xref: /openbmc/linux/fs/ext4/mballoc.c (revision 26626f11)
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 
248f6e39a7SMingming Cao #include "mballoc.h"
256ba495e9STheodore Ts'o #include <linux/debugfs.h>
265a0e3ad6STejun Heo #include <linux/slab.h>
279bffad1eSTheodore Ts'o #include <trace/events/ext4.h>
289bffad1eSTheodore Ts'o 
29c9de560dSAlex Tomas /*
30c9de560dSAlex Tomas  * MUSTDO:
31c9de560dSAlex Tomas  *   - test ext4_ext_search_left() and ext4_ext_search_right()
32c9de560dSAlex Tomas  *   - search for metadata in few groups
33c9de560dSAlex Tomas  *
34c9de560dSAlex Tomas  * TODO v4:
35c9de560dSAlex Tomas  *   - normalization should take into account whether file is still open
36c9de560dSAlex Tomas  *   - discard preallocations if no free space left (policy?)
37c9de560dSAlex Tomas  *   - don't normalize tails
38c9de560dSAlex Tomas  *   - quota
39c9de560dSAlex Tomas  *   - reservation for superuser
40c9de560dSAlex Tomas  *
41c9de560dSAlex Tomas  * TODO v3:
42c9de560dSAlex Tomas  *   - bitmap read-ahead (proposed by Oleg Drokin aka green)
43c9de560dSAlex Tomas  *   - track min/max extents in each group for better group selection
44c9de560dSAlex Tomas  *   - mb_mark_used() may allocate chunk right after splitting buddy
45c9de560dSAlex Tomas  *   - tree of groups sorted by number of free blocks
46c9de560dSAlex Tomas  *   - error handling
47c9de560dSAlex Tomas  */
48c9de560dSAlex Tomas 
49c9de560dSAlex Tomas /*
50c9de560dSAlex Tomas  * The allocation request involve request for multiple number of blocks
51c9de560dSAlex Tomas  * near to the goal(block) value specified.
52c9de560dSAlex Tomas  *
53b713a5ecSTheodore Ts'o  * During initialization phase of the allocator we decide to use the
54b713a5ecSTheodore Ts'o  * group preallocation or inode preallocation depending on the size of
55b713a5ecSTheodore Ts'o  * the file. The size of the file could be the resulting file size we
56b713a5ecSTheodore Ts'o  * would have after allocation, or the current file size, which ever
57b713a5ecSTheodore Ts'o  * is larger. If the size is less than sbi->s_mb_stream_request we
58b713a5ecSTheodore Ts'o  * select to use the group preallocation. The default value of
59b713a5ecSTheodore Ts'o  * s_mb_stream_request is 16 blocks. This can also be tuned via
60b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
61b713a5ecSTheodore Ts'o  * terms of number of blocks.
62c9de560dSAlex Tomas  *
63c9de560dSAlex Tomas  * The main motivation for having small file use group preallocation is to
64b713a5ecSTheodore Ts'o  * ensure that we have small files closer together on the disk.
65c9de560dSAlex Tomas  *
66b713a5ecSTheodore Ts'o  * First stage the allocator looks at the inode prealloc list,
67b713a5ecSTheodore Ts'o  * ext4_inode_info->i_prealloc_list, which contains list of prealloc
68b713a5ecSTheodore Ts'o  * spaces for this particular inode. The inode prealloc space is
69b713a5ecSTheodore Ts'o  * represented as:
70c9de560dSAlex Tomas  *
71c9de560dSAlex Tomas  * pa_lstart -> the logical start block for this prealloc space
72c9de560dSAlex Tomas  * pa_pstart -> the physical start block for this prealloc space
731537a363SDaniel Mack  * pa_len    -> length for this prealloc space
74c9de560dSAlex Tomas  * pa_free   ->  free space available in this prealloc space
75c9de560dSAlex Tomas  *
76c9de560dSAlex Tomas  * The inode preallocation space is used looking at the _logical_ start
77c9de560dSAlex Tomas  * block. If only the logical file block falls within the range of prealloc
78c9de560dSAlex Tomas  * space we will consume the particular prealloc space. This make sure that
79c9de560dSAlex Tomas  * that the we have contiguous physical blocks representing the file blocks
80c9de560dSAlex Tomas  *
81c9de560dSAlex Tomas  * The important thing to be noted in case of inode prealloc space is that
82c9de560dSAlex Tomas  * we don't modify the values associated to inode prealloc space except
83c9de560dSAlex Tomas  * pa_free.
84c9de560dSAlex Tomas  *
85c9de560dSAlex Tomas  * If we are not able to find blocks in the inode prealloc space and if we
86c9de560dSAlex Tomas  * have the group allocation flag set then we look at the locality group
87c9de560dSAlex Tomas  * prealloc space. These are per CPU prealloc list repreasented as
88c9de560dSAlex Tomas  *
89c9de560dSAlex Tomas  * ext4_sb_info.s_locality_groups[smp_processor_id()]
90c9de560dSAlex Tomas  *
91c9de560dSAlex Tomas  * The reason for having a per cpu locality group is to reduce the contention
92c9de560dSAlex Tomas  * between CPUs. It is possible to get scheduled at this point.
93c9de560dSAlex Tomas  *
94c9de560dSAlex Tomas  * The locality group prealloc space is used looking at whether we have
9525985edcSLucas De Marchi  * enough free space (pa_free) within the prealloc space.
96c9de560dSAlex Tomas  *
97c9de560dSAlex Tomas  * If we can't allocate blocks via inode prealloc or/and locality group
98c9de560dSAlex Tomas  * prealloc then we look at the buddy cache. The buddy cache is represented
99c9de560dSAlex Tomas  * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
100c9de560dSAlex Tomas  * mapped to the buddy and bitmap information regarding different
101c9de560dSAlex Tomas  * groups. The buddy information is attached to buddy cache inode so that
102c9de560dSAlex Tomas  * we can access them through the page cache. The information regarding
103c9de560dSAlex Tomas  * each group is loaded via ext4_mb_load_buddy.  The information involve
104c9de560dSAlex Tomas  * block bitmap and buddy information. The information are stored in the
105c9de560dSAlex Tomas  * inode as:
106c9de560dSAlex Tomas  *
107c9de560dSAlex Tomas  *  {                        page                        }
108c3a326a6SAneesh Kumar K.V  *  [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
109c9de560dSAlex Tomas  *
110c9de560dSAlex Tomas  *
111c9de560dSAlex Tomas  * one block each for bitmap and buddy information.  So for each group we
112c9de560dSAlex Tomas  * take up 2 blocks. A page can contain blocks_per_page (PAGE_CACHE_SIZE /
113c9de560dSAlex Tomas  * blocksize) blocks.  So it can have information regarding groups_per_page
114c9de560dSAlex Tomas  * which is blocks_per_page/2
115c9de560dSAlex Tomas  *
116c9de560dSAlex Tomas  * The buddy cache inode is not stored on disk. The inode is thrown
117c9de560dSAlex Tomas  * away when the filesystem is unmounted.
118c9de560dSAlex Tomas  *
119c9de560dSAlex Tomas  * We look for count number of blocks in the buddy cache. If we were able
120c9de560dSAlex Tomas  * to locate that many free blocks we return with additional information
121c9de560dSAlex Tomas  * regarding rest of the contiguous physical block available
122c9de560dSAlex Tomas  *
123c9de560dSAlex Tomas  * Before allocating blocks via buddy cache we normalize the request
124c9de560dSAlex Tomas  * blocks. This ensure we ask for more blocks that we needed. The extra
125c9de560dSAlex Tomas  * blocks that we get after allocation is added to the respective prealloc
126c9de560dSAlex Tomas  * list. In case of inode preallocation we follow a list of heuristics
127c9de560dSAlex Tomas  * based on file size. This can be found in ext4_mb_normalize_request. If
128c9de560dSAlex Tomas  * we are doing a group prealloc we try to normalize the request to
129b713a5ecSTheodore Ts'o  * sbi->s_mb_group_prealloc. Default value of s_mb_group_prealloc is
130c9de560dSAlex Tomas  * 512 blocks. This can be tuned via
131b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition/mb_group_prealloc. The value is represented in
132c9de560dSAlex Tomas  * terms of number of blocks. If we have mounted the file system with -O
133c9de560dSAlex Tomas  * stripe=<value> option the group prealloc request is normalized to the
134c9de560dSAlex Tomas  * stripe value (sbi->s_stripe)
135c9de560dSAlex Tomas  *
136b713a5ecSTheodore Ts'o  * The regular allocator(using the buddy cache) supports few tunables.
137c9de560dSAlex Tomas  *
138b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_min_to_scan
139b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_max_to_scan
140b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_order2_req
141c9de560dSAlex Tomas  *
142b713a5ecSTheodore Ts'o  * The regular allocator uses buddy scan only if the request len is power of
143c9de560dSAlex Tomas  * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
144c9de560dSAlex Tomas  * value of s_mb_order2_reqs can be tuned via
145b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_order2_req.  If the request len is equal to
146af901ca1SAndré Goddard Rosa  * stripe size (sbi->s_stripe), we try to search for contiguous block in
147b713a5ecSTheodore Ts'o  * stripe size. This should result in better allocation on RAID setups. If
148b713a5ecSTheodore Ts'o  * not, we search in the specific group using bitmap for best extents. The
149b713a5ecSTheodore Ts'o  * tunable min_to_scan and max_to_scan control the behaviour here.
150c9de560dSAlex Tomas  * min_to_scan indicate how long the mballoc __must__ look for a best
151b713a5ecSTheodore Ts'o  * extent and max_to_scan indicates how long the mballoc __can__ look for a
152c9de560dSAlex Tomas  * best extent in the found extents. Searching for the blocks starts with
153c9de560dSAlex Tomas  * the group specified as the goal value in allocation context via
154c9de560dSAlex Tomas  * ac_g_ex. Each group is first checked based on the criteria whether it
155c9de560dSAlex Tomas  * can used for allocation. ext4_mb_good_group explains how the groups are
156c9de560dSAlex Tomas  * checked.
157c9de560dSAlex Tomas  *
158c9de560dSAlex Tomas  * Both the prealloc space are getting populated as above. So for the first
159c9de560dSAlex Tomas  * request we will hit the buddy cache which will result in this prealloc
160c9de560dSAlex Tomas  * space getting filled. The prealloc space is then later used for the
161c9de560dSAlex Tomas  * subsequent request.
162c9de560dSAlex Tomas  */
163c9de560dSAlex Tomas 
164c9de560dSAlex Tomas /*
165c9de560dSAlex Tomas  * mballoc operates on the following data:
166c9de560dSAlex Tomas  *  - on-disk bitmap
167c9de560dSAlex Tomas  *  - in-core buddy (actually includes buddy and bitmap)
168c9de560dSAlex Tomas  *  - preallocation descriptors (PAs)
169c9de560dSAlex Tomas  *
170c9de560dSAlex Tomas  * there are two types of preallocations:
171c9de560dSAlex Tomas  *  - inode
172c9de560dSAlex Tomas  *    assiged to specific inode and can be used for this inode only.
173c9de560dSAlex Tomas  *    it describes part of inode's space preallocated to specific
174c9de560dSAlex Tomas  *    physical blocks. any block from that preallocated can be used
175c9de560dSAlex Tomas  *    independent. the descriptor just tracks number of blocks left
176c9de560dSAlex Tomas  *    unused. so, before taking some block from descriptor, one must
177c9de560dSAlex Tomas  *    make sure corresponded logical block isn't allocated yet. this
178c9de560dSAlex Tomas  *    also means that freeing any block within descriptor's range
179c9de560dSAlex Tomas  *    must discard all preallocated blocks.
180c9de560dSAlex Tomas  *  - locality group
181c9de560dSAlex Tomas  *    assigned to specific locality group which does not translate to
182c9de560dSAlex Tomas  *    permanent set of inodes: inode can join and leave group. space
183c9de560dSAlex Tomas  *    from this type of preallocation can be used for any inode. thus
184c9de560dSAlex Tomas  *    it's consumed from the beginning to the end.
185c9de560dSAlex Tomas  *
186c9de560dSAlex Tomas  * relation between them can be expressed as:
187c9de560dSAlex Tomas  *    in-core buddy = on-disk bitmap + preallocation descriptors
188c9de560dSAlex Tomas  *
189c9de560dSAlex Tomas  * this mean blocks mballoc considers used are:
190c9de560dSAlex Tomas  *  - allocated blocks (persistent)
191c9de560dSAlex Tomas  *  - preallocated blocks (non-persistent)
192c9de560dSAlex Tomas  *
193c9de560dSAlex Tomas  * consistency in mballoc world means that at any time a block is either
194c9de560dSAlex Tomas  * free or used in ALL structures. notice: "any time" should not be read
195c9de560dSAlex Tomas  * literally -- time is discrete and delimited by locks.
196c9de560dSAlex Tomas  *
197c9de560dSAlex Tomas  *  to keep it simple, we don't use block numbers, instead we count number of
198c9de560dSAlex Tomas  *  blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
199c9de560dSAlex Tomas  *
200c9de560dSAlex Tomas  * all operations can be expressed as:
201c9de560dSAlex Tomas  *  - init buddy:			buddy = on-disk + PAs
202c9de560dSAlex Tomas  *  - new PA:				buddy += N; PA = N
203c9de560dSAlex Tomas  *  - use inode PA:			on-disk += N; PA -= N
204c9de560dSAlex Tomas  *  - discard inode PA			buddy -= on-disk - PA; PA = 0
205c9de560dSAlex Tomas  *  - use locality group PA		on-disk += N; PA -= N
206c9de560dSAlex Tomas  *  - discard locality group PA		buddy -= PA; PA = 0
207c9de560dSAlex Tomas  *  note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
208c9de560dSAlex Tomas  *        is used in real operation because we can't know actual used
209c9de560dSAlex Tomas  *        bits from PA, only from on-disk bitmap
210c9de560dSAlex Tomas  *
211c9de560dSAlex Tomas  * if we follow this strict logic, then all operations above should be atomic.
212c9de560dSAlex Tomas  * given some of them can block, we'd have to use something like semaphores
213c9de560dSAlex Tomas  * killing performance on high-end SMP hardware. let's try to relax it using
214c9de560dSAlex Tomas  * the following knowledge:
215c9de560dSAlex Tomas  *  1) if buddy is referenced, it's already initialized
216c9de560dSAlex Tomas  *  2) while block is used in buddy and the buddy is referenced,
217c9de560dSAlex Tomas  *     nobody can re-allocate that block
218c9de560dSAlex Tomas  *  3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
219c9de560dSAlex Tomas  *     bit set and PA claims same block, it's OK. IOW, one can set bit in
220c9de560dSAlex Tomas  *     on-disk bitmap if buddy has same bit set or/and PA covers corresponded
221c9de560dSAlex Tomas  *     block
222c9de560dSAlex Tomas  *
223c9de560dSAlex Tomas  * so, now we're building a concurrency table:
224c9de560dSAlex Tomas  *  - init buddy vs.
225c9de560dSAlex Tomas  *    - new PA
226c9de560dSAlex Tomas  *      blocks for PA are allocated in the buddy, buddy must be referenced
227c9de560dSAlex Tomas  *      until PA is linked to allocation group to avoid concurrent buddy init
228c9de560dSAlex Tomas  *    - use inode PA
229c9de560dSAlex Tomas  *      we need to make sure that either on-disk bitmap or PA has uptodate data
230c9de560dSAlex Tomas  *      given (3) we care that PA-=N operation doesn't interfere with init
231c9de560dSAlex Tomas  *    - discard inode PA
232c9de560dSAlex Tomas  *      the simplest way would be to have buddy initialized by the discard
233c9de560dSAlex Tomas  *    - use locality group PA
234c9de560dSAlex Tomas  *      again PA-=N must be serialized with init
235c9de560dSAlex Tomas  *    - discard locality group PA
236c9de560dSAlex Tomas  *      the simplest way would be to have buddy initialized by the discard
237c9de560dSAlex Tomas  *  - new PA vs.
238c9de560dSAlex Tomas  *    - use inode PA
239c9de560dSAlex Tomas  *      i_data_sem serializes them
240c9de560dSAlex Tomas  *    - discard inode PA
241c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
242c9de560dSAlex Tomas  *    - use locality group PA
243c9de560dSAlex Tomas  *      some mutex should serialize them
244c9de560dSAlex Tomas  *    - discard locality group PA
245c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
246c9de560dSAlex Tomas  *  - use inode PA
247c9de560dSAlex Tomas  *    - use inode PA
248c9de560dSAlex Tomas  *      i_data_sem or another mutex should serializes them
249c9de560dSAlex Tomas  *    - discard inode PA
250c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
251c9de560dSAlex Tomas  *    - use locality group PA
252c9de560dSAlex Tomas  *      nothing wrong here -- they're different PAs covering different blocks
253c9de560dSAlex Tomas  *    - discard locality group PA
254c9de560dSAlex Tomas  *      discard process must wait until PA isn't used by another process
255c9de560dSAlex Tomas  *
256c9de560dSAlex Tomas  * now we're ready to make few consequences:
257c9de560dSAlex Tomas  *  - PA is referenced and while it is no discard is possible
258c9de560dSAlex Tomas  *  - PA is referenced until block isn't marked in on-disk bitmap
259c9de560dSAlex Tomas  *  - PA changes only after on-disk bitmap
260c9de560dSAlex Tomas  *  - discard must not compete with init. either init is done before
261c9de560dSAlex Tomas  *    any discard or they're serialized somehow
262c9de560dSAlex Tomas  *  - buddy init as sum of on-disk bitmap and PAs is done atomically
263c9de560dSAlex Tomas  *
264c9de560dSAlex Tomas  * a special case when we've used PA to emptiness. no need to modify buddy
265c9de560dSAlex Tomas  * in this case, but we should care about concurrent init
266c9de560dSAlex Tomas  *
267c9de560dSAlex Tomas  */
268c9de560dSAlex Tomas 
269c9de560dSAlex Tomas  /*
270c9de560dSAlex Tomas  * Logic in few words:
271c9de560dSAlex Tomas  *
272c9de560dSAlex Tomas  *  - allocation:
273c9de560dSAlex Tomas  *    load group
274c9de560dSAlex Tomas  *    find blocks
275c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
276c9de560dSAlex Tomas  *    release group
277c9de560dSAlex Tomas  *
278c9de560dSAlex Tomas  *  - use preallocation:
279c9de560dSAlex Tomas  *    find proper PA (per-inode or group)
280c9de560dSAlex Tomas  *    load group
281c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
282c9de560dSAlex Tomas  *    release group
283c9de560dSAlex Tomas  *    release PA
284c9de560dSAlex Tomas  *
285c9de560dSAlex Tomas  *  - free:
286c9de560dSAlex Tomas  *    load group
287c9de560dSAlex Tomas  *    mark bits in on-disk bitmap
288c9de560dSAlex Tomas  *    release group
289c9de560dSAlex Tomas  *
290c9de560dSAlex Tomas  *  - discard preallocations in group:
291c9de560dSAlex Tomas  *    mark PAs deleted
292c9de560dSAlex Tomas  *    move them onto local list
293c9de560dSAlex Tomas  *    load on-disk bitmap
294c9de560dSAlex Tomas  *    load group
295c9de560dSAlex Tomas  *    remove PA from object (inode or locality group)
296c9de560dSAlex Tomas  *    mark free blocks in-core
297c9de560dSAlex Tomas  *
298c9de560dSAlex Tomas  *  - discard inode's preallocations:
299c9de560dSAlex Tomas  */
300c9de560dSAlex Tomas 
301c9de560dSAlex Tomas /*
302c9de560dSAlex Tomas  * Locking rules
303c9de560dSAlex Tomas  *
304c9de560dSAlex Tomas  * Locks:
305c9de560dSAlex Tomas  *  - bitlock on a group	(group)
306c9de560dSAlex Tomas  *  - object (inode/locality)	(object)
307c9de560dSAlex Tomas  *  - per-pa lock		(pa)
308c9de560dSAlex Tomas  *
309c9de560dSAlex Tomas  * Paths:
310c9de560dSAlex Tomas  *  - new pa
311c9de560dSAlex Tomas  *    object
312c9de560dSAlex Tomas  *    group
313c9de560dSAlex Tomas  *
314c9de560dSAlex Tomas  *  - find and use pa:
315c9de560dSAlex Tomas  *    pa
316c9de560dSAlex Tomas  *
317c9de560dSAlex Tomas  *  - release consumed pa:
318c9de560dSAlex Tomas  *    pa
319c9de560dSAlex Tomas  *    group
320c9de560dSAlex Tomas  *    object
321c9de560dSAlex Tomas  *
322c9de560dSAlex Tomas  *  - generate in-core bitmap:
323c9de560dSAlex Tomas  *    group
324c9de560dSAlex Tomas  *        pa
325c9de560dSAlex Tomas  *
326c9de560dSAlex Tomas  *  - discard all for given object (inode, locality group):
327c9de560dSAlex Tomas  *    object
328c9de560dSAlex Tomas  *        pa
329c9de560dSAlex Tomas  *    group
330c9de560dSAlex Tomas  *
331c9de560dSAlex Tomas  *  - discard all for given group:
332c9de560dSAlex Tomas  *    group
333c9de560dSAlex Tomas  *        pa
334c9de560dSAlex Tomas  *    group
335c9de560dSAlex Tomas  *        object
336c9de560dSAlex Tomas  *
337c9de560dSAlex Tomas  */
338c3a326a6SAneesh Kumar K.V static struct kmem_cache *ext4_pspace_cachep;
339c3a326a6SAneesh Kumar K.V static struct kmem_cache *ext4_ac_cachep;
340c3a326a6SAneesh Kumar K.V static struct kmem_cache *ext4_free_ext_cachep;
341fb1813f4SCurt Wohlgemuth 
342fb1813f4SCurt Wohlgemuth /* We create slab caches for groupinfo data structures based on the
343fb1813f4SCurt Wohlgemuth  * superblock block size.  There will be one per mounted filesystem for
344fb1813f4SCurt Wohlgemuth  * each unique s_blocksize_bits */
3452892c15dSEric Sandeen #define NR_GRPINFO_CACHES 8
346fb1813f4SCurt Wohlgemuth static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
347fb1813f4SCurt Wohlgemuth 
3482892c15dSEric Sandeen static const char *ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
3492892c15dSEric Sandeen 	"ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
3502892c15dSEric Sandeen 	"ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
3512892c15dSEric Sandeen 	"ext4_groupinfo_64k", "ext4_groupinfo_128k"
3522892c15dSEric Sandeen };
3532892c15dSEric Sandeen 
354c3a326a6SAneesh Kumar K.V static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
355c3a326a6SAneesh Kumar K.V 					ext4_group_t group);
3567a2fcbf7SAneesh Kumar K.V static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3577a2fcbf7SAneesh Kumar K.V 						ext4_group_t group);
358c3a326a6SAneesh Kumar K.V static void release_blocks_on_commit(journal_t *journal, transaction_t *txn);
359c3a326a6SAneesh Kumar K.V 
360ffad0a44SAneesh Kumar K.V static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
361ffad0a44SAneesh Kumar K.V {
362c9de560dSAlex Tomas #if BITS_PER_LONG == 64
363ffad0a44SAneesh Kumar K.V 	*bit += ((unsigned long) addr & 7UL) << 3;
364ffad0a44SAneesh Kumar K.V 	addr = (void *) ((unsigned long) addr & ~7UL);
365c9de560dSAlex Tomas #elif BITS_PER_LONG == 32
366ffad0a44SAneesh Kumar K.V 	*bit += ((unsigned long) addr & 3UL) << 3;
367ffad0a44SAneesh Kumar K.V 	addr = (void *) ((unsigned long) addr & ~3UL);
368c9de560dSAlex Tomas #else
369c9de560dSAlex Tomas #error "how many bits you are?!"
370c9de560dSAlex Tomas #endif
371ffad0a44SAneesh Kumar K.V 	return addr;
372ffad0a44SAneesh Kumar K.V }
373c9de560dSAlex Tomas 
374c9de560dSAlex Tomas static inline int mb_test_bit(int bit, void *addr)
375c9de560dSAlex Tomas {
376c9de560dSAlex Tomas 	/*
377c9de560dSAlex Tomas 	 * ext4_test_bit on architecture like powerpc
378c9de560dSAlex Tomas 	 * needs unsigned long aligned address
379c9de560dSAlex Tomas 	 */
380ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
381c9de560dSAlex Tomas 	return ext4_test_bit(bit, addr);
382c9de560dSAlex Tomas }
383c9de560dSAlex Tomas 
384c9de560dSAlex Tomas static inline void mb_set_bit(int bit, void *addr)
385c9de560dSAlex Tomas {
386ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
387c9de560dSAlex Tomas 	ext4_set_bit(bit, addr);
388c9de560dSAlex Tomas }
389c9de560dSAlex Tomas 
390c9de560dSAlex Tomas static inline void mb_clear_bit(int bit, void *addr)
391c9de560dSAlex Tomas {
392ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&bit, addr);
393c9de560dSAlex Tomas 	ext4_clear_bit(bit, addr);
394c9de560dSAlex Tomas }
395c9de560dSAlex Tomas 
396ffad0a44SAneesh Kumar K.V static inline int mb_find_next_zero_bit(void *addr, int max, int start)
397ffad0a44SAneesh Kumar K.V {
398e7dfb246SAneesh Kumar K.V 	int fix = 0, ret, tmpmax;
399ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&fix, addr);
400e7dfb246SAneesh Kumar K.V 	tmpmax = max + fix;
401ffad0a44SAneesh Kumar K.V 	start += fix;
402ffad0a44SAneesh Kumar K.V 
403e7dfb246SAneesh Kumar K.V 	ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
404e7dfb246SAneesh Kumar K.V 	if (ret > max)
405e7dfb246SAneesh Kumar K.V 		return max;
406e7dfb246SAneesh Kumar K.V 	return ret;
407ffad0a44SAneesh Kumar K.V }
408ffad0a44SAneesh Kumar K.V 
409ffad0a44SAneesh Kumar K.V static inline int mb_find_next_bit(void *addr, int max, int start)
410ffad0a44SAneesh Kumar K.V {
411e7dfb246SAneesh Kumar K.V 	int fix = 0, ret, tmpmax;
412ffad0a44SAneesh Kumar K.V 	addr = mb_correct_addr_and_bit(&fix, addr);
413e7dfb246SAneesh Kumar K.V 	tmpmax = max + fix;
414ffad0a44SAneesh Kumar K.V 	start += fix;
415ffad0a44SAneesh Kumar K.V 
416e7dfb246SAneesh Kumar K.V 	ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
417e7dfb246SAneesh Kumar K.V 	if (ret > max)
418e7dfb246SAneesh Kumar K.V 		return max;
419e7dfb246SAneesh Kumar K.V 	return ret;
420ffad0a44SAneesh Kumar K.V }
421ffad0a44SAneesh Kumar K.V 
422c9de560dSAlex Tomas static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
423c9de560dSAlex Tomas {
424c9de560dSAlex Tomas 	char *bb;
425c9de560dSAlex Tomas 
426c9de560dSAlex Tomas 	BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
427c9de560dSAlex Tomas 	BUG_ON(max == NULL);
428c9de560dSAlex Tomas 
429c9de560dSAlex Tomas 	if (order > e4b->bd_blkbits + 1) {
430c9de560dSAlex Tomas 		*max = 0;
431c9de560dSAlex Tomas 		return NULL;
432c9de560dSAlex Tomas 	}
433c9de560dSAlex Tomas 
434c9de560dSAlex Tomas 	/* at order 0 we see each particular block */
43584b775a3SColy Li 	if (order == 0) {
436c9de560dSAlex Tomas 		*max = 1 << (e4b->bd_blkbits + 3);
437c9de560dSAlex Tomas 		return EXT4_MB_BITMAP(e4b);
43884b775a3SColy Li 	}
439c9de560dSAlex Tomas 
440c9de560dSAlex Tomas 	bb = EXT4_MB_BUDDY(e4b) + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
441c9de560dSAlex Tomas 	*max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
442c9de560dSAlex Tomas 
443c9de560dSAlex Tomas 	return bb;
444c9de560dSAlex Tomas }
445c9de560dSAlex Tomas 
446c9de560dSAlex Tomas #ifdef DOUBLE_CHECK
447c9de560dSAlex Tomas static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
448c9de560dSAlex Tomas 			   int first, int count)
449c9de560dSAlex Tomas {
450c9de560dSAlex Tomas 	int i;
451c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
452c9de560dSAlex Tomas 
453c9de560dSAlex Tomas 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
454c9de560dSAlex Tomas 		return;
455bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
456c9de560dSAlex Tomas 	for (i = 0; i < count; i++) {
457c9de560dSAlex Tomas 		if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
458c9de560dSAlex Tomas 			ext4_fsblk_t blocknr;
4595661bd68SAkinobu Mita 
4605661bd68SAkinobu Mita 			blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
461c9de560dSAlex Tomas 			blocknr += first + i;
4625d1b1b3fSAneesh Kumar K.V 			ext4_grp_locked_error(sb, e4b->bd_group,
463e29136f8STheodore Ts'o 					      inode ? inode->i_ino : 0,
464e29136f8STheodore Ts'o 					      blocknr,
465e29136f8STheodore Ts'o 					      "freeing block already freed "
466e29136f8STheodore Ts'o 					      "(bit %u)",
467e29136f8STheodore Ts'o 					      first + i);
468c9de560dSAlex Tomas 		}
469c9de560dSAlex Tomas 		mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
470c9de560dSAlex Tomas 	}
471c9de560dSAlex Tomas }
472c9de560dSAlex Tomas 
473c9de560dSAlex Tomas static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
474c9de560dSAlex Tomas {
475c9de560dSAlex Tomas 	int i;
476c9de560dSAlex Tomas 
477c9de560dSAlex Tomas 	if (unlikely(e4b->bd_info->bb_bitmap == NULL))
478c9de560dSAlex Tomas 		return;
479bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
480c9de560dSAlex Tomas 	for (i = 0; i < count; i++) {
481c9de560dSAlex Tomas 		BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
482c9de560dSAlex Tomas 		mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
483c9de560dSAlex Tomas 	}
484c9de560dSAlex Tomas }
485c9de560dSAlex Tomas 
486c9de560dSAlex Tomas static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
487c9de560dSAlex Tomas {
488c9de560dSAlex Tomas 	if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
489c9de560dSAlex Tomas 		unsigned char *b1, *b2;
490c9de560dSAlex Tomas 		int i;
491c9de560dSAlex Tomas 		b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
492c9de560dSAlex Tomas 		b2 = (unsigned char *) bitmap;
493c9de560dSAlex Tomas 		for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
494c9de560dSAlex Tomas 			if (b1[i] != b2[i]) {
495a9df9a49STheodore Ts'o 				printk(KERN_ERR "corruption in group %u "
4964776004fSTheodore Ts'o 				       "at byte %u(%u): %x in copy != %x "
4974776004fSTheodore Ts'o 				       "on disk/prealloc\n",
498c9de560dSAlex Tomas 				       e4b->bd_group, i, i * 8, b1[i], b2[i]);
499c9de560dSAlex Tomas 				BUG();
500c9de560dSAlex Tomas 			}
501c9de560dSAlex Tomas 		}
502c9de560dSAlex Tomas 	}
503c9de560dSAlex Tomas }
504c9de560dSAlex Tomas 
505c9de560dSAlex Tomas #else
506c9de560dSAlex Tomas static inline void mb_free_blocks_double(struct inode *inode,
507c9de560dSAlex Tomas 				struct ext4_buddy *e4b, int first, int count)
508c9de560dSAlex Tomas {
509c9de560dSAlex Tomas 	return;
510c9de560dSAlex Tomas }
511c9de560dSAlex Tomas static inline void mb_mark_used_double(struct ext4_buddy *e4b,
512c9de560dSAlex Tomas 						int first, int count)
513c9de560dSAlex Tomas {
514c9de560dSAlex Tomas 	return;
515c9de560dSAlex Tomas }
516c9de560dSAlex Tomas static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
517c9de560dSAlex Tomas {
518c9de560dSAlex Tomas 	return;
519c9de560dSAlex Tomas }
520c9de560dSAlex Tomas #endif
521c9de560dSAlex Tomas 
522c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
523c9de560dSAlex Tomas 
524c9de560dSAlex Tomas #define MB_CHECK_ASSERT(assert)						\
525c9de560dSAlex Tomas do {									\
526c9de560dSAlex Tomas 	if (!(assert)) {						\
527c9de560dSAlex Tomas 		printk(KERN_EMERG					\
528c9de560dSAlex Tomas 			"Assertion failure in %s() at %s:%d: \"%s\"\n",	\
529c9de560dSAlex Tomas 			function, file, line, # assert);		\
530c9de560dSAlex Tomas 		BUG();							\
531c9de560dSAlex Tomas 	}								\
532c9de560dSAlex Tomas } while (0)
533c9de560dSAlex Tomas 
534c9de560dSAlex Tomas static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
535c9de560dSAlex Tomas 				const char *function, int line)
536c9de560dSAlex Tomas {
537c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
538c9de560dSAlex Tomas 	int order = e4b->bd_blkbits + 1;
539c9de560dSAlex Tomas 	int max;
540c9de560dSAlex Tomas 	int max2;
541c9de560dSAlex Tomas 	int i;
542c9de560dSAlex Tomas 	int j;
543c9de560dSAlex Tomas 	int k;
544c9de560dSAlex Tomas 	int count;
545c9de560dSAlex Tomas 	struct ext4_group_info *grp;
546c9de560dSAlex Tomas 	int fragments = 0;
547c9de560dSAlex Tomas 	int fstart;
548c9de560dSAlex Tomas 	struct list_head *cur;
549c9de560dSAlex Tomas 	void *buddy;
550c9de560dSAlex Tomas 	void *buddy2;
551c9de560dSAlex Tomas 
552c9de560dSAlex Tomas 	{
553c9de560dSAlex Tomas 		static int mb_check_counter;
554c9de560dSAlex Tomas 		if (mb_check_counter++ % 100 != 0)
555c9de560dSAlex Tomas 			return 0;
556c9de560dSAlex Tomas 	}
557c9de560dSAlex Tomas 
558c9de560dSAlex Tomas 	while (order > 1) {
559c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, order, &max);
560c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy);
561c9de560dSAlex Tomas 		buddy2 = mb_find_buddy(e4b, order - 1, &max2);
562c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy2);
563c9de560dSAlex Tomas 		MB_CHECK_ASSERT(buddy != buddy2);
564c9de560dSAlex Tomas 		MB_CHECK_ASSERT(max * 2 == max2);
565c9de560dSAlex Tomas 
566c9de560dSAlex Tomas 		count = 0;
567c9de560dSAlex Tomas 		for (i = 0; i < max; i++) {
568c9de560dSAlex Tomas 
569c9de560dSAlex Tomas 			if (mb_test_bit(i, buddy)) {
570c9de560dSAlex Tomas 				/* only single bit in buddy2 may be 1 */
571c9de560dSAlex Tomas 				if (!mb_test_bit(i << 1, buddy2)) {
572c9de560dSAlex Tomas 					MB_CHECK_ASSERT(
573c9de560dSAlex Tomas 						mb_test_bit((i<<1)+1, buddy2));
574c9de560dSAlex Tomas 				} else if (!mb_test_bit((i << 1) + 1, buddy2)) {
575c9de560dSAlex Tomas 					MB_CHECK_ASSERT(
576c9de560dSAlex Tomas 						mb_test_bit(i << 1, buddy2));
577c9de560dSAlex Tomas 				}
578c9de560dSAlex Tomas 				continue;
579c9de560dSAlex Tomas 			}
580c9de560dSAlex Tomas 
581c9de560dSAlex Tomas 			/* both bits in buddy2 must be 0 */
582c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
583c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
584c9de560dSAlex Tomas 
585c9de560dSAlex Tomas 			for (j = 0; j < (1 << order); j++) {
586c9de560dSAlex Tomas 				k = (i * (1 << order)) + j;
587c9de560dSAlex Tomas 				MB_CHECK_ASSERT(
588c9de560dSAlex Tomas 					!mb_test_bit(k, EXT4_MB_BITMAP(e4b)));
589c9de560dSAlex Tomas 			}
590c9de560dSAlex Tomas 			count++;
591c9de560dSAlex Tomas 		}
592c9de560dSAlex Tomas 		MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
593c9de560dSAlex Tomas 		order--;
594c9de560dSAlex Tomas 	}
595c9de560dSAlex Tomas 
596c9de560dSAlex Tomas 	fstart = -1;
597c9de560dSAlex Tomas 	buddy = mb_find_buddy(e4b, 0, &max);
598c9de560dSAlex Tomas 	for (i = 0; i < max; i++) {
599c9de560dSAlex Tomas 		if (!mb_test_bit(i, buddy)) {
600c9de560dSAlex Tomas 			MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
601c9de560dSAlex Tomas 			if (fstart == -1) {
602c9de560dSAlex Tomas 				fragments++;
603c9de560dSAlex Tomas 				fstart = i;
604c9de560dSAlex Tomas 			}
605c9de560dSAlex Tomas 			continue;
606c9de560dSAlex Tomas 		}
607c9de560dSAlex Tomas 		fstart = -1;
608c9de560dSAlex Tomas 		/* check used bits only */
609c9de560dSAlex Tomas 		for (j = 0; j < e4b->bd_blkbits + 1; j++) {
610c9de560dSAlex Tomas 			buddy2 = mb_find_buddy(e4b, j, &max2);
611c9de560dSAlex Tomas 			k = i >> j;
612c9de560dSAlex Tomas 			MB_CHECK_ASSERT(k < max2);
613c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
614c9de560dSAlex Tomas 		}
615c9de560dSAlex Tomas 	}
616c9de560dSAlex Tomas 	MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
617c9de560dSAlex Tomas 	MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
618c9de560dSAlex Tomas 
619c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, e4b->bd_group);
620c9de560dSAlex Tomas 	list_for_each(cur, &grp->bb_prealloc_list) {
621c9de560dSAlex Tomas 		ext4_group_t groupnr;
622c9de560dSAlex Tomas 		struct ext4_prealloc_space *pa;
62360bd63d1SSolofo Ramangalahy 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
62460bd63d1SSolofo Ramangalahy 		ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
625c9de560dSAlex Tomas 		MB_CHECK_ASSERT(groupnr == e4b->bd_group);
62660bd63d1SSolofo Ramangalahy 		for (i = 0; i < pa->pa_len; i++)
627c9de560dSAlex Tomas 			MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
628c9de560dSAlex Tomas 	}
629c9de560dSAlex Tomas 	return 0;
630c9de560dSAlex Tomas }
631c9de560dSAlex Tomas #undef MB_CHECK_ASSERT
632c9de560dSAlex Tomas #define mb_check_buddy(e4b) __mb_check_buddy(e4b,	\
63346e665e9SHarvey Harrison 					__FILE__, __func__, __LINE__)
634c9de560dSAlex Tomas #else
635c9de560dSAlex Tomas #define mb_check_buddy(e4b)
636c9de560dSAlex Tomas #endif
637c9de560dSAlex Tomas 
6387c786059SColy Li /*
6397c786059SColy Li  * Divide blocks started from @first with length @len into
6407c786059SColy Li  * smaller chunks with power of 2 blocks.
6417c786059SColy Li  * Clear the bits in bitmap which the blocks of the chunk(s) covered,
6427c786059SColy Li  * then increase bb_counters[] for corresponded chunk size.
6437c786059SColy Li  */
644c9de560dSAlex Tomas static void ext4_mb_mark_free_simple(struct super_block *sb,
645a36b4498SEric Sandeen 				void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
646c9de560dSAlex Tomas 					struct ext4_group_info *grp)
647c9de560dSAlex Tomas {
648c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
649a36b4498SEric Sandeen 	ext4_grpblk_t min;
650a36b4498SEric Sandeen 	ext4_grpblk_t max;
651a36b4498SEric Sandeen 	ext4_grpblk_t chunk;
652c9de560dSAlex Tomas 	unsigned short border;
653c9de560dSAlex Tomas 
654b73fce69SValerie Clement 	BUG_ON(len > EXT4_BLOCKS_PER_GROUP(sb));
655c9de560dSAlex Tomas 
656c9de560dSAlex Tomas 	border = 2 << sb->s_blocksize_bits;
657c9de560dSAlex Tomas 
658c9de560dSAlex Tomas 	while (len > 0) {
659c9de560dSAlex Tomas 		/* find how many blocks can be covered since this position */
660c9de560dSAlex Tomas 		max = ffs(first | border) - 1;
661c9de560dSAlex Tomas 
662c9de560dSAlex Tomas 		/* find how many blocks of power 2 we need to mark */
663c9de560dSAlex Tomas 		min = fls(len) - 1;
664c9de560dSAlex Tomas 
665c9de560dSAlex Tomas 		if (max < min)
666c9de560dSAlex Tomas 			min = max;
667c9de560dSAlex Tomas 		chunk = 1 << min;
668c9de560dSAlex Tomas 
669c9de560dSAlex Tomas 		/* mark multiblock chunks only */
670c9de560dSAlex Tomas 		grp->bb_counters[min]++;
671c9de560dSAlex Tomas 		if (min > 0)
672c9de560dSAlex Tomas 			mb_clear_bit(first >> min,
673c9de560dSAlex Tomas 				     buddy + sbi->s_mb_offsets[min]);
674c9de560dSAlex Tomas 
675c9de560dSAlex Tomas 		len -= chunk;
676c9de560dSAlex Tomas 		first += chunk;
677c9de560dSAlex Tomas 	}
678c9de560dSAlex Tomas }
679c9de560dSAlex Tomas 
6808a57d9d6SCurt Wohlgemuth /*
6818a57d9d6SCurt Wohlgemuth  * Cache the order of the largest free extent we have available in this block
6828a57d9d6SCurt Wohlgemuth  * group.
6838a57d9d6SCurt Wohlgemuth  */
6848a57d9d6SCurt Wohlgemuth static void
6858a57d9d6SCurt Wohlgemuth mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
6868a57d9d6SCurt Wohlgemuth {
6878a57d9d6SCurt Wohlgemuth 	int i;
6888a57d9d6SCurt Wohlgemuth 	int bits;
6898a57d9d6SCurt Wohlgemuth 
6908a57d9d6SCurt Wohlgemuth 	grp->bb_largest_free_order = -1; /* uninit */
6918a57d9d6SCurt Wohlgemuth 
6928a57d9d6SCurt Wohlgemuth 	bits = sb->s_blocksize_bits + 1;
6938a57d9d6SCurt Wohlgemuth 	for (i = bits; i >= 0; i--) {
6948a57d9d6SCurt Wohlgemuth 		if (grp->bb_counters[i] > 0) {
6958a57d9d6SCurt Wohlgemuth 			grp->bb_largest_free_order = i;
6968a57d9d6SCurt Wohlgemuth 			break;
6978a57d9d6SCurt Wohlgemuth 		}
6988a57d9d6SCurt Wohlgemuth 	}
6998a57d9d6SCurt Wohlgemuth }
7008a57d9d6SCurt Wohlgemuth 
701089ceeccSEric Sandeen static noinline_for_stack
702089ceeccSEric Sandeen void ext4_mb_generate_buddy(struct super_block *sb,
703c9de560dSAlex Tomas 				void *buddy, void *bitmap, ext4_group_t group)
704c9de560dSAlex Tomas {
705c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
706a36b4498SEric Sandeen 	ext4_grpblk_t max = EXT4_BLOCKS_PER_GROUP(sb);
707a36b4498SEric Sandeen 	ext4_grpblk_t i = 0;
708a36b4498SEric Sandeen 	ext4_grpblk_t first;
709a36b4498SEric Sandeen 	ext4_grpblk_t len;
710c9de560dSAlex Tomas 	unsigned free = 0;
711c9de560dSAlex Tomas 	unsigned fragments = 0;
712c9de560dSAlex Tomas 	unsigned long long period = get_cycles();
713c9de560dSAlex Tomas 
714c9de560dSAlex Tomas 	/* initialize buddy from bitmap which is aggregation
715c9de560dSAlex Tomas 	 * of on-disk bitmap and preallocations */
716ffad0a44SAneesh Kumar K.V 	i = mb_find_next_zero_bit(bitmap, max, 0);
717c9de560dSAlex Tomas 	grp->bb_first_free = i;
718c9de560dSAlex Tomas 	while (i < max) {
719c9de560dSAlex Tomas 		fragments++;
720c9de560dSAlex Tomas 		first = i;
721ffad0a44SAneesh Kumar K.V 		i = mb_find_next_bit(bitmap, max, i);
722c9de560dSAlex Tomas 		len = i - first;
723c9de560dSAlex Tomas 		free += len;
724c9de560dSAlex Tomas 		if (len > 1)
725c9de560dSAlex Tomas 			ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
726c9de560dSAlex Tomas 		else
727c9de560dSAlex Tomas 			grp->bb_counters[0]++;
728c9de560dSAlex Tomas 		if (i < max)
729ffad0a44SAneesh Kumar K.V 			i = mb_find_next_zero_bit(bitmap, max, i);
730c9de560dSAlex Tomas 	}
731c9de560dSAlex Tomas 	grp->bb_fragments = fragments;
732c9de560dSAlex Tomas 
733c9de560dSAlex Tomas 	if (free != grp->bb_free) {
734e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0,
735e29136f8STheodore Ts'o 				      "%u blocks in bitmap, %u in gd",
736e29136f8STheodore Ts'o 				      free, grp->bb_free);
737e56eb659SAneesh Kumar K.V 		/*
738e56eb659SAneesh Kumar K.V 		 * If we intent to continue, we consider group descritor
739e56eb659SAneesh Kumar K.V 		 * corrupt and update bb_free using bitmap value
740e56eb659SAneesh Kumar K.V 		 */
741c9de560dSAlex Tomas 		grp->bb_free = free;
742c9de560dSAlex Tomas 	}
7438a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, grp);
744c9de560dSAlex Tomas 
745c9de560dSAlex Tomas 	clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
746c9de560dSAlex Tomas 
747c9de560dSAlex Tomas 	period = get_cycles() - period;
748c9de560dSAlex Tomas 	spin_lock(&EXT4_SB(sb)->s_bal_lock);
749c9de560dSAlex Tomas 	EXT4_SB(sb)->s_mb_buddies_generated++;
750c9de560dSAlex Tomas 	EXT4_SB(sb)->s_mb_generation_time += period;
751c9de560dSAlex Tomas 	spin_unlock(&EXT4_SB(sb)->s_bal_lock);
752c9de560dSAlex Tomas }
753c9de560dSAlex Tomas 
754c9de560dSAlex Tomas /* The buddy information is attached the buddy cache inode
755c9de560dSAlex Tomas  * for convenience. The information regarding each group
756c9de560dSAlex Tomas  * is loaded via ext4_mb_load_buddy. The information involve
757c9de560dSAlex Tomas  * block bitmap and buddy information. The information are
758c9de560dSAlex Tomas  * stored in the inode as
759c9de560dSAlex Tomas  *
760c9de560dSAlex Tomas  * {                        page                        }
761c3a326a6SAneesh Kumar K.V  * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
762c9de560dSAlex Tomas  *
763c9de560dSAlex Tomas  *
764c9de560dSAlex Tomas  * one block each for bitmap and buddy information.
765c9de560dSAlex Tomas  * So for each group we take up 2 blocks. A page can
766c9de560dSAlex Tomas  * contain blocks_per_page (PAGE_CACHE_SIZE / blocksize)  blocks.
767c9de560dSAlex Tomas  * So it can have information regarding groups_per_page which
768c9de560dSAlex Tomas  * is blocks_per_page/2
7698a57d9d6SCurt Wohlgemuth  *
7708a57d9d6SCurt Wohlgemuth  * Locking note:  This routine takes the block group lock of all groups
7718a57d9d6SCurt Wohlgemuth  * for this page; do not hold this lock when calling this routine!
772c9de560dSAlex Tomas  */
773c9de560dSAlex Tomas 
774c9de560dSAlex Tomas static int ext4_mb_init_cache(struct page *page, char *incore)
775c9de560dSAlex Tomas {
7768df9675fSTheodore Ts'o 	ext4_group_t ngroups;
777c9de560dSAlex Tomas 	int blocksize;
778c9de560dSAlex Tomas 	int blocks_per_page;
779c9de560dSAlex Tomas 	int groups_per_page;
780c9de560dSAlex Tomas 	int err = 0;
781c9de560dSAlex Tomas 	int i;
782c9de560dSAlex Tomas 	ext4_group_t first_group;
783c9de560dSAlex Tomas 	int first_block;
784c9de560dSAlex Tomas 	struct super_block *sb;
785c9de560dSAlex Tomas 	struct buffer_head *bhs;
786c9de560dSAlex Tomas 	struct buffer_head **bh;
787c9de560dSAlex Tomas 	struct inode *inode;
788c9de560dSAlex Tomas 	char *data;
789c9de560dSAlex Tomas 	char *bitmap;
790c9de560dSAlex Tomas 
7916ba495e9STheodore Ts'o 	mb_debug(1, "init page %lu\n", page->index);
792c9de560dSAlex Tomas 
793c9de560dSAlex Tomas 	inode = page->mapping->host;
794c9de560dSAlex Tomas 	sb = inode->i_sb;
7958df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
796c9de560dSAlex Tomas 	blocksize = 1 << inode->i_blkbits;
797c9de560dSAlex Tomas 	blocks_per_page = PAGE_CACHE_SIZE / blocksize;
798c9de560dSAlex Tomas 
799c9de560dSAlex Tomas 	groups_per_page = blocks_per_page >> 1;
800c9de560dSAlex Tomas 	if (groups_per_page == 0)
801c9de560dSAlex Tomas 		groups_per_page = 1;
802c9de560dSAlex Tomas 
803c9de560dSAlex Tomas 	/* allocate buffer_heads to read bitmaps */
804c9de560dSAlex Tomas 	if (groups_per_page > 1) {
805c9de560dSAlex Tomas 		err = -ENOMEM;
806c9de560dSAlex Tomas 		i = sizeof(struct buffer_head *) * groups_per_page;
807c9de560dSAlex Tomas 		bh = kzalloc(i, GFP_NOFS);
808c9de560dSAlex Tomas 		if (bh == NULL)
809c9de560dSAlex Tomas 			goto out;
810c9de560dSAlex Tomas 	} else
811c9de560dSAlex Tomas 		bh = &bhs;
812c9de560dSAlex Tomas 
813c9de560dSAlex Tomas 	first_group = page->index * blocks_per_page / 2;
814c9de560dSAlex Tomas 
815c9de560dSAlex Tomas 	/* read all groups the page covers into the cache */
816c9de560dSAlex Tomas 	for (i = 0; i < groups_per_page; i++) {
817c9de560dSAlex Tomas 		struct ext4_group_desc *desc;
818c9de560dSAlex Tomas 
8198df9675fSTheodore Ts'o 		if (first_group + i >= ngroups)
820c9de560dSAlex Tomas 			break;
821c9de560dSAlex Tomas 
822c9de560dSAlex Tomas 		err = -EIO;
823c9de560dSAlex Tomas 		desc = ext4_get_group_desc(sb, first_group + i, NULL);
824c9de560dSAlex Tomas 		if (desc == NULL)
825c9de560dSAlex Tomas 			goto out;
826c9de560dSAlex Tomas 
827c9de560dSAlex Tomas 		err = -ENOMEM;
828c9de560dSAlex Tomas 		bh[i] = sb_getblk(sb, ext4_block_bitmap(sb, desc));
829c9de560dSAlex Tomas 		if (bh[i] == NULL)
830c9de560dSAlex Tomas 			goto out;
831c9de560dSAlex Tomas 
8322ccb5fb9SAneesh Kumar K.V 		if (bitmap_uptodate(bh[i]))
833c9de560dSAlex Tomas 			continue;
834c9de560dSAlex Tomas 
835c806e68fSFrederic Bohe 		lock_buffer(bh[i]);
8362ccb5fb9SAneesh Kumar K.V 		if (bitmap_uptodate(bh[i])) {
8372ccb5fb9SAneesh Kumar K.V 			unlock_buffer(bh[i]);
8382ccb5fb9SAneesh Kumar K.V 			continue;
8392ccb5fb9SAneesh Kumar K.V 		}
840955ce5f5SAneesh Kumar K.V 		ext4_lock_group(sb, first_group + i);
841c9de560dSAlex Tomas 		if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
842c9de560dSAlex Tomas 			ext4_init_block_bitmap(sb, bh[i],
843c9de560dSAlex Tomas 						first_group + i, desc);
8442ccb5fb9SAneesh Kumar K.V 			set_bitmap_uptodate(bh[i]);
845c9de560dSAlex Tomas 			set_buffer_uptodate(bh[i]);
846955ce5f5SAneesh Kumar K.V 			ext4_unlock_group(sb, first_group + i);
8473300bedaSAneesh Kumar K.V 			unlock_buffer(bh[i]);
848c9de560dSAlex Tomas 			continue;
849c9de560dSAlex Tomas 		}
850955ce5f5SAneesh Kumar K.V 		ext4_unlock_group(sb, first_group + i);
8512ccb5fb9SAneesh Kumar K.V 		if (buffer_uptodate(bh[i])) {
8522ccb5fb9SAneesh Kumar K.V 			/*
8532ccb5fb9SAneesh Kumar K.V 			 * if not uninit if bh is uptodate,
8542ccb5fb9SAneesh Kumar K.V 			 * bitmap is also uptodate
8552ccb5fb9SAneesh Kumar K.V 			 */
8562ccb5fb9SAneesh Kumar K.V 			set_bitmap_uptodate(bh[i]);
8572ccb5fb9SAneesh Kumar K.V 			unlock_buffer(bh[i]);
8582ccb5fb9SAneesh Kumar K.V 			continue;
8592ccb5fb9SAneesh Kumar K.V 		}
860c9de560dSAlex Tomas 		get_bh(bh[i]);
8612ccb5fb9SAneesh Kumar K.V 		/*
8622ccb5fb9SAneesh Kumar K.V 		 * submit the buffer_head for read. We can
8632ccb5fb9SAneesh Kumar K.V 		 * safely mark the bitmap as uptodate now.
8642ccb5fb9SAneesh Kumar K.V 		 * We do it here so the bitmap uptodate bit
8652ccb5fb9SAneesh Kumar K.V 		 * get set with buffer lock held.
8662ccb5fb9SAneesh Kumar K.V 		 */
8672ccb5fb9SAneesh Kumar K.V 		set_bitmap_uptodate(bh[i]);
868c9de560dSAlex Tomas 		bh[i]->b_end_io = end_buffer_read_sync;
869c9de560dSAlex Tomas 		submit_bh(READ, bh[i]);
8706ba495e9STheodore Ts'o 		mb_debug(1, "read bitmap for group %u\n", first_group + i);
871c9de560dSAlex Tomas 	}
872c9de560dSAlex Tomas 
873c9de560dSAlex Tomas 	/* wait for I/O completion */
874c9de560dSAlex Tomas 	for (i = 0; i < groups_per_page && bh[i]; i++)
875c9de560dSAlex Tomas 		wait_on_buffer(bh[i]);
876c9de560dSAlex Tomas 
877c9de560dSAlex Tomas 	err = -EIO;
878c9de560dSAlex Tomas 	for (i = 0; i < groups_per_page && bh[i]; i++)
879c9de560dSAlex Tomas 		if (!buffer_uptodate(bh[i]))
880c9de560dSAlex Tomas 			goto out;
881c9de560dSAlex Tomas 
88231b481dcSMingming Cao 	err = 0;
883c9de560dSAlex Tomas 	first_block = page->index * blocks_per_page;
88429eaf024SAneesh Kumar K.V 	/* init the page  */
88529eaf024SAneesh Kumar K.V 	memset(page_address(page), 0xff, PAGE_CACHE_SIZE);
886c9de560dSAlex Tomas 	for (i = 0; i < blocks_per_page; i++) {
887c9de560dSAlex Tomas 		int group;
888c9de560dSAlex Tomas 		struct ext4_group_info *grinfo;
889c9de560dSAlex Tomas 
890c9de560dSAlex Tomas 		group = (first_block + i) >> 1;
8918df9675fSTheodore Ts'o 		if (group >= ngroups)
892c9de560dSAlex Tomas 			break;
893c9de560dSAlex Tomas 
894c9de560dSAlex Tomas 		/*
895c9de560dSAlex Tomas 		 * data carry information regarding this
896c9de560dSAlex Tomas 		 * particular group in the format specified
897c9de560dSAlex Tomas 		 * above
898c9de560dSAlex Tomas 		 *
899c9de560dSAlex Tomas 		 */
900c9de560dSAlex Tomas 		data = page_address(page) + (i * blocksize);
901c9de560dSAlex Tomas 		bitmap = bh[group - first_group]->b_data;
902c9de560dSAlex Tomas 
903c9de560dSAlex Tomas 		/*
904c9de560dSAlex Tomas 		 * We place the buddy block and bitmap block
905c9de560dSAlex Tomas 		 * close together
906c9de560dSAlex Tomas 		 */
907c9de560dSAlex Tomas 		if ((first_block + i) & 1) {
908c9de560dSAlex Tomas 			/* this is block of buddy */
909c9de560dSAlex Tomas 			BUG_ON(incore == NULL);
9106ba495e9STheodore Ts'o 			mb_debug(1, "put buddy for group %u in page %lu/%x\n",
911c9de560dSAlex Tomas 				group, page->index, i * blocksize);
912f307333eSTheodore Ts'o 			trace_ext4_mb_buddy_bitmap_load(sb, group);
913c9de560dSAlex Tomas 			grinfo = ext4_get_group_info(sb, group);
914c9de560dSAlex Tomas 			grinfo->bb_fragments = 0;
915c9de560dSAlex Tomas 			memset(grinfo->bb_counters, 0,
9161927805eSEric Sandeen 			       sizeof(*grinfo->bb_counters) *
9171927805eSEric Sandeen 				(sb->s_blocksize_bits+2));
918c9de560dSAlex Tomas 			/*
919c9de560dSAlex Tomas 			 * incore got set to the group block bitmap below
920c9de560dSAlex Tomas 			 */
9217a2fcbf7SAneesh Kumar K.V 			ext4_lock_group(sb, group);
922c9de560dSAlex Tomas 			ext4_mb_generate_buddy(sb, data, incore, group);
9237a2fcbf7SAneesh Kumar K.V 			ext4_unlock_group(sb, group);
924c9de560dSAlex Tomas 			incore = NULL;
925c9de560dSAlex Tomas 		} else {
926c9de560dSAlex Tomas 			/* this is block of bitmap */
927c9de560dSAlex Tomas 			BUG_ON(incore != NULL);
9286ba495e9STheodore Ts'o 			mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
929c9de560dSAlex Tomas 				group, page->index, i * blocksize);
930f307333eSTheodore Ts'o 			trace_ext4_mb_bitmap_load(sb, group);
931c9de560dSAlex Tomas 
932c9de560dSAlex Tomas 			/* see comments in ext4_mb_put_pa() */
933c9de560dSAlex Tomas 			ext4_lock_group(sb, group);
934c9de560dSAlex Tomas 			memcpy(data, bitmap, blocksize);
935c9de560dSAlex Tomas 
936c9de560dSAlex Tomas 			/* mark all preallocated blks used in in-core bitmap */
937c9de560dSAlex Tomas 			ext4_mb_generate_from_pa(sb, data, group);
9387a2fcbf7SAneesh Kumar K.V 			ext4_mb_generate_from_freelist(sb, data, group);
939c9de560dSAlex Tomas 			ext4_unlock_group(sb, group);
940c9de560dSAlex Tomas 
941c9de560dSAlex Tomas 			/* set incore so that the buddy information can be
942c9de560dSAlex Tomas 			 * generated using this
943c9de560dSAlex Tomas 			 */
944c9de560dSAlex Tomas 			incore = data;
945c9de560dSAlex Tomas 		}
946c9de560dSAlex Tomas 	}
947c9de560dSAlex Tomas 	SetPageUptodate(page);
948c9de560dSAlex Tomas 
949c9de560dSAlex Tomas out:
950c9de560dSAlex Tomas 	if (bh) {
951c9de560dSAlex Tomas 		for (i = 0; i < groups_per_page && bh[i]; i++)
952c9de560dSAlex Tomas 			brelse(bh[i]);
953c9de560dSAlex Tomas 		if (bh != &bhs)
954c9de560dSAlex Tomas 			kfree(bh);
955c9de560dSAlex Tomas 	}
956c9de560dSAlex Tomas 	return err;
957c9de560dSAlex Tomas }
958c9de560dSAlex Tomas 
9598a57d9d6SCurt Wohlgemuth /*
960eee4adc7SEric Sandeen  * lock the group_info alloc_sem of all the groups
961eee4adc7SEric Sandeen  * belonging to the same buddy cache page. This
962eee4adc7SEric Sandeen  * make sure other parallel operation on the buddy
963eee4adc7SEric Sandeen  * cache doesn't happen  whild holding the buddy cache
964eee4adc7SEric Sandeen  * lock
965eee4adc7SEric Sandeen  */
966eee4adc7SEric Sandeen static int ext4_mb_get_buddy_cache_lock(struct super_block *sb,
967eee4adc7SEric Sandeen 					ext4_group_t group)
968eee4adc7SEric Sandeen {
969eee4adc7SEric Sandeen 	int i;
970eee4adc7SEric Sandeen 	int block, pnum;
971eee4adc7SEric Sandeen 	int blocks_per_page;
972eee4adc7SEric Sandeen 	int groups_per_page;
973eee4adc7SEric Sandeen 	ext4_group_t ngroups = ext4_get_groups_count(sb);
974eee4adc7SEric Sandeen 	ext4_group_t first_group;
975eee4adc7SEric Sandeen 	struct ext4_group_info *grp;
976eee4adc7SEric Sandeen 
977eee4adc7SEric Sandeen 	blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
978eee4adc7SEric Sandeen 	/*
979eee4adc7SEric Sandeen 	 * the buddy cache inode stores the block bitmap
980eee4adc7SEric Sandeen 	 * and buddy information in consecutive blocks.
981eee4adc7SEric Sandeen 	 * So for each group we need two blocks.
982eee4adc7SEric Sandeen 	 */
983eee4adc7SEric Sandeen 	block = group * 2;
984eee4adc7SEric Sandeen 	pnum = block / blocks_per_page;
985eee4adc7SEric Sandeen 	first_group = pnum * blocks_per_page / 2;
986eee4adc7SEric Sandeen 
987eee4adc7SEric Sandeen 	groups_per_page = blocks_per_page >> 1;
988eee4adc7SEric Sandeen 	if (groups_per_page == 0)
989eee4adc7SEric Sandeen 		groups_per_page = 1;
990eee4adc7SEric Sandeen 	/* read all groups the page covers into the cache */
991eee4adc7SEric Sandeen 	for (i = 0; i < groups_per_page; i++) {
992eee4adc7SEric Sandeen 
993eee4adc7SEric Sandeen 		if ((first_group + i) >= ngroups)
994eee4adc7SEric Sandeen 			break;
995eee4adc7SEric Sandeen 		grp = ext4_get_group_info(sb, first_group + i);
996eee4adc7SEric Sandeen 		/* take all groups write allocation
997eee4adc7SEric Sandeen 		 * semaphore. This make sure there is
998eee4adc7SEric Sandeen 		 * no block allocation going on in any
999eee4adc7SEric Sandeen 		 * of that groups
1000eee4adc7SEric Sandeen 		 */
1001eee4adc7SEric Sandeen 		down_write_nested(&grp->alloc_sem, i);
1002eee4adc7SEric Sandeen 	}
1003eee4adc7SEric Sandeen 	return i;
1004eee4adc7SEric Sandeen }
1005eee4adc7SEric Sandeen 
1006eee4adc7SEric Sandeen static void ext4_mb_put_buddy_cache_lock(struct super_block *sb,
1007eee4adc7SEric Sandeen 					 ext4_group_t group, int locked_group)
1008eee4adc7SEric Sandeen {
1009eee4adc7SEric Sandeen 	int i;
1010eee4adc7SEric Sandeen 	int block, pnum;
1011eee4adc7SEric Sandeen 	int blocks_per_page;
1012eee4adc7SEric Sandeen 	ext4_group_t first_group;
1013eee4adc7SEric Sandeen 	struct ext4_group_info *grp;
1014eee4adc7SEric Sandeen 
1015eee4adc7SEric Sandeen 	blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1016eee4adc7SEric Sandeen 	/*
1017eee4adc7SEric Sandeen 	 * the buddy cache inode stores the block bitmap
1018eee4adc7SEric Sandeen 	 * and buddy information in consecutive blocks.
1019eee4adc7SEric Sandeen 	 * So for each group we need two blocks.
1020eee4adc7SEric Sandeen 	 */
1021eee4adc7SEric Sandeen 	block = group * 2;
1022eee4adc7SEric Sandeen 	pnum = block / blocks_per_page;
1023eee4adc7SEric Sandeen 	first_group = pnum * blocks_per_page / 2;
1024eee4adc7SEric Sandeen 	/* release locks on all the groups */
1025eee4adc7SEric Sandeen 	for (i = 0; i < locked_group; i++) {
1026eee4adc7SEric Sandeen 
1027eee4adc7SEric Sandeen 		grp = ext4_get_group_info(sb, first_group + i);
1028eee4adc7SEric Sandeen 		/* take all groups write allocation
1029eee4adc7SEric Sandeen 		 * semaphore. This make sure there is
1030eee4adc7SEric Sandeen 		 * no block allocation going on in any
1031eee4adc7SEric Sandeen 		 * of that groups
1032eee4adc7SEric Sandeen 		 */
1033eee4adc7SEric Sandeen 		up_write(&grp->alloc_sem);
1034eee4adc7SEric Sandeen 	}
1035eee4adc7SEric Sandeen 
1036eee4adc7SEric Sandeen }
1037eee4adc7SEric Sandeen 
1038eee4adc7SEric Sandeen /*
10398a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
10408a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
10418a57d9d6SCurt Wohlgemuth  * calling this routine!
10428a57d9d6SCurt Wohlgemuth  */
1043b6a758ecSAneesh Kumar K.V static noinline_for_stack
1044b6a758ecSAneesh Kumar K.V int ext4_mb_init_group(struct super_block *sb, ext4_group_t group)
1045b6a758ecSAneesh Kumar K.V {
1046b6a758ecSAneesh Kumar K.V 
1047b6a758ecSAneesh Kumar K.V 	int ret = 0;
1048b6a758ecSAneesh Kumar K.V 	void *bitmap;
1049b6a758ecSAneesh Kumar K.V 	int blocks_per_page;
1050b6a758ecSAneesh Kumar K.V 	int block, pnum, poff;
1051b6a758ecSAneesh Kumar K.V 	int num_grp_locked = 0;
1052b6a758ecSAneesh Kumar K.V 	struct ext4_group_info *this_grp;
1053b6a758ecSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1054b6a758ecSAneesh Kumar K.V 	struct inode *inode = sbi->s_buddy_cache;
1055b6a758ecSAneesh Kumar K.V 	struct page *page = NULL, *bitmap_page = NULL;
1056b6a758ecSAneesh Kumar K.V 
1057b6a758ecSAneesh Kumar K.V 	mb_debug(1, "init group %u\n", group);
1058b6a758ecSAneesh Kumar K.V 	blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1059b6a758ecSAneesh Kumar K.V 	this_grp = ext4_get_group_info(sb, group);
1060b6a758ecSAneesh Kumar K.V 	/*
106108c3a813SAneesh Kumar K.V 	 * This ensures that we don't reinit the buddy cache
106208c3a813SAneesh Kumar K.V 	 * page which map to the group from which we are already
106308c3a813SAneesh Kumar K.V 	 * allocating. If we are looking at the buddy cache we would
106408c3a813SAneesh Kumar K.V 	 * have taken a reference using ext4_mb_load_buddy and that
106508c3a813SAneesh Kumar K.V 	 * would have taken the alloc_sem lock.
1066b6a758ecSAneesh Kumar K.V 	 */
1067b6a758ecSAneesh Kumar K.V 	num_grp_locked =  ext4_mb_get_buddy_cache_lock(sb, group);
1068b6a758ecSAneesh Kumar K.V 	if (!EXT4_MB_GRP_NEED_INIT(this_grp)) {
1069b6a758ecSAneesh Kumar K.V 		/*
1070b6a758ecSAneesh Kumar K.V 		 * somebody initialized the group
1071b6a758ecSAneesh Kumar K.V 		 * return without doing anything
1072b6a758ecSAneesh Kumar K.V 		 */
1073b6a758ecSAneesh Kumar K.V 		ret = 0;
1074b6a758ecSAneesh Kumar K.V 		goto err;
1075b6a758ecSAneesh Kumar K.V 	}
1076b6a758ecSAneesh Kumar K.V 	/*
1077b6a758ecSAneesh Kumar K.V 	 * the buddy cache inode stores the block bitmap
1078b6a758ecSAneesh Kumar K.V 	 * and buddy information in consecutive blocks.
1079b6a758ecSAneesh Kumar K.V 	 * So for each group we need two blocks.
1080b6a758ecSAneesh Kumar K.V 	 */
1081b6a758ecSAneesh Kumar K.V 	block = group * 2;
1082b6a758ecSAneesh Kumar K.V 	pnum = block / blocks_per_page;
1083b6a758ecSAneesh Kumar K.V 	poff = block % blocks_per_page;
1084b6a758ecSAneesh Kumar K.V 	page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1085b6a758ecSAneesh Kumar K.V 	if (page) {
1086b6a758ecSAneesh Kumar K.V 		BUG_ON(page->mapping != inode->i_mapping);
1087b6a758ecSAneesh Kumar K.V 		ret = ext4_mb_init_cache(page, NULL);
1088b6a758ecSAneesh Kumar K.V 		if (ret) {
1089b6a758ecSAneesh Kumar K.V 			unlock_page(page);
1090b6a758ecSAneesh Kumar K.V 			goto err;
1091b6a758ecSAneesh Kumar K.V 		}
1092b6a758ecSAneesh Kumar K.V 		unlock_page(page);
1093b6a758ecSAneesh Kumar K.V 	}
1094b6a758ecSAneesh Kumar K.V 	if (page == NULL || !PageUptodate(page)) {
1095b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1096b6a758ecSAneesh Kumar K.V 		goto err;
1097b6a758ecSAneesh Kumar K.V 	}
1098b6a758ecSAneesh Kumar K.V 	mark_page_accessed(page);
1099b6a758ecSAneesh Kumar K.V 	bitmap_page = page;
1100b6a758ecSAneesh Kumar K.V 	bitmap = page_address(page) + (poff * sb->s_blocksize);
1101b6a758ecSAneesh Kumar K.V 
1102b6a758ecSAneesh Kumar K.V 	/* init buddy cache */
1103b6a758ecSAneesh Kumar K.V 	block++;
1104b6a758ecSAneesh Kumar K.V 	pnum = block / blocks_per_page;
1105b6a758ecSAneesh Kumar K.V 	poff = block % blocks_per_page;
1106b6a758ecSAneesh Kumar K.V 	page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1107b6a758ecSAneesh Kumar K.V 	if (page == bitmap_page) {
1108b6a758ecSAneesh Kumar K.V 		/*
1109b6a758ecSAneesh Kumar K.V 		 * If both the bitmap and buddy are in
1110b6a758ecSAneesh Kumar K.V 		 * the same page we don't need to force
1111b6a758ecSAneesh Kumar K.V 		 * init the buddy
1112b6a758ecSAneesh Kumar K.V 		 */
1113b6a758ecSAneesh Kumar K.V 		unlock_page(page);
1114b6a758ecSAneesh Kumar K.V 	} else if (page) {
1115b6a758ecSAneesh Kumar K.V 		BUG_ON(page->mapping != inode->i_mapping);
1116b6a758ecSAneesh Kumar K.V 		ret = ext4_mb_init_cache(page, bitmap);
1117b6a758ecSAneesh Kumar K.V 		if (ret) {
1118b6a758ecSAneesh Kumar K.V 			unlock_page(page);
1119b6a758ecSAneesh Kumar K.V 			goto err;
1120b6a758ecSAneesh Kumar K.V 		}
1121b6a758ecSAneesh Kumar K.V 		unlock_page(page);
1122b6a758ecSAneesh Kumar K.V 	}
1123b6a758ecSAneesh Kumar K.V 	if (page == NULL || !PageUptodate(page)) {
1124b6a758ecSAneesh Kumar K.V 		ret = -EIO;
1125b6a758ecSAneesh Kumar K.V 		goto err;
1126b6a758ecSAneesh Kumar K.V 	}
1127b6a758ecSAneesh Kumar K.V 	mark_page_accessed(page);
1128b6a758ecSAneesh Kumar K.V err:
1129b6a758ecSAneesh Kumar K.V 	ext4_mb_put_buddy_cache_lock(sb, group, num_grp_locked);
1130b6a758ecSAneesh Kumar K.V 	if (bitmap_page)
1131b6a758ecSAneesh Kumar K.V 		page_cache_release(bitmap_page);
1132b6a758ecSAneesh Kumar K.V 	if (page)
1133b6a758ecSAneesh Kumar K.V 		page_cache_release(page);
1134b6a758ecSAneesh Kumar K.V 	return ret;
1135b6a758ecSAneesh Kumar K.V }
1136b6a758ecSAneesh Kumar K.V 
11378a57d9d6SCurt Wohlgemuth /*
11388a57d9d6SCurt Wohlgemuth  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
11398a57d9d6SCurt Wohlgemuth  * block group lock of all groups for this page; do not hold the BG lock when
11408a57d9d6SCurt Wohlgemuth  * calling this routine!
11418a57d9d6SCurt Wohlgemuth  */
11424ddfef7bSEric Sandeen static noinline_for_stack int
11434ddfef7bSEric Sandeen ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1144c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1145c9de560dSAlex Tomas {
1146c9de560dSAlex Tomas 	int blocks_per_page;
1147c9de560dSAlex Tomas 	int block;
1148c9de560dSAlex Tomas 	int pnum;
1149c9de560dSAlex Tomas 	int poff;
1150c9de560dSAlex Tomas 	struct page *page;
1151fdf6c7a7SShen Feng 	int ret;
1152920313a7SAneesh Kumar K.V 	struct ext4_group_info *grp;
1153920313a7SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1154920313a7SAneesh Kumar K.V 	struct inode *inode = sbi->s_buddy_cache;
1155c9de560dSAlex Tomas 
11566ba495e9STheodore Ts'o 	mb_debug(1, "load group %u\n", group);
1157c9de560dSAlex Tomas 
1158c9de560dSAlex Tomas 	blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1159920313a7SAneesh Kumar K.V 	grp = ext4_get_group_info(sb, group);
1160c9de560dSAlex Tomas 
1161c9de560dSAlex Tomas 	e4b->bd_blkbits = sb->s_blocksize_bits;
1162c9de560dSAlex Tomas 	e4b->bd_info = ext4_get_group_info(sb, group);
1163c9de560dSAlex Tomas 	e4b->bd_sb = sb;
1164c9de560dSAlex Tomas 	e4b->bd_group = group;
1165c9de560dSAlex Tomas 	e4b->bd_buddy_page = NULL;
1166c9de560dSAlex Tomas 	e4b->bd_bitmap_page = NULL;
1167920313a7SAneesh Kumar K.V 	e4b->alloc_semp = &grp->alloc_sem;
1168920313a7SAneesh Kumar K.V 
1169920313a7SAneesh Kumar K.V 	/* Take the read lock on the group alloc
1170920313a7SAneesh Kumar K.V 	 * sem. This would make sure a parallel
1171920313a7SAneesh Kumar K.V 	 * ext4_mb_init_group happening on other
1172920313a7SAneesh Kumar K.V 	 * groups mapped by the page is blocked
1173920313a7SAneesh Kumar K.V 	 * till we are done with allocation
1174920313a7SAneesh Kumar K.V 	 */
1175f41c0750SAneesh Kumar K.V repeat_load_buddy:
1176920313a7SAneesh Kumar K.V 	down_read(e4b->alloc_semp);
1177c9de560dSAlex Tomas 
1178f41c0750SAneesh Kumar K.V 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1179f41c0750SAneesh Kumar K.V 		/* we need to check for group need init flag
1180f41c0750SAneesh Kumar K.V 		 * with alloc_semp held so that we can be sure
1181f41c0750SAneesh Kumar K.V 		 * that new blocks didn't get added to the group
1182f41c0750SAneesh Kumar K.V 		 * when we are loading the buddy cache
1183f41c0750SAneesh Kumar K.V 		 */
1184f41c0750SAneesh Kumar K.V 		up_read(e4b->alloc_semp);
1185f41c0750SAneesh Kumar K.V 		/*
1186f41c0750SAneesh Kumar K.V 		 * we need full data about the group
1187f41c0750SAneesh Kumar K.V 		 * to make a good selection
1188f41c0750SAneesh Kumar K.V 		 */
1189f41c0750SAneesh Kumar K.V 		ret = ext4_mb_init_group(sb, group);
1190f41c0750SAneesh Kumar K.V 		if (ret)
1191f41c0750SAneesh Kumar K.V 			return ret;
1192f41c0750SAneesh Kumar K.V 		goto repeat_load_buddy;
1193f41c0750SAneesh Kumar K.V 	}
1194f41c0750SAneesh Kumar K.V 
1195c9de560dSAlex Tomas 	/*
1196c9de560dSAlex Tomas 	 * the buddy cache inode stores the block bitmap
1197c9de560dSAlex Tomas 	 * and buddy information in consecutive blocks.
1198c9de560dSAlex Tomas 	 * So for each group we need two blocks.
1199c9de560dSAlex Tomas 	 */
1200c9de560dSAlex Tomas 	block = group * 2;
1201c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1202c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1203c9de560dSAlex Tomas 
1204c9de560dSAlex Tomas 	/* we could use find_or_create_page(), but it locks page
1205c9de560dSAlex Tomas 	 * what we'd like to avoid in fast path ... */
1206c9de560dSAlex Tomas 	page = find_get_page(inode->i_mapping, pnum);
1207c9de560dSAlex Tomas 	if (page == NULL || !PageUptodate(page)) {
1208c9de560dSAlex Tomas 		if (page)
1209920313a7SAneesh Kumar K.V 			/*
1210920313a7SAneesh Kumar K.V 			 * drop the page reference and try
1211920313a7SAneesh Kumar K.V 			 * to get the page with lock. If we
1212920313a7SAneesh Kumar K.V 			 * are not uptodate that implies
1213920313a7SAneesh Kumar K.V 			 * somebody just created the page but
1214920313a7SAneesh Kumar K.V 			 * is yet to initialize the same. So
1215920313a7SAneesh Kumar K.V 			 * wait for it to initialize.
1216920313a7SAneesh Kumar K.V 			 */
1217c9de560dSAlex Tomas 			page_cache_release(page);
1218c9de560dSAlex Tomas 		page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1219c9de560dSAlex Tomas 		if (page) {
1220c9de560dSAlex Tomas 			BUG_ON(page->mapping != inode->i_mapping);
1221c9de560dSAlex Tomas 			if (!PageUptodate(page)) {
1222fdf6c7a7SShen Feng 				ret = ext4_mb_init_cache(page, NULL);
1223fdf6c7a7SShen Feng 				if (ret) {
1224fdf6c7a7SShen Feng 					unlock_page(page);
1225fdf6c7a7SShen Feng 					goto err;
1226fdf6c7a7SShen Feng 				}
1227c9de560dSAlex Tomas 				mb_cmp_bitmaps(e4b, page_address(page) +
1228c9de560dSAlex Tomas 					       (poff * sb->s_blocksize));
1229c9de560dSAlex Tomas 			}
1230c9de560dSAlex Tomas 			unlock_page(page);
1231c9de560dSAlex Tomas 		}
1232c9de560dSAlex Tomas 	}
1233fdf6c7a7SShen Feng 	if (page == NULL || !PageUptodate(page)) {
1234fdf6c7a7SShen Feng 		ret = -EIO;
1235c9de560dSAlex Tomas 		goto err;
1236fdf6c7a7SShen Feng 	}
1237c9de560dSAlex Tomas 	e4b->bd_bitmap_page = page;
1238c9de560dSAlex Tomas 	e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1239c9de560dSAlex Tomas 	mark_page_accessed(page);
1240c9de560dSAlex Tomas 
1241c9de560dSAlex Tomas 	block++;
1242c9de560dSAlex Tomas 	pnum = block / blocks_per_page;
1243c9de560dSAlex Tomas 	poff = block % blocks_per_page;
1244c9de560dSAlex Tomas 
1245c9de560dSAlex Tomas 	page = find_get_page(inode->i_mapping, pnum);
1246c9de560dSAlex Tomas 	if (page == NULL || !PageUptodate(page)) {
1247c9de560dSAlex Tomas 		if (page)
1248c9de560dSAlex Tomas 			page_cache_release(page);
1249c9de560dSAlex Tomas 		page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1250c9de560dSAlex Tomas 		if (page) {
1251c9de560dSAlex Tomas 			BUG_ON(page->mapping != inode->i_mapping);
1252fdf6c7a7SShen Feng 			if (!PageUptodate(page)) {
1253fdf6c7a7SShen Feng 				ret = ext4_mb_init_cache(page, e4b->bd_bitmap);
1254fdf6c7a7SShen Feng 				if (ret) {
1255fdf6c7a7SShen Feng 					unlock_page(page);
1256fdf6c7a7SShen Feng 					goto err;
1257fdf6c7a7SShen Feng 				}
1258fdf6c7a7SShen Feng 			}
1259c9de560dSAlex Tomas 			unlock_page(page);
1260c9de560dSAlex Tomas 		}
1261c9de560dSAlex Tomas 	}
1262fdf6c7a7SShen Feng 	if (page == NULL || !PageUptodate(page)) {
1263fdf6c7a7SShen Feng 		ret = -EIO;
1264c9de560dSAlex Tomas 		goto err;
1265fdf6c7a7SShen Feng 	}
1266c9de560dSAlex Tomas 	e4b->bd_buddy_page = page;
1267c9de560dSAlex Tomas 	e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1268c9de560dSAlex Tomas 	mark_page_accessed(page);
1269c9de560dSAlex Tomas 
1270c9de560dSAlex Tomas 	BUG_ON(e4b->bd_bitmap_page == NULL);
1271c9de560dSAlex Tomas 	BUG_ON(e4b->bd_buddy_page == NULL);
1272c9de560dSAlex Tomas 
1273c9de560dSAlex Tomas 	return 0;
1274c9de560dSAlex Tomas 
1275c9de560dSAlex Tomas err:
1276*26626f11SYang Ruirui 	if (page)
1277*26626f11SYang Ruirui 		page_cache_release(page);
1278c9de560dSAlex Tomas 	if (e4b->bd_bitmap_page)
1279c9de560dSAlex Tomas 		page_cache_release(e4b->bd_bitmap_page);
1280c9de560dSAlex Tomas 	if (e4b->bd_buddy_page)
1281c9de560dSAlex Tomas 		page_cache_release(e4b->bd_buddy_page);
1282c9de560dSAlex Tomas 	e4b->bd_buddy = NULL;
1283c9de560dSAlex Tomas 	e4b->bd_bitmap = NULL;
1284920313a7SAneesh Kumar K.V 
1285920313a7SAneesh Kumar K.V 	/* Done with the buddy cache */
1286920313a7SAneesh Kumar K.V 	up_read(e4b->alloc_semp);
1287fdf6c7a7SShen Feng 	return ret;
1288c9de560dSAlex Tomas }
1289c9de560dSAlex Tomas 
1290e39e07fdSJing Zhang static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1291c9de560dSAlex Tomas {
1292c9de560dSAlex Tomas 	if (e4b->bd_bitmap_page)
1293c9de560dSAlex Tomas 		page_cache_release(e4b->bd_bitmap_page);
1294c9de560dSAlex Tomas 	if (e4b->bd_buddy_page)
1295c9de560dSAlex Tomas 		page_cache_release(e4b->bd_buddy_page);
1296920313a7SAneesh Kumar K.V 	/* Done with the buddy cache */
12978556e8f3SAneesh Kumar K.V 	if (e4b->alloc_semp)
1298920313a7SAneesh Kumar K.V 		up_read(e4b->alloc_semp);
1299c9de560dSAlex Tomas }
1300c9de560dSAlex Tomas 
1301c9de560dSAlex Tomas 
1302c9de560dSAlex Tomas static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1303c9de560dSAlex Tomas {
1304c9de560dSAlex Tomas 	int order = 1;
1305c9de560dSAlex Tomas 	void *bb;
1306c9de560dSAlex Tomas 
1307c9de560dSAlex Tomas 	BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
1308c9de560dSAlex Tomas 	BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1309c9de560dSAlex Tomas 
1310c9de560dSAlex Tomas 	bb = EXT4_MB_BUDDY(e4b);
1311c9de560dSAlex Tomas 	while (order <= e4b->bd_blkbits + 1) {
1312c9de560dSAlex Tomas 		block = block >> 1;
1313c9de560dSAlex Tomas 		if (!mb_test_bit(block, bb)) {
1314c9de560dSAlex Tomas 			/* this block is part of buddy of order 'order' */
1315c9de560dSAlex Tomas 			return order;
1316c9de560dSAlex Tomas 		}
1317c9de560dSAlex Tomas 		bb += 1 << (e4b->bd_blkbits - order);
1318c9de560dSAlex Tomas 		order++;
1319c9de560dSAlex Tomas 	}
1320c9de560dSAlex Tomas 	return 0;
1321c9de560dSAlex Tomas }
1322c9de560dSAlex Tomas 
1323955ce5f5SAneesh Kumar K.V static void mb_clear_bits(void *bm, int cur, int len)
1324c9de560dSAlex Tomas {
1325c9de560dSAlex Tomas 	__u32 *addr;
1326c9de560dSAlex Tomas 
1327c9de560dSAlex Tomas 	len = cur + len;
1328c9de560dSAlex Tomas 	while (cur < len) {
1329c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1330c9de560dSAlex Tomas 			/* fast path: clear whole word at once */
1331c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1332c9de560dSAlex Tomas 			*addr = 0;
1333c9de560dSAlex Tomas 			cur += 32;
1334c9de560dSAlex Tomas 			continue;
1335c9de560dSAlex Tomas 		}
1336e8134b27SAneesh Kumar K.V 		mb_clear_bit(cur, bm);
1337c9de560dSAlex Tomas 		cur++;
1338c9de560dSAlex Tomas 	}
1339c9de560dSAlex Tomas }
1340c9de560dSAlex Tomas 
1341955ce5f5SAneesh Kumar K.V static void mb_set_bits(void *bm, int cur, int len)
1342c9de560dSAlex Tomas {
1343c9de560dSAlex Tomas 	__u32 *addr;
1344c9de560dSAlex Tomas 
1345c9de560dSAlex Tomas 	len = cur + len;
1346c9de560dSAlex Tomas 	while (cur < len) {
1347c9de560dSAlex Tomas 		if ((cur & 31) == 0 && (len - cur) >= 32) {
1348c9de560dSAlex Tomas 			/* fast path: set whole word at once */
1349c9de560dSAlex Tomas 			addr = bm + (cur >> 3);
1350c9de560dSAlex Tomas 			*addr = 0xffffffff;
1351c9de560dSAlex Tomas 			cur += 32;
1352c9de560dSAlex Tomas 			continue;
1353c9de560dSAlex Tomas 		}
1354e8134b27SAneesh Kumar K.V 		mb_set_bit(cur, bm);
1355c9de560dSAlex Tomas 		cur++;
1356c9de560dSAlex Tomas 	}
1357c9de560dSAlex Tomas }
1358c9de560dSAlex Tomas 
13597e5a8cddSShen Feng static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1360c9de560dSAlex Tomas 			  int first, int count)
1361c9de560dSAlex Tomas {
1362c9de560dSAlex Tomas 	int block = 0;
1363c9de560dSAlex Tomas 	int max = 0;
1364c9de560dSAlex Tomas 	int order;
1365c9de560dSAlex Tomas 	void *buddy;
1366c9de560dSAlex Tomas 	void *buddy2;
1367c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
1368c9de560dSAlex Tomas 
1369c9de560dSAlex Tomas 	BUG_ON(first + count > (sb->s_blocksize << 3));
1370bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1371c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1372c9de560dSAlex Tomas 	mb_free_blocks_double(inode, e4b, first, count);
1373c9de560dSAlex Tomas 
1374c9de560dSAlex Tomas 	e4b->bd_info->bb_free += count;
1375c9de560dSAlex Tomas 	if (first < e4b->bd_info->bb_first_free)
1376c9de560dSAlex Tomas 		e4b->bd_info->bb_first_free = first;
1377c9de560dSAlex Tomas 
1378c9de560dSAlex Tomas 	/* let's maintain fragments counter */
1379c9de560dSAlex Tomas 	if (first != 0)
1380c9de560dSAlex Tomas 		block = !mb_test_bit(first - 1, EXT4_MB_BITMAP(e4b));
1381c9de560dSAlex Tomas 	if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
1382c9de560dSAlex Tomas 		max = !mb_test_bit(first + count, EXT4_MB_BITMAP(e4b));
1383c9de560dSAlex Tomas 	if (block && max)
1384c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments--;
1385c9de560dSAlex Tomas 	else if (!block && !max)
1386c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments++;
1387c9de560dSAlex Tomas 
1388c9de560dSAlex Tomas 	/* let's maintain buddy itself */
1389c9de560dSAlex Tomas 	while (count-- > 0) {
1390c9de560dSAlex Tomas 		block = first++;
1391c9de560dSAlex Tomas 		order = 0;
1392c9de560dSAlex Tomas 
1393c9de560dSAlex Tomas 		if (!mb_test_bit(block, EXT4_MB_BITMAP(e4b))) {
1394c9de560dSAlex Tomas 			ext4_fsblk_t blocknr;
13955661bd68SAkinobu Mita 
13965661bd68SAkinobu Mita 			blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1397c9de560dSAlex Tomas 			blocknr += block;
13985d1b1b3fSAneesh Kumar K.V 			ext4_grp_locked_error(sb, e4b->bd_group,
1399e29136f8STheodore Ts'o 					      inode ? inode->i_ino : 0,
1400e29136f8STheodore Ts'o 					      blocknr,
1401e29136f8STheodore Ts'o 					      "freeing already freed block "
1402e29136f8STheodore Ts'o 					      "(bit %u)", block);
1403c9de560dSAlex Tomas 		}
1404c9de560dSAlex Tomas 		mb_clear_bit(block, EXT4_MB_BITMAP(e4b));
1405c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[order]++;
1406c9de560dSAlex Tomas 
1407c9de560dSAlex Tomas 		/* start of the buddy */
1408c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, order, &max);
1409c9de560dSAlex Tomas 
1410c9de560dSAlex Tomas 		do {
1411c9de560dSAlex Tomas 			block &= ~1UL;
1412c9de560dSAlex Tomas 			if (mb_test_bit(block, buddy) ||
1413c9de560dSAlex Tomas 					mb_test_bit(block + 1, buddy))
1414c9de560dSAlex Tomas 				break;
1415c9de560dSAlex Tomas 
1416c9de560dSAlex Tomas 			/* both the buddies are free, try to coalesce them */
1417c9de560dSAlex Tomas 			buddy2 = mb_find_buddy(e4b, order + 1, &max);
1418c9de560dSAlex Tomas 
1419c9de560dSAlex Tomas 			if (!buddy2)
1420c9de560dSAlex Tomas 				break;
1421c9de560dSAlex Tomas 
1422c9de560dSAlex Tomas 			if (order > 0) {
1423c9de560dSAlex Tomas 				/* for special purposes, we don't set
1424c9de560dSAlex Tomas 				 * free bits in bitmap */
1425c9de560dSAlex Tomas 				mb_set_bit(block, buddy);
1426c9de560dSAlex Tomas 				mb_set_bit(block + 1, buddy);
1427c9de560dSAlex Tomas 			}
1428c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[order]--;
1429c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[order]--;
1430c9de560dSAlex Tomas 
1431c9de560dSAlex Tomas 			block = block >> 1;
1432c9de560dSAlex Tomas 			order++;
1433c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[order]++;
1434c9de560dSAlex Tomas 
1435c9de560dSAlex Tomas 			mb_clear_bit(block, buddy2);
1436c9de560dSAlex Tomas 			buddy = buddy2;
1437c9de560dSAlex Tomas 		} while (1);
1438c9de560dSAlex Tomas 	}
14398a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(sb, e4b->bd_info);
1440c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1441c9de560dSAlex Tomas }
1442c9de560dSAlex Tomas 
1443c9de560dSAlex Tomas static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
1444c9de560dSAlex Tomas 				int needed, struct ext4_free_extent *ex)
1445c9de560dSAlex Tomas {
1446c9de560dSAlex Tomas 	int next = block;
1447c9de560dSAlex Tomas 	int max;
1448c9de560dSAlex Tomas 	int ord;
1449c9de560dSAlex Tomas 	void *buddy;
1450c9de560dSAlex Tomas 
1451bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1452c9de560dSAlex Tomas 	BUG_ON(ex == NULL);
1453c9de560dSAlex Tomas 
1454c9de560dSAlex Tomas 	buddy = mb_find_buddy(e4b, order, &max);
1455c9de560dSAlex Tomas 	BUG_ON(buddy == NULL);
1456c9de560dSAlex Tomas 	BUG_ON(block >= max);
1457c9de560dSAlex Tomas 	if (mb_test_bit(block, buddy)) {
1458c9de560dSAlex Tomas 		ex->fe_len = 0;
1459c9de560dSAlex Tomas 		ex->fe_start = 0;
1460c9de560dSAlex Tomas 		ex->fe_group = 0;
1461c9de560dSAlex Tomas 		return 0;
1462c9de560dSAlex Tomas 	}
1463c9de560dSAlex Tomas 
1464c9de560dSAlex Tomas 	/* FIXME dorp order completely ? */
1465c9de560dSAlex Tomas 	if (likely(order == 0)) {
1466c9de560dSAlex Tomas 		/* find actual order */
1467c9de560dSAlex Tomas 		order = mb_find_order_for_block(e4b, block);
1468c9de560dSAlex Tomas 		block = block >> order;
1469c9de560dSAlex Tomas 	}
1470c9de560dSAlex Tomas 
1471c9de560dSAlex Tomas 	ex->fe_len = 1 << order;
1472c9de560dSAlex Tomas 	ex->fe_start = block << order;
1473c9de560dSAlex Tomas 	ex->fe_group = e4b->bd_group;
1474c9de560dSAlex Tomas 
1475c9de560dSAlex Tomas 	/* calc difference from given start */
1476c9de560dSAlex Tomas 	next = next - ex->fe_start;
1477c9de560dSAlex Tomas 	ex->fe_len -= next;
1478c9de560dSAlex Tomas 	ex->fe_start += next;
1479c9de560dSAlex Tomas 
1480c9de560dSAlex Tomas 	while (needed > ex->fe_len &&
1481c9de560dSAlex Tomas 	       (buddy = mb_find_buddy(e4b, order, &max))) {
1482c9de560dSAlex Tomas 
1483c9de560dSAlex Tomas 		if (block + 1 >= max)
1484c9de560dSAlex Tomas 			break;
1485c9de560dSAlex Tomas 
1486c9de560dSAlex Tomas 		next = (block + 1) * (1 << order);
1487c9de560dSAlex Tomas 		if (mb_test_bit(next, EXT4_MB_BITMAP(e4b)))
1488c9de560dSAlex Tomas 			break;
1489c9de560dSAlex Tomas 
1490c9de560dSAlex Tomas 		ord = mb_find_order_for_block(e4b, next);
1491c9de560dSAlex Tomas 
1492c9de560dSAlex Tomas 		order = ord;
1493c9de560dSAlex Tomas 		block = next >> order;
1494c9de560dSAlex Tomas 		ex->fe_len += 1 << order;
1495c9de560dSAlex Tomas 	}
1496c9de560dSAlex Tomas 
1497c9de560dSAlex Tomas 	BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1498c9de560dSAlex Tomas 	return ex->fe_len;
1499c9de560dSAlex Tomas }
1500c9de560dSAlex Tomas 
1501c9de560dSAlex Tomas static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1502c9de560dSAlex Tomas {
1503c9de560dSAlex Tomas 	int ord;
1504c9de560dSAlex Tomas 	int mlen = 0;
1505c9de560dSAlex Tomas 	int max = 0;
1506c9de560dSAlex Tomas 	int cur;
1507c9de560dSAlex Tomas 	int start = ex->fe_start;
1508c9de560dSAlex Tomas 	int len = ex->fe_len;
1509c9de560dSAlex Tomas 	unsigned ret = 0;
1510c9de560dSAlex Tomas 	int len0 = len;
1511c9de560dSAlex Tomas 	void *buddy;
1512c9de560dSAlex Tomas 
1513c9de560dSAlex Tomas 	BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1514c9de560dSAlex Tomas 	BUG_ON(e4b->bd_group != ex->fe_group);
1515bc8e6740SVincent Minet 	assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1516c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1517c9de560dSAlex Tomas 	mb_mark_used_double(e4b, start, len);
1518c9de560dSAlex Tomas 
1519c9de560dSAlex Tomas 	e4b->bd_info->bb_free -= len;
1520c9de560dSAlex Tomas 	if (e4b->bd_info->bb_first_free == start)
1521c9de560dSAlex Tomas 		e4b->bd_info->bb_first_free += len;
1522c9de560dSAlex Tomas 
1523c9de560dSAlex Tomas 	/* let's maintain fragments counter */
1524c9de560dSAlex Tomas 	if (start != 0)
1525c9de560dSAlex Tomas 		mlen = !mb_test_bit(start - 1, EXT4_MB_BITMAP(e4b));
1526c9de560dSAlex Tomas 	if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1527c9de560dSAlex Tomas 		max = !mb_test_bit(start + len, EXT4_MB_BITMAP(e4b));
1528c9de560dSAlex Tomas 	if (mlen && max)
1529c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments++;
1530c9de560dSAlex Tomas 	else if (!mlen && !max)
1531c9de560dSAlex Tomas 		e4b->bd_info->bb_fragments--;
1532c9de560dSAlex Tomas 
1533c9de560dSAlex Tomas 	/* let's maintain buddy itself */
1534c9de560dSAlex Tomas 	while (len) {
1535c9de560dSAlex Tomas 		ord = mb_find_order_for_block(e4b, start);
1536c9de560dSAlex Tomas 
1537c9de560dSAlex Tomas 		if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1538c9de560dSAlex Tomas 			/* the whole chunk may be allocated at once! */
1539c9de560dSAlex Tomas 			mlen = 1 << ord;
1540c9de560dSAlex Tomas 			buddy = mb_find_buddy(e4b, ord, &max);
1541c9de560dSAlex Tomas 			BUG_ON((start >> ord) >= max);
1542c9de560dSAlex Tomas 			mb_set_bit(start >> ord, buddy);
1543c9de560dSAlex Tomas 			e4b->bd_info->bb_counters[ord]--;
1544c9de560dSAlex Tomas 			start += mlen;
1545c9de560dSAlex Tomas 			len -= mlen;
1546c9de560dSAlex Tomas 			BUG_ON(len < 0);
1547c9de560dSAlex Tomas 			continue;
1548c9de560dSAlex Tomas 		}
1549c9de560dSAlex Tomas 
1550c9de560dSAlex Tomas 		/* store for history */
1551c9de560dSAlex Tomas 		if (ret == 0)
1552c9de560dSAlex Tomas 			ret = len | (ord << 16);
1553c9de560dSAlex Tomas 
1554c9de560dSAlex Tomas 		/* we have to split large buddy */
1555c9de560dSAlex Tomas 		BUG_ON(ord <= 0);
1556c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, ord, &max);
1557c9de560dSAlex Tomas 		mb_set_bit(start >> ord, buddy);
1558c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]--;
1559c9de560dSAlex Tomas 
1560c9de560dSAlex Tomas 		ord--;
1561c9de560dSAlex Tomas 		cur = (start >> ord) & ~1U;
1562c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, ord, &max);
1563c9de560dSAlex Tomas 		mb_clear_bit(cur, buddy);
1564c9de560dSAlex Tomas 		mb_clear_bit(cur + 1, buddy);
1565c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]++;
1566c9de560dSAlex Tomas 		e4b->bd_info->bb_counters[ord]++;
1567c9de560dSAlex Tomas 	}
15688a57d9d6SCurt Wohlgemuth 	mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1569c9de560dSAlex Tomas 
1570955ce5f5SAneesh Kumar K.V 	mb_set_bits(EXT4_MB_BITMAP(e4b), ex->fe_start, len0);
1571c9de560dSAlex Tomas 	mb_check_buddy(e4b);
1572c9de560dSAlex Tomas 
1573c9de560dSAlex Tomas 	return ret;
1574c9de560dSAlex Tomas }
1575c9de560dSAlex Tomas 
1576c9de560dSAlex Tomas /*
1577c9de560dSAlex Tomas  * Must be called under group lock!
1578c9de560dSAlex Tomas  */
1579c9de560dSAlex Tomas static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1580c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1581c9de560dSAlex Tomas {
1582c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1583c9de560dSAlex Tomas 	int ret;
1584c9de560dSAlex Tomas 
1585c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1586c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1587c9de560dSAlex Tomas 
1588c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1589c9de560dSAlex Tomas 	ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1590c9de560dSAlex Tomas 	ret = mb_mark_used(e4b, &ac->ac_b_ex);
1591c9de560dSAlex Tomas 
1592c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
1593c9de560dSAlex Tomas 	 * allocated blocks for history */
1594c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
1595c9de560dSAlex Tomas 
1596c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
1597c9de560dSAlex Tomas 	ac->ac_tail = ret & 0xffff;
1598c9de560dSAlex Tomas 	ac->ac_buddy = ret >> 16;
1599c9de560dSAlex Tomas 
1600c3a326a6SAneesh Kumar K.V 	/*
1601c3a326a6SAneesh Kumar K.V 	 * take the page reference. We want the page to be pinned
1602c3a326a6SAneesh Kumar K.V 	 * so that we don't get a ext4_mb_init_cache_call for this
1603c3a326a6SAneesh Kumar K.V 	 * group until we update the bitmap. That would mean we
1604c3a326a6SAneesh Kumar K.V 	 * double allocate blocks. The reference is dropped
1605c3a326a6SAneesh Kumar K.V 	 * in ext4_mb_release_context
1606c3a326a6SAneesh Kumar K.V 	 */
1607c9de560dSAlex Tomas 	ac->ac_bitmap_page = e4b->bd_bitmap_page;
1608c9de560dSAlex Tomas 	get_page(ac->ac_bitmap_page);
1609c9de560dSAlex Tomas 	ac->ac_buddy_page = e4b->bd_buddy_page;
1610c9de560dSAlex Tomas 	get_page(ac->ac_buddy_page);
16118556e8f3SAneesh Kumar K.V 	/* on allocation we use ac to track the held semaphore */
16128556e8f3SAneesh Kumar K.V 	ac->alloc_semp =  e4b->alloc_semp;
16138556e8f3SAneesh Kumar K.V 	e4b->alloc_semp = NULL;
1614c9de560dSAlex Tomas 	/* store last allocated for subsequent stream allocation */
16154ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1616c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
1617c9de560dSAlex Tomas 		sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1618c9de560dSAlex Tomas 		sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1619c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
1620c9de560dSAlex Tomas 	}
1621c9de560dSAlex Tomas }
1622c9de560dSAlex Tomas 
1623c9de560dSAlex Tomas /*
1624c9de560dSAlex Tomas  * regular allocator, for general purposes allocation
1625c9de560dSAlex Tomas  */
1626c9de560dSAlex Tomas 
1627c9de560dSAlex Tomas static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1628c9de560dSAlex Tomas 					struct ext4_buddy *e4b,
1629c9de560dSAlex Tomas 					int finish_group)
1630c9de560dSAlex Tomas {
1631c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1632c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
1633c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
1634c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1635c9de560dSAlex Tomas 	int max;
1636c9de560dSAlex Tomas 
1637032115fcSAneesh Kumar K.V 	if (ac->ac_status == AC_STATUS_FOUND)
1638032115fcSAneesh Kumar K.V 		return;
1639c9de560dSAlex Tomas 	/*
1640c9de560dSAlex Tomas 	 * We don't want to scan for a whole year
1641c9de560dSAlex Tomas 	 */
1642c9de560dSAlex Tomas 	if (ac->ac_found > sbi->s_mb_max_to_scan &&
1643c9de560dSAlex Tomas 			!(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1644c9de560dSAlex Tomas 		ac->ac_status = AC_STATUS_BREAK;
1645c9de560dSAlex Tomas 		return;
1646c9de560dSAlex Tomas 	}
1647c9de560dSAlex Tomas 
1648c9de560dSAlex Tomas 	/*
1649c9de560dSAlex Tomas 	 * Haven't found good chunk so far, let's continue
1650c9de560dSAlex Tomas 	 */
1651c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len)
1652c9de560dSAlex Tomas 		return;
1653c9de560dSAlex Tomas 
1654c9de560dSAlex Tomas 	if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1655c9de560dSAlex Tomas 			&& bex->fe_group == e4b->bd_group) {
1656c9de560dSAlex Tomas 		/* recheck chunk's availability - we don't know
1657c9de560dSAlex Tomas 		 * when it was found (within this lock-unlock
1658c9de560dSAlex Tomas 		 * period or not) */
1659c9de560dSAlex Tomas 		max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
1660c9de560dSAlex Tomas 		if (max >= gex->fe_len) {
1661c9de560dSAlex Tomas 			ext4_mb_use_best_found(ac, e4b);
1662c9de560dSAlex Tomas 			return;
1663c9de560dSAlex Tomas 		}
1664c9de560dSAlex Tomas 	}
1665c9de560dSAlex Tomas }
1666c9de560dSAlex Tomas 
1667c9de560dSAlex Tomas /*
1668c9de560dSAlex Tomas  * The routine checks whether found extent is good enough. If it is,
1669c9de560dSAlex Tomas  * then the extent gets marked used and flag is set to the context
1670c9de560dSAlex Tomas  * to stop scanning. Otherwise, the extent is compared with the
1671c9de560dSAlex Tomas  * previous found extent and if new one is better, then it's stored
1672c9de560dSAlex Tomas  * in the context. Later, the best found extent will be used, if
1673c9de560dSAlex Tomas  * mballoc can't find good enough extent.
1674c9de560dSAlex Tomas  *
1675c9de560dSAlex Tomas  * FIXME: real allocation policy is to be designed yet!
1676c9de560dSAlex Tomas  */
1677c9de560dSAlex Tomas static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1678c9de560dSAlex Tomas 					struct ext4_free_extent *ex,
1679c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1680c9de560dSAlex Tomas {
1681c9de560dSAlex Tomas 	struct ext4_free_extent *bex = &ac->ac_b_ex;
1682c9de560dSAlex Tomas 	struct ext4_free_extent *gex = &ac->ac_g_ex;
1683c9de560dSAlex Tomas 
1684c9de560dSAlex Tomas 	BUG_ON(ex->fe_len <= 0);
16858d03c7a0SEric Sandeen 	BUG_ON(ex->fe_len > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1686c9de560dSAlex Tomas 	BUG_ON(ex->fe_start >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1687c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1688c9de560dSAlex Tomas 
1689c9de560dSAlex Tomas 	ac->ac_found++;
1690c9de560dSAlex Tomas 
1691c9de560dSAlex Tomas 	/*
1692c9de560dSAlex Tomas 	 * The special case - take what you catch first
1693c9de560dSAlex Tomas 	 */
1694c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1695c9de560dSAlex Tomas 		*bex = *ex;
1696c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1697c9de560dSAlex Tomas 		return;
1698c9de560dSAlex Tomas 	}
1699c9de560dSAlex Tomas 
1700c9de560dSAlex Tomas 	/*
1701c9de560dSAlex Tomas 	 * Let's check whether the chuck is good enough
1702c9de560dSAlex Tomas 	 */
1703c9de560dSAlex Tomas 	if (ex->fe_len == gex->fe_len) {
1704c9de560dSAlex Tomas 		*bex = *ex;
1705c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1706c9de560dSAlex Tomas 		return;
1707c9de560dSAlex Tomas 	}
1708c9de560dSAlex Tomas 
1709c9de560dSAlex Tomas 	/*
1710c9de560dSAlex Tomas 	 * If this is first found extent, just store it in the context
1711c9de560dSAlex Tomas 	 */
1712c9de560dSAlex Tomas 	if (bex->fe_len == 0) {
1713c9de560dSAlex Tomas 		*bex = *ex;
1714c9de560dSAlex Tomas 		return;
1715c9de560dSAlex Tomas 	}
1716c9de560dSAlex Tomas 
1717c9de560dSAlex Tomas 	/*
1718c9de560dSAlex Tomas 	 * If new found extent is better, store it in the context
1719c9de560dSAlex Tomas 	 */
1720c9de560dSAlex Tomas 	if (bex->fe_len < gex->fe_len) {
1721c9de560dSAlex Tomas 		/* if the request isn't satisfied, any found extent
1722c9de560dSAlex Tomas 		 * larger than previous best one is better */
1723c9de560dSAlex Tomas 		if (ex->fe_len > bex->fe_len)
1724c9de560dSAlex Tomas 			*bex = *ex;
1725c9de560dSAlex Tomas 	} else if (ex->fe_len > gex->fe_len) {
1726c9de560dSAlex Tomas 		/* if the request is satisfied, then we try to find
1727c9de560dSAlex Tomas 		 * an extent that still satisfy the request, but is
1728c9de560dSAlex Tomas 		 * smaller than previous one */
1729c9de560dSAlex Tomas 		if (ex->fe_len < bex->fe_len)
1730c9de560dSAlex Tomas 			*bex = *ex;
1731c9de560dSAlex Tomas 	}
1732c9de560dSAlex Tomas 
1733c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 0);
1734c9de560dSAlex Tomas }
1735c9de560dSAlex Tomas 
1736089ceeccSEric Sandeen static noinline_for_stack
1737089ceeccSEric Sandeen int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1738c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1739c9de560dSAlex Tomas {
1740c9de560dSAlex Tomas 	struct ext4_free_extent ex = ac->ac_b_ex;
1741c9de560dSAlex Tomas 	ext4_group_t group = ex.fe_group;
1742c9de560dSAlex Tomas 	int max;
1743c9de560dSAlex Tomas 	int err;
1744c9de560dSAlex Tomas 
1745c9de560dSAlex Tomas 	BUG_ON(ex.fe_len <= 0);
1746c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1747c9de560dSAlex Tomas 	if (err)
1748c9de560dSAlex Tomas 		return err;
1749c9de560dSAlex Tomas 
1750c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
1751c9de560dSAlex Tomas 	max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
1752c9de560dSAlex Tomas 
1753c9de560dSAlex Tomas 	if (max > 0) {
1754c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
1755c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1756c9de560dSAlex Tomas 	}
1757c9de560dSAlex Tomas 
1758c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
1759e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
1760c9de560dSAlex Tomas 
1761c9de560dSAlex Tomas 	return 0;
1762c9de560dSAlex Tomas }
1763c9de560dSAlex Tomas 
1764089ceeccSEric Sandeen static noinline_for_stack
1765089ceeccSEric Sandeen int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1766c9de560dSAlex Tomas 				struct ext4_buddy *e4b)
1767c9de560dSAlex Tomas {
1768c9de560dSAlex Tomas 	ext4_group_t group = ac->ac_g_ex.fe_group;
1769c9de560dSAlex Tomas 	int max;
1770c9de560dSAlex Tomas 	int err;
1771c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1772c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1773c9de560dSAlex Tomas 
1774c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1775c9de560dSAlex Tomas 		return 0;
1776c9de560dSAlex Tomas 
1777c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1778c9de560dSAlex Tomas 	if (err)
1779c9de560dSAlex Tomas 		return err;
1780c9de560dSAlex Tomas 
1781c9de560dSAlex Tomas 	ext4_lock_group(ac->ac_sb, group);
1782c9de560dSAlex Tomas 	max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
1783c9de560dSAlex Tomas 			     ac->ac_g_ex.fe_len, &ex);
1784c9de560dSAlex Tomas 
1785c9de560dSAlex Tomas 	if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1786c9de560dSAlex Tomas 		ext4_fsblk_t start;
1787c9de560dSAlex Tomas 
17885661bd68SAkinobu Mita 		start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
17895661bd68SAkinobu Mita 			ex.fe_start;
1790c9de560dSAlex Tomas 		/* use do_div to get remainder (would be 64-bit modulo) */
1791c9de560dSAlex Tomas 		if (do_div(start, sbi->s_stripe) == 0) {
1792c9de560dSAlex Tomas 			ac->ac_found++;
1793c9de560dSAlex Tomas 			ac->ac_b_ex = ex;
1794c9de560dSAlex Tomas 			ext4_mb_use_best_found(ac, e4b);
1795c9de560dSAlex Tomas 		}
1796c9de560dSAlex Tomas 	} else if (max >= ac->ac_g_ex.fe_len) {
1797c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
1798c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1799c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1800c9de560dSAlex Tomas 		ac->ac_found++;
1801c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
1802c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1803c9de560dSAlex Tomas 	} else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1804c9de560dSAlex Tomas 		/* Sometimes, caller may want to merge even small
1805c9de560dSAlex Tomas 		 * number of blocks to an existing extent */
1806c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
1807c9de560dSAlex Tomas 		BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1808c9de560dSAlex Tomas 		BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1809c9de560dSAlex Tomas 		ac->ac_found++;
1810c9de560dSAlex Tomas 		ac->ac_b_ex = ex;
1811c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1812c9de560dSAlex Tomas 	}
1813c9de560dSAlex Tomas 	ext4_unlock_group(ac->ac_sb, group);
1814e39e07fdSJing Zhang 	ext4_mb_unload_buddy(e4b);
1815c9de560dSAlex Tomas 
1816c9de560dSAlex Tomas 	return 0;
1817c9de560dSAlex Tomas }
1818c9de560dSAlex Tomas 
1819c9de560dSAlex Tomas /*
1820c9de560dSAlex Tomas  * The routine scans buddy structures (not bitmap!) from given order
1821c9de560dSAlex Tomas  * to max order and tries to find big enough chunk to satisfy the req
1822c9de560dSAlex Tomas  */
1823089ceeccSEric Sandeen static noinline_for_stack
1824089ceeccSEric Sandeen void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1825c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1826c9de560dSAlex Tomas {
1827c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
1828c9de560dSAlex Tomas 	struct ext4_group_info *grp = e4b->bd_info;
1829c9de560dSAlex Tomas 	void *buddy;
1830c9de560dSAlex Tomas 	int i;
1831c9de560dSAlex Tomas 	int k;
1832c9de560dSAlex Tomas 	int max;
1833c9de560dSAlex Tomas 
1834c9de560dSAlex Tomas 	BUG_ON(ac->ac_2order <= 0);
1835c9de560dSAlex Tomas 	for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1836c9de560dSAlex Tomas 		if (grp->bb_counters[i] == 0)
1837c9de560dSAlex Tomas 			continue;
1838c9de560dSAlex Tomas 
1839c9de560dSAlex Tomas 		buddy = mb_find_buddy(e4b, i, &max);
1840c9de560dSAlex Tomas 		BUG_ON(buddy == NULL);
1841c9de560dSAlex Tomas 
1842ffad0a44SAneesh Kumar K.V 		k = mb_find_next_zero_bit(buddy, max, 0);
1843c9de560dSAlex Tomas 		BUG_ON(k >= max);
1844c9de560dSAlex Tomas 
1845c9de560dSAlex Tomas 		ac->ac_found++;
1846c9de560dSAlex Tomas 
1847c9de560dSAlex Tomas 		ac->ac_b_ex.fe_len = 1 << i;
1848c9de560dSAlex Tomas 		ac->ac_b_ex.fe_start = k << i;
1849c9de560dSAlex Tomas 		ac->ac_b_ex.fe_group = e4b->bd_group;
1850c9de560dSAlex Tomas 
1851c9de560dSAlex Tomas 		ext4_mb_use_best_found(ac, e4b);
1852c9de560dSAlex Tomas 
1853c9de560dSAlex Tomas 		BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1854c9de560dSAlex Tomas 
1855c9de560dSAlex Tomas 		if (EXT4_SB(sb)->s_mb_stats)
1856c9de560dSAlex Tomas 			atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1857c9de560dSAlex Tomas 
1858c9de560dSAlex Tomas 		break;
1859c9de560dSAlex Tomas 	}
1860c9de560dSAlex Tomas }
1861c9de560dSAlex Tomas 
1862c9de560dSAlex Tomas /*
1863c9de560dSAlex Tomas  * The routine scans the group and measures all found extents.
1864c9de560dSAlex Tomas  * In order to optimize scanning, caller must pass number of
1865c9de560dSAlex Tomas  * free blocks in the group, so the routine can know upper limit.
1866c9de560dSAlex Tomas  */
1867089ceeccSEric Sandeen static noinline_for_stack
1868089ceeccSEric Sandeen void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1869c9de560dSAlex Tomas 					struct ext4_buddy *e4b)
1870c9de560dSAlex Tomas {
1871c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
1872c9de560dSAlex Tomas 	void *bitmap = EXT4_MB_BITMAP(e4b);
1873c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1874c9de560dSAlex Tomas 	int i;
1875c9de560dSAlex Tomas 	int free;
1876c9de560dSAlex Tomas 
1877c9de560dSAlex Tomas 	free = e4b->bd_info->bb_free;
1878c9de560dSAlex Tomas 	BUG_ON(free <= 0);
1879c9de560dSAlex Tomas 
1880c9de560dSAlex Tomas 	i = e4b->bd_info->bb_first_free;
1881c9de560dSAlex Tomas 
1882c9de560dSAlex Tomas 	while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1883ffad0a44SAneesh Kumar K.V 		i = mb_find_next_zero_bit(bitmap,
1884c9de560dSAlex Tomas 						EXT4_BLOCKS_PER_GROUP(sb), i);
1885c9de560dSAlex Tomas 		if (i >= EXT4_BLOCKS_PER_GROUP(sb)) {
188626346ff6SAneesh Kumar K.V 			/*
1887e56eb659SAneesh Kumar K.V 			 * IF we have corrupt bitmap, we won't find any
188826346ff6SAneesh Kumar K.V 			 * free blocks even though group info says we
188926346ff6SAneesh Kumar K.V 			 * we have free blocks
189026346ff6SAneesh Kumar K.V 			 */
1891e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1892e29136f8STheodore Ts'o 					"%d free blocks as per "
1893fde4d95aSTheodore Ts'o 					"group info. But bitmap says 0",
189426346ff6SAneesh Kumar K.V 					free);
1895c9de560dSAlex Tomas 			break;
1896c9de560dSAlex Tomas 		}
1897c9de560dSAlex Tomas 
1898c9de560dSAlex Tomas 		mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
1899c9de560dSAlex Tomas 		BUG_ON(ex.fe_len <= 0);
190026346ff6SAneesh Kumar K.V 		if (free < ex.fe_len) {
1901e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1902e29136f8STheodore Ts'o 					"%d free blocks as per "
1903fde4d95aSTheodore Ts'o 					"group info. But got %d blocks",
190426346ff6SAneesh Kumar K.V 					free, ex.fe_len);
1905e56eb659SAneesh Kumar K.V 			/*
1906e56eb659SAneesh Kumar K.V 			 * The number of free blocks differs. This mostly
1907e56eb659SAneesh Kumar K.V 			 * indicate that the bitmap is corrupt. So exit
1908e56eb659SAneesh Kumar K.V 			 * without claiming the space.
1909e56eb659SAneesh Kumar K.V 			 */
1910e56eb659SAneesh Kumar K.V 			break;
191126346ff6SAneesh Kumar K.V 		}
1912c9de560dSAlex Tomas 
1913c9de560dSAlex Tomas 		ext4_mb_measure_extent(ac, &ex, e4b);
1914c9de560dSAlex Tomas 
1915c9de560dSAlex Tomas 		i += ex.fe_len;
1916c9de560dSAlex Tomas 		free -= ex.fe_len;
1917c9de560dSAlex Tomas 	}
1918c9de560dSAlex Tomas 
1919c9de560dSAlex Tomas 	ext4_mb_check_limits(ac, e4b, 1);
1920c9de560dSAlex Tomas }
1921c9de560dSAlex Tomas 
1922c9de560dSAlex Tomas /*
1923c9de560dSAlex Tomas  * This is a special case for storages like raid5
1924506bf2d8SEric Sandeen  * we try to find stripe-aligned chunks for stripe-size-multiple requests
1925c9de560dSAlex Tomas  */
1926089ceeccSEric Sandeen static noinline_for_stack
1927089ceeccSEric Sandeen void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1928c9de560dSAlex Tomas 				 struct ext4_buddy *e4b)
1929c9de560dSAlex Tomas {
1930c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
1931c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1932c9de560dSAlex Tomas 	void *bitmap = EXT4_MB_BITMAP(e4b);
1933c9de560dSAlex Tomas 	struct ext4_free_extent ex;
1934c9de560dSAlex Tomas 	ext4_fsblk_t first_group_block;
1935c9de560dSAlex Tomas 	ext4_fsblk_t a;
1936c9de560dSAlex Tomas 	ext4_grpblk_t i;
1937c9de560dSAlex Tomas 	int max;
1938c9de560dSAlex Tomas 
1939c9de560dSAlex Tomas 	BUG_ON(sbi->s_stripe == 0);
1940c9de560dSAlex Tomas 
1941c9de560dSAlex Tomas 	/* find first stripe-aligned block in group */
19425661bd68SAkinobu Mita 	first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
19435661bd68SAkinobu Mita 
1944c9de560dSAlex Tomas 	a = first_group_block + sbi->s_stripe - 1;
1945c9de560dSAlex Tomas 	do_div(a, sbi->s_stripe);
1946c9de560dSAlex Tomas 	i = (a * sbi->s_stripe) - first_group_block;
1947c9de560dSAlex Tomas 
1948c9de560dSAlex Tomas 	while (i < EXT4_BLOCKS_PER_GROUP(sb)) {
1949c9de560dSAlex Tomas 		if (!mb_test_bit(i, bitmap)) {
1950c9de560dSAlex Tomas 			max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
1951c9de560dSAlex Tomas 			if (max >= sbi->s_stripe) {
1952c9de560dSAlex Tomas 				ac->ac_found++;
1953c9de560dSAlex Tomas 				ac->ac_b_ex = ex;
1954c9de560dSAlex Tomas 				ext4_mb_use_best_found(ac, e4b);
1955c9de560dSAlex Tomas 				break;
1956c9de560dSAlex Tomas 			}
1957c9de560dSAlex Tomas 		}
1958c9de560dSAlex Tomas 		i += sbi->s_stripe;
1959c9de560dSAlex Tomas 	}
1960c9de560dSAlex Tomas }
1961c9de560dSAlex Tomas 
19628a57d9d6SCurt Wohlgemuth /* This is now called BEFORE we load the buddy bitmap. */
1963c9de560dSAlex Tomas static int ext4_mb_good_group(struct ext4_allocation_context *ac,
1964c9de560dSAlex Tomas 				ext4_group_t group, int cr)
1965c9de560dSAlex Tomas {
1966c9de560dSAlex Tomas 	unsigned free, fragments;
1967a4912123STheodore Ts'o 	int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
1968c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1969c9de560dSAlex Tomas 
1970c9de560dSAlex Tomas 	BUG_ON(cr < 0 || cr >= 4);
19718a57d9d6SCurt Wohlgemuth 
19728a57d9d6SCurt Wohlgemuth 	/* We only do this if the grp has never been initialized */
19738a57d9d6SCurt Wohlgemuth 	if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
19748a57d9d6SCurt Wohlgemuth 		int ret = ext4_mb_init_group(ac->ac_sb, group);
19758a57d9d6SCurt Wohlgemuth 		if (ret)
19768a57d9d6SCurt Wohlgemuth 			return 0;
19778a57d9d6SCurt Wohlgemuth 	}
1978c9de560dSAlex Tomas 
1979c9de560dSAlex Tomas 	free = grp->bb_free;
1980c9de560dSAlex Tomas 	fragments = grp->bb_fragments;
1981c9de560dSAlex Tomas 	if (free == 0)
1982c9de560dSAlex Tomas 		return 0;
1983c9de560dSAlex Tomas 	if (fragments == 0)
1984c9de560dSAlex Tomas 		return 0;
1985c9de560dSAlex Tomas 
1986c9de560dSAlex Tomas 	switch (cr) {
1987c9de560dSAlex Tomas 	case 0:
1988c9de560dSAlex Tomas 		BUG_ON(ac->ac_2order == 0);
1989c9de560dSAlex Tomas 
19908a57d9d6SCurt Wohlgemuth 		if (grp->bb_largest_free_order < ac->ac_2order)
19918a57d9d6SCurt Wohlgemuth 			return 0;
19928a57d9d6SCurt Wohlgemuth 
1993a4912123STheodore Ts'o 		/* Avoid using the first bg of a flexgroup for data files */
1994a4912123STheodore Ts'o 		if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
1995a4912123STheodore Ts'o 		    (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
1996a4912123STheodore Ts'o 		    ((group % flex_size) == 0))
1997a4912123STheodore Ts'o 			return 0;
1998a4912123STheodore Ts'o 
1999c9de560dSAlex Tomas 		return 1;
2000c9de560dSAlex Tomas 	case 1:
2001c9de560dSAlex Tomas 		if ((free / fragments) >= ac->ac_g_ex.fe_len)
2002c9de560dSAlex Tomas 			return 1;
2003c9de560dSAlex Tomas 		break;
2004c9de560dSAlex Tomas 	case 2:
2005c9de560dSAlex Tomas 		if (free >= ac->ac_g_ex.fe_len)
2006c9de560dSAlex Tomas 			return 1;
2007c9de560dSAlex Tomas 		break;
2008c9de560dSAlex Tomas 	case 3:
2009c9de560dSAlex Tomas 		return 1;
2010c9de560dSAlex Tomas 	default:
2011c9de560dSAlex Tomas 		BUG();
2012c9de560dSAlex Tomas 	}
2013c9de560dSAlex Tomas 
2014c9de560dSAlex Tomas 	return 0;
2015c9de560dSAlex Tomas }
2016c9de560dSAlex Tomas 
20174ddfef7bSEric Sandeen static noinline_for_stack int
20184ddfef7bSEric Sandeen ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2019c9de560dSAlex Tomas {
20208df9675fSTheodore Ts'o 	ext4_group_t ngroups, group, i;
2021c9de560dSAlex Tomas 	int cr;
2022c9de560dSAlex Tomas 	int err = 0;
2023c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
2024c9de560dSAlex Tomas 	struct super_block *sb;
2025c9de560dSAlex Tomas 	struct ext4_buddy e4b;
2026c9de560dSAlex Tomas 
2027c9de560dSAlex Tomas 	sb = ac->ac_sb;
2028c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
20298df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
2030fb0a387dSEric Sandeen 	/* non-extent files are limited to low blocks/groups */
203112e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2032fb0a387dSEric Sandeen 		ngroups = sbi->s_blockfile_groups;
2033fb0a387dSEric Sandeen 
2034c9de560dSAlex Tomas 	BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2035c9de560dSAlex Tomas 
2036c9de560dSAlex Tomas 	/* first, try the goal */
2037c9de560dSAlex Tomas 	err = ext4_mb_find_by_goal(ac, &e4b);
2038c9de560dSAlex Tomas 	if (err || ac->ac_status == AC_STATUS_FOUND)
2039c9de560dSAlex Tomas 		goto out;
2040c9de560dSAlex Tomas 
2041c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2042c9de560dSAlex Tomas 		goto out;
2043c9de560dSAlex Tomas 
2044c9de560dSAlex Tomas 	/*
2045c9de560dSAlex Tomas 	 * ac->ac2_order is set only if the fe_len is a power of 2
2046c9de560dSAlex Tomas 	 * if ac2_order is set we also set criteria to 0 so that we
2047c9de560dSAlex Tomas 	 * try exact allocation using buddy.
2048c9de560dSAlex Tomas 	 */
2049c9de560dSAlex Tomas 	i = fls(ac->ac_g_ex.fe_len);
2050c9de560dSAlex Tomas 	ac->ac_2order = 0;
2051c9de560dSAlex Tomas 	/*
2052c9de560dSAlex Tomas 	 * We search using buddy data only if the order of the request
2053c9de560dSAlex Tomas 	 * is greater than equal to the sbi_s_mb_order2_reqs
2054b713a5ecSTheodore Ts'o 	 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2055c9de560dSAlex Tomas 	 */
2056c9de560dSAlex Tomas 	if (i >= sbi->s_mb_order2_reqs) {
2057c9de560dSAlex Tomas 		/*
2058c9de560dSAlex Tomas 		 * This should tell if fe_len is exactly power of 2
2059c9de560dSAlex Tomas 		 */
2060c9de560dSAlex Tomas 		if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2061c9de560dSAlex Tomas 			ac->ac_2order = i - 1;
2062c9de560dSAlex Tomas 	}
2063c9de560dSAlex Tomas 
20644ba74d00STheodore Ts'o 	/* if stream allocation is enabled, use global goal */
20654ba74d00STheodore Ts'o 	if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2066c9de560dSAlex Tomas 		/* TBD: may be hot point */
2067c9de560dSAlex Tomas 		spin_lock(&sbi->s_md_lock);
2068c9de560dSAlex Tomas 		ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2069c9de560dSAlex Tomas 		ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2070c9de560dSAlex Tomas 		spin_unlock(&sbi->s_md_lock);
2071c9de560dSAlex Tomas 	}
20724ba74d00STheodore Ts'o 
2073c9de560dSAlex Tomas 	/* Let's just scan groups to find more-less suitable blocks */
2074c9de560dSAlex Tomas 	cr = ac->ac_2order ? 0 : 1;
2075c9de560dSAlex Tomas 	/*
2076c9de560dSAlex Tomas 	 * cr == 0 try to get exact allocation,
2077c9de560dSAlex Tomas 	 * cr == 3  try to get anything
2078c9de560dSAlex Tomas 	 */
2079c9de560dSAlex Tomas repeat:
2080c9de560dSAlex Tomas 	for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2081c9de560dSAlex Tomas 		ac->ac_criteria = cr;
2082ed8f9c75SAneesh Kumar K.V 		/*
2083ed8f9c75SAneesh Kumar K.V 		 * searching for the right group start
2084ed8f9c75SAneesh Kumar K.V 		 * from the goal value specified
2085ed8f9c75SAneesh Kumar K.V 		 */
2086ed8f9c75SAneesh Kumar K.V 		group = ac->ac_g_ex.fe_group;
2087ed8f9c75SAneesh Kumar K.V 
20888df9675fSTheodore Ts'o 		for (i = 0; i < ngroups; group++, i++) {
20898df9675fSTheodore Ts'o 			if (group == ngroups)
2090c9de560dSAlex Tomas 				group = 0;
2091c9de560dSAlex Tomas 
20928a57d9d6SCurt Wohlgemuth 			/* This now checks without needing the buddy page */
20938a57d9d6SCurt Wohlgemuth 			if (!ext4_mb_good_group(ac, group, cr))
2094c9de560dSAlex Tomas 				continue;
2095c9de560dSAlex Tomas 
2096c9de560dSAlex Tomas 			err = ext4_mb_load_buddy(sb, group, &e4b);
2097c9de560dSAlex Tomas 			if (err)
2098c9de560dSAlex Tomas 				goto out;
2099c9de560dSAlex Tomas 
2100c9de560dSAlex Tomas 			ext4_lock_group(sb, group);
21018a57d9d6SCurt Wohlgemuth 
21028a57d9d6SCurt Wohlgemuth 			/*
21038a57d9d6SCurt Wohlgemuth 			 * We need to check again after locking the
21048a57d9d6SCurt Wohlgemuth 			 * block group
21058a57d9d6SCurt Wohlgemuth 			 */
2106c9de560dSAlex Tomas 			if (!ext4_mb_good_group(ac, group, cr)) {
2107c9de560dSAlex Tomas 				ext4_unlock_group(sb, group);
2108e39e07fdSJing Zhang 				ext4_mb_unload_buddy(&e4b);
2109c9de560dSAlex Tomas 				continue;
2110c9de560dSAlex Tomas 			}
2111c9de560dSAlex Tomas 
2112c9de560dSAlex Tomas 			ac->ac_groups_scanned++;
211375507efbSTheodore Ts'o 			if (cr == 0)
2114c9de560dSAlex Tomas 				ext4_mb_simple_scan_group(ac, &e4b);
2115506bf2d8SEric Sandeen 			else if (cr == 1 && sbi->s_stripe &&
2116506bf2d8SEric Sandeen 					!(ac->ac_g_ex.fe_len % sbi->s_stripe))
2117c9de560dSAlex Tomas 				ext4_mb_scan_aligned(ac, &e4b);
2118c9de560dSAlex Tomas 			else
2119c9de560dSAlex Tomas 				ext4_mb_complex_scan_group(ac, &e4b);
2120c9de560dSAlex Tomas 
2121c9de560dSAlex Tomas 			ext4_unlock_group(sb, group);
2122e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
2123c9de560dSAlex Tomas 
2124c9de560dSAlex Tomas 			if (ac->ac_status != AC_STATUS_CONTINUE)
2125c9de560dSAlex Tomas 				break;
2126c9de560dSAlex Tomas 		}
2127c9de560dSAlex Tomas 	}
2128c9de560dSAlex Tomas 
2129c9de560dSAlex Tomas 	if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2130c9de560dSAlex Tomas 	    !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2131c9de560dSAlex Tomas 		/*
2132c9de560dSAlex Tomas 		 * We've been searching too long. Let's try to allocate
2133c9de560dSAlex Tomas 		 * the best chunk we've found so far
2134c9de560dSAlex Tomas 		 */
2135c9de560dSAlex Tomas 
2136c9de560dSAlex Tomas 		ext4_mb_try_best_found(ac, &e4b);
2137c9de560dSAlex Tomas 		if (ac->ac_status != AC_STATUS_FOUND) {
2138c9de560dSAlex Tomas 			/*
2139c9de560dSAlex Tomas 			 * Someone more lucky has already allocated it.
2140c9de560dSAlex Tomas 			 * The only thing we can do is just take first
2141c9de560dSAlex Tomas 			 * found block(s)
2142c9de560dSAlex Tomas 			printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2143c9de560dSAlex Tomas 			 */
2144c9de560dSAlex Tomas 			ac->ac_b_ex.fe_group = 0;
2145c9de560dSAlex Tomas 			ac->ac_b_ex.fe_start = 0;
2146c9de560dSAlex Tomas 			ac->ac_b_ex.fe_len = 0;
2147c9de560dSAlex Tomas 			ac->ac_status = AC_STATUS_CONTINUE;
2148c9de560dSAlex Tomas 			ac->ac_flags |= EXT4_MB_HINT_FIRST;
2149c9de560dSAlex Tomas 			cr = 3;
2150c9de560dSAlex Tomas 			atomic_inc(&sbi->s_mb_lost_chunks);
2151c9de560dSAlex Tomas 			goto repeat;
2152c9de560dSAlex Tomas 		}
2153c9de560dSAlex Tomas 	}
2154c9de560dSAlex Tomas out:
2155c9de560dSAlex Tomas 	return err;
2156c9de560dSAlex Tomas }
2157c9de560dSAlex Tomas 
2158c9de560dSAlex Tomas static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2159c9de560dSAlex Tomas {
2160c9de560dSAlex Tomas 	struct super_block *sb = seq->private;
2161c9de560dSAlex Tomas 	ext4_group_t group;
2162c9de560dSAlex Tomas 
21638df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2164c9de560dSAlex Tomas 		return NULL;
2165c9de560dSAlex Tomas 	group = *pos + 1;
2166a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
2167c9de560dSAlex Tomas }
2168c9de560dSAlex Tomas 
2169c9de560dSAlex Tomas static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2170c9de560dSAlex Tomas {
2171c9de560dSAlex Tomas 	struct super_block *sb = seq->private;
2172c9de560dSAlex Tomas 	ext4_group_t group;
2173c9de560dSAlex Tomas 
2174c9de560dSAlex Tomas 	++*pos;
21758df9675fSTheodore Ts'o 	if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2176c9de560dSAlex Tomas 		return NULL;
2177c9de560dSAlex Tomas 	group = *pos + 1;
2178a9df9a49STheodore Ts'o 	return (void *) ((unsigned long) group);
2179c9de560dSAlex Tomas }
2180c9de560dSAlex Tomas 
2181c9de560dSAlex Tomas static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2182c9de560dSAlex Tomas {
2183c9de560dSAlex Tomas 	struct super_block *sb = seq->private;
2184a9df9a49STheodore Ts'o 	ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2185c9de560dSAlex Tomas 	int i;
2186c9de560dSAlex Tomas 	int err;
2187c9de560dSAlex Tomas 	struct ext4_buddy e4b;
2188c9de560dSAlex Tomas 	struct sg {
2189c9de560dSAlex Tomas 		struct ext4_group_info info;
2190a36b4498SEric Sandeen 		ext4_grpblk_t counters[16];
2191c9de560dSAlex Tomas 	} sg;
2192c9de560dSAlex Tomas 
2193c9de560dSAlex Tomas 	group--;
2194c9de560dSAlex Tomas 	if (group == 0)
2195c9de560dSAlex Tomas 		seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
2196c9de560dSAlex Tomas 				"[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2197c9de560dSAlex Tomas 				  "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2198c9de560dSAlex Tomas 			   "group", "free", "frags", "first",
2199c9de560dSAlex Tomas 			   "2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
2200c9de560dSAlex Tomas 			   "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2201c9de560dSAlex Tomas 
2202c9de560dSAlex Tomas 	i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2203c9de560dSAlex Tomas 		sizeof(struct ext4_group_info);
2204c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(sb, group, &e4b);
2205c9de560dSAlex Tomas 	if (err) {
2206a9df9a49STheodore Ts'o 		seq_printf(seq, "#%-5u: I/O error\n", group);
2207c9de560dSAlex Tomas 		return 0;
2208c9de560dSAlex Tomas 	}
2209c9de560dSAlex Tomas 	ext4_lock_group(sb, group);
2210c9de560dSAlex Tomas 	memcpy(&sg, ext4_get_group_info(sb, group), i);
2211c9de560dSAlex Tomas 	ext4_unlock_group(sb, group);
2212e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
2213c9de560dSAlex Tomas 
2214a9df9a49STheodore Ts'o 	seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2215c9de560dSAlex Tomas 			sg.info.bb_fragments, sg.info.bb_first_free);
2216c9de560dSAlex Tomas 	for (i = 0; i <= 13; i++)
2217c9de560dSAlex Tomas 		seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2218c9de560dSAlex Tomas 				sg.info.bb_counters[i] : 0);
2219c9de560dSAlex Tomas 	seq_printf(seq, " ]\n");
2220c9de560dSAlex Tomas 
2221c9de560dSAlex Tomas 	return 0;
2222c9de560dSAlex Tomas }
2223c9de560dSAlex Tomas 
2224c9de560dSAlex Tomas static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2225c9de560dSAlex Tomas {
2226c9de560dSAlex Tomas }
2227c9de560dSAlex Tomas 
22287f1346a9STobias Klauser static const struct seq_operations ext4_mb_seq_groups_ops = {
2229c9de560dSAlex Tomas 	.start  = ext4_mb_seq_groups_start,
2230c9de560dSAlex Tomas 	.next   = ext4_mb_seq_groups_next,
2231c9de560dSAlex Tomas 	.stop   = ext4_mb_seq_groups_stop,
2232c9de560dSAlex Tomas 	.show   = ext4_mb_seq_groups_show,
2233c9de560dSAlex Tomas };
2234c9de560dSAlex Tomas 
2235c9de560dSAlex Tomas static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2236c9de560dSAlex Tomas {
2237c9de560dSAlex Tomas 	struct super_block *sb = PDE(inode)->data;
2238c9de560dSAlex Tomas 	int rc;
2239c9de560dSAlex Tomas 
2240c9de560dSAlex Tomas 	rc = seq_open(file, &ext4_mb_seq_groups_ops);
2241c9de560dSAlex Tomas 	if (rc == 0) {
2242a271fe85SJoe Perches 		struct seq_file *m = file->private_data;
2243c9de560dSAlex Tomas 		m->private = sb;
2244c9de560dSAlex Tomas 	}
2245c9de560dSAlex Tomas 	return rc;
2246c9de560dSAlex Tomas 
2247c9de560dSAlex Tomas }
2248c9de560dSAlex Tomas 
22497f1346a9STobias Klauser static const struct file_operations ext4_mb_seq_groups_fops = {
2250c9de560dSAlex Tomas 	.owner		= THIS_MODULE,
2251c9de560dSAlex Tomas 	.open		= ext4_mb_seq_groups_open,
2252c9de560dSAlex Tomas 	.read		= seq_read,
2253c9de560dSAlex Tomas 	.llseek		= seq_lseek,
2254c9de560dSAlex Tomas 	.release	= seq_release,
2255c9de560dSAlex Tomas };
2256c9de560dSAlex Tomas 
2257fb1813f4SCurt Wohlgemuth static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2258fb1813f4SCurt Wohlgemuth {
2259fb1813f4SCurt Wohlgemuth 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2260fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2261fb1813f4SCurt Wohlgemuth 
2262fb1813f4SCurt Wohlgemuth 	BUG_ON(!cachep);
2263fb1813f4SCurt Wohlgemuth 	return cachep;
2264fb1813f4SCurt Wohlgemuth }
22655f21b0e6SFrederic Bohe 
22665f21b0e6SFrederic Bohe /* Create and initialize ext4_group_info data for the given group. */
2267920313a7SAneesh Kumar K.V int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
22685f21b0e6SFrederic Bohe 			  struct ext4_group_desc *desc)
22695f21b0e6SFrederic Bohe {
2270fb1813f4SCurt Wohlgemuth 	int i;
22715f21b0e6SFrederic Bohe 	int metalen = 0;
22725f21b0e6SFrederic Bohe 	struct ext4_sb_info *sbi = EXT4_SB(sb);
22735f21b0e6SFrederic Bohe 	struct ext4_group_info **meta_group_info;
2274fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
22755f21b0e6SFrederic Bohe 
22765f21b0e6SFrederic Bohe 	/*
22775f21b0e6SFrederic Bohe 	 * First check if this group is the first of a reserved block.
22785f21b0e6SFrederic Bohe 	 * If it's true, we have to allocate a new table of pointers
22795f21b0e6SFrederic Bohe 	 * to ext4_group_info structures
22805f21b0e6SFrederic Bohe 	 */
22815f21b0e6SFrederic Bohe 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
22825f21b0e6SFrederic Bohe 		metalen = sizeof(*meta_group_info) <<
22835f21b0e6SFrederic Bohe 			EXT4_DESC_PER_BLOCK_BITS(sb);
22845f21b0e6SFrederic Bohe 		meta_group_info = kmalloc(metalen, GFP_KERNEL);
22855f21b0e6SFrederic Bohe 		if (meta_group_info == NULL) {
22865f21b0e6SFrederic Bohe 			printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
22875f21b0e6SFrederic Bohe 			       "buddy group\n");
22885f21b0e6SFrederic Bohe 			goto exit_meta_group_info;
22895f21b0e6SFrederic Bohe 		}
22905f21b0e6SFrederic Bohe 		sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] =
22915f21b0e6SFrederic Bohe 			meta_group_info;
22925f21b0e6SFrederic Bohe 	}
22935f21b0e6SFrederic Bohe 
22945f21b0e6SFrederic Bohe 	meta_group_info =
22955f21b0e6SFrederic Bohe 		sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)];
22965f21b0e6SFrederic Bohe 	i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
22975f21b0e6SFrederic Bohe 
2298fb1813f4SCurt Wohlgemuth 	meta_group_info[i] = kmem_cache_alloc(cachep, GFP_KERNEL);
22995f21b0e6SFrederic Bohe 	if (meta_group_info[i] == NULL) {
23005f21b0e6SFrederic Bohe 		printk(KERN_ERR "EXT4-fs: can't allocate buddy mem\n");
23015f21b0e6SFrederic Bohe 		goto exit_group_info;
23025f21b0e6SFrederic Bohe 	}
2303fb1813f4SCurt Wohlgemuth 	memset(meta_group_info[i], 0, kmem_cache_size(cachep));
23045f21b0e6SFrederic Bohe 	set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
23055f21b0e6SFrederic Bohe 		&(meta_group_info[i]->bb_state));
23065f21b0e6SFrederic Bohe 
23075f21b0e6SFrederic Bohe 	/*
23085f21b0e6SFrederic Bohe 	 * initialize bb_free to be able to skip
23095f21b0e6SFrederic Bohe 	 * empty groups without initialization
23105f21b0e6SFrederic Bohe 	 */
23115f21b0e6SFrederic Bohe 	if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
23125f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
23135f21b0e6SFrederic Bohe 			ext4_free_blocks_after_init(sb, group, desc);
23145f21b0e6SFrederic Bohe 	} else {
23155f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_free =
2316560671a0SAneesh Kumar K.V 			ext4_free_blks_count(sb, desc);
23175f21b0e6SFrederic Bohe 	}
23185f21b0e6SFrederic Bohe 
23195f21b0e6SFrederic Bohe 	INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2320920313a7SAneesh Kumar K.V 	init_rwsem(&meta_group_info[i]->alloc_sem);
232164e290ecSVenkatesh Pallipadi 	meta_group_info[i]->bb_free_root = RB_ROOT;
23228a57d9d6SCurt Wohlgemuth 	meta_group_info[i]->bb_largest_free_order = -1;  /* uninit */
23235f21b0e6SFrederic Bohe 
23245f21b0e6SFrederic Bohe #ifdef DOUBLE_CHECK
23255f21b0e6SFrederic Bohe 	{
23265f21b0e6SFrederic Bohe 		struct buffer_head *bh;
23275f21b0e6SFrederic Bohe 		meta_group_info[i]->bb_bitmap =
23285f21b0e6SFrederic Bohe 			kmalloc(sb->s_blocksize, GFP_KERNEL);
23295f21b0e6SFrederic Bohe 		BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
23305f21b0e6SFrederic Bohe 		bh = ext4_read_block_bitmap(sb, group);
23315f21b0e6SFrederic Bohe 		BUG_ON(bh == NULL);
23325f21b0e6SFrederic Bohe 		memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
23335f21b0e6SFrederic Bohe 			sb->s_blocksize);
23345f21b0e6SFrederic Bohe 		put_bh(bh);
23355f21b0e6SFrederic Bohe 	}
23365f21b0e6SFrederic Bohe #endif
23375f21b0e6SFrederic Bohe 
23385f21b0e6SFrederic Bohe 	return 0;
23395f21b0e6SFrederic Bohe 
23405f21b0e6SFrederic Bohe exit_group_info:
23415f21b0e6SFrederic Bohe 	/* If a meta_group_info table has been allocated, release it now */
23425f21b0e6SFrederic Bohe 	if (group % EXT4_DESC_PER_BLOCK(sb) == 0)
23435f21b0e6SFrederic Bohe 		kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
23445f21b0e6SFrederic Bohe exit_meta_group_info:
23455f21b0e6SFrederic Bohe 	return -ENOMEM;
23465f21b0e6SFrederic Bohe } /* ext4_mb_add_groupinfo */
23475f21b0e6SFrederic Bohe 
2348c9de560dSAlex Tomas static int ext4_mb_init_backend(struct super_block *sb)
2349c9de560dSAlex Tomas {
23508df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
2351c9de560dSAlex Tomas 	ext4_group_t i;
2352c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
23535f21b0e6SFrederic Bohe 	struct ext4_super_block *es = sbi->s_es;
23545f21b0e6SFrederic Bohe 	int num_meta_group_infos;
23555f21b0e6SFrederic Bohe 	int num_meta_group_infos_max;
23565f21b0e6SFrederic Bohe 	int array_size;
23575f21b0e6SFrederic Bohe 	struct ext4_group_desc *desc;
2358fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep;
2359c9de560dSAlex Tomas 
23605f21b0e6SFrederic Bohe 	/* This is the number of blocks used by GDT */
23618df9675fSTheodore Ts'o 	num_meta_group_infos = (ngroups + EXT4_DESC_PER_BLOCK(sb) -
23625f21b0e6SFrederic Bohe 				1) >> EXT4_DESC_PER_BLOCK_BITS(sb);
23635f21b0e6SFrederic Bohe 
23645f21b0e6SFrederic Bohe 	/*
23655f21b0e6SFrederic Bohe 	 * This is the total number of blocks used by GDT including
23665f21b0e6SFrederic Bohe 	 * the number of reserved blocks for GDT.
23675f21b0e6SFrederic Bohe 	 * The s_group_info array is allocated with this value
23685f21b0e6SFrederic Bohe 	 * to allow a clean online resize without a complex
23695f21b0e6SFrederic Bohe 	 * manipulation of pointer.
23705f21b0e6SFrederic Bohe 	 * The drawback is the unused memory when no resize
23715f21b0e6SFrederic Bohe 	 * occurs but it's very low in terms of pages
23725f21b0e6SFrederic Bohe 	 * (see comments below)
23735f21b0e6SFrederic Bohe 	 * Need to handle this properly when META_BG resizing is allowed
23745f21b0e6SFrederic Bohe 	 */
23755f21b0e6SFrederic Bohe 	num_meta_group_infos_max = num_meta_group_infos +
23765f21b0e6SFrederic Bohe 				le16_to_cpu(es->s_reserved_gdt_blocks);
23775f21b0e6SFrederic Bohe 
23785f21b0e6SFrederic Bohe 	/*
23795f21b0e6SFrederic Bohe 	 * array_size is the size of s_group_info array. We round it
23805f21b0e6SFrederic Bohe 	 * to the next power of two because this approximation is done
23815f21b0e6SFrederic Bohe 	 * internally by kmalloc so we can have some more memory
23825f21b0e6SFrederic Bohe 	 * for free here (e.g. may be used for META_BG resize).
23835f21b0e6SFrederic Bohe 	 */
23845f21b0e6SFrederic Bohe 	array_size = 1;
23855f21b0e6SFrederic Bohe 	while (array_size < sizeof(*sbi->s_group_info) *
23865f21b0e6SFrederic Bohe 	       num_meta_group_infos_max)
23875f21b0e6SFrederic Bohe 		array_size = array_size << 1;
2388c9de560dSAlex Tomas 	/* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2389c9de560dSAlex Tomas 	 * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2390c9de560dSAlex Tomas 	 * So a two level scheme suffices for now. */
23914596fe07SEric Sandeen 	sbi->s_group_info = kzalloc(array_size, GFP_KERNEL);
2392c9de560dSAlex Tomas 	if (sbi->s_group_info == NULL) {
2393c9de560dSAlex Tomas 		printk(KERN_ERR "EXT4-fs: can't allocate buddy meta group\n");
2394c9de560dSAlex Tomas 		return -ENOMEM;
2395c9de560dSAlex Tomas 	}
2396c9de560dSAlex Tomas 	sbi->s_buddy_cache = new_inode(sb);
2397c9de560dSAlex Tomas 	if (sbi->s_buddy_cache == NULL) {
2398c9de560dSAlex Tomas 		printk(KERN_ERR "EXT4-fs: can't get new inode\n");
2399c9de560dSAlex Tomas 		goto err_freesgi;
2400c9de560dSAlex Tomas 	}
240185fe4025SChristoph Hellwig 	sbi->s_buddy_cache->i_ino = get_next_ino();
2402c9de560dSAlex Tomas 	EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
24038df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
2404c9de560dSAlex Tomas 		desc = ext4_get_group_desc(sb, i, NULL);
2405c9de560dSAlex Tomas 		if (desc == NULL) {
2406c9de560dSAlex Tomas 			printk(KERN_ERR
2407a9df9a49STheodore Ts'o 				"EXT4-fs: can't read descriptor %u\n", i);
2408c9de560dSAlex Tomas 			goto err_freebuddy;
2409c9de560dSAlex Tomas 		}
24105f21b0e6SFrederic Bohe 		if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
24115f21b0e6SFrederic Bohe 			goto err_freebuddy;
2412c9de560dSAlex Tomas 	}
2413c9de560dSAlex Tomas 
2414c9de560dSAlex Tomas 	return 0;
2415c9de560dSAlex Tomas 
2416c9de560dSAlex Tomas err_freebuddy:
2417fb1813f4SCurt Wohlgemuth 	cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2418f1fa3342SRoel Kluin 	while (i-- > 0)
2419fb1813f4SCurt Wohlgemuth 		kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2420c9de560dSAlex Tomas 	i = num_meta_group_infos;
2421f1fa3342SRoel Kluin 	while (i-- > 0)
2422c9de560dSAlex Tomas 		kfree(sbi->s_group_info[i]);
2423c9de560dSAlex Tomas 	iput(sbi->s_buddy_cache);
2424c9de560dSAlex Tomas err_freesgi:
2425c9de560dSAlex Tomas 	kfree(sbi->s_group_info);
2426c9de560dSAlex Tomas 	return -ENOMEM;
2427c9de560dSAlex Tomas }
2428c9de560dSAlex Tomas 
24292892c15dSEric Sandeen static void ext4_groupinfo_destroy_slabs(void)
24302892c15dSEric Sandeen {
24312892c15dSEric Sandeen 	int i;
24322892c15dSEric Sandeen 
24332892c15dSEric Sandeen 	for (i = 0; i < NR_GRPINFO_CACHES; i++) {
24342892c15dSEric Sandeen 		if (ext4_groupinfo_caches[i])
24352892c15dSEric Sandeen 			kmem_cache_destroy(ext4_groupinfo_caches[i]);
24362892c15dSEric Sandeen 		ext4_groupinfo_caches[i] = NULL;
24372892c15dSEric Sandeen 	}
24382892c15dSEric Sandeen }
24392892c15dSEric Sandeen 
24402892c15dSEric Sandeen static int ext4_groupinfo_create_slab(size_t size)
24412892c15dSEric Sandeen {
24422892c15dSEric Sandeen 	static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
24432892c15dSEric Sandeen 	int slab_size;
24442892c15dSEric Sandeen 	int blocksize_bits = order_base_2(size);
24452892c15dSEric Sandeen 	int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
24462892c15dSEric Sandeen 	struct kmem_cache *cachep;
24472892c15dSEric Sandeen 
24482892c15dSEric Sandeen 	if (cache_index >= NR_GRPINFO_CACHES)
24492892c15dSEric Sandeen 		return -EINVAL;
24502892c15dSEric Sandeen 
24512892c15dSEric Sandeen 	if (unlikely(cache_index < 0))
24522892c15dSEric Sandeen 		cache_index = 0;
24532892c15dSEric Sandeen 
24542892c15dSEric Sandeen 	mutex_lock(&ext4_grpinfo_slab_create_mutex);
24552892c15dSEric Sandeen 	if (ext4_groupinfo_caches[cache_index]) {
24562892c15dSEric Sandeen 		mutex_unlock(&ext4_grpinfo_slab_create_mutex);
24572892c15dSEric Sandeen 		return 0;	/* Already created */
24582892c15dSEric Sandeen 	}
24592892c15dSEric Sandeen 
24602892c15dSEric Sandeen 	slab_size = offsetof(struct ext4_group_info,
24612892c15dSEric Sandeen 				bb_counters[blocksize_bits + 2]);
24622892c15dSEric Sandeen 
24632892c15dSEric Sandeen 	cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
24642892c15dSEric Sandeen 					slab_size, 0, SLAB_RECLAIM_ACCOUNT,
24652892c15dSEric Sandeen 					NULL);
24662892c15dSEric Sandeen 
24672892c15dSEric Sandeen 	mutex_unlock(&ext4_grpinfo_slab_create_mutex);
24682892c15dSEric Sandeen 	if (!cachep) {
24692892c15dSEric Sandeen 		printk(KERN_EMERG "EXT4: no memory for groupinfo slab cache\n");
24702892c15dSEric Sandeen 		return -ENOMEM;
24712892c15dSEric Sandeen 	}
24722892c15dSEric Sandeen 
24732892c15dSEric Sandeen 	ext4_groupinfo_caches[cache_index] = cachep;
24742892c15dSEric Sandeen 
24752892c15dSEric Sandeen 	return 0;
24762892c15dSEric Sandeen }
24772892c15dSEric Sandeen 
2478c9de560dSAlex Tomas int ext4_mb_init(struct super_block *sb, int needs_recovery)
2479c9de560dSAlex Tomas {
2480c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
24816be2ded1SAneesh Kumar K.V 	unsigned i, j;
2482c9de560dSAlex Tomas 	unsigned offset;
2483c9de560dSAlex Tomas 	unsigned max;
248474767c5aSShen Feng 	int ret;
2485c9de560dSAlex Tomas 
24861927805eSEric Sandeen 	i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2487c9de560dSAlex Tomas 
2488c9de560dSAlex Tomas 	sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2489c9de560dSAlex Tomas 	if (sbi->s_mb_offsets == NULL) {
2490fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
2491fb1813f4SCurt Wohlgemuth 		goto out;
2492c9de560dSAlex Tomas 	}
2493ff7ef329SYasunori Goto 
24941927805eSEric Sandeen 	i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2495c9de560dSAlex Tomas 	sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2496c9de560dSAlex Tomas 	if (sbi->s_mb_maxs == NULL) {
2497fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
2498fb1813f4SCurt Wohlgemuth 		goto out;
2499fb1813f4SCurt Wohlgemuth 	}
2500fb1813f4SCurt Wohlgemuth 
25012892c15dSEric Sandeen 	ret = ext4_groupinfo_create_slab(sb->s_blocksize);
25022892c15dSEric Sandeen 	if (ret < 0)
2503fb1813f4SCurt Wohlgemuth 		goto out;
2504c9de560dSAlex Tomas 
2505c9de560dSAlex Tomas 	/* order 0 is regular bitmap */
2506c9de560dSAlex Tomas 	sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2507c9de560dSAlex Tomas 	sbi->s_mb_offsets[0] = 0;
2508c9de560dSAlex Tomas 
2509c9de560dSAlex Tomas 	i = 1;
2510c9de560dSAlex Tomas 	offset = 0;
2511c9de560dSAlex Tomas 	max = sb->s_blocksize << 2;
2512c9de560dSAlex Tomas 	do {
2513c9de560dSAlex Tomas 		sbi->s_mb_offsets[i] = offset;
2514c9de560dSAlex Tomas 		sbi->s_mb_maxs[i] = max;
2515c9de560dSAlex Tomas 		offset += 1 << (sb->s_blocksize_bits - i);
2516c9de560dSAlex Tomas 		max = max >> 1;
2517c9de560dSAlex Tomas 		i++;
2518c9de560dSAlex Tomas 	} while (i <= sb->s_blocksize_bits + 1);
2519c9de560dSAlex Tomas 
2520c9de560dSAlex Tomas 	/* init file for buddy data */
252174767c5aSShen Feng 	ret = ext4_mb_init_backend(sb);
252274767c5aSShen Feng 	if (ret != 0) {
2523fb1813f4SCurt Wohlgemuth 		goto out;
2524c9de560dSAlex Tomas 	}
2525c9de560dSAlex Tomas 
2526c9de560dSAlex Tomas 	spin_lock_init(&sbi->s_md_lock);
2527c9de560dSAlex Tomas 	spin_lock_init(&sbi->s_bal_lock);
2528c9de560dSAlex Tomas 
2529c9de560dSAlex Tomas 	sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2530c9de560dSAlex Tomas 	sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2531c9de560dSAlex Tomas 	sbi->s_mb_stats = MB_DEFAULT_STATS;
2532c9de560dSAlex Tomas 	sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2533c9de560dSAlex Tomas 	sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2534c9de560dSAlex Tomas 	sbi->s_mb_group_prealloc = MB_DEFAULT_GROUP_PREALLOC;
2535c9de560dSAlex Tomas 
2536730c213cSEric Sandeen 	sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2537c9de560dSAlex Tomas 	if (sbi->s_locality_groups == NULL) {
2538fb1813f4SCurt Wohlgemuth 		ret = -ENOMEM;
2539fb1813f4SCurt Wohlgemuth 		goto out;
2540c9de560dSAlex Tomas 	}
2541730c213cSEric Sandeen 	for_each_possible_cpu(i) {
2542c9de560dSAlex Tomas 		struct ext4_locality_group *lg;
2543730c213cSEric Sandeen 		lg = per_cpu_ptr(sbi->s_locality_groups, i);
2544c9de560dSAlex Tomas 		mutex_init(&lg->lg_mutex);
25456be2ded1SAneesh Kumar K.V 		for (j = 0; j < PREALLOC_TB_SIZE; j++)
25466be2ded1SAneesh Kumar K.V 			INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2547c9de560dSAlex Tomas 		spin_lock_init(&lg->lg_prealloc_lock);
2548c9de560dSAlex Tomas 	}
2549c9de560dSAlex Tomas 
2550296c355cSTheodore Ts'o 	if (sbi->s_proc)
2551296c355cSTheodore Ts'o 		proc_create_data("mb_groups", S_IRUGO, sbi->s_proc,
2552296c355cSTheodore Ts'o 				 &ext4_mb_seq_groups_fops, sb);
2553c9de560dSAlex Tomas 
25540390131bSFrank Mayhar 	if (sbi->s_journal)
25553e624fc7STheodore Ts'o 		sbi->s_journal->j_commit_callback = release_blocks_on_commit;
2556fb1813f4SCurt Wohlgemuth out:
2557fb1813f4SCurt Wohlgemuth 	if (ret) {
2558fb1813f4SCurt Wohlgemuth 		kfree(sbi->s_mb_offsets);
2559fb1813f4SCurt Wohlgemuth 		kfree(sbi->s_mb_maxs);
2560fb1813f4SCurt Wohlgemuth 	}
2561fb1813f4SCurt Wohlgemuth 	return ret;
2562c9de560dSAlex Tomas }
2563c9de560dSAlex Tomas 
2564955ce5f5SAneesh Kumar K.V /* need to called with the ext4 group lock held */
2565c9de560dSAlex Tomas static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2566c9de560dSAlex Tomas {
2567c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
2568c9de560dSAlex Tomas 	struct list_head *cur, *tmp;
2569c9de560dSAlex Tomas 	int count = 0;
2570c9de560dSAlex Tomas 
2571c9de560dSAlex Tomas 	list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2572c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2573c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
2574c9de560dSAlex Tomas 		count++;
2575688f05a0SAneesh Kumar K.V 		kmem_cache_free(ext4_pspace_cachep, pa);
2576c9de560dSAlex Tomas 	}
2577c9de560dSAlex Tomas 	if (count)
25786ba495e9STheodore Ts'o 		mb_debug(1, "mballoc: %u PAs left\n", count);
2579c9de560dSAlex Tomas 
2580c9de560dSAlex Tomas }
2581c9de560dSAlex Tomas 
2582c9de560dSAlex Tomas int ext4_mb_release(struct super_block *sb)
2583c9de560dSAlex Tomas {
25848df9675fSTheodore Ts'o 	ext4_group_t ngroups = ext4_get_groups_count(sb);
2585c9de560dSAlex Tomas 	ext4_group_t i;
2586c9de560dSAlex Tomas 	int num_meta_group_infos;
2587c9de560dSAlex Tomas 	struct ext4_group_info *grinfo;
2588c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2589fb1813f4SCurt Wohlgemuth 	struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2590c9de560dSAlex Tomas 
2591c9de560dSAlex Tomas 	if (sbi->s_group_info) {
25928df9675fSTheodore Ts'o 		for (i = 0; i < ngroups; i++) {
2593c9de560dSAlex Tomas 			grinfo = ext4_get_group_info(sb, i);
2594c9de560dSAlex Tomas #ifdef DOUBLE_CHECK
2595c9de560dSAlex Tomas 			kfree(grinfo->bb_bitmap);
2596c9de560dSAlex Tomas #endif
2597c9de560dSAlex Tomas 			ext4_lock_group(sb, i);
2598c9de560dSAlex Tomas 			ext4_mb_cleanup_pa(grinfo);
2599c9de560dSAlex Tomas 			ext4_unlock_group(sb, i);
2600fb1813f4SCurt Wohlgemuth 			kmem_cache_free(cachep, grinfo);
2601c9de560dSAlex Tomas 		}
26028df9675fSTheodore Ts'o 		num_meta_group_infos = (ngroups +
2603c9de560dSAlex Tomas 				EXT4_DESC_PER_BLOCK(sb) - 1) >>
2604c9de560dSAlex Tomas 			EXT4_DESC_PER_BLOCK_BITS(sb);
2605c9de560dSAlex Tomas 		for (i = 0; i < num_meta_group_infos; i++)
2606c9de560dSAlex Tomas 			kfree(sbi->s_group_info[i]);
2607c9de560dSAlex Tomas 		kfree(sbi->s_group_info);
2608c9de560dSAlex Tomas 	}
2609c9de560dSAlex Tomas 	kfree(sbi->s_mb_offsets);
2610c9de560dSAlex Tomas 	kfree(sbi->s_mb_maxs);
2611c9de560dSAlex Tomas 	if (sbi->s_buddy_cache)
2612c9de560dSAlex Tomas 		iput(sbi->s_buddy_cache);
2613c9de560dSAlex Tomas 	if (sbi->s_mb_stats) {
2614c9de560dSAlex Tomas 		printk(KERN_INFO
2615c9de560dSAlex Tomas 		       "EXT4-fs: mballoc: %u blocks %u reqs (%u success)\n",
2616c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_allocated),
2617c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_reqs),
2618c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_success));
2619c9de560dSAlex Tomas 		printk(KERN_INFO
2620c9de560dSAlex Tomas 		      "EXT4-fs: mballoc: %u extents scanned, %u goal hits, "
2621c9de560dSAlex Tomas 				"%u 2^N hits, %u breaks, %u lost\n",
2622c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_ex_scanned),
2623c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_goals),
2624c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_2orders),
2625c9de560dSAlex Tomas 				atomic_read(&sbi->s_bal_breaks),
2626c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_lost_chunks));
2627c9de560dSAlex Tomas 		printk(KERN_INFO
2628c9de560dSAlex Tomas 		       "EXT4-fs: mballoc: %lu generated and it took %Lu\n",
2629c9de560dSAlex Tomas 				sbi->s_mb_buddies_generated++,
2630c9de560dSAlex Tomas 				sbi->s_mb_generation_time);
2631c9de560dSAlex Tomas 		printk(KERN_INFO
2632c9de560dSAlex Tomas 		       "EXT4-fs: mballoc: %u preallocated, %u discarded\n",
2633c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_preallocated),
2634c9de560dSAlex Tomas 				atomic_read(&sbi->s_mb_discarded));
2635c9de560dSAlex Tomas 	}
2636c9de560dSAlex Tomas 
2637730c213cSEric Sandeen 	free_percpu(sbi->s_locality_groups);
2638296c355cSTheodore Ts'o 	if (sbi->s_proc)
2639296c355cSTheodore Ts'o 		remove_proc_entry("mb_groups", sbi->s_proc);
2640c9de560dSAlex Tomas 
2641c9de560dSAlex Tomas 	return 0;
2642c9de560dSAlex Tomas }
2643c9de560dSAlex Tomas 
264477ca6cdfSLukas Czerner static inline int ext4_issue_discard(struct super_block *sb,
26455c521830SJiaying Zhang 		ext4_group_t block_group, ext4_grpblk_t block, int count)
26465c521830SJiaying Zhang {
26475c521830SJiaying Zhang 	ext4_fsblk_t discard_block;
26485c521830SJiaying Zhang 
26495c521830SJiaying Zhang 	discard_block = block + ext4_group_first_block_no(sb, block_group);
26505c521830SJiaying Zhang 	trace_ext4_discard_blocks(sb,
26515c521830SJiaying Zhang 			(unsigned long long) discard_block, count);
265293259636SLukas Czerner 	return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
26535c521830SJiaying Zhang }
26545c521830SJiaying Zhang 
26553e624fc7STheodore Ts'o /*
26563e624fc7STheodore Ts'o  * This function is called by the jbd2 layer once the commit has finished,
26573e624fc7STheodore Ts'o  * so we know we can free the blocks that were released with that commit.
26583e624fc7STheodore Ts'o  */
26593e624fc7STheodore Ts'o static void release_blocks_on_commit(journal_t *journal, transaction_t *txn)
2660c9de560dSAlex Tomas {
26613e624fc7STheodore Ts'o 	struct super_block *sb = journal->j_private;
2662c9de560dSAlex Tomas 	struct ext4_buddy e4b;
2663c894058dSAneesh Kumar K.V 	struct ext4_group_info *db;
266493259636SLukas Czerner 	int err, ret, count = 0, count2 = 0;
2665c894058dSAneesh Kumar K.V 	struct ext4_free_data *entry;
26663e624fc7STheodore Ts'o 	struct list_head *l, *ltmp;
2667c9de560dSAlex Tomas 
26683e624fc7STheodore Ts'o 	list_for_each_safe(l, ltmp, &txn->t_private_list) {
26693e624fc7STheodore Ts'o 		entry = list_entry(l, struct ext4_free_data, list);
2670c9de560dSAlex Tomas 
26716ba495e9STheodore Ts'o 		mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2672c894058dSAneesh Kumar K.V 			 entry->count, entry->group, entry);
2673c9de560dSAlex Tomas 
267493259636SLukas Czerner 		if (test_opt(sb, DISCARD)) {
267593259636SLukas Czerner 			ret = ext4_issue_discard(sb, entry->group,
26765c521830SJiaying Zhang 					entry->start_blk, entry->count);
267793259636SLukas Czerner 			if (unlikely(ret == -EOPNOTSUPP)) {
267893259636SLukas Czerner 				ext4_warning(sb, "discard not supported, "
267993259636SLukas Czerner 						 "disabling");
268093259636SLukas Czerner 				clear_opt(sb, DISCARD);
268193259636SLukas Czerner 			}
268293259636SLukas Czerner 		}
2683b90f6870STheodore Ts'o 
2684c894058dSAneesh Kumar K.V 		err = ext4_mb_load_buddy(sb, entry->group, &e4b);
2685c9de560dSAlex Tomas 		/* we expect to find existing buddy because it's pinned */
2686c9de560dSAlex Tomas 		BUG_ON(err != 0);
2687c9de560dSAlex Tomas 
2688c894058dSAneesh Kumar K.V 		db = e4b.bd_info;
2689c9de560dSAlex Tomas 		/* there are blocks to put in buddy to make them really free */
2690c894058dSAneesh Kumar K.V 		count += entry->count;
2691c9de560dSAlex Tomas 		count2++;
2692c894058dSAneesh Kumar K.V 		ext4_lock_group(sb, entry->group);
2693c894058dSAneesh Kumar K.V 		/* Take it out of per group rb tree */
2694c894058dSAneesh Kumar K.V 		rb_erase(&entry->node, &(db->bb_free_root));
2695c894058dSAneesh Kumar K.V 		mb_free_blocks(NULL, &e4b, entry->start_blk, entry->count);
2696c9de560dSAlex Tomas 
2697c894058dSAneesh Kumar K.V 		if (!db->bb_free_root.rb_node) {
2698c894058dSAneesh Kumar K.V 			/* No more items in the per group rb tree
2699c894058dSAneesh Kumar K.V 			 * balance refcounts from ext4_mb_free_metadata()
2700c894058dSAneesh Kumar K.V 			 */
2701c9de560dSAlex Tomas 			page_cache_release(e4b.bd_buddy_page);
2702c9de560dSAlex Tomas 			page_cache_release(e4b.bd_bitmap_page);
2703c894058dSAneesh Kumar K.V 		}
2704c894058dSAneesh Kumar K.V 		ext4_unlock_group(sb, entry->group);
2705c894058dSAneesh Kumar K.V 		kmem_cache_free(ext4_free_ext_cachep, entry);
2706e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
27073e624fc7STheodore Ts'o 	}
2708c9de560dSAlex Tomas 
27096ba495e9STheodore Ts'o 	mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2710c9de560dSAlex Tomas }
2711c9de560dSAlex Tomas 
27126ba495e9STheodore Ts'o #ifdef CONFIG_EXT4_DEBUG
27136ba495e9STheodore Ts'o u8 mb_enable_debug __read_mostly;
27146ba495e9STheodore Ts'o 
27156ba495e9STheodore Ts'o static struct dentry *debugfs_dir;
27166ba495e9STheodore Ts'o static struct dentry *debugfs_debug;
27176ba495e9STheodore Ts'o 
27186ba495e9STheodore Ts'o static void __init ext4_create_debugfs_entry(void)
27196ba495e9STheodore Ts'o {
27206ba495e9STheodore Ts'o 	debugfs_dir = debugfs_create_dir("ext4", NULL);
27216ba495e9STheodore Ts'o 	if (debugfs_dir)
27226ba495e9STheodore Ts'o 		debugfs_debug = debugfs_create_u8("mballoc-debug",
27236ba495e9STheodore Ts'o 						  S_IRUGO | S_IWUSR,
27246ba495e9STheodore Ts'o 						  debugfs_dir,
27256ba495e9STheodore Ts'o 						  &mb_enable_debug);
27266ba495e9STheodore Ts'o }
27276ba495e9STheodore Ts'o 
27286ba495e9STheodore Ts'o static void ext4_remove_debugfs_entry(void)
27296ba495e9STheodore Ts'o {
27306ba495e9STheodore Ts'o 	debugfs_remove(debugfs_debug);
27316ba495e9STheodore Ts'o 	debugfs_remove(debugfs_dir);
27326ba495e9STheodore Ts'o }
27336ba495e9STheodore Ts'o 
27346ba495e9STheodore Ts'o #else
27356ba495e9STheodore Ts'o 
27366ba495e9STheodore Ts'o static void __init ext4_create_debugfs_entry(void)
27376ba495e9STheodore Ts'o {
27386ba495e9STheodore Ts'o }
27396ba495e9STheodore Ts'o 
27406ba495e9STheodore Ts'o static void ext4_remove_debugfs_entry(void)
27416ba495e9STheodore Ts'o {
27426ba495e9STheodore Ts'o }
27436ba495e9STheodore Ts'o 
27446ba495e9STheodore Ts'o #endif
27456ba495e9STheodore Ts'o 
27465dabfc78STheodore Ts'o int __init ext4_init_mballoc(void)
2747c9de560dSAlex Tomas {
274816828088STheodore Ts'o 	ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
274916828088STheodore Ts'o 					SLAB_RECLAIM_ACCOUNT);
2750c9de560dSAlex Tomas 	if (ext4_pspace_cachep == NULL)
2751c9de560dSAlex Tomas 		return -ENOMEM;
2752c9de560dSAlex Tomas 
275316828088STheodore Ts'o 	ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
275416828088STheodore Ts'o 				    SLAB_RECLAIM_ACCOUNT);
2755256bdb49SEric Sandeen 	if (ext4_ac_cachep == NULL) {
2756256bdb49SEric Sandeen 		kmem_cache_destroy(ext4_pspace_cachep);
2757256bdb49SEric Sandeen 		return -ENOMEM;
2758256bdb49SEric Sandeen 	}
2759c894058dSAneesh Kumar K.V 
276016828088STheodore Ts'o 	ext4_free_ext_cachep = KMEM_CACHE(ext4_free_data,
276116828088STheodore Ts'o 					  SLAB_RECLAIM_ACCOUNT);
2762c894058dSAneesh Kumar K.V 	if (ext4_free_ext_cachep == NULL) {
2763c894058dSAneesh Kumar K.V 		kmem_cache_destroy(ext4_pspace_cachep);
2764c894058dSAneesh Kumar K.V 		kmem_cache_destroy(ext4_ac_cachep);
2765c894058dSAneesh Kumar K.V 		return -ENOMEM;
2766c894058dSAneesh Kumar K.V 	}
27676ba495e9STheodore Ts'o 	ext4_create_debugfs_entry();
2768c9de560dSAlex Tomas 	return 0;
2769c9de560dSAlex Tomas }
2770c9de560dSAlex Tomas 
27715dabfc78STheodore Ts'o void ext4_exit_mballoc(void)
2772c9de560dSAlex Tomas {
27733e03f9caSJesper Dangaard Brouer 	/*
27743e03f9caSJesper Dangaard Brouer 	 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
27753e03f9caSJesper Dangaard Brouer 	 * before destroying the slab cache.
27763e03f9caSJesper Dangaard Brouer 	 */
27773e03f9caSJesper Dangaard Brouer 	rcu_barrier();
2778c9de560dSAlex Tomas 	kmem_cache_destroy(ext4_pspace_cachep);
2779256bdb49SEric Sandeen 	kmem_cache_destroy(ext4_ac_cachep);
2780c894058dSAneesh Kumar K.V 	kmem_cache_destroy(ext4_free_ext_cachep);
27812892c15dSEric Sandeen 	ext4_groupinfo_destroy_slabs();
27826ba495e9STheodore Ts'o 	ext4_remove_debugfs_entry();
2783c9de560dSAlex Tomas }
2784c9de560dSAlex Tomas 
2785c9de560dSAlex Tomas 
2786c9de560dSAlex Tomas /*
278773b2c716SUwe Kleine-König  * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2788c9de560dSAlex Tomas  * Returns 0 if success or error code
2789c9de560dSAlex Tomas  */
27904ddfef7bSEric Sandeen static noinline_for_stack int
27914ddfef7bSEric Sandeen ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2792498e5f24STheodore Ts'o 				handle_t *handle, unsigned int reserv_blks)
2793c9de560dSAlex Tomas {
2794c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
2795c9de560dSAlex Tomas 	struct ext4_group_desc *gdp;
2796c9de560dSAlex Tomas 	struct buffer_head *gdp_bh;
2797c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
2798c9de560dSAlex Tomas 	struct super_block *sb;
2799c9de560dSAlex Tomas 	ext4_fsblk_t block;
2800519deca0SAneesh Kumar K.V 	int err, len;
2801c9de560dSAlex Tomas 
2802c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2803c9de560dSAlex Tomas 	BUG_ON(ac->ac_b_ex.fe_len <= 0);
2804c9de560dSAlex Tomas 
2805c9de560dSAlex Tomas 	sb = ac->ac_sb;
2806c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
2807c9de560dSAlex Tomas 
2808c9de560dSAlex Tomas 	err = -EIO;
2809574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2810c9de560dSAlex Tomas 	if (!bitmap_bh)
2811c9de560dSAlex Tomas 		goto out_err;
2812c9de560dSAlex Tomas 
2813c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, bitmap_bh);
2814c9de560dSAlex Tomas 	if (err)
2815c9de560dSAlex Tomas 		goto out_err;
2816c9de560dSAlex Tomas 
2817c9de560dSAlex Tomas 	err = -EIO;
2818c9de560dSAlex Tomas 	gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2819c9de560dSAlex Tomas 	if (!gdp)
2820c9de560dSAlex Tomas 		goto out_err;
2821c9de560dSAlex Tomas 
2822a9df9a49STheodore Ts'o 	ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
28239fd9784cSThadeu Lima de Souza Cascardo 			ext4_free_blks_count(sb, gdp));
282403cddb80SAneesh Kumar K.V 
2825c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, gdp_bh);
2826c9de560dSAlex Tomas 	if (err)
2827c9de560dSAlex Tomas 		goto out_err;
2828c9de560dSAlex Tomas 
2829bda00de7SAkinobu Mita 	block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
2830c9de560dSAlex Tomas 
2831519deca0SAneesh Kumar K.V 	len = ac->ac_b_ex.fe_len;
28326fd058f7STheodore Ts'o 	if (!ext4_data_block_valid(sbi, block, len)) {
283312062dddSEric Sandeen 		ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
28346fd058f7STheodore Ts'o 			   "fs metadata\n", block, block+len);
2835519deca0SAneesh Kumar K.V 		/* File system mounted not to panic on error
2836519deca0SAneesh Kumar K.V 		 * Fix the bitmap and repeat the block allocation
2837519deca0SAneesh Kumar K.V 		 * We leak some of the blocks here.
2838519deca0SAneesh Kumar K.V 		 */
2839955ce5f5SAneesh Kumar K.V 		ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2840955ce5f5SAneesh Kumar K.V 		mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2841519deca0SAneesh Kumar K.V 			    ac->ac_b_ex.fe_len);
2842955ce5f5SAneesh Kumar K.V 		ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
28430390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2844519deca0SAneesh Kumar K.V 		if (!err)
2845519deca0SAneesh Kumar K.V 			err = -EAGAIN;
2846519deca0SAneesh Kumar K.V 		goto out_err;
2847c9de560dSAlex Tomas 	}
2848955ce5f5SAneesh Kumar K.V 
2849955ce5f5SAneesh Kumar K.V 	ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2850c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
2851c9de560dSAlex Tomas 	{
2852c9de560dSAlex Tomas 		int i;
2853c9de560dSAlex Tomas 		for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
2854c9de560dSAlex Tomas 			BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
2855c9de560dSAlex Tomas 						bitmap_bh->b_data));
2856c9de560dSAlex Tomas 		}
2857c9de560dSAlex Tomas 	}
2858c9de560dSAlex Tomas #endif
2859955ce5f5SAneesh Kumar K.V 	mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,ac->ac_b_ex.fe_len);
2860c9de560dSAlex Tomas 	if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2861c9de560dSAlex Tomas 		gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
2862560671a0SAneesh Kumar K.V 		ext4_free_blks_set(sb, gdp,
2863560671a0SAneesh Kumar K.V 					ext4_free_blocks_after_init(sb,
2864560671a0SAneesh Kumar K.V 					ac->ac_b_ex.fe_group, gdp));
2865c9de560dSAlex Tomas 	}
2866560671a0SAneesh Kumar K.V 	len = ext4_free_blks_count(sb, gdp) - ac->ac_b_ex.fe_len;
2867560671a0SAneesh Kumar K.V 	ext4_free_blks_set(sb, gdp, len);
2868c9de560dSAlex Tomas 	gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
2869955ce5f5SAneesh Kumar K.V 
2870955ce5f5SAneesh Kumar K.V 	ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
28716bc6e63fSAneesh Kumar K.V 	percpu_counter_sub(&sbi->s_freeblocks_counter, ac->ac_b_ex.fe_len);
2872d2a17637SMingming Cao 	/*
28736bc6e63fSAneesh Kumar K.V 	 * Now reduce the dirty block count also. Should not go negative
2874d2a17637SMingming Cao 	 */
28756bc6e63fSAneesh Kumar K.V 	if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
28766bc6e63fSAneesh Kumar K.V 		/* release all the reserved blocks if non delalloc */
28776bc6e63fSAneesh Kumar K.V 		percpu_counter_sub(&sbi->s_dirtyblocks_counter, reserv_blks);
2878c9de560dSAlex Tomas 
2879772cb7c8SJose R. Santos 	if (sbi->s_log_groups_per_flex) {
2880772cb7c8SJose R. Santos 		ext4_group_t flex_group = ext4_flex_group(sbi,
2881772cb7c8SJose R. Santos 							  ac->ac_b_ex.fe_group);
28829f24e420STheodore Ts'o 		atomic_sub(ac->ac_b_ex.fe_len,
28839f24e420STheodore Ts'o 			   &sbi->s_flex_groups[flex_group].free_blocks);
2884772cb7c8SJose R. Santos 	}
2885772cb7c8SJose R. Santos 
28860390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2887c9de560dSAlex Tomas 	if (err)
2888c9de560dSAlex Tomas 		goto out_err;
28890390131bSFrank Mayhar 	err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
2890c9de560dSAlex Tomas 
2891c9de560dSAlex Tomas out_err:
2892a0375156STheodore Ts'o 	ext4_mark_super_dirty(sb);
289342a10addSAneesh Kumar K.V 	brelse(bitmap_bh);
2894c9de560dSAlex Tomas 	return err;
2895c9de560dSAlex Tomas }
2896c9de560dSAlex Tomas 
2897c9de560dSAlex Tomas /*
2898c9de560dSAlex Tomas  * here we normalize request for locality group
2899c9de560dSAlex Tomas  * Group request are normalized to s_strip size if we set the same via mount
2900c9de560dSAlex Tomas  * option. If not we set it to s_mb_group_prealloc which can be configured via
2901b713a5ecSTheodore Ts'o  * /sys/fs/ext4/<partition>/mb_group_prealloc
2902c9de560dSAlex Tomas  *
2903c9de560dSAlex Tomas  * XXX: should we try to preallocate more than the group has now?
2904c9de560dSAlex Tomas  */
2905c9de560dSAlex Tomas static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
2906c9de560dSAlex Tomas {
2907c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
2908c9de560dSAlex Tomas 	struct ext4_locality_group *lg = ac->ac_lg;
2909c9de560dSAlex Tomas 
2910c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
2911c9de560dSAlex Tomas 	if (EXT4_SB(sb)->s_stripe)
2912c9de560dSAlex Tomas 		ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_stripe;
2913c9de560dSAlex Tomas 	else
2914c9de560dSAlex Tomas 		ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
29156ba495e9STheodore Ts'o 	mb_debug(1, "#%u: goal %u blocks for locality group\n",
2916c9de560dSAlex Tomas 		current->pid, ac->ac_g_ex.fe_len);
2917c9de560dSAlex Tomas }
2918c9de560dSAlex Tomas 
2919c9de560dSAlex Tomas /*
2920c9de560dSAlex Tomas  * Normalization means making request better in terms of
2921c9de560dSAlex Tomas  * size and alignment
2922c9de560dSAlex Tomas  */
29234ddfef7bSEric Sandeen static noinline_for_stack void
29244ddfef7bSEric Sandeen ext4_mb_normalize_request(struct ext4_allocation_context *ac,
2925c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
2926c9de560dSAlex Tomas {
2927c9de560dSAlex Tomas 	int bsbits, max;
2928c9de560dSAlex Tomas 	ext4_lblk_t end;
2929c9de560dSAlex Tomas 	loff_t size, orig_size, start_off;
29305a0790c2SAndi Kleen 	ext4_lblk_t start;
2931c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
29329a0762c5SAneesh Kumar K.V 	struct ext4_prealloc_space *pa;
2933c9de560dSAlex Tomas 
2934c9de560dSAlex Tomas 	/* do normalize only data requests, metadata requests
2935c9de560dSAlex Tomas 	   do not need preallocation */
2936c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
2937c9de560dSAlex Tomas 		return;
2938c9de560dSAlex Tomas 
2939c9de560dSAlex Tomas 	/* sometime caller may want exact blocks */
2940c9de560dSAlex Tomas 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2941c9de560dSAlex Tomas 		return;
2942c9de560dSAlex Tomas 
2943c9de560dSAlex Tomas 	/* caller may indicate that preallocation isn't
2944c9de560dSAlex Tomas 	 * required (it's a tail, for example) */
2945c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
2946c9de560dSAlex Tomas 		return;
2947c9de560dSAlex Tomas 
2948c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
2949c9de560dSAlex Tomas 		ext4_mb_normalize_group_request(ac);
2950c9de560dSAlex Tomas 		return ;
2951c9de560dSAlex Tomas 	}
2952c9de560dSAlex Tomas 
2953c9de560dSAlex Tomas 	bsbits = ac->ac_sb->s_blocksize_bits;
2954c9de560dSAlex Tomas 
2955c9de560dSAlex Tomas 	/* first, let's learn actual file size
2956c9de560dSAlex Tomas 	 * given current request is allocated */
2957c9de560dSAlex Tomas 	size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
2958c9de560dSAlex Tomas 	size = size << bsbits;
2959c9de560dSAlex Tomas 	if (size < i_size_read(ac->ac_inode))
2960c9de560dSAlex Tomas 		size = i_size_read(ac->ac_inode);
29615a0790c2SAndi Kleen 	orig_size = size;
2962c9de560dSAlex Tomas 
29631930479cSValerie Clement 	/* max size of free chunks */
29641930479cSValerie Clement 	max = 2 << bsbits;
2965c9de560dSAlex Tomas 
29661930479cSValerie Clement #define NRL_CHECK_SIZE(req, size, max, chunk_size)	\
29671930479cSValerie Clement 		(req <= (size) || max <= (chunk_size))
2968c9de560dSAlex Tomas 
2969c9de560dSAlex Tomas 	/* first, try to predict filesize */
2970c9de560dSAlex Tomas 	/* XXX: should this table be tunable? */
2971c9de560dSAlex Tomas 	start_off = 0;
2972c9de560dSAlex Tomas 	if (size <= 16 * 1024) {
2973c9de560dSAlex Tomas 		size = 16 * 1024;
2974c9de560dSAlex Tomas 	} else if (size <= 32 * 1024) {
2975c9de560dSAlex Tomas 		size = 32 * 1024;
2976c9de560dSAlex Tomas 	} else if (size <= 64 * 1024) {
2977c9de560dSAlex Tomas 		size = 64 * 1024;
2978c9de560dSAlex Tomas 	} else if (size <= 128 * 1024) {
2979c9de560dSAlex Tomas 		size = 128 * 1024;
2980c9de560dSAlex Tomas 	} else if (size <= 256 * 1024) {
2981c9de560dSAlex Tomas 		size = 256 * 1024;
2982c9de560dSAlex Tomas 	} else if (size <= 512 * 1024) {
2983c9de560dSAlex Tomas 		size = 512 * 1024;
2984c9de560dSAlex Tomas 	} else if (size <= 1024 * 1024) {
2985c9de560dSAlex Tomas 		size = 1024 * 1024;
29861930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
2987c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
29881930479cSValerie Clement 						(21 - bsbits)) << 21;
29891930479cSValerie Clement 		size = 2 * 1024 * 1024;
29901930479cSValerie Clement 	} else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
2991c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2992c9de560dSAlex Tomas 							(22 - bsbits)) << 22;
2993c9de560dSAlex Tomas 		size = 4 * 1024 * 1024;
2994c9de560dSAlex Tomas 	} else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
29951930479cSValerie Clement 					(8<<20)>>bsbits, max, 8 * 1024)) {
2996c9de560dSAlex Tomas 		start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2997c9de560dSAlex Tomas 							(23 - bsbits)) << 23;
2998c9de560dSAlex Tomas 		size = 8 * 1024 * 1024;
2999c9de560dSAlex Tomas 	} else {
3000c9de560dSAlex Tomas 		start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
3001c9de560dSAlex Tomas 		size	  = ac->ac_o_ex.fe_len << bsbits;
3002c9de560dSAlex Tomas 	}
30035a0790c2SAndi Kleen 	size = size >> bsbits;
30045a0790c2SAndi Kleen 	start = start_off >> bsbits;
3005c9de560dSAlex Tomas 
3006c9de560dSAlex Tomas 	/* don't cover already allocated blocks in selected range */
3007c9de560dSAlex Tomas 	if (ar->pleft && start <= ar->lleft) {
3008c9de560dSAlex Tomas 		size -= ar->lleft + 1 - start;
3009c9de560dSAlex Tomas 		start = ar->lleft + 1;
3010c9de560dSAlex Tomas 	}
3011c9de560dSAlex Tomas 	if (ar->pright && start + size - 1 >= ar->lright)
3012c9de560dSAlex Tomas 		size -= start + size - ar->lright;
3013c9de560dSAlex Tomas 
3014c9de560dSAlex Tomas 	end = start + size;
3015c9de560dSAlex Tomas 
3016c9de560dSAlex Tomas 	/* check we don't cross already preallocated blocks */
3017c9de560dSAlex Tomas 	rcu_read_lock();
30189a0762c5SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3019498e5f24STheodore Ts'o 		ext4_lblk_t pa_end;
3020c9de560dSAlex Tomas 
3021c9de560dSAlex Tomas 		if (pa->pa_deleted)
3022c9de560dSAlex Tomas 			continue;
3023c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3024c9de560dSAlex Tomas 		if (pa->pa_deleted) {
3025c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3026c9de560dSAlex Tomas 			continue;
3027c9de560dSAlex Tomas 		}
3028c9de560dSAlex Tomas 
3029c9de560dSAlex Tomas 		pa_end = pa->pa_lstart + pa->pa_len;
3030c9de560dSAlex Tomas 
3031c9de560dSAlex Tomas 		/* PA must not overlap original request */
3032c9de560dSAlex Tomas 		BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3033c9de560dSAlex Tomas 			ac->ac_o_ex.fe_logical < pa->pa_lstart));
3034c9de560dSAlex Tomas 
303538877f4eSEric Sandeen 		/* skip PAs this normalized request doesn't overlap with */
303638877f4eSEric Sandeen 		if (pa->pa_lstart >= end || pa_end <= start) {
3037c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3038c9de560dSAlex Tomas 			continue;
3039c9de560dSAlex Tomas 		}
3040c9de560dSAlex Tomas 		BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3041c9de560dSAlex Tomas 
304238877f4eSEric Sandeen 		/* adjust start or end to be adjacent to this pa */
3043c9de560dSAlex Tomas 		if (pa_end <= ac->ac_o_ex.fe_logical) {
3044c9de560dSAlex Tomas 			BUG_ON(pa_end < start);
3045c9de560dSAlex Tomas 			start = pa_end;
304638877f4eSEric Sandeen 		} else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3047c9de560dSAlex Tomas 			BUG_ON(pa->pa_lstart > end);
3048c9de560dSAlex Tomas 			end = pa->pa_lstart;
3049c9de560dSAlex Tomas 		}
3050c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3051c9de560dSAlex Tomas 	}
3052c9de560dSAlex Tomas 	rcu_read_unlock();
3053c9de560dSAlex Tomas 	size = end - start;
3054c9de560dSAlex Tomas 
3055c9de560dSAlex Tomas 	/* XXX: extra loop to check we really don't overlap preallocations */
3056c9de560dSAlex Tomas 	rcu_read_lock();
30579a0762c5SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3058498e5f24STheodore Ts'o 		ext4_lblk_t pa_end;
3059c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3060c9de560dSAlex Tomas 		if (pa->pa_deleted == 0) {
3061c9de560dSAlex Tomas 			pa_end = pa->pa_lstart + pa->pa_len;
3062c9de560dSAlex Tomas 			BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3063c9de560dSAlex Tomas 		}
3064c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3065c9de560dSAlex Tomas 	}
3066c9de560dSAlex Tomas 	rcu_read_unlock();
3067c9de560dSAlex Tomas 
3068c9de560dSAlex Tomas 	if (start + size <= ac->ac_o_ex.fe_logical &&
3069c9de560dSAlex Tomas 			start > ac->ac_o_ex.fe_logical) {
3070c9de560dSAlex Tomas 		printk(KERN_ERR "start %lu, size %lu, fe_logical %lu\n",
3071c9de560dSAlex Tomas 			(unsigned long) start, (unsigned long) size,
3072c9de560dSAlex Tomas 			(unsigned long) ac->ac_o_ex.fe_logical);
3073c9de560dSAlex Tomas 	}
3074c9de560dSAlex Tomas 	BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3075c9de560dSAlex Tomas 			start > ac->ac_o_ex.fe_logical);
30768d03c7a0SEric Sandeen 	BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3077c9de560dSAlex Tomas 
3078c9de560dSAlex Tomas 	/* now prepare goal request */
3079c9de560dSAlex Tomas 
3080c9de560dSAlex Tomas 	/* XXX: is it better to align blocks WRT to logical
3081c9de560dSAlex Tomas 	 * placement or satisfy big request as is */
3082c9de560dSAlex Tomas 	ac->ac_g_ex.fe_logical = start;
3083c9de560dSAlex Tomas 	ac->ac_g_ex.fe_len = size;
3084c9de560dSAlex Tomas 
3085c9de560dSAlex Tomas 	/* define goal start in order to merge */
3086c9de560dSAlex Tomas 	if (ar->pright && (ar->lright == (start + size))) {
3087c9de560dSAlex Tomas 		/* merge to the right */
3088c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3089c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_group,
3090c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_start);
3091c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3092c9de560dSAlex Tomas 	}
3093c9de560dSAlex Tomas 	if (ar->pleft && (ar->lleft + 1 == start)) {
3094c9de560dSAlex Tomas 		/* merge to the left */
3095c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3096c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_group,
3097c9de560dSAlex Tomas 						&ac->ac_f_ex.fe_start);
3098c9de560dSAlex Tomas 		ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3099c9de560dSAlex Tomas 	}
3100c9de560dSAlex Tomas 
31016ba495e9STheodore Ts'o 	mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3102c9de560dSAlex Tomas 		(unsigned) orig_size, (unsigned) start);
3103c9de560dSAlex Tomas }
3104c9de560dSAlex Tomas 
3105c9de560dSAlex Tomas static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3106c9de560dSAlex Tomas {
3107c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3108c9de560dSAlex Tomas 
3109c9de560dSAlex Tomas 	if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3110c9de560dSAlex Tomas 		atomic_inc(&sbi->s_bal_reqs);
3111c9de560dSAlex Tomas 		atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3112291dae47SCurt Wohlgemuth 		if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3113c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_success);
3114c9de560dSAlex Tomas 		atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3115c9de560dSAlex Tomas 		if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3116c9de560dSAlex Tomas 				ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3117c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_goals);
3118c9de560dSAlex Tomas 		if (ac->ac_found > sbi->s_mb_max_to_scan)
3119c9de560dSAlex Tomas 			atomic_inc(&sbi->s_bal_breaks);
3120c9de560dSAlex Tomas 	}
3121c9de560dSAlex Tomas 
3122296c355cSTheodore Ts'o 	if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3123296c355cSTheodore Ts'o 		trace_ext4_mballoc_alloc(ac);
3124296c355cSTheodore Ts'o 	else
3125296c355cSTheodore Ts'o 		trace_ext4_mballoc_prealloc(ac);
3126c9de560dSAlex Tomas }
3127c9de560dSAlex Tomas 
3128c9de560dSAlex Tomas /*
3129b844167eSCurt Wohlgemuth  * Called on failure; free up any blocks from the inode PA for this
3130b844167eSCurt Wohlgemuth  * context.  We don't need this for MB_GROUP_PA because we only change
3131b844167eSCurt Wohlgemuth  * pa_free in ext4_mb_release_context(), but on failure, we've already
3132b844167eSCurt Wohlgemuth  * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3133b844167eSCurt Wohlgemuth  */
3134b844167eSCurt Wohlgemuth static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3135b844167eSCurt Wohlgemuth {
3136b844167eSCurt Wohlgemuth 	struct ext4_prealloc_space *pa = ac->ac_pa;
3137b844167eSCurt Wohlgemuth 	int len;
3138b844167eSCurt Wohlgemuth 
3139b844167eSCurt Wohlgemuth 	if (pa && pa->pa_type == MB_INODE_PA) {
3140b844167eSCurt Wohlgemuth 		len = ac->ac_b_ex.fe_len;
3141b844167eSCurt Wohlgemuth 		pa->pa_free += len;
3142b844167eSCurt Wohlgemuth 	}
3143b844167eSCurt Wohlgemuth 
3144b844167eSCurt Wohlgemuth }
3145b844167eSCurt Wohlgemuth 
3146b844167eSCurt Wohlgemuth /*
3147c9de560dSAlex Tomas  * use blocks preallocated to inode
3148c9de560dSAlex Tomas  */
3149c9de560dSAlex Tomas static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3150c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
3151c9de560dSAlex Tomas {
3152c9de560dSAlex Tomas 	ext4_fsblk_t start;
3153c9de560dSAlex Tomas 	ext4_fsblk_t end;
3154c9de560dSAlex Tomas 	int len;
3155c9de560dSAlex Tomas 
3156c9de560dSAlex Tomas 	/* found preallocated blocks, use them */
3157c9de560dSAlex Tomas 	start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3158c9de560dSAlex Tomas 	end = min(pa->pa_pstart + pa->pa_len, start + ac->ac_o_ex.fe_len);
3159c9de560dSAlex Tomas 	len = end - start;
3160c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3161c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
3162c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
3163c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
3164c9de560dSAlex Tomas 	ac->ac_pa = pa;
3165c9de560dSAlex Tomas 
3166c9de560dSAlex Tomas 	BUG_ON(start < pa->pa_pstart);
3167c9de560dSAlex Tomas 	BUG_ON(start + len > pa->pa_pstart + pa->pa_len);
3168c9de560dSAlex Tomas 	BUG_ON(pa->pa_free < len);
3169c9de560dSAlex Tomas 	pa->pa_free -= len;
3170c9de560dSAlex Tomas 
31716ba495e9STheodore Ts'o 	mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3172c9de560dSAlex Tomas }
3173c9de560dSAlex Tomas 
3174c9de560dSAlex Tomas /*
3175c9de560dSAlex Tomas  * use blocks preallocated to locality group
3176c9de560dSAlex Tomas  */
3177c9de560dSAlex Tomas static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3178c9de560dSAlex Tomas 				struct ext4_prealloc_space *pa)
3179c9de560dSAlex Tomas {
318003cddb80SAneesh Kumar K.V 	unsigned int len = ac->ac_o_ex.fe_len;
31816be2ded1SAneesh Kumar K.V 
3182c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3183c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_group,
3184c9de560dSAlex Tomas 					&ac->ac_b_ex.fe_start);
3185c9de560dSAlex Tomas 	ac->ac_b_ex.fe_len = len;
3186c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_FOUND;
3187c9de560dSAlex Tomas 	ac->ac_pa = pa;
3188c9de560dSAlex Tomas 
3189c9de560dSAlex Tomas 	/* we don't correct pa_pstart or pa_plen here to avoid
319026346ff6SAneesh Kumar K.V 	 * possible race when the group is being loaded concurrently
3191c9de560dSAlex Tomas 	 * instead we correct pa later, after blocks are marked
319226346ff6SAneesh Kumar K.V 	 * in on-disk bitmap -- see ext4_mb_release_context()
319326346ff6SAneesh Kumar K.V 	 * Other CPUs are prevented from allocating from this pa by lg_mutex
3194c9de560dSAlex Tomas 	 */
31956ba495e9STheodore Ts'o 	mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3196c9de560dSAlex Tomas }
3197c9de560dSAlex Tomas 
3198c9de560dSAlex Tomas /*
31995e745b04SAneesh Kumar K.V  * Return the prealloc space that have minimal distance
32005e745b04SAneesh Kumar K.V  * from the goal block. @cpa is the prealloc
32015e745b04SAneesh Kumar K.V  * space that is having currently known minimal distance
32025e745b04SAneesh Kumar K.V  * from the goal block.
32035e745b04SAneesh Kumar K.V  */
32045e745b04SAneesh Kumar K.V static struct ext4_prealloc_space *
32055e745b04SAneesh Kumar K.V ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
32065e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *pa,
32075e745b04SAneesh Kumar K.V 			struct ext4_prealloc_space *cpa)
32085e745b04SAneesh Kumar K.V {
32095e745b04SAneesh Kumar K.V 	ext4_fsblk_t cur_distance, new_distance;
32105e745b04SAneesh Kumar K.V 
32115e745b04SAneesh Kumar K.V 	if (cpa == NULL) {
32125e745b04SAneesh Kumar K.V 		atomic_inc(&pa->pa_count);
32135e745b04SAneesh Kumar K.V 		return pa;
32145e745b04SAneesh Kumar K.V 	}
32155e745b04SAneesh Kumar K.V 	cur_distance = abs(goal_block - cpa->pa_pstart);
32165e745b04SAneesh Kumar K.V 	new_distance = abs(goal_block - pa->pa_pstart);
32175e745b04SAneesh Kumar K.V 
32185a54b2f1SColy Li 	if (cur_distance <= new_distance)
32195e745b04SAneesh Kumar K.V 		return cpa;
32205e745b04SAneesh Kumar K.V 
32215e745b04SAneesh Kumar K.V 	/* drop the previous reference */
32225e745b04SAneesh Kumar K.V 	atomic_dec(&cpa->pa_count);
32235e745b04SAneesh Kumar K.V 	atomic_inc(&pa->pa_count);
32245e745b04SAneesh Kumar K.V 	return pa;
32255e745b04SAneesh Kumar K.V }
32265e745b04SAneesh Kumar K.V 
32275e745b04SAneesh Kumar K.V /*
3228c9de560dSAlex Tomas  * search goal blocks in preallocated space
3229c9de560dSAlex Tomas  */
32304ddfef7bSEric Sandeen static noinline_for_stack int
32314ddfef7bSEric Sandeen ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3232c9de560dSAlex Tomas {
32336be2ded1SAneesh Kumar K.V 	int order, i;
3234c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3235c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
32365e745b04SAneesh Kumar K.V 	struct ext4_prealloc_space *pa, *cpa = NULL;
32375e745b04SAneesh Kumar K.V 	ext4_fsblk_t goal_block;
3238c9de560dSAlex Tomas 
3239c9de560dSAlex Tomas 	/* only data can be preallocated */
3240c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3241c9de560dSAlex Tomas 		return 0;
3242c9de560dSAlex Tomas 
3243c9de560dSAlex Tomas 	/* first, try per-file preallocation */
3244c9de560dSAlex Tomas 	rcu_read_lock();
32459a0762c5SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3246c9de560dSAlex Tomas 
3247c9de560dSAlex Tomas 		/* all fields in this condition don't change,
3248c9de560dSAlex Tomas 		 * so we can skip locking for them */
3249c9de560dSAlex Tomas 		if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3250c9de560dSAlex Tomas 			ac->ac_o_ex.fe_logical >= pa->pa_lstart + pa->pa_len)
3251c9de560dSAlex Tomas 			continue;
3252c9de560dSAlex Tomas 
3253fb0a387dSEric Sandeen 		/* non-extent files can't have physical blocks past 2^32 */
325412e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3255fb0a387dSEric Sandeen 			pa->pa_pstart + pa->pa_len > EXT4_MAX_BLOCK_FILE_PHYS)
3256fb0a387dSEric Sandeen 			continue;
3257fb0a387dSEric Sandeen 
3258c9de560dSAlex Tomas 		/* found preallocated blocks, use them */
3259c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3260c9de560dSAlex Tomas 		if (pa->pa_deleted == 0 && pa->pa_free) {
3261c9de560dSAlex Tomas 			atomic_inc(&pa->pa_count);
3262c9de560dSAlex Tomas 			ext4_mb_use_inode_pa(ac, pa);
3263c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3264c9de560dSAlex Tomas 			ac->ac_criteria = 10;
3265c9de560dSAlex Tomas 			rcu_read_unlock();
3266c9de560dSAlex Tomas 			return 1;
3267c9de560dSAlex Tomas 		}
3268c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3269c9de560dSAlex Tomas 	}
3270c9de560dSAlex Tomas 	rcu_read_unlock();
3271c9de560dSAlex Tomas 
3272c9de560dSAlex Tomas 	/* can we use group allocation? */
3273c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3274c9de560dSAlex Tomas 		return 0;
3275c9de560dSAlex Tomas 
3276c9de560dSAlex Tomas 	/* inode may have no locality group for some reason */
3277c9de560dSAlex Tomas 	lg = ac->ac_lg;
3278c9de560dSAlex Tomas 	if (lg == NULL)
3279c9de560dSAlex Tomas 		return 0;
32806be2ded1SAneesh Kumar K.V 	order  = fls(ac->ac_o_ex.fe_len) - 1;
32816be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
32826be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
32836be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
3284c9de560dSAlex Tomas 
3285bda00de7SAkinobu Mita 	goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
32865e745b04SAneesh Kumar K.V 	/*
32875e745b04SAneesh Kumar K.V 	 * search for the prealloc space that is having
32885e745b04SAneesh Kumar K.V 	 * minimal distance from the goal block.
32895e745b04SAneesh Kumar K.V 	 */
32906be2ded1SAneesh Kumar K.V 	for (i = order; i < PREALLOC_TB_SIZE; i++) {
3291c9de560dSAlex Tomas 		rcu_read_lock();
32926be2ded1SAneesh Kumar K.V 		list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
32936be2ded1SAneesh Kumar K.V 					pa_inode_list) {
3294c9de560dSAlex Tomas 			spin_lock(&pa->pa_lock);
32956be2ded1SAneesh Kumar K.V 			if (pa->pa_deleted == 0 &&
32966be2ded1SAneesh Kumar K.V 					pa->pa_free >= ac->ac_o_ex.fe_len) {
32975e745b04SAneesh Kumar K.V 
32985e745b04SAneesh Kumar K.V 				cpa = ext4_mb_check_group_pa(goal_block,
32995e745b04SAneesh Kumar K.V 								pa, cpa);
33005e745b04SAneesh Kumar K.V 			}
3301c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
33025e745b04SAneesh Kumar K.V 		}
33035e745b04SAneesh Kumar K.V 		rcu_read_unlock();
33045e745b04SAneesh Kumar K.V 	}
33055e745b04SAneesh Kumar K.V 	if (cpa) {
33065e745b04SAneesh Kumar K.V 		ext4_mb_use_group_pa(ac, cpa);
3307c9de560dSAlex Tomas 		ac->ac_criteria = 20;
3308c9de560dSAlex Tomas 		return 1;
3309c9de560dSAlex Tomas 	}
3310c9de560dSAlex Tomas 	return 0;
3311c9de560dSAlex Tomas }
3312c9de560dSAlex Tomas 
3313c9de560dSAlex Tomas /*
33147a2fcbf7SAneesh Kumar K.V  * the function goes through all block freed in the group
33157a2fcbf7SAneesh Kumar K.V  * but not yet committed and marks them used in in-core bitmap.
33167a2fcbf7SAneesh Kumar K.V  * buddy must be generated from this bitmap
3317955ce5f5SAneesh Kumar K.V  * Need to be called with the ext4 group lock held
33187a2fcbf7SAneesh Kumar K.V  */
33197a2fcbf7SAneesh Kumar K.V static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
33207a2fcbf7SAneesh Kumar K.V 						ext4_group_t group)
33217a2fcbf7SAneesh Kumar K.V {
33227a2fcbf7SAneesh Kumar K.V 	struct rb_node *n;
33237a2fcbf7SAneesh Kumar K.V 	struct ext4_group_info *grp;
33247a2fcbf7SAneesh Kumar K.V 	struct ext4_free_data *entry;
33257a2fcbf7SAneesh Kumar K.V 
33267a2fcbf7SAneesh Kumar K.V 	grp = ext4_get_group_info(sb, group);
33277a2fcbf7SAneesh Kumar K.V 	n = rb_first(&(grp->bb_free_root));
33287a2fcbf7SAneesh Kumar K.V 
33297a2fcbf7SAneesh Kumar K.V 	while (n) {
33307a2fcbf7SAneesh Kumar K.V 		entry = rb_entry(n, struct ext4_free_data, node);
3331955ce5f5SAneesh Kumar K.V 		mb_set_bits(bitmap, entry->start_blk, entry->count);
33327a2fcbf7SAneesh Kumar K.V 		n = rb_next(n);
33337a2fcbf7SAneesh Kumar K.V 	}
33347a2fcbf7SAneesh Kumar K.V 	return;
33357a2fcbf7SAneesh Kumar K.V }
33367a2fcbf7SAneesh Kumar K.V 
33377a2fcbf7SAneesh Kumar K.V /*
3338c9de560dSAlex Tomas  * the function goes through all preallocation in this group and marks them
3339c9de560dSAlex Tomas  * used in in-core bitmap. buddy must be generated from this bitmap
3340955ce5f5SAneesh Kumar K.V  * Need to be called with ext4 group lock held
3341c9de560dSAlex Tomas  */
3342089ceeccSEric Sandeen static noinline_for_stack
3343089ceeccSEric Sandeen void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3344c9de560dSAlex Tomas 					ext4_group_t group)
3345c9de560dSAlex Tomas {
3346c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3347c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3348c9de560dSAlex Tomas 	struct list_head *cur;
3349c9de560dSAlex Tomas 	ext4_group_t groupnr;
3350c9de560dSAlex Tomas 	ext4_grpblk_t start;
3351c9de560dSAlex Tomas 	int preallocated = 0;
3352c9de560dSAlex Tomas 	int count = 0;
3353c9de560dSAlex Tomas 	int len;
3354c9de560dSAlex Tomas 
3355c9de560dSAlex Tomas 	/* all form of preallocation discards first load group,
3356c9de560dSAlex Tomas 	 * so the only competing code is preallocation use.
3357c9de560dSAlex Tomas 	 * we don't need any locking here
3358c9de560dSAlex Tomas 	 * notice we do NOT ignore preallocations with pa_deleted
3359c9de560dSAlex Tomas 	 * otherwise we could leave used blocks available for
3360c9de560dSAlex Tomas 	 * allocation in buddy when concurrent ext4_mb_put_pa()
3361c9de560dSAlex Tomas 	 * is dropping preallocation
3362c9de560dSAlex Tomas 	 */
3363c9de560dSAlex Tomas 	list_for_each(cur, &grp->bb_prealloc_list) {
3364c9de560dSAlex Tomas 		pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3365c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3366c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3367c9de560dSAlex Tomas 					     &groupnr, &start);
3368c9de560dSAlex Tomas 		len = pa->pa_len;
3369c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3370c9de560dSAlex Tomas 		if (unlikely(len == 0))
3371c9de560dSAlex Tomas 			continue;
3372c9de560dSAlex Tomas 		BUG_ON(groupnr != group);
3373955ce5f5SAneesh Kumar K.V 		mb_set_bits(bitmap, start, len);
3374c9de560dSAlex Tomas 		preallocated += len;
3375c9de560dSAlex Tomas 		count++;
3376c9de560dSAlex Tomas 	}
33776ba495e9STheodore Ts'o 	mb_debug(1, "prellocated %u for group %u\n", preallocated, group);
3378c9de560dSAlex Tomas }
3379c9de560dSAlex Tomas 
3380c9de560dSAlex Tomas static void ext4_mb_pa_callback(struct rcu_head *head)
3381c9de560dSAlex Tomas {
3382c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3383c9de560dSAlex Tomas 	pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3384c9de560dSAlex Tomas 	kmem_cache_free(ext4_pspace_cachep, pa);
3385c9de560dSAlex Tomas }
3386c9de560dSAlex Tomas 
3387c9de560dSAlex Tomas /*
3388c9de560dSAlex Tomas  * drops a reference to preallocated space descriptor
3389c9de560dSAlex Tomas  * if this was the last reference and the space is consumed
3390c9de560dSAlex Tomas  */
3391c9de560dSAlex Tomas static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3392c9de560dSAlex Tomas 			struct super_block *sb, struct ext4_prealloc_space *pa)
3393c9de560dSAlex Tomas {
3394a9df9a49STheodore Ts'o 	ext4_group_t grp;
3395d33a1976SEric Sandeen 	ext4_fsblk_t grp_blk;
3396c9de560dSAlex Tomas 
3397c9de560dSAlex Tomas 	if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3398c9de560dSAlex Tomas 		return;
3399c9de560dSAlex Tomas 
3400c9de560dSAlex Tomas 	/* in this short window concurrent discard can set pa_deleted */
3401c9de560dSAlex Tomas 	spin_lock(&pa->pa_lock);
3402c9de560dSAlex Tomas 	if (pa->pa_deleted == 1) {
3403c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3404c9de560dSAlex Tomas 		return;
3405c9de560dSAlex Tomas 	}
3406c9de560dSAlex Tomas 
3407c9de560dSAlex Tomas 	pa->pa_deleted = 1;
3408c9de560dSAlex Tomas 	spin_unlock(&pa->pa_lock);
3409c9de560dSAlex Tomas 
3410d33a1976SEric Sandeen 	grp_blk = pa->pa_pstart;
3411cc0fb9adSAneesh Kumar K.V 	/*
3412cc0fb9adSAneesh Kumar K.V 	 * If doing group-based preallocation, pa_pstart may be in the
3413cc0fb9adSAneesh Kumar K.V 	 * next group when pa is used up
3414cc0fb9adSAneesh Kumar K.V 	 */
3415cc0fb9adSAneesh Kumar K.V 	if (pa->pa_type == MB_GROUP_PA)
3416d33a1976SEric Sandeen 		grp_blk--;
3417d33a1976SEric Sandeen 
3418d33a1976SEric Sandeen 	ext4_get_group_no_and_offset(sb, grp_blk, &grp, NULL);
3419c9de560dSAlex Tomas 
3420c9de560dSAlex Tomas 	/*
3421c9de560dSAlex Tomas 	 * possible race:
3422c9de560dSAlex Tomas 	 *
3423c9de560dSAlex Tomas 	 *  P1 (buddy init)			P2 (regular allocation)
3424c9de560dSAlex Tomas 	 *					find block B in PA
3425c9de560dSAlex Tomas 	 *  copy on-disk bitmap to buddy
3426c9de560dSAlex Tomas 	 *  					mark B in on-disk bitmap
3427c9de560dSAlex Tomas 	 *					drop PA from group
3428c9de560dSAlex Tomas 	 *  mark all PAs in buddy
3429c9de560dSAlex Tomas 	 *
3430c9de560dSAlex Tomas 	 * thus, P1 initializes buddy with B available. to prevent this
3431c9de560dSAlex Tomas 	 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3432c9de560dSAlex Tomas 	 * against that pair
3433c9de560dSAlex Tomas 	 */
3434c9de560dSAlex Tomas 	ext4_lock_group(sb, grp);
3435c9de560dSAlex Tomas 	list_del(&pa->pa_group_list);
3436c9de560dSAlex Tomas 	ext4_unlock_group(sb, grp);
3437c9de560dSAlex Tomas 
3438c9de560dSAlex Tomas 	spin_lock(pa->pa_obj_lock);
3439c9de560dSAlex Tomas 	list_del_rcu(&pa->pa_inode_list);
3440c9de560dSAlex Tomas 	spin_unlock(pa->pa_obj_lock);
3441c9de560dSAlex Tomas 
3442c9de560dSAlex Tomas 	call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3443c9de560dSAlex Tomas }
3444c9de560dSAlex Tomas 
3445c9de560dSAlex Tomas /*
3446c9de560dSAlex Tomas  * creates new preallocated space for given inode
3447c9de560dSAlex Tomas  */
34484ddfef7bSEric Sandeen static noinline_for_stack int
34494ddfef7bSEric Sandeen ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3450c9de560dSAlex Tomas {
3451c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
3452c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3453c9de560dSAlex Tomas 	struct ext4_group_info *grp;
3454c9de560dSAlex Tomas 	struct ext4_inode_info *ei;
3455c9de560dSAlex Tomas 
3456c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
3457c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3458c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3459c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3460c9de560dSAlex Tomas 
3461c9de560dSAlex Tomas 	pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3462c9de560dSAlex Tomas 	if (pa == NULL)
3463c9de560dSAlex Tomas 		return -ENOMEM;
3464c9de560dSAlex Tomas 
3465c9de560dSAlex Tomas 	if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3466c9de560dSAlex Tomas 		int winl;
3467c9de560dSAlex Tomas 		int wins;
3468c9de560dSAlex Tomas 		int win;
3469c9de560dSAlex Tomas 		int offs;
3470c9de560dSAlex Tomas 
3471c9de560dSAlex Tomas 		/* we can't allocate as much as normalizer wants.
3472c9de560dSAlex Tomas 		 * so, found space must get proper lstart
3473c9de560dSAlex Tomas 		 * to cover original request */
3474c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3475c9de560dSAlex Tomas 		BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3476c9de560dSAlex Tomas 
3477c9de560dSAlex Tomas 		/* we're limited by original request in that
3478c9de560dSAlex Tomas 		 * logical block must be covered any way
3479c9de560dSAlex Tomas 		 * winl is window we can move our chunk within */
3480c9de560dSAlex Tomas 		winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3481c9de560dSAlex Tomas 
3482c9de560dSAlex Tomas 		/* also, we should cover whole original request */
3483c9de560dSAlex Tomas 		wins = ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len;
3484c9de560dSAlex Tomas 
3485c9de560dSAlex Tomas 		/* the smallest one defines real window */
3486c9de560dSAlex Tomas 		win = min(winl, wins);
3487c9de560dSAlex Tomas 
3488c9de560dSAlex Tomas 		offs = ac->ac_o_ex.fe_logical % ac->ac_b_ex.fe_len;
3489c9de560dSAlex Tomas 		if (offs && offs < win)
3490c9de560dSAlex Tomas 			win = offs;
3491c9de560dSAlex Tomas 
3492c9de560dSAlex Tomas 		ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical - win;
3493c9de560dSAlex Tomas 		BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3494c9de560dSAlex Tomas 		BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3495c9de560dSAlex Tomas 	}
3496c9de560dSAlex Tomas 
3497c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
3498c9de560dSAlex Tomas 	 * allocated blocks for history */
3499c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
3500c9de560dSAlex Tomas 
3501c9de560dSAlex Tomas 	pa->pa_lstart = ac->ac_b_ex.fe_logical;
3502c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3503c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
3504c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
3505c9de560dSAlex Tomas 	atomic_set(&pa->pa_count, 1);
3506c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
3507d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_inode_list);
3508d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
3509c9de560dSAlex Tomas 	pa->pa_deleted = 0;
3510cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_INODE_PA;
3511c9de560dSAlex Tomas 
35126ba495e9STheodore Ts'o 	mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3513c9de560dSAlex Tomas 			pa->pa_pstart, pa->pa_len, pa->pa_lstart);
35149bffad1eSTheodore Ts'o 	trace_ext4_mb_new_inode_pa(ac, pa);
3515c9de560dSAlex Tomas 
3516c9de560dSAlex Tomas 	ext4_mb_use_inode_pa(ac, pa);
3517c9de560dSAlex Tomas 	atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3518c9de560dSAlex Tomas 
3519c9de560dSAlex Tomas 	ei = EXT4_I(ac->ac_inode);
3520c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3521c9de560dSAlex Tomas 
3522c9de560dSAlex Tomas 	pa->pa_obj_lock = &ei->i_prealloc_lock;
3523c9de560dSAlex Tomas 	pa->pa_inode = ac->ac_inode;
3524c9de560dSAlex Tomas 
3525c9de560dSAlex Tomas 	ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3526c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3527c9de560dSAlex Tomas 	ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3528c9de560dSAlex Tomas 
3529c9de560dSAlex Tomas 	spin_lock(pa->pa_obj_lock);
3530c9de560dSAlex Tomas 	list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3531c9de560dSAlex Tomas 	spin_unlock(pa->pa_obj_lock);
3532c9de560dSAlex Tomas 
3533c9de560dSAlex Tomas 	return 0;
3534c9de560dSAlex Tomas }
3535c9de560dSAlex Tomas 
3536c9de560dSAlex Tomas /*
3537c9de560dSAlex Tomas  * creates new preallocated space for locality group inodes belongs to
3538c9de560dSAlex Tomas  */
35394ddfef7bSEric Sandeen static noinline_for_stack int
35404ddfef7bSEric Sandeen ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3541c9de560dSAlex Tomas {
3542c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
3543c9de560dSAlex Tomas 	struct ext4_locality_group *lg;
3544c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa;
3545c9de560dSAlex Tomas 	struct ext4_group_info *grp;
3546c9de560dSAlex Tomas 
3547c9de560dSAlex Tomas 	/* preallocate only when found space is larger then requested */
3548c9de560dSAlex Tomas 	BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3549c9de560dSAlex Tomas 	BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3550c9de560dSAlex Tomas 	BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3551c9de560dSAlex Tomas 
3552c9de560dSAlex Tomas 	BUG_ON(ext4_pspace_cachep == NULL);
3553c9de560dSAlex Tomas 	pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3554c9de560dSAlex Tomas 	if (pa == NULL)
3555c9de560dSAlex Tomas 		return -ENOMEM;
3556c9de560dSAlex Tomas 
3557c9de560dSAlex Tomas 	/* preallocation can change ac_b_ex, thus we store actually
3558c9de560dSAlex Tomas 	 * allocated blocks for history */
3559c9de560dSAlex Tomas 	ac->ac_f_ex = ac->ac_b_ex;
3560c9de560dSAlex Tomas 
3561c9de560dSAlex Tomas 	pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3562c9de560dSAlex Tomas 	pa->pa_lstart = pa->pa_pstart;
3563c9de560dSAlex Tomas 	pa->pa_len = ac->ac_b_ex.fe_len;
3564c9de560dSAlex Tomas 	pa->pa_free = pa->pa_len;
3565c9de560dSAlex Tomas 	atomic_set(&pa->pa_count, 1);
3566c9de560dSAlex Tomas 	spin_lock_init(&pa->pa_lock);
35676be2ded1SAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_inode_list);
3568d794bf8eSAneesh Kumar K.V 	INIT_LIST_HEAD(&pa->pa_group_list);
3569c9de560dSAlex Tomas 	pa->pa_deleted = 0;
3570cc0fb9adSAneesh Kumar K.V 	pa->pa_type = MB_GROUP_PA;
3571c9de560dSAlex Tomas 
35726ba495e9STheodore Ts'o 	mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3573c9de560dSAlex Tomas 			pa->pa_pstart, pa->pa_len, pa->pa_lstart);
35749bffad1eSTheodore Ts'o 	trace_ext4_mb_new_group_pa(ac, pa);
3575c9de560dSAlex Tomas 
3576c9de560dSAlex Tomas 	ext4_mb_use_group_pa(ac, pa);
3577c9de560dSAlex Tomas 	atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3578c9de560dSAlex Tomas 
3579c9de560dSAlex Tomas 	grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3580c9de560dSAlex Tomas 	lg = ac->ac_lg;
3581c9de560dSAlex Tomas 	BUG_ON(lg == NULL);
3582c9de560dSAlex Tomas 
3583c9de560dSAlex Tomas 	pa->pa_obj_lock = &lg->lg_prealloc_lock;
3584c9de560dSAlex Tomas 	pa->pa_inode = NULL;
3585c9de560dSAlex Tomas 
3586c9de560dSAlex Tomas 	ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3587c9de560dSAlex Tomas 	list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3588c9de560dSAlex Tomas 	ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3589c9de560dSAlex Tomas 
35906be2ded1SAneesh Kumar K.V 	/*
35916be2ded1SAneesh Kumar K.V 	 * We will later add the new pa to the right bucket
35926be2ded1SAneesh Kumar K.V 	 * after updating the pa_free in ext4_mb_release_context
35936be2ded1SAneesh Kumar K.V 	 */
3594c9de560dSAlex Tomas 	return 0;
3595c9de560dSAlex Tomas }
3596c9de560dSAlex Tomas 
3597c9de560dSAlex Tomas static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3598c9de560dSAlex Tomas {
3599c9de560dSAlex Tomas 	int err;
3600c9de560dSAlex Tomas 
3601c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3602c9de560dSAlex Tomas 		err = ext4_mb_new_group_pa(ac);
3603c9de560dSAlex Tomas 	else
3604c9de560dSAlex Tomas 		err = ext4_mb_new_inode_pa(ac);
3605c9de560dSAlex Tomas 	return err;
3606c9de560dSAlex Tomas }
3607c9de560dSAlex Tomas 
3608c9de560dSAlex Tomas /*
3609c9de560dSAlex Tomas  * finds all unused blocks in on-disk bitmap, frees them in
3610c9de560dSAlex Tomas  * in-core bitmap and buddy.
3611c9de560dSAlex Tomas  * @pa must be unlinked from inode and group lists, so that
3612c9de560dSAlex Tomas  * nobody else can find/use it.
3613c9de560dSAlex Tomas  * the caller MUST hold group/inode locks.
3614c9de560dSAlex Tomas  * TODO: optimize the case when there are no in-core structures yet
3615c9de560dSAlex Tomas  */
36164ddfef7bSEric Sandeen static noinline_for_stack int
36174ddfef7bSEric Sandeen ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
36183e1e5f50SEric Sandeen 			struct ext4_prealloc_space *pa)
3619c9de560dSAlex Tomas {
3620c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
3621c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
3622498e5f24STheodore Ts'o 	unsigned int end;
3623498e5f24STheodore Ts'o 	unsigned int next;
3624c9de560dSAlex Tomas 	ext4_group_t group;
3625c9de560dSAlex Tomas 	ext4_grpblk_t bit;
3626ba80b101STheodore Ts'o 	unsigned long long grp_blk_start;
3627c9de560dSAlex Tomas 	int err = 0;
3628c9de560dSAlex Tomas 	int free = 0;
3629c9de560dSAlex Tomas 
3630c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
3631c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3632ba80b101STheodore Ts'o 	grp_blk_start = pa->pa_pstart - bit;
3633c9de560dSAlex Tomas 	BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3634c9de560dSAlex Tomas 	end = bit + pa->pa_len;
3635c9de560dSAlex Tomas 
3636c9de560dSAlex Tomas 	while (bit < end) {
3637ffad0a44SAneesh Kumar K.V 		bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3638c9de560dSAlex Tomas 		if (bit >= end)
3639c9de560dSAlex Tomas 			break;
3640ffad0a44SAneesh Kumar K.V 		next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
36416ba495e9STheodore Ts'o 		mb_debug(1, "    free preallocated %u/%u in group %u\n",
36425a0790c2SAndi Kleen 			 (unsigned) ext4_group_first_block_no(sb, group) + bit,
36435a0790c2SAndi Kleen 			 (unsigned) next - bit, (unsigned) group);
3644c9de560dSAlex Tomas 		free += next - bit;
3645c9de560dSAlex Tomas 
36463e1e5f50SEric Sandeen 		trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
36473e1e5f50SEric Sandeen 		trace_ext4_mb_release_inode_pa(sb, pa->pa_inode, pa,
36483e1e5f50SEric Sandeen 					       grp_blk_start + bit, next - bit);
3649c9de560dSAlex Tomas 		mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3650c9de560dSAlex Tomas 		bit = next + 1;
3651c9de560dSAlex Tomas 	}
3652c9de560dSAlex Tomas 	if (free != pa->pa_free) {
365326346ff6SAneesh Kumar K.V 		printk(KERN_CRIT "pa %p: logic %lu, phys. %lu, len %lu\n",
3654c9de560dSAlex Tomas 			pa, (unsigned long) pa->pa_lstart,
3655c9de560dSAlex Tomas 			(unsigned long) pa->pa_pstart,
3656c9de560dSAlex Tomas 			(unsigned long) pa->pa_len);
3657e29136f8STheodore Ts'o 		ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
365826346ff6SAneesh Kumar K.V 					free, pa->pa_free);
3659e56eb659SAneesh Kumar K.V 		/*
3660e56eb659SAneesh Kumar K.V 		 * pa is already deleted so we use the value obtained
3661e56eb659SAneesh Kumar K.V 		 * from the bitmap and continue.
3662e56eb659SAneesh Kumar K.V 		 */
3663c9de560dSAlex Tomas 	}
3664c9de560dSAlex Tomas 	atomic_add(free, &sbi->s_mb_discarded);
3665c9de560dSAlex Tomas 
3666c9de560dSAlex Tomas 	return err;
3667c9de560dSAlex Tomas }
3668c9de560dSAlex Tomas 
36694ddfef7bSEric Sandeen static noinline_for_stack int
36704ddfef7bSEric Sandeen ext4_mb_release_group_pa(struct ext4_buddy *e4b,
36713e1e5f50SEric Sandeen 				struct ext4_prealloc_space *pa)
3672c9de560dSAlex Tomas {
3673c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
3674c9de560dSAlex Tomas 	ext4_group_t group;
3675c9de560dSAlex Tomas 	ext4_grpblk_t bit;
3676c9de560dSAlex Tomas 
36773e1e5f50SEric Sandeen 	trace_ext4_mb_release_group_pa(sb, pa);
3678c9de560dSAlex Tomas 	BUG_ON(pa->pa_deleted == 0);
3679c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3680c9de560dSAlex Tomas 	BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3681c9de560dSAlex Tomas 	mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3682c9de560dSAlex Tomas 	atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
36833e1e5f50SEric Sandeen 	trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3684c9de560dSAlex Tomas 
3685c9de560dSAlex Tomas 	return 0;
3686c9de560dSAlex Tomas }
3687c9de560dSAlex Tomas 
3688c9de560dSAlex Tomas /*
3689c9de560dSAlex Tomas  * releases all preallocations in given group
3690c9de560dSAlex Tomas  *
3691c9de560dSAlex Tomas  * first, we need to decide discard policy:
3692c9de560dSAlex Tomas  * - when do we discard
3693c9de560dSAlex Tomas  *   1) ENOSPC
3694c9de560dSAlex Tomas  * - how many do we discard
3695c9de560dSAlex Tomas  *   1) how many requested
3696c9de560dSAlex Tomas  */
36974ddfef7bSEric Sandeen static noinline_for_stack int
36984ddfef7bSEric Sandeen ext4_mb_discard_group_preallocations(struct super_block *sb,
3699c9de560dSAlex Tomas 					ext4_group_t group, int needed)
3700c9de560dSAlex Tomas {
3701c9de560dSAlex Tomas 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3702c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
3703c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
3704c9de560dSAlex Tomas 	struct list_head list;
3705c9de560dSAlex Tomas 	struct ext4_buddy e4b;
3706c9de560dSAlex Tomas 	int err;
3707c9de560dSAlex Tomas 	int busy = 0;
3708c9de560dSAlex Tomas 	int free = 0;
3709c9de560dSAlex Tomas 
37106ba495e9STheodore Ts'o 	mb_debug(1, "discard preallocation for group %u\n", group);
3711c9de560dSAlex Tomas 
3712c9de560dSAlex Tomas 	if (list_empty(&grp->bb_prealloc_list))
3713c9de560dSAlex Tomas 		return 0;
3714c9de560dSAlex Tomas 
3715574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, group);
3716c9de560dSAlex Tomas 	if (bitmap_bh == NULL) {
371712062dddSEric Sandeen 		ext4_error(sb, "Error reading block bitmap for %u", group);
3718ce89f46cSAneesh Kumar K.V 		return 0;
3719c9de560dSAlex Tomas 	}
3720c9de560dSAlex Tomas 
3721c9de560dSAlex Tomas 	err = ext4_mb_load_buddy(sb, group, &e4b);
3722ce89f46cSAneesh Kumar K.V 	if (err) {
372312062dddSEric Sandeen 		ext4_error(sb, "Error loading buddy information for %u", group);
3724ce89f46cSAneesh Kumar K.V 		put_bh(bitmap_bh);
3725ce89f46cSAneesh Kumar K.V 		return 0;
3726ce89f46cSAneesh Kumar K.V 	}
3727c9de560dSAlex Tomas 
3728c9de560dSAlex Tomas 	if (needed == 0)
3729c9de560dSAlex Tomas 		needed = EXT4_BLOCKS_PER_GROUP(sb) + 1;
3730c9de560dSAlex Tomas 
3731c9de560dSAlex Tomas 	INIT_LIST_HEAD(&list);
3732c9de560dSAlex Tomas repeat:
3733c9de560dSAlex Tomas 	ext4_lock_group(sb, group);
3734c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp,
3735c9de560dSAlex Tomas 				&grp->bb_prealloc_list, pa_group_list) {
3736c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3737c9de560dSAlex Tomas 		if (atomic_read(&pa->pa_count)) {
3738c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3739c9de560dSAlex Tomas 			busy = 1;
3740c9de560dSAlex Tomas 			continue;
3741c9de560dSAlex Tomas 		}
3742c9de560dSAlex Tomas 		if (pa->pa_deleted) {
3743c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3744c9de560dSAlex Tomas 			continue;
3745c9de560dSAlex Tomas 		}
3746c9de560dSAlex Tomas 
3747c9de560dSAlex Tomas 		/* seems this one can be freed ... */
3748c9de560dSAlex Tomas 		pa->pa_deleted = 1;
3749c9de560dSAlex Tomas 
3750c9de560dSAlex Tomas 		/* we can trust pa_free ... */
3751c9de560dSAlex Tomas 		free += pa->pa_free;
3752c9de560dSAlex Tomas 
3753c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3754c9de560dSAlex Tomas 
3755c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
3756c9de560dSAlex Tomas 		list_add(&pa->u.pa_tmp_list, &list);
3757c9de560dSAlex Tomas 	}
3758c9de560dSAlex Tomas 
3759c9de560dSAlex Tomas 	/* if we still need more blocks and some PAs were used, try again */
3760c9de560dSAlex Tomas 	if (free < needed && busy) {
3761c9de560dSAlex Tomas 		busy = 0;
3762c9de560dSAlex Tomas 		ext4_unlock_group(sb, group);
3763c9de560dSAlex Tomas 		/*
3764c9de560dSAlex Tomas 		 * Yield the CPU here so that we don't get soft lockup
3765c9de560dSAlex Tomas 		 * in non preempt case.
3766c9de560dSAlex Tomas 		 */
3767c9de560dSAlex Tomas 		yield();
3768c9de560dSAlex Tomas 		goto repeat;
3769c9de560dSAlex Tomas 	}
3770c9de560dSAlex Tomas 
3771c9de560dSAlex Tomas 	/* found anything to free? */
3772c9de560dSAlex Tomas 	if (list_empty(&list)) {
3773c9de560dSAlex Tomas 		BUG_ON(free != 0);
3774c9de560dSAlex Tomas 		goto out;
3775c9de560dSAlex Tomas 	}
3776c9de560dSAlex Tomas 
3777c9de560dSAlex Tomas 	/* now free all selected PAs */
3778c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3779c9de560dSAlex Tomas 
3780c9de560dSAlex Tomas 		/* remove from object (inode or locality group) */
3781c9de560dSAlex Tomas 		spin_lock(pa->pa_obj_lock);
3782c9de560dSAlex Tomas 		list_del_rcu(&pa->pa_inode_list);
3783c9de560dSAlex Tomas 		spin_unlock(pa->pa_obj_lock);
3784c9de560dSAlex Tomas 
3785cc0fb9adSAneesh Kumar K.V 		if (pa->pa_type == MB_GROUP_PA)
37863e1e5f50SEric Sandeen 			ext4_mb_release_group_pa(&e4b, pa);
3787c9de560dSAlex Tomas 		else
37883e1e5f50SEric Sandeen 			ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3789c9de560dSAlex Tomas 
3790c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
3791c9de560dSAlex Tomas 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3792c9de560dSAlex Tomas 	}
3793c9de560dSAlex Tomas 
3794c9de560dSAlex Tomas out:
3795c9de560dSAlex Tomas 	ext4_unlock_group(sb, group);
3796e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
3797c9de560dSAlex Tomas 	put_bh(bitmap_bh);
3798c9de560dSAlex Tomas 	return free;
3799c9de560dSAlex Tomas }
3800c9de560dSAlex Tomas 
3801c9de560dSAlex Tomas /*
3802c9de560dSAlex Tomas  * releases all non-used preallocated blocks for given inode
3803c9de560dSAlex Tomas  *
3804c9de560dSAlex Tomas  * It's important to discard preallocations under i_data_sem
3805c9de560dSAlex Tomas  * We don't want another block to be served from the prealloc
3806c9de560dSAlex Tomas  * space when we are discarding the inode prealloc space.
3807c9de560dSAlex Tomas  *
3808c9de560dSAlex Tomas  * FIXME!! Make sure it is valid at all the call sites
3809c9de560dSAlex Tomas  */
3810c2ea3fdeSTheodore Ts'o void ext4_discard_preallocations(struct inode *inode)
3811c9de560dSAlex Tomas {
3812c9de560dSAlex Tomas 	struct ext4_inode_info *ei = EXT4_I(inode);
3813c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
3814c9de560dSAlex Tomas 	struct buffer_head *bitmap_bh = NULL;
3815c9de560dSAlex Tomas 	struct ext4_prealloc_space *pa, *tmp;
3816c9de560dSAlex Tomas 	ext4_group_t group = 0;
3817c9de560dSAlex Tomas 	struct list_head list;
3818c9de560dSAlex Tomas 	struct ext4_buddy e4b;
3819c9de560dSAlex Tomas 	int err;
3820c9de560dSAlex Tomas 
3821c2ea3fdeSTheodore Ts'o 	if (!S_ISREG(inode->i_mode)) {
3822c9de560dSAlex Tomas 		/*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
3823c9de560dSAlex Tomas 		return;
3824c9de560dSAlex Tomas 	}
3825c9de560dSAlex Tomas 
38266ba495e9STheodore Ts'o 	mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
38279bffad1eSTheodore Ts'o 	trace_ext4_discard_preallocations(inode);
3828c9de560dSAlex Tomas 
3829c9de560dSAlex Tomas 	INIT_LIST_HEAD(&list);
3830c9de560dSAlex Tomas 
3831c9de560dSAlex Tomas repeat:
3832c9de560dSAlex Tomas 	/* first, collect all pa's in the inode */
3833c9de560dSAlex Tomas 	spin_lock(&ei->i_prealloc_lock);
3834c9de560dSAlex Tomas 	while (!list_empty(&ei->i_prealloc_list)) {
3835c9de560dSAlex Tomas 		pa = list_entry(ei->i_prealloc_list.next,
3836c9de560dSAlex Tomas 				struct ext4_prealloc_space, pa_inode_list);
3837c9de560dSAlex Tomas 		BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
3838c9de560dSAlex Tomas 		spin_lock(&pa->pa_lock);
3839c9de560dSAlex Tomas 		if (atomic_read(&pa->pa_count)) {
3840c9de560dSAlex Tomas 			/* this shouldn't happen often - nobody should
3841c9de560dSAlex Tomas 			 * use preallocation while we're discarding it */
3842c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3843c9de560dSAlex Tomas 			spin_unlock(&ei->i_prealloc_lock);
3844c9de560dSAlex Tomas 			printk(KERN_ERR "uh-oh! used pa while discarding\n");
3845c9de560dSAlex Tomas 			WARN_ON(1);
3846c9de560dSAlex Tomas 			schedule_timeout_uninterruptible(HZ);
3847c9de560dSAlex Tomas 			goto repeat;
3848c9de560dSAlex Tomas 
3849c9de560dSAlex Tomas 		}
3850c9de560dSAlex Tomas 		if (pa->pa_deleted == 0) {
3851c9de560dSAlex Tomas 			pa->pa_deleted = 1;
3852c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
3853c9de560dSAlex Tomas 			list_del_rcu(&pa->pa_inode_list);
3854c9de560dSAlex Tomas 			list_add(&pa->u.pa_tmp_list, &list);
3855c9de560dSAlex Tomas 			continue;
3856c9de560dSAlex Tomas 		}
3857c9de560dSAlex Tomas 
3858c9de560dSAlex Tomas 		/* someone is deleting pa right now */
3859c9de560dSAlex Tomas 		spin_unlock(&pa->pa_lock);
3860c9de560dSAlex Tomas 		spin_unlock(&ei->i_prealloc_lock);
3861c9de560dSAlex Tomas 
3862c9de560dSAlex Tomas 		/* we have to wait here because pa_deleted
3863c9de560dSAlex Tomas 		 * doesn't mean pa is already unlinked from
3864c9de560dSAlex Tomas 		 * the list. as we might be called from
3865c9de560dSAlex Tomas 		 * ->clear_inode() the inode will get freed
3866c9de560dSAlex Tomas 		 * and concurrent thread which is unlinking
3867c9de560dSAlex Tomas 		 * pa from inode's list may access already
3868c9de560dSAlex Tomas 		 * freed memory, bad-bad-bad */
3869c9de560dSAlex Tomas 
3870c9de560dSAlex Tomas 		/* XXX: if this happens too often, we can
3871c9de560dSAlex Tomas 		 * add a flag to force wait only in case
3872c9de560dSAlex Tomas 		 * of ->clear_inode(), but not in case of
3873c9de560dSAlex Tomas 		 * regular truncate */
3874c9de560dSAlex Tomas 		schedule_timeout_uninterruptible(HZ);
3875c9de560dSAlex Tomas 		goto repeat;
3876c9de560dSAlex Tomas 	}
3877c9de560dSAlex Tomas 	spin_unlock(&ei->i_prealloc_lock);
3878c9de560dSAlex Tomas 
3879c9de560dSAlex Tomas 	list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3880cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_INODE_PA);
3881c9de560dSAlex Tomas 		ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
3882c9de560dSAlex Tomas 
3883c9de560dSAlex Tomas 		err = ext4_mb_load_buddy(sb, group, &e4b);
3884ce89f46cSAneesh Kumar K.V 		if (err) {
388512062dddSEric Sandeen 			ext4_error(sb, "Error loading buddy information for %u",
388612062dddSEric Sandeen 					group);
3887ce89f46cSAneesh Kumar K.V 			continue;
3888ce89f46cSAneesh Kumar K.V 		}
3889c9de560dSAlex Tomas 
3890574ca174STheodore Ts'o 		bitmap_bh = ext4_read_block_bitmap(sb, group);
3891c9de560dSAlex Tomas 		if (bitmap_bh == NULL) {
389212062dddSEric Sandeen 			ext4_error(sb, "Error reading block bitmap for %u",
389312062dddSEric Sandeen 					group);
3894e39e07fdSJing Zhang 			ext4_mb_unload_buddy(&e4b);
3895ce89f46cSAneesh Kumar K.V 			continue;
3896c9de560dSAlex Tomas 		}
3897c9de560dSAlex Tomas 
3898c9de560dSAlex Tomas 		ext4_lock_group(sb, group);
3899c9de560dSAlex Tomas 		list_del(&pa->pa_group_list);
39003e1e5f50SEric Sandeen 		ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3901c9de560dSAlex Tomas 		ext4_unlock_group(sb, group);
3902c9de560dSAlex Tomas 
3903e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
3904c9de560dSAlex Tomas 		put_bh(bitmap_bh);
3905c9de560dSAlex Tomas 
3906c9de560dSAlex Tomas 		list_del(&pa->u.pa_tmp_list);
3907c9de560dSAlex Tomas 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3908c9de560dSAlex Tomas 	}
3909c9de560dSAlex Tomas }
3910c9de560dSAlex Tomas 
39116ba495e9STheodore Ts'o #ifdef CONFIG_EXT4_DEBUG
3912c9de560dSAlex Tomas static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3913c9de560dSAlex Tomas {
3914c9de560dSAlex Tomas 	struct super_block *sb = ac->ac_sb;
39158df9675fSTheodore Ts'o 	ext4_group_t ngroups, i;
3916c9de560dSAlex Tomas 
39174dd89fc6STheodore Ts'o 	if (!mb_enable_debug ||
39184dd89fc6STheodore Ts'o 	    (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
3919e3570639SEric Sandeen 		return;
3920e3570639SEric Sandeen 
3921c9de560dSAlex Tomas 	printk(KERN_ERR "EXT4-fs: Can't allocate:"
3922c9de560dSAlex Tomas 			" Allocation context details:\n");
3923c9de560dSAlex Tomas 	printk(KERN_ERR "EXT4-fs: status %d flags %d\n",
3924c9de560dSAlex Tomas 			ac->ac_status, ac->ac_flags);
3925c9de560dSAlex Tomas 	printk(KERN_ERR "EXT4-fs: orig %lu/%lu/%lu@%lu, goal %lu/%lu/%lu@%lu, "
3926c9de560dSAlex Tomas 			"best %lu/%lu/%lu@%lu cr %d\n",
3927c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_group,
3928c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_start,
3929c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_len,
3930c9de560dSAlex Tomas 			(unsigned long)ac->ac_o_ex.fe_logical,
3931c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_group,
3932c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_start,
3933c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_len,
3934c9de560dSAlex Tomas 			(unsigned long)ac->ac_g_ex.fe_logical,
3935c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_group,
3936c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_start,
3937c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_len,
3938c9de560dSAlex Tomas 			(unsigned long)ac->ac_b_ex.fe_logical,
3939c9de560dSAlex Tomas 			(int)ac->ac_criteria);
3940c9de560dSAlex Tomas 	printk(KERN_ERR "EXT4-fs: %lu scanned, %d found\n", ac->ac_ex_scanned,
3941c9de560dSAlex Tomas 		ac->ac_found);
3942c9de560dSAlex Tomas 	printk(KERN_ERR "EXT4-fs: groups: \n");
39438df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
39448df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
3945c9de560dSAlex Tomas 		struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3946c9de560dSAlex Tomas 		struct ext4_prealloc_space *pa;
3947c9de560dSAlex Tomas 		ext4_grpblk_t start;
3948c9de560dSAlex Tomas 		struct list_head *cur;
3949c9de560dSAlex Tomas 		ext4_lock_group(sb, i);
3950c9de560dSAlex Tomas 		list_for_each(cur, &grp->bb_prealloc_list) {
3951c9de560dSAlex Tomas 			pa = list_entry(cur, struct ext4_prealloc_space,
3952c9de560dSAlex Tomas 					pa_group_list);
3953c9de560dSAlex Tomas 			spin_lock(&pa->pa_lock);
3954c9de560dSAlex Tomas 			ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3955c9de560dSAlex Tomas 						     NULL, &start);
3956c9de560dSAlex Tomas 			spin_unlock(&pa->pa_lock);
39571c718505SAkira Fujita 			printk(KERN_ERR "PA:%u:%d:%u \n", i,
3958c9de560dSAlex Tomas 			       start, pa->pa_len);
3959c9de560dSAlex Tomas 		}
396060bd63d1SSolofo Ramangalahy 		ext4_unlock_group(sb, i);
3961c9de560dSAlex Tomas 
3962c9de560dSAlex Tomas 		if (grp->bb_free == 0)
3963c9de560dSAlex Tomas 			continue;
39641c718505SAkira Fujita 		printk(KERN_ERR "%u: %d/%d \n",
3965c9de560dSAlex Tomas 		       i, grp->bb_free, grp->bb_fragments);
3966c9de560dSAlex Tomas 	}
3967c9de560dSAlex Tomas 	printk(KERN_ERR "\n");
3968c9de560dSAlex Tomas }
3969c9de560dSAlex Tomas #else
3970c9de560dSAlex Tomas static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3971c9de560dSAlex Tomas {
3972c9de560dSAlex Tomas 	return;
3973c9de560dSAlex Tomas }
3974c9de560dSAlex Tomas #endif
3975c9de560dSAlex Tomas 
3976c9de560dSAlex Tomas /*
3977c9de560dSAlex Tomas  * We use locality group preallocation for small size file. The size of the
3978c9de560dSAlex Tomas  * file is determined by the current size or the resulting size after
3979c9de560dSAlex Tomas  * allocation which ever is larger
3980c9de560dSAlex Tomas  *
3981b713a5ecSTheodore Ts'o  * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
3982c9de560dSAlex Tomas  */
3983c9de560dSAlex Tomas static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
3984c9de560dSAlex Tomas {
3985c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3986c9de560dSAlex Tomas 	int bsbits = ac->ac_sb->s_blocksize_bits;
3987c9de560dSAlex Tomas 	loff_t size, isize;
3988c9de560dSAlex Tomas 
3989c9de560dSAlex Tomas 	if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3990c9de560dSAlex Tomas 		return;
3991c9de560dSAlex Tomas 
39924ba74d00STheodore Ts'o 	if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
39934ba74d00STheodore Ts'o 		return;
39944ba74d00STheodore Ts'o 
3995c9de560dSAlex Tomas 	size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
399650797481STheodore Ts'o 	isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
399750797481STheodore Ts'o 		>> bsbits;
3998c9de560dSAlex Tomas 
399950797481STheodore Ts'o 	if ((size == isize) &&
400050797481STheodore Ts'o 	    !ext4_fs_is_busy(sbi) &&
400150797481STheodore Ts'o 	    (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
400250797481STheodore Ts'o 		ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
400350797481STheodore Ts'o 		return;
400450797481STheodore Ts'o 	}
400550797481STheodore Ts'o 
4006c9de560dSAlex Tomas 	/* don't use group allocation for large files */
400771780577STheodore Ts'o 	size = max(size, isize);
4008cc483f10STao Ma 	if (size > sbi->s_mb_stream_request) {
40094ba74d00STheodore Ts'o 		ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4010c9de560dSAlex Tomas 		return;
40114ba74d00STheodore Ts'o 	}
4012c9de560dSAlex Tomas 
4013c9de560dSAlex Tomas 	BUG_ON(ac->ac_lg != NULL);
4014c9de560dSAlex Tomas 	/*
4015c9de560dSAlex Tomas 	 * locality group prealloc space are per cpu. The reason for having
4016c9de560dSAlex Tomas 	 * per cpu locality group is to reduce the contention between block
4017c9de560dSAlex Tomas 	 * request from multiple CPUs.
4018c9de560dSAlex Tomas 	 */
4019ca0c9584SChristoph Lameter 	ac->ac_lg = __this_cpu_ptr(sbi->s_locality_groups);
4020c9de560dSAlex Tomas 
4021c9de560dSAlex Tomas 	/* we're going to use group allocation */
4022c9de560dSAlex Tomas 	ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4023c9de560dSAlex Tomas 
4024c9de560dSAlex Tomas 	/* serialize all allocations in the group */
4025c9de560dSAlex Tomas 	mutex_lock(&ac->ac_lg->lg_mutex);
4026c9de560dSAlex Tomas }
4027c9de560dSAlex Tomas 
40284ddfef7bSEric Sandeen static noinline_for_stack int
40294ddfef7bSEric Sandeen ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4030c9de560dSAlex Tomas 				struct ext4_allocation_request *ar)
4031c9de560dSAlex Tomas {
4032c9de560dSAlex Tomas 	struct super_block *sb = ar->inode->i_sb;
4033c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
4034c9de560dSAlex Tomas 	struct ext4_super_block *es = sbi->s_es;
4035c9de560dSAlex Tomas 	ext4_group_t group;
4036498e5f24STheodore Ts'o 	unsigned int len;
4037498e5f24STheodore Ts'o 	ext4_fsblk_t goal;
4038c9de560dSAlex Tomas 	ext4_grpblk_t block;
4039c9de560dSAlex Tomas 
4040c9de560dSAlex Tomas 	/* we can't allocate > group size */
4041c9de560dSAlex Tomas 	len = ar->len;
4042c9de560dSAlex Tomas 
4043c9de560dSAlex Tomas 	/* just a dirty hack to filter too big requests  */
4044c9de560dSAlex Tomas 	if (len >= EXT4_BLOCKS_PER_GROUP(sb) - 10)
4045c9de560dSAlex Tomas 		len = EXT4_BLOCKS_PER_GROUP(sb) - 10;
4046c9de560dSAlex Tomas 
4047c9de560dSAlex Tomas 	/* start searching from the goal */
4048c9de560dSAlex Tomas 	goal = ar->goal;
4049c9de560dSAlex Tomas 	if (goal < le32_to_cpu(es->s_first_data_block) ||
4050c9de560dSAlex Tomas 			goal >= ext4_blocks_count(es))
4051c9de560dSAlex Tomas 		goal = le32_to_cpu(es->s_first_data_block);
4052c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, goal, &group, &block);
4053c9de560dSAlex Tomas 
4054c9de560dSAlex Tomas 	/* set up allocation goals */
4055833576b3STheodore Ts'o 	memset(ac, 0, sizeof(struct ext4_allocation_context));
4056c9de560dSAlex Tomas 	ac->ac_b_ex.fe_logical = ar->logical;
4057c9de560dSAlex Tomas 	ac->ac_status = AC_STATUS_CONTINUE;
4058c9de560dSAlex Tomas 	ac->ac_sb = sb;
4059c9de560dSAlex Tomas 	ac->ac_inode = ar->inode;
4060c9de560dSAlex Tomas 	ac->ac_o_ex.fe_logical = ar->logical;
4061c9de560dSAlex Tomas 	ac->ac_o_ex.fe_group = group;
4062c9de560dSAlex Tomas 	ac->ac_o_ex.fe_start = block;
4063c9de560dSAlex Tomas 	ac->ac_o_ex.fe_len = len;
4064c9de560dSAlex Tomas 	ac->ac_g_ex.fe_logical = ar->logical;
4065c9de560dSAlex Tomas 	ac->ac_g_ex.fe_group = group;
4066c9de560dSAlex Tomas 	ac->ac_g_ex.fe_start = block;
4067c9de560dSAlex Tomas 	ac->ac_g_ex.fe_len = len;
4068c9de560dSAlex Tomas 	ac->ac_flags = ar->flags;
4069c9de560dSAlex Tomas 
4070c9de560dSAlex Tomas 	/* we have to define context: we'll we work with a file or
4071c9de560dSAlex Tomas 	 * locality group. this is a policy, actually */
4072c9de560dSAlex Tomas 	ext4_mb_group_or_file(ac);
4073c9de560dSAlex Tomas 
40746ba495e9STheodore Ts'o 	mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4075c9de560dSAlex Tomas 			"left: %u/%u, right %u/%u to %swritable\n",
4076c9de560dSAlex Tomas 			(unsigned) ar->len, (unsigned) ar->logical,
4077c9de560dSAlex Tomas 			(unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4078c9de560dSAlex Tomas 			(unsigned) ar->lleft, (unsigned) ar->pleft,
4079c9de560dSAlex Tomas 			(unsigned) ar->lright, (unsigned) ar->pright,
4080c9de560dSAlex Tomas 			atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4081c9de560dSAlex Tomas 	return 0;
4082c9de560dSAlex Tomas 
4083c9de560dSAlex Tomas }
4084c9de560dSAlex Tomas 
40856be2ded1SAneesh Kumar K.V static noinline_for_stack void
40866be2ded1SAneesh Kumar K.V ext4_mb_discard_lg_preallocations(struct super_block *sb,
40876be2ded1SAneesh Kumar K.V 					struct ext4_locality_group *lg,
40886be2ded1SAneesh Kumar K.V 					int order, int total_entries)
40896be2ded1SAneesh Kumar K.V {
40906be2ded1SAneesh Kumar K.V 	ext4_group_t group = 0;
40916be2ded1SAneesh Kumar K.V 	struct ext4_buddy e4b;
40926be2ded1SAneesh Kumar K.V 	struct list_head discard_list;
40936be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa, *tmp;
40946be2ded1SAneesh Kumar K.V 
40956ba495e9STheodore Ts'o 	mb_debug(1, "discard locality group preallocation\n");
40966be2ded1SAneesh Kumar K.V 
40976be2ded1SAneesh Kumar K.V 	INIT_LIST_HEAD(&discard_list);
40986be2ded1SAneesh Kumar K.V 
40996be2ded1SAneesh Kumar K.V 	spin_lock(&lg->lg_prealloc_lock);
41006be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
41016be2ded1SAneesh Kumar K.V 						pa_inode_list) {
41026be2ded1SAneesh Kumar K.V 		spin_lock(&pa->pa_lock);
41036be2ded1SAneesh Kumar K.V 		if (atomic_read(&pa->pa_count)) {
41046be2ded1SAneesh Kumar K.V 			/*
41056be2ded1SAneesh Kumar K.V 			 * This is the pa that we just used
41066be2ded1SAneesh Kumar K.V 			 * for block allocation. So don't
41076be2ded1SAneesh Kumar K.V 			 * free that
41086be2ded1SAneesh Kumar K.V 			 */
41096be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
41106be2ded1SAneesh Kumar K.V 			continue;
41116be2ded1SAneesh Kumar K.V 		}
41126be2ded1SAneesh Kumar K.V 		if (pa->pa_deleted) {
41136be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
41146be2ded1SAneesh Kumar K.V 			continue;
41156be2ded1SAneesh Kumar K.V 		}
41166be2ded1SAneesh Kumar K.V 		/* only lg prealloc space */
4117cc0fb9adSAneesh Kumar K.V 		BUG_ON(pa->pa_type != MB_GROUP_PA);
41186be2ded1SAneesh Kumar K.V 
41196be2ded1SAneesh Kumar K.V 		/* seems this one can be freed ... */
41206be2ded1SAneesh Kumar K.V 		pa->pa_deleted = 1;
41216be2ded1SAneesh Kumar K.V 		spin_unlock(&pa->pa_lock);
41226be2ded1SAneesh Kumar K.V 
41236be2ded1SAneesh Kumar K.V 		list_del_rcu(&pa->pa_inode_list);
41246be2ded1SAneesh Kumar K.V 		list_add(&pa->u.pa_tmp_list, &discard_list);
41256be2ded1SAneesh Kumar K.V 
41266be2ded1SAneesh Kumar K.V 		total_entries--;
41276be2ded1SAneesh Kumar K.V 		if (total_entries <= 5) {
41286be2ded1SAneesh Kumar K.V 			/*
41296be2ded1SAneesh Kumar K.V 			 * we want to keep only 5 entries
41306be2ded1SAneesh Kumar K.V 			 * allowing it to grow to 8. This
41316be2ded1SAneesh Kumar K.V 			 * mak sure we don't call discard
41326be2ded1SAneesh Kumar K.V 			 * soon for this list.
41336be2ded1SAneesh Kumar K.V 			 */
41346be2ded1SAneesh Kumar K.V 			break;
41356be2ded1SAneesh Kumar K.V 		}
41366be2ded1SAneesh Kumar K.V 	}
41376be2ded1SAneesh Kumar K.V 	spin_unlock(&lg->lg_prealloc_lock);
41386be2ded1SAneesh Kumar K.V 
41396be2ded1SAneesh Kumar K.V 	list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
41406be2ded1SAneesh Kumar K.V 
41416be2ded1SAneesh Kumar K.V 		ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
41426be2ded1SAneesh Kumar K.V 		if (ext4_mb_load_buddy(sb, group, &e4b)) {
414312062dddSEric Sandeen 			ext4_error(sb, "Error loading buddy information for %u",
414412062dddSEric Sandeen 					group);
41456be2ded1SAneesh Kumar K.V 			continue;
41466be2ded1SAneesh Kumar K.V 		}
41476be2ded1SAneesh Kumar K.V 		ext4_lock_group(sb, group);
41486be2ded1SAneesh Kumar K.V 		list_del(&pa->pa_group_list);
41493e1e5f50SEric Sandeen 		ext4_mb_release_group_pa(&e4b, pa);
41506be2ded1SAneesh Kumar K.V 		ext4_unlock_group(sb, group);
41516be2ded1SAneesh Kumar K.V 
4152e39e07fdSJing Zhang 		ext4_mb_unload_buddy(&e4b);
41536be2ded1SAneesh Kumar K.V 		list_del(&pa->u.pa_tmp_list);
41546be2ded1SAneesh Kumar K.V 		call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
41556be2ded1SAneesh Kumar K.V 	}
41566be2ded1SAneesh Kumar K.V }
41576be2ded1SAneesh Kumar K.V 
41586be2ded1SAneesh Kumar K.V /*
41596be2ded1SAneesh Kumar K.V  * We have incremented pa_count. So it cannot be freed at this
41606be2ded1SAneesh Kumar K.V  * point. Also we hold lg_mutex. So no parallel allocation is
41616be2ded1SAneesh Kumar K.V  * possible from this lg. That means pa_free cannot be updated.
41626be2ded1SAneesh Kumar K.V  *
41636be2ded1SAneesh Kumar K.V  * A parallel ext4_mb_discard_group_preallocations is possible.
41646be2ded1SAneesh Kumar K.V  * which can cause the lg_prealloc_list to be updated.
41656be2ded1SAneesh Kumar K.V  */
41666be2ded1SAneesh Kumar K.V 
41676be2ded1SAneesh Kumar K.V static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
41686be2ded1SAneesh Kumar K.V {
41696be2ded1SAneesh Kumar K.V 	int order, added = 0, lg_prealloc_count = 1;
41706be2ded1SAneesh Kumar K.V 	struct super_block *sb = ac->ac_sb;
41716be2ded1SAneesh Kumar K.V 	struct ext4_locality_group *lg = ac->ac_lg;
41726be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
41736be2ded1SAneesh Kumar K.V 
41746be2ded1SAneesh Kumar K.V 	order = fls(pa->pa_free) - 1;
41756be2ded1SAneesh Kumar K.V 	if (order > PREALLOC_TB_SIZE - 1)
41766be2ded1SAneesh Kumar K.V 		/* The max size of hash table is PREALLOC_TB_SIZE */
41776be2ded1SAneesh Kumar K.V 		order = PREALLOC_TB_SIZE - 1;
41786be2ded1SAneesh Kumar K.V 	/* Add the prealloc space to lg */
41796be2ded1SAneesh Kumar K.V 	rcu_read_lock();
41806be2ded1SAneesh Kumar K.V 	list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
41816be2ded1SAneesh Kumar K.V 						pa_inode_list) {
41826be2ded1SAneesh Kumar K.V 		spin_lock(&tmp_pa->pa_lock);
41836be2ded1SAneesh Kumar K.V 		if (tmp_pa->pa_deleted) {
4184e7c9e3e9STheodore Ts'o 			spin_unlock(&tmp_pa->pa_lock);
41856be2ded1SAneesh Kumar K.V 			continue;
41866be2ded1SAneesh Kumar K.V 		}
41876be2ded1SAneesh Kumar K.V 		if (!added && pa->pa_free < tmp_pa->pa_free) {
41886be2ded1SAneesh Kumar K.V 			/* Add to the tail of the previous entry */
41896be2ded1SAneesh Kumar K.V 			list_add_tail_rcu(&pa->pa_inode_list,
41906be2ded1SAneesh Kumar K.V 						&tmp_pa->pa_inode_list);
41916be2ded1SAneesh Kumar K.V 			added = 1;
41926be2ded1SAneesh Kumar K.V 			/*
41936be2ded1SAneesh Kumar K.V 			 * we want to count the total
41946be2ded1SAneesh Kumar K.V 			 * number of entries in the list
41956be2ded1SAneesh Kumar K.V 			 */
41966be2ded1SAneesh Kumar K.V 		}
41976be2ded1SAneesh Kumar K.V 		spin_unlock(&tmp_pa->pa_lock);
41986be2ded1SAneesh Kumar K.V 		lg_prealloc_count++;
41996be2ded1SAneesh Kumar K.V 	}
42006be2ded1SAneesh Kumar K.V 	if (!added)
42016be2ded1SAneesh Kumar K.V 		list_add_tail_rcu(&pa->pa_inode_list,
42026be2ded1SAneesh Kumar K.V 					&lg->lg_prealloc_list[order]);
42036be2ded1SAneesh Kumar K.V 	rcu_read_unlock();
42046be2ded1SAneesh Kumar K.V 
42056be2ded1SAneesh Kumar K.V 	/* Now trim the list to be not more than 8 elements */
42066be2ded1SAneesh Kumar K.V 	if (lg_prealloc_count > 8) {
42076be2ded1SAneesh Kumar K.V 		ext4_mb_discard_lg_preallocations(sb, lg,
42086be2ded1SAneesh Kumar K.V 						order, lg_prealloc_count);
42096be2ded1SAneesh Kumar K.V 		return;
42106be2ded1SAneesh Kumar K.V 	}
42116be2ded1SAneesh Kumar K.V 	return ;
42126be2ded1SAneesh Kumar K.V }
42136be2ded1SAneesh Kumar K.V 
4214c9de560dSAlex Tomas /*
4215c9de560dSAlex Tomas  * release all resource we used in allocation
4216c9de560dSAlex Tomas  */
4217c9de560dSAlex Tomas static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4218c9de560dSAlex Tomas {
42196be2ded1SAneesh Kumar K.V 	struct ext4_prealloc_space *pa = ac->ac_pa;
42206be2ded1SAneesh Kumar K.V 	if (pa) {
4221cc0fb9adSAneesh Kumar K.V 		if (pa->pa_type == MB_GROUP_PA) {
4222c9de560dSAlex Tomas 			/* see comment in ext4_mb_use_group_pa() */
42236be2ded1SAneesh Kumar K.V 			spin_lock(&pa->pa_lock);
42246be2ded1SAneesh Kumar K.V 			pa->pa_pstart += ac->ac_b_ex.fe_len;
42256be2ded1SAneesh Kumar K.V 			pa->pa_lstart += ac->ac_b_ex.fe_len;
42266be2ded1SAneesh Kumar K.V 			pa->pa_free -= ac->ac_b_ex.fe_len;
42276be2ded1SAneesh Kumar K.V 			pa->pa_len -= ac->ac_b_ex.fe_len;
42286be2ded1SAneesh Kumar K.V 			spin_unlock(&pa->pa_lock);
4229ba443916SAneesh Kumar K.V 		}
4230ba443916SAneesh Kumar K.V 	}
4231ba443916SAneesh Kumar K.V 	if (ac->alloc_semp)
4232ba443916SAneesh Kumar K.V 		up_read(ac->alloc_semp);
4233ba443916SAneesh Kumar K.V 	if (pa) {
42346be2ded1SAneesh Kumar K.V 		/*
42356be2ded1SAneesh Kumar K.V 		 * We want to add the pa to the right bucket.
42366be2ded1SAneesh Kumar K.V 		 * Remove it from the list and while adding
42376be2ded1SAneesh Kumar K.V 		 * make sure the list to which we are adding
4238ba443916SAneesh Kumar K.V 		 * doesn't grow big.  We need to release
4239ba443916SAneesh Kumar K.V 		 * alloc_semp before calling ext4_mb_add_n_trim()
42406be2ded1SAneesh Kumar K.V 		 */
4241cc0fb9adSAneesh Kumar K.V 		if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
42426be2ded1SAneesh Kumar K.V 			spin_lock(pa->pa_obj_lock);
42436be2ded1SAneesh Kumar K.V 			list_del_rcu(&pa->pa_inode_list);
42446be2ded1SAneesh Kumar K.V 			spin_unlock(pa->pa_obj_lock);
42456be2ded1SAneesh Kumar K.V 			ext4_mb_add_n_trim(ac);
4246c9de560dSAlex Tomas 		}
42476be2ded1SAneesh Kumar K.V 		ext4_mb_put_pa(ac, ac->ac_sb, pa);
4248c9de560dSAlex Tomas 	}
4249c9de560dSAlex Tomas 	if (ac->ac_bitmap_page)
4250c9de560dSAlex Tomas 		page_cache_release(ac->ac_bitmap_page);
4251c9de560dSAlex Tomas 	if (ac->ac_buddy_page)
4252c9de560dSAlex Tomas 		page_cache_release(ac->ac_buddy_page);
4253c9de560dSAlex Tomas 	if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4254c9de560dSAlex Tomas 		mutex_unlock(&ac->ac_lg->lg_mutex);
4255c9de560dSAlex Tomas 	ext4_mb_collect_stats(ac);
4256c9de560dSAlex Tomas 	return 0;
4257c9de560dSAlex Tomas }
4258c9de560dSAlex Tomas 
4259c9de560dSAlex Tomas static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4260c9de560dSAlex Tomas {
42618df9675fSTheodore Ts'o 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4262c9de560dSAlex Tomas 	int ret;
4263c9de560dSAlex Tomas 	int freed = 0;
4264c9de560dSAlex Tomas 
42659bffad1eSTheodore Ts'o 	trace_ext4_mb_discard_preallocations(sb, needed);
42668df9675fSTheodore Ts'o 	for (i = 0; i < ngroups && needed > 0; i++) {
4267c9de560dSAlex Tomas 		ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4268c9de560dSAlex Tomas 		freed += ret;
4269c9de560dSAlex Tomas 		needed -= ret;
4270c9de560dSAlex Tomas 	}
4271c9de560dSAlex Tomas 
4272c9de560dSAlex Tomas 	return freed;
4273c9de560dSAlex Tomas }
4274c9de560dSAlex Tomas 
4275c9de560dSAlex Tomas /*
4276c9de560dSAlex Tomas  * Main entry point into mballoc to allocate blocks
4277c9de560dSAlex Tomas  * it tries to use preallocation first, then falls back
4278c9de560dSAlex Tomas  * to usual allocation
4279c9de560dSAlex Tomas  */
4280c9de560dSAlex Tomas ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4281c9de560dSAlex Tomas 				struct ext4_allocation_request *ar, int *errp)
4282c9de560dSAlex Tomas {
42836bc6e63fSAneesh Kumar K.V 	int freed;
4284256bdb49SEric Sandeen 	struct ext4_allocation_context *ac = NULL;
4285c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
4286c9de560dSAlex Tomas 	struct super_block *sb;
4287c9de560dSAlex Tomas 	ext4_fsblk_t block = 0;
428860e58e0fSMingming Cao 	unsigned int inquota = 0;
4289498e5f24STheodore Ts'o 	unsigned int reserv_blks = 0;
4290c9de560dSAlex Tomas 
4291c9de560dSAlex Tomas 	sb = ar->inode->i_sb;
4292c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
4293c9de560dSAlex Tomas 
42949bffad1eSTheodore Ts'o 	trace_ext4_request_blocks(ar);
4295ba80b101STheodore Ts'o 
4296d2a17637SMingming Cao 	/*
429760e58e0fSMingming Cao 	 * For delayed allocation, we could skip the ENOSPC and
429860e58e0fSMingming Cao 	 * EDQUOT check, as blocks and quotas have been already
429960e58e0fSMingming Cao 	 * reserved when data being copied into pagecache.
430060e58e0fSMingming Cao 	 */
4301f2321097STheodore Ts'o 	if (ext4_test_inode_state(ar->inode, EXT4_STATE_DELALLOC_RESERVED))
430260e58e0fSMingming Cao 		ar->flags |= EXT4_MB_DELALLOC_RESERVED;
430360e58e0fSMingming Cao 	else {
430460e58e0fSMingming Cao 		/* Without delayed allocation we need to verify
430560e58e0fSMingming Cao 		 * there is enough free blocks to do block allocation
430660e58e0fSMingming Cao 		 * and verify allocation doesn't exceed the quota limits.
4307d2a17637SMingming Cao 		 */
4308030ba6bcSAneesh Kumar K.V 		while (ar->len && ext4_claim_free_blocks(sbi, ar->len)) {
4309030ba6bcSAneesh Kumar K.V 			/* let others to free the space */
4310030ba6bcSAneesh Kumar K.V 			yield();
4311030ba6bcSAneesh Kumar K.V 			ar->len = ar->len >> 1;
4312030ba6bcSAneesh Kumar K.V 		}
4313030ba6bcSAneesh Kumar K.V 		if (!ar->len) {
431407031431SMingming Cao 			*errp = -ENOSPC;
431507031431SMingming Cao 			return 0;
431607031431SMingming Cao 		}
43176bc6e63fSAneesh Kumar K.V 		reserv_blks = ar->len;
43185dd4056dSChristoph Hellwig 		while (ar->len && dquot_alloc_block(ar->inode, ar->len)) {
4319c9de560dSAlex Tomas 			ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4320c9de560dSAlex Tomas 			ar->len--;
4321c9de560dSAlex Tomas 		}
432260e58e0fSMingming Cao 		inquota = ar->len;
4323c9de560dSAlex Tomas 		if (ar->len == 0) {
4324c9de560dSAlex Tomas 			*errp = -EDQUOT;
43256c7a120aSAditya Kali 			goto out;
4326c9de560dSAlex Tomas 		}
432760e58e0fSMingming Cao 	}
4328d2a17637SMingming Cao 
4329256bdb49SEric Sandeen 	ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4330833576b3STheodore Ts'o 	if (!ac) {
4331363d4251SShen Feng 		ar->len = 0;
4332256bdb49SEric Sandeen 		*errp = -ENOMEM;
43336c7a120aSAditya Kali 		goto out;
4334256bdb49SEric Sandeen 	}
4335256bdb49SEric Sandeen 
4336256bdb49SEric Sandeen 	*errp = ext4_mb_initialize_context(ac, ar);
4337c9de560dSAlex Tomas 	if (*errp) {
4338c9de560dSAlex Tomas 		ar->len = 0;
43396c7a120aSAditya Kali 		goto out;
4340c9de560dSAlex Tomas 	}
4341c9de560dSAlex Tomas 
4342256bdb49SEric Sandeen 	ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4343256bdb49SEric Sandeen 	if (!ext4_mb_use_preallocated(ac)) {
4344256bdb49SEric Sandeen 		ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4345256bdb49SEric Sandeen 		ext4_mb_normalize_request(ac, ar);
4346c9de560dSAlex Tomas repeat:
4347c9de560dSAlex Tomas 		/* allocate space in core */
43486c7a120aSAditya Kali 		*errp = ext4_mb_regular_allocator(ac);
43496c7a120aSAditya Kali 		if (*errp)
43506c7a120aSAditya Kali 			goto errout;
4351c9de560dSAlex Tomas 
4352c9de560dSAlex Tomas 		/* as we've just preallocated more space than
4353c9de560dSAlex Tomas 		 * user requested orinally, we store allocated
4354c9de560dSAlex Tomas 		 * space in a special descriptor */
4355256bdb49SEric Sandeen 		if (ac->ac_status == AC_STATUS_FOUND &&
4356256bdb49SEric Sandeen 				ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4357256bdb49SEric Sandeen 			ext4_mb_new_preallocation(ac);
4358c9de560dSAlex Tomas 	}
4359256bdb49SEric Sandeen 	if (likely(ac->ac_status == AC_STATUS_FOUND)) {
43606bc6e63fSAneesh Kumar K.V 		*errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_blks);
4361519deca0SAneesh Kumar K.V 		if (*errp == -EAGAIN) {
43628556e8f3SAneesh Kumar K.V 			/*
43638556e8f3SAneesh Kumar K.V 			 * drop the reference that we took
43648556e8f3SAneesh Kumar K.V 			 * in ext4_mb_use_best_found
43658556e8f3SAneesh Kumar K.V 			 */
43668556e8f3SAneesh Kumar K.V 			ext4_mb_release_context(ac);
4367519deca0SAneesh Kumar K.V 			ac->ac_b_ex.fe_group = 0;
4368519deca0SAneesh Kumar K.V 			ac->ac_b_ex.fe_start = 0;
4369519deca0SAneesh Kumar K.V 			ac->ac_b_ex.fe_len = 0;
4370519deca0SAneesh Kumar K.V 			ac->ac_status = AC_STATUS_CONTINUE;
4371519deca0SAneesh Kumar K.V 			goto repeat;
43726c7a120aSAditya Kali 		} else if (*errp)
43736c7a120aSAditya Kali 		errout:
4374b844167eSCurt Wohlgemuth 			ext4_discard_allocated_blocks(ac);
43756c7a120aSAditya Kali 		else {
4376256bdb49SEric Sandeen 			block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4377256bdb49SEric Sandeen 			ar->len = ac->ac_b_ex.fe_len;
4378519deca0SAneesh Kumar K.V 		}
4379c9de560dSAlex Tomas 	} else {
4380256bdb49SEric Sandeen 		freed  = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4381c9de560dSAlex Tomas 		if (freed)
4382c9de560dSAlex Tomas 			goto repeat;
4383c9de560dSAlex Tomas 		*errp = -ENOSPC;
43846c7a120aSAditya Kali 	}
43856c7a120aSAditya Kali 
43866c7a120aSAditya Kali 	if (*errp) {
4387256bdb49SEric Sandeen 		ac->ac_b_ex.fe_len = 0;
4388c9de560dSAlex Tomas 		ar->len = 0;
4389256bdb49SEric Sandeen 		ext4_mb_show_ac(ac);
4390c9de560dSAlex Tomas 	}
4391256bdb49SEric Sandeen 	ext4_mb_release_context(ac);
43926c7a120aSAditya Kali out:
43936c7a120aSAditya Kali 	if (ac)
4394363d4251SShen Feng 		kmem_cache_free(ext4_ac_cachep, ac);
439560e58e0fSMingming Cao 	if (inquota && ar->len < inquota)
43965dd4056dSChristoph Hellwig 		dquot_free_block(ar->inode, inquota - ar->len);
43970087d9fbSAneesh Kumar K.V 	if (!ar->len) {
4398f2321097STheodore Ts'o 		if (!ext4_test_inode_state(ar->inode,
4399f2321097STheodore Ts'o 					   EXT4_STATE_DELALLOC_RESERVED))
44000087d9fbSAneesh Kumar K.V 			/* release all the reserved blocks if non delalloc */
44010087d9fbSAneesh Kumar K.V 			percpu_counter_sub(&sbi->s_dirtyblocks_counter,
44020087d9fbSAneesh Kumar K.V 						reserv_blks);
44030087d9fbSAneesh Kumar K.V 	}
4404c9de560dSAlex Tomas 
44059bffad1eSTheodore Ts'o 	trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4406ba80b101STheodore Ts'o 
4407c9de560dSAlex Tomas 	return block;
4408c9de560dSAlex Tomas }
4409c9de560dSAlex Tomas 
4410c894058dSAneesh Kumar K.V /*
4411c894058dSAneesh Kumar K.V  * We can merge two free data extents only if the physical blocks
4412c894058dSAneesh Kumar K.V  * are contiguous, AND the extents were freed by the same transaction,
4413c894058dSAneesh Kumar K.V  * AND the blocks are associated with the same group.
4414c894058dSAneesh Kumar K.V  */
4415c894058dSAneesh Kumar K.V static int can_merge(struct ext4_free_data *entry1,
4416c894058dSAneesh Kumar K.V 			struct ext4_free_data *entry2)
4417c894058dSAneesh Kumar K.V {
4418c894058dSAneesh Kumar K.V 	if ((entry1->t_tid == entry2->t_tid) &&
4419c894058dSAneesh Kumar K.V 	    (entry1->group == entry2->group) &&
4420c894058dSAneesh Kumar K.V 	    ((entry1->start_blk + entry1->count) == entry2->start_blk))
4421c894058dSAneesh Kumar K.V 		return 1;
4422c894058dSAneesh Kumar K.V 	return 0;
4423c894058dSAneesh Kumar K.V }
4424c894058dSAneesh Kumar K.V 
44254ddfef7bSEric Sandeen static noinline_for_stack int
44264ddfef7bSEric Sandeen ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
44277a2fcbf7SAneesh Kumar K.V 		      struct ext4_free_data *new_entry)
4428c9de560dSAlex Tomas {
4429e29136f8STheodore Ts'o 	ext4_group_t group = e4b->bd_group;
44307a2fcbf7SAneesh Kumar K.V 	ext4_grpblk_t block;
44317a2fcbf7SAneesh Kumar K.V 	struct ext4_free_data *entry;
4432c9de560dSAlex Tomas 	struct ext4_group_info *db = e4b->bd_info;
4433c9de560dSAlex Tomas 	struct super_block *sb = e4b->bd_sb;
4434c9de560dSAlex Tomas 	struct ext4_sb_info *sbi = EXT4_SB(sb);
4435c894058dSAneesh Kumar K.V 	struct rb_node **n = &db->bb_free_root.rb_node, *node;
4436c894058dSAneesh Kumar K.V 	struct rb_node *parent = NULL, *new_node;
4437c894058dSAneesh Kumar K.V 
44380390131bSFrank Mayhar 	BUG_ON(!ext4_handle_valid(handle));
4439c9de560dSAlex Tomas 	BUG_ON(e4b->bd_bitmap_page == NULL);
4440c9de560dSAlex Tomas 	BUG_ON(e4b->bd_buddy_page == NULL);
4441c9de560dSAlex Tomas 
4442c894058dSAneesh Kumar K.V 	new_node = &new_entry->node;
44437a2fcbf7SAneesh Kumar K.V 	block = new_entry->start_blk;
4444c9de560dSAlex Tomas 
4445c894058dSAneesh Kumar K.V 	if (!*n) {
4446c894058dSAneesh Kumar K.V 		/* first free block exent. We need to
4447c894058dSAneesh Kumar K.V 		   protect buddy cache from being freed,
4448c9de560dSAlex Tomas 		 * otherwise we'll refresh it from
4449c9de560dSAlex Tomas 		 * on-disk bitmap and lose not-yet-available
4450c9de560dSAlex Tomas 		 * blocks */
4451c9de560dSAlex Tomas 		page_cache_get(e4b->bd_buddy_page);
4452c9de560dSAlex Tomas 		page_cache_get(e4b->bd_bitmap_page);
4453c894058dSAneesh Kumar K.V 	}
4454c894058dSAneesh Kumar K.V 	while (*n) {
4455c894058dSAneesh Kumar K.V 		parent = *n;
4456c894058dSAneesh Kumar K.V 		entry = rb_entry(parent, struct ext4_free_data, node);
4457c894058dSAneesh Kumar K.V 		if (block < entry->start_blk)
4458c894058dSAneesh Kumar K.V 			n = &(*n)->rb_left;
4459c894058dSAneesh Kumar K.V 		else if (block >= (entry->start_blk + entry->count))
4460c894058dSAneesh Kumar K.V 			n = &(*n)->rb_right;
4461c894058dSAneesh Kumar K.V 		else {
4462e29136f8STheodore Ts'o 			ext4_grp_locked_error(sb, group, 0,
4463e29136f8STheodore Ts'o 				ext4_group_first_block_no(sb, group) + block,
4464e29136f8STheodore Ts'o 				"Block already on to-be-freed list");
4465c894058dSAneesh Kumar K.V 			return 0;
4466c9de560dSAlex Tomas 		}
4467c9de560dSAlex Tomas 	}
4468c9de560dSAlex Tomas 
4469c894058dSAneesh Kumar K.V 	rb_link_node(new_node, parent, n);
4470c894058dSAneesh Kumar K.V 	rb_insert_color(new_node, &db->bb_free_root);
4471c894058dSAneesh Kumar K.V 
4472c894058dSAneesh Kumar K.V 	/* Now try to see the extent can be merged to left and right */
4473c894058dSAneesh Kumar K.V 	node = rb_prev(new_node);
4474c894058dSAneesh Kumar K.V 	if (node) {
4475c894058dSAneesh Kumar K.V 		entry = rb_entry(node, struct ext4_free_data, node);
4476c894058dSAneesh Kumar K.V 		if (can_merge(entry, new_entry)) {
4477c894058dSAneesh Kumar K.V 			new_entry->start_blk = entry->start_blk;
4478c894058dSAneesh Kumar K.V 			new_entry->count += entry->count;
4479c894058dSAneesh Kumar K.V 			rb_erase(node, &(db->bb_free_root));
4480c894058dSAneesh Kumar K.V 			spin_lock(&sbi->s_md_lock);
4481c894058dSAneesh Kumar K.V 			list_del(&entry->list);
4482c894058dSAneesh Kumar K.V 			spin_unlock(&sbi->s_md_lock);
4483c894058dSAneesh Kumar K.V 			kmem_cache_free(ext4_free_ext_cachep, entry);
4484c9de560dSAlex Tomas 		}
4485c9de560dSAlex Tomas 	}
4486c894058dSAneesh Kumar K.V 
4487c894058dSAneesh Kumar K.V 	node = rb_next(new_node);
4488c894058dSAneesh Kumar K.V 	if (node) {
4489c894058dSAneesh Kumar K.V 		entry = rb_entry(node, struct ext4_free_data, node);
4490c894058dSAneesh Kumar K.V 		if (can_merge(new_entry, entry)) {
4491c894058dSAneesh Kumar K.V 			new_entry->count += entry->count;
4492c894058dSAneesh Kumar K.V 			rb_erase(node, &(db->bb_free_root));
4493c894058dSAneesh Kumar K.V 			spin_lock(&sbi->s_md_lock);
4494c894058dSAneesh Kumar K.V 			list_del(&entry->list);
4495c894058dSAneesh Kumar K.V 			spin_unlock(&sbi->s_md_lock);
4496c894058dSAneesh Kumar K.V 			kmem_cache_free(ext4_free_ext_cachep, entry);
4497c894058dSAneesh Kumar K.V 		}
4498c894058dSAneesh Kumar K.V 	}
44993e624fc7STheodore Ts'o 	/* Add the extent to transaction's private list */
4500c894058dSAneesh Kumar K.V 	spin_lock(&sbi->s_md_lock);
45013e624fc7STheodore Ts'o 	list_add(&new_entry->list, &handle->h_transaction->t_private_list);
4502c894058dSAneesh Kumar K.V 	spin_unlock(&sbi->s_md_lock);
4503c9de560dSAlex Tomas 	return 0;
4504c9de560dSAlex Tomas }
4505c9de560dSAlex Tomas 
450644338711STheodore Ts'o /**
450744338711STheodore Ts'o  * ext4_free_blocks() -- Free given blocks and update quota
450844338711STheodore Ts'o  * @handle:		handle for this transaction
450944338711STheodore Ts'o  * @inode:		inode
451044338711STheodore Ts'o  * @block:		start physical block to free
451144338711STheodore Ts'o  * @count:		number of blocks to count
451244338711STheodore Ts'o  * @metadata: 		Are these metadata blocks
4513c9de560dSAlex Tomas  */
451444338711STheodore Ts'o void ext4_free_blocks(handle_t *handle, struct inode *inode,
4515e6362609STheodore Ts'o 		      struct buffer_head *bh, ext4_fsblk_t block,
4516e6362609STheodore Ts'o 		      unsigned long count, int flags)
4517c9de560dSAlex Tomas {
451826346ff6SAneesh Kumar K.V 	struct buffer_head *bitmap_bh = NULL;
4519c9de560dSAlex Tomas 	struct super_block *sb = inode->i_sb;
4520c9de560dSAlex Tomas 	struct ext4_group_desc *gdp;
452144338711STheodore Ts'o 	unsigned long freed = 0;
4522498e5f24STheodore Ts'o 	unsigned int overflow;
4523c9de560dSAlex Tomas 	ext4_grpblk_t bit;
4524c9de560dSAlex Tomas 	struct buffer_head *gd_bh;
4525c9de560dSAlex Tomas 	ext4_group_t block_group;
4526c9de560dSAlex Tomas 	struct ext4_sb_info *sbi;
4527c9de560dSAlex Tomas 	struct ext4_buddy e4b;
4528c9de560dSAlex Tomas 	int err = 0;
4529c9de560dSAlex Tomas 	int ret;
4530c9de560dSAlex Tomas 
4531e6362609STheodore Ts'o 	if (bh) {
4532e6362609STheodore Ts'o 		if (block)
4533e6362609STheodore Ts'o 			BUG_ON(block != bh->b_blocknr);
4534e6362609STheodore Ts'o 		else
4535e6362609STheodore Ts'o 			block = bh->b_blocknr;
4536e6362609STheodore Ts'o 	}
4537c9de560dSAlex Tomas 
4538c9de560dSAlex Tomas 	sbi = EXT4_SB(sb);
45391f2acb60STheodore Ts'o 	if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
45401f2acb60STheodore Ts'o 	    !ext4_data_block_valid(sbi, block, count)) {
454112062dddSEric Sandeen 		ext4_error(sb, "Freeing blocks not in datazone - "
45420610b6e9STheodore Ts'o 			   "block = %llu, count = %lu", block, count);
4543c9de560dSAlex Tomas 		goto error_return;
4544c9de560dSAlex Tomas 	}
4545c9de560dSAlex Tomas 
45460610b6e9STheodore Ts'o 	ext4_debug("freeing block %llu\n", block);
4547e6362609STheodore Ts'o 	trace_ext4_free_blocks(inode, block, count, flags);
4548e6362609STheodore Ts'o 
4549e6362609STheodore Ts'o 	if (flags & EXT4_FREE_BLOCKS_FORGET) {
4550e6362609STheodore Ts'o 		struct buffer_head *tbh = bh;
4551e6362609STheodore Ts'o 		int i;
4552e6362609STheodore Ts'o 
4553e6362609STheodore Ts'o 		BUG_ON(bh && (count > 1));
4554e6362609STheodore Ts'o 
4555e6362609STheodore Ts'o 		for (i = 0; i < count; i++) {
4556e6362609STheodore Ts'o 			if (!bh)
4557e6362609STheodore Ts'o 				tbh = sb_find_get_block(inode->i_sb,
4558e6362609STheodore Ts'o 							block + i);
455987783690SNamhyung Kim 			if (unlikely(!tbh))
456087783690SNamhyung Kim 				continue;
4561e6362609STheodore Ts'o 			ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4562e6362609STheodore Ts'o 				    inode, tbh, block + i);
4563e6362609STheodore Ts'o 		}
4564e6362609STheodore Ts'o 	}
4565e6362609STheodore Ts'o 
4566e6362609STheodore Ts'o 	/*
4567e6362609STheodore Ts'o 	 * We need to make sure we don't reuse the freed block until
4568e6362609STheodore Ts'o 	 * after the transaction is committed, which we can do by
4569e6362609STheodore Ts'o 	 * treating the block as metadata, below.  We make an
4570e6362609STheodore Ts'o 	 * exception if the inode is to be written in writeback mode
4571e6362609STheodore Ts'o 	 * since writeback mode has weak data consistency guarantees.
4572e6362609STheodore Ts'o 	 */
4573e6362609STheodore Ts'o 	if (!ext4_should_writeback_data(inode))
4574e6362609STheodore Ts'o 		flags |= EXT4_FREE_BLOCKS_METADATA;
4575c9de560dSAlex Tomas 
4576c9de560dSAlex Tomas do_more:
4577c9de560dSAlex Tomas 	overflow = 0;
4578c9de560dSAlex Tomas 	ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4579c9de560dSAlex Tomas 
4580c9de560dSAlex Tomas 	/*
4581c9de560dSAlex Tomas 	 * Check to see if we are freeing blocks across a group
4582c9de560dSAlex Tomas 	 * boundary.
4583c9de560dSAlex Tomas 	 */
4584c9de560dSAlex Tomas 	if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4585c9de560dSAlex Tomas 		overflow = bit + count - EXT4_BLOCKS_PER_GROUP(sb);
4586c9de560dSAlex Tomas 		count -= overflow;
4587c9de560dSAlex Tomas 	}
4588574ca174STheodore Ts'o 	bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4589ce89f46cSAneesh Kumar K.V 	if (!bitmap_bh) {
4590ce89f46cSAneesh Kumar K.V 		err = -EIO;
4591c9de560dSAlex Tomas 		goto error_return;
4592ce89f46cSAneesh Kumar K.V 	}
4593c9de560dSAlex Tomas 	gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4594ce89f46cSAneesh Kumar K.V 	if (!gdp) {
4595ce89f46cSAneesh Kumar K.V 		err = -EIO;
4596c9de560dSAlex Tomas 		goto error_return;
4597ce89f46cSAneesh Kumar K.V 	}
4598c9de560dSAlex Tomas 
4599c9de560dSAlex Tomas 	if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4600c9de560dSAlex Tomas 	    in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4601c9de560dSAlex Tomas 	    in_range(block, ext4_inode_table(sb, gdp),
4602c9de560dSAlex Tomas 		      EXT4_SB(sb)->s_itb_per_group) ||
4603c9de560dSAlex Tomas 	    in_range(block + count - 1, ext4_inode_table(sb, gdp),
4604c9de560dSAlex Tomas 		      EXT4_SB(sb)->s_itb_per_group)) {
4605c9de560dSAlex Tomas 
460612062dddSEric Sandeen 		ext4_error(sb, "Freeing blocks in system zone - "
46070610b6e9STheodore Ts'o 			   "Block = %llu, count = %lu", block, count);
4608519deca0SAneesh Kumar K.V 		/* err = 0. ext4_std_error should be a no op */
4609519deca0SAneesh Kumar K.V 		goto error_return;
4610c9de560dSAlex Tomas 	}
4611c9de560dSAlex Tomas 
4612c9de560dSAlex Tomas 	BUFFER_TRACE(bitmap_bh, "getting write access");
4613c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, bitmap_bh);
4614c9de560dSAlex Tomas 	if (err)
4615c9de560dSAlex Tomas 		goto error_return;
4616c9de560dSAlex Tomas 
4617c9de560dSAlex Tomas 	/*
4618c9de560dSAlex Tomas 	 * We are about to modify some metadata.  Call the journal APIs
4619c9de560dSAlex Tomas 	 * to unshare ->b_data if a currently-committing transaction is
4620c9de560dSAlex Tomas 	 * using it
4621c9de560dSAlex Tomas 	 */
4622c9de560dSAlex Tomas 	BUFFER_TRACE(gd_bh, "get_write_access");
4623c9de560dSAlex Tomas 	err = ext4_journal_get_write_access(handle, gd_bh);
4624c9de560dSAlex Tomas 	if (err)
4625c9de560dSAlex Tomas 		goto error_return;
4626c9de560dSAlex Tomas #ifdef AGGRESSIVE_CHECK
4627c9de560dSAlex Tomas 	{
4628c9de560dSAlex Tomas 		int i;
4629c9de560dSAlex Tomas 		for (i = 0; i < count; i++)
4630c9de560dSAlex Tomas 			BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4631c9de560dSAlex Tomas 	}
4632c9de560dSAlex Tomas #endif
46333e1e5f50SEric Sandeen 	trace_ext4_mballoc_free(sb, inode, block_group, bit, count);
4634c9de560dSAlex Tomas 
4635920313a7SAneesh Kumar K.V 	err = ext4_mb_load_buddy(sb, block_group, &e4b);
4636920313a7SAneesh Kumar K.V 	if (err)
4637920313a7SAneesh Kumar K.V 		goto error_return;
4638e6362609STheodore Ts'o 
4639e6362609STheodore Ts'o 	if ((flags & EXT4_FREE_BLOCKS_METADATA) && ext4_handle_valid(handle)) {
46407a2fcbf7SAneesh Kumar K.V 		struct ext4_free_data *new_entry;
46417a2fcbf7SAneesh Kumar K.V 		/*
46427a2fcbf7SAneesh Kumar K.V 		 * blocks being freed are metadata. these blocks shouldn't
46437a2fcbf7SAneesh Kumar K.V 		 * be used until this transaction is committed
46447a2fcbf7SAneesh Kumar K.V 		 */
46457a2fcbf7SAneesh Kumar K.V 		new_entry = kmem_cache_alloc(ext4_free_ext_cachep, GFP_NOFS);
4646b72143abSTheodore Ts'o 		if (!new_entry) {
4647b72143abSTheodore Ts'o 			err = -ENOMEM;
4648b72143abSTheodore Ts'o 			goto error_return;
4649b72143abSTheodore Ts'o 		}
46507a2fcbf7SAneesh Kumar K.V 		new_entry->start_blk = bit;
46517a2fcbf7SAneesh Kumar K.V 		new_entry->group  = block_group;
46527a2fcbf7SAneesh Kumar K.V 		new_entry->count = count;
46537a2fcbf7SAneesh Kumar K.V 		new_entry->t_tid = handle->h_transaction->t_tid;
4654955ce5f5SAneesh Kumar K.V 
46557a2fcbf7SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
4656955ce5f5SAneesh Kumar K.V 		mb_clear_bits(bitmap_bh->b_data, bit, count);
46577a2fcbf7SAneesh Kumar K.V 		ext4_mb_free_metadata(handle, &e4b, new_entry);
4658c9de560dSAlex Tomas 	} else {
46597a2fcbf7SAneesh Kumar K.V 		/* need to update group_info->bb_free and bitmap
46607a2fcbf7SAneesh Kumar K.V 		 * with group lock held. generate_buddy look at
46617a2fcbf7SAneesh Kumar K.V 		 * them with group lock_held
46627a2fcbf7SAneesh Kumar K.V 		 */
4663955ce5f5SAneesh Kumar K.V 		ext4_lock_group(sb, block_group);
4664955ce5f5SAneesh Kumar K.V 		mb_clear_bits(bitmap_bh->b_data, bit, count);
46657e5a8cddSShen Feng 		mb_free_blocks(inode, &e4b, bit, count);
4666c9de560dSAlex Tomas 	}
4667c9de560dSAlex Tomas 
4668560671a0SAneesh Kumar K.V 	ret = ext4_free_blks_count(sb, gdp) + count;
4669560671a0SAneesh Kumar K.V 	ext4_free_blks_set(sb, gdp, ret);
4670c9de560dSAlex Tomas 	gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4671955ce5f5SAneesh Kumar K.V 	ext4_unlock_group(sb, block_group);
4672c9de560dSAlex Tomas 	percpu_counter_add(&sbi->s_freeblocks_counter, count);
4673c9de560dSAlex Tomas 
4674772cb7c8SJose R. Santos 	if (sbi->s_log_groups_per_flex) {
4675772cb7c8SJose R. Santos 		ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
46769f24e420STheodore Ts'o 		atomic_add(count, &sbi->s_flex_groups[flex_group].free_blocks);
4677772cb7c8SJose R. Santos 	}
4678772cb7c8SJose R. Santos 
4679e39e07fdSJing Zhang 	ext4_mb_unload_buddy(&e4b);
4680c9de560dSAlex Tomas 
468144338711STheodore Ts'o 	freed += count;
4682c9de560dSAlex Tomas 
46837a2fcbf7SAneesh Kumar K.V 	/* We dirtied the bitmap block */
46847a2fcbf7SAneesh Kumar K.V 	BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
46857a2fcbf7SAneesh Kumar K.V 	err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
46867a2fcbf7SAneesh Kumar K.V 
4687c9de560dSAlex Tomas 	/* And the group descriptor block */
4688c9de560dSAlex Tomas 	BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
46890390131bSFrank Mayhar 	ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4690c9de560dSAlex Tomas 	if (!err)
4691c9de560dSAlex Tomas 		err = ret;
4692c9de560dSAlex Tomas 
4693c9de560dSAlex Tomas 	if (overflow && !err) {
4694c9de560dSAlex Tomas 		block += count;
4695c9de560dSAlex Tomas 		count = overflow;
4696c9de560dSAlex Tomas 		put_bh(bitmap_bh);
4697c9de560dSAlex Tomas 		goto do_more;
4698c9de560dSAlex Tomas 	}
4699a0375156STheodore Ts'o 	ext4_mark_super_dirty(sb);
4700c9de560dSAlex Tomas error_return:
470144338711STheodore Ts'o 	if (freed)
47025dd4056dSChristoph Hellwig 		dquot_free_block(inode, freed);
4703c9de560dSAlex Tomas 	brelse(bitmap_bh);
4704c9de560dSAlex Tomas 	ext4_std_error(sb, err);
4705c9de560dSAlex Tomas 	return;
4706c9de560dSAlex Tomas }
47077360d173SLukas Czerner 
47087360d173SLukas Czerner /**
47097360d173SLukas Czerner  * ext4_trim_extent -- function to TRIM one single free extent in the group
47107360d173SLukas Czerner  * @sb:		super block for the file system
47117360d173SLukas Czerner  * @start:	starting block of the free extent in the alloc. group
47127360d173SLukas Czerner  * @count:	number of blocks to TRIM
47137360d173SLukas Czerner  * @group:	alloc. group we are working with
47147360d173SLukas Czerner  * @e4b:	ext4 buddy for the group
47157360d173SLukas Czerner  *
47167360d173SLukas Czerner  * Trim "count" blocks starting at "start" in the "group". To assure that no
47177360d173SLukas Czerner  * one will allocate those blocks, mark it as used in buddy bitmap. This must
47187360d173SLukas Czerner  * be called with under the group lock.
47197360d173SLukas Czerner  */
47207360d173SLukas Czerner static int ext4_trim_extent(struct super_block *sb, int start, int count,
47217360d173SLukas Czerner 		ext4_group_t group, struct ext4_buddy *e4b)
47227360d173SLukas Czerner {
47237360d173SLukas Czerner 	struct ext4_free_extent ex;
47247360d173SLukas Czerner 	int ret = 0;
47257360d173SLukas Czerner 
47267360d173SLukas Czerner 	assert_spin_locked(ext4_group_lock_ptr(sb, group));
47277360d173SLukas Czerner 
47287360d173SLukas Czerner 	ex.fe_start = start;
47297360d173SLukas Czerner 	ex.fe_group = group;
47307360d173SLukas Czerner 	ex.fe_len = count;
47317360d173SLukas Czerner 
47327360d173SLukas Czerner 	/*
47337360d173SLukas Czerner 	 * Mark blocks used, so no one can reuse them while
47347360d173SLukas Czerner 	 * being trimmed.
47357360d173SLukas Czerner 	 */
47367360d173SLukas Czerner 	mb_mark_used(e4b, &ex);
47377360d173SLukas Czerner 	ext4_unlock_group(sb, group);
47387360d173SLukas Czerner 
47397360d173SLukas Czerner 	ret = ext4_issue_discard(sb, group, start, count);
47407360d173SLukas Czerner 
47417360d173SLukas Czerner 	ext4_lock_group(sb, group);
47427360d173SLukas Czerner 	mb_free_blocks(NULL, e4b, start, ex.fe_len);
47437360d173SLukas Czerner 	return ret;
47447360d173SLukas Czerner }
47457360d173SLukas Czerner 
47467360d173SLukas Czerner /**
47477360d173SLukas Czerner  * ext4_trim_all_free -- function to trim all free space in alloc. group
47487360d173SLukas Czerner  * @sb:			super block for file system
47497360d173SLukas Czerner  * @e4b:		ext4 buddy
47507360d173SLukas Czerner  * @start:		first group block to examine
47517360d173SLukas Czerner  * @max:		last group block to examine
47527360d173SLukas Czerner  * @minblocks:		minimum extent block count
47537360d173SLukas Czerner  *
47547360d173SLukas Czerner  * ext4_trim_all_free walks through group's buddy bitmap searching for free
47557360d173SLukas Czerner  * extents. When the free block is found, ext4_trim_extent is called to TRIM
47567360d173SLukas Czerner  * the extent.
47577360d173SLukas Czerner  *
47587360d173SLukas Czerner  *
47597360d173SLukas Czerner  * ext4_trim_all_free walks through group's block bitmap searching for free
47607360d173SLukas Czerner  * extents. When the free extent is found, mark it as used in group buddy
47617360d173SLukas Czerner  * bitmap. Then issue a TRIM command on this extent and free the extent in
47627360d173SLukas Czerner  * the group buddy bitmap. This is done until whole group is scanned.
47637360d173SLukas Czerner  */
47640b75a840SLukas Czerner static ext4_grpblk_t
47650b75a840SLukas Czerner ext4_trim_all_free(struct super_block *sb, struct ext4_buddy *e4b,
47667360d173SLukas Czerner 		ext4_grpblk_t start, ext4_grpblk_t max, ext4_grpblk_t minblocks)
47677360d173SLukas Czerner {
47687360d173SLukas Czerner 	void *bitmap;
47697360d173SLukas Czerner 	ext4_grpblk_t next, count = 0;
47707360d173SLukas Czerner 	ext4_group_t group;
47717360d173SLukas Czerner 	int ret = 0;
47727360d173SLukas Czerner 
47737360d173SLukas Czerner 	BUG_ON(e4b == NULL);
47747360d173SLukas Czerner 
47757360d173SLukas Czerner 	bitmap = e4b->bd_bitmap;
47767360d173SLukas Czerner 	group = e4b->bd_group;
47777360d173SLukas Czerner 	start = (e4b->bd_info->bb_first_free > start) ?
47787360d173SLukas Czerner 		e4b->bd_info->bb_first_free : start;
47797360d173SLukas Czerner 	ext4_lock_group(sb, group);
47807360d173SLukas Czerner 
47817360d173SLukas Czerner 	while (start < max) {
47827360d173SLukas Czerner 		start = mb_find_next_zero_bit(bitmap, max, start);
47837360d173SLukas Czerner 		if (start >= max)
47847360d173SLukas Czerner 			break;
47857360d173SLukas Czerner 		next = mb_find_next_bit(bitmap, max, start);
47867360d173SLukas Czerner 
47877360d173SLukas Czerner 		if ((next - start) >= minblocks) {
47887360d173SLukas Czerner 			ret = ext4_trim_extent(sb, start,
47897360d173SLukas Czerner 				next - start, group, e4b);
47907360d173SLukas Czerner 			if (ret < 0)
47917360d173SLukas Czerner 				break;
47927360d173SLukas Czerner 			count += next - start;
47937360d173SLukas Czerner 		}
47947360d173SLukas Czerner 		start = next + 1;
47957360d173SLukas Czerner 
47967360d173SLukas Czerner 		if (fatal_signal_pending(current)) {
47977360d173SLukas Czerner 			count = -ERESTARTSYS;
47987360d173SLukas Czerner 			break;
47997360d173SLukas Czerner 		}
48007360d173SLukas Czerner 
48017360d173SLukas Czerner 		if (need_resched()) {
48027360d173SLukas Czerner 			ext4_unlock_group(sb, group);
48037360d173SLukas Czerner 			cond_resched();
48047360d173SLukas Czerner 			ext4_lock_group(sb, group);
48057360d173SLukas Czerner 		}
48067360d173SLukas Czerner 
48077360d173SLukas Czerner 		if ((e4b->bd_info->bb_free - count) < minblocks)
48087360d173SLukas Czerner 			break;
48097360d173SLukas Czerner 	}
48107360d173SLukas Czerner 	ext4_unlock_group(sb, group);
48117360d173SLukas Czerner 
48127360d173SLukas Czerner 	ext4_debug("trimmed %d blocks in the group %d\n",
48137360d173SLukas Czerner 		count, group);
48147360d173SLukas Czerner 
48157360d173SLukas Czerner 	if (ret < 0)
48167360d173SLukas Czerner 		count = ret;
48177360d173SLukas Czerner 
48187360d173SLukas Czerner 	return count;
48197360d173SLukas Czerner }
48207360d173SLukas Czerner 
48217360d173SLukas Czerner /**
48227360d173SLukas Czerner  * ext4_trim_fs() -- trim ioctl handle function
48237360d173SLukas Czerner  * @sb:			superblock for filesystem
48247360d173SLukas Czerner  * @range:		fstrim_range structure
48257360d173SLukas Czerner  *
48267360d173SLukas Czerner  * start:	First Byte to trim
48277360d173SLukas Czerner  * len:		number of Bytes to trim from start
48287360d173SLukas Czerner  * minlen:	minimum extent length in Bytes
48297360d173SLukas Czerner  * ext4_trim_fs goes through all allocation groups containing Bytes from
48307360d173SLukas Czerner  * start to start+len. For each such a group ext4_trim_all_free function
48317360d173SLukas Czerner  * is invoked to trim all free space.
48327360d173SLukas Czerner  */
48337360d173SLukas Czerner int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
48347360d173SLukas Czerner {
48357360d173SLukas Czerner 	struct ext4_buddy e4b;
48367360d173SLukas Czerner 	ext4_group_t first_group, last_group;
48377360d173SLukas Czerner 	ext4_group_t group, ngroups = ext4_get_groups_count(sb);
48387360d173SLukas Czerner 	ext4_grpblk_t cnt = 0, first_block, last_block;
48397360d173SLukas Czerner 	uint64_t start, len, minlen, trimmed;
48400f0a25bfSJan Kara 	ext4_fsblk_t first_data_blk =
48410f0a25bfSJan Kara 			le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
48427360d173SLukas Czerner 	int ret = 0;
48437360d173SLukas Czerner 
48447360d173SLukas Czerner 	start = range->start >> sb->s_blocksize_bits;
48457360d173SLukas Czerner 	len = range->len >> sb->s_blocksize_bits;
48467360d173SLukas Czerner 	minlen = range->minlen >> sb->s_blocksize_bits;
48477360d173SLukas Czerner 	trimmed = 0;
48487360d173SLukas Czerner 
48497360d173SLukas Czerner 	if (unlikely(minlen > EXT4_BLOCKS_PER_GROUP(sb)))
48507360d173SLukas Czerner 		return -EINVAL;
48510f0a25bfSJan Kara 	if (start < first_data_blk) {
48520f0a25bfSJan Kara 		len -= first_data_blk - start;
48530f0a25bfSJan Kara 		start = first_data_blk;
48540f0a25bfSJan Kara 	}
48557360d173SLukas Czerner 
48567360d173SLukas Czerner 	/* Determine first and last group to examine based on start and len */
48577360d173SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
48587360d173SLukas Czerner 				     &first_group, &first_block);
48597360d173SLukas Czerner 	ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) (start + len),
48607360d173SLukas Czerner 				     &last_group, &last_block);
48617360d173SLukas Czerner 	last_group = (last_group > ngroups - 1) ? ngroups - 1 : last_group;
48627360d173SLukas Czerner 	last_block = EXT4_BLOCKS_PER_GROUP(sb);
48637360d173SLukas Czerner 
48647360d173SLukas Czerner 	if (first_group > last_group)
48657360d173SLukas Czerner 		return -EINVAL;
48667360d173SLukas Czerner 
48677360d173SLukas Czerner 	for (group = first_group; group <= last_group; group++) {
48687360d173SLukas Czerner 		ret = ext4_mb_load_buddy(sb, group, &e4b);
48697360d173SLukas Czerner 		if (ret) {
48707360d173SLukas Czerner 			ext4_error(sb, "Error in loading buddy "
48717360d173SLukas Czerner 					"information for %u", group);
48727360d173SLukas Czerner 			break;
48737360d173SLukas Czerner 		}
48747360d173SLukas Czerner 
48750ba08517STao Ma 		/*
48760ba08517STao Ma 		 * For all the groups except the last one, last block will
48770ba08517STao Ma 		 * always be EXT4_BLOCKS_PER_GROUP(sb), so we only need to
48780ba08517STao Ma 		 * change it for the last group in which case start +
48790ba08517STao Ma 		 * len < EXT4_BLOCKS_PER_GROUP(sb).
48800ba08517STao Ma 		 */
48810ba08517STao Ma 		if (first_block + len < EXT4_BLOCKS_PER_GROUP(sb))
4882ca6e909fSJan Kara 			last_block = first_block + len;
48830ba08517STao Ma 		len -= last_block - first_block;
48847360d173SLukas Czerner 
48857360d173SLukas Czerner 		if (e4b.bd_info->bb_free >= minlen) {
48867360d173SLukas Czerner 			cnt = ext4_trim_all_free(sb, &e4b, first_block,
48877360d173SLukas Czerner 						last_block, minlen);
48887360d173SLukas Czerner 			if (cnt < 0) {
48897360d173SLukas Czerner 				ret = cnt;
48907360d173SLukas Czerner 				ext4_mb_unload_buddy(&e4b);
48917360d173SLukas Czerner 				break;
48927360d173SLukas Czerner 			}
48937360d173SLukas Czerner 		}
48947360d173SLukas Czerner 		ext4_mb_unload_buddy(&e4b);
48957360d173SLukas Czerner 		trimmed += cnt;
48967360d173SLukas Czerner 		first_block = 0;
48977360d173SLukas Czerner 	}
48987360d173SLukas Czerner 	range->len = trimmed * sb->s_blocksize;
48997360d173SLukas Czerner 
49007360d173SLukas Czerner 	return ret;
49017360d173SLukas Czerner }
4902