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