ext4: check journal inode extents more carefully
[linux-2.6-microblaze.git] / fs / ext4 / mballoc.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
4  * Written by Alex Tomas <alex@clusterfs.com>
5  */
6
7
8 /*
9  * mballoc.c contains the multiblocks allocation routines
10  */
11
12 #include "ext4_jbd2.h"
13 #include "mballoc.h"
14 #include <linux/log2.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/nospec.h>
18 #include <linux/backing-dev.h>
19 #include <trace/events/ext4.h>
20
21 /*
22  * MUSTDO:
23  *   - test ext4_ext_search_left() and ext4_ext_search_right()
24  *   - search for metadata in few groups
25  *
26  * TODO v4:
27  *   - normalization should take into account whether file is still open
28  *   - discard preallocations if no free space left (policy?)
29  *   - don't normalize tails
30  *   - quota
31  *   - reservation for superuser
32  *
33  * TODO v3:
34  *   - bitmap read-ahead (proposed by Oleg Drokin aka green)
35  *   - track min/max extents in each group for better group selection
36  *   - mb_mark_used() may allocate chunk right after splitting buddy
37  *   - tree of groups sorted by number of free blocks
38  *   - error handling
39  */
40
41 /*
42  * The allocation request involve request for multiple number of blocks
43  * near to the goal(block) value specified.
44  *
45  * During initialization phase of the allocator we decide to use the
46  * group preallocation or inode preallocation depending on the size of
47  * the file. The size of the file could be the resulting file size we
48  * would have after allocation, or the current file size, which ever
49  * is larger. If the size is less than sbi->s_mb_stream_request we
50  * select to use the group preallocation. The default value of
51  * s_mb_stream_request is 16 blocks. This can also be tuned via
52  * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
53  * terms of number of blocks.
54  *
55  * The main motivation for having small file use group preallocation is to
56  * ensure that we have small files closer together on the disk.
57  *
58  * First stage the allocator looks at the inode prealloc list,
59  * ext4_inode_info->i_prealloc_list, which contains list of prealloc
60  * spaces for this particular inode. The inode prealloc space is
61  * represented as:
62  *
63  * pa_lstart -> the logical start block for this prealloc space
64  * pa_pstart -> the physical start block for this prealloc space
65  * pa_len    -> length for this prealloc space (in clusters)
66  * pa_free   ->  free space available in this prealloc space (in clusters)
67  *
68  * The inode preallocation space is used looking at the _logical_ start
69  * block. If only the logical file block falls within the range of prealloc
70  * space we will consume the particular prealloc space. This makes sure that
71  * we have contiguous physical blocks representing the file blocks
72  *
73  * The important thing to be noted in case of inode prealloc space is that
74  * we don't modify the values associated to inode prealloc space except
75  * pa_free.
76  *
77  * If we are not able to find blocks in the inode prealloc space and if we
78  * have the group allocation flag set then we look at the locality group
79  * prealloc space. These are per CPU prealloc list represented as
80  *
81  * ext4_sb_info.s_locality_groups[smp_processor_id()]
82  *
83  * The reason for having a per cpu locality group is to reduce the contention
84  * between CPUs. It is possible to get scheduled at this point.
85  *
86  * The locality group prealloc space is used looking at whether we have
87  * enough free space (pa_free) within the prealloc space.
88  *
89  * If we can't allocate blocks via inode prealloc or/and locality group
90  * prealloc then we look at the buddy cache. The buddy cache is represented
91  * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
92  * mapped to the buddy and bitmap information regarding different
93  * groups. The buddy information is attached to buddy cache inode so that
94  * we can access them through the page cache. The information regarding
95  * each group is loaded via ext4_mb_load_buddy.  The information involve
96  * block bitmap and buddy information. The information are stored in the
97  * inode as:
98  *
99  *  {                        page                        }
100  *  [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
101  *
102  *
103  * one block each for bitmap and buddy information.  So for each group we
104  * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
105  * blocksize) blocks.  So it can have information regarding groups_per_page
106  * which is blocks_per_page/2
107  *
108  * The buddy cache inode is not stored on disk. The inode is thrown
109  * away when the filesystem is unmounted.
110  *
111  * We look for count number of blocks in the buddy cache. If we were able
112  * to locate that many free blocks we return with additional information
113  * regarding rest of the contiguous physical block available
114  *
115  * Before allocating blocks via buddy cache we normalize the request
116  * blocks. This ensure we ask for more blocks that we needed. The extra
117  * blocks that we get after allocation is added to the respective prealloc
118  * list. In case of inode preallocation we follow a list of heuristics
119  * based on file size. This can be found in ext4_mb_normalize_request. If
120  * we are doing a group prealloc we try to normalize the request to
121  * sbi->s_mb_group_prealloc.  The default value of s_mb_group_prealloc is
122  * dependent on the cluster size; for non-bigalloc file systems, it is
123  * 512 blocks. This can be tuned via
124  * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
125  * terms of number of blocks. If we have mounted the file system with -O
126  * stripe=<value> option the group prealloc request is normalized to the
127  * the smallest multiple of the stripe value (sbi->s_stripe) which is
128  * greater than the default mb_group_prealloc.
129  *
130  * The regular allocator (using the buddy cache) supports a few tunables.
131  *
132  * /sys/fs/ext4/<partition>/mb_min_to_scan
133  * /sys/fs/ext4/<partition>/mb_max_to_scan
134  * /sys/fs/ext4/<partition>/mb_order2_req
135  *
136  * The regular allocator uses buddy scan only if the request len is power of
137  * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
138  * value of s_mb_order2_reqs can be tuned via
139  * /sys/fs/ext4/<partition>/mb_order2_req.  If the request len is equal to
140  * stripe size (sbi->s_stripe), we try to search for contiguous block in
141  * stripe size. This should result in better allocation on RAID setups. If
142  * not, we search in the specific group using bitmap for best extents. The
143  * tunable min_to_scan and max_to_scan control the behaviour here.
144  * min_to_scan indicate how long the mballoc __must__ look for a best
145  * extent and max_to_scan indicates how long the mballoc __can__ look for a
146  * best extent in the found extents. Searching for the blocks starts with
147  * the group specified as the goal value in allocation context via
148  * ac_g_ex. Each group is first checked based on the criteria whether it
149  * can be used for allocation. ext4_mb_good_group explains how the groups are
150  * checked.
151  *
152  * Both the prealloc space are getting populated as above. So for the first
153  * request we will hit the buddy cache which will result in this prealloc
154  * space getting filled. The prealloc space is then later used for the
155  * subsequent request.
156  */
157
158 /*
159  * mballoc operates on the following data:
160  *  - on-disk bitmap
161  *  - in-core buddy (actually includes buddy and bitmap)
162  *  - preallocation descriptors (PAs)
163  *
164  * there are two types of preallocations:
165  *  - inode
166  *    assiged to specific inode and can be used for this inode only.
167  *    it describes part of inode's space preallocated to specific
168  *    physical blocks. any block from that preallocated can be used
169  *    independent. the descriptor just tracks number of blocks left
170  *    unused. so, before taking some block from descriptor, one must
171  *    make sure corresponded logical block isn't allocated yet. this
172  *    also means that freeing any block within descriptor's range
173  *    must discard all preallocated blocks.
174  *  - locality group
175  *    assigned to specific locality group which does not translate to
176  *    permanent set of inodes: inode can join and leave group. space
177  *    from this type of preallocation can be used for any inode. thus
178  *    it's consumed from the beginning to the end.
179  *
180  * relation between them can be expressed as:
181  *    in-core buddy = on-disk bitmap + preallocation descriptors
182  *
183  * this mean blocks mballoc considers used are:
184  *  - allocated blocks (persistent)
185  *  - preallocated blocks (non-persistent)
186  *
187  * consistency in mballoc world means that at any time a block is either
188  * free or used in ALL structures. notice: "any time" should not be read
189  * literally -- time is discrete and delimited by locks.
190  *
191  *  to keep it simple, we don't use block numbers, instead we count number of
192  *  blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
193  *
194  * all operations can be expressed as:
195  *  - init buddy:                       buddy = on-disk + PAs
196  *  - new PA:                           buddy += N; PA = N
197  *  - use inode PA:                     on-disk += N; PA -= N
198  *  - discard inode PA                  buddy -= on-disk - PA; PA = 0
199  *  - use locality group PA             on-disk += N; PA -= N
200  *  - discard locality group PA         buddy -= PA; PA = 0
201  *  note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
202  *        is used in real operation because we can't know actual used
203  *        bits from PA, only from on-disk bitmap
204  *
205  * if we follow this strict logic, then all operations above should be atomic.
206  * given some of them can block, we'd have to use something like semaphores
207  * killing performance on high-end SMP hardware. let's try to relax it using
208  * the following knowledge:
209  *  1) if buddy is referenced, it's already initialized
210  *  2) while block is used in buddy and the buddy is referenced,
211  *     nobody can re-allocate that block
212  *  3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
213  *     bit set and PA claims same block, it's OK. IOW, one can set bit in
214  *     on-disk bitmap if buddy has same bit set or/and PA covers corresponded
215  *     block
216  *
217  * so, now we're building a concurrency table:
218  *  - init buddy vs.
219  *    - new PA
220  *      blocks for PA are allocated in the buddy, buddy must be referenced
221  *      until PA is linked to allocation group to avoid concurrent buddy init
222  *    - use inode PA
223  *      we need to make sure that either on-disk bitmap or PA has uptodate data
224  *      given (3) we care that PA-=N operation doesn't interfere with init
225  *    - discard inode PA
226  *      the simplest way would be to have buddy initialized by the discard
227  *    - use locality group PA
228  *      again PA-=N must be serialized with init
229  *    - discard locality group PA
230  *      the simplest way would be to have buddy initialized by the discard
231  *  - new PA vs.
232  *    - use inode PA
233  *      i_data_sem serializes them
234  *    - discard inode PA
235  *      discard process must wait until PA isn't used by another process
236  *    - use locality group PA
237  *      some mutex should serialize them
238  *    - discard locality group PA
239  *      discard process must wait until PA isn't used by another process
240  *  - use inode PA
241  *    - use inode PA
242  *      i_data_sem or another mutex should serializes them
243  *    - discard inode PA
244  *      discard process must wait until PA isn't used by another process
245  *    - use locality group PA
246  *      nothing wrong here -- they're different PAs covering different blocks
247  *    - discard locality group PA
248  *      discard process must wait until PA isn't used by another process
249  *
250  * now we're ready to make few consequences:
251  *  - PA is referenced and while it is no discard is possible
252  *  - PA is referenced until block isn't marked in on-disk bitmap
253  *  - PA changes only after on-disk bitmap
254  *  - discard must not compete with init. either init is done before
255  *    any discard or they're serialized somehow
256  *  - buddy init as sum of on-disk bitmap and PAs is done atomically
257  *
258  * a special case when we've used PA to emptiness. no need to modify buddy
259  * in this case, but we should care about concurrent init
260  *
261  */
262
263  /*
264  * Logic in few words:
265  *
266  *  - allocation:
267  *    load group
268  *    find blocks
269  *    mark bits in on-disk bitmap
270  *    release group
271  *
272  *  - use preallocation:
273  *    find proper PA (per-inode or group)
274  *    load group
275  *    mark bits in on-disk bitmap
276  *    release group
277  *    release PA
278  *
279  *  - free:
280  *    load group
281  *    mark bits in on-disk bitmap
282  *    release group
283  *
284  *  - discard preallocations in group:
285  *    mark PAs deleted
286  *    move them onto local list
287  *    load on-disk bitmap
288  *    load group
289  *    remove PA from object (inode or locality group)
290  *    mark free blocks in-core
291  *
292  *  - discard inode's preallocations:
293  */
294
295 /*
296  * Locking rules
297  *
298  * Locks:
299  *  - bitlock on a group        (group)
300  *  - object (inode/locality)   (object)
301  *  - per-pa lock               (pa)
302  *
303  * Paths:
304  *  - new pa
305  *    object
306  *    group
307  *
308  *  - find and use pa:
309  *    pa
310  *
311  *  - release consumed pa:
312  *    pa
313  *    group
314  *    object
315  *
316  *  - generate in-core bitmap:
317  *    group
318  *        pa
319  *
320  *  - discard all for given object (inode, locality group):
321  *    object
322  *        pa
323  *    group
324  *
325  *  - discard all for given group:
326  *    group
327  *        pa
328  *    group
329  *        object
330  *
331  */
332 static struct kmem_cache *ext4_pspace_cachep;
333 static struct kmem_cache *ext4_ac_cachep;
334 static struct kmem_cache *ext4_free_data_cachep;
335
336 /* We create slab caches for groupinfo data structures based on the
337  * superblock block size.  There will be one per mounted filesystem for
338  * each unique s_blocksize_bits */
339 #define NR_GRPINFO_CACHES 8
340 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
341
342 static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
343         "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
344         "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
345         "ext4_groupinfo_64k", "ext4_groupinfo_128k"
346 };
347
348 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
349                                         ext4_group_t group);
350 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
351                                                 ext4_group_t group);
352 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac);
353
354 /*
355  * The algorithm using this percpu seq counter goes below:
356  * 1. We sample the percpu discard_pa_seq counter before trying for block
357  *    allocation in ext4_mb_new_blocks().
358  * 2. We increment this percpu discard_pa_seq counter when we either allocate
359  *    or free these blocks i.e. while marking those blocks as used/free in
360  *    mb_mark_used()/mb_free_blocks().
361  * 3. We also increment this percpu seq counter when we successfully identify
362  *    that the bb_prealloc_list is not empty and hence proceed for discarding
363  *    of those PAs inside ext4_mb_discard_group_preallocations().
364  *
365  * Now to make sure that the regular fast path of block allocation is not
366  * affected, as a small optimization we only sample the percpu seq counter
367  * on that cpu. Only when the block allocation fails and when freed blocks
368  * found were 0, that is when we sample percpu seq counter for all cpus using
369  * below function ext4_get_discard_pa_seq_sum(). This happens after making
370  * sure that all the PAs on grp->bb_prealloc_list got freed or if it's empty.
371  */
372 static DEFINE_PER_CPU(u64, discard_pa_seq);
373 static inline u64 ext4_get_discard_pa_seq_sum(void)
374 {
375         int __cpu;
376         u64 __seq = 0;
377
378         for_each_possible_cpu(__cpu)
379                 __seq += per_cpu(discard_pa_seq, __cpu);
380         return __seq;
381 }
382
383 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
384 {
385 #if BITS_PER_LONG == 64
386         *bit += ((unsigned long) addr & 7UL) << 3;
387         addr = (void *) ((unsigned long) addr & ~7UL);
388 #elif BITS_PER_LONG == 32
389         *bit += ((unsigned long) addr & 3UL) << 3;
390         addr = (void *) ((unsigned long) addr & ~3UL);
391 #else
392 #error "how many bits you are?!"
393 #endif
394         return addr;
395 }
396
397 static inline int mb_test_bit(int bit, void *addr)
398 {
399         /*
400          * ext4_test_bit on architecture like powerpc
401          * needs unsigned long aligned address
402          */
403         addr = mb_correct_addr_and_bit(&bit, addr);
404         return ext4_test_bit(bit, addr);
405 }
406
407 static inline void mb_set_bit(int bit, void *addr)
408 {
409         addr = mb_correct_addr_and_bit(&bit, addr);
410         ext4_set_bit(bit, addr);
411 }
412
413 static inline void mb_clear_bit(int bit, void *addr)
414 {
415         addr = mb_correct_addr_and_bit(&bit, addr);
416         ext4_clear_bit(bit, addr);
417 }
418
419 static inline int mb_test_and_clear_bit(int bit, void *addr)
420 {
421         addr = mb_correct_addr_and_bit(&bit, addr);
422         return ext4_test_and_clear_bit(bit, addr);
423 }
424
425 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
426 {
427         int fix = 0, ret, tmpmax;
428         addr = mb_correct_addr_and_bit(&fix, addr);
429         tmpmax = max + fix;
430         start += fix;
431
432         ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
433         if (ret > max)
434                 return max;
435         return ret;
436 }
437
438 static inline int mb_find_next_bit(void *addr, int max, int start)
439 {
440         int fix = 0, ret, tmpmax;
441         addr = mb_correct_addr_and_bit(&fix, addr);
442         tmpmax = max + fix;
443         start += fix;
444
445         ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
446         if (ret > max)
447                 return max;
448         return ret;
449 }
450
451 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
452 {
453         char *bb;
454
455         BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
456         BUG_ON(max == NULL);
457
458         if (order > e4b->bd_blkbits + 1) {
459                 *max = 0;
460                 return NULL;
461         }
462
463         /* at order 0 we see each particular block */
464         if (order == 0) {
465                 *max = 1 << (e4b->bd_blkbits + 3);
466                 return e4b->bd_bitmap;
467         }
468
469         bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
470         *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
471
472         return bb;
473 }
474
475 #ifdef DOUBLE_CHECK
476 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
477                            int first, int count)
478 {
479         int i;
480         struct super_block *sb = e4b->bd_sb;
481
482         if (unlikely(e4b->bd_info->bb_bitmap == NULL))
483                 return;
484         assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
485         for (i = 0; i < count; i++) {
486                 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
487                         ext4_fsblk_t blocknr;
488
489                         blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
490                         blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
491                         ext4_grp_locked_error(sb, e4b->bd_group,
492                                               inode ? inode->i_ino : 0,
493                                               blocknr,
494                                               "freeing block already freed "
495                                               "(bit %u)",
496                                               first + i);
497                         ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
498                                         EXT4_GROUP_INFO_BBITMAP_CORRUPT);
499                 }
500                 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
501         }
502 }
503
504 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
505 {
506         int i;
507
508         if (unlikely(e4b->bd_info->bb_bitmap == NULL))
509                 return;
510         assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
511         for (i = 0; i < count; i++) {
512                 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
513                 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
514         }
515 }
516
517 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
518 {
519         if (unlikely(e4b->bd_info->bb_bitmap == NULL))
520                 return;
521         if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
522                 unsigned char *b1, *b2;
523                 int i;
524                 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
525                 b2 = (unsigned char *) bitmap;
526                 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
527                         if (b1[i] != b2[i]) {
528                                 ext4_msg(e4b->bd_sb, KERN_ERR,
529                                          "corruption in group %u "
530                                          "at byte %u(%u): %x in copy != %x "
531                                          "on disk/prealloc",
532                                          e4b->bd_group, i, i * 8, b1[i], b2[i]);
533                                 BUG();
534                         }
535                 }
536         }
537 }
538
539 static void mb_group_bb_bitmap_alloc(struct super_block *sb,
540                         struct ext4_group_info *grp, ext4_group_t group)
541 {
542         struct buffer_head *bh;
543
544         grp->bb_bitmap = kmalloc(sb->s_blocksize, GFP_NOFS);
545         if (!grp->bb_bitmap)
546                 return;
547
548         bh = ext4_read_block_bitmap(sb, group);
549         if (IS_ERR_OR_NULL(bh)) {
550                 kfree(grp->bb_bitmap);
551                 grp->bb_bitmap = NULL;
552                 return;
553         }
554
555         memcpy(grp->bb_bitmap, bh->b_data, sb->s_blocksize);
556         put_bh(bh);
557 }
558
559 static void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
560 {
561         kfree(grp->bb_bitmap);
562 }
563
564 #else
565 static inline void mb_free_blocks_double(struct inode *inode,
566                                 struct ext4_buddy *e4b, int first, int count)
567 {
568         return;
569 }
570 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
571                                                 int first, int count)
572 {
573         return;
574 }
575 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
576 {
577         return;
578 }
579
580 static inline void mb_group_bb_bitmap_alloc(struct super_block *sb,
581                         struct ext4_group_info *grp, ext4_group_t group)
582 {
583         return;
584 }
585
586 static inline void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
587 {
588         return;
589 }
590 #endif
591
592 #ifdef AGGRESSIVE_CHECK
593
594 #define MB_CHECK_ASSERT(assert)                                         \
595 do {                                                                    \
596         if (!(assert)) {                                                \
597                 printk(KERN_EMERG                                       \
598                         "Assertion failure in %s() at %s:%d: \"%s\"\n", \
599                         function, file, line, # assert);                \
600                 BUG();                                                  \
601         }                                                               \
602 } while (0)
603
604 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
605                                 const char *function, int line)
606 {
607         struct super_block *sb = e4b->bd_sb;
608         int order = e4b->bd_blkbits + 1;
609         int max;
610         int max2;
611         int i;
612         int j;
613         int k;
614         int count;
615         struct ext4_group_info *grp;
616         int fragments = 0;
617         int fstart;
618         struct list_head *cur;
619         void *buddy;
620         void *buddy2;
621
622         {
623                 static int mb_check_counter;
624                 if (mb_check_counter++ % 100 != 0)
625                         return 0;
626         }
627
628         while (order > 1) {
629                 buddy = mb_find_buddy(e4b, order, &max);
630                 MB_CHECK_ASSERT(buddy);
631                 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
632                 MB_CHECK_ASSERT(buddy2);
633                 MB_CHECK_ASSERT(buddy != buddy2);
634                 MB_CHECK_ASSERT(max * 2 == max2);
635
636                 count = 0;
637                 for (i = 0; i < max; i++) {
638
639                         if (mb_test_bit(i, buddy)) {
640                                 /* only single bit in buddy2 may be 1 */
641                                 if (!mb_test_bit(i << 1, buddy2)) {
642                                         MB_CHECK_ASSERT(
643                                                 mb_test_bit((i<<1)+1, buddy2));
644                                 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
645                                         MB_CHECK_ASSERT(
646                                                 mb_test_bit(i << 1, buddy2));
647                                 }
648                                 continue;
649                         }
650
651                         /* both bits in buddy2 must be 1 */
652                         MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
653                         MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
654
655                         for (j = 0; j < (1 << order); j++) {
656                                 k = (i * (1 << order)) + j;
657                                 MB_CHECK_ASSERT(
658                                         !mb_test_bit(k, e4b->bd_bitmap));
659                         }
660                         count++;
661                 }
662                 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
663                 order--;
664         }
665
666         fstart = -1;
667         buddy = mb_find_buddy(e4b, 0, &max);
668         for (i = 0; i < max; i++) {
669                 if (!mb_test_bit(i, buddy)) {
670                         MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
671                         if (fstart == -1) {
672                                 fragments++;
673                                 fstart = i;
674                         }
675                         continue;
676                 }
677                 fstart = -1;
678                 /* check used bits only */
679                 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
680                         buddy2 = mb_find_buddy(e4b, j, &max2);
681                         k = i >> j;
682                         MB_CHECK_ASSERT(k < max2);
683                         MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
684                 }
685         }
686         MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
687         MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
688
689         grp = ext4_get_group_info(sb, e4b->bd_group);
690         list_for_each(cur, &grp->bb_prealloc_list) {
691                 ext4_group_t groupnr;
692                 struct ext4_prealloc_space *pa;
693                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
694                 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
695                 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
696                 for (i = 0; i < pa->pa_len; i++)
697                         MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
698         }
699         return 0;
700 }
701 #undef MB_CHECK_ASSERT
702 #define mb_check_buddy(e4b) __mb_check_buddy(e4b,       \
703                                         __FILE__, __func__, __LINE__)
704 #else
705 #define mb_check_buddy(e4b)
706 #endif
707
708 /*
709  * Divide blocks started from @first with length @len into
710  * smaller chunks with power of 2 blocks.
711  * Clear the bits in bitmap which the blocks of the chunk(s) covered,
712  * then increase bb_counters[] for corresponded chunk size.
713  */
714 static void ext4_mb_mark_free_simple(struct super_block *sb,
715                                 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
716                                         struct ext4_group_info *grp)
717 {
718         struct ext4_sb_info *sbi = EXT4_SB(sb);
719         ext4_grpblk_t min;
720         ext4_grpblk_t max;
721         ext4_grpblk_t chunk;
722         unsigned int border;
723
724         BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
725
726         border = 2 << sb->s_blocksize_bits;
727
728         while (len > 0) {
729                 /* find how many blocks can be covered since this position */
730                 max = ffs(first | border) - 1;
731
732                 /* find how many blocks of power 2 we need to mark */
733                 min = fls(len) - 1;
734
735                 if (max < min)
736                         min = max;
737                 chunk = 1 << min;
738
739                 /* mark multiblock chunks only */
740                 grp->bb_counters[min]++;
741                 if (min > 0)
742                         mb_clear_bit(first >> min,
743                                      buddy + sbi->s_mb_offsets[min]);
744
745                 len -= chunk;
746                 first += chunk;
747         }
748 }
749
750 /*
751  * Cache the order of the largest free extent we have available in this block
752  * group.
753  */
754 static void
755 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
756 {
757         int i;
758         int bits;
759
760         grp->bb_largest_free_order = -1; /* uninit */
761
762         bits = sb->s_blocksize_bits + 1;
763         for (i = bits; i >= 0; i--) {
764                 if (grp->bb_counters[i] > 0) {
765                         grp->bb_largest_free_order = i;
766                         break;
767                 }
768         }
769 }
770
771 static noinline_for_stack
772 void ext4_mb_generate_buddy(struct super_block *sb,
773                                 void *buddy, void *bitmap, ext4_group_t group)
774 {
775         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
776         struct ext4_sb_info *sbi = EXT4_SB(sb);
777         ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
778         ext4_grpblk_t i = 0;
779         ext4_grpblk_t first;
780         ext4_grpblk_t len;
781         unsigned free = 0;
782         unsigned fragments = 0;
783         unsigned long long period = get_cycles();
784
785         /* initialize buddy from bitmap which is aggregation
786          * of on-disk bitmap and preallocations */
787         i = mb_find_next_zero_bit(bitmap, max, 0);
788         grp->bb_first_free = i;
789         while (i < max) {
790                 fragments++;
791                 first = i;
792                 i = mb_find_next_bit(bitmap, max, i);
793                 len = i - first;
794                 free += len;
795                 if (len > 1)
796                         ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
797                 else
798                         grp->bb_counters[0]++;
799                 if (i < max)
800                         i = mb_find_next_zero_bit(bitmap, max, i);
801         }
802         grp->bb_fragments = fragments;
803
804         if (free != grp->bb_free) {
805                 ext4_grp_locked_error(sb, group, 0, 0,
806                                       "block bitmap and bg descriptor "
807                                       "inconsistent: %u vs %u free clusters",
808                                       free, grp->bb_free);
809                 /*
810                  * If we intend to continue, we consider group descriptor
811                  * corrupt and update bb_free using bitmap value
812                  */
813                 grp->bb_free = free;
814                 ext4_mark_group_bitmap_corrupted(sb, group,
815                                         EXT4_GROUP_INFO_BBITMAP_CORRUPT);
816         }
817         mb_set_largest_free_order(sb, grp);
818
819         clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
820
821         period = get_cycles() - period;
822         spin_lock(&sbi->s_bal_lock);
823         sbi->s_mb_buddies_generated++;
824         sbi->s_mb_generation_time += period;
825         spin_unlock(&sbi->s_bal_lock);
826 }
827
828 static void mb_regenerate_buddy(struct ext4_buddy *e4b)
829 {
830         int count;
831         int order = 1;
832         void *buddy;
833
834         while ((buddy = mb_find_buddy(e4b, order++, &count))) {
835                 ext4_set_bits(buddy, 0, count);
836         }
837         e4b->bd_info->bb_fragments = 0;
838         memset(e4b->bd_info->bb_counters, 0,
839                 sizeof(*e4b->bd_info->bb_counters) *
840                 (e4b->bd_sb->s_blocksize_bits + 2));
841
842         ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
843                 e4b->bd_bitmap, e4b->bd_group);
844 }
845
846 /* The buddy information is attached the buddy cache inode
847  * for convenience. The information regarding each group
848  * is loaded via ext4_mb_load_buddy. The information involve
849  * block bitmap and buddy information. The information are
850  * stored in the inode as
851  *
852  * {                        page                        }
853  * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
854  *
855  *
856  * one block each for bitmap and buddy information.
857  * So for each group we take up 2 blocks. A page can
858  * contain blocks_per_page (PAGE_SIZE / blocksize)  blocks.
859  * So it can have information regarding groups_per_page which
860  * is blocks_per_page/2
861  *
862  * Locking note:  This routine takes the block group lock of all groups
863  * for this page; do not hold this lock when calling this routine!
864  */
865
866 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
867 {
868         ext4_group_t ngroups;
869         int blocksize;
870         int blocks_per_page;
871         int groups_per_page;
872         int err = 0;
873         int i;
874         ext4_group_t first_group, group;
875         int first_block;
876         struct super_block *sb;
877         struct buffer_head *bhs;
878         struct buffer_head **bh = NULL;
879         struct inode *inode;
880         char *data;
881         char *bitmap;
882         struct ext4_group_info *grinfo;
883
884         inode = page->mapping->host;
885         sb = inode->i_sb;
886         ngroups = ext4_get_groups_count(sb);
887         blocksize = i_blocksize(inode);
888         blocks_per_page = PAGE_SIZE / blocksize;
889
890         mb_debug(sb, "init page %lu\n", page->index);
891
892         groups_per_page = blocks_per_page >> 1;
893         if (groups_per_page == 0)
894                 groups_per_page = 1;
895
896         /* allocate buffer_heads to read bitmaps */
897         if (groups_per_page > 1) {
898                 i = sizeof(struct buffer_head *) * groups_per_page;
899                 bh = kzalloc(i, gfp);
900                 if (bh == NULL) {
901                         err = -ENOMEM;
902                         goto out;
903                 }
904         } else
905                 bh = &bhs;
906
907         first_group = page->index * blocks_per_page / 2;
908
909         /* read all groups the page covers into the cache */
910         for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
911                 if (group >= ngroups)
912                         break;
913
914                 grinfo = ext4_get_group_info(sb, group);
915                 /*
916                  * If page is uptodate then we came here after online resize
917                  * which added some new uninitialized group info structs, so
918                  * we must skip all initialized uptodate buddies on the page,
919                  * which may be currently in use by an allocating task.
920                  */
921                 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
922                         bh[i] = NULL;
923                         continue;
924                 }
925                 bh[i] = ext4_read_block_bitmap_nowait(sb, group, false);
926                 if (IS_ERR(bh[i])) {
927                         err = PTR_ERR(bh[i]);
928                         bh[i] = NULL;
929                         goto out;
930                 }
931                 mb_debug(sb, "read bitmap for group %u\n", group);
932         }
933
934         /* wait for I/O completion */
935         for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
936                 int err2;
937
938                 if (!bh[i])
939                         continue;
940                 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
941                 if (!err)
942                         err = err2;
943         }
944
945         first_block = page->index * blocks_per_page;
946         for (i = 0; i < blocks_per_page; i++) {
947                 group = (first_block + i) >> 1;
948                 if (group >= ngroups)
949                         break;
950
951                 if (!bh[group - first_group])
952                         /* skip initialized uptodate buddy */
953                         continue;
954
955                 if (!buffer_verified(bh[group - first_group]))
956                         /* Skip faulty bitmaps */
957                         continue;
958                 err = 0;
959
960                 /*
961                  * data carry information regarding this
962                  * particular group in the format specified
963                  * above
964                  *
965                  */
966                 data = page_address(page) + (i * blocksize);
967                 bitmap = bh[group - first_group]->b_data;
968
969                 /*
970                  * We place the buddy block and bitmap block
971                  * close together
972                  */
973                 if ((first_block + i) & 1) {
974                         /* this is block of buddy */
975                         BUG_ON(incore == NULL);
976                         mb_debug(sb, "put buddy for group %u in page %lu/%x\n",
977                                 group, page->index, i * blocksize);
978                         trace_ext4_mb_buddy_bitmap_load(sb, group);
979                         grinfo = ext4_get_group_info(sb, group);
980                         grinfo->bb_fragments = 0;
981                         memset(grinfo->bb_counters, 0,
982                                sizeof(*grinfo->bb_counters) *
983                                 (sb->s_blocksize_bits+2));
984                         /*
985                          * incore got set to the group block bitmap below
986                          */
987                         ext4_lock_group(sb, group);
988                         /* init the buddy */
989                         memset(data, 0xff, blocksize);
990                         ext4_mb_generate_buddy(sb, data, incore, group);
991                         ext4_unlock_group(sb, group);
992                         incore = NULL;
993                 } else {
994                         /* this is block of bitmap */
995                         BUG_ON(incore != NULL);
996                         mb_debug(sb, "put bitmap for group %u in page %lu/%x\n",
997                                 group, page->index, i * blocksize);
998                         trace_ext4_mb_bitmap_load(sb, group);
999
1000                         /* see comments in ext4_mb_put_pa() */
1001                         ext4_lock_group(sb, group);
1002                         memcpy(data, bitmap, blocksize);
1003
1004                         /* mark all preallocated blks used in in-core bitmap */
1005                         ext4_mb_generate_from_pa(sb, data, group);
1006                         ext4_mb_generate_from_freelist(sb, data, group);
1007                         ext4_unlock_group(sb, group);
1008
1009                         /* set incore so that the buddy information can be
1010                          * generated using this
1011                          */
1012                         incore = data;
1013                 }
1014         }
1015         SetPageUptodate(page);
1016
1017 out:
1018         if (bh) {
1019                 for (i = 0; i < groups_per_page; i++)
1020                         brelse(bh[i]);
1021                 if (bh != &bhs)
1022                         kfree(bh);
1023         }
1024         return err;
1025 }
1026
1027 /*
1028  * Lock the buddy and bitmap pages. This make sure other parallel init_group
1029  * on the same buddy page doesn't happen whild holding the buddy page lock.
1030  * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
1031  * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
1032  */
1033 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
1034                 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
1035 {
1036         struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
1037         int block, pnum, poff;
1038         int blocks_per_page;
1039         struct page *page;
1040
1041         e4b->bd_buddy_page = NULL;
1042         e4b->bd_bitmap_page = NULL;
1043
1044         blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1045         /*
1046          * the buddy cache inode stores the block bitmap
1047          * and buddy information in consecutive blocks.
1048          * So for each group we need two blocks.
1049          */
1050         block = group * 2;
1051         pnum = block / blocks_per_page;
1052         poff = block % blocks_per_page;
1053         page = find_or_create_page(inode->i_mapping, pnum, gfp);
1054         if (!page)
1055                 return -ENOMEM;
1056         BUG_ON(page->mapping != inode->i_mapping);
1057         e4b->bd_bitmap_page = page;
1058         e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1059
1060         if (blocks_per_page >= 2) {
1061                 /* buddy and bitmap are on the same page */
1062                 return 0;
1063         }
1064
1065         block++;
1066         pnum = block / blocks_per_page;
1067         page = find_or_create_page(inode->i_mapping, pnum, gfp);
1068         if (!page)
1069                 return -ENOMEM;
1070         BUG_ON(page->mapping != inode->i_mapping);
1071         e4b->bd_buddy_page = page;
1072         return 0;
1073 }
1074
1075 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1076 {
1077         if (e4b->bd_bitmap_page) {
1078                 unlock_page(e4b->bd_bitmap_page);
1079                 put_page(e4b->bd_bitmap_page);
1080         }
1081         if (e4b->bd_buddy_page) {
1082                 unlock_page(e4b->bd_buddy_page);
1083                 put_page(e4b->bd_buddy_page);
1084         }
1085 }
1086
1087 /*
1088  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
1089  * block group lock of all groups for this page; do not hold the BG lock when
1090  * calling this routine!
1091  */
1092 static noinline_for_stack
1093 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1094 {
1095
1096         struct ext4_group_info *this_grp;
1097         struct ext4_buddy e4b;
1098         struct page *page;
1099         int ret = 0;
1100
1101         might_sleep();
1102         mb_debug(sb, "init group %u\n", group);
1103         this_grp = ext4_get_group_info(sb, group);
1104         /*
1105          * This ensures that we don't reinit the buddy cache
1106          * page which map to the group from which we are already
1107          * allocating. If we are looking at the buddy cache we would
1108          * have taken a reference using ext4_mb_load_buddy and that
1109          * would have pinned buddy page to page cache.
1110          * The call to ext4_mb_get_buddy_page_lock will mark the
1111          * page accessed.
1112          */
1113         ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1114         if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1115                 /*
1116                  * somebody initialized the group
1117                  * return without doing anything
1118                  */
1119                 goto err;
1120         }
1121
1122         page = e4b.bd_bitmap_page;
1123         ret = ext4_mb_init_cache(page, NULL, gfp);
1124         if (ret)
1125                 goto err;
1126         if (!PageUptodate(page)) {
1127                 ret = -EIO;
1128                 goto err;
1129         }
1130
1131         if (e4b.bd_buddy_page == NULL) {
1132                 /*
1133                  * If both the bitmap and buddy are in
1134                  * the same page we don't need to force
1135                  * init the buddy
1136                  */
1137                 ret = 0;
1138                 goto err;
1139         }
1140         /* init buddy cache */
1141         page = e4b.bd_buddy_page;
1142         ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1143         if (ret)
1144                 goto err;
1145         if (!PageUptodate(page)) {
1146                 ret = -EIO;
1147                 goto err;
1148         }
1149 err:
1150         ext4_mb_put_buddy_page_lock(&e4b);
1151         return ret;
1152 }
1153
1154 /*
1155  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
1156  * block group lock of all groups for this page; do not hold the BG lock when
1157  * calling this routine!
1158  */
1159 static noinline_for_stack int
1160 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1161                        struct ext4_buddy *e4b, gfp_t gfp)
1162 {
1163         int blocks_per_page;
1164         int block;
1165         int pnum;
1166         int poff;
1167         struct page *page;
1168         int ret;
1169         struct ext4_group_info *grp;
1170         struct ext4_sb_info *sbi = EXT4_SB(sb);
1171         struct inode *inode = sbi->s_buddy_cache;
1172
1173         might_sleep();
1174         mb_debug(sb, "load group %u\n", group);
1175
1176         blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1177         grp = ext4_get_group_info(sb, group);
1178
1179         e4b->bd_blkbits = sb->s_blocksize_bits;
1180         e4b->bd_info = grp;
1181         e4b->bd_sb = sb;
1182         e4b->bd_group = group;
1183         e4b->bd_buddy_page = NULL;
1184         e4b->bd_bitmap_page = NULL;
1185
1186         if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1187                 /*
1188                  * we need full data about the group
1189                  * to make a good selection
1190                  */
1191                 ret = ext4_mb_init_group(sb, group, gfp);
1192                 if (ret)
1193                         return ret;
1194         }
1195
1196         /*
1197          * the buddy cache inode stores the block bitmap
1198          * and buddy information in consecutive blocks.
1199          * So for each group we need two blocks.
1200          */
1201         block = group * 2;
1202         pnum = block / blocks_per_page;
1203         poff = block % blocks_per_page;
1204
1205         /* we could use find_or_create_page(), but it locks page
1206          * what we'd like to avoid in fast path ... */
1207         page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1208         if (page == NULL || !PageUptodate(page)) {
1209                 if (page)
1210                         /*
1211                          * drop the page reference and try
1212                          * to get the page with lock. If we
1213                          * are not uptodate that implies
1214                          * somebody just created the page but
1215                          * is yet to initialize the same. So
1216                          * wait for it to initialize.
1217                          */
1218                         put_page(page);
1219                 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1220                 if (page) {
1221                         BUG_ON(page->mapping != inode->i_mapping);
1222                         if (!PageUptodate(page)) {
1223                                 ret = ext4_mb_init_cache(page, NULL, gfp);
1224                                 if (ret) {
1225                                         unlock_page(page);
1226                                         goto err;
1227                                 }
1228                                 mb_cmp_bitmaps(e4b, page_address(page) +
1229                                                (poff * sb->s_blocksize));
1230                         }
1231                         unlock_page(page);
1232                 }
1233         }
1234         if (page == NULL) {
1235                 ret = -ENOMEM;
1236                 goto err;
1237         }
1238         if (!PageUptodate(page)) {
1239                 ret = -EIO;
1240                 goto err;
1241         }
1242
1243         /* Pages marked accessed already */
1244         e4b->bd_bitmap_page = page;
1245         e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1246
1247         block++;
1248         pnum = block / blocks_per_page;
1249         poff = block % blocks_per_page;
1250
1251         page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1252         if (page == NULL || !PageUptodate(page)) {
1253                 if (page)
1254                         put_page(page);
1255                 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1256                 if (page) {
1257                         BUG_ON(page->mapping != inode->i_mapping);
1258                         if (!PageUptodate(page)) {
1259                                 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1260                                                          gfp);
1261                                 if (ret) {
1262                                         unlock_page(page);
1263                                         goto err;
1264                                 }
1265                         }
1266                         unlock_page(page);
1267                 }
1268         }
1269         if (page == NULL) {
1270                 ret = -ENOMEM;
1271                 goto err;
1272         }
1273         if (!PageUptodate(page)) {
1274                 ret = -EIO;
1275                 goto err;
1276         }
1277
1278         /* Pages marked accessed already */
1279         e4b->bd_buddy_page = page;
1280         e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1281
1282         return 0;
1283
1284 err:
1285         if (page)
1286                 put_page(page);
1287         if (e4b->bd_bitmap_page)
1288                 put_page(e4b->bd_bitmap_page);
1289         if (e4b->bd_buddy_page)
1290                 put_page(e4b->bd_buddy_page);
1291         e4b->bd_buddy = NULL;
1292         e4b->bd_bitmap = NULL;
1293         return ret;
1294 }
1295
1296 static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1297                               struct ext4_buddy *e4b)
1298 {
1299         return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1300 }
1301
1302 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1303 {
1304         if (e4b->bd_bitmap_page)
1305                 put_page(e4b->bd_bitmap_page);
1306         if (e4b->bd_buddy_page)
1307                 put_page(e4b->bd_buddy_page);
1308 }
1309
1310
1311 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1312 {
1313         int order = 1;
1314         int bb_incr = 1 << (e4b->bd_blkbits - 1);
1315         void *bb;
1316
1317         BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1318         BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1319
1320         bb = e4b->bd_buddy;
1321         while (order <= e4b->bd_blkbits + 1) {
1322                 block = block >> 1;
1323                 if (!mb_test_bit(block, bb)) {
1324                         /* this block is part of buddy of order 'order' */
1325                         return order;
1326                 }
1327                 bb += bb_incr;
1328                 bb_incr >>= 1;
1329                 order++;
1330         }
1331         return 0;
1332 }
1333
1334 static void mb_clear_bits(void *bm, int cur, int len)
1335 {
1336         __u32 *addr;
1337
1338         len = cur + len;
1339         while (cur < len) {
1340                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1341                         /* fast path: clear whole word at once */
1342                         addr = bm + (cur >> 3);
1343                         *addr = 0;
1344                         cur += 32;
1345                         continue;
1346                 }
1347                 mb_clear_bit(cur, bm);
1348                 cur++;
1349         }
1350 }
1351
1352 /* clear bits in given range
1353  * will return first found zero bit if any, -1 otherwise
1354  */
1355 static int mb_test_and_clear_bits(void *bm, int cur, int len)
1356 {
1357         __u32 *addr;
1358         int zero_bit = -1;
1359
1360         len = cur + len;
1361         while (cur < len) {
1362                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1363                         /* fast path: clear whole word at once */
1364                         addr = bm + (cur >> 3);
1365                         if (*addr != (__u32)(-1) && zero_bit == -1)
1366                                 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1367                         *addr = 0;
1368                         cur += 32;
1369                         continue;
1370                 }
1371                 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1372                         zero_bit = cur;
1373                 cur++;
1374         }
1375
1376         return zero_bit;
1377 }
1378
1379 void ext4_set_bits(void *bm, int cur, int len)
1380 {
1381         __u32 *addr;
1382
1383         len = cur + len;
1384         while (cur < len) {
1385                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1386                         /* fast path: set whole word at once */
1387                         addr = bm + (cur >> 3);
1388                         *addr = 0xffffffff;
1389                         cur += 32;
1390                         continue;
1391                 }
1392                 mb_set_bit(cur, bm);
1393                 cur++;
1394         }
1395 }
1396
1397 /*
1398  * _________________________________________________________________ */
1399
1400 static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1401 {
1402         if (mb_test_bit(*bit + side, bitmap)) {
1403                 mb_clear_bit(*bit, bitmap);
1404                 (*bit) -= side;
1405                 return 1;
1406         }
1407         else {
1408                 (*bit) += side;
1409                 mb_set_bit(*bit, bitmap);
1410                 return -1;
1411         }
1412 }
1413
1414 static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1415 {
1416         int max;
1417         int order = 1;
1418         void *buddy = mb_find_buddy(e4b, order, &max);
1419
1420         while (buddy) {
1421                 void *buddy2;
1422
1423                 /* Bits in range [first; last] are known to be set since
1424                  * corresponding blocks were allocated. Bits in range
1425                  * (first; last) will stay set because they form buddies on
1426                  * upper layer. We just deal with borders if they don't
1427                  * align with upper layer and then go up.
1428                  * Releasing entire group is all about clearing
1429                  * single bit of highest order buddy.
1430                  */
1431
1432                 /* Example:
1433                  * ---------------------------------
1434                  * |   1   |   1   |   1   |   1   |
1435                  * ---------------------------------
1436                  * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1437                  * ---------------------------------
1438                  *   0   1   2   3   4   5   6   7
1439                  *      \_____________________/
1440                  *
1441                  * Neither [1] nor [6] is aligned to above layer.
1442                  * Left neighbour [0] is free, so mark it busy,
1443                  * decrease bb_counters and extend range to
1444                  * [0; 6]
1445                  * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1446                  * mark [6] free, increase bb_counters and shrink range to
1447                  * [0; 5].
1448                  * Then shift range to [0; 2], go up and do the same.
1449                  */
1450
1451
1452                 if (first & 1)
1453                         e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1454                 if (!(last & 1))
1455                         e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1456                 if (first > last)
1457                         break;
1458                 order++;
1459
1460                 if (first == last || !(buddy2 = mb_find_buddy(e4b, order, &max))) {
1461                         mb_clear_bits(buddy, first, last - first + 1);
1462                         e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1463                         break;
1464                 }
1465                 first >>= 1;
1466                 last >>= 1;
1467                 buddy = buddy2;
1468         }
1469 }
1470
1471 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1472                            int first, int count)
1473 {
1474         int left_is_free = 0;
1475         int right_is_free = 0;
1476         int block;
1477         int last = first + count - 1;
1478         struct super_block *sb = e4b->bd_sb;
1479
1480         if (WARN_ON(count == 0))
1481                 return;
1482         BUG_ON(last >= (sb->s_blocksize << 3));
1483         assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1484         /* Don't bother if the block group is corrupt. */
1485         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1486                 return;
1487
1488         mb_check_buddy(e4b);
1489         mb_free_blocks_double(inode, e4b, first, count);
1490
1491         this_cpu_inc(discard_pa_seq);
1492         e4b->bd_info->bb_free += count;
1493         if (first < e4b->bd_info->bb_first_free)
1494                 e4b->bd_info->bb_first_free = first;
1495
1496         /* access memory sequentially: check left neighbour,
1497          * clear range and then check right neighbour
1498          */
1499         if (first != 0)
1500                 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1501         block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1502         if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1503                 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1504
1505         if (unlikely(block != -1)) {
1506                 struct ext4_sb_info *sbi = EXT4_SB(sb);
1507                 ext4_fsblk_t blocknr;
1508
1509                 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1510                 blocknr += EXT4_C2B(sbi, block);
1511                 ext4_grp_locked_error(sb, e4b->bd_group,
1512                                       inode ? inode->i_ino : 0,
1513                                       blocknr,
1514                                       "freeing already freed block "
1515                                       "(bit %u); block bitmap corrupt.",
1516                                       block);
1517                 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
1518                                 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1519                 mb_regenerate_buddy(e4b);
1520                 goto done;
1521         }
1522
1523         /* let's maintain fragments counter */
1524         if (left_is_free && right_is_free)
1525                 e4b->bd_info->bb_fragments--;
1526         else if (!left_is_free && !right_is_free)
1527                 e4b->bd_info->bb_fragments++;
1528
1529         /* buddy[0] == bd_bitmap is a special case, so handle
1530          * it right away and let mb_buddy_mark_free stay free of
1531          * zero order checks.
1532          * Check if neighbours are to be coaleasced,
1533          * adjust bitmap bb_counters and borders appropriately.
1534          */
1535         if (first & 1) {
1536                 first += !left_is_free;
1537                 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1538         }
1539         if (!(last & 1)) {
1540                 last -= !right_is_free;
1541                 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1542         }
1543
1544         if (first <= last)
1545                 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1546
1547 done:
1548         mb_set_largest_free_order(sb, e4b->bd_info);
1549         mb_check_buddy(e4b);
1550 }
1551
1552 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1553                                 int needed, struct ext4_free_extent *ex)
1554 {
1555         int next = block;
1556         int max, order;
1557         void *buddy;
1558
1559         assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1560         BUG_ON(ex == NULL);
1561
1562         buddy = mb_find_buddy(e4b, 0, &max);
1563         BUG_ON(buddy == NULL);
1564         BUG_ON(block >= max);
1565         if (mb_test_bit(block, buddy)) {
1566                 ex->fe_len = 0;
1567                 ex->fe_start = 0;
1568                 ex->fe_group = 0;
1569                 return 0;
1570         }
1571
1572         /* find actual order */
1573         order = mb_find_order_for_block(e4b, block);
1574         block = block >> order;
1575
1576         ex->fe_len = 1 << order;
1577         ex->fe_start = block << order;
1578         ex->fe_group = e4b->bd_group;
1579
1580         /* calc difference from given start */
1581         next = next - ex->fe_start;
1582         ex->fe_len -= next;
1583         ex->fe_start += next;
1584
1585         while (needed > ex->fe_len &&
1586                mb_find_buddy(e4b, order, &max)) {
1587
1588                 if (block + 1 >= max)
1589                         break;
1590
1591                 next = (block + 1) * (1 << order);
1592                 if (mb_test_bit(next, e4b->bd_bitmap))
1593                         break;
1594
1595                 order = mb_find_order_for_block(e4b, next);
1596
1597                 block = next >> order;
1598                 ex->fe_len += 1 << order;
1599         }
1600
1601         if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
1602                 /* Should never happen! (but apparently sometimes does?!?) */
1603                 WARN_ON(1);
1604                 ext4_error(e4b->bd_sb, "corruption or bug in mb_find_extent "
1605                            "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
1606                            block, order, needed, ex->fe_group, ex->fe_start,
1607                            ex->fe_len, ex->fe_logical);
1608                 ex->fe_len = 0;
1609                 ex->fe_start = 0;
1610                 ex->fe_group = 0;
1611         }
1612         return ex->fe_len;
1613 }
1614
1615 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1616 {
1617         int ord;
1618         int mlen = 0;
1619         int max = 0;
1620         int cur;
1621         int start = ex->fe_start;
1622         int len = ex->fe_len;
1623         unsigned ret = 0;
1624         int len0 = len;
1625         void *buddy;
1626
1627         BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1628         BUG_ON(e4b->bd_group != ex->fe_group);
1629         assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1630         mb_check_buddy(e4b);
1631         mb_mark_used_double(e4b, start, len);
1632
1633         this_cpu_inc(discard_pa_seq);
1634         e4b->bd_info->bb_free -= len;
1635         if (e4b->bd_info->bb_first_free == start)
1636                 e4b->bd_info->bb_first_free += len;
1637
1638         /* let's maintain fragments counter */
1639         if (start != 0)
1640                 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1641         if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1642                 max = !mb_test_bit(start + len, e4b->bd_bitmap);
1643         if (mlen && max)
1644                 e4b->bd_info->bb_fragments++;
1645         else if (!mlen && !max)
1646                 e4b->bd_info->bb_fragments--;
1647
1648         /* let's maintain buddy itself */
1649         while (len) {
1650                 ord = mb_find_order_for_block(e4b, start);
1651
1652                 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1653                         /* the whole chunk may be allocated at once! */
1654                         mlen = 1 << ord;
1655                         buddy = mb_find_buddy(e4b, ord, &max);
1656                         BUG_ON((start >> ord) >= max);
1657                         mb_set_bit(start >> ord, buddy);
1658                         e4b->bd_info->bb_counters[ord]--;
1659                         start += mlen;
1660                         len -= mlen;
1661                         BUG_ON(len < 0);
1662                         continue;
1663                 }
1664
1665                 /* store for history */
1666                 if (ret == 0)
1667                         ret = len | (ord << 16);
1668
1669                 /* we have to split large buddy */
1670                 BUG_ON(ord <= 0);
1671                 buddy = mb_find_buddy(e4b, ord, &max);
1672                 mb_set_bit(start >> ord, buddy);
1673                 e4b->bd_info->bb_counters[ord]--;
1674
1675                 ord--;
1676                 cur = (start >> ord) & ~1U;
1677                 buddy = mb_find_buddy(e4b, ord, &max);
1678                 mb_clear_bit(cur, buddy);
1679                 mb_clear_bit(cur + 1, buddy);
1680                 e4b->bd_info->bb_counters[ord]++;
1681                 e4b->bd_info->bb_counters[ord]++;
1682         }
1683         mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1684
1685         ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1686         mb_check_buddy(e4b);
1687
1688         return ret;
1689 }
1690
1691 /*
1692  * Must be called under group lock!
1693  */
1694 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1695                                         struct ext4_buddy *e4b)
1696 {
1697         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1698         int ret;
1699
1700         BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1701         BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1702
1703         ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1704         ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1705         ret = mb_mark_used(e4b, &ac->ac_b_ex);
1706
1707         /* preallocation can change ac_b_ex, thus we store actually
1708          * allocated blocks for history */
1709         ac->ac_f_ex = ac->ac_b_ex;
1710
1711         ac->ac_status = AC_STATUS_FOUND;
1712         ac->ac_tail = ret & 0xffff;
1713         ac->ac_buddy = ret >> 16;
1714
1715         /*
1716          * take the page reference. We want the page to be pinned
1717          * so that we don't get a ext4_mb_init_cache_call for this
1718          * group until we update the bitmap. That would mean we
1719          * double allocate blocks. The reference is dropped
1720          * in ext4_mb_release_context
1721          */
1722         ac->ac_bitmap_page = e4b->bd_bitmap_page;
1723         get_page(ac->ac_bitmap_page);
1724         ac->ac_buddy_page = e4b->bd_buddy_page;
1725         get_page(ac->ac_buddy_page);
1726         /* store last allocated for subsequent stream allocation */
1727         if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1728                 spin_lock(&sbi->s_md_lock);
1729                 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1730                 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1731                 spin_unlock(&sbi->s_md_lock);
1732         }
1733         /*
1734          * As we've just preallocated more space than
1735          * user requested originally, we store allocated
1736          * space in a special descriptor.
1737          */
1738         if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
1739                 ext4_mb_new_preallocation(ac);
1740
1741 }
1742
1743 /*
1744  * regular allocator, for general purposes allocation
1745  */
1746
1747 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1748                                         struct ext4_buddy *e4b,
1749                                         int finish_group)
1750 {
1751         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1752         struct ext4_free_extent *bex = &ac->ac_b_ex;
1753         struct ext4_free_extent *gex = &ac->ac_g_ex;
1754         struct ext4_free_extent ex;
1755         int max;
1756
1757         if (ac->ac_status == AC_STATUS_FOUND)
1758                 return;
1759         /*
1760          * We don't want to scan for a whole year
1761          */
1762         if (ac->ac_found > sbi->s_mb_max_to_scan &&
1763                         !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1764                 ac->ac_status = AC_STATUS_BREAK;
1765                 return;
1766         }
1767
1768         /*
1769          * Haven't found good chunk so far, let's continue
1770          */
1771         if (bex->fe_len < gex->fe_len)
1772                 return;
1773
1774         if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1775                         && bex->fe_group == e4b->bd_group) {
1776                 /* recheck chunk's availability - we don't know
1777                  * when it was found (within this lock-unlock
1778                  * period or not) */
1779                 max = mb_find_extent(e4b, bex->fe_start, gex->fe_len, &ex);
1780                 if (max >= gex->fe_len) {
1781                         ext4_mb_use_best_found(ac, e4b);
1782                         return;
1783                 }
1784         }
1785 }
1786
1787 /*
1788  * The routine checks whether found extent is good enough. If it is,
1789  * then the extent gets marked used and flag is set to the context
1790  * to stop scanning. Otherwise, the extent is compared with the
1791  * previous found extent and if new one is better, then it's stored
1792  * in the context. Later, the best found extent will be used, if
1793  * mballoc can't find good enough extent.
1794  *
1795  * FIXME: real allocation policy is to be designed yet!
1796  */
1797 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1798                                         struct ext4_free_extent *ex,
1799                                         struct ext4_buddy *e4b)
1800 {
1801         struct ext4_free_extent *bex = &ac->ac_b_ex;
1802         struct ext4_free_extent *gex = &ac->ac_g_ex;
1803
1804         BUG_ON(ex->fe_len <= 0);
1805         BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1806         BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1807         BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1808
1809         ac->ac_found++;
1810
1811         /*
1812          * The special case - take what you catch first
1813          */
1814         if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1815                 *bex = *ex;
1816                 ext4_mb_use_best_found(ac, e4b);
1817                 return;
1818         }
1819
1820         /*
1821          * Let's check whether the chuck is good enough
1822          */
1823         if (ex->fe_len == gex->fe_len) {
1824                 *bex = *ex;
1825                 ext4_mb_use_best_found(ac, e4b);
1826                 return;
1827         }
1828
1829         /*
1830          * If this is first found extent, just store it in the context
1831          */
1832         if (bex->fe_len == 0) {
1833                 *bex = *ex;
1834                 return;
1835         }
1836
1837         /*
1838          * If new found extent is better, store it in the context
1839          */
1840         if (bex->fe_len < gex->fe_len) {
1841                 /* if the request isn't satisfied, any found extent
1842                  * larger than previous best one is better */
1843                 if (ex->fe_len > bex->fe_len)
1844                         *bex = *ex;
1845         } else if (ex->fe_len > gex->fe_len) {
1846                 /* if the request is satisfied, then we try to find
1847                  * an extent that still satisfy the request, but is
1848                  * smaller than previous one */
1849                 if (ex->fe_len < bex->fe_len)
1850                         *bex = *ex;
1851         }
1852
1853         ext4_mb_check_limits(ac, e4b, 0);
1854 }
1855
1856 static noinline_for_stack
1857 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1858                                         struct ext4_buddy *e4b)
1859 {
1860         struct ext4_free_extent ex = ac->ac_b_ex;
1861         ext4_group_t group = ex.fe_group;
1862         int max;
1863         int err;
1864
1865         BUG_ON(ex.fe_len <= 0);
1866         err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1867         if (err)
1868                 return err;
1869
1870         ext4_lock_group(ac->ac_sb, group);
1871         max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
1872
1873         if (max > 0) {
1874                 ac->ac_b_ex = ex;
1875                 ext4_mb_use_best_found(ac, e4b);
1876         }
1877
1878         ext4_unlock_group(ac->ac_sb, group);
1879         ext4_mb_unload_buddy(e4b);
1880
1881         return 0;
1882 }
1883
1884 static noinline_for_stack
1885 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1886                                 struct ext4_buddy *e4b)
1887 {
1888         ext4_group_t group = ac->ac_g_ex.fe_group;
1889         int max;
1890         int err;
1891         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1892         struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1893         struct ext4_free_extent ex;
1894
1895         if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1896                 return 0;
1897         if (grp->bb_free == 0)
1898                 return 0;
1899
1900         err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1901         if (err)
1902                 return err;
1903
1904         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
1905                 ext4_mb_unload_buddy(e4b);
1906                 return 0;
1907         }
1908
1909         ext4_lock_group(ac->ac_sb, group);
1910         max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
1911                              ac->ac_g_ex.fe_len, &ex);
1912         ex.fe_logical = 0xDEADFA11; /* debug value */
1913
1914         if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1915                 ext4_fsblk_t start;
1916
1917                 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
1918                         ex.fe_start;
1919                 /* use do_div to get remainder (would be 64-bit modulo) */
1920                 if (do_div(start, sbi->s_stripe) == 0) {
1921                         ac->ac_found++;
1922                         ac->ac_b_ex = ex;
1923                         ext4_mb_use_best_found(ac, e4b);
1924                 }
1925         } else if (max >= ac->ac_g_ex.fe_len) {
1926                 BUG_ON(ex.fe_len <= 0);
1927                 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1928                 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1929                 ac->ac_found++;
1930                 ac->ac_b_ex = ex;
1931                 ext4_mb_use_best_found(ac, e4b);
1932         } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1933                 /* Sometimes, caller may want to merge even small
1934                  * number of blocks to an existing extent */
1935                 BUG_ON(ex.fe_len <= 0);
1936                 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1937                 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1938                 ac->ac_found++;
1939                 ac->ac_b_ex = ex;
1940                 ext4_mb_use_best_found(ac, e4b);
1941         }
1942         ext4_unlock_group(ac->ac_sb, group);
1943         ext4_mb_unload_buddy(e4b);
1944
1945         return 0;
1946 }
1947
1948 /*
1949  * The routine scans buddy structures (not bitmap!) from given order
1950  * to max order and tries to find big enough chunk to satisfy the req
1951  */
1952 static noinline_for_stack
1953 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1954                                         struct ext4_buddy *e4b)
1955 {
1956         struct super_block *sb = ac->ac_sb;
1957         struct ext4_group_info *grp = e4b->bd_info;
1958         void *buddy;
1959         int i;
1960         int k;
1961         int max;
1962
1963         BUG_ON(ac->ac_2order <= 0);
1964         for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1965                 if (grp->bb_counters[i] == 0)
1966                         continue;
1967
1968                 buddy = mb_find_buddy(e4b, i, &max);
1969                 BUG_ON(buddy == NULL);
1970
1971                 k = mb_find_next_zero_bit(buddy, max, 0);
1972                 if (k >= max) {
1973                         ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
1974                                 "%d free clusters of order %d. But found 0",
1975                                 grp->bb_counters[i], i);
1976                         ext4_mark_group_bitmap_corrupted(ac->ac_sb,
1977                                          e4b->bd_group,
1978                                         EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1979                         break;
1980                 }
1981                 ac->ac_found++;
1982
1983                 ac->ac_b_ex.fe_len = 1 << i;
1984                 ac->ac_b_ex.fe_start = k << i;
1985                 ac->ac_b_ex.fe_group = e4b->bd_group;
1986
1987                 ext4_mb_use_best_found(ac, e4b);
1988
1989                 BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
1990
1991                 if (EXT4_SB(sb)->s_mb_stats)
1992                         atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1993
1994                 break;
1995         }
1996 }
1997
1998 /*
1999  * The routine scans the group and measures all found extents.
2000  * In order to optimize scanning, caller must pass number of
2001  * free blocks in the group, so the routine can know upper limit.
2002  */
2003 static noinline_for_stack
2004 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
2005                                         struct ext4_buddy *e4b)
2006 {
2007         struct super_block *sb = ac->ac_sb;
2008         void *bitmap = e4b->bd_bitmap;
2009         struct ext4_free_extent ex;
2010         int i;
2011         int free;
2012
2013         free = e4b->bd_info->bb_free;
2014         if (WARN_ON(free <= 0))
2015                 return;
2016
2017         i = e4b->bd_info->bb_first_free;
2018
2019         while (free && ac->ac_status == AC_STATUS_CONTINUE) {
2020                 i = mb_find_next_zero_bit(bitmap,
2021                                                 EXT4_CLUSTERS_PER_GROUP(sb), i);
2022                 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
2023                         /*
2024                          * IF we have corrupt bitmap, we won't find any
2025                          * free blocks even though group info says we
2026                          * we have free blocks
2027                          */
2028                         ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2029                                         "%d free clusters as per "
2030                                         "group info. But bitmap says 0",
2031                                         free);
2032                         ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2033                                         EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2034                         break;
2035                 }
2036
2037                 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
2038                 if (WARN_ON(ex.fe_len <= 0))
2039                         break;
2040                 if (free < ex.fe_len) {
2041                         ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2042                                         "%d free clusters as per "
2043                                         "group info. But got %d blocks",
2044                                         free, ex.fe_len);
2045                         ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2046                                         EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2047                         /*
2048                          * The number of free blocks differs. This mostly
2049                          * indicate that the bitmap is corrupt. So exit
2050                          * without claiming the space.
2051                          */
2052                         break;
2053                 }
2054                 ex.fe_logical = 0xDEADC0DE; /* debug value */
2055                 ext4_mb_measure_extent(ac, &ex, e4b);
2056
2057                 i += ex.fe_len;
2058                 free -= ex.fe_len;
2059         }
2060
2061         ext4_mb_check_limits(ac, e4b, 1);
2062 }
2063
2064 /*
2065  * This is a special case for storages like raid5
2066  * we try to find stripe-aligned chunks for stripe-size-multiple requests
2067  */
2068 static noinline_for_stack
2069 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2070                                  struct ext4_buddy *e4b)
2071 {
2072         struct super_block *sb = ac->ac_sb;
2073         struct ext4_sb_info *sbi = EXT4_SB(sb);
2074         void *bitmap = e4b->bd_bitmap;
2075         struct ext4_free_extent ex;
2076         ext4_fsblk_t first_group_block;
2077         ext4_fsblk_t a;
2078         ext4_grpblk_t i;
2079         int max;
2080
2081         BUG_ON(sbi->s_stripe == 0);
2082
2083         /* find first stripe-aligned block in group */
2084         first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2085
2086         a = first_group_block + sbi->s_stripe - 1;
2087         do_div(a, sbi->s_stripe);
2088         i = (a * sbi->s_stripe) - first_group_block;
2089
2090         while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2091                 if (!mb_test_bit(i, bitmap)) {
2092                         max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
2093                         if (max >= sbi->s_stripe) {
2094                                 ac->ac_found++;
2095                                 ex.fe_logical = 0xDEADF00D; /* debug value */
2096                                 ac->ac_b_ex = ex;
2097                                 ext4_mb_use_best_found(ac, e4b);
2098                                 break;
2099                         }
2100                 }
2101                 i += sbi->s_stripe;
2102         }
2103 }
2104
2105 /*
2106  * This is also called BEFORE we load the buddy bitmap.
2107  * Returns either 1 or 0 indicating that the group is either suitable
2108  * for the allocation or not.
2109  */
2110 static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
2111                                 ext4_group_t group, int cr)
2112 {
2113         ext4_grpblk_t free, fragments;
2114         int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2115         struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2116
2117         BUG_ON(cr < 0 || cr >= 4);
2118
2119         free = grp->bb_free;
2120         if (free == 0)
2121                 return false;
2122         if (cr <= 2 && free < ac->ac_g_ex.fe_len)
2123                 return false;
2124
2125         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2126                 return false;
2127
2128         fragments = grp->bb_fragments;
2129         if (fragments == 0)
2130                 return false;
2131
2132         switch (cr) {
2133         case 0:
2134                 BUG_ON(ac->ac_2order == 0);
2135
2136                 /* Avoid using the first bg of a flexgroup for data files */
2137                 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2138                     (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2139                     ((group % flex_size) == 0))
2140                         return false;
2141
2142                 if ((ac->ac_2order > ac->ac_sb->s_blocksize_bits+1) ||
2143                     (free / fragments) >= ac->ac_g_ex.fe_len)
2144                         return true;
2145
2146                 if (grp->bb_largest_free_order < ac->ac_2order)
2147                         return false;
2148
2149                 return true;
2150         case 1:
2151                 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2152                         return true;
2153                 break;
2154         case 2:
2155                 if (free >= ac->ac_g_ex.fe_len)
2156                         return true;
2157                 break;
2158         case 3:
2159                 return true;
2160         default:
2161                 BUG();
2162         }
2163
2164         return false;
2165 }
2166
2167 /*
2168  * This could return negative error code if something goes wrong
2169  * during ext4_mb_init_group(). This should not be called with
2170  * ext4_lock_group() held.
2171  */
2172 static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
2173                                      ext4_group_t group, int cr)
2174 {
2175         struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2176         struct super_block *sb = ac->ac_sb;
2177         struct ext4_sb_info *sbi = EXT4_SB(sb);
2178         bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
2179         ext4_grpblk_t free;
2180         int ret = 0;
2181
2182         if (should_lock)
2183                 ext4_lock_group(sb, group);
2184         free = grp->bb_free;
2185         if (free == 0)
2186                 goto out;
2187         if (cr <= 2 && free < ac->ac_g_ex.fe_len)
2188                 goto out;
2189         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2190                 goto out;
2191         if (should_lock)
2192                 ext4_unlock_group(sb, group);
2193
2194         /* We only do this if the grp has never been initialized */
2195         if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2196                 struct ext4_group_desc *gdp =
2197                         ext4_get_group_desc(sb, group, NULL);
2198                 int ret;
2199
2200                 /* cr=0/1 is a very optimistic search to find large
2201                  * good chunks almost for free.  If buddy data is not
2202                  * ready, then this optimization makes no sense.  But
2203                  * we never skip the first block group in a flex_bg,
2204                  * since this gets used for metadata block allocation,
2205                  * and we want to make sure we locate metadata blocks
2206                  * in the first block group in the flex_bg if possible.
2207                  */
2208                 if (cr < 2 &&
2209                     (!sbi->s_log_groups_per_flex ||
2210                      ((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
2211                     !(ext4_has_group_desc_csum(sb) &&
2212                       (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
2213                         return 0;
2214                 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
2215                 if (ret)
2216                         return ret;
2217         }
2218
2219         if (should_lock)
2220                 ext4_lock_group(sb, group);
2221         ret = ext4_mb_good_group(ac, group, cr);
2222 out:
2223         if (should_lock)
2224                 ext4_unlock_group(sb, group);
2225         return ret;
2226 }
2227
2228 /*
2229  * Start prefetching @nr block bitmaps starting at @group.
2230  * Return the next group which needs to be prefetched.
2231  */
2232 ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
2233                               unsigned int nr, int *cnt)
2234 {
2235         ext4_group_t ngroups = ext4_get_groups_count(sb);
2236         struct buffer_head *bh;
2237         struct blk_plug plug;
2238
2239         blk_start_plug(&plug);
2240         while (nr-- > 0) {
2241                 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2242                                                                   NULL);
2243                 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2244
2245                 /*
2246                  * Prefetch block groups with free blocks; but don't
2247                  * bother if it is marked uninitialized on disk, since
2248                  * it won't require I/O to read.  Also only try to
2249                  * prefetch once, so we avoid getblk() call, which can
2250                  * be expensive.
2251                  */
2252                 if (!EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
2253                     EXT4_MB_GRP_NEED_INIT(grp) &&
2254                     ext4_free_group_clusters(sb, gdp) > 0 &&
2255                     !(ext4_has_group_desc_csum(sb) &&
2256                       (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)))) {
2257                         bh = ext4_read_block_bitmap_nowait(sb, group, true);
2258                         if (bh && !IS_ERR(bh)) {
2259                                 if (!buffer_uptodate(bh) && cnt)
2260                                         (*cnt)++;
2261                                 brelse(bh);
2262                         }
2263                 }
2264                 if (++group >= ngroups)
2265                         group = 0;
2266         }
2267         blk_finish_plug(&plug);
2268         return group;
2269 }
2270
2271 /*
2272  * Prefetching reads the block bitmap into the buffer cache; but we
2273  * need to make sure that the buddy bitmap in the page cache has been
2274  * initialized.  Note that ext4_mb_init_group() will block if the I/O
2275  * is not yet completed, or indeed if it was not initiated by
2276  * ext4_mb_prefetch did not start the I/O.
2277  *
2278  * TODO: We should actually kick off the buddy bitmap setup in a work
2279  * queue when the buffer I/O is completed, so that we don't block
2280  * waiting for the block allocation bitmap read to finish when
2281  * ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
2282  */
2283 void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
2284                            unsigned int nr)
2285 {
2286         while (nr-- > 0) {
2287                 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2288                                                                   NULL);
2289                 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2290
2291                 if (!group)
2292                         group = ext4_get_groups_count(sb);
2293                 group--;
2294                 grp = ext4_get_group_info(sb, group);
2295
2296                 if (EXT4_MB_GRP_NEED_INIT(grp) &&
2297                     ext4_free_group_clusters(sb, gdp) > 0 &&
2298                     !(ext4_has_group_desc_csum(sb) &&
2299                       (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)))) {
2300                         if (ext4_mb_init_group(sb, group, GFP_NOFS))
2301                                 break;
2302                 }
2303         }
2304 }
2305
2306 static noinline_for_stack int
2307 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2308 {
2309         ext4_group_t prefetch_grp = 0, ngroups, group, i;
2310         int cr = -1;
2311         int err = 0, first_err = 0;
2312         unsigned int nr = 0, prefetch_ios = 0;
2313         struct ext4_sb_info *sbi;
2314         struct super_block *sb;
2315         struct ext4_buddy e4b;
2316
2317         sb = ac->ac_sb;
2318         sbi = EXT4_SB(sb);
2319         ngroups = ext4_get_groups_count(sb);
2320         /* non-extent files are limited to low blocks/groups */
2321         if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2322                 ngroups = sbi->s_blockfile_groups;
2323
2324         BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2325
2326         /* first, try the goal */
2327         err = ext4_mb_find_by_goal(ac, &e4b);
2328         if (err || ac->ac_status == AC_STATUS_FOUND)
2329                 goto out;
2330
2331         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2332                 goto out;
2333
2334         /*
2335          * ac->ac2_order is set only if the fe_len is a power of 2
2336          * if ac2_order is set we also set criteria to 0 so that we
2337          * try exact allocation using buddy.
2338          */
2339         i = fls(ac->ac_g_ex.fe_len);
2340         ac->ac_2order = 0;
2341         /*
2342          * We search using buddy data only if the order of the request
2343          * is greater than equal to the sbi_s_mb_order2_reqs
2344          * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2345          * We also support searching for power-of-two requests only for
2346          * requests upto maximum buddy size we have constructed.
2347          */
2348         if (i >= sbi->s_mb_order2_reqs && i <= sb->s_blocksize_bits + 2) {
2349                 /*
2350                  * This should tell if fe_len is exactly power of 2
2351                  */
2352                 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2353                         ac->ac_2order = array_index_nospec(i - 1,
2354                                                            sb->s_blocksize_bits + 2);
2355         }
2356
2357         /* if stream allocation is enabled, use global goal */
2358         if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2359                 /* TBD: may be hot point */
2360                 spin_lock(&sbi->s_md_lock);
2361                 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2362                 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2363                 spin_unlock(&sbi->s_md_lock);
2364         }
2365
2366         /* Let's just scan groups to find more-less suitable blocks */
2367         cr = ac->ac_2order ? 0 : 1;
2368         /*
2369          * cr == 0 try to get exact allocation,
2370          * cr == 3  try to get anything
2371          */
2372 repeat:
2373         for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2374                 ac->ac_criteria = cr;
2375                 /*
2376                  * searching for the right group start
2377                  * from the goal value specified
2378                  */
2379                 group = ac->ac_g_ex.fe_group;
2380                 prefetch_grp = group;
2381
2382                 for (i = 0; i < ngroups; group++, i++) {
2383                         int ret = 0;
2384                         cond_resched();
2385                         /*
2386                          * Artificially restricted ngroups for non-extent
2387                          * files makes group > ngroups possible on first loop.
2388                          */
2389                         if (group >= ngroups)
2390                                 group = 0;
2391
2392                         /*
2393                          * Batch reads of the block allocation bitmaps
2394                          * to get multiple READs in flight; limit
2395                          * prefetching at cr=0/1, otherwise mballoc can
2396                          * spend a lot of time loading imperfect groups
2397                          */
2398                         if ((prefetch_grp == group) &&
2399                             (cr > 1 ||
2400                              prefetch_ios < sbi->s_mb_prefetch_limit)) {
2401                                 unsigned int curr_ios = prefetch_ios;
2402
2403                                 nr = sbi->s_mb_prefetch;
2404                                 if (ext4_has_feature_flex_bg(sb)) {
2405                                         nr = (group / sbi->s_mb_prefetch) *
2406                                                 sbi->s_mb_prefetch;
2407                                         nr = nr + sbi->s_mb_prefetch - group;
2408                                 }
2409                                 prefetch_grp = ext4_mb_prefetch(sb, group,
2410                                                         nr, &prefetch_ios);
2411                                 if (prefetch_ios == curr_ios)
2412                                         nr = 0;
2413                         }
2414
2415                         /* This now checks without needing the buddy page */
2416                         ret = ext4_mb_good_group_nolock(ac, group, cr);
2417                         if (ret <= 0) {
2418                                 if (!first_err)
2419                                         first_err = ret;
2420                                 continue;
2421                         }
2422
2423                         err = ext4_mb_load_buddy(sb, group, &e4b);
2424                         if (err)
2425                                 goto out;
2426
2427                         ext4_lock_group(sb, group);
2428
2429                         /*
2430                          * We need to check again after locking the
2431                          * block group
2432                          */
2433                         ret = ext4_mb_good_group(ac, group, cr);
2434                         if (ret == 0) {
2435                                 ext4_unlock_group(sb, group);
2436                                 ext4_mb_unload_buddy(&e4b);
2437                                 continue;
2438                         }
2439
2440                         ac->ac_groups_scanned++;
2441                         if (cr == 0)
2442                                 ext4_mb_simple_scan_group(ac, &e4b);
2443                         else if (cr == 1 && sbi->s_stripe &&
2444                                         !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2445                                 ext4_mb_scan_aligned(ac, &e4b);
2446                         else
2447                                 ext4_mb_complex_scan_group(ac, &e4b);
2448
2449                         ext4_unlock_group(sb, group);
2450                         ext4_mb_unload_buddy(&e4b);
2451
2452                         if (ac->ac_status != AC_STATUS_CONTINUE)
2453                                 break;
2454                 }
2455         }
2456
2457         if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2458             !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2459                 /*
2460                  * We've been searching too long. Let's try to allocate
2461                  * the best chunk we've found so far
2462                  */
2463
2464                 ext4_mb_try_best_found(ac, &e4b);
2465                 if (ac->ac_status != AC_STATUS_FOUND) {
2466                         /*
2467                          * Someone more lucky has already allocated it.
2468                          * The only thing we can do is just take first
2469                          * found block(s)
2470                         printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2471                          */
2472                         ac->ac_b_ex.fe_group = 0;
2473                         ac->ac_b_ex.fe_start = 0;
2474                         ac->ac_b_ex.fe_len = 0;
2475                         ac->ac_status = AC_STATUS_CONTINUE;
2476                         ac->ac_flags |= EXT4_MB_HINT_FIRST;
2477                         cr = 3;
2478                         atomic_inc(&sbi->s_mb_lost_chunks);
2479                         goto repeat;
2480                 }
2481         }
2482 out:
2483         if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2484                 err = first_err;
2485
2486         mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
2487                  ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
2488                  ac->ac_flags, cr, err);
2489
2490         if (nr)
2491                 ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
2492
2493         return err;
2494 }
2495
2496 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2497 {
2498         struct super_block *sb = PDE_DATA(file_inode(seq->file));
2499         ext4_group_t group;
2500
2501         if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2502                 return NULL;
2503         group = *pos + 1;
2504         return (void *) ((unsigned long) group);
2505 }
2506
2507 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2508 {
2509         struct super_block *sb = PDE_DATA(file_inode(seq->file));
2510         ext4_group_t group;
2511
2512         ++*pos;
2513         if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2514                 return NULL;
2515         group = *pos + 1;
2516         return (void *) ((unsigned long) group);
2517 }
2518
2519 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2520 {
2521         struct super_block *sb = PDE_DATA(file_inode(seq->file));
2522         ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2523         int i;
2524         int err, buddy_loaded = 0;
2525         struct ext4_buddy e4b;
2526         struct ext4_group_info *grinfo;
2527         unsigned char blocksize_bits = min_t(unsigned char,
2528                                              sb->s_blocksize_bits,
2529                                              EXT4_MAX_BLOCK_LOG_SIZE);
2530         struct sg {
2531                 struct ext4_group_info info;
2532                 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
2533         } sg;
2534
2535         group--;
2536         if (group == 0)
2537                 seq_puts(seq, "#group: free  frags first ["
2538                               " 2^0   2^1   2^2   2^3   2^4   2^5   2^6  "
2539                               " 2^7   2^8   2^9   2^10  2^11  2^12  2^13  ]\n");
2540
2541         i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2542                 sizeof(struct ext4_group_info);
2543
2544         grinfo = ext4_get_group_info(sb, group);
2545         /* Load the group info in memory only if not already loaded. */
2546         if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
2547                 err = ext4_mb_load_buddy(sb, group, &e4b);
2548                 if (err) {
2549                         seq_printf(seq, "#%-5u: I/O error\n", group);
2550                         return 0;
2551                 }
2552                 buddy_loaded = 1;
2553         }
2554
2555         memcpy(&sg, ext4_get_group_info(sb, group), i);
2556
2557         if (buddy_loaded)
2558                 ext4_mb_unload_buddy(&e4b);
2559
2560         seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2561                         sg.info.bb_fragments, sg.info.bb_first_free);
2562         for (i = 0; i <= 13; i++)
2563                 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
2564                                 sg.info.bb_counters[i] : 0);
2565         seq_printf(seq, " ]\n");
2566
2567         return 0;
2568 }
2569
2570 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2571 {
2572 }
2573
2574 const struct seq_operations ext4_mb_seq_groups_ops = {
2575         .start  = ext4_mb_seq_groups_start,
2576         .next   = ext4_mb_seq_groups_next,
2577         .stop   = ext4_mb_seq_groups_stop,
2578         .show   = ext4_mb_seq_groups_show,
2579 };
2580
2581 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2582 {
2583         int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2584         struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2585
2586         BUG_ON(!cachep);
2587         return cachep;
2588 }
2589
2590 /*
2591  * Allocate the top-level s_group_info array for the specified number
2592  * of groups
2593  */
2594 int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
2595 {
2596         struct ext4_sb_info *sbi = EXT4_SB(sb);
2597         unsigned size;
2598         struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
2599
2600         size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
2601                 EXT4_DESC_PER_BLOCK_BITS(sb);
2602         if (size <= sbi->s_group_info_size)
2603                 return 0;
2604
2605         size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
2606         new_groupinfo = kvzalloc(size, GFP_KERNEL);
2607         if (!new_groupinfo) {
2608                 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
2609                 return -ENOMEM;
2610         }
2611         rcu_read_lock();
2612         old_groupinfo = rcu_dereference(sbi->s_group_info);
2613         if (old_groupinfo)
2614                 memcpy(new_groupinfo, old_groupinfo,
2615                        sbi->s_group_info_size * sizeof(*sbi->s_group_info));
2616         rcu_read_unlock();
2617         rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
2618         sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
2619         if (old_groupinfo)
2620                 ext4_kvfree_array_rcu(old_groupinfo);
2621         ext4_debug("allocated s_groupinfo array for %d meta_bg's\n", 
2622                    sbi->s_group_info_size);
2623         return 0;
2624 }
2625
2626 /* Create and initialize ext4_group_info data for the given group. */
2627 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2628                           struct ext4_group_desc *desc)
2629 {
2630         int i;
2631         int metalen = 0;
2632         int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
2633         struct ext4_sb_info *sbi = EXT4_SB(sb);
2634         struct ext4_group_info **meta_group_info;
2635         struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2636
2637         /*
2638          * First check if this group is the first of a reserved block.
2639          * If it's true, we have to allocate a new table of pointers
2640          * to ext4_group_info structures
2641          */
2642         if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2643                 metalen = sizeof(*meta_group_info) <<
2644                         EXT4_DESC_PER_BLOCK_BITS(sb);
2645                 meta_group_info = kmalloc(metalen, GFP_NOFS);
2646                 if (meta_group_info == NULL) {
2647                         ext4_msg(sb, KERN_ERR, "can't allocate mem "
2648                                  "for a buddy group");
2649                         goto exit_meta_group_info;
2650                 }
2651                 rcu_read_lock();
2652                 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
2653                 rcu_read_unlock();
2654         }
2655
2656         meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
2657         i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2658
2659         meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
2660         if (meta_group_info[i] == NULL) {
2661                 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
2662                 goto exit_group_info;
2663         }
2664         set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2665                 &(meta_group_info[i]->bb_state));
2666
2667         /*
2668          * initialize bb_free to be able to skip
2669          * empty groups without initialization
2670          */
2671         if (ext4_has_group_desc_csum(sb) &&
2672             (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
2673                 meta_group_info[i]->bb_free =
2674                         ext4_free_clusters_after_init(sb, group, desc);
2675         } else {
2676                 meta_group_info[i]->bb_free =
2677                         ext4_free_group_clusters(sb, desc);
2678         }
2679
2680         INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2681         init_rwsem(&meta_group_info[i]->alloc_sem);
2682         meta_group_info[i]->bb_free_root = RB_ROOT;
2683         meta_group_info[i]->bb_largest_free_order = -1;  /* uninit */
2684
2685         mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
2686         return 0;
2687
2688 exit_group_info:
2689         /* If a meta_group_info table has been allocated, release it now */
2690         if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2691                 struct ext4_group_info ***group_info;
2692
2693                 rcu_read_lock();
2694                 group_info = rcu_dereference(sbi->s_group_info);
2695                 kfree(group_info[idx]);
2696                 group_info[idx] = NULL;
2697                 rcu_read_unlock();
2698         }
2699 exit_meta_group_info:
2700         return -ENOMEM;
2701 } /* ext4_mb_add_groupinfo */
2702
2703 static int ext4_mb_init_backend(struct super_block *sb)
2704 {
2705         ext4_group_t ngroups = ext4_get_groups_count(sb);
2706         ext4_group_t i;
2707         struct ext4_sb_info *sbi = EXT4_SB(sb);
2708         int err;
2709         struct ext4_group_desc *desc;
2710         struct ext4_group_info ***group_info;
2711         struct kmem_cache *cachep;
2712
2713         err = ext4_mb_alloc_groupinfo(sb, ngroups);
2714         if (err)
2715                 return err;
2716
2717         sbi->s_buddy_cache = new_inode(sb);
2718         if (sbi->s_buddy_cache == NULL) {
2719                 ext4_msg(sb, KERN_ERR, "can't get new inode");
2720                 goto err_freesgi;
2721         }
2722         /* To avoid potentially colliding with an valid on-disk inode number,
2723          * use EXT4_BAD_INO for the buddy cache inode number.  This inode is
2724          * not in the inode hash, so it should never be found by iget(), but
2725          * this will avoid confusion if it ever shows up during debugging. */
2726         sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
2727         EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2728         for (i = 0; i < ngroups; i++) {
2729                 cond_resched();
2730                 desc = ext4_get_group_desc(sb, i, NULL);
2731                 if (desc == NULL) {
2732                         ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2733                         goto err_freebuddy;
2734                 }
2735                 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2736                         goto err_freebuddy;
2737         }
2738
2739         if (ext4_has_feature_flex_bg(sb)) {
2740                 /* a single flex group is supposed to be read by a single IO */
2741                 sbi->s_mb_prefetch = 1 << sbi->s_es->s_log_groups_per_flex;
2742                 sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
2743         } else {
2744                 sbi->s_mb_prefetch = 32;
2745         }
2746         if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
2747                 sbi->s_mb_prefetch = ext4_get_groups_count(sb);
2748         /* now many real IOs to prefetch within a single allocation at cr=0
2749          * given cr=0 is an CPU-related optimization we shouldn't try to
2750          * load too many groups, at some point we should start to use what
2751          * we've got in memory.
2752          * with an average random access time 5ms, it'd take a second to get
2753          * 200 groups (* N with flex_bg), so let's make this limit 4
2754          */
2755         sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
2756         if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
2757                 sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
2758
2759         return 0;
2760
2761 err_freebuddy:
2762         cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2763         while (i-- > 0)
2764                 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2765         i = sbi->s_group_info_size;
2766         rcu_read_lock();
2767         group_info = rcu_dereference(sbi->s_group_info);
2768         while (i-- > 0)
2769                 kfree(group_info[i]);
2770         rcu_read_unlock();
2771         iput(sbi->s_buddy_cache);
2772 err_freesgi:
2773         rcu_read_lock();
2774         kvfree(rcu_dereference(sbi->s_group_info));
2775         rcu_read_unlock();
2776         return -ENOMEM;
2777 }
2778
2779 static void ext4_groupinfo_destroy_slabs(void)
2780 {
2781         int i;
2782
2783         for (i = 0; i < NR_GRPINFO_CACHES; i++) {
2784                 kmem_cache_destroy(ext4_groupinfo_caches[i]);
2785                 ext4_groupinfo_caches[i] = NULL;
2786         }
2787 }
2788
2789 static int ext4_groupinfo_create_slab(size_t size)
2790 {
2791         static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
2792         int slab_size;
2793         int blocksize_bits = order_base_2(size);
2794         int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2795         struct kmem_cache *cachep;
2796
2797         if (cache_index >= NR_GRPINFO_CACHES)
2798                 return -EINVAL;
2799
2800         if (unlikely(cache_index < 0))
2801                 cache_index = 0;
2802
2803         mutex_lock(&ext4_grpinfo_slab_create_mutex);
2804         if (ext4_groupinfo_caches[cache_index]) {
2805                 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2806                 return 0;       /* Already created */
2807         }
2808
2809         slab_size = offsetof(struct ext4_group_info,
2810                                 bb_counters[blocksize_bits + 2]);
2811
2812         cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
2813                                         slab_size, 0, SLAB_RECLAIM_ACCOUNT,
2814                                         NULL);
2815
2816         ext4_groupinfo_caches[cache_index] = cachep;
2817
2818         mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2819         if (!cachep) {
2820                 printk(KERN_EMERG
2821                        "EXT4-fs: no memory for groupinfo slab cache\n");
2822                 return -ENOMEM;
2823         }
2824
2825         return 0;
2826 }
2827
2828 int ext4_mb_init(struct super_block *sb)
2829 {
2830         struct ext4_sb_info *sbi = EXT4_SB(sb);
2831         unsigned i, j;
2832         unsigned offset, offset_incr;
2833         unsigned max;
2834         int ret;
2835
2836         i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2837
2838         sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2839         if (sbi->s_mb_offsets == NULL) {
2840                 ret = -ENOMEM;
2841                 goto out;
2842         }
2843
2844         i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2845         sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2846         if (sbi->s_mb_maxs == NULL) {
2847                 ret = -ENOMEM;
2848                 goto out;
2849         }
2850
2851         ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2852         if (ret < 0)
2853                 goto out;
2854
2855         /* order 0 is regular bitmap */
2856         sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2857         sbi->s_mb_offsets[0] = 0;
2858
2859         i = 1;
2860         offset = 0;
2861         offset_incr = 1 << (sb->s_blocksize_bits - 1);
2862         max = sb->s_blocksize << 2;
2863         do {
2864                 sbi->s_mb_offsets[i] = offset;
2865                 sbi->s_mb_maxs[i] = max;
2866                 offset += offset_incr;
2867                 offset_incr = offset_incr >> 1;
2868                 max = max >> 1;
2869                 i++;
2870         } while (i <= sb->s_blocksize_bits + 1);
2871
2872         spin_lock_init(&sbi->s_md_lock);
2873         spin_lock_init(&sbi->s_bal_lock);
2874         sbi->s_mb_free_pending = 0;
2875         INIT_LIST_HEAD(&sbi->s_freed_data_list);
2876
2877         sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2878         sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2879         sbi->s_mb_stats = MB_DEFAULT_STATS;
2880         sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2881         sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2882         /*
2883          * The default group preallocation is 512, which for 4k block
2884          * sizes translates to 2 megabytes.  However for bigalloc file
2885          * systems, this is probably too big (i.e, if the cluster size
2886          * is 1 megabyte, then group preallocation size becomes half a
2887          * gigabyte!).  As a default, we will keep a two megabyte
2888          * group pralloc size for cluster sizes up to 64k, and after
2889          * that, we will force a minimum group preallocation size of
2890          * 32 clusters.  This translates to 8 megs when the cluster
2891          * size is 256k, and 32 megs when the cluster size is 1 meg,
2892          * which seems reasonable as a default.
2893          */
2894         sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
2895                                        sbi->s_cluster_bits, 32);
2896         /*
2897          * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
2898          * to the lowest multiple of s_stripe which is bigger than
2899          * the s_mb_group_prealloc as determined above. We want
2900          * the preallocation size to be an exact multiple of the
2901          * RAID stripe size so that preallocations don't fragment
2902          * the stripes.
2903          */
2904         if (sbi->s_stripe > 1) {
2905                 sbi->s_mb_group_prealloc = roundup(
2906                         sbi->s_mb_group_prealloc, sbi->s_stripe);
2907         }
2908
2909         sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2910         if (sbi->s_locality_groups == NULL) {
2911                 ret = -ENOMEM;
2912                 goto out;
2913         }
2914         for_each_possible_cpu(i) {
2915                 struct ext4_locality_group *lg;
2916                 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2917                 mutex_init(&lg->lg_mutex);
2918                 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2919                         INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2920                 spin_lock_init(&lg->lg_prealloc_lock);
2921         }
2922
2923         /* init file for buddy data */
2924         ret = ext4_mb_init_backend(sb);
2925         if (ret != 0)
2926                 goto out_free_locality_groups;
2927
2928         return 0;
2929
2930 out_free_locality_groups:
2931         free_percpu(sbi->s_locality_groups);
2932         sbi->s_locality_groups = NULL;
2933 out:
2934         kfree(sbi->s_mb_offsets);
2935         sbi->s_mb_offsets = NULL;
2936         kfree(sbi->s_mb_maxs);
2937         sbi->s_mb_maxs = NULL;
2938         return ret;
2939 }
2940
2941 /* need to called with the ext4 group lock held */
2942 static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2943 {
2944         struct ext4_prealloc_space *pa;
2945         struct list_head *cur, *tmp;
2946         int count = 0;
2947
2948         list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2949                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2950                 list_del(&pa->pa_group_list);
2951                 count++;
2952                 kmem_cache_free(ext4_pspace_cachep, pa);
2953         }
2954         return count;
2955 }
2956
2957 int ext4_mb_release(struct super_block *sb)
2958 {
2959         ext4_group_t ngroups = ext4_get_groups_count(sb);
2960         ext4_group_t i;
2961         int num_meta_group_infos;
2962         struct ext4_group_info *grinfo, ***group_info;
2963         struct ext4_sb_info *sbi = EXT4_SB(sb);
2964         struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2965         int count;
2966
2967         if (sbi->s_group_info) {
2968                 for (i = 0; i < ngroups; i++) {
2969                         cond_resched();
2970                         grinfo = ext4_get_group_info(sb, i);
2971                         mb_group_bb_bitmap_free(grinfo);
2972                         ext4_lock_group(sb, i);
2973                         count = ext4_mb_cleanup_pa(grinfo);
2974                         if (count)
2975                                 mb_debug(sb, "mballoc: %d PAs left\n",
2976                                          count);
2977                         ext4_unlock_group(sb, i);
2978                         kmem_cache_free(cachep, grinfo);
2979                 }
2980                 num_meta_group_infos = (ngroups +
2981                                 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2982                         EXT4_DESC_PER_BLOCK_BITS(sb);
2983                 rcu_read_lock();
2984                 group_info = rcu_dereference(sbi->s_group_info);
2985                 for (i = 0; i < num_meta_group_infos; i++)
2986                         kfree(group_info[i]);
2987                 kvfree(group_info);
2988                 rcu_read_unlock();
2989         }
2990         kfree(sbi->s_mb_offsets);
2991         kfree(sbi->s_mb_maxs);
2992         iput(sbi->s_buddy_cache);
2993         if (sbi->s_mb_stats) {
2994                 ext4_msg(sb, KERN_INFO,
2995                        "mballoc: %u blocks %u reqs (%u success)",
2996                                 atomic_read(&sbi->s_bal_allocated),
2997                                 atomic_read(&sbi->s_bal_reqs),
2998                                 atomic_read(&sbi->s_bal_success));
2999                 ext4_msg(sb, KERN_INFO,
3000                       "mballoc: %u extents scanned, %u goal hits, "
3001                                 "%u 2^N hits, %u breaks, %u lost",
3002                                 atomic_read(&sbi->s_bal_ex_scanned),
3003                                 atomic_read(&sbi->s_bal_goals),
3004                                 atomic_read(&sbi->s_bal_2orders),
3005                                 atomic_read(&sbi->s_bal_breaks),
3006                                 atomic_read(&sbi->s_mb_lost_chunks));
3007                 ext4_msg(sb, KERN_INFO,
3008                        "mballoc: %lu generated and it took %Lu",
3009                                 sbi->s_mb_buddies_generated,
3010                                 sbi->s_mb_generation_time);
3011                 ext4_msg(sb, KERN_INFO,
3012                        "mballoc: %u preallocated, %u discarded",
3013                                 atomic_read(&sbi->s_mb_preallocated),
3014                                 atomic_read(&sbi->s_mb_discarded));
3015         }
3016
3017         free_percpu(sbi->s_locality_groups);
3018
3019         return 0;
3020 }
3021
3022 static inline int ext4_issue_discard(struct super_block *sb,
3023                 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
3024                 struct bio **biop)
3025 {
3026         ext4_fsblk_t discard_block;
3027
3028         discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
3029                          ext4_group_first_block_no(sb, block_group));
3030         count = EXT4_C2B(EXT4_SB(sb), count);
3031         trace_ext4_discard_blocks(sb,
3032                         (unsigned long long) discard_block, count);
3033         if (biop) {
3034                 return __blkdev_issue_discard(sb->s_bdev,
3035                         (sector_t)discard_block << (sb->s_blocksize_bits - 9),
3036                         (sector_t)count << (sb->s_blocksize_bits - 9),
3037                         GFP_NOFS, 0, biop);
3038         } else
3039                 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
3040 }
3041
3042 static void ext4_free_data_in_buddy(struct super_block *sb,
3043                                     struct ext4_free_data *entry)
3044 {
3045         struct ext4_buddy e4b;
3046         struct ext4_group_info *db;
3047         int err, count = 0, count2 = 0;
3048
3049         mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
3050                  entry->efd_count, entry->efd_group, entry);
3051
3052         err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
3053         /* we expect to find existing buddy because it's pinned */
3054         BUG_ON(err != 0);
3055
3056         spin_lock(&EXT4_SB(sb)->s_md_lock);
3057         EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
3058         spin_unlock(&EXT4_SB(sb)->s_md_lock);
3059
3060         db = e4b.bd_info;
3061         /* there are blocks to put in buddy to make them really free */
3062         count += entry->efd_count;
3063         count2++;
3064         ext4_lock_group(sb, entry->efd_group);
3065         /* Take it out of per group rb tree */
3066         rb_erase(&entry->efd_node, &(db->bb_free_root));
3067         mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
3068
3069         /*
3070          * Clear the trimmed flag for the group so that the next
3071          * ext4_trim_fs can trim it.
3072          * If the volume is mounted with -o discard, online discard
3073          * is supported and the free blocks will be trimmed online.
3074          */
3075         if (!test_opt(sb, DISCARD))
3076                 EXT4_MB_GRP_CLEAR_TRIMMED(db);
3077
3078         if (!db->bb_free_root.rb_node) {
3079                 /* No more items in the per group rb tree
3080                  * balance refcounts from ext4_mb_free_metadata()
3081                  */
3082                 put_page(e4b.bd_buddy_page);
3083                 put_page(e4b.bd_bitmap_page);
3084         }
3085         ext4_unlock_group(sb, entry->efd_group);
3086         kmem_cache_free(ext4_free_data_cachep, entry);
3087         ext4_mb_unload_buddy(&e4b);
3088
3089         mb_debug(sb, "freed %d blocks in %d structures\n", count,
3090                  count2);
3091 }
3092
3093 /*
3094  * This function is called by the jbd2 layer once the commit has finished,
3095  * so we know we can free the blocks that were released with that commit.
3096  */
3097 void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
3098 {
3099         struct ext4_sb_info *sbi = EXT4_SB(sb);
3100         struct ext4_free_data *entry, *tmp;
3101         struct bio *discard_bio = NULL;
3102         struct list_head freed_data_list;
3103         struct list_head *cut_pos = NULL;
3104         int err;
3105
3106         INIT_LIST_HEAD(&freed_data_list);
3107
3108         spin_lock(&sbi->s_md_lock);
3109         list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
3110                 if (entry->efd_tid != commit_tid)
3111                         break;
3112                 cut_pos = &entry->efd_list;
3113         }
3114         if (cut_pos)
3115                 list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
3116                                   cut_pos);
3117         spin_unlock(&sbi->s_md_lock);
3118
3119         if (test_opt(sb, DISCARD)) {
3120                 list_for_each_entry(entry, &freed_data_list, efd_list) {
3121                         err = ext4_issue_discard(sb, entry->efd_group,
3122                                                  entry->efd_start_cluster,
3123                                                  entry->efd_count,
3124                                                  &discard_bio);
3125                         if (err && err != -EOPNOTSUPP) {
3126                                 ext4_msg(sb, KERN_WARNING, "discard request in"
3127                                          " group:%d block:%d count:%d failed"
3128                                          " with %d", entry->efd_group,
3129                                          entry->efd_start_cluster,
3130                                          entry->efd_count, err);
3131                         } else if (err == -EOPNOTSUPP)
3132                                 break;
3133                 }
3134
3135                 if (discard_bio) {
3136                         submit_bio_wait(discard_bio);
3137                         bio_put(discard_bio);
3138                 }
3139         }
3140
3141         list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
3142                 ext4_free_data_in_buddy(sb, entry);
3143 }
3144
3145 int __init ext4_init_mballoc(void)
3146 {
3147         ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
3148                                         SLAB_RECLAIM_ACCOUNT);
3149         if (ext4_pspace_cachep == NULL)
3150                 goto out;
3151
3152         ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
3153                                     SLAB_RECLAIM_ACCOUNT);
3154         if (ext4_ac_cachep == NULL)
3155                 goto out_pa_free;
3156
3157         ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
3158                                            SLAB_RECLAIM_ACCOUNT);
3159         if (ext4_free_data_cachep == NULL)
3160                 goto out_ac_free;
3161
3162         return 0;
3163
3164 out_ac_free:
3165         kmem_cache_destroy(ext4_ac_cachep);
3166 out_pa_free:
3167         kmem_cache_destroy(ext4_pspace_cachep);
3168 out:
3169         return -ENOMEM;
3170 }
3171
3172 void ext4_exit_mballoc(void)
3173 {
3174         /*
3175          * Wait for completion of call_rcu()'s on ext4_pspace_cachep
3176          * before destroying the slab cache.
3177          */
3178         rcu_barrier();
3179         kmem_cache_destroy(ext4_pspace_cachep);
3180         kmem_cache_destroy(ext4_ac_cachep);
3181         kmem_cache_destroy(ext4_free_data_cachep);
3182         ext4_groupinfo_destroy_slabs();
3183 }
3184
3185
3186 /*
3187  * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
3188  * Returns 0 if success or error code
3189  */
3190 static noinline_for_stack int
3191 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
3192                                 handle_t *handle, unsigned int reserv_clstrs)
3193 {
3194         struct buffer_head *bitmap_bh = NULL;
3195         struct ext4_group_desc *gdp;
3196         struct buffer_head *gdp_bh;
3197         struct ext4_sb_info *sbi;
3198         struct super_block *sb;
3199         ext4_fsblk_t block;
3200         int err, len;
3201
3202         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3203         BUG_ON(ac->ac_b_ex.fe_len <= 0);
3204
3205         sb = ac->ac_sb;
3206         sbi = EXT4_SB(sb);
3207
3208         bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
3209         if (IS_ERR(bitmap_bh)) {
3210                 err = PTR_ERR(bitmap_bh);
3211                 bitmap_bh = NULL;
3212                 goto out_err;
3213         }
3214
3215         BUFFER_TRACE(bitmap_bh, "getting write access");
3216         err = ext4_journal_get_write_access(handle, bitmap_bh);
3217         if (err)
3218                 goto out_err;
3219
3220         err = -EIO;
3221         gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3222         if (!gdp)
3223                 goto out_err;
3224
3225         ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
3226                         ext4_free_group_clusters(sb, gdp));
3227
3228         BUFFER_TRACE(gdp_bh, "get_write_access");
3229         err = ext4_journal_get_write_access(handle, gdp_bh);
3230         if (err)
3231                 goto out_err;
3232
3233         block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3234
3235         len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3236         if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
3237                 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
3238                            "fs metadata", block, block+len);
3239                 /* File system mounted not to panic on error
3240                  * Fix the bitmap and return EFSCORRUPTED
3241                  * We leak some of the blocks here.
3242                  */
3243                 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3244                 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3245                               ac->ac_b_ex.fe_len);
3246                 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3247                 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3248                 if (!err)
3249                         err = -EFSCORRUPTED;
3250                 goto out_err;
3251         }
3252
3253         ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3254 #ifdef AGGRESSIVE_CHECK
3255         {
3256                 int i;
3257                 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3258                         BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3259                                                 bitmap_bh->b_data));
3260                 }
3261         }
3262 #endif
3263         ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3264                       ac->ac_b_ex.fe_len);
3265         if (ext4_has_group_desc_csum(sb) &&
3266             (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3267                 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3268                 ext4_free_group_clusters_set(sb, gdp,
3269                                              ext4_free_clusters_after_init(sb,
3270                                                 ac->ac_b_ex.fe_group, gdp));
3271         }
3272         len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
3273         ext4_free_group_clusters_set(sb, gdp, len);
3274         ext4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);
3275         ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
3276
3277         ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3278         percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
3279         /*
3280          * Now reduce the dirty block count also. Should not go negative
3281          */
3282         if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3283                 /* release all the reserved blocks if non delalloc */
3284                 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
3285                                    reserv_clstrs);
3286
3287         if (sbi->s_log_groups_per_flex) {
3288                 ext4_group_t flex_group = ext4_flex_group(sbi,
3289                                                           ac->ac_b_ex.fe_group);
3290                 atomic64_sub(ac->ac_b_ex.fe_len,
3291                              &sbi_array_rcu_deref(sbi, s_flex_groups,
3292                                                   flex_group)->free_clusters);
3293         }
3294
3295         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3296         if (err)
3297                 goto out_err;
3298         err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3299
3300 out_err:
3301         brelse(bitmap_bh);
3302         return err;
3303 }
3304
3305 /*
3306  * here we normalize request for locality group
3307  * Group request are normalized to s_mb_group_prealloc, which goes to
3308  * s_strip if we set the same via mount option.
3309  * s_mb_group_prealloc can be configured via
3310  * /sys/fs/ext4/<partition>/mb_group_prealloc
3311  *
3312  * XXX: should we try to preallocate more than the group has now?
3313  */
3314 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3315 {
3316         struct super_block *sb = ac->ac_sb;
3317         struct ext4_locality_group *lg = ac->ac_lg;
3318
3319         BUG_ON(lg == NULL);
3320         ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3321         mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
3322 }
3323
3324 /*
3325  * Normalization means making request better in terms of
3326  * size and alignment
3327  */
3328 static noinline_for_stack void
3329 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3330                                 struct ext4_allocation_request *ar)
3331 {
3332         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3333         int bsbits, max;
3334         ext4_lblk_t end;
3335         loff_t size, start_off;
3336         loff_t orig_size __maybe_unused;
3337         ext4_lblk_t start;
3338         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3339         struct ext4_prealloc_space *pa;
3340
3341         /* do normalize only data requests, metadata requests
3342            do not need preallocation */
3343         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3344                 return;
3345
3346         /* sometime caller may want exact blocks */
3347         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3348                 return;
3349
3350         /* caller may indicate that preallocation isn't
3351          * required (it's a tail, for example) */
3352         if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3353                 return;
3354
3355         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3356                 ext4_mb_normalize_group_request(ac);
3357                 return ;
3358         }
3359
3360         bsbits = ac->ac_sb->s_blocksize_bits;
3361
3362         /* first, let's learn actual file size
3363          * given current request is allocated */
3364         size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
3365         size = size << bsbits;
3366         if (size < i_size_read(ac->ac_inode))
3367                 size = i_size_read(ac->ac_inode);
3368         orig_size = size;
3369
3370         /* max size of free chunks */
3371         max = 2 << bsbits;
3372
3373 #define NRL_CHECK_SIZE(req, size, max, chunk_size)      \
3374                 (req <= (size) || max <= (chunk_size))
3375
3376         /* first, try to predict filesize */
3377         /* XXX: should this table be tunable? */
3378         start_off = 0;
3379         if (size <= 16 * 1024) {
3380                 size = 16 * 1024;
3381         } else if (size <= 32 * 1024) {
3382                 size = 32 * 1024;
3383         } else if (size <= 64 * 1024) {
3384                 size = 64 * 1024;
3385         } else if (size <= 128 * 1024) {
3386                 size = 128 * 1024;
3387         } else if (size <= 256 * 1024) {
3388                 size = 256 * 1024;
3389         } else if (size <= 512 * 1024) {
3390                 size = 512 * 1024;
3391         } else if (size <= 1024 * 1024) {
3392                 size = 1024 * 1024;
3393         } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3394                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3395                                                 (21 - bsbits)) << 21;
3396                 size = 2 * 1024 * 1024;
3397         } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3398                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3399                                                         (22 - bsbits)) << 22;
3400                 size = 4 * 1024 * 1024;
3401         } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3402                                         (8<<20)>>bsbits, max, 8 * 1024)) {
3403                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3404                                                         (23 - bsbits)) << 23;
3405                 size = 8 * 1024 * 1024;
3406         } else {
3407                 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
3408                 size      = (loff_t) EXT4_C2B(EXT4_SB(ac->ac_sb),
3409                                               ac->ac_o_ex.fe_len) << bsbits;
3410         }
3411         size = size >> bsbits;
3412         start = start_off >> bsbits;
3413
3414         /* don't cover already allocated blocks in selected range */
3415         if (ar->pleft && start <= ar->lleft) {
3416                 size -= ar->lleft + 1 - start;
3417                 start = ar->lleft + 1;
3418         }
3419         if (ar->pright && start + size - 1 >= ar->lright)
3420                 size -= start + size - ar->lright;
3421
3422         /*
3423          * Trim allocation request for filesystems with artificially small
3424          * groups.
3425          */
3426         if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
3427                 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
3428
3429         end = start + size;
3430
3431         /* check we don't cross already preallocated blocks */
3432         rcu_read_lock();
3433         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3434                 ext4_lblk_t pa_end;
3435
3436                 if (pa->pa_deleted)
3437                         continue;
3438                 spin_lock(&pa->pa_lock);
3439                 if (pa->pa_deleted) {
3440                         spin_unlock(&pa->pa_lock);
3441                         continue;
3442                 }
3443
3444                 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3445                                                   pa->pa_len);
3446
3447                 /* PA must not overlap original request */
3448                 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3449                         ac->ac_o_ex.fe_logical < pa->pa_lstart));
3450
3451                 /* skip PAs this normalized request doesn't overlap with */
3452                 if (pa->pa_lstart >= end || pa_end <= start) {
3453                         spin_unlock(&pa->pa_lock);
3454                         continue;
3455                 }
3456                 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3457
3458                 /* adjust start or end to be adjacent to this pa */
3459                 if (pa_end <= ac->ac_o_ex.fe_logical) {
3460                         BUG_ON(pa_end < start);
3461                         start = pa_end;
3462                 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3463                         BUG_ON(pa->pa_lstart > end);
3464                         end = pa->pa_lstart;
3465                 }
3466                 spin_unlock(&pa->pa_lock);
3467         }
3468         rcu_read_unlock();
3469         size = end - start;
3470
3471         /* XXX: extra loop to check we really don't overlap preallocations */
3472         rcu_read_lock();
3473         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3474                 ext4_lblk_t pa_end;
3475
3476                 spin_lock(&pa->pa_lock);
3477                 if (pa->pa_deleted == 0) {
3478                         pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3479                                                           pa->pa_len);
3480                         BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3481                 }
3482                 spin_unlock(&pa->pa_lock);
3483         }
3484         rcu_read_unlock();
3485
3486         if (start + size <= ac->ac_o_ex.fe_logical &&
3487                         start > ac->ac_o_ex.fe_logical) {
3488                 ext4_msg(ac->ac_sb, KERN_ERR,
3489                          "start %lu, size %lu, fe_logical %lu",
3490                          (unsigned long) start, (unsigned long) size,
3491                          (unsigned long) ac->ac_o_ex.fe_logical);
3492                 BUG();
3493         }
3494         BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3495
3496         /* now prepare goal request */
3497
3498         /* XXX: is it better to align blocks WRT to logical
3499          * placement or satisfy big request as is */
3500         ac->ac_g_ex.fe_logical = start;
3501         ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3502
3503         /* define goal start in order to merge */
3504         if (ar->pright && (ar->lright == (start + size))) {
3505                 /* merge to the right */
3506                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3507                                                 &ac->ac_f_ex.fe_group,
3508                                                 &ac->ac_f_ex.fe_start);
3509                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3510         }
3511         if (ar->pleft && (ar->lleft + 1 == start)) {
3512                 /* merge to the left */
3513                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3514                                                 &ac->ac_f_ex.fe_group,
3515                                                 &ac->ac_f_ex.fe_start);
3516                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3517         }
3518
3519         mb_debug(ac->ac_sb, "goal: %lld(was %lld) blocks at %u\n", size,
3520                  orig_size, start);
3521 }
3522
3523 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3524 {
3525         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3526
3527         if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3528                 atomic_inc(&sbi->s_bal_reqs);
3529                 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3530                 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3531                         atomic_inc(&sbi->s_bal_success);
3532                 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3533                 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3534                                 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3535                         atomic_inc(&sbi->s_bal_goals);
3536                 if (ac->ac_found > sbi->s_mb_max_to_scan)
3537                         atomic_inc(&sbi->s_bal_breaks);
3538         }
3539
3540         if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3541                 trace_ext4_mballoc_alloc(ac);
3542         else
3543                 trace_ext4_mballoc_prealloc(ac);
3544 }
3545
3546 /*
3547  * Called on failure; free up any blocks from the inode PA for this
3548  * context.  We don't need this for MB_GROUP_PA because we only change
3549  * pa_free in ext4_mb_release_context(), but on failure, we've already
3550  * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3551  */
3552 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3553 {
3554         struct ext4_prealloc_space *pa = ac->ac_pa;
3555         struct ext4_buddy e4b;
3556         int err;
3557
3558         if (pa == NULL) {
3559                 if (ac->ac_f_ex.fe_len == 0)
3560                         return;
3561                 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
3562                 if (err) {
3563                         /*
3564                          * This should never happen since we pin the
3565                          * pages in the ext4_allocation_context so
3566                          * ext4_mb_load_buddy() should never fail.
3567                          */
3568                         WARN(1, "mb_load_buddy failed (%d)", err);
3569                         return;
3570                 }
3571                 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3572                 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
3573                                ac->ac_f_ex.fe_len);
3574                 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3575                 ext4_mb_unload_buddy(&e4b);
3576                 return;
3577         }
3578         if (pa->pa_type == MB_INODE_PA)
3579                 pa->pa_free += ac->ac_b_ex.fe_len;
3580 }
3581
3582 /*
3583  * use blocks preallocated to inode
3584  */
3585 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3586                                 struct ext4_prealloc_space *pa)
3587 {
3588         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3589         ext4_fsblk_t start;
3590         ext4_fsblk_t end;
3591         int len;
3592
3593         /* found preallocated blocks, use them */
3594         start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3595         end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
3596                   start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
3597         len = EXT4_NUM_B2C(sbi, end - start);
3598         ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3599                                         &ac->ac_b_ex.fe_start);
3600         ac->ac_b_ex.fe_len = len;
3601         ac->ac_status = AC_STATUS_FOUND;
3602         ac->ac_pa = pa;
3603
3604         BUG_ON(start < pa->pa_pstart);
3605         BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3606         BUG_ON(pa->pa_free < len);
3607         pa->pa_free -= len;
3608
3609         mb_debug(ac->ac_sb, "use %llu/%d from inode pa %p\n", start, len, pa);
3610 }
3611
3612 /*
3613  * use blocks preallocated to locality group
3614  */
3615 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3616                                 struct ext4_prealloc_space *pa)
3617 {
3618         unsigned int len = ac->ac_o_ex.fe_len;
3619
3620         ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3621                                         &ac->ac_b_ex.fe_group,
3622                                         &ac->ac_b_ex.fe_start);
3623         ac->ac_b_ex.fe_len = len;
3624         ac->ac_status = AC_STATUS_FOUND;
3625         ac->ac_pa = pa;
3626
3627         /* we don't correct pa_pstart or pa_plen here to avoid
3628          * possible race when the group is being loaded concurrently
3629          * instead we correct pa later, after blocks are marked
3630          * in on-disk bitmap -- see ext4_mb_release_context()
3631          * Other CPUs are prevented from allocating from this pa by lg_mutex
3632          */
3633         mb_debug(ac->ac_sb, "use %u/%u from group pa %p\n",
3634                  pa->pa_lstart-len, len, pa);
3635 }
3636
3637 /*
3638  * Return the prealloc space that have minimal distance
3639  * from the goal block. @cpa is the prealloc
3640  * space that is having currently known minimal distance
3641  * from the goal block.
3642  */
3643 static struct ext4_prealloc_space *
3644 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3645                         struct ext4_prealloc_space *pa,
3646                         struct ext4_prealloc_space *cpa)
3647 {
3648         ext4_fsblk_t cur_distance, new_distance;
3649
3650         if (cpa == NULL) {
3651                 atomic_inc(&pa->pa_count);
3652                 return pa;
3653         }
3654         cur_distance = abs(goal_block - cpa->pa_pstart);
3655         new_distance = abs(goal_block - pa->pa_pstart);
3656
3657         if (cur_distance <= new_distance)
3658                 return cpa;
3659
3660         /* drop the previous reference */
3661         atomic_dec(&cpa->pa_count);
3662         atomic_inc(&pa->pa_count);
3663         return pa;
3664 }
3665
3666 /*
3667  * search goal blocks in preallocated space
3668  */
3669 static noinline_for_stack bool
3670 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3671 {
3672         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3673         int order, i;
3674         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3675         struct ext4_locality_group *lg;
3676         struct ext4_prealloc_space *pa, *cpa = NULL;
3677         ext4_fsblk_t goal_block;
3678
3679         /* only data can be preallocated */
3680         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3681                 return false;
3682
3683         /* first, try per-file preallocation */
3684         rcu_read_lock();
3685         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3686
3687                 /* all fields in this condition don't change,
3688                  * so we can skip locking for them */
3689                 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3690                     ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
3691                                                EXT4_C2B(sbi, pa->pa_len)))
3692                         continue;
3693
3694                 /* non-extent files can't have physical blocks past 2^32 */
3695                 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3696                     (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
3697                      EXT4_MAX_BLOCK_FILE_PHYS))
3698                         continue;
3699
3700                 /* found preallocated blocks, use them */
3701                 spin_lock(&pa->pa_lock);
3702                 if (pa->pa_deleted == 0 && pa->pa_free) {
3703                         atomic_inc(&pa->pa_count);
3704                         ext4_mb_use_inode_pa(ac, pa);
3705                         spin_unlock(&pa->pa_lock);
3706                         ac->ac_criteria = 10;
3707                         rcu_read_unlock();
3708                         return true;
3709                 }
3710                 spin_unlock(&pa->pa_lock);
3711         }
3712         rcu_read_unlock();
3713
3714         /* can we use group allocation? */
3715         if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3716                 return false;
3717
3718         /* inode may have no locality group for some reason */
3719         lg = ac->ac_lg;
3720         if (lg == NULL)
3721                 return false;
3722         order  = fls(ac->ac_o_ex.fe_len) - 1;
3723         if (order > PREALLOC_TB_SIZE - 1)
3724                 /* The max size of hash table is PREALLOC_TB_SIZE */
3725                 order = PREALLOC_TB_SIZE - 1;
3726
3727         goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3728         /*
3729          * search for the prealloc space that is having
3730          * minimal distance from the goal block.
3731          */
3732         for (i = order; i < PREALLOC_TB_SIZE; i++) {
3733                 rcu_read_lock();
3734                 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3735                                         pa_inode_list) {
3736                         spin_lock(&pa->pa_lock);
3737                         if (pa->pa_deleted == 0 &&
3738                                         pa->pa_free >= ac->ac_o_ex.fe_len) {
3739
3740                                 cpa = ext4_mb_check_group_pa(goal_block,
3741                                                                 pa, cpa);
3742                         }
3743                         spin_unlock(&pa->pa_lock);
3744                 }
3745                 rcu_read_unlock();
3746         }
3747         if (cpa) {
3748                 ext4_mb_use_group_pa(ac, cpa);
3749                 ac->ac_criteria = 20;
3750                 return true;
3751         }
3752         return false;
3753 }
3754
3755 /*
3756  * the function goes through all block freed in the group
3757  * but not yet committed and marks them used in in-core bitmap.
3758  * buddy must be generated from this bitmap
3759  * Need to be called with the ext4 group lock held
3760  */
3761 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3762                                                 ext4_group_t group)
3763 {
3764         struct rb_node *n;
3765         struct ext4_group_info *grp;
3766         struct ext4_free_data *entry;
3767
3768         grp = ext4_get_group_info(sb, group);
3769         n = rb_first(&(grp->bb_free_root));
3770
3771         while (n) {
3772                 entry = rb_entry(n, struct ext4_free_data, efd_node);
3773                 ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
3774                 n = rb_next(n);
3775         }
3776         return;
3777 }
3778
3779 /*
3780  * the function goes through all preallocation in this group and marks them
3781  * used in in-core bitmap. buddy must be generated from this bitmap
3782  * Need to be called with ext4 group lock held
3783  */
3784 static noinline_for_stack
3785 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3786                                         ext4_group_t group)
3787 {
3788         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3789         struct ext4_prealloc_space *pa;
3790         struct list_head *cur;
3791         ext4_group_t groupnr;
3792         ext4_grpblk_t start;
3793         int preallocated = 0;
3794         int len;
3795
3796         /* all form of preallocation discards first load group,
3797          * so the only competing code is preallocation use.
3798          * we don't need any locking here
3799          * notice we do NOT ignore preallocations with pa_deleted
3800          * otherwise we could leave used blocks available for
3801          * allocation in buddy when concurrent ext4_mb_put_pa()
3802          * is dropping preallocation
3803          */
3804         list_for_each(cur, &grp->bb_prealloc_list) {
3805                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3806                 spin_lock(&pa->pa_lock);
3807                 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3808                                              &groupnr, &start);
3809                 len = pa->pa_len;
3810                 spin_unlock(&pa->pa_lock);
3811                 if (unlikely(len == 0))
3812                         continue;
3813                 BUG_ON(groupnr != group);
3814                 ext4_set_bits(bitmap, start, len);
3815                 preallocated += len;
3816         }
3817         mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
3818 }
3819
3820 static void ext4_mb_pa_callback(struct rcu_head *head)
3821 {
3822         struct ext4_prealloc_space *pa;
3823         pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3824
3825         BUG_ON(atomic_read(&pa->pa_count));
3826         BUG_ON(pa->pa_deleted == 0);
3827         kmem_cache_free(ext4_pspace_cachep, pa);
3828 }
3829
3830 /*
3831  * drops a reference to preallocated space descriptor
3832  * if this was the last reference and the space is consumed
3833  */
3834 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3835                         struct super_block *sb, struct ext4_prealloc_space *pa)
3836 {
3837         ext4_group_t grp;
3838         ext4_fsblk_t grp_blk;
3839
3840         /* in this short window concurrent discard can set pa_deleted */
3841         spin_lock(&pa->pa_lock);
3842         if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
3843                 spin_unlock(&pa->pa_lock);
3844                 return;
3845         }
3846
3847         if (pa->pa_deleted == 1) {
3848                 spin_unlock(&pa->pa_lock);
3849                 return;
3850         }
3851
3852         pa->pa_deleted = 1;
3853         spin_unlock(&pa->pa_lock);
3854
3855         grp_blk = pa->pa_pstart;
3856         /*
3857          * If doing group-based preallocation, pa_pstart may be in the
3858          * next group when pa is used up
3859          */
3860         if (pa->pa_type == MB_GROUP_PA)
3861                 grp_blk--;
3862
3863         grp = ext4_get_group_number(sb, grp_blk);
3864
3865         /*
3866          * possible race:
3867          *
3868          *  P1 (buddy init)                     P2 (regular allocation)
3869          *                                      find block B in PA
3870          *  copy on-disk bitmap to buddy
3871          *                                      mark B in on-disk bitmap
3872          *                                      drop PA from group
3873          *  mark all PAs in buddy
3874          *
3875          * thus, P1 initializes buddy with B available. to prevent this
3876          * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3877          * against that pair
3878          */
3879         ext4_lock_group(sb, grp);
3880         list_del(&pa->pa_group_list);
3881         ext4_unlock_group(sb, grp);
3882
3883         spin_lock(pa->pa_obj_lock);
3884         list_del_rcu(&pa->pa_inode_list);
3885         spin_unlock(pa->pa_obj_lock);
3886
3887         call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3888 }
3889
3890 /*
3891  * creates new preallocated space for given inode
3892  */
3893 static noinline_for_stack void
3894 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3895 {
3896         struct super_block *sb = ac->ac_sb;
3897         struct ext4_sb_info *sbi = EXT4_SB(sb);
3898         struct ext4_prealloc_space *pa;
3899         struct ext4_group_info *grp;
3900         struct ext4_inode_info *ei;
3901
3902         /* preallocate only when found space is larger then requested */
3903         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3904         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3905         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3906         BUG_ON(ac->ac_pa == NULL);
3907
3908         pa = ac->ac_pa;
3909
3910         if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3911                 int winl;
3912                 int wins;
3913                 int win;
3914                 int offs;
3915
3916                 /* we can't allocate as much as normalizer wants.
3917                  * so, found space must get proper lstart
3918                  * to cover original request */
3919                 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3920                 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3921
3922                 /* we're limited by original request in that
3923                  * logical block must be covered any way
3924                  * winl is window we can move our chunk within */
3925                 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3926
3927                 /* also, we should cover whole original request */
3928                 wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
3929
3930                 /* the smallest one defines real window */
3931                 win = min(winl, wins);
3932
3933                 offs = ac->ac_o_ex.fe_logical %
3934                         EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3935                 if (offs && offs < win)
3936                         win = offs;
3937
3938                 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
3939                         EXT4_NUM_B2C(sbi, win);
3940                 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3941                 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3942         }
3943
3944         /* preallocation can change ac_b_ex, thus we store actually
3945          * allocated blocks for history */
3946         ac->ac_f_ex = ac->ac_b_ex;
3947
3948         pa->pa_lstart = ac->ac_b_ex.fe_logical;
3949         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3950         pa->pa_len = ac->ac_b_ex.fe_len;
3951         pa->pa_free = pa->pa_len;
3952         spin_lock_init(&pa->pa_lock);
3953         INIT_LIST_HEAD(&pa->pa_inode_list);
3954         INIT_LIST_HEAD(&pa->pa_group_list);
3955         pa->pa_deleted = 0;
3956         pa->pa_type = MB_INODE_PA;
3957
3958         mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
3959                  pa->pa_len, pa->pa_lstart);
3960         trace_ext4_mb_new_inode_pa(ac, pa);
3961
3962         ext4_mb_use_inode_pa(ac, pa);
3963         atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
3964
3965         ei = EXT4_I(ac->ac_inode);
3966         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3967
3968         pa->pa_obj_lock = &ei->i_prealloc_lock;
3969         pa->pa_inode = ac->ac_inode;
3970
3971         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3972
3973         spin_lock(pa->pa_obj_lock);
3974         list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3975         spin_unlock(pa->pa_obj_lock);
3976 }
3977
3978 /*
3979  * creates new preallocated space for locality group inodes belongs to
3980  */
3981 static noinline_for_stack void
3982 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3983 {
3984         struct super_block *sb = ac->ac_sb;
3985         struct ext4_locality_group *lg;
3986         struct ext4_prealloc_space *pa;
3987         struct ext4_group_info *grp;
3988
3989         /* preallocate only when found space is larger then requested */
3990         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3991         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3992         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3993         BUG_ON(ac->ac_pa == NULL);
3994
3995         pa = ac->ac_pa;
3996
3997         /* preallocation can change ac_b_ex, thus we store actually
3998          * allocated blocks for history */
3999         ac->ac_f_ex = ac->ac_b_ex;
4000
4001         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4002         pa->pa_lstart = pa->pa_pstart;
4003         pa->pa_len = ac->ac_b_ex.fe_len;
4004         pa->pa_free = pa->pa_len;
4005         spin_lock_init(&pa->pa_lock);
4006         INIT_LIST_HEAD(&pa->pa_inode_list);
4007         INIT_LIST_HEAD(&pa->pa_group_list);
4008         pa->pa_deleted = 0;
4009         pa->pa_type = MB_GROUP_PA;
4010
4011         mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
4012                  pa->pa_len, pa->pa_lstart);
4013         trace_ext4_mb_new_group_pa(ac, pa);
4014
4015         ext4_mb_use_group_pa(ac, pa);
4016         atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
4017
4018         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
4019         lg = ac->ac_lg;
4020         BUG_ON(lg == NULL);
4021
4022         pa->pa_obj_lock = &lg->lg_prealloc_lock;
4023         pa->pa_inode = NULL;
4024
4025         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
4026
4027         /*
4028          * We will later add the new pa to the right bucket
4029          * after updating the pa_free in ext4_mb_release_context
4030          */
4031 }
4032
4033 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
4034 {
4035         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4036                 ext4_mb_new_group_pa(ac);
4037         else
4038                 ext4_mb_new_inode_pa(ac);
4039 }
4040
4041 /*
4042  * finds all unused blocks in on-disk bitmap, frees them in
4043  * in-core bitmap and buddy.
4044  * @pa must be unlinked from inode and group lists, so that
4045  * nobody else can find/use it.
4046  * the caller MUST hold group/inode locks.
4047  * TODO: optimize the case when there are no in-core structures yet
4048  */
4049 static noinline_for_stack int
4050 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
4051                         struct ext4_prealloc_space *pa)
4052 {
4053         struct super_block *sb = e4b->bd_sb;
4054         struct ext4_sb_info *sbi = EXT4_SB(sb);
4055         unsigned int end;
4056         unsigned int next;
4057         ext4_group_t group;
4058         ext4_grpblk_t bit;
4059         unsigned long long grp_blk_start;
4060         int free = 0;
4061
4062         BUG_ON(pa->pa_deleted == 0);
4063         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
4064         grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
4065         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
4066         end = bit + pa->pa_len;
4067
4068         while (bit < end) {
4069                 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
4070                 if (bit >= end)
4071                         break;
4072                 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
4073                 mb_debug(sb, "free preallocated %u/%u in group %u\n",
4074                          (unsigned) ext4_group_first_block_no(sb, group) + bit,
4075                          (unsigned) next - bit, (unsigned) group);
4076                 free += next - bit;
4077
4078                 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
4079                 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
4080                                                     EXT4_C2B(sbi, bit)),
4081                                                next - bit);
4082                 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
4083                 bit = next + 1;
4084         }
4085         if (free != pa->pa_free) {
4086                 ext4_msg(e4b->bd_sb, KERN_CRIT,
4087                          "pa %p: logic %lu, phys. %lu, len %d",
4088                          pa, (unsigned long) pa->pa_lstart,
4089                          (unsigned long) pa->pa_pstart,
4090                          pa->pa_len);
4091                 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
4092                                         free, pa->pa_free);
4093                 /*
4094                  * pa is already deleted so we use the value obtained
4095                  * from the bitmap and continue.
4096                  */
4097         }
4098         atomic_add(free, &sbi->s_mb_discarded);
4099
4100         return 0;
4101 }
4102
4103 static noinline_for_stack int
4104 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
4105                                 struct ext4_prealloc_space *pa)
4106 {
4107         struct super_block *sb = e4b->bd_sb;
4108         ext4_group_t group;
4109         ext4_grpblk_t bit;
4110
4111         trace_ext4_mb_release_group_pa(sb, pa);
4112         BUG_ON(pa->pa_deleted == 0);
4113         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
4114         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
4115         mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
4116         atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
4117         trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
4118
4119         return 0;
4120 }
4121
4122 /*
4123  * releases all preallocations in given group
4124  *
4125  * first, we need to decide discard policy:
4126  * - when do we discard
4127  *   1) ENOSPC
4128  * - how many do we discard
4129  *   1) how many requested
4130  */
4131 static noinline_for_stack int
4132 ext4_mb_discard_group_preallocations(struct super_block *sb,
4133                                         ext4_group_t group, int needed)
4134 {
4135         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
4136         struct buffer_head *bitmap_bh = NULL;
4137         struct ext4_prealloc_space *pa, *tmp;
4138         struct list_head list;
4139         struct ext4_buddy e4b;
4140         int err;
4141         int busy = 0;
4142         int free = 0;
4143
4144         mb_debug(sb, "discard preallocation for group %u\n", group);
4145         if (list_empty(&grp->bb_prealloc_list))
4146                 goto out_dbg;
4147
4148         bitmap_bh = ext4_read_block_bitmap(sb, group);
4149         if (IS_ERR(bitmap_bh)) {
4150                 err = PTR_ERR(bitmap_bh);
4151                 ext4_error_err(sb, -err,
4152                                "Error %d reading block bitmap for %u",
4153                                err, group);
4154                 goto out_dbg;
4155         }
4156
4157         err = ext4_mb_load_buddy(sb, group, &e4b);
4158         if (err) {
4159                 ext4_warning(sb, "Error %d loading buddy information for %u",
4160                              err, group);
4161                 put_bh(bitmap_bh);
4162                 goto out_dbg;
4163         }
4164
4165         if (needed == 0)
4166                 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
4167
4168         INIT_LIST_HEAD(&list);
4169 repeat:
4170         ext4_lock_group(sb, group);
4171         this_cpu_inc(discard_pa_seq);
4172         list_for_each_entry_safe(pa, tmp,
4173                                 &grp->bb_prealloc_list, pa_group_list) {
4174                 spin_lock(&pa->pa_lock);
4175                 if (atomic_read(&pa->pa_count)) {
4176                         spin_unlock(&pa->pa_lock);
4177                         busy = 1;
4178                         continue;
4179                 }
4180                 if (pa->pa_deleted) {
4181                         spin_unlock(&pa->pa_lock);
4182                         continue;
4183                 }
4184
4185                 /* seems this one can be freed ... */
4186                 pa->pa_deleted = 1;
4187
4188                 /* we can trust pa_free ... */
4189                 free += pa->pa_free;
4190
4191                 spin_unlock(&pa->pa_lock);
4192
4193                 list_del(&pa->pa_group_list);
4194                 list_add(&pa->u.pa_tmp_list, &list);
4195         }
4196
4197         /* if we still need more blocks and some PAs were used, try again */
4198         if (free < needed && busy) {
4199                 busy = 0;
4200                 ext4_unlock_group(sb, group);
4201                 cond_resched();
4202                 goto repeat;
4203         }
4204
4205         /* found anything to free? */
4206         if (list_empty(&list)) {
4207                 BUG_ON(free != 0);
4208                 mb_debug(sb, "Someone else may have freed PA for this group %u\n",
4209                          group);
4210                 goto out;
4211         }
4212
4213         /* now free all selected PAs */
4214         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4215
4216                 /* remove from object (inode or locality group) */
4217                 spin_lock(pa->pa_obj_lock);
4218                 list_del_rcu(&pa->pa_inode_list);
4219                 spin_unlock(pa->pa_obj_lock);
4220
4221                 if (pa->pa_type == MB_GROUP_PA)
4222                         ext4_mb_release_group_pa(&e4b, pa);
4223                 else
4224                         ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4225
4226                 list_del(&pa->u.pa_tmp_list);
4227                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4228         }
4229
4230 out:
4231         ext4_unlock_group(sb, group);
4232         ext4_mb_unload_buddy(&e4b);
4233         put_bh(bitmap_bh);
4234 out_dbg:
4235         mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
4236                  free, group, grp->bb_free);
4237         return free;
4238 }
4239
4240 /*
4241  * releases all non-used preallocated blocks for given inode
4242  *
4243  * It's important to discard preallocations under i_data_sem
4244  * We don't want another block to be served from the prealloc
4245  * space when we are discarding the inode prealloc space.
4246  *
4247  * FIXME!! Make sure it is valid at all the call sites
4248  */
4249 void ext4_discard_preallocations(struct inode *inode)
4250 {
4251         struct ext4_inode_info *ei = EXT4_I(inode);
4252         struct super_block *sb = inode->i_sb;
4253         struct buffer_head *bitmap_bh = NULL;
4254         struct ext4_prealloc_space *pa, *tmp;
4255         ext4_group_t group = 0;
4256         struct list_head list;
4257         struct ext4_buddy e4b;
4258         int err;
4259
4260         if (!S_ISREG(inode->i_mode)) {
4261                 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4262                 return;
4263         }
4264
4265         mb_debug(sb, "discard preallocation for inode %lu\n",
4266                  inode->i_ino);
4267         trace_ext4_discard_preallocations(inode);
4268
4269         INIT_LIST_HEAD(&list);
4270
4271 repeat:
4272         /* first, collect all pa's in the inode */
4273         spin_lock(&ei->i_prealloc_lock);
4274         while (!list_empty(&ei->i_prealloc_list)) {
4275                 pa = list_entry(ei->i_prealloc_list.next,
4276                                 struct ext4_prealloc_space, pa_inode_list);
4277                 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4278                 spin_lock(&pa->pa_lock);
4279                 if (atomic_read(&pa->pa_count)) {
4280                         /* this shouldn't happen often - nobody should
4281                          * use preallocation while we're discarding it */
4282                         spin_unlock(&pa->pa_lock);
4283                         spin_unlock(&ei->i_prealloc_lock);
4284                         ext4_msg(sb, KERN_ERR,
4285                                  "uh-oh! used pa while discarding");
4286                         WARN_ON(1);
4287                         schedule_timeout_uninterruptible(HZ);
4288                         goto repeat;
4289
4290                 }
4291                 if (pa->pa_deleted == 0) {
4292                         pa->pa_deleted = 1;
4293                         spin_unlock(&pa->pa_lock);
4294                         list_del_rcu(&pa->pa_inode_list);
4295                         list_add(&pa->u.pa_tmp_list, &list);
4296                         continue;
4297                 }
4298
4299                 /* someone is deleting pa right now */
4300                 spin_unlock(&pa->pa_lock);
4301                 spin_unlock(&ei->i_prealloc_lock);
4302
4303                 /* we have to wait here because pa_deleted
4304                  * doesn't mean pa is already unlinked from
4305                  * the list. as we might be called from
4306                  * ->clear_inode() the inode will get freed
4307                  * and concurrent thread which is unlinking
4308                  * pa from inode's list may access already
4309                  * freed memory, bad-bad-bad */
4310
4311                 /* XXX: if this happens too often, we can
4312                  * add a flag to force wait only in case
4313                  * of ->clear_inode(), but not in case of
4314                  * regular truncate */
4315                 schedule_timeout_uninterruptible(HZ);
4316                 goto repeat;
4317         }
4318         spin_unlock(&ei->i_prealloc_lock);
4319
4320         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4321                 BUG_ON(pa->pa_type != MB_INODE_PA);
4322                 group = ext4_get_group_number(sb, pa->pa_pstart);
4323
4324                 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4325                                              GFP_NOFS|__GFP_NOFAIL);
4326                 if (err) {
4327                         ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
4328                                        err, group);
4329                         continue;
4330                 }
4331
4332                 bitmap_bh = ext4_read_block_bitmap(sb, group);
4333                 if (IS_ERR(bitmap_bh)) {
4334                         err = PTR_ERR(bitmap_bh);
4335                         ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
4336                                        err, group);
4337                         ext4_mb_unload_buddy(&e4b);
4338                         continue;
4339                 }
4340
4341                 ext4_lock_group(sb, group);
4342                 list_del(&pa->pa_group_list);
4343                 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4344                 ext4_unlock_group(sb, group);
4345
4346                 ext4_mb_unload_buddy(&e4b);
4347                 put_bh(bitmap_bh);
4348
4349                 list_del(&pa->u.pa_tmp_list);
4350                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4351         }
4352 }
4353
4354 static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
4355 {
4356         struct ext4_prealloc_space *pa;
4357
4358         BUG_ON(ext4_pspace_cachep == NULL);
4359         pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
4360         if (!pa)
4361                 return -ENOMEM;
4362         atomic_set(&pa->pa_count, 1);
4363         ac->ac_pa = pa;
4364         return 0;
4365 }
4366
4367 static void ext4_mb_pa_free(struct ext4_allocation_context *ac)
4368 {
4369         struct ext4_prealloc_space *pa = ac->ac_pa;
4370
4371         BUG_ON(!pa);
4372         ac->ac_pa = NULL;
4373         WARN_ON(!atomic_dec_and_test(&pa->pa_count));
4374         kmem_cache_free(ext4_pspace_cachep, pa);
4375 }
4376
4377 #ifdef CONFIG_EXT4_DEBUG
4378 static inline void ext4_mb_show_pa(struct super_block *sb)
4379 {
4380         ext4_group_t i, ngroups;
4381
4382         if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
4383                 return;
4384
4385         ngroups = ext4_get_groups_count(sb);
4386         mb_debug(sb, "groups: ");
4387         for (i = 0; i < ngroups; i++) {
4388                 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4389                 struct ext4_prealloc_space *pa;
4390                 ext4_grpblk_t start;
4391                 struct list_head *cur;
4392                 ext4_lock_group(sb, i);
4393                 list_for_each(cur, &grp->bb_prealloc_list) {
4394                         pa = list_entry(cur, struct ext4_prealloc_space,
4395                                         pa_group_list);
4396                         spin_lock(&pa->pa_lock);
4397                         ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4398                                                      NULL, &start);
4399                         spin_unlock(&pa->pa_lock);
4400                         mb_debug(sb, "PA:%u:%d:%d\n", i, start,
4401                                  pa->pa_len);
4402                 }
4403                 ext4_unlock_group(sb, i);
4404                 mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
4405                          grp->bb_fragments);
4406         }
4407 }
4408
4409 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4410 {
4411         struct super_block *sb = ac->ac_sb;
4412
4413         if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
4414                 return;
4415
4416         mb_debug(sb, "Can't allocate:"
4417                         " Allocation context details:");
4418         mb_debug(sb, "status %u flags 0x%x",
4419                         ac->ac_status, ac->ac_flags);
4420         mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
4421                         "goal %lu/%lu/%lu@%lu, "
4422                         "best %lu/%lu/%lu@%lu cr %d",
4423                         (unsigned long)ac->ac_o_ex.fe_group,
4424                         (unsigned long)ac->ac_o_ex.fe_start,
4425                         (unsigned long)ac->ac_o_ex.fe_len,
4426                         (unsigned long)ac->ac_o_ex.fe_logical,
4427                         (unsigned long)ac->ac_g_ex.fe_group,
4428                         (unsigned long)ac->ac_g_ex.fe_start,
4429                         (unsigned long)ac->ac_g_ex.fe_len,
4430                         (unsigned long)ac->ac_g_ex.fe_logical,
4431                         (unsigned long)ac->ac_b_ex.fe_group,
4432                         (unsigned long)ac->ac_b_ex.fe_start,
4433                         (unsigned long)ac->ac_b_ex.fe_len,
4434                         (unsigned long)ac->ac_b_ex.fe_logical,
4435                         (int)ac->ac_criteria);
4436         mb_debug(sb, "%u found", ac->ac_found);
4437         ext4_mb_show_pa(sb);
4438 }
4439 #else
4440 static inline void ext4_mb_show_pa(struct super_block *sb)
4441 {
4442         return;
4443 }
4444 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4445 {
4446         ext4_mb_show_pa(ac->ac_sb);
4447         return;
4448 }
4449 #endif
4450
4451 /*
4452  * We use locality group preallocation for small size file. The size of the
4453  * file is determined by the current size or the resulting size after
4454  * allocation which ever is larger
4455  *
4456  * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4457  */
4458 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4459 {
4460         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4461         int bsbits = ac->ac_sb->s_blocksize_bits;
4462         loff_t size, isize;
4463
4464         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4465                 return;
4466
4467         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4468                 return;
4469
4470         size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
4471         isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
4472                 >> bsbits;
4473
4474         if ((size == isize) && !ext4_fs_is_busy(sbi) &&
4475             !inode_is_open_for_write(ac->ac_inode)) {
4476                 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
4477                 return;
4478         }
4479
4480         if (sbi->s_mb_group_prealloc <= 0) {
4481                 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4482                 return;
4483         }
4484
4485         /* don't use group allocation for large files */
4486         size = max(size, isize);
4487         if (size > sbi->s_mb_stream_request) {
4488                 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4489                 return;
4490         }
4491
4492         BUG_ON(ac->ac_lg != NULL);
4493         /*
4494          * locality group prealloc space are per cpu. The reason for having
4495          * per cpu locality group is to reduce the contention between block
4496          * request from multiple CPUs.
4497          */
4498         ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
4499
4500         /* we're going to use group allocation */
4501         ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4502
4503         /* serialize all allocations in the group */
4504         mutex_lock(&ac->ac_lg->lg_mutex);
4505 }
4506
4507 static noinline_for_stack int
4508 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4509                                 struct ext4_allocation_request *ar)
4510 {
4511         struct super_block *sb = ar->inode->i_sb;
4512         struct ext4_sb_info *sbi = EXT4_SB(sb);
4513         struct ext4_super_block *es = sbi->s_es;
4514         ext4_group_t group;
4515         unsigned int len;
4516         ext4_fsblk_t goal;
4517         ext4_grpblk_t block;
4518
4519         /* we can't allocate > group size */
4520         len = ar->len;
4521
4522         /* just a dirty hack to filter too big requests  */
4523         if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
4524                 len = EXT4_CLUSTERS_PER_GROUP(sb);
4525
4526         /* start searching from the goal */
4527         goal = ar->goal;
4528         if (goal < le32_to_cpu(es->s_first_data_block) ||
4529                         goal >= ext4_blocks_count(es))
4530                 goal = le32_to_cpu(es->s_first_data_block);
4531         ext4_get_group_no_and_offset(sb, goal, &group, &block);
4532
4533         /* set up allocation goals */
4534         ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
4535         ac->ac_status = AC_STATUS_CONTINUE;
4536         ac->ac_sb = sb;
4537         ac->ac_inode = ar->inode;
4538         ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4539         ac->ac_o_ex.fe_group = group;
4540         ac->ac_o_ex.fe_start = block;
4541         ac->ac_o_ex.fe_len = len;
4542         ac->ac_g_ex = ac->ac_o_ex;
4543         ac->ac_flags = ar->flags;
4544
4545         /* we have to define context: we'll work with a file or
4546          * locality group. this is a policy, actually */
4547         ext4_mb_group_or_file(ac);
4548
4549         mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
4550                         "left: %u/%u, right %u/%u to %swritable\n",
4551                         (unsigned) ar->len, (unsigned) ar->logical,
4552                         (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4553                         (unsigned) ar->lleft, (unsigned) ar->pleft,
4554                         (unsigned) ar->lright, (unsigned) ar->pright,
4555                         inode_is_open_for_write(ar->inode) ? "" : "non-");
4556         return 0;
4557
4558 }
4559
4560 static noinline_for_stack void
4561 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4562                                         struct ext4_locality_group *lg,
4563                                         int order, int total_entries)
4564 {
4565         ext4_group_t group = 0;
4566         struct ext4_buddy e4b;
4567         struct list_head discard_list;
4568         struct ext4_prealloc_space *pa, *tmp;
4569
4570         mb_debug(sb, "discard locality group preallocation\n");
4571
4572         INIT_LIST_HEAD(&discard_list);
4573
4574         spin_lock(&lg->lg_prealloc_lock);
4575         list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4576                                 pa_inode_list,
4577                                 lockdep_is_held(&lg->lg_prealloc_lock)) {
4578                 spin_lock(&pa->pa_lock);
4579                 if (atomic_read(&pa->pa_count)) {
4580                         /*
4581                          * This is the pa that we just used
4582                          * for block allocation. So don't
4583                          * free that
4584                          */
4585                         spin_unlock(&pa->pa_lock);
4586                         continue;
4587                 }
4588                 if (pa->pa_deleted) {
4589                         spin_unlock(&pa->pa_lock);
4590                         continue;
4591                 }
4592                 /* only lg prealloc space */
4593                 BUG_ON(pa->pa_type != MB_GROUP_PA);
4594
4595                 /* seems this one can be freed ... */
4596                 pa->pa_deleted = 1;
4597                 spin_unlock(&pa->pa_lock);
4598
4599                 list_del_rcu(&pa->pa_inode_list);
4600                 list_add(&pa->u.pa_tmp_list, &discard_list);
4601
4602                 total_entries--;
4603                 if (total_entries <= 5) {
4604                         /*
4605                          * we want to keep only 5 entries
4606                          * allowing it to grow to 8. This
4607                          * mak sure we don't call discard
4608                          * soon for this list.
4609                          */
4610                         break;
4611                 }
4612         }
4613         spin_unlock(&lg->lg_prealloc_lock);
4614
4615         list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4616                 int err;
4617
4618                 group = ext4_get_group_number(sb, pa->pa_pstart);
4619                 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4620                                              GFP_NOFS|__GFP_NOFAIL);
4621                 if (err) {
4622                         ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
4623                                        err, group);
4624                         continue;
4625                 }
4626                 ext4_lock_group(sb, group);
4627                 list_del(&pa->pa_group_list);
4628                 ext4_mb_release_group_pa(&e4b, pa);
4629                 ext4_unlock_group(sb, group);
4630
4631                 ext4_mb_unload_buddy(&e4b);
4632                 list_del(&pa->u.pa_tmp_list);
4633                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4634         }
4635 }
4636
4637 /*
4638  * We have incremented pa_count. So it cannot be freed at this
4639  * point. Also we hold lg_mutex. So no parallel allocation is
4640  * possible from this lg. That means pa_free cannot be updated.
4641  *
4642  * A parallel ext4_mb_discard_group_preallocations is possible.
4643  * which can cause the lg_prealloc_list to be updated.
4644  */
4645
4646 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4647 {
4648         int order, added = 0, lg_prealloc_count = 1;
4649         struct super_block *sb = ac->ac_sb;
4650         struct ext4_locality_group *lg = ac->ac_lg;
4651         struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4652
4653         order = fls(pa->pa_free) - 1;
4654         if (order > PREALLOC_TB_SIZE - 1)
4655                 /* The max size of hash table is PREALLOC_TB_SIZE */
4656                 order = PREALLOC_TB_SIZE - 1;
4657         /* Add the prealloc space to lg */
4658         spin_lock(&lg->lg_prealloc_lock);
4659         list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4660                                 pa_inode_list,
4661                                 lockdep_is_held(&lg->lg_prealloc_lock)) {
4662                 spin_lock(&tmp_pa->pa_lock);
4663                 if (tmp_pa->pa_deleted) {
4664                         spin_unlock(&tmp_pa->pa_lock);
4665                         continue;
4666                 }
4667                 if (!added && pa->pa_free < tmp_pa->pa_free) {
4668                         /* Add to the tail of the previous entry */
4669                         list_add_tail_rcu(&pa->pa_inode_list,
4670                                                 &tmp_pa->pa_inode_list);
4671                         added = 1;
4672                         /*
4673                          * we want to count the total
4674                          * number of entries in the list
4675                          */
4676                 }
4677                 spin_unlock(&tmp_pa->pa_lock);
4678                 lg_prealloc_count++;
4679         }
4680         if (!added)
4681                 list_add_tail_rcu(&pa->pa_inode_list,
4682                                         &lg->lg_prealloc_list[order]);
4683         spin_unlock(&lg->lg_prealloc_lock);
4684
4685         /* Now trim the list to be not more than 8 elements */
4686         if (lg_prealloc_count > 8) {
4687                 ext4_mb_discard_lg_preallocations(sb, lg,
4688                                                   order, lg_prealloc_count);
4689                 return;
4690         }
4691         return ;
4692 }
4693
4694 /*
4695  * release all resource we used in allocation
4696  */
4697 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4698 {
4699         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4700         struct ext4_prealloc_space *pa = ac->ac_pa;
4701         if (pa) {
4702                 if (pa->pa_type == MB_GROUP_PA) {
4703                         /* see comment in ext4_mb_use_group_pa() */
4704                         spin_lock(&pa->pa_lock);
4705                         pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4706                         pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4707                         pa->pa_free -= ac->ac_b_ex.fe_len;
4708                         pa->pa_len -= ac->ac_b_ex.fe_len;
4709                         spin_unlock(&pa->pa_lock);
4710                 }
4711         }
4712         if (pa) {
4713                 /*
4714                  * We want to add the pa to the right bucket.
4715                  * Remove it from the list and while adding
4716                  * make sure the list to which we are adding
4717                  * doesn't grow big.
4718                  */
4719                 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4720                         spin_lock(pa->pa_obj_lock);
4721                         list_del_rcu(&pa->pa_inode_list);
4722                         spin_unlock(pa->pa_obj_lock);
4723                         ext4_mb_add_n_trim(ac);
4724                 }
4725                 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4726         }
4727         if (ac->ac_bitmap_page)
4728                 put_page(ac->ac_bitmap_page);
4729         if (ac->ac_buddy_page)
4730                 put_page(ac->ac_buddy_page);
4731         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4732                 mutex_unlock(&ac->ac_lg->lg_mutex);
4733         ext4_mb_collect_stats(ac);
4734         return 0;
4735 }
4736
4737 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4738 {
4739         ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4740         int ret;
4741         int freed = 0;
4742
4743         trace_ext4_mb_discard_preallocations(sb, needed);
4744         for (i = 0; i < ngroups && needed > 0; i++) {
4745                 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4746                 freed += ret;
4747                 needed -= ret;
4748         }
4749
4750         return freed;
4751 }
4752
4753 static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
4754                         struct ext4_allocation_context *ac, u64 *seq)
4755 {
4756         int freed;
4757         u64 seq_retry = 0;
4758         bool ret = false;
4759
4760         freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4761         if (freed) {
4762                 ret = true;
4763                 goto out_dbg;
4764         }
4765         seq_retry = ext4_get_discard_pa_seq_sum();
4766         if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
4767                 ac->ac_flags |= EXT4_MB_STRICT_CHECK;
4768                 *seq = seq_retry;
4769                 ret = true;
4770         }
4771
4772 out_dbg:
4773         mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
4774         return ret;
4775 }
4776
4777 /*
4778  * Main entry point into mballoc to allocate blocks
4779  * it tries to use preallocation first, then falls back
4780  * to usual allocation
4781  */
4782 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4783                                 struct ext4_allocation_request *ar, int *errp)
4784 {
4785         struct ext4_allocation_context *ac = NULL;
4786         struct ext4_sb_info *sbi;
4787         struct super_block *sb;
4788         ext4_fsblk_t block = 0;
4789         unsigned int inquota = 0;
4790         unsigned int reserv_clstrs = 0;
4791         u64 seq;
4792
4793         might_sleep();
4794         sb = ar->inode->i_sb;
4795         sbi = EXT4_SB(sb);
4796
4797         trace_ext4_request_blocks(ar);
4798
4799         /* Allow to use superuser reservation for quota file */
4800         if (ext4_is_quota_file(ar->inode))
4801                 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
4802
4803         if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
4804                 /* Without delayed allocation we need to verify
4805                  * there is enough free blocks to do block allocation
4806                  * and verify allocation doesn't exceed the quota limits.
4807                  */
4808                 while (ar->len &&
4809                         ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
4810
4811                         /* let others to free the space */
4812                         cond_resched();
4813                         ar->len = ar->len >> 1;
4814                 }
4815                 if (!ar->len) {
4816                         ext4_mb_show_pa(sb);
4817                         *errp = -ENOSPC;
4818                         return 0;
4819                 }
4820                 reserv_clstrs = ar->len;
4821                 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
4822                         dquot_alloc_block_nofail(ar->inode,
4823                                                  EXT4_C2B(sbi, ar->len));
4824                 } else {
4825                         while (ar->len &&
4826                                 dquot_alloc_block(ar->inode,
4827                                                   EXT4_C2B(sbi, ar->len))) {
4828
4829                                 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4830                                 ar->len--;
4831                         }
4832                 }
4833                 inquota = ar->len;
4834                 if (ar->len == 0) {
4835                         *errp = -EDQUOT;
4836                         goto out;
4837                 }
4838         }
4839
4840         ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
4841         if (!ac) {
4842                 ar->len = 0;
4843                 *errp = -ENOMEM;
4844                 goto out;
4845         }
4846
4847         *errp = ext4_mb_initialize_context(ac, ar);
4848         if (*errp) {
4849                 ar->len = 0;
4850                 goto out;
4851         }
4852
4853         ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4854         seq = this_cpu_read(discard_pa_seq);
4855         if (!ext4_mb_use_preallocated(ac)) {
4856                 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4857                 ext4_mb_normalize_request(ac, ar);
4858
4859                 *errp = ext4_mb_pa_alloc(ac);
4860                 if (*errp)
4861                         goto errout;
4862 repeat:
4863                 /* allocate space in core */
4864                 *errp = ext4_mb_regular_allocator(ac);
4865                 /*
4866                  * pa allocated above is added to grp->bb_prealloc_list only
4867                  * when we were able to allocate some block i.e. when
4868                  * ac->ac_status == AC_STATUS_FOUND.
4869                  * And error from above mean ac->ac_status != AC_STATUS_FOUND
4870                  * So we have to free this pa here itself.
4871                  */
4872                 if (*errp) {
4873                         ext4_mb_pa_free(ac);
4874                         ext4_discard_allocated_blocks(ac);
4875                         goto errout;
4876                 }
4877                 if (ac->ac_status == AC_STATUS_FOUND &&
4878                         ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
4879                         ext4_mb_pa_free(ac);
4880         }
4881         if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4882                 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4883                 if (*errp) {
4884                         ext4_discard_allocated_blocks(ac);
4885                         goto errout;
4886                 } else {
4887                         block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4888                         ar->len = ac->ac_b_ex.fe_len;
4889                 }
4890         } else {
4891                 if (ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
4892                         goto repeat;
4893                 /*
4894                  * If block allocation fails then the pa allocated above
4895                  * needs to be freed here itself.
4896                  */
4897                 ext4_mb_pa_free(ac);
4898                 *errp = -ENOSPC;
4899         }
4900
4901 errout:
4902         if (*errp) {
4903                 ac->ac_b_ex.fe_len = 0;
4904                 ar->len = 0;
4905                 ext4_mb_show_ac(ac);
4906         }
4907         ext4_mb_release_context(ac);
4908 out:
4909         if (ac)
4910                 kmem_cache_free(ext4_ac_cachep, ac);
4911         if (inquota && ar->len < inquota)
4912                 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
4913         if (!ar->len) {
4914                 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
4915                         /* release all the reserved blocks if non delalloc */
4916                         percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4917                                                 reserv_clstrs);
4918         }
4919
4920         trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4921
4922         return block;
4923 }
4924
4925 /*
4926  * We can merge two free data extents only if the physical blocks
4927  * are contiguous, AND the extents were freed by the same transaction,
4928  * AND the blocks are associated with the same group.
4929  */
4930 static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
4931                                         struct ext4_free_data *entry,
4932                                         struct ext4_free_data *new_entry,
4933                                         struct rb_root *entry_rb_root)
4934 {
4935         if ((entry->efd_tid != new_entry->efd_tid) ||
4936             (entry->efd_group != new_entry->efd_group))
4937                 return;
4938         if (entry->efd_start_cluster + entry->efd_count ==
4939             new_entry->efd_start_cluster) {
4940                 new_entry->efd_start_cluster = entry->efd_start_cluster;
4941                 new_entry->efd_count += entry->efd_count;
4942         } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
4943                    entry->efd_start_cluster) {
4944                 new_entry->efd_count += entry->efd_count;
4945         } else
4946                 return;
4947         spin_lock(&sbi->s_md_lock);
4948         list_del(&entry->efd_list);
4949         spin_unlock(&sbi->s_md_lock);
4950         rb_erase(&entry->efd_node, entry_rb_root);
4951         kmem_cache_free(ext4_free_data_cachep, entry);
4952 }
4953
4954 static noinline_for_stack int
4955 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4956                       struct ext4_free_data *new_entry)
4957 {
4958         ext4_group_t group = e4b->bd_group;
4959         ext4_grpblk_t cluster;
4960         ext4_grpblk_t clusters = new_entry->efd_count;
4961         struct ext4_free_data *entry;
4962         struct ext4_group_info *db = e4b->bd_info;
4963         struct super_block *sb = e4b->bd_sb;
4964         struct ext4_sb_info *sbi = EXT4_SB(sb);
4965         struct rb_node **n = &db->bb_free_root.rb_node, *node;
4966         struct rb_node *parent = NULL, *new_node;
4967
4968         BUG_ON(!ext4_handle_valid(handle));
4969         BUG_ON(e4b->bd_bitmap_page == NULL);
4970         BUG_ON(e4b->bd_buddy_page == NULL);
4971
4972         new_node = &new_entry->efd_node;
4973         cluster = new_entry->efd_start_cluster;
4974
4975         if (!*n) {
4976                 /* first free block exent. We need to
4977                    protect buddy cache from being freed,
4978                  * otherwise we'll refresh it from
4979                  * on-disk bitmap and lose not-yet-available
4980                  * blocks */
4981                 get_page(e4b->bd_buddy_page);
4982                 get_page(e4b->bd_bitmap_page);
4983         }
4984         while (*n) {
4985                 parent = *n;
4986                 entry = rb_entry(parent, struct ext4_free_data, efd_node);
4987                 if (cluster < entry->efd_start_cluster)
4988                         n = &(*n)->rb_left;
4989                 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
4990                         n = &(*n)->rb_right;
4991                 else {
4992                         ext4_grp_locked_error(sb, group, 0,
4993                                 ext4_group_first_block_no(sb, group) +
4994                                 EXT4_C2B(sbi, cluster),
4995                                 "Block already on to-be-freed list");
4996                         return 0;
4997                 }
4998         }
4999
5000         rb_link_node(new_node, parent, n);
5001         rb_insert_color(new_node, &db->bb_free_root);
5002
5003         /* Now try to see the extent can be merged to left and right */
5004         node = rb_prev(new_node);
5005         if (node) {
5006                 entry = rb_entry(node, struct ext4_free_data, efd_node);
5007                 ext4_try_merge_freed_extent(sbi, entry, new_entry,
5008                                             &(db->bb_free_root));
5009         }
5010
5011         node = rb_next(new_node);
5012         if (node) {
5013                 entry = rb_entry(node, struct ext4_free_data, efd_node);
5014                 ext4_try_merge_freed_extent(sbi, entry, new_entry,
5015                                             &(db->bb_free_root));
5016         }
5017
5018         spin_lock(&sbi->s_md_lock);
5019         list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
5020         sbi->s_mb_free_pending += clusters;
5021         spin_unlock(&sbi->s_md_lock);
5022         return 0;
5023 }
5024
5025 /**
5026  * ext4_free_blocks() -- Free given blocks and update quota
5027  * @handle:             handle for this transaction
5028  * @inode:              inode
5029  * @bh:                 optional buffer of the block to be freed
5030  * @block:              starting physical block to be freed
5031  * @count:              number of blocks to be freed
5032  * @flags:              flags used by ext4_free_blocks
5033  */
5034 void ext4_free_blocks(handle_t *handle, struct inode *inode,
5035                       struct buffer_head *bh, ext4_fsblk_t block,
5036                       unsigned long count, int flags)
5037 {
5038         struct buffer_head *bitmap_bh = NULL;
5039         struct super_block *sb = inode->i_sb;
5040         struct ext4_group_desc *gdp;
5041         unsigned int overflow;
5042         ext4_grpblk_t bit;
5043         struct buffer_head *gd_bh;
5044         ext4_group_t block_group;
5045         struct ext4_sb_info *sbi;
5046         struct ext4_buddy e4b;
5047         unsigned int count_clusters;
5048         int err = 0;
5049         int ret;
5050
5051         might_sleep();
5052         if (bh) {
5053                 if (block)
5054                         BUG_ON(block != bh->b_blocknr);
5055                 else
5056                         block = bh->b_blocknr;
5057         }
5058
5059         sbi = EXT4_SB(sb);
5060         if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
5061             !ext4_inode_block_valid(inode, block, count)) {
5062                 ext4_error(sb, "Freeing blocks not in datazone - "
5063                            "block = %llu, count = %lu", block, count);
5064                 goto error_return;
5065         }
5066
5067         ext4_debug("freeing block %llu\n", block);
5068         trace_ext4_free_blocks(inode, block, count, flags);
5069
5070         if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
5071                 BUG_ON(count > 1);
5072
5073                 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
5074                             inode, bh, block);
5075         }
5076
5077         /*
5078          * If the extent to be freed does not begin on a cluster
5079          * boundary, we need to deal with partial clusters at the
5080          * beginning and end of the extent.  Normally we will free
5081          * blocks at the beginning or the end unless we are explicitly
5082          * requested to avoid doing so.
5083          */
5084         overflow = EXT4_PBLK_COFF(sbi, block);
5085         if (overflow) {
5086                 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
5087                         overflow = sbi->s_cluster_ratio - overflow;
5088                         block += overflow;
5089                         if (count > overflow)
5090                                 count -= overflow;
5091                         else
5092                                 return;
5093                 } else {
5094                         block -= overflow;
5095                         count += overflow;
5096                 }
5097         }
5098         overflow = EXT4_LBLK_COFF(sbi, count);
5099         if (overflow) {
5100                 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
5101                         if (count > overflow)
5102                                 count -= overflow;
5103                         else
5104                                 return;
5105                 } else
5106                         count += sbi->s_cluster_ratio - overflow;
5107         }
5108
5109         if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
5110                 int i;
5111                 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
5112
5113                 for (i = 0; i < count; i++) {
5114                         cond_resched();
5115                         if (is_metadata)
5116                                 bh = sb_find_get_block(inode->i_sb, block + i);
5117                         ext4_forget(handle, is_metadata, inode, bh, block + i);
5118                 }
5119         }
5120
5121 do_more:
5122         overflow = 0;
5123         ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5124
5125         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
5126                         ext4_get_group_info(sb, block_group))))
5127                 return;
5128
5129         /*
5130          * Check to see if we are freeing blocks across a group
5131          * boundary.
5132          */
5133         if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
5134                 overflow = EXT4_C2B(sbi, bit) + count -
5135                         EXT4_BLOCKS_PER_GROUP(sb);
5136                 count -= overflow;
5137         }
5138         count_clusters = EXT4_NUM_B2C(sbi, count);
5139         bitmap_bh = ext4_read_block_bitmap(sb, block_group);
5140         if (IS_ERR(bitmap_bh)) {
5141                 err = PTR_ERR(bitmap_bh);
5142                 bitmap_bh = NULL;
5143                 goto error_return;
5144         }
5145         gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
5146         if (!gdp) {
5147                 err = -EIO;
5148                 goto error_return;
5149         }
5150
5151         if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
5152             in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
5153             in_range(block, ext4_inode_table(sb, gdp),
5154                      sbi->s_itb_per_group) ||
5155             in_range(block + count - 1, ext4_inode_table(sb, gdp),
5156                      sbi->s_itb_per_group)) {
5157
5158                 ext4_error(sb, "Freeing blocks in system zone - "
5159                            "Block = %llu, count = %lu", block, count);
5160                 /* err = 0. ext4_std_error should be a no op */
5161                 goto error_return;
5162         }
5163
5164         BUFFER_TRACE(bitmap_bh, "getting write access");
5165         err = ext4_journal_get_write_access(handle, bitmap_bh);
5166         if (err)
5167                 goto error_return;
5168
5169         /*
5170          * We are about to modify some metadata.  Call the journal APIs
5171          * to unshare ->b_data if a currently-committing transaction is
5172          * using it
5173          */
5174         BUFFER_TRACE(gd_bh, "get_write_access");
5175         err = ext4_journal_get_write_access(handle, gd_bh);
5176         if (err)
5177                 goto error_return;
5178 #ifdef AGGRESSIVE_CHECK
5179         {
5180                 int i;
5181                 for (i = 0; i < count_clusters; i++)
5182                         BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
5183         }
5184 #endif
5185         trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
5186
5187         /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
5188         err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
5189                                      GFP_NOFS|__GFP_NOFAIL);
5190         if (err)
5191                 goto error_return;
5192
5193         /*
5194          * We need to make sure we don't reuse the freed block until after the
5195          * transaction is committed. We make an exception if the inode is to be
5196          * written in writeback mode since writeback mode has weak data
5197          * consistency guarantees.
5198          */
5199         if (ext4_handle_valid(handle) &&
5200             ((flags & EXT4_FREE_BLOCKS_METADATA) ||
5201              !ext4_should_writeback_data(inode))) {
5202                 struct ext4_free_data *new_entry;
5203                 /*
5204                  * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
5205                  * to fail.
5206                  */
5207                 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
5208                                 GFP_NOFS|__GFP_NOFAIL);
5209                 new_entry->efd_start_cluster = bit;
5210                 new_entry->efd_group = block_group;
5211                 new_entry->efd_count = count_clusters;
5212                 new_entry->efd_tid = handle->h_transaction->t_tid;
5213
5214                 ext4_lock_group(sb, block_group);
5215                 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
5216                 ext4_mb_free_metadata(handle, &e4b, new_entry);
5217         } else {
5218                 /* need to update group_info->bb_free and bitmap
5219                  * with group lock held. generate_buddy look at
5220                  * them with group lock_held
5221                  */
5222                 if (test_opt(sb, DISCARD)) {
5223                         err = ext4_issue_discard(sb, block_group, bit, count,
5224                                                  NULL);
5225                         if (err && err != -EOPNOTSUPP)
5226                                 ext4_msg(sb, KERN_WARNING, "discard request in"
5227                                          " group:%d block:%d count:%lu failed"
5228                                          " with %d", block_group, bit, count,
5229                                          err);
5230                 } else
5231                         EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
5232
5233                 ext4_lock_group(sb, block_group);
5234                 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
5235                 mb_free_blocks(inode, &e4b, bit, count_clusters);
5236         }
5237
5238         ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
5239         ext4_free_group_clusters_set(sb, gdp, ret);
5240         ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
5241         ext4_group_desc_csum_set(sb, block_group, gdp);
5242         ext4_unlock_group(sb, block_group);
5243
5244         if (sbi->s_log_groups_per_flex) {
5245                 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5246                 atomic64_add(count_clusters,
5247                              &sbi_array_rcu_deref(sbi, s_flex_groups,
5248                                                   flex_group)->free_clusters);
5249         }
5250
5251         /*
5252          * on a bigalloc file system, defer the s_freeclusters_counter
5253          * update to the caller (ext4_remove_space and friends) so they
5254          * can determine if a cluster freed here should be rereserved
5255          */
5256         if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
5257                 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
5258                         dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
5259                 percpu_counter_add(&sbi->s_freeclusters_counter,
5260                                    count_clusters);
5261         }
5262
5263         ext4_mb_unload_buddy(&e4b);
5264
5265         /* We dirtied the bitmap block */
5266         BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5267         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5268
5269         /* And the group descriptor block */
5270         BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5271         ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5272         if (!err)
5273                 err = ret;
5274
5275         if (overflow && !err) {
5276                 block += count;
5277                 count = overflow;
5278                 put_bh(bitmap_bh);
5279                 goto do_more;
5280         }
5281 error_return:
5282         brelse(bitmap_bh);
5283         ext4_std_error(sb, err);
5284         return;
5285 }
5286
5287 /**
5288  * ext4_group_add_blocks() -- Add given blocks to an existing group
5289  * @handle:                     handle to this transaction
5290  * @sb:                         super block
5291  * @block:                      start physical block to add to the block group
5292  * @count:                      number of blocks to free
5293  *
5294  * This marks the blocks as free in the bitmap and buddy.
5295  */
5296 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
5297                          ext4_fsblk_t block, unsigned long count)
5298 {
5299         struct buffer_head *bitmap_bh = NULL;
5300         struct buffer_head *gd_bh;
5301         ext4_group_t block_group;
5302         ext4_grpblk_t bit;
5303         unsigned int i;
5304         struct ext4_group_desc *desc;
5305         struct ext4_sb_info *sbi = EXT4_SB(sb);
5306         struct ext4_buddy e4b;
5307         int err = 0, ret, free_clusters_count;
5308         ext4_grpblk_t clusters_freed;
5309         ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
5310         ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
5311         unsigned long cluster_count = last_cluster - first_cluster + 1;
5312
5313         ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
5314
5315         if (count == 0)
5316                 return 0;
5317
5318         ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5319         /*
5320          * Check to see if we are freeing blocks across a group
5321          * boundary.
5322          */
5323         if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
5324                 ext4_warning(sb, "too many blocks added to group %u",
5325                              block_group);
5326                 err = -EINVAL;
5327                 goto error_return;
5328         }
5329
5330         bitmap_bh = ext4_read_block_bitmap(sb, block_group);
5331         if (IS_ERR(bitmap_bh)) {
5332                 err = PTR_ERR(bitmap_bh);
5333                 bitmap_bh = NULL;
5334                 goto error_return;
5335         }
5336
5337         desc = ext4_get_group_desc(sb, block_group, &gd_bh);
5338         if (!desc) {
5339                 err = -EIO;
5340                 goto error_return;
5341         }
5342
5343         if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
5344             in_range(ext4_inode_bitmap(sb, desc), block, count) ||
5345             in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
5346             in_range(block + count - 1, ext4_inode_table(sb, desc),
5347                      sbi->s_itb_per_group)) {
5348                 ext4_error(sb, "Adding blocks in system zones - "
5349                            "Block = %llu, count = %lu",
5350                            block, count);
5351                 err = -EINVAL;
5352                 goto error_return;
5353         }
5354
5355         BUFFER_TRACE(bitmap_bh, "getting write access");
5356         err = ext4_journal_get_write_access(handle, bitmap_bh);
5357         if (err)
5358                 goto error_return;
5359
5360         /*
5361          * We are about to modify some metadata.  Call the journal APIs
5362          * to unshare ->b_data if a currently-committing transaction is
5363          * using it
5364          */
5365         BUFFER_TRACE(gd_bh, "get_write_access");
5366         err = ext4_journal_get_write_access(handle, gd_bh);
5367         if (err)
5368                 goto error_return;
5369
5370         for (i = 0, clusters_freed = 0; i < cluster_count; i++) {
5371                 BUFFER_TRACE(bitmap_bh, "clear bit");
5372                 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
5373                         ext4_error(sb, "bit already cleared for block %llu",
5374                                    (ext4_fsblk_t)(block + i));
5375                         BUFFER_TRACE(bitmap_bh, "bit already cleared");
5376                 } else {
5377                         clusters_freed++;
5378                 }
5379         }
5380
5381         err = ext4_mb_load_buddy(sb, block_group, &e4b);
5382         if (err)
5383                 goto error_return;
5384
5385         /*
5386          * need to update group_info->bb_free and bitmap
5387          * with group lock held. generate_buddy look at
5388          * them with group lock_held
5389          */
5390         ext4_lock_group(sb, block_group);
5391         mb_clear_bits(bitmap_bh->b_data, bit, cluster_count);
5392         mb_free_blocks(NULL, &e4b, bit, cluster_count);
5393         free_clusters_count = clusters_freed +
5394                 ext4_free_group_clusters(sb, desc);
5395         ext4_free_group_clusters_set(sb, desc, free_clusters_count);
5396         ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
5397         ext4_group_desc_csum_set(sb, block_group, desc);
5398         ext4_unlock_group(sb, block_group);
5399         percpu_counter_add(&sbi->s_freeclusters_counter,
5400                            clusters_freed);
5401
5402         if (sbi->s_log_groups_per_flex) {
5403                 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5404                 atomic64_add(clusters_freed,
5405                              &sbi_array_rcu_deref(sbi, s_flex_groups,
5406                                                   flex_group)->free_clusters);
5407         }
5408
5409         ext4_mb_unload_buddy(&e4b);
5410
5411         /* We dirtied the bitmap block */
5412         BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5413         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5414
5415         /* And the group descriptor block */
5416         BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5417         ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5418         if (!err)
5419                 err = ret;
5420
5421 error_return:
5422         brelse(bitmap_bh);
5423         ext4_std_error(sb, err);
5424         return err;
5425 }
5426
5427 /**
5428  * ext4_trim_extent -- function to TRIM one single free extent in the group
5429  * @sb:         super block for the file system
5430  * @start:      starting block of the free extent in the alloc. group
5431  * @count:      number of blocks to TRIM
5432  * @group:      alloc. group we are working with
5433  * @e4b:        ext4 buddy for the group
5434  *
5435  * Trim "count" blocks starting at "start" in the "group". To assure that no
5436  * one will allocate those blocks, mark it as used in buddy bitmap. This must
5437  * be called with under the group lock.
5438  */
5439 static int ext4_trim_extent(struct super_block *sb, int start, int count,
5440                              ext4_group_t group, struct ext4_buddy *e4b)
5441 __releases(bitlock)
5442 __acquires(bitlock)
5443 {
5444         struct ext4_free_extent ex;
5445         int ret = 0;
5446
5447         trace_ext4_trim_extent(sb, group, start, count);
5448
5449         assert_spin_locked(ext4_group_lock_ptr(sb, group));
5450
5451         ex.fe_start = start;
5452         ex.fe_group = group;
5453         ex.fe_len = count;
5454
5455         /*
5456          * Mark blocks used, so no one can reuse them while
5457          * being trimmed.
5458          */
5459         mb_mark_used(e4b, &ex);
5460         ext4_unlock_group(sb, group);
5461         ret = ext4_issue_discard(sb, group, start, count, NULL);
5462         ext4_lock_group(sb, group);
5463         mb_free_blocks(NULL, e4b, start, ex.fe_len);
5464         return ret;
5465 }
5466
5467 /**
5468  * ext4_trim_all_free -- function to trim all free space in alloc. group
5469  * @sb:                 super block for file system
5470  * @group:              group to be trimmed
5471  * @start:              first group block to examine
5472  * @max:                last group block to examine
5473  * @minblocks:          minimum extent block count
5474  *
5475  * ext4_trim_all_free walks through group's buddy bitmap searching for free
5476  * extents. When the free block is found, ext4_trim_extent is called to TRIM
5477  * the extent.
5478  *
5479  *
5480  * ext4_trim_all_free walks through group's block bitmap searching for free
5481  * extents. When the free extent is found, mark it as used in group buddy
5482  * bitmap. Then issue a TRIM command on this extent and free the extent in
5483  * the group buddy bitmap. This is done until whole group is scanned.
5484  */
5485 static ext4_grpblk_t
5486 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
5487                    ext4_grpblk_t start, ext4_grpblk_t max,
5488                    ext4_grpblk_t minblocks)
5489 {
5490         void *bitmap;
5491         ext4_grpblk_t next, count = 0, free_count = 0;
5492         struct ext4_buddy e4b;
5493         int ret = 0;
5494
5495         trace_ext4_trim_all_free(sb, group, start, max);
5496
5497         ret = ext4_mb_load_buddy(sb, group, &e4b);
5498         if (ret) {
5499                 ext4_warning(sb, "Error %d loading buddy information for %u",
5500                              ret, group);
5501                 return ret;
5502         }
5503         bitmap = e4b.bd_bitmap;
5504
5505         ext4_lock_group(sb, group);
5506         if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
5507             minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
5508                 goto out;
5509
5510         start = (e4b.bd_info->bb_first_free > start) ?
5511                 e4b.bd_info->bb_first_free : start;
5512
5513         while (start <= max) {
5514                 start = mb_find_next_zero_bit(bitmap, max + 1, start);
5515                 if (start > max)
5516                         break;
5517                 next = mb_find_next_bit(bitmap, max + 1, start);
5518
5519                 if ((next - start) >= minblocks) {
5520                         ret = ext4_trim_extent(sb, start,
5521                                                next - start, group, &e4b);
5522                         if (ret && ret != -EOPNOTSUPP)
5523                                 break;
5524                         ret = 0;
5525                         count += next - start;
5526                 }
5527                 free_count += next - start;
5528                 start = next + 1;
5529
5530                 if (fatal_signal_pending(current)) {
5531                         count = -ERESTARTSYS;
5532                         break;
5533                 }
5534
5535                 if (need_resched()) {
5536                         ext4_unlock_group(sb, group);
5537                         cond_resched();
5538                         ext4_lock_group(sb, group);
5539                 }
5540
5541                 if ((e4b.bd_info->bb_free - free_count) < minblocks)
5542                         break;
5543         }
5544
5545         if (!ret) {
5546                 ret = count;
5547                 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
5548         }
5549 out:
5550         ext4_unlock_group(sb, group);
5551         ext4_mb_unload_buddy(&e4b);
5552
5553         ext4_debug("trimmed %d blocks in the group %d\n",
5554                 count, group);
5555
5556         return ret;
5557 }
5558
5559 /**
5560  * ext4_trim_fs() -- trim ioctl handle function
5561  * @sb:                 superblock for filesystem
5562  * @range:              fstrim_range structure
5563  *
5564  * start:       First Byte to trim
5565  * len:         number of Bytes to trim from start
5566  * minlen:      minimum extent length in Bytes
5567  * ext4_trim_fs goes through all allocation groups containing Bytes from
5568  * start to start+len. For each such a group ext4_trim_all_free function
5569  * is invoked to trim all free space.
5570  */
5571 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
5572 {
5573         struct ext4_group_info *grp;
5574         ext4_group_t group, first_group, last_group;
5575         ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5576         uint64_t start, end, minlen, trimmed = 0;
5577         ext4_fsblk_t first_data_blk =
5578                         le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5579         ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
5580         int ret = 0;
5581
5582         start = range->start >> sb->s_blocksize_bits;
5583         end = start + (range->len >> sb->s_blocksize_bits) - 1;
5584         minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5585                               range->minlen >> sb->s_blocksize_bits);
5586
5587         if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
5588             start >= max_blks ||
5589             range->len < sb->s_blocksize)
5590                 return -EINVAL;
5591         if (end >= max_blks)
5592                 end = max_blks - 1;
5593         if (end <= first_data_blk)
5594                 goto out;
5595         if (start < first_data_blk)
5596                 start = first_data_blk;
5597
5598         /* Determine first and last group to examine based on start and end */
5599         ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
5600                                      &first_group, &first_cluster);
5601         ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
5602                                      &last_group, &last_cluster);
5603
5604         /* end now represents the last cluster to discard in this group */
5605         end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5606
5607         for (group = first_group; group <= last_group; group++) {
5608                 grp = ext4_get_group_info(sb, group);
5609                 /* We only do this if the grp has never been initialized */
5610                 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
5611                         ret = ext4_mb_init_group(sb, group, GFP_NOFS);
5612                         if (ret)
5613                                 break;
5614                 }
5615
5616                 /*
5617                  * For all the groups except the last one, last cluster will
5618                  * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
5619                  * change it for the last group, note that last_cluster is
5620                  * already computed earlier by ext4_get_group_no_and_offset()
5621                  */
5622                 if (group == last_group)
5623                         end = last_cluster;
5624
5625                 if (grp->bb_free >= minlen) {
5626                         cnt = ext4_trim_all_free(sb, group, first_cluster,
5627                                                 end, minlen);
5628                         if (cnt < 0) {
5629                                 ret = cnt;
5630                                 break;
5631                         }
5632                         trimmed += cnt;
5633                 }
5634
5635                 /*
5636                  * For every group except the first one, we are sure
5637                  * that the first cluster to discard will be cluster #0.
5638                  */
5639                 first_cluster = 0;
5640         }
5641
5642         if (!ret)
5643                 atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
5644
5645 out:
5646         range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
5647         return ret;
5648 }
5649
5650 /* Iterate all the free extents in the group. */
5651 int
5652 ext4_mballoc_query_range(
5653         struct super_block              *sb,
5654         ext4_group_t                    group,
5655         ext4_grpblk_t                   start,
5656         ext4_grpblk_t                   end,
5657         ext4_mballoc_query_range_fn     formatter,
5658         void                            *priv)
5659 {
5660         void                            *bitmap;
5661         ext4_grpblk_t                   next;
5662         struct ext4_buddy               e4b;
5663         int                             error;
5664
5665         error = ext4_mb_load_buddy(sb, group, &e4b);
5666         if (error)
5667                 return error;
5668         bitmap = e4b.bd_bitmap;
5669
5670         ext4_lock_group(sb, group);
5671
5672         start = (e4b.bd_info->bb_first_free > start) ?
5673                 e4b.bd_info->bb_first_free : start;
5674         if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
5675                 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5676
5677         while (start <= end) {
5678                 start = mb_find_next_zero_bit(bitmap, end + 1, start);
5679                 if (start > end)
5680                         break;
5681                 next = mb_find_next_bit(bitmap, end + 1, start);
5682
5683                 ext4_unlock_group(sb, group);
5684                 error = formatter(sb, group, start, next - start, priv);
5685                 if (error)
5686                         goto out_unload;
5687                 ext4_lock_group(sb, group);
5688
5689                 start = next + 1;
5690         }
5691
5692         ext4_unlock_group(sb, group);
5693 out_unload:
5694         ext4_mb_unload_buddy(&e4b);
5695
5696         return error;
5697 }