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