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