xref: /openbmc/linux/fs/ext4/mballoc.c (revision f96c450d)
1c9de560dSAlex Tomas /*
2c9de560dSAlex Tomas  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3c9de560dSAlex Tomas  * Written by Alex Tomas <alex@clusterfs.com>
4c9de560dSAlex Tomas  *
5c9de560dSAlex Tomas  * This program is free software; you can redistribute it and/or modify
6c9de560dSAlex Tomas  * it under the terms of the GNU General Public License version 2 as
7c9de560dSAlex Tomas  * published by the Free Software Foundation.
8c9de560dSAlex Tomas  *
9c9de560dSAlex Tomas  * This program is distributed in the hope that it will be useful,
10c9de560dSAlex Tomas  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11c9de560dSAlex Tomas  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12c9de560dSAlex Tomas  * GNU General Public License for more details.
13c9de560dSAlex Tomas  *
14c9de560dSAlex Tomas  * You should have received a copy of the GNU General Public Licens
15c9de560dSAlex Tomas  * along with this program; if not, write to the Free Software
16c9de560dSAlex Tomas  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-
17c9de560dSAlex Tomas  */
18c9de560dSAlex Tomas 
19c9de560dSAlex Tomas 
20c9de560dSAlex Tomas /*
21c9de560dSAlex Tomas  * mballoc.c contains the multiblocks allocation routines
22c9de560dSAlex Tomas  */
23c9de560dSAlex Tomas 
2418aadd47SBobi Jam #include "ext4_jbd2.h"
258f6e39a7SMingming Cao #include "mballoc.h"
2628623c2fSTheodore Ts'o #include <linux/log2.h>
27a0b30c12STheodore Ts'o #include <linux/module.h>
285a0e3ad6STejun Heo #include <linux/slab.h>
2966114cadSTejun Heo #include <linux/backing-dev.h>
309bffad1eSTheodore Ts'o #include <trace/events/ext4.h>
319bffad1eSTheodore Ts'o 
32a0b30c12STheodore Ts'o #ifdef CONFIG_EXT4_DEBUG
33a0b30c12STheodore Ts'o ushort ext4_mballoc_debug __read_mostly;
34a0b30c12STheodore Ts'o 
35a0b30c12STheodore Ts'o module_param_named(mballoc_debug, ext4_mballoc_debug, ushort, 0644);
36a0b30c12STheodore Ts'o MODULE_PARM_DESC(mballoc_debug, "Debugging level for ext4's mballoc");
37a0b30c12STheodore Ts'o #endif
38a0b30c12STheodore Ts'o 
39c9de560dSAlex Tomas /*
40c9de560dSAlex Tomas  * MUSTDO:
41c9de560dSAlex Tomas  *   - test ext4_ext_search_left() and ext4_ext_search_right()
42c9de560dSAlex Tomas  *   - search for metadata in few groups
43c9de560dSAlex Tomas  *
44c9de560dSAlex Tomas  * TODO v4:
45c9de560dSAlex Tomas  *   - normalization should take into account whether file is still open
46c9de560dSAlex Tomas  *   - discard preallocations if no free space left (policy?)
47c9de560dSAlex Tomas  *   - don't normalize tails
48c9de560dSAlex Tomas  *   - quota
49c9de560dSAlex Tomas  *   - reservation for superuser
50c9de560dSAlex Tomas  *
51c9de560dSAlex Tomas  * TODO v3:
52c9de560dSAlex Tomas  *   - bitmap read-ahead (proposed by Oleg Drokin aka green)
53c9de560dSAlex Tomas  *   - track min/max extents in each group for better group selection
54c9de560dSAlex Tomas  *   - mb_mark_used() may allocate chunk right after splitting buddy
55c9de560dSAlex Tomas  *   - tree of groups sorted by number of free blocks
56c9de560dSAlex Tomas  *   - error handling
57c9de560dSAlex Tomas  */
58c9de560dSAlex Tomas 
59c9de560dSAlex Tomas /*
60c9de560dSAlex Tomas  * The allocation request involve request for multiple number of blocks
61c9de560dSAlex Tomas  * near to the goal(block) value specified.
62c9de560dSAlex Tomas  *
63b713a5ecSTheodore Ts'o  * During initialization phase of the allocator we decide to use the
64b713a5ecSTheodore Ts'o  * group preallocation or inode preallocation depending on the size of
65b713a5ecSTheodore Ts'o  * the file. The size of the file could be the resulting file size we
66b713a5ecSTheodore Ts'o  * would have after allocation, or the current file size, which ever
67b713a5ecSTheodore Ts'o  * is larger. If the size is less than sbi->s_mb_stream_request we
68b713a5ecSTheodore Ts'o  * select to use the group preallocation. The default value of
69b713a5ecSTheodore Ts'o  * s_mb_stream_request is 16 blocks. This can also be tuned via
70b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
71b713a5ecSTheodore Ts'o  * terms of number of blocks.
72c9de560dSAlex Tomas  *
73c9de560dSAlex Tomas  * The main motivation for having small file use group preallocation is to
74b713a5ecSTheodore Ts'o  * ensure that we have small files closer together on the disk.
75c9de560dSAlex Tomas  *
76b713a5ecSTheodore Ts'o  * First stage the allocator looks at the inode prealloc list,
77b713a5ecSTheodore Ts'o  * ext4_inode_info->i_prealloc_list, which contains list of prealloc
78b713a5ecSTheodore Ts'o  * spaces for this particular inode. The inode prealloc space is
79b713a5ecSTheodore Ts'o  * represented as:
80c9de560dSAlex Tomas  *
81c9de560dSAlex Tomas  * pa_lstart -> the logical start block for this prealloc space
82c9de560dSAlex Tomas  * pa_pstart -> the physical start block for this prealloc space
8353accfa9STheodore Ts'o  * pa_len    -> length for this prealloc space (in clusters)
8453accfa9STheodore Ts'o  * pa_free   ->  free space available in this prealloc space (in clusters)
85c9de560dSAlex Tomas  *
86c9de560dSAlex Tomas  * The inode preallocation space is used looking at the _logical_ start
87c9de560dSAlex Tomas  * block. If only the logical file block falls within the range of prealloc
88caaf7a29STao Ma  * space we will consume the particular prealloc space. This makes sure that
89caaf7a29STao Ma  * we have contiguous physical blocks representing the file blocks
90c9de560dSAlex Tomas  *
91c9de560dSAlex Tomas  * The important thing to be noted in case of inode prealloc space is that
92c9de560dSAlex Tomas  * we don't modify the values associated to inode prealloc space except
93c9de560dSAlex Tomas  * pa_free.
94c9de560dSAlex Tomas  *
95c9de560dSAlex Tomas  * If we are not able to find blocks in the inode prealloc space and if we
96c9de560dSAlex Tomas  * have the group allocation flag set then we look at the locality group
97caaf7a29STao Ma  * prealloc space. These are per CPU prealloc list represented as
98c9de560dSAlex Tomas  *
99c9de560dSAlex Tomas  * ext4_sb_info.s_locality_groups[smp_processor_id()]
100c9de560dSAlex Tomas  *
101c9de560dSAlex Tomas  * The reason for having a per cpu locality group is to reduce the contention
102c9de560dSAlex Tomas  * between CPUs. It is possible to get scheduled at this point.
103c9de560dSAlex Tomas  *
104c9de560dSAlex Tomas  * The locality group prealloc space is used looking at whether we have
10525985edcSLucas De Marchi  * enough free space (pa_free) within the prealloc space.
106c9de560dSAlex Tomas  *
107c9de560dSAlex Tomas  * If we can't allocate blocks via inode prealloc or/and locality group
108c9de560dSAlex Tomas  * prealloc then we look at the buddy cache. The buddy cache is represented
109c9de560dSAlex Tomas  * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
110c9de560dSAlex Tomas  * mapped to the buddy and bitmap information regarding different
111c9de560dSAlex Tomas  * groups. The buddy information is attached to buddy cache inode so that
112c9de560dSAlex Tomas  * we can access them through the page cache. The information regarding
113c9de560dSAlex Tomas  * each group is loaded via ext4_mb_load_buddy.  The information involve
114c9de560dSAlex Tomas  * block bitmap and buddy information. The information are stored in the
115c9de560dSAlex Tomas  * inode as:
116c9de560dSAlex Tomas  *
117c9de560dSAlex Tomas  *  {                        page                        }
118c3a326a6SAneesh Kumar K.V  *  [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
119c9de560dSAlex Tomas  *
120c9de560dSAlex Tomas  *
121c9de560dSAlex Tomas  * one block each for bitmap and buddy information.  So for each group we
122c9de560dSAlex Tomas  * take up 2 blocks. A page can contain blocks_per_page (PAGE_CACHE_SIZE /
123c9de560dSAlex Tomas  * blocksize) blocks.  So it can have information regarding groups_per_page
124c9de560dSAlex Tomas  * which is blocks_per_page/2
125c9de560dSAlex Tomas  *
126c9de560dSAlex Tomas  * The buddy cache inode is not stored on disk. The inode is thrown
127c9de560dSAlex Tomas  * away when the filesystem is unmounted.
128c9de560dSAlex Tomas  *
129c9de560dSAlex Tomas  * We look for count number of blocks in the buddy cache. If we were able
130c9de560dSAlex Tomas  * to locate that many free blocks we return with additional information
131c9de560dSAlex Tomas  * regarding rest of the contiguous physical block available
132c9de560dSAlex Tomas  *
133c9de560dSAlex Tomas  * Before allocating blocks via buddy cache we normalize the request
134c9de560dSAlex Tomas  * blocks. This ensure we ask for more blocks that we needed. The extra
135c9de560dSAlex Tomas  * blocks that we get after allocation is added to the respective prealloc
136c9de560dSAlex Tomas  * list. In case of inode preallocation we follow a list of heuristics
137c9de560dSAlex Tomas  * based on file size. This can be found in ext4_mb_normalize_request. If
138c9de560dSAlex Tomas  * we are doing a group prealloc we try to normalize the request to
13927baebb8STheodore Ts'o  * sbi->s_mb_group_prealloc.  The default value of s_mb_group_prealloc is
14027baebb8STheodore Ts'o  * dependent on the cluster size; for non-bigalloc file systems, it is
141c9de560dSAlex Tomas  * 512 blocks. This can be tuned via
142d7a1fee1SDan Ehrenberg  * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
143c9de560dSAlex Tomas  * terms of number of blocks. If we have mounted the file system with -O
144c9de560dSAlex Tomas  * stripe=<value> option the group prealloc request is normalized to the
145d7a1fee1SDan Ehrenberg  * the smallest multiple of the stripe value (sbi->s_stripe) which is
146d7a1fee1SDan Ehrenberg  * greater than the default mb_group_prealloc.
147c9de560dSAlex Tomas  *
148d7a1fee1SDan Ehrenberg  * The regular allocator (using the buddy cache) supports a few tunables.
149c9de560dSAlex Tomas  *
150b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_min_to_scan
151b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_max_to_scan
152b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_order2_req
153c9de560dSAlex Tomas  *
154b713a5ecSTheodore Ts'o  * The regular allocator uses buddy scan only if the request len is power of
155c9de560dSAlex Tomas  * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
156c9de560dSAlex Tomas  * value of s_mb_order2_reqs can be tuned via
157b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_order2_req.  If the request len is equal to
158af901ca1SAndré Goddard Rosa  * stripe size (sbi->s_stripe), we try to search for contiguous block in
159b713a5ecSTheodore Ts'o  * stripe size. This should result in better allocation on RAID setups. If
160b713a5ecSTheodore Ts'o  * not, we search in the specific group using bitmap for best extents. The
161b713a5ecSTheodore Ts'o  * tunable min_to_scan and max_to_scan control the behaviour here.
162c9de560dSAlex Tomas  * min_to_scan indicate how long the mballoc __must__ look for a best
163b713a5ecSTheodore Ts'o  * extent and max_to_scan indicates how long the mballoc __can__ look for a
164c9de560dSAlex Tomas  * best extent in the found extents. Searching for the blocks starts with
165c9de560dSAlex Tomas  * the group specified as the goal value in allocation context via
166c9de560dSAlex Tomas  * ac_g_ex. Each group is first checked based on the criteria whether it
167caaf7a29STao Ma  * can be used for allocation. ext4_mb_good_group explains how the groups are
168c9de560dSAlex Tomas  * checked.
169c9de560dSAlex Tomas  *
170c9de560dSAlex Tomas  * Both the prealloc space are getting populated as above. So for the first
171c9de560dSAlex Tomas  * request we will hit the buddy cache which will result in this prealloc
172c9de560dSAlex Tomas  * space getting filled. The prealloc space is then later used for the
173c9de560dSAlex Tomas  * subsequent request.
174c9de560dSAlex Tomas  */
175c9de560dSAlex Tomas 
176c9de560dSAlex Tomas /*
177c9de560dSAlex Tomas  * mballoc operates on the following data:
178c9de560dSAlex Tomas  *  - on-disk bitmap
179c9de560dSAlex Tomas  *  - in-core buddy (actually includes buddy and bitmap)
180c9de560dSAlex Tomas  *  - preallocation descriptors (PAs)
181c9de560dSAlex Tomas  *
182c9de560dSAlex Tomas  * there are two types of preallocations:
183c9de560dSAlex Tomas  *  - inode
184c9de560dSAlex Tomas  *    assiged to specific inode and can be used for this inode only.
185c9de560dSAlex Tomas  *    it describes part of inode's space preallocated to specific
186c9de560dSAlex Tomas  *    physical blocks. any block from that preallocated can be used
187c9de560dSAlex Tomas  *    independent. the descriptor just tracks number of blocks left
188c9de560dSAlex Tomas  *    unused. so, before taking some block from descriptor, one must
189c9de560dSAlex Tomas  *    make sure corresponded logical block isn't allocated yet. this
190c9de560dSAlex Tomas  *    also means that freeing any block within descriptor's range
191c9de560dSAlex Tomas  *    must discard all preallocated blocks.
192c9de560dSAlex Tomas  *  - locality group
193c9de560dSAlex Tomas  *    assigned to specific locality group which does not translate to
194c9de560dSAlex Tomas  *    permanent set of inodes: inode can join and leave group. space
195c9de560dSAlex Tomas  *    from this type of preallocation can be used for any inode. thus
196c9de560dSAlex Tomas  *    it's consumed from the beginning to the end.
197c9de560dSAlex Tomas  *
198c9de560dSAlex Tomas  * relation between them can be expressed as:
199c9de560dSAlex Tomas  *    in-core buddy = on-disk bitmap + preallocation descriptors
200c9de560dSAlex Tomas  *
201c9de560dSAlex Tomas  * this mean blocks mballoc considers used are:
202c9de560dSAlex Tomas  *  - allocated blocks (persistent)
203c9de560dSAlex Tomas  *  - preallocated blocks (non-persistent)
204c9de560dSAlex Tomas  *
205c9de560dSAlex Tomas  * consistency in mballoc world means that at any time a block is either
206c9de560dSAlex Tomas  * free or used in ALL structures. notice: "any time" should not be read
207c9de560dSAlex Tomas  * literally -- time is discrete and delimited by locks.
208c9de560dSAlex Tomas  *
209c9de560dSAlex Tomas  *  to keep it simple, we don't use block numbers, instead we count number of
210c9de560dSAlex Tomas  *  blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
211c9de560dSAlex Tomas  *
212c9de560dSAlex Tomas  * all operations can be expressed as:
213c9de560dSAlex Tomas  *  - init buddy:			buddy = on-disk + PAs
214c9de560dSAlex Tomas  *  - new PA:				buddy += N; PA = N
215c9de560dSAlex Tomas  *  - use inode PA:			on-disk += N; PA -= N
216c9de560dSAlex Tomas  *  - discard inode PA			buddy -= on-disk - PA; PA = 0
217c9de560dSAlex Tomas  *  - use locality group PA		on-disk += N; PA -= N
218c9de560dSAlex Tomas  *  - discard locality group PA		buddy -= PA; PA = 0
219c9de560dSAlex Tomas  *  note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
220c9de560dSAlex Tomas  *        is used in real operation because we can't know actual used
221c9de560dSAlex Tomas  *        bits from PA, only from on-disk bitmap
222c9de560dSAlex Tomas  *
223c9de560dSAlex Tomas  * if we follow this strict logic, then all operations above should be atomic.
224c9de560dSAlex Tomas  * given some of them can block, we'd have to use something like semaphores
225c9de560dSAlex Tomas  * killing performance on high-end SMP hardware. let's try to relax it using
226c9de560dSAlex Tomas  * the following knowledge:
227c9de560dSAlex Tomas  *  1) if buddy is referenced, it's already initialized
228c9de560dSAlex Tomas  *  2) while block is used in buddy and the buddy is referenced,
229c9de560dSAlex Tomas  *     nobody can re-allocate that block
230c9de560dSAlex Tomas  *  3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
231c9de560dSAlex Tomas  *     bit set and PA claims same block, it's OK. IOW, one can set bit in
232c9de560dSAlex Tomas  *     on-disk bitmap if buddy has same bit set or/and PA covers corresponded
233c9de560dSAlex Tomas  *     block
234c9de560dSAlex Tomas  *
235c9de560dSAlex Tomas  * so, now we're building a concurrency table:
236c9de560dSAlex Tomas  *  - init buddy vs.
237c9de560dSAlex Tomas  *    - new PA
238c9de560dSAlex Tomas  *      blocks for PA are allocated in the buddy, buddy must be referenced
239c9de560dSAlex Tomas  *      until PA is linked to allocation group to avoid concurrent buddy init
240c9de560dSAlex Tomas  *    - use inode PA
241c9de560dSAlex Tomas  *      we need to make sure that either on-disk bitmap or PA has uptodate data
242c9de560dSAlex Tomas  *      given (3) we care that PA-=N operation doesn't interfere with init
243c9de560dSAlex Tomas  *    - discard inode PA
244c9de560dSAlex Tomas  *      the simplest way would be to have buddy initialized by the discard
245c9de560dSAlex Tomas  *    - use locality group PA
246c9de560dSAlex Tomas  *      again PA-=N must be serialized with init
247c9de560dSAlex Tomas  *    - discard locality group PA
248c9de560dSAlex Tomas  *      the simplest way would be to have buddy initialized by the discard
249c9de560dSAlex Tomas  *  - new PA vs.
250c9de560dSAlex Tomas  *    - use inode PA
251c9de560dSAlex Tomas  *      i_data_sem serializes them
252c9de560dSAlex Tomas  *    - discard inode PA
253c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
254c9de560dSAlex Tomas  *    - use locality group PA
255c9de560dSAlex Tomas  *      some mutex should serialize them
256c9de560dSAlex Tomas  *    - discard locality group PA
257c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
258c9de560dSAlex Tomas  *  - use inode PA
259c9de560dSAlex Tomas  *    - use inode PA
260c9de560dSAlex Tomas  *      i_data_sem or another mutex should serializes them
261c9de560dSAlex Tomas  *    - discard inode PA
262c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
263c9de560dSAlex Tomas  *    - use locality group PA
264c9de560dSAlex Tomas  *      nothing wrong here -- they're different PAs covering different blocks
265c9de560dSAlex Tomas  *    - discard locality group PA
266c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
267c9de560dSAlex Tomas  *
268c9de560dSAlex Tomas  * now we're ready to make few consequences:
269c9de560dSAlex Tomas  *  - PA is referenced and while it is no discard is possible
270c9de560dSAlex Tomas  *  - PA is referenced until block isn't marked in on-disk bitmap
271c9de560dSAlex Tomas  *  - PA changes only after on-disk bitmap
272c9de560dSAlex Tomas  *  - discard must not compete with init. either init is done before
273c9de560dSAlex Tomas  *    any discard or they're serialized somehow
274c9de560dSAlex Tomas  *  - buddy init as sum of on-disk bitmap and PAs is done atomically
275c9de560dSAlex Tomas  *
276c9de560dSAlex Tomas  * a special case when we've used PA to emptiness. no need to modify buddy
277c9de560dSAlex Tomas  * in this case, but we should care about concurrent init
278c9de560dSAlex Tomas  *
279c9de560dSAlex Tomas  */
280c9de560dSAlex Tomas 
281c9de560dSAlex Tomas  /*
282c9de560dSAlex Tomas  * Logic in few words:
283c9de560dSAlex Tomas  *
284c9de560dSAlex Tomas  *  - allocation:
285c9de560dSAlex Tomas  *    load group
286c9de560dSAlex Tomas  *    find blocks
287c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
288c9de560dSAlex Tomas  *    release group
289c9de560dSAlex Tomas  *
290c9de560dSAlex Tomas  *  - use preallocation:
291c9de560dSAlex Tomas  *    find proper PA (per-inode or group)
292c9de560dSAlex Tomas  *    load group
293c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
294c9de560dSAlex Tomas  *    release group
295c9de560dSAlex Tomas  *    release PA
296c9de560dSAlex Tomas  *
297c9de560dSAlex Tomas  *  - free:
298c9de560dSAlex Tomas  *    load group
299c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
300c9de560dSAlex Tomas  *    release group
301c9de560dSAlex Tomas  *
302c9de560dSAlex Tomas  *  - discard preallocations in group:
303c9de560dSAlex Tomas  *    mark PAs deleted
304c9de560dSAlex Tomas  *    move them onto local list
305c9de560dSAlex Tomas  *    load on-disk bitmap
306c9de560dSAlex Tomas  *    load group
307c9de560dSAlex Tomas  *    remove PA from object (inode or locality group)
308c9de560dSAlex Tomas  *    mark free blocks in-core
309c9de560dSAlex Tomas  *
310c9de560dSAlex Tomas  *  - discard inode's preallocations:
311c9de560dSAlex Tomas  */
312c9de560dSAlex Tomas 
313c9de560dSAlex Tomas /*
314c9de560dSAlex Tomas  * Locking rules
315c9de560dSAlex Tomas  *
316c9de560dSAlex Tomas  * Locks:
317c9de560dSAlex Tomas  *  - bitlock on a group	(group)
318c9de560dSAlex Tomas  *  - object (inode/locality)	(object)
319c9de560dSAlex Tomas  *  - per-pa lock		(pa)
320c9de560dSAlex Tomas  *
321c9de560dSAlex Tomas  * Paths:
322c9de560dSAlex Tomas  *  - new pa
323c9de560dSAlex Tomas  *    object
324c9de560dSAlex Tomas  *    group
325c9de560dSAlex Tomas  *
326c9de560dSAlex Tomas  *  - find and use pa:
327c9de560dSAlex Tomas  *    pa
328c9de560dSAlex Tomas  *
329c9de560dSAlex Tomas  *  - release consumed pa:
330c9de560dSAlex Tomas  *    pa
331c9de560dSAlex Tomas  *    group
332c9de560dSAlex Tomas  *    object
333c9de560dSAlex Tomas  *
334c9de560dSAlex Tomas  *  - generate in-core bitmap:
335c9de560dSAlex Tomas  *    group
336c9de560dSAlex Tomas  *        pa
337c9de560dSAlex Tomas  *
338c9de560dSAlex Tomas  *  - discard all for given object (inode, locality group):
339c9de560dSAlex Tomas  *    object
340c9de560dSAlex Tomas  *        pa
341c9de560dSAlex Tomas  *    group
342c9de560dSAlex Tomas  *
343c9de560dSAlex Tomas  *  - discard all for given group:
344c9de560dSAlex Tomas  *    group
345c9de560dSAlex Tomas  *        pa
346c9de560dSAlex Tomas  *    group
347c9de560dSAlex Tomas  *        object
348c9de560dSAlex Tomas  *
349c9de560dSAlex Tomas  */
350c3a326a6SAneesh Kumar K.V static struct kmem_cache *ext4_pspace_cachep;
351c3a326a6SAneesh Kumar K.V static struct kmem_cache *ext4_ac_cachep;
35218aadd47SBobi Jam static struct kmem_cache *ext4_free_data_cachep;
353fb1813f4SCurt Wohlgemuth 
354fb1813f4SCurt Wohlgemuth /* We create slab caches for groupinfo data structures based on the
355fb1813f4SCurt Wohlgemuth  * superblock block size.  There will be one per mounted filesystem for
356fb1813f4SCurt Wohlgemuth  * each unique s_blocksize_bits */
3572892c15dSEric Sandeen #define NR_GRPINFO_CACHES 8
358fb1813f4SCurt Wohlgemuth static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
359fb1813f4SCurt Wohlgemuth 
3602892c15dSEric Sandeen static const char *ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
3612892c15dSEric Sandeen 	"ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
3622892c15dSEric Sandeen 	"ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
3632892c15dSEric Sandeen 	"ext4_groupinfo_64k", "ext4_groupinfo_128k"
3642892c15dSEric Sandeen };
3652892c15dSEric Sandeen 
366c3a326a6SAneesh Kumar K.V static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
367c3a326a6SAneesh Kumar K.V 					ext4_group_t group);
3687a2fcbf7SAneesh Kumar K.V static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3697a2fcbf7SAneesh Kumar K.V 						ext4_group_t group);
37018aadd47SBobi Jam static void ext4_free_data_callback(struct super_block *sb,
37118aadd47SBobi Jam 				struct ext4_journal_cb_entry *jce, int rc);
372c3a326a6SAneesh Kumar K.V 
373ffad0a44SAneesh Kumar K.V static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
374ffad0a44SAneesh Kumar K.V {
375c9de560dSAlex Tomas #if BITS_PER_LONG == 64
376ffad0a44SAneesh Kumar K.V 	*bit += ((unsigned long) addr & 7UL) << 3;
377ffad0a44SAneesh Kumar K.V 	addr = (void *) ((unsigned long) addr & ~7UL);
378c9de560dSAlex Tomas #elif BITS_PER_LONG == 32
379ffad0a44SAneesh Kumar K.V 	*bit += ((unsigned long) addr & 3UL) << 3;
380ffad0a44SAneesh Kumar K.V 	addr = (void *) ((unsigned long) addr & ~3UL);
381c9de560dSAlex Tomas #else
382c9de560dSAlex Tomas #error "how many bits you are?!"
383c9de560dSAlex Tomas #endif
384ffad0a44SAneesh Kumar K.V 	return addr;
385ffad0a44SAneesh Kumar K.V }
386c9de560dSAlex Tomas 
387c9de560dSAlex Tomas static inline int mb_test_bit(int bit, void *addr)
388c9de560dSAlex Tomas {
389c9de560dSAlex Tomas 	/*
390c9de560dSAlex Tomas 	 * ext4_test_bit on architecture like powerpc
391c9de560dSAlex Tomas 	 * needs unsigned long aligned address
392c9de560dSAlex Tomas 	 */
393ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
394c9de560dSAlex Tomas 	return ext4_test_bit(bit, addr);
395c9de560dSAlex Tomas }
396c9de560dSAlex Tomas 
397c9de560dSAlex Tomas static inline void mb_set_bit(int bit, void *addr)
398c9de560dSAlex Tomas {
399ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
400c9de560dSAlex Tomas 	ext4_set_bit(bit, addr);
401c9de560dSAlex Tomas }
402c9de560dSAlex Tomas 
403c9de560dSAlex Tomas static inline void mb_clear_bit(int bit, void *addr)
404c9de560dSAlex Tomas {
405ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
406c9de560dSAlex Tomas 	ext4_clear_bit(bit, addr);
407c9de560dSAlex Tomas }
408c9de560dSAlex Tomas 
409eabe0444SAndrey Sidorov static inline int mb_test_and_clear_bit(int bit, void *addr)
410eabe0444SAndrey Sidorov {
411eabe0444SAndrey Sidorov 	addr = mb_correct_addr_and_bit(&bit, addr);
412eabe0444SAndrey Sidorov 	return ext4_test_and_clear_bit(bit, addr);
413eabe0444SAndrey Sidorov }
414eabe0444SAndrey Sidorov 
415ffad0a44SAneesh Kumar K.V static inline int mb_find_next_zero_bit(void *addr, int max, int start)
416ffad0a44SAneesh Kumar K.V {
417e7dfb246SAneesh Kumar K.V 	int fix = 0, ret, tmpmax;
418ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&fix, addr);
419e7dfb246SAneesh Kumar K.V 	tmpmax = max + fix;
420ffad0a44SAneesh Kumar K.V 	start += fix;
421ffad0a44SAneesh Kumar K.V 
422e7dfb246SAneesh Kumar K.V 	ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
423e7dfb246SAneesh Kumar K.V 	if (ret > max)
424e7dfb246SAneesh Kumar K.V 		return max;
425e7dfb246SAneesh Kumar K.V 	return ret;
426ffad0a44SAneesh Kumar K.V }
427ffad0a44SAneesh Kumar K.V 
428ffad0a44SAneesh Kumar K.V static inline int mb_find_next_bit(void *addr, int max, int start)
429ffad0a44SAneesh Kumar K.V {
430e7dfb246SAneesh Kumar K.V 	int fix = 0, ret, tmpmax;
431ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&fix, addr);
432e7dfb246SAneesh Kumar K.V 	tmpmax = max + fix;
433ffad0a44SAneesh Kumar K.V 	start += fix;
434ffad0a44SAneesh Kumar K.V 
435e7dfb246SAneesh Kumar K.V 	ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
436e7dfb246SAneesh Kumar K.V 	if (ret > max)
437e7dfb246SAneesh Kumar K.V 		return max;
438e7dfb246SAneesh Kumar K.V 	return ret;
439ffad0a44SAneesh Kumar K.V }
440ffad0a44SAneesh Kumar K.V 
441c9de560dSAlex Tomas static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
442c9de560dSAlex Tomas {
443c9de560dSAlex Tomas 	char *bb;
444c9de560dSAlex Tomas 
445c5e8f3f3STheodore Ts'o 	BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
446c9de560dSAlex Tomas 	BUG_ON(max == NULL);
447c9de560dSAlex Tomas 
448c9de560dSAlex Tomas 	if (order > e4b->bd_blkbits + 1) {
449c9de560dSAlex Tomas 		*max = 0;
450c9de560dSAlex Tomas 		return NULL;
451c9de560dSAlex Tomas 	}
452c9de560dSAlex Tomas 
453c9de560dSAlex Tomas 	/* at order 0 we see each particular block */
45484b775a3SColy Li 	if (order == 0) {
455c9de560dSAlex Tomas 		*max = 1 << (e4b->bd_blkbits + 3);
456c5e8f3f3STheodore Ts'o 		return e4b->bd_bitmap;
45784b775a3SColy Li 	}
458c9de560dSAlex Tomas 
459c5e8f3f3STheodore Ts'o 	bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
460c9de560dSAlex Tomas 	*max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
461c9de560dSAlex Tomas 
462c9de560dSAlex Tomas 	return bb;
463c9de560dSAlex Tomas }
464c9de560dSAlex Tomas 
465c9de560dSAlex Tomas #ifdef DOUBLE_CHECK
466c9de560dSAlex Tomas static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
467c9de560dSAlex Tomas 			   int first, int count)
468c9de560dSAlex Tomas {
469c9de560dSAlex Tomas 	int i;
470c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
471c9de560dSAlex Tomas 
472c9de560dSAlex Tomas 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
473c9de560dSAlex Tomas 		return;
474bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
475c9de560dSAlex Tomas 	for (i = 0; i < count; i++) {
476c9de560dSAlex Tomas 		if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
477c9de560dSAlex Tomas 			ext4_fsblk_t blocknr;
4785661bd68SAkinobu Mita 
4795661bd68SAkinobu Mita 			blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
48053accfa9STheodore Ts'o 			blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
4815d1b1b3fSAneesh Kumar K.V 			ext4_grp_locked_error(sb, e4b->bd_group,
482e29136f8STheodore Ts'o 					      inode ? inode->i_ino : 0,
483e29136f8STheodore Ts'o 					      blocknr,
484e29136f8STheodore Ts'o 					      "freeing block already freed "
485e29136f8STheodore Ts'o 					      "(bit %u)",
486e29136f8STheodore Ts'o 					      first + i);
487c9de560dSAlex Tomas 		}
488c9de560dSAlex Tomas 		mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
489c9de560dSAlex Tomas 	}
490c9de560dSAlex Tomas }
491c9de560dSAlex Tomas 
492c9de560dSAlex Tomas static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
493c9de560dSAlex Tomas {
494c9de560dSAlex Tomas 	int i;
495c9de560dSAlex Tomas 
496c9de560dSAlex Tomas 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
497c9de560dSAlex Tomas 		return;
498bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
499c9de560dSAlex Tomas 	for (i = 0; i < count; i++) {
500c9de560dSAlex Tomas 		BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
501c9de560dSAlex Tomas 		mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
502c9de560dSAlex Tomas 	}
503c9de560dSAlex Tomas }
504c9de560dSAlex Tomas 
505c9de560dSAlex Tomas static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
506c9de560dSAlex Tomas {
507c9de560dSAlex Tomas 	if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
508c9de560dSAlex Tomas 		unsigned char *b1, *b2;
509c9de560dSAlex Tomas 		int i;
510c9de560dSAlex Tomas 		b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
511c9de560dSAlex Tomas 		b2 = (unsigned char *) bitmap;
512c9de560dSAlex Tomas 		for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
513c9de560dSAlex Tomas 			if (b1[i] != b2[i]) {
5149d8b9ec4STheodore Ts'o 				ext4_msg(e4b->bd_sb, KERN_ERR,
5159d8b9ec4STheodore Ts'o 					 "corruption in group %u "
5164776004fSTheodore Ts'o 					 "at byte %u(%u): %x in copy != %x "
5179d8b9ec4STheodore Ts'o 					 "on disk/prealloc",
518c9de560dSAlex Tomas 					 e4b->bd_group, i, i * 8, b1[i], b2[i]);
519c9de560dSAlex Tomas 				BUG();
520c9de560dSAlex Tomas 			}
521c9de560dSAlex Tomas 		}
522c9de560dSAlex Tomas 	}
523c9de560dSAlex Tomas }
524c9de560dSAlex Tomas 
525c9de560dSAlex Tomas #else
526c9de560dSAlex Tomas static inline void mb_free_blocks_double(struct inode *inode,
527c9de560dSAlex Tomas 				struct ext4_buddy *e4b, int first, int count)
528c9de560dSAlex Tomas {
529c9de560dSAlex Tomas 	return;
530c9de560dSAlex Tomas }
531c9de560dSAlex Tomas static inline void mb_mark_used_double(struct ext4_buddy *e4b,
532c9de560dSAlex Tomas 						int first, int count)
533c9de560dSAlex Tomas {
534c9de560dSAlex Tomas 	return;
535c9de560dSAlex Tomas }
536c9de560dSAlex Tomas static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
537c9de560dSAlex Tomas {
538c9de560dSAlex Tomas 	return;
539c9de560dSAlex Tomas }
540c9de560dSAlex Tomas #endif
541c9de560dSAlex Tomas 
542c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
543c9de560dSAlex Tomas 
544c9de560dSAlex Tomas #define MB_CHECK_ASSERT(assert)						\
545c9de560dSAlex Tomas do {									\
546c9de560dSAlex Tomas 	if (!(assert)) {						\
547c9de560dSAlex Tomas 		printk(KERN_EMERG					\
548c9de560dSAlex Tomas 			"Assertion failure in %s() at %s:%d: \"%s\"\n",	\
549c9de560dSAlex Tomas 			function, file, line, # assert);		\
550c9de560dSAlex Tomas 		BUG();							\
551c9de560dSAlex Tomas 	}								\
552c9de560dSAlex Tomas } while (0)
553c9de560dSAlex Tomas 
554c9de560dSAlex Tomas static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
555c9de560dSAlex Tomas 				const char *function, int line)
556c9de560dSAlex Tomas {
557c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
558c9de560dSAlex Tomas 	int order = e4b->bd_blkbits + 1;
559c9de560dSAlex Tomas 	int max;
560c9de560dSAlex Tomas 	int max2;
561c9de560dSAlex Tomas 	int i;
562c9de560dSAlex Tomas 	int j;
563c9de560dSAlex Tomas 	int k;
564c9de560dSAlex Tomas 	int count;
565c9de560dSAlex Tomas 	struct ext4_group_info *grp;
566c9de560dSAlex Tomas 	int fragments = 0;
567c9de560dSAlex Tomas 	int fstart;
568c9de560dSAlex Tomas 	struct list_head *cur;
569c9de560dSAlex Tomas 	void *buddy;
570c9de560dSAlex Tomas 	void *buddy2;
571c9de560dSAlex Tomas 
572c9de560dSAlex Tomas 	{
573c9de560dSAlex Tomas 		static int mb_check_counter;
574c9de560dSAlex Tomas 		if (mb_check_counter++ % 100 != 0)
575c9de560dSAlex Tomas 			return 0;
576c9de560dSAlex Tomas 	}
577c9de560dSAlex Tomas 
578c9de560dSAlex Tomas 	while (order > 1) {
579c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, order, &max);
580c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy);
581c9de560dSAlex Tomas 		buddy2 = mb_find_buddy(e4b, order - 1, &max2);
582c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy2);
583c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy != buddy2);
584c9de560dSAlex Tomas 		MB_CHECK_ASSERT(max * 2 == max2);
585c9de560dSAlex Tomas 
586c9de560dSAlex Tomas 		count = 0;
587c9de560dSAlex Tomas 		for (i = 0; i < max; i++) {
588c9de560dSAlex Tomas 
589c9de560dSAlex Tomas 			if (mb_test_bit(i, buddy)) {
590c9de560dSAlex Tomas 				/* only single bit in buddy2 may be 1 */
591c9de560dSAlex Tomas 				if (!mb_test_bit(i << 1, buddy2)) {
592c9de560dSAlex Tomas 					MB_CHECK_ASSERT(
593c9de560dSAlex Tomas 						mb_test_bit((i<<1)+1, buddy2));
594c9de560dSAlex Tomas 				} else if (!mb_test_bit((i << 1) + 1, buddy2)) {
595c9de560dSAlex Tomas 					MB_CHECK_ASSERT(
596c9de560dSAlex Tomas 						mb_test_bit(i << 1, buddy2));
597c9de560dSAlex Tomas 				}
598c9de560dSAlex Tomas 				continue;
599c9de560dSAlex Tomas 			}
600c9de560dSAlex Tomas 
6010a10da73SRobin Dong 			/* both bits in buddy2 must be 1 */
602c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
603c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
604c9de560dSAlex Tomas 
605c9de560dSAlex Tomas 			for (j = 0; j < (1 << order); j++) {
606c9de560dSAlex Tomas 				k = (i * (1 << order)) + j;
607c9de560dSAlex Tomas 				MB_CHECK_ASSERT(
608c5e8f3f3STheodore Ts'o 					!mb_test_bit(k, e4b->bd_bitmap));
609c9de560dSAlex Tomas 			}
610c9de560dSAlex Tomas 			count++;
611c9de560dSAlex Tomas 		}
612c9de560dSAlex Tomas 		MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
613c9de560dSAlex Tomas 		order--;
614c9de560dSAlex Tomas 	}
615c9de560dSAlex Tomas 
616c9de560dSAlex Tomas 	fstart = -1;
617c9de560dSAlex Tomas 	buddy = mb_find_buddy(e4b, 0, &max);
618c9de560dSAlex Tomas 	for (i = 0; i < max; i++) {
619c9de560dSAlex Tomas 		if (!mb_test_bit(i, buddy)) {
620c9de560dSAlex Tomas 			MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
621c9de560dSAlex Tomas 			if (fstart == -1) {
622c9de560dSAlex Tomas 				fragments++;
623c9de560dSAlex Tomas 				fstart = i;
624c9de560dSAlex Tomas 			}
625c9de560dSAlex Tomas 			continue;
626c9de560dSAlex Tomas 		}
627c9de560dSAlex Tomas 		fstart = -1;
628c9de560dSAlex Tomas 		/* check used bits only */
629c9de560dSAlex Tomas 		for (j = 0; j < e4b->bd_blkbits + 1; j++) {
630c9de560dSAlex Tomas 			buddy2 = mb_find_buddy(e4b, j, &max2);
631c9de560dSAlex Tomas 			k = i >> j;
632c9de560dSAlex Tomas 			MB_CHECK_ASSERT(k < max2);
633c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
634c9de560dSAlex Tomas 		}
635c9de560dSAlex Tomas 	}
636c9de560dSAlex Tomas 	MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
637c9de560dSAlex Tomas 	MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
638c9de560dSAlex Tomas 
639c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, e4b->bd_group);
640c9de560dSAlex Tomas 	list_for_each(cur, &grp->bb_prealloc_list) {
641c9de560dSAlex Tomas 		ext4_group_t groupnr;
642c9de560dSAlex Tomas 		struct ext4_prealloc_space *pa;
64360bd63d1SSolofo Ramangalahy 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
64460bd63d1SSolofo Ramangalahy 		ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
645c9de560dSAlex Tomas 		MB_CHECK_ASSERT(groupnr == e4b->bd_group);
64660bd63d1SSolofo Ramangalahy 		for (i = 0; i < pa->pa_len; i++)
647c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
648c9de560dSAlex Tomas 	}
649c9de560dSAlex Tomas 	return 0;
650c9de560dSAlex Tomas }
651c9de560dSAlex Tomas #undef MB_CHECK_ASSERT
652c9de560dSAlex Tomas #define mb_check_buddy(e4b) __mb_check_buddy(e4b,	\
65346e665e9SHarvey Harrison 					__FILE__, __func__, __LINE__)
654c9de560dSAlex Tomas #else
655c9de560dSAlex Tomas #define mb_check_buddy(e4b)
656c9de560dSAlex Tomas #endif
657c9de560dSAlex Tomas 
6587c786059SColy Li /*
6597c786059SColy Li  * Divide blocks started from @first with length @len into
6607c786059SColy Li  * smaller chunks with power of 2 blocks.
6617c786059SColy Li  * Clear the bits in bitmap which the blocks of the chunk(s) covered,
6627c786059SColy Li  * then increase bb_counters[] for corresponded chunk size.
6637c786059SColy Li  */
664c9de560dSAlex Tomas static void ext4_mb_mark_free_simple(struct super_block *sb,
665a36b4498SEric Sandeen 				void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
666c9de560dSAlex Tomas 					struct ext4_group_info *grp)
667c9de560dSAlex Tomas {
668c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
669a36b4498SEric Sandeen 	ext4_grpblk_t min;
670a36b4498SEric Sandeen 	ext4_grpblk_t max;
671a36b4498SEric Sandeen 	ext4_grpblk_t chunk;
672c9de560dSAlex Tomas 	unsigned short border;
673c9de560dSAlex Tomas 
6747137d7a4STheodore Ts'o 	BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
675c9de560dSAlex Tomas 
676c9de560dSAlex Tomas 	border = 2 << sb->s_blocksize_bits;
677c9de560dSAlex Tomas 
678c9de560dSAlex Tomas 	while (len > 0) {
679c9de560dSAlex Tomas 		/* find how many blocks can be covered since this position */
680c9de560dSAlex Tomas 		max = ffs(first | border) - 1;
681c9de560dSAlex Tomas 
682c9de560dSAlex Tomas 		/* find how many blocks of power 2 we need to mark */
683c9de560dSAlex Tomas 		min = fls(len) - 1;
684c9de560dSAlex Tomas 
685c9de560dSAlex Tomas 		if (max < min)
686c9de560dSAlex Tomas 			min = max;
687c9de560dSAlex Tomas 		chunk = 1 << min;
688c9de560dSAlex Tomas 
689c9de560dSAlex Tomas 		/* mark multiblock chunks only */
690c9de560dSAlex Tomas 		grp->bb_counters[min]++;
691c9de560dSAlex Tomas 		if (min > 0)
692c9de560dSAlex Tomas 			mb_clear_bit(first >> min,
693c9de560dSAlex Tomas 				     buddy + sbi->s_mb_offsets[min]);
694c9de560dSAlex Tomas 
695c9de560dSAlex Tomas 		len -= chunk;
696c9de560dSAlex Tomas 		first += chunk;
697c9de560dSAlex Tomas 	}
698c9de560dSAlex Tomas }
699c9de560dSAlex Tomas 
7008a57d9d6SCurt Wohlgemuth /*
7018a57d9d6SCurt Wohlgemuth  * Cache the order of the largest free extent we have available in this block
7028a57d9d6SCurt Wohlgemuth  * group.
7038a57d9d6SCurt Wohlgemuth  */
7048a57d9d6SCurt Wohlgemuth static void
7058a57d9d6SCurt Wohlgemuth mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
7068a57d9d6SCurt Wohlgemuth {
7078a57d9d6SCurt Wohlgemuth 	int i;
7088a57d9d6SCurt Wohlgemuth 	int bits;
7098a57d9d6SCurt Wohlgemuth 
7108a57d9d6SCurt Wohlgemuth 	grp->bb_largest_free_order = -1; /* uninit */
7118a57d9d6SCurt Wohlgemuth 
7128a57d9d6SCurt Wohlgemuth 	bits = sb->s_blocksize_bits + 1;
7138a57d9d6SCurt Wohlgemuth 	for (i = bits; i >= 0; i--) {
7148a57d9d6SCurt Wohlgemuth 		if (grp->bb_counters[i] > 0) {
7158a57d9d6SCurt Wohlgemuth 			grp->bb_largest_free_order = i;
7168a57d9d6SCurt Wohlgemuth 			break;
7178a57d9d6SCurt Wohlgemuth 		}
7188a57d9d6SCurt Wohlgemuth 	}
7198a57d9d6SCurt Wohlgemuth }
7208a57d9d6SCurt Wohlgemuth 
721089ceeccSEric Sandeen static noinline_for_stack
722089ceeccSEric Sandeen void ext4_mb_generate_buddy(struct super_block *sb,
723c9de560dSAlex Tomas 				void *buddy, void *bitmap, ext4_group_t group)
724c9de560dSAlex Tomas {
725c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
726e43bb4e6SNamjae Jeon 	struct ext4_sb_info *sbi = EXT4_SB(sb);
7277137d7a4STheodore Ts'o 	ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
728a36b4498SEric Sandeen 	ext4_grpblk_t i = 0;
729a36b4498SEric Sandeen 	ext4_grpblk_t first;
730a36b4498SEric Sandeen 	ext4_grpblk_t len;
731c9de560dSAlex Tomas 	unsigned free = 0;
732c9de560dSAlex Tomas 	unsigned fragments = 0;
733c9de560dSAlex Tomas 	unsigned long long period = get_cycles();
734c9de560dSAlex Tomas 
735c9de560dSAlex Tomas 	/* initialize buddy from bitmap which is aggregation
736c9de560dSAlex Tomas 	 * of on-disk bitmap and preallocations */
737ffad0a44SAneesh Kumar K.V 	i = mb_find_next_zero_bit(bitmap, max, 0);
738c9de560dSAlex Tomas 	grp->bb_first_free = i;
739c9de560dSAlex Tomas 	while (i < max) {
740c9de560dSAlex Tomas 		fragments++;
741c9de560dSAlex Tomas 		first = i;
742ffad0a44SAneesh Kumar K.V 		i = mb_find_next_bit(bitmap, max, i);
743c9de560dSAlex Tomas 		len = i - first;
744c9de560dSAlex Tomas 		free += len;
745c9de560dSAlex Tomas 		if (len > 1)
746c9de560dSAlex Tomas 			ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
747c9de560dSAlex Tomas 		else
748c9de560dSAlex Tomas 			grp->bb_counters[0]++;
749c9de560dSAlex Tomas 		if (i < max)
750ffad0a44SAneesh Kumar K.V 			i = mb_find_next_zero_bit(bitmap, max, i);
751c9de560dSAlex Tomas 	}
752c9de560dSAlex Tomas 	grp->bb_fragments = fragments;
753c9de560dSAlex Tomas 
754c9de560dSAlex Tomas 	if (free != grp->bb_free) {
755e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0,
75694d4c066STheodore Ts'o 				      "block bitmap and bg descriptor "
75794d4c066STheodore Ts'o 				      "inconsistent: %u vs %u free clusters",
758e29136f8STheodore Ts'o 				      free, grp->bb_free);
759e56eb659SAneesh Kumar K.V 		/*
760163a203dSDarrick J. Wong 		 * If we intend to continue, we consider group descriptor
761e56eb659SAneesh Kumar K.V 		 * corrupt and update bb_free using bitmap value
762e56eb659SAneesh Kumar K.V 		 */
763c9de560dSAlex Tomas 		grp->bb_free = free;
764e43bb4e6SNamjae Jeon 		if (!EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
765e43bb4e6SNamjae Jeon 			percpu_counter_sub(&sbi->s_freeclusters_counter,
766e43bb4e6SNamjae Jeon 					   grp->bb_free);
767163a203dSDarrick J. Wong 		set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT, &grp->bb_state);
768c9de560dSAlex Tomas 	}
7698a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, grp);
770c9de560dSAlex Tomas 
771c9de560dSAlex Tomas 	clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
772c9de560dSAlex Tomas 
773c9de560dSAlex Tomas 	period = get_cycles() - period;
774c9de560dSAlex Tomas 	spin_lock(&EXT4_SB(sb)->s_bal_lock);
775c9de560dSAlex Tomas 	EXT4_SB(sb)->s_mb_buddies_generated++;
776c9de560dSAlex Tomas 	EXT4_SB(sb)->s_mb_generation_time += period;
777c9de560dSAlex Tomas 	spin_unlock(&EXT4_SB(sb)->s_bal_lock);
778c9de560dSAlex Tomas }
779c9de560dSAlex Tomas 
780eabe0444SAndrey Sidorov static void mb_regenerate_buddy(struct ext4_buddy *e4b)
781eabe0444SAndrey Sidorov {
782eabe0444SAndrey Sidorov 	int count;
783eabe0444SAndrey Sidorov 	int order = 1;
784eabe0444SAndrey Sidorov 	void *buddy;
785eabe0444SAndrey Sidorov 
786eabe0444SAndrey Sidorov 	while ((buddy = mb_find_buddy(e4b, order++, &count))) {
787eabe0444SAndrey Sidorov 		ext4_set_bits(buddy, 0, count);
788eabe0444SAndrey Sidorov 	}
789eabe0444SAndrey Sidorov 	e4b->bd_info->bb_fragments = 0;
790eabe0444SAndrey Sidorov 	memset(e4b->bd_info->bb_counters, 0,
791eabe0444SAndrey Sidorov 		sizeof(*e4b->bd_info->bb_counters) *
792eabe0444SAndrey Sidorov 		(e4b->bd_sb->s_blocksize_bits + 2));
793eabe0444SAndrey Sidorov 
794eabe0444SAndrey Sidorov 	ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
795eabe0444SAndrey Sidorov 		e4b->bd_bitmap, e4b->bd_group);
796eabe0444SAndrey Sidorov }
797eabe0444SAndrey Sidorov 
798c9de560dSAlex Tomas /* The buddy information is attached the buddy cache inode
799c9de560dSAlex Tomas  * for convenience. The information regarding each group
800c9de560dSAlex Tomas  * is loaded via ext4_mb_load_buddy. The information involve
801c9de560dSAlex Tomas  * block bitmap and buddy information. The information are
802c9de560dSAlex Tomas  * stored in the inode as
803c9de560dSAlex Tomas  *
804c9de560dSAlex Tomas  * {                        page                        }
805c3a326a6SAneesh Kumar K.V  * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
806c9de560dSAlex Tomas  *
807c9de560dSAlex Tomas  *
808c9de560dSAlex Tomas  * one block each for bitmap and buddy information.
809c9de560dSAlex Tomas  * So for each group we take up 2 blocks. A page can
810c9de560dSAlex Tomas  * contain blocks_per_page (PAGE_CACHE_SIZE / blocksize)  blocks.
811c9de560dSAlex Tomas  * So it can have information regarding groups_per_page which
812c9de560dSAlex Tomas  * is blocks_per_page/2
8138a57d9d6SCurt Wohlgemuth  *
8148a57d9d6SCurt Wohlgemuth  * Locking note:  This routine takes the block group lock of all groups
8158a57d9d6SCurt Wohlgemuth  * for this page; do not hold this lock when calling this routine!
816c9de560dSAlex Tomas  */
817c9de560dSAlex Tomas 
818c9de560dSAlex Tomas static int ext4_mb_init_cache(struct page *page, char *incore)
819c9de560dSAlex Tomas {
8208df9675fSTheodore Ts'o 	ext4_group_t ngroups;
821c9de560dSAlex Tomas 	int blocksize;
822c9de560dSAlex Tomas 	int blocks_per_page;
823c9de560dSAlex Tomas 	int groups_per_page;
824c9de560dSAlex Tomas 	int err = 0;
825c9de560dSAlex Tomas 	int i;
826813e5727STheodore Ts'o 	ext4_group_t first_group, group;
827c9de560dSAlex Tomas 	int first_block;
828c9de560dSAlex Tomas 	struct super_block *sb;
829c9de560dSAlex Tomas 	struct buffer_head *bhs;
830fa77dcfaSDarrick J. Wong 	struct buffer_head **bh = NULL;
831c9de560dSAlex Tomas 	struct inode *inode;
832c9de560dSAlex Tomas 	char *data;
833c9de560dSAlex Tomas 	char *bitmap;
8349b8b7d35SAmir Goldstein 	struct ext4_group_info *grinfo;
835c9de560dSAlex Tomas 
8366ba495e9STheodore Ts'o 	mb_debug(1, "init page %lu\n", page->index);
837c9de560dSAlex Tomas 
838c9de560dSAlex Tomas 	inode = page->mapping->host;
839c9de560dSAlex Tomas 	sb = inode->i_sb;
8408df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
841c9de560dSAlex Tomas 	blocksize = 1 << inode->i_blkbits;
842c9de560dSAlex Tomas 	blocks_per_page = PAGE_CACHE_SIZE / blocksize;
843c9de560dSAlex Tomas 
844c9de560dSAlex Tomas 	groups_per_page = blocks_per_page >> 1;
845c9de560dSAlex Tomas 	if (groups_per_page == 0)
846c9de560dSAlex Tomas 		groups_per_page = 1;
847c9de560dSAlex Tomas 
848c9de560dSAlex Tomas 	/* allocate buffer_heads to read bitmaps */
849c9de560dSAlex Tomas 	if (groups_per_page > 1) {
850c9de560dSAlex Tomas 		i = sizeof(struct buffer_head *) * groups_per_page;
851c9de560dSAlex Tomas 		bh = kzalloc(i, GFP_NOFS);
852813e5727STheodore Ts'o 		if (bh == NULL) {
853813e5727STheodore Ts'o 			err = -ENOMEM;
854c9de560dSAlex Tomas 			goto out;
855813e5727STheodore Ts'o 		}
856c9de560dSAlex Tomas 	} else
857c9de560dSAlex Tomas 		bh = &bhs;
858c9de560dSAlex Tomas 
859c9de560dSAlex Tomas 	first_group = page->index * blocks_per_page / 2;
860c9de560dSAlex Tomas 
861c9de560dSAlex Tomas 	/* read all groups the page covers into the cache */
862813e5727STheodore Ts'o 	for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
863813e5727STheodore Ts'o 		if (group >= ngroups)
864c9de560dSAlex Tomas 			break;
865c9de560dSAlex Tomas 
866813e5727STheodore Ts'o 		grinfo = ext4_get_group_info(sb, group);
8679b8b7d35SAmir Goldstein 		/*
8689b8b7d35SAmir Goldstein 		 * If page is uptodate then we came here after online resize
8699b8b7d35SAmir Goldstein 		 * which added some new uninitialized group info structs, so
8709b8b7d35SAmir Goldstein 		 * we must skip all initialized uptodate buddies on the page,
8719b8b7d35SAmir Goldstein 		 * which may be currently in use by an allocating task.
8729b8b7d35SAmir Goldstein 		 */
8739b8b7d35SAmir Goldstein 		if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
8749b8b7d35SAmir Goldstein 			bh[i] = NULL;
8759b8b7d35SAmir Goldstein 			continue;
8769b8b7d35SAmir Goldstein 		}
8779008a58eSDarrick J. Wong 		bh[i] = ext4_read_block_bitmap_nowait(sb, group);
8789008a58eSDarrick J. Wong 		if (IS_ERR(bh[i])) {
8799008a58eSDarrick J. Wong 			err = PTR_ERR(bh[i]);
8809008a58eSDarrick J. Wong 			bh[i] = NULL;
881c9de560dSAlex Tomas 			goto out;
8822ccb5fb9SAneesh Kumar K.V 		}
883813e5727STheodore Ts'o 		mb_debug(1, "read bitmap for group %u\n", group);
884c9de560dSAlex Tomas 	}
885c9de560dSAlex Tomas 
886c9de560dSAlex Tomas 	/* wait for I/O completion */
887813e5727STheodore Ts'o 	for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
8889008a58eSDarrick J. Wong 		int err2;
8899008a58eSDarrick J. Wong 
8909008a58eSDarrick J. Wong 		if (!bh[i])
8919008a58eSDarrick J. Wong 			continue;
8929008a58eSDarrick J. Wong 		err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
8939008a58eSDarrick J. Wong 		if (!err)
8949008a58eSDarrick J. Wong 			err = err2;
895813e5727STheodore Ts'o 	}
896c9de560dSAlex Tomas 
897c9de560dSAlex Tomas 	first_block = page->index * blocks_per_page;
898c9de560dSAlex Tomas 	for (i = 0; i < blocks_per_page; i++) {
899c9de560dSAlex Tomas 		group = (first_block + i) >> 1;
9008df9675fSTheodore Ts'o 		if (group >= ngroups)
901c9de560dSAlex Tomas 			break;
902c9de560dSAlex Tomas 
9039b8b7d35SAmir Goldstein 		if (!bh[group - first_group])
9049b8b7d35SAmir Goldstein 			/* skip initialized uptodate buddy */
9059b8b7d35SAmir Goldstein 			continue;
9069b8b7d35SAmir Goldstein 
907bbdc322fSLukas Czerner 		if (!buffer_verified(bh[group - first_group]))
908bbdc322fSLukas Czerner 			/* Skip faulty bitmaps */
909bbdc322fSLukas Czerner 			continue;
910bbdc322fSLukas Czerner 		err = 0;
911bbdc322fSLukas Czerner 
912c9de560dSAlex Tomas 		/*
913c9de560dSAlex Tomas 		 * data carry information regarding this
914c9de560dSAlex Tomas 		 * particular group in the format specified
915c9de560dSAlex Tomas 		 * above
916c9de560dSAlex Tomas 		 *
917c9de560dSAlex Tomas 		 */
918c9de560dSAlex Tomas 		data = page_address(page) + (i * blocksize);
919c9de560dSAlex Tomas 		bitmap = bh[group - first_group]->b_data;
920c9de560dSAlex Tomas 
921c9de560dSAlex Tomas 		/*
922c9de560dSAlex Tomas 		 * We place the buddy block and bitmap block
923c9de560dSAlex Tomas 		 * close together
924c9de560dSAlex Tomas 		 */
925c9de560dSAlex Tomas 		if ((first_block + i) & 1) {
926c9de560dSAlex Tomas 			/* this is block of buddy */
927c9de560dSAlex Tomas 			BUG_ON(incore == NULL);
9286ba495e9STheodore Ts'o 			mb_debug(1, "put buddy for group %u in page %lu/%x\n",
929c9de560dSAlex Tomas 				group, page->index, i * blocksize);
930f307333eSTheodore Ts'o 			trace_ext4_mb_buddy_bitmap_load(sb, group);
931c9de560dSAlex Tomas 			grinfo = ext4_get_group_info(sb, group);
932c9de560dSAlex Tomas 			grinfo->bb_fragments = 0;
933c9de560dSAlex Tomas 			memset(grinfo->bb_counters, 0,
9341927805eSEric Sandeen 			       sizeof(*grinfo->bb_counters) *
9351927805eSEric Sandeen 				(sb->s_blocksize_bits+2));
936c9de560dSAlex Tomas 			/*
937c9de560dSAlex Tomas 			 * incore got set to the group block bitmap below
938c9de560dSAlex Tomas 			 */
9397a2fcbf7SAneesh Kumar K.V 			ext4_lock_group(sb, group);
9409b8b7d35SAmir Goldstein 			/* init the buddy */
9419b8b7d35SAmir Goldstein 			memset(data, 0xff, blocksize);
942c9de560dSAlex Tomas 			ext4_mb_generate_buddy(sb, data, incore, group);
9437a2fcbf7SAneesh Kumar K.V 			ext4_unlock_group(sb, group);
944c9de560dSAlex Tomas 			incore = NULL;
945c9de560dSAlex Tomas 		} else {
946c9de560dSAlex Tomas 			/* this is block of bitmap */
947c9de560dSAlex Tomas 			BUG_ON(incore != NULL);
9486ba495e9STheodore Ts'o 			mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
949c9de560dSAlex Tomas 				group, page->index, i * blocksize);
950f307333eSTheodore Ts'o 			trace_ext4_mb_bitmap_load(sb, group);
951c9de560dSAlex Tomas 
952c9de560dSAlex Tomas 			/* see comments in ext4_mb_put_pa() */
953c9de560dSAlex Tomas 			ext4_lock_group(sb, group);
954c9de560dSAlex Tomas 			memcpy(data, bitmap, blocksize);
955c9de560dSAlex Tomas 
956c9de560dSAlex Tomas 			/* mark all preallocated blks used in in-core bitmap */
957c9de560dSAlex Tomas 			ext4_mb_generate_from_pa(sb, data, group);
9587a2fcbf7SAneesh Kumar K.V 			ext4_mb_generate_from_freelist(sb, data, group);
959c9de560dSAlex Tomas 			ext4_unlock_group(sb, group);
960c9de560dSAlex Tomas 
961c9de560dSAlex Tomas 			/* set incore so that the buddy information can be
962c9de560dSAlex Tomas 			 * generated using this
963c9de560dSAlex Tomas 			 */
964c9de560dSAlex Tomas 			incore = data;
965c9de560dSAlex Tomas 		}
966c9de560dSAlex Tomas 	}
967c9de560dSAlex Tomas 	SetPageUptodate(page);
968c9de560dSAlex Tomas 
969c9de560dSAlex Tomas out:
970c9de560dSAlex Tomas 	if (bh) {
9719b8b7d35SAmir Goldstein 		for (i = 0; i < groups_per_page; i++)
972c9de560dSAlex Tomas 			brelse(bh[i]);
973c9de560dSAlex Tomas 		if (bh != &bhs)
974c9de560dSAlex Tomas 			kfree(bh);
975c9de560dSAlex Tomas 	}
976c9de560dSAlex Tomas 	return err;
977c9de560dSAlex Tomas }
978c9de560dSAlex Tomas 
9798a57d9d6SCurt Wohlgemuth /*
9802de8807bSAmir Goldstein  * Lock the buddy and bitmap pages. This make sure other parallel init_group
9812de8807bSAmir Goldstein  * on the same buddy page doesn't happen whild holding the buddy page lock.
9822de8807bSAmir Goldstein  * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
9832de8807bSAmir Goldstein  * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
984eee4adc7SEric Sandeen  */
9852de8807bSAmir Goldstein static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
9862de8807bSAmir Goldstein 		ext4_group_t group, struct ext4_buddy *e4b)
987eee4adc7SEric Sandeen {
9882de8807bSAmir Goldstein 	struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
9892de8807bSAmir Goldstein 	int block, pnum, poff;
990eee4adc7SEric Sandeen 	int blocks_per_page;
9912de8807bSAmir Goldstein 	struct page *page;
9922de8807bSAmir Goldstein 
9932de8807bSAmir Goldstein 	e4b->bd_buddy_page = NULL;
9942de8807bSAmir Goldstein 	e4b->bd_bitmap_page = NULL;
995eee4adc7SEric Sandeen 
996eee4adc7SEric Sandeen 	blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
997eee4adc7SEric Sandeen 	/*
998eee4adc7SEric Sandeen 	 * the buddy cache inode stores the block bitmap
999eee4adc7SEric Sandeen 	 * and buddy information in consecutive blocks.
1000eee4adc7SEric Sandeen 	 * So for each group we need two blocks.
1001eee4adc7SEric Sandeen 	 */
1002eee4adc7SEric Sandeen 	block = group * 2;
1003eee4adc7SEric Sandeen 	pnum = block / blocks_per_page;
10042de8807bSAmir Goldstein 	poff = block % blocks_per_page;
10052de8807bSAmir Goldstein 	page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
10062de8807bSAmir Goldstein 	if (!page)
1007c57ab39bSYounger Liu 		return -ENOMEM;
10082de8807bSAmir Goldstein 	BUG_ON(page->mapping != inode->i_mapping);
10092de8807bSAmir Goldstein 	e4b->bd_bitmap_page = page;
10102de8807bSAmir Goldstein 	e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1011eee4adc7SEric Sandeen 
10122de8807bSAmir Goldstein 	if (blocks_per_page >= 2) {
10132de8807bSAmir Goldstein 		/* buddy and bitmap are on the same page */
10142de8807bSAmir Goldstein 		return 0;
1015eee4adc7SEric Sandeen 	}
1016eee4adc7SEric Sandeen 
10172de8807bSAmir Goldstein 	block++;
1018eee4adc7SEric Sandeen 	pnum = block / blocks_per_page;
10192de8807bSAmir Goldstein 	page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
10202de8807bSAmir Goldstein 	if (!page)
1021c57ab39bSYounger Liu 		return -ENOMEM;
10222de8807bSAmir Goldstein 	BUG_ON(page->mapping != inode->i_mapping);
10232de8807bSAmir Goldstein 	e4b->bd_buddy_page = page;
10242de8807bSAmir Goldstein 	return 0;
1025eee4adc7SEric Sandeen }
1026eee4adc7SEric Sandeen 
10272de8807bSAmir Goldstein static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
10282de8807bSAmir Goldstein {
10292de8807bSAmir Goldstein 	if (e4b->bd_bitmap_page) {
10302de8807bSAmir Goldstein 		unlock_page(e4b->bd_bitmap_page);
10312de8807bSAmir Goldstein 		page_cache_release(e4b->bd_bitmap_page);
10322de8807bSAmir Goldstein 	}
10332de8807bSAmir Goldstein 	if (e4b->bd_buddy_page) {
10342de8807bSAmir Goldstein 		unlock_page(e4b->bd_buddy_page);
10352de8807bSAmir Goldstein 		page_cache_release(e4b->bd_buddy_page);
10362de8807bSAmir Goldstein 	}
1037eee4adc7SEric Sandeen }
1038eee4adc7SEric Sandeen 
1039eee4adc7SEric Sandeen /*
10408a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
10418a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
10428a57d9d6SCurt Wohlgemuth  * calling this routine!
10438a57d9d6SCurt Wohlgemuth  */
1044b6a758ecSAneesh Kumar K.V static noinline_for_stack
1045b6a758ecSAneesh Kumar K.V int ext4_mb_init_group(struct super_block *sb, ext4_group_t group)
1046b6a758ecSAneesh Kumar K.V {
1047b6a758ecSAneesh Kumar K.V 
1048b6a758ecSAneesh Kumar K.V 	struct ext4_group_info *this_grp;
10492de8807bSAmir Goldstein 	struct ext4_buddy e4b;
10502de8807bSAmir Goldstein 	struct page *page;
10512de8807bSAmir Goldstein 	int ret = 0;
1052b6a758ecSAneesh Kumar K.V 
1053b10a44c3STheodore Ts'o 	might_sleep();
1054b6a758ecSAneesh Kumar K.V 	mb_debug(1, "init group %u\n", group);
1055b6a758ecSAneesh Kumar K.V 	this_grp = ext4_get_group_info(sb, group);
1056b6a758ecSAneesh Kumar K.V 	/*
105708c3a813SAneesh Kumar K.V 	 * This ensures that we don't reinit the buddy cache
105808c3a813SAneesh Kumar K.V 	 * page which map to the group from which we are already
105908c3a813SAneesh Kumar K.V 	 * allocating. If we are looking at the buddy cache we would
106008c3a813SAneesh Kumar K.V 	 * have taken a reference using ext4_mb_load_buddy and that
10612de8807bSAmir Goldstein 	 * would have pinned buddy page to page cache.
10622457aec6SMel Gorman 	 * The call to ext4_mb_get_buddy_page_lock will mark the
10632457aec6SMel Gorman 	 * page accessed.
1064b6a758ecSAneesh Kumar K.V 	 */
10652de8807bSAmir Goldstein 	ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b);
10662de8807bSAmir Goldstein 	if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1067b6a758ecSAneesh Kumar K.V 		/*
1068b6a758ecSAneesh Kumar K.V 		 * somebody initialized the group
1069b6a758ecSAneesh Kumar K.V 		 * return without doing anything
1070b6a758ecSAneesh Kumar K.V 		 */
1071b6a758ecSAneesh Kumar K.V 		goto err;
1072b6a758ecSAneesh Kumar K.V 	}
10732de8807bSAmir Goldstein 
10742de8807bSAmir Goldstein 	page = e4b.bd_bitmap_page;
1075b6a758ecSAneesh Kumar K.V 	ret = ext4_mb_init_cache(page, NULL);
10762de8807bSAmir Goldstein 	if (ret)
1077b6a758ecSAneesh Kumar K.V 		goto err;
10782de8807bSAmir Goldstein 	if (!PageUptodate(page)) {
1079b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1080b6a758ecSAneesh Kumar K.V 		goto err;
1081b6a758ecSAneesh Kumar K.V 	}
1082b6a758ecSAneesh Kumar K.V 
10832de8807bSAmir Goldstein 	if (e4b.bd_buddy_page == NULL) {
1084b6a758ecSAneesh Kumar K.V 		/*
1085b6a758ecSAneesh Kumar K.V 		 * If both the bitmap and buddy are in
1086b6a758ecSAneesh Kumar K.V 		 * the same page we don't need to force
1087b6a758ecSAneesh Kumar K.V 		 * init the buddy
1088b6a758ecSAneesh Kumar K.V 		 */
10892de8807bSAmir Goldstein 		ret = 0;
1090b6a758ecSAneesh Kumar K.V 		goto err;
1091b6a758ecSAneesh Kumar K.V 	}
10922de8807bSAmir Goldstein 	/* init buddy cache */
10932de8807bSAmir Goldstein 	page = e4b.bd_buddy_page;
10942de8807bSAmir Goldstein 	ret = ext4_mb_init_cache(page, e4b.bd_bitmap);
10952de8807bSAmir Goldstein 	if (ret)
10962de8807bSAmir Goldstein 		goto err;
10972de8807bSAmir Goldstein 	if (!PageUptodate(page)) {
1098b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1099b6a758ecSAneesh Kumar K.V 		goto err;
1100b6a758ecSAneesh Kumar K.V 	}
1101b6a758ecSAneesh Kumar K.V err:
11022de8807bSAmir Goldstein 	ext4_mb_put_buddy_page_lock(&e4b);
1103b6a758ecSAneesh Kumar K.V 	return ret;
1104b6a758ecSAneesh Kumar K.V }
1105b6a758ecSAneesh Kumar K.V 
11068a57d9d6SCurt Wohlgemuth /*
11078a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
11088a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
11098a57d9d6SCurt Wohlgemuth  * calling this routine!
11108a57d9d6SCurt Wohlgemuth  */
11114ddfef7bSEric Sandeen static noinline_for_stack int
11124ddfef7bSEric Sandeen ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1113c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1114c9de560dSAlex Tomas {
1115c9de560dSAlex Tomas 	int blocks_per_page;
1116c9de560dSAlex Tomas 	int block;
1117c9de560dSAlex Tomas 	int pnum;
1118c9de560dSAlex Tomas 	int poff;
1119c9de560dSAlex Tomas 	struct page *page;
1120fdf6c7a7SShen Feng 	int ret;
1121920313a7SAneesh Kumar K.V 	struct ext4_group_info *grp;
1122920313a7SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1123920313a7SAneesh Kumar K.V 	struct inode *inode = sbi->s_buddy_cache;
1124c9de560dSAlex Tomas 
1125b10a44c3STheodore Ts'o 	might_sleep();
11266ba495e9STheodore Ts'o 	mb_debug(1, "load group %u\n", group);
1127c9de560dSAlex Tomas 
1128c9de560dSAlex Tomas 	blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1129920313a7SAneesh Kumar K.V 	grp = ext4_get_group_info(sb, group);
1130c9de560dSAlex Tomas 
1131c9de560dSAlex Tomas 	e4b->bd_blkbits = sb->s_blocksize_bits;
1132529da704STao Ma 	e4b->bd_info = grp;
1133c9de560dSAlex Tomas 	e4b->bd_sb = sb;
1134c9de560dSAlex Tomas 	e4b->bd_group = group;
1135c9de560dSAlex Tomas 	e4b->bd_buddy_page = NULL;
1136c9de560dSAlex Tomas 	e4b->bd_bitmap_page = NULL;
1137c9de560dSAlex Tomas 
1138f41c0750SAneesh Kumar K.V 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1139f41c0750SAneesh Kumar K.V 		/*
1140f41c0750SAneesh Kumar K.V 		 * we need full data about the group
1141f41c0750SAneesh Kumar K.V 		 * to make a good selection
1142f41c0750SAneesh Kumar K.V 		 */
1143f41c0750SAneesh Kumar K.V 		ret = ext4_mb_init_group(sb, group);
1144f41c0750SAneesh Kumar K.V 		if (ret)
1145f41c0750SAneesh Kumar K.V 			return ret;
1146f41c0750SAneesh Kumar K.V 	}
1147f41c0750SAneesh Kumar K.V 
1148c9de560dSAlex Tomas 	/*
1149c9de560dSAlex Tomas 	 * the buddy cache inode stores the block bitmap
1150c9de560dSAlex Tomas 	 * and buddy information in consecutive blocks.
1151c9de560dSAlex Tomas 	 * So for each group we need two blocks.
1152c9de560dSAlex Tomas 	 */
1153c9de560dSAlex Tomas 	block = group * 2;
1154c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1155c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1156c9de560dSAlex Tomas 
1157c9de560dSAlex Tomas 	/* we could use find_or_create_page(), but it locks page
1158c9de560dSAlex Tomas 	 * what we'd like to avoid in fast path ... */
11592457aec6SMel Gorman 	page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1160c9de560dSAlex Tomas 	if (page == NULL || !PageUptodate(page)) {
1161c9de560dSAlex Tomas 		if (page)
1162920313a7SAneesh Kumar K.V 			/*
1163920313a7SAneesh Kumar K.V 			 * drop the page reference and try
1164920313a7SAneesh Kumar K.V 			 * to get the page with lock. If we
1165920313a7SAneesh Kumar K.V 			 * are not uptodate that implies
1166920313a7SAneesh Kumar K.V 			 * somebody just created the page but
1167920313a7SAneesh Kumar K.V 			 * is yet to initialize the same. So
1168920313a7SAneesh Kumar K.V 			 * wait for it to initialize.
1169920313a7SAneesh Kumar K.V 			 */
1170c9de560dSAlex Tomas 			page_cache_release(page);
1171c9de560dSAlex Tomas 		page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1172c9de560dSAlex Tomas 		if (page) {
1173c9de560dSAlex Tomas 			BUG_ON(page->mapping != inode->i_mapping);
1174c9de560dSAlex Tomas 			if (!PageUptodate(page)) {
1175fdf6c7a7SShen Feng 				ret = ext4_mb_init_cache(page, NULL);
1176fdf6c7a7SShen Feng 				if (ret) {
1177fdf6c7a7SShen Feng 					unlock_page(page);
1178fdf6c7a7SShen Feng 					goto err;
1179fdf6c7a7SShen Feng 				}
1180c9de560dSAlex Tomas 				mb_cmp_bitmaps(e4b, page_address(page) +
1181c9de560dSAlex Tomas 					       (poff * sb->s_blocksize));
1182c9de560dSAlex Tomas 			}
1183c9de560dSAlex Tomas 			unlock_page(page);
1184c9de560dSAlex Tomas 		}
1185c9de560dSAlex Tomas 	}
1186c57ab39bSYounger Liu 	if (page == NULL) {
1187c57ab39bSYounger Liu 		ret = -ENOMEM;
1188c57ab39bSYounger Liu 		goto err;
1189c57ab39bSYounger Liu 	}
1190c57ab39bSYounger Liu 	if (!PageUptodate(page)) {
1191fdf6c7a7SShen Feng 		ret = -EIO;
1192c9de560dSAlex Tomas 		goto err;
1193fdf6c7a7SShen Feng 	}
11942457aec6SMel Gorman 
11952457aec6SMel Gorman 	/* Pages marked accessed already */
1196c9de560dSAlex Tomas 	e4b->bd_bitmap_page = page;
1197c9de560dSAlex Tomas 	e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1198c9de560dSAlex Tomas 
1199c9de560dSAlex Tomas 	block++;
1200c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1201c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1202c9de560dSAlex Tomas 
12032457aec6SMel Gorman 	page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1204c9de560dSAlex Tomas 	if (page == NULL || !PageUptodate(page)) {
1205c9de560dSAlex Tomas 		if (page)
1206c9de560dSAlex Tomas 			page_cache_release(page);
1207c9de560dSAlex Tomas 		page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1208c9de560dSAlex Tomas 		if (page) {
1209c9de560dSAlex Tomas 			BUG_ON(page->mapping != inode->i_mapping);
1210fdf6c7a7SShen Feng 			if (!PageUptodate(page)) {
1211fdf6c7a7SShen Feng 				ret = ext4_mb_init_cache(page, e4b->bd_bitmap);
1212fdf6c7a7SShen Feng 				if (ret) {
1213fdf6c7a7SShen Feng 					unlock_page(page);
1214fdf6c7a7SShen Feng 					goto err;
1215fdf6c7a7SShen Feng 				}
1216fdf6c7a7SShen Feng 			}
1217c9de560dSAlex Tomas 			unlock_page(page);
1218c9de560dSAlex Tomas 		}
1219c9de560dSAlex Tomas 	}
1220c57ab39bSYounger Liu 	if (page == NULL) {
1221c57ab39bSYounger Liu 		ret = -ENOMEM;
1222c57ab39bSYounger Liu 		goto err;
1223c57ab39bSYounger Liu 	}
1224c57ab39bSYounger Liu 	if (!PageUptodate(page)) {
1225fdf6c7a7SShen Feng 		ret = -EIO;
1226c9de560dSAlex Tomas 		goto err;
1227fdf6c7a7SShen Feng 	}
12282457aec6SMel Gorman 
12292457aec6SMel Gorman 	/* Pages marked accessed already */
1230c9de560dSAlex Tomas 	e4b->bd_buddy_page = page;
1231c9de560dSAlex Tomas 	e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1232c9de560dSAlex Tomas 
1233c9de560dSAlex Tomas 	BUG_ON(e4b->bd_bitmap_page == NULL);
1234c9de560dSAlex Tomas 	BUG_ON(e4b->bd_buddy_page == NULL);
1235c9de560dSAlex Tomas 
1236c9de560dSAlex Tomas 	return 0;
1237c9de560dSAlex Tomas 
1238c9de560dSAlex Tomas err:
123926626f11SYang Ruirui 	if (page)
124026626f11SYang Ruirui 		page_cache_release(page);
1241c9de560dSAlex Tomas 	if (e4b->bd_bitmap_page)
1242c9de560dSAlex Tomas 		page_cache_release(e4b->bd_bitmap_page);
1243c9de560dSAlex Tomas 	if (e4b->bd_buddy_page)
1244c9de560dSAlex Tomas 		page_cache_release(e4b->bd_buddy_page);
1245c9de560dSAlex Tomas 	e4b->bd_buddy = NULL;
1246c9de560dSAlex Tomas 	e4b->bd_bitmap = NULL;
1247fdf6c7a7SShen Feng 	return ret;
1248c9de560dSAlex Tomas }
1249c9de560dSAlex Tomas 
1250e39e07fdSJing Zhang static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1251c9de560dSAlex Tomas {
1252c9de560dSAlex Tomas 	if (e4b->bd_bitmap_page)
1253c9de560dSAlex Tomas 		page_cache_release(e4b->bd_bitmap_page);
1254c9de560dSAlex Tomas 	if (e4b->bd_buddy_page)
1255c9de560dSAlex Tomas 		page_cache_release(e4b->bd_buddy_page);
1256c9de560dSAlex Tomas }
1257c9de560dSAlex Tomas 
1258c9de560dSAlex Tomas 
1259c9de560dSAlex Tomas static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1260c9de560dSAlex Tomas {
1261c9de560dSAlex Tomas 	int order = 1;
1262c9de560dSAlex Tomas 	void *bb;
1263c9de560dSAlex Tomas 
1264c5e8f3f3STheodore Ts'o 	BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1265c9de560dSAlex Tomas 	BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1266c9de560dSAlex Tomas 
1267c5e8f3f3STheodore Ts'o 	bb = e4b->bd_buddy;
1268c9de560dSAlex Tomas 	while (order <= e4b->bd_blkbits + 1) {
1269c9de560dSAlex Tomas 		block = block >> 1;
1270c9de560dSAlex Tomas 		if (!mb_test_bit(block, bb)) {
1271c9de560dSAlex Tomas 			/* this block is part of buddy of order 'order' */
1272c9de560dSAlex Tomas 			return order;
1273c9de560dSAlex Tomas 		}
1274c9de560dSAlex Tomas 		bb += 1 << (e4b->bd_blkbits - order);
1275c9de560dSAlex Tomas 		order++;
1276c9de560dSAlex Tomas 	}
1277c9de560dSAlex Tomas 	return 0;
1278c9de560dSAlex Tomas }
1279c9de560dSAlex Tomas 
1280955ce5f5SAneesh Kumar K.V static void mb_clear_bits(void *bm, int cur, int len)
1281c9de560dSAlex Tomas {
1282c9de560dSAlex Tomas 	__u32 *addr;
1283c9de560dSAlex Tomas 
1284c9de560dSAlex Tomas 	len = cur + len;
1285c9de560dSAlex Tomas 	while (cur < len) {
1286c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1287c9de560dSAlex Tomas 			/* fast path: clear whole word at once */
1288c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1289c9de560dSAlex Tomas 			*addr = 0;
1290c9de560dSAlex Tomas 			cur += 32;
1291c9de560dSAlex Tomas 			continue;
1292c9de560dSAlex Tomas 		}
1293e8134b27SAneesh Kumar K.V 		mb_clear_bit(cur, bm);
1294c9de560dSAlex Tomas 		cur++;
1295c9de560dSAlex Tomas 	}
1296c9de560dSAlex Tomas }
1297c9de560dSAlex Tomas 
1298eabe0444SAndrey Sidorov /* clear bits in given range
1299eabe0444SAndrey Sidorov  * will return first found zero bit if any, -1 otherwise
1300eabe0444SAndrey Sidorov  */
1301eabe0444SAndrey Sidorov static int mb_test_and_clear_bits(void *bm, int cur, int len)
1302eabe0444SAndrey Sidorov {
1303eabe0444SAndrey Sidorov 	__u32 *addr;
1304eabe0444SAndrey Sidorov 	int zero_bit = -1;
1305eabe0444SAndrey Sidorov 
1306eabe0444SAndrey Sidorov 	len = cur + len;
1307eabe0444SAndrey Sidorov 	while (cur < len) {
1308eabe0444SAndrey Sidorov 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1309eabe0444SAndrey Sidorov 			/* fast path: clear whole word at once */
1310eabe0444SAndrey Sidorov 			addr = bm + (cur >> 3);
1311eabe0444SAndrey Sidorov 			if (*addr != (__u32)(-1) && zero_bit == -1)
1312eabe0444SAndrey Sidorov 				zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1313eabe0444SAndrey Sidorov 			*addr = 0;
1314eabe0444SAndrey Sidorov 			cur += 32;
1315eabe0444SAndrey Sidorov 			continue;
1316eabe0444SAndrey Sidorov 		}
1317eabe0444SAndrey Sidorov 		if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1318eabe0444SAndrey Sidorov 			zero_bit = cur;
1319eabe0444SAndrey Sidorov 		cur++;
1320eabe0444SAndrey Sidorov 	}
1321eabe0444SAndrey Sidorov 
1322eabe0444SAndrey Sidorov 	return zero_bit;
1323eabe0444SAndrey Sidorov }
1324eabe0444SAndrey Sidorov 
1325c3e94d1dSYongqiang Yang void ext4_set_bits(void *bm, int cur, int len)
1326c9de560dSAlex Tomas {
1327c9de560dSAlex Tomas 	__u32 *addr;
1328c9de560dSAlex Tomas 
1329c9de560dSAlex Tomas 	len = cur + len;
1330c9de560dSAlex Tomas 	while (cur < len) {
1331c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1332c9de560dSAlex Tomas 			/* fast path: set whole word at once */
1333c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1334c9de560dSAlex Tomas 			*addr = 0xffffffff;
1335c9de560dSAlex Tomas 			cur += 32;
1336c9de560dSAlex Tomas 			continue;
1337c9de560dSAlex Tomas 		}
1338e8134b27SAneesh Kumar K.V 		mb_set_bit(cur, bm);
1339c9de560dSAlex Tomas 		cur++;
1340c9de560dSAlex Tomas 	}
1341c9de560dSAlex Tomas }
1342c9de560dSAlex Tomas 
1343eabe0444SAndrey Sidorov /*
1344eabe0444SAndrey Sidorov  * _________________________________________________________________ */
1345eabe0444SAndrey Sidorov 
1346eabe0444SAndrey Sidorov static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1347eabe0444SAndrey Sidorov {
1348eabe0444SAndrey Sidorov 	if (mb_test_bit(*bit + side, bitmap)) {
1349eabe0444SAndrey Sidorov 		mb_clear_bit(*bit, bitmap);
1350eabe0444SAndrey Sidorov 		(*bit) -= side;
1351eabe0444SAndrey Sidorov 		return 1;
1352eabe0444SAndrey Sidorov 	}
1353eabe0444SAndrey Sidorov 	else {
1354eabe0444SAndrey Sidorov 		(*bit) += side;
1355eabe0444SAndrey Sidorov 		mb_set_bit(*bit, bitmap);
1356eabe0444SAndrey Sidorov 		return -1;
1357eabe0444SAndrey Sidorov 	}
1358eabe0444SAndrey Sidorov }
1359eabe0444SAndrey Sidorov 
1360eabe0444SAndrey Sidorov static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1361eabe0444SAndrey Sidorov {
1362eabe0444SAndrey Sidorov 	int max;
1363eabe0444SAndrey Sidorov 	int order = 1;
1364eabe0444SAndrey Sidorov 	void *buddy = mb_find_buddy(e4b, order, &max);
1365eabe0444SAndrey Sidorov 
1366eabe0444SAndrey Sidorov 	while (buddy) {
1367eabe0444SAndrey Sidorov 		void *buddy2;
1368eabe0444SAndrey Sidorov 
1369eabe0444SAndrey Sidorov 		/* Bits in range [first; last] are known to be set since
1370eabe0444SAndrey Sidorov 		 * corresponding blocks were allocated. Bits in range
1371eabe0444SAndrey Sidorov 		 * (first; last) will stay set because they form buddies on
1372eabe0444SAndrey Sidorov 		 * upper layer. We just deal with borders if they don't
1373eabe0444SAndrey Sidorov 		 * align with upper layer and then go up.
1374eabe0444SAndrey Sidorov 		 * Releasing entire group is all about clearing
1375eabe0444SAndrey Sidorov 		 * single bit of highest order buddy.
1376eabe0444SAndrey Sidorov 		 */
1377eabe0444SAndrey Sidorov 
1378eabe0444SAndrey Sidorov 		/* Example:
1379eabe0444SAndrey Sidorov 		 * ---------------------------------
1380eabe0444SAndrey Sidorov 		 * |   1   |   1   |   1   |   1   |
1381eabe0444SAndrey Sidorov 		 * ---------------------------------
1382eabe0444SAndrey Sidorov 		 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1383eabe0444SAndrey Sidorov 		 * ---------------------------------
1384eabe0444SAndrey Sidorov 		 *   0   1   2   3   4   5   6   7
1385eabe0444SAndrey Sidorov 		 *      \_____________________/
1386eabe0444SAndrey Sidorov 		 *
1387eabe0444SAndrey Sidorov 		 * Neither [1] nor [6] is aligned to above layer.
1388eabe0444SAndrey Sidorov 		 * Left neighbour [0] is free, so mark it busy,
1389eabe0444SAndrey Sidorov 		 * decrease bb_counters and extend range to
1390eabe0444SAndrey Sidorov 		 * [0; 6]
1391eabe0444SAndrey Sidorov 		 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1392eabe0444SAndrey Sidorov 		 * mark [6] free, increase bb_counters and shrink range to
1393eabe0444SAndrey Sidorov 		 * [0; 5].
1394eabe0444SAndrey Sidorov 		 * Then shift range to [0; 2], go up and do the same.
1395eabe0444SAndrey Sidorov 		 */
1396eabe0444SAndrey Sidorov 
1397eabe0444SAndrey Sidorov 
1398eabe0444SAndrey Sidorov 		if (first & 1)
1399eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1400eabe0444SAndrey Sidorov 		if (!(last & 1))
1401eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1402eabe0444SAndrey Sidorov 		if (first > last)
1403eabe0444SAndrey Sidorov 			break;
1404eabe0444SAndrey Sidorov 		order++;
1405eabe0444SAndrey Sidorov 
1406eabe0444SAndrey Sidorov 		if (first == last || !(buddy2 = mb_find_buddy(e4b, order, &max))) {
1407eabe0444SAndrey Sidorov 			mb_clear_bits(buddy, first, last - first + 1);
1408eabe0444SAndrey Sidorov 			e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1409eabe0444SAndrey Sidorov 			break;
1410eabe0444SAndrey Sidorov 		}
1411eabe0444SAndrey Sidorov 		first >>= 1;
1412eabe0444SAndrey Sidorov 		last >>= 1;
1413eabe0444SAndrey Sidorov 		buddy = buddy2;
1414eabe0444SAndrey Sidorov 	}
1415eabe0444SAndrey Sidorov }
1416eabe0444SAndrey Sidorov 
14177e5a8cddSShen Feng static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1418c9de560dSAlex Tomas 			   int first, int count)
1419c9de560dSAlex Tomas {
1420eabe0444SAndrey Sidorov 	int left_is_free = 0;
1421eabe0444SAndrey Sidorov 	int right_is_free = 0;
1422eabe0444SAndrey Sidorov 	int block;
1423eabe0444SAndrey Sidorov 	int last = first + count - 1;
1424c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
1425c9de560dSAlex Tomas 
1426c99d1e6eSTheodore Ts'o 	if (WARN_ON(count == 0))
1427c99d1e6eSTheodore Ts'o 		return;
1428eabe0444SAndrey Sidorov 	BUG_ON(last >= (sb->s_blocksize << 3));
1429bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1430163a203dSDarrick J. Wong 	/* Don't bother if the block group is corrupt. */
1431163a203dSDarrick J. Wong 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1432163a203dSDarrick J. Wong 		return;
1433163a203dSDarrick J. Wong 
1434c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1435c9de560dSAlex Tomas 	mb_free_blocks_double(inode, e4b, first, count);
1436c9de560dSAlex Tomas 
1437c9de560dSAlex Tomas 	e4b->bd_info->bb_free += count;
1438c9de560dSAlex Tomas 	if (first < e4b->bd_info->bb_first_free)
1439c9de560dSAlex Tomas 		e4b->bd_info->bb_first_free = first;
1440c9de560dSAlex Tomas 
1441eabe0444SAndrey Sidorov 	/* access memory sequentially: check left neighbour,
1442eabe0444SAndrey Sidorov 	 * clear range and then check right neighbour
1443eabe0444SAndrey Sidorov 	 */
1444c9de560dSAlex Tomas 	if (first != 0)
1445eabe0444SAndrey Sidorov 		left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1446eabe0444SAndrey Sidorov 	block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1447eabe0444SAndrey Sidorov 	if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1448eabe0444SAndrey Sidorov 		right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1449c9de560dSAlex Tomas 
1450eabe0444SAndrey Sidorov 	if (unlikely(block != -1)) {
1451e43bb4e6SNamjae Jeon 		struct ext4_sb_info *sbi = EXT4_SB(sb);
1452c9de560dSAlex Tomas 		ext4_fsblk_t blocknr;
14535661bd68SAkinobu Mita 
14545661bd68SAkinobu Mita 		blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
145553accfa9STheodore Ts'o 		blocknr += EXT4_C2B(EXT4_SB(sb), block);
14565d1b1b3fSAneesh Kumar K.V 		ext4_grp_locked_error(sb, e4b->bd_group,
1457e29136f8STheodore Ts'o 				      inode ? inode->i_ino : 0,
1458e29136f8STheodore Ts'o 				      blocknr,
1459e29136f8STheodore Ts'o 				      "freeing already freed block "
1460163a203dSDarrick J. Wong 				      "(bit %u); block bitmap corrupt.",
1461163a203dSDarrick J. Wong 				      block);
1462e43bb4e6SNamjae Jeon 		if (!EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))
1463e43bb4e6SNamjae Jeon 			percpu_counter_sub(&sbi->s_freeclusters_counter,
1464e43bb4e6SNamjae Jeon 					   e4b->bd_info->bb_free);
1465163a203dSDarrick J. Wong 		/* Mark the block group as corrupt. */
1466163a203dSDarrick J. Wong 		set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT,
1467163a203dSDarrick J. Wong 			&e4b->bd_info->bb_state);
1468eabe0444SAndrey Sidorov 		mb_regenerate_buddy(e4b);
1469eabe0444SAndrey Sidorov 		goto done;
1470c9de560dSAlex Tomas 	}
1471c9de560dSAlex Tomas 
1472eabe0444SAndrey Sidorov 	/* let's maintain fragments counter */
1473eabe0444SAndrey Sidorov 	if (left_is_free && right_is_free)
1474eabe0444SAndrey Sidorov 		e4b->bd_info->bb_fragments--;
1475eabe0444SAndrey Sidorov 	else if (!left_is_free && !right_is_free)
1476eabe0444SAndrey Sidorov 		e4b->bd_info->bb_fragments++;
1477c9de560dSAlex Tomas 
1478eabe0444SAndrey Sidorov 	/* buddy[0] == bd_bitmap is a special case, so handle
1479eabe0444SAndrey Sidorov 	 * it right away and let mb_buddy_mark_free stay free of
1480eabe0444SAndrey Sidorov 	 * zero order checks.
1481eabe0444SAndrey Sidorov 	 * Check if neighbours are to be coaleasced,
1482eabe0444SAndrey Sidorov 	 * adjust bitmap bb_counters and borders appropriately.
1483eabe0444SAndrey Sidorov 	 */
1484eabe0444SAndrey Sidorov 	if (first & 1) {
1485eabe0444SAndrey Sidorov 		first += !left_is_free;
1486eabe0444SAndrey Sidorov 		e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1487c9de560dSAlex Tomas 	}
1488eabe0444SAndrey Sidorov 	if (!(last & 1)) {
1489eabe0444SAndrey Sidorov 		last -= !right_is_free;
1490eabe0444SAndrey Sidorov 		e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1491c9de560dSAlex Tomas 	}
1492eabe0444SAndrey Sidorov 
1493eabe0444SAndrey Sidorov 	if (first <= last)
1494eabe0444SAndrey Sidorov 		mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1495eabe0444SAndrey Sidorov 
1496eabe0444SAndrey Sidorov done:
14978a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, e4b->bd_info);
1498c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1499c9de560dSAlex Tomas }
1500c9de560dSAlex Tomas 
150115c006a2SRobin Dong static int mb_find_extent(struct ext4_buddy *e4b, int block,
1502c9de560dSAlex Tomas 				int needed, struct ext4_free_extent *ex)
1503c9de560dSAlex Tomas {
1504c9de560dSAlex Tomas 	int next = block;
150515c006a2SRobin Dong 	int max, order;
1506c9de560dSAlex Tomas 	void *buddy;
1507c9de560dSAlex Tomas 
1508bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1509c9de560dSAlex Tomas 	BUG_ON(ex == NULL);
1510c9de560dSAlex Tomas 
151115c006a2SRobin Dong 	buddy = mb_find_buddy(e4b, 0, &max);
1512c9de560dSAlex Tomas 	BUG_ON(buddy == NULL);
1513c9de560dSAlex Tomas 	BUG_ON(block >= max);
1514c9de560dSAlex Tomas 	if (mb_test_bit(block, buddy)) {
1515c9de560dSAlex Tomas 		ex->fe_len = 0;
1516c9de560dSAlex Tomas 		ex->fe_start = 0;
1517c9de560dSAlex Tomas 		ex->fe_group = 0;
1518c9de560dSAlex Tomas 		return 0;
1519c9de560dSAlex Tomas 	}
1520c9de560dSAlex Tomas 
1521c9de560dSAlex Tomas 	/* find actual order */
1522c9de560dSAlex Tomas 	order = mb_find_order_for_block(e4b, block);
1523c9de560dSAlex Tomas 	block = block >> order;
1524c9de560dSAlex Tomas 
1525c9de560dSAlex Tomas 	ex->fe_len = 1 << order;
1526c9de560dSAlex Tomas 	ex->fe_start = block << order;
1527c9de560dSAlex Tomas 	ex->fe_group = e4b->bd_group;
1528c9de560dSAlex Tomas 
1529c9de560dSAlex Tomas 	/* calc difference from given start */
1530c9de560dSAlex Tomas 	next = next - ex->fe_start;
1531c9de560dSAlex Tomas 	ex->fe_len -= next;
1532c9de560dSAlex Tomas 	ex->fe_start += next;
1533c9de560dSAlex Tomas 
1534c9de560dSAlex Tomas 	while (needed > ex->fe_len &&
1535d8ec0c39SAlan Cox 	       mb_find_buddy(e4b, order, &max)) {
1536c9de560dSAlex Tomas 
1537c9de560dSAlex Tomas 		if (block + 1 >= max)
1538c9de560dSAlex Tomas 			break;
1539c9de560dSAlex Tomas 
1540c9de560dSAlex Tomas 		next = (block + 1) * (1 << order);
1541c5e8f3f3STheodore Ts'o 		if (mb_test_bit(next, e4b->bd_bitmap))
1542c9de560dSAlex Tomas 			break;
1543c9de560dSAlex Tomas 
1544b051d8dcSRobin Dong 		order = mb_find_order_for_block(e4b, next);
1545c9de560dSAlex Tomas 
1546c9de560dSAlex Tomas 		block = next >> order;
1547c9de560dSAlex Tomas 		ex->fe_len += 1 << order;
1548c9de560dSAlex Tomas 	}
1549c9de560dSAlex Tomas 
1550c9de560dSAlex Tomas 	BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1551c9de560dSAlex Tomas 	return ex->fe_len;
1552c9de560dSAlex Tomas }
1553c9de560dSAlex Tomas 
1554c9de560dSAlex Tomas static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1555c9de560dSAlex Tomas {
1556c9de560dSAlex Tomas 	int ord;
1557c9de560dSAlex Tomas 	int mlen = 0;
1558c9de560dSAlex Tomas 	int max = 0;
1559c9de560dSAlex Tomas 	int cur;
1560c9de560dSAlex Tomas 	int start = ex->fe_start;
1561c9de560dSAlex Tomas 	int len = ex->fe_len;
1562c9de560dSAlex Tomas 	unsigned ret = 0;
1563c9de560dSAlex Tomas 	int len0 = len;
1564c9de560dSAlex Tomas 	void *buddy;
1565c9de560dSAlex Tomas 
1566c9de560dSAlex Tomas 	BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1567c9de560dSAlex Tomas 	BUG_ON(e4b->bd_group != ex->fe_group);
1568bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1569c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1570c9de560dSAlex Tomas 	mb_mark_used_double(e4b, start, len);
1571c9de560dSAlex Tomas 
1572c9de560dSAlex Tomas 	e4b->bd_info->bb_free -= len;
1573c9de560dSAlex Tomas 	if (e4b->bd_info->bb_first_free == start)
1574c9de560dSAlex Tomas 		e4b->bd_info->bb_first_free += len;
1575c9de560dSAlex Tomas 
1576c9de560dSAlex Tomas 	/* let's maintain fragments counter */
1577c9de560dSAlex Tomas 	if (start != 0)
1578c5e8f3f3STheodore Ts'o 		mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1579c9de560dSAlex Tomas 	if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1580c5e8f3f3STheodore Ts'o 		max = !mb_test_bit(start + len, e4b->bd_bitmap);
1581c9de560dSAlex Tomas 	if (mlen && max)
1582c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments++;
1583c9de560dSAlex Tomas 	else if (!mlen && !max)
1584c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments--;
1585c9de560dSAlex Tomas 
1586c9de560dSAlex Tomas 	/* let's maintain buddy itself */
1587c9de560dSAlex Tomas 	while (len) {
1588c9de560dSAlex Tomas 		ord = mb_find_order_for_block(e4b, start);
1589c9de560dSAlex Tomas 
1590c9de560dSAlex Tomas 		if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1591c9de560dSAlex Tomas 			/* the whole chunk may be allocated at once! */
1592c9de560dSAlex Tomas 			mlen = 1 << ord;
1593c9de560dSAlex Tomas 			buddy = mb_find_buddy(e4b, ord, &max);
1594c9de560dSAlex Tomas 			BUG_ON((start >> ord) >= max);
1595c9de560dSAlex Tomas 			mb_set_bit(start >> ord, buddy);
1596c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[ord]--;
1597c9de560dSAlex Tomas 			start += mlen;
1598c9de560dSAlex Tomas 			len -= mlen;
1599c9de560dSAlex Tomas 			BUG_ON(len < 0);
1600c9de560dSAlex Tomas 			continue;
1601c9de560dSAlex Tomas 		}
1602c9de560dSAlex Tomas 
1603c9de560dSAlex Tomas 		/* store for history */
1604c9de560dSAlex Tomas 		if (ret == 0)
1605c9de560dSAlex Tomas 			ret = len | (ord << 16);
1606c9de560dSAlex Tomas 
1607c9de560dSAlex Tomas 		/* we have to split large buddy */
1608c9de560dSAlex Tomas 		BUG_ON(ord <= 0);
1609c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, ord, &max);
1610c9de560dSAlex Tomas 		mb_set_bit(start >> ord, buddy);
1611c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]--;
1612c9de560dSAlex Tomas 
1613c9de560dSAlex Tomas 		ord--;
1614c9de560dSAlex Tomas 		cur = (start >> ord) & ~1U;
1615c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, ord, &max);
1616c9de560dSAlex Tomas 		mb_clear_bit(cur, buddy);
1617c9de560dSAlex Tomas 		mb_clear_bit(cur + 1, buddy);
1618c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]++;
1619c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]++;
1620c9de560dSAlex Tomas 	}
16218a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1622c9de560dSAlex Tomas 
1623c5e8f3f3STheodore Ts'o 	ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1624c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1625c9de560dSAlex Tomas 
1626c9de560dSAlex Tomas 	return ret;
1627c9de560dSAlex Tomas }
1628c9de560dSAlex Tomas 
1629c9de560dSAlex Tomas /*
1630c9de560dSAlex Tomas  * Must be called under group lock!
1631c9de560dSAlex Tomas  */
1632c9de560dSAlex Tomas static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1633c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1634c9de560dSAlex Tomas {
1635c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1636c9de560dSAlex Tomas 	int ret;
1637c9de560dSAlex Tomas 
1638c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1639c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1640c9de560dSAlex Tomas 
1641c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1642c9de560dSAlex Tomas 	ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1643c9de560dSAlex Tomas 	ret = mb_mark_used(e4b, &ac->ac_b_ex);
1644c9de560dSAlex Tomas 
1645c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
1646c9de560dSAlex Tomas 	 * allocated blocks for history */
1647c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
1648c9de560dSAlex Tomas 
1649c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
1650c9de560dSAlex Tomas 	ac->ac_tail = ret & 0xffff;
1651c9de560dSAlex Tomas 	ac->ac_buddy = ret >> 16;
1652c9de560dSAlex Tomas 
1653c3a326a6SAneesh Kumar K.V 	/*
1654c3a326a6SAneesh Kumar K.V 	 * take the page reference. We want the page to be pinned
1655c3a326a6SAneesh Kumar K.V 	 * so that we don't get a ext4_mb_init_cache_call for this
1656c3a326a6SAneesh Kumar K.V 	 * group until we update the bitmap. That would mean we
1657c3a326a6SAneesh Kumar K.V 	 * double allocate blocks. The reference is dropped
1658c3a326a6SAneesh Kumar K.V 	 * in ext4_mb_release_context
1659c3a326a6SAneesh Kumar K.V 	 */
1660c9de560dSAlex Tomas 	ac->ac_bitmap_page = e4b->bd_bitmap_page;
1661c9de560dSAlex Tomas 	get_page(ac->ac_bitmap_page);
1662c9de560dSAlex Tomas 	ac->ac_buddy_page = e4b->bd_buddy_page;
1663c9de560dSAlex Tomas 	get_page(ac->ac_buddy_page);
1664c9de560dSAlex Tomas 	/* store last allocated for subsequent stream allocation */
16654ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1666c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
1667c9de560dSAlex Tomas 		sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1668c9de560dSAlex Tomas 		sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1669c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
1670c9de560dSAlex Tomas 	}
1671c9de560dSAlex Tomas }
1672c9de560dSAlex Tomas 
1673c9de560dSAlex Tomas /*
1674c9de560dSAlex Tomas  * regular allocator, for general purposes allocation
1675c9de560dSAlex Tomas  */
1676c9de560dSAlex Tomas 
1677c9de560dSAlex Tomas static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1678c9de560dSAlex Tomas 					struct ext4_buddy *e4b,
1679c9de560dSAlex Tomas 					int finish_group)
1680c9de560dSAlex Tomas {
1681c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1682c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
1683c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
1684c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1685c9de560dSAlex Tomas 	int max;
1686c9de560dSAlex Tomas 
1687032115fcSAneesh Kumar K.V 	if (ac->ac_status == AC_STATUS_FOUND)
1688032115fcSAneesh Kumar K.V 		return;
1689c9de560dSAlex Tomas 	/*
1690c9de560dSAlex Tomas 	 * We don't want to scan for a whole year
1691c9de560dSAlex Tomas 	 */
1692c9de560dSAlex Tomas 	if (ac->ac_found > sbi->s_mb_max_to_scan &&
1693c9de560dSAlex Tomas 			!(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1694c9de560dSAlex Tomas 		ac->ac_status = AC_STATUS_BREAK;
1695c9de560dSAlex Tomas 		return;
1696c9de560dSAlex Tomas 	}
1697c9de560dSAlex Tomas 
1698c9de560dSAlex Tomas 	/*
1699c9de560dSAlex Tomas 	 * Haven't found good chunk so far, let's continue
1700c9de560dSAlex Tomas 	 */
1701c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len)
1702c9de560dSAlex Tomas 		return;
1703c9de560dSAlex Tomas 
1704c9de560dSAlex Tomas 	if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1705c9de560dSAlex Tomas 			&& bex->fe_group == e4b->bd_group) {
1706c9de560dSAlex Tomas 		/* recheck chunk's availability - we don't know
1707c9de560dSAlex Tomas 		 * when it was found (within this lock-unlock
1708c9de560dSAlex Tomas 		 * period or not) */
170915c006a2SRobin Dong 		max = mb_find_extent(e4b, bex->fe_start, gex->fe_len, &ex);
1710c9de560dSAlex Tomas 		if (max >= gex->fe_len) {
1711c9de560dSAlex Tomas 			ext4_mb_use_best_found(ac, e4b);
1712c9de560dSAlex Tomas 			return;
1713c9de560dSAlex Tomas 		}
1714c9de560dSAlex Tomas 	}
1715c9de560dSAlex Tomas }
1716c9de560dSAlex Tomas 
1717c9de560dSAlex Tomas /*
1718c9de560dSAlex Tomas  * The routine checks whether found extent is good enough. If it is,
1719c9de560dSAlex Tomas  * then the extent gets marked used and flag is set to the context
1720c9de560dSAlex Tomas  * to stop scanning. Otherwise, the extent is compared with the
1721c9de560dSAlex Tomas  * previous found extent and if new one is better, then it's stored
1722c9de560dSAlex Tomas  * in the context. Later, the best found extent will be used, if
1723c9de560dSAlex Tomas  * mballoc can't find good enough extent.
1724c9de560dSAlex Tomas  *
1725c9de560dSAlex Tomas  * FIXME: real allocation policy is to be designed yet!
1726c9de560dSAlex Tomas  */
1727c9de560dSAlex Tomas static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1728c9de560dSAlex Tomas 					struct ext4_free_extent *ex,
1729c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1730c9de560dSAlex Tomas {
1731c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
1732c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
1733c9de560dSAlex Tomas 
1734c9de560dSAlex Tomas 	BUG_ON(ex->fe_len <= 0);
17357137d7a4STheodore Ts'o 	BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
17367137d7a4STheodore Ts'o 	BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1737c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1738c9de560dSAlex Tomas 
1739c9de560dSAlex Tomas 	ac->ac_found++;
1740c9de560dSAlex Tomas 
1741c9de560dSAlex Tomas 	/*
1742c9de560dSAlex Tomas 	 * The special case - take what you catch first
1743c9de560dSAlex Tomas 	 */
1744c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1745c9de560dSAlex Tomas 		*bex = *ex;
1746c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1747c9de560dSAlex Tomas 		return;
1748c9de560dSAlex Tomas 	}
1749c9de560dSAlex Tomas 
1750c9de560dSAlex Tomas 	/*
1751c9de560dSAlex Tomas 	 * Let's check whether the chuck is good enough
1752c9de560dSAlex Tomas 	 */
1753c9de560dSAlex Tomas 	if (ex->fe_len == gex->fe_len) {
1754c9de560dSAlex Tomas 		*bex = *ex;
1755c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1756c9de560dSAlex Tomas 		return;
1757c9de560dSAlex Tomas 	}
1758c9de560dSAlex Tomas 
1759c9de560dSAlex Tomas 	/*
1760c9de560dSAlex Tomas 	 * If this is first found extent, just store it in the context
1761c9de560dSAlex Tomas 	 */
1762c9de560dSAlex Tomas 	if (bex->fe_len == 0) {
1763c9de560dSAlex Tomas 		*bex = *ex;
1764c9de560dSAlex Tomas 		return;
1765c9de560dSAlex Tomas 	}
1766c9de560dSAlex Tomas 
1767c9de560dSAlex Tomas 	/*
1768c9de560dSAlex Tomas 	 * If new found extent is better, store it in the context
1769c9de560dSAlex Tomas 	 */
1770c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len) {
1771c9de560dSAlex Tomas 		/* if the request isn't satisfied, any found extent
1772c9de560dSAlex Tomas 		 * larger than previous best one is better */
1773c9de560dSAlex Tomas 		if (ex->fe_len > bex->fe_len)
1774c9de560dSAlex Tomas 			*bex = *ex;
1775c9de560dSAlex Tomas 	} else if (ex->fe_len > gex->fe_len) {
1776c9de560dSAlex Tomas 		/* if the request is satisfied, then we try to find
1777c9de560dSAlex Tomas 		 * an extent that still satisfy the request, but is
1778c9de560dSAlex Tomas 		 * smaller than previous one */
1779c9de560dSAlex Tomas 		if (ex->fe_len < bex->fe_len)
1780c9de560dSAlex Tomas 			*bex = *ex;
1781c9de560dSAlex Tomas 	}
1782c9de560dSAlex Tomas 
1783c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 0);
1784c9de560dSAlex Tomas }
1785c9de560dSAlex Tomas 
1786089ceeccSEric Sandeen static noinline_for_stack
1787089ceeccSEric Sandeen int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1788c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1789c9de560dSAlex Tomas {
1790c9de560dSAlex Tomas 	struct ext4_free_extent ex = ac->ac_b_ex;
1791c9de560dSAlex Tomas 	ext4_group_t group = ex.fe_group;
1792c9de560dSAlex Tomas 	int max;
1793c9de560dSAlex Tomas 	int err;
1794c9de560dSAlex Tomas 
1795c9de560dSAlex Tomas 	BUG_ON(ex.fe_len <= 0);
1796c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1797c9de560dSAlex Tomas 	if (err)
1798c9de560dSAlex Tomas 		return err;
1799c9de560dSAlex Tomas 
1800c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
180115c006a2SRobin Dong 	max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
1802c9de560dSAlex Tomas 
1803c9de560dSAlex Tomas 	if (max > 0) {
1804c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
1805c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1806c9de560dSAlex Tomas 	}
1807c9de560dSAlex Tomas 
1808c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
1809e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
1810c9de560dSAlex Tomas 
1811c9de560dSAlex Tomas 	return 0;
1812c9de560dSAlex Tomas }
1813c9de560dSAlex Tomas 
1814089ceeccSEric Sandeen static noinline_for_stack
1815089ceeccSEric Sandeen int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1816c9de560dSAlex Tomas 				struct ext4_buddy *e4b)
1817c9de560dSAlex Tomas {
1818c9de560dSAlex Tomas 	ext4_group_t group = ac->ac_g_ex.fe_group;
1819c9de560dSAlex Tomas 	int max;
1820c9de560dSAlex Tomas 	int err;
1821c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1822838cd0cfSYongqiang Yang 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1823c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1824c9de560dSAlex Tomas 
1825c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1826c9de560dSAlex Tomas 		return 0;
1827838cd0cfSYongqiang Yang 	if (grp->bb_free == 0)
1828838cd0cfSYongqiang Yang 		return 0;
1829c9de560dSAlex Tomas 
1830c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1831c9de560dSAlex Tomas 	if (err)
1832c9de560dSAlex Tomas 		return err;
1833c9de560dSAlex Tomas 
1834163a203dSDarrick J. Wong 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
1835163a203dSDarrick J. Wong 		ext4_mb_unload_buddy(e4b);
1836163a203dSDarrick J. Wong 		return 0;
1837163a203dSDarrick J. Wong 	}
1838163a203dSDarrick J. Wong 
1839c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
184015c006a2SRobin Dong 	max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
1841c9de560dSAlex Tomas 			     ac->ac_g_ex.fe_len, &ex);
1842ab0c00fcSTheodore Ts'o 	ex.fe_logical = 0xDEADFA11; /* debug value */
1843c9de560dSAlex Tomas 
1844c9de560dSAlex Tomas 	if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1845c9de560dSAlex Tomas 		ext4_fsblk_t start;
1846c9de560dSAlex Tomas 
18475661bd68SAkinobu Mita 		start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
18485661bd68SAkinobu Mita 			ex.fe_start;
1849c9de560dSAlex Tomas 		/* use do_div to get remainder (would be 64-bit modulo) */
1850c9de560dSAlex Tomas 		if (do_div(start, sbi->s_stripe) == 0) {
1851c9de560dSAlex Tomas 			ac->ac_found++;
1852c9de560dSAlex Tomas 			ac->ac_b_ex = ex;
1853c9de560dSAlex Tomas 			ext4_mb_use_best_found(ac, e4b);
1854c9de560dSAlex Tomas 		}
1855c9de560dSAlex Tomas 	} else if (max >= ac->ac_g_ex.fe_len) {
1856c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
1857c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1858c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1859c9de560dSAlex Tomas 		ac->ac_found++;
1860c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
1861c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1862c9de560dSAlex Tomas 	} else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1863c9de560dSAlex Tomas 		/* Sometimes, caller may want to merge even small
1864c9de560dSAlex Tomas 		 * number of blocks to an existing extent */
1865c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
1866c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1867c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1868c9de560dSAlex Tomas 		ac->ac_found++;
1869c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
1870c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1871c9de560dSAlex Tomas 	}
1872c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
1873e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
1874c9de560dSAlex Tomas 
1875c9de560dSAlex Tomas 	return 0;
1876c9de560dSAlex Tomas }
1877c9de560dSAlex Tomas 
1878c9de560dSAlex Tomas /*
1879c9de560dSAlex Tomas  * The routine scans buddy structures (not bitmap!) from given order
1880c9de560dSAlex Tomas  * to max order and tries to find big enough chunk to satisfy the req
1881c9de560dSAlex Tomas  */
1882089ceeccSEric Sandeen static noinline_for_stack
1883089ceeccSEric Sandeen void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1884c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1885c9de560dSAlex Tomas {
1886c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
1887c9de560dSAlex Tomas 	struct ext4_group_info *grp = e4b->bd_info;
1888c9de560dSAlex Tomas 	void *buddy;
1889c9de560dSAlex Tomas 	int i;
1890c9de560dSAlex Tomas 	int k;
1891c9de560dSAlex Tomas 	int max;
1892c9de560dSAlex Tomas 
1893c9de560dSAlex Tomas 	BUG_ON(ac->ac_2order <= 0);
1894c9de560dSAlex Tomas 	for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1895c9de560dSAlex Tomas 		if (grp->bb_counters[i] == 0)
1896c9de560dSAlex Tomas 			continue;
1897c9de560dSAlex Tomas 
1898c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, i, &max);
1899c9de560dSAlex Tomas 		BUG_ON(buddy == NULL);
1900c9de560dSAlex Tomas 
1901ffad0a44SAneesh Kumar K.V 		k = mb_find_next_zero_bit(buddy, max, 0);
1902c9de560dSAlex Tomas 		BUG_ON(k >= max);
1903c9de560dSAlex Tomas 
1904c9de560dSAlex Tomas 		ac->ac_found++;
1905c9de560dSAlex Tomas 
1906c9de560dSAlex Tomas 		ac->ac_b_ex.fe_len = 1 << i;
1907c9de560dSAlex Tomas 		ac->ac_b_ex.fe_start = k << i;
1908c9de560dSAlex Tomas 		ac->ac_b_ex.fe_group = e4b->bd_group;
1909c9de560dSAlex Tomas 
1910c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1911c9de560dSAlex Tomas 
1912c9de560dSAlex Tomas 		BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1913c9de560dSAlex Tomas 
1914c9de560dSAlex Tomas 		if (EXT4_SB(sb)->s_mb_stats)
1915c9de560dSAlex Tomas 			atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1916c9de560dSAlex Tomas 
1917c9de560dSAlex Tomas 		break;
1918c9de560dSAlex Tomas 	}
1919c9de560dSAlex Tomas }
1920c9de560dSAlex Tomas 
1921c9de560dSAlex Tomas /*
1922c9de560dSAlex Tomas  * The routine scans the group and measures all found extents.
1923c9de560dSAlex Tomas  * In order to optimize scanning, caller must pass number of
1924c9de560dSAlex Tomas  * free blocks in the group, so the routine can know upper limit.
1925c9de560dSAlex Tomas  */
1926089ceeccSEric Sandeen static noinline_for_stack
1927089ceeccSEric Sandeen void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1928c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1929c9de560dSAlex Tomas {
1930c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
1931c5e8f3f3STheodore Ts'o 	void *bitmap = e4b->bd_bitmap;
1932c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1933c9de560dSAlex Tomas 	int i;
1934c9de560dSAlex Tomas 	int free;
1935c9de560dSAlex Tomas 
1936c9de560dSAlex Tomas 	free = e4b->bd_info->bb_free;
1937c9de560dSAlex Tomas 	BUG_ON(free <= 0);
1938c9de560dSAlex Tomas 
1939c9de560dSAlex Tomas 	i = e4b->bd_info->bb_first_free;
1940c9de560dSAlex Tomas 
1941c9de560dSAlex Tomas 	while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1942ffad0a44SAneesh Kumar K.V 		i = mb_find_next_zero_bit(bitmap,
19437137d7a4STheodore Ts'o 						EXT4_CLUSTERS_PER_GROUP(sb), i);
19447137d7a4STheodore Ts'o 		if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
194526346ff6SAneesh Kumar K.V 			/*
1946e56eb659SAneesh Kumar K.V 			 * IF we have corrupt bitmap, we won't find any
194726346ff6SAneesh Kumar K.V 			 * free blocks even though group info says we
194826346ff6SAneesh Kumar K.V 			 * we have free blocks
194926346ff6SAneesh Kumar K.V 			 */
1950e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
195153accfa9STheodore Ts'o 					"%d free clusters as per "
1952fde4d95aSTheodore Ts'o 					"group info. But bitmap says 0",
195326346ff6SAneesh Kumar K.V 					free);
1954c9de560dSAlex Tomas 			break;
1955c9de560dSAlex Tomas 		}
1956c9de560dSAlex Tomas 
195715c006a2SRobin Dong 		mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
1958c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
195926346ff6SAneesh Kumar K.V 		if (free < ex.fe_len) {
1960e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
196153accfa9STheodore Ts'o 					"%d free clusters as per "
1962fde4d95aSTheodore Ts'o 					"group info. But got %d blocks",
196326346ff6SAneesh Kumar K.V 					free, ex.fe_len);
1964e56eb659SAneesh Kumar K.V 			/*
1965e56eb659SAneesh Kumar K.V 			 * The number of free blocks differs. This mostly
1966e56eb659SAneesh Kumar K.V 			 * indicate that the bitmap is corrupt. So exit
1967e56eb659SAneesh Kumar K.V 			 * without claiming the space.
1968e56eb659SAneesh Kumar K.V 			 */
1969e56eb659SAneesh Kumar K.V 			break;
197026346ff6SAneesh Kumar K.V 		}
1971ab0c00fcSTheodore Ts'o 		ex.fe_logical = 0xDEADC0DE; /* debug value */
1972c9de560dSAlex Tomas 		ext4_mb_measure_extent(ac, &ex, e4b);
1973c9de560dSAlex Tomas 
1974c9de560dSAlex Tomas 		i += ex.fe_len;
1975c9de560dSAlex Tomas 		free -= ex.fe_len;
1976c9de560dSAlex Tomas 	}
1977c9de560dSAlex Tomas 
1978c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 1);
1979c9de560dSAlex Tomas }
1980c9de560dSAlex Tomas 
1981c9de560dSAlex Tomas /*
1982c9de560dSAlex Tomas  * This is a special case for storages like raid5
1983506bf2d8SEric Sandeen  * we try to find stripe-aligned chunks for stripe-size-multiple requests
1984c9de560dSAlex Tomas  */
1985089ceeccSEric Sandeen static noinline_for_stack
1986089ceeccSEric Sandeen void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1987c9de560dSAlex Tomas 				 struct ext4_buddy *e4b)
1988c9de560dSAlex Tomas {
1989c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
1990c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1991c5e8f3f3STheodore Ts'o 	void *bitmap = e4b->bd_bitmap;
1992c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1993c9de560dSAlex Tomas 	ext4_fsblk_t first_group_block;
1994c9de560dSAlex Tomas 	ext4_fsblk_t a;
1995c9de560dSAlex Tomas 	ext4_grpblk_t i;
1996c9de560dSAlex Tomas 	int max;
1997c9de560dSAlex Tomas 
1998c9de560dSAlex Tomas 	BUG_ON(sbi->s_stripe == 0);
1999c9de560dSAlex Tomas 
2000c9de560dSAlex Tomas 	/* find first stripe-aligned block in group */
20015661bd68SAkinobu Mita 	first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
20025661bd68SAkinobu Mita 
2003c9de560dSAlex Tomas 	a = first_group_block + sbi->s_stripe - 1;
2004c9de560dSAlex Tomas 	do_div(a, sbi->s_stripe);
2005c9de560dSAlex Tomas 	i = (a * sbi->s_stripe) - first_group_block;
2006c9de560dSAlex Tomas 
20077137d7a4STheodore Ts'o 	while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2008c9de560dSAlex Tomas 		if (!mb_test_bit(i, bitmap)) {
200915c006a2SRobin Dong 			max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
2010c9de560dSAlex Tomas 			if (max >= sbi->s_stripe) {
2011c9de560dSAlex Tomas 				ac->ac_found++;
2012ab0c00fcSTheodore Ts'o 				ex.fe_logical = 0xDEADF00D; /* debug value */
2013c9de560dSAlex Tomas 				ac->ac_b_ex = ex;
2014c9de560dSAlex Tomas 				ext4_mb_use_best_found(ac, e4b);
2015c9de560dSAlex Tomas 				break;
2016c9de560dSAlex Tomas 			}
2017c9de560dSAlex Tomas 		}
2018c9de560dSAlex Tomas 		i += sbi->s_stripe;
2019c9de560dSAlex Tomas 	}
2020c9de560dSAlex Tomas }
2021c9de560dSAlex Tomas 
202242ac1848SLukas Czerner /*
202342ac1848SLukas Czerner  * This is now called BEFORE we load the buddy bitmap.
202442ac1848SLukas Czerner  * Returns either 1 or 0 indicating that the group is either suitable
202542ac1848SLukas Czerner  * for the allocation or not. In addition it can also return negative
202642ac1848SLukas Czerner  * error code when something goes wrong.
202742ac1848SLukas Czerner  */
2028c9de560dSAlex Tomas static int ext4_mb_good_group(struct ext4_allocation_context *ac,
2029c9de560dSAlex Tomas 				ext4_group_t group, int cr)
2030c9de560dSAlex Tomas {
2031c9de560dSAlex Tomas 	unsigned free, fragments;
2032a4912123STheodore Ts'o 	int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2033c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2034c9de560dSAlex Tomas 
2035c9de560dSAlex Tomas 	BUG_ON(cr < 0 || cr >= 4);
20368a57d9d6SCurt Wohlgemuth 
203701fc48e8STheodore Ts'o 	free = grp->bb_free;
203801fc48e8STheodore Ts'o 	if (free == 0)
203901fc48e8STheodore Ts'o 		return 0;
204001fc48e8STheodore Ts'o 	if (cr <= 2 && free < ac->ac_g_ex.fe_len)
204101fc48e8STheodore Ts'o 		return 0;
204201fc48e8STheodore Ts'o 
2043163a203dSDarrick J. Wong 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2044163a203dSDarrick J. Wong 		return 0;
2045163a203dSDarrick J. Wong 
20468a57d9d6SCurt Wohlgemuth 	/* We only do this if the grp has never been initialized */
20478a57d9d6SCurt Wohlgemuth 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
20488a57d9d6SCurt Wohlgemuth 		int ret = ext4_mb_init_group(ac->ac_sb, group);
20498a57d9d6SCurt Wohlgemuth 		if (ret)
205042ac1848SLukas Czerner 			return ret;
20518a57d9d6SCurt Wohlgemuth 	}
2052c9de560dSAlex Tomas 
2053c9de560dSAlex Tomas 	fragments = grp->bb_fragments;
2054c9de560dSAlex Tomas 	if (fragments == 0)
2055c9de560dSAlex Tomas 		return 0;
2056c9de560dSAlex Tomas 
2057c9de560dSAlex Tomas 	switch (cr) {
2058c9de560dSAlex Tomas 	case 0:
2059c9de560dSAlex Tomas 		BUG_ON(ac->ac_2order == 0);
2060c9de560dSAlex Tomas 
2061a4912123STheodore Ts'o 		/* Avoid using the first bg of a flexgroup for data files */
2062a4912123STheodore Ts'o 		if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2063a4912123STheodore Ts'o 		    (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2064a4912123STheodore Ts'o 		    ((group % flex_size) == 0))
2065a4912123STheodore Ts'o 			return 0;
2066a4912123STheodore Ts'o 
206740ae3487STheodore Ts'o 		if ((ac->ac_2order > ac->ac_sb->s_blocksize_bits+1) ||
206840ae3487STheodore Ts'o 		    (free / fragments) >= ac->ac_g_ex.fe_len)
206940ae3487STheodore Ts'o 			return 1;
207040ae3487STheodore Ts'o 
207140ae3487STheodore Ts'o 		if (grp->bb_largest_free_order < ac->ac_2order)
207240ae3487STheodore Ts'o 			return 0;
207340ae3487STheodore Ts'o 
2074c9de560dSAlex Tomas 		return 1;
2075c9de560dSAlex Tomas 	case 1:
2076c9de560dSAlex Tomas 		if ((free / fragments) >= ac->ac_g_ex.fe_len)
2077c9de560dSAlex Tomas 			return 1;
2078c9de560dSAlex Tomas 		break;
2079c9de560dSAlex Tomas 	case 2:
2080c9de560dSAlex Tomas 		if (free >= ac->ac_g_ex.fe_len)
2081c9de560dSAlex Tomas 			return 1;
2082c9de560dSAlex Tomas 		break;
2083c9de560dSAlex Tomas 	case 3:
2084c9de560dSAlex Tomas 		return 1;
2085c9de560dSAlex Tomas 	default:
2086c9de560dSAlex Tomas 		BUG();
2087c9de560dSAlex Tomas 	}
2088c9de560dSAlex Tomas 
2089c9de560dSAlex Tomas 	return 0;
2090c9de560dSAlex Tomas }
2091c9de560dSAlex Tomas 
20924ddfef7bSEric Sandeen static noinline_for_stack int
20934ddfef7bSEric Sandeen ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2094c9de560dSAlex Tomas {
20958df9675fSTheodore Ts'o 	ext4_group_t ngroups, group, i;
2096c9de560dSAlex Tomas 	int cr;
209742ac1848SLukas Czerner 	int err = 0, first_err = 0;
2098c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
2099c9de560dSAlex Tomas 	struct super_block *sb;
2100c9de560dSAlex Tomas 	struct ext4_buddy e4b;
2101c9de560dSAlex Tomas 
2102c9de560dSAlex Tomas 	sb = ac->ac_sb;
2103c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
21048df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
2105fb0a387dSEric Sandeen 	/* non-extent files are limited to low blocks/groups */
210612e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2107fb0a387dSEric Sandeen 		ngroups = sbi->s_blockfile_groups;
2108fb0a387dSEric Sandeen 
2109c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2110c9de560dSAlex Tomas 
2111c9de560dSAlex Tomas 	/* first, try the goal */
2112c9de560dSAlex Tomas 	err = ext4_mb_find_by_goal(ac, &e4b);
2113c9de560dSAlex Tomas 	if (err || ac->ac_status == AC_STATUS_FOUND)
2114c9de560dSAlex Tomas 		goto out;
2115c9de560dSAlex Tomas 
2116c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2117c9de560dSAlex Tomas 		goto out;
2118c9de560dSAlex Tomas 
2119c9de560dSAlex Tomas 	/*
2120c9de560dSAlex Tomas 	 * ac->ac2_order is set only if the fe_len is a power of 2
2121c9de560dSAlex Tomas 	 * if ac2_order is set we also set criteria to 0 so that we
2122c9de560dSAlex Tomas 	 * try exact allocation using buddy.
2123c9de560dSAlex Tomas 	 */
2124c9de560dSAlex Tomas 	i = fls(ac->ac_g_ex.fe_len);
2125c9de560dSAlex Tomas 	ac->ac_2order = 0;
2126c9de560dSAlex Tomas 	/*
2127c9de560dSAlex Tomas 	 * We search using buddy data only if the order of the request
2128c9de560dSAlex Tomas 	 * is greater than equal to the sbi_s_mb_order2_reqs
2129b713a5ecSTheodore Ts'o 	 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2130c9de560dSAlex Tomas 	 */
2131c9de560dSAlex Tomas 	if (i >= sbi->s_mb_order2_reqs) {
2132c9de560dSAlex Tomas 		/*
2133c9de560dSAlex Tomas 		 * This should tell if fe_len is exactly power of 2
2134c9de560dSAlex Tomas 		 */
2135c9de560dSAlex Tomas 		if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2136c9de560dSAlex Tomas 			ac->ac_2order = i - 1;
2137c9de560dSAlex Tomas 	}
2138c9de560dSAlex Tomas 
21394ba74d00STheodore Ts'o 	/* if stream allocation is enabled, use global goal */
21404ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2141c9de560dSAlex Tomas 		/* TBD: may be hot point */
2142c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
2143c9de560dSAlex Tomas 		ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2144c9de560dSAlex Tomas 		ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2145c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
2146c9de560dSAlex Tomas 	}
21474ba74d00STheodore Ts'o 
2148c9de560dSAlex Tomas 	/* Let's just scan groups to find more-less suitable blocks */
2149c9de560dSAlex Tomas 	cr = ac->ac_2order ? 0 : 1;
2150c9de560dSAlex Tomas 	/*
2151c9de560dSAlex Tomas 	 * cr == 0 try to get exact allocation,
2152c9de560dSAlex Tomas 	 * cr == 3  try to get anything
2153c9de560dSAlex Tomas 	 */
2154c9de560dSAlex Tomas repeat:
2155c9de560dSAlex Tomas 	for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2156c9de560dSAlex Tomas 		ac->ac_criteria = cr;
2157ed8f9c75SAneesh Kumar K.V 		/*
2158ed8f9c75SAneesh Kumar K.V 		 * searching for the right group start
2159ed8f9c75SAneesh Kumar K.V 		 * from the goal value specified
2160ed8f9c75SAneesh Kumar K.V 		 */
2161ed8f9c75SAneesh Kumar K.V 		group = ac->ac_g_ex.fe_group;
2162ed8f9c75SAneesh Kumar K.V 
21638df9675fSTheodore Ts'o 		for (i = 0; i < ngroups; group++, i++) {
216442ac1848SLukas Czerner 			int ret = 0;
21652ed5724dSTheodore Ts'o 			cond_resched();
2166e6155736SLachlan McIlroy 			/*
2167e6155736SLachlan McIlroy 			 * Artificially restricted ngroups for non-extent
2168e6155736SLachlan McIlroy 			 * files makes group > ngroups possible on first loop.
2169e6155736SLachlan McIlroy 			 */
2170e6155736SLachlan McIlroy 			if (group >= ngroups)
2171c9de560dSAlex Tomas 				group = 0;
2172c9de560dSAlex Tomas 
21738a57d9d6SCurt Wohlgemuth 			/* This now checks without needing the buddy page */
217442ac1848SLukas Czerner 			ret = ext4_mb_good_group(ac, group, cr);
217542ac1848SLukas Czerner 			if (ret <= 0) {
217642ac1848SLukas Czerner 				if (!first_err)
217742ac1848SLukas Czerner 					first_err = ret;
2178c9de560dSAlex Tomas 				continue;
217942ac1848SLukas Czerner 			}
2180c9de560dSAlex Tomas 
2181c9de560dSAlex Tomas 			err = ext4_mb_load_buddy(sb, group, &e4b);
2182c9de560dSAlex Tomas 			if (err)
2183c9de560dSAlex Tomas 				goto out;
2184c9de560dSAlex Tomas 
2185c9de560dSAlex Tomas 			ext4_lock_group(sb, group);
21868a57d9d6SCurt Wohlgemuth 
21878a57d9d6SCurt Wohlgemuth 			/*
21888a57d9d6SCurt Wohlgemuth 			 * We need to check again after locking the
21898a57d9d6SCurt Wohlgemuth 			 * block group
21908a57d9d6SCurt Wohlgemuth 			 */
219142ac1848SLukas Czerner 			ret = ext4_mb_good_group(ac, group, cr);
219242ac1848SLukas Czerner 			if (ret <= 0) {
2193c9de560dSAlex Tomas 				ext4_unlock_group(sb, group);
2194e39e07fdSJing Zhang 				ext4_mb_unload_buddy(&e4b);
219542ac1848SLukas Czerner 				if (!first_err)
219642ac1848SLukas Czerner 					first_err = ret;
2197c9de560dSAlex Tomas 				continue;
2198c9de560dSAlex Tomas 			}
2199c9de560dSAlex Tomas 
2200c9de560dSAlex Tomas 			ac->ac_groups_scanned++;
220140ae3487STheodore Ts'o 			if (cr == 0 && ac->ac_2order < sb->s_blocksize_bits+2)
2202c9de560dSAlex Tomas 				ext4_mb_simple_scan_group(ac, &e4b);
2203506bf2d8SEric Sandeen 			else if (cr == 1 && sbi->s_stripe &&
2204506bf2d8SEric Sandeen 					!(ac->ac_g_ex.fe_len % sbi->s_stripe))
2205c9de560dSAlex Tomas 				ext4_mb_scan_aligned(ac, &e4b);
2206c9de560dSAlex Tomas 			else
2207c9de560dSAlex Tomas 				ext4_mb_complex_scan_group(ac, &e4b);
2208c9de560dSAlex Tomas 
2209c9de560dSAlex Tomas 			ext4_unlock_group(sb, group);
2210e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
2211c9de560dSAlex Tomas 
2212c9de560dSAlex Tomas 			if (ac->ac_status != AC_STATUS_CONTINUE)
2213c9de560dSAlex Tomas 				break;
2214c9de560dSAlex Tomas 		}
2215c9de560dSAlex Tomas 	}
2216c9de560dSAlex Tomas 
2217c9de560dSAlex Tomas 	if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2218c9de560dSAlex Tomas 	    !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2219c9de560dSAlex Tomas 		/*
2220c9de560dSAlex Tomas 		 * We've been searching too long. Let's try to allocate
2221c9de560dSAlex Tomas 		 * the best chunk we've found so far
2222c9de560dSAlex Tomas 		 */
2223c9de560dSAlex Tomas 
2224c9de560dSAlex Tomas 		ext4_mb_try_best_found(ac, &e4b);
2225c9de560dSAlex Tomas 		if (ac->ac_status != AC_STATUS_FOUND) {
2226c9de560dSAlex Tomas 			/*
2227c9de560dSAlex Tomas 			 * Someone more lucky has already allocated it.
2228c9de560dSAlex Tomas 			 * The only thing we can do is just take first
2229c9de560dSAlex Tomas 			 * found block(s)
2230c9de560dSAlex Tomas 			printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2231c9de560dSAlex Tomas 			 */
2232c9de560dSAlex Tomas 			ac->ac_b_ex.fe_group = 0;
2233c9de560dSAlex Tomas 			ac->ac_b_ex.fe_start = 0;
2234c9de560dSAlex Tomas 			ac->ac_b_ex.fe_len = 0;
2235c9de560dSAlex Tomas 			ac->ac_status = AC_STATUS_CONTINUE;
2236c9de560dSAlex Tomas 			ac->ac_flags |= EXT4_MB_HINT_FIRST;
2237c9de560dSAlex Tomas 			cr = 3;
2238c9de560dSAlex Tomas 			atomic_inc(&sbi->s_mb_lost_chunks);
2239c9de560dSAlex Tomas 			goto repeat;
2240c9de560dSAlex Tomas 		}
2241c9de560dSAlex Tomas 	}
2242c9de560dSAlex Tomas out:
224342ac1848SLukas Czerner 	if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
224442ac1848SLukas Czerner 		err = first_err;
2245c9de560dSAlex Tomas 	return err;
2246c9de560dSAlex Tomas }
2247c9de560dSAlex Tomas 
2248c9de560dSAlex Tomas static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2249c9de560dSAlex Tomas {
2250c9de560dSAlex Tomas 	struct super_block *sb = seq->private;
2251c9de560dSAlex Tomas 	ext4_group_t group;
2252c9de560dSAlex Tomas 
22538df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2254c9de560dSAlex Tomas 		return NULL;
2255c9de560dSAlex Tomas 	group = *pos + 1;
2256a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
2257c9de560dSAlex Tomas }
2258c9de560dSAlex Tomas 
2259c9de560dSAlex Tomas static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2260c9de560dSAlex Tomas {
2261c9de560dSAlex Tomas 	struct super_block *sb = seq->private;
2262c9de560dSAlex Tomas 	ext4_group_t group;
2263c9de560dSAlex Tomas 
2264c9de560dSAlex Tomas 	++*pos;
22658df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2266c9de560dSAlex Tomas 		return NULL;
2267c9de560dSAlex Tomas 	group = *pos + 1;
2268a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
2269c9de560dSAlex Tomas }
2270c9de560dSAlex Tomas 
2271c9de560dSAlex Tomas static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2272c9de560dSAlex Tomas {
2273c9de560dSAlex Tomas 	struct super_block *sb = seq->private;
2274a9df9a49STheodore Ts'o 	ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2275c9de560dSAlex Tomas 	int i;
22761c8457caSAditya Kali 	int err, buddy_loaded = 0;
2277c9de560dSAlex Tomas 	struct ext4_buddy e4b;
22781c8457caSAditya Kali 	struct ext4_group_info *grinfo;
2279c9de560dSAlex Tomas 	struct sg {
2280c9de560dSAlex Tomas 		struct ext4_group_info info;
2281a36b4498SEric Sandeen 		ext4_grpblk_t counters[16];
2282c9de560dSAlex Tomas 	} sg;
2283c9de560dSAlex Tomas 
2284c9de560dSAlex Tomas 	group--;
2285c9de560dSAlex Tomas 	if (group == 0)
228697b4af2fSRasmus Villemoes 		seq_puts(seq, "#group: free  frags first ["
228797b4af2fSRasmus Villemoes 			      " 2^0   2^1   2^2   2^3   2^4   2^5   2^6  "
2288802cf1f9SHuaitong Han 			      " 2^7   2^8   2^9   2^10  2^11  2^12  2^13  ]\n");
2289c9de560dSAlex Tomas 
2290c9de560dSAlex Tomas 	i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2291c9de560dSAlex Tomas 		sizeof(struct ext4_group_info);
22921c8457caSAditya Kali 	grinfo = ext4_get_group_info(sb, group);
22931c8457caSAditya Kali 	/* Load the group info in memory only if not already loaded. */
22941c8457caSAditya Kali 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
2295c9de560dSAlex Tomas 		err = ext4_mb_load_buddy(sb, group, &e4b);
2296c9de560dSAlex Tomas 		if (err) {
2297a9df9a49STheodore Ts'o 			seq_printf(seq, "#%-5u: I/O error\n", group);
2298c9de560dSAlex Tomas 			return 0;
2299c9de560dSAlex Tomas 		}
23001c8457caSAditya Kali 		buddy_loaded = 1;
23011c8457caSAditya Kali 	}
23021c8457caSAditya Kali 
2303c9de560dSAlex Tomas 	memcpy(&sg, ext4_get_group_info(sb, group), i);
23041c8457caSAditya Kali 
23051c8457caSAditya Kali 	if (buddy_loaded)
2306e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
2307c9de560dSAlex Tomas 
2308a9df9a49STheodore Ts'o 	seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2309c9de560dSAlex Tomas 			sg.info.bb_fragments, sg.info.bb_first_free);
2310c9de560dSAlex Tomas 	for (i = 0; i <= 13; i++)
2311c9de560dSAlex Tomas 		seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2312c9de560dSAlex Tomas 				sg.info.bb_counters[i] : 0);
2313c9de560dSAlex Tomas 	seq_printf(seq, " ]\n");
2314c9de560dSAlex Tomas 
2315c9de560dSAlex Tomas 	return 0;
2316c9de560dSAlex Tomas }
2317c9de560dSAlex Tomas 
2318c9de560dSAlex Tomas static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2319c9de560dSAlex Tomas {
2320c9de560dSAlex Tomas }
2321c9de560dSAlex Tomas 
23227f1346a9STobias Klauser static const struct seq_operations ext4_mb_seq_groups_ops = {
2323c9de560dSAlex Tomas 	.start  = ext4_mb_seq_groups_start,
2324c9de560dSAlex Tomas 	.next   = ext4_mb_seq_groups_next,
2325c9de560dSAlex Tomas 	.stop   = ext4_mb_seq_groups_stop,
2326c9de560dSAlex Tomas 	.show   = ext4_mb_seq_groups_show,
2327c9de560dSAlex Tomas };
2328c9de560dSAlex Tomas 
2329c9de560dSAlex Tomas static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2330c9de560dSAlex Tomas {
2331d9dda78bSAl Viro 	struct super_block *sb = PDE_DATA(inode);
2332c9de560dSAlex Tomas 	int rc;
2333c9de560dSAlex Tomas 
2334c9de560dSAlex Tomas 	rc = seq_open(file, &ext4_mb_seq_groups_ops);
2335c9de560dSAlex Tomas 	if (rc == 0) {
2336a271fe85SJoe Perches 		struct seq_file *m = file->private_data;
2337c9de560dSAlex Tomas 		m->private = sb;
2338c9de560dSAlex Tomas 	}
2339c9de560dSAlex Tomas 	return rc;
2340c9de560dSAlex Tomas 
2341c9de560dSAlex Tomas }
2342c9de560dSAlex Tomas 
2343ebd173beSTheodore Ts'o const struct file_operations ext4_seq_mb_groups_fops = {
2344c9de560dSAlex Tomas 	.owner		= THIS_MODULE,
2345c9de560dSAlex Tomas 	.open		= ext4_mb_seq_groups_open,
2346c9de560dSAlex Tomas 	.read		= seq_read,
2347c9de560dSAlex Tomas 	.llseek		= seq_lseek,
2348c9de560dSAlex Tomas 	.release	= seq_release,
2349c9de560dSAlex Tomas };
2350c9de560dSAlex Tomas 
2351fb1813f4SCurt Wohlgemuth static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2352fb1813f4SCurt Wohlgemuth {
2353fb1813f4SCurt Wohlgemuth 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2354fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2355fb1813f4SCurt Wohlgemuth 
2356fb1813f4SCurt Wohlgemuth 	BUG_ON(!cachep);
2357fb1813f4SCurt Wohlgemuth 	return cachep;
2358fb1813f4SCurt Wohlgemuth }
23595f21b0e6SFrederic Bohe 
236028623c2fSTheodore Ts'o /*
236128623c2fSTheodore Ts'o  * Allocate the top-level s_group_info array for the specified number
236228623c2fSTheodore Ts'o  * of groups
236328623c2fSTheodore Ts'o  */
236428623c2fSTheodore Ts'o int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
236528623c2fSTheodore Ts'o {
236628623c2fSTheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(sb);
236728623c2fSTheodore Ts'o 	unsigned size;
236828623c2fSTheodore Ts'o 	struct ext4_group_info ***new_groupinfo;
236928623c2fSTheodore Ts'o 
237028623c2fSTheodore Ts'o 	size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
237128623c2fSTheodore Ts'o 		EXT4_DESC_PER_BLOCK_BITS(sb);
237228623c2fSTheodore Ts'o 	if (size <= sbi->s_group_info_size)
237328623c2fSTheodore Ts'o 		return 0;
237428623c2fSTheodore Ts'o 
237528623c2fSTheodore Ts'o 	size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
237628623c2fSTheodore Ts'o 	new_groupinfo = ext4_kvzalloc(size, GFP_KERNEL);
237728623c2fSTheodore Ts'o 	if (!new_groupinfo) {
237828623c2fSTheodore Ts'o 		ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
237928623c2fSTheodore Ts'o 		return -ENOMEM;
238028623c2fSTheodore Ts'o 	}
238128623c2fSTheodore Ts'o 	if (sbi->s_group_info) {
238228623c2fSTheodore Ts'o 		memcpy(new_groupinfo, sbi->s_group_info,
238328623c2fSTheodore Ts'o 		       sbi->s_group_info_size * sizeof(*sbi->s_group_info));
2384b93b41d4SAl Viro 		kvfree(sbi->s_group_info);
238528623c2fSTheodore Ts'o 	}
238628623c2fSTheodore Ts'o 	sbi->s_group_info = new_groupinfo;
238728623c2fSTheodore Ts'o 	sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
238828623c2fSTheodore Ts'o 	ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
238928623c2fSTheodore Ts'o 		   sbi->s_group_info_size);
239028623c2fSTheodore Ts'o 	return 0;
239128623c2fSTheodore Ts'o }
239228623c2fSTheodore Ts'o 
23935f21b0e6SFrederic Bohe /* Create and initialize ext4_group_info data for the given group. */
2394920313a7SAneesh Kumar K.V int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
23955f21b0e6SFrederic Bohe 			  struct ext4_group_desc *desc)
23965f21b0e6SFrederic Bohe {
2397fb1813f4SCurt Wohlgemuth 	int i;
23985f21b0e6SFrederic Bohe 	int metalen = 0;
23995f21b0e6SFrederic Bohe 	struct ext4_sb_info *sbi = EXT4_SB(sb);
24005f21b0e6SFrederic Bohe 	struct ext4_group_info **meta_group_info;
2401fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
24025f21b0e6SFrederic Bohe 
24035f21b0e6SFrederic Bohe 	/*
24045f21b0e6SFrederic Bohe 	 * First check if this group is the first of a reserved block.
24055f21b0e6SFrederic Bohe 	 * If it's true, we have to allocate a new table of pointers
24065f21b0e6SFrederic Bohe 	 * to ext4_group_info structures
24075f21b0e6SFrederic Bohe 	 */
24085f21b0e6SFrederic Bohe 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
24095f21b0e6SFrederic Bohe 		metalen = sizeof(*meta_group_info) <<
24105f21b0e6SFrederic Bohe 			EXT4_DESC_PER_BLOCK_BITS(sb);
24114fdb5543SDmitry Monakhov 		meta_group_info = kmalloc(metalen, GFP_NOFS);
24125f21b0e6SFrederic Bohe 		if (meta_group_info == NULL) {
24137f6a11e7SJoe Perches 			ext4_msg(sb, KERN_ERR, "can't allocate mem "
24149d8b9ec4STheodore Ts'o 				 "for a buddy group");
24155f21b0e6SFrederic Bohe 			goto exit_meta_group_info;
24165f21b0e6SFrederic Bohe 		}
24175f21b0e6SFrederic Bohe 		sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] =
24185f21b0e6SFrederic Bohe 			meta_group_info;
24195f21b0e6SFrederic Bohe 	}
24205f21b0e6SFrederic Bohe 
24215f21b0e6SFrederic Bohe 	meta_group_info =
24225f21b0e6SFrederic Bohe 		sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)];
24235f21b0e6SFrederic Bohe 	i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
24245f21b0e6SFrederic Bohe 
24254fdb5543SDmitry Monakhov 	meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
24265f21b0e6SFrederic Bohe 	if (meta_group_info[i] == NULL) {
24277f6a11e7SJoe Perches 		ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
24285f21b0e6SFrederic Bohe 		goto exit_group_info;
24295f21b0e6SFrederic Bohe 	}
24305f21b0e6SFrederic Bohe 	set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
24315f21b0e6SFrederic Bohe 		&(meta_group_info[i]->bb_state));
24325f21b0e6SFrederic Bohe 
24335f21b0e6SFrederic Bohe 	/*
24345f21b0e6SFrederic Bohe 	 * initialize bb_free to be able to skip
24355f21b0e6SFrederic Bohe 	 * empty groups without initialization
24365f21b0e6SFrederic Bohe 	 */
24375f21b0e6SFrederic Bohe 	if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
24385f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
2439cff1dfd7STheodore Ts'o 			ext4_free_clusters_after_init(sb, group, desc);
24405f21b0e6SFrederic Bohe 	} else {
24415f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
2442021b65bbSTheodore Ts'o 			ext4_free_group_clusters(sb, desc);
24435f21b0e6SFrederic Bohe 	}
24445f21b0e6SFrederic Bohe 
24455f21b0e6SFrederic Bohe 	INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2446920313a7SAneesh Kumar K.V 	init_rwsem(&meta_group_info[i]->alloc_sem);
244764e290ecSVenkatesh Pallipadi 	meta_group_info[i]->bb_free_root = RB_ROOT;
24488a57d9d6SCurt Wohlgemuth 	meta_group_info[i]->bb_largest_free_order = -1;  /* uninit */
24495f21b0e6SFrederic Bohe 
24505f21b0e6SFrederic Bohe #ifdef DOUBLE_CHECK
24515f21b0e6SFrederic Bohe 	{
24525f21b0e6SFrederic Bohe 		struct buffer_head *bh;
24535f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_bitmap =
24544fdb5543SDmitry Monakhov 			kmalloc(sb->s_blocksize, GFP_NOFS);
24555f21b0e6SFrederic Bohe 		BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
24565f21b0e6SFrederic Bohe 		bh = ext4_read_block_bitmap(sb, group);
24579008a58eSDarrick J. Wong 		BUG_ON(IS_ERR_OR_NULL(bh));
24585f21b0e6SFrederic Bohe 		memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
24595f21b0e6SFrederic Bohe 			sb->s_blocksize);
24605f21b0e6SFrederic Bohe 		put_bh(bh);
24615f21b0e6SFrederic Bohe 	}
24625f21b0e6SFrederic Bohe #endif
24635f21b0e6SFrederic Bohe 
24645f21b0e6SFrederic Bohe 	return 0;
24655f21b0e6SFrederic Bohe 
24665f21b0e6SFrederic Bohe exit_group_info:
24675f21b0e6SFrederic Bohe 	/* If a meta_group_info table has been allocated, release it now */
2468caaf7a29STao Ma 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
24695f21b0e6SFrederic Bohe 		kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
2470caaf7a29STao Ma 		sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] = NULL;
2471caaf7a29STao Ma 	}
24725f21b0e6SFrederic Bohe exit_meta_group_info:
24735f21b0e6SFrederic Bohe 	return -ENOMEM;
24745f21b0e6SFrederic Bohe } /* ext4_mb_add_groupinfo */
24755f21b0e6SFrederic Bohe 
2476c9de560dSAlex Tomas static int ext4_mb_init_backend(struct super_block *sb)
2477c9de560dSAlex Tomas {
24788df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
2479c9de560dSAlex Tomas 	ext4_group_t i;
2480c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
248128623c2fSTheodore Ts'o 	int err;
24825f21b0e6SFrederic Bohe 	struct ext4_group_desc *desc;
2483fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep;
2484c9de560dSAlex Tomas 
248528623c2fSTheodore Ts'o 	err = ext4_mb_alloc_groupinfo(sb, ngroups);
248628623c2fSTheodore Ts'o 	if (err)
248728623c2fSTheodore Ts'o 		return err;
24885f21b0e6SFrederic Bohe 
2489c9de560dSAlex Tomas 	sbi->s_buddy_cache = new_inode(sb);
2490c9de560dSAlex Tomas 	if (sbi->s_buddy_cache == NULL) {
24919d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_ERR, "can't get new inode");
2492c9de560dSAlex Tomas 		goto err_freesgi;
2493c9de560dSAlex Tomas 	}
249448e6061bSYu Jian 	/* To avoid potentially colliding with an valid on-disk inode number,
249548e6061bSYu Jian 	 * use EXT4_BAD_INO for the buddy cache inode number.  This inode is
249648e6061bSYu Jian 	 * not in the inode hash, so it should never be found by iget(), but
249748e6061bSYu Jian 	 * this will avoid confusion if it ever shows up during debugging. */
249848e6061bSYu Jian 	sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
2499c9de560dSAlex Tomas 	EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
25008df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
2501c9de560dSAlex Tomas 		desc = ext4_get_group_desc(sb, i, NULL);
2502c9de560dSAlex Tomas 		if (desc == NULL) {
25039d8b9ec4STheodore Ts'o 			ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2504c9de560dSAlex Tomas 			goto err_freebuddy;
2505c9de560dSAlex Tomas 		}
25065f21b0e6SFrederic Bohe 		if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
25075f21b0e6SFrederic Bohe 			goto err_freebuddy;
2508c9de560dSAlex Tomas 	}
2509c9de560dSAlex Tomas 
2510c9de560dSAlex Tomas 	return 0;
2511c9de560dSAlex Tomas 
2512c9de560dSAlex Tomas err_freebuddy:
2513fb1813f4SCurt Wohlgemuth 	cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2514f1fa3342SRoel Kluin 	while (i-- > 0)
2515fb1813f4SCurt Wohlgemuth 		kmem_cache_free(cachep, ext4_get_group_info(sb, i));
251628623c2fSTheodore Ts'o 	i = sbi->s_group_info_size;
2517f1fa3342SRoel Kluin 	while (i-- > 0)
2518c9de560dSAlex Tomas 		kfree(sbi->s_group_info[i]);
2519c9de560dSAlex Tomas 	iput(sbi->s_buddy_cache);
2520c9de560dSAlex Tomas err_freesgi:
2521b93b41d4SAl Viro 	kvfree(sbi->s_group_info);
2522c9de560dSAlex Tomas 	return -ENOMEM;
2523c9de560dSAlex Tomas }
2524c9de560dSAlex Tomas 
25252892c15dSEric Sandeen static void ext4_groupinfo_destroy_slabs(void)
25262892c15dSEric Sandeen {
25272892c15dSEric Sandeen 	int i;
25282892c15dSEric Sandeen 
25292892c15dSEric Sandeen 	for (i = 0; i < NR_GRPINFO_CACHES; i++) {
25302892c15dSEric Sandeen 		if (ext4_groupinfo_caches[i])
25312892c15dSEric Sandeen 			kmem_cache_destroy(ext4_groupinfo_caches[i]);
25322892c15dSEric Sandeen 		ext4_groupinfo_caches[i] = NULL;
25332892c15dSEric Sandeen 	}
25342892c15dSEric Sandeen }
25352892c15dSEric Sandeen 
25362892c15dSEric Sandeen static int ext4_groupinfo_create_slab(size_t size)
25372892c15dSEric Sandeen {
25382892c15dSEric Sandeen 	static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
25392892c15dSEric Sandeen 	int slab_size;
25402892c15dSEric Sandeen 	int blocksize_bits = order_base_2(size);
25412892c15dSEric Sandeen 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
25422892c15dSEric Sandeen 	struct kmem_cache *cachep;
25432892c15dSEric Sandeen 
25442892c15dSEric Sandeen 	if (cache_index >= NR_GRPINFO_CACHES)
25452892c15dSEric Sandeen 		return -EINVAL;
25462892c15dSEric Sandeen 
25472892c15dSEric Sandeen 	if (unlikely(cache_index < 0))
25482892c15dSEric Sandeen 		cache_index = 0;
25492892c15dSEric Sandeen 
25502892c15dSEric Sandeen 	mutex_lock(&ext4_grpinfo_slab_create_mutex);
25512892c15dSEric Sandeen 	if (ext4_groupinfo_caches[cache_index]) {
25522892c15dSEric Sandeen 		mutex_unlock(&ext4_grpinfo_slab_create_mutex);
25532892c15dSEric Sandeen 		return 0;	/* Already created */
25542892c15dSEric Sandeen 	}
25552892c15dSEric Sandeen 
25562892c15dSEric Sandeen 	slab_size = offsetof(struct ext4_group_info,
25572892c15dSEric Sandeen 				bb_counters[blocksize_bits + 2]);
25582892c15dSEric Sandeen 
25592892c15dSEric Sandeen 	cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
25602892c15dSEric Sandeen 					slab_size, 0, SLAB_RECLAIM_ACCOUNT,
25612892c15dSEric Sandeen 					NULL);
25622892c15dSEric Sandeen 
2563823ba01fSTao Ma 	ext4_groupinfo_caches[cache_index] = cachep;
2564823ba01fSTao Ma 
25652892c15dSEric Sandeen 	mutex_unlock(&ext4_grpinfo_slab_create_mutex);
25662892c15dSEric Sandeen 	if (!cachep) {
25679d8b9ec4STheodore Ts'o 		printk(KERN_EMERG
25689d8b9ec4STheodore Ts'o 		       "EXT4-fs: no memory for groupinfo slab cache\n");
25692892c15dSEric Sandeen 		return -ENOMEM;
25702892c15dSEric Sandeen 	}
25712892c15dSEric Sandeen 
25722892c15dSEric Sandeen 	return 0;
25732892c15dSEric Sandeen }
25742892c15dSEric Sandeen 
25759d99012fSAkira Fujita int ext4_mb_init(struct super_block *sb)
2576c9de560dSAlex Tomas {
2577c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
25786be2ded1SAneesh Kumar K.V 	unsigned i, j;
2579c9de560dSAlex Tomas 	unsigned offset;
2580c9de560dSAlex Tomas 	unsigned max;
258174767c5aSShen Feng 	int ret;
2582c9de560dSAlex Tomas 
25831927805eSEric Sandeen 	i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2584c9de560dSAlex Tomas 
2585c9de560dSAlex Tomas 	sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2586c9de560dSAlex Tomas 	if (sbi->s_mb_offsets == NULL) {
2587fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
2588fb1813f4SCurt Wohlgemuth 		goto out;
2589c9de560dSAlex Tomas 	}
2590ff7ef329SYasunori Goto 
25911927805eSEric Sandeen 	i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2592c9de560dSAlex Tomas 	sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2593c9de560dSAlex Tomas 	if (sbi->s_mb_maxs == NULL) {
2594fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
2595fb1813f4SCurt Wohlgemuth 		goto out;
2596fb1813f4SCurt Wohlgemuth 	}
2597fb1813f4SCurt Wohlgemuth 
25982892c15dSEric Sandeen 	ret = ext4_groupinfo_create_slab(sb->s_blocksize);
25992892c15dSEric Sandeen 	if (ret < 0)
2600fb1813f4SCurt Wohlgemuth 		goto out;
2601c9de560dSAlex Tomas 
2602c9de560dSAlex Tomas 	/* order 0 is regular bitmap */
2603c9de560dSAlex Tomas 	sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2604c9de560dSAlex Tomas 	sbi->s_mb_offsets[0] = 0;
2605c9de560dSAlex Tomas 
2606c9de560dSAlex Tomas 	i = 1;
2607c9de560dSAlex Tomas 	offset = 0;
2608c9de560dSAlex Tomas 	max = sb->s_blocksize << 2;
2609c9de560dSAlex Tomas 	do {
2610c9de560dSAlex Tomas 		sbi->s_mb_offsets[i] = offset;
2611c9de560dSAlex Tomas 		sbi->s_mb_maxs[i] = max;
2612c9de560dSAlex Tomas 		offset += 1 << (sb->s_blocksize_bits - i);
2613c9de560dSAlex Tomas 		max = max >> 1;
2614c9de560dSAlex Tomas 		i++;
2615c9de560dSAlex Tomas 	} while (i <= sb->s_blocksize_bits + 1);
2616c9de560dSAlex Tomas 
2617c9de560dSAlex Tomas 	spin_lock_init(&sbi->s_md_lock);
2618c9de560dSAlex Tomas 	spin_lock_init(&sbi->s_bal_lock);
2619c9de560dSAlex Tomas 
2620c9de560dSAlex Tomas 	sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2621c9de560dSAlex Tomas 	sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2622c9de560dSAlex Tomas 	sbi->s_mb_stats = MB_DEFAULT_STATS;
2623c9de560dSAlex Tomas 	sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2624c9de560dSAlex Tomas 	sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
262527baebb8STheodore Ts'o 	/*
262627baebb8STheodore Ts'o 	 * The default group preallocation is 512, which for 4k block
262727baebb8STheodore Ts'o 	 * sizes translates to 2 megabytes.  However for bigalloc file
262827baebb8STheodore Ts'o 	 * systems, this is probably too big (i.e, if the cluster size
262927baebb8STheodore Ts'o 	 * is 1 megabyte, then group preallocation size becomes half a
263027baebb8STheodore Ts'o 	 * gigabyte!).  As a default, we will keep a two megabyte
263127baebb8STheodore Ts'o 	 * group pralloc size for cluster sizes up to 64k, and after
263227baebb8STheodore Ts'o 	 * that, we will force a minimum group preallocation size of
263327baebb8STheodore Ts'o 	 * 32 clusters.  This translates to 8 megs when the cluster
263427baebb8STheodore Ts'o 	 * size is 256k, and 32 megs when the cluster size is 1 meg,
263527baebb8STheodore Ts'o 	 * which seems reasonable as a default.
263627baebb8STheodore Ts'o 	 */
263727baebb8STheodore Ts'o 	sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
263827baebb8STheodore Ts'o 				       sbi->s_cluster_bits, 32);
2639d7a1fee1SDan Ehrenberg 	/*
2640d7a1fee1SDan Ehrenberg 	 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
2641d7a1fee1SDan Ehrenberg 	 * to the lowest multiple of s_stripe which is bigger than
2642d7a1fee1SDan Ehrenberg 	 * the s_mb_group_prealloc as determined above. We want
2643d7a1fee1SDan Ehrenberg 	 * the preallocation size to be an exact multiple of the
2644d7a1fee1SDan Ehrenberg 	 * RAID stripe size so that preallocations don't fragment
2645d7a1fee1SDan Ehrenberg 	 * the stripes.
2646d7a1fee1SDan Ehrenberg 	 */
2647d7a1fee1SDan Ehrenberg 	if (sbi->s_stripe > 1) {
2648d7a1fee1SDan Ehrenberg 		sbi->s_mb_group_prealloc = roundup(
2649d7a1fee1SDan Ehrenberg 			sbi->s_mb_group_prealloc, sbi->s_stripe);
2650d7a1fee1SDan Ehrenberg 	}
2651c9de560dSAlex Tomas 
2652730c213cSEric Sandeen 	sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2653c9de560dSAlex Tomas 	if (sbi->s_locality_groups == NULL) {
2654fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
2655029b10c5SAndrey Tsyvarev 		goto out;
2656c9de560dSAlex Tomas 	}
2657730c213cSEric Sandeen 	for_each_possible_cpu(i) {
2658c9de560dSAlex Tomas 		struct ext4_locality_group *lg;
2659730c213cSEric Sandeen 		lg = per_cpu_ptr(sbi->s_locality_groups, i);
2660c9de560dSAlex Tomas 		mutex_init(&lg->lg_mutex);
26616be2ded1SAneesh Kumar K.V 		for (j = 0; j < PREALLOC_TB_SIZE; j++)
26626be2ded1SAneesh Kumar K.V 			INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2663c9de560dSAlex Tomas 		spin_lock_init(&lg->lg_prealloc_lock);
2664c9de560dSAlex Tomas 	}
2665c9de560dSAlex Tomas 
266679a77c5aSYu Jian 	/* init file for buddy data */
266779a77c5aSYu Jian 	ret = ext4_mb_init_backend(sb);
26687aa0baeaSTao Ma 	if (ret != 0)
26697aa0baeaSTao Ma 		goto out_free_locality_groups;
267079a77c5aSYu Jian 
26717aa0baeaSTao Ma 	return 0;
26727aa0baeaSTao Ma 
26737aa0baeaSTao Ma out_free_locality_groups:
26747aa0baeaSTao Ma 	free_percpu(sbi->s_locality_groups);
26757aa0baeaSTao Ma 	sbi->s_locality_groups = NULL;
2676fb1813f4SCurt Wohlgemuth out:
2677fb1813f4SCurt Wohlgemuth 	kfree(sbi->s_mb_offsets);
26787aa0baeaSTao Ma 	sbi->s_mb_offsets = NULL;
2679fb1813f4SCurt Wohlgemuth 	kfree(sbi->s_mb_maxs);
26807aa0baeaSTao Ma 	sbi->s_mb_maxs = NULL;
2681fb1813f4SCurt Wohlgemuth 	return ret;
2682c9de560dSAlex Tomas }
2683c9de560dSAlex Tomas 
2684955ce5f5SAneesh Kumar K.V /* need to called with the ext4 group lock held */
2685c9de560dSAlex Tomas static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2686c9de560dSAlex Tomas {
2687c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
2688c9de560dSAlex Tomas 	struct list_head *cur, *tmp;
2689c9de560dSAlex Tomas 	int count = 0;
2690c9de560dSAlex Tomas 
2691c9de560dSAlex Tomas 	list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2692c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2693c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
2694c9de560dSAlex Tomas 		count++;
2695688f05a0SAneesh Kumar K.V 		kmem_cache_free(ext4_pspace_cachep, pa);
2696c9de560dSAlex Tomas 	}
2697c9de560dSAlex Tomas 	if (count)
26986ba495e9STheodore Ts'o 		mb_debug(1, "mballoc: %u PAs left\n", count);
2699c9de560dSAlex Tomas 
2700c9de560dSAlex Tomas }
2701c9de560dSAlex Tomas 
2702c9de560dSAlex Tomas int ext4_mb_release(struct super_block *sb)
2703c9de560dSAlex Tomas {
27048df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
2705c9de560dSAlex Tomas 	ext4_group_t i;
2706c9de560dSAlex Tomas 	int num_meta_group_infos;
2707c9de560dSAlex Tomas 	struct ext4_group_info *grinfo;
2708c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2709fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2710c9de560dSAlex Tomas 
2711c9de560dSAlex Tomas 	if (sbi->s_group_info) {
27128df9675fSTheodore Ts'o 		for (i = 0; i < ngroups; i++) {
2713c9de560dSAlex Tomas 			grinfo = ext4_get_group_info(sb, i);
2714c9de560dSAlex Tomas #ifdef DOUBLE_CHECK
2715c9de560dSAlex Tomas 			kfree(grinfo->bb_bitmap);
2716c9de560dSAlex Tomas #endif
2717c9de560dSAlex Tomas 			ext4_lock_group(sb, i);
2718c9de560dSAlex Tomas 			ext4_mb_cleanup_pa(grinfo);
2719c9de560dSAlex Tomas 			ext4_unlock_group(sb, i);
2720fb1813f4SCurt Wohlgemuth 			kmem_cache_free(cachep, grinfo);
2721c9de560dSAlex Tomas 		}
27228df9675fSTheodore Ts'o 		num_meta_group_infos = (ngroups +
2723c9de560dSAlex Tomas 				EXT4_DESC_PER_BLOCK(sb) - 1) >>
2724c9de560dSAlex Tomas 			EXT4_DESC_PER_BLOCK_BITS(sb);
2725c9de560dSAlex Tomas 		for (i = 0; i < num_meta_group_infos; i++)
2726c9de560dSAlex Tomas 			kfree(sbi->s_group_info[i]);
2727b93b41d4SAl Viro 		kvfree(sbi->s_group_info);
2728c9de560dSAlex Tomas 	}
2729c9de560dSAlex Tomas 	kfree(sbi->s_mb_offsets);
2730c9de560dSAlex Tomas 	kfree(sbi->s_mb_maxs);
2731c9de560dSAlex Tomas 	iput(sbi->s_buddy_cache);
2732c9de560dSAlex Tomas 	if (sbi->s_mb_stats) {
27339d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
27349d8b9ec4STheodore Ts'o 		       "mballoc: %u blocks %u reqs (%u success)",
2735c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_allocated),
2736c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_reqs),
2737c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_success));
27389d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
27399d8b9ec4STheodore Ts'o 		      "mballoc: %u extents scanned, %u goal hits, "
27409d8b9ec4STheodore Ts'o 				"%u 2^N hits, %u breaks, %u lost",
2741c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_ex_scanned),
2742c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_goals),
2743c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_2orders),
2744c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_breaks),
2745c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_lost_chunks));
27469d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
27479d8b9ec4STheodore Ts'o 		       "mballoc: %lu generated and it took %Lu",
2748ced156e4STao Ma 				sbi->s_mb_buddies_generated,
2749c9de560dSAlex Tomas 				sbi->s_mb_generation_time);
27509d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
27519d8b9ec4STheodore Ts'o 		       "mballoc: %u preallocated, %u discarded",
2752c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_preallocated),
2753c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_discarded));
2754c9de560dSAlex Tomas 	}
2755c9de560dSAlex Tomas 
2756730c213cSEric Sandeen 	free_percpu(sbi->s_locality_groups);
2757c9de560dSAlex Tomas 
2758c9de560dSAlex Tomas 	return 0;
2759c9de560dSAlex Tomas }
2760c9de560dSAlex Tomas 
276177ca6cdfSLukas Czerner static inline int ext4_issue_discard(struct super_block *sb,
276284130193STheodore Ts'o 		ext4_group_t block_group, ext4_grpblk_t cluster, int count)
27635c521830SJiaying Zhang {
27645c521830SJiaying Zhang 	ext4_fsblk_t discard_block;
27655c521830SJiaying Zhang 
276684130193STheodore Ts'o 	discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
276784130193STheodore Ts'o 			 ext4_group_first_block_no(sb, block_group));
276884130193STheodore Ts'o 	count = EXT4_C2B(EXT4_SB(sb), count);
27695c521830SJiaying Zhang 	trace_ext4_discard_blocks(sb,
27705c521830SJiaying Zhang 			(unsigned long long) discard_block, count);
277193259636SLukas Czerner 	return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
27725c521830SJiaying Zhang }
27735c521830SJiaying Zhang 
27743e624fc7STheodore Ts'o /*
27753e624fc7STheodore Ts'o  * This function is called by the jbd2 layer once the commit has finished,
27763e624fc7STheodore Ts'o  * so we know we can free the blocks that were released with that commit.
27773e624fc7STheodore Ts'o  */
277818aadd47SBobi Jam static void ext4_free_data_callback(struct super_block *sb,
277918aadd47SBobi Jam 				    struct ext4_journal_cb_entry *jce,
278018aadd47SBobi Jam 				    int rc)
2781c9de560dSAlex Tomas {
278218aadd47SBobi Jam 	struct ext4_free_data *entry = (struct ext4_free_data *)jce;
2783c9de560dSAlex Tomas 	struct ext4_buddy e4b;
2784c894058dSAneesh Kumar K.V 	struct ext4_group_info *db;
2785d9f34504STheodore Ts'o 	int err, count = 0, count2 = 0;
2786c9de560dSAlex Tomas 
27876ba495e9STheodore Ts'o 	mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
278818aadd47SBobi Jam 		 entry->efd_count, entry->efd_group, entry);
2789c9de560dSAlex Tomas 
2790d71c1ae2SLukas Czerner 	if (test_opt(sb, DISCARD)) {
2791d71c1ae2SLukas Czerner 		err = ext4_issue_discard(sb, entry->efd_group,
2792d71c1ae2SLukas Czerner 					 entry->efd_start_cluster,
2793d71c1ae2SLukas Czerner 					 entry->efd_count);
2794d71c1ae2SLukas Czerner 		if (err && err != -EOPNOTSUPP)
2795d71c1ae2SLukas Czerner 			ext4_msg(sb, KERN_WARNING, "discard request in"
2796d71c1ae2SLukas Czerner 				 " group:%d block:%d count:%d failed"
2797d71c1ae2SLukas Czerner 				 " with %d", entry->efd_group,
2798d71c1ae2SLukas Czerner 				 entry->efd_start_cluster,
2799d71c1ae2SLukas Czerner 				 entry->efd_count, err);
2800d71c1ae2SLukas Czerner 	}
2801b90f6870STheodore Ts'o 
280218aadd47SBobi Jam 	err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
2803c9de560dSAlex Tomas 	/* we expect to find existing buddy because it's pinned */
2804c9de560dSAlex Tomas 	BUG_ON(err != 0);
2805c9de560dSAlex Tomas 
280618aadd47SBobi Jam 
2807c894058dSAneesh Kumar K.V 	db = e4b.bd_info;
2808c9de560dSAlex Tomas 	/* there are blocks to put in buddy to make them really free */
280918aadd47SBobi Jam 	count += entry->efd_count;
2810c9de560dSAlex Tomas 	count2++;
281118aadd47SBobi Jam 	ext4_lock_group(sb, entry->efd_group);
2812c894058dSAneesh Kumar K.V 	/* Take it out of per group rb tree */
281318aadd47SBobi Jam 	rb_erase(&entry->efd_node, &(db->bb_free_root));
281418aadd47SBobi Jam 	mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
2815c9de560dSAlex Tomas 
28163d56b8d2STao Ma 	/*
28173d56b8d2STao Ma 	 * Clear the trimmed flag for the group so that the next
28183d56b8d2STao Ma 	 * ext4_trim_fs can trim it.
28193d56b8d2STao Ma 	 * If the volume is mounted with -o discard, online discard
28203d56b8d2STao Ma 	 * is supported and the free blocks will be trimmed online.
28213d56b8d2STao Ma 	 */
28223d56b8d2STao Ma 	if (!test_opt(sb, DISCARD))
28233d56b8d2STao Ma 		EXT4_MB_GRP_CLEAR_TRIMMED(db);
28243d56b8d2STao Ma 
2825c894058dSAneesh Kumar K.V 	if (!db->bb_free_root.rb_node) {
2826c894058dSAneesh Kumar K.V 		/* No more items in the per group rb tree
2827c894058dSAneesh Kumar K.V 		 * balance refcounts from ext4_mb_free_metadata()
2828c894058dSAneesh Kumar K.V 		 */
2829c9de560dSAlex Tomas 		page_cache_release(e4b.bd_buddy_page);
2830c9de560dSAlex Tomas 		page_cache_release(e4b.bd_bitmap_page);
2831c894058dSAneesh Kumar K.V 	}
283218aadd47SBobi Jam 	ext4_unlock_group(sb, entry->efd_group);
283318aadd47SBobi Jam 	kmem_cache_free(ext4_free_data_cachep, entry);
2834e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
2835c9de560dSAlex Tomas 
28366ba495e9STheodore Ts'o 	mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2837c9de560dSAlex Tomas }
2838c9de560dSAlex Tomas 
28395dabfc78STheodore Ts'o int __init ext4_init_mballoc(void)
2840c9de560dSAlex Tomas {
284116828088STheodore Ts'o 	ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
284216828088STheodore Ts'o 					SLAB_RECLAIM_ACCOUNT);
2843c9de560dSAlex Tomas 	if (ext4_pspace_cachep == NULL)
2844c9de560dSAlex Tomas 		return -ENOMEM;
2845c9de560dSAlex Tomas 
284616828088STheodore Ts'o 	ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
284716828088STheodore Ts'o 				    SLAB_RECLAIM_ACCOUNT);
2848256bdb49SEric Sandeen 	if (ext4_ac_cachep == NULL) {
2849256bdb49SEric Sandeen 		kmem_cache_destroy(ext4_pspace_cachep);
2850256bdb49SEric Sandeen 		return -ENOMEM;
2851256bdb49SEric Sandeen 	}
2852c894058dSAneesh Kumar K.V 
285318aadd47SBobi Jam 	ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
285416828088STheodore Ts'o 					   SLAB_RECLAIM_ACCOUNT);
285518aadd47SBobi Jam 	if (ext4_free_data_cachep == NULL) {
2856c894058dSAneesh Kumar K.V 		kmem_cache_destroy(ext4_pspace_cachep);
2857c894058dSAneesh Kumar K.V 		kmem_cache_destroy(ext4_ac_cachep);
2858c894058dSAneesh Kumar K.V 		return -ENOMEM;
2859c894058dSAneesh Kumar K.V 	}
2860c9de560dSAlex Tomas 	return 0;
2861c9de560dSAlex Tomas }
2862c9de560dSAlex Tomas 
28635dabfc78STheodore Ts'o void ext4_exit_mballoc(void)
2864c9de560dSAlex Tomas {
28653e03f9caSJesper Dangaard Brouer 	/*
28663e03f9caSJesper Dangaard Brouer 	 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
28673e03f9caSJesper Dangaard Brouer 	 * before destroying the slab cache.
28683e03f9caSJesper Dangaard Brouer 	 */
28693e03f9caSJesper Dangaard Brouer 	rcu_barrier();
2870c9de560dSAlex Tomas 	kmem_cache_destroy(ext4_pspace_cachep);
2871256bdb49SEric Sandeen 	kmem_cache_destroy(ext4_ac_cachep);
287218aadd47SBobi Jam 	kmem_cache_destroy(ext4_free_data_cachep);
28732892c15dSEric Sandeen 	ext4_groupinfo_destroy_slabs();
2874c9de560dSAlex Tomas }
2875c9de560dSAlex Tomas 
2876c9de560dSAlex Tomas 
2877c9de560dSAlex Tomas /*
287873b2c716SUwe Kleine-König  * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2879c9de560dSAlex Tomas  * Returns 0 if success or error code
2880c9de560dSAlex Tomas  */
28814ddfef7bSEric Sandeen static noinline_for_stack int
28824ddfef7bSEric Sandeen ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
288353accfa9STheodore Ts'o 				handle_t *handle, unsigned int reserv_clstrs)
2884c9de560dSAlex Tomas {
2885c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
2886c9de560dSAlex Tomas 	struct ext4_group_desc *gdp;
2887c9de560dSAlex Tomas 	struct buffer_head *gdp_bh;
2888c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
2889c9de560dSAlex Tomas 	struct super_block *sb;
2890c9de560dSAlex Tomas 	ext4_fsblk_t block;
2891519deca0SAneesh Kumar K.V 	int err, len;
2892c9de560dSAlex Tomas 
2893c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2894c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_len <= 0);
2895c9de560dSAlex Tomas 
2896c9de560dSAlex Tomas 	sb = ac->ac_sb;
2897c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
2898c9de560dSAlex Tomas 
2899574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
29009008a58eSDarrick J. Wong 	if (IS_ERR(bitmap_bh)) {
29019008a58eSDarrick J. Wong 		err = PTR_ERR(bitmap_bh);
29029008a58eSDarrick J. Wong 		bitmap_bh = NULL;
2903c9de560dSAlex Tomas 		goto out_err;
29049008a58eSDarrick J. Wong 	}
2905c9de560dSAlex Tomas 
29065d601255Sliang xie 	BUFFER_TRACE(bitmap_bh, "getting write access");
2907c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, bitmap_bh);
2908c9de560dSAlex Tomas 	if (err)
2909c9de560dSAlex Tomas 		goto out_err;
2910c9de560dSAlex Tomas 
2911c9de560dSAlex Tomas 	err = -EIO;
2912c9de560dSAlex Tomas 	gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2913c9de560dSAlex Tomas 	if (!gdp)
2914c9de560dSAlex Tomas 		goto out_err;
2915c9de560dSAlex Tomas 
2916a9df9a49STheodore Ts'o 	ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
2917021b65bbSTheodore Ts'o 			ext4_free_group_clusters(sb, gdp));
291803cddb80SAneesh Kumar K.V 
29195d601255Sliang xie 	BUFFER_TRACE(gdp_bh, "get_write_access");
2920c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, gdp_bh);
2921c9de560dSAlex Tomas 	if (err)
2922c9de560dSAlex Tomas 		goto out_err;
2923c9de560dSAlex Tomas 
2924bda00de7SAkinobu Mita 	block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
2925c9de560dSAlex Tomas 
292653accfa9STheodore Ts'o 	len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
29276fd058f7STheodore Ts'o 	if (!ext4_data_block_valid(sbi, block, len)) {
292812062dddSEric Sandeen 		ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
29291084f252STheodore Ts'o 			   "fs metadata", block, block+len);
2930519deca0SAneesh Kumar K.V 		/* File system mounted not to panic on error
2931519deca0SAneesh Kumar K.V 		 * Fix the bitmap and repeat the block allocation
2932519deca0SAneesh Kumar K.V 		 * We leak some of the blocks here.
2933519deca0SAneesh Kumar K.V 		 */
2934955ce5f5SAneesh Kumar K.V 		ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2935c3e94d1dSYongqiang Yang 		ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2936519deca0SAneesh Kumar K.V 			      ac->ac_b_ex.fe_len);
2937955ce5f5SAneesh Kumar K.V 		ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
29380390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2939519deca0SAneesh Kumar K.V 		if (!err)
2940519deca0SAneesh Kumar K.V 			err = -EAGAIN;
2941519deca0SAneesh Kumar K.V 		goto out_err;
2942c9de560dSAlex Tomas 	}
2943955ce5f5SAneesh Kumar K.V 
2944955ce5f5SAneesh Kumar K.V 	ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2945c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
2946c9de560dSAlex Tomas 	{
2947c9de560dSAlex Tomas 		int i;
2948c9de560dSAlex Tomas 		for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
2949c9de560dSAlex Tomas 			BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
2950c9de560dSAlex Tomas 						bitmap_bh->b_data));
2951c9de560dSAlex Tomas 		}
2952c9de560dSAlex Tomas 	}
2953c9de560dSAlex Tomas #endif
2954c3e94d1dSYongqiang Yang 	ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2955c3e94d1dSYongqiang Yang 		      ac->ac_b_ex.fe_len);
2956c9de560dSAlex Tomas 	if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2957c9de560dSAlex Tomas 		gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
2958021b65bbSTheodore Ts'o 		ext4_free_group_clusters_set(sb, gdp,
2959cff1dfd7STheodore Ts'o 					     ext4_free_clusters_after_init(sb,
2960560671a0SAneesh Kumar K.V 						ac->ac_b_ex.fe_group, gdp));
2961c9de560dSAlex Tomas 	}
2962021b65bbSTheodore Ts'o 	len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
2963021b65bbSTheodore Ts'o 	ext4_free_group_clusters_set(sb, gdp, len);
296479f1ba49STao Ma 	ext4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);
2965feb0ab32SDarrick J. Wong 	ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
2966955ce5f5SAneesh Kumar K.V 
2967955ce5f5SAneesh Kumar K.V 	ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
296857042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
2969d2a17637SMingming Cao 	/*
29706bc6e63fSAneesh Kumar K.V 	 * Now reduce the dirty block count also. Should not go negative
2971d2a17637SMingming Cao 	 */
29726bc6e63fSAneesh Kumar K.V 	if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
29736bc6e63fSAneesh Kumar K.V 		/* release all the reserved blocks if non delalloc */
297457042651STheodore Ts'o 		percpu_counter_sub(&sbi->s_dirtyclusters_counter,
297557042651STheodore Ts'o 				   reserv_clstrs);
2976c9de560dSAlex Tomas 
2977772cb7c8SJose R. Santos 	if (sbi->s_log_groups_per_flex) {
2978772cb7c8SJose R. Santos 		ext4_group_t flex_group = ext4_flex_group(sbi,
2979772cb7c8SJose R. Santos 							  ac->ac_b_ex.fe_group);
298090ba983fSTheodore Ts'o 		atomic64_sub(ac->ac_b_ex.fe_len,
298124aaa8efSTheodore Ts'o 			     &sbi->s_flex_groups[flex_group].free_clusters);
2982772cb7c8SJose R. Santos 	}
2983772cb7c8SJose R. Santos 
29840390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2985c9de560dSAlex Tomas 	if (err)
2986c9de560dSAlex Tomas 		goto out_err;
29870390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
2988c9de560dSAlex Tomas 
2989c9de560dSAlex Tomas out_err:
299042a10addSAneesh Kumar K.V 	brelse(bitmap_bh);
2991c9de560dSAlex Tomas 	return err;
2992c9de560dSAlex Tomas }
2993c9de560dSAlex Tomas 
2994c9de560dSAlex Tomas /*
2995c9de560dSAlex Tomas  * here we normalize request for locality group
2996d7a1fee1SDan Ehrenberg  * Group request are normalized to s_mb_group_prealloc, which goes to
2997d7a1fee1SDan Ehrenberg  * s_strip if we set the same via mount option.
2998d7a1fee1SDan Ehrenberg  * s_mb_group_prealloc can be configured via
2999b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_group_prealloc
3000c9de560dSAlex Tomas  *
3001c9de560dSAlex Tomas  * XXX: should we try to preallocate more than the group has now?
3002c9de560dSAlex Tomas  */
3003c9de560dSAlex Tomas static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3004c9de560dSAlex Tomas {
3005c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
3006c9de560dSAlex Tomas 	struct ext4_locality_group *lg = ac->ac_lg;
3007c9de560dSAlex Tomas 
3008c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
3009c9de560dSAlex Tomas 	ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
30106ba495e9STheodore Ts'o 	mb_debug(1, "#%u: goal %u blocks for locality group\n",
3011c9de560dSAlex Tomas 		current->pid, ac->ac_g_ex.fe_len);
3012c9de560dSAlex Tomas }
3013c9de560dSAlex Tomas 
3014c9de560dSAlex Tomas /*
3015c9de560dSAlex Tomas  * Normalization means making request better in terms of
3016c9de560dSAlex Tomas  * size and alignment
3017c9de560dSAlex Tomas  */
30184ddfef7bSEric Sandeen static noinline_for_stack void
30194ddfef7bSEric Sandeen ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3020c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
3021c9de560dSAlex Tomas {
302253accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3023c9de560dSAlex Tomas 	int bsbits, max;
3024c9de560dSAlex Tomas 	ext4_lblk_t end;
30251592d2c5SCurt Wohlgemuth 	loff_t size, start_off;
30261592d2c5SCurt Wohlgemuth 	loff_t orig_size __maybe_unused;
30275a0790c2SAndi Kleen 	ext4_lblk_t start;
3028c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
30299a0762c5SAneesh Kumar K.V 	struct ext4_prealloc_space *pa;
3030c9de560dSAlex Tomas 
3031c9de560dSAlex Tomas 	/* do normalize only data requests, metadata requests
3032c9de560dSAlex Tomas 	   do not need preallocation */
3033c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3034c9de560dSAlex Tomas 		return;
3035c9de560dSAlex Tomas 
3036c9de560dSAlex Tomas 	/* sometime caller may want exact blocks */
3037c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3038c9de560dSAlex Tomas 		return;
3039c9de560dSAlex Tomas 
3040c9de560dSAlex Tomas 	/* caller may indicate that preallocation isn't
3041c9de560dSAlex Tomas 	 * required (it's a tail, for example) */
3042c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3043c9de560dSAlex Tomas 		return;
3044c9de560dSAlex Tomas 
3045c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3046c9de560dSAlex Tomas 		ext4_mb_normalize_group_request(ac);
3047c9de560dSAlex Tomas 		return ;
3048c9de560dSAlex Tomas 	}
3049c9de560dSAlex Tomas 
3050c9de560dSAlex Tomas 	bsbits = ac->ac_sb->s_blocksize_bits;
3051c9de560dSAlex Tomas 
3052c9de560dSAlex Tomas 	/* first, let's learn actual file size
3053c9de560dSAlex Tomas 	 * given current request is allocated */
305453accfa9STheodore Ts'o 	size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
3055c9de560dSAlex Tomas 	size = size << bsbits;
3056c9de560dSAlex Tomas 	if (size < i_size_read(ac->ac_inode))
3057c9de560dSAlex Tomas 		size = i_size_read(ac->ac_inode);
30585a0790c2SAndi Kleen 	orig_size = size;
3059c9de560dSAlex Tomas 
30601930479cSValerie Clement 	/* max size of free chunks */
30611930479cSValerie Clement 	max = 2 << bsbits;
3062c9de560dSAlex Tomas 
30631930479cSValerie Clement #define NRL_CHECK_SIZE(req, size, max, chunk_size)	\
30641930479cSValerie Clement 		(req <= (size) || max <= (chunk_size))
3065c9de560dSAlex Tomas 
3066c9de560dSAlex Tomas 	/* first, try to predict filesize */
3067c9de560dSAlex Tomas 	/* XXX: should this table be tunable? */
3068c9de560dSAlex Tomas 	start_off = 0;
3069c9de560dSAlex Tomas 	if (size <= 16 * 1024) {
3070c9de560dSAlex Tomas 		size = 16 * 1024;
3071c9de560dSAlex Tomas 	} else if (size <= 32 * 1024) {
3072c9de560dSAlex Tomas 		size = 32 * 1024;
3073c9de560dSAlex Tomas 	} else if (size <= 64 * 1024) {
3074c9de560dSAlex Tomas 		size = 64 * 1024;
3075c9de560dSAlex Tomas 	} else if (size <= 128 * 1024) {
3076c9de560dSAlex Tomas 		size = 128 * 1024;
3077c9de560dSAlex Tomas 	} else if (size <= 256 * 1024) {
3078c9de560dSAlex Tomas 		size = 256 * 1024;
3079c9de560dSAlex Tomas 	} else if (size <= 512 * 1024) {
3080c9de560dSAlex Tomas 		size = 512 * 1024;
3081c9de560dSAlex Tomas 	} else if (size <= 1024 * 1024) {
3082c9de560dSAlex Tomas 		size = 1024 * 1024;
30831930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3084c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
30851930479cSValerie Clement 						(21 - bsbits)) << 21;
30861930479cSValerie Clement 		size = 2 * 1024 * 1024;
30871930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3088c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3089c9de560dSAlex Tomas 							(22 - bsbits)) << 22;
3090c9de560dSAlex Tomas 		size = 4 * 1024 * 1024;
3091c9de560dSAlex Tomas 	} else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
30921930479cSValerie Clement 					(8<<20)>>bsbits, max, 8 * 1024)) {
3093c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3094c9de560dSAlex Tomas 							(23 - bsbits)) << 23;
3095c9de560dSAlex Tomas 		size = 8 * 1024 * 1024;
3096c9de560dSAlex Tomas 	} else {
3097c9de560dSAlex Tomas 		start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
3098b27b1535SXiaoguang Wang 		size	  = (loff_t) EXT4_C2B(EXT4_SB(ac->ac_sb),
3099b27b1535SXiaoguang Wang 					      ac->ac_o_ex.fe_len) << bsbits;
3100c9de560dSAlex Tomas 	}
31015a0790c2SAndi Kleen 	size = size >> bsbits;
31025a0790c2SAndi Kleen 	start = start_off >> bsbits;
3103c9de560dSAlex Tomas 
3104c9de560dSAlex Tomas 	/* don't cover already allocated blocks in selected range */
3105c9de560dSAlex Tomas 	if (ar->pleft && start <= ar->lleft) {
3106c9de560dSAlex Tomas 		size -= ar->lleft + 1 - start;
3107c9de560dSAlex Tomas 		start = ar->lleft + 1;
3108c9de560dSAlex Tomas 	}
3109c9de560dSAlex Tomas 	if (ar->pright && start + size - 1 >= ar->lright)
3110c9de560dSAlex Tomas 		size -= start + size - ar->lright;
3111c9de560dSAlex Tomas 
3112c9de560dSAlex Tomas 	end = start + size;
3113c9de560dSAlex Tomas 
3114c9de560dSAlex Tomas 	/* check we don't cross already preallocated blocks */
3115c9de560dSAlex Tomas 	rcu_read_lock();
31169a0762c5SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3117498e5f24STheodore Ts'o 		ext4_lblk_t pa_end;
3118c9de560dSAlex Tomas 
3119c9de560dSAlex Tomas 		if (pa->pa_deleted)
3120c9de560dSAlex Tomas 			continue;
3121c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3122c9de560dSAlex Tomas 		if (pa->pa_deleted) {
3123c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3124c9de560dSAlex Tomas 			continue;
3125c9de560dSAlex Tomas 		}
3126c9de560dSAlex Tomas 
312753accfa9STheodore Ts'o 		pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
312853accfa9STheodore Ts'o 						  pa->pa_len);
3129c9de560dSAlex Tomas 
3130c9de560dSAlex Tomas 		/* PA must not overlap original request */
3131c9de560dSAlex Tomas 		BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3132c9de560dSAlex Tomas 			ac->ac_o_ex.fe_logical < pa->pa_lstart));
3133c9de560dSAlex Tomas 
313438877f4eSEric Sandeen 		/* skip PAs this normalized request doesn't overlap with */
313538877f4eSEric Sandeen 		if (pa->pa_lstart >= end || pa_end <= start) {
3136c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3137c9de560dSAlex Tomas 			continue;
3138c9de560dSAlex Tomas 		}
3139c9de560dSAlex Tomas 		BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3140c9de560dSAlex Tomas 
314138877f4eSEric Sandeen 		/* adjust start or end to be adjacent to this pa */
3142c9de560dSAlex Tomas 		if (pa_end <= ac->ac_o_ex.fe_logical) {
3143c9de560dSAlex Tomas 			BUG_ON(pa_end < start);
3144c9de560dSAlex Tomas 			start = pa_end;
314538877f4eSEric Sandeen 		} else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3146c9de560dSAlex Tomas 			BUG_ON(pa->pa_lstart > end);
3147c9de560dSAlex Tomas 			end = pa->pa_lstart;
3148c9de560dSAlex Tomas 		}
3149c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3150c9de560dSAlex Tomas 	}
3151c9de560dSAlex Tomas 	rcu_read_unlock();
3152c9de560dSAlex Tomas 	size = end - start;
3153c9de560dSAlex Tomas 
3154c9de560dSAlex Tomas 	/* XXX: extra loop to check we really don't overlap preallocations */
3155c9de560dSAlex Tomas 	rcu_read_lock();
31569a0762c5SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3157498e5f24STheodore Ts'o 		ext4_lblk_t pa_end;
315853accfa9STheodore Ts'o 
3159c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3160c9de560dSAlex Tomas 		if (pa->pa_deleted == 0) {
316153accfa9STheodore Ts'o 			pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
316253accfa9STheodore Ts'o 							  pa->pa_len);
3163c9de560dSAlex Tomas 			BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3164c9de560dSAlex Tomas 		}
3165c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3166c9de560dSAlex Tomas 	}
3167c9de560dSAlex Tomas 	rcu_read_unlock();
3168c9de560dSAlex Tomas 
3169c9de560dSAlex Tomas 	if (start + size <= ac->ac_o_ex.fe_logical &&
3170c9de560dSAlex Tomas 			start > ac->ac_o_ex.fe_logical) {
31719d8b9ec4STheodore Ts'o 		ext4_msg(ac->ac_sb, KERN_ERR,
31729d8b9ec4STheodore Ts'o 			 "start %lu, size %lu, fe_logical %lu",
3173c9de560dSAlex Tomas 			 (unsigned long) start, (unsigned long) size,
3174c9de560dSAlex Tomas 			 (unsigned long) ac->ac_o_ex.fe_logical);
3175dfe076c1SDmitry Monakhov 		BUG();
3176c9de560dSAlex Tomas 	}
3177b5b60778SMaurizio Lombardi 	BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3178c9de560dSAlex Tomas 
3179c9de560dSAlex Tomas 	/* now prepare goal request */
3180c9de560dSAlex Tomas 
3181c9de560dSAlex Tomas 	/* XXX: is it better to align blocks WRT to logical
3182c9de560dSAlex Tomas 	 * placement or satisfy big request as is */
3183c9de560dSAlex Tomas 	ac->ac_g_ex.fe_logical = start;
318453accfa9STheodore Ts'o 	ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3185c9de560dSAlex Tomas 
3186c9de560dSAlex Tomas 	/* define goal start in order to merge */
3187c9de560dSAlex Tomas 	if (ar->pright && (ar->lright == (start + size))) {
3188c9de560dSAlex Tomas 		/* merge to the right */
3189c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3190c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_group,
3191c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_start);
3192c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3193c9de560dSAlex Tomas 	}
3194c9de560dSAlex Tomas 	if (ar->pleft && (ar->lleft + 1 == start)) {
3195c9de560dSAlex Tomas 		/* merge to the left */
3196c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3197c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_group,
3198c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_start);
3199c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3200c9de560dSAlex Tomas 	}
3201c9de560dSAlex Tomas 
32026ba495e9STheodore Ts'o 	mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3203c9de560dSAlex Tomas 		(unsigned) orig_size, (unsigned) start);
3204c9de560dSAlex Tomas }
3205c9de560dSAlex Tomas 
3206c9de560dSAlex Tomas static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3207c9de560dSAlex Tomas {
3208c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3209c9de560dSAlex Tomas 
3210c9de560dSAlex Tomas 	if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3211c9de560dSAlex Tomas 		atomic_inc(&sbi->s_bal_reqs);
3212c9de560dSAlex Tomas 		atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3213291dae47SCurt Wohlgemuth 		if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3214c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_success);
3215c9de560dSAlex Tomas 		atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3216c9de560dSAlex Tomas 		if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3217c9de560dSAlex Tomas 				ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3218c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_goals);
3219c9de560dSAlex Tomas 		if (ac->ac_found > sbi->s_mb_max_to_scan)
3220c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_breaks);
3221c9de560dSAlex Tomas 	}
3222c9de560dSAlex Tomas 
3223296c355cSTheodore Ts'o 	if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3224296c355cSTheodore Ts'o 		trace_ext4_mballoc_alloc(ac);
3225296c355cSTheodore Ts'o 	else
3226296c355cSTheodore Ts'o 		trace_ext4_mballoc_prealloc(ac);
3227c9de560dSAlex Tomas }
3228c9de560dSAlex Tomas 
3229c9de560dSAlex Tomas /*
3230b844167eSCurt Wohlgemuth  * Called on failure; free up any blocks from the inode PA for this
3231b844167eSCurt Wohlgemuth  * context.  We don't need this for MB_GROUP_PA because we only change
3232b844167eSCurt Wohlgemuth  * pa_free in ext4_mb_release_context(), but on failure, we've already
3233b844167eSCurt Wohlgemuth  * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3234b844167eSCurt Wohlgemuth  */
3235b844167eSCurt Wohlgemuth static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3236b844167eSCurt Wohlgemuth {
3237b844167eSCurt Wohlgemuth 	struct ext4_prealloc_space *pa = ac->ac_pa;
323886f0afd4STheodore Ts'o 	struct ext4_buddy e4b;
323986f0afd4STheodore Ts'o 	int err;
3240b844167eSCurt Wohlgemuth 
324186f0afd4STheodore Ts'o 	if (pa == NULL) {
3242c99d1e6eSTheodore Ts'o 		if (ac->ac_f_ex.fe_len == 0)
3243c99d1e6eSTheodore Ts'o 			return;
324486f0afd4STheodore Ts'o 		err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
324586f0afd4STheodore Ts'o 		if (err) {
324686f0afd4STheodore Ts'o 			/*
324786f0afd4STheodore Ts'o 			 * This should never happen since we pin the
324886f0afd4STheodore Ts'o 			 * pages in the ext4_allocation_context so
324986f0afd4STheodore Ts'o 			 * ext4_mb_load_buddy() should never fail.
325086f0afd4STheodore Ts'o 			 */
325186f0afd4STheodore Ts'o 			WARN(1, "mb_load_buddy failed (%d)", err);
325286f0afd4STheodore Ts'o 			return;
325386f0afd4STheodore Ts'o 		}
325486f0afd4STheodore Ts'o 		ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
325586f0afd4STheodore Ts'o 		mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
325686f0afd4STheodore Ts'o 			       ac->ac_f_ex.fe_len);
325786f0afd4STheodore Ts'o 		ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3258c99d1e6eSTheodore Ts'o 		ext4_mb_unload_buddy(&e4b);
325986f0afd4STheodore Ts'o 		return;
326086f0afd4STheodore Ts'o 	}
326186f0afd4STheodore Ts'o 	if (pa->pa_type == MB_INODE_PA)
3262400db9d3SZheng Liu 		pa->pa_free += ac->ac_b_ex.fe_len;
3263b844167eSCurt Wohlgemuth }
3264b844167eSCurt Wohlgemuth 
3265b844167eSCurt Wohlgemuth /*
3266c9de560dSAlex Tomas  * use blocks preallocated to inode
3267c9de560dSAlex Tomas  */
3268c9de560dSAlex Tomas static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3269c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
3270c9de560dSAlex Tomas {
327153accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3272c9de560dSAlex Tomas 	ext4_fsblk_t start;
3273c9de560dSAlex Tomas 	ext4_fsblk_t end;
3274c9de560dSAlex Tomas 	int len;
3275c9de560dSAlex Tomas 
3276c9de560dSAlex Tomas 	/* found preallocated blocks, use them */
3277c9de560dSAlex Tomas 	start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
327853accfa9STheodore Ts'o 	end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
327953accfa9STheodore Ts'o 		  start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
328053accfa9STheodore Ts'o 	len = EXT4_NUM_B2C(sbi, end - start);
3281c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3282c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
3283c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
3284c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
3285c9de560dSAlex Tomas 	ac->ac_pa = pa;
3286c9de560dSAlex Tomas 
3287c9de560dSAlex Tomas 	BUG_ON(start < pa->pa_pstart);
328853accfa9STheodore Ts'o 	BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3289c9de560dSAlex Tomas 	BUG_ON(pa->pa_free < len);
3290c9de560dSAlex Tomas 	pa->pa_free -= len;
3291c9de560dSAlex Tomas 
32926ba495e9STheodore Ts'o 	mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3293c9de560dSAlex Tomas }
3294c9de560dSAlex Tomas 
3295c9de560dSAlex Tomas /*
3296c9de560dSAlex Tomas  * use blocks preallocated to locality group
3297c9de560dSAlex Tomas  */
3298c9de560dSAlex Tomas static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3299c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
3300c9de560dSAlex Tomas {
330103cddb80SAneesh Kumar K.V 	unsigned int len = ac->ac_o_ex.fe_len;
33026be2ded1SAneesh Kumar K.V 
3303c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3304c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_group,
3305c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
3306c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
3307c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
3308c9de560dSAlex Tomas 	ac->ac_pa = pa;
3309c9de560dSAlex Tomas 
3310c9de560dSAlex Tomas 	/* we don't correct pa_pstart or pa_plen here to avoid
331126346ff6SAneesh Kumar K.V 	 * possible race when the group is being loaded concurrently
3312c9de560dSAlex Tomas 	 * instead we correct pa later, after blocks are marked
331326346ff6SAneesh Kumar K.V 	 * in on-disk bitmap -- see ext4_mb_release_context()
331426346ff6SAneesh Kumar K.V 	 * Other CPUs are prevented from allocating from this pa by lg_mutex
3315c9de560dSAlex Tomas 	 */
33166ba495e9STheodore Ts'o 	mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3317c9de560dSAlex Tomas }
3318c9de560dSAlex Tomas 
3319c9de560dSAlex Tomas /*
33205e745b04SAneesh Kumar K.V  * Return the prealloc space that have minimal distance
33215e745b04SAneesh Kumar K.V  * from the goal block. @cpa is the prealloc
33225e745b04SAneesh Kumar K.V  * space that is having currently known minimal distance
33235e745b04SAneesh Kumar K.V  * from the goal block.
33245e745b04SAneesh Kumar K.V  */
33255e745b04SAneesh Kumar K.V static struct ext4_prealloc_space *
33265e745b04SAneesh Kumar K.V ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
33275e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *pa,
33285e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *cpa)
33295e745b04SAneesh Kumar K.V {
33305e745b04SAneesh Kumar K.V 	ext4_fsblk_t cur_distance, new_distance;
33315e745b04SAneesh Kumar K.V 
33325e745b04SAneesh Kumar K.V 	if (cpa == NULL) {
33335e745b04SAneesh Kumar K.V 		atomic_inc(&pa->pa_count);
33345e745b04SAneesh Kumar K.V 		return pa;
33355e745b04SAneesh Kumar K.V 	}
333679211c8eSAndrew Morton 	cur_distance = abs(goal_block - cpa->pa_pstart);
333779211c8eSAndrew Morton 	new_distance = abs(goal_block - pa->pa_pstart);
33385e745b04SAneesh Kumar K.V 
33395a54b2f1SColy Li 	if (cur_distance <= new_distance)
33405e745b04SAneesh Kumar K.V 		return cpa;
33415e745b04SAneesh Kumar K.V 
33425e745b04SAneesh Kumar K.V 	/* drop the previous reference */
33435e745b04SAneesh Kumar K.V 	atomic_dec(&cpa->pa_count);
33445e745b04SAneesh Kumar K.V 	atomic_inc(&pa->pa_count);
33455e745b04SAneesh Kumar K.V 	return pa;
33465e745b04SAneesh Kumar K.V }
33475e745b04SAneesh Kumar K.V 
33485e745b04SAneesh Kumar K.V /*
3349c9de560dSAlex Tomas  * search goal blocks in preallocated space
3350c9de560dSAlex Tomas  */
33514ddfef7bSEric Sandeen static noinline_for_stack int
33524ddfef7bSEric Sandeen ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3353c9de560dSAlex Tomas {
335453accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
33556be2ded1SAneesh Kumar K.V 	int order, i;
3356c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3357c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
33585e745b04SAneesh Kumar K.V 	struct ext4_prealloc_space *pa, *cpa = NULL;
33595e745b04SAneesh Kumar K.V 	ext4_fsblk_t goal_block;
3360c9de560dSAlex Tomas 
3361c9de560dSAlex Tomas 	/* only data can be preallocated */
3362c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3363c9de560dSAlex Tomas 		return 0;
3364c9de560dSAlex Tomas 
3365c9de560dSAlex Tomas 	/* first, try per-file preallocation */
3366c9de560dSAlex Tomas 	rcu_read_lock();
33679a0762c5SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3368c9de560dSAlex Tomas 
3369c9de560dSAlex Tomas 		/* all fields in this condition don't change,
3370c9de560dSAlex Tomas 		 * so we can skip locking for them */
3371c9de560dSAlex Tomas 		if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
337253accfa9STheodore Ts'o 		    ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
337353accfa9STheodore Ts'o 					       EXT4_C2B(sbi, pa->pa_len)))
3374c9de560dSAlex Tomas 			continue;
3375c9de560dSAlex Tomas 
3376fb0a387dSEric Sandeen 		/* non-extent files can't have physical blocks past 2^32 */
337712e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
337853accfa9STheodore Ts'o 		    (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
337953accfa9STheodore Ts'o 		     EXT4_MAX_BLOCK_FILE_PHYS))
3380fb0a387dSEric Sandeen 			continue;
3381fb0a387dSEric Sandeen 
3382c9de560dSAlex Tomas 		/* found preallocated blocks, use them */
3383c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3384c9de560dSAlex Tomas 		if (pa->pa_deleted == 0 && pa->pa_free) {
3385c9de560dSAlex Tomas 			atomic_inc(&pa->pa_count);
3386c9de560dSAlex Tomas 			ext4_mb_use_inode_pa(ac, pa);
3387c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3388c9de560dSAlex Tomas 			ac->ac_criteria = 10;
3389c9de560dSAlex Tomas 			rcu_read_unlock();
3390c9de560dSAlex Tomas 			return 1;
3391c9de560dSAlex Tomas 		}
3392c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3393c9de560dSAlex Tomas 	}
3394c9de560dSAlex Tomas 	rcu_read_unlock();
3395c9de560dSAlex Tomas 
3396c9de560dSAlex Tomas 	/* can we use group allocation? */
3397c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3398c9de560dSAlex Tomas 		return 0;
3399c9de560dSAlex Tomas 
3400c9de560dSAlex Tomas 	/* inode may have no locality group for some reason */
3401c9de560dSAlex Tomas 	lg = ac->ac_lg;
3402c9de560dSAlex Tomas 	if (lg == NULL)
3403c9de560dSAlex Tomas 		return 0;
34046be2ded1SAneesh Kumar K.V 	order  = fls(ac->ac_o_ex.fe_len) - 1;
34056be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
34066be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
34076be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
3408c9de560dSAlex Tomas 
3409bda00de7SAkinobu Mita 	goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
34105e745b04SAneesh Kumar K.V 	/*
34115e745b04SAneesh Kumar K.V 	 * search for the prealloc space that is having
34125e745b04SAneesh Kumar K.V 	 * minimal distance from the goal block.
34135e745b04SAneesh Kumar K.V 	 */
34146be2ded1SAneesh Kumar K.V 	for (i = order; i < PREALLOC_TB_SIZE; i++) {
3415c9de560dSAlex Tomas 		rcu_read_lock();
34166be2ded1SAneesh Kumar K.V 		list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
34176be2ded1SAneesh Kumar K.V 					pa_inode_list) {
3418c9de560dSAlex Tomas 			spin_lock(&pa->pa_lock);
34196be2ded1SAneesh Kumar K.V 			if (pa->pa_deleted == 0 &&
34206be2ded1SAneesh Kumar K.V 					pa->pa_free >= ac->ac_o_ex.fe_len) {
34215e745b04SAneesh Kumar K.V 
34225e745b04SAneesh Kumar K.V 				cpa = ext4_mb_check_group_pa(goal_block,
34235e745b04SAneesh Kumar K.V 								pa, cpa);
34245e745b04SAneesh Kumar K.V 			}
3425c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
34265e745b04SAneesh Kumar K.V 		}
34275e745b04SAneesh Kumar K.V 		rcu_read_unlock();
34285e745b04SAneesh Kumar K.V 	}
34295e745b04SAneesh Kumar K.V 	if (cpa) {
34305e745b04SAneesh Kumar K.V 		ext4_mb_use_group_pa(ac, cpa);
3431c9de560dSAlex Tomas 		ac->ac_criteria = 20;
3432c9de560dSAlex Tomas 		return 1;
3433c9de560dSAlex Tomas 	}
3434c9de560dSAlex Tomas 	return 0;
3435c9de560dSAlex Tomas }
3436c9de560dSAlex Tomas 
3437c9de560dSAlex Tomas /*
34387a2fcbf7SAneesh Kumar K.V  * the function goes through all block freed in the group
34397a2fcbf7SAneesh Kumar K.V  * but not yet committed and marks them used in in-core bitmap.
34407a2fcbf7SAneesh Kumar K.V  * buddy must be generated from this bitmap
3441955ce5f5SAneesh Kumar K.V  * Need to be called with the ext4 group lock held
34427a2fcbf7SAneesh Kumar K.V  */
34437a2fcbf7SAneesh Kumar K.V static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
34447a2fcbf7SAneesh Kumar K.V 						ext4_group_t group)
34457a2fcbf7SAneesh Kumar K.V {
34467a2fcbf7SAneesh Kumar K.V 	struct rb_node *n;
34477a2fcbf7SAneesh Kumar K.V 	struct ext4_group_info *grp;
34487a2fcbf7SAneesh Kumar K.V 	struct ext4_free_data *entry;
34497a2fcbf7SAneesh Kumar K.V 
34507a2fcbf7SAneesh Kumar K.V 	grp = ext4_get_group_info(sb, group);
34517a2fcbf7SAneesh Kumar K.V 	n = rb_first(&(grp->bb_free_root));
34527a2fcbf7SAneesh Kumar K.V 
34537a2fcbf7SAneesh Kumar K.V 	while (n) {
345418aadd47SBobi Jam 		entry = rb_entry(n, struct ext4_free_data, efd_node);
345518aadd47SBobi Jam 		ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
34567a2fcbf7SAneesh Kumar K.V 		n = rb_next(n);
34577a2fcbf7SAneesh Kumar K.V 	}
34587a2fcbf7SAneesh Kumar K.V 	return;
34597a2fcbf7SAneesh Kumar K.V }
34607a2fcbf7SAneesh Kumar K.V 
34617a2fcbf7SAneesh Kumar K.V /*
3462c9de560dSAlex Tomas  * the function goes through all preallocation in this group and marks them
3463c9de560dSAlex Tomas  * used in in-core bitmap. buddy must be generated from this bitmap
3464955ce5f5SAneesh Kumar K.V  * Need to be called with ext4 group lock held
3465c9de560dSAlex Tomas  */
3466089ceeccSEric Sandeen static noinline_for_stack
3467089ceeccSEric Sandeen void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3468c9de560dSAlex Tomas 					ext4_group_t group)
3469c9de560dSAlex Tomas {
3470c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3471c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3472c9de560dSAlex Tomas 	struct list_head *cur;
3473c9de560dSAlex Tomas 	ext4_group_t groupnr;
3474c9de560dSAlex Tomas 	ext4_grpblk_t start;
3475c9de560dSAlex Tomas 	int preallocated = 0;
3476c9de560dSAlex Tomas 	int len;
3477c9de560dSAlex Tomas 
3478c9de560dSAlex Tomas 	/* all form of preallocation discards first load group,
3479c9de560dSAlex Tomas 	 * so the only competing code is preallocation use.
3480c9de560dSAlex Tomas 	 * we don't need any locking here
3481c9de560dSAlex Tomas 	 * notice we do NOT ignore preallocations with pa_deleted
3482c9de560dSAlex Tomas 	 * otherwise we could leave used blocks available for
3483c9de560dSAlex Tomas 	 * allocation in buddy when concurrent ext4_mb_put_pa()
3484c9de560dSAlex Tomas 	 * is dropping preallocation
3485c9de560dSAlex Tomas 	 */
3486c9de560dSAlex Tomas 	list_for_each(cur, &grp->bb_prealloc_list) {
3487c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3488c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3489c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3490c9de560dSAlex Tomas 					     &groupnr, &start);
3491c9de560dSAlex Tomas 		len = pa->pa_len;
3492c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3493c9de560dSAlex Tomas 		if (unlikely(len == 0))
3494c9de560dSAlex Tomas 			continue;
3495c9de560dSAlex Tomas 		BUG_ON(groupnr != group);
3496c3e94d1dSYongqiang Yang 		ext4_set_bits(bitmap, start, len);
3497c9de560dSAlex Tomas 		preallocated += len;
3498c9de560dSAlex Tomas 	}
34996ba495e9STheodore Ts'o 	mb_debug(1, "prellocated %u for group %u\n", preallocated, group);
3500c9de560dSAlex Tomas }
3501c9de560dSAlex Tomas 
3502c9de560dSAlex Tomas static void ext4_mb_pa_callback(struct rcu_head *head)
3503c9de560dSAlex Tomas {
3504c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3505c9de560dSAlex Tomas 	pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
35064e8d2139SJunho Ryu 
35074e8d2139SJunho Ryu 	BUG_ON(atomic_read(&pa->pa_count));
35084e8d2139SJunho Ryu 	BUG_ON(pa->pa_deleted == 0);
3509c9de560dSAlex Tomas 	kmem_cache_free(ext4_pspace_cachep, pa);
3510c9de560dSAlex Tomas }
3511c9de560dSAlex Tomas 
3512c9de560dSAlex Tomas /*
3513c9de560dSAlex Tomas  * drops a reference to preallocated space descriptor
3514c9de560dSAlex Tomas  * if this was the last reference and the space is consumed
3515c9de560dSAlex Tomas  */
3516c9de560dSAlex Tomas static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3517c9de560dSAlex Tomas 			struct super_block *sb, struct ext4_prealloc_space *pa)
3518c9de560dSAlex Tomas {
3519a9df9a49STheodore Ts'o 	ext4_group_t grp;
3520d33a1976SEric Sandeen 	ext4_fsblk_t grp_blk;
3521c9de560dSAlex Tomas 
3522c9de560dSAlex Tomas 	/* in this short window concurrent discard can set pa_deleted */
3523c9de560dSAlex Tomas 	spin_lock(&pa->pa_lock);
35244e8d2139SJunho Ryu 	if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
35254e8d2139SJunho Ryu 		spin_unlock(&pa->pa_lock);
35264e8d2139SJunho Ryu 		return;
35274e8d2139SJunho Ryu 	}
35284e8d2139SJunho Ryu 
3529c9de560dSAlex Tomas 	if (pa->pa_deleted == 1) {
3530c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3531c9de560dSAlex Tomas 		return;
3532c9de560dSAlex Tomas 	}
3533c9de560dSAlex Tomas 
3534c9de560dSAlex Tomas 	pa->pa_deleted = 1;
3535c9de560dSAlex Tomas 	spin_unlock(&pa->pa_lock);
3536c9de560dSAlex Tomas 
3537d33a1976SEric Sandeen 	grp_blk = pa->pa_pstart;
3538cc0fb9adSAneesh Kumar K.V 	/*
3539cc0fb9adSAneesh Kumar K.V 	 * If doing group-based preallocation, pa_pstart may be in the
3540cc0fb9adSAneesh Kumar K.V 	 * next group when pa is used up
3541cc0fb9adSAneesh Kumar K.V 	 */
3542cc0fb9adSAneesh Kumar K.V 	if (pa->pa_type == MB_GROUP_PA)
3543d33a1976SEric Sandeen 		grp_blk--;
3544d33a1976SEric Sandeen 
3545bd86298eSLukas Czerner 	grp = ext4_get_group_number(sb, grp_blk);
3546c9de560dSAlex Tomas 
3547c9de560dSAlex Tomas 	/*
3548c9de560dSAlex Tomas 	 * possible race:
3549c9de560dSAlex Tomas 	 *
3550c9de560dSAlex Tomas 	 *  P1 (buddy init)			P2 (regular allocation)
3551c9de560dSAlex Tomas 	 *					find block B in PA
3552c9de560dSAlex Tomas 	 *  copy on-disk bitmap to buddy
3553c9de560dSAlex Tomas 	 *  					mark B in on-disk bitmap
3554c9de560dSAlex Tomas 	 *					drop PA from group
3555c9de560dSAlex Tomas 	 *  mark all PAs in buddy
3556c9de560dSAlex Tomas 	 *
3557c9de560dSAlex Tomas 	 * thus, P1 initializes buddy with B available. to prevent this
3558c9de560dSAlex Tomas 	 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3559c9de560dSAlex Tomas 	 * against that pair
3560c9de560dSAlex Tomas 	 */
3561c9de560dSAlex Tomas 	ext4_lock_group(sb, grp);
3562c9de560dSAlex Tomas 	list_del(&pa->pa_group_list);
3563c9de560dSAlex Tomas 	ext4_unlock_group(sb, grp);
3564c9de560dSAlex Tomas 
3565c9de560dSAlex Tomas 	spin_lock(pa->pa_obj_lock);
3566c9de560dSAlex Tomas 	list_del_rcu(&pa->pa_inode_list);
3567c9de560dSAlex Tomas 	spin_unlock(pa->pa_obj_lock);
3568c9de560dSAlex Tomas 
3569c9de560dSAlex Tomas 	call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3570c9de560dSAlex Tomas }
3571c9de560dSAlex Tomas 
3572c9de560dSAlex Tomas /*
3573c9de560dSAlex Tomas  * creates new preallocated space for given inode
3574c9de560dSAlex Tomas  */
35754ddfef7bSEric Sandeen static noinline_for_stack int
35764ddfef7bSEric Sandeen ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3577c9de560dSAlex Tomas {
3578c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
357953accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3580c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3581c9de560dSAlex Tomas 	struct ext4_group_info *grp;
3582c9de560dSAlex Tomas 	struct ext4_inode_info *ei;
3583c9de560dSAlex Tomas 
3584c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
3585c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3586c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3587c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3588c9de560dSAlex Tomas 
3589c9de560dSAlex Tomas 	pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3590c9de560dSAlex Tomas 	if (pa == NULL)
3591c9de560dSAlex Tomas 		return -ENOMEM;
3592c9de560dSAlex Tomas 
3593c9de560dSAlex Tomas 	if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3594c9de560dSAlex Tomas 		int winl;
3595c9de560dSAlex Tomas 		int wins;
3596c9de560dSAlex Tomas 		int win;
3597c9de560dSAlex Tomas 		int offs;
3598c9de560dSAlex Tomas 
3599c9de560dSAlex Tomas 		/* we can't allocate as much as normalizer wants.
3600c9de560dSAlex Tomas 		 * so, found space must get proper lstart
3601c9de560dSAlex Tomas 		 * to cover original request */
3602c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3603c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3604c9de560dSAlex Tomas 
3605c9de560dSAlex Tomas 		/* we're limited by original request in that
3606c9de560dSAlex Tomas 		 * logical block must be covered any way
3607c9de560dSAlex Tomas 		 * winl is window we can move our chunk within */
3608c9de560dSAlex Tomas 		winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3609c9de560dSAlex Tomas 
3610c9de560dSAlex Tomas 		/* also, we should cover whole original request */
361153accfa9STheodore Ts'o 		wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
3612c9de560dSAlex Tomas 
3613c9de560dSAlex Tomas 		/* the smallest one defines real window */
3614c9de560dSAlex Tomas 		win = min(winl, wins);
3615c9de560dSAlex Tomas 
361653accfa9STheodore Ts'o 		offs = ac->ac_o_ex.fe_logical %
361753accfa9STheodore Ts'o 			EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3618c9de560dSAlex Tomas 		if (offs && offs < win)
3619c9de560dSAlex Tomas 			win = offs;
3620c9de560dSAlex Tomas 
362153accfa9STheodore Ts'o 		ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
3622810da240SLukas Czerner 			EXT4_NUM_B2C(sbi, win);
3623c9de560dSAlex Tomas 		BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3624c9de560dSAlex Tomas 		BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3625c9de560dSAlex Tomas 	}
3626c9de560dSAlex Tomas 
3627c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
3628c9de560dSAlex Tomas 	 * allocated blocks for history */
3629c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
3630c9de560dSAlex Tomas 
3631c9de560dSAlex Tomas 	pa->pa_lstart = ac->ac_b_ex.fe_logical;
3632c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3633c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
3634c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
3635c9de560dSAlex Tomas 	atomic_set(&pa->pa_count, 1);
3636c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
3637d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_inode_list);
3638d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
3639c9de560dSAlex Tomas 	pa->pa_deleted = 0;
3640cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_INODE_PA;
3641c9de560dSAlex Tomas 
36426ba495e9STheodore Ts'o 	mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3643c9de560dSAlex Tomas 			pa->pa_pstart, pa->pa_len, pa->pa_lstart);
36449bffad1eSTheodore Ts'o 	trace_ext4_mb_new_inode_pa(ac, pa);
3645c9de560dSAlex Tomas 
3646c9de560dSAlex Tomas 	ext4_mb_use_inode_pa(ac, pa);
364753accfa9STheodore Ts'o 	atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
3648c9de560dSAlex Tomas 
3649c9de560dSAlex Tomas 	ei = EXT4_I(ac->ac_inode);
3650c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3651c9de560dSAlex Tomas 
3652c9de560dSAlex Tomas 	pa->pa_obj_lock = &ei->i_prealloc_lock;
3653c9de560dSAlex Tomas 	pa->pa_inode = ac->ac_inode;
3654c9de560dSAlex Tomas 
3655c9de560dSAlex Tomas 	ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3656c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3657c9de560dSAlex Tomas 	ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3658c9de560dSAlex Tomas 
3659c9de560dSAlex Tomas 	spin_lock(pa->pa_obj_lock);
3660c9de560dSAlex Tomas 	list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3661c9de560dSAlex Tomas 	spin_unlock(pa->pa_obj_lock);
3662c9de560dSAlex Tomas 
3663c9de560dSAlex Tomas 	return 0;
3664c9de560dSAlex Tomas }
3665c9de560dSAlex Tomas 
3666c9de560dSAlex Tomas /*
3667c9de560dSAlex Tomas  * creates new preallocated space for locality group inodes belongs to
3668c9de560dSAlex Tomas  */
36694ddfef7bSEric Sandeen static noinline_for_stack int
36704ddfef7bSEric Sandeen ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3671c9de560dSAlex Tomas {
3672c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
3673c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
3674c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3675c9de560dSAlex Tomas 	struct ext4_group_info *grp;
3676c9de560dSAlex Tomas 
3677c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
3678c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3679c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3680c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3681c9de560dSAlex Tomas 
3682c9de560dSAlex Tomas 	BUG_ON(ext4_pspace_cachep == NULL);
3683c9de560dSAlex Tomas 	pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3684c9de560dSAlex Tomas 	if (pa == NULL)
3685c9de560dSAlex Tomas 		return -ENOMEM;
3686c9de560dSAlex Tomas 
3687c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
3688c9de560dSAlex Tomas 	 * allocated blocks for history */
3689c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
3690c9de560dSAlex Tomas 
3691c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3692c9de560dSAlex Tomas 	pa->pa_lstart = pa->pa_pstart;
3693c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
3694c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
3695c9de560dSAlex Tomas 	atomic_set(&pa->pa_count, 1);
3696c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
36976be2ded1SAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_inode_list);
3698d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
3699c9de560dSAlex Tomas 	pa->pa_deleted = 0;
3700cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_GROUP_PA;
3701c9de560dSAlex Tomas 
37026ba495e9STheodore Ts'o 	mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3703c9de560dSAlex Tomas 			pa->pa_pstart, pa->pa_len, pa->pa_lstart);
37049bffad1eSTheodore Ts'o 	trace_ext4_mb_new_group_pa(ac, pa);
3705c9de560dSAlex Tomas 
3706c9de560dSAlex Tomas 	ext4_mb_use_group_pa(ac, pa);
3707c9de560dSAlex Tomas 	atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3708c9de560dSAlex Tomas 
3709c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3710c9de560dSAlex Tomas 	lg = ac->ac_lg;
3711c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
3712c9de560dSAlex Tomas 
3713c9de560dSAlex Tomas 	pa->pa_obj_lock = &lg->lg_prealloc_lock;
3714c9de560dSAlex Tomas 	pa->pa_inode = NULL;
3715c9de560dSAlex Tomas 
3716c9de560dSAlex Tomas 	ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3717c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3718c9de560dSAlex Tomas 	ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3719c9de560dSAlex Tomas 
37206be2ded1SAneesh Kumar K.V 	/*
37216be2ded1SAneesh Kumar K.V 	 * We will later add the new pa to the right bucket
37226be2ded1SAneesh Kumar K.V 	 * after updating the pa_free in ext4_mb_release_context
37236be2ded1SAneesh Kumar K.V 	 */
3724c9de560dSAlex Tomas 	return 0;
3725c9de560dSAlex Tomas }
3726c9de560dSAlex Tomas 
3727c9de560dSAlex Tomas static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3728c9de560dSAlex Tomas {
3729c9de560dSAlex Tomas 	int err;
3730c9de560dSAlex Tomas 
3731c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3732c9de560dSAlex Tomas 		err = ext4_mb_new_group_pa(ac);
3733c9de560dSAlex Tomas 	else
3734c9de560dSAlex Tomas 		err = ext4_mb_new_inode_pa(ac);
3735c9de560dSAlex Tomas 	return err;
3736c9de560dSAlex Tomas }
3737c9de560dSAlex Tomas 
3738c9de560dSAlex Tomas /*
3739c9de560dSAlex Tomas  * finds all unused blocks in on-disk bitmap, frees them in
3740c9de560dSAlex Tomas  * in-core bitmap and buddy.
3741c9de560dSAlex Tomas  * @pa must be unlinked from inode and group lists, so that
3742c9de560dSAlex Tomas  * nobody else can find/use it.
3743c9de560dSAlex Tomas  * the caller MUST hold group/inode locks.
3744c9de560dSAlex Tomas  * TODO: optimize the case when there are no in-core structures yet
3745c9de560dSAlex Tomas  */
37464ddfef7bSEric Sandeen static noinline_for_stack int
37474ddfef7bSEric Sandeen ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
37483e1e5f50SEric Sandeen 			struct ext4_prealloc_space *pa)
3749c9de560dSAlex Tomas {
3750c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
3751c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3752498e5f24STheodore Ts'o 	unsigned int end;
3753498e5f24STheodore Ts'o 	unsigned int next;
3754c9de560dSAlex Tomas 	ext4_group_t group;
3755c9de560dSAlex Tomas 	ext4_grpblk_t bit;
3756ba80b101STheodore Ts'o 	unsigned long long grp_blk_start;
3757c9de560dSAlex Tomas 	int err = 0;
3758c9de560dSAlex Tomas 	int free = 0;
3759c9de560dSAlex Tomas 
3760c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
3761c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
376253accfa9STheodore Ts'o 	grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
3763c9de560dSAlex Tomas 	BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3764c9de560dSAlex Tomas 	end = bit + pa->pa_len;
3765c9de560dSAlex Tomas 
3766c9de560dSAlex Tomas 	while (bit < end) {
3767ffad0a44SAneesh Kumar K.V 		bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3768c9de560dSAlex Tomas 		if (bit >= end)
3769c9de560dSAlex Tomas 			break;
3770ffad0a44SAneesh Kumar K.V 		next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
37716ba495e9STheodore Ts'o 		mb_debug(1, "    free preallocated %u/%u in group %u\n",
37725a0790c2SAndi Kleen 			 (unsigned) ext4_group_first_block_no(sb, group) + bit,
37735a0790c2SAndi Kleen 			 (unsigned) next - bit, (unsigned) group);
3774c9de560dSAlex Tomas 		free += next - bit;
3775c9de560dSAlex Tomas 
37763e1e5f50SEric Sandeen 		trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
377753accfa9STheodore Ts'o 		trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
377853accfa9STheodore Ts'o 						    EXT4_C2B(sbi, bit)),
3779a9c667f8SLukas Czerner 					       next - bit);
3780c9de560dSAlex Tomas 		mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3781c9de560dSAlex Tomas 		bit = next + 1;
3782c9de560dSAlex Tomas 	}
3783c9de560dSAlex Tomas 	if (free != pa->pa_free) {
37849d8b9ec4STheodore Ts'o 		ext4_msg(e4b->bd_sb, KERN_CRIT,
37859d8b9ec4STheodore Ts'o 			 "pa %p: logic %lu, phys. %lu, len %lu",
3786c9de560dSAlex Tomas 			 pa, (unsigned long) pa->pa_lstart,
3787c9de560dSAlex Tomas 			 (unsigned long) pa->pa_pstart,
3788c9de560dSAlex Tomas 			 (unsigned long) pa->pa_len);
3789e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
379026346ff6SAneesh Kumar K.V 					free, pa->pa_free);
3791e56eb659SAneesh Kumar K.V 		/*
3792e56eb659SAneesh Kumar K.V 		 * pa is already deleted so we use the value obtained
3793e56eb659SAneesh Kumar K.V 		 * from the bitmap and continue.
3794e56eb659SAneesh Kumar K.V 		 */
3795c9de560dSAlex Tomas 	}
3796c9de560dSAlex Tomas 	atomic_add(free, &sbi->s_mb_discarded);
3797c9de560dSAlex Tomas 
3798c9de560dSAlex Tomas 	return err;
3799c9de560dSAlex Tomas }
3800c9de560dSAlex Tomas 
38014ddfef7bSEric Sandeen static noinline_for_stack int
38024ddfef7bSEric Sandeen ext4_mb_release_group_pa(struct ext4_buddy *e4b,
38033e1e5f50SEric Sandeen 				struct ext4_prealloc_space *pa)
3804c9de560dSAlex Tomas {
3805c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
3806c9de560dSAlex Tomas 	ext4_group_t group;
3807c9de560dSAlex Tomas 	ext4_grpblk_t bit;
3808c9de560dSAlex Tomas 
380960e07cf5SYongqiang Yang 	trace_ext4_mb_release_group_pa(sb, pa);
3810c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
3811c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3812c9de560dSAlex Tomas 	BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3813c9de560dSAlex Tomas 	mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3814c9de560dSAlex Tomas 	atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
38153e1e5f50SEric Sandeen 	trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3816c9de560dSAlex Tomas 
3817c9de560dSAlex Tomas 	return 0;
3818c9de560dSAlex Tomas }
3819c9de560dSAlex Tomas 
3820c9de560dSAlex Tomas /*
3821c9de560dSAlex Tomas  * releases all preallocations in given group
3822c9de560dSAlex Tomas  *
3823c9de560dSAlex Tomas  * first, we need to decide discard policy:
3824c9de560dSAlex Tomas  * - when do we discard
3825c9de560dSAlex Tomas  *   1) ENOSPC
3826c9de560dSAlex Tomas  * - how many do we discard
3827c9de560dSAlex Tomas  *   1) how many requested
3828c9de560dSAlex Tomas  */
38294ddfef7bSEric Sandeen static noinline_for_stack int
38304ddfef7bSEric Sandeen ext4_mb_discard_group_preallocations(struct super_block *sb,
3831c9de560dSAlex Tomas 					ext4_group_t group, int needed)
3832c9de560dSAlex Tomas {
3833c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3834c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
3835c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
3836c9de560dSAlex Tomas 	struct list_head list;
3837c9de560dSAlex Tomas 	struct ext4_buddy e4b;
3838c9de560dSAlex Tomas 	int err;
3839c9de560dSAlex Tomas 	int busy = 0;
3840c9de560dSAlex Tomas 	int free = 0;
3841c9de560dSAlex Tomas 
38426ba495e9STheodore Ts'o 	mb_debug(1, "discard preallocation for group %u\n", group);
3843c9de560dSAlex Tomas 
3844c9de560dSAlex Tomas 	if (list_empty(&grp->bb_prealloc_list))
3845c9de560dSAlex Tomas 		return 0;
3846c9de560dSAlex Tomas 
3847574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, group);
38489008a58eSDarrick J. Wong 	if (IS_ERR(bitmap_bh)) {
38499008a58eSDarrick J. Wong 		err = PTR_ERR(bitmap_bh);
38509008a58eSDarrick J. Wong 		ext4_error(sb, "Error %d reading block bitmap for %u",
38519008a58eSDarrick J. Wong 			   err, group);
3852ce89f46cSAneesh Kumar K.V 		return 0;
3853c9de560dSAlex Tomas 	}
3854c9de560dSAlex Tomas 
3855c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(sb, group, &e4b);
3856ce89f46cSAneesh Kumar K.V 	if (err) {
385712062dddSEric Sandeen 		ext4_error(sb, "Error loading buddy information for %u", group);
3858ce89f46cSAneesh Kumar K.V 		put_bh(bitmap_bh);
3859ce89f46cSAneesh Kumar K.V 		return 0;
3860ce89f46cSAneesh Kumar K.V 	}
3861c9de560dSAlex Tomas 
3862c9de560dSAlex Tomas 	if (needed == 0)
38637137d7a4STheodore Ts'o 		needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
3864c9de560dSAlex Tomas 
3865c9de560dSAlex Tomas 	INIT_LIST_HEAD(&list);
3866c9de560dSAlex Tomas repeat:
3867c9de560dSAlex Tomas 	ext4_lock_group(sb, group);
3868c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp,
3869c9de560dSAlex Tomas 				&grp->bb_prealloc_list, pa_group_list) {
3870c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3871c9de560dSAlex Tomas 		if (atomic_read(&pa->pa_count)) {
3872c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3873c9de560dSAlex Tomas 			busy = 1;
3874c9de560dSAlex Tomas 			continue;
3875c9de560dSAlex Tomas 		}
3876c9de560dSAlex Tomas 		if (pa->pa_deleted) {
3877c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3878c9de560dSAlex Tomas 			continue;
3879c9de560dSAlex Tomas 		}
3880c9de560dSAlex Tomas 
3881c9de560dSAlex Tomas 		/* seems this one can be freed ... */
3882c9de560dSAlex Tomas 		pa->pa_deleted = 1;
3883c9de560dSAlex Tomas 
3884c9de560dSAlex Tomas 		/* we can trust pa_free ... */
3885c9de560dSAlex Tomas 		free += pa->pa_free;
3886c9de560dSAlex Tomas 
3887c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3888c9de560dSAlex Tomas 
3889c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
3890c9de560dSAlex Tomas 		list_add(&pa->u.pa_tmp_list, &list);
3891c9de560dSAlex Tomas 	}
3892c9de560dSAlex Tomas 
3893c9de560dSAlex Tomas 	/* if we still need more blocks and some PAs were used, try again */
3894c9de560dSAlex Tomas 	if (free < needed && busy) {
3895c9de560dSAlex Tomas 		busy = 0;
3896c9de560dSAlex Tomas 		ext4_unlock_group(sb, group);
3897bb8b20edSLukas Czerner 		cond_resched();
3898c9de560dSAlex Tomas 		goto repeat;
3899c9de560dSAlex Tomas 	}
3900c9de560dSAlex Tomas 
3901c9de560dSAlex Tomas 	/* found anything to free? */
3902c9de560dSAlex Tomas 	if (list_empty(&list)) {
3903c9de560dSAlex Tomas 		BUG_ON(free != 0);
3904c9de560dSAlex Tomas 		goto out;
3905c9de560dSAlex Tomas 	}
3906c9de560dSAlex Tomas 
3907c9de560dSAlex Tomas 	/* now free all selected PAs */
3908c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3909c9de560dSAlex Tomas 
3910c9de560dSAlex Tomas 		/* remove from object (inode or locality group) */
3911c9de560dSAlex Tomas 		spin_lock(pa->pa_obj_lock);
3912c9de560dSAlex Tomas 		list_del_rcu(&pa->pa_inode_list);
3913c9de560dSAlex Tomas 		spin_unlock(pa->pa_obj_lock);
3914c9de560dSAlex Tomas 
3915cc0fb9adSAneesh Kumar K.V 		if (pa->pa_type == MB_GROUP_PA)
39163e1e5f50SEric Sandeen 			ext4_mb_release_group_pa(&e4b, pa);
3917c9de560dSAlex Tomas 		else
39183e1e5f50SEric Sandeen 			ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3919c9de560dSAlex Tomas 
3920c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
3921c9de560dSAlex Tomas 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3922c9de560dSAlex Tomas 	}
3923c9de560dSAlex Tomas 
3924c9de560dSAlex Tomas out:
3925c9de560dSAlex Tomas 	ext4_unlock_group(sb, group);
3926e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
3927c9de560dSAlex Tomas 	put_bh(bitmap_bh);
3928c9de560dSAlex Tomas 	return free;
3929c9de560dSAlex Tomas }
3930c9de560dSAlex Tomas 
3931c9de560dSAlex Tomas /*
3932c9de560dSAlex Tomas  * releases all non-used preallocated blocks for given inode
3933c9de560dSAlex Tomas  *
3934c9de560dSAlex Tomas  * It's important to discard preallocations under i_data_sem
3935c9de560dSAlex Tomas  * We don't want another block to be served from the prealloc
3936c9de560dSAlex Tomas  * space when we are discarding the inode prealloc space.
3937c9de560dSAlex Tomas  *
3938c9de560dSAlex Tomas  * FIXME!! Make sure it is valid at all the call sites
3939c9de560dSAlex Tomas  */
3940c2ea3fdeSTheodore Ts'o void ext4_discard_preallocations(struct inode *inode)
3941c9de560dSAlex Tomas {
3942c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(inode);
3943c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
3944c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
3945c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
3946c9de560dSAlex Tomas 	ext4_group_t group = 0;
3947c9de560dSAlex Tomas 	struct list_head list;
3948c9de560dSAlex Tomas 	struct ext4_buddy e4b;
3949c9de560dSAlex Tomas 	int err;
3950c9de560dSAlex Tomas 
3951c2ea3fdeSTheodore Ts'o 	if (!S_ISREG(inode->i_mode)) {
3952c9de560dSAlex Tomas 		/*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
3953c9de560dSAlex Tomas 		return;
3954c9de560dSAlex Tomas 	}
3955c9de560dSAlex Tomas 
39566ba495e9STheodore Ts'o 	mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
39579bffad1eSTheodore Ts'o 	trace_ext4_discard_preallocations(inode);
3958c9de560dSAlex Tomas 
3959c9de560dSAlex Tomas 	INIT_LIST_HEAD(&list);
3960c9de560dSAlex Tomas 
3961c9de560dSAlex Tomas repeat:
3962c9de560dSAlex Tomas 	/* first, collect all pa's in the inode */
3963c9de560dSAlex Tomas 	spin_lock(&ei->i_prealloc_lock);
3964c9de560dSAlex Tomas 	while (!list_empty(&ei->i_prealloc_list)) {
3965c9de560dSAlex Tomas 		pa = list_entry(ei->i_prealloc_list.next,
3966c9de560dSAlex Tomas 				struct ext4_prealloc_space, pa_inode_list);
3967c9de560dSAlex Tomas 		BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
3968c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3969c9de560dSAlex Tomas 		if (atomic_read(&pa->pa_count)) {
3970c9de560dSAlex Tomas 			/* this shouldn't happen often - nobody should
3971c9de560dSAlex Tomas 			 * use preallocation while we're discarding it */
3972c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3973c9de560dSAlex Tomas 			spin_unlock(&ei->i_prealloc_lock);
39749d8b9ec4STheodore Ts'o 			ext4_msg(sb, KERN_ERR,
39759d8b9ec4STheodore Ts'o 				 "uh-oh! used pa while discarding");
3976c9de560dSAlex Tomas 			WARN_ON(1);
3977c9de560dSAlex Tomas 			schedule_timeout_uninterruptible(HZ);
3978c9de560dSAlex Tomas 			goto repeat;
3979c9de560dSAlex Tomas 
3980c9de560dSAlex Tomas 		}
3981c9de560dSAlex Tomas 		if (pa->pa_deleted == 0) {
3982c9de560dSAlex Tomas 			pa->pa_deleted = 1;
3983c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3984c9de560dSAlex Tomas 			list_del_rcu(&pa->pa_inode_list);
3985c9de560dSAlex Tomas 			list_add(&pa->u.pa_tmp_list, &list);
3986c9de560dSAlex Tomas 			continue;
3987c9de560dSAlex Tomas 		}
3988c9de560dSAlex Tomas 
3989c9de560dSAlex Tomas 		/* someone is deleting pa right now */
3990c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3991c9de560dSAlex Tomas 		spin_unlock(&ei->i_prealloc_lock);
3992c9de560dSAlex Tomas 
3993c9de560dSAlex Tomas 		/* we have to wait here because pa_deleted
3994c9de560dSAlex Tomas 		 * doesn't mean pa is already unlinked from
3995c9de560dSAlex Tomas 		 * the list. as we might be called from
3996c9de560dSAlex Tomas 		 * ->clear_inode() the inode will get freed
3997c9de560dSAlex Tomas 		 * and concurrent thread which is unlinking
3998c9de560dSAlex Tomas 		 * pa from inode's list may access already
3999c9de560dSAlex Tomas 		 * freed memory, bad-bad-bad */
4000c9de560dSAlex Tomas 
4001c9de560dSAlex Tomas 		/* XXX: if this happens too often, we can
4002c9de560dSAlex Tomas 		 * add a flag to force wait only in case
4003c9de560dSAlex Tomas 		 * of ->clear_inode(), but not in case of
4004c9de560dSAlex Tomas 		 * regular truncate */
4005c9de560dSAlex Tomas 		schedule_timeout_uninterruptible(HZ);
4006c9de560dSAlex Tomas 		goto repeat;
4007c9de560dSAlex Tomas 	}
4008c9de560dSAlex Tomas 	spin_unlock(&ei->i_prealloc_lock);
4009c9de560dSAlex Tomas 
4010c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4011cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_INODE_PA);
4012bd86298eSLukas Czerner 		group = ext4_get_group_number(sb, pa->pa_pstart);
4013c9de560dSAlex Tomas 
4014c9de560dSAlex Tomas 		err = ext4_mb_load_buddy(sb, group, &e4b);
4015ce89f46cSAneesh Kumar K.V 		if (err) {
401612062dddSEric Sandeen 			ext4_error(sb, "Error loading buddy information for %u",
401712062dddSEric Sandeen 					group);
4018ce89f46cSAneesh Kumar K.V 			continue;
4019ce89f46cSAneesh Kumar K.V 		}
4020c9de560dSAlex Tomas 
4021574ca174STheodore Ts'o 		bitmap_bh = ext4_read_block_bitmap(sb, group);
40229008a58eSDarrick J. Wong 		if (IS_ERR(bitmap_bh)) {
40239008a58eSDarrick J. Wong 			err = PTR_ERR(bitmap_bh);
40249008a58eSDarrick J. Wong 			ext4_error(sb, "Error %d reading block bitmap for %u",
40259008a58eSDarrick J. Wong 					err, group);
4026e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
4027ce89f46cSAneesh Kumar K.V 			continue;
4028c9de560dSAlex Tomas 		}
4029c9de560dSAlex Tomas 
4030c9de560dSAlex Tomas 		ext4_lock_group(sb, group);
4031c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
40323e1e5f50SEric Sandeen 		ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4033c9de560dSAlex Tomas 		ext4_unlock_group(sb, group);
4034c9de560dSAlex Tomas 
4035e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
4036c9de560dSAlex Tomas 		put_bh(bitmap_bh);
4037c9de560dSAlex Tomas 
4038c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
4039c9de560dSAlex Tomas 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4040c9de560dSAlex Tomas 	}
4041c9de560dSAlex Tomas }
4042c9de560dSAlex Tomas 
40436ba495e9STheodore Ts'o #ifdef CONFIG_EXT4_DEBUG
4044c9de560dSAlex Tomas static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4045c9de560dSAlex Tomas {
4046c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
40478df9675fSTheodore Ts'o 	ext4_group_t ngroups, i;
4048c9de560dSAlex Tomas 
4049a0b30c12STheodore Ts'o 	if (!ext4_mballoc_debug ||
40504dd89fc6STheodore Ts'o 	    (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
4051e3570639SEric Sandeen 		return;
4052e3570639SEric Sandeen 
40537f6a11e7SJoe Perches 	ext4_msg(ac->ac_sb, KERN_ERR, "Can't allocate:"
40549d8b9ec4STheodore Ts'o 			" Allocation context details:");
40557f6a11e7SJoe Perches 	ext4_msg(ac->ac_sb, KERN_ERR, "status %d flags %d",
4056c9de560dSAlex Tomas 			ac->ac_status, ac->ac_flags);
40577f6a11e7SJoe Perches 	ext4_msg(ac->ac_sb, KERN_ERR, "orig %lu/%lu/%lu@%lu, "
40589d8b9ec4STheodore Ts'o 		 	"goal %lu/%lu/%lu@%lu, "
40599d8b9ec4STheodore Ts'o 			"best %lu/%lu/%lu@%lu cr %d",
4060c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_group,
4061c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_start,
4062c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_len,
4063c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_logical,
4064c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_group,
4065c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_start,
4066c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_len,
4067c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_logical,
4068c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_group,
4069c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_start,
4070c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_len,
4071c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_logical,
4072c9de560dSAlex Tomas 			(int)ac->ac_criteria);
4073dc9ddd98SEric Sandeen 	ext4_msg(ac->ac_sb, KERN_ERR, "%d found", ac->ac_found);
40747f6a11e7SJoe Perches 	ext4_msg(ac->ac_sb, KERN_ERR, "groups: ");
40758df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
40768df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
4077c9de560dSAlex Tomas 		struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4078c9de560dSAlex Tomas 		struct ext4_prealloc_space *pa;
4079c9de560dSAlex Tomas 		ext4_grpblk_t start;
4080c9de560dSAlex Tomas 		struct list_head *cur;
4081c9de560dSAlex Tomas 		ext4_lock_group(sb, i);
4082c9de560dSAlex Tomas 		list_for_each(cur, &grp->bb_prealloc_list) {
4083c9de560dSAlex Tomas 			pa = list_entry(cur, struct ext4_prealloc_space,
4084c9de560dSAlex Tomas 					pa_group_list);
4085c9de560dSAlex Tomas 			spin_lock(&pa->pa_lock);
4086c9de560dSAlex Tomas 			ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4087c9de560dSAlex Tomas 						     NULL, &start);
4088c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
40891c718505SAkira Fujita 			printk(KERN_ERR "PA:%u:%d:%u \n", i,
4090c9de560dSAlex Tomas 			       start, pa->pa_len);
4091c9de560dSAlex Tomas 		}
409260bd63d1SSolofo Ramangalahy 		ext4_unlock_group(sb, i);
4093c9de560dSAlex Tomas 
4094c9de560dSAlex Tomas 		if (grp->bb_free == 0)
4095c9de560dSAlex Tomas 			continue;
40961c718505SAkira Fujita 		printk(KERN_ERR "%u: %d/%d \n",
4097c9de560dSAlex Tomas 		       i, grp->bb_free, grp->bb_fragments);
4098c9de560dSAlex Tomas 	}
4099c9de560dSAlex Tomas 	printk(KERN_ERR "\n");
4100c9de560dSAlex Tomas }
4101c9de560dSAlex Tomas #else
4102c9de560dSAlex Tomas static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4103c9de560dSAlex Tomas {
4104c9de560dSAlex Tomas 	return;
4105c9de560dSAlex Tomas }
4106c9de560dSAlex Tomas #endif
4107c9de560dSAlex Tomas 
4108c9de560dSAlex Tomas /*
4109c9de560dSAlex Tomas  * We use locality group preallocation for small size file. The size of the
4110c9de560dSAlex Tomas  * file is determined by the current size or the resulting size after
4111c9de560dSAlex Tomas  * allocation which ever is larger
4112c9de560dSAlex Tomas  *
4113b713a5ecSTheodore Ts'o  * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4114c9de560dSAlex Tomas  */
4115c9de560dSAlex Tomas static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4116c9de560dSAlex Tomas {
4117c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4118c9de560dSAlex Tomas 	int bsbits = ac->ac_sb->s_blocksize_bits;
4119c9de560dSAlex Tomas 	loff_t size, isize;
4120c9de560dSAlex Tomas 
4121c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4122c9de560dSAlex Tomas 		return;
4123c9de560dSAlex Tomas 
41244ba74d00STheodore Ts'o 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
41254ba74d00STheodore Ts'o 		return;
41264ba74d00STheodore Ts'o 
412753accfa9STheodore Ts'o 	size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
412850797481STheodore Ts'o 	isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
412950797481STheodore Ts'o 		>> bsbits;
4130c9de560dSAlex Tomas 
413150797481STheodore Ts'o 	if ((size == isize) &&
413250797481STheodore Ts'o 	    !ext4_fs_is_busy(sbi) &&
413350797481STheodore Ts'o 	    (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
413450797481STheodore Ts'o 		ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
413550797481STheodore Ts'o 		return;
413650797481STheodore Ts'o 	}
413750797481STheodore Ts'o 
4138ebbe0277SRobin Dong 	if (sbi->s_mb_group_prealloc <= 0) {
4139ebbe0277SRobin Dong 		ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4140ebbe0277SRobin Dong 		return;
4141ebbe0277SRobin Dong 	}
4142ebbe0277SRobin Dong 
4143c9de560dSAlex Tomas 	/* don't use group allocation for large files */
414471780577STheodore Ts'o 	size = max(size, isize);
4145cc483f10STao Ma 	if (size > sbi->s_mb_stream_request) {
41464ba74d00STheodore Ts'o 		ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4147c9de560dSAlex Tomas 		return;
41484ba74d00STheodore Ts'o 	}
4149c9de560dSAlex Tomas 
4150c9de560dSAlex Tomas 	BUG_ON(ac->ac_lg != NULL);
4151c9de560dSAlex Tomas 	/*
4152c9de560dSAlex Tomas 	 * locality group prealloc space are per cpu. The reason for having
4153c9de560dSAlex Tomas 	 * per cpu locality group is to reduce the contention between block
4154c9de560dSAlex Tomas 	 * request from multiple CPUs.
4155c9de560dSAlex Tomas 	 */
4156a0b6bc63SChristoph Lameter 	ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
4157c9de560dSAlex Tomas 
4158c9de560dSAlex Tomas 	/* we're going to use group allocation */
4159c9de560dSAlex Tomas 	ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4160c9de560dSAlex Tomas 
4161c9de560dSAlex Tomas 	/* serialize all allocations in the group */
4162c9de560dSAlex Tomas 	mutex_lock(&ac->ac_lg->lg_mutex);
4163c9de560dSAlex Tomas }
4164c9de560dSAlex Tomas 
41654ddfef7bSEric Sandeen static noinline_for_stack int
41664ddfef7bSEric Sandeen ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4167c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
4168c9de560dSAlex Tomas {
4169c9de560dSAlex Tomas 	struct super_block *sb = ar->inode->i_sb;
4170c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
4171c9de560dSAlex Tomas 	struct ext4_super_block *es = sbi->s_es;
4172c9de560dSAlex Tomas 	ext4_group_t group;
4173498e5f24STheodore Ts'o 	unsigned int len;
4174498e5f24STheodore Ts'o 	ext4_fsblk_t goal;
4175c9de560dSAlex Tomas 	ext4_grpblk_t block;
4176c9de560dSAlex Tomas 
4177c9de560dSAlex Tomas 	/* we can't allocate > group size */
4178c9de560dSAlex Tomas 	len = ar->len;
4179c9de560dSAlex Tomas 
4180c9de560dSAlex Tomas 	/* just a dirty hack to filter too big requests  */
418140ae3487STheodore Ts'o 	if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
418240ae3487STheodore Ts'o 		len = EXT4_CLUSTERS_PER_GROUP(sb);
4183c9de560dSAlex Tomas 
4184c9de560dSAlex Tomas 	/* start searching from the goal */
4185c9de560dSAlex Tomas 	goal = ar->goal;
4186c9de560dSAlex Tomas 	if (goal < le32_to_cpu(es->s_first_data_block) ||
4187c9de560dSAlex Tomas 			goal >= ext4_blocks_count(es))
4188c9de560dSAlex Tomas 		goal = le32_to_cpu(es->s_first_data_block);
4189c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, goal, &group, &block);
4190c9de560dSAlex Tomas 
4191c9de560dSAlex Tomas 	/* set up allocation goals */
4192f5a44db5STheodore Ts'o 	ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
4193c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_CONTINUE;
4194c9de560dSAlex Tomas 	ac->ac_sb = sb;
4195c9de560dSAlex Tomas 	ac->ac_inode = ar->inode;
419653accfa9STheodore Ts'o 	ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4197c9de560dSAlex Tomas 	ac->ac_o_ex.fe_group = group;
4198c9de560dSAlex Tomas 	ac->ac_o_ex.fe_start = block;
4199c9de560dSAlex Tomas 	ac->ac_o_ex.fe_len = len;
420053accfa9STheodore Ts'o 	ac->ac_g_ex = ac->ac_o_ex;
4201c9de560dSAlex Tomas 	ac->ac_flags = ar->flags;
4202c9de560dSAlex Tomas 
4203c9de560dSAlex Tomas 	/* we have to define context: we'll we work with a file or
4204c9de560dSAlex Tomas 	 * locality group. this is a policy, actually */
4205c9de560dSAlex Tomas 	ext4_mb_group_or_file(ac);
4206c9de560dSAlex Tomas 
42076ba495e9STheodore Ts'o 	mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4208c9de560dSAlex Tomas 			"left: %u/%u, right %u/%u to %swritable\n",
4209c9de560dSAlex Tomas 			(unsigned) ar->len, (unsigned) ar->logical,
4210c9de560dSAlex Tomas 			(unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4211c9de560dSAlex Tomas 			(unsigned) ar->lleft, (unsigned) ar->pleft,
4212c9de560dSAlex Tomas 			(unsigned) ar->lright, (unsigned) ar->pright,
4213c9de560dSAlex Tomas 			atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4214c9de560dSAlex Tomas 	return 0;
4215c9de560dSAlex Tomas 
4216c9de560dSAlex Tomas }
4217c9de560dSAlex Tomas 
42186be2ded1SAneesh Kumar K.V static noinline_for_stack void
42196be2ded1SAneesh Kumar K.V ext4_mb_discard_lg_preallocations(struct super_block *sb,
42206be2ded1SAneesh Kumar K.V 					struct ext4_locality_group *lg,
42216be2ded1SAneesh Kumar K.V 					int order, int total_entries)
42226be2ded1SAneesh Kumar K.V {
42236be2ded1SAneesh Kumar K.V 	ext4_group_t group = 0;
42246be2ded1SAneesh Kumar K.V 	struct ext4_buddy e4b;
42256be2ded1SAneesh Kumar K.V 	struct list_head discard_list;
42266be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa, *tmp;
42276be2ded1SAneesh Kumar K.V 
42286ba495e9STheodore Ts'o 	mb_debug(1, "discard locality group preallocation\n");
42296be2ded1SAneesh Kumar K.V 
42306be2ded1SAneesh Kumar K.V 	INIT_LIST_HEAD(&discard_list);
42316be2ded1SAneesh Kumar K.V 
42326be2ded1SAneesh Kumar K.V 	spin_lock(&lg->lg_prealloc_lock);
42336be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
42346be2ded1SAneesh Kumar K.V 						pa_inode_list) {
42356be2ded1SAneesh Kumar K.V 		spin_lock(&pa->pa_lock);
42366be2ded1SAneesh Kumar K.V 		if (atomic_read(&pa->pa_count)) {
42376be2ded1SAneesh Kumar K.V 			/*
42386be2ded1SAneesh Kumar K.V 			 * This is the pa that we just used
42396be2ded1SAneesh Kumar K.V 			 * for block allocation. So don't
42406be2ded1SAneesh Kumar K.V 			 * free that
42416be2ded1SAneesh Kumar K.V 			 */
42426be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
42436be2ded1SAneesh Kumar K.V 			continue;
42446be2ded1SAneesh Kumar K.V 		}
42456be2ded1SAneesh Kumar K.V 		if (pa->pa_deleted) {
42466be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
42476be2ded1SAneesh Kumar K.V 			continue;
42486be2ded1SAneesh Kumar K.V 		}
42496be2ded1SAneesh Kumar K.V 		/* only lg prealloc space */
4250cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_GROUP_PA);
42516be2ded1SAneesh Kumar K.V 
42526be2ded1SAneesh Kumar K.V 		/* seems this one can be freed ... */
42536be2ded1SAneesh Kumar K.V 		pa->pa_deleted = 1;
42546be2ded1SAneesh Kumar K.V 		spin_unlock(&pa->pa_lock);
42556be2ded1SAneesh Kumar K.V 
42566be2ded1SAneesh Kumar K.V 		list_del_rcu(&pa->pa_inode_list);
42576be2ded1SAneesh Kumar K.V 		list_add(&pa->u.pa_tmp_list, &discard_list);
42586be2ded1SAneesh Kumar K.V 
42596be2ded1SAneesh Kumar K.V 		total_entries--;
42606be2ded1SAneesh Kumar K.V 		if (total_entries <= 5) {
42616be2ded1SAneesh Kumar K.V 			/*
42626be2ded1SAneesh Kumar K.V 			 * we want to keep only 5 entries
42636be2ded1SAneesh Kumar K.V 			 * allowing it to grow to 8. This
42646be2ded1SAneesh Kumar K.V 			 * mak sure we don't call discard
42656be2ded1SAneesh Kumar K.V 			 * soon for this list.
42666be2ded1SAneesh Kumar K.V 			 */
42676be2ded1SAneesh Kumar K.V 			break;
42686be2ded1SAneesh Kumar K.V 		}
42696be2ded1SAneesh Kumar K.V 	}
42706be2ded1SAneesh Kumar K.V 	spin_unlock(&lg->lg_prealloc_lock);
42716be2ded1SAneesh Kumar K.V 
42726be2ded1SAneesh Kumar K.V 	list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
42736be2ded1SAneesh Kumar K.V 
4274bd86298eSLukas Czerner 		group = ext4_get_group_number(sb, pa->pa_pstart);
42756be2ded1SAneesh Kumar K.V 		if (ext4_mb_load_buddy(sb, group, &e4b)) {
427612062dddSEric Sandeen 			ext4_error(sb, "Error loading buddy information for %u",
427712062dddSEric Sandeen 					group);
42786be2ded1SAneesh Kumar K.V 			continue;
42796be2ded1SAneesh Kumar K.V 		}
42806be2ded1SAneesh Kumar K.V 		ext4_lock_group(sb, group);
42816be2ded1SAneesh Kumar K.V 		list_del(&pa->pa_group_list);
42823e1e5f50SEric Sandeen 		ext4_mb_release_group_pa(&e4b, pa);
42836be2ded1SAneesh Kumar K.V 		ext4_unlock_group(sb, group);
42846be2ded1SAneesh Kumar K.V 
4285e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
42866be2ded1SAneesh Kumar K.V 		list_del(&pa->u.pa_tmp_list);
42876be2ded1SAneesh Kumar K.V 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
42886be2ded1SAneesh Kumar K.V 	}
42896be2ded1SAneesh Kumar K.V }
42906be2ded1SAneesh Kumar K.V 
42916be2ded1SAneesh Kumar K.V /*
42926be2ded1SAneesh Kumar K.V  * We have incremented pa_count. So it cannot be freed at this
42936be2ded1SAneesh Kumar K.V  * point. Also we hold lg_mutex. So no parallel allocation is
42946be2ded1SAneesh Kumar K.V  * possible from this lg. That means pa_free cannot be updated.
42956be2ded1SAneesh Kumar K.V  *
42966be2ded1SAneesh Kumar K.V  * A parallel ext4_mb_discard_group_preallocations is possible.
42976be2ded1SAneesh Kumar K.V  * which can cause the lg_prealloc_list to be updated.
42986be2ded1SAneesh Kumar K.V  */
42996be2ded1SAneesh Kumar K.V 
43006be2ded1SAneesh Kumar K.V static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
43016be2ded1SAneesh Kumar K.V {
43026be2ded1SAneesh Kumar K.V 	int order, added = 0, lg_prealloc_count = 1;
43036be2ded1SAneesh Kumar K.V 	struct super_block *sb = ac->ac_sb;
43046be2ded1SAneesh Kumar K.V 	struct ext4_locality_group *lg = ac->ac_lg;
43056be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
43066be2ded1SAneesh Kumar K.V 
43076be2ded1SAneesh Kumar K.V 	order = fls(pa->pa_free) - 1;
43086be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
43096be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
43106be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
43116be2ded1SAneesh Kumar K.V 	/* Add the prealloc space to lg */
4312f1167009SNiu Yawei 	spin_lock(&lg->lg_prealloc_lock);
43136be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
43146be2ded1SAneesh Kumar K.V 						pa_inode_list) {
43156be2ded1SAneesh Kumar K.V 		spin_lock(&tmp_pa->pa_lock);
43166be2ded1SAneesh Kumar K.V 		if (tmp_pa->pa_deleted) {
4317e7c9e3e9STheodore Ts'o 			spin_unlock(&tmp_pa->pa_lock);
43186be2ded1SAneesh Kumar K.V 			continue;
43196be2ded1SAneesh Kumar K.V 		}
43206be2ded1SAneesh Kumar K.V 		if (!added && pa->pa_free < tmp_pa->pa_free) {
43216be2ded1SAneesh Kumar K.V 			/* Add to the tail of the previous entry */
43226be2ded1SAneesh Kumar K.V 			list_add_tail_rcu(&pa->pa_inode_list,
43236be2ded1SAneesh Kumar K.V 						&tmp_pa->pa_inode_list);
43246be2ded1SAneesh Kumar K.V 			added = 1;
43256be2ded1SAneesh Kumar K.V 			/*
43266be2ded1SAneesh Kumar K.V 			 * we want to count the total
43276be2ded1SAneesh Kumar K.V 			 * number of entries in the list
43286be2ded1SAneesh Kumar K.V 			 */
43296be2ded1SAneesh Kumar K.V 		}
43306be2ded1SAneesh Kumar K.V 		spin_unlock(&tmp_pa->pa_lock);
43316be2ded1SAneesh Kumar K.V 		lg_prealloc_count++;
43326be2ded1SAneesh Kumar K.V 	}
43336be2ded1SAneesh Kumar K.V 	if (!added)
43346be2ded1SAneesh Kumar K.V 		list_add_tail_rcu(&pa->pa_inode_list,
43356be2ded1SAneesh Kumar K.V 					&lg->lg_prealloc_list[order]);
4336f1167009SNiu Yawei 	spin_unlock(&lg->lg_prealloc_lock);
43376be2ded1SAneesh Kumar K.V 
43386be2ded1SAneesh Kumar K.V 	/* Now trim the list to be not more than 8 elements */
43396be2ded1SAneesh Kumar K.V 	if (lg_prealloc_count > 8) {
43406be2ded1SAneesh Kumar K.V 		ext4_mb_discard_lg_preallocations(sb, lg,
43416be2ded1SAneesh Kumar K.V 						  order, lg_prealloc_count);
43426be2ded1SAneesh Kumar K.V 		return;
43436be2ded1SAneesh Kumar K.V 	}
43446be2ded1SAneesh Kumar K.V 	return ;
43456be2ded1SAneesh Kumar K.V }
43466be2ded1SAneesh Kumar K.V 
4347c9de560dSAlex Tomas /*
4348c9de560dSAlex Tomas  * release all resource we used in allocation
4349c9de560dSAlex Tomas  */
4350c9de560dSAlex Tomas static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4351c9de560dSAlex Tomas {
435253accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
43536be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa = ac->ac_pa;
43546be2ded1SAneesh Kumar K.V 	if (pa) {
4355cc0fb9adSAneesh Kumar K.V 		if (pa->pa_type == MB_GROUP_PA) {
4356c9de560dSAlex Tomas 			/* see comment in ext4_mb_use_group_pa() */
43576be2ded1SAneesh Kumar K.V 			spin_lock(&pa->pa_lock);
435853accfa9STheodore Ts'o 			pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
435953accfa9STheodore Ts'o 			pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
43606be2ded1SAneesh Kumar K.V 			pa->pa_free -= ac->ac_b_ex.fe_len;
43616be2ded1SAneesh Kumar K.V 			pa->pa_len -= ac->ac_b_ex.fe_len;
43626be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
4363ba443916SAneesh Kumar K.V 		}
4364ba443916SAneesh Kumar K.V 	}
4365ba443916SAneesh Kumar K.V 	if (pa) {
43666be2ded1SAneesh Kumar K.V 		/*
43676be2ded1SAneesh Kumar K.V 		 * We want to add the pa to the right bucket.
43686be2ded1SAneesh Kumar K.V 		 * Remove it from the list and while adding
43696be2ded1SAneesh Kumar K.V 		 * make sure the list to which we are adding
437044183d42SAmir Goldstein 		 * doesn't grow big.
43716be2ded1SAneesh Kumar K.V 		 */
4372cc0fb9adSAneesh Kumar K.V 		if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
43736be2ded1SAneesh Kumar K.V 			spin_lock(pa->pa_obj_lock);
43746be2ded1SAneesh Kumar K.V 			list_del_rcu(&pa->pa_inode_list);
43756be2ded1SAneesh Kumar K.V 			spin_unlock(pa->pa_obj_lock);
43766be2ded1SAneesh Kumar K.V 			ext4_mb_add_n_trim(ac);
4377c9de560dSAlex Tomas 		}
43786be2ded1SAneesh Kumar K.V 		ext4_mb_put_pa(ac, ac->ac_sb, pa);
4379c9de560dSAlex Tomas 	}
4380c9de560dSAlex Tomas 	if (ac->ac_bitmap_page)
4381c9de560dSAlex Tomas 		page_cache_release(ac->ac_bitmap_page);
4382c9de560dSAlex Tomas 	if (ac->ac_buddy_page)
4383c9de560dSAlex Tomas 		page_cache_release(ac->ac_buddy_page);
4384c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4385c9de560dSAlex Tomas 		mutex_unlock(&ac->ac_lg->lg_mutex);
4386c9de560dSAlex Tomas 	ext4_mb_collect_stats(ac);
4387c9de560dSAlex Tomas 	return 0;
4388c9de560dSAlex Tomas }
4389c9de560dSAlex Tomas 
4390c9de560dSAlex Tomas static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4391c9de560dSAlex Tomas {
43928df9675fSTheodore Ts'o 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4393c9de560dSAlex Tomas 	int ret;
4394c9de560dSAlex Tomas 	int freed = 0;
4395c9de560dSAlex Tomas 
43969bffad1eSTheodore Ts'o 	trace_ext4_mb_discard_preallocations(sb, needed);
43978df9675fSTheodore Ts'o 	for (i = 0; i < ngroups && needed > 0; i++) {
4398c9de560dSAlex Tomas 		ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4399c9de560dSAlex Tomas 		freed += ret;
4400c9de560dSAlex Tomas 		needed -= ret;
4401c9de560dSAlex Tomas 	}
4402c9de560dSAlex Tomas 
4403c9de560dSAlex Tomas 	return freed;
4404c9de560dSAlex Tomas }
4405c9de560dSAlex Tomas 
4406c9de560dSAlex Tomas /*
4407c9de560dSAlex Tomas  * Main entry point into mballoc to allocate blocks
4408c9de560dSAlex Tomas  * it tries to use preallocation first, then falls back
4409c9de560dSAlex Tomas  * to usual allocation
4410c9de560dSAlex Tomas  */
4411c9de560dSAlex Tomas ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4412c9de560dSAlex Tomas 				struct ext4_allocation_request *ar, int *errp)
4413c9de560dSAlex Tomas {
44146bc6e63fSAneesh Kumar K.V 	int freed;
4415256bdb49SEric Sandeen 	struct ext4_allocation_context *ac = NULL;
4416c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
4417c9de560dSAlex Tomas 	struct super_block *sb;
4418c9de560dSAlex Tomas 	ext4_fsblk_t block = 0;
441960e58e0fSMingming Cao 	unsigned int inquota = 0;
442053accfa9STheodore Ts'o 	unsigned int reserv_clstrs = 0;
4421c9de560dSAlex Tomas 
4422b10a44c3STheodore Ts'o 	might_sleep();
4423c9de560dSAlex Tomas 	sb = ar->inode->i_sb;
4424c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
4425c9de560dSAlex Tomas 
44269bffad1eSTheodore Ts'o 	trace_ext4_request_blocks(ar);
4427ba80b101STheodore Ts'o 
442845dc63e7SDmitry Monakhov 	/* Allow to use superuser reservation for quota file */
442945dc63e7SDmitry Monakhov 	if (IS_NOQUOTA(ar->inode))
443045dc63e7SDmitry Monakhov 		ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
443145dc63e7SDmitry Monakhov 
4432e3cf5d5dSTheodore Ts'o 	if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
443360e58e0fSMingming Cao 		/* Without delayed allocation we need to verify
443460e58e0fSMingming Cao 		 * there is enough free blocks to do block allocation
443560e58e0fSMingming Cao 		 * and verify allocation doesn't exceed the quota limits.
4436d2a17637SMingming Cao 		 */
443755f020dbSAllison Henderson 		while (ar->len &&
4438e7d5f315STheodore Ts'o 			ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
443955f020dbSAllison Henderson 
4440030ba6bcSAneesh Kumar K.V 			/* let others to free the space */
4441bb8b20edSLukas Czerner 			cond_resched();
4442030ba6bcSAneesh Kumar K.V 			ar->len = ar->len >> 1;
4443030ba6bcSAneesh Kumar K.V 		}
4444030ba6bcSAneesh Kumar K.V 		if (!ar->len) {
444507031431SMingming Cao 			*errp = -ENOSPC;
444607031431SMingming Cao 			return 0;
444707031431SMingming Cao 		}
444853accfa9STheodore Ts'o 		reserv_clstrs = ar->len;
444955f020dbSAllison Henderson 		if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
445053accfa9STheodore Ts'o 			dquot_alloc_block_nofail(ar->inode,
445153accfa9STheodore Ts'o 						 EXT4_C2B(sbi, ar->len));
445255f020dbSAllison Henderson 		} else {
445355f020dbSAllison Henderson 			while (ar->len &&
445453accfa9STheodore Ts'o 				dquot_alloc_block(ar->inode,
445553accfa9STheodore Ts'o 						  EXT4_C2B(sbi, ar->len))) {
445655f020dbSAllison Henderson 
4457c9de560dSAlex Tomas 				ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4458c9de560dSAlex Tomas 				ar->len--;
4459c9de560dSAlex Tomas 			}
446055f020dbSAllison Henderson 		}
446160e58e0fSMingming Cao 		inquota = ar->len;
4462c9de560dSAlex Tomas 		if (ar->len == 0) {
4463c9de560dSAlex Tomas 			*errp = -EDQUOT;
44646c7a120aSAditya Kali 			goto out;
4465c9de560dSAlex Tomas 		}
446660e58e0fSMingming Cao 	}
4467d2a17637SMingming Cao 
446885556c9aSWei Yongjun 	ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
4469833576b3STheodore Ts'o 	if (!ac) {
4470363d4251SShen Feng 		ar->len = 0;
4471256bdb49SEric Sandeen 		*errp = -ENOMEM;
44726c7a120aSAditya Kali 		goto out;
4473256bdb49SEric Sandeen 	}
4474256bdb49SEric Sandeen 
4475256bdb49SEric Sandeen 	*errp = ext4_mb_initialize_context(ac, ar);
4476c9de560dSAlex Tomas 	if (*errp) {
4477c9de560dSAlex Tomas 		ar->len = 0;
44786c7a120aSAditya Kali 		goto out;
4479c9de560dSAlex Tomas 	}
4480c9de560dSAlex Tomas 
4481256bdb49SEric Sandeen 	ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4482256bdb49SEric Sandeen 	if (!ext4_mb_use_preallocated(ac)) {
4483256bdb49SEric Sandeen 		ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4484256bdb49SEric Sandeen 		ext4_mb_normalize_request(ac, ar);
4485c9de560dSAlex Tomas repeat:
4486c9de560dSAlex Tomas 		/* allocate space in core */
44876c7a120aSAditya Kali 		*errp = ext4_mb_regular_allocator(ac);
44882c00ef3eSAlexey Khoroshilov 		if (*errp)
44892c00ef3eSAlexey Khoroshilov 			goto discard_and_exit;
4490c9de560dSAlex Tomas 
4491c9de560dSAlex Tomas 		/* as we've just preallocated more space than
44922c00ef3eSAlexey Khoroshilov 		 * user requested originally, we store allocated
4493c9de560dSAlex Tomas 		 * space in a special descriptor */
4494256bdb49SEric Sandeen 		if (ac->ac_status == AC_STATUS_FOUND &&
4495256bdb49SEric Sandeen 		    ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
44962c00ef3eSAlexey Khoroshilov 			*errp = ext4_mb_new_preallocation(ac);
44972c00ef3eSAlexey Khoroshilov 		if (*errp) {
44982c00ef3eSAlexey Khoroshilov 		discard_and_exit:
44992c00ef3eSAlexey Khoroshilov 			ext4_discard_allocated_blocks(ac);
45002c00ef3eSAlexey Khoroshilov 			goto errout;
45012c00ef3eSAlexey Khoroshilov 		}
4502c9de560dSAlex Tomas 	}
4503256bdb49SEric Sandeen 	if (likely(ac->ac_status == AC_STATUS_FOUND)) {
450453accfa9STheodore Ts'o 		*errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4505519deca0SAneesh Kumar K.V 		if (*errp == -EAGAIN) {
45068556e8f3SAneesh Kumar K.V 			/*
45078556e8f3SAneesh Kumar K.V 			 * drop the reference that we took
45088556e8f3SAneesh Kumar K.V 			 * in ext4_mb_use_best_found
45098556e8f3SAneesh Kumar K.V 			 */
45108556e8f3SAneesh Kumar K.V 			ext4_mb_release_context(ac);
4511519deca0SAneesh Kumar K.V 			ac->ac_b_ex.fe_group = 0;
4512519deca0SAneesh Kumar K.V 			ac->ac_b_ex.fe_start = 0;
4513519deca0SAneesh Kumar K.V 			ac->ac_b_ex.fe_len = 0;
4514519deca0SAneesh Kumar K.V 			ac->ac_status = AC_STATUS_CONTINUE;
4515519deca0SAneesh Kumar K.V 			goto repeat;
45166d138cedSEric Sandeen 		} else if (*errp) {
4517b844167eSCurt Wohlgemuth 			ext4_discard_allocated_blocks(ac);
45186d138cedSEric Sandeen 			goto errout;
45196d138cedSEric Sandeen 		} else {
4520256bdb49SEric Sandeen 			block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4521256bdb49SEric Sandeen 			ar->len = ac->ac_b_ex.fe_len;
4522519deca0SAneesh Kumar K.V 		}
4523c9de560dSAlex Tomas 	} else {
4524256bdb49SEric Sandeen 		freed  = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4525c9de560dSAlex Tomas 		if (freed)
4526c9de560dSAlex Tomas 			goto repeat;
4527c9de560dSAlex Tomas 		*errp = -ENOSPC;
45286c7a120aSAditya Kali 	}
45296c7a120aSAditya Kali 
45306d138cedSEric Sandeen errout:
45316c7a120aSAditya Kali 	if (*errp) {
4532256bdb49SEric Sandeen 		ac->ac_b_ex.fe_len = 0;
4533c9de560dSAlex Tomas 		ar->len = 0;
4534256bdb49SEric Sandeen 		ext4_mb_show_ac(ac);
4535c9de560dSAlex Tomas 	}
4536256bdb49SEric Sandeen 	ext4_mb_release_context(ac);
45376c7a120aSAditya Kali out:
45386c7a120aSAditya Kali 	if (ac)
4539363d4251SShen Feng 		kmem_cache_free(ext4_ac_cachep, ac);
454060e58e0fSMingming Cao 	if (inquota && ar->len < inquota)
454153accfa9STheodore Ts'o 		dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
45420087d9fbSAneesh Kumar K.V 	if (!ar->len) {
4543e3cf5d5dSTheodore Ts'o 		if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
45440087d9fbSAneesh Kumar K.V 			/* release all the reserved blocks if non delalloc */
454557042651STheodore Ts'o 			percpu_counter_sub(&sbi->s_dirtyclusters_counter,
454653accfa9STheodore Ts'o 						reserv_clstrs);
45470087d9fbSAneesh Kumar K.V 	}
4548c9de560dSAlex Tomas 
45499bffad1eSTheodore Ts'o 	trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4550ba80b101STheodore Ts'o 
4551c9de560dSAlex Tomas 	return block;
4552c9de560dSAlex Tomas }
4553c9de560dSAlex Tomas 
4554c894058dSAneesh Kumar K.V /*
4555c894058dSAneesh Kumar K.V  * We can merge two free data extents only if the physical blocks
4556c894058dSAneesh Kumar K.V  * are contiguous, AND the extents were freed by the same transaction,
4557c894058dSAneesh Kumar K.V  * AND the blocks are associated with the same group.
4558c894058dSAneesh Kumar K.V  */
4559c894058dSAneesh Kumar K.V static int can_merge(struct ext4_free_data *entry1,
4560c894058dSAneesh Kumar K.V 			struct ext4_free_data *entry2)
4561c894058dSAneesh Kumar K.V {
456218aadd47SBobi Jam 	if ((entry1->efd_tid == entry2->efd_tid) &&
456318aadd47SBobi Jam 	    (entry1->efd_group == entry2->efd_group) &&
456418aadd47SBobi Jam 	    ((entry1->efd_start_cluster + entry1->efd_count) == entry2->efd_start_cluster))
4565c894058dSAneesh Kumar K.V 		return 1;
4566c894058dSAneesh Kumar K.V 	return 0;
4567c894058dSAneesh Kumar K.V }
4568c894058dSAneesh Kumar K.V 
45694ddfef7bSEric Sandeen static noinline_for_stack int
45704ddfef7bSEric Sandeen ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
45717a2fcbf7SAneesh Kumar K.V 		      struct ext4_free_data *new_entry)
4572c9de560dSAlex Tomas {
4573e29136f8STheodore Ts'o 	ext4_group_t group = e4b->bd_group;
457484130193STheodore Ts'o 	ext4_grpblk_t cluster;
45757a2fcbf7SAneesh Kumar K.V 	struct ext4_free_data *entry;
4576c9de560dSAlex Tomas 	struct ext4_group_info *db = e4b->bd_info;
4577c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
4578c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
4579c894058dSAneesh Kumar K.V 	struct rb_node **n = &db->bb_free_root.rb_node, *node;
4580c894058dSAneesh Kumar K.V 	struct rb_node *parent = NULL, *new_node;
4581c894058dSAneesh Kumar K.V 
45820390131bSFrank Mayhar 	BUG_ON(!ext4_handle_valid(handle));
4583c9de560dSAlex Tomas 	BUG_ON(e4b->bd_bitmap_page == NULL);
4584c9de560dSAlex Tomas 	BUG_ON(e4b->bd_buddy_page == NULL);
4585c9de560dSAlex Tomas 
458618aadd47SBobi Jam 	new_node = &new_entry->efd_node;
458718aadd47SBobi Jam 	cluster = new_entry->efd_start_cluster;
4588c9de560dSAlex Tomas 
4589c894058dSAneesh Kumar K.V 	if (!*n) {
4590c894058dSAneesh Kumar K.V 		/* first free block exent. We need to
4591c894058dSAneesh Kumar K.V 		   protect buddy cache from being freed,
4592c9de560dSAlex Tomas 		 * otherwise we'll refresh it from
4593c9de560dSAlex Tomas 		 * on-disk bitmap and lose not-yet-available
4594c9de560dSAlex Tomas 		 * blocks */
4595c9de560dSAlex Tomas 		page_cache_get(e4b->bd_buddy_page);
4596c9de560dSAlex Tomas 		page_cache_get(e4b->bd_bitmap_page);
4597c894058dSAneesh Kumar K.V 	}
4598c894058dSAneesh Kumar K.V 	while (*n) {
4599c894058dSAneesh Kumar K.V 		parent = *n;
460018aadd47SBobi Jam 		entry = rb_entry(parent, struct ext4_free_data, efd_node);
460118aadd47SBobi Jam 		if (cluster < entry->efd_start_cluster)
4602c894058dSAneesh Kumar K.V 			n = &(*n)->rb_left;
460318aadd47SBobi Jam 		else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
4604c894058dSAneesh Kumar K.V 			n = &(*n)->rb_right;
4605c894058dSAneesh Kumar K.V 		else {
4606e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, group, 0,
460784130193STheodore Ts'o 				ext4_group_first_block_no(sb, group) +
460884130193STheodore Ts'o 				EXT4_C2B(sbi, cluster),
4609e29136f8STheodore Ts'o 				"Block already on to-be-freed list");
4610c894058dSAneesh Kumar K.V 			return 0;
4611c9de560dSAlex Tomas 		}
4612c9de560dSAlex Tomas 	}
4613c9de560dSAlex Tomas 
4614c894058dSAneesh Kumar K.V 	rb_link_node(new_node, parent, n);
4615c894058dSAneesh Kumar K.V 	rb_insert_color(new_node, &db->bb_free_root);
4616c894058dSAneesh Kumar K.V 
4617c894058dSAneesh Kumar K.V 	/* Now try to see the extent can be merged to left and right */
4618c894058dSAneesh Kumar K.V 	node = rb_prev(new_node);
4619c894058dSAneesh Kumar K.V 	if (node) {
462018aadd47SBobi Jam 		entry = rb_entry(node, struct ext4_free_data, efd_node);
46215d3ee208SDmitry Monakhov 		if (can_merge(entry, new_entry) &&
46225d3ee208SDmitry Monakhov 		    ext4_journal_callback_try_del(handle, &entry->efd_jce)) {
462318aadd47SBobi Jam 			new_entry->efd_start_cluster = entry->efd_start_cluster;
462418aadd47SBobi Jam 			new_entry->efd_count += entry->efd_count;
4625c894058dSAneesh Kumar K.V 			rb_erase(node, &(db->bb_free_root));
462618aadd47SBobi Jam 			kmem_cache_free(ext4_free_data_cachep, entry);
4627c9de560dSAlex Tomas 		}
4628c9de560dSAlex Tomas 	}
4629c894058dSAneesh Kumar K.V 
4630c894058dSAneesh Kumar K.V 	node = rb_next(new_node);
4631c894058dSAneesh Kumar K.V 	if (node) {
463218aadd47SBobi Jam 		entry = rb_entry(node, struct ext4_free_data, efd_node);
46335d3ee208SDmitry Monakhov 		if (can_merge(new_entry, entry) &&
46345d3ee208SDmitry Monakhov 		    ext4_journal_callback_try_del(handle, &entry->efd_jce)) {
463518aadd47SBobi Jam 			new_entry->efd_count += entry->efd_count;
4636c894058dSAneesh Kumar K.V 			rb_erase(node, &(db->bb_free_root));
463718aadd47SBobi Jam 			kmem_cache_free(ext4_free_data_cachep, entry);
4638c894058dSAneesh Kumar K.V 		}
4639c894058dSAneesh Kumar K.V 	}
46403e624fc7STheodore Ts'o 	/* Add the extent to transaction's private list */
464118aadd47SBobi Jam 	ext4_journal_callback_add(handle, ext4_free_data_callback,
464218aadd47SBobi Jam 				  &new_entry->efd_jce);
4643c9de560dSAlex Tomas 	return 0;
4644c9de560dSAlex Tomas }
4645c9de560dSAlex Tomas 
464644338711STheodore Ts'o /**
464744338711STheodore Ts'o  * ext4_free_blocks() -- Free given blocks and update quota
464844338711STheodore Ts'o  * @handle:		handle for this transaction
464944338711STheodore Ts'o  * @inode:		inode
465044338711STheodore Ts'o  * @block:		start physical block to free
465144338711STheodore Ts'o  * @count:		number of blocks to count
46525def1360SYongqiang Yang  * @flags:		flags used by ext4_free_blocks
4653c9de560dSAlex Tomas  */
465444338711STheodore Ts'o void ext4_free_blocks(handle_t *handle, struct inode *inode,
4655e6362609STheodore Ts'o 		      struct buffer_head *bh, ext4_fsblk_t block,
4656e6362609STheodore Ts'o 		      unsigned long count, int flags)
4657c9de560dSAlex Tomas {
465826346ff6SAneesh Kumar K.V 	struct buffer_head *bitmap_bh = NULL;
4659c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
4660c9de560dSAlex Tomas 	struct ext4_group_desc *gdp;
4661498e5f24STheodore Ts'o 	unsigned int overflow;
4662c9de560dSAlex Tomas 	ext4_grpblk_t bit;
4663c9de560dSAlex Tomas 	struct buffer_head *gd_bh;
4664c9de560dSAlex Tomas 	ext4_group_t block_group;
4665c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
4666c9de560dSAlex Tomas 	struct ext4_buddy e4b;
466784130193STheodore Ts'o 	unsigned int count_clusters;
4668c9de560dSAlex Tomas 	int err = 0;
4669c9de560dSAlex Tomas 	int ret;
4670c9de560dSAlex Tomas 
4671b10a44c3STheodore Ts'o 	might_sleep();
4672e6362609STheodore Ts'o 	if (bh) {
4673e6362609STheodore Ts'o 		if (block)
4674e6362609STheodore Ts'o 			BUG_ON(block != bh->b_blocknr);
4675e6362609STheodore Ts'o 		else
4676e6362609STheodore Ts'o 			block = bh->b_blocknr;
4677e6362609STheodore Ts'o 	}
4678c9de560dSAlex Tomas 
4679c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
46801f2acb60STheodore Ts'o 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
46811f2acb60STheodore Ts'o 	    !ext4_data_block_valid(sbi, block, count)) {
468212062dddSEric Sandeen 		ext4_error(sb, "Freeing blocks not in datazone - "
46830610b6e9STheodore Ts'o 			   "block = %llu, count = %lu", block, count);
4684c9de560dSAlex Tomas 		goto error_return;
4685c9de560dSAlex Tomas 	}
4686c9de560dSAlex Tomas 
46870610b6e9STheodore Ts'o 	ext4_debug("freeing block %llu\n", block);
4688e6362609STheodore Ts'o 	trace_ext4_free_blocks(inode, block, count, flags);
4689e6362609STheodore Ts'o 
46909c02ac97SDaeho Jeong 	if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
46919c02ac97SDaeho Jeong 		BUG_ON(count > 1);
4692e6362609STheodore Ts'o 
4693e6362609STheodore Ts'o 		ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
46949c02ac97SDaeho Jeong 			    inode, bh, block);
4695e6362609STheodore Ts'o 	}
4696e6362609STheodore Ts'o 
4697e6362609STheodore Ts'o 	/*
469884130193STheodore Ts'o 	 * If the extent to be freed does not begin on a cluster
469984130193STheodore Ts'o 	 * boundary, we need to deal with partial clusters at the
470084130193STheodore Ts'o 	 * beginning and end of the extent.  Normally we will free
470184130193STheodore Ts'o 	 * blocks at the beginning or the end unless we are explicitly
470284130193STheodore Ts'o 	 * requested to avoid doing so.
470384130193STheodore Ts'o 	 */
4704f5a44db5STheodore Ts'o 	overflow = EXT4_PBLK_COFF(sbi, block);
470584130193STheodore Ts'o 	if (overflow) {
470684130193STheodore Ts'o 		if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
470784130193STheodore Ts'o 			overflow = sbi->s_cluster_ratio - overflow;
470884130193STheodore Ts'o 			block += overflow;
470984130193STheodore Ts'o 			if (count > overflow)
471084130193STheodore Ts'o 				count -= overflow;
471184130193STheodore Ts'o 			else
471284130193STheodore Ts'o 				return;
471384130193STheodore Ts'o 		} else {
471484130193STheodore Ts'o 			block -= overflow;
471584130193STheodore Ts'o 			count += overflow;
471684130193STheodore Ts'o 		}
471784130193STheodore Ts'o 	}
4718f5a44db5STheodore Ts'o 	overflow = EXT4_LBLK_COFF(sbi, count);
471984130193STheodore Ts'o 	if (overflow) {
472084130193STheodore Ts'o 		if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
472184130193STheodore Ts'o 			if (count > overflow)
472284130193STheodore Ts'o 				count -= overflow;
472384130193STheodore Ts'o 			else
472484130193STheodore Ts'o 				return;
472584130193STheodore Ts'o 		} else
472684130193STheodore Ts'o 			count += sbi->s_cluster_ratio - overflow;
472784130193STheodore Ts'o 	}
472884130193STheodore Ts'o 
47299c02ac97SDaeho Jeong 	if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
47309c02ac97SDaeho Jeong 		int i;
4731f96c450dSDaeho Jeong 		int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
47329c02ac97SDaeho Jeong 
47339c02ac97SDaeho Jeong 		for (i = 0; i < count; i++) {
47349c02ac97SDaeho Jeong 			cond_resched();
4735f96c450dSDaeho Jeong 			if (is_metadata)
47369c02ac97SDaeho Jeong 				bh = sb_find_get_block(inode->i_sb, block + i);
4737f96c450dSDaeho Jeong 			ext4_forget(handle, is_metadata, inode, bh, block + i);
47389c02ac97SDaeho Jeong 		}
47399c02ac97SDaeho Jeong 	}
47409c02ac97SDaeho Jeong 
4741c9de560dSAlex Tomas do_more:
4742c9de560dSAlex Tomas 	overflow = 0;
4743c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4744c9de560dSAlex Tomas 
4745163a203dSDarrick J. Wong 	if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
4746163a203dSDarrick J. Wong 			ext4_get_group_info(sb, block_group))))
4747163a203dSDarrick J. Wong 		return;
4748163a203dSDarrick J. Wong 
4749c9de560dSAlex Tomas 	/*
4750c9de560dSAlex Tomas 	 * Check to see if we are freeing blocks across a group
4751c9de560dSAlex Tomas 	 * boundary.
4752c9de560dSAlex Tomas 	 */
475384130193STheodore Ts'o 	if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
475484130193STheodore Ts'o 		overflow = EXT4_C2B(sbi, bit) + count -
475584130193STheodore Ts'o 			EXT4_BLOCKS_PER_GROUP(sb);
4756c9de560dSAlex Tomas 		count -= overflow;
4757c9de560dSAlex Tomas 	}
4758810da240SLukas Czerner 	count_clusters = EXT4_NUM_B2C(sbi, count);
4759574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, block_group);
47609008a58eSDarrick J. Wong 	if (IS_ERR(bitmap_bh)) {
47619008a58eSDarrick J. Wong 		err = PTR_ERR(bitmap_bh);
47629008a58eSDarrick J. Wong 		bitmap_bh = NULL;
4763c9de560dSAlex Tomas 		goto error_return;
4764ce89f46cSAneesh Kumar K.V 	}
4765c9de560dSAlex Tomas 	gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4766ce89f46cSAneesh Kumar K.V 	if (!gdp) {
4767ce89f46cSAneesh Kumar K.V 		err = -EIO;
4768c9de560dSAlex Tomas 		goto error_return;
4769ce89f46cSAneesh Kumar K.V 	}
4770c9de560dSAlex Tomas 
4771c9de560dSAlex Tomas 	if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4772c9de560dSAlex Tomas 	    in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4773c9de560dSAlex Tomas 	    in_range(block, ext4_inode_table(sb, gdp),
4774c9de560dSAlex Tomas 		     EXT4_SB(sb)->s_itb_per_group) ||
4775c9de560dSAlex Tomas 	    in_range(block + count - 1, ext4_inode_table(sb, gdp),
4776c9de560dSAlex Tomas 		     EXT4_SB(sb)->s_itb_per_group)) {
4777c9de560dSAlex Tomas 
477812062dddSEric Sandeen 		ext4_error(sb, "Freeing blocks in system zone - "
47790610b6e9STheodore Ts'o 			   "Block = %llu, count = %lu", block, count);
4780519deca0SAneesh Kumar K.V 		/* err = 0. ext4_std_error should be a no op */
4781519deca0SAneesh Kumar K.V 		goto error_return;
4782c9de560dSAlex Tomas 	}
4783c9de560dSAlex Tomas 
4784c9de560dSAlex Tomas 	BUFFER_TRACE(bitmap_bh, "getting write access");
4785c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, bitmap_bh);
4786c9de560dSAlex Tomas 	if (err)
4787c9de560dSAlex Tomas 		goto error_return;
4788c9de560dSAlex Tomas 
4789c9de560dSAlex Tomas 	/*
4790c9de560dSAlex Tomas 	 * We are about to modify some metadata.  Call the journal APIs
4791c9de560dSAlex Tomas 	 * to unshare ->b_data if a currently-committing transaction is
4792c9de560dSAlex Tomas 	 * using it
4793c9de560dSAlex Tomas 	 */
4794c9de560dSAlex Tomas 	BUFFER_TRACE(gd_bh, "get_write_access");
4795c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, gd_bh);
4796c9de560dSAlex Tomas 	if (err)
4797c9de560dSAlex Tomas 		goto error_return;
4798c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
4799c9de560dSAlex Tomas 	{
4800c9de560dSAlex Tomas 		int i;
480184130193STheodore Ts'o 		for (i = 0; i < count_clusters; i++)
4802c9de560dSAlex Tomas 			BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4803c9de560dSAlex Tomas 	}
4804c9de560dSAlex Tomas #endif
480584130193STheodore Ts'o 	trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
4806c9de560dSAlex Tomas 
4807920313a7SAneesh Kumar K.V 	err = ext4_mb_load_buddy(sb, block_group, &e4b);
4808920313a7SAneesh Kumar K.V 	if (err)
4809920313a7SAneesh Kumar K.V 		goto error_return;
4810e6362609STheodore Ts'o 
4811f96c450dSDaeho Jeong 	/*
4812f96c450dSDaeho Jeong 	 * We need to make sure we don't reuse the freed block until after the
4813f96c450dSDaeho Jeong 	 * transaction is committed. We make an exception if the inode is to be
4814f96c450dSDaeho Jeong 	 * written in writeback mode since writeback mode has weak data
4815f96c450dSDaeho Jeong 	 * consistency guarantees.
4816f96c450dSDaeho Jeong 	 */
4817f96c450dSDaeho Jeong 	if (ext4_handle_valid(handle) &&
4818f96c450dSDaeho Jeong 	    ((flags & EXT4_FREE_BLOCKS_METADATA) ||
4819f96c450dSDaeho Jeong 	     !ext4_should_writeback_data(inode))) {
48207a2fcbf7SAneesh Kumar K.V 		struct ext4_free_data *new_entry;
48217a2fcbf7SAneesh Kumar K.V 		/*
48227444a072SMichal Hocko 		 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
48237444a072SMichal Hocko 		 * to fail.
48247a2fcbf7SAneesh Kumar K.V 		 */
48257444a072SMichal Hocko 		new_entry = kmem_cache_alloc(ext4_free_data_cachep,
48267444a072SMichal Hocko 				GFP_NOFS|__GFP_NOFAIL);
482718aadd47SBobi Jam 		new_entry->efd_start_cluster = bit;
482818aadd47SBobi Jam 		new_entry->efd_group = block_group;
482918aadd47SBobi Jam 		new_entry->efd_count = count_clusters;
483018aadd47SBobi Jam 		new_entry->efd_tid = handle->h_transaction->t_tid;
4831955ce5f5SAneesh Kumar K.V 
48327a2fcbf7SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
483384130193STheodore Ts'o 		mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
48347a2fcbf7SAneesh Kumar K.V 		ext4_mb_free_metadata(handle, &e4b, new_entry);
4835c9de560dSAlex Tomas 	} else {
48367a2fcbf7SAneesh Kumar K.V 		/* need to update group_info->bb_free and bitmap
48377a2fcbf7SAneesh Kumar K.V 		 * with group lock held. generate_buddy look at
48387a2fcbf7SAneesh Kumar K.V 		 * them with group lock_held
48397a2fcbf7SAneesh Kumar K.V 		 */
4840d71c1ae2SLukas Czerner 		if (test_opt(sb, DISCARD)) {
4841d71c1ae2SLukas Czerner 			err = ext4_issue_discard(sb, block_group, bit, count);
4842d71c1ae2SLukas Czerner 			if (err && err != -EOPNOTSUPP)
4843d71c1ae2SLukas Czerner 				ext4_msg(sb, KERN_WARNING, "discard request in"
4844d71c1ae2SLukas Czerner 					 " group:%d block:%d count:%lu failed"
4845d71c1ae2SLukas Czerner 					 " with %d", block_group, bit, count,
4846d71c1ae2SLukas Czerner 					 err);
48478f9ff189SLukas Czerner 		} else
48488f9ff189SLukas Czerner 			EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
4849d71c1ae2SLukas Czerner 
4850955ce5f5SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
485184130193STheodore Ts'o 		mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
485284130193STheodore Ts'o 		mb_free_blocks(inode, &e4b, bit, count_clusters);
4853c9de560dSAlex Tomas 	}
4854c9de560dSAlex Tomas 
4855021b65bbSTheodore Ts'o 	ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
4856021b65bbSTheodore Ts'o 	ext4_free_group_clusters_set(sb, gdp, ret);
485779f1ba49STao Ma 	ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
4858feb0ab32SDarrick J. Wong 	ext4_group_desc_csum_set(sb, block_group, gdp);
4859955ce5f5SAneesh Kumar K.V 	ext4_unlock_group(sb, block_group);
4860c9de560dSAlex Tomas 
4861772cb7c8SJose R. Santos 	if (sbi->s_log_groups_per_flex) {
4862772cb7c8SJose R. Santos 		ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
486390ba983fSTheodore Ts'o 		atomic64_add(count_clusters,
486424aaa8efSTheodore Ts'o 			     &sbi->s_flex_groups[flex_group].free_clusters);
4865772cb7c8SJose R. Santos 	}
4866772cb7c8SJose R. Santos 
48677b415bf6SAditya Kali 	if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
48687b415bf6SAditya Kali 		dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
48697d734532SJan Kara 	percpu_counter_add(&sbi->s_freeclusters_counter, count_clusters);
48707d734532SJan Kara 
48717d734532SJan Kara 	ext4_mb_unload_buddy(&e4b);
48727b415bf6SAditya Kali 
48737a2fcbf7SAneesh Kumar K.V 	/* We dirtied the bitmap block */
48747a2fcbf7SAneesh Kumar K.V 	BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
48757a2fcbf7SAneesh Kumar K.V 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
48767a2fcbf7SAneesh Kumar K.V 
4877c9de560dSAlex Tomas 	/* And the group descriptor block */
4878c9de560dSAlex Tomas 	BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
48790390131bSFrank Mayhar 	ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4880c9de560dSAlex Tomas 	if (!err)
4881c9de560dSAlex Tomas 		err = ret;
4882c9de560dSAlex Tomas 
4883c9de560dSAlex Tomas 	if (overflow && !err) {
4884c9de560dSAlex Tomas 		block += count;
4885c9de560dSAlex Tomas 		count = overflow;
4886c9de560dSAlex Tomas 		put_bh(bitmap_bh);
4887c9de560dSAlex Tomas 		goto do_more;
4888c9de560dSAlex Tomas 	}
4889c9de560dSAlex Tomas error_return:
4890c9de560dSAlex Tomas 	brelse(bitmap_bh);
4891c9de560dSAlex Tomas 	ext4_std_error(sb, err);
4892c9de560dSAlex Tomas 	return;
4893c9de560dSAlex Tomas }
48947360d173SLukas Czerner 
48957360d173SLukas Czerner /**
48960529155eSYongqiang Yang  * ext4_group_add_blocks() -- Add given blocks to an existing group
48972846e820SAmir Goldstein  * @handle:			handle to this transaction
48982846e820SAmir Goldstein  * @sb:				super block
48994907cb7bSAnatol Pomozov  * @block:			start physical block to add to the block group
49002846e820SAmir Goldstein  * @count:			number of blocks to free
49012846e820SAmir Goldstein  *
4902e73a347bSAmir Goldstein  * This marks the blocks as free in the bitmap and buddy.
49032846e820SAmir Goldstein  */
4904cc7365dfSYongqiang Yang int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
49052846e820SAmir Goldstein 			 ext4_fsblk_t block, unsigned long count)
49062846e820SAmir Goldstein {
49072846e820SAmir Goldstein 	struct buffer_head *bitmap_bh = NULL;
49082846e820SAmir Goldstein 	struct buffer_head *gd_bh;
49092846e820SAmir Goldstein 	ext4_group_t block_group;
49102846e820SAmir Goldstein 	ext4_grpblk_t bit;
49112846e820SAmir Goldstein 	unsigned int i;
49122846e820SAmir Goldstein 	struct ext4_group_desc *desc;
49132846e820SAmir Goldstein 	struct ext4_sb_info *sbi = EXT4_SB(sb);
4914e73a347bSAmir Goldstein 	struct ext4_buddy e4b;
49152846e820SAmir Goldstein 	int err = 0, ret, blk_free_count;
49162846e820SAmir Goldstein 	ext4_grpblk_t blocks_freed;
49172846e820SAmir Goldstein 
49182846e820SAmir Goldstein 	ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
49192846e820SAmir Goldstein 
49204740b830SYongqiang Yang 	if (count == 0)
49214740b830SYongqiang Yang 		return 0;
49224740b830SYongqiang Yang 
49232846e820SAmir Goldstein 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
49242846e820SAmir Goldstein 	/*
49252846e820SAmir Goldstein 	 * Check to see if we are freeing blocks across a group
49262846e820SAmir Goldstein 	 * boundary.
49272846e820SAmir Goldstein 	 */
4928cc7365dfSYongqiang Yang 	if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4929cc7365dfSYongqiang Yang 		ext4_warning(sb, "too much blocks added to group %u\n",
4930cc7365dfSYongqiang Yang 			     block_group);
4931cc7365dfSYongqiang Yang 		err = -EINVAL;
49322846e820SAmir Goldstein 		goto error_return;
4933cc7365dfSYongqiang Yang 	}
49342cd05cc3STheodore Ts'o 
49352846e820SAmir Goldstein 	bitmap_bh = ext4_read_block_bitmap(sb, block_group);
49369008a58eSDarrick J. Wong 	if (IS_ERR(bitmap_bh)) {
49379008a58eSDarrick J. Wong 		err = PTR_ERR(bitmap_bh);
49389008a58eSDarrick J. Wong 		bitmap_bh = NULL;
49392846e820SAmir Goldstein 		goto error_return;
4940cc7365dfSYongqiang Yang 	}
4941cc7365dfSYongqiang Yang 
49422846e820SAmir Goldstein 	desc = ext4_get_group_desc(sb, block_group, &gd_bh);
4943cc7365dfSYongqiang Yang 	if (!desc) {
4944cc7365dfSYongqiang Yang 		err = -EIO;
49452846e820SAmir Goldstein 		goto error_return;
4946cc7365dfSYongqiang Yang 	}
49472846e820SAmir Goldstein 
49482846e820SAmir Goldstein 	if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
49492846e820SAmir Goldstein 	    in_range(ext4_inode_bitmap(sb, desc), block, count) ||
49502846e820SAmir Goldstein 	    in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
49512846e820SAmir Goldstein 	    in_range(block + count - 1, ext4_inode_table(sb, desc),
49522846e820SAmir Goldstein 		     sbi->s_itb_per_group)) {
49532846e820SAmir Goldstein 		ext4_error(sb, "Adding blocks in system zones - "
49542846e820SAmir Goldstein 			   "Block = %llu, count = %lu",
49552846e820SAmir Goldstein 			   block, count);
4956cc7365dfSYongqiang Yang 		err = -EINVAL;
49572846e820SAmir Goldstein 		goto error_return;
49582846e820SAmir Goldstein 	}
49592846e820SAmir Goldstein 
49602cd05cc3STheodore Ts'o 	BUFFER_TRACE(bitmap_bh, "getting write access");
49612cd05cc3STheodore Ts'o 	err = ext4_journal_get_write_access(handle, bitmap_bh);
49622846e820SAmir Goldstein 	if (err)
49632846e820SAmir Goldstein 		goto error_return;
49642846e820SAmir Goldstein 
49652846e820SAmir Goldstein 	/*
49662846e820SAmir Goldstein 	 * We are about to modify some metadata.  Call the journal APIs
49672846e820SAmir Goldstein 	 * to unshare ->b_data if a currently-committing transaction is
49682846e820SAmir Goldstein 	 * using it
49692846e820SAmir Goldstein 	 */
49702846e820SAmir Goldstein 	BUFFER_TRACE(gd_bh, "get_write_access");
49712846e820SAmir Goldstein 	err = ext4_journal_get_write_access(handle, gd_bh);
49722846e820SAmir Goldstein 	if (err)
49732846e820SAmir Goldstein 		goto error_return;
4974e73a347bSAmir Goldstein 
49752846e820SAmir Goldstein 	for (i = 0, blocks_freed = 0; i < count; i++) {
49762846e820SAmir Goldstein 		BUFFER_TRACE(bitmap_bh, "clear bit");
4977e73a347bSAmir Goldstein 		if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
49782846e820SAmir Goldstein 			ext4_error(sb, "bit already cleared for block %llu",
49792846e820SAmir Goldstein 				   (ext4_fsblk_t)(block + i));
49802846e820SAmir Goldstein 			BUFFER_TRACE(bitmap_bh, "bit already cleared");
49812846e820SAmir Goldstein 		} else {
49822846e820SAmir Goldstein 			blocks_freed++;
49832846e820SAmir Goldstein 		}
49842846e820SAmir Goldstein 	}
4985e73a347bSAmir Goldstein 
4986e73a347bSAmir Goldstein 	err = ext4_mb_load_buddy(sb, block_group, &e4b);
4987e73a347bSAmir Goldstein 	if (err)
4988e73a347bSAmir Goldstein 		goto error_return;
4989e73a347bSAmir Goldstein 
4990e73a347bSAmir Goldstein 	/*
4991e73a347bSAmir Goldstein 	 * need to update group_info->bb_free and bitmap
4992e73a347bSAmir Goldstein 	 * with group lock held. generate_buddy look at
4993e73a347bSAmir Goldstein 	 * them with group lock_held
4994e73a347bSAmir Goldstein 	 */
49952846e820SAmir Goldstein 	ext4_lock_group(sb, block_group);
4996e73a347bSAmir Goldstein 	mb_clear_bits(bitmap_bh->b_data, bit, count);
4997e73a347bSAmir Goldstein 	mb_free_blocks(NULL, &e4b, bit, count);
4998021b65bbSTheodore Ts'o 	blk_free_count = blocks_freed + ext4_free_group_clusters(sb, desc);
4999021b65bbSTheodore Ts'o 	ext4_free_group_clusters_set(sb, desc, blk_free_count);
500079f1ba49STao Ma 	ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
5001feb0ab32SDarrick J. Wong 	ext4_group_desc_csum_set(sb, block_group, desc);
50022846e820SAmir Goldstein 	ext4_unlock_group(sb, block_group);
500357042651STheodore Ts'o 	percpu_counter_add(&sbi->s_freeclusters_counter,
5004810da240SLukas Czerner 			   EXT4_NUM_B2C(sbi, blocks_freed));
50052846e820SAmir Goldstein 
50062846e820SAmir Goldstein 	if (sbi->s_log_groups_per_flex) {
50072846e820SAmir Goldstein 		ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
500890ba983fSTheodore Ts'o 		atomic64_add(EXT4_NUM_B2C(sbi, blocks_freed),
500924aaa8efSTheodore Ts'o 			     &sbi->s_flex_groups[flex_group].free_clusters);
50102846e820SAmir Goldstein 	}
5011e73a347bSAmir Goldstein 
5012e73a347bSAmir Goldstein 	ext4_mb_unload_buddy(&e4b);
50132846e820SAmir Goldstein 
50142846e820SAmir Goldstein 	/* We dirtied the bitmap block */
50152846e820SAmir Goldstein 	BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
50162846e820SAmir Goldstein 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
50172846e820SAmir Goldstein 
50182846e820SAmir Goldstein 	/* And the group descriptor block */
50192846e820SAmir Goldstein 	BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
50202846e820SAmir Goldstein 	ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
50212846e820SAmir Goldstein 	if (!err)
50222846e820SAmir Goldstein 		err = ret;
50232846e820SAmir Goldstein 
50242846e820SAmir Goldstein error_return:
50252846e820SAmir Goldstein 	brelse(bitmap_bh);
50262846e820SAmir Goldstein 	ext4_std_error(sb, err);
5027cc7365dfSYongqiang Yang 	return err;
50282846e820SAmir Goldstein }
50292846e820SAmir Goldstein 
50302846e820SAmir Goldstein /**
50317360d173SLukas Czerner  * ext4_trim_extent -- function to TRIM one single free extent in the group
50327360d173SLukas Czerner  * @sb:		super block for the file system
50337360d173SLukas Czerner  * @start:	starting block of the free extent in the alloc. group
50347360d173SLukas Czerner  * @count:	number of blocks to TRIM
50357360d173SLukas Czerner  * @group:	alloc. group we are working with
50367360d173SLukas Czerner  * @e4b:	ext4 buddy for the group
50377360d173SLukas Czerner  *
50387360d173SLukas Czerner  * Trim "count" blocks starting at "start" in the "group". To assure that no
50397360d173SLukas Czerner  * one will allocate those blocks, mark it as used in buddy bitmap. This must
50407360d173SLukas Czerner  * be called with under the group lock.
50417360d173SLukas Czerner  */
5042d71c1ae2SLukas Czerner static int ext4_trim_extent(struct super_block *sb, int start, int count,
50437360d173SLukas Czerner 			     ext4_group_t group, struct ext4_buddy *e4b)
5044e2cbd587Sjon ernst __releases(bitlock)
5045e2cbd587Sjon ernst __acquires(bitlock)
50467360d173SLukas Czerner {
50477360d173SLukas Czerner 	struct ext4_free_extent ex;
5048d71c1ae2SLukas Czerner 	int ret = 0;
50497360d173SLukas Czerner 
5050b3d4c2b1STao Ma 	trace_ext4_trim_extent(sb, group, start, count);
5051b3d4c2b1STao Ma 
50527360d173SLukas Czerner 	assert_spin_locked(ext4_group_lock_ptr(sb, group));
50537360d173SLukas Czerner 
50547360d173SLukas Czerner 	ex.fe_start = start;
50557360d173SLukas Czerner 	ex.fe_group = group;
50567360d173SLukas Czerner 	ex.fe_len = count;
50577360d173SLukas Czerner 
50587360d173SLukas Czerner 	/*
50597360d173SLukas Czerner 	 * Mark blocks used, so no one can reuse them while
50607360d173SLukas Czerner 	 * being trimmed.
50617360d173SLukas Czerner 	 */
50627360d173SLukas Czerner 	mb_mark_used(e4b, &ex);
50637360d173SLukas Czerner 	ext4_unlock_group(sb, group);
5064d71c1ae2SLukas Czerner 	ret = ext4_issue_discard(sb, group, start, count);
50657360d173SLukas Czerner 	ext4_lock_group(sb, group);
50667360d173SLukas Czerner 	mb_free_blocks(NULL, e4b, start, ex.fe_len);
5067d71c1ae2SLukas Czerner 	return ret;
50687360d173SLukas Czerner }
50697360d173SLukas Czerner 
50707360d173SLukas Czerner /**
50717360d173SLukas Czerner  * ext4_trim_all_free -- function to trim all free space in alloc. group
50727360d173SLukas Czerner  * @sb:			super block for file system
507322612283STao Ma  * @group:		group to be trimmed
50747360d173SLukas Czerner  * @start:		first group block to examine
50757360d173SLukas Czerner  * @max:		last group block to examine
50767360d173SLukas Czerner  * @minblocks:		minimum extent block count
50777360d173SLukas Czerner  *
50787360d173SLukas Czerner  * ext4_trim_all_free walks through group's buddy bitmap searching for free
50797360d173SLukas Czerner  * extents. When the free block is found, ext4_trim_extent is called to TRIM
50807360d173SLukas Czerner  * the extent.
50817360d173SLukas Czerner  *
50827360d173SLukas Czerner  *
50837360d173SLukas Czerner  * ext4_trim_all_free walks through group's block bitmap searching for free
50847360d173SLukas Czerner  * extents. When the free extent is found, mark it as used in group buddy
50857360d173SLukas Czerner  * bitmap. Then issue a TRIM command on this extent and free the extent in
50867360d173SLukas Czerner  * the group buddy bitmap. This is done until whole group is scanned.
50877360d173SLukas Czerner  */
50880b75a840SLukas Czerner static ext4_grpblk_t
508978944086SLukas Czerner ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
509078944086SLukas Czerner 		   ext4_grpblk_t start, ext4_grpblk_t max,
509178944086SLukas Czerner 		   ext4_grpblk_t minblocks)
50927360d173SLukas Czerner {
50937360d173SLukas Czerner 	void *bitmap;
5094169ddc3eSTao Ma 	ext4_grpblk_t next, count = 0, free_count = 0;
509578944086SLukas Czerner 	struct ext4_buddy e4b;
5096d71c1ae2SLukas Czerner 	int ret = 0;
50977360d173SLukas Czerner 
5098b3d4c2b1STao Ma 	trace_ext4_trim_all_free(sb, group, start, max);
5099b3d4c2b1STao Ma 
510078944086SLukas Czerner 	ret = ext4_mb_load_buddy(sb, group, &e4b);
510178944086SLukas Czerner 	if (ret) {
510278944086SLukas Czerner 		ext4_error(sb, "Error in loading buddy "
510378944086SLukas Czerner 				"information for %u", group);
510478944086SLukas Czerner 		return ret;
510578944086SLukas Czerner 	}
510678944086SLukas Czerner 	bitmap = e4b.bd_bitmap;
510728739eeaSLukas Czerner 
510828739eeaSLukas Czerner 	ext4_lock_group(sb, group);
51093d56b8d2STao Ma 	if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
51103d56b8d2STao Ma 	    minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
51113d56b8d2STao Ma 		goto out;
51123d56b8d2STao Ma 
511378944086SLukas Czerner 	start = (e4b.bd_info->bb_first_free > start) ?
511478944086SLukas Czerner 		e4b.bd_info->bb_first_free : start;
51157360d173SLukas Czerner 
5116913eed83SLukas Czerner 	while (start <= max) {
5117913eed83SLukas Czerner 		start = mb_find_next_zero_bit(bitmap, max + 1, start);
5118913eed83SLukas Czerner 		if (start > max)
51197360d173SLukas Czerner 			break;
5120913eed83SLukas Czerner 		next = mb_find_next_bit(bitmap, max + 1, start);
51217360d173SLukas Czerner 
51227360d173SLukas Czerner 		if ((next - start) >= minblocks) {
5123d71c1ae2SLukas Czerner 			ret = ext4_trim_extent(sb, start,
512478944086SLukas Czerner 					       next - start, group, &e4b);
5125d71c1ae2SLukas Czerner 			if (ret && ret != -EOPNOTSUPP)
5126d71c1ae2SLukas Czerner 				break;
5127d71c1ae2SLukas Czerner 			ret = 0;
51287360d173SLukas Czerner 			count += next - start;
51297360d173SLukas Czerner 		}
5130169ddc3eSTao Ma 		free_count += next - start;
51317360d173SLukas Czerner 		start = next + 1;
51327360d173SLukas Czerner 
51337360d173SLukas Czerner 		if (fatal_signal_pending(current)) {
51347360d173SLukas Czerner 			count = -ERESTARTSYS;
51357360d173SLukas Czerner 			break;
51367360d173SLukas Czerner 		}
51377360d173SLukas Czerner 
51387360d173SLukas Czerner 		if (need_resched()) {
51397360d173SLukas Czerner 			ext4_unlock_group(sb, group);
51407360d173SLukas Czerner 			cond_resched();
51417360d173SLukas Czerner 			ext4_lock_group(sb, group);
51427360d173SLukas Czerner 		}
51437360d173SLukas Czerner 
5144169ddc3eSTao Ma 		if ((e4b.bd_info->bb_free - free_count) < minblocks)
51457360d173SLukas Czerner 			break;
51467360d173SLukas Czerner 	}
51473d56b8d2STao Ma 
5148d71c1ae2SLukas Czerner 	if (!ret) {
5149d71c1ae2SLukas Czerner 		ret = count;
51503d56b8d2STao Ma 		EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
5151d71c1ae2SLukas Czerner 	}
51523d56b8d2STao Ma out:
51537360d173SLukas Czerner 	ext4_unlock_group(sb, group);
515478944086SLukas Czerner 	ext4_mb_unload_buddy(&e4b);
51557360d173SLukas Czerner 
51567360d173SLukas Czerner 	ext4_debug("trimmed %d blocks in the group %d\n",
51577360d173SLukas Czerner 		count, group);
51587360d173SLukas Czerner 
5159d71c1ae2SLukas Czerner 	return ret;
51607360d173SLukas Czerner }
51617360d173SLukas Czerner 
51627360d173SLukas Czerner /**
51637360d173SLukas Czerner  * ext4_trim_fs() -- trim ioctl handle function
51647360d173SLukas Czerner  * @sb:			superblock for filesystem
51657360d173SLukas Czerner  * @range:		fstrim_range structure
51667360d173SLukas Czerner  *
51677360d173SLukas Czerner  * start:	First Byte to trim
51687360d173SLukas Czerner  * len:		number of Bytes to trim from start
51697360d173SLukas Czerner  * minlen:	minimum extent length in Bytes
51707360d173SLukas Czerner  * ext4_trim_fs goes through all allocation groups containing Bytes from
51717360d173SLukas Czerner  * start to start+len. For each such a group ext4_trim_all_free function
51727360d173SLukas Czerner  * is invoked to trim all free space.
51737360d173SLukas Czerner  */
51747360d173SLukas Czerner int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
51757360d173SLukas Czerner {
517678944086SLukas Czerner 	struct ext4_group_info *grp;
5177913eed83SLukas Czerner 	ext4_group_t group, first_group, last_group;
51787137d7a4STheodore Ts'o 	ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5179913eed83SLukas Czerner 	uint64_t start, end, minlen, trimmed = 0;
51800f0a25bfSJan Kara 	ext4_fsblk_t first_data_blk =
51810f0a25bfSJan Kara 			le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5182913eed83SLukas Czerner 	ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
51837360d173SLukas Czerner 	int ret = 0;
51847360d173SLukas Czerner 
51857360d173SLukas Czerner 	start = range->start >> sb->s_blocksize_bits;
5186913eed83SLukas Czerner 	end = start + (range->len >> sb->s_blocksize_bits) - 1;
5187aaf7d73eSLukas Czerner 	minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5188aaf7d73eSLukas Czerner 			      range->minlen >> sb->s_blocksize_bits);
51897360d173SLukas Czerner 
51905de35e8dSLukas Czerner 	if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
51915de35e8dSLukas Czerner 	    start >= max_blks ||
51925de35e8dSLukas Czerner 	    range->len < sb->s_blocksize)
51937360d173SLukas Czerner 		return -EINVAL;
5194913eed83SLukas Czerner 	if (end >= max_blks)
5195913eed83SLukas Czerner 		end = max_blks - 1;
5196913eed83SLukas Czerner 	if (end <= first_data_blk)
519722f10457STao Ma 		goto out;
5198913eed83SLukas Czerner 	if (start < first_data_blk)
51990f0a25bfSJan Kara 		start = first_data_blk;
52007360d173SLukas Czerner 
5201913eed83SLukas Czerner 	/* Determine first and last group to examine based on start and end */
52027360d173SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
52037137d7a4STheodore Ts'o 				     &first_group, &first_cluster);
5204913eed83SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
52057137d7a4STheodore Ts'o 				     &last_group, &last_cluster);
52067360d173SLukas Czerner 
5207913eed83SLukas Czerner 	/* end now represents the last cluster to discard in this group */
5208913eed83SLukas Czerner 	end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
52097360d173SLukas Czerner 
52107360d173SLukas Czerner 	for (group = first_group; group <= last_group; group++) {
521178944086SLukas Czerner 		grp = ext4_get_group_info(sb, group);
521278944086SLukas Czerner 		/* We only do this if the grp has never been initialized */
521378944086SLukas Czerner 		if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
521478944086SLukas Czerner 			ret = ext4_mb_init_group(sb, group);
521578944086SLukas Czerner 			if (ret)
52167360d173SLukas Czerner 				break;
52177360d173SLukas Czerner 		}
52187360d173SLukas Czerner 
52190ba08517STao Ma 		/*
5220913eed83SLukas Czerner 		 * For all the groups except the last one, last cluster will
5221913eed83SLukas Czerner 		 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
5222913eed83SLukas Czerner 		 * change it for the last group, note that last_cluster is
5223913eed83SLukas Czerner 		 * already computed earlier by ext4_get_group_no_and_offset()
52240ba08517STao Ma 		 */
5225913eed83SLukas Czerner 		if (group == last_group)
5226913eed83SLukas Czerner 			end = last_cluster;
52277360d173SLukas Czerner 
522878944086SLukas Czerner 		if (grp->bb_free >= minlen) {
52297137d7a4STheodore Ts'o 			cnt = ext4_trim_all_free(sb, group, first_cluster,
5230913eed83SLukas Czerner 						end, minlen);
52317360d173SLukas Czerner 			if (cnt < 0) {
52327360d173SLukas Czerner 				ret = cnt;
52337360d173SLukas Czerner 				break;
52347360d173SLukas Czerner 			}
52357360d173SLukas Czerner 			trimmed += cnt;
523621e7fd22SLukas Czerner 		}
5237913eed83SLukas Czerner 
5238913eed83SLukas Czerner 		/*
5239913eed83SLukas Czerner 		 * For every group except the first one, we are sure
5240913eed83SLukas Czerner 		 * that the first cluster to discard will be cluster #0.
5241913eed83SLukas Czerner 		 */
52427137d7a4STheodore Ts'o 		first_cluster = 0;
52437360d173SLukas Czerner 	}
52447360d173SLukas Czerner 
52453d56b8d2STao Ma 	if (!ret)
52463d56b8d2STao Ma 		atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
52473d56b8d2STao Ma 
524822f10457STao Ma out:
5249aaf7d73eSLukas Czerner 	range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
52507360d173SLukas Czerner 	return ret;
52517360d173SLukas Czerner }
5252