xref: /linux/fs/ext4/mballoc.c (revision ce774e5365e46be73ed055302c6de123a03394ea)
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>
219bffad1eSTheodore Ts'o 
22c9de560dSAlex Tomas /*
23c9de560dSAlex Tomas  * MUSTDO:
24c9de560dSAlex Tomas  *   - test ext4_ext_search_left() and ext4_ext_search_right()
25c9de560dSAlex Tomas  *   - search for metadata in few groups
26c9de560dSAlex Tomas  *
27c9de560dSAlex Tomas  * TODO v4:
28c9de560dSAlex Tomas  *   - normalization should take into account whether file is still open
29c9de560dSAlex Tomas  *   - discard preallocations if no free space left (policy?)
30c9de560dSAlex Tomas  *   - don't normalize tails
31c9de560dSAlex Tomas  *   - quota
32c9de560dSAlex Tomas  *   - reservation for superuser
33c9de560dSAlex Tomas  *
34c9de560dSAlex Tomas  * TODO v3:
35c9de560dSAlex Tomas  *   - bitmap read-ahead (proposed by Oleg Drokin aka green)
36c9de560dSAlex Tomas  *   - track min/max extents in each group for better group selection
37c9de560dSAlex Tomas  *   - mb_mark_used() may allocate chunk right after splitting buddy
38c9de560dSAlex Tomas  *   - tree of groups sorted by number of free blocks
39c9de560dSAlex Tomas  *   - error handling
40c9de560dSAlex Tomas  */
41c9de560dSAlex Tomas 
42c9de560dSAlex Tomas /*
43c9de560dSAlex Tomas  * The allocation request involve request for multiple number of blocks
44c9de560dSAlex Tomas  * near to the goal(block) value specified.
45c9de560dSAlex Tomas  *
46b713a5ecSTheodore Ts'o  * During initialization phase of the allocator we decide to use the
47b713a5ecSTheodore Ts'o  * group preallocation or inode preallocation depending on the size of
48b713a5ecSTheodore Ts'o  * the file. The size of the file could be the resulting file size we
49b713a5ecSTheodore Ts'o  * would have after allocation, or the current file size, which ever
50b713a5ecSTheodore Ts'o  * is larger. If the size is less than sbi->s_mb_stream_request we
51b713a5ecSTheodore Ts'o  * select to use the group preallocation. The default value of
52b713a5ecSTheodore Ts'o  * s_mb_stream_request is 16 blocks. This can also be tuned via
53b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
54b713a5ecSTheodore Ts'o  * terms of number of blocks.
55c9de560dSAlex Tomas  *
56c9de560dSAlex Tomas  * The main motivation for having small file use group preallocation is to
57b713a5ecSTheodore Ts'o  * ensure that we have small files closer together on the disk.
58c9de560dSAlex Tomas  *
59b713a5ecSTheodore Ts'o  * First stage the allocator looks at the inode prealloc list,
60b713a5ecSTheodore Ts'o  * ext4_inode_info->i_prealloc_list, which contains list of prealloc
61b713a5ecSTheodore Ts'o  * spaces for this particular inode. The inode prealloc space is
62b713a5ecSTheodore Ts'o  * represented as:
63c9de560dSAlex Tomas  *
64c9de560dSAlex Tomas  * pa_lstart -> the logical start block for this prealloc space
65c9de560dSAlex Tomas  * pa_pstart -> the physical start block for this prealloc space
6653accfa9STheodore Ts'o  * pa_len    -> length for this prealloc space (in clusters)
6753accfa9STheodore Ts'o  * pa_free   ->  free space available in this prealloc space (in clusters)
68c9de560dSAlex Tomas  *
69c9de560dSAlex Tomas  * The inode preallocation space is used looking at the _logical_ start
70c9de560dSAlex Tomas  * block. If only the logical file block falls within the range of prealloc
71caaf7a29STao Ma  * space we will consume the particular prealloc space. This makes sure that
72caaf7a29STao Ma  * we have contiguous physical blocks representing the file blocks
73c9de560dSAlex Tomas  *
74c9de560dSAlex Tomas  * The important thing to be noted in case of inode prealloc space is that
75c9de560dSAlex Tomas  * we don't modify the values associated to inode prealloc space except
76c9de560dSAlex Tomas  * pa_free.
77c9de560dSAlex Tomas  *
78c9de560dSAlex Tomas  * If we are not able to find blocks in the inode prealloc space and if we
79c9de560dSAlex Tomas  * have the group allocation flag set then we look at the locality group
80caaf7a29STao Ma  * prealloc space. These are per CPU prealloc list represented as
81c9de560dSAlex Tomas  *
82c9de560dSAlex Tomas  * ext4_sb_info.s_locality_groups[smp_processor_id()]
83c9de560dSAlex Tomas  *
84c9de560dSAlex Tomas  * The reason for having a per cpu locality group is to reduce the contention
85c9de560dSAlex Tomas  * between CPUs. It is possible to get scheduled at this point.
86c9de560dSAlex Tomas  *
87c9de560dSAlex Tomas  * The locality group prealloc space is used looking at whether we have
8825985edcSLucas De Marchi  * enough free space (pa_free) within the prealloc space.
89c9de560dSAlex Tomas  *
90c9de560dSAlex Tomas  * If we can't allocate blocks via inode prealloc or/and locality group
91c9de560dSAlex Tomas  * prealloc then we look at the buddy cache. The buddy cache is represented
92c9de560dSAlex Tomas  * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
93c9de560dSAlex Tomas  * mapped to the buddy and bitmap information regarding different
94c9de560dSAlex Tomas  * groups. The buddy information is attached to buddy cache inode so that
95c9de560dSAlex Tomas  * we can access them through the page cache. The information regarding
96c9de560dSAlex Tomas  * each group is loaded via ext4_mb_load_buddy.  The information involve
97c9de560dSAlex Tomas  * block bitmap and buddy information. The information are stored in the
98c9de560dSAlex Tomas  * inode as:
99c9de560dSAlex Tomas  *
100c9de560dSAlex Tomas  *  {                        page                        }
101c3a326a6SAneesh Kumar K.V  *  [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
102c9de560dSAlex Tomas  *
103c9de560dSAlex Tomas  *
104c9de560dSAlex Tomas  * one block each for bitmap and buddy information.  So for each group we
105ea1754a0SKirill A. Shutemov  * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
106c9de560dSAlex Tomas  * blocksize) blocks.  So it can have information regarding groups_per_page
107c9de560dSAlex Tomas  * which is blocks_per_page/2
108c9de560dSAlex Tomas  *
109c9de560dSAlex Tomas  * The buddy cache inode is not stored on disk. The inode is thrown
110c9de560dSAlex Tomas  * away when the filesystem is unmounted.
111c9de560dSAlex Tomas  *
112c9de560dSAlex Tomas  * We look for count number of blocks in the buddy cache. If we were able
113c9de560dSAlex Tomas  * to locate that many free blocks we return with additional information
114c9de560dSAlex Tomas  * regarding rest of the contiguous physical block available
115c9de560dSAlex Tomas  *
116c9de560dSAlex Tomas  * Before allocating blocks via buddy cache we normalize the request
117c9de560dSAlex Tomas  * blocks. This ensure we ask for more blocks that we needed. The extra
118c9de560dSAlex Tomas  * blocks that we get after allocation is added to the respective prealloc
119c9de560dSAlex Tomas  * list. In case of inode preallocation we follow a list of heuristics
120c9de560dSAlex Tomas  * based on file size. This can be found in ext4_mb_normalize_request. If
121c9de560dSAlex Tomas  * we are doing a group prealloc we try to normalize the request to
12227baebb8STheodore Ts'o  * sbi->s_mb_group_prealloc.  The default value of s_mb_group_prealloc is
12327baebb8STheodore Ts'o  * dependent on the cluster size; for non-bigalloc file systems, it is
124c9de560dSAlex Tomas  * 512 blocks. This can be tuned via
125d7a1fee1SDan Ehrenberg  * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
126c9de560dSAlex Tomas  * terms of number of blocks. If we have mounted the file system with -O
127c9de560dSAlex Tomas  * stripe=<value> option the group prealloc request is normalized to the
128b483bb77SRandy Dunlap  * smallest multiple of the stripe value (sbi->s_stripe) which is
129d7a1fee1SDan Ehrenberg  * greater than the default mb_group_prealloc.
130c9de560dSAlex Tomas  *
131196e402aSHarshad Shirwadkar  * If "mb_optimize_scan" mount option is set, we maintain in memory group info
132196e402aSHarshad Shirwadkar  * structures in two data structures:
133196e402aSHarshad Shirwadkar  *
134196e402aSHarshad Shirwadkar  * 1) Array of largest free order lists (sbi->s_mb_largest_free_orders)
135196e402aSHarshad Shirwadkar  *
136196e402aSHarshad Shirwadkar  *    Locking: sbi->s_mb_largest_free_orders_locks(array of rw locks)
137196e402aSHarshad Shirwadkar  *
138196e402aSHarshad Shirwadkar  *    This is an array of lists where the index in the array represents the
139196e402aSHarshad Shirwadkar  *    largest free order in the buddy bitmap of the participating group infos of
140196e402aSHarshad Shirwadkar  *    that list. So, there are exactly MB_NUM_ORDERS(sb) (which means total
141196e402aSHarshad Shirwadkar  *    number of buddy bitmap orders possible) number of lists. Group-infos are
142196e402aSHarshad Shirwadkar  *    placed in appropriate lists.
143196e402aSHarshad Shirwadkar  *
14483e80a6eSJan Kara  * 2) Average fragment size lists (sbi->s_mb_avg_fragment_size)
145196e402aSHarshad Shirwadkar  *
14683e80a6eSJan Kara  *    Locking: sbi->s_mb_avg_fragment_size_locks(array of rw locks)
147196e402aSHarshad Shirwadkar  *
14883e80a6eSJan Kara  *    This is an array of lists where in the i-th list there are groups with
14983e80a6eSJan Kara  *    average fragment size >= 2^i and < 2^(i+1). The average fragment size
15083e80a6eSJan Kara  *    is computed as ext4_group_info->bb_free / ext4_group_info->bb_fragments.
15183e80a6eSJan Kara  *    Note that we don't bother with a special list for completely empty groups
15283e80a6eSJan Kara  *    so we only have MB_NUM_ORDERS(sb) lists.
153196e402aSHarshad Shirwadkar  *
154196e402aSHarshad Shirwadkar  * When "mb_optimize_scan" mount option is set, mballoc consults the above data
155196e402aSHarshad Shirwadkar  * structures to decide the order in which groups are to be traversed for
156196e402aSHarshad Shirwadkar  * fulfilling an allocation request.
157196e402aSHarshad Shirwadkar  *
158f52f3d2bSOjaswin Mujoo  * At CR_POWER2_ALIGNED , we look for groups which have the largest_free_order
159f52f3d2bSOjaswin Mujoo  * >= the order of the request. We directly look at the largest free order list
160f52f3d2bSOjaswin Mujoo  * in the data structure (1) above where largest_free_order = order of the
161f52f3d2bSOjaswin Mujoo  * request. If that list is empty, we look at remaining list in the increasing
162f52f3d2bSOjaswin Mujoo  * order of largest_free_order. This allows us to perform CR_POWER2_ALIGNED
163f52f3d2bSOjaswin Mujoo  * lookup in O(1) time.
164196e402aSHarshad Shirwadkar  *
165f52f3d2bSOjaswin Mujoo  * At CR_GOAL_LEN_FAST, we only consider groups where
166f52f3d2bSOjaswin Mujoo  * average fragment size > request size. So, we lookup a group which has average
167f52f3d2bSOjaswin Mujoo  * fragment size just above or equal to request size using our average fragment
168f52f3d2bSOjaswin Mujoo  * size group lists (data structure 2) in O(1) time.
169196e402aSHarshad Shirwadkar  *
170f52f3d2bSOjaswin Mujoo  * At CR_BEST_AVAIL_LEN, we aim to optimize allocations which can't be satisfied
171f52f3d2bSOjaswin Mujoo  * in CR_GOAL_LEN_FAST. The fact that we couldn't find a group in
172f52f3d2bSOjaswin Mujoo  * CR_GOAL_LEN_FAST suggests that there is no BG that has avg
173f52f3d2bSOjaswin Mujoo  * fragment size > goal length. So before falling to the slower
174f52f3d2bSOjaswin Mujoo  * CR_GOAL_LEN_SLOW, in CR_BEST_AVAIL_LEN we proactively trim goal length and
175f52f3d2bSOjaswin Mujoo  * then use the same fragment lists as CR_GOAL_LEN_FAST to find a BG with a big
176f52f3d2bSOjaswin Mujoo  * enough average fragment size. This increases the chances of finding a
177f52f3d2bSOjaswin Mujoo  * suitable block group in O(1) time and results in faster allocation at the
178f52f3d2bSOjaswin Mujoo  * cost of reduced size of allocation.
1797e170922SOjaswin Mujoo  *
180196e402aSHarshad Shirwadkar  * If "mb_optimize_scan" mount option is not set, mballoc traverses groups in
181f52f3d2bSOjaswin Mujoo  * linear order which requires O(N) search time for each CR_POWER2_ALIGNED and
182f52f3d2bSOjaswin Mujoo  * CR_GOAL_LEN_FAST phase.
183196e402aSHarshad Shirwadkar  *
184d7a1fee1SDan Ehrenberg  * The regular allocator (using the buddy cache) supports a few tunables.
185c9de560dSAlex Tomas  *
186b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_min_to_scan
187b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_max_to_scan
188b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_order2_req
189196e402aSHarshad Shirwadkar  * /sys/fs/ext4/<partition>/mb_linear_limit
190c9de560dSAlex Tomas  *
191b713a5ecSTheodore Ts'o  * The regular allocator uses buddy scan only if the request len is power of
192c9de560dSAlex Tomas  * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
193c9de560dSAlex Tomas  * value of s_mb_order2_reqs can be tuned via
194b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_order2_req.  If the request len is equal to
195af901ca1SAndré Goddard Rosa  * stripe size (sbi->s_stripe), we try to search for contiguous block in
196b713a5ecSTheodore Ts'o  * stripe size. This should result in better allocation on RAID setups. If
197b713a5ecSTheodore Ts'o  * not, we search in the specific group using bitmap for best extents. The
198b713a5ecSTheodore Ts'o  * tunable min_to_scan and max_to_scan control the behaviour here.
199c9de560dSAlex Tomas  * min_to_scan indicate how long the mballoc __must__ look for a best
200b713a5ecSTheodore Ts'o  * extent and max_to_scan indicates how long the mballoc __can__ look for a
201c9de560dSAlex Tomas  * best extent in the found extents. Searching for the blocks starts with
202c9de560dSAlex Tomas  * the group specified as the goal value in allocation context via
203c9de560dSAlex Tomas  * ac_g_ex. Each group is first checked based on the criteria whether it
204caaf7a29STao Ma  * can be used for allocation. ext4_mb_good_group explains how the groups are
205c9de560dSAlex Tomas  * checked.
206c9de560dSAlex Tomas  *
207196e402aSHarshad Shirwadkar  * When "mb_optimize_scan" is turned on, as mentioned above, the groups may not
208196e402aSHarshad Shirwadkar  * get traversed linearly. That may result in subsequent allocations being not
209196e402aSHarshad Shirwadkar  * close to each other. And so, the underlying device may get filled up in a
210196e402aSHarshad Shirwadkar  * non-linear fashion. While that may not matter on non-rotational devices, for
211196e402aSHarshad Shirwadkar  * rotational devices that may result in higher seek times. "mb_linear_limit"
212196e402aSHarshad Shirwadkar  * tells mballoc how many groups mballoc should search linearly before
213196e402aSHarshad Shirwadkar  * performing consulting above data structures for more efficient lookups. For
214196e402aSHarshad Shirwadkar  * non rotational devices, this value defaults to 0 and for rotational devices
215196e402aSHarshad Shirwadkar  * this is set to MB_DEFAULT_LINEAR_LIMIT.
216196e402aSHarshad Shirwadkar  *
217c9de560dSAlex Tomas  * Both the prealloc space are getting populated as above. So for the first
218c9de560dSAlex Tomas  * request we will hit the buddy cache which will result in this prealloc
219c9de560dSAlex Tomas  * space getting filled. The prealloc space is then later used for the
220c9de560dSAlex Tomas  * subsequent request.
221c9de560dSAlex Tomas  */
222c9de560dSAlex Tomas 
223c9de560dSAlex Tomas /*
224c9de560dSAlex Tomas  * mballoc operates on the following data:
225c9de560dSAlex Tomas  *  - on-disk bitmap
226c9de560dSAlex Tomas  *  - in-core buddy (actually includes buddy and bitmap)
227c9de560dSAlex Tomas  *  - preallocation descriptors (PAs)
228c9de560dSAlex Tomas  *
229c9de560dSAlex Tomas  * there are two types of preallocations:
230c9de560dSAlex Tomas  *  - inode
231c9de560dSAlex Tomas  *    assiged to specific inode and can be used for this inode only.
232c9de560dSAlex Tomas  *    it describes part of inode's space preallocated to specific
233c9de560dSAlex Tomas  *    physical blocks. any block from that preallocated can be used
234c9de560dSAlex Tomas  *    independent. the descriptor just tracks number of blocks left
235c9de560dSAlex Tomas  *    unused. so, before taking some block from descriptor, one must
236c9de560dSAlex Tomas  *    make sure corresponded logical block isn't allocated yet. this
237c9de560dSAlex Tomas  *    also means that freeing any block within descriptor's range
238c9de560dSAlex Tomas  *    must discard all preallocated blocks.
239c9de560dSAlex Tomas  *  - locality group
240c9de560dSAlex Tomas  *    assigned to specific locality group which does not translate to
241c9de560dSAlex Tomas  *    permanent set of inodes: inode can join and leave group. space
242c9de560dSAlex Tomas  *    from this type of preallocation can be used for any inode. thus
243c9de560dSAlex Tomas  *    it's consumed from the beginning to the end.
244c9de560dSAlex Tomas  *
245c9de560dSAlex Tomas  * relation between them can be expressed as:
246c9de560dSAlex Tomas  *    in-core buddy = on-disk bitmap + preallocation descriptors
247c9de560dSAlex Tomas  *
248c9de560dSAlex Tomas  * this mean blocks mballoc considers used are:
249c9de560dSAlex Tomas  *  - allocated blocks (persistent)
250c9de560dSAlex Tomas  *  - preallocated blocks (non-persistent)
251c9de560dSAlex Tomas  *
252c9de560dSAlex Tomas  * consistency in mballoc world means that at any time a block is either
253c9de560dSAlex Tomas  * free or used in ALL structures. notice: "any time" should not be read
254c9de560dSAlex Tomas  * literally -- time is discrete and delimited by locks.
255c9de560dSAlex Tomas  *
256c9de560dSAlex Tomas  *  to keep it simple, we don't use block numbers, instead we count number of
257c9de560dSAlex Tomas  *  blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
258c9de560dSAlex Tomas  *
259c9de560dSAlex Tomas  * all operations can be expressed as:
260c9de560dSAlex Tomas  *  - init buddy:			buddy = on-disk + PAs
261c9de560dSAlex Tomas  *  - new PA:				buddy += N; PA = N
262c9de560dSAlex Tomas  *  - use inode PA:			on-disk += N; PA -= N
263c9de560dSAlex Tomas  *  - discard inode PA			buddy -= on-disk - PA; PA = 0
264c9de560dSAlex Tomas  *  - use locality group PA		on-disk += N; PA -= N
265c9de560dSAlex Tomas  *  - discard locality group PA		buddy -= PA; PA = 0
266c9de560dSAlex Tomas  *  note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
267c9de560dSAlex Tomas  *        is used in real operation because we can't know actual used
268c9de560dSAlex Tomas  *        bits from PA, only from on-disk bitmap
269c9de560dSAlex Tomas  *
270c9de560dSAlex Tomas  * if we follow this strict logic, then all operations above should be atomic.
271c9de560dSAlex Tomas  * given some of them can block, we'd have to use something like semaphores
272c9de560dSAlex Tomas  * killing performance on high-end SMP hardware. let's try to relax it using
273c9de560dSAlex Tomas  * the following knowledge:
274c9de560dSAlex Tomas  *  1) if buddy is referenced, it's already initialized
275c9de560dSAlex Tomas  *  2) while block is used in buddy and the buddy is referenced,
276c9de560dSAlex Tomas  *     nobody can re-allocate that block
277c9de560dSAlex Tomas  *  3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
278c9de560dSAlex Tomas  *     bit set and PA claims same block, it's OK. IOW, one can set bit in
279c9de560dSAlex Tomas  *     on-disk bitmap if buddy has same bit set or/and PA covers corresponded
280c9de560dSAlex Tomas  *     block
281c9de560dSAlex Tomas  *
282c9de560dSAlex Tomas  * so, now we're building a concurrency table:
283c9de560dSAlex Tomas  *  - init buddy vs.
284c9de560dSAlex Tomas  *    - new PA
285c9de560dSAlex Tomas  *      blocks for PA are allocated in the buddy, buddy must be referenced
286c9de560dSAlex Tomas  *      until PA is linked to allocation group to avoid concurrent buddy init
287c9de560dSAlex Tomas  *    - use inode PA
288c9de560dSAlex Tomas  *      we need to make sure that either on-disk bitmap or PA has uptodate data
289c9de560dSAlex Tomas  *      given (3) we care that PA-=N operation doesn't interfere with init
290c9de560dSAlex Tomas  *    - discard inode PA
291c9de560dSAlex Tomas  *      the simplest way would be to have buddy initialized by the discard
292c9de560dSAlex Tomas  *    - use locality group PA
293c9de560dSAlex Tomas  *      again PA-=N must be serialized with init
294c9de560dSAlex Tomas  *    - discard locality group PA
295c9de560dSAlex Tomas  *      the simplest way would be to have buddy initialized by the discard
296c9de560dSAlex Tomas  *  - new PA vs.
297c9de560dSAlex Tomas  *    - use inode PA
298c9de560dSAlex Tomas  *      i_data_sem serializes them
299c9de560dSAlex Tomas  *    - discard inode PA
300c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
301c9de560dSAlex Tomas  *    - use locality group PA
302c9de560dSAlex Tomas  *      some mutex should serialize them
303c9de560dSAlex Tomas  *    - discard locality group PA
304c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
305c9de560dSAlex Tomas  *  - use inode PA
306c9de560dSAlex Tomas  *    - use inode PA
307c9de560dSAlex Tomas  *      i_data_sem or another mutex should serializes them
308c9de560dSAlex Tomas  *    - discard inode PA
309c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
310c9de560dSAlex Tomas  *    - use locality group PA
311c9de560dSAlex Tomas  *      nothing wrong here -- they're different PAs covering different blocks
312c9de560dSAlex Tomas  *    - discard locality group PA
313c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
314c9de560dSAlex Tomas  *
315c9de560dSAlex Tomas  * now we're ready to make few consequences:
316c9de560dSAlex Tomas  *  - PA is referenced and while it is no discard is possible
317c9de560dSAlex Tomas  *  - PA is referenced until block isn't marked in on-disk bitmap
318c9de560dSAlex Tomas  *  - PA changes only after on-disk bitmap
319c9de560dSAlex Tomas  *  - discard must not compete with init. either init is done before
320c9de560dSAlex Tomas  *    any discard or they're serialized somehow
321c9de560dSAlex Tomas  *  - buddy init as sum of on-disk bitmap and PAs is done atomically
322c9de560dSAlex Tomas  *
323c9de560dSAlex Tomas  * a special case when we've used PA to emptiness. no need to modify buddy
324c9de560dSAlex Tomas  * in this case, but we should care about concurrent init
325c9de560dSAlex Tomas  *
326c9de560dSAlex Tomas  */
327c9de560dSAlex Tomas 
328c9de560dSAlex Tomas  /*
329c9de560dSAlex Tomas  * Logic in few words:
330c9de560dSAlex Tomas  *
331c9de560dSAlex Tomas  *  - allocation:
332c9de560dSAlex Tomas  *    load group
333c9de560dSAlex Tomas  *    find blocks
334c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
335c9de560dSAlex Tomas  *    release group
336c9de560dSAlex Tomas  *
337c9de560dSAlex Tomas  *  - use preallocation:
338c9de560dSAlex Tomas  *    find proper PA (per-inode or group)
339c9de560dSAlex Tomas  *    load group
340c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
341c9de560dSAlex Tomas  *    release group
342c9de560dSAlex Tomas  *    release PA
343c9de560dSAlex Tomas  *
344c9de560dSAlex Tomas  *  - free:
345c9de560dSAlex Tomas  *    load group
346c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
347c9de560dSAlex Tomas  *    release group
348c9de560dSAlex Tomas  *
349c9de560dSAlex Tomas  *  - discard preallocations in group:
350c9de560dSAlex Tomas  *    mark PAs deleted
351c9de560dSAlex Tomas  *    move them onto local list
352c9de560dSAlex Tomas  *    load on-disk bitmap
353c9de560dSAlex Tomas  *    load group
354c9de560dSAlex Tomas  *    remove PA from object (inode or locality group)
355c9de560dSAlex Tomas  *    mark free blocks in-core
356c9de560dSAlex Tomas  *
357c9de560dSAlex Tomas  *  - discard inode's preallocations:
358c9de560dSAlex Tomas  */
359c9de560dSAlex Tomas 
360c9de560dSAlex Tomas /*
361c9de560dSAlex Tomas  * Locking rules
362c9de560dSAlex Tomas  *
363c9de560dSAlex Tomas  * Locks:
364c9de560dSAlex Tomas  *  - bitlock on a group	(group)
365c9de560dSAlex Tomas  *  - object (inode/locality)	(object)
366c9de560dSAlex Tomas  *  - per-pa lock		(pa)
367f52f3d2bSOjaswin Mujoo  *  - cr_power2_aligned lists lock	(cr_power2_aligned)
368f52f3d2bSOjaswin Mujoo  *  - cr_goal_len_fast lists lock	(cr_goal_len_fast)
369c9de560dSAlex Tomas  *
370c9de560dSAlex Tomas  * Paths:
371c9de560dSAlex Tomas  *  - new pa
372c9de560dSAlex Tomas  *    object
373c9de560dSAlex Tomas  *    group
374c9de560dSAlex Tomas  *
375c9de560dSAlex Tomas  *  - find and use pa:
376c9de560dSAlex Tomas  *    pa
377c9de560dSAlex Tomas  *
378c9de560dSAlex Tomas  *  - release consumed pa:
379c9de560dSAlex Tomas  *    pa
380c9de560dSAlex Tomas  *    group
381c9de560dSAlex Tomas  *    object
382c9de560dSAlex Tomas  *
383c9de560dSAlex Tomas  *  - generate in-core bitmap:
384c9de560dSAlex Tomas  *    group
385c9de560dSAlex Tomas  *        pa
386c9de560dSAlex Tomas  *
387c9de560dSAlex Tomas  *  - discard all for given object (inode, locality group):
388c9de560dSAlex Tomas  *    object
389c9de560dSAlex Tomas  *        pa
390c9de560dSAlex Tomas  *    group
391c9de560dSAlex Tomas  *
392c9de560dSAlex Tomas  *  - discard all for given group:
393c9de560dSAlex Tomas  *    group
394c9de560dSAlex Tomas  *        pa
395c9de560dSAlex Tomas  *    group
396c9de560dSAlex Tomas  *        object
397c9de560dSAlex Tomas  *
398196e402aSHarshad Shirwadkar  *  - allocation path (ext4_mb_regular_allocator)
399196e402aSHarshad Shirwadkar  *    group
400f52f3d2bSOjaswin Mujoo  *    cr_power2_aligned/cr_goal_len_fast
401c9de560dSAlex Tomas  */
402c3a326a6SAneesh Kumar K.V static struct kmem_cache *ext4_pspace_cachep;
403c3a326a6SAneesh Kumar K.V static struct kmem_cache *ext4_ac_cachep;
40418aadd47SBobi Jam static struct kmem_cache *ext4_free_data_cachep;
405fb1813f4SCurt Wohlgemuth 
406fb1813f4SCurt Wohlgemuth /* We create slab caches for groupinfo data structures based on the
407fb1813f4SCurt Wohlgemuth  * superblock block size.  There will be one per mounted filesystem for
408fb1813f4SCurt Wohlgemuth  * each unique s_blocksize_bits */
4092892c15dSEric Sandeen #define NR_GRPINFO_CACHES 8
410fb1813f4SCurt Wohlgemuth static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
411fb1813f4SCurt Wohlgemuth 
412d6006186SEric Biggers static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
4132892c15dSEric Sandeen 	"ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
4142892c15dSEric Sandeen 	"ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
4152892c15dSEric Sandeen 	"ext4_groupinfo_64k", "ext4_groupinfo_128k"
4162892c15dSEric Sandeen };
4172892c15dSEric Sandeen 
418c3a326a6SAneesh Kumar K.V static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
419c3a326a6SAneesh Kumar K.V 					ext4_group_t group);
4207a2fcbf7SAneesh Kumar K.V static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
4217a2fcbf7SAneesh Kumar K.V 						ext4_group_t group);
42253f86b17SRitesh Harjani static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac);
423c3a326a6SAneesh Kumar K.V 
424196e402aSHarshad Shirwadkar static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
4254eb7a4a1SOjaswin Mujoo 			       ext4_group_t group, enum criteria cr);
426196e402aSHarshad Shirwadkar 
42755cdd0afSWang Jianchao static int ext4_try_to_trim_range(struct super_block *sb,
42855cdd0afSWang Jianchao 		struct ext4_buddy *e4b, ext4_grpblk_t start,
42955cdd0afSWang Jianchao 		ext4_grpblk_t max, ext4_grpblk_t minblocks);
43055cdd0afSWang Jianchao 
43107b5b8e1SRitesh Harjani /*
43207b5b8e1SRitesh Harjani  * The algorithm using this percpu seq counter goes below:
43307b5b8e1SRitesh Harjani  * 1. We sample the percpu discard_pa_seq counter before trying for block
43407b5b8e1SRitesh Harjani  *    allocation in ext4_mb_new_blocks().
43507b5b8e1SRitesh Harjani  * 2. We increment this percpu discard_pa_seq counter when we either allocate
43607b5b8e1SRitesh Harjani  *    or free these blocks i.e. while marking those blocks as used/free in
43707b5b8e1SRitesh Harjani  *    mb_mark_used()/mb_free_blocks().
43807b5b8e1SRitesh Harjani  * 3. We also increment this percpu seq counter when we successfully identify
43907b5b8e1SRitesh Harjani  *    that the bb_prealloc_list is not empty and hence proceed for discarding
44007b5b8e1SRitesh Harjani  *    of those PAs inside ext4_mb_discard_group_preallocations().
44107b5b8e1SRitesh Harjani  *
44207b5b8e1SRitesh Harjani  * Now to make sure that the regular fast path of block allocation is not
44307b5b8e1SRitesh Harjani  * affected, as a small optimization we only sample the percpu seq counter
44407b5b8e1SRitesh Harjani  * on that cpu. Only when the block allocation fails and when freed blocks
44507b5b8e1SRitesh Harjani  * found were 0, that is when we sample percpu seq counter for all cpus using
44607b5b8e1SRitesh Harjani  * below function ext4_get_discard_pa_seq_sum(). This happens after making
44707b5b8e1SRitesh Harjani  * sure that all the PAs on grp->bb_prealloc_list got freed or if it's empty.
44807b5b8e1SRitesh Harjani  */
44907b5b8e1SRitesh Harjani static DEFINE_PER_CPU(u64, discard_pa_seq);
45007b5b8e1SRitesh Harjani static inline u64 ext4_get_discard_pa_seq_sum(void)
45107b5b8e1SRitesh Harjani {
45207b5b8e1SRitesh Harjani 	int __cpu;
45307b5b8e1SRitesh Harjani 	u64 __seq = 0;
45407b5b8e1SRitesh Harjani 
45507b5b8e1SRitesh Harjani 	for_each_possible_cpu(__cpu)
45607b5b8e1SRitesh Harjani 		__seq += per_cpu(discard_pa_seq, __cpu);
45707b5b8e1SRitesh Harjani 	return __seq;
45807b5b8e1SRitesh Harjani }
45907b5b8e1SRitesh Harjani 
460ffad0a44SAneesh Kumar K.V static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
461ffad0a44SAneesh Kumar K.V {
462c9de560dSAlex Tomas #if BITS_PER_LONG == 64
463ffad0a44SAneesh Kumar K.V 	*bit += ((unsigned long) addr & 7UL) << 3;
464ffad0a44SAneesh Kumar K.V 	addr = (void *) ((unsigned long) addr & ~7UL);
465c9de560dSAlex Tomas #elif BITS_PER_LONG == 32
466ffad0a44SAneesh Kumar K.V 	*bit += ((unsigned long) addr & 3UL) << 3;
467ffad0a44SAneesh Kumar K.V 	addr = (void *) ((unsigned long) addr & ~3UL);
468c9de560dSAlex Tomas #else
469c9de560dSAlex Tomas #error "how many bits you are?!"
470c9de560dSAlex Tomas #endif
471ffad0a44SAneesh Kumar K.V 	return addr;
472ffad0a44SAneesh Kumar K.V }
473c9de560dSAlex Tomas 
474c9de560dSAlex Tomas static inline int mb_test_bit(int bit, void *addr)
475c9de560dSAlex Tomas {
476c9de560dSAlex Tomas 	/*
477c9de560dSAlex Tomas 	 * ext4_test_bit on architecture like powerpc
478c9de560dSAlex Tomas 	 * needs unsigned long aligned address
479c9de560dSAlex Tomas 	 */
480ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
481c9de560dSAlex Tomas 	return ext4_test_bit(bit, addr);
482c9de560dSAlex Tomas }
483c9de560dSAlex Tomas 
484c9de560dSAlex Tomas static inline void mb_set_bit(int bit, void *addr)
485c9de560dSAlex Tomas {
486ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
487c9de560dSAlex Tomas 	ext4_set_bit(bit, addr);
488c9de560dSAlex Tomas }
489c9de560dSAlex Tomas 
490c9de560dSAlex Tomas static inline void mb_clear_bit(int bit, void *addr)
491c9de560dSAlex Tomas {
492ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
493c9de560dSAlex Tomas 	ext4_clear_bit(bit, addr);
494c9de560dSAlex Tomas }
495c9de560dSAlex Tomas 
496eabe0444SAndrey Sidorov static inline int mb_test_and_clear_bit(int bit, void *addr)
497eabe0444SAndrey Sidorov {
498eabe0444SAndrey Sidorov 	addr = mb_correct_addr_and_bit(&bit, addr);
499eabe0444SAndrey Sidorov 	return ext4_test_and_clear_bit(bit, addr);
500eabe0444SAndrey Sidorov }
501eabe0444SAndrey Sidorov 
502ffad0a44SAneesh Kumar K.V static inline int mb_find_next_zero_bit(void *addr, int max, int start)
503ffad0a44SAneesh Kumar K.V {
504e7dfb246SAneesh Kumar K.V 	int fix = 0, ret, tmpmax;
505ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&fix, addr);
506e7dfb246SAneesh Kumar K.V 	tmpmax = max + fix;
507ffad0a44SAneesh Kumar K.V 	start += fix;
508ffad0a44SAneesh Kumar K.V 
509e7dfb246SAneesh Kumar K.V 	ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
510e7dfb246SAneesh Kumar K.V 	if (ret > max)
511e7dfb246SAneesh Kumar K.V 		return max;
512e7dfb246SAneesh Kumar K.V 	return ret;
513ffad0a44SAneesh Kumar K.V }
514ffad0a44SAneesh Kumar K.V 
515ffad0a44SAneesh Kumar K.V static inline int mb_find_next_bit(void *addr, int max, int start)
516ffad0a44SAneesh Kumar K.V {
517e7dfb246SAneesh Kumar K.V 	int fix = 0, ret, tmpmax;
518ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&fix, addr);
519e7dfb246SAneesh Kumar K.V 	tmpmax = max + fix;
520ffad0a44SAneesh Kumar K.V 	start += fix;
521ffad0a44SAneesh Kumar K.V 
522e7dfb246SAneesh Kumar K.V 	ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
523e7dfb246SAneesh Kumar K.V 	if (ret > max)
524e7dfb246SAneesh Kumar K.V 		return max;
525e7dfb246SAneesh Kumar K.V 	return ret;
526ffad0a44SAneesh Kumar K.V }
527ffad0a44SAneesh Kumar K.V 
528c9de560dSAlex Tomas static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
529c9de560dSAlex Tomas {
530c9de560dSAlex Tomas 	char *bb;
531c9de560dSAlex Tomas 
532c5e8f3f3STheodore Ts'o 	BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
533c9de560dSAlex Tomas 	BUG_ON(max == NULL);
534c9de560dSAlex Tomas 
535c9de560dSAlex Tomas 	if (order > e4b->bd_blkbits + 1) {
536c9de560dSAlex Tomas 		*max = 0;
537c9de560dSAlex Tomas 		return NULL;
538c9de560dSAlex Tomas 	}
539c9de560dSAlex Tomas 
540c9de560dSAlex Tomas 	/* at order 0 we see each particular block */
54184b775a3SColy Li 	if (order == 0) {
542c9de560dSAlex Tomas 		*max = 1 << (e4b->bd_blkbits + 3);
543c5e8f3f3STheodore Ts'o 		return e4b->bd_bitmap;
54484b775a3SColy Li 	}
545c9de560dSAlex Tomas 
546c5e8f3f3STheodore Ts'o 	bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
547c9de560dSAlex Tomas 	*max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
548c9de560dSAlex Tomas 
549c9de560dSAlex Tomas 	return bb;
550c9de560dSAlex Tomas }
551c9de560dSAlex Tomas 
552c9de560dSAlex Tomas #ifdef DOUBLE_CHECK
553c9de560dSAlex Tomas static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
554c9de560dSAlex Tomas 			   int first, int count)
555c9de560dSAlex Tomas {
556c9de560dSAlex Tomas 	int i;
557c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
558c9de560dSAlex Tomas 
559c9de560dSAlex Tomas 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
560c9de560dSAlex Tomas 		return;
561bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
562c9de560dSAlex Tomas 	for (i = 0; i < count; i++) {
563c9de560dSAlex Tomas 		if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
564c9de560dSAlex Tomas 			ext4_fsblk_t blocknr;
5655661bd68SAkinobu Mita 
5665661bd68SAkinobu Mita 			blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
56753accfa9STheodore Ts'o 			blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
5685d1b1b3fSAneesh Kumar K.V 			ext4_grp_locked_error(sb, e4b->bd_group,
569e29136f8STheodore Ts'o 					      inode ? inode->i_ino : 0,
570e29136f8STheodore Ts'o 					      blocknr,
571e29136f8STheodore Ts'o 					      "freeing block already freed "
572e29136f8STheodore Ts'o 					      "(bit %u)",
573e29136f8STheodore Ts'o 					      first + i);
574736dedbbSWang Shilong 			ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
575736dedbbSWang Shilong 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
576c9de560dSAlex Tomas 		}
577c9de560dSAlex Tomas 		mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
578c9de560dSAlex Tomas 	}
579c9de560dSAlex Tomas }
580c9de560dSAlex Tomas 
581c9de560dSAlex Tomas static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
582c9de560dSAlex Tomas {
583c9de560dSAlex Tomas 	int i;
584c9de560dSAlex Tomas 
585c9de560dSAlex Tomas 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
586c9de560dSAlex Tomas 		return;
587bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
588c9de560dSAlex Tomas 	for (i = 0; i < count; i++) {
589c9de560dSAlex Tomas 		BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
590c9de560dSAlex Tomas 		mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
591c9de560dSAlex Tomas 	}
592c9de560dSAlex Tomas }
593c9de560dSAlex Tomas 
594c9de560dSAlex Tomas static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
595c9de560dSAlex Tomas {
596eb2b8ebbSRitesh Harjani 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
597eb2b8ebbSRitesh Harjani 		return;
598c9de560dSAlex Tomas 	if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
599c9de560dSAlex Tomas 		unsigned char *b1, *b2;
600c9de560dSAlex Tomas 		int i;
601c9de560dSAlex Tomas 		b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
602c9de560dSAlex Tomas 		b2 = (unsigned char *) bitmap;
603c9de560dSAlex Tomas 		for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
604c9de560dSAlex Tomas 			if (b1[i] != b2[i]) {
6059d8b9ec4STheodore Ts'o 				ext4_msg(e4b->bd_sb, KERN_ERR,
6069d8b9ec4STheodore Ts'o 					 "corruption in group %u "
6074776004fSTheodore Ts'o 					 "at byte %u(%u): %x in copy != %x "
6089d8b9ec4STheodore Ts'o 					 "on disk/prealloc",
609c9de560dSAlex Tomas 					 e4b->bd_group, i, i * 8, b1[i], b2[i]);
610c9de560dSAlex Tomas 				BUG();
611c9de560dSAlex Tomas 			}
612c9de560dSAlex Tomas 		}
613c9de560dSAlex Tomas 	}
614c9de560dSAlex Tomas }
615c9de560dSAlex Tomas 
616a3450215SRitesh Harjani static void mb_group_bb_bitmap_alloc(struct super_block *sb,
617a3450215SRitesh Harjani 			struct ext4_group_info *grp, ext4_group_t group)
618a3450215SRitesh Harjani {
619a3450215SRitesh Harjani 	struct buffer_head *bh;
620a3450215SRitesh Harjani 
621a3450215SRitesh Harjani 	grp->bb_bitmap = kmalloc(sb->s_blocksize, GFP_NOFS);
622eb2b8ebbSRitesh Harjani 	if (!grp->bb_bitmap)
623eb2b8ebbSRitesh Harjani 		return;
624a3450215SRitesh Harjani 
625a3450215SRitesh Harjani 	bh = ext4_read_block_bitmap(sb, group);
626eb2b8ebbSRitesh Harjani 	if (IS_ERR_OR_NULL(bh)) {
627eb2b8ebbSRitesh Harjani 		kfree(grp->bb_bitmap);
628eb2b8ebbSRitesh Harjani 		grp->bb_bitmap = NULL;
629eb2b8ebbSRitesh Harjani 		return;
630eb2b8ebbSRitesh Harjani 	}
631a3450215SRitesh Harjani 
632a3450215SRitesh Harjani 	memcpy(grp->bb_bitmap, bh->b_data, sb->s_blocksize);
633a3450215SRitesh Harjani 	put_bh(bh);
634a3450215SRitesh Harjani }
635a3450215SRitesh Harjani 
636a3450215SRitesh Harjani static void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
637a3450215SRitesh Harjani {
638a3450215SRitesh Harjani 	kfree(grp->bb_bitmap);
639a3450215SRitesh Harjani }
640a3450215SRitesh Harjani 
641c9de560dSAlex Tomas #else
642c9de560dSAlex Tomas static inline void mb_free_blocks_double(struct inode *inode,
643c9de560dSAlex Tomas 				struct ext4_buddy *e4b, int first, int count)
644c9de560dSAlex Tomas {
645c9de560dSAlex Tomas 	return;
646c9de560dSAlex Tomas }
647c9de560dSAlex Tomas static inline void mb_mark_used_double(struct ext4_buddy *e4b,
648c9de560dSAlex Tomas 						int first, int count)
649c9de560dSAlex Tomas {
650c9de560dSAlex Tomas 	return;
651c9de560dSAlex Tomas }
652c9de560dSAlex Tomas static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
653c9de560dSAlex Tomas {
654c9de560dSAlex Tomas 	return;
655c9de560dSAlex Tomas }
656a3450215SRitesh Harjani 
657a3450215SRitesh Harjani static inline void mb_group_bb_bitmap_alloc(struct super_block *sb,
658a3450215SRitesh Harjani 			struct ext4_group_info *grp, ext4_group_t group)
659a3450215SRitesh Harjani {
660a3450215SRitesh Harjani 	return;
661a3450215SRitesh Harjani }
662a3450215SRitesh Harjani 
663a3450215SRitesh Harjani static inline void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
664a3450215SRitesh Harjani {
665a3450215SRitesh Harjani 	return;
666a3450215SRitesh Harjani }
667c9de560dSAlex Tomas #endif
668c9de560dSAlex Tomas 
669c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
670c9de560dSAlex Tomas 
671c9de560dSAlex Tomas #define MB_CHECK_ASSERT(assert)						\
672c9de560dSAlex Tomas do {									\
673c9de560dSAlex Tomas 	if (!(assert)) {						\
674c9de560dSAlex Tomas 		printk(KERN_EMERG					\
675c9de560dSAlex Tomas 			"Assertion failure in %s() at %s:%d: \"%s\"\n",	\
676c9de560dSAlex Tomas 			function, file, line, # assert);		\
677c9de560dSAlex Tomas 		BUG();							\
678c9de560dSAlex Tomas 	}								\
679c9de560dSAlex Tomas } while (0)
680c9de560dSAlex Tomas 
681c9de560dSAlex Tomas static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
682c9de560dSAlex Tomas 				const char *function, int line)
683c9de560dSAlex Tomas {
684c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
685c9de560dSAlex Tomas 	int order = e4b->bd_blkbits + 1;
686c9de560dSAlex Tomas 	int max;
687c9de560dSAlex Tomas 	int max2;
688c9de560dSAlex Tomas 	int i;
689c9de560dSAlex Tomas 	int j;
690c9de560dSAlex Tomas 	int k;
691c9de560dSAlex Tomas 	int count;
692c9de560dSAlex Tomas 	struct ext4_group_info *grp;
693c9de560dSAlex Tomas 	int fragments = 0;
694c9de560dSAlex Tomas 	int fstart;
695c9de560dSAlex Tomas 	struct list_head *cur;
696c9de560dSAlex Tomas 	void *buddy;
697c9de560dSAlex Tomas 	void *buddy2;
698c9de560dSAlex Tomas 
699addd752cSChunguang Xu 	if (e4b->bd_info->bb_check_counter++ % 10)
700c9de560dSAlex Tomas 		return 0;
701c9de560dSAlex Tomas 
702c9de560dSAlex Tomas 	while (order > 1) {
703c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, order, &max);
704c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy);
705c9de560dSAlex Tomas 		buddy2 = mb_find_buddy(e4b, order - 1, &max2);
706c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy2);
707c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy != buddy2);
708c9de560dSAlex Tomas 		MB_CHECK_ASSERT(max * 2 == max2);
709c9de560dSAlex Tomas 
710c9de560dSAlex Tomas 		count = 0;
711c9de560dSAlex Tomas 		for (i = 0; i < max; i++) {
712c9de560dSAlex Tomas 
713c9de560dSAlex Tomas 			if (mb_test_bit(i, buddy)) {
714af2b3275SJinke Han 				/* only single bit in buddy2 may be 0 */
715c9de560dSAlex Tomas 				if (!mb_test_bit(i << 1, buddy2)) {
716c9de560dSAlex Tomas 					MB_CHECK_ASSERT(
717c9de560dSAlex Tomas 						mb_test_bit((i<<1)+1, buddy2));
718c9de560dSAlex Tomas 				}
719c9de560dSAlex Tomas 				continue;
720c9de560dSAlex Tomas 			}
721c9de560dSAlex Tomas 
7220a10da73SRobin Dong 			/* both bits in buddy2 must be 1 */
723c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
724c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
725c9de560dSAlex Tomas 
726c9de560dSAlex Tomas 			for (j = 0; j < (1 << order); j++) {
727c9de560dSAlex Tomas 				k = (i * (1 << order)) + j;
728c9de560dSAlex Tomas 				MB_CHECK_ASSERT(
729c5e8f3f3STheodore Ts'o 					!mb_test_bit(k, e4b->bd_bitmap));
730c9de560dSAlex Tomas 			}
731c9de560dSAlex Tomas 			count++;
732c9de560dSAlex Tomas 		}
733c9de560dSAlex Tomas 		MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
734c9de560dSAlex Tomas 		order--;
735c9de560dSAlex Tomas 	}
736c9de560dSAlex Tomas 
737c9de560dSAlex Tomas 	fstart = -1;
738c9de560dSAlex Tomas 	buddy = mb_find_buddy(e4b, 0, &max);
739c9de560dSAlex Tomas 	for (i = 0; i < max; i++) {
740c9de560dSAlex Tomas 		if (!mb_test_bit(i, buddy)) {
741c9de560dSAlex Tomas 			MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
742c9de560dSAlex Tomas 			if (fstart == -1) {
743c9de560dSAlex Tomas 				fragments++;
744c9de560dSAlex Tomas 				fstart = i;
745c9de560dSAlex Tomas 			}
746c9de560dSAlex Tomas 			continue;
747c9de560dSAlex Tomas 		}
748c9de560dSAlex Tomas 		fstart = -1;
749c9de560dSAlex Tomas 		/* check used bits only */
750c9de560dSAlex Tomas 		for (j = 0; j < e4b->bd_blkbits + 1; j++) {
751c9de560dSAlex Tomas 			buddy2 = mb_find_buddy(e4b, j, &max2);
752c9de560dSAlex Tomas 			k = i >> j;
753c9de560dSAlex Tomas 			MB_CHECK_ASSERT(k < max2);
754c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
755c9de560dSAlex Tomas 		}
756c9de560dSAlex Tomas 	}
757c9de560dSAlex Tomas 	MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
758c9de560dSAlex Tomas 	MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
759c9de560dSAlex Tomas 
760c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, e4b->bd_group);
7615354b2afSTheodore Ts'o 	if (!grp)
7625354b2afSTheodore Ts'o 		return NULL;
763c9de560dSAlex Tomas 	list_for_each(cur, &grp->bb_prealloc_list) {
764c9de560dSAlex Tomas 		ext4_group_t groupnr;
765c9de560dSAlex Tomas 		struct ext4_prealloc_space *pa;
76660bd63d1SSolofo Ramangalahy 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
76760bd63d1SSolofo Ramangalahy 		ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
768c9de560dSAlex Tomas 		MB_CHECK_ASSERT(groupnr == e4b->bd_group);
76960bd63d1SSolofo Ramangalahy 		for (i = 0; i < pa->pa_len; i++)
770c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
771c9de560dSAlex Tomas 	}
772c9de560dSAlex Tomas 	return 0;
773c9de560dSAlex Tomas }
774c9de560dSAlex Tomas #undef MB_CHECK_ASSERT
775c9de560dSAlex Tomas #define mb_check_buddy(e4b) __mb_check_buddy(e4b,	\
77646e665e9SHarvey Harrison 					__FILE__, __func__, __LINE__)
777c9de560dSAlex Tomas #else
778c9de560dSAlex Tomas #define mb_check_buddy(e4b)
779c9de560dSAlex Tomas #endif
780c9de560dSAlex Tomas 
7817c786059SColy Li /*
7827c786059SColy Li  * Divide blocks started from @first with length @len into
7837c786059SColy Li  * smaller chunks with power of 2 blocks.
7847c786059SColy Li  * Clear the bits in bitmap which the blocks of the chunk(s) covered,
7857c786059SColy Li  * then increase bb_counters[] for corresponded chunk size.
7867c786059SColy Li  */
787c9de560dSAlex Tomas static void ext4_mb_mark_free_simple(struct super_block *sb,
788a36b4498SEric Sandeen 				void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
789c9de560dSAlex Tomas 					struct ext4_group_info *grp)
790c9de560dSAlex Tomas {
791c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
792a36b4498SEric Sandeen 	ext4_grpblk_t min;
793a36b4498SEric Sandeen 	ext4_grpblk_t max;
794a36b4498SEric Sandeen 	ext4_grpblk_t chunk;
79569e43e8cSChandan Rajendra 	unsigned int border;
796c9de560dSAlex Tomas 
7977137d7a4STheodore Ts'o 	BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
798c9de560dSAlex Tomas 
799c9de560dSAlex Tomas 	border = 2 << sb->s_blocksize_bits;
800c9de560dSAlex Tomas 
801c9de560dSAlex Tomas 	while (len > 0) {
802c9de560dSAlex Tomas 		/* find how many blocks can be covered since this position */
803c9de560dSAlex Tomas 		max = ffs(first | border) - 1;
804c9de560dSAlex Tomas 
805c9de560dSAlex Tomas 		/* find how many blocks of power 2 we need to mark */
806c9de560dSAlex Tomas 		min = fls(len) - 1;
807c9de560dSAlex Tomas 
808c9de560dSAlex Tomas 		if (max < min)
809c9de560dSAlex Tomas 			min = max;
810c9de560dSAlex Tomas 		chunk = 1 << min;
811c9de560dSAlex Tomas 
812c9de560dSAlex Tomas 		/* mark multiblock chunks only */
813c9de560dSAlex Tomas 		grp->bb_counters[min]++;
814c9de560dSAlex Tomas 		if (min > 0)
815c9de560dSAlex Tomas 			mb_clear_bit(first >> min,
816c9de560dSAlex Tomas 				     buddy + sbi->s_mb_offsets[min]);
817c9de560dSAlex Tomas 
818c9de560dSAlex Tomas 		len -= chunk;
819c9de560dSAlex Tomas 		first += chunk;
820c9de560dSAlex Tomas 	}
821c9de560dSAlex Tomas }
822c9de560dSAlex Tomas 
82383e80a6eSJan Kara static int mb_avg_fragment_size_order(struct super_block *sb, ext4_grpblk_t len)
824196e402aSHarshad Shirwadkar {
82583e80a6eSJan Kara 	int order;
826196e402aSHarshad Shirwadkar 
827196e402aSHarshad Shirwadkar 	/*
82883e80a6eSJan Kara 	 * We don't bother with a special lists groups with only 1 block free
82983e80a6eSJan Kara 	 * extents and for completely empty groups.
830196e402aSHarshad Shirwadkar 	 */
83183e80a6eSJan Kara 	order = fls(len) - 2;
83283e80a6eSJan Kara 	if (order < 0)
83383e80a6eSJan Kara 		return 0;
83483e80a6eSJan Kara 	if (order == MB_NUM_ORDERS(sb))
83583e80a6eSJan Kara 		order--;
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 
846196e402aSHarshad Shirwadkar 	if (!test_opt2(sb, MB_OPTIMIZE_SCAN) || grp->bb_free == 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,
8754eb7a4a1SOjaswin Mujoo 			enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
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,
9494eb7a4a1SOjaswin Mujoo 		enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
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,
9947e170922SOjaswin Mujoo 		enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
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;
1013f52f3d2bSOjaswin Mujoo 	min_order = order - sbi->s_mb_best_avail_max_trim_order;
10147e170922SOjaswin Mujoo 	if (min_order < 0)
10157e170922SOjaswin Mujoo 		min_order = 0;
10167e170922SOjaswin Mujoo 
10177e170922SOjaswin Mujoo 	if (sbi->s_stripe > 0) {
10187e170922SOjaswin Mujoo 		/*
10197e170922SOjaswin Mujoo 		 * We are assuming that stripe size is always a multiple of
10207e170922SOjaswin Mujoo 		 * cluster ratio otherwise __ext4_fill_super exists early.
10217e170922SOjaswin Mujoo 		 */
10227e170922SOjaswin Mujoo 		num_stripe_clusters = EXT4_NUM_B2C(sbi, sbi->s_stripe);
10237e170922SOjaswin Mujoo 		if (1 << min_order < num_stripe_clusters)
10245d5460faSOjaswin Mujoo 			/*
10255d5460faSOjaswin Mujoo 			 * We consider 1 order less because later we round
10265d5460faSOjaswin Mujoo 			 * up the goal len to num_stripe_clusters
10275d5460faSOjaswin Mujoo 			 */
10285d5460faSOjaswin Mujoo 			min_order = fls(num_stripe_clusters) - 1;
10297e170922SOjaswin Mujoo 	}
10307e170922SOjaswin Mujoo 
10315d5460faSOjaswin Mujoo 	if (1 << min_order < ac->ac_o_ex.fe_len)
10325d5460faSOjaswin Mujoo 		min_order = fls(ac->ac_o_ex.fe_len);
10335d5460faSOjaswin Mujoo 
10347e170922SOjaswin Mujoo 	for (i = order; i >= min_order; i--) {
10357e170922SOjaswin Mujoo 		int frag_order;
10367e170922SOjaswin Mujoo 		/*
10377e170922SOjaswin Mujoo 		 * Scale down goal len to make sure we find something
10387e170922SOjaswin Mujoo 		 * in the free fragments list. Basically, reduce
10397e170922SOjaswin Mujoo 		 * preallocations.
10407e170922SOjaswin Mujoo 		 */
10417e170922SOjaswin Mujoo 		ac->ac_g_ex.fe_len = 1 << i;
10427e170922SOjaswin Mujoo 
10437e170922SOjaswin Mujoo 		if (num_stripe_clusters > 0) {
10447e170922SOjaswin Mujoo 			/*
10454c0cfebdSTheodore Ts'o 			 * Try to round up the adjusted goal length to
10464c0cfebdSTheodore Ts'o 			 * stripe size (in cluster units) multiple for
10474c0cfebdSTheodore Ts'o 			 * efficiency.
10487e170922SOjaswin Mujoo 			 */
10497e170922SOjaswin Mujoo 			ac->ac_g_ex.fe_len = roundup(ac->ac_g_ex.fe_len,
10507e170922SOjaswin Mujoo 						     num_stripe_clusters);
10517e170922SOjaswin Mujoo 		}
10527e170922SOjaswin Mujoo 
10537e170922SOjaswin Mujoo 		frag_order = mb_avg_fragment_size_order(ac->ac_sb,
10547e170922SOjaswin Mujoo 							ac->ac_g_ex.fe_len);
10557e170922SOjaswin Mujoo 
10567e170922SOjaswin Mujoo 		grp = ext4_mb_find_good_group_avg_frag_lists(ac, frag_order);
10577e170922SOjaswin Mujoo 		if (grp) {
10587e170922SOjaswin Mujoo 			*group = grp->bb_group;
1059f52f3d2bSOjaswin Mujoo 			ac->ac_flags |= EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED;
1060bcb123acSKemeng Shi 			return;
1061bcb123acSKemeng Shi 		}
1062bcb123acSKemeng Shi 	}
1063bcb123acSKemeng Shi 
1064f52f3d2bSOjaswin Mujoo 	/* Reset goal length to original goal length before falling into CR_GOAL_LEN_SLOW */
10657e170922SOjaswin Mujoo 	ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
1066f52f3d2bSOjaswin Mujoo 	*new_cr = CR_GOAL_LEN_SLOW;
1067196e402aSHarshad Shirwadkar }
1068196e402aSHarshad Shirwadkar 
1069196e402aSHarshad Shirwadkar static inline int should_optimize_scan(struct ext4_allocation_context *ac)
1070196e402aSHarshad Shirwadkar {
1071196e402aSHarshad Shirwadkar 	if (unlikely(!test_opt2(ac->ac_sb, MB_OPTIMIZE_SCAN)))
1072196e402aSHarshad Shirwadkar 		return 0;
1073f52f3d2bSOjaswin Mujoo 	if (ac->ac_criteria >= CR_GOAL_LEN_SLOW)
1074196e402aSHarshad Shirwadkar 		return 0;
1075077d0c2cSOjaswin Mujoo 	if (!ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS))
1076196e402aSHarshad Shirwadkar 		return 0;
1077196e402aSHarshad Shirwadkar 	return 1;
1078196e402aSHarshad Shirwadkar }
1079196e402aSHarshad Shirwadkar 
1080196e402aSHarshad Shirwadkar /*
1081196e402aSHarshad Shirwadkar  * Return next linear group for allocation. If linear traversal should not be
1082196e402aSHarshad Shirwadkar  * performed, this function just returns the same group
1083196e402aSHarshad Shirwadkar  */
108460c672b7SKemeng Shi static ext4_group_t
108560c672b7SKemeng Shi next_linear_group(struct ext4_allocation_context *ac, ext4_group_t group,
108660c672b7SKemeng Shi 		  ext4_group_t ngroups)
1087196e402aSHarshad Shirwadkar {
1088196e402aSHarshad Shirwadkar 	if (!should_optimize_scan(ac))
1089196e402aSHarshad Shirwadkar 		goto inc_and_return;
1090196e402aSHarshad Shirwadkar 
1091196e402aSHarshad Shirwadkar 	if (ac->ac_groups_linear_remaining) {
1092196e402aSHarshad Shirwadkar 		ac->ac_groups_linear_remaining--;
1093196e402aSHarshad Shirwadkar 		goto inc_and_return;
1094196e402aSHarshad Shirwadkar 	}
1095196e402aSHarshad Shirwadkar 
1096196e402aSHarshad Shirwadkar 	return group;
1097196e402aSHarshad Shirwadkar inc_and_return:
1098196e402aSHarshad Shirwadkar 	/*
1099196e402aSHarshad Shirwadkar 	 * Artificially restricted ngroups for non-extent
1100196e402aSHarshad Shirwadkar 	 * files makes group > ngroups possible on first loop.
1101196e402aSHarshad Shirwadkar 	 */
1102196e402aSHarshad Shirwadkar 	return group + 1 >= ngroups ? 0 : group + 1;
1103196e402aSHarshad Shirwadkar }
1104196e402aSHarshad Shirwadkar 
1105196e402aSHarshad Shirwadkar /*
1106196e402aSHarshad Shirwadkar  * ext4_mb_choose_next_group: choose next group for allocation.
1107196e402aSHarshad Shirwadkar  *
1108196e402aSHarshad Shirwadkar  * @ac        Allocation Context
1109196e402aSHarshad Shirwadkar  * @new_cr    This is an output parameter. If the there is no good group
1110196e402aSHarshad Shirwadkar  *            available at current CR level, this field is updated to indicate
1111196e402aSHarshad Shirwadkar  *            the new cr level that should be used.
1112196e402aSHarshad Shirwadkar  * @group     This is an input / output parameter. As an input it indicates the
1113196e402aSHarshad Shirwadkar  *            next group that the allocator intends to use for allocation. As
1114196e402aSHarshad Shirwadkar  *            output, this field indicates the next group that should be used as
1115196e402aSHarshad Shirwadkar  *            determined by the optimization functions.
1116196e402aSHarshad Shirwadkar  * @ngroups   Total number of groups
1117196e402aSHarshad Shirwadkar  */
1118196e402aSHarshad Shirwadkar static void ext4_mb_choose_next_group(struct ext4_allocation_context *ac,
11194eb7a4a1SOjaswin Mujoo 		enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
1120196e402aSHarshad Shirwadkar {
1121196e402aSHarshad Shirwadkar 	*new_cr = ac->ac_criteria;
1122196e402aSHarshad Shirwadkar 
11234fca50d4SJan Kara 	if (!should_optimize_scan(ac) || ac->ac_groups_linear_remaining) {
11244fca50d4SJan Kara 		*group = next_linear_group(ac, *group, ngroups);
1125196e402aSHarshad Shirwadkar 		return;
11264fca50d4SJan Kara 	}
1127196e402aSHarshad Shirwadkar 
1128f52f3d2bSOjaswin Mujoo 	if (*new_cr == CR_POWER2_ALIGNED) {
1129f52f3d2bSOjaswin Mujoo 		ext4_mb_choose_next_group_p2_aligned(ac, new_cr, group, ngroups);
1130f52f3d2bSOjaswin Mujoo 	} else if (*new_cr == CR_GOAL_LEN_FAST) {
1131f52f3d2bSOjaswin Mujoo 		ext4_mb_choose_next_group_goal_fast(ac, new_cr, group, ngroups);
1132f52f3d2bSOjaswin Mujoo 	} else if (*new_cr == CR_BEST_AVAIL_LEN) {
1133f52f3d2bSOjaswin Mujoo 		ext4_mb_choose_next_group_best_avail(ac, new_cr, group, ngroups);
1134196e402aSHarshad Shirwadkar 	} else {
1135196e402aSHarshad Shirwadkar 		/*
1136196e402aSHarshad Shirwadkar 		 * TODO: For CR=2, we can arrange groups in an rb tree sorted by
1137196e402aSHarshad Shirwadkar 		 * bb_free. But until that happens, we should never come here.
1138196e402aSHarshad Shirwadkar 		 */
1139196e402aSHarshad Shirwadkar 		WARN_ON(1);
1140196e402aSHarshad Shirwadkar 	}
1141196e402aSHarshad Shirwadkar }
1142196e402aSHarshad Shirwadkar 
11438a57d9d6SCurt Wohlgemuth /*
11448a57d9d6SCurt Wohlgemuth  * Cache the order of the largest free extent we have available in this block
11458a57d9d6SCurt Wohlgemuth  * group.
11468a57d9d6SCurt Wohlgemuth  */
11478a57d9d6SCurt Wohlgemuth static void
11488a57d9d6SCurt Wohlgemuth mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
11498a57d9d6SCurt Wohlgemuth {
1150196e402aSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
11518a57d9d6SCurt Wohlgemuth 	int i;
11528a57d9d6SCurt Wohlgemuth 
11531940265eSJan Kara 	for (i = MB_NUM_ORDERS(sb) - 1; i >= 0; i--)
11541940265eSJan Kara 		if (grp->bb_counters[i] > 0)
11551940265eSJan Kara 			break;
11561940265eSJan Kara 	/* No need to move between order lists? */
11571940265eSJan Kara 	if (!test_opt2(sb, MB_OPTIMIZE_SCAN) ||
11581940265eSJan Kara 	    i == grp->bb_largest_free_order) {
11591940265eSJan Kara 		grp->bb_largest_free_order = i;
11601940265eSJan Kara 		return;
11611940265eSJan Kara 	}
11621940265eSJan Kara 
11631940265eSJan Kara 	if (grp->bb_largest_free_order >= 0) {
1164196e402aSHarshad Shirwadkar 		write_lock(&sbi->s_mb_largest_free_orders_locks[
1165196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1166196e402aSHarshad Shirwadkar 		list_del_init(&grp->bb_largest_free_order_node);
1167196e402aSHarshad Shirwadkar 		write_unlock(&sbi->s_mb_largest_free_orders_locks[
1168196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1169196e402aSHarshad Shirwadkar 	}
11708a57d9d6SCurt Wohlgemuth 	grp->bb_largest_free_order = i;
11711940265eSJan Kara 	if (grp->bb_largest_free_order >= 0 && grp->bb_free) {
1172196e402aSHarshad Shirwadkar 		write_lock(&sbi->s_mb_largest_free_orders_locks[
1173196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1174196e402aSHarshad Shirwadkar 		list_add_tail(&grp->bb_largest_free_order_node,
1175196e402aSHarshad Shirwadkar 		      &sbi->s_mb_largest_free_orders[grp->bb_largest_free_order]);
1176196e402aSHarshad Shirwadkar 		write_unlock(&sbi->s_mb_largest_free_orders_locks[
1177196e402aSHarshad Shirwadkar 					      grp->bb_largest_free_order]);
1178196e402aSHarshad Shirwadkar 	}
11798a57d9d6SCurt Wohlgemuth }
11808a57d9d6SCurt Wohlgemuth 
1181089ceeccSEric Sandeen static noinline_for_stack
1182089ceeccSEric Sandeen void ext4_mb_generate_buddy(struct super_block *sb,
11835354b2afSTheodore Ts'o 			    void *buddy, void *bitmap, ext4_group_t group,
11845354b2afSTheodore Ts'o 			    struct ext4_group_info *grp)
1185c9de560dSAlex Tomas {
1186e43bb4e6SNamjae Jeon 	struct ext4_sb_info *sbi = EXT4_SB(sb);
11877137d7a4STheodore Ts'o 	ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
1188a36b4498SEric Sandeen 	ext4_grpblk_t i = 0;
1189a36b4498SEric Sandeen 	ext4_grpblk_t first;
1190a36b4498SEric Sandeen 	ext4_grpblk_t len;
1191c9de560dSAlex Tomas 	unsigned free = 0;
1192c9de560dSAlex Tomas 	unsigned fragments = 0;
1193c9de560dSAlex Tomas 	unsigned long long period = get_cycles();
1194c9de560dSAlex Tomas 
1195c9de560dSAlex Tomas 	/* initialize buddy from bitmap which is aggregation
1196c9de560dSAlex Tomas 	 * of on-disk bitmap and preallocations */
1197ffad0a44SAneesh Kumar K.V 	i = mb_find_next_zero_bit(bitmap, max, 0);
1198c9de560dSAlex Tomas 	grp->bb_first_free = i;
1199c9de560dSAlex Tomas 	while (i < max) {
1200c9de560dSAlex Tomas 		fragments++;
1201c9de560dSAlex Tomas 		first = i;
1202ffad0a44SAneesh Kumar K.V 		i = mb_find_next_bit(bitmap, max, i);
1203c9de560dSAlex Tomas 		len = i - first;
1204c9de560dSAlex Tomas 		free += len;
1205c9de560dSAlex Tomas 		if (len > 1)
1206c9de560dSAlex Tomas 			ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
1207c9de560dSAlex Tomas 		else
1208c9de560dSAlex Tomas 			grp->bb_counters[0]++;
1209c9de560dSAlex Tomas 		if (i < max)
1210ffad0a44SAneesh Kumar K.V 			i = mb_find_next_zero_bit(bitmap, max, i);
1211c9de560dSAlex Tomas 	}
1212c9de560dSAlex Tomas 	grp->bb_fragments = fragments;
1213c9de560dSAlex Tomas 
1214c9de560dSAlex Tomas 	if (free != grp->bb_free) {
1215e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0,
121694d4c066STheodore Ts'o 				      "block bitmap and bg descriptor "
121794d4c066STheodore Ts'o 				      "inconsistent: %u vs %u free clusters",
1218e29136f8STheodore Ts'o 				      free, grp->bb_free);
1219e56eb659SAneesh Kumar K.V 		/*
1220163a203dSDarrick J. Wong 		 * If we intend to continue, we consider group descriptor
1221e56eb659SAneesh Kumar K.V 		 * corrupt and update bb_free using bitmap value
1222e56eb659SAneesh Kumar K.V 		 */
1223c9de560dSAlex Tomas 		grp->bb_free = free;
1224db79e6d1SWang Shilong 		ext4_mark_group_bitmap_corrupted(sb, group,
1225db79e6d1SWang Shilong 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1226c9de560dSAlex Tomas 	}
12278a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, grp);
122883e80a6eSJan Kara 	mb_update_avg_fragment_size(sb, grp);
1229c9de560dSAlex Tomas 
1230c9de560dSAlex Tomas 	clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
1231c9de560dSAlex Tomas 
1232c9de560dSAlex Tomas 	period = get_cycles() - period;
123367d25186SHarshad Shirwadkar 	atomic_inc(&sbi->s_mb_buddies_generated);
123467d25186SHarshad Shirwadkar 	atomic64_add(period, &sbi->s_mb_generation_time);
1235c9de560dSAlex Tomas }
1236c9de560dSAlex Tomas 
1237c9de560dSAlex Tomas /* The buddy information is attached the buddy cache inode
1238c9de560dSAlex Tomas  * for convenience. The information regarding each group
1239c9de560dSAlex Tomas  * is loaded via ext4_mb_load_buddy. The information involve
1240c9de560dSAlex Tomas  * block bitmap and buddy information. The information are
1241c9de560dSAlex Tomas  * stored in the inode as
1242c9de560dSAlex Tomas  *
1243c9de560dSAlex Tomas  * {                        page                        }
1244c3a326a6SAneesh Kumar K.V  * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
1245c9de560dSAlex Tomas  *
1246c9de560dSAlex Tomas  *
1247c9de560dSAlex Tomas  * one block each for bitmap and buddy information.
1248c9de560dSAlex Tomas  * So for each group we take up 2 blocks. A page can
1249ea1754a0SKirill A. Shutemov  * contain blocks_per_page (PAGE_SIZE / blocksize)  blocks.
1250c9de560dSAlex Tomas  * So it can have information regarding groups_per_page which
1251c9de560dSAlex Tomas  * is blocks_per_page/2
12528a57d9d6SCurt Wohlgemuth  *
12538a57d9d6SCurt Wohlgemuth  * Locking note:  This routine takes the block group lock of all groups
12548a57d9d6SCurt Wohlgemuth  * for this page; do not hold this lock when calling this routine!
1255c9de560dSAlex Tomas  */
1256c9de560dSAlex Tomas 
1257adb7ef60SKonstantin Khlebnikov static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
1258c9de560dSAlex Tomas {
12598df9675fSTheodore Ts'o 	ext4_group_t ngroups;
126089cadf6eSLu Hongfei 	unsigned int blocksize;
1261c9de560dSAlex Tomas 	int blocks_per_page;
1262c9de560dSAlex Tomas 	int groups_per_page;
1263c9de560dSAlex Tomas 	int err = 0;
1264c9de560dSAlex Tomas 	int i;
1265813e5727STheodore Ts'o 	ext4_group_t first_group, group;
1266c9de560dSAlex Tomas 	int first_block;
1267c9de560dSAlex Tomas 	struct super_block *sb;
1268c9de560dSAlex Tomas 	struct buffer_head *bhs;
1269fa77dcfaSDarrick J. Wong 	struct buffer_head **bh = NULL;
1270c9de560dSAlex Tomas 	struct inode *inode;
1271c9de560dSAlex Tomas 	char *data;
1272c9de560dSAlex Tomas 	char *bitmap;
12739b8b7d35SAmir Goldstein 	struct ext4_group_info *grinfo;
1274c9de560dSAlex Tomas 
1275c9de560dSAlex Tomas 	inode = page->mapping->host;
1276c9de560dSAlex Tomas 	sb = inode->i_sb;
12778df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
127893407472SFabian Frederick 	blocksize = i_blocksize(inode);
127909cbfeafSKirill A. Shutemov 	blocks_per_page = PAGE_SIZE / blocksize;
1280c9de560dSAlex Tomas 
1281d3df1453SRitesh Harjani 	mb_debug(sb, "init page %lu\n", page->index);
1282d3df1453SRitesh Harjani 
1283c9de560dSAlex Tomas 	groups_per_page = blocks_per_page >> 1;
1284c9de560dSAlex Tomas 	if (groups_per_page == 0)
1285c9de560dSAlex Tomas 		groups_per_page = 1;
1286c9de560dSAlex Tomas 
1287c9de560dSAlex Tomas 	/* allocate buffer_heads to read bitmaps */
1288c9de560dSAlex Tomas 	if (groups_per_page > 1) {
1289c9de560dSAlex Tomas 		i = sizeof(struct buffer_head *) * groups_per_page;
1290adb7ef60SKonstantin Khlebnikov 		bh = kzalloc(i, gfp);
1291139f46d3SKemeng Shi 		if (bh == NULL)
1292139f46d3SKemeng Shi 			return -ENOMEM;
1293c9de560dSAlex Tomas 	} else
1294c9de560dSAlex Tomas 		bh = &bhs;
1295c9de560dSAlex Tomas 
1296c9de560dSAlex Tomas 	first_group = page->index * blocks_per_page / 2;
1297c9de560dSAlex Tomas 
1298c9de560dSAlex Tomas 	/* read all groups the page covers into the cache */
1299813e5727STheodore Ts'o 	for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1300813e5727STheodore Ts'o 		if (group >= ngroups)
1301c9de560dSAlex Tomas 			break;
1302c9de560dSAlex Tomas 
1303813e5727STheodore Ts'o 		grinfo = ext4_get_group_info(sb, group);
13045354b2afSTheodore Ts'o 		if (!grinfo)
13055354b2afSTheodore Ts'o 			continue;
13069b8b7d35SAmir Goldstein 		/*
13079b8b7d35SAmir Goldstein 		 * If page is uptodate then we came here after online resize
13089b8b7d35SAmir Goldstein 		 * which added some new uninitialized group info structs, so
13099b8b7d35SAmir Goldstein 		 * we must skip all initialized uptodate buddies on the page,
13109b8b7d35SAmir Goldstein 		 * which may be currently in use by an allocating task.
13119b8b7d35SAmir Goldstein 		 */
13129b8b7d35SAmir Goldstein 		if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
13139b8b7d35SAmir Goldstein 			bh[i] = NULL;
13149b8b7d35SAmir Goldstein 			continue;
13159b8b7d35SAmir Goldstein 		}
1316cfd73237SAlex Zhuravlev 		bh[i] = ext4_read_block_bitmap_nowait(sb, group, false);
13179008a58eSDarrick J. Wong 		if (IS_ERR(bh[i])) {
13189008a58eSDarrick J. Wong 			err = PTR_ERR(bh[i]);
13199008a58eSDarrick J. Wong 			bh[i] = NULL;
1320c9de560dSAlex Tomas 			goto out;
13212ccb5fb9SAneesh Kumar K.V 		}
1322d3df1453SRitesh Harjani 		mb_debug(sb, "read bitmap for group %u\n", group);
1323c9de560dSAlex Tomas 	}
1324c9de560dSAlex Tomas 
1325c9de560dSAlex Tomas 	/* wait for I/O completion */
1326813e5727STheodore Ts'o 	for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
13279008a58eSDarrick J. Wong 		int err2;
13289008a58eSDarrick J. Wong 
13299008a58eSDarrick J. Wong 		if (!bh[i])
13309008a58eSDarrick J. Wong 			continue;
13319008a58eSDarrick J. Wong 		err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
13329008a58eSDarrick J. Wong 		if (!err)
13339008a58eSDarrick J. Wong 			err = err2;
1334813e5727STheodore Ts'o 	}
1335c9de560dSAlex Tomas 
1336c9de560dSAlex Tomas 	first_block = page->index * blocks_per_page;
1337c9de560dSAlex Tomas 	for (i = 0; i < blocks_per_page; i++) {
1338c9de560dSAlex Tomas 		group = (first_block + i) >> 1;
13398df9675fSTheodore Ts'o 		if (group >= ngroups)
1340c9de560dSAlex Tomas 			break;
1341c9de560dSAlex Tomas 
13429b8b7d35SAmir Goldstein 		if (!bh[group - first_group])
13439b8b7d35SAmir Goldstein 			/* skip initialized uptodate buddy */
13449b8b7d35SAmir Goldstein 			continue;
13459b8b7d35SAmir Goldstein 
1346bbdc322fSLukas Czerner 		if (!buffer_verified(bh[group - first_group]))
1347bbdc322fSLukas Czerner 			/* Skip faulty bitmaps */
1348bbdc322fSLukas Czerner 			continue;
1349bbdc322fSLukas Czerner 		err = 0;
1350bbdc322fSLukas Czerner 
1351c9de560dSAlex Tomas 		/*
1352c9de560dSAlex Tomas 		 * data carry information regarding this
1353c9de560dSAlex Tomas 		 * particular group in the format specified
1354c9de560dSAlex Tomas 		 * above
1355c9de560dSAlex Tomas 		 *
1356c9de560dSAlex Tomas 		 */
1357c9de560dSAlex Tomas 		data = page_address(page) + (i * blocksize);
1358c9de560dSAlex Tomas 		bitmap = bh[group - first_group]->b_data;
1359c9de560dSAlex Tomas 
1360c9de560dSAlex Tomas 		/*
1361c9de560dSAlex Tomas 		 * We place the buddy block and bitmap block
1362c9de560dSAlex Tomas 		 * close together
1363c9de560dSAlex Tomas 		 */
1364c9de560dSAlex Tomas 		if ((first_block + i) & 1) {
1365c9de560dSAlex Tomas 			/* this is block of buddy */
1366c9de560dSAlex Tomas 			BUG_ON(incore == NULL);
1367d3df1453SRitesh Harjani 			mb_debug(sb, "put buddy for group %u in page %lu/%x\n",
1368c9de560dSAlex Tomas 				group, page->index, i * blocksize);
1369f307333eSTheodore Ts'o 			trace_ext4_mb_buddy_bitmap_load(sb, group);
1370c9de560dSAlex Tomas 			grinfo = ext4_get_group_info(sb, group);
13715354b2afSTheodore Ts'o 			if (!grinfo) {
13725354b2afSTheodore Ts'o 				err = -EFSCORRUPTED;
13735354b2afSTheodore Ts'o 				goto out;
13745354b2afSTheodore Ts'o 			}
1375c9de560dSAlex Tomas 			grinfo->bb_fragments = 0;
1376c9de560dSAlex Tomas 			memset(grinfo->bb_counters, 0,
13771927805eSEric Sandeen 			       sizeof(*grinfo->bb_counters) *
13784b68f6dfSHarshad Shirwadkar 			       (MB_NUM_ORDERS(sb)));
1379c9de560dSAlex Tomas 			/*
1380c9de560dSAlex Tomas 			 * incore got set to the group block bitmap below
1381c9de560dSAlex Tomas 			 */
13827a2fcbf7SAneesh Kumar K.V 			ext4_lock_group(sb, group);
13839b8b7d35SAmir Goldstein 			/* init the buddy */
13849b8b7d35SAmir Goldstein 			memset(data, 0xff, blocksize);
13855354b2afSTheodore Ts'o 			ext4_mb_generate_buddy(sb, data, incore, group, grinfo);
13867a2fcbf7SAneesh Kumar K.V 			ext4_unlock_group(sb, group);
1387c9de560dSAlex Tomas 			incore = NULL;
1388c9de560dSAlex Tomas 		} else {
1389c9de560dSAlex Tomas 			/* this is block of bitmap */
1390c9de560dSAlex Tomas 			BUG_ON(incore != NULL);
1391d3df1453SRitesh Harjani 			mb_debug(sb, "put bitmap for group %u in page %lu/%x\n",
1392c9de560dSAlex Tomas 				group, page->index, i * blocksize);
1393f307333eSTheodore Ts'o 			trace_ext4_mb_bitmap_load(sb, group);
1394c9de560dSAlex Tomas 
1395c9de560dSAlex Tomas 			/* see comments in ext4_mb_put_pa() */
1396c9de560dSAlex Tomas 			ext4_lock_group(sb, group);
1397c9de560dSAlex Tomas 			memcpy(data, bitmap, blocksize);
1398c9de560dSAlex Tomas 
1399c9de560dSAlex Tomas 			/* mark all preallocated blks used in in-core bitmap */
1400c9de560dSAlex Tomas 			ext4_mb_generate_from_pa(sb, data, group);
14017a2fcbf7SAneesh Kumar K.V 			ext4_mb_generate_from_freelist(sb, data, group);
1402c9de560dSAlex Tomas 			ext4_unlock_group(sb, group);
1403c9de560dSAlex Tomas 
1404c9de560dSAlex Tomas 			/* set incore so that the buddy information can be
1405c9de560dSAlex Tomas 			 * generated using this
1406c9de560dSAlex Tomas 			 */
1407c9de560dSAlex Tomas 			incore = data;
1408c9de560dSAlex Tomas 		}
1409c9de560dSAlex Tomas 	}
1410c9de560dSAlex Tomas 	SetPageUptodate(page);
1411c9de560dSAlex Tomas 
1412c9de560dSAlex Tomas out:
1413c9de560dSAlex Tomas 	if (bh) {
14149b8b7d35SAmir Goldstein 		for (i = 0; i < groups_per_page; i++)
1415c9de560dSAlex Tomas 			brelse(bh[i]);
1416c9de560dSAlex Tomas 		if (bh != &bhs)
1417c9de560dSAlex Tomas 			kfree(bh);
1418c9de560dSAlex Tomas 	}
1419c9de560dSAlex Tomas 	return err;
1420c9de560dSAlex Tomas }
1421c9de560dSAlex Tomas 
14228a57d9d6SCurt Wohlgemuth /*
14232de8807bSAmir Goldstein  * Lock the buddy and bitmap pages. This make sure other parallel init_group
14242de8807bSAmir Goldstein  * on the same buddy page doesn't happen whild holding the buddy page lock.
14252de8807bSAmir Goldstein  * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
14262de8807bSAmir Goldstein  * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
1427eee4adc7SEric Sandeen  */
14282de8807bSAmir Goldstein static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
1429adb7ef60SKonstantin Khlebnikov 		ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
1430eee4adc7SEric Sandeen {
14312de8807bSAmir Goldstein 	struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
14322de8807bSAmir Goldstein 	int block, pnum, poff;
1433eee4adc7SEric Sandeen 	int blocks_per_page;
14342de8807bSAmir Goldstein 	struct page *page;
14352de8807bSAmir Goldstein 
14362de8807bSAmir Goldstein 	e4b->bd_buddy_page = NULL;
14372de8807bSAmir Goldstein 	e4b->bd_bitmap_page = NULL;
1438eee4adc7SEric Sandeen 
143909cbfeafSKirill A. Shutemov 	blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1440eee4adc7SEric Sandeen 	/*
1441eee4adc7SEric Sandeen 	 * the buddy cache inode stores the block bitmap
1442eee4adc7SEric Sandeen 	 * and buddy information in consecutive blocks.
1443eee4adc7SEric Sandeen 	 * So for each group we need two blocks.
1444eee4adc7SEric Sandeen 	 */
1445eee4adc7SEric Sandeen 	block = group * 2;
1446eee4adc7SEric Sandeen 	pnum = block / blocks_per_page;
14472de8807bSAmir Goldstein 	poff = block % blocks_per_page;
1448adb7ef60SKonstantin Khlebnikov 	page = find_or_create_page(inode->i_mapping, pnum, gfp);
14492de8807bSAmir Goldstein 	if (!page)
1450c57ab39bSYounger Liu 		return -ENOMEM;
14512de8807bSAmir Goldstein 	BUG_ON(page->mapping != inode->i_mapping);
14522de8807bSAmir Goldstein 	e4b->bd_bitmap_page = page;
14532de8807bSAmir Goldstein 	e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1454eee4adc7SEric Sandeen 
14552de8807bSAmir Goldstein 	if (blocks_per_page >= 2) {
14562de8807bSAmir Goldstein 		/* buddy and bitmap are on the same page */
14572de8807bSAmir Goldstein 		return 0;
1458eee4adc7SEric Sandeen 	}
1459eee4adc7SEric Sandeen 
14602de8807bSAmir Goldstein 	block++;
1461eee4adc7SEric Sandeen 	pnum = block / blocks_per_page;
1462adb7ef60SKonstantin Khlebnikov 	page = find_or_create_page(inode->i_mapping, pnum, gfp);
14632de8807bSAmir Goldstein 	if (!page)
1464c57ab39bSYounger Liu 		return -ENOMEM;
14652de8807bSAmir Goldstein 	BUG_ON(page->mapping != inode->i_mapping);
14662de8807bSAmir Goldstein 	e4b->bd_buddy_page = page;
14672de8807bSAmir Goldstein 	return 0;
1468eee4adc7SEric Sandeen }
1469eee4adc7SEric Sandeen 
14702de8807bSAmir Goldstein static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
14712de8807bSAmir Goldstein {
14722de8807bSAmir Goldstein 	if (e4b->bd_bitmap_page) {
14732de8807bSAmir Goldstein 		unlock_page(e4b->bd_bitmap_page);
147409cbfeafSKirill A. Shutemov 		put_page(e4b->bd_bitmap_page);
14752de8807bSAmir Goldstein 	}
14762de8807bSAmir Goldstein 	if (e4b->bd_buddy_page) {
14772de8807bSAmir Goldstein 		unlock_page(e4b->bd_buddy_page);
147809cbfeafSKirill A. Shutemov 		put_page(e4b->bd_buddy_page);
14792de8807bSAmir Goldstein 	}
1480eee4adc7SEric Sandeen }
1481eee4adc7SEric Sandeen 
1482eee4adc7SEric Sandeen /*
14838a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
14848a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
14858a57d9d6SCurt Wohlgemuth  * calling this routine!
14868a57d9d6SCurt Wohlgemuth  */
1487b6a758ecSAneesh Kumar K.V static noinline_for_stack
1488adb7ef60SKonstantin Khlebnikov int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1489b6a758ecSAneesh Kumar K.V {
1490b6a758ecSAneesh Kumar K.V 
1491b6a758ecSAneesh Kumar K.V 	struct ext4_group_info *this_grp;
14922de8807bSAmir Goldstein 	struct ext4_buddy e4b;
14932de8807bSAmir Goldstein 	struct page *page;
14942de8807bSAmir Goldstein 	int ret = 0;
1495b6a758ecSAneesh Kumar K.V 
1496b10a44c3STheodore Ts'o 	might_sleep();
1497d3df1453SRitesh Harjani 	mb_debug(sb, "init group %u\n", group);
1498b6a758ecSAneesh Kumar K.V 	this_grp = ext4_get_group_info(sb, group);
14995354b2afSTheodore Ts'o 	if (!this_grp)
15005354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
15015354b2afSTheodore Ts'o 
1502b6a758ecSAneesh Kumar K.V 	/*
150308c3a813SAneesh Kumar K.V 	 * This ensures that we don't reinit the buddy cache
150408c3a813SAneesh Kumar K.V 	 * page which map to the group from which we are already
150508c3a813SAneesh Kumar K.V 	 * allocating. If we are looking at the buddy cache we would
150608c3a813SAneesh Kumar K.V 	 * have taken a reference using ext4_mb_load_buddy and that
15072de8807bSAmir Goldstein 	 * would have pinned buddy page to page cache.
15082457aec6SMel Gorman 	 * The call to ext4_mb_get_buddy_page_lock will mark the
15092457aec6SMel Gorman 	 * page accessed.
1510b6a758ecSAneesh Kumar K.V 	 */
1511adb7ef60SKonstantin Khlebnikov 	ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
15122de8807bSAmir Goldstein 	if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1513b6a758ecSAneesh Kumar K.V 		/*
1514b6a758ecSAneesh Kumar K.V 		 * somebody initialized the group
1515b6a758ecSAneesh Kumar K.V 		 * return without doing anything
1516b6a758ecSAneesh Kumar K.V 		 */
1517b6a758ecSAneesh Kumar K.V 		goto err;
1518b6a758ecSAneesh Kumar K.V 	}
15192de8807bSAmir Goldstein 
15202de8807bSAmir Goldstein 	page = e4b.bd_bitmap_page;
1521adb7ef60SKonstantin Khlebnikov 	ret = ext4_mb_init_cache(page, NULL, gfp);
15222de8807bSAmir Goldstein 	if (ret)
1523b6a758ecSAneesh Kumar K.V 		goto err;
15242de8807bSAmir Goldstein 	if (!PageUptodate(page)) {
1525b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1526b6a758ecSAneesh Kumar K.V 		goto err;
1527b6a758ecSAneesh Kumar K.V 	}
1528b6a758ecSAneesh Kumar K.V 
15292de8807bSAmir Goldstein 	if (e4b.bd_buddy_page == NULL) {
1530b6a758ecSAneesh Kumar K.V 		/*
1531b6a758ecSAneesh Kumar K.V 		 * If both the bitmap and buddy are in
1532b6a758ecSAneesh Kumar K.V 		 * the same page we don't need to force
1533b6a758ecSAneesh Kumar K.V 		 * init the buddy
1534b6a758ecSAneesh Kumar K.V 		 */
15352de8807bSAmir Goldstein 		ret = 0;
1536b6a758ecSAneesh Kumar K.V 		goto err;
1537b6a758ecSAneesh Kumar K.V 	}
15382de8807bSAmir Goldstein 	/* init buddy cache */
15392de8807bSAmir Goldstein 	page = e4b.bd_buddy_page;
1540adb7ef60SKonstantin Khlebnikov 	ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
15412de8807bSAmir Goldstein 	if (ret)
15422de8807bSAmir Goldstein 		goto err;
15432de8807bSAmir Goldstein 	if (!PageUptodate(page)) {
1544b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1545b6a758ecSAneesh Kumar K.V 		goto err;
1546b6a758ecSAneesh Kumar K.V 	}
1547b6a758ecSAneesh Kumar K.V err:
15482de8807bSAmir Goldstein 	ext4_mb_put_buddy_page_lock(&e4b);
1549b6a758ecSAneesh Kumar K.V 	return ret;
1550b6a758ecSAneesh Kumar K.V }
1551b6a758ecSAneesh Kumar K.V 
15528a57d9d6SCurt Wohlgemuth /*
15538a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
15548a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
15558a57d9d6SCurt Wohlgemuth  * calling this routine!
15568a57d9d6SCurt Wohlgemuth  */
15574ddfef7bSEric Sandeen static noinline_for_stack int
1558adb7ef60SKonstantin Khlebnikov ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1559adb7ef60SKonstantin Khlebnikov 		       struct ext4_buddy *e4b, gfp_t gfp)
1560c9de560dSAlex Tomas {
1561c9de560dSAlex Tomas 	int blocks_per_page;
1562c9de560dSAlex Tomas 	int block;
1563c9de560dSAlex Tomas 	int pnum;
1564c9de560dSAlex Tomas 	int poff;
1565c9de560dSAlex Tomas 	struct page *page;
1566fdf6c7a7SShen Feng 	int ret;
1567920313a7SAneesh Kumar K.V 	struct ext4_group_info *grp;
1568920313a7SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1569920313a7SAneesh Kumar K.V 	struct inode *inode = sbi->s_buddy_cache;
1570c9de560dSAlex Tomas 
1571b10a44c3STheodore Ts'o 	might_sleep();
1572d3df1453SRitesh Harjani 	mb_debug(sb, "load group %u\n", group);
1573c9de560dSAlex Tomas 
157409cbfeafSKirill A. Shutemov 	blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1575920313a7SAneesh Kumar K.V 	grp = ext4_get_group_info(sb, group);
15765354b2afSTheodore Ts'o 	if (!grp)
15775354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
1578c9de560dSAlex Tomas 
1579c9de560dSAlex Tomas 	e4b->bd_blkbits = sb->s_blocksize_bits;
1580529da704STao Ma 	e4b->bd_info = grp;
1581c9de560dSAlex Tomas 	e4b->bd_sb = sb;
1582c9de560dSAlex Tomas 	e4b->bd_group = group;
1583c9de560dSAlex Tomas 	e4b->bd_buddy_page = NULL;
1584c9de560dSAlex Tomas 	e4b->bd_bitmap_page = NULL;
1585c9de560dSAlex Tomas 
1586f41c0750SAneesh Kumar K.V 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1587f41c0750SAneesh Kumar K.V 		/*
1588f41c0750SAneesh Kumar K.V 		 * we need full data about the group
1589f41c0750SAneesh Kumar K.V 		 * to make a good selection
1590f41c0750SAneesh Kumar K.V 		 */
1591adb7ef60SKonstantin Khlebnikov 		ret = ext4_mb_init_group(sb, group, gfp);
1592f41c0750SAneesh Kumar K.V 		if (ret)
1593f41c0750SAneesh Kumar K.V 			return ret;
1594f41c0750SAneesh Kumar K.V 	}
1595f41c0750SAneesh Kumar K.V 
1596c9de560dSAlex Tomas 	/*
1597c9de560dSAlex Tomas 	 * the buddy cache inode stores the block bitmap
1598c9de560dSAlex Tomas 	 * and buddy information in consecutive blocks.
1599c9de560dSAlex Tomas 	 * So for each group we need two blocks.
1600c9de560dSAlex Tomas 	 */
1601c9de560dSAlex Tomas 	block = group * 2;
1602c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1603c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1604c9de560dSAlex Tomas 
1605c9de560dSAlex Tomas 	/* we could use find_or_create_page(), but it locks page
1606c9de560dSAlex Tomas 	 * what we'd like to avoid in fast path ... */
16072457aec6SMel Gorman 	page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1608c9de560dSAlex Tomas 	if (page == NULL || !PageUptodate(page)) {
1609c9de560dSAlex Tomas 		if (page)
1610920313a7SAneesh Kumar K.V 			/*
1611920313a7SAneesh Kumar K.V 			 * drop the page reference and try
1612920313a7SAneesh Kumar K.V 			 * to get the page with lock. If we
1613920313a7SAneesh Kumar K.V 			 * are not uptodate that implies
1614920313a7SAneesh Kumar K.V 			 * somebody just created the page but
1615920313a7SAneesh Kumar K.V 			 * is yet to initialize the same. So
1616920313a7SAneesh Kumar K.V 			 * wait for it to initialize.
1617920313a7SAneesh Kumar K.V 			 */
161809cbfeafSKirill A. Shutemov 			put_page(page);
1619adb7ef60SKonstantin Khlebnikov 		page = find_or_create_page(inode->i_mapping, pnum, gfp);
1620c9de560dSAlex Tomas 		if (page) {
162119b8b035STheodore Ts'o 			if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
162219b8b035STheodore Ts'o 	"ext4: bitmap's paging->mapping != inode->i_mapping\n")) {
162319b8b035STheodore Ts'o 				/* should never happen */
162419b8b035STheodore Ts'o 				unlock_page(page);
162519b8b035STheodore Ts'o 				ret = -EINVAL;
162619b8b035STheodore Ts'o 				goto err;
162719b8b035STheodore Ts'o 			}
1628c9de560dSAlex Tomas 			if (!PageUptodate(page)) {
1629adb7ef60SKonstantin Khlebnikov 				ret = ext4_mb_init_cache(page, NULL, gfp);
1630fdf6c7a7SShen Feng 				if (ret) {
1631fdf6c7a7SShen Feng 					unlock_page(page);
1632fdf6c7a7SShen Feng 					goto err;
1633fdf6c7a7SShen Feng 				}
1634c9de560dSAlex Tomas 				mb_cmp_bitmaps(e4b, page_address(page) +
1635c9de560dSAlex Tomas 					       (poff * sb->s_blocksize));
1636c9de560dSAlex Tomas 			}
1637c9de560dSAlex Tomas 			unlock_page(page);
1638c9de560dSAlex Tomas 		}
1639c9de560dSAlex Tomas 	}
1640c57ab39bSYounger Liu 	if (page == NULL) {
1641c57ab39bSYounger Liu 		ret = -ENOMEM;
1642c57ab39bSYounger Liu 		goto err;
1643c57ab39bSYounger Liu 	}
1644c57ab39bSYounger Liu 	if (!PageUptodate(page)) {
1645fdf6c7a7SShen Feng 		ret = -EIO;
1646c9de560dSAlex Tomas 		goto err;
1647fdf6c7a7SShen Feng 	}
16482457aec6SMel Gorman 
16492457aec6SMel Gorman 	/* Pages marked accessed already */
1650c9de560dSAlex Tomas 	e4b->bd_bitmap_page = page;
1651c9de560dSAlex Tomas 	e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1652c9de560dSAlex Tomas 
1653c9de560dSAlex Tomas 	block++;
1654c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1655c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1656c9de560dSAlex Tomas 
16572457aec6SMel Gorman 	page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1658c9de560dSAlex Tomas 	if (page == NULL || !PageUptodate(page)) {
1659c9de560dSAlex Tomas 		if (page)
166009cbfeafSKirill A. Shutemov 			put_page(page);
1661adb7ef60SKonstantin Khlebnikov 		page = find_or_create_page(inode->i_mapping, pnum, gfp);
1662c9de560dSAlex Tomas 		if (page) {
166319b8b035STheodore Ts'o 			if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
166419b8b035STheodore Ts'o 	"ext4: buddy bitmap's page->mapping != inode->i_mapping\n")) {
166519b8b035STheodore Ts'o 				/* should never happen */
166619b8b035STheodore Ts'o 				unlock_page(page);
166719b8b035STheodore Ts'o 				ret = -EINVAL;
166819b8b035STheodore Ts'o 				goto err;
166919b8b035STheodore Ts'o 			}
1670fdf6c7a7SShen Feng 			if (!PageUptodate(page)) {
1671adb7ef60SKonstantin Khlebnikov 				ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1672adb7ef60SKonstantin Khlebnikov 							 gfp);
1673fdf6c7a7SShen Feng 				if (ret) {
1674fdf6c7a7SShen Feng 					unlock_page(page);
1675fdf6c7a7SShen Feng 					goto err;
1676fdf6c7a7SShen Feng 				}
1677fdf6c7a7SShen Feng 			}
1678c9de560dSAlex Tomas 			unlock_page(page);
1679c9de560dSAlex Tomas 		}
1680c9de560dSAlex Tomas 	}
1681c57ab39bSYounger Liu 	if (page == NULL) {
1682c57ab39bSYounger Liu 		ret = -ENOMEM;
1683c57ab39bSYounger Liu 		goto err;
1684c57ab39bSYounger Liu 	}
1685c57ab39bSYounger Liu 	if (!PageUptodate(page)) {
1686fdf6c7a7SShen Feng 		ret = -EIO;
1687c9de560dSAlex Tomas 		goto err;
1688fdf6c7a7SShen Feng 	}
16892457aec6SMel Gorman 
16902457aec6SMel Gorman 	/* Pages marked accessed already */
1691c9de560dSAlex Tomas 	e4b->bd_buddy_page = page;
1692c9de560dSAlex Tomas 	e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1693c9de560dSAlex Tomas 
1694c9de560dSAlex Tomas 	return 0;
1695c9de560dSAlex Tomas 
1696c9de560dSAlex Tomas err:
169726626f11SYang Ruirui 	if (page)
169809cbfeafSKirill A. Shutemov 		put_page(page);
1699c9de560dSAlex Tomas 	if (e4b->bd_bitmap_page)
170009cbfeafSKirill A. Shutemov 		put_page(e4b->bd_bitmap_page);
1701285164b8SKemeng Shi 
1702c9de560dSAlex Tomas 	e4b->bd_buddy = NULL;
1703c9de560dSAlex Tomas 	e4b->bd_bitmap = NULL;
1704fdf6c7a7SShen Feng 	return ret;
1705c9de560dSAlex Tomas }
1706c9de560dSAlex Tomas 
1707adb7ef60SKonstantin Khlebnikov static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1708adb7ef60SKonstantin Khlebnikov 			      struct ext4_buddy *e4b)
1709adb7ef60SKonstantin Khlebnikov {
1710adb7ef60SKonstantin Khlebnikov 	return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1711adb7ef60SKonstantin Khlebnikov }
1712adb7ef60SKonstantin Khlebnikov 
1713e39e07fdSJing Zhang static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1714c9de560dSAlex Tomas {
1715c9de560dSAlex Tomas 	if (e4b->bd_bitmap_page)
171609cbfeafSKirill A. Shutemov 		put_page(e4b->bd_bitmap_page);
1717c9de560dSAlex Tomas 	if (e4b->bd_buddy_page)
171809cbfeafSKirill A. Shutemov 		put_page(e4b->bd_buddy_page);
1719c9de560dSAlex Tomas }
1720c9de560dSAlex Tomas 
1721c9de560dSAlex Tomas 
1722c9de560dSAlex Tomas static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1723c9de560dSAlex Tomas {
1724ce3cca33SChunguang Xu 	int order = 1, max;
1725c9de560dSAlex Tomas 	void *bb;
1726c9de560dSAlex Tomas 
1727c5e8f3f3STheodore Ts'o 	BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1728c9de560dSAlex Tomas 	BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1729c9de560dSAlex Tomas 
1730c9de560dSAlex Tomas 	while (order <= e4b->bd_blkbits + 1) {
1731ce3cca33SChunguang Xu 		bb = mb_find_buddy(e4b, order, &max);
1732ce3cca33SChunguang Xu 		if (!mb_test_bit(block >> order, bb)) {
1733c9de560dSAlex Tomas 			/* this block is part of buddy of order 'order' */
1734c9de560dSAlex Tomas 			return order;
1735c9de560dSAlex Tomas 		}
1736c9de560dSAlex Tomas 		order++;
1737c9de560dSAlex Tomas 	}
1738c9de560dSAlex Tomas 	return 0;
1739c9de560dSAlex Tomas }
1740c9de560dSAlex Tomas 
1741955ce5f5SAneesh Kumar K.V static void mb_clear_bits(void *bm, int cur, int len)
1742c9de560dSAlex Tomas {
1743c9de560dSAlex Tomas 	__u32 *addr;
1744c9de560dSAlex Tomas 
1745c9de560dSAlex Tomas 	len = cur + len;
1746c9de560dSAlex Tomas 	while (cur < len) {
1747c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1748c9de560dSAlex Tomas 			/* fast path: clear whole word at once */
1749c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1750c9de560dSAlex Tomas 			*addr = 0;
1751c9de560dSAlex Tomas 			cur += 32;
1752c9de560dSAlex Tomas 			continue;
1753c9de560dSAlex Tomas 		}
1754e8134b27SAneesh Kumar K.V 		mb_clear_bit(cur, bm);
1755c9de560dSAlex Tomas 		cur++;
1756c9de560dSAlex Tomas 	}
1757c9de560dSAlex Tomas }
1758c9de560dSAlex Tomas 
1759eabe0444SAndrey Sidorov /* clear bits in given range
1760eabe0444SAndrey Sidorov  * will return first found zero bit if any, -1 otherwise
1761eabe0444SAndrey Sidorov  */
1762eabe0444SAndrey Sidorov static int mb_test_and_clear_bits(void *bm, int cur, int len)
1763eabe0444SAndrey Sidorov {
1764eabe0444SAndrey Sidorov 	__u32 *addr;
1765eabe0444SAndrey Sidorov 	int zero_bit = -1;
1766eabe0444SAndrey Sidorov 
1767eabe0444SAndrey Sidorov 	len = cur + len;
1768eabe0444SAndrey Sidorov 	while (cur < len) {
1769eabe0444SAndrey Sidorov 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1770eabe0444SAndrey Sidorov 			/* fast path: clear whole word at once */
1771eabe0444SAndrey Sidorov 			addr = bm + (cur >> 3);
1772eabe0444SAndrey Sidorov 			if (*addr != (__u32)(-1) && zero_bit == -1)
1773eabe0444SAndrey Sidorov 				zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1774eabe0444SAndrey Sidorov 			*addr = 0;
1775eabe0444SAndrey Sidorov 			cur += 32;
1776eabe0444SAndrey Sidorov 			continue;
1777eabe0444SAndrey Sidorov 		}
1778eabe0444SAndrey Sidorov 		if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1779eabe0444SAndrey Sidorov 			zero_bit = cur;
1780eabe0444SAndrey Sidorov 		cur++;
1781eabe0444SAndrey Sidorov 	}
1782eabe0444SAndrey Sidorov 
1783eabe0444SAndrey Sidorov 	return zero_bit;
1784eabe0444SAndrey Sidorov }
1785eabe0444SAndrey Sidorov 
1786123e3016SRitesh Harjani void mb_set_bits(void *bm, int cur, int len)
1787c9de560dSAlex Tomas {
1788c9de560dSAlex Tomas 	__u32 *addr;
1789c9de560dSAlex Tomas 
1790c9de560dSAlex Tomas 	len = cur + len;
1791c9de560dSAlex Tomas 	while (cur < len) {
1792c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1793c9de560dSAlex Tomas 			/* fast path: set whole word at once */
1794c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1795c9de560dSAlex Tomas 			*addr = 0xffffffff;
1796c9de560dSAlex Tomas 			cur += 32;
1797c9de560dSAlex Tomas 			continue;
1798c9de560dSAlex Tomas 		}
1799e8134b27SAneesh Kumar K.V 		mb_set_bit(cur, bm);
1800c9de560dSAlex Tomas 		cur++;
1801c9de560dSAlex Tomas 	}
1802c9de560dSAlex Tomas }
1803c9de560dSAlex Tomas 
1804eabe0444SAndrey Sidorov static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1805eabe0444SAndrey Sidorov {
1806eabe0444SAndrey Sidorov 	if (mb_test_bit(*bit + side, bitmap)) {
1807eabe0444SAndrey Sidorov 		mb_clear_bit(*bit, bitmap);
1808eabe0444SAndrey Sidorov 		(*bit) -= side;
1809eabe0444SAndrey Sidorov 		return 1;
1810eabe0444SAndrey Sidorov 	}
1811eabe0444SAndrey Sidorov 	else {
1812eabe0444SAndrey Sidorov 		(*bit) += side;
1813eabe0444SAndrey Sidorov 		mb_set_bit(*bit, bitmap);
1814eabe0444SAndrey Sidorov 		return -1;
1815eabe0444SAndrey Sidorov 	}
1816eabe0444SAndrey Sidorov }
1817eabe0444SAndrey Sidorov 
1818eabe0444SAndrey Sidorov static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1819eabe0444SAndrey Sidorov {
1820eabe0444SAndrey Sidorov 	int max;
1821eabe0444SAndrey Sidorov 	int order = 1;
1822eabe0444SAndrey Sidorov 	void *buddy = mb_find_buddy(e4b, order, &max);
1823eabe0444SAndrey Sidorov 
1824eabe0444SAndrey Sidorov 	while (buddy) {
1825eabe0444SAndrey Sidorov 		void *buddy2;
1826eabe0444SAndrey Sidorov 
1827eabe0444SAndrey Sidorov 		/* Bits in range [first; last] are known to be set since
1828eabe0444SAndrey Sidorov 		 * corresponding blocks were allocated. Bits in range
1829eabe0444SAndrey Sidorov 		 * (first; last) will stay set because they form buddies on
1830eabe0444SAndrey Sidorov 		 * upper layer. We just deal with borders if they don't
1831eabe0444SAndrey Sidorov 		 * align with upper layer and then go up.
1832eabe0444SAndrey Sidorov 		 * Releasing entire group is all about clearing
1833eabe0444SAndrey Sidorov 		 * single bit of highest order buddy.
1834eabe0444SAndrey Sidorov 		 */
1835eabe0444SAndrey Sidorov 
1836eabe0444SAndrey Sidorov 		/* Example:
1837eabe0444SAndrey Sidorov 		 * ---------------------------------
1838eabe0444SAndrey Sidorov 		 * |   1   |   1   |   1   |   1   |
1839eabe0444SAndrey Sidorov 		 * ---------------------------------
1840eabe0444SAndrey Sidorov 		 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1841eabe0444SAndrey Sidorov 		 * ---------------------------------
1842eabe0444SAndrey Sidorov 		 *   0   1   2   3   4   5   6   7
1843eabe0444SAndrey Sidorov 		 *      \_____________________/
1844eabe0444SAndrey Sidorov 		 *
1845eabe0444SAndrey Sidorov 		 * Neither [1] nor [6] is aligned to above layer.
1846eabe0444SAndrey Sidorov 		 * Left neighbour [0] is free, so mark it busy,
1847eabe0444SAndrey Sidorov 		 * decrease bb_counters and extend range to
1848eabe0444SAndrey Sidorov 		 * [0; 6]
1849eabe0444SAndrey Sidorov 		 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1850eabe0444SAndrey Sidorov 		 * mark [6] free, increase bb_counters and shrink range to
1851eabe0444SAndrey Sidorov 		 * [0; 5].
1852eabe0444SAndrey Sidorov 		 * Then shift range to [0; 2], go up and do the same.
1853eabe0444SAndrey Sidorov 		 */
1854eabe0444SAndrey Sidorov 
1855eabe0444SAndrey Sidorov 
1856eabe0444SAndrey Sidorov 		if (first & 1)
1857eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1858eabe0444SAndrey Sidorov 		if (!(last & 1))
1859eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1860eabe0444SAndrey Sidorov 		if (first > last)
1861eabe0444SAndrey Sidorov 			break;
1862eabe0444SAndrey Sidorov 		order++;
1863eabe0444SAndrey Sidorov 
1864976620bdSKemeng Shi 		buddy2 = mb_find_buddy(e4b, order, &max);
1865976620bdSKemeng Shi 		if (!buddy2) {
1866eabe0444SAndrey Sidorov 			mb_clear_bits(buddy, first, last - first + 1);
1867eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1868eabe0444SAndrey Sidorov 			break;
1869eabe0444SAndrey Sidorov 		}
1870eabe0444SAndrey Sidorov 		first >>= 1;
1871eabe0444SAndrey Sidorov 		last >>= 1;
1872eabe0444SAndrey Sidorov 		buddy = buddy2;
1873eabe0444SAndrey Sidorov 	}
1874eabe0444SAndrey Sidorov }
1875eabe0444SAndrey Sidorov 
18767e5a8cddSShen Feng static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1877c9de560dSAlex Tomas 			   int first, int count)
1878c9de560dSAlex Tomas {
1879eabe0444SAndrey Sidorov 	int left_is_free = 0;
1880eabe0444SAndrey Sidorov 	int right_is_free = 0;
1881eabe0444SAndrey Sidorov 	int block;
1882eabe0444SAndrey Sidorov 	int last = first + count - 1;
1883c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
1884c9de560dSAlex Tomas 
1885c99d1e6eSTheodore Ts'o 	if (WARN_ON(count == 0))
1886c99d1e6eSTheodore Ts'o 		return;
1887eabe0444SAndrey Sidorov 	BUG_ON(last >= (sb->s_blocksize << 3));
1888bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1889163a203dSDarrick J. Wong 	/* Don't bother if the block group is corrupt. */
1890163a203dSDarrick J. Wong 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1891163a203dSDarrick J. Wong 		return;
1892163a203dSDarrick J. Wong 
1893c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1894c9de560dSAlex Tomas 	mb_free_blocks_double(inode, e4b, first, count);
1895c9de560dSAlex Tomas 
189607b5b8e1SRitesh Harjani 	this_cpu_inc(discard_pa_seq);
1897c9de560dSAlex Tomas 	e4b->bd_info->bb_free += count;
1898c9de560dSAlex Tomas 	if (first < e4b->bd_info->bb_first_free)
1899c9de560dSAlex Tomas 		e4b->bd_info->bb_first_free = first;
1900c9de560dSAlex Tomas 
1901eabe0444SAndrey Sidorov 	/* access memory sequentially: check left neighbour,
1902eabe0444SAndrey Sidorov 	 * clear range and then check right neighbour
1903eabe0444SAndrey Sidorov 	 */
1904c9de560dSAlex Tomas 	if (first != 0)
1905eabe0444SAndrey Sidorov 		left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1906eabe0444SAndrey Sidorov 	block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1907eabe0444SAndrey Sidorov 	if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1908eabe0444SAndrey Sidorov 		right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1909c9de560dSAlex Tomas 
1910eabe0444SAndrey Sidorov 	if (unlikely(block != -1)) {
1911e43bb4e6SNamjae Jeon 		struct ext4_sb_info *sbi = EXT4_SB(sb);
1912c9de560dSAlex Tomas 		ext4_fsblk_t blocknr;
19135661bd68SAkinobu Mita 
19145661bd68SAkinobu Mita 		blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
191549598e04SJun Piao 		blocknr += EXT4_C2B(sbi, block);
19168016e29fSHarshad Shirwadkar 		if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
19175d1b1b3fSAneesh Kumar K.V 			ext4_grp_locked_error(sb, e4b->bd_group,
1918e29136f8STheodore Ts'o 					      inode ? inode->i_ino : 0,
1919e29136f8STheodore Ts'o 					      blocknr,
19208016e29fSHarshad Shirwadkar 					      "freeing already freed block (bit %u); block bitmap corrupt.",
1921163a203dSDarrick J. Wong 					      block);
19228016e29fSHarshad Shirwadkar 			ext4_mark_group_bitmap_corrupted(
19238016e29fSHarshad Shirwadkar 				sb, e4b->bd_group,
1924db79e6d1SWang Shilong 				EXT4_GROUP_INFO_BBITMAP_CORRUPT);
19258016e29fSHarshad Shirwadkar 		}
1926eabe0444SAndrey Sidorov 		goto done;
1927c9de560dSAlex Tomas 	}
1928c9de560dSAlex Tomas 
1929eabe0444SAndrey Sidorov 	/* let's maintain fragments counter */
1930eabe0444SAndrey Sidorov 	if (left_is_free && right_is_free)
1931eabe0444SAndrey Sidorov 		e4b->bd_info->bb_fragments--;
1932eabe0444SAndrey Sidorov 	else if (!left_is_free && !right_is_free)
1933eabe0444SAndrey Sidorov 		e4b->bd_info->bb_fragments++;
1934c9de560dSAlex Tomas 
1935eabe0444SAndrey Sidorov 	/* buddy[0] == bd_bitmap is a special case, so handle
1936eabe0444SAndrey Sidorov 	 * it right away and let mb_buddy_mark_free stay free of
1937eabe0444SAndrey Sidorov 	 * zero order checks.
1938eabe0444SAndrey Sidorov 	 * Check if neighbours are to be coaleasced,
1939eabe0444SAndrey Sidorov 	 * adjust bitmap bb_counters and borders appropriately.
1940eabe0444SAndrey Sidorov 	 */
1941eabe0444SAndrey Sidorov 	if (first & 1) {
1942eabe0444SAndrey Sidorov 		first += !left_is_free;
1943eabe0444SAndrey Sidorov 		e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1944c9de560dSAlex Tomas 	}
1945eabe0444SAndrey Sidorov 	if (!(last & 1)) {
1946eabe0444SAndrey Sidorov 		last -= !right_is_free;
1947eabe0444SAndrey Sidorov 		e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1948c9de560dSAlex Tomas 	}
1949eabe0444SAndrey Sidorov 
1950eabe0444SAndrey Sidorov 	if (first <= last)
1951eabe0444SAndrey Sidorov 		mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1952eabe0444SAndrey Sidorov 
1953eabe0444SAndrey Sidorov done:
19548a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, e4b->bd_info);
1955196e402aSHarshad Shirwadkar 	mb_update_avg_fragment_size(sb, e4b->bd_info);
1956c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1957c9de560dSAlex Tomas }
1958c9de560dSAlex Tomas 
195915c006a2SRobin Dong static int mb_find_extent(struct ext4_buddy *e4b, int block,
1960c9de560dSAlex Tomas 				int needed, struct ext4_free_extent *ex)
1961c9de560dSAlex Tomas {
1962c9de560dSAlex Tomas 	int next = block;
196315c006a2SRobin Dong 	int max, order;
1964c9de560dSAlex Tomas 	void *buddy;
1965c9de560dSAlex Tomas 
1966bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1967c9de560dSAlex Tomas 	BUG_ON(ex == NULL);
1968c9de560dSAlex Tomas 
196915c006a2SRobin Dong 	buddy = mb_find_buddy(e4b, 0, &max);
1970c9de560dSAlex Tomas 	BUG_ON(buddy == NULL);
1971c9de560dSAlex Tomas 	BUG_ON(block >= max);
1972c9de560dSAlex Tomas 	if (mb_test_bit(block, buddy)) {
1973c9de560dSAlex Tomas 		ex->fe_len = 0;
1974c9de560dSAlex Tomas 		ex->fe_start = 0;
1975c9de560dSAlex Tomas 		ex->fe_group = 0;
1976c9de560dSAlex Tomas 		return 0;
1977c9de560dSAlex Tomas 	}
1978c9de560dSAlex Tomas 
1979c9de560dSAlex Tomas 	/* find actual order */
1980c9de560dSAlex Tomas 	order = mb_find_order_for_block(e4b, block);
1981c9de560dSAlex Tomas 	block = block >> order;
1982c9de560dSAlex Tomas 
1983c9de560dSAlex Tomas 	ex->fe_len = 1 << order;
1984c9de560dSAlex Tomas 	ex->fe_start = block << order;
1985c9de560dSAlex Tomas 	ex->fe_group = e4b->bd_group;
1986c9de560dSAlex Tomas 
1987c9de560dSAlex Tomas 	/* calc difference from given start */
1988c9de560dSAlex Tomas 	next = next - ex->fe_start;
1989c9de560dSAlex Tomas 	ex->fe_len -= next;
1990c9de560dSAlex Tomas 	ex->fe_start += next;
1991c9de560dSAlex Tomas 
1992c9de560dSAlex Tomas 	while (needed > ex->fe_len &&
1993d8ec0c39SAlan Cox 	       mb_find_buddy(e4b, order, &max)) {
1994c9de560dSAlex Tomas 
1995c9de560dSAlex Tomas 		if (block + 1 >= max)
1996c9de560dSAlex Tomas 			break;
1997c9de560dSAlex Tomas 
1998c9de560dSAlex Tomas 		next = (block + 1) * (1 << order);
1999c5e8f3f3STheodore Ts'o 		if (mb_test_bit(next, e4b->bd_bitmap))
2000c9de560dSAlex Tomas 			break;
2001c9de560dSAlex Tomas 
2002b051d8dcSRobin Dong 		order = mb_find_order_for_block(e4b, next);
2003c9de560dSAlex Tomas 
2004c9de560dSAlex Tomas 		block = next >> order;
2005c9de560dSAlex Tomas 		ex->fe_len += 1 << order;
2006c9de560dSAlex Tomas 	}
2007c9de560dSAlex Tomas 
200831562b95SJan Kara 	if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
200943c73221STheodore Ts'o 		/* Should never happen! (but apparently sometimes does?!?) */
201043c73221STheodore Ts'o 		WARN_ON(1);
2011cd84bbbaSStephen Brennan 		ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
2012cd84bbbaSStephen Brennan 			"corruption or bug in mb_find_extent "
201343c73221STheodore Ts'o 			"block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
201443c73221STheodore Ts'o 			block, order, needed, ex->fe_group, ex->fe_start,
201543c73221STheodore Ts'o 			ex->fe_len, ex->fe_logical);
201643c73221STheodore Ts'o 		ex->fe_len = 0;
201743c73221STheodore Ts'o 		ex->fe_start = 0;
201843c73221STheodore Ts'o 		ex->fe_group = 0;
201943c73221STheodore Ts'o 	}
2020c9de560dSAlex Tomas 	return ex->fe_len;
2021c9de560dSAlex Tomas }
2022c9de560dSAlex Tomas 
2023c9de560dSAlex Tomas static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
2024c9de560dSAlex Tomas {
2025c9de560dSAlex Tomas 	int ord;
2026c9de560dSAlex Tomas 	int mlen = 0;
2027c9de560dSAlex Tomas 	int max = 0;
2028c9de560dSAlex Tomas 	int cur;
2029c9de560dSAlex Tomas 	int start = ex->fe_start;
2030c9de560dSAlex Tomas 	int len = ex->fe_len;
2031c9de560dSAlex Tomas 	unsigned ret = 0;
2032c9de560dSAlex Tomas 	int len0 = len;
2033c9de560dSAlex Tomas 	void *buddy;
2034218a6944Shanjinke 	bool split = false;
2035c9de560dSAlex Tomas 
2036c9de560dSAlex Tomas 	BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
2037c9de560dSAlex Tomas 	BUG_ON(e4b->bd_group != ex->fe_group);
2038bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
2039c9de560dSAlex Tomas 	mb_check_buddy(e4b);
2040c9de560dSAlex Tomas 	mb_mark_used_double(e4b, start, len);
2041c9de560dSAlex Tomas 
204207b5b8e1SRitesh Harjani 	this_cpu_inc(discard_pa_seq);
2043c9de560dSAlex Tomas 	e4b->bd_info->bb_free -= len;
2044c9de560dSAlex Tomas 	if (e4b->bd_info->bb_first_free == start)
2045c9de560dSAlex Tomas 		e4b->bd_info->bb_first_free += len;
2046c9de560dSAlex Tomas 
2047c9de560dSAlex Tomas 	/* let's maintain fragments counter */
2048c9de560dSAlex Tomas 	if (start != 0)
2049c5e8f3f3STheodore Ts'o 		mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
2050c9de560dSAlex Tomas 	if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
2051c5e8f3f3STheodore Ts'o 		max = !mb_test_bit(start + len, e4b->bd_bitmap);
2052c9de560dSAlex Tomas 	if (mlen && max)
2053c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments++;
2054c9de560dSAlex Tomas 	else if (!mlen && !max)
2055c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments--;
2056c9de560dSAlex Tomas 
2057c9de560dSAlex Tomas 	/* let's maintain buddy itself */
2058c9de560dSAlex Tomas 	while (len) {
2059218a6944Shanjinke 		if (!split)
2060c9de560dSAlex Tomas 			ord = mb_find_order_for_block(e4b, start);
2061c9de560dSAlex Tomas 
2062c9de560dSAlex Tomas 		if (((start >> ord) << ord) == start && len >= (1 << ord)) {
2063c9de560dSAlex Tomas 			/* the whole chunk may be allocated at once! */
2064c9de560dSAlex Tomas 			mlen = 1 << ord;
2065218a6944Shanjinke 			if (!split)
2066c9de560dSAlex Tomas 				buddy = mb_find_buddy(e4b, ord, &max);
2067218a6944Shanjinke 			else
2068218a6944Shanjinke 				split = false;
2069c9de560dSAlex Tomas 			BUG_ON((start >> ord) >= max);
2070c9de560dSAlex Tomas 			mb_set_bit(start >> ord, buddy);
2071c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[ord]--;
2072c9de560dSAlex Tomas 			start += mlen;
2073c9de560dSAlex Tomas 			len -= mlen;
2074c9de560dSAlex Tomas 			BUG_ON(len < 0);
2075c9de560dSAlex Tomas 			continue;
2076c9de560dSAlex Tomas 		}
2077c9de560dSAlex Tomas 
2078c9de560dSAlex Tomas 		/* store for history */
2079c9de560dSAlex Tomas 		if (ret == 0)
2080c9de560dSAlex Tomas 			ret = len | (ord << 16);
2081c9de560dSAlex Tomas 
2082c9de560dSAlex Tomas 		/* we have to split large buddy */
2083c9de560dSAlex Tomas 		BUG_ON(ord <= 0);
2084c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, ord, &max);
2085c9de560dSAlex Tomas 		mb_set_bit(start >> ord, buddy);
2086c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]--;
2087c9de560dSAlex Tomas 
2088c9de560dSAlex Tomas 		ord--;
2089c9de560dSAlex Tomas 		cur = (start >> ord) & ~1U;
2090c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, ord, &max);
2091c9de560dSAlex Tomas 		mb_clear_bit(cur, buddy);
2092c9de560dSAlex Tomas 		mb_clear_bit(cur + 1, buddy);
2093c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]++;
2094c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]++;
2095218a6944Shanjinke 		split = true;
2096c9de560dSAlex Tomas 	}
20978a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
2098c9de560dSAlex Tomas 
2099196e402aSHarshad Shirwadkar 	mb_update_avg_fragment_size(e4b->bd_sb, e4b->bd_info);
2100123e3016SRitesh Harjani 	mb_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
2101c9de560dSAlex Tomas 	mb_check_buddy(e4b);
2102c9de560dSAlex Tomas 
2103c9de560dSAlex Tomas 	return ret;
2104c9de560dSAlex Tomas }
2105c9de560dSAlex Tomas 
2106c9de560dSAlex Tomas /*
2107c9de560dSAlex Tomas  * Must be called under group lock!
2108c9de560dSAlex Tomas  */
2109c9de560dSAlex Tomas static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
2110c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2111c9de560dSAlex Tomas {
2112c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2113c9de560dSAlex Tomas 	int ret;
2114c9de560dSAlex Tomas 
2115c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
2116c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2117c9de560dSAlex Tomas 
2118c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
2119c9de560dSAlex Tomas 	ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
2120c9de560dSAlex Tomas 	ret = mb_mark_used(e4b, &ac->ac_b_ex);
2121c9de560dSAlex Tomas 
2122c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
2123c9de560dSAlex Tomas 	 * allocated blocks for history */
2124c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
2125c9de560dSAlex Tomas 
2126c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
2127c9de560dSAlex Tomas 	ac->ac_tail = ret & 0xffff;
2128c9de560dSAlex Tomas 	ac->ac_buddy = ret >> 16;
2129c9de560dSAlex Tomas 
2130c3a326a6SAneesh Kumar K.V 	/*
2131c3a326a6SAneesh Kumar K.V 	 * take the page reference. We want the page to be pinned
2132c3a326a6SAneesh Kumar K.V 	 * so that we don't get a ext4_mb_init_cache_call for this
2133c3a326a6SAneesh Kumar K.V 	 * group until we update the bitmap. That would mean we
2134c3a326a6SAneesh Kumar K.V 	 * double allocate blocks. The reference is dropped
2135c3a326a6SAneesh Kumar K.V 	 * in ext4_mb_release_context
2136c3a326a6SAneesh Kumar K.V 	 */
2137c9de560dSAlex Tomas 	ac->ac_bitmap_page = e4b->bd_bitmap_page;
2138c9de560dSAlex Tomas 	get_page(ac->ac_bitmap_page);
2139c9de560dSAlex Tomas 	ac->ac_buddy_page = e4b->bd_buddy_page;
2140c9de560dSAlex Tomas 	get_page(ac->ac_buddy_page);
2141c9de560dSAlex Tomas 	/* store last allocated for subsequent stream allocation */
21424ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2143c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
2144c9de560dSAlex Tomas 		sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
2145c9de560dSAlex Tomas 		sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
2146c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
2147c9de560dSAlex Tomas 	}
214853f86b17SRitesh Harjani 	/*
214953f86b17SRitesh Harjani 	 * As we've just preallocated more space than
215053f86b17SRitesh Harjani 	 * user requested originally, we store allocated
215153f86b17SRitesh Harjani 	 * space in a special descriptor.
215253f86b17SRitesh Harjani 	 */
215353f86b17SRitesh Harjani 	if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
215453f86b17SRitesh Harjani 		ext4_mb_new_preallocation(ac);
215553f86b17SRitesh Harjani 
2156c9de560dSAlex Tomas }
2157c9de560dSAlex Tomas 
2158c9de560dSAlex Tomas static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
2159c9de560dSAlex Tomas 					struct ext4_buddy *e4b,
2160c9de560dSAlex Tomas 					int finish_group)
2161c9de560dSAlex Tomas {
2162c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2163c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
2164c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
2165c9de560dSAlex Tomas 
2166032115fcSAneesh Kumar K.V 	if (ac->ac_status == AC_STATUS_FOUND)
2167032115fcSAneesh Kumar K.V 		return;
2168c9de560dSAlex Tomas 	/*
2169c9de560dSAlex Tomas 	 * We don't want to scan for a whole year
2170c9de560dSAlex Tomas 	 */
2171c9de560dSAlex Tomas 	if (ac->ac_found > sbi->s_mb_max_to_scan &&
2172c9de560dSAlex Tomas 			!(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2173c9de560dSAlex Tomas 		ac->ac_status = AC_STATUS_BREAK;
2174c9de560dSAlex Tomas 		return;
2175c9de560dSAlex Tomas 	}
2176c9de560dSAlex Tomas 
2177c9de560dSAlex Tomas 	/*
2178c9de560dSAlex Tomas 	 * Haven't found good chunk so far, let's continue
2179c9de560dSAlex Tomas 	 */
2180c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len)
2181c9de560dSAlex Tomas 		return;
2182c9de560dSAlex Tomas 
21833582e745SOjaswin Mujoo 	if (finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
2184c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2185c9de560dSAlex Tomas }
2186c9de560dSAlex Tomas 
2187c9de560dSAlex Tomas /*
2188c9de560dSAlex Tomas  * The routine checks whether found extent is good enough. If it is,
2189c9de560dSAlex Tomas  * then the extent gets marked used and flag is set to the context
2190c9de560dSAlex Tomas  * to stop scanning. Otherwise, the extent is compared with the
2191c9de560dSAlex Tomas  * previous found extent and if new one is better, then it's stored
2192c9de560dSAlex Tomas  * in the context. Later, the best found extent will be used, if
2193c9de560dSAlex Tomas  * mballoc can't find good enough extent.
2194c9de560dSAlex Tomas  *
21953582e745SOjaswin Mujoo  * The algorithm used is roughly as follows:
21963582e745SOjaswin Mujoo  *
21973582e745SOjaswin Mujoo  * * If free extent found is exactly as big as goal, then
21983582e745SOjaswin Mujoo  *   stop the scan and use it immediately
21993582e745SOjaswin Mujoo  *
22003582e745SOjaswin Mujoo  * * If free extent found is smaller than goal, then keep retrying
22013582e745SOjaswin Mujoo  *   upto a max of sbi->s_mb_max_to_scan times (default 200). After
22023582e745SOjaswin Mujoo  *   that stop scanning and use whatever we have.
22033582e745SOjaswin Mujoo  *
22043582e745SOjaswin Mujoo  * * If free extent found is bigger than goal, then keep retrying
22053582e745SOjaswin Mujoo  *   upto a max of sbi->s_mb_min_to_scan times (default 10) before
22063582e745SOjaswin Mujoo  *   stopping the scan and using the extent.
22073582e745SOjaswin Mujoo  *
22083582e745SOjaswin Mujoo  *
2209c9de560dSAlex Tomas  * FIXME: real allocation policy is to be designed yet!
2210c9de560dSAlex Tomas  */
2211c9de560dSAlex Tomas static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
2212c9de560dSAlex Tomas 					struct ext4_free_extent *ex,
2213c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2214c9de560dSAlex Tomas {
2215c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
2216c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
2217c9de560dSAlex Tomas 
2218c9de560dSAlex Tomas 	BUG_ON(ex->fe_len <= 0);
22197137d7a4STheodore Ts'o 	BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
22207137d7a4STheodore Ts'o 	BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2221c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
2222c9de560dSAlex Tomas 
2223c9de560dSAlex Tomas 	ac->ac_found++;
2224fdd9a009SOjaswin Mujoo 	ac->ac_cX_found[ac->ac_criteria]++;
2225c9de560dSAlex Tomas 
2226c9de560dSAlex Tomas 	/*
2227c9de560dSAlex Tomas 	 * The special case - take what you catch first
2228c9de560dSAlex Tomas 	 */
2229c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2230c9de560dSAlex Tomas 		*bex = *ex;
2231c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2232c9de560dSAlex Tomas 		return;
2233c9de560dSAlex Tomas 	}
2234c9de560dSAlex Tomas 
2235c9de560dSAlex Tomas 	/*
2236c9de560dSAlex Tomas 	 * Let's check whether the chuck is good enough
2237c9de560dSAlex Tomas 	 */
2238c9de560dSAlex Tomas 	if (ex->fe_len == gex->fe_len) {
2239c9de560dSAlex Tomas 		*bex = *ex;
2240c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2241c9de560dSAlex Tomas 		return;
2242c9de560dSAlex Tomas 	}
2243c9de560dSAlex Tomas 
2244c9de560dSAlex Tomas 	/*
2245c9de560dSAlex Tomas 	 * If this is first found extent, just store it in the context
2246c9de560dSAlex Tomas 	 */
2247c9de560dSAlex Tomas 	if (bex->fe_len == 0) {
2248c9de560dSAlex Tomas 		*bex = *ex;
2249c9de560dSAlex Tomas 		return;
2250c9de560dSAlex Tomas 	}
2251c9de560dSAlex Tomas 
2252c9de560dSAlex Tomas 	/*
2253c9de560dSAlex Tomas 	 * If new found extent is better, store it in the context
2254c9de560dSAlex Tomas 	 */
2255c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len) {
2256c9de560dSAlex Tomas 		/* if the request isn't satisfied, any found extent
2257c9de560dSAlex Tomas 		 * larger than previous best one is better */
2258c9de560dSAlex Tomas 		if (ex->fe_len > bex->fe_len)
2259c9de560dSAlex Tomas 			*bex = *ex;
2260c9de560dSAlex Tomas 	} else if (ex->fe_len > gex->fe_len) {
2261c9de560dSAlex Tomas 		/* if the request is satisfied, then we try to find
2262c9de560dSAlex Tomas 		 * an extent that still satisfy the request, but is
2263c9de560dSAlex Tomas 		 * smaller than previous one */
2264c9de560dSAlex Tomas 		if (ex->fe_len < bex->fe_len)
2265c9de560dSAlex Tomas 			*bex = *ex;
2266c9de560dSAlex Tomas 	}
2267c9de560dSAlex Tomas 
2268c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 0);
2269c9de560dSAlex Tomas }
2270c9de560dSAlex Tomas 
2271089ceeccSEric Sandeen static noinline_for_stack
227285b67ffbSKemeng Shi void ext4_mb_try_best_found(struct ext4_allocation_context *ac,
2273c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2274c9de560dSAlex Tomas {
2275c9de560dSAlex Tomas 	struct ext4_free_extent ex = ac->ac_b_ex;
2276c9de560dSAlex Tomas 	ext4_group_t group = ex.fe_group;
2277c9de560dSAlex Tomas 	int max;
2278c9de560dSAlex Tomas 	int err;
2279c9de560dSAlex Tomas 
2280c9de560dSAlex Tomas 	BUG_ON(ex.fe_len <= 0);
2281c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2282c9de560dSAlex Tomas 	if (err)
228385b67ffbSKemeng Shi 		return;
2284c9de560dSAlex Tomas 
2285c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
228615c006a2SRobin Dong 	max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
2287c9de560dSAlex Tomas 
2288c9de560dSAlex Tomas 	if (max > 0) {
2289c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
2290c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2291c9de560dSAlex Tomas 	}
2292c9de560dSAlex Tomas 
2293c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
2294e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
2295c9de560dSAlex Tomas }
2296c9de560dSAlex Tomas 
2297089ceeccSEric Sandeen static noinline_for_stack
2298089ceeccSEric Sandeen int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
2299c9de560dSAlex Tomas 				struct ext4_buddy *e4b)
2300c9de560dSAlex Tomas {
2301c9de560dSAlex Tomas 	ext4_group_t group = ac->ac_g_ex.fe_group;
2302c9de560dSAlex Tomas 	int max;
2303c9de560dSAlex Tomas 	int err;
2304c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2305838cd0cfSYongqiang Yang 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2306c9de560dSAlex Tomas 	struct ext4_free_extent ex;
2307c9de560dSAlex Tomas 
23085354b2afSTheodore Ts'o 	if (!grp)
23095354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
231001e4ca29SKemeng Shi 	if (!(ac->ac_flags & (EXT4_MB_HINT_TRY_GOAL | EXT4_MB_HINT_GOAL_ONLY)))
2311c9de560dSAlex Tomas 		return 0;
2312838cd0cfSYongqiang Yang 	if (grp->bb_free == 0)
2313838cd0cfSYongqiang Yang 		return 0;
2314c9de560dSAlex Tomas 
2315c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2316c9de560dSAlex Tomas 	if (err)
2317c9de560dSAlex Tomas 		return err;
2318c9de560dSAlex Tomas 
2319163a203dSDarrick J. Wong 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
2320163a203dSDarrick J. Wong 		ext4_mb_unload_buddy(e4b);
2321163a203dSDarrick J. Wong 		return 0;
2322163a203dSDarrick J. Wong 	}
2323163a203dSDarrick J. Wong 
2324c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
232515c006a2SRobin Dong 	max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
2326c9de560dSAlex Tomas 			     ac->ac_g_ex.fe_len, &ex);
2327ab0c00fcSTheodore Ts'o 	ex.fe_logical = 0xDEADFA11; /* debug value */
2328c9de560dSAlex Tomas 
2329c3defd99SKemeng Shi 	if (max >= ac->ac_g_ex.fe_len &&
2330c3defd99SKemeng Shi 	    ac->ac_g_ex.fe_len == EXT4_B2C(sbi, sbi->s_stripe)) {
2331c9de560dSAlex Tomas 		ext4_fsblk_t start;
2332c9de560dSAlex Tomas 
233399c515e3SKemeng Shi 		start = ext4_grp_offs_to_block(ac->ac_sb, &ex);
2334c9de560dSAlex Tomas 		/* use do_div to get remainder (would be 64-bit modulo) */
2335c9de560dSAlex Tomas 		if (do_div(start, sbi->s_stripe) == 0) {
2336c9de560dSAlex Tomas 			ac->ac_found++;
2337c9de560dSAlex Tomas 			ac->ac_b_ex = ex;
2338c9de560dSAlex Tomas 			ext4_mb_use_best_found(ac, e4b);
2339c9de560dSAlex Tomas 		}
2340c9de560dSAlex Tomas 	} else if (max >= ac->ac_g_ex.fe_len) {
2341c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
2342c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2343c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2344c9de560dSAlex Tomas 		ac->ac_found++;
2345c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
2346c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2347c9de560dSAlex Tomas 	} else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
2348c9de560dSAlex Tomas 		/* Sometimes, caller may want to merge even small
2349c9de560dSAlex Tomas 		 * number of blocks to an existing extent */
2350c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
2351c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2352c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2353c9de560dSAlex Tomas 		ac->ac_found++;
2354c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
2355c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2356c9de560dSAlex Tomas 	}
2357c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
2358e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
2359c9de560dSAlex Tomas 
2360c9de560dSAlex Tomas 	return 0;
2361c9de560dSAlex Tomas }
2362c9de560dSAlex Tomas 
2363c9de560dSAlex Tomas /*
2364c9de560dSAlex Tomas  * The routine scans buddy structures (not bitmap!) from given order
2365c9de560dSAlex Tomas  * to max order and tries to find big enough chunk to satisfy the req
2366c9de560dSAlex Tomas  */
2367089ceeccSEric Sandeen static noinline_for_stack
2368089ceeccSEric Sandeen void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
2369c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2370c9de560dSAlex Tomas {
2371c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
2372c9de560dSAlex Tomas 	struct ext4_group_info *grp = e4b->bd_info;
2373c9de560dSAlex Tomas 	void *buddy;
2374c9de560dSAlex Tomas 	int i;
2375c9de560dSAlex Tomas 	int k;
2376c9de560dSAlex Tomas 	int max;
2377c9de560dSAlex Tomas 
2378c9de560dSAlex Tomas 	BUG_ON(ac->ac_2order <= 0);
23794b68f6dfSHarshad Shirwadkar 	for (i = ac->ac_2order; i < MB_NUM_ORDERS(sb); i++) {
2380c9de560dSAlex Tomas 		if (grp->bb_counters[i] == 0)
2381c9de560dSAlex Tomas 			continue;
2382c9de560dSAlex Tomas 
2383c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, i, &max);
238419b8b035STheodore Ts'o 		if (WARN_RATELIMIT(buddy == NULL,
238519b8b035STheodore Ts'o 			 "ext4: mb_simple_scan_group: mb_find_buddy failed, (%d)\n", i))
238619b8b035STheodore Ts'o 			continue;
2387c9de560dSAlex Tomas 
2388ffad0a44SAneesh Kumar K.V 		k = mb_find_next_zero_bit(buddy, max, 0);
2389eb576086SDmitry Monakhov 		if (k >= max) {
2390eb576086SDmitry Monakhov 			ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
2391eb576086SDmitry Monakhov 				"%d free clusters of order %d. But found 0",
2392eb576086SDmitry Monakhov 				grp->bb_counters[i], i);
2393eb576086SDmitry Monakhov 			ext4_mark_group_bitmap_corrupted(ac->ac_sb,
2394eb576086SDmitry Monakhov 					 e4b->bd_group,
2395eb576086SDmitry Monakhov 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2396eb576086SDmitry Monakhov 			break;
2397eb576086SDmitry Monakhov 		}
2398c9de560dSAlex Tomas 		ac->ac_found++;
2399fdd9a009SOjaswin Mujoo 		ac->ac_cX_found[ac->ac_criteria]++;
2400c9de560dSAlex Tomas 
2401c9de560dSAlex Tomas 		ac->ac_b_ex.fe_len = 1 << i;
2402c9de560dSAlex Tomas 		ac->ac_b_ex.fe_start = k << i;
2403c9de560dSAlex Tomas 		ac->ac_b_ex.fe_group = e4b->bd_group;
2404c9de560dSAlex Tomas 
2405c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
2406c9de560dSAlex Tomas 
240753f86b17SRitesh Harjani 		BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
2408c9de560dSAlex Tomas 
2409c9de560dSAlex Tomas 		if (EXT4_SB(sb)->s_mb_stats)
2410c9de560dSAlex Tomas 			atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
2411c9de560dSAlex Tomas 
2412c9de560dSAlex Tomas 		break;
2413c9de560dSAlex Tomas 	}
2414c9de560dSAlex Tomas }
2415c9de560dSAlex Tomas 
2416c9de560dSAlex Tomas /*
2417c9de560dSAlex Tomas  * The routine scans the group and measures all found extents.
2418c9de560dSAlex Tomas  * In order to optimize scanning, caller must pass number of
2419c9de560dSAlex Tomas  * free blocks in the group, so the routine can know upper limit.
2420c9de560dSAlex Tomas  */
2421089ceeccSEric Sandeen static noinline_for_stack
2422089ceeccSEric Sandeen void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
2423c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
2424c9de560dSAlex Tomas {
2425c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
2426c5e8f3f3STheodore Ts'o 	void *bitmap = e4b->bd_bitmap;
2427c9de560dSAlex Tomas 	struct ext4_free_extent ex;
24281b420011SOjaswin Mujoo 	int i, j, freelen;
2429c9de560dSAlex Tomas 	int free;
2430c9de560dSAlex Tomas 
2431c9de560dSAlex Tomas 	free = e4b->bd_info->bb_free;
2432907ea529STheodore Ts'o 	if (WARN_ON(free <= 0))
2433907ea529STheodore Ts'o 		return;
2434c9de560dSAlex Tomas 
2435c9de560dSAlex Tomas 	i = e4b->bd_info->bb_first_free;
2436c9de560dSAlex Tomas 
2437c9de560dSAlex Tomas 	while (free && ac->ac_status == AC_STATUS_CONTINUE) {
2438ffad0a44SAneesh Kumar K.V 		i = mb_find_next_zero_bit(bitmap,
24397137d7a4STheodore Ts'o 						EXT4_CLUSTERS_PER_GROUP(sb), i);
24407137d7a4STheodore Ts'o 		if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
244126346ff6SAneesh Kumar K.V 			/*
2442e56eb659SAneesh Kumar K.V 			 * IF we have corrupt bitmap, we won't find any
244326346ff6SAneesh Kumar K.V 			 * free blocks even though group info says we
2444b483bb77SRandy Dunlap 			 * have free blocks
244526346ff6SAneesh Kumar K.V 			 */
2446e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
244753accfa9STheodore Ts'o 					"%d free clusters as per "
2448fde4d95aSTheodore Ts'o 					"group info. But bitmap says 0",
244926346ff6SAneesh Kumar K.V 					free);
2450736dedbbSWang Shilong 			ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2451736dedbbSWang Shilong 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2452c9de560dSAlex Tomas 			break;
2453c9de560dSAlex Tomas 		}
2454c9de560dSAlex Tomas 
2455304749c0SOjaswin Mujoo 		if (!ext4_mb_cr_expensive(ac->ac_criteria)) {
24561b420011SOjaswin Mujoo 			/*
2457f52f3d2bSOjaswin Mujoo 			 * In CR_GOAL_LEN_FAST and CR_BEST_AVAIL_LEN, we are
2458f52f3d2bSOjaswin Mujoo 			 * sure that this group will have a large enough
2459f52f3d2bSOjaswin Mujoo 			 * continuous free extent, so skip over the smaller free
2460f52f3d2bSOjaswin Mujoo 			 * extents
24611b420011SOjaswin Mujoo 			 */
24621b420011SOjaswin Mujoo 			j = mb_find_next_bit(bitmap,
24631b420011SOjaswin Mujoo 						EXT4_CLUSTERS_PER_GROUP(sb), i);
24641b420011SOjaswin Mujoo 			freelen = j - i;
24651b420011SOjaswin Mujoo 
24661b420011SOjaswin Mujoo 			if (freelen < ac->ac_g_ex.fe_len) {
24671b420011SOjaswin Mujoo 				i = j;
24681b420011SOjaswin Mujoo 				free -= freelen;
24691b420011SOjaswin Mujoo 				continue;
24701b420011SOjaswin Mujoo 			}
24711b420011SOjaswin Mujoo 		}
24721b420011SOjaswin Mujoo 
247315c006a2SRobin Dong 		mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
2474907ea529STheodore Ts'o 		if (WARN_ON(ex.fe_len <= 0))
2475907ea529STheodore Ts'o 			break;
247626346ff6SAneesh Kumar K.V 		if (free < ex.fe_len) {
2477e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
247853accfa9STheodore Ts'o 					"%d free clusters as per "
2479fde4d95aSTheodore Ts'o 					"group info. But got %d blocks",
248026346ff6SAneesh Kumar K.V 					free, ex.fe_len);
2481736dedbbSWang Shilong 			ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2482736dedbbSWang Shilong 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2483e56eb659SAneesh Kumar K.V 			/*
2484e56eb659SAneesh Kumar K.V 			 * The number of free blocks differs. This mostly
2485e56eb659SAneesh Kumar K.V 			 * indicate that the bitmap is corrupt. So exit
2486e56eb659SAneesh Kumar K.V 			 * without claiming the space.
2487e56eb659SAneesh Kumar K.V 			 */
2488e56eb659SAneesh Kumar K.V 			break;
248926346ff6SAneesh Kumar K.V 		}
2490ab0c00fcSTheodore Ts'o 		ex.fe_logical = 0xDEADC0DE; /* debug value */
2491c9de560dSAlex Tomas 		ext4_mb_measure_extent(ac, &ex, e4b);
2492c9de560dSAlex Tomas 
2493c9de560dSAlex Tomas 		i += ex.fe_len;
2494c9de560dSAlex Tomas 		free -= ex.fe_len;
2495c9de560dSAlex Tomas 	}
2496c9de560dSAlex Tomas 
2497c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 1);
2498c9de560dSAlex Tomas }
2499c9de560dSAlex Tomas 
2500c9de560dSAlex Tomas /*
2501c9de560dSAlex Tomas  * This is a special case for storages like raid5
2502506bf2d8SEric Sandeen  * we try to find stripe-aligned chunks for stripe-size-multiple requests
2503c9de560dSAlex Tomas  */
2504089ceeccSEric Sandeen static noinline_for_stack
2505089ceeccSEric Sandeen void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2506c9de560dSAlex Tomas 				 struct ext4_buddy *e4b)
2507c9de560dSAlex Tomas {
2508c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
2509c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2510c5e8f3f3STheodore Ts'o 	void *bitmap = e4b->bd_bitmap;
2511c9de560dSAlex Tomas 	struct ext4_free_extent ex;
2512c9de560dSAlex Tomas 	ext4_fsblk_t first_group_block;
2513c9de560dSAlex Tomas 	ext4_fsblk_t a;
2514c3defd99SKemeng Shi 	ext4_grpblk_t i, stripe;
2515c9de560dSAlex Tomas 	int max;
2516c9de560dSAlex Tomas 
2517c9de560dSAlex Tomas 	BUG_ON(sbi->s_stripe == 0);
2518c9de560dSAlex Tomas 
2519c9de560dSAlex Tomas 	/* find first stripe-aligned block in group */
25205661bd68SAkinobu Mita 	first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
25215661bd68SAkinobu Mita 
2522c9de560dSAlex Tomas 	a = first_group_block + sbi->s_stripe - 1;
2523c9de560dSAlex Tomas 	do_div(a, sbi->s_stripe);
2524c9de560dSAlex Tomas 	i = (a * sbi->s_stripe) - first_group_block;
2525c9de560dSAlex Tomas 
2526c3defd99SKemeng Shi 	stripe = EXT4_B2C(sbi, sbi->s_stripe);
2527c3defd99SKemeng Shi 	i = EXT4_B2C(sbi, i);
25287137d7a4STheodore Ts'o 	while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2529c9de560dSAlex Tomas 		if (!mb_test_bit(i, bitmap)) {
2530c3defd99SKemeng Shi 			max = mb_find_extent(e4b, i, stripe, &ex);
2531c3defd99SKemeng Shi 			if (max >= stripe) {
2532c9de560dSAlex Tomas 				ac->ac_found++;
2533fdd9a009SOjaswin Mujoo 				ac->ac_cX_found[ac->ac_criteria]++;
2534ab0c00fcSTheodore Ts'o 				ex.fe_logical = 0xDEADF00D; /* debug value */
2535c9de560dSAlex Tomas 				ac->ac_b_ex = ex;
2536c9de560dSAlex Tomas 				ext4_mb_use_best_found(ac, e4b);
2537c9de560dSAlex Tomas 				break;
2538c9de560dSAlex Tomas 			}
2539c9de560dSAlex Tomas 		}
2540c3defd99SKemeng Shi 		i += stripe;
2541c9de560dSAlex Tomas 	}
2542c9de560dSAlex Tomas }
2543c9de560dSAlex Tomas 
254442ac1848SLukas Czerner /*
25458ef123feSRitesh Harjani  * This is also called BEFORE we load the buddy bitmap.
254642ac1848SLukas Czerner  * Returns either 1 or 0 indicating that the group is either suitable
25478ef123feSRitesh Harjani  * for the allocation or not.
254842ac1848SLukas Czerner  */
25498ef123feSRitesh Harjani static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
25504eb7a4a1SOjaswin Mujoo 				ext4_group_t group, enum criteria cr)
2551c9de560dSAlex Tomas {
25528ef123feSRitesh Harjani 	ext4_grpblk_t free, fragments;
2553a4912123STheodore Ts'o 	int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2554c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2555c9de560dSAlex Tomas 
2556f52f3d2bSOjaswin Mujoo 	BUG_ON(cr < CR_POWER2_ALIGNED || cr >= EXT4_MB_NUM_CRS);
25578a57d9d6SCurt Wohlgemuth 
2558a9ce5993SKemeng Shi 	if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
25598ef123feSRitesh Harjani 		return false;
256001fc48e8STheodore Ts'o 
2561dddcd2f9Sbrookxu 	free = grp->bb_free;
2562dddcd2f9Sbrookxu 	if (free == 0)
25638ef123feSRitesh Harjani 		return false;
2564c9de560dSAlex Tomas 
2565c9de560dSAlex Tomas 	fragments = grp->bb_fragments;
2566c9de560dSAlex Tomas 	if (fragments == 0)
25678ef123feSRitesh Harjani 		return false;
2568c9de560dSAlex Tomas 
2569c9de560dSAlex Tomas 	switch (cr) {
2570f52f3d2bSOjaswin Mujoo 	case CR_POWER2_ALIGNED:
2571c9de560dSAlex Tomas 		BUG_ON(ac->ac_2order == 0);
2572c9de560dSAlex Tomas 
2573a4912123STheodore Ts'o 		/* Avoid using the first bg of a flexgroup for data files */
2574a4912123STheodore Ts'o 		if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2575a4912123STheodore Ts'o 		    (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2576a4912123STheodore Ts'o 		    ((group % flex_size) == 0))
25778ef123feSRitesh Harjani 			return false;
2578a4912123STheodore Ts'o 
2579dddcd2f9Sbrookxu 		if (free < ac->ac_g_ex.fe_len)
2580dddcd2f9Sbrookxu 			return false;
2581dddcd2f9Sbrookxu 
25824b68f6dfSHarshad Shirwadkar 		if (ac->ac_2order >= MB_NUM_ORDERS(ac->ac_sb))
25838ef123feSRitesh Harjani 			return true;
258440ae3487STheodore Ts'o 
258540ae3487STheodore Ts'o 		if (grp->bb_largest_free_order < ac->ac_2order)
25868ef123feSRitesh Harjani 			return false;
258740ae3487STheodore Ts'o 
25888ef123feSRitesh Harjani 		return true;
2589f52f3d2bSOjaswin Mujoo 	case CR_GOAL_LEN_FAST:
2590f52f3d2bSOjaswin Mujoo 	case CR_BEST_AVAIL_LEN:
2591c9de560dSAlex Tomas 		if ((free / fragments) >= ac->ac_g_ex.fe_len)
25928ef123feSRitesh Harjani 			return true;
2593c9de560dSAlex Tomas 		break;
2594f52f3d2bSOjaswin Mujoo 	case CR_GOAL_LEN_SLOW:
2595c9de560dSAlex Tomas 		if (free >= ac->ac_g_ex.fe_len)
25968ef123feSRitesh Harjani 			return true;
2597c9de560dSAlex Tomas 		break;
2598f52f3d2bSOjaswin Mujoo 	case CR_ANY_FREE:
25998ef123feSRitesh Harjani 		return true;
2600c9de560dSAlex Tomas 	default:
2601c9de560dSAlex Tomas 		BUG();
2602c9de560dSAlex Tomas 	}
2603c9de560dSAlex Tomas 
26048ef123feSRitesh Harjani 	return false;
26058ef123feSRitesh Harjani }
26068ef123feSRitesh Harjani 
26078ef123feSRitesh Harjani /*
26088ef123feSRitesh Harjani  * This could return negative error code if something goes wrong
26098ef123feSRitesh Harjani  * during ext4_mb_init_group(). This should not be called with
26108ef123feSRitesh Harjani  * ext4_lock_group() held.
2611a5fda113STheodore Ts'o  *
2612a5fda113STheodore Ts'o  * Note: because we are conditionally operating with the group lock in
2613a5fda113STheodore Ts'o  * the EXT4_MB_STRICT_CHECK case, we need to fake out sparse in this
2614a5fda113STheodore Ts'o  * function using __acquire and __release.  This means we need to be
2615a5fda113STheodore Ts'o  * super careful before messing with the error path handling via "goto
2616a5fda113STheodore Ts'o  * out"!
26178ef123feSRitesh Harjani  */
26188ef123feSRitesh Harjani static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
26194eb7a4a1SOjaswin Mujoo 				     ext4_group_t group, enum criteria cr)
26208ef123feSRitesh Harjani {
26218ef123feSRitesh Harjani 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
262299377830SRitesh Harjani 	struct super_block *sb = ac->ac_sb;
2623c1d2c7d4SAlex Zhuravlev 	struct ext4_sb_info *sbi = EXT4_SB(sb);
262499377830SRitesh Harjani 	bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
26258ef123feSRitesh Harjani 	ext4_grpblk_t free;
26268ef123feSRitesh Harjani 	int ret = 0;
26278ef123feSRitesh Harjani 
26285354b2afSTheodore Ts'o 	if (!grp)
26295354b2afSTheodore Ts'o 		return -EFSCORRUPTED;
2630a6c75eafSHarshad Shirwadkar 	if (sbi->s_mb_stats)
2631a6c75eafSHarshad Shirwadkar 		atomic64_inc(&sbi->s_bal_cX_groups_considered[ac->ac_criteria]);
2632a5fda113STheodore Ts'o 	if (should_lock) {
263399377830SRitesh Harjani 		ext4_lock_group(sb, group);
2634a5fda113STheodore Ts'o 		__release(ext4_group_lock_ptr(sb, group));
2635a5fda113STheodore Ts'o 	}
26368ef123feSRitesh Harjani 	free = grp->bb_free;
26378ef123feSRitesh Harjani 	if (free == 0)
26388ef123feSRitesh Harjani 		goto out;
2639304749c0SOjaswin Mujoo 	/*
2640304749c0SOjaswin Mujoo 	 * In all criterias except CR_ANY_FREE we try to avoid groups that
2641304749c0SOjaswin Mujoo 	 * can't possibly satisfy the full goal request due to insufficient
2642304749c0SOjaswin Mujoo 	 * free blocks.
2643304749c0SOjaswin Mujoo 	 */
2644304749c0SOjaswin Mujoo 	if (cr < CR_ANY_FREE && free < ac->ac_g_ex.fe_len)
26458ef123feSRitesh Harjani 		goto out;
26468ef123feSRitesh Harjani 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
26478ef123feSRitesh Harjani 		goto out;
2648a5fda113STheodore Ts'o 	if (should_lock) {
2649a5fda113STheodore Ts'o 		__acquire(ext4_group_lock_ptr(sb, group));
265099377830SRitesh Harjani 		ext4_unlock_group(sb, group);
2651a5fda113STheodore Ts'o 	}
26528ef123feSRitesh Harjani 
26538ef123feSRitesh Harjani 	/* We only do this if the grp has never been initialized */
26548ef123feSRitesh Harjani 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2655c1d2c7d4SAlex Zhuravlev 		struct ext4_group_desc *gdp =
2656c1d2c7d4SAlex Zhuravlev 			ext4_get_group_desc(sb, group, NULL);
2657c1d2c7d4SAlex Zhuravlev 		int ret;
2658c1d2c7d4SAlex Zhuravlev 
2659f52f3d2bSOjaswin Mujoo 		/*
2660f52f3d2bSOjaswin Mujoo 		 * cr=CR_POWER2_ALIGNED/CR_GOAL_LEN_FAST is a very optimistic
2661f52f3d2bSOjaswin Mujoo 		 * search to find large good chunks almost for free. If buddy
2662f52f3d2bSOjaswin Mujoo 		 * data is not ready, then this optimization makes no sense. But
2663f52f3d2bSOjaswin Mujoo 		 * we never skip the first block group in a flex_bg, since this
2664f52f3d2bSOjaswin Mujoo 		 * gets used for metadata block allocation, and we want to make
2665f52f3d2bSOjaswin Mujoo 		 * sure we locate metadata blocks in the first block group in
2666f52f3d2bSOjaswin Mujoo 		 * the flex_bg if possible.
2667c1d2c7d4SAlex Zhuravlev 		 */
2668304749c0SOjaswin Mujoo 		if (!ext4_mb_cr_expensive(cr) &&
2669c1d2c7d4SAlex Zhuravlev 		    (!sbi->s_log_groups_per_flex ||
2670c1d2c7d4SAlex Zhuravlev 		     ((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
2671c1d2c7d4SAlex Zhuravlev 		    !(ext4_has_group_desc_csum(sb) &&
2672c1d2c7d4SAlex Zhuravlev 		      (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
2673c1d2c7d4SAlex Zhuravlev 			return 0;
2674c1d2c7d4SAlex Zhuravlev 		ret = ext4_mb_init_group(sb, group, GFP_NOFS);
26758ef123feSRitesh Harjani 		if (ret)
26768ef123feSRitesh Harjani 			return ret;
26778ef123feSRitesh Harjani 	}
26788ef123feSRitesh Harjani 
2679a5fda113STheodore Ts'o 	if (should_lock) {
268099377830SRitesh Harjani 		ext4_lock_group(sb, group);
2681a5fda113STheodore Ts'o 		__release(ext4_group_lock_ptr(sb, group));
2682a5fda113STheodore Ts'o 	}
26838ef123feSRitesh Harjani 	ret = ext4_mb_good_group(ac, group, cr);
26848ef123feSRitesh Harjani out:
2685a5fda113STheodore Ts'o 	if (should_lock) {
2686a5fda113STheodore Ts'o 		__acquire(ext4_group_lock_ptr(sb, group));
268799377830SRitesh Harjani 		ext4_unlock_group(sb, group);
2688a5fda113STheodore Ts'o 	}
26898ef123feSRitesh Harjani 	return ret;
2690c9de560dSAlex Tomas }
2691c9de560dSAlex Tomas 
2692cfd73237SAlex Zhuravlev /*
2693cfd73237SAlex Zhuravlev  * Start prefetching @nr block bitmaps starting at @group.
2694cfd73237SAlex Zhuravlev  * Return the next group which needs to be prefetched.
2695cfd73237SAlex Zhuravlev  */
26963d392b26STheodore Ts'o ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
2697cfd73237SAlex Zhuravlev 			      unsigned int nr, int *cnt)
2698cfd73237SAlex Zhuravlev {
2699cfd73237SAlex Zhuravlev 	ext4_group_t ngroups = ext4_get_groups_count(sb);
2700cfd73237SAlex Zhuravlev 	struct buffer_head *bh;
2701cfd73237SAlex Zhuravlev 	struct blk_plug plug;
2702cfd73237SAlex Zhuravlev 
2703cfd73237SAlex Zhuravlev 	blk_start_plug(&plug);
2704cfd73237SAlex Zhuravlev 	while (nr-- > 0) {
2705cfd73237SAlex Zhuravlev 		struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2706cfd73237SAlex Zhuravlev 								  NULL);
2707cfd73237SAlex Zhuravlev 		struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2708cfd73237SAlex Zhuravlev 
2709cfd73237SAlex Zhuravlev 		/*
2710cfd73237SAlex Zhuravlev 		 * Prefetch block groups with free blocks; but don't
2711cfd73237SAlex Zhuravlev 		 * bother if it is marked uninitialized on disk, since
2712cfd73237SAlex Zhuravlev 		 * it won't require I/O to read.  Also only try to
2713cfd73237SAlex Zhuravlev 		 * prefetch once, so we avoid getblk() call, which can
2714cfd73237SAlex Zhuravlev 		 * be expensive.
2715cfd73237SAlex Zhuravlev 		 */
27165354b2afSTheodore Ts'o 		if (gdp && grp && !EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
2717cfd73237SAlex Zhuravlev 		    EXT4_MB_GRP_NEED_INIT(grp) &&
27183c629604SOjaswin Mujoo 		    ext4_free_group_clusters(sb, gdp) > 0 ) {
2719cfd73237SAlex Zhuravlev 			bh = ext4_read_block_bitmap_nowait(sb, group, true);
2720cfd73237SAlex Zhuravlev 			if (bh && !IS_ERR(bh)) {
2721cfd73237SAlex Zhuravlev 				if (!buffer_uptodate(bh) && cnt)
2722cfd73237SAlex Zhuravlev 					(*cnt)++;
2723cfd73237SAlex Zhuravlev 				brelse(bh);
2724cfd73237SAlex Zhuravlev 			}
2725cfd73237SAlex Zhuravlev 		}
2726cfd73237SAlex Zhuravlev 		if (++group >= ngroups)
2727cfd73237SAlex Zhuravlev 			group = 0;
2728cfd73237SAlex Zhuravlev 	}
2729cfd73237SAlex Zhuravlev 	blk_finish_plug(&plug);
2730cfd73237SAlex Zhuravlev 	return group;
2731cfd73237SAlex Zhuravlev }
2732cfd73237SAlex Zhuravlev 
2733cfd73237SAlex Zhuravlev /*
2734cfd73237SAlex Zhuravlev  * Prefetching reads the block bitmap into the buffer cache; but we
2735cfd73237SAlex Zhuravlev  * need to make sure that the buddy bitmap in the page cache has been
2736cfd73237SAlex Zhuravlev  * initialized.  Note that ext4_mb_init_group() will block if the I/O
2737cfd73237SAlex Zhuravlev  * is not yet completed, or indeed if it was not initiated by
2738cfd73237SAlex Zhuravlev  * ext4_mb_prefetch did not start the I/O.
2739cfd73237SAlex Zhuravlev  *
2740cfd73237SAlex Zhuravlev  * TODO: We should actually kick off the buddy bitmap setup in a work
2741cfd73237SAlex Zhuravlev  * queue when the buffer I/O is completed, so that we don't block
2742cfd73237SAlex Zhuravlev  * waiting for the block allocation bitmap read to finish when
2743cfd73237SAlex Zhuravlev  * ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
2744cfd73237SAlex Zhuravlev  */
27453d392b26STheodore Ts'o void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
2746cfd73237SAlex Zhuravlev 			   unsigned int nr)
2747cfd73237SAlex Zhuravlev {
274822fab984SKemeng Shi 	struct ext4_group_desc *gdp;
274922fab984SKemeng Shi 	struct ext4_group_info *grp;
2750cfd73237SAlex Zhuravlev 
275122fab984SKemeng Shi 	while (nr-- > 0) {
2752cfd73237SAlex Zhuravlev 		if (!group)
2753cfd73237SAlex Zhuravlev 			group = ext4_get_groups_count(sb);
2754cfd73237SAlex Zhuravlev 		group--;
275522fab984SKemeng Shi 		gdp = ext4_get_group_desc(sb, group, NULL);
2756cfd73237SAlex Zhuravlev 		grp = ext4_get_group_info(sb, group);
2757cfd73237SAlex Zhuravlev 
27585354b2afSTheodore Ts'o 		if (grp && gdp && EXT4_MB_GRP_NEED_INIT(grp) &&
27593c629604SOjaswin Mujoo 		    ext4_free_group_clusters(sb, gdp) > 0) {
2760cfd73237SAlex Zhuravlev 			if (ext4_mb_init_group(sb, group, GFP_NOFS))
2761cfd73237SAlex Zhuravlev 				break;
2762cfd73237SAlex Zhuravlev 		}
2763cfd73237SAlex Zhuravlev 	}
2764cfd73237SAlex Zhuravlev }
2765cfd73237SAlex Zhuravlev 
27664ddfef7bSEric Sandeen static noinline_for_stack int
27674ddfef7bSEric Sandeen ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2768c9de560dSAlex Tomas {
2769cfd73237SAlex Zhuravlev 	ext4_group_t prefetch_grp = 0, ngroups, group, i;
27704c0cfebdSTheodore Ts'o 	enum criteria new_cr, cr = CR_GOAL_LEN_FAST;
277142ac1848SLukas Czerner 	int err = 0, first_err = 0;
2772cfd73237SAlex Zhuravlev 	unsigned int nr = 0, prefetch_ios = 0;
2773c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
2774c9de560dSAlex Tomas 	struct super_block *sb;
2775c9de560dSAlex Tomas 	struct ext4_buddy e4b;
277666d5e027Sbrookxu 	int lost;
2777c9de560dSAlex Tomas 
2778c9de560dSAlex Tomas 	sb = ac->ac_sb;
2779c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
27808df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
2781fb0a387dSEric Sandeen 	/* non-extent files are limited to low blocks/groups */
278212e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2783fb0a387dSEric Sandeen 		ngroups = sbi->s_blockfile_groups;
2784fb0a387dSEric Sandeen 
2785c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2786c9de560dSAlex Tomas 
2787c9de560dSAlex Tomas 	/* first, try the goal */
2788c9de560dSAlex Tomas 	err = ext4_mb_find_by_goal(ac, &e4b);
2789c9de560dSAlex Tomas 	if (err || ac->ac_status == AC_STATUS_FOUND)
2790c9de560dSAlex Tomas 		goto out;
2791c9de560dSAlex Tomas 
2792c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2793c9de560dSAlex Tomas 		goto out;
2794c9de560dSAlex Tomas 
2795c9de560dSAlex Tomas 	/*
2796e9a3cd48Sbrookxu 	 * ac->ac_2order is set only if the fe_len is a power of 2
27974eea9fbeSKemeng Shi 	 * if ac->ac_2order is set we also set criteria to CR_POWER2_ALIGNED
27984eea9fbeSKemeng Shi 	 * so that we try exact allocation using buddy.
2799c9de560dSAlex Tomas 	 */
2800c9de560dSAlex Tomas 	i = fls(ac->ac_g_ex.fe_len);
2801c9de560dSAlex Tomas 	ac->ac_2order = 0;
2802c9de560dSAlex Tomas 	/*
2803c9de560dSAlex Tomas 	 * We search using buddy data only if the order of the request
2804c9de560dSAlex Tomas 	 * is greater than equal to the sbi_s_mb_order2_reqs
2805b713a5ecSTheodore Ts'o 	 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2806d9b22cf9SJan Kara 	 * We also support searching for power-of-two requests only for
2807d9b22cf9SJan Kara 	 * requests upto maximum buddy size we have constructed.
2808c9de560dSAlex Tomas 	 */
28094b68f6dfSHarshad Shirwadkar 	if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) {
2810bb60caa2SKemeng Shi 		if (is_power_of_2(ac->ac_g_ex.fe_len))
28111a5d5e5dSJeremy Cline 			ac->ac_2order = array_index_nospec(i - 1,
28124b68f6dfSHarshad Shirwadkar 							   MB_NUM_ORDERS(sb));
2813c9de560dSAlex Tomas 	}
2814c9de560dSAlex Tomas 
28154ba74d00STheodore Ts'o 	/* if stream allocation is enabled, use global goal */
28164ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2817c9de560dSAlex Tomas 		/* TBD: may be hot point */
2818c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
2819c9de560dSAlex Tomas 		ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2820c9de560dSAlex Tomas 		ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2821c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
2822c9de560dSAlex Tomas 	}
28234ba74d00STheodore Ts'o 
2824c9de560dSAlex Tomas 	/*
28254c0cfebdSTheodore Ts'o 	 * Let's just scan groups to find more-less suitable blocks We
28264c0cfebdSTheodore Ts'o 	 * start with CR_GOAL_LEN_FAST, unless it is power of 2
28274c0cfebdSTheodore Ts'o 	 * aligned, in which case let's do that faster approach first.
2828c9de560dSAlex Tomas 	 */
28294c0cfebdSTheodore Ts'o 	if (ac->ac_2order)
28304c0cfebdSTheodore Ts'o 		cr = CR_POWER2_ALIGNED;
2831c9de560dSAlex Tomas repeat:
28324eb7a4a1SOjaswin Mujoo 	for (; cr < EXT4_MB_NUM_CRS && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2833c9de560dSAlex Tomas 		ac->ac_criteria = cr;
2834ed8f9c75SAneesh Kumar K.V 		/*
2835ed8f9c75SAneesh Kumar K.V 		 * searching for the right group start
2836ed8f9c75SAneesh Kumar K.V 		 * from the goal value specified
2837ed8f9c75SAneesh Kumar K.V 		 */
2838ed8f9c75SAneesh Kumar K.V 		group = ac->ac_g_ex.fe_group;
2839196e402aSHarshad Shirwadkar 		ac->ac_groups_linear_remaining = sbi->s_mb_max_linear_groups;
2840cfd73237SAlex Zhuravlev 		prefetch_grp = group;
2841ed8f9c75SAneesh Kumar K.V 
28424fca50d4SJan Kara 		for (i = 0, new_cr = cr; i < ngroups; i++,
28434fca50d4SJan Kara 		     ext4_mb_choose_next_group(ac, &new_cr, &group, ngroups)) {
28444fca50d4SJan Kara 			int ret = 0;
2845196e402aSHarshad Shirwadkar 
28462ed5724dSTheodore Ts'o 			cond_resched();
2847196e402aSHarshad Shirwadkar 			if (new_cr != cr) {
2848196e402aSHarshad Shirwadkar 				cr = new_cr;
2849196e402aSHarshad Shirwadkar 				goto repeat;
2850196e402aSHarshad Shirwadkar 			}
2851c9de560dSAlex Tomas 
2852cfd73237SAlex Zhuravlev 			/*
2853cfd73237SAlex Zhuravlev 			 * Batch reads of the block allocation bitmaps
2854cfd73237SAlex Zhuravlev 			 * to get multiple READs in flight; limit
28554eea9fbeSKemeng Shi 			 * prefetching at inexpensive CR, otherwise mballoc
28564eea9fbeSKemeng Shi 			 * can spend a lot of time loading imperfect groups
2857cfd73237SAlex Zhuravlev 			 */
2858cfd73237SAlex Zhuravlev 			if ((prefetch_grp == group) &&
2859304749c0SOjaswin Mujoo 			    (ext4_mb_cr_expensive(cr) ||
2860cfd73237SAlex Zhuravlev 			     prefetch_ios < sbi->s_mb_prefetch_limit)) {
2861cfd73237SAlex Zhuravlev 				nr = sbi->s_mb_prefetch;
2862cfd73237SAlex Zhuravlev 				if (ext4_has_feature_flex_bg(sb)) {
286382ef1370SChunguang Xu 					nr = 1 << sbi->s_log_groups_per_flex;
286482ef1370SChunguang Xu 					nr -= group & (nr - 1);
286582ef1370SChunguang Xu 					nr = min(nr, sbi->s_mb_prefetch);
2866cfd73237SAlex Zhuravlev 				}
2867cfd73237SAlex Zhuravlev 				prefetch_grp = ext4_mb_prefetch(sb, group,
2868cfd73237SAlex Zhuravlev 							nr, &prefetch_ios);
2869cfd73237SAlex Zhuravlev 			}
2870cfd73237SAlex Zhuravlev 
28718a57d9d6SCurt Wohlgemuth 			/* This now checks without needing the buddy page */
28728ef123feSRitesh Harjani 			ret = ext4_mb_good_group_nolock(ac, group, cr);
287342ac1848SLukas Czerner 			if (ret <= 0) {
287442ac1848SLukas Czerner 				if (!first_err)
287542ac1848SLukas Czerner 					first_err = ret;
2876c9de560dSAlex Tomas 				continue;
287742ac1848SLukas Czerner 			}
2878c9de560dSAlex Tomas 
2879c9de560dSAlex Tomas 			err = ext4_mb_load_buddy(sb, group, &e4b);
2880c9de560dSAlex Tomas 			if (err)
2881c9de560dSAlex Tomas 				goto out;
2882c9de560dSAlex Tomas 
2883c9de560dSAlex Tomas 			ext4_lock_group(sb, group);
28848a57d9d6SCurt Wohlgemuth 
28858a57d9d6SCurt Wohlgemuth 			/*
28868a57d9d6SCurt Wohlgemuth 			 * We need to check again after locking the
28878a57d9d6SCurt Wohlgemuth 			 * block group
28888a57d9d6SCurt Wohlgemuth 			 */
288942ac1848SLukas Czerner 			ret = ext4_mb_good_group(ac, group, cr);
28908ef123feSRitesh Harjani 			if (ret == 0) {
2891c9de560dSAlex Tomas 				ext4_unlock_group(sb, group);
2892e39e07fdSJing Zhang 				ext4_mb_unload_buddy(&e4b);
2893c9de560dSAlex Tomas 				continue;
2894c9de560dSAlex Tomas 			}
2895c9de560dSAlex Tomas 
2896c9de560dSAlex Tomas 			ac->ac_groups_scanned++;
2897f52f3d2bSOjaswin Mujoo 			if (cr == CR_POWER2_ALIGNED)
2898c9de560dSAlex Tomas 				ext4_mb_simple_scan_group(ac, &e4b);
2899f52f3d2bSOjaswin Mujoo 			else if ((cr == CR_GOAL_LEN_FAST ||
2900f52f3d2bSOjaswin Mujoo 				 cr == CR_BEST_AVAIL_LEN) &&
2901f52f3d2bSOjaswin Mujoo 				 sbi->s_stripe &&
2902c3defd99SKemeng Shi 				 !(ac->ac_g_ex.fe_len %
2903c3defd99SKemeng Shi 				 EXT4_B2C(sbi, sbi->s_stripe)))
2904c9de560dSAlex Tomas 				ext4_mb_scan_aligned(ac, &e4b);
2905c9de560dSAlex Tomas 			else
2906c9de560dSAlex Tomas 				ext4_mb_complex_scan_group(ac, &e4b);
2907c9de560dSAlex Tomas 
2908c9de560dSAlex Tomas 			ext4_unlock_group(sb, group);
2909e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
2910c9de560dSAlex Tomas 
2911c9de560dSAlex Tomas 			if (ac->ac_status != AC_STATUS_CONTINUE)
2912c9de560dSAlex Tomas 				break;
2913c9de560dSAlex Tomas 		}
2914a6c75eafSHarshad Shirwadkar 		/* Processed all groups and haven't found blocks */
2915a6c75eafSHarshad Shirwadkar 		if (sbi->s_mb_stats && i == ngroups)
2916a6c75eafSHarshad Shirwadkar 			atomic64_inc(&sbi->s_bal_cX_failed[cr]);
29177e170922SOjaswin Mujoo 
2918f52f3d2bSOjaswin Mujoo 		if (i == ngroups && ac->ac_criteria == CR_BEST_AVAIL_LEN)
29197e170922SOjaswin Mujoo 			/* Reset goal length to original goal length before
2920f52f3d2bSOjaswin Mujoo 			 * falling into CR_GOAL_LEN_SLOW */
29217e170922SOjaswin Mujoo 			ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
2922c9de560dSAlex Tomas 	}
2923c9de560dSAlex Tomas 
2924c9de560dSAlex Tomas 	if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2925c9de560dSAlex Tomas 	    !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2926c9de560dSAlex Tomas 		/*
2927c9de560dSAlex Tomas 		 * We've been searching too long. Let's try to allocate
2928c9de560dSAlex Tomas 		 * the best chunk we've found so far
2929c9de560dSAlex Tomas 		 */
2930c9de560dSAlex Tomas 		ext4_mb_try_best_found(ac, &e4b);
2931c9de560dSAlex Tomas 		if (ac->ac_status != AC_STATUS_FOUND) {
2932c9de560dSAlex Tomas 			/*
2933c9de560dSAlex Tomas 			 * Someone more lucky has already allocated it.
2934c9de560dSAlex Tomas 			 * The only thing we can do is just take first
2935c9de560dSAlex Tomas 			 * found block(s)
2936c9de560dSAlex Tomas 			 */
293766d5e027Sbrookxu 			lost = atomic_inc_return(&sbi->s_mb_lost_chunks);
293866d5e027Sbrookxu 			mb_debug(sb, "lost chunk, group: %u, start: %d, len: %d, lost: %d\n",
2939c55ee7d2Sbrookxu 				 ac->ac_b_ex.fe_group, ac->ac_b_ex.fe_start,
2940c55ee7d2Sbrookxu 				 ac->ac_b_ex.fe_len, lost);
2941c55ee7d2Sbrookxu 
2942c9de560dSAlex Tomas 			ac->ac_b_ex.fe_group = 0;
2943c9de560dSAlex Tomas 			ac->ac_b_ex.fe_start = 0;
2944c9de560dSAlex Tomas 			ac->ac_b_ex.fe_len = 0;
2945c9de560dSAlex Tomas 			ac->ac_status = AC_STATUS_CONTINUE;
2946c9de560dSAlex Tomas 			ac->ac_flags |= EXT4_MB_HINT_FIRST;
2947f52f3d2bSOjaswin Mujoo 			cr = CR_ANY_FREE;
2948c9de560dSAlex Tomas 			goto repeat;
2949c9de560dSAlex Tomas 		}
2950c9de560dSAlex Tomas 	}
2951a6c75eafSHarshad Shirwadkar 
2952a6c75eafSHarshad Shirwadkar 	if (sbi->s_mb_stats && ac->ac_status == AC_STATUS_FOUND)
2953a6c75eafSHarshad Shirwadkar 		atomic64_inc(&sbi->s_bal_cX_hits[ac->ac_criteria]);
2954c9de560dSAlex Tomas out:
295542ac1848SLukas Czerner 	if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
295642ac1848SLukas Czerner 		err = first_err;
2957bbc4ec77SRitesh Harjani 
2958d3df1453SRitesh Harjani 	mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
2959bbc4ec77SRitesh Harjani 		 ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
2960bbc4ec77SRitesh Harjani 		 ac->ac_flags, cr, err);
2961cfd73237SAlex Zhuravlev 
2962cfd73237SAlex Zhuravlev 	if (nr)
2963cfd73237SAlex Zhuravlev 		ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
2964cfd73237SAlex Zhuravlev 
2965c9de560dSAlex Tomas 	return err;
2966c9de560dSAlex Tomas }
2967c9de560dSAlex Tomas 
2968c9de560dSAlex Tomas static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2969c9de560dSAlex Tomas {
2970359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
2971c9de560dSAlex Tomas 	ext4_group_t group;
2972c9de560dSAlex Tomas 
29738df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2974c9de560dSAlex Tomas 		return NULL;
2975c9de560dSAlex Tomas 	group = *pos + 1;
2976a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
2977c9de560dSAlex Tomas }
2978c9de560dSAlex Tomas 
2979c9de560dSAlex Tomas static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2980c9de560dSAlex Tomas {
2981359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
2982c9de560dSAlex Tomas 	ext4_group_t group;
2983c9de560dSAlex Tomas 
2984c9de560dSAlex Tomas 	++*pos;
29858df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2986c9de560dSAlex Tomas 		return NULL;
2987c9de560dSAlex Tomas 	group = *pos + 1;
2988a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
2989c9de560dSAlex Tomas }
2990c9de560dSAlex Tomas 
2991c9de560dSAlex Tomas static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2992c9de560dSAlex Tomas {
2993359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
2994a9df9a49STheodore Ts'o 	ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2995c9de560dSAlex Tomas 	int i;
29961c8457caSAditya Kali 	int err, buddy_loaded = 0;
2997c9de560dSAlex Tomas 	struct ext4_buddy e4b;
29981c8457caSAditya Kali 	struct ext4_group_info *grinfo;
29992df2c340SArnd Bergmann 	unsigned char blocksize_bits = min_t(unsigned char,
30002df2c340SArnd Bergmann 					     sb->s_blocksize_bits,
30012df2c340SArnd Bergmann 					     EXT4_MAX_BLOCK_LOG_SIZE);
3002c9de560dSAlex Tomas 	struct sg {
3003c9de560dSAlex Tomas 		struct ext4_group_info info;
3004b80b32b6STheodore Ts'o 		ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
3005c9de560dSAlex Tomas 	} sg;
3006c9de560dSAlex Tomas 
3007c9de560dSAlex Tomas 	group--;
3008c9de560dSAlex Tomas 	if (group == 0)
300997b4af2fSRasmus Villemoes 		seq_puts(seq, "#group: free  frags first ["
301097b4af2fSRasmus Villemoes 			      " 2^0   2^1   2^2   2^3   2^4   2^5   2^6  "
3011802cf1f9SHuaitong Han 			      " 2^7   2^8   2^9   2^10  2^11  2^12  2^13  ]\n");
3012c9de560dSAlex Tomas 
3013b80b32b6STheodore Ts'o 	i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
3014b80b32b6STheodore Ts'o 		sizeof(struct ext4_group_info);
3015b80b32b6STheodore Ts'o 
30161c8457caSAditya Kali 	grinfo = ext4_get_group_info(sb, group);
30175354b2afSTheodore Ts'o 	if (!grinfo)
30185354b2afSTheodore Ts'o 		return 0;
30191c8457caSAditya Kali 	/* Load the group info in memory only if not already loaded. */
30201c8457caSAditya Kali 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
3021c9de560dSAlex Tomas 		err = ext4_mb_load_buddy(sb, group, &e4b);
3022c9de560dSAlex Tomas 		if (err) {
3023a9df9a49STheodore Ts'o 			seq_printf(seq, "#%-5u: I/O error\n", group);
3024c9de560dSAlex Tomas 			return 0;
3025c9de560dSAlex Tomas 		}
30261c8457caSAditya Kali 		buddy_loaded = 1;
30271c8457caSAditya Kali 	}
30281c8457caSAditya Kali 
30295354b2afSTheodore Ts'o 	memcpy(&sg, grinfo, i);
30301c8457caSAditya Kali 
30311c8457caSAditya Kali 	if (buddy_loaded)
3032e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
3033c9de560dSAlex Tomas 
3034a9df9a49STheodore Ts'o 	seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
3035c9de560dSAlex Tomas 			sg.info.bb_fragments, sg.info.bb_first_free);
3036c9de560dSAlex Tomas 	for (i = 0; i <= 13; i++)
30372df2c340SArnd Bergmann 		seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
3038c9de560dSAlex Tomas 				sg.info.bb_counters[i] : 0);
3039e0d438c7SXu Wang 	seq_puts(seq, " ]\n");
3040c9de560dSAlex Tomas 
3041c9de560dSAlex Tomas 	return 0;
3042c9de560dSAlex Tomas }
3043c9de560dSAlex Tomas 
3044c9de560dSAlex Tomas static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
3045c9de560dSAlex Tomas {
3046c9de560dSAlex Tomas }
3047c9de560dSAlex Tomas 
3048247dbed8SChristoph Hellwig const struct seq_operations ext4_mb_seq_groups_ops = {
3049c9de560dSAlex Tomas 	.start  = ext4_mb_seq_groups_start,
3050c9de560dSAlex Tomas 	.next   = ext4_mb_seq_groups_next,
3051c9de560dSAlex Tomas 	.stop   = ext4_mb_seq_groups_stop,
3052c9de560dSAlex Tomas 	.show   = ext4_mb_seq_groups_show,
3053c9de560dSAlex Tomas };
3054c9de560dSAlex Tomas 
3055a6c75eafSHarshad Shirwadkar int ext4_seq_mb_stats_show(struct seq_file *seq, void *offset)
3056a6c75eafSHarshad Shirwadkar {
3057c30365b9SYu Zhe 	struct super_block *sb = seq->private;
3058a6c75eafSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3059a6c75eafSHarshad Shirwadkar 
3060a6c75eafSHarshad Shirwadkar 	seq_puts(seq, "mballoc:\n");
3061a6c75eafSHarshad Shirwadkar 	if (!sbi->s_mb_stats) {
3062a6c75eafSHarshad Shirwadkar 		seq_puts(seq, "\tmb stats collection turned off.\n");
3063f52f3d2bSOjaswin Mujoo 		seq_puts(
3064f52f3d2bSOjaswin Mujoo 			seq,
3065f52f3d2bSOjaswin Mujoo 			"\tTo enable, please write \"1\" to sysfs file mb_stats.\n");
3066a6c75eafSHarshad Shirwadkar 		return 0;
3067a6c75eafSHarshad Shirwadkar 	}
3068a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\treqs: %u\n", atomic_read(&sbi->s_bal_reqs));
3069a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tsuccess: %u\n", atomic_read(&sbi->s_bal_success));
3070a6c75eafSHarshad Shirwadkar 
3071f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\tgroups_scanned: %u\n",
3072f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_groups_scanned));
3073a6c75eafSHarshad Shirwadkar 
3074f52f3d2bSOjaswin Mujoo 	/* CR_POWER2_ALIGNED stats */
3075f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_p2_aligned_stats:\n");
3076f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3077f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_POWER2_ALIGNED]));
3078f52f3d2bSOjaswin Mujoo 	seq_printf(
3079f52f3d2bSOjaswin Mujoo 		seq, "\t\tgroups_considered: %llu\n",
3080f52f3d2bSOjaswin Mujoo 		atomic64_read(
3081f52f3d2bSOjaswin Mujoo 			&sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]));
3082f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3083f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_POWER2_ALIGNED]));
3084a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3085f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_POWER2_ALIGNED]));
3086196e402aSHarshad Shirwadkar 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3087f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_p2_aligned_bad_suggestions));
3088a6c75eafSHarshad Shirwadkar 
3089f52f3d2bSOjaswin Mujoo 	/* CR_GOAL_LEN_FAST stats */
3090f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_goal_fast_stats:\n");
3091f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3092f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_FAST]));
3093a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tgroups_considered: %llu\n",
3094f52f3d2bSOjaswin Mujoo 		   atomic64_read(
3095f52f3d2bSOjaswin Mujoo 			   &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_FAST]));
3096f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3097f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_FAST]));
3098a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3099f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_FAST]));
3100196e402aSHarshad Shirwadkar 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3101f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_goal_fast_bad_suggestions));
3102a6c75eafSHarshad Shirwadkar 
3103f52f3d2bSOjaswin Mujoo 	/* CR_BEST_AVAIL_LEN stats */
3104f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_best_avail_stats:\n");
3105f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3106f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_BEST_AVAIL_LEN]));
3107f52f3d2bSOjaswin Mujoo 	seq_printf(
3108f52f3d2bSOjaswin Mujoo 		seq, "\t\tgroups_considered: %llu\n",
3109f52f3d2bSOjaswin Mujoo 		atomic64_read(
3110f52f3d2bSOjaswin Mujoo 			&sbi->s_bal_cX_groups_considered[CR_BEST_AVAIL_LEN]));
3111f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3112f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_BEST_AVAIL_LEN]));
31137e170922SOjaswin Mujoo 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3114f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_BEST_AVAIL_LEN]));
31157e170922SOjaswin Mujoo 	seq_printf(seq, "\t\tbad_suggestions: %u\n",
3116f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_best_avail_bad_suggestions));
31177e170922SOjaswin Mujoo 
3118f52f3d2bSOjaswin Mujoo 	/* CR_GOAL_LEN_SLOW stats */
3119f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_goal_slow_stats:\n");
3120f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3121f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_SLOW]));
3122a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tgroups_considered: %llu\n",
3123f52f3d2bSOjaswin Mujoo 		   atomic64_read(
3124f52f3d2bSOjaswin Mujoo 			   &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_SLOW]));
3125f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3126f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_SLOW]));
3127a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3128f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_SLOW]));
3129a6c75eafSHarshad Shirwadkar 
3130f52f3d2bSOjaswin Mujoo 	/* CR_ANY_FREE stats */
3131f52f3d2bSOjaswin Mujoo 	seq_puts(seq, "\tcr_any_free_stats:\n");
3132f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\thits: %llu\n",
3133f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_hits[CR_ANY_FREE]));
3134f52f3d2bSOjaswin Mujoo 	seq_printf(
3135f52f3d2bSOjaswin Mujoo 		seq, "\t\tgroups_considered: %llu\n",
3136f52f3d2bSOjaswin Mujoo 		atomic64_read(&sbi->s_bal_cX_groups_considered[CR_ANY_FREE]));
3137f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\textents_scanned: %u\n",
3138f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_cX_ex_scanned[CR_ANY_FREE]));
3139a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tuseless_loops: %llu\n",
3140f52f3d2bSOjaswin Mujoo 		   atomic64_read(&sbi->s_bal_cX_failed[CR_ANY_FREE]));
3141f52f3d2bSOjaswin Mujoo 
3142f52f3d2bSOjaswin Mujoo 	/* Aggregates */
3143f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\textents_scanned: %u\n",
3144f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_ex_scanned));
3145a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tgoal_hits: %u\n", atomic_read(&sbi->s_bal_goals));
3146f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\t\tlen_goal_hits: %u\n",
3147f52f3d2bSOjaswin Mujoo 		   atomic_read(&sbi->s_bal_len_goals));
3148a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\t2^n_hits: %u\n", atomic_read(&sbi->s_bal_2orders));
3149a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tbreaks: %u\n", atomic_read(&sbi->s_bal_breaks));
3150a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\t\tlost: %u\n", atomic_read(&sbi->s_mb_lost_chunks));
3151a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tbuddies_generated: %u/%u\n",
3152a6c75eafSHarshad Shirwadkar 		   atomic_read(&sbi->s_mb_buddies_generated),
3153a6c75eafSHarshad Shirwadkar 		   ext4_get_groups_count(sb));
3154a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tbuddies_time_used: %llu\n",
3155a6c75eafSHarshad Shirwadkar 		   atomic64_read(&sbi->s_mb_generation_time));
3156a6c75eafSHarshad Shirwadkar 	seq_printf(seq, "\tpreallocated: %u\n",
3157a6c75eafSHarshad Shirwadkar 		   atomic_read(&sbi->s_mb_preallocated));
3158f52f3d2bSOjaswin Mujoo 	seq_printf(seq, "\tdiscarded: %u\n", atomic_read(&sbi->s_mb_discarded));
3159a6c75eafSHarshad Shirwadkar 	return 0;
3160a6c75eafSHarshad Shirwadkar }
3161a6c75eafSHarshad Shirwadkar 
3162f68f4063SHarshad Shirwadkar static void *ext4_mb_seq_structs_summary_start(struct seq_file *seq, loff_t *pos)
3163a5fda113STheodore Ts'o __acquires(&EXT4_SB(sb)->s_mb_rb_lock)
3164f68f4063SHarshad Shirwadkar {
3165359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3166f68f4063SHarshad Shirwadkar 	unsigned long position;
3167f68f4063SHarshad Shirwadkar 
316883e80a6eSJan Kara 	if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3169f68f4063SHarshad Shirwadkar 		return NULL;
3170f68f4063SHarshad Shirwadkar 	position = *pos + 1;
3171f68f4063SHarshad Shirwadkar 	return (void *) ((unsigned long) position);
3172f68f4063SHarshad Shirwadkar }
3173f68f4063SHarshad Shirwadkar 
3174f68f4063SHarshad Shirwadkar static void *ext4_mb_seq_structs_summary_next(struct seq_file *seq, void *v, loff_t *pos)
3175f68f4063SHarshad Shirwadkar {
3176359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3177f68f4063SHarshad Shirwadkar 	unsigned long position;
3178f68f4063SHarshad Shirwadkar 
3179f68f4063SHarshad Shirwadkar 	++*pos;
318083e80a6eSJan Kara 	if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3181f68f4063SHarshad Shirwadkar 		return NULL;
3182f68f4063SHarshad Shirwadkar 	position = *pos + 1;
3183f68f4063SHarshad Shirwadkar 	return (void *) ((unsigned long) position);
3184f68f4063SHarshad Shirwadkar }
3185f68f4063SHarshad Shirwadkar 
3186f68f4063SHarshad Shirwadkar static int ext4_mb_seq_structs_summary_show(struct seq_file *seq, void *v)
3187f68f4063SHarshad Shirwadkar {
3188359745d7SMuchun Song 	struct super_block *sb = pde_data(file_inode(seq->file));
3189f68f4063SHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3190f68f4063SHarshad Shirwadkar 	unsigned long position = ((unsigned long) v);
3191f68f4063SHarshad Shirwadkar 	struct ext4_group_info *grp;
319283e80a6eSJan Kara 	unsigned int count;
3193f68f4063SHarshad Shirwadkar 
3194f68f4063SHarshad Shirwadkar 	position--;
3195f68f4063SHarshad Shirwadkar 	if (position >= MB_NUM_ORDERS(sb)) {
319683e80a6eSJan Kara 		position -= MB_NUM_ORDERS(sb);
319783e80a6eSJan Kara 		if (position == 0)
319883e80a6eSJan Kara 			seq_puts(seq, "avg_fragment_size_lists:\n");
3199f68f4063SHarshad Shirwadkar 
320083e80a6eSJan Kara 		count = 0;
320183e80a6eSJan Kara 		read_lock(&sbi->s_mb_avg_fragment_size_locks[position]);
320283e80a6eSJan Kara 		list_for_each_entry(grp, &sbi->s_mb_avg_fragment_size[position],
320383e80a6eSJan Kara 				    bb_avg_fragment_size_node)
320483e80a6eSJan Kara 			count++;
320583e80a6eSJan Kara 		read_unlock(&sbi->s_mb_avg_fragment_size_locks[position]);
320683e80a6eSJan Kara 		seq_printf(seq, "\tlist_order_%u_groups: %u\n",
320783e80a6eSJan Kara 					(unsigned int)position, count);
3208f68f4063SHarshad Shirwadkar 		return 0;
3209f68f4063SHarshad Shirwadkar 	}
3210f68f4063SHarshad Shirwadkar 
3211f68f4063SHarshad Shirwadkar 	if (position == 0) {
3212f68f4063SHarshad Shirwadkar 		seq_printf(seq, "optimize_scan: %d\n",
3213f68f4063SHarshad Shirwadkar 			   test_opt2(sb, MB_OPTIMIZE_SCAN) ? 1 : 0);
3214f68f4063SHarshad Shirwadkar 		seq_puts(seq, "max_free_order_lists:\n");
3215f68f4063SHarshad Shirwadkar 	}
3216f68f4063SHarshad Shirwadkar 	count = 0;
321783e80a6eSJan Kara 	read_lock(&sbi->s_mb_largest_free_orders_locks[position]);
3218f68f4063SHarshad Shirwadkar 	list_for_each_entry(grp, &sbi->s_mb_largest_free_orders[position],
3219f68f4063SHarshad Shirwadkar 			    bb_largest_free_order_node)
3220f68f4063SHarshad Shirwadkar 		count++;
322183e80a6eSJan Kara 	read_unlock(&sbi->s_mb_largest_free_orders_locks[position]);
3222f68f4063SHarshad Shirwadkar 	seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3223f68f4063SHarshad Shirwadkar 		   (unsigned int)position, count);
3224f68f4063SHarshad Shirwadkar 
3225f68f4063SHarshad Shirwadkar 	return 0;
3226f68f4063SHarshad Shirwadkar }
3227f68f4063SHarshad Shirwadkar 
3228f68f4063SHarshad Shirwadkar static void ext4_mb_seq_structs_summary_stop(struct seq_file *seq, void *v)
3229f68f4063SHarshad Shirwadkar {
3230f68f4063SHarshad Shirwadkar }
3231f68f4063SHarshad Shirwadkar 
3232f68f4063SHarshad Shirwadkar const struct seq_operations ext4_mb_seq_structs_summary_ops = {
3233f68f4063SHarshad Shirwadkar 	.start  = ext4_mb_seq_structs_summary_start,
3234f68f4063SHarshad Shirwadkar 	.next   = ext4_mb_seq_structs_summary_next,
3235f68f4063SHarshad Shirwadkar 	.stop   = ext4_mb_seq_structs_summary_stop,
3236f68f4063SHarshad Shirwadkar 	.show   = ext4_mb_seq_structs_summary_show,
3237f68f4063SHarshad Shirwadkar };
3238f68f4063SHarshad Shirwadkar 
3239fb1813f4SCurt Wohlgemuth static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
3240fb1813f4SCurt Wohlgemuth {
3241fb1813f4SCurt Wohlgemuth 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3242fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
3243fb1813f4SCurt Wohlgemuth 
3244fb1813f4SCurt Wohlgemuth 	BUG_ON(!cachep);
3245fb1813f4SCurt Wohlgemuth 	return cachep;
3246fb1813f4SCurt Wohlgemuth }
32475f21b0e6SFrederic Bohe 
324828623c2fSTheodore Ts'o /*
324928623c2fSTheodore Ts'o  * Allocate the top-level s_group_info array for the specified number
325028623c2fSTheodore Ts'o  * of groups
325128623c2fSTheodore Ts'o  */
325228623c2fSTheodore Ts'o int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
325328623c2fSTheodore Ts'o {
325428623c2fSTheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(sb);
325528623c2fSTheodore Ts'o 	unsigned size;
3256df3da4eaSSuraj Jitindar Singh 	struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
325728623c2fSTheodore Ts'o 
325828623c2fSTheodore Ts'o 	size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
325928623c2fSTheodore Ts'o 		EXT4_DESC_PER_BLOCK_BITS(sb);
326028623c2fSTheodore Ts'o 	if (size <= sbi->s_group_info_size)
326128623c2fSTheodore Ts'o 		return 0;
326228623c2fSTheodore Ts'o 
326328623c2fSTheodore Ts'o 	size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
3264a7c3e901SMichal Hocko 	new_groupinfo = kvzalloc(size, GFP_KERNEL);
326528623c2fSTheodore Ts'o 	if (!new_groupinfo) {
326628623c2fSTheodore Ts'o 		ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
326728623c2fSTheodore Ts'o 		return -ENOMEM;
326828623c2fSTheodore Ts'o 	}
3269df3da4eaSSuraj Jitindar Singh 	rcu_read_lock();
3270df3da4eaSSuraj Jitindar Singh 	old_groupinfo = rcu_dereference(sbi->s_group_info);
3271df3da4eaSSuraj Jitindar Singh 	if (old_groupinfo)
3272df3da4eaSSuraj Jitindar Singh 		memcpy(new_groupinfo, old_groupinfo,
327328623c2fSTheodore Ts'o 		       sbi->s_group_info_size * sizeof(*sbi->s_group_info));
3274df3da4eaSSuraj Jitindar Singh 	rcu_read_unlock();
3275df3da4eaSSuraj Jitindar Singh 	rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
327628623c2fSTheodore Ts'o 	sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
3277df3da4eaSSuraj Jitindar Singh 	if (old_groupinfo)
3278df3da4eaSSuraj Jitindar Singh 		ext4_kvfree_array_rcu(old_groupinfo);
327928623c2fSTheodore Ts'o 	ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
328028623c2fSTheodore Ts'o 		   sbi->s_group_info_size);
328128623c2fSTheodore Ts'o 	return 0;
328228623c2fSTheodore Ts'o }
328328623c2fSTheodore Ts'o 
32845f21b0e6SFrederic Bohe /* Create and initialize ext4_group_info data for the given group. */
3285920313a7SAneesh Kumar K.V int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
32865f21b0e6SFrederic Bohe 			  struct ext4_group_desc *desc)
32875f21b0e6SFrederic Bohe {
3288fb1813f4SCurt Wohlgemuth 	int i;
32895f21b0e6SFrederic Bohe 	int metalen = 0;
3290df3da4eaSSuraj Jitindar Singh 	int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
32915f21b0e6SFrederic Bohe 	struct ext4_sb_info *sbi = EXT4_SB(sb);
32925f21b0e6SFrederic Bohe 	struct ext4_group_info **meta_group_info;
3293fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
32945f21b0e6SFrederic Bohe 
32955f21b0e6SFrederic Bohe 	/*
32965f21b0e6SFrederic Bohe 	 * First check if this group is the first of a reserved block.
32975f21b0e6SFrederic Bohe 	 * If it's true, we have to allocate a new table of pointers
32985f21b0e6SFrederic Bohe 	 * to ext4_group_info structures
32995f21b0e6SFrederic Bohe 	 */
33005f21b0e6SFrederic Bohe 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
33015f21b0e6SFrederic Bohe 		metalen = sizeof(*meta_group_info) <<
33025f21b0e6SFrederic Bohe 			EXT4_DESC_PER_BLOCK_BITS(sb);
33034fdb5543SDmitry Monakhov 		meta_group_info = kmalloc(metalen, GFP_NOFS);
33045f21b0e6SFrederic Bohe 		if (meta_group_info == NULL) {
33057f6a11e7SJoe Perches 			ext4_msg(sb, KERN_ERR, "can't allocate mem "
33069d8b9ec4STheodore Ts'o 				 "for a buddy group");
3307df119095SKemeng Shi 			return -ENOMEM;
33085f21b0e6SFrederic Bohe 		}
3309df3da4eaSSuraj Jitindar Singh 		rcu_read_lock();
3310df3da4eaSSuraj Jitindar Singh 		rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
3311df3da4eaSSuraj Jitindar Singh 		rcu_read_unlock();
33125f21b0e6SFrederic Bohe 	}
33135f21b0e6SFrederic Bohe 
3314df3da4eaSSuraj Jitindar Singh 	meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
33155f21b0e6SFrederic Bohe 	i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
33165f21b0e6SFrederic Bohe 
33174fdb5543SDmitry Monakhov 	meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
33185f21b0e6SFrederic Bohe 	if (meta_group_info[i] == NULL) {
33197f6a11e7SJoe Perches 		ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
33205f21b0e6SFrederic Bohe 		goto exit_group_info;
33215f21b0e6SFrederic Bohe 	}
33225f21b0e6SFrederic Bohe 	set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
33235f21b0e6SFrederic Bohe 		&(meta_group_info[i]->bb_state));
33245f21b0e6SFrederic Bohe 
33255f21b0e6SFrederic Bohe 	/*
33265f21b0e6SFrederic Bohe 	 * initialize bb_free to be able to skip
33275f21b0e6SFrederic Bohe 	 * empty groups without initialization
33285f21b0e6SFrederic Bohe 	 */
33298844618dSTheodore Ts'o 	if (ext4_has_group_desc_csum(sb) &&
33308844618dSTheodore Ts'o 	    (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
33315f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
3332cff1dfd7STheodore Ts'o 			ext4_free_clusters_after_init(sb, group, desc);
33335f21b0e6SFrederic Bohe 	} else {
33345f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
3335021b65bbSTheodore Ts'o 			ext4_free_group_clusters(sb, desc);
33365f21b0e6SFrederic Bohe 	}
33375f21b0e6SFrederic Bohe 
33385f21b0e6SFrederic Bohe 	INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
3339920313a7SAneesh Kumar K.V 	init_rwsem(&meta_group_info[i]->alloc_sem);
334064e290ecSVenkatesh Pallipadi 	meta_group_info[i]->bb_free_root = RB_ROOT;
3341196e402aSHarshad Shirwadkar 	INIT_LIST_HEAD(&meta_group_info[i]->bb_largest_free_order_node);
334283e80a6eSJan Kara 	INIT_LIST_HEAD(&meta_group_info[i]->bb_avg_fragment_size_node);
33438a57d9d6SCurt Wohlgemuth 	meta_group_info[i]->bb_largest_free_order = -1;  /* uninit */
334483e80a6eSJan Kara 	meta_group_info[i]->bb_avg_fragment_size_order = -1;  /* uninit */
3345196e402aSHarshad Shirwadkar 	meta_group_info[i]->bb_group = group;
33465f21b0e6SFrederic Bohe 
3347a3450215SRitesh Harjani 	mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
33485f21b0e6SFrederic Bohe 	return 0;
33495f21b0e6SFrederic Bohe 
33505f21b0e6SFrederic Bohe exit_group_info:
33515f21b0e6SFrederic Bohe 	/* If a meta_group_info table has been allocated, release it now */
3352caaf7a29STao Ma 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3353df3da4eaSSuraj Jitindar Singh 		struct ext4_group_info ***group_info;
3354df3da4eaSSuraj Jitindar Singh 
3355df3da4eaSSuraj Jitindar Singh 		rcu_read_lock();
3356df3da4eaSSuraj Jitindar Singh 		group_info = rcu_dereference(sbi->s_group_info);
3357df3da4eaSSuraj Jitindar Singh 		kfree(group_info[idx]);
3358df3da4eaSSuraj Jitindar Singh 		group_info[idx] = NULL;
3359df3da4eaSSuraj Jitindar Singh 		rcu_read_unlock();
3360caaf7a29STao Ma 	}
33615f21b0e6SFrederic Bohe 	return -ENOMEM;
33625f21b0e6SFrederic Bohe } /* ext4_mb_add_groupinfo */
33635f21b0e6SFrederic Bohe 
3364c9de560dSAlex Tomas static int ext4_mb_init_backend(struct super_block *sb)
3365c9de560dSAlex Tomas {
33668df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
3367c9de560dSAlex Tomas 	ext4_group_t i;
3368c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
336928623c2fSTheodore Ts'o 	int err;
33705f21b0e6SFrederic Bohe 	struct ext4_group_desc *desc;
3371df3da4eaSSuraj Jitindar Singh 	struct ext4_group_info ***group_info;
3372fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep;
3373c9de560dSAlex Tomas 
337428623c2fSTheodore Ts'o 	err = ext4_mb_alloc_groupinfo(sb, ngroups);
337528623c2fSTheodore Ts'o 	if (err)
337628623c2fSTheodore Ts'o 		return err;
33775f21b0e6SFrederic Bohe 
3378c9de560dSAlex Tomas 	sbi->s_buddy_cache = new_inode(sb);
3379c9de560dSAlex Tomas 	if (sbi->s_buddy_cache == NULL) {
33809d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_ERR, "can't get new inode");
3381c9de560dSAlex Tomas 		goto err_freesgi;
3382c9de560dSAlex Tomas 	}
338348e6061bSYu Jian 	/* To avoid potentially colliding with an valid on-disk inode number,
338448e6061bSYu Jian 	 * use EXT4_BAD_INO for the buddy cache inode number.  This inode is
338548e6061bSYu Jian 	 * not in the inode hash, so it should never be found by iget(), but
338648e6061bSYu Jian 	 * this will avoid confusion if it ever shows up during debugging. */
338748e6061bSYu Jian 	sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
3388c9de560dSAlex Tomas 	EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
33898df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
33904b99faa2SKhazhismel Kumykov 		cond_resched();
3391c9de560dSAlex Tomas 		desc = ext4_get_group_desc(sb, i, NULL);
3392c9de560dSAlex Tomas 		if (desc == NULL) {
33939d8b9ec4STheodore Ts'o 			ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
3394c9de560dSAlex Tomas 			goto err_freebuddy;
3395c9de560dSAlex Tomas 		}
33965f21b0e6SFrederic Bohe 		if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
33975f21b0e6SFrederic Bohe 			goto err_freebuddy;
3398c9de560dSAlex Tomas 	}
3399c9de560dSAlex Tomas 
3400cfd73237SAlex Zhuravlev 	if (ext4_has_feature_flex_bg(sb)) {
3401f91436d5SSabyrzhan Tasbolatov 		/* a single flex group is supposed to be read by a single IO.
3402f91436d5SSabyrzhan Tasbolatov 		 * 2 ^ s_log_groups_per_flex != UINT_MAX as s_mb_prefetch is
3403f91436d5SSabyrzhan Tasbolatov 		 * unsigned integer, so the maximum shift is 32.
3404f91436d5SSabyrzhan Tasbolatov 		 */
3405f91436d5SSabyrzhan Tasbolatov 		if (sbi->s_es->s_log_groups_per_flex >= 32) {
3406f91436d5SSabyrzhan Tasbolatov 			ext4_msg(sb, KERN_ERR, "too many log groups per flexible block group");
3407a8867f4eSPhillip Potter 			goto err_freebuddy;
3408f91436d5SSabyrzhan Tasbolatov 		}
3409f91436d5SSabyrzhan Tasbolatov 		sbi->s_mb_prefetch = min_t(uint, 1 << sbi->s_es->s_log_groups_per_flex,
341082ef1370SChunguang Xu 			BLK_MAX_SEGMENT_SIZE >> (sb->s_blocksize_bits - 9));
3411cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
3412cfd73237SAlex Zhuravlev 	} else {
3413cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch = 32;
3414cfd73237SAlex Zhuravlev 	}
3415cfd73237SAlex Zhuravlev 	if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
3416cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch = ext4_get_groups_count(sb);
3417cfd73237SAlex Zhuravlev 	/* now many real IOs to prefetch within a single allocation at cr=0
3418cfd73237SAlex Zhuravlev 	 * given cr=0 is an CPU-related optimization we shouldn't try to
3419cfd73237SAlex Zhuravlev 	 * load too many groups, at some point we should start to use what
3420cfd73237SAlex Zhuravlev 	 * we've got in memory.
3421cfd73237SAlex Zhuravlev 	 * with an average random access time 5ms, it'd take a second to get
3422cfd73237SAlex Zhuravlev 	 * 200 groups (* N with flex_bg), so let's make this limit 4
3423cfd73237SAlex Zhuravlev 	 */
3424cfd73237SAlex Zhuravlev 	sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
3425cfd73237SAlex Zhuravlev 	if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
3426cfd73237SAlex Zhuravlev 		sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
3427cfd73237SAlex Zhuravlev 
3428c9de560dSAlex Tomas 	return 0;
3429c9de560dSAlex Tomas 
3430c9de560dSAlex Tomas err_freebuddy:
3431fb1813f4SCurt Wohlgemuth 	cachep = get_groupinfo_cache(sb->s_blocksize_bits);
34325354b2afSTheodore Ts'o 	while (i-- > 0) {
34335354b2afSTheodore Ts'o 		struct ext4_group_info *grp = ext4_get_group_info(sb, i);
34345354b2afSTheodore Ts'o 
34355354b2afSTheodore Ts'o 		if (grp)
34365354b2afSTheodore Ts'o 			kmem_cache_free(cachep, grp);
34375354b2afSTheodore Ts'o 	}
343828623c2fSTheodore Ts'o 	i = sbi->s_group_info_size;
3439df3da4eaSSuraj Jitindar Singh 	rcu_read_lock();
3440df3da4eaSSuraj Jitindar Singh 	group_info = rcu_dereference(sbi->s_group_info);
3441f1fa3342SRoel Kluin 	while (i-- > 0)
3442df3da4eaSSuraj Jitindar Singh 		kfree(group_info[i]);
3443df3da4eaSSuraj Jitindar Singh 	rcu_read_unlock();
3444c9de560dSAlex Tomas 	iput(sbi->s_buddy_cache);
3445c9de560dSAlex Tomas err_freesgi:
3446df3da4eaSSuraj Jitindar Singh 	rcu_read_lock();
3447df3da4eaSSuraj Jitindar Singh 	kvfree(rcu_dereference(sbi->s_group_info));
3448df3da4eaSSuraj Jitindar Singh 	rcu_read_unlock();
3449c9de560dSAlex Tomas 	return -ENOMEM;
3450c9de560dSAlex Tomas }
3451c9de560dSAlex Tomas 
34522892c15dSEric Sandeen static void ext4_groupinfo_destroy_slabs(void)
34532892c15dSEric Sandeen {
34542892c15dSEric Sandeen 	int i;
34552892c15dSEric Sandeen 
34562892c15dSEric Sandeen 	for (i = 0; i < NR_GRPINFO_CACHES; i++) {
34572892c15dSEric Sandeen 		kmem_cache_destroy(ext4_groupinfo_caches[i]);
34582892c15dSEric Sandeen 		ext4_groupinfo_caches[i] = NULL;
34592892c15dSEric Sandeen 	}
34602892c15dSEric Sandeen }
34612892c15dSEric Sandeen 
34622892c15dSEric Sandeen static int ext4_groupinfo_create_slab(size_t size)
34632892c15dSEric Sandeen {
34642892c15dSEric Sandeen 	static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
34652892c15dSEric Sandeen 	int slab_size;
34662892c15dSEric Sandeen 	int blocksize_bits = order_base_2(size);
34672892c15dSEric Sandeen 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
34682892c15dSEric Sandeen 	struct kmem_cache *cachep;
34692892c15dSEric Sandeen 
34702892c15dSEric Sandeen 	if (cache_index >= NR_GRPINFO_CACHES)
34712892c15dSEric Sandeen 		return -EINVAL;
34722892c15dSEric Sandeen 
34732892c15dSEric Sandeen 	if (unlikely(cache_index < 0))
34742892c15dSEric Sandeen 		cache_index = 0;
34752892c15dSEric Sandeen 
34762892c15dSEric Sandeen 	mutex_lock(&ext4_grpinfo_slab_create_mutex);
34772892c15dSEric Sandeen 	if (ext4_groupinfo_caches[cache_index]) {
34782892c15dSEric Sandeen 		mutex_unlock(&ext4_grpinfo_slab_create_mutex);
34792892c15dSEric Sandeen 		return 0;	/* Already created */
34802892c15dSEric Sandeen 	}
34812892c15dSEric Sandeen 
34822892c15dSEric Sandeen 	slab_size = offsetof(struct ext4_group_info,
34832892c15dSEric Sandeen 				bb_counters[blocksize_bits + 2]);
34842892c15dSEric Sandeen 
34852892c15dSEric Sandeen 	cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
34862892c15dSEric Sandeen 					slab_size, 0, SLAB_RECLAIM_ACCOUNT,
34872892c15dSEric Sandeen 					NULL);
34882892c15dSEric Sandeen 
3489823ba01fSTao Ma 	ext4_groupinfo_caches[cache_index] = cachep;
3490823ba01fSTao Ma 
34912892c15dSEric Sandeen 	mutex_unlock(&ext4_grpinfo_slab_create_mutex);
34922892c15dSEric Sandeen 	if (!cachep) {
34939d8b9ec4STheodore Ts'o 		printk(KERN_EMERG
34949d8b9ec4STheodore Ts'o 		       "EXT4-fs: no memory for groupinfo slab cache\n");
34952892c15dSEric Sandeen 		return -ENOMEM;
34962892c15dSEric Sandeen 	}
34972892c15dSEric Sandeen 
34982892c15dSEric Sandeen 	return 0;
34992892c15dSEric Sandeen }
35002892c15dSEric Sandeen 
350155cdd0afSWang Jianchao static void ext4_discard_work(struct work_struct *work)
350255cdd0afSWang Jianchao {
350355cdd0afSWang Jianchao 	struct ext4_sb_info *sbi = container_of(work,
350455cdd0afSWang Jianchao 			struct ext4_sb_info, s_discard_work);
350555cdd0afSWang Jianchao 	struct super_block *sb = sbi->s_sb;
350655cdd0afSWang Jianchao 	struct ext4_free_data *fd, *nfd;
350755cdd0afSWang Jianchao 	struct ext4_buddy e4b;
35080f6bc579SRuan Jinjie 	LIST_HEAD(discard_list);
350955cdd0afSWang Jianchao 	ext4_group_t grp, load_grp;
351055cdd0afSWang Jianchao 	int err = 0;
351155cdd0afSWang Jianchao 
351255cdd0afSWang Jianchao 	spin_lock(&sbi->s_md_lock);
351355cdd0afSWang Jianchao 	list_splice_init(&sbi->s_discard_list, &discard_list);
351455cdd0afSWang Jianchao 	spin_unlock(&sbi->s_md_lock);
351555cdd0afSWang Jianchao 
351655cdd0afSWang Jianchao 	load_grp = UINT_MAX;
351755cdd0afSWang Jianchao 	list_for_each_entry_safe(fd, nfd, &discard_list, efd_list) {
351855cdd0afSWang Jianchao 		/*
35195036ab8dSWang Jianchao 		 * If filesystem is umounting or no memory or suffering
35205036ab8dSWang Jianchao 		 * from no space, give up the discard
352155cdd0afSWang Jianchao 		 */
35225036ab8dSWang Jianchao 		if ((sb->s_flags & SB_ACTIVE) && !err &&
35235036ab8dSWang Jianchao 		    !atomic_read(&sbi->s_retry_alloc_pending)) {
352455cdd0afSWang Jianchao 			grp = fd->efd_group;
352555cdd0afSWang Jianchao 			if (grp != load_grp) {
352655cdd0afSWang Jianchao 				if (load_grp != UINT_MAX)
352755cdd0afSWang Jianchao 					ext4_mb_unload_buddy(&e4b);
352855cdd0afSWang Jianchao 
352955cdd0afSWang Jianchao 				err = ext4_mb_load_buddy(sb, grp, &e4b);
353055cdd0afSWang Jianchao 				if (err) {
353155cdd0afSWang Jianchao 					kmem_cache_free(ext4_free_data_cachep, fd);
353255cdd0afSWang Jianchao 					load_grp = UINT_MAX;
353355cdd0afSWang Jianchao 					continue;
353455cdd0afSWang Jianchao 				} else {
353555cdd0afSWang Jianchao 					load_grp = grp;
353655cdd0afSWang Jianchao 				}
353755cdd0afSWang Jianchao 			}
353855cdd0afSWang Jianchao 
353955cdd0afSWang Jianchao 			ext4_lock_group(sb, grp);
354055cdd0afSWang Jianchao 			ext4_try_to_trim_range(sb, &e4b, fd->efd_start_cluster,
354155cdd0afSWang Jianchao 						fd->efd_start_cluster + fd->efd_count - 1, 1);
354255cdd0afSWang Jianchao 			ext4_unlock_group(sb, grp);
354355cdd0afSWang Jianchao 		}
354455cdd0afSWang Jianchao 		kmem_cache_free(ext4_free_data_cachep, fd);
354555cdd0afSWang Jianchao 	}
354655cdd0afSWang Jianchao 
354755cdd0afSWang Jianchao 	if (load_grp != UINT_MAX)
354855cdd0afSWang Jianchao 		ext4_mb_unload_buddy(&e4b);
354955cdd0afSWang Jianchao }
355055cdd0afSWang Jianchao 
35519d99012fSAkira Fujita int ext4_mb_init(struct super_block *sb)
3552c9de560dSAlex Tomas {
3553c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
35546be2ded1SAneesh Kumar K.V 	unsigned i, j;
3555935244cdSNicolai Stange 	unsigned offset, offset_incr;
3556c9de560dSAlex Tomas 	unsigned max;
355774767c5aSShen Feng 	int ret;
3558c9de560dSAlex Tomas 
35594b68f6dfSHarshad Shirwadkar 	i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_offsets);
3560c9de560dSAlex Tomas 
3561c9de560dSAlex Tomas 	sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
3562c9de560dSAlex Tomas 	if (sbi->s_mb_offsets == NULL) {
3563fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
3564fb1813f4SCurt Wohlgemuth 		goto out;
3565c9de560dSAlex Tomas 	}
3566ff7ef329SYasunori Goto 
35674b68f6dfSHarshad Shirwadkar 	i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_maxs);
3568c9de560dSAlex Tomas 	sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
3569c9de560dSAlex Tomas 	if (sbi->s_mb_maxs == NULL) {
3570fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
3571fb1813f4SCurt Wohlgemuth 		goto out;
3572fb1813f4SCurt Wohlgemuth 	}
3573fb1813f4SCurt Wohlgemuth 
35742892c15dSEric Sandeen 	ret = ext4_groupinfo_create_slab(sb->s_blocksize);
35752892c15dSEric Sandeen 	if (ret < 0)
3576fb1813f4SCurt Wohlgemuth 		goto out;
3577c9de560dSAlex Tomas 
3578c9de560dSAlex Tomas 	/* order 0 is regular bitmap */
3579c9de560dSAlex Tomas 	sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
3580c9de560dSAlex Tomas 	sbi->s_mb_offsets[0] = 0;
3581c9de560dSAlex Tomas 
3582c9de560dSAlex Tomas 	i = 1;
3583c9de560dSAlex Tomas 	offset = 0;
3584935244cdSNicolai Stange 	offset_incr = 1 << (sb->s_blocksize_bits - 1);
3585c9de560dSAlex Tomas 	max = sb->s_blocksize << 2;
3586c9de560dSAlex Tomas 	do {
3587c9de560dSAlex Tomas 		sbi->s_mb_offsets[i] = offset;
3588c9de560dSAlex Tomas 		sbi->s_mb_maxs[i] = max;
3589935244cdSNicolai Stange 		offset += offset_incr;
3590935244cdSNicolai Stange 		offset_incr = offset_incr >> 1;
3591c9de560dSAlex Tomas 		max = max >> 1;
3592c9de560dSAlex Tomas 		i++;
35934b68f6dfSHarshad Shirwadkar 	} while (i < MB_NUM_ORDERS(sb));
35944b68f6dfSHarshad Shirwadkar 
359583e80a6eSJan Kara 	sbi->s_mb_avg_fragment_size =
359683e80a6eSJan Kara 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
359783e80a6eSJan Kara 			GFP_KERNEL);
359883e80a6eSJan Kara 	if (!sbi->s_mb_avg_fragment_size) {
359983e80a6eSJan Kara 		ret = -ENOMEM;
360083e80a6eSJan Kara 		goto out;
360183e80a6eSJan Kara 	}
360283e80a6eSJan Kara 	sbi->s_mb_avg_fragment_size_locks =
360383e80a6eSJan Kara 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
360483e80a6eSJan Kara 			GFP_KERNEL);
360583e80a6eSJan Kara 	if (!sbi->s_mb_avg_fragment_size_locks) {
360683e80a6eSJan Kara 		ret = -ENOMEM;
360783e80a6eSJan Kara 		goto out;
360883e80a6eSJan Kara 	}
360983e80a6eSJan Kara 	for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
361083e80a6eSJan Kara 		INIT_LIST_HEAD(&sbi->s_mb_avg_fragment_size[i]);
361183e80a6eSJan Kara 		rwlock_init(&sbi->s_mb_avg_fragment_size_locks[i]);
361283e80a6eSJan Kara 	}
3613196e402aSHarshad Shirwadkar 	sbi->s_mb_largest_free_orders =
3614196e402aSHarshad Shirwadkar 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3615196e402aSHarshad Shirwadkar 			GFP_KERNEL);
3616196e402aSHarshad Shirwadkar 	if (!sbi->s_mb_largest_free_orders) {
3617196e402aSHarshad Shirwadkar 		ret = -ENOMEM;
3618196e402aSHarshad Shirwadkar 		goto out;
3619196e402aSHarshad Shirwadkar 	}
3620196e402aSHarshad Shirwadkar 	sbi->s_mb_largest_free_orders_locks =
3621196e402aSHarshad Shirwadkar 		kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3622196e402aSHarshad Shirwadkar 			GFP_KERNEL);
3623196e402aSHarshad Shirwadkar 	if (!sbi->s_mb_largest_free_orders_locks) {
3624196e402aSHarshad Shirwadkar 		ret = -ENOMEM;
3625196e402aSHarshad Shirwadkar 		goto out;
3626196e402aSHarshad Shirwadkar 	}
3627196e402aSHarshad Shirwadkar 	for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3628196e402aSHarshad Shirwadkar 		INIT_LIST_HEAD(&sbi->s_mb_largest_free_orders[i]);
3629196e402aSHarshad Shirwadkar 		rwlock_init(&sbi->s_mb_largest_free_orders_locks[i]);
3630196e402aSHarshad Shirwadkar 	}
3631c9de560dSAlex Tomas 
3632c9de560dSAlex Tomas 	spin_lock_init(&sbi->s_md_lock);
3633d08854f5STheodore Ts'o 	sbi->s_mb_free_pending = 0;
3634*ce774e53SJinke Han 	INIT_LIST_HEAD(&sbi->s_freed_data_list[0]);
3635*ce774e53SJinke Han 	INIT_LIST_HEAD(&sbi->s_freed_data_list[1]);
363655cdd0afSWang Jianchao 	INIT_LIST_HEAD(&sbi->s_discard_list);
363755cdd0afSWang Jianchao 	INIT_WORK(&sbi->s_discard_work, ext4_discard_work);
36385036ab8dSWang Jianchao 	atomic_set(&sbi->s_retry_alloc_pending, 0);
3639c9de560dSAlex Tomas 
3640c9de560dSAlex Tomas 	sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
3641c9de560dSAlex Tomas 	sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
3642c9de560dSAlex Tomas 	sbi->s_mb_stats = MB_DEFAULT_STATS;
3643c9de560dSAlex Tomas 	sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
3644c9de560dSAlex Tomas 	sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
3645f52f3d2bSOjaswin Mujoo 	sbi->s_mb_best_avail_max_trim_order = MB_DEFAULT_BEST_AVAIL_TRIM_ORDER;
36467e170922SOjaswin Mujoo 
364727baebb8STheodore Ts'o 	/*
364827baebb8STheodore Ts'o 	 * The default group preallocation is 512, which for 4k block
364927baebb8STheodore Ts'o 	 * sizes translates to 2 megabytes.  However for bigalloc file
365027baebb8STheodore Ts'o 	 * systems, this is probably too big (i.e, if the cluster size
365127baebb8STheodore Ts'o 	 * is 1 megabyte, then group preallocation size becomes half a
365227baebb8STheodore Ts'o 	 * gigabyte!).  As a default, we will keep a two megabyte
365327baebb8STheodore Ts'o 	 * group pralloc size for cluster sizes up to 64k, and after
365427baebb8STheodore Ts'o 	 * that, we will force a minimum group preallocation size of
365527baebb8STheodore Ts'o 	 * 32 clusters.  This translates to 8 megs when the cluster
365627baebb8STheodore Ts'o 	 * size is 256k, and 32 megs when the cluster size is 1 meg,
365727baebb8STheodore Ts'o 	 * which seems reasonable as a default.
365827baebb8STheodore Ts'o 	 */
365927baebb8STheodore Ts'o 	sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
366027baebb8STheodore Ts'o 				       sbi->s_cluster_bits, 32);
3661d7a1fee1SDan Ehrenberg 	/*
3662d7a1fee1SDan Ehrenberg 	 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
3663d7a1fee1SDan Ehrenberg 	 * to the lowest multiple of s_stripe which is bigger than
3664d7a1fee1SDan Ehrenberg 	 * the s_mb_group_prealloc as determined above. We want
3665d7a1fee1SDan Ehrenberg 	 * the preallocation size to be an exact multiple of the
3666d7a1fee1SDan Ehrenberg 	 * RAID stripe size so that preallocations don't fragment
3667d7a1fee1SDan Ehrenberg 	 * the stripes.
3668d7a1fee1SDan Ehrenberg 	 */
3669d7a1fee1SDan Ehrenberg 	if (sbi->s_stripe > 1) {
3670d7a1fee1SDan Ehrenberg 		sbi->s_mb_group_prealloc = roundup(
3671c3defd99SKemeng Shi 			sbi->s_mb_group_prealloc, EXT4_B2C(sbi, sbi->s_stripe));
3672d7a1fee1SDan Ehrenberg 	}
3673c9de560dSAlex Tomas 
3674730c213cSEric Sandeen 	sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
3675c9de560dSAlex Tomas 	if (sbi->s_locality_groups == NULL) {
3676fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
3677029b10c5SAndrey Tsyvarev 		goto out;
3678c9de560dSAlex Tomas 	}
3679730c213cSEric Sandeen 	for_each_possible_cpu(i) {
3680c9de560dSAlex Tomas 		struct ext4_locality_group *lg;
3681730c213cSEric Sandeen 		lg = per_cpu_ptr(sbi->s_locality_groups, i);
3682c9de560dSAlex Tomas 		mutex_init(&lg->lg_mutex);
36836be2ded1SAneesh Kumar K.V 		for (j = 0; j < PREALLOC_TB_SIZE; j++)
36846be2ded1SAneesh Kumar K.V 			INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
3685c9de560dSAlex Tomas 		spin_lock_init(&lg->lg_prealloc_lock);
3686c9de560dSAlex Tomas 	}
3687c9de560dSAlex Tomas 
368810f0d2a5SChristoph Hellwig 	if (bdev_nonrot(sb->s_bdev))
3689196e402aSHarshad Shirwadkar 		sbi->s_mb_max_linear_groups = 0;
3690196e402aSHarshad Shirwadkar 	else
3691196e402aSHarshad Shirwadkar 		sbi->s_mb_max_linear_groups = MB_DEFAULT_LINEAR_LIMIT;
369279a77c5aSYu Jian 	/* init file for buddy data */
369379a77c5aSYu Jian 	ret = ext4_mb_init_backend(sb);
36947aa0baeaSTao Ma 	if (ret != 0)
36957aa0baeaSTao Ma 		goto out_free_locality_groups;
369679a77c5aSYu Jian 
36977aa0baeaSTao Ma 	return 0;
36987aa0baeaSTao Ma 
36997aa0baeaSTao Ma out_free_locality_groups:
37007aa0baeaSTao Ma 	free_percpu(sbi->s_locality_groups);
37017aa0baeaSTao Ma 	sbi->s_locality_groups = NULL;
3702fb1813f4SCurt Wohlgemuth out:
370383e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size);
370483e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size_locks);
3705196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders);
3706196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders_locks);
3707fb1813f4SCurt Wohlgemuth 	kfree(sbi->s_mb_offsets);
37087aa0baeaSTao Ma 	sbi->s_mb_offsets = NULL;
3709fb1813f4SCurt Wohlgemuth 	kfree(sbi->s_mb_maxs);
37107aa0baeaSTao Ma 	sbi->s_mb_maxs = NULL;
3711fb1813f4SCurt Wohlgemuth 	return ret;
3712c9de560dSAlex Tomas }
3713c9de560dSAlex Tomas 
3714955ce5f5SAneesh Kumar K.V /* need to called with the ext4 group lock held */
3715d3df1453SRitesh Harjani static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
3716c9de560dSAlex Tomas {
3717c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3718c9de560dSAlex Tomas 	struct list_head *cur, *tmp;
3719c9de560dSAlex Tomas 	int count = 0;
3720c9de560dSAlex Tomas 
3721c9de560dSAlex Tomas 	list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
3722c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3723c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
3724c9de560dSAlex Tomas 		count++;
3725688f05a0SAneesh Kumar K.V 		kmem_cache_free(ext4_pspace_cachep, pa);
3726c9de560dSAlex Tomas 	}
3727d3df1453SRitesh Harjani 	return count;
3728c9de560dSAlex Tomas }
3729c9de560dSAlex Tomas 
3730c9de560dSAlex Tomas int ext4_mb_release(struct super_block *sb)
3731c9de560dSAlex Tomas {
37328df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
3733c9de560dSAlex Tomas 	ext4_group_t i;
3734c9de560dSAlex Tomas 	int num_meta_group_infos;
3735df3da4eaSSuraj Jitindar Singh 	struct ext4_group_info *grinfo, ***group_info;
3736c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3737fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3738d3df1453SRitesh Harjani 	int count;
3739c9de560dSAlex Tomas 
374055cdd0afSWang Jianchao 	if (test_opt(sb, DISCARD)) {
374155cdd0afSWang Jianchao 		/*
374255cdd0afSWang Jianchao 		 * wait the discard work to drain all of ext4_free_data
374355cdd0afSWang Jianchao 		 */
374455cdd0afSWang Jianchao 		flush_work(&sbi->s_discard_work);
374555cdd0afSWang Jianchao 		WARN_ON_ONCE(!list_empty(&sbi->s_discard_list));
374655cdd0afSWang Jianchao 	}
374755cdd0afSWang Jianchao 
3748c9de560dSAlex Tomas 	if (sbi->s_group_info) {
37498df9675fSTheodore Ts'o 		for (i = 0; i < ngroups; i++) {
37504b99faa2SKhazhismel Kumykov 			cond_resched();
3751c9de560dSAlex Tomas 			grinfo = ext4_get_group_info(sb, i);
37525354b2afSTheodore Ts'o 			if (!grinfo)
37535354b2afSTheodore Ts'o 				continue;
3754a3450215SRitesh Harjani 			mb_group_bb_bitmap_free(grinfo);
3755c9de560dSAlex Tomas 			ext4_lock_group(sb, i);
3756d3df1453SRitesh Harjani 			count = ext4_mb_cleanup_pa(grinfo);
3757d3df1453SRitesh Harjani 			if (count)
3758d3df1453SRitesh Harjani 				mb_debug(sb, "mballoc: %d PAs left\n",
3759d3df1453SRitesh Harjani 					 count);
3760c9de560dSAlex Tomas 			ext4_unlock_group(sb, i);
3761fb1813f4SCurt Wohlgemuth 			kmem_cache_free(cachep, grinfo);
3762c9de560dSAlex Tomas 		}
37638df9675fSTheodore Ts'o 		num_meta_group_infos = (ngroups +
3764c9de560dSAlex Tomas 				EXT4_DESC_PER_BLOCK(sb) - 1) >>
3765c9de560dSAlex Tomas 			EXT4_DESC_PER_BLOCK_BITS(sb);
3766df3da4eaSSuraj Jitindar Singh 		rcu_read_lock();
3767df3da4eaSSuraj Jitindar Singh 		group_info = rcu_dereference(sbi->s_group_info);
3768c9de560dSAlex Tomas 		for (i = 0; i < num_meta_group_infos; i++)
3769df3da4eaSSuraj Jitindar Singh 			kfree(group_info[i]);
3770df3da4eaSSuraj Jitindar Singh 		kvfree(group_info);
3771df3da4eaSSuraj Jitindar Singh 		rcu_read_unlock();
3772c9de560dSAlex Tomas 	}
377383e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size);
377483e80a6eSJan Kara 	kfree(sbi->s_mb_avg_fragment_size_locks);
3775196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders);
3776196e402aSHarshad Shirwadkar 	kfree(sbi->s_mb_largest_free_orders_locks);
3777c9de560dSAlex Tomas 	kfree(sbi->s_mb_offsets);
3778c9de560dSAlex Tomas 	kfree(sbi->s_mb_maxs);
3779c9de560dSAlex Tomas 	iput(sbi->s_buddy_cache);
3780c9de560dSAlex Tomas 	if (sbi->s_mb_stats) {
37819d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
37829d8b9ec4STheodore Ts'o 		       "mballoc: %u blocks %u reqs (%u success)",
3783c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_allocated),
3784c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_reqs),
3785c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_success));
37869d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
3787a6c75eafSHarshad Shirwadkar 		      "mballoc: %u extents scanned, %u groups scanned, %u goal hits, "
37889d8b9ec4STheodore Ts'o 				"%u 2^N hits, %u breaks, %u lost",
3789c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_ex_scanned),
3790a6c75eafSHarshad Shirwadkar 				atomic_read(&sbi->s_bal_groups_scanned),
3791c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_goals),
3792c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_2orders),
3793c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_breaks),
3794c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_lost_chunks));
37959d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
379667d25186SHarshad Shirwadkar 		       "mballoc: %u generated and it took %llu",
379767d25186SHarshad Shirwadkar 				atomic_read(&sbi->s_mb_buddies_generated),
379867d25186SHarshad Shirwadkar 				atomic64_read(&sbi->s_mb_generation_time));
37999d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
38009d8b9ec4STheodore Ts'o 		       "mballoc: %u preallocated, %u discarded",
3801c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_preallocated),
3802c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_discarded));
3803c9de560dSAlex Tomas 	}
3804c9de560dSAlex Tomas 
3805730c213cSEric Sandeen 	free_percpu(sbi->s_locality_groups);
3806c9de560dSAlex Tomas 
3807c9de560dSAlex Tomas 	return 0;
3808c9de560dSAlex Tomas }
3809c9de560dSAlex Tomas 
381077ca6cdfSLukas Czerner static inline int ext4_issue_discard(struct super_block *sb,
3811a0154344SDaeho Jeong 		ext4_group_t block_group, ext4_grpblk_t cluster, int count,
3812a0154344SDaeho Jeong 		struct bio **biop)
38135c521830SJiaying Zhang {
38145c521830SJiaying Zhang 	ext4_fsblk_t discard_block;
38155c521830SJiaying Zhang 
381684130193STheodore Ts'o 	discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
381784130193STheodore Ts'o 			 ext4_group_first_block_no(sb, block_group));
381884130193STheodore Ts'o 	count = EXT4_C2B(EXT4_SB(sb), count);
38195c521830SJiaying Zhang 	trace_ext4_discard_blocks(sb,
38205c521830SJiaying Zhang 			(unsigned long long) discard_block, count);
3821a0154344SDaeho Jeong 	if (biop) {
3822a0154344SDaeho Jeong 		return __blkdev_issue_discard(sb->s_bdev,
3823a0154344SDaeho Jeong 			(sector_t)discard_block << (sb->s_blocksize_bits - 9),
3824a0154344SDaeho Jeong 			(sector_t)count << (sb->s_blocksize_bits - 9),
382544abff2cSChristoph Hellwig 			GFP_NOFS, biop);
3826a0154344SDaeho Jeong 	} else
382793259636SLukas Czerner 		return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
38285c521830SJiaying Zhang }
38295c521830SJiaying Zhang 
3830a0154344SDaeho Jeong static void ext4_free_data_in_buddy(struct super_block *sb,
3831a0154344SDaeho Jeong 				    struct ext4_free_data *entry)
3832c9de560dSAlex Tomas {
3833c9de560dSAlex Tomas 	struct ext4_buddy e4b;
3834c894058dSAneesh Kumar K.V 	struct ext4_group_info *db;
3835c7f2bafaSKemeng Shi 	int err, count = 0;
3836c9de560dSAlex Tomas 
3837d3df1453SRitesh Harjani 	mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
383818aadd47SBobi Jam 		 entry->efd_count, entry->efd_group, entry);
3839c9de560dSAlex Tomas 
384018aadd47SBobi Jam 	err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
3841c9de560dSAlex Tomas 	/* we expect to find existing buddy because it's pinned */
3842c9de560dSAlex Tomas 	BUG_ON(err != 0);
3843c9de560dSAlex Tomas 
3844d08854f5STheodore Ts'o 	spin_lock(&EXT4_SB(sb)->s_md_lock);
3845d08854f5STheodore Ts'o 	EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
3846d08854f5STheodore Ts'o 	spin_unlock(&EXT4_SB(sb)->s_md_lock);
384718aadd47SBobi Jam 
3848c894058dSAneesh Kumar K.V 	db = e4b.bd_info;
3849c9de560dSAlex Tomas 	/* there are blocks to put in buddy to make them really free */
385018aadd47SBobi Jam 	count += entry->efd_count;
385118aadd47SBobi Jam 	ext4_lock_group(sb, entry->efd_group);
3852c894058dSAneesh Kumar K.V 	/* Take it out of per group rb tree */
385318aadd47SBobi Jam 	rb_erase(&entry->efd_node, &(db->bb_free_root));
385418aadd47SBobi Jam 	mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
3855c9de560dSAlex Tomas 
38563d56b8d2STao Ma 	/*
38573d56b8d2STao Ma 	 * Clear the trimmed flag for the group so that the next
38583d56b8d2STao Ma 	 * ext4_trim_fs can trim it.
38593d56b8d2STao Ma 	 * If the volume is mounted with -o discard, online discard
38603d56b8d2STao Ma 	 * is supported and the free blocks will be trimmed online.
38613d56b8d2STao Ma 	 */
38623d56b8d2STao Ma 	if (!test_opt(sb, DISCARD))
38633d56b8d2STao Ma 		EXT4_MB_GRP_CLEAR_TRIMMED(db);
38643d56b8d2STao Ma 
3865c894058dSAneesh Kumar K.V 	if (!db->bb_free_root.rb_node) {
3866c894058dSAneesh Kumar K.V 		/* No more items in the per group rb tree
3867c894058dSAneesh Kumar K.V 		 * balance refcounts from ext4_mb_free_metadata()
3868c894058dSAneesh Kumar K.V 		 */
386909cbfeafSKirill A. Shutemov 		put_page(e4b.bd_buddy_page);
387009cbfeafSKirill A. Shutemov 		put_page(e4b.bd_bitmap_page);
3871c894058dSAneesh Kumar K.V 	}
387218aadd47SBobi Jam 	ext4_unlock_group(sb, entry->efd_group);
3873e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
3874c9de560dSAlex Tomas 
3875c7f2bafaSKemeng Shi 	mb_debug(sb, "freed %d blocks in 1 structures\n", count);
3876c9de560dSAlex Tomas }
3877c9de560dSAlex Tomas 
3878a0154344SDaeho Jeong /*
3879a0154344SDaeho Jeong  * This function is called by the jbd2 layer once the commit has finished,
3880a0154344SDaeho Jeong  * so we know we can free the blocks that were released with that commit.
3881a0154344SDaeho Jeong  */
3882a0154344SDaeho Jeong void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
3883a0154344SDaeho Jeong {
3884a0154344SDaeho Jeong 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3885a0154344SDaeho Jeong 	struct ext4_free_data *entry, *tmp;
38860f6bc579SRuan Jinjie 	LIST_HEAD(freed_data_list);
3887*ce774e53SJinke Han 	struct list_head *s_freed_head = &sbi->s_freed_data_list[commit_tid & 1];
388855cdd0afSWang Jianchao 	bool wake;
3889a0154344SDaeho Jeong 
3890*ce774e53SJinke Han 	list_replace_init(s_freed_head, &freed_data_list);
3891a0154344SDaeho Jeong 
389255cdd0afSWang Jianchao 	list_for_each_entry(entry, &freed_data_list, efd_list)
3893a0154344SDaeho Jeong 		ext4_free_data_in_buddy(sb, entry);
389455cdd0afSWang Jianchao 
389555cdd0afSWang Jianchao 	if (test_opt(sb, DISCARD)) {
389655cdd0afSWang Jianchao 		spin_lock(&sbi->s_md_lock);
389755cdd0afSWang Jianchao 		wake = list_empty(&sbi->s_discard_list);
389855cdd0afSWang Jianchao 		list_splice_tail(&freed_data_list, &sbi->s_discard_list);
389955cdd0afSWang Jianchao 		spin_unlock(&sbi->s_md_lock);
390055cdd0afSWang Jianchao 		if (wake)
390155cdd0afSWang Jianchao 			queue_work(system_unbound_wq, &sbi->s_discard_work);
390255cdd0afSWang Jianchao 	} else {
390355cdd0afSWang Jianchao 		list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
390455cdd0afSWang Jianchao 			kmem_cache_free(ext4_free_data_cachep, entry);
390555cdd0afSWang Jianchao 	}
3906a0154344SDaeho Jeong }
3907a0154344SDaeho Jeong 
39085dabfc78STheodore Ts'o int __init ext4_init_mballoc(void)
3909c9de560dSAlex Tomas {
391016828088STheodore Ts'o 	ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
391116828088STheodore Ts'o 					SLAB_RECLAIM_ACCOUNT);
3912c9de560dSAlex Tomas 	if (ext4_pspace_cachep == NULL)
3913f283529aSRitesh Harjani 		goto out;
3914c9de560dSAlex Tomas 
391516828088STheodore Ts'o 	ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
391616828088STheodore Ts'o 				    SLAB_RECLAIM_ACCOUNT);
3917f283529aSRitesh Harjani 	if (ext4_ac_cachep == NULL)
3918f283529aSRitesh Harjani 		goto out_pa_free;
3919c894058dSAneesh Kumar K.V 
392018aadd47SBobi Jam 	ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
392116828088STheodore Ts'o 					   SLAB_RECLAIM_ACCOUNT);
3922f283529aSRitesh Harjani 	if (ext4_free_data_cachep == NULL)
3923f283529aSRitesh Harjani 		goto out_ac_free;
3924f283529aSRitesh Harjani 
3925c9de560dSAlex Tomas 	return 0;
3926f283529aSRitesh Harjani 
3927f283529aSRitesh Harjani out_ac_free:
3928f283529aSRitesh Harjani 	kmem_cache_destroy(ext4_ac_cachep);
3929f283529aSRitesh Harjani out_pa_free:
3930f283529aSRitesh Harjani 	kmem_cache_destroy(ext4_pspace_cachep);
3931f283529aSRitesh Harjani out:
3932f283529aSRitesh Harjani 	return -ENOMEM;
3933c9de560dSAlex Tomas }
3934c9de560dSAlex Tomas 
39355dabfc78STheodore Ts'o void ext4_exit_mballoc(void)
3936c9de560dSAlex Tomas {
39373e03f9caSJesper Dangaard Brouer 	/*
39383e03f9caSJesper Dangaard Brouer 	 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
39393e03f9caSJesper Dangaard Brouer 	 * before destroying the slab cache.
39403e03f9caSJesper Dangaard Brouer 	 */
39413e03f9caSJesper Dangaard Brouer 	rcu_barrier();
3942c9de560dSAlex Tomas 	kmem_cache_destroy(ext4_pspace_cachep);
3943256bdb49SEric Sandeen 	kmem_cache_destroy(ext4_ac_cachep);
394418aadd47SBobi Jam 	kmem_cache_destroy(ext4_free_data_cachep);
39452892c15dSEric Sandeen 	ext4_groupinfo_destroy_slabs();
3946c9de560dSAlex Tomas }
3947c9de560dSAlex Tomas 
3948c9de560dSAlex Tomas 
3949c9de560dSAlex Tomas /*
395073b2c716SUwe Kleine-König  * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
3951c9de560dSAlex Tomas  * Returns 0 if success or error code
3952c9de560dSAlex Tomas  */
39534ddfef7bSEric Sandeen static noinline_for_stack int
39544ddfef7bSEric Sandeen ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
395553accfa9STheodore Ts'o 				handle_t *handle, unsigned int reserv_clstrs)
3956c9de560dSAlex Tomas {
3957c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
3958c9de560dSAlex Tomas 	struct ext4_group_desc *gdp;
3959c9de560dSAlex Tomas 	struct buffer_head *gdp_bh;
3960c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
3961c9de560dSAlex Tomas 	struct super_block *sb;
3962c9de560dSAlex Tomas 	ext4_fsblk_t block;
3963519deca0SAneesh Kumar K.V 	int err, len;
3964c9de560dSAlex Tomas 
3965c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3966c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_len <= 0);
3967c9de560dSAlex Tomas 
3968c9de560dSAlex Tomas 	sb = ac->ac_sb;
3969c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
3970c9de560dSAlex Tomas 
3971574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
39729008a58eSDarrick J. Wong 	if (IS_ERR(bitmap_bh)) {
3973fb28f9ceSKemeng Shi 		return PTR_ERR(bitmap_bh);
39749008a58eSDarrick J. Wong 	}
3975c9de560dSAlex Tomas 
39765d601255Sliang xie 	BUFFER_TRACE(bitmap_bh, "getting write access");
3977188c299eSJan Kara 	err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
3978188c299eSJan Kara 					    EXT4_JTR_NONE);
3979c9de560dSAlex Tomas 	if (err)
3980c9de560dSAlex Tomas 		goto out_err;
3981c9de560dSAlex Tomas 
3982c9de560dSAlex Tomas 	err = -EIO;
3983c9de560dSAlex Tomas 	gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3984c9de560dSAlex Tomas 	if (!gdp)
3985c9de560dSAlex Tomas 		goto out_err;
3986c9de560dSAlex Tomas 
3987a9df9a49STheodore Ts'o 	ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
3988021b65bbSTheodore Ts'o 			ext4_free_group_clusters(sb, gdp));
398903cddb80SAneesh Kumar K.V 
39905d601255Sliang xie 	BUFFER_TRACE(gdp_bh, "get_write_access");
3991188c299eSJan Kara 	err = ext4_journal_get_write_access(handle, sb, gdp_bh, EXT4_JTR_NONE);
3992c9de560dSAlex Tomas 	if (err)
3993c9de560dSAlex Tomas 		goto out_err;
3994c9de560dSAlex Tomas 
3995bda00de7SAkinobu Mita 	block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3996c9de560dSAlex Tomas 
399753accfa9STheodore Ts'o 	len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3998ce9f24ccSJan Kara 	if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
399912062dddSEric Sandeen 		ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
40001084f252STheodore Ts'o 			   "fs metadata", block, block+len);
4001519deca0SAneesh Kumar K.V 		/* File system mounted not to panic on error
4002554a5cccSVegard Nossum 		 * Fix the bitmap and return EFSCORRUPTED
4003519deca0SAneesh Kumar K.V 		 * We leak some of the blocks here.
4004519deca0SAneesh Kumar K.V 		 */
4005955ce5f5SAneesh Kumar K.V 		ext4_lock_group(sb, ac->ac_b_ex.fe_group);
4006123e3016SRitesh Harjani 		mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
4007519deca0SAneesh Kumar K.V 			      ac->ac_b_ex.fe_len);
4008955ce5f5SAneesh Kumar K.V 		ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
40090390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4010519deca0SAneesh Kumar K.V 		if (!err)
4011554a5cccSVegard Nossum 			err = -EFSCORRUPTED;
4012519deca0SAneesh Kumar K.V 		goto out_err;
4013c9de560dSAlex Tomas 	}
4014955ce5f5SAneesh Kumar K.V 
4015955ce5f5SAneesh Kumar K.V 	ext4_lock_group(sb, ac->ac_b_ex.fe_group);
4016c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
4017c9de560dSAlex Tomas 	{
4018c9de560dSAlex Tomas 		int i;
4019c9de560dSAlex Tomas 		for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
4020c9de560dSAlex Tomas 			BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
4021c9de560dSAlex Tomas 						bitmap_bh->b_data));
4022c9de560dSAlex Tomas 		}
4023c9de560dSAlex Tomas 	}
4024c9de560dSAlex Tomas #endif
4025123e3016SRitesh Harjani 	mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
4026c3e94d1dSYongqiang Yang 		      ac->ac_b_ex.fe_len);
40278844618dSTheodore Ts'o 	if (ext4_has_group_desc_csum(sb) &&
40288844618dSTheodore Ts'o 	    (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
4029c9de560dSAlex Tomas 		gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
4030021b65bbSTheodore Ts'o 		ext4_free_group_clusters_set(sb, gdp,
4031cff1dfd7STheodore Ts'o 					     ext4_free_clusters_after_init(sb,
4032560671a0SAneesh Kumar K.V 						ac->ac_b_ex.fe_group, gdp));
4033c9de560dSAlex Tomas 	}
4034021b65bbSTheodore Ts'o 	len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
4035021b65bbSTheodore Ts'o 	ext4_free_group_clusters_set(sb, gdp, len);
40361df9bde4SKemeng Shi 	ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
4037feb0ab32SDarrick J. Wong 	ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
4038955ce5f5SAneesh Kumar K.V 
4039955ce5f5SAneesh Kumar K.V 	ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
404057042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
4041d2a17637SMingming Cao 	/*
40426bc6e63fSAneesh Kumar K.V 	 * Now reduce the dirty block count also. Should not go negative
4043d2a17637SMingming Cao 	 */
40446bc6e63fSAneesh Kumar K.V 	if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
40456bc6e63fSAneesh Kumar K.V 		/* release all the reserved blocks if non delalloc */
404657042651STheodore Ts'o 		percpu_counter_sub(&sbi->s_dirtyclusters_counter,
404757042651STheodore Ts'o 				   reserv_clstrs);
4048c9de560dSAlex Tomas 
4049772cb7c8SJose R. Santos 	if (sbi->s_log_groups_per_flex) {
4050772cb7c8SJose R. Santos 		ext4_group_t flex_group = ext4_flex_group(sbi,
4051772cb7c8SJose R. Santos 							  ac->ac_b_ex.fe_group);
405290ba983fSTheodore Ts'o 		atomic64_sub(ac->ac_b_ex.fe_len,
40537c990728SSuraj Jitindar Singh 			     &sbi_array_rcu_deref(sbi, s_flex_groups,
40547c990728SSuraj Jitindar Singh 						  flex_group)->free_clusters);
4055772cb7c8SJose R. Santos 	}
4056772cb7c8SJose R. Santos 
40570390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4058c9de560dSAlex Tomas 	if (err)
4059c9de560dSAlex Tomas 		goto out_err;
40600390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
4061c9de560dSAlex Tomas 
4062c9de560dSAlex Tomas out_err:
406342a10addSAneesh Kumar K.V 	brelse(bitmap_bh);
4064c9de560dSAlex Tomas 	return err;
4065c9de560dSAlex Tomas }
4066c9de560dSAlex Tomas 
4067c9de560dSAlex Tomas /*
40688016e29fSHarshad Shirwadkar  * Idempotent helper for Ext4 fast commit replay path to set the state of
40698016e29fSHarshad Shirwadkar  * blocks in bitmaps and update counters.
40708016e29fSHarshad Shirwadkar  */
40718016e29fSHarshad Shirwadkar void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
40728016e29fSHarshad Shirwadkar 			int len, int state)
40738016e29fSHarshad Shirwadkar {
40748016e29fSHarshad Shirwadkar 	struct buffer_head *bitmap_bh = NULL;
40758016e29fSHarshad Shirwadkar 	struct ext4_group_desc *gdp;
40768016e29fSHarshad Shirwadkar 	struct buffer_head *gdp_bh;
40778016e29fSHarshad Shirwadkar 	struct ext4_sb_info *sbi = EXT4_SB(sb);
40788016e29fSHarshad Shirwadkar 	ext4_group_t group;
40798016e29fSHarshad Shirwadkar 	ext4_grpblk_t blkoff;
4080a50bda14SSu Hui 	int i, err = 0;
40818016e29fSHarshad Shirwadkar 	int already;
4082bfdc502aSRitesh Harjani 	unsigned int clen, clen_changed, thisgrp_len;
40838016e29fSHarshad Shirwadkar 
4084bfdc502aSRitesh Harjani 	while (len > 0) {
40858016e29fSHarshad Shirwadkar 		ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
4086bfdc502aSRitesh Harjani 
4087bfdc502aSRitesh Harjani 		/*
4088bfdc502aSRitesh Harjani 		 * Check to see if we are freeing blocks across a group
4089bfdc502aSRitesh Harjani 		 * boundary.
4090bfdc502aSRitesh Harjani 		 * In case of flex_bg, this can happen that (block, len) may
4091bfdc502aSRitesh Harjani 		 * span across more than one group. In that case we need to
4092bfdc502aSRitesh Harjani 		 * get the corresponding group metadata to work with.
4093bfdc502aSRitesh Harjani 		 * For this we have goto again loop.
4094bfdc502aSRitesh Harjani 		 */
4095bfdc502aSRitesh Harjani 		thisgrp_len = min_t(unsigned int, (unsigned int)len,
4096bfdc502aSRitesh Harjani 			EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
4097bfdc502aSRitesh Harjani 		clen = EXT4_NUM_B2C(sbi, thisgrp_len);
4098bfdc502aSRitesh Harjani 
40998c91c579SRitesh Harjani 		if (!ext4_sb_block_valid(sb, NULL, block, thisgrp_len)) {
41008c91c579SRitesh Harjani 			ext4_error(sb, "Marking blocks in system zone - "
41018c91c579SRitesh Harjani 				   "Block = %llu, len = %u",
41028c91c579SRitesh Harjani 				   block, thisgrp_len);
41038c91c579SRitesh Harjani 			bitmap_bh = NULL;
41048c91c579SRitesh Harjani 			break;
41058c91c579SRitesh Harjani 		}
41068c91c579SRitesh Harjani 
41078016e29fSHarshad Shirwadkar 		bitmap_bh = ext4_read_block_bitmap(sb, group);
41088016e29fSHarshad Shirwadkar 		if (IS_ERR(bitmap_bh)) {
41098016e29fSHarshad Shirwadkar 			err = PTR_ERR(bitmap_bh);
41108016e29fSHarshad Shirwadkar 			bitmap_bh = NULL;
4111bfdc502aSRitesh Harjani 			break;
41128016e29fSHarshad Shirwadkar 		}
41138016e29fSHarshad Shirwadkar 
41148016e29fSHarshad Shirwadkar 		err = -EIO;
41158016e29fSHarshad Shirwadkar 		gdp = ext4_get_group_desc(sb, group, &gdp_bh);
41168016e29fSHarshad Shirwadkar 		if (!gdp)
4117bfdc502aSRitesh Harjani 			break;
41188016e29fSHarshad Shirwadkar 
41198016e29fSHarshad Shirwadkar 		ext4_lock_group(sb, group);
41208016e29fSHarshad Shirwadkar 		already = 0;
41218016e29fSHarshad Shirwadkar 		for (i = 0; i < clen; i++)
4122bfdc502aSRitesh Harjani 			if (!mb_test_bit(blkoff + i, bitmap_bh->b_data) ==
4123bfdc502aSRitesh Harjani 					 !state)
41248016e29fSHarshad Shirwadkar 				already++;
41258016e29fSHarshad Shirwadkar 
4126a5c0e2fdSRitesh Harjani 		clen_changed = clen - already;
41278016e29fSHarshad Shirwadkar 		if (state)
4128123e3016SRitesh Harjani 			mb_set_bits(bitmap_bh->b_data, blkoff, clen);
41298016e29fSHarshad Shirwadkar 		else
4130bd8247eeSRitesh Harjani 			mb_clear_bits(bitmap_bh->b_data, blkoff, clen);
41318016e29fSHarshad Shirwadkar 		if (ext4_has_group_desc_csum(sb) &&
41328016e29fSHarshad Shirwadkar 		    (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
41338016e29fSHarshad Shirwadkar 			gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
41348016e29fSHarshad Shirwadkar 			ext4_free_group_clusters_set(sb, gdp,
4135bfdc502aSRitesh Harjani 			     ext4_free_clusters_after_init(sb, group, gdp));
41368016e29fSHarshad Shirwadkar 		}
41378016e29fSHarshad Shirwadkar 		if (state)
4138a5c0e2fdSRitesh Harjani 			clen = ext4_free_group_clusters(sb, gdp) - clen_changed;
41398016e29fSHarshad Shirwadkar 		else
4140a5c0e2fdSRitesh Harjani 			clen = ext4_free_group_clusters(sb, gdp) + clen_changed;
41418016e29fSHarshad Shirwadkar 
41428016e29fSHarshad Shirwadkar 		ext4_free_group_clusters_set(sb, gdp, clen);
41431df9bde4SKemeng Shi 		ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
41448016e29fSHarshad Shirwadkar 		ext4_group_desc_csum_set(sb, group, gdp);
41458016e29fSHarshad Shirwadkar 
41468016e29fSHarshad Shirwadkar 		ext4_unlock_group(sb, group);
41478016e29fSHarshad Shirwadkar 
41488016e29fSHarshad Shirwadkar 		if (sbi->s_log_groups_per_flex) {
41498016e29fSHarshad Shirwadkar 			ext4_group_t flex_group = ext4_flex_group(sbi, group);
4150a5c0e2fdSRitesh Harjani 			struct flex_groups *fg = sbi_array_rcu_deref(sbi,
4151a5c0e2fdSRitesh Harjani 						   s_flex_groups, flex_group);
41528016e29fSHarshad Shirwadkar 
4153a5c0e2fdSRitesh Harjani 			if (state)
4154a5c0e2fdSRitesh Harjani 				atomic64_sub(clen_changed, &fg->free_clusters);
4155a5c0e2fdSRitesh Harjani 			else
4156a5c0e2fdSRitesh Harjani 				atomic64_add(clen_changed, &fg->free_clusters);
4157bfdc502aSRitesh Harjani 
41588016e29fSHarshad Shirwadkar 		}
41598016e29fSHarshad Shirwadkar 
41608016e29fSHarshad Shirwadkar 		err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
41618016e29fSHarshad Shirwadkar 		if (err)
4162bfdc502aSRitesh Harjani 			break;
41638016e29fSHarshad Shirwadkar 		sync_dirty_buffer(bitmap_bh);
41648016e29fSHarshad Shirwadkar 		err = ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
41658016e29fSHarshad Shirwadkar 		sync_dirty_buffer(gdp_bh);
4166bfdc502aSRitesh Harjani 		if (err)
4167bfdc502aSRitesh Harjani 			break;
41688016e29fSHarshad Shirwadkar 
4169bfdc502aSRitesh Harjani 		block += thisgrp_len;
4170bfdc502aSRitesh Harjani 		len -= thisgrp_len;
4171bfdc502aSRitesh Harjani 		brelse(bitmap_bh);
4172bfdc502aSRitesh Harjani 		BUG_ON(len < 0);
4173bfdc502aSRitesh Harjani 	}
4174bfdc502aSRitesh Harjani 
4175bfdc502aSRitesh Harjani 	if (err)
41768016e29fSHarshad Shirwadkar 		brelse(bitmap_bh);
41778016e29fSHarshad Shirwadkar }
41788016e29fSHarshad Shirwadkar 
41798016e29fSHarshad Shirwadkar /*
4180c9de560dSAlex Tomas  * here we normalize request for locality group
4181d7a1fee1SDan Ehrenberg  * Group request are normalized to s_mb_group_prealloc, which goes to
4182d7a1fee1SDan Ehrenberg  * s_strip if we set the same via mount option.
4183d7a1fee1SDan Ehrenberg  * s_mb_group_prealloc can be configured via
4184b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_group_prealloc
4185c9de560dSAlex Tomas  *
4186c9de560dSAlex Tomas  * XXX: should we try to preallocate more than the group has now?
4187c9de560dSAlex Tomas  */
4188c9de560dSAlex Tomas static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
4189c9de560dSAlex Tomas {
4190c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
4191c9de560dSAlex Tomas 	struct ext4_locality_group *lg = ac->ac_lg;
4192c9de560dSAlex Tomas 
4193c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
4194c9de560dSAlex Tomas 	ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
4195d3df1453SRitesh Harjani 	mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
4196c9de560dSAlex Tomas }
4197c9de560dSAlex Tomas 
419838727786SOjaswin Mujoo /*
419938727786SOjaswin Mujoo  * This function returns the next element to look at during inode
420038727786SOjaswin Mujoo  * PA rbtree walk. We assume that we have held the inode PA rbtree lock
420138727786SOjaswin Mujoo  * (ei->i_prealloc_lock)
420238727786SOjaswin Mujoo  *
420338727786SOjaswin Mujoo  * new_start	The start of the range we want to compare
420438727786SOjaswin Mujoo  * cur_start	The existing start that we are comparing against
420538727786SOjaswin Mujoo  * node	The node of the rb_tree
420638727786SOjaswin Mujoo  */
420738727786SOjaswin Mujoo static inline struct rb_node*
420838727786SOjaswin Mujoo ext4_mb_pa_rb_next_iter(ext4_lblk_t new_start, ext4_lblk_t cur_start, struct rb_node *node)
420938727786SOjaswin Mujoo {
421038727786SOjaswin Mujoo 	if (new_start < cur_start)
421138727786SOjaswin Mujoo 		return node->rb_left;
421238727786SOjaswin Mujoo 	else
421338727786SOjaswin Mujoo 		return node->rb_right;
421438727786SOjaswin Mujoo }
421538727786SOjaswin Mujoo 
42167692094aSOjaswin Mujoo static inline void
42177692094aSOjaswin Mujoo ext4_mb_pa_assert_overlap(struct ext4_allocation_context *ac,
4218bedc5d34SBaokun Li 			  ext4_lblk_t start, loff_t end)
42197692094aSOjaswin Mujoo {
42207692094aSOjaswin Mujoo 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
42217692094aSOjaswin Mujoo 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
42227692094aSOjaswin Mujoo 	struct ext4_prealloc_space *tmp_pa;
4223bedc5d34SBaokun Li 	ext4_lblk_t tmp_pa_start;
4224bedc5d34SBaokun Li 	loff_t tmp_pa_end;
422538727786SOjaswin Mujoo 	struct rb_node *iter;
42267692094aSOjaswin Mujoo 
422738727786SOjaswin Mujoo 	read_lock(&ei->i_prealloc_lock);
422838727786SOjaswin Mujoo 	for (iter = ei->i_prealloc_node.rb_node; iter;
422938727786SOjaswin Mujoo 	     iter = ext4_mb_pa_rb_next_iter(start, tmp_pa_start, iter)) {
423038727786SOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
423138727786SOjaswin Mujoo 				  pa_node.inode_node);
42327692094aSOjaswin Mujoo 		tmp_pa_start = tmp_pa->pa_lstart;
4233bedc5d34SBaokun Li 		tmp_pa_end = pa_logical_end(sbi, tmp_pa);
42347692094aSOjaswin Mujoo 
423538727786SOjaswin Mujoo 		spin_lock(&tmp_pa->pa_lock);
423638727786SOjaswin Mujoo 		if (tmp_pa->pa_deleted == 0)
42377692094aSOjaswin Mujoo 			BUG_ON(!(start >= tmp_pa_end || end <= tmp_pa_start));
42387692094aSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
42397692094aSOjaswin Mujoo 	}
424038727786SOjaswin Mujoo 	read_unlock(&ei->i_prealloc_lock);
42417692094aSOjaswin Mujoo }
42427692094aSOjaswin Mujoo 
4243c9de560dSAlex Tomas /*
42440830344cSOjaswin Mujoo  * Given an allocation context "ac" and a range "start", "end", check
42450830344cSOjaswin Mujoo  * and adjust boundaries if the range overlaps with any of the existing
42460830344cSOjaswin Mujoo  * preallocatoins stored in the corresponding inode of the allocation context.
42470830344cSOjaswin Mujoo  *
42480830344cSOjaswin Mujoo  * Parameters:
42490830344cSOjaswin Mujoo  *	ac			allocation context
42500830344cSOjaswin Mujoo  *	start			start of the new range
42510830344cSOjaswin Mujoo  *	end			end of the new range
42520830344cSOjaswin Mujoo  */
42530830344cSOjaswin Mujoo static inline void
42540830344cSOjaswin Mujoo ext4_mb_pa_adjust_overlap(struct ext4_allocation_context *ac,
4255bedc5d34SBaokun Li 			  ext4_lblk_t *start, loff_t *end)
42560830344cSOjaswin Mujoo {
42570830344cSOjaswin Mujoo 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
42580830344cSOjaswin Mujoo 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
425938727786SOjaswin Mujoo 	struct ext4_prealloc_space *tmp_pa = NULL, *left_pa = NULL, *right_pa = NULL;
426038727786SOjaswin Mujoo 	struct rb_node *iter;
4261bedc5d34SBaokun Li 	ext4_lblk_t new_start, tmp_pa_start, right_pa_start = -1;
4262bedc5d34SBaokun Li 	loff_t new_end, tmp_pa_end, left_pa_end = -1;
42630830344cSOjaswin Mujoo 
42640830344cSOjaswin Mujoo 	new_start = *start;
42650830344cSOjaswin Mujoo 	new_end = *end;
42660830344cSOjaswin Mujoo 
426738727786SOjaswin Mujoo 	/*
426838727786SOjaswin Mujoo 	 * Adjust the normalized range so that it doesn't overlap with any
426938727786SOjaswin Mujoo 	 * existing preallocated blocks(PAs). Make sure to hold the rbtree lock
427038727786SOjaswin Mujoo 	 * so it doesn't change underneath us.
427138727786SOjaswin Mujoo 	 */
427238727786SOjaswin Mujoo 	read_lock(&ei->i_prealloc_lock);
42730830344cSOjaswin Mujoo 
427438727786SOjaswin Mujoo 	/* Step 1: find any one immediate neighboring PA of the normalized range */
427538727786SOjaswin Mujoo 	for (iter = ei->i_prealloc_node.rb_node; iter;
427638727786SOjaswin Mujoo 	     iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
427738727786SOjaswin Mujoo 					    tmp_pa_start, iter)) {
427838727786SOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
427938727786SOjaswin Mujoo 				  pa_node.inode_node);
42800830344cSOjaswin Mujoo 		tmp_pa_start = tmp_pa->pa_lstart;
4281bedc5d34SBaokun Li 		tmp_pa_end = pa_logical_end(sbi, tmp_pa);
42820830344cSOjaswin Mujoo 
42830830344cSOjaswin Mujoo 		/* PA must not overlap original request */
428438727786SOjaswin Mujoo 		spin_lock(&tmp_pa->pa_lock);
428538727786SOjaswin Mujoo 		if (tmp_pa->pa_deleted == 0)
42860830344cSOjaswin Mujoo 			BUG_ON(!(ac->ac_o_ex.fe_logical >= tmp_pa_end ||
42870830344cSOjaswin Mujoo 				 ac->ac_o_ex.fe_logical < tmp_pa_start));
42880830344cSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
42890830344cSOjaswin Mujoo 	}
42900830344cSOjaswin Mujoo 
429138727786SOjaswin Mujoo 	/*
429238727786SOjaswin Mujoo 	 * Step 2: check if the found PA is left or right neighbor and
429338727786SOjaswin Mujoo 	 * get the other neighbor
429438727786SOjaswin Mujoo 	 */
429538727786SOjaswin Mujoo 	if (tmp_pa) {
429638727786SOjaswin Mujoo 		if (tmp_pa->pa_lstart < ac->ac_o_ex.fe_logical) {
429738727786SOjaswin Mujoo 			struct rb_node *tmp;
429838727786SOjaswin Mujoo 
429938727786SOjaswin Mujoo 			left_pa = tmp_pa;
430038727786SOjaswin Mujoo 			tmp = rb_next(&left_pa->pa_node.inode_node);
430138727786SOjaswin Mujoo 			if (tmp) {
430238727786SOjaswin Mujoo 				right_pa = rb_entry(tmp,
430338727786SOjaswin Mujoo 						    struct ext4_prealloc_space,
430438727786SOjaswin Mujoo 						    pa_node.inode_node);
430538727786SOjaswin Mujoo 			}
430638727786SOjaswin Mujoo 		} else {
430738727786SOjaswin Mujoo 			struct rb_node *tmp;
430838727786SOjaswin Mujoo 
430938727786SOjaswin Mujoo 			right_pa = tmp_pa;
431038727786SOjaswin Mujoo 			tmp = rb_prev(&right_pa->pa_node.inode_node);
431138727786SOjaswin Mujoo 			if (tmp) {
431238727786SOjaswin Mujoo 				left_pa = rb_entry(tmp,
431338727786SOjaswin Mujoo 						   struct ext4_prealloc_space,
431438727786SOjaswin Mujoo 						   pa_node.inode_node);
431538727786SOjaswin Mujoo 			}
431638727786SOjaswin Mujoo 		}
431738727786SOjaswin Mujoo 	}
431838727786SOjaswin Mujoo 
431938727786SOjaswin Mujoo 	/* Step 3: get the non deleted neighbors */
432038727786SOjaswin Mujoo 	if (left_pa) {
432138727786SOjaswin Mujoo 		for (iter = &left_pa->pa_node.inode_node;;
432238727786SOjaswin Mujoo 		     iter = rb_prev(iter)) {
432338727786SOjaswin Mujoo 			if (!iter) {
432438727786SOjaswin Mujoo 				left_pa = NULL;
432538727786SOjaswin Mujoo 				break;
432638727786SOjaswin Mujoo 			}
432738727786SOjaswin Mujoo 
432838727786SOjaswin Mujoo 			tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
432938727786SOjaswin Mujoo 					  pa_node.inode_node);
433038727786SOjaswin Mujoo 			left_pa = tmp_pa;
433138727786SOjaswin Mujoo 			spin_lock(&tmp_pa->pa_lock);
433238727786SOjaswin Mujoo 			if (tmp_pa->pa_deleted == 0) {
433338727786SOjaswin Mujoo 				spin_unlock(&tmp_pa->pa_lock);
433438727786SOjaswin Mujoo 				break;
43350830344cSOjaswin Mujoo 			}
43360830344cSOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
43370830344cSOjaswin Mujoo 		}
433838727786SOjaswin Mujoo 	}
433938727786SOjaswin Mujoo 
434038727786SOjaswin Mujoo 	if (right_pa) {
434138727786SOjaswin Mujoo 		for (iter = &right_pa->pa_node.inode_node;;
434238727786SOjaswin Mujoo 		     iter = rb_next(iter)) {
434338727786SOjaswin Mujoo 			if (!iter) {
434438727786SOjaswin Mujoo 				right_pa = NULL;
434538727786SOjaswin Mujoo 				break;
434638727786SOjaswin Mujoo 			}
434738727786SOjaswin Mujoo 
434838727786SOjaswin Mujoo 			tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
434938727786SOjaswin Mujoo 					  pa_node.inode_node);
435038727786SOjaswin Mujoo 			right_pa = tmp_pa;
435138727786SOjaswin Mujoo 			spin_lock(&tmp_pa->pa_lock);
435238727786SOjaswin Mujoo 			if (tmp_pa->pa_deleted == 0) {
435338727786SOjaswin Mujoo 				spin_unlock(&tmp_pa->pa_lock);
435438727786SOjaswin Mujoo 				break;
435538727786SOjaswin Mujoo 			}
435638727786SOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
435738727786SOjaswin Mujoo 		}
435838727786SOjaswin Mujoo 	}
435938727786SOjaswin Mujoo 
436038727786SOjaswin Mujoo 	if (left_pa) {
4361bedc5d34SBaokun Li 		left_pa_end = pa_logical_end(sbi, left_pa);
436238727786SOjaswin Mujoo 		BUG_ON(left_pa_end > ac->ac_o_ex.fe_logical);
436338727786SOjaswin Mujoo 	}
436438727786SOjaswin Mujoo 
436538727786SOjaswin Mujoo 	if (right_pa) {
436638727786SOjaswin Mujoo 		right_pa_start = right_pa->pa_lstart;
436738727786SOjaswin Mujoo 		BUG_ON(right_pa_start <= ac->ac_o_ex.fe_logical);
436838727786SOjaswin Mujoo 	}
436938727786SOjaswin Mujoo 
437038727786SOjaswin Mujoo 	/* Step 4: trim our normalized range to not overlap with the neighbors */
437138727786SOjaswin Mujoo 	if (left_pa) {
437238727786SOjaswin Mujoo 		if (left_pa_end > new_start)
437338727786SOjaswin Mujoo 			new_start = left_pa_end;
437438727786SOjaswin Mujoo 	}
437538727786SOjaswin Mujoo 
437638727786SOjaswin Mujoo 	if (right_pa) {
437738727786SOjaswin Mujoo 		if (right_pa_start < new_end)
437838727786SOjaswin Mujoo 			new_end = right_pa_start;
437938727786SOjaswin Mujoo 	}
438038727786SOjaswin Mujoo 	read_unlock(&ei->i_prealloc_lock);
43810830344cSOjaswin Mujoo 
43820830344cSOjaswin Mujoo 	/* XXX: extra loop to check we really don't overlap preallocations */
43830830344cSOjaswin Mujoo 	ext4_mb_pa_assert_overlap(ac, new_start, new_end);
43840830344cSOjaswin Mujoo 
43850830344cSOjaswin Mujoo 	*start = new_start;
43860830344cSOjaswin Mujoo 	*end = new_end;
43870830344cSOjaswin Mujoo }
43880830344cSOjaswin Mujoo 
43890830344cSOjaswin Mujoo /*
4390c9de560dSAlex Tomas  * Normalization means making request better in terms of
4391c9de560dSAlex Tomas  * size and alignment
4392c9de560dSAlex Tomas  */
43934ddfef7bSEric Sandeen static noinline_for_stack void
43944ddfef7bSEric Sandeen ext4_mb_normalize_request(struct ext4_allocation_context *ac,
4395c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
4396c9de560dSAlex Tomas {
439753accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4398b07ffe69SKemeng Shi 	struct ext4_super_block *es = sbi->s_es;
4399c9de560dSAlex Tomas 	int bsbits, max;
4400bedc5d34SBaokun Li 	loff_t size, start_off, end;
44011592d2c5SCurt Wohlgemuth 	loff_t orig_size __maybe_unused;
44025a0790c2SAndi Kleen 	ext4_lblk_t start;
4403c9de560dSAlex Tomas 
4404c9de560dSAlex Tomas 	/* do normalize only data requests, metadata requests
4405c9de560dSAlex Tomas 	   do not need preallocation */
4406c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4407c9de560dSAlex Tomas 		return;
4408c9de560dSAlex Tomas 
4409c9de560dSAlex Tomas 	/* sometime caller may want exact blocks */
4410c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4411c9de560dSAlex Tomas 		return;
4412c9de560dSAlex Tomas 
4413c9de560dSAlex Tomas 	/* caller may indicate that preallocation isn't
4414c9de560dSAlex Tomas 	 * required (it's a tail, for example) */
4415c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
4416c9de560dSAlex Tomas 		return;
4417c9de560dSAlex Tomas 
4418c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
4419c9de560dSAlex Tomas 		ext4_mb_normalize_group_request(ac);
4420c9de560dSAlex Tomas 		return ;
4421c9de560dSAlex Tomas 	}
4422c9de560dSAlex Tomas 
4423c9de560dSAlex Tomas 	bsbits = ac->ac_sb->s_blocksize_bits;
4424c9de560dSAlex Tomas 
4425c9de560dSAlex Tomas 	/* first, let's learn actual file size
4426c9de560dSAlex Tomas 	 * given current request is allocated */
442743bbddc0SBaokun Li 	size = extent_logical_end(sbi, &ac->ac_o_ex);
4428c9de560dSAlex Tomas 	size = size << bsbits;
4429c9de560dSAlex Tomas 	if (size < i_size_read(ac->ac_inode))
4430c9de560dSAlex Tomas 		size = i_size_read(ac->ac_inode);
44315a0790c2SAndi Kleen 	orig_size = size;
4432c9de560dSAlex Tomas 
44331930479cSValerie Clement 	/* max size of free chunks */
44341930479cSValerie Clement 	max = 2 << bsbits;
4435c9de560dSAlex Tomas 
44361930479cSValerie Clement #define NRL_CHECK_SIZE(req, size, max, chunk_size)	\
44371930479cSValerie Clement 		(req <= (size) || max <= (chunk_size))
4438c9de560dSAlex Tomas 
4439c9de560dSAlex Tomas 	/* first, try to predict filesize */
4440c9de560dSAlex Tomas 	/* XXX: should this table be tunable? */
4441c9de560dSAlex Tomas 	start_off = 0;
4442c9de560dSAlex Tomas 	if (size <= 16 * 1024) {
4443c9de560dSAlex Tomas 		size = 16 * 1024;
4444c9de560dSAlex Tomas 	} else if (size <= 32 * 1024) {
4445c9de560dSAlex Tomas 		size = 32 * 1024;
4446c9de560dSAlex Tomas 	} else if (size <= 64 * 1024) {
4447c9de560dSAlex Tomas 		size = 64 * 1024;
4448c9de560dSAlex Tomas 	} else if (size <= 128 * 1024) {
4449c9de560dSAlex Tomas 		size = 128 * 1024;
4450c9de560dSAlex Tomas 	} else if (size <= 256 * 1024) {
4451c9de560dSAlex Tomas 		size = 256 * 1024;
4452c9de560dSAlex Tomas 	} else if (size <= 512 * 1024) {
4453c9de560dSAlex Tomas 		size = 512 * 1024;
4454c9de560dSAlex Tomas 	} else if (size <= 1024 * 1024) {
4455c9de560dSAlex Tomas 		size = 1024 * 1024;
44561930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
4457c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
44581930479cSValerie Clement 						(21 - bsbits)) << 21;
44591930479cSValerie Clement 		size = 2 * 1024 * 1024;
44601930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
4461c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4462c9de560dSAlex Tomas 							(22 - bsbits)) << 22;
4463c9de560dSAlex Tomas 		size = 4 * 1024 * 1024;
4464b3916da0SKemeng Shi 	} else if (NRL_CHECK_SIZE(EXT4_C2B(sbi, ac->ac_o_ex.fe_len),
44651930479cSValerie Clement 					(8<<20)>>bsbits, max, 8 * 1024)) {
4466c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4467c9de560dSAlex Tomas 							(23 - bsbits)) << 23;
4468c9de560dSAlex Tomas 		size = 8 * 1024 * 1024;
4469c9de560dSAlex Tomas 	} else {
4470c9de560dSAlex Tomas 		start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
447191a48aafSKemeng Shi 		size	  = (loff_t) EXT4_C2B(sbi,
4472b27b1535SXiaoguang Wang 					      ac->ac_o_ex.fe_len) << bsbits;
4473c9de560dSAlex Tomas 	}
44745a0790c2SAndi Kleen 	size = size >> bsbits;
44755a0790c2SAndi Kleen 	start = start_off >> bsbits;
4476c9de560dSAlex Tomas 
4477a08f789dSBaokun Li 	/*
4478a08f789dSBaokun Li 	 * For tiny groups (smaller than 8MB) the chosen allocation
4479a08f789dSBaokun Li 	 * alignment may be larger than group size. Make sure the
4480a08f789dSBaokun Li 	 * alignment does not move allocation to a different group which
4481a08f789dSBaokun Li 	 * makes mballoc fail assertions later.
4482a08f789dSBaokun Li 	 */
4483a08f789dSBaokun Li 	start = max(start, rounddown(ac->ac_o_ex.fe_logical,
4484a08f789dSBaokun Li 			(ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
4485a08f789dSBaokun Li 
4486c9de560dSAlex Tomas 	/* don't cover already allocated blocks in selected range */
4487c9de560dSAlex Tomas 	if (ar->pleft && start <= ar->lleft) {
4488c9de560dSAlex Tomas 		size -= ar->lleft + 1 - start;
4489c9de560dSAlex Tomas 		start = ar->lleft + 1;
4490c9de560dSAlex Tomas 	}
4491c9de560dSAlex Tomas 	if (ar->pright && start + size - 1 >= ar->lright)
4492c9de560dSAlex Tomas 		size -= start + size - ar->lright;
4493c9de560dSAlex Tomas 
4494cd648b8aSJan Kara 	/*
4495cd648b8aSJan Kara 	 * Trim allocation request for filesystems with artificially small
4496cd648b8aSJan Kara 	 * groups.
4497cd648b8aSJan Kara 	 */
4498cd648b8aSJan Kara 	if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
4499cd648b8aSJan Kara 		size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
4500cd648b8aSJan Kara 
4501c9de560dSAlex Tomas 	end = start + size;
4502c9de560dSAlex Tomas 
45030830344cSOjaswin Mujoo 	ext4_mb_pa_adjust_overlap(ac, &start, &end);
4504c9de560dSAlex Tomas 
4505c9de560dSAlex Tomas 	size = end - start;
4506c9de560dSAlex Tomas 
4507cf4ff938SBaokun Li 	/*
4508cf4ff938SBaokun Li 	 * In this function "start" and "size" are normalized for better
4509cf4ff938SBaokun Li 	 * alignment and length such that we could preallocate more blocks.
4510cf4ff938SBaokun Li 	 * This normalization is done such that original request of
4511cf4ff938SBaokun Li 	 * ac->ac_o_ex.fe_logical & fe_len should always lie within "start" and
4512cf4ff938SBaokun Li 	 * "size" boundaries.
4513cf4ff938SBaokun Li 	 * (Note fe_len can be relaxed since FS block allocation API does not
4514cf4ff938SBaokun Li 	 * provide gurantee on number of contiguous blocks allocation since that
4515cf4ff938SBaokun Li 	 * depends upon free space left, etc).
4516cf4ff938SBaokun Li 	 * In case of inode pa, later we use the allocated blocks
45171221b235SKemeng Shi 	 * [pa_pstart + fe_logical - pa_lstart, fe_len/size] from the preallocated
4518cf4ff938SBaokun Li 	 * range of goal/best blocks [start, size] to put it at the
4519cf4ff938SBaokun Li 	 * ac_o_ex.fe_logical extent of this inode.
4520cf4ff938SBaokun Li 	 * (See ext4_mb_use_inode_pa() for more details)
4521cf4ff938SBaokun Li 	 */
4522cf4ff938SBaokun Li 	if (start + size <= ac->ac_o_ex.fe_logical ||
4523c9de560dSAlex Tomas 			start > ac->ac_o_ex.fe_logical) {
45249d8b9ec4STheodore Ts'o 		ext4_msg(ac->ac_sb, KERN_ERR,
45259d8b9ec4STheodore Ts'o 			 "start %lu, size %lu, fe_logical %lu",
4526c9de560dSAlex Tomas 			 (unsigned long) start, (unsigned long) size,
4527c9de560dSAlex Tomas 			 (unsigned long) ac->ac_o_ex.fe_logical);
4528dfe076c1SDmitry Monakhov 		BUG();
4529c9de560dSAlex Tomas 	}
4530b5b60778SMaurizio Lombardi 	BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
4531c9de560dSAlex Tomas 
4532c9de560dSAlex Tomas 	/* now prepare goal request */
4533c9de560dSAlex Tomas 
4534c9de560dSAlex Tomas 	/* XXX: is it better to align blocks WRT to logical
4535c9de560dSAlex Tomas 	 * placement or satisfy big request as is */
4536c9de560dSAlex Tomas 	ac->ac_g_ex.fe_logical = start;
453753accfa9STheodore Ts'o 	ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
45387e170922SOjaswin Mujoo 	ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
4539c9de560dSAlex Tomas 
4540c9de560dSAlex Tomas 	/* define goal start in order to merge */
4541b07ffe69SKemeng Shi 	if (ar->pright && (ar->lright == (start + size)) &&
4542b07ffe69SKemeng Shi 	    ar->pright >= size &&
4543b07ffe69SKemeng Shi 	    ar->pright - size >= le32_to_cpu(es->s_first_data_block)) {
4544c9de560dSAlex Tomas 		/* merge to the right */
4545c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
4546b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_group,
4547b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_start);
4548c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4549c9de560dSAlex Tomas 	}
4550b07ffe69SKemeng Shi 	if (ar->pleft && (ar->lleft + 1 == start) &&
4551b07ffe69SKemeng Shi 	    ar->pleft + 1 < ext4_blocks_count(es)) {
4552c9de560dSAlex Tomas 		/* merge to the left */
4553c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
4554b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_group,
4555b07ffe69SKemeng Shi 						&ac->ac_g_ex.fe_start);
4556c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4557c9de560dSAlex Tomas 	}
4558c9de560dSAlex Tomas 
4559d3df1453SRitesh Harjani 	mb_debug(ac->ac_sb, "goal: %lld(was %lld) blocks at %u\n", size,
4560d3df1453SRitesh Harjani 		 orig_size, start);
4561c9de560dSAlex Tomas }
4562c9de560dSAlex Tomas 
4563c9de560dSAlex Tomas static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
4564c9de560dSAlex Tomas {
4565c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4566c9de560dSAlex Tomas 
4567a6c75eafSHarshad Shirwadkar 	if (sbi->s_mb_stats && ac->ac_g_ex.fe_len >= 1) {
4568c9de560dSAlex Tomas 		atomic_inc(&sbi->s_bal_reqs);
4569c9de560dSAlex Tomas 		atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
4570291dae47SCurt Wohlgemuth 		if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
4571c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_success);
4572fdd9a009SOjaswin Mujoo 
4573c9de560dSAlex Tomas 		atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
4574fdd9a009SOjaswin Mujoo 		for (int i=0; i<EXT4_MB_NUM_CRS; i++) {
4575fdd9a009SOjaswin Mujoo 			atomic_add(ac->ac_cX_found[i], &sbi->s_bal_cX_ex_scanned[i]);
4576fdd9a009SOjaswin Mujoo 		}
4577fdd9a009SOjaswin Mujoo 
4578a6c75eafSHarshad Shirwadkar 		atomic_add(ac->ac_groups_scanned, &sbi->s_bal_groups_scanned);
4579c9de560dSAlex Tomas 		if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
4580c9de560dSAlex Tomas 				ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
4581c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_goals);
45827e170922SOjaswin Mujoo 		/* did we allocate as much as normalizer originally wanted? */
45837e170922SOjaswin Mujoo 		if (ac->ac_f_ex.fe_len == ac->ac_orig_goal_len)
45843ef5d263SOjaswin Mujoo 			atomic_inc(&sbi->s_bal_len_goals);
45857e170922SOjaswin Mujoo 
4586c9de560dSAlex Tomas 		if (ac->ac_found > sbi->s_mb_max_to_scan)
4587c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_breaks);
4588c9de560dSAlex Tomas 	}
4589c9de560dSAlex Tomas 
4590296c355cSTheodore Ts'o 	if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
4591296c355cSTheodore Ts'o 		trace_ext4_mballoc_alloc(ac);
4592296c355cSTheodore Ts'o 	else
4593296c355cSTheodore Ts'o 		trace_ext4_mballoc_prealloc(ac);
4594c9de560dSAlex Tomas }
4595c9de560dSAlex Tomas 
4596c9de560dSAlex Tomas /*
4597b844167eSCurt Wohlgemuth  * Called on failure; free up any blocks from the inode PA for this
4598b844167eSCurt Wohlgemuth  * context.  We don't need this for MB_GROUP_PA because we only change
4599b844167eSCurt Wohlgemuth  * pa_free in ext4_mb_release_context(), but on failure, we've already
4600b844167eSCurt Wohlgemuth  * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
4601b844167eSCurt Wohlgemuth  */
4602b844167eSCurt Wohlgemuth static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
4603b844167eSCurt Wohlgemuth {
4604b844167eSCurt Wohlgemuth 	struct ext4_prealloc_space *pa = ac->ac_pa;
460586f0afd4STheodore Ts'o 	struct ext4_buddy e4b;
460686f0afd4STheodore Ts'o 	int err;
4607b844167eSCurt Wohlgemuth 
460886f0afd4STheodore Ts'o 	if (pa == NULL) {
4609c99d1e6eSTheodore Ts'o 		if (ac->ac_f_ex.fe_len == 0)
4610c99d1e6eSTheodore Ts'o 			return;
461186f0afd4STheodore Ts'o 		err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
461219b8b035STheodore Ts'o 		if (WARN_RATELIMIT(err,
461319b8b035STheodore Ts'o 				   "ext4: mb_load_buddy failed (%d)", err))
461486f0afd4STheodore Ts'o 			/*
461586f0afd4STheodore Ts'o 			 * This should never happen since we pin the
461686f0afd4STheodore Ts'o 			 * pages in the ext4_allocation_context so
461786f0afd4STheodore Ts'o 			 * ext4_mb_load_buddy() should never fail.
461886f0afd4STheodore Ts'o 			 */
461986f0afd4STheodore Ts'o 			return;
462086f0afd4STheodore Ts'o 		ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
462186f0afd4STheodore Ts'o 		mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
462286f0afd4STheodore Ts'o 			       ac->ac_f_ex.fe_len);
462386f0afd4STheodore Ts'o 		ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
4624c99d1e6eSTheodore Ts'o 		ext4_mb_unload_buddy(&e4b);
462586f0afd4STheodore Ts'o 		return;
462686f0afd4STheodore Ts'o 	}
462736cb0f52SKemeng Shi 	if (pa->pa_type == MB_INODE_PA) {
462836cb0f52SKemeng Shi 		spin_lock(&pa->pa_lock);
4629400db9d3SZheng Liu 		pa->pa_free += ac->ac_b_ex.fe_len;
463036cb0f52SKemeng Shi 		spin_unlock(&pa->pa_lock);
463136cb0f52SKemeng Shi 	}
4632b844167eSCurt Wohlgemuth }
4633b844167eSCurt Wohlgemuth 
4634b844167eSCurt Wohlgemuth /*
4635c9de560dSAlex Tomas  * use blocks preallocated to inode
4636c9de560dSAlex Tomas  */
4637c9de560dSAlex Tomas static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
4638c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
4639c9de560dSAlex Tomas {
464053accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4641c9de560dSAlex Tomas 	ext4_fsblk_t start;
4642c9de560dSAlex Tomas 	ext4_fsblk_t end;
4643c9de560dSAlex Tomas 	int len;
4644c9de560dSAlex Tomas 
4645c9de560dSAlex Tomas 	/* found preallocated blocks, use them */
4646c9de560dSAlex Tomas 	start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
464753accfa9STheodore Ts'o 	end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
464853accfa9STheodore Ts'o 		  start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
464953accfa9STheodore Ts'o 	len = EXT4_NUM_B2C(sbi, end - start);
4650c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
4651c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
4652c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
4653c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
4654c9de560dSAlex Tomas 	ac->ac_pa = pa;
4655c9de560dSAlex Tomas 
4656c9de560dSAlex Tomas 	BUG_ON(start < pa->pa_pstart);
465753accfa9STheodore Ts'o 	BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
4658c9de560dSAlex Tomas 	BUG_ON(pa->pa_free < len);
465993cdf49fSOjaswin Mujoo 	BUG_ON(ac->ac_b_ex.fe_len <= 0);
4660c9de560dSAlex Tomas 	pa->pa_free -= len;
4661c9de560dSAlex Tomas 
4662d3df1453SRitesh Harjani 	mb_debug(ac->ac_sb, "use %llu/%d from inode pa %p\n", start, len, pa);
4663c9de560dSAlex Tomas }
4664c9de560dSAlex Tomas 
4665c9de560dSAlex Tomas /*
4666c9de560dSAlex Tomas  * use blocks preallocated to locality group
4667c9de560dSAlex Tomas  */
4668c9de560dSAlex Tomas static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
4669c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
4670c9de560dSAlex Tomas {
467103cddb80SAneesh Kumar K.V 	unsigned int len = ac->ac_o_ex.fe_len;
46726be2ded1SAneesh Kumar K.V 
4673c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
4674c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_group,
4675c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
4676c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
4677c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
4678c9de560dSAlex Tomas 	ac->ac_pa = pa;
4679c9de560dSAlex Tomas 
46801221b235SKemeng Shi 	/* we don't correct pa_pstart or pa_len here to avoid
468126346ff6SAneesh Kumar K.V 	 * possible race when the group is being loaded concurrently
4682c9de560dSAlex Tomas 	 * instead we correct pa later, after blocks are marked
468326346ff6SAneesh Kumar K.V 	 * in on-disk bitmap -- see ext4_mb_release_context()
468426346ff6SAneesh Kumar K.V 	 * Other CPUs are prevented from allocating from this pa by lg_mutex
4685c9de560dSAlex Tomas 	 */
4686d3df1453SRitesh Harjani 	mb_debug(ac->ac_sb, "use %u/%u from group pa %p\n",
46871afdc588SKemeng Shi 		 pa->pa_lstart, len, pa);
4688c9de560dSAlex Tomas }
4689c9de560dSAlex Tomas 
4690c9de560dSAlex Tomas /*
46915e745b04SAneesh Kumar K.V  * Return the prealloc space that have minimal distance
46925e745b04SAneesh Kumar K.V  * from the goal block. @cpa is the prealloc
46935e745b04SAneesh Kumar K.V  * space that is having currently known minimal distance
46945e745b04SAneesh Kumar K.V  * from the goal block.
46955e745b04SAneesh Kumar K.V  */
46965e745b04SAneesh Kumar K.V static struct ext4_prealloc_space *
46975e745b04SAneesh Kumar K.V ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
46985e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *pa,
46995e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *cpa)
47005e745b04SAneesh Kumar K.V {
47015e745b04SAneesh Kumar K.V 	ext4_fsblk_t cur_distance, new_distance;
47025e745b04SAneesh Kumar K.V 
47035e745b04SAneesh Kumar K.V 	if (cpa == NULL) {
47045e745b04SAneesh Kumar K.V 		atomic_inc(&pa->pa_count);
47055e745b04SAneesh Kumar K.V 		return pa;
47065e745b04SAneesh Kumar K.V 	}
470779211c8eSAndrew Morton 	cur_distance = abs(goal_block - cpa->pa_pstart);
470879211c8eSAndrew Morton 	new_distance = abs(goal_block - pa->pa_pstart);
47095e745b04SAneesh Kumar K.V 
47105a54b2f1SColy Li 	if (cur_distance <= new_distance)
47115e745b04SAneesh Kumar K.V 		return cpa;
47125e745b04SAneesh Kumar K.V 
47135e745b04SAneesh Kumar K.V 	/* drop the previous reference */
47145e745b04SAneesh Kumar K.V 	atomic_dec(&cpa->pa_count);
47155e745b04SAneesh Kumar K.V 	atomic_inc(&pa->pa_count);
47165e745b04SAneesh Kumar K.V 	return pa;
47175e745b04SAneesh Kumar K.V }
47185e745b04SAneesh Kumar K.V 
47195e745b04SAneesh Kumar K.V /*
47201eff5904SKemeng Shi  * check if found pa meets EXT4_MB_HINT_GOAL_ONLY
47211eff5904SKemeng Shi  */
47221eff5904SKemeng Shi static bool
47231eff5904SKemeng Shi ext4_mb_pa_goal_check(struct ext4_allocation_context *ac,
47241eff5904SKemeng Shi 		      struct ext4_prealloc_space *pa)
47251eff5904SKemeng Shi {
47261eff5904SKemeng Shi 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
47271eff5904SKemeng Shi 	ext4_fsblk_t start;
47281eff5904SKemeng Shi 
47291eff5904SKemeng Shi 	if (likely(!(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY)))
47301eff5904SKemeng Shi 		return true;
47311eff5904SKemeng Shi 
47321eff5904SKemeng Shi 	/*
47331eff5904SKemeng Shi 	 * If EXT4_MB_HINT_GOAL_ONLY is set, ac_g_ex will not be adjusted
47341eff5904SKemeng Shi 	 * in ext4_mb_normalize_request and will keep same with ac_o_ex
47351eff5904SKemeng Shi 	 * from ext4_mb_initialize_context. Choose ac_g_ex here to keep
47361eff5904SKemeng Shi 	 * consistent with ext4_mb_find_by_goal.
47371eff5904SKemeng Shi 	 */
47381eff5904SKemeng Shi 	start = pa->pa_pstart +
47391eff5904SKemeng Shi 		(ac->ac_g_ex.fe_logical - pa->pa_lstart);
47401eff5904SKemeng Shi 	if (ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex) != start)
47411eff5904SKemeng Shi 		return false;
47421eff5904SKemeng Shi 
47431eff5904SKemeng Shi 	if (ac->ac_g_ex.fe_len > pa->pa_len -
47441eff5904SKemeng Shi 	    EXT4_B2C(sbi, ac->ac_g_ex.fe_logical - pa->pa_lstart))
47451eff5904SKemeng Shi 		return false;
47461eff5904SKemeng Shi 
47471eff5904SKemeng Shi 	return true;
47481eff5904SKemeng Shi }
47491eff5904SKemeng Shi 
47501eff5904SKemeng Shi /*
4751c9de560dSAlex Tomas  * search goal blocks in preallocated space
4752c9de560dSAlex Tomas  */
47534fca8f07SRitesh Harjani static noinline_for_stack bool
47544ddfef7bSEric Sandeen ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
4755c9de560dSAlex Tomas {
475653accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
47576be2ded1SAneesh Kumar K.V 	int order, i;
4758c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4759c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
47609d3de7eeSOjaswin Mujoo 	struct ext4_prealloc_space *tmp_pa = NULL, *cpa = NULL;
476138727786SOjaswin Mujoo 	struct rb_node *iter;
47625e745b04SAneesh Kumar K.V 	ext4_fsblk_t goal_block;
4763c9de560dSAlex Tomas 
4764c9de560dSAlex Tomas 	/* only data can be preallocated */
4765c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
47664fca8f07SRitesh Harjani 		return false;
4767c9de560dSAlex Tomas 
47689d3de7eeSOjaswin Mujoo 	/*
47699d3de7eeSOjaswin Mujoo 	 * first, try per-file preallocation by searching the inode pa rbtree.
47709d3de7eeSOjaswin Mujoo 	 *
47719d3de7eeSOjaswin Mujoo 	 * Here, we can't do a direct traversal of the tree because
47729d3de7eeSOjaswin Mujoo 	 * ext4_mb_discard_group_preallocation() can paralelly mark the pa
47739d3de7eeSOjaswin Mujoo 	 * deleted and that can cause direct traversal to skip some entries.
47749d3de7eeSOjaswin Mujoo 	 */
477538727786SOjaswin Mujoo 	read_lock(&ei->i_prealloc_lock);
47769d3de7eeSOjaswin Mujoo 
47779d3de7eeSOjaswin Mujoo 	if (RB_EMPTY_ROOT(&ei->i_prealloc_node)) {
47789d3de7eeSOjaswin Mujoo 		goto try_group_pa;
47799d3de7eeSOjaswin Mujoo 	}
47809d3de7eeSOjaswin Mujoo 
47819d3de7eeSOjaswin Mujoo 	/*
47829d3de7eeSOjaswin Mujoo 	 * Step 1: Find a pa with logical start immediately adjacent to the
47839d3de7eeSOjaswin Mujoo 	 * original logical start. This could be on the left or right.
47849d3de7eeSOjaswin Mujoo 	 *
47859d3de7eeSOjaswin Mujoo 	 * (tmp_pa->pa_lstart never changes so we can skip locking for it).
47869d3de7eeSOjaswin Mujoo 	 */
478738727786SOjaswin Mujoo 	for (iter = ei->i_prealloc_node.rb_node; iter;
478838727786SOjaswin Mujoo 	     iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
47899d3de7eeSOjaswin Mujoo 					    tmp_pa->pa_lstart, iter)) {
479038727786SOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
479138727786SOjaswin Mujoo 				  pa_node.inode_node);
47929d3de7eeSOjaswin Mujoo 	}
4793c9de560dSAlex Tomas 
47949d3de7eeSOjaswin Mujoo 	/*
47959d3de7eeSOjaswin Mujoo 	 * Step 2: The adjacent pa might be to the right of logical start, find
47969d3de7eeSOjaswin Mujoo 	 * the left adjacent pa. After this step we'd have a valid tmp_pa whose
47979d3de7eeSOjaswin Mujoo 	 * logical start is towards the left of original request's logical start
47989d3de7eeSOjaswin Mujoo 	 */
47999d3de7eeSOjaswin Mujoo 	if (tmp_pa->pa_lstart > ac->ac_o_ex.fe_logical) {
48009d3de7eeSOjaswin Mujoo 		struct rb_node *tmp;
48019d3de7eeSOjaswin Mujoo 		tmp = rb_prev(&tmp_pa->pa_node.inode_node);
4802bcf43499SOjaswin Mujoo 
48039d3de7eeSOjaswin Mujoo 		if (tmp) {
48049d3de7eeSOjaswin Mujoo 			tmp_pa = rb_entry(tmp, struct ext4_prealloc_space,
48059d3de7eeSOjaswin Mujoo 					    pa_node.inode_node);
48069d3de7eeSOjaswin Mujoo 		} else {
48079d3de7eeSOjaswin Mujoo 			/*
48089d3de7eeSOjaswin Mujoo 			 * If there is no adjacent pa to the left then finding
48099d3de7eeSOjaswin Mujoo 			 * an overlapping pa is not possible hence stop searching
48109d3de7eeSOjaswin Mujoo 			 * inode pa tree
48119d3de7eeSOjaswin Mujoo 			 */
48129d3de7eeSOjaswin Mujoo 			goto try_group_pa;
48139d3de7eeSOjaswin Mujoo 		}
48149d3de7eeSOjaswin Mujoo 	}
48159d3de7eeSOjaswin Mujoo 
48169d3de7eeSOjaswin Mujoo 	BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
48179d3de7eeSOjaswin Mujoo 
48189d3de7eeSOjaswin Mujoo 	/*
48199d3de7eeSOjaswin Mujoo 	 * Step 3: If the left adjacent pa is deleted, keep moving left to find
48209d3de7eeSOjaswin Mujoo 	 * the first non deleted adjacent pa. After this step we should have a
48219d3de7eeSOjaswin Mujoo 	 * valid tmp_pa which is guaranteed to be non deleted.
48229d3de7eeSOjaswin Mujoo 	 */
48239d3de7eeSOjaswin Mujoo 	for (iter = &tmp_pa->pa_node.inode_node;; iter = rb_prev(iter)) {
48249d3de7eeSOjaswin Mujoo 		if (!iter) {
48259d3de7eeSOjaswin Mujoo 			/*
48269d3de7eeSOjaswin Mujoo 			 * no non deleted left adjacent pa, so stop searching
48279d3de7eeSOjaswin Mujoo 			 * inode pa tree
48289d3de7eeSOjaswin Mujoo 			 */
48299d3de7eeSOjaswin Mujoo 			goto try_group_pa;
48309d3de7eeSOjaswin Mujoo 		}
48319d3de7eeSOjaswin Mujoo 		tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
48329d3de7eeSOjaswin Mujoo 				  pa_node.inode_node);
48339d3de7eeSOjaswin Mujoo 		spin_lock(&tmp_pa->pa_lock);
48349d3de7eeSOjaswin Mujoo 		if (tmp_pa->pa_deleted == 0) {
48359d3de7eeSOjaswin Mujoo 			/*
48369d3de7eeSOjaswin Mujoo 			 * We will keep holding the pa_lock from
48379d3de7eeSOjaswin Mujoo 			 * this point on because we don't want group discard
48389d3de7eeSOjaswin Mujoo 			 * to delete this pa underneath us. Since group
48399d3de7eeSOjaswin Mujoo 			 * discard is anyways an ENOSPC operation it
48409d3de7eeSOjaswin Mujoo 			 * should be okay for it to wait a few more cycles.
48419d3de7eeSOjaswin Mujoo 			 */
48429d3de7eeSOjaswin Mujoo 			break;
48439d3de7eeSOjaswin Mujoo 		} else {
48449d3de7eeSOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
48459d3de7eeSOjaswin Mujoo 		}
48469d3de7eeSOjaswin Mujoo 	}
48479d3de7eeSOjaswin Mujoo 
48489d3de7eeSOjaswin Mujoo 	BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
48499d3de7eeSOjaswin Mujoo 	BUG_ON(tmp_pa->pa_deleted == 1);
48509d3de7eeSOjaswin Mujoo 
48519d3de7eeSOjaswin Mujoo 	/*
48529d3de7eeSOjaswin Mujoo 	 * Step 4: We now have the non deleted left adjacent pa. Only this
48539d3de7eeSOjaswin Mujoo 	 * pa can possibly satisfy the request hence check if it overlaps
48549d3de7eeSOjaswin Mujoo 	 * original logical start and stop searching if it doesn't.
48559d3de7eeSOjaswin Mujoo 	 */
485643bbddc0SBaokun Li 	if (ac->ac_o_ex.fe_logical >= pa_logical_end(sbi, tmp_pa)) {
48579d3de7eeSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
48589d3de7eeSOjaswin Mujoo 		goto try_group_pa;
48599d3de7eeSOjaswin Mujoo 	}
4860c9de560dSAlex Tomas 
4861fb0a387dSEric Sandeen 	/* non-extent files can't have physical blocks past 2^32 */
486212e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
4863bcf43499SOjaswin Mujoo 	    (tmp_pa->pa_pstart + EXT4_C2B(sbi, tmp_pa->pa_len) >
4864e86a7182SOjaswin Mujoo 	     EXT4_MAX_BLOCK_FILE_PHYS)) {
4865e86a7182SOjaswin Mujoo 		/*
48669d3de7eeSOjaswin Mujoo 		 * Since PAs don't overlap, we won't find any other PA to
48679d3de7eeSOjaswin Mujoo 		 * satisfy this.
4868e86a7182SOjaswin Mujoo 		 */
48699d3de7eeSOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
48709d3de7eeSOjaswin Mujoo 		goto try_group_pa;
4871e86a7182SOjaswin Mujoo 	}
4872fb0a387dSEric Sandeen 
48739d3de7eeSOjaswin Mujoo 	if (tmp_pa->pa_free && likely(ext4_mb_pa_goal_check(ac, tmp_pa))) {
4874bcf43499SOjaswin Mujoo 		atomic_inc(&tmp_pa->pa_count);
4875bcf43499SOjaswin Mujoo 		ext4_mb_use_inode_pa(ac, tmp_pa);
4876bcf43499SOjaswin Mujoo 		spin_unlock(&tmp_pa->pa_lock);
487738727786SOjaswin Mujoo 		read_unlock(&ei->i_prealloc_lock);
48784fca8f07SRitesh Harjani 		return true;
48799d3de7eeSOjaswin Mujoo 	} else {
48809d3de7eeSOjaswin Mujoo 		/*
48819d3de7eeSOjaswin Mujoo 		 * We found a valid overlapping pa but couldn't use it because
48829d3de7eeSOjaswin Mujoo 		 * it had no free blocks. This should ideally never happen
48839d3de7eeSOjaswin Mujoo 		 * because:
48849d3de7eeSOjaswin Mujoo 		 *
48859d3de7eeSOjaswin Mujoo 		 * 1. When a new inode pa is added to rbtree it must have
48869d3de7eeSOjaswin Mujoo 		 *    pa_free > 0 since otherwise we won't actually need
48879d3de7eeSOjaswin Mujoo 		 *    preallocation.
48889d3de7eeSOjaswin Mujoo 		 *
48899d3de7eeSOjaswin Mujoo 		 * 2. An inode pa that is in the rbtree can only have it's
48909d3de7eeSOjaswin Mujoo 		 *    pa_free become zero when another thread calls:
48919d3de7eeSOjaswin Mujoo 		 *      ext4_mb_new_blocks
48929d3de7eeSOjaswin Mujoo 		 *       ext4_mb_use_preallocated
48939d3de7eeSOjaswin Mujoo 		 *        ext4_mb_use_inode_pa
48949d3de7eeSOjaswin Mujoo 		 *
48959d3de7eeSOjaswin Mujoo 		 * 3. Further, after the above calls make pa_free == 0, we will
48969d3de7eeSOjaswin Mujoo 		 *    immediately remove it from the rbtree in:
48979d3de7eeSOjaswin Mujoo 		 *      ext4_mb_new_blocks
48989d3de7eeSOjaswin Mujoo 		 *       ext4_mb_release_context
48999d3de7eeSOjaswin Mujoo 		 *        ext4_mb_put_pa
49009d3de7eeSOjaswin Mujoo 		 *
49019d3de7eeSOjaswin Mujoo 		 * 4. Since the pa_free becoming 0 and pa_free getting removed
49029d3de7eeSOjaswin Mujoo 		 * from tree both happen in ext4_mb_new_blocks, which is always
49039d3de7eeSOjaswin Mujoo 		 * called with i_data_sem held for data allocations, we can be
49049d3de7eeSOjaswin Mujoo 		 * sure that another process will never see a pa in rbtree with
49059d3de7eeSOjaswin Mujoo 		 * pa_free == 0.
49069d3de7eeSOjaswin Mujoo 		 */
49079d3de7eeSOjaswin Mujoo 		WARN_ON_ONCE(tmp_pa->pa_free == 0);
4908c9de560dSAlex Tomas 	}
4909bcf43499SOjaswin Mujoo 	spin_unlock(&tmp_pa->pa_lock);
49109d3de7eeSOjaswin Mujoo try_group_pa:
491138727786SOjaswin Mujoo 	read_unlock(&ei->i_prealloc_lock);
4912c9de560dSAlex Tomas 
4913c9de560dSAlex Tomas 	/* can we use group allocation? */
4914c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
49154fca8f07SRitesh Harjani 		return false;
4916c9de560dSAlex Tomas 
4917c9de560dSAlex Tomas 	/* inode may have no locality group for some reason */
4918c9de560dSAlex Tomas 	lg = ac->ac_lg;
4919c9de560dSAlex Tomas 	if (lg == NULL)
49204fca8f07SRitesh Harjani 		return false;
49216be2ded1SAneesh Kumar K.V 	order  = fls(ac->ac_o_ex.fe_len) - 1;
49226be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
49236be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
49246be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
4925c9de560dSAlex Tomas 
4926bda00de7SAkinobu Mita 	goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
49275e745b04SAneesh Kumar K.V 	/*
49285e745b04SAneesh Kumar K.V 	 * search for the prealloc space that is having
49295e745b04SAneesh Kumar K.V 	 * minimal distance from the goal block.
49305e745b04SAneesh Kumar K.V 	 */
49316be2ded1SAneesh Kumar K.V 	for (i = order; i < PREALLOC_TB_SIZE; i++) {
4932c9de560dSAlex Tomas 		rcu_read_lock();
4933bcf43499SOjaswin Mujoo 		list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[i],
4934a8e38fd3SOjaswin Mujoo 					pa_node.lg_list) {
4935bcf43499SOjaswin Mujoo 			spin_lock(&tmp_pa->pa_lock);
4936bcf43499SOjaswin Mujoo 			if (tmp_pa->pa_deleted == 0 &&
4937bcf43499SOjaswin Mujoo 					tmp_pa->pa_free >= ac->ac_o_ex.fe_len) {
49385e745b04SAneesh Kumar K.V 
49395e745b04SAneesh Kumar K.V 				cpa = ext4_mb_check_group_pa(goal_block,
4940bcf43499SOjaswin Mujoo 								tmp_pa, cpa);
49415e745b04SAneesh Kumar K.V 			}
4942bcf43499SOjaswin Mujoo 			spin_unlock(&tmp_pa->pa_lock);
49435e745b04SAneesh Kumar K.V 		}
49445e745b04SAneesh Kumar K.V 		rcu_read_unlock();
49455e745b04SAneesh Kumar K.V 	}
49465e745b04SAneesh Kumar K.V 	if (cpa) {
49475e745b04SAneesh Kumar K.V 		ext4_mb_use_group_pa(ac, cpa);
49484fca8f07SRitesh Harjani 		return true;
4949c9de560dSAlex Tomas 	}
49504fca8f07SRitesh Harjani 	return false;
4951c9de560dSAlex Tomas }
4952c9de560dSAlex Tomas 
4953c9de560dSAlex Tomas /*
49547a2fcbf7SAneesh Kumar K.V  * the function goes through all block freed in the group
49557a2fcbf7SAneesh Kumar K.V  * but not yet committed and marks them used in in-core bitmap.
49567a2fcbf7SAneesh Kumar K.V  * buddy must be generated from this bitmap
4957955ce5f5SAneesh Kumar K.V  * Need to be called with the ext4 group lock held
49587a2fcbf7SAneesh Kumar K.V  */
49597a2fcbf7SAneesh Kumar K.V static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
49607a2fcbf7SAneesh Kumar K.V 						ext4_group_t group)
49617a2fcbf7SAneesh Kumar K.V {
49627a2fcbf7SAneesh Kumar K.V 	struct rb_node *n;
49637a2fcbf7SAneesh Kumar K.V 	struct ext4_group_info *grp;
49647a2fcbf7SAneesh Kumar K.V 	struct ext4_free_data *entry;
49657a2fcbf7SAneesh Kumar K.V 
49667a2fcbf7SAneesh Kumar K.V 	grp = ext4_get_group_info(sb, group);
49675354b2afSTheodore Ts'o 	if (!grp)
49685354b2afSTheodore Ts'o 		return;
49697a2fcbf7SAneesh Kumar K.V 	n = rb_first(&(grp->bb_free_root));
49707a2fcbf7SAneesh Kumar K.V 
49717a2fcbf7SAneesh Kumar K.V 	while (n) {
497218aadd47SBobi Jam 		entry = rb_entry(n, struct ext4_free_data, efd_node);
4973123e3016SRitesh Harjani 		mb_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
49747a2fcbf7SAneesh Kumar K.V 		n = rb_next(n);
49757a2fcbf7SAneesh Kumar K.V 	}
49767a2fcbf7SAneesh Kumar K.V }
49777a2fcbf7SAneesh Kumar K.V 
49787a2fcbf7SAneesh Kumar K.V /*
4979c9de560dSAlex Tomas  * the function goes through all preallocation in this group and marks them
4980c9de560dSAlex Tomas  * used in in-core bitmap. buddy must be generated from this bitmap
4981955ce5f5SAneesh Kumar K.V  * Need to be called with ext4 group lock held
4982c9de560dSAlex Tomas  */
4983089ceeccSEric Sandeen static noinline_for_stack
4984089ceeccSEric Sandeen void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
4985c9de560dSAlex Tomas 					ext4_group_t group)
4986c9de560dSAlex Tomas {
4987c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
4988c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
4989c9de560dSAlex Tomas 	struct list_head *cur;
4990c9de560dSAlex Tomas 	ext4_group_t groupnr;
4991c9de560dSAlex Tomas 	ext4_grpblk_t start;
4992c9de560dSAlex Tomas 	int preallocated = 0;
4993c9de560dSAlex Tomas 	int len;
4994c9de560dSAlex Tomas 
49955354b2afSTheodore Ts'o 	if (!grp)
49965354b2afSTheodore Ts'o 		return;
49975354b2afSTheodore Ts'o 
4998c9de560dSAlex Tomas 	/* all form of preallocation discards first load group,
4999c9de560dSAlex Tomas 	 * so the only competing code is preallocation use.
5000c9de560dSAlex Tomas 	 * we don't need any locking here
5001c9de560dSAlex Tomas 	 * notice we do NOT ignore preallocations with pa_deleted
5002c9de560dSAlex Tomas 	 * otherwise we could leave used blocks available for
5003c9de560dSAlex Tomas 	 * allocation in buddy when concurrent ext4_mb_put_pa()
5004c9de560dSAlex Tomas 	 * is dropping preallocation
5005c9de560dSAlex Tomas 	 */
5006c9de560dSAlex Tomas 	list_for_each(cur, &grp->bb_prealloc_list) {
5007c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
5008c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
5009c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5010c9de560dSAlex Tomas 					     &groupnr, &start);
5011c9de560dSAlex Tomas 		len = pa->pa_len;
5012c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
5013c9de560dSAlex Tomas 		if (unlikely(len == 0))
5014c9de560dSAlex Tomas 			continue;
5015c9de560dSAlex Tomas 		BUG_ON(groupnr != group);
5016123e3016SRitesh Harjani 		mb_set_bits(bitmap, start, len);
5017c9de560dSAlex Tomas 		preallocated += len;
5018c9de560dSAlex Tomas 	}
5019d3df1453SRitesh Harjani 	mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
5020c9de560dSAlex Tomas }
5021c9de560dSAlex Tomas 
502227bc446eSbrookxu static void ext4_mb_mark_pa_deleted(struct super_block *sb,
502327bc446eSbrookxu 				    struct ext4_prealloc_space *pa)
502427bc446eSbrookxu {
502527bc446eSbrookxu 	struct ext4_inode_info *ei;
502627bc446eSbrookxu 
502727bc446eSbrookxu 	if (pa->pa_deleted) {
502827bc446eSbrookxu 		ext4_warning(sb, "deleted pa, type:%d, pblk:%llu, lblk:%u, len:%d\n",
502927bc446eSbrookxu 			     pa->pa_type, pa->pa_pstart, pa->pa_lstart,
503027bc446eSbrookxu 			     pa->pa_len);
503127bc446eSbrookxu 		return;
503227bc446eSbrookxu 	}
503327bc446eSbrookxu 
503427bc446eSbrookxu 	pa->pa_deleted = 1;
503527bc446eSbrookxu 
503627bc446eSbrookxu 	if (pa->pa_type == MB_INODE_PA) {
503727bc446eSbrookxu 		ei = EXT4_I(pa->pa_inode);
503827bc446eSbrookxu 		atomic_dec(&ei->i_prealloc_active);
503927bc446eSbrookxu 	}
504027bc446eSbrookxu }
504127bc446eSbrookxu 
504282089725SOjaswin Mujoo static inline void ext4_mb_pa_free(struct ext4_prealloc_space *pa)
5043c9de560dSAlex Tomas {
504482089725SOjaswin Mujoo 	BUG_ON(!pa);
50454e8d2139SJunho Ryu 	BUG_ON(atomic_read(&pa->pa_count));
50464e8d2139SJunho Ryu 	BUG_ON(pa->pa_deleted == 0);
5047c9de560dSAlex Tomas 	kmem_cache_free(ext4_pspace_cachep, pa);
5048c9de560dSAlex Tomas }
5049c9de560dSAlex Tomas 
505082089725SOjaswin Mujoo static void ext4_mb_pa_callback(struct rcu_head *head)
505182089725SOjaswin Mujoo {
505282089725SOjaswin Mujoo 	struct ext4_prealloc_space *pa;
505382089725SOjaswin Mujoo 
505482089725SOjaswin Mujoo 	pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
505582089725SOjaswin Mujoo 	ext4_mb_pa_free(pa);
505682089725SOjaswin Mujoo }
505782089725SOjaswin Mujoo 
5058c9de560dSAlex Tomas /*
5059c9de560dSAlex Tomas  * drops a reference to preallocated space descriptor
5060c9de560dSAlex Tomas  * if this was the last reference and the space is consumed
5061c9de560dSAlex Tomas  */
5062c9de560dSAlex Tomas static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
5063c9de560dSAlex Tomas 			struct super_block *sb, struct ext4_prealloc_space *pa)
5064c9de560dSAlex Tomas {
5065a9df9a49STheodore Ts'o 	ext4_group_t grp;
5066d33a1976SEric Sandeen 	ext4_fsblk_t grp_blk;
506738727786SOjaswin Mujoo 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
5068c9de560dSAlex Tomas 
5069c9de560dSAlex Tomas 	/* in this short window concurrent discard can set pa_deleted */
5070c9de560dSAlex Tomas 	spin_lock(&pa->pa_lock);
50714e8d2139SJunho Ryu 	if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
50724e8d2139SJunho Ryu 		spin_unlock(&pa->pa_lock);
50734e8d2139SJunho Ryu 		return;
50744e8d2139SJunho Ryu 	}
50754e8d2139SJunho Ryu 
5076c9de560dSAlex Tomas 	if (pa->pa_deleted == 1) {
5077c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
5078c9de560dSAlex Tomas 		return;
5079c9de560dSAlex Tomas 	}
5080c9de560dSAlex Tomas 
508127bc446eSbrookxu 	ext4_mb_mark_pa_deleted(sb, pa);
5082c9de560dSAlex Tomas 	spin_unlock(&pa->pa_lock);
5083c9de560dSAlex Tomas 
5084d33a1976SEric Sandeen 	grp_blk = pa->pa_pstart;
5085cc0fb9adSAneesh Kumar K.V 	/*
5086cc0fb9adSAneesh Kumar K.V 	 * If doing group-based preallocation, pa_pstart may be in the
5087cc0fb9adSAneesh Kumar K.V 	 * next group when pa is used up
5088cc0fb9adSAneesh Kumar K.V 	 */
5089cc0fb9adSAneesh Kumar K.V 	if (pa->pa_type == MB_GROUP_PA)
5090d33a1976SEric Sandeen 		grp_blk--;
5091d33a1976SEric Sandeen 
5092bd86298eSLukas Czerner 	grp = ext4_get_group_number(sb, grp_blk);
5093c9de560dSAlex Tomas 
5094c9de560dSAlex Tomas 	/*
5095c9de560dSAlex Tomas 	 * possible race:
5096c9de560dSAlex Tomas 	 *
5097c9de560dSAlex Tomas 	 *  P1 (buddy init)			P2 (regular allocation)
5098c9de560dSAlex Tomas 	 *					find block B in PA
5099c9de560dSAlex Tomas 	 *  copy on-disk bitmap to buddy
5100c9de560dSAlex Tomas 	 *  					mark B in on-disk bitmap
5101c9de560dSAlex Tomas 	 *					drop PA from group
5102c9de560dSAlex Tomas 	 *  mark all PAs in buddy
5103c9de560dSAlex Tomas 	 *
5104c9de560dSAlex Tomas 	 * thus, P1 initializes buddy with B available. to prevent this
5105c9de560dSAlex Tomas 	 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
5106c9de560dSAlex Tomas 	 * against that pair
5107c9de560dSAlex Tomas 	 */
5108c9de560dSAlex Tomas 	ext4_lock_group(sb, grp);
5109c9de560dSAlex Tomas 	list_del(&pa->pa_group_list);
5110c9de560dSAlex Tomas 	ext4_unlock_group(sb, grp);
5111c9de560dSAlex Tomas 
5112a8e38fd3SOjaswin Mujoo 	if (pa->pa_type == MB_INODE_PA) {
511338727786SOjaswin Mujoo 		write_lock(pa->pa_node_lock.inode_lock);
511438727786SOjaswin Mujoo 		rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
511538727786SOjaswin Mujoo 		write_unlock(pa->pa_node_lock.inode_lock);
511638727786SOjaswin Mujoo 		ext4_mb_pa_free(pa);
5117a8e38fd3SOjaswin Mujoo 	} else {
5118a8e38fd3SOjaswin Mujoo 		spin_lock(pa->pa_node_lock.lg_lock);
5119a8e38fd3SOjaswin Mujoo 		list_del_rcu(&pa->pa_node.lg_list);
5120a8e38fd3SOjaswin Mujoo 		spin_unlock(pa->pa_node_lock.lg_lock);
512138727786SOjaswin Mujoo 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
512238727786SOjaswin Mujoo 	}
5123a8e38fd3SOjaswin Mujoo }
5124c9de560dSAlex Tomas 
512538727786SOjaswin Mujoo static void ext4_mb_pa_rb_insert(struct rb_root *root, struct rb_node *new)
512638727786SOjaswin Mujoo {
512738727786SOjaswin Mujoo 	struct rb_node **iter = &root->rb_node, *parent = NULL;
512838727786SOjaswin Mujoo 	struct ext4_prealloc_space *iter_pa, *new_pa;
512938727786SOjaswin Mujoo 	ext4_lblk_t iter_start, new_start;
513038727786SOjaswin Mujoo 
513138727786SOjaswin Mujoo 	while (*iter) {
513238727786SOjaswin Mujoo 		iter_pa = rb_entry(*iter, struct ext4_prealloc_space,
513338727786SOjaswin Mujoo 				   pa_node.inode_node);
513438727786SOjaswin Mujoo 		new_pa = rb_entry(new, struct ext4_prealloc_space,
513538727786SOjaswin Mujoo 				   pa_node.inode_node);
513638727786SOjaswin Mujoo 		iter_start = iter_pa->pa_lstart;
513738727786SOjaswin Mujoo 		new_start = new_pa->pa_lstart;
513838727786SOjaswin Mujoo 
513938727786SOjaswin Mujoo 		parent = *iter;
514038727786SOjaswin Mujoo 		if (new_start < iter_start)
514138727786SOjaswin Mujoo 			iter = &((*iter)->rb_left);
514238727786SOjaswin Mujoo 		else
514338727786SOjaswin Mujoo 			iter = &((*iter)->rb_right);
514438727786SOjaswin Mujoo 	}
514538727786SOjaswin Mujoo 
514638727786SOjaswin Mujoo 	rb_link_node(new, parent, iter);
514738727786SOjaswin Mujoo 	rb_insert_color(new, root);
5148c9de560dSAlex Tomas }
5149c9de560dSAlex Tomas 
5150c9de560dSAlex Tomas /*
5151c9de560dSAlex Tomas  * creates new preallocated space for given inode
5152c9de560dSAlex Tomas  */
515353f86b17SRitesh Harjani static noinline_for_stack void
51544ddfef7bSEric Sandeen ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
5155c9de560dSAlex Tomas {
5156c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
515753accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5158c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
5159c9de560dSAlex Tomas 	struct ext4_group_info *grp;
5160c9de560dSAlex Tomas 	struct ext4_inode_info *ei;
5161c9de560dSAlex Tomas 
5162c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
5163c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5164c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5165c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
516653f86b17SRitesh Harjani 	BUG_ON(ac->ac_pa == NULL);
5167c9de560dSAlex Tomas 
516853f86b17SRitesh Harjani 	pa = ac->ac_pa;
5169c9de560dSAlex Tomas 
51707e170922SOjaswin Mujoo 	if (ac->ac_b_ex.fe_len < ac->ac_orig_goal_len) {
5171bc056e71SBaokun Li 		struct ext4_free_extent ex = {
5172bc056e71SBaokun Li 			.fe_logical = ac->ac_g_ex.fe_logical,
5173bc056e71SBaokun Li 			.fe_len = ac->ac_orig_goal_len,
5174bc056e71SBaokun Li 		};
5175bc056e71SBaokun Li 		loff_t orig_goal_end = extent_logical_end(sbi, &ex);
5176c9de560dSAlex Tomas 
5177c9de560dSAlex Tomas 		/* we can't allocate as much as normalizer wants.
5178c9de560dSAlex Tomas 		 * so, found space must get proper lstart
5179c9de560dSAlex Tomas 		 * to cover original request */
5180c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
5181c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
5182c9de560dSAlex Tomas 
518393cdf49fSOjaswin Mujoo 		/*
518493cdf49fSOjaswin Mujoo 		 * Use the below logic for adjusting best extent as it keeps
518593cdf49fSOjaswin Mujoo 		 * fragmentation in check while ensuring logical range of best
518693cdf49fSOjaswin Mujoo 		 * extent doesn't overflow out of goal extent:
518793cdf49fSOjaswin Mujoo 		 *
51887e170922SOjaswin Mujoo 		 * 1. Check if best ex can be kept at end of goal (before
51897e170922SOjaswin Mujoo 		 *    cr_best_avail trimmed it) and still cover original start
519093cdf49fSOjaswin Mujoo 		 * 2. Else, check if best ex can be kept at start of goal and
519193cdf49fSOjaswin Mujoo 		 *    still cover original start
519293cdf49fSOjaswin Mujoo 		 * 3. Else, keep the best ex at start of original request.
519393cdf49fSOjaswin Mujoo 		 */
5194bc056e71SBaokun Li 		ex.fe_len = ac->ac_b_ex.fe_len;
5195bc056e71SBaokun Li 
5196bc056e71SBaokun Li 		ex.fe_logical = orig_goal_end - EXT4_C2B(sbi, ex.fe_len);
5197bc056e71SBaokun Li 		if (ac->ac_o_ex.fe_logical >= ex.fe_logical)
519893cdf49fSOjaswin Mujoo 			goto adjust_bex;
5199c9de560dSAlex Tomas 
5200bc056e71SBaokun Li 		ex.fe_logical = ac->ac_g_ex.fe_logical;
5201bc056e71SBaokun Li 		if (ac->ac_o_ex.fe_logical < extent_logical_end(sbi, &ex))
520293cdf49fSOjaswin Mujoo 			goto adjust_bex;
5203c9de560dSAlex Tomas 
5204bc056e71SBaokun Li 		ex.fe_logical = ac->ac_o_ex.fe_logical;
520593cdf49fSOjaswin Mujoo adjust_bex:
5206bc056e71SBaokun Li 		ac->ac_b_ex.fe_logical = ex.fe_logical;
5207c9de560dSAlex Tomas 
5208c9de560dSAlex Tomas 		BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
5209c9de560dSAlex Tomas 		BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
5210bc056e71SBaokun Li 		BUG_ON(extent_logical_end(sbi, &ex) > orig_goal_end);
5211c9de560dSAlex Tomas 	}
5212c9de560dSAlex Tomas 
5213c9de560dSAlex Tomas 	pa->pa_lstart = ac->ac_b_ex.fe_logical;
5214c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5215c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
5216c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
5217c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
5218d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
5219c9de560dSAlex Tomas 	pa->pa_deleted = 0;
5220cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_INODE_PA;
5221c9de560dSAlex Tomas 
5222d3df1453SRitesh Harjani 	mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5223d3df1453SRitesh Harjani 		 pa->pa_len, pa->pa_lstart);
52249bffad1eSTheodore Ts'o 	trace_ext4_mb_new_inode_pa(ac, pa);
5225c9de560dSAlex Tomas 
522653accfa9STheodore Ts'o 	atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
5227abc075d4SKemeng Shi 	ext4_mb_use_inode_pa(ac, pa);
5228c9de560dSAlex Tomas 
5229c9de560dSAlex Tomas 	ei = EXT4_I(ac->ac_inode);
5230c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
52315354b2afSTheodore Ts'o 	if (!grp)
52325354b2afSTheodore Ts'o 		return;
5233c9de560dSAlex Tomas 
5234a8e38fd3SOjaswin Mujoo 	pa->pa_node_lock.inode_lock = &ei->i_prealloc_lock;
5235c9de560dSAlex Tomas 	pa->pa_inode = ac->ac_inode;
5236c9de560dSAlex Tomas 
5237c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5238c9de560dSAlex Tomas 
523938727786SOjaswin Mujoo 	write_lock(pa->pa_node_lock.inode_lock);
524038727786SOjaswin Mujoo 	ext4_mb_pa_rb_insert(&ei->i_prealloc_node, &pa->pa_node.inode_node);
524138727786SOjaswin Mujoo 	write_unlock(pa->pa_node_lock.inode_lock);
524227bc446eSbrookxu 	atomic_inc(&ei->i_prealloc_active);
5243c9de560dSAlex Tomas }
5244c9de560dSAlex Tomas 
5245c9de560dSAlex Tomas /*
5246c9de560dSAlex Tomas  * creates new preallocated space for locality group inodes belongs to
5247c9de560dSAlex Tomas  */
524853f86b17SRitesh Harjani static noinline_for_stack void
52494ddfef7bSEric Sandeen ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
5250c9de560dSAlex Tomas {
5251c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
5252c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
5253c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
5254c9de560dSAlex Tomas 	struct ext4_group_info *grp;
5255c9de560dSAlex Tomas 
5256c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
5257c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5258c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5259c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
526053f86b17SRitesh Harjani 	BUG_ON(ac->ac_pa == NULL);
5261c9de560dSAlex Tomas 
526253f86b17SRitesh Harjani 	pa = ac->ac_pa;
5263c9de560dSAlex Tomas 
5264c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5265c9de560dSAlex Tomas 	pa->pa_lstart = pa->pa_pstart;
5266c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
5267c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
5268c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
5269a8e38fd3SOjaswin Mujoo 	INIT_LIST_HEAD(&pa->pa_node.lg_list);
5270d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
5271c9de560dSAlex Tomas 	pa->pa_deleted = 0;
5272cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_GROUP_PA;
5273c9de560dSAlex Tomas 
5274d3df1453SRitesh Harjani 	mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5275d3df1453SRitesh Harjani 		 pa->pa_len, pa->pa_lstart);
52769bffad1eSTheodore Ts'o 	trace_ext4_mb_new_group_pa(ac, pa);
5277c9de560dSAlex Tomas 
5278c9de560dSAlex Tomas 	ext4_mb_use_group_pa(ac, pa);
5279c9de560dSAlex Tomas 	atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
5280c9de560dSAlex Tomas 
5281c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
52825354b2afSTheodore Ts'o 	if (!grp)
52835354b2afSTheodore Ts'o 		return;
5284c9de560dSAlex Tomas 	lg = ac->ac_lg;
5285c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
5286c9de560dSAlex Tomas 
5287a8e38fd3SOjaswin Mujoo 	pa->pa_node_lock.lg_lock = &lg->lg_prealloc_lock;
5288c9de560dSAlex Tomas 	pa->pa_inode = NULL;
5289c9de560dSAlex Tomas 
5290c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5291c9de560dSAlex Tomas 
52926be2ded1SAneesh Kumar K.V 	/*
52936be2ded1SAneesh Kumar K.V 	 * We will later add the new pa to the right bucket
52946be2ded1SAneesh Kumar K.V 	 * after updating the pa_free in ext4_mb_release_context
52956be2ded1SAneesh Kumar K.V 	 */
5296c9de560dSAlex Tomas }
5297c9de560dSAlex Tomas 
529853f86b17SRitesh Harjani static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
5299c9de560dSAlex Tomas {
5300c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
530153f86b17SRitesh Harjani 		ext4_mb_new_group_pa(ac);
5302c9de560dSAlex Tomas 	else
530353f86b17SRitesh Harjani 		ext4_mb_new_inode_pa(ac);
5304c9de560dSAlex Tomas }
5305c9de560dSAlex Tomas 
5306c9de560dSAlex Tomas /*
5307c9de560dSAlex Tomas  * finds all unused blocks in on-disk bitmap, frees them in
5308c9de560dSAlex Tomas  * in-core bitmap and buddy.
5309c9de560dSAlex Tomas  * @pa must be unlinked from inode and group lists, so that
5310c9de560dSAlex Tomas  * nobody else can find/use it.
5311c9de560dSAlex Tomas  * the caller MUST hold group/inode locks.
5312c9de560dSAlex Tomas  * TODO: optimize the case when there are no in-core structures yet
5313c9de560dSAlex Tomas  */
53144ddfef7bSEric Sandeen static noinline_for_stack int
53154ddfef7bSEric Sandeen ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
53163e1e5f50SEric Sandeen 			struct ext4_prealloc_space *pa)
5317c9de560dSAlex Tomas {
5318c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
5319c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5320498e5f24STheodore Ts'o 	unsigned int end;
5321498e5f24STheodore Ts'o 	unsigned int next;
5322c9de560dSAlex Tomas 	ext4_group_t group;
5323c9de560dSAlex Tomas 	ext4_grpblk_t bit;
5324ba80b101STheodore Ts'o 	unsigned long long grp_blk_start;
5325c9de560dSAlex Tomas 	int free = 0;
5326c9de560dSAlex Tomas 
5327c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
5328c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
532953accfa9STheodore Ts'o 	grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
5330c9de560dSAlex Tomas 	BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
5331c9de560dSAlex Tomas 	end = bit + pa->pa_len;
5332c9de560dSAlex Tomas 
5333c9de560dSAlex Tomas 	while (bit < end) {
5334ffad0a44SAneesh Kumar K.V 		bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
5335c9de560dSAlex Tomas 		if (bit >= end)
5336c9de560dSAlex Tomas 			break;
5337ffad0a44SAneesh Kumar K.V 		next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
5338d3df1453SRitesh Harjani 		mb_debug(sb, "free preallocated %u/%u in group %u\n",
53395a0790c2SAndi Kleen 			 (unsigned) ext4_group_first_block_no(sb, group) + bit,
53405a0790c2SAndi Kleen 			 (unsigned) next - bit, (unsigned) group);
5341c9de560dSAlex Tomas 		free += next - bit;
5342c9de560dSAlex Tomas 
53433e1e5f50SEric Sandeen 		trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
534453accfa9STheodore Ts'o 		trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
534553accfa9STheodore Ts'o 						    EXT4_C2B(sbi, bit)),
5346a9c667f8SLukas Czerner 					       next - bit);
5347c9de560dSAlex Tomas 		mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
5348c9de560dSAlex Tomas 		bit = next + 1;
5349c9de560dSAlex Tomas 	}
5350c9de560dSAlex Tomas 	if (free != pa->pa_free) {
53519d8b9ec4STheodore Ts'o 		ext4_msg(e4b->bd_sb, KERN_CRIT,
535236bad423SRitesh Harjani 			 "pa %p: logic %lu, phys. %lu, len %d",
5353c9de560dSAlex Tomas 			 pa, (unsigned long) pa->pa_lstart,
5354c9de560dSAlex Tomas 			 (unsigned long) pa->pa_pstart,
535536bad423SRitesh Harjani 			 pa->pa_len);
5356e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
535726346ff6SAneesh Kumar K.V 					free, pa->pa_free);
5358e56eb659SAneesh Kumar K.V 		/*
5359e56eb659SAneesh Kumar K.V 		 * pa is already deleted so we use the value obtained
5360e56eb659SAneesh Kumar K.V 		 * from the bitmap and continue.
5361e56eb659SAneesh Kumar K.V 		 */
5362c9de560dSAlex Tomas 	}
5363c9de560dSAlex Tomas 	atomic_add(free, &sbi->s_mb_discarded);
5364c9de560dSAlex Tomas 
5365863c37fcSzhong jiang 	return 0;
5366c9de560dSAlex Tomas }
5367c9de560dSAlex Tomas 
53684ddfef7bSEric Sandeen static noinline_for_stack int
53694ddfef7bSEric Sandeen ext4_mb_release_group_pa(struct ext4_buddy *e4b,
53703e1e5f50SEric Sandeen 				struct ext4_prealloc_space *pa)
5371c9de560dSAlex Tomas {
5372c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
5373c9de560dSAlex Tomas 	ext4_group_t group;
5374c9de560dSAlex Tomas 	ext4_grpblk_t bit;
5375c9de560dSAlex Tomas 
537660e07cf5SYongqiang Yang 	trace_ext4_mb_release_group_pa(sb, pa);
5377c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
5378c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
5379463808f2STheodore Ts'o 	if (unlikely(group != e4b->bd_group && pa->pa_len != 0)) {
5380463808f2STheodore Ts'o 		ext4_warning(sb, "bad group: expected %u, group %u, pa_start %llu",
5381463808f2STheodore Ts'o 			     e4b->bd_group, group, pa->pa_pstart);
5382463808f2STheodore Ts'o 		return 0;
5383463808f2STheodore Ts'o 	}
5384c9de560dSAlex Tomas 	mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
5385c9de560dSAlex Tomas 	atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
53863e1e5f50SEric Sandeen 	trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
5387c9de560dSAlex Tomas 
5388c9de560dSAlex Tomas 	return 0;
5389c9de560dSAlex Tomas }
5390c9de560dSAlex Tomas 
5391c9de560dSAlex Tomas /*
5392c9de560dSAlex Tomas  * releases all preallocations in given group
5393c9de560dSAlex Tomas  *
5394c9de560dSAlex Tomas  * first, we need to decide discard policy:
5395c9de560dSAlex Tomas  * - when do we discard
5396c9de560dSAlex Tomas  *   1) ENOSPC
5397c9de560dSAlex Tomas  * - how many do we discard
5398c9de560dSAlex Tomas  *   1) how many requested
5399c9de560dSAlex Tomas  */
54004ddfef7bSEric Sandeen static noinline_for_stack int
54014ddfef7bSEric Sandeen ext4_mb_discard_group_preallocations(struct super_block *sb,
54028c80fb31SChunguang Xu 				     ext4_group_t group, int *busy)
5403c9de560dSAlex Tomas {
5404c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
5405c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
5406c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
54070f6bc579SRuan Jinjie 	LIST_HEAD(list);
5408c9de560dSAlex Tomas 	struct ext4_buddy e4b;
540938727786SOjaswin Mujoo 	struct ext4_inode_info *ei;
5410c9de560dSAlex Tomas 	int err;
54118c80fb31SChunguang Xu 	int free = 0;
5412c9de560dSAlex Tomas 
54135354b2afSTheodore Ts'o 	if (!grp)
54145354b2afSTheodore Ts'o 		return 0;
5415d3df1453SRitesh Harjani 	mb_debug(sb, "discard preallocation for group %u\n", group);
5416c9de560dSAlex Tomas 	if (list_empty(&grp->bb_prealloc_list))
5417bbc4ec77SRitesh Harjani 		goto out_dbg;
5418c9de560dSAlex Tomas 
5419574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, group);
54209008a58eSDarrick J. Wong 	if (IS_ERR(bitmap_bh)) {
54219008a58eSDarrick J. Wong 		err = PTR_ERR(bitmap_bh);
542254d3adbcSTheodore Ts'o 		ext4_error_err(sb, -err,
542354d3adbcSTheodore Ts'o 			       "Error %d reading block bitmap for %u",
54249008a58eSDarrick J. Wong 			       err, group);
5425bbc4ec77SRitesh Harjani 		goto out_dbg;
5426c9de560dSAlex Tomas 	}
5427c9de560dSAlex Tomas 
5428c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(sb, group, &e4b);
5429ce89f46cSAneesh Kumar K.V 	if (err) {
54309651e6b2SKonstantin Khlebnikov 		ext4_warning(sb, "Error %d loading buddy information for %u",
54319651e6b2SKonstantin Khlebnikov 			     err, group);
5432ce89f46cSAneesh Kumar K.V 		put_bh(bitmap_bh);
5433bbc4ec77SRitesh Harjani 		goto out_dbg;
5434ce89f46cSAneesh Kumar K.V 	}
5435c9de560dSAlex Tomas 
5436c9de560dSAlex Tomas 	ext4_lock_group(sb, group);
5437c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp,
5438c9de560dSAlex Tomas 				&grp->bb_prealloc_list, pa_group_list) {
5439c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
5440c9de560dSAlex Tomas 		if (atomic_read(&pa->pa_count)) {
5441c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
54428c80fb31SChunguang Xu 			*busy = 1;
5443c9de560dSAlex Tomas 			continue;
5444c9de560dSAlex Tomas 		}
5445c9de560dSAlex Tomas 		if (pa->pa_deleted) {
5446c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
5447c9de560dSAlex Tomas 			continue;
5448c9de560dSAlex Tomas 		}
5449c9de560dSAlex Tomas 
5450c9de560dSAlex Tomas 		/* seems this one can be freed ... */
545127bc446eSbrookxu 		ext4_mb_mark_pa_deleted(sb, pa);
5452c9de560dSAlex Tomas 
545370022da8SYe Bin 		if (!free)
545470022da8SYe Bin 			this_cpu_inc(discard_pa_seq);
545570022da8SYe Bin 
5456c9de560dSAlex Tomas 		/* we can trust pa_free ... */
5457c9de560dSAlex Tomas 		free += pa->pa_free;
5458c9de560dSAlex Tomas 
5459c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
5460c9de560dSAlex Tomas 
5461c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
5462c9de560dSAlex Tomas 		list_add(&pa->u.pa_tmp_list, &list);
5463c9de560dSAlex Tomas 	}
5464c9de560dSAlex Tomas 
5465c9de560dSAlex Tomas 	/* now free all selected PAs */
5466c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5467c9de560dSAlex Tomas 
5468c9de560dSAlex Tomas 		/* remove from object (inode or locality group) */
5469a8e38fd3SOjaswin Mujoo 		if (pa->pa_type == MB_GROUP_PA) {
5470a8e38fd3SOjaswin Mujoo 			spin_lock(pa->pa_node_lock.lg_lock);
5471a8e38fd3SOjaswin Mujoo 			list_del_rcu(&pa->pa_node.lg_list);
5472a8e38fd3SOjaswin Mujoo 			spin_unlock(pa->pa_node_lock.lg_lock);
5473a8e38fd3SOjaswin Mujoo 		} else {
547438727786SOjaswin Mujoo 			write_lock(pa->pa_node_lock.inode_lock);
547538727786SOjaswin Mujoo 			ei = EXT4_I(pa->pa_inode);
547638727786SOjaswin Mujoo 			rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
547738727786SOjaswin Mujoo 			write_unlock(pa->pa_node_lock.inode_lock);
5478a8e38fd3SOjaswin Mujoo 		}
5479c9de560dSAlex Tomas 
5480c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
548138727786SOjaswin Mujoo 
548238727786SOjaswin Mujoo 		if (pa->pa_type == MB_GROUP_PA) {
548338727786SOjaswin Mujoo 			ext4_mb_release_group_pa(&e4b, pa);
5484c9de560dSAlex Tomas 			call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
548538727786SOjaswin Mujoo 		} else {
548638727786SOjaswin Mujoo 			ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
548738727786SOjaswin Mujoo 			ext4_mb_pa_free(pa);
548838727786SOjaswin Mujoo 		}
5489c9de560dSAlex Tomas 	}
5490c9de560dSAlex Tomas 
5491c9de560dSAlex Tomas 	ext4_unlock_group(sb, group);
5492e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
5493c9de560dSAlex Tomas 	put_bh(bitmap_bh);
5494bbc4ec77SRitesh Harjani out_dbg:
5495d3df1453SRitesh Harjani 	mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
54968c80fb31SChunguang Xu 		 free, group, grp->bb_free);
54978c80fb31SChunguang Xu 	return free;
5498c9de560dSAlex Tomas }
5499c9de560dSAlex Tomas 
5500c9de560dSAlex Tomas /*
5501c9de560dSAlex Tomas  * releases all non-used preallocated blocks for given inode
5502c9de560dSAlex Tomas  *
5503c9de560dSAlex Tomas  * It's important to discard preallocations under i_data_sem
5504c9de560dSAlex Tomas  * We don't want another block to be served from the prealloc
5505c9de560dSAlex Tomas  * space when we are discarding the inode prealloc space.
5506c9de560dSAlex Tomas  *
5507c9de560dSAlex Tomas  * FIXME!! Make sure it is valid at all the call sites
5508c9de560dSAlex Tomas  */
550927bc446eSbrookxu void ext4_discard_preallocations(struct inode *inode, unsigned int needed)
5510c9de560dSAlex Tomas {
5511c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(inode);
5512c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
5513c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
5514c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
5515c9de560dSAlex Tomas 	ext4_group_t group = 0;
55160f6bc579SRuan Jinjie 	LIST_HEAD(list);
5517c9de560dSAlex Tomas 	struct ext4_buddy e4b;
551838727786SOjaswin Mujoo 	struct rb_node *iter;
5519c9de560dSAlex Tomas 	int err;
5520c9de560dSAlex Tomas 
5521c2ea3fdeSTheodore Ts'o 	if (!S_ISREG(inode->i_mode)) {
5522c9de560dSAlex Tomas 		return;
5523c9de560dSAlex Tomas 	}
5524c9de560dSAlex Tomas 
55258016e29fSHarshad Shirwadkar 	if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
55268016e29fSHarshad Shirwadkar 		return;
55278016e29fSHarshad Shirwadkar 
5528d3df1453SRitesh Harjani 	mb_debug(sb, "discard preallocation for inode %lu\n",
5529d3df1453SRitesh Harjani 		 inode->i_ino);
553027bc446eSbrookxu 	trace_ext4_discard_preallocations(inode,
553127bc446eSbrookxu 			atomic_read(&ei->i_prealloc_active), needed);
5532c9de560dSAlex Tomas 
553327bc446eSbrookxu 	if (needed == 0)
553427bc446eSbrookxu 		needed = UINT_MAX;
553527bc446eSbrookxu 
5536c9de560dSAlex Tomas repeat:
5537c9de560dSAlex Tomas 	/* first, collect all pa's in the inode */
553838727786SOjaswin Mujoo 	write_lock(&ei->i_prealloc_lock);
553938727786SOjaswin Mujoo 	for (iter = rb_first(&ei->i_prealloc_node); iter && needed;
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);
556327bc446eSbrookxu 			needed--;
5564c9de560dSAlex Tomas 			continue;
5565c9de560dSAlex Tomas 		}
5566c9de560dSAlex Tomas 
5567c9de560dSAlex Tomas 		/* someone is deleting pa right now */
5568c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
556938727786SOjaswin Mujoo 		write_unlock(&ei->i_prealloc_lock);
5570c9de560dSAlex Tomas 
5571c9de560dSAlex Tomas 		/* we have to wait here because pa_deleted
5572c9de560dSAlex Tomas 		 * doesn't mean pa is already unlinked from
5573c9de560dSAlex Tomas 		 * the list. as we might be called from
5574c9de560dSAlex Tomas 		 * ->clear_inode() the inode will get freed
5575c9de560dSAlex Tomas 		 * and concurrent thread which is unlinking
5576c9de560dSAlex Tomas 		 * pa from inode's list may access already
5577c9de560dSAlex Tomas 		 * freed memory, bad-bad-bad */
5578c9de560dSAlex Tomas 
5579c9de560dSAlex Tomas 		/* XXX: if this happens too often, we can
5580c9de560dSAlex Tomas 		 * add a flag to force wait only in case
5581c9de560dSAlex Tomas 		 * of ->clear_inode(), but not in case of
5582c9de560dSAlex Tomas 		 * regular truncate */
5583c9de560dSAlex Tomas 		schedule_timeout_uninterruptible(HZ);
5584c9de560dSAlex Tomas 		goto repeat;
5585c9de560dSAlex Tomas 	}
558638727786SOjaswin Mujoo 	write_unlock(&ei->i_prealloc_lock);
5587c9de560dSAlex Tomas 
5588c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5589cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_INODE_PA);
5590bd86298eSLukas Czerner 		group = ext4_get_group_number(sb, pa->pa_pstart);
5591c9de560dSAlex Tomas 
55929651e6b2SKonstantin Khlebnikov 		err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
55939651e6b2SKonstantin Khlebnikov 					     GFP_NOFS|__GFP_NOFAIL);
5594ce89f46cSAneesh Kumar K.V 		if (err) {
559554d3adbcSTheodore Ts'o 			ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
55969651e6b2SKonstantin Khlebnikov 				       err, group);
5597ce89f46cSAneesh Kumar K.V 			continue;
5598ce89f46cSAneesh Kumar K.V 		}
5599c9de560dSAlex Tomas 
5600574ca174STheodore Ts'o 		bitmap_bh = ext4_read_block_bitmap(sb, group);
56019008a58eSDarrick J. Wong 		if (IS_ERR(bitmap_bh)) {
56029008a58eSDarrick J. Wong 			err = PTR_ERR(bitmap_bh);
560354d3adbcSTheodore Ts'o 			ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
56049008a58eSDarrick J. Wong 				       err, group);
5605e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
5606ce89f46cSAneesh Kumar K.V 			continue;
5607c9de560dSAlex Tomas 		}
5608c9de560dSAlex Tomas 
5609c9de560dSAlex Tomas 		ext4_lock_group(sb, group);
5610c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
56113e1e5f50SEric Sandeen 		ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
5612c9de560dSAlex Tomas 		ext4_unlock_group(sb, group);
5613c9de560dSAlex Tomas 
5614e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
5615c9de560dSAlex Tomas 		put_bh(bitmap_bh);
5616c9de560dSAlex Tomas 
5617c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
561838727786SOjaswin Mujoo 		ext4_mb_pa_free(pa);
5619c9de560dSAlex Tomas 	}
5620c9de560dSAlex Tomas }
5621c9de560dSAlex Tomas 
562253f86b17SRitesh Harjani static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
562353f86b17SRitesh Harjani {
562453f86b17SRitesh Harjani 	struct ext4_prealloc_space *pa;
562553f86b17SRitesh Harjani 
562653f86b17SRitesh Harjani 	BUG_ON(ext4_pspace_cachep == NULL);
562753f86b17SRitesh Harjani 	pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
562853f86b17SRitesh Harjani 	if (!pa)
562953f86b17SRitesh Harjani 		return -ENOMEM;
563053f86b17SRitesh Harjani 	atomic_set(&pa->pa_count, 1);
563153f86b17SRitesh Harjani 	ac->ac_pa = pa;
563253f86b17SRitesh Harjani 	return 0;
563353f86b17SRitesh Harjani }
563453f86b17SRitesh Harjani 
563582089725SOjaswin Mujoo static void ext4_mb_pa_put_free(struct ext4_allocation_context *ac)
563653f86b17SRitesh Harjani {
563753f86b17SRitesh Harjani 	struct ext4_prealloc_space *pa = ac->ac_pa;
563853f86b17SRitesh Harjani 
563953f86b17SRitesh Harjani 	BUG_ON(!pa);
564053f86b17SRitesh Harjani 	ac->ac_pa = NULL;
564153f86b17SRitesh Harjani 	WARN_ON(!atomic_dec_and_test(&pa->pa_count));
564282089725SOjaswin Mujoo 	/*
564382089725SOjaswin Mujoo 	 * current function is only called due to an error or due to
564482089725SOjaswin Mujoo 	 * len of found blocks < len of requested blocks hence the PA has not
564582089725SOjaswin Mujoo 	 * been added to grp->bb_prealloc_list. So we don't need to lock it
564682089725SOjaswin Mujoo 	 */
564782089725SOjaswin Mujoo 	pa->pa_deleted = 1;
564882089725SOjaswin Mujoo 	ext4_mb_pa_free(pa);
564953f86b17SRitesh Harjani }
565053f86b17SRitesh Harjani 
56516ba495e9STheodore Ts'o #ifdef CONFIG_EXT4_DEBUG
5652e68cf40cSRitesh Harjani static inline void ext4_mb_show_pa(struct super_block *sb)
5653c9de560dSAlex Tomas {
5654e68cf40cSRitesh Harjani 	ext4_group_t i, ngroups;
5655c9de560dSAlex Tomas 
565695257987SJan Kara 	if (ext4_forced_shutdown(sb))
5657e3570639SEric Sandeen 		return;
5658e3570639SEric Sandeen 
56598df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
5660d3df1453SRitesh Harjani 	mb_debug(sb, "groups: ");
56618df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
5662c9de560dSAlex Tomas 		struct ext4_group_info *grp = ext4_get_group_info(sb, i);
5663c9de560dSAlex Tomas 		struct ext4_prealloc_space *pa;
5664c9de560dSAlex Tomas 		ext4_grpblk_t start;
5665c9de560dSAlex Tomas 		struct list_head *cur;
56665354b2afSTheodore Ts'o 
56675354b2afSTheodore Ts'o 		if (!grp)
56685354b2afSTheodore Ts'o 			continue;
5669c9de560dSAlex Tomas 		ext4_lock_group(sb, i);
5670c9de560dSAlex Tomas 		list_for_each(cur, &grp->bb_prealloc_list) {
5671c9de560dSAlex Tomas 			pa = list_entry(cur, struct ext4_prealloc_space,
5672c9de560dSAlex Tomas 					pa_group_list);
5673c9de560dSAlex Tomas 			spin_lock(&pa->pa_lock);
5674c9de560dSAlex Tomas 			ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5675c9de560dSAlex Tomas 						     NULL, &start);
5676c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
5677d3df1453SRitesh Harjani 			mb_debug(sb, "PA:%u:%d:%d\n", i, start,
5678d3df1453SRitesh Harjani 				 pa->pa_len);
5679c9de560dSAlex Tomas 		}
568060bd63d1SSolofo Ramangalahy 		ext4_unlock_group(sb, i);
5681d3df1453SRitesh Harjani 		mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
5682d3df1453SRitesh Harjani 			 grp->bb_fragments);
5683c9de560dSAlex Tomas 	}
5684c9de560dSAlex Tomas }
5685e68cf40cSRitesh Harjani 
5686e68cf40cSRitesh Harjani static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5687e68cf40cSRitesh Harjani {
5688e68cf40cSRitesh Harjani 	struct super_block *sb = ac->ac_sb;
5689e68cf40cSRitesh Harjani 
569095257987SJan Kara 	if (ext4_forced_shutdown(sb))
5691e68cf40cSRitesh Harjani 		return;
5692e68cf40cSRitesh Harjani 
5693d3df1453SRitesh Harjani 	mb_debug(sb, "Can't allocate:"
5694e68cf40cSRitesh Harjani 			" Allocation context details:");
5695d3df1453SRitesh Harjani 	mb_debug(sb, "status %u flags 0x%x",
5696e68cf40cSRitesh Harjani 			ac->ac_status, ac->ac_flags);
5697d3df1453SRitesh Harjani 	mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
5698e68cf40cSRitesh Harjani 			"goal %lu/%lu/%lu@%lu, "
5699e68cf40cSRitesh Harjani 			"best %lu/%lu/%lu@%lu cr %d",
5700e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_group,
5701e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_start,
5702e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_len,
5703e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_o_ex.fe_logical,
5704e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_group,
5705e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_start,
5706e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_len,
5707e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_g_ex.fe_logical,
5708e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_group,
5709e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_start,
5710e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_len,
5711e68cf40cSRitesh Harjani 			(unsigned long)ac->ac_b_ex.fe_logical,
5712e68cf40cSRitesh Harjani 			(int)ac->ac_criteria);
5713d3df1453SRitesh Harjani 	mb_debug(sb, "%u found", ac->ac_found);
5714569f196fSRitesh Harjani 	mb_debug(sb, "used pa: %s, ", ac->ac_pa ? "yes" : "no");
5715569f196fSRitesh Harjani 	if (ac->ac_pa)
5716569f196fSRitesh Harjani 		mb_debug(sb, "pa_type %s\n", ac->ac_pa->pa_type == MB_GROUP_PA ?
5717569f196fSRitesh Harjani 			 "group pa" : "inode pa");
5718e68cf40cSRitesh Harjani 	ext4_mb_show_pa(sb);
5719e68cf40cSRitesh Harjani }
5720c9de560dSAlex Tomas #else
5721e68cf40cSRitesh Harjani static inline void ext4_mb_show_pa(struct super_block *sb)
5722e68cf40cSRitesh Harjani {
5723e68cf40cSRitesh Harjani }
5724c9de560dSAlex Tomas static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5725c9de560dSAlex Tomas {
5726e68cf40cSRitesh Harjani 	ext4_mb_show_pa(ac->ac_sb);
5727c9de560dSAlex Tomas }
5728c9de560dSAlex Tomas #endif
5729c9de560dSAlex Tomas 
5730c9de560dSAlex Tomas /*
5731c9de560dSAlex Tomas  * We use locality group preallocation for small size file. The size of the
5732c9de560dSAlex Tomas  * file is determined by the current size or the resulting size after
5733c9de560dSAlex Tomas  * allocation which ever is larger
5734c9de560dSAlex Tomas  *
5735b713a5ecSTheodore Ts'o  * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
5736c9de560dSAlex Tomas  */
5737c9de560dSAlex Tomas static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
5738c9de560dSAlex Tomas {
5739c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
5740c9de560dSAlex Tomas 	int bsbits = ac->ac_sb->s_blocksize_bits;
5741c9de560dSAlex Tomas 	loff_t size, isize;
5742a9f2a293SJan Kara 	bool inode_pa_eligible, group_pa_eligible;
5743c9de560dSAlex Tomas 
5744c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
5745c9de560dSAlex Tomas 		return;
5746c9de560dSAlex Tomas 
57474ba74d00STheodore Ts'o 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
57484ba74d00STheodore Ts'o 		return;
57494ba74d00STheodore Ts'o 
5750a9f2a293SJan Kara 	group_pa_eligible = sbi->s_mb_group_prealloc > 0;
5751a9f2a293SJan Kara 	inode_pa_eligible = true;
575243bbddc0SBaokun Li 	size = extent_logical_end(sbi, &ac->ac_o_ex);
575350797481STheodore Ts'o 	isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
575450797481STheodore Ts'o 		>> bsbits;
5755c9de560dSAlex Tomas 
5756a9f2a293SJan Kara 	/* No point in using inode preallocation for closed files */
575782dd124cSNikolay Borisov 	if ((size == isize) && !ext4_fs_is_busy(sbi) &&
5758a9f2a293SJan Kara 	    !inode_is_open_for_write(ac->ac_inode))
5759a9f2a293SJan Kara 		inode_pa_eligible = false;
576050797481STheodore Ts'o 
576171780577STheodore Ts'o 	size = max(size, isize);
5762a9f2a293SJan Kara 	/* Don't use group allocation for large files */
5763a9f2a293SJan Kara 	if (size > sbi->s_mb_stream_request)
5764a9f2a293SJan Kara 		group_pa_eligible = false;
5765a9f2a293SJan Kara 
5766a9f2a293SJan Kara 	if (!group_pa_eligible) {
5767a9f2a293SJan Kara 		if (inode_pa_eligible)
57684ba74d00STheodore Ts'o 			ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
5769a9f2a293SJan Kara 		else
5770a9f2a293SJan Kara 			ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
5771c9de560dSAlex Tomas 		return;
57724ba74d00STheodore Ts'o 	}
5773c9de560dSAlex Tomas 
5774c9de560dSAlex Tomas 	BUG_ON(ac->ac_lg != NULL);
5775c9de560dSAlex Tomas 	/*
5776c9de560dSAlex Tomas 	 * locality group prealloc space are per cpu. The reason for having
5777c9de560dSAlex Tomas 	 * per cpu locality group is to reduce the contention between block
5778c9de560dSAlex Tomas 	 * request from multiple CPUs.
5779c9de560dSAlex Tomas 	 */
5780a0b6bc63SChristoph Lameter 	ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
5781c9de560dSAlex Tomas 
5782c9de560dSAlex Tomas 	/* we're going to use group allocation */
5783c9de560dSAlex Tomas 	ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
5784c9de560dSAlex Tomas 
5785c9de560dSAlex Tomas 	/* serialize all allocations in the group */
5786c9de560dSAlex Tomas 	mutex_lock(&ac->ac_lg->lg_mutex);
5787c9de560dSAlex Tomas }
5788c9de560dSAlex Tomas 
5789d73eff68SGuoqing Jiang static noinline_for_stack void
57904ddfef7bSEric Sandeen ext4_mb_initialize_context(struct ext4_allocation_context *ac,
5791c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
5792c9de560dSAlex Tomas {
5793c9de560dSAlex Tomas 	struct super_block *sb = ar->inode->i_sb;
5794c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
5795c9de560dSAlex Tomas 	struct ext4_super_block *es = sbi->s_es;
5796c9de560dSAlex Tomas 	ext4_group_t group;
5797498e5f24STheodore Ts'o 	unsigned int len;
5798498e5f24STheodore Ts'o 	ext4_fsblk_t goal;
5799c9de560dSAlex Tomas 	ext4_grpblk_t block;
5800c9de560dSAlex Tomas 
5801c9de560dSAlex Tomas 	/* we can't allocate > group size */
5802c9de560dSAlex Tomas 	len = ar->len;
5803c9de560dSAlex Tomas 
5804c9de560dSAlex Tomas 	/* just a dirty hack to filter too big requests  */
580540ae3487STheodore Ts'o 	if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
580640ae3487STheodore Ts'o 		len = EXT4_CLUSTERS_PER_GROUP(sb);
5807c9de560dSAlex Tomas 
5808c9de560dSAlex Tomas 	/* start searching from the goal */
5809c9de560dSAlex Tomas 	goal = ar->goal;
5810c9de560dSAlex Tomas 	if (goal < le32_to_cpu(es->s_first_data_block) ||
5811c9de560dSAlex Tomas 			goal >= ext4_blocks_count(es))
5812c9de560dSAlex Tomas 		goal = le32_to_cpu(es->s_first_data_block);
5813c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, goal, &group, &block);
5814c9de560dSAlex Tomas 
5815c9de560dSAlex Tomas 	/* set up allocation goals */
5816f5a44db5STheodore Ts'o 	ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
5817c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_CONTINUE;
5818c9de560dSAlex Tomas 	ac->ac_sb = sb;
5819c9de560dSAlex Tomas 	ac->ac_inode = ar->inode;
582053accfa9STheodore Ts'o 	ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
5821c9de560dSAlex Tomas 	ac->ac_o_ex.fe_group = group;
5822c9de560dSAlex Tomas 	ac->ac_o_ex.fe_start = block;
5823c9de560dSAlex Tomas 	ac->ac_o_ex.fe_len = len;
582453accfa9STheodore Ts'o 	ac->ac_g_ex = ac->ac_o_ex;
58257e170922SOjaswin Mujoo 	ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
5826c9de560dSAlex Tomas 	ac->ac_flags = ar->flags;
5827c9de560dSAlex Tomas 
58283cb77bd2Sbrookxu 	/* we have to define context: we'll work with a file or
5829c9de560dSAlex Tomas 	 * locality group. this is a policy, actually */
5830c9de560dSAlex Tomas 	ext4_mb_group_or_file(ac);
5831c9de560dSAlex Tomas 
5832d3df1453SRitesh Harjani 	mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
5833c9de560dSAlex Tomas 			"left: %u/%u, right %u/%u to %swritable\n",
5834c9de560dSAlex Tomas 			(unsigned) ar->len, (unsigned) ar->logical,
5835c9de560dSAlex Tomas 			(unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
5836c9de560dSAlex Tomas 			(unsigned) ar->lleft, (unsigned) ar->pleft,
5837c9de560dSAlex Tomas 			(unsigned) ar->lright, (unsigned) ar->pright,
583882dd124cSNikolay Borisov 			inode_is_open_for_write(ar->inode) ? "" : "non-");
5839c9de560dSAlex Tomas }
5840c9de560dSAlex Tomas 
58416be2ded1SAneesh Kumar K.V static noinline_for_stack void
58426be2ded1SAneesh Kumar K.V ext4_mb_discard_lg_preallocations(struct super_block *sb,
58436be2ded1SAneesh Kumar K.V 					struct ext4_locality_group *lg,
58446be2ded1SAneesh Kumar K.V 					int order, int total_entries)
58456be2ded1SAneesh Kumar K.V {
58466be2ded1SAneesh Kumar K.V 	ext4_group_t group = 0;
58476be2ded1SAneesh Kumar K.V 	struct ext4_buddy e4b;
58480f6bc579SRuan Jinjie 	LIST_HEAD(discard_list);
58496be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa, *tmp;
58506be2ded1SAneesh Kumar K.V 
5851d3df1453SRitesh Harjani 	mb_debug(sb, "discard locality group preallocation\n");
58526be2ded1SAneesh Kumar K.V 
58536be2ded1SAneesh Kumar K.V 	spin_lock(&lg->lg_prealloc_lock);
58546be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
5855a8e38fd3SOjaswin Mujoo 				pa_node.lg_list,
585692e9c58cSMadhuparna Bhowmik 				lockdep_is_held(&lg->lg_prealloc_lock)) {
58576be2ded1SAneesh Kumar K.V 		spin_lock(&pa->pa_lock);
58586be2ded1SAneesh Kumar K.V 		if (atomic_read(&pa->pa_count)) {
58596be2ded1SAneesh Kumar K.V 			/*
58606be2ded1SAneesh Kumar K.V 			 * This is the pa that we just used
58616be2ded1SAneesh Kumar K.V 			 * for block allocation. So don't
58626be2ded1SAneesh Kumar K.V 			 * free that
58636be2ded1SAneesh Kumar K.V 			 */
58646be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
58656be2ded1SAneesh Kumar K.V 			continue;
58666be2ded1SAneesh Kumar K.V 		}
58676be2ded1SAneesh Kumar K.V 		if (pa->pa_deleted) {
58686be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
58696be2ded1SAneesh Kumar K.V 			continue;
58706be2ded1SAneesh Kumar K.V 		}
58716be2ded1SAneesh Kumar K.V 		/* only lg prealloc space */
5872cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_GROUP_PA);
58736be2ded1SAneesh Kumar K.V 
58746be2ded1SAneesh Kumar K.V 		/* seems this one can be freed ... */
587527bc446eSbrookxu 		ext4_mb_mark_pa_deleted(sb, pa);
58766be2ded1SAneesh Kumar K.V 		spin_unlock(&pa->pa_lock);
58776be2ded1SAneesh Kumar K.V 
5878a8e38fd3SOjaswin Mujoo 		list_del_rcu(&pa->pa_node.lg_list);
58796be2ded1SAneesh Kumar K.V 		list_add(&pa->u.pa_tmp_list, &discard_list);
58806be2ded1SAneesh Kumar K.V 
58816be2ded1SAneesh Kumar K.V 		total_entries--;
58826be2ded1SAneesh Kumar K.V 		if (total_entries <= 5) {
58836be2ded1SAneesh Kumar K.V 			/*
58846be2ded1SAneesh Kumar K.V 			 * we want to keep only 5 entries
58856be2ded1SAneesh Kumar K.V 			 * allowing it to grow to 8. This
58866be2ded1SAneesh Kumar K.V 			 * mak sure we don't call discard
58876be2ded1SAneesh Kumar K.V 			 * soon for this list.
58886be2ded1SAneesh Kumar K.V 			 */
58896be2ded1SAneesh Kumar K.V 			break;
58906be2ded1SAneesh Kumar K.V 		}
58916be2ded1SAneesh Kumar K.V 	}
58926be2ded1SAneesh Kumar K.V 	spin_unlock(&lg->lg_prealloc_lock);
58936be2ded1SAneesh Kumar K.V 
58946be2ded1SAneesh Kumar K.V 	list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
58959651e6b2SKonstantin Khlebnikov 		int err;
58966be2ded1SAneesh Kumar K.V 
5897bd86298eSLukas Czerner 		group = ext4_get_group_number(sb, pa->pa_pstart);
58989651e6b2SKonstantin Khlebnikov 		err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
58999651e6b2SKonstantin Khlebnikov 					     GFP_NOFS|__GFP_NOFAIL);
59009651e6b2SKonstantin Khlebnikov 		if (err) {
590154d3adbcSTheodore Ts'o 			ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
59029651e6b2SKonstantin Khlebnikov 				       err, group);
59036be2ded1SAneesh Kumar K.V 			continue;
59046be2ded1SAneesh Kumar K.V 		}
59056be2ded1SAneesh Kumar K.V 		ext4_lock_group(sb, group);
59066be2ded1SAneesh Kumar K.V 		list_del(&pa->pa_group_list);
59073e1e5f50SEric Sandeen 		ext4_mb_release_group_pa(&e4b, pa);
59086be2ded1SAneesh Kumar K.V 		ext4_unlock_group(sb, group);
59096be2ded1SAneesh Kumar K.V 
5910e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
59116be2ded1SAneesh Kumar K.V 		list_del(&pa->u.pa_tmp_list);
59126be2ded1SAneesh Kumar K.V 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
59136be2ded1SAneesh Kumar K.V 	}
59146be2ded1SAneesh Kumar K.V }
59156be2ded1SAneesh Kumar K.V 
59166be2ded1SAneesh Kumar K.V /*
59176be2ded1SAneesh Kumar K.V  * We have incremented pa_count. So it cannot be freed at this
59186be2ded1SAneesh Kumar K.V  * point. Also we hold lg_mutex. So no parallel allocation is
59196be2ded1SAneesh Kumar K.V  * possible from this lg. That means pa_free cannot be updated.
59206be2ded1SAneesh Kumar K.V  *
59216be2ded1SAneesh Kumar K.V  * A parallel ext4_mb_discard_group_preallocations is possible.
59226be2ded1SAneesh Kumar K.V  * which can cause the lg_prealloc_list to be updated.
59236be2ded1SAneesh Kumar K.V  */
59246be2ded1SAneesh Kumar K.V 
59256be2ded1SAneesh Kumar K.V static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
59266be2ded1SAneesh Kumar K.V {
59276be2ded1SAneesh Kumar K.V 	int order, added = 0, lg_prealloc_count = 1;
59286be2ded1SAneesh Kumar K.V 	struct super_block *sb = ac->ac_sb;
59296be2ded1SAneesh Kumar K.V 	struct ext4_locality_group *lg = ac->ac_lg;
59306be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
59316be2ded1SAneesh Kumar K.V 
59326be2ded1SAneesh Kumar K.V 	order = fls(pa->pa_free) - 1;
59336be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
59346be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
59356be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
59366be2ded1SAneesh Kumar K.V 	/* Add the prealloc space to lg */
5937f1167009SNiu Yawei 	spin_lock(&lg->lg_prealloc_lock);
59386be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
5939a8e38fd3SOjaswin Mujoo 				pa_node.lg_list,
594092e9c58cSMadhuparna Bhowmik 				lockdep_is_held(&lg->lg_prealloc_lock)) {
59416be2ded1SAneesh Kumar K.V 		spin_lock(&tmp_pa->pa_lock);
59426be2ded1SAneesh Kumar K.V 		if (tmp_pa->pa_deleted) {
5943e7c9e3e9STheodore Ts'o 			spin_unlock(&tmp_pa->pa_lock);
59446be2ded1SAneesh Kumar K.V 			continue;
59456be2ded1SAneesh Kumar K.V 		}
59466be2ded1SAneesh Kumar K.V 		if (!added && pa->pa_free < tmp_pa->pa_free) {
59476be2ded1SAneesh Kumar K.V 			/* Add to the tail of the previous entry */
5948a8e38fd3SOjaswin Mujoo 			list_add_tail_rcu(&pa->pa_node.lg_list,
5949a8e38fd3SOjaswin Mujoo 						&tmp_pa->pa_node.lg_list);
59506be2ded1SAneesh Kumar K.V 			added = 1;
59516be2ded1SAneesh Kumar K.V 			/*
59526be2ded1SAneesh Kumar K.V 			 * we want to count the total
59536be2ded1SAneesh Kumar K.V 			 * number of entries in the list
59546be2ded1SAneesh Kumar K.V 			 */
59556be2ded1SAneesh Kumar K.V 		}
59566be2ded1SAneesh Kumar K.V 		spin_unlock(&tmp_pa->pa_lock);
59576be2ded1SAneesh Kumar K.V 		lg_prealloc_count++;
59586be2ded1SAneesh Kumar K.V 	}
59596be2ded1SAneesh Kumar K.V 	if (!added)
5960a8e38fd3SOjaswin Mujoo 		list_add_tail_rcu(&pa->pa_node.lg_list,
59616be2ded1SAneesh Kumar K.V 					&lg->lg_prealloc_list[order]);
5962f1167009SNiu Yawei 	spin_unlock(&lg->lg_prealloc_lock);
59636be2ded1SAneesh Kumar K.V 
59646be2ded1SAneesh Kumar K.V 	/* Now trim the list to be not more than 8 elements */
5965ad635507SKemeng Shi 	if (lg_prealloc_count > 8)
59666be2ded1SAneesh Kumar K.V 		ext4_mb_discard_lg_preallocations(sb, lg,
59676be2ded1SAneesh Kumar K.V 						  order, lg_prealloc_count);
59686be2ded1SAneesh Kumar K.V }
59696be2ded1SAneesh Kumar K.V 
5970c9de560dSAlex Tomas /*
5971c9de560dSAlex Tomas  * release all resource we used in allocation
5972c9de560dSAlex Tomas  */
5973c9de560dSAlex Tomas static int ext4_mb_release_context(struct ext4_allocation_context *ac)
5974c9de560dSAlex Tomas {
597553accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
59766be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa = ac->ac_pa;
59776be2ded1SAneesh Kumar K.V 	if (pa) {
5978cc0fb9adSAneesh Kumar K.V 		if (pa->pa_type == MB_GROUP_PA) {
5979c9de560dSAlex Tomas 			/* see comment in ext4_mb_use_group_pa() */
59806be2ded1SAneesh Kumar K.V 			spin_lock(&pa->pa_lock);
598153accfa9STheodore Ts'o 			pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
598253accfa9STheodore Ts'o 			pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
59836be2ded1SAneesh Kumar K.V 			pa->pa_free -= ac->ac_b_ex.fe_len;
59846be2ded1SAneesh Kumar K.V 			pa->pa_len -= ac->ac_b_ex.fe_len;
59856be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
598666d5e027Sbrookxu 
59876be2ded1SAneesh Kumar K.V 			/*
59886be2ded1SAneesh Kumar K.V 			 * We want to add the pa to the right bucket.
59896be2ded1SAneesh Kumar K.V 			 * Remove it from the list and while adding
59906be2ded1SAneesh Kumar K.V 			 * make sure the list to which we are adding
599144183d42SAmir Goldstein 			 * doesn't grow big.
59926be2ded1SAneesh Kumar K.V 			 */
599366d5e027Sbrookxu 			if (likely(pa->pa_free)) {
5994a8e38fd3SOjaswin Mujoo 				spin_lock(pa->pa_node_lock.lg_lock);
5995a8e38fd3SOjaswin Mujoo 				list_del_rcu(&pa->pa_node.lg_list);
5996a8e38fd3SOjaswin Mujoo 				spin_unlock(pa->pa_node_lock.lg_lock);
59976be2ded1SAneesh Kumar K.V 				ext4_mb_add_n_trim(ac);
5998c9de560dSAlex Tomas 			}
599966d5e027Sbrookxu 		}
600027bc446eSbrookxu 
60016be2ded1SAneesh Kumar K.V 		ext4_mb_put_pa(ac, ac->ac_sb, pa);
6002c9de560dSAlex Tomas 	}
6003c9de560dSAlex Tomas 	if (ac->ac_bitmap_page)
600409cbfeafSKirill A. Shutemov 		put_page(ac->ac_bitmap_page);
6005c9de560dSAlex Tomas 	if (ac->ac_buddy_page)
600609cbfeafSKirill A. Shutemov 		put_page(ac->ac_buddy_page);
6007c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
6008c9de560dSAlex Tomas 		mutex_unlock(&ac->ac_lg->lg_mutex);
6009c9de560dSAlex Tomas 	ext4_mb_collect_stats(ac);
6010c9de560dSAlex Tomas 	return 0;
6011c9de560dSAlex Tomas }
6012c9de560dSAlex Tomas 
6013c9de560dSAlex Tomas static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
6014c9de560dSAlex Tomas {
60158df9675fSTheodore Ts'o 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
6016c9de560dSAlex Tomas 	int ret;
60178c80fb31SChunguang Xu 	int freed = 0, busy = 0;
60188c80fb31SChunguang Xu 	int retry = 0;
6019c9de560dSAlex Tomas 
60209bffad1eSTheodore Ts'o 	trace_ext4_mb_discard_preallocations(sb, needed);
60218c80fb31SChunguang Xu 
60228c80fb31SChunguang Xu 	if (needed == 0)
60238c80fb31SChunguang Xu 		needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
60248c80fb31SChunguang Xu  repeat:
60258df9675fSTheodore Ts'o 	for (i = 0; i < ngroups && needed > 0; i++) {
60268c80fb31SChunguang Xu 		ret = ext4_mb_discard_group_preallocations(sb, i, &busy);
6027c9de560dSAlex Tomas 		freed += ret;
6028c9de560dSAlex Tomas 		needed -= ret;
60298c80fb31SChunguang Xu 		cond_resched();
60308c80fb31SChunguang Xu 	}
60318c80fb31SChunguang Xu 
60328c80fb31SChunguang Xu 	if (needed > 0 && busy && ++retry < 3) {
60338c80fb31SChunguang Xu 		busy = 0;
60348c80fb31SChunguang Xu 		goto repeat;
6035c9de560dSAlex Tomas 	}
6036c9de560dSAlex Tomas 
6037c9de560dSAlex Tomas 	return freed;
6038c9de560dSAlex Tomas }
6039c9de560dSAlex Tomas 
6040cf5e2ca6SRitesh Harjani static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
604107b5b8e1SRitesh Harjani 			struct ext4_allocation_context *ac, u64 *seq)
6042cf5e2ca6SRitesh Harjani {
6043cf5e2ca6SRitesh Harjani 	int freed;
604407b5b8e1SRitesh Harjani 	u64 seq_retry = 0;
604507b5b8e1SRitesh Harjani 	bool ret = false;
6046cf5e2ca6SRitesh Harjani 
6047cf5e2ca6SRitesh Harjani 	freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
604807b5b8e1SRitesh Harjani 	if (freed) {
604907b5b8e1SRitesh Harjani 		ret = true;
605007b5b8e1SRitesh Harjani 		goto out_dbg;
605107b5b8e1SRitesh Harjani 	}
605207b5b8e1SRitesh Harjani 	seq_retry = ext4_get_discard_pa_seq_sum();
605399377830SRitesh Harjani 	if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
605499377830SRitesh Harjani 		ac->ac_flags |= EXT4_MB_STRICT_CHECK;
605507b5b8e1SRitesh Harjani 		*seq = seq_retry;
605607b5b8e1SRitesh Harjani 		ret = true;
605707b5b8e1SRitesh Harjani 	}
605807b5b8e1SRitesh Harjani 
605907b5b8e1SRitesh Harjani out_dbg:
606007b5b8e1SRitesh Harjani 	mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
606107b5b8e1SRitesh Harjani 	return ret;
6062cf5e2ca6SRitesh Harjani }
6063cf5e2ca6SRitesh Harjani 
6064ad78b5efSKemeng Shi /*
6065ad78b5efSKemeng Shi  * Simple allocator for Ext4 fast commit replay path. It searches for blocks
6066ad78b5efSKemeng Shi  * linearly starting at the goal block and also excludes the blocks which
6067ad78b5efSKemeng Shi  * are going to be in use after fast commit replay.
6068ad78b5efSKemeng Shi  */
6069ad78b5efSKemeng Shi static ext4_fsblk_t
6070ad78b5efSKemeng Shi ext4_mb_new_blocks_simple(struct ext4_allocation_request *ar, int *errp)
6071ad78b5efSKemeng Shi {
6072ad78b5efSKemeng Shi 	struct buffer_head *bitmap_bh;
6073ad78b5efSKemeng Shi 	struct super_block *sb = ar->inode->i_sb;
6074ad78b5efSKemeng Shi 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6075ad78b5efSKemeng Shi 	ext4_group_t group, nr;
6076ad78b5efSKemeng Shi 	ext4_grpblk_t blkoff;
6077ad78b5efSKemeng Shi 	ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
6078ad78b5efSKemeng Shi 	ext4_grpblk_t i = 0;
6079ad78b5efSKemeng Shi 	ext4_fsblk_t goal, block;
608079ebf48cSLu Hongfei 	struct ext4_super_block *es = sbi->s_es;
6081ad78b5efSKemeng Shi 
6082ad78b5efSKemeng Shi 	goal = ar->goal;
6083ad78b5efSKemeng Shi 	if (goal < le32_to_cpu(es->s_first_data_block) ||
6084ad78b5efSKemeng Shi 			goal >= ext4_blocks_count(es))
6085ad78b5efSKemeng Shi 		goal = le32_to_cpu(es->s_first_data_block);
6086ad78b5efSKemeng Shi 
6087ad78b5efSKemeng Shi 	ar->len = 0;
6088ad78b5efSKemeng Shi 	ext4_get_group_no_and_offset(sb, goal, &group, &blkoff);
6089ad78b5efSKemeng Shi 	for (nr = ext4_get_groups_count(sb); nr > 0; nr--) {
6090ad78b5efSKemeng Shi 		bitmap_bh = ext4_read_block_bitmap(sb, group);
6091ad78b5efSKemeng Shi 		if (IS_ERR(bitmap_bh)) {
6092ad78b5efSKemeng Shi 			*errp = PTR_ERR(bitmap_bh);
6093ad78b5efSKemeng Shi 			pr_warn("Failed to read block bitmap\n");
6094ad78b5efSKemeng Shi 			return 0;
6095ad78b5efSKemeng Shi 		}
6096ad78b5efSKemeng Shi 
6097ad78b5efSKemeng Shi 		while (1) {
6098ad78b5efSKemeng Shi 			i = mb_find_next_zero_bit(bitmap_bh->b_data, max,
6099ad78b5efSKemeng Shi 						blkoff);
6100ad78b5efSKemeng Shi 			if (i >= max)
6101ad78b5efSKemeng Shi 				break;
6102ad78b5efSKemeng Shi 			if (ext4_fc_replay_check_excluded(sb,
6103ad78b5efSKemeng Shi 				ext4_group_first_block_no(sb, group) +
6104ad78b5efSKemeng Shi 				EXT4_C2B(sbi, i))) {
6105ad78b5efSKemeng Shi 				blkoff = i + 1;
6106ad78b5efSKemeng Shi 			} else
6107ad78b5efSKemeng Shi 				break;
6108ad78b5efSKemeng Shi 		}
6109ad78b5efSKemeng Shi 		brelse(bitmap_bh);
6110ad78b5efSKemeng Shi 		if (i < max)
6111ad78b5efSKemeng Shi 			break;
6112ad78b5efSKemeng Shi 
6113ad78b5efSKemeng Shi 		if (++group >= ext4_get_groups_count(sb))
6114ad78b5efSKemeng Shi 			group = 0;
6115ad78b5efSKemeng Shi 
6116ad78b5efSKemeng Shi 		blkoff = 0;
6117ad78b5efSKemeng Shi 	}
6118ad78b5efSKemeng Shi 
6119ad78b5efSKemeng Shi 	if (i >= max) {
6120ad78b5efSKemeng Shi 		*errp = -ENOSPC;
6121ad78b5efSKemeng Shi 		return 0;
6122ad78b5efSKemeng Shi 	}
6123ad78b5efSKemeng Shi 
6124ad78b5efSKemeng Shi 	block = ext4_group_first_block_no(sb, group) + EXT4_C2B(sbi, i);
6125ad78b5efSKemeng Shi 	ext4_mb_mark_bb(sb, block, 1, 1);
6126ad78b5efSKemeng Shi 	ar->len = 1;
6127ad78b5efSKemeng Shi 
6128ad78b5efSKemeng Shi 	return block;
6129ad78b5efSKemeng Shi }
61308016e29fSHarshad Shirwadkar 
6131c9de560dSAlex Tomas /*
6132c9de560dSAlex Tomas  * Main entry point into mballoc to allocate blocks
6133c9de560dSAlex Tomas  * it tries to use preallocation first, then falls back
6134c9de560dSAlex Tomas  * to usual allocation
6135c9de560dSAlex Tomas  */
6136c9de560dSAlex Tomas ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
6137c9de560dSAlex Tomas 				struct ext4_allocation_request *ar, int *errp)
6138c9de560dSAlex Tomas {
6139256bdb49SEric Sandeen 	struct ext4_allocation_context *ac = NULL;
6140c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
6141c9de560dSAlex Tomas 	struct super_block *sb;
6142c9de560dSAlex Tomas 	ext4_fsblk_t block = 0;
614360e58e0fSMingming Cao 	unsigned int inquota = 0;
614453accfa9STheodore Ts'o 	unsigned int reserv_clstrs = 0;
614580fa46d6STheodore Ts'o 	int retries = 0;
614607b5b8e1SRitesh Harjani 	u64 seq;
6147c9de560dSAlex Tomas 
6148b10a44c3STheodore Ts'o 	might_sleep();
6149c9de560dSAlex Tomas 	sb = ar->inode->i_sb;
6150c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
6151c9de560dSAlex Tomas 
61529bffad1eSTheodore Ts'o 	trace_ext4_request_blocks(ar);
61538016e29fSHarshad Shirwadkar 	if (sbi->s_mount_state & EXT4_FC_REPLAY)
6154ad78b5efSKemeng Shi 		return ext4_mb_new_blocks_simple(ar, errp);
6155ba80b101STheodore Ts'o 
615645dc63e7SDmitry Monakhov 	/* Allow to use superuser reservation for quota file */
615702749a4cSTahsin Erdogan 	if (ext4_is_quota_file(ar->inode))
615845dc63e7SDmitry Monakhov 		ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
615945dc63e7SDmitry Monakhov 
6160e3cf5d5dSTheodore Ts'o 	if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
616160e58e0fSMingming Cao 		/* Without delayed allocation we need to verify
616260e58e0fSMingming Cao 		 * there is enough free blocks to do block allocation
616360e58e0fSMingming Cao 		 * and verify allocation doesn't exceed the quota limits.
6164d2a17637SMingming Cao 		 */
616555f020dbSAllison Henderson 		while (ar->len &&
6166e7d5f315STheodore Ts'o 			ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
616755f020dbSAllison Henderson 
6168030ba6bcSAneesh Kumar K.V 			/* let others to free the space */
6169bb8b20edSLukas Czerner 			cond_resched();
6170030ba6bcSAneesh Kumar K.V 			ar->len = ar->len >> 1;
6171030ba6bcSAneesh Kumar K.V 		}
6172030ba6bcSAneesh Kumar K.V 		if (!ar->len) {
6173bbc4ec77SRitesh Harjani 			ext4_mb_show_pa(sb);
617407031431SMingming Cao 			*errp = -ENOSPC;
617507031431SMingming Cao 			return 0;
617607031431SMingming Cao 		}
617753accfa9STheodore Ts'o 		reserv_clstrs = ar->len;
617855f020dbSAllison Henderson 		if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
617953accfa9STheodore Ts'o 			dquot_alloc_block_nofail(ar->inode,
618053accfa9STheodore Ts'o 						 EXT4_C2B(sbi, ar->len));
618155f020dbSAllison Henderson 		} else {
618255f020dbSAllison Henderson 			while (ar->len &&
618353accfa9STheodore Ts'o 				dquot_alloc_block(ar->inode,
618453accfa9STheodore Ts'o 						  EXT4_C2B(sbi, ar->len))) {
618555f020dbSAllison Henderson 
6186c9de560dSAlex Tomas 				ar->flags |= EXT4_MB_HINT_NOPREALLOC;
6187c9de560dSAlex Tomas 				ar->len--;
6188c9de560dSAlex Tomas 			}
618955f020dbSAllison Henderson 		}
619060e58e0fSMingming Cao 		inquota = ar->len;
6191c9de560dSAlex Tomas 		if (ar->len == 0) {
6192c9de560dSAlex Tomas 			*errp = -EDQUOT;
61936c7a120aSAditya Kali 			goto out;
6194c9de560dSAlex Tomas 		}
619560e58e0fSMingming Cao 	}
6196d2a17637SMingming Cao 
619785556c9aSWei Yongjun 	ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
6198833576b3STheodore Ts'o 	if (!ac) {
6199363d4251SShen Feng 		ar->len = 0;
6200256bdb49SEric Sandeen 		*errp = -ENOMEM;
62016c7a120aSAditya Kali 		goto out;
6202256bdb49SEric Sandeen 	}
6203256bdb49SEric Sandeen 
6204d73eff68SGuoqing Jiang 	ext4_mb_initialize_context(ac, ar);
6205c9de560dSAlex Tomas 
6206256bdb49SEric Sandeen 	ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
620781198536SRitesh Harjani 	seq = this_cpu_read(discard_pa_seq);
6208256bdb49SEric Sandeen 	if (!ext4_mb_use_preallocated(ac)) {
6209256bdb49SEric Sandeen 		ac->ac_op = EXT4_MB_HISTORY_ALLOC;
6210256bdb49SEric Sandeen 		ext4_mb_normalize_request(ac, ar);
621153f86b17SRitesh Harjani 
621253f86b17SRitesh Harjani 		*errp = ext4_mb_pa_alloc(ac);
621353f86b17SRitesh Harjani 		if (*errp)
621453f86b17SRitesh Harjani 			goto errout;
6215c9de560dSAlex Tomas repeat:
6216c9de560dSAlex Tomas 		/* allocate space in core */
62176c7a120aSAditya Kali 		*errp = ext4_mb_regular_allocator(ac);
621853f86b17SRitesh Harjani 		/*
621953f86b17SRitesh Harjani 		 * pa allocated above is added to grp->bb_prealloc_list only
622053f86b17SRitesh Harjani 		 * when we were able to allocate some block i.e. when
622153f86b17SRitesh Harjani 		 * ac->ac_status == AC_STATUS_FOUND.
622253f86b17SRitesh Harjani 		 * And error from above mean ac->ac_status != AC_STATUS_FOUND
622353f86b17SRitesh Harjani 		 * So we have to free this pa here itself.
622453f86b17SRitesh Harjani 		 */
62252c00ef3eSAlexey Khoroshilov 		if (*errp) {
622682089725SOjaswin Mujoo 			ext4_mb_pa_put_free(ac);
62272c00ef3eSAlexey Khoroshilov 			ext4_discard_allocated_blocks(ac);
62282c00ef3eSAlexey Khoroshilov 			goto errout;
62292c00ef3eSAlexey Khoroshilov 		}
623053f86b17SRitesh Harjani 		if (ac->ac_status == AC_STATUS_FOUND &&
623153f86b17SRitesh Harjani 			ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
623282089725SOjaswin Mujoo 			ext4_mb_pa_put_free(ac);
6233c9de560dSAlex Tomas 	}
6234256bdb49SEric Sandeen 	if (likely(ac->ac_status == AC_STATUS_FOUND)) {
623553accfa9STheodore Ts'o 		*errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
6236554a5cccSVegard Nossum 		if (*errp) {
6237b844167eSCurt Wohlgemuth 			ext4_discard_allocated_blocks(ac);
62386d138cedSEric Sandeen 			goto errout;
62396d138cedSEric Sandeen 		} else {
6240256bdb49SEric Sandeen 			block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
6241256bdb49SEric Sandeen 			ar->len = ac->ac_b_ex.fe_len;
6242519deca0SAneesh Kumar K.V 		}
6243c9de560dSAlex Tomas 	} else {
624480fa46d6STheodore Ts'o 		if (++retries < 3 &&
624580fa46d6STheodore Ts'o 		    ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
6246c9de560dSAlex Tomas 			goto repeat;
624753f86b17SRitesh Harjani 		/*
624853f86b17SRitesh Harjani 		 * If block allocation fails then the pa allocated above
624953f86b17SRitesh Harjani 		 * needs to be freed here itself.
625053f86b17SRitesh Harjani 		 */
625182089725SOjaswin Mujoo 		ext4_mb_pa_put_free(ac);
6252c9de560dSAlex Tomas 		*errp = -ENOSPC;
62536c7a120aSAditya Kali 	}
62546c7a120aSAditya Kali 
62556c7a120aSAditya Kali 	if (*errp) {
6256aaae558dSKemeng Shi errout:
6257256bdb49SEric Sandeen 		ac->ac_b_ex.fe_len = 0;
6258c9de560dSAlex Tomas 		ar->len = 0;
6259256bdb49SEric Sandeen 		ext4_mb_show_ac(ac);
6260c9de560dSAlex Tomas 	}
6261256bdb49SEric Sandeen 	ext4_mb_release_context(ac);
6262363d4251SShen Feng 	kmem_cache_free(ext4_ac_cachep, ac);
6263aaae558dSKemeng Shi out:
626460e58e0fSMingming Cao 	if (inquota && ar->len < inquota)
626553accfa9STheodore Ts'o 		dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
62660087d9fbSAneesh Kumar K.V 	if (!ar->len) {
6267e3cf5d5dSTheodore Ts'o 		if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
62680087d9fbSAneesh Kumar K.V 			/* release all the reserved blocks if non delalloc */
626957042651STheodore Ts'o 			percpu_counter_sub(&sbi->s_dirtyclusters_counter,
627053accfa9STheodore Ts'o 						reserv_clstrs);
62710087d9fbSAneesh Kumar K.V 	}
6272c9de560dSAlex Tomas 
62739bffad1eSTheodore Ts'o 	trace_ext4_allocate_blocks(ar, (unsigned long long)block);
6274ba80b101STheodore Ts'o 
6275c9de560dSAlex Tomas 	return block;
6276c9de560dSAlex Tomas }
6277c9de560dSAlex Tomas 
6278c894058dSAneesh Kumar K.V /*
6279c894058dSAneesh Kumar K.V  * We can merge two free data extents only if the physical blocks
6280c894058dSAneesh Kumar K.V  * are contiguous, AND the extents were freed by the same transaction,
6281c894058dSAneesh Kumar K.V  * AND the blocks are associated with the same group.
6282c894058dSAneesh Kumar K.V  */
6283a0154344SDaeho Jeong static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
6284a0154344SDaeho Jeong 					struct ext4_free_data *entry,
6285a0154344SDaeho Jeong 					struct ext4_free_data *new_entry,
6286a0154344SDaeho Jeong 					struct rb_root *entry_rb_root)
6287c894058dSAneesh Kumar K.V {
6288a0154344SDaeho Jeong 	if ((entry->efd_tid != new_entry->efd_tid) ||
6289a0154344SDaeho Jeong 	    (entry->efd_group != new_entry->efd_group))
6290a0154344SDaeho Jeong 		return;
6291a0154344SDaeho Jeong 	if (entry->efd_start_cluster + entry->efd_count ==
6292a0154344SDaeho Jeong 	    new_entry->efd_start_cluster) {
6293a0154344SDaeho Jeong 		new_entry->efd_start_cluster = entry->efd_start_cluster;
6294a0154344SDaeho Jeong 		new_entry->efd_count += entry->efd_count;
6295a0154344SDaeho Jeong 	} else if (new_entry->efd_start_cluster + new_entry->efd_count ==
6296a0154344SDaeho Jeong 		   entry->efd_start_cluster) {
6297a0154344SDaeho Jeong 		new_entry->efd_count += entry->efd_count;
6298a0154344SDaeho Jeong 	} else
6299a0154344SDaeho Jeong 		return;
6300a0154344SDaeho Jeong 	spin_lock(&sbi->s_md_lock);
6301a0154344SDaeho Jeong 	list_del(&entry->efd_list);
6302a0154344SDaeho Jeong 	spin_unlock(&sbi->s_md_lock);
6303a0154344SDaeho Jeong 	rb_erase(&entry->efd_node, entry_rb_root);
6304a0154344SDaeho Jeong 	kmem_cache_free(ext4_free_data_cachep, entry);
6305c894058dSAneesh Kumar K.V }
6306c894058dSAneesh Kumar K.V 
630785b67ffbSKemeng Shi static noinline_for_stack void
63084ddfef7bSEric Sandeen ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
63097a2fcbf7SAneesh Kumar K.V 		      struct ext4_free_data *new_entry)
6310c9de560dSAlex Tomas {
6311e29136f8STheodore Ts'o 	ext4_group_t group = e4b->bd_group;
631284130193STheodore Ts'o 	ext4_grpblk_t cluster;
6313d08854f5STheodore Ts'o 	ext4_grpblk_t clusters = new_entry->efd_count;
63147a2fcbf7SAneesh Kumar K.V 	struct ext4_free_data *entry;
6315c9de560dSAlex Tomas 	struct ext4_group_info *db = e4b->bd_info;
6316c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
6317c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6318c894058dSAneesh Kumar K.V 	struct rb_node **n = &db->bb_free_root.rb_node, *node;
6319c894058dSAneesh Kumar K.V 	struct rb_node *parent = NULL, *new_node;
6320c894058dSAneesh Kumar K.V 
63210390131bSFrank Mayhar 	BUG_ON(!ext4_handle_valid(handle));
6322c9de560dSAlex Tomas 	BUG_ON(e4b->bd_bitmap_page == NULL);
6323c9de560dSAlex Tomas 	BUG_ON(e4b->bd_buddy_page == NULL);
6324c9de560dSAlex Tomas 
632518aadd47SBobi Jam 	new_node = &new_entry->efd_node;
632618aadd47SBobi Jam 	cluster = new_entry->efd_start_cluster;
6327c9de560dSAlex Tomas 
6328c894058dSAneesh Kumar K.V 	if (!*n) {
6329c894058dSAneesh Kumar K.V 		/* first free block exent. We need to
6330c894058dSAneesh Kumar K.V 		   protect buddy cache from being freed,
6331c9de560dSAlex Tomas 		 * otherwise we'll refresh it from
6332c9de560dSAlex Tomas 		 * on-disk bitmap and lose not-yet-available
6333c9de560dSAlex Tomas 		 * blocks */
633409cbfeafSKirill A. Shutemov 		get_page(e4b->bd_buddy_page);
633509cbfeafSKirill A. Shutemov 		get_page(e4b->bd_bitmap_page);
6336c894058dSAneesh Kumar K.V 	}
6337c894058dSAneesh Kumar K.V 	while (*n) {
6338c894058dSAneesh Kumar K.V 		parent = *n;
633918aadd47SBobi Jam 		entry = rb_entry(parent, struct ext4_free_data, efd_node);
634018aadd47SBobi Jam 		if (cluster < entry->efd_start_cluster)
6341c894058dSAneesh Kumar K.V 			n = &(*n)->rb_left;
634218aadd47SBobi Jam 		else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
6343c894058dSAneesh Kumar K.V 			n = &(*n)->rb_right;
6344c894058dSAneesh Kumar K.V 		else {
6345e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, group, 0,
634684130193STheodore Ts'o 				ext4_group_first_block_no(sb, group) +
634784130193STheodore Ts'o 				EXT4_C2B(sbi, cluster),
6348e29136f8STheodore Ts'o 				"Block already on to-be-freed list");
6349cca41553SChunguang Xu 			kmem_cache_free(ext4_free_data_cachep, new_entry);
635085b67ffbSKemeng Shi 			return;
6351c9de560dSAlex Tomas 		}
6352c9de560dSAlex Tomas 	}
6353c9de560dSAlex Tomas 
6354c894058dSAneesh Kumar K.V 	rb_link_node(new_node, parent, n);
6355c894058dSAneesh Kumar K.V 	rb_insert_color(new_node, &db->bb_free_root);
6356c894058dSAneesh Kumar K.V 
6357c894058dSAneesh Kumar K.V 	/* Now try to see the extent can be merged to left and right */
6358c894058dSAneesh Kumar K.V 	node = rb_prev(new_node);
6359c894058dSAneesh Kumar K.V 	if (node) {
636018aadd47SBobi Jam 		entry = rb_entry(node, struct ext4_free_data, efd_node);
6361a0154344SDaeho Jeong 		ext4_try_merge_freed_extent(sbi, entry, new_entry,
6362a0154344SDaeho Jeong 					    &(db->bb_free_root));
6363c9de560dSAlex Tomas 	}
6364c894058dSAneesh Kumar K.V 
6365c894058dSAneesh Kumar K.V 	node = rb_next(new_node);
6366c894058dSAneesh Kumar K.V 	if (node) {
636718aadd47SBobi Jam 		entry = rb_entry(node, struct ext4_free_data, efd_node);
6368a0154344SDaeho Jeong 		ext4_try_merge_freed_extent(sbi, entry, new_entry,
6369a0154344SDaeho Jeong 					    &(db->bb_free_root));
6370c894058dSAneesh Kumar K.V 	}
6371a0154344SDaeho Jeong 
6372d08854f5STheodore Ts'o 	spin_lock(&sbi->s_md_lock);
6373*ce774e53SJinke Han 	list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list[new_entry->efd_tid & 1]);
6374d08854f5STheodore Ts'o 	sbi->s_mb_free_pending += clusters;
6375d08854f5STheodore Ts'o 	spin_unlock(&sbi->s_md_lock);
6376c9de560dSAlex Tomas }
6377c9de560dSAlex Tomas 
63788016e29fSHarshad Shirwadkar static void ext4_free_blocks_simple(struct inode *inode, ext4_fsblk_t block,
63798016e29fSHarshad Shirwadkar 					unsigned long count)
63808016e29fSHarshad Shirwadkar {
63818016e29fSHarshad Shirwadkar 	struct buffer_head *bitmap_bh;
63828016e29fSHarshad Shirwadkar 	struct super_block *sb = inode->i_sb;
63838016e29fSHarshad Shirwadkar 	struct ext4_group_desc *gdp;
63848016e29fSHarshad Shirwadkar 	struct buffer_head *gdp_bh;
63858016e29fSHarshad Shirwadkar 	ext4_group_t group;
63868016e29fSHarshad Shirwadkar 	ext4_grpblk_t blkoff;
63878016e29fSHarshad Shirwadkar 	int already_freed = 0, err, i;
63888016e29fSHarshad Shirwadkar 
63898016e29fSHarshad Shirwadkar 	ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
63908016e29fSHarshad Shirwadkar 	bitmap_bh = ext4_read_block_bitmap(sb, group);
63918016e29fSHarshad Shirwadkar 	if (IS_ERR(bitmap_bh)) {
63928016e29fSHarshad Shirwadkar 		pr_warn("Failed to read block bitmap\n");
63938016e29fSHarshad Shirwadkar 		return;
63948016e29fSHarshad Shirwadkar 	}
63958016e29fSHarshad Shirwadkar 	gdp = ext4_get_group_desc(sb, group, &gdp_bh);
63968016e29fSHarshad Shirwadkar 	if (!gdp)
63971b5c9d34SKemeng Shi 		goto err_out;
63988016e29fSHarshad Shirwadkar 
63998016e29fSHarshad Shirwadkar 	for (i = 0; i < count; i++) {
64008016e29fSHarshad Shirwadkar 		if (!mb_test_bit(blkoff + i, bitmap_bh->b_data))
64018016e29fSHarshad Shirwadkar 			already_freed++;
64028016e29fSHarshad Shirwadkar 	}
64038016e29fSHarshad Shirwadkar 	mb_clear_bits(bitmap_bh->b_data, blkoff, count);
64048016e29fSHarshad Shirwadkar 	err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
64058016e29fSHarshad Shirwadkar 	if (err)
64061b5c9d34SKemeng Shi 		goto err_out;
64078016e29fSHarshad Shirwadkar 	ext4_free_group_clusters_set(
64088016e29fSHarshad Shirwadkar 		sb, gdp, ext4_free_group_clusters(sb, gdp) +
64098016e29fSHarshad Shirwadkar 		count - already_freed);
64101df9bde4SKemeng Shi 	ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
64118016e29fSHarshad Shirwadkar 	ext4_group_desc_csum_set(sb, group, gdp);
64128016e29fSHarshad Shirwadkar 	ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
64138016e29fSHarshad Shirwadkar 	sync_dirty_buffer(bitmap_bh);
64148016e29fSHarshad Shirwadkar 	sync_dirty_buffer(gdp_bh);
64151b5c9d34SKemeng Shi 
64161b5c9d34SKemeng Shi err_out:
64178016e29fSHarshad Shirwadkar 	brelse(bitmap_bh);
64188016e29fSHarshad Shirwadkar }
64198016e29fSHarshad Shirwadkar 
642044338711STheodore Ts'o /**
64218ac3939dSRitesh Harjani  * ext4_mb_clear_bb() -- helper function for freeing blocks.
64228ac3939dSRitesh Harjani  *			Used by ext4_free_blocks()
642344338711STheodore Ts'o  * @handle:		handle for this transaction
642444338711STheodore Ts'o  * @inode:		inode
6425c60990b3STheodore Ts'o  * @block:		starting physical block to be freed
6426c60990b3STheodore Ts'o  * @count:		number of blocks to be freed
64275def1360SYongqiang Yang  * @flags:		flags used by ext4_free_blocks
6428c9de560dSAlex Tomas  */
64298ac3939dSRitesh Harjani static void ext4_mb_clear_bb(handle_t *handle, struct inode *inode,
64308ac3939dSRitesh Harjani 			       ext4_fsblk_t block, unsigned long count,
64318ac3939dSRitesh Harjani 			       int flags)
6432c9de560dSAlex Tomas {
643326346ff6SAneesh Kumar K.V 	struct buffer_head *bitmap_bh = NULL;
6434c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
6435c9de560dSAlex Tomas 	struct ext4_group_desc *gdp;
64365354b2afSTheodore Ts'o 	struct ext4_group_info *grp;
6437498e5f24STheodore Ts'o 	unsigned int overflow;
6438c9de560dSAlex Tomas 	ext4_grpblk_t bit;
6439c9de560dSAlex Tomas 	struct buffer_head *gd_bh;
6440c9de560dSAlex Tomas 	ext4_group_t block_group;
6441c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
6442c9de560dSAlex Tomas 	struct ext4_buddy e4b;
644384130193STheodore Ts'o 	unsigned int count_clusters;
6444c9de560dSAlex Tomas 	int err = 0;
6445c9de560dSAlex Tomas 	int ret;
6446c9de560dSAlex Tomas 
64478016e29fSHarshad Shirwadkar 	sbi = EXT4_SB(sb);
64488016e29fSHarshad Shirwadkar 
64491e1c2b86SLukas Czerner 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
64501e1c2b86SLukas Czerner 	    !ext4_inode_block_valid(inode, block, count)) {
64511e1c2b86SLukas Czerner 		ext4_error(sb, "Freeing blocks in system zone - "
64521e1c2b86SLukas Czerner 			   "Block = %llu, count = %lu", block, count);
64531e1c2b86SLukas Czerner 		/* err = 0. ext4_std_error should be a no op */
64541e1c2b86SLukas Czerner 		goto error_return;
64551e1c2b86SLukas Czerner 	}
64561e1c2b86SLukas Czerner 	flags |= EXT4_FREE_BLOCKS_VALIDATED;
64571e1c2b86SLukas Czerner 
6458c9de560dSAlex Tomas do_more:
6459c9de560dSAlex Tomas 	overflow = 0;
6460c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
6461c9de560dSAlex Tomas 
64625354b2afSTheodore Ts'o 	grp = ext4_get_group_info(sb, block_group);
64635354b2afSTheodore Ts'o 	if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
6464163a203dSDarrick J. Wong 		return;
6465163a203dSDarrick J. Wong 
6466c9de560dSAlex Tomas 	/*
6467c9de560dSAlex Tomas 	 * Check to see if we are freeing blocks across a group
6468c9de560dSAlex Tomas 	 * boundary.
6469c9de560dSAlex Tomas 	 */
647084130193STheodore Ts'o 	if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
647184130193STheodore Ts'o 		overflow = EXT4_C2B(sbi, bit) + count -
647284130193STheodore Ts'o 			EXT4_BLOCKS_PER_GROUP(sb);
6473c9de560dSAlex Tomas 		count -= overflow;
64741e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
64751e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6476c9de560dSAlex Tomas 	}
6477810da240SLukas Czerner 	count_clusters = EXT4_NUM_B2C(sbi, count);
6478574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, block_group);
64799008a58eSDarrick J. Wong 	if (IS_ERR(bitmap_bh)) {
64809008a58eSDarrick J. Wong 		err = PTR_ERR(bitmap_bh);
64819008a58eSDarrick J. Wong 		bitmap_bh = NULL;
6482c9de560dSAlex Tomas 		goto error_return;
6483ce89f46cSAneesh Kumar K.V 	}
6484c9de560dSAlex Tomas 	gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
6485ce89f46cSAneesh Kumar K.V 	if (!gdp) {
6486ce89f46cSAneesh Kumar K.V 		err = -EIO;
6487c9de560dSAlex Tomas 		goto error_return;
6488ce89f46cSAneesh Kumar K.V 	}
6489c9de560dSAlex Tomas 
64901e1c2b86SLukas Czerner 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
64911e1c2b86SLukas Czerner 	    !ext4_inode_block_valid(inode, block, count)) {
649212062dddSEric Sandeen 		ext4_error(sb, "Freeing blocks in system zone - "
64930610b6e9STheodore Ts'o 			   "Block = %llu, count = %lu", block, count);
6494519deca0SAneesh Kumar K.V 		/* err = 0. ext4_std_error should be a no op */
6495519deca0SAneesh Kumar K.V 		goto error_return;
6496c9de560dSAlex Tomas 	}
6497c9de560dSAlex Tomas 
6498c9de560dSAlex Tomas 	BUFFER_TRACE(bitmap_bh, "getting write access");
6499188c299eSJan Kara 	err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
6500188c299eSJan Kara 					    EXT4_JTR_NONE);
6501c9de560dSAlex Tomas 	if (err)
6502c9de560dSAlex Tomas 		goto error_return;
6503c9de560dSAlex Tomas 
6504c9de560dSAlex Tomas 	/*
6505c9de560dSAlex Tomas 	 * We are about to modify some metadata.  Call the journal APIs
6506c9de560dSAlex Tomas 	 * to unshare ->b_data if a currently-committing transaction is
6507c9de560dSAlex Tomas 	 * using it
6508c9de560dSAlex Tomas 	 */
6509c9de560dSAlex Tomas 	BUFFER_TRACE(gd_bh, "get_write_access");
6510188c299eSJan Kara 	err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
6511c9de560dSAlex Tomas 	if (err)
6512c9de560dSAlex Tomas 		goto error_return;
6513c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
6514c9de560dSAlex Tomas 	{
6515c9de560dSAlex Tomas 		int i;
651684130193STheodore Ts'o 		for (i = 0; i < count_clusters; i++)
6517c9de560dSAlex Tomas 			BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
6518c9de560dSAlex Tomas 	}
6519c9de560dSAlex Tomas #endif
652084130193STheodore Ts'o 	trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
6521c9de560dSAlex Tomas 
6522adb7ef60SKonstantin Khlebnikov 	/* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
6523adb7ef60SKonstantin Khlebnikov 	err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
6524adb7ef60SKonstantin Khlebnikov 				     GFP_NOFS|__GFP_NOFAIL);
6525920313a7SAneesh Kumar K.V 	if (err)
6526920313a7SAneesh Kumar K.V 		goto error_return;
6527e6362609STheodore Ts'o 
6528f96c450dSDaeho Jeong 	/*
6529f96c450dSDaeho Jeong 	 * We need to make sure we don't reuse the freed block until after the
6530f96c450dSDaeho Jeong 	 * transaction is committed. We make an exception if the inode is to be
6531f96c450dSDaeho Jeong 	 * written in writeback mode since writeback mode has weak data
6532f96c450dSDaeho Jeong 	 * consistency guarantees.
6533f96c450dSDaeho Jeong 	 */
6534f96c450dSDaeho Jeong 	if (ext4_handle_valid(handle) &&
6535f96c450dSDaeho Jeong 	    ((flags & EXT4_FREE_BLOCKS_METADATA) ||
6536f96c450dSDaeho Jeong 	     !ext4_should_writeback_data(inode))) {
65377a2fcbf7SAneesh Kumar K.V 		struct ext4_free_data *new_entry;
65387a2fcbf7SAneesh Kumar K.V 		/*
65397444a072SMichal Hocko 		 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
65407444a072SMichal Hocko 		 * to fail.
65417a2fcbf7SAneesh Kumar K.V 		 */
65427444a072SMichal Hocko 		new_entry = kmem_cache_alloc(ext4_free_data_cachep,
65437444a072SMichal Hocko 				GFP_NOFS|__GFP_NOFAIL);
654418aadd47SBobi Jam 		new_entry->efd_start_cluster = bit;
654518aadd47SBobi Jam 		new_entry->efd_group = block_group;
654618aadd47SBobi Jam 		new_entry->efd_count = count_clusters;
654718aadd47SBobi Jam 		new_entry->efd_tid = handle->h_transaction->t_tid;
6548955ce5f5SAneesh Kumar K.V 
65497a2fcbf7SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
655084130193STheodore Ts'o 		mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
65517a2fcbf7SAneesh Kumar K.V 		ext4_mb_free_metadata(handle, &e4b, new_entry);
6552c9de560dSAlex Tomas 	} else {
65537a2fcbf7SAneesh Kumar K.V 		/* need to update group_info->bb_free and bitmap
65547a2fcbf7SAneesh Kumar K.V 		 * with group lock held. generate_buddy look at
65557a2fcbf7SAneesh Kumar K.V 		 * them with group lock_held
65567a2fcbf7SAneesh Kumar K.V 		 */
6557d71c1ae2SLukas Czerner 		if (test_opt(sb, DISCARD)) {
6558247c3d21SKemeng Shi 			err = ext4_issue_discard(sb, block_group, bit,
6559247c3d21SKemeng Shi 						 count_clusters, NULL);
6560d71c1ae2SLukas Czerner 			if (err && err != -EOPNOTSUPP)
6561d71c1ae2SLukas Czerner 				ext4_msg(sb, KERN_WARNING, "discard request in"
6562a00b482bSRitesh Harjani 					 " group:%u block:%d count:%lu failed"
6563d71c1ae2SLukas Czerner 					 " with %d", block_group, bit, count,
6564d71c1ae2SLukas Czerner 					 err);
65658f9ff189SLukas Czerner 		} else
65668f9ff189SLukas Czerner 			EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
6567d71c1ae2SLukas Czerner 
6568955ce5f5SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
656984130193STheodore Ts'o 		mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
657084130193STheodore Ts'o 		mb_free_blocks(inode, &e4b, bit, count_clusters);
6571c9de560dSAlex Tomas 	}
6572c9de560dSAlex Tomas 
6573021b65bbSTheodore Ts'o 	ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
6574021b65bbSTheodore Ts'o 	ext4_free_group_clusters_set(sb, gdp, ret);
65751df9bde4SKemeng Shi 	ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
6576feb0ab32SDarrick J. Wong 	ext4_group_desc_csum_set(sb, block_group, gdp);
6577955ce5f5SAneesh Kumar K.V 	ext4_unlock_group(sb, block_group);
6578c9de560dSAlex Tomas 
6579772cb7c8SJose R. Santos 	if (sbi->s_log_groups_per_flex) {
6580772cb7c8SJose R. Santos 		ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
658190ba983fSTheodore Ts'o 		atomic64_add(count_clusters,
65827c990728SSuraj Jitindar Singh 			     &sbi_array_rcu_deref(sbi, s_flex_groups,
65837c990728SSuraj Jitindar Singh 						  flex_group)->free_clusters);
6584772cb7c8SJose R. Santos 	}
6585772cb7c8SJose R. Santos 
65869fe67149SEric Whitney 	/*
65879fe67149SEric Whitney 	 * on a bigalloc file system, defer the s_freeclusters_counter
65889fe67149SEric Whitney 	 * update to the caller (ext4_remove_space and friends) so they
65899fe67149SEric Whitney 	 * can determine if a cluster freed here should be rereserved
65909fe67149SEric Whitney 	 */
65919fe67149SEric Whitney 	if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
65927b415bf6SAditya Kali 		if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
65937b415bf6SAditya Kali 			dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
65949fe67149SEric Whitney 		percpu_counter_add(&sbi->s_freeclusters_counter,
65959fe67149SEric Whitney 				   count_clusters);
65969fe67149SEric Whitney 	}
65977d734532SJan Kara 
65987d734532SJan Kara 	ext4_mb_unload_buddy(&e4b);
65997b415bf6SAditya Kali 
66007a2fcbf7SAneesh Kumar K.V 	/* We dirtied the bitmap block */
66017a2fcbf7SAneesh Kumar K.V 	BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
66027a2fcbf7SAneesh Kumar K.V 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
66037a2fcbf7SAneesh Kumar K.V 
6604c9de560dSAlex Tomas 	/* And the group descriptor block */
6605c9de560dSAlex Tomas 	BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
66060390131bSFrank Mayhar 	ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
6607c9de560dSAlex Tomas 	if (!err)
6608c9de560dSAlex Tomas 		err = ret;
6609c9de560dSAlex Tomas 
6610c9de560dSAlex Tomas 	if (overflow && !err) {
6611c9de560dSAlex Tomas 		block += count;
6612c9de560dSAlex Tomas 		count = overflow;
6613c9de560dSAlex Tomas 		put_bh(bitmap_bh);
66141e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
66151e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6616c9de560dSAlex Tomas 		goto do_more;
6617c9de560dSAlex Tomas 	}
6618c9de560dSAlex Tomas error_return:
6619c9de560dSAlex Tomas 	brelse(bitmap_bh);
6620c9de560dSAlex Tomas 	ext4_std_error(sb, err);
6621c9de560dSAlex Tomas }
66227360d173SLukas Czerner 
66237360d173SLukas Czerner /**
66248ac3939dSRitesh Harjani  * ext4_free_blocks() -- Free given blocks and update quota
66258ac3939dSRitesh Harjani  * @handle:		handle for this transaction
66268ac3939dSRitesh Harjani  * @inode:		inode
66278ac3939dSRitesh Harjani  * @bh:			optional buffer of the block to be freed
66288ac3939dSRitesh Harjani  * @block:		starting physical block to be freed
66298ac3939dSRitesh Harjani  * @count:		number of blocks to be freed
66308ac3939dSRitesh Harjani  * @flags:		flags used by ext4_free_blocks
66318ac3939dSRitesh Harjani  */
66328ac3939dSRitesh Harjani void ext4_free_blocks(handle_t *handle, struct inode *inode,
66338ac3939dSRitesh Harjani 		      struct buffer_head *bh, ext4_fsblk_t block,
66348ac3939dSRitesh Harjani 		      unsigned long count, int flags)
66358ac3939dSRitesh Harjani {
66368ac3939dSRitesh Harjani 	struct super_block *sb = inode->i_sb;
66378ac3939dSRitesh Harjani 	unsigned int overflow;
66388ac3939dSRitesh Harjani 	struct ext4_sb_info *sbi;
66398ac3939dSRitesh Harjani 
66408ac3939dSRitesh Harjani 	sbi = EXT4_SB(sb);
66418ac3939dSRitesh Harjani 
66428ac3939dSRitesh Harjani 	if (bh) {
66438ac3939dSRitesh Harjani 		if (block)
66448ac3939dSRitesh Harjani 			BUG_ON(block != bh->b_blocknr);
66458ac3939dSRitesh Harjani 		else
66468ac3939dSRitesh Harjani 			block = bh->b_blocknr;
66478ac3939dSRitesh Harjani 	}
66488ac3939dSRitesh Harjani 
664911b6890bSKemeng Shi 	if (sbi->s_mount_state & EXT4_FC_REPLAY) {
66502ec6d0a5SKemeng Shi 		ext4_free_blocks_simple(inode, block, EXT4_NUM_B2C(sbi, count));
665111b6890bSKemeng Shi 		return;
665211b6890bSKemeng Shi 	}
665311b6890bSKemeng Shi 
665411b6890bSKemeng Shi 	might_sleep();
665511b6890bSKemeng Shi 
66568ac3939dSRitesh Harjani 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
66578ac3939dSRitesh Harjani 	    !ext4_inode_block_valid(inode, block, count)) {
66588ac3939dSRitesh Harjani 		ext4_error(sb, "Freeing blocks not in datazone - "
66598ac3939dSRitesh Harjani 			   "block = %llu, count = %lu", block, count);
66608ac3939dSRitesh Harjani 		return;
66618ac3939dSRitesh Harjani 	}
66621e1c2b86SLukas Czerner 	flags |= EXT4_FREE_BLOCKS_VALIDATED;
66638ac3939dSRitesh Harjani 
66648ac3939dSRitesh Harjani 	ext4_debug("freeing block %llu\n", block);
66658ac3939dSRitesh Harjani 	trace_ext4_free_blocks(inode, block, count, flags);
66668ac3939dSRitesh Harjani 
66678ac3939dSRitesh Harjani 	if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
66688ac3939dSRitesh Harjani 		BUG_ON(count > 1);
66698ac3939dSRitesh Harjani 
66708ac3939dSRitesh Harjani 		ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
66718ac3939dSRitesh Harjani 			    inode, bh, block);
66728ac3939dSRitesh Harjani 	}
66738ac3939dSRitesh Harjani 
66748ac3939dSRitesh Harjani 	/*
66758ac3939dSRitesh Harjani 	 * If the extent to be freed does not begin on a cluster
66768ac3939dSRitesh Harjani 	 * boundary, we need to deal with partial clusters at the
66778ac3939dSRitesh Harjani 	 * beginning and end of the extent.  Normally we will free
66788ac3939dSRitesh Harjani 	 * blocks at the beginning or the end unless we are explicitly
66798ac3939dSRitesh Harjani 	 * requested to avoid doing so.
66808ac3939dSRitesh Harjani 	 */
66818ac3939dSRitesh Harjani 	overflow = EXT4_PBLK_COFF(sbi, block);
66828ac3939dSRitesh Harjani 	if (overflow) {
66838ac3939dSRitesh Harjani 		if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
66848ac3939dSRitesh Harjani 			overflow = sbi->s_cluster_ratio - overflow;
66858ac3939dSRitesh Harjani 			block += overflow;
66868ac3939dSRitesh Harjani 			if (count > overflow)
66878ac3939dSRitesh Harjani 				count -= overflow;
66888ac3939dSRitesh Harjani 			else
66898ac3939dSRitesh Harjani 				return;
66908ac3939dSRitesh Harjani 		} else {
66918ac3939dSRitesh Harjani 			block -= overflow;
66928ac3939dSRitesh Harjani 			count += overflow;
66938ac3939dSRitesh Harjani 		}
66941e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
66951e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
66968ac3939dSRitesh Harjani 	}
66978ac3939dSRitesh Harjani 	overflow = EXT4_LBLK_COFF(sbi, count);
66988ac3939dSRitesh Harjani 	if (overflow) {
66998ac3939dSRitesh Harjani 		if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
67008ac3939dSRitesh Harjani 			if (count > overflow)
67018ac3939dSRitesh Harjani 				count -= overflow;
67028ac3939dSRitesh Harjani 			else
67038ac3939dSRitesh Harjani 				return;
67048ac3939dSRitesh Harjani 		} else
67058ac3939dSRitesh Harjani 			count += sbi->s_cluster_ratio - overflow;
67061e1c2b86SLukas Czerner 		/* The range changed so it's no longer validated */
67071e1c2b86SLukas Czerner 		flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
67088ac3939dSRitesh Harjani 	}
67098ac3939dSRitesh Harjani 
67108ac3939dSRitesh Harjani 	if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
67118ac3939dSRitesh Harjani 		int i;
67128ac3939dSRitesh Harjani 		int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
67138ac3939dSRitesh Harjani 
67148ac3939dSRitesh Harjani 		for (i = 0; i < count; i++) {
67158ac3939dSRitesh Harjani 			cond_resched();
67168ac3939dSRitesh Harjani 			if (is_metadata)
67178ac3939dSRitesh Harjani 				bh = sb_find_get_block(inode->i_sb, block + i);
67188ac3939dSRitesh Harjani 			ext4_forget(handle, is_metadata, inode, bh, block + i);
67198ac3939dSRitesh Harjani 		}
67208ac3939dSRitesh Harjani 	}
67218ac3939dSRitesh Harjani 
67228ac3939dSRitesh Harjani 	ext4_mb_clear_bb(handle, inode, block, count, flags);
67238ac3939dSRitesh Harjani }
67248ac3939dSRitesh Harjani 
67258ac3939dSRitesh Harjani /**
67260529155eSYongqiang Yang  * ext4_group_add_blocks() -- Add given blocks to an existing group
67272846e820SAmir Goldstein  * @handle:			handle to this transaction
67282846e820SAmir Goldstein  * @sb:				super block
67294907cb7bSAnatol Pomozov  * @block:			start physical block to add to the block group
67302846e820SAmir Goldstein  * @count:			number of blocks to free
67312846e820SAmir Goldstein  *
6732e73a347bSAmir Goldstein  * This marks the blocks as free in the bitmap and buddy.
67332846e820SAmir Goldstein  */
6734cc7365dfSYongqiang Yang int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
67352846e820SAmir Goldstein 			 ext4_fsblk_t block, unsigned long count)
67362846e820SAmir Goldstein {
67372846e820SAmir Goldstein 	struct buffer_head *bitmap_bh = NULL;
67382846e820SAmir Goldstein 	struct buffer_head *gd_bh;
67392846e820SAmir Goldstein 	ext4_group_t block_group;
67402846e820SAmir Goldstein 	ext4_grpblk_t bit;
67412846e820SAmir Goldstein 	unsigned int i;
67422846e820SAmir Goldstein 	struct ext4_group_desc *desc;
67432846e820SAmir Goldstein 	struct ext4_sb_info *sbi = EXT4_SB(sb);
6744e73a347bSAmir Goldstein 	struct ext4_buddy e4b;
6745d77147ffSharshads 	int err = 0, ret, free_clusters_count;
6746d77147ffSharshads 	ext4_grpblk_t clusters_freed;
6747d77147ffSharshads 	ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
6748d77147ffSharshads 	ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
6749d77147ffSharshads 	unsigned long cluster_count = last_cluster - first_cluster + 1;
67502846e820SAmir Goldstein 
67512846e820SAmir Goldstein 	ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
67522846e820SAmir Goldstein 
67534740b830SYongqiang Yang 	if (count == 0)
67544740b830SYongqiang Yang 		return 0;
67554740b830SYongqiang Yang 
67562846e820SAmir Goldstein 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
67572846e820SAmir Goldstein 	/*
67582846e820SAmir Goldstein 	 * Check to see if we are freeing blocks across a group
67592846e820SAmir Goldstein 	 * boundary.
67602846e820SAmir Goldstein 	 */
6761d77147ffSharshads 	if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
6762d77147ffSharshads 		ext4_warning(sb, "too many blocks added to group %u",
6763cc7365dfSYongqiang Yang 			     block_group);
6764cc7365dfSYongqiang Yang 		err = -EINVAL;
67652846e820SAmir Goldstein 		goto error_return;
6766cc7365dfSYongqiang Yang 	}
67672cd05cc3STheodore Ts'o 
67682846e820SAmir Goldstein 	bitmap_bh = ext4_read_block_bitmap(sb, block_group);
67699008a58eSDarrick J. Wong 	if (IS_ERR(bitmap_bh)) {
67709008a58eSDarrick J. Wong 		err = PTR_ERR(bitmap_bh);
67719008a58eSDarrick J. Wong 		bitmap_bh = NULL;
67722846e820SAmir Goldstein 		goto error_return;
6773cc7365dfSYongqiang Yang 	}
6774cc7365dfSYongqiang Yang 
67752846e820SAmir Goldstein 	desc = ext4_get_group_desc(sb, block_group, &gd_bh);
6776cc7365dfSYongqiang Yang 	if (!desc) {
6777cc7365dfSYongqiang Yang 		err = -EIO;
67782846e820SAmir Goldstein 		goto error_return;
6779cc7365dfSYongqiang Yang 	}
67802846e820SAmir Goldstein 
6781a00b482bSRitesh Harjani 	if (!ext4_sb_block_valid(sb, NULL, block, count)) {
67822846e820SAmir Goldstein 		ext4_error(sb, "Adding blocks in system zones - "
67832846e820SAmir Goldstein 			   "Block = %llu, count = %lu",
67842846e820SAmir Goldstein 			   block, count);
6785cc7365dfSYongqiang Yang 		err = -EINVAL;
67862846e820SAmir Goldstein 		goto error_return;
67872846e820SAmir Goldstein 	}
67882846e820SAmir Goldstein 
67892cd05cc3STheodore Ts'o 	BUFFER_TRACE(bitmap_bh, "getting write access");
6790188c299eSJan Kara 	err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
6791188c299eSJan Kara 					    EXT4_JTR_NONE);
67922846e820SAmir Goldstein 	if (err)
67932846e820SAmir Goldstein 		goto error_return;
67942846e820SAmir Goldstein 
67952846e820SAmir Goldstein 	/*
67962846e820SAmir Goldstein 	 * We are about to modify some metadata.  Call the journal APIs
67972846e820SAmir Goldstein 	 * to unshare ->b_data if a currently-committing transaction is
67982846e820SAmir Goldstein 	 * using it
67992846e820SAmir Goldstein 	 */
68002846e820SAmir Goldstein 	BUFFER_TRACE(gd_bh, "get_write_access");
6801188c299eSJan Kara 	err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
68022846e820SAmir Goldstein 	if (err)
68032846e820SAmir Goldstein 		goto error_return;
6804e73a347bSAmir Goldstein 
6805d77147ffSharshads 	for (i = 0, clusters_freed = 0; i < cluster_count; i++) {
68062846e820SAmir Goldstein 		BUFFER_TRACE(bitmap_bh, "clear bit");
6807e73a347bSAmir Goldstein 		if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
68082846e820SAmir Goldstein 			ext4_error(sb, "bit already cleared for block %llu",
68092846e820SAmir Goldstein 				   (ext4_fsblk_t)(block + i));
68102846e820SAmir Goldstein 			BUFFER_TRACE(bitmap_bh, "bit already cleared");
68112846e820SAmir Goldstein 		} else {
6812d77147ffSharshads 			clusters_freed++;
68132846e820SAmir Goldstein 		}
68142846e820SAmir Goldstein 	}
6815e73a347bSAmir Goldstein 
6816e73a347bSAmir Goldstein 	err = ext4_mb_load_buddy(sb, block_group, &e4b);
6817e73a347bSAmir Goldstein 	if (err)
6818e73a347bSAmir Goldstein 		goto error_return;
6819e73a347bSAmir Goldstein 
6820e73a347bSAmir Goldstein 	/*
6821e73a347bSAmir Goldstein 	 * need to update group_info->bb_free and bitmap
6822e73a347bSAmir Goldstein 	 * with group lock held. generate_buddy look at
6823e73a347bSAmir Goldstein 	 * them with group lock_held
6824e73a347bSAmir Goldstein 	 */
68252846e820SAmir Goldstein 	ext4_lock_group(sb, block_group);
6826d77147ffSharshads 	mb_clear_bits(bitmap_bh->b_data, bit, cluster_count);
6827d77147ffSharshads 	mb_free_blocks(NULL, &e4b, bit, cluster_count);
6828d77147ffSharshads 	free_clusters_count = clusters_freed +
6829d77147ffSharshads 		ext4_free_group_clusters(sb, desc);
6830d77147ffSharshads 	ext4_free_group_clusters_set(sb, desc, free_clusters_count);
68311df9bde4SKemeng Shi 	ext4_block_bitmap_csum_set(sb, desc, bitmap_bh);
6832feb0ab32SDarrick J. Wong 	ext4_group_desc_csum_set(sb, block_group, desc);
68332846e820SAmir Goldstein 	ext4_unlock_group(sb, block_group);
683457042651STheodore Ts'o 	percpu_counter_add(&sbi->s_freeclusters_counter,
6835d77147ffSharshads 			   clusters_freed);
68362846e820SAmir Goldstein 
68372846e820SAmir Goldstein 	if (sbi->s_log_groups_per_flex) {
68382846e820SAmir Goldstein 		ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
6839d77147ffSharshads 		atomic64_add(clusters_freed,
68407c990728SSuraj Jitindar Singh 			     &sbi_array_rcu_deref(sbi, s_flex_groups,
68417c990728SSuraj Jitindar Singh 						  flex_group)->free_clusters);
68422846e820SAmir Goldstein 	}
6843e73a347bSAmir Goldstein 
6844e73a347bSAmir Goldstein 	ext4_mb_unload_buddy(&e4b);
68452846e820SAmir Goldstein 
68462846e820SAmir Goldstein 	/* We dirtied the bitmap block */
68472846e820SAmir Goldstein 	BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
68482846e820SAmir Goldstein 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
68492846e820SAmir Goldstein 
68502846e820SAmir Goldstein 	/* And the group descriptor block */
68512846e820SAmir Goldstein 	BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
68522846e820SAmir Goldstein 	ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
68532846e820SAmir Goldstein 	if (!err)
68542846e820SAmir Goldstein 		err = ret;
68552846e820SAmir Goldstein 
68562846e820SAmir Goldstein error_return:
68572846e820SAmir Goldstein 	brelse(bitmap_bh);
68582846e820SAmir Goldstein 	ext4_std_error(sb, err);
6859cc7365dfSYongqiang Yang 	return err;
68602846e820SAmir Goldstein }
68612846e820SAmir Goldstein 
68622846e820SAmir Goldstein /**
68637360d173SLukas Czerner  * ext4_trim_extent -- function to TRIM one single free extent in the group
68647360d173SLukas Czerner  * @sb:		super block for the file system
68657360d173SLukas Czerner  * @start:	starting block of the free extent in the alloc. group
68667360d173SLukas Czerner  * @count:	number of blocks to TRIM
68677360d173SLukas Czerner  * @e4b:	ext4 buddy for the group
68687360d173SLukas Czerner  *
68697360d173SLukas Czerner  * Trim "count" blocks starting at "start" in the "group". To assure that no
68707360d173SLukas Czerner  * one will allocate those blocks, mark it as used in buddy bitmap. This must
68717360d173SLukas Czerner  * be called with under the group lock.
68727360d173SLukas Czerner  */
6873bd2eea8dSWang Jianchao static int ext4_trim_extent(struct super_block *sb,
6874bd2eea8dSWang Jianchao 		int start, int count, struct ext4_buddy *e4b)
6875e2cbd587Sjon ernst __releases(bitlock)
6876e2cbd587Sjon ernst __acquires(bitlock)
68777360d173SLukas Czerner {
68787360d173SLukas Czerner 	struct ext4_free_extent ex;
6879bd2eea8dSWang Jianchao 	ext4_group_t group = e4b->bd_group;
6880d71c1ae2SLukas Czerner 	int ret = 0;
68817360d173SLukas Czerner 
6882b3d4c2b1STao Ma 	trace_ext4_trim_extent(sb, group, start, count);
6883b3d4c2b1STao Ma 
68847360d173SLukas Czerner 	assert_spin_locked(ext4_group_lock_ptr(sb, group));
68857360d173SLukas Czerner 
68867360d173SLukas Czerner 	ex.fe_start = start;
68877360d173SLukas Czerner 	ex.fe_group = group;
68887360d173SLukas Czerner 	ex.fe_len = count;
68897360d173SLukas Czerner 
68907360d173SLukas Czerner 	/*
68917360d173SLukas Czerner 	 * Mark blocks used, so no one can reuse them while
68927360d173SLukas Czerner 	 * being trimmed.
68937360d173SLukas Czerner 	 */
68947360d173SLukas Czerner 	mb_mark_used(e4b, &ex);
68957360d173SLukas Czerner 	ext4_unlock_group(sb, group);
6896a0154344SDaeho Jeong 	ret = ext4_issue_discard(sb, group, start, count, NULL);
68977360d173SLukas Czerner 	ext4_lock_group(sb, group);
68987360d173SLukas Czerner 	mb_free_blocks(NULL, e4b, start, ex.fe_len);
6899d71c1ae2SLukas Czerner 	return ret;
69007360d173SLukas Czerner }
69017360d173SLukas Czerner 
690245e4ab32SJan Kara static ext4_grpblk_t ext4_last_grp_cluster(struct super_block *sb,
690345e4ab32SJan Kara 					   ext4_group_t grp)
690445e4ab32SJan Kara {
690545e4ab32SJan Kara 	if (grp < ext4_get_groups_count(sb))
690645e4ab32SJan Kara 		return EXT4_CLUSTERS_PER_GROUP(sb) - 1;
690745e4ab32SJan Kara 	return (ext4_blocks_count(EXT4_SB(sb)->s_es) -
690845e4ab32SJan Kara 		ext4_group_first_block_no(sb, grp) - 1) >>
690945e4ab32SJan Kara 					EXT4_CLUSTER_BITS(sb);
691045e4ab32SJan Kara }
691145e4ab32SJan Kara 
69125229a658SJan Kara static bool ext4_trim_interrupted(void)
69135229a658SJan Kara {
69145229a658SJan Kara 	return fatal_signal_pending(current) || freezing(current);
69155229a658SJan Kara }
69165229a658SJan Kara 
69176920b391SWang Jianchao static int ext4_try_to_trim_range(struct super_block *sb,
69186920b391SWang Jianchao 		struct ext4_buddy *e4b, ext4_grpblk_t start,
69196920b391SWang Jianchao 		ext4_grpblk_t max, ext4_grpblk_t minblocks)
6920a5fda113STheodore Ts'o __acquires(ext4_group_lock_ptr(sb, e4b->bd_group))
6921a5fda113STheodore Ts'o __releases(ext4_group_lock_ptr(sb, e4b->bd_group))
69226920b391SWang Jianchao {
69236920b391SWang Jianchao 	ext4_grpblk_t next, count, free_count;
692445e4ab32SJan Kara 	bool set_trimmed = false;
69256920b391SWang Jianchao 	void *bitmap;
69266920b391SWang Jianchao 
69276920b391SWang Jianchao 	bitmap = e4b->bd_bitmap;
692845e4ab32SJan Kara 	if (start == 0 && max >= ext4_last_grp_cluster(sb, e4b->bd_group))
692945e4ab32SJan Kara 		set_trimmed = true;
6930de8bf0e5SKemeng Shi 	start = max(e4b->bd_info->bb_first_free, start);
69316920b391SWang Jianchao 	count = 0;
69326920b391SWang Jianchao 	free_count = 0;
69336920b391SWang Jianchao 
69346920b391SWang Jianchao 	while (start <= max) {
69356920b391SWang Jianchao 		start = mb_find_next_zero_bit(bitmap, max + 1, start);
69366920b391SWang Jianchao 		if (start > max)
69376920b391SWang Jianchao 			break;
69386920b391SWang Jianchao 		next = mb_find_next_bit(bitmap, max + 1, start);
69396920b391SWang Jianchao 
69406920b391SWang Jianchao 		if ((next - start) >= minblocks) {
6941afcc4e32SLukas Bulwahn 			int ret = ext4_trim_extent(sb, start, next - start, e4b);
6942afcc4e32SLukas Bulwahn 
69436920b391SWang Jianchao 			if (ret && ret != -EOPNOTSUPP)
694445e4ab32SJan Kara 				return count;
69456920b391SWang Jianchao 			count += next - start;
69466920b391SWang Jianchao 		}
69476920b391SWang Jianchao 		free_count += next - start;
69486920b391SWang Jianchao 		start = next + 1;
69496920b391SWang Jianchao 
69505229a658SJan Kara 		if (ext4_trim_interrupted())
69515229a658SJan Kara 			return count;
69526920b391SWang Jianchao 
69536920b391SWang Jianchao 		if (need_resched()) {
69546920b391SWang Jianchao 			ext4_unlock_group(sb, e4b->bd_group);
69556920b391SWang Jianchao 			cond_resched();
69566920b391SWang Jianchao 			ext4_lock_group(sb, e4b->bd_group);
69576920b391SWang Jianchao 		}
69586920b391SWang Jianchao 
69596920b391SWang Jianchao 		if ((e4b->bd_info->bb_free - free_count) < minblocks)
69606920b391SWang Jianchao 			break;
69616920b391SWang Jianchao 	}
69626920b391SWang Jianchao 
696345e4ab32SJan Kara 	if (set_trimmed)
696445e4ab32SJan Kara 		EXT4_MB_GRP_SET_TRIMMED(e4b->bd_info);
696545e4ab32SJan Kara 
69666920b391SWang Jianchao 	return count;
69676920b391SWang Jianchao }
69686920b391SWang Jianchao 
69697360d173SLukas Czerner /**
69707360d173SLukas Czerner  * ext4_trim_all_free -- function to trim all free space in alloc. group
69717360d173SLukas Czerner  * @sb:			super block for file system
697222612283STao Ma  * @group:		group to be trimmed
69737360d173SLukas Czerner  * @start:		first group block to examine
69747360d173SLukas Czerner  * @max:		last group block to examine
69757360d173SLukas Czerner  * @minblocks:		minimum extent block count
69767360d173SLukas Czerner  *
69777360d173SLukas Czerner  * ext4_trim_all_free walks through group's block bitmap searching for free
69787360d173SLukas Czerner  * extents. When the free extent is found, mark it as used in group buddy
69797360d173SLukas Czerner  * bitmap. Then issue a TRIM command on this extent and free the extent in
6980b6f5558cSWang Jianchao  * the group buddy bitmap.
69817360d173SLukas Czerner  */
69820b75a840SLukas Czerner static ext4_grpblk_t
698378944086SLukas Czerner ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
698478944086SLukas Czerner 		   ext4_grpblk_t start, ext4_grpblk_t max,
698545e4ab32SJan Kara 		   ext4_grpblk_t minblocks)
69867360d173SLukas Czerner {
698778944086SLukas Czerner 	struct ext4_buddy e4b;
69886920b391SWang Jianchao 	int ret;
69897360d173SLukas Czerner 
6990b3d4c2b1STao Ma 	trace_ext4_trim_all_free(sb, group, start, max);
6991b3d4c2b1STao Ma 
699278944086SLukas Czerner 	ret = ext4_mb_load_buddy(sb, group, &e4b);
699378944086SLukas Czerner 	if (ret) {
69949651e6b2SKonstantin Khlebnikov 		ext4_warning(sb, "Error %d loading buddy information for %u",
69959651e6b2SKonstantin Khlebnikov 			     ret, group);
699678944086SLukas Czerner 		return ret;
699778944086SLukas Czerner 	}
699828739eeaSLukas Czerner 
699928739eeaSLukas Czerner 	ext4_lock_group(sb, group);
70003d56b8d2STao Ma 
70016920b391SWang Jianchao 	if (!EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) ||
700245e4ab32SJan Kara 	    minblocks < EXT4_SB(sb)->s_last_trim_minblks)
70036920b391SWang Jianchao 		ret = ext4_try_to_trim_range(sb, &e4b, start, max, minblocks);
700445e4ab32SJan Kara 	else
70056920b391SWang Jianchao 		ret = 0;
70066920b391SWang Jianchao 
70077360d173SLukas Czerner 	ext4_unlock_group(sb, group);
700878944086SLukas Czerner 	ext4_mb_unload_buddy(&e4b);
70097360d173SLukas Czerner 
70107360d173SLukas Czerner 	ext4_debug("trimmed %d blocks in the group %d\n",
70116920b391SWang Jianchao 		ret, group);
70127360d173SLukas Czerner 
7013d71c1ae2SLukas Czerner 	return ret;
70147360d173SLukas Czerner }
70157360d173SLukas Czerner 
70167360d173SLukas Czerner /**
70177360d173SLukas Czerner  * ext4_trim_fs() -- trim ioctl handle function
70187360d173SLukas Czerner  * @sb:			superblock for filesystem
70197360d173SLukas Czerner  * @range:		fstrim_range structure
70207360d173SLukas Czerner  *
70217360d173SLukas Czerner  * start:	First Byte to trim
70227360d173SLukas Czerner  * len:		number of Bytes to trim from start
70237360d173SLukas Czerner  * minlen:	minimum extent length in Bytes
70247360d173SLukas Czerner  * ext4_trim_fs goes through all allocation groups containing Bytes from
70257360d173SLukas Czerner  * start to start+len. For each such a group ext4_trim_all_free function
70267360d173SLukas Czerner  * is invoked to trim all free space.
70277360d173SLukas Czerner  */
70287360d173SLukas Czerner int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
70297360d173SLukas Czerner {
70307b47ef52SChristoph Hellwig 	unsigned int discard_granularity = bdev_discard_granularity(sb->s_bdev);
703178944086SLukas Czerner 	struct ext4_group_info *grp;
7032913eed83SLukas Czerner 	ext4_group_t group, first_group, last_group;
70337137d7a4STheodore Ts'o 	ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
7034913eed83SLukas Czerner 	uint64_t start, end, minlen, trimmed = 0;
70350f0a25bfSJan Kara 	ext4_fsblk_t first_data_blk =
70360f0a25bfSJan Kara 			le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
7037913eed83SLukas Czerner 	ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
70387360d173SLukas Czerner 	int ret = 0;
70397360d173SLukas Czerner 
70407360d173SLukas Czerner 	start = range->start >> sb->s_blocksize_bits;
7041913eed83SLukas Czerner 	end = start + (range->len >> sb->s_blocksize_bits) - 1;
7042aaf7d73eSLukas Czerner 	minlen = EXT4_NUM_B2C(EXT4_SB(sb),
7043aaf7d73eSLukas Czerner 			      range->minlen >> sb->s_blocksize_bits);
70447360d173SLukas Czerner 
70455de35e8dSLukas Czerner 	if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
70465de35e8dSLukas Czerner 	    start >= max_blks ||
70475de35e8dSLukas Czerner 	    range->len < sb->s_blocksize)
70487360d173SLukas Czerner 		return -EINVAL;
7049173b6e38SJan Kara 	/* No point to try to trim less than discard granularity */
70507b47ef52SChristoph Hellwig 	if (range->minlen < discard_granularity) {
7051173b6e38SJan Kara 		minlen = EXT4_NUM_B2C(EXT4_SB(sb),
70527b47ef52SChristoph Hellwig 				discard_granularity >> sb->s_blocksize_bits);
7053173b6e38SJan Kara 		if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
7054173b6e38SJan Kara 			goto out;
7055173b6e38SJan Kara 	}
705645e4ab32SJan Kara 	if (end >= max_blks - 1)
7057913eed83SLukas Czerner 		end = max_blks - 1;
7058913eed83SLukas Czerner 	if (end <= first_data_blk)
705922f10457STao Ma 		goto out;
7060913eed83SLukas Czerner 	if (start < first_data_blk)
70610f0a25bfSJan Kara 		start = first_data_blk;
70627360d173SLukas Czerner 
7063913eed83SLukas Czerner 	/* Determine first and last group to examine based on start and end */
70647360d173SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
70657137d7a4STheodore Ts'o 				     &first_group, &first_cluster);
7066913eed83SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
70677137d7a4STheodore Ts'o 				     &last_group, &last_cluster);
70687360d173SLukas Czerner 
7069913eed83SLukas Czerner 	/* end now represents the last cluster to discard in this group */
7070913eed83SLukas Czerner 	end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
70717360d173SLukas Czerner 
70727360d173SLukas Czerner 	for (group = first_group; group <= last_group; group++) {
70735229a658SJan Kara 		if (ext4_trim_interrupted())
70745229a658SJan Kara 			break;
707578944086SLukas Czerner 		grp = ext4_get_group_info(sb, group);
70765354b2afSTheodore Ts'o 		if (!grp)
70775354b2afSTheodore Ts'o 			continue;
707878944086SLukas Czerner 		/* We only do this if the grp has never been initialized */
707978944086SLukas Czerner 		if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
7080adb7ef60SKonstantin Khlebnikov 			ret = ext4_mb_init_group(sb, group, GFP_NOFS);
708178944086SLukas Czerner 			if (ret)
70827360d173SLukas Czerner 				break;
70837360d173SLukas Czerner 		}
70847360d173SLukas Czerner 
70850ba08517STao Ma 		/*
7086913eed83SLukas Czerner 		 * For all the groups except the last one, last cluster will
7087913eed83SLukas Czerner 		 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
7088913eed83SLukas Czerner 		 * change it for the last group, note that last_cluster is
7089913eed83SLukas Czerner 		 * already computed earlier by ext4_get_group_no_and_offset()
70900ba08517STao Ma 		 */
709145e4ab32SJan Kara 		if (group == last_group)
7092913eed83SLukas Czerner 			end = last_cluster;
709378944086SLukas Czerner 		if (grp->bb_free >= minlen) {
70947137d7a4STheodore Ts'o 			cnt = ext4_trim_all_free(sb, group, first_cluster,
709545e4ab32SJan Kara 						 end, minlen);
70967360d173SLukas Czerner 			if (cnt < 0) {
70977360d173SLukas Czerner 				ret = cnt;
70987360d173SLukas Czerner 				break;
70997360d173SLukas Czerner 			}
71007360d173SLukas Czerner 			trimmed += cnt;
710121e7fd22SLukas Czerner 		}
7102913eed83SLukas Czerner 
7103913eed83SLukas Czerner 		/*
7104913eed83SLukas Czerner 		 * For every group except the first one, we are sure
7105913eed83SLukas Czerner 		 * that the first cluster to discard will be cluster #0.
7106913eed83SLukas Czerner 		 */
71077137d7a4STheodore Ts'o 		first_cluster = 0;
71087360d173SLukas Czerner 	}
71097360d173SLukas Czerner 
71103d56b8d2STao Ma 	if (!ret)
71112327fb2eSLukas Czerner 		EXT4_SB(sb)->s_last_trim_minblks = minlen;
71123d56b8d2STao Ma 
711322f10457STao Ma out:
7114aaf7d73eSLukas Czerner 	range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
71157360d173SLukas Czerner 	return ret;
71167360d173SLukas Czerner }
71170c9ec4beSDarrick J. Wong 
71180c9ec4beSDarrick J. Wong /* Iterate all the free extents in the group. */
71190c9ec4beSDarrick J. Wong int
71200c9ec4beSDarrick J. Wong ext4_mballoc_query_range(
71210c9ec4beSDarrick J. Wong 	struct super_block		*sb,
71220c9ec4beSDarrick J. Wong 	ext4_group_t			group,
71230c9ec4beSDarrick J. Wong 	ext4_grpblk_t			start,
71240c9ec4beSDarrick J. Wong 	ext4_grpblk_t			end,
71250c9ec4beSDarrick J. Wong 	ext4_mballoc_query_range_fn	formatter,
71260c9ec4beSDarrick J. Wong 	void				*priv)
71270c9ec4beSDarrick J. Wong {
71280c9ec4beSDarrick J. Wong 	void				*bitmap;
71290c9ec4beSDarrick J. Wong 	ext4_grpblk_t			next;
71300c9ec4beSDarrick J. Wong 	struct ext4_buddy		e4b;
71310c9ec4beSDarrick J. Wong 	int				error;
71320c9ec4beSDarrick J. Wong 
71330c9ec4beSDarrick J. Wong 	error = ext4_mb_load_buddy(sb, group, &e4b);
71340c9ec4beSDarrick J. Wong 	if (error)
71350c9ec4beSDarrick J. Wong 		return error;
71360c9ec4beSDarrick J. Wong 	bitmap = e4b.bd_bitmap;
71370c9ec4beSDarrick J. Wong 
71380c9ec4beSDarrick J. Wong 	ext4_lock_group(sb, group);
71390c9ec4beSDarrick J. Wong 
7140de8bf0e5SKemeng Shi 	start = max(e4b.bd_info->bb_first_free, start);
71410c9ec4beSDarrick J. Wong 	if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
71420c9ec4beSDarrick J. Wong 		end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
71430c9ec4beSDarrick J. Wong 
71440c9ec4beSDarrick J. Wong 	while (start <= end) {
71450c9ec4beSDarrick J. Wong 		start = mb_find_next_zero_bit(bitmap, end + 1, start);
71460c9ec4beSDarrick J. Wong 		if (start > end)
71470c9ec4beSDarrick J. Wong 			break;
71480c9ec4beSDarrick J. Wong 		next = mb_find_next_bit(bitmap, end + 1, start);
71490c9ec4beSDarrick J. Wong 
71500c9ec4beSDarrick J. Wong 		ext4_unlock_group(sb, group);
71510c9ec4beSDarrick J. Wong 		error = formatter(sb, group, start, next - start, priv);
71520c9ec4beSDarrick J. Wong 		if (error)
71530c9ec4beSDarrick J. Wong 			goto out_unload;
71540c9ec4beSDarrick J. Wong 		ext4_lock_group(sb, group);
71550c9ec4beSDarrick J. Wong 
71560c9ec4beSDarrick J. Wong 		start = next + 1;
71570c9ec4beSDarrick J. Wong 	}
71580c9ec4beSDarrick J. Wong 
71590c9ec4beSDarrick J. Wong 	ext4_unlock_group(sb, group);
71600c9ec4beSDarrick J. Wong out_unload:
71610c9ec4beSDarrick J. Wong 	ext4_mb_unload_buddy(&e4b);
71620c9ec4beSDarrick J. Wong 
71630c9ec4beSDarrick J. Wong 	return error;
71640c9ec4beSDarrick J. Wong }
7165