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