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