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