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