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