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