GNU Linux-libre 5.10.153-gnu1
[releases.git] / fs / ext4 / mballoc.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
4  * Written by Alex Tomas <alex@clusterfs.com>
5  */
6
7
8 /*
9  * mballoc.c contains the multiblocks allocation routines
10  */
11
12 #include "ext4_jbd2.h"
13 #include "mballoc.h"
14 #include <linux/log2.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/nospec.h>
18 #include <linux/backing-dev.h>
19 #include <trace/events/ext4.h>
20
21 /*
22  * MUSTDO:
23  *   - test ext4_ext_search_left() and ext4_ext_search_right()
24  *   - search for metadata in few groups
25  *
26  * TODO v4:
27  *   - normalization should take into account whether file is still open
28  *   - discard preallocations if no free space left (policy?)
29  *   - don't normalize tails
30  *   - quota
31  *   - reservation for superuser
32  *
33  * TODO v3:
34  *   - bitmap read-ahead (proposed by Oleg Drokin aka green)
35  *   - track min/max extents in each group for better group selection
36  *   - mb_mark_used() may allocate chunk right after splitting buddy
37  *   - tree of groups sorted by number of free blocks
38  *   - error handling
39  */
40
41 /*
42  * The allocation request involve request for multiple number of blocks
43  * near to the goal(block) value specified.
44  *
45  * During initialization phase of the allocator we decide to use the
46  * group preallocation or inode preallocation depending on the size of
47  * the file. The size of the file could be the resulting file size we
48  * would have after allocation, or the current file size, which ever
49  * is larger. If the size is less than sbi->s_mb_stream_request we
50  * select to use the group preallocation. The default value of
51  * s_mb_stream_request is 16 blocks. This can also be tuned via
52  * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
53  * terms of number of blocks.
54  *
55  * The main motivation for having small file use group preallocation is to
56  * ensure that we have small files closer together on the disk.
57  *
58  * First stage the allocator looks at the inode prealloc list,
59  * ext4_inode_info->i_prealloc_list, which contains list of prealloc
60  * spaces for this particular inode. The inode prealloc space is
61  * represented as:
62  *
63  * pa_lstart -> the logical start block for this prealloc space
64  * pa_pstart -> the physical start block for this prealloc space
65  * pa_len    -> length for this prealloc space (in clusters)
66  * pa_free   ->  free space available in this prealloc space (in clusters)
67  *
68  * The inode preallocation space is used looking at the _logical_ start
69  * block. If only the logical file block falls within the range of prealloc
70  * space we will consume the particular prealloc space. This makes sure that
71  * we have contiguous physical blocks representing the file blocks
72  *
73  * The important thing to be noted in case of inode prealloc space is that
74  * we don't modify the values associated to inode prealloc space except
75  * pa_free.
76  *
77  * If we are not able to find blocks in the inode prealloc space and if we
78  * have the group allocation flag set then we look at the locality group
79  * prealloc space. These are per CPU prealloc list represented as
80  *
81  * ext4_sb_info.s_locality_groups[smp_processor_id()]
82  *
83  * The reason for having a per cpu locality group is to reduce the contention
84  * between CPUs. It is possible to get scheduled at this point.
85  *
86  * The locality group prealloc space is used looking at whether we have
87  * enough free space (pa_free) within the prealloc space.
88  *
89  * If we can't allocate blocks via inode prealloc or/and locality group
90  * prealloc then we look at the buddy cache. The buddy cache is represented
91  * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
92  * mapped to the buddy and bitmap information regarding different
93  * groups. The buddy information is attached to buddy cache inode so that
94  * we can access them through the page cache. The information regarding
95  * each group is loaded via ext4_mb_load_buddy.  The information involve
96  * block bitmap and buddy information. The information are stored in the
97  * inode as:
98  *
99  *  {                        page                        }
100  *  [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
101  *
102  *
103  * one block each for bitmap and buddy information.  So for each group we
104  * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
105  * blocksize) blocks.  So it can have information regarding groups_per_page
106  * which is blocks_per_page/2
107  *
108  * The buddy cache inode is not stored on disk. The inode is thrown
109  * away when the filesystem is unmounted.
110  *
111  * We look for count number of blocks in the buddy cache. If we were able
112  * to locate that many free blocks we return with additional information
113  * regarding rest of the contiguous physical block available
114  *
115  * Before allocating blocks via buddy cache we normalize the request
116  * blocks. This ensure we ask for more blocks that we needed. The extra
117  * blocks that we get after allocation is added to the respective prealloc
118  * list. In case of inode preallocation we follow a list of heuristics
119  * based on file size. This can be found in ext4_mb_normalize_request. If
120  * we are doing a group prealloc we try to normalize the request to
121  * sbi->s_mb_group_prealloc.  The default value of s_mb_group_prealloc is
122  * dependent on the cluster size; for non-bigalloc file systems, it is
123  * 512 blocks. This can be tuned via
124  * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
125  * terms of number of blocks. If we have mounted the file system with -O
126  * stripe=<value> option the group prealloc request is normalized to the
127  * smallest multiple of the stripe value (sbi->s_stripe) which is
128  * greater than the default mb_group_prealloc.
129  *
130  * The regular allocator (using the buddy cache) supports a few tunables.
131  *
132  * /sys/fs/ext4/<partition>/mb_min_to_scan
133  * /sys/fs/ext4/<partition>/mb_max_to_scan
134  * /sys/fs/ext4/<partition>/mb_order2_req
135  *
136  * The regular allocator uses buddy scan only if the request len is power of
137  * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
138  * value of s_mb_order2_reqs can be tuned via
139  * /sys/fs/ext4/<partition>/mb_order2_req.  If the request len is equal to
140  * stripe size (sbi->s_stripe), we try to search for contiguous block in
141  * stripe size. This should result in better allocation on RAID setups. If
142  * not, we search in the specific group using bitmap for best extents. The
143  * tunable min_to_scan and max_to_scan control the behaviour here.
144  * min_to_scan indicate how long the mballoc __must__ look for a best
145  * extent and max_to_scan indicates how long the mballoc __can__ look for a
146  * best extent in the found extents. Searching for the blocks starts with
147  * the group specified as the goal value in allocation context via
148  * ac_g_ex. Each group is first checked based on the criteria whether it
149  * can be used for allocation. ext4_mb_good_group explains how the groups are
150  * checked.
151  *
152  * Both the prealloc space are getting populated as above. So for the first
153  * request we will hit the buddy cache which will result in this prealloc
154  * space getting filled. The prealloc space is then later used for the
155  * subsequent request.
156  */
157
158 /*
159  * mballoc operates on the following data:
160  *  - on-disk bitmap
161  *  - in-core buddy (actually includes buddy and bitmap)
162  *  - preallocation descriptors (PAs)
163  *
164  * there are two types of preallocations:
165  *  - inode
166  *    assiged to specific inode and can be used for this inode only.
167  *    it describes part of inode's space preallocated to specific
168  *    physical blocks. any block from that preallocated can be used
169  *    independent. the descriptor just tracks number of blocks left
170  *    unused. so, before taking some block from descriptor, one must
171  *    make sure corresponded logical block isn't allocated yet. this
172  *    also means that freeing any block within descriptor's range
173  *    must discard all preallocated blocks.
174  *  - locality group
175  *    assigned to specific locality group which does not translate to
176  *    permanent set of inodes: inode can join and leave group. space
177  *    from this type of preallocation can be used for any inode. thus
178  *    it's consumed from the beginning to the end.
179  *
180  * relation between them can be expressed as:
181  *    in-core buddy = on-disk bitmap + preallocation descriptors
182  *
183  * this mean blocks mballoc considers used are:
184  *  - allocated blocks (persistent)
185  *  - preallocated blocks (non-persistent)
186  *
187  * consistency in mballoc world means that at any time a block is either
188  * free or used in ALL structures. notice: "any time" should not be read
189  * literally -- time is discrete and delimited by locks.
190  *
191  *  to keep it simple, we don't use block numbers, instead we count number of
192  *  blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
193  *
194  * all operations can be expressed as:
195  *  - init buddy:                       buddy = on-disk + PAs
196  *  - new PA:                           buddy += N; PA = N
197  *  - use inode PA:                     on-disk += N; PA -= N
198  *  - discard inode PA                  buddy -= on-disk - PA; PA = 0
199  *  - use locality group PA             on-disk += N; PA -= N
200  *  - discard locality group PA         buddy -= PA; PA = 0
201  *  note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
202  *        is used in real operation because we can't know actual used
203  *        bits from PA, only from on-disk bitmap
204  *
205  * if we follow this strict logic, then all operations above should be atomic.
206  * given some of them can block, we'd have to use something like semaphores
207  * killing performance on high-end SMP hardware. let's try to relax it using
208  * the following knowledge:
209  *  1) if buddy is referenced, it's already initialized
210  *  2) while block is used in buddy and the buddy is referenced,
211  *     nobody can re-allocate that block
212  *  3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
213  *     bit set and PA claims same block, it's OK. IOW, one can set bit in
214  *     on-disk bitmap if buddy has same bit set or/and PA covers corresponded
215  *     block
216  *
217  * so, now we're building a concurrency table:
218  *  - init buddy vs.
219  *    - new PA
220  *      blocks for PA are allocated in the buddy, buddy must be referenced
221  *      until PA is linked to allocation group to avoid concurrent buddy init
222  *    - use inode PA
223  *      we need to make sure that either on-disk bitmap or PA has uptodate data
224  *      given (3) we care that PA-=N operation doesn't interfere with init
225  *    - discard inode PA
226  *      the simplest way would be to have buddy initialized by the discard
227  *    - use locality group PA
228  *      again PA-=N must be serialized with init
229  *    - discard locality group PA
230  *      the simplest way would be to have buddy initialized by the discard
231  *  - new PA vs.
232  *    - use inode PA
233  *      i_data_sem serializes them
234  *    - discard inode PA
235  *      discard process must wait until PA isn't used by another process
236  *    - use locality group PA
237  *      some mutex should serialize them
238  *    - discard locality group PA
239  *      discard process must wait until PA isn't used by another process
240  *  - use inode PA
241  *    - use inode PA
242  *      i_data_sem or another mutex should serializes them
243  *    - discard inode PA
244  *      discard process must wait until PA isn't used by another process
245  *    - use locality group PA
246  *      nothing wrong here -- they're different PAs covering different blocks
247  *    - discard locality group PA
248  *      discard process must wait until PA isn't used by another process
249  *
250  * now we're ready to make few consequences:
251  *  - PA is referenced and while it is no discard is possible
252  *  - PA is referenced until block isn't marked in on-disk bitmap
253  *  - PA changes only after on-disk bitmap
254  *  - discard must not compete with init. either init is done before
255  *    any discard or they're serialized somehow
256  *  - buddy init as sum of on-disk bitmap and PAs is done atomically
257  *
258  * a special case when we've used PA to emptiness. no need to modify buddy
259  * in this case, but we should care about concurrent init
260  *
261  */
262
263  /*
264  * Logic in few words:
265  *
266  *  - allocation:
267  *    load group
268  *    find blocks
269  *    mark bits in on-disk bitmap
270  *    release group
271  *
272  *  - use preallocation:
273  *    find proper PA (per-inode or group)
274  *    load group
275  *    mark bits in on-disk bitmap
276  *    release group
277  *    release PA
278  *
279  *  - free:
280  *    load group
281  *    mark bits in on-disk bitmap
282  *    release group
283  *
284  *  - discard preallocations in group:
285  *    mark PAs deleted
286  *    move them onto local list
287  *    load on-disk bitmap
288  *    load group
289  *    remove PA from object (inode or locality group)
290  *    mark free blocks in-core
291  *
292  *  - discard inode's preallocations:
293  */
294
295 /*
296  * Locking rules
297  *
298  * Locks:
299  *  - bitlock on a group        (group)
300  *  - object (inode/locality)   (object)
301  *  - per-pa lock               (pa)
302  *
303  * Paths:
304  *  - new pa
305  *    object
306  *    group
307  *
308  *  - find and use pa:
309  *    pa
310  *
311  *  - release consumed pa:
312  *    pa
313  *    group
314  *    object
315  *
316  *  - generate in-core bitmap:
317  *    group
318  *        pa
319  *
320  *  - discard all for given object (inode, locality group):
321  *    object
322  *        pa
323  *    group
324  *
325  *  - discard all for given group:
326  *    group
327  *        pa
328  *    group
329  *        object
330  *
331  */
332 static struct kmem_cache *ext4_pspace_cachep;
333 static struct kmem_cache *ext4_ac_cachep;
334 static struct kmem_cache *ext4_free_data_cachep;
335
336 /* We create slab caches for groupinfo data structures based on the
337  * superblock block size.  There will be one per mounted filesystem for
338  * each unique s_blocksize_bits */
339 #define NR_GRPINFO_CACHES 8
340 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
341
342 static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
343         "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
344         "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
345         "ext4_groupinfo_64k", "ext4_groupinfo_128k"
346 };
347
348 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
349                                         ext4_group_t group);
350 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
351                                                 ext4_group_t group);
352 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac);
353
354 /*
355  * The algorithm using this percpu seq counter goes below:
356  * 1. We sample the percpu discard_pa_seq counter before trying for block
357  *    allocation in ext4_mb_new_blocks().
358  * 2. We increment this percpu discard_pa_seq counter when we either allocate
359  *    or free these blocks i.e. while marking those blocks as used/free in
360  *    mb_mark_used()/mb_free_blocks().
361  * 3. We also increment this percpu seq counter when we successfully identify
362  *    that the bb_prealloc_list is not empty and hence proceed for discarding
363  *    of those PAs inside ext4_mb_discard_group_preallocations().
364  *
365  * Now to make sure that the regular fast path of block allocation is not
366  * affected, as a small optimization we only sample the percpu seq counter
367  * on that cpu. Only when the block allocation fails and when freed blocks
368  * found were 0, that is when we sample percpu seq counter for all cpus using
369  * below function ext4_get_discard_pa_seq_sum(). This happens after making
370  * sure that all the PAs on grp->bb_prealloc_list got freed or if it's empty.
371  */
372 static DEFINE_PER_CPU(u64, discard_pa_seq);
373 static inline u64 ext4_get_discard_pa_seq_sum(void)
374 {
375         int __cpu;
376         u64 __seq = 0;
377
378         for_each_possible_cpu(__cpu)
379                 __seq += per_cpu(discard_pa_seq, __cpu);
380         return __seq;
381 }
382
383 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
384 {
385 #if BITS_PER_LONG == 64
386         *bit += ((unsigned long) addr & 7UL) << 3;
387         addr = (void *) ((unsigned long) addr & ~7UL);
388 #elif BITS_PER_LONG == 32
389         *bit += ((unsigned long) addr & 3UL) << 3;
390         addr = (void *) ((unsigned long) addr & ~3UL);
391 #else
392 #error "how many bits you are?!"
393 #endif
394         return addr;
395 }
396
397 static inline int mb_test_bit(int bit, void *addr)
398 {
399         /*
400          * ext4_test_bit on architecture like powerpc
401          * needs unsigned long aligned address
402          */
403         addr = mb_correct_addr_and_bit(&bit, addr);
404         return ext4_test_bit(bit, addr);
405 }
406
407 static inline void mb_set_bit(int bit, void *addr)
408 {
409         addr = mb_correct_addr_and_bit(&bit, addr);
410         ext4_set_bit(bit, addr);
411 }
412
413 static inline void mb_clear_bit(int bit, void *addr)
414 {
415         addr = mb_correct_addr_and_bit(&bit, addr);
416         ext4_clear_bit(bit, addr);
417 }
418
419 static inline int mb_test_and_clear_bit(int bit, void *addr)
420 {
421         addr = mb_correct_addr_and_bit(&bit, addr);
422         return ext4_test_and_clear_bit(bit, addr);
423 }
424
425 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
426 {
427         int fix = 0, ret, tmpmax;
428         addr = mb_correct_addr_and_bit(&fix, addr);
429         tmpmax = max + fix;
430         start += fix;
431
432         ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
433         if (ret > max)
434                 return max;
435         return ret;
436 }
437
438 static inline int mb_find_next_bit(void *addr, int max, int start)
439 {
440         int fix = 0, ret, tmpmax;
441         addr = mb_correct_addr_and_bit(&fix, addr);
442         tmpmax = max + fix;
443         start += fix;
444
445         ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
446         if (ret > max)
447                 return max;
448         return ret;
449 }
450
451 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
452 {
453         char *bb;
454
455         BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
456         BUG_ON(max == NULL);
457
458         if (order > e4b->bd_blkbits + 1) {
459                 *max = 0;
460                 return NULL;
461         }
462
463         /* at order 0 we see each particular block */
464         if (order == 0) {
465                 *max = 1 << (e4b->bd_blkbits + 3);
466                 return e4b->bd_bitmap;
467         }
468
469         bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
470         *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
471
472         return bb;
473 }
474
475 #ifdef DOUBLE_CHECK
476 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
477                            int first, int count)
478 {
479         int i;
480         struct super_block *sb = e4b->bd_sb;
481
482         if (unlikely(e4b->bd_info->bb_bitmap == NULL))
483                 return;
484         assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
485         for (i = 0; i < count; i++) {
486                 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
487                         ext4_fsblk_t blocknr;
488
489                         blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
490                         blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
491                         ext4_grp_locked_error(sb, e4b->bd_group,
492                                               inode ? inode->i_ino : 0,
493                                               blocknr,
494                                               "freeing block already freed "
495                                               "(bit %u)",
496                                               first + i);
497                         ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
498                                         EXT4_GROUP_INFO_BBITMAP_CORRUPT);
499                 }
500                 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
501         }
502 }
503
504 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
505 {
506         int i;
507
508         if (unlikely(e4b->bd_info->bb_bitmap == NULL))
509                 return;
510         assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
511         for (i = 0; i < count; i++) {
512                 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
513                 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
514         }
515 }
516
517 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
518 {
519         if (unlikely(e4b->bd_info->bb_bitmap == NULL))
520                 return;
521         if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
522                 unsigned char *b1, *b2;
523                 int i;
524                 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
525                 b2 = (unsigned char *) bitmap;
526                 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
527                         if (b1[i] != b2[i]) {
528                                 ext4_msg(e4b->bd_sb, KERN_ERR,
529                                          "corruption in group %u "
530                                          "at byte %u(%u): %x in copy != %x "
531                                          "on disk/prealloc",
532                                          e4b->bd_group, i, i * 8, b1[i], b2[i]);
533                                 BUG();
534                         }
535                 }
536         }
537 }
538
539 static void mb_group_bb_bitmap_alloc(struct super_block *sb,
540                         struct ext4_group_info *grp, ext4_group_t group)
541 {
542         struct buffer_head *bh;
543
544         grp->bb_bitmap = kmalloc(sb->s_blocksize, GFP_NOFS);
545         if (!grp->bb_bitmap)
546                 return;
547
548         bh = ext4_read_block_bitmap(sb, group);
549         if (IS_ERR_OR_NULL(bh)) {
550                 kfree(grp->bb_bitmap);
551                 grp->bb_bitmap = NULL;
552                 return;
553         }
554
555         memcpy(grp->bb_bitmap, bh->b_data, sb->s_blocksize);
556         put_bh(bh);
557 }
558
559 static void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
560 {
561         kfree(grp->bb_bitmap);
562 }
563
564 #else
565 static inline void mb_free_blocks_double(struct inode *inode,
566                                 struct ext4_buddy *e4b, int first, int count)
567 {
568         return;
569 }
570 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
571                                                 int first, int count)
572 {
573         return;
574 }
575 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
576 {
577         return;
578 }
579
580 static inline void mb_group_bb_bitmap_alloc(struct super_block *sb,
581                         struct ext4_group_info *grp, ext4_group_t group)
582 {
583         return;
584 }
585
586 static inline void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
587 {
588         return;
589 }
590 #endif
591
592 #ifdef AGGRESSIVE_CHECK
593
594 #define MB_CHECK_ASSERT(assert)                                         \
595 do {                                                                    \
596         if (!(assert)) {                                                \
597                 printk(KERN_EMERG                                       \
598                         "Assertion failure in %s() at %s:%d: \"%s\"\n", \
599                         function, file, line, # assert);                \
600                 BUG();                                                  \
601         }                                                               \
602 } while (0)
603
604 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
605                                 const char *function, int line)
606 {
607         struct super_block *sb = e4b->bd_sb;
608         int order = e4b->bd_blkbits + 1;
609         int max;
610         int max2;
611         int i;
612         int j;
613         int k;
614         int count;
615         struct ext4_group_info *grp;
616         int fragments = 0;
617         int fstart;
618         struct list_head *cur;
619         void *buddy;
620         void *buddy2;
621
622         if (e4b->bd_info->bb_check_counter++ % 10)
623                 return 0;
624
625         while (order > 1) {
626                 buddy = mb_find_buddy(e4b, order, &max);
627                 MB_CHECK_ASSERT(buddy);
628                 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
629                 MB_CHECK_ASSERT(buddy2);
630                 MB_CHECK_ASSERT(buddy != buddy2);
631                 MB_CHECK_ASSERT(max * 2 == max2);
632
633                 count = 0;
634                 for (i = 0; i < max; i++) {
635
636                         if (mb_test_bit(i, buddy)) {
637                                 /* only single bit in buddy2 may be 1 */
638                                 if (!mb_test_bit(i << 1, buddy2)) {
639                                         MB_CHECK_ASSERT(
640                                                 mb_test_bit((i<<1)+1, buddy2));
641                                 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
642                                         MB_CHECK_ASSERT(
643                                                 mb_test_bit(i << 1, buddy2));
644                                 }
645                                 continue;
646                         }
647
648                         /* both bits in buddy2 must be 1 */
649                         MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
650                         MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
651
652                         for (j = 0; j < (1 << order); j++) {
653                                 k = (i * (1 << order)) + j;
654                                 MB_CHECK_ASSERT(
655                                         !mb_test_bit(k, e4b->bd_bitmap));
656                         }
657                         count++;
658                 }
659                 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
660                 order--;
661         }
662
663         fstart = -1;
664         buddy = mb_find_buddy(e4b, 0, &max);
665         for (i = 0; i < max; i++) {
666                 if (!mb_test_bit(i, buddy)) {
667                         MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
668                         if (fstart == -1) {
669                                 fragments++;
670                                 fstart = i;
671                         }
672                         continue;
673                 }
674                 fstart = -1;
675                 /* check used bits only */
676                 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
677                         buddy2 = mb_find_buddy(e4b, j, &max2);
678                         k = i >> j;
679                         MB_CHECK_ASSERT(k < max2);
680                         MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
681                 }
682         }
683         MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
684         MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
685
686         grp = ext4_get_group_info(sb, e4b->bd_group);
687         list_for_each(cur, &grp->bb_prealloc_list) {
688                 ext4_group_t groupnr;
689                 struct ext4_prealloc_space *pa;
690                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
691                 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
692                 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
693                 for (i = 0; i < pa->pa_len; i++)
694                         MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
695         }
696         return 0;
697 }
698 #undef MB_CHECK_ASSERT
699 #define mb_check_buddy(e4b) __mb_check_buddy(e4b,       \
700                                         __FILE__, __func__, __LINE__)
701 #else
702 #define mb_check_buddy(e4b)
703 #endif
704
705 /*
706  * Divide blocks started from @first with length @len into
707  * smaller chunks with power of 2 blocks.
708  * Clear the bits in bitmap which the blocks of the chunk(s) covered,
709  * then increase bb_counters[] for corresponded chunk size.
710  */
711 static void ext4_mb_mark_free_simple(struct super_block *sb,
712                                 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
713                                         struct ext4_group_info *grp)
714 {
715         struct ext4_sb_info *sbi = EXT4_SB(sb);
716         ext4_grpblk_t min;
717         ext4_grpblk_t max;
718         ext4_grpblk_t chunk;
719         unsigned int border;
720
721         BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
722
723         border = 2 << sb->s_blocksize_bits;
724
725         while (len > 0) {
726                 /* find how many blocks can be covered since this position */
727                 max = ffs(first | border) - 1;
728
729                 /* find how many blocks of power 2 we need to mark */
730                 min = fls(len) - 1;
731
732                 if (max < min)
733                         min = max;
734                 chunk = 1 << min;
735
736                 /* mark multiblock chunks only */
737                 grp->bb_counters[min]++;
738                 if (min > 0)
739                         mb_clear_bit(first >> min,
740                                      buddy + sbi->s_mb_offsets[min]);
741
742                 len -= chunk;
743                 first += chunk;
744         }
745 }
746
747 /*
748  * Cache the order of the largest free extent we have available in this block
749  * group.
750  */
751 static void
752 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
753 {
754         int i;
755         int bits;
756
757         grp->bb_largest_free_order = -1; /* uninit */
758
759         bits = sb->s_blocksize_bits + 1;
760         for (i = bits; i >= 0; i--) {
761                 if (grp->bb_counters[i] > 0) {
762                         grp->bb_largest_free_order = i;
763                         break;
764                 }
765         }
766 }
767
768 static noinline_for_stack
769 void ext4_mb_generate_buddy(struct super_block *sb,
770                                 void *buddy, void *bitmap, ext4_group_t group)
771 {
772         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
773         struct ext4_sb_info *sbi = EXT4_SB(sb);
774         ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
775         ext4_grpblk_t i = 0;
776         ext4_grpblk_t first;
777         ext4_grpblk_t len;
778         unsigned free = 0;
779         unsigned fragments = 0;
780         unsigned long long period = get_cycles();
781
782         /* initialize buddy from bitmap which is aggregation
783          * of on-disk bitmap and preallocations */
784         i = mb_find_next_zero_bit(bitmap, max, 0);
785         grp->bb_first_free = i;
786         while (i < max) {
787                 fragments++;
788                 first = i;
789                 i = mb_find_next_bit(bitmap, max, i);
790                 len = i - first;
791                 free += len;
792                 if (len > 1)
793                         ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
794                 else
795                         grp->bb_counters[0]++;
796                 if (i < max)
797                         i = mb_find_next_zero_bit(bitmap, max, i);
798         }
799         grp->bb_fragments = fragments;
800
801         if (free != grp->bb_free) {
802                 ext4_grp_locked_error(sb, group, 0, 0,
803                                       "block bitmap and bg descriptor "
804                                       "inconsistent: %u vs %u free clusters",
805                                       free, grp->bb_free);
806                 /*
807                  * If we intend to continue, we consider group descriptor
808                  * corrupt and update bb_free using bitmap value
809                  */
810                 grp->bb_free = free;
811                 ext4_mark_group_bitmap_corrupted(sb, group,
812                                         EXT4_GROUP_INFO_BBITMAP_CORRUPT);
813         }
814         mb_set_largest_free_order(sb, grp);
815
816         clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
817
818         period = get_cycles() - period;
819         spin_lock(&sbi->s_bal_lock);
820         sbi->s_mb_buddies_generated++;
821         sbi->s_mb_generation_time += period;
822         spin_unlock(&sbi->s_bal_lock);
823 }
824
825 static void mb_regenerate_buddy(struct ext4_buddy *e4b)
826 {
827         int count;
828         int order = 1;
829         void *buddy;
830
831         while ((buddy = mb_find_buddy(e4b, order++, &count))) {
832                 ext4_set_bits(buddy, 0, count);
833         }
834         e4b->bd_info->bb_fragments = 0;
835         memset(e4b->bd_info->bb_counters, 0,
836                 sizeof(*e4b->bd_info->bb_counters) *
837                 (e4b->bd_sb->s_blocksize_bits + 2));
838
839         ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
840                 e4b->bd_bitmap, e4b->bd_group);
841 }
842
843 /* The buddy information is attached the buddy cache inode
844  * for convenience. The information regarding each group
845  * is loaded via ext4_mb_load_buddy. The information involve
846  * block bitmap and buddy information. The information are
847  * stored in the inode as
848  *
849  * {                        page                        }
850  * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
851  *
852  *
853  * one block each for bitmap and buddy information.
854  * So for each group we take up 2 blocks. A page can
855  * contain blocks_per_page (PAGE_SIZE / blocksize)  blocks.
856  * So it can have information regarding groups_per_page which
857  * is blocks_per_page/2
858  *
859  * Locking note:  This routine takes the block group lock of all groups
860  * for this page; do not hold this lock when calling this routine!
861  */
862
863 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
864 {
865         ext4_group_t ngroups;
866         int blocksize;
867         int blocks_per_page;
868         int groups_per_page;
869         int err = 0;
870         int i;
871         ext4_group_t first_group, group;
872         int first_block;
873         struct super_block *sb;
874         struct buffer_head *bhs;
875         struct buffer_head **bh = NULL;
876         struct inode *inode;
877         char *data;
878         char *bitmap;
879         struct ext4_group_info *grinfo;
880
881         inode = page->mapping->host;
882         sb = inode->i_sb;
883         ngroups = ext4_get_groups_count(sb);
884         blocksize = i_blocksize(inode);
885         blocks_per_page = PAGE_SIZE / blocksize;
886
887         mb_debug(sb, "init page %lu\n", page->index);
888
889         groups_per_page = blocks_per_page >> 1;
890         if (groups_per_page == 0)
891                 groups_per_page = 1;
892
893         /* allocate buffer_heads to read bitmaps */
894         if (groups_per_page > 1) {
895                 i = sizeof(struct buffer_head *) * groups_per_page;
896                 bh = kzalloc(i, gfp);
897                 if (bh == NULL) {
898                         err = -ENOMEM;
899                         goto out;
900                 }
901         } else
902                 bh = &bhs;
903
904         first_group = page->index * blocks_per_page / 2;
905
906         /* read all groups the page covers into the cache */
907         for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
908                 if (group >= ngroups)
909                         break;
910
911                 grinfo = ext4_get_group_info(sb, group);
912                 /*
913                  * If page is uptodate then we came here after online resize
914                  * which added some new uninitialized group info structs, so
915                  * we must skip all initialized uptodate buddies on the page,
916                  * which may be currently in use by an allocating task.
917                  */
918                 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
919                         bh[i] = NULL;
920                         continue;
921                 }
922                 bh[i] = ext4_read_block_bitmap_nowait(sb, group, false);
923                 if (IS_ERR(bh[i])) {
924                         err = PTR_ERR(bh[i]);
925                         bh[i] = NULL;
926                         goto out;
927                 }
928                 mb_debug(sb, "read bitmap for group %u\n", group);
929         }
930
931         /* wait for I/O completion */
932         for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
933                 int err2;
934
935                 if (!bh[i])
936                         continue;
937                 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
938                 if (!err)
939                         err = err2;
940         }
941
942         first_block = page->index * blocks_per_page;
943         for (i = 0; i < blocks_per_page; i++) {
944                 group = (first_block + i) >> 1;
945                 if (group >= ngroups)
946                         break;
947
948                 if (!bh[group - first_group])
949                         /* skip initialized uptodate buddy */
950                         continue;
951
952                 if (!buffer_verified(bh[group - first_group]))
953                         /* Skip faulty bitmaps */
954                         continue;
955                 err = 0;
956
957                 /*
958                  * data carry information regarding this
959                  * particular group in the format specified
960                  * above
961                  *
962                  */
963                 data = page_address(page) + (i * blocksize);
964                 bitmap = bh[group - first_group]->b_data;
965
966                 /*
967                  * We place the buddy block and bitmap block
968                  * close together
969                  */
970                 if ((first_block + i) & 1) {
971                         /* this is block of buddy */
972                         BUG_ON(incore == NULL);
973                         mb_debug(sb, "put buddy for group %u in page %lu/%x\n",
974                                 group, page->index, i * blocksize);
975                         trace_ext4_mb_buddy_bitmap_load(sb, group);
976                         grinfo = ext4_get_group_info(sb, group);
977                         grinfo->bb_fragments = 0;
978                         memset(grinfo->bb_counters, 0,
979                                sizeof(*grinfo->bb_counters) *
980                                 (sb->s_blocksize_bits+2));
981                         /*
982                          * incore got set to the group block bitmap below
983                          */
984                         ext4_lock_group(sb, group);
985                         /* init the buddy */
986                         memset(data, 0xff, blocksize);
987                         ext4_mb_generate_buddy(sb, data, incore, group);
988                         ext4_unlock_group(sb, group);
989                         incore = NULL;
990                 } else {
991                         /* this is block of bitmap */
992                         BUG_ON(incore != NULL);
993                         mb_debug(sb, "put bitmap for group %u in page %lu/%x\n",
994                                 group, page->index, i * blocksize);
995                         trace_ext4_mb_bitmap_load(sb, group);
996
997                         /* see comments in ext4_mb_put_pa() */
998                         ext4_lock_group(sb, group);
999                         memcpy(data, bitmap, blocksize);
1000
1001                         /* mark all preallocated blks used in in-core bitmap */
1002                         ext4_mb_generate_from_pa(sb, data, group);
1003                         ext4_mb_generate_from_freelist(sb, data, group);
1004                         ext4_unlock_group(sb, group);
1005
1006                         /* set incore so that the buddy information can be
1007                          * generated using this
1008                          */
1009                         incore = data;
1010                 }
1011         }
1012         SetPageUptodate(page);
1013
1014 out:
1015         if (bh) {
1016                 for (i = 0; i < groups_per_page; i++)
1017                         brelse(bh[i]);
1018                 if (bh != &bhs)
1019                         kfree(bh);
1020         }
1021         return err;
1022 }
1023
1024 /*
1025  * Lock the buddy and bitmap pages. This make sure other parallel init_group
1026  * on the same buddy page doesn't happen whild holding the buddy page lock.
1027  * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
1028  * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
1029  */
1030 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
1031                 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
1032 {
1033         struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
1034         int block, pnum, poff;
1035         int blocks_per_page;
1036         struct page *page;
1037
1038         e4b->bd_buddy_page = NULL;
1039         e4b->bd_bitmap_page = NULL;
1040
1041         blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1042         /*
1043          * the buddy cache inode stores the block bitmap
1044          * and buddy information in consecutive blocks.
1045          * So for each group we need two blocks.
1046          */
1047         block = group * 2;
1048         pnum = block / blocks_per_page;
1049         poff = block % blocks_per_page;
1050         page = find_or_create_page(inode->i_mapping, pnum, gfp);
1051         if (!page)
1052                 return -ENOMEM;
1053         BUG_ON(page->mapping != inode->i_mapping);
1054         e4b->bd_bitmap_page = page;
1055         e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1056
1057         if (blocks_per_page >= 2) {
1058                 /* buddy and bitmap are on the same page */
1059                 return 0;
1060         }
1061
1062         block++;
1063         pnum = block / blocks_per_page;
1064         page = find_or_create_page(inode->i_mapping, pnum, gfp);
1065         if (!page)
1066                 return -ENOMEM;
1067         BUG_ON(page->mapping != inode->i_mapping);
1068         e4b->bd_buddy_page = page;
1069         return 0;
1070 }
1071
1072 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1073 {
1074         if (e4b->bd_bitmap_page) {
1075                 unlock_page(e4b->bd_bitmap_page);
1076                 put_page(e4b->bd_bitmap_page);
1077         }
1078         if (e4b->bd_buddy_page) {
1079                 unlock_page(e4b->bd_buddy_page);
1080                 put_page(e4b->bd_buddy_page);
1081         }
1082 }
1083
1084 /*
1085  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
1086  * block group lock of all groups for this page; do not hold the BG lock when
1087  * calling this routine!
1088  */
1089 static noinline_for_stack
1090 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1091 {
1092
1093         struct ext4_group_info *this_grp;
1094         struct ext4_buddy e4b;
1095         struct page *page;
1096         int ret = 0;
1097
1098         might_sleep();
1099         mb_debug(sb, "init group %u\n", group);
1100         this_grp = ext4_get_group_info(sb, group);
1101         /*
1102          * This ensures that we don't reinit the buddy cache
1103          * page which map to the group from which we are already
1104          * allocating. If we are looking at the buddy cache we would
1105          * have taken a reference using ext4_mb_load_buddy and that
1106          * would have pinned buddy page to page cache.
1107          * The call to ext4_mb_get_buddy_page_lock will mark the
1108          * page accessed.
1109          */
1110         ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1111         if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1112                 /*
1113                  * somebody initialized the group
1114                  * return without doing anything
1115                  */
1116                 goto err;
1117         }
1118
1119         page = e4b.bd_bitmap_page;
1120         ret = ext4_mb_init_cache(page, NULL, gfp);
1121         if (ret)
1122                 goto err;
1123         if (!PageUptodate(page)) {
1124                 ret = -EIO;
1125                 goto err;
1126         }
1127
1128         if (e4b.bd_buddy_page == NULL) {
1129                 /*
1130                  * If both the bitmap and buddy are in
1131                  * the same page we don't need to force
1132                  * init the buddy
1133                  */
1134                 ret = 0;
1135                 goto err;
1136         }
1137         /* init buddy cache */
1138         page = e4b.bd_buddy_page;
1139         ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1140         if (ret)
1141                 goto err;
1142         if (!PageUptodate(page)) {
1143                 ret = -EIO;
1144                 goto err;
1145         }
1146 err:
1147         ext4_mb_put_buddy_page_lock(&e4b);
1148         return ret;
1149 }
1150
1151 /*
1152  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
1153  * block group lock of all groups for this page; do not hold the BG lock when
1154  * calling this routine!
1155  */
1156 static noinline_for_stack int
1157 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1158                        struct ext4_buddy *e4b, gfp_t gfp)
1159 {
1160         int blocks_per_page;
1161         int block;
1162         int pnum;
1163         int poff;
1164         struct page *page;
1165         int ret;
1166         struct ext4_group_info *grp;
1167         struct ext4_sb_info *sbi = EXT4_SB(sb);
1168         struct inode *inode = sbi->s_buddy_cache;
1169
1170         might_sleep();
1171         mb_debug(sb, "load group %u\n", group);
1172
1173         blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1174         grp = ext4_get_group_info(sb, group);
1175
1176         e4b->bd_blkbits = sb->s_blocksize_bits;
1177         e4b->bd_info = grp;
1178         e4b->bd_sb = sb;
1179         e4b->bd_group = group;
1180         e4b->bd_buddy_page = NULL;
1181         e4b->bd_bitmap_page = NULL;
1182
1183         if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1184                 /*
1185                  * we need full data about the group
1186                  * to make a good selection
1187                  */
1188                 ret = ext4_mb_init_group(sb, group, gfp);
1189                 if (ret)
1190                         return ret;
1191         }
1192
1193         /*
1194          * the buddy cache inode stores the block bitmap
1195          * and buddy information in consecutive blocks.
1196          * So for each group we need two blocks.
1197          */
1198         block = group * 2;
1199         pnum = block / blocks_per_page;
1200         poff = block % blocks_per_page;
1201
1202         /* we could use find_or_create_page(), but it locks page
1203          * what we'd like to avoid in fast path ... */
1204         page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1205         if (page == NULL || !PageUptodate(page)) {
1206                 if (page)
1207                         /*
1208                          * drop the page reference and try
1209                          * to get the page with lock. If we
1210                          * are not uptodate that implies
1211                          * somebody just created the page but
1212                          * is yet to initialize the same. So
1213                          * wait for it to initialize.
1214                          */
1215                         put_page(page);
1216                 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1217                 if (page) {
1218                         BUG_ON(page->mapping != inode->i_mapping);
1219                         if (!PageUptodate(page)) {
1220                                 ret = ext4_mb_init_cache(page, NULL, gfp);
1221                                 if (ret) {
1222                                         unlock_page(page);
1223                                         goto err;
1224                                 }
1225                                 mb_cmp_bitmaps(e4b, page_address(page) +
1226                                                (poff * sb->s_blocksize));
1227                         }
1228                         unlock_page(page);
1229                 }
1230         }
1231         if (page == NULL) {
1232                 ret = -ENOMEM;
1233                 goto err;
1234         }
1235         if (!PageUptodate(page)) {
1236                 ret = -EIO;
1237                 goto err;
1238         }
1239
1240         /* Pages marked accessed already */
1241         e4b->bd_bitmap_page = page;
1242         e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1243
1244         block++;
1245         pnum = block / blocks_per_page;
1246         poff = block % blocks_per_page;
1247
1248         page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1249         if (page == NULL || !PageUptodate(page)) {
1250                 if (page)
1251                         put_page(page);
1252                 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1253                 if (page) {
1254                         BUG_ON(page->mapping != inode->i_mapping);
1255                         if (!PageUptodate(page)) {
1256                                 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1257                                                          gfp);
1258                                 if (ret) {
1259                                         unlock_page(page);
1260                                         goto err;
1261                                 }
1262                         }
1263                         unlock_page(page);
1264                 }
1265         }
1266         if (page == NULL) {
1267                 ret = -ENOMEM;
1268                 goto err;
1269         }
1270         if (!PageUptodate(page)) {
1271                 ret = -EIO;
1272                 goto err;
1273         }
1274
1275         /* Pages marked accessed already */
1276         e4b->bd_buddy_page = page;
1277         e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1278
1279         return 0;
1280
1281 err:
1282         if (page)
1283                 put_page(page);
1284         if (e4b->bd_bitmap_page)
1285                 put_page(e4b->bd_bitmap_page);
1286         if (e4b->bd_buddy_page)
1287                 put_page(e4b->bd_buddy_page);
1288         e4b->bd_buddy = NULL;
1289         e4b->bd_bitmap = NULL;
1290         return ret;
1291 }
1292
1293 static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1294                               struct ext4_buddy *e4b)
1295 {
1296         return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1297 }
1298
1299 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1300 {
1301         if (e4b->bd_bitmap_page)
1302                 put_page(e4b->bd_bitmap_page);
1303         if (e4b->bd_buddy_page)
1304                 put_page(e4b->bd_buddy_page);
1305 }
1306
1307
1308 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1309 {
1310         int order = 1;
1311         int bb_incr = 1 << (e4b->bd_blkbits - 1);
1312         void *bb;
1313
1314         BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1315         BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1316
1317         bb = e4b->bd_buddy;
1318         while (order <= e4b->bd_blkbits + 1) {
1319                 block = block >> 1;
1320                 if (!mb_test_bit(block, bb)) {
1321                         /* this block is part of buddy of order 'order' */
1322                         return order;
1323                 }
1324                 bb += bb_incr;
1325                 bb_incr >>= 1;
1326                 order++;
1327         }
1328         return 0;
1329 }
1330
1331 static void mb_clear_bits(void *bm, int cur, int len)
1332 {
1333         __u32 *addr;
1334
1335         len = cur + len;
1336         while (cur < len) {
1337                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1338                         /* fast path: clear whole word at once */
1339                         addr = bm + (cur >> 3);
1340                         *addr = 0;
1341                         cur += 32;
1342                         continue;
1343                 }
1344                 mb_clear_bit(cur, bm);
1345                 cur++;
1346         }
1347 }
1348
1349 /* clear bits in given range
1350  * will return first found zero bit if any, -1 otherwise
1351  */
1352 static int mb_test_and_clear_bits(void *bm, int cur, int len)
1353 {
1354         __u32 *addr;
1355         int zero_bit = -1;
1356
1357         len = cur + len;
1358         while (cur < len) {
1359                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1360                         /* fast path: clear whole word at once */
1361                         addr = bm + (cur >> 3);
1362                         if (*addr != (__u32)(-1) && zero_bit == -1)
1363                                 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1364                         *addr = 0;
1365                         cur += 32;
1366                         continue;
1367                 }
1368                 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1369                         zero_bit = cur;
1370                 cur++;
1371         }
1372
1373         return zero_bit;
1374 }
1375
1376 void ext4_set_bits(void *bm, int cur, int len)
1377 {
1378         __u32 *addr;
1379
1380         len = cur + len;
1381         while (cur < len) {
1382                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1383                         /* fast path: set whole word at once */
1384                         addr = bm + (cur >> 3);
1385                         *addr = 0xffffffff;
1386                         cur += 32;
1387                         continue;
1388                 }
1389                 mb_set_bit(cur, bm);
1390                 cur++;
1391         }
1392 }
1393
1394 static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1395 {
1396         if (mb_test_bit(*bit + side, bitmap)) {
1397                 mb_clear_bit(*bit, bitmap);
1398                 (*bit) -= side;
1399                 return 1;
1400         }
1401         else {
1402                 (*bit) += side;
1403                 mb_set_bit(*bit, bitmap);
1404                 return -1;
1405         }
1406 }
1407
1408 static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1409 {
1410         int max;
1411         int order = 1;
1412         void *buddy = mb_find_buddy(e4b, order, &max);
1413
1414         while (buddy) {
1415                 void *buddy2;
1416
1417                 /* Bits in range [first; last] are known to be set since
1418                  * corresponding blocks were allocated. Bits in range
1419                  * (first; last) will stay set because they form buddies on
1420                  * upper layer. We just deal with borders if they don't
1421                  * align with upper layer and then go up.
1422                  * Releasing entire group is all about clearing
1423                  * single bit of highest order buddy.
1424                  */
1425
1426                 /* Example:
1427                  * ---------------------------------
1428                  * |   1   |   1   |   1   |   1   |
1429                  * ---------------------------------
1430                  * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1431                  * ---------------------------------
1432                  *   0   1   2   3   4   5   6   7
1433                  *      \_____________________/
1434                  *
1435                  * Neither [1] nor [6] is aligned to above layer.
1436                  * Left neighbour [0] is free, so mark it busy,
1437                  * decrease bb_counters and extend range to
1438                  * [0; 6]
1439                  * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1440                  * mark [6] free, increase bb_counters and shrink range to
1441                  * [0; 5].
1442                  * Then shift range to [0; 2], go up and do the same.
1443                  */
1444
1445
1446                 if (first & 1)
1447                         e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1448                 if (!(last & 1))
1449                         e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1450                 if (first > last)
1451                         break;
1452                 order++;
1453
1454                 if (first == last || !(buddy2 = mb_find_buddy(e4b, order, &max))) {
1455                         mb_clear_bits(buddy, first, last - first + 1);
1456                         e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1457                         break;
1458                 }
1459                 first >>= 1;
1460                 last >>= 1;
1461                 buddy = buddy2;
1462         }
1463 }
1464
1465 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1466                            int first, int count)
1467 {
1468         int left_is_free = 0;
1469         int right_is_free = 0;
1470         int block;
1471         int last = first + count - 1;
1472         struct super_block *sb = e4b->bd_sb;
1473
1474         if (WARN_ON(count == 0))
1475                 return;
1476         BUG_ON(last >= (sb->s_blocksize << 3));
1477         assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1478         /* Don't bother if the block group is corrupt. */
1479         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1480                 return;
1481
1482         mb_check_buddy(e4b);
1483         mb_free_blocks_double(inode, e4b, first, count);
1484
1485         this_cpu_inc(discard_pa_seq);
1486         e4b->bd_info->bb_free += count;
1487         if (first < e4b->bd_info->bb_first_free)
1488                 e4b->bd_info->bb_first_free = first;
1489
1490         /* access memory sequentially: check left neighbour,
1491          * clear range and then check right neighbour
1492          */
1493         if (first != 0)
1494                 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1495         block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1496         if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1497                 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1498
1499         if (unlikely(block != -1)) {
1500                 struct ext4_sb_info *sbi = EXT4_SB(sb);
1501                 ext4_fsblk_t blocknr;
1502
1503                 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1504                 blocknr += EXT4_C2B(sbi, block);
1505                 if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
1506                         ext4_grp_locked_error(sb, e4b->bd_group,
1507                                               inode ? inode->i_ino : 0,
1508                                               blocknr,
1509                                               "freeing already freed block (bit %u); block bitmap corrupt.",
1510                                               block);
1511                         ext4_mark_group_bitmap_corrupted(
1512                                 sb, e4b->bd_group,
1513                                 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1514                 }
1515                 mb_regenerate_buddy(e4b);
1516                 goto done;
1517         }
1518
1519         /* let's maintain fragments counter */
1520         if (left_is_free && right_is_free)
1521                 e4b->bd_info->bb_fragments--;
1522         else if (!left_is_free && !right_is_free)
1523                 e4b->bd_info->bb_fragments++;
1524
1525         /* buddy[0] == bd_bitmap is a special case, so handle
1526          * it right away and let mb_buddy_mark_free stay free of
1527          * zero order checks.
1528          * Check if neighbours are to be coaleasced,
1529          * adjust bitmap bb_counters and borders appropriately.
1530          */
1531         if (first & 1) {
1532                 first += !left_is_free;
1533                 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1534         }
1535         if (!(last & 1)) {
1536                 last -= !right_is_free;
1537                 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1538         }
1539
1540         if (first <= last)
1541                 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1542
1543 done:
1544         mb_set_largest_free_order(sb, e4b->bd_info);
1545         mb_check_buddy(e4b);
1546 }
1547
1548 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1549                                 int needed, struct ext4_free_extent *ex)
1550 {
1551         int next = block;
1552         int max, order;
1553         void *buddy;
1554
1555         assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1556         BUG_ON(ex == NULL);
1557
1558         buddy = mb_find_buddy(e4b, 0, &max);
1559         BUG_ON(buddy == NULL);
1560         BUG_ON(block >= max);
1561         if (mb_test_bit(block, buddy)) {
1562                 ex->fe_len = 0;
1563                 ex->fe_start = 0;
1564                 ex->fe_group = 0;
1565                 return 0;
1566         }
1567
1568         /* find actual order */
1569         order = mb_find_order_for_block(e4b, block);
1570         block = block >> order;
1571
1572         ex->fe_len = 1 << order;
1573         ex->fe_start = block << order;
1574         ex->fe_group = e4b->bd_group;
1575
1576         /* calc difference from given start */
1577         next = next - ex->fe_start;
1578         ex->fe_len -= next;
1579         ex->fe_start += next;
1580
1581         while (needed > ex->fe_len &&
1582                mb_find_buddy(e4b, order, &max)) {
1583
1584                 if (block + 1 >= max)
1585                         break;
1586
1587                 next = (block + 1) * (1 << order);
1588                 if (mb_test_bit(next, e4b->bd_bitmap))
1589                         break;
1590
1591                 order = mb_find_order_for_block(e4b, next);
1592
1593                 block = next >> order;
1594                 ex->fe_len += 1 << order;
1595         }
1596
1597         if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
1598                 /* Should never happen! (but apparently sometimes does?!?) */
1599                 WARN_ON(1);
1600                 ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
1601                         "corruption or bug in mb_find_extent "
1602                         "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
1603                         block, order, needed, ex->fe_group, ex->fe_start,
1604                         ex->fe_len, ex->fe_logical);
1605                 ex->fe_len = 0;
1606                 ex->fe_start = 0;
1607                 ex->fe_group = 0;
1608         }
1609         return ex->fe_len;
1610 }
1611
1612 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1613 {
1614         int ord;
1615         int mlen = 0;
1616         int max = 0;
1617         int cur;
1618         int start = ex->fe_start;
1619         int len = ex->fe_len;
1620         unsigned ret = 0;
1621         int len0 = len;
1622         void *buddy;
1623
1624         BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1625         BUG_ON(e4b->bd_group != ex->fe_group);
1626         assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1627         mb_check_buddy(e4b);
1628         mb_mark_used_double(e4b, start, len);
1629
1630         this_cpu_inc(discard_pa_seq);
1631         e4b->bd_info->bb_free -= len;
1632         if (e4b->bd_info->bb_first_free == start)
1633                 e4b->bd_info->bb_first_free += len;
1634
1635         /* let's maintain fragments counter */
1636         if (start != 0)
1637                 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1638         if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1639                 max = !mb_test_bit(start + len, e4b->bd_bitmap);
1640         if (mlen && max)
1641                 e4b->bd_info->bb_fragments++;
1642         else if (!mlen && !max)
1643                 e4b->bd_info->bb_fragments--;
1644
1645         /* let's maintain buddy itself */
1646         while (len) {
1647                 ord = mb_find_order_for_block(e4b, start);
1648
1649                 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1650                         /* the whole chunk may be allocated at once! */
1651                         mlen = 1 << ord;
1652                         buddy = mb_find_buddy(e4b, ord, &max);
1653                         BUG_ON((start >> ord) >= max);
1654                         mb_set_bit(start >> ord, buddy);
1655                         e4b->bd_info->bb_counters[ord]--;
1656                         start += mlen;
1657                         len -= mlen;
1658                         BUG_ON(len < 0);
1659                         continue;
1660                 }
1661
1662                 /* store for history */
1663                 if (ret == 0)
1664                         ret = len | (ord << 16);
1665
1666                 /* we have to split large buddy */
1667                 BUG_ON(ord <= 0);
1668                 buddy = mb_find_buddy(e4b, ord, &max);
1669                 mb_set_bit(start >> ord, buddy);
1670                 e4b->bd_info->bb_counters[ord]--;
1671
1672                 ord--;
1673                 cur = (start >> ord) & ~1U;
1674                 buddy = mb_find_buddy(e4b, ord, &max);
1675                 mb_clear_bit(cur, buddy);
1676                 mb_clear_bit(cur + 1, buddy);
1677                 e4b->bd_info->bb_counters[ord]++;
1678                 e4b->bd_info->bb_counters[ord]++;
1679         }
1680         mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1681
1682         ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1683         mb_check_buddy(e4b);
1684
1685         return ret;
1686 }
1687
1688 /*
1689  * Must be called under group lock!
1690  */
1691 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1692                                         struct ext4_buddy *e4b)
1693 {
1694         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1695         int ret;
1696
1697         BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1698         BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1699
1700         ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1701         ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1702         ret = mb_mark_used(e4b, &ac->ac_b_ex);
1703
1704         /* preallocation can change ac_b_ex, thus we store actually
1705          * allocated blocks for history */
1706         ac->ac_f_ex = ac->ac_b_ex;
1707
1708         ac->ac_status = AC_STATUS_FOUND;
1709         ac->ac_tail = ret & 0xffff;
1710         ac->ac_buddy = ret >> 16;
1711
1712         /*
1713          * take the page reference. We want the page to be pinned
1714          * so that we don't get a ext4_mb_init_cache_call for this
1715          * group until we update the bitmap. That would mean we
1716          * double allocate blocks. The reference is dropped
1717          * in ext4_mb_release_context
1718          */
1719         ac->ac_bitmap_page = e4b->bd_bitmap_page;
1720         get_page(ac->ac_bitmap_page);
1721         ac->ac_buddy_page = e4b->bd_buddy_page;
1722         get_page(ac->ac_buddy_page);
1723         /* store last allocated for subsequent stream allocation */
1724         if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1725                 spin_lock(&sbi->s_md_lock);
1726                 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1727                 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1728                 spin_unlock(&sbi->s_md_lock);
1729         }
1730         /*
1731          * As we've just preallocated more space than
1732          * user requested originally, we store allocated
1733          * space in a special descriptor.
1734          */
1735         if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
1736                 ext4_mb_new_preallocation(ac);
1737
1738 }
1739
1740 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1741                                         struct ext4_buddy *e4b,
1742                                         int finish_group)
1743 {
1744         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1745         struct ext4_free_extent *bex = &ac->ac_b_ex;
1746         struct ext4_free_extent *gex = &ac->ac_g_ex;
1747         struct ext4_free_extent ex;
1748         int max;
1749
1750         if (ac->ac_status == AC_STATUS_FOUND)
1751                 return;
1752         /*
1753          * We don't want to scan for a whole year
1754          */
1755         if (ac->ac_found > sbi->s_mb_max_to_scan &&
1756                         !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1757                 ac->ac_status = AC_STATUS_BREAK;
1758                 return;
1759         }
1760
1761         /*
1762          * Haven't found good chunk so far, let's continue
1763          */
1764         if (bex->fe_len < gex->fe_len)
1765                 return;
1766
1767         if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1768                         && bex->fe_group == e4b->bd_group) {
1769                 /* recheck chunk's availability - we don't know
1770                  * when it was found (within this lock-unlock
1771                  * period or not) */
1772                 max = mb_find_extent(e4b, bex->fe_start, gex->fe_len, &ex);
1773                 if (max >= gex->fe_len) {
1774                         ext4_mb_use_best_found(ac, e4b);
1775                         return;
1776                 }
1777         }
1778 }
1779
1780 /*
1781  * The routine checks whether found extent is good enough. If it is,
1782  * then the extent gets marked used and flag is set to the context
1783  * to stop scanning. Otherwise, the extent is compared with the
1784  * previous found extent and if new one is better, then it's stored
1785  * in the context. Later, the best found extent will be used, if
1786  * mballoc can't find good enough extent.
1787  *
1788  * FIXME: real allocation policy is to be designed yet!
1789  */
1790 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1791                                         struct ext4_free_extent *ex,
1792                                         struct ext4_buddy *e4b)
1793 {
1794         struct ext4_free_extent *bex = &ac->ac_b_ex;
1795         struct ext4_free_extent *gex = &ac->ac_g_ex;
1796
1797         BUG_ON(ex->fe_len <= 0);
1798         BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1799         BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1800         BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1801
1802         ac->ac_found++;
1803
1804         /*
1805          * The special case - take what you catch first
1806          */
1807         if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1808                 *bex = *ex;
1809                 ext4_mb_use_best_found(ac, e4b);
1810                 return;
1811         }
1812
1813         /*
1814          * Let's check whether the chuck is good enough
1815          */
1816         if (ex->fe_len == gex->fe_len) {
1817                 *bex = *ex;
1818                 ext4_mb_use_best_found(ac, e4b);
1819                 return;
1820         }
1821
1822         /*
1823          * If this is first found extent, just store it in the context
1824          */
1825         if (bex->fe_len == 0) {
1826                 *bex = *ex;
1827                 return;
1828         }
1829
1830         /*
1831          * If new found extent is better, store it in the context
1832          */
1833         if (bex->fe_len < gex->fe_len) {
1834                 /* if the request isn't satisfied, any found extent
1835                  * larger than previous best one is better */
1836                 if (ex->fe_len > bex->fe_len)
1837                         *bex = *ex;
1838         } else if (ex->fe_len > gex->fe_len) {
1839                 /* if the request is satisfied, then we try to find
1840                  * an extent that still satisfy the request, but is
1841                  * smaller than previous one */
1842                 if (ex->fe_len < bex->fe_len)
1843                         *bex = *ex;
1844         }
1845
1846         ext4_mb_check_limits(ac, e4b, 0);
1847 }
1848
1849 static noinline_for_stack
1850 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1851                                         struct ext4_buddy *e4b)
1852 {
1853         struct ext4_free_extent ex = ac->ac_b_ex;
1854         ext4_group_t group = ex.fe_group;
1855         int max;
1856         int err;
1857
1858         BUG_ON(ex.fe_len <= 0);
1859         err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1860         if (err)
1861                 return err;
1862
1863         ext4_lock_group(ac->ac_sb, group);
1864         max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
1865
1866         if (max > 0) {
1867                 ac->ac_b_ex = ex;
1868                 ext4_mb_use_best_found(ac, e4b);
1869         }
1870
1871         ext4_unlock_group(ac->ac_sb, group);
1872         ext4_mb_unload_buddy(e4b);
1873
1874         return 0;
1875 }
1876
1877 static noinline_for_stack
1878 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1879                                 struct ext4_buddy *e4b)
1880 {
1881         ext4_group_t group = ac->ac_g_ex.fe_group;
1882         int max;
1883         int err;
1884         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1885         struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1886         struct ext4_free_extent ex;
1887
1888         if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1889                 return 0;
1890         if (grp->bb_free == 0)
1891                 return 0;
1892
1893         err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1894         if (err)
1895                 return err;
1896
1897         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
1898                 ext4_mb_unload_buddy(e4b);
1899                 return 0;
1900         }
1901
1902         ext4_lock_group(ac->ac_sb, group);
1903         max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
1904                              ac->ac_g_ex.fe_len, &ex);
1905         ex.fe_logical = 0xDEADFA11; /* debug value */
1906
1907         if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1908                 ext4_fsblk_t start;
1909
1910                 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
1911                         ex.fe_start;
1912                 /* use do_div to get remainder (would be 64-bit modulo) */
1913                 if (do_div(start, sbi->s_stripe) == 0) {
1914                         ac->ac_found++;
1915                         ac->ac_b_ex = ex;
1916                         ext4_mb_use_best_found(ac, e4b);
1917                 }
1918         } else if (max >= ac->ac_g_ex.fe_len) {
1919                 BUG_ON(ex.fe_len <= 0);
1920                 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1921                 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1922                 ac->ac_found++;
1923                 ac->ac_b_ex = ex;
1924                 ext4_mb_use_best_found(ac, e4b);
1925         } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1926                 /* Sometimes, caller may want to merge even small
1927                  * number of blocks to an existing extent */
1928                 BUG_ON(ex.fe_len <= 0);
1929                 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1930                 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1931                 ac->ac_found++;
1932                 ac->ac_b_ex = ex;
1933                 ext4_mb_use_best_found(ac, e4b);
1934         }
1935         ext4_unlock_group(ac->ac_sb, group);
1936         ext4_mb_unload_buddy(e4b);
1937
1938         return 0;
1939 }
1940
1941 /*
1942  * The routine scans buddy structures (not bitmap!) from given order
1943  * to max order and tries to find big enough chunk to satisfy the req
1944  */
1945 static noinline_for_stack
1946 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1947                                         struct ext4_buddy *e4b)
1948 {
1949         struct super_block *sb = ac->ac_sb;
1950         struct ext4_group_info *grp = e4b->bd_info;
1951         void *buddy;
1952         int i;
1953         int k;
1954         int max;
1955
1956         BUG_ON(ac->ac_2order <= 0);
1957         for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1958                 if (grp->bb_counters[i] == 0)
1959                         continue;
1960
1961                 buddy = mb_find_buddy(e4b, i, &max);
1962                 BUG_ON(buddy == NULL);
1963
1964                 k = mb_find_next_zero_bit(buddy, max, 0);
1965                 if (k >= max) {
1966                         ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
1967                                 "%d free clusters of order %d. But found 0",
1968                                 grp->bb_counters[i], i);
1969                         ext4_mark_group_bitmap_corrupted(ac->ac_sb,
1970                                          e4b->bd_group,
1971                                         EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1972                         break;
1973                 }
1974                 ac->ac_found++;
1975
1976                 ac->ac_b_ex.fe_len = 1 << i;
1977                 ac->ac_b_ex.fe_start = k << i;
1978                 ac->ac_b_ex.fe_group = e4b->bd_group;
1979
1980                 ext4_mb_use_best_found(ac, e4b);
1981
1982                 BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
1983
1984                 if (EXT4_SB(sb)->s_mb_stats)
1985                         atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1986
1987                 break;
1988         }
1989 }
1990
1991 /*
1992  * The routine scans the group and measures all found extents.
1993  * In order to optimize scanning, caller must pass number of
1994  * free blocks in the group, so the routine can know upper limit.
1995  */
1996 static noinline_for_stack
1997 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1998                                         struct ext4_buddy *e4b)
1999 {
2000         struct super_block *sb = ac->ac_sb;
2001         void *bitmap = e4b->bd_bitmap;
2002         struct ext4_free_extent ex;
2003         int i;
2004         int free;
2005
2006         free = e4b->bd_info->bb_free;
2007         if (WARN_ON(free <= 0))
2008                 return;
2009
2010         i = e4b->bd_info->bb_first_free;
2011
2012         while (free && ac->ac_status == AC_STATUS_CONTINUE) {
2013                 i = mb_find_next_zero_bit(bitmap,
2014                                                 EXT4_CLUSTERS_PER_GROUP(sb), i);
2015                 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
2016                         /*
2017                          * IF we have corrupt bitmap, we won't find any
2018                          * free blocks even though group info says we
2019                          * have free blocks
2020                          */
2021                         ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2022                                         "%d free clusters as per "
2023                                         "group info. But bitmap says 0",
2024                                         free);
2025                         ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2026                                         EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2027                         break;
2028                 }
2029
2030                 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
2031                 if (WARN_ON(ex.fe_len <= 0))
2032                         break;
2033                 if (free < ex.fe_len) {
2034                         ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2035                                         "%d free clusters as per "
2036                                         "group info. But got %d blocks",
2037                                         free, ex.fe_len);
2038                         ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2039                                         EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2040                         /*
2041                          * The number of free blocks differs. This mostly
2042                          * indicate that the bitmap is corrupt. So exit
2043                          * without claiming the space.
2044                          */
2045                         break;
2046                 }
2047                 ex.fe_logical = 0xDEADC0DE; /* debug value */
2048                 ext4_mb_measure_extent(ac, &ex, e4b);
2049
2050                 i += ex.fe_len;
2051                 free -= ex.fe_len;
2052         }
2053
2054         ext4_mb_check_limits(ac, e4b, 1);
2055 }
2056
2057 /*
2058  * This is a special case for storages like raid5
2059  * we try to find stripe-aligned chunks for stripe-size-multiple requests
2060  */
2061 static noinline_for_stack
2062 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2063                                  struct ext4_buddy *e4b)
2064 {
2065         struct super_block *sb = ac->ac_sb;
2066         struct ext4_sb_info *sbi = EXT4_SB(sb);
2067         void *bitmap = e4b->bd_bitmap;
2068         struct ext4_free_extent ex;
2069         ext4_fsblk_t first_group_block;
2070         ext4_fsblk_t a;
2071         ext4_grpblk_t i;
2072         int max;
2073
2074         BUG_ON(sbi->s_stripe == 0);
2075
2076         /* find first stripe-aligned block in group */
2077         first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2078
2079         a = first_group_block + sbi->s_stripe - 1;
2080         do_div(a, sbi->s_stripe);
2081         i = (a * sbi->s_stripe) - first_group_block;
2082
2083         while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2084                 if (!mb_test_bit(i, bitmap)) {
2085                         max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
2086                         if (max >= sbi->s_stripe) {
2087                                 ac->ac_found++;
2088                                 ex.fe_logical = 0xDEADF00D; /* debug value */
2089                                 ac->ac_b_ex = ex;
2090                                 ext4_mb_use_best_found(ac, e4b);
2091                                 break;
2092                         }
2093                 }
2094                 i += sbi->s_stripe;
2095         }
2096 }
2097
2098 /*
2099  * This is also called BEFORE we load the buddy bitmap.
2100  * Returns either 1 or 0 indicating that the group is either suitable
2101  * for the allocation or not.
2102  */
2103 static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
2104                                 ext4_group_t group, int cr)
2105 {
2106         ext4_grpblk_t free, fragments;
2107         int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2108         struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2109
2110         BUG_ON(cr < 0 || cr >= 4);
2111
2112         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2113                 return false;
2114
2115         free = grp->bb_free;
2116         if (free == 0)
2117                 return false;
2118
2119         fragments = grp->bb_fragments;
2120         if (fragments == 0)
2121                 return false;
2122
2123         switch (cr) {
2124         case 0:
2125                 BUG_ON(ac->ac_2order == 0);
2126
2127                 /* Avoid using the first bg of a flexgroup for data files */
2128                 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2129                     (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2130                     ((group % flex_size) == 0))
2131                         return false;
2132
2133                 if (free < ac->ac_g_ex.fe_len)
2134                         return false;
2135
2136                 if (ac->ac_2order > ac->ac_sb->s_blocksize_bits+1)
2137                         return true;
2138
2139                 if (grp->bb_largest_free_order < ac->ac_2order)
2140                         return false;
2141
2142                 return true;
2143         case 1:
2144                 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2145                         return true;
2146                 break;
2147         case 2:
2148                 if (free >= ac->ac_g_ex.fe_len)
2149                         return true;
2150                 break;
2151         case 3:
2152                 return true;
2153         default:
2154                 BUG();
2155         }
2156
2157         return false;
2158 }
2159
2160 /*
2161  * This could return negative error code if something goes wrong
2162  * during ext4_mb_init_group(). This should not be called with
2163  * ext4_lock_group() held.
2164  */
2165 static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
2166                                      ext4_group_t group, int cr)
2167 {
2168         struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2169         struct super_block *sb = ac->ac_sb;
2170         struct ext4_sb_info *sbi = EXT4_SB(sb);
2171         bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
2172         ext4_grpblk_t free;
2173         int ret = 0;
2174
2175         if (should_lock)
2176                 ext4_lock_group(sb, group);
2177         free = grp->bb_free;
2178         if (free == 0)
2179                 goto out;
2180         if (cr <= 2 && free < ac->ac_g_ex.fe_len)
2181                 goto out;
2182         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2183                 goto out;
2184         if (should_lock)
2185                 ext4_unlock_group(sb, group);
2186
2187         /* We only do this if the grp has never been initialized */
2188         if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2189                 struct ext4_group_desc *gdp =
2190                         ext4_get_group_desc(sb, group, NULL);
2191                 int ret;
2192
2193                 /* cr=0/1 is a very optimistic search to find large
2194                  * good chunks almost for free.  If buddy data is not
2195                  * ready, then this optimization makes no sense.  But
2196                  * we never skip the first block group in a flex_bg,
2197                  * since this gets used for metadata block allocation,
2198                  * and we want to make sure we locate metadata blocks
2199                  * in the first block group in the flex_bg if possible.
2200                  */
2201                 if (cr < 2 &&
2202                     (!sbi->s_log_groups_per_flex ||
2203                      ((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
2204                     !(ext4_has_group_desc_csum(sb) &&
2205                       (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
2206                         return 0;
2207                 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
2208                 if (ret)
2209                         return ret;
2210         }
2211
2212         if (should_lock)
2213                 ext4_lock_group(sb, group);
2214         ret = ext4_mb_good_group(ac, group, cr);
2215 out:
2216         if (should_lock)
2217                 ext4_unlock_group(sb, group);
2218         return ret;
2219 }
2220
2221 /*
2222  * Start prefetching @nr block bitmaps starting at @group.
2223  * Return the next group which needs to be prefetched.
2224  */
2225 ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
2226                               unsigned int nr, int *cnt)
2227 {
2228         ext4_group_t ngroups = ext4_get_groups_count(sb);
2229         struct buffer_head *bh;
2230         struct blk_plug plug;
2231
2232         blk_start_plug(&plug);
2233         while (nr-- > 0) {
2234                 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2235                                                                   NULL);
2236                 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2237
2238                 /*
2239                  * Prefetch block groups with free blocks; but don't
2240                  * bother if it is marked uninitialized on disk, since
2241                  * it won't require I/O to read.  Also only try to
2242                  * prefetch once, so we avoid getblk() call, which can
2243                  * be expensive.
2244                  */
2245                 if (!EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
2246                     EXT4_MB_GRP_NEED_INIT(grp) &&
2247                     ext4_free_group_clusters(sb, gdp) > 0 &&
2248                     !(ext4_has_group_desc_csum(sb) &&
2249                       (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)))) {
2250                         bh = ext4_read_block_bitmap_nowait(sb, group, true);
2251                         if (bh && !IS_ERR(bh)) {
2252                                 if (!buffer_uptodate(bh) && cnt)
2253                                         (*cnt)++;
2254                                 brelse(bh);
2255                         }
2256                 }
2257                 if (++group >= ngroups)
2258                         group = 0;
2259         }
2260         blk_finish_plug(&plug);
2261         return group;
2262 }
2263
2264 /*
2265  * Prefetching reads the block bitmap into the buffer cache; but we
2266  * need to make sure that the buddy bitmap in the page cache has been
2267  * initialized.  Note that ext4_mb_init_group() will block if the I/O
2268  * is not yet completed, or indeed if it was not initiated by
2269  * ext4_mb_prefetch did not start the I/O.
2270  *
2271  * TODO: We should actually kick off the buddy bitmap setup in a work
2272  * queue when the buffer I/O is completed, so that we don't block
2273  * waiting for the block allocation bitmap read to finish when
2274  * ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
2275  */
2276 void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
2277                            unsigned int nr)
2278 {
2279         while (nr-- > 0) {
2280                 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2281                                                                   NULL);
2282                 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2283
2284                 if (!group)
2285                         group = ext4_get_groups_count(sb);
2286                 group--;
2287                 grp = ext4_get_group_info(sb, group);
2288
2289                 if (EXT4_MB_GRP_NEED_INIT(grp) &&
2290                     ext4_free_group_clusters(sb, gdp) > 0 &&
2291                     !(ext4_has_group_desc_csum(sb) &&
2292                       (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)))) {
2293                         if (ext4_mb_init_group(sb, group, GFP_NOFS))
2294                                 break;
2295                 }
2296         }
2297 }
2298
2299 static noinline_for_stack int
2300 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2301 {
2302         ext4_group_t prefetch_grp = 0, ngroups, group, i;
2303         int cr = -1;
2304         int err = 0, first_err = 0;
2305         unsigned int nr = 0, prefetch_ios = 0;
2306         struct ext4_sb_info *sbi;
2307         struct super_block *sb;
2308         struct ext4_buddy e4b;
2309         int lost;
2310
2311         sb = ac->ac_sb;
2312         sbi = EXT4_SB(sb);
2313         ngroups = ext4_get_groups_count(sb);
2314         /* non-extent files are limited to low blocks/groups */
2315         if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2316                 ngroups = sbi->s_blockfile_groups;
2317
2318         BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2319
2320         /* first, try the goal */
2321         err = ext4_mb_find_by_goal(ac, &e4b);
2322         if (err || ac->ac_status == AC_STATUS_FOUND)
2323                 goto out;
2324
2325         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2326                 goto out;
2327
2328         /*
2329          * ac->ac_2order is set only if the fe_len is a power of 2
2330          * if ac->ac_2order is set we also set criteria to 0 so that we
2331          * try exact allocation using buddy.
2332          */
2333         i = fls(ac->ac_g_ex.fe_len);
2334         ac->ac_2order = 0;
2335         /*
2336          * We search using buddy data only if the order of the request
2337          * is greater than equal to the sbi_s_mb_order2_reqs
2338          * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2339          * We also support searching for power-of-two requests only for
2340          * requests upto maximum buddy size we have constructed.
2341          */
2342         if (i >= sbi->s_mb_order2_reqs && i <= sb->s_blocksize_bits + 2) {
2343                 /*
2344                  * This should tell if fe_len is exactly power of 2
2345                  */
2346                 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2347                         ac->ac_2order = array_index_nospec(i - 1,
2348                                                            sb->s_blocksize_bits + 2);
2349         }
2350
2351         /* if stream allocation is enabled, use global goal */
2352         if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2353                 /* TBD: may be hot point */
2354                 spin_lock(&sbi->s_md_lock);
2355                 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2356                 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2357                 spin_unlock(&sbi->s_md_lock);
2358         }
2359
2360         /* Let's just scan groups to find more-less suitable blocks */
2361         cr = ac->ac_2order ? 0 : 1;
2362         /*
2363          * cr == 0 try to get exact allocation,
2364          * cr == 3  try to get anything
2365          */
2366 repeat:
2367         for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2368                 ac->ac_criteria = cr;
2369                 /*
2370                  * searching for the right group start
2371                  * from the goal value specified
2372                  */
2373                 group = ac->ac_g_ex.fe_group;
2374                 prefetch_grp = group;
2375
2376                 for (i = 0; i < ngroups; group++, i++) {
2377                         int ret = 0;
2378                         cond_resched();
2379                         /*
2380                          * Artificially restricted ngroups for non-extent
2381                          * files makes group > ngroups possible on first loop.
2382                          */
2383                         if (group >= ngroups)
2384                                 group = 0;
2385
2386                         /*
2387                          * Batch reads of the block allocation bitmaps
2388                          * to get multiple READs in flight; limit
2389                          * prefetching at cr=0/1, otherwise mballoc can
2390                          * spend a lot of time loading imperfect groups
2391                          */
2392                         if ((prefetch_grp == group) &&
2393                             (cr > 1 ||
2394                              prefetch_ios < sbi->s_mb_prefetch_limit)) {
2395                                 unsigned int curr_ios = prefetch_ios;
2396
2397                                 nr = sbi->s_mb_prefetch;
2398                                 if (ext4_has_feature_flex_bg(sb)) {
2399                                         nr = 1 << sbi->s_log_groups_per_flex;
2400                                         nr -= group & (nr - 1);
2401                                         nr = min(nr, sbi->s_mb_prefetch);
2402                                 }
2403                                 prefetch_grp = ext4_mb_prefetch(sb, group,
2404                                                         nr, &prefetch_ios);
2405                                 if (prefetch_ios == curr_ios)
2406                                         nr = 0;
2407                         }
2408
2409                         /* This now checks without needing the buddy page */
2410                         ret = ext4_mb_good_group_nolock(ac, group, cr);
2411                         if (ret <= 0) {
2412                                 if (!first_err)
2413                                         first_err = ret;
2414                                 continue;
2415                         }
2416
2417                         err = ext4_mb_load_buddy(sb, group, &e4b);
2418                         if (err)
2419                                 goto out;
2420
2421                         ext4_lock_group(sb, group);
2422
2423                         /*
2424                          * We need to check again after locking the
2425                          * block group
2426                          */
2427                         ret = ext4_mb_good_group(ac, group, cr);
2428                         if (ret == 0) {
2429                                 ext4_unlock_group(sb, group);
2430                                 ext4_mb_unload_buddy(&e4b);
2431                                 continue;
2432                         }
2433
2434                         ac->ac_groups_scanned++;
2435                         if (cr == 0)
2436                                 ext4_mb_simple_scan_group(ac, &e4b);
2437                         else if (cr == 1 && sbi->s_stripe &&
2438                                         !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2439                                 ext4_mb_scan_aligned(ac, &e4b);
2440                         else
2441                                 ext4_mb_complex_scan_group(ac, &e4b);
2442
2443                         ext4_unlock_group(sb, group);
2444                         ext4_mb_unload_buddy(&e4b);
2445
2446                         if (ac->ac_status != AC_STATUS_CONTINUE)
2447                                 break;
2448                 }
2449         }
2450
2451         if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2452             !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2453                 /*
2454                  * We've been searching too long. Let's try to allocate
2455                  * the best chunk we've found so far
2456                  */
2457                 ext4_mb_try_best_found(ac, &e4b);
2458                 if (ac->ac_status != AC_STATUS_FOUND) {
2459                         /*
2460                          * Someone more lucky has already allocated it.
2461                          * The only thing we can do is just take first
2462                          * found block(s)
2463                          */
2464                         lost = atomic_inc_return(&sbi->s_mb_lost_chunks);
2465                         mb_debug(sb, "lost chunk, group: %u, start: %d, len: %d, lost: %d\n",
2466                                  ac->ac_b_ex.fe_group, ac->ac_b_ex.fe_start,
2467                                  ac->ac_b_ex.fe_len, lost);
2468
2469                         ac->ac_b_ex.fe_group = 0;
2470                         ac->ac_b_ex.fe_start = 0;
2471                         ac->ac_b_ex.fe_len = 0;
2472                         ac->ac_status = AC_STATUS_CONTINUE;
2473                         ac->ac_flags |= EXT4_MB_HINT_FIRST;
2474                         cr = 3;
2475                         goto repeat;
2476                 }
2477         }
2478 out:
2479         if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2480                 err = first_err;
2481
2482         mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
2483                  ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
2484                  ac->ac_flags, cr, err);
2485
2486         if (nr)
2487                 ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
2488
2489         return err;
2490 }
2491
2492 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2493 {
2494         struct super_block *sb = PDE_DATA(file_inode(seq->file));
2495         ext4_group_t group;
2496
2497         if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2498                 return NULL;
2499         group = *pos + 1;
2500         return (void *) ((unsigned long) group);
2501 }
2502
2503 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2504 {
2505         struct super_block *sb = PDE_DATA(file_inode(seq->file));
2506         ext4_group_t group;
2507
2508         ++*pos;
2509         if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2510                 return NULL;
2511         group = *pos + 1;
2512         return (void *) ((unsigned long) group);
2513 }
2514
2515 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2516 {
2517         struct super_block *sb = PDE_DATA(file_inode(seq->file));
2518         ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2519         int i;
2520         int err, buddy_loaded = 0;
2521         struct ext4_buddy e4b;
2522         struct ext4_group_info *grinfo;
2523         unsigned char blocksize_bits = min_t(unsigned char,
2524                                              sb->s_blocksize_bits,
2525                                              EXT4_MAX_BLOCK_LOG_SIZE);
2526         struct sg {
2527                 struct ext4_group_info info;
2528                 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
2529         } sg;
2530
2531         group--;
2532         if (group == 0)
2533                 seq_puts(seq, "#group: free  frags first ["
2534                               " 2^0   2^1   2^2   2^3   2^4   2^5   2^6  "
2535                               " 2^7   2^8   2^9   2^10  2^11  2^12  2^13  ]\n");
2536
2537         i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2538                 sizeof(struct ext4_group_info);
2539
2540         grinfo = ext4_get_group_info(sb, group);
2541         /* Load the group info in memory only if not already loaded. */
2542         if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
2543                 err = ext4_mb_load_buddy(sb, group, &e4b);
2544                 if (err) {
2545                         seq_printf(seq, "#%-5u: I/O error\n", group);
2546                         return 0;
2547                 }
2548                 buddy_loaded = 1;
2549         }
2550
2551         memcpy(&sg, ext4_get_group_info(sb, group), i);
2552
2553         if (buddy_loaded)
2554                 ext4_mb_unload_buddy(&e4b);
2555
2556         seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2557                         sg.info.bb_fragments, sg.info.bb_first_free);
2558         for (i = 0; i <= 13; i++)
2559                 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
2560                                 sg.info.bb_counters[i] : 0);
2561         seq_puts(seq, " ]\n");
2562
2563         return 0;
2564 }
2565
2566 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2567 {
2568 }
2569
2570 const struct seq_operations ext4_mb_seq_groups_ops = {
2571         .start  = ext4_mb_seq_groups_start,
2572         .next   = ext4_mb_seq_groups_next,
2573         .stop   = ext4_mb_seq_groups_stop,
2574         .show   = ext4_mb_seq_groups_show,
2575 };
2576
2577 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2578 {
2579         int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2580         struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2581
2582         BUG_ON(!cachep);
2583         return cachep;
2584 }
2585
2586 /*
2587  * Allocate the top-level s_group_info array for the specified number
2588  * of groups
2589  */
2590 int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
2591 {
2592         struct ext4_sb_info *sbi = EXT4_SB(sb);
2593         unsigned size;
2594         struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
2595
2596         size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
2597                 EXT4_DESC_PER_BLOCK_BITS(sb);
2598         if (size <= sbi->s_group_info_size)
2599                 return 0;
2600
2601         size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
2602         new_groupinfo = kvzalloc(size, GFP_KERNEL);
2603         if (!new_groupinfo) {
2604                 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
2605                 return -ENOMEM;
2606         }
2607         rcu_read_lock();
2608         old_groupinfo = rcu_dereference(sbi->s_group_info);
2609         if (old_groupinfo)
2610                 memcpy(new_groupinfo, old_groupinfo,
2611                        sbi->s_group_info_size * sizeof(*sbi->s_group_info));
2612         rcu_read_unlock();
2613         rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
2614         sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
2615         if (old_groupinfo)
2616                 ext4_kvfree_array_rcu(old_groupinfo);
2617         ext4_debug("allocated s_groupinfo array for %d meta_bg's\n", 
2618                    sbi->s_group_info_size);
2619         return 0;
2620 }
2621
2622 /* Create and initialize ext4_group_info data for the given group. */
2623 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2624                           struct ext4_group_desc *desc)
2625 {
2626         int i;
2627         int metalen = 0;
2628         int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
2629         struct ext4_sb_info *sbi = EXT4_SB(sb);
2630         struct ext4_group_info **meta_group_info;
2631         struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2632
2633         /*
2634          * First check if this group is the first of a reserved block.
2635          * If it's true, we have to allocate a new table of pointers
2636          * to ext4_group_info structures
2637          */
2638         if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2639                 metalen = sizeof(*meta_group_info) <<
2640                         EXT4_DESC_PER_BLOCK_BITS(sb);
2641                 meta_group_info = kmalloc(metalen, GFP_NOFS);
2642                 if (meta_group_info == NULL) {
2643                         ext4_msg(sb, KERN_ERR, "can't allocate mem "
2644                                  "for a buddy group");
2645                         goto exit_meta_group_info;
2646                 }
2647                 rcu_read_lock();
2648                 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
2649                 rcu_read_unlock();
2650         }
2651
2652         meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
2653         i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2654
2655         meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
2656         if (meta_group_info[i] == NULL) {
2657                 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
2658                 goto exit_group_info;
2659         }
2660         set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2661                 &(meta_group_info[i]->bb_state));
2662
2663         /*
2664          * initialize bb_free to be able to skip
2665          * empty groups without initialization
2666          */
2667         if (ext4_has_group_desc_csum(sb) &&
2668             (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
2669                 meta_group_info[i]->bb_free =
2670                         ext4_free_clusters_after_init(sb, group, desc);
2671         } else {
2672                 meta_group_info[i]->bb_free =
2673                         ext4_free_group_clusters(sb, desc);
2674         }
2675
2676         INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2677         init_rwsem(&meta_group_info[i]->alloc_sem);
2678         meta_group_info[i]->bb_free_root = RB_ROOT;
2679         meta_group_info[i]->bb_largest_free_order = -1;  /* uninit */
2680
2681         mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
2682         return 0;
2683
2684 exit_group_info:
2685         /* If a meta_group_info table has been allocated, release it now */
2686         if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2687                 struct ext4_group_info ***group_info;
2688
2689                 rcu_read_lock();
2690                 group_info = rcu_dereference(sbi->s_group_info);
2691                 kfree(group_info[idx]);
2692                 group_info[idx] = NULL;
2693                 rcu_read_unlock();
2694         }
2695 exit_meta_group_info:
2696         return -ENOMEM;
2697 } /* ext4_mb_add_groupinfo */
2698
2699 static int ext4_mb_init_backend(struct super_block *sb)
2700 {
2701         ext4_group_t ngroups = ext4_get_groups_count(sb);
2702         ext4_group_t i;
2703         struct ext4_sb_info *sbi = EXT4_SB(sb);
2704         int err;
2705         struct ext4_group_desc *desc;
2706         struct ext4_group_info ***group_info;
2707         struct kmem_cache *cachep;
2708
2709         err = ext4_mb_alloc_groupinfo(sb, ngroups);
2710         if (err)
2711                 return err;
2712
2713         sbi->s_buddy_cache = new_inode(sb);
2714         if (sbi->s_buddy_cache == NULL) {
2715                 ext4_msg(sb, KERN_ERR, "can't get new inode");
2716                 goto err_freesgi;
2717         }
2718         /* To avoid potentially colliding with an valid on-disk inode number,
2719          * use EXT4_BAD_INO for the buddy cache inode number.  This inode is
2720          * not in the inode hash, so it should never be found by iget(), but
2721          * this will avoid confusion if it ever shows up during debugging. */
2722         sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
2723         EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2724         for (i = 0; i < ngroups; i++) {
2725                 cond_resched();
2726                 desc = ext4_get_group_desc(sb, i, NULL);
2727                 if (desc == NULL) {
2728                         ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2729                         goto err_freebuddy;
2730                 }
2731                 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2732                         goto err_freebuddy;
2733         }
2734
2735         if (ext4_has_feature_flex_bg(sb)) {
2736                 /* a single flex group is supposed to be read by a single IO.
2737                  * 2 ^ s_log_groups_per_flex != UINT_MAX as s_mb_prefetch is
2738                  * unsigned integer, so the maximum shift is 32.
2739                  */
2740                 if (sbi->s_es->s_log_groups_per_flex >= 32) {
2741                         ext4_msg(sb, KERN_ERR, "too many log groups per flexible block group");
2742                         goto err_freebuddy;
2743                 }
2744                 sbi->s_mb_prefetch = min_t(uint, 1 << sbi->s_es->s_log_groups_per_flex,
2745                         BLK_MAX_SEGMENT_SIZE >> (sb->s_blocksize_bits - 9));
2746                 sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
2747         } else {
2748                 sbi->s_mb_prefetch = 32;
2749         }
2750         if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
2751                 sbi->s_mb_prefetch = ext4_get_groups_count(sb);
2752         /* now many real IOs to prefetch within a single allocation at cr=0
2753          * given cr=0 is an CPU-related optimization we shouldn't try to
2754          * load too many groups, at some point we should start to use what
2755          * we've got in memory.
2756          * with an average random access time 5ms, it'd take a second to get
2757          * 200 groups (* N with flex_bg), so let's make this limit 4
2758          */
2759         sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
2760         if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
2761                 sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
2762
2763         return 0;
2764
2765 err_freebuddy:
2766         cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2767         while (i-- > 0)
2768                 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2769         i = sbi->s_group_info_size;
2770         rcu_read_lock();
2771         group_info = rcu_dereference(sbi->s_group_info);
2772         while (i-- > 0)
2773                 kfree(group_info[i]);
2774         rcu_read_unlock();
2775         iput(sbi->s_buddy_cache);
2776 err_freesgi:
2777         rcu_read_lock();
2778         kvfree(rcu_dereference(sbi->s_group_info));
2779         rcu_read_unlock();
2780         return -ENOMEM;
2781 }
2782
2783 static void ext4_groupinfo_destroy_slabs(void)
2784 {
2785         int i;
2786
2787         for (i = 0; i < NR_GRPINFO_CACHES; i++) {
2788                 kmem_cache_destroy(ext4_groupinfo_caches[i]);
2789                 ext4_groupinfo_caches[i] = NULL;
2790         }
2791 }
2792
2793 static int ext4_groupinfo_create_slab(size_t size)
2794 {
2795         static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
2796         int slab_size;
2797         int blocksize_bits = order_base_2(size);
2798         int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2799         struct kmem_cache *cachep;
2800
2801         if (cache_index >= NR_GRPINFO_CACHES)
2802                 return -EINVAL;
2803
2804         if (unlikely(cache_index < 0))
2805                 cache_index = 0;
2806
2807         mutex_lock(&ext4_grpinfo_slab_create_mutex);
2808         if (ext4_groupinfo_caches[cache_index]) {
2809                 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2810                 return 0;       /* Already created */
2811         }
2812
2813         slab_size = offsetof(struct ext4_group_info,
2814                                 bb_counters[blocksize_bits + 2]);
2815
2816         cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
2817                                         slab_size, 0, SLAB_RECLAIM_ACCOUNT,
2818                                         NULL);
2819
2820         ext4_groupinfo_caches[cache_index] = cachep;
2821
2822         mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2823         if (!cachep) {
2824                 printk(KERN_EMERG
2825                        "EXT4-fs: no memory for groupinfo slab cache\n");
2826                 return -ENOMEM;
2827         }
2828
2829         return 0;
2830 }
2831
2832 int ext4_mb_init(struct super_block *sb)
2833 {
2834         struct ext4_sb_info *sbi = EXT4_SB(sb);
2835         unsigned i, j;
2836         unsigned offset, offset_incr;
2837         unsigned max;
2838         int ret;
2839
2840         i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2841
2842         sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2843         if (sbi->s_mb_offsets == NULL) {
2844                 ret = -ENOMEM;
2845                 goto out;
2846         }
2847
2848         i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2849         sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2850         if (sbi->s_mb_maxs == NULL) {
2851                 ret = -ENOMEM;
2852                 goto out;
2853         }
2854
2855         ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2856         if (ret < 0)
2857                 goto out;
2858
2859         /* order 0 is regular bitmap */
2860         sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2861         sbi->s_mb_offsets[0] = 0;
2862
2863         i = 1;
2864         offset = 0;
2865         offset_incr = 1 << (sb->s_blocksize_bits - 1);
2866         max = sb->s_blocksize << 2;
2867         do {
2868                 sbi->s_mb_offsets[i] = offset;
2869                 sbi->s_mb_maxs[i] = max;
2870                 offset += offset_incr;
2871                 offset_incr = offset_incr >> 1;
2872                 max = max >> 1;
2873                 i++;
2874         } while (i <= sb->s_blocksize_bits + 1);
2875
2876         spin_lock_init(&sbi->s_md_lock);
2877         spin_lock_init(&sbi->s_bal_lock);
2878         sbi->s_mb_free_pending = 0;
2879         INIT_LIST_HEAD(&sbi->s_freed_data_list);
2880
2881         sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2882         sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2883         sbi->s_mb_stats = MB_DEFAULT_STATS;
2884         sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2885         sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2886         sbi->s_mb_max_inode_prealloc = MB_DEFAULT_MAX_INODE_PREALLOC;
2887         /*
2888          * The default group preallocation is 512, which for 4k block
2889          * sizes translates to 2 megabytes.  However for bigalloc file
2890          * systems, this is probably too big (i.e, if the cluster size
2891          * is 1 megabyte, then group preallocation size becomes half a
2892          * gigabyte!).  As a default, we will keep a two megabyte
2893          * group pralloc size for cluster sizes up to 64k, and after
2894          * that, we will force a minimum group preallocation size of
2895          * 32 clusters.  This translates to 8 megs when the cluster
2896          * size is 256k, and 32 megs when the cluster size is 1 meg,
2897          * which seems reasonable as a default.
2898          */
2899         sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
2900                                        sbi->s_cluster_bits, 32);
2901         /*
2902          * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
2903          * to the lowest multiple of s_stripe which is bigger than
2904          * the s_mb_group_prealloc as determined above. We want
2905          * the preallocation size to be an exact multiple of the
2906          * RAID stripe size so that preallocations don't fragment
2907          * the stripes.
2908          */
2909         if (sbi->s_stripe > 1) {
2910                 sbi->s_mb_group_prealloc = roundup(
2911                         sbi->s_mb_group_prealloc, sbi->s_stripe);
2912         }
2913
2914         sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2915         if (sbi->s_locality_groups == NULL) {
2916                 ret = -ENOMEM;
2917                 goto out;
2918         }
2919         for_each_possible_cpu(i) {
2920                 struct ext4_locality_group *lg;
2921                 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2922                 mutex_init(&lg->lg_mutex);
2923                 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2924                         INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2925                 spin_lock_init(&lg->lg_prealloc_lock);
2926         }
2927
2928         /* init file for buddy data */
2929         ret = ext4_mb_init_backend(sb);
2930         if (ret != 0)
2931                 goto out_free_locality_groups;
2932
2933         return 0;
2934
2935 out_free_locality_groups:
2936         free_percpu(sbi->s_locality_groups);
2937         sbi->s_locality_groups = NULL;
2938 out:
2939         kfree(sbi->s_mb_offsets);
2940         sbi->s_mb_offsets = NULL;
2941         kfree(sbi->s_mb_maxs);
2942         sbi->s_mb_maxs = NULL;
2943         return ret;
2944 }
2945
2946 /* need to called with the ext4 group lock held */
2947 static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2948 {
2949         struct ext4_prealloc_space *pa;
2950         struct list_head *cur, *tmp;
2951         int count = 0;
2952
2953         list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2954                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2955                 list_del(&pa->pa_group_list);
2956                 count++;
2957                 kmem_cache_free(ext4_pspace_cachep, pa);
2958         }
2959         return count;
2960 }
2961
2962 int ext4_mb_release(struct super_block *sb)
2963 {
2964         ext4_group_t ngroups = ext4_get_groups_count(sb);
2965         ext4_group_t i;
2966         int num_meta_group_infos;
2967         struct ext4_group_info *grinfo, ***group_info;
2968         struct ext4_sb_info *sbi = EXT4_SB(sb);
2969         struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2970         int count;
2971
2972         if (sbi->s_group_info) {
2973                 for (i = 0; i < ngroups; i++) {
2974                         cond_resched();
2975                         grinfo = ext4_get_group_info(sb, i);
2976                         mb_group_bb_bitmap_free(grinfo);
2977                         ext4_lock_group(sb, i);
2978                         count = ext4_mb_cleanup_pa(grinfo);
2979                         if (count)
2980                                 mb_debug(sb, "mballoc: %d PAs left\n",
2981                                          count);
2982                         ext4_unlock_group(sb, i);
2983                         kmem_cache_free(cachep, grinfo);
2984                 }
2985                 num_meta_group_infos = (ngroups +
2986                                 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2987                         EXT4_DESC_PER_BLOCK_BITS(sb);
2988                 rcu_read_lock();
2989                 group_info = rcu_dereference(sbi->s_group_info);
2990                 for (i = 0; i < num_meta_group_infos; i++)
2991                         kfree(group_info[i]);
2992                 kvfree(group_info);
2993                 rcu_read_unlock();
2994         }
2995         kfree(sbi->s_mb_offsets);
2996         kfree(sbi->s_mb_maxs);
2997         iput(sbi->s_buddy_cache);
2998         if (sbi->s_mb_stats) {
2999                 ext4_msg(sb, KERN_INFO,
3000                        "mballoc: %u blocks %u reqs (%u success)",
3001                                 atomic_read(&sbi->s_bal_allocated),
3002                                 atomic_read(&sbi->s_bal_reqs),
3003                                 atomic_read(&sbi->s_bal_success));
3004                 ext4_msg(sb, KERN_INFO,
3005                       "mballoc: %u extents scanned, %u goal hits, "
3006                                 "%u 2^N hits, %u breaks, %u lost",
3007                                 atomic_read(&sbi->s_bal_ex_scanned),
3008                                 atomic_read(&sbi->s_bal_goals),
3009                                 atomic_read(&sbi->s_bal_2orders),
3010                                 atomic_read(&sbi->s_bal_breaks),
3011                                 atomic_read(&sbi->s_mb_lost_chunks));
3012                 ext4_msg(sb, KERN_INFO,
3013                        "mballoc: %lu generated and it took %Lu",
3014                                 sbi->s_mb_buddies_generated,
3015                                 sbi->s_mb_generation_time);
3016                 ext4_msg(sb, KERN_INFO,
3017                        "mballoc: %u preallocated, %u discarded",
3018                                 atomic_read(&sbi->s_mb_preallocated),
3019                                 atomic_read(&sbi->s_mb_discarded));
3020         }
3021
3022         free_percpu(sbi->s_locality_groups);
3023
3024         return 0;
3025 }
3026
3027 static inline int ext4_issue_discard(struct super_block *sb,
3028                 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
3029                 struct bio **biop)
3030 {
3031         ext4_fsblk_t discard_block;
3032
3033         discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
3034                          ext4_group_first_block_no(sb, block_group));
3035         count = EXT4_C2B(EXT4_SB(sb), count);
3036         trace_ext4_discard_blocks(sb,
3037                         (unsigned long long) discard_block, count);
3038         if (biop) {
3039                 return __blkdev_issue_discard(sb->s_bdev,
3040                         (sector_t)discard_block << (sb->s_blocksize_bits - 9),
3041                         (sector_t)count << (sb->s_blocksize_bits - 9),
3042                         GFP_NOFS, 0, biop);
3043         } else
3044                 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
3045 }
3046
3047 static void ext4_free_data_in_buddy(struct super_block *sb,
3048                                     struct ext4_free_data *entry)
3049 {
3050         struct ext4_buddy e4b;
3051         struct ext4_group_info *db;
3052         int err, count = 0, count2 = 0;
3053
3054         mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
3055                  entry->efd_count, entry->efd_group, entry);
3056
3057         err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
3058         /* we expect to find existing buddy because it's pinned */
3059         BUG_ON(err != 0);
3060
3061         spin_lock(&EXT4_SB(sb)->s_md_lock);
3062         EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
3063         spin_unlock(&EXT4_SB(sb)->s_md_lock);
3064
3065         db = e4b.bd_info;
3066         /* there are blocks to put in buddy to make them really free */
3067         count += entry->efd_count;
3068         count2++;
3069         ext4_lock_group(sb, entry->efd_group);
3070         /* Take it out of per group rb tree */
3071         rb_erase(&entry->efd_node, &(db->bb_free_root));
3072         mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
3073
3074         /*
3075          * Clear the trimmed flag for the group so that the next
3076          * ext4_trim_fs can trim it.
3077          * If the volume is mounted with -o discard, online discard
3078          * is supported and the free blocks will be trimmed online.
3079          */
3080         if (!test_opt(sb, DISCARD))
3081                 EXT4_MB_GRP_CLEAR_TRIMMED(db);
3082
3083         if (!db->bb_free_root.rb_node) {
3084                 /* No more items in the per group rb tree
3085                  * balance refcounts from ext4_mb_free_metadata()
3086                  */
3087                 put_page(e4b.bd_buddy_page);
3088                 put_page(e4b.bd_bitmap_page);
3089         }
3090         ext4_unlock_group(sb, entry->efd_group);
3091         kmem_cache_free(ext4_free_data_cachep, entry);
3092         ext4_mb_unload_buddy(&e4b);
3093
3094         mb_debug(sb, "freed %d blocks in %d structures\n", count,
3095                  count2);
3096 }
3097
3098 /*
3099  * This function is called by the jbd2 layer once the commit has finished,
3100  * so we know we can free the blocks that were released with that commit.
3101  */
3102 void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
3103 {
3104         struct ext4_sb_info *sbi = EXT4_SB(sb);
3105         struct ext4_free_data *entry, *tmp;
3106         struct bio *discard_bio = NULL;
3107         struct list_head freed_data_list;
3108         struct list_head *cut_pos = NULL;
3109         int err;
3110
3111         INIT_LIST_HEAD(&freed_data_list);
3112
3113         spin_lock(&sbi->s_md_lock);
3114         list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
3115                 if (entry->efd_tid != commit_tid)
3116                         break;
3117                 cut_pos = &entry->efd_list;
3118         }
3119         if (cut_pos)
3120                 list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
3121                                   cut_pos);
3122         spin_unlock(&sbi->s_md_lock);
3123
3124         if (test_opt(sb, DISCARD)) {
3125                 list_for_each_entry(entry, &freed_data_list, efd_list) {
3126                         err = ext4_issue_discard(sb, entry->efd_group,
3127                                                  entry->efd_start_cluster,
3128                                                  entry->efd_count,
3129                                                  &discard_bio);
3130                         if (err && err != -EOPNOTSUPP) {
3131                                 ext4_msg(sb, KERN_WARNING, "discard request in"
3132                                          " group:%d block:%d count:%d failed"
3133                                          " with %d", entry->efd_group,
3134                                          entry->efd_start_cluster,
3135                                          entry->efd_count, err);
3136                         } else if (err == -EOPNOTSUPP)
3137                                 break;
3138                 }
3139
3140                 if (discard_bio) {
3141                         submit_bio_wait(discard_bio);
3142                         bio_put(discard_bio);
3143                 }
3144         }
3145
3146         list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
3147                 ext4_free_data_in_buddy(sb, entry);
3148 }
3149
3150 int __init ext4_init_mballoc(void)
3151 {
3152         ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
3153                                         SLAB_RECLAIM_ACCOUNT);
3154         if (ext4_pspace_cachep == NULL)
3155                 goto out;
3156
3157         ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
3158                                     SLAB_RECLAIM_ACCOUNT);
3159         if (ext4_ac_cachep == NULL)
3160                 goto out_pa_free;
3161
3162         ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
3163                                            SLAB_RECLAIM_ACCOUNT);
3164         if (ext4_free_data_cachep == NULL)
3165                 goto out_ac_free;
3166
3167         return 0;
3168
3169 out_ac_free:
3170         kmem_cache_destroy(ext4_ac_cachep);
3171 out_pa_free:
3172         kmem_cache_destroy(ext4_pspace_cachep);
3173 out:
3174         return -ENOMEM;
3175 }
3176
3177 void ext4_exit_mballoc(void)
3178 {
3179         /*
3180          * Wait for completion of call_rcu()'s on ext4_pspace_cachep
3181          * before destroying the slab cache.
3182          */
3183         rcu_barrier();
3184         kmem_cache_destroy(ext4_pspace_cachep);
3185         kmem_cache_destroy(ext4_ac_cachep);
3186         kmem_cache_destroy(ext4_free_data_cachep);
3187         ext4_groupinfo_destroy_slabs();
3188 }
3189
3190
3191 /*
3192  * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
3193  * Returns 0 if success or error code
3194  */
3195 static noinline_for_stack int
3196 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
3197                                 handle_t *handle, unsigned int reserv_clstrs)
3198 {
3199         struct buffer_head *bitmap_bh = NULL;
3200         struct ext4_group_desc *gdp;
3201         struct buffer_head *gdp_bh;
3202         struct ext4_sb_info *sbi;
3203         struct super_block *sb;
3204         ext4_fsblk_t block;
3205         int err, len;
3206
3207         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3208         BUG_ON(ac->ac_b_ex.fe_len <= 0);
3209
3210         sb = ac->ac_sb;
3211         sbi = EXT4_SB(sb);
3212
3213         bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
3214         if (IS_ERR(bitmap_bh)) {
3215                 err = PTR_ERR(bitmap_bh);
3216                 bitmap_bh = NULL;
3217                 goto out_err;
3218         }
3219
3220         BUFFER_TRACE(bitmap_bh, "getting write access");
3221         err = ext4_journal_get_write_access(handle, bitmap_bh);
3222         if (err)
3223                 goto out_err;
3224
3225         err = -EIO;
3226         gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3227         if (!gdp)
3228                 goto out_err;
3229
3230         ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
3231                         ext4_free_group_clusters(sb, gdp));
3232
3233         BUFFER_TRACE(gdp_bh, "get_write_access");
3234         err = ext4_journal_get_write_access(handle, gdp_bh);
3235         if (err)
3236                 goto out_err;
3237
3238         block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3239
3240         len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3241         if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
3242                 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
3243                            "fs metadata", block, block+len);
3244                 /* File system mounted not to panic on error
3245                  * Fix the bitmap and return EFSCORRUPTED
3246                  * We leak some of the blocks here.
3247                  */
3248                 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3249                 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3250                               ac->ac_b_ex.fe_len);
3251                 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3252                 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3253                 if (!err)
3254                         err = -EFSCORRUPTED;
3255                 goto out_err;
3256         }
3257
3258         ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3259 #ifdef AGGRESSIVE_CHECK
3260         {
3261                 int i;
3262                 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3263                         BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3264                                                 bitmap_bh->b_data));
3265                 }
3266         }
3267 #endif
3268         ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3269                       ac->ac_b_ex.fe_len);
3270         if (ext4_has_group_desc_csum(sb) &&
3271             (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3272                 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3273                 ext4_free_group_clusters_set(sb, gdp,
3274                                              ext4_free_clusters_after_init(sb,
3275                                                 ac->ac_b_ex.fe_group, gdp));
3276         }
3277         len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
3278         ext4_free_group_clusters_set(sb, gdp, len);
3279         ext4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);
3280         ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
3281
3282         ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3283         percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
3284         /*
3285          * Now reduce the dirty block count also. Should not go negative
3286          */
3287         if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3288                 /* release all the reserved blocks if non delalloc */
3289                 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
3290                                    reserv_clstrs);
3291
3292         if (sbi->s_log_groups_per_flex) {
3293                 ext4_group_t flex_group = ext4_flex_group(sbi,
3294                                                           ac->ac_b_ex.fe_group);
3295                 atomic64_sub(ac->ac_b_ex.fe_len,
3296                              &sbi_array_rcu_deref(sbi, s_flex_groups,
3297                                                   flex_group)->free_clusters);
3298         }
3299
3300         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3301         if (err)
3302                 goto out_err;
3303         err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3304
3305 out_err:
3306         brelse(bitmap_bh);
3307         return err;
3308 }
3309
3310 /*
3311  * Idempotent helper for Ext4 fast commit replay path to set the state of
3312  * blocks in bitmaps and update counters.
3313  */
3314 void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
3315                         int len, int state)
3316 {
3317         struct buffer_head *bitmap_bh = NULL;
3318         struct ext4_group_desc *gdp;
3319         struct buffer_head *gdp_bh;
3320         struct ext4_sb_info *sbi = EXT4_SB(sb);
3321         ext4_group_t group;
3322         ext4_grpblk_t blkoff;
3323         int i, err;
3324         int already;
3325         unsigned int clen, clen_changed, thisgrp_len;
3326
3327         while (len > 0) {
3328                 ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
3329
3330                 /*
3331                  * Check to see if we are freeing blocks across a group
3332                  * boundary.
3333                  * In case of flex_bg, this can happen that (block, len) may
3334                  * span across more than one group. In that case we need to
3335                  * get the corresponding group metadata to work with.
3336                  * For this we have goto again loop.
3337                  */
3338                 thisgrp_len = min_t(unsigned int, (unsigned int)len,
3339                         EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
3340                 clen = EXT4_NUM_B2C(sbi, thisgrp_len);
3341
3342                 bitmap_bh = ext4_read_block_bitmap(sb, group);
3343                 if (IS_ERR(bitmap_bh)) {
3344                         err = PTR_ERR(bitmap_bh);
3345                         bitmap_bh = NULL;
3346                         break;
3347                 }
3348
3349                 err = -EIO;
3350                 gdp = ext4_get_group_desc(sb, group, &gdp_bh);
3351                 if (!gdp)
3352                         break;
3353
3354                 ext4_lock_group(sb, group);
3355                 already = 0;
3356                 for (i = 0; i < clen; i++)
3357                         if (!mb_test_bit(blkoff + i, bitmap_bh->b_data) ==
3358                                          !state)
3359                                 already++;
3360
3361                 clen_changed = clen - already;
3362                 if (state)
3363                         ext4_set_bits(bitmap_bh->b_data, blkoff, clen);
3364                 else
3365                         mb_test_and_clear_bits(bitmap_bh->b_data, blkoff, clen);
3366                 if (ext4_has_group_desc_csum(sb) &&
3367                     (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3368                         gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3369                         ext4_free_group_clusters_set(sb, gdp,
3370                              ext4_free_clusters_after_init(sb, group, gdp));
3371                 }
3372                 if (state)
3373                         clen = ext4_free_group_clusters(sb, gdp) - clen_changed;
3374                 else
3375                         clen = ext4_free_group_clusters(sb, gdp) + clen_changed;
3376
3377                 ext4_free_group_clusters_set(sb, gdp, clen);
3378                 ext4_block_bitmap_csum_set(sb, group, gdp, bitmap_bh);
3379                 ext4_group_desc_csum_set(sb, group, gdp);
3380
3381                 ext4_unlock_group(sb, group);
3382
3383                 if (sbi->s_log_groups_per_flex) {
3384                         ext4_group_t flex_group = ext4_flex_group(sbi, group);
3385                         struct flex_groups *fg = sbi_array_rcu_deref(sbi,
3386                                                    s_flex_groups, flex_group);
3387
3388                         if (state)
3389                                 atomic64_sub(clen_changed, &fg->free_clusters);
3390                         else
3391                                 atomic64_add(clen_changed, &fg->free_clusters);
3392
3393                 }
3394
3395                 err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
3396                 if (err)
3397                         break;
3398                 sync_dirty_buffer(bitmap_bh);
3399                 err = ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
3400                 sync_dirty_buffer(gdp_bh);
3401                 if (err)
3402                         break;
3403
3404                 block += thisgrp_len;
3405                 len -= thisgrp_len;
3406                 brelse(bitmap_bh);
3407                 BUG_ON(len < 0);
3408         }
3409
3410         if (err)
3411                 brelse(bitmap_bh);
3412 }
3413
3414 /*
3415  * here we normalize request for locality group
3416  * Group request are normalized to s_mb_group_prealloc, which goes to
3417  * s_strip if we set the same via mount option.
3418  * s_mb_group_prealloc can be configured via
3419  * /sys/fs/ext4/<partition>/mb_group_prealloc
3420  *
3421  * XXX: should we try to preallocate more than the group has now?
3422  */
3423 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3424 {
3425         struct super_block *sb = ac->ac_sb;
3426         struct ext4_locality_group *lg = ac->ac_lg;
3427
3428         BUG_ON(lg == NULL);
3429         ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3430         mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
3431 }
3432
3433 /*
3434  * Normalization means making request better in terms of
3435  * size and alignment
3436  */
3437 static noinline_for_stack void
3438 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3439                                 struct ext4_allocation_request *ar)
3440 {
3441         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3442         int bsbits, max;
3443         ext4_lblk_t end;
3444         loff_t size, start_off;
3445         loff_t orig_size __maybe_unused;
3446         ext4_lblk_t start;
3447         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3448         struct ext4_prealloc_space *pa;
3449
3450         /* do normalize only data requests, metadata requests
3451            do not need preallocation */
3452         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3453                 return;
3454
3455         /* sometime caller may want exact blocks */
3456         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3457                 return;
3458
3459         /* caller may indicate that preallocation isn't
3460          * required (it's a tail, for example) */
3461         if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3462                 return;
3463
3464         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3465                 ext4_mb_normalize_group_request(ac);
3466                 return ;
3467         }
3468
3469         bsbits = ac->ac_sb->s_blocksize_bits;
3470
3471         /* first, let's learn actual file size
3472          * given current request is allocated */
3473         size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
3474         size = size << bsbits;
3475         if (size < i_size_read(ac->ac_inode))
3476                 size = i_size_read(ac->ac_inode);
3477         orig_size = size;
3478
3479         /* max size of free chunks */
3480         max = 2 << bsbits;
3481
3482 #define NRL_CHECK_SIZE(req, size, max, chunk_size)      \
3483                 (req <= (size) || max <= (chunk_size))
3484
3485         /* first, try to predict filesize */
3486         /* XXX: should this table be tunable? */
3487         start_off = 0;
3488         if (size <= 16 * 1024) {
3489                 size = 16 * 1024;
3490         } else if (size <= 32 * 1024) {
3491                 size = 32 * 1024;
3492         } else if (size <= 64 * 1024) {
3493                 size = 64 * 1024;
3494         } else if (size <= 128 * 1024) {
3495                 size = 128 * 1024;
3496         } else if (size <= 256 * 1024) {
3497                 size = 256 * 1024;
3498         } else if (size <= 512 * 1024) {
3499                 size = 512 * 1024;
3500         } else if (size <= 1024 * 1024) {
3501                 size = 1024 * 1024;
3502         } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3503                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3504                                                 (21 - bsbits)) << 21;
3505                 size = 2 * 1024 * 1024;
3506         } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3507                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3508                                                         (22 - bsbits)) << 22;
3509                 size = 4 * 1024 * 1024;
3510         } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3511                                         (8<<20)>>bsbits, max, 8 * 1024)) {
3512                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3513                                                         (23 - bsbits)) << 23;
3514                 size = 8 * 1024 * 1024;
3515         } else {
3516                 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
3517                 size      = (loff_t) EXT4_C2B(EXT4_SB(ac->ac_sb),
3518                                               ac->ac_o_ex.fe_len) << bsbits;
3519         }
3520         size = size >> bsbits;
3521         start = start_off >> bsbits;
3522
3523         /*
3524          * For tiny groups (smaller than 8MB) the chosen allocation
3525          * alignment may be larger than group size. Make sure the
3526          * alignment does not move allocation to a different group which
3527          * makes mballoc fail assertions later.
3528          */
3529         start = max(start, rounddown(ac->ac_o_ex.fe_logical,
3530                         (ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
3531
3532         /* don't cover already allocated blocks in selected range */
3533         if (ar->pleft && start <= ar->lleft) {
3534                 size -= ar->lleft + 1 - start;
3535                 start = ar->lleft + 1;
3536         }
3537         if (ar->pright && start + size - 1 >= ar->lright)
3538                 size -= start + size - ar->lright;
3539
3540         /*
3541          * Trim allocation request for filesystems with artificially small
3542          * groups.
3543          */
3544         if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
3545                 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
3546
3547         end = start + size;
3548
3549         /* check we don't cross already preallocated blocks */
3550         rcu_read_lock();
3551         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3552                 ext4_lblk_t pa_end;
3553
3554                 if (pa->pa_deleted)
3555                         continue;
3556                 spin_lock(&pa->pa_lock);
3557                 if (pa->pa_deleted) {
3558                         spin_unlock(&pa->pa_lock);
3559                         continue;
3560                 }
3561
3562                 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3563                                                   pa->pa_len);
3564
3565                 /* PA must not overlap original request */
3566                 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3567                         ac->ac_o_ex.fe_logical < pa->pa_lstart));
3568
3569                 /* skip PAs this normalized request doesn't overlap with */
3570                 if (pa->pa_lstart >= end || pa_end <= start) {
3571                         spin_unlock(&pa->pa_lock);
3572                         continue;
3573                 }
3574                 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3575
3576                 /* adjust start or end to be adjacent to this pa */
3577                 if (pa_end <= ac->ac_o_ex.fe_logical) {
3578                         BUG_ON(pa_end < start);
3579                         start = pa_end;
3580                 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3581                         BUG_ON(pa->pa_lstart > end);
3582                         end = pa->pa_lstart;
3583                 }
3584                 spin_unlock(&pa->pa_lock);
3585         }
3586         rcu_read_unlock();
3587         size = end - start;
3588
3589         /* XXX: extra loop to check we really don't overlap preallocations */
3590         rcu_read_lock();
3591         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3592                 ext4_lblk_t pa_end;
3593
3594                 spin_lock(&pa->pa_lock);
3595                 if (pa->pa_deleted == 0) {
3596                         pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3597                                                           pa->pa_len);
3598                         BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3599                 }
3600                 spin_unlock(&pa->pa_lock);
3601         }
3602         rcu_read_unlock();
3603
3604         if (start + size <= ac->ac_o_ex.fe_logical &&
3605                         start > ac->ac_o_ex.fe_logical) {
3606                 ext4_msg(ac->ac_sb, KERN_ERR,
3607                          "start %lu, size %lu, fe_logical %lu",
3608                          (unsigned long) start, (unsigned long) size,
3609                          (unsigned long) ac->ac_o_ex.fe_logical);
3610                 BUG();
3611         }
3612         BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3613
3614         /* now prepare goal request */
3615
3616         /* XXX: is it better to align blocks WRT to logical
3617          * placement or satisfy big request as is */
3618         ac->ac_g_ex.fe_logical = start;
3619         ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3620
3621         /* define goal start in order to merge */
3622         if (ar->pright && (ar->lright == (start + size))) {
3623                 /* merge to the right */
3624                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3625                                                 &ac->ac_f_ex.fe_group,
3626                                                 &ac->ac_f_ex.fe_start);
3627                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3628         }
3629         if (ar->pleft && (ar->lleft + 1 == start)) {
3630                 /* merge to the left */
3631                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3632                                                 &ac->ac_f_ex.fe_group,
3633                                                 &ac->ac_f_ex.fe_start);
3634                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3635         }
3636
3637         mb_debug(ac->ac_sb, "goal: %lld(was %lld) blocks at %u\n", size,
3638                  orig_size, start);
3639 }
3640
3641 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3642 {
3643         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3644
3645         if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3646                 atomic_inc(&sbi->s_bal_reqs);
3647                 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3648                 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3649                         atomic_inc(&sbi->s_bal_success);
3650                 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3651                 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3652                                 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3653                         atomic_inc(&sbi->s_bal_goals);
3654                 if (ac->ac_found > sbi->s_mb_max_to_scan)
3655                         atomic_inc(&sbi->s_bal_breaks);
3656         }
3657
3658         if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3659                 trace_ext4_mballoc_alloc(ac);
3660         else
3661                 trace_ext4_mballoc_prealloc(ac);
3662 }
3663
3664 /*
3665  * Called on failure; free up any blocks from the inode PA for this
3666  * context.  We don't need this for MB_GROUP_PA because we only change
3667  * pa_free in ext4_mb_release_context(), but on failure, we've already
3668  * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3669  */
3670 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3671 {
3672         struct ext4_prealloc_space *pa = ac->ac_pa;
3673         struct ext4_buddy e4b;
3674         int err;
3675
3676         if (pa == NULL) {
3677                 if (ac->ac_f_ex.fe_len == 0)
3678                         return;
3679                 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
3680                 if (err) {
3681                         /*
3682                          * This should never happen since we pin the
3683                          * pages in the ext4_allocation_context so
3684                          * ext4_mb_load_buddy() should never fail.
3685                          */
3686                         WARN(1, "mb_load_buddy failed (%d)", err);
3687                         return;
3688                 }
3689                 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3690                 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
3691                                ac->ac_f_ex.fe_len);
3692                 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3693                 ext4_mb_unload_buddy(&e4b);
3694                 return;
3695         }
3696         if (pa->pa_type == MB_INODE_PA)
3697                 pa->pa_free += ac->ac_b_ex.fe_len;
3698 }
3699
3700 /*
3701  * use blocks preallocated to inode
3702  */
3703 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3704                                 struct ext4_prealloc_space *pa)
3705 {
3706         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3707         ext4_fsblk_t start;
3708         ext4_fsblk_t end;
3709         int len;
3710
3711         /* found preallocated blocks, use them */
3712         start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3713         end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
3714                   start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
3715         len = EXT4_NUM_B2C(sbi, end - start);
3716         ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3717                                         &ac->ac_b_ex.fe_start);
3718         ac->ac_b_ex.fe_len = len;
3719         ac->ac_status = AC_STATUS_FOUND;
3720         ac->ac_pa = pa;
3721
3722         BUG_ON(start < pa->pa_pstart);
3723         BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3724         BUG_ON(pa->pa_free < len);
3725         pa->pa_free -= len;
3726
3727         mb_debug(ac->ac_sb, "use %llu/%d from inode pa %p\n", start, len, pa);
3728 }
3729
3730 /*
3731  * use blocks preallocated to locality group
3732  */
3733 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3734                                 struct ext4_prealloc_space *pa)
3735 {
3736         unsigned int len = ac->ac_o_ex.fe_len;
3737
3738         ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3739                                         &ac->ac_b_ex.fe_group,
3740                                         &ac->ac_b_ex.fe_start);
3741         ac->ac_b_ex.fe_len = len;
3742         ac->ac_status = AC_STATUS_FOUND;
3743         ac->ac_pa = pa;
3744
3745         /* we don't correct pa_pstart or pa_plen here to avoid
3746          * possible race when the group is being loaded concurrently
3747          * instead we correct pa later, after blocks are marked
3748          * in on-disk bitmap -- see ext4_mb_release_context()
3749          * Other CPUs are prevented from allocating from this pa by lg_mutex
3750          */
3751         mb_debug(ac->ac_sb, "use %u/%u from group pa %p\n",
3752                  pa->pa_lstart-len, len, pa);
3753 }
3754
3755 /*
3756  * Return the prealloc space that have minimal distance
3757  * from the goal block. @cpa is the prealloc
3758  * space that is having currently known minimal distance
3759  * from the goal block.
3760  */
3761 static struct ext4_prealloc_space *
3762 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3763                         struct ext4_prealloc_space *pa,
3764                         struct ext4_prealloc_space *cpa)
3765 {
3766         ext4_fsblk_t cur_distance, new_distance;
3767
3768         if (cpa == NULL) {
3769                 atomic_inc(&pa->pa_count);
3770                 return pa;
3771         }
3772         cur_distance = abs(goal_block - cpa->pa_pstart);
3773         new_distance = abs(goal_block - pa->pa_pstart);
3774
3775         if (cur_distance <= new_distance)
3776                 return cpa;
3777
3778         /* drop the previous reference */
3779         atomic_dec(&cpa->pa_count);
3780         atomic_inc(&pa->pa_count);
3781         return pa;
3782 }
3783
3784 /*
3785  * search goal blocks in preallocated space
3786  */
3787 static noinline_for_stack bool
3788 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3789 {
3790         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3791         int order, i;
3792         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3793         struct ext4_locality_group *lg;
3794         struct ext4_prealloc_space *pa, *cpa = NULL;
3795         ext4_fsblk_t goal_block;
3796
3797         /* only data can be preallocated */
3798         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3799                 return false;
3800
3801         /* first, try per-file preallocation */
3802         rcu_read_lock();
3803         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3804
3805                 /* all fields in this condition don't change,
3806                  * so we can skip locking for them */
3807                 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3808                     ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
3809                                                EXT4_C2B(sbi, pa->pa_len)))
3810                         continue;
3811
3812                 /* non-extent files can't have physical blocks past 2^32 */
3813                 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3814                     (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
3815                      EXT4_MAX_BLOCK_FILE_PHYS))
3816                         continue;
3817
3818                 /* found preallocated blocks, use them */
3819                 spin_lock(&pa->pa_lock);
3820                 if (pa->pa_deleted == 0 && pa->pa_free) {
3821                         atomic_inc(&pa->pa_count);
3822                         ext4_mb_use_inode_pa(ac, pa);
3823                         spin_unlock(&pa->pa_lock);
3824                         ac->ac_criteria = 10;
3825                         rcu_read_unlock();
3826                         return true;
3827                 }
3828                 spin_unlock(&pa->pa_lock);
3829         }
3830         rcu_read_unlock();
3831
3832         /* can we use group allocation? */
3833         if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3834                 return false;
3835
3836         /* inode may have no locality group for some reason */
3837         lg = ac->ac_lg;
3838         if (lg == NULL)
3839                 return false;
3840         order  = fls(ac->ac_o_ex.fe_len) - 1;
3841         if (order > PREALLOC_TB_SIZE - 1)
3842                 /* The max size of hash table is PREALLOC_TB_SIZE */
3843                 order = PREALLOC_TB_SIZE - 1;
3844
3845         goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3846         /*
3847          * search for the prealloc space that is having
3848          * minimal distance from the goal block.
3849          */
3850         for (i = order; i < PREALLOC_TB_SIZE; i++) {
3851                 rcu_read_lock();
3852                 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3853                                         pa_inode_list) {
3854                         spin_lock(&pa->pa_lock);
3855                         if (pa->pa_deleted == 0 &&
3856                                         pa->pa_free >= ac->ac_o_ex.fe_len) {
3857
3858                                 cpa = ext4_mb_check_group_pa(goal_block,
3859                                                                 pa, cpa);
3860                         }
3861                         spin_unlock(&pa->pa_lock);
3862                 }
3863                 rcu_read_unlock();
3864         }
3865         if (cpa) {
3866                 ext4_mb_use_group_pa(ac, cpa);
3867                 ac->ac_criteria = 20;
3868                 return true;
3869         }
3870         return false;
3871 }
3872
3873 /*
3874  * the function goes through all block freed in the group
3875  * but not yet committed and marks them used in in-core bitmap.
3876  * buddy must be generated from this bitmap
3877  * Need to be called with the ext4 group lock held
3878  */
3879 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3880                                                 ext4_group_t group)
3881 {
3882         struct rb_node *n;
3883         struct ext4_group_info *grp;
3884         struct ext4_free_data *entry;
3885
3886         grp = ext4_get_group_info(sb, group);
3887         n = rb_first(&(grp->bb_free_root));
3888
3889         while (n) {
3890                 entry = rb_entry(n, struct ext4_free_data, efd_node);
3891                 ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
3892                 n = rb_next(n);
3893         }
3894         return;
3895 }
3896
3897 /*
3898  * the function goes through all preallocation in this group and marks them
3899  * used in in-core bitmap. buddy must be generated from this bitmap
3900  * Need to be called with ext4 group lock held
3901  */
3902 static noinline_for_stack
3903 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3904                                         ext4_group_t group)
3905 {
3906         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3907         struct ext4_prealloc_space *pa;
3908         struct list_head *cur;
3909         ext4_group_t groupnr;
3910         ext4_grpblk_t start;
3911         int preallocated = 0;
3912         int len;
3913
3914         /* all form of preallocation discards first load group,
3915          * so the only competing code is preallocation use.
3916          * we don't need any locking here
3917          * notice we do NOT ignore preallocations with pa_deleted
3918          * otherwise we could leave used blocks available for
3919          * allocation in buddy when concurrent ext4_mb_put_pa()
3920          * is dropping preallocation
3921          */
3922         list_for_each(cur, &grp->bb_prealloc_list) {
3923                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3924                 spin_lock(&pa->pa_lock);
3925                 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3926                                              &groupnr, &start);
3927                 len = pa->pa_len;
3928                 spin_unlock(&pa->pa_lock);
3929                 if (unlikely(len == 0))
3930                         continue;
3931                 BUG_ON(groupnr != group);
3932                 ext4_set_bits(bitmap, start, len);
3933                 preallocated += len;
3934         }
3935         mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
3936 }
3937
3938 static void ext4_mb_mark_pa_deleted(struct super_block *sb,
3939                                     struct ext4_prealloc_space *pa)
3940 {
3941         struct ext4_inode_info *ei;
3942
3943         if (pa->pa_deleted) {
3944                 ext4_warning(sb, "deleted pa, type:%d, pblk:%llu, lblk:%u, len:%d\n",
3945                              pa->pa_type, pa->pa_pstart, pa->pa_lstart,
3946                              pa->pa_len);
3947                 return;
3948         }
3949
3950         pa->pa_deleted = 1;
3951
3952         if (pa->pa_type == MB_INODE_PA) {
3953                 ei = EXT4_I(pa->pa_inode);
3954                 atomic_dec(&ei->i_prealloc_active);
3955         }
3956 }
3957
3958 static void ext4_mb_pa_callback(struct rcu_head *head)
3959 {
3960         struct ext4_prealloc_space *pa;
3961         pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3962
3963         BUG_ON(atomic_read(&pa->pa_count));
3964         BUG_ON(pa->pa_deleted == 0);
3965         kmem_cache_free(ext4_pspace_cachep, pa);
3966 }
3967
3968 /*
3969  * drops a reference to preallocated space descriptor
3970  * if this was the last reference and the space is consumed
3971  */
3972 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3973                         struct super_block *sb, struct ext4_prealloc_space *pa)
3974 {
3975         ext4_group_t grp;
3976         ext4_fsblk_t grp_blk;
3977
3978         /* in this short window concurrent discard can set pa_deleted */
3979         spin_lock(&pa->pa_lock);
3980         if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
3981                 spin_unlock(&pa->pa_lock);
3982                 return;
3983         }
3984
3985         if (pa->pa_deleted == 1) {
3986                 spin_unlock(&pa->pa_lock);
3987                 return;
3988         }
3989
3990         ext4_mb_mark_pa_deleted(sb, pa);
3991         spin_unlock(&pa->pa_lock);
3992
3993         grp_blk = pa->pa_pstart;
3994         /*
3995          * If doing group-based preallocation, pa_pstart may be in the
3996          * next group when pa is used up
3997          */
3998         if (pa->pa_type == MB_GROUP_PA)
3999                 grp_blk--;
4000
4001         grp = ext4_get_group_number(sb, grp_blk);
4002
4003         /*
4004          * possible race:
4005          *
4006          *  P1 (buddy init)                     P2 (regular allocation)
4007          *                                      find block B in PA
4008          *  copy on-disk bitmap to buddy
4009          *                                      mark B in on-disk bitmap
4010          *                                      drop PA from group
4011          *  mark all PAs in buddy
4012          *
4013          * thus, P1 initializes buddy with B available. to prevent this
4014          * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
4015          * against that pair
4016          */
4017         ext4_lock_group(sb, grp);
4018         list_del(&pa->pa_group_list);
4019         ext4_unlock_group(sb, grp);
4020
4021         spin_lock(pa->pa_obj_lock);
4022         list_del_rcu(&pa->pa_inode_list);
4023         spin_unlock(pa->pa_obj_lock);
4024
4025         call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4026 }
4027
4028 /*
4029  * creates new preallocated space for given inode
4030  */
4031 static noinline_for_stack void
4032 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
4033 {
4034         struct super_block *sb = ac->ac_sb;
4035         struct ext4_sb_info *sbi = EXT4_SB(sb);
4036         struct ext4_prealloc_space *pa;
4037         struct ext4_group_info *grp;
4038         struct ext4_inode_info *ei;
4039
4040         /* preallocate only when found space is larger then requested */
4041         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
4042         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
4043         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
4044         BUG_ON(ac->ac_pa == NULL);
4045
4046         pa = ac->ac_pa;
4047
4048         if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
4049                 int winl;
4050                 int wins;
4051                 int win;
4052                 int offs;
4053
4054                 /* we can't allocate as much as normalizer wants.
4055                  * so, found space must get proper lstart
4056                  * to cover original request */
4057                 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
4058                 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
4059
4060                 /* we're limited by original request in that
4061                  * logical block must be covered any way
4062                  * winl is window we can move our chunk within */
4063                 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
4064
4065                 /* also, we should cover whole original request */
4066                 wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
4067
4068                 /* the smallest one defines real window */
4069                 win = min(winl, wins);
4070
4071                 offs = ac->ac_o_ex.fe_logical %
4072                         EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4073                 if (offs && offs < win)
4074                         win = offs;
4075
4076                 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
4077                         EXT4_NUM_B2C(sbi, win);
4078                 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
4079                 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
4080         }
4081
4082         /* preallocation can change ac_b_ex, thus we store actually
4083          * allocated blocks for history */
4084         ac->ac_f_ex = ac->ac_b_ex;
4085
4086         pa->pa_lstart = ac->ac_b_ex.fe_logical;
4087         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4088         pa->pa_len = ac->ac_b_ex.fe_len;
4089         pa->pa_free = pa->pa_len;
4090         spin_lock_init(&pa->pa_lock);
4091         INIT_LIST_HEAD(&pa->pa_inode_list);
4092         INIT_LIST_HEAD(&pa->pa_group_list);
4093         pa->pa_deleted = 0;
4094         pa->pa_type = MB_INODE_PA;
4095
4096         mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
4097                  pa->pa_len, pa->pa_lstart);
4098         trace_ext4_mb_new_inode_pa(ac, pa);
4099
4100         ext4_mb_use_inode_pa(ac, pa);
4101         atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
4102
4103         ei = EXT4_I(ac->ac_inode);
4104         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
4105
4106         pa->pa_obj_lock = &ei->i_prealloc_lock;
4107         pa->pa_inode = ac->ac_inode;
4108
4109         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
4110
4111         spin_lock(pa->pa_obj_lock);
4112         list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
4113         spin_unlock(pa->pa_obj_lock);
4114         atomic_inc(&ei->i_prealloc_active);
4115 }
4116
4117 /*
4118  * creates new preallocated space for locality group inodes belongs to
4119  */
4120 static noinline_for_stack void
4121 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
4122 {
4123         struct super_block *sb = ac->ac_sb;
4124         struct ext4_locality_group *lg;
4125         struct ext4_prealloc_space *pa;
4126         struct ext4_group_info *grp;
4127
4128         /* preallocate only when found space is larger then requested */
4129         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
4130         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
4131         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
4132         BUG_ON(ac->ac_pa == NULL);
4133
4134         pa = ac->ac_pa;
4135
4136         /* preallocation can change ac_b_ex, thus we store actually
4137          * allocated blocks for history */
4138         ac->ac_f_ex = ac->ac_b_ex;
4139
4140         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4141         pa->pa_lstart = pa->pa_pstart;
4142         pa->pa_len = ac->ac_b_ex.fe_len;
4143         pa->pa_free = pa->pa_len;
4144         spin_lock_init(&pa->pa_lock);
4145         INIT_LIST_HEAD(&pa->pa_inode_list);
4146         INIT_LIST_HEAD(&pa->pa_group_list);
4147         pa->pa_deleted = 0;
4148         pa->pa_type = MB_GROUP_PA;
4149
4150         mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
4151                  pa->pa_len, pa->pa_lstart);
4152         trace_ext4_mb_new_group_pa(ac, pa);
4153
4154         ext4_mb_use_group_pa(ac, pa);
4155         atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
4156
4157         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
4158         lg = ac->ac_lg;
4159         BUG_ON(lg == NULL);
4160
4161         pa->pa_obj_lock = &lg->lg_prealloc_lock;
4162         pa->pa_inode = NULL;
4163
4164         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
4165
4166         /*
4167          * We will later add the new pa to the right bucket
4168          * after updating the pa_free in ext4_mb_release_context
4169          */
4170 }
4171
4172 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
4173 {
4174         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4175                 ext4_mb_new_group_pa(ac);
4176         else
4177                 ext4_mb_new_inode_pa(ac);
4178 }
4179
4180 /*
4181  * finds all unused blocks in on-disk bitmap, frees them in
4182  * in-core bitmap and buddy.
4183  * @pa must be unlinked from inode and group lists, so that
4184  * nobody else can find/use it.
4185  * the caller MUST hold group/inode locks.
4186  * TODO: optimize the case when there are no in-core structures yet
4187  */
4188 static noinline_for_stack int
4189 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
4190                         struct ext4_prealloc_space *pa)
4191 {
4192         struct super_block *sb = e4b->bd_sb;
4193         struct ext4_sb_info *sbi = EXT4_SB(sb);
4194         unsigned int end;
4195         unsigned int next;
4196         ext4_group_t group;
4197         ext4_grpblk_t bit;
4198         unsigned long long grp_blk_start;
4199         int free = 0;
4200
4201         BUG_ON(pa->pa_deleted == 0);
4202         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
4203         grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
4204         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
4205         end = bit + pa->pa_len;
4206
4207         while (bit < end) {
4208                 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
4209                 if (bit >= end)
4210                         break;
4211                 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
4212                 mb_debug(sb, "free preallocated %u/%u in group %u\n",
4213                          (unsigned) ext4_group_first_block_no(sb, group) + bit,
4214                          (unsigned) next - bit, (unsigned) group);
4215                 free += next - bit;
4216
4217                 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
4218                 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
4219                                                     EXT4_C2B(sbi, bit)),
4220                                                next - bit);
4221                 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
4222                 bit = next + 1;
4223         }
4224         if (free != pa->pa_free) {
4225                 ext4_msg(e4b->bd_sb, KERN_CRIT,
4226                          "pa %p: logic %lu, phys. %lu, len %d",
4227                          pa, (unsigned long) pa->pa_lstart,
4228                          (unsigned long) pa->pa_pstart,
4229                          pa->pa_len);
4230                 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
4231                                         free, pa->pa_free);
4232                 /*
4233                  * pa is already deleted so we use the value obtained
4234                  * from the bitmap and continue.
4235                  */
4236         }
4237         atomic_add(free, &sbi->s_mb_discarded);
4238
4239         return 0;
4240 }
4241
4242 static noinline_for_stack int
4243 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
4244                                 struct ext4_prealloc_space *pa)
4245 {
4246         struct super_block *sb = e4b->bd_sb;
4247         ext4_group_t group;
4248         ext4_grpblk_t bit;
4249
4250         trace_ext4_mb_release_group_pa(sb, pa);
4251         BUG_ON(pa->pa_deleted == 0);
4252         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
4253         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
4254         mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
4255         atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
4256         trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
4257
4258         return 0;
4259 }
4260
4261 /*
4262  * releases all preallocations in given group
4263  *
4264  * first, we need to decide discard policy:
4265  * - when do we discard
4266  *   1) ENOSPC
4267  * - how many do we discard
4268  *   1) how many requested
4269  */
4270 static noinline_for_stack int
4271 ext4_mb_discard_group_preallocations(struct super_block *sb,
4272                                      ext4_group_t group, int *busy)
4273 {
4274         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
4275         struct buffer_head *bitmap_bh = NULL;
4276         struct ext4_prealloc_space *pa, *tmp;
4277         struct list_head list;
4278         struct ext4_buddy e4b;
4279         int err;
4280         int free = 0;
4281
4282         mb_debug(sb, "discard preallocation for group %u\n", group);
4283         if (list_empty(&grp->bb_prealloc_list))
4284                 goto out_dbg;
4285
4286         bitmap_bh = ext4_read_block_bitmap(sb, group);
4287         if (IS_ERR(bitmap_bh)) {
4288                 err = PTR_ERR(bitmap_bh);
4289                 ext4_error_err(sb, -err,
4290                                "Error %d reading block bitmap for %u",
4291                                err, group);
4292                 goto out_dbg;
4293         }
4294
4295         err = ext4_mb_load_buddy(sb, group, &e4b);
4296         if (err) {
4297                 ext4_warning(sb, "Error %d loading buddy information for %u",
4298                              err, group);
4299                 put_bh(bitmap_bh);
4300                 goto out_dbg;
4301         }
4302
4303         INIT_LIST_HEAD(&list);
4304         ext4_lock_group(sb, group);
4305         list_for_each_entry_safe(pa, tmp,
4306                                 &grp->bb_prealloc_list, pa_group_list) {
4307                 spin_lock(&pa->pa_lock);
4308                 if (atomic_read(&pa->pa_count)) {
4309                         spin_unlock(&pa->pa_lock);
4310                         *busy = 1;
4311                         continue;
4312                 }
4313                 if (pa->pa_deleted) {
4314                         spin_unlock(&pa->pa_lock);
4315                         continue;
4316                 }
4317
4318                 /* seems this one can be freed ... */
4319                 ext4_mb_mark_pa_deleted(sb, pa);
4320
4321                 if (!free)
4322                         this_cpu_inc(discard_pa_seq);
4323
4324                 /* we can trust pa_free ... */
4325                 free += pa->pa_free;
4326
4327                 spin_unlock(&pa->pa_lock);
4328
4329                 list_del(&pa->pa_group_list);
4330                 list_add(&pa->u.pa_tmp_list, &list);
4331         }
4332
4333         /* now free all selected PAs */
4334         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4335
4336                 /* remove from object (inode or locality group) */
4337                 spin_lock(pa->pa_obj_lock);
4338                 list_del_rcu(&pa->pa_inode_list);
4339                 spin_unlock(pa->pa_obj_lock);
4340
4341                 if (pa->pa_type == MB_GROUP_PA)
4342                         ext4_mb_release_group_pa(&e4b, pa);
4343                 else
4344                         ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4345
4346                 list_del(&pa->u.pa_tmp_list);
4347                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4348         }
4349
4350         ext4_unlock_group(sb, group);
4351         ext4_mb_unload_buddy(&e4b);
4352         put_bh(bitmap_bh);
4353 out_dbg:
4354         mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
4355                  free, group, grp->bb_free);
4356         return free;
4357 }
4358
4359 /*
4360  * releases all non-used preallocated blocks for given inode
4361  *
4362  * It's important to discard preallocations under i_data_sem
4363  * We don't want another block to be served from the prealloc
4364  * space when we are discarding the inode prealloc space.
4365  *
4366  * FIXME!! Make sure it is valid at all the call sites
4367  */
4368 void ext4_discard_preallocations(struct inode *inode, unsigned int needed)
4369 {
4370         struct ext4_inode_info *ei = EXT4_I(inode);
4371         struct super_block *sb = inode->i_sb;
4372         struct buffer_head *bitmap_bh = NULL;
4373         struct ext4_prealloc_space *pa, *tmp;
4374         ext4_group_t group = 0;
4375         struct list_head list;
4376         struct ext4_buddy e4b;
4377         int err;
4378
4379         if (!S_ISREG(inode->i_mode)) {
4380                 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4381                 return;
4382         }
4383
4384         if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
4385                 return;
4386
4387         mb_debug(sb, "discard preallocation for inode %lu\n",
4388                  inode->i_ino);
4389         trace_ext4_discard_preallocations(inode,
4390                         atomic_read(&ei->i_prealloc_active), needed);
4391
4392         INIT_LIST_HEAD(&list);
4393
4394         if (needed == 0)
4395                 needed = UINT_MAX;
4396
4397 repeat:
4398         /* first, collect all pa's in the inode */
4399         spin_lock(&ei->i_prealloc_lock);
4400         while (!list_empty(&ei->i_prealloc_list) && needed) {
4401                 pa = list_entry(ei->i_prealloc_list.prev,
4402                                 struct ext4_prealloc_space, pa_inode_list);
4403                 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4404                 spin_lock(&pa->pa_lock);
4405                 if (atomic_read(&pa->pa_count)) {
4406                         /* this shouldn't happen often - nobody should
4407                          * use preallocation while we're discarding it */
4408                         spin_unlock(&pa->pa_lock);
4409                         spin_unlock(&ei->i_prealloc_lock);
4410                         ext4_msg(sb, KERN_ERR,
4411                                  "uh-oh! used pa while discarding");
4412                         WARN_ON(1);
4413                         schedule_timeout_uninterruptible(HZ);
4414                         goto repeat;
4415
4416                 }
4417                 if (pa->pa_deleted == 0) {
4418                         ext4_mb_mark_pa_deleted(sb, pa);
4419                         spin_unlock(&pa->pa_lock);
4420                         list_del_rcu(&pa->pa_inode_list);
4421                         list_add(&pa->u.pa_tmp_list, &list);
4422                         needed--;
4423                         continue;
4424                 }
4425
4426                 /* someone is deleting pa right now */
4427                 spin_unlock(&pa->pa_lock);
4428                 spin_unlock(&ei->i_prealloc_lock);
4429
4430                 /* we have to wait here because pa_deleted
4431                  * doesn't mean pa is already unlinked from
4432                  * the list. as we might be called from
4433                  * ->clear_inode() the inode will get freed
4434                  * and concurrent thread which is unlinking
4435                  * pa from inode's list may access already
4436                  * freed memory, bad-bad-bad */
4437
4438                 /* XXX: if this happens too often, we can
4439                  * add a flag to force wait only in case
4440                  * of ->clear_inode(), but not in case of
4441                  * regular truncate */
4442                 schedule_timeout_uninterruptible(HZ);
4443                 goto repeat;
4444         }
4445         spin_unlock(&ei->i_prealloc_lock);
4446
4447         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4448                 BUG_ON(pa->pa_type != MB_INODE_PA);
4449                 group = ext4_get_group_number(sb, pa->pa_pstart);
4450
4451                 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4452                                              GFP_NOFS|__GFP_NOFAIL);
4453                 if (err) {
4454                         ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
4455                                        err, group);
4456                         continue;
4457                 }
4458
4459                 bitmap_bh = ext4_read_block_bitmap(sb, group);
4460                 if (IS_ERR(bitmap_bh)) {
4461                         err = PTR_ERR(bitmap_bh);
4462                         ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
4463                                        err, group);
4464                         ext4_mb_unload_buddy(&e4b);
4465                         continue;
4466                 }
4467
4468                 ext4_lock_group(sb, group);
4469                 list_del(&pa->pa_group_list);
4470                 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4471                 ext4_unlock_group(sb, group);
4472
4473                 ext4_mb_unload_buddy(&e4b);
4474                 put_bh(bitmap_bh);
4475
4476                 list_del(&pa->u.pa_tmp_list);
4477                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4478         }
4479 }
4480
4481 static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
4482 {
4483         struct ext4_prealloc_space *pa;
4484
4485         BUG_ON(ext4_pspace_cachep == NULL);
4486         pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
4487         if (!pa)
4488                 return -ENOMEM;
4489         atomic_set(&pa->pa_count, 1);
4490         ac->ac_pa = pa;
4491         return 0;
4492 }
4493
4494 static void ext4_mb_pa_free(struct ext4_allocation_context *ac)
4495 {
4496         struct ext4_prealloc_space *pa = ac->ac_pa;
4497
4498         BUG_ON(!pa);
4499         ac->ac_pa = NULL;
4500         WARN_ON(!atomic_dec_and_test(&pa->pa_count));
4501         kmem_cache_free(ext4_pspace_cachep, pa);
4502 }
4503
4504 #ifdef CONFIG_EXT4_DEBUG
4505 static inline void ext4_mb_show_pa(struct super_block *sb)
4506 {
4507         ext4_group_t i, ngroups;
4508
4509         if (ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
4510                 return;
4511
4512         ngroups = ext4_get_groups_count(sb);
4513         mb_debug(sb, "groups: ");
4514         for (i = 0; i < ngroups; i++) {
4515                 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4516                 struct ext4_prealloc_space *pa;
4517                 ext4_grpblk_t start;
4518                 struct list_head *cur;
4519                 ext4_lock_group(sb, i);
4520                 list_for_each(cur, &grp->bb_prealloc_list) {
4521                         pa = list_entry(cur, struct ext4_prealloc_space,
4522                                         pa_group_list);
4523                         spin_lock(&pa->pa_lock);
4524                         ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4525                                                      NULL, &start);
4526                         spin_unlock(&pa->pa_lock);
4527                         mb_debug(sb, "PA:%u:%d:%d\n", i, start,
4528                                  pa->pa_len);
4529                 }
4530                 ext4_unlock_group(sb, i);
4531                 mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
4532                          grp->bb_fragments);
4533         }
4534 }
4535
4536 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4537 {
4538         struct super_block *sb = ac->ac_sb;
4539
4540         if (ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
4541                 return;
4542
4543         mb_debug(sb, "Can't allocate:"
4544                         " Allocation context details:");
4545         mb_debug(sb, "status %u flags 0x%x",
4546                         ac->ac_status, ac->ac_flags);
4547         mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
4548                         "goal %lu/%lu/%lu@%lu, "
4549                         "best %lu/%lu/%lu@%lu cr %d",
4550                         (unsigned long)ac->ac_o_ex.fe_group,
4551                         (unsigned long)ac->ac_o_ex.fe_start,
4552                         (unsigned long)ac->ac_o_ex.fe_len,
4553                         (unsigned long)ac->ac_o_ex.fe_logical,
4554                         (unsigned long)ac->ac_g_ex.fe_group,
4555                         (unsigned long)ac->ac_g_ex.fe_start,
4556                         (unsigned long)ac->ac_g_ex.fe_len,
4557                         (unsigned long)ac->ac_g_ex.fe_logical,
4558                         (unsigned long)ac->ac_b_ex.fe_group,
4559                         (unsigned long)ac->ac_b_ex.fe_start,
4560                         (unsigned long)ac->ac_b_ex.fe_len,
4561                         (unsigned long)ac->ac_b_ex.fe_logical,
4562                         (int)ac->ac_criteria);
4563         mb_debug(sb, "%u found", ac->ac_found);
4564         ext4_mb_show_pa(sb);
4565 }
4566 #else
4567 static inline void ext4_mb_show_pa(struct super_block *sb)
4568 {
4569         return;
4570 }
4571 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4572 {
4573         ext4_mb_show_pa(ac->ac_sb);
4574         return;
4575 }
4576 #endif
4577
4578 /*
4579  * We use locality group preallocation for small size file. The size of the
4580  * file is determined by the current size or the resulting size after
4581  * allocation which ever is larger
4582  *
4583  * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4584  */
4585 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4586 {
4587         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4588         int bsbits = ac->ac_sb->s_blocksize_bits;
4589         loff_t size, isize;
4590
4591         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4592                 return;
4593
4594         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4595                 return;
4596
4597         size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
4598         isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
4599                 >> bsbits;
4600
4601         if ((size == isize) && !ext4_fs_is_busy(sbi) &&
4602             !inode_is_open_for_write(ac->ac_inode)) {
4603                 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
4604                 return;
4605         }
4606
4607         if (sbi->s_mb_group_prealloc <= 0) {
4608                 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4609                 return;
4610         }
4611
4612         /* don't use group allocation for large files */
4613         size = max(size, isize);
4614         if (size > sbi->s_mb_stream_request) {
4615                 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4616                 return;
4617         }
4618
4619         BUG_ON(ac->ac_lg != NULL);
4620         /*
4621          * locality group prealloc space are per cpu. The reason for having
4622          * per cpu locality group is to reduce the contention between block
4623          * request from multiple CPUs.
4624          */
4625         ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
4626
4627         /* we're going to use group allocation */
4628         ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4629
4630         /* serialize all allocations in the group */
4631         mutex_lock(&ac->ac_lg->lg_mutex);
4632 }
4633
4634 static noinline_for_stack int
4635 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4636                                 struct ext4_allocation_request *ar)
4637 {
4638         struct super_block *sb = ar->inode->i_sb;
4639         struct ext4_sb_info *sbi = EXT4_SB(sb);
4640         struct ext4_super_block *es = sbi->s_es;
4641         ext4_group_t group;
4642         unsigned int len;
4643         ext4_fsblk_t goal;
4644         ext4_grpblk_t block;
4645
4646         /* we can't allocate > group size */
4647         len = ar->len;
4648
4649         /* just a dirty hack to filter too big requests  */
4650         if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
4651                 len = EXT4_CLUSTERS_PER_GROUP(sb);
4652
4653         /* start searching from the goal */
4654         goal = ar->goal;
4655         if (goal < le32_to_cpu(es->s_first_data_block) ||
4656                         goal >= ext4_blocks_count(es))
4657                 goal = le32_to_cpu(es->s_first_data_block);
4658         ext4_get_group_no_and_offset(sb, goal, &group, &block);
4659
4660         /* set up allocation goals */
4661         ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
4662         ac->ac_status = AC_STATUS_CONTINUE;
4663         ac->ac_sb = sb;
4664         ac->ac_inode = ar->inode;
4665         ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4666         ac->ac_o_ex.fe_group = group;
4667         ac->ac_o_ex.fe_start = block;
4668         ac->ac_o_ex.fe_len = len;
4669         ac->ac_g_ex = ac->ac_o_ex;
4670         ac->ac_flags = ar->flags;
4671
4672         /* we have to define context: we'll work with a file or
4673          * locality group. this is a policy, actually */
4674         ext4_mb_group_or_file(ac);
4675
4676         mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
4677                         "left: %u/%u, right %u/%u to %swritable\n",
4678                         (unsigned) ar->len, (unsigned) ar->logical,
4679                         (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4680                         (unsigned) ar->lleft, (unsigned) ar->pleft,
4681                         (unsigned) ar->lright, (unsigned) ar->pright,
4682                         inode_is_open_for_write(ar->inode) ? "" : "non-");
4683         return 0;
4684
4685 }
4686
4687 static noinline_for_stack void
4688 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4689                                         struct ext4_locality_group *lg,
4690                                         int order, int total_entries)
4691 {
4692         ext4_group_t group = 0;
4693         struct ext4_buddy e4b;
4694         struct list_head discard_list;
4695         struct ext4_prealloc_space *pa, *tmp;
4696
4697         mb_debug(sb, "discard locality group preallocation\n");
4698
4699         INIT_LIST_HEAD(&discard_list);
4700
4701         spin_lock(&lg->lg_prealloc_lock);
4702         list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4703                                 pa_inode_list,
4704                                 lockdep_is_held(&lg->lg_prealloc_lock)) {
4705                 spin_lock(&pa->pa_lock);
4706                 if (atomic_read(&pa->pa_count)) {
4707                         /*
4708                          * This is the pa that we just used
4709                          * for block allocation. So don't
4710                          * free that
4711                          */
4712                         spin_unlock(&pa->pa_lock);
4713                         continue;
4714                 }
4715                 if (pa->pa_deleted) {
4716                         spin_unlock(&pa->pa_lock);
4717                         continue;
4718                 }
4719                 /* only lg prealloc space */
4720                 BUG_ON(pa->pa_type != MB_GROUP_PA);
4721
4722                 /* seems this one can be freed ... */
4723                 ext4_mb_mark_pa_deleted(sb, pa);
4724                 spin_unlock(&pa->pa_lock);
4725
4726                 list_del_rcu(&pa->pa_inode_list);
4727                 list_add(&pa->u.pa_tmp_list, &discard_list);
4728
4729                 total_entries--;
4730                 if (total_entries <= 5) {
4731                         /*
4732                          * we want to keep only 5 entries
4733                          * allowing it to grow to 8. This
4734                          * mak sure we don't call discard
4735                          * soon for this list.
4736                          */
4737                         break;
4738                 }
4739         }
4740         spin_unlock(&lg->lg_prealloc_lock);
4741
4742         list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4743                 int err;
4744
4745                 group = ext4_get_group_number(sb, pa->pa_pstart);
4746                 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4747                                              GFP_NOFS|__GFP_NOFAIL);
4748                 if (err) {
4749                         ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
4750                                        err, group);
4751                         continue;
4752                 }
4753                 ext4_lock_group(sb, group);
4754                 list_del(&pa->pa_group_list);
4755                 ext4_mb_release_group_pa(&e4b, pa);
4756                 ext4_unlock_group(sb, group);
4757
4758                 ext4_mb_unload_buddy(&e4b);
4759                 list_del(&pa->u.pa_tmp_list);
4760                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4761         }
4762 }
4763
4764 /*
4765  * We have incremented pa_count. So it cannot be freed at this
4766  * point. Also we hold lg_mutex. So no parallel allocation is
4767  * possible from this lg. That means pa_free cannot be updated.
4768  *
4769  * A parallel ext4_mb_discard_group_preallocations is possible.
4770  * which can cause the lg_prealloc_list to be updated.
4771  */
4772
4773 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4774 {
4775         int order, added = 0, lg_prealloc_count = 1;
4776         struct super_block *sb = ac->ac_sb;
4777         struct ext4_locality_group *lg = ac->ac_lg;
4778         struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4779
4780         order = fls(pa->pa_free) - 1;
4781         if (order > PREALLOC_TB_SIZE - 1)
4782                 /* The max size of hash table is PREALLOC_TB_SIZE */
4783                 order = PREALLOC_TB_SIZE - 1;
4784         /* Add the prealloc space to lg */
4785         spin_lock(&lg->lg_prealloc_lock);
4786         list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4787                                 pa_inode_list,
4788                                 lockdep_is_held(&lg->lg_prealloc_lock)) {
4789                 spin_lock(&tmp_pa->pa_lock);
4790                 if (tmp_pa->pa_deleted) {
4791                         spin_unlock(&tmp_pa->pa_lock);
4792                         continue;
4793                 }
4794                 if (!added && pa->pa_free < tmp_pa->pa_free) {
4795                         /* Add to the tail of the previous entry */
4796                         list_add_tail_rcu(&pa->pa_inode_list,
4797                                                 &tmp_pa->pa_inode_list);
4798                         added = 1;
4799                         /*
4800                          * we want to count the total
4801                          * number of entries in the list
4802                          */
4803                 }
4804                 spin_unlock(&tmp_pa->pa_lock);
4805                 lg_prealloc_count++;
4806         }
4807         if (!added)
4808                 list_add_tail_rcu(&pa->pa_inode_list,
4809                                         &lg->lg_prealloc_list[order]);
4810         spin_unlock(&lg->lg_prealloc_lock);
4811
4812         /* Now trim the list to be not more than 8 elements */
4813         if (lg_prealloc_count > 8) {
4814                 ext4_mb_discard_lg_preallocations(sb, lg,
4815                                                   order, lg_prealloc_count);
4816                 return;
4817         }
4818         return ;
4819 }
4820
4821 /*
4822  * if per-inode prealloc list is too long, trim some PA
4823  */
4824 static void ext4_mb_trim_inode_pa(struct inode *inode)
4825 {
4826         struct ext4_inode_info *ei = EXT4_I(inode);
4827         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4828         int count, delta;
4829
4830         count = atomic_read(&ei->i_prealloc_active);
4831         delta = (sbi->s_mb_max_inode_prealloc >> 2) + 1;
4832         if (count > sbi->s_mb_max_inode_prealloc + delta) {
4833                 count -= sbi->s_mb_max_inode_prealloc;
4834                 ext4_discard_preallocations(inode, count);
4835         }
4836 }
4837
4838 /*
4839  * release all resource we used in allocation
4840  */
4841 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4842 {
4843         struct inode *inode = ac->ac_inode;
4844         struct ext4_inode_info *ei = EXT4_I(inode);
4845         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4846         struct ext4_prealloc_space *pa = ac->ac_pa;
4847         if (pa) {
4848                 if (pa->pa_type == MB_GROUP_PA) {
4849                         /* see comment in ext4_mb_use_group_pa() */
4850                         spin_lock(&pa->pa_lock);
4851                         pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4852                         pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4853                         pa->pa_free -= ac->ac_b_ex.fe_len;
4854                         pa->pa_len -= ac->ac_b_ex.fe_len;
4855                         spin_unlock(&pa->pa_lock);
4856
4857                         /*
4858                          * We want to add the pa to the right bucket.
4859                          * Remove it from the list and while adding
4860                          * make sure the list to which we are adding
4861                          * doesn't grow big.
4862                          */
4863                         if (likely(pa->pa_free)) {
4864                                 spin_lock(pa->pa_obj_lock);
4865                                 list_del_rcu(&pa->pa_inode_list);
4866                                 spin_unlock(pa->pa_obj_lock);
4867                                 ext4_mb_add_n_trim(ac);
4868                         }
4869                 }
4870
4871                 if (pa->pa_type == MB_INODE_PA) {
4872                         /*
4873                          * treat per-inode prealloc list as a lru list, then try
4874                          * to trim the least recently used PA.
4875                          */
4876                         spin_lock(pa->pa_obj_lock);
4877                         list_move(&pa->pa_inode_list, &ei->i_prealloc_list);
4878                         spin_unlock(pa->pa_obj_lock);
4879                 }
4880
4881                 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4882         }
4883         if (ac->ac_bitmap_page)
4884                 put_page(ac->ac_bitmap_page);
4885         if (ac->ac_buddy_page)
4886                 put_page(ac->ac_buddy_page);
4887         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4888                 mutex_unlock(&ac->ac_lg->lg_mutex);
4889         ext4_mb_collect_stats(ac);
4890         ext4_mb_trim_inode_pa(inode);
4891         return 0;
4892 }
4893
4894 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4895 {
4896         ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4897         int ret;
4898         int freed = 0, busy = 0;
4899         int retry = 0;
4900
4901         trace_ext4_mb_discard_preallocations(sb, needed);
4902
4903         if (needed == 0)
4904                 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
4905  repeat:
4906         for (i = 0; i < ngroups && needed > 0; i++) {
4907                 ret = ext4_mb_discard_group_preallocations(sb, i, &busy);
4908                 freed += ret;
4909                 needed -= ret;
4910                 cond_resched();
4911         }
4912
4913         if (needed > 0 && busy && ++retry < 3) {
4914                 busy = 0;
4915                 goto repeat;
4916         }
4917
4918         return freed;
4919 }
4920
4921 static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
4922                         struct ext4_allocation_context *ac, u64 *seq)
4923 {
4924         int freed;
4925         u64 seq_retry = 0;
4926         bool ret = false;
4927
4928         freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4929         if (freed) {
4930                 ret = true;
4931                 goto out_dbg;
4932         }
4933         seq_retry = ext4_get_discard_pa_seq_sum();
4934         if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
4935                 ac->ac_flags |= EXT4_MB_STRICT_CHECK;
4936                 *seq = seq_retry;
4937                 ret = true;
4938         }
4939
4940 out_dbg:
4941         mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
4942         return ret;
4943 }
4944
4945 static ext4_fsblk_t ext4_mb_new_blocks_simple(handle_t *handle,
4946                                 struct ext4_allocation_request *ar, int *errp);
4947
4948 /*
4949  * Main entry point into mballoc to allocate blocks
4950  * it tries to use preallocation first, then falls back
4951  * to usual allocation
4952  */
4953 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4954                                 struct ext4_allocation_request *ar, int *errp)
4955 {
4956         struct ext4_allocation_context *ac = NULL;
4957         struct ext4_sb_info *sbi;
4958         struct super_block *sb;
4959         ext4_fsblk_t block = 0;
4960         unsigned int inquota = 0;
4961         unsigned int reserv_clstrs = 0;
4962         int retries = 0;
4963         u64 seq;
4964
4965         might_sleep();
4966         sb = ar->inode->i_sb;
4967         sbi = EXT4_SB(sb);
4968
4969         trace_ext4_request_blocks(ar);
4970         if (sbi->s_mount_state & EXT4_FC_REPLAY)
4971                 return ext4_mb_new_blocks_simple(handle, ar, errp);
4972
4973         /* Allow to use superuser reservation for quota file */
4974         if (ext4_is_quota_file(ar->inode))
4975                 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
4976
4977         if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
4978                 /* Without delayed allocation we need to verify
4979                  * there is enough free blocks to do block allocation
4980                  * and verify allocation doesn't exceed the quota limits.
4981                  */
4982                 while (ar->len &&
4983                         ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
4984
4985                         /* let others to free the space */
4986                         cond_resched();
4987                         ar->len = ar->len >> 1;
4988                 }
4989                 if (!ar->len) {
4990                         ext4_mb_show_pa(sb);
4991                         *errp = -ENOSPC;
4992                         return 0;
4993                 }
4994                 reserv_clstrs = ar->len;
4995                 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
4996                         dquot_alloc_block_nofail(ar->inode,
4997                                                  EXT4_C2B(sbi, ar->len));
4998                 } else {
4999                         while (ar->len &&
5000                                 dquot_alloc_block(ar->inode,
5001                                                   EXT4_C2B(sbi, ar->len))) {
5002
5003                                 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
5004                                 ar->len--;
5005                         }
5006                 }
5007                 inquota = ar->len;
5008                 if (ar->len == 0) {
5009                         *errp = -EDQUOT;
5010                         goto out;
5011                 }
5012         }
5013
5014         ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
5015         if (!ac) {
5016                 ar->len = 0;
5017                 *errp = -ENOMEM;
5018                 goto out;
5019         }
5020
5021         *errp = ext4_mb_initialize_context(ac, ar);
5022         if (*errp) {
5023                 ar->len = 0;
5024                 goto out;
5025         }
5026
5027         ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
5028         seq = this_cpu_read(discard_pa_seq);
5029         if (!ext4_mb_use_preallocated(ac)) {
5030                 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
5031                 ext4_mb_normalize_request(ac, ar);
5032
5033                 *errp = ext4_mb_pa_alloc(ac);
5034                 if (*errp)
5035                         goto errout;
5036 repeat:
5037                 /* allocate space in core */
5038                 *errp = ext4_mb_regular_allocator(ac);
5039                 /*
5040                  * pa allocated above is added to grp->bb_prealloc_list only
5041                  * when we were able to allocate some block i.e. when
5042                  * ac->ac_status == AC_STATUS_FOUND.
5043                  * And error from above mean ac->ac_status != AC_STATUS_FOUND
5044                  * So we have to free this pa here itself.
5045                  */
5046                 if (*errp) {
5047                         ext4_mb_pa_free(ac);
5048                         ext4_discard_allocated_blocks(ac);
5049                         goto errout;
5050                 }
5051                 if (ac->ac_status == AC_STATUS_FOUND &&
5052                         ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
5053                         ext4_mb_pa_free(ac);
5054         }
5055         if (likely(ac->ac_status == AC_STATUS_FOUND)) {
5056                 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
5057                 if (*errp) {
5058                         ext4_discard_allocated_blocks(ac);
5059                         goto errout;
5060                 } else {
5061                         block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5062                         ar->len = ac->ac_b_ex.fe_len;
5063                 }
5064         } else {
5065                 if (++retries < 3 &&
5066                     ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
5067                         goto repeat;
5068                 /*
5069                  * If block allocation fails then the pa allocated above
5070                  * needs to be freed here itself.
5071                  */
5072                 ext4_mb_pa_free(ac);
5073                 *errp = -ENOSPC;
5074         }
5075
5076 errout:
5077         if (*errp) {
5078                 ac->ac_b_ex.fe_len = 0;
5079                 ar->len = 0;
5080                 ext4_mb_show_ac(ac);
5081         }
5082         ext4_mb_release_context(ac);
5083 out:
5084         if (ac)
5085                 kmem_cache_free(ext4_ac_cachep, ac);
5086         if (inquota && ar->len < inquota)
5087                 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
5088         if (!ar->len) {
5089                 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
5090                         /* release all the reserved blocks if non delalloc */
5091                         percpu_counter_sub(&sbi->s_dirtyclusters_counter,
5092                                                 reserv_clstrs);
5093         }
5094
5095         trace_ext4_allocate_blocks(ar, (unsigned long long)block);
5096
5097         return block;
5098 }
5099
5100 /*
5101  * We can merge two free data extents only if the physical blocks
5102  * are contiguous, AND the extents were freed by the same transaction,
5103  * AND the blocks are associated with the same group.
5104  */
5105 static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
5106                                         struct ext4_free_data *entry,
5107                                         struct ext4_free_data *new_entry,
5108                                         struct rb_root *entry_rb_root)
5109 {
5110         if ((entry->efd_tid != new_entry->efd_tid) ||
5111             (entry->efd_group != new_entry->efd_group))
5112                 return;
5113         if (entry->efd_start_cluster + entry->efd_count ==
5114             new_entry->efd_start_cluster) {
5115                 new_entry->efd_start_cluster = entry->efd_start_cluster;
5116                 new_entry->efd_count += entry->efd_count;
5117         } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
5118                    entry->efd_start_cluster) {
5119                 new_entry->efd_count += entry->efd_count;
5120         } else
5121                 return;
5122         spin_lock(&sbi->s_md_lock);
5123         list_del(&entry->efd_list);
5124         spin_unlock(&sbi->s_md_lock);
5125         rb_erase(&entry->efd_node, entry_rb_root);
5126         kmem_cache_free(ext4_free_data_cachep, entry);
5127 }
5128
5129 static noinline_for_stack int
5130 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
5131                       struct ext4_free_data *new_entry)
5132 {
5133         ext4_group_t group = e4b->bd_group;
5134         ext4_grpblk_t cluster;
5135         ext4_grpblk_t clusters = new_entry->efd_count;
5136         struct ext4_free_data *entry;
5137         struct ext4_group_info *db = e4b->bd_info;
5138         struct super_block *sb = e4b->bd_sb;
5139         struct ext4_sb_info *sbi = EXT4_SB(sb);
5140         struct rb_node **n = &db->bb_free_root.rb_node, *node;
5141         struct rb_node *parent = NULL, *new_node;
5142
5143         BUG_ON(!ext4_handle_valid(handle));
5144         BUG_ON(e4b->bd_bitmap_page == NULL);
5145         BUG_ON(e4b->bd_buddy_page == NULL);
5146
5147         new_node = &new_entry->efd_node;
5148         cluster = new_entry->efd_start_cluster;
5149
5150         if (!*n) {
5151                 /* first free block exent. We need to
5152                    protect buddy cache from being freed,
5153                  * otherwise we'll refresh it from
5154                  * on-disk bitmap and lose not-yet-available
5155                  * blocks */
5156                 get_page(e4b->bd_buddy_page);
5157                 get_page(e4b->bd_bitmap_page);
5158         }
5159         while (*n) {
5160                 parent = *n;
5161                 entry = rb_entry(parent, struct ext4_free_data, efd_node);
5162                 if (cluster < entry->efd_start_cluster)
5163                         n = &(*n)->rb_left;
5164                 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
5165                         n = &(*n)->rb_right;
5166                 else {
5167                         ext4_grp_locked_error(sb, group, 0,
5168                                 ext4_group_first_block_no(sb, group) +
5169                                 EXT4_C2B(sbi, cluster),
5170                                 "Block already on to-be-freed list");
5171                         kmem_cache_free(ext4_free_data_cachep, new_entry);
5172                         return 0;
5173                 }
5174         }
5175
5176         rb_link_node(new_node, parent, n);
5177         rb_insert_color(new_node, &db->bb_free_root);
5178
5179         /* Now try to see the extent can be merged to left and right */
5180         node = rb_prev(new_node);
5181         if (node) {
5182                 entry = rb_entry(node, struct ext4_free_data, efd_node);
5183                 ext4_try_merge_freed_extent(sbi, entry, new_entry,
5184                                             &(db->bb_free_root));
5185         }
5186
5187         node = rb_next(new_node);
5188         if (node) {
5189                 entry = rb_entry(node, struct ext4_free_data, efd_node);
5190                 ext4_try_merge_freed_extent(sbi, entry, new_entry,
5191                                             &(db->bb_free_root));
5192         }
5193
5194         spin_lock(&sbi->s_md_lock);
5195         list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
5196         sbi->s_mb_free_pending += clusters;
5197         spin_unlock(&sbi->s_md_lock);
5198         return 0;
5199 }
5200
5201 /*
5202  * Simple allocator for Ext4 fast commit replay path. It searches for blocks
5203  * linearly starting at the goal block and also excludes the blocks which
5204  * are going to be in use after fast commit replay.
5205  */
5206 static ext4_fsblk_t ext4_mb_new_blocks_simple(handle_t *handle,
5207                                 struct ext4_allocation_request *ar, int *errp)
5208 {
5209         struct buffer_head *bitmap_bh;
5210         struct super_block *sb = ar->inode->i_sb;
5211         ext4_group_t group;
5212         ext4_grpblk_t blkoff;
5213         ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
5214         ext4_grpblk_t i = 0;
5215         ext4_fsblk_t goal, block;
5216         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
5217
5218         goal = ar->goal;
5219         if (goal < le32_to_cpu(es->s_first_data_block) ||
5220                         goal >= ext4_blocks_count(es))
5221                 goal = le32_to_cpu(es->s_first_data_block);
5222
5223         ar->len = 0;
5224         ext4_get_group_no_and_offset(sb, goal, &group, &blkoff);
5225         for (; group < ext4_get_groups_count(sb); group++) {
5226                 bitmap_bh = ext4_read_block_bitmap(sb, group);
5227                 if (IS_ERR(bitmap_bh)) {
5228                         *errp = PTR_ERR(bitmap_bh);
5229                         pr_warn("Failed to read block bitmap\n");
5230                         return 0;
5231                 }
5232
5233                 ext4_get_group_no_and_offset(sb,
5234                         max(ext4_group_first_block_no(sb, group), goal),
5235                         NULL, &blkoff);
5236                 while (1) {
5237                         i = mb_find_next_zero_bit(bitmap_bh->b_data, max,
5238                                                 blkoff);
5239                         if (i >= max)
5240                                 break;
5241                         if (ext4_fc_replay_check_excluded(sb,
5242                                 ext4_group_first_block_no(sb, group) + i)) {
5243                                 blkoff = i + 1;
5244                         } else
5245                                 break;
5246                 }
5247                 brelse(bitmap_bh);
5248                 if (i < max)
5249                         break;
5250         }
5251
5252         if (group >= ext4_get_groups_count(sb) || i >= max) {
5253                 *errp = -ENOSPC;
5254                 return 0;
5255         }
5256
5257         block = ext4_group_first_block_no(sb, group) + i;
5258         ext4_mb_mark_bb(sb, block, 1, 1);
5259         ar->len = 1;
5260
5261         return block;
5262 }
5263
5264 static void ext4_free_blocks_simple(struct inode *inode, ext4_fsblk_t block,
5265                                         unsigned long count)
5266 {
5267         struct buffer_head *bitmap_bh;
5268         struct super_block *sb = inode->i_sb;
5269         struct ext4_group_desc *gdp;
5270         struct buffer_head *gdp_bh;
5271         ext4_group_t group;
5272         ext4_grpblk_t blkoff;
5273         int already_freed = 0, err, i;
5274
5275         ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
5276         bitmap_bh = ext4_read_block_bitmap(sb, group);
5277         if (IS_ERR(bitmap_bh)) {
5278                 err = PTR_ERR(bitmap_bh);
5279                 pr_warn("Failed to read block bitmap\n");
5280                 return;
5281         }
5282         gdp = ext4_get_group_desc(sb, group, &gdp_bh);
5283         if (!gdp)
5284                 return;
5285
5286         for (i = 0; i < count; i++) {
5287                 if (!mb_test_bit(blkoff + i, bitmap_bh->b_data))
5288                         already_freed++;
5289         }
5290         mb_clear_bits(bitmap_bh->b_data, blkoff, count);
5291         err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
5292         if (err)
5293                 return;
5294         ext4_free_group_clusters_set(
5295                 sb, gdp, ext4_free_group_clusters(sb, gdp) +
5296                 count - already_freed);
5297         ext4_block_bitmap_csum_set(sb, group, gdp, bitmap_bh);
5298         ext4_group_desc_csum_set(sb, group, gdp);
5299         ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
5300         sync_dirty_buffer(bitmap_bh);
5301         sync_dirty_buffer(gdp_bh);
5302         brelse(bitmap_bh);
5303 }
5304
5305 /**
5306  * ext4_free_blocks() -- Free given blocks and update quota
5307  * @handle:             handle for this transaction
5308  * @inode:              inode
5309  * @bh:                 optional buffer of the block to be freed
5310  * @block:              starting physical block to be freed
5311  * @count:              number of blocks to be freed
5312  * @flags:              flags used by ext4_free_blocks
5313  */
5314 void ext4_free_blocks(handle_t *handle, struct inode *inode,
5315                       struct buffer_head *bh, ext4_fsblk_t block,
5316                       unsigned long count, int flags)
5317 {
5318         struct buffer_head *bitmap_bh = NULL;
5319         struct super_block *sb = inode->i_sb;
5320         struct ext4_group_desc *gdp;
5321         unsigned int overflow;
5322         ext4_grpblk_t bit;
5323         struct buffer_head *gd_bh;
5324         ext4_group_t block_group;
5325         struct ext4_sb_info *sbi;
5326         struct ext4_buddy e4b;
5327         unsigned int count_clusters;
5328         int err = 0;
5329         int ret;
5330
5331         sbi = EXT4_SB(sb);
5332
5333         if (sbi->s_mount_state & EXT4_FC_REPLAY) {
5334                 ext4_free_blocks_simple(inode, block, count);
5335                 return;
5336         }
5337
5338         might_sleep();
5339         if (bh) {
5340                 if (block)
5341                         BUG_ON(block != bh->b_blocknr);
5342                 else
5343                         block = bh->b_blocknr;
5344         }
5345
5346         if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
5347             !ext4_inode_block_valid(inode, block, count)) {
5348                 ext4_error(sb, "Freeing blocks not in datazone - "
5349                            "block = %llu, count = %lu", block, count);
5350                 goto error_return;
5351         }
5352
5353         ext4_debug("freeing block %llu\n", block);
5354         trace_ext4_free_blocks(inode, block, count, flags);
5355
5356         if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
5357                 BUG_ON(count > 1);
5358
5359                 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
5360                             inode, bh, block);
5361         }
5362
5363         /*
5364          * If the extent to be freed does not begin on a cluster
5365          * boundary, we need to deal with partial clusters at the
5366          * beginning and end of the extent.  Normally we will free
5367          * blocks at the beginning or the end unless we are explicitly
5368          * requested to avoid doing so.
5369          */
5370         overflow = EXT4_PBLK_COFF(sbi, block);
5371         if (overflow) {
5372                 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
5373                         overflow = sbi->s_cluster_ratio - overflow;
5374                         block += overflow;
5375                         if (count > overflow)
5376                                 count -= overflow;
5377                         else
5378                                 return;
5379                 } else {
5380                         block -= overflow;
5381                         count += overflow;
5382                 }
5383         }
5384         overflow = EXT4_LBLK_COFF(sbi, count);
5385         if (overflow) {
5386                 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
5387                         if (count > overflow)
5388                                 count -= overflow;
5389                         else
5390                                 return;
5391                 } else
5392                         count += sbi->s_cluster_ratio - overflow;
5393         }
5394
5395         if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
5396                 int i;
5397                 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
5398
5399                 for (i = 0; i < count; i++) {
5400                         cond_resched();
5401                         if (is_metadata)
5402                                 bh = sb_find_get_block(inode->i_sb, block + i);
5403                         ext4_forget(handle, is_metadata, inode, bh, block + i);
5404                 }
5405         }
5406
5407 do_more:
5408         overflow = 0;
5409         ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5410
5411         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
5412                         ext4_get_group_info(sb, block_group))))
5413                 return;
5414
5415         /*
5416          * Check to see if we are freeing blocks across a group
5417          * boundary.
5418          */
5419         if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
5420                 overflow = EXT4_C2B(sbi, bit) + count -
5421                         EXT4_BLOCKS_PER_GROUP(sb);
5422                 count -= overflow;
5423         }
5424         count_clusters = EXT4_NUM_B2C(sbi, count);
5425         bitmap_bh = ext4_read_block_bitmap(sb, block_group);
5426         if (IS_ERR(bitmap_bh)) {
5427                 err = PTR_ERR(bitmap_bh);
5428                 bitmap_bh = NULL;
5429                 goto error_return;
5430         }
5431         gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
5432         if (!gdp) {
5433                 err = -EIO;
5434                 goto error_return;
5435         }
5436
5437         if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
5438             in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
5439             in_range(block, ext4_inode_table(sb, gdp),
5440                      sbi->s_itb_per_group) ||
5441             in_range(block + count - 1, ext4_inode_table(sb, gdp),
5442                      sbi->s_itb_per_group)) {
5443
5444                 ext4_error(sb, "Freeing blocks in system zone - "
5445                            "Block = %llu, count = %lu", block, count);
5446                 /* err = 0. ext4_std_error should be a no op */
5447                 goto error_return;
5448         }
5449
5450         BUFFER_TRACE(bitmap_bh, "getting write access");
5451         err = ext4_journal_get_write_access(handle, bitmap_bh);
5452         if (err)
5453                 goto error_return;
5454
5455         /*
5456          * We are about to modify some metadata.  Call the journal APIs
5457          * to unshare ->b_data if a currently-committing transaction is
5458          * using it
5459          */
5460         BUFFER_TRACE(gd_bh, "get_write_access");
5461         err = ext4_journal_get_write_access(handle, gd_bh);
5462         if (err)
5463                 goto error_return;
5464 #ifdef AGGRESSIVE_CHECK
5465         {
5466                 int i;
5467                 for (i = 0; i < count_clusters; i++)
5468                         BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
5469         }
5470 #endif
5471         trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
5472
5473         /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
5474         err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
5475                                      GFP_NOFS|__GFP_NOFAIL);
5476         if (err)
5477                 goto error_return;
5478
5479         /*
5480          * We need to make sure we don't reuse the freed block until after the
5481          * transaction is committed. We make an exception if the inode is to be
5482          * written in writeback mode since writeback mode has weak data
5483          * consistency guarantees.
5484          */
5485         if (ext4_handle_valid(handle) &&
5486             ((flags & EXT4_FREE_BLOCKS_METADATA) ||
5487              !ext4_should_writeback_data(inode))) {
5488                 struct ext4_free_data *new_entry;
5489                 /*
5490                  * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
5491                  * to fail.
5492                  */
5493                 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
5494                                 GFP_NOFS|__GFP_NOFAIL);
5495                 new_entry->efd_start_cluster = bit;
5496                 new_entry->efd_group = block_group;
5497                 new_entry->efd_count = count_clusters;
5498                 new_entry->efd_tid = handle->h_transaction->t_tid;
5499
5500                 ext4_lock_group(sb, block_group);
5501                 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
5502                 ext4_mb_free_metadata(handle, &e4b, new_entry);
5503         } else {
5504                 /* need to update group_info->bb_free and bitmap
5505                  * with group lock held. generate_buddy look at
5506                  * them with group lock_held
5507                  */
5508                 if (test_opt(sb, DISCARD)) {
5509                         err = ext4_issue_discard(sb, block_group, bit, count,
5510                                                  NULL);
5511                         if (err && err != -EOPNOTSUPP)
5512                                 ext4_msg(sb, KERN_WARNING, "discard request in"
5513                                          " group:%d block:%d count:%lu failed"
5514                                          " with %d", block_group, bit, count,
5515                                          err);
5516                 } else
5517                         EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
5518
5519                 ext4_lock_group(sb, block_group);
5520                 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
5521                 mb_free_blocks(inode, &e4b, bit, count_clusters);
5522         }
5523
5524         ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
5525         ext4_free_group_clusters_set(sb, gdp, ret);
5526         ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
5527         ext4_group_desc_csum_set(sb, block_group, gdp);
5528         ext4_unlock_group(sb, block_group);
5529
5530         if (sbi->s_log_groups_per_flex) {
5531                 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5532                 atomic64_add(count_clusters,
5533                              &sbi_array_rcu_deref(sbi, s_flex_groups,
5534                                                   flex_group)->free_clusters);
5535         }
5536
5537         /*
5538          * on a bigalloc file system, defer the s_freeclusters_counter
5539          * update to the caller (ext4_remove_space and friends) so they
5540          * can determine if a cluster freed here should be rereserved
5541          */
5542         if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
5543                 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
5544                         dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
5545                 percpu_counter_add(&sbi->s_freeclusters_counter,
5546                                    count_clusters);
5547         }
5548
5549         ext4_mb_unload_buddy(&e4b);
5550
5551         /* We dirtied the bitmap block */
5552         BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5553         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5554
5555         /* And the group descriptor block */
5556         BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5557         ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5558         if (!err)
5559                 err = ret;
5560
5561         if (overflow && !err) {
5562                 block += count;
5563                 count = overflow;
5564                 put_bh(bitmap_bh);
5565                 goto do_more;
5566         }
5567 error_return:
5568         brelse(bitmap_bh);
5569         ext4_std_error(sb, err);
5570         return;
5571 }
5572
5573 /**
5574  * ext4_group_add_blocks() -- Add given blocks to an existing group
5575  * @handle:                     handle to this transaction
5576  * @sb:                         super block
5577  * @block:                      start physical block to add to the block group
5578  * @count:                      number of blocks to free
5579  *
5580  * This marks the blocks as free in the bitmap and buddy.
5581  */
5582 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
5583                          ext4_fsblk_t block, unsigned long count)
5584 {
5585         struct buffer_head *bitmap_bh = NULL;
5586         struct buffer_head *gd_bh;
5587         ext4_group_t block_group;
5588         ext4_grpblk_t bit;
5589         unsigned int i;
5590         struct ext4_group_desc *desc;
5591         struct ext4_sb_info *sbi = EXT4_SB(sb);
5592         struct ext4_buddy e4b;
5593         int err = 0, ret, free_clusters_count;
5594         ext4_grpblk_t clusters_freed;
5595         ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
5596         ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
5597         unsigned long cluster_count = last_cluster - first_cluster + 1;
5598
5599         ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
5600
5601         if (count == 0)
5602                 return 0;
5603
5604         ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5605         /*
5606          * Check to see if we are freeing blocks across a group
5607          * boundary.
5608          */
5609         if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
5610                 ext4_warning(sb, "too many blocks added to group %u",
5611                              block_group);
5612                 err = -EINVAL;
5613                 goto error_return;
5614         }
5615
5616         bitmap_bh = ext4_read_block_bitmap(sb, block_group);
5617         if (IS_ERR(bitmap_bh)) {
5618                 err = PTR_ERR(bitmap_bh);
5619                 bitmap_bh = NULL;
5620                 goto error_return;
5621         }
5622
5623         desc = ext4_get_group_desc(sb, block_group, &gd_bh);
5624         if (!desc) {
5625                 err = -EIO;
5626                 goto error_return;
5627         }
5628
5629         if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
5630             in_range(ext4_inode_bitmap(sb, desc), block, count) ||
5631             in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
5632             in_range(block + count - 1, ext4_inode_table(sb, desc),
5633                      sbi->s_itb_per_group)) {
5634                 ext4_error(sb, "Adding blocks in system zones - "
5635                            "Block = %llu, count = %lu",
5636                            block, count);
5637                 err = -EINVAL;
5638                 goto error_return;
5639         }
5640
5641         BUFFER_TRACE(bitmap_bh, "getting write access");
5642         err = ext4_journal_get_write_access(handle, bitmap_bh);
5643         if (err)
5644                 goto error_return;
5645
5646         /*
5647          * We are about to modify some metadata.  Call the journal APIs
5648          * to unshare ->b_data if a currently-committing transaction is
5649          * using it
5650          */
5651         BUFFER_TRACE(gd_bh, "get_write_access");
5652         err = ext4_journal_get_write_access(handle, gd_bh);
5653         if (err)
5654                 goto error_return;
5655
5656         for (i = 0, clusters_freed = 0; i < cluster_count; i++) {
5657                 BUFFER_TRACE(bitmap_bh, "clear bit");
5658                 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
5659                         ext4_error(sb, "bit already cleared for block %llu",
5660                                    (ext4_fsblk_t)(block + i));
5661                         BUFFER_TRACE(bitmap_bh, "bit already cleared");
5662                 } else {
5663                         clusters_freed++;
5664                 }
5665         }
5666
5667         err = ext4_mb_load_buddy(sb, block_group, &e4b);
5668         if (err)
5669                 goto error_return;
5670
5671         /*
5672          * need to update group_info->bb_free and bitmap
5673          * with group lock held. generate_buddy look at
5674          * them with group lock_held
5675          */
5676         ext4_lock_group(sb, block_group);
5677         mb_clear_bits(bitmap_bh->b_data, bit, cluster_count);
5678         mb_free_blocks(NULL, &e4b, bit, cluster_count);
5679         free_clusters_count = clusters_freed +
5680                 ext4_free_group_clusters(sb, desc);
5681         ext4_free_group_clusters_set(sb, desc, free_clusters_count);
5682         ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
5683         ext4_group_desc_csum_set(sb, block_group, desc);
5684         ext4_unlock_group(sb, block_group);
5685         percpu_counter_add(&sbi->s_freeclusters_counter,
5686                            clusters_freed);
5687
5688         if (sbi->s_log_groups_per_flex) {
5689                 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5690                 atomic64_add(clusters_freed,
5691                              &sbi_array_rcu_deref(sbi, s_flex_groups,
5692                                                   flex_group)->free_clusters);
5693         }
5694
5695         ext4_mb_unload_buddy(&e4b);
5696
5697         /* We dirtied the bitmap block */
5698         BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5699         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5700
5701         /* And the group descriptor block */
5702         BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5703         ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5704         if (!err)
5705                 err = ret;
5706
5707 error_return:
5708         brelse(bitmap_bh);
5709         ext4_std_error(sb, err);
5710         return err;
5711 }
5712
5713 /**
5714  * ext4_trim_extent -- function to TRIM one single free extent in the group
5715  * @sb:         super block for the file system
5716  * @start:      starting block of the free extent in the alloc. group
5717  * @count:      number of blocks to TRIM
5718  * @group:      alloc. group we are working with
5719  * @e4b:        ext4 buddy for the group
5720  *
5721  * Trim "count" blocks starting at "start" in the "group". To assure that no
5722  * one will allocate those blocks, mark it as used in buddy bitmap. This must
5723  * be called with under the group lock.
5724  */
5725 static int ext4_trim_extent(struct super_block *sb, int start, int count,
5726                              ext4_group_t group, struct ext4_buddy *e4b)
5727 __releases(bitlock)
5728 __acquires(bitlock)
5729 {
5730         struct ext4_free_extent ex;
5731         int ret = 0;
5732
5733         trace_ext4_trim_extent(sb, group, start, count);
5734
5735         assert_spin_locked(ext4_group_lock_ptr(sb, group));
5736
5737         ex.fe_start = start;
5738         ex.fe_group = group;
5739         ex.fe_len = count;
5740
5741         /*
5742          * Mark blocks used, so no one can reuse them while
5743          * being trimmed.
5744          */
5745         mb_mark_used(e4b, &ex);
5746         ext4_unlock_group(sb, group);
5747         ret = ext4_issue_discard(sb, group, start, count, NULL);
5748         ext4_lock_group(sb, group);
5749         mb_free_blocks(NULL, e4b, start, ex.fe_len);
5750         return ret;
5751 }
5752
5753 /**
5754  * ext4_trim_all_free -- function to trim all free space in alloc. group
5755  * @sb:                 super block for file system
5756  * @group:              group to be trimmed
5757  * @start:              first group block to examine
5758  * @max:                last group block to examine
5759  * @minblocks:          minimum extent block count
5760  *
5761  * ext4_trim_all_free walks through group's buddy bitmap searching for free
5762  * extents. When the free block is found, ext4_trim_extent is called to TRIM
5763  * the extent.
5764  *
5765  *
5766  * ext4_trim_all_free walks through group's block bitmap searching for free
5767  * extents. When the free extent is found, mark it as used in group buddy
5768  * bitmap. Then issue a TRIM command on this extent and free the extent in
5769  * the group buddy bitmap. This is done until whole group is scanned.
5770  */
5771 static ext4_grpblk_t
5772 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
5773                    ext4_grpblk_t start, ext4_grpblk_t max,
5774                    ext4_grpblk_t minblocks)
5775 {
5776         void *bitmap;
5777         ext4_grpblk_t next, count = 0, free_count = 0;
5778         struct ext4_buddy e4b;
5779         int ret = 0;
5780
5781         trace_ext4_trim_all_free(sb, group, start, max);
5782
5783         ret = ext4_mb_load_buddy(sb, group, &e4b);
5784         if (ret) {
5785                 ext4_warning(sb, "Error %d loading buddy information for %u",
5786                              ret, group);
5787                 return ret;
5788         }
5789         bitmap = e4b.bd_bitmap;
5790
5791         ext4_lock_group(sb, group);
5792         if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
5793             minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
5794                 goto out;
5795
5796         start = (e4b.bd_info->bb_first_free > start) ?
5797                 e4b.bd_info->bb_first_free : start;
5798
5799         while (start <= max) {
5800                 start = mb_find_next_zero_bit(bitmap, max + 1, start);
5801                 if (start > max)
5802                         break;
5803                 next = mb_find_next_bit(bitmap, max + 1, start);
5804
5805                 if ((next - start) >= minblocks) {
5806                         ret = ext4_trim_extent(sb, start,
5807                                                next - start, group, &e4b);
5808                         if (ret && ret != -EOPNOTSUPP)
5809                                 break;
5810                         ret = 0;
5811                         count += next - start;
5812                 }
5813                 free_count += next - start;
5814                 start = next + 1;
5815
5816                 if (fatal_signal_pending(current)) {
5817                         count = -ERESTARTSYS;
5818                         break;
5819                 }
5820
5821                 if (need_resched()) {
5822                         ext4_unlock_group(sb, group);
5823                         cond_resched();
5824                         ext4_lock_group(sb, group);
5825                 }
5826
5827                 if ((e4b.bd_info->bb_free - free_count) < minblocks)
5828                         break;
5829         }
5830
5831         if (!ret) {
5832                 ret = count;
5833                 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
5834         }
5835 out:
5836         ext4_unlock_group(sb, group);
5837         ext4_mb_unload_buddy(&e4b);
5838
5839         ext4_debug("trimmed %d blocks in the group %d\n",
5840                 count, group);
5841
5842         return ret;
5843 }
5844
5845 /**
5846  * ext4_trim_fs() -- trim ioctl handle function
5847  * @sb:                 superblock for filesystem
5848  * @range:              fstrim_range structure
5849  *
5850  * start:       First Byte to trim
5851  * len:         number of Bytes to trim from start
5852  * minlen:      minimum extent length in Bytes
5853  * ext4_trim_fs goes through all allocation groups containing Bytes from
5854  * start to start+len. For each such a group ext4_trim_all_free function
5855  * is invoked to trim all free space.
5856  */
5857 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
5858 {
5859         struct request_queue *q = bdev_get_queue(sb->s_bdev);
5860         struct ext4_group_info *grp;
5861         ext4_group_t group, first_group, last_group;
5862         ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5863         uint64_t start, end, minlen, trimmed = 0;
5864         ext4_fsblk_t first_data_blk =
5865                         le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5866         ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
5867         int ret = 0;
5868
5869         start = range->start >> sb->s_blocksize_bits;
5870         end = start + (range->len >> sb->s_blocksize_bits) - 1;
5871         minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5872                               range->minlen >> sb->s_blocksize_bits);
5873
5874         if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
5875             start >= max_blks ||
5876             range->len < sb->s_blocksize)
5877                 return -EINVAL;
5878         /* No point to try to trim less than discard granularity */
5879         if (range->minlen < q->limits.discard_granularity) {
5880                 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5881                         q->limits.discard_granularity >> sb->s_blocksize_bits);
5882                 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
5883                         goto out;
5884         }
5885         if (end >= max_blks)
5886                 end = max_blks - 1;
5887         if (end <= first_data_blk)
5888                 goto out;
5889         if (start < first_data_blk)
5890                 start = first_data_blk;
5891
5892         /* Determine first and last group to examine based on start and end */
5893         ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
5894                                      &first_group, &first_cluster);
5895         ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
5896                                      &last_group, &last_cluster);
5897
5898         /* end now represents the last cluster to discard in this group */
5899         end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5900
5901         for (group = first_group; group <= last_group; group++) {
5902                 grp = ext4_get_group_info(sb, group);
5903                 /* We only do this if the grp has never been initialized */
5904                 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
5905                         ret = ext4_mb_init_group(sb, group, GFP_NOFS);
5906                         if (ret)
5907                                 break;
5908                 }
5909
5910                 /*
5911                  * For all the groups except the last one, last cluster will
5912                  * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
5913                  * change it for the last group, note that last_cluster is
5914                  * already computed earlier by ext4_get_group_no_and_offset()
5915                  */
5916                 if (group == last_group)
5917                         end = last_cluster;
5918
5919                 if (grp->bb_free >= minlen) {
5920                         cnt = ext4_trim_all_free(sb, group, first_cluster,
5921                                                 end, minlen);
5922                         if (cnt < 0) {
5923                                 ret = cnt;
5924                                 break;
5925                         }
5926                         trimmed += cnt;
5927                 }
5928
5929                 /*
5930                  * For every group except the first one, we are sure
5931                  * that the first cluster to discard will be cluster #0.
5932                  */
5933                 first_cluster = 0;
5934         }
5935
5936         if (!ret)
5937                 atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
5938
5939 out:
5940         range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
5941         return ret;
5942 }
5943
5944 /* Iterate all the free extents in the group. */
5945 int
5946 ext4_mballoc_query_range(
5947         struct super_block              *sb,
5948         ext4_group_t                    group,
5949         ext4_grpblk_t                   start,
5950         ext4_grpblk_t                   end,
5951         ext4_mballoc_query_range_fn     formatter,
5952         void                            *priv)
5953 {
5954         void                            *bitmap;
5955         ext4_grpblk_t                   next;
5956         struct ext4_buddy               e4b;
5957         int                             error;
5958
5959         error = ext4_mb_load_buddy(sb, group, &e4b);
5960         if (error)
5961                 return error;
5962         bitmap = e4b.bd_bitmap;
5963
5964         ext4_lock_group(sb, group);
5965
5966         start = (e4b.bd_info->bb_first_free > start) ?
5967                 e4b.bd_info->bb_first_free : start;
5968         if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
5969                 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5970
5971         while (start <= end) {
5972                 start = mb_find_next_zero_bit(bitmap, end + 1, start);
5973                 if (start > end)
5974                         break;
5975                 next = mb_find_next_bit(bitmap, end + 1, start);
5976
5977                 ext4_unlock_group(sb, group);
5978                 error = formatter(sb, group, start, next - start, priv);
5979                 if (error)
5980                         goto out_unload;
5981                 ext4_lock_group(sb, group);
5982
5983                 start = next + 1;
5984         }
5985
5986         ext4_unlock_group(sb, group);
5987 out_unload:
5988         ext4_mb_unload_buddy(&e4b);
5989
5990         return error;
5991 }