ext4: code cleanup
[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                         spin_unlock(sb_bgl_lock(EXT4_SB(sb), first_group + i));
808                         unlock_buffer(bh[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                 if (lock)
1074                         mb_clear_bit_atomic(lock, cur, bm);
1075                 else
1076                         mb_clear_bit(cur, bm);
1077                 cur++;
1078         }
1079 }
1080
1081 static void mb_set_bits(spinlock_t *lock, void *bm, int cur, int len)
1082 {
1083         __u32 *addr;
1084
1085         len = cur + len;
1086         while (cur < len) {
1087                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1088                         /* fast path: set whole word at once */
1089                         addr = bm + (cur >> 3);
1090                         *addr = 0xffffffff;
1091                         cur += 32;
1092                         continue;
1093                 }
1094                 if (lock)
1095                         mb_set_bit_atomic(lock, cur, bm);
1096                 else
1097                         mb_set_bit(cur, bm);
1098                 cur++;
1099         }
1100 }
1101
1102 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1103                           int first, int count)
1104 {
1105         int block = 0;
1106         int max = 0;
1107         int order;
1108         void *buddy;
1109         void *buddy2;
1110         struct super_block *sb = e4b->bd_sb;
1111
1112         BUG_ON(first + count > (sb->s_blocksize << 3));
1113         BUG_ON(!ext4_is_group_locked(sb, e4b->bd_group));
1114         mb_check_buddy(e4b);
1115         mb_free_blocks_double(inode, e4b, first, count);
1116
1117         e4b->bd_info->bb_free += count;
1118         if (first < e4b->bd_info->bb_first_free)
1119                 e4b->bd_info->bb_first_free = first;
1120
1121         /* let's maintain fragments counter */
1122         if (first != 0)
1123                 block = !mb_test_bit(first - 1, EXT4_MB_BITMAP(e4b));
1124         if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
1125                 max = !mb_test_bit(first + count, EXT4_MB_BITMAP(e4b));
1126         if (block && max)
1127                 e4b->bd_info->bb_fragments--;
1128         else if (!block && !max)
1129                 e4b->bd_info->bb_fragments++;
1130
1131         /* let's maintain buddy itself */
1132         while (count-- > 0) {
1133                 block = first++;
1134                 order = 0;
1135
1136                 if (!mb_test_bit(block, EXT4_MB_BITMAP(e4b))) {
1137                         ext4_fsblk_t blocknr;
1138                         blocknr = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb);
1139                         blocknr += block;
1140                         blocknr +=
1141                             le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
1142                         ext4_grp_locked_error(sb, e4b->bd_group,
1143                                    __func__, "double-free of inode"
1144                                    " %lu's block %llu(bit %u in group %u)",
1145                                    inode ? inode->i_ino : 0, blocknr, block,
1146                                    e4b->bd_group);
1147                 }
1148                 mb_clear_bit(block, EXT4_MB_BITMAP(e4b));
1149                 e4b->bd_info->bb_counters[order]++;
1150
1151                 /* start of the buddy */
1152                 buddy = mb_find_buddy(e4b, order, &max);
1153
1154                 do {
1155                         block &= ~1UL;
1156                         if (mb_test_bit(block, buddy) ||
1157                                         mb_test_bit(block + 1, buddy))
1158                                 break;
1159
1160                         /* both the buddies are free, try to coalesce them */
1161                         buddy2 = mb_find_buddy(e4b, order + 1, &max);
1162
1163                         if (!buddy2)
1164                                 break;
1165
1166                         if (order > 0) {
1167                                 /* for special purposes, we don't set
1168                                  * free bits in bitmap */
1169                                 mb_set_bit(block, buddy);
1170                                 mb_set_bit(block + 1, buddy);
1171                         }
1172                         e4b->bd_info->bb_counters[order]--;
1173                         e4b->bd_info->bb_counters[order]--;
1174
1175                         block = block >> 1;
1176                         order++;
1177                         e4b->bd_info->bb_counters[order]++;
1178
1179                         mb_clear_bit(block, buddy2);
1180                         buddy = buddy2;
1181                 } while (1);
1182         }
1183         mb_check_buddy(e4b);
1184 }
1185
1186 static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
1187                                 int needed, struct ext4_free_extent *ex)
1188 {
1189         int next = block;
1190         int max;
1191         int ord;
1192         void *buddy;
1193
1194         BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
1195         BUG_ON(ex == NULL);
1196
1197         buddy = mb_find_buddy(e4b, order, &max);
1198         BUG_ON(buddy == NULL);
1199         BUG_ON(block >= max);
1200         if (mb_test_bit(block, buddy)) {
1201                 ex->fe_len = 0;
1202                 ex->fe_start = 0;
1203                 ex->fe_group = 0;
1204                 return 0;
1205         }
1206
1207         /* FIXME dorp order completely ? */
1208         if (likely(order == 0)) {
1209                 /* find actual order */
1210                 order = mb_find_order_for_block(e4b, block);
1211                 block = block >> order;
1212         }
1213
1214         ex->fe_len = 1 << order;
1215         ex->fe_start = block << order;
1216         ex->fe_group = e4b->bd_group;
1217
1218         /* calc difference from given start */
1219         next = next - ex->fe_start;
1220         ex->fe_len -= next;
1221         ex->fe_start += next;
1222
1223         while (needed > ex->fe_len &&
1224                (buddy = mb_find_buddy(e4b, order, &max))) {
1225
1226                 if (block + 1 >= max)
1227                         break;
1228
1229                 next = (block + 1) * (1 << order);
1230                 if (mb_test_bit(next, EXT4_MB_BITMAP(e4b)))
1231                         break;
1232
1233                 ord = mb_find_order_for_block(e4b, next);
1234
1235                 order = ord;
1236                 block = next >> order;
1237                 ex->fe_len += 1 << order;
1238         }
1239
1240         BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1241         return ex->fe_len;
1242 }
1243
1244 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1245 {
1246         int ord;
1247         int mlen = 0;
1248         int max = 0;
1249         int cur;
1250         int start = ex->fe_start;
1251         int len = ex->fe_len;
1252         unsigned ret = 0;
1253         int len0 = len;
1254         void *buddy;
1255
1256         BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1257         BUG_ON(e4b->bd_group != ex->fe_group);
1258         BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
1259         mb_check_buddy(e4b);
1260         mb_mark_used_double(e4b, start, len);
1261
1262         e4b->bd_info->bb_free -= len;
1263         if (e4b->bd_info->bb_first_free == start)
1264                 e4b->bd_info->bb_first_free += len;
1265
1266         /* let's maintain fragments counter */
1267         if (start != 0)
1268                 mlen = !mb_test_bit(start - 1, EXT4_MB_BITMAP(e4b));
1269         if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1270                 max = !mb_test_bit(start + len, EXT4_MB_BITMAP(e4b));
1271         if (mlen && max)
1272                 e4b->bd_info->bb_fragments++;
1273         else if (!mlen && !max)
1274                 e4b->bd_info->bb_fragments--;
1275
1276         /* let's maintain buddy itself */
1277         while (len) {
1278                 ord = mb_find_order_for_block(e4b, start);
1279
1280                 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1281                         /* the whole chunk may be allocated at once! */
1282                         mlen = 1 << ord;
1283                         buddy = mb_find_buddy(e4b, ord, &max);
1284                         BUG_ON((start >> ord) >= max);
1285                         mb_set_bit(start >> ord, buddy);
1286                         e4b->bd_info->bb_counters[ord]--;
1287                         start += mlen;
1288                         len -= mlen;
1289                         BUG_ON(len < 0);
1290                         continue;
1291                 }
1292
1293                 /* store for history */
1294                 if (ret == 0)
1295                         ret = len | (ord << 16);
1296
1297                 /* we have to split large buddy */
1298                 BUG_ON(ord <= 0);
1299                 buddy = mb_find_buddy(e4b, ord, &max);
1300                 mb_set_bit(start >> ord, buddy);
1301                 e4b->bd_info->bb_counters[ord]--;
1302
1303                 ord--;
1304                 cur = (start >> ord) & ~1U;
1305                 buddy = mb_find_buddy(e4b, ord, &max);
1306                 mb_clear_bit(cur, buddy);
1307                 mb_clear_bit(cur + 1, buddy);
1308                 e4b->bd_info->bb_counters[ord]++;
1309                 e4b->bd_info->bb_counters[ord]++;
1310         }
1311
1312         mb_set_bits(sb_bgl_lock(EXT4_SB(e4b->bd_sb), ex->fe_group),
1313                         EXT4_MB_BITMAP(e4b), ex->fe_start, len0);
1314         mb_check_buddy(e4b);
1315
1316         return ret;
1317 }
1318
1319 /*
1320  * Must be called under group lock!
1321  */
1322 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1323                                         struct ext4_buddy *e4b)
1324 {
1325         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1326         int ret;
1327
1328         BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1329         BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1330
1331         ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1332         ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1333         ret = mb_mark_used(e4b, &ac->ac_b_ex);
1334
1335         /* preallocation can change ac_b_ex, thus we store actually
1336          * allocated blocks for history */
1337         ac->ac_f_ex = ac->ac_b_ex;
1338
1339         ac->ac_status = AC_STATUS_FOUND;
1340         ac->ac_tail = ret & 0xffff;
1341         ac->ac_buddy = ret >> 16;
1342
1343         /*
1344          * take the page reference. We want the page to be pinned
1345          * so that we don't get a ext4_mb_init_cache_call for this
1346          * group until we update the bitmap. That would mean we
1347          * double allocate blocks. The reference is dropped
1348          * in ext4_mb_release_context
1349          */
1350         ac->ac_bitmap_page = e4b->bd_bitmap_page;
1351         get_page(ac->ac_bitmap_page);
1352         ac->ac_buddy_page = e4b->bd_buddy_page;
1353         get_page(ac->ac_buddy_page);
1354
1355         /* store last allocated for subsequent stream allocation */
1356         if ((ac->ac_flags & EXT4_MB_HINT_DATA)) {
1357                 spin_lock(&sbi->s_md_lock);
1358                 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1359                 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1360                 spin_unlock(&sbi->s_md_lock);
1361         }
1362 }
1363
1364 /*
1365  * regular allocator, for general purposes allocation
1366  */
1367
1368 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1369                                         struct ext4_buddy *e4b,
1370                                         int finish_group)
1371 {
1372         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1373         struct ext4_free_extent *bex = &ac->ac_b_ex;
1374         struct ext4_free_extent *gex = &ac->ac_g_ex;
1375         struct ext4_free_extent ex;
1376         int max;
1377
1378         if (ac->ac_status == AC_STATUS_FOUND)
1379                 return;
1380         /*
1381          * We don't want to scan for a whole year
1382          */
1383         if (ac->ac_found > sbi->s_mb_max_to_scan &&
1384                         !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1385                 ac->ac_status = AC_STATUS_BREAK;
1386                 return;
1387         }
1388
1389         /*
1390          * Haven't found good chunk so far, let's continue
1391          */
1392         if (bex->fe_len < gex->fe_len)
1393                 return;
1394
1395         if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1396                         && bex->fe_group == e4b->bd_group) {
1397                 /* recheck chunk's availability - we don't know
1398                  * when it was found (within this lock-unlock
1399                  * period or not) */
1400                 max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
1401                 if (max >= gex->fe_len) {
1402                         ext4_mb_use_best_found(ac, e4b);
1403                         return;
1404                 }
1405         }
1406 }
1407
1408 /*
1409  * The routine checks whether found extent is good enough. If it is,
1410  * then the extent gets marked used and flag is set to the context
1411  * to stop scanning. Otherwise, the extent is compared with the
1412  * previous found extent and if new one is better, then it's stored
1413  * in the context. Later, the best found extent will be used, if
1414  * mballoc can't find good enough extent.
1415  *
1416  * FIXME: real allocation policy is to be designed yet!
1417  */
1418 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1419                                         struct ext4_free_extent *ex,
1420                                         struct ext4_buddy *e4b)
1421 {
1422         struct ext4_free_extent *bex = &ac->ac_b_ex;
1423         struct ext4_free_extent *gex = &ac->ac_g_ex;
1424
1425         BUG_ON(ex->fe_len <= 0);
1426         BUG_ON(ex->fe_len >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1427         BUG_ON(ex->fe_start >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1428         BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1429
1430         ac->ac_found++;
1431
1432         /*
1433          * The special case - take what you catch first
1434          */
1435         if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1436                 *bex = *ex;
1437                 ext4_mb_use_best_found(ac, e4b);
1438                 return;
1439         }
1440
1441         /*
1442          * Let's check whether the chuck is good enough
1443          */
1444         if (ex->fe_len == gex->fe_len) {
1445                 *bex = *ex;
1446                 ext4_mb_use_best_found(ac, e4b);
1447                 return;
1448         }
1449
1450         /*
1451          * If this is first found extent, just store it in the context
1452          */
1453         if (bex->fe_len == 0) {
1454                 *bex = *ex;
1455                 return;
1456         }
1457
1458         /*
1459          * If new found extent is better, store it in the context
1460          */
1461         if (bex->fe_len < gex->fe_len) {
1462                 /* if the request isn't satisfied, any found extent
1463                  * larger than previous best one is better */
1464                 if (ex->fe_len > bex->fe_len)
1465                         *bex = *ex;
1466         } else if (ex->fe_len > gex->fe_len) {
1467                 /* if the request is satisfied, then we try to find
1468                  * an extent that still satisfy the request, but is
1469                  * smaller than previous one */
1470                 if (ex->fe_len < bex->fe_len)
1471                         *bex = *ex;
1472         }
1473
1474         ext4_mb_check_limits(ac, e4b, 0);
1475 }
1476
1477 static int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1478                                         struct ext4_buddy *e4b)
1479 {
1480         struct ext4_free_extent ex = ac->ac_b_ex;
1481         ext4_group_t group = ex.fe_group;
1482         int max;
1483         int err;
1484
1485         BUG_ON(ex.fe_len <= 0);
1486         err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1487         if (err)
1488                 return err;
1489
1490         ext4_lock_group(ac->ac_sb, group);
1491         max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
1492
1493         if (max > 0) {
1494                 ac->ac_b_ex = ex;
1495                 ext4_mb_use_best_found(ac, e4b);
1496         }
1497
1498         ext4_unlock_group(ac->ac_sb, group);
1499         ext4_mb_release_desc(e4b);
1500
1501         return 0;
1502 }
1503
1504 static int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1505                                 struct ext4_buddy *e4b)
1506 {
1507         ext4_group_t group = ac->ac_g_ex.fe_group;
1508         int max;
1509         int err;
1510         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1511         struct ext4_super_block *es = sbi->s_es;
1512         struct ext4_free_extent ex;
1513
1514         if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1515                 return 0;
1516
1517         err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1518         if (err)
1519                 return err;
1520
1521         ext4_lock_group(ac->ac_sb, group);
1522         max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
1523                              ac->ac_g_ex.fe_len, &ex);
1524
1525         if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1526                 ext4_fsblk_t start;
1527
1528                 start = (e4b->bd_group * EXT4_BLOCKS_PER_GROUP(ac->ac_sb)) +
1529                         ex.fe_start + le32_to_cpu(es->s_first_data_block);
1530                 /* use do_div to get remainder (would be 64-bit modulo) */
1531                 if (do_div(start, sbi->s_stripe) == 0) {
1532                         ac->ac_found++;
1533                         ac->ac_b_ex = ex;
1534                         ext4_mb_use_best_found(ac, e4b);
1535                 }
1536         } else if (max >= ac->ac_g_ex.fe_len) {
1537                 BUG_ON(ex.fe_len <= 0);
1538                 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1539                 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1540                 ac->ac_found++;
1541                 ac->ac_b_ex = ex;
1542                 ext4_mb_use_best_found(ac, e4b);
1543         } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1544                 /* Sometimes, caller may want to merge even small
1545                  * number of blocks to an existing extent */
1546                 BUG_ON(ex.fe_len <= 0);
1547                 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1548                 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1549                 ac->ac_found++;
1550                 ac->ac_b_ex = ex;
1551                 ext4_mb_use_best_found(ac, e4b);
1552         }
1553         ext4_unlock_group(ac->ac_sb, group);
1554         ext4_mb_release_desc(e4b);
1555
1556         return 0;
1557 }
1558
1559 /*
1560  * The routine scans buddy structures (not bitmap!) from given order
1561  * to max order and tries to find big enough chunk to satisfy the req
1562  */
1563 static void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1564                                         struct ext4_buddy *e4b)
1565 {
1566         struct super_block *sb = ac->ac_sb;
1567         struct ext4_group_info *grp = e4b->bd_info;
1568         void *buddy;
1569         int i;
1570         int k;
1571         int max;
1572
1573         BUG_ON(ac->ac_2order <= 0);
1574         for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1575                 if (grp->bb_counters[i] == 0)
1576                         continue;
1577
1578                 buddy = mb_find_buddy(e4b, i, &max);
1579                 BUG_ON(buddy == NULL);
1580
1581                 k = mb_find_next_zero_bit(buddy, max, 0);
1582                 BUG_ON(k >= max);
1583
1584                 ac->ac_found++;
1585
1586                 ac->ac_b_ex.fe_len = 1 << i;
1587                 ac->ac_b_ex.fe_start = k << i;
1588                 ac->ac_b_ex.fe_group = e4b->bd_group;
1589
1590                 ext4_mb_use_best_found(ac, e4b);
1591
1592                 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1593
1594                 if (EXT4_SB(sb)->s_mb_stats)
1595                         atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1596
1597                 break;
1598         }
1599 }
1600
1601 /*
1602  * The routine scans the group and measures all found extents.
1603  * In order to optimize scanning, caller must pass number of
1604  * free blocks in the group, so the routine can know upper limit.
1605  */
1606 static void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1607                                         struct ext4_buddy *e4b)
1608 {
1609         struct super_block *sb = ac->ac_sb;
1610         void *bitmap = EXT4_MB_BITMAP(e4b);
1611         struct ext4_free_extent ex;
1612         int i;
1613         int free;
1614
1615         free = e4b->bd_info->bb_free;
1616         BUG_ON(free <= 0);
1617
1618         i = e4b->bd_info->bb_first_free;
1619
1620         while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1621                 i = mb_find_next_zero_bit(bitmap,
1622                                                 EXT4_BLOCKS_PER_GROUP(sb), i);
1623                 if (i >= EXT4_BLOCKS_PER_GROUP(sb)) {
1624                         /*
1625                          * IF we have corrupt bitmap, we won't find any
1626                          * free blocks even though group info says we
1627                          * we have free blocks
1628                          */
1629                         ext4_grp_locked_error(sb, e4b->bd_group,
1630                                         __func__, "%d free blocks as per "
1631                                         "group info. But bitmap says 0",
1632                                         free);
1633                         break;
1634                 }
1635
1636                 mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
1637                 BUG_ON(ex.fe_len <= 0);
1638                 if (free < ex.fe_len) {
1639                         ext4_grp_locked_error(sb, e4b->bd_group,
1640                                         __func__, "%d free blocks as per "
1641                                         "group info. But got %d blocks",
1642                                         free, ex.fe_len);
1643                         /*
1644                          * The number of free blocks differs. This mostly
1645                          * indicate that the bitmap is corrupt. So exit
1646                          * without claiming the space.
1647                          */
1648                         break;
1649                 }
1650
1651                 ext4_mb_measure_extent(ac, &ex, e4b);
1652
1653                 i += ex.fe_len;
1654                 free -= ex.fe_len;
1655         }
1656
1657         ext4_mb_check_limits(ac, e4b, 1);
1658 }
1659
1660 /*
1661  * This is a special case for storages like raid5
1662  * we try to find stripe-aligned chunks for stripe-size requests
1663  * XXX should do so at least for multiples of stripe size as well
1664  */
1665 static void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1666                                  struct ext4_buddy *e4b)
1667 {
1668         struct super_block *sb = ac->ac_sb;
1669         struct ext4_sb_info *sbi = EXT4_SB(sb);
1670         void *bitmap = EXT4_MB_BITMAP(e4b);
1671         struct ext4_free_extent ex;
1672         ext4_fsblk_t first_group_block;
1673         ext4_fsblk_t a;
1674         ext4_grpblk_t i;
1675         int max;
1676
1677         BUG_ON(sbi->s_stripe == 0);
1678
1679         /* find first stripe-aligned block in group */
1680         first_group_block = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb)
1681                 + le32_to_cpu(sbi->s_es->s_first_data_block);
1682         a = first_group_block + sbi->s_stripe - 1;
1683         do_div(a, sbi->s_stripe);
1684         i = (a * sbi->s_stripe) - first_group_block;
1685
1686         while (i < EXT4_BLOCKS_PER_GROUP(sb)) {
1687                 if (!mb_test_bit(i, bitmap)) {
1688                         max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
1689                         if (max >= sbi->s_stripe) {
1690                                 ac->ac_found++;
1691                                 ac->ac_b_ex = ex;
1692                                 ext4_mb_use_best_found(ac, e4b);
1693                                 break;
1694                         }
1695                 }
1696                 i += sbi->s_stripe;
1697         }
1698 }
1699
1700 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
1701                                 ext4_group_t group, int cr)
1702 {
1703         unsigned free, fragments;
1704         unsigned i, bits;
1705         struct ext4_group_desc *desc;
1706         struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1707
1708         BUG_ON(cr < 0 || cr >= 4);
1709         BUG_ON(EXT4_MB_GRP_NEED_INIT(grp));
1710
1711         free = grp->bb_free;
1712         fragments = grp->bb_fragments;
1713         if (free == 0)
1714                 return 0;
1715         if (fragments == 0)
1716                 return 0;
1717
1718         switch (cr) {
1719         case 0:
1720                 BUG_ON(ac->ac_2order == 0);
1721                 /* If this group is uninitialized, skip it initially */
1722                 desc = ext4_get_group_desc(ac->ac_sb, group, NULL);
1723                 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))
1724                         return 0;
1725
1726                 bits = ac->ac_sb->s_blocksize_bits + 1;
1727                 for (i = ac->ac_2order; i <= bits; i++)
1728                         if (grp->bb_counters[i] > 0)
1729                                 return 1;
1730                 break;
1731         case 1:
1732                 if ((free / fragments) >= ac->ac_g_ex.fe_len)
1733                         return 1;
1734                 break;
1735         case 2:
1736                 if (free >= ac->ac_g_ex.fe_len)
1737                         return 1;
1738                 break;
1739         case 3:
1740                 return 1;
1741         default:
1742                 BUG();
1743         }
1744
1745         return 0;
1746 }
1747
1748 /*
1749  * lock the group_info alloc_sem of all the groups
1750  * belonging to the same buddy cache page. This
1751  * make sure other parallel operation on the buddy
1752  * cache doesn't happen  whild holding the buddy cache
1753  * lock
1754  */
1755 int ext4_mb_get_buddy_cache_lock(struct super_block *sb, ext4_group_t group)
1756 {
1757         int i;
1758         int block, pnum;
1759         int blocks_per_page;
1760         int groups_per_page;
1761         ext4_group_t first_group;
1762         struct ext4_group_info *grp;
1763
1764         blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1765         /*
1766          * the buddy cache inode stores the block bitmap
1767          * and buddy information in consecutive blocks.
1768          * So for each group we need two blocks.
1769          */
1770         block = group * 2;
1771         pnum = block / blocks_per_page;
1772         first_group = pnum * blocks_per_page / 2;
1773
1774         groups_per_page = blocks_per_page >> 1;
1775         if (groups_per_page == 0)
1776                 groups_per_page = 1;
1777         /* read all groups the page covers into the cache */
1778         for (i = 0; i < groups_per_page; i++) {
1779
1780                 if ((first_group + i) >= EXT4_SB(sb)->s_groups_count)
1781                         break;
1782                 grp = ext4_get_group_info(sb, first_group + i);
1783                 /* take all groups write allocation
1784                  * semaphore. This make sure there is
1785                  * no block allocation going on in any
1786                  * of that groups
1787                  */
1788                 down_write_nested(&grp->alloc_sem, i);
1789         }
1790         return i;
1791 }
1792
1793 void ext4_mb_put_buddy_cache_lock(struct super_block *sb,
1794                                         ext4_group_t group, int locked_group)
1795 {
1796         int i;
1797         int block, pnum;
1798         int blocks_per_page;
1799         ext4_group_t first_group;
1800         struct ext4_group_info *grp;
1801
1802         blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1803         /*
1804          * the buddy cache inode stores the block bitmap
1805          * and buddy information in consecutive blocks.
1806          * So for each group we need two blocks.
1807          */
1808         block = group * 2;
1809         pnum = block / blocks_per_page;
1810         first_group = pnum * blocks_per_page / 2;
1811         /* release locks on all the groups */
1812         for (i = 0; i < locked_group; i++) {
1813
1814                 grp = ext4_get_group_info(sb, first_group + i);
1815                 /* take all groups write allocation
1816                  * semaphore. This make sure there is
1817                  * no block allocation going on in any
1818                  * of that groups
1819                  */
1820                 up_write(&grp->alloc_sem);
1821         }
1822
1823 }
1824
1825 static int ext4_mb_init_group(struct super_block *sb, ext4_group_t group)
1826 {
1827
1828         int ret;
1829         void *bitmap;
1830         int blocks_per_page;
1831         int block, pnum, poff;
1832         int num_grp_locked = 0;
1833         struct ext4_group_info *this_grp;
1834         struct ext4_sb_info *sbi = EXT4_SB(sb);
1835         struct inode *inode = sbi->s_buddy_cache;
1836         struct page *page = NULL, *bitmap_page = NULL;
1837
1838         mb_debug("init group %lu\n", group);
1839         blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1840         this_grp = ext4_get_group_info(sb, group);
1841         /*
1842          * This ensures we don't add group
1843          * to this buddy cache via resize
1844          */
1845         num_grp_locked =  ext4_mb_get_buddy_cache_lock(sb, group);
1846         if (!EXT4_MB_GRP_NEED_INIT(this_grp)) {
1847                 /*
1848                  * somebody initialized the group
1849                  * return without doing anything
1850                  */
1851                 ret = 0;
1852                 goto err;
1853         }
1854         /*
1855          * the buddy cache inode stores the block bitmap
1856          * and buddy information in consecutive blocks.
1857          * So for each group we need two blocks.
1858          */
1859         block = group * 2;
1860         pnum = block / blocks_per_page;
1861         poff = block % blocks_per_page;
1862         page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1863         if (page) {
1864                 BUG_ON(page->mapping != inode->i_mapping);
1865                 ret = ext4_mb_init_cache(page, NULL);
1866                 if (ret) {
1867                         unlock_page(page);
1868                         goto err;
1869                 }
1870                 unlock_page(page);
1871         }
1872         if (page == NULL || !PageUptodate(page)) {
1873                 ret = -EIO;
1874                 goto err;
1875         }
1876         mark_page_accessed(page);
1877         bitmap_page = page;
1878         bitmap = page_address(page) + (poff * sb->s_blocksize);
1879
1880         /* init buddy cache */
1881         block++;
1882         pnum = block / blocks_per_page;
1883         poff = block % blocks_per_page;
1884         page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1885         if (page == bitmap_page) {
1886                 /*
1887                  * If both the bitmap and buddy are in
1888                  * the same page we don't need to force
1889                  * init the buddy
1890                  */
1891                 unlock_page(page);
1892         } else if (page) {
1893                 BUG_ON(page->mapping != inode->i_mapping);
1894                 ret = ext4_mb_init_cache(page, bitmap);
1895                 if (ret) {
1896                         unlock_page(page);
1897                         goto err;
1898                 }
1899                 unlock_page(page);
1900         }
1901         if (page == NULL || !PageUptodate(page)) {
1902                 ret = -EIO;
1903                 goto err;
1904         }
1905         mark_page_accessed(page);
1906 err:
1907         ext4_mb_put_buddy_cache_lock(sb, group, num_grp_locked);
1908         if (bitmap_page)
1909                 page_cache_release(bitmap_page);
1910         if (page)
1911                 page_cache_release(page);
1912         return ret;
1913 }
1914
1915 static noinline_for_stack int
1916 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
1917 {
1918         ext4_group_t group;
1919         ext4_group_t i;
1920         int cr;
1921         int err = 0;
1922         int bsbits;
1923         struct ext4_sb_info *sbi;
1924         struct super_block *sb;
1925         struct ext4_buddy e4b;
1926         loff_t size, isize;
1927
1928         sb = ac->ac_sb;
1929         sbi = EXT4_SB(sb);
1930         BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1931
1932         /* first, try the goal */
1933         err = ext4_mb_find_by_goal(ac, &e4b);
1934         if (err || ac->ac_status == AC_STATUS_FOUND)
1935                 goto out;
1936
1937         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
1938                 goto out;
1939
1940         /*
1941          * ac->ac2_order is set only if the fe_len is a power of 2
1942          * if ac2_order is set we also set criteria to 0 so that we
1943          * try exact allocation using buddy.
1944          */
1945         i = fls(ac->ac_g_ex.fe_len);
1946         ac->ac_2order = 0;
1947         /*
1948          * We search using buddy data only if the order of the request
1949          * is greater than equal to the sbi_s_mb_order2_reqs
1950          * You can tune it via /proc/fs/ext4/<partition>/order2_req
1951          */
1952         if (i >= sbi->s_mb_order2_reqs) {
1953                 /*
1954                  * This should tell if fe_len is exactly power of 2
1955                  */
1956                 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
1957                         ac->ac_2order = i - 1;
1958         }
1959
1960         bsbits = ac->ac_sb->s_blocksize_bits;
1961         /* if stream allocation is enabled, use global goal */
1962         size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
1963         isize = i_size_read(ac->ac_inode) >> bsbits;
1964         if (size < isize)
1965                 size = isize;
1966
1967         if (size < sbi->s_mb_stream_request &&
1968                         (ac->ac_flags & EXT4_MB_HINT_DATA)) {
1969                 /* TBD: may be hot point */
1970                 spin_lock(&sbi->s_md_lock);
1971                 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
1972                 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
1973                 spin_unlock(&sbi->s_md_lock);
1974         }
1975         /* Let's just scan groups to find more-less suitable blocks */
1976         cr = ac->ac_2order ? 0 : 1;
1977         /*
1978          * cr == 0 try to get exact allocation,
1979          * cr == 3  try to get anything
1980          */
1981 repeat:
1982         for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
1983                 ac->ac_criteria = cr;
1984                 /*
1985                  * searching for the right group start
1986                  * from the goal value specified
1987                  */
1988                 group = ac->ac_g_ex.fe_group;
1989
1990                 for (i = 0; i < EXT4_SB(sb)->s_groups_count; group++, i++) {
1991                         struct ext4_group_info *grp;
1992                         struct ext4_group_desc *desc;
1993
1994                         if (group == EXT4_SB(sb)->s_groups_count)
1995                                 group = 0;
1996
1997                         /* quick check to skip empty groups */
1998                         grp = ext4_get_group_info(sb, group);
1999                         if (grp->bb_free == 0)
2000                                 continue;
2001
2002                         /*
2003                          * if the group is already init we check whether it is
2004                          * a good group and if not we don't load the buddy
2005                          */
2006                         if (EXT4_MB_GRP_NEED_INIT(grp)) {
2007                                 /*
2008                                  * we need full data about the group
2009                                  * to make a good selection
2010                                  */
2011                                 err = ext4_mb_init_group(sb, group);
2012                                 if (err)
2013                                         goto out;
2014                         }
2015
2016                         /*
2017                          * If the particular group doesn't satisfy our
2018                          * criteria we continue with the next group
2019                          */
2020                         if (!ext4_mb_good_group(ac, group, cr))
2021                                 continue;
2022
2023                         err = ext4_mb_load_buddy(sb, group, &e4b);
2024                         if (err)
2025                                 goto out;
2026
2027                         ext4_lock_group(sb, group);
2028                         if (!ext4_mb_good_group(ac, group, cr)) {
2029                                 /* someone did allocation from this group */
2030                                 ext4_unlock_group(sb, group);
2031                                 ext4_mb_release_desc(&e4b);
2032                                 continue;
2033                         }
2034
2035                         ac->ac_groups_scanned++;
2036                         desc = ext4_get_group_desc(sb, group, NULL);
2037                         if (cr == 0 || (desc->bg_flags &
2038                                         cpu_to_le16(EXT4_BG_BLOCK_UNINIT) &&
2039                                         ac->ac_2order != 0))
2040                                 ext4_mb_simple_scan_group(ac, &e4b);
2041                         else if (cr == 1 &&
2042                                         ac->ac_g_ex.fe_len == sbi->s_stripe)
2043                                 ext4_mb_scan_aligned(ac, &e4b);
2044                         else
2045                                 ext4_mb_complex_scan_group(ac, &e4b);
2046
2047                         ext4_unlock_group(sb, group);
2048                         ext4_mb_release_desc(&e4b);
2049
2050                         if (ac->ac_status != AC_STATUS_CONTINUE)
2051                                 break;
2052                 }
2053         }
2054
2055         if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2056             !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2057                 /*
2058                  * We've been searching too long. Let's try to allocate
2059                  * the best chunk we've found so far
2060                  */
2061
2062                 ext4_mb_try_best_found(ac, &e4b);
2063                 if (ac->ac_status != AC_STATUS_FOUND) {
2064                         /*
2065                          * Someone more lucky has already allocated it.
2066                          * The only thing we can do is just take first
2067                          * found block(s)
2068                         printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2069                          */
2070                         ac->ac_b_ex.fe_group = 0;
2071                         ac->ac_b_ex.fe_start = 0;
2072                         ac->ac_b_ex.fe_len = 0;
2073                         ac->ac_status = AC_STATUS_CONTINUE;
2074                         ac->ac_flags |= EXT4_MB_HINT_FIRST;
2075                         cr = 3;
2076                         atomic_inc(&sbi->s_mb_lost_chunks);
2077                         goto repeat;
2078                 }
2079         }
2080 out:
2081         return err;
2082 }
2083
2084 #ifdef EXT4_MB_HISTORY
2085 struct ext4_mb_proc_session {
2086         struct ext4_mb_history *history;
2087         struct super_block *sb;
2088         int start;
2089         int max;
2090 };
2091
2092 static void *ext4_mb_history_skip_empty(struct ext4_mb_proc_session *s,
2093                                         struct ext4_mb_history *hs,
2094                                         int first)
2095 {
2096         if (hs == s->history + s->max)
2097                 hs = s->history;
2098         if (!first && hs == s->history + s->start)
2099                 return NULL;
2100         while (hs->orig.fe_len == 0) {
2101                 hs++;
2102                 if (hs == s->history + s->max)
2103                         hs = s->history;
2104                 if (hs == s->history + s->start)
2105                         return NULL;
2106         }
2107         return hs;
2108 }
2109
2110 static void *ext4_mb_seq_history_start(struct seq_file *seq, loff_t *pos)
2111 {
2112         struct ext4_mb_proc_session *s = seq->private;
2113         struct ext4_mb_history *hs;
2114         int l = *pos;
2115
2116         if (l == 0)
2117                 return SEQ_START_TOKEN;
2118         hs = ext4_mb_history_skip_empty(s, s->history + s->start, 1);
2119         if (!hs)
2120                 return NULL;
2121         while (--l && (hs = ext4_mb_history_skip_empty(s, ++hs, 0)) != NULL);
2122         return hs;
2123 }
2124
2125 static void *ext4_mb_seq_history_next(struct seq_file *seq, void *v,
2126                                       loff_t *pos)
2127 {
2128         struct ext4_mb_proc_session *s = seq->private;
2129         struct ext4_mb_history *hs = v;
2130
2131         ++*pos;
2132         if (v == SEQ_START_TOKEN)
2133                 return ext4_mb_history_skip_empty(s, s->history + s->start, 1);
2134         else
2135                 return ext4_mb_history_skip_empty(s, ++hs, 0);
2136 }
2137
2138 static int ext4_mb_seq_history_show(struct seq_file *seq, void *v)
2139 {
2140         char buf[25], buf2[25], buf3[25], *fmt;
2141         struct ext4_mb_history *hs = v;
2142
2143         if (v == SEQ_START_TOKEN) {
2144                 seq_printf(seq, "%-5s %-8s %-23s %-23s %-23s %-5s "
2145                                 "%-5s %-2s %-5s %-5s %-5s %-6s\n",
2146                           "pid", "inode", "original", "goal", "result", "found",
2147                            "grps", "cr", "flags", "merge", "tail", "broken");
2148                 return 0;
2149         }
2150
2151         if (hs->op == EXT4_MB_HISTORY_ALLOC) {
2152                 fmt = "%-5u %-8u %-23s %-23s %-23s %-5u %-5u %-2u "
2153                         "%-5u %-5s %-5u %-6u\n";
2154                 sprintf(buf2, "%u/%d/%u@%u", hs->result.fe_group,
2155                         hs->result.fe_start, hs->result.fe_len,
2156                         hs->result.fe_logical);
2157                 sprintf(buf, "%u/%d/%u@%u", hs->orig.fe_group,
2158                         hs->orig.fe_start, hs->orig.fe_len,
2159                         hs->orig.fe_logical);
2160                 sprintf(buf3, "%u/%d/%u@%u", hs->goal.fe_group,
2161                         hs->goal.fe_start, hs->goal.fe_len,
2162                         hs->goal.fe_logical);
2163                 seq_printf(seq, fmt, hs->pid, hs->ino, buf, buf3, buf2,
2164                                 hs->found, hs->groups, hs->cr, hs->flags,
2165                                 hs->merged ? "M" : "", hs->tail,
2166                                 hs->buddy ? 1 << hs->buddy : 0);
2167         } else if (hs->op == EXT4_MB_HISTORY_PREALLOC) {
2168                 fmt = "%-5u %-8u %-23s %-23s %-23s\n";
2169                 sprintf(buf2, "%u/%d/%u@%u", hs->result.fe_group,
2170                         hs->result.fe_start, hs->result.fe_len,
2171                         hs->result.fe_logical);
2172                 sprintf(buf, "%u/%d/%u@%u", hs->orig.fe_group,
2173                         hs->orig.fe_start, hs->orig.fe_len,
2174                         hs->orig.fe_logical);
2175                 seq_printf(seq, fmt, hs->pid, hs->ino, buf, "", buf2);
2176         } else if (hs->op == EXT4_MB_HISTORY_DISCARD) {
2177                 sprintf(buf2, "%u/%d/%u", hs->result.fe_group,
2178                         hs->result.fe_start, hs->result.fe_len);
2179                 seq_printf(seq, "%-5u %-8u %-23s discard\n",
2180                                 hs->pid, hs->ino, buf2);
2181         } else if (hs->op == EXT4_MB_HISTORY_FREE) {
2182                 sprintf(buf2, "%u/%d/%u", hs->result.fe_group,
2183                         hs->result.fe_start, hs->result.fe_len);
2184                 seq_printf(seq, "%-5u %-8u %-23s free\n",
2185                                 hs->pid, hs->ino, buf2);
2186         }
2187         return 0;
2188 }
2189
2190 static void ext4_mb_seq_history_stop(struct seq_file *seq, void *v)
2191 {
2192 }
2193
2194 static struct seq_operations ext4_mb_seq_history_ops = {
2195         .start  = ext4_mb_seq_history_start,
2196         .next   = ext4_mb_seq_history_next,
2197         .stop   = ext4_mb_seq_history_stop,
2198         .show   = ext4_mb_seq_history_show,
2199 };
2200
2201 static int ext4_mb_seq_history_open(struct inode *inode, struct file *file)
2202 {
2203         struct super_block *sb = PDE(inode)->data;
2204         struct ext4_sb_info *sbi = EXT4_SB(sb);
2205         struct ext4_mb_proc_session *s;
2206         int rc;
2207         int size;
2208
2209         if (unlikely(sbi->s_mb_history == NULL))
2210                 return -ENOMEM;
2211         s = kmalloc(sizeof(*s), GFP_KERNEL);
2212         if (s == NULL)
2213                 return -ENOMEM;
2214         s->sb = sb;
2215         size = sizeof(struct ext4_mb_history) * sbi->s_mb_history_max;
2216         s->history = kmalloc(size, GFP_KERNEL);
2217         if (s->history == NULL) {
2218                 kfree(s);
2219                 return -ENOMEM;
2220         }
2221
2222         spin_lock(&sbi->s_mb_history_lock);
2223         memcpy(s->history, sbi->s_mb_history, size);
2224         s->max = sbi->s_mb_history_max;
2225         s->start = sbi->s_mb_history_cur % s->max;
2226         spin_unlock(&sbi->s_mb_history_lock);
2227
2228         rc = seq_open(file, &ext4_mb_seq_history_ops);
2229         if (rc == 0) {
2230                 struct seq_file *m = (struct seq_file *)file->private_data;
2231                 m->private = s;
2232         } else {
2233                 kfree(s->history);
2234                 kfree(s);
2235         }
2236         return rc;
2237
2238 }
2239
2240 static int ext4_mb_seq_history_release(struct inode *inode, struct file *file)
2241 {
2242         struct seq_file *seq = (struct seq_file *)file->private_data;
2243         struct ext4_mb_proc_session *s = seq->private;
2244         kfree(s->history);
2245         kfree(s);
2246         return seq_release(inode, file);
2247 }
2248
2249 static ssize_t ext4_mb_seq_history_write(struct file *file,
2250                                 const char __user *buffer,
2251                                 size_t count, loff_t *ppos)
2252 {
2253         struct seq_file *seq = (struct seq_file *)file->private_data;
2254         struct ext4_mb_proc_session *s = seq->private;
2255         struct super_block *sb = s->sb;
2256         char str[32];
2257         int value;
2258
2259         if (count >= sizeof(str)) {
2260                 printk(KERN_ERR "EXT4-fs: %s string too long, max %u bytes\n",
2261                                 "mb_history", (int)sizeof(str));
2262                 return -EOVERFLOW;
2263         }
2264
2265         if (copy_from_user(str, buffer, count))
2266                 return -EFAULT;
2267
2268         value = simple_strtol(str, NULL, 0);
2269         if (value < 0)
2270                 return -ERANGE;
2271         EXT4_SB(sb)->s_mb_history_filter = value;
2272
2273         return count;
2274 }
2275
2276 static struct file_operations ext4_mb_seq_history_fops = {
2277         .owner          = THIS_MODULE,
2278         .open           = ext4_mb_seq_history_open,
2279         .read           = seq_read,
2280         .write          = ext4_mb_seq_history_write,
2281         .llseek         = seq_lseek,
2282         .release        = ext4_mb_seq_history_release,
2283 };
2284
2285 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2286 {
2287         struct super_block *sb = seq->private;
2288         struct ext4_sb_info *sbi = EXT4_SB(sb);
2289         ext4_group_t group;
2290
2291         if (*pos < 0 || *pos >= sbi->s_groups_count)
2292                 return NULL;
2293
2294         group = *pos + 1;
2295         return (void *) ((unsigned long) group);
2296 }
2297
2298 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2299 {
2300         struct super_block *sb = seq->private;
2301         struct ext4_sb_info *sbi = EXT4_SB(sb);
2302         ext4_group_t group;
2303
2304         ++*pos;
2305         if (*pos < 0 || *pos >= sbi->s_groups_count)
2306                 return NULL;
2307         group = *pos + 1;
2308         return (void *) ((unsigned long) group);
2309 }
2310
2311 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2312 {
2313         struct super_block *sb = seq->private;
2314         ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2315         int i;
2316         int err;
2317         struct ext4_buddy e4b;
2318         struct sg {
2319                 struct ext4_group_info info;
2320                 unsigned short counters[16];
2321         } sg;
2322
2323         group--;
2324         if (group == 0)
2325                 seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
2326                                 "[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2327                                   "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2328                            "group", "free", "frags", "first",
2329                            "2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
2330                            "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2331
2332         i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2333                 sizeof(struct ext4_group_info);
2334         err = ext4_mb_load_buddy(sb, group, &e4b);
2335         if (err) {
2336                 seq_printf(seq, "#%-5u: I/O error\n", group);
2337                 return 0;
2338         }
2339         ext4_lock_group(sb, group);
2340         memcpy(&sg, ext4_get_group_info(sb, group), i);
2341         ext4_unlock_group(sb, group);
2342         ext4_mb_release_desc(&e4b);
2343
2344         seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2345                         sg.info.bb_fragments, sg.info.bb_first_free);
2346         for (i = 0; i <= 13; i++)
2347                 seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2348                                 sg.info.bb_counters[i] : 0);
2349         seq_printf(seq, " ]\n");
2350
2351         return 0;
2352 }
2353
2354 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2355 {
2356 }
2357
2358 static struct seq_operations ext4_mb_seq_groups_ops = {
2359         .start  = ext4_mb_seq_groups_start,
2360         .next   = ext4_mb_seq_groups_next,
2361         .stop   = ext4_mb_seq_groups_stop,
2362         .show   = ext4_mb_seq_groups_show,
2363 };
2364
2365 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2366 {
2367         struct super_block *sb = PDE(inode)->data;
2368         int rc;
2369
2370         rc = seq_open(file, &ext4_mb_seq_groups_ops);
2371         if (rc == 0) {
2372                 struct seq_file *m = (struct seq_file *)file->private_data;
2373                 m->private = sb;
2374         }
2375         return rc;
2376
2377 }
2378
2379 static struct file_operations ext4_mb_seq_groups_fops = {
2380         .owner          = THIS_MODULE,
2381         .open           = ext4_mb_seq_groups_open,
2382         .read           = seq_read,
2383         .llseek         = seq_lseek,
2384         .release        = seq_release,
2385 };
2386
2387 static void ext4_mb_history_release(struct super_block *sb)
2388 {
2389         struct ext4_sb_info *sbi = EXT4_SB(sb);
2390
2391         if (sbi->s_proc != NULL) {
2392                 remove_proc_entry("mb_groups", sbi->s_proc);
2393                 remove_proc_entry("mb_history", sbi->s_proc);
2394         }
2395         kfree(sbi->s_mb_history);
2396 }
2397
2398 static void ext4_mb_history_init(struct super_block *sb)
2399 {
2400         struct ext4_sb_info *sbi = EXT4_SB(sb);
2401         int i;
2402
2403         if (sbi->s_proc != NULL) {
2404                 proc_create_data("mb_history", S_IRUGO, sbi->s_proc,
2405                                  &ext4_mb_seq_history_fops, sb);
2406                 proc_create_data("mb_groups", S_IRUGO, sbi->s_proc,
2407                                  &ext4_mb_seq_groups_fops, sb);
2408         }
2409
2410         sbi->s_mb_history_max = 1000;
2411         sbi->s_mb_history_cur = 0;
2412         spin_lock_init(&sbi->s_mb_history_lock);
2413         i = sbi->s_mb_history_max * sizeof(struct ext4_mb_history);
2414         sbi->s_mb_history = kzalloc(i, GFP_KERNEL);
2415         /* if we can't allocate history, then we simple won't use it */
2416 }
2417
2418 static noinline_for_stack void
2419 ext4_mb_store_history(struct ext4_allocation_context *ac)
2420 {
2421         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2422         struct ext4_mb_history h;
2423
2424         if (unlikely(sbi->s_mb_history == NULL))
2425                 return;
2426
2427         if (!(ac->ac_op & sbi->s_mb_history_filter))
2428                 return;
2429
2430         h.op = ac->ac_op;
2431         h.pid = current->pid;
2432         h.ino = ac->ac_inode ? ac->ac_inode->i_ino : 0;
2433         h.orig = ac->ac_o_ex;
2434         h.result = ac->ac_b_ex;
2435         h.flags = ac->ac_flags;
2436         h.found = ac->ac_found;
2437         h.groups = ac->ac_groups_scanned;
2438         h.cr = ac->ac_criteria;
2439         h.tail = ac->ac_tail;
2440         h.buddy = ac->ac_buddy;
2441         h.merged = 0;
2442         if (ac->ac_op == EXT4_MB_HISTORY_ALLOC) {
2443                 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
2444                                 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
2445                         h.merged = 1;
2446                 h.goal = ac->ac_g_ex;
2447                 h.result = ac->ac_f_ex;
2448         }
2449
2450         spin_lock(&sbi->s_mb_history_lock);
2451         memcpy(sbi->s_mb_history + sbi->s_mb_history_cur, &h, sizeof(h));
2452         if (++sbi->s_mb_history_cur >= sbi->s_mb_history_max)
2453                 sbi->s_mb_history_cur = 0;
2454         spin_unlock(&sbi->s_mb_history_lock);
2455 }
2456
2457 #else
2458 #define ext4_mb_history_release(sb)
2459 #define ext4_mb_history_init(sb)
2460 #endif
2461
2462
2463 /* Create and initialize ext4_group_info data for the given group. */
2464 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2465                           struct ext4_group_desc *desc)
2466 {
2467         int i, len;
2468         int metalen = 0;
2469         struct ext4_sb_info *sbi = EXT4_SB(sb);
2470         struct ext4_group_info **meta_group_info;
2471
2472         /*
2473          * First check if this group is the first of a reserved block.
2474          * If it's true, we have to allocate a new table of pointers
2475          * to ext4_group_info structures
2476          */
2477         if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2478                 metalen = sizeof(*meta_group_info) <<
2479                         EXT4_DESC_PER_BLOCK_BITS(sb);
2480                 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2481                 if (meta_group_info == NULL) {
2482                         printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2483                                "buddy group\n");
2484                         goto exit_meta_group_info;
2485                 }
2486                 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] =
2487                         meta_group_info;
2488         }
2489
2490         /*
2491          * calculate needed size. if change bb_counters size,
2492          * don't forget about ext4_mb_generate_buddy()
2493          */
2494         len = offsetof(typeof(**meta_group_info),
2495                        bb_counters[sb->s_blocksize_bits + 2]);
2496
2497         meta_group_info =
2498                 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)];
2499         i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2500
2501         meta_group_info[i] = kzalloc(len, GFP_KERNEL);
2502         if (meta_group_info[i] == NULL) {
2503                 printk(KERN_ERR "EXT4-fs: can't allocate buddy mem\n");
2504                 goto exit_group_info;
2505         }
2506         set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2507                 &(meta_group_info[i]->bb_state));
2508
2509         /*
2510          * initialize bb_free to be able to skip
2511          * empty groups without initialization
2512          */
2513         if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2514                 meta_group_info[i]->bb_free =
2515                         ext4_free_blocks_after_init(sb, group, desc);
2516         } else {
2517                 meta_group_info[i]->bb_free =
2518                         ext4_free_blks_count(sb, desc);
2519         }
2520
2521         INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2522         init_rwsem(&meta_group_info[i]->alloc_sem);
2523         meta_group_info[i]->bb_free_root.rb_node = NULL;;
2524
2525 #ifdef DOUBLE_CHECK
2526         {
2527                 struct buffer_head *bh;
2528                 meta_group_info[i]->bb_bitmap =
2529                         kmalloc(sb->s_blocksize, GFP_KERNEL);
2530                 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2531                 bh = ext4_read_block_bitmap(sb, group);
2532                 BUG_ON(bh == NULL);
2533                 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2534                         sb->s_blocksize);
2535                 put_bh(bh);
2536         }
2537 #endif
2538
2539         return 0;
2540
2541 exit_group_info:
2542         /* If a meta_group_info table has been allocated, release it now */
2543         if (group % EXT4_DESC_PER_BLOCK(sb) == 0)
2544                 kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
2545 exit_meta_group_info:
2546         return -ENOMEM;
2547 } /* ext4_mb_add_groupinfo */
2548
2549 /*
2550  * Update an existing group.
2551  * This function is used for online resize
2552  */
2553 void ext4_mb_update_group_info(struct ext4_group_info *grp, ext4_grpblk_t add)
2554 {
2555         grp->bb_free += add;
2556 }
2557
2558 static int ext4_mb_init_backend(struct super_block *sb)
2559 {
2560         ext4_group_t i;
2561         int metalen;
2562         struct ext4_sb_info *sbi = EXT4_SB(sb);
2563         struct ext4_super_block *es = sbi->s_es;
2564         int num_meta_group_infos;
2565         int num_meta_group_infos_max;
2566         int array_size;
2567         struct ext4_group_info **meta_group_info;
2568         struct ext4_group_desc *desc;
2569
2570         /* This is the number of blocks used by GDT */
2571         num_meta_group_infos = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) -
2572                                 1) >> EXT4_DESC_PER_BLOCK_BITS(sb);
2573
2574         /*
2575          * This is the total number of blocks used by GDT including
2576          * the number of reserved blocks for GDT.
2577          * The s_group_info array is allocated with this value
2578          * to allow a clean online resize without a complex
2579          * manipulation of pointer.
2580          * The drawback is the unused memory when no resize
2581          * occurs but it's very low in terms of pages
2582          * (see comments below)
2583          * Need to handle this properly when META_BG resizing is allowed
2584          */
2585         num_meta_group_infos_max = num_meta_group_infos +
2586                                 le16_to_cpu(es->s_reserved_gdt_blocks);
2587
2588         /*
2589          * array_size is the size of s_group_info array. We round it
2590          * to the next power of two because this approximation is done
2591          * internally by kmalloc so we can have some more memory
2592          * for free here (e.g. may be used for META_BG resize).
2593          */
2594         array_size = 1;
2595         while (array_size < sizeof(*sbi->s_group_info) *
2596                num_meta_group_infos_max)
2597                 array_size = array_size << 1;
2598         /* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2599          * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2600          * So a two level scheme suffices for now. */
2601         sbi->s_group_info = kmalloc(array_size, GFP_KERNEL);
2602         if (sbi->s_group_info == NULL) {
2603                 printk(KERN_ERR "EXT4-fs: can't allocate buddy meta group\n");
2604                 return -ENOMEM;
2605         }
2606         sbi->s_buddy_cache = new_inode(sb);
2607         if (sbi->s_buddy_cache == NULL) {
2608                 printk(KERN_ERR "EXT4-fs: can't get new inode\n");
2609                 goto err_freesgi;
2610         }
2611         EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2612
2613         metalen = sizeof(*meta_group_info) << EXT4_DESC_PER_BLOCK_BITS(sb);
2614         for (i = 0; i < num_meta_group_infos; i++) {
2615                 if ((i + 1) == num_meta_group_infos)
2616                         metalen = sizeof(*meta_group_info) *
2617                                 (sbi->s_groups_count -
2618                                         (i << EXT4_DESC_PER_BLOCK_BITS(sb)));
2619                 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2620                 if (meta_group_info == NULL) {
2621                         printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2622                                "buddy group\n");
2623                         goto err_freemeta;
2624                 }
2625                 sbi->s_group_info[i] = meta_group_info;
2626         }
2627
2628         for (i = 0; i < sbi->s_groups_count; i++) {
2629                 desc = ext4_get_group_desc(sb, i, NULL);
2630                 if (desc == NULL) {
2631                         printk(KERN_ERR
2632                                 "EXT4-fs: can't read descriptor %u\n", i);
2633                         goto err_freebuddy;
2634                 }
2635                 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2636                         goto err_freebuddy;
2637         }
2638
2639         return 0;
2640
2641 err_freebuddy:
2642         while (i-- > 0)
2643                 kfree(ext4_get_group_info(sb, i));
2644         i = num_meta_group_infos;
2645 err_freemeta:
2646         while (i-- > 0)
2647                 kfree(sbi->s_group_info[i]);
2648         iput(sbi->s_buddy_cache);
2649 err_freesgi:
2650         kfree(sbi->s_group_info);
2651         return -ENOMEM;
2652 }
2653
2654 int ext4_mb_init(struct super_block *sb, int needs_recovery)
2655 {
2656         struct ext4_sb_info *sbi = EXT4_SB(sb);
2657         unsigned i, j;
2658         unsigned offset;
2659         unsigned max;
2660         int ret;
2661
2662         i = (sb->s_blocksize_bits + 2) * sizeof(unsigned short);
2663
2664         sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2665         if (sbi->s_mb_offsets == NULL) {
2666                 return -ENOMEM;
2667         }
2668
2669         i = (sb->s_blocksize_bits + 2) * sizeof(unsigned int);
2670         sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2671         if (sbi->s_mb_maxs == NULL) {
2672                 kfree(sbi->s_mb_maxs);
2673                 return -ENOMEM;
2674         }
2675
2676         /* order 0 is regular bitmap */
2677         sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2678         sbi->s_mb_offsets[0] = 0;
2679
2680         i = 1;
2681         offset = 0;
2682         max = sb->s_blocksize << 2;
2683         do {
2684                 sbi->s_mb_offsets[i] = offset;
2685                 sbi->s_mb_maxs[i] = max;
2686                 offset += 1 << (sb->s_blocksize_bits - i);
2687                 max = max >> 1;
2688                 i++;
2689         } while (i <= sb->s_blocksize_bits + 1);
2690
2691         /* init file for buddy data */
2692         ret = ext4_mb_init_backend(sb);
2693         if (ret != 0) {
2694                 kfree(sbi->s_mb_offsets);
2695                 kfree(sbi->s_mb_maxs);
2696                 return ret;
2697         }
2698
2699         spin_lock_init(&sbi->s_md_lock);
2700         spin_lock_init(&sbi->s_bal_lock);
2701
2702         sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2703         sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2704         sbi->s_mb_stats = MB_DEFAULT_STATS;
2705         sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2706         sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2707         sbi->s_mb_history_filter = EXT4_MB_HISTORY_DEFAULT;
2708         sbi->s_mb_group_prealloc = MB_DEFAULT_GROUP_PREALLOC;
2709
2710         sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2711         if (sbi->s_locality_groups == NULL) {
2712                 kfree(sbi->s_mb_offsets);
2713                 kfree(sbi->s_mb_maxs);
2714                 return -ENOMEM;
2715         }
2716         for_each_possible_cpu(i) {
2717                 struct ext4_locality_group *lg;
2718                 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2719                 mutex_init(&lg->lg_mutex);
2720                 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2721                         INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2722                 spin_lock_init(&lg->lg_prealloc_lock);
2723         }
2724
2725         ext4_mb_init_per_dev_proc(sb);
2726         ext4_mb_history_init(sb);
2727
2728         if (sbi->s_journal)
2729                 sbi->s_journal->j_commit_callback = release_blocks_on_commit;
2730
2731         printk(KERN_INFO "EXT4-fs: mballoc enabled\n");
2732         return 0;
2733 }
2734
2735 /* need to called with ext4 group lock (ext4_lock_group) */
2736 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2737 {
2738         struct ext4_prealloc_space *pa;
2739         struct list_head *cur, *tmp;
2740         int count = 0;
2741
2742         list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2743                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2744                 list_del(&pa->pa_group_list);
2745                 count++;
2746                 kmem_cache_free(ext4_pspace_cachep, pa);
2747         }
2748         if (count)
2749                 mb_debug("mballoc: %u PAs left\n", count);
2750
2751 }
2752
2753 int ext4_mb_release(struct super_block *sb)
2754 {
2755         ext4_group_t i;
2756         int num_meta_group_infos;
2757         struct ext4_group_info *grinfo;
2758         struct ext4_sb_info *sbi = EXT4_SB(sb);
2759
2760         if (sbi->s_group_info) {
2761                 for (i = 0; i < sbi->s_groups_count; i++) {
2762                         grinfo = ext4_get_group_info(sb, i);
2763 #ifdef DOUBLE_CHECK
2764                         kfree(grinfo->bb_bitmap);
2765 #endif
2766                         ext4_lock_group(sb, i);
2767                         ext4_mb_cleanup_pa(grinfo);
2768                         ext4_unlock_group(sb, i);
2769                         kfree(grinfo);
2770                 }
2771                 num_meta_group_infos = (sbi->s_groups_count +
2772                                 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2773                         EXT4_DESC_PER_BLOCK_BITS(sb);
2774                 for (i = 0; i < num_meta_group_infos; i++)
2775                         kfree(sbi->s_group_info[i]);
2776                 kfree(sbi->s_group_info);
2777         }
2778         kfree(sbi->s_mb_offsets);
2779         kfree(sbi->s_mb_maxs);
2780         if (sbi->s_buddy_cache)
2781                 iput(sbi->s_buddy_cache);
2782         if (sbi->s_mb_stats) {
2783                 printk(KERN_INFO
2784                        "EXT4-fs: mballoc: %u blocks %u reqs (%u success)\n",
2785                                 atomic_read(&sbi->s_bal_allocated),
2786                                 atomic_read(&sbi->s_bal_reqs),
2787                                 atomic_read(&sbi->s_bal_success));
2788                 printk(KERN_INFO
2789                       "EXT4-fs: mballoc: %u extents scanned, %u goal hits, "
2790                                 "%u 2^N hits, %u breaks, %u lost\n",
2791                                 atomic_read(&sbi->s_bal_ex_scanned),
2792                                 atomic_read(&sbi->s_bal_goals),
2793                                 atomic_read(&sbi->s_bal_2orders),
2794                                 atomic_read(&sbi->s_bal_breaks),
2795                                 atomic_read(&sbi->s_mb_lost_chunks));
2796                 printk(KERN_INFO
2797                        "EXT4-fs: mballoc: %lu generated and it took %Lu\n",
2798                                 sbi->s_mb_buddies_generated++,
2799                                 sbi->s_mb_generation_time);
2800                 printk(KERN_INFO
2801                        "EXT4-fs: mballoc: %u preallocated, %u discarded\n",
2802                                 atomic_read(&sbi->s_mb_preallocated),
2803                                 atomic_read(&sbi->s_mb_discarded));
2804         }
2805
2806         free_percpu(sbi->s_locality_groups);
2807         ext4_mb_history_release(sb);
2808         ext4_mb_destroy_per_dev_proc(sb);
2809
2810         return 0;
2811 }
2812
2813 /*
2814  * This function is called by the jbd2 layer once the commit has finished,
2815  * so we know we can free the blocks that were released with that commit.
2816  */
2817 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn)
2818 {
2819         struct super_block *sb = journal->j_private;
2820         struct ext4_buddy e4b;
2821         struct ext4_group_info *db;
2822         int err, count = 0, count2 = 0;
2823         struct ext4_free_data *entry;
2824         ext4_fsblk_t discard_block;
2825         struct list_head *l, *ltmp;
2826
2827         list_for_each_safe(l, ltmp, &txn->t_private_list) {
2828                 entry = list_entry(l, struct ext4_free_data, list);
2829
2830                 mb_debug("gonna free %u blocks in group %u (0x%p):",
2831                          entry->count, entry->group, entry);
2832
2833                 err = ext4_mb_load_buddy(sb, entry->group, &e4b);
2834                 /* we expect to find existing buddy because it's pinned */
2835                 BUG_ON(err != 0);
2836
2837                 db = e4b.bd_info;
2838                 /* there are blocks to put in buddy to make them really free */
2839                 count += entry->count;
2840                 count2++;
2841                 ext4_lock_group(sb, entry->group);
2842                 /* Take it out of per group rb tree */
2843                 rb_erase(&entry->node, &(db->bb_free_root));
2844                 mb_free_blocks(NULL, &e4b, entry->start_blk, entry->count);
2845
2846                 if (!db->bb_free_root.rb_node) {
2847                         /* No more items in the per group rb tree
2848                          * balance refcounts from ext4_mb_free_metadata()
2849                          */
2850                         page_cache_release(e4b.bd_buddy_page);
2851                         page_cache_release(e4b.bd_bitmap_page);
2852                 }
2853                 ext4_unlock_group(sb, entry->group);
2854                 discard_block = (ext4_fsblk_t) entry->group * EXT4_BLOCKS_PER_GROUP(sb)
2855                         + entry->start_blk
2856                         + le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
2857                 trace_mark(ext4_discard_blocks, "dev %s blk %llu count %u", sb->s_id,
2858                            (unsigned long long) discard_block, entry->count);
2859                 sb_issue_discard(sb, discard_block, entry->count);
2860
2861                 kmem_cache_free(ext4_free_ext_cachep, entry);
2862                 ext4_mb_release_desc(&e4b);
2863         }
2864
2865         mb_debug("freed %u blocks in %u structures\n", count, count2);
2866 }
2867
2868 #define EXT4_MB_STATS_NAME              "stats"
2869 #define EXT4_MB_MAX_TO_SCAN_NAME        "max_to_scan"
2870 #define EXT4_MB_MIN_TO_SCAN_NAME        "min_to_scan"
2871 #define EXT4_MB_ORDER2_REQ              "order2_req"
2872 #define EXT4_MB_STREAM_REQ              "stream_req"
2873 #define EXT4_MB_GROUP_PREALLOC          "group_prealloc"
2874
2875 static int ext4_mb_init_per_dev_proc(struct super_block *sb)
2876 {
2877 #ifdef CONFIG_PROC_FS
2878         mode_t mode = S_IFREG | S_IRUGO | S_IWUSR;
2879         struct ext4_sb_info *sbi = EXT4_SB(sb);
2880         struct proc_dir_entry *proc;
2881
2882         if (sbi->s_proc == NULL)
2883                 return -EINVAL;
2884
2885         EXT4_PROC_HANDLER(EXT4_MB_STATS_NAME, mb_stats);
2886         EXT4_PROC_HANDLER(EXT4_MB_MAX_TO_SCAN_NAME, mb_max_to_scan);
2887         EXT4_PROC_HANDLER(EXT4_MB_MIN_TO_SCAN_NAME, mb_min_to_scan);
2888         EXT4_PROC_HANDLER(EXT4_MB_ORDER2_REQ, mb_order2_reqs);
2889         EXT4_PROC_HANDLER(EXT4_MB_STREAM_REQ, mb_stream_request);
2890         EXT4_PROC_HANDLER(EXT4_MB_GROUP_PREALLOC, mb_group_prealloc);
2891         return 0;
2892
2893 err_out:
2894         remove_proc_entry(EXT4_MB_GROUP_PREALLOC, sbi->s_proc);
2895         remove_proc_entry(EXT4_MB_STREAM_REQ, sbi->s_proc);
2896         remove_proc_entry(EXT4_MB_ORDER2_REQ, sbi->s_proc);
2897         remove_proc_entry(EXT4_MB_MIN_TO_SCAN_NAME, sbi->s_proc);
2898         remove_proc_entry(EXT4_MB_MAX_TO_SCAN_NAME, sbi->s_proc);
2899         remove_proc_entry(EXT4_MB_STATS_NAME, sbi->s_proc);
2900         return -ENOMEM;
2901 #else
2902         return 0;
2903 #endif
2904 }
2905
2906 static int ext4_mb_destroy_per_dev_proc(struct super_block *sb)
2907 {
2908 #ifdef CONFIG_PROC_FS
2909         struct ext4_sb_info *sbi = EXT4_SB(sb);
2910
2911         if (sbi->s_proc == NULL)
2912                 return -EINVAL;
2913
2914         remove_proc_entry(EXT4_MB_GROUP_PREALLOC, sbi->s_proc);
2915         remove_proc_entry(EXT4_MB_STREAM_REQ, sbi->s_proc);
2916         remove_proc_entry(EXT4_MB_ORDER2_REQ, sbi->s_proc);
2917         remove_proc_entry(EXT4_MB_MIN_TO_SCAN_NAME, sbi->s_proc);
2918         remove_proc_entry(EXT4_MB_MAX_TO_SCAN_NAME, sbi->s_proc);
2919         remove_proc_entry(EXT4_MB_STATS_NAME, sbi->s_proc);
2920 #endif
2921         return 0;
2922 }
2923
2924 int __init init_ext4_mballoc(void)
2925 {
2926         ext4_pspace_cachep =
2927                 kmem_cache_create("ext4_prealloc_space",
2928                                      sizeof(struct ext4_prealloc_space),
2929                                      0, SLAB_RECLAIM_ACCOUNT, NULL);
2930         if (ext4_pspace_cachep == NULL)
2931                 return -ENOMEM;
2932
2933         ext4_ac_cachep =
2934                 kmem_cache_create("ext4_alloc_context",
2935                                      sizeof(struct ext4_allocation_context),
2936                                      0, SLAB_RECLAIM_ACCOUNT, NULL);
2937         if (ext4_ac_cachep == NULL) {
2938                 kmem_cache_destroy(ext4_pspace_cachep);
2939                 return -ENOMEM;
2940         }
2941
2942         ext4_free_ext_cachep =
2943                 kmem_cache_create("ext4_free_block_extents",
2944                                      sizeof(struct ext4_free_data),
2945                                      0, SLAB_RECLAIM_ACCOUNT, NULL);
2946         if (ext4_free_ext_cachep == NULL) {
2947                 kmem_cache_destroy(ext4_pspace_cachep);
2948                 kmem_cache_destroy(ext4_ac_cachep);
2949                 return -ENOMEM;
2950         }
2951         return 0;
2952 }
2953
2954 void exit_ext4_mballoc(void)
2955 {
2956         /* XXX: synchronize_rcu(); */
2957         kmem_cache_destroy(ext4_pspace_cachep);
2958         kmem_cache_destroy(ext4_ac_cachep);
2959         kmem_cache_destroy(ext4_free_ext_cachep);
2960 }
2961
2962
2963 /*
2964  * Check quota and mark choosed space (ac->ac_b_ex) non-free in bitmaps
2965  * Returns 0 if success or error code
2966  */
2967 static noinline_for_stack int
2968 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2969                                 handle_t *handle, unsigned int reserv_blks)
2970 {
2971         struct buffer_head *bitmap_bh = NULL;
2972         struct ext4_super_block *es;
2973         struct ext4_group_desc *gdp;
2974         struct buffer_head *gdp_bh;
2975         struct ext4_sb_info *sbi;
2976         struct super_block *sb;
2977         ext4_fsblk_t block;
2978         int err, len;
2979
2980         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2981         BUG_ON(ac->ac_b_ex.fe_len <= 0);
2982
2983         sb = ac->ac_sb;
2984         sbi = EXT4_SB(sb);
2985         es = sbi->s_es;
2986
2987
2988         err = -EIO;
2989         bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2990         if (!bitmap_bh)
2991                 goto out_err;
2992
2993         err = ext4_journal_get_write_access(handle, bitmap_bh);
2994         if (err)
2995                 goto out_err;
2996
2997         err = -EIO;
2998         gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2999         if (!gdp)
3000                 goto out_err;
3001
3002         ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
3003                         gdp->bg_free_blocks_count);
3004
3005         err = ext4_journal_get_write_access(handle, gdp_bh);
3006         if (err)
3007                 goto out_err;
3008
3009         block = ac->ac_b_ex.fe_group * EXT4_BLOCKS_PER_GROUP(sb)
3010                 + ac->ac_b_ex.fe_start
3011                 + le32_to_cpu(es->s_first_data_block);
3012
3013         len = ac->ac_b_ex.fe_len;
3014         if (in_range(ext4_block_bitmap(sb, gdp), block, len) ||
3015             in_range(ext4_inode_bitmap(sb, gdp), block, len) ||
3016             in_range(block, ext4_inode_table(sb, gdp),
3017                      EXT4_SB(sb)->s_itb_per_group) ||
3018             in_range(block + len - 1, ext4_inode_table(sb, gdp),
3019                      EXT4_SB(sb)->s_itb_per_group)) {
3020                 ext4_error(sb, __func__,
3021                            "Allocating block in system zone - block = %llu",
3022                            block);
3023                 /* File system mounted not to panic on error
3024                  * Fix the bitmap and repeat the block allocation
3025                  * We leak some of the blocks here.
3026                  */
3027                 mb_set_bits(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group),
3028                                 bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3029                                 ac->ac_b_ex.fe_len);
3030                 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3031                 if (!err)
3032                         err = -EAGAIN;
3033                 goto out_err;
3034         }
3035 #ifdef AGGRESSIVE_CHECK
3036         {
3037                 int i;
3038                 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3039                         BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3040                                                 bitmap_bh->b_data));
3041                 }
3042         }
3043 #endif
3044         spin_lock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
3045         mb_set_bits(NULL, bitmap_bh->b_data,
3046                                 ac->ac_b_ex.fe_start, ac->ac_b_ex.fe_len);
3047         if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
3048                 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3049                 ext4_free_blks_set(sb, gdp,
3050                                         ext4_free_blocks_after_init(sb,
3051                                         ac->ac_b_ex.fe_group, gdp));
3052         }
3053         len = ext4_free_blks_count(sb, gdp) - ac->ac_b_ex.fe_len;
3054         ext4_free_blks_set(sb, gdp, len);
3055         gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
3056         spin_unlock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
3057         percpu_counter_sub(&sbi->s_freeblocks_counter, ac->ac_b_ex.fe_len);
3058         /*
3059          * Now reduce the dirty block count also. Should not go negative
3060          */
3061         if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3062                 /* release all the reserved blocks if non delalloc */
3063                 percpu_counter_sub(&sbi->s_dirtyblocks_counter, reserv_blks);
3064         else
3065                 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
3066                                                 ac->ac_b_ex.fe_len);
3067
3068         if (sbi->s_log_groups_per_flex) {
3069                 ext4_group_t flex_group = ext4_flex_group(sbi,
3070                                                           ac->ac_b_ex.fe_group);
3071                 spin_lock(sb_bgl_lock(sbi, flex_group));
3072                 sbi->s_flex_groups[flex_group].free_blocks -= ac->ac_b_ex.fe_len;
3073                 spin_unlock(sb_bgl_lock(sbi, flex_group));
3074         }
3075
3076         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3077         if (err)
3078                 goto out_err;
3079         err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3080
3081 out_err:
3082         sb->s_dirt = 1;
3083         brelse(bitmap_bh);
3084         return err;
3085 }
3086
3087 /*
3088  * here we normalize request for locality group
3089  * Group request are normalized to s_strip size if we set the same via mount
3090  * option. If not we set it to s_mb_group_prealloc which can be configured via
3091  * /proc/fs/ext4/<partition>/group_prealloc
3092  *
3093  * XXX: should we try to preallocate more than the group has now?
3094  */
3095 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3096 {
3097         struct super_block *sb = ac->ac_sb;
3098         struct ext4_locality_group *lg = ac->ac_lg;
3099
3100         BUG_ON(lg == NULL);
3101         if (EXT4_SB(sb)->s_stripe)
3102                 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_stripe;
3103         else
3104                 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3105         mb_debug("#%u: goal %u blocks for locality group\n",
3106                 current->pid, ac->ac_g_ex.fe_len);
3107 }
3108
3109 /*
3110  * Normalization means making request better in terms of
3111  * size and alignment
3112  */
3113 static noinline_for_stack void
3114 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3115                                 struct ext4_allocation_request *ar)
3116 {
3117         int bsbits, max;
3118         ext4_lblk_t end;
3119         loff_t size, orig_size, start_off;
3120         ext4_lblk_t start, orig_start;
3121         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3122         struct ext4_prealloc_space *pa;
3123
3124         /* do normalize only data requests, metadata requests
3125            do not need preallocation */
3126         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3127                 return;
3128
3129         /* sometime caller may want exact blocks */
3130         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3131                 return;
3132
3133         /* caller may indicate that preallocation isn't
3134          * required (it's a tail, for example) */
3135         if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3136                 return;
3137
3138         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3139                 ext4_mb_normalize_group_request(ac);
3140                 return ;
3141         }
3142
3143         bsbits = ac->ac_sb->s_blocksize_bits;
3144
3145         /* first, let's learn actual file size
3146          * given current request is allocated */
3147         size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
3148         size = size << bsbits;
3149         if (size < i_size_read(ac->ac_inode))
3150                 size = i_size_read(ac->ac_inode);
3151
3152         /* max size of free chunks */
3153         max = 2 << bsbits;
3154
3155 #define NRL_CHECK_SIZE(req, size, max, chunk_size)      \
3156                 (req <= (size) || max <= (chunk_size))
3157
3158         /* first, try to predict filesize */
3159         /* XXX: should this table be tunable? */
3160         start_off = 0;
3161         if (size <= 16 * 1024) {
3162                 size = 16 * 1024;
3163         } else if (size <= 32 * 1024) {
3164                 size = 32 * 1024;
3165         } else if (size <= 64 * 1024) {
3166                 size = 64 * 1024;
3167         } else if (size <= 128 * 1024) {
3168                 size = 128 * 1024;
3169         } else if (size <= 256 * 1024) {
3170                 size = 256 * 1024;
3171         } else if (size <= 512 * 1024) {
3172                 size = 512 * 1024;
3173         } else if (size <= 1024 * 1024) {
3174                 size = 1024 * 1024;
3175         } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3176                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3177                                                 (21 - bsbits)) << 21;
3178                 size = 2 * 1024 * 1024;
3179         } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3180                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3181                                                         (22 - bsbits)) << 22;
3182                 size = 4 * 1024 * 1024;
3183         } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3184                                         (8<<20)>>bsbits, max, 8 * 1024)) {
3185                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3186                                                         (23 - bsbits)) << 23;
3187                 size = 8 * 1024 * 1024;
3188         } else {
3189                 start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
3190                 size      = ac->ac_o_ex.fe_len << bsbits;
3191         }
3192         orig_size = size = size >> bsbits;
3193         orig_start = start = start_off >> bsbits;
3194
3195         /* don't cover already allocated blocks in selected range */
3196         if (ar->pleft && start <= ar->lleft) {
3197                 size -= ar->lleft + 1 - start;
3198                 start = ar->lleft + 1;
3199         }
3200         if (ar->pright && start + size - 1 >= ar->lright)
3201                 size -= start + size - ar->lright;
3202
3203         end = start + size;
3204
3205         /* check we don't cross already preallocated blocks */
3206         rcu_read_lock();
3207         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3208                 ext4_lblk_t pa_end;
3209
3210                 if (pa->pa_deleted)
3211                         continue;
3212                 spin_lock(&pa->pa_lock);
3213                 if (pa->pa_deleted) {
3214                         spin_unlock(&pa->pa_lock);
3215                         continue;
3216                 }
3217
3218                 pa_end = pa->pa_lstart + pa->pa_len;
3219
3220                 /* PA must not overlap original request */
3221                 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3222                         ac->ac_o_ex.fe_logical < pa->pa_lstart));
3223
3224                 /* skip PA normalized request doesn't overlap with */
3225                 if (pa->pa_lstart >= end) {
3226                         spin_unlock(&pa->pa_lock);
3227                         continue;
3228                 }
3229                 if (pa_end <= start) {
3230                         spin_unlock(&pa->pa_lock);
3231                         continue;
3232                 }
3233                 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3234
3235                 if (pa_end <= ac->ac_o_ex.fe_logical) {
3236                         BUG_ON(pa_end < start);
3237                         start = pa_end;
3238                 }
3239
3240                 if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3241                         BUG_ON(pa->pa_lstart > end);
3242                         end = pa->pa_lstart;
3243                 }
3244                 spin_unlock(&pa->pa_lock);
3245         }
3246         rcu_read_unlock();
3247         size = end - start;
3248
3249         /* XXX: extra loop to check we really don't overlap preallocations */
3250         rcu_read_lock();
3251         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3252                 ext4_lblk_t pa_end;
3253                 spin_lock(&pa->pa_lock);
3254                 if (pa->pa_deleted == 0) {
3255                         pa_end = pa->pa_lstart + pa->pa_len;
3256                         BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3257                 }
3258                 spin_unlock(&pa->pa_lock);
3259         }
3260         rcu_read_unlock();
3261
3262         if (start + size <= ac->ac_o_ex.fe_logical &&
3263                         start > ac->ac_o_ex.fe_logical) {
3264                 printk(KERN_ERR "start %lu, size %lu, fe_logical %lu\n",
3265                         (unsigned long) start, (unsigned long) size,
3266                         (unsigned long) ac->ac_o_ex.fe_logical);
3267         }
3268         BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3269                         start > ac->ac_o_ex.fe_logical);
3270         BUG_ON(size <= 0 || size >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3271
3272         /* now prepare goal request */
3273
3274         /* XXX: is it better to align blocks WRT to logical
3275          * placement or satisfy big request as is */
3276         ac->ac_g_ex.fe_logical = start;
3277         ac->ac_g_ex.fe_len = size;
3278
3279         /* define goal start in order to merge */
3280         if (ar->pright && (ar->lright == (start + size))) {
3281                 /* merge to the right */
3282                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3283                                                 &ac->ac_f_ex.fe_group,
3284                                                 &ac->ac_f_ex.fe_start);
3285                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3286         }
3287         if (ar->pleft && (ar->lleft + 1 == start)) {
3288                 /* merge to the left */
3289                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3290                                                 &ac->ac_f_ex.fe_group,
3291                                                 &ac->ac_f_ex.fe_start);
3292                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3293         }
3294
3295         mb_debug("goal: %u(was %u) blocks at %u\n", (unsigned) size,
3296                 (unsigned) orig_size, (unsigned) start);
3297 }
3298
3299 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3300 {
3301         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3302
3303         if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3304                 atomic_inc(&sbi->s_bal_reqs);
3305                 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3306                 if (ac->ac_o_ex.fe_len >= ac->ac_g_ex.fe_len)
3307                         atomic_inc(&sbi->s_bal_success);
3308                 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3309                 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3310                                 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3311                         atomic_inc(&sbi->s_bal_goals);
3312                 if (ac->ac_found > sbi->s_mb_max_to_scan)
3313                         atomic_inc(&sbi->s_bal_breaks);
3314         }
3315
3316         ext4_mb_store_history(ac);
3317 }
3318
3319 /*
3320  * use blocks preallocated to inode
3321  */
3322 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3323                                 struct ext4_prealloc_space *pa)
3324 {
3325         ext4_fsblk_t start;
3326         ext4_fsblk_t end;
3327         int len;
3328
3329         /* found preallocated blocks, use them */
3330         start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3331         end = min(pa->pa_pstart + pa->pa_len, start + ac->ac_o_ex.fe_len);
3332         len = end - start;
3333         ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3334                                         &ac->ac_b_ex.fe_start);
3335         ac->ac_b_ex.fe_len = len;
3336         ac->ac_status = AC_STATUS_FOUND;
3337         ac->ac_pa = pa;
3338
3339         BUG_ON(start < pa->pa_pstart);
3340         BUG_ON(start + len > pa->pa_pstart + pa->pa_len);
3341         BUG_ON(pa->pa_free < len);
3342         pa->pa_free -= len;
3343
3344         mb_debug("use %llu/%u from inode pa %p\n", start, len, pa);
3345 }
3346
3347 /*
3348  * use blocks preallocated to locality group
3349  */
3350 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3351                                 struct ext4_prealloc_space *pa)
3352 {
3353         unsigned int len = ac->ac_o_ex.fe_len;
3354
3355         ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3356                                         &ac->ac_b_ex.fe_group,
3357                                         &ac->ac_b_ex.fe_start);
3358         ac->ac_b_ex.fe_len = len;
3359         ac->ac_status = AC_STATUS_FOUND;
3360         ac->ac_pa = pa;
3361
3362         /* we don't correct pa_pstart or pa_plen here to avoid
3363          * possible race when the group is being loaded concurrently
3364          * instead we correct pa later, after blocks are marked
3365          * in on-disk bitmap -- see ext4_mb_release_context()
3366          * Other CPUs are prevented from allocating from this pa by lg_mutex
3367          */
3368         mb_debug("use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3369 }
3370
3371 /*
3372  * Return the prealloc space that have minimal distance
3373  * from the goal block. @cpa is the prealloc
3374  * space that is having currently known minimal distance
3375  * from the goal block.
3376  */
3377 static struct ext4_prealloc_space *
3378 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3379                         struct ext4_prealloc_space *pa,
3380                         struct ext4_prealloc_space *cpa)
3381 {
3382         ext4_fsblk_t cur_distance, new_distance;
3383
3384         if (cpa == NULL) {
3385                 atomic_inc(&pa->pa_count);
3386                 return pa;
3387         }
3388         cur_distance = abs(goal_block - cpa->pa_pstart);
3389         new_distance = abs(goal_block - pa->pa_pstart);
3390
3391         if (cur_distance < new_distance)
3392                 return cpa;
3393
3394         /* drop the previous reference */
3395         atomic_dec(&cpa->pa_count);
3396         atomic_inc(&pa->pa_count);
3397         return pa;
3398 }
3399
3400 /*
3401  * search goal blocks in preallocated space
3402  */
3403 static noinline_for_stack int
3404 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3405 {
3406         int order, i;
3407         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3408         struct ext4_locality_group *lg;
3409         struct ext4_prealloc_space *pa, *cpa = NULL;
3410         ext4_fsblk_t goal_block;
3411
3412         /* only data can be preallocated */
3413         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3414                 return 0;
3415
3416         /* first, try per-file preallocation */
3417         rcu_read_lock();
3418         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3419
3420                 /* all fields in this condition don't change,
3421                  * so we can skip locking for them */
3422                 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3423                         ac->ac_o_ex.fe_logical >= pa->pa_lstart + pa->pa_len)
3424                         continue;
3425
3426                 /* found preallocated blocks, use them */
3427                 spin_lock(&pa->pa_lock);
3428                 if (pa->pa_deleted == 0 && pa->pa_free) {
3429                         atomic_inc(&pa->pa_count);
3430                         ext4_mb_use_inode_pa(ac, pa);
3431                         spin_unlock(&pa->pa_lock);
3432                         ac->ac_criteria = 10;
3433                         rcu_read_unlock();
3434                         return 1;
3435                 }
3436                 spin_unlock(&pa->pa_lock);
3437         }
3438         rcu_read_unlock();
3439
3440         /* can we use group allocation? */
3441         if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3442                 return 0;
3443
3444         /* inode may have no locality group for some reason */
3445         lg = ac->ac_lg;
3446         if (lg == NULL)
3447                 return 0;
3448         order  = fls(ac->ac_o_ex.fe_len) - 1;
3449         if (order > PREALLOC_TB_SIZE - 1)
3450                 /* The max size of hash table is PREALLOC_TB_SIZE */
3451                 order = PREALLOC_TB_SIZE - 1;
3452
3453         goal_block = ac->ac_g_ex.fe_group * EXT4_BLOCKS_PER_GROUP(ac->ac_sb) +
3454                      ac->ac_g_ex.fe_start +
3455                      le32_to_cpu(EXT4_SB(ac->ac_sb)->s_es->s_first_data_block);
3456         /*
3457          * search for the prealloc space that is having
3458          * minimal distance from the goal block.
3459          */
3460         for (i = order; i < PREALLOC_TB_SIZE; i++) {
3461                 rcu_read_lock();
3462                 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3463                                         pa_inode_list) {
3464                         spin_lock(&pa->pa_lock);
3465                         if (pa->pa_deleted == 0 &&
3466                                         pa->pa_free >= ac->ac_o_ex.fe_len) {
3467
3468                                 cpa = ext4_mb_check_group_pa(goal_block,
3469                                                                 pa, cpa);
3470                         }
3471                         spin_unlock(&pa->pa_lock);
3472                 }
3473                 rcu_read_unlock();
3474         }
3475         if (cpa) {
3476                 ext4_mb_use_group_pa(ac, cpa);
3477                 ac->ac_criteria = 20;
3478                 return 1;
3479         }
3480         return 0;
3481 }
3482
3483 /*
3484  * the function goes through all block freed in the group
3485  * but not yet committed and marks them used in in-core bitmap.
3486  * buddy must be generated from this bitmap
3487  * Need to be called with ext4 group lock (ext4_lock_group)
3488  */
3489 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3490                                                 ext4_group_t group)
3491 {
3492         struct rb_node *n;
3493         struct ext4_group_info *grp;
3494         struct ext4_free_data *entry;
3495
3496         grp = ext4_get_group_info(sb, group);
3497         n = rb_first(&(grp->bb_free_root));
3498
3499         while (n) {
3500                 entry = rb_entry(n, struct ext4_free_data, node);
3501                 mb_set_bits(sb_bgl_lock(EXT4_SB(sb), group),
3502                                 bitmap, entry->start_blk,
3503                                 entry->count);
3504                 n = rb_next(n);
3505         }
3506         return;
3507 }
3508
3509 /*
3510  * the function goes through all preallocation in this group and marks them
3511  * used in in-core bitmap. buddy must be generated from this bitmap
3512  * Need to be called with ext4 group lock (ext4_lock_group)
3513  */
3514 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3515                                         ext4_group_t group)
3516 {
3517         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3518         struct ext4_prealloc_space *pa;
3519         struct list_head *cur;
3520         ext4_group_t groupnr;
3521         ext4_grpblk_t start;
3522         int preallocated = 0;
3523         int count = 0;
3524         int len;
3525
3526         /* all form of preallocation discards first load group,
3527          * so the only competing code is preallocation use.
3528          * we don't need any locking here
3529          * notice we do NOT ignore preallocations with pa_deleted
3530          * otherwise we could leave used blocks available for
3531          * allocation in buddy when concurrent ext4_mb_put_pa()
3532          * is dropping preallocation
3533          */
3534         list_for_each(cur, &grp->bb_prealloc_list) {
3535                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3536                 spin_lock(&pa->pa_lock);
3537                 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3538                                              &groupnr, &start);
3539                 len = pa->pa_len;
3540                 spin_unlock(&pa->pa_lock);
3541                 if (unlikely(len == 0))
3542                         continue;
3543                 BUG_ON(groupnr != group);
3544                 mb_set_bits(sb_bgl_lock(EXT4_SB(sb), group),
3545                                                 bitmap, start, len);
3546                 preallocated += len;
3547                 count++;
3548         }
3549         mb_debug("prellocated %u for group %u\n", preallocated, group);
3550 }
3551
3552 static void ext4_mb_pa_callback(struct rcu_head *head)
3553 {
3554         struct ext4_prealloc_space *pa;
3555         pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3556         kmem_cache_free(ext4_pspace_cachep, pa);
3557 }
3558
3559 /*
3560  * drops a reference to preallocated space descriptor
3561  * if this was the last reference and the space is consumed
3562  */
3563 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3564                         struct super_block *sb, struct ext4_prealloc_space *pa)
3565 {
3566         ext4_group_t grp;
3567
3568         if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3569                 return;
3570
3571         /* in this short window concurrent discard can set pa_deleted */
3572         spin_lock(&pa->pa_lock);
3573         if (pa->pa_deleted == 1) {
3574                 spin_unlock(&pa->pa_lock);
3575                 return;
3576         }
3577
3578         pa->pa_deleted = 1;
3579         spin_unlock(&pa->pa_lock);
3580
3581         /* -1 is to protect from crossing allocation group */
3582         ext4_get_group_no_and_offset(sb, pa->pa_pstart - 1, &grp, NULL);
3583
3584         /*
3585          * possible race:
3586          *
3587          *  P1 (buddy init)                     P2 (regular allocation)
3588          *                                      find block B in PA
3589          *  copy on-disk bitmap to buddy
3590          *                                      mark B in on-disk bitmap
3591          *                                      drop PA from group
3592          *  mark all PAs in buddy
3593          *
3594          * thus, P1 initializes buddy with B available. to prevent this
3595          * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3596          * against that pair
3597          */
3598         ext4_lock_group(sb, grp);
3599         list_del(&pa->pa_group_list);
3600         ext4_unlock_group(sb, grp);
3601
3602         spin_lock(pa->pa_obj_lock);
3603         list_del_rcu(&pa->pa_inode_list);
3604         spin_unlock(pa->pa_obj_lock);
3605
3606         call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3607 }
3608
3609 /*
3610  * creates new preallocated space for given inode
3611  */
3612 static noinline_for_stack int
3613 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3614 {
3615         struct super_block *sb = ac->ac_sb;
3616         struct ext4_prealloc_space *pa;
3617         struct ext4_group_info *grp;
3618         struct ext4_inode_info *ei;
3619
3620         /* preallocate only when found space is larger then requested */
3621         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3622         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3623         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3624
3625         pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3626         if (pa == NULL)
3627                 return -ENOMEM;
3628
3629         if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3630                 int winl;
3631                 int wins;
3632                 int win;
3633                 int offs;
3634
3635                 /* we can't allocate as much as normalizer wants.
3636                  * so, found space must get proper lstart
3637                  * to cover original request */
3638                 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3639                 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3640
3641                 /* we're limited by original request in that
3642                  * logical block must be covered any way
3643                  * winl is window we can move our chunk within */
3644                 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3645
3646                 /* also, we should cover whole original request */
3647                 wins = ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len;
3648
3649                 /* the smallest one defines real window */
3650                 win = min(winl, wins);
3651
3652                 offs = ac->ac_o_ex.fe_logical % ac->ac_b_ex.fe_len;
3653                 if (offs && offs < win)
3654                         win = offs;
3655
3656                 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical - win;
3657                 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3658                 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3659         }
3660
3661         /* preallocation can change ac_b_ex, thus we store actually
3662          * allocated blocks for history */
3663         ac->ac_f_ex = ac->ac_b_ex;
3664
3665         pa->pa_lstart = ac->ac_b_ex.fe_logical;
3666         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3667         pa->pa_len = ac->ac_b_ex.fe_len;
3668         pa->pa_free = pa->pa_len;
3669         atomic_set(&pa->pa_count, 1);
3670         spin_lock_init(&pa->pa_lock);
3671         pa->pa_deleted = 0;
3672         pa->pa_linear = 0;
3673
3674         mb_debug("new inode pa %p: %llu/%u for %u\n", pa,
3675                         pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3676
3677         ext4_mb_use_inode_pa(ac, pa);
3678         atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3679
3680         ei = EXT4_I(ac->ac_inode);
3681         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3682
3683         pa->pa_obj_lock = &ei->i_prealloc_lock;
3684         pa->pa_inode = ac->ac_inode;
3685
3686         ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3687         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3688         ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3689
3690         spin_lock(pa->pa_obj_lock);
3691         list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3692         spin_unlock(pa->pa_obj_lock);
3693
3694         return 0;
3695 }
3696
3697 /*
3698  * creates new preallocated space for locality group inodes belongs to
3699  */
3700 static noinline_for_stack int
3701 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3702 {
3703         struct super_block *sb = ac->ac_sb;
3704         struct ext4_locality_group *lg;
3705         struct ext4_prealloc_space *pa;
3706         struct ext4_group_info *grp;
3707
3708         /* preallocate only when found space is larger then requested */
3709         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3710         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3711         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3712
3713         BUG_ON(ext4_pspace_cachep == NULL);
3714         pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3715         if (pa == NULL)
3716                 return -ENOMEM;
3717
3718         /* preallocation can change ac_b_ex, thus we store actually
3719          * allocated blocks for history */
3720         ac->ac_f_ex = ac->ac_b_ex;
3721
3722         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3723         pa->pa_lstart = pa->pa_pstart;
3724         pa->pa_len = ac->ac_b_ex.fe_len;
3725         pa->pa_free = pa->pa_len;
3726         atomic_set(&pa->pa_count, 1);
3727         spin_lock_init(&pa->pa_lock);
3728         INIT_LIST_HEAD(&pa->pa_inode_list);
3729         pa->pa_deleted = 0;
3730         pa->pa_linear = 1;
3731
3732         mb_debug("new group pa %p: %llu/%u for %u\n", pa,
3733                         pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3734
3735         ext4_mb_use_group_pa(ac, pa);
3736         atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3737
3738         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3739         lg = ac->ac_lg;
3740         BUG_ON(lg == NULL);
3741
3742         pa->pa_obj_lock = &lg->lg_prealloc_lock;
3743         pa->pa_inode = NULL;
3744
3745         ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3746         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3747         ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3748
3749         /*
3750          * We will later add the new pa to the right bucket
3751          * after updating the pa_free in ext4_mb_release_context
3752          */
3753         return 0;
3754 }
3755
3756 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3757 {
3758         int err;
3759
3760         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3761                 err = ext4_mb_new_group_pa(ac);
3762         else
3763                 err = ext4_mb_new_inode_pa(ac);
3764         return err;
3765 }
3766
3767 /*
3768  * finds all unused blocks in on-disk bitmap, frees them in
3769  * in-core bitmap and buddy.
3770  * @pa must be unlinked from inode and group lists, so that
3771  * nobody else can find/use it.
3772  * the caller MUST hold group/inode locks.
3773  * TODO: optimize the case when there are no in-core structures yet
3774  */
3775 static noinline_for_stack int
3776 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3777                         struct ext4_prealloc_space *pa,
3778                         struct ext4_allocation_context *ac)
3779 {
3780         struct super_block *sb = e4b->bd_sb;
3781         struct ext4_sb_info *sbi = EXT4_SB(sb);
3782         unsigned int end;
3783         unsigned int next;
3784         ext4_group_t group;
3785         ext4_grpblk_t bit;
3786         sector_t start;
3787         int err = 0;
3788         int free = 0;
3789
3790         BUG_ON(pa->pa_deleted == 0);
3791         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3792         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3793         end = bit + pa->pa_len;
3794
3795         if (ac) {
3796                 ac->ac_sb = sb;
3797                 ac->ac_inode = pa->pa_inode;
3798                 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3799         }
3800
3801         while (bit < end) {
3802                 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3803                 if (bit >= end)
3804                         break;
3805                 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3806                 start = group * EXT4_BLOCKS_PER_GROUP(sb) + bit +
3807                                 le32_to_cpu(sbi->s_es->s_first_data_block);
3808                 mb_debug("    free preallocated %u/%u in group %u\n",
3809                                 (unsigned) start, (unsigned) next - bit,
3810                                 (unsigned) group);
3811                 free += next - bit;
3812
3813                 if (ac) {
3814                         ac->ac_b_ex.fe_group = group;
3815                         ac->ac_b_ex.fe_start = bit;
3816                         ac->ac_b_ex.fe_len = next - bit;
3817                         ac->ac_b_ex.fe_logical = 0;
3818                         ext4_mb_store_history(ac);
3819                 }
3820
3821                 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3822                 bit = next + 1;
3823         }
3824         if (free != pa->pa_free) {
3825                 printk(KERN_CRIT "pa %p: logic %lu, phys. %lu, len %lu\n",
3826                         pa, (unsigned long) pa->pa_lstart,
3827                         (unsigned long) pa->pa_pstart,
3828                         (unsigned long) pa->pa_len);
3829                 ext4_grp_locked_error(sb, group,
3830                                         __func__, "free %u, pa_free %u",
3831                                         free, pa->pa_free);
3832                 /*
3833                  * pa is already deleted so we use the value obtained
3834                  * from the bitmap and continue.
3835                  */
3836         }
3837         atomic_add(free, &sbi->s_mb_discarded);
3838
3839         return err;
3840 }
3841
3842 static noinline_for_stack int
3843 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3844                                 struct ext4_prealloc_space *pa,
3845                                 struct ext4_allocation_context *ac)
3846 {
3847         struct super_block *sb = e4b->bd_sb;
3848         ext4_group_t group;
3849         ext4_grpblk_t bit;
3850
3851         if (ac)
3852                 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3853
3854         BUG_ON(pa->pa_deleted == 0);
3855         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3856         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3857         mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3858         atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3859
3860         if (ac) {
3861                 ac->ac_sb = sb;
3862                 ac->ac_inode = NULL;
3863                 ac->ac_b_ex.fe_group = group;
3864                 ac->ac_b_ex.fe_start = bit;
3865                 ac->ac_b_ex.fe_len = pa->pa_len;
3866                 ac->ac_b_ex.fe_logical = 0;
3867                 ext4_mb_store_history(ac);
3868         }
3869
3870         return 0;
3871 }
3872
3873 /*
3874  * releases all preallocations in given group
3875  *
3876  * first, we need to decide discard policy:
3877  * - when do we discard
3878  *   1) ENOSPC
3879  * - how many do we discard
3880  *   1) how many requested
3881  */
3882 static noinline_for_stack int
3883 ext4_mb_discard_group_preallocations(struct super_block *sb,
3884                                         ext4_group_t group, int needed)
3885 {
3886         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3887         struct buffer_head *bitmap_bh = NULL;
3888         struct ext4_prealloc_space *pa, *tmp;
3889         struct ext4_allocation_context *ac;
3890         struct list_head list;
3891         struct ext4_buddy e4b;
3892         int err;
3893         int busy = 0;
3894         int free = 0;
3895
3896         mb_debug("discard preallocation for group %u\n", group);
3897
3898         if (list_empty(&grp->bb_prealloc_list))
3899                 return 0;
3900
3901         bitmap_bh = ext4_read_block_bitmap(sb, group);
3902         if (bitmap_bh == NULL) {
3903                 ext4_error(sb, __func__, "Error in reading block "
3904                                 "bitmap for %u", group);
3905                 return 0;
3906         }
3907
3908         err = ext4_mb_load_buddy(sb, group, &e4b);
3909         if (err) {
3910                 ext4_error(sb, __func__, "Error in loading buddy "
3911                                 "information for %u", group);
3912                 put_bh(bitmap_bh);
3913                 return 0;
3914         }
3915
3916         if (needed == 0)
3917                 needed = EXT4_BLOCKS_PER_GROUP(sb) + 1;
3918
3919         INIT_LIST_HEAD(&list);
3920         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
3921 repeat:
3922         ext4_lock_group(sb, group);
3923         list_for_each_entry_safe(pa, tmp,
3924                                 &grp->bb_prealloc_list, pa_group_list) {
3925                 spin_lock(&pa->pa_lock);
3926                 if (atomic_read(&pa->pa_count)) {
3927                         spin_unlock(&pa->pa_lock);
3928                         busy = 1;
3929                         continue;
3930                 }
3931                 if (pa->pa_deleted) {
3932                         spin_unlock(&pa->pa_lock);
3933                         continue;
3934                 }
3935
3936                 /* seems this one can be freed ... */
3937                 pa->pa_deleted = 1;
3938
3939                 /* we can trust pa_free ... */
3940                 free += pa->pa_free;
3941
3942                 spin_unlock(&pa->pa_lock);
3943
3944                 list_del(&pa->pa_group_list);
3945                 list_add(&pa->u.pa_tmp_list, &list);
3946         }
3947
3948         /* if we still need more blocks and some PAs were used, try again */
3949         if (free < needed && busy) {
3950                 busy = 0;
3951                 ext4_unlock_group(sb, group);
3952                 /*
3953                  * Yield the CPU here so that we don't get soft lockup
3954                  * in non preempt case.
3955                  */
3956                 yield();
3957                 goto repeat;
3958         }
3959
3960         /* found anything to free? */
3961         if (list_empty(&list)) {
3962                 BUG_ON(free != 0);
3963                 goto out;
3964         }
3965
3966         /* now free all selected PAs */
3967         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3968
3969                 /* remove from object (inode or locality group) */
3970                 spin_lock(pa->pa_obj_lock);
3971                 list_del_rcu(&pa->pa_inode_list);
3972                 spin_unlock(pa->pa_obj_lock);
3973
3974                 if (pa->pa_linear)
3975                         ext4_mb_release_group_pa(&e4b, pa, ac);
3976                 else
3977                         ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
3978
3979                 list_del(&pa->u.pa_tmp_list);
3980                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3981         }
3982
3983 out:
3984         ext4_unlock_group(sb, group);
3985         if (ac)
3986                 kmem_cache_free(ext4_ac_cachep, ac);
3987         ext4_mb_release_desc(&e4b);
3988         put_bh(bitmap_bh);
3989         return free;
3990 }
3991
3992 /*
3993  * releases all non-used preallocated blocks for given inode
3994  *
3995  * It's important to discard preallocations under i_data_sem
3996  * We don't want another block to be served from the prealloc
3997  * space when we are discarding the inode prealloc space.
3998  *
3999  * FIXME!! Make sure it is valid at all the call sites
4000  */
4001 void ext4_discard_preallocations(struct inode *inode)
4002 {
4003         struct ext4_inode_info *ei = EXT4_I(inode);
4004         struct super_block *sb = inode->i_sb;
4005         struct buffer_head *bitmap_bh = NULL;
4006         struct ext4_prealloc_space *pa, *tmp;
4007         struct ext4_allocation_context *ac;
4008         ext4_group_t group = 0;
4009         struct list_head list;
4010         struct ext4_buddy e4b;
4011         int err;
4012
4013         if (!S_ISREG(inode->i_mode)) {
4014                 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4015                 return;
4016         }
4017
4018         mb_debug("discard preallocation for inode %lu\n", inode->i_ino);
4019
4020         INIT_LIST_HEAD(&list);
4021
4022         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4023 repeat:
4024         /* first, collect all pa's in the inode */
4025         spin_lock(&ei->i_prealloc_lock);
4026         while (!list_empty(&ei->i_prealloc_list)) {
4027                 pa = list_entry(ei->i_prealloc_list.next,
4028                                 struct ext4_prealloc_space, pa_inode_list);
4029                 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4030                 spin_lock(&pa->pa_lock);
4031                 if (atomic_read(&pa->pa_count)) {
4032                         /* this shouldn't happen often - nobody should
4033                          * use preallocation while we're discarding it */
4034                         spin_unlock(&pa->pa_lock);
4035                         spin_unlock(&ei->i_prealloc_lock);
4036                         printk(KERN_ERR "uh-oh! used pa while discarding\n");
4037                         WARN_ON(1);
4038                         schedule_timeout_uninterruptible(HZ);
4039                         goto repeat;
4040
4041                 }
4042                 if (pa->pa_deleted == 0) {
4043                         pa->pa_deleted = 1;
4044                         spin_unlock(&pa->pa_lock);
4045                         list_del_rcu(&pa->pa_inode_list);
4046                         list_add(&pa->u.pa_tmp_list, &list);
4047                         continue;
4048                 }
4049
4050                 /* someone is deleting pa right now */
4051                 spin_unlock(&pa->pa_lock);
4052                 spin_unlock(&ei->i_prealloc_lock);
4053
4054                 /* we have to wait here because pa_deleted
4055                  * doesn't mean pa is already unlinked from
4056                  * the list. as we might be called from
4057                  * ->clear_inode() the inode will get freed
4058                  * and concurrent thread which is unlinking
4059                  * pa from inode's list may access already
4060                  * freed memory, bad-bad-bad */
4061
4062                 /* XXX: if this happens too often, we can
4063                  * add a flag to force wait only in case
4064                  * of ->clear_inode(), but not in case of
4065                  * regular truncate */
4066                 schedule_timeout_uninterruptible(HZ);
4067                 goto repeat;
4068         }
4069         spin_unlock(&ei->i_prealloc_lock);
4070
4071         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4072                 BUG_ON(pa->pa_linear != 0);
4073                 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
4074
4075                 err = ext4_mb_load_buddy(sb, group, &e4b);
4076                 if (err) {
4077                         ext4_error(sb, __func__, "Error in loading buddy "
4078                                         "information for %u", group);
4079                         continue;
4080                 }
4081
4082                 bitmap_bh = ext4_read_block_bitmap(sb, group);
4083                 if (bitmap_bh == NULL) {
4084                         ext4_error(sb, __func__, "Error in reading block "
4085                                         "bitmap for %u", group);
4086                         ext4_mb_release_desc(&e4b);
4087                         continue;
4088                 }
4089
4090                 ext4_lock_group(sb, group);
4091                 list_del(&pa->pa_group_list);
4092                 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
4093                 ext4_unlock_group(sb, group);
4094
4095                 ext4_mb_release_desc(&e4b);
4096                 put_bh(bitmap_bh);
4097
4098                 list_del(&pa->u.pa_tmp_list);
4099                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4100         }
4101         if (ac)
4102                 kmem_cache_free(ext4_ac_cachep, ac);
4103 }
4104
4105 /*
4106  * finds all preallocated spaces and return blocks being freed to them
4107  * if preallocated space becomes full (no block is used from the space)
4108  * then the function frees space in buddy
4109  * XXX: at the moment, truncate (which is the only way to free blocks)
4110  * discards all preallocations
4111  */
4112 static void ext4_mb_return_to_preallocation(struct inode *inode,
4113                                         struct ext4_buddy *e4b,
4114                                         sector_t block, int count)
4115 {
4116         BUG_ON(!list_empty(&EXT4_I(inode)->i_prealloc_list));
4117 }
4118 #ifdef MB_DEBUG
4119 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4120 {
4121         struct super_block *sb = ac->ac_sb;
4122         ext4_group_t i;
4123
4124         printk(KERN_ERR "EXT4-fs: Can't allocate:"
4125                         " Allocation context details:\n");
4126         printk(KERN_ERR "EXT4-fs: status %d flags %d\n",
4127                         ac->ac_status, ac->ac_flags);
4128         printk(KERN_ERR "EXT4-fs: orig %lu/%lu/%lu@%lu, goal %lu/%lu/%lu@%lu, "
4129                         "best %lu/%lu/%lu@%lu cr %d\n",
4130                         (unsigned long)ac->ac_o_ex.fe_group,
4131                         (unsigned long)ac->ac_o_ex.fe_start,
4132                         (unsigned long)ac->ac_o_ex.fe_len,
4133                         (unsigned long)ac->ac_o_ex.fe_logical,
4134                         (unsigned long)ac->ac_g_ex.fe_group,
4135                         (unsigned long)ac->ac_g_ex.fe_start,
4136                         (unsigned long)ac->ac_g_ex.fe_len,
4137                         (unsigned long)ac->ac_g_ex.fe_logical,
4138                         (unsigned long)ac->ac_b_ex.fe_group,
4139                         (unsigned long)ac->ac_b_ex.fe_start,
4140                         (unsigned long)ac->ac_b_ex.fe_len,
4141                         (unsigned long)ac->ac_b_ex.fe_logical,
4142                         (int)ac->ac_criteria);
4143         printk(KERN_ERR "EXT4-fs: %lu scanned, %d found\n", ac->ac_ex_scanned,
4144                 ac->ac_found);
4145         printk(KERN_ERR "EXT4-fs: groups: \n");
4146         for (i = 0; i < EXT4_SB(sb)->s_groups_count; i++) {
4147                 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4148                 struct ext4_prealloc_space *pa;
4149                 ext4_grpblk_t start;
4150                 struct list_head *cur;
4151                 ext4_lock_group(sb, i);
4152                 list_for_each(cur, &grp->bb_prealloc_list) {
4153                         pa = list_entry(cur, struct ext4_prealloc_space,
4154                                         pa_group_list);
4155                         spin_lock(&pa->pa_lock);
4156                         ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4157                                                      NULL, &start);
4158                         spin_unlock(&pa->pa_lock);
4159                         printk(KERN_ERR "PA:%lu:%d:%u \n", i,
4160                                                         start, pa->pa_len);
4161                 }
4162                 ext4_unlock_group(sb, i);
4163
4164                 if (grp->bb_free == 0)
4165                         continue;
4166                 printk(KERN_ERR "%lu: %d/%d \n",
4167                        i, grp->bb_free, grp->bb_fragments);
4168         }
4169         printk(KERN_ERR "\n");
4170 }
4171 #else
4172 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4173 {
4174         return;
4175 }
4176 #endif
4177
4178 /*
4179  * We use locality group preallocation for small size file. The size of the
4180  * file is determined by the current size or the resulting size after
4181  * allocation which ever is larger
4182  *
4183  * One can tune this size via /proc/fs/ext4/<partition>/stream_req
4184  */
4185 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4186 {
4187         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4188         int bsbits = ac->ac_sb->s_blocksize_bits;
4189         loff_t size, isize;
4190
4191         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4192                 return;
4193
4194         size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
4195         isize = i_size_read(ac->ac_inode) >> bsbits;
4196         size = max(size, isize);
4197
4198         /* don't use group allocation for large files */
4199         if (size >= sbi->s_mb_stream_request)
4200                 return;
4201
4202         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4203                 return;
4204
4205         BUG_ON(ac->ac_lg != NULL);
4206         /*
4207          * locality group prealloc space are per cpu. The reason for having
4208          * per cpu locality group is to reduce the contention between block
4209          * request from multiple CPUs.
4210          */
4211         ac->ac_lg = per_cpu_ptr(sbi->s_locality_groups, raw_smp_processor_id());
4212
4213         /* we're going to use group allocation */
4214         ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4215
4216         /* serialize all allocations in the group */
4217         mutex_lock(&ac->ac_lg->lg_mutex);
4218 }
4219
4220 static noinline_for_stack int
4221 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4222                                 struct ext4_allocation_request *ar)
4223 {
4224         struct super_block *sb = ar->inode->i_sb;
4225         struct ext4_sb_info *sbi = EXT4_SB(sb);
4226         struct ext4_super_block *es = sbi->s_es;
4227         ext4_group_t group;
4228         unsigned int len;
4229         ext4_fsblk_t goal;
4230         ext4_grpblk_t block;
4231
4232         /* we can't allocate > group size */
4233         len = ar->len;
4234
4235         /* just a dirty hack to filter too big requests  */
4236         if (len >= EXT4_BLOCKS_PER_GROUP(sb) - 10)
4237                 len = EXT4_BLOCKS_PER_GROUP(sb) - 10;
4238
4239         /* start searching from the goal */
4240         goal = ar->goal;
4241         if (goal < le32_to_cpu(es->s_first_data_block) ||
4242                         goal >= ext4_blocks_count(es))
4243                 goal = le32_to_cpu(es->s_first_data_block);
4244         ext4_get_group_no_and_offset(sb, goal, &group, &block);
4245
4246         /* set up allocation goals */
4247         ac->ac_b_ex.fe_logical = ar->logical;
4248         ac->ac_b_ex.fe_group = 0;
4249         ac->ac_b_ex.fe_start = 0;
4250         ac->ac_b_ex.fe_len = 0;
4251         ac->ac_status = AC_STATUS_CONTINUE;
4252         ac->ac_groups_scanned = 0;
4253         ac->ac_ex_scanned = 0;
4254         ac->ac_found = 0;
4255         ac->ac_sb = sb;
4256         ac->ac_inode = ar->inode;
4257         ac->ac_o_ex.fe_logical = ar->logical;
4258         ac->ac_o_ex.fe_group = group;
4259         ac->ac_o_ex.fe_start = block;
4260         ac->ac_o_ex.fe_len = len;
4261         ac->ac_g_ex.fe_logical = ar->logical;
4262         ac->ac_g_ex.fe_group = group;
4263         ac->ac_g_ex.fe_start = block;
4264         ac->ac_g_ex.fe_len = len;
4265         ac->ac_f_ex.fe_len = 0;
4266         ac->ac_flags = ar->flags;
4267         ac->ac_2order = 0;
4268         ac->ac_criteria = 0;
4269         ac->ac_pa = NULL;
4270         ac->ac_bitmap_page = NULL;
4271         ac->ac_buddy_page = NULL;
4272         ac->ac_lg = NULL;
4273
4274         /* we have to define context: we'll we work with a file or
4275          * locality group. this is a policy, actually */
4276         ext4_mb_group_or_file(ac);
4277
4278         mb_debug("init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4279                         "left: %u/%u, right %u/%u to %swritable\n",
4280                         (unsigned) ar->len, (unsigned) ar->logical,
4281                         (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4282                         (unsigned) ar->lleft, (unsigned) ar->pleft,
4283                         (unsigned) ar->lright, (unsigned) ar->pright,
4284                         atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4285         return 0;
4286
4287 }
4288
4289 static noinline_for_stack void
4290 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4291                                         struct ext4_locality_group *lg,
4292                                         int order, int total_entries)
4293 {
4294         ext4_group_t group = 0;
4295         struct ext4_buddy e4b;
4296         struct list_head discard_list;
4297         struct ext4_prealloc_space *pa, *tmp;
4298         struct ext4_allocation_context *ac;
4299
4300         mb_debug("discard locality group preallocation\n");
4301
4302         INIT_LIST_HEAD(&discard_list);
4303         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4304
4305         spin_lock(&lg->lg_prealloc_lock);
4306         list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4307                                                 pa_inode_list) {
4308                 spin_lock(&pa->pa_lock);
4309                 if (atomic_read(&pa->pa_count)) {
4310                         /*
4311                          * This is the pa that we just used
4312                          * for block allocation. So don't
4313                          * free that
4314                          */
4315                         spin_unlock(&pa->pa_lock);
4316                         continue;
4317                 }
4318                 if (pa->pa_deleted) {
4319                         spin_unlock(&pa->pa_lock);
4320                         continue;
4321                 }
4322                 /* only lg prealloc space */
4323                 BUG_ON(!pa->pa_linear);
4324
4325                 /* seems this one can be freed ... */
4326                 pa->pa_deleted = 1;
4327                 spin_unlock(&pa->pa_lock);
4328
4329                 list_del_rcu(&pa->pa_inode_list);
4330                 list_add(&pa->u.pa_tmp_list, &discard_list);
4331
4332                 total_entries--;
4333                 if (total_entries <= 5) {
4334                         /*
4335                          * we want to keep only 5 entries
4336                          * allowing it to grow to 8. This
4337                          * mak sure we don't call discard
4338                          * soon for this list.
4339                          */
4340                         break;
4341                 }
4342         }
4343         spin_unlock(&lg->lg_prealloc_lock);
4344
4345         list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4346
4347                 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
4348                 if (ext4_mb_load_buddy(sb, group, &e4b)) {
4349                         ext4_error(sb, __func__, "Error in loading buddy "
4350                                         "information for %u", group);
4351                         continue;
4352                 }
4353                 ext4_lock_group(sb, group);
4354                 list_del(&pa->pa_group_list);
4355                 ext4_mb_release_group_pa(&e4b, pa, ac);
4356                 ext4_unlock_group(sb, group);
4357
4358                 ext4_mb_release_desc(&e4b);
4359                 list_del(&pa->u.pa_tmp_list);
4360                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4361         }
4362         if (ac)
4363                 kmem_cache_free(ext4_ac_cachep, ac);
4364 }
4365
4366 /*
4367  * We have incremented pa_count. So it cannot be freed at this
4368  * point. Also we hold lg_mutex. So no parallel allocation is
4369  * possible from this lg. That means pa_free cannot be updated.
4370  *
4371  * A parallel ext4_mb_discard_group_preallocations is possible.
4372  * which can cause the lg_prealloc_list to be updated.
4373  */
4374
4375 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4376 {
4377         int order, added = 0, lg_prealloc_count = 1;
4378         struct super_block *sb = ac->ac_sb;
4379         struct ext4_locality_group *lg = ac->ac_lg;
4380         struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4381
4382         order = fls(pa->pa_free) - 1;
4383         if (order > PREALLOC_TB_SIZE - 1)
4384                 /* The max size of hash table is PREALLOC_TB_SIZE */
4385                 order = PREALLOC_TB_SIZE - 1;
4386         /* Add the prealloc space to lg */
4387         rcu_read_lock();
4388         list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4389                                                 pa_inode_list) {
4390                 spin_lock(&tmp_pa->pa_lock);
4391                 if (tmp_pa->pa_deleted) {
4392                         spin_unlock(&pa->pa_lock);
4393                         continue;
4394                 }
4395                 if (!added && pa->pa_free < tmp_pa->pa_free) {
4396                         /* Add to the tail of the previous entry */
4397                         list_add_tail_rcu(&pa->pa_inode_list,
4398                                                 &tmp_pa->pa_inode_list);
4399                         added = 1;
4400                         /*
4401                          * we want to count the total
4402                          * number of entries in the list
4403                          */
4404                 }
4405                 spin_unlock(&tmp_pa->pa_lock);
4406                 lg_prealloc_count++;
4407         }
4408         if (!added)
4409                 list_add_tail_rcu(&pa->pa_inode_list,
4410                                         &lg->lg_prealloc_list[order]);
4411         rcu_read_unlock();
4412
4413         /* Now trim the list to be not more than 8 elements */
4414         if (lg_prealloc_count > 8) {
4415                 ext4_mb_discard_lg_preallocations(sb, lg,
4416                                                 order, lg_prealloc_count);
4417                 return;
4418         }
4419         return ;
4420 }
4421
4422 /*
4423  * release all resource we used in allocation
4424  */
4425 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4426 {
4427         struct ext4_prealloc_space *pa = ac->ac_pa;
4428         if (pa) {
4429                 if (pa->pa_linear) {
4430                         /* see comment in ext4_mb_use_group_pa() */
4431                         spin_lock(&pa->pa_lock);
4432                         pa->pa_pstart += ac->ac_b_ex.fe_len;
4433                         pa->pa_lstart += ac->ac_b_ex.fe_len;
4434                         pa->pa_free -= ac->ac_b_ex.fe_len;
4435                         pa->pa_len -= ac->ac_b_ex.fe_len;
4436                         spin_unlock(&pa->pa_lock);
4437                         /*
4438                          * We want to add the pa to the right bucket.
4439                          * Remove it from the list and while adding
4440                          * make sure the list to which we are adding
4441                          * doesn't grow big.
4442                          */
4443                         if (likely(pa->pa_free)) {
4444                                 spin_lock(pa->pa_obj_lock);
4445                                 list_del_rcu(&pa->pa_inode_list);
4446                                 spin_unlock(pa->pa_obj_lock);
4447                                 ext4_mb_add_n_trim(ac);
4448                         }
4449                 }
4450                 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4451         }
4452         if (ac->ac_bitmap_page)
4453                 page_cache_release(ac->ac_bitmap_page);
4454         if (ac->ac_buddy_page)
4455                 page_cache_release(ac->ac_buddy_page);
4456         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4457                 mutex_unlock(&ac->ac_lg->lg_mutex);
4458         ext4_mb_collect_stats(ac);
4459         return 0;
4460 }
4461
4462 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4463 {
4464         ext4_group_t i;
4465         int ret;
4466         int freed = 0;
4467
4468         for (i = 0; i < EXT4_SB(sb)->s_groups_count && needed > 0; i++) {
4469                 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4470                 freed += ret;
4471                 needed -= ret;
4472         }
4473
4474         return freed;
4475 }
4476
4477 /*
4478  * Main entry point into mballoc to allocate blocks
4479  * it tries to use preallocation first, then falls back
4480  * to usual allocation
4481  */
4482 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4483                                  struct ext4_allocation_request *ar, int *errp)
4484 {
4485         int freed;
4486         struct ext4_allocation_context *ac = NULL;
4487         struct ext4_sb_info *sbi;
4488         struct super_block *sb;
4489         ext4_fsblk_t block = 0;
4490         unsigned int inquota;
4491         unsigned int reserv_blks = 0;
4492
4493         sb = ar->inode->i_sb;
4494         sbi = EXT4_SB(sb);
4495
4496         if (!EXT4_I(ar->inode)->i_delalloc_reserved_flag) {
4497                 /*
4498                  * With delalloc we already reserved the blocks
4499                  */
4500                 while (ar->len && ext4_claim_free_blocks(sbi, ar->len)) {
4501                         /* let others to free the space */
4502                         yield();
4503                         ar->len = ar->len >> 1;
4504                 }
4505                 if (!ar->len) {
4506                         *errp = -ENOSPC;
4507                         return 0;
4508                 }
4509                 reserv_blks = ar->len;
4510         }
4511         while (ar->len && DQUOT_ALLOC_BLOCK(ar->inode, ar->len)) {
4512                 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4513                 ar->len--;
4514         }
4515         if (ar->len == 0) {
4516                 *errp = -EDQUOT;
4517                 return 0;
4518         }
4519         inquota = ar->len;
4520
4521         if (EXT4_I(ar->inode)->i_delalloc_reserved_flag)
4522                 ar->flags |= EXT4_MB_DELALLOC_RESERVED;
4523
4524         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4525         if (!ac) {
4526                 ar->len = 0;
4527                 *errp = -ENOMEM;
4528                 goto out1;
4529         }
4530
4531         *errp = ext4_mb_initialize_context(ac, ar);
4532         if (*errp) {
4533                 ar->len = 0;
4534                 goto out2;
4535         }
4536
4537         ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4538         if (!ext4_mb_use_preallocated(ac)) {
4539                 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4540                 ext4_mb_normalize_request(ac, ar);
4541 repeat:
4542                 /* allocate space in core */
4543                 ext4_mb_regular_allocator(ac);
4544
4545                 /* as we've just preallocated more space than
4546                  * user requested orinally, we store allocated
4547                  * space in a special descriptor */
4548                 if (ac->ac_status == AC_STATUS_FOUND &&
4549                                 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4550                         ext4_mb_new_preallocation(ac);
4551         }
4552
4553         if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4554                 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_blks);
4555                 if (*errp ==  -EAGAIN) {
4556                         ac->ac_b_ex.fe_group = 0;
4557                         ac->ac_b_ex.fe_start = 0;
4558                         ac->ac_b_ex.fe_len = 0;
4559                         ac->ac_status = AC_STATUS_CONTINUE;
4560                         goto repeat;
4561                 } else if (*errp) {
4562                         ac->ac_b_ex.fe_len = 0;
4563                         ar->len = 0;
4564                         ext4_mb_show_ac(ac);
4565                 } else {
4566                         block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4567                         ar->len = ac->ac_b_ex.fe_len;
4568                 }
4569         } else {
4570                 freed  = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4571                 if (freed)
4572                         goto repeat;
4573                 *errp = -ENOSPC;
4574                 ac->ac_b_ex.fe_len = 0;
4575                 ar->len = 0;
4576                 ext4_mb_show_ac(ac);
4577         }
4578
4579         ext4_mb_release_context(ac);
4580
4581 out2:
4582         kmem_cache_free(ext4_ac_cachep, ac);
4583 out1:
4584         if (ar->len < inquota)
4585                 DQUOT_FREE_BLOCK(ar->inode, inquota - ar->len);
4586
4587         return block;
4588 }
4589
4590 /*
4591  * We can merge two free data extents only if the physical blocks
4592  * are contiguous, AND the extents were freed by the same transaction,
4593  * AND the blocks are associated with the same group.
4594  */
4595 static int can_merge(struct ext4_free_data *entry1,
4596                         struct ext4_free_data *entry2)
4597 {
4598         if ((entry1->t_tid == entry2->t_tid) &&
4599             (entry1->group == entry2->group) &&
4600             ((entry1->start_blk + entry1->count) == entry2->start_blk))
4601                 return 1;
4602         return 0;
4603 }
4604
4605 static noinline_for_stack int
4606 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4607                       struct ext4_free_data *new_entry)
4608 {
4609         ext4_grpblk_t block;
4610         struct ext4_free_data *entry;
4611         struct ext4_group_info *db = e4b->bd_info;
4612         struct super_block *sb = e4b->bd_sb;
4613         struct ext4_sb_info *sbi = EXT4_SB(sb);
4614         struct rb_node **n = &db->bb_free_root.rb_node, *node;
4615         struct rb_node *parent = NULL, *new_node;
4616
4617         BUG_ON(!ext4_handle_valid(handle));
4618         BUG_ON(e4b->bd_bitmap_page == NULL);
4619         BUG_ON(e4b->bd_buddy_page == NULL);
4620
4621         new_node = &new_entry->node;
4622         block = new_entry->start_blk;
4623
4624         if (!*n) {
4625                 /* first free block exent. We need to
4626                    protect buddy cache from being freed,
4627                  * otherwise we'll refresh it from
4628                  * on-disk bitmap and lose not-yet-available
4629                  * blocks */
4630                 page_cache_get(e4b->bd_buddy_page);
4631                 page_cache_get(e4b->bd_bitmap_page);
4632         }
4633         while (*n) {
4634                 parent = *n;
4635                 entry = rb_entry(parent, struct ext4_free_data, node);
4636                 if (block < entry->start_blk)
4637                         n = &(*n)->rb_left;
4638                 else if (block >= (entry->start_blk + entry->count))
4639                         n = &(*n)->rb_right;
4640                 else {
4641                         ext4_grp_locked_error(sb, e4b->bd_group, __func__,
4642                                         "Double free of blocks %d (%d %d)",
4643                                         block, entry->start_blk, entry->count);
4644                         return 0;
4645                 }
4646         }
4647
4648         rb_link_node(new_node, parent, n);
4649         rb_insert_color(new_node, &db->bb_free_root);
4650
4651         /* Now try to see the extent can be merged to left and right */
4652         node = rb_prev(new_node);
4653         if (node) {
4654                 entry = rb_entry(node, struct ext4_free_data, node);
4655                 if (can_merge(entry, new_entry)) {
4656                         new_entry->start_blk = entry->start_blk;
4657                         new_entry->count += entry->count;
4658                         rb_erase(node, &(db->bb_free_root));
4659                         spin_lock(&sbi->s_md_lock);
4660                         list_del(&entry->list);
4661                         spin_unlock(&sbi->s_md_lock);
4662                         kmem_cache_free(ext4_free_ext_cachep, entry);
4663                 }
4664         }
4665
4666         node = rb_next(new_node);
4667         if (node) {
4668                 entry = rb_entry(node, struct ext4_free_data, node);
4669                 if (can_merge(new_entry, entry)) {
4670                         new_entry->count += entry->count;
4671                         rb_erase(node, &(db->bb_free_root));
4672                         spin_lock(&sbi->s_md_lock);
4673                         list_del(&entry->list);
4674                         spin_unlock(&sbi->s_md_lock);
4675                         kmem_cache_free(ext4_free_ext_cachep, entry);
4676                 }
4677         }
4678         /* Add the extent to transaction's private list */
4679         spin_lock(&sbi->s_md_lock);
4680         list_add(&new_entry->list, &handle->h_transaction->t_private_list);
4681         spin_unlock(&sbi->s_md_lock);
4682         return 0;
4683 }
4684
4685 /*
4686  * Main entry point into mballoc to free blocks
4687  */
4688 void ext4_mb_free_blocks(handle_t *handle, struct inode *inode,
4689                         unsigned long block, unsigned long count,
4690                         int metadata, unsigned long *freed)
4691 {
4692         struct buffer_head *bitmap_bh = NULL;
4693         struct super_block *sb = inode->i_sb;
4694         struct ext4_allocation_context *ac = NULL;
4695         struct ext4_group_desc *gdp;
4696         struct ext4_super_block *es;
4697         unsigned int overflow;
4698         ext4_grpblk_t bit;
4699         struct buffer_head *gd_bh;
4700         ext4_group_t block_group;
4701         struct ext4_sb_info *sbi;
4702         struct ext4_buddy e4b;
4703         int err = 0;
4704         int ret;
4705
4706         *freed = 0;
4707
4708         sbi = EXT4_SB(sb);
4709         es = EXT4_SB(sb)->s_es;
4710         if (block < le32_to_cpu(es->s_first_data_block) ||
4711             block + count < block ||
4712             block + count > ext4_blocks_count(es)) {
4713                 ext4_error(sb, __func__,
4714                             "Freeing blocks not in datazone - "
4715                             "block = %lu, count = %lu", block, count);
4716                 goto error_return;
4717         }
4718
4719         ext4_debug("freeing block %lu\n", block);
4720
4721         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4722         if (ac) {
4723                 ac->ac_op = EXT4_MB_HISTORY_FREE;
4724                 ac->ac_inode = inode;
4725                 ac->ac_sb = sb;
4726         }
4727
4728 do_more:
4729         overflow = 0;
4730         ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4731
4732         /*
4733          * Check to see if we are freeing blocks across a group
4734          * boundary.
4735          */
4736         if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4737                 overflow = bit + count - EXT4_BLOCKS_PER_GROUP(sb);
4738                 count -= overflow;
4739         }
4740         bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4741         if (!bitmap_bh) {
4742                 err = -EIO;
4743                 goto error_return;
4744         }
4745         gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4746         if (!gdp) {
4747                 err = -EIO;
4748                 goto error_return;
4749         }
4750
4751         if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4752             in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4753             in_range(block, ext4_inode_table(sb, gdp),
4754                       EXT4_SB(sb)->s_itb_per_group) ||
4755             in_range(block + count - 1, ext4_inode_table(sb, gdp),
4756                       EXT4_SB(sb)->s_itb_per_group)) {
4757
4758                 ext4_error(sb, __func__,
4759                            "Freeing blocks in system zone - "
4760                            "Block = %lu, count = %lu", block, count);
4761                 /* err = 0. ext4_std_error should be a no op */
4762                 goto error_return;
4763         }
4764
4765         BUFFER_TRACE(bitmap_bh, "getting write access");
4766         err = ext4_journal_get_write_access(handle, bitmap_bh);
4767         if (err)
4768                 goto error_return;
4769
4770         /*
4771          * We are about to modify some metadata.  Call the journal APIs
4772          * to unshare ->b_data if a currently-committing transaction is
4773          * using it
4774          */
4775         BUFFER_TRACE(gd_bh, "get_write_access");
4776         err = ext4_journal_get_write_access(handle, gd_bh);
4777         if (err)
4778                 goto error_return;
4779 #ifdef AGGRESSIVE_CHECK
4780         {
4781                 int i;
4782                 for (i = 0; i < count; i++)
4783                         BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4784         }
4785 #endif
4786         if (ac) {
4787                 ac->ac_b_ex.fe_group = block_group;
4788                 ac->ac_b_ex.fe_start = bit;
4789                 ac->ac_b_ex.fe_len = count;
4790                 ext4_mb_store_history(ac);
4791         }
4792
4793         err = ext4_mb_load_buddy(sb, block_group, &e4b);
4794         if (err)
4795                 goto error_return;
4796         if (metadata && ext4_handle_valid(handle)) {
4797                 struct ext4_free_data *new_entry;
4798                 /*
4799                  * blocks being freed are metadata. these blocks shouldn't
4800                  * be used until this transaction is committed
4801                  */
4802                 new_entry  = kmem_cache_alloc(ext4_free_ext_cachep, GFP_NOFS);
4803                 new_entry->start_blk = bit;
4804                 new_entry->group  = block_group;
4805                 new_entry->count = count;
4806                 new_entry->t_tid = handle->h_transaction->t_tid;
4807                 ext4_lock_group(sb, block_group);
4808                 mb_clear_bits(sb_bgl_lock(sbi, block_group), bitmap_bh->b_data,
4809                                 bit, count);
4810                 ext4_mb_free_metadata(handle, &e4b, new_entry);
4811                 ext4_unlock_group(sb, block_group);
4812         } else {
4813                 ext4_lock_group(sb, block_group);
4814                 /* need to update group_info->bb_free and bitmap
4815                  * with group lock held. generate_buddy look at
4816                  * them with group lock_held
4817                  */
4818                 mb_clear_bits(sb_bgl_lock(sbi, block_group), bitmap_bh->b_data,
4819                                 bit, count);
4820                 mb_free_blocks(inode, &e4b, bit, count);
4821                 ext4_mb_return_to_preallocation(inode, &e4b, block, count);
4822                 ext4_unlock_group(sb, block_group);
4823         }
4824
4825         spin_lock(sb_bgl_lock(sbi, block_group));
4826         ret = ext4_free_blks_count(sb, gdp) + count;
4827         ext4_free_blks_set(sb, gdp, ret);
4828         gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4829         spin_unlock(sb_bgl_lock(sbi, block_group));
4830         percpu_counter_add(&sbi->s_freeblocks_counter, count);
4831
4832         if (sbi->s_log_groups_per_flex) {
4833                 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4834                 spin_lock(sb_bgl_lock(sbi, flex_group));
4835                 sbi->s_flex_groups[flex_group].free_blocks += count;
4836                 spin_unlock(sb_bgl_lock(sbi, flex_group));
4837         }
4838
4839         ext4_mb_release_desc(&e4b);
4840
4841         *freed += count;
4842
4843         /* We dirtied the bitmap block */
4844         BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4845         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4846
4847         /* And the group descriptor block */
4848         BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4849         ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4850         if (!err)
4851                 err = ret;
4852
4853         if (overflow && !err) {
4854                 block += count;
4855                 count = overflow;
4856                 put_bh(bitmap_bh);
4857                 goto do_more;
4858         }
4859         sb->s_dirt = 1;
4860 error_return:
4861         brelse(bitmap_bh);
4862         ext4_std_error(sb, err);
4863         if (ac)
4864                 kmem_cache_free(ext4_ac_cachep, ac);
4865         return;
4866 }