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