xref: /linux/fs/ext4/mballoc.c (revision e1622a0d558200b0ccdfbf69ee29b9ac1f5c2442)
1f5166768STheodore Ts'o // SPDX-License-Identifier: GPL-2.0
2c9de560dSAlex Tomas /*
3c9de560dSAlex Tomas  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
4c9de560dSAlex Tomas  * Written by Alex Tomas <alex@clusterfs.com>
5c9de560dSAlex Tomas  */
6c9de560dSAlex Tomas 
7c9de560dSAlex Tomas 
8c9de560dSAlex Tomas /*
9c9de560dSAlex Tomas  * mballoc.c contains the multiblocks allocation routines
10c9de560dSAlex Tomas  */
11c9de560dSAlex Tomas 
1218aadd47SBobi Jam #include "ext4_jbd2.h"
138f6e39a7SMingming Cao #include "mballoc.h"
1428623c2fSTheodore Ts'o #include <linux/log2.h>
15a0b30c12STheodore Ts'o #include <linux/module.h>
165a0e3ad6STejun Heo #include <linux/slab.h>
171a5d5e5dSJeremy Cline #include <linux/nospec.h>
1866114cadSTejun Heo #include <linux/backing-dev.h>
195229a658SJan Kara #include <linux/freezer.h>
209bffad1eSTheodore Ts'o #include <trace/events/ext4.h>
21bdefd689SKemeng Shi #include <kunit/static_stub.h>
229bffad1eSTheodore Ts'o 
23c9de560dSAlex Tomas /*
24c9de560dSAlex Tomas  * MUSTDO:
25c9de560dSAlex Tomas  *   - test ext4_ext_search_left() and ext4_ext_search_right()
26c9de560dSAlex Tomas  *   - search for metadata in few groups
27c9de560dSAlex Tomas  *
28c9de560dSAlex Tomas  * TODO v4:
29c9de560dSAlex Tomas  *   - normalization should take into account whether file is still open
30c9de560dSAlex Tomas  *   - discard preallocations if no free space left (policy?)
31c9de560dSAlex Tomas  *   - don't normalize tails
32c9de560dSAlex Tomas  *   - quota
33c9de560dSAlex Tomas  *   - reservation for superuser
34c9de560dSAlex Tomas  *
35c9de560dSAlex Tomas  * TODO v3:
36c9de560dSAlex Tomas  *   - bitmap read-ahead (proposed by Oleg Drokin aka green)
37c9de560dSAlex Tomas  *   - track min/max extents in each group for better group selection
38c9de560dSAlex Tomas  *   - mb_mark_used() may allocate chunk right after splitting buddy
39c9de560dSAlex Tomas  *   - tree of groups sorted by number of free blocks
40c9de560dSAlex Tomas  *   - error handling
41c9de560dSAlex Tomas  */
42c9de560dSAlex Tomas 
43c9de560dSAlex Tomas /*
44c9de560dSAlex Tomas  * The allocation request involve request for multiple number of blocks
45c9de560dSAlex Tomas  * near to the goal(block) value specified.
46c9de560dSAlex Tomas  *
47b713a5ecSTheodore Ts'o  * During initialization phase of the allocator we decide to use the
48b713a5ecSTheodore Ts'o  * group preallocation or inode preallocation depending on the size of
49b713a5ecSTheodore Ts'o  * the file. The size of the file could be the resulting file size we
50b713a5ecSTheodore Ts'o  * would have after allocation, or the current file size, which ever
51b713a5ecSTheodore Ts'o  * is larger. If the size is less than sbi->s_mb_stream_request we
52b713a5ecSTheodore Ts'o  * select to use the group preallocation. The default value of
53b713a5ecSTheodore Ts'o  * s_mb_stream_request is 16 blocks. This can also be tuned via
54b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
55b713a5ecSTheodore Ts'o  * terms of number of blocks.
56c9de560dSAlex Tomas  *
57c9de560dSAlex Tomas  * The main motivation for having small file use group preallocation is to
58b713a5ecSTheodore Ts'o  * ensure that we have small files closer together on the disk.
59c9de560dSAlex Tomas  *
60b713a5ecSTheodore Ts'o  * First stage the allocator looks at the inode prealloc list,
61b713a5ecSTheodore Ts'o  * ext4_inode_info->i_prealloc_list, which contains list of prealloc
62b713a5ecSTheodore Ts'o  * spaces for this particular inode. The inode prealloc space is
63b713a5ecSTheodore Ts'o  * represented as:
64c9de560dSAlex Tomas  *
65c9de560dSAlex Tomas  * pa_lstart -> the logical start block for this prealloc space
66c9de560dSAlex Tomas  * pa_pstart -> the physical start block for this prealloc space
6753accfa9STheodore Ts'o  * pa_len    -> length for this prealloc space (in clusters)
6853accfa9STheodore Ts'o  * pa_free   ->  free space available in this prealloc space (in clusters)
69c9de560dSAlex Tomas  *
70c9de560dSAlex Tomas  * The inode preallocation space is used looking at the _logical_ start
71c9de560dSAlex Tomas  * block. If only the logical file block falls within the range of prealloc
72caaf7a29STao Ma  * space we will consume the particular prealloc space. This makes sure that
73caaf7a29STao Ma  * we have contiguous physical blocks representing the file blocks
74c9de560dSAlex Tomas  *
75c9de560dSAlex Tomas  * The important thing to be noted in case of inode prealloc space is that
76c9de560dSAlex Tomas  * we don't modify the values associated to inode prealloc space except
77c9de560dSAlex Tomas  * pa_free.
78c9de560dSAlex Tomas  *
79c9de560dSAlex Tomas  * If we are not able to find blocks in the inode prealloc space and if we
80c9de560dSAlex Tomas  * have the group allocation flag set then we look at the locality group
81caaf7a29STao Ma  * prealloc space. These are per CPU prealloc list represented as
82c9de560dSAlex Tomas  *
83c9de560dSAlex Tomas  * ext4_sb_info.s_locality_groups[smp_processor_id()]
84c9de560dSAlex Tomas  *
85c9de560dSAlex Tomas  * The reason for having a per cpu locality group is to reduce the contention
86c9de560dSAlex Tomas  * between CPUs. It is possible to get scheduled at this point.
87c9de560dSAlex Tomas  *
88c9de560dSAlex Tomas  * The locality group prealloc space is used looking at whether we have
8925985edcSLucas De Marchi  * enough free space (pa_free) within the prealloc space.
90c9de560dSAlex Tomas  *
91c9de560dSAlex Tomas  * If we can't allocate blocks via inode prealloc or/and locality group
92c9de560dSAlex Tomas  * prealloc then we look at the buddy cache. The buddy cache is represented
93c9de560dSAlex Tomas  * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
94c9de560dSAlex Tomas  * mapped to the buddy and bitmap information regarding different
95c9de560dSAlex Tomas  * groups. The buddy information is attached to buddy cache inode so that
96c9de560dSAlex Tomas  * we can access them through the page cache. The information regarding
97c9de560dSAlex Tomas  * each group is loaded via ext4_mb_load_buddy.  The information involve
98c9de560dSAlex Tomas  * block bitmap and buddy information. The information are stored in the
99c9de560dSAlex Tomas  * inode as:
100c9de560dSAlex Tomas  *
101c9de560dSAlex Tomas  *  {                        page                        }
102c3a326a6SAneesh Kumar K.V  *  [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
103c9de560dSAlex Tomas  *
104c9de560dSAlex Tomas  *
105c9de560dSAlex Tomas  * one block each for bitmap and buddy information.  So for each group we
106ea1754a0SKirill A. Shutemov  * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
107c9de560dSAlex Tomas  * blocksize) blocks.  So it can have information regarding groups_per_page
108c9de560dSAlex Tomas  * which is blocks_per_page/2
109c9de560dSAlex Tomas  *
110c9de560dSAlex Tomas  * The buddy cache inode is not stored on disk. The inode is thrown
111c9de560dSAlex Tomas  * away when the filesystem is unmounted.
112c9de560dSAlex Tomas  *
113c9de560dSAlex Tomas  * We look for count number of blocks in the buddy cache. If we were able
114c9de560dSAlex Tomas  * to locate that many free blocks we return with additional information
115c9de560dSAlex Tomas  * regarding rest of the contiguous physical block available
116c9de560dSAlex Tomas  *
117c9de560dSAlex Tomas  * Before allocating blocks via buddy cache we normalize the request
118c9de560dSAlex Tomas  * blocks. This ensure we ask for more blocks that we needed. The extra
119c9de560dSAlex Tomas  * blocks that we get after allocation is added to the respective prealloc
120c9de560dSAlex Tomas  * list. In case of inode preallocation we follow a list of heuristics
121c9de560dSAlex Tomas  * based on file size. This can be found in ext4_mb_normalize_request. If
122c9de560dSAlex Tomas  * we are doing a group prealloc we try to normalize the request to
12327baebb8STheodore Ts'o  * sbi->s_mb_group_prealloc.  The default value of s_mb_group_prealloc is
12427baebb8STheodore Ts'o  * dependent on the cluster size; for non-bigalloc file systems, it is
125c9de560dSAlex Tomas  * 512 blocks. This can be tuned via
126d7a1fee1SDan Ehrenberg  * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
127c9de560dSAlex Tomas  * terms of number of blocks. If we have mounted the file system with -O
128c9de560dSAlex Tomas  * stripe=<value> option the group prealloc request is normalized to the
129b483bb77SRandy Dunlap  * smallest multiple of the stripe value (sbi->s_stripe) which is
130d7a1fee1SDan Ehrenberg  * greater than the default mb_group_prealloc.
131c9de560dSAlex Tomas  *
132196e402aSHarshad Shirwadkar  * If "mb_optimize_scan" mount option is set, we maintain in memory group info
133196e402aSHarshad Shirwadkar  * structures in two data structures:
134196e402aSHarshad Shirwadkar  *
135196e402aSHarshad Shirwadkar  * 1) Array of largest free order lists (sbi->s_mb_largest_free_orders)
136196e402aSHarshad Shirwadkar  *
137196e402aSHarshad Shirwadkar  *    Locking: sbi->s_mb_largest_free_orders_locks(array of rw locks)
138196e402aSHarshad Shirwadkar  *
139196e402aSHarshad Shirwadkar  *    This is an array of lists where the index in the array represents the
140196e402aSHarshad Shirwadkar  *    largest free order in the buddy bitmap of the participating group infos of
141196e402aSHarshad Shirwadkar  *    that list. So, there are exactly MB_NUM_ORDERS(sb) (which means total
142196e402aSHarshad Shirwadkar  *    number of buddy bitmap orders possible) number of lists. Group-infos are
143196e402aSHarshad Shirwadkar  *    placed in appropriate lists.
144196e402aSHarshad Shirwadkar  *
14583e80a6eSJan Kara  * 2) Average fragment size lists (sbi->s_mb_avg_fragment_size)
146196e402aSHarshad Shirwadkar  *
14783e80a6eSJan Kara  *    Locking: sbi->s_mb_avg_fragment_size_locks(array of rw locks)
148196e402aSHarshad Shirwadkar  *
14983e80a6eSJan Kara  *    This is an array of lists where in the i-th list there are groups with
15083e80a6eSJan Kara  *    average fragment size >= 2^i and < 2^(i+1). The average fragment size
15183e80a6eSJan Kara  *    is computed as ext4_group_info->bb_free / ext4_group_info->bb_fragments.
15283e80a6eSJan Kara  *    Note that we don't bother with a special list for completely empty groups
15383e80a6eSJan Kara  *    so we only have MB_NUM_ORDERS(sb) lists.
154196e402aSHarshad Shirwadkar  *
155196e402aSHarshad Shirwadkar  * When "mb_optimize_scan" mount option is set, mballoc consults the above data
156196e402aSHarshad Shirwadkar  * structures to decide the order in which groups are to be traversed for
157196e402aSHarshad Shirwadkar  * fulfilling an allocation request.
158196e402aSHarshad Shirwadkar  *
159f52f3d2bSOjaswin Mujoo  * At CR_POWER2_ALIGNED , we look for groups which have the largest_free_order
160f52f3d2bSOjaswin Mujoo  * >= the order of the request. We directly look at the largest free order list
161f52f3d2bSOjaswin Mujoo  * in the data structure (1) above where largest_free_order = order of the
162f52f3d2bSOjaswin Mujoo  * request. If that list is empty, we look at remaining list in the increasing
163f52f3d2bSOjaswin Mujoo  * order of largest_free_order. This allows us to perform CR_POWER2_ALIGNED
164f52f3d2bSOjaswin Mujoo  * lookup in O(1) time.
165196e402aSHarshad Shirwadkar  *
166f52f3d2bSOjaswin Mujoo  * At CR_GOAL_LEN_FAST, we only consider groups where
167f52f3d2bSOjaswin Mujoo  * average fragment size > request size. So, we lookup a group which has average
168f52f3d2bSOjaswin Mujoo  * fragment size just above or equal to request size using our average fragment
169f52f3d2bSOjaswin Mujoo  * size group lists (data structure 2) in O(1) time.
170196e402aSHarshad Shirwadkar  *
171f52f3d2bSOjaswin Mujoo  * At CR_BEST_AVAIL_LEN, we aim to optimize allocations which can't be satisfied
172f52f3d2bSOjaswin Mujoo  * in CR_GOAL_LEN_FAST. The fact that we couldn't find a group in
173f52f3d2bSOjaswin Mujoo  * CR_GOAL_LEN_FAST suggests that there is no BG that has avg
174f52f3d2bSOjaswin Mujoo  * fragment size > goal length. So before falling to the slower
175f52f3d2bSOjaswin Mujoo  * CR_GOAL_LEN_SLOW, in CR_BEST_AVAIL_LEN we proactively trim goal length and
176f52f3d2bSOjaswin Mujoo  * then use the same fragment lists as CR_GOAL_LEN_FAST to find a BG with a big
177f52f3d2bSOjaswin Mujoo  * enough average fragment size. This increases the chances of finding a
178f52f3d2bSOjaswin Mujoo  * suitable block group in O(1) time and results in faster allocation at the
179f52f3d2bSOjaswin Mujoo  * cost of reduced size of allocation.
1807e170922SOjaswin Mujoo  *
181196e402aSHarshad Shirwadkar  * If "mb_optimize_scan" mount option is not set, mballoc traverses groups in
182f52f3d2bSOjaswin Mujoo  * linear order which requires O(N) search time for each CR_POWER2_ALIGNED and
183f52f3d2bSOjaswin Mujoo  * CR_GOAL_LEN_FAST phase.
184196e402aSHarshad Shirwadkar  *
185d7a1fee1SDan Ehrenberg  * The regular allocator (using the buddy cache) supports a few tunables.
186c9de560dSAlex Tomas  *
187b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_min_to_scan
188b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_max_to_scan
189b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_order2_req
190196e402aSHarshad Shirwadkar  * /sys/fs/ext4/<partition>/mb_linear_limit
191c9de560dSAlex Tomas  *
192b713a5ecSTheodore Ts'o  * The regular allocator uses buddy scan only if the request len is power of
193c9de560dSAlex Tomas  * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
194c9de560dSAlex Tomas  * value of s_mb_order2_reqs can be tuned via
195b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_order2_req.  If the request len is equal to
196af901ca1SAndré Goddard Rosa  * stripe size (sbi->s_stripe), we try to search for contiguous block in
197b713a5ecSTheodore Ts'o  * stripe size. This should result in better allocation on RAID setups. If
198b713a5ecSTheodore Ts'o  * not, we search in the specific group using bitmap for best extents. The
199b713a5ecSTheodore Ts'o  * tunable min_to_scan and max_to_scan control the behaviour here.
200c9de560dSAlex Tomas  * min_to_scan indicate how long the mballoc __must__ look for a best
201b713a5ecSTheodore Ts'o  * extent and max_to_scan indicates how long the mballoc __can__ look for a
202c9de560dSAlex Tomas  * best extent in the found extents. Searching for the blocks starts with
203c9de560dSAlex Tomas  * the group specified as the goal value in allocation context via
204c9de560dSAlex Tomas  * ac_g_ex. Each group is first checked based on the criteria whether it
205caaf7a29STao Ma  * can be used for allocation. ext4_mb_good_group explains how the groups are
206c9de560dSAlex Tomas  * checked.
207c9de560dSAlex Tomas  *
208196e402aSHarshad Shirwadkar  * When "mb_optimize_scan" is turned on, as mentioned above, the groups may not
209196e402aSHarshad Shirwadkar  * get traversed linearly. That may result in subsequent allocations being not
210196e402aSHarshad Shirwadkar  * close to each other. And so, the underlying device may get filled up in a
211196e402aSHarshad Shirwadkar  * non-linear fashion. While that may not matter on non-rotational devices, for
212196e402aSHarshad Shirwadkar  * rotational devices that may result in higher seek times. "mb_linear_limit"
213196e402aSHarshad Shirwadkar  * tells mballoc how many groups mballoc should search linearly before
214196e402aSHarshad Shirwadkar  * performing consulting above data structures for more efficient lookups. For
215196e402aSHarshad Shirwadkar  * non rotational devices, this value defaults to 0 and for rotational devices
216196e402aSHarshad Shirwadkar  * this is set to MB_DEFAULT_LINEAR_LIMIT.
217196e402aSHarshad Shirwadkar  *
218c9de560dSAlex Tomas  * Both the prealloc space are getting populated as above. So for the first
219c9de560dSAlex Tomas  * request we will hit the buddy cache which will result in this prealloc
220c9de560dSAlex Tomas  * space getting filled. The prealloc space is then later used for the
221c9de560dSAlex Tomas  * subsequent request.
222c9de560dSAlex Tomas  */
223c9de560dSAlex Tomas 
224c9de560dSAlex Tomas /*
225c9de560dSAlex Tomas  * mballoc operates on the following data:
226c9de560dSAlex Tomas  *  - on-disk bitmap
227c9de560dSAlex Tomas  *  - in-core buddy (actually includes buddy and bitmap)
228c9de560dSAlex Tomas  *  - preallocation descriptors (PAs)
229c9de560dSAlex Tomas  *
230c9de560dSAlex Tomas  * there are two types of preallocations:
231c9de560dSAlex Tomas  *  - inode
232c9de560dSAlex Tomas  *    assiged to specific inode and can be used for this inode only.
233c9de560dSAlex Tomas  *    it describes part of inode's space preallocated to specific
234c9de560dSAlex Tomas  *    physical blocks. any block from that preallocated can be used
235c9de560dSAlex Tomas  *    independent. the descriptor just tracks number of blocks left
236c9de560dSAlex Tomas  *    unused. so, before taking some block from descriptor, one must
237c9de560dSAlex Tomas  *    make sure corresponded logical block isn't allocated yet. this
238c9de560dSAlex Tomas  *    also means that freeing any block within descriptor's range
239c9de560dSAlex Tomas  *    must discard all preallocated blocks.
240c9de560dSAlex Tomas  *  - locality group
241c9de560dSAlex Tomas  *    assigned to specific locality group which does not translate to
242c9de560dSAlex Tomas  *    permanent set of inodes: inode can join and leave group. space
243c9de560dSAlex Tomas  *    from this type of preallocation can be used for any inode. thus
244c9de560dSAlex Tomas  *    it's consumed from the beginning to the end.
245c9de560dSAlex Tomas  *
246c9de560dSAlex Tomas  * relation between them can be expressed as:
247c9de560dSAlex Tomas  *    in-core buddy = on-disk bitmap + preallocation descriptors
248c9de560dSAlex Tomas  *
249c9de560dSAlex Tomas  * this mean blocks mballoc considers used are:
250c9de560dSAlex Tomas  *  - allocated blocks (persistent)
251c9de560dSAlex Tomas  *  - preallocated blocks (non-persistent)
252c9de560dSAlex Tomas  *
253c9de560dSAlex Tomas  * consistency in mballoc world means that at any time a block is either
254c9de560dSAlex Tomas  * free or used in ALL structures. notice: "any time" should not be read
255c9de560dSAlex Tomas  * literally -- time is discrete and delimited by locks.
256c9de560dSAlex Tomas  *
257c9de560dSAlex Tomas  *  to keep it simple, we don't use block numbers, instead we count number of
258c9de560dSAlex Tomas  *  blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
259c9de560dSAlex Tomas  *
260c9de560dSAlex Tomas  * all operations can be expressed as:
261c9de560dSAlex Tomas  *  - init buddy:			buddy = on-disk + PAs
262c9de560dSAlex Tomas  *  - new PA:				buddy += N; PA = N
263c9de560dSAlex Tomas  *  - use inode PA:			on-disk += N; PA -= N
264c9de560dSAlex Tomas  *  - discard inode PA			buddy -= on-disk - PA; PA = 0
265c9de560dSAlex Tomas  *  - use locality group PA		on-disk += N; PA -= N
266c9de560dSAlex Tomas  *  - discard locality group PA		buddy -= PA; PA = 0
267c9de560dSAlex Tomas  *  note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
268c9de560dSAlex Tomas  *        is used in real operation because we can't know actual used
269c9de560dSAlex Tomas  *        bits from PA, only from on-disk bitmap
270c9de560dSAlex Tomas  *
271c9de560dSAlex Tomas  * if we follow this strict logic, then all operations above should be atomic.
272c9de560dSAlex Tomas  * given some of them can block, we'd have to use something like semaphores
273c9de560dSAlex Tomas  * killing performance on high-end SMP hardware. let's try to relax it using
274c9de560dSAlex Tomas  * the following knowledge:
275c9de560dSAlex Tomas  *  1) if buddy is referenced, it's already initialized
276c9de560dSAlex Tomas  *  2) while block is used in buddy and the buddy is referenced,
277c9de560dSAlex Tomas  *     nobody can re-allocate that block
278c9de560dSAlex Tomas  *  3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
279c9de560dSAlex Tomas  *     bit set and PA claims same block, it's OK. IOW, one can set bit in
280c9de560dSAlex Tomas  *     on-disk bitmap if buddy has same bit set or/and PA covers corresponded
281c9de560dSAlex Tomas  *     block
282c9de560dSAlex Tomas  *
283c9de560dSAlex Tomas  * so, now we're building a concurrency table:
284c9de560dSAlex Tomas  *  - init buddy vs.
285c9de560dSAlex Tomas  *    - new PA
286c9de560dSAlex Tomas  *      blocks for PA are allocated in the buddy, buddy must be referenced
287c9de560dSAlex Tomas  *      until PA is linked to allocation group to avoid concurrent buddy init
288c9de560dSAlex Tomas  *    - use inode PA
289c9de560dSAlex Tomas  *      we need to make sure that either on-disk bitmap or PA has uptodate data
290c9de560dSAlex Tomas  *      given (3) we care that PA-=N operation doesn't interfere with init
291c9de560dSAlex Tomas  *    - discard inode PA
292c9de560dSAlex Tomas  *      the simplest way would be to have buddy initialized by the discard
293c9de560dSAlex Tomas  *    - use locality group PA
294c9de560dSAlex Tomas  *      again PA-=N must be serialized with init
295c9de560dSAlex Tomas  *    - discard locality group PA
296c9de560dSAlex Tomas  *      the simplest way would be to have buddy initialized by the discard
297c9de560dSAlex Tomas  *  - new PA vs.
298c9de560dSAlex Tomas  *    - use inode PA
299c9de560dSAlex Tomas  *      i_data_sem serializes them
300c9de560dSAlex Tomas  *    - discard inode PA
301c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
302c9de560dSAlex Tomas  *    - use locality group PA
303c9de560dSAlex Tomas  *      some mutex should serialize them
304c9de560dSAlex Tomas  *    - discard locality group PA
305c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
306c9de560dSAlex Tomas  *  - use inode PA
307c9de560dSAlex Tomas  *    - use inode PA
308c9de560dSAlex Tomas  *      i_data_sem or another mutex should serializes them
309c9de560dSAlex Tomas  *    - discard inode PA
310c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
311c9de560dSAlex Tomas  *    - use locality group PA
312c9de560dSAlex Tomas  *      nothing wrong here -- they're different PAs covering different blocks
313c9de560dSAlex Tomas  *    - discard locality group PA
314c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
315c9de560dSAlex Tomas  *
316c9de560dSAlex Tomas  * now we're ready to make few consequences:
317c9de560dSAlex Tomas  *  - PA is referenced and while it is no discard is possible
318c9de560dSAlex Tomas  *  - PA is referenced until block isn't marked in on-disk bitmap
319c9de560dSAlex Tomas  *  - PA changes only after on-disk bitmap
320c9de560dSAlex Tomas  *  - discard must not compete with init. either init is done before
321c9de560dSAlex Tomas  *    any discard or they're serialized somehow
322c9de560dSAlex Tomas  *  - buddy init as sum of on-disk bitmap and PAs is done atomically
323c9de560dSAlex Tomas  *
324c9de560dSAlex Tomas  * a special case when we've used PA to emptiness. no need to modify buddy
325c9de560dSAlex Tomas  * in this case, but we should care about concurrent init
326c9de560dSAlex Tomas  *
327c9de560dSAlex Tomas  */
328c9de560dSAlex Tomas 
329c9de560dSAlex Tomas  /*
330c9de560dSAlex Tomas  * Logic in few words:
331c9de560dSAlex Tomas  *
332c9de560dSAlex Tomas  *  - allocation:
333c9de560dSAlex Tomas  *    load group
334c9de560dSAlex Tomas  *    find blocks
335c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
336c9de560dSAlex Tomas  *    release group
337c9de560dSAlex Tomas  *
338c9de560dSAlex Tomas  *  - use preallocation:
339c9de560dSAlex Tomas  *    find proper PA (per-inode or group)
340c9de560dSAlex Tomas  *    load group
341c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
342c9de560dSAlex Tomas  *    release group
343c9de560dSAlex Tomas  *    release PA
344c9de560dSAlex Tomas  *
345c9de560dSAlex Tomas  *  - free:
346c9de560dSAlex Tomas  *    load group
347c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
348c9de560dSAlex Tomas  *    release group
349c9de560dSAlex Tomas  *
350c9de560dSAlex Tomas  *  - discard preallocations in group:
351c9de560dSAlex Tomas  *    mark PAs deleted
352c9de560dSAlex Tomas  *    move them onto local list
353c9de560dSAlex Tomas  *    load on-disk bitmap
354c9de560dSAlex Tomas  *    load group
355c9de560dSAlex Tomas  *    remove PA from object (inode or locality group)
356c9de560dSAlex Tomas  *    mark free blocks in-core
357c9de560dSAlex Tomas  *
358c9de560dSAlex Tomas  *  - discard inode's preallocations:
359c9de560dSAlex Tomas  */
360c9de560dSAlex Tomas 
361c9de560dSAlex Tomas /*
362c9de560dSAlex Tomas  * Locking rules
363c9de560dSAlex Tomas  *
364c9de560dSAlex Tomas  * Locks:
365c9de560dSAlex Tomas  *  - bitlock on a group	(group)
366c9de560dSAlex Tomas  *  - object (inode/locality)	(object)
367c9de560dSAlex Tomas  *  - per-pa lock		(pa)
368f52f3d2bSOjaswin Mujoo  *  - cr_power2_aligned lists lock	(cr_power2_aligned)
369f52f3d2bSOjaswin Mujoo  *  - cr_goal_len_fast lists lock	(cr_goal_len_fast)
370c9de560dSAlex Tomas  *
371c9de560dSAlex Tomas  * Paths:
372c9de560dSAlex Tomas  *  - new pa
373c9de560dSAlex Tomas  *    object
374c9de560dSAlex Tomas  *    group
375c9de560dSAlex Tomas  *
376c9de560dSAlex Tomas  *  - find and use pa:
377c9de560dSAlex Tomas  *    pa
378c9de560dSAlex Tomas  *
379c9de560dSAlex Tomas  *  - release consumed pa:
380c9de560dSAlex Tomas  *    pa
381c9de560dSAlex Tomas  *    group
382c9de560dSAlex Tomas  *    object
383c9de560dSAlex Tomas  *
384c9de560dSAlex Tomas  *  - generate in-core bitmap:
385c9de560dSAlex Tomas  *    group
386c9de560dSAlex Tomas  *        pa
387c9de560dSAlex Tomas  *
388c9de560dSAlex Tomas  *  - discard all for given object (inode, locality group):
389c9de560dSAlex Tomas  *    object
390c9de560dSAlex Tomas  *        pa
391c9de560dSAlex Tomas  *    group
392c9de560dSAlex Tomas  *
393c9de560dSAlex Tomas  *  - discard all for given group:
394c9de560dSAlex Tomas  *    group
395c9de560dSAlex Tomas  *        pa
396c9de560dSAlex Tomas  *    group
397c9de560dSAlex Tomas  *        object
398c9de560dSAlex Tomas  *
399196e402aSHarshad Shirwadkar  *  - allocation path (ext4_mb_regular_allocator)
400196e402aSHarshad Shirwadkar  *    group
401f52f3d2bSOjaswin Mujoo  *    cr_power2_aligned/cr_goal_len_fast
402c9de560dSAlex Tomas  */
403c3a326a6SAneesh Kumar K.V static struct kmem_cache *ext4_pspace_cachep;
404c3a326a6SAneesh Kumar K.V static struct kmem_cache *ext4_ac_cachep;
40518aadd47SBobi Jam static struct kmem_cache *ext4_free_data_cachep;
406fb1813f4SCurt Wohlgemuth 
407fb1813f4SCurt Wohlgemuth /* We create slab caches for groupinfo data structures based on the
408fb1813f4SCurt Wohlgemuth  * superblock block size.  There will be one per mounted filesystem for
409fb1813f4SCurt Wohlgemuth  * each unique s_blocksize_bits */
4102892c15dSEric Sandeen #define NR_GRPINFO_CACHES 8
411fb1813f4SCurt Wohlgemuth static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
412fb1813f4SCurt Wohlgemuth 
413d6006186SEric Biggers static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
4142892c15dSEric Sandeen 	"ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
4152892c15dSEric Sandeen 	"ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
4162892c15dSEric Sandeen 	"ext4_groupinfo_64k", "ext4_groupinfo_128k"
4172892c15dSEric Sandeen };
4182892c15dSEric Sandeen 
419c3a326a6SAneesh Kumar K.V static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
420c3a326a6SAneesh Kumar K.V 					ext4_group_t group);
42153f86b17SRitesh Harjani static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac);
422c3a326a6SAneesh Kumar K.V 
423196e402aSHarshad Shirwadkar static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
4244eb7a4a1SOjaswin Mujoo 			       ext4_group_t group, enum criteria cr);
425196e402aSHarshad Shirwadkar 
42655cdd0afSWang Jianchao static int ext4_try_to_trim_range(struct super_block *sb,
42755cdd0afSWang Jianchao 		struct ext4_buddy *e4b, ext4_grpblk_t start,
42855cdd0afSWang Jianchao 		ext4_grpblk_t max, ext4_grpblk_t minblocks);
42955cdd0afSWang Jianchao 
43007b5b8e1SRitesh Harjani /*
43107b5b8e1SRitesh Harjani  * The algorithm using this percpu seq counter goes below:
43207b5b8e1SRitesh Harjani  * 1. We sample the percpu discard_pa_seq counter before trying for block
43307b5b8e1SRitesh Harjani  *    allocation in ext4_mb_new_blocks().
43407b5b8e1SRitesh Harjani  * 2. We increment this percpu discard_pa_seq counter when we either allocate
43507b5b8e1SRitesh Harjani  *    or free these blocks i.e. while marking those blocks as used/free in
43607b5b8e1SRitesh Harjani  *    mb_mark_used()/mb_free_blocks().
43707b5b8e1SRitesh Harjani  * 3. We also increment this percpu seq counter when we successfully identify
43807b5b8e1SRitesh Harjani  *    that the bb_prealloc_list is not empty and hence proceed for discarding
43907b5b8e1SRitesh Harjani  *    of those PAs inside ext4_mb_discard_group_preallocations().
44007b5b8e1SRitesh Harjani  *
44107b5b8e1SRitesh Harjani  * Now to make sure that the regular fast path of block allocation is not
44207b5b8e1SRitesh Harjani  * affected, as a small optimization we only sample the percpu seq counter
44307b5b8e1SRitesh Harjani  * on that cpu. Only when the block allocation fails and when freed blocks
44407b5b8e1SRitesh Harjani  * found were 0, that is when we sample percpu seq counter for all cpus using
44507b5b8e1SRitesh Harjani  * below function ext4_get_discard_pa_seq_sum(). This happens after making
44607b5b8e1SRitesh Harjani  * sure that all the PAs on grp->bb_prealloc_list got freed or if it's empty.
44707b5b8e1SRitesh Harjani  */
44807b5b8e1SRitesh Harjani static DEFINE_PER_CPU(u64, discard_pa_seq);
44907b5b8e1SRitesh Harjani static inline u64 ext4_get_discard_pa_seq_sum(void)
45007b5b8e1SRitesh Harjani {
45107b5b8e1SRitesh Harjani 	int __cpu;
45207b5b8e1SRitesh Harjani 	u64 __seq = 0;
45307b5b8e1SRitesh Harjani 
45407b5b8e1SRitesh Harjani 	for_each_possible_cpu(__cpu)
45507b5b8e1SRitesh Harjani 		__seq += per_cpu(discard_pa_seq, __cpu);
45607b5b8e1SRitesh Harjani 	return __seq;
45707b5b8e1SRitesh Harjani }
45807b5b8e1SRitesh Harjani 
459ffad0a44SAneesh Kumar K.V static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
460ffad0a44SAneesh Kumar K.V {
461c9de560dSAlex Tomas #if BITS_PER_LONG == 64
462ffad0a44SAneesh Kumar K.V 	*bit += ((unsigned long) addr & 7UL) << 3;
463ffad0a44SAneesh Kumar K.V 	addr = (void *) ((unsigned long) addr & ~7UL);
464c9de560dSAlex Tomas #elif BITS_PER_LONG == 32
465ffad0a44SAneesh Kumar K.V 	*bit += ((unsigned long) addr & 3UL) << 3;
466ffad0a44SAneesh Kumar K.V 	addr = (void *) ((unsigned long) addr & ~3UL);
467c9de560dSAlex Tomas #else
468c9de560dSAlex Tomas #error "how many bits you are?!"
469c9de560dSAlex Tomas #endif
470ffad0a44SAneesh Kumar K.V 	return addr;
471ffad0a44SAneesh Kumar K.V }
472c9de560dSAlex Tomas 
473c9de560dSAlex Tomas static inline int mb_test_bit(int bit, void *addr)
474c9de560dSAlex Tomas {
475c9de560dSAlex Tomas 	/*
476c9de560dSAlex Tomas 	 * ext4_test_bit on architecture like powerpc
477c9de560dSAlex Tomas 	 * needs unsigned long aligned address
478c9de560dSAlex Tomas 	 */
479ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
480c9de560dSAlex Tomas 	return ext4_test_bit(bit, addr);
481c9de560dSAlex Tomas }
482c9de560dSAlex Tomas 
483c9de560dSAlex Tomas static inline void mb_set_bit(int bit, void *addr)
484c9de560dSAlex Tomas {
485ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
486c9de560dSAlex Tomas 	ext4_set_bit(bit, addr);
487c9de560dSAlex Tomas }
488c9de560dSAlex Tomas 
489c9de560dSAlex Tomas static inline void mb_clear_bit(int bit, void *addr)
490c9de560dSAlex Tomas {
491ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
492c9de560dSAlex Tomas 	ext4_clear_bit(bit, addr);
493c9de560dSAlex Tomas }
494c9de560dSAlex Tomas 
495eabe0444SAndrey Sidorov static inline int mb_test_and_clear_bit(int bit, void *addr)
496eabe0444SAndrey Sidorov {
497eabe0444SAndrey Sidorov 	addr = mb_correct_addr_and_bit(&bit, addr);
498eabe0444SAndrey Sidorov 	return ext4_test_and_clear_bit(bit, addr);
499eabe0444SAndrey Sidorov }
500eabe0444SAndrey Sidorov 
501ffad0a44SAneesh Kumar K.V static inline int mb_find_next_zero_bit(void *addr, int max, int start)
502ffad0a44SAneesh Kumar K.V {
503e7dfb246SAneesh Kumar K.V 	int fix = 0, ret, tmpmax;
504ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&fix, addr);
505e7dfb246SAneesh Kumar K.V 	tmpmax = max + fix;
506ffad0a44SAneesh Kumar K.V 	start += fix;
507ffad0a44SAneesh Kumar K.V 
508e7dfb246SAneesh Kumar K.V 	ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
509e7dfb246SAneesh Kumar K.V 	if (ret > max)
510e7dfb246SAneesh Kumar K.V 		return max;
511e7dfb246SAneesh Kumar K.V 	return ret;
512ffad0a44SAneesh Kumar K.V }
513ffad0a44SAneesh Kumar K.V 
514ffad0a44SAneesh Kumar K.V static inline int mb_find_next_bit(void *addr, int max, int start)
515ffad0a44SAneesh Kumar K.V {
516e7dfb246SAneesh Kumar K.V 	int fix = 0, ret, tmpmax;
517ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&fix, addr);
518e7dfb246SAneesh Kumar K.V 	tmpmax = max + fix;
519ffad0a44SAneesh Kumar K.V 	start += fix;
520ffad0a44SAneesh Kumar K.V 
521e7dfb246SAneesh Kumar K.V 	ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
522e7dfb246SAneesh Kumar K.V 	if (ret > max)
523e7dfb246SAneesh Kumar K.V 		return max;
524e7dfb246SAneesh Kumar K.V 	return ret;
525ffad0a44SAneesh Kumar K.V }
526ffad0a44SAneesh Kumar K.V 
527c9de560dSAlex Tomas static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
528c9de560dSAlex Tomas {
529c9de560dSAlex Tomas 	char *bb;
530c9de560dSAlex Tomas 
531c5e8f3f3STheodore Ts'o 	BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
532c9de560dSAlex Tomas 	BUG_ON(max == NULL);
533c9de560dSAlex Tomas 
534c9de560dSAlex Tomas 	if (order > e4b->bd_blkbits + 1) {
535c9de560dSAlex Tomas 		*max = 0;
536c9de560dSAlex Tomas 		return NULL;
537c9de560dSAlex Tomas 	}
538c9de560dSAlex Tomas 
539c9de560dSAlex Tomas 	/* at order 0 we see each particular block */
54084b775a3SColy Li 	if (order == 0) {
541c9de560dSAlex Tomas 		*max = 1 << (e4b->bd_blkbits + 3);
542c5e8f3f3STheodore Ts'o 		return e4b->bd_bitmap;
54384b775a3SColy Li 	}
544c9de560dSAlex Tomas 
545c5e8f3f3STheodore Ts'o 	bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
546c9de560dSAlex Tomas 	*max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
547c9de560dSAlex Tomas 
548c9de560dSAlex Tomas 	return bb;
549c9de560dSAlex Tomas }
550c9de560dSAlex Tomas 
551c9de560dSAlex Tomas #ifdef DOUBLE_CHECK
552c9de560dSAlex Tomas static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
553c9de560dSAlex Tomas 			   int first, int count)
554c9de560dSAlex Tomas {
555c9de560dSAlex Tomas 	int i;
556c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
557c9de560dSAlex Tomas 
558c9de560dSAlex Tomas 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
559c9de560dSAlex Tomas 		return;
560bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
561c9de560dSAlex Tomas 	for (i = 0; i < count; i++) {
562c9de560dSAlex Tomas 		if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
563c9de560dSAlex Tomas 			ext4_fsblk_t blocknr;
5645661bd68SAkinobu Mita 
5655661bd68SAkinobu Mita 			blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
56653accfa9STheodore Ts'o 			blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
567c5f3a382SBaokun Li 			ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
568c5f3a382SBaokun Li 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
5695d1b1b3fSAneesh Kumar K.V 			ext4_grp_locked_error(sb, e4b->bd_group,
570e29136f8STheodore Ts'o 					      inode ? inode->i_ino : 0,
571e29136f8STheodore Ts'o 					      blocknr,
572e29136f8STheodore Ts'o 					      "freeing block already freed "
573e29136f8STheodore Ts'o 					      "(bit %u)",
574e29136f8STheodore Ts'o 					      first + i);
575c9de560dSAlex Tomas 		}
576c9de560dSAlex Tomas 		mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
577c9de560dSAlex Tomas 	}
578c9de560dSAlex Tomas }
579c9de560dSAlex Tomas 
580c9de560dSAlex Tomas static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
581c9de560dSAlex Tomas {
582c9de560dSAlex Tomas 	int i;
583c9de560dSAlex Tomas 
584c9de560dSAlex Tomas 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
585c9de560dSAlex Tomas 		return;
586bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
587c9de560dSAlex Tomas 	for (i = 0; i < count; i++) {
588c9de560dSAlex Tomas 		BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
589c9de560dSAlex Tomas 		mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
590c9de560dSAlex Tomas 	}
591c9de560dSAlex Tomas }
592c9de560dSAlex Tomas 
593c9de560dSAlex Tomas static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
594c9de560dSAlex Tomas {
595eb2b8ebbSRitesh Harjani 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
596eb2b8ebbSRitesh Harjani 		return;
597c9de560dSAlex Tomas 	if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
598c9de560dSAlex Tomas 		unsigned char *b1, *b2;
599c9de560dSAlex Tomas 		int i;
600c9de560dSAlex Tomas 		b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
601c9de560dSAlex Tomas 		b2 = (unsigned char *) bitmap;
602c9de560dSAlex Tomas 		for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
603c9de560dSAlex Tomas 			if (b1[i] != b2[i]) {
6049d8b9ec4STheodore Ts'o 				ext4_msg(e4b->bd_sb, KERN_ERR,
6059d8b9ec4STheodore Ts'o 					 "corruption in group %u "
6064776004fSTheodore Ts'o 					 "at byte %u(%u): %x in copy != %x "
6079d8b9ec4STheodore Ts'o 					 "on disk/prealloc",
608c9de560dSAlex Tomas 					 e4b->bd_group, i, i * 8, b1[i], b2[i]);
609c9de560dSAlex Tomas 				BUG();
610c9de560dSAlex Tomas 			}
611c9de560dSAlex Tomas 		}
612c9de560dSAlex Tomas 	}
613c9de560dSAlex Tomas }
614c9de560dSAlex Tomas 
615a3450215SRitesh Harjani static void mb_group_bb_bitmap_alloc(struct super_block *sb,
616a3450215SRitesh Harjani 			struct ext4_group_info *grp, ext4_group_t group)
617a3450215SRitesh Harjani {
618a3450215SRitesh Harjani 	struct buffer_head *bh;
619a3450215SRitesh Harjani 
620a3450215SRitesh Harjani 	grp->bb_bitmap = kmalloc(sb->s_blocksize, GFP_NOFS);
621eb2b8ebbSRitesh Harjani 	if (!grp->bb_bitmap)
622eb2b8ebbSRitesh Harjani 		return;
623a3450215SRitesh Harjani 
624a3450215SRitesh Harjani 	bh = ext4_read_block_bitmap(sb, group);
625eb2b8ebbSRitesh Harjani 	if (IS_ERR_OR_NULL(bh)) {
626eb2b8ebbSRitesh Harjani 		kfree(grp->bb_bitmap);
627eb2b8ebbSRitesh Harjani 		grp->bb_bitmap = NULL;
628eb2b8ebbSRitesh Harjani 		return;
629eb2b8ebbSRitesh Harjani 	}
630a3450215SRitesh Harjani 
631a3450215SRitesh Harjani 	memcpy(grp->bb_bitmap, bh->b_data, sb->s_blocksize);
632a3450215SRitesh Harjani 	put_bh(bh);
633a3450215SRitesh Harjani }
634a3450215SRitesh Harjani 
635a3450215SRitesh Harjani static void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
636a3450215SRitesh Harjani {
637a3450215SRitesh Harjani 	kfree(grp->bb_bitmap);
638a3450215SRitesh Harjani }
639a3450215SRitesh Harjani 
640c9de560dSAlex Tomas #else
641c9de560dSAlex Tomas static inline void mb_free_blocks_double(struct inode *inode,
642c9de560dSAlex Tomas 				struct ext4_buddy *e4b, int first, int count)
643c9de560dSAlex Tomas {
644c9de560dSAlex Tomas 	return;
645c9de560dSAlex Tomas }
646c9de560dSAlex Tomas static inline void mb_mark_used_double(struct ext4_buddy *e4b,
647c9de560dSAlex Tomas 						int first, int count)
648c9de560dSAlex Tomas {
649c9de560dSAlex Tomas 	return;
650c9de560dSAlex Tomas }
651c9de560dSAlex Tomas static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
652c9de560dSAlex Tomas {
653c9de560dSAlex Tomas 	return;
654c9de560dSAlex Tomas }
655a3450215SRitesh Harjani 
656a3450215SRitesh Harjani static inline void mb_group_bb_bitmap_alloc(struct super_block *sb,
657a3450215SRitesh Harjani 			struct ext4_group_info *grp, ext4_group_t group)
658a3450215SRitesh Harjani {
659a3450215SRitesh Harjani 	return;
660a3450215SRitesh Harjani }
661a3450215SRitesh Harjani 
662a3450215SRitesh Harjani static inline void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
663a3450215SRitesh Harjani {
664a3450215SRitesh Harjani 	return;
665a3450215SRitesh Harjani }
666c9de560dSAlex Tomas #endif
667c9de560dSAlex Tomas 
668c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
669c9de560dSAlex Tomas 
670c9de560dSAlex Tomas #define MB_CHECK_ASSERT(assert)						\
671c9de560dSAlex Tomas do {									\
672c9de560dSAlex Tomas 	if (!(assert)) {						\
673c9de560dSAlex Tomas 		printk(KERN_EMERG					\
674c9de560dSAlex Tomas 			"Assertion failure in %s() at %s:%d: \"%s\"\n",	\
675c9de560dSAlex Tomas 			function, file, line, # assert);		\
676c9de560dSAlex Tomas 		BUG();							\
677c9de560dSAlex Tomas 	}								\
678c9de560dSAlex Tomas } while (0)
679c9de560dSAlex Tomas 
680133de5a0SKemeng Shi static void __mb_check_buddy(struct ext4_buddy *e4b, char *file,
681c9de560dSAlex Tomas 				const char *function, int line)
682c9de560dSAlex Tomas {
683c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
684c9de560dSAlex Tomas 	int order = e4b->bd_blkbits + 1;
685c9de560dSAlex Tomas 	int max;
686c9de560dSAlex Tomas 	int max2;
687c9de560dSAlex Tomas 	int i;
688c9de560dSAlex Tomas 	int j;
689c9de560dSAlex Tomas 	int k;
690c9de560dSAlex Tomas 	int count;
691c9de560dSAlex Tomas 	struct ext4_group_info *grp;
692c9de560dSAlex Tomas 	int fragments = 0;
693c9de560dSAlex Tomas 	int fstart;
694c9de560dSAlex Tomas 	struct list_head *cur;
695c9de560dSAlex Tomas 	void *buddy;
696c9de560dSAlex Tomas 	void *buddy2;
697c9de560dSAlex Tomas 
698addd752cSChunguang Xu 	if (e4b->bd_info->bb_check_counter++ % 10)
699133de5a0SKemeng Shi 		return;
700c9de560dSAlex Tomas 
701c9de560dSAlex Tomas 	while (order > 1) {
702c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, order, &max);
703c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy);
704c9de560dSAlex Tomas 		buddy2 = mb_find_buddy(e4b, order - 1, &max2);
705c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy2);
706c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy != buddy2);
707c9de560dSAlex Tomas 		MB_CHECK_ASSERT(max * 2 == max2);
708c9de560dSAlex Tomas 
709c9de560dSAlex Tomas 		count = 0;
710c9de560dSAlex Tomas 		for (i = 0; i < max; i++) {
711c9de560dSAlex Tomas 
712c9de560dSAlex Tomas 			if (mb_test_bit(i, buddy)) {
713af2b3275SJinke Han 				/* only single bit in buddy2 may be 0 */
714c9de560dSAlex Tomas 				if (!mb_test_bit(i << 1, buddy2)) {
715c9de560dSAlex Tomas 					MB_CHECK_ASSERT(
716c9de560dSAlex Tomas 						mb_test_bit((i<<1)+1, buddy2));
717c9de560dSAlex Tomas 				}
718c9de560dSAlex Tomas 				continue;
719c9de560dSAlex Tomas 			}
720c9de560dSAlex Tomas 
7210a10da73SRobin Dong 			/* both bits in buddy2 must be 1 */
722c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
723c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
724c9de560dSAlex Tomas 
725c9de560dSAlex Tomas 			for (j = 0; j < (1 << order); j++) {
726c9de560dSAlex Tomas 				k = (i * (1 << order)) + j;
727c9de560dSAlex Tomas 				MB_CHECK_ASSERT(
728c5e8f3f3STheodore Ts'o 					!mb_test_bit(k, e4b->bd_bitmap));
729c9de560dSAlex Tomas 			}
730c9de560dSAlex Tomas 			count++;
731c9de560dSAlex Tomas 		}
732c9de560dSAlex Tomas 		MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
733c9de560dSAlex Tomas 		order--;
734c9de560dSAlex Tomas 	}
735c9de560dSAlex Tomas 
736c9de560dSAlex Tomas 	fstart = -1;
737c9de560dSAlex Tomas 	buddy = mb_find_buddy(e4b, 0, &max);
738c9de560dSAlex Tomas 	for (i = 0; i < max; i++) {
739c9de560dSAlex Tomas 		if (!mb_test_bit(i, buddy)) {
740c9de560dSAlex Tomas 			MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
741c9de560dSAlex Tomas 			if (fstart == -1) {
742c9de560dSAlex Tomas 				fragments++;
743c9de560dSAlex Tomas 				fstart = i;
744c9de560dSAlex Tomas 			}
745c9de560dSAlex Tomas 			continue;
746c9de560dSAlex Tomas 		}
747c9de560dSAlex Tomas 		fstart = -1;
748c9de560dSAlex Tomas 		/* check used bits only */
749c9de560dSAlex Tomas 		for (j = 0; j < e4b->bd_blkbits + 1; j++) {
750c9de560dSAlex Tomas 			buddy2 = mb_find_buddy(e4b, j, &max2);
751c9de560dSAlex Tomas 			k = i >> j;
752c9de560dSAlex Tomas 			MB_CHECK_ASSERT(k < max2);
753c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
754c9de560dSAlex Tomas 		}
755c9de560dSAlex Tomas 	}
756c9de560dSAlex Tomas 	MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
757c9de560dSAlex Tomas 	MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
758c9de560dSAlex Tomas 
759c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, e4b->bd_group);
7605354b2afSTheodore Ts'o 	if (!grp)
761133de5a0SKemeng Shi 		return;
762c9de560dSAlex Tomas 	list_for_each(cur, &grp->bb_prealloc_list) {
763c9de560dSAlex Tomas 		ext4_group_t groupnr;
764c9de560dSAlex Tomas 		struct ext4_prealloc_space *pa;
76560bd63d1SSolofo Ramangalahy 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
76660bd63d1SSolofo Ramangalahy 		ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
767c9de560dSAlex Tomas 		MB_CHECK_ASSERT(groupnr == e4b->bd_group);
76860bd63d1SSolofo Ramangalahy 		for (i = 0; i < pa->pa_len; i++)
769c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
770c9de560dSAlex Tomas 	}
771c9de560dSAlex Tomas }
772c9de560dSAlex Tomas #undef MB_CHECK_ASSERT
773c9de560dSAlex Tomas #define mb_check_buddy(e4b) __mb_check_buddy(e4b,	\
77446e665e9SHarvey Harrison 					__FILE__, __func__, __LINE__)
775c9de560dSAlex Tomas #else
776c9de560dSAlex Tomas #define mb_check_buddy(e4b)
777c9de560dSAlex Tomas #endif
778c9de560dSAlex Tomas 
7797c786059SColy Li /*
7807c786059SColy Li  * Divide blocks started from @first with length @len into
7817c786059SColy Li  * smaller chunks with power of 2 blocks.
7827c786059SColy Li  * Clear the bits in bitmap which the blocks of the chunk(s) covered,
7837c786059SColy Li  * then increase bb_counters[] for corresponded chunk size.
7847c786059SColy Li  */
785c9de560dSAlex Tomas static void ext4_mb_mark_free_simple(struct super_block *sb,
786a36b4498SEric Sandeen 				void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
787c9de560dSAlex Tomas 					struct ext4_group_info *grp)
788c9de560dSAlex Tomas {
789c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
790a36b4498SEric Sandeen 	ext4_grpblk_t min;
791a36b4498SEric Sandeen 	ext4_grpblk_t max;
792a36b4498SEric Sandeen 	ext4_grpblk_t chunk;
79369e43e8cSChandan Rajendra 	unsigned int border;
794c9de560dSAlex Tomas 
7957137d7a4STheodore Ts'o 	BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
796c9de560dSAlex Tomas 
797c9de560dSAlex Tomas 	border = 2 << sb->s_blocksize_bits;
798c9de560dSAlex Tomas 
799c9de560dSAlex Tomas 	while (len > 0) {
800c9de560dSAlex Tomas 		/* find how many blocks can be covered since this position */
801c9de560dSAlex Tomas 		max = ffs(first | border) - 1;
802c9de560dSAlex Tomas 
803c9de560dSAlex Tomas 		/* find how many blocks of power 2 we need to mark */
804c9de560dSAlex Tomas 		min = fls(len) - 1;
805c9de560dSAlex Tomas 
806c9de560dSAlex Tomas 		if (max < min)
807c9de560dSAlex Tomas 			min = max;
808c9de560dSAlex Tomas 		chunk = 1 << min;
809c9de560dSAlex Tomas 
810c9de560dSAlex Tomas 		/* mark multiblock chunks only */
811c9de560dSAlex Tomas 		grp->bb_counters[min]++;
812c9de560dSAlex Tomas 		if (min > 0)
813c9de560dSAlex Tomas 			mb_clear_bit(first >> min,
814c9de560dSAlex Tomas 				     buddy + sbi->s_mb_offsets[min]);
815c9de560dSAlex Tomas 
816c9de560dSAlex Tomas 		len -= chunk;
817c9de560dSAlex Tomas 		first += chunk;
818c9de560dSAlex Tomas 	}
819c9de560dSAlex Tomas }
820c9de560dSAlex Tomas 
82183e80a6eSJan Kara static int mb_avg_fragment_size_order(struct super_block *sb, ext4_grpblk_t len)
822196e402aSHarshad Shirwadkar {
82383e80a6eSJan Kara 	int order;
824196e402aSHarshad Shirwadkar 
825196e402aSHarshad Shirwadkar 	/*
82683e80a6eSJan Kara 	 * We don't bother with a special lists groups with only 1 block free
82783e80a6eSJan Kara 	 * extents and for completely empty groups.
828196e402aSHarshad Shirwadkar 	 */
82983e80a6eSJan Kara 	order = fls(len) - 2;
83083e80a6eSJan Kara 	if (order < 0)
83183e80a6eSJan Kara 		return 0;
83283e80a6eSJan Kara 	if (order == MB_NUM_ORDERS(sb))
83383e80a6eSJan Kara 		order--;
83413df4d44SBaokun Li 	if (WARN_ON_ONCE(order > MB_NUM_ORDERS(sb)))
83513df4d44SBaokun Li 		order = MB_NUM_ORDERS(sb) - 1;
83683e80a6eSJan Kara 	return order;
83783e80a6eSJan Kara }
83883e80a6eSJan Kara 
83983e80a6eSJan Kara /* Move group to appropriate avg_fragment_size list */
840196e402aSHarshad Shirwadkar static void
841196e402aSHarshad Shirwadkar mb_update_avg_fragment_size(struct super_block *sb, struct ext4_group_info *grp)
842196e402aSHarshad Shirwadkar {
843196e402aSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
84483e80a6eSJan Kara 	int new_order;
845196e402aSHarshad Shirwadkar 
846993bf0f4SBaokun Li 	if (!test_opt2(sb, MB_OPTIMIZE_SCAN) || grp->bb_fragments == 0)
847196e402aSHarshad Shirwadkar 		return;
848196e402aSHarshad Shirwadkar 
84983e80a6eSJan Kara 	new_order = mb_avg_fragment_size_order(sb,
85083e80a6eSJan Kara 					grp->bb_free / grp->bb_fragments);
85183e80a6eSJan Kara 	if (new_order == grp->bb_avg_fragment_size_order)
85283e80a6eSJan Kara 		return;
853196e402aSHarshad Shirwadkar 
85483e80a6eSJan Kara 	if (grp->bb_avg_fragment_size_order != -1) {
85583e80a6eSJan Kara 		write_lock(&sbi->s_mb_avg_fragment_size_locks[
85683e80a6eSJan Kara 					grp->bb_avg_fragment_size_order]);
85783e80a6eSJan Kara 		list_del(&grp->bb_avg_fragment_size_node);
85883e80a6eSJan Kara 		write_unlock(&sbi->s_mb_avg_fragment_size_locks[
85983e80a6eSJan Kara 					grp->bb_avg_fragment_size_order]);
86083e80a6eSJan Kara 	}
86183e80a6eSJan Kara 	grp->bb_avg_fragment_size_order = new_order;
86283e80a6eSJan Kara 	write_lock(&sbi->s_mb_avg_fragment_size_locks[
86383e80a6eSJan Kara 					grp->bb_avg_fragment_size_order]);
86483e80a6eSJan Kara 	list_add_tail(&grp->bb_avg_fragment_size_node,
86583e80a6eSJan Kara 		&sbi->s_mb_avg_fragment_size[grp->bb_avg_fragment_size_order]);
86683e80a6eSJan Kara 	write_unlock(&sbi->s_mb_avg_fragment_size_locks[
86783e80a6eSJan Kara 					grp->bb_avg_fragment_size_order]);
868196e402aSHarshad Shirwadkar }
869196e402aSHarshad Shirwadkar 
870196e402aSHarshad Shirwadkar /*
871196e402aSHarshad Shirwadkar  * Choose next group by traversing largest_free_order lists. Updates *new_cr if
872196e402aSHarshad Shirwadkar  * cr level needs an update.
873196e402aSHarshad Shirwadkar  */
874f52f3d2bSOjaswin Mujoo static void ext4_mb_choose_next_group_p2_aligned(struct ext4_allocation_context *ac,
875438a35e7SKemeng Shi 			enum criteria *new_cr, ext4_group_t *group)
876196e402aSHarshad Shirwadkar {
877196e402aSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
878919eb90cSKemeng Shi 	struct ext4_group_info *iter;
879196e402aSHarshad Shirwadkar 	int i;
880196e402aSHarshad Shirwadkar 
881196e402aSHarshad Shirwadkar 	if (ac->ac_status == AC_STATUS_FOUND)
882196e402aSHarshad Shirwadkar 		return;
883196e402aSHarshad Shirwadkar 
884f52f3d2bSOjaswin Mujoo 	if (unlikely(sbi->s_mb_stats && ac->ac_flags & EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED))
885f52f3d2bSOjaswin Mujoo 		atomic_inc(&sbi->s_bal_p2_aligned_bad_suggestions);
886196e402aSHarshad Shirwadkar 
887196e402aSHarshad Shirwadkar 	for (i = ac->ac_2order; i < MB_NUM_ORDERS(ac->ac_sb); i++) {
888196e402aSHarshad Shirwadkar 		if (list_empty(&sbi->s_mb_largest_free_orders[i]))
889196e402aSHarshad Shirwadkar 			continue;
890196e402aSHarshad Shirwadkar 		read_lock(&sbi->s_mb_largest_free_orders_locks[i]);
891196e402aSHarshad Shirwadkar 		if (list_empty(&sbi->s_mb_largest_free_orders[i])) {
892196e402aSHarshad Shirwadkar 			read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
893196e402aSHarshad Shirwadkar 			continue;
894196e402aSHarshad Shirwadkar 		}
895196e402aSHarshad Shirwadkar 		list_for_each_entry(iter, &sbi->s_mb_largest_free_orders[i],
896196e402aSHarshad Shirwadkar 				    bb_largest_free_order_node) {
897196e402aSHarshad Shirwadkar 			if (sbi->s_mb_stats)
898f52f3d2bSOjaswin Mujoo 				atomic64_inc(&sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]);
899f52f3d2bSOjaswin Mujoo 			if (likely(ext4_mb_good_group(ac, iter->bb_group, CR_POWER2_ALIGNED))) {
900919eb90cSKemeng Shi 				*group = iter->bb_group;
901919eb90cSKemeng Shi 				ac->ac_flags |= EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED;
902919eb90cSKemeng Shi 				read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
903919eb90cSKemeng Shi 				return;
904196e402aSHarshad Shirwadkar 			}
905196e402aSHarshad Shirwadkar 		}
906196e402aSHarshad Shirwadkar 		read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
907196e402aSHarshad Shirwadkar 	}
908196e402aSHarshad Shirwadkar 
909919eb90cSKemeng Shi 	/* Increment cr and search again if no group is found */
910f52f3d2bSOjaswin Mujoo 	*new_cr = CR_GOAL_LEN_FAST;
911196e402aSHarshad Shirwadkar }
912196e402aSHarshad Shirwadkar 
913196e402aSHarshad Shirwadkar /*
914856d865cSOjaswin Mujoo  * Find a suitable group of given order from the average fragments list.
915856d865cSOjaswin Mujoo  */
916856d865cSOjaswin Mujoo static struct ext4_group_info *
917856d865cSOjaswin Mujoo ext4_mb_find_good_group_avg_frag_lists(struct ext4_allocation_context *ac, int order)
918856d865cSOjaswin Mujoo {
919856d865cSOjaswin Mujoo 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
920856d865cSOjaswin Mujoo 	struct list_head *frag_list = &sbi->s_mb_avg_fragment_size[order];
921856d865cSOjaswin Mujoo 	rwlock_t *frag_list_lock = &sbi->s_mb_avg_fragment_size_locks[order];
922856d865cSOjaswin Mujoo 	struct ext4_group_info *grp = NULL, *iter;
923856d865cSOjaswin Mujoo 	enum criteria cr = ac->ac_criteria;
924856d865cSOjaswin Mujoo 
925856d865cSOjaswin Mujoo 	if (list_empty(frag_list))
926856d865cSOjaswin Mujoo 		return NULL;
927856d865cSOjaswin Mujoo 	read_lock(frag_list_lock);
928856d865cSOjaswin Mujoo 	if (list_empty(frag_list)) {
929856d865cSOjaswin Mujoo 		read_unlock(frag_list_lock);
930856d865cSOjaswin Mujoo 		return NULL;
931856d865cSOjaswin Mujoo 	}
932856d865cSOjaswin Mujoo 	list_for_each_entry(iter, frag_list, bb_avg_fragment_size_node) {
933856d865cSOjaswin Mujoo 		if (sbi->s_mb_stats)
934856d865cSOjaswin Mujoo 			atomic64_inc(&sbi->s_bal_cX_groups_considered[cr]);
935856d865cSOjaswin Mujoo 		if (likely(ext4_mb_good_group(ac, iter->bb_group, cr))) {
936856d865cSOjaswin Mujoo 			grp = iter;
937856d865cSOjaswin Mujoo 			break;
938856d865cSOjaswin Mujoo 		}
939856d865cSOjaswin Mujoo 	}
940856d865cSOjaswin Mujoo 	read_unlock(frag_list_lock);
941856d865cSOjaswin Mujoo 	return grp;
942856d865cSOjaswin Mujoo }
943856d865cSOjaswin Mujoo 
944856d865cSOjaswin Mujoo /*
94583e80a6eSJan Kara  * Choose next group by traversing average fragment size list of suitable
94683e80a6eSJan Kara  * order. Updates *new_cr if cr level needs an update.
947196e402aSHarshad Shirwadkar  */
948f52f3d2bSOjaswin Mujoo static void ext4_mb_choose_next_group_goal_fast(struct ext4_allocation_context *ac,
949438a35e7SKemeng Shi 		enum criteria *new_cr, ext4_group_t *group)
950196e402aSHarshad Shirwadkar {
951196e402aSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
952856d865cSOjaswin Mujoo 	struct ext4_group_info *grp = NULL;
95383e80a6eSJan Kara 	int i;
954196e402aSHarshad Shirwadkar 
955f52f3d2bSOjaswin Mujoo 	if (unlikely(ac->ac_flags & EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED)) {
956196e402aSHarshad Shirwadkar 		if (sbi->s_mb_stats)
957f52f3d2bSOjaswin Mujoo 			atomic_inc(&sbi->s_bal_goal_fast_bad_suggestions);
95883e80a6eSJan Kara 	}
95983e80a6eSJan Kara 
96083e80a6eSJan Kara 	for (i = mb_avg_fragment_size_order(ac->ac_sb, ac->ac_g_ex.fe_len);
96183e80a6eSJan Kara 	     i < MB_NUM_ORDERS(ac->ac_sb); i++) {
962856d865cSOjaswin Mujoo 		grp = ext4_mb_find_good_group_avg_frag_lists(ac, i);
96383e80a6eSJan Kara 		if (grp) {
964196e402aSHarshad Shirwadkar 			*group = grp->bb_group;
965f52f3d2bSOjaswin Mujoo 			ac->ac_flags |= EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED;
966b50675a4SKemeng Shi 			return;
9677e170922SOjaswin Mujoo 		}
9687e170922SOjaswin Mujoo 	}
9697e170922SOjaswin Mujoo 
970772c9f69SRitesh Harjani 	/*
971772c9f69SRitesh Harjani 	 * CR_BEST_AVAIL_LEN works based on the concept that we have
972772c9f69SRitesh Harjani 	 * a larger normalized goal len request which can be trimmed to
973772c9f69SRitesh Harjani 	 * a smaller goal len such that it can still satisfy original
974772c9f69SRitesh Harjani 	 * request len. However, allocation request for non-regular
975772c9f69SRitesh Harjani 	 * files never gets normalized.
976772c9f69SRitesh Harjani 	 * See function ext4_mb_normalize_request() (EXT4_MB_HINT_DATA).
977772c9f69SRitesh Harjani 	 */
978772c9f69SRitesh Harjani 	if (ac->ac_flags & EXT4_MB_HINT_DATA)
979b50675a4SKemeng Shi 		*new_cr = CR_BEST_AVAIL_LEN;
980772c9f69SRitesh Harjani 	else
981772c9f69SRitesh Harjani 		*new_cr = CR_GOAL_LEN_SLOW;
982b50675a4SKemeng Shi }
983b50675a4SKemeng Shi 
9847e170922SOjaswin Mujoo /*
985f52f3d2bSOjaswin Mujoo  * We couldn't find a group in CR_GOAL_LEN_FAST so try to find the highest free fragment
9867e170922SOjaswin Mujoo  * order we have and proactively trim the goal request length to that order to
9877e170922SOjaswin Mujoo  * find a suitable group faster.
9887e170922SOjaswin Mujoo  *
9897e170922SOjaswin Mujoo  * This optimizes allocation speed at the cost of slightly reduced
9907e170922SOjaswin Mujoo  * preallocations. However, we make sure that we don't trim the request too
991f52f3d2bSOjaswin Mujoo  * much and fall to CR_GOAL_LEN_SLOW in that case.
9927e170922SOjaswin Mujoo  */
993f52f3d2bSOjaswin Mujoo static void ext4_mb_choose_next_group_best_avail(struct ext4_allocation_context *ac,
994438a35e7SKemeng Shi 		enum criteria *new_cr, ext4_group_t *group)
9957e170922SOjaswin Mujoo {
9967e170922SOjaswin Mujoo 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
9977e170922SOjaswin Mujoo 	struct ext4_group_info *grp = NULL;
9987e170922SOjaswin Mujoo 	int i, order, min_order;
9997e170922SOjaswin Mujoo 	unsigned long num_stripe_clusters = 0;
10007e170922SOjaswin Mujoo 
1001f52f3d2bSOjaswin Mujoo 	if (unlikely(ac->ac_flags & EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED)) {
10027e170922SOjaswin Mujoo 		if (sbi->s_mb_stats)
1003f52f3d2bSOjaswin Mujoo 			atomic_inc(&sbi->s_bal_best_avail_bad_suggestions);
10047e170922SOjaswin Mujoo 	}
10057e170922SOjaswin Mujoo 
10067e170922SOjaswin Mujoo 	/*
10077e170922SOjaswin Mujoo 	 * mb_avg_fragment_size_order() returns order in a way that makes
10087e170922SOjaswin Mujoo 	 * retrieving back the length using (1 << order) inaccurate. Hence, use
10097e170922SOjaswin Mujoo 	 * fls() instead since we need to know the actual length while modifying
10107e170922SOjaswin Mujoo 	 * goal length.
10117e170922SOjaswin Mujoo 	 */
10125d5460faSOjaswin Mujoo 	order = fls(ac->ac_g_ex.fe_len) - 1;
101313df4d44SBaokun Li 	if (WARN_ON_ONCE(order - 1 > MB_NUM_ORDERS(ac->ac_sb)))
101413df4d44SBaokun Li 		order = MB_NUM_ORDERS(ac->ac_sb);
1015f52f3d2bSOjaswin Mujoo 	min_order = order - sbi->s_mb_best_avail_max_trim_order;
10167e170922SOjaswin Mujoo 	if (min_order < 0)
10177e170922SOjaswin Mujoo 		min_order = 0;
10187e170922SOjaswin Mujoo 
10197e170922SOjaswin Mujoo 	if (sbi->s_stripe > 0) {
10207e170922SOjaswin Mujoo 		/*
10217e170922SOjaswin Mujoo 		 * We are assuming that stripe size is always a multiple of
10227e170922SOjaswin Mujoo 		 * cluster ratio otherwise __ext4_fill_super exists early.
10237e170922SOjaswin Mujoo 		 */
10247e170922SOjaswin Mujoo 		num_stripe_clusters = EXT4_NUM_B2C(sbi, sbi->s_stripe);
10257e170922SOjaswin Mujoo 		if (1 << min_order < num_stripe_clusters)
10265d5460faSOjaswin Mujoo 			/*
10275d5460faSOjaswin Mujoo 			 * We consider 1 order less because later we round
10285d5460faSOjaswin Mujoo 			 * up the goal len to num_stripe_clusters
10295d5460faSOjaswin Mujoo 			 */
10305d5460faSOjaswin Mujoo 			min_order = fls(num_stripe_clusters) - 1;
10317e170922SOjaswin Mujoo 	}
10327e170922SOjaswin Mujoo 
10335d5460faSOjaswin Mujoo 	if (1 << min_order < ac->ac_o_ex.fe_len)
10345d5460faSOjaswin Mujoo 		min_order = fls(ac->ac_o_ex.fe_len);
10355d5460faSOjaswin Mujoo 
10367e170922SOjaswin Mujoo 	for (i = order; i >= min_order; i--) {
10377e170922SOjaswin Mujoo 		int frag_order;
10387e170922SOjaswin Mujoo 		/*
10397e170922SOjaswin Mujoo 		 * Scale down goal len to make sure we find something
10407e170922SOjaswin Mujoo 		 * in the free fragments list. Basically, reduce
10417e170922SOjaswin Mujoo 		 * preallocations.
10427e170922SOjaswin Mujoo 		 */
10437e170922SOjaswin Mujoo 		ac->ac_g_ex.fe_len = 1 << i;
10447e170922SOjaswin Mujoo 
10457e170922SOjaswin Mujoo 		if (num_stripe_clusters > 0) {
10467e170922SOjaswin Mujoo 			/*
10474c0cfebdSTheodore Ts'o 			 * Try to round up the adjusted goal length to
10484c0cfebdSTheodore Ts'o 			 * stripe size (in cluster units) multiple for
10494c0cfebdSTheodore Ts'o 			 * efficiency.
10507e170922SOjaswin Mujoo 			 */
10517e170922SOjaswin Mujoo 			ac->ac_g_ex.fe_len = roundup(ac->ac_g_ex.fe_len,
10527e170922SOjaswin Mujoo 						     num_stripe_clusters);
10537e170922SOjaswin Mujoo 		}
10547e170922SOjaswin Mujoo 
10557e170922SOjaswin Mujoo 		frag_order = mb_avg_fragment_size_order(ac->ac_sb,
10567e170922SOjaswin Mujoo 							ac->ac_g_ex.fe_len);
10577e170922SOjaswin Mujoo 
10587e170922SOjaswin Mujoo 		grp = ext4_mb_find_good_group_avg_frag_lists(ac, frag_order);
10597e170922SOjaswin Mujoo 		if (grp) {
10607e170922SOjaswin Mujoo 			*group = grp->bb_group;
1061f52f3d2bSOjaswin Mujoo 			ac->ac_flags |= EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED;
1062bcb123acSKemeng Shi 			return;
1063bcb123acSKemeng Shi 		}
1064bcb123acSKemeng Shi 	}
1065bcb123acSKemeng Shi 
1066f52f3d2bSOjaswin Mujoo 	/* Reset goal length to original goal length before falling into CR_GOAL_LEN_SLOW */
10677e170922SOjaswin Mujoo 	ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
1068f52f3d2bSOjaswin Mujoo 	*new_cr = CR_GOAL_LEN_SLOW;
1069196e402aSHarshad Shirwadkar }
1070196e402aSHarshad Shirwadkar 
1071196e402aSHarshad Shirwadkar static inline int should_optimize_scan(struct ext4_allocation_context *ac)
1072196e402aSHarshad Shirwadkar {
1073196e402aSHarshad Shirwadkar 	if (unlikely(!test_opt2(ac->ac_sb, MB_OPTIMIZE_SCAN)))
1074196e402aSHarshad Shirwadkar 		return 0;
1075f52f3d2bSOjaswin Mujoo 	if (ac->ac_criteria >= CR_GOAL_LEN_SLOW)
1076196e402aSHarshad Shirwadkar 		return 0;
1077077d0c2cSOjaswin Mujoo 	if (!ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS))
1078196e402aSHarshad Shirwadkar 		return 0;
1079196e402aSHarshad Shirwadkar 	return 1;
1080196e402aSHarshad Shirwadkar }
1081196e402aSHarshad Shirwadkar 
1082196e402aSHarshad Shirwadkar /*
1083da5704eeSKemeng Shi  * Return next linear group for allocation.
1084196e402aSHarshad Shirwadkar  */
108560c672b7SKemeng Shi static ext4_group_t
1086da5704eeSKemeng Shi next_linear_group(ext4_group_t group, ext4_group_t ngroups)
1087196e402aSHarshad Shirwadkar {
1088196e402aSHarshad Shirwadkar 	/*
1089196e402aSHarshad Shirwadkar 	 * Artificially restricted ngroups for non-extent
1090196e402aSHarshad Shirwadkar 	 * files makes group > ngroups possible on first loop.
1091196e402aSHarshad Shirwadkar 	 */
1092196e402aSHarshad Shirwadkar 	return group + 1 >= ngroups ? 0 : group + 1;
1093196e402aSHarshad Shirwadkar }
1094196e402aSHarshad Shirwadkar 
1095196e402aSHarshad Shirwadkar /*
1096196e402aSHarshad Shirwadkar  * ext4_mb_choose_next_group: choose next group for allocation.
1097196e402aSHarshad Shirwadkar  *
1098196e402aSHarshad Shirwadkar  * @ac        Allocation Context
1099196e402aSHarshad Shirwadkar  * @new_cr    This is an output parameter. If the there is no good group
1100196e402aSHarshad Shirwadkar  *            available at current CR level, this field is updated to indicate
1101196e402aSHarshad Shirwadkar  *            the new cr level that should be used.
1102196e402aSHarshad Shirwadkar  * @group     This is an input / output parameter. As an input it indicates the
1103196e402aSHarshad Shirwadkar  *            next group that the allocator intends to use for allocation. As
1104196e402aSHarshad Shirwadkar  *            output, this field indicates the next group that should be used as
1105196e402aSHarshad Shirwadkar  *            determined by the optimization functions.
1106196e402aSHarshad Shirwadkar  * @ngroups   Total number of groups
1107196e402aSHarshad Shirwadkar  */
1108196e402aSHarshad Shirwadkar static void ext4_mb_choose_next_group(struct ext4_allocation_context *ac,
11094eb7a4a1SOjaswin Mujoo 		enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
1110196e402aSHarshad Shirwadkar {
1111196e402aSHarshad Shirwadkar 	*new_cr = ac->ac_criteria;
1112196e402aSHarshad Shirwadkar 
1113da5704eeSKemeng Shi 	if (!should_optimize_scan(ac)) {
1114da5704eeSKemeng Shi 		*group = next_linear_group(*group, ngroups);
1115da5704eeSKemeng Shi 		return;
1116da5704eeSKemeng Shi 	}
1117da5704eeSKemeng Shi 
1118da5704eeSKemeng Shi 	/*
1119da5704eeSKemeng Shi 	 * Optimized scanning can return non adjacent groups which can cause
1120da5704eeSKemeng Shi 	 * seek overhead for rotational disks. So try few linear groups before
1121da5704eeSKemeng Shi 	 * trying optimized scan.
1122da5704eeSKemeng Shi 	 */
1123da5704eeSKemeng Shi 	if (ac->ac_groups_linear_remaining) {
1124da5704eeSKemeng Shi 		*group = next_linear_group(*group, ngroups);
1125da5704eeSKemeng Shi 		ac->ac_groups_linear_remaining--;
1126196e402aSHarshad Shirwadkar 		return;
11274fca50d4SJan Kara 	}
1128196e402aSHarshad Shirwadkar 
1129f52f3d2bSOjaswin Mujoo 	if (*new_cr == CR_POWER2_ALIGNED) {
1130438a35e7SKemeng Shi 		ext4_mb_choose_next_group_p2_aligned(ac, new_cr, group);
1131f52f3d2bSOjaswin Mujoo 	} else if (*new_cr == CR_GOAL_LEN_FAST) {
1132438a35e7SKemeng Shi 		ext4_mb_choose_next_group_goal_fast(ac, new_cr, group);
1133f52f3d2bSOjaswin Mujoo 	} else if (*new_cr == CR_BEST_AVAIL_LEN) {
1134438a35e7SKemeng Shi 		ext4_mb_choose_next_group_best_avail(ac, new_cr, group);
1135196e402aSHarshad Shirwadkar 	} else {
1136196e402aSHarshad Shirwadkar 		/*
11372caffb6aSKemeng Shi 		 * TODO: For CR_GOAL_LEN_SLOW, we can arrange groups in an
11382caffb6aSKemeng Shi 		 * rb tree sorted by bb_free. But until that happens, we should
11392caffb6aSKemeng Shi 		 * never come here.
1140196e402aSHarshad Shirwadkar 		 */
1141196e402aSHarshad Shirwadkar 		WARN_ON(1);
1142196e402aSHarshad Shirwadkar 	}
1143196e402aSHarshad Shirwadkar }
1144196e402aSHarshad Shirwadkar 
11458a57d9d6SCurt Wohlgemuth /*
11468a57d9d6SCurt Wohlgemuth  * Cache the order of the largest free extent we have available in this block
11478a57d9d6SCurt Wohlgemuth  * group.
11488a57d9d6SCurt Wohlgemuth  */
11498a57d9d6SCurt Wohlgemuth static void
11508a57d9d6SCurt Wohlgemuth mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
11518a57d9d6SCurt Wohlgemuth {
1152196e402aSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
11538a57d9d6SCurt Wohlgemuth 	int i;
11548a57d9d6SCurt Wohlgemuth 
11551940265eSJan Kara 	for (i = MB_NUM_ORDERS(sb) - 1; i >= 0; i--)
11561940265eSJan Kara 		if (grp->bb_counters[i] > 0)
11571940265eSJan Kara 			break;
11581940265eSJan Kara 	/* No need to move between order lists? */
11591940265eSJan Kara 	if (!test_opt2(sb, MB_OPTIMIZE_SCAN) ||
11601940265eSJan Kara 	    i == grp->bb_largest_free_order) {
11611940265eSJan Kara 		grp->bb_largest_free_order = i;
11621940265eSJan Kara 		return;
11631940265eSJan Kara 	}
11641940265eSJan Kara 
11651940265eSJan Kara 	if (grp->bb_largest_free_order >= 0) {
1166196e402aSHarshad Shirwadkar 		write_lock(&sbi->s_mb_largest_free_orders_locks[
1167196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1168196e402aSHarshad Shirwadkar 		list_del_init(&grp->bb_largest_free_order_node);
1169196e402aSHarshad Shirwadkar 		write_unlock(&sbi->s_mb_largest_free_orders_locks[
1170196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1171196e402aSHarshad Shirwadkar 	}
11728a57d9d6SCurt Wohlgemuth 	grp->bb_largest_free_order = i;
11731940265eSJan Kara 	if (grp->bb_largest_free_order >= 0 && grp->bb_free) {
1174196e402aSHarshad Shirwadkar 		write_lock(&sbi->s_mb_largest_free_orders_locks[
1175196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1176196e402aSHarshad Shirwadkar 		list_add_tail(&grp->bb_largest_free_order_node,
1177196e402aSHarshad Shirwadkar 		      &sbi->s_mb_largest_free_orders[grp->bb_largest_free_order]);
1178196e402aSHarshad Shirwadkar 		write_unlock(&sbi->s_mb_largest_free_orders_locks[
1179196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1180196e402aSHarshad Shirwadkar 	}
11818a57d9d6SCurt Wohlgemuth }
11828a57d9d6SCurt Wohlgemuth 
1183089ceeccSEric Sandeen static noinline_for_stack
1184089ceeccSEric Sandeen void ext4_mb_generate_buddy(struct super_block *sb,
11855354b2afSTheodore Ts'o 			    void *buddy, void *bitmap, ext4_group_t group,
11865354b2afSTheodore Ts'o 			    struct ext4_group_info *grp)
1187c9de560dSAlex Tomas {
1188e43bb4e6SNamjae Jeon 	struct ext4_sb_info *sbi = EXT4_SB(sb);
11897137d7a4STheodore Ts'o 	ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
1190a36b4498SEric Sandeen 	ext4_grpblk_t i = 0;
1191a36b4498SEric Sandeen 	ext4_grpblk_t first;
1192a36b4498SEric Sandeen 	ext4_grpblk_t len;
1193c9de560dSAlex Tomas 	unsigned free = 0;
1194c9de560dSAlex Tomas 	unsigned fragments = 0;
1195c9de560dSAlex Tomas 	unsigned long long period = get_cycles();
1196c9de560dSAlex Tomas 
1197c9de560dSAlex Tomas 	/* initialize buddy from bitmap which is aggregation
1198c9de560dSAlex Tomas 	 * of on-disk bitmap and preallocations */
1199ffad0a44SAneesh Kumar K.V 	i = mb_find_next_zero_bit(bitmap, max, 0);
1200c9de560dSAlex Tomas 	grp->bb_first_free = i;
1201c9de560dSAlex Tomas 	while (i < max) {
1202c9de560dSAlex Tomas 		fragments++;
1203c9de560dSAlex Tomas 		first = i;
1204ffad0a44SAneesh Kumar K.V 		i = mb_find_next_bit(bitmap, max, i);
1205c9de560dSAlex Tomas 		len = i - first;
1206c9de560dSAlex Tomas 		free += len;
1207c9de560dSAlex Tomas 		if (len > 1)
1208c9de560dSAlex Tomas 			ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
1209c9de560dSAlex Tomas 		else
1210c9de560dSAlex Tomas 			grp->bb_counters[0]++;
1211c9de560dSAlex Tomas 		if (i < max)
1212ffad0a44SAneesh Kumar K.V 			i = mb_find_next_zero_bit(bitmap, max, i);
1213c9de560dSAlex Tomas 	}
1214c9de560dSAlex Tomas 	grp->bb_fragments = fragments;
1215c9de560dSAlex Tomas 
1216c9de560dSAlex Tomas 	if (free != grp->bb_free) {
1217e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0,
121894d4c066STheodore Ts'o 				      "block bitmap and bg descriptor "
121994d4c066STheodore Ts'o 				      "inconsistent: %u vs %u free clusters",
1220e29136f8STheodore Ts'o 				      free, grp->bb_free);
1221e56eb659SAneesh Kumar K.V 		/*
1222163a203dSDarrick J. Wong 		 * If we intend to continue, we consider group descriptor
1223e56eb659SAneesh Kumar K.V 		 * corrupt and update bb_free using bitmap value
1224e56eb659SAneesh Kumar K.V 		 */
1225c9de560dSAlex Tomas 		grp->bb_free = free;
1226db79e6d1SWang Shilong 		ext4_mark_group_bitmap_corrupted(sb, group,
1227db79e6d1SWang Shilong 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1228c9de560dSAlex Tomas 	}
12298a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, grp);
123083e80a6eSJan Kara 	mb_update_avg_fragment_size(sb, grp);
1231c9de560dSAlex Tomas 
1232c9de560dSAlex Tomas 	clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
1233c9de560dSAlex Tomas 
1234c9de560dSAlex Tomas 	period = get_cycles() - period;
123567d25186SHarshad Shirwadkar 	atomic_inc(&sbi->s_mb_buddies_generated);
123667d25186SHarshad Shirwadkar 	atomic64_add(period, &sbi->s_mb_generation_time);
1237c9de560dSAlex Tomas }
1238c9de560dSAlex Tomas 
1239c9b528c3SBaokun Li static void mb_regenerate_buddy(struct ext4_buddy *e4b)
1240c9b528c3SBaokun Li {
1241c9b528c3SBaokun Li 	int count;
1242c9b528c3SBaokun Li 	int order = 1;
1243c9b528c3SBaokun Li 	void *buddy;
1244c9b528c3SBaokun Li 
1245c9b528c3SBaokun Li 	while ((buddy = mb_find_buddy(e4b, order++, &count)))
1246c9b528c3SBaokun Li 		mb_set_bits(buddy, 0, count);
1247c9b528c3SBaokun Li 
1248c9b528c3SBaokun Li 	e4b->bd_info->bb_fragments = 0;
1249c9b528c3SBaokun Li 	memset(e4b->bd_info->bb_counters, 0,
1250c9b528c3SBaokun Li 		sizeof(*e4b->bd_info->bb_counters) *
1251c9b528c3SBaokun Li 		(e4b->bd_sb->s_blocksize_bits + 2));
1252c9b528c3SBaokun Li 
1253c9b528c3SBaokun Li 	ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
1254c9b528c3SBaokun Li 		e4b->bd_bitmap, e4b->bd_group, e4b->bd_info);
1255c9b528c3SBaokun Li }
1256c9b528c3SBaokun Li 
1257c9de560dSAlex Tomas /* The buddy information is attached the buddy cache inode
1258c9de560dSAlex Tomas  * for convenience. The information regarding each group
1259c9de560dSAlex Tomas  * is loaded via ext4_mb_load_buddy. The information involve
1260c9de560dSAlex Tomas  * block bitmap and buddy information. The information are
1261c9de560dSAlex Tomas  * stored in the inode as
1262c9de560dSAlex Tomas  *
1263c9de560dSAlex Tomas  * {                        page                        }
1264c3a326a6SAneesh Kumar K.V  * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
1265c9de560dSAlex Tomas  *
1266c9de560dSAlex Tomas  *
1267c9de560dSAlex Tomas  * one block each for bitmap and buddy information.
1268c9de560dSAlex Tomas  * So for each group we take up 2 blocks. A page can
1269ea1754a0SKirill A. Shutemov  * contain blocks_per_page (PAGE_SIZE / blocksize)  blocks.
1270c9de560dSAlex Tomas  * So it can have information regarding groups_per_page which
1271c9de560dSAlex Tomas  * is blocks_per_page/2
12728a57d9d6SCurt Wohlgemuth  *
12738a57d9d6SCurt Wohlgemuth  * Locking note:  This routine takes the block group lock of all groups
12748a57d9d6SCurt Wohlgemuth  * for this page; do not hold this lock when calling this routine!
1275c9de560dSAlex Tomas  */
1276c9de560dSAlex Tomas 
1277*e1622a0dSMatthew Wilcox (Oracle) static int ext4_mb_init_cache(struct folio *folio, char *incore, gfp_t gfp)
1278c9de560dSAlex Tomas {
12798df9675fSTheodore Ts'o 	ext4_group_t ngroups;
128089cadf6eSLu Hongfei 	unsigned int blocksize;
1281c9de560dSAlex Tomas 	int blocks_per_page;
1282c9de560dSAlex Tomas 	int groups_per_page;
1283c9de560dSAlex Tomas 	int err = 0;
1284c9de560dSAlex Tomas 	int i;
1285813e5727STheodore Ts'o 	ext4_group_t first_group, group;
1286c9de560dSAlex Tomas 	int first_block;
1287c9de560dSAlex Tomas 	struct super_block *sb;
1288c9de560dSAlex Tomas 	struct buffer_head *bhs;
1289fa77dcfaSDarrick J. Wong 	struct buffer_head **bh = NULL;
1290c9de560dSAlex Tomas 	struct inode *inode;
1291c9de560dSAlex Tomas 	char *data;
1292c9de560dSAlex Tomas 	char *bitmap;
12939b8b7d35SAmir Goldstein 	struct ext4_group_info *grinfo;
1294c9de560dSAlex Tomas 
1295*e1622a0dSMatthew Wilcox (Oracle) 	inode = folio->mapping->host;
1296c9de560dSAlex Tomas 	sb = inode->i_sb;
12978df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
129893407472SFabian Frederick 	blocksize = i_blocksize(inode);
129909cbfeafSKirill A. Shutemov 	blocks_per_page = PAGE_SIZE / blocksize;
1300c9de560dSAlex Tomas 
1301*e1622a0dSMatthew Wilcox (Oracle) 	mb_debug(sb, "init folio %lu\n", folio->index);
1302d3df1453SRitesh Harjani 
1303c9de560dSAlex Tomas 	groups_per_page = blocks_per_page >> 1;
1304c9de560dSAlex Tomas 	if (groups_per_page == 0)
1305c9de560dSAlex Tomas 		groups_per_page = 1;
1306c9de560dSAlex Tomas 
1307c9de560dSAlex Tomas 	/* allocate buffer_heads to read bitmaps */
1308c9de560dSAlex Tomas 	if (groups_per_page > 1) {
1309c9de560dSAlex Tomas 		i = sizeof(struct buffer_head *) * groups_per_page;
1310adb7ef60SKonstantin Khlebnikov 		bh = kzalloc(i, gfp);
1311139f46d3SKemeng Shi 		if (bh == NULL)
1312139f46d3SKemeng Shi 			return -ENOMEM;
1313c9de560dSAlex Tomas 	} else
1314c9de560dSAlex Tomas 		bh = &bhs;
1315c9de560dSAlex Tomas 
1316*e1622a0dSMatthew Wilcox (Oracle) 	first_group = folio->index * blocks_per_page / 2;
1317c9de560dSAlex Tomas 
1318*e1622a0dSMatthew Wilcox (Oracle) 	/* read all groups the folio covers into the cache */
1319813e5727STheodore Ts'o 	for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1320813e5727STheodore Ts'o 		if (group >= ngroups)
1321c9de560dSAlex Tomas 			break;
1322c9de560dSAlex Tomas 
1323813e5727STheodore Ts'o 		grinfo = ext4_get_group_info(sb, group);
13245354b2afSTheodore Ts'o 		if (!grinfo)
13255354b2afSTheodore Ts'o 			continue;
13269b8b7d35SAmir Goldstein 		/*
13279b8b7d35SAmir Goldstein 		 * If page is uptodate then we came here after online resize
13289b8b7d35SAmir Goldstein 		 * which added some new uninitialized group info structs, so
1329*e1622a0dSMatthew Wilcox (Oracle) 		 * we must skip all initialized uptodate buddies on the folio,
13309b8b7d35SAmir Goldstein 		 * which may be currently in use by an allocating task.
13319b8b7d35SAmir Goldstein 		 */
1332*e1622a0dSMatthew Wilcox (Oracle) 		if (folio_test_uptodate(folio) &&
1333*e1622a0dSMatthew Wilcox (Oracle) 				!EXT4_MB_GRP_NEED_INIT(grinfo)) {
13349b8b7d35SAmir Goldstein 			bh[i] = NULL;
13359b8b7d35SAmir Goldstein 			continue;
13369b8b7d35SAmir Goldstein 		}
1337cfd73237SAlex Zhuravlev 		bh[i] = ext4_read_block_bitmap_nowait(sb, group, false);
13389008a58eSDarrick J. Wong 		if (IS_ERR(bh[i])) {
13399008a58eSDarrick J. Wong 			err = PTR_ERR(bh[i]);
13409008a58eSDarrick J. Wong 			bh[i] = NULL;
1341c9de560dSAlex Tomas 			goto out;
13422ccb5fb9SAneesh Kumar K.V 		}
1343d3df1453SRitesh Harjani 		mb_debug(sb, "read bitmap for group %u\n", group);
1344c9de560dSAlex Tomas 	}
1345c9de560dSAlex Tomas 
1346c9de560dSAlex Tomas 	/* wait for I/O completion */
1347813e5727STheodore Ts'o 	for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
13489008a58eSDarrick J. Wong 		int err2;
13499008a58eSDarrick J. Wong 
13509008a58eSDarrick J. Wong 		if (!bh[i])
13519008a58eSDarrick J. Wong 			continue;
13529008a58eSDarrick J. Wong 		err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
13539008a58eSDarrick J. Wong 		if (!err)
13549008a58eSDarrick J. Wong 			err = err2;
1355813e5727STheodore Ts'o 	}
1356c9de560dSAlex Tomas 
1357*e1622a0dSMatthew Wilcox (Oracle) 	first_block = folio->index * blocks_per_page;
1358c9de560dSAlex Tomas 	for (i = 0; i < blocks_per_page; i++) {
1359c9de560dSAlex Tomas 		group = (first_block + i) >> 1;
13608df9675fSTheodore Ts'o 		if (group >= ngroups)
1361c9de560dSAlex Tomas 			break;
1362c9de560dSAlex Tomas 
13639b8b7d35SAmir Goldstein 		if (!bh[group - first_group])
13649b8b7d35SAmir Goldstein 			/* skip initialized uptodate buddy */
13659b8b7d35SAmir Goldstein 			continue;
13669b8b7d35SAmir Goldstein 
1367bbdc322fSLukas Czerner 		if (!buffer_verified(bh[group - first_group]))
1368bbdc322fSLukas Czerner 			/* Skip faulty bitmaps */
1369bbdc322fSLukas Czerner 			continue;
1370bbdc322fSLukas Czerner 		err = 0;
1371bbdc322fSLukas Czerner 
1372c9de560dSAlex Tomas 		/*
1373c9de560dSAlex Tomas 		 * data carry information regarding this
1374c9de560dSAlex Tomas 		 * particular group in the format specified
1375c9de560dSAlex Tomas 		 * above
1376c9de560dSAlex Tomas 		 *
1377c9de560dSAlex Tomas 		 */
1378*e1622a0dSMatthew Wilcox (Oracle) 		data = folio_address(folio) + (i * blocksize);
1379c9de560dSAlex Tomas 		bitmap = bh[group - first_group]->b_data;
1380c9de560dSAlex Tomas 
1381c9de560dSAlex Tomas 		/*
1382c9de560dSAlex Tomas 		 * We place the buddy block and bitmap block
1383c9de560dSAlex Tomas 		 * close together
1384c9de560dSAlex Tomas 		 */
1385ebf6cb7cSWang Jianjian 		grinfo = ext4_get_group_info(sb, group);
1386ebf6cb7cSWang Jianjian 		if (!grinfo) {
1387ebf6cb7cSWang Jianjian 			err = -EFSCORRUPTED;
1388ebf6cb7cSWang Jianjian 		        goto out;
1389ebf6cb7cSWang Jianjian 		}
1390c9de560dSAlex Tomas 		if ((first_block + i) & 1) {
1391c9de560dSAlex Tomas 			/* this is block of buddy */
1392c9de560dSAlex Tomas 			BUG_ON(incore == NULL);
1393*e1622a0dSMatthew Wilcox (Oracle) 			mb_debug(sb, "put buddy for group %u in folio %lu/%x\n",
1394*e1622a0dSMatthew Wilcox (Oracle) 				group, folio->index, i * blocksize);
1395f307333eSTheodore Ts'o 			trace_ext4_mb_buddy_bitmap_load(sb, group);
1396c9de560dSAlex Tomas 			grinfo->bb_fragments = 0;
1397c9de560dSAlex Tomas 			memset(grinfo->bb_counters, 0,
13981927805eSEric Sandeen 			       sizeof(*grinfo->bb_counters) *
13994b68f6dfSHarshad Shirwadkar 			       (MB_NUM_ORDERS(sb)));
1400c9de560dSAlex Tomas 			/*
1401c9de560dSAlex Tomas 			 * incore got set to the group block bitmap below
1402c9de560dSAlex Tomas 			 */
14037a2fcbf7SAneesh Kumar K.V 			ext4_lock_group(sb, group);
14049b8b7d35SAmir Goldstein 			/* init the buddy */
14059b8b7d35SAmir Goldstein 			memset(data, 0xff, blocksize);
14065354b2afSTheodore Ts'o 			ext4_mb_generate_buddy(sb, data, incore, group, grinfo);
14077a2fcbf7SAneesh Kumar K.V 			ext4_unlock_group(sb, group);
1408c9de560dSAlex Tomas 			incore = NULL;
1409c9de560dSAlex Tomas 		} else {
1410c9de560dSAlex Tomas 			/* this is block of bitmap */
1411c9de560dSAlex Tomas 			BUG_ON(incore != NULL);
1412*e1622a0dSMatthew Wilcox (Oracle) 			mb_debug(sb, "put bitmap for group %u in folio %lu/%x\n",
1413*e1622a0dSMatthew Wilcox (Oracle) 				group, folio->index, i * blocksize);
1414f307333eSTheodore Ts'o 			trace_ext4_mb_bitmap_load(sb, group);
1415c9de560dSAlex Tomas 
1416c9de560dSAlex Tomas 			/* see comments in ext4_mb_put_pa() */
1417c9de560dSAlex Tomas 			ext4_lock_group(sb, group);
1418c9de560dSAlex Tomas 			memcpy(data, bitmap, blocksize);
1419c9de560dSAlex Tomas 
1420c9de560dSAlex Tomas 			/* mark all preallocated blks used in in-core bitmap */
1421c9de560dSAlex Tomas 			ext4_mb_generate_from_pa(sb, data, group);
1422ebf6cb7cSWang Jianjian 			WARN_ON_ONCE(!RB_EMPTY_ROOT(&grinfo->bb_free_root));
1423c9de560dSAlex Tomas 			ext4_unlock_group(sb, group);
1424c9de560dSAlex Tomas 
1425c9de560dSAlex Tomas 			/* set incore so that the buddy information can be
1426c9de560dSAlex Tomas 			 * generated using this
1427c9de560dSAlex Tomas 			 */
1428c9de560dSAlex Tomas 			incore = data;
1429c9de560dSAlex Tomas 		}
1430c9de560dSAlex Tomas 	}
1431*e1622a0dSMatthew Wilcox (Oracle) 	folio_mark_uptodate(folio);
1432c9de560dSAlex Tomas 
1433c9de560dSAlex Tomas out:
1434c9de560dSAlex Tomas 	if (bh) {
14359b8b7d35SAmir Goldstein 		for (i = 0; i < groups_per_page; i++)
1436c9de560dSAlex Tomas 			brelse(bh[i]);
1437c9de560dSAlex Tomas 		if (bh != &bhs)
1438c9de560dSAlex Tomas 			kfree(bh);
1439c9de560dSAlex Tomas 	}
1440c9de560dSAlex Tomas 	return err;
1441c9de560dSAlex Tomas }
1442c9de560dSAlex Tomas 
14438a57d9d6SCurt Wohlgemuth /*
14442de8807bSAmir Goldstein  * Lock the buddy and bitmap pages. This make sure other parallel init_group
14452de8807bSAmir Goldstein  * on the same buddy page doesn't happen whild holding the buddy page lock.
14462de8807bSAmir Goldstein  * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
14475eea586bSMatthew Wilcox (Oracle)  * are on the same page e4b->bd_buddy_folio is NULL and return value is 0.
1448eee4adc7SEric Sandeen  */
14492de8807bSAmir Goldstein static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
1450adb7ef60SKonstantin Khlebnikov 		ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
1451eee4adc7SEric Sandeen {
14522de8807bSAmir Goldstein 	struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
14532de8807bSAmir Goldstein 	int block, pnum, poff;
1454eee4adc7SEric Sandeen 	int blocks_per_page;
145599b150d8SMatthew Wilcox (Oracle) 	struct folio *folio;
14562de8807bSAmir Goldstein 
14575eea586bSMatthew Wilcox (Oracle) 	e4b->bd_buddy_folio = NULL;
145899b150d8SMatthew Wilcox (Oracle) 	e4b->bd_bitmap_folio = NULL;
1459eee4adc7SEric Sandeen 
146009cbfeafSKirill A. Shutemov 	blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1461eee4adc7SEric Sandeen 	/*
1462eee4adc7SEric Sandeen 	 * the buddy cache inode stores the block bitmap
1463eee4adc7SEric Sandeen 	 * and buddy information in consecutive blocks.
1464eee4adc7SEric Sandeen 	 * So for each group we need two blocks.
1465eee4adc7SEric Sandeen 	 */
1466eee4adc7SEric Sandeen 	block = group * 2;
1467eee4adc7SEric Sandeen 	pnum = block / blocks_per_page;
14682de8807bSAmir Goldstein 	poff = block % blocks_per_page;
146999b150d8SMatthew Wilcox (Oracle) 	folio = __filemap_get_folio(inode->i_mapping, pnum,
147099b150d8SMatthew Wilcox (Oracle) 			FGP_LOCK | FGP_ACCESSED | FGP_CREAT, gfp);
147199b150d8SMatthew Wilcox (Oracle) 	if (IS_ERR(folio))
147299b150d8SMatthew Wilcox (Oracle) 		return PTR_ERR(folio);
147399b150d8SMatthew Wilcox (Oracle) 	BUG_ON(folio->mapping != inode->i_mapping);
147499b150d8SMatthew Wilcox (Oracle) 	e4b->bd_bitmap_folio = folio;
147599b150d8SMatthew Wilcox (Oracle) 	e4b->bd_bitmap = folio_address(folio) + (poff * sb->s_blocksize);
1476eee4adc7SEric Sandeen 
14772de8807bSAmir Goldstein 	if (blocks_per_page >= 2) {
14782de8807bSAmir Goldstein 		/* buddy and bitmap are on the same page */
14792de8807bSAmir Goldstein 		return 0;
1480eee4adc7SEric Sandeen 	}
1481eee4adc7SEric Sandeen 
1482f2fec3e9SGou Hao 	/* blocks_per_page == 1, hence we need another page for the buddy */
14835eea586bSMatthew Wilcox (Oracle) 	folio = __filemap_get_folio(inode->i_mapping, block + 1,
14845eea586bSMatthew Wilcox (Oracle) 			FGP_LOCK | FGP_ACCESSED | FGP_CREAT, gfp);
14855eea586bSMatthew Wilcox (Oracle) 	if (IS_ERR(folio))
14865eea586bSMatthew Wilcox (Oracle) 		return PTR_ERR(folio);
14875eea586bSMatthew Wilcox (Oracle) 	BUG_ON(folio->mapping != inode->i_mapping);
14885eea586bSMatthew Wilcox (Oracle) 	e4b->bd_buddy_folio = folio;
14892de8807bSAmir Goldstein 	return 0;
1490eee4adc7SEric Sandeen }
1491eee4adc7SEric Sandeen 
14922de8807bSAmir Goldstein static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
14932de8807bSAmir Goldstein {
149499b150d8SMatthew Wilcox (Oracle) 	if (e4b->bd_bitmap_folio) {
149599b150d8SMatthew Wilcox (Oracle) 		folio_unlock(e4b->bd_bitmap_folio);
149699b150d8SMatthew Wilcox (Oracle) 		folio_put(e4b->bd_bitmap_folio);
14972de8807bSAmir Goldstein 	}
14985eea586bSMatthew Wilcox (Oracle) 	if (e4b->bd_buddy_folio) {
14995eea586bSMatthew Wilcox (Oracle) 		folio_unlock(e4b->bd_buddy_folio);
15005eea586bSMatthew Wilcox (Oracle) 		folio_put(e4b->bd_buddy_folio);
15012de8807bSAmir Goldstein 	}
1502eee4adc7SEric Sandeen }
1503eee4adc7SEric Sandeen 
1504eee4adc7SEric Sandeen /*
15058a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
15068a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
15078a57d9d6SCurt Wohlgemuth  * calling this routine!
15088a57d9d6SCurt Wohlgemuth  */
1509b6a758ecSAneesh Kumar K.V static noinline_for_stack
1510adb7ef60SKonstantin Khlebnikov int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1511b6a758ecSAneesh Kumar K.V {
1512b6a758ecSAneesh Kumar K.V 
1513b6a758ecSAneesh Kumar K.V 	struct ext4_group_info *this_grp;
15142de8807bSAmir Goldstein 	struct ext4_buddy e4b;
151599b150d8SMatthew Wilcox (Oracle) 	struct folio *folio;
15162de8807bSAmir Goldstein 	int ret = 0;
1517b6a758ecSAneesh Kumar K.V 
1518b10a44c3STheodore Ts'o 	might_sleep();
1519d3df1453SRitesh Harjani 	mb_debug(sb, "init group %u\n", group);
1520b6a758ecSAneesh Kumar K.V 	this_grp = ext4_get_group_info(sb, group);
15215354b2afSTheodore Ts'o 	if (!this_grp)
15225354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
15235354b2afSTheodore Ts'o 
1524b6a758ecSAneesh Kumar K.V 	/*
152508c3a813SAneesh Kumar K.V 	 * This ensures that we don't reinit the buddy cache
152608c3a813SAneesh Kumar K.V 	 * page which map to the group from which we are already
152708c3a813SAneesh Kumar K.V 	 * allocating. If we are looking at the buddy cache we would
152808c3a813SAneesh Kumar K.V 	 * have taken a reference using ext4_mb_load_buddy and that
15292de8807bSAmir Goldstein 	 * would have pinned buddy page to page cache.
15302457aec6SMel Gorman 	 * The call to ext4_mb_get_buddy_page_lock will mark the
15312457aec6SMel Gorman 	 * page accessed.
1532b6a758ecSAneesh Kumar K.V 	 */
1533adb7ef60SKonstantin Khlebnikov 	ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
15342de8807bSAmir Goldstein 	if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1535b6a758ecSAneesh Kumar K.V 		/*
1536b6a758ecSAneesh Kumar K.V 		 * somebody initialized the group
1537b6a758ecSAneesh Kumar K.V 		 * return without doing anything
1538b6a758ecSAneesh Kumar K.V 		 */
1539b6a758ecSAneesh Kumar K.V 		goto err;
1540b6a758ecSAneesh Kumar K.V 	}
15412de8807bSAmir Goldstein 
154299b150d8SMatthew Wilcox (Oracle) 	folio = e4b.bd_bitmap_folio;
1543*e1622a0dSMatthew Wilcox (Oracle) 	ret = ext4_mb_init_cache(folio, NULL, gfp);
15442de8807bSAmir Goldstein 	if (ret)
1545b6a758ecSAneesh Kumar K.V 		goto err;
154699b150d8SMatthew Wilcox (Oracle) 	if (!folio_test_uptodate(folio)) {
1547b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1548b6a758ecSAneesh Kumar K.V 		goto err;
1549b6a758ecSAneesh Kumar K.V 	}
1550b6a758ecSAneesh Kumar K.V 
15515eea586bSMatthew Wilcox (Oracle) 	if (e4b.bd_buddy_folio == NULL) {
1552b6a758ecSAneesh Kumar K.V 		/*
1553b6a758ecSAneesh Kumar K.V 		 * If both the bitmap and buddy are in
1554b6a758ecSAneesh Kumar K.V 		 * the same page we don't need to force
1555b6a758ecSAneesh Kumar K.V 		 * init the buddy
1556b6a758ecSAneesh Kumar K.V 		 */
15572de8807bSAmir Goldstein 		ret = 0;
1558b6a758ecSAneesh Kumar K.V 		goto err;
1559b6a758ecSAneesh Kumar K.V 	}
15602de8807bSAmir Goldstein 	/* init buddy cache */
15615eea586bSMatthew Wilcox (Oracle) 	folio = e4b.bd_buddy_folio;
1562*e1622a0dSMatthew Wilcox (Oracle) 	ret = ext4_mb_init_cache(folio, e4b.bd_bitmap, gfp);
15632de8807bSAmir Goldstein 	if (ret)
15642de8807bSAmir Goldstein 		goto err;
15655eea586bSMatthew Wilcox (Oracle) 	if (!folio_test_uptodate(folio)) {
1566b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1567b6a758ecSAneesh Kumar K.V 		goto err;
1568b6a758ecSAneesh Kumar K.V 	}
1569b6a758ecSAneesh Kumar K.V err:
15702de8807bSAmir Goldstein 	ext4_mb_put_buddy_page_lock(&e4b);
1571b6a758ecSAneesh Kumar K.V 	return ret;
1572b6a758ecSAneesh Kumar K.V }
1573b6a758ecSAneesh Kumar K.V 
15748a57d9d6SCurt Wohlgemuth /*
15758a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
15768a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
15778a57d9d6SCurt Wohlgemuth  * calling this routine!
15788a57d9d6SCurt Wohlgemuth  */
15794ddfef7bSEric Sandeen static noinline_for_stack int
1580adb7ef60SKonstantin Khlebnikov ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1581adb7ef60SKonstantin Khlebnikov 		       struct ext4_buddy *e4b, gfp_t gfp)
1582c9de560dSAlex Tomas {
1583c9de560dSAlex Tomas 	int blocks_per_page;
1584c9de560dSAlex Tomas 	int block;
1585c9de560dSAlex Tomas 	int pnum;
1586c9de560dSAlex Tomas 	int poff;
158799b150d8SMatthew Wilcox (Oracle) 	struct folio *folio;
1588fdf6c7a7SShen Feng 	int ret;
1589920313a7SAneesh Kumar K.V 	struct ext4_group_info *grp;
1590920313a7SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1591920313a7SAneesh Kumar K.V 	struct inode *inode = sbi->s_buddy_cache;
1592c9de560dSAlex Tomas 
1593b10a44c3STheodore Ts'o 	might_sleep();
1594d3df1453SRitesh Harjani 	mb_debug(sb, "load group %u\n", group);
1595c9de560dSAlex Tomas 
159609cbfeafSKirill A. Shutemov 	blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1597920313a7SAneesh Kumar K.V 	grp = ext4_get_group_info(sb, group);
15985354b2afSTheodore Ts'o 	if (!grp)
15995354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
1600c9de560dSAlex Tomas 
1601c9de560dSAlex Tomas 	e4b->bd_blkbits = sb->s_blocksize_bits;
1602529da704STao Ma 	e4b->bd_info = grp;
1603c9de560dSAlex Tomas 	e4b->bd_sb = sb;
1604c9de560dSAlex Tomas 	e4b->bd_group = group;
16055eea586bSMatthew Wilcox (Oracle) 	e4b->bd_buddy_folio = NULL;
160699b150d8SMatthew Wilcox (Oracle) 	e4b->bd_bitmap_folio = NULL;
1607c9de560dSAlex Tomas 
1608f41c0750SAneesh Kumar K.V 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1609f41c0750SAneesh Kumar K.V 		/*
1610f41c0750SAneesh Kumar K.V 		 * we need full data about the group
1611f41c0750SAneesh Kumar K.V 		 * to make a good selection
1612f41c0750SAneesh Kumar K.V 		 */
1613adb7ef60SKonstantin Khlebnikov 		ret = ext4_mb_init_group(sb, group, gfp);
1614f41c0750SAneesh Kumar K.V 		if (ret)
1615f41c0750SAneesh Kumar K.V 			return ret;
1616f41c0750SAneesh Kumar K.V 	}
1617f41c0750SAneesh Kumar K.V 
1618c9de560dSAlex Tomas 	/*
1619c9de560dSAlex Tomas 	 * the buddy cache inode stores the block bitmap
1620c9de560dSAlex Tomas 	 * and buddy information in consecutive blocks.
1621c9de560dSAlex Tomas 	 * So for each group we need two blocks.
1622c9de560dSAlex Tomas 	 */
1623c9de560dSAlex Tomas 	block = group * 2;
1624c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1625c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1626c9de560dSAlex Tomas 
162799b150d8SMatthew Wilcox (Oracle) 	/* Avoid locking the folio in the fast path ... */
162899b150d8SMatthew Wilcox (Oracle) 	folio = __filemap_get_folio(inode->i_mapping, pnum, FGP_ACCESSED, 0);
162999b150d8SMatthew Wilcox (Oracle) 	if (IS_ERR(folio) || !folio_test_uptodate(folio)) {
163099b150d8SMatthew Wilcox (Oracle) 		if (!IS_ERR(folio))
1631920313a7SAneesh Kumar K.V 			/*
163299b150d8SMatthew Wilcox (Oracle) 			 * drop the folio reference and try
163399b150d8SMatthew Wilcox (Oracle) 			 * to get the folio with lock. If we
1634920313a7SAneesh Kumar K.V 			 * are not uptodate that implies
163599b150d8SMatthew Wilcox (Oracle) 			 * somebody just created the folio but
163699b150d8SMatthew Wilcox (Oracle) 			 * is yet to initialize it. So
1637920313a7SAneesh Kumar K.V 			 * wait for it to initialize.
1638920313a7SAneesh Kumar K.V 			 */
163999b150d8SMatthew Wilcox (Oracle) 			folio_put(folio);
164099b150d8SMatthew Wilcox (Oracle) 		folio = __filemap_get_folio(inode->i_mapping, pnum,
164199b150d8SMatthew Wilcox (Oracle) 				FGP_LOCK | FGP_ACCESSED | FGP_CREAT, gfp);
164299b150d8SMatthew Wilcox (Oracle) 		if (!IS_ERR(folio)) {
164399b150d8SMatthew Wilcox (Oracle) 			if (WARN_RATELIMIT(folio->mapping != inode->i_mapping,
164499b150d8SMatthew Wilcox (Oracle) 	"ext4: bitmap's mapping != inode->i_mapping\n")) {
164519b8b035STheodore Ts'o 				/* should never happen */
164699b150d8SMatthew Wilcox (Oracle) 				folio_unlock(folio);
164719b8b035STheodore Ts'o 				ret = -EINVAL;
164819b8b035STheodore Ts'o 				goto err;
164919b8b035STheodore Ts'o 			}
165099b150d8SMatthew Wilcox (Oracle) 			if (!folio_test_uptodate(folio)) {
1651*e1622a0dSMatthew Wilcox (Oracle) 				ret = ext4_mb_init_cache(folio, NULL, gfp);
1652fdf6c7a7SShen Feng 				if (ret) {
165399b150d8SMatthew Wilcox (Oracle) 					folio_unlock(folio);
1654fdf6c7a7SShen Feng 					goto err;
1655fdf6c7a7SShen Feng 				}
165699b150d8SMatthew Wilcox (Oracle) 				mb_cmp_bitmaps(e4b, folio_address(folio) +
1657c9de560dSAlex Tomas 					       (poff * sb->s_blocksize));
1658c9de560dSAlex Tomas 			}
165999b150d8SMatthew Wilcox (Oracle) 			folio_unlock(folio);
1660c9de560dSAlex Tomas 		}
1661c9de560dSAlex Tomas 	}
166299b150d8SMatthew Wilcox (Oracle) 	if (IS_ERR(folio)) {
166399b150d8SMatthew Wilcox (Oracle) 		ret = PTR_ERR(folio);
1664c57ab39bSYounger Liu 		goto err;
1665c57ab39bSYounger Liu 	}
166699b150d8SMatthew Wilcox (Oracle) 	if (!folio_test_uptodate(folio)) {
1667fdf6c7a7SShen Feng 		ret = -EIO;
1668c9de560dSAlex Tomas 		goto err;
1669fdf6c7a7SShen Feng 	}
16702457aec6SMel Gorman 
16715eea586bSMatthew Wilcox (Oracle) 	/* Folios marked accessed already */
167299b150d8SMatthew Wilcox (Oracle) 	e4b->bd_bitmap_folio = folio;
167399b150d8SMatthew Wilcox (Oracle) 	e4b->bd_bitmap = folio_address(folio) + (poff * sb->s_blocksize);
1674c9de560dSAlex Tomas 
1675c9de560dSAlex Tomas 	block++;
1676c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1677c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1678c9de560dSAlex Tomas 
16795eea586bSMatthew Wilcox (Oracle) 	folio = __filemap_get_folio(inode->i_mapping, pnum, FGP_ACCESSED, 0);
16805eea586bSMatthew Wilcox (Oracle) 	if (IS_ERR(folio) || !folio_test_uptodate(folio)) {
16815eea586bSMatthew Wilcox (Oracle) 		if (!IS_ERR(folio))
16825eea586bSMatthew Wilcox (Oracle) 			folio_put(folio);
16835eea586bSMatthew Wilcox (Oracle) 		folio = __filemap_get_folio(inode->i_mapping, pnum,
16845eea586bSMatthew Wilcox (Oracle) 				FGP_LOCK | FGP_ACCESSED | FGP_CREAT, gfp);
16855eea586bSMatthew Wilcox (Oracle) 		if (!IS_ERR(folio)) {
16865eea586bSMatthew Wilcox (Oracle) 			if (WARN_RATELIMIT(folio->mapping != inode->i_mapping,
16875eea586bSMatthew Wilcox (Oracle) 	"ext4: buddy bitmap's mapping != inode->i_mapping\n")) {
168819b8b035STheodore Ts'o 				/* should never happen */
16895eea586bSMatthew Wilcox (Oracle) 				folio_unlock(folio);
169019b8b035STheodore Ts'o 				ret = -EINVAL;
169119b8b035STheodore Ts'o 				goto err;
169219b8b035STheodore Ts'o 			}
16935eea586bSMatthew Wilcox (Oracle) 			if (!folio_test_uptodate(folio)) {
1694*e1622a0dSMatthew Wilcox (Oracle) 				ret = ext4_mb_init_cache(folio, e4b->bd_bitmap,
1695adb7ef60SKonstantin Khlebnikov 							 gfp);
1696fdf6c7a7SShen Feng 				if (ret) {
16975eea586bSMatthew Wilcox (Oracle) 					folio_unlock(folio);
1698fdf6c7a7SShen Feng 					goto err;
1699fdf6c7a7SShen Feng 				}
1700fdf6c7a7SShen Feng 			}
17015eea586bSMatthew Wilcox (Oracle) 			folio_unlock(folio);
1702c9de560dSAlex Tomas 		}
1703c9de560dSAlex Tomas 	}
17045eea586bSMatthew Wilcox (Oracle) 	if (IS_ERR(folio)) {
17055eea586bSMatthew Wilcox (Oracle) 		ret = PTR_ERR(folio);
1706c57ab39bSYounger Liu 		goto err;
1707c57ab39bSYounger Liu 	}
17085eea586bSMatthew Wilcox (Oracle) 	if (!folio_test_uptodate(folio)) {
1709fdf6c7a7SShen Feng 		ret = -EIO;
1710c9de560dSAlex Tomas 		goto err;
1711fdf6c7a7SShen Feng 	}
17122457aec6SMel Gorman 
17135eea586bSMatthew Wilcox (Oracle) 	/* Folios marked accessed already */
17145eea586bSMatthew Wilcox (Oracle) 	e4b->bd_buddy_folio = folio;
17155eea586bSMatthew Wilcox (Oracle) 	e4b->bd_buddy = folio_address(folio) + (poff * sb->s_blocksize);
1716c9de560dSAlex Tomas 
1717c9de560dSAlex Tomas 	return 0;
1718c9de560dSAlex Tomas 
1719c9de560dSAlex Tomas err:
17205eea586bSMatthew Wilcox (Oracle) 	if (folio)
17215eea586bSMatthew Wilcox (Oracle) 		folio_put(folio);
172299b150d8SMatthew Wilcox (Oracle) 	if (e4b->bd_bitmap_folio)
172399b150d8SMatthew Wilcox (Oracle) 		folio_put(e4b->bd_bitmap_folio);
1724285164b8SKemeng Shi 
1725c9de560dSAlex Tomas 	e4b->bd_buddy = NULL;
1726c9de560dSAlex Tomas 	e4b->bd_bitmap = NULL;
1727fdf6c7a7SShen Feng 	return ret;
1728c9de560dSAlex Tomas }
1729c9de560dSAlex Tomas 
1730adb7ef60SKonstantin Khlebnikov static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1731adb7ef60SKonstantin Khlebnikov 			      struct ext4_buddy *e4b)
1732adb7ef60SKonstantin Khlebnikov {
1733adb7ef60SKonstantin Khlebnikov 	return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1734adb7ef60SKonstantin Khlebnikov }
1735adb7ef60SKonstantin Khlebnikov 
1736e39e07fdSJing Zhang static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1737c9de560dSAlex Tomas {
173899b150d8SMatthew Wilcox (Oracle) 	if (e4b->bd_bitmap_folio)
173999b150d8SMatthew Wilcox (Oracle) 		folio_put(e4b->bd_bitmap_folio);
17405eea586bSMatthew Wilcox (Oracle) 	if (e4b->bd_buddy_folio)
17415eea586bSMatthew Wilcox (Oracle) 		folio_put(e4b->bd_buddy_folio);
1742c9de560dSAlex Tomas }
1743c9de560dSAlex Tomas 
1744c9de560dSAlex Tomas 
1745c9de560dSAlex Tomas static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1746c9de560dSAlex Tomas {
1747ce3cca33SChunguang Xu 	int order = 1, max;
1748c9de560dSAlex Tomas 	void *bb;
1749c9de560dSAlex Tomas 
1750c5e8f3f3STheodore Ts'o 	BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1751c9de560dSAlex Tomas 	BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1752c9de560dSAlex Tomas 
1753c9de560dSAlex Tomas 	while (order <= e4b->bd_blkbits + 1) {
1754ce3cca33SChunguang Xu 		bb = mb_find_buddy(e4b, order, &max);
1755ce3cca33SChunguang Xu 		if (!mb_test_bit(block >> order, bb)) {
1756c9de560dSAlex Tomas 			/* this block is part of buddy of order 'order' */
1757c9de560dSAlex Tomas 			return order;
1758c9de560dSAlex Tomas 		}
1759c9de560dSAlex Tomas 		order++;
1760c9de560dSAlex Tomas 	}
1761c9de560dSAlex Tomas 	return 0;
1762c9de560dSAlex Tomas }
1763c9de560dSAlex Tomas 
1764955ce5f5SAneesh Kumar K.V static void mb_clear_bits(void *bm, int cur, int len)
1765c9de560dSAlex Tomas {
1766c9de560dSAlex Tomas 	__u32 *addr;
1767c9de560dSAlex Tomas 
1768c9de560dSAlex Tomas 	len = cur + len;
1769c9de560dSAlex Tomas 	while (cur < len) {
1770c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1771c9de560dSAlex Tomas 			/* fast path: clear whole word at once */
1772c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1773c9de560dSAlex Tomas 			*addr = 0;
1774c9de560dSAlex Tomas 			cur += 32;
1775c9de560dSAlex Tomas 			continue;
1776c9de560dSAlex Tomas 		}
1777e8134b27SAneesh Kumar K.V 		mb_clear_bit(cur, bm);
1778c9de560dSAlex Tomas 		cur++;
1779c9de560dSAlex Tomas 	}
1780c9de560dSAlex Tomas }
1781c9de560dSAlex Tomas 
1782eabe0444SAndrey Sidorov /* clear bits in given range
1783eabe0444SAndrey Sidorov  * will return first found zero bit if any, -1 otherwise
1784eabe0444SAndrey Sidorov  */
1785eabe0444SAndrey Sidorov static int mb_test_and_clear_bits(void *bm, int cur, int len)
1786eabe0444SAndrey Sidorov {
1787eabe0444SAndrey Sidorov 	__u32 *addr;
1788eabe0444SAndrey Sidorov 	int zero_bit = -1;
1789eabe0444SAndrey Sidorov 
1790eabe0444SAndrey Sidorov 	len = cur + len;
1791eabe0444SAndrey Sidorov 	while (cur < len) {
1792eabe0444SAndrey Sidorov 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1793eabe0444SAndrey Sidorov 			/* fast path: clear whole word at once */
1794eabe0444SAndrey Sidorov 			addr = bm + (cur >> 3);
1795eabe0444SAndrey Sidorov 			if (*addr != (__u32)(-1) && zero_bit == -1)
1796eabe0444SAndrey Sidorov 				zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1797eabe0444SAndrey Sidorov 			*addr = 0;
1798eabe0444SAndrey Sidorov 			cur += 32;
1799eabe0444SAndrey Sidorov 			continue;
1800eabe0444SAndrey Sidorov 		}
1801eabe0444SAndrey Sidorov 		if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1802eabe0444SAndrey Sidorov 			zero_bit = cur;
1803eabe0444SAndrey Sidorov 		cur++;
1804eabe0444SAndrey Sidorov 	}
1805eabe0444SAndrey Sidorov 
1806eabe0444SAndrey Sidorov 	return zero_bit;
1807eabe0444SAndrey Sidorov }
1808eabe0444SAndrey Sidorov 
1809123e3016SRitesh Harjani void mb_set_bits(void *bm, int cur, int len)
1810c9de560dSAlex Tomas {
1811c9de560dSAlex Tomas 	__u32 *addr;
1812c9de560dSAlex Tomas 
1813c9de560dSAlex Tomas 	len = cur + len;
1814c9de560dSAlex Tomas 	while (cur < len) {
1815c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1816c9de560dSAlex Tomas 			/* fast path: set whole word at once */
1817c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1818c9de560dSAlex Tomas 			*addr = 0xffffffff;
1819c9de560dSAlex Tomas 			cur += 32;
1820c9de560dSAlex Tomas 			continue;
1821c9de560dSAlex Tomas 		}
1822e8134b27SAneesh Kumar K.V 		mb_set_bit(cur, bm);
1823c9de560dSAlex Tomas 		cur++;
1824c9de560dSAlex Tomas 	}
1825c9de560dSAlex Tomas }
1826c9de560dSAlex Tomas 
1827eabe0444SAndrey Sidorov static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1828eabe0444SAndrey Sidorov {
1829eabe0444SAndrey Sidorov 	if (mb_test_bit(*bit + side, bitmap)) {
1830eabe0444SAndrey Sidorov 		mb_clear_bit(*bit, bitmap);
1831eabe0444SAndrey Sidorov 		(*bit) -= side;
1832eabe0444SAndrey Sidorov 		return 1;
1833eabe0444SAndrey Sidorov 	}
1834eabe0444SAndrey Sidorov 	else {
1835eabe0444SAndrey Sidorov 		(*bit) += side;
1836eabe0444SAndrey Sidorov 		mb_set_bit(*bit, bitmap);
1837eabe0444SAndrey Sidorov 		return -1;
1838eabe0444SAndrey Sidorov 	}
1839eabe0444SAndrey Sidorov }
1840eabe0444SAndrey Sidorov 
1841eabe0444SAndrey Sidorov static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1842eabe0444SAndrey Sidorov {
1843eabe0444SAndrey Sidorov 	int max;
1844eabe0444SAndrey Sidorov 	int order = 1;
1845eabe0444SAndrey Sidorov 	void *buddy = mb_find_buddy(e4b, order, &max);
1846eabe0444SAndrey Sidorov 
1847eabe0444SAndrey Sidorov 	while (buddy) {
1848eabe0444SAndrey Sidorov 		void *buddy2;
1849eabe0444SAndrey Sidorov 
1850eabe0444SAndrey Sidorov 		/* Bits in range [first; last] are known to be set since
1851eabe0444SAndrey Sidorov 		 * corresponding blocks were allocated. Bits in range
1852eabe0444SAndrey Sidorov 		 * (first; last) will stay set because they form buddies on
1853eabe0444SAndrey Sidorov 		 * upper layer. We just deal with borders if they don't
1854eabe0444SAndrey Sidorov 		 * align with upper layer and then go up.
1855eabe0444SAndrey Sidorov 		 * Releasing entire group is all about clearing
1856eabe0444SAndrey Sidorov 		 * single bit of highest order buddy.
1857eabe0444SAndrey Sidorov 		 */
1858eabe0444SAndrey Sidorov 
1859eabe0444SAndrey Sidorov 		/* Example:
1860eabe0444SAndrey Sidorov 		 * ---------------------------------
1861eabe0444SAndrey Sidorov 		 * |   1   |   1   |   1   |   1   |
1862eabe0444SAndrey Sidorov 		 * ---------------------------------
1863eabe0444SAndrey Sidorov 		 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1864eabe0444SAndrey Sidorov 		 * ---------------------------------
1865eabe0444SAndrey Sidorov 		 *   0   1   2   3   4   5   6   7
1866eabe0444SAndrey Sidorov 		 *      \_____________________/
1867eabe0444SAndrey Sidorov 		 *
1868eabe0444SAndrey Sidorov 		 * Neither [1] nor [6] is aligned to above layer.
1869eabe0444SAndrey Sidorov 		 * Left neighbour [0] is free, so mark it busy,
1870eabe0444SAndrey Sidorov 		 * decrease bb_counters and extend range to
1871eabe0444SAndrey Sidorov 		 * [0; 6]
1872eabe0444SAndrey Sidorov 		 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1873eabe0444SAndrey Sidorov 		 * mark [6] free, increase bb_counters and shrink range to
1874eabe0444SAndrey Sidorov 		 * [0; 5].
1875eabe0444SAndrey Sidorov 		 * Then shift range to [0; 2], go up and do the same.
1876eabe0444SAndrey Sidorov 		 */
1877eabe0444SAndrey Sidorov 
1878eabe0444SAndrey Sidorov 
1879eabe0444SAndrey Sidorov 		if (first & 1)
1880eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1881eabe0444SAndrey Sidorov 		if (!(last & 1))
1882eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1883eabe0444SAndrey Sidorov 		if (first > last)
1884eabe0444SAndrey Sidorov 			break;
1885eabe0444SAndrey Sidorov 		order++;
1886eabe0444SAndrey Sidorov 
1887976620bdSKemeng Shi 		buddy2 = mb_find_buddy(e4b, order, &max);
1888976620bdSKemeng Shi 		if (!buddy2) {
1889eabe0444SAndrey Sidorov 			mb_clear_bits(buddy, first, last - first + 1);
1890eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1891eabe0444SAndrey Sidorov 			break;
1892eabe0444SAndrey Sidorov 		}
1893eabe0444SAndrey Sidorov 		first >>= 1;
1894eabe0444SAndrey Sidorov 		last >>= 1;
1895eabe0444SAndrey Sidorov 		buddy = buddy2;
1896eabe0444SAndrey Sidorov 	}
1897eabe0444SAndrey Sidorov }
1898eabe0444SAndrey Sidorov 
18997e5a8cddSShen Feng static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1900c9de560dSAlex Tomas 			   int first, int count)
1901c9de560dSAlex Tomas {
1902eabe0444SAndrey Sidorov 	int left_is_free = 0;
1903eabe0444SAndrey Sidorov 	int right_is_free = 0;
1904eabe0444SAndrey Sidorov 	int block;
1905eabe0444SAndrey Sidorov 	int last = first + count - 1;
1906c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
1907c9de560dSAlex Tomas 
1908c99d1e6eSTheodore Ts'o 	if (WARN_ON(count == 0))
1909c99d1e6eSTheodore Ts'o 		return;
1910eabe0444SAndrey Sidorov 	BUG_ON(last >= (sb->s_blocksize << 3));
1911bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1912163a203dSDarrick J. Wong 	/* Don't bother if the block group is corrupt. */
1913163a203dSDarrick J. Wong 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1914163a203dSDarrick J. Wong 		return;
1915163a203dSDarrick J. Wong 
1916c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1917c9de560dSAlex Tomas 	mb_free_blocks_double(inode, e4b, first, count);
1918c9de560dSAlex Tomas 
1919eabe0444SAndrey Sidorov 	/* access memory sequentially: check left neighbour,
1920eabe0444SAndrey Sidorov 	 * clear range and then check right neighbour
1921eabe0444SAndrey Sidorov 	 */
1922c9de560dSAlex Tomas 	if (first != 0)
1923eabe0444SAndrey Sidorov 		left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1924eabe0444SAndrey Sidorov 	block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1925eabe0444SAndrey Sidorov 	if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1926eabe0444SAndrey Sidorov 		right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1927c9de560dSAlex Tomas 
1928eabe0444SAndrey Sidorov 	if (unlikely(block != -1)) {
1929e43bb4e6SNamjae Jeon 		struct ext4_sb_info *sbi = EXT4_SB(sb);
1930c9de560dSAlex Tomas 		ext4_fsblk_t blocknr;
19315661bd68SAkinobu Mita 
19322331fd4aSBaokun Li 		/*
19332331fd4aSBaokun Li 		 * Fastcommit replay can free already freed blocks which
19342331fd4aSBaokun Li 		 * corrupts allocation info. Regenerate it.
19352331fd4aSBaokun Li 		 */
19362331fd4aSBaokun Li 		if (sbi->s_mount_state & EXT4_FC_REPLAY) {
19372331fd4aSBaokun Li 			mb_regenerate_buddy(e4b);
19382331fd4aSBaokun Li 			goto check;
19392331fd4aSBaokun Li 		}
19402331fd4aSBaokun Li 
19415661bd68SAkinobu Mita 		blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
194249598e04SJun Piao 		blocknr += EXT4_C2B(sbi, block);
1943c5f3a382SBaokun Li 		ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
1944c5f3a382SBaokun Li 				EXT4_GROUP_INFO_BBITMAP_CORRUPT);
19455d1b1b3fSAneesh Kumar K.V 		ext4_grp_locked_error(sb, e4b->bd_group,
19462331fd4aSBaokun Li 				      inode ? inode->i_ino : 0, blocknr,
19478016e29fSHarshad Shirwadkar 				      "freeing already freed block (bit %u); block bitmap corrupt.",
1948163a203dSDarrick J. Wong 				      block);
19492331fd4aSBaokun Li 		return;
19508016e29fSHarshad Shirwadkar 	}
19512331fd4aSBaokun Li 
19522331fd4aSBaokun Li 	this_cpu_inc(discard_pa_seq);
19532331fd4aSBaokun Li 	e4b->bd_info->bb_free += count;
19542331fd4aSBaokun Li 	if (first < e4b->bd_info->bb_first_free)
19552331fd4aSBaokun Li 		e4b->bd_info->bb_first_free = first;
1956c9de560dSAlex Tomas 
1957eabe0444SAndrey Sidorov 	/* let's maintain fragments counter */
1958eabe0444SAndrey Sidorov 	if (left_is_free && right_is_free)
1959eabe0444SAndrey Sidorov 		e4b->bd_info->bb_fragments--;
1960eabe0444SAndrey Sidorov 	else if (!left_is_free && !right_is_free)
1961eabe0444SAndrey Sidorov 		e4b->bd_info->bb_fragments++;
1962c9de560dSAlex Tomas 
1963eabe0444SAndrey Sidorov 	/* buddy[0] == bd_bitmap is a special case, so handle
1964eabe0444SAndrey Sidorov 	 * it right away and let mb_buddy_mark_free stay free of
1965eabe0444SAndrey Sidorov 	 * zero order checks.
1966eabe0444SAndrey Sidorov 	 * Check if neighbours are to be coaleasced,
1967eabe0444SAndrey Sidorov 	 * adjust bitmap bb_counters and borders appropriately.
1968eabe0444SAndrey Sidorov 	 */
1969eabe0444SAndrey Sidorov 	if (first & 1) {
1970eabe0444SAndrey Sidorov 		first += !left_is_free;
1971eabe0444SAndrey Sidorov 		e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1972c9de560dSAlex Tomas 	}
1973eabe0444SAndrey Sidorov 	if (!(last & 1)) {
1974eabe0444SAndrey Sidorov 		last -= !right_is_free;
1975eabe0444SAndrey Sidorov 		e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1976c9de560dSAlex Tomas 	}
1977eabe0444SAndrey Sidorov 
1978eabe0444SAndrey Sidorov 	if (first <= last)
1979eabe0444SAndrey Sidorov 		mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1980eabe0444SAndrey Sidorov 
19818a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, e4b->bd_info);
1982196e402aSHarshad Shirwadkar 	mb_update_avg_fragment_size(sb, e4b->bd_info);
19832331fd4aSBaokun Li check:
1984c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1985c9de560dSAlex Tomas }
1986c9de560dSAlex Tomas 
198715c006a2SRobin Dong static int mb_find_extent(struct ext4_buddy *e4b, int block,
1988c9de560dSAlex Tomas 				int needed, struct ext4_free_extent *ex)
1989c9de560dSAlex Tomas {
19902bf5eb2aSGou Hao 	int max, order, next;
1991c9de560dSAlex Tomas 	void *buddy;
1992c9de560dSAlex Tomas 
1993bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1994c9de560dSAlex Tomas 	BUG_ON(ex == NULL);
1995c9de560dSAlex Tomas 
199615c006a2SRobin Dong 	buddy = mb_find_buddy(e4b, 0, &max);
1997c9de560dSAlex Tomas 	BUG_ON(buddy == NULL);
1998c9de560dSAlex Tomas 	BUG_ON(block >= max);
1999c9de560dSAlex Tomas 	if (mb_test_bit(block, buddy)) {
2000c9de560dSAlex Tomas 		ex->fe_len = 0;
2001c9de560dSAlex Tomas 		ex->fe_start = 0;
2002c9de560dSAlex Tomas 		ex->fe_group = 0;
2003c9de560dSAlex Tomas 		return 0;
2004c9de560dSAlex Tomas 	}
2005c9de560dSAlex Tomas 
2006c9de560dSAlex Tomas 	/* find actual order */
2007c9de560dSAlex Tomas 	order = mb_find_order_for_block(e4b, block);
2008c9de560dSAlex Tomas 
20092bf5eb2aSGou Hao 	ex->fe_len = (1 << order) - (block & ((1 << order) - 1));
20102bf5eb2aSGou Hao 	ex->fe_start = block;
2011c9de560dSAlex Tomas 	ex->fe_group = e4b->bd_group;
2012c9de560dSAlex Tomas 
20132bf5eb2aSGou Hao 	block = block >> order;
2014c9de560dSAlex Tomas 
2015c9de560dSAlex Tomas 	while (needed > ex->fe_len &&
2016d8ec0c39SAlan Cox 	       mb_find_buddy(e4b, order, &max)) {
2017c9de560dSAlex Tomas 
2018c9de560dSAlex Tomas 		if (block + 1 >= max)
2019c9de560dSAlex Tomas 			break;
2020c9de560dSAlex Tomas 
2021c9de560dSAlex Tomas 		next = (block + 1) * (1 << order);
2022c5e8f3f3STheodore Ts'o 		if (mb_test_bit(next, e4b->bd_bitmap))
2023c9de560dSAlex Tomas 			break;
2024c9de560dSAlex Tomas 
2025b051d8dcSRobin Dong 		order = mb_find_order_for_block(e4b, next);
2026c9de560dSAlex Tomas 
2027c9de560dSAlex Tomas 		block = next >> order;
2028c9de560dSAlex Tomas 		ex->fe_len += 1 << order;
2029c9de560dSAlex Tomas 	}
2030c9de560dSAlex Tomas 
203131562b95SJan Kara 	if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
203243c73221STheodore Ts'o 		/* Should never happen! (but apparently sometimes does?!?) */
203343c73221STheodore Ts'o 		WARN_ON(1);
2034cd84bbbaSStephen Brennan 		ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
2035cd84bbbaSStephen Brennan 			"corruption or bug in mb_find_extent "
203643c73221STheodore Ts'o 			"block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
203743c73221STheodore Ts'o 			block, order, needed, ex->fe_group, ex->fe_start,
203843c73221STheodore Ts'o 			ex->fe_len, ex->fe_logical);
203943c73221STheodore Ts'o 		ex->fe_len = 0;
204043c73221STheodore Ts'o 		ex->fe_start = 0;
204143c73221STheodore Ts'o 		ex->fe_group = 0;
204243c73221STheodore Ts'o 	}
2043c9de560dSAlex Tomas 	return ex->fe_len;
2044c9de560dSAlex Tomas }
2045c9de560dSAlex Tomas 
2046c9de560dSAlex Tomas static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
2047c9de560dSAlex Tomas {
2048c9de560dSAlex Tomas 	int ord;
2049c9de560dSAlex Tomas 	int mlen = 0;
2050c9de560dSAlex Tomas 	int max = 0;
2051c9de560dSAlex Tomas 	int start = ex->fe_start;
2052c9de560dSAlex Tomas 	int len = ex->fe_len;
2053c9de560dSAlex Tomas 	unsigned ret = 0;
2054c9de560dSAlex Tomas 	int len0 = len;
2055c9de560dSAlex Tomas 	void *buddy;
2056d1a3924eSKemeng Shi 	int ord_start, ord_end;
2057c9de560dSAlex Tomas 
2058c9de560dSAlex Tomas 	BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
2059c9de560dSAlex Tomas 	BUG_ON(e4b->bd_group != ex->fe_group);
2060bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
2061c9de560dSAlex Tomas 	mb_check_buddy(e4b);
2062c9de560dSAlex Tomas 	mb_mark_used_double(e4b, start, len);
2063c9de560dSAlex Tomas 
206407b5b8e1SRitesh Harjani 	this_cpu_inc(discard_pa_seq);
2065c9de560dSAlex Tomas 	e4b->bd_info->bb_free -= len;
2066c9de560dSAlex Tomas 	if (e4b->bd_info->bb_first_free == start)
2067c9de560dSAlex Tomas 		e4b->bd_info->bb_first_free += len;
2068c9de560dSAlex Tomas 
2069c9de560dSAlex Tomas 	/* let's maintain fragments counter */
2070c9de560dSAlex Tomas 	if (start != 0)
2071c5e8f3f3STheodore Ts'o 		mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
2072c9de560dSAlex Tomas 	if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
2073c5e8f3f3STheodore Ts'o 		max = !mb_test_bit(start + len, e4b->bd_bitmap);
2074c9de560dSAlex Tomas 	if (mlen && max)
2075c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments++;
2076c9de560dSAlex Tomas 	else if (!mlen && !max)
2077c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments--;
2078c9de560dSAlex Tomas 
2079c9de560dSAlex Tomas 	/* let's maintain buddy itself */
2080c9de560dSAlex Tomas 	while (len) {
2081c9de560dSAlex Tomas 		ord = mb_find_order_for_block(e4b, start);
2082c9de560dSAlex Tomas 
2083c9de560dSAlex Tomas 		if (((start >> ord) << ord) == start && len >= (1 << ord)) {
2084c9de560dSAlex Tomas 			/* the whole chunk may be allocated at once! */
2085c9de560dSAlex Tomas 			mlen = 1 << ord;
2086c9de560dSAlex Tomas 			buddy = mb_find_buddy(e4b, ord, &max);
2087c9de560dSAlex Tomas 			BUG_ON((start >> ord) >= max);
2088c9de560dSAlex Tomas 			mb_set_bit(start >> ord, buddy);
2089c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[ord]--;
2090c9de560dSAlex Tomas 			start += mlen;
2091c9de560dSAlex Tomas 			len -= mlen;
2092c9de560dSAlex Tomas 			BUG_ON(len < 0);
2093c9de560dSAlex Tomas 			continue;
2094c9de560dSAlex Tomas 		}
2095c9de560dSAlex Tomas 
2096c9de560dSAlex Tomas 		/* store for history */
2097c9de560dSAlex Tomas 		if (ret == 0)
2098c9de560dSAlex Tomas 			ret = len | (ord << 16);
2099c9de560dSAlex Tomas 
2100c9de560dSAlex Tomas 		BUG_ON(ord <= 0);
2101c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, ord, &max);
2102c9de560dSAlex Tomas 		mb_set_bit(start >> ord, buddy);
2103c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]--;
2104c9de560dSAlex Tomas 
2105d1a3924eSKemeng Shi 		ord_start = (start >> ord) << ord;
2106d1a3924eSKemeng Shi 		ord_end = ord_start + (1 << ord);
2107d1a3924eSKemeng Shi 		/* first chunk */
2108d1a3924eSKemeng Shi 		if (start > ord_start)
2109d1a3924eSKemeng Shi 			ext4_mb_mark_free_simple(e4b->bd_sb, e4b->bd_buddy,
2110d1a3924eSKemeng Shi 						 ord_start, start - ord_start,
2111d1a3924eSKemeng Shi 						 e4b->bd_info);
2112d1a3924eSKemeng Shi 
2113d1a3924eSKemeng Shi 		/* last chunk */
2114d1a3924eSKemeng Shi 		if (start + len < ord_end) {
2115d1a3924eSKemeng Shi 			ext4_mb_mark_free_simple(e4b->bd_sb, e4b->bd_buddy,
2116d1a3924eSKemeng Shi 						 start + len,
2117d1a3924eSKemeng Shi 						 ord_end - (start + len),
2118d1a3924eSKemeng Shi 						 e4b->bd_info);
2119d1a3924eSKemeng Shi 			break;
2120d1a3924eSKemeng Shi 		}
2121d1a3924eSKemeng Shi 		len = start + len - ord_end;
2122d1a3924eSKemeng Shi 		start = ord_end;
2123c9de560dSAlex Tomas 	}
21248a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
2125c9de560dSAlex Tomas 
2126196e402aSHarshad Shirwadkar 	mb_update_avg_fragment_size(e4b->bd_sb, e4b->bd_info);
2127123e3016SRitesh Harjani 	mb_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
2128c9de560dSAlex Tomas 	mb_check_buddy(e4b);
2129c9de560dSAlex Tomas 
2130c9de560dSAlex Tomas 	return ret;
2131c9de560dSAlex Tomas }
2132c9de560dSAlex Tomas 
2133c9de560dSAlex Tomas /*
2134c9de560dSAlex Tomas  * Must be called under group lock!
2135c9de560dSAlex Tomas  */
2136c9de560dSAlex Tomas static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
2137c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2138c9de560dSAlex Tomas {
2139c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2140c9de560dSAlex Tomas 	int ret;
2141c9de560dSAlex Tomas 
2142c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
2143c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2144c9de560dSAlex Tomas 
2145c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
2146c9de560dSAlex Tomas 	ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
2147c9de560dSAlex Tomas 	ret = mb_mark_used(e4b, &ac->ac_b_ex);
2148c9de560dSAlex Tomas 
2149c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
2150c9de560dSAlex Tomas 	 * allocated blocks for history */
2151c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
2152c9de560dSAlex Tomas 
2153c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
2154c9de560dSAlex Tomas 	ac->ac_tail = ret & 0xffff;
2155c9de560dSAlex Tomas 	ac->ac_buddy = ret >> 16;
2156c9de560dSAlex Tomas 
2157c3a326a6SAneesh Kumar K.V 	/*
2158c3a326a6SAneesh Kumar K.V 	 * take the page reference. We want the page to be pinned
2159c3a326a6SAneesh Kumar K.V 	 * so that we don't get a ext4_mb_init_cache_call for this
2160c3a326a6SAneesh Kumar K.V 	 * group until we update the bitmap. That would mean we
2161c3a326a6SAneesh Kumar K.V 	 * double allocate blocks. The reference is dropped
2162c3a326a6SAneesh Kumar K.V 	 * in ext4_mb_release_context
2163c3a326a6SAneesh Kumar K.V 	 */
216499b150d8SMatthew Wilcox (Oracle) 	ac->ac_bitmap_page = &e4b->bd_bitmap_folio->page;
2165c9de560dSAlex Tomas 	get_page(ac->ac_bitmap_page);
21665eea586bSMatthew Wilcox (Oracle) 	ac->ac_buddy_page = &e4b->bd_buddy_folio->page;
2167c9de560dSAlex Tomas 	get_page(ac->ac_buddy_page);
2168c9de560dSAlex Tomas 	/* store last allocated for subsequent stream allocation */
21694ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2170c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
2171c9de560dSAlex Tomas 		sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
2172c9de560dSAlex Tomas 		sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
2173c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
2174c9de560dSAlex Tomas 	}
217553f86b17SRitesh Harjani 	/*
217653f86b17SRitesh Harjani 	 * As we've just preallocated more space than
217753f86b17SRitesh Harjani 	 * user requested originally, we store allocated
217853f86b17SRitesh Harjani 	 * space in a special descriptor.
217953f86b17SRitesh Harjani 	 */
218053f86b17SRitesh Harjani 	if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
218153f86b17SRitesh Harjani 		ext4_mb_new_preallocation(ac);
218253f86b17SRitesh Harjani 
2183c9de560dSAlex Tomas }
2184c9de560dSAlex Tomas 
2185c9de560dSAlex Tomas static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
2186c9de560dSAlex Tomas 					struct ext4_buddy *e4b,
2187c9de560dSAlex Tomas 					int finish_group)
2188c9de560dSAlex Tomas {
2189c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2190c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
2191c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
2192c9de560dSAlex Tomas 
2193032115fcSAneesh Kumar K.V 	if (ac->ac_status == AC_STATUS_FOUND)
2194032115fcSAneesh Kumar K.V 		return;
2195c9de560dSAlex Tomas 	/*
2196c9de560dSAlex Tomas 	 * We don't want to scan for a whole year
2197c9de560dSAlex Tomas 	 */
2198c9de560dSAlex Tomas 	if (ac->ac_found > sbi->s_mb_max_to_scan &&
2199c9de560dSAlex Tomas 			!(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2200c9de560dSAlex Tomas 		ac->ac_status = AC_STATUS_BREAK;
2201c9de560dSAlex Tomas 		return;
2202c9de560dSAlex Tomas 	}
2203c9de560dSAlex Tomas 
2204c9de560dSAlex Tomas 	/*
2205c9de560dSAlex Tomas 	 * Haven't found good chunk so far, let's continue
2206c9de560dSAlex Tomas 	 */
2207c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len)
2208c9de560dSAlex Tomas 		return;
2209c9de560dSAlex Tomas 
22103582e745SOjaswin Mujoo 	if (finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
2211c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2212c9de560dSAlex Tomas }
2213c9de560dSAlex Tomas 
2214c9de560dSAlex Tomas /*
2215c9de560dSAlex Tomas  * The routine checks whether found extent is good enough. If it is,
2216c9de560dSAlex Tomas  * then the extent gets marked used and flag is set to the context
2217c9de560dSAlex Tomas  * to stop scanning. Otherwise, the extent is compared with the
2218c9de560dSAlex Tomas  * previous found extent and if new one is better, then it's stored
2219c9de560dSAlex Tomas  * in the context. Later, the best found extent will be used, if
2220c9de560dSAlex Tomas  * mballoc can't find good enough extent.
2221c9de560dSAlex Tomas  *
22223582e745SOjaswin Mujoo  * The algorithm used is roughly as follows:
22233582e745SOjaswin Mujoo  *
22243582e745SOjaswin Mujoo  * * If free extent found is exactly as big as goal, then
22253582e745SOjaswin Mujoo  *   stop the scan and use it immediately
22263582e745SOjaswin Mujoo  *
22273582e745SOjaswin Mujoo  * * If free extent found is smaller than goal, then keep retrying
22283582e745SOjaswin Mujoo  *   upto a max of sbi->s_mb_max_to_scan times (default 200). After
22293582e745SOjaswin Mujoo  *   that stop scanning and use whatever we have.
22303582e745SOjaswin Mujoo  *
22313582e745SOjaswin Mujoo  * * If free extent found is bigger than goal, then keep retrying
22323582e745SOjaswin Mujoo  *   upto a max of sbi->s_mb_min_to_scan times (default 10) before
22333582e745SOjaswin Mujoo  *   stopping the scan and using the extent.
22343582e745SOjaswin Mujoo  *
22353582e745SOjaswin Mujoo  *
2236c9de560dSAlex Tomas  * FIXME: real allocation policy is to be designed yet!
2237c9de560dSAlex Tomas  */
2238c9de560dSAlex Tomas static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
2239c9de560dSAlex Tomas 					struct ext4_free_extent *ex,
2240c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2241c9de560dSAlex Tomas {
2242c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
2243c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
2244c9de560dSAlex Tomas 
2245c9de560dSAlex Tomas 	BUG_ON(ex->fe_len <= 0);
22467137d7a4STheodore Ts'o 	BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
22477137d7a4STheodore Ts'o 	BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2248c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
2249c9de560dSAlex Tomas 
2250c9de560dSAlex Tomas 	ac->ac_found++;
2251fdd9a009SOjaswin Mujoo 	ac->ac_cX_found[ac->ac_criteria]++;
2252c9de560dSAlex Tomas 
2253c9de560dSAlex Tomas 	/*
2254c9de560dSAlex Tomas 	 * The special case - take what you catch first
2255c9de560dSAlex Tomas 	 */
2256c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2257c9de560dSAlex Tomas 		*bex = *ex;
2258c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2259c9de560dSAlex Tomas 		return;
2260c9de560dSAlex Tomas 	}
2261c9de560dSAlex Tomas 
2262c9de560dSAlex Tomas 	/*
2263c9de560dSAlex Tomas 	 * Let's check whether the chuck is good enough
2264c9de560dSAlex Tomas 	 */
2265c9de560dSAlex Tomas 	if (ex->fe_len == gex->fe_len) {
2266c9de560dSAlex Tomas 		*bex = *ex;
2267c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2268c9de560dSAlex Tomas 		return;
2269c9de560dSAlex Tomas 	}
2270c9de560dSAlex Tomas 
2271c9de560dSAlex Tomas 	/*
2272c9de560dSAlex Tomas 	 * If this is first found extent, just store it in the context
2273c9de560dSAlex Tomas 	 */
2274c9de560dSAlex Tomas 	if (bex->fe_len == 0) {
2275c9de560dSAlex Tomas 		*bex = *ex;
2276c9de560dSAlex Tomas 		return;
2277c9de560dSAlex Tomas 	}
2278c9de560dSAlex Tomas 
2279c9de560dSAlex Tomas 	/*
2280c9de560dSAlex Tomas 	 * If new found extent is better, store it in the context
2281c9de560dSAlex Tomas 	 */
2282c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len) {
2283c9de560dSAlex Tomas 		/* if the request isn't satisfied, any found extent
2284c9de560dSAlex Tomas 		 * larger than previous best one is better */
2285c9de560dSAlex Tomas 		if (ex->fe_len > bex->fe_len)
2286c9de560dSAlex Tomas 			*bex = *ex;
2287c9de560dSAlex Tomas 	} else if (ex->fe_len > gex->fe_len) {
2288c9de560dSAlex Tomas 		/* if the request is satisfied, then we try to find
2289c9de560dSAlex Tomas 		 * an extent that still satisfy the request, but is
2290c9de560dSAlex Tomas 		 * smaller than previous one */
2291c9de560dSAlex Tomas 		if (ex->fe_len < bex->fe_len)
2292c9de560dSAlex Tomas 			*bex = *ex;
2293c9de560dSAlex Tomas 	}
2294c9de560dSAlex Tomas 
2295c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 0);
2296c9de560dSAlex Tomas }
2297c9de560dSAlex Tomas 
2298089ceeccSEric Sandeen static noinline_for_stack
229985b67ffbSKemeng Shi void ext4_mb_try_best_found(struct ext4_allocation_context *ac,
2300c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2301c9de560dSAlex Tomas {
2302c9de560dSAlex Tomas 	struct ext4_free_extent ex = ac->ac_b_ex;
2303c9de560dSAlex Tomas 	ext4_group_t group = ex.fe_group;
2304c9de560dSAlex Tomas 	int max;
2305c9de560dSAlex Tomas 	int err;
2306c9de560dSAlex Tomas 
2307c9de560dSAlex Tomas 	BUG_ON(ex.fe_len <= 0);
2308c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2309c9de560dSAlex Tomas 	if (err)
231085b67ffbSKemeng Shi 		return;
2311c9de560dSAlex Tomas 
2312c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
23134530b366SBaokun Li 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
23144530b366SBaokun Li 		goto out;
23154530b366SBaokun Li 
231615c006a2SRobin Dong 	max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
2317c9de560dSAlex Tomas 
2318c9de560dSAlex Tomas 	if (max > 0) {
2319c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
2320c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2321c9de560dSAlex Tomas 	}
2322c9de560dSAlex Tomas 
23234530b366SBaokun Li out:
2324c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
2325e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
2326c9de560dSAlex Tomas }
2327c9de560dSAlex Tomas 
2328089ceeccSEric Sandeen static noinline_for_stack
2329089ceeccSEric Sandeen int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
2330c9de560dSAlex Tomas 				struct ext4_buddy *e4b)
2331c9de560dSAlex Tomas {
2332c9de560dSAlex Tomas 	ext4_group_t group = ac->ac_g_ex.fe_group;
2333c9de560dSAlex Tomas 	int max;
2334c9de560dSAlex Tomas 	int err;
2335c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2336838cd0cfSYongqiang Yang 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2337c9de560dSAlex Tomas 	struct ext4_free_extent ex;
2338c9de560dSAlex Tomas 
23395354b2afSTheodore Ts'o 	if (!grp)
23405354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
234101e4ca29SKemeng Shi 	if (!(ac->ac_flags & (EXT4_MB_HINT_TRY_GOAL | EXT4_MB_HINT_GOAL_ONLY)))
2342c9de560dSAlex Tomas 		return 0;
2343838cd0cfSYongqiang Yang 	if (grp->bb_free == 0)
2344838cd0cfSYongqiang Yang 		return 0;
2345c9de560dSAlex Tomas 
2346c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2347c9de560dSAlex Tomas 	if (err)
2348c9de560dSAlex Tomas 		return err;
2349c9de560dSAlex Tomas 
2350c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
235183269837SBaokun Li 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
235283269837SBaokun Li 		goto out;
235383269837SBaokun Li 
235415c006a2SRobin Dong 	max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
2355c9de560dSAlex Tomas 			     ac->ac_g_ex.fe_len, &ex);
2356ab0c00fcSTheodore Ts'o 	ex.fe_logical = 0xDEADFA11; /* debug value */
2357c9de560dSAlex Tomas 
2358c3defd99SKemeng Shi 	if (max >= ac->ac_g_ex.fe_len &&
2359c3defd99SKemeng Shi 	    ac->ac_g_ex.fe_len == EXT4_B2C(sbi, sbi->s_stripe)) {
2360c9de560dSAlex Tomas 		ext4_fsblk_t start;
2361c9de560dSAlex Tomas 
236299c515e3SKemeng Shi 		start = ext4_grp_offs_to_block(ac->ac_sb, &ex);
2363c9de560dSAlex Tomas 		/* use do_div to get remainder (would be 64-bit modulo) */
2364c9de560dSAlex Tomas 		if (do_div(start, sbi->s_stripe) == 0) {
2365c9de560dSAlex Tomas 			ac->ac_found++;
2366c9de560dSAlex Tomas 			ac->ac_b_ex = ex;
2367c9de560dSAlex Tomas 			ext4_mb_use_best_found(ac, e4b);
2368c9de560dSAlex Tomas 		}
2369c9de560dSAlex Tomas 	} else if (max >= ac->ac_g_ex.fe_len) {
2370c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
2371c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2372c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2373c9de560dSAlex Tomas 		ac->ac_found++;
2374c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
2375c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2376c9de560dSAlex Tomas 	} else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
2377c9de560dSAlex Tomas 		/* Sometimes, caller may want to merge even small
2378c9de560dSAlex Tomas 		 * number of blocks to an existing extent */
2379c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
2380c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2381c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2382c9de560dSAlex Tomas 		ac->ac_found++;
2383c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
2384c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2385c9de560dSAlex Tomas 	}
238683269837SBaokun Li out:
2387c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
2388e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
2389c9de560dSAlex Tomas 
2390c9de560dSAlex Tomas 	return 0;
2391c9de560dSAlex Tomas }
2392c9de560dSAlex Tomas 
2393c9de560dSAlex Tomas /*
2394c9de560dSAlex Tomas  * The routine scans buddy structures (not bitmap!) from given order
2395c9de560dSAlex Tomas  * to max order and tries to find big enough chunk to satisfy the req
2396c9de560dSAlex Tomas  */
2397089ceeccSEric Sandeen static noinline_for_stack
2398089ceeccSEric Sandeen void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
2399c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2400c9de560dSAlex Tomas {
2401c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
2402c9de560dSAlex Tomas 	struct ext4_group_info *grp = e4b->bd_info;
2403c9de560dSAlex Tomas 	void *buddy;
2404c9de560dSAlex Tomas 	int i;
2405c9de560dSAlex Tomas 	int k;
2406c9de560dSAlex Tomas 	int max;
2407c9de560dSAlex Tomas 
2408c9de560dSAlex Tomas 	BUG_ON(ac->ac_2order <= 0);
24094b68f6dfSHarshad Shirwadkar 	for (i = ac->ac_2order; i < MB_NUM_ORDERS(sb); i++) {
2410c9de560dSAlex Tomas 		if (grp->bb_counters[i] == 0)
2411c9de560dSAlex Tomas 			continue;
2412c9de560dSAlex Tomas 
2413c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, i, &max);
241419b8b035STheodore Ts'o 		if (WARN_RATELIMIT(buddy == NULL,
241519b8b035STheodore Ts'o 			 "ext4: mb_simple_scan_group: mb_find_buddy failed, (%d)\n", i))
241619b8b035STheodore Ts'o 			continue;
2417c9de560dSAlex Tomas 
2418ffad0a44SAneesh Kumar K.V 		k = mb_find_next_zero_bit(buddy, max, 0);
2419eb576086SDmitry Monakhov 		if (k >= max) {
2420eb576086SDmitry Monakhov 			ext4_mark_group_bitmap_corrupted(ac->ac_sb,
2421eb576086SDmitry Monakhov 					e4b->bd_group,
2422eb576086SDmitry Monakhov 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2423c5f3a382SBaokun Li 			ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
2424c5f3a382SBaokun Li 				"%d free clusters of order %d. But found 0",
2425c5f3a382SBaokun Li 				grp->bb_counters[i], i);
2426eb576086SDmitry Monakhov 			break;
2427eb576086SDmitry Monakhov 		}
2428c9de560dSAlex Tomas 		ac->ac_found++;
2429fdd9a009SOjaswin Mujoo 		ac->ac_cX_found[ac->ac_criteria]++;
2430c9de560dSAlex Tomas 
2431c9de560dSAlex Tomas 		ac->ac_b_ex.fe_len = 1 << i;
2432c9de560dSAlex Tomas 		ac->ac_b_ex.fe_start = k << i;
2433c9de560dSAlex Tomas 		ac->ac_b_ex.fe_group = e4b->bd_group;
2434c9de560dSAlex Tomas 
2435c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2436c9de560dSAlex Tomas 
243753f86b17SRitesh Harjani 		BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
2438c9de560dSAlex Tomas 
2439c9de560dSAlex Tomas 		if (EXT4_SB(sb)->s_mb_stats)
2440c9de560dSAlex Tomas 			atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
2441c9de560dSAlex Tomas 
2442c9de560dSAlex Tomas 		break;
2443c9de560dSAlex Tomas 	}
2444c9de560dSAlex Tomas }
2445c9de560dSAlex Tomas 
2446c9de560dSAlex Tomas /*
2447c9de560dSAlex Tomas  * The routine scans the group and measures all found extents.
2448c9de560dSAlex Tomas  * In order to optimize scanning, caller must pass number of
2449c9de560dSAlex Tomas  * free blocks in the group, so the routine can know upper limit.
2450c9de560dSAlex Tomas  */
2451089ceeccSEric Sandeen static noinline_for_stack
2452089ceeccSEric Sandeen void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
2453c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2454c9de560dSAlex Tomas {
2455c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
2456c5e8f3f3STheodore Ts'o 	void *bitmap = e4b->bd_bitmap;
2457c9de560dSAlex Tomas 	struct ext4_free_extent ex;
24581b420011SOjaswin Mujoo 	int i, j, freelen;
2459c9de560dSAlex Tomas 	int free;
2460c9de560dSAlex Tomas 
2461c9de560dSAlex Tomas 	free = e4b->bd_info->bb_free;
2462907ea529STheodore Ts'o 	if (WARN_ON(free <= 0))
2463907ea529STheodore Ts'o 		return;
2464c9de560dSAlex Tomas 
2465c9de560dSAlex Tomas 	i = e4b->bd_info->bb_first_free;
2466c9de560dSAlex Tomas 
2467c9de560dSAlex Tomas 	while (free && ac->ac_status == AC_STATUS_CONTINUE) {
2468ffad0a44SAneesh Kumar K.V 		i = mb_find_next_zero_bit(bitmap,
24697137d7a4STheodore Ts'o 						EXT4_CLUSTERS_PER_GROUP(sb), i);
24707137d7a4STheodore Ts'o 		if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
247126346ff6SAneesh Kumar K.V 			/*
2472e56eb659SAneesh Kumar K.V 			 * IF we have corrupt bitmap, we won't find any
247326346ff6SAneesh Kumar K.V 			 * free blocks even though group info says we
2474b483bb77SRandy Dunlap 			 * have free blocks
247526346ff6SAneesh Kumar K.V 			 */
2476c5f3a382SBaokun Li 			ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2477c5f3a382SBaokun Li 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2478e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
247953accfa9STheodore Ts'o 					"%d free clusters as per "
2480fde4d95aSTheodore Ts'o 					"group info. But bitmap says 0",
248126346ff6SAneesh Kumar K.V 					free);
2482c9de560dSAlex Tomas 			break;
2483c9de560dSAlex Tomas 		}
2484c9de560dSAlex Tomas 
2485304749c0SOjaswin Mujoo 		if (!ext4_mb_cr_expensive(ac->ac_criteria)) {
24861b420011SOjaswin Mujoo 			/*
2487f52f3d2bSOjaswin Mujoo 			 * In CR_GOAL_LEN_FAST and CR_BEST_AVAIL_LEN, we are
2488f52f3d2bSOjaswin Mujoo 			 * sure that this group will have a large enough
2489f52f3d2bSOjaswin Mujoo 			 * continuous free extent, so skip over the smaller free
2490f52f3d2bSOjaswin Mujoo 			 * extents
24911b420011SOjaswin Mujoo 			 */
24921b420011SOjaswin Mujoo 			j = mb_find_next_bit(bitmap,
24931b420011SOjaswin Mujoo 						EXT4_CLUSTERS_PER_GROUP(sb), i);
24941b420011SOjaswin Mujoo 			freelen = j - i;
24951b420011SOjaswin Mujoo 
24961b420011SOjaswin Mujoo 			if (freelen < ac->ac_g_ex.fe_len) {
24971b420011SOjaswin Mujoo 				i = j;
24981b420011SOjaswin Mujoo 				free -= freelen;
24991b420011SOjaswin Mujoo 				continue;
25001b420011SOjaswin Mujoo 			}
25011b420011SOjaswin Mujoo 		}
25021b420011SOjaswin Mujoo 
250315c006a2SRobin Dong 		mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
2504907ea529STheodore Ts'o 		if (WARN_ON(ex.fe_len <= 0))
2505907ea529STheodore Ts'o 			break;
250626346ff6SAneesh Kumar K.V 		if (free < ex.fe_len) {
2507c5f3a382SBaokun Li 			ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2508c5f3a382SBaokun Li 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2509e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
251053accfa9STheodore Ts'o 					"%d free clusters as per "
2511fde4d95aSTheodore Ts'o 					"group info. But got %d blocks",
251226346ff6SAneesh Kumar K.V 					free, ex.fe_len);
2513e56eb659SAneesh Kumar K.V 			/*
2514e56eb659SAneesh Kumar K.V 			 * The number of free blocks differs. This mostly
2515e56eb659SAneesh Kumar K.V 			 * indicate that the bitmap is corrupt. So exit
2516e56eb659SAneesh Kumar K.V 			 * without claiming the space.
2517e56eb659SAneesh Kumar K.V 			 */
2518e56eb659SAneesh Kumar K.V 			break;
251926346ff6SAneesh Kumar K.V 		}
2520ab0c00fcSTheodore Ts'o 		ex.fe_logical = 0xDEADC0DE; /* debug value */
2521c9de560dSAlex Tomas 		ext4_mb_measure_extent(ac, &ex, e4b);
2522c9de560dSAlex Tomas 
2523c9de560dSAlex Tomas 		i += ex.fe_len;
2524c9de560dSAlex Tomas 		free -= ex.fe_len;
2525c9de560dSAlex Tomas 	}
2526c9de560dSAlex Tomas 
2527c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 1);
2528c9de560dSAlex Tomas }
2529c9de560dSAlex Tomas 
2530c9de560dSAlex Tomas /*
2531c9de560dSAlex Tomas  * This is a special case for storages like raid5
2532506bf2d8SEric Sandeen  * we try to find stripe-aligned chunks for stripe-size-multiple requests
2533c9de560dSAlex Tomas  */
2534089ceeccSEric Sandeen static noinline_for_stack
2535089ceeccSEric Sandeen void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2536c9de560dSAlex Tomas 				 struct ext4_buddy *e4b)
2537c9de560dSAlex Tomas {
2538c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
2539c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2540c5e8f3f3STheodore Ts'o 	void *bitmap = e4b->bd_bitmap;
2541c9de560dSAlex Tomas 	struct ext4_free_extent ex;
2542c9de560dSAlex Tomas 	ext4_fsblk_t first_group_block;
2543c9de560dSAlex Tomas 	ext4_fsblk_t a;
2544c3defd99SKemeng Shi 	ext4_grpblk_t i, stripe;
2545c9de560dSAlex Tomas 	int max;
2546c9de560dSAlex Tomas 
2547c9de560dSAlex Tomas 	BUG_ON(sbi->s_stripe == 0);
2548c9de560dSAlex Tomas 
2549c9de560dSAlex Tomas 	/* find first stripe-aligned block in group */
25505661bd68SAkinobu Mita 	first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
25515661bd68SAkinobu Mita 
2552c9de560dSAlex Tomas 	a = first_group_block + sbi->s_stripe - 1;
2553c9de560dSAlex Tomas 	do_div(a, sbi->s_stripe);
2554c9de560dSAlex Tomas 	i = (a * sbi->s_stripe) - first_group_block;
2555c9de560dSAlex Tomas 
2556c3defd99SKemeng Shi 	stripe = EXT4_B2C(sbi, sbi->s_stripe);
2557c3defd99SKemeng Shi 	i = EXT4_B2C(sbi, i);
25587137d7a4STheodore Ts'o 	while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2559c9de560dSAlex Tomas 		if (!mb_test_bit(i, bitmap)) {
2560c3defd99SKemeng Shi 			max = mb_find_extent(e4b, i, stripe, &ex);
2561c3defd99SKemeng Shi 			if (max >= stripe) {
2562c9de560dSAlex Tomas 				ac->ac_found++;
2563fdd9a009SOjaswin Mujoo 				ac->ac_cX_found[ac->ac_criteria]++;
2564ab0c00fcSTheodore Ts'o 				ex.fe_logical = 0xDEADF00D; /* debug value */
2565c9de560dSAlex Tomas 				ac->ac_b_ex = ex;
2566c9de560dSAlex Tomas 				ext4_mb_use_best_found(ac, e4b);
2567c9de560dSAlex Tomas 				break;
2568c9de560dSAlex Tomas 			}
2569c9de560dSAlex Tomas 		}
2570c3defd99SKemeng Shi 		i += stripe;
2571c9de560dSAlex Tomas 	}
2572c9de560dSAlex Tomas }
2573c9de560dSAlex Tomas 
257442ac1848SLukas Czerner /*
25758ef123feSRitesh Harjani  * This is also called BEFORE we load the buddy bitmap.
257642ac1848SLukas Czerner  * Returns either 1 or 0 indicating that the group is either suitable
25778ef123feSRitesh Harjani  * for the allocation or not.
257842ac1848SLukas Czerner  */
25798ef123feSRitesh Harjani static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
25804eb7a4a1SOjaswin Mujoo 				ext4_group_t group, enum criteria cr)
2581c9de560dSAlex Tomas {
25828ef123feSRitesh Harjani 	ext4_grpblk_t free, fragments;
2583a4912123STheodore Ts'o 	int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2584c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2585c9de560dSAlex Tomas 
2586f52f3d2bSOjaswin Mujoo 	BUG_ON(cr < CR_POWER2_ALIGNED || cr >= EXT4_MB_NUM_CRS);
25878a57d9d6SCurt Wohlgemuth 
2588a9ce5993SKemeng Shi 	if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
25898ef123feSRitesh Harjani 		return false;
259001fc48e8STheodore Ts'o 
2591dddcd2f9Sbrookxu 	free = grp->bb_free;
2592dddcd2f9Sbrookxu 	if (free == 0)
25938ef123feSRitesh Harjani 		return false;
2594c9de560dSAlex Tomas 
2595c9de560dSAlex Tomas 	fragments = grp->bb_fragments;
2596c9de560dSAlex Tomas 	if (fragments == 0)
25978ef123feSRitesh Harjani 		return false;
2598c9de560dSAlex Tomas 
2599c9de560dSAlex Tomas 	switch (cr) {
2600f52f3d2bSOjaswin Mujoo 	case CR_POWER2_ALIGNED:
2601c9de560dSAlex Tomas 		BUG_ON(ac->ac_2order == 0);
2602c9de560dSAlex Tomas 
2603a4912123STheodore Ts'o 		/* Avoid using the first bg of a flexgroup for data files */
2604a4912123STheodore Ts'o 		if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2605a4912123STheodore Ts'o 		    (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2606a4912123STheodore Ts'o 		    ((group % flex_size) == 0))
26078ef123feSRitesh Harjani 			return false;
2608a4912123STheodore Ts'o 
2609dddcd2f9Sbrookxu 		if (free < ac->ac_g_ex.fe_len)
2610dddcd2f9Sbrookxu 			return false;
2611dddcd2f9Sbrookxu 
26124b68f6dfSHarshad Shirwadkar 		if (ac->ac_2order >= MB_NUM_ORDERS(ac->ac_sb))
26138ef123feSRitesh Harjani 			return true;
261440ae3487STheodore Ts'o 
261540ae3487STheodore Ts'o 		if (grp->bb_largest_free_order < ac->ac_2order)
26168ef123feSRitesh Harjani 			return false;
261740ae3487STheodore Ts'o 
26188ef123feSRitesh Harjani 		return true;
2619f52f3d2bSOjaswin Mujoo 	case CR_GOAL_LEN_FAST:
2620f52f3d2bSOjaswin Mujoo 	case CR_BEST_AVAIL_LEN:
2621c9de560dSAlex Tomas 		if ((free / fragments) >= ac->ac_g_ex.fe_len)
26228ef123feSRitesh Harjani 			return true;
2623c9de560dSAlex Tomas 		break;
2624f52f3d2bSOjaswin Mujoo 	case CR_GOAL_LEN_SLOW:
2625c9de560dSAlex Tomas 		if (free >= ac->ac_g_ex.fe_len)
26268ef123feSRitesh Harjani 			return true;
2627c9de560dSAlex Tomas 		break;
2628f52f3d2bSOjaswin Mujoo 	case CR_ANY_FREE:
26298ef123feSRitesh Harjani 		return true;
2630c9de560dSAlex Tomas 	default:
2631c9de560dSAlex Tomas 		BUG();
2632c9de560dSAlex Tomas 	}
2633c9de560dSAlex Tomas 
26348ef123feSRitesh Harjani 	return false;
26358ef123feSRitesh Harjani }
26368ef123feSRitesh Harjani 
26378ef123feSRitesh Harjani /*
26388ef123feSRitesh Harjani  * This could return negative error code if something goes wrong
26398ef123feSRitesh Harjani  * during ext4_mb_init_group(). This should not be called with
26408ef123feSRitesh Harjani  * ext4_lock_group() held.
2641a5fda113STheodore Ts'o  *
2642a5fda113STheodore Ts'o  * Note: because we are conditionally operating with the group lock in
2643a5fda113STheodore Ts'o  * the EXT4_MB_STRICT_CHECK case, we need to fake out sparse in this
2644a5fda113STheodore Ts'o  * function using __acquire and __release.  This means we need to be
2645a5fda113STheodore Ts'o  * super careful before messing with the error path handling via "goto
2646a5fda113STheodore Ts'o  * out"!
26478ef123feSRitesh Harjani  */
26488ef123feSRitesh Harjani static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
26494eb7a4a1SOjaswin Mujoo 				     ext4_group_t group, enum criteria cr)
26508ef123feSRitesh Harjani {
26518ef123feSRitesh Harjani 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
265299377830SRitesh Harjani 	struct super_block *sb = ac->ac_sb;
2653c1d2c7d4SAlex Zhuravlev 	struct ext4_sb_info *sbi = EXT4_SB(sb);
265499377830SRitesh Harjani 	bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
26558ef123feSRitesh Harjani 	ext4_grpblk_t free;
26568ef123feSRitesh Harjani 	int ret = 0;
26578ef123feSRitesh Harjani 
26585354b2afSTheodore Ts'o 	if (!grp)
26595354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
2660a6c75eafSHarshad Shirwadkar 	if (sbi->s_mb_stats)
2661a6c75eafSHarshad Shirwadkar 		atomic64_inc(&sbi->s_bal_cX_groups_considered[ac->ac_criteria]);
2662a5fda113STheodore Ts'o 	if (should_lock) {
266399377830SRitesh Harjani 		ext4_lock_group(sb, group);
2664a5fda113STheodore Ts'o 		__release(ext4_group_lock_ptr(sb, group));
2665a5fda113STheodore Ts'o 	}
26668ef123feSRitesh Harjani 	free = grp->bb_free;
26678ef123feSRitesh Harjani 	if (free == 0)
26688ef123feSRitesh Harjani 		goto out;
2669304749c0SOjaswin Mujoo 	/*
2670304749c0SOjaswin Mujoo 	 * In all criterias except CR_ANY_FREE we try to avoid groups that
2671304749c0SOjaswin Mujoo 	 * can't possibly satisfy the full goal request due to insufficient
2672304749c0SOjaswin Mujoo 	 * free blocks.
2673304749c0SOjaswin Mujoo 	 */
2674304749c0SOjaswin Mujoo 	if (cr < CR_ANY_FREE && free < ac->ac_g_ex.fe_len)
26758ef123feSRitesh Harjani 		goto out;
26768ef123feSRitesh Harjani 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
26778ef123feSRitesh Harjani 		goto out;
2678a5fda113STheodore Ts'o 	if (should_lock) {
2679a5fda113STheodore Ts'o 		__acquire(ext4_group_lock_ptr(sb, group));
268099377830SRitesh Harjani 		ext4_unlock_group(sb, group);
2681a5fda113STheodore Ts'o 	}
26828ef123feSRitesh Harjani 
26838ef123feSRitesh Harjani 	/* We only do this if the grp has never been initialized */
26848ef123feSRitesh Harjani 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2685c1d2c7d4SAlex Zhuravlev 		struct ext4_group_desc *gdp =
2686c1d2c7d4SAlex Zhuravlev 			ext4_get_group_desc(sb, group, NULL);
2687c1d2c7d4SAlex Zhuravlev 		int ret;
2688c1d2c7d4SAlex Zhuravlev 
2689f52f3d2bSOjaswin Mujoo 		/*
26902caffb6aSKemeng Shi 		 * CR_POWER2_ALIGNED/CR_GOAL_LEN_FAST is a very optimistic
2691f52f3d2bSOjaswin Mujoo 		 * search to find large good chunks almost for free. If buddy
2692f52f3d2bSOjaswin Mujoo 		 * data is not ready, then this optimization makes no sense. But
2693f52f3d2bSOjaswin Mujoo 		 * we never skip the first block group in a flex_bg, since this
2694f52f3d2bSOjaswin Mujoo 		 * gets used for metadata block allocation, and we want to make
2695f52f3d2bSOjaswin Mujoo 		 * sure we locate metadata blocks in the first block group in
2696f52f3d2bSOjaswin Mujoo 		 * the flex_bg if possible.
2697c1d2c7d4SAlex Zhuravlev 		 */
2698304749c0SOjaswin Mujoo 		if (!ext4_mb_cr_expensive(cr) &&
2699c1d2c7d4SAlex Zhuravlev 		    (!sbi->s_log_groups_per_flex ||
2700c1d2c7d4SAlex Zhuravlev 		     ((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
2701c1d2c7d4SAlex Zhuravlev 		    !(ext4_has_group_desc_csum(sb) &&
2702c1d2c7d4SAlex Zhuravlev 		      (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
2703c1d2c7d4SAlex Zhuravlev 			return 0;
2704c1d2c7d4SAlex Zhuravlev 		ret = ext4_mb_init_group(sb, group, GFP_NOFS);
27058ef123feSRitesh Harjani 		if (ret)
27068ef123feSRitesh Harjani 			return ret;
27078ef123feSRitesh Harjani 	}
27088ef123feSRitesh Harjani 
2709a5fda113STheodore Ts'o 	if (should_lock) {
271099377830SRitesh Harjani 		ext4_lock_group(sb, group);
2711a5fda113STheodore Ts'o 		__release(ext4_group_lock_ptr(sb, group));
2712a5fda113STheodore Ts'o 	}
27138ef123feSRitesh Harjani 	ret = ext4_mb_good_group(ac, group, cr);
27148ef123feSRitesh Harjani out:
2715a5fda113STheodore Ts'o 	if (should_lock) {
2716a5fda113STheodore Ts'o 		__acquire(ext4_group_lock_ptr(sb, group));
271799377830SRitesh Harjani 		ext4_unlock_group(sb, group);
2718a5fda113STheodore Ts'o 	}
27198ef123feSRitesh Harjani 	return ret;
2720c9de560dSAlex Tomas }
2721c9de560dSAlex Tomas 
2722cfd73237SAlex Zhuravlev /*
2723cfd73237SAlex Zhuravlev  * Start prefetching @nr block bitmaps starting at @group.
2724cfd73237SAlex Zhuravlev  * Return the next group which needs to be prefetched.
2725cfd73237SAlex Zhuravlev  */
27263d392b26STheodore Ts'o ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
2727cfd73237SAlex Zhuravlev 			      unsigned int nr, int *cnt)
2728cfd73237SAlex Zhuravlev {
2729cfd73237SAlex Zhuravlev 	ext4_group_t ngroups = ext4_get_groups_count(sb);
2730cfd73237SAlex Zhuravlev 	struct buffer_head *bh;
2731cfd73237SAlex Zhuravlev 	struct blk_plug plug;
2732cfd73237SAlex Zhuravlev 
2733cfd73237SAlex Zhuravlev 	blk_start_plug(&plug);
2734cfd73237SAlex Zhuravlev 	while (nr-- > 0) {
2735cfd73237SAlex Zhuravlev 		struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2736cfd73237SAlex Zhuravlev 								  NULL);
2737cfd73237SAlex Zhuravlev 		struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2738cfd73237SAlex Zhuravlev 
2739cfd73237SAlex Zhuravlev 		/*
2740cfd73237SAlex Zhuravlev 		 * Prefetch block groups with free blocks; but don't
2741cfd73237SAlex Zhuravlev 		 * bother if it is marked uninitialized on disk, since
2742cfd73237SAlex Zhuravlev 		 * it won't require I/O to read.  Also only try to
2743cfd73237SAlex Zhuravlev 		 * prefetch once, so we avoid getblk() call, which can
2744cfd73237SAlex Zhuravlev 		 * be expensive.
2745cfd73237SAlex Zhuravlev 		 */
27465354b2afSTheodore Ts'o 		if (gdp && grp && !EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
2747cfd73237SAlex Zhuravlev 		    EXT4_MB_GRP_NEED_INIT(grp) &&
27483c629604SOjaswin Mujoo 		    ext4_free_group_clusters(sb, gdp) > 0 ) {
2749cfd73237SAlex Zhuravlev 			bh = ext4_read_block_bitmap_nowait(sb, group, true);
2750cfd73237SAlex Zhuravlev 			if (bh && !IS_ERR(bh)) {
2751cfd73237SAlex Zhuravlev 				if (!buffer_uptodate(bh) && cnt)
2752cfd73237SAlex Zhuravlev 					(*cnt)++;
2753cfd73237SAlex Zhuravlev 				brelse(bh);
2754cfd73237SAlex Zhuravlev 			}
2755cfd73237SAlex Zhuravlev 		}
2756cfd73237SAlex Zhuravlev 		if (++group >= ngroups)
2757cfd73237SAlex Zhuravlev 			group = 0;
2758cfd73237SAlex Zhuravlev 	}
2759cfd73237SAlex Zhuravlev 	blk_finish_plug(&plug);
2760cfd73237SAlex Zhuravlev 	return group;
2761cfd73237SAlex Zhuravlev }
2762cfd73237SAlex Zhuravlev 
2763cfd73237SAlex Zhuravlev /*
2764cfd73237SAlex Zhuravlev  * Prefetching reads the block bitmap into the buffer cache; but we
2765cfd73237SAlex Zhuravlev  * need to make sure that the buddy bitmap in the page cache has been
2766cfd73237SAlex Zhuravlev  * initialized.  Note that ext4_mb_init_group() will block if the I/O
2767cfd73237SAlex Zhuravlev  * is not yet completed, or indeed if it was not initiated by
2768cfd73237SAlex Zhuravlev  * ext4_mb_prefetch did not start the I/O.
2769cfd73237SAlex Zhuravlev  *
2770cfd73237SAlex Zhuravlev  * TODO: We should actually kick off the buddy bitmap setup in a work
2771cfd73237SAlex Zhuravlev  * queue when the buffer I/O is completed, so that we don't block
2772cfd73237SAlex Zhuravlev  * waiting for the block allocation bitmap read to finish when
2773cfd73237SAlex Zhuravlev  * ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
2774cfd73237SAlex Zhuravlev  */
27753d392b26STheodore Ts'o void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
2776cfd73237SAlex Zhuravlev 			   unsigned int nr)
2777cfd73237SAlex Zhuravlev {
277822fab984SKemeng Shi 	struct ext4_group_desc *gdp;
277922fab984SKemeng Shi 	struct ext4_group_info *grp;
2780cfd73237SAlex Zhuravlev 
278122fab984SKemeng Shi 	while (nr-- > 0) {
2782cfd73237SAlex Zhuravlev 		if (!group)
2783cfd73237SAlex Zhuravlev 			group = ext4_get_groups_count(sb);
2784cfd73237SAlex Zhuravlev 		group--;
278522fab984SKemeng Shi 		gdp = ext4_get_group_desc(sb, group, NULL);
2786cfd73237SAlex Zhuravlev 		grp = ext4_get_group_info(sb, group);
2787cfd73237SAlex Zhuravlev 
27885354b2afSTheodore Ts'o 		if (grp && gdp && EXT4_MB_GRP_NEED_INIT(grp) &&
27893c629604SOjaswin Mujoo 		    ext4_free_group_clusters(sb, gdp) > 0) {
2790cfd73237SAlex Zhuravlev 			if (ext4_mb_init_group(sb, group, GFP_NOFS))
2791cfd73237SAlex Zhuravlev 				break;
2792cfd73237SAlex Zhuravlev 		}
2793cfd73237SAlex Zhuravlev 	}
2794cfd73237SAlex Zhuravlev }
2795cfd73237SAlex Zhuravlev 
27964ddfef7bSEric Sandeen static noinline_for_stack int
27974ddfef7bSEric Sandeen ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2798c9de560dSAlex Tomas {
2799cfd73237SAlex Zhuravlev 	ext4_group_t prefetch_grp = 0, ngroups, group, i;
28004c0cfebdSTheodore Ts'o 	enum criteria new_cr, cr = CR_GOAL_LEN_FAST;
280142ac1848SLukas Czerner 	int err = 0, first_err = 0;
2802cfd73237SAlex Zhuravlev 	unsigned int nr = 0, prefetch_ios = 0;
2803c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
2804c9de560dSAlex Tomas 	struct super_block *sb;
2805c9de560dSAlex Tomas 	struct ext4_buddy e4b;
280666d5e027Sbrookxu 	int lost;
2807c9de560dSAlex Tomas 
2808c9de560dSAlex Tomas 	sb = ac->ac_sb;
2809c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
28108df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
2811fb0a387dSEric Sandeen 	/* non-extent files are limited to low blocks/groups */
281212e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2813fb0a387dSEric Sandeen 		ngroups = sbi->s_blockfile_groups;
2814fb0a387dSEric Sandeen 
2815c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2816c9de560dSAlex Tomas 
2817c9de560dSAlex Tomas 	/* first, try the goal */
2818c9de560dSAlex Tomas 	err = ext4_mb_find_by_goal(ac, &e4b);
2819c9de560dSAlex Tomas 	if (err || ac->ac_status == AC_STATUS_FOUND)
2820c9de560dSAlex Tomas 		goto out;
2821c9de560dSAlex Tomas 
2822c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2823c9de560dSAlex Tomas 		goto out;
2824c9de560dSAlex Tomas 
2825c9de560dSAlex Tomas 	/*
2826e9a3cd48Sbrookxu 	 * ac->ac_2order is set only if the fe_len is a power of 2
28274eea9fbeSKemeng Shi 	 * if ac->ac_2order is set we also set criteria to CR_POWER2_ALIGNED
28284eea9fbeSKemeng Shi 	 * so that we try exact allocation using buddy.
2829c9de560dSAlex Tomas 	 */
2830c9de560dSAlex Tomas 	i = fls(ac->ac_g_ex.fe_len);
2831c9de560dSAlex Tomas 	ac->ac_2order = 0;
2832c9de560dSAlex Tomas 	/*
2833c9de560dSAlex Tomas 	 * We search using buddy data only if the order of the request
2834c9de560dSAlex Tomas 	 * is greater than equal to the sbi_s_mb_order2_reqs
2835b713a5ecSTheodore Ts'o 	 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2836d9b22cf9SJan Kara 	 * We also support searching for power-of-two requests only for
2837d9b22cf9SJan Kara 	 * requests upto maximum buddy size we have constructed.
2838c9de560dSAlex Tomas 	 */
28394b68f6dfSHarshad Shirwadkar 	if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) {
2840bb60caa2SKemeng Shi 		if (is_power_of_2(ac->ac_g_ex.fe_len))
28411a5d5e5dSJeremy Cline 			ac->ac_2order = array_index_nospec(i - 1,
28424b68f6dfSHarshad Shirwadkar 							   MB_NUM_ORDERS(sb));
2843c9de560dSAlex Tomas 	}
2844c9de560dSAlex Tomas 
28454ba74d00STheodore Ts'o 	/* if stream allocation is enabled, use global goal */
28464ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2847c9de560dSAlex Tomas 		/* TBD: may be hot point */
2848c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
2849c9de560dSAlex Tomas 		ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2850c9de560dSAlex Tomas 		ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2851c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
2852c9de560dSAlex Tomas 	}
28534ba74d00STheodore Ts'o 
2854c9de560dSAlex Tomas 	/*
28554c0cfebdSTheodore Ts'o 	 * Let's just scan groups to find more-less suitable blocks We
28564c0cfebdSTheodore Ts'o 	 * start with CR_GOAL_LEN_FAST, unless it is power of 2
28574c0cfebdSTheodore Ts'o 	 * aligned, in which case let's do that faster approach first.
2858c9de560dSAlex Tomas 	 */
28594c0cfebdSTheodore Ts'o 	if (ac->ac_2order)
28604c0cfebdSTheodore Ts'o 		cr = CR_POWER2_ALIGNED;
2861c9de560dSAlex Tomas repeat:
28624eb7a4a1SOjaswin Mujoo 	for (; cr < EXT4_MB_NUM_CRS && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2863c9de560dSAlex Tomas 		ac->ac_criteria = cr;
2864ed8f9c75SAneesh Kumar K.V 		/*
2865ed8f9c75SAneesh Kumar K.V 		 * searching for the right group start
2866ed8f9c75SAneesh Kumar K.V 		 * from the goal value specified
2867ed8f9c75SAneesh Kumar K.V 		 */
2868ed8f9c75SAneesh Kumar K.V 		group = ac->ac_g_ex.fe_group;
2869196e402aSHarshad Shirwadkar 		ac->ac_groups_linear_remaining = sbi->s_mb_max_linear_groups;
2870cfd73237SAlex Zhuravlev 		prefetch_grp = group;
28719c97c34aSKemeng Shi 		nr = 0;
2872ed8f9c75SAneesh Kumar K.V 
28734fca50d4SJan Kara 		for (i = 0, new_cr = cr; i < ngroups; i++,
28744fca50d4SJan Kara 		     ext4_mb_choose_next_group(ac, &new_cr, &group, ngroups)) {
28754fca50d4SJan Kara 			int ret = 0;
2876196e402aSHarshad Shirwadkar 
28772ed5724dSTheodore Ts'o 			cond_resched();
2878196e402aSHarshad Shirwadkar 			if (new_cr != cr) {
2879196e402aSHarshad Shirwadkar 				cr = new_cr;
2880196e402aSHarshad Shirwadkar 				goto repeat;
2881196e402aSHarshad Shirwadkar 			}
2882c9de560dSAlex Tomas 
2883cfd73237SAlex Zhuravlev 			/*
2884cfd73237SAlex Zhuravlev 			 * Batch reads of the block allocation bitmaps
2885cfd73237SAlex Zhuravlev 			 * to get multiple READs in flight; limit
28864eea9fbeSKemeng Shi 			 * prefetching at inexpensive CR, otherwise mballoc
28874eea9fbeSKemeng Shi 			 * can spend a lot of time loading imperfect groups
2888cfd73237SAlex Zhuravlev 			 */
2889cfd73237SAlex Zhuravlev 			if ((prefetch_grp == group) &&
2890304749c0SOjaswin Mujoo 			    (ext4_mb_cr_expensive(cr) ||
2891cfd73237SAlex Zhuravlev 			     prefetch_ios < sbi->s_mb_prefetch_limit)) {
2892cfd73237SAlex Zhuravlev 				nr = sbi->s_mb_prefetch;
2893cfd73237SAlex Zhuravlev 				if (ext4_has_feature_flex_bg(sb)) {
289482ef1370SChunguang Xu 					nr = 1 << sbi->s_log_groups_per_flex;
289582ef1370SChunguang Xu 					nr -= group & (nr - 1);
289682ef1370SChunguang Xu 					nr = min(nr, sbi->s_mb_prefetch);
2897cfd73237SAlex Zhuravlev 				}
2898cfd73237SAlex Zhuravlev 				prefetch_grp = ext4_mb_prefetch(sb, group,
2899cfd73237SAlex Zhuravlev 							nr, &prefetch_ios);
2900cfd73237SAlex Zhuravlev 			}
2901cfd73237SAlex Zhuravlev 
29028a57d9d6SCurt Wohlgemuth 			/* This now checks without needing the buddy page */
29038ef123feSRitesh Harjani 			ret = ext4_mb_good_group_nolock(ac, group, cr);
290442ac1848SLukas Czerner 			if (ret <= 0) {
290542ac1848SLukas Czerner 				if (!first_err)
290642ac1848SLukas Czerner 					first_err = ret;
2907c9de560dSAlex Tomas 				continue;
290842ac1848SLukas Czerner 			}
2909c9de560dSAlex Tomas 
2910c9de560dSAlex Tomas 			err = ext4_mb_load_buddy(sb, group, &e4b);
2911c9de560dSAlex Tomas 			if (err)
2912c9de560dSAlex Tomas 				goto out;
2913c9de560dSAlex Tomas 
2914c9de560dSAlex Tomas 			ext4_lock_group(sb, group);
29158a57d9d6SCurt Wohlgemuth 
29168a57d9d6SCurt Wohlgemuth 			/*
29178a57d9d6SCurt Wohlgemuth 			 * We need to check again after locking the
29188a57d9d6SCurt Wohlgemuth 			 * block group
29198a57d9d6SCurt Wohlgemuth 			 */
292042ac1848SLukas Czerner 			ret = ext4_mb_good_group(ac, group, cr);
29218ef123feSRitesh Harjani 			if (ret == 0) {
2922c9de560dSAlex Tomas 				ext4_unlock_group(sb, group);
2923e39e07fdSJing Zhang 				ext4_mb_unload_buddy(&e4b);
2924c9de560dSAlex Tomas 				continue;
2925c9de560dSAlex Tomas 			}
2926c9de560dSAlex Tomas 
2927c9de560dSAlex Tomas 			ac->ac_groups_scanned++;
2928f52f3d2bSOjaswin Mujoo 			if (cr == CR_POWER2_ALIGNED)
2929c9de560dSAlex Tomas 				ext4_mb_simple_scan_group(ac, &e4b);
29301f6bc02fSOjaswin Mujoo 			else {
29311f6bc02fSOjaswin Mujoo 				bool is_stripe_aligned = sbi->s_stripe &&
2932c3defd99SKemeng Shi 					!(ac->ac_g_ex.fe_len %
29331f6bc02fSOjaswin Mujoo 					  EXT4_B2C(sbi, sbi->s_stripe));
29341f6bc02fSOjaswin Mujoo 
29351f6bc02fSOjaswin Mujoo 				if ((cr == CR_GOAL_LEN_FAST ||
29361f6bc02fSOjaswin Mujoo 				     cr == CR_BEST_AVAIL_LEN) &&
29371f6bc02fSOjaswin Mujoo 				    is_stripe_aligned)
2938c9de560dSAlex Tomas 					ext4_mb_scan_aligned(ac, &e4b);
29391f6bc02fSOjaswin Mujoo 
29401f6bc02fSOjaswin Mujoo 				if (ac->ac_status == AC_STATUS_CONTINUE)
2941c9de560dSAlex Tomas 					ext4_mb_complex_scan_group(ac, &e4b);
29421f6bc02fSOjaswin Mujoo 			}
2943c9de560dSAlex Tomas 
2944c9de560dSAlex Tomas 			ext4_unlock_group(sb, group);
2945e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
2946c9de560dSAlex Tomas 
2947c9de560dSAlex Tomas 			if (ac->ac_status != AC_STATUS_CONTINUE)
2948c9de560dSAlex Tomas 				break;
2949c9de560dSAlex Tomas 		}
2950a6c75eafSHarshad Shirwadkar 		/* Processed all groups and haven't found blocks */
2951a6c75eafSHarshad Shirwadkar 		if (sbi->s_mb_stats && i == ngroups)
2952a6c75eafSHarshad Shirwadkar 			atomic64_inc(&sbi->s_bal_cX_failed[cr]);
29537e170922SOjaswin Mujoo 
2954f52f3d2bSOjaswin Mujoo 		if (i == ngroups && ac->ac_criteria == CR_BEST_AVAIL_LEN)
29557e170922SOjaswin Mujoo 			/* Reset goal length to original goal length before
2956f52f3d2bSOjaswin Mujoo 			 * falling into CR_GOAL_LEN_SLOW */
29577e170922SOjaswin Mujoo 			ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
2958c9de560dSAlex Tomas 	}
2959c9de560dSAlex Tomas 
2960c9de560dSAlex Tomas 	if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2961c9de560dSAlex Tomas 	    !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2962c9de560dSAlex Tomas 		/*
2963c9de560dSAlex Tomas 		 * We've been searching too long. Let's try to allocate
2964c9de560dSAlex Tomas 		 * the best chunk we've found so far
2965c9de560dSAlex Tomas 		 */
2966c9de560dSAlex Tomas 		ext4_mb_try_best_found(ac, &e4b);
2967c9de560dSAlex Tomas 		if (ac->ac_status != AC_STATUS_FOUND) {
2968c9de560dSAlex Tomas 			/*
2969c9de560dSAlex Tomas 			 * Someone more lucky has already allocated it.
2970c9de560dSAlex Tomas 			 * The only thing we can do is just take first
2971c9de560dSAlex Tomas 			 * found block(s)
2972c9de560dSAlex Tomas 			 */
297366d5e027Sbrookxu 			lost = atomic_inc_return(&sbi->s_mb_lost_chunks);
297466d5e027Sbrookxu 			mb_debug(sb, "lost chunk, group: %u, start: %d, len: %d, lost: %d\n",
2975c55ee7d2Sbrookxu 				 ac->ac_b_ex.fe_group, ac->ac_b_ex.fe_start,
2976c55ee7d2Sbrookxu 				 ac->ac_b_ex.fe_len, lost);
2977c55ee7d2Sbrookxu 
2978c9de560dSAlex Tomas 			ac->ac_b_ex.fe_group = 0;
2979c9de560dSAlex Tomas 			ac->ac_b_ex.fe_start = 0;
2980c9de560dSAlex Tomas 			ac->ac_b_ex.fe_len = 0;
2981c9de560dSAlex Tomas 			ac->ac_status = AC_STATUS_CONTINUE;
2982c9de560dSAlex Tomas 			ac->ac_flags |= EXT4_MB_HINT_FIRST;
2983f52f3d2bSOjaswin Mujoo 			cr = CR_ANY_FREE;
2984c9de560dSAlex Tomas 			goto repeat;
2985c9de560dSAlex Tomas 		}
2986c9de560dSAlex Tomas 	}
2987a6c75eafSHarshad Shirwadkar 
2988a6c75eafSHarshad Shirwadkar 	if (sbi->s_mb_stats && ac->ac_status == AC_STATUS_FOUND)
2989a6c75eafSHarshad Shirwadkar 		atomic64_inc(&sbi->s_bal_cX_hits[ac->ac_criteria]);
2990c9de560dSAlex Tomas out:
299142ac1848SLukas Czerner 	if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
299242ac1848SLukas Czerner 		err = first_err;
2993bbc4ec77SRitesh Harjani 
2994d3df1453SRitesh Harjani 	mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
2995bbc4ec77SRitesh Harjani 		 ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
2996bbc4ec77SRitesh Harjani 		 ac->ac_flags, cr, err);
2997cfd73237SAlex Zhuravlev 
2998cfd73237SAlex Zhuravlev 	if (nr)
2999cfd73237SAlex Zhuravlev 		ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
3000cfd73237SAlex Zhuravlev 
3001c9de560dSAlex Tomas 	return err;
3002c9de560dSAlex Tomas }
3003c9de560dSAlex Tomas 
3004c9de560dSAlex Tomas static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
3005c9de560dSAlex Tomas {
3006359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3007c9de560dSAlex Tomas 	ext4_group_t group;
3008c9de560dSAlex Tomas 
30098df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
3010c9de560dSAlex Tomas 		return NULL;
3011c9de560dSAlex Tomas 	group = *pos + 1;
3012a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
3013c9de560dSAlex Tomas }
3014c9de560dSAlex Tomas 
3015c9de560dSAlex Tomas static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
3016c9de560dSAlex Tomas {
3017359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3018c9de560dSAlex Tomas 	ext4_group_t group;
3019c9de560dSAlex Tomas 
3020c9de560dSAlex Tomas 	++*pos;
30218df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
3022c9de560dSAlex Tomas 		return NULL;
3023c9de560dSAlex Tomas 	group = *pos + 1;
3024a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
3025c9de560dSAlex Tomas }
3026c9de560dSAlex Tomas 
3027c9de560dSAlex Tomas static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
3028c9de560dSAlex Tomas {
3029359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3030a9df9a49STheodore Ts'o 	ext4_group_t group = (ext4_group_t) ((unsigned long) v);
303125044880Syangerkun 	int i, err;
30324b55d343Syangerkun 	char nbuf[16];
3033c9de560dSAlex Tomas 	struct ext4_buddy e4b;
30341c8457caSAditya Kali 	struct ext4_group_info *grinfo;
30352df2c340SArnd Bergmann 	unsigned char blocksize_bits = min_t(unsigned char,
30362df2c340SArnd Bergmann 					     sb->s_blocksize_bits,
30372df2c340SArnd Bergmann 					     EXT4_MAX_BLOCK_LOG_SIZE);
3038c9de560dSAlex Tomas 	struct sg {
3039c9de560dSAlex Tomas 		struct ext4_group_info info;
3040b80b32b6STheodore Ts'o 		ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
3041c9de560dSAlex Tomas 	} sg;
3042c9de560dSAlex Tomas 
3043c9de560dSAlex Tomas 	group--;
3044c9de560dSAlex Tomas 	if (group == 0)
304597b4af2fSRasmus Villemoes 		seq_puts(seq, "#group: free  frags first ["
304697b4af2fSRasmus Villemoes 			      " 2^0   2^1   2^2   2^3   2^4   2^5   2^6  "
3047802cf1f9SHuaitong Han 			      " 2^7   2^8   2^9   2^10  2^11  2^12  2^13  ]\n");
3048c9de560dSAlex Tomas 
3049b80b32b6STheodore Ts'o 	i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
3050b80b32b6STheodore Ts'o 		sizeof(struct ext4_group_info);
3051b80b32b6STheodore Ts'o 
30521c8457caSAditya Kali 	grinfo = ext4_get_group_info(sb, group);
30535354b2afSTheodore Ts'o 	if (!grinfo)
30545354b2afSTheodore Ts'o 		return 0;
30551c8457caSAditya Kali 	/* Load the group info in memory only if not already loaded. */
30561c8457caSAditya Kali 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
3057c9de560dSAlex Tomas 		err = ext4_mb_load_buddy(sb, group, &e4b);
3058c9de560dSAlex Tomas 		if (err) {
30594b55d343Syangerkun 			seq_printf(seq, "#%-5u: %s\n", group, ext4_decode_error(NULL, err, nbuf));
3060c9de560dSAlex Tomas 			return 0;
3061c9de560dSAlex Tomas 		}
306225044880Syangerkun 		ext4_mb_unload_buddy(&e4b);
30631c8457caSAditya Kali 	}
30641c8457caSAditya Kali 
306525044880Syangerkun 	/*
306625044880Syangerkun 	 * We care only about free space counters in the group info and
306725044880Syangerkun 	 * these are safe to access even after the buddy has been unloaded
306825044880Syangerkun 	 */
30695354b2afSTheodore Ts'o 	memcpy(&sg, grinfo, i);
3070a9df9a49STheodore Ts'o 	seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
3071c9de560dSAlex Tomas 			sg.info.bb_fragments, sg.info.bb_first_free);
3072c9de560dSAlex Tomas 	for (i = 0; i <= 13; i++)
30732df2c340SArnd Bergmann 		seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
3074c9de560dSAlex Tomas 				sg.info.bb_counters[i] : 0);
307568ee261fSZhang Yi 	seq_puts(seq, " ]");
307668ee261fSZhang Yi 	if (EXT4_MB_GRP_BBITMAP_CORRUPT(&sg.info))
307768ee261fSZhang Yi 		seq_puts(seq, " Block bitmap corrupted!");
307868ee261fSZhang Yi 	seq_puts(seq, "\n");
3079c9de560dSAlex Tomas 
3080c9de560dSAlex Tomas 	return 0;
3081c9de560dSAlex Tomas }
3082c9de560dSAlex Tomas 
3083c9de560dSAlex Tomas static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
3084c9de560dSAlex Tomas {
3085c9de560dSAlex Tomas }
3086c9de560dSAlex Tomas 
3087247dbed8SChristoph Hellwig const struct seq_operations ext4_mb_seq_groups_ops = {
3088c9de560dSAlex Tomas 	.start  = ext4_mb_seq_groups_start,
3089c9de560dSAlex Tomas 	.next   = ext4_mb_seq_groups_next,
3090c9de560dSAlex Tomas 	.stop   = ext4_mb_seq_groups_stop,
3091c9de560dSAlex Tomas 	.show   = ext4_mb_seq_groups_show,
3092c9de560dSAlex Tomas };
3093c9de560dSAlex Tomas 
3094a6c75eafSHarshad Shirwadkar int ext4_seq_mb_stats_show(struct seq_file *seq, void *offset)
3095a6c75eafSHarshad Shirwadkar {
3096c30365b9SYu Zhe 	struct super_block *sb = seq->private;
3097a6c75eafSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3098a6c75eafSHarshad Shirwadkar 
3099a6c75eafSHarshad Shirwadkar 	seq_puts(seq, "mballoc:\n");
3100a6c75eafSHarshad Shirwadkar 	if (!sbi->s_mb_stats) {
3101a6c75eafSHarshad Shirwadkar 		seq_puts(seq, "\tmb stats collection turned off.\n");
3102f52f3d2bSOjaswin Mujoo 		seq_puts(
3103f52f3d2bSOjaswin Mujoo 			seq,
3104f52f3d2bSOjaswin Mujoo 			"\tTo enable, please write \"1\" to sysfs file mb_stats.\n");
3105a6c75eafSHarshad Shirwadkar 		return 0;
3106a6c75eafSHarshad Shirwadkar 	}
3107a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\treqs: %u\n", atomic_read(&sbi->s_bal_reqs));
3108a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tsuccess: %u\n", atomic_read(&sbi->s_bal_success));
3109a6c75eafSHarshad Shirwadkar 
3110f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\tgroups_scanned: %u\n",
3111f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_groups_scanned));
3112a6c75eafSHarshad Shirwadkar 
3113f52f3d2bSOjaswin Mujoo 	/* CR_POWER2_ALIGNED stats */
3114f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_p2_aligned_stats:\n");
3115f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3116f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_POWER2_ALIGNED]));
3117f52f3d2bSOjaswin Mujoo 	seq_printf(
3118f52f3d2bSOjaswin Mujoo 		seq, "\t\tgroups_considered: %llu\n",
3119f52f3d2bSOjaswin Mujoo 		atomic64_read(
3120f52f3d2bSOjaswin Mujoo 			&sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]));
3121f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3122f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_POWER2_ALIGNED]));
3123a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3124f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_POWER2_ALIGNED]));
3125196e402aSHarshad Shirwadkar 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3126f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_p2_aligned_bad_suggestions));
3127a6c75eafSHarshad Shirwadkar 
3128f52f3d2bSOjaswin Mujoo 	/* CR_GOAL_LEN_FAST stats */
3129f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_goal_fast_stats:\n");
3130f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3131f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_FAST]));
3132a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tgroups_considered: %llu\n",
3133f52f3d2bSOjaswin Mujoo 		   atomic64_read(
3134f52f3d2bSOjaswin Mujoo 			   &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_FAST]));
3135f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3136f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_FAST]));
3137a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3138f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_FAST]));
3139196e402aSHarshad Shirwadkar 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3140f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_goal_fast_bad_suggestions));
3141a6c75eafSHarshad Shirwadkar 
3142f52f3d2bSOjaswin Mujoo 	/* CR_BEST_AVAIL_LEN stats */
3143f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_best_avail_stats:\n");
3144f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3145f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_BEST_AVAIL_LEN]));
3146f52f3d2bSOjaswin Mujoo 	seq_printf(
3147f52f3d2bSOjaswin Mujoo 		seq, "\t\tgroups_considered: %llu\n",
3148f52f3d2bSOjaswin Mujoo 		atomic64_read(
3149f52f3d2bSOjaswin Mujoo 			&sbi->s_bal_cX_groups_considered[CR_BEST_AVAIL_LEN]));
3150f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3151f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_BEST_AVAIL_LEN]));
31527e170922SOjaswin Mujoo 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3153f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_BEST_AVAIL_LEN]));
31547e170922SOjaswin Mujoo 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3155f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_best_avail_bad_suggestions));
31567e170922SOjaswin Mujoo 
3157f52f3d2bSOjaswin Mujoo 	/* CR_GOAL_LEN_SLOW stats */
3158f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_goal_slow_stats:\n");
3159f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3160f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_SLOW]));
3161a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tgroups_considered: %llu\n",
3162f52f3d2bSOjaswin Mujoo 		   atomic64_read(
3163f52f3d2bSOjaswin Mujoo 			   &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_SLOW]));
3164f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3165f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_SLOW]));
3166a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3167f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_SLOW]));
3168a6c75eafSHarshad Shirwadkar 
3169f52f3d2bSOjaswin Mujoo 	/* CR_ANY_FREE stats */
3170f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_any_free_stats:\n");
3171f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3172f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_ANY_FREE]));
3173f52f3d2bSOjaswin Mujoo 	seq_printf(
3174f52f3d2bSOjaswin Mujoo 		seq, "\t\tgroups_considered: %llu\n",
3175f52f3d2bSOjaswin Mujoo 		atomic64_read(&sbi->s_bal_cX_groups_considered[CR_ANY_FREE]));
3176f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3177f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_ANY_FREE]));
3178a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3179f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_ANY_FREE]));
3180f52f3d2bSOjaswin Mujoo 
3181f52f3d2bSOjaswin Mujoo 	/* Aggregates */
3182f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\textents_scanned: %u\n",
3183f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_ex_scanned));
3184a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tgoal_hits: %u\n", atomic_read(&sbi->s_bal_goals));
3185f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\tlen_goal_hits: %u\n",
3186f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_len_goals));
3187a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\t2^n_hits: %u\n", atomic_read(&sbi->s_bal_2orders));
3188a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tbreaks: %u\n", atomic_read(&sbi->s_bal_breaks));
3189a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tlost: %u\n", atomic_read(&sbi->s_mb_lost_chunks));
3190a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tbuddies_generated: %u/%u\n",
3191a6c75eafSHarshad Shirwadkar 		   atomic_read(&sbi->s_mb_buddies_generated),
3192a6c75eafSHarshad Shirwadkar 		   ext4_get_groups_count(sb));
3193a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tbuddies_time_used: %llu\n",
3194a6c75eafSHarshad Shirwadkar 		   atomic64_read(&sbi->s_mb_generation_time));
3195a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tpreallocated: %u\n",
3196a6c75eafSHarshad Shirwadkar 		   atomic_read(&sbi->s_mb_preallocated));
3197f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\tdiscarded: %u\n", atomic_read(&sbi->s_mb_discarded));
3198a6c75eafSHarshad Shirwadkar 	return 0;
3199a6c75eafSHarshad Shirwadkar }
3200a6c75eafSHarshad Shirwadkar 
3201f68f4063SHarshad Shirwadkar static void *ext4_mb_seq_structs_summary_start(struct seq_file *seq, loff_t *pos)
3202f68f4063SHarshad Shirwadkar {
3203359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3204f68f4063SHarshad Shirwadkar 	unsigned long position;
3205f68f4063SHarshad Shirwadkar 
320683e80a6eSJan Kara 	if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3207f68f4063SHarshad Shirwadkar 		return NULL;
3208f68f4063SHarshad Shirwadkar 	position = *pos + 1;
3209f68f4063SHarshad Shirwadkar 	return (void *) ((unsigned long) position);
3210f68f4063SHarshad Shirwadkar }
3211f68f4063SHarshad Shirwadkar 
3212f68f4063SHarshad Shirwadkar static void *ext4_mb_seq_structs_summary_next(struct seq_file *seq, void *v, loff_t *pos)
3213f68f4063SHarshad Shirwadkar {
3214359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3215f68f4063SHarshad Shirwadkar 	unsigned long position;
3216f68f4063SHarshad Shirwadkar 
3217f68f4063SHarshad Shirwadkar 	++*pos;
321883e80a6eSJan Kara 	if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3219f68f4063SHarshad Shirwadkar 		return NULL;
3220f68f4063SHarshad Shirwadkar 	position = *pos + 1;
3221f68f4063SHarshad Shirwadkar 	return (void *) ((unsigned long) position);
3222f68f4063SHarshad Shirwadkar }
3223f68f4063SHarshad Shirwadkar 
3224f68f4063SHarshad Shirwadkar static int ext4_mb_seq_structs_summary_show(struct seq_file *seq, void *v)
3225f68f4063SHarshad Shirwadkar {
3226359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3227f68f4063SHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3228f68f4063SHarshad Shirwadkar 	unsigned long position = ((unsigned long) v);
3229f68f4063SHarshad Shirwadkar 	struct ext4_group_info *grp;
323083e80a6eSJan Kara 	unsigned int count;
3231f68f4063SHarshad Shirwadkar 
3232f68f4063SHarshad Shirwadkar 	position--;
3233f68f4063SHarshad Shirwadkar 	if (position >= MB_NUM_ORDERS(sb)) {
323483e80a6eSJan Kara 		position -= MB_NUM_ORDERS(sb);
323583e80a6eSJan Kara 		if (position == 0)
323683e80a6eSJan Kara 			seq_puts(seq, "avg_fragment_size_lists:\n");
3237f68f4063SHarshad Shirwadkar 
323883e80a6eSJan Kara 		count = 0;
323983e80a6eSJan Kara 		read_lock(&sbi->s_mb_avg_fragment_size_locks[position]);
324083e80a6eSJan Kara 		list_for_each_entry(grp, &sbi->s_mb_avg_fragment_size[position],
324183e80a6eSJan Kara 				    bb_avg_fragment_size_node)
324283e80a6eSJan Kara 			count++;
324383e80a6eSJan Kara 		read_unlock(&sbi->s_mb_avg_fragment_size_locks[position]);
324483e80a6eSJan Kara 		seq_printf(seq, "\tlist_order_%u_groups: %u\n",
324583e80a6eSJan Kara 					(unsigned int)position, count);
3246f68f4063SHarshad Shirwadkar 		return 0;
3247f68f4063SHarshad Shirwadkar 	}
3248f68f4063SHarshad Shirwadkar 
3249f68f4063SHarshad Shirwadkar 	if (position == 0) {
3250f68f4063SHarshad Shirwadkar 		seq_printf(seq, "optimize_scan: %d\n",
3251f68f4063SHarshad Shirwadkar 			   test_opt2(sb, MB_OPTIMIZE_SCAN) ? 1 : 0);
3252f68f4063SHarshad Shirwadkar 		seq_puts(seq, "max_free_order_lists:\n");
3253f68f4063SHarshad Shirwadkar 	}
3254f68f4063SHarshad Shirwadkar 	count = 0;
325583e80a6eSJan Kara 	read_lock(&sbi->s_mb_largest_free_orders_locks[position]);
3256f68f4063SHarshad Shirwadkar 	list_for_each_entry(grp, &sbi->s_mb_largest_free_orders[position],
3257f68f4063SHarshad Shirwadkar 			    bb_largest_free_order_node)
3258f68f4063SHarshad Shirwadkar 		count++;
325983e80a6eSJan Kara 	read_unlock(&sbi->s_mb_largest_free_orders_locks[position]);
3260f68f4063SHarshad Shirwadkar 	seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3261f68f4063SHarshad Shirwadkar 		   (unsigned int)position, count);
3262f68f4063SHarshad Shirwadkar 
3263f68f4063SHarshad Shirwadkar 	return 0;
3264f68f4063SHarshad Shirwadkar }
3265f68f4063SHarshad Shirwadkar 
3266f68f4063SHarshad Shirwadkar static void ext4_mb_seq_structs_summary_stop(struct seq_file *seq, void *v)
3267f68f4063SHarshad Shirwadkar {
3268f68f4063SHarshad Shirwadkar }
3269f68f4063SHarshad Shirwadkar 
3270f68f4063SHarshad Shirwadkar const struct seq_operations ext4_mb_seq_structs_summary_ops = {
3271f68f4063SHarshad Shirwadkar 	.start  = ext4_mb_seq_structs_summary_start,
3272f68f4063SHarshad Shirwadkar 	.next   = ext4_mb_seq_structs_summary_next,
3273f68f4063SHarshad Shirwadkar 	.stop   = ext4_mb_seq_structs_summary_stop,
3274f68f4063SHarshad Shirwadkar 	.show   = ext4_mb_seq_structs_summary_show,
3275f68f4063SHarshad Shirwadkar };
3276f68f4063SHarshad Shirwadkar 
3277fb1813f4SCurt Wohlgemuth static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
3278fb1813f4SCurt Wohlgemuth {
3279fb1813f4SCurt Wohlgemuth 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3280fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
3281fb1813f4SCurt Wohlgemuth 
3282fb1813f4SCurt Wohlgemuth 	BUG_ON(!cachep);
3283fb1813f4SCurt Wohlgemuth 	return cachep;
3284fb1813f4SCurt Wohlgemuth }
32855f21b0e6SFrederic Bohe 
328628623c2fSTheodore Ts'o /*
328728623c2fSTheodore Ts'o  * Allocate the top-level s_group_info array for the specified number
328828623c2fSTheodore Ts'o  * of groups
328928623c2fSTheodore Ts'o  */
329028623c2fSTheodore Ts'o int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
329128623c2fSTheodore Ts'o {
329228623c2fSTheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(sb);
329328623c2fSTheodore Ts'o 	unsigned size;
3294df3da4eaSSuraj Jitindar Singh 	struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
329528623c2fSTheodore Ts'o 
329628623c2fSTheodore Ts'o 	size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
329728623c2fSTheodore Ts'o 		EXT4_DESC_PER_BLOCK_BITS(sb);
329828623c2fSTheodore Ts'o 	if (size <= sbi->s_group_info_size)
329928623c2fSTheodore Ts'o 		return 0;
330028623c2fSTheodore Ts'o 
330128623c2fSTheodore Ts'o 	size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
3302a7c3e901SMichal Hocko 	new_groupinfo = kvzalloc(size, GFP_KERNEL);
330328623c2fSTheodore Ts'o 	if (!new_groupinfo) {
330428623c2fSTheodore Ts'o 		ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
330528623c2fSTheodore Ts'o 		return -ENOMEM;
330628623c2fSTheodore Ts'o 	}
3307df3da4eaSSuraj Jitindar Singh 	rcu_read_lock();
3308df3da4eaSSuraj Jitindar Singh 	old_groupinfo = rcu_dereference(sbi->s_group_info);
3309df3da4eaSSuraj Jitindar Singh 	if (old_groupinfo)
3310df3da4eaSSuraj Jitindar Singh 		memcpy(new_groupinfo, old_groupinfo,
331128623c2fSTheodore Ts'o 		       sbi->s_group_info_size * sizeof(*sbi->s_group_info));
3312df3da4eaSSuraj Jitindar Singh 	rcu_read_unlock();
3313df3da4eaSSuraj Jitindar Singh 	rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
331428623c2fSTheodore Ts'o 	sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
3315df3da4eaSSuraj Jitindar Singh 	if (old_groupinfo)
3316df3da4eaSSuraj Jitindar Singh 		ext4_kvfree_array_rcu(old_groupinfo);
331728623c2fSTheodore Ts'o 	ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
331828623c2fSTheodore Ts'o 		   sbi->s_group_info_size);
331928623c2fSTheodore Ts'o 	return 0;
332028623c2fSTheodore Ts'o }
332128623c2fSTheodore Ts'o 
33225f21b0e6SFrederic Bohe /* Create and initialize ext4_group_info data for the given group. */
3323920313a7SAneesh Kumar K.V int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
33245f21b0e6SFrederic Bohe 			  struct ext4_group_desc *desc)
33255f21b0e6SFrederic Bohe {
3326fb1813f4SCurt Wohlgemuth 	int i;
33275f21b0e6SFrederic Bohe 	int metalen = 0;
3328df3da4eaSSuraj Jitindar Singh 	int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
33295f21b0e6SFrederic Bohe 	struct ext4_sb_info *sbi = EXT4_SB(sb);
33305f21b0e6SFrederic Bohe 	struct ext4_group_info **meta_group_info;
3331fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
33325f21b0e6SFrederic Bohe 
33335f21b0e6SFrederic Bohe 	/*
33345f21b0e6SFrederic Bohe 	 * First check if this group is the first of a reserved block.
33355f21b0e6SFrederic Bohe 	 * If it's true, we have to allocate a new table of pointers
33365f21b0e6SFrederic Bohe 	 * to ext4_group_info structures
33375f21b0e6SFrederic Bohe 	 */
33385f21b0e6SFrederic Bohe 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
33395f21b0e6SFrederic Bohe 		metalen = sizeof(*meta_group_info) <<
33405f21b0e6SFrederic Bohe 			EXT4_DESC_PER_BLOCK_BITS(sb);
33414fdb5543SDmitry Monakhov 		meta_group_info = kmalloc(metalen, GFP_NOFS);
33425f21b0e6SFrederic Bohe 		if (meta_group_info == NULL) {
33437f6a11e7SJoe Perches 			ext4_msg(sb, KERN_ERR, "can't allocate mem "
33449d8b9ec4STheodore Ts'o 				 "for a buddy group");
3345df119095SKemeng Shi 			return -ENOMEM;
33465f21b0e6SFrederic Bohe 		}
3347df3da4eaSSuraj Jitindar Singh 		rcu_read_lock();
3348df3da4eaSSuraj Jitindar Singh 		rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
3349df3da4eaSSuraj Jitindar Singh 		rcu_read_unlock();
33505f21b0e6SFrederic Bohe 	}
33515f21b0e6SFrederic Bohe 
3352df3da4eaSSuraj Jitindar Singh 	meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
33535f21b0e6SFrederic Bohe 	i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
33545f21b0e6SFrederic Bohe 
33554fdb5543SDmitry Monakhov 	meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
33565f21b0e6SFrederic Bohe 	if (meta_group_info[i] == NULL) {
33577f6a11e7SJoe Perches 		ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
33585f21b0e6SFrederic Bohe 		goto exit_group_info;
33595f21b0e6SFrederic Bohe 	}
33605f21b0e6SFrederic Bohe 	set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
33615f21b0e6SFrederic Bohe 		&(meta_group_info[i]->bb_state));
33625f21b0e6SFrederic Bohe 
33635f21b0e6SFrederic Bohe 	/*
33645f21b0e6SFrederic Bohe 	 * initialize bb_free to be able to skip
33655f21b0e6SFrederic Bohe 	 * empty groups without initialization
33665f21b0e6SFrederic Bohe 	 */
33678844618dSTheodore Ts'o 	if (ext4_has_group_desc_csum(sb) &&
33688844618dSTheodore Ts'o 	    (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
33695f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
3370cff1dfd7STheodore Ts'o 			ext4_free_clusters_after_init(sb, group, desc);
33715f21b0e6SFrederic Bohe 	} else {
33725f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
3373021b65bbSTheodore Ts'o 			ext4_free_group_clusters(sb, desc);
33745f21b0e6SFrederic Bohe 	}
33755f21b0e6SFrederic Bohe 
33765f21b0e6SFrederic Bohe 	INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
3377920313a7SAneesh Kumar K.V 	init_rwsem(&meta_group_info[i]->alloc_sem);
337864e290ecSVenkatesh Pallipadi 	meta_group_info[i]->bb_free_root = RB_ROOT;
3379196e402aSHarshad Shirwadkar 	INIT_LIST_HEAD(&meta_group_info[i]->bb_largest_free_order_node);
338083e80a6eSJan Kara 	INIT_LIST_HEAD(&meta_group_info[i]->bb_avg_fragment_size_node);
33818a57d9d6SCurt Wohlgemuth 	meta_group_info[i]->bb_largest_free_order = -1;  /* uninit */
338283e80a6eSJan Kara 	meta_group_info[i]->bb_avg_fragment_size_order = -1;  /* uninit */
3383196e402aSHarshad Shirwadkar 	meta_group_info[i]->bb_group = group;
33845f21b0e6SFrederic Bohe 
3385a3450215SRitesh Harjani 	mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
33865f21b0e6SFrederic Bohe 	return 0;
33875f21b0e6SFrederic Bohe 
33885f21b0e6SFrederic Bohe exit_group_info:
33895f21b0e6SFrederic Bohe 	/* If a meta_group_info table has been allocated, release it now */
3390caaf7a29STao Ma 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3391df3da4eaSSuraj Jitindar Singh 		struct ext4_group_info ***group_info;
3392df3da4eaSSuraj Jitindar Singh 
3393df3da4eaSSuraj Jitindar Singh 		rcu_read_lock();
3394df3da4eaSSuraj Jitindar Singh 		group_info = rcu_dereference(sbi->s_group_info);
3395df3da4eaSSuraj Jitindar Singh 		kfree(group_info[idx]);
3396df3da4eaSSuraj Jitindar Singh 		group_info[idx] = NULL;
3397df3da4eaSSuraj Jitindar Singh 		rcu_read_unlock();
3398caaf7a29STao Ma 	}
33995f21b0e6SFrederic Bohe 	return -ENOMEM;
34005f21b0e6SFrederic Bohe } /* ext4_mb_add_groupinfo */
34015f21b0e6SFrederic Bohe 
3402c9de560dSAlex Tomas static int ext4_mb_init_backend(struct super_block *sb)
3403c9de560dSAlex Tomas {
34048df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
3405c9de560dSAlex Tomas 	ext4_group_t i;
3406c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
340728623c2fSTheodore Ts'o 	int err;
34085f21b0e6SFrederic Bohe 	struct ext4_group_desc *desc;
3409df3da4eaSSuraj Jitindar Singh 	struct ext4_group_info ***group_info;
3410fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep;
3411c9de560dSAlex Tomas 
341228623c2fSTheodore Ts'o 	err = ext4_mb_alloc_groupinfo(sb, ngroups);
341328623c2fSTheodore Ts'o 	if (err)
341428623c2fSTheodore Ts'o 		return err;
34155f21b0e6SFrederic Bohe 
3416c9de560dSAlex Tomas 	sbi->s_buddy_cache = new_inode(sb);
3417c9de560dSAlex Tomas 	if (sbi->s_buddy_cache == NULL) {
34189d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_ERR, "can't get new inode");
3419c9de560dSAlex Tomas 		goto err_freesgi;
3420c9de560dSAlex Tomas 	}
342148e6061bSYu Jian 	/* To avoid potentially colliding with an valid on-disk inode number,
342248e6061bSYu Jian 	 * use EXT4_BAD_INO for the buddy cache inode number.  This inode is
342348e6061bSYu Jian 	 * not in the inode hash, so it should never be found by iget(), but
342448e6061bSYu Jian 	 * this will avoid confusion if it ever shows up during debugging. */
342548e6061bSYu Jian 	sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
3426c9de560dSAlex Tomas 	EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
34278df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
34284b99faa2SKhazhismel Kumykov 		cond_resched();
3429c9de560dSAlex Tomas 		desc = ext4_get_group_desc(sb, i, NULL);
3430c9de560dSAlex Tomas 		if (desc == NULL) {
34319d8b9ec4STheodore Ts'o 			ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
3432c9de560dSAlex Tomas 			goto err_freebuddy;
3433c9de560dSAlex Tomas 		}
34345f21b0e6SFrederic Bohe 		if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
34355f21b0e6SFrederic Bohe 			goto err_freebuddy;
3436c9de560dSAlex Tomas 	}
3437c9de560dSAlex Tomas 
3438cfd73237SAlex Zhuravlev 	if (ext4_has_feature_flex_bg(sb)) {
3439f91436d5SSabyrzhan Tasbolatov 		/* a single flex group is supposed to be read by a single IO.
3440f91436d5SSabyrzhan Tasbolatov 		 * 2 ^ s_log_groups_per_flex != UINT_MAX as s_mb_prefetch is
3441f91436d5SSabyrzhan Tasbolatov 		 * unsigned integer, so the maximum shift is 32.
3442f91436d5SSabyrzhan Tasbolatov 		 */
3443f91436d5SSabyrzhan Tasbolatov 		if (sbi->s_es->s_log_groups_per_flex >= 32) {
3444f91436d5SSabyrzhan Tasbolatov 			ext4_msg(sb, KERN_ERR, "too many log groups per flexible block group");
3445a8867f4eSPhillip Potter 			goto err_freebuddy;
3446f91436d5SSabyrzhan Tasbolatov 		}
3447f91436d5SSabyrzhan Tasbolatov 		sbi->s_mb_prefetch = min_t(uint, 1 << sbi->s_es->s_log_groups_per_flex,
344882ef1370SChunguang Xu 			BLK_MAX_SEGMENT_SIZE >> (sb->s_blocksize_bits - 9));
3449cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
3450cfd73237SAlex Zhuravlev 	} else {
3451cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch = 32;
3452cfd73237SAlex Zhuravlev 	}
3453cfd73237SAlex Zhuravlev 	if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
3454cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch = ext4_get_groups_count(sb);
34552caffb6aSKemeng Shi 	/*
34562caffb6aSKemeng Shi 	 * now many real IOs to prefetch within a single allocation at
34572caffb6aSKemeng Shi 	 * CR_POWER2_ALIGNED. Given CR_POWER2_ALIGNED is an CPU-related
34582caffb6aSKemeng Shi 	 * optimization we shouldn't try to load too many groups, at some point
34592caffb6aSKemeng Shi 	 * we should start to use what we've got in memory.
3460cfd73237SAlex Zhuravlev 	 * with an average random access time 5ms, it'd take a second to get
3461cfd73237SAlex Zhuravlev 	 * 200 groups (* N with flex_bg), so let's make this limit 4
3462cfd73237SAlex Zhuravlev 	 */
3463cfd73237SAlex Zhuravlev 	sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
3464cfd73237SAlex Zhuravlev 	if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
3465cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
3466cfd73237SAlex Zhuravlev 
3467c9de560dSAlex Tomas 	return 0;
3468c9de560dSAlex Tomas 
3469c9de560dSAlex Tomas err_freebuddy:
3470fb1813f4SCurt Wohlgemuth 	cachep = get_groupinfo_cache(sb->s_blocksize_bits);
34715354b2afSTheodore Ts'o 	while (i-- > 0) {
34725354b2afSTheodore Ts'o 		struct ext4_group_info *grp = ext4_get_group_info(sb, i);
34735354b2afSTheodore Ts'o 
34745354b2afSTheodore Ts'o 		if (grp)
34755354b2afSTheodore Ts'o 			kmem_cache_free(cachep, grp);
34765354b2afSTheodore Ts'o 	}
347728623c2fSTheodore Ts'o 	i = sbi->s_group_info_size;
3478df3da4eaSSuraj Jitindar Singh 	rcu_read_lock();
3479df3da4eaSSuraj Jitindar Singh 	group_info = rcu_dereference(sbi->s_group_info);
3480f1fa3342SRoel Kluin 	while (i-- > 0)
3481df3da4eaSSuraj Jitindar Singh 		kfree(group_info[i]);
3482df3da4eaSSuraj Jitindar Singh 	rcu_read_unlock();
3483c9de560dSAlex Tomas 	iput(sbi->s_buddy_cache);
3484c9de560dSAlex Tomas err_freesgi:
3485df3da4eaSSuraj Jitindar Singh 	rcu_read_lock();
3486df3da4eaSSuraj Jitindar Singh 	kvfree(rcu_dereference(sbi->s_group_info));
3487df3da4eaSSuraj Jitindar Singh 	rcu_read_unlock();
3488c9de560dSAlex Tomas 	return -ENOMEM;
3489c9de560dSAlex Tomas }
3490c9de560dSAlex Tomas 
34912892c15dSEric Sandeen static void ext4_groupinfo_destroy_slabs(void)
34922892c15dSEric Sandeen {
34932892c15dSEric Sandeen 	int i;
34942892c15dSEric Sandeen 
34952892c15dSEric Sandeen 	for (i = 0; i < NR_GRPINFO_CACHES; i++) {
34962892c15dSEric Sandeen 		kmem_cache_destroy(ext4_groupinfo_caches[i]);
34972892c15dSEric Sandeen 		ext4_groupinfo_caches[i] = NULL;
34982892c15dSEric Sandeen 	}
34992892c15dSEric Sandeen }
35002892c15dSEric Sandeen 
35012892c15dSEric Sandeen static int ext4_groupinfo_create_slab(size_t size)
35022892c15dSEric Sandeen {
35032892c15dSEric Sandeen 	static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
35042892c15dSEric Sandeen 	int slab_size;
35052892c15dSEric Sandeen 	int blocksize_bits = order_base_2(size);
35062892c15dSEric Sandeen 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
35072892c15dSEric Sandeen 	struct kmem_cache *cachep;
35082892c15dSEric Sandeen 
35092892c15dSEric Sandeen 	if (cache_index >= NR_GRPINFO_CACHES)
35102892c15dSEric Sandeen 		return -EINVAL;
35112892c15dSEric Sandeen 
35122892c15dSEric Sandeen 	if (unlikely(cache_index < 0))
35132892c15dSEric Sandeen 		cache_index = 0;
35142892c15dSEric Sandeen 
35152892c15dSEric Sandeen 	mutex_lock(&ext4_grpinfo_slab_create_mutex);
35162892c15dSEric Sandeen 	if (ext4_groupinfo_caches[cache_index]) {
35172892c15dSEric Sandeen 		mutex_unlock(&ext4_grpinfo_slab_create_mutex);
35182892c15dSEric Sandeen 		return 0;	/* Already created */
35192892c15dSEric Sandeen 	}
35202892c15dSEric Sandeen 
35212892c15dSEric Sandeen 	slab_size = offsetof(struct ext4_group_info,
35222892c15dSEric Sandeen 				bb_counters[blocksize_bits + 2]);
35232892c15dSEric Sandeen 
35242892c15dSEric Sandeen 	cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
35252892c15dSEric Sandeen 					slab_size, 0, SLAB_RECLAIM_ACCOUNT,
35262892c15dSEric Sandeen 					NULL);
35272892c15dSEric Sandeen 
3528823ba01fSTao Ma 	ext4_groupinfo_caches[cache_index] = cachep;
3529823ba01fSTao Ma 
35302892c15dSEric Sandeen 	mutex_unlock(&ext4_grpinfo_slab_create_mutex);
35312892c15dSEric Sandeen 	if (!cachep) {
35329d8b9ec4STheodore Ts'o 		printk(KERN_EMERG
35339d8b9ec4STheodore Ts'o 		       "EXT4-fs: no memory for groupinfo slab cache\n");
35342892c15dSEric Sandeen 		return -ENOMEM;
35352892c15dSEric Sandeen 	}
35362892c15dSEric Sandeen 
35372892c15dSEric Sandeen 	return 0;
35382892c15dSEric Sandeen }
35392892c15dSEric Sandeen 
354055cdd0afSWang Jianchao static void ext4_discard_work(struct work_struct *work)
354155cdd0afSWang Jianchao {
354255cdd0afSWang Jianchao 	struct ext4_sb_info *sbi = container_of(work,
354355cdd0afSWang Jianchao 			struct ext4_sb_info, s_discard_work);
354455cdd0afSWang Jianchao 	struct super_block *sb = sbi->s_sb;
354555cdd0afSWang Jianchao 	struct ext4_free_data *fd, *nfd;
354655cdd0afSWang Jianchao 	struct ext4_buddy e4b;
35470f6bc579SRuan Jinjie 	LIST_HEAD(discard_list);
354855cdd0afSWang Jianchao 	ext4_group_t grp, load_grp;
354955cdd0afSWang Jianchao 	int err = 0;
355055cdd0afSWang Jianchao 
355155cdd0afSWang Jianchao 	spin_lock(&sbi->s_md_lock);
355255cdd0afSWang Jianchao 	list_splice_init(&sbi->s_discard_list, &discard_list);
355355cdd0afSWang Jianchao 	spin_unlock(&sbi->s_md_lock);
355455cdd0afSWang Jianchao 
355555cdd0afSWang Jianchao 	load_grp = UINT_MAX;
355655cdd0afSWang Jianchao 	list_for_each_entry_safe(fd, nfd, &discard_list, efd_list) {
355755cdd0afSWang Jianchao 		/*
35585036ab8dSWang Jianchao 		 * If filesystem is umounting or no memory or suffering
35595036ab8dSWang Jianchao 		 * from no space, give up the discard
356055cdd0afSWang Jianchao 		 */
35615036ab8dSWang Jianchao 		if ((sb->s_flags & SB_ACTIVE) && !err &&
35625036ab8dSWang Jianchao 		    !atomic_read(&sbi->s_retry_alloc_pending)) {
356355cdd0afSWang Jianchao 			grp = fd->efd_group;
356455cdd0afSWang Jianchao 			if (grp != load_grp) {
356555cdd0afSWang Jianchao 				if (load_grp != UINT_MAX)
356655cdd0afSWang Jianchao 					ext4_mb_unload_buddy(&e4b);
356755cdd0afSWang Jianchao 
356855cdd0afSWang Jianchao 				err = ext4_mb_load_buddy(sb, grp, &e4b);
356955cdd0afSWang Jianchao 				if (err) {
357055cdd0afSWang Jianchao 					kmem_cache_free(ext4_free_data_cachep, fd);
357155cdd0afSWang Jianchao 					load_grp = UINT_MAX;
357255cdd0afSWang Jianchao 					continue;
357355cdd0afSWang Jianchao 				} else {
357455cdd0afSWang Jianchao 					load_grp = grp;
357555cdd0afSWang Jianchao 				}
357655cdd0afSWang Jianchao 			}
357755cdd0afSWang Jianchao 
357855cdd0afSWang Jianchao 			ext4_lock_group(sb, grp);
357955cdd0afSWang Jianchao 			ext4_try_to_trim_range(sb, &e4b, fd->efd_start_cluster,
358055cdd0afSWang Jianchao 						fd->efd_start_cluster + fd->efd_count - 1, 1);
358155cdd0afSWang Jianchao 			ext4_unlock_group(sb, grp);
358255cdd0afSWang Jianchao 		}
358355cdd0afSWang Jianchao 		kmem_cache_free(ext4_free_data_cachep, fd);
358455cdd0afSWang Jianchao 	}
358555cdd0afSWang Jianchao 
358655cdd0afSWang Jianchao 	if (load_grp != UINT_MAX)
358755cdd0afSWang Jianchao 		ext4_mb_unload_buddy(&e4b);
358855cdd0afSWang Jianchao }
358955cdd0afSWang Jianchao 
35909d99012fSAkira Fujita int ext4_mb_init(struct super_block *sb)
3591c9de560dSAlex Tomas {
3592c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
35936be2ded1SAneesh Kumar K.V 	unsigned i, j;
3594935244cdSNicolai Stange 	unsigned offset, offset_incr;
3595c9de560dSAlex Tomas 	unsigned max;
359674767c5aSShen Feng 	int ret;
3597c9de560dSAlex Tomas 
35984b68f6dfSHarshad Shirwadkar 	i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_offsets);
3599c9de560dSAlex Tomas 
3600c9de560dSAlex Tomas 	sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
3601c9de560dSAlex Tomas 	if (sbi->s_mb_offsets == NULL) {
3602fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
3603fb1813f4SCurt Wohlgemuth 		goto out;
3604c9de560dSAlex Tomas 	}
3605ff7ef329SYasunori Goto 
36064b68f6dfSHarshad Shirwadkar 	i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_maxs);
3607c9de560dSAlex Tomas 	sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
3608c9de560dSAlex Tomas 	if (sbi->s_mb_maxs == NULL) {
3609fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
3610fb1813f4SCurt Wohlgemuth 		goto out;
3611fb1813f4SCurt Wohlgemuth 	}
3612fb1813f4SCurt Wohlgemuth 
36132892c15dSEric Sandeen 	ret = ext4_groupinfo_create_slab(sb->s_blocksize);
36142892c15dSEric Sandeen 	if (ret < 0)
3615fb1813f4SCurt Wohlgemuth 		goto out;
3616c9de560dSAlex Tomas 
3617c9de560dSAlex Tomas 	/* order 0 is regular bitmap */
3618c9de560dSAlex Tomas 	sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
3619c9de560dSAlex Tomas 	sbi->s_mb_offsets[0] = 0;
3620c9de560dSAlex Tomas 
3621c9de560dSAlex Tomas 	i = 1;
3622c9de560dSAlex Tomas 	offset = 0;
3623935244cdSNicolai Stange 	offset_incr = 1 << (sb->s_blocksize_bits - 1);
3624c9de560dSAlex Tomas 	max = sb->s_blocksize << 2;
3625c9de560dSAlex Tomas 	do {
3626c9de560dSAlex Tomas 		sbi->s_mb_offsets[i] = offset;
3627c9de560dSAlex Tomas 		sbi->s_mb_maxs[i] = max;
3628935244cdSNicolai Stange 		offset += offset_incr;
3629935244cdSNicolai Stange 		offset_incr = offset_incr >> 1;
3630c9de560dSAlex Tomas 		max = max >> 1;
3631c9de560dSAlex Tomas 		i++;
36324b68f6dfSHarshad Shirwadkar 	} while (i < MB_NUM_ORDERS(sb));
36334b68f6dfSHarshad Shirwadkar 
363483e80a6eSJan Kara 	sbi->s_mb_avg_fragment_size =
363583e80a6eSJan Kara 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
363683e80a6eSJan Kara 			GFP_KERNEL);
363783e80a6eSJan Kara 	if (!sbi->s_mb_avg_fragment_size) {
363883e80a6eSJan Kara 		ret = -ENOMEM;
363983e80a6eSJan Kara 		goto out;
364083e80a6eSJan Kara 	}
364183e80a6eSJan Kara 	sbi->s_mb_avg_fragment_size_locks =
364283e80a6eSJan Kara 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
364383e80a6eSJan Kara 			GFP_KERNEL);
364483e80a6eSJan Kara 	if (!sbi->s_mb_avg_fragment_size_locks) {
364583e80a6eSJan Kara 		ret = -ENOMEM;
364683e80a6eSJan Kara 		goto out;
364783e80a6eSJan Kara 	}
364883e80a6eSJan Kara 	for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
364983e80a6eSJan Kara 		INIT_LIST_HEAD(&sbi->s_mb_avg_fragment_size[i]);
365083e80a6eSJan Kara 		rwlock_init(&sbi->s_mb_avg_fragment_size_locks[i]);
365183e80a6eSJan Kara 	}
3652196e402aSHarshad Shirwadkar 	sbi->s_mb_largest_free_orders =
3653196e402aSHarshad Shirwadkar 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3654196e402aSHarshad Shirwadkar 			GFP_KERNEL);
3655196e402aSHarshad Shirwadkar 	if (!sbi->s_mb_largest_free_orders) {
3656196e402aSHarshad Shirwadkar 		ret = -ENOMEM;
3657196e402aSHarshad Shirwadkar 		goto out;
3658196e402aSHarshad Shirwadkar 	}
3659196e402aSHarshad Shirwadkar 	sbi->s_mb_largest_free_orders_locks =
3660196e402aSHarshad Shirwadkar 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3661196e402aSHarshad Shirwadkar 			GFP_KERNEL);
3662196e402aSHarshad Shirwadkar 	if (!sbi->s_mb_largest_free_orders_locks) {
3663196e402aSHarshad Shirwadkar 		ret = -ENOMEM;
3664196e402aSHarshad Shirwadkar 		goto out;
3665196e402aSHarshad Shirwadkar 	}
3666196e402aSHarshad Shirwadkar 	for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3667196e402aSHarshad Shirwadkar 		INIT_LIST_HEAD(&sbi->s_mb_largest_free_orders[i]);
3668196e402aSHarshad Shirwadkar 		rwlock_init(&sbi->s_mb_largest_free_orders_locks[i]);
3669196e402aSHarshad Shirwadkar 	}
3670c9de560dSAlex Tomas 
3671c9de560dSAlex Tomas 	spin_lock_init(&sbi->s_md_lock);
3672d08854f5STheodore Ts'o 	sbi->s_mb_free_pending = 0;
3673ce774e53SJinke Han 	INIT_LIST_HEAD(&sbi->s_freed_data_list[0]);
3674ce774e53SJinke Han 	INIT_LIST_HEAD(&sbi->s_freed_data_list[1]);
367555cdd0afSWang Jianchao 	INIT_LIST_HEAD(&sbi->s_discard_list);
367655cdd0afSWang Jianchao 	INIT_WORK(&sbi->s_discard_work, ext4_discard_work);
36775036ab8dSWang Jianchao 	atomic_set(&sbi->s_retry_alloc_pending, 0);
3678c9de560dSAlex Tomas 
3679c9de560dSAlex Tomas 	sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
3680c9de560dSAlex Tomas 	sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
3681c9de560dSAlex Tomas 	sbi->s_mb_stats = MB_DEFAULT_STATS;
3682c9de560dSAlex Tomas 	sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
3683c9de560dSAlex Tomas 	sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
3684f52f3d2bSOjaswin Mujoo 	sbi->s_mb_best_avail_max_trim_order = MB_DEFAULT_BEST_AVAIL_TRIM_ORDER;
36857e170922SOjaswin Mujoo 
368627baebb8STheodore Ts'o 	/*
368727baebb8STheodore Ts'o 	 * The default group preallocation is 512, which for 4k block
368827baebb8STheodore Ts'o 	 * sizes translates to 2 megabytes.  However for bigalloc file
368927baebb8STheodore Ts'o 	 * systems, this is probably too big (i.e, if the cluster size
369027baebb8STheodore Ts'o 	 * is 1 megabyte, then group preallocation size becomes half a
369127baebb8STheodore Ts'o 	 * gigabyte!).  As a default, we will keep a two megabyte
369227baebb8STheodore Ts'o 	 * group pralloc size for cluster sizes up to 64k, and after
369327baebb8STheodore Ts'o 	 * that, we will force a minimum group preallocation size of
369427baebb8STheodore Ts'o 	 * 32 clusters.  This translates to 8 megs when the cluster
369527baebb8STheodore Ts'o 	 * size is 256k, and 32 megs when the cluster size is 1 meg,
369627baebb8STheodore Ts'o 	 * which seems reasonable as a default.
369727baebb8STheodore Ts'o 	 */
369827baebb8STheodore Ts'o 	sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
369927baebb8STheodore Ts'o 				       sbi->s_cluster_bits, 32);
3700d7a1fee1SDan Ehrenberg 	/*
3701d7a1fee1SDan Ehrenberg 	 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
3702d7a1fee1SDan Ehrenberg 	 * to the lowest multiple of s_stripe which is bigger than
3703d7a1fee1SDan Ehrenberg 	 * the s_mb_group_prealloc as determined above. We want
3704d7a1fee1SDan Ehrenberg 	 * the preallocation size to be an exact multiple of the
3705d7a1fee1SDan Ehrenberg 	 * RAID stripe size so that preallocations don't fragment
3706d7a1fee1SDan Ehrenberg 	 * the stripes.
3707d7a1fee1SDan Ehrenberg 	 */
3708d7a1fee1SDan Ehrenberg 	if (sbi->s_stripe > 1) {
3709d7a1fee1SDan Ehrenberg 		sbi->s_mb_group_prealloc = roundup(
3710c3defd99SKemeng Shi 			sbi->s_mb_group_prealloc, EXT4_B2C(sbi, sbi->s_stripe));
3711d7a1fee1SDan Ehrenberg 	}
3712c9de560dSAlex Tomas 
3713730c213cSEric Sandeen 	sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
3714c9de560dSAlex Tomas 	if (sbi->s_locality_groups == NULL) {
3715fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
3716029b10c5SAndrey Tsyvarev 		goto out;
3717c9de560dSAlex Tomas 	}
3718730c213cSEric Sandeen 	for_each_possible_cpu(i) {
3719c9de560dSAlex Tomas 		struct ext4_locality_group *lg;
3720730c213cSEric Sandeen 		lg = per_cpu_ptr(sbi->s_locality_groups, i);
3721c9de560dSAlex Tomas 		mutex_init(&lg->lg_mutex);
37226be2ded1SAneesh Kumar K.V 		for (j = 0; j < PREALLOC_TB_SIZE; j++)
37236be2ded1SAneesh Kumar K.V 			INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
3724c9de560dSAlex Tomas 		spin_lock_init(&lg->lg_prealloc_lock);
3725c9de560dSAlex Tomas 	}
3726c9de560dSAlex Tomas 
372710f0d2a5SChristoph Hellwig 	if (bdev_nonrot(sb->s_bdev))
3728196e402aSHarshad Shirwadkar 		sbi->s_mb_max_linear_groups = 0;
3729196e402aSHarshad Shirwadkar 	else
3730196e402aSHarshad Shirwadkar 		sbi->s_mb_max_linear_groups = MB_DEFAULT_LINEAR_LIMIT;
373179a77c5aSYu Jian 	/* init file for buddy data */
373279a77c5aSYu Jian 	ret = ext4_mb_init_backend(sb);
37337aa0baeaSTao Ma 	if (ret != 0)
37347aa0baeaSTao Ma 		goto out_free_locality_groups;
373579a77c5aSYu Jian 
37367aa0baeaSTao Ma 	return 0;
37377aa0baeaSTao Ma 
37387aa0baeaSTao Ma out_free_locality_groups:
37397aa0baeaSTao Ma 	free_percpu(sbi->s_locality_groups);
37407aa0baeaSTao Ma 	sbi->s_locality_groups = NULL;
3741fb1813f4SCurt Wohlgemuth out:
374283e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size);
374383e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size_locks);
3744196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders);
3745196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders_locks);
3746fb1813f4SCurt Wohlgemuth 	kfree(sbi->s_mb_offsets);
37477aa0baeaSTao Ma 	sbi->s_mb_offsets = NULL;
3748fb1813f4SCurt Wohlgemuth 	kfree(sbi->s_mb_maxs);
37497aa0baeaSTao Ma 	sbi->s_mb_maxs = NULL;
3750fb1813f4SCurt Wohlgemuth 	return ret;
3751c9de560dSAlex Tomas }
3752c9de560dSAlex Tomas 
3753955ce5f5SAneesh Kumar K.V /* need to called with the ext4 group lock held */
3754d3df1453SRitesh Harjani static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
3755c9de560dSAlex Tomas {
3756c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3757c9de560dSAlex Tomas 	struct list_head *cur, *tmp;
3758c9de560dSAlex Tomas 	int count = 0;
3759c9de560dSAlex Tomas 
3760c9de560dSAlex Tomas 	list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
3761c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3762c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
3763c9de560dSAlex Tomas 		count++;
3764688f05a0SAneesh Kumar K.V 		kmem_cache_free(ext4_pspace_cachep, pa);
3765c9de560dSAlex Tomas 	}
3766d3df1453SRitesh Harjani 	return count;
3767c9de560dSAlex Tomas }
3768c9de560dSAlex Tomas 
376990817717SKemeng Shi void ext4_mb_release(struct super_block *sb)
3770c9de560dSAlex Tomas {
37718df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
3772c9de560dSAlex Tomas 	ext4_group_t i;
3773c9de560dSAlex Tomas 	int num_meta_group_infos;
3774df3da4eaSSuraj Jitindar Singh 	struct ext4_group_info *grinfo, ***group_info;
3775c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3776fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3777d3df1453SRitesh Harjani 	int count;
3778c9de560dSAlex Tomas 
377955cdd0afSWang Jianchao 	if (test_opt(sb, DISCARD)) {
378055cdd0afSWang Jianchao 		/*
378155cdd0afSWang Jianchao 		 * wait the discard work to drain all of ext4_free_data
378255cdd0afSWang Jianchao 		 */
378355cdd0afSWang Jianchao 		flush_work(&sbi->s_discard_work);
378455cdd0afSWang Jianchao 		WARN_ON_ONCE(!list_empty(&sbi->s_discard_list));
378555cdd0afSWang Jianchao 	}
378655cdd0afSWang Jianchao 
3787c9de560dSAlex Tomas 	if (sbi->s_group_info) {
37888df9675fSTheodore Ts'o 		for (i = 0; i < ngroups; i++) {
37894b99faa2SKhazhismel Kumykov 			cond_resched();
3790c9de560dSAlex Tomas 			grinfo = ext4_get_group_info(sb, i);
37915354b2afSTheodore Ts'o 			if (!grinfo)
37925354b2afSTheodore Ts'o 				continue;
3793a3450215SRitesh Harjani 			mb_group_bb_bitmap_free(grinfo);
3794c9de560dSAlex Tomas 			ext4_lock_group(sb, i);
3795d3df1453SRitesh Harjani 			count = ext4_mb_cleanup_pa(grinfo);
3796d3df1453SRitesh Harjani 			if (count)
3797d3df1453SRitesh Harjani 				mb_debug(sb, "mballoc: %d PAs left\n",
3798d3df1453SRitesh Harjani 					 count);
3799c9de560dSAlex Tomas 			ext4_unlock_group(sb, i);
3800fb1813f4SCurt Wohlgemuth 			kmem_cache_free(cachep, grinfo);
3801c9de560dSAlex Tomas 		}
38028df9675fSTheodore Ts'o 		num_meta_group_infos = (ngroups +
3803c9de560dSAlex Tomas 				EXT4_DESC_PER_BLOCK(sb) - 1) >>
3804c9de560dSAlex Tomas 			EXT4_DESC_PER_BLOCK_BITS(sb);
3805df3da4eaSSuraj Jitindar Singh 		rcu_read_lock();
3806df3da4eaSSuraj Jitindar Singh 		group_info = rcu_dereference(sbi->s_group_info);
3807c9de560dSAlex Tomas 		for (i = 0; i < num_meta_group_infos; i++)
3808df3da4eaSSuraj Jitindar Singh 			kfree(group_info[i]);
3809df3da4eaSSuraj Jitindar Singh 		kvfree(group_info);
3810df3da4eaSSuraj Jitindar Singh 		rcu_read_unlock();
3811c9de560dSAlex Tomas 	}
381283e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size);
381383e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size_locks);
3814196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders);
3815196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders_locks);
3816c9de560dSAlex Tomas 	kfree(sbi->s_mb_offsets);
3817c9de560dSAlex Tomas 	kfree(sbi->s_mb_maxs);
3818c9de560dSAlex Tomas 	iput(sbi->s_buddy_cache);
3819c9de560dSAlex Tomas 	if (sbi->s_mb_stats) {
38209d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
38219d8b9ec4STheodore Ts'o 		       "mballoc: %u blocks %u reqs (%u success)",
3822c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_allocated),
3823c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_reqs),
3824c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_success));
38259d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
3826a6c75eafSHarshad Shirwadkar 		      "mballoc: %u extents scanned, %u groups scanned, %u goal hits, "
38279d8b9ec4STheodore Ts'o 				"%u 2^N hits, %u breaks, %u lost",
3828c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_ex_scanned),
3829a6c75eafSHarshad Shirwadkar 				atomic_read(&sbi->s_bal_groups_scanned),
3830c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_goals),
3831c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_2orders),
3832c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_breaks),
3833c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_lost_chunks));
38349d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
383567d25186SHarshad Shirwadkar 		       "mballoc: %u generated and it took %llu",
383667d25186SHarshad Shirwadkar 				atomic_read(&sbi->s_mb_buddies_generated),
383767d25186SHarshad Shirwadkar 				atomic64_read(&sbi->s_mb_generation_time));
38389d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
38399d8b9ec4STheodore Ts'o 		       "mballoc: %u preallocated, %u discarded",
3840c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_preallocated),
3841c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_discarded));
3842c9de560dSAlex Tomas 	}
3843c9de560dSAlex Tomas 
3844730c213cSEric Sandeen 	free_percpu(sbi->s_locality_groups);
3845c9de560dSAlex Tomas }
3846c9de560dSAlex Tomas 
384777ca6cdfSLukas Czerner static inline int ext4_issue_discard(struct super_block *sb,
38480efcd739SWenchao Hao 		ext4_group_t block_group, ext4_grpblk_t cluster, int count)
38495c521830SJiaying Zhang {
38505c521830SJiaying Zhang 	ext4_fsblk_t discard_block;
38515c521830SJiaying Zhang 
385284130193STheodore Ts'o 	discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
385384130193STheodore Ts'o 			 ext4_group_first_block_no(sb, block_group));
385484130193STheodore Ts'o 	count = EXT4_C2B(EXT4_SB(sb), count);
38555c521830SJiaying Zhang 	trace_ext4_discard_blocks(sb,
38565c521830SJiaying Zhang 			(unsigned long long) discard_block, count);
38570efcd739SWenchao Hao 
385893259636SLukas Czerner 	return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
38595c521830SJiaying Zhang }
38605c521830SJiaying Zhang 
3861a0154344SDaeho Jeong static void ext4_free_data_in_buddy(struct super_block *sb,
3862a0154344SDaeho Jeong 				    struct ext4_free_data *entry)
3863c9de560dSAlex Tomas {
3864c9de560dSAlex Tomas 	struct ext4_buddy e4b;
3865c894058dSAneesh Kumar K.V 	struct ext4_group_info *db;
3866c7f2bafaSKemeng Shi 	int err, count = 0;
3867c9de560dSAlex Tomas 
3868d3df1453SRitesh Harjani 	mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
386918aadd47SBobi Jam 		 entry->efd_count, entry->efd_group, entry);
3870c9de560dSAlex Tomas 
387118aadd47SBobi Jam 	err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
3872c9de560dSAlex Tomas 	/* we expect to find existing buddy because it's pinned */
3873c9de560dSAlex Tomas 	BUG_ON(err != 0);
3874c9de560dSAlex Tomas 
3875d08854f5STheodore Ts'o 	spin_lock(&EXT4_SB(sb)->s_md_lock);
3876d08854f5STheodore Ts'o 	EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
3877d08854f5STheodore Ts'o 	spin_unlock(&EXT4_SB(sb)->s_md_lock);
387818aadd47SBobi Jam 
3879c894058dSAneesh Kumar K.V 	db = e4b.bd_info;
3880c9de560dSAlex Tomas 	/* there are blocks to put in buddy to make them really free */
388118aadd47SBobi Jam 	count += entry->efd_count;
388218aadd47SBobi Jam 	ext4_lock_group(sb, entry->efd_group);
3883c894058dSAneesh Kumar K.V 	/* Take it out of per group rb tree */
388418aadd47SBobi Jam 	rb_erase(&entry->efd_node, &(db->bb_free_root));
388518aadd47SBobi Jam 	mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
3886c9de560dSAlex Tomas 
38873d56b8d2STao Ma 	/*
38883d56b8d2STao Ma 	 * Clear the trimmed flag for the group so that the next
38893d56b8d2STao Ma 	 * ext4_trim_fs can trim it.
38903d56b8d2STao Ma 	 * If the volume is mounted with -o discard, online discard
38913d56b8d2STao Ma 	 * is supported and the free blocks will be trimmed online.
38923d56b8d2STao Ma 	 */
38933d56b8d2STao Ma 	if (!test_opt(sb, DISCARD))
38943d56b8d2STao Ma 		EXT4_MB_GRP_CLEAR_TRIMMED(db);
38953d56b8d2STao Ma 
3896c894058dSAneesh Kumar K.V 	if (!db->bb_free_root.rb_node) {
3897c894058dSAneesh Kumar K.V 		/* No more items in the per group rb tree
3898c894058dSAneesh Kumar K.V 		 * balance refcounts from ext4_mb_free_metadata()
3899c894058dSAneesh Kumar K.V 		 */
39005eea586bSMatthew Wilcox (Oracle) 		folio_put(e4b.bd_buddy_folio);
390199b150d8SMatthew Wilcox (Oracle) 		folio_put(e4b.bd_bitmap_folio);
3902c894058dSAneesh Kumar K.V 	}
390318aadd47SBobi Jam 	ext4_unlock_group(sb, entry->efd_group);
3904e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
3905c9de560dSAlex Tomas 
3906c7f2bafaSKemeng Shi 	mb_debug(sb, "freed %d blocks in 1 structures\n", count);
3907c9de560dSAlex Tomas }
3908c9de560dSAlex Tomas 
3909a0154344SDaeho Jeong /*
3910a0154344SDaeho Jeong  * This function is called by the jbd2 layer once the commit has finished,
3911a0154344SDaeho Jeong  * so we know we can free the blocks that were released with that commit.
3912a0154344SDaeho Jeong  */
3913a0154344SDaeho Jeong void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
3914a0154344SDaeho Jeong {
3915a0154344SDaeho Jeong 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3916a0154344SDaeho Jeong 	struct ext4_free_data *entry, *tmp;
39170f6bc579SRuan Jinjie 	LIST_HEAD(freed_data_list);
3918ce774e53SJinke Han 	struct list_head *s_freed_head = &sbi->s_freed_data_list[commit_tid & 1];
391955cdd0afSWang Jianchao 	bool wake;
3920a0154344SDaeho Jeong 
3921ce774e53SJinke Han 	list_replace_init(s_freed_head, &freed_data_list);
3922a0154344SDaeho Jeong 
392355cdd0afSWang Jianchao 	list_for_each_entry(entry, &freed_data_list, efd_list)
3924a0154344SDaeho Jeong 		ext4_free_data_in_buddy(sb, entry);
392555cdd0afSWang Jianchao 
392655cdd0afSWang Jianchao 	if (test_opt(sb, DISCARD)) {
392755cdd0afSWang Jianchao 		spin_lock(&sbi->s_md_lock);
392855cdd0afSWang Jianchao 		wake = list_empty(&sbi->s_discard_list);
392955cdd0afSWang Jianchao 		list_splice_tail(&freed_data_list, &sbi->s_discard_list);
393055cdd0afSWang Jianchao 		spin_unlock(&sbi->s_md_lock);
393155cdd0afSWang Jianchao 		if (wake)
393255cdd0afSWang Jianchao 			queue_work(system_unbound_wq, &sbi->s_discard_work);
393355cdd0afSWang Jianchao 	} else {
393455cdd0afSWang Jianchao 		list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
393555cdd0afSWang Jianchao 			kmem_cache_free(ext4_free_data_cachep, entry);
393655cdd0afSWang Jianchao 	}
3937a0154344SDaeho Jeong }
3938a0154344SDaeho Jeong 
39395dabfc78STheodore Ts'o int __init ext4_init_mballoc(void)
3940c9de560dSAlex Tomas {
394116828088STheodore Ts'o 	ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
394216828088STheodore Ts'o 					SLAB_RECLAIM_ACCOUNT);
3943c9de560dSAlex Tomas 	if (ext4_pspace_cachep == NULL)
3944f283529aSRitesh Harjani 		goto out;
3945c9de560dSAlex Tomas 
394616828088STheodore Ts'o 	ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
394716828088STheodore Ts'o 				    SLAB_RECLAIM_ACCOUNT);
3948f283529aSRitesh Harjani 	if (ext4_ac_cachep == NULL)
3949f283529aSRitesh Harjani 		goto out_pa_free;
3950c894058dSAneesh Kumar K.V 
395118aadd47SBobi Jam 	ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
395216828088STheodore Ts'o 					   SLAB_RECLAIM_ACCOUNT);
3953f283529aSRitesh Harjani 	if (ext4_free_data_cachep == NULL)
3954f283529aSRitesh Harjani 		goto out_ac_free;
3955f283529aSRitesh Harjani 
3956c9de560dSAlex Tomas 	return 0;
3957f283529aSRitesh Harjani 
3958f283529aSRitesh Harjani out_ac_free:
3959f283529aSRitesh Harjani 	kmem_cache_destroy(ext4_ac_cachep);
3960f283529aSRitesh Harjani out_pa_free:
3961f283529aSRitesh Harjani 	kmem_cache_destroy(ext4_pspace_cachep);
3962f283529aSRitesh Harjani out:
3963f283529aSRitesh Harjani 	return -ENOMEM;
3964c9de560dSAlex Tomas }
3965c9de560dSAlex Tomas 
39665dabfc78STheodore Ts'o void ext4_exit_mballoc(void)
3967c9de560dSAlex Tomas {
39683e03f9caSJesper Dangaard Brouer 	/*
39693e03f9caSJesper Dangaard Brouer 	 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
39703e03f9caSJesper Dangaard Brouer 	 * before destroying the slab cache.
39713e03f9caSJesper Dangaard Brouer 	 */
39723e03f9caSJesper Dangaard Brouer 	rcu_barrier();
3973c9de560dSAlex Tomas 	kmem_cache_destroy(ext4_pspace_cachep);
3974256bdb49SEric Sandeen 	kmem_cache_destroy(ext4_ac_cachep);
397518aadd47SBobi Jam 	kmem_cache_destroy(ext4_free_data_cachep);
39762892c15dSEric Sandeen 	ext4_groupinfo_destroy_slabs();
3977c9de560dSAlex Tomas }
3978c9de560dSAlex Tomas 
3979c431d386SKemeng Shi #define EXT4_MB_BITMAP_MARKED_CHECK 0x0001
3980c431d386SKemeng Shi #define EXT4_MB_SYNC_UPDATE 0x0002
3981f9e2d95aSKemeng Shi static int
3982c431d386SKemeng Shi ext4_mb_mark_context(handle_t *handle, struct super_block *sb, bool state,
3983c431d386SKemeng Shi 		     ext4_group_t group, ext4_grpblk_t blkoff,
3984c431d386SKemeng Shi 		     ext4_grpblk_t len, int flags, ext4_grpblk_t *ret_changed)
3985f9e2d95aSKemeng Shi {
3986f9e2d95aSKemeng Shi 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3987f9e2d95aSKemeng Shi 	struct buffer_head *bitmap_bh = NULL;
3988f9e2d95aSKemeng Shi 	struct ext4_group_desc *gdp;
3989f9e2d95aSKemeng Shi 	struct buffer_head *gdp_bh;
3990f9e2d95aSKemeng Shi 	int err;
3991c431d386SKemeng Shi 	unsigned int i, already, changed = len;
3992f9e2d95aSKemeng Shi 
3993bdefd689SKemeng Shi 	KUNIT_STATIC_STUB_REDIRECT(ext4_mb_mark_context,
3994bdefd689SKemeng Shi 				   handle, sb, state, group, blkoff, len,
3995bdefd689SKemeng Shi 				   flags, ret_changed);
3996bdefd689SKemeng Shi 
3997c431d386SKemeng Shi 	if (ret_changed)
3998c431d386SKemeng Shi 		*ret_changed = 0;
3999f9e2d95aSKemeng Shi 	bitmap_bh = ext4_read_block_bitmap(sb, group);
4000f9e2d95aSKemeng Shi 	if (IS_ERR(bitmap_bh))
4001f9e2d95aSKemeng Shi 		return PTR_ERR(bitmap_bh);
4002f9e2d95aSKemeng Shi 
4003c431d386SKemeng Shi 	if (handle) {
4004c431d386SKemeng Shi 		BUFFER_TRACE(bitmap_bh, "getting write access");
4005c431d386SKemeng Shi 		err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
4006c431d386SKemeng Shi 						    EXT4_JTR_NONE);
4007c431d386SKemeng Shi 		if (err)
4008c431d386SKemeng Shi 			goto out_err;
4009c431d386SKemeng Shi 	}
4010c431d386SKemeng Shi 
4011f9e2d95aSKemeng Shi 	err = -EIO;
4012f9e2d95aSKemeng Shi 	gdp = ext4_get_group_desc(sb, group, &gdp_bh);
4013f9e2d95aSKemeng Shi 	if (!gdp)
4014f9e2d95aSKemeng Shi 		goto out_err;
4015f9e2d95aSKemeng Shi 
4016c431d386SKemeng Shi 	if (handle) {
4017c431d386SKemeng Shi 		BUFFER_TRACE(gdp_bh, "get_write_access");
4018c431d386SKemeng Shi 		err = ext4_journal_get_write_access(handle, sb, gdp_bh,
4019c431d386SKemeng Shi 						    EXT4_JTR_NONE);
4020c431d386SKemeng Shi 		if (err)
4021c431d386SKemeng Shi 			goto out_err;
4022c431d386SKemeng Shi 	}
4023c431d386SKemeng Shi 
4024f9e2d95aSKemeng Shi 	ext4_lock_group(sb, group);
4025f9e2d95aSKemeng Shi 	if (ext4_has_group_desc_csum(sb) &&
4026f9e2d95aSKemeng Shi 	    (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
4027f9e2d95aSKemeng Shi 		gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
4028f9e2d95aSKemeng Shi 		ext4_free_group_clusters_set(sb, gdp,
4029f9e2d95aSKemeng Shi 			ext4_free_clusters_after_init(sb, group, gdp));
4030f9e2d95aSKemeng Shi 	}
4031f9e2d95aSKemeng Shi 
4032c431d386SKemeng Shi 	if (flags & EXT4_MB_BITMAP_MARKED_CHECK) {
4033f9e2d95aSKemeng Shi 		already = 0;
4034f9e2d95aSKemeng Shi 		for (i = 0; i < len; i++)
4035f9e2d95aSKemeng Shi 			if (mb_test_bit(blkoff + i, bitmap_bh->b_data) ==
4036f9e2d95aSKemeng Shi 					state)
4037f9e2d95aSKemeng Shi 				already++;
4038f9e2d95aSKemeng Shi 		changed = len - already;
4039c431d386SKemeng Shi 	}
4040f9e2d95aSKemeng Shi 
4041f9e2d95aSKemeng Shi 	if (state) {
4042f9e2d95aSKemeng Shi 		mb_set_bits(bitmap_bh->b_data, blkoff, len);
4043f9e2d95aSKemeng Shi 		ext4_free_group_clusters_set(sb, gdp,
4044f9e2d95aSKemeng Shi 			ext4_free_group_clusters(sb, gdp) - changed);
4045f9e2d95aSKemeng Shi 	} else {
4046f9e2d95aSKemeng Shi 		mb_clear_bits(bitmap_bh->b_data, blkoff, len);
4047f9e2d95aSKemeng Shi 		ext4_free_group_clusters_set(sb, gdp,
4048f9e2d95aSKemeng Shi 			ext4_free_group_clusters(sb, gdp) + changed);
4049f9e2d95aSKemeng Shi 	}
4050f9e2d95aSKemeng Shi 
4051f9e2d95aSKemeng Shi 	ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
4052f9e2d95aSKemeng Shi 	ext4_group_desc_csum_set(sb, group, gdp);
4053f9e2d95aSKemeng Shi 	ext4_unlock_group(sb, group);
4054c431d386SKemeng Shi 	if (ret_changed)
4055c431d386SKemeng Shi 		*ret_changed = changed;
4056f9e2d95aSKemeng Shi 
4057f9e2d95aSKemeng Shi 	if (sbi->s_log_groups_per_flex) {
4058f9e2d95aSKemeng Shi 		ext4_group_t flex_group = ext4_flex_group(sbi, group);
4059f9e2d95aSKemeng Shi 		struct flex_groups *fg = sbi_array_rcu_deref(sbi,
4060f9e2d95aSKemeng Shi 					   s_flex_groups, flex_group);
4061f9e2d95aSKemeng Shi 
4062f9e2d95aSKemeng Shi 		if (state)
4063f9e2d95aSKemeng Shi 			atomic64_sub(changed, &fg->free_clusters);
4064f9e2d95aSKemeng Shi 		else
4065f9e2d95aSKemeng Shi 			atomic64_add(changed, &fg->free_clusters);
4066f9e2d95aSKemeng Shi 	}
4067f9e2d95aSKemeng Shi 
4068c431d386SKemeng Shi 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4069f9e2d95aSKemeng Shi 	if (err)
4070f9e2d95aSKemeng Shi 		goto out_err;
4071c431d386SKemeng Shi 	err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
4072f9e2d95aSKemeng Shi 	if (err)
4073f9e2d95aSKemeng Shi 		goto out_err;
4074f9e2d95aSKemeng Shi 
4075c431d386SKemeng Shi 	if (flags & EXT4_MB_SYNC_UPDATE) {
4076f9e2d95aSKemeng Shi 		sync_dirty_buffer(bitmap_bh);
4077f9e2d95aSKemeng Shi 		sync_dirty_buffer(gdp_bh);
4078c431d386SKemeng Shi 	}
4079f9e2d95aSKemeng Shi 
4080f9e2d95aSKemeng Shi out_err:
4081f9e2d95aSKemeng Shi 	brelse(bitmap_bh);
4082f9e2d95aSKemeng Shi 	return err;
4083f9e2d95aSKemeng Shi }
4084c9de560dSAlex Tomas 
4085c9de560dSAlex Tomas /*
408673b2c716SUwe Kleine-König  * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
4087c9de560dSAlex Tomas  * Returns 0 if success or error code
4088c9de560dSAlex Tomas  */
40894ddfef7bSEric Sandeen static noinline_for_stack int
40904ddfef7bSEric Sandeen ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
409153accfa9STheodore Ts'o 				handle_t *handle, unsigned int reserv_clstrs)
4092c9de560dSAlex Tomas {
4093c9de560dSAlex Tomas 	struct ext4_group_desc *gdp;
4094c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
4095c9de560dSAlex Tomas 	struct super_block *sb;
4096c9de560dSAlex Tomas 	ext4_fsblk_t block;
4097519deca0SAneesh Kumar K.V 	int err, len;
40982f94711bSKemeng Shi 	int flags = 0;
40992f94711bSKemeng Shi 	ext4_grpblk_t changed;
4100c9de560dSAlex Tomas 
4101c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
4102c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_len <= 0);
4103c9de560dSAlex Tomas 
4104c9de560dSAlex Tomas 	sb = ac->ac_sb;
4105c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
4106c9de560dSAlex Tomas 
41072f94711bSKemeng Shi 	gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, NULL);
4108c9de560dSAlex Tomas 	if (!gdp)
41092f94711bSKemeng Shi 		return -EIO;
4110a9df9a49STheodore Ts'o 	ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
4111021b65bbSTheodore Ts'o 			ext4_free_group_clusters(sb, gdp));
411203cddb80SAneesh Kumar K.V 
4113bda00de7SAkinobu Mita 	block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
411453accfa9STheodore Ts'o 	len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4115ce9f24ccSJan Kara 	if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
411612062dddSEric Sandeen 		ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
41171084f252STheodore Ts'o 			   "fs metadata", block, block+len);
4118519deca0SAneesh Kumar K.V 		/* File system mounted not to panic on error
4119554a5cccSVegard Nossum 		 * Fix the bitmap and return EFSCORRUPTED
4120519deca0SAneesh Kumar K.V 		 * We leak some of the blocks here.
4121519deca0SAneesh Kumar K.V 		 */
41222f94711bSKemeng Shi 		err = ext4_mb_mark_context(handle, sb, true,
41232f94711bSKemeng Shi 					   ac->ac_b_ex.fe_group,
41242f94711bSKemeng Shi 					   ac->ac_b_ex.fe_start,
41252f94711bSKemeng Shi 					   ac->ac_b_ex.fe_len,
41262f94711bSKemeng Shi 					   0, NULL);
4127519deca0SAneesh Kumar K.V 		if (!err)
4128554a5cccSVegard Nossum 			err = -EFSCORRUPTED;
41292f94711bSKemeng Shi 		return err;
4130c9de560dSAlex Tomas 	}
4131955ce5f5SAneesh Kumar K.V 
4132c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
41332f94711bSKemeng Shi 	flags |= EXT4_MB_BITMAP_MARKED_CHECK;
4134c9de560dSAlex Tomas #endif
41352f94711bSKemeng Shi 	err = ext4_mb_mark_context(handle, sb, true, ac->ac_b_ex.fe_group,
41362f94711bSKemeng Shi 				   ac->ac_b_ex.fe_start, ac->ac_b_ex.fe_len,
41372f94711bSKemeng Shi 				   flags, &changed);
4138955ce5f5SAneesh Kumar K.V 
41392f94711bSKemeng Shi 	if (err && changed == 0)
41402f94711bSKemeng Shi 		return err;
41412f94711bSKemeng Shi 
41422f94711bSKemeng Shi #ifdef AGGRESSIVE_CHECK
41432f94711bSKemeng Shi 	BUG_ON(changed != ac->ac_b_ex.fe_len);
41442f94711bSKemeng Shi #endif
414557042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
4146d2a17637SMingming Cao 	/*
41476bc6e63fSAneesh Kumar K.V 	 * Now reduce the dirty block count also. Should not go negative
4148d2a17637SMingming Cao 	 */
41496bc6e63fSAneesh Kumar K.V 	if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
41506bc6e63fSAneesh Kumar K.V 		/* release all the reserved blocks if non delalloc */
415157042651STheodore Ts'o 		percpu_counter_sub(&sbi->s_dirtyclusters_counter,
415257042651STheodore Ts'o 				   reserv_clstrs);
4153c9de560dSAlex Tomas 
4154c9de560dSAlex Tomas 	return err;
4155c9de560dSAlex Tomas }
4156c9de560dSAlex Tomas 
4157c9de560dSAlex Tomas /*
41588016e29fSHarshad Shirwadkar  * Idempotent helper for Ext4 fast commit replay path to set the state of
41598016e29fSHarshad Shirwadkar  * blocks in bitmaps and update counters.
41608016e29fSHarshad Shirwadkar  */
41618016e29fSHarshad Shirwadkar void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
4162d2f7cf40SKemeng Shi 		     int len, bool state)
41638016e29fSHarshad Shirwadkar {
41648016e29fSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
41658016e29fSHarshad Shirwadkar 	ext4_group_t group;
41668016e29fSHarshad Shirwadkar 	ext4_grpblk_t blkoff;
4167f9e2d95aSKemeng Shi 	int err = 0;
4168f9e2d95aSKemeng Shi 	unsigned int clen, thisgrp_len;
41698016e29fSHarshad Shirwadkar 
4170bfdc502aSRitesh Harjani 	while (len > 0) {
41718016e29fSHarshad Shirwadkar 		ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
4172bfdc502aSRitesh Harjani 
4173bfdc502aSRitesh Harjani 		/*
4174bfdc502aSRitesh Harjani 		 * Check to see if we are freeing blocks across a group
4175bfdc502aSRitesh Harjani 		 * boundary.
4176bfdc502aSRitesh Harjani 		 * In case of flex_bg, this can happen that (block, len) may
4177bfdc502aSRitesh Harjani 		 * span across more than one group. In that case we need to
4178bfdc502aSRitesh Harjani 		 * get the corresponding group metadata to work with.
4179bfdc502aSRitesh Harjani 		 * For this we have goto again loop.
4180bfdc502aSRitesh Harjani 		 */
4181bfdc502aSRitesh Harjani 		thisgrp_len = min_t(unsigned int, (unsigned int)len,
4182bfdc502aSRitesh Harjani 			EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
4183bfdc502aSRitesh Harjani 		clen = EXT4_NUM_B2C(sbi, thisgrp_len);
4184bfdc502aSRitesh Harjani 
41858c91c579SRitesh Harjani 		if (!ext4_sb_block_valid(sb, NULL, block, thisgrp_len)) {
41868c91c579SRitesh Harjani 			ext4_error(sb, "Marking blocks in system zone - "
41878c91c579SRitesh Harjani 				   "Block = %llu, len = %u",
41888c91c579SRitesh Harjani 				   block, thisgrp_len);
41898c91c579SRitesh Harjani 			break;
41908c91c579SRitesh Harjani 		}
41918c91c579SRitesh Harjani 
4192c431d386SKemeng Shi 		err = ext4_mb_mark_context(NULL, sb, state,
4193c431d386SKemeng Shi 					   group, blkoff, clen,
4194c431d386SKemeng Shi 					   EXT4_MB_BITMAP_MARKED_CHECK |
4195c431d386SKemeng Shi 					   EXT4_MB_SYNC_UPDATE,
4196c431d386SKemeng Shi 					   NULL);
4197bfdc502aSRitesh Harjani 		if (err)
4198bfdc502aSRitesh Harjani 			break;
41998016e29fSHarshad Shirwadkar 
4200bfdc502aSRitesh Harjani 		block += thisgrp_len;
4201bfdc502aSRitesh Harjani 		len -= thisgrp_len;
4202bfdc502aSRitesh Harjani 		BUG_ON(len < 0);
4203bfdc502aSRitesh Harjani 	}
42048016e29fSHarshad Shirwadkar }
42058016e29fSHarshad Shirwadkar 
42068016e29fSHarshad Shirwadkar /*
4207c9de560dSAlex Tomas  * here we normalize request for locality group
4208d7a1fee1SDan Ehrenberg  * Group request are normalized to s_mb_group_prealloc, which goes to
4209d7a1fee1SDan Ehrenberg  * s_strip if we set the same via mount option.
4210d7a1fee1SDan Ehrenberg  * s_mb_group_prealloc can be configured via
4211b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_group_prealloc
4212c9de560dSAlex Tomas  *
4213c9de560dSAlex Tomas  * XXX: should we try to preallocate more than the group has now?
4214c9de560dSAlex Tomas  */
4215c9de560dSAlex Tomas static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
4216c9de560dSAlex Tomas {
4217c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
4218c9de560dSAlex Tomas 	struct ext4_locality_group *lg = ac->ac_lg;
4219c9de560dSAlex Tomas 
4220c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
4221c9de560dSAlex Tomas 	ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
4222d3df1453SRitesh Harjani 	mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
4223c9de560dSAlex Tomas }
4224c9de560dSAlex Tomas 
422538727786SOjaswin Mujoo /*
422638727786SOjaswin Mujoo  * This function returns the next element to look at during inode
422738727786SOjaswin Mujoo  * PA rbtree walk. We assume that we have held the inode PA rbtree lock
422838727786SOjaswin Mujoo  * (ei->i_prealloc_lock)
422938727786SOjaswin Mujoo  *
423038727786SOjaswin Mujoo  * new_start	The start of the range we want to compare
423138727786SOjaswin Mujoo  * cur_start	The existing start that we are comparing against
423238727786SOjaswin Mujoo  * node	The node of the rb_tree
423338727786SOjaswin Mujoo  */
423438727786SOjaswin Mujoo static inline struct rb_node*
423538727786SOjaswin Mujoo ext4_mb_pa_rb_next_iter(ext4_lblk_t new_start, ext4_lblk_t cur_start, struct rb_node *node)
423638727786SOjaswin Mujoo {
423738727786SOjaswin Mujoo 	if (new_start < cur_start)
423838727786SOjaswin Mujoo 		return node->rb_left;
423938727786SOjaswin Mujoo 	else
424038727786SOjaswin Mujoo 		return node->rb_right;
424138727786SOjaswin Mujoo }
424238727786SOjaswin Mujoo 
42437692094aSOjaswin Mujoo static inline void
42447692094aSOjaswin Mujoo ext4_mb_pa_assert_overlap(struct ext4_allocation_context *ac,
4245bedc5d34SBaokun Li 			  ext4_lblk_t start, loff_t end)
42467692094aSOjaswin Mujoo {
42477692094aSOjaswin Mujoo 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
42487692094aSOjaswin Mujoo 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
42497692094aSOjaswin Mujoo 	struct ext4_prealloc_space *tmp_pa;
4250bedc5d34SBaokun Li 	ext4_lblk_t tmp_pa_start;
4251bedc5d34SBaokun Li 	loff_t tmp_pa_end;
425238727786SOjaswin Mujoo 	struct rb_node *iter;
42537692094aSOjaswin Mujoo 
425438727786SOjaswin Mujoo 	read_lock(&ei->i_prealloc_lock);
425538727786SOjaswin Mujoo 	for (iter = ei->i_prealloc_node.rb_node; iter;
425638727786SOjaswin Mujoo 	     iter = ext4_mb_pa_rb_next_iter(start, tmp_pa_start, iter)) {
425738727786SOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
425838727786SOjaswin Mujoo 				  pa_node.inode_node);
42597692094aSOjaswin Mujoo 		tmp_pa_start = tmp_pa->pa_lstart;
4260bedc5d34SBaokun Li 		tmp_pa_end = pa_logical_end(sbi, tmp_pa);
42617692094aSOjaswin Mujoo 
426238727786SOjaswin Mujoo 		spin_lock(&tmp_pa->pa_lock);
426338727786SOjaswin Mujoo 		if (tmp_pa->pa_deleted == 0)
42647692094aSOjaswin Mujoo 			BUG_ON(!(start >= tmp_pa_end || end <= tmp_pa_start));
42657692094aSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
42667692094aSOjaswin Mujoo 	}
426738727786SOjaswin Mujoo 	read_unlock(&ei->i_prealloc_lock);
42687692094aSOjaswin Mujoo }
42697692094aSOjaswin Mujoo 
4270c9de560dSAlex Tomas /*
42710830344cSOjaswin Mujoo  * Given an allocation context "ac" and a range "start", "end", check
42720830344cSOjaswin Mujoo  * and adjust boundaries if the range overlaps with any of the existing
42730830344cSOjaswin Mujoo  * preallocatoins stored in the corresponding inode of the allocation context.
42740830344cSOjaswin Mujoo  *
42750830344cSOjaswin Mujoo  * Parameters:
42760830344cSOjaswin Mujoo  *	ac			allocation context
42770830344cSOjaswin Mujoo  *	start			start of the new range
42780830344cSOjaswin Mujoo  *	end			end of the new range
42790830344cSOjaswin Mujoo  */
42800830344cSOjaswin Mujoo static inline void
42810830344cSOjaswin Mujoo ext4_mb_pa_adjust_overlap(struct ext4_allocation_context *ac,
4282bedc5d34SBaokun Li 			  ext4_lblk_t *start, loff_t *end)
42830830344cSOjaswin Mujoo {
42840830344cSOjaswin Mujoo 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
42850830344cSOjaswin Mujoo 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
428638727786SOjaswin Mujoo 	struct ext4_prealloc_space *tmp_pa = NULL, *left_pa = NULL, *right_pa = NULL;
428738727786SOjaswin Mujoo 	struct rb_node *iter;
4288bedc5d34SBaokun Li 	ext4_lblk_t new_start, tmp_pa_start, right_pa_start = -1;
4289bedc5d34SBaokun Li 	loff_t new_end, tmp_pa_end, left_pa_end = -1;
42900830344cSOjaswin Mujoo 
42910830344cSOjaswin Mujoo 	new_start = *start;
42920830344cSOjaswin Mujoo 	new_end = *end;
42930830344cSOjaswin Mujoo 
429438727786SOjaswin Mujoo 	/*
429538727786SOjaswin Mujoo 	 * Adjust the normalized range so that it doesn't overlap with any
429638727786SOjaswin Mujoo 	 * existing preallocated blocks(PAs). Make sure to hold the rbtree lock
429738727786SOjaswin Mujoo 	 * so it doesn't change underneath us.
429838727786SOjaswin Mujoo 	 */
429938727786SOjaswin Mujoo 	read_lock(&ei->i_prealloc_lock);
43000830344cSOjaswin Mujoo 
430138727786SOjaswin Mujoo 	/* Step 1: find any one immediate neighboring PA of the normalized range */
430238727786SOjaswin Mujoo 	for (iter = ei->i_prealloc_node.rb_node; iter;
430338727786SOjaswin Mujoo 	     iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
430438727786SOjaswin Mujoo 					    tmp_pa_start, iter)) {
430538727786SOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
430638727786SOjaswin Mujoo 				  pa_node.inode_node);
43070830344cSOjaswin Mujoo 		tmp_pa_start = tmp_pa->pa_lstart;
4308bedc5d34SBaokun Li 		tmp_pa_end = pa_logical_end(sbi, tmp_pa);
43090830344cSOjaswin Mujoo 
43100830344cSOjaswin Mujoo 		/* PA must not overlap original request */
431138727786SOjaswin Mujoo 		spin_lock(&tmp_pa->pa_lock);
431238727786SOjaswin Mujoo 		if (tmp_pa->pa_deleted == 0)
43130830344cSOjaswin Mujoo 			BUG_ON(!(ac->ac_o_ex.fe_logical >= tmp_pa_end ||
43140830344cSOjaswin Mujoo 				 ac->ac_o_ex.fe_logical < tmp_pa_start));
43150830344cSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
43160830344cSOjaswin Mujoo 	}
43170830344cSOjaswin Mujoo 
431838727786SOjaswin Mujoo 	/*
431938727786SOjaswin Mujoo 	 * Step 2: check if the found PA is left or right neighbor and
432038727786SOjaswin Mujoo 	 * get the other neighbor
432138727786SOjaswin Mujoo 	 */
432238727786SOjaswin Mujoo 	if (tmp_pa) {
432338727786SOjaswin Mujoo 		if (tmp_pa->pa_lstart < ac->ac_o_ex.fe_logical) {
432438727786SOjaswin Mujoo 			struct rb_node *tmp;
432538727786SOjaswin Mujoo 
432638727786SOjaswin Mujoo 			left_pa = tmp_pa;
432738727786SOjaswin Mujoo 			tmp = rb_next(&left_pa->pa_node.inode_node);
432838727786SOjaswin Mujoo 			if (tmp) {
432938727786SOjaswin Mujoo 				right_pa = rb_entry(tmp,
433038727786SOjaswin Mujoo 						    struct ext4_prealloc_space,
433138727786SOjaswin Mujoo 						    pa_node.inode_node);
433238727786SOjaswin Mujoo 			}
433338727786SOjaswin Mujoo 		} else {
433438727786SOjaswin Mujoo 			struct rb_node *tmp;
433538727786SOjaswin Mujoo 
433638727786SOjaswin Mujoo 			right_pa = tmp_pa;
433738727786SOjaswin Mujoo 			tmp = rb_prev(&right_pa->pa_node.inode_node);
433838727786SOjaswin Mujoo 			if (tmp) {
433938727786SOjaswin Mujoo 				left_pa = rb_entry(tmp,
434038727786SOjaswin Mujoo 						   struct ext4_prealloc_space,
434138727786SOjaswin Mujoo 						   pa_node.inode_node);
434238727786SOjaswin Mujoo 			}
434338727786SOjaswin Mujoo 		}
434438727786SOjaswin Mujoo 	}
434538727786SOjaswin Mujoo 
434638727786SOjaswin Mujoo 	/* Step 3: get the non deleted neighbors */
434738727786SOjaswin Mujoo 	if (left_pa) {
434838727786SOjaswin Mujoo 		for (iter = &left_pa->pa_node.inode_node;;
434938727786SOjaswin Mujoo 		     iter = rb_prev(iter)) {
435038727786SOjaswin Mujoo 			if (!iter) {
435138727786SOjaswin Mujoo 				left_pa = NULL;
435238727786SOjaswin Mujoo 				break;
435338727786SOjaswin Mujoo 			}
435438727786SOjaswin Mujoo 
435538727786SOjaswin Mujoo 			tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
435638727786SOjaswin Mujoo 					  pa_node.inode_node);
435738727786SOjaswin Mujoo 			left_pa = tmp_pa;
435838727786SOjaswin Mujoo 			spin_lock(&tmp_pa->pa_lock);
435938727786SOjaswin Mujoo 			if (tmp_pa->pa_deleted == 0) {
436038727786SOjaswin Mujoo 				spin_unlock(&tmp_pa->pa_lock);
436138727786SOjaswin Mujoo 				break;
43620830344cSOjaswin Mujoo 			}
43630830344cSOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
43640830344cSOjaswin Mujoo 		}
436538727786SOjaswin Mujoo 	}
436638727786SOjaswin Mujoo 
436738727786SOjaswin Mujoo 	if (right_pa) {
436838727786SOjaswin Mujoo 		for (iter = &right_pa->pa_node.inode_node;;
436938727786SOjaswin Mujoo 		     iter = rb_next(iter)) {
437038727786SOjaswin Mujoo 			if (!iter) {
437138727786SOjaswin Mujoo 				right_pa = NULL;
437238727786SOjaswin Mujoo 				break;
437338727786SOjaswin Mujoo 			}
437438727786SOjaswin Mujoo 
437538727786SOjaswin Mujoo 			tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
437638727786SOjaswin Mujoo 					  pa_node.inode_node);
437738727786SOjaswin Mujoo 			right_pa = tmp_pa;
437838727786SOjaswin Mujoo 			spin_lock(&tmp_pa->pa_lock);
437938727786SOjaswin Mujoo 			if (tmp_pa->pa_deleted == 0) {
438038727786SOjaswin Mujoo 				spin_unlock(&tmp_pa->pa_lock);
438138727786SOjaswin Mujoo 				break;
438238727786SOjaswin Mujoo 			}
438338727786SOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
438438727786SOjaswin Mujoo 		}
438538727786SOjaswin Mujoo 	}
438638727786SOjaswin Mujoo 
438738727786SOjaswin Mujoo 	if (left_pa) {
4388bedc5d34SBaokun Li 		left_pa_end = pa_logical_end(sbi, left_pa);
438938727786SOjaswin Mujoo 		BUG_ON(left_pa_end > ac->ac_o_ex.fe_logical);
439038727786SOjaswin Mujoo 	}
439138727786SOjaswin Mujoo 
439238727786SOjaswin Mujoo 	if (right_pa) {
439338727786SOjaswin Mujoo 		right_pa_start = right_pa->pa_lstart;
439438727786SOjaswin Mujoo 		BUG_ON(right_pa_start <= ac->ac_o_ex.fe_logical);
439538727786SOjaswin Mujoo 	}
439638727786SOjaswin Mujoo 
439738727786SOjaswin Mujoo 	/* Step 4: trim our normalized range to not overlap with the neighbors */
439838727786SOjaswin Mujoo 	if (left_pa) {
439938727786SOjaswin Mujoo 		if (left_pa_end > new_start)
440038727786SOjaswin Mujoo 			new_start = left_pa_end;
440138727786SOjaswin Mujoo 	}
440238727786SOjaswin Mujoo 
440338727786SOjaswin Mujoo 	if (right_pa) {
440438727786SOjaswin Mujoo 		if (right_pa_start < new_end)
440538727786SOjaswin Mujoo 			new_end = right_pa_start;
440638727786SOjaswin Mujoo 	}
440738727786SOjaswin Mujoo 	read_unlock(&ei->i_prealloc_lock);
44080830344cSOjaswin Mujoo 
44090830344cSOjaswin Mujoo 	/* XXX: extra loop to check we really don't overlap preallocations */
44100830344cSOjaswin Mujoo 	ext4_mb_pa_assert_overlap(ac, new_start, new_end);
44110830344cSOjaswin Mujoo 
44120830344cSOjaswin Mujoo 	*start = new_start;
44130830344cSOjaswin Mujoo 	*end = new_end;
44140830344cSOjaswin Mujoo }
44150830344cSOjaswin Mujoo 
44160830344cSOjaswin Mujoo /*
4417c9de560dSAlex Tomas  * Normalization means making request better in terms of
4418c9de560dSAlex Tomas  * size and alignment
4419c9de560dSAlex Tomas  */
44204ddfef7bSEric Sandeen static noinline_for_stack void
44214ddfef7bSEric Sandeen ext4_mb_normalize_request(struct ext4_allocation_context *ac,
4422c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
4423c9de560dSAlex Tomas {
442453accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4425b07ffe69SKemeng Shi 	struct ext4_super_block *es = sbi->s_es;
4426c9de560dSAlex Tomas 	int bsbits, max;
4427bedc5d34SBaokun Li 	loff_t size, start_off, end;
44281592d2c5SCurt Wohlgemuth 	loff_t orig_size __maybe_unused;
44295a0790c2SAndi Kleen 	ext4_lblk_t start;
4430c9de560dSAlex Tomas 
4431c9de560dSAlex Tomas 	/* do normalize only data requests, metadata requests
4432c9de560dSAlex Tomas 	   do not need preallocation */
4433c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4434c9de560dSAlex Tomas 		return;
4435c9de560dSAlex Tomas 
4436c9de560dSAlex Tomas 	/* sometime caller may want exact blocks */
4437c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4438c9de560dSAlex Tomas 		return;
4439c9de560dSAlex Tomas 
4440c9de560dSAlex Tomas 	/* caller may indicate that preallocation isn't
4441c9de560dSAlex Tomas 	 * required (it's a tail, for example) */
4442c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
4443c9de560dSAlex Tomas 		return;
4444c9de560dSAlex Tomas 
4445c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
4446c9de560dSAlex Tomas 		ext4_mb_normalize_group_request(ac);
4447c9de560dSAlex Tomas 		return ;
4448c9de560dSAlex Tomas 	}
4449c9de560dSAlex Tomas 
4450c9de560dSAlex Tomas 	bsbits = ac->ac_sb->s_blocksize_bits;
4451c9de560dSAlex Tomas 
4452c9de560dSAlex Tomas 	/* first, let's learn actual file size
4453c9de560dSAlex Tomas 	 * given current request is allocated */
445443bbddc0SBaokun Li 	size = extent_logical_end(sbi, &ac->ac_o_ex);
4455c9de560dSAlex Tomas 	size = size << bsbits;
4456c9de560dSAlex Tomas 	if (size < i_size_read(ac->ac_inode))
4457c9de560dSAlex Tomas 		size = i_size_read(ac->ac_inode);
44585a0790c2SAndi Kleen 	orig_size = size;
4459c9de560dSAlex Tomas 
44601930479cSValerie Clement 	/* max size of free chunks */
44611930479cSValerie Clement 	max = 2 << bsbits;
4462c9de560dSAlex Tomas 
44631930479cSValerie Clement #define NRL_CHECK_SIZE(req, size, max, chunk_size)	\
44641930479cSValerie Clement 		(req <= (size) || max <= (chunk_size))
4465c9de560dSAlex Tomas 
4466c9de560dSAlex Tomas 	/* first, try to predict filesize */
4467c9de560dSAlex Tomas 	/* XXX: should this table be tunable? */
4468c9de560dSAlex Tomas 	start_off = 0;
4469c9de560dSAlex Tomas 	if (size <= 16 * 1024) {
4470c9de560dSAlex Tomas 		size = 16 * 1024;
4471c9de560dSAlex Tomas 	} else if (size <= 32 * 1024) {
4472c9de560dSAlex Tomas 		size = 32 * 1024;
4473c9de560dSAlex Tomas 	} else if (size <= 64 * 1024) {
4474c9de560dSAlex Tomas 		size = 64 * 1024;
4475c9de560dSAlex Tomas 	} else if (size <= 128 * 1024) {
4476c9de560dSAlex Tomas 		size = 128 * 1024;
4477c9de560dSAlex Tomas 	} else if (size <= 256 * 1024) {
4478c9de560dSAlex Tomas 		size = 256 * 1024;
4479c9de560dSAlex Tomas 	} else if (size <= 512 * 1024) {
4480c9de560dSAlex Tomas 		size = 512 * 1024;
4481c9de560dSAlex Tomas 	} else if (size <= 1024 * 1024) {
4482c9de560dSAlex Tomas 		size = 1024 * 1024;
44831930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
4484c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
44851930479cSValerie Clement 						(21 - bsbits)) << 21;
44861930479cSValerie Clement 		size = 2 * 1024 * 1024;
44871930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
4488c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4489c9de560dSAlex Tomas 							(22 - bsbits)) << 22;
4490c9de560dSAlex Tomas 		size = 4 * 1024 * 1024;
4491b3916da0SKemeng Shi 	} else if (NRL_CHECK_SIZE(EXT4_C2B(sbi, ac->ac_o_ex.fe_len),
44921930479cSValerie Clement 					(8<<20)>>bsbits, max, 8 * 1024)) {
4493c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4494c9de560dSAlex Tomas 							(23 - bsbits)) << 23;
4495c9de560dSAlex Tomas 		size = 8 * 1024 * 1024;
4496c9de560dSAlex Tomas 	} else {
4497c9de560dSAlex Tomas 		start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
449891a48aafSKemeng Shi 		size	  = (loff_t) EXT4_C2B(sbi,
4499b27b1535SXiaoguang Wang 					      ac->ac_o_ex.fe_len) << bsbits;
4500c9de560dSAlex Tomas 	}
45015a0790c2SAndi Kleen 	size = size >> bsbits;
45025a0790c2SAndi Kleen 	start = start_off >> bsbits;
4503c9de560dSAlex Tomas 
4504a08f789dSBaokun Li 	/*
4505a08f789dSBaokun Li 	 * For tiny groups (smaller than 8MB) the chosen allocation
4506a08f789dSBaokun Li 	 * alignment may be larger than group size. Make sure the
4507a08f789dSBaokun Li 	 * alignment does not move allocation to a different group which
4508a08f789dSBaokun Li 	 * makes mballoc fail assertions later.
4509a08f789dSBaokun Li 	 */
4510a08f789dSBaokun Li 	start = max(start, rounddown(ac->ac_o_ex.fe_logical,
4511a08f789dSBaokun Li 			(ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
4512a08f789dSBaokun Li 
45132dcf5fdeSBaokun Li 	/* avoid unnecessary preallocation that may trigger assertions */
45142dcf5fdeSBaokun Li 	if (start + size > EXT_MAX_BLOCKS)
45152dcf5fdeSBaokun Li 		size = EXT_MAX_BLOCKS - start;
45162dcf5fdeSBaokun Li 
4517c9de560dSAlex Tomas 	/* don't cover already allocated blocks in selected range */
4518c9de560dSAlex Tomas 	if (ar->pleft && start <= ar->lleft) {
4519c9de560dSAlex Tomas 		size -= ar->lleft + 1 - start;
4520c9de560dSAlex Tomas 		start = ar->lleft + 1;
4521c9de560dSAlex Tomas 	}
4522c9de560dSAlex Tomas 	if (ar->pright && start + size - 1 >= ar->lright)
4523c9de560dSAlex Tomas 		size -= start + size - ar->lright;
4524c9de560dSAlex Tomas 
4525cd648b8aSJan Kara 	/*
4526cd648b8aSJan Kara 	 * Trim allocation request for filesystems with artificially small
4527cd648b8aSJan Kara 	 * groups.
4528cd648b8aSJan Kara 	 */
4529cd648b8aSJan Kara 	if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
4530cd648b8aSJan Kara 		size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
4531cd648b8aSJan Kara 
4532c9de560dSAlex Tomas 	end = start + size;
4533c9de560dSAlex Tomas 
45340830344cSOjaswin Mujoo 	ext4_mb_pa_adjust_overlap(ac, &start, &end);
4535c9de560dSAlex Tomas 
4536c9de560dSAlex Tomas 	size = end - start;
4537c9de560dSAlex Tomas 
4538cf4ff938SBaokun Li 	/*
4539cf4ff938SBaokun Li 	 * In this function "start" and "size" are normalized for better
4540cf4ff938SBaokun Li 	 * alignment and length such that we could preallocate more blocks.
4541cf4ff938SBaokun Li 	 * This normalization is done such that original request of
4542cf4ff938SBaokun Li 	 * ac->ac_o_ex.fe_logical & fe_len should always lie within "start" and
4543cf4ff938SBaokun Li 	 * "size" boundaries.
4544cf4ff938SBaokun Li 	 * (Note fe_len can be relaxed since FS block allocation API does not
4545cf4ff938SBaokun Li 	 * provide gurantee on number of contiguous blocks allocation since that
4546cf4ff938SBaokun Li 	 * depends upon free space left, etc).
4547cf4ff938SBaokun Li 	 * In case of inode pa, later we use the allocated blocks
45481221b235SKemeng Shi 	 * [pa_pstart + fe_logical - pa_lstart, fe_len/size] from the preallocated
4549cf4ff938SBaokun Li 	 * range of goal/best blocks [start, size] to put it at the
4550cf4ff938SBaokun Li 	 * ac_o_ex.fe_logical extent of this inode.
4551cf4ff938SBaokun Li 	 * (See ext4_mb_use_inode_pa() for more details)
4552cf4ff938SBaokun Li 	 */
4553cf4ff938SBaokun Li 	if (start + size <= ac->ac_o_ex.fe_logical ||
4554c9de560dSAlex Tomas 			start > ac->ac_o_ex.fe_logical) {
45559d8b9ec4STheodore Ts'o 		ext4_msg(ac->ac_sb, KERN_ERR,
45569d8b9ec4STheodore Ts'o 			 "start %lu, size %lu, fe_logical %lu",
4557c9de560dSAlex Tomas 			 (unsigned long) start, (unsigned long) size,
4558c9de560dSAlex Tomas 			 (unsigned long) ac->ac_o_ex.fe_logical);
4559dfe076c1SDmitry Monakhov 		BUG();
4560c9de560dSAlex Tomas 	}
4561b5b60778SMaurizio Lombardi 	BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
4562c9de560dSAlex Tomas 
4563c9de560dSAlex Tomas 	/* now prepare goal request */
4564c9de560dSAlex Tomas 
4565c9de560dSAlex Tomas 	/* XXX: is it better to align blocks WRT to logical
4566c9de560dSAlex Tomas 	 * placement or satisfy big request as is */
4567c9de560dSAlex Tomas 	ac->ac_g_ex.fe_logical = start;
456853accfa9STheodore Ts'o 	ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
45697e170922SOjaswin Mujoo 	ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
4570c9de560dSAlex Tomas 
4571c9de560dSAlex Tomas 	/* define goal start in order to merge */
4572b07ffe69SKemeng Shi 	if (ar->pright && (ar->lright == (start + size)) &&
4573b07ffe69SKemeng Shi 	    ar->pright >= size &&
4574b07ffe69SKemeng Shi 	    ar->pright - size >= le32_to_cpu(es->s_first_data_block)) {
4575c9de560dSAlex Tomas 		/* merge to the right */
4576c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
4577b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_group,
4578b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_start);
4579c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4580c9de560dSAlex Tomas 	}
4581b07ffe69SKemeng Shi 	if (ar->pleft && (ar->lleft + 1 == start) &&
4582b07ffe69SKemeng Shi 	    ar->pleft + 1 < ext4_blocks_count(es)) {
4583c9de560dSAlex Tomas 		/* merge to the left */
4584c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
4585b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_group,
4586b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_start);
4587c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4588c9de560dSAlex Tomas 	}
4589c9de560dSAlex Tomas 
4590d3df1453SRitesh Harjani 	mb_debug(ac->ac_sb, "goal: %lld(was %lld) blocks at %u\n", size,
4591d3df1453SRitesh Harjani 		 orig_size, start);
4592c9de560dSAlex Tomas }
4593c9de560dSAlex Tomas 
4594c9de560dSAlex Tomas static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
4595c9de560dSAlex Tomas {
4596c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4597c9de560dSAlex Tomas 
4598a6c75eafSHarshad Shirwadkar 	if (sbi->s_mb_stats && ac->ac_g_ex.fe_len >= 1) {
4599c9de560dSAlex Tomas 		atomic_inc(&sbi->s_bal_reqs);
4600c9de560dSAlex Tomas 		atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
4601291dae47SCurt Wohlgemuth 		if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
4602c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_success);
4603fdd9a009SOjaswin Mujoo 
4604c9de560dSAlex Tomas 		atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
4605fdd9a009SOjaswin Mujoo 		for (int i=0; i<EXT4_MB_NUM_CRS; i++) {
4606fdd9a009SOjaswin Mujoo 			atomic_add(ac->ac_cX_found[i], &sbi->s_bal_cX_ex_scanned[i]);
4607fdd9a009SOjaswin Mujoo 		}
4608fdd9a009SOjaswin Mujoo 
4609a6c75eafSHarshad Shirwadkar 		atomic_add(ac->ac_groups_scanned, &sbi->s_bal_groups_scanned);
4610c9de560dSAlex Tomas 		if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
4611c9de560dSAlex Tomas 				ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
4612c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_goals);
46137e170922SOjaswin Mujoo 		/* did we allocate as much as normalizer originally wanted? */
46147e170922SOjaswin Mujoo 		if (ac->ac_f_ex.fe_len == ac->ac_orig_goal_len)
46153ef5d263SOjaswin Mujoo 			atomic_inc(&sbi->s_bal_len_goals);
46167e170922SOjaswin Mujoo 
4617c9de560dSAlex Tomas 		if (ac->ac_found > sbi->s_mb_max_to_scan)
4618c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_breaks);
4619c9de560dSAlex Tomas 	}
4620c9de560dSAlex Tomas 
4621296c355cSTheodore Ts'o 	if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
4622296c355cSTheodore Ts'o 		trace_ext4_mballoc_alloc(ac);
4623296c355cSTheodore Ts'o 	else
4624296c355cSTheodore Ts'o 		trace_ext4_mballoc_prealloc(ac);
4625c9de560dSAlex Tomas }
4626c9de560dSAlex Tomas 
4627c9de560dSAlex Tomas /*
4628b844167eSCurt Wohlgemuth  * Called on failure; free up any blocks from the inode PA for this
4629b844167eSCurt Wohlgemuth  * context.  We don't need this for MB_GROUP_PA because we only change
4630b844167eSCurt Wohlgemuth  * pa_free in ext4_mb_release_context(), but on failure, we've already
4631b844167eSCurt Wohlgemuth  * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
4632b844167eSCurt Wohlgemuth  */
4633b844167eSCurt Wohlgemuth static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
4634b844167eSCurt Wohlgemuth {
4635b844167eSCurt Wohlgemuth 	struct ext4_prealloc_space *pa = ac->ac_pa;
463686f0afd4STheodore Ts'o 	struct ext4_buddy e4b;
463786f0afd4STheodore Ts'o 	int err;
4638b844167eSCurt Wohlgemuth 
463986f0afd4STheodore Ts'o 	if (pa == NULL) {
4640c99d1e6eSTheodore Ts'o 		if (ac->ac_f_ex.fe_len == 0)
4641c99d1e6eSTheodore Ts'o 			return;
464286f0afd4STheodore Ts'o 		err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
464319b8b035STheodore Ts'o 		if (WARN_RATELIMIT(err,
464419b8b035STheodore Ts'o 				   "ext4: mb_load_buddy failed (%d)", err))
464586f0afd4STheodore Ts'o 			/*
464686f0afd4STheodore Ts'o 			 * This should never happen since we pin the
464786f0afd4STheodore Ts'o 			 * pages in the ext4_allocation_context so
464886f0afd4STheodore Ts'o 			 * ext4_mb_load_buddy() should never fail.
464986f0afd4STheodore Ts'o 			 */
465086f0afd4STheodore Ts'o 			return;
465186f0afd4STheodore Ts'o 		ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
465286f0afd4STheodore Ts'o 		mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
465386f0afd4STheodore Ts'o 			       ac->ac_f_ex.fe_len);
465486f0afd4STheodore Ts'o 		ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
4655c99d1e6eSTheodore Ts'o 		ext4_mb_unload_buddy(&e4b);
465686f0afd4STheodore Ts'o 		return;
465786f0afd4STheodore Ts'o 	}
465836cb0f52SKemeng Shi 	if (pa->pa_type == MB_INODE_PA) {
465936cb0f52SKemeng Shi 		spin_lock(&pa->pa_lock);
4660400db9d3SZheng Liu 		pa->pa_free += ac->ac_b_ex.fe_len;
466136cb0f52SKemeng Shi 		spin_unlock(&pa->pa_lock);
466236cb0f52SKemeng Shi 	}
4663b844167eSCurt Wohlgemuth }
4664b844167eSCurt Wohlgemuth 
4665b844167eSCurt Wohlgemuth /*
4666c9de560dSAlex Tomas  * use blocks preallocated to inode
4667c9de560dSAlex Tomas  */
4668c9de560dSAlex Tomas static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
4669c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
4670c9de560dSAlex Tomas {
467153accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4672c9de560dSAlex Tomas 	ext4_fsblk_t start;
4673c9de560dSAlex Tomas 	ext4_fsblk_t end;
4674c9de560dSAlex Tomas 	int len;
4675c9de560dSAlex Tomas 
4676c9de560dSAlex Tomas 	/* found preallocated blocks, use them */
4677c9de560dSAlex Tomas 	start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
467853accfa9STheodore Ts'o 	end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
467953accfa9STheodore Ts'o 		  start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
468053accfa9STheodore Ts'o 	len = EXT4_NUM_B2C(sbi, end - start);
4681c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
4682c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
4683c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
4684c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
4685c9de560dSAlex Tomas 	ac->ac_pa = pa;
4686c9de560dSAlex Tomas 
4687c9de560dSAlex Tomas 	BUG_ON(start < pa->pa_pstart);
468853accfa9STheodore Ts'o 	BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
4689c9de560dSAlex Tomas 	BUG_ON(pa->pa_free < len);
469093cdf49fSOjaswin Mujoo 	BUG_ON(ac->ac_b_ex.fe_len <= 0);
4691c9de560dSAlex Tomas 	pa->pa_free -= len;
4692c9de560dSAlex Tomas 
4693d3df1453SRitesh Harjani 	mb_debug(ac->ac_sb, "use %llu/%d from inode pa %p\n", start, len, pa);
4694c9de560dSAlex Tomas }
4695c9de560dSAlex Tomas 
4696c9de560dSAlex Tomas /*
4697c9de560dSAlex Tomas  * use blocks preallocated to locality group
4698c9de560dSAlex Tomas  */
4699c9de560dSAlex Tomas static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
4700c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
4701c9de560dSAlex Tomas {
470203cddb80SAneesh Kumar K.V 	unsigned int len = ac->ac_o_ex.fe_len;
47036be2ded1SAneesh Kumar K.V 
4704c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
4705c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_group,
4706c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
4707c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
4708c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
4709c9de560dSAlex Tomas 	ac->ac_pa = pa;
4710c9de560dSAlex Tomas 
47111221b235SKemeng Shi 	/* we don't correct pa_pstart or pa_len here to avoid
471226346ff6SAneesh Kumar K.V 	 * possible race when the group is being loaded concurrently
4713c9de560dSAlex Tomas 	 * instead we correct pa later, after blocks are marked
471426346ff6SAneesh Kumar K.V 	 * in on-disk bitmap -- see ext4_mb_release_context()
471526346ff6SAneesh Kumar K.V 	 * Other CPUs are prevented from allocating from this pa by lg_mutex
4716c9de560dSAlex Tomas 	 */
4717d3df1453SRitesh Harjani 	mb_debug(ac->ac_sb, "use %u/%u from group pa %p\n",
47181afdc588SKemeng Shi 		 pa->pa_lstart, len, pa);
4719c9de560dSAlex Tomas }
4720c9de560dSAlex Tomas 
4721c9de560dSAlex Tomas /*
47225e745b04SAneesh Kumar K.V  * Return the prealloc space that have minimal distance
47235e745b04SAneesh Kumar K.V  * from the goal block. @cpa is the prealloc
47245e745b04SAneesh Kumar K.V  * space that is having currently known minimal distance
47255e745b04SAneesh Kumar K.V  * from the goal block.
47265e745b04SAneesh Kumar K.V  */
47275e745b04SAneesh Kumar K.V static struct ext4_prealloc_space *
47285e745b04SAneesh Kumar K.V ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
47295e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *pa,
47305e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *cpa)
47315e745b04SAneesh Kumar K.V {
47325e745b04SAneesh Kumar K.V 	ext4_fsblk_t cur_distance, new_distance;
47335e745b04SAneesh Kumar K.V 
47345e745b04SAneesh Kumar K.V 	if (cpa == NULL) {
47355e745b04SAneesh Kumar K.V 		atomic_inc(&pa->pa_count);
47365e745b04SAneesh Kumar K.V 		return pa;
47375e745b04SAneesh Kumar K.V 	}
473879211c8eSAndrew Morton 	cur_distance = abs(goal_block - cpa->pa_pstart);
473979211c8eSAndrew Morton 	new_distance = abs(goal_block - pa->pa_pstart);
47405e745b04SAneesh Kumar K.V 
47415a54b2f1SColy Li 	if (cur_distance <= new_distance)
47425e745b04SAneesh Kumar K.V 		return cpa;
47435e745b04SAneesh Kumar K.V 
47445e745b04SAneesh Kumar K.V 	/* drop the previous reference */
47455e745b04SAneesh Kumar K.V 	atomic_dec(&cpa->pa_count);
47465e745b04SAneesh Kumar K.V 	atomic_inc(&pa->pa_count);
47475e745b04SAneesh Kumar K.V 	return pa;
47485e745b04SAneesh Kumar K.V }
47495e745b04SAneesh Kumar K.V 
47505e745b04SAneesh Kumar K.V /*
47511eff5904SKemeng Shi  * check if found pa meets EXT4_MB_HINT_GOAL_ONLY
47521eff5904SKemeng Shi  */
47531eff5904SKemeng Shi static bool
47541eff5904SKemeng Shi ext4_mb_pa_goal_check(struct ext4_allocation_context *ac,
47551eff5904SKemeng Shi 		      struct ext4_prealloc_space *pa)
47561eff5904SKemeng Shi {
47571eff5904SKemeng Shi 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
47581eff5904SKemeng Shi 	ext4_fsblk_t start;
47591eff5904SKemeng Shi 
47601eff5904SKemeng Shi 	if (likely(!(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY)))
47611eff5904SKemeng Shi 		return true;
47621eff5904SKemeng Shi 
47631eff5904SKemeng Shi 	/*
47641eff5904SKemeng Shi 	 * If EXT4_MB_HINT_GOAL_ONLY is set, ac_g_ex will not be adjusted
47651eff5904SKemeng Shi 	 * in ext4_mb_normalize_request and will keep same with ac_o_ex
47661eff5904SKemeng Shi 	 * from ext4_mb_initialize_context. Choose ac_g_ex here to keep
47671eff5904SKemeng Shi 	 * consistent with ext4_mb_find_by_goal.
47681eff5904SKemeng Shi 	 */
47691eff5904SKemeng Shi 	start = pa->pa_pstart +
47701eff5904SKemeng Shi 		(ac->ac_g_ex.fe_logical - pa->pa_lstart);
47711eff5904SKemeng Shi 	if (ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex) != start)
47721eff5904SKemeng Shi 		return false;
47731eff5904SKemeng Shi 
47741eff5904SKemeng Shi 	if (ac->ac_g_ex.fe_len > pa->pa_len -
47751eff5904SKemeng Shi 	    EXT4_B2C(sbi, ac->ac_g_ex.fe_logical - pa->pa_lstart))
47761eff5904SKemeng Shi 		return false;
47771eff5904SKemeng Shi 
47781eff5904SKemeng Shi 	return true;
47791eff5904SKemeng Shi }
47801eff5904SKemeng Shi 
47811eff5904SKemeng Shi /*
4782c9de560dSAlex Tomas  * search goal blocks in preallocated space
4783c9de560dSAlex Tomas  */
47844fca8f07SRitesh Harjani static noinline_for_stack bool
47854ddfef7bSEric Sandeen ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
4786c9de560dSAlex Tomas {
478753accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
47886be2ded1SAneesh Kumar K.V 	int order, i;
4789c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4790c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
47919d3de7eeSOjaswin Mujoo 	struct ext4_prealloc_space *tmp_pa = NULL, *cpa = NULL;
479238727786SOjaswin Mujoo 	struct rb_node *iter;
47935e745b04SAneesh Kumar K.V 	ext4_fsblk_t goal_block;
4794c9de560dSAlex Tomas 
4795c9de560dSAlex Tomas 	/* only data can be preallocated */
4796c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
47974fca8f07SRitesh Harjani 		return false;
4798c9de560dSAlex Tomas 
47999d3de7eeSOjaswin Mujoo 	/*
48009d3de7eeSOjaswin Mujoo 	 * first, try per-file preallocation by searching the inode pa rbtree.
48019d3de7eeSOjaswin Mujoo 	 *
48029d3de7eeSOjaswin Mujoo 	 * Here, we can't do a direct traversal of the tree because
48039d3de7eeSOjaswin Mujoo 	 * ext4_mb_discard_group_preallocation() can paralelly mark the pa
48049d3de7eeSOjaswin Mujoo 	 * deleted and that can cause direct traversal to skip some entries.
48059d3de7eeSOjaswin Mujoo 	 */
480638727786SOjaswin Mujoo 	read_lock(&ei->i_prealloc_lock);
48079d3de7eeSOjaswin Mujoo 
48089d3de7eeSOjaswin Mujoo 	if (RB_EMPTY_ROOT(&ei->i_prealloc_node)) {
48099d3de7eeSOjaswin Mujoo 		goto try_group_pa;
48109d3de7eeSOjaswin Mujoo 	}
48119d3de7eeSOjaswin Mujoo 
48129d3de7eeSOjaswin Mujoo 	/*
48139d3de7eeSOjaswin Mujoo 	 * Step 1: Find a pa with logical start immediately adjacent to the
48149d3de7eeSOjaswin Mujoo 	 * original logical start. This could be on the left or right.
48159d3de7eeSOjaswin Mujoo 	 *
48169d3de7eeSOjaswin Mujoo 	 * (tmp_pa->pa_lstart never changes so we can skip locking for it).
48179d3de7eeSOjaswin Mujoo 	 */
481838727786SOjaswin Mujoo 	for (iter = ei->i_prealloc_node.rb_node; iter;
481938727786SOjaswin Mujoo 	     iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
48209d3de7eeSOjaswin Mujoo 					    tmp_pa->pa_lstart, iter)) {
482138727786SOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
482238727786SOjaswin Mujoo 				  pa_node.inode_node);
48239d3de7eeSOjaswin Mujoo 	}
4824c9de560dSAlex Tomas 
48259d3de7eeSOjaswin Mujoo 	/*
48269d3de7eeSOjaswin Mujoo 	 * Step 2: The adjacent pa might be to the right of logical start, find
48279d3de7eeSOjaswin Mujoo 	 * the left adjacent pa. After this step we'd have a valid tmp_pa whose
48289d3de7eeSOjaswin Mujoo 	 * logical start is towards the left of original request's logical start
48299d3de7eeSOjaswin Mujoo 	 */
48309d3de7eeSOjaswin Mujoo 	if (tmp_pa->pa_lstart > ac->ac_o_ex.fe_logical) {
48319d3de7eeSOjaswin Mujoo 		struct rb_node *tmp;
48329d3de7eeSOjaswin Mujoo 		tmp = rb_prev(&tmp_pa->pa_node.inode_node);
4833bcf43499SOjaswin Mujoo 
48349d3de7eeSOjaswin Mujoo 		if (tmp) {
48359d3de7eeSOjaswin Mujoo 			tmp_pa = rb_entry(tmp, struct ext4_prealloc_space,
48369d3de7eeSOjaswin Mujoo 					    pa_node.inode_node);
48379d3de7eeSOjaswin Mujoo 		} else {
48389d3de7eeSOjaswin Mujoo 			/*
48399d3de7eeSOjaswin Mujoo 			 * If there is no adjacent pa to the left then finding
48409d3de7eeSOjaswin Mujoo 			 * an overlapping pa is not possible hence stop searching
48419d3de7eeSOjaswin Mujoo 			 * inode pa tree
48429d3de7eeSOjaswin Mujoo 			 */
48439d3de7eeSOjaswin Mujoo 			goto try_group_pa;
48449d3de7eeSOjaswin Mujoo 		}
48459d3de7eeSOjaswin Mujoo 	}
48469d3de7eeSOjaswin Mujoo 
48479d3de7eeSOjaswin Mujoo 	BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
48489d3de7eeSOjaswin Mujoo 
48499d3de7eeSOjaswin Mujoo 	/*
48509d3de7eeSOjaswin Mujoo 	 * Step 3: If the left adjacent pa is deleted, keep moving left to find
48519d3de7eeSOjaswin Mujoo 	 * the first non deleted adjacent pa. After this step we should have a
48529d3de7eeSOjaswin Mujoo 	 * valid tmp_pa which is guaranteed to be non deleted.
48539d3de7eeSOjaswin Mujoo 	 */
48549d3de7eeSOjaswin Mujoo 	for (iter = &tmp_pa->pa_node.inode_node;; iter = rb_prev(iter)) {
48559d3de7eeSOjaswin Mujoo 		if (!iter) {
48569d3de7eeSOjaswin Mujoo 			/*
48579d3de7eeSOjaswin Mujoo 			 * no non deleted left adjacent pa, so stop searching
48589d3de7eeSOjaswin Mujoo 			 * inode pa tree
48599d3de7eeSOjaswin Mujoo 			 */
48609d3de7eeSOjaswin Mujoo 			goto try_group_pa;
48619d3de7eeSOjaswin Mujoo 		}
48629d3de7eeSOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
48639d3de7eeSOjaswin Mujoo 				  pa_node.inode_node);
48649d3de7eeSOjaswin Mujoo 		spin_lock(&tmp_pa->pa_lock);
48659d3de7eeSOjaswin Mujoo 		if (tmp_pa->pa_deleted == 0) {
48669d3de7eeSOjaswin Mujoo 			/*
48679d3de7eeSOjaswin Mujoo 			 * We will keep holding the pa_lock from
48689d3de7eeSOjaswin Mujoo 			 * this point on because we don't want group discard
48699d3de7eeSOjaswin Mujoo 			 * to delete this pa underneath us. Since group
48709d3de7eeSOjaswin Mujoo 			 * discard is anyways an ENOSPC operation it
48719d3de7eeSOjaswin Mujoo 			 * should be okay for it to wait a few more cycles.
48729d3de7eeSOjaswin Mujoo 			 */
48739d3de7eeSOjaswin Mujoo 			break;
48749d3de7eeSOjaswin Mujoo 		} else {
48759d3de7eeSOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
48769d3de7eeSOjaswin Mujoo 		}
48779d3de7eeSOjaswin Mujoo 	}
48789d3de7eeSOjaswin Mujoo 
48799d3de7eeSOjaswin Mujoo 	BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
48809d3de7eeSOjaswin Mujoo 	BUG_ON(tmp_pa->pa_deleted == 1);
48819d3de7eeSOjaswin Mujoo 
48829d3de7eeSOjaswin Mujoo 	/*
48839d3de7eeSOjaswin Mujoo 	 * Step 4: We now have the non deleted left adjacent pa. Only this
48849d3de7eeSOjaswin Mujoo 	 * pa can possibly satisfy the request hence check if it overlaps
48859d3de7eeSOjaswin Mujoo 	 * original logical start and stop searching if it doesn't.
48869d3de7eeSOjaswin Mujoo 	 */
488743bbddc0SBaokun Li 	if (ac->ac_o_ex.fe_logical >= pa_logical_end(sbi, tmp_pa)) {
48889d3de7eeSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
48899d3de7eeSOjaswin Mujoo 		goto try_group_pa;
48909d3de7eeSOjaswin Mujoo 	}
4891c9de560dSAlex Tomas 
4892fb0a387dSEric Sandeen 	/* non-extent files can't have physical blocks past 2^32 */
489312e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
4894bcf43499SOjaswin Mujoo 	    (tmp_pa->pa_pstart + EXT4_C2B(sbi, tmp_pa->pa_len) >
4895e86a7182SOjaswin Mujoo 	     EXT4_MAX_BLOCK_FILE_PHYS)) {
4896e86a7182SOjaswin Mujoo 		/*
48979d3de7eeSOjaswin Mujoo 		 * Since PAs don't overlap, we won't find any other PA to
48989d3de7eeSOjaswin Mujoo 		 * satisfy this.
4899e86a7182SOjaswin Mujoo 		 */
49009d3de7eeSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
49019d3de7eeSOjaswin Mujoo 		goto try_group_pa;
4902e86a7182SOjaswin Mujoo 	}
4903fb0a387dSEric Sandeen 
49049d3de7eeSOjaswin Mujoo 	if (tmp_pa->pa_free && likely(ext4_mb_pa_goal_check(ac, tmp_pa))) {
4905bcf43499SOjaswin Mujoo 		atomic_inc(&tmp_pa->pa_count);
4906bcf43499SOjaswin Mujoo 		ext4_mb_use_inode_pa(ac, tmp_pa);
4907bcf43499SOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
490838727786SOjaswin Mujoo 		read_unlock(&ei->i_prealloc_lock);
49094fca8f07SRitesh Harjani 		return true;
49109d3de7eeSOjaswin Mujoo 	} else {
49119d3de7eeSOjaswin Mujoo 		/*
49129d3de7eeSOjaswin Mujoo 		 * We found a valid overlapping pa but couldn't use it because
49139d3de7eeSOjaswin Mujoo 		 * it had no free blocks. This should ideally never happen
49149d3de7eeSOjaswin Mujoo 		 * because:
49159d3de7eeSOjaswin Mujoo 		 *
49169d3de7eeSOjaswin Mujoo 		 * 1. When a new inode pa is added to rbtree it must have
49179d3de7eeSOjaswin Mujoo 		 *    pa_free > 0 since otherwise we won't actually need
49189d3de7eeSOjaswin Mujoo 		 *    preallocation.
49199d3de7eeSOjaswin Mujoo 		 *
49209d3de7eeSOjaswin Mujoo 		 * 2. An inode pa that is in the rbtree can only have it's
49219d3de7eeSOjaswin Mujoo 		 *    pa_free become zero when another thread calls:
49229d3de7eeSOjaswin Mujoo 		 *      ext4_mb_new_blocks
49239d3de7eeSOjaswin Mujoo 		 *       ext4_mb_use_preallocated
49249d3de7eeSOjaswin Mujoo 		 *        ext4_mb_use_inode_pa
49259d3de7eeSOjaswin Mujoo 		 *
49269d3de7eeSOjaswin Mujoo 		 * 3. Further, after the above calls make pa_free == 0, we will
49279d3de7eeSOjaswin Mujoo 		 *    immediately remove it from the rbtree in:
49289d3de7eeSOjaswin Mujoo 		 *      ext4_mb_new_blocks
49299d3de7eeSOjaswin Mujoo 		 *       ext4_mb_release_context
49309d3de7eeSOjaswin Mujoo 		 *        ext4_mb_put_pa
49319d3de7eeSOjaswin Mujoo 		 *
49329d3de7eeSOjaswin Mujoo 		 * 4. Since the pa_free becoming 0 and pa_free getting removed
49339d3de7eeSOjaswin Mujoo 		 * from tree both happen in ext4_mb_new_blocks, which is always
49349d3de7eeSOjaswin Mujoo 		 * called with i_data_sem held for data allocations, we can be
49359d3de7eeSOjaswin Mujoo 		 * sure that another process will never see a pa in rbtree with
49369d3de7eeSOjaswin Mujoo 		 * pa_free == 0.
49379d3de7eeSOjaswin Mujoo 		 */
49389d3de7eeSOjaswin Mujoo 		WARN_ON_ONCE(tmp_pa->pa_free == 0);
4939c9de560dSAlex Tomas 	}
4940bcf43499SOjaswin Mujoo 	spin_unlock(&tmp_pa->pa_lock);
49419d3de7eeSOjaswin Mujoo try_group_pa:
494238727786SOjaswin Mujoo 	read_unlock(&ei->i_prealloc_lock);
4943c9de560dSAlex Tomas 
4944c9de560dSAlex Tomas 	/* can we use group allocation? */
4945c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
49464fca8f07SRitesh Harjani 		return false;
4947c9de560dSAlex Tomas 
4948c9de560dSAlex Tomas 	/* inode may have no locality group for some reason */
4949c9de560dSAlex Tomas 	lg = ac->ac_lg;
4950c9de560dSAlex Tomas 	if (lg == NULL)
49514fca8f07SRitesh Harjani 		return false;
49526be2ded1SAneesh Kumar K.V 	order  = fls(ac->ac_o_ex.fe_len) - 1;
49536be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
49546be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
49556be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
4956c9de560dSAlex Tomas 
4957bda00de7SAkinobu Mita 	goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
49585e745b04SAneesh Kumar K.V 	/*
49595e745b04SAneesh Kumar K.V 	 * search for the prealloc space that is having
49605e745b04SAneesh Kumar K.V 	 * minimal distance from the goal block.
49615e745b04SAneesh Kumar K.V 	 */
49626be2ded1SAneesh Kumar K.V 	for (i = order; i < PREALLOC_TB_SIZE; i++) {
4963c9de560dSAlex Tomas 		rcu_read_lock();
4964bcf43499SOjaswin Mujoo 		list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[i],
4965a8e38fd3SOjaswin Mujoo 					pa_node.lg_list) {
4966bcf43499SOjaswin Mujoo 			spin_lock(&tmp_pa->pa_lock);
4967bcf43499SOjaswin Mujoo 			if (tmp_pa->pa_deleted == 0 &&
4968bcf43499SOjaswin Mujoo 					tmp_pa->pa_free >= ac->ac_o_ex.fe_len) {
49695e745b04SAneesh Kumar K.V 
49705e745b04SAneesh Kumar K.V 				cpa = ext4_mb_check_group_pa(goal_block,
4971bcf43499SOjaswin Mujoo 								tmp_pa, cpa);
49725e745b04SAneesh Kumar K.V 			}
4973bcf43499SOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
49745e745b04SAneesh Kumar K.V 		}
49755e745b04SAneesh Kumar K.V 		rcu_read_unlock();
49765e745b04SAneesh Kumar K.V 	}
49775e745b04SAneesh Kumar K.V 	if (cpa) {
49785e745b04SAneesh Kumar K.V 		ext4_mb_use_group_pa(ac, cpa);
49794fca8f07SRitesh Harjani 		return true;
4980c9de560dSAlex Tomas 	}
49814fca8f07SRitesh Harjani 	return false;
4982c9de560dSAlex Tomas }
4983c9de560dSAlex Tomas 
4984c9de560dSAlex Tomas /*
4985c9de560dSAlex Tomas  * the function goes through all preallocation in this group and marks them
4986c9de560dSAlex Tomas  * used in in-core bitmap. buddy must be generated from this bitmap
4987955ce5f5SAneesh Kumar K.V  * Need to be called with ext4 group lock held
4988c9de560dSAlex Tomas  */
4989089ceeccSEric Sandeen static noinline_for_stack
4990089ceeccSEric Sandeen void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
4991c9de560dSAlex Tomas 					ext4_group_t group)
4992c9de560dSAlex Tomas {
4993c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
4994c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
4995c9de560dSAlex Tomas 	struct list_head *cur;
4996c9de560dSAlex Tomas 	ext4_group_t groupnr;
4997c9de560dSAlex Tomas 	ext4_grpblk_t start;
4998c9de560dSAlex Tomas 	int preallocated = 0;
4999c9de560dSAlex Tomas 	int len;
5000c9de560dSAlex Tomas 
50015354b2afSTheodore Ts'o 	if (!grp)
50025354b2afSTheodore Ts'o 		return;
50035354b2afSTheodore Ts'o 
5004c9de560dSAlex Tomas 	/* all form of preallocation discards first load group,
5005c9de560dSAlex Tomas 	 * so the only competing code is preallocation use.
5006c9de560dSAlex Tomas 	 * we don't need any locking here
5007c9de560dSAlex Tomas 	 * notice we do NOT ignore preallocations with pa_deleted
5008c9de560dSAlex Tomas 	 * otherwise we could leave used blocks available for
5009c9de560dSAlex Tomas 	 * allocation in buddy when concurrent ext4_mb_put_pa()
5010c9de560dSAlex Tomas 	 * is dropping preallocation
5011c9de560dSAlex Tomas 	 */
5012c9de560dSAlex Tomas 	list_for_each(cur, &grp->bb_prealloc_list) {
5013c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
5014c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
5015c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5016c9de560dSAlex Tomas 					     &groupnr, &start);
5017c9de560dSAlex Tomas 		len = pa->pa_len;
5018c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
5019c9de560dSAlex Tomas 		if (unlikely(len == 0))
5020c9de560dSAlex Tomas 			continue;
5021c9de560dSAlex Tomas 		BUG_ON(groupnr != group);
5022123e3016SRitesh Harjani 		mb_set_bits(bitmap, start, len);
5023c9de560dSAlex Tomas 		preallocated += len;
5024c9de560dSAlex Tomas 	}
5025d3df1453SRitesh Harjani 	mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
5026c9de560dSAlex Tomas }
5027c9de560dSAlex Tomas 
502827bc446eSbrookxu static void ext4_mb_mark_pa_deleted(struct super_block *sb,
502927bc446eSbrookxu 				    struct ext4_prealloc_space *pa)
503027bc446eSbrookxu {
503127bc446eSbrookxu 	struct ext4_inode_info *ei;
503227bc446eSbrookxu 
503327bc446eSbrookxu 	if (pa->pa_deleted) {
503427bc446eSbrookxu 		ext4_warning(sb, "deleted pa, type:%d, pblk:%llu, lblk:%u, len:%d\n",
503527bc446eSbrookxu 			     pa->pa_type, pa->pa_pstart, pa->pa_lstart,
503627bc446eSbrookxu 			     pa->pa_len);
503727bc446eSbrookxu 		return;
503827bc446eSbrookxu 	}
503927bc446eSbrookxu 
504027bc446eSbrookxu 	pa->pa_deleted = 1;
504127bc446eSbrookxu 
504227bc446eSbrookxu 	if (pa->pa_type == MB_INODE_PA) {
504327bc446eSbrookxu 		ei = EXT4_I(pa->pa_inode);
504427bc446eSbrookxu 		atomic_dec(&ei->i_prealloc_active);
504527bc446eSbrookxu 	}
504627bc446eSbrookxu }
504727bc446eSbrookxu 
504882089725SOjaswin Mujoo static inline void ext4_mb_pa_free(struct ext4_prealloc_space *pa)
5049c9de560dSAlex Tomas {
505082089725SOjaswin Mujoo 	BUG_ON(!pa);
50514e8d2139SJunho Ryu 	BUG_ON(atomic_read(&pa->pa_count));
50524e8d2139SJunho Ryu 	BUG_ON(pa->pa_deleted == 0);
5053c9de560dSAlex Tomas 	kmem_cache_free(ext4_pspace_cachep, pa);
5054c9de560dSAlex Tomas }
5055c9de560dSAlex Tomas 
505682089725SOjaswin Mujoo static void ext4_mb_pa_callback(struct rcu_head *head)
505782089725SOjaswin Mujoo {
505882089725SOjaswin Mujoo 	struct ext4_prealloc_space *pa;
505982089725SOjaswin Mujoo 
506082089725SOjaswin Mujoo 	pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
506182089725SOjaswin Mujoo 	ext4_mb_pa_free(pa);
506282089725SOjaswin Mujoo }
506382089725SOjaswin Mujoo 
5064c9de560dSAlex Tomas /*
5065c9de560dSAlex Tomas  * drops a reference to preallocated space descriptor
5066c9de560dSAlex Tomas  * if this was the last reference and the space is consumed
5067c9de560dSAlex Tomas  */
5068c9de560dSAlex Tomas static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
5069c9de560dSAlex Tomas 			struct super_block *sb, struct ext4_prealloc_space *pa)
5070c9de560dSAlex Tomas {
5071a9df9a49STheodore Ts'o 	ext4_group_t grp;
5072d33a1976SEric Sandeen 	ext4_fsblk_t grp_blk;
507338727786SOjaswin Mujoo 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
5074c9de560dSAlex Tomas 
5075c9de560dSAlex Tomas 	/* in this short window concurrent discard can set pa_deleted */
5076c9de560dSAlex Tomas 	spin_lock(&pa->pa_lock);
50774e8d2139SJunho Ryu 	if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
50784e8d2139SJunho Ryu 		spin_unlock(&pa->pa_lock);
50794e8d2139SJunho Ryu 		return;
50804e8d2139SJunho Ryu 	}
50814e8d2139SJunho Ryu 
5082c9de560dSAlex Tomas 	if (pa->pa_deleted == 1) {
5083c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
5084c9de560dSAlex Tomas 		return;
5085c9de560dSAlex Tomas 	}
5086c9de560dSAlex Tomas 
508727bc446eSbrookxu 	ext4_mb_mark_pa_deleted(sb, pa);
5088c9de560dSAlex Tomas 	spin_unlock(&pa->pa_lock);
5089c9de560dSAlex Tomas 
5090d33a1976SEric Sandeen 	grp_blk = pa->pa_pstart;
5091cc0fb9adSAneesh Kumar K.V 	/*
5092cc0fb9adSAneesh Kumar K.V 	 * If doing group-based preallocation, pa_pstart may be in the
5093cc0fb9adSAneesh Kumar K.V 	 * next group when pa is used up
5094cc0fb9adSAneesh Kumar K.V 	 */
5095cc0fb9adSAneesh Kumar K.V 	if (pa->pa_type == MB_GROUP_PA)
5096d33a1976SEric Sandeen 		grp_blk--;
5097d33a1976SEric Sandeen 
5098bd86298eSLukas Czerner 	grp = ext4_get_group_number(sb, grp_blk);
5099c9de560dSAlex Tomas 
5100c9de560dSAlex Tomas 	/*
5101c9de560dSAlex Tomas 	 * possible race:
5102c9de560dSAlex Tomas 	 *
5103c9de560dSAlex Tomas 	 *  P1 (buddy init)			P2 (regular allocation)
5104c9de560dSAlex Tomas 	 *					find block B in PA
5105c9de560dSAlex Tomas 	 *  copy on-disk bitmap to buddy
5106c9de560dSAlex Tomas 	 *  					mark B in on-disk bitmap
5107c9de560dSAlex Tomas 	 *					drop PA from group
5108c9de560dSAlex Tomas 	 *  mark all PAs in buddy
5109c9de560dSAlex Tomas 	 *
5110c9de560dSAlex Tomas 	 * thus, P1 initializes buddy with B available. to prevent this
5111c9de560dSAlex Tomas 	 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
5112c9de560dSAlex Tomas 	 * against that pair
5113c9de560dSAlex Tomas 	 */
5114c9de560dSAlex Tomas 	ext4_lock_group(sb, grp);
5115c9de560dSAlex Tomas 	list_del(&pa->pa_group_list);
5116c9de560dSAlex Tomas 	ext4_unlock_group(sb, grp);
5117c9de560dSAlex Tomas 
5118a8e38fd3SOjaswin Mujoo 	if (pa->pa_type == MB_INODE_PA) {
511938727786SOjaswin Mujoo 		write_lock(pa->pa_node_lock.inode_lock);
512038727786SOjaswin Mujoo 		rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
512138727786SOjaswin Mujoo 		write_unlock(pa->pa_node_lock.inode_lock);
512238727786SOjaswin Mujoo 		ext4_mb_pa_free(pa);
5123a8e38fd3SOjaswin Mujoo 	} else {
5124a8e38fd3SOjaswin Mujoo 		spin_lock(pa->pa_node_lock.lg_lock);
5125a8e38fd3SOjaswin Mujoo 		list_del_rcu(&pa->pa_node.lg_list);
5126a8e38fd3SOjaswin Mujoo 		spin_unlock(pa->pa_node_lock.lg_lock);
512738727786SOjaswin Mujoo 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
512838727786SOjaswin Mujoo 	}
5129a8e38fd3SOjaswin Mujoo }
5130c9de560dSAlex Tomas 
513138727786SOjaswin Mujoo static void ext4_mb_pa_rb_insert(struct rb_root *root, struct rb_node *new)
513238727786SOjaswin Mujoo {
513338727786SOjaswin Mujoo 	struct rb_node **iter = &root->rb_node, *parent = NULL;
513438727786SOjaswin Mujoo 	struct ext4_prealloc_space *iter_pa, *new_pa;
513538727786SOjaswin Mujoo 	ext4_lblk_t iter_start, new_start;
513638727786SOjaswin Mujoo 
513738727786SOjaswin Mujoo 	while (*iter) {
513838727786SOjaswin Mujoo 		iter_pa = rb_entry(*iter, struct ext4_prealloc_space,
513938727786SOjaswin Mujoo 				   pa_node.inode_node);
514038727786SOjaswin Mujoo 		new_pa = rb_entry(new, struct ext4_prealloc_space,
514138727786SOjaswin Mujoo 				   pa_node.inode_node);
514238727786SOjaswin Mujoo 		iter_start = iter_pa->pa_lstart;
514338727786SOjaswin Mujoo 		new_start = new_pa->pa_lstart;
514438727786SOjaswin Mujoo 
514538727786SOjaswin Mujoo 		parent = *iter;
514638727786SOjaswin Mujoo 		if (new_start < iter_start)
514738727786SOjaswin Mujoo 			iter = &((*iter)->rb_left);
514838727786SOjaswin Mujoo 		else
514938727786SOjaswin Mujoo 			iter = &((*iter)->rb_right);
515038727786SOjaswin Mujoo 	}
515138727786SOjaswin Mujoo 
515238727786SOjaswin Mujoo 	rb_link_node(new, parent, iter);
515338727786SOjaswin Mujoo 	rb_insert_color(new, root);
5154c9de560dSAlex Tomas }
5155c9de560dSAlex Tomas 
5156c9de560dSAlex Tomas /*
5157c9de560dSAlex Tomas  * creates new preallocated space for given inode
5158c9de560dSAlex Tomas  */
515953f86b17SRitesh Harjani static noinline_for_stack void
51604ddfef7bSEric Sandeen ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
5161c9de560dSAlex Tomas {
5162c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
516353accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5164c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
5165c9de560dSAlex Tomas 	struct ext4_group_info *grp;
5166c9de560dSAlex Tomas 	struct ext4_inode_info *ei;
5167c9de560dSAlex Tomas 
5168c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
5169c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5170c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5171c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
517253f86b17SRitesh Harjani 	BUG_ON(ac->ac_pa == NULL);
5173c9de560dSAlex Tomas 
517453f86b17SRitesh Harjani 	pa = ac->ac_pa;
5175c9de560dSAlex Tomas 
51767e170922SOjaswin Mujoo 	if (ac->ac_b_ex.fe_len < ac->ac_orig_goal_len) {
5177bc056e71SBaokun Li 		struct ext4_free_extent ex = {
5178bc056e71SBaokun Li 			.fe_logical = ac->ac_g_ex.fe_logical,
5179bc056e71SBaokun Li 			.fe_len = ac->ac_orig_goal_len,
5180bc056e71SBaokun Li 		};
5181bc056e71SBaokun Li 		loff_t orig_goal_end = extent_logical_end(sbi, &ex);
51824fbf8bc7SBaokun Li 		loff_t o_ex_end = extent_logical_end(sbi, &ac->ac_o_ex);
5183c9de560dSAlex Tomas 
51844fbf8bc7SBaokun Li 		/*
51854fbf8bc7SBaokun Li 		 * We can't allocate as much as normalizer wants, so we try
51864fbf8bc7SBaokun Li 		 * to get proper lstart to cover the original request, except
51874fbf8bc7SBaokun Li 		 * when the goal doesn't cover the original request as below:
51884fbf8bc7SBaokun Li 		 *
51894fbf8bc7SBaokun Li 		 * orig_ex:2045/2055(10), isize:8417280 -> normalized:0/2048
51904fbf8bc7SBaokun Li 		 * best_ex:0/200(200) -> adjusted: 1848/2048(200)
51914fbf8bc7SBaokun Li 		 */
5192c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
5193c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
5194c9de560dSAlex Tomas 
519593cdf49fSOjaswin Mujoo 		/*
519693cdf49fSOjaswin Mujoo 		 * Use the below logic for adjusting best extent as it keeps
519793cdf49fSOjaswin Mujoo 		 * fragmentation in check while ensuring logical range of best
519893cdf49fSOjaswin Mujoo 		 * extent doesn't overflow out of goal extent:
519993cdf49fSOjaswin Mujoo 		 *
52007e170922SOjaswin Mujoo 		 * 1. Check if best ex can be kept at end of goal (before
52017e170922SOjaswin Mujoo 		 *    cr_best_avail trimmed it) and still cover original start
520293cdf49fSOjaswin Mujoo 		 * 2. Else, check if best ex can be kept at start of goal and
52034fbf8bc7SBaokun Li 		 *    still cover original end
520493cdf49fSOjaswin Mujoo 		 * 3. Else, keep the best ex at start of original request.
520593cdf49fSOjaswin Mujoo 		 */
5206bc056e71SBaokun Li 		ex.fe_len = ac->ac_b_ex.fe_len;
5207bc056e71SBaokun Li 
5208bc056e71SBaokun Li 		ex.fe_logical = orig_goal_end - EXT4_C2B(sbi, ex.fe_len);
5209bc056e71SBaokun Li 		if (ac->ac_o_ex.fe_logical >= ex.fe_logical)
521093cdf49fSOjaswin Mujoo 			goto adjust_bex;
5211c9de560dSAlex Tomas 
5212bc056e71SBaokun Li 		ex.fe_logical = ac->ac_g_ex.fe_logical;
52134fbf8bc7SBaokun Li 		if (o_ex_end <= extent_logical_end(sbi, &ex))
521493cdf49fSOjaswin Mujoo 			goto adjust_bex;
5215c9de560dSAlex Tomas 
5216bc056e71SBaokun Li 		ex.fe_logical = ac->ac_o_ex.fe_logical;
521793cdf49fSOjaswin Mujoo adjust_bex:
5218bc056e71SBaokun Li 		ac->ac_b_ex.fe_logical = ex.fe_logical;
5219c9de560dSAlex Tomas 
5220c9de560dSAlex Tomas 		BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
5221bc056e71SBaokun Li 		BUG_ON(extent_logical_end(sbi, &ex) > orig_goal_end);
5222c9de560dSAlex Tomas 	}
5223c9de560dSAlex Tomas 
5224c9de560dSAlex Tomas 	pa->pa_lstart = ac->ac_b_ex.fe_logical;
5225c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5226c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
5227c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
5228c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
5229d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
5230c9de560dSAlex Tomas 	pa->pa_deleted = 0;
5231cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_INODE_PA;
5232c9de560dSAlex Tomas 
5233d3df1453SRitesh Harjani 	mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5234d3df1453SRitesh Harjani 		 pa->pa_len, pa->pa_lstart);
52359bffad1eSTheodore Ts'o 	trace_ext4_mb_new_inode_pa(ac, pa);
5236c9de560dSAlex Tomas 
523753accfa9STheodore Ts'o 	atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
5238abc075d4SKemeng Shi 	ext4_mb_use_inode_pa(ac, pa);
5239c9de560dSAlex Tomas 
5240c9de560dSAlex Tomas 	ei = EXT4_I(ac->ac_inode);
5241c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
52425354b2afSTheodore Ts'o 	if (!grp)
52435354b2afSTheodore Ts'o 		return;
5244c9de560dSAlex Tomas 
5245a8e38fd3SOjaswin Mujoo 	pa->pa_node_lock.inode_lock = &ei->i_prealloc_lock;
5246c9de560dSAlex Tomas 	pa->pa_inode = ac->ac_inode;
5247c9de560dSAlex Tomas 
5248c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5249c9de560dSAlex Tomas 
525038727786SOjaswin Mujoo 	write_lock(pa->pa_node_lock.inode_lock);
525138727786SOjaswin Mujoo 	ext4_mb_pa_rb_insert(&ei->i_prealloc_node, &pa->pa_node.inode_node);
525238727786SOjaswin Mujoo 	write_unlock(pa->pa_node_lock.inode_lock);
525327bc446eSbrookxu 	atomic_inc(&ei->i_prealloc_active);
5254c9de560dSAlex Tomas }
5255c9de560dSAlex Tomas 
5256c9de560dSAlex Tomas /*
5257c9de560dSAlex Tomas  * creates new preallocated space for locality group inodes belongs to
5258c9de560dSAlex Tomas  */
525953f86b17SRitesh Harjani static noinline_for_stack void
52604ddfef7bSEric Sandeen ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
5261c9de560dSAlex Tomas {
5262c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
5263c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
5264c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
5265c9de560dSAlex Tomas 	struct ext4_group_info *grp;
5266c9de560dSAlex Tomas 
5267c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
5268c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5269c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5270c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
527153f86b17SRitesh Harjani 	BUG_ON(ac->ac_pa == NULL);
5272c9de560dSAlex Tomas 
527353f86b17SRitesh Harjani 	pa = ac->ac_pa;
5274c9de560dSAlex Tomas 
5275c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5276c9de560dSAlex Tomas 	pa->pa_lstart = pa->pa_pstart;
5277c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
5278c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
5279c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
5280a8e38fd3SOjaswin Mujoo 	INIT_LIST_HEAD(&pa->pa_node.lg_list);
5281d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
5282c9de560dSAlex Tomas 	pa->pa_deleted = 0;
5283cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_GROUP_PA;
5284c9de560dSAlex Tomas 
5285d3df1453SRitesh Harjani 	mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5286d3df1453SRitesh Harjani 		 pa->pa_len, pa->pa_lstart);
52879bffad1eSTheodore Ts'o 	trace_ext4_mb_new_group_pa(ac, pa);
5288c9de560dSAlex Tomas 
5289c9de560dSAlex Tomas 	ext4_mb_use_group_pa(ac, pa);
5290c9de560dSAlex Tomas 	atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
5291c9de560dSAlex Tomas 
5292c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
52935354b2afSTheodore Ts'o 	if (!grp)
52945354b2afSTheodore Ts'o 		return;
5295c9de560dSAlex Tomas 	lg = ac->ac_lg;
5296c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
5297c9de560dSAlex Tomas 
5298a8e38fd3SOjaswin Mujoo 	pa->pa_node_lock.lg_lock = &lg->lg_prealloc_lock;
5299c9de560dSAlex Tomas 	pa->pa_inode = NULL;
5300c9de560dSAlex Tomas 
5301c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5302c9de560dSAlex Tomas 
53036be2ded1SAneesh Kumar K.V 	/*
53046be2ded1SAneesh Kumar K.V 	 * We will later add the new pa to the right bucket
53056be2ded1SAneesh Kumar K.V 	 * after updating the pa_free in ext4_mb_release_context
53066be2ded1SAneesh Kumar K.V 	 */
5307c9de560dSAlex Tomas }
5308c9de560dSAlex Tomas 
530953f86b17SRitesh Harjani static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
5310c9de560dSAlex Tomas {
5311c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
531253f86b17SRitesh Harjani 		ext4_mb_new_group_pa(ac);
5313c9de560dSAlex Tomas 	else
531453f86b17SRitesh Harjani 		ext4_mb_new_inode_pa(ac);
5315c9de560dSAlex Tomas }
5316c9de560dSAlex Tomas 
5317c9de560dSAlex Tomas /*
5318c9de560dSAlex Tomas  * finds all unused blocks in on-disk bitmap, frees them in
5319c9de560dSAlex Tomas  * in-core bitmap and buddy.
5320c9de560dSAlex Tomas  * @pa must be unlinked from inode and group lists, so that
5321c9de560dSAlex Tomas  * nobody else can find/use it.
5322c9de560dSAlex Tomas  * the caller MUST hold group/inode locks.
5323c9de560dSAlex Tomas  * TODO: optimize the case when there are no in-core structures yet
5324c9de560dSAlex Tomas  */
5325820c2808SKemeng Shi static noinline_for_stack void
53264ddfef7bSEric Sandeen ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
53273e1e5f50SEric Sandeen 			struct ext4_prealloc_space *pa)
5328c9de560dSAlex Tomas {
5329c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
5330c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5331498e5f24STheodore Ts'o 	unsigned int end;
5332498e5f24STheodore Ts'o 	unsigned int next;
5333c9de560dSAlex Tomas 	ext4_group_t group;
5334c9de560dSAlex Tomas 	ext4_grpblk_t bit;
5335ba80b101STheodore Ts'o 	unsigned long long grp_blk_start;
5336c9de560dSAlex Tomas 	int free = 0;
5337c9de560dSAlex Tomas 
5338c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
5339c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
534053accfa9STheodore Ts'o 	grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
5341c9de560dSAlex Tomas 	BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
5342c9de560dSAlex Tomas 	end = bit + pa->pa_len;
5343c9de560dSAlex Tomas 
5344c9de560dSAlex Tomas 	while (bit < end) {
5345ffad0a44SAneesh Kumar K.V 		bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
5346c9de560dSAlex Tomas 		if (bit >= end)
5347c9de560dSAlex Tomas 			break;
5348ffad0a44SAneesh Kumar K.V 		next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
5349d3df1453SRitesh Harjani 		mb_debug(sb, "free preallocated %u/%u in group %u\n",
53505a0790c2SAndi Kleen 			 (unsigned) ext4_group_first_block_no(sb, group) + bit,
53515a0790c2SAndi Kleen 			 (unsigned) next - bit, (unsigned) group);
5352c9de560dSAlex Tomas 		free += next - bit;
5353c9de560dSAlex Tomas 
53543e1e5f50SEric Sandeen 		trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
535553accfa9STheodore Ts'o 		trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
535653accfa9STheodore Ts'o 						    EXT4_C2B(sbi, bit)),
5357a9c667f8SLukas Czerner 					       next - bit);
5358c9de560dSAlex Tomas 		mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
5359c9de560dSAlex Tomas 		bit = next + 1;
5360c9de560dSAlex Tomas 	}
5361c9de560dSAlex Tomas 	if (free != pa->pa_free) {
53629d8b9ec4STheodore Ts'o 		ext4_msg(e4b->bd_sb, KERN_CRIT,
536336bad423SRitesh Harjani 			 "pa %p: logic %lu, phys. %lu, len %d",
5364c9de560dSAlex Tomas 			 pa, (unsigned long) pa->pa_lstart,
5365c9de560dSAlex Tomas 			 (unsigned long) pa->pa_pstart,
536636bad423SRitesh Harjani 			 pa->pa_len);
5367e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
536826346ff6SAneesh Kumar K.V 					free, pa->pa_free);
5369e56eb659SAneesh Kumar K.V 		/*
5370e56eb659SAneesh Kumar K.V 		 * pa is already deleted so we use the value obtained
5371e56eb659SAneesh Kumar K.V 		 * from the bitmap and continue.
5372e56eb659SAneesh Kumar K.V 		 */
5373c9de560dSAlex Tomas 	}
5374c9de560dSAlex Tomas 	atomic_add(free, &sbi->s_mb_discarded);
5375c9de560dSAlex Tomas }
5376c9de560dSAlex Tomas 
537720427949SKemeng Shi static noinline_for_stack void
53784ddfef7bSEric Sandeen ext4_mb_release_group_pa(struct ext4_buddy *e4b,
53793e1e5f50SEric Sandeen 				struct ext4_prealloc_space *pa)
5380c9de560dSAlex Tomas {
5381c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
5382c9de560dSAlex Tomas 	ext4_group_t group;
5383c9de560dSAlex Tomas 	ext4_grpblk_t bit;
5384c9de560dSAlex Tomas 
538560e07cf5SYongqiang Yang 	trace_ext4_mb_release_group_pa(sb, pa);
5386c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
5387c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
5388463808f2STheodore Ts'o 	if (unlikely(group != e4b->bd_group && pa->pa_len != 0)) {
5389463808f2STheodore Ts'o 		ext4_warning(sb, "bad group: expected %u, group %u, pa_start %llu",
5390463808f2STheodore Ts'o 			     e4b->bd_group, group, pa->pa_pstart);
539120427949SKemeng Shi 		return;
5392463808f2STheodore Ts'o 	}
5393c9de560dSAlex Tomas 	mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
5394c9de560dSAlex Tomas 	atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
53953e1e5f50SEric Sandeen 	trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
5396c9de560dSAlex Tomas }
5397c9de560dSAlex Tomas 
5398c9de560dSAlex Tomas /*
5399c9de560dSAlex Tomas  * releases all preallocations in given group
5400c9de560dSAlex Tomas  *
5401c9de560dSAlex Tomas  * first, we need to decide discard policy:
5402c9de560dSAlex Tomas  * - when do we discard
5403c9de560dSAlex Tomas  *   1) ENOSPC
5404c9de560dSAlex Tomas  * - how many do we discard
5405c9de560dSAlex Tomas  *   1) how many requested
5406c9de560dSAlex Tomas  */
54074ddfef7bSEric Sandeen static noinline_for_stack int
54084ddfef7bSEric Sandeen ext4_mb_discard_group_preallocations(struct super_block *sb,
54098c80fb31SChunguang Xu 				     ext4_group_t group, int *busy)
5410c9de560dSAlex Tomas {
5411c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
5412c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
5413c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
54140f6bc579SRuan Jinjie 	LIST_HEAD(list);
5415c9de560dSAlex Tomas 	struct ext4_buddy e4b;
541638727786SOjaswin Mujoo 	struct ext4_inode_info *ei;
5417c9de560dSAlex Tomas 	int err;
54188c80fb31SChunguang Xu 	int free = 0;
5419c9de560dSAlex Tomas 
54205354b2afSTheodore Ts'o 	if (!grp)
54215354b2afSTheodore Ts'o 		return 0;
5422d3df1453SRitesh Harjani 	mb_debug(sb, "discard preallocation for group %u\n", group);
5423c9de560dSAlex Tomas 	if (list_empty(&grp->bb_prealloc_list))
5424bbc4ec77SRitesh Harjani 		goto out_dbg;
5425c9de560dSAlex Tomas 
5426574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, group);
54279008a58eSDarrick J. Wong 	if (IS_ERR(bitmap_bh)) {
54289008a58eSDarrick J. Wong 		err = PTR_ERR(bitmap_bh);
542954d3adbcSTheodore Ts'o 		ext4_error_err(sb, -err,
543054d3adbcSTheodore Ts'o 			       "Error %d reading block bitmap for %u",
54319008a58eSDarrick J. Wong 			       err, group);
5432bbc4ec77SRitesh Harjani 		goto out_dbg;
5433c9de560dSAlex Tomas 	}
5434c9de560dSAlex Tomas 
5435c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(sb, group, &e4b);
5436ce89f46cSAneesh Kumar K.V 	if (err) {
54379651e6b2SKonstantin Khlebnikov 		ext4_warning(sb, "Error %d loading buddy information for %u",
54389651e6b2SKonstantin Khlebnikov 			     err, group);
5439ce89f46cSAneesh Kumar K.V 		put_bh(bitmap_bh);
5440bbc4ec77SRitesh Harjani 		goto out_dbg;
5441ce89f46cSAneesh Kumar K.V 	}
5442c9de560dSAlex Tomas 
5443c9de560dSAlex Tomas 	ext4_lock_group(sb, group);
5444c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp,
5445c9de560dSAlex Tomas 				&grp->bb_prealloc_list, pa_group_list) {
5446c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
5447c9de560dSAlex Tomas 		if (atomic_read(&pa->pa_count)) {
5448c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
54498c80fb31SChunguang Xu 			*busy = 1;
5450c9de560dSAlex Tomas 			continue;
5451c9de560dSAlex Tomas 		}
5452c9de560dSAlex Tomas 		if (pa->pa_deleted) {
5453c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
5454c9de560dSAlex Tomas 			continue;
5455c9de560dSAlex Tomas 		}
5456c9de560dSAlex Tomas 
5457c9de560dSAlex Tomas 		/* seems this one can be freed ... */
545827bc446eSbrookxu 		ext4_mb_mark_pa_deleted(sb, pa);
5459c9de560dSAlex Tomas 
546070022da8SYe Bin 		if (!free)
546170022da8SYe Bin 			this_cpu_inc(discard_pa_seq);
546270022da8SYe Bin 
5463c9de560dSAlex Tomas 		/* we can trust pa_free ... */
5464c9de560dSAlex Tomas 		free += pa->pa_free;
5465c9de560dSAlex Tomas 
5466c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
5467c9de560dSAlex Tomas 
5468c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
5469c9de560dSAlex Tomas 		list_add(&pa->u.pa_tmp_list, &list);
5470c9de560dSAlex Tomas 	}
5471c9de560dSAlex Tomas 
5472c9de560dSAlex Tomas 	/* now free all selected PAs */
5473c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5474c9de560dSAlex Tomas 
5475c9de560dSAlex Tomas 		/* remove from object (inode or locality group) */
5476a8e38fd3SOjaswin Mujoo 		if (pa->pa_type == MB_GROUP_PA) {
5477a8e38fd3SOjaswin Mujoo 			spin_lock(pa->pa_node_lock.lg_lock);
5478a8e38fd3SOjaswin Mujoo 			list_del_rcu(&pa->pa_node.lg_list);
5479a8e38fd3SOjaswin Mujoo 			spin_unlock(pa->pa_node_lock.lg_lock);
5480a8e38fd3SOjaswin Mujoo 		} else {
548138727786SOjaswin Mujoo 			write_lock(pa->pa_node_lock.inode_lock);
548238727786SOjaswin Mujoo 			ei = EXT4_I(pa->pa_inode);
548338727786SOjaswin Mujoo 			rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
548438727786SOjaswin Mujoo 			write_unlock(pa->pa_node_lock.inode_lock);
5485a8e38fd3SOjaswin Mujoo 		}
5486c9de560dSAlex Tomas 
5487c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
548838727786SOjaswin Mujoo 
548938727786SOjaswin Mujoo 		if (pa->pa_type == MB_GROUP_PA) {
549038727786SOjaswin Mujoo 			ext4_mb_release_group_pa(&e4b, pa);
5491c9de560dSAlex Tomas 			call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
549238727786SOjaswin Mujoo 		} else {
549338727786SOjaswin Mujoo 			ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
549438727786SOjaswin Mujoo 			ext4_mb_pa_free(pa);
549538727786SOjaswin Mujoo 		}
5496c9de560dSAlex Tomas 	}
5497c9de560dSAlex Tomas 
5498c9de560dSAlex Tomas 	ext4_unlock_group(sb, group);
5499e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
5500c9de560dSAlex Tomas 	put_bh(bitmap_bh);
5501bbc4ec77SRitesh Harjani out_dbg:
5502d3df1453SRitesh Harjani 	mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
55038c80fb31SChunguang Xu 		 free, group, grp->bb_free);
55048c80fb31SChunguang Xu 	return free;
5505c9de560dSAlex Tomas }
5506c9de560dSAlex Tomas 
5507c9de560dSAlex Tomas /*
5508c9de560dSAlex Tomas  * releases all non-used preallocated blocks for given inode
5509c9de560dSAlex Tomas  *
5510c9de560dSAlex Tomas  * It's important to discard preallocations under i_data_sem
5511c9de560dSAlex Tomas  * We don't want another block to be served from the prealloc
5512c9de560dSAlex Tomas  * space when we are discarding the inode prealloc space.
5513c9de560dSAlex Tomas  *
5514c9de560dSAlex Tomas  * FIXME!! Make sure it is valid at all the call sites
5515c9de560dSAlex Tomas  */
55162ffd2a6aSKemeng Shi void ext4_discard_preallocations(struct inode *inode)
5517c9de560dSAlex Tomas {
5518c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(inode);
5519c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
5520c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
5521c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
5522c9de560dSAlex Tomas 	ext4_group_t group = 0;
55230f6bc579SRuan Jinjie 	LIST_HEAD(list);
5524c9de560dSAlex Tomas 	struct ext4_buddy e4b;
552538727786SOjaswin Mujoo 	struct rb_node *iter;
5526c9de560dSAlex Tomas 	int err;
5527c9de560dSAlex Tomas 
5528f0e54b60SKemeng Shi 	if (!S_ISREG(inode->i_mode))
5529c9de560dSAlex Tomas 		return;
5530c9de560dSAlex Tomas 
55318016e29fSHarshad Shirwadkar 	if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
55328016e29fSHarshad Shirwadkar 		return;
55338016e29fSHarshad Shirwadkar 
5534d3df1453SRitesh Harjani 	mb_debug(sb, "discard preallocation for inode %lu\n",
5535d3df1453SRitesh Harjani 		 inode->i_ino);
553627bc446eSbrookxu 	trace_ext4_discard_preallocations(inode,
5537f0e54b60SKemeng Shi 			atomic_read(&ei->i_prealloc_active));
553827bc446eSbrookxu 
5539c9de560dSAlex Tomas repeat:
5540c9de560dSAlex Tomas 	/* first, collect all pa's in the inode */
554138727786SOjaswin Mujoo 	write_lock(&ei->i_prealloc_lock);
55422ffd2a6aSKemeng Shi 	for (iter = rb_first(&ei->i_prealloc_node); iter;
554338727786SOjaswin Mujoo 	     iter = rb_next(iter)) {
554438727786SOjaswin Mujoo 		pa = rb_entry(iter, struct ext4_prealloc_space,
554538727786SOjaswin Mujoo 			      pa_node.inode_node);
5546a8e38fd3SOjaswin Mujoo 		BUG_ON(pa->pa_node_lock.inode_lock != &ei->i_prealloc_lock);
554738727786SOjaswin Mujoo 
5548c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
5549c9de560dSAlex Tomas 		if (atomic_read(&pa->pa_count)) {
5550c9de560dSAlex Tomas 			/* this shouldn't happen often - nobody should
5551c9de560dSAlex Tomas 			 * use preallocation while we're discarding it */
5552c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
555338727786SOjaswin Mujoo 			write_unlock(&ei->i_prealloc_lock);
55549d8b9ec4STheodore Ts'o 			ext4_msg(sb, KERN_ERR,
55559d8b9ec4STheodore Ts'o 				 "uh-oh! used pa while discarding");
5556c9de560dSAlex Tomas 			WARN_ON(1);
5557c9de560dSAlex Tomas 			schedule_timeout_uninterruptible(HZ);
5558c9de560dSAlex Tomas 			goto repeat;
5559c9de560dSAlex Tomas 
5560c9de560dSAlex Tomas 		}
5561c9de560dSAlex Tomas 		if (pa->pa_deleted == 0) {
556227bc446eSbrookxu 			ext4_mb_mark_pa_deleted(sb, pa);
5563c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
556438727786SOjaswin Mujoo 			rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5565c9de560dSAlex Tomas 			list_add(&pa->u.pa_tmp_list, &list);
5566c9de560dSAlex Tomas 			continue;
5567c9de560dSAlex Tomas 		}
5568c9de560dSAlex Tomas 
5569c9de560dSAlex Tomas 		/* someone is deleting pa right now */
5570c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
557138727786SOjaswin Mujoo 		write_unlock(&ei->i_prealloc_lock);
5572c9de560dSAlex Tomas 
5573c9de560dSAlex Tomas 		/* we have to wait here because pa_deleted
5574c9de560dSAlex Tomas 		 * doesn't mean pa is already unlinked from
5575c9de560dSAlex Tomas 		 * the list. as we might be called from
5576c9de560dSAlex Tomas 		 * ->clear_inode() the inode will get freed
5577c9de560dSAlex Tomas 		 * and concurrent thread which is unlinking
5578c9de560dSAlex Tomas 		 * pa from inode's list may access already
5579c9de560dSAlex Tomas 		 * freed memory, bad-bad-bad */
5580c9de560dSAlex Tomas 
5581c9de560dSAlex Tomas 		/* XXX: if this happens too often, we can
5582c9de560dSAlex Tomas 		 * add a flag to force wait only in case
5583c9de560dSAlex Tomas 		 * of ->clear_inode(), but not in case of
5584c9de560dSAlex Tomas 		 * regular truncate */
5585c9de560dSAlex Tomas 		schedule_timeout_uninterruptible(HZ);
5586c9de560dSAlex Tomas 		goto repeat;
5587c9de560dSAlex Tomas 	}
558838727786SOjaswin Mujoo 	write_unlock(&ei->i_prealloc_lock);
5589c9de560dSAlex Tomas 
5590c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5591cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_INODE_PA);
5592bd86298eSLukas Czerner 		group = ext4_get_group_number(sb, pa->pa_pstart);
5593c9de560dSAlex Tomas 
55949651e6b2SKonstantin Khlebnikov 		err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
55959651e6b2SKonstantin Khlebnikov 					     GFP_NOFS|__GFP_NOFAIL);
5596ce89f46cSAneesh Kumar K.V 		if (err) {
559754d3adbcSTheodore Ts'o 			ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
55989651e6b2SKonstantin Khlebnikov 				       err, group);
5599ce89f46cSAneesh Kumar K.V 			continue;
5600ce89f46cSAneesh Kumar K.V 		}
5601c9de560dSAlex Tomas 
5602574ca174STheodore Ts'o 		bitmap_bh = ext4_read_block_bitmap(sb, group);
56039008a58eSDarrick J. Wong 		if (IS_ERR(bitmap_bh)) {
56049008a58eSDarrick J. Wong 			err = PTR_ERR(bitmap_bh);
560554d3adbcSTheodore Ts'o 			ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
56069008a58eSDarrick J. Wong 				       err, group);
5607e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
5608ce89f46cSAneesh Kumar K.V 			continue;
5609c9de560dSAlex Tomas 		}
5610c9de560dSAlex Tomas 
5611c9de560dSAlex Tomas 		ext4_lock_group(sb, group);
5612c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
56133e1e5f50SEric Sandeen 		ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
5614c9de560dSAlex Tomas 		ext4_unlock_group(sb, group);
5615c9de560dSAlex Tomas 
5616e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
5617c9de560dSAlex Tomas 		put_bh(bitmap_bh);
5618c9de560dSAlex Tomas 
5619c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
562038727786SOjaswin Mujoo 		ext4_mb_pa_free(pa);
5621c9de560dSAlex Tomas 	}
5622c9de560dSAlex Tomas }
5623c9de560dSAlex Tomas 
562453f86b17SRitesh Harjani static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
562553f86b17SRitesh Harjani {
562653f86b17SRitesh Harjani 	struct ext4_prealloc_space *pa;
562753f86b17SRitesh Harjani 
562853f86b17SRitesh Harjani 	BUG_ON(ext4_pspace_cachep == NULL);
562953f86b17SRitesh Harjani 	pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
563053f86b17SRitesh Harjani 	if (!pa)
563153f86b17SRitesh Harjani 		return -ENOMEM;
563253f86b17SRitesh Harjani 	atomic_set(&pa->pa_count, 1);
563353f86b17SRitesh Harjani 	ac->ac_pa = pa;
563453f86b17SRitesh Harjani 	return 0;
563553f86b17SRitesh Harjani }
563653f86b17SRitesh Harjani 
563782089725SOjaswin Mujoo static void ext4_mb_pa_put_free(struct ext4_allocation_context *ac)
563853f86b17SRitesh Harjani {
563953f86b17SRitesh Harjani 	struct ext4_prealloc_space *pa = ac->ac_pa;
564053f86b17SRitesh Harjani 
564153f86b17SRitesh Harjani 	BUG_ON(!pa);
564253f86b17SRitesh Harjani 	ac->ac_pa = NULL;
564353f86b17SRitesh Harjani 	WARN_ON(!atomic_dec_and_test(&pa->pa_count));
564482089725SOjaswin Mujoo 	/*
564582089725SOjaswin Mujoo 	 * current function is only called due to an error or due to
564682089725SOjaswin Mujoo 	 * len of found blocks < len of requested blocks hence the PA has not
564782089725SOjaswin Mujoo 	 * been added to grp->bb_prealloc_list. So we don't need to lock it
564882089725SOjaswin Mujoo 	 */
564982089725SOjaswin Mujoo 	pa->pa_deleted = 1;
565082089725SOjaswin Mujoo 	ext4_mb_pa_free(pa);
565153f86b17SRitesh Harjani }
565253f86b17SRitesh Harjani 
56536ba495e9STheodore Ts'o #ifdef CONFIG_EXT4_DEBUG
5654e68cf40cSRitesh Harjani static inline void ext4_mb_show_pa(struct super_block *sb)
5655c9de560dSAlex Tomas {
5656e68cf40cSRitesh Harjani 	ext4_group_t i, ngroups;
5657c9de560dSAlex Tomas 
565895257987SJan Kara 	if (ext4_forced_shutdown(sb))
5659e3570639SEric Sandeen 		return;
5660e3570639SEric Sandeen 
56618df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
5662d3df1453SRitesh Harjani 	mb_debug(sb, "groups: ");
56638df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
5664c9de560dSAlex Tomas 		struct ext4_group_info *grp = ext4_get_group_info(sb, i);
5665c9de560dSAlex Tomas 		struct ext4_prealloc_space *pa;
5666c9de560dSAlex Tomas 		ext4_grpblk_t start;
5667c9de560dSAlex Tomas 		struct list_head *cur;
56685354b2afSTheodore Ts'o 
56695354b2afSTheodore Ts'o 		if (!grp)
56705354b2afSTheodore Ts'o 			continue;
5671c9de560dSAlex Tomas 		ext4_lock_group(sb, i);
5672c9de560dSAlex Tomas 		list_for_each(cur, &grp->bb_prealloc_list) {
5673c9de560dSAlex Tomas 			pa = list_entry(cur, struct ext4_prealloc_space,
5674c9de560dSAlex Tomas 					pa_group_list);
5675c9de560dSAlex Tomas 			spin_lock(&pa->pa_lock);
5676c9de560dSAlex Tomas 			ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5677c9de560dSAlex Tomas 						     NULL, &start);
5678c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
5679d3df1453SRitesh Harjani 			mb_debug(sb, "PA:%u:%d:%d\n", i, start,
5680d3df1453SRitesh Harjani 				 pa->pa_len);
5681c9de560dSAlex Tomas 		}
568260bd63d1SSolofo Ramangalahy 		ext4_unlock_group(sb, i);
5683d3df1453SRitesh Harjani 		mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
5684d3df1453SRitesh Harjani 			 grp->bb_fragments);
5685c9de560dSAlex Tomas 	}
5686c9de560dSAlex Tomas }
5687e68cf40cSRitesh Harjani 
5688e68cf40cSRitesh Harjani static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5689e68cf40cSRitesh Harjani {
5690e68cf40cSRitesh Harjani 	struct super_block *sb = ac->ac_sb;
5691e68cf40cSRitesh Harjani 
569295257987SJan Kara 	if (ext4_forced_shutdown(sb))
5693e68cf40cSRitesh Harjani 		return;
5694e68cf40cSRitesh Harjani 
5695d3df1453SRitesh Harjani 	mb_debug(sb, "Can't allocate:"
5696e68cf40cSRitesh Harjani 			" Allocation context details:");
5697d3df1453SRitesh Harjani 	mb_debug(sb, "status %u flags 0x%x",
5698e68cf40cSRitesh Harjani 			ac->ac_status, ac->ac_flags);
5699d3df1453SRitesh Harjani 	mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
5700e68cf40cSRitesh Harjani 			"goal %lu/%lu/%lu@%lu, "
5701e68cf40cSRitesh Harjani 			"best %lu/%lu/%lu@%lu cr %d",
5702e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_group,
5703e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_start,
5704e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_len,
5705e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_logical,
5706e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_group,
5707e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_start,
5708e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_len,
5709e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_logical,
5710e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_group,
5711e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_start,
5712e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_len,
5713e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_logical,
5714e68cf40cSRitesh Harjani 			(int)ac->ac_criteria);
5715d3df1453SRitesh Harjani 	mb_debug(sb, "%u found", ac->ac_found);
5716569f196fSRitesh Harjani 	mb_debug(sb, "used pa: %s, ", ac->ac_pa ? "yes" : "no");
5717569f196fSRitesh Harjani 	if (ac->ac_pa)
5718569f196fSRitesh Harjani 		mb_debug(sb, "pa_type %s\n", ac->ac_pa->pa_type == MB_GROUP_PA ?
5719569f196fSRitesh Harjani 			 "group pa" : "inode pa");
5720e68cf40cSRitesh Harjani 	ext4_mb_show_pa(sb);
5721e68cf40cSRitesh Harjani }
5722c9de560dSAlex Tomas #else
5723e68cf40cSRitesh Harjani static inline void ext4_mb_show_pa(struct super_block *sb)
5724e68cf40cSRitesh Harjani {
5725e68cf40cSRitesh Harjani }
5726c9de560dSAlex Tomas static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5727c9de560dSAlex Tomas {
5728e68cf40cSRitesh Harjani 	ext4_mb_show_pa(ac->ac_sb);
5729c9de560dSAlex Tomas }
5730c9de560dSAlex Tomas #endif
5731c9de560dSAlex Tomas 
5732c9de560dSAlex Tomas /*
5733c9de560dSAlex Tomas  * We use locality group preallocation for small size file. The size of the
5734c9de560dSAlex Tomas  * file is determined by the current size or the resulting size after
5735c9de560dSAlex Tomas  * allocation which ever is larger
5736c9de560dSAlex Tomas  *
5737b713a5ecSTheodore Ts'o  * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
5738c9de560dSAlex Tomas  */
5739c9de560dSAlex Tomas static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
5740c9de560dSAlex Tomas {
5741c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
5742c9de560dSAlex Tomas 	int bsbits = ac->ac_sb->s_blocksize_bits;
5743c9de560dSAlex Tomas 	loff_t size, isize;
5744a9f2a293SJan Kara 	bool inode_pa_eligible, group_pa_eligible;
5745c9de560dSAlex Tomas 
5746c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
5747c9de560dSAlex Tomas 		return;
5748c9de560dSAlex Tomas 
57494ba74d00STheodore Ts'o 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
57504ba74d00STheodore Ts'o 		return;
57514ba74d00STheodore Ts'o 
5752a9f2a293SJan Kara 	group_pa_eligible = sbi->s_mb_group_prealloc > 0;
5753a9f2a293SJan Kara 	inode_pa_eligible = true;
575443bbddc0SBaokun Li 	size = extent_logical_end(sbi, &ac->ac_o_ex);
575550797481STheodore Ts'o 	isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
575650797481STheodore Ts'o 		>> bsbits;
5757c9de560dSAlex Tomas 
5758a9f2a293SJan Kara 	/* No point in using inode preallocation for closed files */
575982dd124cSNikolay Borisov 	if ((size == isize) && !ext4_fs_is_busy(sbi) &&
5760a9f2a293SJan Kara 	    !inode_is_open_for_write(ac->ac_inode))
5761a9f2a293SJan Kara 		inode_pa_eligible = false;
576250797481STheodore Ts'o 
576371780577STheodore Ts'o 	size = max(size, isize);
5764a9f2a293SJan Kara 	/* Don't use group allocation for large files */
5765a9f2a293SJan Kara 	if (size > sbi->s_mb_stream_request)
5766a9f2a293SJan Kara 		group_pa_eligible = false;
5767a9f2a293SJan Kara 
5768a9f2a293SJan Kara 	if (!group_pa_eligible) {
5769a9f2a293SJan Kara 		if (inode_pa_eligible)
57704ba74d00STheodore Ts'o 			ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
5771a9f2a293SJan Kara 		else
5772a9f2a293SJan Kara 			ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
5773c9de560dSAlex Tomas 		return;
57744ba74d00STheodore Ts'o 	}
5775c9de560dSAlex Tomas 
5776c9de560dSAlex Tomas 	BUG_ON(ac->ac_lg != NULL);
5777c9de560dSAlex Tomas 	/*
5778c9de560dSAlex Tomas 	 * locality group prealloc space are per cpu. The reason for having
5779c9de560dSAlex Tomas 	 * per cpu locality group is to reduce the contention between block
5780c9de560dSAlex Tomas 	 * request from multiple CPUs.
5781c9de560dSAlex Tomas 	 */
5782a0b6bc63SChristoph Lameter 	ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
5783c9de560dSAlex Tomas 
5784c9de560dSAlex Tomas 	/* we're going to use group allocation */
5785c9de560dSAlex Tomas 	ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
5786c9de560dSAlex Tomas 
5787c9de560dSAlex Tomas 	/* serialize all allocations in the group */
5788c9de560dSAlex Tomas 	mutex_lock(&ac->ac_lg->lg_mutex);
5789c9de560dSAlex Tomas }
5790c9de560dSAlex Tomas 
5791d73eff68SGuoqing Jiang static noinline_for_stack void
57924ddfef7bSEric Sandeen ext4_mb_initialize_context(struct ext4_allocation_context *ac,
5793c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
5794c9de560dSAlex Tomas {
5795c9de560dSAlex Tomas 	struct super_block *sb = ar->inode->i_sb;
5796c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5797c9de560dSAlex Tomas 	struct ext4_super_block *es = sbi->s_es;
5798c9de560dSAlex Tomas 	ext4_group_t group;
5799498e5f24STheodore Ts'o 	unsigned int len;
5800498e5f24STheodore Ts'o 	ext4_fsblk_t goal;
5801c9de560dSAlex Tomas 	ext4_grpblk_t block;
5802c9de560dSAlex Tomas 
5803c9de560dSAlex Tomas 	/* we can't allocate > group size */
5804c9de560dSAlex Tomas 	len = ar->len;
5805c9de560dSAlex Tomas 
5806c9de560dSAlex Tomas 	/* just a dirty hack to filter too big requests  */
580740ae3487STheodore Ts'o 	if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
580840ae3487STheodore Ts'o 		len = EXT4_CLUSTERS_PER_GROUP(sb);
5809c9de560dSAlex Tomas 
5810c9de560dSAlex Tomas 	/* start searching from the goal */
5811c9de560dSAlex Tomas 	goal = ar->goal;
5812c9de560dSAlex Tomas 	if (goal < le32_to_cpu(es->s_first_data_block) ||
5813c9de560dSAlex Tomas 			goal >= ext4_blocks_count(es))
5814c9de560dSAlex Tomas 		goal = le32_to_cpu(es->s_first_data_block);
5815c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, goal, &group, &block);
5816c9de560dSAlex Tomas 
5817c9de560dSAlex Tomas 	/* set up allocation goals */
5818f5a44db5STheodore Ts'o 	ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
5819c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_CONTINUE;
5820c9de560dSAlex Tomas 	ac->ac_sb = sb;
5821c9de560dSAlex Tomas 	ac->ac_inode = ar->inode;
582253accfa9STheodore Ts'o 	ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
5823c9de560dSAlex Tomas 	ac->ac_o_ex.fe_group = group;
5824c9de560dSAlex Tomas 	ac->ac_o_ex.fe_start = block;
5825c9de560dSAlex Tomas 	ac->ac_o_ex.fe_len = len;
582653accfa9STheodore Ts'o 	ac->ac_g_ex = ac->ac_o_ex;
58277e170922SOjaswin Mujoo 	ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
5828c9de560dSAlex Tomas 	ac->ac_flags = ar->flags;
5829c9de560dSAlex Tomas 
58303cb77bd2Sbrookxu 	/* we have to define context: we'll work with a file or
5831c9de560dSAlex Tomas 	 * locality group. this is a policy, actually */
5832c9de560dSAlex Tomas 	ext4_mb_group_or_file(ac);
5833c9de560dSAlex Tomas 
5834d3df1453SRitesh Harjani 	mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
5835c9de560dSAlex Tomas 			"left: %u/%u, right %u/%u to %swritable\n",
5836c9de560dSAlex Tomas 			(unsigned) ar->len, (unsigned) ar->logical,
5837c9de560dSAlex Tomas 			(unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
5838c9de560dSAlex Tomas 			(unsigned) ar->lleft, (unsigned) ar->pleft,
5839c9de560dSAlex Tomas 			(unsigned) ar->lright, (unsigned) ar->pright,
584082dd124cSNikolay Borisov 			inode_is_open_for_write(ar->inode) ? "" : "non-");
5841c9de560dSAlex Tomas }
5842c9de560dSAlex Tomas 
58436be2ded1SAneesh Kumar K.V static noinline_for_stack void
58446be2ded1SAneesh Kumar K.V ext4_mb_discard_lg_preallocations(struct super_block *sb,
58456be2ded1SAneesh Kumar K.V 					struct ext4_locality_group *lg,
58466be2ded1SAneesh Kumar K.V 					int order, int total_entries)
58476be2ded1SAneesh Kumar K.V {
58486be2ded1SAneesh Kumar K.V 	ext4_group_t group = 0;
58496be2ded1SAneesh Kumar K.V 	struct ext4_buddy e4b;
58500f6bc579SRuan Jinjie 	LIST_HEAD(discard_list);
58516be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa, *tmp;
58526be2ded1SAneesh Kumar K.V 
5853d3df1453SRitesh Harjani 	mb_debug(sb, "discard locality group preallocation\n");
58546be2ded1SAneesh Kumar K.V 
58556be2ded1SAneesh Kumar K.V 	spin_lock(&lg->lg_prealloc_lock);
58566be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
5857a8e38fd3SOjaswin Mujoo 				pa_node.lg_list,
585892e9c58cSMadhuparna Bhowmik 				lockdep_is_held(&lg->lg_prealloc_lock)) {
58596be2ded1SAneesh Kumar K.V 		spin_lock(&pa->pa_lock);
58606be2ded1SAneesh Kumar K.V 		if (atomic_read(&pa->pa_count)) {
58616be2ded1SAneesh Kumar K.V 			/*
58626be2ded1SAneesh Kumar K.V 			 * This is the pa that we just used
58636be2ded1SAneesh Kumar K.V 			 * for block allocation. So don't
58646be2ded1SAneesh Kumar K.V 			 * free that
58656be2ded1SAneesh Kumar K.V 			 */
58666be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
58676be2ded1SAneesh Kumar K.V 			continue;
58686be2ded1SAneesh Kumar K.V 		}
58696be2ded1SAneesh Kumar K.V 		if (pa->pa_deleted) {
58706be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
58716be2ded1SAneesh Kumar K.V 			continue;
58726be2ded1SAneesh Kumar K.V 		}
58736be2ded1SAneesh Kumar K.V 		/* only lg prealloc space */
5874cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_GROUP_PA);
58756be2ded1SAneesh Kumar K.V 
58766be2ded1SAneesh Kumar K.V 		/* seems this one can be freed ... */
587727bc446eSbrookxu 		ext4_mb_mark_pa_deleted(sb, pa);
58786be2ded1SAneesh Kumar K.V 		spin_unlock(&pa->pa_lock);
58796be2ded1SAneesh Kumar K.V 
5880a8e38fd3SOjaswin Mujoo 		list_del_rcu(&pa->pa_node.lg_list);
58816be2ded1SAneesh Kumar K.V 		list_add(&pa->u.pa_tmp_list, &discard_list);
58826be2ded1SAneesh Kumar K.V 
58836be2ded1SAneesh Kumar K.V 		total_entries--;
58846be2ded1SAneesh Kumar K.V 		if (total_entries <= 5) {
58856be2ded1SAneesh Kumar K.V 			/*
58866be2ded1SAneesh Kumar K.V 			 * we want to keep only 5 entries
58876be2ded1SAneesh Kumar K.V 			 * allowing it to grow to 8. This
58886be2ded1SAneesh Kumar K.V 			 * mak sure we don't call discard
58896be2ded1SAneesh Kumar K.V 			 * soon for this list.
58906be2ded1SAneesh Kumar K.V 			 */
58916be2ded1SAneesh Kumar K.V 			break;
58926be2ded1SAneesh Kumar K.V 		}
58936be2ded1SAneesh Kumar K.V 	}
58946be2ded1SAneesh Kumar K.V 	spin_unlock(&lg->lg_prealloc_lock);
58956be2ded1SAneesh Kumar K.V 
58966be2ded1SAneesh Kumar K.V 	list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
58979651e6b2SKonstantin Khlebnikov 		int err;
58986be2ded1SAneesh Kumar K.V 
5899bd86298eSLukas Czerner 		group = ext4_get_group_number(sb, pa->pa_pstart);
59009651e6b2SKonstantin Khlebnikov 		err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
59019651e6b2SKonstantin Khlebnikov 					     GFP_NOFS|__GFP_NOFAIL);
59029651e6b2SKonstantin Khlebnikov 		if (err) {
590354d3adbcSTheodore Ts'o 			ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
59049651e6b2SKonstantin Khlebnikov 				       err, group);
59056be2ded1SAneesh Kumar K.V 			continue;
59066be2ded1SAneesh Kumar K.V 		}
59076be2ded1SAneesh Kumar K.V 		ext4_lock_group(sb, group);
59086be2ded1SAneesh Kumar K.V 		list_del(&pa->pa_group_list);
59093e1e5f50SEric Sandeen 		ext4_mb_release_group_pa(&e4b, pa);
59106be2ded1SAneesh Kumar K.V 		ext4_unlock_group(sb, group);
59116be2ded1SAneesh Kumar K.V 
5912e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
59136be2ded1SAneesh Kumar K.V 		list_del(&pa->u.pa_tmp_list);
59146be2ded1SAneesh Kumar K.V 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
59156be2ded1SAneesh Kumar K.V 	}
59166be2ded1SAneesh Kumar K.V }
59176be2ded1SAneesh Kumar K.V 
59186be2ded1SAneesh Kumar K.V /*
59196be2ded1SAneesh Kumar K.V  * We have incremented pa_count. So it cannot be freed at this
59206be2ded1SAneesh Kumar K.V  * point. Also we hold lg_mutex. So no parallel allocation is
59216be2ded1SAneesh Kumar K.V  * possible from this lg. That means pa_free cannot be updated.
59226be2ded1SAneesh Kumar K.V  *
59236be2ded1SAneesh Kumar K.V  * A parallel ext4_mb_discard_group_preallocations is possible.
59246be2ded1SAneesh Kumar K.V  * which can cause the lg_prealloc_list to be updated.
59256be2ded1SAneesh Kumar K.V  */
59266be2ded1SAneesh Kumar K.V 
59276be2ded1SAneesh Kumar K.V static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
59286be2ded1SAneesh Kumar K.V {
59296be2ded1SAneesh Kumar K.V 	int order, added = 0, lg_prealloc_count = 1;
59306be2ded1SAneesh Kumar K.V 	struct super_block *sb = ac->ac_sb;
59316be2ded1SAneesh Kumar K.V 	struct ext4_locality_group *lg = ac->ac_lg;
59326be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
59336be2ded1SAneesh Kumar K.V 
59346be2ded1SAneesh Kumar K.V 	order = fls(pa->pa_free) - 1;
59356be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
59366be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
59376be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
59386be2ded1SAneesh Kumar K.V 	/* Add the prealloc space to lg */
5939f1167009SNiu Yawei 	spin_lock(&lg->lg_prealloc_lock);
59406be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
5941a8e38fd3SOjaswin Mujoo 				pa_node.lg_list,
594292e9c58cSMadhuparna Bhowmik 				lockdep_is_held(&lg->lg_prealloc_lock)) {
59436be2ded1SAneesh Kumar K.V 		spin_lock(&tmp_pa->pa_lock);
59446be2ded1SAneesh Kumar K.V 		if (tmp_pa->pa_deleted) {
5945e7c9e3e9STheodore Ts'o 			spin_unlock(&tmp_pa->pa_lock);
59466be2ded1SAneesh Kumar K.V 			continue;
59476be2ded1SAneesh Kumar K.V 		}
59486be2ded1SAneesh Kumar K.V 		if (!added && pa->pa_free < tmp_pa->pa_free) {
59496be2ded1SAneesh Kumar K.V 			/* Add to the tail of the previous entry */
5950a8e38fd3SOjaswin Mujoo 			list_add_tail_rcu(&pa->pa_node.lg_list,
5951a8e38fd3SOjaswin Mujoo 						&tmp_pa->pa_node.lg_list);
59526be2ded1SAneesh Kumar K.V 			added = 1;
59536be2ded1SAneesh Kumar K.V 			/*
59546be2ded1SAneesh Kumar K.V 			 * we want to count the total
59556be2ded1SAneesh Kumar K.V 			 * number of entries in the list
59566be2ded1SAneesh Kumar K.V 			 */
59576be2ded1SAneesh Kumar K.V 		}
59586be2ded1SAneesh Kumar K.V 		spin_unlock(&tmp_pa->pa_lock);
59596be2ded1SAneesh Kumar K.V 		lg_prealloc_count++;
59606be2ded1SAneesh Kumar K.V 	}
59616be2ded1SAneesh Kumar K.V 	if (!added)
5962a8e38fd3SOjaswin Mujoo 		list_add_tail_rcu(&pa->pa_node.lg_list,
59636be2ded1SAneesh Kumar K.V 					&lg->lg_prealloc_list[order]);
5964f1167009SNiu Yawei 	spin_unlock(&lg->lg_prealloc_lock);
59656be2ded1SAneesh Kumar K.V 
59666be2ded1SAneesh Kumar K.V 	/* Now trim the list to be not more than 8 elements */
5967ad635507SKemeng Shi 	if (lg_prealloc_count > 8)
59686be2ded1SAneesh Kumar K.V 		ext4_mb_discard_lg_preallocations(sb, lg,
59696be2ded1SAneesh Kumar K.V 						  order, lg_prealloc_count);
59706be2ded1SAneesh Kumar K.V }
59716be2ded1SAneesh Kumar K.V 
5972c9de560dSAlex Tomas /*
5973c9de560dSAlex Tomas  * release all resource we used in allocation
5974c9de560dSAlex Tomas  */
597511fd1a5dSKemeng Shi static void ext4_mb_release_context(struct ext4_allocation_context *ac)
5976c9de560dSAlex Tomas {
597753accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
59786be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa = ac->ac_pa;
59796be2ded1SAneesh Kumar K.V 	if (pa) {
5980cc0fb9adSAneesh Kumar K.V 		if (pa->pa_type == MB_GROUP_PA) {
5981c9de560dSAlex Tomas 			/* see comment in ext4_mb_use_group_pa() */
59826be2ded1SAneesh Kumar K.V 			spin_lock(&pa->pa_lock);
598353accfa9STheodore Ts'o 			pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
598453accfa9STheodore Ts'o 			pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
59856be2ded1SAneesh Kumar K.V 			pa->pa_free -= ac->ac_b_ex.fe_len;
59866be2ded1SAneesh Kumar K.V 			pa->pa_len -= ac->ac_b_ex.fe_len;
59876be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
598866d5e027Sbrookxu 
59896be2ded1SAneesh Kumar K.V 			/*
59906be2ded1SAneesh Kumar K.V 			 * We want to add the pa to the right bucket.
59916be2ded1SAneesh Kumar K.V 			 * Remove it from the list and while adding
59926be2ded1SAneesh Kumar K.V 			 * make sure the list to which we are adding
599344183d42SAmir Goldstein 			 * doesn't grow big.
59946be2ded1SAneesh Kumar K.V 			 */
599566d5e027Sbrookxu 			if (likely(pa->pa_free)) {
5996a8e38fd3SOjaswin Mujoo 				spin_lock(pa->pa_node_lock.lg_lock);
5997a8e38fd3SOjaswin Mujoo 				list_del_rcu(&pa->pa_node.lg_list);
5998a8e38fd3SOjaswin Mujoo 				spin_unlock(pa->pa_node_lock.lg_lock);
59996be2ded1SAneesh Kumar K.V 				ext4_mb_add_n_trim(ac);
6000c9de560dSAlex Tomas 			}
600166d5e027Sbrookxu 		}
600227bc446eSbrookxu 
60036be2ded1SAneesh Kumar K.V 		ext4_mb_put_pa(ac, ac->ac_sb, pa);
6004c9de560dSAlex Tomas 	}
6005c9de560dSAlex Tomas 	if (ac->ac_bitmap_page)
600609cbfeafSKirill A. Shutemov 		put_page(ac->ac_bitmap_page);
6007c9de560dSAlex Tomas 	if (ac->ac_buddy_page)
600809cbfeafSKirill A. Shutemov 		put_page(ac->ac_buddy_page);
6009c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
6010c9de560dSAlex Tomas 		mutex_unlock(&ac->ac_lg->lg_mutex);
6011c9de560dSAlex Tomas 	ext4_mb_collect_stats(ac);
6012c9de560dSAlex Tomas }
6013c9de560dSAlex Tomas 
6014c9de560dSAlex Tomas static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
6015c9de560dSAlex Tomas {
60168df9675fSTheodore Ts'o 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
6017c9de560dSAlex Tomas 	int ret;
60188c80fb31SChunguang Xu 	int freed = 0, busy = 0;
60198c80fb31SChunguang Xu 	int retry = 0;
6020c9de560dSAlex Tomas 
60219bffad1eSTheodore Ts'o 	trace_ext4_mb_discard_preallocations(sb, needed);
60228c80fb31SChunguang Xu 
60238c80fb31SChunguang Xu 	if (needed == 0)
60248c80fb31SChunguang Xu 		needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
60258c80fb31SChunguang Xu  repeat:
60268df9675fSTheodore Ts'o 	for (i = 0; i < ngroups && needed > 0; i++) {
60278c80fb31SChunguang Xu 		ret = ext4_mb_discard_group_preallocations(sb, i, &busy);
6028c9de560dSAlex Tomas 		freed += ret;
6029c9de560dSAlex Tomas 		needed -= ret;
60308c80fb31SChunguang Xu 		cond_resched();
60318c80fb31SChunguang Xu 	}
60328c80fb31SChunguang Xu 
60338c80fb31SChunguang Xu 	if (needed > 0 && busy && ++retry < 3) {
60348c80fb31SChunguang Xu 		busy = 0;
60358c80fb31SChunguang Xu 		goto repeat;
6036c9de560dSAlex Tomas 	}
6037c9de560dSAlex Tomas 
6038c9de560dSAlex Tomas 	return freed;
6039c9de560dSAlex Tomas }
6040c9de560dSAlex Tomas 
6041cf5e2ca6SRitesh Harjani static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
604207b5b8e1SRitesh Harjani 			struct ext4_allocation_context *ac, u64 *seq)
6043cf5e2ca6SRitesh Harjani {
6044cf5e2ca6SRitesh Harjani 	int freed;
604507b5b8e1SRitesh Harjani 	u64 seq_retry = 0;
604607b5b8e1SRitesh Harjani 	bool ret = false;
6047cf5e2ca6SRitesh Harjani 
6048cf5e2ca6SRitesh Harjani 	freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
604907b5b8e1SRitesh Harjani 	if (freed) {
605007b5b8e1SRitesh Harjani 		ret = true;
605107b5b8e1SRitesh Harjani 		goto out_dbg;
605207b5b8e1SRitesh Harjani 	}
605307b5b8e1SRitesh Harjani 	seq_retry = ext4_get_discard_pa_seq_sum();
605499377830SRitesh Harjani 	if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
605599377830SRitesh Harjani 		ac->ac_flags |= EXT4_MB_STRICT_CHECK;
605607b5b8e1SRitesh Harjani 		*seq = seq_retry;
605707b5b8e1SRitesh Harjani 		ret = true;
605807b5b8e1SRitesh Harjani 	}
605907b5b8e1SRitesh Harjani 
606007b5b8e1SRitesh Harjani out_dbg:
606107b5b8e1SRitesh Harjani 	mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
606207b5b8e1SRitesh Harjani 	return ret;
6063cf5e2ca6SRitesh Harjani }
6064cf5e2ca6SRitesh Harjani 
6065ad78b5efSKemeng Shi /*
6066ad78b5efSKemeng Shi  * Simple allocator for Ext4 fast commit replay path. It searches for blocks
6067ad78b5efSKemeng Shi  * linearly starting at the goal block and also excludes the blocks which
6068ad78b5efSKemeng Shi  * are going to be in use after fast commit replay.
6069ad78b5efSKemeng Shi  */
6070ad78b5efSKemeng Shi static ext4_fsblk_t
6071ad78b5efSKemeng Shi ext4_mb_new_blocks_simple(struct ext4_allocation_request *ar, int *errp)
6072ad78b5efSKemeng Shi {
6073ad78b5efSKemeng Shi 	struct buffer_head *bitmap_bh;
6074ad78b5efSKemeng Shi 	struct super_block *sb = ar->inode->i_sb;
6075ad78b5efSKemeng Shi 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6076ad78b5efSKemeng Shi 	ext4_group_t group, nr;
6077ad78b5efSKemeng Shi 	ext4_grpblk_t blkoff;
6078ad78b5efSKemeng Shi 	ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
6079ad78b5efSKemeng Shi 	ext4_grpblk_t i = 0;
6080ad78b5efSKemeng Shi 	ext4_fsblk_t goal, block;
608179ebf48cSLu Hongfei 	struct ext4_super_block *es = sbi->s_es;
6082ad78b5efSKemeng Shi 
6083ad78b5efSKemeng Shi 	goal = ar->goal;
6084ad78b5efSKemeng Shi 	if (goal < le32_to_cpu(es->s_first_data_block) ||
6085ad78b5efSKemeng Shi 			goal >= ext4_blocks_count(es))
6086ad78b5efSKemeng Shi 		goal = le32_to_cpu(es->s_first_data_block);
6087ad78b5efSKemeng Shi 
6088ad78b5efSKemeng Shi 	ar->len = 0;
6089ad78b5efSKemeng Shi 	ext4_get_group_no_and_offset(sb, goal, &group, &blkoff);
6090ad78b5efSKemeng Shi 	for (nr = ext4_get_groups_count(sb); nr > 0; nr--) {
6091ad78b5efSKemeng Shi 		bitmap_bh = ext4_read_block_bitmap(sb, group);
6092ad78b5efSKemeng Shi 		if (IS_ERR(bitmap_bh)) {
6093ad78b5efSKemeng Shi 			*errp = PTR_ERR(bitmap_bh);
6094ad78b5efSKemeng Shi 			pr_warn("Failed to read block bitmap\n");
6095ad78b5efSKemeng Shi 			return 0;
6096ad78b5efSKemeng Shi 		}
6097ad78b5efSKemeng Shi 
6098ad78b5efSKemeng Shi 		while (1) {
6099ad78b5efSKemeng Shi 			i = mb_find_next_zero_bit(bitmap_bh->b_data, max,
6100ad78b5efSKemeng Shi 						blkoff);
6101ad78b5efSKemeng Shi 			if (i >= max)
6102ad78b5efSKemeng Shi 				break;
6103ad78b5efSKemeng Shi 			if (ext4_fc_replay_check_excluded(sb,
6104ad78b5efSKemeng Shi 				ext4_group_first_block_no(sb, group) +
6105ad78b5efSKemeng Shi 				EXT4_C2B(sbi, i))) {
6106ad78b5efSKemeng Shi 				blkoff = i + 1;
6107ad78b5efSKemeng Shi 			} else
6108ad78b5efSKemeng Shi 				break;
6109ad78b5efSKemeng Shi 		}
6110ad78b5efSKemeng Shi 		brelse(bitmap_bh);
6111ad78b5efSKemeng Shi 		if (i < max)
6112ad78b5efSKemeng Shi 			break;
6113ad78b5efSKemeng Shi 
6114ad78b5efSKemeng Shi 		if (++group >= ext4_get_groups_count(sb))
6115ad78b5efSKemeng Shi 			group = 0;
6116ad78b5efSKemeng Shi 
6117ad78b5efSKemeng Shi 		blkoff = 0;
6118ad78b5efSKemeng Shi 	}
6119ad78b5efSKemeng Shi 
6120ad78b5efSKemeng Shi 	if (i >= max) {
6121ad78b5efSKemeng Shi 		*errp = -ENOSPC;
6122ad78b5efSKemeng Shi 		return 0;
6123ad78b5efSKemeng Shi 	}
6124ad78b5efSKemeng Shi 
6125ad78b5efSKemeng Shi 	block = ext4_group_first_block_no(sb, group) + EXT4_C2B(sbi, i);
6126d2f7cf40SKemeng Shi 	ext4_mb_mark_bb(sb, block, 1, true);
6127ad78b5efSKemeng Shi 	ar->len = 1;
6128ad78b5efSKemeng Shi 
6129ad78b5efSKemeng Shi 	return block;
6130ad78b5efSKemeng Shi }
61318016e29fSHarshad Shirwadkar 
6132c9de560dSAlex Tomas /*
6133c9de560dSAlex Tomas  * Main entry point into mballoc to allocate blocks
6134c9de560dSAlex Tomas  * it tries to use preallocation first, then falls back
6135c9de560dSAlex Tomas  * to usual allocation
6136c9de560dSAlex Tomas  */
6137c9de560dSAlex Tomas ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
6138c9de560dSAlex Tomas 				struct ext4_allocation_request *ar, int *errp)
6139c9de560dSAlex Tomas {
6140256bdb49SEric Sandeen 	struct ext4_allocation_context *ac = NULL;
6141c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
6142c9de560dSAlex Tomas 	struct super_block *sb;
6143c9de560dSAlex Tomas 	ext4_fsblk_t block = 0;
614460e58e0fSMingming Cao 	unsigned int inquota = 0;
614553accfa9STheodore Ts'o 	unsigned int reserv_clstrs = 0;
614680fa46d6STheodore Ts'o 	int retries = 0;
614707b5b8e1SRitesh Harjani 	u64 seq;
6148c9de560dSAlex Tomas 
6149b10a44c3STheodore Ts'o 	might_sleep();
6150c9de560dSAlex Tomas 	sb = ar->inode->i_sb;
6151c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
6152c9de560dSAlex Tomas 
61539bffad1eSTheodore Ts'o 	trace_ext4_request_blocks(ar);
61548016e29fSHarshad Shirwadkar 	if (sbi->s_mount_state & EXT4_FC_REPLAY)
6155ad78b5efSKemeng Shi 		return ext4_mb_new_blocks_simple(ar, errp);
6156ba80b101STheodore Ts'o 
615745dc63e7SDmitry Monakhov 	/* Allow to use superuser reservation for quota file */
615802749a4cSTahsin Erdogan 	if (ext4_is_quota_file(ar->inode))
615945dc63e7SDmitry Monakhov 		ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
616045dc63e7SDmitry Monakhov 
6161e3cf5d5dSTheodore Ts'o 	if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
616260e58e0fSMingming Cao 		/* Without delayed allocation we need to verify
616360e58e0fSMingming Cao 		 * there is enough free blocks to do block allocation
616460e58e0fSMingming Cao 		 * and verify allocation doesn't exceed the quota limits.
6165d2a17637SMingming Cao 		 */
616655f020dbSAllison Henderson 		while (ar->len &&
6167e7d5f315STheodore Ts'o 			ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
616855f020dbSAllison Henderson 
6169030ba6bcSAneesh Kumar K.V 			/* let others to free the space */
6170bb8b20edSLukas Czerner 			cond_resched();
6171030ba6bcSAneesh Kumar K.V 			ar->len = ar->len >> 1;
6172030ba6bcSAneesh Kumar K.V 		}
6173030ba6bcSAneesh Kumar K.V 		if (!ar->len) {
6174bbc4ec77SRitesh Harjani 			ext4_mb_show_pa(sb);
617507031431SMingming Cao 			*errp = -ENOSPC;
617607031431SMingming Cao 			return 0;
617707031431SMingming Cao 		}
617853accfa9STheodore Ts'o 		reserv_clstrs = ar->len;
617955f020dbSAllison Henderson 		if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
618053accfa9STheodore Ts'o 			dquot_alloc_block_nofail(ar->inode,
618153accfa9STheodore Ts'o 						 EXT4_C2B(sbi, ar->len));
618255f020dbSAllison Henderson 		} else {
618355f020dbSAllison Henderson 			while (ar->len &&
618453accfa9STheodore Ts'o 				dquot_alloc_block(ar->inode,
618553accfa9STheodore Ts'o 						  EXT4_C2B(sbi, ar->len))) {
618655f020dbSAllison Henderson 
6187c9de560dSAlex Tomas 				ar->flags |= EXT4_MB_HINT_NOPREALLOC;
6188c9de560dSAlex Tomas 				ar->len--;
6189c9de560dSAlex Tomas 			}
619055f020dbSAllison Henderson 		}
619160e58e0fSMingming Cao 		inquota = ar->len;
6192c9de560dSAlex Tomas 		if (ar->len == 0) {
6193c9de560dSAlex Tomas 			*errp = -EDQUOT;
61946c7a120aSAditya Kali 			goto out;
6195c9de560dSAlex Tomas 		}
619660e58e0fSMingming Cao 	}
6197d2a17637SMingming Cao 
619885556c9aSWei Yongjun 	ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
6199833576b3STheodore Ts'o 	if (!ac) {
6200363d4251SShen Feng 		ar->len = 0;
6201256bdb49SEric Sandeen 		*errp = -ENOMEM;
62026c7a120aSAditya Kali 		goto out;
6203256bdb49SEric Sandeen 	}
6204256bdb49SEric Sandeen 
6205d73eff68SGuoqing Jiang 	ext4_mb_initialize_context(ac, ar);
6206c9de560dSAlex Tomas 
6207256bdb49SEric Sandeen 	ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
620881198536SRitesh Harjani 	seq = this_cpu_read(discard_pa_seq);
6209256bdb49SEric Sandeen 	if (!ext4_mb_use_preallocated(ac)) {
6210256bdb49SEric Sandeen 		ac->ac_op = EXT4_MB_HISTORY_ALLOC;
6211256bdb49SEric Sandeen 		ext4_mb_normalize_request(ac, ar);
621253f86b17SRitesh Harjani 
621353f86b17SRitesh Harjani 		*errp = ext4_mb_pa_alloc(ac);
621453f86b17SRitesh Harjani 		if (*errp)
621553f86b17SRitesh Harjani 			goto errout;
6216c9de560dSAlex Tomas repeat:
6217c9de560dSAlex Tomas 		/* allocate space in core */
62186c7a120aSAditya Kali 		*errp = ext4_mb_regular_allocator(ac);
621953f86b17SRitesh Harjani 		/*
622053f86b17SRitesh Harjani 		 * pa allocated above is added to grp->bb_prealloc_list only
622153f86b17SRitesh Harjani 		 * when we were able to allocate some block i.e. when
622253f86b17SRitesh Harjani 		 * ac->ac_status == AC_STATUS_FOUND.
622353f86b17SRitesh Harjani 		 * And error from above mean ac->ac_status != AC_STATUS_FOUND
622453f86b17SRitesh Harjani 		 * So we have to free this pa here itself.
622553f86b17SRitesh Harjani 		 */
62262c00ef3eSAlexey Khoroshilov 		if (*errp) {
622782089725SOjaswin Mujoo 			ext4_mb_pa_put_free(ac);
62282c00ef3eSAlexey Khoroshilov 			ext4_discard_allocated_blocks(ac);
62292c00ef3eSAlexey Khoroshilov 			goto errout;
62302c00ef3eSAlexey Khoroshilov 		}
623153f86b17SRitesh Harjani 		if (ac->ac_status == AC_STATUS_FOUND &&
623253f86b17SRitesh Harjani 			ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
623382089725SOjaswin Mujoo 			ext4_mb_pa_put_free(ac);
6234c9de560dSAlex Tomas 	}
6235256bdb49SEric Sandeen 	if (likely(ac->ac_status == AC_STATUS_FOUND)) {
623653accfa9STheodore Ts'o 		*errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
6237554a5cccSVegard Nossum 		if (*errp) {
6238b844167eSCurt Wohlgemuth 			ext4_discard_allocated_blocks(ac);
62396d138cedSEric Sandeen 			goto errout;
62406d138cedSEric Sandeen 		} else {
6241256bdb49SEric Sandeen 			block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
6242256bdb49SEric Sandeen 			ar->len = ac->ac_b_ex.fe_len;
6243519deca0SAneesh Kumar K.V 		}
6244c9de560dSAlex Tomas 	} else {
624580fa46d6STheodore Ts'o 		if (++retries < 3 &&
624680fa46d6STheodore Ts'o 		    ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
6247c9de560dSAlex Tomas 			goto repeat;
624853f86b17SRitesh Harjani 		/*
624953f86b17SRitesh Harjani 		 * If block allocation fails then the pa allocated above
625053f86b17SRitesh Harjani 		 * needs to be freed here itself.
625153f86b17SRitesh Harjani 		 */
625282089725SOjaswin Mujoo 		ext4_mb_pa_put_free(ac);
6253c9de560dSAlex Tomas 		*errp = -ENOSPC;
62546c7a120aSAditya Kali 	}
62556c7a120aSAditya Kali 
62566c7a120aSAditya Kali 	if (*errp) {
6257aaae558dSKemeng Shi errout:
6258256bdb49SEric Sandeen 		ac->ac_b_ex.fe_len = 0;
6259c9de560dSAlex Tomas 		ar->len = 0;
6260256bdb49SEric Sandeen 		ext4_mb_show_ac(ac);
6261c9de560dSAlex Tomas 	}
6262256bdb49SEric Sandeen 	ext4_mb_release_context(ac);
6263363d4251SShen Feng 	kmem_cache_free(ext4_ac_cachep, ac);
6264aaae558dSKemeng Shi out:
626560e58e0fSMingming Cao 	if (inquota && ar->len < inquota)
626653accfa9STheodore Ts'o 		dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
62670087d9fbSAneesh Kumar K.V 	if (!ar->len) {
6268e3cf5d5dSTheodore Ts'o 		if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
62690087d9fbSAneesh Kumar K.V 			/* release all the reserved blocks if non delalloc */
627057042651STheodore Ts'o 			percpu_counter_sub(&sbi->s_dirtyclusters_counter,
627153accfa9STheodore Ts'o 						reserv_clstrs);
62720087d9fbSAneesh Kumar K.V 	}
6273c9de560dSAlex Tomas 
62749bffad1eSTheodore Ts'o 	trace_ext4_allocate_blocks(ar, (unsigned long long)block);
6275ba80b101STheodore Ts'o 
6276c9de560dSAlex Tomas 	return block;
6277c9de560dSAlex Tomas }
6278c9de560dSAlex Tomas 
6279c894058dSAneesh Kumar K.V /*
6280c894058dSAneesh Kumar K.V  * We can merge two free data extents only if the physical blocks
6281c894058dSAneesh Kumar K.V  * are contiguous, AND the extents were freed by the same transaction,
6282c894058dSAneesh Kumar K.V  * AND the blocks are associated with the same group.
6283c894058dSAneesh Kumar K.V  */
6284a0154344SDaeho Jeong static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
6285a0154344SDaeho Jeong 					struct ext4_free_data *entry,
6286a0154344SDaeho Jeong 					struct ext4_free_data *new_entry,
6287a0154344SDaeho Jeong 					struct rb_root *entry_rb_root)
6288c894058dSAneesh Kumar K.V {
6289a0154344SDaeho Jeong 	if ((entry->efd_tid != new_entry->efd_tid) ||
6290a0154344SDaeho Jeong 	    (entry->efd_group != new_entry->efd_group))
6291a0154344SDaeho Jeong 		return;
6292a0154344SDaeho Jeong 	if (entry->efd_start_cluster + entry->efd_count ==
6293a0154344SDaeho Jeong 	    new_entry->efd_start_cluster) {
6294a0154344SDaeho Jeong 		new_entry->efd_start_cluster = entry->efd_start_cluster;
6295a0154344SDaeho Jeong 		new_entry->efd_count += entry->efd_count;
6296a0154344SDaeho Jeong 	} else if (new_entry->efd_start_cluster + new_entry->efd_count ==
6297a0154344SDaeho Jeong 		   entry->efd_start_cluster) {
6298a0154344SDaeho Jeong 		new_entry->efd_count += entry->efd_count;
6299a0154344SDaeho Jeong 	} else
6300a0154344SDaeho Jeong 		return;
6301a0154344SDaeho Jeong 	spin_lock(&sbi->s_md_lock);
6302a0154344SDaeho Jeong 	list_del(&entry->efd_list);
6303a0154344SDaeho Jeong 	spin_unlock(&sbi->s_md_lock);
6304a0154344SDaeho Jeong 	rb_erase(&entry->efd_node, entry_rb_root);
6305a0154344SDaeho Jeong 	kmem_cache_free(ext4_free_data_cachep, entry);
6306c894058dSAneesh Kumar K.V }
6307c894058dSAneesh Kumar K.V 
630885b67ffbSKemeng Shi static noinline_for_stack void
63094ddfef7bSEric Sandeen ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
63107a2fcbf7SAneesh Kumar K.V 		      struct ext4_free_data *new_entry)
6311c9de560dSAlex Tomas {
6312e29136f8STheodore Ts'o 	ext4_group_t group = e4b->bd_group;
631384130193STheodore Ts'o 	ext4_grpblk_t cluster;
6314d08854f5STheodore Ts'o 	ext4_grpblk_t clusters = new_entry->efd_count;
63157a2fcbf7SAneesh Kumar K.V 	struct ext4_free_data *entry;
6316c9de560dSAlex Tomas 	struct ext4_group_info *db = e4b->bd_info;
6317c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
6318c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6319c894058dSAneesh Kumar K.V 	struct rb_node **n = &db->bb_free_root.rb_node, *node;
6320c894058dSAneesh Kumar K.V 	struct rb_node *parent = NULL, *new_node;
6321c894058dSAneesh Kumar K.V 
63220390131bSFrank Mayhar 	BUG_ON(!ext4_handle_valid(handle));
632399b150d8SMatthew Wilcox (Oracle) 	BUG_ON(e4b->bd_bitmap_folio == NULL);
63245eea586bSMatthew Wilcox (Oracle) 	BUG_ON(e4b->bd_buddy_folio == NULL);
6325c9de560dSAlex Tomas 
632618aadd47SBobi Jam 	new_node = &new_entry->efd_node;
632718aadd47SBobi Jam 	cluster = new_entry->efd_start_cluster;
6328c9de560dSAlex Tomas 
6329c894058dSAneesh Kumar K.V 	if (!*n) {
6330c894058dSAneesh Kumar K.V 		/* first free block exent. We need to
6331c894058dSAneesh Kumar K.V 		   protect buddy cache from being freed,
6332c9de560dSAlex Tomas 		 * otherwise we'll refresh it from
6333c9de560dSAlex Tomas 		 * on-disk bitmap and lose not-yet-available
6334c9de560dSAlex Tomas 		 * blocks */
63355eea586bSMatthew Wilcox (Oracle) 		folio_get(e4b->bd_buddy_folio);
633699b150d8SMatthew Wilcox (Oracle) 		folio_get(e4b->bd_bitmap_folio);
6337c894058dSAneesh Kumar K.V 	}
6338c894058dSAneesh Kumar K.V 	while (*n) {
6339c894058dSAneesh Kumar K.V 		parent = *n;
634018aadd47SBobi Jam 		entry = rb_entry(parent, struct ext4_free_data, efd_node);
634118aadd47SBobi Jam 		if (cluster < entry->efd_start_cluster)
6342c894058dSAneesh Kumar K.V 			n = &(*n)->rb_left;
634318aadd47SBobi Jam 		else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
6344c894058dSAneesh Kumar K.V 			n = &(*n)->rb_right;
6345c894058dSAneesh Kumar K.V 		else {
6346e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, group, 0,
634784130193STheodore Ts'o 				ext4_group_first_block_no(sb, group) +
634884130193STheodore Ts'o 				EXT4_C2B(sbi, cluster),
6349e29136f8STheodore Ts'o 				"Block already on to-be-freed list");
6350cca41553SChunguang Xu 			kmem_cache_free(ext4_free_data_cachep, new_entry);
635185b67ffbSKemeng Shi 			return;
6352c9de560dSAlex Tomas 		}
6353c9de560dSAlex Tomas 	}
6354c9de560dSAlex Tomas 
6355c894058dSAneesh Kumar K.V 	rb_link_node(new_node, parent, n);
6356c894058dSAneesh Kumar K.V 	rb_insert_color(new_node, &db->bb_free_root);
6357c894058dSAneesh Kumar K.V 
6358c894058dSAneesh Kumar K.V 	/* Now try to see the extent can be merged to left and right */
6359c894058dSAneesh Kumar K.V 	node = rb_prev(new_node);
6360c894058dSAneesh Kumar K.V 	if (node) {
636118aadd47SBobi Jam 		entry = rb_entry(node, struct ext4_free_data, efd_node);
6362a0154344SDaeho Jeong 		ext4_try_merge_freed_extent(sbi, entry, new_entry,
6363a0154344SDaeho Jeong 					    &(db->bb_free_root));
6364c9de560dSAlex Tomas 	}
6365c894058dSAneesh Kumar K.V 
6366c894058dSAneesh Kumar K.V 	node = rb_next(new_node);
6367c894058dSAneesh Kumar K.V 	if (node) {
636818aadd47SBobi Jam 		entry = rb_entry(node, struct ext4_free_data, efd_node);
6369a0154344SDaeho Jeong 		ext4_try_merge_freed_extent(sbi, entry, new_entry,
6370a0154344SDaeho Jeong 					    &(db->bb_free_root));
6371c894058dSAneesh Kumar K.V 	}
6372a0154344SDaeho Jeong 
6373d08854f5STheodore Ts'o 	spin_lock(&sbi->s_md_lock);
6374ce774e53SJinke Han 	list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list[new_entry->efd_tid & 1]);
6375d08854f5STheodore Ts'o 	sbi->s_mb_free_pending += clusters;
6376d08854f5STheodore Ts'o 	spin_unlock(&sbi->s_md_lock);
6377c9de560dSAlex Tomas }
6378c9de560dSAlex Tomas 
63798016e29fSHarshad Shirwadkar static void ext4_free_blocks_simple(struct inode *inode, ext4_fsblk_t block,
63808016e29fSHarshad Shirwadkar 					unsigned long count)
63818016e29fSHarshad Shirwadkar {
63828016e29fSHarshad Shirwadkar 	struct super_block *sb = inode->i_sb;
63838016e29fSHarshad Shirwadkar 	ext4_group_t group;
63848016e29fSHarshad Shirwadkar 	ext4_grpblk_t blkoff;
63858016e29fSHarshad Shirwadkar 
63868016e29fSHarshad Shirwadkar 	ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
6387c431d386SKemeng Shi 	ext4_mb_mark_context(NULL, sb, false, group, blkoff, count,
6388c431d386SKemeng Shi 			     EXT4_MB_BITMAP_MARKED_CHECK |
6389c431d386SKemeng Shi 			     EXT4_MB_SYNC_UPDATE,
6390c431d386SKemeng Shi 			     NULL);
63918016e29fSHarshad Shirwadkar }
63928016e29fSHarshad Shirwadkar 
639344338711STheodore Ts'o /**
63948ac3939dSRitesh Harjani  * ext4_mb_clear_bb() -- helper function for freeing blocks.
63958ac3939dSRitesh Harjani  *			Used by ext4_free_blocks()
639644338711STheodore Ts'o  * @handle:		handle for this transaction
639744338711STheodore Ts'o  * @inode:		inode
6398c60990b3STheodore Ts'o  * @block:		starting physical block to be freed
6399c60990b3STheodore Ts'o  * @count:		number of blocks to be freed
64005def1360SYongqiang Yang  * @flags:		flags used by ext4_free_blocks
6401c9de560dSAlex Tomas  */
64028ac3939dSRitesh Harjani static void ext4_mb_clear_bb(handle_t *handle, struct inode *inode,
64038ac3939dSRitesh Harjani 			       ext4_fsblk_t block, unsigned long count,
64048ac3939dSRitesh Harjani 			       int flags)
6405c9de560dSAlex Tomas {
6406c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
64075354b2afSTheodore Ts'o 	struct ext4_group_info *grp;
6408498e5f24STheodore Ts'o 	unsigned int overflow;
6409c9de560dSAlex Tomas 	ext4_grpblk_t bit;
6410c9de560dSAlex Tomas 	ext4_group_t block_group;
6411c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
6412c9de560dSAlex Tomas 	struct ext4_buddy e4b;
641384130193STheodore Ts'o 	unsigned int count_clusters;
6414c9de560dSAlex Tomas 	int err = 0;
641538b8f70cSKemeng Shi 	int mark_flags = 0;
641638b8f70cSKemeng Shi 	ext4_grpblk_t changed;
6417c9de560dSAlex Tomas 
64188016e29fSHarshad Shirwadkar 	sbi = EXT4_SB(sb);
64198016e29fSHarshad Shirwadkar 
64201e1c2b86SLukas Czerner 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
64211e1c2b86SLukas Czerner 	    !ext4_inode_block_valid(inode, block, count)) {
64221e1c2b86SLukas Czerner 		ext4_error(sb, "Freeing blocks in system zone - "
64231e1c2b86SLukas Czerner 			   "Block = %llu, count = %lu", block, count);
64241e1c2b86SLukas Czerner 		/* err = 0. ext4_std_error should be a no op */
642533e728c6SKemeng Shi 		goto error_out;
64261e1c2b86SLukas Czerner 	}
64271e1c2b86SLukas Czerner 	flags |= EXT4_FREE_BLOCKS_VALIDATED;
64281e1c2b86SLukas Czerner 
6429c9de560dSAlex Tomas do_more:
6430c9de560dSAlex Tomas 	overflow = 0;
6431c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
6432c9de560dSAlex Tomas 
64335354b2afSTheodore Ts'o 	grp = ext4_get_group_info(sb, block_group);
64345354b2afSTheodore Ts'o 	if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
6435163a203dSDarrick J. Wong 		return;
6436163a203dSDarrick J. Wong 
6437c9de560dSAlex Tomas 	/*
6438c9de560dSAlex Tomas 	 * Check to see if we are freeing blocks across a group
6439c9de560dSAlex Tomas 	 * boundary.
6440c9de560dSAlex Tomas 	 */
644184130193STheodore Ts'o 	if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
644284130193STheodore Ts'o 		overflow = EXT4_C2B(sbi, bit) + count -
644384130193STheodore Ts'o 			EXT4_BLOCKS_PER_GROUP(sb);
6444c9de560dSAlex Tomas 		count -= overflow;
64451e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
64461e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6447c9de560dSAlex Tomas 	}
6448810da240SLukas Czerner 	count_clusters = EXT4_NUM_B2C(sbi, count);
644933e728c6SKemeng Shi 	trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
645033e728c6SKemeng Shi 
645133e728c6SKemeng Shi 	/* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
645233e728c6SKemeng Shi 	err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
645333e728c6SKemeng Shi 				     GFP_NOFS|__GFP_NOFAIL);
645433e728c6SKemeng Shi 	if (err)
645533e728c6SKemeng Shi 		goto error_out;
6456c9de560dSAlex Tomas 
64571e1c2b86SLukas Czerner 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
64581e1c2b86SLukas Czerner 	    !ext4_inode_block_valid(inode, block, count)) {
645912062dddSEric Sandeen 		ext4_error(sb, "Freeing blocks in system zone - "
64600610b6e9STheodore Ts'o 			   "Block = %llu, count = %lu", block, count);
6461519deca0SAneesh Kumar K.V 		/* err = 0. ext4_std_error should be a no op */
646233e728c6SKemeng Shi 		goto error_clean;
646333e728c6SKemeng Shi 	}
646433e728c6SKemeng Shi 
6465c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
646638b8f70cSKemeng Shi 	mark_flags |= EXT4_MB_BITMAP_MARKED_CHECK;
6467c9de560dSAlex Tomas #endif
646838b8f70cSKemeng Shi 	err = ext4_mb_mark_context(handle, sb, false, block_group, bit,
646938b8f70cSKemeng Shi 				   count_clusters, mark_flags, &changed);
6470c9de560dSAlex Tomas 
647133e728c6SKemeng Shi 
647238b8f70cSKemeng Shi 	if (err && changed == 0)
647338b8f70cSKemeng Shi 		goto error_clean;
647433e728c6SKemeng Shi 
647538b8f70cSKemeng Shi #ifdef AGGRESSIVE_CHECK
647638b8f70cSKemeng Shi 	BUG_ON(changed != count_clusters);
647738b8f70cSKemeng Shi #endif
6478e6362609STheodore Ts'o 
6479f96c450dSDaeho Jeong 	/*
6480f96c450dSDaeho Jeong 	 * We need to make sure we don't reuse the freed block until after the
6481f96c450dSDaeho Jeong 	 * transaction is committed. We make an exception if the inode is to be
6482f96c450dSDaeho Jeong 	 * written in writeback mode since writeback mode has weak data
6483f96c450dSDaeho Jeong 	 * consistency guarantees.
6484f96c450dSDaeho Jeong 	 */
6485f96c450dSDaeho Jeong 	if (ext4_handle_valid(handle) &&
6486f96c450dSDaeho Jeong 	    ((flags & EXT4_FREE_BLOCKS_METADATA) ||
6487f96c450dSDaeho Jeong 	     !ext4_should_writeback_data(inode))) {
64887a2fcbf7SAneesh Kumar K.V 		struct ext4_free_data *new_entry;
64897a2fcbf7SAneesh Kumar K.V 		/*
64907444a072SMichal Hocko 		 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
64917444a072SMichal Hocko 		 * to fail.
64927a2fcbf7SAneesh Kumar K.V 		 */
64937444a072SMichal Hocko 		new_entry = kmem_cache_alloc(ext4_free_data_cachep,
64947444a072SMichal Hocko 				GFP_NOFS|__GFP_NOFAIL);
649518aadd47SBobi Jam 		new_entry->efd_start_cluster = bit;
649618aadd47SBobi Jam 		new_entry->efd_group = block_group;
649718aadd47SBobi Jam 		new_entry->efd_count = count_clusters;
649818aadd47SBobi Jam 		new_entry->efd_tid = handle->h_transaction->t_tid;
6499955ce5f5SAneesh Kumar K.V 
65007a2fcbf7SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
65017a2fcbf7SAneesh Kumar K.V 		ext4_mb_free_metadata(handle, &e4b, new_entry);
6502c9de560dSAlex Tomas 	} else {
6503d71c1ae2SLukas Czerner 		if (test_opt(sb, DISCARD)) {
6504247c3d21SKemeng Shi 			err = ext4_issue_discard(sb, block_group, bit,
65050efcd739SWenchao Hao 						 count_clusters);
6506fa606293SJan Kara 			/*
6507fa606293SJan Kara 			 * Ignore EOPNOTSUPP error. This is consistent with
6508fa606293SJan Kara 			 * what happens when using journal.
6509fa606293SJan Kara 			 */
6510fa606293SJan Kara 			if (err == -EOPNOTSUPP)
6511fa606293SJan Kara 				err = 0;
6512fa606293SJan Kara 			if (err)
6513d71c1ae2SLukas Czerner 				ext4_msg(sb, KERN_WARNING, "discard request in"
6514a00b482bSRitesh Harjani 					 " group:%u block:%d count:%lu failed"
6515d71c1ae2SLukas Czerner 					 " with %d", block_group, bit, count,
6516d71c1ae2SLukas Czerner 					 err);
65178f9ff189SLukas Czerner 		} else
65188f9ff189SLukas Czerner 			EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
6519d71c1ae2SLukas Czerner 
6520955ce5f5SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
652184130193STheodore Ts'o 		mb_free_blocks(inode, &e4b, bit, count_clusters);
6522c9de560dSAlex Tomas 	}
6523c9de560dSAlex Tomas 
6524955ce5f5SAneesh Kumar K.V 	ext4_unlock_group(sb, block_group);
6525c9de560dSAlex Tomas 
65269fe67149SEric Whitney 	/*
65279fe67149SEric Whitney 	 * on a bigalloc file system, defer the s_freeclusters_counter
65289fe67149SEric Whitney 	 * update to the caller (ext4_remove_space and friends) so they
65299fe67149SEric Whitney 	 * can determine if a cluster freed here should be rereserved
65309fe67149SEric Whitney 	 */
65319fe67149SEric Whitney 	if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
65327b415bf6SAditya Kali 		if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
65337b415bf6SAditya Kali 			dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
65349fe67149SEric Whitney 		percpu_counter_add(&sbi->s_freeclusters_counter,
65359fe67149SEric Whitney 				   count_clusters);
65369fe67149SEric Whitney 	}
65377d734532SJan Kara 
6538c9de560dSAlex Tomas 	if (overflow && !err) {
6539c9de560dSAlex Tomas 		block += count;
6540c9de560dSAlex Tomas 		count = overflow;
654133e728c6SKemeng Shi 		ext4_mb_unload_buddy(&e4b);
65421e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
65431e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6544c9de560dSAlex Tomas 		goto do_more;
6545c9de560dSAlex Tomas 	}
654633e728c6SKemeng Shi 
654733e728c6SKemeng Shi error_clean:
654833e728c6SKemeng Shi 	ext4_mb_unload_buddy(&e4b);
654933e728c6SKemeng Shi error_out:
6550c9de560dSAlex Tomas 	ext4_std_error(sb, err);
6551c9de560dSAlex Tomas }
65527360d173SLukas Czerner 
65537360d173SLukas Czerner /**
65548ac3939dSRitesh Harjani  * ext4_free_blocks() -- Free given blocks and update quota
65558ac3939dSRitesh Harjani  * @handle:		handle for this transaction
65568ac3939dSRitesh Harjani  * @inode:		inode
65578ac3939dSRitesh Harjani  * @bh:			optional buffer of the block to be freed
65588ac3939dSRitesh Harjani  * @block:		starting physical block to be freed
65598ac3939dSRitesh Harjani  * @count:		number of blocks to be freed
65608ac3939dSRitesh Harjani  * @flags:		flags used by ext4_free_blocks
65618ac3939dSRitesh Harjani  */
65628ac3939dSRitesh Harjani void ext4_free_blocks(handle_t *handle, struct inode *inode,
65638ac3939dSRitesh Harjani 		      struct buffer_head *bh, ext4_fsblk_t block,
65648ac3939dSRitesh Harjani 		      unsigned long count, int flags)
65658ac3939dSRitesh Harjani {
65668ac3939dSRitesh Harjani 	struct super_block *sb = inode->i_sb;
65678ac3939dSRitesh Harjani 	unsigned int overflow;
65688ac3939dSRitesh Harjani 	struct ext4_sb_info *sbi;
65698ac3939dSRitesh Harjani 
65708ac3939dSRitesh Harjani 	sbi = EXT4_SB(sb);
65718ac3939dSRitesh Harjani 
65728ac3939dSRitesh Harjani 	if (bh) {
65738ac3939dSRitesh Harjani 		if (block)
65748ac3939dSRitesh Harjani 			BUG_ON(block != bh->b_blocknr);
65758ac3939dSRitesh Harjani 		else
65768ac3939dSRitesh Harjani 			block = bh->b_blocknr;
65778ac3939dSRitesh Harjani 	}
65788ac3939dSRitesh Harjani 
657911b6890bSKemeng Shi 	if (sbi->s_mount_state & EXT4_FC_REPLAY) {
65802ec6d0a5SKemeng Shi 		ext4_free_blocks_simple(inode, block, EXT4_NUM_B2C(sbi, count));
658111b6890bSKemeng Shi 		return;
658211b6890bSKemeng Shi 	}
658311b6890bSKemeng Shi 
658411b6890bSKemeng Shi 	might_sleep();
658511b6890bSKemeng Shi 
65868ac3939dSRitesh Harjani 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
65878ac3939dSRitesh Harjani 	    !ext4_inode_block_valid(inode, block, count)) {
65888ac3939dSRitesh Harjani 		ext4_error(sb, "Freeing blocks not in datazone - "
65898ac3939dSRitesh Harjani 			   "block = %llu, count = %lu", block, count);
65908ac3939dSRitesh Harjani 		return;
65918ac3939dSRitesh Harjani 	}
65921e1c2b86SLukas Czerner 	flags |= EXT4_FREE_BLOCKS_VALIDATED;
65938ac3939dSRitesh Harjani 
65948ac3939dSRitesh Harjani 	ext4_debug("freeing block %llu\n", block);
65958ac3939dSRitesh Harjani 	trace_ext4_free_blocks(inode, block, count, flags);
65968ac3939dSRitesh Harjani 
65978ac3939dSRitesh Harjani 	if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
65988ac3939dSRitesh Harjani 		BUG_ON(count > 1);
65998ac3939dSRitesh Harjani 
66008ac3939dSRitesh Harjani 		ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
66018ac3939dSRitesh Harjani 			    inode, bh, block);
66028ac3939dSRitesh Harjani 	}
66038ac3939dSRitesh Harjani 
66048ac3939dSRitesh Harjani 	/*
66058ac3939dSRitesh Harjani 	 * If the extent to be freed does not begin on a cluster
66068ac3939dSRitesh Harjani 	 * boundary, we need to deal with partial clusters at the
66078ac3939dSRitesh Harjani 	 * beginning and end of the extent.  Normally we will free
66088ac3939dSRitesh Harjani 	 * blocks at the beginning or the end unless we are explicitly
66098ac3939dSRitesh Harjani 	 * requested to avoid doing so.
66108ac3939dSRitesh Harjani 	 */
66118ac3939dSRitesh Harjani 	overflow = EXT4_PBLK_COFF(sbi, block);
66128ac3939dSRitesh Harjani 	if (overflow) {
66138ac3939dSRitesh Harjani 		if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
66148ac3939dSRitesh Harjani 			overflow = sbi->s_cluster_ratio - overflow;
66158ac3939dSRitesh Harjani 			block += overflow;
66168ac3939dSRitesh Harjani 			if (count > overflow)
66178ac3939dSRitesh Harjani 				count -= overflow;
66188ac3939dSRitesh Harjani 			else
66198ac3939dSRitesh Harjani 				return;
66208ac3939dSRitesh Harjani 		} else {
66218ac3939dSRitesh Harjani 			block -= overflow;
66228ac3939dSRitesh Harjani 			count += overflow;
66238ac3939dSRitesh Harjani 		}
66241e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
66251e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
66268ac3939dSRitesh Harjani 	}
66278ac3939dSRitesh Harjani 	overflow = EXT4_LBLK_COFF(sbi, count);
66288ac3939dSRitesh Harjani 	if (overflow) {
66298ac3939dSRitesh Harjani 		if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
66308ac3939dSRitesh Harjani 			if (count > overflow)
66318ac3939dSRitesh Harjani 				count -= overflow;
66328ac3939dSRitesh Harjani 			else
66338ac3939dSRitesh Harjani 				return;
66348ac3939dSRitesh Harjani 		} else
66358ac3939dSRitesh Harjani 			count += sbi->s_cluster_ratio - overflow;
66361e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
66371e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
66388ac3939dSRitesh Harjani 	}
66398ac3939dSRitesh Harjani 
66408ac3939dSRitesh Harjani 	if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
66418ac3939dSRitesh Harjani 		int i;
66428ac3939dSRitesh Harjani 		int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
66438ac3939dSRitesh Harjani 
66448ac3939dSRitesh Harjani 		for (i = 0; i < count; i++) {
66458ac3939dSRitesh Harjani 			cond_resched();
66468ac3939dSRitesh Harjani 			if (is_metadata)
66478ac3939dSRitesh Harjani 				bh = sb_find_get_block(inode->i_sb, block + i);
66488ac3939dSRitesh Harjani 			ext4_forget(handle, is_metadata, inode, bh, block + i);
66498ac3939dSRitesh Harjani 		}
66508ac3939dSRitesh Harjani 	}
66518ac3939dSRitesh Harjani 
66528ac3939dSRitesh Harjani 	ext4_mb_clear_bb(handle, inode, block, count, flags);
66538ac3939dSRitesh Harjani }
66548ac3939dSRitesh Harjani 
66558ac3939dSRitesh Harjani /**
66560529155eSYongqiang Yang  * ext4_group_add_blocks() -- Add given blocks to an existing group
66572846e820SAmir Goldstein  * @handle:			handle to this transaction
66582846e820SAmir Goldstein  * @sb:				super block
66594907cb7bSAnatol Pomozov  * @block:			start physical block to add to the block group
66602846e820SAmir Goldstein  * @count:			number of blocks to free
66612846e820SAmir Goldstein  *
6662e73a347bSAmir Goldstein  * This marks the blocks as free in the bitmap and buddy.
66632846e820SAmir Goldstein  */
6664cc7365dfSYongqiang Yang int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
66652846e820SAmir Goldstein 			 ext4_fsblk_t block, unsigned long count)
66662846e820SAmir Goldstein {
66672846e820SAmir Goldstein 	ext4_group_t block_group;
66682846e820SAmir Goldstein 	ext4_grpblk_t bit;
66692846e820SAmir Goldstein 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6670e73a347bSAmir Goldstein 	struct ext4_buddy e4b;
66715c657db4SKemeng Shi 	int err = 0;
6672d77147ffSharshads 	ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
6673d77147ffSharshads 	ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
6674d77147ffSharshads 	unsigned long cluster_count = last_cluster - first_cluster + 1;
66755c657db4SKemeng Shi 	ext4_grpblk_t changed;
66762846e820SAmir Goldstein 
66772846e820SAmir Goldstein 	ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
66782846e820SAmir Goldstein 
66795c657db4SKemeng Shi 	if (cluster_count == 0)
66804740b830SYongqiang Yang 		return 0;
66814740b830SYongqiang Yang 
66822846e820SAmir Goldstein 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
66832846e820SAmir Goldstein 	/*
66842846e820SAmir Goldstein 	 * Check to see if we are freeing blocks across a group
66852846e820SAmir Goldstein 	 * boundary.
66862846e820SAmir Goldstein 	 */
6687d77147ffSharshads 	if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
6688d77147ffSharshads 		ext4_warning(sb, "too many blocks added to group %u",
6689cc7365dfSYongqiang Yang 			     block_group);
6690cc7365dfSYongqiang Yang 		err = -EINVAL;
669103c7fc39SKemeng Shi 		goto error_out;
6692cc7365dfSYongqiang Yang 	}
66932cd05cc3STheodore Ts'o 
669403c7fc39SKemeng Shi 	err = ext4_mb_load_buddy(sb, block_group, &e4b);
669503c7fc39SKemeng Shi 	if (err)
669603c7fc39SKemeng Shi 		goto error_out;
66972846e820SAmir Goldstein 
6698a00b482bSRitesh Harjani 	if (!ext4_sb_block_valid(sb, NULL, block, count)) {
66992846e820SAmir Goldstein 		ext4_error(sb, "Adding blocks in system zones - "
67002846e820SAmir Goldstein 			   "Block = %llu, count = %lu",
67012846e820SAmir Goldstein 			   block, count);
6702cc7365dfSYongqiang Yang 		err = -EINVAL;
670303c7fc39SKemeng Shi 		goto error_clean;
670403c7fc39SKemeng Shi 	}
670503c7fc39SKemeng Shi 
67065c657db4SKemeng Shi 	err = ext4_mb_mark_context(handle, sb, false, block_group, bit,
67075c657db4SKemeng Shi 				   cluster_count, EXT4_MB_BITMAP_MARKED_CHECK,
67085c657db4SKemeng Shi 				   &changed);
67095c657db4SKemeng Shi 	if (err && changed == 0)
671003c7fc39SKemeng Shi 		goto error_clean;
67112846e820SAmir Goldstein 
67125c657db4SKemeng Shi 	if (changed != cluster_count)
67135c657db4SKemeng Shi 		ext4_error(sb, "bit already cleared in group %u", block_group);
67142846e820SAmir Goldstein 
671503c7fc39SKemeng Shi 	ext4_lock_group(sb, block_group);
671603c7fc39SKemeng Shi 	mb_free_blocks(NULL, &e4b, bit, cluster_count);
671703c7fc39SKemeng Shi 	ext4_unlock_group(sb, block_group);
671803c7fc39SKemeng Shi 	percpu_counter_add(&sbi->s_freeclusters_counter,
67195c657db4SKemeng Shi 			   changed);
672003c7fc39SKemeng Shi 
672103c7fc39SKemeng Shi error_clean:
672203c7fc39SKemeng Shi 	ext4_mb_unload_buddy(&e4b);
672303c7fc39SKemeng Shi error_out:
67242846e820SAmir Goldstein 	ext4_std_error(sb, err);
6725cc7365dfSYongqiang Yang 	return err;
67262846e820SAmir Goldstein }
67272846e820SAmir Goldstein 
67282846e820SAmir Goldstein /**
67297360d173SLukas Czerner  * ext4_trim_extent -- function to TRIM one single free extent in the group
67307360d173SLukas Czerner  * @sb:		super block for the file system
67317360d173SLukas Czerner  * @start:	starting block of the free extent in the alloc. group
67327360d173SLukas Czerner  * @count:	number of blocks to TRIM
67337360d173SLukas Czerner  * @e4b:	ext4 buddy for the group
67347360d173SLukas Czerner  *
67357360d173SLukas Czerner  * Trim "count" blocks starting at "start" in the "group". To assure that no
67367360d173SLukas Czerner  * one will allocate those blocks, mark it as used in buddy bitmap. This must
67377360d173SLukas Czerner  * be called with under the group lock.
67387360d173SLukas Czerner  */
6739bd2eea8dSWang Jianchao static int ext4_trim_extent(struct super_block *sb,
6740bd2eea8dSWang Jianchao 		int start, int count, struct ext4_buddy *e4b)
6741e2cbd587Sjon ernst __releases(bitlock)
6742e2cbd587Sjon ernst __acquires(bitlock)
67437360d173SLukas Czerner {
67447360d173SLukas Czerner 	struct ext4_free_extent ex;
6745bd2eea8dSWang Jianchao 	ext4_group_t group = e4b->bd_group;
6746d71c1ae2SLukas Czerner 	int ret = 0;
67477360d173SLukas Czerner 
6748b3d4c2b1STao Ma 	trace_ext4_trim_extent(sb, group, start, count);
6749b3d4c2b1STao Ma 
67507360d173SLukas Czerner 	assert_spin_locked(ext4_group_lock_ptr(sb, group));
67517360d173SLukas Czerner 
67527360d173SLukas Czerner 	ex.fe_start = start;
67537360d173SLukas Czerner 	ex.fe_group = group;
67547360d173SLukas Czerner 	ex.fe_len = count;
67557360d173SLukas Czerner 
67567360d173SLukas Czerner 	/*
67577360d173SLukas Czerner 	 * Mark blocks used, so no one can reuse them while
67587360d173SLukas Czerner 	 * being trimmed.
67597360d173SLukas Czerner 	 */
67607360d173SLukas Czerner 	mb_mark_used(e4b, &ex);
67617360d173SLukas Czerner 	ext4_unlock_group(sb, group);
67620efcd739SWenchao Hao 	ret = ext4_issue_discard(sb, group, start, count);
67637360d173SLukas Czerner 	ext4_lock_group(sb, group);
67647360d173SLukas Czerner 	mb_free_blocks(NULL, e4b, start, ex.fe_len);
6765d71c1ae2SLukas Czerner 	return ret;
67667360d173SLukas Czerner }
67677360d173SLukas Czerner 
676845e4ab32SJan Kara static ext4_grpblk_t ext4_last_grp_cluster(struct super_block *sb,
676945e4ab32SJan Kara 					   ext4_group_t grp)
677045e4ab32SJan Kara {
67717c784d62SSuraj Jitindar Singh 	unsigned long nr_clusters_in_group;
67727c784d62SSuraj Jitindar Singh 
67737c784d62SSuraj Jitindar Singh 	if (grp < (ext4_get_groups_count(sb) - 1))
67747c784d62SSuraj Jitindar Singh 		nr_clusters_in_group = EXT4_CLUSTERS_PER_GROUP(sb);
67757c784d62SSuraj Jitindar Singh 	else
67767c784d62SSuraj Jitindar Singh 		nr_clusters_in_group = (ext4_blocks_count(EXT4_SB(sb)->s_es) -
67777c784d62SSuraj Jitindar Singh 					ext4_group_first_block_no(sb, grp))
67787c784d62SSuraj Jitindar Singh 				       >> EXT4_CLUSTER_BITS(sb);
67797c784d62SSuraj Jitindar Singh 
67807c784d62SSuraj Jitindar Singh 	return nr_clusters_in_group - 1;
678145e4ab32SJan Kara }
678245e4ab32SJan Kara 
67835229a658SJan Kara static bool ext4_trim_interrupted(void)
67845229a658SJan Kara {
67855229a658SJan Kara 	return fatal_signal_pending(current) || freezing(current);
67865229a658SJan Kara }
67875229a658SJan Kara 
67886920b391SWang Jianchao static int ext4_try_to_trim_range(struct super_block *sb,
67896920b391SWang Jianchao 		struct ext4_buddy *e4b, ext4_grpblk_t start,
67906920b391SWang Jianchao 		ext4_grpblk_t max, ext4_grpblk_t minblocks)
6791a5fda113STheodore Ts'o __acquires(ext4_group_lock_ptr(sb, e4b->bd_group))
6792a5fda113STheodore Ts'o __releases(ext4_group_lock_ptr(sb, e4b->bd_group))
67936920b391SWang Jianchao {
679468da4c44SYe Bin 	ext4_grpblk_t next, count, free_count, last, origin_start;
679545e4ab32SJan Kara 	bool set_trimmed = false;
67966920b391SWang Jianchao 	void *bitmap;
67976920b391SWang Jianchao 
679817220215SBaokun Li 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
679917220215SBaokun Li 		return 0;
680017220215SBaokun Li 
680168da4c44SYe Bin 	last = ext4_last_grp_cluster(sb, e4b->bd_group);
68026920b391SWang Jianchao 	bitmap = e4b->bd_bitmap;
680368da4c44SYe Bin 	if (start == 0 && max >= last)
680445e4ab32SJan Kara 		set_trimmed = true;
680568da4c44SYe Bin 	origin_start = start;
6806de8bf0e5SKemeng Shi 	start = max(e4b->bd_info->bb_first_free, start);
68076920b391SWang Jianchao 	count = 0;
68086920b391SWang Jianchao 	free_count = 0;
68096920b391SWang Jianchao 
68106920b391SWang Jianchao 	while (start <= max) {
68116920b391SWang Jianchao 		start = mb_find_next_zero_bit(bitmap, max + 1, start);
68126920b391SWang Jianchao 		if (start > max)
68136920b391SWang Jianchao 			break;
681468da4c44SYe Bin 
681568da4c44SYe Bin 		next = mb_find_next_bit(bitmap, last + 1, start);
681668da4c44SYe Bin 		if (origin_start == 0 && next >= last)
681768da4c44SYe Bin 			set_trimmed = true;
68186920b391SWang Jianchao 
68196920b391SWang Jianchao 		if ((next - start) >= minblocks) {
6820afcc4e32SLukas Bulwahn 			int ret = ext4_trim_extent(sb, start, next - start, e4b);
6821afcc4e32SLukas Bulwahn 
68226920b391SWang Jianchao 			if (ret && ret != -EOPNOTSUPP)
682345e4ab32SJan Kara 				return count;
68246920b391SWang Jianchao 			count += next - start;
68256920b391SWang Jianchao 		}
68266920b391SWang Jianchao 		free_count += next - start;
68276920b391SWang Jianchao 		start = next + 1;
68286920b391SWang Jianchao 
68295229a658SJan Kara 		if (ext4_trim_interrupted())
68305229a658SJan Kara 			return count;
68316920b391SWang Jianchao 
68326920b391SWang Jianchao 		if (need_resched()) {
68336920b391SWang Jianchao 			ext4_unlock_group(sb, e4b->bd_group);
68346920b391SWang Jianchao 			cond_resched();
68356920b391SWang Jianchao 			ext4_lock_group(sb, e4b->bd_group);
68366920b391SWang Jianchao 		}
68376920b391SWang Jianchao 
68386920b391SWang Jianchao 		if ((e4b->bd_info->bb_free - free_count) < minblocks)
68396920b391SWang Jianchao 			break;
68406920b391SWang Jianchao 	}
68416920b391SWang Jianchao 
684245e4ab32SJan Kara 	if (set_trimmed)
684345e4ab32SJan Kara 		EXT4_MB_GRP_SET_TRIMMED(e4b->bd_info);
684445e4ab32SJan Kara 
68456920b391SWang Jianchao 	return count;
68466920b391SWang Jianchao }
68476920b391SWang Jianchao 
68487360d173SLukas Czerner /**
68497360d173SLukas Czerner  * ext4_trim_all_free -- function to trim all free space in alloc. group
68507360d173SLukas Czerner  * @sb:			super block for file system
685122612283STao Ma  * @group:		group to be trimmed
68527360d173SLukas Czerner  * @start:		first group block to examine
68537360d173SLukas Czerner  * @max:		last group block to examine
68547360d173SLukas Czerner  * @minblocks:		minimum extent block count
68557360d173SLukas Czerner  *
68567360d173SLukas Czerner  * ext4_trim_all_free walks through group's block bitmap searching for free
68577360d173SLukas Czerner  * extents. When the free extent is found, mark it as used in group buddy
68587360d173SLukas Czerner  * bitmap. Then issue a TRIM command on this extent and free the extent in
6859b6f5558cSWang Jianchao  * the group buddy bitmap.
68607360d173SLukas Czerner  */
68610b75a840SLukas Czerner static ext4_grpblk_t
686278944086SLukas Czerner ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
686378944086SLukas Czerner 		   ext4_grpblk_t start, ext4_grpblk_t max,
686445e4ab32SJan Kara 		   ext4_grpblk_t minblocks)
68657360d173SLukas Czerner {
686678944086SLukas Czerner 	struct ext4_buddy e4b;
68676920b391SWang Jianchao 	int ret;
68687360d173SLukas Czerner 
6869b3d4c2b1STao Ma 	trace_ext4_trim_all_free(sb, group, start, max);
6870b3d4c2b1STao Ma 
687178944086SLukas Czerner 	ret = ext4_mb_load_buddy(sb, group, &e4b);
687278944086SLukas Czerner 	if (ret) {
68739651e6b2SKonstantin Khlebnikov 		ext4_warning(sb, "Error %d loading buddy information for %u",
68749651e6b2SKonstantin Khlebnikov 			     ret, group);
687578944086SLukas Czerner 		return ret;
687678944086SLukas Czerner 	}
687728739eeaSLukas Czerner 
687828739eeaSLukas Czerner 	ext4_lock_group(sb, group);
68793d56b8d2STao Ma 
68806920b391SWang Jianchao 	if (!EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) ||
688145e4ab32SJan Kara 	    minblocks < EXT4_SB(sb)->s_last_trim_minblks)
68826920b391SWang Jianchao 		ret = ext4_try_to_trim_range(sb, &e4b, start, max, minblocks);
688345e4ab32SJan Kara 	else
68846920b391SWang Jianchao 		ret = 0;
68856920b391SWang Jianchao 
68867360d173SLukas Czerner 	ext4_unlock_group(sb, group);
688778944086SLukas Czerner 	ext4_mb_unload_buddy(&e4b);
68887360d173SLukas Czerner 
68897360d173SLukas Czerner 	ext4_debug("trimmed %d blocks in the group %d\n",
68906920b391SWang Jianchao 		ret, group);
68917360d173SLukas Czerner 
6892d71c1ae2SLukas Czerner 	return ret;
68937360d173SLukas Czerner }
68947360d173SLukas Czerner 
68957360d173SLukas Czerner /**
68967360d173SLukas Czerner  * ext4_trim_fs() -- trim ioctl handle function
68977360d173SLukas Czerner  * @sb:			superblock for filesystem
68987360d173SLukas Czerner  * @range:		fstrim_range structure
68997360d173SLukas Czerner  *
69007360d173SLukas Czerner  * start:	First Byte to trim
69017360d173SLukas Czerner  * len:		number of Bytes to trim from start
69027360d173SLukas Czerner  * minlen:	minimum extent length in Bytes
69037360d173SLukas Czerner  * ext4_trim_fs goes through all allocation groups containing Bytes from
69047360d173SLukas Czerner  * start to start+len. For each such a group ext4_trim_all_free function
69057360d173SLukas Czerner  * is invoked to trim all free space.
69067360d173SLukas Czerner  */
69077360d173SLukas Czerner int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
69087360d173SLukas Czerner {
69097b47ef52SChristoph Hellwig 	unsigned int discard_granularity = bdev_discard_granularity(sb->s_bdev);
691078944086SLukas Czerner 	struct ext4_group_info *grp;
6911913eed83SLukas Czerner 	ext4_group_t group, first_group, last_group;
69127137d7a4STheodore Ts'o 	ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
6913913eed83SLukas Czerner 	uint64_t start, end, minlen, trimmed = 0;
69140f0a25bfSJan Kara 	ext4_fsblk_t first_data_blk =
69150f0a25bfSJan Kara 			le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
6916913eed83SLukas Czerner 	ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
69177360d173SLukas Czerner 	int ret = 0;
69187360d173SLukas Czerner 
69197360d173SLukas Czerner 	start = range->start >> sb->s_blocksize_bits;
6920913eed83SLukas Czerner 	end = start + (range->len >> sb->s_blocksize_bits) - 1;
6921aaf7d73eSLukas Czerner 	minlen = EXT4_NUM_B2C(EXT4_SB(sb),
6922aaf7d73eSLukas Czerner 			      range->minlen >> sb->s_blocksize_bits);
69237360d173SLukas Czerner 
69245de35e8dSLukas Czerner 	if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
69255de35e8dSLukas Czerner 	    start >= max_blks ||
69265de35e8dSLukas Czerner 	    range->len < sb->s_blocksize)
69277360d173SLukas Czerner 		return -EINVAL;
6928173b6e38SJan Kara 	/* No point to try to trim less than discard granularity */
69297b47ef52SChristoph Hellwig 	if (range->minlen < discard_granularity) {
6930173b6e38SJan Kara 		minlen = EXT4_NUM_B2C(EXT4_SB(sb),
69317b47ef52SChristoph Hellwig 				discard_granularity >> sb->s_blocksize_bits);
6932173b6e38SJan Kara 		if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
6933173b6e38SJan Kara 			goto out;
6934173b6e38SJan Kara 	}
693545e4ab32SJan Kara 	if (end >= max_blks - 1)
6936913eed83SLukas Czerner 		end = max_blks - 1;
6937913eed83SLukas Czerner 	if (end <= first_data_blk)
693822f10457STao Ma 		goto out;
6939913eed83SLukas Czerner 	if (start < first_data_blk)
69400f0a25bfSJan Kara 		start = first_data_blk;
69417360d173SLukas Czerner 
6942913eed83SLukas Czerner 	/* Determine first and last group to examine based on start and end */
69437360d173SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
69447137d7a4STheodore Ts'o 				     &first_group, &first_cluster);
6945913eed83SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
69467137d7a4STheodore Ts'o 				     &last_group, &last_cluster);
69477360d173SLukas Czerner 
6948913eed83SLukas Czerner 	/* end now represents the last cluster to discard in this group */
6949913eed83SLukas Czerner 	end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
69507360d173SLukas Czerner 
69517360d173SLukas Czerner 	for (group = first_group; group <= last_group; group++) {
69525229a658SJan Kara 		if (ext4_trim_interrupted())
69535229a658SJan Kara 			break;
695478944086SLukas Czerner 		grp = ext4_get_group_info(sb, group);
69555354b2afSTheodore Ts'o 		if (!grp)
69565354b2afSTheodore Ts'o 			continue;
695778944086SLukas Czerner 		/* We only do this if the grp has never been initialized */
695878944086SLukas Czerner 		if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
6959adb7ef60SKonstantin Khlebnikov 			ret = ext4_mb_init_group(sb, group, GFP_NOFS);
696078944086SLukas Czerner 			if (ret)
69617360d173SLukas Czerner 				break;
69627360d173SLukas Czerner 		}
69637360d173SLukas Czerner 
69640ba08517STao Ma 		/*
6965913eed83SLukas Czerner 		 * For all the groups except the last one, last cluster will
6966913eed83SLukas Czerner 		 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
6967913eed83SLukas Czerner 		 * change it for the last group, note that last_cluster is
6968913eed83SLukas Czerner 		 * already computed earlier by ext4_get_group_no_and_offset()
69690ba08517STao Ma 		 */
697045e4ab32SJan Kara 		if (group == last_group)
6971913eed83SLukas Czerner 			end = last_cluster;
697278944086SLukas Czerner 		if (grp->bb_free >= minlen) {
69737137d7a4STheodore Ts'o 			cnt = ext4_trim_all_free(sb, group, first_cluster,
697445e4ab32SJan Kara 						 end, minlen);
69757360d173SLukas Czerner 			if (cnt < 0) {
69767360d173SLukas Czerner 				ret = cnt;
69777360d173SLukas Czerner 				break;
69787360d173SLukas Czerner 			}
69797360d173SLukas Czerner 			trimmed += cnt;
698021e7fd22SLukas Czerner 		}
6981913eed83SLukas Czerner 
6982913eed83SLukas Czerner 		/*
6983913eed83SLukas Czerner 		 * For every group except the first one, we are sure
6984913eed83SLukas Czerner 		 * that the first cluster to discard will be cluster #0.
6985913eed83SLukas Czerner 		 */
69867137d7a4STheodore Ts'o 		first_cluster = 0;
69877360d173SLukas Czerner 	}
69887360d173SLukas Czerner 
69893d56b8d2STao Ma 	if (!ret)
69902327fb2eSLukas Czerner 		EXT4_SB(sb)->s_last_trim_minblks = minlen;
69913d56b8d2STao Ma 
699222f10457STao Ma out:
6993aaf7d73eSLukas Czerner 	range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
69947360d173SLukas Czerner 	return ret;
69957360d173SLukas Czerner }
69960c9ec4beSDarrick J. Wong 
69970c9ec4beSDarrick J. Wong /* Iterate all the free extents in the group. */
69980c9ec4beSDarrick J. Wong int
69990c9ec4beSDarrick J. Wong ext4_mballoc_query_range(
70000c9ec4beSDarrick J. Wong 	struct super_block		*sb,
70010c9ec4beSDarrick J. Wong 	ext4_group_t			group,
70020c9ec4beSDarrick J. Wong 	ext4_grpblk_t			start,
70030c9ec4beSDarrick J. Wong 	ext4_grpblk_t			end,
70040c9ec4beSDarrick J. Wong 	ext4_mballoc_query_range_fn	formatter,
70050c9ec4beSDarrick J. Wong 	void				*priv)
70060c9ec4beSDarrick J. Wong {
70070c9ec4beSDarrick J. Wong 	void				*bitmap;
70080c9ec4beSDarrick J. Wong 	ext4_grpblk_t			next;
70090c9ec4beSDarrick J. Wong 	struct ext4_buddy		e4b;
70100c9ec4beSDarrick J. Wong 	int				error;
70110c9ec4beSDarrick J. Wong 
70120c9ec4beSDarrick J. Wong 	error = ext4_mb_load_buddy(sb, group, &e4b);
70130c9ec4beSDarrick J. Wong 	if (error)
70140c9ec4beSDarrick J. Wong 		return error;
70150c9ec4beSDarrick J. Wong 	bitmap = e4b.bd_bitmap;
70160c9ec4beSDarrick J. Wong 
70170c9ec4beSDarrick J. Wong 	ext4_lock_group(sb, group);
70180c9ec4beSDarrick J. Wong 
7019de8bf0e5SKemeng Shi 	start = max(e4b.bd_info->bb_first_free, start);
70200c9ec4beSDarrick J. Wong 	if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
70210c9ec4beSDarrick J. Wong 		end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
70220c9ec4beSDarrick J. Wong 
70230c9ec4beSDarrick J. Wong 	while (start <= end) {
70240c9ec4beSDarrick J. Wong 		start = mb_find_next_zero_bit(bitmap, end + 1, start);
70250c9ec4beSDarrick J. Wong 		if (start > end)
70260c9ec4beSDarrick J. Wong 			break;
70270c9ec4beSDarrick J. Wong 		next = mb_find_next_bit(bitmap, end + 1, start);
70280c9ec4beSDarrick J. Wong 
70290c9ec4beSDarrick J. Wong 		ext4_unlock_group(sb, group);
70300c9ec4beSDarrick J. Wong 		error = formatter(sb, group, start, next - start, priv);
70310c9ec4beSDarrick J. Wong 		if (error)
70320c9ec4beSDarrick J. Wong 			goto out_unload;
70330c9ec4beSDarrick J. Wong 		ext4_lock_group(sb, group);
70340c9ec4beSDarrick J. Wong 
70350c9ec4beSDarrick J. Wong 		start = next + 1;
70360c9ec4beSDarrick J. Wong 	}
70370c9ec4beSDarrick J. Wong 
70380c9ec4beSDarrick J. Wong 	ext4_unlock_group(sb, group);
70390c9ec4beSDarrick J. Wong out_unload:
70400c9ec4beSDarrick J. Wong 	ext4_mb_unload_buddy(&e4b);
70410c9ec4beSDarrick J. Wong 
70420c9ec4beSDarrick J. Wong 	return error;
70430c9ec4beSDarrick J. Wong }
70447c9fa399SKemeng Shi 
70457c9fa399SKemeng Shi #ifdef CONFIG_EXT4_KUNIT_TESTS
70467c9fa399SKemeng Shi #include "mballoc-test.c"
70477c9fa399SKemeng Shi #endif
7048