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