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