xref: /linux/fs/ext4/mballoc.c (revision 2caffb6a277bb0f2a482a2eb824d012d5f45f4d0)
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 /*
1083196e402aSHarshad Shirwadkar  * Return next linear group for allocation. If linear traversal should not be
1084196e402aSHarshad Shirwadkar  * performed, this function just returns the same group
1085196e402aSHarshad Shirwadkar  */
108660c672b7SKemeng Shi static ext4_group_t
108760c672b7SKemeng Shi next_linear_group(struct ext4_allocation_context *ac, ext4_group_t group,
108860c672b7SKemeng Shi 		  ext4_group_t ngroups)
1089196e402aSHarshad Shirwadkar {
1090196e402aSHarshad Shirwadkar 	if (!should_optimize_scan(ac))
1091196e402aSHarshad Shirwadkar 		goto inc_and_return;
1092196e402aSHarshad Shirwadkar 
1093196e402aSHarshad Shirwadkar 	if (ac->ac_groups_linear_remaining) {
1094196e402aSHarshad Shirwadkar 		ac->ac_groups_linear_remaining--;
1095196e402aSHarshad Shirwadkar 		goto inc_and_return;
1096196e402aSHarshad Shirwadkar 	}
1097196e402aSHarshad Shirwadkar 
1098196e402aSHarshad Shirwadkar 	return group;
1099196e402aSHarshad Shirwadkar inc_and_return:
1100196e402aSHarshad Shirwadkar 	/*
1101196e402aSHarshad Shirwadkar 	 * Artificially restricted ngroups for non-extent
1102196e402aSHarshad Shirwadkar 	 * files makes group > ngroups possible on first loop.
1103196e402aSHarshad Shirwadkar 	 */
1104196e402aSHarshad Shirwadkar 	return group + 1 >= ngroups ? 0 : group + 1;
1105196e402aSHarshad Shirwadkar }
1106196e402aSHarshad Shirwadkar 
1107196e402aSHarshad Shirwadkar /*
1108196e402aSHarshad Shirwadkar  * ext4_mb_choose_next_group: choose next group for allocation.
1109196e402aSHarshad Shirwadkar  *
1110196e402aSHarshad Shirwadkar  * @ac        Allocation Context
1111196e402aSHarshad Shirwadkar  * @new_cr    This is an output parameter. If the there is no good group
1112196e402aSHarshad Shirwadkar  *            available at current CR level, this field is updated to indicate
1113196e402aSHarshad Shirwadkar  *            the new cr level that should be used.
1114196e402aSHarshad Shirwadkar  * @group     This is an input / output parameter. As an input it indicates the
1115196e402aSHarshad Shirwadkar  *            next group that the allocator intends to use for allocation. As
1116196e402aSHarshad Shirwadkar  *            output, this field indicates the next group that should be used as
1117196e402aSHarshad Shirwadkar  *            determined by the optimization functions.
1118196e402aSHarshad Shirwadkar  * @ngroups   Total number of groups
1119196e402aSHarshad Shirwadkar  */
1120196e402aSHarshad Shirwadkar static void ext4_mb_choose_next_group(struct ext4_allocation_context *ac,
11214eb7a4a1SOjaswin Mujoo 		enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
1122196e402aSHarshad Shirwadkar {
1123196e402aSHarshad Shirwadkar 	*new_cr = ac->ac_criteria;
1124196e402aSHarshad Shirwadkar 
11254fca50d4SJan Kara 	if (!should_optimize_scan(ac) || ac->ac_groups_linear_remaining) {
11264fca50d4SJan Kara 		*group = next_linear_group(ac, *group, ngroups);
1127196e402aSHarshad Shirwadkar 		return;
11284fca50d4SJan Kara 	}
1129196e402aSHarshad Shirwadkar 
1130f52f3d2bSOjaswin Mujoo 	if (*new_cr == CR_POWER2_ALIGNED) {
1131438a35e7SKemeng Shi 		ext4_mb_choose_next_group_p2_aligned(ac, new_cr, group);
1132f52f3d2bSOjaswin Mujoo 	} else if (*new_cr == CR_GOAL_LEN_FAST) {
1133438a35e7SKemeng Shi 		ext4_mb_choose_next_group_goal_fast(ac, new_cr, group);
1134f52f3d2bSOjaswin Mujoo 	} else if (*new_cr == CR_BEST_AVAIL_LEN) {
1135438a35e7SKemeng Shi 		ext4_mb_choose_next_group_best_avail(ac, new_cr, group);
1136196e402aSHarshad Shirwadkar 	} else {
1137196e402aSHarshad Shirwadkar 		/*
1138*2caffb6aSKemeng Shi 		 * TODO: For CR_GOAL_LEN_SLOW, we can arrange groups in an
1139*2caffb6aSKemeng Shi 		 * rb tree sorted by bb_free. But until that happens, we should
1140*2caffb6aSKemeng Shi 		 * never come here.
1141196e402aSHarshad Shirwadkar 		 */
1142196e402aSHarshad Shirwadkar 		WARN_ON(1);
1143196e402aSHarshad Shirwadkar 	}
1144196e402aSHarshad Shirwadkar }
1145196e402aSHarshad Shirwadkar 
11468a57d9d6SCurt Wohlgemuth /*
11478a57d9d6SCurt Wohlgemuth  * Cache the order of the largest free extent we have available in this block
11488a57d9d6SCurt Wohlgemuth  * group.
11498a57d9d6SCurt Wohlgemuth  */
11508a57d9d6SCurt Wohlgemuth static void
11518a57d9d6SCurt Wohlgemuth mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
11528a57d9d6SCurt Wohlgemuth {
1153196e402aSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
11548a57d9d6SCurt Wohlgemuth 	int i;
11558a57d9d6SCurt Wohlgemuth 
11561940265eSJan Kara 	for (i = MB_NUM_ORDERS(sb) - 1; i >= 0; i--)
11571940265eSJan Kara 		if (grp->bb_counters[i] > 0)
11581940265eSJan Kara 			break;
11591940265eSJan Kara 	/* No need to move between order lists? */
11601940265eSJan Kara 	if (!test_opt2(sb, MB_OPTIMIZE_SCAN) ||
11611940265eSJan Kara 	    i == grp->bb_largest_free_order) {
11621940265eSJan Kara 		grp->bb_largest_free_order = i;
11631940265eSJan Kara 		return;
11641940265eSJan Kara 	}
11651940265eSJan Kara 
11661940265eSJan Kara 	if (grp->bb_largest_free_order >= 0) {
1167196e402aSHarshad Shirwadkar 		write_lock(&sbi->s_mb_largest_free_orders_locks[
1168196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1169196e402aSHarshad Shirwadkar 		list_del_init(&grp->bb_largest_free_order_node);
1170196e402aSHarshad Shirwadkar 		write_unlock(&sbi->s_mb_largest_free_orders_locks[
1171196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1172196e402aSHarshad Shirwadkar 	}
11738a57d9d6SCurt Wohlgemuth 	grp->bb_largest_free_order = i;
11741940265eSJan Kara 	if (grp->bb_largest_free_order >= 0 && grp->bb_free) {
1175196e402aSHarshad Shirwadkar 		write_lock(&sbi->s_mb_largest_free_orders_locks[
1176196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1177196e402aSHarshad Shirwadkar 		list_add_tail(&grp->bb_largest_free_order_node,
1178196e402aSHarshad Shirwadkar 		      &sbi->s_mb_largest_free_orders[grp->bb_largest_free_order]);
1179196e402aSHarshad Shirwadkar 		write_unlock(&sbi->s_mb_largest_free_orders_locks[
1180196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1181196e402aSHarshad Shirwadkar 	}
11828a57d9d6SCurt Wohlgemuth }
11838a57d9d6SCurt Wohlgemuth 
1184089ceeccSEric Sandeen static noinline_for_stack
1185089ceeccSEric Sandeen void ext4_mb_generate_buddy(struct super_block *sb,
11865354b2afSTheodore Ts'o 			    void *buddy, void *bitmap, ext4_group_t group,
11875354b2afSTheodore Ts'o 			    struct ext4_group_info *grp)
1188c9de560dSAlex Tomas {
1189e43bb4e6SNamjae Jeon 	struct ext4_sb_info *sbi = EXT4_SB(sb);
11907137d7a4STheodore Ts'o 	ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
1191a36b4498SEric Sandeen 	ext4_grpblk_t i = 0;
1192a36b4498SEric Sandeen 	ext4_grpblk_t first;
1193a36b4498SEric Sandeen 	ext4_grpblk_t len;
1194c9de560dSAlex Tomas 	unsigned free = 0;
1195c9de560dSAlex Tomas 	unsigned fragments = 0;
1196c9de560dSAlex Tomas 	unsigned long long period = get_cycles();
1197c9de560dSAlex Tomas 
1198c9de560dSAlex Tomas 	/* initialize buddy from bitmap which is aggregation
1199c9de560dSAlex Tomas 	 * of on-disk bitmap and preallocations */
1200ffad0a44SAneesh Kumar K.V 	i = mb_find_next_zero_bit(bitmap, max, 0);
1201c9de560dSAlex Tomas 	grp->bb_first_free = i;
1202c9de560dSAlex Tomas 	while (i < max) {
1203c9de560dSAlex Tomas 		fragments++;
1204c9de560dSAlex Tomas 		first = i;
1205ffad0a44SAneesh Kumar K.V 		i = mb_find_next_bit(bitmap, max, i);
1206c9de560dSAlex Tomas 		len = i - first;
1207c9de560dSAlex Tomas 		free += len;
1208c9de560dSAlex Tomas 		if (len > 1)
1209c9de560dSAlex Tomas 			ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
1210c9de560dSAlex Tomas 		else
1211c9de560dSAlex Tomas 			grp->bb_counters[0]++;
1212c9de560dSAlex Tomas 		if (i < max)
1213ffad0a44SAneesh Kumar K.V 			i = mb_find_next_zero_bit(bitmap, max, i);
1214c9de560dSAlex Tomas 	}
1215c9de560dSAlex Tomas 	grp->bb_fragments = fragments;
1216c9de560dSAlex Tomas 
1217c9de560dSAlex Tomas 	if (free != grp->bb_free) {
1218e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0,
121994d4c066STheodore Ts'o 				      "block bitmap and bg descriptor "
122094d4c066STheodore Ts'o 				      "inconsistent: %u vs %u free clusters",
1221e29136f8STheodore Ts'o 				      free, grp->bb_free);
1222e56eb659SAneesh Kumar K.V 		/*
1223163a203dSDarrick J. Wong 		 * If we intend to continue, we consider group descriptor
1224e56eb659SAneesh Kumar K.V 		 * corrupt and update bb_free using bitmap value
1225e56eb659SAneesh Kumar K.V 		 */
1226c9de560dSAlex Tomas 		grp->bb_free = free;
1227db79e6d1SWang Shilong 		ext4_mark_group_bitmap_corrupted(sb, group,
1228db79e6d1SWang Shilong 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1229c9de560dSAlex Tomas 	}
12308a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, grp);
123183e80a6eSJan Kara 	mb_update_avg_fragment_size(sb, grp);
1232c9de560dSAlex Tomas 
1233c9de560dSAlex Tomas 	clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
1234c9de560dSAlex Tomas 
1235c9de560dSAlex Tomas 	period = get_cycles() - period;
123667d25186SHarshad Shirwadkar 	atomic_inc(&sbi->s_mb_buddies_generated);
123767d25186SHarshad Shirwadkar 	atomic64_add(period, &sbi->s_mb_generation_time);
1238c9de560dSAlex Tomas }
1239c9de560dSAlex Tomas 
1240c9b528c3SBaokun Li static void mb_regenerate_buddy(struct ext4_buddy *e4b)
1241c9b528c3SBaokun Li {
1242c9b528c3SBaokun Li 	int count;
1243c9b528c3SBaokun Li 	int order = 1;
1244c9b528c3SBaokun Li 	void *buddy;
1245c9b528c3SBaokun Li 
1246c9b528c3SBaokun Li 	while ((buddy = mb_find_buddy(e4b, order++, &count)))
1247c9b528c3SBaokun Li 		mb_set_bits(buddy, 0, count);
1248c9b528c3SBaokun Li 
1249c9b528c3SBaokun Li 	e4b->bd_info->bb_fragments = 0;
1250c9b528c3SBaokun Li 	memset(e4b->bd_info->bb_counters, 0,
1251c9b528c3SBaokun Li 		sizeof(*e4b->bd_info->bb_counters) *
1252c9b528c3SBaokun Li 		(e4b->bd_sb->s_blocksize_bits + 2));
1253c9b528c3SBaokun Li 
1254c9b528c3SBaokun Li 	ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
1255c9b528c3SBaokun Li 		e4b->bd_bitmap, e4b->bd_group, e4b->bd_info);
1256c9b528c3SBaokun Li }
1257c9b528c3SBaokun Li 
1258c9de560dSAlex Tomas /* The buddy information is attached the buddy cache inode
1259c9de560dSAlex Tomas  * for convenience. The information regarding each group
1260c9de560dSAlex Tomas  * is loaded via ext4_mb_load_buddy. The information involve
1261c9de560dSAlex Tomas  * block bitmap and buddy information. The information are
1262c9de560dSAlex Tomas  * stored in the inode as
1263c9de560dSAlex Tomas  *
1264c9de560dSAlex Tomas  * {                        page                        }
1265c3a326a6SAneesh Kumar K.V  * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
1266c9de560dSAlex Tomas  *
1267c9de560dSAlex Tomas  *
1268c9de560dSAlex Tomas  * one block each for bitmap and buddy information.
1269c9de560dSAlex Tomas  * So for each group we take up 2 blocks. A page can
1270ea1754a0SKirill A. Shutemov  * contain blocks_per_page (PAGE_SIZE / blocksize)  blocks.
1271c9de560dSAlex Tomas  * So it can have information regarding groups_per_page which
1272c9de560dSAlex Tomas  * is blocks_per_page/2
12738a57d9d6SCurt Wohlgemuth  *
12748a57d9d6SCurt Wohlgemuth  * Locking note:  This routine takes the block group lock of all groups
12758a57d9d6SCurt Wohlgemuth  * for this page; do not hold this lock when calling this routine!
1276c9de560dSAlex Tomas  */
1277c9de560dSAlex Tomas 
1278adb7ef60SKonstantin Khlebnikov static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
1279c9de560dSAlex Tomas {
12808df9675fSTheodore Ts'o 	ext4_group_t ngroups;
128189cadf6eSLu Hongfei 	unsigned int blocksize;
1282c9de560dSAlex Tomas 	int blocks_per_page;
1283c9de560dSAlex Tomas 	int groups_per_page;
1284c9de560dSAlex Tomas 	int err = 0;
1285c9de560dSAlex Tomas 	int i;
1286813e5727STheodore Ts'o 	ext4_group_t first_group, group;
1287c9de560dSAlex Tomas 	int first_block;
1288c9de560dSAlex Tomas 	struct super_block *sb;
1289c9de560dSAlex Tomas 	struct buffer_head *bhs;
1290fa77dcfaSDarrick J. Wong 	struct buffer_head **bh = NULL;
1291c9de560dSAlex Tomas 	struct inode *inode;
1292c9de560dSAlex Tomas 	char *data;
1293c9de560dSAlex Tomas 	char *bitmap;
12949b8b7d35SAmir Goldstein 	struct ext4_group_info *grinfo;
1295c9de560dSAlex Tomas 
1296c9de560dSAlex Tomas 	inode = page->mapping->host;
1297c9de560dSAlex Tomas 	sb = inode->i_sb;
12988df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
129993407472SFabian Frederick 	blocksize = i_blocksize(inode);
130009cbfeafSKirill A. Shutemov 	blocks_per_page = PAGE_SIZE / blocksize;
1301c9de560dSAlex Tomas 
1302d3df1453SRitesh Harjani 	mb_debug(sb, "init page %lu\n", page->index);
1303d3df1453SRitesh Harjani 
1304c9de560dSAlex Tomas 	groups_per_page = blocks_per_page >> 1;
1305c9de560dSAlex Tomas 	if (groups_per_page == 0)
1306c9de560dSAlex Tomas 		groups_per_page = 1;
1307c9de560dSAlex Tomas 
1308c9de560dSAlex Tomas 	/* allocate buffer_heads to read bitmaps */
1309c9de560dSAlex Tomas 	if (groups_per_page > 1) {
1310c9de560dSAlex Tomas 		i = sizeof(struct buffer_head *) * groups_per_page;
1311adb7ef60SKonstantin Khlebnikov 		bh = kzalloc(i, gfp);
1312139f46d3SKemeng Shi 		if (bh == NULL)
1313139f46d3SKemeng Shi 			return -ENOMEM;
1314c9de560dSAlex Tomas 	} else
1315c9de560dSAlex Tomas 		bh = &bhs;
1316c9de560dSAlex Tomas 
1317c9de560dSAlex Tomas 	first_group = page->index * blocks_per_page / 2;
1318c9de560dSAlex Tomas 
1319c9de560dSAlex Tomas 	/* read all groups the page covers into the cache */
1320813e5727STheodore Ts'o 	for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1321813e5727STheodore Ts'o 		if (group >= ngroups)
1322c9de560dSAlex Tomas 			break;
1323c9de560dSAlex Tomas 
1324813e5727STheodore Ts'o 		grinfo = ext4_get_group_info(sb, group);
13255354b2afSTheodore Ts'o 		if (!grinfo)
13265354b2afSTheodore Ts'o 			continue;
13279b8b7d35SAmir Goldstein 		/*
13289b8b7d35SAmir Goldstein 		 * If page is uptodate then we came here after online resize
13299b8b7d35SAmir Goldstein 		 * which added some new uninitialized group info structs, so
13309b8b7d35SAmir Goldstein 		 * we must skip all initialized uptodate buddies on the page,
13319b8b7d35SAmir Goldstein 		 * which may be currently in use by an allocating task.
13329b8b7d35SAmir Goldstein 		 */
13339b8b7d35SAmir Goldstein 		if (PageUptodate(page) && !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 
1357c9de560dSAlex Tomas 	first_block = page->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 		 */
1378c9de560dSAlex Tomas 		data = page_address(page) + (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);
1393d3df1453SRitesh Harjani 			mb_debug(sb, "put buddy for group %u in page %lu/%x\n",
1394c9de560dSAlex Tomas 				group, page->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);
1412d3df1453SRitesh Harjani 			mb_debug(sb, "put bitmap for group %u in page %lu/%x\n",
1413c9de560dSAlex Tomas 				group, page->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 	}
1431c9de560dSAlex Tomas 	SetPageUptodate(page);
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
14472de8807bSAmir Goldstein  * are on the same page e4b->bd_buddy_page 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;
14552de8807bSAmir Goldstein 	struct page *page;
14562de8807bSAmir Goldstein 
14572de8807bSAmir Goldstein 	e4b->bd_buddy_page = NULL;
14582de8807bSAmir Goldstein 	e4b->bd_bitmap_page = 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;
1469adb7ef60SKonstantin Khlebnikov 	page = find_or_create_page(inode->i_mapping, pnum, gfp);
14702de8807bSAmir Goldstein 	if (!page)
1471c57ab39bSYounger Liu 		return -ENOMEM;
14722de8807bSAmir Goldstein 	BUG_ON(page->mapping != inode->i_mapping);
14732de8807bSAmir Goldstein 	e4b->bd_bitmap_page = page;
14742de8807bSAmir Goldstein 	e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1475eee4adc7SEric Sandeen 
14762de8807bSAmir Goldstein 	if (blocks_per_page >= 2) {
14772de8807bSAmir Goldstein 		/* buddy and bitmap are on the same page */
14782de8807bSAmir Goldstein 		return 0;
1479eee4adc7SEric Sandeen 	}
1480eee4adc7SEric Sandeen 
1481f2fec3e9SGou Hao 	/* blocks_per_page == 1, hence we need another page for the buddy */
1482f2fec3e9SGou Hao 	page = find_or_create_page(inode->i_mapping, block + 1, gfp);
14832de8807bSAmir Goldstein 	if (!page)
1484c57ab39bSYounger Liu 		return -ENOMEM;
14852de8807bSAmir Goldstein 	BUG_ON(page->mapping != inode->i_mapping);
14862de8807bSAmir Goldstein 	e4b->bd_buddy_page = page;
14872de8807bSAmir Goldstein 	return 0;
1488eee4adc7SEric Sandeen }
1489eee4adc7SEric Sandeen 
14902de8807bSAmir Goldstein static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
14912de8807bSAmir Goldstein {
14922de8807bSAmir Goldstein 	if (e4b->bd_bitmap_page) {
14932de8807bSAmir Goldstein 		unlock_page(e4b->bd_bitmap_page);
149409cbfeafSKirill A. Shutemov 		put_page(e4b->bd_bitmap_page);
14952de8807bSAmir Goldstein 	}
14962de8807bSAmir Goldstein 	if (e4b->bd_buddy_page) {
14972de8807bSAmir Goldstein 		unlock_page(e4b->bd_buddy_page);
149809cbfeafSKirill A. Shutemov 		put_page(e4b->bd_buddy_page);
14992de8807bSAmir Goldstein 	}
1500eee4adc7SEric Sandeen }
1501eee4adc7SEric Sandeen 
1502eee4adc7SEric Sandeen /*
15038a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
15048a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
15058a57d9d6SCurt Wohlgemuth  * calling this routine!
15068a57d9d6SCurt Wohlgemuth  */
1507b6a758ecSAneesh Kumar K.V static noinline_for_stack
1508adb7ef60SKonstantin Khlebnikov int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1509b6a758ecSAneesh Kumar K.V {
1510b6a758ecSAneesh Kumar K.V 
1511b6a758ecSAneesh Kumar K.V 	struct ext4_group_info *this_grp;
15122de8807bSAmir Goldstein 	struct ext4_buddy e4b;
15132de8807bSAmir Goldstein 	struct page *page;
15142de8807bSAmir Goldstein 	int ret = 0;
1515b6a758ecSAneesh Kumar K.V 
1516b10a44c3STheodore Ts'o 	might_sleep();
1517d3df1453SRitesh Harjani 	mb_debug(sb, "init group %u\n", group);
1518b6a758ecSAneesh Kumar K.V 	this_grp = ext4_get_group_info(sb, group);
15195354b2afSTheodore Ts'o 	if (!this_grp)
15205354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
15215354b2afSTheodore Ts'o 
1522b6a758ecSAneesh Kumar K.V 	/*
152308c3a813SAneesh Kumar K.V 	 * This ensures that we don't reinit the buddy cache
152408c3a813SAneesh Kumar K.V 	 * page which map to the group from which we are already
152508c3a813SAneesh Kumar K.V 	 * allocating. If we are looking at the buddy cache we would
152608c3a813SAneesh Kumar K.V 	 * have taken a reference using ext4_mb_load_buddy and that
15272de8807bSAmir Goldstein 	 * would have pinned buddy page to page cache.
15282457aec6SMel Gorman 	 * The call to ext4_mb_get_buddy_page_lock will mark the
15292457aec6SMel Gorman 	 * page accessed.
1530b6a758ecSAneesh Kumar K.V 	 */
1531adb7ef60SKonstantin Khlebnikov 	ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
15322de8807bSAmir Goldstein 	if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1533b6a758ecSAneesh Kumar K.V 		/*
1534b6a758ecSAneesh Kumar K.V 		 * somebody initialized the group
1535b6a758ecSAneesh Kumar K.V 		 * return without doing anything
1536b6a758ecSAneesh Kumar K.V 		 */
1537b6a758ecSAneesh Kumar K.V 		goto err;
1538b6a758ecSAneesh Kumar K.V 	}
15392de8807bSAmir Goldstein 
15402de8807bSAmir Goldstein 	page = e4b.bd_bitmap_page;
1541adb7ef60SKonstantin Khlebnikov 	ret = ext4_mb_init_cache(page, NULL, gfp);
15422de8807bSAmir Goldstein 	if (ret)
1543b6a758ecSAneesh Kumar K.V 		goto err;
15442de8807bSAmir Goldstein 	if (!PageUptodate(page)) {
1545b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1546b6a758ecSAneesh Kumar K.V 		goto err;
1547b6a758ecSAneesh Kumar K.V 	}
1548b6a758ecSAneesh Kumar K.V 
15492de8807bSAmir Goldstein 	if (e4b.bd_buddy_page == NULL) {
1550b6a758ecSAneesh Kumar K.V 		/*
1551b6a758ecSAneesh Kumar K.V 		 * If both the bitmap and buddy are in
1552b6a758ecSAneesh Kumar K.V 		 * the same page we don't need to force
1553b6a758ecSAneesh Kumar K.V 		 * init the buddy
1554b6a758ecSAneesh Kumar K.V 		 */
15552de8807bSAmir Goldstein 		ret = 0;
1556b6a758ecSAneesh Kumar K.V 		goto err;
1557b6a758ecSAneesh Kumar K.V 	}
15582de8807bSAmir Goldstein 	/* init buddy cache */
15592de8807bSAmir Goldstein 	page = e4b.bd_buddy_page;
1560adb7ef60SKonstantin Khlebnikov 	ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
15612de8807bSAmir Goldstein 	if (ret)
15622de8807bSAmir Goldstein 		goto err;
15632de8807bSAmir Goldstein 	if (!PageUptodate(page)) {
1564b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1565b6a758ecSAneesh Kumar K.V 		goto err;
1566b6a758ecSAneesh Kumar K.V 	}
1567b6a758ecSAneesh Kumar K.V err:
15682de8807bSAmir Goldstein 	ext4_mb_put_buddy_page_lock(&e4b);
1569b6a758ecSAneesh Kumar K.V 	return ret;
1570b6a758ecSAneesh Kumar K.V }
1571b6a758ecSAneesh Kumar K.V 
15728a57d9d6SCurt Wohlgemuth /*
15738a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
15748a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
15758a57d9d6SCurt Wohlgemuth  * calling this routine!
15768a57d9d6SCurt Wohlgemuth  */
15774ddfef7bSEric Sandeen static noinline_for_stack int
1578adb7ef60SKonstantin Khlebnikov ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1579adb7ef60SKonstantin Khlebnikov 		       struct ext4_buddy *e4b, gfp_t gfp)
1580c9de560dSAlex Tomas {
1581c9de560dSAlex Tomas 	int blocks_per_page;
1582c9de560dSAlex Tomas 	int block;
1583c9de560dSAlex Tomas 	int pnum;
1584c9de560dSAlex Tomas 	int poff;
1585c9de560dSAlex Tomas 	struct page *page;
1586fdf6c7a7SShen Feng 	int ret;
1587920313a7SAneesh Kumar K.V 	struct ext4_group_info *grp;
1588920313a7SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1589920313a7SAneesh Kumar K.V 	struct inode *inode = sbi->s_buddy_cache;
1590c9de560dSAlex Tomas 
1591b10a44c3STheodore Ts'o 	might_sleep();
1592d3df1453SRitesh Harjani 	mb_debug(sb, "load group %u\n", group);
1593c9de560dSAlex Tomas 
159409cbfeafSKirill A. Shutemov 	blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1595920313a7SAneesh Kumar K.V 	grp = ext4_get_group_info(sb, group);
15965354b2afSTheodore Ts'o 	if (!grp)
15975354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
1598c9de560dSAlex Tomas 
1599c9de560dSAlex Tomas 	e4b->bd_blkbits = sb->s_blocksize_bits;
1600529da704STao Ma 	e4b->bd_info = grp;
1601c9de560dSAlex Tomas 	e4b->bd_sb = sb;
1602c9de560dSAlex Tomas 	e4b->bd_group = group;
1603c9de560dSAlex Tomas 	e4b->bd_buddy_page = NULL;
1604c9de560dSAlex Tomas 	e4b->bd_bitmap_page = NULL;
1605c9de560dSAlex Tomas 
1606f41c0750SAneesh Kumar K.V 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1607f41c0750SAneesh Kumar K.V 		/*
1608f41c0750SAneesh Kumar K.V 		 * we need full data about the group
1609f41c0750SAneesh Kumar K.V 		 * to make a good selection
1610f41c0750SAneesh Kumar K.V 		 */
1611adb7ef60SKonstantin Khlebnikov 		ret = ext4_mb_init_group(sb, group, gfp);
1612f41c0750SAneesh Kumar K.V 		if (ret)
1613f41c0750SAneesh Kumar K.V 			return ret;
1614f41c0750SAneesh Kumar K.V 	}
1615f41c0750SAneesh Kumar K.V 
1616c9de560dSAlex Tomas 	/*
1617c9de560dSAlex Tomas 	 * the buddy cache inode stores the block bitmap
1618c9de560dSAlex Tomas 	 * and buddy information in consecutive blocks.
1619c9de560dSAlex Tomas 	 * So for each group we need two blocks.
1620c9de560dSAlex Tomas 	 */
1621c9de560dSAlex Tomas 	block = group * 2;
1622c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1623c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1624c9de560dSAlex Tomas 
1625c9de560dSAlex Tomas 	/* we could use find_or_create_page(), but it locks page
1626c9de560dSAlex Tomas 	 * what we'd like to avoid in fast path ... */
16272457aec6SMel Gorman 	page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1628c9de560dSAlex Tomas 	if (page == NULL || !PageUptodate(page)) {
1629c9de560dSAlex Tomas 		if (page)
1630920313a7SAneesh Kumar K.V 			/*
1631920313a7SAneesh Kumar K.V 			 * drop the page reference and try
1632920313a7SAneesh Kumar K.V 			 * to get the page with lock. If we
1633920313a7SAneesh Kumar K.V 			 * are not uptodate that implies
1634920313a7SAneesh Kumar K.V 			 * somebody just created the page but
1635920313a7SAneesh Kumar K.V 			 * is yet to initialize the same. So
1636920313a7SAneesh Kumar K.V 			 * wait for it to initialize.
1637920313a7SAneesh Kumar K.V 			 */
163809cbfeafSKirill A. Shutemov 			put_page(page);
1639adb7ef60SKonstantin Khlebnikov 		page = find_or_create_page(inode->i_mapping, pnum, gfp);
1640c9de560dSAlex Tomas 		if (page) {
164119b8b035STheodore Ts'o 			if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
164219b8b035STheodore Ts'o 	"ext4: bitmap's paging->mapping != inode->i_mapping\n")) {
164319b8b035STheodore Ts'o 				/* should never happen */
164419b8b035STheodore Ts'o 				unlock_page(page);
164519b8b035STheodore Ts'o 				ret = -EINVAL;
164619b8b035STheodore Ts'o 				goto err;
164719b8b035STheodore Ts'o 			}
1648c9de560dSAlex Tomas 			if (!PageUptodate(page)) {
1649adb7ef60SKonstantin Khlebnikov 				ret = ext4_mb_init_cache(page, NULL, gfp);
1650fdf6c7a7SShen Feng 				if (ret) {
1651fdf6c7a7SShen Feng 					unlock_page(page);
1652fdf6c7a7SShen Feng 					goto err;
1653fdf6c7a7SShen Feng 				}
1654c9de560dSAlex Tomas 				mb_cmp_bitmaps(e4b, page_address(page) +
1655c9de560dSAlex Tomas 					       (poff * sb->s_blocksize));
1656c9de560dSAlex Tomas 			}
1657c9de560dSAlex Tomas 			unlock_page(page);
1658c9de560dSAlex Tomas 		}
1659c9de560dSAlex Tomas 	}
1660c57ab39bSYounger Liu 	if (page == NULL) {
1661c57ab39bSYounger Liu 		ret = -ENOMEM;
1662c57ab39bSYounger Liu 		goto err;
1663c57ab39bSYounger Liu 	}
1664c57ab39bSYounger Liu 	if (!PageUptodate(page)) {
1665fdf6c7a7SShen Feng 		ret = -EIO;
1666c9de560dSAlex Tomas 		goto err;
1667fdf6c7a7SShen Feng 	}
16682457aec6SMel Gorman 
16692457aec6SMel Gorman 	/* Pages marked accessed already */
1670c9de560dSAlex Tomas 	e4b->bd_bitmap_page = page;
1671c9de560dSAlex Tomas 	e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1672c9de560dSAlex Tomas 
1673c9de560dSAlex Tomas 	block++;
1674c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1675c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1676c9de560dSAlex Tomas 
16772457aec6SMel Gorman 	page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1678c9de560dSAlex Tomas 	if (page == NULL || !PageUptodate(page)) {
1679c9de560dSAlex Tomas 		if (page)
168009cbfeafSKirill A. Shutemov 			put_page(page);
1681adb7ef60SKonstantin Khlebnikov 		page = find_or_create_page(inode->i_mapping, pnum, gfp);
1682c9de560dSAlex Tomas 		if (page) {
168319b8b035STheodore Ts'o 			if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
168419b8b035STheodore Ts'o 	"ext4: buddy bitmap's page->mapping != inode->i_mapping\n")) {
168519b8b035STheodore Ts'o 				/* should never happen */
168619b8b035STheodore Ts'o 				unlock_page(page);
168719b8b035STheodore Ts'o 				ret = -EINVAL;
168819b8b035STheodore Ts'o 				goto err;
168919b8b035STheodore Ts'o 			}
1690fdf6c7a7SShen Feng 			if (!PageUptodate(page)) {
1691adb7ef60SKonstantin Khlebnikov 				ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1692adb7ef60SKonstantin Khlebnikov 							 gfp);
1693fdf6c7a7SShen Feng 				if (ret) {
1694fdf6c7a7SShen Feng 					unlock_page(page);
1695fdf6c7a7SShen Feng 					goto err;
1696fdf6c7a7SShen Feng 				}
1697fdf6c7a7SShen Feng 			}
1698c9de560dSAlex Tomas 			unlock_page(page);
1699c9de560dSAlex Tomas 		}
1700c9de560dSAlex Tomas 	}
1701c57ab39bSYounger Liu 	if (page == NULL) {
1702c57ab39bSYounger Liu 		ret = -ENOMEM;
1703c57ab39bSYounger Liu 		goto err;
1704c57ab39bSYounger Liu 	}
1705c57ab39bSYounger Liu 	if (!PageUptodate(page)) {
1706fdf6c7a7SShen Feng 		ret = -EIO;
1707c9de560dSAlex Tomas 		goto err;
1708fdf6c7a7SShen Feng 	}
17092457aec6SMel Gorman 
17102457aec6SMel Gorman 	/* Pages marked accessed already */
1711c9de560dSAlex Tomas 	e4b->bd_buddy_page = page;
1712c9de560dSAlex Tomas 	e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1713c9de560dSAlex Tomas 
1714c9de560dSAlex Tomas 	return 0;
1715c9de560dSAlex Tomas 
1716c9de560dSAlex Tomas err:
171726626f11SYang Ruirui 	if (page)
171809cbfeafSKirill A. Shutemov 		put_page(page);
1719c9de560dSAlex Tomas 	if (e4b->bd_bitmap_page)
172009cbfeafSKirill A. Shutemov 		put_page(e4b->bd_bitmap_page);
1721285164b8SKemeng Shi 
1722c9de560dSAlex Tomas 	e4b->bd_buddy = NULL;
1723c9de560dSAlex Tomas 	e4b->bd_bitmap = NULL;
1724fdf6c7a7SShen Feng 	return ret;
1725c9de560dSAlex Tomas }
1726c9de560dSAlex Tomas 
1727adb7ef60SKonstantin Khlebnikov static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1728adb7ef60SKonstantin Khlebnikov 			      struct ext4_buddy *e4b)
1729adb7ef60SKonstantin Khlebnikov {
1730adb7ef60SKonstantin Khlebnikov 	return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1731adb7ef60SKonstantin Khlebnikov }
1732adb7ef60SKonstantin Khlebnikov 
1733e39e07fdSJing Zhang static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1734c9de560dSAlex Tomas {
1735c9de560dSAlex Tomas 	if (e4b->bd_bitmap_page)
173609cbfeafSKirill A. Shutemov 		put_page(e4b->bd_bitmap_page);
1737c9de560dSAlex Tomas 	if (e4b->bd_buddy_page)
173809cbfeafSKirill A. Shutemov 		put_page(e4b->bd_buddy_page);
1739c9de560dSAlex Tomas }
1740c9de560dSAlex Tomas 
1741c9de560dSAlex Tomas 
1742c9de560dSAlex Tomas static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1743c9de560dSAlex Tomas {
1744ce3cca33SChunguang Xu 	int order = 1, max;
1745c9de560dSAlex Tomas 	void *bb;
1746c9de560dSAlex Tomas 
1747c5e8f3f3STheodore Ts'o 	BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1748c9de560dSAlex Tomas 	BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1749c9de560dSAlex Tomas 
1750c9de560dSAlex Tomas 	while (order <= e4b->bd_blkbits + 1) {
1751ce3cca33SChunguang Xu 		bb = mb_find_buddy(e4b, order, &max);
1752ce3cca33SChunguang Xu 		if (!mb_test_bit(block >> order, bb)) {
1753c9de560dSAlex Tomas 			/* this block is part of buddy of order 'order' */
1754c9de560dSAlex Tomas 			return order;
1755c9de560dSAlex Tomas 		}
1756c9de560dSAlex Tomas 		order++;
1757c9de560dSAlex Tomas 	}
1758c9de560dSAlex Tomas 	return 0;
1759c9de560dSAlex Tomas }
1760c9de560dSAlex Tomas 
1761955ce5f5SAneesh Kumar K.V static void mb_clear_bits(void *bm, int cur, int len)
1762c9de560dSAlex Tomas {
1763c9de560dSAlex Tomas 	__u32 *addr;
1764c9de560dSAlex Tomas 
1765c9de560dSAlex Tomas 	len = cur + len;
1766c9de560dSAlex Tomas 	while (cur < len) {
1767c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1768c9de560dSAlex Tomas 			/* fast path: clear whole word at once */
1769c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1770c9de560dSAlex Tomas 			*addr = 0;
1771c9de560dSAlex Tomas 			cur += 32;
1772c9de560dSAlex Tomas 			continue;
1773c9de560dSAlex Tomas 		}
1774e8134b27SAneesh Kumar K.V 		mb_clear_bit(cur, bm);
1775c9de560dSAlex Tomas 		cur++;
1776c9de560dSAlex Tomas 	}
1777c9de560dSAlex Tomas }
1778c9de560dSAlex Tomas 
1779eabe0444SAndrey Sidorov /* clear bits in given range
1780eabe0444SAndrey Sidorov  * will return first found zero bit if any, -1 otherwise
1781eabe0444SAndrey Sidorov  */
1782eabe0444SAndrey Sidorov static int mb_test_and_clear_bits(void *bm, int cur, int len)
1783eabe0444SAndrey Sidorov {
1784eabe0444SAndrey Sidorov 	__u32 *addr;
1785eabe0444SAndrey Sidorov 	int zero_bit = -1;
1786eabe0444SAndrey Sidorov 
1787eabe0444SAndrey Sidorov 	len = cur + len;
1788eabe0444SAndrey Sidorov 	while (cur < len) {
1789eabe0444SAndrey Sidorov 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1790eabe0444SAndrey Sidorov 			/* fast path: clear whole word at once */
1791eabe0444SAndrey Sidorov 			addr = bm + (cur >> 3);
1792eabe0444SAndrey Sidorov 			if (*addr != (__u32)(-1) && zero_bit == -1)
1793eabe0444SAndrey Sidorov 				zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1794eabe0444SAndrey Sidorov 			*addr = 0;
1795eabe0444SAndrey Sidorov 			cur += 32;
1796eabe0444SAndrey Sidorov 			continue;
1797eabe0444SAndrey Sidorov 		}
1798eabe0444SAndrey Sidorov 		if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1799eabe0444SAndrey Sidorov 			zero_bit = cur;
1800eabe0444SAndrey Sidorov 		cur++;
1801eabe0444SAndrey Sidorov 	}
1802eabe0444SAndrey Sidorov 
1803eabe0444SAndrey Sidorov 	return zero_bit;
1804eabe0444SAndrey Sidorov }
1805eabe0444SAndrey Sidorov 
1806123e3016SRitesh Harjani void mb_set_bits(void *bm, int cur, int len)
1807c9de560dSAlex Tomas {
1808c9de560dSAlex Tomas 	__u32 *addr;
1809c9de560dSAlex Tomas 
1810c9de560dSAlex Tomas 	len = cur + len;
1811c9de560dSAlex Tomas 	while (cur < len) {
1812c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1813c9de560dSAlex Tomas 			/* fast path: set whole word at once */
1814c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1815c9de560dSAlex Tomas 			*addr = 0xffffffff;
1816c9de560dSAlex Tomas 			cur += 32;
1817c9de560dSAlex Tomas 			continue;
1818c9de560dSAlex Tomas 		}
1819e8134b27SAneesh Kumar K.V 		mb_set_bit(cur, bm);
1820c9de560dSAlex Tomas 		cur++;
1821c9de560dSAlex Tomas 	}
1822c9de560dSAlex Tomas }
1823c9de560dSAlex Tomas 
1824eabe0444SAndrey Sidorov static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1825eabe0444SAndrey Sidorov {
1826eabe0444SAndrey Sidorov 	if (mb_test_bit(*bit + side, bitmap)) {
1827eabe0444SAndrey Sidorov 		mb_clear_bit(*bit, bitmap);
1828eabe0444SAndrey Sidorov 		(*bit) -= side;
1829eabe0444SAndrey Sidorov 		return 1;
1830eabe0444SAndrey Sidorov 	}
1831eabe0444SAndrey Sidorov 	else {
1832eabe0444SAndrey Sidorov 		(*bit) += side;
1833eabe0444SAndrey Sidorov 		mb_set_bit(*bit, bitmap);
1834eabe0444SAndrey Sidorov 		return -1;
1835eabe0444SAndrey Sidorov 	}
1836eabe0444SAndrey Sidorov }
1837eabe0444SAndrey Sidorov 
1838eabe0444SAndrey Sidorov static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1839eabe0444SAndrey Sidorov {
1840eabe0444SAndrey Sidorov 	int max;
1841eabe0444SAndrey Sidorov 	int order = 1;
1842eabe0444SAndrey Sidorov 	void *buddy = mb_find_buddy(e4b, order, &max);
1843eabe0444SAndrey Sidorov 
1844eabe0444SAndrey Sidorov 	while (buddy) {
1845eabe0444SAndrey Sidorov 		void *buddy2;
1846eabe0444SAndrey Sidorov 
1847eabe0444SAndrey Sidorov 		/* Bits in range [first; last] are known to be set since
1848eabe0444SAndrey Sidorov 		 * corresponding blocks were allocated. Bits in range
1849eabe0444SAndrey Sidorov 		 * (first; last) will stay set because they form buddies on
1850eabe0444SAndrey Sidorov 		 * upper layer. We just deal with borders if they don't
1851eabe0444SAndrey Sidorov 		 * align with upper layer and then go up.
1852eabe0444SAndrey Sidorov 		 * Releasing entire group is all about clearing
1853eabe0444SAndrey Sidorov 		 * single bit of highest order buddy.
1854eabe0444SAndrey Sidorov 		 */
1855eabe0444SAndrey Sidorov 
1856eabe0444SAndrey Sidorov 		/* Example:
1857eabe0444SAndrey Sidorov 		 * ---------------------------------
1858eabe0444SAndrey Sidorov 		 * |   1   |   1   |   1   |   1   |
1859eabe0444SAndrey Sidorov 		 * ---------------------------------
1860eabe0444SAndrey Sidorov 		 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1861eabe0444SAndrey Sidorov 		 * ---------------------------------
1862eabe0444SAndrey Sidorov 		 *   0   1   2   3   4   5   6   7
1863eabe0444SAndrey Sidorov 		 *      \_____________________/
1864eabe0444SAndrey Sidorov 		 *
1865eabe0444SAndrey Sidorov 		 * Neither [1] nor [6] is aligned to above layer.
1866eabe0444SAndrey Sidorov 		 * Left neighbour [0] is free, so mark it busy,
1867eabe0444SAndrey Sidorov 		 * decrease bb_counters and extend range to
1868eabe0444SAndrey Sidorov 		 * [0; 6]
1869eabe0444SAndrey Sidorov 		 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1870eabe0444SAndrey Sidorov 		 * mark [6] free, increase bb_counters and shrink range to
1871eabe0444SAndrey Sidorov 		 * [0; 5].
1872eabe0444SAndrey Sidorov 		 * Then shift range to [0; 2], go up and do the same.
1873eabe0444SAndrey Sidorov 		 */
1874eabe0444SAndrey Sidorov 
1875eabe0444SAndrey Sidorov 
1876eabe0444SAndrey Sidorov 		if (first & 1)
1877eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1878eabe0444SAndrey Sidorov 		if (!(last & 1))
1879eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1880eabe0444SAndrey Sidorov 		if (first > last)
1881eabe0444SAndrey Sidorov 			break;
1882eabe0444SAndrey Sidorov 		order++;
1883eabe0444SAndrey Sidorov 
1884976620bdSKemeng Shi 		buddy2 = mb_find_buddy(e4b, order, &max);
1885976620bdSKemeng Shi 		if (!buddy2) {
1886eabe0444SAndrey Sidorov 			mb_clear_bits(buddy, first, last - first + 1);
1887eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1888eabe0444SAndrey Sidorov 			break;
1889eabe0444SAndrey Sidorov 		}
1890eabe0444SAndrey Sidorov 		first >>= 1;
1891eabe0444SAndrey Sidorov 		last >>= 1;
1892eabe0444SAndrey Sidorov 		buddy = buddy2;
1893eabe0444SAndrey Sidorov 	}
1894eabe0444SAndrey Sidorov }
1895eabe0444SAndrey Sidorov 
18967e5a8cddSShen Feng static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1897c9de560dSAlex Tomas 			   int first, int count)
1898c9de560dSAlex Tomas {
1899eabe0444SAndrey Sidorov 	int left_is_free = 0;
1900eabe0444SAndrey Sidorov 	int right_is_free = 0;
1901eabe0444SAndrey Sidorov 	int block;
1902eabe0444SAndrey Sidorov 	int last = first + count - 1;
1903c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
1904c9de560dSAlex Tomas 
1905c99d1e6eSTheodore Ts'o 	if (WARN_ON(count == 0))
1906c99d1e6eSTheodore Ts'o 		return;
1907eabe0444SAndrey Sidorov 	BUG_ON(last >= (sb->s_blocksize << 3));
1908bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1909163a203dSDarrick J. Wong 	/* Don't bother if the block group is corrupt. */
1910163a203dSDarrick J. Wong 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1911163a203dSDarrick J. Wong 		return;
1912163a203dSDarrick J. Wong 
1913c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1914c9de560dSAlex Tomas 	mb_free_blocks_double(inode, e4b, first, count);
1915c9de560dSAlex Tomas 
1916eabe0444SAndrey Sidorov 	/* access memory sequentially: check left neighbour,
1917eabe0444SAndrey Sidorov 	 * clear range and then check right neighbour
1918eabe0444SAndrey Sidorov 	 */
1919c9de560dSAlex Tomas 	if (first != 0)
1920eabe0444SAndrey Sidorov 		left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1921eabe0444SAndrey Sidorov 	block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1922eabe0444SAndrey Sidorov 	if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1923eabe0444SAndrey Sidorov 		right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1924c9de560dSAlex Tomas 
1925eabe0444SAndrey Sidorov 	if (unlikely(block != -1)) {
1926e43bb4e6SNamjae Jeon 		struct ext4_sb_info *sbi = EXT4_SB(sb);
1927c9de560dSAlex Tomas 		ext4_fsblk_t blocknr;
19285661bd68SAkinobu Mita 
19292331fd4aSBaokun Li 		/*
19302331fd4aSBaokun Li 		 * Fastcommit replay can free already freed blocks which
19312331fd4aSBaokun Li 		 * corrupts allocation info. Regenerate it.
19322331fd4aSBaokun Li 		 */
19332331fd4aSBaokun Li 		if (sbi->s_mount_state & EXT4_FC_REPLAY) {
19342331fd4aSBaokun Li 			mb_regenerate_buddy(e4b);
19352331fd4aSBaokun Li 			goto check;
19362331fd4aSBaokun Li 		}
19372331fd4aSBaokun Li 
19385661bd68SAkinobu Mita 		blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
193949598e04SJun Piao 		blocknr += EXT4_C2B(sbi, block);
1940c5f3a382SBaokun Li 		ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
1941c5f3a382SBaokun Li 				EXT4_GROUP_INFO_BBITMAP_CORRUPT);
19425d1b1b3fSAneesh Kumar K.V 		ext4_grp_locked_error(sb, e4b->bd_group,
19432331fd4aSBaokun Li 				      inode ? inode->i_ino : 0, blocknr,
19448016e29fSHarshad Shirwadkar 				      "freeing already freed block (bit %u); block bitmap corrupt.",
1945163a203dSDarrick J. Wong 				      block);
19462331fd4aSBaokun Li 		return;
19478016e29fSHarshad Shirwadkar 	}
19482331fd4aSBaokun Li 
19492331fd4aSBaokun Li 	this_cpu_inc(discard_pa_seq);
19502331fd4aSBaokun Li 	e4b->bd_info->bb_free += count;
19512331fd4aSBaokun Li 	if (first < e4b->bd_info->bb_first_free)
19522331fd4aSBaokun Li 		e4b->bd_info->bb_first_free = first;
1953c9de560dSAlex Tomas 
1954eabe0444SAndrey Sidorov 	/* let's maintain fragments counter */
1955eabe0444SAndrey Sidorov 	if (left_is_free && right_is_free)
1956eabe0444SAndrey Sidorov 		e4b->bd_info->bb_fragments--;
1957eabe0444SAndrey Sidorov 	else if (!left_is_free && !right_is_free)
1958eabe0444SAndrey Sidorov 		e4b->bd_info->bb_fragments++;
1959c9de560dSAlex Tomas 
1960eabe0444SAndrey Sidorov 	/* buddy[0] == bd_bitmap is a special case, so handle
1961eabe0444SAndrey Sidorov 	 * it right away and let mb_buddy_mark_free stay free of
1962eabe0444SAndrey Sidorov 	 * zero order checks.
1963eabe0444SAndrey Sidorov 	 * Check if neighbours are to be coaleasced,
1964eabe0444SAndrey Sidorov 	 * adjust bitmap bb_counters and borders appropriately.
1965eabe0444SAndrey Sidorov 	 */
1966eabe0444SAndrey Sidorov 	if (first & 1) {
1967eabe0444SAndrey Sidorov 		first += !left_is_free;
1968eabe0444SAndrey Sidorov 		e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1969c9de560dSAlex Tomas 	}
1970eabe0444SAndrey Sidorov 	if (!(last & 1)) {
1971eabe0444SAndrey Sidorov 		last -= !right_is_free;
1972eabe0444SAndrey Sidorov 		e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1973c9de560dSAlex Tomas 	}
1974eabe0444SAndrey Sidorov 
1975eabe0444SAndrey Sidorov 	if (first <= last)
1976eabe0444SAndrey Sidorov 		mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1977eabe0444SAndrey Sidorov 
19788a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, e4b->bd_info);
1979196e402aSHarshad Shirwadkar 	mb_update_avg_fragment_size(sb, e4b->bd_info);
19802331fd4aSBaokun Li check:
1981c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1982c9de560dSAlex Tomas }
1983c9de560dSAlex Tomas 
198415c006a2SRobin Dong static int mb_find_extent(struct ext4_buddy *e4b, int block,
1985c9de560dSAlex Tomas 				int needed, struct ext4_free_extent *ex)
1986c9de560dSAlex Tomas {
19872bf5eb2aSGou Hao 	int max, order, next;
1988c9de560dSAlex Tomas 	void *buddy;
1989c9de560dSAlex Tomas 
1990bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1991c9de560dSAlex Tomas 	BUG_ON(ex == NULL);
1992c9de560dSAlex Tomas 
199315c006a2SRobin Dong 	buddy = mb_find_buddy(e4b, 0, &max);
1994c9de560dSAlex Tomas 	BUG_ON(buddy == NULL);
1995c9de560dSAlex Tomas 	BUG_ON(block >= max);
1996c9de560dSAlex Tomas 	if (mb_test_bit(block, buddy)) {
1997c9de560dSAlex Tomas 		ex->fe_len = 0;
1998c9de560dSAlex Tomas 		ex->fe_start = 0;
1999c9de560dSAlex Tomas 		ex->fe_group = 0;
2000c9de560dSAlex Tomas 		return 0;
2001c9de560dSAlex Tomas 	}
2002c9de560dSAlex Tomas 
2003c9de560dSAlex Tomas 	/* find actual order */
2004c9de560dSAlex Tomas 	order = mb_find_order_for_block(e4b, block);
2005c9de560dSAlex Tomas 
20062bf5eb2aSGou Hao 	ex->fe_len = (1 << order) - (block & ((1 << order) - 1));
20072bf5eb2aSGou Hao 	ex->fe_start = block;
2008c9de560dSAlex Tomas 	ex->fe_group = e4b->bd_group;
2009c9de560dSAlex Tomas 
20102bf5eb2aSGou Hao 	block = block >> order;
2011c9de560dSAlex Tomas 
2012c9de560dSAlex Tomas 	while (needed > ex->fe_len &&
2013d8ec0c39SAlan Cox 	       mb_find_buddy(e4b, order, &max)) {
2014c9de560dSAlex Tomas 
2015c9de560dSAlex Tomas 		if (block + 1 >= max)
2016c9de560dSAlex Tomas 			break;
2017c9de560dSAlex Tomas 
2018c9de560dSAlex Tomas 		next = (block + 1) * (1 << order);
2019c5e8f3f3STheodore Ts'o 		if (mb_test_bit(next, e4b->bd_bitmap))
2020c9de560dSAlex Tomas 			break;
2021c9de560dSAlex Tomas 
2022b051d8dcSRobin Dong 		order = mb_find_order_for_block(e4b, next);
2023c9de560dSAlex Tomas 
2024c9de560dSAlex Tomas 		block = next >> order;
2025c9de560dSAlex Tomas 		ex->fe_len += 1 << order;
2026c9de560dSAlex Tomas 	}
2027c9de560dSAlex Tomas 
202831562b95SJan Kara 	if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
202943c73221STheodore Ts'o 		/* Should never happen! (but apparently sometimes does?!?) */
203043c73221STheodore Ts'o 		WARN_ON(1);
2031cd84bbbaSStephen Brennan 		ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
2032cd84bbbaSStephen Brennan 			"corruption or bug in mb_find_extent "
203343c73221STheodore Ts'o 			"block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
203443c73221STheodore Ts'o 			block, order, needed, ex->fe_group, ex->fe_start,
203543c73221STheodore Ts'o 			ex->fe_len, ex->fe_logical);
203643c73221STheodore Ts'o 		ex->fe_len = 0;
203743c73221STheodore Ts'o 		ex->fe_start = 0;
203843c73221STheodore Ts'o 		ex->fe_group = 0;
203943c73221STheodore Ts'o 	}
2040c9de560dSAlex Tomas 	return ex->fe_len;
2041c9de560dSAlex Tomas }
2042c9de560dSAlex Tomas 
2043c9de560dSAlex Tomas static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
2044c9de560dSAlex Tomas {
2045c9de560dSAlex Tomas 	int ord;
2046c9de560dSAlex Tomas 	int mlen = 0;
2047c9de560dSAlex Tomas 	int max = 0;
2048c9de560dSAlex Tomas 	int start = ex->fe_start;
2049c9de560dSAlex Tomas 	int len = ex->fe_len;
2050c9de560dSAlex Tomas 	unsigned ret = 0;
2051c9de560dSAlex Tomas 	int len0 = len;
2052c9de560dSAlex Tomas 	void *buddy;
2053d1a3924eSKemeng Shi 	int ord_start, ord_end;
2054c9de560dSAlex Tomas 
2055c9de560dSAlex Tomas 	BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
2056c9de560dSAlex Tomas 	BUG_ON(e4b->bd_group != ex->fe_group);
2057bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
2058c9de560dSAlex Tomas 	mb_check_buddy(e4b);
2059c9de560dSAlex Tomas 	mb_mark_used_double(e4b, start, len);
2060c9de560dSAlex Tomas 
206107b5b8e1SRitesh Harjani 	this_cpu_inc(discard_pa_seq);
2062c9de560dSAlex Tomas 	e4b->bd_info->bb_free -= len;
2063c9de560dSAlex Tomas 	if (e4b->bd_info->bb_first_free == start)
2064c9de560dSAlex Tomas 		e4b->bd_info->bb_first_free += len;
2065c9de560dSAlex Tomas 
2066c9de560dSAlex Tomas 	/* let's maintain fragments counter */
2067c9de560dSAlex Tomas 	if (start != 0)
2068c5e8f3f3STheodore Ts'o 		mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
2069c9de560dSAlex Tomas 	if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
2070c5e8f3f3STheodore Ts'o 		max = !mb_test_bit(start + len, e4b->bd_bitmap);
2071c9de560dSAlex Tomas 	if (mlen && max)
2072c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments++;
2073c9de560dSAlex Tomas 	else if (!mlen && !max)
2074c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments--;
2075c9de560dSAlex Tomas 
2076c9de560dSAlex Tomas 	/* let's maintain buddy itself */
2077c9de560dSAlex Tomas 	while (len) {
2078c9de560dSAlex Tomas 		ord = mb_find_order_for_block(e4b, start);
2079c9de560dSAlex Tomas 
2080c9de560dSAlex Tomas 		if (((start >> ord) << ord) == start && len >= (1 << ord)) {
2081c9de560dSAlex Tomas 			/* the whole chunk may be allocated at once! */
2082c9de560dSAlex Tomas 			mlen = 1 << ord;
2083c9de560dSAlex Tomas 			buddy = mb_find_buddy(e4b, ord, &max);
2084c9de560dSAlex Tomas 			BUG_ON((start >> ord) >= max);
2085c9de560dSAlex Tomas 			mb_set_bit(start >> ord, buddy);
2086c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[ord]--;
2087c9de560dSAlex Tomas 			start += mlen;
2088c9de560dSAlex Tomas 			len -= mlen;
2089c9de560dSAlex Tomas 			BUG_ON(len < 0);
2090c9de560dSAlex Tomas 			continue;
2091c9de560dSAlex Tomas 		}
2092c9de560dSAlex Tomas 
2093c9de560dSAlex Tomas 		/* store for history */
2094c9de560dSAlex Tomas 		if (ret == 0)
2095c9de560dSAlex Tomas 			ret = len | (ord << 16);
2096c9de560dSAlex Tomas 
2097c9de560dSAlex Tomas 		BUG_ON(ord <= 0);
2098c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, ord, &max);
2099c9de560dSAlex Tomas 		mb_set_bit(start >> ord, buddy);
2100c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]--;
2101c9de560dSAlex Tomas 
2102d1a3924eSKemeng Shi 		ord_start = (start >> ord) << ord;
2103d1a3924eSKemeng Shi 		ord_end = ord_start + (1 << ord);
2104d1a3924eSKemeng Shi 		/* first chunk */
2105d1a3924eSKemeng Shi 		if (start > ord_start)
2106d1a3924eSKemeng Shi 			ext4_mb_mark_free_simple(e4b->bd_sb, e4b->bd_buddy,
2107d1a3924eSKemeng Shi 						 ord_start, start - ord_start,
2108d1a3924eSKemeng Shi 						 e4b->bd_info);
2109d1a3924eSKemeng Shi 
2110d1a3924eSKemeng Shi 		/* last chunk */
2111d1a3924eSKemeng Shi 		if (start + len < ord_end) {
2112d1a3924eSKemeng Shi 			ext4_mb_mark_free_simple(e4b->bd_sb, e4b->bd_buddy,
2113d1a3924eSKemeng Shi 						 start + len,
2114d1a3924eSKemeng Shi 						 ord_end - (start + len),
2115d1a3924eSKemeng Shi 						 e4b->bd_info);
2116d1a3924eSKemeng Shi 			break;
2117d1a3924eSKemeng Shi 		}
2118d1a3924eSKemeng Shi 		len = start + len - ord_end;
2119d1a3924eSKemeng Shi 		start = ord_end;
2120c9de560dSAlex Tomas 	}
21218a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
2122c9de560dSAlex Tomas 
2123196e402aSHarshad Shirwadkar 	mb_update_avg_fragment_size(e4b->bd_sb, e4b->bd_info);
2124123e3016SRitesh Harjani 	mb_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
2125c9de560dSAlex Tomas 	mb_check_buddy(e4b);
2126c9de560dSAlex Tomas 
2127c9de560dSAlex Tomas 	return ret;
2128c9de560dSAlex Tomas }
2129c9de560dSAlex Tomas 
2130c9de560dSAlex Tomas /*
2131c9de560dSAlex Tomas  * Must be called under group lock!
2132c9de560dSAlex Tomas  */
2133c9de560dSAlex Tomas static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
2134c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2135c9de560dSAlex Tomas {
2136c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2137c9de560dSAlex Tomas 	int ret;
2138c9de560dSAlex Tomas 
2139c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
2140c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2141c9de560dSAlex Tomas 
2142c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
2143c9de560dSAlex Tomas 	ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
2144c9de560dSAlex Tomas 	ret = mb_mark_used(e4b, &ac->ac_b_ex);
2145c9de560dSAlex Tomas 
2146c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
2147c9de560dSAlex Tomas 	 * allocated blocks for history */
2148c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
2149c9de560dSAlex Tomas 
2150c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
2151c9de560dSAlex Tomas 	ac->ac_tail = ret & 0xffff;
2152c9de560dSAlex Tomas 	ac->ac_buddy = ret >> 16;
2153c9de560dSAlex Tomas 
2154c3a326a6SAneesh Kumar K.V 	/*
2155c3a326a6SAneesh Kumar K.V 	 * take the page reference. We want the page to be pinned
2156c3a326a6SAneesh Kumar K.V 	 * so that we don't get a ext4_mb_init_cache_call for this
2157c3a326a6SAneesh Kumar K.V 	 * group until we update the bitmap. That would mean we
2158c3a326a6SAneesh Kumar K.V 	 * double allocate blocks. The reference is dropped
2159c3a326a6SAneesh Kumar K.V 	 * in ext4_mb_release_context
2160c3a326a6SAneesh Kumar K.V 	 */
2161c9de560dSAlex Tomas 	ac->ac_bitmap_page = e4b->bd_bitmap_page;
2162c9de560dSAlex Tomas 	get_page(ac->ac_bitmap_page);
2163c9de560dSAlex Tomas 	ac->ac_buddy_page = e4b->bd_buddy_page;
2164c9de560dSAlex Tomas 	get_page(ac->ac_buddy_page);
2165c9de560dSAlex Tomas 	/* store last allocated for subsequent stream allocation */
21664ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2167c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
2168c9de560dSAlex Tomas 		sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
2169c9de560dSAlex Tomas 		sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
2170c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
2171c9de560dSAlex Tomas 	}
217253f86b17SRitesh Harjani 	/*
217353f86b17SRitesh Harjani 	 * As we've just preallocated more space than
217453f86b17SRitesh Harjani 	 * user requested originally, we store allocated
217553f86b17SRitesh Harjani 	 * space in a special descriptor.
217653f86b17SRitesh Harjani 	 */
217753f86b17SRitesh Harjani 	if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
217853f86b17SRitesh Harjani 		ext4_mb_new_preallocation(ac);
217953f86b17SRitesh Harjani 
2180c9de560dSAlex Tomas }
2181c9de560dSAlex Tomas 
2182c9de560dSAlex Tomas static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
2183c9de560dSAlex Tomas 					struct ext4_buddy *e4b,
2184c9de560dSAlex Tomas 					int finish_group)
2185c9de560dSAlex Tomas {
2186c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2187c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
2188c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
2189c9de560dSAlex Tomas 
2190032115fcSAneesh Kumar K.V 	if (ac->ac_status == AC_STATUS_FOUND)
2191032115fcSAneesh Kumar K.V 		return;
2192c9de560dSAlex Tomas 	/*
2193c9de560dSAlex Tomas 	 * We don't want to scan for a whole year
2194c9de560dSAlex Tomas 	 */
2195c9de560dSAlex Tomas 	if (ac->ac_found > sbi->s_mb_max_to_scan &&
2196c9de560dSAlex Tomas 			!(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2197c9de560dSAlex Tomas 		ac->ac_status = AC_STATUS_BREAK;
2198c9de560dSAlex Tomas 		return;
2199c9de560dSAlex Tomas 	}
2200c9de560dSAlex Tomas 
2201c9de560dSAlex Tomas 	/*
2202c9de560dSAlex Tomas 	 * Haven't found good chunk so far, let's continue
2203c9de560dSAlex Tomas 	 */
2204c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len)
2205c9de560dSAlex Tomas 		return;
2206c9de560dSAlex Tomas 
22073582e745SOjaswin Mujoo 	if (finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
2208c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2209c9de560dSAlex Tomas }
2210c9de560dSAlex Tomas 
2211c9de560dSAlex Tomas /*
2212c9de560dSAlex Tomas  * The routine checks whether found extent is good enough. If it is,
2213c9de560dSAlex Tomas  * then the extent gets marked used and flag is set to the context
2214c9de560dSAlex Tomas  * to stop scanning. Otherwise, the extent is compared with the
2215c9de560dSAlex Tomas  * previous found extent and if new one is better, then it's stored
2216c9de560dSAlex Tomas  * in the context. Later, the best found extent will be used, if
2217c9de560dSAlex Tomas  * mballoc can't find good enough extent.
2218c9de560dSAlex Tomas  *
22193582e745SOjaswin Mujoo  * The algorithm used is roughly as follows:
22203582e745SOjaswin Mujoo  *
22213582e745SOjaswin Mujoo  * * If free extent found is exactly as big as goal, then
22223582e745SOjaswin Mujoo  *   stop the scan and use it immediately
22233582e745SOjaswin Mujoo  *
22243582e745SOjaswin Mujoo  * * If free extent found is smaller than goal, then keep retrying
22253582e745SOjaswin Mujoo  *   upto a max of sbi->s_mb_max_to_scan times (default 200). After
22263582e745SOjaswin Mujoo  *   that stop scanning and use whatever we have.
22273582e745SOjaswin Mujoo  *
22283582e745SOjaswin Mujoo  * * If free extent found is bigger than goal, then keep retrying
22293582e745SOjaswin Mujoo  *   upto a max of sbi->s_mb_min_to_scan times (default 10) before
22303582e745SOjaswin Mujoo  *   stopping the scan and using the extent.
22313582e745SOjaswin Mujoo  *
22323582e745SOjaswin Mujoo  *
2233c9de560dSAlex Tomas  * FIXME: real allocation policy is to be designed yet!
2234c9de560dSAlex Tomas  */
2235c9de560dSAlex Tomas static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
2236c9de560dSAlex Tomas 					struct ext4_free_extent *ex,
2237c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2238c9de560dSAlex Tomas {
2239c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
2240c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
2241c9de560dSAlex Tomas 
2242c9de560dSAlex Tomas 	BUG_ON(ex->fe_len <= 0);
22437137d7a4STheodore Ts'o 	BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
22447137d7a4STheodore Ts'o 	BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2245c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
2246c9de560dSAlex Tomas 
2247c9de560dSAlex Tomas 	ac->ac_found++;
2248fdd9a009SOjaswin Mujoo 	ac->ac_cX_found[ac->ac_criteria]++;
2249c9de560dSAlex Tomas 
2250c9de560dSAlex Tomas 	/*
2251c9de560dSAlex Tomas 	 * The special case - take what you catch first
2252c9de560dSAlex Tomas 	 */
2253c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2254c9de560dSAlex Tomas 		*bex = *ex;
2255c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2256c9de560dSAlex Tomas 		return;
2257c9de560dSAlex Tomas 	}
2258c9de560dSAlex Tomas 
2259c9de560dSAlex Tomas 	/*
2260c9de560dSAlex Tomas 	 * Let's check whether the chuck is good enough
2261c9de560dSAlex Tomas 	 */
2262c9de560dSAlex Tomas 	if (ex->fe_len == gex->fe_len) {
2263c9de560dSAlex Tomas 		*bex = *ex;
2264c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2265c9de560dSAlex Tomas 		return;
2266c9de560dSAlex Tomas 	}
2267c9de560dSAlex Tomas 
2268c9de560dSAlex Tomas 	/*
2269c9de560dSAlex Tomas 	 * If this is first found extent, just store it in the context
2270c9de560dSAlex Tomas 	 */
2271c9de560dSAlex Tomas 	if (bex->fe_len == 0) {
2272c9de560dSAlex Tomas 		*bex = *ex;
2273c9de560dSAlex Tomas 		return;
2274c9de560dSAlex Tomas 	}
2275c9de560dSAlex Tomas 
2276c9de560dSAlex Tomas 	/*
2277c9de560dSAlex Tomas 	 * If new found extent is better, store it in the context
2278c9de560dSAlex Tomas 	 */
2279c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len) {
2280c9de560dSAlex Tomas 		/* if the request isn't satisfied, any found extent
2281c9de560dSAlex Tomas 		 * larger than previous best one is better */
2282c9de560dSAlex Tomas 		if (ex->fe_len > bex->fe_len)
2283c9de560dSAlex Tomas 			*bex = *ex;
2284c9de560dSAlex Tomas 	} else if (ex->fe_len > gex->fe_len) {
2285c9de560dSAlex Tomas 		/* if the request is satisfied, then we try to find
2286c9de560dSAlex Tomas 		 * an extent that still satisfy the request, but is
2287c9de560dSAlex Tomas 		 * smaller than previous one */
2288c9de560dSAlex Tomas 		if (ex->fe_len < bex->fe_len)
2289c9de560dSAlex Tomas 			*bex = *ex;
2290c9de560dSAlex Tomas 	}
2291c9de560dSAlex Tomas 
2292c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 0);
2293c9de560dSAlex Tomas }
2294c9de560dSAlex Tomas 
2295089ceeccSEric Sandeen static noinline_for_stack
229685b67ffbSKemeng Shi void ext4_mb_try_best_found(struct ext4_allocation_context *ac,
2297c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2298c9de560dSAlex Tomas {
2299c9de560dSAlex Tomas 	struct ext4_free_extent ex = ac->ac_b_ex;
2300c9de560dSAlex Tomas 	ext4_group_t group = ex.fe_group;
2301c9de560dSAlex Tomas 	int max;
2302c9de560dSAlex Tomas 	int err;
2303c9de560dSAlex Tomas 
2304c9de560dSAlex Tomas 	BUG_ON(ex.fe_len <= 0);
2305c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2306c9de560dSAlex Tomas 	if (err)
230785b67ffbSKemeng Shi 		return;
2308c9de560dSAlex Tomas 
2309c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
23104530b366SBaokun Li 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
23114530b366SBaokun Li 		goto out;
23124530b366SBaokun Li 
231315c006a2SRobin Dong 	max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
2314c9de560dSAlex Tomas 
2315c9de560dSAlex Tomas 	if (max > 0) {
2316c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
2317c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2318c9de560dSAlex Tomas 	}
2319c9de560dSAlex Tomas 
23204530b366SBaokun Li out:
2321c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
2322e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
2323c9de560dSAlex Tomas }
2324c9de560dSAlex Tomas 
2325089ceeccSEric Sandeen static noinline_for_stack
2326089ceeccSEric Sandeen int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
2327c9de560dSAlex Tomas 				struct ext4_buddy *e4b)
2328c9de560dSAlex Tomas {
2329c9de560dSAlex Tomas 	ext4_group_t group = ac->ac_g_ex.fe_group;
2330c9de560dSAlex Tomas 	int max;
2331c9de560dSAlex Tomas 	int err;
2332c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2333838cd0cfSYongqiang Yang 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2334c9de560dSAlex Tomas 	struct ext4_free_extent ex;
2335c9de560dSAlex Tomas 
23365354b2afSTheodore Ts'o 	if (!grp)
23375354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
233801e4ca29SKemeng Shi 	if (!(ac->ac_flags & (EXT4_MB_HINT_TRY_GOAL | EXT4_MB_HINT_GOAL_ONLY)))
2339c9de560dSAlex Tomas 		return 0;
2340838cd0cfSYongqiang Yang 	if (grp->bb_free == 0)
2341838cd0cfSYongqiang Yang 		return 0;
2342c9de560dSAlex Tomas 
2343c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2344c9de560dSAlex Tomas 	if (err)
2345c9de560dSAlex Tomas 		return err;
2346c9de560dSAlex Tomas 
2347c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
234883269837SBaokun Li 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
234983269837SBaokun Li 		goto out;
235083269837SBaokun Li 
235115c006a2SRobin Dong 	max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
2352c9de560dSAlex Tomas 			     ac->ac_g_ex.fe_len, &ex);
2353ab0c00fcSTheodore Ts'o 	ex.fe_logical = 0xDEADFA11; /* debug value */
2354c9de560dSAlex Tomas 
2355c3defd99SKemeng Shi 	if (max >= ac->ac_g_ex.fe_len &&
2356c3defd99SKemeng Shi 	    ac->ac_g_ex.fe_len == EXT4_B2C(sbi, sbi->s_stripe)) {
2357c9de560dSAlex Tomas 		ext4_fsblk_t start;
2358c9de560dSAlex Tomas 
235999c515e3SKemeng Shi 		start = ext4_grp_offs_to_block(ac->ac_sb, &ex);
2360c9de560dSAlex Tomas 		/* use do_div to get remainder (would be 64-bit modulo) */
2361c9de560dSAlex Tomas 		if (do_div(start, sbi->s_stripe) == 0) {
2362c9de560dSAlex Tomas 			ac->ac_found++;
2363c9de560dSAlex Tomas 			ac->ac_b_ex = ex;
2364c9de560dSAlex Tomas 			ext4_mb_use_best_found(ac, e4b);
2365c9de560dSAlex Tomas 		}
2366c9de560dSAlex Tomas 	} else if (max >= ac->ac_g_ex.fe_len) {
2367c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
2368c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2369c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2370c9de560dSAlex Tomas 		ac->ac_found++;
2371c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
2372c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2373c9de560dSAlex Tomas 	} else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
2374c9de560dSAlex Tomas 		/* Sometimes, caller may want to merge even small
2375c9de560dSAlex Tomas 		 * number of blocks to an existing extent */
2376c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
2377c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2378c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2379c9de560dSAlex Tomas 		ac->ac_found++;
2380c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
2381c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2382c9de560dSAlex Tomas 	}
238383269837SBaokun Li out:
2384c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
2385e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
2386c9de560dSAlex Tomas 
2387c9de560dSAlex Tomas 	return 0;
2388c9de560dSAlex Tomas }
2389c9de560dSAlex Tomas 
2390c9de560dSAlex Tomas /*
2391c9de560dSAlex Tomas  * The routine scans buddy structures (not bitmap!) from given order
2392c9de560dSAlex Tomas  * to max order and tries to find big enough chunk to satisfy the req
2393c9de560dSAlex Tomas  */
2394089ceeccSEric Sandeen static noinline_for_stack
2395089ceeccSEric Sandeen void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
2396c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2397c9de560dSAlex Tomas {
2398c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
2399c9de560dSAlex Tomas 	struct ext4_group_info *grp = e4b->bd_info;
2400c9de560dSAlex Tomas 	void *buddy;
2401c9de560dSAlex Tomas 	int i;
2402c9de560dSAlex Tomas 	int k;
2403c9de560dSAlex Tomas 	int max;
2404c9de560dSAlex Tomas 
2405c9de560dSAlex Tomas 	BUG_ON(ac->ac_2order <= 0);
24064b68f6dfSHarshad Shirwadkar 	for (i = ac->ac_2order; i < MB_NUM_ORDERS(sb); i++) {
2407c9de560dSAlex Tomas 		if (grp->bb_counters[i] == 0)
2408c9de560dSAlex Tomas 			continue;
2409c9de560dSAlex Tomas 
2410c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, i, &max);
241119b8b035STheodore Ts'o 		if (WARN_RATELIMIT(buddy == NULL,
241219b8b035STheodore Ts'o 			 "ext4: mb_simple_scan_group: mb_find_buddy failed, (%d)\n", i))
241319b8b035STheodore Ts'o 			continue;
2414c9de560dSAlex Tomas 
2415ffad0a44SAneesh Kumar K.V 		k = mb_find_next_zero_bit(buddy, max, 0);
2416eb576086SDmitry Monakhov 		if (k >= max) {
2417eb576086SDmitry Monakhov 			ext4_mark_group_bitmap_corrupted(ac->ac_sb,
2418eb576086SDmitry Monakhov 					e4b->bd_group,
2419eb576086SDmitry Monakhov 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2420c5f3a382SBaokun Li 			ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
2421c5f3a382SBaokun Li 				"%d free clusters of order %d. But found 0",
2422c5f3a382SBaokun Li 				grp->bb_counters[i], i);
2423eb576086SDmitry Monakhov 			break;
2424eb576086SDmitry Monakhov 		}
2425c9de560dSAlex Tomas 		ac->ac_found++;
2426fdd9a009SOjaswin Mujoo 		ac->ac_cX_found[ac->ac_criteria]++;
2427c9de560dSAlex Tomas 
2428c9de560dSAlex Tomas 		ac->ac_b_ex.fe_len = 1 << i;
2429c9de560dSAlex Tomas 		ac->ac_b_ex.fe_start = k << i;
2430c9de560dSAlex Tomas 		ac->ac_b_ex.fe_group = e4b->bd_group;
2431c9de560dSAlex Tomas 
2432c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2433c9de560dSAlex Tomas 
243453f86b17SRitesh Harjani 		BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
2435c9de560dSAlex Tomas 
2436c9de560dSAlex Tomas 		if (EXT4_SB(sb)->s_mb_stats)
2437c9de560dSAlex Tomas 			atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
2438c9de560dSAlex Tomas 
2439c9de560dSAlex Tomas 		break;
2440c9de560dSAlex Tomas 	}
2441c9de560dSAlex Tomas }
2442c9de560dSAlex Tomas 
2443c9de560dSAlex Tomas /*
2444c9de560dSAlex Tomas  * The routine scans the group and measures all found extents.
2445c9de560dSAlex Tomas  * In order to optimize scanning, caller must pass number of
2446c9de560dSAlex Tomas  * free blocks in the group, so the routine can know upper limit.
2447c9de560dSAlex Tomas  */
2448089ceeccSEric Sandeen static noinline_for_stack
2449089ceeccSEric Sandeen void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
2450c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2451c9de560dSAlex Tomas {
2452c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
2453c5e8f3f3STheodore Ts'o 	void *bitmap = e4b->bd_bitmap;
2454c9de560dSAlex Tomas 	struct ext4_free_extent ex;
24551b420011SOjaswin Mujoo 	int i, j, freelen;
2456c9de560dSAlex Tomas 	int free;
2457c9de560dSAlex Tomas 
2458c9de560dSAlex Tomas 	free = e4b->bd_info->bb_free;
2459907ea529STheodore Ts'o 	if (WARN_ON(free <= 0))
2460907ea529STheodore Ts'o 		return;
2461c9de560dSAlex Tomas 
2462c9de560dSAlex Tomas 	i = e4b->bd_info->bb_first_free;
2463c9de560dSAlex Tomas 
2464c9de560dSAlex Tomas 	while (free && ac->ac_status == AC_STATUS_CONTINUE) {
2465ffad0a44SAneesh Kumar K.V 		i = mb_find_next_zero_bit(bitmap,
24667137d7a4STheodore Ts'o 						EXT4_CLUSTERS_PER_GROUP(sb), i);
24677137d7a4STheodore Ts'o 		if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
246826346ff6SAneesh Kumar K.V 			/*
2469e56eb659SAneesh Kumar K.V 			 * IF we have corrupt bitmap, we won't find any
247026346ff6SAneesh Kumar K.V 			 * free blocks even though group info says we
2471b483bb77SRandy Dunlap 			 * have free blocks
247226346ff6SAneesh Kumar K.V 			 */
2473c5f3a382SBaokun Li 			ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2474c5f3a382SBaokun Li 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2475e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
247653accfa9STheodore Ts'o 					"%d free clusters as per "
2477fde4d95aSTheodore Ts'o 					"group info. But bitmap says 0",
247826346ff6SAneesh Kumar K.V 					free);
2479c9de560dSAlex Tomas 			break;
2480c9de560dSAlex Tomas 		}
2481c9de560dSAlex Tomas 
2482304749c0SOjaswin Mujoo 		if (!ext4_mb_cr_expensive(ac->ac_criteria)) {
24831b420011SOjaswin Mujoo 			/*
2484f52f3d2bSOjaswin Mujoo 			 * In CR_GOAL_LEN_FAST and CR_BEST_AVAIL_LEN, we are
2485f52f3d2bSOjaswin Mujoo 			 * sure that this group will have a large enough
2486f52f3d2bSOjaswin Mujoo 			 * continuous free extent, so skip over the smaller free
2487f52f3d2bSOjaswin Mujoo 			 * extents
24881b420011SOjaswin Mujoo 			 */
24891b420011SOjaswin Mujoo 			j = mb_find_next_bit(bitmap,
24901b420011SOjaswin Mujoo 						EXT4_CLUSTERS_PER_GROUP(sb), i);
24911b420011SOjaswin Mujoo 			freelen = j - i;
24921b420011SOjaswin Mujoo 
24931b420011SOjaswin Mujoo 			if (freelen < ac->ac_g_ex.fe_len) {
24941b420011SOjaswin Mujoo 				i = j;
24951b420011SOjaswin Mujoo 				free -= freelen;
24961b420011SOjaswin Mujoo 				continue;
24971b420011SOjaswin Mujoo 			}
24981b420011SOjaswin Mujoo 		}
24991b420011SOjaswin Mujoo 
250015c006a2SRobin Dong 		mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
2501907ea529STheodore Ts'o 		if (WARN_ON(ex.fe_len <= 0))
2502907ea529STheodore Ts'o 			break;
250326346ff6SAneesh Kumar K.V 		if (free < ex.fe_len) {
2504c5f3a382SBaokun Li 			ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2505c5f3a382SBaokun Li 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2506e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
250753accfa9STheodore Ts'o 					"%d free clusters as per "
2508fde4d95aSTheodore Ts'o 					"group info. But got %d blocks",
250926346ff6SAneesh Kumar K.V 					free, ex.fe_len);
2510e56eb659SAneesh Kumar K.V 			/*
2511e56eb659SAneesh Kumar K.V 			 * The number of free blocks differs. This mostly
2512e56eb659SAneesh Kumar K.V 			 * indicate that the bitmap is corrupt. So exit
2513e56eb659SAneesh Kumar K.V 			 * without claiming the space.
2514e56eb659SAneesh Kumar K.V 			 */
2515e56eb659SAneesh Kumar K.V 			break;
251626346ff6SAneesh Kumar K.V 		}
2517ab0c00fcSTheodore Ts'o 		ex.fe_logical = 0xDEADC0DE; /* debug value */
2518c9de560dSAlex Tomas 		ext4_mb_measure_extent(ac, &ex, e4b);
2519c9de560dSAlex Tomas 
2520c9de560dSAlex Tomas 		i += ex.fe_len;
2521c9de560dSAlex Tomas 		free -= ex.fe_len;
2522c9de560dSAlex Tomas 	}
2523c9de560dSAlex Tomas 
2524c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 1);
2525c9de560dSAlex Tomas }
2526c9de560dSAlex Tomas 
2527c9de560dSAlex Tomas /*
2528c9de560dSAlex Tomas  * This is a special case for storages like raid5
2529506bf2d8SEric Sandeen  * we try to find stripe-aligned chunks for stripe-size-multiple requests
2530c9de560dSAlex Tomas  */
2531089ceeccSEric Sandeen static noinline_for_stack
2532089ceeccSEric Sandeen void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2533c9de560dSAlex Tomas 				 struct ext4_buddy *e4b)
2534c9de560dSAlex Tomas {
2535c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
2536c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2537c5e8f3f3STheodore Ts'o 	void *bitmap = e4b->bd_bitmap;
2538c9de560dSAlex Tomas 	struct ext4_free_extent ex;
2539c9de560dSAlex Tomas 	ext4_fsblk_t first_group_block;
2540c9de560dSAlex Tomas 	ext4_fsblk_t a;
2541c3defd99SKemeng Shi 	ext4_grpblk_t i, stripe;
2542c9de560dSAlex Tomas 	int max;
2543c9de560dSAlex Tomas 
2544c9de560dSAlex Tomas 	BUG_ON(sbi->s_stripe == 0);
2545c9de560dSAlex Tomas 
2546c9de560dSAlex Tomas 	/* find first stripe-aligned block in group */
25475661bd68SAkinobu Mita 	first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
25485661bd68SAkinobu Mita 
2549c9de560dSAlex Tomas 	a = first_group_block + sbi->s_stripe - 1;
2550c9de560dSAlex Tomas 	do_div(a, sbi->s_stripe);
2551c9de560dSAlex Tomas 	i = (a * sbi->s_stripe) - first_group_block;
2552c9de560dSAlex Tomas 
2553c3defd99SKemeng Shi 	stripe = EXT4_B2C(sbi, sbi->s_stripe);
2554c3defd99SKemeng Shi 	i = EXT4_B2C(sbi, i);
25557137d7a4STheodore Ts'o 	while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2556c9de560dSAlex Tomas 		if (!mb_test_bit(i, bitmap)) {
2557c3defd99SKemeng Shi 			max = mb_find_extent(e4b, i, stripe, &ex);
2558c3defd99SKemeng Shi 			if (max >= stripe) {
2559c9de560dSAlex Tomas 				ac->ac_found++;
2560fdd9a009SOjaswin Mujoo 				ac->ac_cX_found[ac->ac_criteria]++;
2561ab0c00fcSTheodore Ts'o 				ex.fe_logical = 0xDEADF00D; /* debug value */
2562c9de560dSAlex Tomas 				ac->ac_b_ex = ex;
2563c9de560dSAlex Tomas 				ext4_mb_use_best_found(ac, e4b);
2564c9de560dSAlex Tomas 				break;
2565c9de560dSAlex Tomas 			}
2566c9de560dSAlex Tomas 		}
2567c3defd99SKemeng Shi 		i += stripe;
2568c9de560dSAlex Tomas 	}
2569c9de560dSAlex Tomas }
2570c9de560dSAlex Tomas 
257142ac1848SLukas Czerner /*
25728ef123feSRitesh Harjani  * This is also called BEFORE we load the buddy bitmap.
257342ac1848SLukas Czerner  * Returns either 1 or 0 indicating that the group is either suitable
25748ef123feSRitesh Harjani  * for the allocation or not.
257542ac1848SLukas Czerner  */
25768ef123feSRitesh Harjani static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
25774eb7a4a1SOjaswin Mujoo 				ext4_group_t group, enum criteria cr)
2578c9de560dSAlex Tomas {
25798ef123feSRitesh Harjani 	ext4_grpblk_t free, fragments;
2580a4912123STheodore Ts'o 	int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2581c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2582c9de560dSAlex Tomas 
2583f52f3d2bSOjaswin Mujoo 	BUG_ON(cr < CR_POWER2_ALIGNED || cr >= EXT4_MB_NUM_CRS);
25848a57d9d6SCurt Wohlgemuth 
2585a9ce5993SKemeng Shi 	if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
25868ef123feSRitesh Harjani 		return false;
258701fc48e8STheodore Ts'o 
2588dddcd2f9Sbrookxu 	free = grp->bb_free;
2589dddcd2f9Sbrookxu 	if (free == 0)
25908ef123feSRitesh Harjani 		return false;
2591c9de560dSAlex Tomas 
2592c9de560dSAlex Tomas 	fragments = grp->bb_fragments;
2593c9de560dSAlex Tomas 	if (fragments == 0)
25948ef123feSRitesh Harjani 		return false;
2595c9de560dSAlex Tomas 
2596c9de560dSAlex Tomas 	switch (cr) {
2597f52f3d2bSOjaswin Mujoo 	case CR_POWER2_ALIGNED:
2598c9de560dSAlex Tomas 		BUG_ON(ac->ac_2order == 0);
2599c9de560dSAlex Tomas 
2600a4912123STheodore Ts'o 		/* Avoid using the first bg of a flexgroup for data files */
2601a4912123STheodore Ts'o 		if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2602a4912123STheodore Ts'o 		    (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2603a4912123STheodore Ts'o 		    ((group % flex_size) == 0))
26048ef123feSRitesh Harjani 			return false;
2605a4912123STheodore Ts'o 
2606dddcd2f9Sbrookxu 		if (free < ac->ac_g_ex.fe_len)
2607dddcd2f9Sbrookxu 			return false;
2608dddcd2f9Sbrookxu 
26094b68f6dfSHarshad Shirwadkar 		if (ac->ac_2order >= MB_NUM_ORDERS(ac->ac_sb))
26108ef123feSRitesh Harjani 			return true;
261140ae3487STheodore Ts'o 
261240ae3487STheodore Ts'o 		if (grp->bb_largest_free_order < ac->ac_2order)
26138ef123feSRitesh Harjani 			return false;
261440ae3487STheodore Ts'o 
26158ef123feSRitesh Harjani 		return true;
2616f52f3d2bSOjaswin Mujoo 	case CR_GOAL_LEN_FAST:
2617f52f3d2bSOjaswin Mujoo 	case CR_BEST_AVAIL_LEN:
2618c9de560dSAlex Tomas 		if ((free / fragments) >= ac->ac_g_ex.fe_len)
26198ef123feSRitesh Harjani 			return true;
2620c9de560dSAlex Tomas 		break;
2621f52f3d2bSOjaswin Mujoo 	case CR_GOAL_LEN_SLOW:
2622c9de560dSAlex Tomas 		if (free >= ac->ac_g_ex.fe_len)
26238ef123feSRitesh Harjani 			return true;
2624c9de560dSAlex Tomas 		break;
2625f52f3d2bSOjaswin Mujoo 	case CR_ANY_FREE:
26268ef123feSRitesh Harjani 		return true;
2627c9de560dSAlex Tomas 	default:
2628c9de560dSAlex Tomas 		BUG();
2629c9de560dSAlex Tomas 	}
2630c9de560dSAlex Tomas 
26318ef123feSRitesh Harjani 	return false;
26328ef123feSRitesh Harjani }
26338ef123feSRitesh Harjani 
26348ef123feSRitesh Harjani /*
26358ef123feSRitesh Harjani  * This could return negative error code if something goes wrong
26368ef123feSRitesh Harjani  * during ext4_mb_init_group(). This should not be called with
26378ef123feSRitesh Harjani  * ext4_lock_group() held.
2638a5fda113STheodore Ts'o  *
2639a5fda113STheodore Ts'o  * Note: because we are conditionally operating with the group lock in
2640a5fda113STheodore Ts'o  * the EXT4_MB_STRICT_CHECK case, we need to fake out sparse in this
2641a5fda113STheodore Ts'o  * function using __acquire and __release.  This means we need to be
2642a5fda113STheodore Ts'o  * super careful before messing with the error path handling via "goto
2643a5fda113STheodore Ts'o  * out"!
26448ef123feSRitesh Harjani  */
26458ef123feSRitesh Harjani static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
26464eb7a4a1SOjaswin Mujoo 				     ext4_group_t group, enum criteria cr)
26478ef123feSRitesh Harjani {
26488ef123feSRitesh Harjani 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
264999377830SRitesh Harjani 	struct super_block *sb = ac->ac_sb;
2650c1d2c7d4SAlex Zhuravlev 	struct ext4_sb_info *sbi = EXT4_SB(sb);
265199377830SRitesh Harjani 	bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
26528ef123feSRitesh Harjani 	ext4_grpblk_t free;
26538ef123feSRitesh Harjani 	int ret = 0;
26548ef123feSRitesh Harjani 
26555354b2afSTheodore Ts'o 	if (!grp)
26565354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
2657a6c75eafSHarshad Shirwadkar 	if (sbi->s_mb_stats)
2658a6c75eafSHarshad Shirwadkar 		atomic64_inc(&sbi->s_bal_cX_groups_considered[ac->ac_criteria]);
2659a5fda113STheodore Ts'o 	if (should_lock) {
266099377830SRitesh Harjani 		ext4_lock_group(sb, group);
2661a5fda113STheodore Ts'o 		__release(ext4_group_lock_ptr(sb, group));
2662a5fda113STheodore Ts'o 	}
26638ef123feSRitesh Harjani 	free = grp->bb_free;
26648ef123feSRitesh Harjani 	if (free == 0)
26658ef123feSRitesh Harjani 		goto out;
2666304749c0SOjaswin Mujoo 	/*
2667304749c0SOjaswin Mujoo 	 * In all criterias except CR_ANY_FREE we try to avoid groups that
2668304749c0SOjaswin Mujoo 	 * can't possibly satisfy the full goal request due to insufficient
2669304749c0SOjaswin Mujoo 	 * free blocks.
2670304749c0SOjaswin Mujoo 	 */
2671304749c0SOjaswin Mujoo 	if (cr < CR_ANY_FREE && free < ac->ac_g_ex.fe_len)
26728ef123feSRitesh Harjani 		goto out;
26738ef123feSRitesh Harjani 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
26748ef123feSRitesh Harjani 		goto out;
2675a5fda113STheodore Ts'o 	if (should_lock) {
2676a5fda113STheodore Ts'o 		__acquire(ext4_group_lock_ptr(sb, group));
267799377830SRitesh Harjani 		ext4_unlock_group(sb, group);
2678a5fda113STheodore Ts'o 	}
26798ef123feSRitesh Harjani 
26808ef123feSRitesh Harjani 	/* We only do this if the grp has never been initialized */
26818ef123feSRitesh Harjani 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2682c1d2c7d4SAlex Zhuravlev 		struct ext4_group_desc *gdp =
2683c1d2c7d4SAlex Zhuravlev 			ext4_get_group_desc(sb, group, NULL);
2684c1d2c7d4SAlex Zhuravlev 		int ret;
2685c1d2c7d4SAlex Zhuravlev 
2686f52f3d2bSOjaswin Mujoo 		/*
2687*2caffb6aSKemeng Shi 		 * CR_POWER2_ALIGNED/CR_GOAL_LEN_FAST is a very optimistic
2688f52f3d2bSOjaswin Mujoo 		 * search to find large good chunks almost for free. If buddy
2689f52f3d2bSOjaswin Mujoo 		 * data is not ready, then this optimization makes no sense. But
2690f52f3d2bSOjaswin Mujoo 		 * we never skip the first block group in a flex_bg, since this
2691f52f3d2bSOjaswin Mujoo 		 * gets used for metadata block allocation, and we want to make
2692f52f3d2bSOjaswin Mujoo 		 * sure we locate metadata blocks in the first block group in
2693f52f3d2bSOjaswin Mujoo 		 * the flex_bg if possible.
2694c1d2c7d4SAlex Zhuravlev 		 */
2695304749c0SOjaswin Mujoo 		if (!ext4_mb_cr_expensive(cr) &&
2696c1d2c7d4SAlex Zhuravlev 		    (!sbi->s_log_groups_per_flex ||
2697c1d2c7d4SAlex Zhuravlev 		     ((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
2698c1d2c7d4SAlex Zhuravlev 		    !(ext4_has_group_desc_csum(sb) &&
2699c1d2c7d4SAlex Zhuravlev 		      (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
2700c1d2c7d4SAlex Zhuravlev 			return 0;
2701c1d2c7d4SAlex Zhuravlev 		ret = ext4_mb_init_group(sb, group, GFP_NOFS);
27028ef123feSRitesh Harjani 		if (ret)
27038ef123feSRitesh Harjani 			return ret;
27048ef123feSRitesh Harjani 	}
27058ef123feSRitesh Harjani 
2706a5fda113STheodore Ts'o 	if (should_lock) {
270799377830SRitesh Harjani 		ext4_lock_group(sb, group);
2708a5fda113STheodore Ts'o 		__release(ext4_group_lock_ptr(sb, group));
2709a5fda113STheodore Ts'o 	}
27108ef123feSRitesh Harjani 	ret = ext4_mb_good_group(ac, group, cr);
27118ef123feSRitesh Harjani out:
2712a5fda113STheodore Ts'o 	if (should_lock) {
2713a5fda113STheodore Ts'o 		__acquire(ext4_group_lock_ptr(sb, group));
271499377830SRitesh Harjani 		ext4_unlock_group(sb, group);
2715a5fda113STheodore Ts'o 	}
27168ef123feSRitesh Harjani 	return ret;
2717c9de560dSAlex Tomas }
2718c9de560dSAlex Tomas 
2719cfd73237SAlex Zhuravlev /*
2720cfd73237SAlex Zhuravlev  * Start prefetching @nr block bitmaps starting at @group.
2721cfd73237SAlex Zhuravlev  * Return the next group which needs to be prefetched.
2722cfd73237SAlex Zhuravlev  */
27233d392b26STheodore Ts'o ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
2724cfd73237SAlex Zhuravlev 			      unsigned int nr, int *cnt)
2725cfd73237SAlex Zhuravlev {
2726cfd73237SAlex Zhuravlev 	ext4_group_t ngroups = ext4_get_groups_count(sb);
2727cfd73237SAlex Zhuravlev 	struct buffer_head *bh;
2728cfd73237SAlex Zhuravlev 	struct blk_plug plug;
2729cfd73237SAlex Zhuravlev 
2730cfd73237SAlex Zhuravlev 	blk_start_plug(&plug);
2731cfd73237SAlex Zhuravlev 	while (nr-- > 0) {
2732cfd73237SAlex Zhuravlev 		struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2733cfd73237SAlex Zhuravlev 								  NULL);
2734cfd73237SAlex Zhuravlev 		struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2735cfd73237SAlex Zhuravlev 
2736cfd73237SAlex Zhuravlev 		/*
2737cfd73237SAlex Zhuravlev 		 * Prefetch block groups with free blocks; but don't
2738cfd73237SAlex Zhuravlev 		 * bother if it is marked uninitialized on disk, since
2739cfd73237SAlex Zhuravlev 		 * it won't require I/O to read.  Also only try to
2740cfd73237SAlex Zhuravlev 		 * prefetch once, so we avoid getblk() call, which can
2741cfd73237SAlex Zhuravlev 		 * be expensive.
2742cfd73237SAlex Zhuravlev 		 */
27435354b2afSTheodore Ts'o 		if (gdp && grp && !EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
2744cfd73237SAlex Zhuravlev 		    EXT4_MB_GRP_NEED_INIT(grp) &&
27453c629604SOjaswin Mujoo 		    ext4_free_group_clusters(sb, gdp) > 0 ) {
2746cfd73237SAlex Zhuravlev 			bh = ext4_read_block_bitmap_nowait(sb, group, true);
2747cfd73237SAlex Zhuravlev 			if (bh && !IS_ERR(bh)) {
2748cfd73237SAlex Zhuravlev 				if (!buffer_uptodate(bh) && cnt)
2749cfd73237SAlex Zhuravlev 					(*cnt)++;
2750cfd73237SAlex Zhuravlev 				brelse(bh);
2751cfd73237SAlex Zhuravlev 			}
2752cfd73237SAlex Zhuravlev 		}
2753cfd73237SAlex Zhuravlev 		if (++group >= ngroups)
2754cfd73237SAlex Zhuravlev 			group = 0;
2755cfd73237SAlex Zhuravlev 	}
2756cfd73237SAlex Zhuravlev 	blk_finish_plug(&plug);
2757cfd73237SAlex Zhuravlev 	return group;
2758cfd73237SAlex Zhuravlev }
2759cfd73237SAlex Zhuravlev 
2760cfd73237SAlex Zhuravlev /*
2761cfd73237SAlex Zhuravlev  * Prefetching reads the block bitmap into the buffer cache; but we
2762cfd73237SAlex Zhuravlev  * need to make sure that the buddy bitmap in the page cache has been
2763cfd73237SAlex Zhuravlev  * initialized.  Note that ext4_mb_init_group() will block if the I/O
2764cfd73237SAlex Zhuravlev  * is not yet completed, or indeed if it was not initiated by
2765cfd73237SAlex Zhuravlev  * ext4_mb_prefetch did not start the I/O.
2766cfd73237SAlex Zhuravlev  *
2767cfd73237SAlex Zhuravlev  * TODO: We should actually kick off the buddy bitmap setup in a work
2768cfd73237SAlex Zhuravlev  * queue when the buffer I/O is completed, so that we don't block
2769cfd73237SAlex Zhuravlev  * waiting for the block allocation bitmap read to finish when
2770cfd73237SAlex Zhuravlev  * ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
2771cfd73237SAlex Zhuravlev  */
27723d392b26STheodore Ts'o void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
2773cfd73237SAlex Zhuravlev 			   unsigned int nr)
2774cfd73237SAlex Zhuravlev {
277522fab984SKemeng Shi 	struct ext4_group_desc *gdp;
277622fab984SKemeng Shi 	struct ext4_group_info *grp;
2777cfd73237SAlex Zhuravlev 
277822fab984SKemeng Shi 	while (nr-- > 0) {
2779cfd73237SAlex Zhuravlev 		if (!group)
2780cfd73237SAlex Zhuravlev 			group = ext4_get_groups_count(sb);
2781cfd73237SAlex Zhuravlev 		group--;
278222fab984SKemeng Shi 		gdp = ext4_get_group_desc(sb, group, NULL);
2783cfd73237SAlex Zhuravlev 		grp = ext4_get_group_info(sb, group);
2784cfd73237SAlex Zhuravlev 
27855354b2afSTheodore Ts'o 		if (grp && gdp && EXT4_MB_GRP_NEED_INIT(grp) &&
27863c629604SOjaswin Mujoo 		    ext4_free_group_clusters(sb, gdp) > 0) {
2787cfd73237SAlex Zhuravlev 			if (ext4_mb_init_group(sb, group, GFP_NOFS))
2788cfd73237SAlex Zhuravlev 				break;
2789cfd73237SAlex Zhuravlev 		}
2790cfd73237SAlex Zhuravlev 	}
2791cfd73237SAlex Zhuravlev }
2792cfd73237SAlex Zhuravlev 
27934ddfef7bSEric Sandeen static noinline_for_stack int
27944ddfef7bSEric Sandeen ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2795c9de560dSAlex Tomas {
2796cfd73237SAlex Zhuravlev 	ext4_group_t prefetch_grp = 0, ngroups, group, i;
27974c0cfebdSTheodore Ts'o 	enum criteria new_cr, cr = CR_GOAL_LEN_FAST;
279842ac1848SLukas Czerner 	int err = 0, first_err = 0;
2799cfd73237SAlex Zhuravlev 	unsigned int nr = 0, prefetch_ios = 0;
2800c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
2801c9de560dSAlex Tomas 	struct super_block *sb;
2802c9de560dSAlex Tomas 	struct ext4_buddy e4b;
280366d5e027Sbrookxu 	int lost;
2804c9de560dSAlex Tomas 
2805c9de560dSAlex Tomas 	sb = ac->ac_sb;
2806c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
28078df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
2808fb0a387dSEric Sandeen 	/* non-extent files are limited to low blocks/groups */
280912e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2810fb0a387dSEric Sandeen 		ngroups = sbi->s_blockfile_groups;
2811fb0a387dSEric Sandeen 
2812c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2813c9de560dSAlex Tomas 
2814c9de560dSAlex Tomas 	/* first, try the goal */
2815c9de560dSAlex Tomas 	err = ext4_mb_find_by_goal(ac, &e4b);
2816c9de560dSAlex Tomas 	if (err || ac->ac_status == AC_STATUS_FOUND)
2817c9de560dSAlex Tomas 		goto out;
2818c9de560dSAlex Tomas 
2819c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2820c9de560dSAlex Tomas 		goto out;
2821c9de560dSAlex Tomas 
2822c9de560dSAlex Tomas 	/*
2823e9a3cd48Sbrookxu 	 * ac->ac_2order is set only if the fe_len is a power of 2
28244eea9fbeSKemeng Shi 	 * if ac->ac_2order is set we also set criteria to CR_POWER2_ALIGNED
28254eea9fbeSKemeng Shi 	 * so that we try exact allocation using buddy.
2826c9de560dSAlex Tomas 	 */
2827c9de560dSAlex Tomas 	i = fls(ac->ac_g_ex.fe_len);
2828c9de560dSAlex Tomas 	ac->ac_2order = 0;
2829c9de560dSAlex Tomas 	/*
2830c9de560dSAlex Tomas 	 * We search using buddy data only if the order of the request
2831c9de560dSAlex Tomas 	 * is greater than equal to the sbi_s_mb_order2_reqs
2832b713a5ecSTheodore Ts'o 	 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2833d9b22cf9SJan Kara 	 * We also support searching for power-of-two requests only for
2834d9b22cf9SJan Kara 	 * requests upto maximum buddy size we have constructed.
2835c9de560dSAlex Tomas 	 */
28364b68f6dfSHarshad Shirwadkar 	if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) {
2837bb60caa2SKemeng Shi 		if (is_power_of_2(ac->ac_g_ex.fe_len))
28381a5d5e5dSJeremy Cline 			ac->ac_2order = array_index_nospec(i - 1,
28394b68f6dfSHarshad Shirwadkar 							   MB_NUM_ORDERS(sb));
2840c9de560dSAlex Tomas 	}
2841c9de560dSAlex Tomas 
28424ba74d00STheodore Ts'o 	/* if stream allocation is enabled, use global goal */
28434ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2844c9de560dSAlex Tomas 		/* TBD: may be hot point */
2845c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
2846c9de560dSAlex Tomas 		ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2847c9de560dSAlex Tomas 		ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2848c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
2849c9de560dSAlex Tomas 	}
28504ba74d00STheodore Ts'o 
2851c9de560dSAlex Tomas 	/*
28524c0cfebdSTheodore Ts'o 	 * Let's just scan groups to find more-less suitable blocks We
28534c0cfebdSTheodore Ts'o 	 * start with CR_GOAL_LEN_FAST, unless it is power of 2
28544c0cfebdSTheodore Ts'o 	 * aligned, in which case let's do that faster approach first.
2855c9de560dSAlex Tomas 	 */
28564c0cfebdSTheodore Ts'o 	if (ac->ac_2order)
28574c0cfebdSTheodore Ts'o 		cr = CR_POWER2_ALIGNED;
2858c9de560dSAlex Tomas repeat:
28594eb7a4a1SOjaswin Mujoo 	for (; cr < EXT4_MB_NUM_CRS && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2860c9de560dSAlex Tomas 		ac->ac_criteria = cr;
2861ed8f9c75SAneesh Kumar K.V 		/*
2862ed8f9c75SAneesh Kumar K.V 		 * searching for the right group start
2863ed8f9c75SAneesh Kumar K.V 		 * from the goal value specified
2864ed8f9c75SAneesh Kumar K.V 		 */
2865ed8f9c75SAneesh Kumar K.V 		group = ac->ac_g_ex.fe_group;
2866196e402aSHarshad Shirwadkar 		ac->ac_groups_linear_remaining = sbi->s_mb_max_linear_groups;
2867cfd73237SAlex Zhuravlev 		prefetch_grp = group;
28689c97c34aSKemeng Shi 		nr = 0;
2869ed8f9c75SAneesh Kumar K.V 
28704fca50d4SJan Kara 		for (i = 0, new_cr = cr; i < ngroups; i++,
28714fca50d4SJan Kara 		     ext4_mb_choose_next_group(ac, &new_cr, &group, ngroups)) {
28724fca50d4SJan Kara 			int ret = 0;
2873196e402aSHarshad Shirwadkar 
28742ed5724dSTheodore Ts'o 			cond_resched();
2875196e402aSHarshad Shirwadkar 			if (new_cr != cr) {
2876196e402aSHarshad Shirwadkar 				cr = new_cr;
2877196e402aSHarshad Shirwadkar 				goto repeat;
2878196e402aSHarshad Shirwadkar 			}
2879c9de560dSAlex Tomas 
2880cfd73237SAlex Zhuravlev 			/*
2881cfd73237SAlex Zhuravlev 			 * Batch reads of the block allocation bitmaps
2882cfd73237SAlex Zhuravlev 			 * to get multiple READs in flight; limit
28834eea9fbeSKemeng Shi 			 * prefetching at inexpensive CR, otherwise mballoc
28844eea9fbeSKemeng Shi 			 * can spend a lot of time loading imperfect groups
2885cfd73237SAlex Zhuravlev 			 */
2886cfd73237SAlex Zhuravlev 			if ((prefetch_grp == group) &&
2887304749c0SOjaswin Mujoo 			    (ext4_mb_cr_expensive(cr) ||
2888cfd73237SAlex Zhuravlev 			     prefetch_ios < sbi->s_mb_prefetch_limit)) {
2889cfd73237SAlex Zhuravlev 				nr = sbi->s_mb_prefetch;
2890cfd73237SAlex Zhuravlev 				if (ext4_has_feature_flex_bg(sb)) {
289182ef1370SChunguang Xu 					nr = 1 << sbi->s_log_groups_per_flex;
289282ef1370SChunguang Xu 					nr -= group & (nr - 1);
289382ef1370SChunguang Xu 					nr = min(nr, sbi->s_mb_prefetch);
2894cfd73237SAlex Zhuravlev 				}
2895cfd73237SAlex Zhuravlev 				prefetch_grp = ext4_mb_prefetch(sb, group,
2896cfd73237SAlex Zhuravlev 							nr, &prefetch_ios);
2897cfd73237SAlex Zhuravlev 			}
2898cfd73237SAlex Zhuravlev 
28998a57d9d6SCurt Wohlgemuth 			/* This now checks without needing the buddy page */
29008ef123feSRitesh Harjani 			ret = ext4_mb_good_group_nolock(ac, group, cr);
290142ac1848SLukas Czerner 			if (ret <= 0) {
290242ac1848SLukas Czerner 				if (!first_err)
290342ac1848SLukas Czerner 					first_err = ret;
2904c9de560dSAlex Tomas 				continue;
290542ac1848SLukas Czerner 			}
2906c9de560dSAlex Tomas 
2907c9de560dSAlex Tomas 			err = ext4_mb_load_buddy(sb, group, &e4b);
2908c9de560dSAlex Tomas 			if (err)
2909c9de560dSAlex Tomas 				goto out;
2910c9de560dSAlex Tomas 
2911c9de560dSAlex Tomas 			ext4_lock_group(sb, group);
29128a57d9d6SCurt Wohlgemuth 
29138a57d9d6SCurt Wohlgemuth 			/*
29148a57d9d6SCurt Wohlgemuth 			 * We need to check again after locking the
29158a57d9d6SCurt Wohlgemuth 			 * block group
29168a57d9d6SCurt Wohlgemuth 			 */
291742ac1848SLukas Czerner 			ret = ext4_mb_good_group(ac, group, cr);
29188ef123feSRitesh Harjani 			if (ret == 0) {
2919c9de560dSAlex Tomas 				ext4_unlock_group(sb, group);
2920e39e07fdSJing Zhang 				ext4_mb_unload_buddy(&e4b);
2921c9de560dSAlex Tomas 				continue;
2922c9de560dSAlex Tomas 			}
2923c9de560dSAlex Tomas 
2924c9de560dSAlex Tomas 			ac->ac_groups_scanned++;
2925f52f3d2bSOjaswin Mujoo 			if (cr == CR_POWER2_ALIGNED)
2926c9de560dSAlex Tomas 				ext4_mb_simple_scan_group(ac, &e4b);
29271f6bc02fSOjaswin Mujoo 			else {
29281f6bc02fSOjaswin Mujoo 				bool is_stripe_aligned = sbi->s_stripe &&
2929c3defd99SKemeng Shi 					!(ac->ac_g_ex.fe_len %
29301f6bc02fSOjaswin Mujoo 					  EXT4_B2C(sbi, sbi->s_stripe));
29311f6bc02fSOjaswin Mujoo 
29321f6bc02fSOjaswin Mujoo 				if ((cr == CR_GOAL_LEN_FAST ||
29331f6bc02fSOjaswin Mujoo 				     cr == CR_BEST_AVAIL_LEN) &&
29341f6bc02fSOjaswin Mujoo 				    is_stripe_aligned)
2935c9de560dSAlex Tomas 					ext4_mb_scan_aligned(ac, &e4b);
29361f6bc02fSOjaswin Mujoo 
29371f6bc02fSOjaswin Mujoo 				if (ac->ac_status == AC_STATUS_CONTINUE)
2938c9de560dSAlex Tomas 					ext4_mb_complex_scan_group(ac, &e4b);
29391f6bc02fSOjaswin Mujoo 			}
2940c9de560dSAlex Tomas 
2941c9de560dSAlex Tomas 			ext4_unlock_group(sb, group);
2942e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
2943c9de560dSAlex Tomas 
2944c9de560dSAlex Tomas 			if (ac->ac_status != AC_STATUS_CONTINUE)
2945c9de560dSAlex Tomas 				break;
2946c9de560dSAlex Tomas 		}
2947a6c75eafSHarshad Shirwadkar 		/* Processed all groups and haven't found blocks */
2948a6c75eafSHarshad Shirwadkar 		if (sbi->s_mb_stats && i == ngroups)
2949a6c75eafSHarshad Shirwadkar 			atomic64_inc(&sbi->s_bal_cX_failed[cr]);
29507e170922SOjaswin Mujoo 
2951f52f3d2bSOjaswin Mujoo 		if (i == ngroups && ac->ac_criteria == CR_BEST_AVAIL_LEN)
29527e170922SOjaswin Mujoo 			/* Reset goal length to original goal length before
2953f52f3d2bSOjaswin Mujoo 			 * falling into CR_GOAL_LEN_SLOW */
29547e170922SOjaswin Mujoo 			ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
2955c9de560dSAlex Tomas 	}
2956c9de560dSAlex Tomas 
2957c9de560dSAlex Tomas 	if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2958c9de560dSAlex Tomas 	    !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2959c9de560dSAlex Tomas 		/*
2960c9de560dSAlex Tomas 		 * We've been searching too long. Let's try to allocate
2961c9de560dSAlex Tomas 		 * the best chunk we've found so far
2962c9de560dSAlex Tomas 		 */
2963c9de560dSAlex Tomas 		ext4_mb_try_best_found(ac, &e4b);
2964c9de560dSAlex Tomas 		if (ac->ac_status != AC_STATUS_FOUND) {
2965c9de560dSAlex Tomas 			/*
2966c9de560dSAlex Tomas 			 * Someone more lucky has already allocated it.
2967c9de560dSAlex Tomas 			 * The only thing we can do is just take first
2968c9de560dSAlex Tomas 			 * found block(s)
2969c9de560dSAlex Tomas 			 */
297066d5e027Sbrookxu 			lost = atomic_inc_return(&sbi->s_mb_lost_chunks);
297166d5e027Sbrookxu 			mb_debug(sb, "lost chunk, group: %u, start: %d, len: %d, lost: %d\n",
2972c55ee7d2Sbrookxu 				 ac->ac_b_ex.fe_group, ac->ac_b_ex.fe_start,
2973c55ee7d2Sbrookxu 				 ac->ac_b_ex.fe_len, lost);
2974c55ee7d2Sbrookxu 
2975c9de560dSAlex Tomas 			ac->ac_b_ex.fe_group = 0;
2976c9de560dSAlex Tomas 			ac->ac_b_ex.fe_start = 0;
2977c9de560dSAlex Tomas 			ac->ac_b_ex.fe_len = 0;
2978c9de560dSAlex Tomas 			ac->ac_status = AC_STATUS_CONTINUE;
2979c9de560dSAlex Tomas 			ac->ac_flags |= EXT4_MB_HINT_FIRST;
2980f52f3d2bSOjaswin Mujoo 			cr = CR_ANY_FREE;
2981c9de560dSAlex Tomas 			goto repeat;
2982c9de560dSAlex Tomas 		}
2983c9de560dSAlex Tomas 	}
2984a6c75eafSHarshad Shirwadkar 
2985a6c75eafSHarshad Shirwadkar 	if (sbi->s_mb_stats && ac->ac_status == AC_STATUS_FOUND)
2986a6c75eafSHarshad Shirwadkar 		atomic64_inc(&sbi->s_bal_cX_hits[ac->ac_criteria]);
2987c9de560dSAlex Tomas out:
298842ac1848SLukas Czerner 	if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
298942ac1848SLukas Czerner 		err = first_err;
2990bbc4ec77SRitesh Harjani 
2991d3df1453SRitesh Harjani 	mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
2992bbc4ec77SRitesh Harjani 		 ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
2993bbc4ec77SRitesh Harjani 		 ac->ac_flags, cr, err);
2994cfd73237SAlex Zhuravlev 
2995cfd73237SAlex Zhuravlev 	if (nr)
2996cfd73237SAlex Zhuravlev 		ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
2997cfd73237SAlex Zhuravlev 
2998c9de560dSAlex Tomas 	return err;
2999c9de560dSAlex Tomas }
3000c9de560dSAlex Tomas 
3001c9de560dSAlex Tomas static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
3002c9de560dSAlex Tomas {
3003359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3004c9de560dSAlex Tomas 	ext4_group_t group;
3005c9de560dSAlex Tomas 
30068df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
3007c9de560dSAlex Tomas 		return NULL;
3008c9de560dSAlex Tomas 	group = *pos + 1;
3009a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
3010c9de560dSAlex Tomas }
3011c9de560dSAlex Tomas 
3012c9de560dSAlex Tomas static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
3013c9de560dSAlex Tomas {
3014359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3015c9de560dSAlex Tomas 	ext4_group_t group;
3016c9de560dSAlex Tomas 
3017c9de560dSAlex Tomas 	++*pos;
30188df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
3019c9de560dSAlex Tomas 		return NULL;
3020c9de560dSAlex Tomas 	group = *pos + 1;
3021a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
3022c9de560dSAlex Tomas }
3023c9de560dSAlex Tomas 
3024c9de560dSAlex Tomas static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
3025c9de560dSAlex Tomas {
3026359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3027a9df9a49STheodore Ts'o 	ext4_group_t group = (ext4_group_t) ((unsigned long) v);
302825044880Syangerkun 	int i, err;
30294b55d343Syangerkun 	char nbuf[16];
3030c9de560dSAlex Tomas 	struct ext4_buddy e4b;
30311c8457caSAditya Kali 	struct ext4_group_info *grinfo;
30322df2c340SArnd Bergmann 	unsigned char blocksize_bits = min_t(unsigned char,
30332df2c340SArnd Bergmann 					     sb->s_blocksize_bits,
30342df2c340SArnd Bergmann 					     EXT4_MAX_BLOCK_LOG_SIZE);
3035c9de560dSAlex Tomas 	struct sg {
3036c9de560dSAlex Tomas 		struct ext4_group_info info;
3037b80b32b6STheodore Ts'o 		ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
3038c9de560dSAlex Tomas 	} sg;
3039c9de560dSAlex Tomas 
3040c9de560dSAlex Tomas 	group--;
3041c9de560dSAlex Tomas 	if (group == 0)
304297b4af2fSRasmus Villemoes 		seq_puts(seq, "#group: free  frags first ["
304397b4af2fSRasmus Villemoes 			      " 2^0   2^1   2^2   2^3   2^4   2^5   2^6  "
3044802cf1f9SHuaitong Han 			      " 2^7   2^8   2^9   2^10  2^11  2^12  2^13  ]\n");
3045c9de560dSAlex Tomas 
3046b80b32b6STheodore Ts'o 	i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
3047b80b32b6STheodore Ts'o 		sizeof(struct ext4_group_info);
3048b80b32b6STheodore Ts'o 
30491c8457caSAditya Kali 	grinfo = ext4_get_group_info(sb, group);
30505354b2afSTheodore Ts'o 	if (!grinfo)
30515354b2afSTheodore Ts'o 		return 0;
30521c8457caSAditya Kali 	/* Load the group info in memory only if not already loaded. */
30531c8457caSAditya Kali 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
3054c9de560dSAlex Tomas 		err = ext4_mb_load_buddy(sb, group, &e4b);
3055c9de560dSAlex Tomas 		if (err) {
30564b55d343Syangerkun 			seq_printf(seq, "#%-5u: %s\n", group, ext4_decode_error(NULL, err, nbuf));
3057c9de560dSAlex Tomas 			return 0;
3058c9de560dSAlex Tomas 		}
305925044880Syangerkun 		ext4_mb_unload_buddy(&e4b);
30601c8457caSAditya Kali 	}
30611c8457caSAditya Kali 
306225044880Syangerkun 	/*
306325044880Syangerkun 	 * We care only about free space counters in the group info and
306425044880Syangerkun 	 * these are safe to access even after the buddy has been unloaded
306525044880Syangerkun 	 */
30665354b2afSTheodore Ts'o 	memcpy(&sg, grinfo, i);
3067a9df9a49STheodore Ts'o 	seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
3068c9de560dSAlex Tomas 			sg.info.bb_fragments, sg.info.bb_first_free);
3069c9de560dSAlex Tomas 	for (i = 0; i <= 13; i++)
30702df2c340SArnd Bergmann 		seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
3071c9de560dSAlex Tomas 				sg.info.bb_counters[i] : 0);
307268ee261fSZhang Yi 	seq_puts(seq, " ]");
307368ee261fSZhang Yi 	if (EXT4_MB_GRP_BBITMAP_CORRUPT(&sg.info))
307468ee261fSZhang Yi 		seq_puts(seq, " Block bitmap corrupted!");
307568ee261fSZhang Yi 	seq_puts(seq, "\n");
3076c9de560dSAlex Tomas 
3077c9de560dSAlex Tomas 	return 0;
3078c9de560dSAlex Tomas }
3079c9de560dSAlex Tomas 
3080c9de560dSAlex Tomas static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
3081c9de560dSAlex Tomas {
3082c9de560dSAlex Tomas }
3083c9de560dSAlex Tomas 
3084247dbed8SChristoph Hellwig const struct seq_operations ext4_mb_seq_groups_ops = {
3085c9de560dSAlex Tomas 	.start  = ext4_mb_seq_groups_start,
3086c9de560dSAlex Tomas 	.next   = ext4_mb_seq_groups_next,
3087c9de560dSAlex Tomas 	.stop   = ext4_mb_seq_groups_stop,
3088c9de560dSAlex Tomas 	.show   = ext4_mb_seq_groups_show,
3089c9de560dSAlex Tomas };
3090c9de560dSAlex Tomas 
3091a6c75eafSHarshad Shirwadkar int ext4_seq_mb_stats_show(struct seq_file *seq, void *offset)
3092a6c75eafSHarshad Shirwadkar {
3093c30365b9SYu Zhe 	struct super_block *sb = seq->private;
3094a6c75eafSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3095a6c75eafSHarshad Shirwadkar 
3096a6c75eafSHarshad Shirwadkar 	seq_puts(seq, "mballoc:\n");
3097a6c75eafSHarshad Shirwadkar 	if (!sbi->s_mb_stats) {
3098a6c75eafSHarshad Shirwadkar 		seq_puts(seq, "\tmb stats collection turned off.\n");
3099f52f3d2bSOjaswin Mujoo 		seq_puts(
3100f52f3d2bSOjaswin Mujoo 			seq,
3101f52f3d2bSOjaswin Mujoo 			"\tTo enable, please write \"1\" to sysfs file mb_stats.\n");
3102a6c75eafSHarshad Shirwadkar 		return 0;
3103a6c75eafSHarshad Shirwadkar 	}
3104a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\treqs: %u\n", atomic_read(&sbi->s_bal_reqs));
3105a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tsuccess: %u\n", atomic_read(&sbi->s_bal_success));
3106a6c75eafSHarshad Shirwadkar 
3107f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\tgroups_scanned: %u\n",
3108f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_groups_scanned));
3109a6c75eafSHarshad Shirwadkar 
3110f52f3d2bSOjaswin Mujoo 	/* CR_POWER2_ALIGNED stats */
3111f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_p2_aligned_stats:\n");
3112f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3113f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_POWER2_ALIGNED]));
3114f52f3d2bSOjaswin Mujoo 	seq_printf(
3115f52f3d2bSOjaswin Mujoo 		seq, "\t\tgroups_considered: %llu\n",
3116f52f3d2bSOjaswin Mujoo 		atomic64_read(
3117f52f3d2bSOjaswin Mujoo 			&sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]));
3118f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3119f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_POWER2_ALIGNED]));
3120a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3121f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_POWER2_ALIGNED]));
3122196e402aSHarshad Shirwadkar 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3123f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_p2_aligned_bad_suggestions));
3124a6c75eafSHarshad Shirwadkar 
3125f52f3d2bSOjaswin Mujoo 	/* CR_GOAL_LEN_FAST stats */
3126f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_goal_fast_stats:\n");
3127f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3128f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_FAST]));
3129a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tgroups_considered: %llu\n",
3130f52f3d2bSOjaswin Mujoo 		   atomic64_read(
3131f52f3d2bSOjaswin Mujoo 			   &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_FAST]));
3132f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3133f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_FAST]));
3134a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3135f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_FAST]));
3136196e402aSHarshad Shirwadkar 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3137f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_goal_fast_bad_suggestions));
3138a6c75eafSHarshad Shirwadkar 
3139f52f3d2bSOjaswin Mujoo 	/* CR_BEST_AVAIL_LEN stats */
3140f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_best_avail_stats:\n");
3141f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3142f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_BEST_AVAIL_LEN]));
3143f52f3d2bSOjaswin Mujoo 	seq_printf(
3144f52f3d2bSOjaswin Mujoo 		seq, "\t\tgroups_considered: %llu\n",
3145f52f3d2bSOjaswin Mujoo 		atomic64_read(
3146f52f3d2bSOjaswin Mujoo 			&sbi->s_bal_cX_groups_considered[CR_BEST_AVAIL_LEN]));
3147f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3148f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_BEST_AVAIL_LEN]));
31497e170922SOjaswin Mujoo 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3150f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_BEST_AVAIL_LEN]));
31517e170922SOjaswin Mujoo 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3152f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_best_avail_bad_suggestions));
31537e170922SOjaswin Mujoo 
3154f52f3d2bSOjaswin Mujoo 	/* CR_GOAL_LEN_SLOW stats */
3155f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_goal_slow_stats:\n");
3156f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3157f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_SLOW]));
3158a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tgroups_considered: %llu\n",
3159f52f3d2bSOjaswin Mujoo 		   atomic64_read(
3160f52f3d2bSOjaswin Mujoo 			   &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_SLOW]));
3161f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3162f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_SLOW]));
3163a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3164f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_SLOW]));
3165a6c75eafSHarshad Shirwadkar 
3166f52f3d2bSOjaswin Mujoo 	/* CR_ANY_FREE stats */
3167f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_any_free_stats:\n");
3168f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3169f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_ANY_FREE]));
3170f52f3d2bSOjaswin Mujoo 	seq_printf(
3171f52f3d2bSOjaswin Mujoo 		seq, "\t\tgroups_considered: %llu\n",
3172f52f3d2bSOjaswin Mujoo 		atomic64_read(&sbi->s_bal_cX_groups_considered[CR_ANY_FREE]));
3173f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3174f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_ANY_FREE]));
3175a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3176f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_ANY_FREE]));
3177f52f3d2bSOjaswin Mujoo 
3178f52f3d2bSOjaswin Mujoo 	/* Aggregates */
3179f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\textents_scanned: %u\n",
3180f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_ex_scanned));
3181a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tgoal_hits: %u\n", atomic_read(&sbi->s_bal_goals));
3182f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\tlen_goal_hits: %u\n",
3183f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_len_goals));
3184a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\t2^n_hits: %u\n", atomic_read(&sbi->s_bal_2orders));
3185a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tbreaks: %u\n", atomic_read(&sbi->s_bal_breaks));
3186a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tlost: %u\n", atomic_read(&sbi->s_mb_lost_chunks));
3187a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tbuddies_generated: %u/%u\n",
3188a6c75eafSHarshad Shirwadkar 		   atomic_read(&sbi->s_mb_buddies_generated),
3189a6c75eafSHarshad Shirwadkar 		   ext4_get_groups_count(sb));
3190a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tbuddies_time_used: %llu\n",
3191a6c75eafSHarshad Shirwadkar 		   atomic64_read(&sbi->s_mb_generation_time));
3192a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tpreallocated: %u\n",
3193a6c75eafSHarshad Shirwadkar 		   atomic_read(&sbi->s_mb_preallocated));
3194f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\tdiscarded: %u\n", atomic_read(&sbi->s_mb_discarded));
3195a6c75eafSHarshad Shirwadkar 	return 0;
3196a6c75eafSHarshad Shirwadkar }
3197a6c75eafSHarshad Shirwadkar 
3198f68f4063SHarshad Shirwadkar static void *ext4_mb_seq_structs_summary_start(struct seq_file *seq, loff_t *pos)
3199f68f4063SHarshad Shirwadkar {
3200359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3201f68f4063SHarshad Shirwadkar 	unsigned long position;
3202f68f4063SHarshad Shirwadkar 
320383e80a6eSJan Kara 	if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3204f68f4063SHarshad Shirwadkar 		return NULL;
3205f68f4063SHarshad Shirwadkar 	position = *pos + 1;
3206f68f4063SHarshad Shirwadkar 	return (void *) ((unsigned long) position);
3207f68f4063SHarshad Shirwadkar }
3208f68f4063SHarshad Shirwadkar 
3209f68f4063SHarshad Shirwadkar static void *ext4_mb_seq_structs_summary_next(struct seq_file *seq, void *v, loff_t *pos)
3210f68f4063SHarshad Shirwadkar {
3211359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3212f68f4063SHarshad Shirwadkar 	unsigned long position;
3213f68f4063SHarshad Shirwadkar 
3214f68f4063SHarshad Shirwadkar 	++*pos;
321583e80a6eSJan Kara 	if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3216f68f4063SHarshad Shirwadkar 		return NULL;
3217f68f4063SHarshad Shirwadkar 	position = *pos + 1;
3218f68f4063SHarshad Shirwadkar 	return (void *) ((unsigned long) position);
3219f68f4063SHarshad Shirwadkar }
3220f68f4063SHarshad Shirwadkar 
3221f68f4063SHarshad Shirwadkar static int ext4_mb_seq_structs_summary_show(struct seq_file *seq, void *v)
3222f68f4063SHarshad Shirwadkar {
3223359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3224f68f4063SHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3225f68f4063SHarshad Shirwadkar 	unsigned long position = ((unsigned long) v);
3226f68f4063SHarshad Shirwadkar 	struct ext4_group_info *grp;
322783e80a6eSJan Kara 	unsigned int count;
3228f68f4063SHarshad Shirwadkar 
3229f68f4063SHarshad Shirwadkar 	position--;
3230f68f4063SHarshad Shirwadkar 	if (position >= MB_NUM_ORDERS(sb)) {
323183e80a6eSJan Kara 		position -= MB_NUM_ORDERS(sb);
323283e80a6eSJan Kara 		if (position == 0)
323383e80a6eSJan Kara 			seq_puts(seq, "avg_fragment_size_lists:\n");
3234f68f4063SHarshad Shirwadkar 
323583e80a6eSJan Kara 		count = 0;
323683e80a6eSJan Kara 		read_lock(&sbi->s_mb_avg_fragment_size_locks[position]);
323783e80a6eSJan Kara 		list_for_each_entry(grp, &sbi->s_mb_avg_fragment_size[position],
323883e80a6eSJan Kara 				    bb_avg_fragment_size_node)
323983e80a6eSJan Kara 			count++;
324083e80a6eSJan Kara 		read_unlock(&sbi->s_mb_avg_fragment_size_locks[position]);
324183e80a6eSJan Kara 		seq_printf(seq, "\tlist_order_%u_groups: %u\n",
324283e80a6eSJan Kara 					(unsigned int)position, count);
3243f68f4063SHarshad Shirwadkar 		return 0;
3244f68f4063SHarshad Shirwadkar 	}
3245f68f4063SHarshad Shirwadkar 
3246f68f4063SHarshad Shirwadkar 	if (position == 0) {
3247f68f4063SHarshad Shirwadkar 		seq_printf(seq, "optimize_scan: %d\n",
3248f68f4063SHarshad Shirwadkar 			   test_opt2(sb, MB_OPTIMIZE_SCAN) ? 1 : 0);
3249f68f4063SHarshad Shirwadkar 		seq_puts(seq, "max_free_order_lists:\n");
3250f68f4063SHarshad Shirwadkar 	}
3251f68f4063SHarshad Shirwadkar 	count = 0;
325283e80a6eSJan Kara 	read_lock(&sbi->s_mb_largest_free_orders_locks[position]);
3253f68f4063SHarshad Shirwadkar 	list_for_each_entry(grp, &sbi->s_mb_largest_free_orders[position],
3254f68f4063SHarshad Shirwadkar 			    bb_largest_free_order_node)
3255f68f4063SHarshad Shirwadkar 		count++;
325683e80a6eSJan Kara 	read_unlock(&sbi->s_mb_largest_free_orders_locks[position]);
3257f68f4063SHarshad Shirwadkar 	seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3258f68f4063SHarshad Shirwadkar 		   (unsigned int)position, count);
3259f68f4063SHarshad Shirwadkar 
3260f68f4063SHarshad Shirwadkar 	return 0;
3261f68f4063SHarshad Shirwadkar }
3262f68f4063SHarshad Shirwadkar 
3263f68f4063SHarshad Shirwadkar static void ext4_mb_seq_structs_summary_stop(struct seq_file *seq, void *v)
3264f68f4063SHarshad Shirwadkar {
3265f68f4063SHarshad Shirwadkar }
3266f68f4063SHarshad Shirwadkar 
3267f68f4063SHarshad Shirwadkar const struct seq_operations ext4_mb_seq_structs_summary_ops = {
3268f68f4063SHarshad Shirwadkar 	.start  = ext4_mb_seq_structs_summary_start,
3269f68f4063SHarshad Shirwadkar 	.next   = ext4_mb_seq_structs_summary_next,
3270f68f4063SHarshad Shirwadkar 	.stop   = ext4_mb_seq_structs_summary_stop,
3271f68f4063SHarshad Shirwadkar 	.show   = ext4_mb_seq_structs_summary_show,
3272f68f4063SHarshad Shirwadkar };
3273f68f4063SHarshad Shirwadkar 
3274fb1813f4SCurt Wohlgemuth static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
3275fb1813f4SCurt Wohlgemuth {
3276fb1813f4SCurt Wohlgemuth 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3277fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
3278fb1813f4SCurt Wohlgemuth 
3279fb1813f4SCurt Wohlgemuth 	BUG_ON(!cachep);
3280fb1813f4SCurt Wohlgemuth 	return cachep;
3281fb1813f4SCurt Wohlgemuth }
32825f21b0e6SFrederic Bohe 
328328623c2fSTheodore Ts'o /*
328428623c2fSTheodore Ts'o  * Allocate the top-level s_group_info array for the specified number
328528623c2fSTheodore Ts'o  * of groups
328628623c2fSTheodore Ts'o  */
328728623c2fSTheodore Ts'o int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
328828623c2fSTheodore Ts'o {
328928623c2fSTheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(sb);
329028623c2fSTheodore Ts'o 	unsigned size;
3291df3da4eaSSuraj Jitindar Singh 	struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
329228623c2fSTheodore Ts'o 
329328623c2fSTheodore Ts'o 	size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
329428623c2fSTheodore Ts'o 		EXT4_DESC_PER_BLOCK_BITS(sb);
329528623c2fSTheodore Ts'o 	if (size <= sbi->s_group_info_size)
329628623c2fSTheodore Ts'o 		return 0;
329728623c2fSTheodore Ts'o 
329828623c2fSTheodore Ts'o 	size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
3299a7c3e901SMichal Hocko 	new_groupinfo = kvzalloc(size, GFP_KERNEL);
330028623c2fSTheodore Ts'o 	if (!new_groupinfo) {
330128623c2fSTheodore Ts'o 		ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
330228623c2fSTheodore Ts'o 		return -ENOMEM;
330328623c2fSTheodore Ts'o 	}
3304df3da4eaSSuraj Jitindar Singh 	rcu_read_lock();
3305df3da4eaSSuraj Jitindar Singh 	old_groupinfo = rcu_dereference(sbi->s_group_info);
3306df3da4eaSSuraj Jitindar Singh 	if (old_groupinfo)
3307df3da4eaSSuraj Jitindar Singh 		memcpy(new_groupinfo, old_groupinfo,
330828623c2fSTheodore Ts'o 		       sbi->s_group_info_size * sizeof(*sbi->s_group_info));
3309df3da4eaSSuraj Jitindar Singh 	rcu_read_unlock();
3310df3da4eaSSuraj Jitindar Singh 	rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
331128623c2fSTheodore Ts'o 	sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
3312df3da4eaSSuraj Jitindar Singh 	if (old_groupinfo)
3313df3da4eaSSuraj Jitindar Singh 		ext4_kvfree_array_rcu(old_groupinfo);
331428623c2fSTheodore Ts'o 	ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
331528623c2fSTheodore Ts'o 		   sbi->s_group_info_size);
331628623c2fSTheodore Ts'o 	return 0;
331728623c2fSTheodore Ts'o }
331828623c2fSTheodore Ts'o 
33195f21b0e6SFrederic Bohe /* Create and initialize ext4_group_info data for the given group. */
3320920313a7SAneesh Kumar K.V int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
33215f21b0e6SFrederic Bohe 			  struct ext4_group_desc *desc)
33225f21b0e6SFrederic Bohe {
3323fb1813f4SCurt Wohlgemuth 	int i;
33245f21b0e6SFrederic Bohe 	int metalen = 0;
3325df3da4eaSSuraj Jitindar Singh 	int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
33265f21b0e6SFrederic Bohe 	struct ext4_sb_info *sbi = EXT4_SB(sb);
33275f21b0e6SFrederic Bohe 	struct ext4_group_info **meta_group_info;
3328fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
33295f21b0e6SFrederic Bohe 
33305f21b0e6SFrederic Bohe 	/*
33315f21b0e6SFrederic Bohe 	 * First check if this group is the first of a reserved block.
33325f21b0e6SFrederic Bohe 	 * If it's true, we have to allocate a new table of pointers
33335f21b0e6SFrederic Bohe 	 * to ext4_group_info structures
33345f21b0e6SFrederic Bohe 	 */
33355f21b0e6SFrederic Bohe 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
33365f21b0e6SFrederic Bohe 		metalen = sizeof(*meta_group_info) <<
33375f21b0e6SFrederic Bohe 			EXT4_DESC_PER_BLOCK_BITS(sb);
33384fdb5543SDmitry Monakhov 		meta_group_info = kmalloc(metalen, GFP_NOFS);
33395f21b0e6SFrederic Bohe 		if (meta_group_info == NULL) {
33407f6a11e7SJoe Perches 			ext4_msg(sb, KERN_ERR, "can't allocate mem "
33419d8b9ec4STheodore Ts'o 				 "for a buddy group");
3342df119095SKemeng Shi 			return -ENOMEM;
33435f21b0e6SFrederic Bohe 		}
3344df3da4eaSSuraj Jitindar Singh 		rcu_read_lock();
3345df3da4eaSSuraj Jitindar Singh 		rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
3346df3da4eaSSuraj Jitindar Singh 		rcu_read_unlock();
33475f21b0e6SFrederic Bohe 	}
33485f21b0e6SFrederic Bohe 
3349df3da4eaSSuraj Jitindar Singh 	meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
33505f21b0e6SFrederic Bohe 	i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
33515f21b0e6SFrederic Bohe 
33524fdb5543SDmitry Monakhov 	meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
33535f21b0e6SFrederic Bohe 	if (meta_group_info[i] == NULL) {
33547f6a11e7SJoe Perches 		ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
33555f21b0e6SFrederic Bohe 		goto exit_group_info;
33565f21b0e6SFrederic Bohe 	}
33575f21b0e6SFrederic Bohe 	set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
33585f21b0e6SFrederic Bohe 		&(meta_group_info[i]->bb_state));
33595f21b0e6SFrederic Bohe 
33605f21b0e6SFrederic Bohe 	/*
33615f21b0e6SFrederic Bohe 	 * initialize bb_free to be able to skip
33625f21b0e6SFrederic Bohe 	 * empty groups without initialization
33635f21b0e6SFrederic Bohe 	 */
33648844618dSTheodore Ts'o 	if (ext4_has_group_desc_csum(sb) &&
33658844618dSTheodore Ts'o 	    (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
33665f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
3367cff1dfd7STheodore Ts'o 			ext4_free_clusters_after_init(sb, group, desc);
33685f21b0e6SFrederic Bohe 	} else {
33695f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
3370021b65bbSTheodore Ts'o 			ext4_free_group_clusters(sb, desc);
33715f21b0e6SFrederic Bohe 	}
33725f21b0e6SFrederic Bohe 
33735f21b0e6SFrederic Bohe 	INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
3374920313a7SAneesh Kumar K.V 	init_rwsem(&meta_group_info[i]->alloc_sem);
337564e290ecSVenkatesh Pallipadi 	meta_group_info[i]->bb_free_root = RB_ROOT;
3376196e402aSHarshad Shirwadkar 	INIT_LIST_HEAD(&meta_group_info[i]->bb_largest_free_order_node);
337783e80a6eSJan Kara 	INIT_LIST_HEAD(&meta_group_info[i]->bb_avg_fragment_size_node);
33788a57d9d6SCurt Wohlgemuth 	meta_group_info[i]->bb_largest_free_order = -1;  /* uninit */
337983e80a6eSJan Kara 	meta_group_info[i]->bb_avg_fragment_size_order = -1;  /* uninit */
3380196e402aSHarshad Shirwadkar 	meta_group_info[i]->bb_group = group;
33815f21b0e6SFrederic Bohe 
3382a3450215SRitesh Harjani 	mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
33835f21b0e6SFrederic Bohe 	return 0;
33845f21b0e6SFrederic Bohe 
33855f21b0e6SFrederic Bohe exit_group_info:
33865f21b0e6SFrederic Bohe 	/* If a meta_group_info table has been allocated, release it now */
3387caaf7a29STao Ma 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3388df3da4eaSSuraj Jitindar Singh 		struct ext4_group_info ***group_info;
3389df3da4eaSSuraj Jitindar Singh 
3390df3da4eaSSuraj Jitindar Singh 		rcu_read_lock();
3391df3da4eaSSuraj Jitindar Singh 		group_info = rcu_dereference(sbi->s_group_info);
3392df3da4eaSSuraj Jitindar Singh 		kfree(group_info[idx]);
3393df3da4eaSSuraj Jitindar Singh 		group_info[idx] = NULL;
3394df3da4eaSSuraj Jitindar Singh 		rcu_read_unlock();
3395caaf7a29STao Ma 	}
33965f21b0e6SFrederic Bohe 	return -ENOMEM;
33975f21b0e6SFrederic Bohe } /* ext4_mb_add_groupinfo */
33985f21b0e6SFrederic Bohe 
3399c9de560dSAlex Tomas static int ext4_mb_init_backend(struct super_block *sb)
3400c9de560dSAlex Tomas {
34018df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
3402c9de560dSAlex Tomas 	ext4_group_t i;
3403c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
340428623c2fSTheodore Ts'o 	int err;
34055f21b0e6SFrederic Bohe 	struct ext4_group_desc *desc;
3406df3da4eaSSuraj Jitindar Singh 	struct ext4_group_info ***group_info;
3407fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep;
3408c9de560dSAlex Tomas 
340928623c2fSTheodore Ts'o 	err = ext4_mb_alloc_groupinfo(sb, ngroups);
341028623c2fSTheodore Ts'o 	if (err)
341128623c2fSTheodore Ts'o 		return err;
34125f21b0e6SFrederic Bohe 
3413c9de560dSAlex Tomas 	sbi->s_buddy_cache = new_inode(sb);
3414c9de560dSAlex Tomas 	if (sbi->s_buddy_cache == NULL) {
34159d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_ERR, "can't get new inode");
3416c9de560dSAlex Tomas 		goto err_freesgi;
3417c9de560dSAlex Tomas 	}
341848e6061bSYu Jian 	/* To avoid potentially colliding with an valid on-disk inode number,
341948e6061bSYu Jian 	 * use EXT4_BAD_INO for the buddy cache inode number.  This inode is
342048e6061bSYu Jian 	 * not in the inode hash, so it should never be found by iget(), but
342148e6061bSYu Jian 	 * this will avoid confusion if it ever shows up during debugging. */
342248e6061bSYu Jian 	sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
3423c9de560dSAlex Tomas 	EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
34248df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
34254b99faa2SKhazhismel Kumykov 		cond_resched();
3426c9de560dSAlex Tomas 		desc = ext4_get_group_desc(sb, i, NULL);
3427c9de560dSAlex Tomas 		if (desc == NULL) {
34289d8b9ec4STheodore Ts'o 			ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
3429c9de560dSAlex Tomas 			goto err_freebuddy;
3430c9de560dSAlex Tomas 		}
34315f21b0e6SFrederic Bohe 		if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
34325f21b0e6SFrederic Bohe 			goto err_freebuddy;
3433c9de560dSAlex Tomas 	}
3434c9de560dSAlex Tomas 
3435cfd73237SAlex Zhuravlev 	if (ext4_has_feature_flex_bg(sb)) {
3436f91436d5SSabyrzhan Tasbolatov 		/* a single flex group is supposed to be read by a single IO.
3437f91436d5SSabyrzhan Tasbolatov 		 * 2 ^ s_log_groups_per_flex != UINT_MAX as s_mb_prefetch is
3438f91436d5SSabyrzhan Tasbolatov 		 * unsigned integer, so the maximum shift is 32.
3439f91436d5SSabyrzhan Tasbolatov 		 */
3440f91436d5SSabyrzhan Tasbolatov 		if (sbi->s_es->s_log_groups_per_flex >= 32) {
3441f91436d5SSabyrzhan Tasbolatov 			ext4_msg(sb, KERN_ERR, "too many log groups per flexible block group");
3442a8867f4eSPhillip Potter 			goto err_freebuddy;
3443f91436d5SSabyrzhan Tasbolatov 		}
3444f91436d5SSabyrzhan Tasbolatov 		sbi->s_mb_prefetch = min_t(uint, 1 << sbi->s_es->s_log_groups_per_flex,
344582ef1370SChunguang Xu 			BLK_MAX_SEGMENT_SIZE >> (sb->s_blocksize_bits - 9));
3446cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
3447cfd73237SAlex Zhuravlev 	} else {
3448cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch = 32;
3449cfd73237SAlex Zhuravlev 	}
3450cfd73237SAlex Zhuravlev 	if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
3451cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch = ext4_get_groups_count(sb);
3452*2caffb6aSKemeng Shi 	/*
3453*2caffb6aSKemeng Shi 	 * now many real IOs to prefetch within a single allocation at
3454*2caffb6aSKemeng Shi 	 * CR_POWER2_ALIGNED. Given CR_POWER2_ALIGNED is an CPU-related
3455*2caffb6aSKemeng Shi 	 * optimization we shouldn't try to load too many groups, at some point
3456*2caffb6aSKemeng Shi 	 * we should start to use what we've got in memory.
3457cfd73237SAlex Zhuravlev 	 * with an average random access time 5ms, it'd take a second to get
3458cfd73237SAlex Zhuravlev 	 * 200 groups (* N with flex_bg), so let's make this limit 4
3459cfd73237SAlex Zhuravlev 	 */
3460cfd73237SAlex Zhuravlev 	sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
3461cfd73237SAlex Zhuravlev 	if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
3462cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
3463cfd73237SAlex Zhuravlev 
3464c9de560dSAlex Tomas 	return 0;
3465c9de560dSAlex Tomas 
3466c9de560dSAlex Tomas err_freebuddy:
3467fb1813f4SCurt Wohlgemuth 	cachep = get_groupinfo_cache(sb->s_blocksize_bits);
34685354b2afSTheodore Ts'o 	while (i-- > 0) {
34695354b2afSTheodore Ts'o 		struct ext4_group_info *grp = ext4_get_group_info(sb, i);
34705354b2afSTheodore Ts'o 
34715354b2afSTheodore Ts'o 		if (grp)
34725354b2afSTheodore Ts'o 			kmem_cache_free(cachep, grp);
34735354b2afSTheodore Ts'o 	}
347428623c2fSTheodore Ts'o 	i = sbi->s_group_info_size;
3475df3da4eaSSuraj Jitindar Singh 	rcu_read_lock();
3476df3da4eaSSuraj Jitindar Singh 	group_info = rcu_dereference(sbi->s_group_info);
3477f1fa3342SRoel Kluin 	while (i-- > 0)
3478df3da4eaSSuraj Jitindar Singh 		kfree(group_info[i]);
3479df3da4eaSSuraj Jitindar Singh 	rcu_read_unlock();
3480c9de560dSAlex Tomas 	iput(sbi->s_buddy_cache);
3481c9de560dSAlex Tomas err_freesgi:
3482df3da4eaSSuraj Jitindar Singh 	rcu_read_lock();
3483df3da4eaSSuraj Jitindar Singh 	kvfree(rcu_dereference(sbi->s_group_info));
3484df3da4eaSSuraj Jitindar Singh 	rcu_read_unlock();
3485c9de560dSAlex Tomas 	return -ENOMEM;
3486c9de560dSAlex Tomas }
3487c9de560dSAlex Tomas 
34882892c15dSEric Sandeen static void ext4_groupinfo_destroy_slabs(void)
34892892c15dSEric Sandeen {
34902892c15dSEric Sandeen 	int i;
34912892c15dSEric Sandeen 
34922892c15dSEric Sandeen 	for (i = 0; i < NR_GRPINFO_CACHES; i++) {
34932892c15dSEric Sandeen 		kmem_cache_destroy(ext4_groupinfo_caches[i]);
34942892c15dSEric Sandeen 		ext4_groupinfo_caches[i] = NULL;
34952892c15dSEric Sandeen 	}
34962892c15dSEric Sandeen }
34972892c15dSEric Sandeen 
34982892c15dSEric Sandeen static int ext4_groupinfo_create_slab(size_t size)
34992892c15dSEric Sandeen {
35002892c15dSEric Sandeen 	static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
35012892c15dSEric Sandeen 	int slab_size;
35022892c15dSEric Sandeen 	int blocksize_bits = order_base_2(size);
35032892c15dSEric Sandeen 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
35042892c15dSEric Sandeen 	struct kmem_cache *cachep;
35052892c15dSEric Sandeen 
35062892c15dSEric Sandeen 	if (cache_index >= NR_GRPINFO_CACHES)
35072892c15dSEric Sandeen 		return -EINVAL;
35082892c15dSEric Sandeen 
35092892c15dSEric Sandeen 	if (unlikely(cache_index < 0))
35102892c15dSEric Sandeen 		cache_index = 0;
35112892c15dSEric Sandeen 
35122892c15dSEric Sandeen 	mutex_lock(&ext4_grpinfo_slab_create_mutex);
35132892c15dSEric Sandeen 	if (ext4_groupinfo_caches[cache_index]) {
35142892c15dSEric Sandeen 		mutex_unlock(&ext4_grpinfo_slab_create_mutex);
35152892c15dSEric Sandeen 		return 0;	/* Already created */
35162892c15dSEric Sandeen 	}
35172892c15dSEric Sandeen 
35182892c15dSEric Sandeen 	slab_size = offsetof(struct ext4_group_info,
35192892c15dSEric Sandeen 				bb_counters[blocksize_bits + 2]);
35202892c15dSEric Sandeen 
35212892c15dSEric Sandeen 	cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
35222892c15dSEric Sandeen 					slab_size, 0, SLAB_RECLAIM_ACCOUNT,
35232892c15dSEric Sandeen 					NULL);
35242892c15dSEric Sandeen 
3525823ba01fSTao Ma 	ext4_groupinfo_caches[cache_index] = cachep;
3526823ba01fSTao Ma 
35272892c15dSEric Sandeen 	mutex_unlock(&ext4_grpinfo_slab_create_mutex);
35282892c15dSEric Sandeen 	if (!cachep) {
35299d8b9ec4STheodore Ts'o 		printk(KERN_EMERG
35309d8b9ec4STheodore Ts'o 		       "EXT4-fs: no memory for groupinfo slab cache\n");
35312892c15dSEric Sandeen 		return -ENOMEM;
35322892c15dSEric Sandeen 	}
35332892c15dSEric Sandeen 
35342892c15dSEric Sandeen 	return 0;
35352892c15dSEric Sandeen }
35362892c15dSEric Sandeen 
353755cdd0afSWang Jianchao static void ext4_discard_work(struct work_struct *work)
353855cdd0afSWang Jianchao {
353955cdd0afSWang Jianchao 	struct ext4_sb_info *sbi = container_of(work,
354055cdd0afSWang Jianchao 			struct ext4_sb_info, s_discard_work);
354155cdd0afSWang Jianchao 	struct super_block *sb = sbi->s_sb;
354255cdd0afSWang Jianchao 	struct ext4_free_data *fd, *nfd;
354355cdd0afSWang Jianchao 	struct ext4_buddy e4b;
35440f6bc579SRuan Jinjie 	LIST_HEAD(discard_list);
354555cdd0afSWang Jianchao 	ext4_group_t grp, load_grp;
354655cdd0afSWang Jianchao 	int err = 0;
354755cdd0afSWang Jianchao 
354855cdd0afSWang Jianchao 	spin_lock(&sbi->s_md_lock);
354955cdd0afSWang Jianchao 	list_splice_init(&sbi->s_discard_list, &discard_list);
355055cdd0afSWang Jianchao 	spin_unlock(&sbi->s_md_lock);
355155cdd0afSWang Jianchao 
355255cdd0afSWang Jianchao 	load_grp = UINT_MAX;
355355cdd0afSWang Jianchao 	list_for_each_entry_safe(fd, nfd, &discard_list, efd_list) {
355455cdd0afSWang Jianchao 		/*
35555036ab8dSWang Jianchao 		 * If filesystem is umounting or no memory or suffering
35565036ab8dSWang Jianchao 		 * from no space, give up the discard
355755cdd0afSWang Jianchao 		 */
35585036ab8dSWang Jianchao 		if ((sb->s_flags & SB_ACTIVE) && !err &&
35595036ab8dSWang Jianchao 		    !atomic_read(&sbi->s_retry_alloc_pending)) {
356055cdd0afSWang Jianchao 			grp = fd->efd_group;
356155cdd0afSWang Jianchao 			if (grp != load_grp) {
356255cdd0afSWang Jianchao 				if (load_grp != UINT_MAX)
356355cdd0afSWang Jianchao 					ext4_mb_unload_buddy(&e4b);
356455cdd0afSWang Jianchao 
356555cdd0afSWang Jianchao 				err = ext4_mb_load_buddy(sb, grp, &e4b);
356655cdd0afSWang Jianchao 				if (err) {
356755cdd0afSWang Jianchao 					kmem_cache_free(ext4_free_data_cachep, fd);
356855cdd0afSWang Jianchao 					load_grp = UINT_MAX;
356955cdd0afSWang Jianchao 					continue;
357055cdd0afSWang Jianchao 				} else {
357155cdd0afSWang Jianchao 					load_grp = grp;
357255cdd0afSWang Jianchao 				}
357355cdd0afSWang Jianchao 			}
357455cdd0afSWang Jianchao 
357555cdd0afSWang Jianchao 			ext4_lock_group(sb, grp);
357655cdd0afSWang Jianchao 			ext4_try_to_trim_range(sb, &e4b, fd->efd_start_cluster,
357755cdd0afSWang Jianchao 						fd->efd_start_cluster + fd->efd_count - 1, 1);
357855cdd0afSWang Jianchao 			ext4_unlock_group(sb, grp);
357955cdd0afSWang Jianchao 		}
358055cdd0afSWang Jianchao 		kmem_cache_free(ext4_free_data_cachep, fd);
358155cdd0afSWang Jianchao 	}
358255cdd0afSWang Jianchao 
358355cdd0afSWang Jianchao 	if (load_grp != UINT_MAX)
358455cdd0afSWang Jianchao 		ext4_mb_unload_buddy(&e4b);
358555cdd0afSWang Jianchao }
358655cdd0afSWang Jianchao 
35879d99012fSAkira Fujita int ext4_mb_init(struct super_block *sb)
3588c9de560dSAlex Tomas {
3589c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
35906be2ded1SAneesh Kumar K.V 	unsigned i, j;
3591935244cdSNicolai Stange 	unsigned offset, offset_incr;
3592c9de560dSAlex Tomas 	unsigned max;
359374767c5aSShen Feng 	int ret;
3594c9de560dSAlex Tomas 
35954b68f6dfSHarshad Shirwadkar 	i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_offsets);
3596c9de560dSAlex Tomas 
3597c9de560dSAlex Tomas 	sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
3598c9de560dSAlex Tomas 	if (sbi->s_mb_offsets == NULL) {
3599fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
3600fb1813f4SCurt Wohlgemuth 		goto out;
3601c9de560dSAlex Tomas 	}
3602ff7ef329SYasunori Goto 
36034b68f6dfSHarshad Shirwadkar 	i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_maxs);
3604c9de560dSAlex Tomas 	sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
3605c9de560dSAlex Tomas 	if (sbi->s_mb_maxs == NULL) {
3606fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
3607fb1813f4SCurt Wohlgemuth 		goto out;
3608fb1813f4SCurt Wohlgemuth 	}
3609fb1813f4SCurt Wohlgemuth 
36102892c15dSEric Sandeen 	ret = ext4_groupinfo_create_slab(sb->s_blocksize);
36112892c15dSEric Sandeen 	if (ret < 0)
3612fb1813f4SCurt Wohlgemuth 		goto out;
3613c9de560dSAlex Tomas 
3614c9de560dSAlex Tomas 	/* order 0 is regular bitmap */
3615c9de560dSAlex Tomas 	sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
3616c9de560dSAlex Tomas 	sbi->s_mb_offsets[0] = 0;
3617c9de560dSAlex Tomas 
3618c9de560dSAlex Tomas 	i = 1;
3619c9de560dSAlex Tomas 	offset = 0;
3620935244cdSNicolai Stange 	offset_incr = 1 << (sb->s_blocksize_bits - 1);
3621c9de560dSAlex Tomas 	max = sb->s_blocksize << 2;
3622c9de560dSAlex Tomas 	do {
3623c9de560dSAlex Tomas 		sbi->s_mb_offsets[i] = offset;
3624c9de560dSAlex Tomas 		sbi->s_mb_maxs[i] = max;
3625935244cdSNicolai Stange 		offset += offset_incr;
3626935244cdSNicolai Stange 		offset_incr = offset_incr >> 1;
3627c9de560dSAlex Tomas 		max = max >> 1;
3628c9de560dSAlex Tomas 		i++;
36294b68f6dfSHarshad Shirwadkar 	} while (i < MB_NUM_ORDERS(sb));
36304b68f6dfSHarshad Shirwadkar 
363183e80a6eSJan Kara 	sbi->s_mb_avg_fragment_size =
363283e80a6eSJan Kara 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
363383e80a6eSJan Kara 			GFP_KERNEL);
363483e80a6eSJan Kara 	if (!sbi->s_mb_avg_fragment_size) {
363583e80a6eSJan Kara 		ret = -ENOMEM;
363683e80a6eSJan Kara 		goto out;
363783e80a6eSJan Kara 	}
363883e80a6eSJan Kara 	sbi->s_mb_avg_fragment_size_locks =
363983e80a6eSJan Kara 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
364083e80a6eSJan Kara 			GFP_KERNEL);
364183e80a6eSJan Kara 	if (!sbi->s_mb_avg_fragment_size_locks) {
364283e80a6eSJan Kara 		ret = -ENOMEM;
364383e80a6eSJan Kara 		goto out;
364483e80a6eSJan Kara 	}
364583e80a6eSJan Kara 	for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
364683e80a6eSJan Kara 		INIT_LIST_HEAD(&sbi->s_mb_avg_fragment_size[i]);
364783e80a6eSJan Kara 		rwlock_init(&sbi->s_mb_avg_fragment_size_locks[i]);
364883e80a6eSJan Kara 	}
3649196e402aSHarshad Shirwadkar 	sbi->s_mb_largest_free_orders =
3650196e402aSHarshad Shirwadkar 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3651196e402aSHarshad Shirwadkar 			GFP_KERNEL);
3652196e402aSHarshad Shirwadkar 	if (!sbi->s_mb_largest_free_orders) {
3653196e402aSHarshad Shirwadkar 		ret = -ENOMEM;
3654196e402aSHarshad Shirwadkar 		goto out;
3655196e402aSHarshad Shirwadkar 	}
3656196e402aSHarshad Shirwadkar 	sbi->s_mb_largest_free_orders_locks =
3657196e402aSHarshad Shirwadkar 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3658196e402aSHarshad Shirwadkar 			GFP_KERNEL);
3659196e402aSHarshad Shirwadkar 	if (!sbi->s_mb_largest_free_orders_locks) {
3660196e402aSHarshad Shirwadkar 		ret = -ENOMEM;
3661196e402aSHarshad Shirwadkar 		goto out;
3662196e402aSHarshad Shirwadkar 	}
3663196e402aSHarshad Shirwadkar 	for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3664196e402aSHarshad Shirwadkar 		INIT_LIST_HEAD(&sbi->s_mb_largest_free_orders[i]);
3665196e402aSHarshad Shirwadkar 		rwlock_init(&sbi->s_mb_largest_free_orders_locks[i]);
3666196e402aSHarshad Shirwadkar 	}
3667c9de560dSAlex Tomas 
3668c9de560dSAlex Tomas 	spin_lock_init(&sbi->s_md_lock);
3669d08854f5STheodore Ts'o 	sbi->s_mb_free_pending = 0;
3670ce774e53SJinke Han 	INIT_LIST_HEAD(&sbi->s_freed_data_list[0]);
3671ce774e53SJinke Han 	INIT_LIST_HEAD(&sbi->s_freed_data_list[1]);
367255cdd0afSWang Jianchao 	INIT_LIST_HEAD(&sbi->s_discard_list);
367355cdd0afSWang Jianchao 	INIT_WORK(&sbi->s_discard_work, ext4_discard_work);
36745036ab8dSWang Jianchao 	atomic_set(&sbi->s_retry_alloc_pending, 0);
3675c9de560dSAlex Tomas 
3676c9de560dSAlex Tomas 	sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
3677c9de560dSAlex Tomas 	sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
3678c9de560dSAlex Tomas 	sbi->s_mb_stats = MB_DEFAULT_STATS;
3679c9de560dSAlex Tomas 	sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
3680c9de560dSAlex Tomas 	sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
3681f52f3d2bSOjaswin Mujoo 	sbi->s_mb_best_avail_max_trim_order = MB_DEFAULT_BEST_AVAIL_TRIM_ORDER;
36827e170922SOjaswin Mujoo 
368327baebb8STheodore Ts'o 	/*
368427baebb8STheodore Ts'o 	 * The default group preallocation is 512, which for 4k block
368527baebb8STheodore Ts'o 	 * sizes translates to 2 megabytes.  However for bigalloc file
368627baebb8STheodore Ts'o 	 * systems, this is probably too big (i.e, if the cluster size
368727baebb8STheodore Ts'o 	 * is 1 megabyte, then group preallocation size becomes half a
368827baebb8STheodore Ts'o 	 * gigabyte!).  As a default, we will keep a two megabyte
368927baebb8STheodore Ts'o 	 * group pralloc size for cluster sizes up to 64k, and after
369027baebb8STheodore Ts'o 	 * that, we will force a minimum group preallocation size of
369127baebb8STheodore Ts'o 	 * 32 clusters.  This translates to 8 megs when the cluster
369227baebb8STheodore Ts'o 	 * size is 256k, and 32 megs when the cluster size is 1 meg,
369327baebb8STheodore Ts'o 	 * which seems reasonable as a default.
369427baebb8STheodore Ts'o 	 */
369527baebb8STheodore Ts'o 	sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
369627baebb8STheodore Ts'o 				       sbi->s_cluster_bits, 32);
3697d7a1fee1SDan Ehrenberg 	/*
3698d7a1fee1SDan Ehrenberg 	 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
3699d7a1fee1SDan Ehrenberg 	 * to the lowest multiple of s_stripe which is bigger than
3700d7a1fee1SDan Ehrenberg 	 * the s_mb_group_prealloc as determined above. We want
3701d7a1fee1SDan Ehrenberg 	 * the preallocation size to be an exact multiple of the
3702d7a1fee1SDan Ehrenberg 	 * RAID stripe size so that preallocations don't fragment
3703d7a1fee1SDan Ehrenberg 	 * the stripes.
3704d7a1fee1SDan Ehrenberg 	 */
3705d7a1fee1SDan Ehrenberg 	if (sbi->s_stripe > 1) {
3706d7a1fee1SDan Ehrenberg 		sbi->s_mb_group_prealloc = roundup(
3707c3defd99SKemeng Shi 			sbi->s_mb_group_prealloc, EXT4_B2C(sbi, sbi->s_stripe));
3708d7a1fee1SDan Ehrenberg 	}
3709c9de560dSAlex Tomas 
3710730c213cSEric Sandeen 	sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
3711c9de560dSAlex Tomas 	if (sbi->s_locality_groups == NULL) {
3712fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
3713029b10c5SAndrey Tsyvarev 		goto out;
3714c9de560dSAlex Tomas 	}
3715730c213cSEric Sandeen 	for_each_possible_cpu(i) {
3716c9de560dSAlex Tomas 		struct ext4_locality_group *lg;
3717730c213cSEric Sandeen 		lg = per_cpu_ptr(sbi->s_locality_groups, i);
3718c9de560dSAlex Tomas 		mutex_init(&lg->lg_mutex);
37196be2ded1SAneesh Kumar K.V 		for (j = 0; j < PREALLOC_TB_SIZE; j++)
37206be2ded1SAneesh Kumar K.V 			INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
3721c9de560dSAlex Tomas 		spin_lock_init(&lg->lg_prealloc_lock);
3722c9de560dSAlex Tomas 	}
3723c9de560dSAlex Tomas 
372410f0d2a5SChristoph Hellwig 	if (bdev_nonrot(sb->s_bdev))
3725196e402aSHarshad Shirwadkar 		sbi->s_mb_max_linear_groups = 0;
3726196e402aSHarshad Shirwadkar 	else
3727196e402aSHarshad Shirwadkar 		sbi->s_mb_max_linear_groups = MB_DEFAULT_LINEAR_LIMIT;
372879a77c5aSYu Jian 	/* init file for buddy data */
372979a77c5aSYu Jian 	ret = ext4_mb_init_backend(sb);
37307aa0baeaSTao Ma 	if (ret != 0)
37317aa0baeaSTao Ma 		goto out_free_locality_groups;
373279a77c5aSYu Jian 
37337aa0baeaSTao Ma 	return 0;
37347aa0baeaSTao Ma 
37357aa0baeaSTao Ma out_free_locality_groups:
37367aa0baeaSTao Ma 	free_percpu(sbi->s_locality_groups);
37377aa0baeaSTao Ma 	sbi->s_locality_groups = NULL;
3738fb1813f4SCurt Wohlgemuth out:
373983e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size);
374083e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size_locks);
3741196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders);
3742196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders_locks);
3743fb1813f4SCurt Wohlgemuth 	kfree(sbi->s_mb_offsets);
37447aa0baeaSTao Ma 	sbi->s_mb_offsets = NULL;
3745fb1813f4SCurt Wohlgemuth 	kfree(sbi->s_mb_maxs);
37467aa0baeaSTao Ma 	sbi->s_mb_maxs = NULL;
3747fb1813f4SCurt Wohlgemuth 	return ret;
3748c9de560dSAlex Tomas }
3749c9de560dSAlex Tomas 
3750955ce5f5SAneesh Kumar K.V /* need to called with the ext4 group lock held */
3751d3df1453SRitesh Harjani static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
3752c9de560dSAlex Tomas {
3753c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3754c9de560dSAlex Tomas 	struct list_head *cur, *tmp;
3755c9de560dSAlex Tomas 	int count = 0;
3756c9de560dSAlex Tomas 
3757c9de560dSAlex Tomas 	list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
3758c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3759c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
3760c9de560dSAlex Tomas 		count++;
3761688f05a0SAneesh Kumar K.V 		kmem_cache_free(ext4_pspace_cachep, pa);
3762c9de560dSAlex Tomas 	}
3763d3df1453SRitesh Harjani 	return count;
3764c9de560dSAlex Tomas }
3765c9de560dSAlex Tomas 
376690817717SKemeng Shi void ext4_mb_release(struct super_block *sb)
3767c9de560dSAlex Tomas {
37688df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
3769c9de560dSAlex Tomas 	ext4_group_t i;
3770c9de560dSAlex Tomas 	int num_meta_group_infos;
3771df3da4eaSSuraj Jitindar Singh 	struct ext4_group_info *grinfo, ***group_info;
3772c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3773fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3774d3df1453SRitesh Harjani 	int count;
3775c9de560dSAlex Tomas 
377655cdd0afSWang Jianchao 	if (test_opt(sb, DISCARD)) {
377755cdd0afSWang Jianchao 		/*
377855cdd0afSWang Jianchao 		 * wait the discard work to drain all of ext4_free_data
377955cdd0afSWang Jianchao 		 */
378055cdd0afSWang Jianchao 		flush_work(&sbi->s_discard_work);
378155cdd0afSWang Jianchao 		WARN_ON_ONCE(!list_empty(&sbi->s_discard_list));
378255cdd0afSWang Jianchao 	}
378355cdd0afSWang Jianchao 
3784c9de560dSAlex Tomas 	if (sbi->s_group_info) {
37858df9675fSTheodore Ts'o 		for (i = 0; i < ngroups; i++) {
37864b99faa2SKhazhismel Kumykov 			cond_resched();
3787c9de560dSAlex Tomas 			grinfo = ext4_get_group_info(sb, i);
37885354b2afSTheodore Ts'o 			if (!grinfo)
37895354b2afSTheodore Ts'o 				continue;
3790a3450215SRitesh Harjani 			mb_group_bb_bitmap_free(grinfo);
3791c9de560dSAlex Tomas 			ext4_lock_group(sb, i);
3792d3df1453SRitesh Harjani 			count = ext4_mb_cleanup_pa(grinfo);
3793d3df1453SRitesh Harjani 			if (count)
3794d3df1453SRitesh Harjani 				mb_debug(sb, "mballoc: %d PAs left\n",
3795d3df1453SRitesh Harjani 					 count);
3796c9de560dSAlex Tomas 			ext4_unlock_group(sb, i);
3797fb1813f4SCurt Wohlgemuth 			kmem_cache_free(cachep, grinfo);
3798c9de560dSAlex Tomas 		}
37998df9675fSTheodore Ts'o 		num_meta_group_infos = (ngroups +
3800c9de560dSAlex Tomas 				EXT4_DESC_PER_BLOCK(sb) - 1) >>
3801c9de560dSAlex Tomas 			EXT4_DESC_PER_BLOCK_BITS(sb);
3802df3da4eaSSuraj Jitindar Singh 		rcu_read_lock();
3803df3da4eaSSuraj Jitindar Singh 		group_info = rcu_dereference(sbi->s_group_info);
3804c9de560dSAlex Tomas 		for (i = 0; i < num_meta_group_infos; i++)
3805df3da4eaSSuraj Jitindar Singh 			kfree(group_info[i]);
3806df3da4eaSSuraj Jitindar Singh 		kvfree(group_info);
3807df3da4eaSSuraj Jitindar Singh 		rcu_read_unlock();
3808c9de560dSAlex Tomas 	}
380983e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size);
381083e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size_locks);
3811196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders);
3812196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders_locks);
3813c9de560dSAlex Tomas 	kfree(sbi->s_mb_offsets);
3814c9de560dSAlex Tomas 	kfree(sbi->s_mb_maxs);
3815c9de560dSAlex Tomas 	iput(sbi->s_buddy_cache);
3816c9de560dSAlex Tomas 	if (sbi->s_mb_stats) {
38179d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
38189d8b9ec4STheodore Ts'o 		       "mballoc: %u blocks %u reqs (%u success)",
3819c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_allocated),
3820c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_reqs),
3821c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_success));
38229d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
3823a6c75eafSHarshad Shirwadkar 		      "mballoc: %u extents scanned, %u groups scanned, %u goal hits, "
38249d8b9ec4STheodore Ts'o 				"%u 2^N hits, %u breaks, %u lost",
3825c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_ex_scanned),
3826a6c75eafSHarshad Shirwadkar 				atomic_read(&sbi->s_bal_groups_scanned),
3827c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_goals),
3828c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_2orders),
3829c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_breaks),
3830c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_lost_chunks));
38319d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
383267d25186SHarshad Shirwadkar 		       "mballoc: %u generated and it took %llu",
383367d25186SHarshad Shirwadkar 				atomic_read(&sbi->s_mb_buddies_generated),
383467d25186SHarshad Shirwadkar 				atomic64_read(&sbi->s_mb_generation_time));
38359d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
38369d8b9ec4STheodore Ts'o 		       "mballoc: %u preallocated, %u discarded",
3837c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_preallocated),
3838c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_discarded));
3839c9de560dSAlex Tomas 	}
3840c9de560dSAlex Tomas 
3841730c213cSEric Sandeen 	free_percpu(sbi->s_locality_groups);
3842c9de560dSAlex Tomas }
3843c9de560dSAlex Tomas 
384477ca6cdfSLukas Czerner static inline int ext4_issue_discard(struct super_block *sb,
38450efcd739SWenchao Hao 		ext4_group_t block_group, ext4_grpblk_t cluster, int count)
38465c521830SJiaying Zhang {
38475c521830SJiaying Zhang 	ext4_fsblk_t discard_block;
38485c521830SJiaying Zhang 
384984130193STheodore Ts'o 	discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
385084130193STheodore Ts'o 			 ext4_group_first_block_no(sb, block_group));
385184130193STheodore Ts'o 	count = EXT4_C2B(EXT4_SB(sb), count);
38525c521830SJiaying Zhang 	trace_ext4_discard_blocks(sb,
38535c521830SJiaying Zhang 			(unsigned long long) discard_block, count);
38540efcd739SWenchao Hao 
385593259636SLukas Czerner 	return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
38565c521830SJiaying Zhang }
38575c521830SJiaying Zhang 
3858a0154344SDaeho Jeong static void ext4_free_data_in_buddy(struct super_block *sb,
3859a0154344SDaeho Jeong 				    struct ext4_free_data *entry)
3860c9de560dSAlex Tomas {
3861c9de560dSAlex Tomas 	struct ext4_buddy e4b;
3862c894058dSAneesh Kumar K.V 	struct ext4_group_info *db;
3863c7f2bafaSKemeng Shi 	int err, count = 0;
3864c9de560dSAlex Tomas 
3865d3df1453SRitesh Harjani 	mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
386618aadd47SBobi Jam 		 entry->efd_count, entry->efd_group, entry);
3867c9de560dSAlex Tomas 
386818aadd47SBobi Jam 	err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
3869c9de560dSAlex Tomas 	/* we expect to find existing buddy because it's pinned */
3870c9de560dSAlex Tomas 	BUG_ON(err != 0);
3871c9de560dSAlex Tomas 
3872d08854f5STheodore Ts'o 	spin_lock(&EXT4_SB(sb)->s_md_lock);
3873d08854f5STheodore Ts'o 	EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
3874d08854f5STheodore Ts'o 	spin_unlock(&EXT4_SB(sb)->s_md_lock);
387518aadd47SBobi Jam 
3876c894058dSAneesh Kumar K.V 	db = e4b.bd_info;
3877c9de560dSAlex Tomas 	/* there are blocks to put in buddy to make them really free */
387818aadd47SBobi Jam 	count += entry->efd_count;
387918aadd47SBobi Jam 	ext4_lock_group(sb, entry->efd_group);
3880c894058dSAneesh Kumar K.V 	/* Take it out of per group rb tree */
388118aadd47SBobi Jam 	rb_erase(&entry->efd_node, &(db->bb_free_root));
388218aadd47SBobi Jam 	mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
3883c9de560dSAlex Tomas 
38843d56b8d2STao Ma 	/*
38853d56b8d2STao Ma 	 * Clear the trimmed flag for the group so that the next
38863d56b8d2STao Ma 	 * ext4_trim_fs can trim it.
38873d56b8d2STao Ma 	 * If the volume is mounted with -o discard, online discard
38883d56b8d2STao Ma 	 * is supported and the free blocks will be trimmed online.
38893d56b8d2STao Ma 	 */
38903d56b8d2STao Ma 	if (!test_opt(sb, DISCARD))
38913d56b8d2STao Ma 		EXT4_MB_GRP_CLEAR_TRIMMED(db);
38923d56b8d2STao Ma 
3893c894058dSAneesh Kumar K.V 	if (!db->bb_free_root.rb_node) {
3894c894058dSAneesh Kumar K.V 		/* No more items in the per group rb tree
3895c894058dSAneesh Kumar K.V 		 * balance refcounts from ext4_mb_free_metadata()
3896c894058dSAneesh Kumar K.V 		 */
389709cbfeafSKirill A. Shutemov 		put_page(e4b.bd_buddy_page);
389809cbfeafSKirill A. Shutemov 		put_page(e4b.bd_bitmap_page);
3899c894058dSAneesh Kumar K.V 	}
390018aadd47SBobi Jam 	ext4_unlock_group(sb, entry->efd_group);
3901e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
3902c9de560dSAlex Tomas 
3903c7f2bafaSKemeng Shi 	mb_debug(sb, "freed %d blocks in 1 structures\n", count);
3904c9de560dSAlex Tomas }
3905c9de560dSAlex Tomas 
3906a0154344SDaeho Jeong /*
3907a0154344SDaeho Jeong  * This function is called by the jbd2 layer once the commit has finished,
3908a0154344SDaeho Jeong  * so we know we can free the blocks that were released with that commit.
3909a0154344SDaeho Jeong  */
3910a0154344SDaeho Jeong void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
3911a0154344SDaeho Jeong {
3912a0154344SDaeho Jeong 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3913a0154344SDaeho Jeong 	struct ext4_free_data *entry, *tmp;
39140f6bc579SRuan Jinjie 	LIST_HEAD(freed_data_list);
3915ce774e53SJinke Han 	struct list_head *s_freed_head = &sbi->s_freed_data_list[commit_tid & 1];
391655cdd0afSWang Jianchao 	bool wake;
3917a0154344SDaeho Jeong 
3918ce774e53SJinke Han 	list_replace_init(s_freed_head, &freed_data_list);
3919a0154344SDaeho Jeong 
392055cdd0afSWang Jianchao 	list_for_each_entry(entry, &freed_data_list, efd_list)
3921a0154344SDaeho Jeong 		ext4_free_data_in_buddy(sb, entry);
392255cdd0afSWang Jianchao 
392355cdd0afSWang Jianchao 	if (test_opt(sb, DISCARD)) {
392455cdd0afSWang Jianchao 		spin_lock(&sbi->s_md_lock);
392555cdd0afSWang Jianchao 		wake = list_empty(&sbi->s_discard_list);
392655cdd0afSWang Jianchao 		list_splice_tail(&freed_data_list, &sbi->s_discard_list);
392755cdd0afSWang Jianchao 		spin_unlock(&sbi->s_md_lock);
392855cdd0afSWang Jianchao 		if (wake)
392955cdd0afSWang Jianchao 			queue_work(system_unbound_wq, &sbi->s_discard_work);
393055cdd0afSWang Jianchao 	} else {
393155cdd0afSWang Jianchao 		list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
393255cdd0afSWang Jianchao 			kmem_cache_free(ext4_free_data_cachep, entry);
393355cdd0afSWang Jianchao 	}
3934a0154344SDaeho Jeong }
3935a0154344SDaeho Jeong 
39365dabfc78STheodore Ts'o int __init ext4_init_mballoc(void)
3937c9de560dSAlex Tomas {
393816828088STheodore Ts'o 	ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
393916828088STheodore Ts'o 					SLAB_RECLAIM_ACCOUNT);
3940c9de560dSAlex Tomas 	if (ext4_pspace_cachep == NULL)
3941f283529aSRitesh Harjani 		goto out;
3942c9de560dSAlex Tomas 
394316828088STheodore Ts'o 	ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
394416828088STheodore Ts'o 				    SLAB_RECLAIM_ACCOUNT);
3945f283529aSRitesh Harjani 	if (ext4_ac_cachep == NULL)
3946f283529aSRitesh Harjani 		goto out_pa_free;
3947c894058dSAneesh Kumar K.V 
394818aadd47SBobi Jam 	ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
394916828088STheodore Ts'o 					   SLAB_RECLAIM_ACCOUNT);
3950f283529aSRitesh Harjani 	if (ext4_free_data_cachep == NULL)
3951f283529aSRitesh Harjani 		goto out_ac_free;
3952f283529aSRitesh Harjani 
3953c9de560dSAlex Tomas 	return 0;
3954f283529aSRitesh Harjani 
3955f283529aSRitesh Harjani out_ac_free:
3956f283529aSRitesh Harjani 	kmem_cache_destroy(ext4_ac_cachep);
3957f283529aSRitesh Harjani out_pa_free:
3958f283529aSRitesh Harjani 	kmem_cache_destroy(ext4_pspace_cachep);
3959f283529aSRitesh Harjani out:
3960f283529aSRitesh Harjani 	return -ENOMEM;
3961c9de560dSAlex Tomas }
3962c9de560dSAlex Tomas 
39635dabfc78STheodore Ts'o void ext4_exit_mballoc(void)
3964c9de560dSAlex Tomas {
39653e03f9caSJesper Dangaard Brouer 	/*
39663e03f9caSJesper Dangaard Brouer 	 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
39673e03f9caSJesper Dangaard Brouer 	 * before destroying the slab cache.
39683e03f9caSJesper Dangaard Brouer 	 */
39693e03f9caSJesper Dangaard Brouer 	rcu_barrier();
3970c9de560dSAlex Tomas 	kmem_cache_destroy(ext4_pspace_cachep);
3971256bdb49SEric Sandeen 	kmem_cache_destroy(ext4_ac_cachep);
397218aadd47SBobi Jam 	kmem_cache_destroy(ext4_free_data_cachep);
39732892c15dSEric Sandeen 	ext4_groupinfo_destroy_slabs();
3974c9de560dSAlex Tomas }
3975c9de560dSAlex Tomas 
3976c431d386SKemeng Shi #define EXT4_MB_BITMAP_MARKED_CHECK 0x0001
3977c431d386SKemeng Shi #define EXT4_MB_SYNC_UPDATE 0x0002
3978f9e2d95aSKemeng Shi static int
3979c431d386SKemeng Shi ext4_mb_mark_context(handle_t *handle, struct super_block *sb, bool state,
3980c431d386SKemeng Shi 		     ext4_group_t group, ext4_grpblk_t blkoff,
3981c431d386SKemeng Shi 		     ext4_grpblk_t len, int flags, ext4_grpblk_t *ret_changed)
3982f9e2d95aSKemeng Shi {
3983f9e2d95aSKemeng Shi 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3984f9e2d95aSKemeng Shi 	struct buffer_head *bitmap_bh = NULL;
3985f9e2d95aSKemeng Shi 	struct ext4_group_desc *gdp;
3986f9e2d95aSKemeng Shi 	struct buffer_head *gdp_bh;
3987f9e2d95aSKemeng Shi 	int err;
3988c431d386SKemeng Shi 	unsigned int i, already, changed = len;
3989f9e2d95aSKemeng Shi 
3990bdefd689SKemeng Shi 	KUNIT_STATIC_STUB_REDIRECT(ext4_mb_mark_context,
3991bdefd689SKemeng Shi 				   handle, sb, state, group, blkoff, len,
3992bdefd689SKemeng Shi 				   flags, ret_changed);
3993bdefd689SKemeng Shi 
3994c431d386SKemeng Shi 	if (ret_changed)
3995c431d386SKemeng Shi 		*ret_changed = 0;
3996f9e2d95aSKemeng Shi 	bitmap_bh = ext4_read_block_bitmap(sb, group);
3997f9e2d95aSKemeng Shi 	if (IS_ERR(bitmap_bh))
3998f9e2d95aSKemeng Shi 		return PTR_ERR(bitmap_bh);
3999f9e2d95aSKemeng Shi 
4000c431d386SKemeng Shi 	if (handle) {
4001c431d386SKemeng Shi 		BUFFER_TRACE(bitmap_bh, "getting write access");
4002c431d386SKemeng Shi 		err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
4003c431d386SKemeng Shi 						    EXT4_JTR_NONE);
4004c431d386SKemeng Shi 		if (err)
4005c431d386SKemeng Shi 			goto out_err;
4006c431d386SKemeng Shi 	}
4007c431d386SKemeng Shi 
4008f9e2d95aSKemeng Shi 	err = -EIO;
4009f9e2d95aSKemeng Shi 	gdp = ext4_get_group_desc(sb, group, &gdp_bh);
4010f9e2d95aSKemeng Shi 	if (!gdp)
4011f9e2d95aSKemeng Shi 		goto out_err;
4012f9e2d95aSKemeng Shi 
4013c431d386SKemeng Shi 	if (handle) {
4014c431d386SKemeng Shi 		BUFFER_TRACE(gdp_bh, "get_write_access");
4015c431d386SKemeng Shi 		err = ext4_journal_get_write_access(handle, sb, gdp_bh,
4016c431d386SKemeng Shi 						    EXT4_JTR_NONE);
4017c431d386SKemeng Shi 		if (err)
4018c431d386SKemeng Shi 			goto out_err;
4019c431d386SKemeng Shi 	}
4020c431d386SKemeng Shi 
4021f9e2d95aSKemeng Shi 	ext4_lock_group(sb, group);
4022f9e2d95aSKemeng Shi 	if (ext4_has_group_desc_csum(sb) &&
4023f9e2d95aSKemeng Shi 	    (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
4024f9e2d95aSKemeng Shi 		gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
4025f9e2d95aSKemeng Shi 		ext4_free_group_clusters_set(sb, gdp,
4026f9e2d95aSKemeng Shi 			ext4_free_clusters_after_init(sb, group, gdp));
4027f9e2d95aSKemeng Shi 	}
4028f9e2d95aSKemeng Shi 
4029c431d386SKemeng Shi 	if (flags & EXT4_MB_BITMAP_MARKED_CHECK) {
4030f9e2d95aSKemeng Shi 		already = 0;
4031f9e2d95aSKemeng Shi 		for (i = 0; i < len; i++)
4032f9e2d95aSKemeng Shi 			if (mb_test_bit(blkoff + i, bitmap_bh->b_data) ==
4033f9e2d95aSKemeng Shi 					state)
4034f9e2d95aSKemeng Shi 				already++;
4035f9e2d95aSKemeng Shi 		changed = len - already;
4036c431d386SKemeng Shi 	}
4037f9e2d95aSKemeng Shi 
4038f9e2d95aSKemeng Shi 	if (state) {
4039f9e2d95aSKemeng Shi 		mb_set_bits(bitmap_bh->b_data, blkoff, len);
4040f9e2d95aSKemeng Shi 		ext4_free_group_clusters_set(sb, gdp,
4041f9e2d95aSKemeng Shi 			ext4_free_group_clusters(sb, gdp) - changed);
4042f9e2d95aSKemeng Shi 	} else {
4043f9e2d95aSKemeng Shi 		mb_clear_bits(bitmap_bh->b_data, blkoff, len);
4044f9e2d95aSKemeng Shi 		ext4_free_group_clusters_set(sb, gdp,
4045f9e2d95aSKemeng Shi 			ext4_free_group_clusters(sb, gdp) + changed);
4046f9e2d95aSKemeng Shi 	}
4047f9e2d95aSKemeng Shi 
4048f9e2d95aSKemeng Shi 	ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
4049f9e2d95aSKemeng Shi 	ext4_group_desc_csum_set(sb, group, gdp);
4050f9e2d95aSKemeng Shi 	ext4_unlock_group(sb, group);
4051c431d386SKemeng Shi 	if (ret_changed)
4052c431d386SKemeng Shi 		*ret_changed = changed;
4053f9e2d95aSKemeng Shi 
4054f9e2d95aSKemeng Shi 	if (sbi->s_log_groups_per_flex) {
4055f9e2d95aSKemeng Shi 		ext4_group_t flex_group = ext4_flex_group(sbi, group);
4056f9e2d95aSKemeng Shi 		struct flex_groups *fg = sbi_array_rcu_deref(sbi,
4057f9e2d95aSKemeng Shi 					   s_flex_groups, flex_group);
4058f9e2d95aSKemeng Shi 
4059f9e2d95aSKemeng Shi 		if (state)
4060f9e2d95aSKemeng Shi 			atomic64_sub(changed, &fg->free_clusters);
4061f9e2d95aSKemeng Shi 		else
4062f9e2d95aSKemeng Shi 			atomic64_add(changed, &fg->free_clusters);
4063f9e2d95aSKemeng Shi 	}
4064f9e2d95aSKemeng Shi 
4065c431d386SKemeng Shi 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4066f9e2d95aSKemeng Shi 	if (err)
4067f9e2d95aSKemeng Shi 		goto out_err;
4068c431d386SKemeng Shi 	err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
4069f9e2d95aSKemeng Shi 	if (err)
4070f9e2d95aSKemeng Shi 		goto out_err;
4071f9e2d95aSKemeng Shi 
4072c431d386SKemeng Shi 	if (flags & EXT4_MB_SYNC_UPDATE) {
4073f9e2d95aSKemeng Shi 		sync_dirty_buffer(bitmap_bh);
4074f9e2d95aSKemeng Shi 		sync_dirty_buffer(gdp_bh);
4075c431d386SKemeng Shi 	}
4076f9e2d95aSKemeng Shi 
4077f9e2d95aSKemeng Shi out_err:
4078f9e2d95aSKemeng Shi 	brelse(bitmap_bh);
4079f9e2d95aSKemeng Shi 	return err;
4080f9e2d95aSKemeng Shi }
4081c9de560dSAlex Tomas 
4082c9de560dSAlex Tomas /*
408373b2c716SUwe Kleine-König  * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
4084c9de560dSAlex Tomas  * Returns 0 if success or error code
4085c9de560dSAlex Tomas  */
40864ddfef7bSEric Sandeen static noinline_for_stack int
40874ddfef7bSEric Sandeen ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
408853accfa9STheodore Ts'o 				handle_t *handle, unsigned int reserv_clstrs)
4089c9de560dSAlex Tomas {
4090c9de560dSAlex Tomas 	struct ext4_group_desc *gdp;
4091c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
4092c9de560dSAlex Tomas 	struct super_block *sb;
4093c9de560dSAlex Tomas 	ext4_fsblk_t block;
4094519deca0SAneesh Kumar K.V 	int err, len;
40952f94711bSKemeng Shi 	int flags = 0;
40962f94711bSKemeng Shi 	ext4_grpblk_t changed;
4097c9de560dSAlex Tomas 
4098c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
4099c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_len <= 0);
4100c9de560dSAlex Tomas 
4101c9de560dSAlex Tomas 	sb = ac->ac_sb;
4102c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
4103c9de560dSAlex Tomas 
41042f94711bSKemeng Shi 	gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, NULL);
4105c9de560dSAlex Tomas 	if (!gdp)
41062f94711bSKemeng Shi 		return -EIO;
4107a9df9a49STheodore Ts'o 	ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
4108021b65bbSTheodore Ts'o 			ext4_free_group_clusters(sb, gdp));
410903cddb80SAneesh Kumar K.V 
4110bda00de7SAkinobu Mita 	block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
411153accfa9STheodore Ts'o 	len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4112ce9f24ccSJan Kara 	if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
411312062dddSEric Sandeen 		ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
41141084f252STheodore Ts'o 			   "fs metadata", block, block+len);
4115519deca0SAneesh Kumar K.V 		/* File system mounted not to panic on error
4116554a5cccSVegard Nossum 		 * Fix the bitmap and return EFSCORRUPTED
4117519deca0SAneesh Kumar K.V 		 * We leak some of the blocks here.
4118519deca0SAneesh Kumar K.V 		 */
41192f94711bSKemeng Shi 		err = ext4_mb_mark_context(handle, sb, true,
41202f94711bSKemeng Shi 					   ac->ac_b_ex.fe_group,
41212f94711bSKemeng Shi 					   ac->ac_b_ex.fe_start,
41222f94711bSKemeng Shi 					   ac->ac_b_ex.fe_len,
41232f94711bSKemeng Shi 					   0, NULL);
4124519deca0SAneesh Kumar K.V 		if (!err)
4125554a5cccSVegard Nossum 			err = -EFSCORRUPTED;
41262f94711bSKemeng Shi 		return err;
4127c9de560dSAlex Tomas 	}
4128955ce5f5SAneesh Kumar K.V 
4129c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
41302f94711bSKemeng Shi 	flags |= EXT4_MB_BITMAP_MARKED_CHECK;
4131c9de560dSAlex Tomas #endif
41322f94711bSKemeng Shi 	err = ext4_mb_mark_context(handle, sb, true, ac->ac_b_ex.fe_group,
41332f94711bSKemeng Shi 				   ac->ac_b_ex.fe_start, ac->ac_b_ex.fe_len,
41342f94711bSKemeng Shi 				   flags, &changed);
4135955ce5f5SAneesh Kumar K.V 
41362f94711bSKemeng Shi 	if (err && changed == 0)
41372f94711bSKemeng Shi 		return err;
41382f94711bSKemeng Shi 
41392f94711bSKemeng Shi #ifdef AGGRESSIVE_CHECK
41402f94711bSKemeng Shi 	BUG_ON(changed != ac->ac_b_ex.fe_len);
41412f94711bSKemeng Shi #endif
414257042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
4143d2a17637SMingming Cao 	/*
41446bc6e63fSAneesh Kumar K.V 	 * Now reduce the dirty block count also. Should not go negative
4145d2a17637SMingming Cao 	 */
41466bc6e63fSAneesh Kumar K.V 	if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
41476bc6e63fSAneesh Kumar K.V 		/* release all the reserved blocks if non delalloc */
414857042651STheodore Ts'o 		percpu_counter_sub(&sbi->s_dirtyclusters_counter,
414957042651STheodore Ts'o 				   reserv_clstrs);
4150c9de560dSAlex Tomas 
4151c9de560dSAlex Tomas 	return err;
4152c9de560dSAlex Tomas }
4153c9de560dSAlex Tomas 
4154c9de560dSAlex Tomas /*
41558016e29fSHarshad Shirwadkar  * Idempotent helper for Ext4 fast commit replay path to set the state of
41568016e29fSHarshad Shirwadkar  * blocks in bitmaps and update counters.
41578016e29fSHarshad Shirwadkar  */
41588016e29fSHarshad Shirwadkar void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
4159d2f7cf40SKemeng Shi 		     int len, bool state)
41608016e29fSHarshad Shirwadkar {
41618016e29fSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
41628016e29fSHarshad Shirwadkar 	ext4_group_t group;
41638016e29fSHarshad Shirwadkar 	ext4_grpblk_t blkoff;
4164f9e2d95aSKemeng Shi 	int err = 0;
4165f9e2d95aSKemeng Shi 	unsigned int clen, thisgrp_len;
41668016e29fSHarshad Shirwadkar 
4167bfdc502aSRitesh Harjani 	while (len > 0) {
41688016e29fSHarshad Shirwadkar 		ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
4169bfdc502aSRitesh Harjani 
4170bfdc502aSRitesh Harjani 		/*
4171bfdc502aSRitesh Harjani 		 * Check to see if we are freeing blocks across a group
4172bfdc502aSRitesh Harjani 		 * boundary.
4173bfdc502aSRitesh Harjani 		 * In case of flex_bg, this can happen that (block, len) may
4174bfdc502aSRitesh Harjani 		 * span across more than one group. In that case we need to
4175bfdc502aSRitesh Harjani 		 * get the corresponding group metadata to work with.
4176bfdc502aSRitesh Harjani 		 * For this we have goto again loop.
4177bfdc502aSRitesh Harjani 		 */
4178bfdc502aSRitesh Harjani 		thisgrp_len = min_t(unsigned int, (unsigned int)len,
4179bfdc502aSRitesh Harjani 			EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
4180bfdc502aSRitesh Harjani 		clen = EXT4_NUM_B2C(sbi, thisgrp_len);
4181bfdc502aSRitesh Harjani 
41828c91c579SRitesh Harjani 		if (!ext4_sb_block_valid(sb, NULL, block, thisgrp_len)) {
41838c91c579SRitesh Harjani 			ext4_error(sb, "Marking blocks in system zone - "
41848c91c579SRitesh Harjani 				   "Block = %llu, len = %u",
41858c91c579SRitesh Harjani 				   block, thisgrp_len);
41868c91c579SRitesh Harjani 			break;
41878c91c579SRitesh Harjani 		}
41888c91c579SRitesh Harjani 
4189c431d386SKemeng Shi 		err = ext4_mb_mark_context(NULL, sb, state,
4190c431d386SKemeng Shi 					   group, blkoff, clen,
4191c431d386SKemeng Shi 					   EXT4_MB_BITMAP_MARKED_CHECK |
4192c431d386SKemeng Shi 					   EXT4_MB_SYNC_UPDATE,
4193c431d386SKemeng Shi 					   NULL);
4194bfdc502aSRitesh Harjani 		if (err)
4195bfdc502aSRitesh Harjani 			break;
41968016e29fSHarshad Shirwadkar 
4197bfdc502aSRitesh Harjani 		block += thisgrp_len;
4198bfdc502aSRitesh Harjani 		len -= thisgrp_len;
4199bfdc502aSRitesh Harjani 		BUG_ON(len < 0);
4200bfdc502aSRitesh Harjani 	}
42018016e29fSHarshad Shirwadkar }
42028016e29fSHarshad Shirwadkar 
42038016e29fSHarshad Shirwadkar /*
4204c9de560dSAlex Tomas  * here we normalize request for locality group
4205d7a1fee1SDan Ehrenberg  * Group request are normalized to s_mb_group_prealloc, which goes to
4206d7a1fee1SDan Ehrenberg  * s_strip if we set the same via mount option.
4207d7a1fee1SDan Ehrenberg  * s_mb_group_prealloc can be configured via
4208b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_group_prealloc
4209c9de560dSAlex Tomas  *
4210c9de560dSAlex Tomas  * XXX: should we try to preallocate more than the group has now?
4211c9de560dSAlex Tomas  */
4212c9de560dSAlex Tomas static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
4213c9de560dSAlex Tomas {
4214c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
4215c9de560dSAlex Tomas 	struct ext4_locality_group *lg = ac->ac_lg;
4216c9de560dSAlex Tomas 
4217c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
4218c9de560dSAlex Tomas 	ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
4219d3df1453SRitesh Harjani 	mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
4220c9de560dSAlex Tomas }
4221c9de560dSAlex Tomas 
422238727786SOjaswin Mujoo /*
422338727786SOjaswin Mujoo  * This function returns the next element to look at during inode
422438727786SOjaswin Mujoo  * PA rbtree walk. We assume that we have held the inode PA rbtree lock
422538727786SOjaswin Mujoo  * (ei->i_prealloc_lock)
422638727786SOjaswin Mujoo  *
422738727786SOjaswin Mujoo  * new_start	The start of the range we want to compare
422838727786SOjaswin Mujoo  * cur_start	The existing start that we are comparing against
422938727786SOjaswin Mujoo  * node	The node of the rb_tree
423038727786SOjaswin Mujoo  */
423138727786SOjaswin Mujoo static inline struct rb_node*
423238727786SOjaswin Mujoo ext4_mb_pa_rb_next_iter(ext4_lblk_t new_start, ext4_lblk_t cur_start, struct rb_node *node)
423338727786SOjaswin Mujoo {
423438727786SOjaswin Mujoo 	if (new_start < cur_start)
423538727786SOjaswin Mujoo 		return node->rb_left;
423638727786SOjaswin Mujoo 	else
423738727786SOjaswin Mujoo 		return node->rb_right;
423838727786SOjaswin Mujoo }
423938727786SOjaswin Mujoo 
42407692094aSOjaswin Mujoo static inline void
42417692094aSOjaswin Mujoo ext4_mb_pa_assert_overlap(struct ext4_allocation_context *ac,
4242bedc5d34SBaokun Li 			  ext4_lblk_t start, loff_t end)
42437692094aSOjaswin Mujoo {
42447692094aSOjaswin Mujoo 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
42457692094aSOjaswin Mujoo 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
42467692094aSOjaswin Mujoo 	struct ext4_prealloc_space *tmp_pa;
4247bedc5d34SBaokun Li 	ext4_lblk_t tmp_pa_start;
4248bedc5d34SBaokun Li 	loff_t tmp_pa_end;
424938727786SOjaswin Mujoo 	struct rb_node *iter;
42507692094aSOjaswin Mujoo 
425138727786SOjaswin Mujoo 	read_lock(&ei->i_prealloc_lock);
425238727786SOjaswin Mujoo 	for (iter = ei->i_prealloc_node.rb_node; iter;
425338727786SOjaswin Mujoo 	     iter = ext4_mb_pa_rb_next_iter(start, tmp_pa_start, iter)) {
425438727786SOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
425538727786SOjaswin Mujoo 				  pa_node.inode_node);
42567692094aSOjaswin Mujoo 		tmp_pa_start = tmp_pa->pa_lstart;
4257bedc5d34SBaokun Li 		tmp_pa_end = pa_logical_end(sbi, tmp_pa);
42587692094aSOjaswin Mujoo 
425938727786SOjaswin Mujoo 		spin_lock(&tmp_pa->pa_lock);
426038727786SOjaswin Mujoo 		if (tmp_pa->pa_deleted == 0)
42617692094aSOjaswin Mujoo 			BUG_ON(!(start >= tmp_pa_end || end <= tmp_pa_start));
42627692094aSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
42637692094aSOjaswin Mujoo 	}
426438727786SOjaswin Mujoo 	read_unlock(&ei->i_prealloc_lock);
42657692094aSOjaswin Mujoo }
42667692094aSOjaswin Mujoo 
4267c9de560dSAlex Tomas /*
42680830344cSOjaswin Mujoo  * Given an allocation context "ac" and a range "start", "end", check
42690830344cSOjaswin Mujoo  * and adjust boundaries if the range overlaps with any of the existing
42700830344cSOjaswin Mujoo  * preallocatoins stored in the corresponding inode of the allocation context.
42710830344cSOjaswin Mujoo  *
42720830344cSOjaswin Mujoo  * Parameters:
42730830344cSOjaswin Mujoo  *	ac			allocation context
42740830344cSOjaswin Mujoo  *	start			start of the new range
42750830344cSOjaswin Mujoo  *	end			end of the new range
42760830344cSOjaswin Mujoo  */
42770830344cSOjaswin Mujoo static inline void
42780830344cSOjaswin Mujoo ext4_mb_pa_adjust_overlap(struct ext4_allocation_context *ac,
4279bedc5d34SBaokun Li 			  ext4_lblk_t *start, loff_t *end)
42800830344cSOjaswin Mujoo {
42810830344cSOjaswin Mujoo 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
42820830344cSOjaswin Mujoo 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
428338727786SOjaswin Mujoo 	struct ext4_prealloc_space *tmp_pa = NULL, *left_pa = NULL, *right_pa = NULL;
428438727786SOjaswin Mujoo 	struct rb_node *iter;
4285bedc5d34SBaokun Li 	ext4_lblk_t new_start, tmp_pa_start, right_pa_start = -1;
4286bedc5d34SBaokun Li 	loff_t new_end, tmp_pa_end, left_pa_end = -1;
42870830344cSOjaswin Mujoo 
42880830344cSOjaswin Mujoo 	new_start = *start;
42890830344cSOjaswin Mujoo 	new_end = *end;
42900830344cSOjaswin Mujoo 
429138727786SOjaswin Mujoo 	/*
429238727786SOjaswin Mujoo 	 * Adjust the normalized range so that it doesn't overlap with any
429338727786SOjaswin Mujoo 	 * existing preallocated blocks(PAs). Make sure to hold the rbtree lock
429438727786SOjaswin Mujoo 	 * so it doesn't change underneath us.
429538727786SOjaswin Mujoo 	 */
429638727786SOjaswin Mujoo 	read_lock(&ei->i_prealloc_lock);
42970830344cSOjaswin Mujoo 
429838727786SOjaswin Mujoo 	/* Step 1: find any one immediate neighboring PA of the normalized range */
429938727786SOjaswin Mujoo 	for (iter = ei->i_prealloc_node.rb_node; iter;
430038727786SOjaswin Mujoo 	     iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
430138727786SOjaswin Mujoo 					    tmp_pa_start, iter)) {
430238727786SOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
430338727786SOjaswin Mujoo 				  pa_node.inode_node);
43040830344cSOjaswin Mujoo 		tmp_pa_start = tmp_pa->pa_lstart;
4305bedc5d34SBaokun Li 		tmp_pa_end = pa_logical_end(sbi, tmp_pa);
43060830344cSOjaswin Mujoo 
43070830344cSOjaswin Mujoo 		/* PA must not overlap original request */
430838727786SOjaswin Mujoo 		spin_lock(&tmp_pa->pa_lock);
430938727786SOjaswin Mujoo 		if (tmp_pa->pa_deleted == 0)
43100830344cSOjaswin Mujoo 			BUG_ON(!(ac->ac_o_ex.fe_logical >= tmp_pa_end ||
43110830344cSOjaswin Mujoo 				 ac->ac_o_ex.fe_logical < tmp_pa_start));
43120830344cSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
43130830344cSOjaswin Mujoo 	}
43140830344cSOjaswin Mujoo 
431538727786SOjaswin Mujoo 	/*
431638727786SOjaswin Mujoo 	 * Step 2: check if the found PA is left or right neighbor and
431738727786SOjaswin Mujoo 	 * get the other neighbor
431838727786SOjaswin Mujoo 	 */
431938727786SOjaswin Mujoo 	if (tmp_pa) {
432038727786SOjaswin Mujoo 		if (tmp_pa->pa_lstart < ac->ac_o_ex.fe_logical) {
432138727786SOjaswin Mujoo 			struct rb_node *tmp;
432238727786SOjaswin Mujoo 
432338727786SOjaswin Mujoo 			left_pa = tmp_pa;
432438727786SOjaswin Mujoo 			tmp = rb_next(&left_pa->pa_node.inode_node);
432538727786SOjaswin Mujoo 			if (tmp) {
432638727786SOjaswin Mujoo 				right_pa = rb_entry(tmp,
432738727786SOjaswin Mujoo 						    struct ext4_prealloc_space,
432838727786SOjaswin Mujoo 						    pa_node.inode_node);
432938727786SOjaswin Mujoo 			}
433038727786SOjaswin Mujoo 		} else {
433138727786SOjaswin Mujoo 			struct rb_node *tmp;
433238727786SOjaswin Mujoo 
433338727786SOjaswin Mujoo 			right_pa = tmp_pa;
433438727786SOjaswin Mujoo 			tmp = rb_prev(&right_pa->pa_node.inode_node);
433538727786SOjaswin Mujoo 			if (tmp) {
433638727786SOjaswin Mujoo 				left_pa = rb_entry(tmp,
433738727786SOjaswin Mujoo 						   struct ext4_prealloc_space,
433838727786SOjaswin Mujoo 						   pa_node.inode_node);
433938727786SOjaswin Mujoo 			}
434038727786SOjaswin Mujoo 		}
434138727786SOjaswin Mujoo 	}
434238727786SOjaswin Mujoo 
434338727786SOjaswin Mujoo 	/* Step 3: get the non deleted neighbors */
434438727786SOjaswin Mujoo 	if (left_pa) {
434538727786SOjaswin Mujoo 		for (iter = &left_pa->pa_node.inode_node;;
434638727786SOjaswin Mujoo 		     iter = rb_prev(iter)) {
434738727786SOjaswin Mujoo 			if (!iter) {
434838727786SOjaswin Mujoo 				left_pa = NULL;
434938727786SOjaswin Mujoo 				break;
435038727786SOjaswin Mujoo 			}
435138727786SOjaswin Mujoo 
435238727786SOjaswin Mujoo 			tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
435338727786SOjaswin Mujoo 					  pa_node.inode_node);
435438727786SOjaswin Mujoo 			left_pa = tmp_pa;
435538727786SOjaswin Mujoo 			spin_lock(&tmp_pa->pa_lock);
435638727786SOjaswin Mujoo 			if (tmp_pa->pa_deleted == 0) {
435738727786SOjaswin Mujoo 				spin_unlock(&tmp_pa->pa_lock);
435838727786SOjaswin Mujoo 				break;
43590830344cSOjaswin Mujoo 			}
43600830344cSOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
43610830344cSOjaswin Mujoo 		}
436238727786SOjaswin Mujoo 	}
436338727786SOjaswin Mujoo 
436438727786SOjaswin Mujoo 	if (right_pa) {
436538727786SOjaswin Mujoo 		for (iter = &right_pa->pa_node.inode_node;;
436638727786SOjaswin Mujoo 		     iter = rb_next(iter)) {
436738727786SOjaswin Mujoo 			if (!iter) {
436838727786SOjaswin Mujoo 				right_pa = NULL;
436938727786SOjaswin Mujoo 				break;
437038727786SOjaswin Mujoo 			}
437138727786SOjaswin Mujoo 
437238727786SOjaswin Mujoo 			tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
437338727786SOjaswin Mujoo 					  pa_node.inode_node);
437438727786SOjaswin Mujoo 			right_pa = tmp_pa;
437538727786SOjaswin Mujoo 			spin_lock(&tmp_pa->pa_lock);
437638727786SOjaswin Mujoo 			if (tmp_pa->pa_deleted == 0) {
437738727786SOjaswin Mujoo 				spin_unlock(&tmp_pa->pa_lock);
437838727786SOjaswin Mujoo 				break;
437938727786SOjaswin Mujoo 			}
438038727786SOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
438138727786SOjaswin Mujoo 		}
438238727786SOjaswin Mujoo 	}
438338727786SOjaswin Mujoo 
438438727786SOjaswin Mujoo 	if (left_pa) {
4385bedc5d34SBaokun Li 		left_pa_end = pa_logical_end(sbi, left_pa);
438638727786SOjaswin Mujoo 		BUG_ON(left_pa_end > ac->ac_o_ex.fe_logical);
438738727786SOjaswin Mujoo 	}
438838727786SOjaswin Mujoo 
438938727786SOjaswin Mujoo 	if (right_pa) {
439038727786SOjaswin Mujoo 		right_pa_start = right_pa->pa_lstart;
439138727786SOjaswin Mujoo 		BUG_ON(right_pa_start <= ac->ac_o_ex.fe_logical);
439238727786SOjaswin Mujoo 	}
439338727786SOjaswin Mujoo 
439438727786SOjaswin Mujoo 	/* Step 4: trim our normalized range to not overlap with the neighbors */
439538727786SOjaswin Mujoo 	if (left_pa) {
439638727786SOjaswin Mujoo 		if (left_pa_end > new_start)
439738727786SOjaswin Mujoo 			new_start = left_pa_end;
439838727786SOjaswin Mujoo 	}
439938727786SOjaswin Mujoo 
440038727786SOjaswin Mujoo 	if (right_pa) {
440138727786SOjaswin Mujoo 		if (right_pa_start < new_end)
440238727786SOjaswin Mujoo 			new_end = right_pa_start;
440338727786SOjaswin Mujoo 	}
440438727786SOjaswin Mujoo 	read_unlock(&ei->i_prealloc_lock);
44050830344cSOjaswin Mujoo 
44060830344cSOjaswin Mujoo 	/* XXX: extra loop to check we really don't overlap preallocations */
44070830344cSOjaswin Mujoo 	ext4_mb_pa_assert_overlap(ac, new_start, new_end);
44080830344cSOjaswin Mujoo 
44090830344cSOjaswin Mujoo 	*start = new_start;
44100830344cSOjaswin Mujoo 	*end = new_end;
44110830344cSOjaswin Mujoo }
44120830344cSOjaswin Mujoo 
44130830344cSOjaswin Mujoo /*
4414c9de560dSAlex Tomas  * Normalization means making request better in terms of
4415c9de560dSAlex Tomas  * size and alignment
4416c9de560dSAlex Tomas  */
44174ddfef7bSEric Sandeen static noinline_for_stack void
44184ddfef7bSEric Sandeen ext4_mb_normalize_request(struct ext4_allocation_context *ac,
4419c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
4420c9de560dSAlex Tomas {
442153accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4422b07ffe69SKemeng Shi 	struct ext4_super_block *es = sbi->s_es;
4423c9de560dSAlex Tomas 	int bsbits, max;
4424bedc5d34SBaokun Li 	loff_t size, start_off, end;
44251592d2c5SCurt Wohlgemuth 	loff_t orig_size __maybe_unused;
44265a0790c2SAndi Kleen 	ext4_lblk_t start;
4427c9de560dSAlex Tomas 
4428c9de560dSAlex Tomas 	/* do normalize only data requests, metadata requests
4429c9de560dSAlex Tomas 	   do not need preallocation */
4430c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4431c9de560dSAlex Tomas 		return;
4432c9de560dSAlex Tomas 
4433c9de560dSAlex Tomas 	/* sometime caller may want exact blocks */
4434c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4435c9de560dSAlex Tomas 		return;
4436c9de560dSAlex Tomas 
4437c9de560dSAlex Tomas 	/* caller may indicate that preallocation isn't
4438c9de560dSAlex Tomas 	 * required (it's a tail, for example) */
4439c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
4440c9de560dSAlex Tomas 		return;
4441c9de560dSAlex Tomas 
4442c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
4443c9de560dSAlex Tomas 		ext4_mb_normalize_group_request(ac);
4444c9de560dSAlex Tomas 		return ;
4445c9de560dSAlex Tomas 	}
4446c9de560dSAlex Tomas 
4447c9de560dSAlex Tomas 	bsbits = ac->ac_sb->s_blocksize_bits;
4448c9de560dSAlex Tomas 
4449c9de560dSAlex Tomas 	/* first, let's learn actual file size
4450c9de560dSAlex Tomas 	 * given current request is allocated */
445143bbddc0SBaokun Li 	size = extent_logical_end(sbi, &ac->ac_o_ex);
4452c9de560dSAlex Tomas 	size = size << bsbits;
4453c9de560dSAlex Tomas 	if (size < i_size_read(ac->ac_inode))
4454c9de560dSAlex Tomas 		size = i_size_read(ac->ac_inode);
44555a0790c2SAndi Kleen 	orig_size = size;
4456c9de560dSAlex Tomas 
44571930479cSValerie Clement 	/* max size of free chunks */
44581930479cSValerie Clement 	max = 2 << bsbits;
4459c9de560dSAlex Tomas 
44601930479cSValerie Clement #define NRL_CHECK_SIZE(req, size, max, chunk_size)	\
44611930479cSValerie Clement 		(req <= (size) || max <= (chunk_size))
4462c9de560dSAlex Tomas 
4463c9de560dSAlex Tomas 	/* first, try to predict filesize */
4464c9de560dSAlex Tomas 	/* XXX: should this table be tunable? */
4465c9de560dSAlex Tomas 	start_off = 0;
4466c9de560dSAlex Tomas 	if (size <= 16 * 1024) {
4467c9de560dSAlex Tomas 		size = 16 * 1024;
4468c9de560dSAlex Tomas 	} else if (size <= 32 * 1024) {
4469c9de560dSAlex Tomas 		size = 32 * 1024;
4470c9de560dSAlex Tomas 	} else if (size <= 64 * 1024) {
4471c9de560dSAlex Tomas 		size = 64 * 1024;
4472c9de560dSAlex Tomas 	} else if (size <= 128 * 1024) {
4473c9de560dSAlex Tomas 		size = 128 * 1024;
4474c9de560dSAlex Tomas 	} else if (size <= 256 * 1024) {
4475c9de560dSAlex Tomas 		size = 256 * 1024;
4476c9de560dSAlex Tomas 	} else if (size <= 512 * 1024) {
4477c9de560dSAlex Tomas 		size = 512 * 1024;
4478c9de560dSAlex Tomas 	} else if (size <= 1024 * 1024) {
4479c9de560dSAlex Tomas 		size = 1024 * 1024;
44801930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
4481c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
44821930479cSValerie Clement 						(21 - bsbits)) << 21;
44831930479cSValerie Clement 		size = 2 * 1024 * 1024;
44841930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
4485c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4486c9de560dSAlex Tomas 							(22 - bsbits)) << 22;
4487c9de560dSAlex Tomas 		size = 4 * 1024 * 1024;
4488b3916da0SKemeng Shi 	} else if (NRL_CHECK_SIZE(EXT4_C2B(sbi, ac->ac_o_ex.fe_len),
44891930479cSValerie Clement 					(8<<20)>>bsbits, max, 8 * 1024)) {
4490c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4491c9de560dSAlex Tomas 							(23 - bsbits)) << 23;
4492c9de560dSAlex Tomas 		size = 8 * 1024 * 1024;
4493c9de560dSAlex Tomas 	} else {
4494c9de560dSAlex Tomas 		start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
449591a48aafSKemeng Shi 		size	  = (loff_t) EXT4_C2B(sbi,
4496b27b1535SXiaoguang Wang 					      ac->ac_o_ex.fe_len) << bsbits;
4497c9de560dSAlex Tomas 	}
44985a0790c2SAndi Kleen 	size = size >> bsbits;
44995a0790c2SAndi Kleen 	start = start_off >> bsbits;
4500c9de560dSAlex Tomas 
4501a08f789dSBaokun Li 	/*
4502a08f789dSBaokun Li 	 * For tiny groups (smaller than 8MB) the chosen allocation
4503a08f789dSBaokun Li 	 * alignment may be larger than group size. Make sure the
4504a08f789dSBaokun Li 	 * alignment does not move allocation to a different group which
4505a08f789dSBaokun Li 	 * makes mballoc fail assertions later.
4506a08f789dSBaokun Li 	 */
4507a08f789dSBaokun Li 	start = max(start, rounddown(ac->ac_o_ex.fe_logical,
4508a08f789dSBaokun Li 			(ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
4509a08f789dSBaokun Li 
45102dcf5fdeSBaokun Li 	/* avoid unnecessary preallocation that may trigger assertions */
45112dcf5fdeSBaokun Li 	if (start + size > EXT_MAX_BLOCKS)
45122dcf5fdeSBaokun Li 		size = EXT_MAX_BLOCKS - start;
45132dcf5fdeSBaokun Li 
4514c9de560dSAlex Tomas 	/* don't cover already allocated blocks in selected range */
4515c9de560dSAlex Tomas 	if (ar->pleft && start <= ar->lleft) {
4516c9de560dSAlex Tomas 		size -= ar->lleft + 1 - start;
4517c9de560dSAlex Tomas 		start = ar->lleft + 1;
4518c9de560dSAlex Tomas 	}
4519c9de560dSAlex Tomas 	if (ar->pright && start + size - 1 >= ar->lright)
4520c9de560dSAlex Tomas 		size -= start + size - ar->lright;
4521c9de560dSAlex Tomas 
4522cd648b8aSJan Kara 	/*
4523cd648b8aSJan Kara 	 * Trim allocation request for filesystems with artificially small
4524cd648b8aSJan Kara 	 * groups.
4525cd648b8aSJan Kara 	 */
4526cd648b8aSJan Kara 	if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
4527cd648b8aSJan Kara 		size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
4528cd648b8aSJan Kara 
4529c9de560dSAlex Tomas 	end = start + size;
4530c9de560dSAlex Tomas 
45310830344cSOjaswin Mujoo 	ext4_mb_pa_adjust_overlap(ac, &start, &end);
4532c9de560dSAlex Tomas 
4533c9de560dSAlex Tomas 	size = end - start;
4534c9de560dSAlex Tomas 
4535cf4ff938SBaokun Li 	/*
4536cf4ff938SBaokun Li 	 * In this function "start" and "size" are normalized for better
4537cf4ff938SBaokun Li 	 * alignment and length such that we could preallocate more blocks.
4538cf4ff938SBaokun Li 	 * This normalization is done such that original request of
4539cf4ff938SBaokun Li 	 * ac->ac_o_ex.fe_logical & fe_len should always lie within "start" and
4540cf4ff938SBaokun Li 	 * "size" boundaries.
4541cf4ff938SBaokun Li 	 * (Note fe_len can be relaxed since FS block allocation API does not
4542cf4ff938SBaokun Li 	 * provide gurantee on number of contiguous blocks allocation since that
4543cf4ff938SBaokun Li 	 * depends upon free space left, etc).
4544cf4ff938SBaokun Li 	 * In case of inode pa, later we use the allocated blocks
45451221b235SKemeng Shi 	 * [pa_pstart + fe_logical - pa_lstart, fe_len/size] from the preallocated
4546cf4ff938SBaokun Li 	 * range of goal/best blocks [start, size] to put it at the
4547cf4ff938SBaokun Li 	 * ac_o_ex.fe_logical extent of this inode.
4548cf4ff938SBaokun Li 	 * (See ext4_mb_use_inode_pa() for more details)
4549cf4ff938SBaokun Li 	 */
4550cf4ff938SBaokun Li 	if (start + size <= ac->ac_o_ex.fe_logical ||
4551c9de560dSAlex Tomas 			start > ac->ac_o_ex.fe_logical) {
45529d8b9ec4STheodore Ts'o 		ext4_msg(ac->ac_sb, KERN_ERR,
45539d8b9ec4STheodore Ts'o 			 "start %lu, size %lu, fe_logical %lu",
4554c9de560dSAlex Tomas 			 (unsigned long) start, (unsigned long) size,
4555c9de560dSAlex Tomas 			 (unsigned long) ac->ac_o_ex.fe_logical);
4556dfe076c1SDmitry Monakhov 		BUG();
4557c9de560dSAlex Tomas 	}
4558b5b60778SMaurizio Lombardi 	BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
4559c9de560dSAlex Tomas 
4560c9de560dSAlex Tomas 	/* now prepare goal request */
4561c9de560dSAlex Tomas 
4562c9de560dSAlex Tomas 	/* XXX: is it better to align blocks WRT to logical
4563c9de560dSAlex Tomas 	 * placement or satisfy big request as is */
4564c9de560dSAlex Tomas 	ac->ac_g_ex.fe_logical = start;
456553accfa9STheodore Ts'o 	ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
45667e170922SOjaswin Mujoo 	ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
4567c9de560dSAlex Tomas 
4568c9de560dSAlex Tomas 	/* define goal start in order to merge */
4569b07ffe69SKemeng Shi 	if (ar->pright && (ar->lright == (start + size)) &&
4570b07ffe69SKemeng Shi 	    ar->pright >= size &&
4571b07ffe69SKemeng Shi 	    ar->pright - size >= le32_to_cpu(es->s_first_data_block)) {
4572c9de560dSAlex Tomas 		/* merge to the right */
4573c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
4574b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_group,
4575b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_start);
4576c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4577c9de560dSAlex Tomas 	}
4578b07ffe69SKemeng Shi 	if (ar->pleft && (ar->lleft + 1 == start) &&
4579b07ffe69SKemeng Shi 	    ar->pleft + 1 < ext4_blocks_count(es)) {
4580c9de560dSAlex Tomas 		/* merge to the left */
4581c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
4582b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_group,
4583b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_start);
4584c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4585c9de560dSAlex Tomas 	}
4586c9de560dSAlex Tomas 
4587d3df1453SRitesh Harjani 	mb_debug(ac->ac_sb, "goal: %lld(was %lld) blocks at %u\n", size,
4588d3df1453SRitesh Harjani 		 orig_size, start);
4589c9de560dSAlex Tomas }
4590c9de560dSAlex Tomas 
4591c9de560dSAlex Tomas static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
4592c9de560dSAlex Tomas {
4593c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4594c9de560dSAlex Tomas 
4595a6c75eafSHarshad Shirwadkar 	if (sbi->s_mb_stats && ac->ac_g_ex.fe_len >= 1) {
4596c9de560dSAlex Tomas 		atomic_inc(&sbi->s_bal_reqs);
4597c9de560dSAlex Tomas 		atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
4598291dae47SCurt Wohlgemuth 		if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
4599c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_success);
4600fdd9a009SOjaswin Mujoo 
4601c9de560dSAlex Tomas 		atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
4602fdd9a009SOjaswin Mujoo 		for (int i=0; i<EXT4_MB_NUM_CRS; i++) {
4603fdd9a009SOjaswin Mujoo 			atomic_add(ac->ac_cX_found[i], &sbi->s_bal_cX_ex_scanned[i]);
4604fdd9a009SOjaswin Mujoo 		}
4605fdd9a009SOjaswin Mujoo 
4606a6c75eafSHarshad Shirwadkar 		atomic_add(ac->ac_groups_scanned, &sbi->s_bal_groups_scanned);
4607c9de560dSAlex Tomas 		if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
4608c9de560dSAlex Tomas 				ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
4609c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_goals);
46107e170922SOjaswin Mujoo 		/* did we allocate as much as normalizer originally wanted? */
46117e170922SOjaswin Mujoo 		if (ac->ac_f_ex.fe_len == ac->ac_orig_goal_len)
46123ef5d263SOjaswin Mujoo 			atomic_inc(&sbi->s_bal_len_goals);
46137e170922SOjaswin Mujoo 
4614c9de560dSAlex Tomas 		if (ac->ac_found > sbi->s_mb_max_to_scan)
4615c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_breaks);
4616c9de560dSAlex Tomas 	}
4617c9de560dSAlex Tomas 
4618296c355cSTheodore Ts'o 	if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
4619296c355cSTheodore Ts'o 		trace_ext4_mballoc_alloc(ac);
4620296c355cSTheodore Ts'o 	else
4621296c355cSTheodore Ts'o 		trace_ext4_mballoc_prealloc(ac);
4622c9de560dSAlex Tomas }
4623c9de560dSAlex Tomas 
4624c9de560dSAlex Tomas /*
4625b844167eSCurt Wohlgemuth  * Called on failure; free up any blocks from the inode PA for this
4626b844167eSCurt Wohlgemuth  * context.  We don't need this for MB_GROUP_PA because we only change
4627b844167eSCurt Wohlgemuth  * pa_free in ext4_mb_release_context(), but on failure, we've already
4628b844167eSCurt Wohlgemuth  * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
4629b844167eSCurt Wohlgemuth  */
4630b844167eSCurt Wohlgemuth static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
4631b844167eSCurt Wohlgemuth {
4632b844167eSCurt Wohlgemuth 	struct ext4_prealloc_space *pa = ac->ac_pa;
463386f0afd4STheodore Ts'o 	struct ext4_buddy e4b;
463486f0afd4STheodore Ts'o 	int err;
4635b844167eSCurt Wohlgemuth 
463686f0afd4STheodore Ts'o 	if (pa == NULL) {
4637c99d1e6eSTheodore Ts'o 		if (ac->ac_f_ex.fe_len == 0)
4638c99d1e6eSTheodore Ts'o 			return;
463986f0afd4STheodore Ts'o 		err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
464019b8b035STheodore Ts'o 		if (WARN_RATELIMIT(err,
464119b8b035STheodore Ts'o 				   "ext4: mb_load_buddy failed (%d)", err))
464286f0afd4STheodore Ts'o 			/*
464386f0afd4STheodore Ts'o 			 * This should never happen since we pin the
464486f0afd4STheodore Ts'o 			 * pages in the ext4_allocation_context so
464586f0afd4STheodore Ts'o 			 * ext4_mb_load_buddy() should never fail.
464686f0afd4STheodore Ts'o 			 */
464786f0afd4STheodore Ts'o 			return;
464886f0afd4STheodore Ts'o 		ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
464986f0afd4STheodore Ts'o 		mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
465086f0afd4STheodore Ts'o 			       ac->ac_f_ex.fe_len);
465186f0afd4STheodore Ts'o 		ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
4652c99d1e6eSTheodore Ts'o 		ext4_mb_unload_buddy(&e4b);
465386f0afd4STheodore Ts'o 		return;
465486f0afd4STheodore Ts'o 	}
465536cb0f52SKemeng Shi 	if (pa->pa_type == MB_INODE_PA) {
465636cb0f52SKemeng Shi 		spin_lock(&pa->pa_lock);
4657400db9d3SZheng Liu 		pa->pa_free += ac->ac_b_ex.fe_len;
465836cb0f52SKemeng Shi 		spin_unlock(&pa->pa_lock);
465936cb0f52SKemeng Shi 	}
4660b844167eSCurt Wohlgemuth }
4661b844167eSCurt Wohlgemuth 
4662b844167eSCurt Wohlgemuth /*
4663c9de560dSAlex Tomas  * use blocks preallocated to inode
4664c9de560dSAlex Tomas  */
4665c9de560dSAlex Tomas static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
4666c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
4667c9de560dSAlex Tomas {
466853accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4669c9de560dSAlex Tomas 	ext4_fsblk_t start;
4670c9de560dSAlex Tomas 	ext4_fsblk_t end;
4671c9de560dSAlex Tomas 	int len;
4672c9de560dSAlex Tomas 
4673c9de560dSAlex Tomas 	/* found preallocated blocks, use them */
4674c9de560dSAlex Tomas 	start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
467553accfa9STheodore Ts'o 	end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
467653accfa9STheodore Ts'o 		  start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
467753accfa9STheodore Ts'o 	len = EXT4_NUM_B2C(sbi, end - start);
4678c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
4679c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
4680c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
4681c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
4682c9de560dSAlex Tomas 	ac->ac_pa = pa;
4683c9de560dSAlex Tomas 
4684c9de560dSAlex Tomas 	BUG_ON(start < pa->pa_pstart);
468553accfa9STheodore Ts'o 	BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
4686c9de560dSAlex Tomas 	BUG_ON(pa->pa_free < len);
468793cdf49fSOjaswin Mujoo 	BUG_ON(ac->ac_b_ex.fe_len <= 0);
4688c9de560dSAlex Tomas 	pa->pa_free -= len;
4689c9de560dSAlex Tomas 
4690d3df1453SRitesh Harjani 	mb_debug(ac->ac_sb, "use %llu/%d from inode pa %p\n", start, len, pa);
4691c9de560dSAlex Tomas }
4692c9de560dSAlex Tomas 
4693c9de560dSAlex Tomas /*
4694c9de560dSAlex Tomas  * use blocks preallocated to locality group
4695c9de560dSAlex Tomas  */
4696c9de560dSAlex Tomas static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
4697c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
4698c9de560dSAlex Tomas {
469903cddb80SAneesh Kumar K.V 	unsigned int len = ac->ac_o_ex.fe_len;
47006be2ded1SAneesh Kumar K.V 
4701c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
4702c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_group,
4703c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
4704c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
4705c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
4706c9de560dSAlex Tomas 	ac->ac_pa = pa;
4707c9de560dSAlex Tomas 
47081221b235SKemeng Shi 	/* we don't correct pa_pstart or pa_len here to avoid
470926346ff6SAneesh Kumar K.V 	 * possible race when the group is being loaded concurrently
4710c9de560dSAlex Tomas 	 * instead we correct pa later, after blocks are marked
471126346ff6SAneesh Kumar K.V 	 * in on-disk bitmap -- see ext4_mb_release_context()
471226346ff6SAneesh Kumar K.V 	 * Other CPUs are prevented from allocating from this pa by lg_mutex
4713c9de560dSAlex Tomas 	 */
4714d3df1453SRitesh Harjani 	mb_debug(ac->ac_sb, "use %u/%u from group pa %p\n",
47151afdc588SKemeng Shi 		 pa->pa_lstart, len, pa);
4716c9de560dSAlex Tomas }
4717c9de560dSAlex Tomas 
4718c9de560dSAlex Tomas /*
47195e745b04SAneesh Kumar K.V  * Return the prealloc space that have minimal distance
47205e745b04SAneesh Kumar K.V  * from the goal block. @cpa is the prealloc
47215e745b04SAneesh Kumar K.V  * space that is having currently known minimal distance
47225e745b04SAneesh Kumar K.V  * from the goal block.
47235e745b04SAneesh Kumar K.V  */
47245e745b04SAneesh Kumar K.V static struct ext4_prealloc_space *
47255e745b04SAneesh Kumar K.V ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
47265e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *pa,
47275e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *cpa)
47285e745b04SAneesh Kumar K.V {
47295e745b04SAneesh Kumar K.V 	ext4_fsblk_t cur_distance, new_distance;
47305e745b04SAneesh Kumar K.V 
47315e745b04SAneesh Kumar K.V 	if (cpa == NULL) {
47325e745b04SAneesh Kumar K.V 		atomic_inc(&pa->pa_count);
47335e745b04SAneesh Kumar K.V 		return pa;
47345e745b04SAneesh Kumar K.V 	}
473579211c8eSAndrew Morton 	cur_distance = abs(goal_block - cpa->pa_pstart);
473679211c8eSAndrew Morton 	new_distance = abs(goal_block - pa->pa_pstart);
47375e745b04SAneesh Kumar K.V 
47385a54b2f1SColy Li 	if (cur_distance <= new_distance)
47395e745b04SAneesh Kumar K.V 		return cpa;
47405e745b04SAneesh Kumar K.V 
47415e745b04SAneesh Kumar K.V 	/* drop the previous reference */
47425e745b04SAneesh Kumar K.V 	atomic_dec(&cpa->pa_count);
47435e745b04SAneesh Kumar K.V 	atomic_inc(&pa->pa_count);
47445e745b04SAneesh Kumar K.V 	return pa;
47455e745b04SAneesh Kumar K.V }
47465e745b04SAneesh Kumar K.V 
47475e745b04SAneesh Kumar K.V /*
47481eff5904SKemeng Shi  * check if found pa meets EXT4_MB_HINT_GOAL_ONLY
47491eff5904SKemeng Shi  */
47501eff5904SKemeng Shi static bool
47511eff5904SKemeng Shi ext4_mb_pa_goal_check(struct ext4_allocation_context *ac,
47521eff5904SKemeng Shi 		      struct ext4_prealloc_space *pa)
47531eff5904SKemeng Shi {
47541eff5904SKemeng Shi 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
47551eff5904SKemeng Shi 	ext4_fsblk_t start;
47561eff5904SKemeng Shi 
47571eff5904SKemeng Shi 	if (likely(!(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY)))
47581eff5904SKemeng Shi 		return true;
47591eff5904SKemeng Shi 
47601eff5904SKemeng Shi 	/*
47611eff5904SKemeng Shi 	 * If EXT4_MB_HINT_GOAL_ONLY is set, ac_g_ex will not be adjusted
47621eff5904SKemeng Shi 	 * in ext4_mb_normalize_request and will keep same with ac_o_ex
47631eff5904SKemeng Shi 	 * from ext4_mb_initialize_context. Choose ac_g_ex here to keep
47641eff5904SKemeng Shi 	 * consistent with ext4_mb_find_by_goal.
47651eff5904SKemeng Shi 	 */
47661eff5904SKemeng Shi 	start = pa->pa_pstart +
47671eff5904SKemeng Shi 		(ac->ac_g_ex.fe_logical - pa->pa_lstart);
47681eff5904SKemeng Shi 	if (ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex) != start)
47691eff5904SKemeng Shi 		return false;
47701eff5904SKemeng Shi 
47711eff5904SKemeng Shi 	if (ac->ac_g_ex.fe_len > pa->pa_len -
47721eff5904SKemeng Shi 	    EXT4_B2C(sbi, ac->ac_g_ex.fe_logical - pa->pa_lstart))
47731eff5904SKemeng Shi 		return false;
47741eff5904SKemeng Shi 
47751eff5904SKemeng Shi 	return true;
47761eff5904SKemeng Shi }
47771eff5904SKemeng Shi 
47781eff5904SKemeng Shi /*
4779c9de560dSAlex Tomas  * search goal blocks in preallocated space
4780c9de560dSAlex Tomas  */
47814fca8f07SRitesh Harjani static noinline_for_stack bool
47824ddfef7bSEric Sandeen ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
4783c9de560dSAlex Tomas {
478453accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
47856be2ded1SAneesh Kumar K.V 	int order, i;
4786c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4787c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
47889d3de7eeSOjaswin Mujoo 	struct ext4_prealloc_space *tmp_pa = NULL, *cpa = NULL;
478938727786SOjaswin Mujoo 	struct rb_node *iter;
47905e745b04SAneesh Kumar K.V 	ext4_fsblk_t goal_block;
4791c9de560dSAlex Tomas 
4792c9de560dSAlex Tomas 	/* only data can be preallocated */
4793c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
47944fca8f07SRitesh Harjani 		return false;
4795c9de560dSAlex Tomas 
47969d3de7eeSOjaswin Mujoo 	/*
47979d3de7eeSOjaswin Mujoo 	 * first, try per-file preallocation by searching the inode pa rbtree.
47989d3de7eeSOjaswin Mujoo 	 *
47999d3de7eeSOjaswin Mujoo 	 * Here, we can't do a direct traversal of the tree because
48009d3de7eeSOjaswin Mujoo 	 * ext4_mb_discard_group_preallocation() can paralelly mark the pa
48019d3de7eeSOjaswin Mujoo 	 * deleted and that can cause direct traversal to skip some entries.
48029d3de7eeSOjaswin Mujoo 	 */
480338727786SOjaswin Mujoo 	read_lock(&ei->i_prealloc_lock);
48049d3de7eeSOjaswin Mujoo 
48059d3de7eeSOjaswin Mujoo 	if (RB_EMPTY_ROOT(&ei->i_prealloc_node)) {
48069d3de7eeSOjaswin Mujoo 		goto try_group_pa;
48079d3de7eeSOjaswin Mujoo 	}
48089d3de7eeSOjaswin Mujoo 
48099d3de7eeSOjaswin Mujoo 	/*
48109d3de7eeSOjaswin Mujoo 	 * Step 1: Find a pa with logical start immediately adjacent to the
48119d3de7eeSOjaswin Mujoo 	 * original logical start. This could be on the left or right.
48129d3de7eeSOjaswin Mujoo 	 *
48139d3de7eeSOjaswin Mujoo 	 * (tmp_pa->pa_lstart never changes so we can skip locking for it).
48149d3de7eeSOjaswin Mujoo 	 */
481538727786SOjaswin Mujoo 	for (iter = ei->i_prealloc_node.rb_node; iter;
481638727786SOjaswin Mujoo 	     iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
48179d3de7eeSOjaswin Mujoo 					    tmp_pa->pa_lstart, iter)) {
481838727786SOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
481938727786SOjaswin Mujoo 				  pa_node.inode_node);
48209d3de7eeSOjaswin Mujoo 	}
4821c9de560dSAlex Tomas 
48229d3de7eeSOjaswin Mujoo 	/*
48239d3de7eeSOjaswin Mujoo 	 * Step 2: The adjacent pa might be to the right of logical start, find
48249d3de7eeSOjaswin Mujoo 	 * the left adjacent pa. After this step we'd have a valid tmp_pa whose
48259d3de7eeSOjaswin Mujoo 	 * logical start is towards the left of original request's logical start
48269d3de7eeSOjaswin Mujoo 	 */
48279d3de7eeSOjaswin Mujoo 	if (tmp_pa->pa_lstart > ac->ac_o_ex.fe_logical) {
48289d3de7eeSOjaswin Mujoo 		struct rb_node *tmp;
48299d3de7eeSOjaswin Mujoo 		tmp = rb_prev(&tmp_pa->pa_node.inode_node);
4830bcf43499SOjaswin Mujoo 
48319d3de7eeSOjaswin Mujoo 		if (tmp) {
48329d3de7eeSOjaswin Mujoo 			tmp_pa = rb_entry(tmp, struct ext4_prealloc_space,
48339d3de7eeSOjaswin Mujoo 					    pa_node.inode_node);
48349d3de7eeSOjaswin Mujoo 		} else {
48359d3de7eeSOjaswin Mujoo 			/*
48369d3de7eeSOjaswin Mujoo 			 * If there is no adjacent pa to the left then finding
48379d3de7eeSOjaswin Mujoo 			 * an overlapping pa is not possible hence stop searching
48389d3de7eeSOjaswin Mujoo 			 * inode pa tree
48399d3de7eeSOjaswin Mujoo 			 */
48409d3de7eeSOjaswin Mujoo 			goto try_group_pa;
48419d3de7eeSOjaswin Mujoo 		}
48429d3de7eeSOjaswin Mujoo 	}
48439d3de7eeSOjaswin Mujoo 
48449d3de7eeSOjaswin Mujoo 	BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
48459d3de7eeSOjaswin Mujoo 
48469d3de7eeSOjaswin Mujoo 	/*
48479d3de7eeSOjaswin Mujoo 	 * Step 3: If the left adjacent pa is deleted, keep moving left to find
48489d3de7eeSOjaswin Mujoo 	 * the first non deleted adjacent pa. After this step we should have a
48499d3de7eeSOjaswin Mujoo 	 * valid tmp_pa which is guaranteed to be non deleted.
48509d3de7eeSOjaswin Mujoo 	 */
48519d3de7eeSOjaswin Mujoo 	for (iter = &tmp_pa->pa_node.inode_node;; iter = rb_prev(iter)) {
48529d3de7eeSOjaswin Mujoo 		if (!iter) {
48539d3de7eeSOjaswin Mujoo 			/*
48549d3de7eeSOjaswin Mujoo 			 * no non deleted left adjacent pa, so stop searching
48559d3de7eeSOjaswin Mujoo 			 * inode pa tree
48569d3de7eeSOjaswin Mujoo 			 */
48579d3de7eeSOjaswin Mujoo 			goto try_group_pa;
48589d3de7eeSOjaswin Mujoo 		}
48599d3de7eeSOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
48609d3de7eeSOjaswin Mujoo 				  pa_node.inode_node);
48619d3de7eeSOjaswin Mujoo 		spin_lock(&tmp_pa->pa_lock);
48629d3de7eeSOjaswin Mujoo 		if (tmp_pa->pa_deleted == 0) {
48639d3de7eeSOjaswin Mujoo 			/*
48649d3de7eeSOjaswin Mujoo 			 * We will keep holding the pa_lock from
48659d3de7eeSOjaswin Mujoo 			 * this point on because we don't want group discard
48669d3de7eeSOjaswin Mujoo 			 * to delete this pa underneath us. Since group
48679d3de7eeSOjaswin Mujoo 			 * discard is anyways an ENOSPC operation it
48689d3de7eeSOjaswin Mujoo 			 * should be okay for it to wait a few more cycles.
48699d3de7eeSOjaswin Mujoo 			 */
48709d3de7eeSOjaswin Mujoo 			break;
48719d3de7eeSOjaswin Mujoo 		} else {
48729d3de7eeSOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
48739d3de7eeSOjaswin Mujoo 		}
48749d3de7eeSOjaswin Mujoo 	}
48759d3de7eeSOjaswin Mujoo 
48769d3de7eeSOjaswin Mujoo 	BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
48779d3de7eeSOjaswin Mujoo 	BUG_ON(tmp_pa->pa_deleted == 1);
48789d3de7eeSOjaswin Mujoo 
48799d3de7eeSOjaswin Mujoo 	/*
48809d3de7eeSOjaswin Mujoo 	 * Step 4: We now have the non deleted left adjacent pa. Only this
48819d3de7eeSOjaswin Mujoo 	 * pa can possibly satisfy the request hence check if it overlaps
48829d3de7eeSOjaswin Mujoo 	 * original logical start and stop searching if it doesn't.
48839d3de7eeSOjaswin Mujoo 	 */
488443bbddc0SBaokun Li 	if (ac->ac_o_ex.fe_logical >= pa_logical_end(sbi, tmp_pa)) {
48859d3de7eeSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
48869d3de7eeSOjaswin Mujoo 		goto try_group_pa;
48879d3de7eeSOjaswin Mujoo 	}
4888c9de560dSAlex Tomas 
4889fb0a387dSEric Sandeen 	/* non-extent files can't have physical blocks past 2^32 */
489012e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
4891bcf43499SOjaswin Mujoo 	    (tmp_pa->pa_pstart + EXT4_C2B(sbi, tmp_pa->pa_len) >
4892e86a7182SOjaswin Mujoo 	     EXT4_MAX_BLOCK_FILE_PHYS)) {
4893e86a7182SOjaswin Mujoo 		/*
48949d3de7eeSOjaswin Mujoo 		 * Since PAs don't overlap, we won't find any other PA to
48959d3de7eeSOjaswin Mujoo 		 * satisfy this.
4896e86a7182SOjaswin Mujoo 		 */
48979d3de7eeSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
48989d3de7eeSOjaswin Mujoo 		goto try_group_pa;
4899e86a7182SOjaswin Mujoo 	}
4900fb0a387dSEric Sandeen 
49019d3de7eeSOjaswin Mujoo 	if (tmp_pa->pa_free && likely(ext4_mb_pa_goal_check(ac, tmp_pa))) {
4902bcf43499SOjaswin Mujoo 		atomic_inc(&tmp_pa->pa_count);
4903bcf43499SOjaswin Mujoo 		ext4_mb_use_inode_pa(ac, tmp_pa);
4904bcf43499SOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
490538727786SOjaswin Mujoo 		read_unlock(&ei->i_prealloc_lock);
49064fca8f07SRitesh Harjani 		return true;
49079d3de7eeSOjaswin Mujoo 	} else {
49089d3de7eeSOjaswin Mujoo 		/*
49099d3de7eeSOjaswin Mujoo 		 * We found a valid overlapping pa but couldn't use it because
49109d3de7eeSOjaswin Mujoo 		 * it had no free blocks. This should ideally never happen
49119d3de7eeSOjaswin Mujoo 		 * because:
49129d3de7eeSOjaswin Mujoo 		 *
49139d3de7eeSOjaswin Mujoo 		 * 1. When a new inode pa is added to rbtree it must have
49149d3de7eeSOjaswin Mujoo 		 *    pa_free > 0 since otherwise we won't actually need
49159d3de7eeSOjaswin Mujoo 		 *    preallocation.
49169d3de7eeSOjaswin Mujoo 		 *
49179d3de7eeSOjaswin Mujoo 		 * 2. An inode pa that is in the rbtree can only have it's
49189d3de7eeSOjaswin Mujoo 		 *    pa_free become zero when another thread calls:
49199d3de7eeSOjaswin Mujoo 		 *      ext4_mb_new_blocks
49209d3de7eeSOjaswin Mujoo 		 *       ext4_mb_use_preallocated
49219d3de7eeSOjaswin Mujoo 		 *        ext4_mb_use_inode_pa
49229d3de7eeSOjaswin Mujoo 		 *
49239d3de7eeSOjaswin Mujoo 		 * 3. Further, after the above calls make pa_free == 0, we will
49249d3de7eeSOjaswin Mujoo 		 *    immediately remove it from the rbtree in:
49259d3de7eeSOjaswin Mujoo 		 *      ext4_mb_new_blocks
49269d3de7eeSOjaswin Mujoo 		 *       ext4_mb_release_context
49279d3de7eeSOjaswin Mujoo 		 *        ext4_mb_put_pa
49289d3de7eeSOjaswin Mujoo 		 *
49299d3de7eeSOjaswin Mujoo 		 * 4. Since the pa_free becoming 0 and pa_free getting removed
49309d3de7eeSOjaswin Mujoo 		 * from tree both happen in ext4_mb_new_blocks, which is always
49319d3de7eeSOjaswin Mujoo 		 * called with i_data_sem held for data allocations, we can be
49329d3de7eeSOjaswin Mujoo 		 * sure that another process will never see a pa in rbtree with
49339d3de7eeSOjaswin Mujoo 		 * pa_free == 0.
49349d3de7eeSOjaswin Mujoo 		 */
49359d3de7eeSOjaswin Mujoo 		WARN_ON_ONCE(tmp_pa->pa_free == 0);
4936c9de560dSAlex Tomas 	}
4937bcf43499SOjaswin Mujoo 	spin_unlock(&tmp_pa->pa_lock);
49389d3de7eeSOjaswin Mujoo try_group_pa:
493938727786SOjaswin Mujoo 	read_unlock(&ei->i_prealloc_lock);
4940c9de560dSAlex Tomas 
4941c9de560dSAlex Tomas 	/* can we use group allocation? */
4942c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
49434fca8f07SRitesh Harjani 		return false;
4944c9de560dSAlex Tomas 
4945c9de560dSAlex Tomas 	/* inode may have no locality group for some reason */
4946c9de560dSAlex Tomas 	lg = ac->ac_lg;
4947c9de560dSAlex Tomas 	if (lg == NULL)
49484fca8f07SRitesh Harjani 		return false;
49496be2ded1SAneesh Kumar K.V 	order  = fls(ac->ac_o_ex.fe_len) - 1;
49506be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
49516be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
49526be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
4953c9de560dSAlex Tomas 
4954bda00de7SAkinobu Mita 	goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
49555e745b04SAneesh Kumar K.V 	/*
49565e745b04SAneesh Kumar K.V 	 * search for the prealloc space that is having
49575e745b04SAneesh Kumar K.V 	 * minimal distance from the goal block.
49585e745b04SAneesh Kumar K.V 	 */
49596be2ded1SAneesh Kumar K.V 	for (i = order; i < PREALLOC_TB_SIZE; i++) {
4960c9de560dSAlex Tomas 		rcu_read_lock();
4961bcf43499SOjaswin Mujoo 		list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[i],
4962a8e38fd3SOjaswin Mujoo 					pa_node.lg_list) {
4963bcf43499SOjaswin Mujoo 			spin_lock(&tmp_pa->pa_lock);
4964bcf43499SOjaswin Mujoo 			if (tmp_pa->pa_deleted == 0 &&
4965bcf43499SOjaswin Mujoo 					tmp_pa->pa_free >= ac->ac_o_ex.fe_len) {
49665e745b04SAneesh Kumar K.V 
49675e745b04SAneesh Kumar K.V 				cpa = ext4_mb_check_group_pa(goal_block,
4968bcf43499SOjaswin Mujoo 								tmp_pa, cpa);
49695e745b04SAneesh Kumar K.V 			}
4970bcf43499SOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
49715e745b04SAneesh Kumar K.V 		}
49725e745b04SAneesh Kumar K.V 		rcu_read_unlock();
49735e745b04SAneesh Kumar K.V 	}
49745e745b04SAneesh Kumar K.V 	if (cpa) {
49755e745b04SAneesh Kumar K.V 		ext4_mb_use_group_pa(ac, cpa);
49764fca8f07SRitesh Harjani 		return true;
4977c9de560dSAlex Tomas 	}
49784fca8f07SRitesh Harjani 	return false;
4979c9de560dSAlex Tomas }
4980c9de560dSAlex Tomas 
4981c9de560dSAlex Tomas /*
4982c9de560dSAlex Tomas  * the function goes through all preallocation in this group and marks them
4983c9de560dSAlex Tomas  * used in in-core bitmap. buddy must be generated from this bitmap
4984955ce5f5SAneesh Kumar K.V  * Need to be called with ext4 group lock held
4985c9de560dSAlex Tomas  */
4986089ceeccSEric Sandeen static noinline_for_stack
4987089ceeccSEric Sandeen void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
4988c9de560dSAlex Tomas 					ext4_group_t group)
4989c9de560dSAlex Tomas {
4990c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
4991c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
4992c9de560dSAlex Tomas 	struct list_head *cur;
4993c9de560dSAlex Tomas 	ext4_group_t groupnr;
4994c9de560dSAlex Tomas 	ext4_grpblk_t start;
4995c9de560dSAlex Tomas 	int preallocated = 0;
4996c9de560dSAlex Tomas 	int len;
4997c9de560dSAlex Tomas 
49985354b2afSTheodore Ts'o 	if (!grp)
49995354b2afSTheodore Ts'o 		return;
50005354b2afSTheodore Ts'o 
5001c9de560dSAlex Tomas 	/* all form of preallocation discards first load group,
5002c9de560dSAlex Tomas 	 * so the only competing code is preallocation use.
5003c9de560dSAlex Tomas 	 * we don't need any locking here
5004c9de560dSAlex Tomas 	 * notice we do NOT ignore preallocations with pa_deleted
5005c9de560dSAlex Tomas 	 * otherwise we could leave used blocks available for
5006c9de560dSAlex Tomas 	 * allocation in buddy when concurrent ext4_mb_put_pa()
5007c9de560dSAlex Tomas 	 * is dropping preallocation
5008c9de560dSAlex Tomas 	 */
5009c9de560dSAlex Tomas 	list_for_each(cur, &grp->bb_prealloc_list) {
5010c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
5011c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
5012c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5013c9de560dSAlex Tomas 					     &groupnr, &start);
5014c9de560dSAlex Tomas 		len = pa->pa_len;
5015c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
5016c9de560dSAlex Tomas 		if (unlikely(len == 0))
5017c9de560dSAlex Tomas 			continue;
5018c9de560dSAlex Tomas 		BUG_ON(groupnr != group);
5019123e3016SRitesh Harjani 		mb_set_bits(bitmap, start, len);
5020c9de560dSAlex Tomas 		preallocated += len;
5021c9de560dSAlex Tomas 	}
5022d3df1453SRitesh Harjani 	mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
5023c9de560dSAlex Tomas }
5024c9de560dSAlex Tomas 
502527bc446eSbrookxu static void ext4_mb_mark_pa_deleted(struct super_block *sb,
502627bc446eSbrookxu 				    struct ext4_prealloc_space *pa)
502727bc446eSbrookxu {
502827bc446eSbrookxu 	struct ext4_inode_info *ei;
502927bc446eSbrookxu 
503027bc446eSbrookxu 	if (pa->pa_deleted) {
503127bc446eSbrookxu 		ext4_warning(sb, "deleted pa, type:%d, pblk:%llu, lblk:%u, len:%d\n",
503227bc446eSbrookxu 			     pa->pa_type, pa->pa_pstart, pa->pa_lstart,
503327bc446eSbrookxu 			     pa->pa_len);
503427bc446eSbrookxu 		return;
503527bc446eSbrookxu 	}
503627bc446eSbrookxu 
503727bc446eSbrookxu 	pa->pa_deleted = 1;
503827bc446eSbrookxu 
503927bc446eSbrookxu 	if (pa->pa_type == MB_INODE_PA) {
504027bc446eSbrookxu 		ei = EXT4_I(pa->pa_inode);
504127bc446eSbrookxu 		atomic_dec(&ei->i_prealloc_active);
504227bc446eSbrookxu 	}
504327bc446eSbrookxu }
504427bc446eSbrookxu 
504582089725SOjaswin Mujoo static inline void ext4_mb_pa_free(struct ext4_prealloc_space *pa)
5046c9de560dSAlex Tomas {
504782089725SOjaswin Mujoo 	BUG_ON(!pa);
50484e8d2139SJunho Ryu 	BUG_ON(atomic_read(&pa->pa_count));
50494e8d2139SJunho Ryu 	BUG_ON(pa->pa_deleted == 0);
5050c9de560dSAlex Tomas 	kmem_cache_free(ext4_pspace_cachep, pa);
5051c9de560dSAlex Tomas }
5052c9de560dSAlex Tomas 
505382089725SOjaswin Mujoo static void ext4_mb_pa_callback(struct rcu_head *head)
505482089725SOjaswin Mujoo {
505582089725SOjaswin Mujoo 	struct ext4_prealloc_space *pa;
505682089725SOjaswin Mujoo 
505782089725SOjaswin Mujoo 	pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
505882089725SOjaswin Mujoo 	ext4_mb_pa_free(pa);
505982089725SOjaswin Mujoo }
506082089725SOjaswin Mujoo 
5061c9de560dSAlex Tomas /*
5062c9de560dSAlex Tomas  * drops a reference to preallocated space descriptor
5063c9de560dSAlex Tomas  * if this was the last reference and the space is consumed
5064c9de560dSAlex Tomas  */
5065c9de560dSAlex Tomas static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
5066c9de560dSAlex Tomas 			struct super_block *sb, struct ext4_prealloc_space *pa)
5067c9de560dSAlex Tomas {
5068a9df9a49STheodore Ts'o 	ext4_group_t grp;
5069d33a1976SEric Sandeen 	ext4_fsblk_t grp_blk;
507038727786SOjaswin Mujoo 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
5071c9de560dSAlex Tomas 
5072c9de560dSAlex Tomas 	/* in this short window concurrent discard can set pa_deleted */
5073c9de560dSAlex Tomas 	spin_lock(&pa->pa_lock);
50744e8d2139SJunho Ryu 	if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
50754e8d2139SJunho Ryu 		spin_unlock(&pa->pa_lock);
50764e8d2139SJunho Ryu 		return;
50774e8d2139SJunho Ryu 	}
50784e8d2139SJunho Ryu 
5079c9de560dSAlex Tomas 	if (pa->pa_deleted == 1) {
5080c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
5081c9de560dSAlex Tomas 		return;
5082c9de560dSAlex Tomas 	}
5083c9de560dSAlex Tomas 
508427bc446eSbrookxu 	ext4_mb_mark_pa_deleted(sb, pa);
5085c9de560dSAlex Tomas 	spin_unlock(&pa->pa_lock);
5086c9de560dSAlex Tomas 
5087d33a1976SEric Sandeen 	grp_blk = pa->pa_pstart;
5088cc0fb9adSAneesh Kumar K.V 	/*
5089cc0fb9adSAneesh Kumar K.V 	 * If doing group-based preallocation, pa_pstart may be in the
5090cc0fb9adSAneesh Kumar K.V 	 * next group when pa is used up
5091cc0fb9adSAneesh Kumar K.V 	 */
5092cc0fb9adSAneesh Kumar K.V 	if (pa->pa_type == MB_GROUP_PA)
5093d33a1976SEric Sandeen 		grp_blk--;
5094d33a1976SEric Sandeen 
5095bd86298eSLukas Czerner 	grp = ext4_get_group_number(sb, grp_blk);
5096c9de560dSAlex Tomas 
5097c9de560dSAlex Tomas 	/*
5098c9de560dSAlex Tomas 	 * possible race:
5099c9de560dSAlex Tomas 	 *
5100c9de560dSAlex Tomas 	 *  P1 (buddy init)			P2 (regular allocation)
5101c9de560dSAlex Tomas 	 *					find block B in PA
5102c9de560dSAlex Tomas 	 *  copy on-disk bitmap to buddy
5103c9de560dSAlex Tomas 	 *  					mark B in on-disk bitmap
5104c9de560dSAlex Tomas 	 *					drop PA from group
5105c9de560dSAlex Tomas 	 *  mark all PAs in buddy
5106c9de560dSAlex Tomas 	 *
5107c9de560dSAlex Tomas 	 * thus, P1 initializes buddy with B available. to prevent this
5108c9de560dSAlex Tomas 	 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
5109c9de560dSAlex Tomas 	 * against that pair
5110c9de560dSAlex Tomas 	 */
5111c9de560dSAlex Tomas 	ext4_lock_group(sb, grp);
5112c9de560dSAlex Tomas 	list_del(&pa->pa_group_list);
5113c9de560dSAlex Tomas 	ext4_unlock_group(sb, grp);
5114c9de560dSAlex Tomas 
5115a8e38fd3SOjaswin Mujoo 	if (pa->pa_type == MB_INODE_PA) {
511638727786SOjaswin Mujoo 		write_lock(pa->pa_node_lock.inode_lock);
511738727786SOjaswin Mujoo 		rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
511838727786SOjaswin Mujoo 		write_unlock(pa->pa_node_lock.inode_lock);
511938727786SOjaswin Mujoo 		ext4_mb_pa_free(pa);
5120a8e38fd3SOjaswin Mujoo 	} else {
5121a8e38fd3SOjaswin Mujoo 		spin_lock(pa->pa_node_lock.lg_lock);
5122a8e38fd3SOjaswin Mujoo 		list_del_rcu(&pa->pa_node.lg_list);
5123a8e38fd3SOjaswin Mujoo 		spin_unlock(pa->pa_node_lock.lg_lock);
512438727786SOjaswin Mujoo 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
512538727786SOjaswin Mujoo 	}
5126a8e38fd3SOjaswin Mujoo }
5127c9de560dSAlex Tomas 
512838727786SOjaswin Mujoo static void ext4_mb_pa_rb_insert(struct rb_root *root, struct rb_node *new)
512938727786SOjaswin Mujoo {
513038727786SOjaswin Mujoo 	struct rb_node **iter = &root->rb_node, *parent = NULL;
513138727786SOjaswin Mujoo 	struct ext4_prealloc_space *iter_pa, *new_pa;
513238727786SOjaswin Mujoo 	ext4_lblk_t iter_start, new_start;
513338727786SOjaswin Mujoo 
513438727786SOjaswin Mujoo 	while (*iter) {
513538727786SOjaswin Mujoo 		iter_pa = rb_entry(*iter, struct ext4_prealloc_space,
513638727786SOjaswin Mujoo 				   pa_node.inode_node);
513738727786SOjaswin Mujoo 		new_pa = rb_entry(new, struct ext4_prealloc_space,
513838727786SOjaswin Mujoo 				   pa_node.inode_node);
513938727786SOjaswin Mujoo 		iter_start = iter_pa->pa_lstart;
514038727786SOjaswin Mujoo 		new_start = new_pa->pa_lstart;
514138727786SOjaswin Mujoo 
514238727786SOjaswin Mujoo 		parent = *iter;
514338727786SOjaswin Mujoo 		if (new_start < iter_start)
514438727786SOjaswin Mujoo 			iter = &((*iter)->rb_left);
514538727786SOjaswin Mujoo 		else
514638727786SOjaswin Mujoo 			iter = &((*iter)->rb_right);
514738727786SOjaswin Mujoo 	}
514838727786SOjaswin Mujoo 
514938727786SOjaswin Mujoo 	rb_link_node(new, parent, iter);
515038727786SOjaswin Mujoo 	rb_insert_color(new, root);
5151c9de560dSAlex Tomas }
5152c9de560dSAlex Tomas 
5153c9de560dSAlex Tomas /*
5154c9de560dSAlex Tomas  * creates new preallocated space for given inode
5155c9de560dSAlex Tomas  */
515653f86b17SRitesh Harjani static noinline_for_stack void
51574ddfef7bSEric Sandeen ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
5158c9de560dSAlex Tomas {
5159c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
516053accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5161c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
5162c9de560dSAlex Tomas 	struct ext4_group_info *grp;
5163c9de560dSAlex Tomas 	struct ext4_inode_info *ei;
5164c9de560dSAlex Tomas 
5165c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
5166c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5167c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5168c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
516953f86b17SRitesh Harjani 	BUG_ON(ac->ac_pa == NULL);
5170c9de560dSAlex Tomas 
517153f86b17SRitesh Harjani 	pa = ac->ac_pa;
5172c9de560dSAlex Tomas 
51737e170922SOjaswin Mujoo 	if (ac->ac_b_ex.fe_len < ac->ac_orig_goal_len) {
5174bc056e71SBaokun Li 		struct ext4_free_extent ex = {
5175bc056e71SBaokun Li 			.fe_logical = ac->ac_g_ex.fe_logical,
5176bc056e71SBaokun Li 			.fe_len = ac->ac_orig_goal_len,
5177bc056e71SBaokun Li 		};
5178bc056e71SBaokun Li 		loff_t orig_goal_end = extent_logical_end(sbi, &ex);
51794fbf8bc7SBaokun Li 		loff_t o_ex_end = extent_logical_end(sbi, &ac->ac_o_ex);
5180c9de560dSAlex Tomas 
51814fbf8bc7SBaokun Li 		/*
51824fbf8bc7SBaokun Li 		 * We can't allocate as much as normalizer wants, so we try
51834fbf8bc7SBaokun Li 		 * to get proper lstart to cover the original request, except
51844fbf8bc7SBaokun Li 		 * when the goal doesn't cover the original request as below:
51854fbf8bc7SBaokun Li 		 *
51864fbf8bc7SBaokun Li 		 * orig_ex:2045/2055(10), isize:8417280 -> normalized:0/2048
51874fbf8bc7SBaokun Li 		 * best_ex:0/200(200) -> adjusted: 1848/2048(200)
51884fbf8bc7SBaokun Li 		 */
5189c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
5190c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
5191c9de560dSAlex Tomas 
519293cdf49fSOjaswin Mujoo 		/*
519393cdf49fSOjaswin Mujoo 		 * Use the below logic for adjusting best extent as it keeps
519493cdf49fSOjaswin Mujoo 		 * fragmentation in check while ensuring logical range of best
519593cdf49fSOjaswin Mujoo 		 * extent doesn't overflow out of goal extent:
519693cdf49fSOjaswin Mujoo 		 *
51977e170922SOjaswin Mujoo 		 * 1. Check if best ex can be kept at end of goal (before
51987e170922SOjaswin Mujoo 		 *    cr_best_avail trimmed it) and still cover original start
519993cdf49fSOjaswin Mujoo 		 * 2. Else, check if best ex can be kept at start of goal and
52004fbf8bc7SBaokun Li 		 *    still cover original end
520193cdf49fSOjaswin Mujoo 		 * 3. Else, keep the best ex at start of original request.
520293cdf49fSOjaswin Mujoo 		 */
5203bc056e71SBaokun Li 		ex.fe_len = ac->ac_b_ex.fe_len;
5204bc056e71SBaokun Li 
5205bc056e71SBaokun Li 		ex.fe_logical = orig_goal_end - EXT4_C2B(sbi, ex.fe_len);
5206bc056e71SBaokun Li 		if (ac->ac_o_ex.fe_logical >= ex.fe_logical)
520793cdf49fSOjaswin Mujoo 			goto adjust_bex;
5208c9de560dSAlex Tomas 
5209bc056e71SBaokun Li 		ex.fe_logical = ac->ac_g_ex.fe_logical;
52104fbf8bc7SBaokun Li 		if (o_ex_end <= extent_logical_end(sbi, &ex))
521193cdf49fSOjaswin Mujoo 			goto adjust_bex;
5212c9de560dSAlex Tomas 
5213bc056e71SBaokun Li 		ex.fe_logical = ac->ac_o_ex.fe_logical;
521493cdf49fSOjaswin Mujoo adjust_bex:
5215bc056e71SBaokun Li 		ac->ac_b_ex.fe_logical = ex.fe_logical;
5216c9de560dSAlex Tomas 
5217c9de560dSAlex Tomas 		BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
5218bc056e71SBaokun Li 		BUG_ON(extent_logical_end(sbi, &ex) > orig_goal_end);
5219c9de560dSAlex Tomas 	}
5220c9de560dSAlex Tomas 
5221c9de560dSAlex Tomas 	pa->pa_lstart = ac->ac_b_ex.fe_logical;
5222c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5223c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
5224c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
5225c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
5226d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
5227c9de560dSAlex Tomas 	pa->pa_deleted = 0;
5228cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_INODE_PA;
5229c9de560dSAlex Tomas 
5230d3df1453SRitesh Harjani 	mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5231d3df1453SRitesh Harjani 		 pa->pa_len, pa->pa_lstart);
52329bffad1eSTheodore Ts'o 	trace_ext4_mb_new_inode_pa(ac, pa);
5233c9de560dSAlex Tomas 
523453accfa9STheodore Ts'o 	atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
5235abc075d4SKemeng Shi 	ext4_mb_use_inode_pa(ac, pa);
5236c9de560dSAlex Tomas 
5237c9de560dSAlex Tomas 	ei = EXT4_I(ac->ac_inode);
5238c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
52395354b2afSTheodore Ts'o 	if (!grp)
52405354b2afSTheodore Ts'o 		return;
5241c9de560dSAlex Tomas 
5242a8e38fd3SOjaswin Mujoo 	pa->pa_node_lock.inode_lock = &ei->i_prealloc_lock;
5243c9de560dSAlex Tomas 	pa->pa_inode = ac->ac_inode;
5244c9de560dSAlex Tomas 
5245c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5246c9de560dSAlex Tomas 
524738727786SOjaswin Mujoo 	write_lock(pa->pa_node_lock.inode_lock);
524838727786SOjaswin Mujoo 	ext4_mb_pa_rb_insert(&ei->i_prealloc_node, &pa->pa_node.inode_node);
524938727786SOjaswin Mujoo 	write_unlock(pa->pa_node_lock.inode_lock);
525027bc446eSbrookxu 	atomic_inc(&ei->i_prealloc_active);
5251c9de560dSAlex Tomas }
5252c9de560dSAlex Tomas 
5253c9de560dSAlex Tomas /*
5254c9de560dSAlex Tomas  * creates new preallocated space for locality group inodes belongs to
5255c9de560dSAlex Tomas  */
525653f86b17SRitesh Harjani static noinline_for_stack void
52574ddfef7bSEric Sandeen ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
5258c9de560dSAlex Tomas {
5259c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
5260c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
5261c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
5262c9de560dSAlex Tomas 	struct ext4_group_info *grp;
5263c9de560dSAlex Tomas 
5264c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
5265c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5266c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5267c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
526853f86b17SRitesh Harjani 	BUG_ON(ac->ac_pa == NULL);
5269c9de560dSAlex Tomas 
527053f86b17SRitesh Harjani 	pa = ac->ac_pa;
5271c9de560dSAlex Tomas 
5272c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5273c9de560dSAlex Tomas 	pa->pa_lstart = pa->pa_pstart;
5274c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
5275c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
5276c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
5277a8e38fd3SOjaswin Mujoo 	INIT_LIST_HEAD(&pa->pa_node.lg_list);
5278d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
5279c9de560dSAlex Tomas 	pa->pa_deleted = 0;
5280cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_GROUP_PA;
5281c9de560dSAlex Tomas 
5282d3df1453SRitesh Harjani 	mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5283d3df1453SRitesh Harjani 		 pa->pa_len, pa->pa_lstart);
52849bffad1eSTheodore Ts'o 	trace_ext4_mb_new_group_pa(ac, pa);
5285c9de560dSAlex Tomas 
5286c9de560dSAlex Tomas 	ext4_mb_use_group_pa(ac, pa);
5287c9de560dSAlex Tomas 	atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
5288c9de560dSAlex Tomas 
5289c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
52905354b2afSTheodore Ts'o 	if (!grp)
52915354b2afSTheodore Ts'o 		return;
5292c9de560dSAlex Tomas 	lg = ac->ac_lg;
5293c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
5294c9de560dSAlex Tomas 
5295a8e38fd3SOjaswin Mujoo 	pa->pa_node_lock.lg_lock = &lg->lg_prealloc_lock;
5296c9de560dSAlex Tomas 	pa->pa_inode = NULL;
5297c9de560dSAlex Tomas 
5298c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5299c9de560dSAlex Tomas 
53006be2ded1SAneesh Kumar K.V 	/*
53016be2ded1SAneesh Kumar K.V 	 * We will later add the new pa to the right bucket
53026be2ded1SAneesh Kumar K.V 	 * after updating the pa_free in ext4_mb_release_context
53036be2ded1SAneesh Kumar K.V 	 */
5304c9de560dSAlex Tomas }
5305c9de560dSAlex Tomas 
530653f86b17SRitesh Harjani static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
5307c9de560dSAlex Tomas {
5308c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
530953f86b17SRitesh Harjani 		ext4_mb_new_group_pa(ac);
5310c9de560dSAlex Tomas 	else
531153f86b17SRitesh Harjani 		ext4_mb_new_inode_pa(ac);
5312c9de560dSAlex Tomas }
5313c9de560dSAlex Tomas 
5314c9de560dSAlex Tomas /*
5315c9de560dSAlex Tomas  * finds all unused blocks in on-disk bitmap, frees them in
5316c9de560dSAlex Tomas  * in-core bitmap and buddy.
5317c9de560dSAlex Tomas  * @pa must be unlinked from inode and group lists, so that
5318c9de560dSAlex Tomas  * nobody else can find/use it.
5319c9de560dSAlex Tomas  * the caller MUST hold group/inode locks.
5320c9de560dSAlex Tomas  * TODO: optimize the case when there are no in-core structures yet
5321c9de560dSAlex Tomas  */
5322820c2808SKemeng Shi static noinline_for_stack void
53234ddfef7bSEric Sandeen ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
53243e1e5f50SEric Sandeen 			struct ext4_prealloc_space *pa)
5325c9de560dSAlex Tomas {
5326c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
5327c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5328498e5f24STheodore Ts'o 	unsigned int end;
5329498e5f24STheodore Ts'o 	unsigned int next;
5330c9de560dSAlex Tomas 	ext4_group_t group;
5331c9de560dSAlex Tomas 	ext4_grpblk_t bit;
5332ba80b101STheodore Ts'o 	unsigned long long grp_blk_start;
5333c9de560dSAlex Tomas 	int free = 0;
5334c9de560dSAlex Tomas 
5335c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
5336c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
533753accfa9STheodore Ts'o 	grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
5338c9de560dSAlex Tomas 	BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
5339c9de560dSAlex Tomas 	end = bit + pa->pa_len;
5340c9de560dSAlex Tomas 
5341c9de560dSAlex Tomas 	while (bit < end) {
5342ffad0a44SAneesh Kumar K.V 		bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
5343c9de560dSAlex Tomas 		if (bit >= end)
5344c9de560dSAlex Tomas 			break;
5345ffad0a44SAneesh Kumar K.V 		next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
5346d3df1453SRitesh Harjani 		mb_debug(sb, "free preallocated %u/%u in group %u\n",
53475a0790c2SAndi Kleen 			 (unsigned) ext4_group_first_block_no(sb, group) + bit,
53485a0790c2SAndi Kleen 			 (unsigned) next - bit, (unsigned) group);
5349c9de560dSAlex Tomas 		free += next - bit;
5350c9de560dSAlex Tomas 
53513e1e5f50SEric Sandeen 		trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
535253accfa9STheodore Ts'o 		trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
535353accfa9STheodore Ts'o 						    EXT4_C2B(sbi, bit)),
5354a9c667f8SLukas Czerner 					       next - bit);
5355c9de560dSAlex Tomas 		mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
5356c9de560dSAlex Tomas 		bit = next + 1;
5357c9de560dSAlex Tomas 	}
5358c9de560dSAlex Tomas 	if (free != pa->pa_free) {
53599d8b9ec4STheodore Ts'o 		ext4_msg(e4b->bd_sb, KERN_CRIT,
536036bad423SRitesh Harjani 			 "pa %p: logic %lu, phys. %lu, len %d",
5361c9de560dSAlex Tomas 			 pa, (unsigned long) pa->pa_lstart,
5362c9de560dSAlex Tomas 			 (unsigned long) pa->pa_pstart,
536336bad423SRitesh Harjani 			 pa->pa_len);
5364e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
536526346ff6SAneesh Kumar K.V 					free, pa->pa_free);
5366e56eb659SAneesh Kumar K.V 		/*
5367e56eb659SAneesh Kumar K.V 		 * pa is already deleted so we use the value obtained
5368e56eb659SAneesh Kumar K.V 		 * from the bitmap and continue.
5369e56eb659SAneesh Kumar K.V 		 */
5370c9de560dSAlex Tomas 	}
5371c9de560dSAlex Tomas 	atomic_add(free, &sbi->s_mb_discarded);
5372c9de560dSAlex Tomas }
5373c9de560dSAlex Tomas 
537420427949SKemeng Shi static noinline_for_stack void
53754ddfef7bSEric Sandeen ext4_mb_release_group_pa(struct ext4_buddy *e4b,
53763e1e5f50SEric Sandeen 				struct ext4_prealloc_space *pa)
5377c9de560dSAlex Tomas {
5378c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
5379c9de560dSAlex Tomas 	ext4_group_t group;
5380c9de560dSAlex Tomas 	ext4_grpblk_t bit;
5381c9de560dSAlex Tomas 
538260e07cf5SYongqiang Yang 	trace_ext4_mb_release_group_pa(sb, pa);
5383c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
5384c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
5385463808f2STheodore Ts'o 	if (unlikely(group != e4b->bd_group && pa->pa_len != 0)) {
5386463808f2STheodore Ts'o 		ext4_warning(sb, "bad group: expected %u, group %u, pa_start %llu",
5387463808f2STheodore Ts'o 			     e4b->bd_group, group, pa->pa_pstart);
538820427949SKemeng Shi 		return;
5389463808f2STheodore Ts'o 	}
5390c9de560dSAlex Tomas 	mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
5391c9de560dSAlex Tomas 	atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
53923e1e5f50SEric Sandeen 	trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
5393c9de560dSAlex Tomas }
5394c9de560dSAlex Tomas 
5395c9de560dSAlex Tomas /*
5396c9de560dSAlex Tomas  * releases all preallocations in given group
5397c9de560dSAlex Tomas  *
5398c9de560dSAlex Tomas  * first, we need to decide discard policy:
5399c9de560dSAlex Tomas  * - when do we discard
5400c9de560dSAlex Tomas  *   1) ENOSPC
5401c9de560dSAlex Tomas  * - how many do we discard
5402c9de560dSAlex Tomas  *   1) how many requested
5403c9de560dSAlex Tomas  */
54044ddfef7bSEric Sandeen static noinline_for_stack int
54054ddfef7bSEric Sandeen ext4_mb_discard_group_preallocations(struct super_block *sb,
54068c80fb31SChunguang Xu 				     ext4_group_t group, int *busy)
5407c9de560dSAlex Tomas {
5408c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
5409c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
5410c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
54110f6bc579SRuan Jinjie 	LIST_HEAD(list);
5412c9de560dSAlex Tomas 	struct ext4_buddy e4b;
541338727786SOjaswin Mujoo 	struct ext4_inode_info *ei;
5414c9de560dSAlex Tomas 	int err;
54158c80fb31SChunguang Xu 	int free = 0;
5416c9de560dSAlex Tomas 
54175354b2afSTheodore Ts'o 	if (!grp)
54185354b2afSTheodore Ts'o 		return 0;
5419d3df1453SRitesh Harjani 	mb_debug(sb, "discard preallocation for group %u\n", group);
5420c9de560dSAlex Tomas 	if (list_empty(&grp->bb_prealloc_list))
5421bbc4ec77SRitesh Harjani 		goto out_dbg;
5422c9de560dSAlex Tomas 
5423574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, group);
54249008a58eSDarrick J. Wong 	if (IS_ERR(bitmap_bh)) {
54259008a58eSDarrick J. Wong 		err = PTR_ERR(bitmap_bh);
542654d3adbcSTheodore Ts'o 		ext4_error_err(sb, -err,
542754d3adbcSTheodore Ts'o 			       "Error %d reading block bitmap for %u",
54289008a58eSDarrick J. Wong 			       err, group);
5429bbc4ec77SRitesh Harjani 		goto out_dbg;
5430c9de560dSAlex Tomas 	}
5431c9de560dSAlex Tomas 
5432c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(sb, group, &e4b);
5433ce89f46cSAneesh Kumar K.V 	if (err) {
54349651e6b2SKonstantin Khlebnikov 		ext4_warning(sb, "Error %d loading buddy information for %u",
54359651e6b2SKonstantin Khlebnikov 			     err, group);
5436ce89f46cSAneesh Kumar K.V 		put_bh(bitmap_bh);
5437bbc4ec77SRitesh Harjani 		goto out_dbg;
5438ce89f46cSAneesh Kumar K.V 	}
5439c9de560dSAlex Tomas 
5440c9de560dSAlex Tomas 	ext4_lock_group(sb, group);
5441c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp,
5442c9de560dSAlex Tomas 				&grp->bb_prealloc_list, pa_group_list) {
5443c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
5444c9de560dSAlex Tomas 		if (atomic_read(&pa->pa_count)) {
5445c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
54468c80fb31SChunguang Xu 			*busy = 1;
5447c9de560dSAlex Tomas 			continue;
5448c9de560dSAlex Tomas 		}
5449c9de560dSAlex Tomas 		if (pa->pa_deleted) {
5450c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
5451c9de560dSAlex Tomas 			continue;
5452c9de560dSAlex Tomas 		}
5453c9de560dSAlex Tomas 
5454c9de560dSAlex Tomas 		/* seems this one can be freed ... */
545527bc446eSbrookxu 		ext4_mb_mark_pa_deleted(sb, pa);
5456c9de560dSAlex Tomas 
545770022da8SYe Bin 		if (!free)
545870022da8SYe Bin 			this_cpu_inc(discard_pa_seq);
545970022da8SYe Bin 
5460c9de560dSAlex Tomas 		/* we can trust pa_free ... */
5461c9de560dSAlex Tomas 		free += pa->pa_free;
5462c9de560dSAlex Tomas 
5463c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
5464c9de560dSAlex Tomas 
5465c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
5466c9de560dSAlex Tomas 		list_add(&pa->u.pa_tmp_list, &list);
5467c9de560dSAlex Tomas 	}
5468c9de560dSAlex Tomas 
5469c9de560dSAlex Tomas 	/* now free all selected PAs */
5470c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5471c9de560dSAlex Tomas 
5472c9de560dSAlex Tomas 		/* remove from object (inode or locality group) */
5473a8e38fd3SOjaswin Mujoo 		if (pa->pa_type == MB_GROUP_PA) {
5474a8e38fd3SOjaswin Mujoo 			spin_lock(pa->pa_node_lock.lg_lock);
5475a8e38fd3SOjaswin Mujoo 			list_del_rcu(&pa->pa_node.lg_list);
5476a8e38fd3SOjaswin Mujoo 			spin_unlock(pa->pa_node_lock.lg_lock);
5477a8e38fd3SOjaswin Mujoo 		} else {
547838727786SOjaswin Mujoo 			write_lock(pa->pa_node_lock.inode_lock);
547938727786SOjaswin Mujoo 			ei = EXT4_I(pa->pa_inode);
548038727786SOjaswin Mujoo 			rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
548138727786SOjaswin Mujoo 			write_unlock(pa->pa_node_lock.inode_lock);
5482a8e38fd3SOjaswin Mujoo 		}
5483c9de560dSAlex Tomas 
5484c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
548538727786SOjaswin Mujoo 
548638727786SOjaswin Mujoo 		if (pa->pa_type == MB_GROUP_PA) {
548738727786SOjaswin Mujoo 			ext4_mb_release_group_pa(&e4b, pa);
5488c9de560dSAlex Tomas 			call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
548938727786SOjaswin Mujoo 		} else {
549038727786SOjaswin Mujoo 			ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
549138727786SOjaswin Mujoo 			ext4_mb_pa_free(pa);
549238727786SOjaswin Mujoo 		}
5493c9de560dSAlex Tomas 	}
5494c9de560dSAlex Tomas 
5495c9de560dSAlex Tomas 	ext4_unlock_group(sb, group);
5496e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
5497c9de560dSAlex Tomas 	put_bh(bitmap_bh);
5498bbc4ec77SRitesh Harjani out_dbg:
5499d3df1453SRitesh Harjani 	mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
55008c80fb31SChunguang Xu 		 free, group, grp->bb_free);
55018c80fb31SChunguang Xu 	return free;
5502c9de560dSAlex Tomas }
5503c9de560dSAlex Tomas 
5504c9de560dSAlex Tomas /*
5505c9de560dSAlex Tomas  * releases all non-used preallocated blocks for given inode
5506c9de560dSAlex Tomas  *
5507c9de560dSAlex Tomas  * It's important to discard preallocations under i_data_sem
5508c9de560dSAlex Tomas  * We don't want another block to be served from the prealloc
5509c9de560dSAlex Tomas  * space when we are discarding the inode prealloc space.
5510c9de560dSAlex Tomas  *
5511c9de560dSAlex Tomas  * FIXME!! Make sure it is valid at all the call sites
5512c9de560dSAlex Tomas  */
55132ffd2a6aSKemeng Shi void ext4_discard_preallocations(struct inode *inode)
5514c9de560dSAlex Tomas {
5515c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(inode);
5516c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
5517c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
5518c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
5519c9de560dSAlex Tomas 	ext4_group_t group = 0;
55200f6bc579SRuan Jinjie 	LIST_HEAD(list);
5521c9de560dSAlex Tomas 	struct ext4_buddy e4b;
552238727786SOjaswin Mujoo 	struct rb_node *iter;
5523c9de560dSAlex Tomas 	int err;
5524c9de560dSAlex Tomas 
5525f0e54b60SKemeng Shi 	if (!S_ISREG(inode->i_mode))
5526c9de560dSAlex Tomas 		return;
5527c9de560dSAlex Tomas 
55288016e29fSHarshad Shirwadkar 	if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
55298016e29fSHarshad Shirwadkar 		return;
55308016e29fSHarshad Shirwadkar 
5531d3df1453SRitesh Harjani 	mb_debug(sb, "discard preallocation for inode %lu\n",
5532d3df1453SRitesh Harjani 		 inode->i_ino);
553327bc446eSbrookxu 	trace_ext4_discard_preallocations(inode,
5534f0e54b60SKemeng Shi 			atomic_read(&ei->i_prealloc_active));
553527bc446eSbrookxu 
5536c9de560dSAlex Tomas repeat:
5537c9de560dSAlex Tomas 	/* first, collect all pa's in the inode */
553838727786SOjaswin Mujoo 	write_lock(&ei->i_prealloc_lock);
55392ffd2a6aSKemeng Shi 	for (iter = rb_first(&ei->i_prealloc_node); iter;
554038727786SOjaswin Mujoo 	     iter = rb_next(iter)) {
554138727786SOjaswin Mujoo 		pa = rb_entry(iter, struct ext4_prealloc_space,
554238727786SOjaswin Mujoo 			      pa_node.inode_node);
5543a8e38fd3SOjaswin Mujoo 		BUG_ON(pa->pa_node_lock.inode_lock != &ei->i_prealloc_lock);
554438727786SOjaswin Mujoo 
5545c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
5546c9de560dSAlex Tomas 		if (atomic_read(&pa->pa_count)) {
5547c9de560dSAlex Tomas 			/* this shouldn't happen often - nobody should
5548c9de560dSAlex Tomas 			 * use preallocation while we're discarding it */
5549c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
555038727786SOjaswin Mujoo 			write_unlock(&ei->i_prealloc_lock);
55519d8b9ec4STheodore Ts'o 			ext4_msg(sb, KERN_ERR,
55529d8b9ec4STheodore Ts'o 				 "uh-oh! used pa while discarding");
5553c9de560dSAlex Tomas 			WARN_ON(1);
5554c9de560dSAlex Tomas 			schedule_timeout_uninterruptible(HZ);
5555c9de560dSAlex Tomas 			goto repeat;
5556c9de560dSAlex Tomas 
5557c9de560dSAlex Tomas 		}
5558c9de560dSAlex Tomas 		if (pa->pa_deleted == 0) {
555927bc446eSbrookxu 			ext4_mb_mark_pa_deleted(sb, pa);
5560c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
556138727786SOjaswin Mujoo 			rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5562c9de560dSAlex Tomas 			list_add(&pa->u.pa_tmp_list, &list);
5563c9de560dSAlex Tomas 			continue;
5564c9de560dSAlex Tomas 		}
5565c9de560dSAlex Tomas 
5566c9de560dSAlex Tomas 		/* someone is deleting pa right now */
5567c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
556838727786SOjaswin Mujoo 		write_unlock(&ei->i_prealloc_lock);
5569c9de560dSAlex Tomas 
5570c9de560dSAlex Tomas 		/* we have to wait here because pa_deleted
5571c9de560dSAlex Tomas 		 * doesn't mean pa is already unlinked from
5572c9de560dSAlex Tomas 		 * the list. as we might be called from
5573c9de560dSAlex Tomas 		 * ->clear_inode() the inode will get freed
5574c9de560dSAlex Tomas 		 * and concurrent thread which is unlinking
5575c9de560dSAlex Tomas 		 * pa from inode's list may access already
5576c9de560dSAlex Tomas 		 * freed memory, bad-bad-bad */
5577c9de560dSAlex Tomas 
5578c9de560dSAlex Tomas 		/* XXX: if this happens too often, we can
5579c9de560dSAlex Tomas 		 * add a flag to force wait only in case
5580c9de560dSAlex Tomas 		 * of ->clear_inode(), but not in case of
5581c9de560dSAlex Tomas 		 * regular truncate */
5582c9de560dSAlex Tomas 		schedule_timeout_uninterruptible(HZ);
5583c9de560dSAlex Tomas 		goto repeat;
5584c9de560dSAlex Tomas 	}
558538727786SOjaswin Mujoo 	write_unlock(&ei->i_prealloc_lock);
5586c9de560dSAlex Tomas 
5587c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5588cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_INODE_PA);
5589bd86298eSLukas Czerner 		group = ext4_get_group_number(sb, pa->pa_pstart);
5590c9de560dSAlex Tomas 
55919651e6b2SKonstantin Khlebnikov 		err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
55929651e6b2SKonstantin Khlebnikov 					     GFP_NOFS|__GFP_NOFAIL);
5593ce89f46cSAneesh Kumar K.V 		if (err) {
559454d3adbcSTheodore Ts'o 			ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
55959651e6b2SKonstantin Khlebnikov 				       err, group);
5596ce89f46cSAneesh Kumar K.V 			continue;
5597ce89f46cSAneesh Kumar K.V 		}
5598c9de560dSAlex Tomas 
5599574ca174STheodore Ts'o 		bitmap_bh = ext4_read_block_bitmap(sb, group);
56009008a58eSDarrick J. Wong 		if (IS_ERR(bitmap_bh)) {
56019008a58eSDarrick J. Wong 			err = PTR_ERR(bitmap_bh);
560254d3adbcSTheodore Ts'o 			ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
56039008a58eSDarrick J. Wong 				       err, group);
5604e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
5605ce89f46cSAneesh Kumar K.V 			continue;
5606c9de560dSAlex Tomas 		}
5607c9de560dSAlex Tomas 
5608c9de560dSAlex Tomas 		ext4_lock_group(sb, group);
5609c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
56103e1e5f50SEric Sandeen 		ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
5611c9de560dSAlex Tomas 		ext4_unlock_group(sb, group);
5612c9de560dSAlex Tomas 
5613e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
5614c9de560dSAlex Tomas 		put_bh(bitmap_bh);
5615c9de560dSAlex Tomas 
5616c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
561738727786SOjaswin Mujoo 		ext4_mb_pa_free(pa);
5618c9de560dSAlex Tomas 	}
5619c9de560dSAlex Tomas }
5620c9de560dSAlex Tomas 
562153f86b17SRitesh Harjani static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
562253f86b17SRitesh Harjani {
562353f86b17SRitesh Harjani 	struct ext4_prealloc_space *pa;
562453f86b17SRitesh Harjani 
562553f86b17SRitesh Harjani 	BUG_ON(ext4_pspace_cachep == NULL);
562653f86b17SRitesh Harjani 	pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
562753f86b17SRitesh Harjani 	if (!pa)
562853f86b17SRitesh Harjani 		return -ENOMEM;
562953f86b17SRitesh Harjani 	atomic_set(&pa->pa_count, 1);
563053f86b17SRitesh Harjani 	ac->ac_pa = pa;
563153f86b17SRitesh Harjani 	return 0;
563253f86b17SRitesh Harjani }
563353f86b17SRitesh Harjani 
563482089725SOjaswin Mujoo static void ext4_mb_pa_put_free(struct ext4_allocation_context *ac)
563553f86b17SRitesh Harjani {
563653f86b17SRitesh Harjani 	struct ext4_prealloc_space *pa = ac->ac_pa;
563753f86b17SRitesh Harjani 
563853f86b17SRitesh Harjani 	BUG_ON(!pa);
563953f86b17SRitesh Harjani 	ac->ac_pa = NULL;
564053f86b17SRitesh Harjani 	WARN_ON(!atomic_dec_and_test(&pa->pa_count));
564182089725SOjaswin Mujoo 	/*
564282089725SOjaswin Mujoo 	 * current function is only called due to an error or due to
564382089725SOjaswin Mujoo 	 * len of found blocks < len of requested blocks hence the PA has not
564482089725SOjaswin Mujoo 	 * been added to grp->bb_prealloc_list. So we don't need to lock it
564582089725SOjaswin Mujoo 	 */
564682089725SOjaswin Mujoo 	pa->pa_deleted = 1;
564782089725SOjaswin Mujoo 	ext4_mb_pa_free(pa);
564853f86b17SRitesh Harjani }
564953f86b17SRitesh Harjani 
56506ba495e9STheodore Ts'o #ifdef CONFIG_EXT4_DEBUG
5651e68cf40cSRitesh Harjani static inline void ext4_mb_show_pa(struct super_block *sb)
5652c9de560dSAlex Tomas {
5653e68cf40cSRitesh Harjani 	ext4_group_t i, ngroups;
5654c9de560dSAlex Tomas 
565595257987SJan Kara 	if (ext4_forced_shutdown(sb))
5656e3570639SEric Sandeen 		return;
5657e3570639SEric Sandeen 
56588df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
5659d3df1453SRitesh Harjani 	mb_debug(sb, "groups: ");
56608df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
5661c9de560dSAlex Tomas 		struct ext4_group_info *grp = ext4_get_group_info(sb, i);
5662c9de560dSAlex Tomas 		struct ext4_prealloc_space *pa;
5663c9de560dSAlex Tomas 		ext4_grpblk_t start;
5664c9de560dSAlex Tomas 		struct list_head *cur;
56655354b2afSTheodore Ts'o 
56665354b2afSTheodore Ts'o 		if (!grp)
56675354b2afSTheodore Ts'o 			continue;
5668c9de560dSAlex Tomas 		ext4_lock_group(sb, i);
5669c9de560dSAlex Tomas 		list_for_each(cur, &grp->bb_prealloc_list) {
5670c9de560dSAlex Tomas 			pa = list_entry(cur, struct ext4_prealloc_space,
5671c9de560dSAlex Tomas 					pa_group_list);
5672c9de560dSAlex Tomas 			spin_lock(&pa->pa_lock);
5673c9de560dSAlex Tomas 			ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5674c9de560dSAlex Tomas 						     NULL, &start);
5675c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
5676d3df1453SRitesh Harjani 			mb_debug(sb, "PA:%u:%d:%d\n", i, start,
5677d3df1453SRitesh Harjani 				 pa->pa_len);
5678c9de560dSAlex Tomas 		}
567960bd63d1SSolofo Ramangalahy 		ext4_unlock_group(sb, i);
5680d3df1453SRitesh Harjani 		mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
5681d3df1453SRitesh Harjani 			 grp->bb_fragments);
5682c9de560dSAlex Tomas 	}
5683c9de560dSAlex Tomas }
5684e68cf40cSRitesh Harjani 
5685e68cf40cSRitesh Harjani static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5686e68cf40cSRitesh Harjani {
5687e68cf40cSRitesh Harjani 	struct super_block *sb = ac->ac_sb;
5688e68cf40cSRitesh Harjani 
568995257987SJan Kara 	if (ext4_forced_shutdown(sb))
5690e68cf40cSRitesh Harjani 		return;
5691e68cf40cSRitesh Harjani 
5692d3df1453SRitesh Harjani 	mb_debug(sb, "Can't allocate:"
5693e68cf40cSRitesh Harjani 			" Allocation context details:");
5694d3df1453SRitesh Harjani 	mb_debug(sb, "status %u flags 0x%x",
5695e68cf40cSRitesh Harjani 			ac->ac_status, ac->ac_flags);
5696d3df1453SRitesh Harjani 	mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
5697e68cf40cSRitesh Harjani 			"goal %lu/%lu/%lu@%lu, "
5698e68cf40cSRitesh Harjani 			"best %lu/%lu/%lu@%lu cr %d",
5699e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_group,
5700e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_start,
5701e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_len,
5702e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_logical,
5703e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_group,
5704e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_start,
5705e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_len,
5706e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_logical,
5707e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_group,
5708e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_start,
5709e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_len,
5710e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_logical,
5711e68cf40cSRitesh Harjani 			(int)ac->ac_criteria);
5712d3df1453SRitesh Harjani 	mb_debug(sb, "%u found", ac->ac_found);
5713569f196fSRitesh Harjani 	mb_debug(sb, "used pa: %s, ", ac->ac_pa ? "yes" : "no");
5714569f196fSRitesh Harjani 	if (ac->ac_pa)
5715569f196fSRitesh Harjani 		mb_debug(sb, "pa_type %s\n", ac->ac_pa->pa_type == MB_GROUP_PA ?
5716569f196fSRitesh Harjani 			 "group pa" : "inode pa");
5717e68cf40cSRitesh Harjani 	ext4_mb_show_pa(sb);
5718e68cf40cSRitesh Harjani }
5719c9de560dSAlex Tomas #else
5720e68cf40cSRitesh Harjani static inline void ext4_mb_show_pa(struct super_block *sb)
5721e68cf40cSRitesh Harjani {
5722e68cf40cSRitesh Harjani }
5723c9de560dSAlex Tomas static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5724c9de560dSAlex Tomas {
5725e68cf40cSRitesh Harjani 	ext4_mb_show_pa(ac->ac_sb);
5726c9de560dSAlex Tomas }
5727c9de560dSAlex Tomas #endif
5728c9de560dSAlex Tomas 
5729c9de560dSAlex Tomas /*
5730c9de560dSAlex Tomas  * We use locality group preallocation for small size file. The size of the
5731c9de560dSAlex Tomas  * file is determined by the current size or the resulting size after
5732c9de560dSAlex Tomas  * allocation which ever is larger
5733c9de560dSAlex Tomas  *
5734b713a5ecSTheodore Ts'o  * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
5735c9de560dSAlex Tomas  */
5736c9de560dSAlex Tomas static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
5737c9de560dSAlex Tomas {
5738c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
5739c9de560dSAlex Tomas 	int bsbits = ac->ac_sb->s_blocksize_bits;
5740c9de560dSAlex Tomas 	loff_t size, isize;
5741a9f2a293SJan Kara 	bool inode_pa_eligible, group_pa_eligible;
5742c9de560dSAlex Tomas 
5743c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
5744c9de560dSAlex Tomas 		return;
5745c9de560dSAlex Tomas 
57464ba74d00STheodore Ts'o 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
57474ba74d00STheodore Ts'o 		return;
57484ba74d00STheodore Ts'o 
5749a9f2a293SJan Kara 	group_pa_eligible = sbi->s_mb_group_prealloc > 0;
5750a9f2a293SJan Kara 	inode_pa_eligible = true;
575143bbddc0SBaokun Li 	size = extent_logical_end(sbi, &ac->ac_o_ex);
575250797481STheodore Ts'o 	isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
575350797481STheodore Ts'o 		>> bsbits;
5754c9de560dSAlex Tomas 
5755a9f2a293SJan Kara 	/* No point in using inode preallocation for closed files */
575682dd124cSNikolay Borisov 	if ((size == isize) && !ext4_fs_is_busy(sbi) &&
5757a9f2a293SJan Kara 	    !inode_is_open_for_write(ac->ac_inode))
5758a9f2a293SJan Kara 		inode_pa_eligible = false;
575950797481STheodore Ts'o 
576071780577STheodore Ts'o 	size = max(size, isize);
5761a9f2a293SJan Kara 	/* Don't use group allocation for large files */
5762a9f2a293SJan Kara 	if (size > sbi->s_mb_stream_request)
5763a9f2a293SJan Kara 		group_pa_eligible = false;
5764a9f2a293SJan Kara 
5765a9f2a293SJan Kara 	if (!group_pa_eligible) {
5766a9f2a293SJan Kara 		if (inode_pa_eligible)
57674ba74d00STheodore Ts'o 			ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
5768a9f2a293SJan Kara 		else
5769a9f2a293SJan Kara 			ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
5770c9de560dSAlex Tomas 		return;
57714ba74d00STheodore Ts'o 	}
5772c9de560dSAlex Tomas 
5773c9de560dSAlex Tomas 	BUG_ON(ac->ac_lg != NULL);
5774c9de560dSAlex Tomas 	/*
5775c9de560dSAlex Tomas 	 * locality group prealloc space are per cpu. The reason for having
5776c9de560dSAlex Tomas 	 * per cpu locality group is to reduce the contention between block
5777c9de560dSAlex Tomas 	 * request from multiple CPUs.
5778c9de560dSAlex Tomas 	 */
5779a0b6bc63SChristoph Lameter 	ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
5780c9de560dSAlex Tomas 
5781c9de560dSAlex Tomas 	/* we're going to use group allocation */
5782c9de560dSAlex Tomas 	ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
5783c9de560dSAlex Tomas 
5784c9de560dSAlex Tomas 	/* serialize all allocations in the group */
5785c9de560dSAlex Tomas 	mutex_lock(&ac->ac_lg->lg_mutex);
5786c9de560dSAlex Tomas }
5787c9de560dSAlex Tomas 
5788d73eff68SGuoqing Jiang static noinline_for_stack void
57894ddfef7bSEric Sandeen ext4_mb_initialize_context(struct ext4_allocation_context *ac,
5790c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
5791c9de560dSAlex Tomas {
5792c9de560dSAlex Tomas 	struct super_block *sb = ar->inode->i_sb;
5793c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5794c9de560dSAlex Tomas 	struct ext4_super_block *es = sbi->s_es;
5795c9de560dSAlex Tomas 	ext4_group_t group;
5796498e5f24STheodore Ts'o 	unsigned int len;
5797498e5f24STheodore Ts'o 	ext4_fsblk_t goal;
5798c9de560dSAlex Tomas 	ext4_grpblk_t block;
5799c9de560dSAlex Tomas 
5800c9de560dSAlex Tomas 	/* we can't allocate > group size */
5801c9de560dSAlex Tomas 	len = ar->len;
5802c9de560dSAlex Tomas 
5803c9de560dSAlex Tomas 	/* just a dirty hack to filter too big requests  */
580440ae3487STheodore Ts'o 	if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
580540ae3487STheodore Ts'o 		len = EXT4_CLUSTERS_PER_GROUP(sb);
5806c9de560dSAlex Tomas 
5807c9de560dSAlex Tomas 	/* start searching from the goal */
5808c9de560dSAlex Tomas 	goal = ar->goal;
5809c9de560dSAlex Tomas 	if (goal < le32_to_cpu(es->s_first_data_block) ||
5810c9de560dSAlex Tomas 			goal >= ext4_blocks_count(es))
5811c9de560dSAlex Tomas 		goal = le32_to_cpu(es->s_first_data_block);
5812c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, goal, &group, &block);
5813c9de560dSAlex Tomas 
5814c9de560dSAlex Tomas 	/* set up allocation goals */
5815f5a44db5STheodore Ts'o 	ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
5816c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_CONTINUE;
5817c9de560dSAlex Tomas 	ac->ac_sb = sb;
5818c9de560dSAlex Tomas 	ac->ac_inode = ar->inode;
581953accfa9STheodore Ts'o 	ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
5820c9de560dSAlex Tomas 	ac->ac_o_ex.fe_group = group;
5821c9de560dSAlex Tomas 	ac->ac_o_ex.fe_start = block;
5822c9de560dSAlex Tomas 	ac->ac_o_ex.fe_len = len;
582353accfa9STheodore Ts'o 	ac->ac_g_ex = ac->ac_o_ex;
58247e170922SOjaswin Mujoo 	ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
5825c9de560dSAlex Tomas 	ac->ac_flags = ar->flags;
5826c9de560dSAlex Tomas 
58273cb77bd2Sbrookxu 	/* we have to define context: we'll work with a file or
5828c9de560dSAlex Tomas 	 * locality group. this is a policy, actually */
5829c9de560dSAlex Tomas 	ext4_mb_group_or_file(ac);
5830c9de560dSAlex Tomas 
5831d3df1453SRitesh Harjani 	mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
5832c9de560dSAlex Tomas 			"left: %u/%u, right %u/%u to %swritable\n",
5833c9de560dSAlex Tomas 			(unsigned) ar->len, (unsigned) ar->logical,
5834c9de560dSAlex Tomas 			(unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
5835c9de560dSAlex Tomas 			(unsigned) ar->lleft, (unsigned) ar->pleft,
5836c9de560dSAlex Tomas 			(unsigned) ar->lright, (unsigned) ar->pright,
583782dd124cSNikolay Borisov 			inode_is_open_for_write(ar->inode) ? "" : "non-");
5838c9de560dSAlex Tomas }
5839c9de560dSAlex Tomas 
58406be2ded1SAneesh Kumar K.V static noinline_for_stack void
58416be2ded1SAneesh Kumar K.V ext4_mb_discard_lg_preallocations(struct super_block *sb,
58426be2ded1SAneesh Kumar K.V 					struct ext4_locality_group *lg,
58436be2ded1SAneesh Kumar K.V 					int order, int total_entries)
58446be2ded1SAneesh Kumar K.V {
58456be2ded1SAneesh Kumar K.V 	ext4_group_t group = 0;
58466be2ded1SAneesh Kumar K.V 	struct ext4_buddy e4b;
58470f6bc579SRuan Jinjie 	LIST_HEAD(discard_list);
58486be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa, *tmp;
58496be2ded1SAneesh Kumar K.V 
5850d3df1453SRitesh Harjani 	mb_debug(sb, "discard locality group preallocation\n");
58516be2ded1SAneesh Kumar K.V 
58526be2ded1SAneesh Kumar K.V 	spin_lock(&lg->lg_prealloc_lock);
58536be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
5854a8e38fd3SOjaswin Mujoo 				pa_node.lg_list,
585592e9c58cSMadhuparna Bhowmik 				lockdep_is_held(&lg->lg_prealloc_lock)) {
58566be2ded1SAneesh Kumar K.V 		spin_lock(&pa->pa_lock);
58576be2ded1SAneesh Kumar K.V 		if (atomic_read(&pa->pa_count)) {
58586be2ded1SAneesh Kumar K.V 			/*
58596be2ded1SAneesh Kumar K.V 			 * This is the pa that we just used
58606be2ded1SAneesh Kumar K.V 			 * for block allocation. So don't
58616be2ded1SAneesh Kumar K.V 			 * free that
58626be2ded1SAneesh Kumar K.V 			 */
58636be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
58646be2ded1SAneesh Kumar K.V 			continue;
58656be2ded1SAneesh Kumar K.V 		}
58666be2ded1SAneesh Kumar K.V 		if (pa->pa_deleted) {
58676be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
58686be2ded1SAneesh Kumar K.V 			continue;
58696be2ded1SAneesh Kumar K.V 		}
58706be2ded1SAneesh Kumar K.V 		/* only lg prealloc space */
5871cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_GROUP_PA);
58726be2ded1SAneesh Kumar K.V 
58736be2ded1SAneesh Kumar K.V 		/* seems this one can be freed ... */
587427bc446eSbrookxu 		ext4_mb_mark_pa_deleted(sb, pa);
58756be2ded1SAneesh Kumar K.V 		spin_unlock(&pa->pa_lock);
58766be2ded1SAneesh Kumar K.V 
5877a8e38fd3SOjaswin Mujoo 		list_del_rcu(&pa->pa_node.lg_list);
58786be2ded1SAneesh Kumar K.V 		list_add(&pa->u.pa_tmp_list, &discard_list);
58796be2ded1SAneesh Kumar K.V 
58806be2ded1SAneesh Kumar K.V 		total_entries--;
58816be2ded1SAneesh Kumar K.V 		if (total_entries <= 5) {
58826be2ded1SAneesh Kumar K.V 			/*
58836be2ded1SAneesh Kumar K.V 			 * we want to keep only 5 entries
58846be2ded1SAneesh Kumar K.V 			 * allowing it to grow to 8. This
58856be2ded1SAneesh Kumar K.V 			 * mak sure we don't call discard
58866be2ded1SAneesh Kumar K.V 			 * soon for this list.
58876be2ded1SAneesh Kumar K.V 			 */
58886be2ded1SAneesh Kumar K.V 			break;
58896be2ded1SAneesh Kumar K.V 		}
58906be2ded1SAneesh Kumar K.V 	}
58916be2ded1SAneesh Kumar K.V 	spin_unlock(&lg->lg_prealloc_lock);
58926be2ded1SAneesh Kumar K.V 
58936be2ded1SAneesh Kumar K.V 	list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
58949651e6b2SKonstantin Khlebnikov 		int err;
58956be2ded1SAneesh Kumar K.V 
5896bd86298eSLukas Czerner 		group = ext4_get_group_number(sb, pa->pa_pstart);
58979651e6b2SKonstantin Khlebnikov 		err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
58989651e6b2SKonstantin Khlebnikov 					     GFP_NOFS|__GFP_NOFAIL);
58999651e6b2SKonstantin Khlebnikov 		if (err) {
590054d3adbcSTheodore Ts'o 			ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
59019651e6b2SKonstantin Khlebnikov 				       err, group);
59026be2ded1SAneesh Kumar K.V 			continue;
59036be2ded1SAneesh Kumar K.V 		}
59046be2ded1SAneesh Kumar K.V 		ext4_lock_group(sb, group);
59056be2ded1SAneesh Kumar K.V 		list_del(&pa->pa_group_list);
59063e1e5f50SEric Sandeen 		ext4_mb_release_group_pa(&e4b, pa);
59076be2ded1SAneesh Kumar K.V 		ext4_unlock_group(sb, group);
59086be2ded1SAneesh Kumar K.V 
5909e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
59106be2ded1SAneesh Kumar K.V 		list_del(&pa->u.pa_tmp_list);
59116be2ded1SAneesh Kumar K.V 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
59126be2ded1SAneesh Kumar K.V 	}
59136be2ded1SAneesh Kumar K.V }
59146be2ded1SAneesh Kumar K.V 
59156be2ded1SAneesh Kumar K.V /*
59166be2ded1SAneesh Kumar K.V  * We have incremented pa_count. So it cannot be freed at this
59176be2ded1SAneesh Kumar K.V  * point. Also we hold lg_mutex. So no parallel allocation is
59186be2ded1SAneesh Kumar K.V  * possible from this lg. That means pa_free cannot be updated.
59196be2ded1SAneesh Kumar K.V  *
59206be2ded1SAneesh Kumar K.V  * A parallel ext4_mb_discard_group_preallocations is possible.
59216be2ded1SAneesh Kumar K.V  * which can cause the lg_prealloc_list to be updated.
59226be2ded1SAneesh Kumar K.V  */
59236be2ded1SAneesh Kumar K.V 
59246be2ded1SAneesh Kumar K.V static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
59256be2ded1SAneesh Kumar K.V {
59266be2ded1SAneesh Kumar K.V 	int order, added = 0, lg_prealloc_count = 1;
59276be2ded1SAneesh Kumar K.V 	struct super_block *sb = ac->ac_sb;
59286be2ded1SAneesh Kumar K.V 	struct ext4_locality_group *lg = ac->ac_lg;
59296be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
59306be2ded1SAneesh Kumar K.V 
59316be2ded1SAneesh Kumar K.V 	order = fls(pa->pa_free) - 1;
59326be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
59336be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
59346be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
59356be2ded1SAneesh Kumar K.V 	/* Add the prealloc space to lg */
5936f1167009SNiu Yawei 	spin_lock(&lg->lg_prealloc_lock);
59376be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
5938a8e38fd3SOjaswin Mujoo 				pa_node.lg_list,
593992e9c58cSMadhuparna Bhowmik 				lockdep_is_held(&lg->lg_prealloc_lock)) {
59406be2ded1SAneesh Kumar K.V 		spin_lock(&tmp_pa->pa_lock);
59416be2ded1SAneesh Kumar K.V 		if (tmp_pa->pa_deleted) {
5942e7c9e3e9STheodore Ts'o 			spin_unlock(&tmp_pa->pa_lock);
59436be2ded1SAneesh Kumar K.V 			continue;
59446be2ded1SAneesh Kumar K.V 		}
59456be2ded1SAneesh Kumar K.V 		if (!added && pa->pa_free < tmp_pa->pa_free) {
59466be2ded1SAneesh Kumar K.V 			/* Add to the tail of the previous entry */
5947a8e38fd3SOjaswin Mujoo 			list_add_tail_rcu(&pa->pa_node.lg_list,
5948a8e38fd3SOjaswin Mujoo 						&tmp_pa->pa_node.lg_list);
59496be2ded1SAneesh Kumar K.V 			added = 1;
59506be2ded1SAneesh Kumar K.V 			/*
59516be2ded1SAneesh Kumar K.V 			 * we want to count the total
59526be2ded1SAneesh Kumar K.V 			 * number of entries in the list
59536be2ded1SAneesh Kumar K.V 			 */
59546be2ded1SAneesh Kumar K.V 		}
59556be2ded1SAneesh Kumar K.V 		spin_unlock(&tmp_pa->pa_lock);
59566be2ded1SAneesh Kumar K.V 		lg_prealloc_count++;
59576be2ded1SAneesh Kumar K.V 	}
59586be2ded1SAneesh Kumar K.V 	if (!added)
5959a8e38fd3SOjaswin Mujoo 		list_add_tail_rcu(&pa->pa_node.lg_list,
59606be2ded1SAneesh Kumar K.V 					&lg->lg_prealloc_list[order]);
5961f1167009SNiu Yawei 	spin_unlock(&lg->lg_prealloc_lock);
59626be2ded1SAneesh Kumar K.V 
59636be2ded1SAneesh Kumar K.V 	/* Now trim the list to be not more than 8 elements */
5964ad635507SKemeng Shi 	if (lg_prealloc_count > 8)
59656be2ded1SAneesh Kumar K.V 		ext4_mb_discard_lg_preallocations(sb, lg,
59666be2ded1SAneesh Kumar K.V 						  order, lg_prealloc_count);
59676be2ded1SAneesh Kumar K.V }
59686be2ded1SAneesh Kumar K.V 
5969c9de560dSAlex Tomas /*
5970c9de560dSAlex Tomas  * release all resource we used in allocation
5971c9de560dSAlex Tomas  */
597211fd1a5dSKemeng Shi static void ext4_mb_release_context(struct ext4_allocation_context *ac)
5973c9de560dSAlex Tomas {
597453accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
59756be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa = ac->ac_pa;
59766be2ded1SAneesh Kumar K.V 	if (pa) {
5977cc0fb9adSAneesh Kumar K.V 		if (pa->pa_type == MB_GROUP_PA) {
5978c9de560dSAlex Tomas 			/* see comment in ext4_mb_use_group_pa() */
59796be2ded1SAneesh Kumar K.V 			spin_lock(&pa->pa_lock);
598053accfa9STheodore Ts'o 			pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
598153accfa9STheodore Ts'o 			pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
59826be2ded1SAneesh Kumar K.V 			pa->pa_free -= ac->ac_b_ex.fe_len;
59836be2ded1SAneesh Kumar K.V 			pa->pa_len -= ac->ac_b_ex.fe_len;
59846be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
598566d5e027Sbrookxu 
59866be2ded1SAneesh Kumar K.V 			/*
59876be2ded1SAneesh Kumar K.V 			 * We want to add the pa to the right bucket.
59886be2ded1SAneesh Kumar K.V 			 * Remove it from the list and while adding
59896be2ded1SAneesh Kumar K.V 			 * make sure the list to which we are adding
599044183d42SAmir Goldstein 			 * doesn't grow big.
59916be2ded1SAneesh Kumar K.V 			 */
599266d5e027Sbrookxu 			if (likely(pa->pa_free)) {
5993a8e38fd3SOjaswin Mujoo 				spin_lock(pa->pa_node_lock.lg_lock);
5994a8e38fd3SOjaswin Mujoo 				list_del_rcu(&pa->pa_node.lg_list);
5995a8e38fd3SOjaswin Mujoo 				spin_unlock(pa->pa_node_lock.lg_lock);
59966be2ded1SAneesh Kumar K.V 				ext4_mb_add_n_trim(ac);
5997c9de560dSAlex Tomas 			}
599866d5e027Sbrookxu 		}
599927bc446eSbrookxu 
60006be2ded1SAneesh Kumar K.V 		ext4_mb_put_pa(ac, ac->ac_sb, pa);
6001c9de560dSAlex Tomas 	}
6002c9de560dSAlex Tomas 	if (ac->ac_bitmap_page)
600309cbfeafSKirill A. Shutemov 		put_page(ac->ac_bitmap_page);
6004c9de560dSAlex Tomas 	if (ac->ac_buddy_page)
600509cbfeafSKirill A. Shutemov 		put_page(ac->ac_buddy_page);
6006c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
6007c9de560dSAlex Tomas 		mutex_unlock(&ac->ac_lg->lg_mutex);
6008c9de560dSAlex Tomas 	ext4_mb_collect_stats(ac);
6009c9de560dSAlex Tomas }
6010c9de560dSAlex Tomas 
6011c9de560dSAlex Tomas static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
6012c9de560dSAlex Tomas {
60138df9675fSTheodore Ts'o 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
6014c9de560dSAlex Tomas 	int ret;
60158c80fb31SChunguang Xu 	int freed = 0, busy = 0;
60168c80fb31SChunguang Xu 	int retry = 0;
6017c9de560dSAlex Tomas 
60189bffad1eSTheodore Ts'o 	trace_ext4_mb_discard_preallocations(sb, needed);
60198c80fb31SChunguang Xu 
60208c80fb31SChunguang Xu 	if (needed == 0)
60218c80fb31SChunguang Xu 		needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
60228c80fb31SChunguang Xu  repeat:
60238df9675fSTheodore Ts'o 	for (i = 0; i < ngroups && needed > 0; i++) {
60248c80fb31SChunguang Xu 		ret = ext4_mb_discard_group_preallocations(sb, i, &busy);
6025c9de560dSAlex Tomas 		freed += ret;
6026c9de560dSAlex Tomas 		needed -= ret;
60278c80fb31SChunguang Xu 		cond_resched();
60288c80fb31SChunguang Xu 	}
60298c80fb31SChunguang Xu 
60308c80fb31SChunguang Xu 	if (needed > 0 && busy && ++retry < 3) {
60318c80fb31SChunguang Xu 		busy = 0;
60328c80fb31SChunguang Xu 		goto repeat;
6033c9de560dSAlex Tomas 	}
6034c9de560dSAlex Tomas 
6035c9de560dSAlex Tomas 	return freed;
6036c9de560dSAlex Tomas }
6037c9de560dSAlex Tomas 
6038cf5e2ca6SRitesh Harjani static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
603907b5b8e1SRitesh Harjani 			struct ext4_allocation_context *ac, u64 *seq)
6040cf5e2ca6SRitesh Harjani {
6041cf5e2ca6SRitesh Harjani 	int freed;
604207b5b8e1SRitesh Harjani 	u64 seq_retry = 0;
604307b5b8e1SRitesh Harjani 	bool ret = false;
6044cf5e2ca6SRitesh Harjani 
6045cf5e2ca6SRitesh Harjani 	freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
604607b5b8e1SRitesh Harjani 	if (freed) {
604707b5b8e1SRitesh Harjani 		ret = true;
604807b5b8e1SRitesh Harjani 		goto out_dbg;
604907b5b8e1SRitesh Harjani 	}
605007b5b8e1SRitesh Harjani 	seq_retry = ext4_get_discard_pa_seq_sum();
605199377830SRitesh Harjani 	if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
605299377830SRitesh Harjani 		ac->ac_flags |= EXT4_MB_STRICT_CHECK;
605307b5b8e1SRitesh Harjani 		*seq = seq_retry;
605407b5b8e1SRitesh Harjani 		ret = true;
605507b5b8e1SRitesh Harjani 	}
605607b5b8e1SRitesh Harjani 
605707b5b8e1SRitesh Harjani out_dbg:
605807b5b8e1SRitesh Harjani 	mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
605907b5b8e1SRitesh Harjani 	return ret;
6060cf5e2ca6SRitesh Harjani }
6061cf5e2ca6SRitesh Harjani 
6062ad78b5efSKemeng Shi /*
6063ad78b5efSKemeng Shi  * Simple allocator for Ext4 fast commit replay path. It searches for blocks
6064ad78b5efSKemeng Shi  * linearly starting at the goal block and also excludes the blocks which
6065ad78b5efSKemeng Shi  * are going to be in use after fast commit replay.
6066ad78b5efSKemeng Shi  */
6067ad78b5efSKemeng Shi static ext4_fsblk_t
6068ad78b5efSKemeng Shi ext4_mb_new_blocks_simple(struct ext4_allocation_request *ar, int *errp)
6069ad78b5efSKemeng Shi {
6070ad78b5efSKemeng Shi 	struct buffer_head *bitmap_bh;
6071ad78b5efSKemeng Shi 	struct super_block *sb = ar->inode->i_sb;
6072ad78b5efSKemeng Shi 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6073ad78b5efSKemeng Shi 	ext4_group_t group, nr;
6074ad78b5efSKemeng Shi 	ext4_grpblk_t blkoff;
6075ad78b5efSKemeng Shi 	ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
6076ad78b5efSKemeng Shi 	ext4_grpblk_t i = 0;
6077ad78b5efSKemeng Shi 	ext4_fsblk_t goal, block;
607879ebf48cSLu Hongfei 	struct ext4_super_block *es = sbi->s_es;
6079ad78b5efSKemeng Shi 
6080ad78b5efSKemeng Shi 	goal = ar->goal;
6081ad78b5efSKemeng Shi 	if (goal < le32_to_cpu(es->s_first_data_block) ||
6082ad78b5efSKemeng Shi 			goal >= ext4_blocks_count(es))
6083ad78b5efSKemeng Shi 		goal = le32_to_cpu(es->s_first_data_block);
6084ad78b5efSKemeng Shi 
6085ad78b5efSKemeng Shi 	ar->len = 0;
6086ad78b5efSKemeng Shi 	ext4_get_group_no_and_offset(sb, goal, &group, &blkoff);
6087ad78b5efSKemeng Shi 	for (nr = ext4_get_groups_count(sb); nr > 0; nr--) {
6088ad78b5efSKemeng Shi 		bitmap_bh = ext4_read_block_bitmap(sb, group);
6089ad78b5efSKemeng Shi 		if (IS_ERR(bitmap_bh)) {
6090ad78b5efSKemeng Shi 			*errp = PTR_ERR(bitmap_bh);
6091ad78b5efSKemeng Shi 			pr_warn("Failed to read block bitmap\n");
6092ad78b5efSKemeng Shi 			return 0;
6093ad78b5efSKemeng Shi 		}
6094ad78b5efSKemeng Shi 
6095ad78b5efSKemeng Shi 		while (1) {
6096ad78b5efSKemeng Shi 			i = mb_find_next_zero_bit(bitmap_bh->b_data, max,
6097ad78b5efSKemeng Shi 						blkoff);
6098ad78b5efSKemeng Shi 			if (i >= max)
6099ad78b5efSKemeng Shi 				break;
6100ad78b5efSKemeng Shi 			if (ext4_fc_replay_check_excluded(sb,
6101ad78b5efSKemeng Shi 				ext4_group_first_block_no(sb, group) +
6102ad78b5efSKemeng Shi 				EXT4_C2B(sbi, i))) {
6103ad78b5efSKemeng Shi 				blkoff = i + 1;
6104ad78b5efSKemeng Shi 			} else
6105ad78b5efSKemeng Shi 				break;
6106ad78b5efSKemeng Shi 		}
6107ad78b5efSKemeng Shi 		brelse(bitmap_bh);
6108ad78b5efSKemeng Shi 		if (i < max)
6109ad78b5efSKemeng Shi 			break;
6110ad78b5efSKemeng Shi 
6111ad78b5efSKemeng Shi 		if (++group >= ext4_get_groups_count(sb))
6112ad78b5efSKemeng Shi 			group = 0;
6113ad78b5efSKemeng Shi 
6114ad78b5efSKemeng Shi 		blkoff = 0;
6115ad78b5efSKemeng Shi 	}
6116ad78b5efSKemeng Shi 
6117ad78b5efSKemeng Shi 	if (i >= max) {
6118ad78b5efSKemeng Shi 		*errp = -ENOSPC;
6119ad78b5efSKemeng Shi 		return 0;
6120ad78b5efSKemeng Shi 	}
6121ad78b5efSKemeng Shi 
6122ad78b5efSKemeng Shi 	block = ext4_group_first_block_no(sb, group) + EXT4_C2B(sbi, i);
6123d2f7cf40SKemeng Shi 	ext4_mb_mark_bb(sb, block, 1, true);
6124ad78b5efSKemeng Shi 	ar->len = 1;
6125ad78b5efSKemeng Shi 
6126ad78b5efSKemeng Shi 	return block;
6127ad78b5efSKemeng Shi }
61288016e29fSHarshad Shirwadkar 
6129c9de560dSAlex Tomas /*
6130c9de560dSAlex Tomas  * Main entry point into mballoc to allocate blocks
6131c9de560dSAlex Tomas  * it tries to use preallocation first, then falls back
6132c9de560dSAlex Tomas  * to usual allocation
6133c9de560dSAlex Tomas  */
6134c9de560dSAlex Tomas ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
6135c9de560dSAlex Tomas 				struct ext4_allocation_request *ar, int *errp)
6136c9de560dSAlex Tomas {
6137256bdb49SEric Sandeen 	struct ext4_allocation_context *ac = NULL;
6138c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
6139c9de560dSAlex Tomas 	struct super_block *sb;
6140c9de560dSAlex Tomas 	ext4_fsblk_t block = 0;
614160e58e0fSMingming Cao 	unsigned int inquota = 0;
614253accfa9STheodore Ts'o 	unsigned int reserv_clstrs = 0;
614380fa46d6STheodore Ts'o 	int retries = 0;
614407b5b8e1SRitesh Harjani 	u64 seq;
6145c9de560dSAlex Tomas 
6146b10a44c3STheodore Ts'o 	might_sleep();
6147c9de560dSAlex Tomas 	sb = ar->inode->i_sb;
6148c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
6149c9de560dSAlex Tomas 
61509bffad1eSTheodore Ts'o 	trace_ext4_request_blocks(ar);
61518016e29fSHarshad Shirwadkar 	if (sbi->s_mount_state & EXT4_FC_REPLAY)
6152ad78b5efSKemeng Shi 		return ext4_mb_new_blocks_simple(ar, errp);
6153ba80b101STheodore Ts'o 
615445dc63e7SDmitry Monakhov 	/* Allow to use superuser reservation for quota file */
615502749a4cSTahsin Erdogan 	if (ext4_is_quota_file(ar->inode))
615645dc63e7SDmitry Monakhov 		ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
615745dc63e7SDmitry Monakhov 
6158e3cf5d5dSTheodore Ts'o 	if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
615960e58e0fSMingming Cao 		/* Without delayed allocation we need to verify
616060e58e0fSMingming Cao 		 * there is enough free blocks to do block allocation
616160e58e0fSMingming Cao 		 * and verify allocation doesn't exceed the quota limits.
6162d2a17637SMingming Cao 		 */
616355f020dbSAllison Henderson 		while (ar->len &&
6164e7d5f315STheodore Ts'o 			ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
616555f020dbSAllison Henderson 
6166030ba6bcSAneesh Kumar K.V 			/* let others to free the space */
6167bb8b20edSLukas Czerner 			cond_resched();
6168030ba6bcSAneesh Kumar K.V 			ar->len = ar->len >> 1;
6169030ba6bcSAneesh Kumar K.V 		}
6170030ba6bcSAneesh Kumar K.V 		if (!ar->len) {
6171bbc4ec77SRitesh Harjani 			ext4_mb_show_pa(sb);
617207031431SMingming Cao 			*errp = -ENOSPC;
617307031431SMingming Cao 			return 0;
617407031431SMingming Cao 		}
617553accfa9STheodore Ts'o 		reserv_clstrs = ar->len;
617655f020dbSAllison Henderson 		if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
617753accfa9STheodore Ts'o 			dquot_alloc_block_nofail(ar->inode,
617853accfa9STheodore Ts'o 						 EXT4_C2B(sbi, ar->len));
617955f020dbSAllison Henderson 		} else {
618055f020dbSAllison Henderson 			while (ar->len &&
618153accfa9STheodore Ts'o 				dquot_alloc_block(ar->inode,
618253accfa9STheodore Ts'o 						  EXT4_C2B(sbi, ar->len))) {
618355f020dbSAllison Henderson 
6184c9de560dSAlex Tomas 				ar->flags |= EXT4_MB_HINT_NOPREALLOC;
6185c9de560dSAlex Tomas 				ar->len--;
6186c9de560dSAlex Tomas 			}
618755f020dbSAllison Henderson 		}
618860e58e0fSMingming Cao 		inquota = ar->len;
6189c9de560dSAlex Tomas 		if (ar->len == 0) {
6190c9de560dSAlex Tomas 			*errp = -EDQUOT;
61916c7a120aSAditya Kali 			goto out;
6192c9de560dSAlex Tomas 		}
619360e58e0fSMingming Cao 	}
6194d2a17637SMingming Cao 
619585556c9aSWei Yongjun 	ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
6196833576b3STheodore Ts'o 	if (!ac) {
6197363d4251SShen Feng 		ar->len = 0;
6198256bdb49SEric Sandeen 		*errp = -ENOMEM;
61996c7a120aSAditya Kali 		goto out;
6200256bdb49SEric Sandeen 	}
6201256bdb49SEric Sandeen 
6202d73eff68SGuoqing Jiang 	ext4_mb_initialize_context(ac, ar);
6203c9de560dSAlex Tomas 
6204256bdb49SEric Sandeen 	ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
620581198536SRitesh Harjani 	seq = this_cpu_read(discard_pa_seq);
6206256bdb49SEric Sandeen 	if (!ext4_mb_use_preallocated(ac)) {
6207256bdb49SEric Sandeen 		ac->ac_op = EXT4_MB_HISTORY_ALLOC;
6208256bdb49SEric Sandeen 		ext4_mb_normalize_request(ac, ar);
620953f86b17SRitesh Harjani 
621053f86b17SRitesh Harjani 		*errp = ext4_mb_pa_alloc(ac);
621153f86b17SRitesh Harjani 		if (*errp)
621253f86b17SRitesh Harjani 			goto errout;
6213c9de560dSAlex Tomas repeat:
6214c9de560dSAlex Tomas 		/* allocate space in core */
62156c7a120aSAditya Kali 		*errp = ext4_mb_regular_allocator(ac);
621653f86b17SRitesh Harjani 		/*
621753f86b17SRitesh Harjani 		 * pa allocated above is added to grp->bb_prealloc_list only
621853f86b17SRitesh Harjani 		 * when we were able to allocate some block i.e. when
621953f86b17SRitesh Harjani 		 * ac->ac_status == AC_STATUS_FOUND.
622053f86b17SRitesh Harjani 		 * And error from above mean ac->ac_status != AC_STATUS_FOUND
622153f86b17SRitesh Harjani 		 * So we have to free this pa here itself.
622253f86b17SRitesh Harjani 		 */
62232c00ef3eSAlexey Khoroshilov 		if (*errp) {
622482089725SOjaswin Mujoo 			ext4_mb_pa_put_free(ac);
62252c00ef3eSAlexey Khoroshilov 			ext4_discard_allocated_blocks(ac);
62262c00ef3eSAlexey Khoroshilov 			goto errout;
62272c00ef3eSAlexey Khoroshilov 		}
622853f86b17SRitesh Harjani 		if (ac->ac_status == AC_STATUS_FOUND &&
622953f86b17SRitesh Harjani 			ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
623082089725SOjaswin Mujoo 			ext4_mb_pa_put_free(ac);
6231c9de560dSAlex Tomas 	}
6232256bdb49SEric Sandeen 	if (likely(ac->ac_status == AC_STATUS_FOUND)) {
623353accfa9STheodore Ts'o 		*errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
6234554a5cccSVegard Nossum 		if (*errp) {
6235b844167eSCurt Wohlgemuth 			ext4_discard_allocated_blocks(ac);
62366d138cedSEric Sandeen 			goto errout;
62376d138cedSEric Sandeen 		} else {
6238256bdb49SEric Sandeen 			block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
6239256bdb49SEric Sandeen 			ar->len = ac->ac_b_ex.fe_len;
6240519deca0SAneesh Kumar K.V 		}
6241c9de560dSAlex Tomas 	} else {
624280fa46d6STheodore Ts'o 		if (++retries < 3 &&
624380fa46d6STheodore Ts'o 		    ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
6244c9de560dSAlex Tomas 			goto repeat;
624553f86b17SRitesh Harjani 		/*
624653f86b17SRitesh Harjani 		 * If block allocation fails then the pa allocated above
624753f86b17SRitesh Harjani 		 * needs to be freed here itself.
624853f86b17SRitesh Harjani 		 */
624982089725SOjaswin Mujoo 		ext4_mb_pa_put_free(ac);
6250c9de560dSAlex Tomas 		*errp = -ENOSPC;
62516c7a120aSAditya Kali 	}
62526c7a120aSAditya Kali 
62536c7a120aSAditya Kali 	if (*errp) {
6254aaae558dSKemeng Shi errout:
6255256bdb49SEric Sandeen 		ac->ac_b_ex.fe_len = 0;
6256c9de560dSAlex Tomas 		ar->len = 0;
6257256bdb49SEric Sandeen 		ext4_mb_show_ac(ac);
6258c9de560dSAlex Tomas 	}
6259256bdb49SEric Sandeen 	ext4_mb_release_context(ac);
6260363d4251SShen Feng 	kmem_cache_free(ext4_ac_cachep, ac);
6261aaae558dSKemeng Shi out:
626260e58e0fSMingming Cao 	if (inquota && ar->len < inquota)
626353accfa9STheodore Ts'o 		dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
62640087d9fbSAneesh Kumar K.V 	if (!ar->len) {
6265e3cf5d5dSTheodore Ts'o 		if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
62660087d9fbSAneesh Kumar K.V 			/* release all the reserved blocks if non delalloc */
626757042651STheodore Ts'o 			percpu_counter_sub(&sbi->s_dirtyclusters_counter,
626853accfa9STheodore Ts'o 						reserv_clstrs);
62690087d9fbSAneesh Kumar K.V 	}
6270c9de560dSAlex Tomas 
62719bffad1eSTheodore Ts'o 	trace_ext4_allocate_blocks(ar, (unsigned long long)block);
6272ba80b101STheodore Ts'o 
6273c9de560dSAlex Tomas 	return block;
6274c9de560dSAlex Tomas }
6275c9de560dSAlex Tomas 
6276c894058dSAneesh Kumar K.V /*
6277c894058dSAneesh Kumar K.V  * We can merge two free data extents only if the physical blocks
6278c894058dSAneesh Kumar K.V  * are contiguous, AND the extents were freed by the same transaction,
6279c894058dSAneesh Kumar K.V  * AND the blocks are associated with the same group.
6280c894058dSAneesh Kumar K.V  */
6281a0154344SDaeho Jeong static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
6282a0154344SDaeho Jeong 					struct ext4_free_data *entry,
6283a0154344SDaeho Jeong 					struct ext4_free_data *new_entry,
6284a0154344SDaeho Jeong 					struct rb_root *entry_rb_root)
6285c894058dSAneesh Kumar K.V {
6286a0154344SDaeho Jeong 	if ((entry->efd_tid != new_entry->efd_tid) ||
6287a0154344SDaeho Jeong 	    (entry->efd_group != new_entry->efd_group))
6288a0154344SDaeho Jeong 		return;
6289a0154344SDaeho Jeong 	if (entry->efd_start_cluster + entry->efd_count ==
6290a0154344SDaeho Jeong 	    new_entry->efd_start_cluster) {
6291a0154344SDaeho Jeong 		new_entry->efd_start_cluster = entry->efd_start_cluster;
6292a0154344SDaeho Jeong 		new_entry->efd_count += entry->efd_count;
6293a0154344SDaeho Jeong 	} else if (new_entry->efd_start_cluster + new_entry->efd_count ==
6294a0154344SDaeho Jeong 		   entry->efd_start_cluster) {
6295a0154344SDaeho Jeong 		new_entry->efd_count += entry->efd_count;
6296a0154344SDaeho Jeong 	} else
6297a0154344SDaeho Jeong 		return;
6298a0154344SDaeho Jeong 	spin_lock(&sbi->s_md_lock);
6299a0154344SDaeho Jeong 	list_del(&entry->efd_list);
6300a0154344SDaeho Jeong 	spin_unlock(&sbi->s_md_lock);
6301a0154344SDaeho Jeong 	rb_erase(&entry->efd_node, entry_rb_root);
6302a0154344SDaeho Jeong 	kmem_cache_free(ext4_free_data_cachep, entry);
6303c894058dSAneesh Kumar K.V }
6304c894058dSAneesh Kumar K.V 
630585b67ffbSKemeng Shi static noinline_for_stack void
63064ddfef7bSEric Sandeen ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
63077a2fcbf7SAneesh Kumar K.V 		      struct ext4_free_data *new_entry)
6308c9de560dSAlex Tomas {
6309e29136f8STheodore Ts'o 	ext4_group_t group = e4b->bd_group;
631084130193STheodore Ts'o 	ext4_grpblk_t cluster;
6311d08854f5STheodore Ts'o 	ext4_grpblk_t clusters = new_entry->efd_count;
63127a2fcbf7SAneesh Kumar K.V 	struct ext4_free_data *entry;
6313c9de560dSAlex Tomas 	struct ext4_group_info *db = e4b->bd_info;
6314c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
6315c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6316c894058dSAneesh Kumar K.V 	struct rb_node **n = &db->bb_free_root.rb_node, *node;
6317c894058dSAneesh Kumar K.V 	struct rb_node *parent = NULL, *new_node;
6318c894058dSAneesh Kumar K.V 
63190390131bSFrank Mayhar 	BUG_ON(!ext4_handle_valid(handle));
6320c9de560dSAlex Tomas 	BUG_ON(e4b->bd_bitmap_page == NULL);
6321c9de560dSAlex Tomas 	BUG_ON(e4b->bd_buddy_page == NULL);
6322c9de560dSAlex Tomas 
632318aadd47SBobi Jam 	new_node = &new_entry->efd_node;
632418aadd47SBobi Jam 	cluster = new_entry->efd_start_cluster;
6325c9de560dSAlex Tomas 
6326c894058dSAneesh Kumar K.V 	if (!*n) {
6327c894058dSAneesh Kumar K.V 		/* first free block exent. We need to
6328c894058dSAneesh Kumar K.V 		   protect buddy cache from being freed,
6329c9de560dSAlex Tomas 		 * otherwise we'll refresh it from
6330c9de560dSAlex Tomas 		 * on-disk bitmap and lose not-yet-available
6331c9de560dSAlex Tomas 		 * blocks */
633209cbfeafSKirill A. Shutemov 		get_page(e4b->bd_buddy_page);
633309cbfeafSKirill A. Shutemov 		get_page(e4b->bd_bitmap_page);
6334c894058dSAneesh Kumar K.V 	}
6335c894058dSAneesh Kumar K.V 	while (*n) {
6336c894058dSAneesh Kumar K.V 		parent = *n;
633718aadd47SBobi Jam 		entry = rb_entry(parent, struct ext4_free_data, efd_node);
633818aadd47SBobi Jam 		if (cluster < entry->efd_start_cluster)
6339c894058dSAneesh Kumar K.V 			n = &(*n)->rb_left;
634018aadd47SBobi Jam 		else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
6341c894058dSAneesh Kumar K.V 			n = &(*n)->rb_right;
6342c894058dSAneesh Kumar K.V 		else {
6343e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, group, 0,
634484130193STheodore Ts'o 				ext4_group_first_block_no(sb, group) +
634584130193STheodore Ts'o 				EXT4_C2B(sbi, cluster),
6346e29136f8STheodore Ts'o 				"Block already on to-be-freed list");
6347cca41553SChunguang Xu 			kmem_cache_free(ext4_free_data_cachep, new_entry);
634885b67ffbSKemeng Shi 			return;
6349c9de560dSAlex Tomas 		}
6350c9de560dSAlex Tomas 	}
6351c9de560dSAlex Tomas 
6352c894058dSAneesh Kumar K.V 	rb_link_node(new_node, parent, n);
6353c894058dSAneesh Kumar K.V 	rb_insert_color(new_node, &db->bb_free_root);
6354c894058dSAneesh Kumar K.V 
6355c894058dSAneesh Kumar K.V 	/* Now try to see the extent can be merged to left and right */
6356c894058dSAneesh Kumar K.V 	node = rb_prev(new_node);
6357c894058dSAneesh Kumar K.V 	if (node) {
635818aadd47SBobi Jam 		entry = rb_entry(node, struct ext4_free_data, efd_node);
6359a0154344SDaeho Jeong 		ext4_try_merge_freed_extent(sbi, entry, new_entry,
6360a0154344SDaeho Jeong 					    &(db->bb_free_root));
6361c9de560dSAlex Tomas 	}
6362c894058dSAneesh Kumar K.V 
6363c894058dSAneesh Kumar K.V 	node = rb_next(new_node);
6364c894058dSAneesh Kumar K.V 	if (node) {
636518aadd47SBobi Jam 		entry = rb_entry(node, struct ext4_free_data, efd_node);
6366a0154344SDaeho Jeong 		ext4_try_merge_freed_extent(sbi, entry, new_entry,
6367a0154344SDaeho Jeong 					    &(db->bb_free_root));
6368c894058dSAneesh Kumar K.V 	}
6369a0154344SDaeho Jeong 
6370d08854f5STheodore Ts'o 	spin_lock(&sbi->s_md_lock);
6371ce774e53SJinke Han 	list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list[new_entry->efd_tid & 1]);
6372d08854f5STheodore Ts'o 	sbi->s_mb_free_pending += clusters;
6373d08854f5STheodore Ts'o 	spin_unlock(&sbi->s_md_lock);
6374c9de560dSAlex Tomas }
6375c9de560dSAlex Tomas 
63768016e29fSHarshad Shirwadkar static void ext4_free_blocks_simple(struct inode *inode, ext4_fsblk_t block,
63778016e29fSHarshad Shirwadkar 					unsigned long count)
63788016e29fSHarshad Shirwadkar {
63798016e29fSHarshad Shirwadkar 	struct super_block *sb = inode->i_sb;
63808016e29fSHarshad Shirwadkar 	ext4_group_t group;
63818016e29fSHarshad Shirwadkar 	ext4_grpblk_t blkoff;
63828016e29fSHarshad Shirwadkar 
63838016e29fSHarshad Shirwadkar 	ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
6384c431d386SKemeng Shi 	ext4_mb_mark_context(NULL, sb, false, group, blkoff, count,
6385c431d386SKemeng Shi 			     EXT4_MB_BITMAP_MARKED_CHECK |
6386c431d386SKemeng Shi 			     EXT4_MB_SYNC_UPDATE,
6387c431d386SKemeng Shi 			     NULL);
63888016e29fSHarshad Shirwadkar }
63898016e29fSHarshad Shirwadkar 
639044338711STheodore Ts'o /**
63918ac3939dSRitesh Harjani  * ext4_mb_clear_bb() -- helper function for freeing blocks.
63928ac3939dSRitesh Harjani  *			Used by ext4_free_blocks()
639344338711STheodore Ts'o  * @handle:		handle for this transaction
639444338711STheodore Ts'o  * @inode:		inode
6395c60990b3STheodore Ts'o  * @block:		starting physical block to be freed
6396c60990b3STheodore Ts'o  * @count:		number of blocks to be freed
63975def1360SYongqiang Yang  * @flags:		flags used by ext4_free_blocks
6398c9de560dSAlex Tomas  */
63998ac3939dSRitesh Harjani static void ext4_mb_clear_bb(handle_t *handle, struct inode *inode,
64008ac3939dSRitesh Harjani 			       ext4_fsblk_t block, unsigned long count,
64018ac3939dSRitesh Harjani 			       int flags)
6402c9de560dSAlex Tomas {
6403c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
64045354b2afSTheodore Ts'o 	struct ext4_group_info *grp;
6405498e5f24STheodore Ts'o 	unsigned int overflow;
6406c9de560dSAlex Tomas 	ext4_grpblk_t bit;
6407c9de560dSAlex Tomas 	ext4_group_t block_group;
6408c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
6409c9de560dSAlex Tomas 	struct ext4_buddy e4b;
641084130193STheodore Ts'o 	unsigned int count_clusters;
6411c9de560dSAlex Tomas 	int err = 0;
641238b8f70cSKemeng Shi 	int mark_flags = 0;
641338b8f70cSKemeng Shi 	ext4_grpblk_t changed;
6414c9de560dSAlex Tomas 
64158016e29fSHarshad Shirwadkar 	sbi = EXT4_SB(sb);
64168016e29fSHarshad Shirwadkar 
64171e1c2b86SLukas Czerner 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
64181e1c2b86SLukas Czerner 	    !ext4_inode_block_valid(inode, block, count)) {
64191e1c2b86SLukas Czerner 		ext4_error(sb, "Freeing blocks in system zone - "
64201e1c2b86SLukas Czerner 			   "Block = %llu, count = %lu", block, count);
64211e1c2b86SLukas Czerner 		/* err = 0. ext4_std_error should be a no op */
642233e728c6SKemeng Shi 		goto error_out;
64231e1c2b86SLukas Czerner 	}
64241e1c2b86SLukas Czerner 	flags |= EXT4_FREE_BLOCKS_VALIDATED;
64251e1c2b86SLukas Czerner 
6426c9de560dSAlex Tomas do_more:
6427c9de560dSAlex Tomas 	overflow = 0;
6428c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
6429c9de560dSAlex Tomas 
64305354b2afSTheodore Ts'o 	grp = ext4_get_group_info(sb, block_group);
64315354b2afSTheodore Ts'o 	if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
6432163a203dSDarrick J. Wong 		return;
6433163a203dSDarrick J. Wong 
6434c9de560dSAlex Tomas 	/*
6435c9de560dSAlex Tomas 	 * Check to see if we are freeing blocks across a group
6436c9de560dSAlex Tomas 	 * boundary.
6437c9de560dSAlex Tomas 	 */
643884130193STheodore Ts'o 	if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
643984130193STheodore Ts'o 		overflow = EXT4_C2B(sbi, bit) + count -
644084130193STheodore Ts'o 			EXT4_BLOCKS_PER_GROUP(sb);
6441c9de560dSAlex Tomas 		count -= overflow;
64421e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
64431e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6444c9de560dSAlex Tomas 	}
6445810da240SLukas Czerner 	count_clusters = EXT4_NUM_B2C(sbi, count);
644633e728c6SKemeng Shi 	trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
644733e728c6SKemeng Shi 
644833e728c6SKemeng Shi 	/* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
644933e728c6SKemeng Shi 	err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
645033e728c6SKemeng Shi 				     GFP_NOFS|__GFP_NOFAIL);
645133e728c6SKemeng Shi 	if (err)
645233e728c6SKemeng Shi 		goto error_out;
6453c9de560dSAlex Tomas 
64541e1c2b86SLukas Czerner 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
64551e1c2b86SLukas Czerner 	    !ext4_inode_block_valid(inode, block, count)) {
645612062dddSEric Sandeen 		ext4_error(sb, "Freeing blocks in system zone - "
64570610b6e9STheodore Ts'o 			   "Block = %llu, count = %lu", block, count);
6458519deca0SAneesh Kumar K.V 		/* err = 0. ext4_std_error should be a no op */
645933e728c6SKemeng Shi 		goto error_clean;
646033e728c6SKemeng Shi 	}
646133e728c6SKemeng Shi 
6462c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
646338b8f70cSKemeng Shi 	mark_flags |= EXT4_MB_BITMAP_MARKED_CHECK;
6464c9de560dSAlex Tomas #endif
646538b8f70cSKemeng Shi 	err = ext4_mb_mark_context(handle, sb, false, block_group, bit,
646638b8f70cSKemeng Shi 				   count_clusters, mark_flags, &changed);
6467c9de560dSAlex Tomas 
646833e728c6SKemeng Shi 
646938b8f70cSKemeng Shi 	if (err && changed == 0)
647038b8f70cSKemeng Shi 		goto error_clean;
647133e728c6SKemeng Shi 
647238b8f70cSKemeng Shi #ifdef AGGRESSIVE_CHECK
647338b8f70cSKemeng Shi 	BUG_ON(changed != count_clusters);
647438b8f70cSKemeng Shi #endif
6475e6362609STheodore Ts'o 
6476f96c450dSDaeho Jeong 	/*
6477f96c450dSDaeho Jeong 	 * We need to make sure we don't reuse the freed block until after the
6478f96c450dSDaeho Jeong 	 * transaction is committed. We make an exception if the inode is to be
6479f96c450dSDaeho Jeong 	 * written in writeback mode since writeback mode has weak data
6480f96c450dSDaeho Jeong 	 * consistency guarantees.
6481f96c450dSDaeho Jeong 	 */
6482f96c450dSDaeho Jeong 	if (ext4_handle_valid(handle) &&
6483f96c450dSDaeho Jeong 	    ((flags & EXT4_FREE_BLOCKS_METADATA) ||
6484f96c450dSDaeho Jeong 	     !ext4_should_writeback_data(inode))) {
64857a2fcbf7SAneesh Kumar K.V 		struct ext4_free_data *new_entry;
64867a2fcbf7SAneesh Kumar K.V 		/*
64877444a072SMichal Hocko 		 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
64887444a072SMichal Hocko 		 * to fail.
64897a2fcbf7SAneesh Kumar K.V 		 */
64907444a072SMichal Hocko 		new_entry = kmem_cache_alloc(ext4_free_data_cachep,
64917444a072SMichal Hocko 				GFP_NOFS|__GFP_NOFAIL);
649218aadd47SBobi Jam 		new_entry->efd_start_cluster = bit;
649318aadd47SBobi Jam 		new_entry->efd_group = block_group;
649418aadd47SBobi Jam 		new_entry->efd_count = count_clusters;
649518aadd47SBobi Jam 		new_entry->efd_tid = handle->h_transaction->t_tid;
6496955ce5f5SAneesh Kumar K.V 
64977a2fcbf7SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
64987a2fcbf7SAneesh Kumar K.V 		ext4_mb_free_metadata(handle, &e4b, new_entry);
6499c9de560dSAlex Tomas 	} else {
6500d71c1ae2SLukas Czerner 		if (test_opt(sb, DISCARD)) {
6501247c3d21SKemeng Shi 			err = ext4_issue_discard(sb, block_group, bit,
65020efcd739SWenchao Hao 						 count_clusters);
6503fa606293SJan Kara 			/*
6504fa606293SJan Kara 			 * Ignore EOPNOTSUPP error. This is consistent with
6505fa606293SJan Kara 			 * what happens when using journal.
6506fa606293SJan Kara 			 */
6507fa606293SJan Kara 			if (err == -EOPNOTSUPP)
6508fa606293SJan Kara 				err = 0;
6509fa606293SJan Kara 			if (err)
6510d71c1ae2SLukas Czerner 				ext4_msg(sb, KERN_WARNING, "discard request in"
6511a00b482bSRitesh Harjani 					 " group:%u block:%d count:%lu failed"
6512d71c1ae2SLukas Czerner 					 " with %d", block_group, bit, count,
6513d71c1ae2SLukas Czerner 					 err);
65148f9ff189SLukas Czerner 		} else
65158f9ff189SLukas Czerner 			EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
6516d71c1ae2SLukas Czerner 
6517955ce5f5SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
651884130193STheodore Ts'o 		mb_free_blocks(inode, &e4b, bit, count_clusters);
6519c9de560dSAlex Tomas 	}
6520c9de560dSAlex Tomas 
6521955ce5f5SAneesh Kumar K.V 	ext4_unlock_group(sb, block_group);
6522c9de560dSAlex Tomas 
65239fe67149SEric Whitney 	/*
65249fe67149SEric Whitney 	 * on a bigalloc file system, defer the s_freeclusters_counter
65259fe67149SEric Whitney 	 * update to the caller (ext4_remove_space and friends) so they
65269fe67149SEric Whitney 	 * can determine if a cluster freed here should be rereserved
65279fe67149SEric Whitney 	 */
65289fe67149SEric Whitney 	if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
65297b415bf6SAditya Kali 		if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
65307b415bf6SAditya Kali 			dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
65319fe67149SEric Whitney 		percpu_counter_add(&sbi->s_freeclusters_counter,
65329fe67149SEric Whitney 				   count_clusters);
65339fe67149SEric Whitney 	}
65347d734532SJan Kara 
6535c9de560dSAlex Tomas 	if (overflow && !err) {
6536c9de560dSAlex Tomas 		block += count;
6537c9de560dSAlex Tomas 		count = overflow;
653833e728c6SKemeng Shi 		ext4_mb_unload_buddy(&e4b);
65391e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
65401e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6541c9de560dSAlex Tomas 		goto do_more;
6542c9de560dSAlex Tomas 	}
654333e728c6SKemeng Shi 
654433e728c6SKemeng Shi error_clean:
654533e728c6SKemeng Shi 	ext4_mb_unload_buddy(&e4b);
654633e728c6SKemeng Shi error_out:
6547c9de560dSAlex Tomas 	ext4_std_error(sb, err);
6548c9de560dSAlex Tomas }
65497360d173SLukas Czerner 
65507360d173SLukas Czerner /**
65518ac3939dSRitesh Harjani  * ext4_free_blocks() -- Free given blocks and update quota
65528ac3939dSRitesh Harjani  * @handle:		handle for this transaction
65538ac3939dSRitesh Harjani  * @inode:		inode
65548ac3939dSRitesh Harjani  * @bh:			optional buffer of the block to be freed
65558ac3939dSRitesh Harjani  * @block:		starting physical block to be freed
65568ac3939dSRitesh Harjani  * @count:		number of blocks to be freed
65578ac3939dSRitesh Harjani  * @flags:		flags used by ext4_free_blocks
65588ac3939dSRitesh Harjani  */
65598ac3939dSRitesh Harjani void ext4_free_blocks(handle_t *handle, struct inode *inode,
65608ac3939dSRitesh Harjani 		      struct buffer_head *bh, ext4_fsblk_t block,
65618ac3939dSRitesh Harjani 		      unsigned long count, int flags)
65628ac3939dSRitesh Harjani {
65638ac3939dSRitesh Harjani 	struct super_block *sb = inode->i_sb;
65648ac3939dSRitesh Harjani 	unsigned int overflow;
65658ac3939dSRitesh Harjani 	struct ext4_sb_info *sbi;
65668ac3939dSRitesh Harjani 
65678ac3939dSRitesh Harjani 	sbi = EXT4_SB(sb);
65688ac3939dSRitesh Harjani 
65698ac3939dSRitesh Harjani 	if (bh) {
65708ac3939dSRitesh Harjani 		if (block)
65718ac3939dSRitesh Harjani 			BUG_ON(block != bh->b_blocknr);
65728ac3939dSRitesh Harjani 		else
65738ac3939dSRitesh Harjani 			block = bh->b_blocknr;
65748ac3939dSRitesh Harjani 	}
65758ac3939dSRitesh Harjani 
657611b6890bSKemeng Shi 	if (sbi->s_mount_state & EXT4_FC_REPLAY) {
65772ec6d0a5SKemeng Shi 		ext4_free_blocks_simple(inode, block, EXT4_NUM_B2C(sbi, count));
657811b6890bSKemeng Shi 		return;
657911b6890bSKemeng Shi 	}
658011b6890bSKemeng Shi 
658111b6890bSKemeng Shi 	might_sleep();
658211b6890bSKemeng Shi 
65838ac3939dSRitesh Harjani 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
65848ac3939dSRitesh Harjani 	    !ext4_inode_block_valid(inode, block, count)) {
65858ac3939dSRitesh Harjani 		ext4_error(sb, "Freeing blocks not in datazone - "
65868ac3939dSRitesh Harjani 			   "block = %llu, count = %lu", block, count);
65878ac3939dSRitesh Harjani 		return;
65888ac3939dSRitesh Harjani 	}
65891e1c2b86SLukas Czerner 	flags |= EXT4_FREE_BLOCKS_VALIDATED;
65908ac3939dSRitesh Harjani 
65918ac3939dSRitesh Harjani 	ext4_debug("freeing block %llu\n", block);
65928ac3939dSRitesh Harjani 	trace_ext4_free_blocks(inode, block, count, flags);
65938ac3939dSRitesh Harjani 
65948ac3939dSRitesh Harjani 	if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
65958ac3939dSRitesh Harjani 		BUG_ON(count > 1);
65968ac3939dSRitesh Harjani 
65978ac3939dSRitesh Harjani 		ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
65988ac3939dSRitesh Harjani 			    inode, bh, block);
65998ac3939dSRitesh Harjani 	}
66008ac3939dSRitesh Harjani 
66018ac3939dSRitesh Harjani 	/*
66028ac3939dSRitesh Harjani 	 * If the extent to be freed does not begin on a cluster
66038ac3939dSRitesh Harjani 	 * boundary, we need to deal with partial clusters at the
66048ac3939dSRitesh Harjani 	 * beginning and end of the extent.  Normally we will free
66058ac3939dSRitesh Harjani 	 * blocks at the beginning or the end unless we are explicitly
66068ac3939dSRitesh Harjani 	 * requested to avoid doing so.
66078ac3939dSRitesh Harjani 	 */
66088ac3939dSRitesh Harjani 	overflow = EXT4_PBLK_COFF(sbi, block);
66098ac3939dSRitesh Harjani 	if (overflow) {
66108ac3939dSRitesh Harjani 		if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
66118ac3939dSRitesh Harjani 			overflow = sbi->s_cluster_ratio - overflow;
66128ac3939dSRitesh Harjani 			block += overflow;
66138ac3939dSRitesh Harjani 			if (count > overflow)
66148ac3939dSRitesh Harjani 				count -= overflow;
66158ac3939dSRitesh Harjani 			else
66168ac3939dSRitesh Harjani 				return;
66178ac3939dSRitesh Harjani 		} else {
66188ac3939dSRitesh Harjani 			block -= overflow;
66198ac3939dSRitesh Harjani 			count += overflow;
66208ac3939dSRitesh Harjani 		}
66211e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
66221e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
66238ac3939dSRitesh Harjani 	}
66248ac3939dSRitesh Harjani 	overflow = EXT4_LBLK_COFF(sbi, count);
66258ac3939dSRitesh Harjani 	if (overflow) {
66268ac3939dSRitesh Harjani 		if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
66278ac3939dSRitesh Harjani 			if (count > overflow)
66288ac3939dSRitesh Harjani 				count -= overflow;
66298ac3939dSRitesh Harjani 			else
66308ac3939dSRitesh Harjani 				return;
66318ac3939dSRitesh Harjani 		} else
66328ac3939dSRitesh Harjani 			count += sbi->s_cluster_ratio - overflow;
66331e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
66341e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
66358ac3939dSRitesh Harjani 	}
66368ac3939dSRitesh Harjani 
66378ac3939dSRitesh Harjani 	if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
66388ac3939dSRitesh Harjani 		int i;
66398ac3939dSRitesh Harjani 		int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
66408ac3939dSRitesh Harjani 
66418ac3939dSRitesh Harjani 		for (i = 0; i < count; i++) {
66428ac3939dSRitesh Harjani 			cond_resched();
66438ac3939dSRitesh Harjani 			if (is_metadata)
66448ac3939dSRitesh Harjani 				bh = sb_find_get_block(inode->i_sb, block + i);
66458ac3939dSRitesh Harjani 			ext4_forget(handle, is_metadata, inode, bh, block + i);
66468ac3939dSRitesh Harjani 		}
66478ac3939dSRitesh Harjani 	}
66488ac3939dSRitesh Harjani 
66498ac3939dSRitesh Harjani 	ext4_mb_clear_bb(handle, inode, block, count, flags);
66508ac3939dSRitesh Harjani }
66518ac3939dSRitesh Harjani 
66528ac3939dSRitesh Harjani /**
66530529155eSYongqiang Yang  * ext4_group_add_blocks() -- Add given blocks to an existing group
66542846e820SAmir Goldstein  * @handle:			handle to this transaction
66552846e820SAmir Goldstein  * @sb:				super block
66564907cb7bSAnatol Pomozov  * @block:			start physical block to add to the block group
66572846e820SAmir Goldstein  * @count:			number of blocks to free
66582846e820SAmir Goldstein  *
6659e73a347bSAmir Goldstein  * This marks the blocks as free in the bitmap and buddy.
66602846e820SAmir Goldstein  */
6661cc7365dfSYongqiang Yang int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
66622846e820SAmir Goldstein 			 ext4_fsblk_t block, unsigned long count)
66632846e820SAmir Goldstein {
66642846e820SAmir Goldstein 	ext4_group_t block_group;
66652846e820SAmir Goldstein 	ext4_grpblk_t bit;
66662846e820SAmir Goldstein 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6667e73a347bSAmir Goldstein 	struct ext4_buddy e4b;
66685c657db4SKemeng Shi 	int err = 0;
6669d77147ffSharshads 	ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
6670d77147ffSharshads 	ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
6671d77147ffSharshads 	unsigned long cluster_count = last_cluster - first_cluster + 1;
66725c657db4SKemeng Shi 	ext4_grpblk_t changed;
66732846e820SAmir Goldstein 
66742846e820SAmir Goldstein 	ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
66752846e820SAmir Goldstein 
66765c657db4SKemeng Shi 	if (cluster_count == 0)
66774740b830SYongqiang Yang 		return 0;
66784740b830SYongqiang Yang 
66792846e820SAmir Goldstein 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
66802846e820SAmir Goldstein 	/*
66812846e820SAmir Goldstein 	 * Check to see if we are freeing blocks across a group
66822846e820SAmir Goldstein 	 * boundary.
66832846e820SAmir Goldstein 	 */
6684d77147ffSharshads 	if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
6685d77147ffSharshads 		ext4_warning(sb, "too many blocks added to group %u",
6686cc7365dfSYongqiang Yang 			     block_group);
6687cc7365dfSYongqiang Yang 		err = -EINVAL;
668803c7fc39SKemeng Shi 		goto error_out;
6689cc7365dfSYongqiang Yang 	}
66902cd05cc3STheodore Ts'o 
669103c7fc39SKemeng Shi 	err = ext4_mb_load_buddy(sb, block_group, &e4b);
669203c7fc39SKemeng Shi 	if (err)
669303c7fc39SKemeng Shi 		goto error_out;
66942846e820SAmir Goldstein 
6695a00b482bSRitesh Harjani 	if (!ext4_sb_block_valid(sb, NULL, block, count)) {
66962846e820SAmir Goldstein 		ext4_error(sb, "Adding blocks in system zones - "
66972846e820SAmir Goldstein 			   "Block = %llu, count = %lu",
66982846e820SAmir Goldstein 			   block, count);
6699cc7365dfSYongqiang Yang 		err = -EINVAL;
670003c7fc39SKemeng Shi 		goto error_clean;
670103c7fc39SKemeng Shi 	}
670203c7fc39SKemeng Shi 
67035c657db4SKemeng Shi 	err = ext4_mb_mark_context(handle, sb, false, block_group, bit,
67045c657db4SKemeng Shi 				   cluster_count, EXT4_MB_BITMAP_MARKED_CHECK,
67055c657db4SKemeng Shi 				   &changed);
67065c657db4SKemeng Shi 	if (err && changed == 0)
670703c7fc39SKemeng Shi 		goto error_clean;
67082846e820SAmir Goldstein 
67095c657db4SKemeng Shi 	if (changed != cluster_count)
67105c657db4SKemeng Shi 		ext4_error(sb, "bit already cleared in group %u", block_group);
67112846e820SAmir Goldstein 
671203c7fc39SKemeng Shi 	ext4_lock_group(sb, block_group);
671303c7fc39SKemeng Shi 	mb_free_blocks(NULL, &e4b, bit, cluster_count);
671403c7fc39SKemeng Shi 	ext4_unlock_group(sb, block_group);
671503c7fc39SKemeng Shi 	percpu_counter_add(&sbi->s_freeclusters_counter,
67165c657db4SKemeng Shi 			   changed);
671703c7fc39SKemeng Shi 
671803c7fc39SKemeng Shi error_clean:
671903c7fc39SKemeng Shi 	ext4_mb_unload_buddy(&e4b);
672003c7fc39SKemeng Shi error_out:
67212846e820SAmir Goldstein 	ext4_std_error(sb, err);
6722cc7365dfSYongqiang Yang 	return err;
67232846e820SAmir Goldstein }
67242846e820SAmir Goldstein 
67252846e820SAmir Goldstein /**
67267360d173SLukas Czerner  * ext4_trim_extent -- function to TRIM one single free extent in the group
67277360d173SLukas Czerner  * @sb:		super block for the file system
67287360d173SLukas Czerner  * @start:	starting block of the free extent in the alloc. group
67297360d173SLukas Czerner  * @count:	number of blocks to TRIM
67307360d173SLukas Czerner  * @e4b:	ext4 buddy for the group
67317360d173SLukas Czerner  *
67327360d173SLukas Czerner  * Trim "count" blocks starting at "start" in the "group". To assure that no
67337360d173SLukas Czerner  * one will allocate those blocks, mark it as used in buddy bitmap. This must
67347360d173SLukas Czerner  * be called with under the group lock.
67357360d173SLukas Czerner  */
6736bd2eea8dSWang Jianchao static int ext4_trim_extent(struct super_block *sb,
6737bd2eea8dSWang Jianchao 		int start, int count, struct ext4_buddy *e4b)
6738e2cbd587Sjon ernst __releases(bitlock)
6739e2cbd587Sjon ernst __acquires(bitlock)
67407360d173SLukas Czerner {
67417360d173SLukas Czerner 	struct ext4_free_extent ex;
6742bd2eea8dSWang Jianchao 	ext4_group_t group = e4b->bd_group;
6743d71c1ae2SLukas Czerner 	int ret = 0;
67447360d173SLukas Czerner 
6745b3d4c2b1STao Ma 	trace_ext4_trim_extent(sb, group, start, count);
6746b3d4c2b1STao Ma 
67477360d173SLukas Czerner 	assert_spin_locked(ext4_group_lock_ptr(sb, group));
67487360d173SLukas Czerner 
67497360d173SLukas Czerner 	ex.fe_start = start;
67507360d173SLukas Czerner 	ex.fe_group = group;
67517360d173SLukas Czerner 	ex.fe_len = count;
67527360d173SLukas Czerner 
67537360d173SLukas Czerner 	/*
67547360d173SLukas Czerner 	 * Mark blocks used, so no one can reuse them while
67557360d173SLukas Czerner 	 * being trimmed.
67567360d173SLukas Czerner 	 */
67577360d173SLukas Czerner 	mb_mark_used(e4b, &ex);
67587360d173SLukas Czerner 	ext4_unlock_group(sb, group);
67590efcd739SWenchao Hao 	ret = ext4_issue_discard(sb, group, start, count);
67607360d173SLukas Czerner 	ext4_lock_group(sb, group);
67617360d173SLukas Czerner 	mb_free_blocks(NULL, e4b, start, ex.fe_len);
6762d71c1ae2SLukas Czerner 	return ret;
67637360d173SLukas Czerner }
67647360d173SLukas Czerner 
676545e4ab32SJan Kara static ext4_grpblk_t ext4_last_grp_cluster(struct super_block *sb,
676645e4ab32SJan Kara 					   ext4_group_t grp)
676745e4ab32SJan Kara {
67687c784d62SSuraj Jitindar Singh 	unsigned long nr_clusters_in_group;
67697c784d62SSuraj Jitindar Singh 
67707c784d62SSuraj Jitindar Singh 	if (grp < (ext4_get_groups_count(sb) - 1))
67717c784d62SSuraj Jitindar Singh 		nr_clusters_in_group = EXT4_CLUSTERS_PER_GROUP(sb);
67727c784d62SSuraj Jitindar Singh 	else
67737c784d62SSuraj Jitindar Singh 		nr_clusters_in_group = (ext4_blocks_count(EXT4_SB(sb)->s_es) -
67747c784d62SSuraj Jitindar Singh 					ext4_group_first_block_no(sb, grp))
67757c784d62SSuraj Jitindar Singh 				       >> EXT4_CLUSTER_BITS(sb);
67767c784d62SSuraj Jitindar Singh 
67777c784d62SSuraj Jitindar Singh 	return nr_clusters_in_group - 1;
677845e4ab32SJan Kara }
677945e4ab32SJan Kara 
67805229a658SJan Kara static bool ext4_trim_interrupted(void)
67815229a658SJan Kara {
67825229a658SJan Kara 	return fatal_signal_pending(current) || freezing(current);
67835229a658SJan Kara }
67845229a658SJan Kara 
67856920b391SWang Jianchao static int ext4_try_to_trim_range(struct super_block *sb,
67866920b391SWang Jianchao 		struct ext4_buddy *e4b, ext4_grpblk_t start,
67876920b391SWang Jianchao 		ext4_grpblk_t max, ext4_grpblk_t minblocks)
6788a5fda113STheodore Ts'o __acquires(ext4_group_lock_ptr(sb, e4b->bd_group))
6789a5fda113STheodore Ts'o __releases(ext4_group_lock_ptr(sb, e4b->bd_group))
67906920b391SWang Jianchao {
679168da4c44SYe Bin 	ext4_grpblk_t next, count, free_count, last, origin_start;
679245e4ab32SJan Kara 	bool set_trimmed = false;
67936920b391SWang Jianchao 	void *bitmap;
67946920b391SWang Jianchao 
679517220215SBaokun Li 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
679617220215SBaokun Li 		return 0;
679717220215SBaokun Li 
679868da4c44SYe Bin 	last = ext4_last_grp_cluster(sb, e4b->bd_group);
67996920b391SWang Jianchao 	bitmap = e4b->bd_bitmap;
680068da4c44SYe Bin 	if (start == 0 && max >= last)
680145e4ab32SJan Kara 		set_trimmed = true;
680268da4c44SYe Bin 	origin_start = start;
6803de8bf0e5SKemeng Shi 	start = max(e4b->bd_info->bb_first_free, start);
68046920b391SWang Jianchao 	count = 0;
68056920b391SWang Jianchao 	free_count = 0;
68066920b391SWang Jianchao 
68076920b391SWang Jianchao 	while (start <= max) {
68086920b391SWang Jianchao 		start = mb_find_next_zero_bit(bitmap, max + 1, start);
68096920b391SWang Jianchao 		if (start > max)
68106920b391SWang Jianchao 			break;
681168da4c44SYe Bin 
681268da4c44SYe Bin 		next = mb_find_next_bit(bitmap, last + 1, start);
681368da4c44SYe Bin 		if (origin_start == 0 && next >= last)
681468da4c44SYe Bin 			set_trimmed = true;
68156920b391SWang Jianchao 
68166920b391SWang Jianchao 		if ((next - start) >= minblocks) {
6817afcc4e32SLukas Bulwahn 			int ret = ext4_trim_extent(sb, start, next - start, e4b);
6818afcc4e32SLukas Bulwahn 
68196920b391SWang Jianchao 			if (ret && ret != -EOPNOTSUPP)
682045e4ab32SJan Kara 				return count;
68216920b391SWang Jianchao 			count += next - start;
68226920b391SWang Jianchao 		}
68236920b391SWang Jianchao 		free_count += next - start;
68246920b391SWang Jianchao 		start = next + 1;
68256920b391SWang Jianchao 
68265229a658SJan Kara 		if (ext4_trim_interrupted())
68275229a658SJan Kara 			return count;
68286920b391SWang Jianchao 
68296920b391SWang Jianchao 		if (need_resched()) {
68306920b391SWang Jianchao 			ext4_unlock_group(sb, e4b->bd_group);
68316920b391SWang Jianchao 			cond_resched();
68326920b391SWang Jianchao 			ext4_lock_group(sb, e4b->bd_group);
68336920b391SWang Jianchao 		}
68346920b391SWang Jianchao 
68356920b391SWang Jianchao 		if ((e4b->bd_info->bb_free - free_count) < minblocks)
68366920b391SWang Jianchao 			break;
68376920b391SWang Jianchao 	}
68386920b391SWang Jianchao 
683945e4ab32SJan Kara 	if (set_trimmed)
684045e4ab32SJan Kara 		EXT4_MB_GRP_SET_TRIMMED(e4b->bd_info);
684145e4ab32SJan Kara 
68426920b391SWang Jianchao 	return count;
68436920b391SWang Jianchao }
68446920b391SWang Jianchao 
68457360d173SLukas Czerner /**
68467360d173SLukas Czerner  * ext4_trim_all_free -- function to trim all free space in alloc. group
68477360d173SLukas Czerner  * @sb:			super block for file system
684822612283STao Ma  * @group:		group to be trimmed
68497360d173SLukas Czerner  * @start:		first group block to examine
68507360d173SLukas Czerner  * @max:		last group block to examine
68517360d173SLukas Czerner  * @minblocks:		minimum extent block count
68527360d173SLukas Czerner  *
68537360d173SLukas Czerner  * ext4_trim_all_free walks through group's block bitmap searching for free
68547360d173SLukas Czerner  * extents. When the free extent is found, mark it as used in group buddy
68557360d173SLukas Czerner  * bitmap. Then issue a TRIM command on this extent and free the extent in
6856b6f5558cSWang Jianchao  * the group buddy bitmap.
68577360d173SLukas Czerner  */
68580b75a840SLukas Czerner static ext4_grpblk_t
685978944086SLukas Czerner ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
686078944086SLukas Czerner 		   ext4_grpblk_t start, ext4_grpblk_t max,
686145e4ab32SJan Kara 		   ext4_grpblk_t minblocks)
68627360d173SLukas Czerner {
686378944086SLukas Czerner 	struct ext4_buddy e4b;
68646920b391SWang Jianchao 	int ret;
68657360d173SLukas Czerner 
6866b3d4c2b1STao Ma 	trace_ext4_trim_all_free(sb, group, start, max);
6867b3d4c2b1STao Ma 
686878944086SLukas Czerner 	ret = ext4_mb_load_buddy(sb, group, &e4b);
686978944086SLukas Czerner 	if (ret) {
68709651e6b2SKonstantin Khlebnikov 		ext4_warning(sb, "Error %d loading buddy information for %u",
68719651e6b2SKonstantin Khlebnikov 			     ret, group);
687278944086SLukas Czerner 		return ret;
687378944086SLukas Czerner 	}
687428739eeaSLukas Czerner 
687528739eeaSLukas Czerner 	ext4_lock_group(sb, group);
68763d56b8d2STao Ma 
68776920b391SWang Jianchao 	if (!EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) ||
687845e4ab32SJan Kara 	    minblocks < EXT4_SB(sb)->s_last_trim_minblks)
68796920b391SWang Jianchao 		ret = ext4_try_to_trim_range(sb, &e4b, start, max, minblocks);
688045e4ab32SJan Kara 	else
68816920b391SWang Jianchao 		ret = 0;
68826920b391SWang Jianchao 
68837360d173SLukas Czerner 	ext4_unlock_group(sb, group);
688478944086SLukas Czerner 	ext4_mb_unload_buddy(&e4b);
68857360d173SLukas Czerner 
68867360d173SLukas Czerner 	ext4_debug("trimmed %d blocks in the group %d\n",
68876920b391SWang Jianchao 		ret, group);
68887360d173SLukas Czerner 
6889d71c1ae2SLukas Czerner 	return ret;
68907360d173SLukas Czerner }
68917360d173SLukas Czerner 
68927360d173SLukas Czerner /**
68937360d173SLukas Czerner  * ext4_trim_fs() -- trim ioctl handle function
68947360d173SLukas Czerner  * @sb:			superblock for filesystem
68957360d173SLukas Czerner  * @range:		fstrim_range structure
68967360d173SLukas Czerner  *
68977360d173SLukas Czerner  * start:	First Byte to trim
68987360d173SLukas Czerner  * len:		number of Bytes to trim from start
68997360d173SLukas Czerner  * minlen:	minimum extent length in Bytes
69007360d173SLukas Czerner  * ext4_trim_fs goes through all allocation groups containing Bytes from
69017360d173SLukas Czerner  * start to start+len. For each such a group ext4_trim_all_free function
69027360d173SLukas Czerner  * is invoked to trim all free space.
69037360d173SLukas Czerner  */
69047360d173SLukas Czerner int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
69057360d173SLukas Czerner {
69067b47ef52SChristoph Hellwig 	unsigned int discard_granularity = bdev_discard_granularity(sb->s_bdev);
690778944086SLukas Czerner 	struct ext4_group_info *grp;
6908913eed83SLukas Czerner 	ext4_group_t group, first_group, last_group;
69097137d7a4STheodore Ts'o 	ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
6910913eed83SLukas Czerner 	uint64_t start, end, minlen, trimmed = 0;
69110f0a25bfSJan Kara 	ext4_fsblk_t first_data_blk =
69120f0a25bfSJan Kara 			le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
6913913eed83SLukas Czerner 	ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
69147360d173SLukas Czerner 	int ret = 0;
69157360d173SLukas Czerner 
69167360d173SLukas Czerner 	start = range->start >> sb->s_blocksize_bits;
6917913eed83SLukas Czerner 	end = start + (range->len >> sb->s_blocksize_bits) - 1;
6918aaf7d73eSLukas Czerner 	minlen = EXT4_NUM_B2C(EXT4_SB(sb),
6919aaf7d73eSLukas Czerner 			      range->minlen >> sb->s_blocksize_bits);
69207360d173SLukas Czerner 
69215de35e8dSLukas Czerner 	if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
69225de35e8dSLukas Czerner 	    start >= max_blks ||
69235de35e8dSLukas Czerner 	    range->len < sb->s_blocksize)
69247360d173SLukas Czerner 		return -EINVAL;
6925173b6e38SJan Kara 	/* No point to try to trim less than discard granularity */
69267b47ef52SChristoph Hellwig 	if (range->minlen < discard_granularity) {
6927173b6e38SJan Kara 		minlen = EXT4_NUM_B2C(EXT4_SB(sb),
69287b47ef52SChristoph Hellwig 				discard_granularity >> sb->s_blocksize_bits);
6929173b6e38SJan Kara 		if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
6930173b6e38SJan Kara 			goto out;
6931173b6e38SJan Kara 	}
693245e4ab32SJan Kara 	if (end >= max_blks - 1)
6933913eed83SLukas Czerner 		end = max_blks - 1;
6934913eed83SLukas Czerner 	if (end <= first_data_blk)
693522f10457STao Ma 		goto out;
6936913eed83SLukas Czerner 	if (start < first_data_blk)
69370f0a25bfSJan Kara 		start = first_data_blk;
69387360d173SLukas Czerner 
6939913eed83SLukas Czerner 	/* Determine first and last group to examine based on start and end */
69407360d173SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
69417137d7a4STheodore Ts'o 				     &first_group, &first_cluster);
6942913eed83SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
69437137d7a4STheodore Ts'o 				     &last_group, &last_cluster);
69447360d173SLukas Czerner 
6945913eed83SLukas Czerner 	/* end now represents the last cluster to discard in this group */
6946913eed83SLukas Czerner 	end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
69477360d173SLukas Czerner 
69487360d173SLukas Czerner 	for (group = first_group; group <= last_group; group++) {
69495229a658SJan Kara 		if (ext4_trim_interrupted())
69505229a658SJan Kara 			break;
695178944086SLukas Czerner 		grp = ext4_get_group_info(sb, group);
69525354b2afSTheodore Ts'o 		if (!grp)
69535354b2afSTheodore Ts'o 			continue;
695478944086SLukas Czerner 		/* We only do this if the grp has never been initialized */
695578944086SLukas Czerner 		if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
6956adb7ef60SKonstantin Khlebnikov 			ret = ext4_mb_init_group(sb, group, GFP_NOFS);
695778944086SLukas Czerner 			if (ret)
69587360d173SLukas Czerner 				break;
69597360d173SLukas Czerner 		}
69607360d173SLukas Czerner 
69610ba08517STao Ma 		/*
6962913eed83SLukas Czerner 		 * For all the groups except the last one, last cluster will
6963913eed83SLukas Czerner 		 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
6964913eed83SLukas Czerner 		 * change it for the last group, note that last_cluster is
6965913eed83SLukas Czerner 		 * already computed earlier by ext4_get_group_no_and_offset()
69660ba08517STao Ma 		 */
696745e4ab32SJan Kara 		if (group == last_group)
6968913eed83SLukas Czerner 			end = last_cluster;
696978944086SLukas Czerner 		if (grp->bb_free >= minlen) {
69707137d7a4STheodore Ts'o 			cnt = ext4_trim_all_free(sb, group, first_cluster,
697145e4ab32SJan Kara 						 end, minlen);
69727360d173SLukas Czerner 			if (cnt < 0) {
69737360d173SLukas Czerner 				ret = cnt;
69747360d173SLukas Czerner 				break;
69757360d173SLukas Czerner 			}
69767360d173SLukas Czerner 			trimmed += cnt;
697721e7fd22SLukas Czerner 		}
6978913eed83SLukas Czerner 
6979913eed83SLukas Czerner 		/*
6980913eed83SLukas Czerner 		 * For every group except the first one, we are sure
6981913eed83SLukas Czerner 		 * that the first cluster to discard will be cluster #0.
6982913eed83SLukas Czerner 		 */
69837137d7a4STheodore Ts'o 		first_cluster = 0;
69847360d173SLukas Czerner 	}
69857360d173SLukas Czerner 
69863d56b8d2STao Ma 	if (!ret)
69872327fb2eSLukas Czerner 		EXT4_SB(sb)->s_last_trim_minblks = minlen;
69883d56b8d2STao Ma 
698922f10457STao Ma out:
6990aaf7d73eSLukas Czerner 	range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
69917360d173SLukas Czerner 	return ret;
69927360d173SLukas Czerner }
69930c9ec4beSDarrick J. Wong 
69940c9ec4beSDarrick J. Wong /* Iterate all the free extents in the group. */
69950c9ec4beSDarrick J. Wong int
69960c9ec4beSDarrick J. Wong ext4_mballoc_query_range(
69970c9ec4beSDarrick J. Wong 	struct super_block		*sb,
69980c9ec4beSDarrick J. Wong 	ext4_group_t			group,
69990c9ec4beSDarrick J. Wong 	ext4_grpblk_t			start,
70000c9ec4beSDarrick J. Wong 	ext4_grpblk_t			end,
70010c9ec4beSDarrick J. Wong 	ext4_mballoc_query_range_fn	formatter,
70020c9ec4beSDarrick J. Wong 	void				*priv)
70030c9ec4beSDarrick J. Wong {
70040c9ec4beSDarrick J. Wong 	void				*bitmap;
70050c9ec4beSDarrick J. Wong 	ext4_grpblk_t			next;
70060c9ec4beSDarrick J. Wong 	struct ext4_buddy		e4b;
70070c9ec4beSDarrick J. Wong 	int				error;
70080c9ec4beSDarrick J. Wong 
70090c9ec4beSDarrick J. Wong 	error = ext4_mb_load_buddy(sb, group, &e4b);
70100c9ec4beSDarrick J. Wong 	if (error)
70110c9ec4beSDarrick J. Wong 		return error;
70120c9ec4beSDarrick J. Wong 	bitmap = e4b.bd_bitmap;
70130c9ec4beSDarrick J. Wong 
70140c9ec4beSDarrick J. Wong 	ext4_lock_group(sb, group);
70150c9ec4beSDarrick J. Wong 
7016de8bf0e5SKemeng Shi 	start = max(e4b.bd_info->bb_first_free, start);
70170c9ec4beSDarrick J. Wong 	if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
70180c9ec4beSDarrick J. Wong 		end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
70190c9ec4beSDarrick J. Wong 
70200c9ec4beSDarrick J. Wong 	while (start <= end) {
70210c9ec4beSDarrick J. Wong 		start = mb_find_next_zero_bit(bitmap, end + 1, start);
70220c9ec4beSDarrick J. Wong 		if (start > end)
70230c9ec4beSDarrick J. Wong 			break;
70240c9ec4beSDarrick J. Wong 		next = mb_find_next_bit(bitmap, end + 1, start);
70250c9ec4beSDarrick J. Wong 
70260c9ec4beSDarrick J. Wong 		ext4_unlock_group(sb, group);
70270c9ec4beSDarrick J. Wong 		error = formatter(sb, group, start, next - start, priv);
70280c9ec4beSDarrick J. Wong 		if (error)
70290c9ec4beSDarrick J. Wong 			goto out_unload;
70300c9ec4beSDarrick J. Wong 		ext4_lock_group(sb, group);
70310c9ec4beSDarrick J. Wong 
70320c9ec4beSDarrick J. Wong 		start = next + 1;
70330c9ec4beSDarrick J. Wong 	}
70340c9ec4beSDarrick J. Wong 
70350c9ec4beSDarrick J. Wong 	ext4_unlock_group(sb, group);
70360c9ec4beSDarrick J. Wong out_unload:
70370c9ec4beSDarrick J. Wong 	ext4_mb_unload_buddy(&e4b);
70380c9ec4beSDarrick J. Wong 
70390c9ec4beSDarrick J. Wong 	return error;
70400c9ec4beSDarrick J. Wong }
70417c9fa399SKemeng Shi 
70427c9fa399SKemeng Shi #ifdef CONFIG_EXT4_KUNIT_TESTS
70437c9fa399SKemeng Shi #include "mballoc-test.c"
70447c9fa399SKemeng Shi #endif
7045