xref: /openbmc/linux/fs/ext4/mballoc.c (revision 21e7fd22)
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"
266ba495e9STheodore Ts'o #include <linux/debugfs.h>
275a0e3ad6STejun Heo #include <linux/slab.h>
289bffad1eSTheodore Ts'o #include <trace/events/ext4.h>
299bffad1eSTheodore Ts'o 
30c9de560dSAlex Tomas /*
31c9de560dSAlex Tomas  * MUSTDO:
32c9de560dSAlex Tomas  *   - test ext4_ext_search_left() and ext4_ext_search_right()
33c9de560dSAlex Tomas  *   - search for metadata in few groups
34c9de560dSAlex Tomas  *
35c9de560dSAlex Tomas  * TODO v4:
36c9de560dSAlex Tomas  *   - normalization should take into account whether file is still open
37c9de560dSAlex Tomas  *   - discard preallocations if no free space left (policy?)
38c9de560dSAlex Tomas  *   - don't normalize tails
39c9de560dSAlex Tomas  *   - quota
40c9de560dSAlex Tomas  *   - reservation for superuser
41c9de560dSAlex Tomas  *
42c9de560dSAlex Tomas  * TODO v3:
43c9de560dSAlex Tomas  *   - bitmap read-ahead (proposed by Oleg Drokin aka green)
44c9de560dSAlex Tomas  *   - track min/max extents in each group for better group selection
45c9de560dSAlex Tomas  *   - mb_mark_used() may allocate chunk right after splitting buddy
46c9de560dSAlex Tomas  *   - tree of groups sorted by number of free blocks
47c9de560dSAlex Tomas  *   - error handling
48c9de560dSAlex Tomas  */
49c9de560dSAlex Tomas 
50c9de560dSAlex Tomas /*
51c9de560dSAlex Tomas  * The allocation request involve request for multiple number of blocks
52c9de560dSAlex Tomas  * near to the goal(block) value specified.
53c9de560dSAlex Tomas  *
54b713a5ecSTheodore Ts'o  * During initialization phase of the allocator we decide to use the
55b713a5ecSTheodore Ts'o  * group preallocation or inode preallocation depending on the size of
56b713a5ecSTheodore Ts'o  * the file. The size of the file could be the resulting file size we
57b713a5ecSTheodore Ts'o  * would have after allocation, or the current file size, which ever
58b713a5ecSTheodore Ts'o  * is larger. If the size is less than sbi->s_mb_stream_request we
59b713a5ecSTheodore Ts'o  * select to use the group preallocation. The default value of
60b713a5ecSTheodore Ts'o  * s_mb_stream_request is 16 blocks. This can also be tuned via
61b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
62b713a5ecSTheodore Ts'o  * terms of number of blocks.
63c9de560dSAlex Tomas  *
64c9de560dSAlex Tomas  * The main motivation for having small file use group preallocation is to
65b713a5ecSTheodore Ts'o  * ensure that we have small files closer together on the disk.
66c9de560dSAlex Tomas  *
67b713a5ecSTheodore Ts'o  * First stage the allocator looks at the inode prealloc list,
68b713a5ecSTheodore Ts'o  * ext4_inode_info->i_prealloc_list, which contains list of prealloc
69b713a5ecSTheodore Ts'o  * spaces for this particular inode. The inode prealloc space is
70b713a5ecSTheodore Ts'o  * represented as:
71c9de560dSAlex Tomas  *
72c9de560dSAlex Tomas  * pa_lstart -> the logical start block for this prealloc space
73c9de560dSAlex Tomas  * pa_pstart -> the physical start block for this prealloc space
7453accfa9STheodore Ts'o  * pa_len    -> length for this prealloc space (in clusters)
7553accfa9STheodore Ts'o  * pa_free   ->  free space available in this prealloc space (in clusters)
76c9de560dSAlex Tomas  *
77c9de560dSAlex Tomas  * The inode preallocation space is used looking at the _logical_ start
78c9de560dSAlex Tomas  * block. If only the logical file block falls within the range of prealloc
79caaf7a29STao Ma  * space we will consume the particular prealloc space. This makes sure that
80caaf7a29STao Ma  * we have contiguous physical blocks representing the file blocks
81c9de560dSAlex Tomas  *
82c9de560dSAlex Tomas  * The important thing to be noted in case of inode prealloc space is that
83c9de560dSAlex Tomas  * we don't modify the values associated to inode prealloc space except
84c9de560dSAlex Tomas  * pa_free.
85c9de560dSAlex Tomas  *
86c9de560dSAlex Tomas  * If we are not able to find blocks in the inode prealloc space and if we
87c9de560dSAlex Tomas  * have the group allocation flag set then we look at the locality group
88caaf7a29STao Ma  * prealloc space. These are per CPU prealloc list represented as
89c9de560dSAlex Tomas  *
90c9de560dSAlex Tomas  * ext4_sb_info.s_locality_groups[smp_processor_id()]
91c9de560dSAlex Tomas  *
92c9de560dSAlex Tomas  * The reason for having a per cpu locality group is to reduce the contention
93c9de560dSAlex Tomas  * between CPUs. It is possible to get scheduled at this point.
94c9de560dSAlex Tomas  *
95c9de560dSAlex Tomas  * The locality group prealloc space is used looking at whether we have
9625985edcSLucas De Marchi  * enough free space (pa_free) within the prealloc space.
97c9de560dSAlex Tomas  *
98c9de560dSAlex Tomas  * If we can't allocate blocks via inode prealloc or/and locality group
99c9de560dSAlex Tomas  * prealloc then we look at the buddy cache. The buddy cache is represented
100c9de560dSAlex Tomas  * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
101c9de560dSAlex Tomas  * mapped to the buddy and bitmap information regarding different
102c9de560dSAlex Tomas  * groups. The buddy information is attached to buddy cache inode so that
103c9de560dSAlex Tomas  * we can access them through the page cache. The information regarding
104c9de560dSAlex Tomas  * each group is loaded via ext4_mb_load_buddy.  The information involve
105c9de560dSAlex Tomas  * block bitmap and buddy information. The information are stored in the
106c9de560dSAlex Tomas  * inode as:
107c9de560dSAlex Tomas  *
108c9de560dSAlex Tomas  *  {                        page                        }
109c3a326a6SAneesh Kumar K.V  *  [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
110c9de560dSAlex Tomas  *
111c9de560dSAlex Tomas  *
112c9de560dSAlex Tomas  * one block each for bitmap and buddy information.  So for each group we
113c9de560dSAlex Tomas  * take up 2 blocks. A page can contain blocks_per_page (PAGE_CACHE_SIZE /
114c9de560dSAlex Tomas  * blocksize) blocks.  So it can have information regarding groups_per_page
115c9de560dSAlex Tomas  * which is blocks_per_page/2
116c9de560dSAlex Tomas  *
117c9de560dSAlex Tomas  * The buddy cache inode is not stored on disk. The inode is thrown
118c9de560dSAlex Tomas  * away when the filesystem is unmounted.
119c9de560dSAlex Tomas  *
120c9de560dSAlex Tomas  * We look for count number of blocks in the buddy cache. If we were able
121c9de560dSAlex Tomas  * to locate that many free blocks we return with additional information
122c9de560dSAlex Tomas  * regarding rest of the contiguous physical block available
123c9de560dSAlex Tomas  *
124c9de560dSAlex Tomas  * Before allocating blocks via buddy cache we normalize the request
125c9de560dSAlex Tomas  * blocks. This ensure we ask for more blocks that we needed. The extra
126c9de560dSAlex Tomas  * blocks that we get after allocation is added to the respective prealloc
127c9de560dSAlex Tomas  * list. In case of inode preallocation we follow a list of heuristics
128c9de560dSAlex Tomas  * based on file size. This can be found in ext4_mb_normalize_request. If
129c9de560dSAlex Tomas  * we are doing a group prealloc we try to normalize the request to
13027baebb8STheodore Ts'o  * sbi->s_mb_group_prealloc.  The default value of s_mb_group_prealloc is
13127baebb8STheodore Ts'o  * dependent on the cluster size; for non-bigalloc file systems, it is
132c9de560dSAlex Tomas  * 512 blocks. This can be tuned via
133d7a1fee1SDan Ehrenberg  * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
134c9de560dSAlex Tomas  * terms of number of blocks. If we have mounted the file system with -O
135c9de560dSAlex Tomas  * stripe=<value> option the group prealloc request is normalized to the
136d7a1fee1SDan Ehrenberg  * the smallest multiple of the stripe value (sbi->s_stripe) which is
137d7a1fee1SDan Ehrenberg  * greater than the default mb_group_prealloc.
138c9de560dSAlex Tomas  *
139d7a1fee1SDan Ehrenberg  * The regular allocator (using the buddy cache) supports a few tunables.
140c9de560dSAlex Tomas  *
141b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_min_to_scan
142b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_max_to_scan
143b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_order2_req
144c9de560dSAlex Tomas  *
145b713a5ecSTheodore Ts'o  * The regular allocator uses buddy scan only if the request len is power of
146c9de560dSAlex Tomas  * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
147c9de560dSAlex Tomas  * value of s_mb_order2_reqs can be tuned via
148b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_order2_req.  If the request len is equal to
149af901ca1SAndré Goddard Rosa  * stripe size (sbi->s_stripe), we try to search for contiguous block in
150b713a5ecSTheodore Ts'o  * stripe size. This should result in better allocation on RAID setups. If
151b713a5ecSTheodore Ts'o  * not, we search in the specific group using bitmap for best extents. The
152b713a5ecSTheodore Ts'o  * tunable min_to_scan and max_to_scan control the behaviour here.
153c9de560dSAlex Tomas  * min_to_scan indicate how long the mballoc __must__ look for a best
154b713a5ecSTheodore Ts'o  * extent and max_to_scan indicates how long the mballoc __can__ look for a
155c9de560dSAlex Tomas  * best extent in the found extents. Searching for the blocks starts with
156c9de560dSAlex Tomas  * the group specified as the goal value in allocation context via
157c9de560dSAlex Tomas  * ac_g_ex. Each group is first checked based on the criteria whether it
158caaf7a29STao Ma  * can be used for allocation. ext4_mb_good_group explains how the groups are
159c9de560dSAlex Tomas  * checked.
160c9de560dSAlex Tomas  *
161c9de560dSAlex Tomas  * Both the prealloc space are getting populated as above. So for the first
162c9de560dSAlex Tomas  * request we will hit the buddy cache which will result in this prealloc
163c9de560dSAlex Tomas  * space getting filled. The prealloc space is then later used for the
164c9de560dSAlex Tomas  * subsequent request.
165c9de560dSAlex Tomas  */
166c9de560dSAlex Tomas 
167c9de560dSAlex Tomas /*
168c9de560dSAlex Tomas  * mballoc operates on the following data:
169c9de560dSAlex Tomas  *  - on-disk bitmap
170c9de560dSAlex Tomas  *  - in-core buddy (actually includes buddy and bitmap)
171c9de560dSAlex Tomas  *  - preallocation descriptors (PAs)
172c9de560dSAlex Tomas  *
173c9de560dSAlex Tomas  * there are two types of preallocations:
174c9de560dSAlex Tomas  *  - inode
175c9de560dSAlex Tomas  *    assiged to specific inode and can be used for this inode only.
176c9de560dSAlex Tomas  *    it describes part of inode's space preallocated to specific
177c9de560dSAlex Tomas  *    physical blocks. any block from that preallocated can be used
178c9de560dSAlex Tomas  *    independent. the descriptor just tracks number of blocks left
179c9de560dSAlex Tomas  *    unused. so, before taking some block from descriptor, one must
180c9de560dSAlex Tomas  *    make sure corresponded logical block isn't allocated yet. this
181c9de560dSAlex Tomas  *    also means that freeing any block within descriptor's range
182c9de560dSAlex Tomas  *    must discard all preallocated blocks.
183c9de560dSAlex Tomas  *  - locality group
184c9de560dSAlex Tomas  *    assigned to specific locality group which does not translate to
185c9de560dSAlex Tomas  *    permanent set of inodes: inode can join and leave group. space
186c9de560dSAlex Tomas  *    from this type of preallocation can be used for any inode. thus
187c9de560dSAlex Tomas  *    it's consumed from the beginning to the end.
188c9de560dSAlex Tomas  *
189c9de560dSAlex Tomas  * relation between them can be expressed as:
190c9de560dSAlex Tomas  *    in-core buddy = on-disk bitmap + preallocation descriptors
191c9de560dSAlex Tomas  *
192c9de560dSAlex Tomas  * this mean blocks mballoc considers used are:
193c9de560dSAlex Tomas  *  - allocated blocks (persistent)
194c9de560dSAlex Tomas  *  - preallocated blocks (non-persistent)
195c9de560dSAlex Tomas  *
196c9de560dSAlex Tomas  * consistency in mballoc world means that at any time a block is either
197c9de560dSAlex Tomas  * free or used in ALL structures. notice: "any time" should not be read
198c9de560dSAlex Tomas  * literally -- time is discrete and delimited by locks.
199c9de560dSAlex Tomas  *
200c9de560dSAlex Tomas  *  to keep it simple, we don't use block numbers, instead we count number of
201c9de560dSAlex Tomas  *  blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
202c9de560dSAlex Tomas  *
203c9de560dSAlex Tomas  * all operations can be expressed as:
204c9de560dSAlex Tomas  *  - init buddy:			buddy = on-disk + PAs
205c9de560dSAlex Tomas  *  - new PA:				buddy += N; PA = N
206c9de560dSAlex Tomas  *  - use inode PA:			on-disk += N; PA -= N
207c9de560dSAlex Tomas  *  - discard inode PA			buddy -= on-disk - PA; PA = 0
208c9de560dSAlex Tomas  *  - use locality group PA		on-disk += N; PA -= N
209c9de560dSAlex Tomas  *  - discard locality group PA		buddy -= PA; PA = 0
210c9de560dSAlex Tomas  *  note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
211c9de560dSAlex Tomas  *        is used in real operation because we can't know actual used
212c9de560dSAlex Tomas  *        bits from PA, only from on-disk bitmap
213c9de560dSAlex Tomas  *
214c9de560dSAlex Tomas  * if we follow this strict logic, then all operations above should be atomic.
215c9de560dSAlex Tomas  * given some of them can block, we'd have to use something like semaphores
216c9de560dSAlex Tomas  * killing performance on high-end SMP hardware. let's try to relax it using
217c9de560dSAlex Tomas  * the following knowledge:
218c9de560dSAlex Tomas  *  1) if buddy is referenced, it's already initialized
219c9de560dSAlex Tomas  *  2) while block is used in buddy and the buddy is referenced,
220c9de560dSAlex Tomas  *     nobody can re-allocate that block
221c9de560dSAlex Tomas  *  3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
222c9de560dSAlex Tomas  *     bit set and PA claims same block, it's OK. IOW, one can set bit in
223c9de560dSAlex Tomas  *     on-disk bitmap if buddy has same bit set or/and PA covers corresponded
224c9de560dSAlex Tomas  *     block
225c9de560dSAlex Tomas  *
226c9de560dSAlex Tomas  * so, now we're building a concurrency table:
227c9de560dSAlex Tomas  *  - init buddy vs.
228c9de560dSAlex Tomas  *    - new PA
229c9de560dSAlex Tomas  *      blocks for PA are allocated in the buddy, buddy must be referenced
230c9de560dSAlex Tomas  *      until PA is linked to allocation group to avoid concurrent buddy init
231c9de560dSAlex Tomas  *    - use inode PA
232c9de560dSAlex Tomas  *      we need to make sure that either on-disk bitmap or PA has uptodate data
233c9de560dSAlex Tomas  *      given (3) we care that PA-=N operation doesn't interfere with init
234c9de560dSAlex Tomas  *    - discard inode PA
235c9de560dSAlex Tomas  *      the simplest way would be to have buddy initialized by the discard
236c9de560dSAlex Tomas  *    - use locality group PA
237c9de560dSAlex Tomas  *      again PA-=N must be serialized with init
238c9de560dSAlex Tomas  *    - discard locality group PA
239c9de560dSAlex Tomas  *      the simplest way would be to have buddy initialized by the discard
240c9de560dSAlex Tomas  *  - new PA vs.
241c9de560dSAlex Tomas  *    - use inode PA
242c9de560dSAlex Tomas  *      i_data_sem serializes them
243c9de560dSAlex Tomas  *    - discard inode PA
244c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
245c9de560dSAlex Tomas  *    - use locality group PA
246c9de560dSAlex Tomas  *      some mutex should serialize them
247c9de560dSAlex Tomas  *    - discard locality group PA
248c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
249c9de560dSAlex Tomas  *  - use inode PA
250c9de560dSAlex Tomas  *    - use inode PA
251c9de560dSAlex Tomas  *      i_data_sem or another mutex should 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  *      nothing wrong here -- they're different PAs covering different blocks
256c9de560dSAlex Tomas  *    - discard locality group PA
257c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
258c9de560dSAlex Tomas  *
259c9de560dSAlex Tomas  * now we're ready to make few consequences:
260c9de560dSAlex Tomas  *  - PA is referenced and while it is no discard is possible
261c9de560dSAlex Tomas  *  - PA is referenced until block isn't marked in on-disk bitmap
262c9de560dSAlex Tomas  *  - PA changes only after on-disk bitmap
263c9de560dSAlex Tomas  *  - discard must not compete with init. either init is done before
264c9de560dSAlex Tomas  *    any discard or they're serialized somehow
265c9de560dSAlex Tomas  *  - buddy init as sum of on-disk bitmap and PAs is done atomically
266c9de560dSAlex Tomas  *
267c9de560dSAlex Tomas  * a special case when we've used PA to emptiness. no need to modify buddy
268c9de560dSAlex Tomas  * in this case, but we should care about concurrent init
269c9de560dSAlex Tomas  *
270c9de560dSAlex Tomas  */
271c9de560dSAlex Tomas 
272c9de560dSAlex Tomas  /*
273c9de560dSAlex Tomas  * Logic in few words:
274c9de560dSAlex Tomas  *
275c9de560dSAlex Tomas  *  - allocation:
276c9de560dSAlex Tomas  *    load group
277c9de560dSAlex Tomas  *    find blocks
278c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
279c9de560dSAlex Tomas  *    release group
280c9de560dSAlex Tomas  *
281c9de560dSAlex Tomas  *  - use preallocation:
282c9de560dSAlex Tomas  *    find proper PA (per-inode or group)
283c9de560dSAlex Tomas  *    load group
284c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
285c9de560dSAlex Tomas  *    release group
286c9de560dSAlex Tomas  *    release PA
287c9de560dSAlex Tomas  *
288c9de560dSAlex Tomas  *  - free:
289c9de560dSAlex Tomas  *    load group
290c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
291c9de560dSAlex Tomas  *    release group
292c9de560dSAlex Tomas  *
293c9de560dSAlex Tomas  *  - discard preallocations in group:
294c9de560dSAlex Tomas  *    mark PAs deleted
295c9de560dSAlex Tomas  *    move them onto local list
296c9de560dSAlex Tomas  *    load on-disk bitmap
297c9de560dSAlex Tomas  *    load group
298c9de560dSAlex Tomas  *    remove PA from object (inode or locality group)
299c9de560dSAlex Tomas  *    mark free blocks in-core
300c9de560dSAlex Tomas  *
301c9de560dSAlex Tomas  *  - discard inode's preallocations:
302c9de560dSAlex Tomas  */
303c9de560dSAlex Tomas 
304c9de560dSAlex Tomas /*
305c9de560dSAlex Tomas  * Locking rules
306c9de560dSAlex Tomas  *
307c9de560dSAlex Tomas  * Locks:
308c9de560dSAlex Tomas  *  - bitlock on a group	(group)
309c9de560dSAlex Tomas  *  - object (inode/locality)	(object)
310c9de560dSAlex Tomas  *  - per-pa lock		(pa)
311c9de560dSAlex Tomas  *
312c9de560dSAlex Tomas  * Paths:
313c9de560dSAlex Tomas  *  - new pa
314c9de560dSAlex Tomas  *    object
315c9de560dSAlex Tomas  *    group
316c9de560dSAlex Tomas  *
317c9de560dSAlex Tomas  *  - find and use pa:
318c9de560dSAlex Tomas  *    pa
319c9de560dSAlex Tomas  *
320c9de560dSAlex Tomas  *  - release consumed pa:
321c9de560dSAlex Tomas  *    pa
322c9de560dSAlex Tomas  *    group
323c9de560dSAlex Tomas  *    object
324c9de560dSAlex Tomas  *
325c9de560dSAlex Tomas  *  - generate in-core bitmap:
326c9de560dSAlex Tomas  *    group
327c9de560dSAlex Tomas  *        pa
328c9de560dSAlex Tomas  *
329c9de560dSAlex Tomas  *  - discard all for given object (inode, locality group):
330c9de560dSAlex Tomas  *    object
331c9de560dSAlex Tomas  *        pa
332c9de560dSAlex Tomas  *    group
333c9de560dSAlex Tomas  *
334c9de560dSAlex Tomas  *  - discard all for given group:
335c9de560dSAlex Tomas  *    group
336c9de560dSAlex Tomas  *        pa
337c9de560dSAlex Tomas  *    group
338c9de560dSAlex Tomas  *        object
339c9de560dSAlex Tomas  *
340c9de560dSAlex Tomas  */
341c3a326a6SAneesh Kumar K.V static struct kmem_cache *ext4_pspace_cachep;
342c3a326a6SAneesh Kumar K.V static struct kmem_cache *ext4_ac_cachep;
34318aadd47SBobi Jam static struct kmem_cache *ext4_free_data_cachep;
344fb1813f4SCurt Wohlgemuth 
345fb1813f4SCurt Wohlgemuth /* We create slab caches for groupinfo data structures based on the
346fb1813f4SCurt Wohlgemuth  * superblock block size.  There will be one per mounted filesystem for
347fb1813f4SCurt Wohlgemuth  * each unique s_blocksize_bits */
3482892c15dSEric Sandeen #define NR_GRPINFO_CACHES 8
349fb1813f4SCurt Wohlgemuth static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
350fb1813f4SCurt Wohlgemuth 
3512892c15dSEric Sandeen static const char *ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
3522892c15dSEric Sandeen 	"ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
3532892c15dSEric Sandeen 	"ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
3542892c15dSEric Sandeen 	"ext4_groupinfo_64k", "ext4_groupinfo_128k"
3552892c15dSEric Sandeen };
3562892c15dSEric Sandeen 
357c3a326a6SAneesh Kumar K.V static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
358c3a326a6SAneesh Kumar K.V 					ext4_group_t group);
3597a2fcbf7SAneesh Kumar K.V static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3607a2fcbf7SAneesh Kumar K.V 						ext4_group_t group);
36118aadd47SBobi Jam static void ext4_free_data_callback(struct super_block *sb,
36218aadd47SBobi Jam 				struct ext4_journal_cb_entry *jce, int rc);
363c3a326a6SAneesh Kumar K.V 
364ffad0a44SAneesh Kumar K.V static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
365ffad0a44SAneesh Kumar K.V {
366c9de560dSAlex Tomas #if BITS_PER_LONG == 64
367ffad0a44SAneesh Kumar K.V 	*bit += ((unsigned long) addr & 7UL) << 3;
368ffad0a44SAneesh Kumar K.V 	addr = (void *) ((unsigned long) addr & ~7UL);
369c9de560dSAlex Tomas #elif BITS_PER_LONG == 32
370ffad0a44SAneesh Kumar K.V 	*bit += ((unsigned long) addr & 3UL) << 3;
371ffad0a44SAneesh Kumar K.V 	addr = (void *) ((unsigned long) addr & ~3UL);
372c9de560dSAlex Tomas #else
373c9de560dSAlex Tomas #error "how many bits you are?!"
374c9de560dSAlex Tomas #endif
375ffad0a44SAneesh Kumar K.V 	return addr;
376ffad0a44SAneesh Kumar K.V }
377c9de560dSAlex Tomas 
378c9de560dSAlex Tomas static inline int mb_test_bit(int bit, void *addr)
379c9de560dSAlex Tomas {
380c9de560dSAlex Tomas 	/*
381c9de560dSAlex Tomas 	 * ext4_test_bit on architecture like powerpc
382c9de560dSAlex Tomas 	 * needs unsigned long aligned address
383c9de560dSAlex Tomas 	 */
384ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
385c9de560dSAlex Tomas 	return ext4_test_bit(bit, addr);
386c9de560dSAlex Tomas }
387c9de560dSAlex Tomas 
388c9de560dSAlex Tomas static inline void mb_set_bit(int bit, void *addr)
389c9de560dSAlex Tomas {
390ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
391c9de560dSAlex Tomas 	ext4_set_bit(bit, addr);
392c9de560dSAlex Tomas }
393c9de560dSAlex Tomas 
394c9de560dSAlex Tomas static inline void mb_clear_bit(int bit, void *addr)
395c9de560dSAlex Tomas {
396ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
397c9de560dSAlex Tomas 	ext4_clear_bit(bit, addr);
398c9de560dSAlex Tomas }
399c9de560dSAlex Tomas 
400ffad0a44SAneesh Kumar K.V static inline int mb_find_next_zero_bit(void *addr, int max, int start)
401ffad0a44SAneesh Kumar K.V {
402e7dfb246SAneesh Kumar K.V 	int fix = 0, ret, tmpmax;
403ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&fix, addr);
404e7dfb246SAneesh Kumar K.V 	tmpmax = max + fix;
405ffad0a44SAneesh Kumar K.V 	start += fix;
406ffad0a44SAneesh Kumar K.V 
407e7dfb246SAneesh Kumar K.V 	ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
408e7dfb246SAneesh Kumar K.V 	if (ret > max)
409e7dfb246SAneesh Kumar K.V 		return max;
410e7dfb246SAneesh Kumar K.V 	return ret;
411ffad0a44SAneesh Kumar K.V }
412ffad0a44SAneesh Kumar K.V 
413ffad0a44SAneesh Kumar K.V static inline int mb_find_next_bit(void *addr, int max, int start)
414ffad0a44SAneesh Kumar K.V {
415e7dfb246SAneesh Kumar K.V 	int fix = 0, ret, tmpmax;
416ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&fix, addr);
417e7dfb246SAneesh Kumar K.V 	tmpmax = max + fix;
418ffad0a44SAneesh Kumar K.V 	start += fix;
419ffad0a44SAneesh Kumar K.V 
420e7dfb246SAneesh Kumar K.V 	ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
421e7dfb246SAneesh Kumar K.V 	if (ret > max)
422e7dfb246SAneesh Kumar K.V 		return max;
423e7dfb246SAneesh Kumar K.V 	return ret;
424ffad0a44SAneesh Kumar K.V }
425ffad0a44SAneesh Kumar K.V 
426c9de560dSAlex Tomas static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
427c9de560dSAlex Tomas {
428c9de560dSAlex Tomas 	char *bb;
429c9de560dSAlex Tomas 
430c5e8f3f3STheodore Ts'o 	BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
431c9de560dSAlex Tomas 	BUG_ON(max == NULL);
432c9de560dSAlex Tomas 
433c9de560dSAlex Tomas 	if (order > e4b->bd_blkbits + 1) {
434c9de560dSAlex Tomas 		*max = 0;
435c9de560dSAlex Tomas 		return NULL;
436c9de560dSAlex Tomas 	}
437c9de560dSAlex Tomas 
438c9de560dSAlex Tomas 	/* at order 0 we see each particular block */
43984b775a3SColy Li 	if (order == 0) {
440c9de560dSAlex Tomas 		*max = 1 << (e4b->bd_blkbits + 3);
441c5e8f3f3STheodore Ts'o 		return e4b->bd_bitmap;
44284b775a3SColy Li 	}
443c9de560dSAlex Tomas 
444c5e8f3f3STheodore Ts'o 	bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
445c9de560dSAlex Tomas 	*max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
446c9de560dSAlex Tomas 
447c9de560dSAlex Tomas 	return bb;
448c9de560dSAlex Tomas }
449c9de560dSAlex Tomas 
450c9de560dSAlex Tomas #ifdef DOUBLE_CHECK
451c9de560dSAlex Tomas static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
452c9de560dSAlex Tomas 			   int first, int count)
453c9de560dSAlex Tomas {
454c9de560dSAlex Tomas 	int i;
455c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
456c9de560dSAlex Tomas 
457c9de560dSAlex Tomas 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
458c9de560dSAlex Tomas 		return;
459bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
460c9de560dSAlex Tomas 	for (i = 0; i < count; i++) {
461c9de560dSAlex Tomas 		if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
462c9de560dSAlex Tomas 			ext4_fsblk_t blocknr;
4635661bd68SAkinobu Mita 
4645661bd68SAkinobu Mita 			blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
46553accfa9STheodore Ts'o 			blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
4665d1b1b3fSAneesh Kumar K.V 			ext4_grp_locked_error(sb, e4b->bd_group,
467e29136f8STheodore Ts'o 					      inode ? inode->i_ino : 0,
468e29136f8STheodore Ts'o 					      blocknr,
469e29136f8STheodore Ts'o 					      "freeing block already freed "
470e29136f8STheodore Ts'o 					      "(bit %u)",
471e29136f8STheodore Ts'o 					      first + i);
472c9de560dSAlex Tomas 		}
473c9de560dSAlex Tomas 		mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
474c9de560dSAlex Tomas 	}
475c9de560dSAlex Tomas }
476c9de560dSAlex Tomas 
477c9de560dSAlex Tomas static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
478c9de560dSAlex Tomas {
479c9de560dSAlex Tomas 	int i;
480c9de560dSAlex Tomas 
481c9de560dSAlex Tomas 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
482c9de560dSAlex Tomas 		return;
483bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
484c9de560dSAlex Tomas 	for (i = 0; i < count; i++) {
485c9de560dSAlex Tomas 		BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
486c9de560dSAlex Tomas 		mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
487c9de560dSAlex Tomas 	}
488c9de560dSAlex Tomas }
489c9de560dSAlex Tomas 
490c9de560dSAlex Tomas static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
491c9de560dSAlex Tomas {
492c9de560dSAlex Tomas 	if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
493c9de560dSAlex Tomas 		unsigned char *b1, *b2;
494c9de560dSAlex Tomas 		int i;
495c9de560dSAlex Tomas 		b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
496c9de560dSAlex Tomas 		b2 = (unsigned char *) bitmap;
497c9de560dSAlex Tomas 		for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
498c9de560dSAlex Tomas 			if (b1[i] != b2[i]) {
4999d8b9ec4STheodore Ts'o 				ext4_msg(e4b->bd_sb, KERN_ERR,
5009d8b9ec4STheodore Ts'o 					 "corruption in group %u "
5014776004fSTheodore Ts'o 					 "at byte %u(%u): %x in copy != %x "
5029d8b9ec4STheodore Ts'o 					 "on disk/prealloc",
503c9de560dSAlex Tomas 					 e4b->bd_group, i, i * 8, b1[i], b2[i]);
504c9de560dSAlex Tomas 				BUG();
505c9de560dSAlex Tomas 			}
506c9de560dSAlex Tomas 		}
507c9de560dSAlex Tomas 	}
508c9de560dSAlex Tomas }
509c9de560dSAlex Tomas 
510c9de560dSAlex Tomas #else
511c9de560dSAlex Tomas static inline void mb_free_blocks_double(struct inode *inode,
512c9de560dSAlex Tomas 				struct ext4_buddy *e4b, int first, int count)
513c9de560dSAlex Tomas {
514c9de560dSAlex Tomas 	return;
515c9de560dSAlex Tomas }
516c9de560dSAlex Tomas static inline void mb_mark_used_double(struct ext4_buddy *e4b,
517c9de560dSAlex Tomas 						int first, int count)
518c9de560dSAlex Tomas {
519c9de560dSAlex Tomas 	return;
520c9de560dSAlex Tomas }
521c9de560dSAlex Tomas static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
522c9de560dSAlex Tomas {
523c9de560dSAlex Tomas 	return;
524c9de560dSAlex Tomas }
525c9de560dSAlex Tomas #endif
526c9de560dSAlex Tomas 
527c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
528c9de560dSAlex Tomas 
529c9de560dSAlex Tomas #define MB_CHECK_ASSERT(assert)						\
530c9de560dSAlex Tomas do {									\
531c9de560dSAlex Tomas 	if (!(assert)) {						\
532c9de560dSAlex Tomas 		printk(KERN_EMERG					\
533c9de560dSAlex Tomas 			"Assertion failure in %s() at %s:%d: \"%s\"\n",	\
534c9de560dSAlex Tomas 			function, file, line, # assert);		\
535c9de560dSAlex Tomas 		BUG();							\
536c9de560dSAlex Tomas 	}								\
537c9de560dSAlex Tomas } while (0)
538c9de560dSAlex Tomas 
539c9de560dSAlex Tomas static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
540c9de560dSAlex Tomas 				const char *function, int line)
541c9de560dSAlex Tomas {
542c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
543c9de560dSAlex Tomas 	int order = e4b->bd_blkbits + 1;
544c9de560dSAlex Tomas 	int max;
545c9de560dSAlex Tomas 	int max2;
546c9de560dSAlex Tomas 	int i;
547c9de560dSAlex Tomas 	int j;
548c9de560dSAlex Tomas 	int k;
549c9de560dSAlex Tomas 	int count;
550c9de560dSAlex Tomas 	struct ext4_group_info *grp;
551c9de560dSAlex Tomas 	int fragments = 0;
552c9de560dSAlex Tomas 	int fstart;
553c9de560dSAlex Tomas 	struct list_head *cur;
554c9de560dSAlex Tomas 	void *buddy;
555c9de560dSAlex Tomas 	void *buddy2;
556c9de560dSAlex Tomas 
557c9de560dSAlex Tomas 	{
558c9de560dSAlex Tomas 		static int mb_check_counter;
559c9de560dSAlex Tomas 		if (mb_check_counter++ % 100 != 0)
560c9de560dSAlex Tomas 			return 0;
561c9de560dSAlex Tomas 	}
562c9de560dSAlex Tomas 
563c9de560dSAlex Tomas 	while (order > 1) {
564c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, order, &max);
565c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy);
566c9de560dSAlex Tomas 		buddy2 = mb_find_buddy(e4b, order - 1, &max2);
567c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy2);
568c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy != buddy2);
569c9de560dSAlex Tomas 		MB_CHECK_ASSERT(max * 2 == max2);
570c9de560dSAlex Tomas 
571c9de560dSAlex Tomas 		count = 0;
572c9de560dSAlex Tomas 		for (i = 0; i < max; i++) {
573c9de560dSAlex Tomas 
574c9de560dSAlex Tomas 			if (mb_test_bit(i, buddy)) {
575c9de560dSAlex Tomas 				/* only single bit in buddy2 may be 1 */
576c9de560dSAlex Tomas 				if (!mb_test_bit(i << 1, buddy2)) {
577c9de560dSAlex Tomas 					MB_CHECK_ASSERT(
578c9de560dSAlex Tomas 						mb_test_bit((i<<1)+1, buddy2));
579c9de560dSAlex Tomas 				} else if (!mb_test_bit((i << 1) + 1, buddy2)) {
580c9de560dSAlex Tomas 					MB_CHECK_ASSERT(
581c9de560dSAlex Tomas 						mb_test_bit(i << 1, buddy2));
582c9de560dSAlex Tomas 				}
583c9de560dSAlex Tomas 				continue;
584c9de560dSAlex Tomas 			}
585c9de560dSAlex Tomas 
5860a10da73SRobin Dong 			/* both bits in buddy2 must be 1 */
587c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
588c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
589c9de560dSAlex Tomas 
590c9de560dSAlex Tomas 			for (j = 0; j < (1 << order); j++) {
591c9de560dSAlex Tomas 				k = (i * (1 << order)) + j;
592c9de560dSAlex Tomas 				MB_CHECK_ASSERT(
593c5e8f3f3STheodore Ts'o 					!mb_test_bit(k, e4b->bd_bitmap));
594c9de560dSAlex Tomas 			}
595c9de560dSAlex Tomas 			count++;
596c9de560dSAlex Tomas 		}
597c9de560dSAlex Tomas 		MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
598c9de560dSAlex Tomas 		order--;
599c9de560dSAlex Tomas 	}
600c9de560dSAlex Tomas 
601c9de560dSAlex Tomas 	fstart = -1;
602c9de560dSAlex Tomas 	buddy = mb_find_buddy(e4b, 0, &max);
603c9de560dSAlex Tomas 	for (i = 0; i < max; i++) {
604c9de560dSAlex Tomas 		if (!mb_test_bit(i, buddy)) {
605c9de560dSAlex Tomas 			MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
606c9de560dSAlex Tomas 			if (fstart == -1) {
607c9de560dSAlex Tomas 				fragments++;
608c9de560dSAlex Tomas 				fstart = i;
609c9de560dSAlex Tomas 			}
610c9de560dSAlex Tomas 			continue;
611c9de560dSAlex Tomas 		}
612c9de560dSAlex Tomas 		fstart = -1;
613c9de560dSAlex Tomas 		/* check used bits only */
614c9de560dSAlex Tomas 		for (j = 0; j < e4b->bd_blkbits + 1; j++) {
615c9de560dSAlex Tomas 			buddy2 = mb_find_buddy(e4b, j, &max2);
616c9de560dSAlex Tomas 			k = i >> j;
617c9de560dSAlex Tomas 			MB_CHECK_ASSERT(k < max2);
618c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
619c9de560dSAlex Tomas 		}
620c9de560dSAlex Tomas 	}
621c9de560dSAlex Tomas 	MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
622c9de560dSAlex Tomas 	MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
623c9de560dSAlex Tomas 
624c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, e4b->bd_group);
625c9de560dSAlex Tomas 	list_for_each(cur, &grp->bb_prealloc_list) {
626c9de560dSAlex Tomas 		ext4_group_t groupnr;
627c9de560dSAlex Tomas 		struct ext4_prealloc_space *pa;
62860bd63d1SSolofo Ramangalahy 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
62960bd63d1SSolofo Ramangalahy 		ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
630c9de560dSAlex Tomas 		MB_CHECK_ASSERT(groupnr == e4b->bd_group);
63160bd63d1SSolofo Ramangalahy 		for (i = 0; i < pa->pa_len; i++)
632c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
633c9de560dSAlex Tomas 	}
634c9de560dSAlex Tomas 	return 0;
635c9de560dSAlex Tomas }
636c9de560dSAlex Tomas #undef MB_CHECK_ASSERT
637c9de560dSAlex Tomas #define mb_check_buddy(e4b) __mb_check_buddy(e4b,	\
63846e665e9SHarvey Harrison 					__FILE__, __func__, __LINE__)
639c9de560dSAlex Tomas #else
640c9de560dSAlex Tomas #define mb_check_buddy(e4b)
641c9de560dSAlex Tomas #endif
642c9de560dSAlex Tomas 
6437c786059SColy Li /*
6447c786059SColy Li  * Divide blocks started from @first with length @len into
6457c786059SColy Li  * smaller chunks with power of 2 blocks.
6467c786059SColy Li  * Clear the bits in bitmap which the blocks of the chunk(s) covered,
6477c786059SColy Li  * then increase bb_counters[] for corresponded chunk size.
6487c786059SColy Li  */
649c9de560dSAlex Tomas static void ext4_mb_mark_free_simple(struct super_block *sb,
650a36b4498SEric Sandeen 				void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
651c9de560dSAlex Tomas 					struct ext4_group_info *grp)
652c9de560dSAlex Tomas {
653c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
654a36b4498SEric Sandeen 	ext4_grpblk_t min;
655a36b4498SEric Sandeen 	ext4_grpblk_t max;
656a36b4498SEric Sandeen 	ext4_grpblk_t chunk;
657c9de560dSAlex Tomas 	unsigned short border;
658c9de560dSAlex Tomas 
6597137d7a4STheodore Ts'o 	BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
660c9de560dSAlex Tomas 
661c9de560dSAlex Tomas 	border = 2 << sb->s_blocksize_bits;
662c9de560dSAlex Tomas 
663c9de560dSAlex Tomas 	while (len > 0) {
664c9de560dSAlex Tomas 		/* find how many blocks can be covered since this position */
665c9de560dSAlex Tomas 		max = ffs(first | border) - 1;
666c9de560dSAlex Tomas 
667c9de560dSAlex Tomas 		/* find how many blocks of power 2 we need to mark */
668c9de560dSAlex Tomas 		min = fls(len) - 1;
669c9de560dSAlex Tomas 
670c9de560dSAlex Tomas 		if (max < min)
671c9de560dSAlex Tomas 			min = max;
672c9de560dSAlex Tomas 		chunk = 1 << min;
673c9de560dSAlex Tomas 
674c9de560dSAlex Tomas 		/* mark multiblock chunks only */
675c9de560dSAlex Tomas 		grp->bb_counters[min]++;
676c9de560dSAlex Tomas 		if (min > 0)
677c9de560dSAlex Tomas 			mb_clear_bit(first >> min,
678c9de560dSAlex Tomas 				     buddy + sbi->s_mb_offsets[min]);
679c9de560dSAlex Tomas 
680c9de560dSAlex Tomas 		len -= chunk;
681c9de560dSAlex Tomas 		first += chunk;
682c9de560dSAlex Tomas 	}
683c9de560dSAlex Tomas }
684c9de560dSAlex Tomas 
6858a57d9d6SCurt Wohlgemuth /*
6868a57d9d6SCurt Wohlgemuth  * Cache the order of the largest free extent we have available in this block
6878a57d9d6SCurt Wohlgemuth  * group.
6888a57d9d6SCurt Wohlgemuth  */
6898a57d9d6SCurt Wohlgemuth static void
6908a57d9d6SCurt Wohlgemuth mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
6918a57d9d6SCurt Wohlgemuth {
6928a57d9d6SCurt Wohlgemuth 	int i;
6938a57d9d6SCurt Wohlgemuth 	int bits;
6948a57d9d6SCurt Wohlgemuth 
6958a57d9d6SCurt Wohlgemuth 	grp->bb_largest_free_order = -1; /* uninit */
6968a57d9d6SCurt Wohlgemuth 
6978a57d9d6SCurt Wohlgemuth 	bits = sb->s_blocksize_bits + 1;
6988a57d9d6SCurt Wohlgemuth 	for (i = bits; i >= 0; i--) {
6998a57d9d6SCurt Wohlgemuth 		if (grp->bb_counters[i] > 0) {
7008a57d9d6SCurt Wohlgemuth 			grp->bb_largest_free_order = i;
7018a57d9d6SCurt Wohlgemuth 			break;
7028a57d9d6SCurt Wohlgemuth 		}
7038a57d9d6SCurt Wohlgemuth 	}
7048a57d9d6SCurt Wohlgemuth }
7058a57d9d6SCurt Wohlgemuth 
706089ceeccSEric Sandeen static noinline_for_stack
707089ceeccSEric Sandeen void ext4_mb_generate_buddy(struct super_block *sb,
708c9de560dSAlex Tomas 				void *buddy, void *bitmap, ext4_group_t group)
709c9de560dSAlex Tomas {
710c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
7117137d7a4STheodore Ts'o 	ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
712a36b4498SEric Sandeen 	ext4_grpblk_t i = 0;
713a36b4498SEric Sandeen 	ext4_grpblk_t first;
714a36b4498SEric Sandeen 	ext4_grpblk_t len;
715c9de560dSAlex Tomas 	unsigned free = 0;
716c9de560dSAlex Tomas 	unsigned fragments = 0;
717c9de560dSAlex Tomas 	unsigned long long period = get_cycles();
718c9de560dSAlex Tomas 
719c9de560dSAlex Tomas 	/* initialize buddy from bitmap which is aggregation
720c9de560dSAlex Tomas 	 * of on-disk bitmap and preallocations */
721ffad0a44SAneesh Kumar K.V 	i = mb_find_next_zero_bit(bitmap, max, 0);
722c9de560dSAlex Tomas 	grp->bb_first_free = i;
723c9de560dSAlex Tomas 	while (i < max) {
724c9de560dSAlex Tomas 		fragments++;
725c9de560dSAlex Tomas 		first = i;
726ffad0a44SAneesh Kumar K.V 		i = mb_find_next_bit(bitmap, max, i);
727c9de560dSAlex Tomas 		len = i - first;
728c9de560dSAlex Tomas 		free += len;
729c9de560dSAlex Tomas 		if (len > 1)
730c9de560dSAlex Tomas 			ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
731c9de560dSAlex Tomas 		else
732c9de560dSAlex Tomas 			grp->bb_counters[0]++;
733c9de560dSAlex Tomas 		if (i < max)
734ffad0a44SAneesh Kumar K.V 			i = mb_find_next_zero_bit(bitmap, max, i);
735c9de560dSAlex Tomas 	}
736c9de560dSAlex Tomas 	grp->bb_fragments = fragments;
737c9de560dSAlex Tomas 
738c9de560dSAlex Tomas 	if (free != grp->bb_free) {
739e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0,
74053accfa9STheodore Ts'o 				      "%u clusters in bitmap, %u in gd",
741e29136f8STheodore Ts'o 				      free, grp->bb_free);
742e56eb659SAneesh Kumar K.V 		/*
743e56eb659SAneesh Kumar K.V 		 * If we intent to continue, we consider group descritor
744e56eb659SAneesh Kumar K.V 		 * corrupt and update bb_free using bitmap value
745e56eb659SAneesh Kumar K.V 		 */
746c9de560dSAlex Tomas 		grp->bb_free = free;
747c9de560dSAlex Tomas 	}
7488a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, grp);
749c9de560dSAlex Tomas 
750c9de560dSAlex Tomas 	clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
751c9de560dSAlex Tomas 
752c9de560dSAlex Tomas 	period = get_cycles() - period;
753c9de560dSAlex Tomas 	spin_lock(&EXT4_SB(sb)->s_bal_lock);
754c9de560dSAlex Tomas 	EXT4_SB(sb)->s_mb_buddies_generated++;
755c9de560dSAlex Tomas 	EXT4_SB(sb)->s_mb_generation_time += period;
756c9de560dSAlex Tomas 	spin_unlock(&EXT4_SB(sb)->s_bal_lock);
757c9de560dSAlex Tomas }
758c9de560dSAlex Tomas 
759c9de560dSAlex Tomas /* The buddy information is attached the buddy cache inode
760c9de560dSAlex Tomas  * for convenience. The information regarding each group
761c9de560dSAlex Tomas  * is loaded via ext4_mb_load_buddy. The information involve
762c9de560dSAlex Tomas  * block bitmap and buddy information. The information are
763c9de560dSAlex Tomas  * stored in the inode as
764c9de560dSAlex Tomas  *
765c9de560dSAlex Tomas  * {                        page                        }
766c3a326a6SAneesh Kumar K.V  * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
767c9de560dSAlex Tomas  *
768c9de560dSAlex Tomas  *
769c9de560dSAlex Tomas  * one block each for bitmap and buddy information.
770c9de560dSAlex Tomas  * So for each group we take up 2 blocks. A page can
771c9de560dSAlex Tomas  * contain blocks_per_page (PAGE_CACHE_SIZE / blocksize)  blocks.
772c9de560dSAlex Tomas  * So it can have information regarding groups_per_page which
773c9de560dSAlex Tomas  * is blocks_per_page/2
7748a57d9d6SCurt Wohlgemuth  *
7758a57d9d6SCurt Wohlgemuth  * Locking note:  This routine takes the block group lock of all groups
7768a57d9d6SCurt Wohlgemuth  * for this page; do not hold this lock when calling this routine!
777c9de560dSAlex Tomas  */
778c9de560dSAlex Tomas 
779c9de560dSAlex Tomas static int ext4_mb_init_cache(struct page *page, char *incore)
780c9de560dSAlex Tomas {
7818df9675fSTheodore Ts'o 	ext4_group_t ngroups;
782c9de560dSAlex Tomas 	int blocksize;
783c9de560dSAlex Tomas 	int blocks_per_page;
784c9de560dSAlex Tomas 	int groups_per_page;
785c9de560dSAlex Tomas 	int err = 0;
786c9de560dSAlex Tomas 	int i;
787813e5727STheodore Ts'o 	ext4_group_t first_group, group;
788c9de560dSAlex Tomas 	int first_block;
789c9de560dSAlex Tomas 	struct super_block *sb;
790c9de560dSAlex Tomas 	struct buffer_head *bhs;
791c9de560dSAlex Tomas 	struct buffer_head **bh;
792c9de560dSAlex Tomas 	struct inode *inode;
793c9de560dSAlex Tomas 	char *data;
794c9de560dSAlex Tomas 	char *bitmap;
7959b8b7d35SAmir Goldstein 	struct ext4_group_info *grinfo;
796c9de560dSAlex Tomas 
7976ba495e9STheodore Ts'o 	mb_debug(1, "init page %lu\n", page->index);
798c9de560dSAlex Tomas 
799c9de560dSAlex Tomas 	inode = page->mapping->host;
800c9de560dSAlex Tomas 	sb = inode->i_sb;
8018df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
802c9de560dSAlex Tomas 	blocksize = 1 << inode->i_blkbits;
803c9de560dSAlex Tomas 	blocks_per_page = PAGE_CACHE_SIZE / blocksize;
804c9de560dSAlex Tomas 
805c9de560dSAlex Tomas 	groups_per_page = blocks_per_page >> 1;
806c9de560dSAlex Tomas 	if (groups_per_page == 0)
807c9de560dSAlex Tomas 		groups_per_page = 1;
808c9de560dSAlex Tomas 
809c9de560dSAlex Tomas 	/* allocate buffer_heads to read bitmaps */
810c9de560dSAlex Tomas 	if (groups_per_page > 1) {
811c9de560dSAlex Tomas 		i = sizeof(struct buffer_head *) * groups_per_page;
812c9de560dSAlex Tomas 		bh = kzalloc(i, GFP_NOFS);
813813e5727STheodore Ts'o 		if (bh == NULL) {
814813e5727STheodore Ts'o 			err = -ENOMEM;
815c9de560dSAlex Tomas 			goto out;
816813e5727STheodore Ts'o 		}
817c9de560dSAlex Tomas 	} else
818c9de560dSAlex Tomas 		bh = &bhs;
819c9de560dSAlex Tomas 
820c9de560dSAlex Tomas 	first_group = page->index * blocks_per_page / 2;
821c9de560dSAlex Tomas 
822c9de560dSAlex Tomas 	/* read all groups the page covers into the cache */
823813e5727STheodore Ts'o 	for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
824813e5727STheodore Ts'o 		if (group >= ngroups)
825c9de560dSAlex Tomas 			break;
826c9de560dSAlex Tomas 
827813e5727STheodore Ts'o 		grinfo = ext4_get_group_info(sb, group);
8289b8b7d35SAmir Goldstein 		/*
8299b8b7d35SAmir Goldstein 		 * If page is uptodate then we came here after online resize
8309b8b7d35SAmir Goldstein 		 * which added some new uninitialized group info structs, so
8319b8b7d35SAmir Goldstein 		 * we must skip all initialized uptodate buddies on the page,
8329b8b7d35SAmir Goldstein 		 * which may be currently in use by an allocating task.
8339b8b7d35SAmir Goldstein 		 */
8349b8b7d35SAmir Goldstein 		if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
8359b8b7d35SAmir Goldstein 			bh[i] = NULL;
8369b8b7d35SAmir Goldstein 			continue;
8379b8b7d35SAmir Goldstein 		}
838813e5727STheodore Ts'o 		if (!(bh[i] = ext4_read_block_bitmap_nowait(sb, group))) {
839c9de560dSAlex Tomas 			err = -ENOMEM;
840c9de560dSAlex Tomas 			goto out;
8412ccb5fb9SAneesh Kumar K.V 		}
842813e5727STheodore Ts'o 		mb_debug(1, "read bitmap for group %u\n", group);
843c9de560dSAlex Tomas 	}
844c9de560dSAlex Tomas 
845c9de560dSAlex Tomas 	/* wait for I/O completion */
846813e5727STheodore Ts'o 	for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
847813e5727STheodore Ts'o 		if (bh[i] && ext4_wait_block_bitmap(sb, group, bh[i])) {
848c9de560dSAlex Tomas 			err = -EIO;
849c9de560dSAlex Tomas 			goto out;
850813e5727STheodore Ts'o 		}
851813e5727STheodore Ts'o 	}
852c9de560dSAlex Tomas 
853c9de560dSAlex Tomas 	first_block = page->index * blocks_per_page;
854c9de560dSAlex Tomas 	for (i = 0; i < blocks_per_page; i++) {
855c9de560dSAlex Tomas 		int group;
856c9de560dSAlex Tomas 
857c9de560dSAlex Tomas 		group = (first_block + i) >> 1;
8588df9675fSTheodore Ts'o 		if (group >= ngroups)
859c9de560dSAlex Tomas 			break;
860c9de560dSAlex Tomas 
8619b8b7d35SAmir Goldstein 		if (!bh[group - first_group])
8629b8b7d35SAmir Goldstein 			/* skip initialized uptodate buddy */
8639b8b7d35SAmir Goldstein 			continue;
8649b8b7d35SAmir Goldstein 
865c9de560dSAlex Tomas 		/*
866c9de560dSAlex Tomas 		 * data carry information regarding this
867c9de560dSAlex Tomas 		 * particular group in the format specified
868c9de560dSAlex Tomas 		 * above
869c9de560dSAlex Tomas 		 *
870c9de560dSAlex Tomas 		 */
871c9de560dSAlex Tomas 		data = page_address(page) + (i * blocksize);
872c9de560dSAlex Tomas 		bitmap = bh[group - first_group]->b_data;
873c9de560dSAlex Tomas 
874c9de560dSAlex Tomas 		/*
875c9de560dSAlex Tomas 		 * We place the buddy block and bitmap block
876c9de560dSAlex Tomas 		 * close together
877c9de560dSAlex Tomas 		 */
878c9de560dSAlex Tomas 		if ((first_block + i) & 1) {
879c9de560dSAlex Tomas 			/* this is block of buddy */
880c9de560dSAlex Tomas 			BUG_ON(incore == NULL);
8816ba495e9STheodore Ts'o 			mb_debug(1, "put buddy for group %u in page %lu/%x\n",
882c9de560dSAlex Tomas 				group, page->index, i * blocksize);
883f307333eSTheodore Ts'o 			trace_ext4_mb_buddy_bitmap_load(sb, group);
884c9de560dSAlex Tomas 			grinfo = ext4_get_group_info(sb, group);
885c9de560dSAlex Tomas 			grinfo->bb_fragments = 0;
886c9de560dSAlex Tomas 			memset(grinfo->bb_counters, 0,
8871927805eSEric Sandeen 			       sizeof(*grinfo->bb_counters) *
8881927805eSEric Sandeen 				(sb->s_blocksize_bits+2));
889c9de560dSAlex Tomas 			/*
890c9de560dSAlex Tomas 			 * incore got set to the group block bitmap below
891c9de560dSAlex Tomas 			 */
8927a2fcbf7SAneesh Kumar K.V 			ext4_lock_group(sb, group);
8939b8b7d35SAmir Goldstein 			/* init the buddy */
8949b8b7d35SAmir Goldstein 			memset(data, 0xff, blocksize);
895c9de560dSAlex Tomas 			ext4_mb_generate_buddy(sb, data, incore, group);
8967a2fcbf7SAneesh Kumar K.V 			ext4_unlock_group(sb, group);
897c9de560dSAlex Tomas 			incore = NULL;
898c9de560dSAlex Tomas 		} else {
899c9de560dSAlex Tomas 			/* this is block of bitmap */
900c9de560dSAlex Tomas 			BUG_ON(incore != NULL);
9016ba495e9STheodore Ts'o 			mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
902c9de560dSAlex Tomas 				group, page->index, i * blocksize);
903f307333eSTheodore Ts'o 			trace_ext4_mb_bitmap_load(sb, group);
904c9de560dSAlex Tomas 
905c9de560dSAlex Tomas 			/* see comments in ext4_mb_put_pa() */
906c9de560dSAlex Tomas 			ext4_lock_group(sb, group);
907c9de560dSAlex Tomas 			memcpy(data, bitmap, blocksize);
908c9de560dSAlex Tomas 
909c9de560dSAlex Tomas 			/* mark all preallocated blks used in in-core bitmap */
910c9de560dSAlex Tomas 			ext4_mb_generate_from_pa(sb, data, group);
9117a2fcbf7SAneesh Kumar K.V 			ext4_mb_generate_from_freelist(sb, data, group);
912c9de560dSAlex Tomas 			ext4_unlock_group(sb, group);
913c9de560dSAlex Tomas 
914c9de560dSAlex Tomas 			/* set incore so that the buddy information can be
915c9de560dSAlex Tomas 			 * generated using this
916c9de560dSAlex Tomas 			 */
917c9de560dSAlex Tomas 			incore = data;
918c9de560dSAlex Tomas 		}
919c9de560dSAlex Tomas 	}
920c9de560dSAlex Tomas 	SetPageUptodate(page);
921c9de560dSAlex Tomas 
922c9de560dSAlex Tomas out:
923c9de560dSAlex Tomas 	if (bh) {
9249b8b7d35SAmir Goldstein 		for (i = 0; i < groups_per_page; i++)
925c9de560dSAlex Tomas 			brelse(bh[i]);
926c9de560dSAlex Tomas 		if (bh != &bhs)
927c9de560dSAlex Tomas 			kfree(bh);
928c9de560dSAlex Tomas 	}
929c9de560dSAlex Tomas 	return err;
930c9de560dSAlex Tomas }
931c9de560dSAlex Tomas 
9328a57d9d6SCurt Wohlgemuth /*
9332de8807bSAmir Goldstein  * Lock the buddy and bitmap pages. This make sure other parallel init_group
9342de8807bSAmir Goldstein  * on the same buddy page doesn't happen whild holding the buddy page lock.
9352de8807bSAmir Goldstein  * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
9362de8807bSAmir Goldstein  * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
937eee4adc7SEric Sandeen  */
9382de8807bSAmir Goldstein static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
9392de8807bSAmir Goldstein 		ext4_group_t group, struct ext4_buddy *e4b)
940eee4adc7SEric Sandeen {
9412de8807bSAmir Goldstein 	struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
9422de8807bSAmir Goldstein 	int block, pnum, poff;
943eee4adc7SEric Sandeen 	int blocks_per_page;
9442de8807bSAmir Goldstein 	struct page *page;
9452de8807bSAmir Goldstein 
9462de8807bSAmir Goldstein 	e4b->bd_buddy_page = NULL;
9472de8807bSAmir Goldstein 	e4b->bd_bitmap_page = NULL;
948eee4adc7SEric Sandeen 
949eee4adc7SEric Sandeen 	blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
950eee4adc7SEric Sandeen 	/*
951eee4adc7SEric Sandeen 	 * the buddy cache inode stores the block bitmap
952eee4adc7SEric Sandeen 	 * and buddy information in consecutive blocks.
953eee4adc7SEric Sandeen 	 * So for each group we need two blocks.
954eee4adc7SEric Sandeen 	 */
955eee4adc7SEric Sandeen 	block = group * 2;
956eee4adc7SEric Sandeen 	pnum = block / blocks_per_page;
9572de8807bSAmir Goldstein 	poff = block % blocks_per_page;
9582de8807bSAmir Goldstein 	page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
9592de8807bSAmir Goldstein 	if (!page)
9602de8807bSAmir Goldstein 		return -EIO;
9612de8807bSAmir Goldstein 	BUG_ON(page->mapping != inode->i_mapping);
9622de8807bSAmir Goldstein 	e4b->bd_bitmap_page = page;
9632de8807bSAmir Goldstein 	e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
964eee4adc7SEric Sandeen 
9652de8807bSAmir Goldstein 	if (blocks_per_page >= 2) {
9662de8807bSAmir Goldstein 		/* buddy and bitmap are on the same page */
9672de8807bSAmir Goldstein 		return 0;
968eee4adc7SEric Sandeen 	}
969eee4adc7SEric Sandeen 
9702de8807bSAmir Goldstein 	block++;
971eee4adc7SEric Sandeen 	pnum = block / blocks_per_page;
9722de8807bSAmir Goldstein 	poff = block % blocks_per_page;
9732de8807bSAmir Goldstein 	page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
9742de8807bSAmir Goldstein 	if (!page)
9752de8807bSAmir Goldstein 		return -EIO;
9762de8807bSAmir Goldstein 	BUG_ON(page->mapping != inode->i_mapping);
9772de8807bSAmir Goldstein 	e4b->bd_buddy_page = page;
9782de8807bSAmir Goldstein 	return 0;
979eee4adc7SEric Sandeen }
980eee4adc7SEric Sandeen 
9812de8807bSAmir Goldstein static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
9822de8807bSAmir Goldstein {
9832de8807bSAmir Goldstein 	if (e4b->bd_bitmap_page) {
9842de8807bSAmir Goldstein 		unlock_page(e4b->bd_bitmap_page);
9852de8807bSAmir Goldstein 		page_cache_release(e4b->bd_bitmap_page);
9862de8807bSAmir Goldstein 	}
9872de8807bSAmir Goldstein 	if (e4b->bd_buddy_page) {
9882de8807bSAmir Goldstein 		unlock_page(e4b->bd_buddy_page);
9892de8807bSAmir Goldstein 		page_cache_release(e4b->bd_buddy_page);
9902de8807bSAmir Goldstein 	}
991eee4adc7SEric Sandeen }
992eee4adc7SEric Sandeen 
993eee4adc7SEric Sandeen /*
9948a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
9958a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
9968a57d9d6SCurt Wohlgemuth  * calling this routine!
9978a57d9d6SCurt Wohlgemuth  */
998b6a758ecSAneesh Kumar K.V static noinline_for_stack
999b6a758ecSAneesh Kumar K.V int ext4_mb_init_group(struct super_block *sb, ext4_group_t group)
1000b6a758ecSAneesh Kumar K.V {
1001b6a758ecSAneesh Kumar K.V 
1002b6a758ecSAneesh Kumar K.V 	struct ext4_group_info *this_grp;
10032de8807bSAmir Goldstein 	struct ext4_buddy e4b;
10042de8807bSAmir Goldstein 	struct page *page;
10052de8807bSAmir Goldstein 	int ret = 0;
1006b6a758ecSAneesh Kumar K.V 
1007b6a758ecSAneesh Kumar K.V 	mb_debug(1, "init group %u\n", group);
1008b6a758ecSAneesh Kumar K.V 	this_grp = ext4_get_group_info(sb, group);
1009b6a758ecSAneesh Kumar K.V 	/*
101008c3a813SAneesh Kumar K.V 	 * This ensures that we don't reinit the buddy cache
101108c3a813SAneesh Kumar K.V 	 * page which map to the group from which we are already
101208c3a813SAneesh Kumar K.V 	 * allocating. If we are looking at the buddy cache we would
101308c3a813SAneesh Kumar K.V 	 * have taken a reference using ext4_mb_load_buddy and that
10142de8807bSAmir Goldstein 	 * would have pinned buddy page to page cache.
1015b6a758ecSAneesh Kumar K.V 	 */
10162de8807bSAmir Goldstein 	ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b);
10172de8807bSAmir Goldstein 	if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1018b6a758ecSAneesh Kumar K.V 		/*
1019b6a758ecSAneesh Kumar K.V 		 * somebody initialized the group
1020b6a758ecSAneesh Kumar K.V 		 * return without doing anything
1021b6a758ecSAneesh Kumar K.V 		 */
1022b6a758ecSAneesh Kumar K.V 		goto err;
1023b6a758ecSAneesh Kumar K.V 	}
10242de8807bSAmir Goldstein 
10252de8807bSAmir Goldstein 	page = e4b.bd_bitmap_page;
1026b6a758ecSAneesh Kumar K.V 	ret = ext4_mb_init_cache(page, NULL);
10272de8807bSAmir Goldstein 	if (ret)
1028b6a758ecSAneesh Kumar K.V 		goto err;
10292de8807bSAmir Goldstein 	if (!PageUptodate(page)) {
1030b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1031b6a758ecSAneesh Kumar K.V 		goto err;
1032b6a758ecSAneesh Kumar K.V 	}
1033b6a758ecSAneesh Kumar K.V 	mark_page_accessed(page);
1034b6a758ecSAneesh Kumar K.V 
10352de8807bSAmir Goldstein 	if (e4b.bd_buddy_page == NULL) {
1036b6a758ecSAneesh Kumar K.V 		/*
1037b6a758ecSAneesh Kumar K.V 		 * If both the bitmap and buddy are in
1038b6a758ecSAneesh Kumar K.V 		 * the same page we don't need to force
1039b6a758ecSAneesh Kumar K.V 		 * init the buddy
1040b6a758ecSAneesh Kumar K.V 		 */
10412de8807bSAmir Goldstein 		ret = 0;
1042b6a758ecSAneesh Kumar K.V 		goto err;
1043b6a758ecSAneesh Kumar K.V 	}
10442de8807bSAmir Goldstein 	/* init buddy cache */
10452de8807bSAmir Goldstein 	page = e4b.bd_buddy_page;
10462de8807bSAmir Goldstein 	ret = ext4_mb_init_cache(page, e4b.bd_bitmap);
10472de8807bSAmir Goldstein 	if (ret)
10482de8807bSAmir Goldstein 		goto err;
10492de8807bSAmir Goldstein 	if (!PageUptodate(page)) {
1050b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1051b6a758ecSAneesh Kumar K.V 		goto err;
1052b6a758ecSAneesh Kumar K.V 	}
1053b6a758ecSAneesh Kumar K.V 	mark_page_accessed(page);
1054b6a758ecSAneesh Kumar K.V err:
10552de8807bSAmir Goldstein 	ext4_mb_put_buddy_page_lock(&e4b);
1056b6a758ecSAneesh Kumar K.V 	return ret;
1057b6a758ecSAneesh Kumar K.V }
1058b6a758ecSAneesh Kumar K.V 
10598a57d9d6SCurt Wohlgemuth /*
10608a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
10618a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
10628a57d9d6SCurt Wohlgemuth  * calling this routine!
10638a57d9d6SCurt Wohlgemuth  */
10644ddfef7bSEric Sandeen static noinline_for_stack int
10654ddfef7bSEric Sandeen ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1066c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1067c9de560dSAlex Tomas {
1068c9de560dSAlex Tomas 	int blocks_per_page;
1069c9de560dSAlex Tomas 	int block;
1070c9de560dSAlex Tomas 	int pnum;
1071c9de560dSAlex Tomas 	int poff;
1072c9de560dSAlex Tomas 	struct page *page;
1073fdf6c7a7SShen Feng 	int ret;
1074920313a7SAneesh Kumar K.V 	struct ext4_group_info *grp;
1075920313a7SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1076920313a7SAneesh Kumar K.V 	struct inode *inode = sbi->s_buddy_cache;
1077c9de560dSAlex Tomas 
10786ba495e9STheodore Ts'o 	mb_debug(1, "load group %u\n", group);
1079c9de560dSAlex Tomas 
1080c9de560dSAlex Tomas 	blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1081920313a7SAneesh Kumar K.V 	grp = ext4_get_group_info(sb, group);
1082c9de560dSAlex Tomas 
1083c9de560dSAlex Tomas 	e4b->bd_blkbits = sb->s_blocksize_bits;
1084529da704STao Ma 	e4b->bd_info = grp;
1085c9de560dSAlex Tomas 	e4b->bd_sb = sb;
1086c9de560dSAlex Tomas 	e4b->bd_group = group;
1087c9de560dSAlex Tomas 	e4b->bd_buddy_page = NULL;
1088c9de560dSAlex Tomas 	e4b->bd_bitmap_page = NULL;
1089c9de560dSAlex Tomas 
1090f41c0750SAneesh Kumar K.V 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1091f41c0750SAneesh Kumar K.V 		/*
1092f41c0750SAneesh Kumar K.V 		 * we need full data about the group
1093f41c0750SAneesh Kumar K.V 		 * to make a good selection
1094f41c0750SAneesh Kumar K.V 		 */
1095f41c0750SAneesh Kumar K.V 		ret = ext4_mb_init_group(sb, group);
1096f41c0750SAneesh Kumar K.V 		if (ret)
1097f41c0750SAneesh Kumar K.V 			return ret;
1098f41c0750SAneesh Kumar K.V 	}
1099f41c0750SAneesh Kumar K.V 
1100c9de560dSAlex Tomas 	/*
1101c9de560dSAlex Tomas 	 * the buddy cache inode stores the block bitmap
1102c9de560dSAlex Tomas 	 * and buddy information in consecutive blocks.
1103c9de560dSAlex Tomas 	 * So for each group we need two blocks.
1104c9de560dSAlex Tomas 	 */
1105c9de560dSAlex Tomas 	block = group * 2;
1106c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1107c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1108c9de560dSAlex Tomas 
1109c9de560dSAlex Tomas 	/* we could use find_or_create_page(), but it locks page
1110c9de560dSAlex Tomas 	 * what we'd like to avoid in fast path ... */
1111c9de560dSAlex Tomas 	page = find_get_page(inode->i_mapping, pnum);
1112c9de560dSAlex Tomas 	if (page == NULL || !PageUptodate(page)) {
1113c9de560dSAlex Tomas 		if (page)
1114920313a7SAneesh Kumar K.V 			/*
1115920313a7SAneesh Kumar K.V 			 * drop the page reference and try
1116920313a7SAneesh Kumar K.V 			 * to get the page with lock. If we
1117920313a7SAneesh Kumar K.V 			 * are not uptodate that implies
1118920313a7SAneesh Kumar K.V 			 * somebody just created the page but
1119920313a7SAneesh Kumar K.V 			 * is yet to initialize the same. So
1120920313a7SAneesh Kumar K.V 			 * wait for it to initialize.
1121920313a7SAneesh Kumar K.V 			 */
1122c9de560dSAlex Tomas 			page_cache_release(page);
1123c9de560dSAlex Tomas 		page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1124c9de560dSAlex Tomas 		if (page) {
1125c9de560dSAlex Tomas 			BUG_ON(page->mapping != inode->i_mapping);
1126c9de560dSAlex Tomas 			if (!PageUptodate(page)) {
1127fdf6c7a7SShen Feng 				ret = ext4_mb_init_cache(page, NULL);
1128fdf6c7a7SShen Feng 				if (ret) {
1129fdf6c7a7SShen Feng 					unlock_page(page);
1130fdf6c7a7SShen Feng 					goto err;
1131fdf6c7a7SShen Feng 				}
1132c9de560dSAlex Tomas 				mb_cmp_bitmaps(e4b, page_address(page) +
1133c9de560dSAlex Tomas 					       (poff * sb->s_blocksize));
1134c9de560dSAlex Tomas 			}
1135c9de560dSAlex Tomas 			unlock_page(page);
1136c9de560dSAlex Tomas 		}
1137c9de560dSAlex Tomas 	}
1138fdf6c7a7SShen Feng 	if (page == NULL || !PageUptodate(page)) {
1139fdf6c7a7SShen Feng 		ret = -EIO;
1140c9de560dSAlex Tomas 		goto err;
1141fdf6c7a7SShen Feng 	}
1142c9de560dSAlex Tomas 	e4b->bd_bitmap_page = page;
1143c9de560dSAlex Tomas 	e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1144c9de560dSAlex Tomas 	mark_page_accessed(page);
1145c9de560dSAlex Tomas 
1146c9de560dSAlex Tomas 	block++;
1147c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1148c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1149c9de560dSAlex Tomas 
1150c9de560dSAlex Tomas 	page = find_get_page(inode->i_mapping, pnum);
1151c9de560dSAlex Tomas 	if (page == NULL || !PageUptodate(page)) {
1152c9de560dSAlex Tomas 		if (page)
1153c9de560dSAlex Tomas 			page_cache_release(page);
1154c9de560dSAlex Tomas 		page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1155c9de560dSAlex Tomas 		if (page) {
1156c9de560dSAlex Tomas 			BUG_ON(page->mapping != inode->i_mapping);
1157fdf6c7a7SShen Feng 			if (!PageUptodate(page)) {
1158fdf6c7a7SShen Feng 				ret = ext4_mb_init_cache(page, e4b->bd_bitmap);
1159fdf6c7a7SShen Feng 				if (ret) {
1160fdf6c7a7SShen Feng 					unlock_page(page);
1161fdf6c7a7SShen Feng 					goto err;
1162fdf6c7a7SShen Feng 				}
1163fdf6c7a7SShen Feng 			}
1164c9de560dSAlex Tomas 			unlock_page(page);
1165c9de560dSAlex Tomas 		}
1166c9de560dSAlex Tomas 	}
1167fdf6c7a7SShen Feng 	if (page == NULL || !PageUptodate(page)) {
1168fdf6c7a7SShen Feng 		ret = -EIO;
1169c9de560dSAlex Tomas 		goto err;
1170fdf6c7a7SShen Feng 	}
1171c9de560dSAlex Tomas 	e4b->bd_buddy_page = page;
1172c9de560dSAlex Tomas 	e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1173c9de560dSAlex Tomas 	mark_page_accessed(page);
1174c9de560dSAlex Tomas 
1175c9de560dSAlex Tomas 	BUG_ON(e4b->bd_bitmap_page == NULL);
1176c9de560dSAlex Tomas 	BUG_ON(e4b->bd_buddy_page == NULL);
1177c9de560dSAlex Tomas 
1178c9de560dSAlex Tomas 	return 0;
1179c9de560dSAlex Tomas 
1180c9de560dSAlex Tomas err:
118126626f11SYang Ruirui 	if (page)
118226626f11SYang Ruirui 		page_cache_release(page);
1183c9de560dSAlex Tomas 	if (e4b->bd_bitmap_page)
1184c9de560dSAlex Tomas 		page_cache_release(e4b->bd_bitmap_page);
1185c9de560dSAlex Tomas 	if (e4b->bd_buddy_page)
1186c9de560dSAlex Tomas 		page_cache_release(e4b->bd_buddy_page);
1187c9de560dSAlex Tomas 	e4b->bd_buddy = NULL;
1188c9de560dSAlex Tomas 	e4b->bd_bitmap = NULL;
1189fdf6c7a7SShen Feng 	return ret;
1190c9de560dSAlex Tomas }
1191c9de560dSAlex Tomas 
1192e39e07fdSJing Zhang static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1193c9de560dSAlex Tomas {
1194c9de560dSAlex Tomas 	if (e4b->bd_bitmap_page)
1195c9de560dSAlex Tomas 		page_cache_release(e4b->bd_bitmap_page);
1196c9de560dSAlex Tomas 	if (e4b->bd_buddy_page)
1197c9de560dSAlex Tomas 		page_cache_release(e4b->bd_buddy_page);
1198c9de560dSAlex Tomas }
1199c9de560dSAlex Tomas 
1200c9de560dSAlex Tomas 
1201c9de560dSAlex Tomas static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1202c9de560dSAlex Tomas {
1203c9de560dSAlex Tomas 	int order = 1;
1204c9de560dSAlex Tomas 	void *bb;
1205c9de560dSAlex Tomas 
1206c5e8f3f3STheodore Ts'o 	BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1207c9de560dSAlex Tomas 	BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1208c9de560dSAlex Tomas 
1209c5e8f3f3STheodore Ts'o 	bb = e4b->bd_buddy;
1210c9de560dSAlex Tomas 	while (order <= e4b->bd_blkbits + 1) {
1211c9de560dSAlex Tomas 		block = block >> 1;
1212c9de560dSAlex Tomas 		if (!mb_test_bit(block, bb)) {
1213c9de560dSAlex Tomas 			/* this block is part of buddy of order 'order' */
1214c9de560dSAlex Tomas 			return order;
1215c9de560dSAlex Tomas 		}
1216c9de560dSAlex Tomas 		bb += 1 << (e4b->bd_blkbits - order);
1217c9de560dSAlex Tomas 		order++;
1218c9de560dSAlex Tomas 	}
1219c9de560dSAlex Tomas 	return 0;
1220c9de560dSAlex Tomas }
1221c9de560dSAlex Tomas 
1222955ce5f5SAneesh Kumar K.V static void mb_clear_bits(void *bm, int cur, int len)
1223c9de560dSAlex Tomas {
1224c9de560dSAlex Tomas 	__u32 *addr;
1225c9de560dSAlex Tomas 
1226c9de560dSAlex Tomas 	len = cur + len;
1227c9de560dSAlex Tomas 	while (cur < len) {
1228c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1229c9de560dSAlex Tomas 			/* fast path: clear whole word at once */
1230c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1231c9de560dSAlex Tomas 			*addr = 0;
1232c9de560dSAlex Tomas 			cur += 32;
1233c9de560dSAlex Tomas 			continue;
1234c9de560dSAlex Tomas 		}
1235e8134b27SAneesh Kumar K.V 		mb_clear_bit(cur, bm);
1236c9de560dSAlex Tomas 		cur++;
1237c9de560dSAlex Tomas 	}
1238c9de560dSAlex Tomas }
1239c9de560dSAlex Tomas 
1240c3e94d1dSYongqiang Yang void ext4_set_bits(void *bm, int cur, int len)
1241c9de560dSAlex Tomas {
1242c9de560dSAlex Tomas 	__u32 *addr;
1243c9de560dSAlex Tomas 
1244c9de560dSAlex Tomas 	len = cur + len;
1245c9de560dSAlex Tomas 	while (cur < len) {
1246c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1247c9de560dSAlex Tomas 			/* fast path: set whole word at once */
1248c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1249c9de560dSAlex Tomas 			*addr = 0xffffffff;
1250c9de560dSAlex Tomas 			cur += 32;
1251c9de560dSAlex Tomas 			continue;
1252c9de560dSAlex Tomas 		}
1253e8134b27SAneesh Kumar K.V 		mb_set_bit(cur, bm);
1254c9de560dSAlex Tomas 		cur++;
1255c9de560dSAlex Tomas 	}
1256c9de560dSAlex Tomas }
1257c9de560dSAlex Tomas 
12587e5a8cddSShen Feng static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1259c9de560dSAlex Tomas 			  int first, int count)
1260c9de560dSAlex Tomas {
1261c9de560dSAlex Tomas 	int block = 0;
1262c9de560dSAlex Tomas 	int max = 0;
1263c9de560dSAlex Tomas 	int order;
1264c9de560dSAlex Tomas 	void *buddy;
1265c9de560dSAlex Tomas 	void *buddy2;
1266c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
1267c9de560dSAlex Tomas 
1268c9de560dSAlex Tomas 	BUG_ON(first + count > (sb->s_blocksize << 3));
1269bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1270c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1271c9de560dSAlex Tomas 	mb_free_blocks_double(inode, e4b, first, count);
1272c9de560dSAlex Tomas 
1273c9de560dSAlex Tomas 	e4b->bd_info->bb_free += count;
1274c9de560dSAlex Tomas 	if (first < e4b->bd_info->bb_first_free)
1275c9de560dSAlex Tomas 		e4b->bd_info->bb_first_free = first;
1276c9de560dSAlex Tomas 
1277c9de560dSAlex Tomas 	/* let's maintain fragments counter */
1278c9de560dSAlex Tomas 	if (first != 0)
1279c5e8f3f3STheodore Ts'o 		block = !mb_test_bit(first - 1, e4b->bd_bitmap);
1280c9de560dSAlex Tomas 	if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
1281c5e8f3f3STheodore Ts'o 		max = !mb_test_bit(first + count, e4b->bd_bitmap);
1282c9de560dSAlex Tomas 	if (block && max)
1283c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments--;
1284c9de560dSAlex Tomas 	else if (!block && !max)
1285c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments++;
1286c9de560dSAlex Tomas 
1287c9de560dSAlex Tomas 	/* let's maintain buddy itself */
1288c9de560dSAlex Tomas 	while (count-- > 0) {
1289c9de560dSAlex Tomas 		block = first++;
1290c9de560dSAlex Tomas 		order = 0;
1291c9de560dSAlex Tomas 
1292c5e8f3f3STheodore Ts'o 		if (!mb_test_bit(block, e4b->bd_bitmap)) {
1293c9de560dSAlex Tomas 			ext4_fsblk_t blocknr;
12945661bd68SAkinobu Mita 
12955661bd68SAkinobu Mita 			blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
129653accfa9STheodore Ts'o 			blocknr += EXT4_C2B(EXT4_SB(sb), block);
12975d1b1b3fSAneesh Kumar K.V 			ext4_grp_locked_error(sb, e4b->bd_group,
1298e29136f8STheodore Ts'o 					      inode ? inode->i_ino : 0,
1299e29136f8STheodore Ts'o 					      blocknr,
1300e29136f8STheodore Ts'o 					      "freeing already freed block "
1301e29136f8STheodore Ts'o 					      "(bit %u)", block);
1302c9de560dSAlex Tomas 		}
1303c5e8f3f3STheodore Ts'o 		mb_clear_bit(block, e4b->bd_bitmap);
1304c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[order]++;
1305c9de560dSAlex Tomas 
1306c9de560dSAlex Tomas 		/* start of the buddy */
1307c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, order, &max);
1308c9de560dSAlex Tomas 
1309c9de560dSAlex Tomas 		do {
1310c9de560dSAlex Tomas 			block &= ~1UL;
1311c9de560dSAlex Tomas 			if (mb_test_bit(block, buddy) ||
1312c9de560dSAlex Tomas 					mb_test_bit(block + 1, buddy))
1313c9de560dSAlex Tomas 				break;
1314c9de560dSAlex Tomas 
1315c9de560dSAlex Tomas 			/* both the buddies are free, try to coalesce them */
1316c9de560dSAlex Tomas 			buddy2 = mb_find_buddy(e4b, order + 1, &max);
1317c9de560dSAlex Tomas 
1318c9de560dSAlex Tomas 			if (!buddy2)
1319c9de560dSAlex Tomas 				break;
1320c9de560dSAlex Tomas 
1321c9de560dSAlex Tomas 			if (order > 0) {
1322c9de560dSAlex Tomas 				/* for special purposes, we don't set
1323c9de560dSAlex Tomas 				 * free bits in bitmap */
1324c9de560dSAlex Tomas 				mb_set_bit(block, buddy);
1325c9de560dSAlex Tomas 				mb_set_bit(block + 1, buddy);
1326c9de560dSAlex Tomas 			}
1327c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[order]--;
1328c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[order]--;
1329c9de560dSAlex Tomas 
1330c9de560dSAlex Tomas 			block = block >> 1;
1331c9de560dSAlex Tomas 			order++;
1332c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[order]++;
1333c9de560dSAlex Tomas 
1334c9de560dSAlex Tomas 			mb_clear_bit(block, buddy2);
1335c9de560dSAlex Tomas 			buddy = buddy2;
1336c9de560dSAlex Tomas 		} while (1);
1337c9de560dSAlex Tomas 	}
13388a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, e4b->bd_info);
1339c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1340c9de560dSAlex Tomas }
1341c9de560dSAlex Tomas 
1342c9de560dSAlex Tomas static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
1343c9de560dSAlex Tomas 				int needed, struct ext4_free_extent *ex)
1344c9de560dSAlex Tomas {
1345c9de560dSAlex Tomas 	int next = block;
1346c9de560dSAlex Tomas 	int max;
1347c9de560dSAlex Tomas 	void *buddy;
1348c9de560dSAlex Tomas 
1349bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1350c9de560dSAlex Tomas 	BUG_ON(ex == NULL);
1351c9de560dSAlex Tomas 
1352c9de560dSAlex Tomas 	buddy = mb_find_buddy(e4b, order, &max);
1353c9de560dSAlex Tomas 	BUG_ON(buddy == NULL);
1354c9de560dSAlex Tomas 	BUG_ON(block >= max);
1355c9de560dSAlex Tomas 	if (mb_test_bit(block, buddy)) {
1356c9de560dSAlex Tomas 		ex->fe_len = 0;
1357c9de560dSAlex Tomas 		ex->fe_start = 0;
1358c9de560dSAlex Tomas 		ex->fe_group = 0;
1359c9de560dSAlex Tomas 		return 0;
1360c9de560dSAlex Tomas 	}
1361c9de560dSAlex Tomas 
1362c9de560dSAlex Tomas 	/* FIXME dorp order completely ? */
1363c9de560dSAlex Tomas 	if (likely(order == 0)) {
1364c9de560dSAlex Tomas 		/* find actual order */
1365c9de560dSAlex Tomas 		order = mb_find_order_for_block(e4b, block);
1366c9de560dSAlex Tomas 		block = block >> order;
1367c9de560dSAlex Tomas 	}
1368c9de560dSAlex Tomas 
1369c9de560dSAlex Tomas 	ex->fe_len = 1 << order;
1370c9de560dSAlex Tomas 	ex->fe_start = block << order;
1371c9de560dSAlex Tomas 	ex->fe_group = e4b->bd_group;
1372c9de560dSAlex Tomas 
1373c9de560dSAlex Tomas 	/* calc difference from given start */
1374c9de560dSAlex Tomas 	next = next - ex->fe_start;
1375c9de560dSAlex Tomas 	ex->fe_len -= next;
1376c9de560dSAlex Tomas 	ex->fe_start += next;
1377c9de560dSAlex Tomas 
1378c9de560dSAlex Tomas 	while (needed > ex->fe_len &&
1379c9de560dSAlex Tomas 	       (buddy = mb_find_buddy(e4b, order, &max))) {
1380c9de560dSAlex Tomas 
1381c9de560dSAlex Tomas 		if (block + 1 >= max)
1382c9de560dSAlex Tomas 			break;
1383c9de560dSAlex Tomas 
1384c9de560dSAlex Tomas 		next = (block + 1) * (1 << order);
1385c5e8f3f3STheodore Ts'o 		if (mb_test_bit(next, e4b->bd_bitmap))
1386c9de560dSAlex Tomas 			break;
1387c9de560dSAlex Tomas 
1388b051d8dcSRobin Dong 		order = mb_find_order_for_block(e4b, next);
1389c9de560dSAlex Tomas 
1390c9de560dSAlex Tomas 		block = next >> order;
1391c9de560dSAlex Tomas 		ex->fe_len += 1 << order;
1392c9de560dSAlex Tomas 	}
1393c9de560dSAlex Tomas 
1394c9de560dSAlex Tomas 	BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1395c9de560dSAlex Tomas 	return ex->fe_len;
1396c9de560dSAlex Tomas }
1397c9de560dSAlex Tomas 
1398c9de560dSAlex Tomas static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1399c9de560dSAlex Tomas {
1400c9de560dSAlex Tomas 	int ord;
1401c9de560dSAlex Tomas 	int mlen = 0;
1402c9de560dSAlex Tomas 	int max = 0;
1403c9de560dSAlex Tomas 	int cur;
1404c9de560dSAlex Tomas 	int start = ex->fe_start;
1405c9de560dSAlex Tomas 	int len = ex->fe_len;
1406c9de560dSAlex Tomas 	unsigned ret = 0;
1407c9de560dSAlex Tomas 	int len0 = len;
1408c9de560dSAlex Tomas 	void *buddy;
1409c9de560dSAlex Tomas 
1410c9de560dSAlex Tomas 	BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1411c9de560dSAlex Tomas 	BUG_ON(e4b->bd_group != ex->fe_group);
1412bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1413c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1414c9de560dSAlex Tomas 	mb_mark_used_double(e4b, start, len);
1415c9de560dSAlex Tomas 
1416c9de560dSAlex Tomas 	e4b->bd_info->bb_free -= len;
1417c9de560dSAlex Tomas 	if (e4b->bd_info->bb_first_free == start)
1418c9de560dSAlex Tomas 		e4b->bd_info->bb_first_free += len;
1419c9de560dSAlex Tomas 
1420c9de560dSAlex Tomas 	/* let's maintain fragments counter */
1421c9de560dSAlex Tomas 	if (start != 0)
1422c5e8f3f3STheodore Ts'o 		mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1423c9de560dSAlex Tomas 	if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1424c5e8f3f3STheodore Ts'o 		max = !mb_test_bit(start + len, e4b->bd_bitmap);
1425c9de560dSAlex Tomas 	if (mlen && max)
1426c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments++;
1427c9de560dSAlex Tomas 	else if (!mlen && !max)
1428c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments--;
1429c9de560dSAlex Tomas 
1430c9de560dSAlex Tomas 	/* let's maintain buddy itself */
1431c9de560dSAlex Tomas 	while (len) {
1432c9de560dSAlex Tomas 		ord = mb_find_order_for_block(e4b, start);
1433c9de560dSAlex Tomas 
1434c9de560dSAlex Tomas 		if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1435c9de560dSAlex Tomas 			/* the whole chunk may be allocated at once! */
1436c9de560dSAlex Tomas 			mlen = 1 << ord;
1437c9de560dSAlex Tomas 			buddy = mb_find_buddy(e4b, ord, &max);
1438c9de560dSAlex Tomas 			BUG_ON((start >> ord) >= max);
1439c9de560dSAlex Tomas 			mb_set_bit(start >> ord, buddy);
1440c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[ord]--;
1441c9de560dSAlex Tomas 			start += mlen;
1442c9de560dSAlex Tomas 			len -= mlen;
1443c9de560dSAlex Tomas 			BUG_ON(len < 0);
1444c9de560dSAlex Tomas 			continue;
1445c9de560dSAlex Tomas 		}
1446c9de560dSAlex Tomas 
1447c9de560dSAlex Tomas 		/* store for history */
1448c9de560dSAlex Tomas 		if (ret == 0)
1449c9de560dSAlex Tomas 			ret = len | (ord << 16);
1450c9de560dSAlex Tomas 
1451c9de560dSAlex Tomas 		/* we have to split large buddy */
1452c9de560dSAlex Tomas 		BUG_ON(ord <= 0);
1453c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, ord, &max);
1454c9de560dSAlex Tomas 		mb_set_bit(start >> ord, buddy);
1455c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]--;
1456c9de560dSAlex Tomas 
1457c9de560dSAlex Tomas 		ord--;
1458c9de560dSAlex Tomas 		cur = (start >> ord) & ~1U;
1459c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, ord, &max);
1460c9de560dSAlex Tomas 		mb_clear_bit(cur, buddy);
1461c9de560dSAlex Tomas 		mb_clear_bit(cur + 1, buddy);
1462c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]++;
1463c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]++;
1464c9de560dSAlex Tomas 	}
14658a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1466c9de560dSAlex Tomas 
1467c5e8f3f3STheodore Ts'o 	ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1468c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1469c9de560dSAlex Tomas 
1470c9de560dSAlex Tomas 	return ret;
1471c9de560dSAlex Tomas }
1472c9de560dSAlex Tomas 
1473c9de560dSAlex Tomas /*
1474c9de560dSAlex Tomas  * Must be called under group lock!
1475c9de560dSAlex Tomas  */
1476c9de560dSAlex Tomas static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1477c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1478c9de560dSAlex Tomas {
1479c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1480c9de560dSAlex Tomas 	int ret;
1481c9de560dSAlex Tomas 
1482c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1483c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1484c9de560dSAlex Tomas 
1485c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1486c9de560dSAlex Tomas 	ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1487c9de560dSAlex Tomas 	ret = mb_mark_used(e4b, &ac->ac_b_ex);
1488c9de560dSAlex Tomas 
1489c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
1490c9de560dSAlex Tomas 	 * allocated blocks for history */
1491c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
1492c9de560dSAlex Tomas 
1493c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
1494c9de560dSAlex Tomas 	ac->ac_tail = ret & 0xffff;
1495c9de560dSAlex Tomas 	ac->ac_buddy = ret >> 16;
1496c9de560dSAlex Tomas 
1497c3a326a6SAneesh Kumar K.V 	/*
1498c3a326a6SAneesh Kumar K.V 	 * take the page reference. We want the page to be pinned
1499c3a326a6SAneesh Kumar K.V 	 * so that we don't get a ext4_mb_init_cache_call for this
1500c3a326a6SAneesh Kumar K.V 	 * group until we update the bitmap. That would mean we
1501c3a326a6SAneesh Kumar K.V 	 * double allocate blocks. The reference is dropped
1502c3a326a6SAneesh Kumar K.V 	 * in ext4_mb_release_context
1503c3a326a6SAneesh Kumar K.V 	 */
1504c9de560dSAlex Tomas 	ac->ac_bitmap_page = e4b->bd_bitmap_page;
1505c9de560dSAlex Tomas 	get_page(ac->ac_bitmap_page);
1506c9de560dSAlex Tomas 	ac->ac_buddy_page = e4b->bd_buddy_page;
1507c9de560dSAlex Tomas 	get_page(ac->ac_buddy_page);
1508c9de560dSAlex Tomas 	/* store last allocated for subsequent stream allocation */
15094ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1510c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
1511c9de560dSAlex Tomas 		sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1512c9de560dSAlex Tomas 		sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1513c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
1514c9de560dSAlex Tomas 	}
1515c9de560dSAlex Tomas }
1516c9de560dSAlex Tomas 
1517c9de560dSAlex Tomas /*
1518c9de560dSAlex Tomas  * regular allocator, for general purposes allocation
1519c9de560dSAlex Tomas  */
1520c9de560dSAlex Tomas 
1521c9de560dSAlex Tomas static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1522c9de560dSAlex Tomas 					struct ext4_buddy *e4b,
1523c9de560dSAlex Tomas 					int finish_group)
1524c9de560dSAlex Tomas {
1525c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1526c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
1527c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
1528c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1529c9de560dSAlex Tomas 	int max;
1530c9de560dSAlex Tomas 
1531032115fcSAneesh Kumar K.V 	if (ac->ac_status == AC_STATUS_FOUND)
1532032115fcSAneesh Kumar K.V 		return;
1533c9de560dSAlex Tomas 	/*
1534c9de560dSAlex Tomas 	 * We don't want to scan for a whole year
1535c9de560dSAlex Tomas 	 */
1536c9de560dSAlex Tomas 	if (ac->ac_found > sbi->s_mb_max_to_scan &&
1537c9de560dSAlex Tomas 			!(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1538c9de560dSAlex Tomas 		ac->ac_status = AC_STATUS_BREAK;
1539c9de560dSAlex Tomas 		return;
1540c9de560dSAlex Tomas 	}
1541c9de560dSAlex Tomas 
1542c9de560dSAlex Tomas 	/*
1543c9de560dSAlex Tomas 	 * Haven't found good chunk so far, let's continue
1544c9de560dSAlex Tomas 	 */
1545c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len)
1546c9de560dSAlex Tomas 		return;
1547c9de560dSAlex Tomas 
1548c9de560dSAlex Tomas 	if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1549c9de560dSAlex Tomas 			&& bex->fe_group == e4b->bd_group) {
1550c9de560dSAlex Tomas 		/* recheck chunk's availability - we don't know
1551c9de560dSAlex Tomas 		 * when it was found (within this lock-unlock
1552c9de560dSAlex Tomas 		 * period or not) */
1553c9de560dSAlex Tomas 		max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
1554c9de560dSAlex Tomas 		if (max >= gex->fe_len) {
1555c9de560dSAlex Tomas 			ext4_mb_use_best_found(ac, e4b);
1556c9de560dSAlex Tomas 			return;
1557c9de560dSAlex Tomas 		}
1558c9de560dSAlex Tomas 	}
1559c9de560dSAlex Tomas }
1560c9de560dSAlex Tomas 
1561c9de560dSAlex Tomas /*
1562c9de560dSAlex Tomas  * The routine checks whether found extent is good enough. If it is,
1563c9de560dSAlex Tomas  * then the extent gets marked used and flag is set to the context
1564c9de560dSAlex Tomas  * to stop scanning. Otherwise, the extent is compared with the
1565c9de560dSAlex Tomas  * previous found extent and if new one is better, then it's stored
1566c9de560dSAlex Tomas  * in the context. Later, the best found extent will be used, if
1567c9de560dSAlex Tomas  * mballoc can't find good enough extent.
1568c9de560dSAlex Tomas  *
1569c9de560dSAlex Tomas  * FIXME: real allocation policy is to be designed yet!
1570c9de560dSAlex Tomas  */
1571c9de560dSAlex Tomas static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1572c9de560dSAlex Tomas 					struct ext4_free_extent *ex,
1573c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1574c9de560dSAlex Tomas {
1575c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
1576c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
1577c9de560dSAlex Tomas 
1578c9de560dSAlex Tomas 	BUG_ON(ex->fe_len <= 0);
15797137d7a4STheodore Ts'o 	BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
15807137d7a4STheodore Ts'o 	BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1581c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1582c9de560dSAlex Tomas 
1583c9de560dSAlex Tomas 	ac->ac_found++;
1584c9de560dSAlex Tomas 
1585c9de560dSAlex Tomas 	/*
1586c9de560dSAlex Tomas 	 * The special case - take what you catch first
1587c9de560dSAlex Tomas 	 */
1588c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1589c9de560dSAlex Tomas 		*bex = *ex;
1590c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1591c9de560dSAlex Tomas 		return;
1592c9de560dSAlex Tomas 	}
1593c9de560dSAlex Tomas 
1594c9de560dSAlex Tomas 	/*
1595c9de560dSAlex Tomas 	 * Let's check whether the chuck is good enough
1596c9de560dSAlex Tomas 	 */
1597c9de560dSAlex Tomas 	if (ex->fe_len == gex->fe_len) {
1598c9de560dSAlex Tomas 		*bex = *ex;
1599c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1600c9de560dSAlex Tomas 		return;
1601c9de560dSAlex Tomas 	}
1602c9de560dSAlex Tomas 
1603c9de560dSAlex Tomas 	/*
1604c9de560dSAlex Tomas 	 * If this is first found extent, just store it in the context
1605c9de560dSAlex Tomas 	 */
1606c9de560dSAlex Tomas 	if (bex->fe_len == 0) {
1607c9de560dSAlex Tomas 		*bex = *ex;
1608c9de560dSAlex Tomas 		return;
1609c9de560dSAlex Tomas 	}
1610c9de560dSAlex Tomas 
1611c9de560dSAlex Tomas 	/*
1612c9de560dSAlex Tomas 	 * If new found extent is better, store it in the context
1613c9de560dSAlex Tomas 	 */
1614c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len) {
1615c9de560dSAlex Tomas 		/* if the request isn't satisfied, any found extent
1616c9de560dSAlex Tomas 		 * larger than previous best one is better */
1617c9de560dSAlex Tomas 		if (ex->fe_len > bex->fe_len)
1618c9de560dSAlex Tomas 			*bex = *ex;
1619c9de560dSAlex Tomas 	} else if (ex->fe_len > gex->fe_len) {
1620c9de560dSAlex Tomas 		/* if the request is satisfied, then we try to find
1621c9de560dSAlex Tomas 		 * an extent that still satisfy the request, but is
1622c9de560dSAlex Tomas 		 * smaller than previous one */
1623c9de560dSAlex Tomas 		if (ex->fe_len < bex->fe_len)
1624c9de560dSAlex Tomas 			*bex = *ex;
1625c9de560dSAlex Tomas 	}
1626c9de560dSAlex Tomas 
1627c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 0);
1628c9de560dSAlex Tomas }
1629c9de560dSAlex Tomas 
1630089ceeccSEric Sandeen static noinline_for_stack
1631089ceeccSEric Sandeen int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1632c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1633c9de560dSAlex Tomas {
1634c9de560dSAlex Tomas 	struct ext4_free_extent ex = ac->ac_b_ex;
1635c9de560dSAlex Tomas 	ext4_group_t group = ex.fe_group;
1636c9de560dSAlex Tomas 	int max;
1637c9de560dSAlex Tomas 	int err;
1638c9de560dSAlex Tomas 
1639c9de560dSAlex Tomas 	BUG_ON(ex.fe_len <= 0);
1640c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1641c9de560dSAlex Tomas 	if (err)
1642c9de560dSAlex Tomas 		return err;
1643c9de560dSAlex Tomas 
1644c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
1645c9de560dSAlex Tomas 	max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
1646c9de560dSAlex Tomas 
1647c9de560dSAlex Tomas 	if (max > 0) {
1648c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
1649c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1650c9de560dSAlex Tomas 	}
1651c9de560dSAlex Tomas 
1652c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
1653e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
1654c9de560dSAlex Tomas 
1655c9de560dSAlex Tomas 	return 0;
1656c9de560dSAlex Tomas }
1657c9de560dSAlex Tomas 
1658089ceeccSEric Sandeen static noinline_for_stack
1659089ceeccSEric Sandeen int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1660c9de560dSAlex Tomas 				struct ext4_buddy *e4b)
1661c9de560dSAlex Tomas {
1662c9de560dSAlex Tomas 	ext4_group_t group = ac->ac_g_ex.fe_group;
1663c9de560dSAlex Tomas 	int max;
1664c9de560dSAlex Tomas 	int err;
1665c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1666c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1667c9de560dSAlex Tomas 
1668c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1669c9de560dSAlex Tomas 		return 0;
1670c9de560dSAlex Tomas 
1671c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1672c9de560dSAlex Tomas 	if (err)
1673c9de560dSAlex Tomas 		return err;
1674c9de560dSAlex Tomas 
1675c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
1676c9de560dSAlex Tomas 	max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
1677c9de560dSAlex Tomas 			     ac->ac_g_ex.fe_len, &ex);
1678c9de560dSAlex Tomas 
1679c9de560dSAlex Tomas 	if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1680c9de560dSAlex Tomas 		ext4_fsblk_t start;
1681c9de560dSAlex Tomas 
16825661bd68SAkinobu Mita 		start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
16835661bd68SAkinobu Mita 			ex.fe_start;
1684c9de560dSAlex Tomas 		/* use do_div to get remainder (would be 64-bit modulo) */
1685c9de560dSAlex Tomas 		if (do_div(start, sbi->s_stripe) == 0) {
1686c9de560dSAlex Tomas 			ac->ac_found++;
1687c9de560dSAlex Tomas 			ac->ac_b_ex = ex;
1688c9de560dSAlex Tomas 			ext4_mb_use_best_found(ac, e4b);
1689c9de560dSAlex Tomas 		}
1690c9de560dSAlex Tomas 	} else if (max >= ac->ac_g_ex.fe_len) {
1691c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
1692c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1693c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1694c9de560dSAlex Tomas 		ac->ac_found++;
1695c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
1696c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1697c9de560dSAlex Tomas 	} else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1698c9de560dSAlex Tomas 		/* Sometimes, caller may want to merge even small
1699c9de560dSAlex Tomas 		 * number of blocks to an existing extent */
1700c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
1701c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1702c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1703c9de560dSAlex Tomas 		ac->ac_found++;
1704c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
1705c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1706c9de560dSAlex Tomas 	}
1707c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
1708e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
1709c9de560dSAlex Tomas 
1710c9de560dSAlex Tomas 	return 0;
1711c9de560dSAlex Tomas }
1712c9de560dSAlex Tomas 
1713c9de560dSAlex Tomas /*
1714c9de560dSAlex Tomas  * The routine scans buddy structures (not bitmap!) from given order
1715c9de560dSAlex Tomas  * to max order and tries to find big enough chunk to satisfy the req
1716c9de560dSAlex Tomas  */
1717089ceeccSEric Sandeen static noinline_for_stack
1718089ceeccSEric Sandeen void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1719c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1720c9de560dSAlex Tomas {
1721c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
1722c9de560dSAlex Tomas 	struct ext4_group_info *grp = e4b->bd_info;
1723c9de560dSAlex Tomas 	void *buddy;
1724c9de560dSAlex Tomas 	int i;
1725c9de560dSAlex Tomas 	int k;
1726c9de560dSAlex Tomas 	int max;
1727c9de560dSAlex Tomas 
1728c9de560dSAlex Tomas 	BUG_ON(ac->ac_2order <= 0);
1729c9de560dSAlex Tomas 	for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1730c9de560dSAlex Tomas 		if (grp->bb_counters[i] == 0)
1731c9de560dSAlex Tomas 			continue;
1732c9de560dSAlex Tomas 
1733c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, i, &max);
1734c9de560dSAlex Tomas 		BUG_ON(buddy == NULL);
1735c9de560dSAlex Tomas 
1736ffad0a44SAneesh Kumar K.V 		k = mb_find_next_zero_bit(buddy, max, 0);
1737c9de560dSAlex Tomas 		BUG_ON(k >= max);
1738c9de560dSAlex Tomas 
1739c9de560dSAlex Tomas 		ac->ac_found++;
1740c9de560dSAlex Tomas 
1741c9de560dSAlex Tomas 		ac->ac_b_ex.fe_len = 1 << i;
1742c9de560dSAlex Tomas 		ac->ac_b_ex.fe_start = k << i;
1743c9de560dSAlex Tomas 		ac->ac_b_ex.fe_group = e4b->bd_group;
1744c9de560dSAlex Tomas 
1745c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1746c9de560dSAlex Tomas 
1747c9de560dSAlex Tomas 		BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1748c9de560dSAlex Tomas 
1749c9de560dSAlex Tomas 		if (EXT4_SB(sb)->s_mb_stats)
1750c9de560dSAlex Tomas 			atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1751c9de560dSAlex Tomas 
1752c9de560dSAlex Tomas 		break;
1753c9de560dSAlex Tomas 	}
1754c9de560dSAlex Tomas }
1755c9de560dSAlex Tomas 
1756c9de560dSAlex Tomas /*
1757c9de560dSAlex Tomas  * The routine scans the group and measures all found extents.
1758c9de560dSAlex Tomas  * In order to optimize scanning, caller must pass number of
1759c9de560dSAlex Tomas  * free blocks in the group, so the routine can know upper limit.
1760c9de560dSAlex Tomas  */
1761089ceeccSEric Sandeen static noinline_for_stack
1762089ceeccSEric Sandeen void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1763c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1764c9de560dSAlex Tomas {
1765c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
1766c5e8f3f3STheodore Ts'o 	void *bitmap = e4b->bd_bitmap;
1767c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1768c9de560dSAlex Tomas 	int i;
1769c9de560dSAlex Tomas 	int free;
1770c9de560dSAlex Tomas 
1771c9de560dSAlex Tomas 	free = e4b->bd_info->bb_free;
1772c9de560dSAlex Tomas 	BUG_ON(free <= 0);
1773c9de560dSAlex Tomas 
1774c9de560dSAlex Tomas 	i = e4b->bd_info->bb_first_free;
1775c9de560dSAlex Tomas 
1776c9de560dSAlex Tomas 	while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1777ffad0a44SAneesh Kumar K.V 		i = mb_find_next_zero_bit(bitmap,
17787137d7a4STheodore Ts'o 						EXT4_CLUSTERS_PER_GROUP(sb), i);
17797137d7a4STheodore Ts'o 		if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
178026346ff6SAneesh Kumar K.V 			/*
1781e56eb659SAneesh Kumar K.V 			 * IF we have corrupt bitmap, we won't find any
178226346ff6SAneesh Kumar K.V 			 * free blocks even though group info says we
178326346ff6SAneesh Kumar K.V 			 * we have free blocks
178426346ff6SAneesh Kumar K.V 			 */
1785e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
178653accfa9STheodore Ts'o 					"%d free clusters as per "
1787fde4d95aSTheodore Ts'o 					"group info. But bitmap says 0",
178826346ff6SAneesh Kumar K.V 					free);
1789c9de560dSAlex Tomas 			break;
1790c9de560dSAlex Tomas 		}
1791c9de560dSAlex Tomas 
1792c9de560dSAlex Tomas 		mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
1793c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
179426346ff6SAneesh Kumar K.V 		if (free < ex.fe_len) {
1795e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
179653accfa9STheodore Ts'o 					"%d free clusters as per "
1797fde4d95aSTheodore Ts'o 					"group info. But got %d blocks",
179826346ff6SAneesh Kumar K.V 					free, ex.fe_len);
1799e56eb659SAneesh Kumar K.V 			/*
1800e56eb659SAneesh Kumar K.V 			 * The number of free blocks differs. This mostly
1801e56eb659SAneesh Kumar K.V 			 * indicate that the bitmap is corrupt. So exit
1802e56eb659SAneesh Kumar K.V 			 * without claiming the space.
1803e56eb659SAneesh Kumar K.V 			 */
1804e56eb659SAneesh Kumar K.V 			break;
180526346ff6SAneesh Kumar K.V 		}
1806c9de560dSAlex Tomas 
1807c9de560dSAlex Tomas 		ext4_mb_measure_extent(ac, &ex, e4b);
1808c9de560dSAlex Tomas 
1809c9de560dSAlex Tomas 		i += ex.fe_len;
1810c9de560dSAlex Tomas 		free -= ex.fe_len;
1811c9de560dSAlex Tomas 	}
1812c9de560dSAlex Tomas 
1813c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 1);
1814c9de560dSAlex Tomas }
1815c9de560dSAlex Tomas 
1816c9de560dSAlex Tomas /*
1817c9de560dSAlex Tomas  * This is a special case for storages like raid5
1818506bf2d8SEric Sandeen  * we try to find stripe-aligned chunks for stripe-size-multiple requests
1819c9de560dSAlex Tomas  */
1820089ceeccSEric Sandeen static noinline_for_stack
1821089ceeccSEric Sandeen void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1822c9de560dSAlex Tomas 				 struct ext4_buddy *e4b)
1823c9de560dSAlex Tomas {
1824c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
1825c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1826c5e8f3f3STheodore Ts'o 	void *bitmap = e4b->bd_bitmap;
1827c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1828c9de560dSAlex Tomas 	ext4_fsblk_t first_group_block;
1829c9de560dSAlex Tomas 	ext4_fsblk_t a;
1830c9de560dSAlex Tomas 	ext4_grpblk_t i;
1831c9de560dSAlex Tomas 	int max;
1832c9de560dSAlex Tomas 
1833c9de560dSAlex Tomas 	BUG_ON(sbi->s_stripe == 0);
1834c9de560dSAlex Tomas 
1835c9de560dSAlex Tomas 	/* find first stripe-aligned block in group */
18365661bd68SAkinobu Mita 	first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
18375661bd68SAkinobu Mita 
1838c9de560dSAlex Tomas 	a = first_group_block + sbi->s_stripe - 1;
1839c9de560dSAlex Tomas 	do_div(a, sbi->s_stripe);
1840c9de560dSAlex Tomas 	i = (a * sbi->s_stripe) - first_group_block;
1841c9de560dSAlex Tomas 
18427137d7a4STheodore Ts'o 	while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
1843c9de560dSAlex Tomas 		if (!mb_test_bit(i, bitmap)) {
1844c9de560dSAlex Tomas 			max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
1845c9de560dSAlex Tomas 			if (max >= sbi->s_stripe) {
1846c9de560dSAlex Tomas 				ac->ac_found++;
1847c9de560dSAlex Tomas 				ac->ac_b_ex = ex;
1848c9de560dSAlex Tomas 				ext4_mb_use_best_found(ac, e4b);
1849c9de560dSAlex Tomas 				break;
1850c9de560dSAlex Tomas 			}
1851c9de560dSAlex Tomas 		}
1852c9de560dSAlex Tomas 		i += sbi->s_stripe;
1853c9de560dSAlex Tomas 	}
1854c9de560dSAlex Tomas }
1855c9de560dSAlex Tomas 
18568a57d9d6SCurt Wohlgemuth /* This is now called BEFORE we load the buddy bitmap. */
1857c9de560dSAlex Tomas static int ext4_mb_good_group(struct ext4_allocation_context *ac,
1858c9de560dSAlex Tomas 				ext4_group_t group, int cr)
1859c9de560dSAlex Tomas {
1860c9de560dSAlex Tomas 	unsigned free, fragments;
1861a4912123STheodore Ts'o 	int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
1862c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1863c9de560dSAlex Tomas 
1864c9de560dSAlex Tomas 	BUG_ON(cr < 0 || cr >= 4);
18658a57d9d6SCurt Wohlgemuth 
18668a57d9d6SCurt Wohlgemuth 	/* We only do this if the grp has never been initialized */
18678a57d9d6SCurt Wohlgemuth 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
18688a57d9d6SCurt Wohlgemuth 		int ret = ext4_mb_init_group(ac->ac_sb, group);
18698a57d9d6SCurt Wohlgemuth 		if (ret)
18708a57d9d6SCurt Wohlgemuth 			return 0;
18718a57d9d6SCurt Wohlgemuth 	}
1872c9de560dSAlex Tomas 
1873c9de560dSAlex Tomas 	free = grp->bb_free;
1874c9de560dSAlex Tomas 	fragments = grp->bb_fragments;
1875c9de560dSAlex Tomas 	if (free == 0)
1876c9de560dSAlex Tomas 		return 0;
1877c9de560dSAlex Tomas 	if (fragments == 0)
1878c9de560dSAlex Tomas 		return 0;
1879c9de560dSAlex Tomas 
1880c9de560dSAlex Tomas 	switch (cr) {
1881c9de560dSAlex Tomas 	case 0:
1882c9de560dSAlex Tomas 		BUG_ON(ac->ac_2order == 0);
1883c9de560dSAlex Tomas 
18848a57d9d6SCurt Wohlgemuth 		if (grp->bb_largest_free_order < ac->ac_2order)
18858a57d9d6SCurt Wohlgemuth 			return 0;
18868a57d9d6SCurt Wohlgemuth 
1887a4912123STheodore Ts'o 		/* Avoid using the first bg of a flexgroup for data files */
1888a4912123STheodore Ts'o 		if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
1889a4912123STheodore Ts'o 		    (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
1890a4912123STheodore Ts'o 		    ((group % flex_size) == 0))
1891a4912123STheodore Ts'o 			return 0;
1892a4912123STheodore Ts'o 
1893c9de560dSAlex Tomas 		return 1;
1894c9de560dSAlex Tomas 	case 1:
1895c9de560dSAlex Tomas 		if ((free / fragments) >= ac->ac_g_ex.fe_len)
1896c9de560dSAlex Tomas 			return 1;
1897c9de560dSAlex Tomas 		break;
1898c9de560dSAlex Tomas 	case 2:
1899c9de560dSAlex Tomas 		if (free >= ac->ac_g_ex.fe_len)
1900c9de560dSAlex Tomas 			return 1;
1901c9de560dSAlex Tomas 		break;
1902c9de560dSAlex Tomas 	case 3:
1903c9de560dSAlex Tomas 		return 1;
1904c9de560dSAlex Tomas 	default:
1905c9de560dSAlex Tomas 		BUG();
1906c9de560dSAlex Tomas 	}
1907c9de560dSAlex Tomas 
1908c9de560dSAlex Tomas 	return 0;
1909c9de560dSAlex Tomas }
1910c9de560dSAlex Tomas 
19114ddfef7bSEric Sandeen static noinline_for_stack int
19124ddfef7bSEric Sandeen ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
1913c9de560dSAlex Tomas {
19148df9675fSTheodore Ts'o 	ext4_group_t ngroups, group, i;
1915c9de560dSAlex Tomas 	int cr;
1916c9de560dSAlex Tomas 	int err = 0;
1917c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
1918c9de560dSAlex Tomas 	struct super_block *sb;
1919c9de560dSAlex Tomas 	struct ext4_buddy e4b;
1920c9de560dSAlex Tomas 
1921c9de560dSAlex Tomas 	sb = ac->ac_sb;
1922c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
19238df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
1924fb0a387dSEric Sandeen 	/* non-extent files are limited to low blocks/groups */
192512e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
1926fb0a387dSEric Sandeen 		ngroups = sbi->s_blockfile_groups;
1927fb0a387dSEric Sandeen 
1928c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1929c9de560dSAlex Tomas 
1930c9de560dSAlex Tomas 	/* first, try the goal */
1931c9de560dSAlex Tomas 	err = ext4_mb_find_by_goal(ac, &e4b);
1932c9de560dSAlex Tomas 	if (err || ac->ac_status == AC_STATUS_FOUND)
1933c9de560dSAlex Tomas 		goto out;
1934c9de560dSAlex Tomas 
1935c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
1936c9de560dSAlex Tomas 		goto out;
1937c9de560dSAlex Tomas 
1938c9de560dSAlex Tomas 	/*
1939c9de560dSAlex Tomas 	 * ac->ac2_order is set only if the fe_len is a power of 2
1940c9de560dSAlex Tomas 	 * if ac2_order is set we also set criteria to 0 so that we
1941c9de560dSAlex Tomas 	 * try exact allocation using buddy.
1942c9de560dSAlex Tomas 	 */
1943c9de560dSAlex Tomas 	i = fls(ac->ac_g_ex.fe_len);
1944c9de560dSAlex Tomas 	ac->ac_2order = 0;
1945c9de560dSAlex Tomas 	/*
1946c9de560dSAlex Tomas 	 * We search using buddy data only if the order of the request
1947c9de560dSAlex Tomas 	 * is greater than equal to the sbi_s_mb_order2_reqs
1948b713a5ecSTheodore Ts'o 	 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
1949c9de560dSAlex Tomas 	 */
1950c9de560dSAlex Tomas 	if (i >= sbi->s_mb_order2_reqs) {
1951c9de560dSAlex Tomas 		/*
1952c9de560dSAlex Tomas 		 * This should tell if fe_len is exactly power of 2
1953c9de560dSAlex Tomas 		 */
1954c9de560dSAlex Tomas 		if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
1955c9de560dSAlex Tomas 			ac->ac_2order = i - 1;
1956c9de560dSAlex Tomas 	}
1957c9de560dSAlex Tomas 
19584ba74d00STheodore Ts'o 	/* if stream allocation is enabled, use global goal */
19594ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1960c9de560dSAlex Tomas 		/* TBD: may be hot point */
1961c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
1962c9de560dSAlex Tomas 		ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
1963c9de560dSAlex Tomas 		ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
1964c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
1965c9de560dSAlex Tomas 	}
19664ba74d00STheodore Ts'o 
1967c9de560dSAlex Tomas 	/* Let's just scan groups to find more-less suitable blocks */
1968c9de560dSAlex Tomas 	cr = ac->ac_2order ? 0 : 1;
1969c9de560dSAlex Tomas 	/*
1970c9de560dSAlex Tomas 	 * cr == 0 try to get exact allocation,
1971c9de560dSAlex Tomas 	 * cr == 3  try to get anything
1972c9de560dSAlex Tomas 	 */
1973c9de560dSAlex Tomas repeat:
1974c9de560dSAlex Tomas 	for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
1975c9de560dSAlex Tomas 		ac->ac_criteria = cr;
1976ed8f9c75SAneesh Kumar K.V 		/*
1977ed8f9c75SAneesh Kumar K.V 		 * searching for the right group start
1978ed8f9c75SAneesh Kumar K.V 		 * from the goal value specified
1979ed8f9c75SAneesh Kumar K.V 		 */
1980ed8f9c75SAneesh Kumar K.V 		group = ac->ac_g_ex.fe_group;
1981ed8f9c75SAneesh Kumar K.V 
19828df9675fSTheodore Ts'o 		for (i = 0; i < ngroups; group++, i++) {
19838df9675fSTheodore Ts'o 			if (group == ngroups)
1984c9de560dSAlex Tomas 				group = 0;
1985c9de560dSAlex Tomas 
19868a57d9d6SCurt Wohlgemuth 			/* This now checks without needing the buddy page */
19878a57d9d6SCurt Wohlgemuth 			if (!ext4_mb_good_group(ac, group, cr))
1988c9de560dSAlex Tomas 				continue;
1989c9de560dSAlex Tomas 
1990c9de560dSAlex Tomas 			err = ext4_mb_load_buddy(sb, group, &e4b);
1991c9de560dSAlex Tomas 			if (err)
1992c9de560dSAlex Tomas 				goto out;
1993c9de560dSAlex Tomas 
1994c9de560dSAlex Tomas 			ext4_lock_group(sb, group);
19958a57d9d6SCurt Wohlgemuth 
19968a57d9d6SCurt Wohlgemuth 			/*
19978a57d9d6SCurt Wohlgemuth 			 * We need to check again after locking the
19988a57d9d6SCurt Wohlgemuth 			 * block group
19998a57d9d6SCurt Wohlgemuth 			 */
2000c9de560dSAlex Tomas 			if (!ext4_mb_good_group(ac, group, cr)) {
2001c9de560dSAlex Tomas 				ext4_unlock_group(sb, group);
2002e39e07fdSJing Zhang 				ext4_mb_unload_buddy(&e4b);
2003c9de560dSAlex Tomas 				continue;
2004c9de560dSAlex Tomas 			}
2005c9de560dSAlex Tomas 
2006c9de560dSAlex Tomas 			ac->ac_groups_scanned++;
200775507efbSTheodore Ts'o 			if (cr == 0)
2008c9de560dSAlex Tomas 				ext4_mb_simple_scan_group(ac, &e4b);
2009506bf2d8SEric Sandeen 			else if (cr == 1 && sbi->s_stripe &&
2010506bf2d8SEric Sandeen 					!(ac->ac_g_ex.fe_len % sbi->s_stripe))
2011c9de560dSAlex Tomas 				ext4_mb_scan_aligned(ac, &e4b);
2012c9de560dSAlex Tomas 			else
2013c9de560dSAlex Tomas 				ext4_mb_complex_scan_group(ac, &e4b);
2014c9de560dSAlex Tomas 
2015c9de560dSAlex Tomas 			ext4_unlock_group(sb, group);
2016e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
2017c9de560dSAlex Tomas 
2018c9de560dSAlex Tomas 			if (ac->ac_status != AC_STATUS_CONTINUE)
2019c9de560dSAlex Tomas 				break;
2020c9de560dSAlex Tomas 		}
2021c9de560dSAlex Tomas 	}
2022c9de560dSAlex Tomas 
2023c9de560dSAlex Tomas 	if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2024c9de560dSAlex Tomas 	    !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2025c9de560dSAlex Tomas 		/*
2026c9de560dSAlex Tomas 		 * We've been searching too long. Let's try to allocate
2027c9de560dSAlex Tomas 		 * the best chunk we've found so far
2028c9de560dSAlex Tomas 		 */
2029c9de560dSAlex Tomas 
2030c9de560dSAlex Tomas 		ext4_mb_try_best_found(ac, &e4b);
2031c9de560dSAlex Tomas 		if (ac->ac_status != AC_STATUS_FOUND) {
2032c9de560dSAlex Tomas 			/*
2033c9de560dSAlex Tomas 			 * Someone more lucky has already allocated it.
2034c9de560dSAlex Tomas 			 * The only thing we can do is just take first
2035c9de560dSAlex Tomas 			 * found block(s)
2036c9de560dSAlex Tomas 			printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2037c9de560dSAlex Tomas 			 */
2038c9de560dSAlex Tomas 			ac->ac_b_ex.fe_group = 0;
2039c9de560dSAlex Tomas 			ac->ac_b_ex.fe_start = 0;
2040c9de560dSAlex Tomas 			ac->ac_b_ex.fe_len = 0;
2041c9de560dSAlex Tomas 			ac->ac_status = AC_STATUS_CONTINUE;
2042c9de560dSAlex Tomas 			ac->ac_flags |= EXT4_MB_HINT_FIRST;
2043c9de560dSAlex Tomas 			cr = 3;
2044c9de560dSAlex Tomas 			atomic_inc(&sbi->s_mb_lost_chunks);
2045c9de560dSAlex Tomas 			goto repeat;
2046c9de560dSAlex Tomas 		}
2047c9de560dSAlex Tomas 	}
2048c9de560dSAlex Tomas out:
2049c9de560dSAlex Tomas 	return err;
2050c9de560dSAlex Tomas }
2051c9de560dSAlex Tomas 
2052c9de560dSAlex Tomas static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2053c9de560dSAlex Tomas {
2054c9de560dSAlex Tomas 	struct super_block *sb = seq->private;
2055c9de560dSAlex Tomas 	ext4_group_t group;
2056c9de560dSAlex Tomas 
20578df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2058c9de560dSAlex Tomas 		return NULL;
2059c9de560dSAlex Tomas 	group = *pos + 1;
2060a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
2061c9de560dSAlex Tomas }
2062c9de560dSAlex Tomas 
2063c9de560dSAlex Tomas static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2064c9de560dSAlex Tomas {
2065c9de560dSAlex Tomas 	struct super_block *sb = seq->private;
2066c9de560dSAlex Tomas 	ext4_group_t group;
2067c9de560dSAlex Tomas 
2068c9de560dSAlex Tomas 	++*pos;
20698df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2070c9de560dSAlex Tomas 		return NULL;
2071c9de560dSAlex Tomas 	group = *pos + 1;
2072a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
2073c9de560dSAlex Tomas }
2074c9de560dSAlex Tomas 
2075c9de560dSAlex Tomas static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2076c9de560dSAlex Tomas {
2077c9de560dSAlex Tomas 	struct super_block *sb = seq->private;
2078a9df9a49STheodore Ts'o 	ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2079c9de560dSAlex Tomas 	int i;
2080c9de560dSAlex Tomas 	int err;
2081c9de560dSAlex Tomas 	struct ext4_buddy e4b;
2082c9de560dSAlex Tomas 	struct sg {
2083c9de560dSAlex Tomas 		struct ext4_group_info info;
2084a36b4498SEric Sandeen 		ext4_grpblk_t counters[16];
2085c9de560dSAlex Tomas 	} sg;
2086c9de560dSAlex Tomas 
2087c9de560dSAlex Tomas 	group--;
2088c9de560dSAlex Tomas 	if (group == 0)
2089c9de560dSAlex Tomas 		seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
2090c9de560dSAlex Tomas 				"[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2091c9de560dSAlex Tomas 				  "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2092c9de560dSAlex Tomas 			   "group", "free", "frags", "first",
2093c9de560dSAlex Tomas 			   "2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
2094c9de560dSAlex Tomas 			   "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2095c9de560dSAlex Tomas 
2096c9de560dSAlex Tomas 	i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2097c9de560dSAlex Tomas 		sizeof(struct ext4_group_info);
2098c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(sb, group, &e4b);
2099c9de560dSAlex Tomas 	if (err) {
2100a9df9a49STheodore Ts'o 		seq_printf(seq, "#%-5u: I/O error\n", group);
2101c9de560dSAlex Tomas 		return 0;
2102c9de560dSAlex Tomas 	}
2103c9de560dSAlex Tomas 	ext4_lock_group(sb, group);
2104c9de560dSAlex Tomas 	memcpy(&sg, ext4_get_group_info(sb, group), i);
2105c9de560dSAlex Tomas 	ext4_unlock_group(sb, group);
2106e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
2107c9de560dSAlex Tomas 
2108a9df9a49STheodore Ts'o 	seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2109c9de560dSAlex Tomas 			sg.info.bb_fragments, sg.info.bb_first_free);
2110c9de560dSAlex Tomas 	for (i = 0; i <= 13; i++)
2111c9de560dSAlex Tomas 		seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2112c9de560dSAlex Tomas 				sg.info.bb_counters[i] : 0);
2113c9de560dSAlex Tomas 	seq_printf(seq, " ]\n");
2114c9de560dSAlex Tomas 
2115c9de560dSAlex Tomas 	return 0;
2116c9de560dSAlex Tomas }
2117c9de560dSAlex Tomas 
2118c9de560dSAlex Tomas static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2119c9de560dSAlex Tomas {
2120c9de560dSAlex Tomas }
2121c9de560dSAlex Tomas 
21227f1346a9STobias Klauser static const struct seq_operations ext4_mb_seq_groups_ops = {
2123c9de560dSAlex Tomas 	.start  = ext4_mb_seq_groups_start,
2124c9de560dSAlex Tomas 	.next   = ext4_mb_seq_groups_next,
2125c9de560dSAlex Tomas 	.stop   = ext4_mb_seq_groups_stop,
2126c9de560dSAlex Tomas 	.show   = ext4_mb_seq_groups_show,
2127c9de560dSAlex Tomas };
2128c9de560dSAlex Tomas 
2129c9de560dSAlex Tomas static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2130c9de560dSAlex Tomas {
2131c9de560dSAlex Tomas 	struct super_block *sb = PDE(inode)->data;
2132c9de560dSAlex Tomas 	int rc;
2133c9de560dSAlex Tomas 
2134c9de560dSAlex Tomas 	rc = seq_open(file, &ext4_mb_seq_groups_ops);
2135c9de560dSAlex Tomas 	if (rc == 0) {
2136a271fe85SJoe Perches 		struct seq_file *m = file->private_data;
2137c9de560dSAlex Tomas 		m->private = sb;
2138c9de560dSAlex Tomas 	}
2139c9de560dSAlex Tomas 	return rc;
2140c9de560dSAlex Tomas 
2141c9de560dSAlex Tomas }
2142c9de560dSAlex Tomas 
21437f1346a9STobias Klauser static const struct file_operations ext4_mb_seq_groups_fops = {
2144c9de560dSAlex Tomas 	.owner		= THIS_MODULE,
2145c9de560dSAlex Tomas 	.open		= ext4_mb_seq_groups_open,
2146c9de560dSAlex Tomas 	.read		= seq_read,
2147c9de560dSAlex Tomas 	.llseek		= seq_lseek,
2148c9de560dSAlex Tomas 	.release	= seq_release,
2149c9de560dSAlex Tomas };
2150c9de560dSAlex Tomas 
2151fb1813f4SCurt Wohlgemuth static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2152fb1813f4SCurt Wohlgemuth {
2153fb1813f4SCurt Wohlgemuth 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2154fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2155fb1813f4SCurt Wohlgemuth 
2156fb1813f4SCurt Wohlgemuth 	BUG_ON(!cachep);
2157fb1813f4SCurt Wohlgemuth 	return cachep;
2158fb1813f4SCurt Wohlgemuth }
21595f21b0e6SFrederic Bohe 
21605f21b0e6SFrederic Bohe /* Create and initialize ext4_group_info data for the given group. */
2161920313a7SAneesh Kumar K.V int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
21625f21b0e6SFrederic Bohe 			  struct ext4_group_desc *desc)
21635f21b0e6SFrederic Bohe {
2164fb1813f4SCurt Wohlgemuth 	int i;
21655f21b0e6SFrederic Bohe 	int metalen = 0;
21665f21b0e6SFrederic Bohe 	struct ext4_sb_info *sbi = EXT4_SB(sb);
21675f21b0e6SFrederic Bohe 	struct ext4_group_info **meta_group_info;
2168fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
21695f21b0e6SFrederic Bohe 
21705f21b0e6SFrederic Bohe 	/*
21715f21b0e6SFrederic Bohe 	 * First check if this group is the first of a reserved block.
21725f21b0e6SFrederic Bohe 	 * If it's true, we have to allocate a new table of pointers
21735f21b0e6SFrederic Bohe 	 * to ext4_group_info structures
21745f21b0e6SFrederic Bohe 	 */
21755f21b0e6SFrederic Bohe 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
21765f21b0e6SFrederic Bohe 		metalen = sizeof(*meta_group_info) <<
21775f21b0e6SFrederic Bohe 			EXT4_DESC_PER_BLOCK_BITS(sb);
21785f21b0e6SFrederic Bohe 		meta_group_info = kmalloc(metalen, GFP_KERNEL);
21795f21b0e6SFrederic Bohe 		if (meta_group_info == NULL) {
21807f6a11e7SJoe Perches 			ext4_msg(sb, KERN_ERR, "can't allocate mem "
21819d8b9ec4STheodore Ts'o 				 "for a buddy group");
21825f21b0e6SFrederic Bohe 			goto exit_meta_group_info;
21835f21b0e6SFrederic Bohe 		}
21845f21b0e6SFrederic Bohe 		sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] =
21855f21b0e6SFrederic Bohe 			meta_group_info;
21865f21b0e6SFrederic Bohe 	}
21875f21b0e6SFrederic Bohe 
21885f21b0e6SFrederic Bohe 	meta_group_info =
21895f21b0e6SFrederic Bohe 		sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)];
21905f21b0e6SFrederic Bohe 	i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
21915f21b0e6SFrederic Bohe 
2192fb1813f4SCurt Wohlgemuth 	meta_group_info[i] = kmem_cache_alloc(cachep, GFP_KERNEL);
21935f21b0e6SFrederic Bohe 	if (meta_group_info[i] == NULL) {
21947f6a11e7SJoe Perches 		ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
21955f21b0e6SFrederic Bohe 		goto exit_group_info;
21965f21b0e6SFrederic Bohe 	}
2197fb1813f4SCurt Wohlgemuth 	memset(meta_group_info[i], 0, kmem_cache_size(cachep));
21985f21b0e6SFrederic Bohe 	set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
21995f21b0e6SFrederic Bohe 		&(meta_group_info[i]->bb_state));
22005f21b0e6SFrederic Bohe 
22015f21b0e6SFrederic Bohe 	/*
22025f21b0e6SFrederic Bohe 	 * initialize bb_free to be able to skip
22035f21b0e6SFrederic Bohe 	 * empty groups without initialization
22045f21b0e6SFrederic Bohe 	 */
22055f21b0e6SFrederic Bohe 	if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
22065f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
2207cff1dfd7STheodore Ts'o 			ext4_free_clusters_after_init(sb, group, desc);
22085f21b0e6SFrederic Bohe 	} else {
22095f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
2210021b65bbSTheodore Ts'o 			ext4_free_group_clusters(sb, desc);
22115f21b0e6SFrederic Bohe 	}
22125f21b0e6SFrederic Bohe 
22135f21b0e6SFrederic Bohe 	INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2214920313a7SAneesh Kumar K.V 	init_rwsem(&meta_group_info[i]->alloc_sem);
221564e290ecSVenkatesh Pallipadi 	meta_group_info[i]->bb_free_root = RB_ROOT;
22168a57d9d6SCurt Wohlgemuth 	meta_group_info[i]->bb_largest_free_order = -1;  /* uninit */
22175f21b0e6SFrederic Bohe 
22185f21b0e6SFrederic Bohe #ifdef DOUBLE_CHECK
22195f21b0e6SFrederic Bohe 	{
22205f21b0e6SFrederic Bohe 		struct buffer_head *bh;
22215f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_bitmap =
22225f21b0e6SFrederic Bohe 			kmalloc(sb->s_blocksize, GFP_KERNEL);
22235f21b0e6SFrederic Bohe 		BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
22245f21b0e6SFrederic Bohe 		bh = ext4_read_block_bitmap(sb, group);
22255f21b0e6SFrederic Bohe 		BUG_ON(bh == NULL);
22265f21b0e6SFrederic Bohe 		memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
22275f21b0e6SFrederic Bohe 			sb->s_blocksize);
22285f21b0e6SFrederic Bohe 		put_bh(bh);
22295f21b0e6SFrederic Bohe 	}
22305f21b0e6SFrederic Bohe #endif
22315f21b0e6SFrederic Bohe 
22325f21b0e6SFrederic Bohe 	return 0;
22335f21b0e6SFrederic Bohe 
22345f21b0e6SFrederic Bohe exit_group_info:
22355f21b0e6SFrederic Bohe 	/* If a meta_group_info table has been allocated, release it now */
2236caaf7a29STao Ma 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
22375f21b0e6SFrederic Bohe 		kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
2238caaf7a29STao Ma 		sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] = NULL;
2239caaf7a29STao Ma 	}
22405f21b0e6SFrederic Bohe exit_meta_group_info:
22415f21b0e6SFrederic Bohe 	return -ENOMEM;
22425f21b0e6SFrederic Bohe } /* ext4_mb_add_groupinfo */
22435f21b0e6SFrederic Bohe 
2244c9de560dSAlex Tomas static int ext4_mb_init_backend(struct super_block *sb)
2245c9de560dSAlex Tomas {
22468df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
2247c9de560dSAlex Tomas 	ext4_group_t i;
2248c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
22495f21b0e6SFrederic Bohe 	struct ext4_super_block *es = sbi->s_es;
22505f21b0e6SFrederic Bohe 	int num_meta_group_infos;
22515f21b0e6SFrederic Bohe 	int num_meta_group_infos_max;
22525f21b0e6SFrederic Bohe 	int array_size;
22535f21b0e6SFrederic Bohe 	struct ext4_group_desc *desc;
2254fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep;
2255c9de560dSAlex Tomas 
22565f21b0e6SFrederic Bohe 	/* This is the number of blocks used by GDT */
22578df9675fSTheodore Ts'o 	num_meta_group_infos = (ngroups + EXT4_DESC_PER_BLOCK(sb) -
22585f21b0e6SFrederic Bohe 				1) >> EXT4_DESC_PER_BLOCK_BITS(sb);
22595f21b0e6SFrederic Bohe 
22605f21b0e6SFrederic Bohe 	/*
22615f21b0e6SFrederic Bohe 	 * This is the total number of blocks used by GDT including
22625f21b0e6SFrederic Bohe 	 * the number of reserved blocks for GDT.
22635f21b0e6SFrederic Bohe 	 * The s_group_info array is allocated with this value
22645f21b0e6SFrederic Bohe 	 * to allow a clean online resize without a complex
22655f21b0e6SFrederic Bohe 	 * manipulation of pointer.
22665f21b0e6SFrederic Bohe 	 * The drawback is the unused memory when no resize
22675f21b0e6SFrederic Bohe 	 * occurs but it's very low in terms of pages
22685f21b0e6SFrederic Bohe 	 * (see comments below)
22695f21b0e6SFrederic Bohe 	 * Need to handle this properly when META_BG resizing is allowed
22705f21b0e6SFrederic Bohe 	 */
22715f21b0e6SFrederic Bohe 	num_meta_group_infos_max = num_meta_group_infos +
22725f21b0e6SFrederic Bohe 				le16_to_cpu(es->s_reserved_gdt_blocks);
22735f21b0e6SFrederic Bohe 
22745f21b0e6SFrederic Bohe 	/*
22755f21b0e6SFrederic Bohe 	 * array_size is the size of s_group_info array. We round it
22765f21b0e6SFrederic Bohe 	 * to the next power of two because this approximation is done
22775f21b0e6SFrederic Bohe 	 * internally by kmalloc so we can have some more memory
22785f21b0e6SFrederic Bohe 	 * for free here (e.g. may be used for META_BG resize).
22795f21b0e6SFrederic Bohe 	 */
22805f21b0e6SFrederic Bohe 	array_size = 1;
22815f21b0e6SFrederic Bohe 	while (array_size < sizeof(*sbi->s_group_info) *
22825f21b0e6SFrederic Bohe 	       num_meta_group_infos_max)
22835f21b0e6SFrederic Bohe 		array_size = array_size << 1;
2284c9de560dSAlex Tomas 	/* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2285c9de560dSAlex Tomas 	 * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2286c9de560dSAlex Tomas 	 * So a two level scheme suffices for now. */
2287f18a5f21STheodore Ts'o 	sbi->s_group_info = ext4_kvzalloc(array_size, GFP_KERNEL);
2288c9de560dSAlex Tomas 	if (sbi->s_group_info == NULL) {
22899d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
2290c9de560dSAlex Tomas 		return -ENOMEM;
2291c9de560dSAlex Tomas 	}
2292c9de560dSAlex Tomas 	sbi->s_buddy_cache = new_inode(sb);
2293c9de560dSAlex Tomas 	if (sbi->s_buddy_cache == NULL) {
22949d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_ERR, "can't get new inode");
2295c9de560dSAlex Tomas 		goto err_freesgi;
2296c9de560dSAlex Tomas 	}
229748e6061bSYu Jian 	/* To avoid potentially colliding with an valid on-disk inode number,
229848e6061bSYu Jian 	 * use EXT4_BAD_INO for the buddy cache inode number.  This inode is
229948e6061bSYu Jian 	 * not in the inode hash, so it should never be found by iget(), but
230048e6061bSYu Jian 	 * this will avoid confusion if it ever shows up during debugging. */
230148e6061bSYu Jian 	sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
2302c9de560dSAlex Tomas 	EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
23038df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
2304c9de560dSAlex Tomas 		desc = ext4_get_group_desc(sb, i, NULL);
2305c9de560dSAlex Tomas 		if (desc == NULL) {
23069d8b9ec4STheodore Ts'o 			ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2307c9de560dSAlex Tomas 			goto err_freebuddy;
2308c9de560dSAlex Tomas 		}
23095f21b0e6SFrederic Bohe 		if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
23105f21b0e6SFrederic Bohe 			goto err_freebuddy;
2311c9de560dSAlex Tomas 	}
2312c9de560dSAlex Tomas 
2313c9de560dSAlex Tomas 	return 0;
2314c9de560dSAlex Tomas 
2315c9de560dSAlex Tomas err_freebuddy:
2316fb1813f4SCurt Wohlgemuth 	cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2317f1fa3342SRoel Kluin 	while (i-- > 0)
2318fb1813f4SCurt Wohlgemuth 		kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2319c9de560dSAlex Tomas 	i = num_meta_group_infos;
2320f1fa3342SRoel Kluin 	while (i-- > 0)
2321c9de560dSAlex Tomas 		kfree(sbi->s_group_info[i]);
2322c9de560dSAlex Tomas 	iput(sbi->s_buddy_cache);
2323c9de560dSAlex Tomas err_freesgi:
2324f18a5f21STheodore Ts'o 	ext4_kvfree(sbi->s_group_info);
2325c9de560dSAlex Tomas 	return -ENOMEM;
2326c9de560dSAlex Tomas }
2327c9de560dSAlex Tomas 
23282892c15dSEric Sandeen static void ext4_groupinfo_destroy_slabs(void)
23292892c15dSEric Sandeen {
23302892c15dSEric Sandeen 	int i;
23312892c15dSEric Sandeen 
23322892c15dSEric Sandeen 	for (i = 0; i < NR_GRPINFO_CACHES; i++) {
23332892c15dSEric Sandeen 		if (ext4_groupinfo_caches[i])
23342892c15dSEric Sandeen 			kmem_cache_destroy(ext4_groupinfo_caches[i]);
23352892c15dSEric Sandeen 		ext4_groupinfo_caches[i] = NULL;
23362892c15dSEric Sandeen 	}
23372892c15dSEric Sandeen }
23382892c15dSEric Sandeen 
23392892c15dSEric Sandeen static int ext4_groupinfo_create_slab(size_t size)
23402892c15dSEric Sandeen {
23412892c15dSEric Sandeen 	static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
23422892c15dSEric Sandeen 	int slab_size;
23432892c15dSEric Sandeen 	int blocksize_bits = order_base_2(size);
23442892c15dSEric Sandeen 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
23452892c15dSEric Sandeen 	struct kmem_cache *cachep;
23462892c15dSEric Sandeen 
23472892c15dSEric Sandeen 	if (cache_index >= NR_GRPINFO_CACHES)
23482892c15dSEric Sandeen 		return -EINVAL;
23492892c15dSEric Sandeen 
23502892c15dSEric Sandeen 	if (unlikely(cache_index < 0))
23512892c15dSEric Sandeen 		cache_index = 0;
23522892c15dSEric Sandeen 
23532892c15dSEric Sandeen 	mutex_lock(&ext4_grpinfo_slab_create_mutex);
23542892c15dSEric Sandeen 	if (ext4_groupinfo_caches[cache_index]) {
23552892c15dSEric Sandeen 		mutex_unlock(&ext4_grpinfo_slab_create_mutex);
23562892c15dSEric Sandeen 		return 0;	/* Already created */
23572892c15dSEric Sandeen 	}
23582892c15dSEric Sandeen 
23592892c15dSEric Sandeen 	slab_size = offsetof(struct ext4_group_info,
23602892c15dSEric Sandeen 				bb_counters[blocksize_bits + 2]);
23612892c15dSEric Sandeen 
23622892c15dSEric Sandeen 	cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
23632892c15dSEric Sandeen 					slab_size, 0, SLAB_RECLAIM_ACCOUNT,
23642892c15dSEric Sandeen 					NULL);
23652892c15dSEric Sandeen 
2366823ba01fSTao Ma 	ext4_groupinfo_caches[cache_index] = cachep;
2367823ba01fSTao Ma 
23682892c15dSEric Sandeen 	mutex_unlock(&ext4_grpinfo_slab_create_mutex);
23692892c15dSEric Sandeen 	if (!cachep) {
23709d8b9ec4STheodore Ts'o 		printk(KERN_EMERG
23719d8b9ec4STheodore Ts'o 		       "EXT4-fs: no memory for groupinfo slab cache\n");
23722892c15dSEric Sandeen 		return -ENOMEM;
23732892c15dSEric Sandeen 	}
23742892c15dSEric Sandeen 
23752892c15dSEric Sandeen 	return 0;
23762892c15dSEric Sandeen }
23772892c15dSEric Sandeen 
2378c9de560dSAlex Tomas int ext4_mb_init(struct super_block *sb, int needs_recovery)
2379c9de560dSAlex Tomas {
2380c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
23816be2ded1SAneesh Kumar K.V 	unsigned i, j;
2382c9de560dSAlex Tomas 	unsigned offset;
2383c9de560dSAlex Tomas 	unsigned max;
238474767c5aSShen Feng 	int ret;
2385c9de560dSAlex Tomas 
23861927805eSEric Sandeen 	i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2387c9de560dSAlex Tomas 
2388c9de560dSAlex Tomas 	sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2389c9de560dSAlex Tomas 	if (sbi->s_mb_offsets == NULL) {
2390fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
2391fb1813f4SCurt Wohlgemuth 		goto out;
2392c9de560dSAlex Tomas 	}
2393ff7ef329SYasunori Goto 
23941927805eSEric Sandeen 	i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2395c9de560dSAlex Tomas 	sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2396c9de560dSAlex Tomas 	if (sbi->s_mb_maxs == NULL) {
2397fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
2398fb1813f4SCurt Wohlgemuth 		goto out;
2399fb1813f4SCurt Wohlgemuth 	}
2400fb1813f4SCurt Wohlgemuth 
24012892c15dSEric Sandeen 	ret = ext4_groupinfo_create_slab(sb->s_blocksize);
24022892c15dSEric Sandeen 	if (ret < 0)
2403fb1813f4SCurt Wohlgemuth 		goto out;
2404c9de560dSAlex Tomas 
2405c9de560dSAlex Tomas 	/* order 0 is regular bitmap */
2406c9de560dSAlex Tomas 	sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2407c9de560dSAlex Tomas 	sbi->s_mb_offsets[0] = 0;
2408c9de560dSAlex Tomas 
2409c9de560dSAlex Tomas 	i = 1;
2410c9de560dSAlex Tomas 	offset = 0;
2411c9de560dSAlex Tomas 	max = sb->s_blocksize << 2;
2412c9de560dSAlex Tomas 	do {
2413c9de560dSAlex Tomas 		sbi->s_mb_offsets[i] = offset;
2414c9de560dSAlex Tomas 		sbi->s_mb_maxs[i] = max;
2415c9de560dSAlex Tomas 		offset += 1 << (sb->s_blocksize_bits - i);
2416c9de560dSAlex Tomas 		max = max >> 1;
2417c9de560dSAlex Tomas 		i++;
2418c9de560dSAlex Tomas 	} while (i <= sb->s_blocksize_bits + 1);
2419c9de560dSAlex Tomas 
2420c9de560dSAlex Tomas 	spin_lock_init(&sbi->s_md_lock);
2421c9de560dSAlex Tomas 	spin_lock_init(&sbi->s_bal_lock);
2422c9de560dSAlex Tomas 
2423c9de560dSAlex Tomas 	sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2424c9de560dSAlex Tomas 	sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2425c9de560dSAlex Tomas 	sbi->s_mb_stats = MB_DEFAULT_STATS;
2426c9de560dSAlex Tomas 	sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2427c9de560dSAlex Tomas 	sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
242827baebb8STheodore Ts'o 	/*
242927baebb8STheodore Ts'o 	 * The default group preallocation is 512, which for 4k block
243027baebb8STheodore Ts'o 	 * sizes translates to 2 megabytes.  However for bigalloc file
243127baebb8STheodore Ts'o 	 * systems, this is probably too big (i.e, if the cluster size
243227baebb8STheodore Ts'o 	 * is 1 megabyte, then group preallocation size becomes half a
243327baebb8STheodore Ts'o 	 * gigabyte!).  As a default, we will keep a two megabyte
243427baebb8STheodore Ts'o 	 * group pralloc size for cluster sizes up to 64k, and after
243527baebb8STheodore Ts'o 	 * that, we will force a minimum group preallocation size of
243627baebb8STheodore Ts'o 	 * 32 clusters.  This translates to 8 megs when the cluster
243727baebb8STheodore Ts'o 	 * size is 256k, and 32 megs when the cluster size is 1 meg,
243827baebb8STheodore Ts'o 	 * which seems reasonable as a default.
243927baebb8STheodore Ts'o 	 */
244027baebb8STheodore Ts'o 	sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
244127baebb8STheodore Ts'o 				       sbi->s_cluster_bits, 32);
2442d7a1fee1SDan Ehrenberg 	/*
2443d7a1fee1SDan Ehrenberg 	 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
2444d7a1fee1SDan Ehrenberg 	 * to the lowest multiple of s_stripe which is bigger than
2445d7a1fee1SDan Ehrenberg 	 * the s_mb_group_prealloc as determined above. We want
2446d7a1fee1SDan Ehrenberg 	 * the preallocation size to be an exact multiple of the
2447d7a1fee1SDan Ehrenberg 	 * RAID stripe size so that preallocations don't fragment
2448d7a1fee1SDan Ehrenberg 	 * the stripes.
2449d7a1fee1SDan Ehrenberg 	 */
2450d7a1fee1SDan Ehrenberg 	if (sbi->s_stripe > 1) {
2451d7a1fee1SDan Ehrenberg 		sbi->s_mb_group_prealloc = roundup(
2452d7a1fee1SDan Ehrenberg 			sbi->s_mb_group_prealloc, sbi->s_stripe);
2453d7a1fee1SDan Ehrenberg 	}
2454c9de560dSAlex Tomas 
2455730c213cSEric Sandeen 	sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2456c9de560dSAlex Tomas 	if (sbi->s_locality_groups == NULL) {
2457fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
24587aa0baeaSTao Ma 		goto out_free_groupinfo_slab;
2459c9de560dSAlex Tomas 	}
2460730c213cSEric Sandeen 	for_each_possible_cpu(i) {
2461c9de560dSAlex Tomas 		struct ext4_locality_group *lg;
2462730c213cSEric Sandeen 		lg = per_cpu_ptr(sbi->s_locality_groups, i);
2463c9de560dSAlex Tomas 		mutex_init(&lg->lg_mutex);
24646be2ded1SAneesh Kumar K.V 		for (j = 0; j < PREALLOC_TB_SIZE; j++)
24656be2ded1SAneesh Kumar K.V 			INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2466c9de560dSAlex Tomas 		spin_lock_init(&lg->lg_prealloc_lock);
2467c9de560dSAlex Tomas 	}
2468c9de560dSAlex Tomas 
246979a77c5aSYu Jian 	/* init file for buddy data */
247079a77c5aSYu Jian 	ret = ext4_mb_init_backend(sb);
24717aa0baeaSTao Ma 	if (ret != 0)
24727aa0baeaSTao Ma 		goto out_free_locality_groups;
247379a77c5aSYu Jian 
2474296c355cSTheodore Ts'o 	if (sbi->s_proc)
2475296c355cSTheodore Ts'o 		proc_create_data("mb_groups", S_IRUGO, sbi->s_proc,
2476296c355cSTheodore Ts'o 				 &ext4_mb_seq_groups_fops, sb);
2477c9de560dSAlex Tomas 
24787aa0baeaSTao Ma 	return 0;
24797aa0baeaSTao Ma 
24807aa0baeaSTao Ma out_free_locality_groups:
24817aa0baeaSTao Ma 	free_percpu(sbi->s_locality_groups);
24827aa0baeaSTao Ma 	sbi->s_locality_groups = NULL;
24837aa0baeaSTao Ma out_free_groupinfo_slab:
24847aa0baeaSTao Ma 	ext4_groupinfo_destroy_slabs();
2485fb1813f4SCurt Wohlgemuth out:
2486fb1813f4SCurt Wohlgemuth 	kfree(sbi->s_mb_offsets);
24877aa0baeaSTao Ma 	sbi->s_mb_offsets = NULL;
2488fb1813f4SCurt Wohlgemuth 	kfree(sbi->s_mb_maxs);
24897aa0baeaSTao Ma 	sbi->s_mb_maxs = NULL;
2490fb1813f4SCurt Wohlgemuth 	return ret;
2491c9de560dSAlex Tomas }
2492c9de560dSAlex Tomas 
2493955ce5f5SAneesh Kumar K.V /* need to called with the ext4 group lock held */
2494c9de560dSAlex Tomas static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2495c9de560dSAlex Tomas {
2496c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
2497c9de560dSAlex Tomas 	struct list_head *cur, *tmp;
2498c9de560dSAlex Tomas 	int count = 0;
2499c9de560dSAlex Tomas 
2500c9de560dSAlex Tomas 	list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2501c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2502c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
2503c9de560dSAlex Tomas 		count++;
2504688f05a0SAneesh Kumar K.V 		kmem_cache_free(ext4_pspace_cachep, pa);
2505c9de560dSAlex Tomas 	}
2506c9de560dSAlex Tomas 	if (count)
25076ba495e9STheodore Ts'o 		mb_debug(1, "mballoc: %u PAs left\n", count);
2508c9de560dSAlex Tomas 
2509c9de560dSAlex Tomas }
2510c9de560dSAlex Tomas 
2511c9de560dSAlex Tomas int ext4_mb_release(struct super_block *sb)
2512c9de560dSAlex Tomas {
25138df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
2514c9de560dSAlex Tomas 	ext4_group_t i;
2515c9de560dSAlex Tomas 	int num_meta_group_infos;
2516c9de560dSAlex Tomas 	struct ext4_group_info *grinfo;
2517c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2518fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2519c9de560dSAlex Tomas 
2520c9de560dSAlex Tomas 	if (sbi->s_group_info) {
25218df9675fSTheodore Ts'o 		for (i = 0; i < ngroups; i++) {
2522c9de560dSAlex Tomas 			grinfo = ext4_get_group_info(sb, i);
2523c9de560dSAlex Tomas #ifdef DOUBLE_CHECK
2524c9de560dSAlex Tomas 			kfree(grinfo->bb_bitmap);
2525c9de560dSAlex Tomas #endif
2526c9de560dSAlex Tomas 			ext4_lock_group(sb, i);
2527c9de560dSAlex Tomas 			ext4_mb_cleanup_pa(grinfo);
2528c9de560dSAlex Tomas 			ext4_unlock_group(sb, i);
2529fb1813f4SCurt Wohlgemuth 			kmem_cache_free(cachep, grinfo);
2530c9de560dSAlex Tomas 		}
25318df9675fSTheodore Ts'o 		num_meta_group_infos = (ngroups +
2532c9de560dSAlex Tomas 				EXT4_DESC_PER_BLOCK(sb) - 1) >>
2533c9de560dSAlex Tomas 			EXT4_DESC_PER_BLOCK_BITS(sb);
2534c9de560dSAlex Tomas 		for (i = 0; i < num_meta_group_infos; i++)
2535c9de560dSAlex Tomas 			kfree(sbi->s_group_info[i]);
2536f18a5f21STheodore Ts'o 		ext4_kvfree(sbi->s_group_info);
2537c9de560dSAlex Tomas 	}
2538c9de560dSAlex Tomas 	kfree(sbi->s_mb_offsets);
2539c9de560dSAlex Tomas 	kfree(sbi->s_mb_maxs);
2540c9de560dSAlex Tomas 	if (sbi->s_buddy_cache)
2541c9de560dSAlex Tomas 		iput(sbi->s_buddy_cache);
2542c9de560dSAlex Tomas 	if (sbi->s_mb_stats) {
25439d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
25449d8b9ec4STheodore Ts'o 		       "mballoc: %u blocks %u reqs (%u success)",
2545c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_allocated),
2546c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_reqs),
2547c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_success));
25489d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
25499d8b9ec4STheodore Ts'o 		      "mballoc: %u extents scanned, %u goal hits, "
25509d8b9ec4STheodore Ts'o 				"%u 2^N hits, %u breaks, %u lost",
2551c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_ex_scanned),
2552c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_goals),
2553c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_2orders),
2554c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_breaks),
2555c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_lost_chunks));
25569d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
25579d8b9ec4STheodore Ts'o 		       "mballoc: %lu generated and it took %Lu",
2558ced156e4STao Ma 				sbi->s_mb_buddies_generated,
2559c9de560dSAlex Tomas 				sbi->s_mb_generation_time);
25609d8b9ec4STheodore Ts'o 		ext4_msg(sb, KERN_INFO,
25619d8b9ec4STheodore Ts'o 		       "mballoc: %u preallocated, %u discarded",
2562c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_preallocated),
2563c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_discarded));
2564c9de560dSAlex Tomas 	}
2565c9de560dSAlex Tomas 
2566730c213cSEric Sandeen 	free_percpu(sbi->s_locality_groups);
2567296c355cSTheodore Ts'o 	if (sbi->s_proc)
2568296c355cSTheodore Ts'o 		remove_proc_entry("mb_groups", sbi->s_proc);
2569c9de560dSAlex Tomas 
2570c9de560dSAlex Tomas 	return 0;
2571c9de560dSAlex Tomas }
2572c9de560dSAlex Tomas 
257377ca6cdfSLukas Czerner static inline int ext4_issue_discard(struct super_block *sb,
257484130193STheodore Ts'o 		ext4_group_t block_group, ext4_grpblk_t cluster, int count)
25755c521830SJiaying Zhang {
25765c521830SJiaying Zhang 	ext4_fsblk_t discard_block;
25775c521830SJiaying Zhang 
257884130193STheodore Ts'o 	discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
257984130193STheodore Ts'o 			 ext4_group_first_block_no(sb, block_group));
258084130193STheodore Ts'o 	count = EXT4_C2B(EXT4_SB(sb), count);
25815c521830SJiaying Zhang 	trace_ext4_discard_blocks(sb,
25825c521830SJiaying Zhang 			(unsigned long long) discard_block, count);
258393259636SLukas Czerner 	return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
25845c521830SJiaying Zhang }
25855c521830SJiaying Zhang 
25863e624fc7STheodore Ts'o /*
25873e624fc7STheodore Ts'o  * This function is called by the jbd2 layer once the commit has finished,
25883e624fc7STheodore Ts'o  * so we know we can free the blocks that were released with that commit.
25893e624fc7STheodore Ts'o  */
259018aadd47SBobi Jam static void ext4_free_data_callback(struct super_block *sb,
259118aadd47SBobi Jam 				    struct ext4_journal_cb_entry *jce,
259218aadd47SBobi Jam 				    int rc)
2593c9de560dSAlex Tomas {
259418aadd47SBobi Jam 	struct ext4_free_data *entry = (struct ext4_free_data *)jce;
2595c9de560dSAlex Tomas 	struct ext4_buddy e4b;
2596c894058dSAneesh Kumar K.V 	struct ext4_group_info *db;
2597d9f34504STheodore Ts'o 	int err, count = 0, count2 = 0;
2598c9de560dSAlex Tomas 
25996ba495e9STheodore Ts'o 	mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
260018aadd47SBobi Jam 		 entry->efd_count, entry->efd_group, entry);
2601c9de560dSAlex Tomas 
2602d9f34504STheodore Ts'o 	if (test_opt(sb, DISCARD))
260318aadd47SBobi Jam 		ext4_issue_discard(sb, entry->efd_group,
260418aadd47SBobi Jam 				   entry->efd_start_cluster, entry->efd_count);
2605b90f6870STheodore Ts'o 
260618aadd47SBobi Jam 	err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
2607c9de560dSAlex Tomas 	/* we expect to find existing buddy because it's pinned */
2608c9de560dSAlex Tomas 	BUG_ON(err != 0);
2609c9de560dSAlex Tomas 
261018aadd47SBobi Jam 
2611c894058dSAneesh Kumar K.V 	db = e4b.bd_info;
2612c9de560dSAlex Tomas 	/* there are blocks to put in buddy to make them really free */
261318aadd47SBobi Jam 	count += entry->efd_count;
2614c9de560dSAlex Tomas 	count2++;
261518aadd47SBobi Jam 	ext4_lock_group(sb, entry->efd_group);
2616c894058dSAneesh Kumar K.V 	/* Take it out of per group rb tree */
261718aadd47SBobi Jam 	rb_erase(&entry->efd_node, &(db->bb_free_root));
261818aadd47SBobi Jam 	mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
2619c9de560dSAlex Tomas 
26203d56b8d2STao Ma 	/*
26213d56b8d2STao Ma 	 * Clear the trimmed flag for the group so that the next
26223d56b8d2STao Ma 	 * ext4_trim_fs can trim it.
26233d56b8d2STao Ma 	 * If the volume is mounted with -o discard, online discard
26243d56b8d2STao Ma 	 * is supported and the free blocks will be trimmed online.
26253d56b8d2STao Ma 	 */
26263d56b8d2STao Ma 	if (!test_opt(sb, DISCARD))
26273d56b8d2STao Ma 		EXT4_MB_GRP_CLEAR_TRIMMED(db);
26283d56b8d2STao Ma 
2629c894058dSAneesh Kumar K.V 	if (!db->bb_free_root.rb_node) {
2630c894058dSAneesh Kumar K.V 		/* No more items in the per group rb tree
2631c894058dSAneesh Kumar K.V 		 * balance refcounts from ext4_mb_free_metadata()
2632c894058dSAneesh Kumar K.V 		 */
2633c9de560dSAlex Tomas 		page_cache_release(e4b.bd_buddy_page);
2634c9de560dSAlex Tomas 		page_cache_release(e4b.bd_bitmap_page);
2635c894058dSAneesh Kumar K.V 	}
263618aadd47SBobi Jam 	ext4_unlock_group(sb, entry->efd_group);
263718aadd47SBobi Jam 	kmem_cache_free(ext4_free_data_cachep, entry);
2638e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
2639c9de560dSAlex Tomas 
26406ba495e9STheodore Ts'o 	mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2641c9de560dSAlex Tomas }
2642c9de560dSAlex Tomas 
26436ba495e9STheodore Ts'o #ifdef CONFIG_EXT4_DEBUG
26446ba495e9STheodore Ts'o u8 mb_enable_debug __read_mostly;
26456ba495e9STheodore Ts'o 
26466ba495e9STheodore Ts'o static struct dentry *debugfs_dir;
26476ba495e9STheodore Ts'o static struct dentry *debugfs_debug;
26486ba495e9STheodore Ts'o 
26496ba495e9STheodore Ts'o static void __init ext4_create_debugfs_entry(void)
26506ba495e9STheodore Ts'o {
26516ba495e9STheodore Ts'o 	debugfs_dir = debugfs_create_dir("ext4", NULL);
26526ba495e9STheodore Ts'o 	if (debugfs_dir)
26536ba495e9STheodore Ts'o 		debugfs_debug = debugfs_create_u8("mballoc-debug",
26546ba495e9STheodore Ts'o 						  S_IRUGO | S_IWUSR,
26556ba495e9STheodore Ts'o 						  debugfs_dir,
26566ba495e9STheodore Ts'o 						  &mb_enable_debug);
26576ba495e9STheodore Ts'o }
26586ba495e9STheodore Ts'o 
26596ba495e9STheodore Ts'o static void ext4_remove_debugfs_entry(void)
26606ba495e9STheodore Ts'o {
26616ba495e9STheodore Ts'o 	debugfs_remove(debugfs_debug);
26626ba495e9STheodore Ts'o 	debugfs_remove(debugfs_dir);
26636ba495e9STheodore Ts'o }
26646ba495e9STheodore Ts'o 
26656ba495e9STheodore Ts'o #else
26666ba495e9STheodore Ts'o 
26676ba495e9STheodore Ts'o static void __init ext4_create_debugfs_entry(void)
26686ba495e9STheodore Ts'o {
26696ba495e9STheodore Ts'o }
26706ba495e9STheodore Ts'o 
26716ba495e9STheodore Ts'o static void ext4_remove_debugfs_entry(void)
26726ba495e9STheodore Ts'o {
26736ba495e9STheodore Ts'o }
26746ba495e9STheodore Ts'o 
26756ba495e9STheodore Ts'o #endif
26766ba495e9STheodore Ts'o 
26775dabfc78STheodore Ts'o int __init ext4_init_mballoc(void)
2678c9de560dSAlex Tomas {
267916828088STheodore Ts'o 	ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
268016828088STheodore Ts'o 					SLAB_RECLAIM_ACCOUNT);
2681c9de560dSAlex Tomas 	if (ext4_pspace_cachep == NULL)
2682c9de560dSAlex Tomas 		return -ENOMEM;
2683c9de560dSAlex Tomas 
268416828088STheodore Ts'o 	ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
268516828088STheodore Ts'o 				    SLAB_RECLAIM_ACCOUNT);
2686256bdb49SEric Sandeen 	if (ext4_ac_cachep == NULL) {
2687256bdb49SEric Sandeen 		kmem_cache_destroy(ext4_pspace_cachep);
2688256bdb49SEric Sandeen 		return -ENOMEM;
2689256bdb49SEric Sandeen 	}
2690c894058dSAneesh Kumar K.V 
269118aadd47SBobi Jam 	ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
269216828088STheodore Ts'o 					   SLAB_RECLAIM_ACCOUNT);
269318aadd47SBobi Jam 	if (ext4_free_data_cachep == NULL) {
2694c894058dSAneesh Kumar K.V 		kmem_cache_destroy(ext4_pspace_cachep);
2695c894058dSAneesh Kumar K.V 		kmem_cache_destroy(ext4_ac_cachep);
2696c894058dSAneesh Kumar K.V 		return -ENOMEM;
2697c894058dSAneesh Kumar K.V 	}
26986ba495e9STheodore Ts'o 	ext4_create_debugfs_entry();
2699c9de560dSAlex Tomas 	return 0;
2700c9de560dSAlex Tomas }
2701c9de560dSAlex Tomas 
27025dabfc78STheodore Ts'o void ext4_exit_mballoc(void)
2703c9de560dSAlex Tomas {
27043e03f9caSJesper Dangaard Brouer 	/*
27053e03f9caSJesper Dangaard Brouer 	 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
27063e03f9caSJesper Dangaard Brouer 	 * before destroying the slab cache.
27073e03f9caSJesper Dangaard Brouer 	 */
27083e03f9caSJesper Dangaard Brouer 	rcu_barrier();
2709c9de560dSAlex Tomas 	kmem_cache_destroy(ext4_pspace_cachep);
2710256bdb49SEric Sandeen 	kmem_cache_destroy(ext4_ac_cachep);
271118aadd47SBobi Jam 	kmem_cache_destroy(ext4_free_data_cachep);
27122892c15dSEric Sandeen 	ext4_groupinfo_destroy_slabs();
27136ba495e9STheodore Ts'o 	ext4_remove_debugfs_entry();
2714c9de560dSAlex Tomas }
2715c9de560dSAlex Tomas 
2716c9de560dSAlex Tomas 
2717c9de560dSAlex Tomas /*
271873b2c716SUwe Kleine-König  * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2719c9de560dSAlex Tomas  * Returns 0 if success or error code
2720c9de560dSAlex Tomas  */
27214ddfef7bSEric Sandeen static noinline_for_stack int
27224ddfef7bSEric Sandeen ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
272353accfa9STheodore Ts'o 				handle_t *handle, unsigned int reserv_clstrs)
2724c9de560dSAlex Tomas {
2725c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
2726c9de560dSAlex Tomas 	struct ext4_group_desc *gdp;
2727c9de560dSAlex Tomas 	struct buffer_head *gdp_bh;
2728c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
2729c9de560dSAlex Tomas 	struct super_block *sb;
2730c9de560dSAlex Tomas 	ext4_fsblk_t block;
2731519deca0SAneesh Kumar K.V 	int err, len;
2732c9de560dSAlex Tomas 
2733c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2734c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_len <= 0);
2735c9de560dSAlex Tomas 
2736c9de560dSAlex Tomas 	sb = ac->ac_sb;
2737c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
2738c9de560dSAlex Tomas 
2739c9de560dSAlex Tomas 	err = -EIO;
2740574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2741c9de560dSAlex Tomas 	if (!bitmap_bh)
2742c9de560dSAlex Tomas 		goto out_err;
2743c9de560dSAlex Tomas 
2744c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, bitmap_bh);
2745c9de560dSAlex Tomas 	if (err)
2746c9de560dSAlex Tomas 		goto out_err;
2747c9de560dSAlex Tomas 
2748c9de560dSAlex Tomas 	err = -EIO;
2749c9de560dSAlex Tomas 	gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2750c9de560dSAlex Tomas 	if (!gdp)
2751c9de560dSAlex Tomas 		goto out_err;
2752c9de560dSAlex Tomas 
2753a9df9a49STheodore Ts'o 	ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
2754021b65bbSTheodore Ts'o 			ext4_free_group_clusters(sb, gdp));
275503cddb80SAneesh Kumar K.V 
2756c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, gdp_bh);
2757c9de560dSAlex Tomas 	if (err)
2758c9de560dSAlex Tomas 		goto out_err;
2759c9de560dSAlex Tomas 
2760bda00de7SAkinobu Mita 	block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
2761c9de560dSAlex Tomas 
276253accfa9STheodore Ts'o 	len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
27636fd058f7STheodore Ts'o 	if (!ext4_data_block_valid(sbi, block, len)) {
276412062dddSEric Sandeen 		ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
27651084f252STheodore Ts'o 			   "fs metadata", block, block+len);
2766519deca0SAneesh Kumar K.V 		/* File system mounted not to panic on error
2767519deca0SAneesh Kumar K.V 		 * Fix the bitmap and repeat the block allocation
2768519deca0SAneesh Kumar K.V 		 * We leak some of the blocks here.
2769519deca0SAneesh Kumar K.V 		 */
2770955ce5f5SAneesh Kumar K.V 		ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2771c3e94d1dSYongqiang Yang 		ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2772519deca0SAneesh Kumar K.V 			      ac->ac_b_ex.fe_len);
2773955ce5f5SAneesh Kumar K.V 		ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
27740390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2775519deca0SAneesh Kumar K.V 		if (!err)
2776519deca0SAneesh Kumar K.V 			err = -EAGAIN;
2777519deca0SAneesh Kumar K.V 		goto out_err;
2778c9de560dSAlex Tomas 	}
2779955ce5f5SAneesh Kumar K.V 
2780955ce5f5SAneesh Kumar K.V 	ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2781c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
2782c9de560dSAlex Tomas 	{
2783c9de560dSAlex Tomas 		int i;
2784c9de560dSAlex Tomas 		for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
2785c9de560dSAlex Tomas 			BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
2786c9de560dSAlex Tomas 						bitmap_bh->b_data));
2787c9de560dSAlex Tomas 		}
2788c9de560dSAlex Tomas 	}
2789c9de560dSAlex Tomas #endif
2790c3e94d1dSYongqiang Yang 	ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2791c3e94d1dSYongqiang Yang 		      ac->ac_b_ex.fe_len);
2792c9de560dSAlex Tomas 	if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2793c9de560dSAlex Tomas 		gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
2794021b65bbSTheodore Ts'o 		ext4_free_group_clusters_set(sb, gdp,
2795cff1dfd7STheodore Ts'o 					     ext4_free_clusters_after_init(sb,
2796560671a0SAneesh Kumar K.V 						ac->ac_b_ex.fe_group, gdp));
2797c9de560dSAlex Tomas 	}
2798021b65bbSTheodore Ts'o 	len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
2799021b65bbSTheodore Ts'o 	ext4_free_group_clusters_set(sb, gdp, len);
2800c9de560dSAlex Tomas 	gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
2801955ce5f5SAneesh Kumar K.V 
2802955ce5f5SAneesh Kumar K.V 	ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
280357042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
2804d2a17637SMingming Cao 	/*
28056bc6e63fSAneesh Kumar K.V 	 * Now reduce the dirty block count also. Should not go negative
2806d2a17637SMingming Cao 	 */
28076bc6e63fSAneesh Kumar K.V 	if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
28086bc6e63fSAneesh Kumar K.V 		/* release all the reserved blocks if non delalloc */
280957042651STheodore Ts'o 		percpu_counter_sub(&sbi->s_dirtyclusters_counter,
281057042651STheodore Ts'o 				   reserv_clstrs);
2811c9de560dSAlex Tomas 
2812772cb7c8SJose R. Santos 	if (sbi->s_log_groups_per_flex) {
2813772cb7c8SJose R. Santos 		ext4_group_t flex_group = ext4_flex_group(sbi,
2814772cb7c8SJose R. Santos 							  ac->ac_b_ex.fe_group);
28159f24e420STheodore Ts'o 		atomic_sub(ac->ac_b_ex.fe_len,
281624aaa8efSTheodore Ts'o 			   &sbi->s_flex_groups[flex_group].free_clusters);
2817772cb7c8SJose R. Santos 	}
2818772cb7c8SJose R. Santos 
28190390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2820c9de560dSAlex Tomas 	if (err)
2821c9de560dSAlex Tomas 		goto out_err;
28220390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
2823c9de560dSAlex Tomas 
2824c9de560dSAlex Tomas out_err:
2825a0375156STheodore Ts'o 	ext4_mark_super_dirty(sb);
282642a10addSAneesh Kumar K.V 	brelse(bitmap_bh);
2827c9de560dSAlex Tomas 	return err;
2828c9de560dSAlex Tomas }
2829c9de560dSAlex Tomas 
2830c9de560dSAlex Tomas /*
2831c9de560dSAlex Tomas  * here we normalize request for locality group
2832d7a1fee1SDan Ehrenberg  * Group request are normalized to s_mb_group_prealloc, which goes to
2833d7a1fee1SDan Ehrenberg  * s_strip if we set the same via mount option.
2834d7a1fee1SDan Ehrenberg  * s_mb_group_prealloc can be configured via
2835b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_group_prealloc
2836c9de560dSAlex Tomas  *
2837c9de560dSAlex Tomas  * XXX: should we try to preallocate more than the group has now?
2838c9de560dSAlex Tomas  */
2839c9de560dSAlex Tomas static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
2840c9de560dSAlex Tomas {
2841c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
2842c9de560dSAlex Tomas 	struct ext4_locality_group *lg = ac->ac_lg;
2843c9de560dSAlex Tomas 
2844c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
2845c9de560dSAlex Tomas 	ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
28466ba495e9STheodore Ts'o 	mb_debug(1, "#%u: goal %u blocks for locality group\n",
2847c9de560dSAlex Tomas 		current->pid, ac->ac_g_ex.fe_len);
2848c9de560dSAlex Tomas }
2849c9de560dSAlex Tomas 
2850c9de560dSAlex Tomas /*
2851c9de560dSAlex Tomas  * Normalization means making request better in terms of
2852c9de560dSAlex Tomas  * size and alignment
2853c9de560dSAlex Tomas  */
28544ddfef7bSEric Sandeen static noinline_for_stack void
28554ddfef7bSEric Sandeen ext4_mb_normalize_request(struct ext4_allocation_context *ac,
2856c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
2857c9de560dSAlex Tomas {
285853accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2859c9de560dSAlex Tomas 	int bsbits, max;
2860c9de560dSAlex Tomas 	ext4_lblk_t end;
28611592d2c5SCurt Wohlgemuth 	loff_t size, start_off;
28621592d2c5SCurt Wohlgemuth 	loff_t orig_size __maybe_unused;
28635a0790c2SAndi Kleen 	ext4_lblk_t start;
2864c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
28659a0762c5SAneesh Kumar K.V 	struct ext4_prealloc_space *pa;
2866c9de560dSAlex Tomas 
2867c9de560dSAlex Tomas 	/* do normalize only data requests, metadata requests
2868c9de560dSAlex Tomas 	   do not need preallocation */
2869c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
2870c9de560dSAlex Tomas 		return;
2871c9de560dSAlex Tomas 
2872c9de560dSAlex Tomas 	/* sometime caller may want exact blocks */
2873c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2874c9de560dSAlex Tomas 		return;
2875c9de560dSAlex Tomas 
2876c9de560dSAlex Tomas 	/* caller may indicate that preallocation isn't
2877c9de560dSAlex Tomas 	 * required (it's a tail, for example) */
2878c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
2879c9de560dSAlex Tomas 		return;
2880c9de560dSAlex Tomas 
2881c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
2882c9de560dSAlex Tomas 		ext4_mb_normalize_group_request(ac);
2883c9de560dSAlex Tomas 		return ;
2884c9de560dSAlex Tomas 	}
2885c9de560dSAlex Tomas 
2886c9de560dSAlex Tomas 	bsbits = ac->ac_sb->s_blocksize_bits;
2887c9de560dSAlex Tomas 
2888c9de560dSAlex Tomas 	/* first, let's learn actual file size
2889c9de560dSAlex Tomas 	 * given current request is allocated */
289053accfa9STheodore Ts'o 	size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
2891c9de560dSAlex Tomas 	size = size << bsbits;
2892c9de560dSAlex Tomas 	if (size < i_size_read(ac->ac_inode))
2893c9de560dSAlex Tomas 		size = i_size_read(ac->ac_inode);
28945a0790c2SAndi Kleen 	orig_size = size;
2895c9de560dSAlex Tomas 
28961930479cSValerie Clement 	/* max size of free chunks */
28971930479cSValerie Clement 	max = 2 << bsbits;
2898c9de560dSAlex Tomas 
28991930479cSValerie Clement #define NRL_CHECK_SIZE(req, size, max, chunk_size)	\
29001930479cSValerie Clement 		(req <= (size) || max <= (chunk_size))
2901c9de560dSAlex Tomas 
2902c9de560dSAlex Tomas 	/* first, try to predict filesize */
2903c9de560dSAlex Tomas 	/* XXX: should this table be tunable? */
2904c9de560dSAlex Tomas 	start_off = 0;
2905c9de560dSAlex Tomas 	if (size <= 16 * 1024) {
2906c9de560dSAlex Tomas 		size = 16 * 1024;
2907c9de560dSAlex Tomas 	} else if (size <= 32 * 1024) {
2908c9de560dSAlex Tomas 		size = 32 * 1024;
2909c9de560dSAlex Tomas 	} else if (size <= 64 * 1024) {
2910c9de560dSAlex Tomas 		size = 64 * 1024;
2911c9de560dSAlex Tomas 	} else if (size <= 128 * 1024) {
2912c9de560dSAlex Tomas 		size = 128 * 1024;
2913c9de560dSAlex Tomas 	} else if (size <= 256 * 1024) {
2914c9de560dSAlex Tomas 		size = 256 * 1024;
2915c9de560dSAlex Tomas 	} else if (size <= 512 * 1024) {
2916c9de560dSAlex Tomas 		size = 512 * 1024;
2917c9de560dSAlex Tomas 	} else if (size <= 1024 * 1024) {
2918c9de560dSAlex Tomas 		size = 1024 * 1024;
29191930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
2920c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
29211930479cSValerie Clement 						(21 - bsbits)) << 21;
29221930479cSValerie Clement 		size = 2 * 1024 * 1024;
29231930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
2924c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2925c9de560dSAlex Tomas 							(22 - bsbits)) << 22;
2926c9de560dSAlex Tomas 		size = 4 * 1024 * 1024;
2927c9de560dSAlex Tomas 	} else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
29281930479cSValerie Clement 					(8<<20)>>bsbits, max, 8 * 1024)) {
2929c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2930c9de560dSAlex Tomas 							(23 - bsbits)) << 23;
2931c9de560dSAlex Tomas 		size = 8 * 1024 * 1024;
2932c9de560dSAlex Tomas 	} else {
2933c9de560dSAlex Tomas 		start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
2934c9de560dSAlex Tomas 		size	  = ac->ac_o_ex.fe_len << bsbits;
2935c9de560dSAlex Tomas 	}
29365a0790c2SAndi Kleen 	size = size >> bsbits;
29375a0790c2SAndi Kleen 	start = start_off >> bsbits;
2938c9de560dSAlex Tomas 
2939c9de560dSAlex Tomas 	/* don't cover already allocated blocks in selected range */
2940c9de560dSAlex Tomas 	if (ar->pleft && start <= ar->lleft) {
2941c9de560dSAlex Tomas 		size -= ar->lleft + 1 - start;
2942c9de560dSAlex Tomas 		start = ar->lleft + 1;
2943c9de560dSAlex Tomas 	}
2944c9de560dSAlex Tomas 	if (ar->pright && start + size - 1 >= ar->lright)
2945c9de560dSAlex Tomas 		size -= start + size - ar->lright;
2946c9de560dSAlex Tomas 
2947c9de560dSAlex Tomas 	end = start + size;
2948c9de560dSAlex Tomas 
2949c9de560dSAlex Tomas 	/* check we don't cross already preallocated blocks */
2950c9de560dSAlex Tomas 	rcu_read_lock();
29519a0762c5SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
2952498e5f24STheodore Ts'o 		ext4_lblk_t pa_end;
2953c9de560dSAlex Tomas 
2954c9de560dSAlex Tomas 		if (pa->pa_deleted)
2955c9de560dSAlex Tomas 			continue;
2956c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
2957c9de560dSAlex Tomas 		if (pa->pa_deleted) {
2958c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
2959c9de560dSAlex Tomas 			continue;
2960c9de560dSAlex Tomas 		}
2961c9de560dSAlex Tomas 
296253accfa9STheodore Ts'o 		pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
296353accfa9STheodore Ts'o 						  pa->pa_len);
2964c9de560dSAlex Tomas 
2965c9de560dSAlex Tomas 		/* PA must not overlap original request */
2966c9de560dSAlex Tomas 		BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
2967c9de560dSAlex Tomas 			ac->ac_o_ex.fe_logical < pa->pa_lstart));
2968c9de560dSAlex Tomas 
296938877f4eSEric Sandeen 		/* skip PAs this normalized request doesn't overlap with */
297038877f4eSEric Sandeen 		if (pa->pa_lstart >= end || pa_end <= start) {
2971c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
2972c9de560dSAlex Tomas 			continue;
2973c9de560dSAlex Tomas 		}
2974c9de560dSAlex Tomas 		BUG_ON(pa->pa_lstart <= start && pa_end >= end);
2975c9de560dSAlex Tomas 
297638877f4eSEric Sandeen 		/* adjust start or end to be adjacent to this pa */
2977c9de560dSAlex Tomas 		if (pa_end <= ac->ac_o_ex.fe_logical) {
2978c9de560dSAlex Tomas 			BUG_ON(pa_end < start);
2979c9de560dSAlex Tomas 			start = pa_end;
298038877f4eSEric Sandeen 		} else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
2981c9de560dSAlex Tomas 			BUG_ON(pa->pa_lstart > end);
2982c9de560dSAlex Tomas 			end = pa->pa_lstart;
2983c9de560dSAlex Tomas 		}
2984c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
2985c9de560dSAlex Tomas 	}
2986c9de560dSAlex Tomas 	rcu_read_unlock();
2987c9de560dSAlex Tomas 	size = end - start;
2988c9de560dSAlex Tomas 
2989c9de560dSAlex Tomas 	/* XXX: extra loop to check we really don't overlap preallocations */
2990c9de560dSAlex Tomas 	rcu_read_lock();
29919a0762c5SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
2992498e5f24STheodore Ts'o 		ext4_lblk_t pa_end;
299353accfa9STheodore Ts'o 
2994c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
2995c9de560dSAlex Tomas 		if (pa->pa_deleted == 0) {
299653accfa9STheodore Ts'o 			pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
299753accfa9STheodore Ts'o 							  pa->pa_len);
2998c9de560dSAlex Tomas 			BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
2999c9de560dSAlex Tomas 		}
3000c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3001c9de560dSAlex Tomas 	}
3002c9de560dSAlex Tomas 	rcu_read_unlock();
3003c9de560dSAlex Tomas 
3004c9de560dSAlex Tomas 	if (start + size <= ac->ac_o_ex.fe_logical &&
3005c9de560dSAlex Tomas 			start > ac->ac_o_ex.fe_logical) {
30069d8b9ec4STheodore Ts'o 		ext4_msg(ac->ac_sb, KERN_ERR,
30079d8b9ec4STheodore Ts'o 			 "start %lu, size %lu, fe_logical %lu",
3008c9de560dSAlex Tomas 			 (unsigned long) start, (unsigned long) size,
3009c9de560dSAlex Tomas 			 (unsigned long) ac->ac_o_ex.fe_logical);
3010c9de560dSAlex Tomas 	}
3011c9de560dSAlex Tomas 	BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3012c9de560dSAlex Tomas 			start > ac->ac_o_ex.fe_logical);
30137137d7a4STheodore Ts'o 	BUG_ON(size <= 0 || size > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
3014c9de560dSAlex Tomas 
3015c9de560dSAlex Tomas 	/* now prepare goal request */
3016c9de560dSAlex Tomas 
3017c9de560dSAlex Tomas 	/* XXX: is it better to align blocks WRT to logical
3018c9de560dSAlex Tomas 	 * placement or satisfy big request as is */
3019c9de560dSAlex Tomas 	ac->ac_g_ex.fe_logical = start;
302053accfa9STheodore Ts'o 	ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3021c9de560dSAlex Tomas 
3022c9de560dSAlex Tomas 	/* define goal start in order to merge */
3023c9de560dSAlex Tomas 	if (ar->pright && (ar->lright == (start + size))) {
3024c9de560dSAlex Tomas 		/* merge to the right */
3025c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3026c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_group,
3027c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_start);
3028c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3029c9de560dSAlex Tomas 	}
3030c9de560dSAlex Tomas 	if (ar->pleft && (ar->lleft + 1 == start)) {
3031c9de560dSAlex Tomas 		/* merge to the left */
3032c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3033c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_group,
3034c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_start);
3035c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3036c9de560dSAlex Tomas 	}
3037c9de560dSAlex Tomas 
30386ba495e9STheodore Ts'o 	mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3039c9de560dSAlex Tomas 		(unsigned) orig_size, (unsigned) start);
3040c9de560dSAlex Tomas }
3041c9de560dSAlex Tomas 
3042c9de560dSAlex Tomas static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3043c9de560dSAlex Tomas {
3044c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3045c9de560dSAlex Tomas 
3046c9de560dSAlex Tomas 	if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3047c9de560dSAlex Tomas 		atomic_inc(&sbi->s_bal_reqs);
3048c9de560dSAlex Tomas 		atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3049291dae47SCurt Wohlgemuth 		if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3050c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_success);
3051c9de560dSAlex Tomas 		atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3052c9de560dSAlex Tomas 		if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3053c9de560dSAlex Tomas 				ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3054c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_goals);
3055c9de560dSAlex Tomas 		if (ac->ac_found > sbi->s_mb_max_to_scan)
3056c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_breaks);
3057c9de560dSAlex Tomas 	}
3058c9de560dSAlex Tomas 
3059296c355cSTheodore Ts'o 	if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3060296c355cSTheodore Ts'o 		trace_ext4_mballoc_alloc(ac);
3061296c355cSTheodore Ts'o 	else
3062296c355cSTheodore Ts'o 		trace_ext4_mballoc_prealloc(ac);
3063c9de560dSAlex Tomas }
3064c9de560dSAlex Tomas 
3065c9de560dSAlex Tomas /*
3066b844167eSCurt Wohlgemuth  * Called on failure; free up any blocks from the inode PA for this
3067b844167eSCurt Wohlgemuth  * context.  We don't need this for MB_GROUP_PA because we only change
3068b844167eSCurt Wohlgemuth  * pa_free in ext4_mb_release_context(), but on failure, we've already
3069b844167eSCurt Wohlgemuth  * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3070b844167eSCurt Wohlgemuth  */
3071b844167eSCurt Wohlgemuth static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3072b844167eSCurt Wohlgemuth {
3073b844167eSCurt Wohlgemuth 	struct ext4_prealloc_space *pa = ac->ac_pa;
3074b844167eSCurt Wohlgemuth 	int len;
3075b844167eSCurt Wohlgemuth 
3076b844167eSCurt Wohlgemuth 	if (pa && pa->pa_type == MB_INODE_PA) {
3077b844167eSCurt Wohlgemuth 		len = ac->ac_b_ex.fe_len;
3078b844167eSCurt Wohlgemuth 		pa->pa_free += len;
3079b844167eSCurt Wohlgemuth 	}
3080b844167eSCurt Wohlgemuth 
3081b844167eSCurt Wohlgemuth }
3082b844167eSCurt Wohlgemuth 
3083b844167eSCurt Wohlgemuth /*
3084c9de560dSAlex Tomas  * use blocks preallocated to inode
3085c9de560dSAlex Tomas  */
3086c9de560dSAlex Tomas static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3087c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
3088c9de560dSAlex Tomas {
308953accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3090c9de560dSAlex Tomas 	ext4_fsblk_t start;
3091c9de560dSAlex Tomas 	ext4_fsblk_t end;
3092c9de560dSAlex Tomas 	int len;
3093c9de560dSAlex Tomas 
3094c9de560dSAlex Tomas 	/* found preallocated blocks, use them */
3095c9de560dSAlex Tomas 	start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
309653accfa9STheodore Ts'o 	end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
309753accfa9STheodore Ts'o 		  start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
309853accfa9STheodore Ts'o 	len = EXT4_NUM_B2C(sbi, end - start);
3099c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3100c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
3101c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
3102c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
3103c9de560dSAlex Tomas 	ac->ac_pa = pa;
3104c9de560dSAlex Tomas 
3105c9de560dSAlex Tomas 	BUG_ON(start < pa->pa_pstart);
310653accfa9STheodore Ts'o 	BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3107c9de560dSAlex Tomas 	BUG_ON(pa->pa_free < len);
3108c9de560dSAlex Tomas 	pa->pa_free -= len;
3109c9de560dSAlex Tomas 
31106ba495e9STheodore Ts'o 	mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3111c9de560dSAlex Tomas }
3112c9de560dSAlex Tomas 
3113c9de560dSAlex Tomas /*
3114c9de560dSAlex Tomas  * use blocks preallocated to locality group
3115c9de560dSAlex Tomas  */
3116c9de560dSAlex Tomas static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3117c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
3118c9de560dSAlex Tomas {
311903cddb80SAneesh Kumar K.V 	unsigned int len = ac->ac_o_ex.fe_len;
31206be2ded1SAneesh Kumar K.V 
3121c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3122c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_group,
3123c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
3124c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
3125c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
3126c9de560dSAlex Tomas 	ac->ac_pa = pa;
3127c9de560dSAlex Tomas 
3128c9de560dSAlex Tomas 	/* we don't correct pa_pstart or pa_plen here to avoid
312926346ff6SAneesh Kumar K.V 	 * possible race when the group is being loaded concurrently
3130c9de560dSAlex Tomas 	 * instead we correct pa later, after blocks are marked
313126346ff6SAneesh Kumar K.V 	 * in on-disk bitmap -- see ext4_mb_release_context()
313226346ff6SAneesh Kumar K.V 	 * Other CPUs are prevented from allocating from this pa by lg_mutex
3133c9de560dSAlex Tomas 	 */
31346ba495e9STheodore Ts'o 	mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3135c9de560dSAlex Tomas }
3136c9de560dSAlex Tomas 
3137c9de560dSAlex Tomas /*
31385e745b04SAneesh Kumar K.V  * Return the prealloc space that have minimal distance
31395e745b04SAneesh Kumar K.V  * from the goal block. @cpa is the prealloc
31405e745b04SAneesh Kumar K.V  * space that is having currently known minimal distance
31415e745b04SAneesh Kumar K.V  * from the goal block.
31425e745b04SAneesh Kumar K.V  */
31435e745b04SAneesh Kumar K.V static struct ext4_prealloc_space *
31445e745b04SAneesh Kumar K.V ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
31455e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *pa,
31465e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *cpa)
31475e745b04SAneesh Kumar K.V {
31485e745b04SAneesh Kumar K.V 	ext4_fsblk_t cur_distance, new_distance;
31495e745b04SAneesh Kumar K.V 
31505e745b04SAneesh Kumar K.V 	if (cpa == NULL) {
31515e745b04SAneesh Kumar K.V 		atomic_inc(&pa->pa_count);
31525e745b04SAneesh Kumar K.V 		return pa;
31535e745b04SAneesh Kumar K.V 	}
31545e745b04SAneesh Kumar K.V 	cur_distance = abs(goal_block - cpa->pa_pstart);
31555e745b04SAneesh Kumar K.V 	new_distance = abs(goal_block - pa->pa_pstart);
31565e745b04SAneesh Kumar K.V 
31575a54b2f1SColy Li 	if (cur_distance <= new_distance)
31585e745b04SAneesh Kumar K.V 		return cpa;
31595e745b04SAneesh Kumar K.V 
31605e745b04SAneesh Kumar K.V 	/* drop the previous reference */
31615e745b04SAneesh Kumar K.V 	atomic_dec(&cpa->pa_count);
31625e745b04SAneesh Kumar K.V 	atomic_inc(&pa->pa_count);
31635e745b04SAneesh Kumar K.V 	return pa;
31645e745b04SAneesh Kumar K.V }
31655e745b04SAneesh Kumar K.V 
31665e745b04SAneesh Kumar K.V /*
3167c9de560dSAlex Tomas  * search goal blocks in preallocated space
3168c9de560dSAlex Tomas  */
31694ddfef7bSEric Sandeen static noinline_for_stack int
31704ddfef7bSEric Sandeen ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3171c9de560dSAlex Tomas {
317253accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
31736be2ded1SAneesh Kumar K.V 	int order, i;
3174c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3175c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
31765e745b04SAneesh Kumar K.V 	struct ext4_prealloc_space *pa, *cpa = NULL;
31775e745b04SAneesh Kumar K.V 	ext4_fsblk_t goal_block;
3178c9de560dSAlex Tomas 
3179c9de560dSAlex Tomas 	/* only data can be preallocated */
3180c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3181c9de560dSAlex Tomas 		return 0;
3182c9de560dSAlex Tomas 
3183c9de560dSAlex Tomas 	/* first, try per-file preallocation */
3184c9de560dSAlex Tomas 	rcu_read_lock();
31859a0762c5SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3186c9de560dSAlex Tomas 
3187c9de560dSAlex Tomas 		/* all fields in this condition don't change,
3188c9de560dSAlex Tomas 		 * so we can skip locking for them */
3189c9de560dSAlex Tomas 		if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
319053accfa9STheodore Ts'o 		    ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
319153accfa9STheodore Ts'o 					       EXT4_C2B(sbi, pa->pa_len)))
3192c9de560dSAlex Tomas 			continue;
3193c9de560dSAlex Tomas 
3194fb0a387dSEric Sandeen 		/* non-extent files can't have physical blocks past 2^32 */
319512e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
319653accfa9STheodore Ts'o 		    (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
319753accfa9STheodore Ts'o 		     EXT4_MAX_BLOCK_FILE_PHYS))
3198fb0a387dSEric Sandeen 			continue;
3199fb0a387dSEric Sandeen 
3200c9de560dSAlex Tomas 		/* found preallocated blocks, use them */
3201c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3202c9de560dSAlex Tomas 		if (pa->pa_deleted == 0 && pa->pa_free) {
3203c9de560dSAlex Tomas 			atomic_inc(&pa->pa_count);
3204c9de560dSAlex Tomas 			ext4_mb_use_inode_pa(ac, pa);
3205c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3206c9de560dSAlex Tomas 			ac->ac_criteria = 10;
3207c9de560dSAlex Tomas 			rcu_read_unlock();
3208c9de560dSAlex Tomas 			return 1;
3209c9de560dSAlex Tomas 		}
3210c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3211c9de560dSAlex Tomas 	}
3212c9de560dSAlex Tomas 	rcu_read_unlock();
3213c9de560dSAlex Tomas 
3214c9de560dSAlex Tomas 	/* can we use group allocation? */
3215c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3216c9de560dSAlex Tomas 		return 0;
3217c9de560dSAlex Tomas 
3218c9de560dSAlex Tomas 	/* inode may have no locality group for some reason */
3219c9de560dSAlex Tomas 	lg = ac->ac_lg;
3220c9de560dSAlex Tomas 	if (lg == NULL)
3221c9de560dSAlex Tomas 		return 0;
32226be2ded1SAneesh Kumar K.V 	order  = fls(ac->ac_o_ex.fe_len) - 1;
32236be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
32246be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
32256be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
3226c9de560dSAlex Tomas 
3227bda00de7SAkinobu Mita 	goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
32285e745b04SAneesh Kumar K.V 	/*
32295e745b04SAneesh Kumar K.V 	 * search for the prealloc space that is having
32305e745b04SAneesh Kumar K.V 	 * minimal distance from the goal block.
32315e745b04SAneesh Kumar K.V 	 */
32326be2ded1SAneesh Kumar K.V 	for (i = order; i < PREALLOC_TB_SIZE; i++) {
3233c9de560dSAlex Tomas 		rcu_read_lock();
32346be2ded1SAneesh Kumar K.V 		list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
32356be2ded1SAneesh Kumar K.V 					pa_inode_list) {
3236c9de560dSAlex Tomas 			spin_lock(&pa->pa_lock);
32376be2ded1SAneesh Kumar K.V 			if (pa->pa_deleted == 0 &&
32386be2ded1SAneesh Kumar K.V 					pa->pa_free >= ac->ac_o_ex.fe_len) {
32395e745b04SAneesh Kumar K.V 
32405e745b04SAneesh Kumar K.V 				cpa = ext4_mb_check_group_pa(goal_block,
32415e745b04SAneesh Kumar K.V 								pa, cpa);
32425e745b04SAneesh Kumar K.V 			}
3243c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
32445e745b04SAneesh Kumar K.V 		}
32455e745b04SAneesh Kumar K.V 		rcu_read_unlock();
32465e745b04SAneesh Kumar K.V 	}
32475e745b04SAneesh Kumar K.V 	if (cpa) {
32485e745b04SAneesh Kumar K.V 		ext4_mb_use_group_pa(ac, cpa);
3249c9de560dSAlex Tomas 		ac->ac_criteria = 20;
3250c9de560dSAlex Tomas 		return 1;
3251c9de560dSAlex Tomas 	}
3252c9de560dSAlex Tomas 	return 0;
3253c9de560dSAlex Tomas }
3254c9de560dSAlex Tomas 
3255c9de560dSAlex Tomas /*
32567a2fcbf7SAneesh Kumar K.V  * the function goes through all block freed in the group
32577a2fcbf7SAneesh Kumar K.V  * but not yet committed and marks them used in in-core bitmap.
32587a2fcbf7SAneesh Kumar K.V  * buddy must be generated from this bitmap
3259955ce5f5SAneesh Kumar K.V  * Need to be called with the ext4 group lock held
32607a2fcbf7SAneesh Kumar K.V  */
32617a2fcbf7SAneesh Kumar K.V static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
32627a2fcbf7SAneesh Kumar K.V 						ext4_group_t group)
32637a2fcbf7SAneesh Kumar K.V {
32647a2fcbf7SAneesh Kumar K.V 	struct rb_node *n;
32657a2fcbf7SAneesh Kumar K.V 	struct ext4_group_info *grp;
32667a2fcbf7SAneesh Kumar K.V 	struct ext4_free_data *entry;
32677a2fcbf7SAneesh Kumar K.V 
32687a2fcbf7SAneesh Kumar K.V 	grp = ext4_get_group_info(sb, group);
32697a2fcbf7SAneesh Kumar K.V 	n = rb_first(&(grp->bb_free_root));
32707a2fcbf7SAneesh Kumar K.V 
32717a2fcbf7SAneesh Kumar K.V 	while (n) {
327218aadd47SBobi Jam 		entry = rb_entry(n, struct ext4_free_data, efd_node);
327318aadd47SBobi Jam 		ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
32747a2fcbf7SAneesh Kumar K.V 		n = rb_next(n);
32757a2fcbf7SAneesh Kumar K.V 	}
32767a2fcbf7SAneesh Kumar K.V 	return;
32777a2fcbf7SAneesh Kumar K.V }
32787a2fcbf7SAneesh Kumar K.V 
32797a2fcbf7SAneesh Kumar K.V /*
3280c9de560dSAlex Tomas  * the function goes through all preallocation in this group and marks them
3281c9de560dSAlex Tomas  * used in in-core bitmap. buddy must be generated from this bitmap
3282955ce5f5SAneesh Kumar K.V  * Need to be called with ext4 group lock held
3283c9de560dSAlex Tomas  */
3284089ceeccSEric Sandeen static noinline_for_stack
3285089ceeccSEric Sandeen void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3286c9de560dSAlex Tomas 					ext4_group_t group)
3287c9de560dSAlex Tomas {
3288c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3289c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3290c9de560dSAlex Tomas 	struct list_head *cur;
3291c9de560dSAlex Tomas 	ext4_group_t groupnr;
3292c9de560dSAlex Tomas 	ext4_grpblk_t start;
3293c9de560dSAlex Tomas 	int preallocated = 0;
3294c9de560dSAlex Tomas 	int len;
3295c9de560dSAlex Tomas 
3296c9de560dSAlex Tomas 	/* all form of preallocation discards first load group,
3297c9de560dSAlex Tomas 	 * so the only competing code is preallocation use.
3298c9de560dSAlex Tomas 	 * we don't need any locking here
3299c9de560dSAlex Tomas 	 * notice we do NOT ignore preallocations with pa_deleted
3300c9de560dSAlex Tomas 	 * otherwise we could leave used blocks available for
3301c9de560dSAlex Tomas 	 * allocation in buddy when concurrent ext4_mb_put_pa()
3302c9de560dSAlex Tomas 	 * is dropping preallocation
3303c9de560dSAlex Tomas 	 */
3304c9de560dSAlex Tomas 	list_for_each(cur, &grp->bb_prealloc_list) {
3305c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3306c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3307c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3308c9de560dSAlex Tomas 					     &groupnr, &start);
3309c9de560dSAlex Tomas 		len = pa->pa_len;
3310c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3311c9de560dSAlex Tomas 		if (unlikely(len == 0))
3312c9de560dSAlex Tomas 			continue;
3313c9de560dSAlex Tomas 		BUG_ON(groupnr != group);
3314c3e94d1dSYongqiang Yang 		ext4_set_bits(bitmap, start, len);
3315c9de560dSAlex Tomas 		preallocated += len;
3316c9de560dSAlex Tomas 	}
33176ba495e9STheodore Ts'o 	mb_debug(1, "prellocated %u for group %u\n", preallocated, group);
3318c9de560dSAlex Tomas }
3319c9de560dSAlex Tomas 
3320c9de560dSAlex Tomas static void ext4_mb_pa_callback(struct rcu_head *head)
3321c9de560dSAlex Tomas {
3322c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3323c9de560dSAlex Tomas 	pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3324c9de560dSAlex Tomas 	kmem_cache_free(ext4_pspace_cachep, pa);
3325c9de560dSAlex Tomas }
3326c9de560dSAlex Tomas 
3327c9de560dSAlex Tomas /*
3328c9de560dSAlex Tomas  * drops a reference to preallocated space descriptor
3329c9de560dSAlex Tomas  * if this was the last reference and the space is consumed
3330c9de560dSAlex Tomas  */
3331c9de560dSAlex Tomas static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3332c9de560dSAlex Tomas 			struct super_block *sb, struct ext4_prealloc_space *pa)
3333c9de560dSAlex Tomas {
3334a9df9a49STheodore Ts'o 	ext4_group_t grp;
3335d33a1976SEric Sandeen 	ext4_fsblk_t grp_blk;
3336c9de560dSAlex Tomas 
3337c9de560dSAlex Tomas 	if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3338c9de560dSAlex Tomas 		return;
3339c9de560dSAlex Tomas 
3340c9de560dSAlex Tomas 	/* in this short window concurrent discard can set pa_deleted */
3341c9de560dSAlex Tomas 	spin_lock(&pa->pa_lock);
3342c9de560dSAlex Tomas 	if (pa->pa_deleted == 1) {
3343c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3344c9de560dSAlex Tomas 		return;
3345c9de560dSAlex Tomas 	}
3346c9de560dSAlex Tomas 
3347c9de560dSAlex Tomas 	pa->pa_deleted = 1;
3348c9de560dSAlex Tomas 	spin_unlock(&pa->pa_lock);
3349c9de560dSAlex Tomas 
3350d33a1976SEric Sandeen 	grp_blk = pa->pa_pstart;
3351cc0fb9adSAneesh Kumar K.V 	/*
3352cc0fb9adSAneesh Kumar K.V 	 * If doing group-based preallocation, pa_pstart may be in the
3353cc0fb9adSAneesh Kumar K.V 	 * next group when pa is used up
3354cc0fb9adSAneesh Kumar K.V 	 */
3355cc0fb9adSAneesh Kumar K.V 	if (pa->pa_type == MB_GROUP_PA)
3356d33a1976SEric Sandeen 		grp_blk--;
3357d33a1976SEric Sandeen 
3358d33a1976SEric Sandeen 	ext4_get_group_no_and_offset(sb, grp_blk, &grp, NULL);
3359c9de560dSAlex Tomas 
3360c9de560dSAlex Tomas 	/*
3361c9de560dSAlex Tomas 	 * possible race:
3362c9de560dSAlex Tomas 	 *
3363c9de560dSAlex Tomas 	 *  P1 (buddy init)			P2 (regular allocation)
3364c9de560dSAlex Tomas 	 *					find block B in PA
3365c9de560dSAlex Tomas 	 *  copy on-disk bitmap to buddy
3366c9de560dSAlex Tomas 	 *  					mark B in on-disk bitmap
3367c9de560dSAlex Tomas 	 *					drop PA from group
3368c9de560dSAlex Tomas 	 *  mark all PAs in buddy
3369c9de560dSAlex Tomas 	 *
3370c9de560dSAlex Tomas 	 * thus, P1 initializes buddy with B available. to prevent this
3371c9de560dSAlex Tomas 	 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3372c9de560dSAlex Tomas 	 * against that pair
3373c9de560dSAlex Tomas 	 */
3374c9de560dSAlex Tomas 	ext4_lock_group(sb, grp);
3375c9de560dSAlex Tomas 	list_del(&pa->pa_group_list);
3376c9de560dSAlex Tomas 	ext4_unlock_group(sb, grp);
3377c9de560dSAlex Tomas 
3378c9de560dSAlex Tomas 	spin_lock(pa->pa_obj_lock);
3379c9de560dSAlex Tomas 	list_del_rcu(&pa->pa_inode_list);
3380c9de560dSAlex Tomas 	spin_unlock(pa->pa_obj_lock);
3381c9de560dSAlex Tomas 
3382c9de560dSAlex Tomas 	call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3383c9de560dSAlex Tomas }
3384c9de560dSAlex Tomas 
3385c9de560dSAlex Tomas /*
3386c9de560dSAlex Tomas  * creates new preallocated space for given inode
3387c9de560dSAlex Tomas  */
33884ddfef7bSEric Sandeen static noinline_for_stack int
33894ddfef7bSEric Sandeen ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3390c9de560dSAlex Tomas {
3391c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
339253accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3393c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3394c9de560dSAlex Tomas 	struct ext4_group_info *grp;
3395c9de560dSAlex Tomas 	struct ext4_inode_info *ei;
3396c9de560dSAlex Tomas 
3397c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
3398c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3399c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3400c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3401c9de560dSAlex Tomas 
3402c9de560dSAlex Tomas 	pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3403c9de560dSAlex Tomas 	if (pa == NULL)
3404c9de560dSAlex Tomas 		return -ENOMEM;
3405c9de560dSAlex Tomas 
3406c9de560dSAlex Tomas 	if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3407c9de560dSAlex Tomas 		int winl;
3408c9de560dSAlex Tomas 		int wins;
3409c9de560dSAlex Tomas 		int win;
3410c9de560dSAlex Tomas 		int offs;
3411c9de560dSAlex Tomas 
3412c9de560dSAlex Tomas 		/* we can't allocate as much as normalizer wants.
3413c9de560dSAlex Tomas 		 * so, found space must get proper lstart
3414c9de560dSAlex Tomas 		 * to cover original request */
3415c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3416c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3417c9de560dSAlex Tomas 
3418c9de560dSAlex Tomas 		/* we're limited by original request in that
3419c9de560dSAlex Tomas 		 * logical block must be covered any way
3420c9de560dSAlex Tomas 		 * winl is window we can move our chunk within */
3421c9de560dSAlex Tomas 		winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3422c9de560dSAlex Tomas 
3423c9de560dSAlex Tomas 		/* also, we should cover whole original request */
342453accfa9STheodore Ts'o 		wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
3425c9de560dSAlex Tomas 
3426c9de560dSAlex Tomas 		/* the smallest one defines real window */
3427c9de560dSAlex Tomas 		win = min(winl, wins);
3428c9de560dSAlex Tomas 
342953accfa9STheodore Ts'o 		offs = ac->ac_o_ex.fe_logical %
343053accfa9STheodore Ts'o 			EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3431c9de560dSAlex Tomas 		if (offs && offs < win)
3432c9de560dSAlex Tomas 			win = offs;
3433c9de560dSAlex Tomas 
343453accfa9STheodore Ts'o 		ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
343553accfa9STheodore Ts'o 			EXT4_B2C(sbi, win);
3436c9de560dSAlex Tomas 		BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3437c9de560dSAlex Tomas 		BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3438c9de560dSAlex Tomas 	}
3439c9de560dSAlex Tomas 
3440c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
3441c9de560dSAlex Tomas 	 * allocated blocks for history */
3442c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
3443c9de560dSAlex Tomas 
3444c9de560dSAlex Tomas 	pa->pa_lstart = ac->ac_b_ex.fe_logical;
3445c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3446c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
3447c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
3448c9de560dSAlex Tomas 	atomic_set(&pa->pa_count, 1);
3449c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
3450d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_inode_list);
3451d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
3452c9de560dSAlex Tomas 	pa->pa_deleted = 0;
3453cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_INODE_PA;
3454c9de560dSAlex Tomas 
34556ba495e9STheodore Ts'o 	mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3456c9de560dSAlex Tomas 			pa->pa_pstart, pa->pa_len, pa->pa_lstart);
34579bffad1eSTheodore Ts'o 	trace_ext4_mb_new_inode_pa(ac, pa);
3458c9de560dSAlex Tomas 
3459c9de560dSAlex Tomas 	ext4_mb_use_inode_pa(ac, pa);
346053accfa9STheodore Ts'o 	atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
3461c9de560dSAlex Tomas 
3462c9de560dSAlex Tomas 	ei = EXT4_I(ac->ac_inode);
3463c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3464c9de560dSAlex Tomas 
3465c9de560dSAlex Tomas 	pa->pa_obj_lock = &ei->i_prealloc_lock;
3466c9de560dSAlex Tomas 	pa->pa_inode = ac->ac_inode;
3467c9de560dSAlex Tomas 
3468c9de560dSAlex Tomas 	ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3469c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3470c9de560dSAlex Tomas 	ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3471c9de560dSAlex Tomas 
3472c9de560dSAlex Tomas 	spin_lock(pa->pa_obj_lock);
3473c9de560dSAlex Tomas 	list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3474c9de560dSAlex Tomas 	spin_unlock(pa->pa_obj_lock);
3475c9de560dSAlex Tomas 
3476c9de560dSAlex Tomas 	return 0;
3477c9de560dSAlex Tomas }
3478c9de560dSAlex Tomas 
3479c9de560dSAlex Tomas /*
3480c9de560dSAlex Tomas  * creates new preallocated space for locality group inodes belongs to
3481c9de560dSAlex Tomas  */
34824ddfef7bSEric Sandeen static noinline_for_stack int
34834ddfef7bSEric Sandeen ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3484c9de560dSAlex Tomas {
3485c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
3486c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
3487c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3488c9de560dSAlex Tomas 	struct ext4_group_info *grp;
3489c9de560dSAlex Tomas 
3490c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
3491c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3492c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3493c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3494c9de560dSAlex Tomas 
3495c9de560dSAlex Tomas 	BUG_ON(ext4_pspace_cachep == NULL);
3496c9de560dSAlex Tomas 	pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3497c9de560dSAlex Tomas 	if (pa == NULL)
3498c9de560dSAlex Tomas 		return -ENOMEM;
3499c9de560dSAlex Tomas 
3500c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
3501c9de560dSAlex Tomas 	 * allocated blocks for history */
3502c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
3503c9de560dSAlex Tomas 
3504c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3505c9de560dSAlex Tomas 	pa->pa_lstart = pa->pa_pstart;
3506c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
3507c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
3508c9de560dSAlex Tomas 	atomic_set(&pa->pa_count, 1);
3509c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
35106be2ded1SAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_inode_list);
3511d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
3512c9de560dSAlex Tomas 	pa->pa_deleted = 0;
3513cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_GROUP_PA;
3514c9de560dSAlex Tomas 
35156ba495e9STheodore Ts'o 	mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3516c9de560dSAlex Tomas 			pa->pa_pstart, pa->pa_len, pa->pa_lstart);
35179bffad1eSTheodore Ts'o 	trace_ext4_mb_new_group_pa(ac, pa);
3518c9de560dSAlex Tomas 
3519c9de560dSAlex Tomas 	ext4_mb_use_group_pa(ac, pa);
3520c9de560dSAlex Tomas 	atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3521c9de560dSAlex Tomas 
3522c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3523c9de560dSAlex Tomas 	lg = ac->ac_lg;
3524c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
3525c9de560dSAlex Tomas 
3526c9de560dSAlex Tomas 	pa->pa_obj_lock = &lg->lg_prealloc_lock;
3527c9de560dSAlex Tomas 	pa->pa_inode = NULL;
3528c9de560dSAlex Tomas 
3529c9de560dSAlex Tomas 	ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3530c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3531c9de560dSAlex Tomas 	ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3532c9de560dSAlex Tomas 
35336be2ded1SAneesh Kumar K.V 	/*
35346be2ded1SAneesh Kumar K.V 	 * We will later add the new pa to the right bucket
35356be2ded1SAneesh Kumar K.V 	 * after updating the pa_free in ext4_mb_release_context
35366be2ded1SAneesh Kumar K.V 	 */
3537c9de560dSAlex Tomas 	return 0;
3538c9de560dSAlex Tomas }
3539c9de560dSAlex Tomas 
3540c9de560dSAlex Tomas static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3541c9de560dSAlex Tomas {
3542c9de560dSAlex Tomas 	int err;
3543c9de560dSAlex Tomas 
3544c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3545c9de560dSAlex Tomas 		err = ext4_mb_new_group_pa(ac);
3546c9de560dSAlex Tomas 	else
3547c9de560dSAlex Tomas 		err = ext4_mb_new_inode_pa(ac);
3548c9de560dSAlex Tomas 	return err;
3549c9de560dSAlex Tomas }
3550c9de560dSAlex Tomas 
3551c9de560dSAlex Tomas /*
3552c9de560dSAlex Tomas  * finds all unused blocks in on-disk bitmap, frees them in
3553c9de560dSAlex Tomas  * in-core bitmap and buddy.
3554c9de560dSAlex Tomas  * @pa must be unlinked from inode and group lists, so that
3555c9de560dSAlex Tomas  * nobody else can find/use it.
3556c9de560dSAlex Tomas  * the caller MUST hold group/inode locks.
3557c9de560dSAlex Tomas  * TODO: optimize the case when there are no in-core structures yet
3558c9de560dSAlex Tomas  */
35594ddfef7bSEric Sandeen static noinline_for_stack int
35604ddfef7bSEric Sandeen ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
35613e1e5f50SEric Sandeen 			struct ext4_prealloc_space *pa)
3562c9de560dSAlex Tomas {
3563c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
3564c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3565498e5f24STheodore Ts'o 	unsigned int end;
3566498e5f24STheodore Ts'o 	unsigned int next;
3567c9de560dSAlex Tomas 	ext4_group_t group;
3568c9de560dSAlex Tomas 	ext4_grpblk_t bit;
3569ba80b101STheodore Ts'o 	unsigned long long grp_blk_start;
3570c9de560dSAlex Tomas 	int err = 0;
3571c9de560dSAlex Tomas 	int free = 0;
3572c9de560dSAlex Tomas 
3573c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
3574c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
357553accfa9STheodore Ts'o 	grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
3576c9de560dSAlex Tomas 	BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3577c9de560dSAlex Tomas 	end = bit + pa->pa_len;
3578c9de560dSAlex Tomas 
3579c9de560dSAlex Tomas 	while (bit < end) {
3580ffad0a44SAneesh Kumar K.V 		bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3581c9de560dSAlex Tomas 		if (bit >= end)
3582c9de560dSAlex Tomas 			break;
3583ffad0a44SAneesh Kumar K.V 		next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
35846ba495e9STheodore Ts'o 		mb_debug(1, "    free preallocated %u/%u in group %u\n",
35855a0790c2SAndi Kleen 			 (unsigned) ext4_group_first_block_no(sb, group) + bit,
35865a0790c2SAndi Kleen 			 (unsigned) next - bit, (unsigned) group);
3587c9de560dSAlex Tomas 		free += next - bit;
3588c9de560dSAlex Tomas 
35893e1e5f50SEric Sandeen 		trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
359053accfa9STheodore Ts'o 		trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
359153accfa9STheodore Ts'o 						    EXT4_C2B(sbi, bit)),
3592a9c667f8SLukas Czerner 					       next - bit);
3593c9de560dSAlex Tomas 		mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3594c9de560dSAlex Tomas 		bit = next + 1;
3595c9de560dSAlex Tomas 	}
3596c9de560dSAlex Tomas 	if (free != pa->pa_free) {
35979d8b9ec4STheodore Ts'o 		ext4_msg(e4b->bd_sb, KERN_CRIT,
35989d8b9ec4STheodore Ts'o 			 "pa %p: logic %lu, phys. %lu, len %lu",
3599c9de560dSAlex Tomas 			 pa, (unsigned long) pa->pa_lstart,
3600c9de560dSAlex Tomas 			 (unsigned long) pa->pa_pstart,
3601c9de560dSAlex Tomas 			 (unsigned long) pa->pa_len);
3602e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
360326346ff6SAneesh Kumar K.V 					free, pa->pa_free);
3604e56eb659SAneesh Kumar K.V 		/*
3605e56eb659SAneesh Kumar K.V 		 * pa is already deleted so we use the value obtained
3606e56eb659SAneesh Kumar K.V 		 * from the bitmap and continue.
3607e56eb659SAneesh Kumar K.V 		 */
3608c9de560dSAlex Tomas 	}
3609c9de560dSAlex Tomas 	atomic_add(free, &sbi->s_mb_discarded);
3610c9de560dSAlex Tomas 
3611c9de560dSAlex Tomas 	return err;
3612c9de560dSAlex Tomas }
3613c9de560dSAlex Tomas 
36144ddfef7bSEric Sandeen static noinline_for_stack int
36154ddfef7bSEric Sandeen ext4_mb_release_group_pa(struct ext4_buddy *e4b,
36163e1e5f50SEric Sandeen 				struct ext4_prealloc_space *pa)
3617c9de560dSAlex Tomas {
3618c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
3619c9de560dSAlex Tomas 	ext4_group_t group;
3620c9de560dSAlex Tomas 	ext4_grpblk_t bit;
3621c9de560dSAlex Tomas 
362260e07cf5SYongqiang Yang 	trace_ext4_mb_release_group_pa(sb, pa);
3623c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
3624c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3625c9de560dSAlex Tomas 	BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3626c9de560dSAlex Tomas 	mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3627c9de560dSAlex Tomas 	atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
36283e1e5f50SEric Sandeen 	trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3629c9de560dSAlex Tomas 
3630c9de560dSAlex Tomas 	return 0;
3631c9de560dSAlex Tomas }
3632c9de560dSAlex Tomas 
3633c9de560dSAlex Tomas /*
3634c9de560dSAlex Tomas  * releases all preallocations in given group
3635c9de560dSAlex Tomas  *
3636c9de560dSAlex Tomas  * first, we need to decide discard policy:
3637c9de560dSAlex Tomas  * - when do we discard
3638c9de560dSAlex Tomas  *   1) ENOSPC
3639c9de560dSAlex Tomas  * - how many do we discard
3640c9de560dSAlex Tomas  *   1) how many requested
3641c9de560dSAlex Tomas  */
36424ddfef7bSEric Sandeen static noinline_for_stack int
36434ddfef7bSEric Sandeen ext4_mb_discard_group_preallocations(struct super_block *sb,
3644c9de560dSAlex Tomas 					ext4_group_t group, int needed)
3645c9de560dSAlex Tomas {
3646c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3647c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
3648c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
3649c9de560dSAlex Tomas 	struct list_head list;
3650c9de560dSAlex Tomas 	struct ext4_buddy e4b;
3651c9de560dSAlex Tomas 	int err;
3652c9de560dSAlex Tomas 	int busy = 0;
3653c9de560dSAlex Tomas 	int free = 0;
3654c9de560dSAlex Tomas 
36556ba495e9STheodore Ts'o 	mb_debug(1, "discard preallocation for group %u\n", group);
3656c9de560dSAlex Tomas 
3657c9de560dSAlex Tomas 	if (list_empty(&grp->bb_prealloc_list))
3658c9de560dSAlex Tomas 		return 0;
3659c9de560dSAlex Tomas 
3660574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, group);
3661c9de560dSAlex Tomas 	if (bitmap_bh == NULL) {
366212062dddSEric Sandeen 		ext4_error(sb, "Error reading block bitmap for %u", group);
3663ce89f46cSAneesh Kumar K.V 		return 0;
3664c9de560dSAlex Tomas 	}
3665c9de560dSAlex Tomas 
3666c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(sb, group, &e4b);
3667ce89f46cSAneesh Kumar K.V 	if (err) {
366812062dddSEric Sandeen 		ext4_error(sb, "Error loading buddy information for %u", group);
3669ce89f46cSAneesh Kumar K.V 		put_bh(bitmap_bh);
3670ce89f46cSAneesh Kumar K.V 		return 0;
3671ce89f46cSAneesh Kumar K.V 	}
3672c9de560dSAlex Tomas 
3673c9de560dSAlex Tomas 	if (needed == 0)
36747137d7a4STheodore Ts'o 		needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
3675c9de560dSAlex Tomas 
3676c9de560dSAlex Tomas 	INIT_LIST_HEAD(&list);
3677c9de560dSAlex Tomas repeat:
3678c9de560dSAlex Tomas 	ext4_lock_group(sb, group);
3679c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp,
3680c9de560dSAlex Tomas 				&grp->bb_prealloc_list, pa_group_list) {
3681c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3682c9de560dSAlex Tomas 		if (atomic_read(&pa->pa_count)) {
3683c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3684c9de560dSAlex Tomas 			busy = 1;
3685c9de560dSAlex Tomas 			continue;
3686c9de560dSAlex Tomas 		}
3687c9de560dSAlex Tomas 		if (pa->pa_deleted) {
3688c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3689c9de560dSAlex Tomas 			continue;
3690c9de560dSAlex Tomas 		}
3691c9de560dSAlex Tomas 
3692c9de560dSAlex Tomas 		/* seems this one can be freed ... */
3693c9de560dSAlex Tomas 		pa->pa_deleted = 1;
3694c9de560dSAlex Tomas 
3695c9de560dSAlex Tomas 		/* we can trust pa_free ... */
3696c9de560dSAlex Tomas 		free += pa->pa_free;
3697c9de560dSAlex Tomas 
3698c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3699c9de560dSAlex Tomas 
3700c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
3701c9de560dSAlex Tomas 		list_add(&pa->u.pa_tmp_list, &list);
3702c9de560dSAlex Tomas 	}
3703c9de560dSAlex Tomas 
3704c9de560dSAlex Tomas 	/* if we still need more blocks and some PAs were used, try again */
3705c9de560dSAlex Tomas 	if (free < needed && busy) {
3706c9de560dSAlex Tomas 		busy = 0;
3707c9de560dSAlex Tomas 		ext4_unlock_group(sb, group);
3708c9de560dSAlex Tomas 		/*
3709c9de560dSAlex Tomas 		 * Yield the CPU here so that we don't get soft lockup
3710c9de560dSAlex Tomas 		 * in non preempt case.
3711c9de560dSAlex Tomas 		 */
3712c9de560dSAlex Tomas 		yield();
3713c9de560dSAlex Tomas 		goto repeat;
3714c9de560dSAlex Tomas 	}
3715c9de560dSAlex Tomas 
3716c9de560dSAlex Tomas 	/* found anything to free? */
3717c9de560dSAlex Tomas 	if (list_empty(&list)) {
3718c9de560dSAlex Tomas 		BUG_ON(free != 0);
3719c9de560dSAlex Tomas 		goto out;
3720c9de560dSAlex Tomas 	}
3721c9de560dSAlex Tomas 
3722c9de560dSAlex Tomas 	/* now free all selected PAs */
3723c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3724c9de560dSAlex Tomas 
3725c9de560dSAlex Tomas 		/* remove from object (inode or locality group) */
3726c9de560dSAlex Tomas 		spin_lock(pa->pa_obj_lock);
3727c9de560dSAlex Tomas 		list_del_rcu(&pa->pa_inode_list);
3728c9de560dSAlex Tomas 		spin_unlock(pa->pa_obj_lock);
3729c9de560dSAlex Tomas 
3730cc0fb9adSAneesh Kumar K.V 		if (pa->pa_type == MB_GROUP_PA)
37313e1e5f50SEric Sandeen 			ext4_mb_release_group_pa(&e4b, pa);
3732c9de560dSAlex Tomas 		else
37333e1e5f50SEric Sandeen 			ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3734c9de560dSAlex Tomas 
3735c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
3736c9de560dSAlex Tomas 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3737c9de560dSAlex Tomas 	}
3738c9de560dSAlex Tomas 
3739c9de560dSAlex Tomas out:
3740c9de560dSAlex Tomas 	ext4_unlock_group(sb, group);
3741e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
3742c9de560dSAlex Tomas 	put_bh(bitmap_bh);
3743c9de560dSAlex Tomas 	return free;
3744c9de560dSAlex Tomas }
3745c9de560dSAlex Tomas 
3746c9de560dSAlex Tomas /*
3747c9de560dSAlex Tomas  * releases all non-used preallocated blocks for given inode
3748c9de560dSAlex Tomas  *
3749c9de560dSAlex Tomas  * It's important to discard preallocations under i_data_sem
3750c9de560dSAlex Tomas  * We don't want another block to be served from the prealloc
3751c9de560dSAlex Tomas  * space when we are discarding the inode prealloc space.
3752c9de560dSAlex Tomas  *
3753c9de560dSAlex Tomas  * FIXME!! Make sure it is valid at all the call sites
3754c9de560dSAlex Tomas  */
3755c2ea3fdeSTheodore Ts'o void ext4_discard_preallocations(struct inode *inode)
3756c9de560dSAlex Tomas {
3757c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(inode);
3758c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
3759c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
3760c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
3761c9de560dSAlex Tomas 	ext4_group_t group = 0;
3762c9de560dSAlex Tomas 	struct list_head list;
3763c9de560dSAlex Tomas 	struct ext4_buddy e4b;
3764c9de560dSAlex Tomas 	int err;
3765c9de560dSAlex Tomas 
3766c2ea3fdeSTheodore Ts'o 	if (!S_ISREG(inode->i_mode)) {
3767c9de560dSAlex Tomas 		/*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
3768c9de560dSAlex Tomas 		return;
3769c9de560dSAlex Tomas 	}
3770c9de560dSAlex Tomas 
37716ba495e9STheodore Ts'o 	mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
37729bffad1eSTheodore Ts'o 	trace_ext4_discard_preallocations(inode);
3773c9de560dSAlex Tomas 
3774c9de560dSAlex Tomas 	INIT_LIST_HEAD(&list);
3775c9de560dSAlex Tomas 
3776c9de560dSAlex Tomas repeat:
3777c9de560dSAlex Tomas 	/* first, collect all pa's in the inode */
3778c9de560dSAlex Tomas 	spin_lock(&ei->i_prealloc_lock);
3779c9de560dSAlex Tomas 	while (!list_empty(&ei->i_prealloc_list)) {
3780c9de560dSAlex Tomas 		pa = list_entry(ei->i_prealloc_list.next,
3781c9de560dSAlex Tomas 				struct ext4_prealloc_space, pa_inode_list);
3782c9de560dSAlex Tomas 		BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
3783c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3784c9de560dSAlex Tomas 		if (atomic_read(&pa->pa_count)) {
3785c9de560dSAlex Tomas 			/* this shouldn't happen often - nobody should
3786c9de560dSAlex Tomas 			 * use preallocation while we're discarding it */
3787c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3788c9de560dSAlex Tomas 			spin_unlock(&ei->i_prealloc_lock);
37899d8b9ec4STheodore Ts'o 			ext4_msg(sb, KERN_ERR,
37909d8b9ec4STheodore Ts'o 				 "uh-oh! used pa while discarding");
3791c9de560dSAlex Tomas 			WARN_ON(1);
3792c9de560dSAlex Tomas 			schedule_timeout_uninterruptible(HZ);
3793c9de560dSAlex Tomas 			goto repeat;
3794c9de560dSAlex Tomas 
3795c9de560dSAlex Tomas 		}
3796c9de560dSAlex Tomas 		if (pa->pa_deleted == 0) {
3797c9de560dSAlex Tomas 			pa->pa_deleted = 1;
3798c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3799c9de560dSAlex Tomas 			list_del_rcu(&pa->pa_inode_list);
3800c9de560dSAlex Tomas 			list_add(&pa->u.pa_tmp_list, &list);
3801c9de560dSAlex Tomas 			continue;
3802c9de560dSAlex Tomas 		}
3803c9de560dSAlex Tomas 
3804c9de560dSAlex Tomas 		/* someone is deleting pa right now */
3805c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3806c9de560dSAlex Tomas 		spin_unlock(&ei->i_prealloc_lock);
3807c9de560dSAlex Tomas 
3808c9de560dSAlex Tomas 		/* we have to wait here because pa_deleted
3809c9de560dSAlex Tomas 		 * doesn't mean pa is already unlinked from
3810c9de560dSAlex Tomas 		 * the list. as we might be called from
3811c9de560dSAlex Tomas 		 * ->clear_inode() the inode will get freed
3812c9de560dSAlex Tomas 		 * and concurrent thread which is unlinking
3813c9de560dSAlex Tomas 		 * pa from inode's list may access already
3814c9de560dSAlex Tomas 		 * freed memory, bad-bad-bad */
3815c9de560dSAlex Tomas 
3816c9de560dSAlex Tomas 		/* XXX: if this happens too often, we can
3817c9de560dSAlex Tomas 		 * add a flag to force wait only in case
3818c9de560dSAlex Tomas 		 * of ->clear_inode(), but not in case of
3819c9de560dSAlex Tomas 		 * regular truncate */
3820c9de560dSAlex Tomas 		schedule_timeout_uninterruptible(HZ);
3821c9de560dSAlex Tomas 		goto repeat;
3822c9de560dSAlex Tomas 	}
3823c9de560dSAlex Tomas 	spin_unlock(&ei->i_prealloc_lock);
3824c9de560dSAlex Tomas 
3825c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3826cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_INODE_PA);
3827c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
3828c9de560dSAlex Tomas 
3829c9de560dSAlex Tomas 		err = ext4_mb_load_buddy(sb, group, &e4b);
3830ce89f46cSAneesh Kumar K.V 		if (err) {
383112062dddSEric Sandeen 			ext4_error(sb, "Error loading buddy information for %u",
383212062dddSEric Sandeen 					group);
3833ce89f46cSAneesh Kumar K.V 			continue;
3834ce89f46cSAneesh Kumar K.V 		}
3835c9de560dSAlex Tomas 
3836574ca174STheodore Ts'o 		bitmap_bh = ext4_read_block_bitmap(sb, group);
3837c9de560dSAlex Tomas 		if (bitmap_bh == NULL) {
383812062dddSEric Sandeen 			ext4_error(sb, "Error reading block bitmap for %u",
383912062dddSEric Sandeen 					group);
3840e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
3841ce89f46cSAneesh Kumar K.V 			continue;
3842c9de560dSAlex Tomas 		}
3843c9de560dSAlex Tomas 
3844c9de560dSAlex Tomas 		ext4_lock_group(sb, group);
3845c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
38463e1e5f50SEric Sandeen 		ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3847c9de560dSAlex Tomas 		ext4_unlock_group(sb, group);
3848c9de560dSAlex Tomas 
3849e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
3850c9de560dSAlex Tomas 		put_bh(bitmap_bh);
3851c9de560dSAlex Tomas 
3852c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
3853c9de560dSAlex Tomas 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3854c9de560dSAlex Tomas 	}
3855c9de560dSAlex Tomas }
3856c9de560dSAlex Tomas 
38576ba495e9STheodore Ts'o #ifdef CONFIG_EXT4_DEBUG
3858c9de560dSAlex Tomas static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3859c9de560dSAlex Tomas {
3860c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
38618df9675fSTheodore Ts'o 	ext4_group_t ngroups, i;
3862c9de560dSAlex Tomas 
38634dd89fc6STheodore Ts'o 	if (!mb_enable_debug ||
38644dd89fc6STheodore Ts'o 	    (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
3865e3570639SEric Sandeen 		return;
3866e3570639SEric Sandeen 
38677f6a11e7SJoe Perches 	ext4_msg(ac->ac_sb, KERN_ERR, "Can't allocate:"
38689d8b9ec4STheodore Ts'o 			" Allocation context details:");
38697f6a11e7SJoe Perches 	ext4_msg(ac->ac_sb, KERN_ERR, "status %d flags %d",
3870c9de560dSAlex Tomas 			ac->ac_status, ac->ac_flags);
38717f6a11e7SJoe Perches 	ext4_msg(ac->ac_sb, KERN_ERR, "orig %lu/%lu/%lu@%lu, "
38729d8b9ec4STheodore Ts'o 		 	"goal %lu/%lu/%lu@%lu, "
38739d8b9ec4STheodore Ts'o 			"best %lu/%lu/%lu@%lu cr %d",
3874c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_group,
3875c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_start,
3876c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_len,
3877c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_logical,
3878c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_group,
3879c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_start,
3880c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_len,
3881c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_logical,
3882c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_group,
3883c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_start,
3884c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_len,
3885c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_logical,
3886c9de560dSAlex Tomas 			(int)ac->ac_criteria);
38877f6a11e7SJoe Perches 	ext4_msg(ac->ac_sb, KERN_ERR, "%lu scanned, %d found",
38889d8b9ec4STheodore Ts'o 		 ac->ac_ex_scanned, ac->ac_found);
38897f6a11e7SJoe Perches 	ext4_msg(ac->ac_sb, KERN_ERR, "groups: ");
38908df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
38918df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
3892c9de560dSAlex Tomas 		struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3893c9de560dSAlex Tomas 		struct ext4_prealloc_space *pa;
3894c9de560dSAlex Tomas 		ext4_grpblk_t start;
3895c9de560dSAlex Tomas 		struct list_head *cur;
3896c9de560dSAlex Tomas 		ext4_lock_group(sb, i);
3897c9de560dSAlex Tomas 		list_for_each(cur, &grp->bb_prealloc_list) {
3898c9de560dSAlex Tomas 			pa = list_entry(cur, struct ext4_prealloc_space,
3899c9de560dSAlex Tomas 					pa_group_list);
3900c9de560dSAlex Tomas 			spin_lock(&pa->pa_lock);
3901c9de560dSAlex Tomas 			ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3902c9de560dSAlex Tomas 						     NULL, &start);
3903c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
39041c718505SAkira Fujita 			printk(KERN_ERR "PA:%u:%d:%u \n", i,
3905c9de560dSAlex Tomas 			       start, pa->pa_len);
3906c9de560dSAlex Tomas 		}
390760bd63d1SSolofo Ramangalahy 		ext4_unlock_group(sb, i);
3908c9de560dSAlex Tomas 
3909c9de560dSAlex Tomas 		if (grp->bb_free == 0)
3910c9de560dSAlex Tomas 			continue;
39111c718505SAkira Fujita 		printk(KERN_ERR "%u: %d/%d \n",
3912c9de560dSAlex Tomas 		       i, grp->bb_free, grp->bb_fragments);
3913c9de560dSAlex Tomas 	}
3914c9de560dSAlex Tomas 	printk(KERN_ERR "\n");
3915c9de560dSAlex Tomas }
3916c9de560dSAlex Tomas #else
3917c9de560dSAlex Tomas static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3918c9de560dSAlex Tomas {
3919c9de560dSAlex Tomas 	return;
3920c9de560dSAlex Tomas }
3921c9de560dSAlex Tomas #endif
3922c9de560dSAlex Tomas 
3923c9de560dSAlex Tomas /*
3924c9de560dSAlex Tomas  * We use locality group preallocation for small size file. The size of the
3925c9de560dSAlex Tomas  * file is determined by the current size or the resulting size after
3926c9de560dSAlex Tomas  * allocation which ever is larger
3927c9de560dSAlex Tomas  *
3928b713a5ecSTheodore Ts'o  * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
3929c9de560dSAlex Tomas  */
3930c9de560dSAlex Tomas static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
3931c9de560dSAlex Tomas {
3932c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3933c9de560dSAlex Tomas 	int bsbits = ac->ac_sb->s_blocksize_bits;
3934c9de560dSAlex Tomas 	loff_t size, isize;
3935c9de560dSAlex Tomas 
3936c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3937c9de560dSAlex Tomas 		return;
3938c9de560dSAlex Tomas 
39394ba74d00STheodore Ts'o 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
39404ba74d00STheodore Ts'o 		return;
39414ba74d00STheodore Ts'o 
394253accfa9STheodore Ts'o 	size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
394350797481STheodore Ts'o 	isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
394450797481STheodore Ts'o 		>> bsbits;
3945c9de560dSAlex Tomas 
394650797481STheodore Ts'o 	if ((size == isize) &&
394750797481STheodore Ts'o 	    !ext4_fs_is_busy(sbi) &&
394850797481STheodore Ts'o 	    (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
394950797481STheodore Ts'o 		ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
395050797481STheodore Ts'o 		return;
395150797481STheodore Ts'o 	}
395250797481STheodore Ts'o 
3953ebbe0277SRobin Dong 	if (sbi->s_mb_group_prealloc <= 0) {
3954ebbe0277SRobin Dong 		ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
3955ebbe0277SRobin Dong 		return;
3956ebbe0277SRobin Dong 	}
3957ebbe0277SRobin Dong 
3958c9de560dSAlex Tomas 	/* don't use group allocation for large files */
395971780577STheodore Ts'o 	size = max(size, isize);
3960cc483f10STao Ma 	if (size > sbi->s_mb_stream_request) {
39614ba74d00STheodore Ts'o 		ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
3962c9de560dSAlex Tomas 		return;
39634ba74d00STheodore Ts'o 	}
3964c9de560dSAlex Tomas 
3965c9de560dSAlex Tomas 	BUG_ON(ac->ac_lg != NULL);
3966c9de560dSAlex Tomas 	/*
3967c9de560dSAlex Tomas 	 * locality group prealloc space are per cpu. The reason for having
3968c9de560dSAlex Tomas 	 * per cpu locality group is to reduce the contention between block
3969c9de560dSAlex Tomas 	 * request from multiple CPUs.
3970c9de560dSAlex Tomas 	 */
3971ca0c9584SChristoph Lameter 	ac->ac_lg = __this_cpu_ptr(sbi->s_locality_groups);
3972c9de560dSAlex Tomas 
3973c9de560dSAlex Tomas 	/* we're going to use group allocation */
3974c9de560dSAlex Tomas 	ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
3975c9de560dSAlex Tomas 
3976c9de560dSAlex Tomas 	/* serialize all allocations in the group */
3977c9de560dSAlex Tomas 	mutex_lock(&ac->ac_lg->lg_mutex);
3978c9de560dSAlex Tomas }
3979c9de560dSAlex Tomas 
39804ddfef7bSEric Sandeen static noinline_for_stack int
39814ddfef7bSEric Sandeen ext4_mb_initialize_context(struct ext4_allocation_context *ac,
3982c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
3983c9de560dSAlex Tomas {
3984c9de560dSAlex Tomas 	struct super_block *sb = ar->inode->i_sb;
3985c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3986c9de560dSAlex Tomas 	struct ext4_super_block *es = sbi->s_es;
3987c9de560dSAlex Tomas 	ext4_group_t group;
3988498e5f24STheodore Ts'o 	unsigned int len;
3989498e5f24STheodore Ts'o 	ext4_fsblk_t goal;
3990c9de560dSAlex Tomas 	ext4_grpblk_t block;
3991c9de560dSAlex Tomas 
3992c9de560dSAlex Tomas 	/* we can't allocate > group size */
3993c9de560dSAlex Tomas 	len = ar->len;
3994c9de560dSAlex Tomas 
3995c9de560dSAlex Tomas 	/* just a dirty hack to filter too big requests  */
39967137d7a4STheodore Ts'o 	if (len >= EXT4_CLUSTERS_PER_GROUP(sb) - 10)
39977137d7a4STheodore Ts'o 		len = EXT4_CLUSTERS_PER_GROUP(sb) - 10;
3998c9de560dSAlex Tomas 
3999c9de560dSAlex Tomas 	/* start searching from the goal */
4000c9de560dSAlex Tomas 	goal = ar->goal;
4001c9de560dSAlex Tomas 	if (goal < le32_to_cpu(es->s_first_data_block) ||
4002c9de560dSAlex Tomas 			goal >= ext4_blocks_count(es))
4003c9de560dSAlex Tomas 		goal = le32_to_cpu(es->s_first_data_block);
4004c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, goal, &group, &block);
4005c9de560dSAlex Tomas 
4006c9de560dSAlex Tomas 	/* set up allocation goals */
4007833576b3STheodore Ts'o 	memset(ac, 0, sizeof(struct ext4_allocation_context));
400853accfa9STheodore Ts'o 	ac->ac_b_ex.fe_logical = ar->logical & ~(sbi->s_cluster_ratio - 1);
4009c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_CONTINUE;
4010c9de560dSAlex Tomas 	ac->ac_sb = sb;
4011c9de560dSAlex Tomas 	ac->ac_inode = ar->inode;
401253accfa9STheodore Ts'o 	ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4013c9de560dSAlex Tomas 	ac->ac_o_ex.fe_group = group;
4014c9de560dSAlex Tomas 	ac->ac_o_ex.fe_start = block;
4015c9de560dSAlex Tomas 	ac->ac_o_ex.fe_len = len;
401653accfa9STheodore Ts'o 	ac->ac_g_ex = ac->ac_o_ex;
4017c9de560dSAlex Tomas 	ac->ac_flags = ar->flags;
4018c9de560dSAlex Tomas 
4019c9de560dSAlex Tomas 	/* we have to define context: we'll we work with a file or
4020c9de560dSAlex Tomas 	 * locality group. this is a policy, actually */
4021c9de560dSAlex Tomas 	ext4_mb_group_or_file(ac);
4022c9de560dSAlex Tomas 
40236ba495e9STheodore Ts'o 	mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4024c9de560dSAlex Tomas 			"left: %u/%u, right %u/%u to %swritable\n",
4025c9de560dSAlex Tomas 			(unsigned) ar->len, (unsigned) ar->logical,
4026c9de560dSAlex Tomas 			(unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4027c9de560dSAlex Tomas 			(unsigned) ar->lleft, (unsigned) ar->pleft,
4028c9de560dSAlex Tomas 			(unsigned) ar->lright, (unsigned) ar->pright,
4029c9de560dSAlex Tomas 			atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4030c9de560dSAlex Tomas 	return 0;
4031c9de560dSAlex Tomas 
4032c9de560dSAlex Tomas }
4033c9de560dSAlex Tomas 
40346be2ded1SAneesh Kumar K.V static noinline_for_stack void
40356be2ded1SAneesh Kumar K.V ext4_mb_discard_lg_preallocations(struct super_block *sb,
40366be2ded1SAneesh Kumar K.V 					struct ext4_locality_group *lg,
40376be2ded1SAneesh Kumar K.V 					int order, int total_entries)
40386be2ded1SAneesh Kumar K.V {
40396be2ded1SAneesh Kumar K.V 	ext4_group_t group = 0;
40406be2ded1SAneesh Kumar K.V 	struct ext4_buddy e4b;
40416be2ded1SAneesh Kumar K.V 	struct list_head discard_list;
40426be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa, *tmp;
40436be2ded1SAneesh Kumar K.V 
40446ba495e9STheodore Ts'o 	mb_debug(1, "discard locality group preallocation\n");
40456be2ded1SAneesh Kumar K.V 
40466be2ded1SAneesh Kumar K.V 	INIT_LIST_HEAD(&discard_list);
40476be2ded1SAneesh Kumar K.V 
40486be2ded1SAneesh Kumar K.V 	spin_lock(&lg->lg_prealloc_lock);
40496be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
40506be2ded1SAneesh Kumar K.V 						pa_inode_list) {
40516be2ded1SAneesh Kumar K.V 		spin_lock(&pa->pa_lock);
40526be2ded1SAneesh Kumar K.V 		if (atomic_read(&pa->pa_count)) {
40536be2ded1SAneesh Kumar K.V 			/*
40546be2ded1SAneesh Kumar K.V 			 * This is the pa that we just used
40556be2ded1SAneesh Kumar K.V 			 * for block allocation. So don't
40566be2ded1SAneesh Kumar K.V 			 * free that
40576be2ded1SAneesh Kumar K.V 			 */
40586be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
40596be2ded1SAneesh Kumar K.V 			continue;
40606be2ded1SAneesh Kumar K.V 		}
40616be2ded1SAneesh Kumar K.V 		if (pa->pa_deleted) {
40626be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
40636be2ded1SAneesh Kumar K.V 			continue;
40646be2ded1SAneesh Kumar K.V 		}
40656be2ded1SAneesh Kumar K.V 		/* only lg prealloc space */
4066cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_GROUP_PA);
40676be2ded1SAneesh Kumar K.V 
40686be2ded1SAneesh Kumar K.V 		/* seems this one can be freed ... */
40696be2ded1SAneesh Kumar K.V 		pa->pa_deleted = 1;
40706be2ded1SAneesh Kumar K.V 		spin_unlock(&pa->pa_lock);
40716be2ded1SAneesh Kumar K.V 
40726be2ded1SAneesh Kumar K.V 		list_del_rcu(&pa->pa_inode_list);
40736be2ded1SAneesh Kumar K.V 		list_add(&pa->u.pa_tmp_list, &discard_list);
40746be2ded1SAneesh Kumar K.V 
40756be2ded1SAneesh Kumar K.V 		total_entries--;
40766be2ded1SAneesh Kumar K.V 		if (total_entries <= 5) {
40776be2ded1SAneesh Kumar K.V 			/*
40786be2ded1SAneesh Kumar K.V 			 * we want to keep only 5 entries
40796be2ded1SAneesh Kumar K.V 			 * allowing it to grow to 8. This
40806be2ded1SAneesh Kumar K.V 			 * mak sure we don't call discard
40816be2ded1SAneesh Kumar K.V 			 * soon for this list.
40826be2ded1SAneesh Kumar K.V 			 */
40836be2ded1SAneesh Kumar K.V 			break;
40846be2ded1SAneesh Kumar K.V 		}
40856be2ded1SAneesh Kumar K.V 	}
40866be2ded1SAneesh Kumar K.V 	spin_unlock(&lg->lg_prealloc_lock);
40876be2ded1SAneesh Kumar K.V 
40886be2ded1SAneesh Kumar K.V 	list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
40896be2ded1SAneesh Kumar K.V 
40906be2ded1SAneesh Kumar K.V 		ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
40916be2ded1SAneesh Kumar K.V 		if (ext4_mb_load_buddy(sb, group, &e4b)) {
409212062dddSEric Sandeen 			ext4_error(sb, "Error loading buddy information for %u",
409312062dddSEric Sandeen 					group);
40946be2ded1SAneesh Kumar K.V 			continue;
40956be2ded1SAneesh Kumar K.V 		}
40966be2ded1SAneesh Kumar K.V 		ext4_lock_group(sb, group);
40976be2ded1SAneesh Kumar K.V 		list_del(&pa->pa_group_list);
40983e1e5f50SEric Sandeen 		ext4_mb_release_group_pa(&e4b, pa);
40996be2ded1SAneesh Kumar K.V 		ext4_unlock_group(sb, group);
41006be2ded1SAneesh Kumar K.V 
4101e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
41026be2ded1SAneesh Kumar K.V 		list_del(&pa->u.pa_tmp_list);
41036be2ded1SAneesh Kumar K.V 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
41046be2ded1SAneesh Kumar K.V 	}
41056be2ded1SAneesh Kumar K.V }
41066be2ded1SAneesh Kumar K.V 
41076be2ded1SAneesh Kumar K.V /*
41086be2ded1SAneesh Kumar K.V  * We have incremented pa_count. So it cannot be freed at this
41096be2ded1SAneesh Kumar K.V  * point. Also we hold lg_mutex. So no parallel allocation is
41106be2ded1SAneesh Kumar K.V  * possible from this lg. That means pa_free cannot be updated.
41116be2ded1SAneesh Kumar K.V  *
41126be2ded1SAneesh Kumar K.V  * A parallel ext4_mb_discard_group_preallocations is possible.
41136be2ded1SAneesh Kumar K.V  * which can cause the lg_prealloc_list to be updated.
41146be2ded1SAneesh Kumar K.V  */
41156be2ded1SAneesh Kumar K.V 
41166be2ded1SAneesh Kumar K.V static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
41176be2ded1SAneesh Kumar K.V {
41186be2ded1SAneesh Kumar K.V 	int order, added = 0, lg_prealloc_count = 1;
41196be2ded1SAneesh Kumar K.V 	struct super_block *sb = ac->ac_sb;
41206be2ded1SAneesh Kumar K.V 	struct ext4_locality_group *lg = ac->ac_lg;
41216be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
41226be2ded1SAneesh Kumar K.V 
41236be2ded1SAneesh Kumar K.V 	order = fls(pa->pa_free) - 1;
41246be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
41256be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
41266be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
41276be2ded1SAneesh Kumar K.V 	/* Add the prealloc space to lg */
41286be2ded1SAneesh Kumar K.V 	rcu_read_lock();
41296be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
41306be2ded1SAneesh Kumar K.V 						pa_inode_list) {
41316be2ded1SAneesh Kumar K.V 		spin_lock(&tmp_pa->pa_lock);
41326be2ded1SAneesh Kumar K.V 		if (tmp_pa->pa_deleted) {
4133e7c9e3e9STheodore Ts'o 			spin_unlock(&tmp_pa->pa_lock);
41346be2ded1SAneesh Kumar K.V 			continue;
41356be2ded1SAneesh Kumar K.V 		}
41366be2ded1SAneesh Kumar K.V 		if (!added && pa->pa_free < tmp_pa->pa_free) {
41376be2ded1SAneesh Kumar K.V 			/* Add to the tail of the previous entry */
41386be2ded1SAneesh Kumar K.V 			list_add_tail_rcu(&pa->pa_inode_list,
41396be2ded1SAneesh Kumar K.V 						&tmp_pa->pa_inode_list);
41406be2ded1SAneesh Kumar K.V 			added = 1;
41416be2ded1SAneesh Kumar K.V 			/*
41426be2ded1SAneesh Kumar K.V 			 * we want to count the total
41436be2ded1SAneesh Kumar K.V 			 * number of entries in the list
41446be2ded1SAneesh Kumar K.V 			 */
41456be2ded1SAneesh Kumar K.V 		}
41466be2ded1SAneesh Kumar K.V 		spin_unlock(&tmp_pa->pa_lock);
41476be2ded1SAneesh Kumar K.V 		lg_prealloc_count++;
41486be2ded1SAneesh Kumar K.V 	}
41496be2ded1SAneesh Kumar K.V 	if (!added)
41506be2ded1SAneesh Kumar K.V 		list_add_tail_rcu(&pa->pa_inode_list,
41516be2ded1SAneesh Kumar K.V 					&lg->lg_prealloc_list[order]);
41526be2ded1SAneesh Kumar K.V 	rcu_read_unlock();
41536be2ded1SAneesh Kumar K.V 
41546be2ded1SAneesh Kumar K.V 	/* Now trim the list to be not more than 8 elements */
41556be2ded1SAneesh Kumar K.V 	if (lg_prealloc_count > 8) {
41566be2ded1SAneesh Kumar K.V 		ext4_mb_discard_lg_preallocations(sb, lg,
41576be2ded1SAneesh Kumar K.V 						order, lg_prealloc_count);
41586be2ded1SAneesh Kumar K.V 		return;
41596be2ded1SAneesh Kumar K.V 	}
41606be2ded1SAneesh Kumar K.V 	return ;
41616be2ded1SAneesh Kumar K.V }
41626be2ded1SAneesh Kumar K.V 
4163c9de560dSAlex Tomas /*
4164c9de560dSAlex Tomas  * release all resource we used in allocation
4165c9de560dSAlex Tomas  */
4166c9de560dSAlex Tomas static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4167c9de560dSAlex Tomas {
416853accfa9STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
41696be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa = ac->ac_pa;
41706be2ded1SAneesh Kumar K.V 	if (pa) {
4171cc0fb9adSAneesh Kumar K.V 		if (pa->pa_type == MB_GROUP_PA) {
4172c9de560dSAlex Tomas 			/* see comment in ext4_mb_use_group_pa() */
41736be2ded1SAneesh Kumar K.V 			spin_lock(&pa->pa_lock);
417453accfa9STheodore Ts'o 			pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
417553accfa9STheodore Ts'o 			pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
41766be2ded1SAneesh Kumar K.V 			pa->pa_free -= ac->ac_b_ex.fe_len;
41776be2ded1SAneesh Kumar K.V 			pa->pa_len -= ac->ac_b_ex.fe_len;
41786be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
4179ba443916SAneesh Kumar K.V 		}
4180ba443916SAneesh Kumar K.V 	}
4181ba443916SAneesh Kumar K.V 	if (pa) {
41826be2ded1SAneesh Kumar K.V 		/*
41836be2ded1SAneesh Kumar K.V 		 * We want to add the pa to the right bucket.
41846be2ded1SAneesh Kumar K.V 		 * Remove it from the list and while adding
41856be2ded1SAneesh Kumar K.V 		 * make sure the list to which we are adding
418644183d42SAmir Goldstein 		 * doesn't grow big.
41876be2ded1SAneesh Kumar K.V 		 */
4188cc0fb9adSAneesh Kumar K.V 		if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
41896be2ded1SAneesh Kumar K.V 			spin_lock(pa->pa_obj_lock);
41906be2ded1SAneesh Kumar K.V 			list_del_rcu(&pa->pa_inode_list);
41916be2ded1SAneesh Kumar K.V 			spin_unlock(pa->pa_obj_lock);
41926be2ded1SAneesh Kumar K.V 			ext4_mb_add_n_trim(ac);
4193c9de560dSAlex Tomas 		}
41946be2ded1SAneesh Kumar K.V 		ext4_mb_put_pa(ac, ac->ac_sb, pa);
4195c9de560dSAlex Tomas 	}
4196c9de560dSAlex Tomas 	if (ac->ac_bitmap_page)
4197c9de560dSAlex Tomas 		page_cache_release(ac->ac_bitmap_page);
4198c9de560dSAlex Tomas 	if (ac->ac_buddy_page)
4199c9de560dSAlex Tomas 		page_cache_release(ac->ac_buddy_page);
4200c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4201c9de560dSAlex Tomas 		mutex_unlock(&ac->ac_lg->lg_mutex);
4202c9de560dSAlex Tomas 	ext4_mb_collect_stats(ac);
4203c9de560dSAlex Tomas 	return 0;
4204c9de560dSAlex Tomas }
4205c9de560dSAlex Tomas 
4206c9de560dSAlex Tomas static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4207c9de560dSAlex Tomas {
42088df9675fSTheodore Ts'o 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4209c9de560dSAlex Tomas 	int ret;
4210c9de560dSAlex Tomas 	int freed = 0;
4211c9de560dSAlex Tomas 
42129bffad1eSTheodore Ts'o 	trace_ext4_mb_discard_preallocations(sb, needed);
42138df9675fSTheodore Ts'o 	for (i = 0; i < ngroups && needed > 0; i++) {
4214c9de560dSAlex Tomas 		ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4215c9de560dSAlex Tomas 		freed += ret;
4216c9de560dSAlex Tomas 		needed -= ret;
4217c9de560dSAlex Tomas 	}
4218c9de560dSAlex Tomas 
4219c9de560dSAlex Tomas 	return freed;
4220c9de560dSAlex Tomas }
4221c9de560dSAlex Tomas 
4222c9de560dSAlex Tomas /*
4223c9de560dSAlex Tomas  * Main entry point into mballoc to allocate blocks
4224c9de560dSAlex Tomas  * it tries to use preallocation first, then falls back
4225c9de560dSAlex Tomas  * to usual allocation
4226c9de560dSAlex Tomas  */
4227c9de560dSAlex Tomas ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4228c9de560dSAlex Tomas 				struct ext4_allocation_request *ar, int *errp)
4229c9de560dSAlex Tomas {
42306bc6e63fSAneesh Kumar K.V 	int freed;
4231256bdb49SEric Sandeen 	struct ext4_allocation_context *ac = NULL;
4232c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
4233c9de560dSAlex Tomas 	struct super_block *sb;
4234c9de560dSAlex Tomas 	ext4_fsblk_t block = 0;
423560e58e0fSMingming Cao 	unsigned int inquota = 0;
423653accfa9STheodore Ts'o 	unsigned int reserv_clstrs = 0;
4237c9de560dSAlex Tomas 
4238c9de560dSAlex Tomas 	sb = ar->inode->i_sb;
4239c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
4240c9de560dSAlex Tomas 
42419bffad1eSTheodore Ts'o 	trace_ext4_request_blocks(ar);
4242ba80b101STheodore Ts'o 
424345dc63e7SDmitry Monakhov 	/* Allow to use superuser reservation for quota file */
424445dc63e7SDmitry Monakhov 	if (IS_NOQUOTA(ar->inode))
424545dc63e7SDmitry Monakhov 		ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
424645dc63e7SDmitry Monakhov 
4247d2a17637SMingming Cao 	/*
424860e58e0fSMingming Cao 	 * For delayed allocation, we could skip the ENOSPC and
424960e58e0fSMingming Cao 	 * EDQUOT check, as blocks and quotas have been already
425060e58e0fSMingming Cao 	 * reserved when data being copied into pagecache.
425160e58e0fSMingming Cao 	 */
4252f2321097STheodore Ts'o 	if (ext4_test_inode_state(ar->inode, EXT4_STATE_DELALLOC_RESERVED))
425360e58e0fSMingming Cao 		ar->flags |= EXT4_MB_DELALLOC_RESERVED;
425460e58e0fSMingming Cao 	else {
425560e58e0fSMingming Cao 		/* Without delayed allocation we need to verify
425660e58e0fSMingming Cao 		 * there is enough free blocks to do block allocation
425760e58e0fSMingming Cao 		 * and verify allocation doesn't exceed the quota limits.
4258d2a17637SMingming Cao 		 */
425955f020dbSAllison Henderson 		while (ar->len &&
4260e7d5f315STheodore Ts'o 			ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
426155f020dbSAllison Henderson 
4262030ba6bcSAneesh Kumar K.V 			/* let others to free the space */
4263030ba6bcSAneesh Kumar K.V 			yield();
4264030ba6bcSAneesh Kumar K.V 			ar->len = ar->len >> 1;
4265030ba6bcSAneesh Kumar K.V 		}
4266030ba6bcSAneesh Kumar K.V 		if (!ar->len) {
426707031431SMingming Cao 			*errp = -ENOSPC;
426807031431SMingming Cao 			return 0;
426907031431SMingming Cao 		}
427053accfa9STheodore Ts'o 		reserv_clstrs = ar->len;
427155f020dbSAllison Henderson 		if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
427253accfa9STheodore Ts'o 			dquot_alloc_block_nofail(ar->inode,
427353accfa9STheodore Ts'o 						 EXT4_C2B(sbi, ar->len));
427455f020dbSAllison Henderson 		} else {
427555f020dbSAllison Henderson 			while (ar->len &&
427653accfa9STheodore Ts'o 				dquot_alloc_block(ar->inode,
427753accfa9STheodore Ts'o 						  EXT4_C2B(sbi, ar->len))) {
427855f020dbSAllison Henderson 
4279c9de560dSAlex Tomas 				ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4280c9de560dSAlex Tomas 				ar->len--;
4281c9de560dSAlex Tomas 			}
428255f020dbSAllison Henderson 		}
428360e58e0fSMingming Cao 		inquota = ar->len;
4284c9de560dSAlex Tomas 		if (ar->len == 0) {
4285c9de560dSAlex Tomas 			*errp = -EDQUOT;
42866c7a120aSAditya Kali 			goto out;
4287c9de560dSAlex Tomas 		}
428860e58e0fSMingming Cao 	}
4289d2a17637SMingming Cao 
4290256bdb49SEric Sandeen 	ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4291833576b3STheodore Ts'o 	if (!ac) {
4292363d4251SShen Feng 		ar->len = 0;
4293256bdb49SEric Sandeen 		*errp = -ENOMEM;
42946c7a120aSAditya Kali 		goto out;
4295256bdb49SEric Sandeen 	}
4296256bdb49SEric Sandeen 
4297256bdb49SEric Sandeen 	*errp = ext4_mb_initialize_context(ac, ar);
4298c9de560dSAlex Tomas 	if (*errp) {
4299c9de560dSAlex Tomas 		ar->len = 0;
43006c7a120aSAditya Kali 		goto out;
4301c9de560dSAlex Tomas 	}
4302c9de560dSAlex Tomas 
4303256bdb49SEric Sandeen 	ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4304256bdb49SEric Sandeen 	if (!ext4_mb_use_preallocated(ac)) {
4305256bdb49SEric Sandeen 		ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4306256bdb49SEric Sandeen 		ext4_mb_normalize_request(ac, ar);
4307c9de560dSAlex Tomas repeat:
4308c9de560dSAlex Tomas 		/* allocate space in core */
43096c7a120aSAditya Kali 		*errp = ext4_mb_regular_allocator(ac);
43106c7a120aSAditya Kali 		if (*errp)
43116c7a120aSAditya Kali 			goto errout;
4312c9de560dSAlex Tomas 
4313c9de560dSAlex Tomas 		/* as we've just preallocated more space than
4314c9de560dSAlex Tomas 		 * user requested orinally, we store allocated
4315c9de560dSAlex Tomas 		 * space in a special descriptor */
4316256bdb49SEric Sandeen 		if (ac->ac_status == AC_STATUS_FOUND &&
4317256bdb49SEric Sandeen 				ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4318256bdb49SEric Sandeen 			ext4_mb_new_preallocation(ac);
4319c9de560dSAlex Tomas 	}
4320256bdb49SEric Sandeen 	if (likely(ac->ac_status == AC_STATUS_FOUND)) {
432153accfa9STheodore Ts'o 		*errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4322519deca0SAneesh Kumar K.V 		if (*errp == -EAGAIN) {
43238556e8f3SAneesh Kumar K.V 			/*
43248556e8f3SAneesh Kumar K.V 			 * drop the reference that we took
43258556e8f3SAneesh Kumar K.V 			 * in ext4_mb_use_best_found
43268556e8f3SAneesh Kumar K.V 			 */
43278556e8f3SAneesh Kumar K.V 			ext4_mb_release_context(ac);
4328519deca0SAneesh Kumar K.V 			ac->ac_b_ex.fe_group = 0;
4329519deca0SAneesh Kumar K.V 			ac->ac_b_ex.fe_start = 0;
4330519deca0SAneesh Kumar K.V 			ac->ac_b_ex.fe_len = 0;
4331519deca0SAneesh Kumar K.V 			ac->ac_status = AC_STATUS_CONTINUE;
4332519deca0SAneesh Kumar K.V 			goto repeat;
43336c7a120aSAditya Kali 		} else if (*errp)
43346c7a120aSAditya Kali 		errout:
4335b844167eSCurt Wohlgemuth 			ext4_discard_allocated_blocks(ac);
43366c7a120aSAditya Kali 		else {
4337256bdb49SEric Sandeen 			block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4338256bdb49SEric Sandeen 			ar->len = ac->ac_b_ex.fe_len;
4339519deca0SAneesh Kumar K.V 		}
4340c9de560dSAlex Tomas 	} else {
4341256bdb49SEric Sandeen 		freed  = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4342c9de560dSAlex Tomas 		if (freed)
4343c9de560dSAlex Tomas 			goto repeat;
4344c9de560dSAlex Tomas 		*errp = -ENOSPC;
43456c7a120aSAditya Kali 	}
43466c7a120aSAditya Kali 
43476c7a120aSAditya Kali 	if (*errp) {
4348256bdb49SEric Sandeen 		ac->ac_b_ex.fe_len = 0;
4349c9de560dSAlex Tomas 		ar->len = 0;
4350256bdb49SEric Sandeen 		ext4_mb_show_ac(ac);
4351c9de560dSAlex Tomas 	}
4352256bdb49SEric Sandeen 	ext4_mb_release_context(ac);
43536c7a120aSAditya Kali out:
43546c7a120aSAditya Kali 	if (ac)
4355363d4251SShen Feng 		kmem_cache_free(ext4_ac_cachep, ac);
435660e58e0fSMingming Cao 	if (inquota && ar->len < inquota)
435753accfa9STheodore Ts'o 		dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
43580087d9fbSAneesh Kumar K.V 	if (!ar->len) {
4359f2321097STheodore Ts'o 		if (!ext4_test_inode_state(ar->inode,
4360f2321097STheodore Ts'o 					   EXT4_STATE_DELALLOC_RESERVED))
43610087d9fbSAneesh Kumar K.V 			/* release all the reserved blocks if non delalloc */
436257042651STheodore Ts'o 			percpu_counter_sub(&sbi->s_dirtyclusters_counter,
436353accfa9STheodore Ts'o 						reserv_clstrs);
43640087d9fbSAneesh Kumar K.V 	}
4365c9de560dSAlex Tomas 
43669bffad1eSTheodore Ts'o 	trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4367ba80b101STheodore Ts'o 
4368c9de560dSAlex Tomas 	return block;
4369c9de560dSAlex Tomas }
4370c9de560dSAlex Tomas 
4371c894058dSAneesh Kumar K.V /*
4372c894058dSAneesh Kumar K.V  * We can merge two free data extents only if the physical blocks
4373c894058dSAneesh Kumar K.V  * are contiguous, AND the extents were freed by the same transaction,
4374c894058dSAneesh Kumar K.V  * AND the blocks are associated with the same group.
4375c894058dSAneesh Kumar K.V  */
4376c894058dSAneesh Kumar K.V static int can_merge(struct ext4_free_data *entry1,
4377c894058dSAneesh Kumar K.V 			struct ext4_free_data *entry2)
4378c894058dSAneesh Kumar K.V {
437918aadd47SBobi Jam 	if ((entry1->efd_tid == entry2->efd_tid) &&
438018aadd47SBobi Jam 	    (entry1->efd_group == entry2->efd_group) &&
438118aadd47SBobi Jam 	    ((entry1->efd_start_cluster + entry1->efd_count) == entry2->efd_start_cluster))
4382c894058dSAneesh Kumar K.V 		return 1;
4383c894058dSAneesh Kumar K.V 	return 0;
4384c894058dSAneesh Kumar K.V }
4385c894058dSAneesh Kumar K.V 
43864ddfef7bSEric Sandeen static noinline_for_stack int
43874ddfef7bSEric Sandeen ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
43887a2fcbf7SAneesh Kumar K.V 		      struct ext4_free_data *new_entry)
4389c9de560dSAlex Tomas {
4390e29136f8STheodore Ts'o 	ext4_group_t group = e4b->bd_group;
439184130193STheodore Ts'o 	ext4_grpblk_t cluster;
43927a2fcbf7SAneesh Kumar K.V 	struct ext4_free_data *entry;
4393c9de560dSAlex Tomas 	struct ext4_group_info *db = e4b->bd_info;
4394c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
4395c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
4396c894058dSAneesh Kumar K.V 	struct rb_node **n = &db->bb_free_root.rb_node, *node;
4397c894058dSAneesh Kumar K.V 	struct rb_node *parent = NULL, *new_node;
4398c894058dSAneesh Kumar K.V 
43990390131bSFrank Mayhar 	BUG_ON(!ext4_handle_valid(handle));
4400c9de560dSAlex Tomas 	BUG_ON(e4b->bd_bitmap_page == NULL);
4401c9de560dSAlex Tomas 	BUG_ON(e4b->bd_buddy_page == NULL);
4402c9de560dSAlex Tomas 
440318aadd47SBobi Jam 	new_node = &new_entry->efd_node;
440418aadd47SBobi Jam 	cluster = new_entry->efd_start_cluster;
4405c9de560dSAlex Tomas 
4406c894058dSAneesh Kumar K.V 	if (!*n) {
4407c894058dSAneesh Kumar K.V 		/* first free block exent. We need to
4408c894058dSAneesh Kumar K.V 		   protect buddy cache from being freed,
4409c9de560dSAlex Tomas 		 * otherwise we'll refresh it from
4410c9de560dSAlex Tomas 		 * on-disk bitmap and lose not-yet-available
4411c9de560dSAlex Tomas 		 * blocks */
4412c9de560dSAlex Tomas 		page_cache_get(e4b->bd_buddy_page);
4413c9de560dSAlex Tomas 		page_cache_get(e4b->bd_bitmap_page);
4414c894058dSAneesh Kumar K.V 	}
4415c894058dSAneesh Kumar K.V 	while (*n) {
4416c894058dSAneesh Kumar K.V 		parent = *n;
441718aadd47SBobi Jam 		entry = rb_entry(parent, struct ext4_free_data, efd_node);
441818aadd47SBobi Jam 		if (cluster < entry->efd_start_cluster)
4419c894058dSAneesh Kumar K.V 			n = &(*n)->rb_left;
442018aadd47SBobi Jam 		else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
4421c894058dSAneesh Kumar K.V 			n = &(*n)->rb_right;
4422c894058dSAneesh Kumar K.V 		else {
4423e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, group, 0,
442484130193STheodore Ts'o 				ext4_group_first_block_no(sb, group) +
442584130193STheodore Ts'o 				EXT4_C2B(sbi, cluster),
4426e29136f8STheodore Ts'o 				"Block already on to-be-freed list");
4427c894058dSAneesh Kumar K.V 			return 0;
4428c9de560dSAlex Tomas 		}
4429c9de560dSAlex Tomas 	}
4430c9de560dSAlex Tomas 
4431c894058dSAneesh Kumar K.V 	rb_link_node(new_node, parent, n);
4432c894058dSAneesh Kumar K.V 	rb_insert_color(new_node, &db->bb_free_root);
4433c894058dSAneesh Kumar K.V 
4434c894058dSAneesh Kumar K.V 	/* Now try to see the extent can be merged to left and right */
4435c894058dSAneesh Kumar K.V 	node = rb_prev(new_node);
4436c894058dSAneesh Kumar K.V 	if (node) {
443718aadd47SBobi Jam 		entry = rb_entry(node, struct ext4_free_data, efd_node);
4438c894058dSAneesh Kumar K.V 		if (can_merge(entry, new_entry)) {
443918aadd47SBobi Jam 			new_entry->efd_start_cluster = entry->efd_start_cluster;
444018aadd47SBobi Jam 			new_entry->efd_count += entry->efd_count;
4441c894058dSAneesh Kumar K.V 			rb_erase(node, &(db->bb_free_root));
444218aadd47SBobi Jam 			ext4_journal_callback_del(handle, &entry->efd_jce);
444318aadd47SBobi Jam 			kmem_cache_free(ext4_free_data_cachep, entry);
4444c9de560dSAlex Tomas 		}
4445c9de560dSAlex Tomas 	}
4446c894058dSAneesh Kumar K.V 
4447c894058dSAneesh Kumar K.V 	node = rb_next(new_node);
4448c894058dSAneesh Kumar K.V 	if (node) {
444918aadd47SBobi Jam 		entry = rb_entry(node, struct ext4_free_data, efd_node);
4450c894058dSAneesh Kumar K.V 		if (can_merge(new_entry, entry)) {
445118aadd47SBobi Jam 			new_entry->efd_count += entry->efd_count;
4452c894058dSAneesh Kumar K.V 			rb_erase(node, &(db->bb_free_root));
445318aadd47SBobi Jam 			ext4_journal_callback_del(handle, &entry->efd_jce);
445418aadd47SBobi Jam 			kmem_cache_free(ext4_free_data_cachep, entry);
4455c894058dSAneesh Kumar K.V 		}
4456c894058dSAneesh Kumar K.V 	}
44573e624fc7STheodore Ts'o 	/* Add the extent to transaction's private list */
445818aadd47SBobi Jam 	ext4_journal_callback_add(handle, ext4_free_data_callback,
445918aadd47SBobi Jam 				  &new_entry->efd_jce);
4460c9de560dSAlex Tomas 	return 0;
4461c9de560dSAlex Tomas }
4462c9de560dSAlex Tomas 
446344338711STheodore Ts'o /**
446444338711STheodore Ts'o  * ext4_free_blocks() -- Free given blocks and update quota
446544338711STheodore Ts'o  * @handle:		handle for this transaction
446644338711STheodore Ts'o  * @inode:		inode
446744338711STheodore Ts'o  * @block:		start physical block to free
446844338711STheodore Ts'o  * @count:		number of blocks to count
44695def1360SYongqiang Yang  * @flags:		flags used by ext4_free_blocks
4470c9de560dSAlex Tomas  */
447144338711STheodore Ts'o void ext4_free_blocks(handle_t *handle, struct inode *inode,
4472e6362609STheodore Ts'o 		      struct buffer_head *bh, ext4_fsblk_t block,
4473e6362609STheodore Ts'o 		      unsigned long count, int flags)
4474c9de560dSAlex Tomas {
447526346ff6SAneesh Kumar K.V 	struct buffer_head *bitmap_bh = NULL;
4476c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
4477c9de560dSAlex Tomas 	struct ext4_group_desc *gdp;
447844338711STheodore Ts'o 	unsigned long freed = 0;
4479498e5f24STheodore Ts'o 	unsigned int overflow;
4480c9de560dSAlex Tomas 	ext4_grpblk_t bit;
4481c9de560dSAlex Tomas 	struct buffer_head *gd_bh;
4482c9de560dSAlex Tomas 	ext4_group_t block_group;
4483c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
4484c9de560dSAlex Tomas 	struct ext4_buddy e4b;
448584130193STheodore Ts'o 	unsigned int count_clusters;
4486c9de560dSAlex Tomas 	int err = 0;
4487c9de560dSAlex Tomas 	int ret;
4488c9de560dSAlex Tomas 
4489e6362609STheodore Ts'o 	if (bh) {
4490e6362609STheodore Ts'o 		if (block)
4491e6362609STheodore Ts'o 			BUG_ON(block != bh->b_blocknr);
4492e6362609STheodore Ts'o 		else
4493e6362609STheodore Ts'o 			block = bh->b_blocknr;
4494e6362609STheodore Ts'o 	}
4495c9de560dSAlex Tomas 
4496c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
44971f2acb60STheodore Ts'o 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
44981f2acb60STheodore Ts'o 	    !ext4_data_block_valid(sbi, block, count)) {
449912062dddSEric Sandeen 		ext4_error(sb, "Freeing blocks not in datazone - "
45000610b6e9STheodore Ts'o 			   "block = %llu, count = %lu", block, count);
4501c9de560dSAlex Tomas 		goto error_return;
4502c9de560dSAlex Tomas 	}
4503c9de560dSAlex Tomas 
45040610b6e9STheodore Ts'o 	ext4_debug("freeing block %llu\n", block);
4505e6362609STheodore Ts'o 	trace_ext4_free_blocks(inode, block, count, flags);
4506e6362609STheodore Ts'o 
4507e6362609STheodore Ts'o 	if (flags & EXT4_FREE_BLOCKS_FORGET) {
4508e6362609STheodore Ts'o 		struct buffer_head *tbh = bh;
4509e6362609STheodore Ts'o 		int i;
4510e6362609STheodore Ts'o 
4511e6362609STheodore Ts'o 		BUG_ON(bh && (count > 1));
4512e6362609STheodore Ts'o 
4513e6362609STheodore Ts'o 		for (i = 0; i < count; i++) {
4514e6362609STheodore Ts'o 			if (!bh)
4515e6362609STheodore Ts'o 				tbh = sb_find_get_block(inode->i_sb,
4516e6362609STheodore Ts'o 							block + i);
451787783690SNamhyung Kim 			if (unlikely(!tbh))
451887783690SNamhyung Kim 				continue;
4519e6362609STheodore Ts'o 			ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4520e6362609STheodore Ts'o 				    inode, tbh, block + i);
4521e6362609STheodore Ts'o 		}
4522e6362609STheodore Ts'o 	}
4523e6362609STheodore Ts'o 
4524e6362609STheodore Ts'o 	/*
4525e6362609STheodore Ts'o 	 * We need to make sure we don't reuse the freed block until
4526e6362609STheodore Ts'o 	 * after the transaction is committed, which we can do by
4527e6362609STheodore Ts'o 	 * treating the block as metadata, below.  We make an
4528e6362609STheodore Ts'o 	 * exception if the inode is to be written in writeback mode
4529e6362609STheodore Ts'o 	 * since writeback mode has weak data consistency guarantees.
4530e6362609STheodore Ts'o 	 */
4531e6362609STheodore Ts'o 	if (!ext4_should_writeback_data(inode))
4532e6362609STheodore Ts'o 		flags |= EXT4_FREE_BLOCKS_METADATA;
4533c9de560dSAlex Tomas 
453484130193STheodore Ts'o 	/*
453584130193STheodore Ts'o 	 * If the extent to be freed does not begin on a cluster
453684130193STheodore Ts'o 	 * boundary, we need to deal with partial clusters at the
453784130193STheodore Ts'o 	 * beginning and end of the extent.  Normally we will free
453884130193STheodore Ts'o 	 * blocks at the beginning or the end unless we are explicitly
453984130193STheodore Ts'o 	 * requested to avoid doing so.
454084130193STheodore Ts'o 	 */
454184130193STheodore Ts'o 	overflow = block & (sbi->s_cluster_ratio - 1);
454284130193STheodore Ts'o 	if (overflow) {
454384130193STheodore Ts'o 		if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
454484130193STheodore Ts'o 			overflow = sbi->s_cluster_ratio - overflow;
454584130193STheodore Ts'o 			block += overflow;
454684130193STheodore Ts'o 			if (count > overflow)
454784130193STheodore Ts'o 				count -= overflow;
454884130193STheodore Ts'o 			else
454984130193STheodore Ts'o 				return;
455084130193STheodore Ts'o 		} else {
455184130193STheodore Ts'o 			block -= overflow;
455284130193STheodore Ts'o 			count += overflow;
455384130193STheodore Ts'o 		}
455484130193STheodore Ts'o 	}
455584130193STheodore Ts'o 	overflow = count & (sbi->s_cluster_ratio - 1);
455684130193STheodore Ts'o 	if (overflow) {
455784130193STheodore Ts'o 		if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
455884130193STheodore Ts'o 			if (count > overflow)
455984130193STheodore Ts'o 				count -= overflow;
456084130193STheodore Ts'o 			else
456184130193STheodore Ts'o 				return;
456284130193STheodore Ts'o 		} else
456384130193STheodore Ts'o 			count += sbi->s_cluster_ratio - overflow;
456484130193STheodore Ts'o 	}
456584130193STheodore Ts'o 
4566c9de560dSAlex Tomas do_more:
4567c9de560dSAlex Tomas 	overflow = 0;
4568c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4569c9de560dSAlex Tomas 
4570c9de560dSAlex Tomas 	/*
4571c9de560dSAlex Tomas 	 * Check to see if we are freeing blocks across a group
4572c9de560dSAlex Tomas 	 * boundary.
4573c9de560dSAlex Tomas 	 */
457484130193STheodore Ts'o 	if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
457584130193STheodore Ts'o 		overflow = EXT4_C2B(sbi, bit) + count -
457684130193STheodore Ts'o 			EXT4_BLOCKS_PER_GROUP(sb);
4577c9de560dSAlex Tomas 		count -= overflow;
4578c9de560dSAlex Tomas 	}
457984130193STheodore Ts'o 	count_clusters = EXT4_B2C(sbi, count);
4580574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4581ce89f46cSAneesh Kumar K.V 	if (!bitmap_bh) {
4582ce89f46cSAneesh Kumar K.V 		err = -EIO;
4583c9de560dSAlex Tomas 		goto error_return;
4584ce89f46cSAneesh Kumar K.V 	}
4585c9de560dSAlex Tomas 	gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4586ce89f46cSAneesh Kumar K.V 	if (!gdp) {
4587ce89f46cSAneesh Kumar K.V 		err = -EIO;
4588c9de560dSAlex Tomas 		goto error_return;
4589ce89f46cSAneesh Kumar K.V 	}
4590c9de560dSAlex Tomas 
4591c9de560dSAlex Tomas 	if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4592c9de560dSAlex Tomas 	    in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4593c9de560dSAlex Tomas 	    in_range(block, ext4_inode_table(sb, gdp),
4594c9de560dSAlex Tomas 		     EXT4_SB(sb)->s_itb_per_group) ||
4595c9de560dSAlex Tomas 	    in_range(block + count - 1, ext4_inode_table(sb, gdp),
4596c9de560dSAlex Tomas 		     EXT4_SB(sb)->s_itb_per_group)) {
4597c9de560dSAlex Tomas 
459812062dddSEric Sandeen 		ext4_error(sb, "Freeing blocks in system zone - "
45990610b6e9STheodore Ts'o 			   "Block = %llu, count = %lu", block, count);
4600519deca0SAneesh Kumar K.V 		/* err = 0. ext4_std_error should be a no op */
4601519deca0SAneesh Kumar K.V 		goto error_return;
4602c9de560dSAlex Tomas 	}
4603c9de560dSAlex Tomas 
4604c9de560dSAlex Tomas 	BUFFER_TRACE(bitmap_bh, "getting write access");
4605c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, bitmap_bh);
4606c9de560dSAlex Tomas 	if (err)
4607c9de560dSAlex Tomas 		goto error_return;
4608c9de560dSAlex Tomas 
4609c9de560dSAlex Tomas 	/*
4610c9de560dSAlex Tomas 	 * We are about to modify some metadata.  Call the journal APIs
4611c9de560dSAlex Tomas 	 * to unshare ->b_data if a currently-committing transaction is
4612c9de560dSAlex Tomas 	 * using it
4613c9de560dSAlex Tomas 	 */
4614c9de560dSAlex Tomas 	BUFFER_TRACE(gd_bh, "get_write_access");
4615c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, gd_bh);
4616c9de560dSAlex Tomas 	if (err)
4617c9de560dSAlex Tomas 		goto error_return;
4618c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
4619c9de560dSAlex Tomas 	{
4620c9de560dSAlex Tomas 		int i;
462184130193STheodore Ts'o 		for (i = 0; i < count_clusters; i++)
4622c9de560dSAlex Tomas 			BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4623c9de560dSAlex Tomas 	}
4624c9de560dSAlex Tomas #endif
462584130193STheodore Ts'o 	trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
4626c9de560dSAlex Tomas 
4627920313a7SAneesh Kumar K.V 	err = ext4_mb_load_buddy(sb, block_group, &e4b);
4628920313a7SAneesh Kumar K.V 	if (err)
4629920313a7SAneesh Kumar K.V 		goto error_return;
4630e6362609STheodore Ts'o 
4631e6362609STheodore Ts'o 	if ((flags & EXT4_FREE_BLOCKS_METADATA) && ext4_handle_valid(handle)) {
46327a2fcbf7SAneesh Kumar K.V 		struct ext4_free_data *new_entry;
46337a2fcbf7SAneesh Kumar K.V 		/*
46347a2fcbf7SAneesh Kumar K.V 		 * blocks being freed are metadata. these blocks shouldn't
46357a2fcbf7SAneesh Kumar K.V 		 * be used until this transaction is committed
46367a2fcbf7SAneesh Kumar K.V 		 */
463718aadd47SBobi Jam 		new_entry = kmem_cache_alloc(ext4_free_data_cachep, GFP_NOFS);
4638b72143abSTheodore Ts'o 		if (!new_entry) {
4639b72143abSTheodore Ts'o 			err = -ENOMEM;
4640b72143abSTheodore Ts'o 			goto error_return;
4641b72143abSTheodore Ts'o 		}
464218aadd47SBobi Jam 		new_entry->efd_start_cluster = bit;
464318aadd47SBobi Jam 		new_entry->efd_group = block_group;
464418aadd47SBobi Jam 		new_entry->efd_count = count_clusters;
464518aadd47SBobi Jam 		new_entry->efd_tid = handle->h_transaction->t_tid;
4646955ce5f5SAneesh Kumar K.V 
46477a2fcbf7SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
464884130193STheodore Ts'o 		mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
46497a2fcbf7SAneesh Kumar K.V 		ext4_mb_free_metadata(handle, &e4b, new_entry);
4650c9de560dSAlex Tomas 	} else {
46517a2fcbf7SAneesh Kumar K.V 		/* need to update group_info->bb_free and bitmap
46527a2fcbf7SAneesh Kumar K.V 		 * with group lock held. generate_buddy look at
46537a2fcbf7SAneesh Kumar K.V 		 * them with group lock_held
46547a2fcbf7SAneesh Kumar K.V 		 */
4655955ce5f5SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
465684130193STheodore Ts'o 		mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
465784130193STheodore Ts'o 		mb_free_blocks(inode, &e4b, bit, count_clusters);
4658c9de560dSAlex Tomas 	}
4659c9de560dSAlex Tomas 
4660021b65bbSTheodore Ts'o 	ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
4661021b65bbSTheodore Ts'o 	ext4_free_group_clusters_set(sb, gdp, ret);
4662c9de560dSAlex Tomas 	gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4663955ce5f5SAneesh Kumar K.V 	ext4_unlock_group(sb, block_group);
466457042651STheodore Ts'o 	percpu_counter_add(&sbi->s_freeclusters_counter, count_clusters);
4665c9de560dSAlex Tomas 
4666772cb7c8SJose R. Santos 	if (sbi->s_log_groups_per_flex) {
4667772cb7c8SJose R. Santos 		ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
466824aaa8efSTheodore Ts'o 		atomic_add(count_clusters,
466924aaa8efSTheodore Ts'o 			   &sbi->s_flex_groups[flex_group].free_clusters);
4670772cb7c8SJose R. Santos 	}
4671772cb7c8SJose R. Santos 
4672e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
4673c9de560dSAlex Tomas 
467444338711STheodore Ts'o 	freed += count;
4675c9de560dSAlex Tomas 
46767b415bf6SAditya Kali 	if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
46777b415bf6SAditya Kali 		dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
46787b415bf6SAditya Kali 
46797a2fcbf7SAneesh Kumar K.V 	/* We dirtied the bitmap block */
46807a2fcbf7SAneesh Kumar K.V 	BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
46817a2fcbf7SAneesh Kumar K.V 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
46827a2fcbf7SAneesh Kumar K.V 
4683c9de560dSAlex Tomas 	/* And the group descriptor block */
4684c9de560dSAlex Tomas 	BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
46850390131bSFrank Mayhar 	ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4686c9de560dSAlex Tomas 	if (!err)
4687c9de560dSAlex Tomas 		err = ret;
4688c9de560dSAlex Tomas 
4689c9de560dSAlex Tomas 	if (overflow && !err) {
4690c9de560dSAlex Tomas 		block += count;
4691c9de560dSAlex Tomas 		count = overflow;
4692c9de560dSAlex Tomas 		put_bh(bitmap_bh);
4693c9de560dSAlex Tomas 		goto do_more;
4694c9de560dSAlex Tomas 	}
4695a0375156STheodore Ts'o 	ext4_mark_super_dirty(sb);
4696c9de560dSAlex Tomas error_return:
4697c9de560dSAlex Tomas 	brelse(bitmap_bh);
4698c9de560dSAlex Tomas 	ext4_std_error(sb, err);
4699c9de560dSAlex Tomas 	return;
4700c9de560dSAlex Tomas }
47017360d173SLukas Czerner 
47027360d173SLukas Czerner /**
47030529155eSYongqiang Yang  * ext4_group_add_blocks() -- Add given blocks to an existing group
47042846e820SAmir Goldstein  * @handle:			handle to this transaction
47052846e820SAmir Goldstein  * @sb:				super block
47062846e820SAmir Goldstein  * @block:			start physcial block to add to the block group
47072846e820SAmir Goldstein  * @count:			number of blocks to free
47082846e820SAmir Goldstein  *
4709e73a347bSAmir Goldstein  * This marks the blocks as free in the bitmap and buddy.
47102846e820SAmir Goldstein  */
4711cc7365dfSYongqiang Yang int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
47122846e820SAmir Goldstein 			 ext4_fsblk_t block, unsigned long count)
47132846e820SAmir Goldstein {
47142846e820SAmir Goldstein 	struct buffer_head *bitmap_bh = NULL;
47152846e820SAmir Goldstein 	struct buffer_head *gd_bh;
47162846e820SAmir Goldstein 	ext4_group_t block_group;
47172846e820SAmir Goldstein 	ext4_grpblk_t bit;
47182846e820SAmir Goldstein 	unsigned int i;
47192846e820SAmir Goldstein 	struct ext4_group_desc *desc;
47202846e820SAmir Goldstein 	struct ext4_sb_info *sbi = EXT4_SB(sb);
4721e73a347bSAmir Goldstein 	struct ext4_buddy e4b;
47222846e820SAmir Goldstein 	int err = 0, ret, blk_free_count;
47232846e820SAmir Goldstein 	ext4_grpblk_t blocks_freed;
47242846e820SAmir Goldstein 
47252846e820SAmir Goldstein 	ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
47262846e820SAmir Goldstein 
47274740b830SYongqiang Yang 	if (count == 0)
47284740b830SYongqiang Yang 		return 0;
47294740b830SYongqiang Yang 
47302846e820SAmir Goldstein 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
47312846e820SAmir Goldstein 	/*
47322846e820SAmir Goldstein 	 * Check to see if we are freeing blocks across a group
47332846e820SAmir Goldstein 	 * boundary.
47342846e820SAmir Goldstein 	 */
4735cc7365dfSYongqiang Yang 	if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4736cc7365dfSYongqiang Yang 		ext4_warning(sb, "too much blocks added to group %u\n",
4737cc7365dfSYongqiang Yang 			     block_group);
4738cc7365dfSYongqiang Yang 		err = -EINVAL;
47392846e820SAmir Goldstein 		goto error_return;
4740cc7365dfSYongqiang Yang 	}
47412cd05cc3STheodore Ts'o 
47422846e820SAmir Goldstein 	bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4743cc7365dfSYongqiang Yang 	if (!bitmap_bh) {
4744cc7365dfSYongqiang Yang 		err = -EIO;
47452846e820SAmir Goldstein 		goto error_return;
4746cc7365dfSYongqiang Yang 	}
4747cc7365dfSYongqiang Yang 
47482846e820SAmir Goldstein 	desc = ext4_get_group_desc(sb, block_group, &gd_bh);
4749cc7365dfSYongqiang Yang 	if (!desc) {
4750cc7365dfSYongqiang Yang 		err = -EIO;
47512846e820SAmir Goldstein 		goto error_return;
4752cc7365dfSYongqiang Yang 	}
47532846e820SAmir Goldstein 
47542846e820SAmir Goldstein 	if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
47552846e820SAmir Goldstein 	    in_range(ext4_inode_bitmap(sb, desc), block, count) ||
47562846e820SAmir Goldstein 	    in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
47572846e820SAmir Goldstein 	    in_range(block + count - 1, ext4_inode_table(sb, desc),
47582846e820SAmir Goldstein 		     sbi->s_itb_per_group)) {
47592846e820SAmir Goldstein 		ext4_error(sb, "Adding blocks in system zones - "
47602846e820SAmir Goldstein 			   "Block = %llu, count = %lu",
47612846e820SAmir Goldstein 			   block, count);
4762cc7365dfSYongqiang Yang 		err = -EINVAL;
47632846e820SAmir Goldstein 		goto error_return;
47642846e820SAmir Goldstein 	}
47652846e820SAmir Goldstein 
47662cd05cc3STheodore Ts'o 	BUFFER_TRACE(bitmap_bh, "getting write access");
47672cd05cc3STheodore Ts'o 	err = ext4_journal_get_write_access(handle, bitmap_bh);
47682846e820SAmir Goldstein 	if (err)
47692846e820SAmir Goldstein 		goto error_return;
47702846e820SAmir Goldstein 
47712846e820SAmir Goldstein 	/*
47722846e820SAmir Goldstein 	 * We are about to modify some metadata.  Call the journal APIs
47732846e820SAmir Goldstein 	 * to unshare ->b_data if a currently-committing transaction is
47742846e820SAmir Goldstein 	 * using it
47752846e820SAmir Goldstein 	 */
47762846e820SAmir Goldstein 	BUFFER_TRACE(gd_bh, "get_write_access");
47772846e820SAmir Goldstein 	err = ext4_journal_get_write_access(handle, gd_bh);
47782846e820SAmir Goldstein 	if (err)
47792846e820SAmir Goldstein 		goto error_return;
4780e73a347bSAmir Goldstein 
47812846e820SAmir Goldstein 	for (i = 0, blocks_freed = 0; i < count; i++) {
47822846e820SAmir Goldstein 		BUFFER_TRACE(bitmap_bh, "clear bit");
4783e73a347bSAmir Goldstein 		if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
47842846e820SAmir Goldstein 			ext4_error(sb, "bit already cleared for block %llu",
47852846e820SAmir Goldstein 				   (ext4_fsblk_t)(block + i));
47862846e820SAmir Goldstein 			BUFFER_TRACE(bitmap_bh, "bit already cleared");
47872846e820SAmir Goldstein 		} else {
47882846e820SAmir Goldstein 			blocks_freed++;
47892846e820SAmir Goldstein 		}
47902846e820SAmir Goldstein 	}
4791e73a347bSAmir Goldstein 
4792e73a347bSAmir Goldstein 	err = ext4_mb_load_buddy(sb, block_group, &e4b);
4793e73a347bSAmir Goldstein 	if (err)
4794e73a347bSAmir Goldstein 		goto error_return;
4795e73a347bSAmir Goldstein 
4796e73a347bSAmir Goldstein 	/*
4797e73a347bSAmir Goldstein 	 * need to update group_info->bb_free and bitmap
4798e73a347bSAmir Goldstein 	 * with group lock held. generate_buddy look at
4799e73a347bSAmir Goldstein 	 * them with group lock_held
4800e73a347bSAmir Goldstein 	 */
48012846e820SAmir Goldstein 	ext4_lock_group(sb, block_group);
4802e73a347bSAmir Goldstein 	mb_clear_bits(bitmap_bh->b_data, bit, count);
4803e73a347bSAmir Goldstein 	mb_free_blocks(NULL, &e4b, bit, count);
4804021b65bbSTheodore Ts'o 	blk_free_count = blocks_freed + ext4_free_group_clusters(sb, desc);
4805021b65bbSTheodore Ts'o 	ext4_free_group_clusters_set(sb, desc, blk_free_count);
48062846e820SAmir Goldstein 	desc->bg_checksum = ext4_group_desc_csum(sbi, block_group, desc);
48072846e820SAmir Goldstein 	ext4_unlock_group(sb, block_group);
480857042651STheodore Ts'o 	percpu_counter_add(&sbi->s_freeclusters_counter,
480957042651STheodore Ts'o 			   EXT4_B2C(sbi, blocks_freed));
48102846e820SAmir Goldstein 
48112846e820SAmir Goldstein 	if (sbi->s_log_groups_per_flex) {
48122846e820SAmir Goldstein 		ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
481324aaa8efSTheodore Ts'o 		atomic_add(EXT4_B2C(sbi, blocks_freed),
481424aaa8efSTheodore Ts'o 			   &sbi->s_flex_groups[flex_group].free_clusters);
48152846e820SAmir Goldstein 	}
4816e73a347bSAmir Goldstein 
4817e73a347bSAmir Goldstein 	ext4_mb_unload_buddy(&e4b);
48182846e820SAmir Goldstein 
48192846e820SAmir Goldstein 	/* We dirtied the bitmap block */
48202846e820SAmir Goldstein 	BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
48212846e820SAmir Goldstein 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
48222846e820SAmir Goldstein 
48232846e820SAmir Goldstein 	/* And the group descriptor block */
48242846e820SAmir Goldstein 	BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
48252846e820SAmir Goldstein 	ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
48262846e820SAmir Goldstein 	if (!err)
48272846e820SAmir Goldstein 		err = ret;
48282846e820SAmir Goldstein 
48292846e820SAmir Goldstein error_return:
48302846e820SAmir Goldstein 	brelse(bitmap_bh);
48312846e820SAmir Goldstein 	ext4_std_error(sb, err);
4832cc7365dfSYongqiang Yang 	return err;
48332846e820SAmir Goldstein }
48342846e820SAmir Goldstein 
48352846e820SAmir Goldstein /**
48367360d173SLukas Czerner  * ext4_trim_extent -- function to TRIM one single free extent in the group
48377360d173SLukas Czerner  * @sb:		super block for the file system
48387360d173SLukas Czerner  * @start:	starting block of the free extent in the alloc. group
48397360d173SLukas Czerner  * @count:	number of blocks to TRIM
48407360d173SLukas Czerner  * @group:	alloc. group we are working with
48417360d173SLukas Czerner  * @e4b:	ext4 buddy for the group
48427360d173SLukas Czerner  *
48437360d173SLukas Czerner  * Trim "count" blocks starting at "start" in the "group". To assure that no
48447360d173SLukas Czerner  * one will allocate those blocks, mark it as used in buddy bitmap. This must
48457360d173SLukas Czerner  * be called with under the group lock.
48467360d173SLukas Czerner  */
4847d9f34504STheodore Ts'o static void ext4_trim_extent(struct super_block *sb, int start, int count,
48487360d173SLukas Czerner 			     ext4_group_t group, struct ext4_buddy *e4b)
48497360d173SLukas Czerner {
48507360d173SLukas Czerner 	struct ext4_free_extent ex;
48517360d173SLukas Czerner 
4852b3d4c2b1STao Ma 	trace_ext4_trim_extent(sb, group, start, count);
4853b3d4c2b1STao Ma 
48547360d173SLukas Czerner 	assert_spin_locked(ext4_group_lock_ptr(sb, group));
48557360d173SLukas Czerner 
48567360d173SLukas Czerner 	ex.fe_start = start;
48577360d173SLukas Czerner 	ex.fe_group = group;
48587360d173SLukas Czerner 	ex.fe_len = count;
48597360d173SLukas Czerner 
48607360d173SLukas Czerner 	/*
48617360d173SLukas Czerner 	 * Mark blocks used, so no one can reuse them while
48627360d173SLukas Czerner 	 * being trimmed.
48637360d173SLukas Czerner 	 */
48647360d173SLukas Czerner 	mb_mark_used(e4b, &ex);
48657360d173SLukas Czerner 	ext4_unlock_group(sb, group);
4866d9f34504STheodore Ts'o 	ext4_issue_discard(sb, group, start, count);
48677360d173SLukas Czerner 	ext4_lock_group(sb, group);
48687360d173SLukas Czerner 	mb_free_blocks(NULL, e4b, start, ex.fe_len);
48697360d173SLukas Czerner }
48707360d173SLukas Czerner 
48717360d173SLukas Czerner /**
48727360d173SLukas Czerner  * ext4_trim_all_free -- function to trim all free space in alloc. group
48737360d173SLukas Czerner  * @sb:			super block for file system
487422612283STao Ma  * @group:		group to be trimmed
48757360d173SLukas Czerner  * @start:		first group block to examine
48767360d173SLukas Czerner  * @max:		last group block to examine
48777360d173SLukas Czerner  * @minblocks:		minimum extent block count
48787360d173SLukas Czerner  *
48797360d173SLukas Czerner  * ext4_trim_all_free walks through group's buddy bitmap searching for free
48807360d173SLukas Czerner  * extents. When the free block is found, ext4_trim_extent is called to TRIM
48817360d173SLukas Czerner  * the extent.
48827360d173SLukas Czerner  *
48837360d173SLukas Czerner  *
48847360d173SLukas Czerner  * ext4_trim_all_free walks through group's block bitmap searching for free
48857360d173SLukas Czerner  * extents. When the free extent is found, mark it as used in group buddy
48867360d173SLukas Czerner  * bitmap. Then issue a TRIM command on this extent and free the extent in
48877360d173SLukas Czerner  * the group buddy bitmap. This is done until whole group is scanned.
48887360d173SLukas Czerner  */
48890b75a840SLukas Czerner static ext4_grpblk_t
489078944086SLukas Czerner ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
489178944086SLukas Czerner 		   ext4_grpblk_t start, ext4_grpblk_t max,
489278944086SLukas Czerner 		   ext4_grpblk_t minblocks)
48937360d173SLukas Czerner {
48947360d173SLukas Czerner 	void *bitmap;
4895169ddc3eSTao Ma 	ext4_grpblk_t next, count = 0, free_count = 0;
489678944086SLukas Czerner 	struct ext4_buddy e4b;
489778944086SLukas Czerner 	int ret;
48987360d173SLukas Czerner 
4899b3d4c2b1STao Ma 	trace_ext4_trim_all_free(sb, group, start, max);
4900b3d4c2b1STao Ma 
490178944086SLukas Czerner 	ret = ext4_mb_load_buddy(sb, group, &e4b);
490278944086SLukas Czerner 	if (ret) {
490378944086SLukas Czerner 		ext4_error(sb, "Error in loading buddy "
490478944086SLukas Czerner 				"information for %u", group);
490578944086SLukas Czerner 		return ret;
490678944086SLukas Czerner 	}
490778944086SLukas Czerner 	bitmap = e4b.bd_bitmap;
490828739eeaSLukas Czerner 
490928739eeaSLukas Czerner 	ext4_lock_group(sb, group);
49103d56b8d2STao Ma 	if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
49113d56b8d2STao Ma 	    minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
49123d56b8d2STao Ma 		goto out;
49133d56b8d2STao Ma 
491478944086SLukas Czerner 	start = (e4b.bd_info->bb_first_free > start) ?
491578944086SLukas Czerner 		e4b.bd_info->bb_first_free : start;
49167360d173SLukas Czerner 
4917913eed83SLukas Czerner 	while (start <= max) {
4918913eed83SLukas Czerner 		start = mb_find_next_zero_bit(bitmap, max + 1, start);
4919913eed83SLukas Czerner 		if (start > max)
49207360d173SLukas Czerner 			break;
4921913eed83SLukas Czerner 		next = mb_find_next_bit(bitmap, max + 1, start);
49227360d173SLukas Czerner 
49237360d173SLukas Czerner 		if ((next - start) >= minblocks) {
4924d9f34504STheodore Ts'o 			ext4_trim_extent(sb, start,
492578944086SLukas Czerner 					 next - start, group, &e4b);
49267360d173SLukas Czerner 			count += next - start;
49277360d173SLukas Czerner 		}
4928169ddc3eSTao Ma 		free_count += next - start;
49297360d173SLukas Czerner 		start = next + 1;
49307360d173SLukas Czerner 
49317360d173SLukas Czerner 		if (fatal_signal_pending(current)) {
49327360d173SLukas Czerner 			count = -ERESTARTSYS;
49337360d173SLukas Czerner 			break;
49347360d173SLukas Czerner 		}
49357360d173SLukas Czerner 
49367360d173SLukas Czerner 		if (need_resched()) {
49377360d173SLukas Czerner 			ext4_unlock_group(sb, group);
49387360d173SLukas Czerner 			cond_resched();
49397360d173SLukas Czerner 			ext4_lock_group(sb, group);
49407360d173SLukas Czerner 		}
49417360d173SLukas Czerner 
4942169ddc3eSTao Ma 		if ((e4b.bd_info->bb_free - free_count) < minblocks)
49437360d173SLukas Czerner 			break;
49447360d173SLukas Czerner 	}
49453d56b8d2STao Ma 
49463d56b8d2STao Ma 	if (!ret)
49473d56b8d2STao Ma 		EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
49483d56b8d2STao Ma out:
49497360d173SLukas Czerner 	ext4_unlock_group(sb, group);
495078944086SLukas Czerner 	ext4_mb_unload_buddy(&e4b);
49517360d173SLukas Czerner 
49527360d173SLukas Czerner 	ext4_debug("trimmed %d blocks in the group %d\n",
49537360d173SLukas Czerner 		count, group);
49547360d173SLukas Czerner 
49557360d173SLukas Czerner 	return count;
49567360d173SLukas Czerner }
49577360d173SLukas Czerner 
49587360d173SLukas Czerner /**
49597360d173SLukas Czerner  * ext4_trim_fs() -- trim ioctl handle function
49607360d173SLukas Czerner  * @sb:			superblock for filesystem
49617360d173SLukas Czerner  * @range:		fstrim_range structure
49627360d173SLukas Czerner  *
49637360d173SLukas Czerner  * start:	First Byte to trim
49647360d173SLukas Czerner  * len:		number of Bytes to trim from start
49657360d173SLukas Czerner  * minlen:	minimum extent length in Bytes
49667360d173SLukas Czerner  * ext4_trim_fs goes through all allocation groups containing Bytes from
49677360d173SLukas Czerner  * start to start+len. For each such a group ext4_trim_all_free function
49687360d173SLukas Czerner  * is invoked to trim all free space.
49697360d173SLukas Czerner  */
49707360d173SLukas Czerner int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
49717360d173SLukas Czerner {
497278944086SLukas Czerner 	struct ext4_group_info *grp;
4973913eed83SLukas Czerner 	ext4_group_t group, first_group, last_group;
49747137d7a4STheodore Ts'o 	ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
4975913eed83SLukas Czerner 	uint64_t start, end, minlen, trimmed = 0;
49760f0a25bfSJan Kara 	ext4_fsblk_t first_data_blk =
49770f0a25bfSJan Kara 			le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
4978913eed83SLukas Czerner 	ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
49797360d173SLukas Czerner 	int ret = 0;
49807360d173SLukas Czerner 
49817360d173SLukas Czerner 	start = range->start >> sb->s_blocksize_bits;
4982913eed83SLukas Czerner 	end = start + (range->len >> sb->s_blocksize_bits) - 1;
49837360d173SLukas Czerner 	minlen = range->minlen >> sb->s_blocksize_bits;
49847360d173SLukas Czerner 
4985913eed83SLukas Czerner 	if (unlikely(minlen > EXT4_CLUSTERS_PER_GROUP(sb)) ||
4986913eed83SLukas Czerner 	    unlikely(start >= max_blks))
49877360d173SLukas Czerner 		return -EINVAL;
4988913eed83SLukas Czerner 	if (end >= max_blks)
4989913eed83SLukas Czerner 		end = max_blks - 1;
4990913eed83SLukas Czerner 	if (end <= first_data_blk)
499122f10457STao Ma 		goto out;
4992913eed83SLukas Czerner 	if (start < first_data_blk)
49930f0a25bfSJan Kara 		start = first_data_blk;
49947360d173SLukas Czerner 
4995913eed83SLukas Czerner 	/* Determine first and last group to examine based on start and end */
49967360d173SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
49977137d7a4STheodore Ts'o 				     &first_group, &first_cluster);
4998913eed83SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
49997137d7a4STheodore Ts'o 				     &last_group, &last_cluster);
50007360d173SLukas Czerner 
5001913eed83SLukas Czerner 	/* end now represents the last cluster to discard in this group */
5002913eed83SLukas Czerner 	end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
50037360d173SLukas Czerner 
50047360d173SLukas Czerner 	for (group = first_group; group <= last_group; group++) {
500578944086SLukas Czerner 		grp = ext4_get_group_info(sb, group);
500678944086SLukas Czerner 		/* We only do this if the grp has never been initialized */
500778944086SLukas Czerner 		if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
500878944086SLukas Czerner 			ret = ext4_mb_init_group(sb, group);
500978944086SLukas Czerner 			if (ret)
50107360d173SLukas Czerner 				break;
50117360d173SLukas Czerner 		}
50127360d173SLukas Czerner 
50130ba08517STao Ma 		/*
5014913eed83SLukas Czerner 		 * For all the groups except the last one, last cluster will
5015913eed83SLukas Czerner 		 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
5016913eed83SLukas Czerner 		 * change it for the last group, note that last_cluster is
5017913eed83SLukas Czerner 		 * already computed earlier by ext4_get_group_no_and_offset()
50180ba08517STao Ma 		 */
5019913eed83SLukas Czerner 		if (group == last_group)
5020913eed83SLukas Czerner 			end = last_cluster;
50217360d173SLukas Czerner 
502278944086SLukas Czerner 		if (grp->bb_free >= minlen) {
50237137d7a4STheodore Ts'o 			cnt = ext4_trim_all_free(sb, group, first_cluster,
5024913eed83SLukas Czerner 						end, minlen);
50257360d173SLukas Czerner 			if (cnt < 0) {
50267360d173SLukas Czerner 				ret = cnt;
50277360d173SLukas Czerner 				break;
50287360d173SLukas Czerner 			}
50297360d173SLukas Czerner 			trimmed += cnt;
503021e7fd22SLukas Czerner 		}
5031913eed83SLukas Czerner 
5032913eed83SLukas Czerner 		/*
5033913eed83SLukas Czerner 		 * For every group except the first one, we are sure
5034913eed83SLukas Czerner 		 * that the first cluster to discard will be cluster #0.
5035913eed83SLukas Czerner 		 */
50367137d7a4STheodore Ts'o 		first_cluster = 0;
50377360d173SLukas Czerner 	}
50387360d173SLukas Czerner 	range->len = trimmed * sb->s_blocksize;
50397360d173SLukas Czerner 
50403d56b8d2STao Ma 	if (!ret)
50413d56b8d2STao Ma 		atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
50423d56b8d2STao Ma 
504322f10457STao Ma out:
50447360d173SLukas Czerner 	return ret;
50457360d173SLukas Czerner }
5046