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