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