xref: /openbmc/linux/fs/ext4/mballoc.c (revision a9ce5993)
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  * smallest multiple of the stripe value (sbi->s_stripe) which is
128  * greater than the default mb_group_prealloc.
129  *
130  * If "mb_optimize_scan" mount option is set, we maintain in memory group info
131  * structures in two data structures:
132  *
133  * 1) Array of largest free order lists (sbi->s_mb_largest_free_orders)
134  *
135  *    Locking: sbi->s_mb_largest_free_orders_locks(array of rw locks)
136  *
137  *    This is an array of lists where the index in the array represents the
138  *    largest free order in the buddy bitmap of the participating group infos of
139  *    that list. So, there are exactly MB_NUM_ORDERS(sb) (which means total
140  *    number of buddy bitmap orders possible) number of lists. Group-infos are
141  *    placed in appropriate lists.
142  *
143  * 2) Average fragment size lists (sbi->s_mb_avg_fragment_size)
144  *
145  *    Locking: sbi->s_mb_avg_fragment_size_locks(array of rw locks)
146  *
147  *    This is an array of lists where in the i-th list there are groups with
148  *    average fragment size >= 2^i and < 2^(i+1). The average fragment size
149  *    is computed as ext4_group_info->bb_free / ext4_group_info->bb_fragments.
150  *    Note that we don't bother with a special list for completely empty groups
151  *    so we only have MB_NUM_ORDERS(sb) lists.
152  *
153  * When "mb_optimize_scan" mount option is set, mballoc consults the above data
154  * structures to decide the order in which groups are to be traversed for
155  * fulfilling an allocation request.
156  *
157  * At CR_POWER2_ALIGNED , we look for groups which have the largest_free_order
158  * >= the order of the request. We directly look at the largest free order list
159  * in the data structure (1) above where largest_free_order = order of the
160  * request. If that list is empty, we look at remaining list in the increasing
161  * order of largest_free_order. This allows us to perform CR_POWER2_ALIGNED
162  * lookup in O(1) time.
163  *
164  * At CR_GOAL_LEN_FAST, we only consider groups where
165  * average fragment size > request size. So, we lookup a group which has average
166  * fragment size just above or equal to request size using our average fragment
167  * size group lists (data structure 2) in O(1) time.
168  *
169  * At CR_BEST_AVAIL_LEN, we aim to optimize allocations which can't be satisfied
170  * in CR_GOAL_LEN_FAST. The fact that we couldn't find a group in
171  * CR_GOAL_LEN_FAST suggests that there is no BG that has avg
172  * fragment size > goal length. So before falling to the slower
173  * CR_GOAL_LEN_SLOW, in CR_BEST_AVAIL_LEN we proactively trim goal length and
174  * then use the same fragment lists as CR_GOAL_LEN_FAST to find a BG with a big
175  * enough average fragment size. This increases the chances of finding a
176  * suitable block group in O(1) time and results in faster allocation at the
177  * cost of reduced size of allocation.
178  *
179  * If "mb_optimize_scan" mount option is not set, mballoc traverses groups in
180  * linear order which requires O(N) search time for each CR_POWER2_ALIGNED and
181  * CR_GOAL_LEN_FAST phase.
182  *
183  * The regular allocator (using the buddy cache) supports a few tunables.
184  *
185  * /sys/fs/ext4/<partition>/mb_min_to_scan
186  * /sys/fs/ext4/<partition>/mb_max_to_scan
187  * /sys/fs/ext4/<partition>/mb_order2_req
188  * /sys/fs/ext4/<partition>/mb_linear_limit
189  *
190  * The regular allocator uses buddy scan only if the request len is power of
191  * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
192  * value of s_mb_order2_reqs can be tuned via
193  * /sys/fs/ext4/<partition>/mb_order2_req.  If the request len is equal to
194  * stripe size (sbi->s_stripe), we try to search for contiguous block in
195  * stripe size. This should result in better allocation on RAID setups. If
196  * not, we search in the specific group using bitmap for best extents. The
197  * tunable min_to_scan and max_to_scan control the behaviour here.
198  * min_to_scan indicate how long the mballoc __must__ look for a best
199  * extent and max_to_scan indicates how long the mballoc __can__ look for a
200  * best extent in the found extents. Searching for the blocks starts with
201  * the group specified as the goal value in allocation context via
202  * ac_g_ex. Each group is first checked based on the criteria whether it
203  * can be used for allocation. ext4_mb_good_group explains how the groups are
204  * checked.
205  *
206  * When "mb_optimize_scan" is turned on, as mentioned above, the groups may not
207  * get traversed linearly. That may result in subsequent allocations being not
208  * close to each other. And so, the underlying device may get filled up in a
209  * non-linear fashion. While that may not matter on non-rotational devices, for
210  * rotational devices that may result in higher seek times. "mb_linear_limit"
211  * tells mballoc how many groups mballoc should search linearly before
212  * performing consulting above data structures for more efficient lookups. For
213  * non rotational devices, this value defaults to 0 and for rotational devices
214  * this is set to MB_DEFAULT_LINEAR_LIMIT.
215  *
216  * Both the prealloc space are getting populated as above. So for the first
217  * request we will hit the buddy cache which will result in this prealloc
218  * space getting filled. The prealloc space is then later used for the
219  * subsequent request.
220  */
221 
222 /*
223  * mballoc operates on the following data:
224  *  - on-disk bitmap
225  *  - in-core buddy (actually includes buddy and bitmap)
226  *  - preallocation descriptors (PAs)
227  *
228  * there are two types of preallocations:
229  *  - inode
230  *    assiged to specific inode and can be used for this inode only.
231  *    it describes part of inode's space preallocated to specific
232  *    physical blocks. any block from that preallocated can be used
233  *    independent. the descriptor just tracks number of blocks left
234  *    unused. so, before taking some block from descriptor, one must
235  *    make sure corresponded logical block isn't allocated yet. this
236  *    also means that freeing any block within descriptor's range
237  *    must discard all preallocated blocks.
238  *  - locality group
239  *    assigned to specific locality group which does not translate to
240  *    permanent set of inodes: inode can join and leave group. space
241  *    from this type of preallocation can be used for any inode. thus
242  *    it's consumed from the beginning to the end.
243  *
244  * relation between them can be expressed as:
245  *    in-core buddy = on-disk bitmap + preallocation descriptors
246  *
247  * this mean blocks mballoc considers used are:
248  *  - allocated blocks (persistent)
249  *  - preallocated blocks (non-persistent)
250  *
251  * consistency in mballoc world means that at any time a block is either
252  * free or used in ALL structures. notice: "any time" should not be read
253  * literally -- time is discrete and delimited by locks.
254  *
255  *  to keep it simple, we don't use block numbers, instead we count number of
256  *  blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
257  *
258  * all operations can be expressed as:
259  *  - init buddy:			buddy = on-disk + PAs
260  *  - new PA:				buddy += N; PA = N
261  *  - use inode PA:			on-disk += N; PA -= N
262  *  - discard inode PA			buddy -= on-disk - PA; PA = 0
263  *  - use locality group PA		on-disk += N; PA -= N
264  *  - discard locality group PA		buddy -= PA; PA = 0
265  *  note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
266  *        is used in real operation because we can't know actual used
267  *        bits from PA, only from on-disk bitmap
268  *
269  * if we follow this strict logic, then all operations above should be atomic.
270  * given some of them can block, we'd have to use something like semaphores
271  * killing performance on high-end SMP hardware. let's try to relax it using
272  * the following knowledge:
273  *  1) if buddy is referenced, it's already initialized
274  *  2) while block is used in buddy and the buddy is referenced,
275  *     nobody can re-allocate that block
276  *  3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
277  *     bit set and PA claims same block, it's OK. IOW, one can set bit in
278  *     on-disk bitmap if buddy has same bit set or/and PA covers corresponded
279  *     block
280  *
281  * so, now we're building a concurrency table:
282  *  - init buddy vs.
283  *    - new PA
284  *      blocks for PA are allocated in the buddy, buddy must be referenced
285  *      until PA is linked to allocation group to avoid concurrent buddy init
286  *    - use inode PA
287  *      we need to make sure that either on-disk bitmap or PA has uptodate data
288  *      given (3) we care that PA-=N operation doesn't interfere with init
289  *    - discard inode PA
290  *      the simplest way would be to have buddy initialized by the discard
291  *    - use locality group PA
292  *      again PA-=N must be serialized with init
293  *    - discard locality group PA
294  *      the simplest way would be to have buddy initialized by the discard
295  *  - new PA vs.
296  *    - use inode PA
297  *      i_data_sem serializes them
298  *    - discard inode PA
299  *      discard process must wait until PA isn't used by another process
300  *    - use locality group PA
301  *      some mutex should serialize them
302  *    - discard locality group PA
303  *      discard process must wait until PA isn't used by another process
304  *  - use inode PA
305  *    - use inode PA
306  *      i_data_sem or another mutex should serializes them
307  *    - discard inode PA
308  *      discard process must wait until PA isn't used by another process
309  *    - use locality group PA
310  *      nothing wrong here -- they're different PAs covering different blocks
311  *    - discard locality group PA
312  *      discard process must wait until PA isn't used by another process
313  *
314  * now we're ready to make few consequences:
315  *  - PA is referenced and while it is no discard is possible
316  *  - PA is referenced until block isn't marked in on-disk bitmap
317  *  - PA changes only after on-disk bitmap
318  *  - discard must not compete with init. either init is done before
319  *    any discard or they're serialized somehow
320  *  - buddy init as sum of on-disk bitmap and PAs is done atomically
321  *
322  * a special case when we've used PA to emptiness. no need to modify buddy
323  * in this case, but we should care about concurrent init
324  *
325  */
326 
327  /*
328  * Logic in few words:
329  *
330  *  - allocation:
331  *    load group
332  *    find blocks
333  *    mark bits in on-disk bitmap
334  *    release group
335  *
336  *  - use preallocation:
337  *    find proper PA (per-inode or group)
338  *    load group
339  *    mark bits in on-disk bitmap
340  *    release group
341  *    release PA
342  *
343  *  - free:
344  *    load group
345  *    mark bits in on-disk bitmap
346  *    release group
347  *
348  *  - discard preallocations in group:
349  *    mark PAs deleted
350  *    move them onto local list
351  *    load on-disk bitmap
352  *    load group
353  *    remove PA from object (inode or locality group)
354  *    mark free blocks in-core
355  *
356  *  - discard inode's preallocations:
357  */
358 
359 /*
360  * Locking rules
361  *
362  * Locks:
363  *  - bitlock on a group	(group)
364  *  - object (inode/locality)	(object)
365  *  - per-pa lock		(pa)
366  *  - cr_power2_aligned lists lock	(cr_power2_aligned)
367  *  - cr_goal_len_fast lists lock	(cr_goal_len_fast)
368  *
369  * Paths:
370  *  - new pa
371  *    object
372  *    group
373  *
374  *  - find and use pa:
375  *    pa
376  *
377  *  - release consumed pa:
378  *    pa
379  *    group
380  *    object
381  *
382  *  - generate in-core bitmap:
383  *    group
384  *        pa
385  *
386  *  - discard all for given object (inode, locality group):
387  *    object
388  *        pa
389  *    group
390  *
391  *  - discard all for given group:
392  *    group
393  *        pa
394  *    group
395  *        object
396  *
397  *  - allocation path (ext4_mb_regular_allocator)
398  *    group
399  *    cr_power2_aligned/cr_goal_len_fast
400  */
401 static struct kmem_cache *ext4_pspace_cachep;
402 static struct kmem_cache *ext4_ac_cachep;
403 static struct kmem_cache *ext4_free_data_cachep;
404 
405 /* We create slab caches for groupinfo data structures based on the
406  * superblock block size.  There will be one per mounted filesystem for
407  * each unique s_blocksize_bits */
408 #define NR_GRPINFO_CACHES 8
409 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
410 
411 static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
412 	"ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
413 	"ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
414 	"ext4_groupinfo_64k", "ext4_groupinfo_128k"
415 };
416 
417 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
418 					ext4_group_t group);
419 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
420 						ext4_group_t group);
421 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac);
422 
423 static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
424 			       ext4_group_t group, enum criteria cr);
425 
426 static int ext4_try_to_trim_range(struct super_block *sb,
427 		struct ext4_buddy *e4b, ext4_grpblk_t start,
428 		ext4_grpblk_t max, ext4_grpblk_t minblocks);
429 
430 /*
431  * The algorithm using this percpu seq counter goes below:
432  * 1. We sample the percpu discard_pa_seq counter before trying for block
433  *    allocation in ext4_mb_new_blocks().
434  * 2. We increment this percpu discard_pa_seq counter when we either allocate
435  *    or free these blocks i.e. while marking those blocks as used/free in
436  *    mb_mark_used()/mb_free_blocks().
437  * 3. We also increment this percpu seq counter when we successfully identify
438  *    that the bb_prealloc_list is not empty and hence proceed for discarding
439  *    of those PAs inside ext4_mb_discard_group_preallocations().
440  *
441  * Now to make sure that the regular fast path of block allocation is not
442  * affected, as a small optimization we only sample the percpu seq counter
443  * on that cpu. Only when the block allocation fails and when freed blocks
444  * found were 0, that is when we sample percpu seq counter for all cpus using
445  * below function ext4_get_discard_pa_seq_sum(). This happens after making
446  * sure that all the PAs on grp->bb_prealloc_list got freed or if it's empty.
447  */
448 static DEFINE_PER_CPU(u64, discard_pa_seq);
449 static inline u64 ext4_get_discard_pa_seq_sum(void)
450 {
451 	int __cpu;
452 	u64 __seq = 0;
453 
454 	for_each_possible_cpu(__cpu)
455 		__seq += per_cpu(discard_pa_seq, __cpu);
456 	return __seq;
457 }
458 
459 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
460 {
461 #if BITS_PER_LONG == 64
462 	*bit += ((unsigned long) addr & 7UL) << 3;
463 	addr = (void *) ((unsigned long) addr & ~7UL);
464 #elif BITS_PER_LONG == 32
465 	*bit += ((unsigned long) addr & 3UL) << 3;
466 	addr = (void *) ((unsigned long) addr & ~3UL);
467 #else
468 #error "how many bits you are?!"
469 #endif
470 	return addr;
471 }
472 
473 static inline int mb_test_bit(int bit, void *addr)
474 {
475 	/*
476 	 * ext4_test_bit on architecture like powerpc
477 	 * needs unsigned long aligned address
478 	 */
479 	addr = mb_correct_addr_and_bit(&bit, addr);
480 	return ext4_test_bit(bit, addr);
481 }
482 
483 static inline void mb_set_bit(int bit, void *addr)
484 {
485 	addr = mb_correct_addr_and_bit(&bit, addr);
486 	ext4_set_bit(bit, addr);
487 }
488 
489 static inline void mb_clear_bit(int bit, void *addr)
490 {
491 	addr = mb_correct_addr_and_bit(&bit, addr);
492 	ext4_clear_bit(bit, addr);
493 }
494 
495 static inline int mb_test_and_clear_bit(int bit, void *addr)
496 {
497 	addr = mb_correct_addr_and_bit(&bit, addr);
498 	return ext4_test_and_clear_bit(bit, addr);
499 }
500 
501 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
502 {
503 	int fix = 0, ret, tmpmax;
504 	addr = mb_correct_addr_and_bit(&fix, addr);
505 	tmpmax = max + fix;
506 	start += fix;
507 
508 	ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
509 	if (ret > max)
510 		return max;
511 	return ret;
512 }
513 
514 static inline int mb_find_next_bit(void *addr, int max, int start)
515 {
516 	int fix = 0, ret, tmpmax;
517 	addr = mb_correct_addr_and_bit(&fix, addr);
518 	tmpmax = max + fix;
519 	start += fix;
520 
521 	ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
522 	if (ret > max)
523 		return max;
524 	return ret;
525 }
526 
527 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
528 {
529 	char *bb;
530 
531 	BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
532 	BUG_ON(max == NULL);
533 
534 	if (order > e4b->bd_blkbits + 1) {
535 		*max = 0;
536 		return NULL;
537 	}
538 
539 	/* at order 0 we see each particular block */
540 	if (order == 0) {
541 		*max = 1 << (e4b->bd_blkbits + 3);
542 		return e4b->bd_bitmap;
543 	}
544 
545 	bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
546 	*max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
547 
548 	return bb;
549 }
550 
551 #ifdef DOUBLE_CHECK
552 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
553 			   int first, int count)
554 {
555 	int i;
556 	struct super_block *sb = e4b->bd_sb;
557 
558 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
559 		return;
560 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
561 	for (i = 0; i < count; i++) {
562 		if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
563 			ext4_fsblk_t blocknr;
564 
565 			blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
566 			blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
567 			ext4_grp_locked_error(sb, e4b->bd_group,
568 					      inode ? inode->i_ino : 0,
569 					      blocknr,
570 					      "freeing block already freed "
571 					      "(bit %u)",
572 					      first + i);
573 			ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
574 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
575 		}
576 		mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
577 	}
578 }
579 
580 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
581 {
582 	int i;
583 
584 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
585 		return;
586 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
587 	for (i = 0; i < count; i++) {
588 		BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
589 		mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
590 	}
591 }
592 
593 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
594 {
595 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
596 		return;
597 	if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
598 		unsigned char *b1, *b2;
599 		int i;
600 		b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
601 		b2 = (unsigned char *) bitmap;
602 		for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
603 			if (b1[i] != b2[i]) {
604 				ext4_msg(e4b->bd_sb, KERN_ERR,
605 					 "corruption in group %u "
606 					 "at byte %u(%u): %x in copy != %x "
607 					 "on disk/prealloc",
608 					 e4b->bd_group, i, i * 8, b1[i], b2[i]);
609 				BUG();
610 			}
611 		}
612 	}
613 }
614 
615 static void mb_group_bb_bitmap_alloc(struct super_block *sb,
616 			struct ext4_group_info *grp, ext4_group_t group)
617 {
618 	struct buffer_head *bh;
619 
620 	grp->bb_bitmap = kmalloc(sb->s_blocksize, GFP_NOFS);
621 	if (!grp->bb_bitmap)
622 		return;
623 
624 	bh = ext4_read_block_bitmap(sb, group);
625 	if (IS_ERR_OR_NULL(bh)) {
626 		kfree(grp->bb_bitmap);
627 		grp->bb_bitmap = NULL;
628 		return;
629 	}
630 
631 	memcpy(grp->bb_bitmap, bh->b_data, sb->s_blocksize);
632 	put_bh(bh);
633 }
634 
635 static void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
636 {
637 	kfree(grp->bb_bitmap);
638 }
639 
640 #else
641 static inline void mb_free_blocks_double(struct inode *inode,
642 				struct ext4_buddy *e4b, int first, int count)
643 {
644 	return;
645 }
646 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
647 						int first, int count)
648 {
649 	return;
650 }
651 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
652 {
653 	return;
654 }
655 
656 static inline void mb_group_bb_bitmap_alloc(struct super_block *sb,
657 			struct ext4_group_info *grp, ext4_group_t group)
658 {
659 	return;
660 }
661 
662 static inline void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
663 {
664 	return;
665 }
666 #endif
667 
668 #ifdef AGGRESSIVE_CHECK
669 
670 #define MB_CHECK_ASSERT(assert)						\
671 do {									\
672 	if (!(assert)) {						\
673 		printk(KERN_EMERG					\
674 			"Assertion failure in %s() at %s:%d: \"%s\"\n",	\
675 			function, file, line, # assert);		\
676 		BUG();							\
677 	}								\
678 } while (0)
679 
680 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
681 				const char *function, int line)
682 {
683 	struct super_block *sb = e4b->bd_sb;
684 	int order = e4b->bd_blkbits + 1;
685 	int max;
686 	int max2;
687 	int i;
688 	int j;
689 	int k;
690 	int count;
691 	struct ext4_group_info *grp;
692 	int fragments = 0;
693 	int fstart;
694 	struct list_head *cur;
695 	void *buddy;
696 	void *buddy2;
697 
698 	if (e4b->bd_info->bb_check_counter++ % 10)
699 		return 0;
700 
701 	while (order > 1) {
702 		buddy = mb_find_buddy(e4b, order, &max);
703 		MB_CHECK_ASSERT(buddy);
704 		buddy2 = mb_find_buddy(e4b, order - 1, &max2);
705 		MB_CHECK_ASSERT(buddy2);
706 		MB_CHECK_ASSERT(buddy != buddy2);
707 		MB_CHECK_ASSERT(max * 2 == max2);
708 
709 		count = 0;
710 		for (i = 0; i < max; i++) {
711 
712 			if (mb_test_bit(i, buddy)) {
713 				/* only single bit in buddy2 may be 0 */
714 				if (!mb_test_bit(i << 1, buddy2)) {
715 					MB_CHECK_ASSERT(
716 						mb_test_bit((i<<1)+1, buddy2));
717 				}
718 				continue;
719 			}
720 
721 			/* both bits in buddy2 must be 1 */
722 			MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
723 			MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
724 
725 			for (j = 0; j < (1 << order); j++) {
726 				k = (i * (1 << order)) + j;
727 				MB_CHECK_ASSERT(
728 					!mb_test_bit(k, e4b->bd_bitmap));
729 			}
730 			count++;
731 		}
732 		MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
733 		order--;
734 	}
735 
736 	fstart = -1;
737 	buddy = mb_find_buddy(e4b, 0, &max);
738 	for (i = 0; i < max; i++) {
739 		if (!mb_test_bit(i, buddy)) {
740 			MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
741 			if (fstart == -1) {
742 				fragments++;
743 				fstart = i;
744 			}
745 			continue;
746 		}
747 		fstart = -1;
748 		/* check used bits only */
749 		for (j = 0; j < e4b->bd_blkbits + 1; j++) {
750 			buddy2 = mb_find_buddy(e4b, j, &max2);
751 			k = i >> j;
752 			MB_CHECK_ASSERT(k < max2);
753 			MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
754 		}
755 	}
756 	MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
757 	MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
758 
759 	grp = ext4_get_group_info(sb, e4b->bd_group);
760 	if (!grp)
761 		return NULL;
762 	list_for_each(cur, &grp->bb_prealloc_list) {
763 		ext4_group_t groupnr;
764 		struct ext4_prealloc_space *pa;
765 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
766 		ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
767 		MB_CHECK_ASSERT(groupnr == e4b->bd_group);
768 		for (i = 0; i < pa->pa_len; i++)
769 			MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
770 	}
771 	return 0;
772 }
773 #undef MB_CHECK_ASSERT
774 #define mb_check_buddy(e4b) __mb_check_buddy(e4b,	\
775 					__FILE__, __func__, __LINE__)
776 #else
777 #define mb_check_buddy(e4b)
778 #endif
779 
780 /*
781  * Divide blocks started from @first with length @len into
782  * smaller chunks with power of 2 blocks.
783  * Clear the bits in bitmap which the blocks of the chunk(s) covered,
784  * then increase bb_counters[] for corresponded chunk size.
785  */
786 static void ext4_mb_mark_free_simple(struct super_block *sb,
787 				void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
788 					struct ext4_group_info *grp)
789 {
790 	struct ext4_sb_info *sbi = EXT4_SB(sb);
791 	ext4_grpblk_t min;
792 	ext4_grpblk_t max;
793 	ext4_grpblk_t chunk;
794 	unsigned int border;
795 
796 	BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
797 
798 	border = 2 << sb->s_blocksize_bits;
799 
800 	while (len > 0) {
801 		/* find how many blocks can be covered since this position */
802 		max = ffs(first | border) - 1;
803 
804 		/* find how many blocks of power 2 we need to mark */
805 		min = fls(len) - 1;
806 
807 		if (max < min)
808 			min = max;
809 		chunk = 1 << min;
810 
811 		/* mark multiblock chunks only */
812 		grp->bb_counters[min]++;
813 		if (min > 0)
814 			mb_clear_bit(first >> min,
815 				     buddy + sbi->s_mb_offsets[min]);
816 
817 		len -= chunk;
818 		first += chunk;
819 	}
820 }
821 
822 static int mb_avg_fragment_size_order(struct super_block *sb, ext4_grpblk_t len)
823 {
824 	int order;
825 
826 	/*
827 	 * We don't bother with a special lists groups with only 1 block free
828 	 * extents and for completely empty groups.
829 	 */
830 	order = fls(len) - 2;
831 	if (order < 0)
832 		return 0;
833 	if (order == MB_NUM_ORDERS(sb))
834 		order--;
835 	return order;
836 }
837 
838 /* Move group to appropriate avg_fragment_size list */
839 static void
840 mb_update_avg_fragment_size(struct super_block *sb, struct ext4_group_info *grp)
841 {
842 	struct ext4_sb_info *sbi = EXT4_SB(sb);
843 	int new_order;
844 
845 	if (!test_opt2(sb, MB_OPTIMIZE_SCAN) || grp->bb_free == 0)
846 		return;
847 
848 	new_order = mb_avg_fragment_size_order(sb,
849 					grp->bb_free / grp->bb_fragments);
850 	if (new_order == grp->bb_avg_fragment_size_order)
851 		return;
852 
853 	if (grp->bb_avg_fragment_size_order != -1) {
854 		write_lock(&sbi->s_mb_avg_fragment_size_locks[
855 					grp->bb_avg_fragment_size_order]);
856 		list_del(&grp->bb_avg_fragment_size_node);
857 		write_unlock(&sbi->s_mb_avg_fragment_size_locks[
858 					grp->bb_avg_fragment_size_order]);
859 	}
860 	grp->bb_avg_fragment_size_order = new_order;
861 	write_lock(&sbi->s_mb_avg_fragment_size_locks[
862 					grp->bb_avg_fragment_size_order]);
863 	list_add_tail(&grp->bb_avg_fragment_size_node,
864 		&sbi->s_mb_avg_fragment_size[grp->bb_avg_fragment_size_order]);
865 	write_unlock(&sbi->s_mb_avg_fragment_size_locks[
866 					grp->bb_avg_fragment_size_order]);
867 }
868 
869 /*
870  * Choose next group by traversing largest_free_order lists. Updates *new_cr if
871  * cr level needs an update.
872  */
873 static void ext4_mb_choose_next_group_p2_aligned(struct ext4_allocation_context *ac,
874 			enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
875 {
876 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
877 	struct ext4_group_info *iter, *grp;
878 	int i;
879 
880 	if (ac->ac_status == AC_STATUS_FOUND)
881 		return;
882 
883 	if (unlikely(sbi->s_mb_stats && ac->ac_flags & EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED))
884 		atomic_inc(&sbi->s_bal_p2_aligned_bad_suggestions);
885 
886 	grp = NULL;
887 	for (i = ac->ac_2order; i < MB_NUM_ORDERS(ac->ac_sb); i++) {
888 		if (list_empty(&sbi->s_mb_largest_free_orders[i]))
889 			continue;
890 		read_lock(&sbi->s_mb_largest_free_orders_locks[i]);
891 		if (list_empty(&sbi->s_mb_largest_free_orders[i])) {
892 			read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
893 			continue;
894 		}
895 		grp = NULL;
896 		list_for_each_entry(iter, &sbi->s_mb_largest_free_orders[i],
897 				    bb_largest_free_order_node) {
898 			if (sbi->s_mb_stats)
899 				atomic64_inc(&sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]);
900 			if (likely(ext4_mb_good_group(ac, iter->bb_group, CR_POWER2_ALIGNED))) {
901 				grp = iter;
902 				break;
903 			}
904 		}
905 		read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
906 		if (grp)
907 			break;
908 	}
909 
910 	if (!grp) {
911 		/* Increment cr and search again */
912 		*new_cr = CR_GOAL_LEN_FAST;
913 	} else {
914 		*group = grp->bb_group;
915 		ac->ac_flags |= EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED;
916 	}
917 }
918 
919 /*
920  * Find a suitable group of given order from the average fragments list.
921  */
922 static struct ext4_group_info *
923 ext4_mb_find_good_group_avg_frag_lists(struct ext4_allocation_context *ac, int order)
924 {
925 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
926 	struct list_head *frag_list = &sbi->s_mb_avg_fragment_size[order];
927 	rwlock_t *frag_list_lock = &sbi->s_mb_avg_fragment_size_locks[order];
928 	struct ext4_group_info *grp = NULL, *iter;
929 	enum criteria cr = ac->ac_criteria;
930 
931 	if (list_empty(frag_list))
932 		return NULL;
933 	read_lock(frag_list_lock);
934 	if (list_empty(frag_list)) {
935 		read_unlock(frag_list_lock);
936 		return NULL;
937 	}
938 	list_for_each_entry(iter, frag_list, bb_avg_fragment_size_node) {
939 		if (sbi->s_mb_stats)
940 			atomic64_inc(&sbi->s_bal_cX_groups_considered[cr]);
941 		if (likely(ext4_mb_good_group(ac, iter->bb_group, cr))) {
942 			grp = iter;
943 			break;
944 		}
945 	}
946 	read_unlock(frag_list_lock);
947 	return grp;
948 }
949 
950 /*
951  * Choose next group by traversing average fragment size list of suitable
952  * order. Updates *new_cr if cr level needs an update.
953  */
954 static void ext4_mb_choose_next_group_goal_fast(struct ext4_allocation_context *ac,
955 		enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
956 {
957 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
958 	struct ext4_group_info *grp = NULL;
959 	int i;
960 
961 	if (unlikely(ac->ac_flags & EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED)) {
962 		if (sbi->s_mb_stats)
963 			atomic_inc(&sbi->s_bal_goal_fast_bad_suggestions);
964 	}
965 
966 	for (i = mb_avg_fragment_size_order(ac->ac_sb, ac->ac_g_ex.fe_len);
967 	     i < MB_NUM_ORDERS(ac->ac_sb); i++) {
968 		grp = ext4_mb_find_good_group_avg_frag_lists(ac, i);
969 		if (grp)
970 			break;
971 	}
972 
973 	if (grp) {
974 		*group = grp->bb_group;
975 		ac->ac_flags |= EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED;
976 	} else {
977 		*new_cr = CR_BEST_AVAIL_LEN;
978 	}
979 }
980 
981 /*
982  * We couldn't find a group in CR_GOAL_LEN_FAST so try to find the highest free fragment
983  * order we have and proactively trim the goal request length to that order to
984  * find a suitable group faster.
985  *
986  * This optimizes allocation speed at the cost of slightly reduced
987  * preallocations. However, we make sure that we don't trim the request too
988  * much and fall to CR_GOAL_LEN_SLOW in that case.
989  */
990 static void ext4_mb_choose_next_group_best_avail(struct ext4_allocation_context *ac,
991 		enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
992 {
993 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
994 	struct ext4_group_info *grp = NULL;
995 	int i, order, min_order;
996 	unsigned long num_stripe_clusters = 0;
997 
998 	if (unlikely(ac->ac_flags & EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED)) {
999 		if (sbi->s_mb_stats)
1000 			atomic_inc(&sbi->s_bal_best_avail_bad_suggestions);
1001 	}
1002 
1003 	/*
1004 	 * mb_avg_fragment_size_order() returns order in a way that makes
1005 	 * retrieving back the length using (1 << order) inaccurate. Hence, use
1006 	 * fls() instead since we need to know the actual length while modifying
1007 	 * goal length.
1008 	 */
1009 	order = fls(ac->ac_g_ex.fe_len) - 1;
1010 	min_order = order - sbi->s_mb_best_avail_max_trim_order;
1011 	if (min_order < 0)
1012 		min_order = 0;
1013 
1014 	if (sbi->s_stripe > 0) {
1015 		/*
1016 		 * We are assuming that stripe size is always a multiple of
1017 		 * cluster ratio otherwise __ext4_fill_super exists early.
1018 		 */
1019 		num_stripe_clusters = EXT4_NUM_B2C(sbi, sbi->s_stripe);
1020 		if (1 << min_order < num_stripe_clusters)
1021 			/*
1022 			 * We consider 1 order less because later we round
1023 			 * up the goal len to num_stripe_clusters
1024 			 */
1025 			min_order = fls(num_stripe_clusters) - 1;
1026 	}
1027 
1028 	if (1 << min_order < ac->ac_o_ex.fe_len)
1029 		min_order = fls(ac->ac_o_ex.fe_len);
1030 
1031 	for (i = order; i >= min_order; i--) {
1032 		int frag_order;
1033 		/*
1034 		 * Scale down goal len to make sure we find something
1035 		 * in the free fragments list. Basically, reduce
1036 		 * preallocations.
1037 		 */
1038 		ac->ac_g_ex.fe_len = 1 << i;
1039 
1040 		if (num_stripe_clusters > 0) {
1041 			/*
1042 			 * Try to round up the adjusted goal length to
1043 			 * stripe size (in cluster units) multiple for
1044 			 * efficiency.
1045 			 */
1046 			ac->ac_g_ex.fe_len = roundup(ac->ac_g_ex.fe_len,
1047 						     num_stripe_clusters);
1048 		}
1049 
1050 		frag_order = mb_avg_fragment_size_order(ac->ac_sb,
1051 							ac->ac_g_ex.fe_len);
1052 
1053 		grp = ext4_mb_find_good_group_avg_frag_lists(ac, frag_order);
1054 		if (grp)
1055 			break;
1056 	}
1057 
1058 	if (grp) {
1059 		*group = grp->bb_group;
1060 		ac->ac_flags |= EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED;
1061 	} else {
1062 		/* Reset goal length to original goal length before falling into CR_GOAL_LEN_SLOW */
1063 		ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
1064 		*new_cr = CR_GOAL_LEN_SLOW;
1065 	}
1066 }
1067 
1068 static inline int should_optimize_scan(struct ext4_allocation_context *ac)
1069 {
1070 	if (unlikely(!test_opt2(ac->ac_sb, MB_OPTIMIZE_SCAN)))
1071 		return 0;
1072 	if (ac->ac_criteria >= CR_GOAL_LEN_SLOW)
1073 		return 0;
1074 	if (!ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS))
1075 		return 0;
1076 	return 1;
1077 }
1078 
1079 /*
1080  * Return next linear group for allocation. If linear traversal should not be
1081  * performed, this function just returns the same group
1082  */
1083 static int
1084 next_linear_group(struct ext4_allocation_context *ac, int group, int ngroups)
1085 {
1086 	if (!should_optimize_scan(ac))
1087 		goto inc_and_return;
1088 
1089 	if (ac->ac_groups_linear_remaining) {
1090 		ac->ac_groups_linear_remaining--;
1091 		goto inc_and_return;
1092 	}
1093 
1094 	return group;
1095 inc_and_return:
1096 	/*
1097 	 * Artificially restricted ngroups for non-extent
1098 	 * files makes group > ngroups possible on first loop.
1099 	 */
1100 	return group + 1 >= ngroups ? 0 : group + 1;
1101 }
1102 
1103 /*
1104  * ext4_mb_choose_next_group: choose next group for allocation.
1105  *
1106  * @ac        Allocation Context
1107  * @new_cr    This is an output parameter. If the there is no good group
1108  *            available at current CR level, this field is updated to indicate
1109  *            the new cr level that should be used.
1110  * @group     This is an input / output parameter. As an input it indicates the
1111  *            next group that the allocator intends to use for allocation. As
1112  *            output, this field indicates the next group that should be used as
1113  *            determined by the optimization functions.
1114  * @ngroups   Total number of groups
1115  */
1116 static void ext4_mb_choose_next_group(struct ext4_allocation_context *ac,
1117 		enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
1118 {
1119 	*new_cr = ac->ac_criteria;
1120 
1121 	if (!should_optimize_scan(ac) || ac->ac_groups_linear_remaining) {
1122 		*group = next_linear_group(ac, *group, ngroups);
1123 		return;
1124 	}
1125 
1126 	if (*new_cr == CR_POWER2_ALIGNED) {
1127 		ext4_mb_choose_next_group_p2_aligned(ac, new_cr, group, ngroups);
1128 	} else if (*new_cr == CR_GOAL_LEN_FAST) {
1129 		ext4_mb_choose_next_group_goal_fast(ac, new_cr, group, ngroups);
1130 	} else if (*new_cr == CR_BEST_AVAIL_LEN) {
1131 		ext4_mb_choose_next_group_best_avail(ac, new_cr, group, ngroups);
1132 	} else {
1133 		/*
1134 		 * TODO: For CR=2, we can arrange groups in an rb tree sorted by
1135 		 * bb_free. But until that happens, we should never come here.
1136 		 */
1137 		WARN_ON(1);
1138 	}
1139 }
1140 
1141 /*
1142  * Cache the order of the largest free extent we have available in this block
1143  * group.
1144  */
1145 static void
1146 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
1147 {
1148 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1149 	int i;
1150 
1151 	for (i = MB_NUM_ORDERS(sb) - 1; i >= 0; i--)
1152 		if (grp->bb_counters[i] > 0)
1153 			break;
1154 	/* No need to move between order lists? */
1155 	if (!test_opt2(sb, MB_OPTIMIZE_SCAN) ||
1156 	    i == grp->bb_largest_free_order) {
1157 		grp->bb_largest_free_order = i;
1158 		return;
1159 	}
1160 
1161 	if (grp->bb_largest_free_order >= 0) {
1162 		write_lock(&sbi->s_mb_largest_free_orders_locks[
1163 					      grp->bb_largest_free_order]);
1164 		list_del_init(&grp->bb_largest_free_order_node);
1165 		write_unlock(&sbi->s_mb_largest_free_orders_locks[
1166 					      grp->bb_largest_free_order]);
1167 	}
1168 	grp->bb_largest_free_order = i;
1169 	if (grp->bb_largest_free_order >= 0 && grp->bb_free) {
1170 		write_lock(&sbi->s_mb_largest_free_orders_locks[
1171 					      grp->bb_largest_free_order]);
1172 		list_add_tail(&grp->bb_largest_free_order_node,
1173 		      &sbi->s_mb_largest_free_orders[grp->bb_largest_free_order]);
1174 		write_unlock(&sbi->s_mb_largest_free_orders_locks[
1175 					      grp->bb_largest_free_order]);
1176 	}
1177 }
1178 
1179 static noinline_for_stack
1180 void ext4_mb_generate_buddy(struct super_block *sb,
1181 			    void *buddy, void *bitmap, ext4_group_t group,
1182 			    struct ext4_group_info *grp)
1183 {
1184 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1185 	ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
1186 	ext4_grpblk_t i = 0;
1187 	ext4_grpblk_t first;
1188 	ext4_grpblk_t len;
1189 	unsigned free = 0;
1190 	unsigned fragments = 0;
1191 	unsigned long long period = get_cycles();
1192 
1193 	/* initialize buddy from bitmap which is aggregation
1194 	 * of on-disk bitmap and preallocations */
1195 	i = mb_find_next_zero_bit(bitmap, max, 0);
1196 	grp->bb_first_free = i;
1197 	while (i < max) {
1198 		fragments++;
1199 		first = i;
1200 		i = mb_find_next_bit(bitmap, max, i);
1201 		len = i - first;
1202 		free += len;
1203 		if (len > 1)
1204 			ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
1205 		else
1206 			grp->bb_counters[0]++;
1207 		if (i < max)
1208 			i = mb_find_next_zero_bit(bitmap, max, i);
1209 	}
1210 	grp->bb_fragments = fragments;
1211 
1212 	if (free != grp->bb_free) {
1213 		ext4_grp_locked_error(sb, group, 0, 0,
1214 				      "block bitmap and bg descriptor "
1215 				      "inconsistent: %u vs %u free clusters",
1216 				      free, grp->bb_free);
1217 		/*
1218 		 * If we intend to continue, we consider group descriptor
1219 		 * corrupt and update bb_free using bitmap value
1220 		 */
1221 		grp->bb_free = free;
1222 		ext4_mark_group_bitmap_corrupted(sb, group,
1223 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1224 	}
1225 	mb_set_largest_free_order(sb, grp);
1226 	mb_update_avg_fragment_size(sb, grp);
1227 
1228 	clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
1229 
1230 	period = get_cycles() - period;
1231 	atomic_inc(&sbi->s_mb_buddies_generated);
1232 	atomic64_add(period, &sbi->s_mb_generation_time);
1233 }
1234 
1235 /* The buddy information is attached the buddy cache inode
1236  * for convenience. The information regarding each group
1237  * is loaded via ext4_mb_load_buddy. The information involve
1238  * block bitmap and buddy information. The information are
1239  * stored in the inode as
1240  *
1241  * {                        page                        }
1242  * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
1243  *
1244  *
1245  * one block each for bitmap and buddy information.
1246  * So for each group we take up 2 blocks. A page can
1247  * contain blocks_per_page (PAGE_SIZE / blocksize)  blocks.
1248  * So it can have information regarding groups_per_page which
1249  * is blocks_per_page/2
1250  *
1251  * Locking note:  This routine takes the block group lock of all groups
1252  * for this page; do not hold this lock when calling this routine!
1253  */
1254 
1255 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
1256 {
1257 	ext4_group_t ngroups;
1258 	int blocksize;
1259 	int blocks_per_page;
1260 	int groups_per_page;
1261 	int err = 0;
1262 	int i;
1263 	ext4_group_t first_group, group;
1264 	int first_block;
1265 	struct super_block *sb;
1266 	struct buffer_head *bhs;
1267 	struct buffer_head **bh = NULL;
1268 	struct inode *inode;
1269 	char *data;
1270 	char *bitmap;
1271 	struct ext4_group_info *grinfo;
1272 
1273 	inode = page->mapping->host;
1274 	sb = inode->i_sb;
1275 	ngroups = ext4_get_groups_count(sb);
1276 	blocksize = i_blocksize(inode);
1277 	blocks_per_page = PAGE_SIZE / blocksize;
1278 
1279 	mb_debug(sb, "init page %lu\n", page->index);
1280 
1281 	groups_per_page = blocks_per_page >> 1;
1282 	if (groups_per_page == 0)
1283 		groups_per_page = 1;
1284 
1285 	/* allocate buffer_heads to read bitmaps */
1286 	if (groups_per_page > 1) {
1287 		i = sizeof(struct buffer_head *) * groups_per_page;
1288 		bh = kzalloc(i, gfp);
1289 		if (bh == NULL)
1290 			return -ENOMEM;
1291 	} else
1292 		bh = &bhs;
1293 
1294 	first_group = page->index * blocks_per_page / 2;
1295 
1296 	/* read all groups the page covers into the cache */
1297 	for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1298 		if (group >= ngroups)
1299 			break;
1300 
1301 		grinfo = ext4_get_group_info(sb, group);
1302 		if (!grinfo)
1303 			continue;
1304 		/*
1305 		 * If page is uptodate then we came here after online resize
1306 		 * which added some new uninitialized group info structs, so
1307 		 * we must skip all initialized uptodate buddies on the page,
1308 		 * which may be currently in use by an allocating task.
1309 		 */
1310 		if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
1311 			bh[i] = NULL;
1312 			continue;
1313 		}
1314 		bh[i] = ext4_read_block_bitmap_nowait(sb, group, false);
1315 		if (IS_ERR(bh[i])) {
1316 			err = PTR_ERR(bh[i]);
1317 			bh[i] = NULL;
1318 			goto out;
1319 		}
1320 		mb_debug(sb, "read bitmap for group %u\n", group);
1321 	}
1322 
1323 	/* wait for I/O completion */
1324 	for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1325 		int err2;
1326 
1327 		if (!bh[i])
1328 			continue;
1329 		err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
1330 		if (!err)
1331 			err = err2;
1332 	}
1333 
1334 	first_block = page->index * blocks_per_page;
1335 	for (i = 0; i < blocks_per_page; i++) {
1336 		group = (first_block + i) >> 1;
1337 		if (group >= ngroups)
1338 			break;
1339 
1340 		if (!bh[group - first_group])
1341 			/* skip initialized uptodate buddy */
1342 			continue;
1343 
1344 		if (!buffer_verified(bh[group - first_group]))
1345 			/* Skip faulty bitmaps */
1346 			continue;
1347 		err = 0;
1348 
1349 		/*
1350 		 * data carry information regarding this
1351 		 * particular group in the format specified
1352 		 * above
1353 		 *
1354 		 */
1355 		data = page_address(page) + (i * blocksize);
1356 		bitmap = bh[group - first_group]->b_data;
1357 
1358 		/*
1359 		 * We place the buddy block and bitmap block
1360 		 * close together
1361 		 */
1362 		if ((first_block + i) & 1) {
1363 			/* this is block of buddy */
1364 			BUG_ON(incore == NULL);
1365 			mb_debug(sb, "put buddy for group %u in page %lu/%x\n",
1366 				group, page->index, i * blocksize);
1367 			trace_ext4_mb_buddy_bitmap_load(sb, group);
1368 			grinfo = ext4_get_group_info(sb, group);
1369 			if (!grinfo) {
1370 				err = -EFSCORRUPTED;
1371 				goto out;
1372 			}
1373 			grinfo->bb_fragments = 0;
1374 			memset(grinfo->bb_counters, 0,
1375 			       sizeof(*grinfo->bb_counters) *
1376 			       (MB_NUM_ORDERS(sb)));
1377 			/*
1378 			 * incore got set to the group block bitmap below
1379 			 */
1380 			ext4_lock_group(sb, group);
1381 			/* init the buddy */
1382 			memset(data, 0xff, blocksize);
1383 			ext4_mb_generate_buddy(sb, data, incore, group, grinfo);
1384 			ext4_unlock_group(sb, group);
1385 			incore = NULL;
1386 		} else {
1387 			/* this is block of bitmap */
1388 			BUG_ON(incore != NULL);
1389 			mb_debug(sb, "put bitmap for group %u in page %lu/%x\n",
1390 				group, page->index, i * blocksize);
1391 			trace_ext4_mb_bitmap_load(sb, group);
1392 
1393 			/* see comments in ext4_mb_put_pa() */
1394 			ext4_lock_group(sb, group);
1395 			memcpy(data, bitmap, blocksize);
1396 
1397 			/* mark all preallocated blks used in in-core bitmap */
1398 			ext4_mb_generate_from_pa(sb, data, group);
1399 			ext4_mb_generate_from_freelist(sb, data, group);
1400 			ext4_unlock_group(sb, group);
1401 
1402 			/* set incore so that the buddy information can be
1403 			 * generated using this
1404 			 */
1405 			incore = data;
1406 		}
1407 	}
1408 	SetPageUptodate(page);
1409 
1410 out:
1411 	if (bh) {
1412 		for (i = 0; i < groups_per_page; i++)
1413 			brelse(bh[i]);
1414 		if (bh != &bhs)
1415 			kfree(bh);
1416 	}
1417 	return err;
1418 }
1419 
1420 /*
1421  * Lock the buddy and bitmap pages. This make sure other parallel init_group
1422  * on the same buddy page doesn't happen whild holding the buddy page lock.
1423  * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
1424  * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
1425  */
1426 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
1427 		ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
1428 {
1429 	struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
1430 	int block, pnum, poff;
1431 	int blocks_per_page;
1432 	struct page *page;
1433 
1434 	e4b->bd_buddy_page = NULL;
1435 	e4b->bd_bitmap_page = NULL;
1436 
1437 	blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1438 	/*
1439 	 * the buddy cache inode stores the block bitmap
1440 	 * and buddy information in consecutive blocks.
1441 	 * So for each group we need two blocks.
1442 	 */
1443 	block = group * 2;
1444 	pnum = block / blocks_per_page;
1445 	poff = block % blocks_per_page;
1446 	page = find_or_create_page(inode->i_mapping, pnum, gfp);
1447 	if (!page)
1448 		return -ENOMEM;
1449 	BUG_ON(page->mapping != inode->i_mapping);
1450 	e4b->bd_bitmap_page = page;
1451 	e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1452 
1453 	if (blocks_per_page >= 2) {
1454 		/* buddy and bitmap are on the same page */
1455 		return 0;
1456 	}
1457 
1458 	block++;
1459 	pnum = block / blocks_per_page;
1460 	page = find_or_create_page(inode->i_mapping, pnum, gfp);
1461 	if (!page)
1462 		return -ENOMEM;
1463 	BUG_ON(page->mapping != inode->i_mapping);
1464 	e4b->bd_buddy_page = page;
1465 	return 0;
1466 }
1467 
1468 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1469 {
1470 	if (e4b->bd_bitmap_page) {
1471 		unlock_page(e4b->bd_bitmap_page);
1472 		put_page(e4b->bd_bitmap_page);
1473 	}
1474 	if (e4b->bd_buddy_page) {
1475 		unlock_page(e4b->bd_buddy_page);
1476 		put_page(e4b->bd_buddy_page);
1477 	}
1478 }
1479 
1480 /*
1481  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
1482  * block group lock of all groups for this page; do not hold the BG lock when
1483  * calling this routine!
1484  */
1485 static noinline_for_stack
1486 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1487 {
1488 
1489 	struct ext4_group_info *this_grp;
1490 	struct ext4_buddy e4b;
1491 	struct page *page;
1492 	int ret = 0;
1493 
1494 	might_sleep();
1495 	mb_debug(sb, "init group %u\n", group);
1496 	this_grp = ext4_get_group_info(sb, group);
1497 	if (!this_grp)
1498 		return -EFSCORRUPTED;
1499 
1500 	/*
1501 	 * This ensures that we don't reinit the buddy cache
1502 	 * page which map to the group from which we are already
1503 	 * allocating. If we are looking at the buddy cache we would
1504 	 * have taken a reference using ext4_mb_load_buddy and that
1505 	 * would have pinned buddy page to page cache.
1506 	 * The call to ext4_mb_get_buddy_page_lock will mark the
1507 	 * page accessed.
1508 	 */
1509 	ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1510 	if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1511 		/*
1512 		 * somebody initialized the group
1513 		 * return without doing anything
1514 		 */
1515 		goto err;
1516 	}
1517 
1518 	page = e4b.bd_bitmap_page;
1519 	ret = ext4_mb_init_cache(page, NULL, gfp);
1520 	if (ret)
1521 		goto err;
1522 	if (!PageUptodate(page)) {
1523 		ret = -EIO;
1524 		goto err;
1525 	}
1526 
1527 	if (e4b.bd_buddy_page == NULL) {
1528 		/*
1529 		 * If both the bitmap and buddy are in
1530 		 * the same page we don't need to force
1531 		 * init the buddy
1532 		 */
1533 		ret = 0;
1534 		goto err;
1535 	}
1536 	/* init buddy cache */
1537 	page = e4b.bd_buddy_page;
1538 	ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1539 	if (ret)
1540 		goto err;
1541 	if (!PageUptodate(page)) {
1542 		ret = -EIO;
1543 		goto err;
1544 	}
1545 err:
1546 	ext4_mb_put_buddy_page_lock(&e4b);
1547 	return ret;
1548 }
1549 
1550 /*
1551  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
1552  * block group lock of all groups for this page; do not hold the BG lock when
1553  * calling this routine!
1554  */
1555 static noinline_for_stack int
1556 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1557 		       struct ext4_buddy *e4b, gfp_t gfp)
1558 {
1559 	int blocks_per_page;
1560 	int block;
1561 	int pnum;
1562 	int poff;
1563 	struct page *page;
1564 	int ret;
1565 	struct ext4_group_info *grp;
1566 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1567 	struct inode *inode = sbi->s_buddy_cache;
1568 
1569 	might_sleep();
1570 	mb_debug(sb, "load group %u\n", group);
1571 
1572 	blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1573 	grp = ext4_get_group_info(sb, group);
1574 	if (!grp)
1575 		return -EFSCORRUPTED;
1576 
1577 	e4b->bd_blkbits = sb->s_blocksize_bits;
1578 	e4b->bd_info = grp;
1579 	e4b->bd_sb = sb;
1580 	e4b->bd_group = group;
1581 	e4b->bd_buddy_page = NULL;
1582 	e4b->bd_bitmap_page = NULL;
1583 
1584 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1585 		/*
1586 		 * we need full data about the group
1587 		 * to make a good selection
1588 		 */
1589 		ret = ext4_mb_init_group(sb, group, gfp);
1590 		if (ret)
1591 			return ret;
1592 	}
1593 
1594 	/*
1595 	 * the buddy cache inode stores the block bitmap
1596 	 * and buddy information in consecutive blocks.
1597 	 * So for each group we need two blocks.
1598 	 */
1599 	block = group * 2;
1600 	pnum = block / blocks_per_page;
1601 	poff = block % blocks_per_page;
1602 
1603 	/* we could use find_or_create_page(), but it locks page
1604 	 * what we'd like to avoid in fast path ... */
1605 	page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1606 	if (page == NULL || !PageUptodate(page)) {
1607 		if (page)
1608 			/*
1609 			 * drop the page reference and try
1610 			 * to get the page with lock. If we
1611 			 * are not uptodate that implies
1612 			 * somebody just created the page but
1613 			 * is yet to initialize the same. So
1614 			 * wait for it to initialize.
1615 			 */
1616 			put_page(page);
1617 		page = find_or_create_page(inode->i_mapping, pnum, gfp);
1618 		if (page) {
1619 			if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
1620 	"ext4: bitmap's paging->mapping != inode->i_mapping\n")) {
1621 				/* should never happen */
1622 				unlock_page(page);
1623 				ret = -EINVAL;
1624 				goto err;
1625 			}
1626 			if (!PageUptodate(page)) {
1627 				ret = ext4_mb_init_cache(page, NULL, gfp);
1628 				if (ret) {
1629 					unlock_page(page);
1630 					goto err;
1631 				}
1632 				mb_cmp_bitmaps(e4b, page_address(page) +
1633 					       (poff * sb->s_blocksize));
1634 			}
1635 			unlock_page(page);
1636 		}
1637 	}
1638 	if (page == NULL) {
1639 		ret = -ENOMEM;
1640 		goto err;
1641 	}
1642 	if (!PageUptodate(page)) {
1643 		ret = -EIO;
1644 		goto err;
1645 	}
1646 
1647 	/* Pages marked accessed already */
1648 	e4b->bd_bitmap_page = page;
1649 	e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1650 
1651 	block++;
1652 	pnum = block / blocks_per_page;
1653 	poff = block % blocks_per_page;
1654 
1655 	page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1656 	if (page == NULL || !PageUptodate(page)) {
1657 		if (page)
1658 			put_page(page);
1659 		page = find_or_create_page(inode->i_mapping, pnum, gfp);
1660 		if (page) {
1661 			if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
1662 	"ext4: buddy bitmap's page->mapping != inode->i_mapping\n")) {
1663 				/* should never happen */
1664 				unlock_page(page);
1665 				ret = -EINVAL;
1666 				goto err;
1667 			}
1668 			if (!PageUptodate(page)) {
1669 				ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1670 							 gfp);
1671 				if (ret) {
1672 					unlock_page(page);
1673 					goto err;
1674 				}
1675 			}
1676 			unlock_page(page);
1677 		}
1678 	}
1679 	if (page == NULL) {
1680 		ret = -ENOMEM;
1681 		goto err;
1682 	}
1683 	if (!PageUptodate(page)) {
1684 		ret = -EIO;
1685 		goto err;
1686 	}
1687 
1688 	/* Pages marked accessed already */
1689 	e4b->bd_buddy_page = page;
1690 	e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1691 
1692 	return 0;
1693 
1694 err:
1695 	if (page)
1696 		put_page(page);
1697 	if (e4b->bd_bitmap_page)
1698 		put_page(e4b->bd_bitmap_page);
1699 
1700 	e4b->bd_buddy = NULL;
1701 	e4b->bd_bitmap = NULL;
1702 	return ret;
1703 }
1704 
1705 static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1706 			      struct ext4_buddy *e4b)
1707 {
1708 	return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1709 }
1710 
1711 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1712 {
1713 	if (e4b->bd_bitmap_page)
1714 		put_page(e4b->bd_bitmap_page);
1715 	if (e4b->bd_buddy_page)
1716 		put_page(e4b->bd_buddy_page);
1717 }
1718 
1719 
1720 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1721 {
1722 	int order = 1, max;
1723 	void *bb;
1724 
1725 	BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1726 	BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1727 
1728 	while (order <= e4b->bd_blkbits + 1) {
1729 		bb = mb_find_buddy(e4b, order, &max);
1730 		if (!mb_test_bit(block >> order, bb)) {
1731 			/* this block is part of buddy of order 'order' */
1732 			return order;
1733 		}
1734 		order++;
1735 	}
1736 	return 0;
1737 }
1738 
1739 static void mb_clear_bits(void *bm, int cur, int len)
1740 {
1741 	__u32 *addr;
1742 
1743 	len = cur + len;
1744 	while (cur < len) {
1745 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1746 			/* fast path: clear whole word at once */
1747 			addr = bm + (cur >> 3);
1748 			*addr = 0;
1749 			cur += 32;
1750 			continue;
1751 		}
1752 		mb_clear_bit(cur, bm);
1753 		cur++;
1754 	}
1755 }
1756 
1757 /* clear bits in given range
1758  * will return first found zero bit if any, -1 otherwise
1759  */
1760 static int mb_test_and_clear_bits(void *bm, int cur, int len)
1761 {
1762 	__u32 *addr;
1763 	int zero_bit = -1;
1764 
1765 	len = cur + len;
1766 	while (cur < len) {
1767 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1768 			/* fast path: clear whole word at once */
1769 			addr = bm + (cur >> 3);
1770 			if (*addr != (__u32)(-1) && zero_bit == -1)
1771 				zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1772 			*addr = 0;
1773 			cur += 32;
1774 			continue;
1775 		}
1776 		if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1777 			zero_bit = cur;
1778 		cur++;
1779 	}
1780 
1781 	return zero_bit;
1782 }
1783 
1784 void mb_set_bits(void *bm, int cur, int len)
1785 {
1786 	__u32 *addr;
1787 
1788 	len = cur + len;
1789 	while (cur < len) {
1790 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1791 			/* fast path: set whole word at once */
1792 			addr = bm + (cur >> 3);
1793 			*addr = 0xffffffff;
1794 			cur += 32;
1795 			continue;
1796 		}
1797 		mb_set_bit(cur, bm);
1798 		cur++;
1799 	}
1800 }
1801 
1802 static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1803 {
1804 	if (mb_test_bit(*bit + side, bitmap)) {
1805 		mb_clear_bit(*bit, bitmap);
1806 		(*bit) -= side;
1807 		return 1;
1808 	}
1809 	else {
1810 		(*bit) += side;
1811 		mb_set_bit(*bit, bitmap);
1812 		return -1;
1813 	}
1814 }
1815 
1816 static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1817 {
1818 	int max;
1819 	int order = 1;
1820 	void *buddy = mb_find_buddy(e4b, order, &max);
1821 
1822 	while (buddy) {
1823 		void *buddy2;
1824 
1825 		/* Bits in range [first; last] are known to be set since
1826 		 * corresponding blocks were allocated. Bits in range
1827 		 * (first; last) will stay set because they form buddies on
1828 		 * upper layer. We just deal with borders if they don't
1829 		 * align with upper layer and then go up.
1830 		 * Releasing entire group is all about clearing
1831 		 * single bit of highest order buddy.
1832 		 */
1833 
1834 		/* Example:
1835 		 * ---------------------------------
1836 		 * |   1   |   1   |   1   |   1   |
1837 		 * ---------------------------------
1838 		 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1839 		 * ---------------------------------
1840 		 *   0   1   2   3   4   5   6   7
1841 		 *      \_____________________/
1842 		 *
1843 		 * Neither [1] nor [6] is aligned to above layer.
1844 		 * Left neighbour [0] is free, so mark it busy,
1845 		 * decrease bb_counters and extend range to
1846 		 * [0; 6]
1847 		 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1848 		 * mark [6] free, increase bb_counters and shrink range to
1849 		 * [0; 5].
1850 		 * Then shift range to [0; 2], go up and do the same.
1851 		 */
1852 
1853 
1854 		if (first & 1)
1855 			e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1856 		if (!(last & 1))
1857 			e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1858 		if (first > last)
1859 			break;
1860 		order++;
1861 
1862 		buddy2 = mb_find_buddy(e4b, order, &max);
1863 		if (!buddy2) {
1864 			mb_clear_bits(buddy, first, last - first + 1);
1865 			e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1866 			break;
1867 		}
1868 		first >>= 1;
1869 		last >>= 1;
1870 		buddy = buddy2;
1871 	}
1872 }
1873 
1874 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1875 			   int first, int count)
1876 {
1877 	int left_is_free = 0;
1878 	int right_is_free = 0;
1879 	int block;
1880 	int last = first + count - 1;
1881 	struct super_block *sb = e4b->bd_sb;
1882 
1883 	if (WARN_ON(count == 0))
1884 		return;
1885 	BUG_ON(last >= (sb->s_blocksize << 3));
1886 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1887 	/* Don't bother if the block group is corrupt. */
1888 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1889 		return;
1890 
1891 	mb_check_buddy(e4b);
1892 	mb_free_blocks_double(inode, e4b, first, count);
1893 
1894 	this_cpu_inc(discard_pa_seq);
1895 	e4b->bd_info->bb_free += count;
1896 	if (first < e4b->bd_info->bb_first_free)
1897 		e4b->bd_info->bb_first_free = first;
1898 
1899 	/* access memory sequentially: check left neighbour,
1900 	 * clear range and then check right neighbour
1901 	 */
1902 	if (first != 0)
1903 		left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1904 	block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1905 	if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1906 		right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1907 
1908 	if (unlikely(block != -1)) {
1909 		struct ext4_sb_info *sbi = EXT4_SB(sb);
1910 		ext4_fsblk_t blocknr;
1911 
1912 		blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1913 		blocknr += EXT4_C2B(sbi, block);
1914 		if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
1915 			ext4_grp_locked_error(sb, e4b->bd_group,
1916 					      inode ? inode->i_ino : 0,
1917 					      blocknr,
1918 					      "freeing already freed block (bit %u); block bitmap corrupt.",
1919 					      block);
1920 			ext4_mark_group_bitmap_corrupted(
1921 				sb, e4b->bd_group,
1922 				EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1923 		}
1924 		goto done;
1925 	}
1926 
1927 	/* let's maintain fragments counter */
1928 	if (left_is_free && right_is_free)
1929 		e4b->bd_info->bb_fragments--;
1930 	else if (!left_is_free && !right_is_free)
1931 		e4b->bd_info->bb_fragments++;
1932 
1933 	/* buddy[0] == bd_bitmap is a special case, so handle
1934 	 * it right away and let mb_buddy_mark_free stay free of
1935 	 * zero order checks.
1936 	 * Check if neighbours are to be coaleasced,
1937 	 * adjust bitmap bb_counters and borders appropriately.
1938 	 */
1939 	if (first & 1) {
1940 		first += !left_is_free;
1941 		e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1942 	}
1943 	if (!(last & 1)) {
1944 		last -= !right_is_free;
1945 		e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1946 	}
1947 
1948 	if (first <= last)
1949 		mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1950 
1951 done:
1952 	mb_set_largest_free_order(sb, e4b->bd_info);
1953 	mb_update_avg_fragment_size(sb, e4b->bd_info);
1954 	mb_check_buddy(e4b);
1955 }
1956 
1957 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1958 				int needed, struct ext4_free_extent *ex)
1959 {
1960 	int next = block;
1961 	int max, order;
1962 	void *buddy;
1963 
1964 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1965 	BUG_ON(ex == NULL);
1966 
1967 	buddy = mb_find_buddy(e4b, 0, &max);
1968 	BUG_ON(buddy == NULL);
1969 	BUG_ON(block >= max);
1970 	if (mb_test_bit(block, buddy)) {
1971 		ex->fe_len = 0;
1972 		ex->fe_start = 0;
1973 		ex->fe_group = 0;
1974 		return 0;
1975 	}
1976 
1977 	/* find actual order */
1978 	order = mb_find_order_for_block(e4b, block);
1979 	block = block >> order;
1980 
1981 	ex->fe_len = 1 << order;
1982 	ex->fe_start = block << order;
1983 	ex->fe_group = e4b->bd_group;
1984 
1985 	/* calc difference from given start */
1986 	next = next - ex->fe_start;
1987 	ex->fe_len -= next;
1988 	ex->fe_start += next;
1989 
1990 	while (needed > ex->fe_len &&
1991 	       mb_find_buddy(e4b, order, &max)) {
1992 
1993 		if (block + 1 >= max)
1994 			break;
1995 
1996 		next = (block + 1) * (1 << order);
1997 		if (mb_test_bit(next, e4b->bd_bitmap))
1998 			break;
1999 
2000 		order = mb_find_order_for_block(e4b, next);
2001 
2002 		block = next >> order;
2003 		ex->fe_len += 1 << order;
2004 	}
2005 
2006 	if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
2007 		/* Should never happen! (but apparently sometimes does?!?) */
2008 		WARN_ON(1);
2009 		ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
2010 			"corruption or bug in mb_find_extent "
2011 			"block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
2012 			block, order, needed, ex->fe_group, ex->fe_start,
2013 			ex->fe_len, ex->fe_logical);
2014 		ex->fe_len = 0;
2015 		ex->fe_start = 0;
2016 		ex->fe_group = 0;
2017 	}
2018 	return ex->fe_len;
2019 }
2020 
2021 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
2022 {
2023 	int ord;
2024 	int mlen = 0;
2025 	int max = 0;
2026 	int cur;
2027 	int start = ex->fe_start;
2028 	int len = ex->fe_len;
2029 	unsigned ret = 0;
2030 	int len0 = len;
2031 	void *buddy;
2032 	bool split = false;
2033 
2034 	BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
2035 	BUG_ON(e4b->bd_group != ex->fe_group);
2036 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
2037 	mb_check_buddy(e4b);
2038 	mb_mark_used_double(e4b, start, len);
2039 
2040 	this_cpu_inc(discard_pa_seq);
2041 	e4b->bd_info->bb_free -= len;
2042 	if (e4b->bd_info->bb_first_free == start)
2043 		e4b->bd_info->bb_first_free += len;
2044 
2045 	/* let's maintain fragments counter */
2046 	if (start != 0)
2047 		mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
2048 	if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
2049 		max = !mb_test_bit(start + len, e4b->bd_bitmap);
2050 	if (mlen && max)
2051 		e4b->bd_info->bb_fragments++;
2052 	else if (!mlen && !max)
2053 		e4b->bd_info->bb_fragments--;
2054 
2055 	/* let's maintain buddy itself */
2056 	while (len) {
2057 		if (!split)
2058 			ord = mb_find_order_for_block(e4b, start);
2059 
2060 		if (((start >> ord) << ord) == start && len >= (1 << ord)) {
2061 			/* the whole chunk may be allocated at once! */
2062 			mlen = 1 << ord;
2063 			if (!split)
2064 				buddy = mb_find_buddy(e4b, ord, &max);
2065 			else
2066 				split = false;
2067 			BUG_ON((start >> ord) >= max);
2068 			mb_set_bit(start >> ord, buddy);
2069 			e4b->bd_info->bb_counters[ord]--;
2070 			start += mlen;
2071 			len -= mlen;
2072 			BUG_ON(len < 0);
2073 			continue;
2074 		}
2075 
2076 		/* store for history */
2077 		if (ret == 0)
2078 			ret = len | (ord << 16);
2079 
2080 		/* we have to split large buddy */
2081 		BUG_ON(ord <= 0);
2082 		buddy = mb_find_buddy(e4b, ord, &max);
2083 		mb_set_bit(start >> ord, buddy);
2084 		e4b->bd_info->bb_counters[ord]--;
2085 
2086 		ord--;
2087 		cur = (start >> ord) & ~1U;
2088 		buddy = mb_find_buddy(e4b, ord, &max);
2089 		mb_clear_bit(cur, buddy);
2090 		mb_clear_bit(cur + 1, buddy);
2091 		e4b->bd_info->bb_counters[ord]++;
2092 		e4b->bd_info->bb_counters[ord]++;
2093 		split = true;
2094 	}
2095 	mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
2096 
2097 	mb_update_avg_fragment_size(e4b->bd_sb, e4b->bd_info);
2098 	mb_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
2099 	mb_check_buddy(e4b);
2100 
2101 	return ret;
2102 }
2103 
2104 /*
2105  * Must be called under group lock!
2106  */
2107 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
2108 					struct ext4_buddy *e4b)
2109 {
2110 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2111 	int ret;
2112 
2113 	BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
2114 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2115 
2116 	ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
2117 	ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
2118 	ret = mb_mark_used(e4b, &ac->ac_b_ex);
2119 
2120 	/* preallocation can change ac_b_ex, thus we store actually
2121 	 * allocated blocks for history */
2122 	ac->ac_f_ex = ac->ac_b_ex;
2123 
2124 	ac->ac_status = AC_STATUS_FOUND;
2125 	ac->ac_tail = ret & 0xffff;
2126 	ac->ac_buddy = ret >> 16;
2127 
2128 	/*
2129 	 * take the page reference. We want the page to be pinned
2130 	 * so that we don't get a ext4_mb_init_cache_call for this
2131 	 * group until we update the bitmap. That would mean we
2132 	 * double allocate blocks. The reference is dropped
2133 	 * in ext4_mb_release_context
2134 	 */
2135 	ac->ac_bitmap_page = e4b->bd_bitmap_page;
2136 	get_page(ac->ac_bitmap_page);
2137 	ac->ac_buddy_page = e4b->bd_buddy_page;
2138 	get_page(ac->ac_buddy_page);
2139 	/* store last allocated for subsequent stream allocation */
2140 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2141 		spin_lock(&sbi->s_md_lock);
2142 		sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
2143 		sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
2144 		spin_unlock(&sbi->s_md_lock);
2145 	}
2146 	/*
2147 	 * As we've just preallocated more space than
2148 	 * user requested originally, we store allocated
2149 	 * space in a special descriptor.
2150 	 */
2151 	if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
2152 		ext4_mb_new_preallocation(ac);
2153 
2154 }
2155 
2156 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
2157 					struct ext4_buddy *e4b,
2158 					int finish_group)
2159 {
2160 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2161 	struct ext4_free_extent *bex = &ac->ac_b_ex;
2162 	struct ext4_free_extent *gex = &ac->ac_g_ex;
2163 
2164 	if (ac->ac_status == AC_STATUS_FOUND)
2165 		return;
2166 	/*
2167 	 * We don't want to scan for a whole year
2168 	 */
2169 	if (ac->ac_found > sbi->s_mb_max_to_scan &&
2170 			!(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2171 		ac->ac_status = AC_STATUS_BREAK;
2172 		return;
2173 	}
2174 
2175 	/*
2176 	 * Haven't found good chunk so far, let's continue
2177 	 */
2178 	if (bex->fe_len < gex->fe_len)
2179 		return;
2180 
2181 	if (finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
2182 		ext4_mb_use_best_found(ac, e4b);
2183 }
2184 
2185 /*
2186  * The routine checks whether found extent is good enough. If it is,
2187  * then the extent gets marked used and flag is set to the context
2188  * to stop scanning. Otherwise, the extent is compared with the
2189  * previous found extent and if new one is better, then it's stored
2190  * in the context. Later, the best found extent will be used, if
2191  * mballoc can't find good enough extent.
2192  *
2193  * The algorithm used is roughly as follows:
2194  *
2195  * * If free extent found is exactly as big as goal, then
2196  *   stop the scan and use it immediately
2197  *
2198  * * If free extent found is smaller than goal, then keep retrying
2199  *   upto a max of sbi->s_mb_max_to_scan times (default 200). After
2200  *   that stop scanning and use whatever we have.
2201  *
2202  * * If free extent found is bigger than goal, then keep retrying
2203  *   upto a max of sbi->s_mb_min_to_scan times (default 10) before
2204  *   stopping the scan and using the extent.
2205  *
2206  *
2207  * FIXME: real allocation policy is to be designed yet!
2208  */
2209 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
2210 					struct ext4_free_extent *ex,
2211 					struct ext4_buddy *e4b)
2212 {
2213 	struct ext4_free_extent *bex = &ac->ac_b_ex;
2214 	struct ext4_free_extent *gex = &ac->ac_g_ex;
2215 
2216 	BUG_ON(ex->fe_len <= 0);
2217 	BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2218 	BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2219 	BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
2220 
2221 	ac->ac_found++;
2222 	ac->ac_cX_found[ac->ac_criteria]++;
2223 
2224 	/*
2225 	 * The special case - take what you catch first
2226 	 */
2227 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2228 		*bex = *ex;
2229 		ext4_mb_use_best_found(ac, e4b);
2230 		return;
2231 	}
2232 
2233 	/*
2234 	 * Let's check whether the chuck is good enough
2235 	 */
2236 	if (ex->fe_len == gex->fe_len) {
2237 		*bex = *ex;
2238 		ext4_mb_use_best_found(ac, e4b);
2239 		return;
2240 	}
2241 
2242 	/*
2243 	 * If this is first found extent, just store it in the context
2244 	 */
2245 	if (bex->fe_len == 0) {
2246 		*bex = *ex;
2247 		return;
2248 	}
2249 
2250 	/*
2251 	 * If new found extent is better, store it in the context
2252 	 */
2253 	if (bex->fe_len < gex->fe_len) {
2254 		/* if the request isn't satisfied, any found extent
2255 		 * larger than previous best one is better */
2256 		if (ex->fe_len > bex->fe_len)
2257 			*bex = *ex;
2258 	} else if (ex->fe_len > gex->fe_len) {
2259 		/* if the request is satisfied, then we try to find
2260 		 * an extent that still satisfy the request, but is
2261 		 * smaller than previous one */
2262 		if (ex->fe_len < bex->fe_len)
2263 			*bex = *ex;
2264 	}
2265 
2266 	ext4_mb_check_limits(ac, e4b, 0);
2267 }
2268 
2269 static noinline_for_stack
2270 void ext4_mb_try_best_found(struct ext4_allocation_context *ac,
2271 					struct ext4_buddy *e4b)
2272 {
2273 	struct ext4_free_extent ex = ac->ac_b_ex;
2274 	ext4_group_t group = ex.fe_group;
2275 	int max;
2276 	int err;
2277 
2278 	BUG_ON(ex.fe_len <= 0);
2279 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2280 	if (err)
2281 		return;
2282 
2283 	ext4_lock_group(ac->ac_sb, group);
2284 	max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
2285 
2286 	if (max > 0) {
2287 		ac->ac_b_ex = ex;
2288 		ext4_mb_use_best_found(ac, e4b);
2289 	}
2290 
2291 	ext4_unlock_group(ac->ac_sb, group);
2292 	ext4_mb_unload_buddy(e4b);
2293 }
2294 
2295 static noinline_for_stack
2296 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
2297 				struct ext4_buddy *e4b)
2298 {
2299 	ext4_group_t group = ac->ac_g_ex.fe_group;
2300 	int max;
2301 	int err;
2302 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2303 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2304 	struct ext4_free_extent ex;
2305 
2306 	if (!grp)
2307 		return -EFSCORRUPTED;
2308 	if (!(ac->ac_flags & (EXT4_MB_HINT_TRY_GOAL | EXT4_MB_HINT_GOAL_ONLY)))
2309 		return 0;
2310 	if (grp->bb_free == 0)
2311 		return 0;
2312 
2313 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2314 	if (err)
2315 		return err;
2316 
2317 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
2318 		ext4_mb_unload_buddy(e4b);
2319 		return 0;
2320 	}
2321 
2322 	ext4_lock_group(ac->ac_sb, group);
2323 	max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
2324 			     ac->ac_g_ex.fe_len, &ex);
2325 	ex.fe_logical = 0xDEADFA11; /* debug value */
2326 
2327 	if (max >= ac->ac_g_ex.fe_len &&
2328 	    ac->ac_g_ex.fe_len == EXT4_B2C(sbi, sbi->s_stripe)) {
2329 		ext4_fsblk_t start;
2330 
2331 		start = ext4_grp_offs_to_block(ac->ac_sb, &ex);
2332 		/* use do_div to get remainder (would be 64-bit modulo) */
2333 		if (do_div(start, sbi->s_stripe) == 0) {
2334 			ac->ac_found++;
2335 			ac->ac_b_ex = ex;
2336 			ext4_mb_use_best_found(ac, e4b);
2337 		}
2338 	} else if (max >= ac->ac_g_ex.fe_len) {
2339 		BUG_ON(ex.fe_len <= 0);
2340 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2341 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2342 		ac->ac_found++;
2343 		ac->ac_b_ex = ex;
2344 		ext4_mb_use_best_found(ac, e4b);
2345 	} else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
2346 		/* Sometimes, caller may want to merge even small
2347 		 * number of blocks to an existing extent */
2348 		BUG_ON(ex.fe_len <= 0);
2349 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2350 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2351 		ac->ac_found++;
2352 		ac->ac_b_ex = ex;
2353 		ext4_mb_use_best_found(ac, e4b);
2354 	}
2355 	ext4_unlock_group(ac->ac_sb, group);
2356 	ext4_mb_unload_buddy(e4b);
2357 
2358 	return 0;
2359 }
2360 
2361 /*
2362  * The routine scans buddy structures (not bitmap!) from given order
2363  * to max order and tries to find big enough chunk to satisfy the req
2364  */
2365 static noinline_for_stack
2366 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
2367 					struct ext4_buddy *e4b)
2368 {
2369 	struct super_block *sb = ac->ac_sb;
2370 	struct ext4_group_info *grp = e4b->bd_info;
2371 	void *buddy;
2372 	int i;
2373 	int k;
2374 	int max;
2375 
2376 	BUG_ON(ac->ac_2order <= 0);
2377 	for (i = ac->ac_2order; i < MB_NUM_ORDERS(sb); i++) {
2378 		if (grp->bb_counters[i] == 0)
2379 			continue;
2380 
2381 		buddy = mb_find_buddy(e4b, i, &max);
2382 		if (WARN_RATELIMIT(buddy == NULL,
2383 			 "ext4: mb_simple_scan_group: mb_find_buddy failed, (%d)\n", i))
2384 			continue;
2385 
2386 		k = mb_find_next_zero_bit(buddy, max, 0);
2387 		if (k >= max) {
2388 			ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
2389 				"%d free clusters of order %d. But found 0",
2390 				grp->bb_counters[i], i);
2391 			ext4_mark_group_bitmap_corrupted(ac->ac_sb,
2392 					 e4b->bd_group,
2393 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2394 			break;
2395 		}
2396 		ac->ac_found++;
2397 		ac->ac_cX_found[ac->ac_criteria]++;
2398 
2399 		ac->ac_b_ex.fe_len = 1 << i;
2400 		ac->ac_b_ex.fe_start = k << i;
2401 		ac->ac_b_ex.fe_group = e4b->bd_group;
2402 
2403 		ext4_mb_use_best_found(ac, e4b);
2404 
2405 		BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
2406 
2407 		if (EXT4_SB(sb)->s_mb_stats)
2408 			atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
2409 
2410 		break;
2411 	}
2412 }
2413 
2414 /*
2415  * The routine scans the group and measures all found extents.
2416  * In order to optimize scanning, caller must pass number of
2417  * free blocks in the group, so the routine can know upper limit.
2418  */
2419 static noinline_for_stack
2420 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
2421 					struct ext4_buddy *e4b)
2422 {
2423 	struct super_block *sb = ac->ac_sb;
2424 	void *bitmap = e4b->bd_bitmap;
2425 	struct ext4_free_extent ex;
2426 	int i, j, freelen;
2427 	int free;
2428 
2429 	free = e4b->bd_info->bb_free;
2430 	if (WARN_ON(free <= 0))
2431 		return;
2432 
2433 	i = e4b->bd_info->bb_first_free;
2434 
2435 	while (free && ac->ac_status == AC_STATUS_CONTINUE) {
2436 		i = mb_find_next_zero_bit(bitmap,
2437 						EXT4_CLUSTERS_PER_GROUP(sb), i);
2438 		if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
2439 			/*
2440 			 * IF we have corrupt bitmap, we won't find any
2441 			 * free blocks even though group info says we
2442 			 * have free blocks
2443 			 */
2444 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2445 					"%d free clusters as per "
2446 					"group info. But bitmap says 0",
2447 					free);
2448 			ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2449 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2450 			break;
2451 		}
2452 
2453 		if (!ext4_mb_cr_expensive(ac->ac_criteria)) {
2454 			/*
2455 			 * In CR_GOAL_LEN_FAST and CR_BEST_AVAIL_LEN, we are
2456 			 * sure that this group will have a large enough
2457 			 * continuous free extent, so skip over the smaller free
2458 			 * extents
2459 			 */
2460 			j = mb_find_next_bit(bitmap,
2461 						EXT4_CLUSTERS_PER_GROUP(sb), i);
2462 			freelen = j - i;
2463 
2464 			if (freelen < ac->ac_g_ex.fe_len) {
2465 				i = j;
2466 				free -= freelen;
2467 				continue;
2468 			}
2469 		}
2470 
2471 		mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
2472 		if (WARN_ON(ex.fe_len <= 0))
2473 			break;
2474 		if (free < ex.fe_len) {
2475 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2476 					"%d free clusters as per "
2477 					"group info. But got %d blocks",
2478 					free, ex.fe_len);
2479 			ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2480 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2481 			/*
2482 			 * The number of free blocks differs. This mostly
2483 			 * indicate that the bitmap is corrupt. So exit
2484 			 * without claiming the space.
2485 			 */
2486 			break;
2487 		}
2488 		ex.fe_logical = 0xDEADC0DE; /* debug value */
2489 		ext4_mb_measure_extent(ac, &ex, e4b);
2490 
2491 		i += ex.fe_len;
2492 		free -= ex.fe_len;
2493 	}
2494 
2495 	ext4_mb_check_limits(ac, e4b, 1);
2496 }
2497 
2498 /*
2499  * This is a special case for storages like raid5
2500  * we try to find stripe-aligned chunks for stripe-size-multiple requests
2501  */
2502 static noinline_for_stack
2503 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2504 				 struct ext4_buddy *e4b)
2505 {
2506 	struct super_block *sb = ac->ac_sb;
2507 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2508 	void *bitmap = e4b->bd_bitmap;
2509 	struct ext4_free_extent ex;
2510 	ext4_fsblk_t first_group_block;
2511 	ext4_fsblk_t a;
2512 	ext4_grpblk_t i, stripe;
2513 	int max;
2514 
2515 	BUG_ON(sbi->s_stripe == 0);
2516 
2517 	/* find first stripe-aligned block in group */
2518 	first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2519 
2520 	a = first_group_block + sbi->s_stripe - 1;
2521 	do_div(a, sbi->s_stripe);
2522 	i = (a * sbi->s_stripe) - first_group_block;
2523 
2524 	stripe = EXT4_B2C(sbi, sbi->s_stripe);
2525 	i = EXT4_B2C(sbi, i);
2526 	while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2527 		if (!mb_test_bit(i, bitmap)) {
2528 			max = mb_find_extent(e4b, i, stripe, &ex);
2529 			if (max >= stripe) {
2530 				ac->ac_found++;
2531 				ac->ac_cX_found[ac->ac_criteria]++;
2532 				ex.fe_logical = 0xDEADF00D; /* debug value */
2533 				ac->ac_b_ex = ex;
2534 				ext4_mb_use_best_found(ac, e4b);
2535 				break;
2536 			}
2537 		}
2538 		i += stripe;
2539 	}
2540 }
2541 
2542 /*
2543  * This is also called BEFORE we load the buddy bitmap.
2544  * Returns either 1 or 0 indicating that the group is either suitable
2545  * for the allocation or not.
2546  */
2547 static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
2548 				ext4_group_t group, enum criteria cr)
2549 {
2550 	ext4_grpblk_t free, fragments;
2551 	int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2552 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2553 
2554 	BUG_ON(cr < CR_POWER2_ALIGNED || cr >= EXT4_MB_NUM_CRS);
2555 
2556 	if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2557 		return false;
2558 
2559 	free = grp->bb_free;
2560 	if (free == 0)
2561 		return false;
2562 
2563 	fragments = grp->bb_fragments;
2564 	if (fragments == 0)
2565 		return false;
2566 
2567 	switch (cr) {
2568 	case CR_POWER2_ALIGNED:
2569 		BUG_ON(ac->ac_2order == 0);
2570 
2571 		/* Avoid using the first bg of a flexgroup for data files */
2572 		if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2573 		    (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2574 		    ((group % flex_size) == 0))
2575 			return false;
2576 
2577 		if (free < ac->ac_g_ex.fe_len)
2578 			return false;
2579 
2580 		if (ac->ac_2order >= MB_NUM_ORDERS(ac->ac_sb))
2581 			return true;
2582 
2583 		if (grp->bb_largest_free_order < ac->ac_2order)
2584 			return false;
2585 
2586 		return true;
2587 	case CR_GOAL_LEN_FAST:
2588 	case CR_BEST_AVAIL_LEN:
2589 		if ((free / fragments) >= ac->ac_g_ex.fe_len)
2590 			return true;
2591 		break;
2592 	case CR_GOAL_LEN_SLOW:
2593 		if (free >= ac->ac_g_ex.fe_len)
2594 			return true;
2595 		break;
2596 	case CR_ANY_FREE:
2597 		return true;
2598 	default:
2599 		BUG();
2600 	}
2601 
2602 	return false;
2603 }
2604 
2605 /*
2606  * This could return negative error code if something goes wrong
2607  * during ext4_mb_init_group(). This should not be called with
2608  * ext4_lock_group() held.
2609  *
2610  * Note: because we are conditionally operating with the group lock in
2611  * the EXT4_MB_STRICT_CHECK case, we need to fake out sparse in this
2612  * function using __acquire and __release.  This means we need to be
2613  * super careful before messing with the error path handling via "goto
2614  * out"!
2615  */
2616 static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
2617 				     ext4_group_t group, enum criteria cr)
2618 {
2619 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2620 	struct super_block *sb = ac->ac_sb;
2621 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2622 	bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
2623 	ext4_grpblk_t free;
2624 	int ret = 0;
2625 
2626 	if (!grp)
2627 		return -EFSCORRUPTED;
2628 	if (sbi->s_mb_stats)
2629 		atomic64_inc(&sbi->s_bal_cX_groups_considered[ac->ac_criteria]);
2630 	if (should_lock) {
2631 		ext4_lock_group(sb, group);
2632 		__release(ext4_group_lock_ptr(sb, group));
2633 	}
2634 	free = grp->bb_free;
2635 	if (free == 0)
2636 		goto out;
2637 	/*
2638 	 * In all criterias except CR_ANY_FREE we try to avoid groups that
2639 	 * can't possibly satisfy the full goal request due to insufficient
2640 	 * free blocks.
2641 	 */
2642 	if (cr < CR_ANY_FREE && free < ac->ac_g_ex.fe_len)
2643 		goto out;
2644 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2645 		goto out;
2646 	if (should_lock) {
2647 		__acquire(ext4_group_lock_ptr(sb, group));
2648 		ext4_unlock_group(sb, group);
2649 	}
2650 
2651 	/* We only do this if the grp has never been initialized */
2652 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2653 		struct ext4_group_desc *gdp =
2654 			ext4_get_group_desc(sb, group, NULL);
2655 		int ret;
2656 
2657 		/*
2658 		 * cr=CR_POWER2_ALIGNED/CR_GOAL_LEN_FAST is a very optimistic
2659 		 * search to find large good chunks almost for free. If buddy
2660 		 * data is not ready, then this optimization makes no sense. But
2661 		 * we never skip the first block group in a flex_bg, since this
2662 		 * gets used for metadata block allocation, and we want to make
2663 		 * sure we locate metadata blocks in the first block group in
2664 		 * the flex_bg if possible.
2665 		 */
2666 		if (!ext4_mb_cr_expensive(cr) &&
2667 		    (!sbi->s_log_groups_per_flex ||
2668 		     ((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
2669 		    !(ext4_has_group_desc_csum(sb) &&
2670 		      (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
2671 			return 0;
2672 		ret = ext4_mb_init_group(sb, group, GFP_NOFS);
2673 		if (ret)
2674 			return ret;
2675 	}
2676 
2677 	if (should_lock) {
2678 		ext4_lock_group(sb, group);
2679 		__release(ext4_group_lock_ptr(sb, group));
2680 	}
2681 	ret = ext4_mb_good_group(ac, group, cr);
2682 out:
2683 	if (should_lock) {
2684 		__acquire(ext4_group_lock_ptr(sb, group));
2685 		ext4_unlock_group(sb, group);
2686 	}
2687 	return ret;
2688 }
2689 
2690 /*
2691  * Start prefetching @nr block bitmaps starting at @group.
2692  * Return the next group which needs to be prefetched.
2693  */
2694 ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
2695 			      unsigned int nr, int *cnt)
2696 {
2697 	ext4_group_t ngroups = ext4_get_groups_count(sb);
2698 	struct buffer_head *bh;
2699 	struct blk_plug plug;
2700 
2701 	blk_start_plug(&plug);
2702 	while (nr-- > 0) {
2703 		struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2704 								  NULL);
2705 		struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2706 
2707 		/*
2708 		 * Prefetch block groups with free blocks; but don't
2709 		 * bother if it is marked uninitialized on disk, since
2710 		 * it won't require I/O to read.  Also only try to
2711 		 * prefetch once, so we avoid getblk() call, which can
2712 		 * be expensive.
2713 		 */
2714 		if (gdp && grp && !EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
2715 		    EXT4_MB_GRP_NEED_INIT(grp) &&
2716 		    ext4_free_group_clusters(sb, gdp) > 0 ) {
2717 			bh = ext4_read_block_bitmap_nowait(sb, group, true);
2718 			if (bh && !IS_ERR(bh)) {
2719 				if (!buffer_uptodate(bh) && cnt)
2720 					(*cnt)++;
2721 				brelse(bh);
2722 			}
2723 		}
2724 		if (++group >= ngroups)
2725 			group = 0;
2726 	}
2727 	blk_finish_plug(&plug);
2728 	return group;
2729 }
2730 
2731 /*
2732  * Prefetching reads the block bitmap into the buffer cache; but we
2733  * need to make sure that the buddy bitmap in the page cache has been
2734  * initialized.  Note that ext4_mb_init_group() will block if the I/O
2735  * is not yet completed, or indeed if it was not initiated by
2736  * ext4_mb_prefetch did not start the I/O.
2737  *
2738  * TODO: We should actually kick off the buddy bitmap setup in a work
2739  * queue when the buffer I/O is completed, so that we don't block
2740  * waiting for the block allocation bitmap read to finish when
2741  * ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
2742  */
2743 void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
2744 			   unsigned int nr)
2745 {
2746 	struct ext4_group_desc *gdp;
2747 	struct ext4_group_info *grp;
2748 
2749 	while (nr-- > 0) {
2750 		if (!group)
2751 			group = ext4_get_groups_count(sb);
2752 		group--;
2753 		gdp = ext4_get_group_desc(sb, group, NULL);
2754 		grp = ext4_get_group_info(sb, group);
2755 
2756 		if (grp && gdp && EXT4_MB_GRP_NEED_INIT(grp) &&
2757 		    ext4_free_group_clusters(sb, gdp) > 0) {
2758 			if (ext4_mb_init_group(sb, group, GFP_NOFS))
2759 				break;
2760 		}
2761 	}
2762 }
2763 
2764 static noinline_for_stack int
2765 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2766 {
2767 	ext4_group_t prefetch_grp = 0, ngroups, group, i;
2768 	enum criteria new_cr, cr = CR_GOAL_LEN_FAST;
2769 	int err = 0, first_err = 0;
2770 	unsigned int nr = 0, prefetch_ios = 0;
2771 	struct ext4_sb_info *sbi;
2772 	struct super_block *sb;
2773 	struct ext4_buddy e4b;
2774 	int lost;
2775 
2776 	sb = ac->ac_sb;
2777 	sbi = EXT4_SB(sb);
2778 	ngroups = ext4_get_groups_count(sb);
2779 	/* non-extent files are limited to low blocks/groups */
2780 	if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2781 		ngroups = sbi->s_blockfile_groups;
2782 
2783 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2784 
2785 	/* first, try the goal */
2786 	err = ext4_mb_find_by_goal(ac, &e4b);
2787 	if (err || ac->ac_status == AC_STATUS_FOUND)
2788 		goto out;
2789 
2790 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2791 		goto out;
2792 
2793 	/*
2794 	 * ac->ac_2order is set only if the fe_len is a power of 2
2795 	 * if ac->ac_2order is set we also set criteria to 0 so that we
2796 	 * try exact allocation using buddy.
2797 	 */
2798 	i = fls(ac->ac_g_ex.fe_len);
2799 	ac->ac_2order = 0;
2800 	/*
2801 	 * We search using buddy data only if the order of the request
2802 	 * is greater than equal to the sbi_s_mb_order2_reqs
2803 	 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2804 	 * We also support searching for power-of-two requests only for
2805 	 * requests upto maximum buddy size we have constructed.
2806 	 */
2807 	if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) {
2808 		/*
2809 		 * This should tell if fe_len is exactly power of 2
2810 		 */
2811 		if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2812 			ac->ac_2order = array_index_nospec(i - 1,
2813 							   MB_NUM_ORDERS(sb));
2814 	}
2815 
2816 	/* if stream allocation is enabled, use global goal */
2817 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2818 		/* TBD: may be hot point */
2819 		spin_lock(&sbi->s_md_lock);
2820 		ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2821 		ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2822 		spin_unlock(&sbi->s_md_lock);
2823 	}
2824 
2825 	/*
2826 	 * Let's just scan groups to find more-less suitable blocks We
2827 	 * start with CR_GOAL_LEN_FAST, unless it is power of 2
2828 	 * aligned, in which case let's do that faster approach first.
2829 	 */
2830 	if (ac->ac_2order)
2831 		cr = CR_POWER2_ALIGNED;
2832 repeat:
2833 	for (; cr < EXT4_MB_NUM_CRS && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2834 		ac->ac_criteria = cr;
2835 		/*
2836 		 * searching for the right group start
2837 		 * from the goal value specified
2838 		 */
2839 		group = ac->ac_g_ex.fe_group;
2840 		ac->ac_groups_linear_remaining = sbi->s_mb_max_linear_groups;
2841 		prefetch_grp = group;
2842 
2843 		for (i = 0, new_cr = cr; i < ngroups; i++,
2844 		     ext4_mb_choose_next_group(ac, &new_cr, &group, ngroups)) {
2845 			int ret = 0;
2846 
2847 			cond_resched();
2848 			if (new_cr != cr) {
2849 				cr = new_cr;
2850 				goto repeat;
2851 			}
2852 
2853 			/*
2854 			 * Batch reads of the block allocation bitmaps
2855 			 * to get multiple READs in flight; limit
2856 			 * prefetching at cr=0/1, otherwise mballoc can
2857 			 * spend a lot of time loading imperfect groups
2858 			 */
2859 			if ((prefetch_grp == group) &&
2860 			    (ext4_mb_cr_expensive(cr) ||
2861 			     prefetch_ios < sbi->s_mb_prefetch_limit)) {
2862 				nr = sbi->s_mb_prefetch;
2863 				if (ext4_has_feature_flex_bg(sb)) {
2864 					nr = 1 << sbi->s_log_groups_per_flex;
2865 					nr -= group & (nr - 1);
2866 					nr = min(nr, sbi->s_mb_prefetch);
2867 				}
2868 				prefetch_grp = ext4_mb_prefetch(sb, group,
2869 							nr, &prefetch_ios);
2870 			}
2871 
2872 			/* This now checks without needing the buddy page */
2873 			ret = ext4_mb_good_group_nolock(ac, group, cr);
2874 			if (ret <= 0) {
2875 				if (!first_err)
2876 					first_err = ret;
2877 				continue;
2878 			}
2879 
2880 			err = ext4_mb_load_buddy(sb, group, &e4b);
2881 			if (err)
2882 				goto out;
2883 
2884 			ext4_lock_group(sb, group);
2885 
2886 			/*
2887 			 * We need to check again after locking the
2888 			 * block group
2889 			 */
2890 			ret = ext4_mb_good_group(ac, group, cr);
2891 			if (ret == 0) {
2892 				ext4_unlock_group(sb, group);
2893 				ext4_mb_unload_buddy(&e4b);
2894 				continue;
2895 			}
2896 
2897 			ac->ac_groups_scanned++;
2898 			if (cr == CR_POWER2_ALIGNED)
2899 				ext4_mb_simple_scan_group(ac, &e4b);
2900 			else if ((cr == CR_GOAL_LEN_FAST ||
2901 				 cr == CR_BEST_AVAIL_LEN) &&
2902 				 sbi->s_stripe &&
2903 				 !(ac->ac_g_ex.fe_len %
2904 				 EXT4_B2C(sbi, sbi->s_stripe)))
2905 				ext4_mb_scan_aligned(ac, &e4b);
2906 			else
2907 				ext4_mb_complex_scan_group(ac, &e4b);
2908 
2909 			ext4_unlock_group(sb, group);
2910 			ext4_mb_unload_buddy(&e4b);
2911 
2912 			if (ac->ac_status != AC_STATUS_CONTINUE)
2913 				break;
2914 		}
2915 		/* Processed all groups and haven't found blocks */
2916 		if (sbi->s_mb_stats && i == ngroups)
2917 			atomic64_inc(&sbi->s_bal_cX_failed[cr]);
2918 
2919 		if (i == ngroups && ac->ac_criteria == CR_BEST_AVAIL_LEN)
2920 			/* Reset goal length to original goal length before
2921 			 * falling into CR_GOAL_LEN_SLOW */
2922 			ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
2923 	}
2924 
2925 	if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2926 	    !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2927 		/*
2928 		 * We've been searching too long. Let's try to allocate
2929 		 * the best chunk we've found so far
2930 		 */
2931 		ext4_mb_try_best_found(ac, &e4b);
2932 		if (ac->ac_status != AC_STATUS_FOUND) {
2933 			/*
2934 			 * Someone more lucky has already allocated it.
2935 			 * The only thing we can do is just take first
2936 			 * found block(s)
2937 			 */
2938 			lost = atomic_inc_return(&sbi->s_mb_lost_chunks);
2939 			mb_debug(sb, "lost chunk, group: %u, start: %d, len: %d, lost: %d\n",
2940 				 ac->ac_b_ex.fe_group, ac->ac_b_ex.fe_start,
2941 				 ac->ac_b_ex.fe_len, lost);
2942 
2943 			ac->ac_b_ex.fe_group = 0;
2944 			ac->ac_b_ex.fe_start = 0;
2945 			ac->ac_b_ex.fe_len = 0;
2946 			ac->ac_status = AC_STATUS_CONTINUE;
2947 			ac->ac_flags |= EXT4_MB_HINT_FIRST;
2948 			cr = CR_ANY_FREE;
2949 			goto repeat;
2950 		}
2951 	}
2952 
2953 	if (sbi->s_mb_stats && ac->ac_status == AC_STATUS_FOUND)
2954 		atomic64_inc(&sbi->s_bal_cX_hits[ac->ac_criteria]);
2955 out:
2956 	if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2957 		err = first_err;
2958 
2959 	mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
2960 		 ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
2961 		 ac->ac_flags, cr, err);
2962 
2963 	if (nr)
2964 		ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
2965 
2966 	return err;
2967 }
2968 
2969 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2970 {
2971 	struct super_block *sb = pde_data(file_inode(seq->file));
2972 	ext4_group_t group;
2973 
2974 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2975 		return NULL;
2976 	group = *pos + 1;
2977 	return (void *) ((unsigned long) group);
2978 }
2979 
2980 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2981 {
2982 	struct super_block *sb = pde_data(file_inode(seq->file));
2983 	ext4_group_t group;
2984 
2985 	++*pos;
2986 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2987 		return NULL;
2988 	group = *pos + 1;
2989 	return (void *) ((unsigned long) group);
2990 }
2991 
2992 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2993 {
2994 	struct super_block *sb = pde_data(file_inode(seq->file));
2995 	ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2996 	int i;
2997 	int err, buddy_loaded = 0;
2998 	struct ext4_buddy e4b;
2999 	struct ext4_group_info *grinfo;
3000 	unsigned char blocksize_bits = min_t(unsigned char,
3001 					     sb->s_blocksize_bits,
3002 					     EXT4_MAX_BLOCK_LOG_SIZE);
3003 	struct sg {
3004 		struct ext4_group_info info;
3005 		ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
3006 	} sg;
3007 
3008 	group--;
3009 	if (group == 0)
3010 		seq_puts(seq, "#group: free  frags first ["
3011 			      " 2^0   2^1   2^2   2^3   2^4   2^5   2^6  "
3012 			      " 2^7   2^8   2^9   2^10  2^11  2^12  2^13  ]\n");
3013 
3014 	i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
3015 		sizeof(struct ext4_group_info);
3016 
3017 	grinfo = ext4_get_group_info(sb, group);
3018 	if (!grinfo)
3019 		return 0;
3020 	/* Load the group info in memory only if not already loaded. */
3021 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
3022 		err = ext4_mb_load_buddy(sb, group, &e4b);
3023 		if (err) {
3024 			seq_printf(seq, "#%-5u: I/O error\n", group);
3025 			return 0;
3026 		}
3027 		buddy_loaded = 1;
3028 	}
3029 
3030 	memcpy(&sg, grinfo, i);
3031 
3032 	if (buddy_loaded)
3033 		ext4_mb_unload_buddy(&e4b);
3034 
3035 	seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
3036 			sg.info.bb_fragments, sg.info.bb_first_free);
3037 	for (i = 0; i <= 13; i++)
3038 		seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
3039 				sg.info.bb_counters[i] : 0);
3040 	seq_puts(seq, " ]\n");
3041 
3042 	return 0;
3043 }
3044 
3045 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
3046 {
3047 }
3048 
3049 const struct seq_operations ext4_mb_seq_groups_ops = {
3050 	.start  = ext4_mb_seq_groups_start,
3051 	.next   = ext4_mb_seq_groups_next,
3052 	.stop   = ext4_mb_seq_groups_stop,
3053 	.show   = ext4_mb_seq_groups_show,
3054 };
3055 
3056 int ext4_seq_mb_stats_show(struct seq_file *seq, void *offset)
3057 {
3058 	struct super_block *sb = seq->private;
3059 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3060 
3061 	seq_puts(seq, "mballoc:\n");
3062 	if (!sbi->s_mb_stats) {
3063 		seq_puts(seq, "\tmb stats collection turned off.\n");
3064 		seq_puts(
3065 			seq,
3066 			"\tTo enable, please write \"1\" to sysfs file mb_stats.\n");
3067 		return 0;
3068 	}
3069 	seq_printf(seq, "\treqs: %u\n", atomic_read(&sbi->s_bal_reqs));
3070 	seq_printf(seq, "\tsuccess: %u\n", atomic_read(&sbi->s_bal_success));
3071 
3072 	seq_printf(seq, "\tgroups_scanned: %u\n",
3073 		   atomic_read(&sbi->s_bal_groups_scanned));
3074 
3075 	/* CR_POWER2_ALIGNED stats */
3076 	seq_puts(seq, "\tcr_p2_aligned_stats:\n");
3077 	seq_printf(seq, "\t\thits: %llu\n",
3078 		   atomic64_read(&sbi->s_bal_cX_hits[CR_POWER2_ALIGNED]));
3079 	seq_printf(
3080 		seq, "\t\tgroups_considered: %llu\n",
3081 		atomic64_read(
3082 			&sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]));
3083 	seq_printf(seq, "\t\textents_scanned: %u\n",
3084 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_POWER2_ALIGNED]));
3085 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3086 		   atomic64_read(&sbi->s_bal_cX_failed[CR_POWER2_ALIGNED]));
3087 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3088 		   atomic_read(&sbi->s_bal_p2_aligned_bad_suggestions));
3089 
3090 	/* CR_GOAL_LEN_FAST stats */
3091 	seq_puts(seq, "\tcr_goal_fast_stats:\n");
3092 	seq_printf(seq, "\t\thits: %llu\n",
3093 		   atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_FAST]));
3094 	seq_printf(seq, "\t\tgroups_considered: %llu\n",
3095 		   atomic64_read(
3096 			   &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_FAST]));
3097 	seq_printf(seq, "\t\textents_scanned: %u\n",
3098 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_FAST]));
3099 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3100 		   atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_FAST]));
3101 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3102 		   atomic_read(&sbi->s_bal_goal_fast_bad_suggestions));
3103 
3104 	/* CR_BEST_AVAIL_LEN stats */
3105 	seq_puts(seq, "\tcr_best_avail_stats:\n");
3106 	seq_printf(seq, "\t\thits: %llu\n",
3107 		   atomic64_read(&sbi->s_bal_cX_hits[CR_BEST_AVAIL_LEN]));
3108 	seq_printf(
3109 		seq, "\t\tgroups_considered: %llu\n",
3110 		atomic64_read(
3111 			&sbi->s_bal_cX_groups_considered[CR_BEST_AVAIL_LEN]));
3112 	seq_printf(seq, "\t\textents_scanned: %u\n",
3113 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_BEST_AVAIL_LEN]));
3114 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3115 		   atomic64_read(&sbi->s_bal_cX_failed[CR_BEST_AVAIL_LEN]));
3116 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3117 		   atomic_read(&sbi->s_bal_best_avail_bad_suggestions));
3118 
3119 	/* CR_GOAL_LEN_SLOW stats */
3120 	seq_puts(seq, "\tcr_goal_slow_stats:\n");
3121 	seq_printf(seq, "\t\thits: %llu\n",
3122 		   atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_SLOW]));
3123 	seq_printf(seq, "\t\tgroups_considered: %llu\n",
3124 		   atomic64_read(
3125 			   &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_SLOW]));
3126 	seq_printf(seq, "\t\textents_scanned: %u\n",
3127 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_SLOW]));
3128 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3129 		   atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_SLOW]));
3130 
3131 	/* CR_ANY_FREE stats */
3132 	seq_puts(seq, "\tcr_any_free_stats:\n");
3133 	seq_printf(seq, "\t\thits: %llu\n",
3134 		   atomic64_read(&sbi->s_bal_cX_hits[CR_ANY_FREE]));
3135 	seq_printf(
3136 		seq, "\t\tgroups_considered: %llu\n",
3137 		atomic64_read(&sbi->s_bal_cX_groups_considered[CR_ANY_FREE]));
3138 	seq_printf(seq, "\t\textents_scanned: %u\n",
3139 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_ANY_FREE]));
3140 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3141 		   atomic64_read(&sbi->s_bal_cX_failed[CR_ANY_FREE]));
3142 
3143 	/* Aggregates */
3144 	seq_printf(seq, "\textents_scanned: %u\n",
3145 		   atomic_read(&sbi->s_bal_ex_scanned));
3146 	seq_printf(seq, "\t\tgoal_hits: %u\n", atomic_read(&sbi->s_bal_goals));
3147 	seq_printf(seq, "\t\tlen_goal_hits: %u\n",
3148 		   atomic_read(&sbi->s_bal_len_goals));
3149 	seq_printf(seq, "\t\t2^n_hits: %u\n", atomic_read(&sbi->s_bal_2orders));
3150 	seq_printf(seq, "\t\tbreaks: %u\n", atomic_read(&sbi->s_bal_breaks));
3151 	seq_printf(seq, "\t\tlost: %u\n", atomic_read(&sbi->s_mb_lost_chunks));
3152 	seq_printf(seq, "\tbuddies_generated: %u/%u\n",
3153 		   atomic_read(&sbi->s_mb_buddies_generated),
3154 		   ext4_get_groups_count(sb));
3155 	seq_printf(seq, "\tbuddies_time_used: %llu\n",
3156 		   atomic64_read(&sbi->s_mb_generation_time));
3157 	seq_printf(seq, "\tpreallocated: %u\n",
3158 		   atomic_read(&sbi->s_mb_preallocated));
3159 	seq_printf(seq, "\tdiscarded: %u\n", atomic_read(&sbi->s_mb_discarded));
3160 	return 0;
3161 }
3162 
3163 static void *ext4_mb_seq_structs_summary_start(struct seq_file *seq, loff_t *pos)
3164 __acquires(&EXT4_SB(sb)->s_mb_rb_lock)
3165 {
3166 	struct super_block *sb = pde_data(file_inode(seq->file));
3167 	unsigned long position;
3168 
3169 	if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3170 		return NULL;
3171 	position = *pos + 1;
3172 	return (void *) ((unsigned long) position);
3173 }
3174 
3175 static void *ext4_mb_seq_structs_summary_next(struct seq_file *seq, void *v, loff_t *pos)
3176 {
3177 	struct super_block *sb = pde_data(file_inode(seq->file));
3178 	unsigned long position;
3179 
3180 	++*pos;
3181 	if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3182 		return NULL;
3183 	position = *pos + 1;
3184 	return (void *) ((unsigned long) position);
3185 }
3186 
3187 static int ext4_mb_seq_structs_summary_show(struct seq_file *seq, void *v)
3188 {
3189 	struct super_block *sb = pde_data(file_inode(seq->file));
3190 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3191 	unsigned long position = ((unsigned long) v);
3192 	struct ext4_group_info *grp;
3193 	unsigned int count;
3194 
3195 	position--;
3196 	if (position >= MB_NUM_ORDERS(sb)) {
3197 		position -= MB_NUM_ORDERS(sb);
3198 		if (position == 0)
3199 			seq_puts(seq, "avg_fragment_size_lists:\n");
3200 
3201 		count = 0;
3202 		read_lock(&sbi->s_mb_avg_fragment_size_locks[position]);
3203 		list_for_each_entry(grp, &sbi->s_mb_avg_fragment_size[position],
3204 				    bb_avg_fragment_size_node)
3205 			count++;
3206 		read_unlock(&sbi->s_mb_avg_fragment_size_locks[position]);
3207 		seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3208 					(unsigned int)position, count);
3209 		return 0;
3210 	}
3211 
3212 	if (position == 0) {
3213 		seq_printf(seq, "optimize_scan: %d\n",
3214 			   test_opt2(sb, MB_OPTIMIZE_SCAN) ? 1 : 0);
3215 		seq_puts(seq, "max_free_order_lists:\n");
3216 	}
3217 	count = 0;
3218 	read_lock(&sbi->s_mb_largest_free_orders_locks[position]);
3219 	list_for_each_entry(grp, &sbi->s_mb_largest_free_orders[position],
3220 			    bb_largest_free_order_node)
3221 		count++;
3222 	read_unlock(&sbi->s_mb_largest_free_orders_locks[position]);
3223 	seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3224 		   (unsigned int)position, count);
3225 
3226 	return 0;
3227 }
3228 
3229 static void ext4_mb_seq_structs_summary_stop(struct seq_file *seq, void *v)
3230 {
3231 }
3232 
3233 const struct seq_operations ext4_mb_seq_structs_summary_ops = {
3234 	.start  = ext4_mb_seq_structs_summary_start,
3235 	.next   = ext4_mb_seq_structs_summary_next,
3236 	.stop   = ext4_mb_seq_structs_summary_stop,
3237 	.show   = ext4_mb_seq_structs_summary_show,
3238 };
3239 
3240 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
3241 {
3242 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3243 	struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
3244 
3245 	BUG_ON(!cachep);
3246 	return cachep;
3247 }
3248 
3249 /*
3250  * Allocate the top-level s_group_info array for the specified number
3251  * of groups
3252  */
3253 int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
3254 {
3255 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3256 	unsigned size;
3257 	struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
3258 
3259 	size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
3260 		EXT4_DESC_PER_BLOCK_BITS(sb);
3261 	if (size <= sbi->s_group_info_size)
3262 		return 0;
3263 
3264 	size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
3265 	new_groupinfo = kvzalloc(size, GFP_KERNEL);
3266 	if (!new_groupinfo) {
3267 		ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
3268 		return -ENOMEM;
3269 	}
3270 	rcu_read_lock();
3271 	old_groupinfo = rcu_dereference(sbi->s_group_info);
3272 	if (old_groupinfo)
3273 		memcpy(new_groupinfo, old_groupinfo,
3274 		       sbi->s_group_info_size * sizeof(*sbi->s_group_info));
3275 	rcu_read_unlock();
3276 	rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
3277 	sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
3278 	if (old_groupinfo)
3279 		ext4_kvfree_array_rcu(old_groupinfo);
3280 	ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
3281 		   sbi->s_group_info_size);
3282 	return 0;
3283 }
3284 
3285 /* Create and initialize ext4_group_info data for the given group. */
3286 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
3287 			  struct ext4_group_desc *desc)
3288 {
3289 	int i;
3290 	int metalen = 0;
3291 	int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
3292 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3293 	struct ext4_group_info **meta_group_info;
3294 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3295 
3296 	/*
3297 	 * First check if this group is the first of a reserved block.
3298 	 * If it's true, we have to allocate a new table of pointers
3299 	 * to ext4_group_info structures
3300 	 */
3301 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3302 		metalen = sizeof(*meta_group_info) <<
3303 			EXT4_DESC_PER_BLOCK_BITS(sb);
3304 		meta_group_info = kmalloc(metalen, GFP_NOFS);
3305 		if (meta_group_info == NULL) {
3306 			ext4_msg(sb, KERN_ERR, "can't allocate mem "
3307 				 "for a buddy group");
3308 			return -ENOMEM;
3309 		}
3310 		rcu_read_lock();
3311 		rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
3312 		rcu_read_unlock();
3313 	}
3314 
3315 	meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
3316 	i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
3317 
3318 	meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
3319 	if (meta_group_info[i] == NULL) {
3320 		ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
3321 		goto exit_group_info;
3322 	}
3323 	set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
3324 		&(meta_group_info[i]->bb_state));
3325 
3326 	/*
3327 	 * initialize bb_free to be able to skip
3328 	 * empty groups without initialization
3329 	 */
3330 	if (ext4_has_group_desc_csum(sb) &&
3331 	    (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3332 		meta_group_info[i]->bb_free =
3333 			ext4_free_clusters_after_init(sb, group, desc);
3334 	} else {
3335 		meta_group_info[i]->bb_free =
3336 			ext4_free_group_clusters(sb, desc);
3337 	}
3338 
3339 	INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
3340 	init_rwsem(&meta_group_info[i]->alloc_sem);
3341 	meta_group_info[i]->bb_free_root = RB_ROOT;
3342 	INIT_LIST_HEAD(&meta_group_info[i]->bb_largest_free_order_node);
3343 	INIT_LIST_HEAD(&meta_group_info[i]->bb_avg_fragment_size_node);
3344 	meta_group_info[i]->bb_largest_free_order = -1;  /* uninit */
3345 	meta_group_info[i]->bb_avg_fragment_size_order = -1;  /* uninit */
3346 	meta_group_info[i]->bb_group = group;
3347 
3348 	mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
3349 	return 0;
3350 
3351 exit_group_info:
3352 	/* If a meta_group_info table has been allocated, release it now */
3353 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3354 		struct ext4_group_info ***group_info;
3355 
3356 		rcu_read_lock();
3357 		group_info = rcu_dereference(sbi->s_group_info);
3358 		kfree(group_info[idx]);
3359 		group_info[idx] = NULL;
3360 		rcu_read_unlock();
3361 	}
3362 	return -ENOMEM;
3363 } /* ext4_mb_add_groupinfo */
3364 
3365 static int ext4_mb_init_backend(struct super_block *sb)
3366 {
3367 	ext4_group_t ngroups = ext4_get_groups_count(sb);
3368 	ext4_group_t i;
3369 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3370 	int err;
3371 	struct ext4_group_desc *desc;
3372 	struct ext4_group_info ***group_info;
3373 	struct kmem_cache *cachep;
3374 
3375 	err = ext4_mb_alloc_groupinfo(sb, ngroups);
3376 	if (err)
3377 		return err;
3378 
3379 	sbi->s_buddy_cache = new_inode(sb);
3380 	if (sbi->s_buddy_cache == NULL) {
3381 		ext4_msg(sb, KERN_ERR, "can't get new inode");
3382 		goto err_freesgi;
3383 	}
3384 	/* To avoid potentially colliding with an valid on-disk inode number,
3385 	 * use EXT4_BAD_INO for the buddy cache inode number.  This inode is
3386 	 * not in the inode hash, so it should never be found by iget(), but
3387 	 * this will avoid confusion if it ever shows up during debugging. */
3388 	sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
3389 	EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
3390 	for (i = 0; i < ngroups; i++) {
3391 		cond_resched();
3392 		desc = ext4_get_group_desc(sb, i, NULL);
3393 		if (desc == NULL) {
3394 			ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
3395 			goto err_freebuddy;
3396 		}
3397 		if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
3398 			goto err_freebuddy;
3399 	}
3400 
3401 	if (ext4_has_feature_flex_bg(sb)) {
3402 		/* a single flex group is supposed to be read by a single IO.
3403 		 * 2 ^ s_log_groups_per_flex != UINT_MAX as s_mb_prefetch is
3404 		 * unsigned integer, so the maximum shift is 32.
3405 		 */
3406 		if (sbi->s_es->s_log_groups_per_flex >= 32) {
3407 			ext4_msg(sb, KERN_ERR, "too many log groups per flexible block group");
3408 			goto err_freebuddy;
3409 		}
3410 		sbi->s_mb_prefetch = min_t(uint, 1 << sbi->s_es->s_log_groups_per_flex,
3411 			BLK_MAX_SEGMENT_SIZE >> (sb->s_blocksize_bits - 9));
3412 		sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
3413 	} else {
3414 		sbi->s_mb_prefetch = 32;
3415 	}
3416 	if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
3417 		sbi->s_mb_prefetch = ext4_get_groups_count(sb);
3418 	/* now many real IOs to prefetch within a single allocation at cr=0
3419 	 * given cr=0 is an CPU-related optimization we shouldn't try to
3420 	 * load too many groups, at some point we should start to use what
3421 	 * we've got in memory.
3422 	 * with an average random access time 5ms, it'd take a second to get
3423 	 * 200 groups (* N with flex_bg), so let's make this limit 4
3424 	 */
3425 	sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
3426 	if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
3427 		sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
3428 
3429 	return 0;
3430 
3431 err_freebuddy:
3432 	cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3433 	while (i-- > 0) {
3434 		struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3435 
3436 		if (grp)
3437 			kmem_cache_free(cachep, grp);
3438 	}
3439 	i = sbi->s_group_info_size;
3440 	rcu_read_lock();
3441 	group_info = rcu_dereference(sbi->s_group_info);
3442 	while (i-- > 0)
3443 		kfree(group_info[i]);
3444 	rcu_read_unlock();
3445 	iput(sbi->s_buddy_cache);
3446 err_freesgi:
3447 	rcu_read_lock();
3448 	kvfree(rcu_dereference(sbi->s_group_info));
3449 	rcu_read_unlock();
3450 	return -ENOMEM;
3451 }
3452 
3453 static void ext4_groupinfo_destroy_slabs(void)
3454 {
3455 	int i;
3456 
3457 	for (i = 0; i < NR_GRPINFO_CACHES; i++) {
3458 		kmem_cache_destroy(ext4_groupinfo_caches[i]);
3459 		ext4_groupinfo_caches[i] = NULL;
3460 	}
3461 }
3462 
3463 static int ext4_groupinfo_create_slab(size_t size)
3464 {
3465 	static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
3466 	int slab_size;
3467 	int blocksize_bits = order_base_2(size);
3468 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3469 	struct kmem_cache *cachep;
3470 
3471 	if (cache_index >= NR_GRPINFO_CACHES)
3472 		return -EINVAL;
3473 
3474 	if (unlikely(cache_index < 0))
3475 		cache_index = 0;
3476 
3477 	mutex_lock(&ext4_grpinfo_slab_create_mutex);
3478 	if (ext4_groupinfo_caches[cache_index]) {
3479 		mutex_unlock(&ext4_grpinfo_slab_create_mutex);
3480 		return 0;	/* Already created */
3481 	}
3482 
3483 	slab_size = offsetof(struct ext4_group_info,
3484 				bb_counters[blocksize_bits + 2]);
3485 
3486 	cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
3487 					slab_size, 0, SLAB_RECLAIM_ACCOUNT,
3488 					NULL);
3489 
3490 	ext4_groupinfo_caches[cache_index] = cachep;
3491 
3492 	mutex_unlock(&ext4_grpinfo_slab_create_mutex);
3493 	if (!cachep) {
3494 		printk(KERN_EMERG
3495 		       "EXT4-fs: no memory for groupinfo slab cache\n");
3496 		return -ENOMEM;
3497 	}
3498 
3499 	return 0;
3500 }
3501 
3502 static void ext4_discard_work(struct work_struct *work)
3503 {
3504 	struct ext4_sb_info *sbi = container_of(work,
3505 			struct ext4_sb_info, s_discard_work);
3506 	struct super_block *sb = sbi->s_sb;
3507 	struct ext4_free_data *fd, *nfd;
3508 	struct ext4_buddy e4b;
3509 	struct list_head discard_list;
3510 	ext4_group_t grp, load_grp;
3511 	int err = 0;
3512 
3513 	INIT_LIST_HEAD(&discard_list);
3514 	spin_lock(&sbi->s_md_lock);
3515 	list_splice_init(&sbi->s_discard_list, &discard_list);
3516 	spin_unlock(&sbi->s_md_lock);
3517 
3518 	load_grp = UINT_MAX;
3519 	list_for_each_entry_safe(fd, nfd, &discard_list, efd_list) {
3520 		/*
3521 		 * If filesystem is umounting or no memory or suffering
3522 		 * from no space, give up the discard
3523 		 */
3524 		if ((sb->s_flags & SB_ACTIVE) && !err &&
3525 		    !atomic_read(&sbi->s_retry_alloc_pending)) {
3526 			grp = fd->efd_group;
3527 			if (grp != load_grp) {
3528 				if (load_grp != UINT_MAX)
3529 					ext4_mb_unload_buddy(&e4b);
3530 
3531 				err = ext4_mb_load_buddy(sb, grp, &e4b);
3532 				if (err) {
3533 					kmem_cache_free(ext4_free_data_cachep, fd);
3534 					load_grp = UINT_MAX;
3535 					continue;
3536 				} else {
3537 					load_grp = grp;
3538 				}
3539 			}
3540 
3541 			ext4_lock_group(sb, grp);
3542 			ext4_try_to_trim_range(sb, &e4b, fd->efd_start_cluster,
3543 						fd->efd_start_cluster + fd->efd_count - 1, 1);
3544 			ext4_unlock_group(sb, grp);
3545 		}
3546 		kmem_cache_free(ext4_free_data_cachep, fd);
3547 	}
3548 
3549 	if (load_grp != UINT_MAX)
3550 		ext4_mb_unload_buddy(&e4b);
3551 }
3552 
3553 int ext4_mb_init(struct super_block *sb)
3554 {
3555 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3556 	unsigned i, j;
3557 	unsigned offset, offset_incr;
3558 	unsigned max;
3559 	int ret;
3560 
3561 	i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_offsets);
3562 
3563 	sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
3564 	if (sbi->s_mb_offsets == NULL) {
3565 		ret = -ENOMEM;
3566 		goto out;
3567 	}
3568 
3569 	i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_maxs);
3570 	sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
3571 	if (sbi->s_mb_maxs == NULL) {
3572 		ret = -ENOMEM;
3573 		goto out;
3574 	}
3575 
3576 	ret = ext4_groupinfo_create_slab(sb->s_blocksize);
3577 	if (ret < 0)
3578 		goto out;
3579 
3580 	/* order 0 is regular bitmap */
3581 	sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
3582 	sbi->s_mb_offsets[0] = 0;
3583 
3584 	i = 1;
3585 	offset = 0;
3586 	offset_incr = 1 << (sb->s_blocksize_bits - 1);
3587 	max = sb->s_blocksize << 2;
3588 	do {
3589 		sbi->s_mb_offsets[i] = offset;
3590 		sbi->s_mb_maxs[i] = max;
3591 		offset += offset_incr;
3592 		offset_incr = offset_incr >> 1;
3593 		max = max >> 1;
3594 		i++;
3595 	} while (i < MB_NUM_ORDERS(sb));
3596 
3597 	sbi->s_mb_avg_fragment_size =
3598 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3599 			GFP_KERNEL);
3600 	if (!sbi->s_mb_avg_fragment_size) {
3601 		ret = -ENOMEM;
3602 		goto out;
3603 	}
3604 	sbi->s_mb_avg_fragment_size_locks =
3605 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3606 			GFP_KERNEL);
3607 	if (!sbi->s_mb_avg_fragment_size_locks) {
3608 		ret = -ENOMEM;
3609 		goto out;
3610 	}
3611 	for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3612 		INIT_LIST_HEAD(&sbi->s_mb_avg_fragment_size[i]);
3613 		rwlock_init(&sbi->s_mb_avg_fragment_size_locks[i]);
3614 	}
3615 	sbi->s_mb_largest_free_orders =
3616 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3617 			GFP_KERNEL);
3618 	if (!sbi->s_mb_largest_free_orders) {
3619 		ret = -ENOMEM;
3620 		goto out;
3621 	}
3622 	sbi->s_mb_largest_free_orders_locks =
3623 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3624 			GFP_KERNEL);
3625 	if (!sbi->s_mb_largest_free_orders_locks) {
3626 		ret = -ENOMEM;
3627 		goto out;
3628 	}
3629 	for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3630 		INIT_LIST_HEAD(&sbi->s_mb_largest_free_orders[i]);
3631 		rwlock_init(&sbi->s_mb_largest_free_orders_locks[i]);
3632 	}
3633 
3634 	spin_lock_init(&sbi->s_md_lock);
3635 	sbi->s_mb_free_pending = 0;
3636 	INIT_LIST_HEAD(&sbi->s_freed_data_list);
3637 	INIT_LIST_HEAD(&sbi->s_discard_list);
3638 	INIT_WORK(&sbi->s_discard_work, ext4_discard_work);
3639 	atomic_set(&sbi->s_retry_alloc_pending, 0);
3640 
3641 	sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
3642 	sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
3643 	sbi->s_mb_stats = MB_DEFAULT_STATS;
3644 	sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
3645 	sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
3646 	sbi->s_mb_best_avail_max_trim_order = MB_DEFAULT_BEST_AVAIL_TRIM_ORDER;
3647 
3648 	/*
3649 	 * The default group preallocation is 512, which for 4k block
3650 	 * sizes translates to 2 megabytes.  However for bigalloc file
3651 	 * systems, this is probably too big (i.e, if the cluster size
3652 	 * is 1 megabyte, then group preallocation size becomes half a
3653 	 * gigabyte!).  As a default, we will keep a two megabyte
3654 	 * group pralloc size for cluster sizes up to 64k, and after
3655 	 * that, we will force a minimum group preallocation size of
3656 	 * 32 clusters.  This translates to 8 megs when the cluster
3657 	 * size is 256k, and 32 megs when the cluster size is 1 meg,
3658 	 * which seems reasonable as a default.
3659 	 */
3660 	sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
3661 				       sbi->s_cluster_bits, 32);
3662 	/*
3663 	 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
3664 	 * to the lowest multiple of s_stripe which is bigger than
3665 	 * the s_mb_group_prealloc as determined above. We want
3666 	 * the preallocation size to be an exact multiple of the
3667 	 * RAID stripe size so that preallocations don't fragment
3668 	 * the stripes.
3669 	 */
3670 	if (sbi->s_stripe > 1) {
3671 		sbi->s_mb_group_prealloc = roundup(
3672 			sbi->s_mb_group_prealloc, EXT4_B2C(sbi, sbi->s_stripe));
3673 	}
3674 
3675 	sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
3676 	if (sbi->s_locality_groups == NULL) {
3677 		ret = -ENOMEM;
3678 		goto out;
3679 	}
3680 	for_each_possible_cpu(i) {
3681 		struct ext4_locality_group *lg;
3682 		lg = per_cpu_ptr(sbi->s_locality_groups, i);
3683 		mutex_init(&lg->lg_mutex);
3684 		for (j = 0; j < PREALLOC_TB_SIZE; j++)
3685 			INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
3686 		spin_lock_init(&lg->lg_prealloc_lock);
3687 	}
3688 
3689 	if (bdev_nonrot(sb->s_bdev))
3690 		sbi->s_mb_max_linear_groups = 0;
3691 	else
3692 		sbi->s_mb_max_linear_groups = MB_DEFAULT_LINEAR_LIMIT;
3693 	/* init file for buddy data */
3694 	ret = ext4_mb_init_backend(sb);
3695 	if (ret != 0)
3696 		goto out_free_locality_groups;
3697 
3698 	return 0;
3699 
3700 out_free_locality_groups:
3701 	free_percpu(sbi->s_locality_groups);
3702 	sbi->s_locality_groups = NULL;
3703 out:
3704 	kfree(sbi->s_mb_avg_fragment_size);
3705 	kfree(sbi->s_mb_avg_fragment_size_locks);
3706 	kfree(sbi->s_mb_largest_free_orders);
3707 	kfree(sbi->s_mb_largest_free_orders_locks);
3708 	kfree(sbi->s_mb_offsets);
3709 	sbi->s_mb_offsets = NULL;
3710 	kfree(sbi->s_mb_maxs);
3711 	sbi->s_mb_maxs = NULL;
3712 	return ret;
3713 }
3714 
3715 /* need to called with the ext4 group lock held */
3716 static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
3717 {
3718 	struct ext4_prealloc_space *pa;
3719 	struct list_head *cur, *tmp;
3720 	int count = 0;
3721 
3722 	list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
3723 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3724 		list_del(&pa->pa_group_list);
3725 		count++;
3726 		kmem_cache_free(ext4_pspace_cachep, pa);
3727 	}
3728 	return count;
3729 }
3730 
3731 int ext4_mb_release(struct super_block *sb)
3732 {
3733 	ext4_group_t ngroups = ext4_get_groups_count(sb);
3734 	ext4_group_t i;
3735 	int num_meta_group_infos;
3736 	struct ext4_group_info *grinfo, ***group_info;
3737 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3738 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3739 	int count;
3740 
3741 	if (test_opt(sb, DISCARD)) {
3742 		/*
3743 		 * wait the discard work to drain all of ext4_free_data
3744 		 */
3745 		flush_work(&sbi->s_discard_work);
3746 		WARN_ON_ONCE(!list_empty(&sbi->s_discard_list));
3747 	}
3748 
3749 	if (sbi->s_group_info) {
3750 		for (i = 0; i < ngroups; i++) {
3751 			cond_resched();
3752 			grinfo = ext4_get_group_info(sb, i);
3753 			if (!grinfo)
3754 				continue;
3755 			mb_group_bb_bitmap_free(grinfo);
3756 			ext4_lock_group(sb, i);
3757 			count = ext4_mb_cleanup_pa(grinfo);
3758 			if (count)
3759 				mb_debug(sb, "mballoc: %d PAs left\n",
3760 					 count);
3761 			ext4_unlock_group(sb, i);
3762 			kmem_cache_free(cachep, grinfo);
3763 		}
3764 		num_meta_group_infos = (ngroups +
3765 				EXT4_DESC_PER_BLOCK(sb) - 1) >>
3766 			EXT4_DESC_PER_BLOCK_BITS(sb);
3767 		rcu_read_lock();
3768 		group_info = rcu_dereference(sbi->s_group_info);
3769 		for (i = 0; i < num_meta_group_infos; i++)
3770 			kfree(group_info[i]);
3771 		kvfree(group_info);
3772 		rcu_read_unlock();
3773 	}
3774 	kfree(sbi->s_mb_avg_fragment_size);
3775 	kfree(sbi->s_mb_avg_fragment_size_locks);
3776 	kfree(sbi->s_mb_largest_free_orders);
3777 	kfree(sbi->s_mb_largest_free_orders_locks);
3778 	kfree(sbi->s_mb_offsets);
3779 	kfree(sbi->s_mb_maxs);
3780 	iput(sbi->s_buddy_cache);
3781 	if (sbi->s_mb_stats) {
3782 		ext4_msg(sb, KERN_INFO,
3783 		       "mballoc: %u blocks %u reqs (%u success)",
3784 				atomic_read(&sbi->s_bal_allocated),
3785 				atomic_read(&sbi->s_bal_reqs),
3786 				atomic_read(&sbi->s_bal_success));
3787 		ext4_msg(sb, KERN_INFO,
3788 		      "mballoc: %u extents scanned, %u groups scanned, %u goal hits, "
3789 				"%u 2^N hits, %u breaks, %u lost",
3790 				atomic_read(&sbi->s_bal_ex_scanned),
3791 				atomic_read(&sbi->s_bal_groups_scanned),
3792 				atomic_read(&sbi->s_bal_goals),
3793 				atomic_read(&sbi->s_bal_2orders),
3794 				atomic_read(&sbi->s_bal_breaks),
3795 				atomic_read(&sbi->s_mb_lost_chunks));
3796 		ext4_msg(sb, KERN_INFO,
3797 		       "mballoc: %u generated and it took %llu",
3798 				atomic_read(&sbi->s_mb_buddies_generated),
3799 				atomic64_read(&sbi->s_mb_generation_time));
3800 		ext4_msg(sb, KERN_INFO,
3801 		       "mballoc: %u preallocated, %u discarded",
3802 				atomic_read(&sbi->s_mb_preallocated),
3803 				atomic_read(&sbi->s_mb_discarded));
3804 	}
3805 
3806 	free_percpu(sbi->s_locality_groups);
3807 
3808 	return 0;
3809 }
3810 
3811 static inline int ext4_issue_discard(struct super_block *sb,
3812 		ext4_group_t block_group, ext4_grpblk_t cluster, int count,
3813 		struct bio **biop)
3814 {
3815 	ext4_fsblk_t discard_block;
3816 
3817 	discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
3818 			 ext4_group_first_block_no(sb, block_group));
3819 	count = EXT4_C2B(EXT4_SB(sb), count);
3820 	trace_ext4_discard_blocks(sb,
3821 			(unsigned long long) discard_block, count);
3822 	if (biop) {
3823 		return __blkdev_issue_discard(sb->s_bdev,
3824 			(sector_t)discard_block << (sb->s_blocksize_bits - 9),
3825 			(sector_t)count << (sb->s_blocksize_bits - 9),
3826 			GFP_NOFS, biop);
3827 	} else
3828 		return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
3829 }
3830 
3831 static void ext4_free_data_in_buddy(struct super_block *sb,
3832 				    struct ext4_free_data *entry)
3833 {
3834 	struct ext4_buddy e4b;
3835 	struct ext4_group_info *db;
3836 	int err, count = 0;
3837 
3838 	mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
3839 		 entry->efd_count, entry->efd_group, entry);
3840 
3841 	err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
3842 	/* we expect to find existing buddy because it's pinned */
3843 	BUG_ON(err != 0);
3844 
3845 	spin_lock(&EXT4_SB(sb)->s_md_lock);
3846 	EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
3847 	spin_unlock(&EXT4_SB(sb)->s_md_lock);
3848 
3849 	db = e4b.bd_info;
3850 	/* there are blocks to put in buddy to make them really free */
3851 	count += entry->efd_count;
3852 	ext4_lock_group(sb, entry->efd_group);
3853 	/* Take it out of per group rb tree */
3854 	rb_erase(&entry->efd_node, &(db->bb_free_root));
3855 	mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
3856 
3857 	/*
3858 	 * Clear the trimmed flag for the group so that the next
3859 	 * ext4_trim_fs can trim it.
3860 	 * If the volume is mounted with -o discard, online discard
3861 	 * is supported and the free blocks will be trimmed online.
3862 	 */
3863 	if (!test_opt(sb, DISCARD))
3864 		EXT4_MB_GRP_CLEAR_TRIMMED(db);
3865 
3866 	if (!db->bb_free_root.rb_node) {
3867 		/* No more items in the per group rb tree
3868 		 * balance refcounts from ext4_mb_free_metadata()
3869 		 */
3870 		put_page(e4b.bd_buddy_page);
3871 		put_page(e4b.bd_bitmap_page);
3872 	}
3873 	ext4_unlock_group(sb, entry->efd_group);
3874 	ext4_mb_unload_buddy(&e4b);
3875 
3876 	mb_debug(sb, "freed %d blocks in 1 structures\n", count);
3877 }
3878 
3879 /*
3880  * This function is called by the jbd2 layer once the commit has finished,
3881  * so we know we can free the blocks that were released with that commit.
3882  */
3883 void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
3884 {
3885 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3886 	struct ext4_free_data *entry, *tmp;
3887 	struct list_head freed_data_list;
3888 	struct list_head *cut_pos = NULL;
3889 	bool wake;
3890 
3891 	INIT_LIST_HEAD(&freed_data_list);
3892 
3893 	spin_lock(&sbi->s_md_lock);
3894 	list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
3895 		if (entry->efd_tid != commit_tid)
3896 			break;
3897 		cut_pos = &entry->efd_list;
3898 	}
3899 	if (cut_pos)
3900 		list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
3901 				  cut_pos);
3902 	spin_unlock(&sbi->s_md_lock);
3903 
3904 	list_for_each_entry(entry, &freed_data_list, efd_list)
3905 		ext4_free_data_in_buddy(sb, entry);
3906 
3907 	if (test_opt(sb, DISCARD)) {
3908 		spin_lock(&sbi->s_md_lock);
3909 		wake = list_empty(&sbi->s_discard_list);
3910 		list_splice_tail(&freed_data_list, &sbi->s_discard_list);
3911 		spin_unlock(&sbi->s_md_lock);
3912 		if (wake)
3913 			queue_work(system_unbound_wq, &sbi->s_discard_work);
3914 	} else {
3915 		list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
3916 			kmem_cache_free(ext4_free_data_cachep, entry);
3917 	}
3918 }
3919 
3920 int __init ext4_init_mballoc(void)
3921 {
3922 	ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
3923 					SLAB_RECLAIM_ACCOUNT);
3924 	if (ext4_pspace_cachep == NULL)
3925 		goto out;
3926 
3927 	ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
3928 				    SLAB_RECLAIM_ACCOUNT);
3929 	if (ext4_ac_cachep == NULL)
3930 		goto out_pa_free;
3931 
3932 	ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
3933 					   SLAB_RECLAIM_ACCOUNT);
3934 	if (ext4_free_data_cachep == NULL)
3935 		goto out_ac_free;
3936 
3937 	return 0;
3938 
3939 out_ac_free:
3940 	kmem_cache_destroy(ext4_ac_cachep);
3941 out_pa_free:
3942 	kmem_cache_destroy(ext4_pspace_cachep);
3943 out:
3944 	return -ENOMEM;
3945 }
3946 
3947 void ext4_exit_mballoc(void)
3948 {
3949 	/*
3950 	 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
3951 	 * before destroying the slab cache.
3952 	 */
3953 	rcu_barrier();
3954 	kmem_cache_destroy(ext4_pspace_cachep);
3955 	kmem_cache_destroy(ext4_ac_cachep);
3956 	kmem_cache_destroy(ext4_free_data_cachep);
3957 	ext4_groupinfo_destroy_slabs();
3958 }
3959 
3960 
3961 /*
3962  * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
3963  * Returns 0 if success or error code
3964  */
3965 static noinline_for_stack int
3966 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
3967 				handle_t *handle, unsigned int reserv_clstrs)
3968 {
3969 	struct buffer_head *bitmap_bh = NULL;
3970 	struct ext4_group_desc *gdp;
3971 	struct buffer_head *gdp_bh;
3972 	struct ext4_sb_info *sbi;
3973 	struct super_block *sb;
3974 	ext4_fsblk_t block;
3975 	int err, len;
3976 
3977 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3978 	BUG_ON(ac->ac_b_ex.fe_len <= 0);
3979 
3980 	sb = ac->ac_sb;
3981 	sbi = EXT4_SB(sb);
3982 
3983 	bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
3984 	if (IS_ERR(bitmap_bh)) {
3985 		return PTR_ERR(bitmap_bh);
3986 	}
3987 
3988 	BUFFER_TRACE(bitmap_bh, "getting write access");
3989 	err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
3990 					    EXT4_JTR_NONE);
3991 	if (err)
3992 		goto out_err;
3993 
3994 	err = -EIO;
3995 	gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3996 	if (!gdp)
3997 		goto out_err;
3998 
3999 	ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
4000 			ext4_free_group_clusters(sb, gdp));
4001 
4002 	BUFFER_TRACE(gdp_bh, "get_write_access");
4003 	err = ext4_journal_get_write_access(handle, sb, gdp_bh, EXT4_JTR_NONE);
4004 	if (err)
4005 		goto out_err;
4006 
4007 	block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4008 
4009 	len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4010 	if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
4011 		ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
4012 			   "fs metadata", block, block+len);
4013 		/* File system mounted not to panic on error
4014 		 * Fix the bitmap and return EFSCORRUPTED
4015 		 * We leak some of the blocks here.
4016 		 */
4017 		ext4_lock_group(sb, ac->ac_b_ex.fe_group);
4018 		mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
4019 			      ac->ac_b_ex.fe_len);
4020 		ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
4021 		err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4022 		if (!err)
4023 			err = -EFSCORRUPTED;
4024 		goto out_err;
4025 	}
4026 
4027 	ext4_lock_group(sb, ac->ac_b_ex.fe_group);
4028 #ifdef AGGRESSIVE_CHECK
4029 	{
4030 		int i;
4031 		for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
4032 			BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
4033 						bitmap_bh->b_data));
4034 		}
4035 	}
4036 #endif
4037 	mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
4038 		      ac->ac_b_ex.fe_len);
4039 	if (ext4_has_group_desc_csum(sb) &&
4040 	    (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
4041 		gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
4042 		ext4_free_group_clusters_set(sb, gdp,
4043 					     ext4_free_clusters_after_init(sb,
4044 						ac->ac_b_ex.fe_group, gdp));
4045 	}
4046 	len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
4047 	ext4_free_group_clusters_set(sb, gdp, len);
4048 	ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
4049 	ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
4050 
4051 	ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
4052 	percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
4053 	/*
4054 	 * Now reduce the dirty block count also. Should not go negative
4055 	 */
4056 	if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
4057 		/* release all the reserved blocks if non delalloc */
4058 		percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4059 				   reserv_clstrs);
4060 
4061 	if (sbi->s_log_groups_per_flex) {
4062 		ext4_group_t flex_group = ext4_flex_group(sbi,
4063 							  ac->ac_b_ex.fe_group);
4064 		atomic64_sub(ac->ac_b_ex.fe_len,
4065 			     &sbi_array_rcu_deref(sbi, s_flex_groups,
4066 						  flex_group)->free_clusters);
4067 	}
4068 
4069 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4070 	if (err)
4071 		goto out_err;
4072 	err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
4073 
4074 out_err:
4075 	brelse(bitmap_bh);
4076 	return err;
4077 }
4078 
4079 /*
4080  * Idempotent helper for Ext4 fast commit replay path to set the state of
4081  * blocks in bitmaps and update counters.
4082  */
4083 void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
4084 			int len, int state)
4085 {
4086 	struct buffer_head *bitmap_bh = NULL;
4087 	struct ext4_group_desc *gdp;
4088 	struct buffer_head *gdp_bh;
4089 	struct ext4_sb_info *sbi = EXT4_SB(sb);
4090 	ext4_group_t group;
4091 	ext4_grpblk_t blkoff;
4092 	int i, err;
4093 	int already;
4094 	unsigned int clen, clen_changed, thisgrp_len;
4095 
4096 	while (len > 0) {
4097 		ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
4098 
4099 		/*
4100 		 * Check to see if we are freeing blocks across a group
4101 		 * boundary.
4102 		 * In case of flex_bg, this can happen that (block, len) may
4103 		 * span across more than one group. In that case we need to
4104 		 * get the corresponding group metadata to work with.
4105 		 * For this we have goto again loop.
4106 		 */
4107 		thisgrp_len = min_t(unsigned int, (unsigned int)len,
4108 			EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
4109 		clen = EXT4_NUM_B2C(sbi, thisgrp_len);
4110 
4111 		if (!ext4_sb_block_valid(sb, NULL, block, thisgrp_len)) {
4112 			ext4_error(sb, "Marking blocks in system zone - "
4113 				   "Block = %llu, len = %u",
4114 				   block, thisgrp_len);
4115 			bitmap_bh = NULL;
4116 			break;
4117 		}
4118 
4119 		bitmap_bh = ext4_read_block_bitmap(sb, group);
4120 		if (IS_ERR(bitmap_bh)) {
4121 			err = PTR_ERR(bitmap_bh);
4122 			bitmap_bh = NULL;
4123 			break;
4124 		}
4125 
4126 		err = -EIO;
4127 		gdp = ext4_get_group_desc(sb, group, &gdp_bh);
4128 		if (!gdp)
4129 			break;
4130 
4131 		ext4_lock_group(sb, group);
4132 		already = 0;
4133 		for (i = 0; i < clen; i++)
4134 			if (!mb_test_bit(blkoff + i, bitmap_bh->b_data) ==
4135 					 !state)
4136 				already++;
4137 
4138 		clen_changed = clen - already;
4139 		if (state)
4140 			mb_set_bits(bitmap_bh->b_data, blkoff, clen);
4141 		else
4142 			mb_clear_bits(bitmap_bh->b_data, blkoff, clen);
4143 		if (ext4_has_group_desc_csum(sb) &&
4144 		    (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
4145 			gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
4146 			ext4_free_group_clusters_set(sb, gdp,
4147 			     ext4_free_clusters_after_init(sb, group, gdp));
4148 		}
4149 		if (state)
4150 			clen = ext4_free_group_clusters(sb, gdp) - clen_changed;
4151 		else
4152 			clen = ext4_free_group_clusters(sb, gdp) + clen_changed;
4153 
4154 		ext4_free_group_clusters_set(sb, gdp, clen);
4155 		ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
4156 		ext4_group_desc_csum_set(sb, group, gdp);
4157 
4158 		ext4_unlock_group(sb, group);
4159 
4160 		if (sbi->s_log_groups_per_flex) {
4161 			ext4_group_t flex_group = ext4_flex_group(sbi, group);
4162 			struct flex_groups *fg = sbi_array_rcu_deref(sbi,
4163 						   s_flex_groups, flex_group);
4164 
4165 			if (state)
4166 				atomic64_sub(clen_changed, &fg->free_clusters);
4167 			else
4168 				atomic64_add(clen_changed, &fg->free_clusters);
4169 
4170 		}
4171 
4172 		err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
4173 		if (err)
4174 			break;
4175 		sync_dirty_buffer(bitmap_bh);
4176 		err = ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
4177 		sync_dirty_buffer(gdp_bh);
4178 		if (err)
4179 			break;
4180 
4181 		block += thisgrp_len;
4182 		len -= thisgrp_len;
4183 		brelse(bitmap_bh);
4184 		BUG_ON(len < 0);
4185 	}
4186 
4187 	if (err)
4188 		brelse(bitmap_bh);
4189 }
4190 
4191 /*
4192  * here we normalize request for locality group
4193  * Group request are normalized to s_mb_group_prealloc, which goes to
4194  * s_strip if we set the same via mount option.
4195  * s_mb_group_prealloc can be configured via
4196  * /sys/fs/ext4/<partition>/mb_group_prealloc
4197  *
4198  * XXX: should we try to preallocate more than the group has now?
4199  */
4200 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
4201 {
4202 	struct super_block *sb = ac->ac_sb;
4203 	struct ext4_locality_group *lg = ac->ac_lg;
4204 
4205 	BUG_ON(lg == NULL);
4206 	ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
4207 	mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
4208 }
4209 
4210 /*
4211  * This function returns the next element to look at during inode
4212  * PA rbtree walk. We assume that we have held the inode PA rbtree lock
4213  * (ei->i_prealloc_lock)
4214  *
4215  * new_start	The start of the range we want to compare
4216  * cur_start	The existing start that we are comparing against
4217  * node	The node of the rb_tree
4218  */
4219 static inline struct rb_node*
4220 ext4_mb_pa_rb_next_iter(ext4_lblk_t new_start, ext4_lblk_t cur_start, struct rb_node *node)
4221 {
4222 	if (new_start < cur_start)
4223 		return node->rb_left;
4224 	else
4225 		return node->rb_right;
4226 }
4227 
4228 static inline void
4229 ext4_mb_pa_assert_overlap(struct ext4_allocation_context *ac,
4230 			  ext4_lblk_t start, loff_t end)
4231 {
4232 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4233 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4234 	struct ext4_prealloc_space *tmp_pa;
4235 	ext4_lblk_t tmp_pa_start;
4236 	loff_t tmp_pa_end;
4237 	struct rb_node *iter;
4238 
4239 	read_lock(&ei->i_prealloc_lock);
4240 	for (iter = ei->i_prealloc_node.rb_node; iter;
4241 	     iter = ext4_mb_pa_rb_next_iter(start, tmp_pa_start, iter)) {
4242 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4243 				  pa_node.inode_node);
4244 		tmp_pa_start = tmp_pa->pa_lstart;
4245 		tmp_pa_end = pa_logical_end(sbi, tmp_pa);
4246 
4247 		spin_lock(&tmp_pa->pa_lock);
4248 		if (tmp_pa->pa_deleted == 0)
4249 			BUG_ON(!(start >= tmp_pa_end || end <= tmp_pa_start));
4250 		spin_unlock(&tmp_pa->pa_lock);
4251 	}
4252 	read_unlock(&ei->i_prealloc_lock);
4253 }
4254 
4255 /*
4256  * Given an allocation context "ac" and a range "start", "end", check
4257  * and adjust boundaries if the range overlaps with any of the existing
4258  * preallocatoins stored in the corresponding inode of the allocation context.
4259  *
4260  * Parameters:
4261  *	ac			allocation context
4262  *	start			start of the new range
4263  *	end			end of the new range
4264  */
4265 static inline void
4266 ext4_mb_pa_adjust_overlap(struct ext4_allocation_context *ac,
4267 			  ext4_lblk_t *start, loff_t *end)
4268 {
4269 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4270 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4271 	struct ext4_prealloc_space *tmp_pa = NULL, *left_pa = NULL, *right_pa = NULL;
4272 	struct rb_node *iter;
4273 	ext4_lblk_t new_start, tmp_pa_start, right_pa_start = -1;
4274 	loff_t new_end, tmp_pa_end, left_pa_end = -1;
4275 
4276 	new_start = *start;
4277 	new_end = *end;
4278 
4279 	/*
4280 	 * Adjust the normalized range so that it doesn't overlap with any
4281 	 * existing preallocated blocks(PAs). Make sure to hold the rbtree lock
4282 	 * so it doesn't change underneath us.
4283 	 */
4284 	read_lock(&ei->i_prealloc_lock);
4285 
4286 	/* Step 1: find any one immediate neighboring PA of the normalized range */
4287 	for (iter = ei->i_prealloc_node.rb_node; iter;
4288 	     iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
4289 					    tmp_pa_start, iter)) {
4290 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4291 				  pa_node.inode_node);
4292 		tmp_pa_start = tmp_pa->pa_lstart;
4293 		tmp_pa_end = pa_logical_end(sbi, tmp_pa);
4294 
4295 		/* PA must not overlap original request */
4296 		spin_lock(&tmp_pa->pa_lock);
4297 		if (tmp_pa->pa_deleted == 0)
4298 			BUG_ON(!(ac->ac_o_ex.fe_logical >= tmp_pa_end ||
4299 				 ac->ac_o_ex.fe_logical < tmp_pa_start));
4300 		spin_unlock(&tmp_pa->pa_lock);
4301 	}
4302 
4303 	/*
4304 	 * Step 2: check if the found PA is left or right neighbor and
4305 	 * get the other neighbor
4306 	 */
4307 	if (tmp_pa) {
4308 		if (tmp_pa->pa_lstart < ac->ac_o_ex.fe_logical) {
4309 			struct rb_node *tmp;
4310 
4311 			left_pa = tmp_pa;
4312 			tmp = rb_next(&left_pa->pa_node.inode_node);
4313 			if (tmp) {
4314 				right_pa = rb_entry(tmp,
4315 						    struct ext4_prealloc_space,
4316 						    pa_node.inode_node);
4317 			}
4318 		} else {
4319 			struct rb_node *tmp;
4320 
4321 			right_pa = tmp_pa;
4322 			tmp = rb_prev(&right_pa->pa_node.inode_node);
4323 			if (tmp) {
4324 				left_pa = rb_entry(tmp,
4325 						   struct ext4_prealloc_space,
4326 						   pa_node.inode_node);
4327 			}
4328 		}
4329 	}
4330 
4331 	/* Step 3: get the non deleted neighbors */
4332 	if (left_pa) {
4333 		for (iter = &left_pa->pa_node.inode_node;;
4334 		     iter = rb_prev(iter)) {
4335 			if (!iter) {
4336 				left_pa = NULL;
4337 				break;
4338 			}
4339 
4340 			tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4341 					  pa_node.inode_node);
4342 			left_pa = tmp_pa;
4343 			spin_lock(&tmp_pa->pa_lock);
4344 			if (tmp_pa->pa_deleted == 0) {
4345 				spin_unlock(&tmp_pa->pa_lock);
4346 				break;
4347 			}
4348 			spin_unlock(&tmp_pa->pa_lock);
4349 		}
4350 	}
4351 
4352 	if (right_pa) {
4353 		for (iter = &right_pa->pa_node.inode_node;;
4354 		     iter = rb_next(iter)) {
4355 			if (!iter) {
4356 				right_pa = NULL;
4357 				break;
4358 			}
4359 
4360 			tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4361 					  pa_node.inode_node);
4362 			right_pa = tmp_pa;
4363 			spin_lock(&tmp_pa->pa_lock);
4364 			if (tmp_pa->pa_deleted == 0) {
4365 				spin_unlock(&tmp_pa->pa_lock);
4366 				break;
4367 			}
4368 			spin_unlock(&tmp_pa->pa_lock);
4369 		}
4370 	}
4371 
4372 	if (left_pa) {
4373 		left_pa_end = pa_logical_end(sbi, left_pa);
4374 		BUG_ON(left_pa_end > ac->ac_o_ex.fe_logical);
4375 	}
4376 
4377 	if (right_pa) {
4378 		right_pa_start = right_pa->pa_lstart;
4379 		BUG_ON(right_pa_start <= ac->ac_o_ex.fe_logical);
4380 	}
4381 
4382 	/* Step 4: trim our normalized range to not overlap with the neighbors */
4383 	if (left_pa) {
4384 		if (left_pa_end > new_start)
4385 			new_start = left_pa_end;
4386 	}
4387 
4388 	if (right_pa) {
4389 		if (right_pa_start < new_end)
4390 			new_end = right_pa_start;
4391 	}
4392 	read_unlock(&ei->i_prealloc_lock);
4393 
4394 	/* XXX: extra loop to check we really don't overlap preallocations */
4395 	ext4_mb_pa_assert_overlap(ac, new_start, new_end);
4396 
4397 	*start = new_start;
4398 	*end = new_end;
4399 }
4400 
4401 /*
4402  * Normalization means making request better in terms of
4403  * size and alignment
4404  */
4405 static noinline_for_stack void
4406 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
4407 				struct ext4_allocation_request *ar)
4408 {
4409 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4410 	struct ext4_super_block *es = sbi->s_es;
4411 	int bsbits, max;
4412 	loff_t size, start_off, end;
4413 	loff_t orig_size __maybe_unused;
4414 	ext4_lblk_t start;
4415 
4416 	/* do normalize only data requests, metadata requests
4417 	   do not need preallocation */
4418 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4419 		return;
4420 
4421 	/* sometime caller may want exact blocks */
4422 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4423 		return;
4424 
4425 	/* caller may indicate that preallocation isn't
4426 	 * required (it's a tail, for example) */
4427 	if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
4428 		return;
4429 
4430 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
4431 		ext4_mb_normalize_group_request(ac);
4432 		return ;
4433 	}
4434 
4435 	bsbits = ac->ac_sb->s_blocksize_bits;
4436 
4437 	/* first, let's learn actual file size
4438 	 * given current request is allocated */
4439 	size = extent_logical_end(sbi, &ac->ac_o_ex);
4440 	size = size << bsbits;
4441 	if (size < i_size_read(ac->ac_inode))
4442 		size = i_size_read(ac->ac_inode);
4443 	orig_size = size;
4444 
4445 	/* max size of free chunks */
4446 	max = 2 << bsbits;
4447 
4448 #define NRL_CHECK_SIZE(req, size, max, chunk_size)	\
4449 		(req <= (size) || max <= (chunk_size))
4450 
4451 	/* first, try to predict filesize */
4452 	/* XXX: should this table be tunable? */
4453 	start_off = 0;
4454 	if (size <= 16 * 1024) {
4455 		size = 16 * 1024;
4456 	} else if (size <= 32 * 1024) {
4457 		size = 32 * 1024;
4458 	} else if (size <= 64 * 1024) {
4459 		size = 64 * 1024;
4460 	} else if (size <= 128 * 1024) {
4461 		size = 128 * 1024;
4462 	} else if (size <= 256 * 1024) {
4463 		size = 256 * 1024;
4464 	} else if (size <= 512 * 1024) {
4465 		size = 512 * 1024;
4466 	} else if (size <= 1024 * 1024) {
4467 		size = 1024 * 1024;
4468 	} else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
4469 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4470 						(21 - bsbits)) << 21;
4471 		size = 2 * 1024 * 1024;
4472 	} else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
4473 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4474 							(22 - bsbits)) << 22;
4475 		size = 4 * 1024 * 1024;
4476 	} else if (NRL_CHECK_SIZE(EXT4_C2B(sbi, ac->ac_o_ex.fe_len),
4477 					(8<<20)>>bsbits, max, 8 * 1024)) {
4478 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4479 							(23 - bsbits)) << 23;
4480 		size = 8 * 1024 * 1024;
4481 	} else {
4482 		start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
4483 		size	  = (loff_t) EXT4_C2B(sbi,
4484 					      ac->ac_o_ex.fe_len) << bsbits;
4485 	}
4486 	size = size >> bsbits;
4487 	start = start_off >> bsbits;
4488 
4489 	/*
4490 	 * For tiny groups (smaller than 8MB) the chosen allocation
4491 	 * alignment may be larger than group size. Make sure the
4492 	 * alignment does not move allocation to a different group which
4493 	 * makes mballoc fail assertions later.
4494 	 */
4495 	start = max(start, rounddown(ac->ac_o_ex.fe_logical,
4496 			(ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
4497 
4498 	/* don't cover already allocated blocks in selected range */
4499 	if (ar->pleft && start <= ar->lleft) {
4500 		size -= ar->lleft + 1 - start;
4501 		start = ar->lleft + 1;
4502 	}
4503 	if (ar->pright && start + size - 1 >= ar->lright)
4504 		size -= start + size - ar->lright;
4505 
4506 	/*
4507 	 * Trim allocation request for filesystems with artificially small
4508 	 * groups.
4509 	 */
4510 	if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
4511 		size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
4512 
4513 	end = start + size;
4514 
4515 	ext4_mb_pa_adjust_overlap(ac, &start, &end);
4516 
4517 	size = end - start;
4518 
4519 	/*
4520 	 * In this function "start" and "size" are normalized for better
4521 	 * alignment and length such that we could preallocate more blocks.
4522 	 * This normalization is done such that original request of
4523 	 * ac->ac_o_ex.fe_logical & fe_len should always lie within "start" and
4524 	 * "size" boundaries.
4525 	 * (Note fe_len can be relaxed since FS block allocation API does not
4526 	 * provide gurantee on number of contiguous blocks allocation since that
4527 	 * depends upon free space left, etc).
4528 	 * In case of inode pa, later we use the allocated blocks
4529 	 * [pa_pstart + fe_logical - pa_lstart, fe_len/size] from the preallocated
4530 	 * range of goal/best blocks [start, size] to put it at the
4531 	 * ac_o_ex.fe_logical extent of this inode.
4532 	 * (See ext4_mb_use_inode_pa() for more details)
4533 	 */
4534 	if (start + size <= ac->ac_o_ex.fe_logical ||
4535 			start > ac->ac_o_ex.fe_logical) {
4536 		ext4_msg(ac->ac_sb, KERN_ERR,
4537 			 "start %lu, size %lu, fe_logical %lu",
4538 			 (unsigned long) start, (unsigned long) size,
4539 			 (unsigned long) ac->ac_o_ex.fe_logical);
4540 		BUG();
4541 	}
4542 	BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
4543 
4544 	/* now prepare goal request */
4545 
4546 	/* XXX: is it better to align blocks WRT to logical
4547 	 * placement or satisfy big request as is */
4548 	ac->ac_g_ex.fe_logical = start;
4549 	ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
4550 	ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
4551 
4552 	/* define goal start in order to merge */
4553 	if (ar->pright && (ar->lright == (start + size)) &&
4554 	    ar->pright >= size &&
4555 	    ar->pright - size >= le32_to_cpu(es->s_first_data_block)) {
4556 		/* merge to the right */
4557 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
4558 						&ac->ac_g_ex.fe_group,
4559 						&ac->ac_g_ex.fe_start);
4560 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4561 	}
4562 	if (ar->pleft && (ar->lleft + 1 == start) &&
4563 	    ar->pleft + 1 < ext4_blocks_count(es)) {
4564 		/* merge to the left */
4565 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
4566 						&ac->ac_g_ex.fe_group,
4567 						&ac->ac_g_ex.fe_start);
4568 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4569 	}
4570 
4571 	mb_debug(ac->ac_sb, "goal: %lld(was %lld) blocks at %u\n", size,
4572 		 orig_size, start);
4573 }
4574 
4575 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
4576 {
4577 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4578 
4579 	if (sbi->s_mb_stats && ac->ac_g_ex.fe_len >= 1) {
4580 		atomic_inc(&sbi->s_bal_reqs);
4581 		atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
4582 		if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
4583 			atomic_inc(&sbi->s_bal_success);
4584 
4585 		atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
4586 		for (int i=0; i<EXT4_MB_NUM_CRS; i++) {
4587 			atomic_add(ac->ac_cX_found[i], &sbi->s_bal_cX_ex_scanned[i]);
4588 		}
4589 
4590 		atomic_add(ac->ac_groups_scanned, &sbi->s_bal_groups_scanned);
4591 		if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
4592 				ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
4593 			atomic_inc(&sbi->s_bal_goals);
4594 		/* did we allocate as much as normalizer originally wanted? */
4595 		if (ac->ac_f_ex.fe_len == ac->ac_orig_goal_len)
4596 			atomic_inc(&sbi->s_bal_len_goals);
4597 
4598 		if (ac->ac_found > sbi->s_mb_max_to_scan)
4599 			atomic_inc(&sbi->s_bal_breaks);
4600 	}
4601 
4602 	if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
4603 		trace_ext4_mballoc_alloc(ac);
4604 	else
4605 		trace_ext4_mballoc_prealloc(ac);
4606 }
4607 
4608 /*
4609  * Called on failure; free up any blocks from the inode PA for this
4610  * context.  We don't need this for MB_GROUP_PA because we only change
4611  * pa_free in ext4_mb_release_context(), but on failure, we've already
4612  * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
4613  */
4614 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
4615 {
4616 	struct ext4_prealloc_space *pa = ac->ac_pa;
4617 	struct ext4_buddy e4b;
4618 	int err;
4619 
4620 	if (pa == NULL) {
4621 		if (ac->ac_f_ex.fe_len == 0)
4622 			return;
4623 		err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
4624 		if (WARN_RATELIMIT(err,
4625 				   "ext4: mb_load_buddy failed (%d)", err))
4626 			/*
4627 			 * This should never happen since we pin the
4628 			 * pages in the ext4_allocation_context so
4629 			 * ext4_mb_load_buddy() should never fail.
4630 			 */
4631 			return;
4632 		ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
4633 		mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
4634 			       ac->ac_f_ex.fe_len);
4635 		ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
4636 		ext4_mb_unload_buddy(&e4b);
4637 		return;
4638 	}
4639 	if (pa->pa_type == MB_INODE_PA) {
4640 		spin_lock(&pa->pa_lock);
4641 		pa->pa_free += ac->ac_b_ex.fe_len;
4642 		spin_unlock(&pa->pa_lock);
4643 	}
4644 }
4645 
4646 /*
4647  * use blocks preallocated to inode
4648  */
4649 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
4650 				struct ext4_prealloc_space *pa)
4651 {
4652 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4653 	ext4_fsblk_t start;
4654 	ext4_fsblk_t end;
4655 	int len;
4656 
4657 	/* found preallocated blocks, use them */
4658 	start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
4659 	end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
4660 		  start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
4661 	len = EXT4_NUM_B2C(sbi, end - start);
4662 	ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
4663 					&ac->ac_b_ex.fe_start);
4664 	ac->ac_b_ex.fe_len = len;
4665 	ac->ac_status = AC_STATUS_FOUND;
4666 	ac->ac_pa = pa;
4667 
4668 	BUG_ON(start < pa->pa_pstart);
4669 	BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
4670 	BUG_ON(pa->pa_free < len);
4671 	BUG_ON(ac->ac_b_ex.fe_len <= 0);
4672 	pa->pa_free -= len;
4673 
4674 	mb_debug(ac->ac_sb, "use %llu/%d from inode pa %p\n", start, len, pa);
4675 }
4676 
4677 /*
4678  * use blocks preallocated to locality group
4679  */
4680 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
4681 				struct ext4_prealloc_space *pa)
4682 {
4683 	unsigned int len = ac->ac_o_ex.fe_len;
4684 
4685 	ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
4686 					&ac->ac_b_ex.fe_group,
4687 					&ac->ac_b_ex.fe_start);
4688 	ac->ac_b_ex.fe_len = len;
4689 	ac->ac_status = AC_STATUS_FOUND;
4690 	ac->ac_pa = pa;
4691 
4692 	/* we don't correct pa_pstart or pa_len here to avoid
4693 	 * possible race when the group is being loaded concurrently
4694 	 * instead we correct pa later, after blocks are marked
4695 	 * in on-disk bitmap -- see ext4_mb_release_context()
4696 	 * Other CPUs are prevented from allocating from this pa by lg_mutex
4697 	 */
4698 	mb_debug(ac->ac_sb, "use %u/%u from group pa %p\n",
4699 		 pa->pa_lstart, len, pa);
4700 }
4701 
4702 /*
4703  * Return the prealloc space that have minimal distance
4704  * from the goal block. @cpa is the prealloc
4705  * space that is having currently known minimal distance
4706  * from the goal block.
4707  */
4708 static struct ext4_prealloc_space *
4709 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
4710 			struct ext4_prealloc_space *pa,
4711 			struct ext4_prealloc_space *cpa)
4712 {
4713 	ext4_fsblk_t cur_distance, new_distance;
4714 
4715 	if (cpa == NULL) {
4716 		atomic_inc(&pa->pa_count);
4717 		return pa;
4718 	}
4719 	cur_distance = abs(goal_block - cpa->pa_pstart);
4720 	new_distance = abs(goal_block - pa->pa_pstart);
4721 
4722 	if (cur_distance <= new_distance)
4723 		return cpa;
4724 
4725 	/* drop the previous reference */
4726 	atomic_dec(&cpa->pa_count);
4727 	atomic_inc(&pa->pa_count);
4728 	return pa;
4729 }
4730 
4731 /*
4732  * check if found pa meets EXT4_MB_HINT_GOAL_ONLY
4733  */
4734 static bool
4735 ext4_mb_pa_goal_check(struct ext4_allocation_context *ac,
4736 		      struct ext4_prealloc_space *pa)
4737 {
4738 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4739 	ext4_fsblk_t start;
4740 
4741 	if (likely(!(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY)))
4742 		return true;
4743 
4744 	/*
4745 	 * If EXT4_MB_HINT_GOAL_ONLY is set, ac_g_ex will not be adjusted
4746 	 * in ext4_mb_normalize_request and will keep same with ac_o_ex
4747 	 * from ext4_mb_initialize_context. Choose ac_g_ex here to keep
4748 	 * consistent with ext4_mb_find_by_goal.
4749 	 */
4750 	start = pa->pa_pstart +
4751 		(ac->ac_g_ex.fe_logical - pa->pa_lstart);
4752 	if (ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex) != start)
4753 		return false;
4754 
4755 	if (ac->ac_g_ex.fe_len > pa->pa_len -
4756 	    EXT4_B2C(sbi, ac->ac_g_ex.fe_logical - pa->pa_lstart))
4757 		return false;
4758 
4759 	return true;
4760 }
4761 
4762 /*
4763  * search goal blocks in preallocated space
4764  */
4765 static noinline_for_stack bool
4766 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
4767 {
4768 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4769 	int order, i;
4770 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4771 	struct ext4_locality_group *lg;
4772 	struct ext4_prealloc_space *tmp_pa = NULL, *cpa = NULL;
4773 	struct rb_node *iter;
4774 	ext4_fsblk_t goal_block;
4775 
4776 	/* only data can be preallocated */
4777 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4778 		return false;
4779 
4780 	/*
4781 	 * first, try per-file preallocation by searching the inode pa rbtree.
4782 	 *
4783 	 * Here, we can't do a direct traversal of the tree because
4784 	 * ext4_mb_discard_group_preallocation() can paralelly mark the pa
4785 	 * deleted and that can cause direct traversal to skip some entries.
4786 	 */
4787 	read_lock(&ei->i_prealloc_lock);
4788 
4789 	if (RB_EMPTY_ROOT(&ei->i_prealloc_node)) {
4790 		goto try_group_pa;
4791 	}
4792 
4793 	/*
4794 	 * Step 1: Find a pa with logical start immediately adjacent to the
4795 	 * original logical start. This could be on the left or right.
4796 	 *
4797 	 * (tmp_pa->pa_lstart never changes so we can skip locking for it).
4798 	 */
4799 	for (iter = ei->i_prealloc_node.rb_node; iter;
4800 	     iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
4801 					    tmp_pa->pa_lstart, iter)) {
4802 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4803 				  pa_node.inode_node);
4804 	}
4805 
4806 	/*
4807 	 * Step 2: The adjacent pa might be to the right of logical start, find
4808 	 * the left adjacent pa. After this step we'd have a valid tmp_pa whose
4809 	 * logical start is towards the left of original request's logical start
4810 	 */
4811 	if (tmp_pa->pa_lstart > ac->ac_o_ex.fe_logical) {
4812 		struct rb_node *tmp;
4813 		tmp = rb_prev(&tmp_pa->pa_node.inode_node);
4814 
4815 		if (tmp) {
4816 			tmp_pa = rb_entry(tmp, struct ext4_prealloc_space,
4817 					    pa_node.inode_node);
4818 		} else {
4819 			/*
4820 			 * If there is no adjacent pa to the left then finding
4821 			 * an overlapping pa is not possible hence stop searching
4822 			 * inode pa tree
4823 			 */
4824 			goto try_group_pa;
4825 		}
4826 	}
4827 
4828 	BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
4829 
4830 	/*
4831 	 * Step 3: If the left adjacent pa is deleted, keep moving left to find
4832 	 * the first non deleted adjacent pa. After this step we should have a
4833 	 * valid tmp_pa which is guaranteed to be non deleted.
4834 	 */
4835 	for (iter = &tmp_pa->pa_node.inode_node;; iter = rb_prev(iter)) {
4836 		if (!iter) {
4837 			/*
4838 			 * no non deleted left adjacent pa, so stop searching
4839 			 * inode pa tree
4840 			 */
4841 			goto try_group_pa;
4842 		}
4843 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4844 				  pa_node.inode_node);
4845 		spin_lock(&tmp_pa->pa_lock);
4846 		if (tmp_pa->pa_deleted == 0) {
4847 			/*
4848 			 * We will keep holding the pa_lock from
4849 			 * this point on because we don't want group discard
4850 			 * to delete this pa underneath us. Since group
4851 			 * discard is anyways an ENOSPC operation it
4852 			 * should be okay for it to wait a few more cycles.
4853 			 */
4854 			break;
4855 		} else {
4856 			spin_unlock(&tmp_pa->pa_lock);
4857 		}
4858 	}
4859 
4860 	BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
4861 	BUG_ON(tmp_pa->pa_deleted == 1);
4862 
4863 	/*
4864 	 * Step 4: We now have the non deleted left adjacent pa. Only this
4865 	 * pa can possibly satisfy the request hence check if it overlaps
4866 	 * original logical start and stop searching if it doesn't.
4867 	 */
4868 	if (ac->ac_o_ex.fe_logical >= pa_logical_end(sbi, tmp_pa)) {
4869 		spin_unlock(&tmp_pa->pa_lock);
4870 		goto try_group_pa;
4871 	}
4872 
4873 	/* non-extent files can't have physical blocks past 2^32 */
4874 	if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
4875 	    (tmp_pa->pa_pstart + EXT4_C2B(sbi, tmp_pa->pa_len) >
4876 	     EXT4_MAX_BLOCK_FILE_PHYS)) {
4877 		/*
4878 		 * Since PAs don't overlap, we won't find any other PA to
4879 		 * satisfy this.
4880 		 */
4881 		spin_unlock(&tmp_pa->pa_lock);
4882 		goto try_group_pa;
4883 	}
4884 
4885 	if (tmp_pa->pa_free && likely(ext4_mb_pa_goal_check(ac, tmp_pa))) {
4886 		atomic_inc(&tmp_pa->pa_count);
4887 		ext4_mb_use_inode_pa(ac, tmp_pa);
4888 		spin_unlock(&tmp_pa->pa_lock);
4889 		read_unlock(&ei->i_prealloc_lock);
4890 		return true;
4891 	} else {
4892 		/*
4893 		 * We found a valid overlapping pa but couldn't use it because
4894 		 * it had no free blocks. This should ideally never happen
4895 		 * because:
4896 		 *
4897 		 * 1. When a new inode pa is added to rbtree it must have
4898 		 *    pa_free > 0 since otherwise we won't actually need
4899 		 *    preallocation.
4900 		 *
4901 		 * 2. An inode pa that is in the rbtree can only have it's
4902 		 *    pa_free become zero when another thread calls:
4903 		 *      ext4_mb_new_blocks
4904 		 *       ext4_mb_use_preallocated
4905 		 *        ext4_mb_use_inode_pa
4906 		 *
4907 		 * 3. Further, after the above calls make pa_free == 0, we will
4908 		 *    immediately remove it from the rbtree in:
4909 		 *      ext4_mb_new_blocks
4910 		 *       ext4_mb_release_context
4911 		 *        ext4_mb_put_pa
4912 		 *
4913 		 * 4. Since the pa_free becoming 0 and pa_free getting removed
4914 		 * from tree both happen in ext4_mb_new_blocks, which is always
4915 		 * called with i_data_sem held for data allocations, we can be
4916 		 * sure that another process will never see a pa in rbtree with
4917 		 * pa_free == 0.
4918 		 */
4919 		WARN_ON_ONCE(tmp_pa->pa_free == 0);
4920 	}
4921 	spin_unlock(&tmp_pa->pa_lock);
4922 try_group_pa:
4923 	read_unlock(&ei->i_prealloc_lock);
4924 
4925 	/* can we use group allocation? */
4926 	if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
4927 		return false;
4928 
4929 	/* inode may have no locality group for some reason */
4930 	lg = ac->ac_lg;
4931 	if (lg == NULL)
4932 		return false;
4933 	order  = fls(ac->ac_o_ex.fe_len) - 1;
4934 	if (order > PREALLOC_TB_SIZE - 1)
4935 		/* The max size of hash table is PREALLOC_TB_SIZE */
4936 		order = PREALLOC_TB_SIZE - 1;
4937 
4938 	goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
4939 	/*
4940 	 * search for the prealloc space that is having
4941 	 * minimal distance from the goal block.
4942 	 */
4943 	for (i = order; i < PREALLOC_TB_SIZE; i++) {
4944 		rcu_read_lock();
4945 		list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[i],
4946 					pa_node.lg_list) {
4947 			spin_lock(&tmp_pa->pa_lock);
4948 			if (tmp_pa->pa_deleted == 0 &&
4949 					tmp_pa->pa_free >= ac->ac_o_ex.fe_len) {
4950 
4951 				cpa = ext4_mb_check_group_pa(goal_block,
4952 								tmp_pa, cpa);
4953 			}
4954 			spin_unlock(&tmp_pa->pa_lock);
4955 		}
4956 		rcu_read_unlock();
4957 	}
4958 	if (cpa) {
4959 		ext4_mb_use_group_pa(ac, cpa);
4960 		return true;
4961 	}
4962 	return false;
4963 }
4964 
4965 /*
4966  * the function goes through all block freed in the group
4967  * but not yet committed and marks them used in in-core bitmap.
4968  * buddy must be generated from this bitmap
4969  * Need to be called with the ext4 group lock held
4970  */
4971 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
4972 						ext4_group_t group)
4973 {
4974 	struct rb_node *n;
4975 	struct ext4_group_info *grp;
4976 	struct ext4_free_data *entry;
4977 
4978 	grp = ext4_get_group_info(sb, group);
4979 	if (!grp)
4980 		return;
4981 	n = rb_first(&(grp->bb_free_root));
4982 
4983 	while (n) {
4984 		entry = rb_entry(n, struct ext4_free_data, efd_node);
4985 		mb_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
4986 		n = rb_next(n);
4987 	}
4988 	return;
4989 }
4990 
4991 /*
4992  * the function goes through all preallocation in this group and marks them
4993  * used in in-core bitmap. buddy must be generated from this bitmap
4994  * Need to be called with ext4 group lock held
4995  */
4996 static noinline_for_stack
4997 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
4998 					ext4_group_t group)
4999 {
5000 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
5001 	struct ext4_prealloc_space *pa;
5002 	struct list_head *cur;
5003 	ext4_group_t groupnr;
5004 	ext4_grpblk_t start;
5005 	int preallocated = 0;
5006 	int len;
5007 
5008 	if (!grp)
5009 		return;
5010 
5011 	/* all form of preallocation discards first load group,
5012 	 * so the only competing code is preallocation use.
5013 	 * we don't need any locking here
5014 	 * notice we do NOT ignore preallocations with pa_deleted
5015 	 * otherwise we could leave used blocks available for
5016 	 * allocation in buddy when concurrent ext4_mb_put_pa()
5017 	 * is dropping preallocation
5018 	 */
5019 	list_for_each(cur, &grp->bb_prealloc_list) {
5020 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
5021 		spin_lock(&pa->pa_lock);
5022 		ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5023 					     &groupnr, &start);
5024 		len = pa->pa_len;
5025 		spin_unlock(&pa->pa_lock);
5026 		if (unlikely(len == 0))
5027 			continue;
5028 		BUG_ON(groupnr != group);
5029 		mb_set_bits(bitmap, start, len);
5030 		preallocated += len;
5031 	}
5032 	mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
5033 }
5034 
5035 static void ext4_mb_mark_pa_deleted(struct super_block *sb,
5036 				    struct ext4_prealloc_space *pa)
5037 {
5038 	struct ext4_inode_info *ei;
5039 
5040 	if (pa->pa_deleted) {
5041 		ext4_warning(sb, "deleted pa, type:%d, pblk:%llu, lblk:%u, len:%d\n",
5042 			     pa->pa_type, pa->pa_pstart, pa->pa_lstart,
5043 			     pa->pa_len);
5044 		return;
5045 	}
5046 
5047 	pa->pa_deleted = 1;
5048 
5049 	if (pa->pa_type == MB_INODE_PA) {
5050 		ei = EXT4_I(pa->pa_inode);
5051 		atomic_dec(&ei->i_prealloc_active);
5052 	}
5053 }
5054 
5055 static inline void ext4_mb_pa_free(struct ext4_prealloc_space *pa)
5056 {
5057 	BUG_ON(!pa);
5058 	BUG_ON(atomic_read(&pa->pa_count));
5059 	BUG_ON(pa->pa_deleted == 0);
5060 	kmem_cache_free(ext4_pspace_cachep, pa);
5061 }
5062 
5063 static void ext4_mb_pa_callback(struct rcu_head *head)
5064 {
5065 	struct ext4_prealloc_space *pa;
5066 
5067 	pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
5068 	ext4_mb_pa_free(pa);
5069 }
5070 
5071 /*
5072  * drops a reference to preallocated space descriptor
5073  * if this was the last reference and the space is consumed
5074  */
5075 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
5076 			struct super_block *sb, struct ext4_prealloc_space *pa)
5077 {
5078 	ext4_group_t grp;
5079 	ext4_fsblk_t grp_blk;
5080 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
5081 
5082 	/* in this short window concurrent discard can set pa_deleted */
5083 	spin_lock(&pa->pa_lock);
5084 	if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
5085 		spin_unlock(&pa->pa_lock);
5086 		return;
5087 	}
5088 
5089 	if (pa->pa_deleted == 1) {
5090 		spin_unlock(&pa->pa_lock);
5091 		return;
5092 	}
5093 
5094 	ext4_mb_mark_pa_deleted(sb, pa);
5095 	spin_unlock(&pa->pa_lock);
5096 
5097 	grp_blk = pa->pa_pstart;
5098 	/*
5099 	 * If doing group-based preallocation, pa_pstart may be in the
5100 	 * next group when pa is used up
5101 	 */
5102 	if (pa->pa_type == MB_GROUP_PA)
5103 		grp_blk--;
5104 
5105 	grp = ext4_get_group_number(sb, grp_blk);
5106 
5107 	/*
5108 	 * possible race:
5109 	 *
5110 	 *  P1 (buddy init)			P2 (regular allocation)
5111 	 *					find block B in PA
5112 	 *  copy on-disk bitmap to buddy
5113 	 *  					mark B in on-disk bitmap
5114 	 *					drop PA from group
5115 	 *  mark all PAs in buddy
5116 	 *
5117 	 * thus, P1 initializes buddy with B available. to prevent this
5118 	 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
5119 	 * against that pair
5120 	 */
5121 	ext4_lock_group(sb, grp);
5122 	list_del(&pa->pa_group_list);
5123 	ext4_unlock_group(sb, grp);
5124 
5125 	if (pa->pa_type == MB_INODE_PA) {
5126 		write_lock(pa->pa_node_lock.inode_lock);
5127 		rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5128 		write_unlock(pa->pa_node_lock.inode_lock);
5129 		ext4_mb_pa_free(pa);
5130 	} else {
5131 		spin_lock(pa->pa_node_lock.lg_lock);
5132 		list_del_rcu(&pa->pa_node.lg_list);
5133 		spin_unlock(pa->pa_node_lock.lg_lock);
5134 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5135 	}
5136 }
5137 
5138 static void ext4_mb_pa_rb_insert(struct rb_root *root, struct rb_node *new)
5139 {
5140 	struct rb_node **iter = &root->rb_node, *parent = NULL;
5141 	struct ext4_prealloc_space *iter_pa, *new_pa;
5142 	ext4_lblk_t iter_start, new_start;
5143 
5144 	while (*iter) {
5145 		iter_pa = rb_entry(*iter, struct ext4_prealloc_space,
5146 				   pa_node.inode_node);
5147 		new_pa = rb_entry(new, struct ext4_prealloc_space,
5148 				   pa_node.inode_node);
5149 		iter_start = iter_pa->pa_lstart;
5150 		new_start = new_pa->pa_lstart;
5151 
5152 		parent = *iter;
5153 		if (new_start < iter_start)
5154 			iter = &((*iter)->rb_left);
5155 		else
5156 			iter = &((*iter)->rb_right);
5157 	}
5158 
5159 	rb_link_node(new, parent, iter);
5160 	rb_insert_color(new, root);
5161 }
5162 
5163 /*
5164  * creates new preallocated space for given inode
5165  */
5166 static noinline_for_stack void
5167 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
5168 {
5169 	struct super_block *sb = ac->ac_sb;
5170 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5171 	struct ext4_prealloc_space *pa;
5172 	struct ext4_group_info *grp;
5173 	struct ext4_inode_info *ei;
5174 
5175 	/* preallocate only when found space is larger then requested */
5176 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5177 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5178 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
5179 	BUG_ON(ac->ac_pa == NULL);
5180 
5181 	pa = ac->ac_pa;
5182 
5183 	if (ac->ac_b_ex.fe_len < ac->ac_orig_goal_len) {
5184 		struct ext4_free_extent ex = {
5185 			.fe_logical = ac->ac_g_ex.fe_logical,
5186 			.fe_len = ac->ac_orig_goal_len,
5187 		};
5188 		loff_t orig_goal_end = extent_logical_end(sbi, &ex);
5189 
5190 		/* we can't allocate as much as normalizer wants.
5191 		 * so, found space must get proper lstart
5192 		 * to cover original request */
5193 		BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
5194 		BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
5195 
5196 		/*
5197 		 * Use the below logic for adjusting best extent as it keeps
5198 		 * fragmentation in check while ensuring logical range of best
5199 		 * extent doesn't overflow out of goal extent:
5200 		 *
5201 		 * 1. Check if best ex can be kept at end of goal (before
5202 		 *    cr_best_avail trimmed it) and still cover original start
5203 		 * 2. Else, check if best ex can be kept at start of goal and
5204 		 *    still cover original start
5205 		 * 3. Else, keep the best ex at start of original request.
5206 		 */
5207 		ex.fe_len = ac->ac_b_ex.fe_len;
5208 
5209 		ex.fe_logical = orig_goal_end - EXT4_C2B(sbi, ex.fe_len);
5210 		if (ac->ac_o_ex.fe_logical >= ex.fe_logical)
5211 			goto adjust_bex;
5212 
5213 		ex.fe_logical = ac->ac_g_ex.fe_logical;
5214 		if (ac->ac_o_ex.fe_logical < extent_logical_end(sbi, &ex))
5215 			goto adjust_bex;
5216 
5217 		ex.fe_logical = ac->ac_o_ex.fe_logical;
5218 adjust_bex:
5219 		ac->ac_b_ex.fe_logical = ex.fe_logical;
5220 
5221 		BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
5222 		BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
5223 		BUG_ON(extent_logical_end(sbi, &ex) > orig_goal_end);
5224 	}
5225 
5226 	pa->pa_lstart = ac->ac_b_ex.fe_logical;
5227 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5228 	pa->pa_len = ac->ac_b_ex.fe_len;
5229 	pa->pa_free = pa->pa_len;
5230 	spin_lock_init(&pa->pa_lock);
5231 	INIT_LIST_HEAD(&pa->pa_group_list);
5232 	pa->pa_deleted = 0;
5233 	pa->pa_type = MB_INODE_PA;
5234 
5235 	mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5236 		 pa->pa_len, pa->pa_lstart);
5237 	trace_ext4_mb_new_inode_pa(ac, pa);
5238 
5239 	atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
5240 	ext4_mb_use_inode_pa(ac, pa);
5241 
5242 	ei = EXT4_I(ac->ac_inode);
5243 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
5244 	if (!grp)
5245 		return;
5246 
5247 	pa->pa_node_lock.inode_lock = &ei->i_prealloc_lock;
5248 	pa->pa_inode = ac->ac_inode;
5249 
5250 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5251 
5252 	write_lock(pa->pa_node_lock.inode_lock);
5253 	ext4_mb_pa_rb_insert(&ei->i_prealloc_node, &pa->pa_node.inode_node);
5254 	write_unlock(pa->pa_node_lock.inode_lock);
5255 	atomic_inc(&ei->i_prealloc_active);
5256 }
5257 
5258 /*
5259  * creates new preallocated space for locality group inodes belongs to
5260  */
5261 static noinline_for_stack void
5262 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
5263 {
5264 	struct super_block *sb = ac->ac_sb;
5265 	struct ext4_locality_group *lg;
5266 	struct ext4_prealloc_space *pa;
5267 	struct ext4_group_info *grp;
5268 
5269 	/* preallocate only when found space is larger then requested */
5270 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5271 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5272 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
5273 	BUG_ON(ac->ac_pa == NULL);
5274 
5275 	pa = ac->ac_pa;
5276 
5277 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5278 	pa->pa_lstart = pa->pa_pstart;
5279 	pa->pa_len = ac->ac_b_ex.fe_len;
5280 	pa->pa_free = pa->pa_len;
5281 	spin_lock_init(&pa->pa_lock);
5282 	INIT_LIST_HEAD(&pa->pa_node.lg_list);
5283 	INIT_LIST_HEAD(&pa->pa_group_list);
5284 	pa->pa_deleted = 0;
5285 	pa->pa_type = MB_GROUP_PA;
5286 
5287 	mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5288 		 pa->pa_len, pa->pa_lstart);
5289 	trace_ext4_mb_new_group_pa(ac, pa);
5290 
5291 	ext4_mb_use_group_pa(ac, pa);
5292 	atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
5293 
5294 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
5295 	if (!grp)
5296 		return;
5297 	lg = ac->ac_lg;
5298 	BUG_ON(lg == NULL);
5299 
5300 	pa->pa_node_lock.lg_lock = &lg->lg_prealloc_lock;
5301 	pa->pa_inode = NULL;
5302 
5303 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5304 
5305 	/*
5306 	 * We will later add the new pa to the right bucket
5307 	 * after updating the pa_free in ext4_mb_release_context
5308 	 */
5309 }
5310 
5311 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
5312 {
5313 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
5314 		ext4_mb_new_group_pa(ac);
5315 	else
5316 		ext4_mb_new_inode_pa(ac);
5317 }
5318 
5319 /*
5320  * finds all unused blocks in on-disk bitmap, frees them in
5321  * in-core bitmap and buddy.
5322  * @pa must be unlinked from inode and group lists, so that
5323  * nobody else can find/use it.
5324  * the caller MUST hold group/inode locks.
5325  * TODO: optimize the case when there are no in-core structures yet
5326  */
5327 static noinline_for_stack int
5328 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
5329 			struct ext4_prealloc_space *pa)
5330 {
5331 	struct super_block *sb = e4b->bd_sb;
5332 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5333 	unsigned int end;
5334 	unsigned int next;
5335 	ext4_group_t group;
5336 	ext4_grpblk_t bit;
5337 	unsigned long long grp_blk_start;
5338 	int free = 0;
5339 
5340 	BUG_ON(pa->pa_deleted == 0);
5341 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
5342 	grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
5343 	BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
5344 	end = bit + pa->pa_len;
5345 
5346 	while (bit < end) {
5347 		bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
5348 		if (bit >= end)
5349 			break;
5350 		next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
5351 		mb_debug(sb, "free preallocated %u/%u in group %u\n",
5352 			 (unsigned) ext4_group_first_block_no(sb, group) + bit,
5353 			 (unsigned) next - bit, (unsigned) group);
5354 		free += next - bit;
5355 
5356 		trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
5357 		trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
5358 						    EXT4_C2B(sbi, bit)),
5359 					       next - bit);
5360 		mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
5361 		bit = next + 1;
5362 	}
5363 	if (free != pa->pa_free) {
5364 		ext4_msg(e4b->bd_sb, KERN_CRIT,
5365 			 "pa %p: logic %lu, phys. %lu, len %d",
5366 			 pa, (unsigned long) pa->pa_lstart,
5367 			 (unsigned long) pa->pa_pstart,
5368 			 pa->pa_len);
5369 		ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
5370 					free, pa->pa_free);
5371 		/*
5372 		 * pa is already deleted so we use the value obtained
5373 		 * from the bitmap and continue.
5374 		 */
5375 	}
5376 	atomic_add(free, &sbi->s_mb_discarded);
5377 
5378 	return 0;
5379 }
5380 
5381 static noinline_for_stack int
5382 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
5383 				struct ext4_prealloc_space *pa)
5384 {
5385 	struct super_block *sb = e4b->bd_sb;
5386 	ext4_group_t group;
5387 	ext4_grpblk_t bit;
5388 
5389 	trace_ext4_mb_release_group_pa(sb, pa);
5390 	BUG_ON(pa->pa_deleted == 0);
5391 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
5392 	if (unlikely(group != e4b->bd_group && pa->pa_len != 0)) {
5393 		ext4_warning(sb, "bad group: expected %u, group %u, pa_start %llu",
5394 			     e4b->bd_group, group, pa->pa_pstart);
5395 		return 0;
5396 	}
5397 	mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
5398 	atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
5399 	trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
5400 
5401 	return 0;
5402 }
5403 
5404 /*
5405  * releases all preallocations in given group
5406  *
5407  * first, we need to decide discard policy:
5408  * - when do we discard
5409  *   1) ENOSPC
5410  * - how many do we discard
5411  *   1) how many requested
5412  */
5413 static noinline_for_stack int
5414 ext4_mb_discard_group_preallocations(struct super_block *sb,
5415 				     ext4_group_t group, int *busy)
5416 {
5417 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
5418 	struct buffer_head *bitmap_bh = NULL;
5419 	struct ext4_prealloc_space *pa, *tmp;
5420 	struct list_head list;
5421 	struct ext4_buddy e4b;
5422 	struct ext4_inode_info *ei;
5423 	int err;
5424 	int free = 0;
5425 
5426 	if (!grp)
5427 		return 0;
5428 	mb_debug(sb, "discard preallocation for group %u\n", group);
5429 	if (list_empty(&grp->bb_prealloc_list))
5430 		goto out_dbg;
5431 
5432 	bitmap_bh = ext4_read_block_bitmap(sb, group);
5433 	if (IS_ERR(bitmap_bh)) {
5434 		err = PTR_ERR(bitmap_bh);
5435 		ext4_error_err(sb, -err,
5436 			       "Error %d reading block bitmap for %u",
5437 			       err, group);
5438 		goto out_dbg;
5439 	}
5440 
5441 	err = ext4_mb_load_buddy(sb, group, &e4b);
5442 	if (err) {
5443 		ext4_warning(sb, "Error %d loading buddy information for %u",
5444 			     err, group);
5445 		put_bh(bitmap_bh);
5446 		goto out_dbg;
5447 	}
5448 
5449 	INIT_LIST_HEAD(&list);
5450 	ext4_lock_group(sb, group);
5451 	list_for_each_entry_safe(pa, tmp,
5452 				&grp->bb_prealloc_list, pa_group_list) {
5453 		spin_lock(&pa->pa_lock);
5454 		if (atomic_read(&pa->pa_count)) {
5455 			spin_unlock(&pa->pa_lock);
5456 			*busy = 1;
5457 			continue;
5458 		}
5459 		if (pa->pa_deleted) {
5460 			spin_unlock(&pa->pa_lock);
5461 			continue;
5462 		}
5463 
5464 		/* seems this one can be freed ... */
5465 		ext4_mb_mark_pa_deleted(sb, pa);
5466 
5467 		if (!free)
5468 			this_cpu_inc(discard_pa_seq);
5469 
5470 		/* we can trust pa_free ... */
5471 		free += pa->pa_free;
5472 
5473 		spin_unlock(&pa->pa_lock);
5474 
5475 		list_del(&pa->pa_group_list);
5476 		list_add(&pa->u.pa_tmp_list, &list);
5477 	}
5478 
5479 	/* now free all selected PAs */
5480 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5481 
5482 		/* remove from object (inode or locality group) */
5483 		if (pa->pa_type == MB_GROUP_PA) {
5484 			spin_lock(pa->pa_node_lock.lg_lock);
5485 			list_del_rcu(&pa->pa_node.lg_list);
5486 			spin_unlock(pa->pa_node_lock.lg_lock);
5487 		} else {
5488 			write_lock(pa->pa_node_lock.inode_lock);
5489 			ei = EXT4_I(pa->pa_inode);
5490 			rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5491 			write_unlock(pa->pa_node_lock.inode_lock);
5492 		}
5493 
5494 		list_del(&pa->u.pa_tmp_list);
5495 
5496 		if (pa->pa_type == MB_GROUP_PA) {
5497 			ext4_mb_release_group_pa(&e4b, pa);
5498 			call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5499 		} else {
5500 			ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
5501 			ext4_mb_pa_free(pa);
5502 		}
5503 	}
5504 
5505 	ext4_unlock_group(sb, group);
5506 	ext4_mb_unload_buddy(&e4b);
5507 	put_bh(bitmap_bh);
5508 out_dbg:
5509 	mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
5510 		 free, group, grp->bb_free);
5511 	return free;
5512 }
5513 
5514 /*
5515  * releases all non-used preallocated blocks for given inode
5516  *
5517  * It's important to discard preallocations under i_data_sem
5518  * We don't want another block to be served from the prealloc
5519  * space when we are discarding the inode prealloc space.
5520  *
5521  * FIXME!! Make sure it is valid at all the call sites
5522  */
5523 void ext4_discard_preallocations(struct inode *inode, unsigned int needed)
5524 {
5525 	struct ext4_inode_info *ei = EXT4_I(inode);
5526 	struct super_block *sb = inode->i_sb;
5527 	struct buffer_head *bitmap_bh = NULL;
5528 	struct ext4_prealloc_space *pa, *tmp;
5529 	ext4_group_t group = 0;
5530 	struct list_head list;
5531 	struct ext4_buddy e4b;
5532 	struct rb_node *iter;
5533 	int err;
5534 
5535 	if (!S_ISREG(inode->i_mode)) {
5536 		return;
5537 	}
5538 
5539 	if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
5540 		return;
5541 
5542 	mb_debug(sb, "discard preallocation for inode %lu\n",
5543 		 inode->i_ino);
5544 	trace_ext4_discard_preallocations(inode,
5545 			atomic_read(&ei->i_prealloc_active), needed);
5546 
5547 	INIT_LIST_HEAD(&list);
5548 
5549 	if (needed == 0)
5550 		needed = UINT_MAX;
5551 
5552 repeat:
5553 	/* first, collect all pa's in the inode */
5554 	write_lock(&ei->i_prealloc_lock);
5555 	for (iter = rb_first(&ei->i_prealloc_node); iter && needed;
5556 	     iter = rb_next(iter)) {
5557 		pa = rb_entry(iter, struct ext4_prealloc_space,
5558 			      pa_node.inode_node);
5559 		BUG_ON(pa->pa_node_lock.inode_lock != &ei->i_prealloc_lock);
5560 
5561 		spin_lock(&pa->pa_lock);
5562 		if (atomic_read(&pa->pa_count)) {
5563 			/* this shouldn't happen often - nobody should
5564 			 * use preallocation while we're discarding it */
5565 			spin_unlock(&pa->pa_lock);
5566 			write_unlock(&ei->i_prealloc_lock);
5567 			ext4_msg(sb, KERN_ERR,
5568 				 "uh-oh! used pa while discarding");
5569 			WARN_ON(1);
5570 			schedule_timeout_uninterruptible(HZ);
5571 			goto repeat;
5572 
5573 		}
5574 		if (pa->pa_deleted == 0) {
5575 			ext4_mb_mark_pa_deleted(sb, pa);
5576 			spin_unlock(&pa->pa_lock);
5577 			rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5578 			list_add(&pa->u.pa_tmp_list, &list);
5579 			needed--;
5580 			continue;
5581 		}
5582 
5583 		/* someone is deleting pa right now */
5584 		spin_unlock(&pa->pa_lock);
5585 		write_unlock(&ei->i_prealloc_lock);
5586 
5587 		/* we have to wait here because pa_deleted
5588 		 * doesn't mean pa is already unlinked from
5589 		 * the list. as we might be called from
5590 		 * ->clear_inode() the inode will get freed
5591 		 * and concurrent thread which is unlinking
5592 		 * pa from inode's list may access already
5593 		 * freed memory, bad-bad-bad */
5594 
5595 		/* XXX: if this happens too often, we can
5596 		 * add a flag to force wait only in case
5597 		 * of ->clear_inode(), but not in case of
5598 		 * regular truncate */
5599 		schedule_timeout_uninterruptible(HZ);
5600 		goto repeat;
5601 	}
5602 	write_unlock(&ei->i_prealloc_lock);
5603 
5604 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5605 		BUG_ON(pa->pa_type != MB_INODE_PA);
5606 		group = ext4_get_group_number(sb, pa->pa_pstart);
5607 
5608 		err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
5609 					     GFP_NOFS|__GFP_NOFAIL);
5610 		if (err) {
5611 			ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
5612 				       err, group);
5613 			continue;
5614 		}
5615 
5616 		bitmap_bh = ext4_read_block_bitmap(sb, group);
5617 		if (IS_ERR(bitmap_bh)) {
5618 			err = PTR_ERR(bitmap_bh);
5619 			ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
5620 				       err, group);
5621 			ext4_mb_unload_buddy(&e4b);
5622 			continue;
5623 		}
5624 
5625 		ext4_lock_group(sb, group);
5626 		list_del(&pa->pa_group_list);
5627 		ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
5628 		ext4_unlock_group(sb, group);
5629 
5630 		ext4_mb_unload_buddy(&e4b);
5631 		put_bh(bitmap_bh);
5632 
5633 		list_del(&pa->u.pa_tmp_list);
5634 		ext4_mb_pa_free(pa);
5635 	}
5636 }
5637 
5638 static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
5639 {
5640 	struct ext4_prealloc_space *pa;
5641 
5642 	BUG_ON(ext4_pspace_cachep == NULL);
5643 	pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
5644 	if (!pa)
5645 		return -ENOMEM;
5646 	atomic_set(&pa->pa_count, 1);
5647 	ac->ac_pa = pa;
5648 	return 0;
5649 }
5650 
5651 static void ext4_mb_pa_put_free(struct ext4_allocation_context *ac)
5652 {
5653 	struct ext4_prealloc_space *pa = ac->ac_pa;
5654 
5655 	BUG_ON(!pa);
5656 	ac->ac_pa = NULL;
5657 	WARN_ON(!atomic_dec_and_test(&pa->pa_count));
5658 	/*
5659 	 * current function is only called due to an error or due to
5660 	 * len of found blocks < len of requested blocks hence the PA has not
5661 	 * been added to grp->bb_prealloc_list. So we don't need to lock it
5662 	 */
5663 	pa->pa_deleted = 1;
5664 	ext4_mb_pa_free(pa);
5665 }
5666 
5667 #ifdef CONFIG_EXT4_DEBUG
5668 static inline void ext4_mb_show_pa(struct super_block *sb)
5669 {
5670 	ext4_group_t i, ngroups;
5671 
5672 	if (ext4_forced_shutdown(sb))
5673 		return;
5674 
5675 	ngroups = ext4_get_groups_count(sb);
5676 	mb_debug(sb, "groups: ");
5677 	for (i = 0; i < ngroups; i++) {
5678 		struct ext4_group_info *grp = ext4_get_group_info(sb, i);
5679 		struct ext4_prealloc_space *pa;
5680 		ext4_grpblk_t start;
5681 		struct list_head *cur;
5682 
5683 		if (!grp)
5684 			continue;
5685 		ext4_lock_group(sb, i);
5686 		list_for_each(cur, &grp->bb_prealloc_list) {
5687 			pa = list_entry(cur, struct ext4_prealloc_space,
5688 					pa_group_list);
5689 			spin_lock(&pa->pa_lock);
5690 			ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5691 						     NULL, &start);
5692 			spin_unlock(&pa->pa_lock);
5693 			mb_debug(sb, "PA:%u:%d:%d\n", i, start,
5694 				 pa->pa_len);
5695 		}
5696 		ext4_unlock_group(sb, i);
5697 		mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
5698 			 grp->bb_fragments);
5699 	}
5700 }
5701 
5702 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5703 {
5704 	struct super_block *sb = ac->ac_sb;
5705 
5706 	if (ext4_forced_shutdown(sb))
5707 		return;
5708 
5709 	mb_debug(sb, "Can't allocate:"
5710 			" Allocation context details:");
5711 	mb_debug(sb, "status %u flags 0x%x",
5712 			ac->ac_status, ac->ac_flags);
5713 	mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
5714 			"goal %lu/%lu/%lu@%lu, "
5715 			"best %lu/%lu/%lu@%lu cr %d",
5716 			(unsigned long)ac->ac_o_ex.fe_group,
5717 			(unsigned long)ac->ac_o_ex.fe_start,
5718 			(unsigned long)ac->ac_o_ex.fe_len,
5719 			(unsigned long)ac->ac_o_ex.fe_logical,
5720 			(unsigned long)ac->ac_g_ex.fe_group,
5721 			(unsigned long)ac->ac_g_ex.fe_start,
5722 			(unsigned long)ac->ac_g_ex.fe_len,
5723 			(unsigned long)ac->ac_g_ex.fe_logical,
5724 			(unsigned long)ac->ac_b_ex.fe_group,
5725 			(unsigned long)ac->ac_b_ex.fe_start,
5726 			(unsigned long)ac->ac_b_ex.fe_len,
5727 			(unsigned long)ac->ac_b_ex.fe_logical,
5728 			(int)ac->ac_criteria);
5729 	mb_debug(sb, "%u found", ac->ac_found);
5730 	mb_debug(sb, "used pa: %s, ", ac->ac_pa ? "yes" : "no");
5731 	if (ac->ac_pa)
5732 		mb_debug(sb, "pa_type %s\n", ac->ac_pa->pa_type == MB_GROUP_PA ?
5733 			 "group pa" : "inode pa");
5734 	ext4_mb_show_pa(sb);
5735 }
5736 #else
5737 static inline void ext4_mb_show_pa(struct super_block *sb)
5738 {
5739 	return;
5740 }
5741 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5742 {
5743 	ext4_mb_show_pa(ac->ac_sb);
5744 	return;
5745 }
5746 #endif
5747 
5748 /*
5749  * We use locality group preallocation for small size file. The size of the
5750  * file is determined by the current size or the resulting size after
5751  * allocation which ever is larger
5752  *
5753  * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
5754  */
5755 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
5756 {
5757 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
5758 	int bsbits = ac->ac_sb->s_blocksize_bits;
5759 	loff_t size, isize;
5760 	bool inode_pa_eligible, group_pa_eligible;
5761 
5762 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
5763 		return;
5764 
5765 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
5766 		return;
5767 
5768 	group_pa_eligible = sbi->s_mb_group_prealloc > 0;
5769 	inode_pa_eligible = true;
5770 	size = extent_logical_end(sbi, &ac->ac_o_ex);
5771 	isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
5772 		>> bsbits;
5773 
5774 	/* No point in using inode preallocation for closed files */
5775 	if ((size == isize) && !ext4_fs_is_busy(sbi) &&
5776 	    !inode_is_open_for_write(ac->ac_inode))
5777 		inode_pa_eligible = false;
5778 
5779 	size = max(size, isize);
5780 	/* Don't use group allocation for large files */
5781 	if (size > sbi->s_mb_stream_request)
5782 		group_pa_eligible = false;
5783 
5784 	if (!group_pa_eligible) {
5785 		if (inode_pa_eligible)
5786 			ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
5787 		else
5788 			ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
5789 		return;
5790 	}
5791 
5792 	BUG_ON(ac->ac_lg != NULL);
5793 	/*
5794 	 * locality group prealloc space are per cpu. The reason for having
5795 	 * per cpu locality group is to reduce the contention between block
5796 	 * request from multiple CPUs.
5797 	 */
5798 	ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
5799 
5800 	/* we're going to use group allocation */
5801 	ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
5802 
5803 	/* serialize all allocations in the group */
5804 	mutex_lock(&ac->ac_lg->lg_mutex);
5805 }
5806 
5807 static noinline_for_stack void
5808 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
5809 				struct ext4_allocation_request *ar)
5810 {
5811 	struct super_block *sb = ar->inode->i_sb;
5812 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5813 	struct ext4_super_block *es = sbi->s_es;
5814 	ext4_group_t group;
5815 	unsigned int len;
5816 	ext4_fsblk_t goal;
5817 	ext4_grpblk_t block;
5818 
5819 	/* we can't allocate > group size */
5820 	len = ar->len;
5821 
5822 	/* just a dirty hack to filter too big requests  */
5823 	if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
5824 		len = EXT4_CLUSTERS_PER_GROUP(sb);
5825 
5826 	/* start searching from the goal */
5827 	goal = ar->goal;
5828 	if (goal < le32_to_cpu(es->s_first_data_block) ||
5829 			goal >= ext4_blocks_count(es))
5830 		goal = le32_to_cpu(es->s_first_data_block);
5831 	ext4_get_group_no_and_offset(sb, goal, &group, &block);
5832 
5833 	/* set up allocation goals */
5834 	ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
5835 	ac->ac_status = AC_STATUS_CONTINUE;
5836 	ac->ac_sb = sb;
5837 	ac->ac_inode = ar->inode;
5838 	ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
5839 	ac->ac_o_ex.fe_group = group;
5840 	ac->ac_o_ex.fe_start = block;
5841 	ac->ac_o_ex.fe_len = len;
5842 	ac->ac_g_ex = ac->ac_o_ex;
5843 	ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
5844 	ac->ac_flags = ar->flags;
5845 
5846 	/* we have to define context: we'll work with a file or
5847 	 * locality group. this is a policy, actually */
5848 	ext4_mb_group_or_file(ac);
5849 
5850 	mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
5851 			"left: %u/%u, right %u/%u to %swritable\n",
5852 			(unsigned) ar->len, (unsigned) ar->logical,
5853 			(unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
5854 			(unsigned) ar->lleft, (unsigned) ar->pleft,
5855 			(unsigned) ar->lright, (unsigned) ar->pright,
5856 			inode_is_open_for_write(ar->inode) ? "" : "non-");
5857 }
5858 
5859 static noinline_for_stack void
5860 ext4_mb_discard_lg_preallocations(struct super_block *sb,
5861 					struct ext4_locality_group *lg,
5862 					int order, int total_entries)
5863 {
5864 	ext4_group_t group = 0;
5865 	struct ext4_buddy e4b;
5866 	struct list_head discard_list;
5867 	struct ext4_prealloc_space *pa, *tmp;
5868 
5869 	mb_debug(sb, "discard locality group preallocation\n");
5870 
5871 	INIT_LIST_HEAD(&discard_list);
5872 
5873 	spin_lock(&lg->lg_prealloc_lock);
5874 	list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
5875 				pa_node.lg_list,
5876 				lockdep_is_held(&lg->lg_prealloc_lock)) {
5877 		spin_lock(&pa->pa_lock);
5878 		if (atomic_read(&pa->pa_count)) {
5879 			/*
5880 			 * This is the pa that we just used
5881 			 * for block allocation. So don't
5882 			 * free that
5883 			 */
5884 			spin_unlock(&pa->pa_lock);
5885 			continue;
5886 		}
5887 		if (pa->pa_deleted) {
5888 			spin_unlock(&pa->pa_lock);
5889 			continue;
5890 		}
5891 		/* only lg prealloc space */
5892 		BUG_ON(pa->pa_type != MB_GROUP_PA);
5893 
5894 		/* seems this one can be freed ... */
5895 		ext4_mb_mark_pa_deleted(sb, pa);
5896 		spin_unlock(&pa->pa_lock);
5897 
5898 		list_del_rcu(&pa->pa_node.lg_list);
5899 		list_add(&pa->u.pa_tmp_list, &discard_list);
5900 
5901 		total_entries--;
5902 		if (total_entries <= 5) {
5903 			/*
5904 			 * we want to keep only 5 entries
5905 			 * allowing it to grow to 8. This
5906 			 * mak sure we don't call discard
5907 			 * soon for this list.
5908 			 */
5909 			break;
5910 		}
5911 	}
5912 	spin_unlock(&lg->lg_prealloc_lock);
5913 
5914 	list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
5915 		int err;
5916 
5917 		group = ext4_get_group_number(sb, pa->pa_pstart);
5918 		err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
5919 					     GFP_NOFS|__GFP_NOFAIL);
5920 		if (err) {
5921 			ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
5922 				       err, group);
5923 			continue;
5924 		}
5925 		ext4_lock_group(sb, group);
5926 		list_del(&pa->pa_group_list);
5927 		ext4_mb_release_group_pa(&e4b, pa);
5928 		ext4_unlock_group(sb, group);
5929 
5930 		ext4_mb_unload_buddy(&e4b);
5931 		list_del(&pa->u.pa_tmp_list);
5932 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5933 	}
5934 }
5935 
5936 /*
5937  * We have incremented pa_count. So it cannot be freed at this
5938  * point. Also we hold lg_mutex. So no parallel allocation is
5939  * possible from this lg. That means pa_free cannot be updated.
5940  *
5941  * A parallel ext4_mb_discard_group_preallocations is possible.
5942  * which can cause the lg_prealloc_list to be updated.
5943  */
5944 
5945 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
5946 {
5947 	int order, added = 0, lg_prealloc_count = 1;
5948 	struct super_block *sb = ac->ac_sb;
5949 	struct ext4_locality_group *lg = ac->ac_lg;
5950 	struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
5951 
5952 	order = fls(pa->pa_free) - 1;
5953 	if (order > PREALLOC_TB_SIZE - 1)
5954 		/* The max size of hash table is PREALLOC_TB_SIZE */
5955 		order = PREALLOC_TB_SIZE - 1;
5956 	/* Add the prealloc space to lg */
5957 	spin_lock(&lg->lg_prealloc_lock);
5958 	list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
5959 				pa_node.lg_list,
5960 				lockdep_is_held(&lg->lg_prealloc_lock)) {
5961 		spin_lock(&tmp_pa->pa_lock);
5962 		if (tmp_pa->pa_deleted) {
5963 			spin_unlock(&tmp_pa->pa_lock);
5964 			continue;
5965 		}
5966 		if (!added && pa->pa_free < tmp_pa->pa_free) {
5967 			/* Add to the tail of the previous entry */
5968 			list_add_tail_rcu(&pa->pa_node.lg_list,
5969 						&tmp_pa->pa_node.lg_list);
5970 			added = 1;
5971 			/*
5972 			 * we want to count the total
5973 			 * number of entries in the list
5974 			 */
5975 		}
5976 		spin_unlock(&tmp_pa->pa_lock);
5977 		lg_prealloc_count++;
5978 	}
5979 	if (!added)
5980 		list_add_tail_rcu(&pa->pa_node.lg_list,
5981 					&lg->lg_prealloc_list[order]);
5982 	spin_unlock(&lg->lg_prealloc_lock);
5983 
5984 	/* Now trim the list to be not more than 8 elements */
5985 	if (lg_prealloc_count > 8) {
5986 		ext4_mb_discard_lg_preallocations(sb, lg,
5987 						  order, lg_prealloc_count);
5988 		return;
5989 	}
5990 	return ;
5991 }
5992 
5993 /*
5994  * release all resource we used in allocation
5995  */
5996 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
5997 {
5998 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
5999 	struct ext4_prealloc_space *pa = ac->ac_pa;
6000 	if (pa) {
6001 		if (pa->pa_type == MB_GROUP_PA) {
6002 			/* see comment in ext4_mb_use_group_pa() */
6003 			spin_lock(&pa->pa_lock);
6004 			pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
6005 			pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
6006 			pa->pa_free -= ac->ac_b_ex.fe_len;
6007 			pa->pa_len -= ac->ac_b_ex.fe_len;
6008 			spin_unlock(&pa->pa_lock);
6009 
6010 			/*
6011 			 * We want to add the pa to the right bucket.
6012 			 * Remove it from the list and while adding
6013 			 * make sure the list to which we are adding
6014 			 * doesn't grow big.
6015 			 */
6016 			if (likely(pa->pa_free)) {
6017 				spin_lock(pa->pa_node_lock.lg_lock);
6018 				list_del_rcu(&pa->pa_node.lg_list);
6019 				spin_unlock(pa->pa_node_lock.lg_lock);
6020 				ext4_mb_add_n_trim(ac);
6021 			}
6022 		}
6023 
6024 		ext4_mb_put_pa(ac, ac->ac_sb, pa);
6025 	}
6026 	if (ac->ac_bitmap_page)
6027 		put_page(ac->ac_bitmap_page);
6028 	if (ac->ac_buddy_page)
6029 		put_page(ac->ac_buddy_page);
6030 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
6031 		mutex_unlock(&ac->ac_lg->lg_mutex);
6032 	ext4_mb_collect_stats(ac);
6033 	return 0;
6034 }
6035 
6036 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
6037 {
6038 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
6039 	int ret;
6040 	int freed = 0, busy = 0;
6041 	int retry = 0;
6042 
6043 	trace_ext4_mb_discard_preallocations(sb, needed);
6044 
6045 	if (needed == 0)
6046 		needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
6047  repeat:
6048 	for (i = 0; i < ngroups && needed > 0; i++) {
6049 		ret = ext4_mb_discard_group_preallocations(sb, i, &busy);
6050 		freed += ret;
6051 		needed -= ret;
6052 		cond_resched();
6053 	}
6054 
6055 	if (needed > 0 && busy && ++retry < 3) {
6056 		busy = 0;
6057 		goto repeat;
6058 	}
6059 
6060 	return freed;
6061 }
6062 
6063 static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
6064 			struct ext4_allocation_context *ac, u64 *seq)
6065 {
6066 	int freed;
6067 	u64 seq_retry = 0;
6068 	bool ret = false;
6069 
6070 	freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
6071 	if (freed) {
6072 		ret = true;
6073 		goto out_dbg;
6074 	}
6075 	seq_retry = ext4_get_discard_pa_seq_sum();
6076 	if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
6077 		ac->ac_flags |= EXT4_MB_STRICT_CHECK;
6078 		*seq = seq_retry;
6079 		ret = true;
6080 	}
6081 
6082 out_dbg:
6083 	mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
6084 	return ret;
6085 }
6086 
6087 /*
6088  * Simple allocator for Ext4 fast commit replay path. It searches for blocks
6089  * linearly starting at the goal block and also excludes the blocks which
6090  * are going to be in use after fast commit replay.
6091  */
6092 static ext4_fsblk_t
6093 ext4_mb_new_blocks_simple(struct ext4_allocation_request *ar, int *errp)
6094 {
6095 	struct buffer_head *bitmap_bh;
6096 	struct super_block *sb = ar->inode->i_sb;
6097 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6098 	ext4_group_t group, nr;
6099 	ext4_grpblk_t blkoff;
6100 	ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
6101 	ext4_grpblk_t i = 0;
6102 	ext4_fsblk_t goal, block;
6103 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
6104 
6105 	goal = ar->goal;
6106 	if (goal < le32_to_cpu(es->s_first_data_block) ||
6107 			goal >= ext4_blocks_count(es))
6108 		goal = le32_to_cpu(es->s_first_data_block);
6109 
6110 	ar->len = 0;
6111 	ext4_get_group_no_and_offset(sb, goal, &group, &blkoff);
6112 	for (nr = ext4_get_groups_count(sb); nr > 0; nr--) {
6113 		bitmap_bh = ext4_read_block_bitmap(sb, group);
6114 		if (IS_ERR(bitmap_bh)) {
6115 			*errp = PTR_ERR(bitmap_bh);
6116 			pr_warn("Failed to read block bitmap\n");
6117 			return 0;
6118 		}
6119 
6120 		while (1) {
6121 			i = mb_find_next_zero_bit(bitmap_bh->b_data, max,
6122 						blkoff);
6123 			if (i >= max)
6124 				break;
6125 			if (ext4_fc_replay_check_excluded(sb,
6126 				ext4_group_first_block_no(sb, group) +
6127 				EXT4_C2B(sbi, i))) {
6128 				blkoff = i + 1;
6129 			} else
6130 				break;
6131 		}
6132 		brelse(bitmap_bh);
6133 		if (i < max)
6134 			break;
6135 
6136 		if (++group >= ext4_get_groups_count(sb))
6137 			group = 0;
6138 
6139 		blkoff = 0;
6140 	}
6141 
6142 	if (i >= max) {
6143 		*errp = -ENOSPC;
6144 		return 0;
6145 	}
6146 
6147 	block = ext4_group_first_block_no(sb, group) + EXT4_C2B(sbi, i);
6148 	ext4_mb_mark_bb(sb, block, 1, 1);
6149 	ar->len = 1;
6150 
6151 	return block;
6152 }
6153 
6154 /*
6155  * Main entry point into mballoc to allocate blocks
6156  * it tries to use preallocation first, then falls back
6157  * to usual allocation
6158  */
6159 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
6160 				struct ext4_allocation_request *ar, int *errp)
6161 {
6162 	struct ext4_allocation_context *ac = NULL;
6163 	struct ext4_sb_info *sbi;
6164 	struct super_block *sb;
6165 	ext4_fsblk_t block = 0;
6166 	unsigned int inquota = 0;
6167 	unsigned int reserv_clstrs = 0;
6168 	int retries = 0;
6169 	u64 seq;
6170 
6171 	might_sleep();
6172 	sb = ar->inode->i_sb;
6173 	sbi = EXT4_SB(sb);
6174 
6175 	trace_ext4_request_blocks(ar);
6176 	if (sbi->s_mount_state & EXT4_FC_REPLAY)
6177 		return ext4_mb_new_blocks_simple(ar, errp);
6178 
6179 	/* Allow to use superuser reservation for quota file */
6180 	if (ext4_is_quota_file(ar->inode))
6181 		ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
6182 
6183 	if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
6184 		/* Without delayed allocation we need to verify
6185 		 * there is enough free blocks to do block allocation
6186 		 * and verify allocation doesn't exceed the quota limits.
6187 		 */
6188 		while (ar->len &&
6189 			ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
6190 
6191 			/* let others to free the space */
6192 			cond_resched();
6193 			ar->len = ar->len >> 1;
6194 		}
6195 		if (!ar->len) {
6196 			ext4_mb_show_pa(sb);
6197 			*errp = -ENOSPC;
6198 			return 0;
6199 		}
6200 		reserv_clstrs = ar->len;
6201 		if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
6202 			dquot_alloc_block_nofail(ar->inode,
6203 						 EXT4_C2B(sbi, ar->len));
6204 		} else {
6205 			while (ar->len &&
6206 				dquot_alloc_block(ar->inode,
6207 						  EXT4_C2B(sbi, ar->len))) {
6208 
6209 				ar->flags |= EXT4_MB_HINT_NOPREALLOC;
6210 				ar->len--;
6211 			}
6212 		}
6213 		inquota = ar->len;
6214 		if (ar->len == 0) {
6215 			*errp = -EDQUOT;
6216 			goto out;
6217 		}
6218 	}
6219 
6220 	ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
6221 	if (!ac) {
6222 		ar->len = 0;
6223 		*errp = -ENOMEM;
6224 		goto out;
6225 	}
6226 
6227 	ext4_mb_initialize_context(ac, ar);
6228 
6229 	ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
6230 	seq = this_cpu_read(discard_pa_seq);
6231 	if (!ext4_mb_use_preallocated(ac)) {
6232 		ac->ac_op = EXT4_MB_HISTORY_ALLOC;
6233 		ext4_mb_normalize_request(ac, ar);
6234 
6235 		*errp = ext4_mb_pa_alloc(ac);
6236 		if (*errp)
6237 			goto errout;
6238 repeat:
6239 		/* allocate space in core */
6240 		*errp = ext4_mb_regular_allocator(ac);
6241 		/*
6242 		 * pa allocated above is added to grp->bb_prealloc_list only
6243 		 * when we were able to allocate some block i.e. when
6244 		 * ac->ac_status == AC_STATUS_FOUND.
6245 		 * And error from above mean ac->ac_status != AC_STATUS_FOUND
6246 		 * So we have to free this pa here itself.
6247 		 */
6248 		if (*errp) {
6249 			ext4_mb_pa_put_free(ac);
6250 			ext4_discard_allocated_blocks(ac);
6251 			goto errout;
6252 		}
6253 		if (ac->ac_status == AC_STATUS_FOUND &&
6254 			ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
6255 			ext4_mb_pa_put_free(ac);
6256 	}
6257 	if (likely(ac->ac_status == AC_STATUS_FOUND)) {
6258 		*errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
6259 		if (*errp) {
6260 			ext4_discard_allocated_blocks(ac);
6261 			goto errout;
6262 		} else {
6263 			block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
6264 			ar->len = ac->ac_b_ex.fe_len;
6265 		}
6266 	} else {
6267 		if (++retries < 3 &&
6268 		    ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
6269 			goto repeat;
6270 		/*
6271 		 * If block allocation fails then the pa allocated above
6272 		 * needs to be freed here itself.
6273 		 */
6274 		ext4_mb_pa_put_free(ac);
6275 		*errp = -ENOSPC;
6276 	}
6277 
6278 	if (*errp) {
6279 errout:
6280 		ac->ac_b_ex.fe_len = 0;
6281 		ar->len = 0;
6282 		ext4_mb_show_ac(ac);
6283 	}
6284 	ext4_mb_release_context(ac);
6285 	kmem_cache_free(ext4_ac_cachep, ac);
6286 out:
6287 	if (inquota && ar->len < inquota)
6288 		dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
6289 	if (!ar->len) {
6290 		if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
6291 			/* release all the reserved blocks if non delalloc */
6292 			percpu_counter_sub(&sbi->s_dirtyclusters_counter,
6293 						reserv_clstrs);
6294 	}
6295 
6296 	trace_ext4_allocate_blocks(ar, (unsigned long long)block);
6297 
6298 	return block;
6299 }
6300 
6301 /*
6302  * We can merge two free data extents only if the physical blocks
6303  * are contiguous, AND the extents were freed by the same transaction,
6304  * AND the blocks are associated with the same group.
6305  */
6306 static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
6307 					struct ext4_free_data *entry,
6308 					struct ext4_free_data *new_entry,
6309 					struct rb_root *entry_rb_root)
6310 {
6311 	if ((entry->efd_tid != new_entry->efd_tid) ||
6312 	    (entry->efd_group != new_entry->efd_group))
6313 		return;
6314 	if (entry->efd_start_cluster + entry->efd_count ==
6315 	    new_entry->efd_start_cluster) {
6316 		new_entry->efd_start_cluster = entry->efd_start_cluster;
6317 		new_entry->efd_count += entry->efd_count;
6318 	} else if (new_entry->efd_start_cluster + new_entry->efd_count ==
6319 		   entry->efd_start_cluster) {
6320 		new_entry->efd_count += entry->efd_count;
6321 	} else
6322 		return;
6323 	spin_lock(&sbi->s_md_lock);
6324 	list_del(&entry->efd_list);
6325 	spin_unlock(&sbi->s_md_lock);
6326 	rb_erase(&entry->efd_node, entry_rb_root);
6327 	kmem_cache_free(ext4_free_data_cachep, entry);
6328 }
6329 
6330 static noinline_for_stack void
6331 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
6332 		      struct ext4_free_data *new_entry)
6333 {
6334 	ext4_group_t group = e4b->bd_group;
6335 	ext4_grpblk_t cluster;
6336 	ext4_grpblk_t clusters = new_entry->efd_count;
6337 	struct ext4_free_data *entry;
6338 	struct ext4_group_info *db = e4b->bd_info;
6339 	struct super_block *sb = e4b->bd_sb;
6340 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6341 	struct rb_node **n = &db->bb_free_root.rb_node, *node;
6342 	struct rb_node *parent = NULL, *new_node;
6343 
6344 	BUG_ON(!ext4_handle_valid(handle));
6345 	BUG_ON(e4b->bd_bitmap_page == NULL);
6346 	BUG_ON(e4b->bd_buddy_page == NULL);
6347 
6348 	new_node = &new_entry->efd_node;
6349 	cluster = new_entry->efd_start_cluster;
6350 
6351 	if (!*n) {
6352 		/* first free block exent. We need to
6353 		   protect buddy cache from being freed,
6354 		 * otherwise we'll refresh it from
6355 		 * on-disk bitmap and lose not-yet-available
6356 		 * blocks */
6357 		get_page(e4b->bd_buddy_page);
6358 		get_page(e4b->bd_bitmap_page);
6359 	}
6360 	while (*n) {
6361 		parent = *n;
6362 		entry = rb_entry(parent, struct ext4_free_data, efd_node);
6363 		if (cluster < entry->efd_start_cluster)
6364 			n = &(*n)->rb_left;
6365 		else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
6366 			n = &(*n)->rb_right;
6367 		else {
6368 			ext4_grp_locked_error(sb, group, 0,
6369 				ext4_group_first_block_no(sb, group) +
6370 				EXT4_C2B(sbi, cluster),
6371 				"Block already on to-be-freed list");
6372 			kmem_cache_free(ext4_free_data_cachep, new_entry);
6373 			return;
6374 		}
6375 	}
6376 
6377 	rb_link_node(new_node, parent, n);
6378 	rb_insert_color(new_node, &db->bb_free_root);
6379 
6380 	/* Now try to see the extent can be merged to left and right */
6381 	node = rb_prev(new_node);
6382 	if (node) {
6383 		entry = rb_entry(node, struct ext4_free_data, efd_node);
6384 		ext4_try_merge_freed_extent(sbi, entry, new_entry,
6385 					    &(db->bb_free_root));
6386 	}
6387 
6388 	node = rb_next(new_node);
6389 	if (node) {
6390 		entry = rb_entry(node, struct ext4_free_data, efd_node);
6391 		ext4_try_merge_freed_extent(sbi, entry, new_entry,
6392 					    &(db->bb_free_root));
6393 	}
6394 
6395 	spin_lock(&sbi->s_md_lock);
6396 	list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
6397 	sbi->s_mb_free_pending += clusters;
6398 	spin_unlock(&sbi->s_md_lock);
6399 }
6400 
6401 static void ext4_free_blocks_simple(struct inode *inode, ext4_fsblk_t block,
6402 					unsigned long count)
6403 {
6404 	struct buffer_head *bitmap_bh;
6405 	struct super_block *sb = inode->i_sb;
6406 	struct ext4_group_desc *gdp;
6407 	struct buffer_head *gdp_bh;
6408 	ext4_group_t group;
6409 	ext4_grpblk_t blkoff;
6410 	int already_freed = 0, err, i;
6411 
6412 	ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
6413 	bitmap_bh = ext4_read_block_bitmap(sb, group);
6414 	if (IS_ERR(bitmap_bh)) {
6415 		pr_warn("Failed to read block bitmap\n");
6416 		return;
6417 	}
6418 	gdp = ext4_get_group_desc(sb, group, &gdp_bh);
6419 	if (!gdp)
6420 		goto err_out;
6421 
6422 	for (i = 0; i < count; i++) {
6423 		if (!mb_test_bit(blkoff + i, bitmap_bh->b_data))
6424 			already_freed++;
6425 	}
6426 	mb_clear_bits(bitmap_bh->b_data, blkoff, count);
6427 	err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
6428 	if (err)
6429 		goto err_out;
6430 	ext4_free_group_clusters_set(
6431 		sb, gdp, ext4_free_group_clusters(sb, gdp) +
6432 		count - already_freed);
6433 	ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
6434 	ext4_group_desc_csum_set(sb, group, gdp);
6435 	ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
6436 	sync_dirty_buffer(bitmap_bh);
6437 	sync_dirty_buffer(gdp_bh);
6438 
6439 err_out:
6440 	brelse(bitmap_bh);
6441 }
6442 
6443 /**
6444  * ext4_mb_clear_bb() -- helper function for freeing blocks.
6445  *			Used by ext4_free_blocks()
6446  * @handle:		handle for this transaction
6447  * @inode:		inode
6448  * @block:		starting physical block to be freed
6449  * @count:		number of blocks to be freed
6450  * @flags:		flags used by ext4_free_blocks
6451  */
6452 static void ext4_mb_clear_bb(handle_t *handle, struct inode *inode,
6453 			       ext4_fsblk_t block, unsigned long count,
6454 			       int flags)
6455 {
6456 	struct buffer_head *bitmap_bh = NULL;
6457 	struct super_block *sb = inode->i_sb;
6458 	struct ext4_group_desc *gdp;
6459 	struct ext4_group_info *grp;
6460 	unsigned int overflow;
6461 	ext4_grpblk_t bit;
6462 	struct buffer_head *gd_bh;
6463 	ext4_group_t block_group;
6464 	struct ext4_sb_info *sbi;
6465 	struct ext4_buddy e4b;
6466 	unsigned int count_clusters;
6467 	int err = 0;
6468 	int ret;
6469 
6470 	sbi = EXT4_SB(sb);
6471 
6472 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6473 	    !ext4_inode_block_valid(inode, block, count)) {
6474 		ext4_error(sb, "Freeing blocks in system zone - "
6475 			   "Block = %llu, count = %lu", block, count);
6476 		/* err = 0. ext4_std_error should be a no op */
6477 		goto error_return;
6478 	}
6479 	flags |= EXT4_FREE_BLOCKS_VALIDATED;
6480 
6481 do_more:
6482 	overflow = 0;
6483 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
6484 
6485 	grp = ext4_get_group_info(sb, block_group);
6486 	if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
6487 		return;
6488 
6489 	/*
6490 	 * Check to see if we are freeing blocks across a group
6491 	 * boundary.
6492 	 */
6493 	if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
6494 		overflow = EXT4_C2B(sbi, bit) + count -
6495 			EXT4_BLOCKS_PER_GROUP(sb);
6496 		count -= overflow;
6497 		/* The range changed so it's no longer validated */
6498 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6499 	}
6500 	count_clusters = EXT4_NUM_B2C(sbi, count);
6501 	bitmap_bh = ext4_read_block_bitmap(sb, block_group);
6502 	if (IS_ERR(bitmap_bh)) {
6503 		err = PTR_ERR(bitmap_bh);
6504 		bitmap_bh = NULL;
6505 		goto error_return;
6506 	}
6507 	gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
6508 	if (!gdp) {
6509 		err = -EIO;
6510 		goto error_return;
6511 	}
6512 
6513 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6514 	    !ext4_inode_block_valid(inode, block, count)) {
6515 		ext4_error(sb, "Freeing blocks in system zone - "
6516 			   "Block = %llu, count = %lu", block, count);
6517 		/* err = 0. ext4_std_error should be a no op */
6518 		goto error_return;
6519 	}
6520 
6521 	BUFFER_TRACE(bitmap_bh, "getting write access");
6522 	err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
6523 					    EXT4_JTR_NONE);
6524 	if (err)
6525 		goto error_return;
6526 
6527 	/*
6528 	 * We are about to modify some metadata.  Call the journal APIs
6529 	 * to unshare ->b_data if a currently-committing transaction is
6530 	 * using it
6531 	 */
6532 	BUFFER_TRACE(gd_bh, "get_write_access");
6533 	err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
6534 	if (err)
6535 		goto error_return;
6536 #ifdef AGGRESSIVE_CHECK
6537 	{
6538 		int i;
6539 		for (i = 0; i < count_clusters; i++)
6540 			BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
6541 	}
6542 #endif
6543 	trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
6544 
6545 	/* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
6546 	err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
6547 				     GFP_NOFS|__GFP_NOFAIL);
6548 	if (err)
6549 		goto error_return;
6550 
6551 	/*
6552 	 * We need to make sure we don't reuse the freed block until after the
6553 	 * transaction is committed. We make an exception if the inode is to be
6554 	 * written in writeback mode since writeback mode has weak data
6555 	 * consistency guarantees.
6556 	 */
6557 	if (ext4_handle_valid(handle) &&
6558 	    ((flags & EXT4_FREE_BLOCKS_METADATA) ||
6559 	     !ext4_should_writeback_data(inode))) {
6560 		struct ext4_free_data *new_entry;
6561 		/*
6562 		 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
6563 		 * to fail.
6564 		 */
6565 		new_entry = kmem_cache_alloc(ext4_free_data_cachep,
6566 				GFP_NOFS|__GFP_NOFAIL);
6567 		new_entry->efd_start_cluster = bit;
6568 		new_entry->efd_group = block_group;
6569 		new_entry->efd_count = count_clusters;
6570 		new_entry->efd_tid = handle->h_transaction->t_tid;
6571 
6572 		ext4_lock_group(sb, block_group);
6573 		mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
6574 		ext4_mb_free_metadata(handle, &e4b, new_entry);
6575 	} else {
6576 		/* need to update group_info->bb_free and bitmap
6577 		 * with group lock held. generate_buddy look at
6578 		 * them with group lock_held
6579 		 */
6580 		if (test_opt(sb, DISCARD)) {
6581 			err = ext4_issue_discard(sb, block_group, bit,
6582 						 count_clusters, NULL);
6583 			if (err && err != -EOPNOTSUPP)
6584 				ext4_msg(sb, KERN_WARNING, "discard request in"
6585 					 " group:%u block:%d count:%lu failed"
6586 					 " with %d", block_group, bit, count,
6587 					 err);
6588 		} else
6589 			EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
6590 
6591 		ext4_lock_group(sb, block_group);
6592 		mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
6593 		mb_free_blocks(inode, &e4b, bit, count_clusters);
6594 	}
6595 
6596 	ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
6597 	ext4_free_group_clusters_set(sb, gdp, ret);
6598 	ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
6599 	ext4_group_desc_csum_set(sb, block_group, gdp);
6600 	ext4_unlock_group(sb, block_group);
6601 
6602 	if (sbi->s_log_groups_per_flex) {
6603 		ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
6604 		atomic64_add(count_clusters,
6605 			     &sbi_array_rcu_deref(sbi, s_flex_groups,
6606 						  flex_group)->free_clusters);
6607 	}
6608 
6609 	/*
6610 	 * on a bigalloc file system, defer the s_freeclusters_counter
6611 	 * update to the caller (ext4_remove_space and friends) so they
6612 	 * can determine if a cluster freed here should be rereserved
6613 	 */
6614 	if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
6615 		if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
6616 			dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
6617 		percpu_counter_add(&sbi->s_freeclusters_counter,
6618 				   count_clusters);
6619 	}
6620 
6621 	ext4_mb_unload_buddy(&e4b);
6622 
6623 	/* We dirtied the bitmap block */
6624 	BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
6625 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
6626 
6627 	/* And the group descriptor block */
6628 	BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
6629 	ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
6630 	if (!err)
6631 		err = ret;
6632 
6633 	if (overflow && !err) {
6634 		block += count;
6635 		count = overflow;
6636 		put_bh(bitmap_bh);
6637 		/* The range changed so it's no longer validated */
6638 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6639 		goto do_more;
6640 	}
6641 error_return:
6642 	brelse(bitmap_bh);
6643 	ext4_std_error(sb, err);
6644 	return;
6645 }
6646 
6647 /**
6648  * ext4_free_blocks() -- Free given blocks and update quota
6649  * @handle:		handle for this transaction
6650  * @inode:		inode
6651  * @bh:			optional buffer of the block to be freed
6652  * @block:		starting physical block to be freed
6653  * @count:		number of blocks to be freed
6654  * @flags:		flags used by ext4_free_blocks
6655  */
6656 void ext4_free_blocks(handle_t *handle, struct inode *inode,
6657 		      struct buffer_head *bh, ext4_fsblk_t block,
6658 		      unsigned long count, int flags)
6659 {
6660 	struct super_block *sb = inode->i_sb;
6661 	unsigned int overflow;
6662 	struct ext4_sb_info *sbi;
6663 
6664 	sbi = EXT4_SB(sb);
6665 
6666 	if (bh) {
6667 		if (block)
6668 			BUG_ON(block != bh->b_blocknr);
6669 		else
6670 			block = bh->b_blocknr;
6671 	}
6672 
6673 	if (sbi->s_mount_state & EXT4_FC_REPLAY) {
6674 		ext4_free_blocks_simple(inode, block, EXT4_NUM_B2C(sbi, count));
6675 		return;
6676 	}
6677 
6678 	might_sleep();
6679 
6680 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6681 	    !ext4_inode_block_valid(inode, block, count)) {
6682 		ext4_error(sb, "Freeing blocks not in datazone - "
6683 			   "block = %llu, count = %lu", block, count);
6684 		return;
6685 	}
6686 	flags |= EXT4_FREE_BLOCKS_VALIDATED;
6687 
6688 	ext4_debug("freeing block %llu\n", block);
6689 	trace_ext4_free_blocks(inode, block, count, flags);
6690 
6691 	if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
6692 		BUG_ON(count > 1);
6693 
6694 		ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
6695 			    inode, bh, block);
6696 	}
6697 
6698 	/*
6699 	 * If the extent to be freed does not begin on a cluster
6700 	 * boundary, we need to deal with partial clusters at the
6701 	 * beginning and end of the extent.  Normally we will free
6702 	 * blocks at the beginning or the end unless we are explicitly
6703 	 * requested to avoid doing so.
6704 	 */
6705 	overflow = EXT4_PBLK_COFF(sbi, block);
6706 	if (overflow) {
6707 		if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
6708 			overflow = sbi->s_cluster_ratio - overflow;
6709 			block += overflow;
6710 			if (count > overflow)
6711 				count -= overflow;
6712 			else
6713 				return;
6714 		} else {
6715 			block -= overflow;
6716 			count += overflow;
6717 		}
6718 		/* The range changed so it's no longer validated */
6719 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6720 	}
6721 	overflow = EXT4_LBLK_COFF(sbi, count);
6722 	if (overflow) {
6723 		if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
6724 			if (count > overflow)
6725 				count -= overflow;
6726 			else
6727 				return;
6728 		} else
6729 			count += sbi->s_cluster_ratio - overflow;
6730 		/* The range changed so it's no longer validated */
6731 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6732 	}
6733 
6734 	if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
6735 		int i;
6736 		int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
6737 
6738 		for (i = 0; i < count; i++) {
6739 			cond_resched();
6740 			if (is_metadata)
6741 				bh = sb_find_get_block(inode->i_sb, block + i);
6742 			ext4_forget(handle, is_metadata, inode, bh, block + i);
6743 		}
6744 	}
6745 
6746 	ext4_mb_clear_bb(handle, inode, block, count, flags);
6747 	return;
6748 }
6749 
6750 /**
6751  * ext4_group_add_blocks() -- Add given blocks to an existing group
6752  * @handle:			handle to this transaction
6753  * @sb:				super block
6754  * @block:			start physical block to add to the block group
6755  * @count:			number of blocks to free
6756  *
6757  * This marks the blocks as free in the bitmap and buddy.
6758  */
6759 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
6760 			 ext4_fsblk_t block, unsigned long count)
6761 {
6762 	struct buffer_head *bitmap_bh = NULL;
6763 	struct buffer_head *gd_bh;
6764 	ext4_group_t block_group;
6765 	ext4_grpblk_t bit;
6766 	unsigned int i;
6767 	struct ext4_group_desc *desc;
6768 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6769 	struct ext4_buddy e4b;
6770 	int err = 0, ret, free_clusters_count;
6771 	ext4_grpblk_t clusters_freed;
6772 	ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
6773 	ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
6774 	unsigned long cluster_count = last_cluster - first_cluster + 1;
6775 
6776 	ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
6777 
6778 	if (count == 0)
6779 		return 0;
6780 
6781 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
6782 	/*
6783 	 * Check to see if we are freeing blocks across a group
6784 	 * boundary.
6785 	 */
6786 	if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
6787 		ext4_warning(sb, "too many blocks added to group %u",
6788 			     block_group);
6789 		err = -EINVAL;
6790 		goto error_return;
6791 	}
6792 
6793 	bitmap_bh = ext4_read_block_bitmap(sb, block_group);
6794 	if (IS_ERR(bitmap_bh)) {
6795 		err = PTR_ERR(bitmap_bh);
6796 		bitmap_bh = NULL;
6797 		goto error_return;
6798 	}
6799 
6800 	desc = ext4_get_group_desc(sb, block_group, &gd_bh);
6801 	if (!desc) {
6802 		err = -EIO;
6803 		goto error_return;
6804 	}
6805 
6806 	if (!ext4_sb_block_valid(sb, NULL, block, count)) {
6807 		ext4_error(sb, "Adding blocks in system zones - "
6808 			   "Block = %llu, count = %lu",
6809 			   block, count);
6810 		err = -EINVAL;
6811 		goto error_return;
6812 	}
6813 
6814 	BUFFER_TRACE(bitmap_bh, "getting write access");
6815 	err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
6816 					    EXT4_JTR_NONE);
6817 	if (err)
6818 		goto error_return;
6819 
6820 	/*
6821 	 * We are about to modify some metadata.  Call the journal APIs
6822 	 * to unshare ->b_data if a currently-committing transaction is
6823 	 * using it
6824 	 */
6825 	BUFFER_TRACE(gd_bh, "get_write_access");
6826 	err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
6827 	if (err)
6828 		goto error_return;
6829 
6830 	for (i = 0, clusters_freed = 0; i < cluster_count; i++) {
6831 		BUFFER_TRACE(bitmap_bh, "clear bit");
6832 		if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
6833 			ext4_error(sb, "bit already cleared for block %llu",
6834 				   (ext4_fsblk_t)(block + i));
6835 			BUFFER_TRACE(bitmap_bh, "bit already cleared");
6836 		} else {
6837 			clusters_freed++;
6838 		}
6839 	}
6840 
6841 	err = ext4_mb_load_buddy(sb, block_group, &e4b);
6842 	if (err)
6843 		goto error_return;
6844 
6845 	/*
6846 	 * need to update group_info->bb_free and bitmap
6847 	 * with group lock held. generate_buddy look at
6848 	 * them with group lock_held
6849 	 */
6850 	ext4_lock_group(sb, block_group);
6851 	mb_clear_bits(bitmap_bh->b_data, bit, cluster_count);
6852 	mb_free_blocks(NULL, &e4b, bit, cluster_count);
6853 	free_clusters_count = clusters_freed +
6854 		ext4_free_group_clusters(sb, desc);
6855 	ext4_free_group_clusters_set(sb, desc, free_clusters_count);
6856 	ext4_block_bitmap_csum_set(sb, desc, bitmap_bh);
6857 	ext4_group_desc_csum_set(sb, block_group, desc);
6858 	ext4_unlock_group(sb, block_group);
6859 	percpu_counter_add(&sbi->s_freeclusters_counter,
6860 			   clusters_freed);
6861 
6862 	if (sbi->s_log_groups_per_flex) {
6863 		ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
6864 		atomic64_add(clusters_freed,
6865 			     &sbi_array_rcu_deref(sbi, s_flex_groups,
6866 						  flex_group)->free_clusters);
6867 	}
6868 
6869 	ext4_mb_unload_buddy(&e4b);
6870 
6871 	/* We dirtied the bitmap block */
6872 	BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
6873 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
6874 
6875 	/* And the group descriptor block */
6876 	BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
6877 	ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
6878 	if (!err)
6879 		err = ret;
6880 
6881 error_return:
6882 	brelse(bitmap_bh);
6883 	ext4_std_error(sb, err);
6884 	return err;
6885 }
6886 
6887 /**
6888  * ext4_trim_extent -- function to TRIM one single free extent in the group
6889  * @sb:		super block for the file system
6890  * @start:	starting block of the free extent in the alloc. group
6891  * @count:	number of blocks to TRIM
6892  * @e4b:	ext4 buddy for the group
6893  *
6894  * Trim "count" blocks starting at "start" in the "group". To assure that no
6895  * one will allocate those blocks, mark it as used in buddy bitmap. This must
6896  * be called with under the group lock.
6897  */
6898 static int ext4_trim_extent(struct super_block *sb,
6899 		int start, int count, struct ext4_buddy *e4b)
6900 __releases(bitlock)
6901 __acquires(bitlock)
6902 {
6903 	struct ext4_free_extent ex;
6904 	ext4_group_t group = e4b->bd_group;
6905 	int ret = 0;
6906 
6907 	trace_ext4_trim_extent(sb, group, start, count);
6908 
6909 	assert_spin_locked(ext4_group_lock_ptr(sb, group));
6910 
6911 	ex.fe_start = start;
6912 	ex.fe_group = group;
6913 	ex.fe_len = count;
6914 
6915 	/*
6916 	 * Mark blocks used, so no one can reuse them while
6917 	 * being trimmed.
6918 	 */
6919 	mb_mark_used(e4b, &ex);
6920 	ext4_unlock_group(sb, group);
6921 	ret = ext4_issue_discard(sb, group, start, count, NULL);
6922 	ext4_lock_group(sb, group);
6923 	mb_free_blocks(NULL, e4b, start, ex.fe_len);
6924 	return ret;
6925 }
6926 
6927 static int ext4_try_to_trim_range(struct super_block *sb,
6928 		struct ext4_buddy *e4b, ext4_grpblk_t start,
6929 		ext4_grpblk_t max, ext4_grpblk_t minblocks)
6930 __acquires(ext4_group_lock_ptr(sb, e4b->bd_group))
6931 __releases(ext4_group_lock_ptr(sb, e4b->bd_group))
6932 {
6933 	ext4_grpblk_t next, count, free_count;
6934 	void *bitmap;
6935 
6936 	bitmap = e4b->bd_bitmap;
6937 	start = (e4b->bd_info->bb_first_free > start) ?
6938 		e4b->bd_info->bb_first_free : start;
6939 	count = 0;
6940 	free_count = 0;
6941 
6942 	while (start <= max) {
6943 		start = mb_find_next_zero_bit(bitmap, max + 1, start);
6944 		if (start > max)
6945 			break;
6946 		next = mb_find_next_bit(bitmap, max + 1, start);
6947 
6948 		if ((next - start) >= minblocks) {
6949 			int ret = ext4_trim_extent(sb, start, next - start, e4b);
6950 
6951 			if (ret && ret != -EOPNOTSUPP)
6952 				break;
6953 			count += next - start;
6954 		}
6955 		free_count += next - start;
6956 		start = next + 1;
6957 
6958 		if (fatal_signal_pending(current)) {
6959 			count = -ERESTARTSYS;
6960 			break;
6961 		}
6962 
6963 		if (need_resched()) {
6964 			ext4_unlock_group(sb, e4b->bd_group);
6965 			cond_resched();
6966 			ext4_lock_group(sb, e4b->bd_group);
6967 		}
6968 
6969 		if ((e4b->bd_info->bb_free - free_count) < minblocks)
6970 			break;
6971 	}
6972 
6973 	return count;
6974 }
6975 
6976 /**
6977  * ext4_trim_all_free -- function to trim all free space in alloc. group
6978  * @sb:			super block for file system
6979  * @group:		group to be trimmed
6980  * @start:		first group block to examine
6981  * @max:		last group block to examine
6982  * @minblocks:		minimum extent block count
6983  * @set_trimmed:	set the trimmed flag if at least one block is trimmed
6984  *
6985  * ext4_trim_all_free walks through group's block bitmap searching for free
6986  * extents. When the free extent is found, mark it as used in group buddy
6987  * bitmap. Then issue a TRIM command on this extent and free the extent in
6988  * the group buddy bitmap.
6989  */
6990 static ext4_grpblk_t
6991 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
6992 		   ext4_grpblk_t start, ext4_grpblk_t max,
6993 		   ext4_grpblk_t minblocks, bool set_trimmed)
6994 {
6995 	struct ext4_buddy e4b;
6996 	int ret;
6997 
6998 	trace_ext4_trim_all_free(sb, group, start, max);
6999 
7000 	ret = ext4_mb_load_buddy(sb, group, &e4b);
7001 	if (ret) {
7002 		ext4_warning(sb, "Error %d loading buddy information for %u",
7003 			     ret, group);
7004 		return ret;
7005 	}
7006 
7007 	ext4_lock_group(sb, group);
7008 
7009 	if (!EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) ||
7010 	    minblocks < EXT4_SB(sb)->s_last_trim_minblks) {
7011 		ret = ext4_try_to_trim_range(sb, &e4b, start, max, minblocks);
7012 		if (ret >= 0 && set_trimmed)
7013 			EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
7014 	} else {
7015 		ret = 0;
7016 	}
7017 
7018 	ext4_unlock_group(sb, group);
7019 	ext4_mb_unload_buddy(&e4b);
7020 
7021 	ext4_debug("trimmed %d blocks in the group %d\n",
7022 		ret, group);
7023 
7024 	return ret;
7025 }
7026 
7027 /**
7028  * ext4_trim_fs() -- trim ioctl handle function
7029  * @sb:			superblock for filesystem
7030  * @range:		fstrim_range structure
7031  *
7032  * start:	First Byte to trim
7033  * len:		number of Bytes to trim from start
7034  * minlen:	minimum extent length in Bytes
7035  * ext4_trim_fs goes through all allocation groups containing Bytes from
7036  * start to start+len. For each such a group ext4_trim_all_free function
7037  * is invoked to trim all free space.
7038  */
7039 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
7040 {
7041 	unsigned int discard_granularity = bdev_discard_granularity(sb->s_bdev);
7042 	struct ext4_group_info *grp;
7043 	ext4_group_t group, first_group, last_group;
7044 	ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
7045 	uint64_t start, end, minlen, trimmed = 0;
7046 	ext4_fsblk_t first_data_blk =
7047 			le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
7048 	ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
7049 	bool whole_group, eof = false;
7050 	int ret = 0;
7051 
7052 	start = range->start >> sb->s_blocksize_bits;
7053 	end = start + (range->len >> sb->s_blocksize_bits) - 1;
7054 	minlen = EXT4_NUM_B2C(EXT4_SB(sb),
7055 			      range->minlen >> sb->s_blocksize_bits);
7056 
7057 	if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
7058 	    start >= max_blks ||
7059 	    range->len < sb->s_blocksize)
7060 		return -EINVAL;
7061 	/* No point to try to trim less than discard granularity */
7062 	if (range->minlen < discard_granularity) {
7063 		minlen = EXT4_NUM_B2C(EXT4_SB(sb),
7064 				discard_granularity >> sb->s_blocksize_bits);
7065 		if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
7066 			goto out;
7067 	}
7068 	if (end >= max_blks - 1) {
7069 		end = max_blks - 1;
7070 		eof = true;
7071 	}
7072 	if (end <= first_data_blk)
7073 		goto out;
7074 	if (start < first_data_blk)
7075 		start = first_data_blk;
7076 
7077 	/* Determine first and last group to examine based on start and end */
7078 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
7079 				     &first_group, &first_cluster);
7080 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
7081 				     &last_group, &last_cluster);
7082 
7083 	/* end now represents the last cluster to discard in this group */
7084 	end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
7085 	whole_group = true;
7086 
7087 	for (group = first_group; group <= last_group; group++) {
7088 		grp = ext4_get_group_info(sb, group);
7089 		if (!grp)
7090 			continue;
7091 		/* We only do this if the grp has never been initialized */
7092 		if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
7093 			ret = ext4_mb_init_group(sb, group, GFP_NOFS);
7094 			if (ret)
7095 				break;
7096 		}
7097 
7098 		/*
7099 		 * For all the groups except the last one, last cluster will
7100 		 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
7101 		 * change it for the last group, note that last_cluster is
7102 		 * already computed earlier by ext4_get_group_no_and_offset()
7103 		 */
7104 		if (group == last_group) {
7105 			end = last_cluster;
7106 			whole_group = eof ? true : end == EXT4_CLUSTERS_PER_GROUP(sb) - 1;
7107 		}
7108 		if (grp->bb_free >= minlen) {
7109 			cnt = ext4_trim_all_free(sb, group, first_cluster,
7110 						 end, minlen, whole_group);
7111 			if (cnt < 0) {
7112 				ret = cnt;
7113 				break;
7114 			}
7115 			trimmed += cnt;
7116 		}
7117 
7118 		/*
7119 		 * For every group except the first one, we are sure
7120 		 * that the first cluster to discard will be cluster #0.
7121 		 */
7122 		first_cluster = 0;
7123 	}
7124 
7125 	if (!ret)
7126 		EXT4_SB(sb)->s_last_trim_minblks = minlen;
7127 
7128 out:
7129 	range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
7130 	return ret;
7131 }
7132 
7133 /* Iterate all the free extents in the group. */
7134 int
7135 ext4_mballoc_query_range(
7136 	struct super_block		*sb,
7137 	ext4_group_t			group,
7138 	ext4_grpblk_t			start,
7139 	ext4_grpblk_t			end,
7140 	ext4_mballoc_query_range_fn	formatter,
7141 	void				*priv)
7142 {
7143 	void				*bitmap;
7144 	ext4_grpblk_t			next;
7145 	struct ext4_buddy		e4b;
7146 	int				error;
7147 
7148 	error = ext4_mb_load_buddy(sb, group, &e4b);
7149 	if (error)
7150 		return error;
7151 	bitmap = e4b.bd_bitmap;
7152 
7153 	ext4_lock_group(sb, group);
7154 
7155 	start = (e4b.bd_info->bb_first_free > start) ?
7156 		e4b.bd_info->bb_first_free : start;
7157 	if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
7158 		end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
7159 
7160 	while (start <= end) {
7161 		start = mb_find_next_zero_bit(bitmap, end + 1, start);
7162 		if (start > end)
7163 			break;
7164 		next = mb_find_next_bit(bitmap, end + 1, start);
7165 
7166 		ext4_unlock_group(sb, group);
7167 		error = formatter(sb, group, start, next - start, priv);
7168 		if (error)
7169 			goto out_unload;
7170 		ext4_lock_group(sb, group);
7171 
7172 		start = next + 1;
7173 	}
7174 
7175 	ext4_unlock_group(sb, group);
7176 out_unload:
7177 	ext4_mb_unload_buddy(&e4b);
7178 
7179 	return error;
7180 }
7181