ext4: Make the length of the mb_history file tunable
[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                 if (sbi->s_mb_history_max)
2417                         remove_proc_entry("mb_history", sbi->s_proc);
2418         }
2419         kfree(sbi->s_mb_history);
2420 }
2421
2422 static void ext4_mb_history_init(struct super_block *sb)
2423 {
2424         struct ext4_sb_info *sbi = EXT4_SB(sb);
2425         int i;
2426
2427         if (sbi->s_proc != NULL) {
2428                 if (sbi->s_mb_history_max)
2429                         proc_create_data("mb_history", S_IRUGO, sbi->s_proc,
2430                                          &ext4_mb_seq_history_fops, sb);
2431                 proc_create_data("mb_groups", S_IRUGO, sbi->s_proc,
2432                                  &ext4_mb_seq_groups_fops, sb);
2433         }
2434
2435         sbi->s_mb_history_cur = 0;
2436         spin_lock_init(&sbi->s_mb_history_lock);
2437         i = sbi->s_mb_history_max * sizeof(struct ext4_mb_history);
2438         sbi->s_mb_history = i ? kzalloc(i, GFP_KERNEL) : NULL;
2439         /* if we can't allocate history, then we simple won't use it */
2440 }
2441
2442 static noinline_for_stack void
2443 ext4_mb_store_history(struct ext4_allocation_context *ac)
2444 {
2445         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2446         struct ext4_mb_history h;
2447
2448         if (sbi->s_mb_history == NULL)
2449                 return;
2450
2451         if (!(ac->ac_op & sbi->s_mb_history_filter))
2452                 return;
2453
2454         h.op = ac->ac_op;
2455         h.pid = current->pid;
2456         h.ino = ac->ac_inode ? ac->ac_inode->i_ino : 0;
2457         h.orig = ac->ac_o_ex;
2458         h.result = ac->ac_b_ex;
2459         h.flags = ac->ac_flags;
2460         h.found = ac->ac_found;
2461         h.groups = ac->ac_groups_scanned;
2462         h.cr = ac->ac_criteria;
2463         h.tail = ac->ac_tail;
2464         h.buddy = ac->ac_buddy;
2465         h.merged = 0;
2466         if (ac->ac_op == EXT4_MB_HISTORY_ALLOC) {
2467                 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
2468                                 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
2469                         h.merged = 1;
2470                 h.goal = ac->ac_g_ex;
2471                 h.result = ac->ac_f_ex;
2472         }
2473
2474         spin_lock(&sbi->s_mb_history_lock);
2475         memcpy(sbi->s_mb_history + sbi->s_mb_history_cur, &h, sizeof(h));
2476         if (++sbi->s_mb_history_cur >= sbi->s_mb_history_max)
2477                 sbi->s_mb_history_cur = 0;
2478         spin_unlock(&sbi->s_mb_history_lock);
2479 }
2480
2481 #else
2482 #define ext4_mb_history_release(sb)
2483 #define ext4_mb_history_init(sb)
2484 #endif
2485
2486
2487 /* Create and initialize ext4_group_info data for the given group. */
2488 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2489                           struct ext4_group_desc *desc)
2490 {
2491         int i, len;
2492         int metalen = 0;
2493         struct ext4_sb_info *sbi = EXT4_SB(sb);
2494         struct ext4_group_info **meta_group_info;
2495
2496         /*
2497          * First check if this group is the first of a reserved block.
2498          * If it's true, we have to allocate a new table of pointers
2499          * to ext4_group_info structures
2500          */
2501         if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2502                 metalen = sizeof(*meta_group_info) <<
2503                         EXT4_DESC_PER_BLOCK_BITS(sb);
2504                 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2505                 if (meta_group_info == NULL) {
2506                         printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2507                                "buddy group\n");
2508                         goto exit_meta_group_info;
2509                 }
2510                 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] =
2511                         meta_group_info;
2512         }
2513
2514         /*
2515          * calculate needed size. if change bb_counters size,
2516          * don't forget about ext4_mb_generate_buddy()
2517          */
2518         len = offsetof(typeof(**meta_group_info),
2519                        bb_counters[sb->s_blocksize_bits + 2]);
2520
2521         meta_group_info =
2522                 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)];
2523         i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2524
2525         meta_group_info[i] = kzalloc(len, GFP_KERNEL);
2526         if (meta_group_info[i] == NULL) {
2527                 printk(KERN_ERR "EXT4-fs: can't allocate buddy mem\n");
2528                 goto exit_group_info;
2529         }
2530         set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2531                 &(meta_group_info[i]->bb_state));
2532
2533         /*
2534          * initialize bb_free to be able to skip
2535          * empty groups without initialization
2536          */
2537         if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2538                 meta_group_info[i]->bb_free =
2539                         ext4_free_blocks_after_init(sb, group, desc);
2540         } else {
2541                 meta_group_info[i]->bb_free =
2542                         ext4_free_blks_count(sb, desc);
2543         }
2544
2545         INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2546         init_rwsem(&meta_group_info[i]->alloc_sem);
2547         meta_group_info[i]->bb_free_root.rb_node = NULL;;
2548
2549 #ifdef DOUBLE_CHECK
2550         {
2551                 struct buffer_head *bh;
2552                 meta_group_info[i]->bb_bitmap =
2553                         kmalloc(sb->s_blocksize, GFP_KERNEL);
2554                 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2555                 bh = ext4_read_block_bitmap(sb, group);
2556                 BUG_ON(bh == NULL);
2557                 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2558                         sb->s_blocksize);
2559                 put_bh(bh);
2560         }
2561 #endif
2562
2563         return 0;
2564
2565 exit_group_info:
2566         /* If a meta_group_info table has been allocated, release it now */
2567         if (group % EXT4_DESC_PER_BLOCK(sb) == 0)
2568                 kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
2569 exit_meta_group_info:
2570         return -ENOMEM;
2571 } /* ext4_mb_add_groupinfo */
2572
2573 /*
2574  * Update an existing group.
2575  * This function is used for online resize
2576  */
2577 void ext4_mb_update_group_info(struct ext4_group_info *grp, ext4_grpblk_t add)
2578 {
2579         grp->bb_free += add;
2580 }
2581
2582 static int ext4_mb_init_backend(struct super_block *sb)
2583 {
2584         ext4_group_t ngroups = ext4_get_groups_count(sb);
2585         ext4_group_t i;
2586         int metalen;
2587         struct ext4_sb_info *sbi = EXT4_SB(sb);
2588         struct ext4_super_block *es = sbi->s_es;
2589         int num_meta_group_infos;
2590         int num_meta_group_infos_max;
2591         int array_size;
2592         struct ext4_group_info **meta_group_info;
2593         struct ext4_group_desc *desc;
2594
2595         /* This is the number of blocks used by GDT */
2596         num_meta_group_infos = (ngroups + EXT4_DESC_PER_BLOCK(sb) -
2597                                 1) >> EXT4_DESC_PER_BLOCK_BITS(sb);
2598
2599         /*
2600          * This is the total number of blocks used by GDT including
2601          * the number of reserved blocks for GDT.
2602          * The s_group_info array is allocated with this value
2603          * to allow a clean online resize without a complex
2604          * manipulation of pointer.
2605          * The drawback is the unused memory when no resize
2606          * occurs but it's very low in terms of pages
2607          * (see comments below)
2608          * Need to handle this properly when META_BG resizing is allowed
2609          */
2610         num_meta_group_infos_max = num_meta_group_infos +
2611                                 le16_to_cpu(es->s_reserved_gdt_blocks);
2612
2613         /*
2614          * array_size is the size of s_group_info array. We round it
2615          * to the next power of two because this approximation is done
2616          * internally by kmalloc so we can have some more memory
2617          * for free here (e.g. may be used for META_BG resize).
2618          */
2619         array_size = 1;
2620         while (array_size < sizeof(*sbi->s_group_info) *
2621                num_meta_group_infos_max)
2622                 array_size = array_size << 1;
2623         /* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2624          * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2625          * So a two level scheme suffices for now. */
2626         sbi->s_group_info = kmalloc(array_size, GFP_KERNEL);
2627         if (sbi->s_group_info == NULL) {
2628                 printk(KERN_ERR "EXT4-fs: can't allocate buddy meta group\n");
2629                 return -ENOMEM;
2630         }
2631         sbi->s_buddy_cache = new_inode(sb);
2632         if (sbi->s_buddy_cache == NULL) {
2633                 printk(KERN_ERR "EXT4-fs: can't get new inode\n");
2634                 goto err_freesgi;
2635         }
2636         EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2637
2638         metalen = sizeof(*meta_group_info) << EXT4_DESC_PER_BLOCK_BITS(sb);
2639         for (i = 0; i < num_meta_group_infos; i++) {
2640                 if ((i + 1) == num_meta_group_infos)
2641                         metalen = sizeof(*meta_group_info) *
2642                                 (ngroups -
2643                                         (i << EXT4_DESC_PER_BLOCK_BITS(sb)));
2644                 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2645                 if (meta_group_info == NULL) {
2646                         printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2647                                "buddy group\n");
2648                         goto err_freemeta;
2649                 }
2650                 sbi->s_group_info[i] = meta_group_info;
2651         }
2652
2653         for (i = 0; i < ngroups; i++) {
2654                 desc = ext4_get_group_desc(sb, i, NULL);
2655                 if (desc == NULL) {
2656                         printk(KERN_ERR
2657                                 "EXT4-fs: can't read descriptor %u\n", i);
2658                         goto err_freebuddy;
2659                 }
2660                 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2661                         goto err_freebuddy;
2662         }
2663
2664         return 0;
2665
2666 err_freebuddy:
2667         while (i-- > 0)
2668                 kfree(ext4_get_group_info(sb, i));
2669         i = num_meta_group_infos;
2670 err_freemeta:
2671         while (i-- > 0)
2672                 kfree(sbi->s_group_info[i]);
2673         iput(sbi->s_buddy_cache);
2674 err_freesgi:
2675         kfree(sbi->s_group_info);
2676         return -ENOMEM;
2677 }
2678
2679 int ext4_mb_init(struct super_block *sb, int needs_recovery)
2680 {
2681         struct ext4_sb_info *sbi = EXT4_SB(sb);
2682         unsigned i, j;
2683         unsigned offset;
2684         unsigned max;
2685         int ret;
2686
2687         i = (sb->s_blocksize_bits + 2) * sizeof(unsigned short);
2688
2689         sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2690         if (sbi->s_mb_offsets == NULL) {
2691                 return -ENOMEM;
2692         }
2693
2694         i = (sb->s_blocksize_bits + 2) * sizeof(unsigned int);
2695         sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2696         if (sbi->s_mb_maxs == NULL) {
2697                 kfree(sbi->s_mb_offsets);
2698                 return -ENOMEM;
2699         }
2700
2701         /* order 0 is regular bitmap */
2702         sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2703         sbi->s_mb_offsets[0] = 0;
2704
2705         i = 1;
2706         offset = 0;
2707         max = sb->s_blocksize << 2;
2708         do {
2709                 sbi->s_mb_offsets[i] = offset;
2710                 sbi->s_mb_maxs[i] = max;
2711                 offset += 1 << (sb->s_blocksize_bits - i);
2712                 max = max >> 1;
2713                 i++;
2714         } while (i <= sb->s_blocksize_bits + 1);
2715
2716         /* init file for buddy data */
2717         ret = ext4_mb_init_backend(sb);
2718         if (ret != 0) {
2719                 kfree(sbi->s_mb_offsets);
2720                 kfree(sbi->s_mb_maxs);
2721                 return ret;
2722         }
2723
2724         spin_lock_init(&sbi->s_md_lock);
2725         spin_lock_init(&sbi->s_bal_lock);
2726
2727         sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2728         sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2729         sbi->s_mb_stats = MB_DEFAULT_STATS;
2730         sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2731         sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2732         sbi->s_mb_history_filter = EXT4_MB_HISTORY_DEFAULT;
2733         sbi->s_mb_group_prealloc = MB_DEFAULT_GROUP_PREALLOC;
2734
2735         sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2736         if (sbi->s_locality_groups == NULL) {
2737                 kfree(sbi->s_mb_offsets);
2738                 kfree(sbi->s_mb_maxs);
2739                 return -ENOMEM;
2740         }
2741         for_each_possible_cpu(i) {
2742                 struct ext4_locality_group *lg;
2743                 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2744                 mutex_init(&lg->lg_mutex);
2745                 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2746                         INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2747                 spin_lock_init(&lg->lg_prealloc_lock);
2748         }
2749
2750         ext4_mb_history_init(sb);
2751
2752         if (sbi->s_journal)
2753                 sbi->s_journal->j_commit_callback = release_blocks_on_commit;
2754
2755         printk(KERN_INFO "EXT4-fs: mballoc enabled\n");
2756         return 0;
2757 }
2758
2759 /* need to called with ext4 group lock (ext4_lock_group) */
2760 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2761 {
2762         struct ext4_prealloc_space *pa;
2763         struct list_head *cur, *tmp;
2764         int count = 0;
2765
2766         list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2767                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2768                 list_del(&pa->pa_group_list);
2769                 count++;
2770                 kmem_cache_free(ext4_pspace_cachep, pa);
2771         }
2772         if (count)
2773                 mb_debug("mballoc: %u PAs left\n", count);
2774
2775 }
2776
2777 int ext4_mb_release(struct super_block *sb)
2778 {
2779         ext4_group_t ngroups = ext4_get_groups_count(sb);
2780         ext4_group_t i;
2781         int num_meta_group_infos;
2782         struct ext4_group_info *grinfo;
2783         struct ext4_sb_info *sbi = EXT4_SB(sb);
2784
2785         if (sbi->s_group_info) {
2786                 for (i = 0; i < ngroups; i++) {
2787                         grinfo = ext4_get_group_info(sb, i);
2788 #ifdef DOUBLE_CHECK
2789                         kfree(grinfo->bb_bitmap);
2790 #endif
2791                         ext4_lock_group(sb, i);
2792                         ext4_mb_cleanup_pa(grinfo);
2793                         ext4_unlock_group(sb, i);
2794                         kfree(grinfo);
2795                 }
2796                 num_meta_group_infos = (ngroups +
2797                                 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2798                         EXT4_DESC_PER_BLOCK_BITS(sb);
2799                 for (i = 0; i < num_meta_group_infos; i++)
2800                         kfree(sbi->s_group_info[i]);
2801                 kfree(sbi->s_group_info);
2802         }
2803         kfree(sbi->s_mb_offsets);
2804         kfree(sbi->s_mb_maxs);
2805         if (sbi->s_buddy_cache)
2806                 iput(sbi->s_buddy_cache);
2807         if (sbi->s_mb_stats) {
2808                 printk(KERN_INFO
2809                        "EXT4-fs: mballoc: %u blocks %u reqs (%u success)\n",
2810                                 atomic_read(&sbi->s_bal_allocated),
2811                                 atomic_read(&sbi->s_bal_reqs),
2812                                 atomic_read(&sbi->s_bal_success));
2813                 printk(KERN_INFO
2814                       "EXT4-fs: mballoc: %u extents scanned, %u goal hits, "
2815                                 "%u 2^N hits, %u breaks, %u lost\n",
2816                                 atomic_read(&sbi->s_bal_ex_scanned),
2817                                 atomic_read(&sbi->s_bal_goals),
2818                                 atomic_read(&sbi->s_bal_2orders),
2819                                 atomic_read(&sbi->s_bal_breaks),
2820                                 atomic_read(&sbi->s_mb_lost_chunks));
2821                 printk(KERN_INFO
2822                        "EXT4-fs: mballoc: %lu generated and it took %Lu\n",
2823                                 sbi->s_mb_buddies_generated++,
2824                                 sbi->s_mb_generation_time);
2825                 printk(KERN_INFO
2826                        "EXT4-fs: mballoc: %u preallocated, %u discarded\n",
2827                                 atomic_read(&sbi->s_mb_preallocated),
2828                                 atomic_read(&sbi->s_mb_discarded));
2829         }
2830
2831         free_percpu(sbi->s_locality_groups);
2832         ext4_mb_history_release(sb);
2833
2834         return 0;
2835 }
2836
2837 /*
2838  * This function is called by the jbd2 layer once the commit has finished,
2839  * so we know we can free the blocks that were released with that commit.
2840  */
2841 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn)
2842 {
2843         struct super_block *sb = journal->j_private;
2844         struct ext4_buddy e4b;
2845         struct ext4_group_info *db;
2846         int err, count = 0, count2 = 0;
2847         struct ext4_free_data *entry;
2848         ext4_fsblk_t discard_block;
2849         struct list_head *l, *ltmp;
2850
2851         list_for_each_safe(l, ltmp, &txn->t_private_list) {
2852                 entry = list_entry(l, struct ext4_free_data, list);
2853
2854                 mb_debug("gonna free %u blocks in group %u (0x%p):",
2855                          entry->count, entry->group, entry);
2856
2857                 err = ext4_mb_load_buddy(sb, entry->group, &e4b);
2858                 /* we expect to find existing buddy because it's pinned */
2859                 BUG_ON(err != 0);
2860
2861                 db = e4b.bd_info;
2862                 /* there are blocks to put in buddy to make them really free */
2863                 count += entry->count;
2864                 count2++;
2865                 ext4_lock_group(sb, entry->group);
2866                 /* Take it out of per group rb tree */
2867                 rb_erase(&entry->node, &(db->bb_free_root));
2868                 mb_free_blocks(NULL, &e4b, entry->start_blk, entry->count);
2869
2870                 if (!db->bb_free_root.rb_node) {
2871                         /* No more items in the per group rb tree
2872                          * balance refcounts from ext4_mb_free_metadata()
2873                          */
2874                         page_cache_release(e4b.bd_buddy_page);
2875                         page_cache_release(e4b.bd_bitmap_page);
2876                 }
2877                 ext4_unlock_group(sb, entry->group);
2878                 discard_block = (ext4_fsblk_t) entry->group * EXT4_BLOCKS_PER_GROUP(sb)
2879                         + entry->start_blk
2880                         + le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
2881                 trace_mark(ext4_discard_blocks, "dev %s blk %llu count %u",
2882                            sb->s_id, (unsigned long long) discard_block,
2883                            entry->count);
2884                 sb_issue_discard(sb, discard_block, entry->count);
2885
2886                 kmem_cache_free(ext4_free_ext_cachep, entry);
2887                 ext4_mb_release_desc(&e4b);
2888         }
2889
2890         mb_debug("freed %u blocks in %u structures\n", count, count2);
2891 }
2892
2893 int __init init_ext4_mballoc(void)
2894 {
2895         ext4_pspace_cachep =
2896                 kmem_cache_create("ext4_prealloc_space",
2897                                      sizeof(struct ext4_prealloc_space),
2898                                      0, SLAB_RECLAIM_ACCOUNT, NULL);
2899         if (ext4_pspace_cachep == NULL)
2900                 return -ENOMEM;
2901
2902         ext4_ac_cachep =
2903                 kmem_cache_create("ext4_alloc_context",
2904                                      sizeof(struct ext4_allocation_context),
2905                                      0, SLAB_RECLAIM_ACCOUNT, NULL);
2906         if (ext4_ac_cachep == NULL) {
2907                 kmem_cache_destroy(ext4_pspace_cachep);
2908                 return -ENOMEM;
2909         }
2910
2911         ext4_free_ext_cachep =
2912                 kmem_cache_create("ext4_free_block_extents",
2913                                      sizeof(struct ext4_free_data),
2914                                      0, SLAB_RECLAIM_ACCOUNT, NULL);
2915         if (ext4_free_ext_cachep == NULL) {
2916                 kmem_cache_destroy(ext4_pspace_cachep);
2917                 kmem_cache_destroy(ext4_ac_cachep);
2918                 return -ENOMEM;
2919         }
2920         return 0;
2921 }
2922
2923 void exit_ext4_mballoc(void)
2924 {
2925         /* XXX: synchronize_rcu(); */
2926         kmem_cache_destroy(ext4_pspace_cachep);
2927         kmem_cache_destroy(ext4_ac_cachep);
2928         kmem_cache_destroy(ext4_free_ext_cachep);
2929 }
2930
2931
2932 /*
2933  * Check quota and mark choosed space (ac->ac_b_ex) non-free in bitmaps
2934  * Returns 0 if success or error code
2935  */
2936 static noinline_for_stack int
2937 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2938                                 handle_t *handle, unsigned int reserv_blks)
2939 {
2940         struct buffer_head *bitmap_bh = NULL;
2941         struct ext4_super_block *es;
2942         struct ext4_group_desc *gdp;
2943         struct buffer_head *gdp_bh;
2944         struct ext4_sb_info *sbi;
2945         struct super_block *sb;
2946         ext4_fsblk_t block;
2947         int err, len;
2948
2949         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2950         BUG_ON(ac->ac_b_ex.fe_len <= 0);
2951
2952         sb = ac->ac_sb;
2953         sbi = EXT4_SB(sb);
2954         es = sbi->s_es;
2955
2956
2957         err = -EIO;
2958         bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2959         if (!bitmap_bh)
2960                 goto out_err;
2961
2962         err = ext4_journal_get_write_access(handle, bitmap_bh);
2963         if (err)
2964                 goto out_err;
2965
2966         err = -EIO;
2967         gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2968         if (!gdp)
2969                 goto out_err;
2970
2971         ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
2972                         ext4_free_blks_count(sb, gdp));
2973
2974         err = ext4_journal_get_write_access(handle, gdp_bh);
2975         if (err)
2976                 goto out_err;
2977
2978         block = ac->ac_b_ex.fe_group * EXT4_BLOCKS_PER_GROUP(sb)
2979                 + ac->ac_b_ex.fe_start
2980                 + le32_to_cpu(es->s_first_data_block);
2981
2982         len = ac->ac_b_ex.fe_len;
2983         if (in_range(ext4_block_bitmap(sb, gdp), block, len) ||
2984             in_range(ext4_inode_bitmap(sb, gdp), block, len) ||
2985             in_range(block, ext4_inode_table(sb, gdp),
2986                      EXT4_SB(sb)->s_itb_per_group) ||
2987             in_range(block + len - 1, ext4_inode_table(sb, gdp),
2988                      EXT4_SB(sb)->s_itb_per_group)) {
2989                 ext4_error(sb, __func__,
2990                            "Allocating block %llu in system zone of %d group\n",
2991                            block, ac->ac_b_ex.fe_group);
2992                 /* File system mounted not to panic on error
2993                  * Fix the bitmap and repeat the block allocation
2994                  * We leak some of the blocks here.
2995                  */
2996                 mb_set_bits(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group),
2997                                 bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2998                                 ac->ac_b_ex.fe_len);
2999                 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3000                 if (!err)
3001                         err = -EAGAIN;
3002                 goto out_err;
3003         }
3004 #ifdef AGGRESSIVE_CHECK
3005         {
3006                 int i;
3007                 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3008                         BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3009                                                 bitmap_bh->b_data));
3010                 }
3011         }
3012 #endif
3013         spin_lock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
3014         mb_set_bits(NULL, bitmap_bh->b_data,
3015                                 ac->ac_b_ex.fe_start, ac->ac_b_ex.fe_len);
3016         if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
3017                 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3018                 ext4_free_blks_set(sb, gdp,
3019                                         ext4_free_blocks_after_init(sb,
3020                                         ac->ac_b_ex.fe_group, gdp));
3021         }
3022         len = ext4_free_blks_count(sb, gdp) - ac->ac_b_ex.fe_len;
3023         ext4_free_blks_set(sb, gdp, len);
3024         gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
3025         spin_unlock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
3026         percpu_counter_sub(&sbi->s_freeblocks_counter, ac->ac_b_ex.fe_len);
3027         /*
3028          * Now reduce the dirty block count also. Should not go negative
3029          */
3030         if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3031                 /* release all the reserved blocks if non delalloc */
3032                 percpu_counter_sub(&sbi->s_dirtyblocks_counter, reserv_blks);
3033         else {
3034                 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
3035                                                 ac->ac_b_ex.fe_len);
3036                 /* convert reserved quota blocks to real quota blocks */
3037                 vfs_dq_claim_block(ac->ac_inode, ac->ac_b_ex.fe_len);
3038         }
3039
3040         if (sbi->s_log_groups_per_flex) {
3041                 ext4_group_t flex_group = ext4_flex_group(sbi,
3042                                                           ac->ac_b_ex.fe_group);
3043                 atomic_sub(ac->ac_b_ex.fe_len,
3044                            &sbi->s_flex_groups[flex_group].free_blocks);
3045         }
3046
3047         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3048         if (err)
3049                 goto out_err;
3050         err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3051
3052 out_err:
3053         sb->s_dirt = 1;
3054         brelse(bitmap_bh);
3055         return err;
3056 }
3057
3058 /*
3059  * here we normalize request for locality group
3060  * Group request are normalized to s_strip size if we set the same via mount
3061  * option. If not we set it to s_mb_group_prealloc which can be configured via
3062  * /sys/fs/ext4/<partition>/mb_group_prealloc
3063  *
3064  * XXX: should we try to preallocate more than the group has now?
3065  */
3066 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3067 {
3068         struct super_block *sb = ac->ac_sb;
3069         struct ext4_locality_group *lg = ac->ac_lg;
3070
3071         BUG_ON(lg == NULL);
3072         if (EXT4_SB(sb)->s_stripe)
3073                 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_stripe;
3074         else
3075                 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3076         mb_debug("#%u: goal %u blocks for locality group\n",
3077                 current->pid, ac->ac_g_ex.fe_len);
3078 }
3079
3080 /*
3081  * Normalization means making request better in terms of
3082  * size and alignment
3083  */
3084 static noinline_for_stack void
3085 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3086                                 struct ext4_allocation_request *ar)
3087 {
3088         int bsbits, max;
3089         ext4_lblk_t end;
3090         loff_t size, orig_size, start_off;
3091         ext4_lblk_t start, orig_start;
3092         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3093         struct ext4_prealloc_space *pa;
3094
3095         /* do normalize only data requests, metadata requests
3096            do not need preallocation */
3097         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3098                 return;
3099
3100         /* sometime caller may want exact blocks */
3101         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3102                 return;
3103
3104         /* caller may indicate that preallocation isn't
3105          * required (it's a tail, for example) */
3106         if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3107                 return;
3108
3109         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3110                 ext4_mb_normalize_group_request(ac);
3111                 return ;
3112         }
3113
3114         bsbits = ac->ac_sb->s_blocksize_bits;
3115
3116         /* first, let's learn actual file size
3117          * given current request is allocated */
3118         size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
3119         size = size << bsbits;
3120         if (size < i_size_read(ac->ac_inode))
3121                 size = i_size_read(ac->ac_inode);
3122
3123         /* max size of free chunks */
3124         max = 2 << bsbits;
3125
3126 #define NRL_CHECK_SIZE(req, size, max, chunk_size)      \
3127                 (req <= (size) || max <= (chunk_size))
3128
3129         /* first, try to predict filesize */
3130         /* XXX: should this table be tunable? */
3131         start_off = 0;
3132         if (size <= 16 * 1024) {
3133                 size = 16 * 1024;
3134         } else if (size <= 32 * 1024) {
3135                 size = 32 * 1024;
3136         } else if (size <= 64 * 1024) {
3137                 size = 64 * 1024;
3138         } else if (size <= 128 * 1024) {
3139                 size = 128 * 1024;
3140         } else if (size <= 256 * 1024) {
3141                 size = 256 * 1024;
3142         } else if (size <= 512 * 1024) {
3143                 size = 512 * 1024;
3144         } else if (size <= 1024 * 1024) {
3145                 size = 1024 * 1024;
3146         } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3147                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3148                                                 (21 - bsbits)) << 21;
3149                 size = 2 * 1024 * 1024;
3150         } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3151                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3152                                                         (22 - bsbits)) << 22;
3153                 size = 4 * 1024 * 1024;
3154         } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3155                                         (8<<20)>>bsbits, max, 8 * 1024)) {
3156                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3157                                                         (23 - bsbits)) << 23;
3158                 size = 8 * 1024 * 1024;
3159         } else {
3160                 start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
3161                 size      = ac->ac_o_ex.fe_len << bsbits;
3162         }
3163         orig_size = size = size >> bsbits;
3164         orig_start = start = start_off >> bsbits;
3165
3166         /* don't cover already allocated blocks in selected range */
3167         if (ar->pleft && start <= ar->lleft) {
3168                 size -= ar->lleft + 1 - start;
3169                 start = ar->lleft + 1;
3170         }
3171         if (ar->pright && start + size - 1 >= ar->lright)
3172                 size -= start + size - ar->lright;
3173
3174         end = start + size;
3175
3176         /* check we don't cross already preallocated blocks */
3177         rcu_read_lock();
3178         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3179                 ext4_lblk_t pa_end;
3180
3181                 if (pa->pa_deleted)
3182                         continue;
3183                 spin_lock(&pa->pa_lock);
3184                 if (pa->pa_deleted) {
3185                         spin_unlock(&pa->pa_lock);
3186                         continue;
3187                 }
3188
3189                 pa_end = pa->pa_lstart + pa->pa_len;
3190
3191                 /* PA must not overlap original request */
3192                 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3193                         ac->ac_o_ex.fe_logical < pa->pa_lstart));
3194
3195                 /* skip PA normalized request doesn't overlap with */
3196                 if (pa->pa_lstart >= end) {
3197                         spin_unlock(&pa->pa_lock);
3198                         continue;
3199                 }
3200                 if (pa_end <= start) {
3201                         spin_unlock(&pa->pa_lock);
3202                         continue;
3203                 }
3204                 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3205
3206                 if (pa_end <= ac->ac_o_ex.fe_logical) {
3207                         BUG_ON(pa_end < start);
3208                         start = pa_end;
3209                 }
3210
3211                 if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3212                         BUG_ON(pa->pa_lstart > end);
3213                         end = pa->pa_lstart;
3214                 }
3215                 spin_unlock(&pa->pa_lock);
3216         }
3217         rcu_read_unlock();
3218         size = end - start;
3219
3220         /* XXX: extra loop to check we really don't overlap preallocations */
3221         rcu_read_lock();
3222         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3223                 ext4_lblk_t pa_end;
3224                 spin_lock(&pa->pa_lock);
3225                 if (pa->pa_deleted == 0) {
3226                         pa_end = pa->pa_lstart + pa->pa_len;
3227                         BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3228                 }
3229                 spin_unlock(&pa->pa_lock);
3230         }
3231         rcu_read_unlock();
3232
3233         if (start + size <= ac->ac_o_ex.fe_logical &&
3234                         start > ac->ac_o_ex.fe_logical) {
3235                 printk(KERN_ERR "start %lu, size %lu, fe_logical %lu\n",
3236                         (unsigned long) start, (unsigned long) size,
3237                         (unsigned long) ac->ac_o_ex.fe_logical);
3238         }
3239         BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3240                         start > ac->ac_o_ex.fe_logical);
3241         BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3242
3243         /* now prepare goal request */
3244
3245         /* XXX: is it better to align blocks WRT to logical
3246          * placement or satisfy big request as is */
3247         ac->ac_g_ex.fe_logical = start;
3248         ac->ac_g_ex.fe_len = size;
3249
3250         /* define goal start in order to merge */
3251         if (ar->pright && (ar->lright == (start + size))) {
3252                 /* merge to the right */
3253                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3254                                                 &ac->ac_f_ex.fe_group,
3255                                                 &ac->ac_f_ex.fe_start);
3256                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3257         }
3258         if (ar->pleft && (ar->lleft + 1 == start)) {
3259                 /* merge to the left */
3260                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3261                                                 &ac->ac_f_ex.fe_group,
3262                                                 &ac->ac_f_ex.fe_start);
3263                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3264         }
3265
3266         mb_debug("goal: %u(was %u) blocks at %u\n", (unsigned) size,
3267                 (unsigned) orig_size, (unsigned) start);
3268 }
3269
3270 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3271 {
3272         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3273
3274         if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3275                 atomic_inc(&sbi->s_bal_reqs);
3276                 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3277                 if (ac->ac_o_ex.fe_len >= ac->ac_g_ex.fe_len)
3278                         atomic_inc(&sbi->s_bal_success);
3279                 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3280                 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3281                                 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3282                         atomic_inc(&sbi->s_bal_goals);
3283                 if (ac->ac_found > sbi->s_mb_max_to_scan)
3284                         atomic_inc(&sbi->s_bal_breaks);
3285         }
3286
3287         ext4_mb_store_history(ac);
3288 }
3289
3290 /*
3291  * use blocks preallocated to inode
3292  */
3293 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3294                                 struct ext4_prealloc_space *pa)
3295 {
3296         ext4_fsblk_t start;
3297         ext4_fsblk_t end;
3298         int len;
3299
3300         /* found preallocated blocks, use them */
3301         start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3302         end = min(pa->pa_pstart + pa->pa_len, start + ac->ac_o_ex.fe_len);
3303         len = end - start;
3304         ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3305                                         &ac->ac_b_ex.fe_start);
3306         ac->ac_b_ex.fe_len = len;
3307         ac->ac_status = AC_STATUS_FOUND;
3308         ac->ac_pa = pa;
3309
3310         BUG_ON(start < pa->pa_pstart);
3311         BUG_ON(start + len > pa->pa_pstart + pa->pa_len);
3312         BUG_ON(pa->pa_free < len);
3313         pa->pa_free -= len;
3314
3315         mb_debug("use %llu/%u from inode pa %p\n", start, len, pa);
3316 }
3317
3318 /*
3319  * use blocks preallocated to locality group
3320  */
3321 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3322                                 struct ext4_prealloc_space *pa)
3323 {
3324         unsigned int len = ac->ac_o_ex.fe_len;
3325
3326         ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3327                                         &ac->ac_b_ex.fe_group,
3328                                         &ac->ac_b_ex.fe_start);
3329         ac->ac_b_ex.fe_len = len;
3330         ac->ac_status = AC_STATUS_FOUND;
3331         ac->ac_pa = pa;
3332
3333         /* we don't correct pa_pstart or pa_plen here to avoid
3334          * possible race when the group is being loaded concurrently
3335          * instead we correct pa later, after blocks are marked
3336          * in on-disk bitmap -- see ext4_mb_release_context()
3337          * Other CPUs are prevented from allocating from this pa by lg_mutex
3338          */
3339         mb_debug("use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3340 }
3341
3342 /*
3343  * Return the prealloc space that have minimal distance
3344  * from the goal block. @cpa is the prealloc
3345  * space that is having currently known minimal distance
3346  * from the goal block.
3347  */
3348 static struct ext4_prealloc_space *
3349 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3350                         struct ext4_prealloc_space *pa,
3351                         struct ext4_prealloc_space *cpa)
3352 {
3353         ext4_fsblk_t cur_distance, new_distance;
3354
3355         if (cpa == NULL) {
3356                 atomic_inc(&pa->pa_count);
3357                 return pa;
3358         }
3359         cur_distance = abs(goal_block - cpa->pa_pstart);
3360         new_distance = abs(goal_block - pa->pa_pstart);
3361
3362         if (cur_distance < new_distance)
3363                 return cpa;
3364
3365         /* drop the previous reference */
3366         atomic_dec(&cpa->pa_count);
3367         atomic_inc(&pa->pa_count);
3368         return pa;
3369 }
3370
3371 /*
3372  * search goal blocks in preallocated space
3373  */
3374 static noinline_for_stack int
3375 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3376 {
3377         int order, i;
3378         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3379         struct ext4_locality_group *lg;
3380         struct ext4_prealloc_space *pa, *cpa = NULL;
3381         ext4_fsblk_t goal_block;
3382
3383         /* only data can be preallocated */
3384         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3385                 return 0;
3386
3387         /* first, try per-file preallocation */
3388         rcu_read_lock();
3389         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3390
3391                 /* all fields in this condition don't change,
3392                  * so we can skip locking for them */
3393                 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3394                         ac->ac_o_ex.fe_logical >= pa->pa_lstart + pa->pa_len)
3395                         continue;
3396
3397                 /* found preallocated blocks, use them */
3398                 spin_lock(&pa->pa_lock);
3399                 if (pa->pa_deleted == 0 && pa->pa_free) {
3400                         atomic_inc(&pa->pa_count);
3401                         ext4_mb_use_inode_pa(ac, pa);
3402                         spin_unlock(&pa->pa_lock);
3403                         ac->ac_criteria = 10;
3404                         rcu_read_unlock();
3405                         return 1;
3406                 }
3407                 spin_unlock(&pa->pa_lock);
3408         }
3409         rcu_read_unlock();
3410
3411         /* can we use group allocation? */
3412         if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3413                 return 0;
3414
3415         /* inode may have no locality group for some reason */
3416         lg = ac->ac_lg;
3417         if (lg == NULL)
3418                 return 0;
3419         order  = fls(ac->ac_o_ex.fe_len) - 1;
3420         if (order > PREALLOC_TB_SIZE - 1)
3421                 /* The max size of hash table is PREALLOC_TB_SIZE */
3422                 order = PREALLOC_TB_SIZE - 1;
3423
3424         goal_block = ac->ac_g_ex.fe_group * EXT4_BLOCKS_PER_GROUP(ac->ac_sb) +
3425                      ac->ac_g_ex.fe_start +
3426                      le32_to_cpu(EXT4_SB(ac->ac_sb)->s_es->s_first_data_block);
3427         /*
3428          * search for the prealloc space that is having
3429          * minimal distance from the goal block.
3430          */
3431         for (i = order; i < PREALLOC_TB_SIZE; i++) {
3432                 rcu_read_lock();
3433                 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3434                                         pa_inode_list) {
3435                         spin_lock(&pa->pa_lock);
3436                         if (pa->pa_deleted == 0 &&
3437                                         pa->pa_free >= ac->ac_o_ex.fe_len) {
3438
3439                                 cpa = ext4_mb_check_group_pa(goal_block,
3440                                                                 pa, cpa);
3441                         }
3442                         spin_unlock(&pa->pa_lock);
3443                 }
3444                 rcu_read_unlock();
3445         }
3446         if (cpa) {
3447                 ext4_mb_use_group_pa(ac, cpa);
3448                 ac->ac_criteria = 20;
3449                 return 1;
3450         }
3451         return 0;
3452 }
3453
3454 /*
3455  * the function goes through all block freed in the group
3456  * but not yet committed and marks them used in in-core bitmap.
3457  * buddy must be generated from this bitmap
3458  * Need to be called with ext4 group lock (ext4_lock_group)
3459  */
3460 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3461                                                 ext4_group_t group)
3462 {
3463         struct rb_node *n;
3464         struct ext4_group_info *grp;
3465         struct ext4_free_data *entry;
3466
3467         grp = ext4_get_group_info(sb, group);
3468         n = rb_first(&(grp->bb_free_root));
3469
3470         while (n) {
3471                 entry = rb_entry(n, struct ext4_free_data, node);
3472                 mb_set_bits(sb_bgl_lock(EXT4_SB(sb), group),
3473                                 bitmap, entry->start_blk,
3474                                 entry->count);
3475                 n = rb_next(n);
3476         }
3477         return;
3478 }
3479
3480 /*
3481  * the function goes through all preallocation in this group and marks them
3482  * used in in-core bitmap. buddy must be generated from this bitmap
3483  * Need to be called with ext4 group lock (ext4_lock_group)
3484  */
3485 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3486                                         ext4_group_t group)
3487 {
3488         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3489         struct ext4_prealloc_space *pa;
3490         struct list_head *cur;
3491         ext4_group_t groupnr;
3492         ext4_grpblk_t start;
3493         int preallocated = 0;
3494         int count = 0;
3495         int len;
3496
3497         /* all form of preallocation discards first load group,
3498          * so the only competing code is preallocation use.
3499          * we don't need any locking here
3500          * notice we do NOT ignore preallocations with pa_deleted
3501          * otherwise we could leave used blocks available for
3502          * allocation in buddy when concurrent ext4_mb_put_pa()
3503          * is dropping preallocation
3504          */
3505         list_for_each(cur, &grp->bb_prealloc_list) {
3506                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3507                 spin_lock(&pa->pa_lock);
3508                 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3509                                              &groupnr, &start);
3510                 len = pa->pa_len;
3511                 spin_unlock(&pa->pa_lock);
3512                 if (unlikely(len == 0))
3513                         continue;
3514                 BUG_ON(groupnr != group);
3515                 mb_set_bits(sb_bgl_lock(EXT4_SB(sb), group),
3516                                                 bitmap, start, len);
3517                 preallocated += len;
3518                 count++;
3519         }
3520         mb_debug("prellocated %u for group %u\n", preallocated, group);
3521 }
3522
3523 static void ext4_mb_pa_callback(struct rcu_head *head)
3524 {
3525         struct ext4_prealloc_space *pa;
3526         pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3527         kmem_cache_free(ext4_pspace_cachep, pa);
3528 }
3529
3530 /*
3531  * drops a reference to preallocated space descriptor
3532  * if this was the last reference and the space is consumed
3533  */
3534 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3535                         struct super_block *sb, struct ext4_prealloc_space *pa)
3536 {
3537         ext4_group_t grp;
3538         ext4_fsblk_t grp_blk;
3539
3540         if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3541                 return;
3542
3543         /* in this short window concurrent discard can set pa_deleted */
3544         spin_lock(&pa->pa_lock);
3545         if (pa->pa_deleted == 1) {
3546                 spin_unlock(&pa->pa_lock);
3547                 return;
3548         }
3549
3550         pa->pa_deleted = 1;
3551         spin_unlock(&pa->pa_lock);
3552
3553         grp_blk = pa->pa_pstart;
3554         /* 
3555          * If doing group-based preallocation, pa_pstart may be in the
3556          * next group when pa is used up
3557          */
3558         if (pa->pa_type == MB_GROUP_PA)
3559                 grp_blk--;
3560
3561         ext4_get_group_no_and_offset(sb, grp_blk, &grp, NULL);
3562
3563         /*
3564          * possible race:
3565          *
3566          *  P1 (buddy init)                     P2 (regular allocation)
3567          *                                      find block B in PA
3568          *  copy on-disk bitmap to buddy
3569          *                                      mark B in on-disk bitmap
3570          *                                      drop PA from group
3571          *  mark all PAs in buddy
3572          *
3573          * thus, P1 initializes buddy with B available. to prevent this
3574          * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3575          * against that pair
3576          */
3577         ext4_lock_group(sb, grp);
3578         list_del(&pa->pa_group_list);
3579         ext4_unlock_group(sb, grp);
3580
3581         spin_lock(pa->pa_obj_lock);
3582         list_del_rcu(&pa->pa_inode_list);
3583         spin_unlock(pa->pa_obj_lock);
3584
3585         call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3586 }
3587
3588 /*
3589  * creates new preallocated space for given inode
3590  */
3591 static noinline_for_stack int
3592 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3593 {
3594         struct super_block *sb = ac->ac_sb;
3595         struct ext4_prealloc_space *pa;
3596         struct ext4_group_info *grp;
3597         struct ext4_inode_info *ei;
3598
3599         /* preallocate only when found space is larger then requested */
3600         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3601         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3602         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3603
3604         pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3605         if (pa == NULL)
3606                 return -ENOMEM;
3607
3608         if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3609                 int winl;
3610                 int wins;
3611                 int win;
3612                 int offs;
3613
3614                 /* we can't allocate as much as normalizer wants.
3615                  * so, found space must get proper lstart
3616                  * to cover original request */
3617                 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3618                 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3619
3620                 /* we're limited by original request in that
3621                  * logical block must be covered any way
3622                  * winl is window we can move our chunk within */
3623                 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3624
3625                 /* also, we should cover whole original request */
3626                 wins = ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len;
3627
3628                 /* the smallest one defines real window */
3629                 win = min(winl, wins);
3630
3631                 offs = ac->ac_o_ex.fe_logical % ac->ac_b_ex.fe_len;
3632                 if (offs && offs < win)
3633                         win = offs;
3634
3635                 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical - win;
3636                 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3637                 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3638         }
3639
3640         /* preallocation can change ac_b_ex, thus we store actually
3641          * allocated blocks for history */
3642         ac->ac_f_ex = ac->ac_b_ex;
3643
3644         pa->pa_lstart = ac->ac_b_ex.fe_logical;
3645         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3646         pa->pa_len = ac->ac_b_ex.fe_len;
3647         pa->pa_free = pa->pa_len;
3648         atomic_set(&pa->pa_count, 1);
3649         spin_lock_init(&pa->pa_lock);
3650         INIT_LIST_HEAD(&pa->pa_inode_list);
3651         INIT_LIST_HEAD(&pa->pa_group_list);
3652         pa->pa_deleted = 0;
3653         pa->pa_type = MB_INODE_PA;
3654
3655         mb_debug("new inode pa %p: %llu/%u for %u\n", pa,
3656                         pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3657         trace_mark(ext4_mb_new_inode_pa,
3658                    "dev %s ino %lu pstart %llu len %u lstart %u",
3659                    sb->s_id, ac->ac_inode->i_ino,
3660                    pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3661
3662         ext4_mb_use_inode_pa(ac, pa);
3663         atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3664
3665         ei = EXT4_I(ac->ac_inode);
3666         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3667
3668         pa->pa_obj_lock = &ei->i_prealloc_lock;
3669         pa->pa_inode = ac->ac_inode;
3670
3671         ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3672         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3673         ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3674
3675         spin_lock(pa->pa_obj_lock);
3676         list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3677         spin_unlock(pa->pa_obj_lock);
3678
3679         return 0;
3680 }
3681
3682 /*
3683  * creates new preallocated space for locality group inodes belongs to
3684  */
3685 static noinline_for_stack int
3686 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3687 {
3688         struct super_block *sb = ac->ac_sb;
3689         struct ext4_locality_group *lg;
3690         struct ext4_prealloc_space *pa;
3691         struct ext4_group_info *grp;
3692
3693         /* preallocate only when found space is larger then requested */
3694         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3695         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3696         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3697
3698         BUG_ON(ext4_pspace_cachep == NULL);
3699         pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3700         if (pa == NULL)
3701                 return -ENOMEM;
3702
3703         /* preallocation can change ac_b_ex, thus we store actually
3704          * allocated blocks for history */
3705         ac->ac_f_ex = ac->ac_b_ex;
3706
3707         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3708         pa->pa_lstart = pa->pa_pstart;
3709         pa->pa_len = ac->ac_b_ex.fe_len;
3710         pa->pa_free = pa->pa_len;
3711         atomic_set(&pa->pa_count, 1);
3712         spin_lock_init(&pa->pa_lock);
3713         INIT_LIST_HEAD(&pa->pa_inode_list);
3714         INIT_LIST_HEAD(&pa->pa_group_list);
3715         pa->pa_deleted = 0;
3716         pa->pa_type = MB_GROUP_PA;
3717
3718         mb_debug("new group pa %p: %llu/%u for %u\n", pa,
3719                  pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3720         trace_mark(ext4_mb_new_group_pa, "dev %s pstart %llu len %u lstart %u",
3721                    sb->s_id, pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3722
3723         ext4_mb_use_group_pa(ac, pa);
3724         atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3725
3726         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3727         lg = ac->ac_lg;
3728         BUG_ON(lg == NULL);
3729
3730         pa->pa_obj_lock = &lg->lg_prealloc_lock;
3731         pa->pa_inode = NULL;
3732
3733         ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3734         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3735         ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3736
3737         /*
3738          * We will later add the new pa to the right bucket
3739          * after updating the pa_free in ext4_mb_release_context
3740          */
3741         return 0;
3742 }
3743
3744 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3745 {
3746         int err;
3747
3748         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3749                 err = ext4_mb_new_group_pa(ac);
3750         else
3751                 err = ext4_mb_new_inode_pa(ac);
3752         return err;
3753 }
3754
3755 /*
3756  * finds all unused blocks in on-disk bitmap, frees them in
3757  * in-core bitmap and buddy.
3758  * @pa must be unlinked from inode and group lists, so that
3759  * nobody else can find/use it.
3760  * the caller MUST hold group/inode locks.
3761  * TODO: optimize the case when there are no in-core structures yet
3762  */
3763 static noinline_for_stack int
3764 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3765                         struct ext4_prealloc_space *pa,
3766                         struct ext4_allocation_context *ac)
3767 {
3768         struct super_block *sb = e4b->bd_sb;
3769         struct ext4_sb_info *sbi = EXT4_SB(sb);
3770         unsigned int end;
3771         unsigned int next;
3772         ext4_group_t group;
3773         ext4_grpblk_t bit;
3774         unsigned long long grp_blk_start;
3775         sector_t start;
3776         int err = 0;
3777         int free = 0;
3778
3779         BUG_ON(pa->pa_deleted == 0);
3780         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3781         grp_blk_start = pa->pa_pstart - bit;
3782         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3783         end = bit + pa->pa_len;
3784
3785         if (ac) {
3786                 ac->ac_sb = sb;
3787                 ac->ac_inode = pa->pa_inode;
3788                 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3789         }
3790
3791         while (bit < end) {
3792                 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3793                 if (bit >= end)
3794                         break;
3795                 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3796                 start = group * EXT4_BLOCKS_PER_GROUP(sb) + bit +
3797                                 le32_to_cpu(sbi->s_es->s_first_data_block);
3798                 mb_debug("    free preallocated %u/%u in group %u\n",
3799                                 (unsigned) start, (unsigned) next - bit,
3800                                 (unsigned) group);
3801                 free += next - bit;
3802
3803                 if (ac) {
3804                         ac->ac_b_ex.fe_group = group;
3805                         ac->ac_b_ex.fe_start = bit;
3806                         ac->ac_b_ex.fe_len = next - bit;
3807                         ac->ac_b_ex.fe_logical = 0;
3808                         ext4_mb_store_history(ac);
3809                 }
3810
3811                 trace_mark(ext4_mb_release_inode_pa,
3812                            "dev %s ino %lu block %llu count %u",
3813                            sb->s_id, pa->pa_inode->i_ino, grp_blk_start + bit,
3814                            next - bit);
3815                 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3816                 bit = next + 1;
3817         }
3818         if (free != pa->pa_free) {
3819                 printk(KERN_CRIT "pa %p: logic %lu, phys. %lu, len %lu\n",
3820                         pa, (unsigned long) pa->pa_lstart,
3821                         (unsigned long) pa->pa_pstart,
3822                         (unsigned long) pa->pa_len);
3823                 ext4_grp_locked_error(sb, group,
3824                                         __func__, "free %u, pa_free %u",
3825                                         free, pa->pa_free);
3826                 /*
3827                  * pa is already deleted so we use the value obtained
3828                  * from the bitmap and continue.
3829                  */
3830         }
3831         atomic_add(free, &sbi->s_mb_discarded);
3832
3833         return err;
3834 }
3835
3836 static noinline_for_stack int
3837 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3838                                 struct ext4_prealloc_space *pa,
3839                                 struct ext4_allocation_context *ac)
3840 {
3841         struct super_block *sb = e4b->bd_sb;
3842         ext4_group_t group;
3843         ext4_grpblk_t bit;
3844
3845         if (ac)
3846                 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3847
3848         trace_mark(ext4_mb_release_group_pa, "dev %s pstart %llu len %d",
3849                    sb->s_id, pa->pa_pstart, pa->pa_len);
3850         BUG_ON(pa->pa_deleted == 0);
3851         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3852         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3853         mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3854         atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3855
3856         if (ac) {
3857                 ac->ac_sb = sb;
3858                 ac->ac_inode = NULL;
3859                 ac->ac_b_ex.fe_group = group;
3860                 ac->ac_b_ex.fe_start = bit;
3861                 ac->ac_b_ex.fe_len = pa->pa_len;
3862                 ac->ac_b_ex.fe_logical = 0;
3863                 ext4_mb_store_history(ac);
3864         }
3865
3866         return 0;
3867 }
3868
3869 /*
3870  * releases all preallocations in given group
3871  *
3872  * first, we need to decide discard policy:
3873  * - when do we discard
3874  *   1) ENOSPC
3875  * - how many do we discard
3876  *   1) how many requested
3877  */
3878 static noinline_for_stack int
3879 ext4_mb_discard_group_preallocations(struct super_block *sb,
3880                                         ext4_group_t group, int needed)
3881 {
3882         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3883         struct buffer_head *bitmap_bh = NULL;
3884         struct ext4_prealloc_space *pa, *tmp;
3885         struct ext4_allocation_context *ac;
3886         struct list_head list;
3887         struct ext4_buddy e4b;
3888         int err;
3889         int busy = 0;
3890         int free = 0;
3891
3892         mb_debug("discard preallocation for group %u\n", group);
3893
3894         if (list_empty(&grp->bb_prealloc_list))
3895                 return 0;
3896
3897         bitmap_bh = ext4_read_block_bitmap(sb, group);
3898         if (bitmap_bh == NULL) {
3899                 ext4_error(sb, __func__, "Error in reading block "
3900                                 "bitmap for %u", group);
3901                 return 0;
3902         }
3903
3904         err = ext4_mb_load_buddy(sb, group, &e4b);
3905         if (err) {
3906                 ext4_error(sb, __func__, "Error in loading buddy "
3907                                 "information for %u", group);
3908                 put_bh(bitmap_bh);
3909                 return 0;
3910         }
3911
3912         if (needed == 0)
3913                 needed = EXT4_BLOCKS_PER_GROUP(sb) + 1;
3914
3915         INIT_LIST_HEAD(&list);
3916         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
3917 repeat:
3918         ext4_lock_group(sb, group);
3919         list_for_each_entry_safe(pa, tmp,
3920                                 &grp->bb_prealloc_list, pa_group_list) {
3921                 spin_lock(&pa->pa_lock);
3922                 if (atomic_read(&pa->pa_count)) {
3923                         spin_unlock(&pa->pa_lock);
3924                         busy = 1;
3925                         continue;
3926                 }
3927                 if (pa->pa_deleted) {
3928                         spin_unlock(&pa->pa_lock);
3929                         continue;
3930                 }
3931
3932                 /* seems this one can be freed ... */
3933                 pa->pa_deleted = 1;
3934
3935                 /* we can trust pa_free ... */
3936                 free += pa->pa_free;
3937
3938                 spin_unlock(&pa->pa_lock);
3939
3940                 list_del(&pa->pa_group_list);
3941                 list_add(&pa->u.pa_tmp_list, &list);
3942         }
3943
3944         /* if we still need more blocks and some PAs were used, try again */
3945         if (free < needed && busy) {
3946                 busy = 0;
3947                 ext4_unlock_group(sb, group);
3948                 /*
3949                  * Yield the CPU here so that we don't get soft lockup
3950                  * in non preempt case.
3951                  */
3952                 yield();
3953                 goto repeat;
3954         }
3955
3956         /* found anything to free? */
3957         if (list_empty(&list)) {
3958                 BUG_ON(free != 0);
3959                 goto out;
3960         }
3961
3962         /* now free all selected PAs */
3963         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3964
3965                 /* remove from object (inode or locality group) */
3966                 spin_lock(pa->pa_obj_lock);
3967                 list_del_rcu(&pa->pa_inode_list);
3968                 spin_unlock(pa->pa_obj_lock);
3969
3970                 if (pa->pa_type == MB_GROUP_PA)
3971                         ext4_mb_release_group_pa(&e4b, pa, ac);
3972                 else
3973                         ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
3974
3975                 list_del(&pa->u.pa_tmp_list);
3976                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3977         }
3978
3979 out:
3980         ext4_unlock_group(sb, group);
3981         if (ac)
3982                 kmem_cache_free(ext4_ac_cachep, ac);
3983         ext4_mb_release_desc(&e4b);
3984         put_bh(bitmap_bh);
3985         return free;
3986 }
3987
3988 /*
3989  * releases all non-used preallocated blocks for given inode
3990  *
3991  * It's important to discard preallocations under i_data_sem
3992  * We don't want another block to be served from the prealloc
3993  * space when we are discarding the inode prealloc space.
3994  *
3995  * FIXME!! Make sure it is valid at all the call sites
3996  */
3997 void ext4_discard_preallocations(struct inode *inode)
3998 {
3999         struct ext4_inode_info *ei = EXT4_I(inode);
4000         struct super_block *sb = inode->i_sb;
4001         struct buffer_head *bitmap_bh = NULL;
4002         struct ext4_prealloc_space *pa, *tmp;
4003         struct ext4_allocation_context *ac;
4004         ext4_group_t group = 0;
4005         struct list_head list;
4006         struct ext4_buddy e4b;
4007         int err;
4008
4009         if (!S_ISREG(inode->i_mode)) {
4010                 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4011                 return;
4012         }
4013
4014         mb_debug("discard preallocation for inode %lu\n", inode->i_ino);
4015         trace_mark(ext4_discard_preallocations, "dev %s ino %lu", sb->s_id,
4016                    inode->i_ino);
4017
4018         INIT_LIST_HEAD(&list);
4019
4020         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4021 repeat:
4022         /* first, collect all pa's in the inode */
4023         spin_lock(&ei->i_prealloc_lock);
4024         while (!list_empty(&ei->i_prealloc_list)) {
4025                 pa = list_entry(ei->i_prealloc_list.next,
4026                                 struct ext4_prealloc_space, pa_inode_list);
4027                 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4028                 spin_lock(&pa->pa_lock);
4029                 if (atomic_read(&pa->pa_count)) {
4030                         /* this shouldn't happen often - nobody should
4031                          * use preallocation while we're discarding it */
4032                         spin_unlock(&pa->pa_lock);
4033                         spin_unlock(&ei->i_prealloc_lock);
4034                         printk(KERN_ERR "uh-oh! used pa while discarding\n");
4035                         WARN_ON(1);
4036                         schedule_timeout_uninterruptible(HZ);
4037                         goto repeat;
4038
4039                 }
4040                 if (pa->pa_deleted == 0) {
4041                         pa->pa_deleted = 1;
4042                         spin_unlock(&pa->pa_lock);
4043                         list_del_rcu(&pa->pa_inode_list);
4044                         list_add(&pa->u.pa_tmp_list, &list);
4045                         continue;
4046                 }
4047
4048                 /* someone is deleting pa right now */
4049                 spin_unlock(&pa->pa_lock);
4050                 spin_unlock(&ei->i_prealloc_lock);
4051
4052                 /* we have to wait here because pa_deleted
4053                  * doesn't mean pa is already unlinked from
4054                  * the list. as we might be called from
4055                  * ->clear_inode() the inode will get freed
4056                  * and concurrent thread which is unlinking
4057                  * pa from inode's list may access already
4058                  * freed memory, bad-bad-bad */
4059
4060                 /* XXX: if this happens too often, we can
4061                  * add a flag to force wait only in case
4062                  * of ->clear_inode(), but not in case of
4063                  * regular truncate */
4064                 schedule_timeout_uninterruptible(HZ);
4065                 goto repeat;
4066         }
4067         spin_unlock(&ei->i_prealloc_lock);
4068
4069         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4070                 BUG_ON(pa->pa_type != MB_INODE_PA);
4071                 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
4072
4073                 err = ext4_mb_load_buddy(sb, group, &e4b);
4074                 if (err) {
4075                         ext4_error(sb, __func__, "Error in loading buddy "
4076                                         "information for %u", group);
4077                         continue;
4078                 }
4079
4080                 bitmap_bh = ext4_read_block_bitmap(sb, group);
4081                 if (bitmap_bh == NULL) {
4082                         ext4_error(sb, __func__, "Error in reading block "
4083                                         "bitmap for %u", group);
4084                         ext4_mb_release_desc(&e4b);
4085                         continue;
4086                 }
4087
4088                 ext4_lock_group(sb, group);
4089                 list_del(&pa->pa_group_list);
4090                 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
4091                 ext4_unlock_group(sb, group);
4092
4093                 ext4_mb_release_desc(&e4b);
4094                 put_bh(bitmap_bh);
4095
4096                 list_del(&pa->u.pa_tmp_list);
4097                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4098         }
4099         if (ac)
4100                 kmem_cache_free(ext4_ac_cachep, ac);
4101 }
4102
4103 /*
4104  * finds all preallocated spaces and return blocks being freed to them
4105  * if preallocated space becomes full (no block is used from the space)
4106  * then the function frees space in buddy
4107  * XXX: at the moment, truncate (which is the only way to free blocks)
4108  * discards all preallocations
4109  */
4110 static void ext4_mb_return_to_preallocation(struct inode *inode,
4111                                         struct ext4_buddy *e4b,
4112                                         sector_t block, int count)
4113 {
4114         BUG_ON(!list_empty(&EXT4_I(inode)->i_prealloc_list));
4115 }
4116 #ifdef MB_DEBUG
4117 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4118 {
4119         struct super_block *sb = ac->ac_sb;
4120         ext4_group_t ngroups, i;
4121
4122         printk(KERN_ERR "EXT4-fs: Can't allocate:"
4123                         " Allocation context details:\n");
4124         printk(KERN_ERR "EXT4-fs: status %d flags %d\n",
4125                         ac->ac_status, ac->ac_flags);
4126         printk(KERN_ERR "EXT4-fs: orig %lu/%lu/%lu@%lu, goal %lu/%lu/%lu@%lu, "
4127                         "best %lu/%lu/%lu@%lu cr %d\n",
4128                         (unsigned long)ac->ac_o_ex.fe_group,
4129                         (unsigned long)ac->ac_o_ex.fe_start,
4130                         (unsigned long)ac->ac_o_ex.fe_len,
4131                         (unsigned long)ac->ac_o_ex.fe_logical,
4132                         (unsigned long)ac->ac_g_ex.fe_group,
4133                         (unsigned long)ac->ac_g_ex.fe_start,
4134                         (unsigned long)ac->ac_g_ex.fe_len,
4135                         (unsigned long)ac->ac_g_ex.fe_logical,
4136                         (unsigned long)ac->ac_b_ex.fe_group,
4137                         (unsigned long)ac->ac_b_ex.fe_start,
4138                         (unsigned long)ac->ac_b_ex.fe_len,
4139                         (unsigned long)ac->ac_b_ex.fe_logical,
4140                         (int)ac->ac_criteria);
4141         printk(KERN_ERR "EXT4-fs: %lu scanned, %d found\n", ac->ac_ex_scanned,
4142                 ac->ac_found);
4143         printk(KERN_ERR "EXT4-fs: groups: \n");
4144         ngroups = ext4_get_groups_count(sb);
4145         for (i = 0; i < ngroups; i++) {
4146                 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4147                 struct ext4_prealloc_space *pa;
4148                 ext4_grpblk_t start;
4149                 struct list_head *cur;
4150                 ext4_lock_group(sb, i);
4151                 list_for_each(cur, &grp->bb_prealloc_list) {
4152                         pa = list_entry(cur, struct ext4_prealloc_space,
4153                                         pa_group_list);
4154                         spin_lock(&pa->pa_lock);
4155                         ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4156                                                      NULL, &start);
4157                         spin_unlock(&pa->pa_lock);
4158                         printk(KERN_ERR "PA:%lu:%d:%u \n", i,
4159                                                         start, pa->pa_len);
4160                 }
4161                 ext4_unlock_group(sb, i);
4162
4163                 if (grp->bb_free == 0)
4164                         continue;
4165                 printk(KERN_ERR "%lu: %d/%d \n",
4166                        i, grp->bb_free, grp->bb_fragments);
4167         }
4168         printk(KERN_ERR "\n");
4169 }
4170 #else
4171 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4172 {
4173         return;
4174 }
4175 #endif
4176
4177 /*
4178  * We use locality group preallocation for small size file. The size of the
4179  * file is determined by the current size or the resulting size after
4180  * allocation which ever is larger
4181  *
4182  * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4183  */
4184 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4185 {
4186         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4187         int bsbits = ac->ac_sb->s_blocksize_bits;
4188         loff_t size, isize;
4189
4190         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4191                 return;
4192
4193         size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
4194         isize = i_size_read(ac->ac_inode) >> bsbits;
4195         size = max(size, isize);
4196
4197         /* don't use group allocation for large files */
4198         if (size >= sbi->s_mb_stream_request)
4199                 return;
4200
4201         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4202                 return;
4203
4204         BUG_ON(ac->ac_lg != NULL);
4205         /*
4206          * locality group prealloc space are per cpu. The reason for having
4207          * per cpu locality group is to reduce the contention between block
4208          * request from multiple CPUs.
4209          */
4210         ac->ac_lg = per_cpu_ptr(sbi->s_locality_groups, raw_smp_processor_id());
4211
4212         /* we're going to use group allocation */
4213         ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4214
4215         /* serialize all allocations in the group */
4216         mutex_lock(&ac->ac_lg->lg_mutex);
4217 }
4218
4219 static noinline_for_stack int
4220 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4221                                 struct ext4_allocation_request *ar)
4222 {
4223         struct super_block *sb = ar->inode->i_sb;
4224         struct ext4_sb_info *sbi = EXT4_SB(sb);
4225         struct ext4_super_block *es = sbi->s_es;
4226         ext4_group_t group;
4227         unsigned int len;
4228         ext4_fsblk_t goal;
4229         ext4_grpblk_t block;
4230
4231         /* we can't allocate > group size */
4232         len = ar->len;
4233
4234         /* just a dirty hack to filter too big requests  */
4235         if (len >= EXT4_BLOCKS_PER_GROUP(sb) - 10)
4236                 len = EXT4_BLOCKS_PER_GROUP(sb) - 10;
4237
4238         /* start searching from the goal */
4239         goal = ar->goal;
4240         if (goal < le32_to_cpu(es->s_first_data_block) ||
4241                         goal >= ext4_blocks_count(es))
4242                 goal = le32_to_cpu(es->s_first_data_block);
4243         ext4_get_group_no_and_offset(sb, goal, &group, &block);
4244
4245         /* set up allocation goals */
4246         ac->ac_b_ex.fe_logical = ar->logical;
4247         ac->ac_b_ex.fe_group = 0;
4248         ac->ac_b_ex.fe_start = 0;
4249         ac->ac_b_ex.fe_len = 0;
4250         ac->ac_status = AC_STATUS_CONTINUE;
4251         ac->ac_groups_scanned = 0;
4252         ac->ac_ex_scanned = 0;
4253         ac->ac_found = 0;
4254         ac->ac_sb = sb;
4255         ac->ac_inode = ar->inode;
4256         ac->ac_o_ex.fe_logical = ar->logical;
4257         ac->ac_o_ex.fe_group = group;
4258         ac->ac_o_ex.fe_start = block;
4259         ac->ac_o_ex.fe_len = len;
4260         ac->ac_g_ex.fe_logical = ar->logical;
4261         ac->ac_g_ex.fe_group = group;
4262         ac->ac_g_ex.fe_start = block;
4263         ac->ac_g_ex.fe_len = len;
4264         ac->ac_f_ex.fe_len = 0;
4265         ac->ac_flags = ar->flags;
4266         ac->ac_2order = 0;
4267         ac->ac_criteria = 0;
4268         ac->ac_pa = NULL;
4269         ac->ac_bitmap_page = NULL;
4270         ac->ac_buddy_page = NULL;
4271         ac->alloc_semp = NULL;
4272         ac->ac_lg = NULL;
4273
4274         /* we have to define context: we'll we work with a file or
4275          * locality group. this is a policy, actually */
4276         ext4_mb_group_or_file(ac);
4277
4278         mb_debug("init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4279                         "left: %u/%u, right %u/%u to %swritable\n",
4280                         (unsigned) ar->len, (unsigned) ar->logical,
4281                         (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4282                         (unsigned) ar->lleft, (unsigned) ar->pleft,
4283                         (unsigned) ar->lright, (unsigned) ar->pright,
4284                         atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4285         return 0;
4286
4287 }
4288
4289 static noinline_for_stack void
4290 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4291                                         struct ext4_locality_group *lg,
4292                                         int order, int total_entries)
4293 {
4294         ext4_group_t group = 0;
4295         struct ext4_buddy e4b;
4296         struct list_head discard_list;
4297         struct ext4_prealloc_space *pa, *tmp;
4298         struct ext4_allocation_context *ac;
4299
4300         mb_debug("discard locality group preallocation\n");
4301
4302         INIT_LIST_HEAD(&discard_list);
4303         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4304
4305         spin_lock(&lg->lg_prealloc_lock);
4306         list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4307                                                 pa_inode_list) {
4308                 spin_lock(&pa->pa_lock);
4309                 if (atomic_read(&pa->pa_count)) {
4310                         /*
4311                          * This is the pa that we just used
4312                          * for block allocation. So don't
4313                          * free that
4314                          */
4315                         spin_unlock(&pa->pa_lock);
4316                         continue;
4317                 }
4318                 if (pa->pa_deleted) {
4319                         spin_unlock(&pa->pa_lock);
4320                         continue;
4321                 }
4322                 /* only lg prealloc space */
4323                 BUG_ON(pa->pa_type != MB_GROUP_PA);
4324
4325                 /* seems this one can be freed ... */
4326                 pa->pa_deleted = 1;
4327                 spin_unlock(&pa->pa_lock);
4328
4329                 list_del_rcu(&pa->pa_inode_list);
4330                 list_add(&pa->u.pa_tmp_list, &discard_list);
4331
4332                 total_entries--;
4333                 if (total_entries <= 5) {
4334                         /*
4335                          * we want to keep only 5 entries
4336                          * allowing it to grow to 8. This
4337                          * mak sure we don't call discard
4338                          * soon for this list.
4339                          */
4340                         break;
4341                 }
4342         }
4343         spin_unlock(&lg->lg_prealloc_lock);
4344
4345         list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4346
4347                 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
4348                 if (ext4_mb_load_buddy(sb, group, &e4b)) {
4349                         ext4_error(sb, __func__, "Error in loading buddy "
4350                                         "information for %u", group);
4351                         continue;
4352                 }
4353                 ext4_lock_group(sb, group);
4354                 list_del(&pa->pa_group_list);
4355                 ext4_mb_release_group_pa(&e4b, pa, ac);
4356                 ext4_unlock_group(sb, group);
4357
4358                 ext4_mb_release_desc(&e4b);
4359                 list_del(&pa->u.pa_tmp_list);
4360                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4361         }
4362         if (ac)
4363                 kmem_cache_free(ext4_ac_cachep, ac);
4364 }
4365
4366 /*
4367  * We have incremented pa_count. So it cannot be freed at this
4368  * point. Also we hold lg_mutex. So no parallel allocation is
4369  * possible from this lg. That means pa_free cannot be updated.
4370  *
4371  * A parallel ext4_mb_discard_group_preallocations is possible.
4372  * which can cause the lg_prealloc_list to be updated.
4373  */
4374
4375 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4376 {
4377         int order, added = 0, lg_prealloc_count = 1;
4378         struct super_block *sb = ac->ac_sb;
4379         struct ext4_locality_group *lg = ac->ac_lg;
4380         struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4381
4382         order = fls(pa->pa_free) - 1;
4383         if (order > PREALLOC_TB_SIZE - 1)
4384                 /* The max size of hash table is PREALLOC_TB_SIZE */
4385                 order = PREALLOC_TB_SIZE - 1;
4386         /* Add the prealloc space to lg */
4387         rcu_read_lock();
4388         list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4389                                                 pa_inode_list) {
4390                 spin_lock(&tmp_pa->pa_lock);
4391                 if (tmp_pa->pa_deleted) {
4392                         spin_unlock(&tmp_pa->pa_lock);
4393                         continue;
4394                 }
4395                 if (!added && pa->pa_free < tmp_pa->pa_free) {
4396                         /* Add to the tail of the previous entry */
4397                         list_add_tail_rcu(&pa->pa_inode_list,
4398                                                 &tmp_pa->pa_inode_list);
4399                         added = 1;
4400                         /*
4401                          * we want to count the total
4402                          * number of entries in the list
4403                          */
4404                 }
4405                 spin_unlock(&tmp_pa->pa_lock);
4406                 lg_prealloc_count++;
4407         }
4408         if (!added)
4409                 list_add_tail_rcu(&pa->pa_inode_list,
4410                                         &lg->lg_prealloc_list[order]);
4411         rcu_read_unlock();
4412
4413         /* Now trim the list to be not more than 8 elements */
4414         if (lg_prealloc_count > 8) {
4415                 ext4_mb_discard_lg_preallocations(sb, lg,
4416                                                 order, lg_prealloc_count);
4417                 return;
4418         }
4419         return ;
4420 }
4421
4422 /*
4423  * release all resource we used in allocation
4424  */
4425 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4426 {
4427         struct ext4_prealloc_space *pa = ac->ac_pa;
4428         if (pa) {
4429                 if (pa->pa_type == MB_GROUP_PA) {
4430                         /* see comment in ext4_mb_use_group_pa() */
4431                         spin_lock(&pa->pa_lock);
4432                         pa->pa_pstart += ac->ac_b_ex.fe_len;
4433                         pa->pa_lstart += ac->ac_b_ex.fe_len;
4434                         pa->pa_free -= ac->ac_b_ex.fe_len;
4435                         pa->pa_len -= ac->ac_b_ex.fe_len;
4436                         spin_unlock(&pa->pa_lock);
4437                 }
4438         }
4439         if (ac->alloc_semp)
4440                 up_read(ac->alloc_semp);
4441         if (pa) {
4442                 /*
4443                  * We want to add the pa to the right bucket.
4444                  * Remove it from the list and while adding
4445                  * make sure the list to which we are adding
4446                  * doesn't grow big.  We need to release
4447                  * alloc_semp before calling ext4_mb_add_n_trim()
4448                  */
4449                 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4450                         spin_lock(pa->pa_obj_lock);
4451                         list_del_rcu(&pa->pa_inode_list);
4452                         spin_unlock(pa->pa_obj_lock);
4453                         ext4_mb_add_n_trim(ac);
4454                 }
4455                 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4456         }
4457         if (ac->ac_bitmap_page)
4458                 page_cache_release(ac->ac_bitmap_page);
4459         if (ac->ac_buddy_page)
4460                 page_cache_release(ac->ac_buddy_page);
4461         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4462                 mutex_unlock(&ac->ac_lg->lg_mutex);
4463         ext4_mb_collect_stats(ac);
4464         return 0;
4465 }
4466
4467 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4468 {
4469         ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4470         int ret;
4471         int freed = 0;
4472
4473         trace_mark(ext4_mb_discard_preallocations, "dev %s needed %d",
4474                    sb->s_id, needed);
4475         for (i = 0; i < ngroups && needed > 0; i++) {
4476                 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4477                 freed += ret;
4478                 needed -= ret;
4479         }
4480
4481         return freed;
4482 }
4483
4484 /*
4485  * Main entry point into mballoc to allocate blocks
4486  * it tries to use preallocation first, then falls back
4487  * to usual allocation
4488  */
4489 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4490                                  struct ext4_allocation_request *ar, int *errp)
4491 {
4492         int freed;
4493         struct ext4_allocation_context *ac = NULL;
4494         struct ext4_sb_info *sbi;
4495         struct super_block *sb;
4496         ext4_fsblk_t block = 0;
4497         unsigned int inquota = 0;
4498         unsigned int reserv_blks = 0;
4499
4500         sb = ar->inode->i_sb;
4501         sbi = EXT4_SB(sb);
4502
4503         trace_mark(ext4_request_blocks, "dev %s flags %u len %u ino %lu "
4504                    "lblk %llu goal %llu lleft %llu lright %llu "
4505                    "pleft %llu pright %llu ",
4506                    sb->s_id, ar->flags, ar->len,
4507                    ar->inode ? ar->inode->i_ino : 0,
4508                    (unsigned long long) ar->logical,
4509                    (unsigned long long) ar->goal,
4510                    (unsigned long long) ar->lleft,
4511                    (unsigned long long) ar->lright,
4512                    (unsigned long long) ar->pleft,
4513                    (unsigned long long) ar->pright);
4514
4515         /*
4516          * For delayed allocation, we could skip the ENOSPC and
4517          * EDQUOT check, as blocks and quotas have been already
4518          * reserved when data being copied into pagecache.
4519          */
4520         if (EXT4_I(ar->inode)->i_delalloc_reserved_flag)
4521                 ar->flags |= EXT4_MB_DELALLOC_RESERVED;
4522         else {
4523                 /* Without delayed allocation we need to verify
4524                  * there is enough free blocks to do block allocation
4525                  * and verify allocation doesn't exceed the quota limits.
4526                  */
4527                 while (ar->len && ext4_claim_free_blocks(sbi, ar->len)) {
4528                         /* let others to free the space */
4529                         yield();
4530                         ar->len = ar->len >> 1;
4531                 }
4532                 if (!ar->len) {
4533                         *errp = -ENOSPC;
4534                         return 0;
4535                 }
4536                 reserv_blks = ar->len;
4537                 while (ar->len && vfs_dq_alloc_block(ar->inode, ar->len)) {
4538                         ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4539                         ar->len--;
4540                 }
4541                 inquota = ar->len;
4542                 if (ar->len == 0) {
4543                         *errp = -EDQUOT;
4544                         goto out3;
4545                 }
4546         }
4547
4548         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4549         if (!ac) {
4550                 ar->len = 0;
4551                 *errp = -ENOMEM;
4552                 goto out1;
4553         }
4554
4555         *errp = ext4_mb_initialize_context(ac, ar);
4556         if (*errp) {
4557                 ar->len = 0;
4558                 goto out2;
4559         }
4560
4561         ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4562         if (!ext4_mb_use_preallocated(ac)) {
4563                 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4564                 ext4_mb_normalize_request(ac, ar);
4565 repeat:
4566                 /* allocate space in core */
4567                 ext4_mb_regular_allocator(ac);
4568
4569                 /* as we've just preallocated more space than
4570                  * user requested orinally, we store allocated
4571                  * space in a special descriptor */
4572                 if (ac->ac_status == AC_STATUS_FOUND &&
4573                                 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4574                         ext4_mb_new_preallocation(ac);
4575         }
4576         if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4577                 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_blks);
4578                 if (*errp ==  -EAGAIN) {
4579                         /*
4580                          * drop the reference that we took
4581                          * in ext4_mb_use_best_found
4582                          */
4583                         ext4_mb_release_context(ac);
4584                         ac->ac_b_ex.fe_group = 0;
4585                         ac->ac_b_ex.fe_start = 0;
4586                         ac->ac_b_ex.fe_len = 0;
4587                         ac->ac_status = AC_STATUS_CONTINUE;
4588                         goto repeat;
4589                 } else if (*errp) {
4590                         ac->ac_b_ex.fe_len = 0;
4591                         ar->len = 0;
4592                         ext4_mb_show_ac(ac);
4593                 } else {
4594                         block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4595                         ar->len = ac->ac_b_ex.fe_len;
4596                 }
4597         } else {
4598                 freed  = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4599                 if (freed)
4600                         goto repeat;
4601                 *errp = -ENOSPC;
4602                 ac->ac_b_ex.fe_len = 0;
4603                 ar->len = 0;
4604                 ext4_mb_show_ac(ac);
4605         }
4606
4607         ext4_mb_release_context(ac);
4608
4609 out2:
4610         kmem_cache_free(ext4_ac_cachep, ac);
4611 out1:
4612         if (inquota && ar->len < inquota)
4613                 vfs_dq_free_block(ar->inode, inquota - ar->len);
4614 out3:
4615         if (!ar->len) {
4616                 if (!EXT4_I(ar->inode)->i_delalloc_reserved_flag)
4617                         /* release all the reserved blocks if non delalloc */
4618                         percpu_counter_sub(&sbi->s_dirtyblocks_counter,
4619                                                 reserv_blks);
4620         }
4621
4622         trace_mark(ext4_allocate_blocks,
4623                    "dev %s block %llu flags %u len %u ino %lu "
4624                    "logical %llu goal %llu lleft %llu lright %llu "
4625                    "pleft %llu pright %llu ",
4626                    sb->s_id, (unsigned long long) block,
4627                    ar->flags, ar->len, ar->inode ? ar->inode->i_ino : 0,
4628                    (unsigned long long) ar->logical,
4629                    (unsigned long long) ar->goal,
4630                    (unsigned long long) ar->lleft,
4631                    (unsigned long long) ar->lright,
4632                    (unsigned long long) ar->pleft,
4633                    (unsigned long long) ar->pright);
4634
4635         return block;
4636 }
4637
4638 /*
4639  * We can merge two free data extents only if the physical blocks
4640  * are contiguous, AND the extents were freed by the same transaction,
4641  * AND the blocks are associated with the same group.
4642  */
4643 static int can_merge(struct ext4_free_data *entry1,
4644                         struct ext4_free_data *entry2)
4645 {
4646         if ((entry1->t_tid == entry2->t_tid) &&
4647             (entry1->group == entry2->group) &&
4648             ((entry1->start_blk + entry1->count) == entry2->start_blk))
4649                 return 1;
4650         return 0;
4651 }
4652
4653 static noinline_for_stack int
4654 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4655                       struct ext4_free_data *new_entry)
4656 {
4657         ext4_grpblk_t block;
4658         struct ext4_free_data *entry;
4659         struct ext4_group_info *db = e4b->bd_info;
4660         struct super_block *sb = e4b->bd_sb;
4661         struct ext4_sb_info *sbi = EXT4_SB(sb);
4662         struct rb_node **n = &db->bb_free_root.rb_node, *node;
4663         struct rb_node *parent = NULL, *new_node;
4664
4665         BUG_ON(!ext4_handle_valid(handle));
4666         BUG_ON(e4b->bd_bitmap_page == NULL);
4667         BUG_ON(e4b->bd_buddy_page == NULL);
4668
4669         new_node = &new_entry->node;
4670         block = new_entry->start_blk;
4671
4672         if (!*n) {
4673                 /* first free block exent. We need to
4674                    protect buddy cache from being freed,
4675                  * otherwise we'll refresh it from
4676                  * on-disk bitmap and lose not-yet-available
4677                  * blocks */
4678                 page_cache_get(e4b->bd_buddy_page);
4679                 page_cache_get(e4b->bd_bitmap_page);
4680         }
4681         while (*n) {
4682                 parent = *n;
4683                 entry = rb_entry(parent, struct ext4_free_data, node);
4684                 if (block < entry->start_blk)
4685                         n = &(*n)->rb_left;
4686                 else if (block >= (entry->start_blk + entry->count))
4687                         n = &(*n)->rb_right;
4688                 else {
4689                         ext4_grp_locked_error(sb, e4b->bd_group, __func__,
4690                                         "Double free of blocks %d (%d %d)",
4691                                         block, entry->start_blk, entry->count);
4692                         return 0;
4693                 }
4694         }
4695
4696         rb_link_node(new_node, parent, n);
4697         rb_insert_color(new_node, &db->bb_free_root);
4698
4699         /* Now try to see the extent can be merged to left and right */
4700         node = rb_prev(new_node);
4701         if (node) {
4702                 entry = rb_entry(node, struct ext4_free_data, node);
4703                 if (can_merge(entry, new_entry)) {
4704                         new_entry->start_blk = entry->start_blk;
4705                         new_entry->count += entry->count;
4706                         rb_erase(node, &(db->bb_free_root));
4707                         spin_lock(&sbi->s_md_lock);
4708                         list_del(&entry->list);
4709                         spin_unlock(&sbi->s_md_lock);
4710                         kmem_cache_free(ext4_free_ext_cachep, entry);
4711                 }
4712         }
4713
4714         node = rb_next(new_node);
4715         if (node) {
4716                 entry = rb_entry(node, struct ext4_free_data, node);
4717                 if (can_merge(new_entry, entry)) {
4718                         new_entry->count += entry->count;
4719                         rb_erase(node, &(db->bb_free_root));
4720                         spin_lock(&sbi->s_md_lock);
4721                         list_del(&entry->list);
4722                         spin_unlock(&sbi->s_md_lock);
4723                         kmem_cache_free(ext4_free_ext_cachep, entry);
4724                 }
4725         }
4726         /* Add the extent to transaction's private list */
4727         spin_lock(&sbi->s_md_lock);
4728         list_add(&new_entry->list, &handle->h_transaction->t_private_list);
4729         spin_unlock(&sbi->s_md_lock);
4730         return 0;
4731 }
4732
4733 /*
4734  * Main entry point into mballoc to free blocks
4735  */
4736 void ext4_mb_free_blocks(handle_t *handle, struct inode *inode,
4737                         unsigned long block, unsigned long count,
4738                         int metadata, unsigned long *freed)
4739 {
4740         struct buffer_head *bitmap_bh = NULL;
4741         struct super_block *sb = inode->i_sb;
4742         struct ext4_allocation_context *ac = NULL;
4743         struct ext4_group_desc *gdp;
4744         struct ext4_super_block *es;
4745         unsigned int overflow;
4746         ext4_grpblk_t bit;
4747         struct buffer_head *gd_bh;
4748         ext4_group_t block_group;
4749         struct ext4_sb_info *sbi;
4750         struct ext4_buddy e4b;
4751         int err = 0;
4752         int ret;
4753
4754         *freed = 0;
4755
4756         sbi = EXT4_SB(sb);
4757         es = EXT4_SB(sb)->s_es;
4758         if (block < le32_to_cpu(es->s_first_data_block) ||
4759             block + count < block ||
4760             block + count > ext4_blocks_count(es)) {
4761                 ext4_error(sb, __func__,
4762                             "Freeing blocks not in datazone - "
4763                             "block = %lu, count = %lu", block, count);
4764                 goto error_return;
4765         }
4766
4767         ext4_debug("freeing block %lu\n", block);
4768         trace_mark(ext4_free_blocks,
4769                    "dev %s block %llu count %lu metadata %d ino %lu",
4770                    sb->s_id, (unsigned long long) block, count, metadata,
4771                    inode ? inode->i_ino : 0);
4772
4773         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4774         if (ac) {
4775                 ac->ac_op = EXT4_MB_HISTORY_FREE;
4776                 ac->ac_inode = inode;
4777                 ac->ac_sb = sb;
4778         }
4779
4780 do_more:
4781         overflow = 0;
4782         ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4783
4784         /*
4785          * Check to see if we are freeing blocks across a group
4786          * boundary.
4787          */
4788         if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4789                 overflow = bit + count - EXT4_BLOCKS_PER_GROUP(sb);
4790                 count -= overflow;
4791         }
4792         bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4793         if (!bitmap_bh) {
4794                 err = -EIO;
4795                 goto error_return;
4796         }
4797         gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4798         if (!gdp) {
4799                 err = -EIO;
4800                 goto error_return;
4801         }
4802
4803         if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4804             in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4805             in_range(block, ext4_inode_table(sb, gdp),
4806                       EXT4_SB(sb)->s_itb_per_group) ||
4807             in_range(block + count - 1, ext4_inode_table(sb, gdp),
4808                       EXT4_SB(sb)->s_itb_per_group)) {
4809
4810                 ext4_error(sb, __func__,
4811                            "Freeing blocks in system zone - "
4812                            "Block = %lu, count = %lu", block, count);
4813                 /* err = 0. ext4_std_error should be a no op */
4814                 goto error_return;
4815         }
4816
4817         BUFFER_TRACE(bitmap_bh, "getting write access");
4818         err = ext4_journal_get_write_access(handle, bitmap_bh);
4819         if (err)
4820                 goto error_return;
4821
4822         /*
4823          * We are about to modify some metadata.  Call the journal APIs
4824          * to unshare ->b_data if a currently-committing transaction is
4825          * using it
4826          */
4827         BUFFER_TRACE(gd_bh, "get_write_access");
4828         err = ext4_journal_get_write_access(handle, gd_bh);
4829         if (err)
4830                 goto error_return;
4831 #ifdef AGGRESSIVE_CHECK
4832         {
4833                 int i;
4834                 for (i = 0; i < count; i++)
4835                         BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4836         }
4837 #endif
4838         if (ac) {
4839                 ac->ac_b_ex.fe_group = block_group;
4840                 ac->ac_b_ex.fe_start = bit;
4841                 ac->ac_b_ex.fe_len = count;
4842                 ext4_mb_store_history(ac);
4843         }
4844
4845         err = ext4_mb_load_buddy(sb, block_group, &e4b);
4846         if (err)
4847                 goto error_return;
4848         if (metadata && ext4_handle_valid(handle)) {
4849                 struct ext4_free_data *new_entry;
4850                 /*
4851                  * blocks being freed are metadata. these blocks shouldn't
4852                  * be used until this transaction is committed
4853                  */
4854                 new_entry  = kmem_cache_alloc(ext4_free_ext_cachep, GFP_NOFS);
4855                 new_entry->start_blk = bit;
4856                 new_entry->group  = block_group;
4857                 new_entry->count = count;
4858                 new_entry->t_tid = handle->h_transaction->t_tid;
4859                 ext4_lock_group(sb, block_group);
4860                 mb_clear_bits(sb_bgl_lock(sbi, block_group), bitmap_bh->b_data,
4861                                 bit, count);
4862                 ext4_mb_free_metadata(handle, &e4b, new_entry);
4863                 ext4_unlock_group(sb, block_group);
4864         } else {
4865                 ext4_lock_group(sb, block_group);
4866                 /* need to update group_info->bb_free and bitmap
4867                  * with group lock held. generate_buddy look at
4868                  * them with group lock_held
4869                  */
4870                 mb_clear_bits(sb_bgl_lock(sbi, block_group), bitmap_bh->b_data,
4871                                 bit, count);
4872                 mb_free_blocks(inode, &e4b, bit, count);
4873                 ext4_mb_return_to_preallocation(inode, &e4b, block, count);
4874                 ext4_unlock_group(sb, block_group);
4875         }
4876
4877         spin_lock(sb_bgl_lock(sbi, block_group));
4878         ret = ext4_free_blks_count(sb, gdp) + count;
4879         ext4_free_blks_set(sb, gdp, ret);
4880         gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4881         spin_unlock(sb_bgl_lock(sbi, block_group));
4882         percpu_counter_add(&sbi->s_freeblocks_counter, count);
4883
4884         if (sbi->s_log_groups_per_flex) {
4885                 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4886                 atomic_add(count, &sbi->s_flex_groups[flex_group].free_blocks);
4887         }
4888
4889         ext4_mb_release_desc(&e4b);
4890
4891         *freed += count;
4892
4893         /* We dirtied the bitmap block */
4894         BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4895         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4896
4897         /* And the group descriptor block */
4898         BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4899         ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4900         if (!err)
4901                 err = ret;
4902
4903         if (overflow && !err) {
4904                 block += count;
4905                 count = overflow;
4906                 put_bh(bitmap_bh);
4907                 goto do_more;
4908         }
4909         sb->s_dirt = 1;
4910 error_return:
4911         brelse(bitmap_bh);
4912         ext4_std_error(sb, err);
4913         if (ac)
4914                 kmem_cache_free(ext4_ac_cachep, ac);
4915         return;
4916 }