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