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