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