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