]> git.ipfire.org Git - people/ms/linux.git/blame - fs/ext4/mballoc.c
ext4: use locality group preallocation for small closed files
[people/ms/linux.git] / fs / ext4 / mballoc.c
CommitLineData
f5166768 1// SPDX-License-Identifier: GPL-2.0
c9de560d
AT
2/*
3 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
4 * Written by Alex Tomas <alex@clusterfs.com>
c9de560d
AT
5 */
6
7
8/*
9 * mballoc.c contains the multiblocks allocation routines
10 */
11
18aadd47 12#include "ext4_jbd2.h"
8f6e39a7 13#include "mballoc.h"
28623c2f 14#include <linux/log2.h>
a0b30c12 15#include <linux/module.h>
5a0e3ad6 16#include <linux/slab.h>
1a5d5e5d 17#include <linux/nospec.h>
66114cad 18#include <linux/backing-dev.h>
9bffad1e
TT
19#include <trace/events/ext4.h>
20
c9de560d
AT
21/*
22 * MUSTDO:
23 * - test ext4_ext_search_left() and ext4_ext_search_right()
24 * - search for metadata in few groups
25 *
26 * TODO v4:
27 * - normalization should take into account whether file is still open
28 * - discard preallocations if no free space left (policy?)
29 * - don't normalize tails
30 * - quota
31 * - reservation for superuser
32 *
33 * TODO v3:
34 * - bitmap read-ahead (proposed by Oleg Drokin aka green)
35 * - track min/max extents in each group for better group selection
36 * - mb_mark_used() may allocate chunk right after splitting buddy
37 * - tree of groups sorted by number of free blocks
38 * - error handling
39 */
40
41/*
42 * The allocation request involve request for multiple number of blocks
43 * near to the goal(block) value specified.
44 *
b713a5ec
TT
45 * During initialization phase of the allocator we decide to use the
46 * group preallocation or inode preallocation depending on the size of
47 * the file. The size of the file could be the resulting file size we
48 * would have after allocation, or the current file size, which ever
49 * is larger. If the size is less than sbi->s_mb_stream_request we
50 * select to use the group preallocation. The default value of
51 * s_mb_stream_request is 16 blocks. This can also be tuned via
52 * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
53 * terms of number of blocks.
c9de560d
AT
54 *
55 * The main motivation for having small file use group preallocation is to
b713a5ec 56 * ensure that we have small files closer together on the disk.
c9de560d 57 *
b713a5ec
TT
58 * First stage the allocator looks at the inode prealloc list,
59 * ext4_inode_info->i_prealloc_list, which contains list of prealloc
60 * spaces for this particular inode. The inode prealloc space is
61 * represented as:
c9de560d
AT
62 *
63 * pa_lstart -> the logical start block for this prealloc space
64 * pa_pstart -> the physical start block for this prealloc space
53accfa9
TT
65 * pa_len -> length for this prealloc space (in clusters)
66 * pa_free -> free space available in this prealloc space (in clusters)
c9de560d
AT
67 *
68 * The inode preallocation space is used looking at the _logical_ start
69 * block. If only the logical file block falls within the range of prealloc
caaf7a29
TM
70 * space we will consume the particular prealloc space. This makes sure that
71 * we have contiguous physical blocks representing the file blocks
c9de560d
AT
72 *
73 * The important thing to be noted in case of inode prealloc space is that
74 * we don't modify the values associated to inode prealloc space except
75 * pa_free.
76 *
77 * If we are not able to find blocks in the inode prealloc space and if we
78 * have the group allocation flag set then we look at the locality group
caaf7a29 79 * prealloc space. These are per CPU prealloc list represented as
c9de560d
AT
80 *
81 * ext4_sb_info.s_locality_groups[smp_processor_id()]
82 *
83 * The reason for having a per cpu locality group is to reduce the contention
84 * between CPUs. It is possible to get scheduled at this point.
85 *
86 * The locality group prealloc space is used looking at whether we have
25985edc 87 * enough free space (pa_free) within the prealloc space.
c9de560d
AT
88 *
89 * If we can't allocate blocks via inode prealloc or/and locality group
90 * prealloc then we look at the buddy cache. The buddy cache is represented
91 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
92 * mapped to the buddy and bitmap information regarding different
93 * groups. The buddy information is attached to buddy cache inode so that
94 * we can access them through the page cache. The information regarding
95 * each group is loaded via ext4_mb_load_buddy. The information involve
96 * block bitmap and buddy information. The information are stored in the
97 * inode as:
98 *
99 * { page }
c3a326a6 100 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
c9de560d
AT
101 *
102 *
103 * one block each for bitmap and buddy information. So for each group we
ea1754a0 104 * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
c9de560d
AT
105 * blocksize) blocks. So it can have information regarding groups_per_page
106 * which is blocks_per_page/2
107 *
108 * The buddy cache inode is not stored on disk. The inode is thrown
109 * away when the filesystem is unmounted.
110 *
111 * We look for count number of blocks in the buddy cache. If we were able
112 * to locate that many free blocks we return with additional information
113 * regarding rest of the contiguous physical block available
114 *
115 * Before allocating blocks via buddy cache we normalize the request
116 * blocks. This ensure we ask for more blocks that we needed. The extra
117 * blocks that we get after allocation is added to the respective prealloc
118 * list. In case of inode preallocation we follow a list of heuristics
119 * based on file size. This can be found in ext4_mb_normalize_request. If
120 * we are doing a group prealloc we try to normalize the request to
27baebb8
TT
121 * sbi->s_mb_group_prealloc. The default value of s_mb_group_prealloc is
122 * dependent on the cluster size; for non-bigalloc file systems, it is
c9de560d 123 * 512 blocks. This can be tuned via
d7a1fee1 124 * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
c9de560d
AT
125 * terms of number of blocks. If we have mounted the file system with -O
126 * stripe=<value> option the group prealloc request is normalized to the
b483bb77 127 * smallest multiple of the stripe value (sbi->s_stripe) which is
d7a1fee1 128 * greater than the default mb_group_prealloc.
c9de560d 129 *
196e402a
HS
130 * If "mb_optimize_scan" mount option is set, we maintain in memory group info
131 * structures in two data structures:
132 *
133 * 1) Array of largest free order lists (sbi->s_mb_largest_free_orders)
134 *
135 * Locking: sbi->s_mb_largest_free_orders_locks(array of rw locks)
136 *
137 * This is an array of lists where the index in the array represents the
138 * largest free order in the buddy bitmap of the participating group infos of
139 * that list. So, there are exactly MB_NUM_ORDERS(sb) (which means total
140 * number of buddy bitmap orders possible) number of lists. Group-infos are
141 * placed in appropriate lists.
142 *
143 * 2) Average fragment size rb tree (sbi->s_mb_avg_fragment_size_root)
144 *
145 * Locking: sbi->s_mb_rb_lock (rwlock)
146 *
147 * This is a red black tree consisting of group infos and the tree is sorted
148 * by average fragment sizes (which is calculated as ext4_group_info->bb_free
149 * / ext4_group_info->bb_fragments).
150 *
151 * When "mb_optimize_scan" mount option is set, mballoc consults the above data
152 * structures to decide the order in which groups are to be traversed for
153 * fulfilling an allocation request.
154 *
155 * At CR = 0, we look for groups which have the largest_free_order >= the order
156 * of the request. We directly look at the largest free order list in the data
157 * structure (1) above where largest_free_order = order of the request. If that
158 * list is empty, we look at remaining list in the increasing order of
159 * largest_free_order. This allows us to perform CR = 0 lookup in O(1) time.
160 *
161 * At CR = 1, we only consider groups where average fragment size > request
162 * size. So, we lookup a group which has average fragment size just above or
163 * equal to request size using our rb tree (data structure 2) in O(log N) time.
164 *
165 * If "mb_optimize_scan" mount option is not set, mballoc traverses groups in
166 * linear order which requires O(N) search time for each CR 0 and CR 1 phase.
167 *
d7a1fee1 168 * The regular allocator (using the buddy cache) supports a few tunables.
c9de560d 169 *
b713a5ec
TT
170 * /sys/fs/ext4/<partition>/mb_min_to_scan
171 * /sys/fs/ext4/<partition>/mb_max_to_scan
172 * /sys/fs/ext4/<partition>/mb_order2_req
196e402a 173 * /sys/fs/ext4/<partition>/mb_linear_limit
c9de560d 174 *
b713a5ec 175 * The regular allocator uses buddy scan only if the request len is power of
c9de560d
AT
176 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
177 * value of s_mb_order2_reqs can be tuned via
b713a5ec 178 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
af901ca1 179 * stripe size (sbi->s_stripe), we try to search for contiguous block in
b713a5ec
TT
180 * stripe size. This should result in better allocation on RAID setups. If
181 * not, we search in the specific group using bitmap for best extents. The
182 * tunable min_to_scan and max_to_scan control the behaviour here.
c9de560d 183 * min_to_scan indicate how long the mballoc __must__ look for a best
b713a5ec 184 * extent and max_to_scan indicates how long the mballoc __can__ look for a
c9de560d
AT
185 * best extent in the found extents. Searching for the blocks starts with
186 * the group specified as the goal value in allocation context via
187 * ac_g_ex. Each group is first checked based on the criteria whether it
caaf7a29 188 * can be used for allocation. ext4_mb_good_group explains how the groups are
c9de560d
AT
189 * checked.
190 *
196e402a
HS
191 * When "mb_optimize_scan" is turned on, as mentioned above, the groups may not
192 * get traversed linearly. That may result in subsequent allocations being not
193 * close to each other. And so, the underlying device may get filled up in a
194 * non-linear fashion. While that may not matter on non-rotational devices, for
195 * rotational devices that may result in higher seek times. "mb_linear_limit"
196 * tells mballoc how many groups mballoc should search linearly before
197 * performing consulting above data structures for more efficient lookups. For
198 * non rotational devices, this value defaults to 0 and for rotational devices
199 * this is set to MB_DEFAULT_LINEAR_LIMIT.
200 *
c9de560d
AT
201 * Both the prealloc space are getting populated as above. So for the first
202 * request we will hit the buddy cache which will result in this prealloc
203 * space getting filled. The prealloc space is then later used for the
204 * subsequent request.
205 */
206
207/*
208 * mballoc operates on the following data:
209 * - on-disk bitmap
210 * - in-core buddy (actually includes buddy and bitmap)
211 * - preallocation descriptors (PAs)
212 *
213 * there are two types of preallocations:
214 * - inode
215 * assiged to specific inode and can be used for this inode only.
216 * it describes part of inode's space preallocated to specific
217 * physical blocks. any block from that preallocated can be used
218 * independent. the descriptor just tracks number of blocks left
219 * unused. so, before taking some block from descriptor, one must
220 * make sure corresponded logical block isn't allocated yet. this
221 * also means that freeing any block within descriptor's range
222 * must discard all preallocated blocks.
223 * - locality group
224 * assigned to specific locality group which does not translate to
225 * permanent set of inodes: inode can join and leave group. space
226 * from this type of preallocation can be used for any inode. thus
227 * it's consumed from the beginning to the end.
228 *
229 * relation between them can be expressed as:
230 * in-core buddy = on-disk bitmap + preallocation descriptors
231 *
232 * this mean blocks mballoc considers used are:
233 * - allocated blocks (persistent)
234 * - preallocated blocks (non-persistent)
235 *
236 * consistency in mballoc world means that at any time a block is either
237 * free or used in ALL structures. notice: "any time" should not be read
238 * literally -- time is discrete and delimited by locks.
239 *
240 * to keep it simple, we don't use block numbers, instead we count number of
241 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
242 *
243 * all operations can be expressed as:
244 * - init buddy: buddy = on-disk + PAs
245 * - new PA: buddy += N; PA = N
246 * - use inode PA: on-disk += N; PA -= N
247 * - discard inode PA buddy -= on-disk - PA; PA = 0
248 * - use locality group PA on-disk += N; PA -= N
249 * - discard locality group PA buddy -= PA; PA = 0
250 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
251 * is used in real operation because we can't know actual used
252 * bits from PA, only from on-disk bitmap
253 *
254 * if we follow this strict logic, then all operations above should be atomic.
255 * given some of them can block, we'd have to use something like semaphores
256 * killing performance on high-end SMP hardware. let's try to relax it using
257 * the following knowledge:
258 * 1) if buddy is referenced, it's already initialized
259 * 2) while block is used in buddy and the buddy is referenced,
260 * nobody can re-allocate that block
261 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
262 * bit set and PA claims same block, it's OK. IOW, one can set bit in
263 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
264 * block
265 *
266 * so, now we're building a concurrency table:
267 * - init buddy vs.
268 * - new PA
269 * blocks for PA are allocated in the buddy, buddy must be referenced
270 * until PA is linked to allocation group to avoid concurrent buddy init
271 * - use inode PA
272 * we need to make sure that either on-disk bitmap or PA has uptodate data
273 * given (3) we care that PA-=N operation doesn't interfere with init
274 * - discard inode PA
275 * the simplest way would be to have buddy initialized by the discard
276 * - use locality group PA
277 * again PA-=N must be serialized with init
278 * - discard locality group PA
279 * the simplest way would be to have buddy initialized by the discard
280 * - new PA vs.
281 * - use inode PA
282 * i_data_sem serializes them
283 * - discard inode PA
284 * discard process must wait until PA isn't used by another process
285 * - use locality group PA
286 * some mutex should serialize them
287 * - discard locality group PA
288 * discard process must wait until PA isn't used by another process
289 * - use inode PA
290 * - use inode PA
291 * i_data_sem or another mutex should serializes them
292 * - discard inode PA
293 * discard process must wait until PA isn't used by another process
294 * - use locality group PA
295 * nothing wrong here -- they're different PAs covering different blocks
296 * - discard locality group PA
297 * discard process must wait until PA isn't used by another process
298 *
299 * now we're ready to make few consequences:
300 * - PA is referenced and while it is no discard is possible
301 * - PA is referenced until block isn't marked in on-disk bitmap
302 * - PA changes only after on-disk bitmap
303 * - discard must not compete with init. either init is done before
304 * any discard or they're serialized somehow
305 * - buddy init as sum of on-disk bitmap and PAs is done atomically
306 *
307 * a special case when we've used PA to emptiness. no need to modify buddy
308 * in this case, but we should care about concurrent init
309 *
310 */
311
312 /*
313 * Logic in few words:
314 *
315 * - allocation:
316 * load group
317 * find blocks
318 * mark bits in on-disk bitmap
319 * release group
320 *
321 * - use preallocation:
322 * find proper PA (per-inode or group)
323 * load group
324 * mark bits in on-disk bitmap
325 * release group
326 * release PA
327 *
328 * - free:
329 * load group
330 * mark bits in on-disk bitmap
331 * release group
332 *
333 * - discard preallocations in group:
334 * mark PAs deleted
335 * move them onto local list
336 * load on-disk bitmap
337 * load group
338 * remove PA from object (inode or locality group)
339 * mark free blocks in-core
340 *
341 * - discard inode's preallocations:
342 */
343
344/*
345 * Locking rules
346 *
347 * Locks:
348 * - bitlock on a group (group)
349 * - object (inode/locality) (object)
350 * - per-pa lock (pa)
196e402a
HS
351 * - cr0 lists lock (cr0)
352 * - cr1 tree lock (cr1)
c9de560d
AT
353 *
354 * Paths:
355 * - new pa
356 * object
357 * group
358 *
359 * - find and use pa:
360 * pa
361 *
362 * - release consumed pa:
363 * pa
364 * group
365 * object
366 *
367 * - generate in-core bitmap:
368 * group
369 * pa
370 *
371 * - discard all for given object (inode, locality group):
372 * object
373 * pa
374 * group
375 *
376 * - discard all for given group:
377 * group
378 * pa
379 * group
380 * object
381 *
196e402a
HS
382 * - allocation path (ext4_mb_regular_allocator)
383 * group
384 * cr0/cr1
c9de560d 385 */
c3a326a6
AK
386static struct kmem_cache *ext4_pspace_cachep;
387static struct kmem_cache *ext4_ac_cachep;
18aadd47 388static struct kmem_cache *ext4_free_data_cachep;
fb1813f4
CW
389
390/* We create slab caches for groupinfo data structures based on the
391 * superblock block size. There will be one per mounted filesystem for
392 * each unique s_blocksize_bits */
2892c15d 393#define NR_GRPINFO_CACHES 8
fb1813f4
CW
394static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
395
d6006186 396static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
2892c15d
ES
397 "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
398 "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
399 "ext4_groupinfo_64k", "ext4_groupinfo_128k"
400};
401
c3a326a6
AK
402static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
403 ext4_group_t group);
7a2fcbf7
AK
404static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
405 ext4_group_t group);
53f86b17 406static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac);
c3a326a6 407
196e402a
HS
408static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
409 ext4_group_t group, int cr);
410
55cdd0af
WJ
411static int ext4_try_to_trim_range(struct super_block *sb,
412 struct ext4_buddy *e4b, ext4_grpblk_t start,
413 ext4_grpblk_t max, ext4_grpblk_t minblocks);
414
07b5b8e1
RH
415/*
416 * The algorithm using this percpu seq counter goes below:
417 * 1. We sample the percpu discard_pa_seq counter before trying for block
418 * allocation in ext4_mb_new_blocks().
419 * 2. We increment this percpu discard_pa_seq counter when we either allocate
420 * or free these blocks i.e. while marking those blocks as used/free in
421 * mb_mark_used()/mb_free_blocks().
422 * 3. We also increment this percpu seq counter when we successfully identify
423 * that the bb_prealloc_list is not empty and hence proceed for discarding
424 * of those PAs inside ext4_mb_discard_group_preallocations().
425 *
426 * Now to make sure that the regular fast path of block allocation is not
427 * affected, as a small optimization we only sample the percpu seq counter
428 * on that cpu. Only when the block allocation fails and when freed blocks
429 * found were 0, that is when we sample percpu seq counter for all cpus using
430 * below function ext4_get_discard_pa_seq_sum(). This happens after making
431 * sure that all the PAs on grp->bb_prealloc_list got freed or if it's empty.
432 */
433static DEFINE_PER_CPU(u64, discard_pa_seq);
434static inline u64 ext4_get_discard_pa_seq_sum(void)
435{
436 int __cpu;
437 u64 __seq = 0;
438
439 for_each_possible_cpu(__cpu)
440 __seq += per_cpu(discard_pa_seq, __cpu);
441 return __seq;
442}
443
ffad0a44
AK
444static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
445{
c9de560d 446#if BITS_PER_LONG == 64
ffad0a44
AK
447 *bit += ((unsigned long) addr & 7UL) << 3;
448 addr = (void *) ((unsigned long) addr & ~7UL);
c9de560d 449#elif BITS_PER_LONG == 32
ffad0a44
AK
450 *bit += ((unsigned long) addr & 3UL) << 3;
451 addr = (void *) ((unsigned long) addr & ~3UL);
c9de560d
AT
452#else
453#error "how many bits you are?!"
454#endif
ffad0a44
AK
455 return addr;
456}
c9de560d
AT
457
458static inline int mb_test_bit(int bit, void *addr)
459{
460 /*
461 * ext4_test_bit on architecture like powerpc
462 * needs unsigned long aligned address
463 */
ffad0a44 464 addr = mb_correct_addr_and_bit(&bit, addr);
c9de560d
AT
465 return ext4_test_bit(bit, addr);
466}
467
468static inline void mb_set_bit(int bit, void *addr)
469{
ffad0a44 470 addr = mb_correct_addr_and_bit(&bit, addr);
c9de560d
AT
471 ext4_set_bit(bit, addr);
472}
473
c9de560d
AT
474static inline void mb_clear_bit(int bit, void *addr)
475{
ffad0a44 476 addr = mb_correct_addr_and_bit(&bit, addr);
c9de560d
AT
477 ext4_clear_bit(bit, addr);
478}
479
eabe0444
AS
480static inline int mb_test_and_clear_bit(int bit, void *addr)
481{
482 addr = mb_correct_addr_and_bit(&bit, addr);
483 return ext4_test_and_clear_bit(bit, addr);
484}
485
ffad0a44
AK
486static inline int mb_find_next_zero_bit(void *addr, int max, int start)
487{
e7dfb246 488 int fix = 0, ret, tmpmax;
ffad0a44 489 addr = mb_correct_addr_and_bit(&fix, addr);
e7dfb246 490 tmpmax = max + fix;
ffad0a44
AK
491 start += fix;
492
e7dfb246
AK
493 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
494 if (ret > max)
495 return max;
496 return ret;
ffad0a44
AK
497}
498
499static inline int mb_find_next_bit(void *addr, int max, int start)
500{
e7dfb246 501 int fix = 0, ret, tmpmax;
ffad0a44 502 addr = mb_correct_addr_and_bit(&fix, addr);
e7dfb246 503 tmpmax = max + fix;
ffad0a44
AK
504 start += fix;
505
e7dfb246
AK
506 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
507 if (ret > max)
508 return max;
509 return ret;
ffad0a44
AK
510}
511
c9de560d
AT
512static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
513{
514 char *bb;
515
c5e8f3f3 516 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
c9de560d
AT
517 BUG_ON(max == NULL);
518
519 if (order > e4b->bd_blkbits + 1) {
520 *max = 0;
521 return NULL;
522 }
523
524 /* at order 0 we see each particular block */
84b775a3
CL
525 if (order == 0) {
526 *max = 1 << (e4b->bd_blkbits + 3);
c5e8f3f3 527 return e4b->bd_bitmap;
84b775a3 528 }
c9de560d 529
c5e8f3f3 530 bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
c9de560d
AT
531 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
532
533 return bb;
534}
535
536#ifdef DOUBLE_CHECK
537static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
538 int first, int count)
539{
540 int i;
541 struct super_block *sb = e4b->bd_sb;
542
543 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
544 return;
bc8e6740 545 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
c9de560d
AT
546 for (i = 0; i < count; i++) {
547 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
548 ext4_fsblk_t blocknr;
5661bd68
AM
549
550 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
53accfa9 551 blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
5d1b1b3f 552 ext4_grp_locked_error(sb, e4b->bd_group,
e29136f8
TT
553 inode ? inode->i_ino : 0,
554 blocknr,
555 "freeing block already freed "
556 "(bit %u)",
557 first + i);
736dedbb
WS
558 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
559 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
c9de560d
AT
560 }
561 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
562 }
563}
564
565static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
566{
567 int i;
568
569 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
570 return;
bc8e6740 571 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
c9de560d
AT
572 for (i = 0; i < count; i++) {
573 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
574 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
575 }
576}
577
578static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
579{
eb2b8ebb
RH
580 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
581 return;
c9de560d
AT
582 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
583 unsigned char *b1, *b2;
584 int i;
585 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
586 b2 = (unsigned char *) bitmap;
587 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
588 if (b1[i] != b2[i]) {
9d8b9ec4
TT
589 ext4_msg(e4b->bd_sb, KERN_ERR,
590 "corruption in group %u "
591 "at byte %u(%u): %x in copy != %x "
592 "on disk/prealloc",
593 e4b->bd_group, i, i * 8, b1[i], b2[i]);
c9de560d
AT
594 BUG();
595 }
596 }
597 }
598}
599
a3450215
RH
600static void mb_group_bb_bitmap_alloc(struct super_block *sb,
601 struct ext4_group_info *grp, ext4_group_t group)
602{
603 struct buffer_head *bh;
604
605 grp->bb_bitmap = kmalloc(sb->s_blocksize, GFP_NOFS);
eb2b8ebb
RH
606 if (!grp->bb_bitmap)
607 return;
a3450215
RH
608
609 bh = ext4_read_block_bitmap(sb, group);
eb2b8ebb
RH
610 if (IS_ERR_OR_NULL(bh)) {
611 kfree(grp->bb_bitmap);
612 grp->bb_bitmap = NULL;
613 return;
614 }
a3450215
RH
615
616 memcpy(grp->bb_bitmap, bh->b_data, sb->s_blocksize);
617 put_bh(bh);
618}
619
620static void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
621{
622 kfree(grp->bb_bitmap);
623}
624
c9de560d
AT
625#else
626static inline void mb_free_blocks_double(struct inode *inode,
627 struct ext4_buddy *e4b, int first, int count)
628{
629 return;
630}
631static inline void mb_mark_used_double(struct ext4_buddy *e4b,
632 int first, int count)
633{
634 return;
635}
636static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
637{
638 return;
639}
a3450215
RH
640
641static inline void mb_group_bb_bitmap_alloc(struct super_block *sb,
642 struct ext4_group_info *grp, ext4_group_t group)
643{
644 return;
645}
646
647static inline void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
648{
649 return;
650}
c9de560d
AT
651#endif
652
653#ifdef AGGRESSIVE_CHECK
654
655#define MB_CHECK_ASSERT(assert) \
656do { \
657 if (!(assert)) { \
658 printk(KERN_EMERG \
659 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
660 function, file, line, # assert); \
661 BUG(); \
662 } \
663} while (0)
664
665static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
666 const char *function, int line)
667{
668 struct super_block *sb = e4b->bd_sb;
669 int order = e4b->bd_blkbits + 1;
670 int max;
671 int max2;
672 int i;
673 int j;
674 int k;
675 int count;
676 struct ext4_group_info *grp;
677 int fragments = 0;
678 int fstart;
679 struct list_head *cur;
680 void *buddy;
681 void *buddy2;
682
addd752c
CX
683 if (e4b->bd_info->bb_check_counter++ % 10)
684 return 0;
c9de560d
AT
685
686 while (order > 1) {
687 buddy = mb_find_buddy(e4b, order, &max);
688 MB_CHECK_ASSERT(buddy);
689 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
690 MB_CHECK_ASSERT(buddy2);
691 MB_CHECK_ASSERT(buddy != buddy2);
692 MB_CHECK_ASSERT(max * 2 == max2);
693
694 count = 0;
695 for (i = 0; i < max; i++) {
696
697 if (mb_test_bit(i, buddy)) {
af2b3275 698 /* only single bit in buddy2 may be 0 */
c9de560d
AT
699 if (!mb_test_bit(i << 1, buddy2)) {
700 MB_CHECK_ASSERT(
701 mb_test_bit((i<<1)+1, buddy2));
c9de560d
AT
702 }
703 continue;
704 }
705
0a10da73 706 /* both bits in buddy2 must be 1 */
c9de560d
AT
707 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
708 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
709
710 for (j = 0; j < (1 << order); j++) {
711 k = (i * (1 << order)) + j;
712 MB_CHECK_ASSERT(
c5e8f3f3 713 !mb_test_bit(k, e4b->bd_bitmap));
c9de560d
AT
714 }
715 count++;
716 }
717 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
718 order--;
719 }
720
721 fstart = -1;
722 buddy = mb_find_buddy(e4b, 0, &max);
723 for (i = 0; i < max; i++) {
724 if (!mb_test_bit(i, buddy)) {
725 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
726 if (fstart == -1) {
727 fragments++;
728 fstart = i;
729 }
730 continue;
731 }
732 fstart = -1;
733 /* check used bits only */
734 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
735 buddy2 = mb_find_buddy(e4b, j, &max2);
736 k = i >> j;
737 MB_CHECK_ASSERT(k < max2);
738 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
739 }
740 }
741 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
742 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
743
744 grp = ext4_get_group_info(sb, e4b->bd_group);
c9de560d
AT
745 list_for_each(cur, &grp->bb_prealloc_list) {
746 ext4_group_t groupnr;
747 struct ext4_prealloc_space *pa;
60bd63d1
SR
748 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
749 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
c9de560d 750 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
60bd63d1 751 for (i = 0; i < pa->pa_len; i++)
c9de560d
AT
752 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
753 }
754 return 0;
755}
756#undef MB_CHECK_ASSERT
757#define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
46e665e9 758 __FILE__, __func__, __LINE__)
c9de560d
AT
759#else
760#define mb_check_buddy(e4b)
761#endif
762
7c786059
CL
763/*
764 * Divide blocks started from @first with length @len into
765 * smaller chunks with power of 2 blocks.
766 * Clear the bits in bitmap which the blocks of the chunk(s) covered,
767 * then increase bb_counters[] for corresponded chunk size.
768 */
c9de560d 769static void ext4_mb_mark_free_simple(struct super_block *sb,
a36b4498 770 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
c9de560d
AT
771 struct ext4_group_info *grp)
772{
773 struct ext4_sb_info *sbi = EXT4_SB(sb);
a36b4498
ES
774 ext4_grpblk_t min;
775 ext4_grpblk_t max;
776 ext4_grpblk_t chunk;
69e43e8c 777 unsigned int border;
c9de560d 778
7137d7a4 779 BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
c9de560d
AT
780
781 border = 2 << sb->s_blocksize_bits;
782
783 while (len > 0) {
784 /* find how many blocks can be covered since this position */
785 max = ffs(first | border) - 1;
786
787 /* find how many blocks of power 2 we need to mark */
788 min = fls(len) - 1;
789
790 if (max < min)
791 min = max;
792 chunk = 1 << min;
793
794 /* mark multiblock chunks only */
795 grp->bb_counters[min]++;
796 if (min > 0)
797 mb_clear_bit(first >> min,
798 buddy + sbi->s_mb_offsets[min]);
799
800 len -= chunk;
801 first += chunk;
802 }
803}
804
196e402a
HS
805static void ext4_mb_rb_insert(struct rb_root *root, struct rb_node *new,
806 int (*cmp)(struct rb_node *, struct rb_node *))
807{
808 struct rb_node **iter = &root->rb_node, *parent = NULL;
809
810 while (*iter) {
811 parent = *iter;
812 if (cmp(new, *iter) > 0)
813 iter = &((*iter)->rb_left);
814 else
815 iter = &((*iter)->rb_right);
816 }
817
818 rb_link_node(new, parent, iter);
819 rb_insert_color(new, root);
820}
821
822static int
823ext4_mb_avg_fragment_size_cmp(struct rb_node *rb1, struct rb_node *rb2)
824{
825 struct ext4_group_info *grp1 = rb_entry(rb1,
826 struct ext4_group_info,
827 bb_avg_fragment_size_rb);
828 struct ext4_group_info *grp2 = rb_entry(rb2,
829 struct ext4_group_info,
830 bb_avg_fragment_size_rb);
831 int num_frags_1, num_frags_2;
832
833 num_frags_1 = grp1->bb_fragments ?
834 grp1->bb_free / grp1->bb_fragments : 0;
835 num_frags_2 = grp2->bb_fragments ?
836 grp2->bb_free / grp2->bb_fragments : 0;
837
838 return (num_frags_2 - num_frags_1);
839}
840
841/*
842 * Reinsert grpinfo into the avg_fragment_size tree with new average
843 * fragment size.
844 */
845static void
846mb_update_avg_fragment_size(struct super_block *sb, struct ext4_group_info *grp)
847{
848 struct ext4_sb_info *sbi = EXT4_SB(sb);
849
850 if (!test_opt2(sb, MB_OPTIMIZE_SCAN) || grp->bb_free == 0)
851 return;
852
853 write_lock(&sbi->s_mb_rb_lock);
854 if (!RB_EMPTY_NODE(&grp->bb_avg_fragment_size_rb)) {
855 rb_erase(&grp->bb_avg_fragment_size_rb,
856 &sbi->s_mb_avg_fragment_size_root);
857 RB_CLEAR_NODE(&grp->bb_avg_fragment_size_rb);
858 }
859
860 ext4_mb_rb_insert(&sbi->s_mb_avg_fragment_size_root,
861 &grp->bb_avg_fragment_size_rb,
862 ext4_mb_avg_fragment_size_cmp);
863 write_unlock(&sbi->s_mb_rb_lock);
864}
865
866/*
867 * Choose next group by traversing largest_free_order lists. Updates *new_cr if
868 * cr level needs an update.
869 */
870static void ext4_mb_choose_next_group_cr0(struct ext4_allocation_context *ac,
871 int *new_cr, ext4_group_t *group, ext4_group_t ngroups)
872{
873 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
874 struct ext4_group_info *iter, *grp;
875 int i;
876
877 if (ac->ac_status == AC_STATUS_FOUND)
878 return;
879
880 if (unlikely(sbi->s_mb_stats && ac->ac_flags & EXT4_MB_CR0_OPTIMIZED))
881 atomic_inc(&sbi->s_bal_cr0_bad_suggestions);
882
883 grp = NULL;
884 for (i = ac->ac_2order; i < MB_NUM_ORDERS(ac->ac_sb); i++) {
885 if (list_empty(&sbi->s_mb_largest_free_orders[i]))
886 continue;
887 read_lock(&sbi->s_mb_largest_free_orders_locks[i]);
888 if (list_empty(&sbi->s_mb_largest_free_orders[i])) {
889 read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
890 continue;
891 }
892 grp = NULL;
893 list_for_each_entry(iter, &sbi->s_mb_largest_free_orders[i],
894 bb_largest_free_order_node) {
895 if (sbi->s_mb_stats)
896 atomic64_inc(&sbi->s_bal_cX_groups_considered[0]);
897 if (likely(ext4_mb_good_group(ac, iter->bb_group, 0))) {
898 grp = iter;
899 break;
900 }
901 }
902 read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
903 if (grp)
904 break;
905 }
906
907 if (!grp) {
908 /* Increment cr and search again */
909 *new_cr = 1;
910 } else {
911 *group = grp->bb_group;
912 ac->ac_last_optimal_group = *group;
913 ac->ac_flags |= EXT4_MB_CR0_OPTIMIZED;
914 }
915}
916
917/*
918 * Choose next group by traversing average fragment size tree. Updates *new_cr
919 * if cr lvel needs an update. Sets EXT4_MB_SEARCH_NEXT_LINEAR to indicate that
920 * the linear search should continue for one iteration since there's lock
921 * contention on the rb tree lock.
922 */
923static void ext4_mb_choose_next_group_cr1(struct ext4_allocation_context *ac,
924 int *new_cr, ext4_group_t *group, ext4_group_t ngroups)
925{
926 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
927 int avg_fragment_size, best_so_far;
928 struct rb_node *node, *found;
929 struct ext4_group_info *grp;
930
931 /*
932 * If there is contention on the lock, instead of waiting for the lock
933 * to become available, just continue searching lineraly. We'll resume
934 * our rb tree search later starting at ac->ac_last_optimal_group.
935 */
936 if (!read_trylock(&sbi->s_mb_rb_lock)) {
937 ac->ac_flags |= EXT4_MB_SEARCH_NEXT_LINEAR;
938 return;
939 }
940
941 if (unlikely(ac->ac_flags & EXT4_MB_CR1_OPTIMIZED)) {
942 if (sbi->s_mb_stats)
943 atomic_inc(&sbi->s_bal_cr1_bad_suggestions);
944 /* We have found something at CR 1 in the past */
945 grp = ext4_get_group_info(ac->ac_sb, ac->ac_last_optimal_group);
946 for (found = rb_next(&grp->bb_avg_fragment_size_rb); found != NULL;
947 found = rb_next(found)) {
948 grp = rb_entry(found, struct ext4_group_info,
949 bb_avg_fragment_size_rb);
950 if (sbi->s_mb_stats)
951 atomic64_inc(&sbi->s_bal_cX_groups_considered[1]);
952 if (likely(ext4_mb_good_group(ac, grp->bb_group, 1)))
953 break;
954 }
955 goto done;
956 }
957
958 node = sbi->s_mb_avg_fragment_size_root.rb_node;
959 best_so_far = 0;
960 found = NULL;
961
962 while (node) {
963 grp = rb_entry(node, struct ext4_group_info,
964 bb_avg_fragment_size_rb);
965 avg_fragment_size = 0;
966 if (ext4_mb_good_group(ac, grp->bb_group, 1)) {
967 avg_fragment_size = grp->bb_fragments ?
968 grp->bb_free / grp->bb_fragments : 0;
969 if (!best_so_far || avg_fragment_size < best_so_far) {
970 best_so_far = avg_fragment_size;
971 found = node;
972 }
973 }
974 if (avg_fragment_size > ac->ac_g_ex.fe_len)
975 node = node->rb_right;
976 else
977 node = node->rb_left;
978 }
979
980done:
981 if (found) {
982 grp = rb_entry(found, struct ext4_group_info,
983 bb_avg_fragment_size_rb);
984 *group = grp->bb_group;
985 ac->ac_flags |= EXT4_MB_CR1_OPTIMIZED;
986 } else {
987 *new_cr = 2;
988 }
989
990 read_unlock(&sbi->s_mb_rb_lock);
991 ac->ac_last_optimal_group = *group;
992}
993
994static inline int should_optimize_scan(struct ext4_allocation_context *ac)
995{
996 if (unlikely(!test_opt2(ac->ac_sb, MB_OPTIMIZE_SCAN)))
997 return 0;
998 if (ac->ac_criteria >= 2)
999 return 0;
077d0c2c 1000 if (!ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS))
196e402a
HS
1001 return 0;
1002 return 1;
1003}
1004
1005/*
1006 * Return next linear group for allocation. If linear traversal should not be
1007 * performed, this function just returns the same group
1008 */
1009static int
1010next_linear_group(struct ext4_allocation_context *ac, int group, int ngroups)
1011{
1012 if (!should_optimize_scan(ac))
1013 goto inc_and_return;
1014
1015 if (ac->ac_groups_linear_remaining) {
1016 ac->ac_groups_linear_remaining--;
1017 goto inc_and_return;
1018 }
1019
1020 if (ac->ac_flags & EXT4_MB_SEARCH_NEXT_LINEAR) {
1021 ac->ac_flags &= ~EXT4_MB_SEARCH_NEXT_LINEAR;
1022 goto inc_and_return;
1023 }
1024
1025 return group;
1026inc_and_return:
1027 /*
1028 * Artificially restricted ngroups for non-extent
1029 * files makes group > ngroups possible on first loop.
1030 */
1031 return group + 1 >= ngroups ? 0 : group + 1;
1032}
1033
1034/*
1035 * ext4_mb_choose_next_group: choose next group for allocation.
1036 *
1037 * @ac Allocation Context
1038 * @new_cr This is an output parameter. If the there is no good group
1039 * available at current CR level, this field is updated to indicate
1040 * the new cr level that should be used.
1041 * @group This is an input / output parameter. As an input it indicates the
1042 * next group that the allocator intends to use for allocation. As
1043 * output, this field indicates the next group that should be used as
1044 * determined by the optimization functions.
1045 * @ngroups Total number of groups
1046 */
1047static void ext4_mb_choose_next_group(struct ext4_allocation_context *ac,
1048 int *new_cr, ext4_group_t *group, ext4_group_t ngroups)
1049{
1050 *new_cr = ac->ac_criteria;
1051
4fca50d4
JK
1052 if (!should_optimize_scan(ac) || ac->ac_groups_linear_remaining) {
1053 *group = next_linear_group(ac, *group, ngroups);
196e402a 1054 return;
4fca50d4 1055 }
196e402a
HS
1056
1057 if (*new_cr == 0) {
1058 ext4_mb_choose_next_group_cr0(ac, new_cr, group, ngroups);
1059 } else if (*new_cr == 1) {
1060 ext4_mb_choose_next_group_cr1(ac, new_cr, group, ngroups);
1061 } else {
1062 /*
1063 * TODO: For CR=2, we can arrange groups in an rb tree sorted by
1064 * bb_free. But until that happens, we should never come here.
1065 */
1066 WARN_ON(1);
1067 }
1068}
1069
8a57d9d6
CW
1070/*
1071 * Cache the order of the largest free extent we have available in this block
1072 * group.
1073 */
1074static void
1075mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
1076{
196e402a 1077 struct ext4_sb_info *sbi = EXT4_SB(sb);
8a57d9d6 1078 int i;
8a57d9d6 1079
1940265e
JK
1080 for (i = MB_NUM_ORDERS(sb) - 1; i >= 0; i--)
1081 if (grp->bb_counters[i] > 0)
1082 break;
1083 /* No need to move between order lists? */
1084 if (!test_opt2(sb, MB_OPTIMIZE_SCAN) ||
1085 i == grp->bb_largest_free_order) {
1086 grp->bb_largest_free_order = i;
1087 return;
1088 }
1089
1090 if (grp->bb_largest_free_order >= 0) {
196e402a
HS
1091 write_lock(&sbi->s_mb_largest_free_orders_locks[
1092 grp->bb_largest_free_order]);
1093 list_del_init(&grp->bb_largest_free_order_node);
1094 write_unlock(&sbi->s_mb_largest_free_orders_locks[
1095 grp->bb_largest_free_order]);
1096 }
1940265e
JK
1097 grp->bb_largest_free_order = i;
1098 if (grp->bb_largest_free_order >= 0 && grp->bb_free) {
196e402a
HS
1099 write_lock(&sbi->s_mb_largest_free_orders_locks[
1100 grp->bb_largest_free_order]);
1101 list_add_tail(&grp->bb_largest_free_order_node,
1102 &sbi->s_mb_largest_free_orders[grp->bb_largest_free_order]);
1103 write_unlock(&sbi->s_mb_largest_free_orders_locks[
1104 grp->bb_largest_free_order]);
1105 }
8a57d9d6
CW
1106}
1107
089ceecc
ES
1108static noinline_for_stack
1109void ext4_mb_generate_buddy(struct super_block *sb,
c9de560d
AT
1110 void *buddy, void *bitmap, ext4_group_t group)
1111{
1112 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
e43bb4e6 1113 struct ext4_sb_info *sbi = EXT4_SB(sb);
7137d7a4 1114 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
a36b4498
ES
1115 ext4_grpblk_t i = 0;
1116 ext4_grpblk_t first;
1117 ext4_grpblk_t len;
c9de560d
AT
1118 unsigned free = 0;
1119 unsigned fragments = 0;
1120 unsigned long long period = get_cycles();
1121
1122 /* initialize buddy from bitmap which is aggregation
1123 * of on-disk bitmap and preallocations */
ffad0a44 1124 i = mb_find_next_zero_bit(bitmap, max, 0);
c9de560d
AT
1125 grp->bb_first_free = i;
1126 while (i < max) {
1127 fragments++;
1128 first = i;
ffad0a44 1129 i = mb_find_next_bit(bitmap, max, i);
c9de560d
AT
1130 len = i - first;
1131 free += len;
1132 if (len > 1)
1133 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
1134 else
1135 grp->bb_counters[0]++;
1136 if (i < max)
ffad0a44 1137 i = mb_find_next_zero_bit(bitmap, max, i);
c9de560d
AT
1138 }
1139 grp->bb_fragments = fragments;
1140
1141 if (free != grp->bb_free) {
e29136f8 1142 ext4_grp_locked_error(sb, group, 0, 0,
94d4c066
TT
1143 "block bitmap and bg descriptor "
1144 "inconsistent: %u vs %u free clusters",
e29136f8 1145 free, grp->bb_free);
e56eb659 1146 /*
163a203d 1147 * If we intend to continue, we consider group descriptor
e56eb659
AK
1148 * corrupt and update bb_free using bitmap value
1149 */
c9de560d 1150 grp->bb_free = free;
db79e6d1
WS
1151 ext4_mark_group_bitmap_corrupted(sb, group,
1152 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
c9de560d 1153 }
8a57d9d6 1154 mb_set_largest_free_order(sb, grp);
c9de560d
AT
1155
1156 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
1157
1158 period = get_cycles() - period;
67d25186
HS
1159 atomic_inc(&sbi->s_mb_buddies_generated);
1160 atomic64_add(period, &sbi->s_mb_generation_time);
196e402a 1161 mb_update_avg_fragment_size(sb, grp);
c9de560d
AT
1162}
1163
1164/* The buddy information is attached the buddy cache inode
1165 * for convenience. The information regarding each group
1166 * is loaded via ext4_mb_load_buddy. The information involve
1167 * block bitmap and buddy information. The information are
1168 * stored in the inode as
1169 *
1170 * { page }
c3a326a6 1171 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
c9de560d
AT
1172 *
1173 *
1174 * one block each for bitmap and buddy information.
1175 * So for each group we take up 2 blocks. A page can
ea1754a0 1176 * contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
c9de560d
AT
1177 * So it can have information regarding groups_per_page which
1178 * is blocks_per_page/2
8a57d9d6
CW
1179 *
1180 * Locking note: This routine takes the block group lock of all groups
1181 * for this page; do not hold this lock when calling this routine!
c9de560d
AT
1182 */
1183
adb7ef60 1184static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
c9de560d 1185{
8df9675f 1186 ext4_group_t ngroups;
c9de560d
AT
1187 int blocksize;
1188 int blocks_per_page;
1189 int groups_per_page;
1190 int err = 0;
1191 int i;
813e5727 1192 ext4_group_t first_group, group;
c9de560d
AT
1193 int first_block;
1194 struct super_block *sb;
1195 struct buffer_head *bhs;
fa77dcfa 1196 struct buffer_head **bh = NULL;
c9de560d
AT
1197 struct inode *inode;
1198 char *data;
1199 char *bitmap;
9b8b7d35 1200 struct ext4_group_info *grinfo;
c9de560d 1201
c9de560d
AT
1202 inode = page->mapping->host;
1203 sb = inode->i_sb;
8df9675f 1204 ngroups = ext4_get_groups_count(sb);
93407472 1205 blocksize = i_blocksize(inode);
09cbfeaf 1206 blocks_per_page = PAGE_SIZE / blocksize;
c9de560d 1207
d3df1453
RH
1208 mb_debug(sb, "init page %lu\n", page->index);
1209
c9de560d
AT
1210 groups_per_page = blocks_per_page >> 1;
1211 if (groups_per_page == 0)
1212 groups_per_page = 1;
1213
1214 /* allocate buffer_heads to read bitmaps */
1215 if (groups_per_page > 1) {
c9de560d 1216 i = sizeof(struct buffer_head *) * groups_per_page;
adb7ef60 1217 bh = kzalloc(i, gfp);
813e5727
TT
1218 if (bh == NULL) {
1219 err = -ENOMEM;
c9de560d 1220 goto out;
813e5727 1221 }
c9de560d
AT
1222 } else
1223 bh = &bhs;
1224
1225 first_group = page->index * blocks_per_page / 2;
1226
1227 /* read all groups the page covers into the cache */
813e5727
TT
1228 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1229 if (group >= ngroups)
c9de560d
AT
1230 break;
1231
813e5727 1232 grinfo = ext4_get_group_info(sb, group);
9b8b7d35
AG
1233 /*
1234 * If page is uptodate then we came here after online resize
1235 * which added some new uninitialized group info structs, so
1236 * we must skip all initialized uptodate buddies on the page,
1237 * which may be currently in use by an allocating task.
1238 */
1239 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
1240 bh[i] = NULL;
1241 continue;
1242 }
cfd73237 1243 bh[i] = ext4_read_block_bitmap_nowait(sb, group, false);
9008a58e
DW
1244 if (IS_ERR(bh[i])) {
1245 err = PTR_ERR(bh[i]);
1246 bh[i] = NULL;
c9de560d 1247 goto out;
2ccb5fb9 1248 }
d3df1453 1249 mb_debug(sb, "read bitmap for group %u\n", group);
c9de560d
AT
1250 }
1251
1252 /* wait for I/O completion */
813e5727 1253 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
9008a58e
DW
1254 int err2;
1255
1256 if (!bh[i])
1257 continue;
1258 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
1259 if (!err)
1260 err = err2;
813e5727 1261 }
c9de560d
AT
1262
1263 first_block = page->index * blocks_per_page;
1264 for (i = 0; i < blocks_per_page; i++) {
c9de560d 1265 group = (first_block + i) >> 1;
8df9675f 1266 if (group >= ngroups)
c9de560d
AT
1267 break;
1268
9b8b7d35
AG
1269 if (!bh[group - first_group])
1270 /* skip initialized uptodate buddy */
1271 continue;
1272
bbdc322f
LC
1273 if (!buffer_verified(bh[group - first_group]))
1274 /* Skip faulty bitmaps */
1275 continue;
1276 err = 0;
1277
c9de560d
AT
1278 /*
1279 * data carry information regarding this
1280 * particular group in the format specified
1281 * above
1282 *
1283 */
1284 data = page_address(page) + (i * blocksize);
1285 bitmap = bh[group - first_group]->b_data;
1286
1287 /*
1288 * We place the buddy block and bitmap block
1289 * close together
1290 */
1291 if ((first_block + i) & 1) {
1292 /* this is block of buddy */
1293 BUG_ON(incore == NULL);
d3df1453 1294 mb_debug(sb, "put buddy for group %u in page %lu/%x\n",
c9de560d 1295 group, page->index, i * blocksize);
f307333e 1296 trace_ext4_mb_buddy_bitmap_load(sb, group);
c9de560d
AT
1297 grinfo = ext4_get_group_info(sb, group);
1298 grinfo->bb_fragments = 0;
1299 memset(grinfo->bb_counters, 0,
1927805e 1300 sizeof(*grinfo->bb_counters) *
4b68f6df 1301 (MB_NUM_ORDERS(sb)));
c9de560d
AT
1302 /*
1303 * incore got set to the group block bitmap below
1304 */
7a2fcbf7 1305 ext4_lock_group(sb, group);
9b8b7d35
AG
1306 /* init the buddy */
1307 memset(data, 0xff, blocksize);
c9de560d 1308 ext4_mb_generate_buddy(sb, data, incore, group);
7a2fcbf7 1309 ext4_unlock_group(sb, group);
c9de560d
AT
1310 incore = NULL;
1311 } else {
1312 /* this is block of bitmap */
1313 BUG_ON(incore != NULL);
d3df1453 1314 mb_debug(sb, "put bitmap for group %u in page %lu/%x\n",
c9de560d 1315 group, page->index, i * blocksize);
f307333e 1316 trace_ext4_mb_bitmap_load(sb, group);
c9de560d
AT
1317
1318 /* see comments in ext4_mb_put_pa() */
1319 ext4_lock_group(sb, group);
1320 memcpy(data, bitmap, blocksize);
1321
1322 /* mark all preallocated blks used in in-core bitmap */
1323 ext4_mb_generate_from_pa(sb, data, group);
7a2fcbf7 1324 ext4_mb_generate_from_freelist(sb, data, group);
c9de560d
AT
1325 ext4_unlock_group(sb, group);
1326
1327 /* set incore so that the buddy information can be
1328 * generated using this
1329 */
1330 incore = data;
1331 }
1332 }
1333 SetPageUptodate(page);
1334
1335out:
1336 if (bh) {
9b8b7d35 1337 for (i = 0; i < groups_per_page; i++)
c9de560d
AT
1338 brelse(bh[i]);
1339 if (bh != &bhs)
1340 kfree(bh);
1341 }
1342 return err;
1343}
1344
eee4adc7 1345/*
2de8807b
AG
1346 * Lock the buddy and bitmap pages. This make sure other parallel init_group
1347 * on the same buddy page doesn't happen whild holding the buddy page lock.
1348 * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
1349 * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
eee4adc7 1350 */
2de8807b 1351static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
adb7ef60 1352 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
eee4adc7 1353{
2de8807b
AG
1354 struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
1355 int block, pnum, poff;
eee4adc7 1356 int blocks_per_page;
2de8807b
AG
1357 struct page *page;
1358
1359 e4b->bd_buddy_page = NULL;
1360 e4b->bd_bitmap_page = NULL;
eee4adc7 1361
09cbfeaf 1362 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
eee4adc7
ES
1363 /*
1364 * the buddy cache inode stores the block bitmap
1365 * and buddy information in consecutive blocks.
1366 * So for each group we need two blocks.
1367 */
1368 block = group * 2;
1369 pnum = block / blocks_per_page;
2de8807b 1370 poff = block % blocks_per_page;
adb7ef60 1371 page = find_or_create_page(inode->i_mapping, pnum, gfp);
2de8807b 1372 if (!page)
c57ab39b 1373 return -ENOMEM;
2de8807b
AG
1374 BUG_ON(page->mapping != inode->i_mapping);
1375 e4b->bd_bitmap_page = page;
1376 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1377
1378 if (blocks_per_page >= 2) {
1379 /* buddy and bitmap are on the same page */
1380 return 0;
eee4adc7 1381 }
2de8807b
AG
1382
1383 block++;
1384 pnum = block / blocks_per_page;
adb7ef60 1385 page = find_or_create_page(inode->i_mapping, pnum, gfp);
2de8807b 1386 if (!page)
c57ab39b 1387 return -ENOMEM;
2de8807b
AG
1388 BUG_ON(page->mapping != inode->i_mapping);
1389 e4b->bd_buddy_page = page;
1390 return 0;
eee4adc7
ES
1391}
1392
2de8807b 1393static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
eee4adc7 1394{
2de8807b
AG
1395 if (e4b->bd_bitmap_page) {
1396 unlock_page(e4b->bd_bitmap_page);
09cbfeaf 1397 put_page(e4b->bd_bitmap_page);
2de8807b
AG
1398 }
1399 if (e4b->bd_buddy_page) {
1400 unlock_page(e4b->bd_buddy_page);
09cbfeaf 1401 put_page(e4b->bd_buddy_page);
eee4adc7 1402 }
eee4adc7
ES
1403}
1404
8a57d9d6
CW
1405/*
1406 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1407 * block group lock of all groups for this page; do not hold the BG lock when
1408 * calling this routine!
1409 */
b6a758ec 1410static noinline_for_stack
adb7ef60 1411int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
b6a758ec
AK
1412{
1413
b6a758ec 1414 struct ext4_group_info *this_grp;
2de8807b
AG
1415 struct ext4_buddy e4b;
1416 struct page *page;
1417 int ret = 0;
b6a758ec 1418
b10a44c3 1419 might_sleep();
d3df1453 1420 mb_debug(sb, "init group %u\n", group);
b6a758ec
AK
1421 this_grp = ext4_get_group_info(sb, group);
1422 /*
08c3a813
AK
1423 * This ensures that we don't reinit the buddy cache
1424 * page which map to the group from which we are already
1425 * allocating. If we are looking at the buddy cache we would
1426 * have taken a reference using ext4_mb_load_buddy and that
2de8807b 1427 * would have pinned buddy page to page cache.
2457aec6
MG
1428 * The call to ext4_mb_get_buddy_page_lock will mark the
1429 * page accessed.
b6a758ec 1430 */
adb7ef60 1431 ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
2de8807b 1432 if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
b6a758ec
AK
1433 /*
1434 * somebody initialized the group
1435 * return without doing anything
1436 */
b6a758ec
AK
1437 goto err;
1438 }
2de8807b
AG
1439
1440 page = e4b.bd_bitmap_page;
adb7ef60 1441 ret = ext4_mb_init_cache(page, NULL, gfp);
2de8807b
AG
1442 if (ret)
1443 goto err;
1444 if (!PageUptodate(page)) {
b6a758ec
AK
1445 ret = -EIO;
1446 goto err;
1447 }
b6a758ec 1448
2de8807b 1449 if (e4b.bd_buddy_page == NULL) {
b6a758ec
AK
1450 /*
1451 * If both the bitmap and buddy are in
1452 * the same page we don't need to force
1453 * init the buddy
1454 */
2de8807b
AG
1455 ret = 0;
1456 goto err;
b6a758ec 1457 }
2de8807b
AG
1458 /* init buddy cache */
1459 page = e4b.bd_buddy_page;
adb7ef60 1460 ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
2de8807b
AG
1461 if (ret)
1462 goto err;
1463 if (!PageUptodate(page)) {
b6a758ec
AK
1464 ret = -EIO;
1465 goto err;
1466 }
b6a758ec 1467err:
2de8807b 1468 ext4_mb_put_buddy_page_lock(&e4b);
b6a758ec
AK
1469 return ret;
1470}
1471
8a57d9d6
CW
1472/*
1473 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1474 * block group lock of all groups for this page; do not hold the BG lock when
1475 * calling this routine!
1476 */
4ddfef7b 1477static noinline_for_stack int
adb7ef60
KK
1478ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1479 struct ext4_buddy *e4b, gfp_t gfp)
c9de560d 1480{
c9de560d
AT
1481 int blocks_per_page;
1482 int block;
1483 int pnum;
1484 int poff;
1485 struct page *page;
fdf6c7a7 1486 int ret;
920313a7
AK
1487 struct ext4_group_info *grp;
1488 struct ext4_sb_info *sbi = EXT4_SB(sb);
1489 struct inode *inode = sbi->s_buddy_cache;
c9de560d 1490
b10a44c3 1491 might_sleep();
d3df1453 1492 mb_debug(sb, "load group %u\n", group);
c9de560d 1493
09cbfeaf 1494 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
920313a7 1495 grp = ext4_get_group_info(sb, group);
c9de560d
AT
1496
1497 e4b->bd_blkbits = sb->s_blocksize_bits;
529da704 1498 e4b->bd_info = grp;
c9de560d
AT
1499 e4b->bd_sb = sb;
1500 e4b->bd_group = group;
1501 e4b->bd_buddy_page = NULL;
1502 e4b->bd_bitmap_page = NULL;
1503
f41c0750 1504 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
f41c0750
AK
1505 /*
1506 * we need full data about the group
1507 * to make a good selection
1508 */
adb7ef60 1509 ret = ext4_mb_init_group(sb, group, gfp);
f41c0750
AK
1510 if (ret)
1511 return ret;
f41c0750
AK
1512 }
1513
c9de560d
AT
1514 /*
1515 * the buddy cache inode stores the block bitmap
1516 * and buddy information in consecutive blocks.
1517 * So for each group we need two blocks.
1518 */
1519 block = group * 2;
1520 pnum = block / blocks_per_page;
1521 poff = block % blocks_per_page;
1522
1523 /* we could use find_or_create_page(), but it locks page
1524 * what we'd like to avoid in fast path ... */
2457aec6 1525 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
c9de560d
AT
1526 if (page == NULL || !PageUptodate(page)) {
1527 if (page)
920313a7
AK
1528 /*
1529 * drop the page reference and try
1530 * to get the page with lock. If we
1531 * are not uptodate that implies
1532 * somebody just created the page but
1533 * is yet to initialize the same. So
1534 * wait for it to initialize.
1535 */
09cbfeaf 1536 put_page(page);
adb7ef60 1537 page = find_or_create_page(inode->i_mapping, pnum, gfp);
c9de560d
AT
1538 if (page) {
1539 BUG_ON(page->mapping != inode->i_mapping);
1540 if (!PageUptodate(page)) {
adb7ef60 1541 ret = ext4_mb_init_cache(page, NULL, gfp);
fdf6c7a7
SF
1542 if (ret) {
1543 unlock_page(page);
1544 goto err;
1545 }
c9de560d
AT
1546 mb_cmp_bitmaps(e4b, page_address(page) +
1547 (poff * sb->s_blocksize));
1548 }
1549 unlock_page(page);
1550 }
1551 }
c57ab39b
YL
1552 if (page == NULL) {
1553 ret = -ENOMEM;
1554 goto err;
1555 }
1556 if (!PageUptodate(page)) {
fdf6c7a7 1557 ret = -EIO;
c9de560d 1558 goto err;
fdf6c7a7 1559 }
2457aec6
MG
1560
1561 /* Pages marked accessed already */
c9de560d
AT
1562 e4b->bd_bitmap_page = page;
1563 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
c9de560d
AT
1564
1565 block++;
1566 pnum = block / blocks_per_page;
1567 poff = block % blocks_per_page;
1568
2457aec6 1569 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
c9de560d
AT
1570 if (page == NULL || !PageUptodate(page)) {
1571 if (page)
09cbfeaf 1572 put_page(page);
adb7ef60 1573 page = find_or_create_page(inode->i_mapping, pnum, gfp);
c9de560d
AT
1574 if (page) {
1575 BUG_ON(page->mapping != inode->i_mapping);
fdf6c7a7 1576 if (!PageUptodate(page)) {
adb7ef60
KK
1577 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1578 gfp);
fdf6c7a7
SF
1579 if (ret) {
1580 unlock_page(page);
1581 goto err;
1582 }
1583 }
c9de560d
AT
1584 unlock_page(page);
1585 }
1586 }
c57ab39b
YL
1587 if (page == NULL) {
1588 ret = -ENOMEM;
1589 goto err;
1590 }
1591 if (!PageUptodate(page)) {
fdf6c7a7 1592 ret = -EIO;
c9de560d 1593 goto err;
fdf6c7a7 1594 }
2457aec6
MG
1595
1596 /* Pages marked accessed already */
c9de560d
AT
1597 e4b->bd_buddy_page = page;
1598 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
c9de560d 1599
c9de560d
AT
1600 return 0;
1601
1602err:
26626f11 1603 if (page)
09cbfeaf 1604 put_page(page);
c9de560d 1605 if (e4b->bd_bitmap_page)
09cbfeaf 1606 put_page(e4b->bd_bitmap_page);
c9de560d 1607 if (e4b->bd_buddy_page)
09cbfeaf 1608 put_page(e4b->bd_buddy_page);
c9de560d
AT
1609 e4b->bd_buddy = NULL;
1610 e4b->bd_bitmap = NULL;
fdf6c7a7 1611 return ret;
c9de560d
AT
1612}
1613
adb7ef60
KK
1614static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1615 struct ext4_buddy *e4b)
1616{
1617 return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1618}
1619
e39e07fd 1620static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
c9de560d
AT
1621{
1622 if (e4b->bd_bitmap_page)
09cbfeaf 1623 put_page(e4b->bd_bitmap_page);
c9de560d 1624 if (e4b->bd_buddy_page)
09cbfeaf 1625 put_page(e4b->bd_buddy_page);
c9de560d
AT
1626}
1627
1628
1629static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1630{
ce3cca33 1631 int order = 1, max;
c9de560d
AT
1632 void *bb;
1633
c5e8f3f3 1634 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
c9de560d
AT
1635 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1636
c9de560d 1637 while (order <= e4b->bd_blkbits + 1) {
ce3cca33
CX
1638 bb = mb_find_buddy(e4b, order, &max);
1639 if (!mb_test_bit(block >> order, bb)) {
c9de560d
AT
1640 /* this block is part of buddy of order 'order' */
1641 return order;
1642 }
c9de560d
AT
1643 order++;
1644 }
1645 return 0;
1646}
1647
955ce5f5 1648static void mb_clear_bits(void *bm, int cur, int len)
c9de560d
AT
1649{
1650 __u32 *addr;
1651
1652 len = cur + len;
1653 while (cur < len) {
1654 if ((cur & 31) == 0 && (len - cur) >= 32) {
1655 /* fast path: clear whole word at once */
1656 addr = bm + (cur >> 3);
1657 *addr = 0;
1658 cur += 32;
1659 continue;
1660 }
955ce5f5 1661 mb_clear_bit(cur, bm);
c9de560d
AT
1662 cur++;
1663 }
1664}
1665
eabe0444
AS
1666/* clear bits in given range
1667 * will return first found zero bit if any, -1 otherwise
1668 */
1669static int mb_test_and_clear_bits(void *bm, int cur, int len)
1670{
1671 __u32 *addr;
1672 int zero_bit = -1;
1673
1674 len = cur + len;
1675 while (cur < len) {
1676 if ((cur & 31) == 0 && (len - cur) >= 32) {
1677 /* fast path: clear whole word at once */
1678 addr = bm + (cur >> 3);
1679 if (*addr != (__u32)(-1) && zero_bit == -1)
1680 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1681 *addr = 0;
1682 cur += 32;
1683 continue;
1684 }
1685 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1686 zero_bit = cur;
1687 cur++;
1688 }
1689
1690 return zero_bit;
1691}
1692
123e3016 1693void mb_set_bits(void *bm, int cur, int len)
c9de560d
AT
1694{
1695 __u32 *addr;
1696
1697 len = cur + len;
1698 while (cur < len) {
1699 if ((cur & 31) == 0 && (len - cur) >= 32) {
1700 /* fast path: set whole word at once */
1701 addr = bm + (cur >> 3);
1702 *addr = 0xffffffff;
1703 cur += 32;
1704 continue;
1705 }
955ce5f5 1706 mb_set_bit(cur, bm);
c9de560d
AT
1707 cur++;
1708 }
1709}
1710
eabe0444
AS
1711static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1712{
1713 if (mb_test_bit(*bit + side, bitmap)) {
1714 mb_clear_bit(*bit, bitmap);
1715 (*bit) -= side;
1716 return 1;
1717 }
1718 else {
1719 (*bit) += side;
1720 mb_set_bit(*bit, bitmap);
1721 return -1;
1722 }
1723}
1724
1725static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1726{
1727 int max;
1728 int order = 1;
1729 void *buddy = mb_find_buddy(e4b, order, &max);
1730
1731 while (buddy) {
1732 void *buddy2;
1733
1734 /* Bits in range [first; last] are known to be set since
1735 * corresponding blocks were allocated. Bits in range
1736 * (first; last) will stay set because they form buddies on
1737 * upper layer. We just deal with borders if they don't
1738 * align with upper layer and then go up.
1739 * Releasing entire group is all about clearing
1740 * single bit of highest order buddy.
1741 */
1742
1743 /* Example:
1744 * ---------------------------------
1745 * | 1 | 1 | 1 | 1 |
1746 * ---------------------------------
1747 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1748 * ---------------------------------
1749 * 0 1 2 3 4 5 6 7
1750 * \_____________________/
1751 *
1752 * Neither [1] nor [6] is aligned to above layer.
1753 * Left neighbour [0] is free, so mark it busy,
1754 * decrease bb_counters and extend range to
1755 * [0; 6]
1756 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1757 * mark [6] free, increase bb_counters and shrink range to
1758 * [0; 5].
1759 * Then shift range to [0; 2], go up and do the same.
1760 */
1761
1762
1763 if (first & 1)
1764 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1765 if (!(last & 1))
1766 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1767 if (first > last)
1768 break;
1769 order++;
1770
1771 if (first == last || !(buddy2 = mb_find_buddy(e4b, order, &max))) {
1772 mb_clear_bits(buddy, first, last - first + 1);
1773 e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1774 break;
1775 }
1776 first >>= 1;
1777 last >>= 1;
1778 buddy = buddy2;
1779 }
1780}
1781
7e5a8cdd 1782static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
eabe0444 1783 int first, int count)
c9de560d 1784{
eabe0444
AS
1785 int left_is_free = 0;
1786 int right_is_free = 0;
1787 int block;
1788 int last = first + count - 1;
c9de560d
AT
1789 struct super_block *sb = e4b->bd_sb;
1790
c99d1e6e
TT
1791 if (WARN_ON(count == 0))
1792 return;
eabe0444 1793 BUG_ON(last >= (sb->s_blocksize << 3));
bc8e6740 1794 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
163a203d
DW
1795 /* Don't bother if the block group is corrupt. */
1796 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1797 return;
1798
c9de560d
AT
1799 mb_check_buddy(e4b);
1800 mb_free_blocks_double(inode, e4b, first, count);
1801
07b5b8e1 1802 this_cpu_inc(discard_pa_seq);
c9de560d
AT
1803 e4b->bd_info->bb_free += count;
1804 if (first < e4b->bd_info->bb_first_free)
1805 e4b->bd_info->bb_first_free = first;
1806
eabe0444
AS
1807 /* access memory sequentially: check left neighbour,
1808 * clear range and then check right neighbour
1809 */
c9de560d 1810 if (first != 0)
eabe0444
AS
1811 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1812 block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1813 if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1814 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1815
1816 if (unlikely(block != -1)) {
e43bb4e6 1817 struct ext4_sb_info *sbi = EXT4_SB(sb);
eabe0444
AS
1818 ext4_fsblk_t blocknr;
1819
1820 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
49598e04 1821 blocknr += EXT4_C2B(sbi, block);
8016e29f
HS
1822 if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
1823 ext4_grp_locked_error(sb, e4b->bd_group,
1824 inode ? inode->i_ino : 0,
1825 blocknr,
1826 "freeing already freed block (bit %u); block bitmap corrupt.",
1827 block);
1828 ext4_mark_group_bitmap_corrupted(
1829 sb, e4b->bd_group,
db79e6d1 1830 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
8016e29f 1831 }
eabe0444
AS
1832 goto done;
1833 }
1834
1835 /* let's maintain fragments counter */
1836 if (left_is_free && right_is_free)
c9de560d 1837 e4b->bd_info->bb_fragments--;
eabe0444 1838 else if (!left_is_free && !right_is_free)
c9de560d
AT
1839 e4b->bd_info->bb_fragments++;
1840
eabe0444
AS
1841 /* buddy[0] == bd_bitmap is a special case, so handle
1842 * it right away and let mb_buddy_mark_free stay free of
1843 * zero order checks.
1844 * Check if neighbours are to be coaleasced,
1845 * adjust bitmap bb_counters and borders appropriately.
1846 */
1847 if (first & 1) {
1848 first += !left_is_free;
1849 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1850 }
1851 if (!(last & 1)) {
1852 last -= !right_is_free;
1853 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1854 }
c9de560d 1855
eabe0444
AS
1856 if (first <= last)
1857 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
c9de560d 1858
eabe0444 1859done:
8a57d9d6 1860 mb_set_largest_free_order(sb, e4b->bd_info);
196e402a 1861 mb_update_avg_fragment_size(sb, e4b->bd_info);
c9de560d 1862 mb_check_buddy(e4b);
c9de560d
AT
1863}
1864
15c006a2 1865static int mb_find_extent(struct ext4_buddy *e4b, int block,
c9de560d
AT
1866 int needed, struct ext4_free_extent *ex)
1867{
1868 int next = block;
15c006a2 1869 int max, order;
c9de560d
AT
1870 void *buddy;
1871
bc8e6740 1872 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
c9de560d
AT
1873 BUG_ON(ex == NULL);
1874
15c006a2 1875 buddy = mb_find_buddy(e4b, 0, &max);
c9de560d
AT
1876 BUG_ON(buddy == NULL);
1877 BUG_ON(block >= max);
1878 if (mb_test_bit(block, buddy)) {
1879 ex->fe_len = 0;
1880 ex->fe_start = 0;
1881 ex->fe_group = 0;
1882 return 0;
1883 }
1884
15c006a2
RD
1885 /* find actual order */
1886 order = mb_find_order_for_block(e4b, block);
1887 block = block >> order;
c9de560d
AT
1888
1889 ex->fe_len = 1 << order;
1890 ex->fe_start = block << order;
1891 ex->fe_group = e4b->bd_group;
1892
1893 /* calc difference from given start */
1894 next = next - ex->fe_start;
1895 ex->fe_len -= next;
1896 ex->fe_start += next;
1897
1898 while (needed > ex->fe_len &&
d8ec0c39 1899 mb_find_buddy(e4b, order, &max)) {
c9de560d
AT
1900
1901 if (block + 1 >= max)
1902 break;
1903
1904 next = (block + 1) * (1 << order);
c5e8f3f3 1905 if (mb_test_bit(next, e4b->bd_bitmap))
c9de560d
AT
1906 break;
1907
b051d8dc 1908 order = mb_find_order_for_block(e4b, next);
c9de560d 1909
c9de560d
AT
1910 block = next >> order;
1911 ex->fe_len += 1 << order;
1912 }
1913
31562b95 1914 if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
43c73221
TT
1915 /* Should never happen! (but apparently sometimes does?!?) */
1916 WARN_ON(1);
cd84bbba
SB
1917 ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
1918 "corruption or bug in mb_find_extent "
1919 "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
1920 block, order, needed, ex->fe_group, ex->fe_start,
1921 ex->fe_len, ex->fe_logical);
43c73221
TT
1922 ex->fe_len = 0;
1923 ex->fe_start = 0;
1924 ex->fe_group = 0;
1925 }
c9de560d
AT
1926 return ex->fe_len;
1927}
1928
1929static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1930{
1931 int ord;
1932 int mlen = 0;
1933 int max = 0;
1934 int cur;
1935 int start = ex->fe_start;
1936 int len = ex->fe_len;
1937 unsigned ret = 0;
1938 int len0 = len;
1939 void *buddy;
218a6944 1940 bool split = false;
c9de560d
AT
1941
1942 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1943 BUG_ON(e4b->bd_group != ex->fe_group);
bc8e6740 1944 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
c9de560d
AT
1945 mb_check_buddy(e4b);
1946 mb_mark_used_double(e4b, start, len);
1947
07b5b8e1 1948 this_cpu_inc(discard_pa_seq);
c9de560d
AT
1949 e4b->bd_info->bb_free -= len;
1950 if (e4b->bd_info->bb_first_free == start)
1951 e4b->bd_info->bb_first_free += len;
1952
1953 /* let's maintain fragments counter */
1954 if (start != 0)
c5e8f3f3 1955 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
c9de560d 1956 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
c5e8f3f3 1957 max = !mb_test_bit(start + len, e4b->bd_bitmap);
c9de560d
AT
1958 if (mlen && max)
1959 e4b->bd_info->bb_fragments++;
1960 else if (!mlen && !max)
1961 e4b->bd_info->bb_fragments--;
1962
1963 /* let's maintain buddy itself */
1964 while (len) {
218a6944 1965 if (!split)
1966 ord = mb_find_order_for_block(e4b, start);
c9de560d
AT
1967
1968 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1969 /* the whole chunk may be allocated at once! */
1970 mlen = 1 << ord;
218a6944 1971 if (!split)
1972 buddy = mb_find_buddy(e4b, ord, &max);
1973 else
1974 split = false;
c9de560d
AT
1975 BUG_ON((start >> ord) >= max);
1976 mb_set_bit(start >> ord, buddy);
1977 e4b->bd_info->bb_counters[ord]--;
1978 start += mlen;
1979 len -= mlen;
1980 BUG_ON(len < 0);
1981 continue;
1982 }
1983
1984 /* store for history */
1985 if (ret == 0)
1986 ret = len | (ord << 16);
1987
1988 /* we have to split large buddy */
1989 BUG_ON(ord <= 0);
1990 buddy = mb_find_buddy(e4b, ord, &max);
1991 mb_set_bit(start >> ord, buddy);
1992 e4b->bd_info->bb_counters[ord]--;
1993
1994 ord--;
1995 cur = (start >> ord) & ~1U;
1996 buddy = mb_find_buddy(e4b, ord, &max);
1997 mb_clear_bit(cur, buddy);
1998 mb_clear_bit(cur + 1, buddy);
1999 e4b->bd_info->bb_counters[ord]++;
2000 e4b->bd_info->bb_counters[ord]++;
218a6944 2001 split = true;
c9de560d 2002 }
8a57d9d6 2003 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
c9de560d 2004
196e402a 2005 mb_update_avg_fragment_size(e4b->bd_sb, e4b->bd_info);
123e3016 2006 mb_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
c9de560d
AT
2007 mb_check_buddy(e4b);
2008
2009 return ret;
2010}
2011
2012/*
2013 * Must be called under group lock!
2014 */
2015static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
2016 struct ext4_buddy *e4b)
2017{
2018 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2019 int ret;
2020
2021 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
2022 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2023
2024 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
2025 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
2026 ret = mb_mark_used(e4b, &ac->ac_b_ex);
2027
2028 /* preallocation can change ac_b_ex, thus we store actually
2029 * allocated blocks for history */
2030 ac->ac_f_ex = ac->ac_b_ex;
2031
2032 ac->ac_status = AC_STATUS_FOUND;
2033 ac->ac_tail = ret & 0xffff;
2034 ac->ac_buddy = ret >> 16;
2035
c3a326a6
AK
2036 /*
2037 * take the page reference. We want the page to be pinned
2038 * so that we don't get a ext4_mb_init_cache_call for this
2039 * group until we update the bitmap. That would mean we
2040 * double allocate blocks. The reference is dropped
2041 * in ext4_mb_release_context
2042 */
c9de560d
AT
2043 ac->ac_bitmap_page = e4b->bd_bitmap_page;
2044 get_page(ac->ac_bitmap_page);
2045 ac->ac_buddy_page = e4b->bd_buddy_page;
2046 get_page(ac->ac_buddy_page);
c9de560d 2047 /* store last allocated for subsequent stream allocation */
4ba74d00 2048 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
c9de560d
AT
2049 spin_lock(&sbi->s_md_lock);
2050 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
2051 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
2052 spin_unlock(&sbi->s_md_lock);
2053 }
53f86b17
RH
2054 /*
2055 * As we've just preallocated more space than
2056 * user requested originally, we store allocated
2057 * space in a special descriptor.
2058 */
2059 if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
2060 ext4_mb_new_preallocation(ac);
2061
c9de560d
AT
2062}
2063
c9de560d
AT
2064static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
2065 struct ext4_buddy *e4b,
2066 int finish_group)
2067{
2068 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2069 struct ext4_free_extent *bex = &ac->ac_b_ex;
2070 struct ext4_free_extent *gex = &ac->ac_g_ex;
2071 struct ext4_free_extent ex;
2072 int max;
2073
032115fc
AK
2074 if (ac->ac_status == AC_STATUS_FOUND)
2075 return;
c9de560d
AT
2076 /*
2077 * We don't want to scan for a whole year
2078 */
2079 if (ac->ac_found > sbi->s_mb_max_to_scan &&
2080 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2081 ac->ac_status = AC_STATUS_BREAK;
2082 return;
2083 }
2084
2085 /*
2086 * Haven't found good chunk so far, let's continue
2087 */
2088 if (bex->fe_len < gex->fe_len)
2089 return;
2090
2091 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
2092 && bex->fe_group == e4b->bd_group) {
2093 /* recheck chunk's availability - we don't know
2094 * when it was found (within this lock-unlock
2095 * period or not) */
15c006a2 2096 max = mb_find_extent(e4b, bex->fe_start, gex->fe_len, &ex);
c9de560d
AT
2097 if (max >= gex->fe_len) {
2098 ext4_mb_use_best_found(ac, e4b);
2099 return;
2100 }
2101 }
2102}
2103
2104/*
2105 * The routine checks whether found extent is good enough. If it is,
2106 * then the extent gets marked used and flag is set to the context
2107 * to stop scanning. Otherwise, the extent is compared with the
2108 * previous found extent and if new one is better, then it's stored
2109 * in the context. Later, the best found extent will be used, if
2110 * mballoc can't find good enough extent.
2111 *
2112 * FIXME: real allocation policy is to be designed yet!
2113 */
2114static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
2115 struct ext4_free_extent *ex,
2116 struct ext4_buddy *e4b)
2117{
2118 struct ext4_free_extent *bex = &ac->ac_b_ex;
2119 struct ext4_free_extent *gex = &ac->ac_g_ex;
2120
2121 BUG_ON(ex->fe_len <= 0);
7137d7a4
TT
2122 BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2123 BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
c9de560d
AT
2124 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
2125
2126 ac->ac_found++;
2127
2128 /*
2129 * The special case - take what you catch first
2130 */
2131 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2132 *bex = *ex;
2133 ext4_mb_use_best_found(ac, e4b);
2134 return;
2135 }
2136
2137 /*
2138 * Let's check whether the chuck is good enough
2139 */
2140 if (ex->fe_len == gex->fe_len) {
2141 *bex = *ex;
2142 ext4_mb_use_best_found(ac, e4b);
2143 return;
2144 }
2145
2146 /*
2147 * If this is first found extent, just store it in the context
2148 */
2149 if (bex->fe_len == 0) {
2150 *bex = *ex;
2151 return;
2152 }
2153
2154 /*
2155 * If new found extent is better, store it in the context
2156 */
2157 if (bex->fe_len < gex->fe_len) {
2158 /* if the request isn't satisfied, any found extent
2159 * larger than previous best one is better */
2160 if (ex->fe_len > bex->fe_len)
2161 *bex = *ex;
2162 } else if (ex->fe_len > gex->fe_len) {
2163 /* if the request is satisfied, then we try to find
2164 * an extent that still satisfy the request, but is
2165 * smaller than previous one */
2166 if (ex->fe_len < bex->fe_len)
2167 *bex = *ex;
2168 }
2169
2170 ext4_mb_check_limits(ac, e4b, 0);
2171}
2172
089ceecc
ES
2173static noinline_for_stack
2174int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
c9de560d
AT
2175 struct ext4_buddy *e4b)
2176{
2177 struct ext4_free_extent ex = ac->ac_b_ex;
2178 ext4_group_t group = ex.fe_group;
2179 int max;
2180 int err;
2181
2182 BUG_ON(ex.fe_len <= 0);
2183 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2184 if (err)
2185 return err;
2186
2187 ext4_lock_group(ac->ac_sb, group);
15c006a2 2188 max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
c9de560d
AT
2189
2190 if (max > 0) {
2191 ac->ac_b_ex = ex;
2192 ext4_mb_use_best_found(ac, e4b);
2193 }
2194
2195 ext4_unlock_group(ac->ac_sb, group);
e39e07fd 2196 ext4_mb_unload_buddy(e4b);
c9de560d
AT
2197
2198 return 0;
2199}
2200
089ceecc
ES
2201static noinline_for_stack
2202int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
c9de560d
AT
2203 struct ext4_buddy *e4b)
2204{
2205 ext4_group_t group = ac->ac_g_ex.fe_group;
2206 int max;
2207 int err;
2208 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
838cd0cf 2209 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
c9de560d
AT
2210 struct ext4_free_extent ex;
2211
2212 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
2213 return 0;
838cd0cf
YY
2214 if (grp->bb_free == 0)
2215 return 0;
c9de560d
AT
2216
2217 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2218 if (err)
2219 return err;
2220
163a203d
DW
2221 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
2222 ext4_mb_unload_buddy(e4b);
2223 return 0;
2224 }
2225
c9de560d 2226 ext4_lock_group(ac->ac_sb, group);
15c006a2 2227 max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
c9de560d 2228 ac->ac_g_ex.fe_len, &ex);
ab0c00fc 2229 ex.fe_logical = 0xDEADFA11; /* debug value */
c9de560d
AT
2230
2231 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
2232 ext4_fsblk_t start;
2233
5661bd68
AM
2234 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
2235 ex.fe_start;
c9de560d
AT
2236 /* use do_div to get remainder (would be 64-bit modulo) */
2237 if (do_div(start, sbi->s_stripe) == 0) {
2238 ac->ac_found++;
2239 ac->ac_b_ex = ex;
2240 ext4_mb_use_best_found(ac, e4b);
2241 }
2242 } else if (max >= ac->ac_g_ex.fe_len) {
2243 BUG_ON(ex.fe_len <= 0);
2244 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2245 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2246 ac->ac_found++;
2247 ac->ac_b_ex = ex;
2248 ext4_mb_use_best_found(ac, e4b);
2249 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
2250 /* Sometimes, caller may want to merge even small
2251 * number of blocks to an existing extent */
2252 BUG_ON(ex.fe_len <= 0);
2253 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2254 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2255 ac->ac_found++;
2256 ac->ac_b_ex = ex;
2257 ext4_mb_use_best_found(ac, e4b);
2258 }
2259 ext4_unlock_group(ac->ac_sb, group);
e39e07fd 2260 ext4_mb_unload_buddy(e4b);
c9de560d
AT
2261
2262 return 0;
2263}
2264
2265/*
2266 * The routine scans buddy structures (not bitmap!) from given order
2267 * to max order and tries to find big enough chunk to satisfy the req
2268 */
089ceecc
ES
2269static noinline_for_stack
2270void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
c9de560d
AT
2271 struct ext4_buddy *e4b)
2272{
2273 struct super_block *sb = ac->ac_sb;
2274 struct ext4_group_info *grp = e4b->bd_info;
2275 void *buddy;
2276 int i;
2277 int k;
2278 int max;
2279
2280 BUG_ON(ac->ac_2order <= 0);
4b68f6df 2281 for (i = ac->ac_2order; i < MB_NUM_ORDERS(sb); i++) {
c9de560d
AT
2282 if (grp->bb_counters[i] == 0)
2283 continue;
2284
2285 buddy = mb_find_buddy(e4b, i, &max);
2286 BUG_ON(buddy == NULL);
2287
ffad0a44 2288 k = mb_find_next_zero_bit(buddy, max, 0);
eb576086
DM
2289 if (k >= max) {
2290 ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
2291 "%d free clusters of order %d. But found 0",
2292 grp->bb_counters[i], i);
2293 ext4_mark_group_bitmap_corrupted(ac->ac_sb,
2294 e4b->bd_group,
2295 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2296 break;
2297 }
c9de560d
AT
2298 ac->ac_found++;
2299
2300 ac->ac_b_ex.fe_len = 1 << i;
2301 ac->ac_b_ex.fe_start = k << i;
2302 ac->ac_b_ex.fe_group = e4b->bd_group;
2303
2304 ext4_mb_use_best_found(ac, e4b);
2305
53f86b17 2306 BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
c9de560d
AT
2307
2308 if (EXT4_SB(sb)->s_mb_stats)
2309 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
2310
2311 break;
2312 }
2313}
2314
2315/*
2316 * The routine scans the group and measures all found extents.
2317 * In order to optimize scanning, caller must pass number of
2318 * free blocks in the group, so the routine can know upper limit.
2319 */
089ceecc
ES
2320static noinline_for_stack
2321void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
c9de560d
AT
2322 struct ext4_buddy *e4b)
2323{
2324 struct super_block *sb = ac->ac_sb;
c5e8f3f3 2325 void *bitmap = e4b->bd_bitmap;
c9de560d
AT
2326 struct ext4_free_extent ex;
2327 int i;
2328 int free;
2329
2330 free = e4b->bd_info->bb_free;
907ea529
TT
2331 if (WARN_ON(free <= 0))
2332 return;
c9de560d
AT
2333
2334 i = e4b->bd_info->bb_first_free;
2335
2336 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
ffad0a44 2337 i = mb_find_next_zero_bit(bitmap,
7137d7a4
TT
2338 EXT4_CLUSTERS_PER_GROUP(sb), i);
2339 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
26346ff6 2340 /*
e56eb659 2341 * IF we have corrupt bitmap, we won't find any
26346ff6 2342 * free blocks even though group info says we
b483bb77 2343 * have free blocks
26346ff6 2344 */
e29136f8 2345 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
53accfa9 2346 "%d free clusters as per "
fde4d95a 2347 "group info. But bitmap says 0",
26346ff6 2348 free);
736dedbb
WS
2349 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2350 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
c9de560d
AT
2351 break;
2352 }
2353
15c006a2 2354 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
907ea529
TT
2355 if (WARN_ON(ex.fe_len <= 0))
2356 break;
26346ff6 2357 if (free < ex.fe_len) {
e29136f8 2358 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
53accfa9 2359 "%d free clusters as per "
fde4d95a 2360 "group info. But got %d blocks",
26346ff6 2361 free, ex.fe_len);
736dedbb
WS
2362 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2363 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
e56eb659
AK
2364 /*
2365 * The number of free blocks differs. This mostly
2366 * indicate that the bitmap is corrupt. So exit
2367 * without claiming the space.
2368 */
2369 break;
26346ff6 2370 }
ab0c00fc 2371 ex.fe_logical = 0xDEADC0DE; /* debug value */
c9de560d
AT
2372 ext4_mb_measure_extent(ac, &ex, e4b);
2373
2374 i += ex.fe_len;
2375 free -= ex.fe_len;
2376 }
2377
2378 ext4_mb_check_limits(ac, e4b, 1);
2379}
2380
2381/*
2382 * This is a special case for storages like raid5
506bf2d8 2383 * we try to find stripe-aligned chunks for stripe-size-multiple requests
c9de560d 2384 */
089ceecc
ES
2385static noinline_for_stack
2386void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
c9de560d
AT
2387 struct ext4_buddy *e4b)
2388{
2389 struct super_block *sb = ac->ac_sb;
2390 struct ext4_sb_info *sbi = EXT4_SB(sb);
c5e8f3f3 2391 void *bitmap = e4b->bd_bitmap;
c9de560d
AT
2392 struct ext4_free_extent ex;
2393 ext4_fsblk_t first_group_block;
2394 ext4_fsblk_t a;
2395 ext4_grpblk_t i;
2396 int max;
2397
2398 BUG_ON(sbi->s_stripe == 0);
2399
2400 /* find first stripe-aligned block in group */
5661bd68
AM
2401 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2402
c9de560d
AT
2403 a = first_group_block + sbi->s_stripe - 1;
2404 do_div(a, sbi->s_stripe);
2405 i = (a * sbi->s_stripe) - first_group_block;
2406
7137d7a4 2407 while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
c9de560d 2408 if (!mb_test_bit(i, bitmap)) {
15c006a2 2409 max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
c9de560d
AT
2410 if (max >= sbi->s_stripe) {
2411 ac->ac_found++;
ab0c00fc 2412 ex.fe_logical = 0xDEADF00D; /* debug value */
c9de560d
AT
2413 ac->ac_b_ex = ex;
2414 ext4_mb_use_best_found(ac, e4b);
2415 break;
2416 }
2417 }
2418 i += sbi->s_stripe;
2419 }
2420}
2421
42ac1848 2422/*
8ef123fe 2423 * This is also called BEFORE we load the buddy bitmap.
42ac1848 2424 * Returns either 1 or 0 indicating that the group is either suitable
8ef123fe 2425 * for the allocation or not.
42ac1848 2426 */
8ef123fe 2427static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
c9de560d
AT
2428 ext4_group_t group, int cr)
2429{
8ef123fe 2430 ext4_grpblk_t free, fragments;
a4912123 2431 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
c9de560d
AT
2432 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2433
2434 BUG_ON(cr < 0 || cr >= 4);
8a57d9d6 2435
dddcd2f9 2436 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
8ef123fe 2437 return false;
01fc48e8 2438
dddcd2f9 2439 free = grp->bb_free;
2440 if (free == 0)
8ef123fe 2441 return false;
c9de560d 2442
c9de560d 2443 fragments = grp->bb_fragments;
c9de560d 2444 if (fragments == 0)
8ef123fe 2445 return false;
c9de560d
AT
2446
2447 switch (cr) {
2448 case 0:
2449 BUG_ON(ac->ac_2order == 0);
c9de560d 2450
a4912123
TT
2451 /* Avoid using the first bg of a flexgroup for data files */
2452 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2453 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2454 ((group % flex_size) == 0))
8ef123fe 2455 return false;
a4912123 2456
dddcd2f9 2457 if (free < ac->ac_g_ex.fe_len)
2458 return false;
2459
4b68f6df 2460 if (ac->ac_2order >= MB_NUM_ORDERS(ac->ac_sb))
8ef123fe 2461 return true;
40ae3487
TT
2462
2463 if (grp->bb_largest_free_order < ac->ac_2order)
8ef123fe 2464 return false;
40ae3487 2465
8ef123fe 2466 return true;
c9de560d
AT
2467 case 1:
2468 if ((free / fragments) >= ac->ac_g_ex.fe_len)
8ef123fe 2469 return true;
c9de560d
AT
2470 break;
2471 case 2:
2472 if (free >= ac->ac_g_ex.fe_len)
8ef123fe 2473 return true;
c9de560d
AT
2474 break;
2475 case 3:
8ef123fe 2476 return true;
c9de560d
AT
2477 default:
2478 BUG();
2479 }
2480
8ef123fe
RH
2481 return false;
2482}
2483
2484/*
2485 * This could return negative error code if something goes wrong
2486 * during ext4_mb_init_group(). This should not be called with
2487 * ext4_lock_group() held.
a5fda113
TT
2488 *
2489 * Note: because we are conditionally operating with the group lock in
2490 * the EXT4_MB_STRICT_CHECK case, we need to fake out sparse in this
2491 * function using __acquire and __release. This means we need to be
2492 * super careful before messing with the error path handling via "goto
2493 * out"!
8ef123fe
RH
2494 */
2495static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
2496 ext4_group_t group, int cr)
2497{
2498 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
99377830 2499 struct super_block *sb = ac->ac_sb;
c1d2c7d4 2500 struct ext4_sb_info *sbi = EXT4_SB(sb);
99377830 2501 bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
8ef123fe
RH
2502 ext4_grpblk_t free;
2503 int ret = 0;
2504
a6c75eaf
HS
2505 if (sbi->s_mb_stats)
2506 atomic64_inc(&sbi->s_bal_cX_groups_considered[ac->ac_criteria]);
a5fda113 2507 if (should_lock) {
99377830 2508 ext4_lock_group(sb, group);
a5fda113
TT
2509 __release(ext4_group_lock_ptr(sb, group));
2510 }
8ef123fe
RH
2511 free = grp->bb_free;
2512 if (free == 0)
2513 goto out;
2514 if (cr <= 2 && free < ac->ac_g_ex.fe_len)
2515 goto out;
2516 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2517 goto out;
a5fda113
TT
2518 if (should_lock) {
2519 __acquire(ext4_group_lock_ptr(sb, group));
99377830 2520 ext4_unlock_group(sb, group);
a5fda113 2521 }
8ef123fe
RH
2522
2523 /* We only do this if the grp has never been initialized */
2524 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
c1d2c7d4
AZ
2525 struct ext4_group_desc *gdp =
2526 ext4_get_group_desc(sb, group, NULL);
2527 int ret;
2528
2529 /* cr=0/1 is a very optimistic search to find large
2530 * good chunks almost for free. If buddy data is not
2531 * ready, then this optimization makes no sense. But
2532 * we never skip the first block group in a flex_bg,
2533 * since this gets used for metadata block allocation,
2534 * and we want to make sure we locate metadata blocks
2535 * in the first block group in the flex_bg if possible.
2536 */
2537 if (cr < 2 &&
2538 (!sbi->s_log_groups_per_flex ||
2539 ((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
2540 !(ext4_has_group_desc_csum(sb) &&
2541 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
2542 return 0;
2543 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
8ef123fe
RH
2544 if (ret)
2545 return ret;
2546 }
2547
a5fda113 2548 if (should_lock) {
99377830 2549 ext4_lock_group(sb, group);
a5fda113
TT
2550 __release(ext4_group_lock_ptr(sb, group));
2551 }
8ef123fe
RH
2552 ret = ext4_mb_good_group(ac, group, cr);
2553out:
a5fda113
TT
2554 if (should_lock) {
2555 __acquire(ext4_group_lock_ptr(sb, group));
99377830 2556 ext4_unlock_group(sb, group);
a5fda113 2557 }
8ef123fe 2558 return ret;
c9de560d
AT
2559}
2560
cfd73237
AZ
2561/*
2562 * Start prefetching @nr block bitmaps starting at @group.
2563 * Return the next group which needs to be prefetched.
2564 */
3d392b26
TT
2565ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
2566 unsigned int nr, int *cnt)
cfd73237
AZ
2567{
2568 ext4_group_t ngroups = ext4_get_groups_count(sb);
2569 struct buffer_head *bh;
2570 struct blk_plug plug;
2571
2572 blk_start_plug(&plug);
2573 while (nr-- > 0) {
2574 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2575 NULL);
2576 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2577
2578 /*
2579 * Prefetch block groups with free blocks; but don't
2580 * bother if it is marked uninitialized on disk, since
2581 * it won't require I/O to read. Also only try to
2582 * prefetch once, so we avoid getblk() call, which can
2583 * be expensive.
2584 */
2585 if (!EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
2586 EXT4_MB_GRP_NEED_INIT(grp) &&
2587 ext4_free_group_clusters(sb, gdp) > 0 &&
2588 !(ext4_has_group_desc_csum(sb) &&
2589 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)))) {
2590 bh = ext4_read_block_bitmap_nowait(sb, group, true);
2591 if (bh && !IS_ERR(bh)) {
2592 if (!buffer_uptodate(bh) && cnt)
2593 (*cnt)++;
2594 brelse(bh);
2595 }
2596 }
2597 if (++group >= ngroups)
2598 group = 0;
2599 }
2600 blk_finish_plug(&plug);
2601 return group;
2602}
2603
2604/*
2605 * Prefetching reads the block bitmap into the buffer cache; but we
2606 * need to make sure that the buddy bitmap in the page cache has been
2607 * initialized. Note that ext4_mb_init_group() will block if the I/O
2608 * is not yet completed, or indeed if it was not initiated by
2609 * ext4_mb_prefetch did not start the I/O.
2610 *
2611 * TODO: We should actually kick off the buddy bitmap setup in a work
2612 * queue when the buffer I/O is completed, so that we don't block
2613 * waiting for the block allocation bitmap read to finish when
2614 * ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
2615 */
3d392b26
TT
2616void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
2617 unsigned int nr)
cfd73237
AZ
2618{
2619 while (nr-- > 0) {
2620 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2621 NULL);
2622 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2623
2624 if (!group)
2625 group = ext4_get_groups_count(sb);
2626 group--;
2627 grp = ext4_get_group_info(sb, group);
2628
2629 if (EXT4_MB_GRP_NEED_INIT(grp) &&
2630 ext4_free_group_clusters(sb, gdp) > 0 &&
2631 !(ext4_has_group_desc_csum(sb) &&
2632 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)))) {
2633 if (ext4_mb_init_group(sb, group, GFP_NOFS))
2634 break;
2635 }
2636 }
2637}
2638
4ddfef7b
ES
2639static noinline_for_stack int
2640ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
c9de560d 2641{
cfd73237 2642 ext4_group_t prefetch_grp = 0, ngroups, group, i;
4fca50d4 2643 int cr = -1, new_cr;
42ac1848 2644 int err = 0, first_err = 0;
cfd73237 2645 unsigned int nr = 0, prefetch_ios = 0;
c9de560d
AT
2646 struct ext4_sb_info *sbi;
2647 struct super_block *sb;
2648 struct ext4_buddy e4b;
66d5e027 2649 int lost;
c9de560d
AT
2650
2651 sb = ac->ac_sb;
2652 sbi = EXT4_SB(sb);
8df9675f 2653 ngroups = ext4_get_groups_count(sb);
fb0a387d 2654 /* non-extent files are limited to low blocks/groups */
12e9b892 2655 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
fb0a387d
ES
2656 ngroups = sbi->s_blockfile_groups;
2657
c9de560d
AT
2658 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2659
2660 /* first, try the goal */
2661 err = ext4_mb_find_by_goal(ac, &e4b);
2662 if (err || ac->ac_status == AC_STATUS_FOUND)
2663 goto out;
2664
2665 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2666 goto out;
2667
2668 /*
e9a3cd48 2669 * ac->ac_2order is set only if the fe_len is a power of 2
2670 * if ac->ac_2order is set we also set criteria to 0 so that we
c9de560d
AT
2671 * try exact allocation using buddy.
2672 */
2673 i = fls(ac->ac_g_ex.fe_len);
2674 ac->ac_2order = 0;
2675 /*
2676 * We search using buddy data only if the order of the request
2677 * is greater than equal to the sbi_s_mb_order2_reqs
b713a5ec 2678 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
d9b22cf9
JK
2679 * We also support searching for power-of-two requests only for
2680 * requests upto maximum buddy size we have constructed.
c9de560d 2681 */
4b68f6df 2682 if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) {
c9de560d
AT
2683 /*
2684 * This should tell if fe_len is exactly power of 2
2685 */
2686 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
1a5d5e5d 2687 ac->ac_2order = array_index_nospec(i - 1,
4b68f6df 2688 MB_NUM_ORDERS(sb));
c9de560d
AT
2689 }
2690
4ba74d00
TT
2691 /* if stream allocation is enabled, use global goal */
2692 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
c9de560d
AT
2693 /* TBD: may be hot point */
2694 spin_lock(&sbi->s_md_lock);
2695 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2696 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2697 spin_unlock(&sbi->s_md_lock);
2698 }
4ba74d00 2699
c9de560d
AT
2700 /* Let's just scan groups to find more-less suitable blocks */
2701 cr = ac->ac_2order ? 0 : 1;
2702 /*
2703 * cr == 0 try to get exact allocation,
2704 * cr == 3 try to get anything
2705 */
2706repeat:
2707 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2708 ac->ac_criteria = cr;
ed8f9c75
AK
2709 /*
2710 * searching for the right group start
2711 * from the goal value specified
2712 */
2713 group = ac->ac_g_ex.fe_group;
196e402a
HS
2714 ac->ac_last_optimal_group = group;
2715 ac->ac_groups_linear_remaining = sbi->s_mb_max_linear_groups;
cfd73237 2716 prefetch_grp = group;
ed8f9c75 2717
4fca50d4
JK
2718 for (i = 0, new_cr = cr; i < ngroups; i++,
2719 ext4_mb_choose_next_group(ac, &new_cr, &group, ngroups)) {
2720 int ret = 0;
196e402a 2721
2ed5724d 2722 cond_resched();
196e402a
HS
2723 if (new_cr != cr) {
2724 cr = new_cr;
2725 goto repeat;
2726 }
c9de560d 2727
cfd73237
AZ
2728 /*
2729 * Batch reads of the block allocation bitmaps
2730 * to get multiple READs in flight; limit
2731 * prefetching at cr=0/1, otherwise mballoc can
2732 * spend a lot of time loading imperfect groups
2733 */
2734 if ((prefetch_grp == group) &&
2735 (cr > 1 ||
2736 prefetch_ios < sbi->s_mb_prefetch_limit)) {
2737 unsigned int curr_ios = prefetch_ios;
2738
2739 nr = sbi->s_mb_prefetch;
2740 if (ext4_has_feature_flex_bg(sb)) {
82ef1370
CX
2741 nr = 1 << sbi->s_log_groups_per_flex;
2742 nr -= group & (nr - 1);
2743 nr = min(nr, sbi->s_mb_prefetch);
cfd73237
AZ
2744 }
2745 prefetch_grp = ext4_mb_prefetch(sb, group,
2746 nr, &prefetch_ios);
2747 if (prefetch_ios == curr_ios)
2748 nr = 0;
2749 }
2750
8a57d9d6 2751 /* This now checks without needing the buddy page */
8ef123fe 2752 ret = ext4_mb_good_group_nolock(ac, group, cr);
42ac1848
LC
2753 if (ret <= 0) {
2754 if (!first_err)
2755 first_err = ret;
c9de560d 2756 continue;
42ac1848 2757 }
c9de560d 2758
c9de560d
AT
2759 err = ext4_mb_load_buddy(sb, group, &e4b);
2760 if (err)
2761 goto out;
2762
2763 ext4_lock_group(sb, group);
8a57d9d6
CW
2764
2765 /*
2766 * We need to check again after locking the
2767 * block group
2768 */
42ac1848 2769 ret = ext4_mb_good_group(ac, group, cr);
8ef123fe 2770 if (ret == 0) {
c9de560d 2771 ext4_unlock_group(sb, group);
e39e07fd 2772 ext4_mb_unload_buddy(&e4b);
c9de560d
AT
2773 continue;
2774 }
2775
2776 ac->ac_groups_scanned++;
d9b22cf9 2777 if (cr == 0)
c9de560d 2778 ext4_mb_simple_scan_group(ac, &e4b);
506bf2d8
ES
2779 else if (cr == 1 && sbi->s_stripe &&
2780 !(ac->ac_g_ex.fe_len % sbi->s_stripe))
c9de560d
AT
2781 ext4_mb_scan_aligned(ac, &e4b);
2782 else
2783 ext4_mb_complex_scan_group(ac, &e4b);
2784
2785 ext4_unlock_group(sb, group);
e39e07fd 2786 ext4_mb_unload_buddy(&e4b);
c9de560d
AT
2787
2788 if (ac->ac_status != AC_STATUS_CONTINUE)
2789 break;
2790 }
a6c75eaf
HS
2791 /* Processed all groups and haven't found blocks */
2792 if (sbi->s_mb_stats && i == ngroups)
2793 atomic64_inc(&sbi->s_bal_cX_failed[cr]);
c9de560d
AT
2794 }
2795
2796 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2797 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2798 /*
2799 * We've been searching too long. Let's try to allocate
2800 * the best chunk we've found so far
2801 */
c9de560d
AT
2802 ext4_mb_try_best_found(ac, &e4b);
2803 if (ac->ac_status != AC_STATUS_FOUND) {
2804 /*
2805 * Someone more lucky has already allocated it.
2806 * The only thing we can do is just take first
2807 * found block(s)
c9de560d 2808 */
66d5e027 2809 lost = atomic_inc_return(&sbi->s_mb_lost_chunks);
2810 mb_debug(sb, "lost chunk, group: %u, start: %d, len: %d, lost: %d\n",
c55ee7d2 2811 ac->ac_b_ex.fe_group, ac->ac_b_ex.fe_start,
2812 ac->ac_b_ex.fe_len, lost);
2813
c9de560d
AT
2814 ac->ac_b_ex.fe_group = 0;
2815 ac->ac_b_ex.fe_start = 0;
2816 ac->ac_b_ex.fe_len = 0;
2817 ac->ac_status = AC_STATUS_CONTINUE;
2818 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2819 cr = 3;
c9de560d
AT
2820 goto repeat;
2821 }
2822 }
a6c75eaf
HS
2823
2824 if (sbi->s_mb_stats && ac->ac_status == AC_STATUS_FOUND)
2825 atomic64_inc(&sbi->s_bal_cX_hits[ac->ac_criteria]);
c9de560d 2826out:
42ac1848
LC
2827 if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2828 err = first_err;
bbc4ec77 2829
d3df1453 2830 mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
bbc4ec77
RH
2831 ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
2832 ac->ac_flags, cr, err);
cfd73237
AZ
2833
2834 if (nr)
2835 ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
2836
c9de560d
AT
2837 return err;
2838}
2839
c9de560d
AT
2840static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2841{
359745d7 2842 struct super_block *sb = pde_data(file_inode(seq->file));
c9de560d
AT
2843 ext4_group_t group;
2844
8df9675f 2845 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
c9de560d 2846 return NULL;
c9de560d 2847 group = *pos + 1;
a9df9a49 2848 return (void *) ((unsigned long) group);
c9de560d
AT
2849}
2850
2851static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2852{
359745d7 2853 struct super_block *sb = pde_data(file_inode(seq->file));
c9de560d
AT
2854 ext4_group_t group;
2855
2856 ++*pos;
8df9675f 2857 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
c9de560d
AT
2858 return NULL;
2859 group = *pos + 1;
a9df9a49 2860 return (void *) ((unsigned long) group);
c9de560d
AT
2861}
2862
2863static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2864{
359745d7 2865 struct super_block *sb = pde_data(file_inode(seq->file));
a9df9a49 2866 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
c9de560d 2867 int i;
1c8457ca 2868 int err, buddy_loaded = 0;
c9de560d 2869 struct ext4_buddy e4b;
1c8457ca 2870 struct ext4_group_info *grinfo;
2df2c340
AB
2871 unsigned char blocksize_bits = min_t(unsigned char,
2872 sb->s_blocksize_bits,
2873 EXT4_MAX_BLOCK_LOG_SIZE);
c9de560d
AT
2874 struct sg {
2875 struct ext4_group_info info;
b80b32b6 2876 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
c9de560d
AT
2877 } sg;
2878
2879 group--;
2880 if (group == 0)
97b4af2f
RV
2881 seq_puts(seq, "#group: free frags first ["
2882 " 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
802cf1f9 2883 " 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
c9de560d 2884
b80b32b6
TT
2885 i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2886 sizeof(struct ext4_group_info);
2887
1c8457ca
AK
2888 grinfo = ext4_get_group_info(sb, group);
2889 /* Load the group info in memory only if not already loaded. */
2890 if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
2891 err = ext4_mb_load_buddy(sb, group, &e4b);
2892 if (err) {
2893 seq_printf(seq, "#%-5u: I/O error\n", group);
2894 return 0;
2895 }
2896 buddy_loaded = 1;
c9de560d 2897 }
1c8457ca 2898
b80b32b6 2899 memcpy(&sg, ext4_get_group_info(sb, group), i);
1c8457ca
AK
2900
2901 if (buddy_loaded)
2902 ext4_mb_unload_buddy(&e4b);
c9de560d 2903
a9df9a49 2904 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
c9de560d
AT
2905 sg.info.bb_fragments, sg.info.bb_first_free);
2906 for (i = 0; i <= 13; i++)
2df2c340 2907 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
c9de560d 2908 sg.info.bb_counters[i] : 0);
e0d438c7 2909 seq_puts(seq, " ]\n");
c9de560d
AT
2910
2911 return 0;
2912}
2913
2914static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2915{
2916}
2917
247dbed8 2918const struct seq_operations ext4_mb_seq_groups_ops = {
c9de560d
AT
2919 .start = ext4_mb_seq_groups_start,
2920 .next = ext4_mb_seq_groups_next,
2921 .stop = ext4_mb_seq_groups_stop,
2922 .show = ext4_mb_seq_groups_show,
2923};
2924
a6c75eaf
HS
2925int ext4_seq_mb_stats_show(struct seq_file *seq, void *offset)
2926{
c30365b9 2927 struct super_block *sb = seq->private;
a6c75eaf
HS
2928 struct ext4_sb_info *sbi = EXT4_SB(sb);
2929
2930 seq_puts(seq, "mballoc:\n");
2931 if (!sbi->s_mb_stats) {
2932 seq_puts(seq, "\tmb stats collection turned off.\n");
2933 seq_puts(seq, "\tTo enable, please write \"1\" to sysfs file mb_stats.\n");
2934 return 0;
2935 }
2936 seq_printf(seq, "\treqs: %u\n", atomic_read(&sbi->s_bal_reqs));
2937 seq_printf(seq, "\tsuccess: %u\n", atomic_read(&sbi->s_bal_success));
2938
2939 seq_printf(seq, "\tgroups_scanned: %u\n", atomic_read(&sbi->s_bal_groups_scanned));
2940
2941 seq_puts(seq, "\tcr0_stats:\n");
2942 seq_printf(seq, "\t\thits: %llu\n", atomic64_read(&sbi->s_bal_cX_hits[0]));
2943 seq_printf(seq, "\t\tgroups_considered: %llu\n",
2944 atomic64_read(&sbi->s_bal_cX_groups_considered[0]));
2945 seq_printf(seq, "\t\tuseless_loops: %llu\n",
2946 atomic64_read(&sbi->s_bal_cX_failed[0]));
196e402a
HS
2947 seq_printf(seq, "\t\tbad_suggestions: %u\n",
2948 atomic_read(&sbi->s_bal_cr0_bad_suggestions));
a6c75eaf
HS
2949
2950 seq_puts(seq, "\tcr1_stats:\n");
2951 seq_printf(seq, "\t\thits: %llu\n", atomic64_read(&sbi->s_bal_cX_hits[1]));
2952 seq_printf(seq, "\t\tgroups_considered: %llu\n",
2953 atomic64_read(&sbi->s_bal_cX_groups_considered[1]));
2954 seq_printf(seq, "\t\tuseless_loops: %llu\n",
2955 atomic64_read(&sbi->s_bal_cX_failed[1]));
196e402a
HS
2956 seq_printf(seq, "\t\tbad_suggestions: %u\n",
2957 atomic_read(&sbi->s_bal_cr1_bad_suggestions));
a6c75eaf
HS
2958
2959 seq_puts(seq, "\tcr2_stats:\n");
2960 seq_printf(seq, "\t\thits: %llu\n", atomic64_read(&sbi->s_bal_cX_hits[2]));
2961 seq_printf(seq, "\t\tgroups_considered: %llu\n",
2962 atomic64_read(&sbi->s_bal_cX_groups_considered[2]));
2963 seq_printf(seq, "\t\tuseless_loops: %llu\n",
2964 atomic64_read(&sbi->s_bal_cX_failed[2]));
2965
2966 seq_puts(seq, "\tcr3_stats:\n");
2967 seq_printf(seq, "\t\thits: %llu\n", atomic64_read(&sbi->s_bal_cX_hits[3]));
2968 seq_printf(seq, "\t\tgroups_considered: %llu\n",
2969 atomic64_read(&sbi->s_bal_cX_groups_considered[3]));
2970 seq_printf(seq, "\t\tuseless_loops: %llu\n",
2971 atomic64_read(&sbi->s_bal_cX_failed[3]));
2972 seq_printf(seq, "\textents_scanned: %u\n", atomic_read(&sbi->s_bal_ex_scanned));
2973 seq_printf(seq, "\t\tgoal_hits: %u\n", atomic_read(&sbi->s_bal_goals));
2974 seq_printf(seq, "\t\t2^n_hits: %u\n", atomic_read(&sbi->s_bal_2orders));
2975 seq_printf(seq, "\t\tbreaks: %u\n", atomic_read(&sbi->s_bal_breaks));
2976 seq_printf(seq, "\t\tlost: %u\n", atomic_read(&sbi->s_mb_lost_chunks));
2977
2978 seq_printf(seq, "\tbuddies_generated: %u/%u\n",
2979 atomic_read(&sbi->s_mb_buddies_generated),
2980 ext4_get_groups_count(sb));
2981 seq_printf(seq, "\tbuddies_time_used: %llu\n",
2982 atomic64_read(&sbi->s_mb_generation_time));
2983 seq_printf(seq, "\tpreallocated: %u\n",
2984 atomic_read(&sbi->s_mb_preallocated));
2985 seq_printf(seq, "\tdiscarded: %u\n",
2986 atomic_read(&sbi->s_mb_discarded));
2987 return 0;
2988}
2989
f68f4063 2990static void *ext4_mb_seq_structs_summary_start(struct seq_file *seq, loff_t *pos)
a5fda113 2991__acquires(&EXT4_SB(sb)->s_mb_rb_lock)
f68f4063 2992{
359745d7 2993 struct super_block *sb = pde_data(file_inode(seq->file));
f68f4063
HS
2994 unsigned long position;
2995
2996 read_lock(&EXT4_SB(sb)->s_mb_rb_lock);
2997
2998 if (*pos < 0 || *pos >= MB_NUM_ORDERS(sb) + 1)
2999 return NULL;
3000 position = *pos + 1;
3001 return (void *) ((unsigned long) position);
3002}
3003
3004static void *ext4_mb_seq_structs_summary_next(struct seq_file *seq, void *v, loff_t *pos)
3005{
359745d7 3006 struct super_block *sb = pde_data(file_inode(seq->file));
f68f4063
HS
3007 unsigned long position;
3008
3009 ++*pos;
3010 if (*pos < 0 || *pos >= MB_NUM_ORDERS(sb) + 1)
3011 return NULL;
3012 position = *pos + 1;
3013 return (void *) ((unsigned long) position);
3014}
3015
3016static int ext4_mb_seq_structs_summary_show(struct seq_file *seq, void *v)
3017{
359745d7 3018 struct super_block *sb = pde_data(file_inode(seq->file));
f68f4063
HS
3019 struct ext4_sb_info *sbi = EXT4_SB(sb);
3020 unsigned long position = ((unsigned long) v);
3021 struct ext4_group_info *grp;
3022 struct rb_node *n;
3023 unsigned int count, min, max;
3024
3025 position--;
3026 if (position >= MB_NUM_ORDERS(sb)) {
3027 seq_puts(seq, "fragment_size_tree:\n");
3028 n = rb_first(&sbi->s_mb_avg_fragment_size_root);
3029 if (!n) {
3030 seq_puts(seq, "\ttree_min: 0\n\ttree_max: 0\n\ttree_nodes: 0\n");
3031 return 0;
3032 }
3033 grp = rb_entry(n, struct ext4_group_info, bb_avg_fragment_size_rb);
3034 min = grp->bb_fragments ? grp->bb_free / grp->bb_fragments : 0;
3035 count = 1;
3036 while (rb_next(n)) {
3037 count++;
3038 n = rb_next(n);
3039 }
3040 grp = rb_entry(n, struct ext4_group_info, bb_avg_fragment_size_rb);
3041 max = grp->bb_fragments ? grp->bb_free / grp->bb_fragments : 0;
3042
3043 seq_printf(seq, "\ttree_min: %u\n\ttree_max: %u\n\ttree_nodes: %u\n",
3044 min, max, count);
3045 return 0;
3046 }
3047
3048 if (position == 0) {
3049 seq_printf(seq, "optimize_scan: %d\n",
3050 test_opt2(sb, MB_OPTIMIZE_SCAN) ? 1 : 0);
3051 seq_puts(seq, "max_free_order_lists:\n");
3052 }
3053 count = 0;
3054 list_for_each_entry(grp, &sbi->s_mb_largest_free_orders[position],
3055 bb_largest_free_order_node)
3056 count++;
3057 seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3058 (unsigned int)position, count);
3059
3060 return 0;
3061}
3062
3063static void ext4_mb_seq_structs_summary_stop(struct seq_file *seq, void *v)
a5fda113 3064__releases(&EXT4_SB(sb)->s_mb_rb_lock)
f68f4063 3065{
359745d7 3066 struct super_block *sb = pde_data(file_inode(seq->file));
f68f4063
HS
3067
3068 read_unlock(&EXT4_SB(sb)->s_mb_rb_lock);
3069}
3070
3071const struct seq_operations ext4_mb_seq_structs_summary_ops = {
3072 .start = ext4_mb_seq_structs_summary_start,
3073 .next = ext4_mb_seq_structs_summary_next,
3074 .stop = ext4_mb_seq_structs_summary_stop,
3075 .show = ext4_mb_seq_structs_summary_show,
3076};
3077
fb1813f4
CW
3078static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
3079{
3080 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3081 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
3082
3083 BUG_ON(!cachep);
3084 return cachep;
3085}
5f21b0e6 3086
28623c2f
TT
3087/*
3088 * Allocate the top-level s_group_info array for the specified number
3089 * of groups
3090 */
3091int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
3092{
3093 struct ext4_sb_info *sbi = EXT4_SB(sb);
3094 unsigned size;
df3da4ea 3095 struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
28623c2f
TT
3096
3097 size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
3098 EXT4_DESC_PER_BLOCK_BITS(sb);
3099 if (size <= sbi->s_group_info_size)
3100 return 0;
3101
3102 size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
a7c3e901 3103 new_groupinfo = kvzalloc(size, GFP_KERNEL);
28623c2f
TT
3104 if (!new_groupinfo) {
3105 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
3106 return -ENOMEM;
3107 }
df3da4ea
SJS
3108 rcu_read_lock();
3109 old_groupinfo = rcu_dereference(sbi->s_group_info);
3110 if (old_groupinfo)
3111 memcpy(new_groupinfo, old_groupinfo,
28623c2f 3112 sbi->s_group_info_size * sizeof(*sbi->s_group_info));
df3da4ea
SJS
3113 rcu_read_unlock();
3114 rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
28623c2f 3115 sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
df3da4ea
SJS
3116 if (old_groupinfo)
3117 ext4_kvfree_array_rcu(old_groupinfo);
666245d9 3118 ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
28623c2f
TT
3119 sbi->s_group_info_size);
3120 return 0;
3121}
3122
5f21b0e6 3123/* Create and initialize ext4_group_info data for the given group. */
920313a7 3124int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
5f21b0e6
FB
3125 struct ext4_group_desc *desc)
3126{
fb1813f4 3127 int i;
5f21b0e6 3128 int metalen = 0;
df3da4ea 3129 int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
5f21b0e6
FB
3130 struct ext4_sb_info *sbi = EXT4_SB(sb);
3131 struct ext4_group_info **meta_group_info;
fb1813f4 3132 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
5f21b0e6
FB
3133
3134 /*
3135 * First check if this group is the first of a reserved block.
3136 * If it's true, we have to allocate a new table of pointers
3137 * to ext4_group_info structures
3138 */
3139 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3140 metalen = sizeof(*meta_group_info) <<
3141 EXT4_DESC_PER_BLOCK_BITS(sb);
4fdb5543 3142 meta_group_info = kmalloc(metalen, GFP_NOFS);
5f21b0e6 3143 if (meta_group_info == NULL) {
7f6a11e7 3144 ext4_msg(sb, KERN_ERR, "can't allocate mem "
9d8b9ec4 3145 "for a buddy group");
5f21b0e6
FB
3146 goto exit_meta_group_info;
3147 }
df3da4ea
SJS
3148 rcu_read_lock();
3149 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
3150 rcu_read_unlock();
5f21b0e6
FB
3151 }
3152
df3da4ea 3153 meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
5f21b0e6
FB
3154 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
3155
4fdb5543 3156 meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
5f21b0e6 3157 if (meta_group_info[i] == NULL) {
7f6a11e7 3158 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
5f21b0e6
FB
3159 goto exit_group_info;
3160 }
3161 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
3162 &(meta_group_info[i]->bb_state));
3163
3164 /*
3165 * initialize bb_free to be able to skip
3166 * empty groups without initialization
3167 */
8844618d
TT
3168 if (ext4_has_group_desc_csum(sb) &&
3169 (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
5f21b0e6 3170 meta_group_info[i]->bb_free =
cff1dfd7 3171 ext4_free_clusters_after_init(sb, group, desc);
5f21b0e6
FB
3172 } else {
3173 meta_group_info[i]->bb_free =
021b65bb 3174 ext4_free_group_clusters(sb, desc);
5f21b0e6
FB
3175 }
3176
3177 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
920313a7 3178 init_rwsem(&meta_group_info[i]->alloc_sem);
64e290ec 3179 meta_group_info[i]->bb_free_root = RB_ROOT;
196e402a
HS
3180 INIT_LIST_HEAD(&meta_group_info[i]->bb_largest_free_order_node);
3181 RB_CLEAR_NODE(&meta_group_info[i]->bb_avg_fragment_size_rb);
8a57d9d6 3182 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
196e402a 3183 meta_group_info[i]->bb_group = group;
5f21b0e6 3184
a3450215 3185 mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
5f21b0e6
FB
3186 return 0;
3187
3188exit_group_info:
3189 /* If a meta_group_info table has been allocated, release it now */
caaf7a29 3190 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
df3da4ea
SJS
3191 struct ext4_group_info ***group_info;
3192
3193 rcu_read_lock();
3194 group_info = rcu_dereference(sbi->s_group_info);
3195 kfree(group_info[idx]);
3196 group_info[idx] = NULL;
3197 rcu_read_unlock();
caaf7a29 3198 }
5f21b0e6
FB
3199exit_meta_group_info:
3200 return -ENOMEM;
3201} /* ext4_mb_add_groupinfo */
3202
c9de560d
AT
3203static int ext4_mb_init_backend(struct super_block *sb)
3204{
8df9675f 3205 ext4_group_t ngroups = ext4_get_groups_count(sb);
c9de560d 3206 ext4_group_t i;
c9de560d 3207 struct ext4_sb_info *sbi = EXT4_SB(sb);
28623c2f 3208 int err;
5f21b0e6 3209 struct ext4_group_desc *desc;
df3da4ea 3210 struct ext4_group_info ***group_info;
fb1813f4 3211 struct kmem_cache *cachep;
5f21b0e6 3212
28623c2f
TT
3213 err = ext4_mb_alloc_groupinfo(sb, ngroups);
3214 if (err)
3215 return err;
c9de560d 3216
c9de560d
AT
3217 sbi->s_buddy_cache = new_inode(sb);
3218 if (sbi->s_buddy_cache == NULL) {
9d8b9ec4 3219 ext4_msg(sb, KERN_ERR, "can't get new inode");
c9de560d
AT
3220 goto err_freesgi;
3221 }
48e6061b
YJ
3222 /* To avoid potentially colliding with an valid on-disk inode number,
3223 * use EXT4_BAD_INO for the buddy cache inode number. This inode is
3224 * not in the inode hash, so it should never be found by iget(), but
3225 * this will avoid confusion if it ever shows up during debugging. */
3226 sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
c9de560d 3227 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
8df9675f 3228 for (i = 0; i < ngroups; i++) {
4b99faa2 3229 cond_resched();
c9de560d
AT
3230 desc = ext4_get_group_desc(sb, i, NULL);
3231 if (desc == NULL) {
9d8b9ec4 3232 ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
c9de560d
AT
3233 goto err_freebuddy;
3234 }
5f21b0e6
FB
3235 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
3236 goto err_freebuddy;
c9de560d
AT
3237 }
3238
cfd73237 3239 if (ext4_has_feature_flex_bg(sb)) {
f91436d5
ST
3240 /* a single flex group is supposed to be read by a single IO.
3241 * 2 ^ s_log_groups_per_flex != UINT_MAX as s_mb_prefetch is
3242 * unsigned integer, so the maximum shift is 32.
3243 */
3244 if (sbi->s_es->s_log_groups_per_flex >= 32) {
3245 ext4_msg(sb, KERN_ERR, "too many log groups per flexible block group");
a8867f4e 3246 goto err_freebuddy;
f91436d5
ST
3247 }
3248 sbi->s_mb_prefetch = min_t(uint, 1 << sbi->s_es->s_log_groups_per_flex,
82ef1370 3249 BLK_MAX_SEGMENT_SIZE >> (sb->s_blocksize_bits - 9));
cfd73237
AZ
3250 sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
3251 } else {
3252 sbi->s_mb_prefetch = 32;
3253 }
3254 if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
3255 sbi->s_mb_prefetch = ext4_get_groups_count(sb);
3256 /* now many real IOs to prefetch within a single allocation at cr=0
3257 * given cr=0 is an CPU-related optimization we shouldn't try to
3258 * load too many groups, at some point we should start to use what
3259 * we've got in memory.
3260 * with an average random access time 5ms, it'd take a second to get
3261 * 200 groups (* N with flex_bg), so let's make this limit 4
3262 */
3263 sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
3264 if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
3265 sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
3266
c9de560d
AT
3267 return 0;
3268
3269err_freebuddy:
fb1813f4 3270 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
f1fa3342 3271 while (i-- > 0)
fb1813f4 3272 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
28623c2f 3273 i = sbi->s_group_info_size;
df3da4ea
SJS
3274 rcu_read_lock();
3275 group_info = rcu_dereference(sbi->s_group_info);
f1fa3342 3276 while (i-- > 0)
df3da4ea
SJS
3277 kfree(group_info[i]);
3278 rcu_read_unlock();
c9de560d
AT
3279 iput(sbi->s_buddy_cache);
3280err_freesgi:
df3da4ea
SJS
3281 rcu_read_lock();
3282 kvfree(rcu_dereference(sbi->s_group_info));
3283 rcu_read_unlock();
c9de560d
AT
3284 return -ENOMEM;
3285}
3286
2892c15d
ES
3287static void ext4_groupinfo_destroy_slabs(void)
3288{
3289 int i;
3290
3291 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
21c580d8 3292 kmem_cache_destroy(ext4_groupinfo_caches[i]);
2892c15d
ES
3293 ext4_groupinfo_caches[i] = NULL;
3294 }
3295}
3296
3297static int ext4_groupinfo_create_slab(size_t size)
3298{
3299 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
3300 int slab_size;
3301 int blocksize_bits = order_base_2(size);
3302 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3303 struct kmem_cache *cachep;
3304
3305 if (cache_index >= NR_GRPINFO_CACHES)
3306 return -EINVAL;
3307
3308 if (unlikely(cache_index < 0))
3309 cache_index = 0;
3310
3311 mutex_lock(&ext4_grpinfo_slab_create_mutex);
3312 if (ext4_groupinfo_caches[cache_index]) {
3313 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
3314 return 0; /* Already created */
3315 }
3316
3317 slab_size = offsetof(struct ext4_group_info,
3318 bb_counters[blocksize_bits + 2]);
3319
3320 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
3321 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
3322 NULL);
3323
823ba01f
TM
3324 ext4_groupinfo_caches[cache_index] = cachep;
3325
2892c15d
ES
3326 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
3327 if (!cachep) {
9d8b9ec4
TT
3328 printk(KERN_EMERG
3329 "EXT4-fs: no memory for groupinfo slab cache\n");
2892c15d
ES
3330 return -ENOMEM;
3331 }
3332
2892c15d
ES
3333 return 0;
3334}
3335
55cdd0af
WJ
3336static void ext4_discard_work(struct work_struct *work)
3337{
3338 struct ext4_sb_info *sbi = container_of(work,
3339 struct ext4_sb_info, s_discard_work);
3340 struct super_block *sb = sbi->s_sb;
3341 struct ext4_free_data *fd, *nfd;
3342 struct ext4_buddy e4b;
3343 struct list_head discard_list;
3344 ext4_group_t grp, load_grp;
3345 int err = 0;
3346
3347 INIT_LIST_HEAD(&discard_list);
3348 spin_lock(&sbi->s_md_lock);
3349 list_splice_init(&sbi->s_discard_list, &discard_list);
3350 spin_unlock(&sbi->s_md_lock);
3351
3352 load_grp = UINT_MAX;
3353 list_for_each_entry_safe(fd, nfd, &discard_list, efd_list) {
3354 /*
5036ab8d
WJ
3355 * If filesystem is umounting or no memory or suffering
3356 * from no space, give up the discard
55cdd0af 3357 */
5036ab8d
WJ
3358 if ((sb->s_flags & SB_ACTIVE) && !err &&
3359 !atomic_read(&sbi->s_retry_alloc_pending)) {
55cdd0af
WJ
3360 grp = fd->efd_group;
3361 if (grp != load_grp) {
3362 if (load_grp != UINT_MAX)
3363 ext4_mb_unload_buddy(&e4b);
3364
3365 err = ext4_mb_load_buddy(sb, grp, &e4b);
3366 if (err) {
3367 kmem_cache_free(ext4_free_data_cachep, fd);
3368 load_grp = UINT_MAX;
3369 continue;
3370 } else {
3371 load_grp = grp;
3372 }
3373 }
3374
3375 ext4_lock_group(sb, grp);
3376 ext4_try_to_trim_range(sb, &e4b, fd->efd_start_cluster,
3377 fd->efd_start_cluster + fd->efd_count - 1, 1);
3378 ext4_unlock_group(sb, grp);
3379 }
3380 kmem_cache_free(ext4_free_data_cachep, fd);
3381 }
3382
3383 if (load_grp != UINT_MAX)
3384 ext4_mb_unload_buddy(&e4b);
3385}
3386
9d99012f 3387int ext4_mb_init(struct super_block *sb)
c9de560d
AT
3388{
3389 struct ext4_sb_info *sbi = EXT4_SB(sb);
6be2ded1 3390 unsigned i, j;
935244cd 3391 unsigned offset, offset_incr;
c9de560d 3392 unsigned max;
74767c5a 3393 int ret;
c9de560d 3394
4b68f6df 3395 i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_offsets);
c9de560d
AT
3396
3397 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
3398 if (sbi->s_mb_offsets == NULL) {
fb1813f4
CW
3399 ret = -ENOMEM;
3400 goto out;
c9de560d 3401 }
ff7ef329 3402
4b68f6df 3403 i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_maxs);
c9de560d
AT
3404 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
3405 if (sbi->s_mb_maxs == NULL) {
fb1813f4
CW
3406 ret = -ENOMEM;
3407 goto out;
3408 }
3409
2892c15d
ES
3410 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
3411 if (ret < 0)
3412 goto out;
c9de560d
AT
3413
3414 /* order 0 is regular bitmap */
3415 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
3416 sbi->s_mb_offsets[0] = 0;
3417
3418 i = 1;
3419 offset = 0;
935244cd 3420 offset_incr = 1 << (sb->s_blocksize_bits - 1);
c9de560d
AT
3421 max = sb->s_blocksize << 2;
3422 do {
3423 sbi->s_mb_offsets[i] = offset;
3424 sbi->s_mb_maxs[i] = max;
935244cd
NS
3425 offset += offset_incr;
3426 offset_incr = offset_incr >> 1;
c9de560d
AT
3427 max = max >> 1;
3428 i++;
4b68f6df
HS
3429 } while (i < MB_NUM_ORDERS(sb));
3430
196e402a
HS
3431 sbi->s_mb_avg_fragment_size_root = RB_ROOT;
3432 sbi->s_mb_largest_free_orders =
3433 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3434 GFP_KERNEL);
3435 if (!sbi->s_mb_largest_free_orders) {
3436 ret = -ENOMEM;
3437 goto out;
3438 }
3439 sbi->s_mb_largest_free_orders_locks =
3440 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3441 GFP_KERNEL);
3442 if (!sbi->s_mb_largest_free_orders_locks) {
3443 ret = -ENOMEM;
3444 goto out;
3445 }
3446 for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3447 INIT_LIST_HEAD(&sbi->s_mb_largest_free_orders[i]);
3448 rwlock_init(&sbi->s_mb_largest_free_orders_locks[i]);
3449 }
3450 rwlock_init(&sbi->s_mb_rb_lock);
c9de560d 3451
c9de560d 3452 spin_lock_init(&sbi->s_md_lock);
d08854f5 3453 sbi->s_mb_free_pending = 0;
a0154344 3454 INIT_LIST_HEAD(&sbi->s_freed_data_list);
55cdd0af
WJ
3455 INIT_LIST_HEAD(&sbi->s_discard_list);
3456 INIT_WORK(&sbi->s_discard_work, ext4_discard_work);
5036ab8d 3457 atomic_set(&sbi->s_retry_alloc_pending, 0);
c9de560d
AT
3458
3459 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
3460 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
3461 sbi->s_mb_stats = MB_DEFAULT_STATS;
3462 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
3463 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
27bc446e 3464 sbi->s_mb_max_inode_prealloc = MB_DEFAULT_MAX_INODE_PREALLOC;
27baebb8
TT
3465 /*
3466 * The default group preallocation is 512, which for 4k block
3467 * sizes translates to 2 megabytes. However for bigalloc file
3468 * systems, this is probably too big (i.e, if the cluster size
3469 * is 1 megabyte, then group preallocation size becomes half a
3470 * gigabyte!). As a default, we will keep a two megabyte
3471 * group pralloc size for cluster sizes up to 64k, and after
3472 * that, we will force a minimum group preallocation size of
3473 * 32 clusters. This translates to 8 megs when the cluster
3474 * size is 256k, and 32 megs when the cluster size is 1 meg,
3475 * which seems reasonable as a default.
3476 */
3477 sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
3478 sbi->s_cluster_bits, 32);
d7a1fee1
DE
3479 /*
3480 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
3481 * to the lowest multiple of s_stripe which is bigger than
3482 * the s_mb_group_prealloc as determined above. We want
3483 * the preallocation size to be an exact multiple of the
3484 * RAID stripe size so that preallocations don't fragment
3485 * the stripes.
3486 */
3487 if (sbi->s_stripe > 1) {
3488 sbi->s_mb_group_prealloc = roundup(
3489 sbi->s_mb_group_prealloc, sbi->s_stripe);
3490 }
c9de560d 3491
730c213c 3492 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
c9de560d 3493 if (sbi->s_locality_groups == NULL) {
fb1813f4 3494 ret = -ENOMEM;
029b10c5 3495 goto out;
c9de560d 3496 }
730c213c 3497 for_each_possible_cpu(i) {
c9de560d 3498 struct ext4_locality_group *lg;
730c213c 3499 lg = per_cpu_ptr(sbi->s_locality_groups, i);
c9de560d 3500 mutex_init(&lg->lg_mutex);
6be2ded1
AK
3501 for (j = 0; j < PREALLOC_TB_SIZE; j++)
3502 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
c9de560d
AT
3503 spin_lock_init(&lg->lg_prealloc_lock);
3504 }
3505
10f0d2a5 3506 if (bdev_nonrot(sb->s_bdev))
196e402a
HS
3507 sbi->s_mb_max_linear_groups = 0;
3508 else
3509 sbi->s_mb_max_linear_groups = MB_DEFAULT_LINEAR_LIMIT;
79a77c5a
YJ
3510 /* init file for buddy data */
3511 ret = ext4_mb_init_backend(sb);
7aa0baea
TM
3512 if (ret != 0)
3513 goto out_free_locality_groups;
79a77c5a 3514
7aa0baea
TM
3515 return 0;
3516
3517out_free_locality_groups:
3518 free_percpu(sbi->s_locality_groups);
3519 sbi->s_locality_groups = NULL;
fb1813f4 3520out:
196e402a
HS
3521 kfree(sbi->s_mb_largest_free_orders);
3522 kfree(sbi->s_mb_largest_free_orders_locks);
7aa0baea
TM
3523 kfree(sbi->s_mb_offsets);
3524 sbi->s_mb_offsets = NULL;
3525 kfree(sbi->s_mb_maxs);
3526 sbi->s_mb_maxs = NULL;
fb1813f4 3527 return ret;
c9de560d
AT
3528}
3529
955ce5f5 3530/* need to called with the ext4 group lock held */
d3df1453 3531static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
c9de560d
AT
3532{
3533 struct ext4_prealloc_space *pa;
3534 struct list_head *cur, *tmp;
3535 int count = 0;
3536
3537 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
3538 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3539 list_del(&pa->pa_group_list);
3540 count++;
688f05a0 3541 kmem_cache_free(ext4_pspace_cachep, pa);
c9de560d 3542 }
d3df1453 3543 return count;
c9de560d
AT
3544}
3545
3546int ext4_mb_release(struct super_block *sb)
3547{
8df9675f 3548 ext4_group_t ngroups = ext4_get_groups_count(sb);
c9de560d
AT
3549 ext4_group_t i;
3550 int num_meta_group_infos;
df3da4ea 3551 struct ext4_group_info *grinfo, ***group_info;
c9de560d 3552 struct ext4_sb_info *sbi = EXT4_SB(sb);
fb1813f4 3553 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
d3df1453 3554 int count;
c9de560d 3555
55cdd0af
WJ
3556 if (test_opt(sb, DISCARD)) {
3557 /*
3558 * wait the discard work to drain all of ext4_free_data
3559 */
3560 flush_work(&sbi->s_discard_work);
3561 WARN_ON_ONCE(!list_empty(&sbi->s_discard_list));
3562 }
3563
c9de560d 3564 if (sbi->s_group_info) {
8df9675f 3565 for (i = 0; i < ngroups; i++) {
4b99faa2 3566 cond_resched();
c9de560d 3567 grinfo = ext4_get_group_info(sb, i);
a3450215 3568 mb_group_bb_bitmap_free(grinfo);
c9de560d 3569 ext4_lock_group(sb, i);
d3df1453
RH
3570 count = ext4_mb_cleanup_pa(grinfo);
3571 if (count)
3572 mb_debug(sb, "mballoc: %d PAs left\n",
3573 count);
c9de560d 3574 ext4_unlock_group(sb, i);
fb1813f4 3575 kmem_cache_free(cachep, grinfo);
c9de560d 3576 }
8df9675f 3577 num_meta_group_infos = (ngroups +
c9de560d
AT
3578 EXT4_DESC_PER_BLOCK(sb) - 1) >>
3579 EXT4_DESC_PER_BLOCK_BITS(sb);
df3da4ea
SJS
3580 rcu_read_lock();
3581 group_info = rcu_dereference(sbi->s_group_info);
c9de560d 3582 for (i = 0; i < num_meta_group_infos; i++)
df3da4ea
SJS
3583 kfree(group_info[i]);
3584 kvfree(group_info);
3585 rcu_read_unlock();
c9de560d 3586 }
196e402a
HS
3587 kfree(sbi->s_mb_largest_free_orders);
3588 kfree(sbi->s_mb_largest_free_orders_locks);
c9de560d
AT
3589 kfree(sbi->s_mb_offsets);
3590 kfree(sbi->s_mb_maxs);
bfcba2d0 3591 iput(sbi->s_buddy_cache);
c9de560d 3592 if (sbi->s_mb_stats) {
9d8b9ec4
TT
3593 ext4_msg(sb, KERN_INFO,
3594 "mballoc: %u blocks %u reqs (%u success)",
c9de560d
AT
3595 atomic_read(&sbi->s_bal_allocated),
3596 atomic_read(&sbi->s_bal_reqs),
3597 atomic_read(&sbi->s_bal_success));
9d8b9ec4 3598 ext4_msg(sb, KERN_INFO,
a6c75eaf 3599 "mballoc: %u extents scanned, %u groups scanned, %u goal hits, "
9d8b9ec4 3600 "%u 2^N hits, %u breaks, %u lost",
c9de560d 3601 atomic_read(&sbi->s_bal_ex_scanned),
a6c75eaf 3602 atomic_read(&sbi->s_bal_groups_scanned),
c9de560d
AT
3603 atomic_read(&sbi->s_bal_goals),
3604 atomic_read(&sbi->s_bal_2orders),
3605 atomic_read(&sbi->s_bal_breaks),
3606 atomic_read(&sbi->s_mb_lost_chunks));
9d8b9ec4 3607 ext4_msg(sb, KERN_INFO,
67d25186
HS
3608 "mballoc: %u generated and it took %llu",
3609 atomic_read(&sbi->s_mb_buddies_generated),
3610 atomic64_read(&sbi->s_mb_generation_time));
9d8b9ec4
TT
3611 ext4_msg(sb, KERN_INFO,
3612 "mballoc: %u preallocated, %u discarded",
c9de560d
AT
3613 atomic_read(&sbi->s_mb_preallocated),
3614 atomic_read(&sbi->s_mb_discarded));
3615 }
3616
730c213c 3617 free_percpu(sbi->s_locality_groups);
c9de560d
AT
3618
3619 return 0;
3620}
3621
77ca6cdf 3622static inline int ext4_issue_discard(struct super_block *sb,
a0154344
DJ
3623 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
3624 struct bio **biop)
5c521830 3625{
5c521830
JZ
3626 ext4_fsblk_t discard_block;
3627
84130193
TT
3628 discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
3629 ext4_group_first_block_no(sb, block_group));
3630 count = EXT4_C2B(EXT4_SB(sb), count);
5c521830
JZ
3631 trace_ext4_discard_blocks(sb,
3632 (unsigned long long) discard_block, count);
a0154344
DJ
3633 if (biop) {
3634 return __blkdev_issue_discard(sb->s_bdev,
3635 (sector_t)discard_block << (sb->s_blocksize_bits - 9),
3636 (sector_t)count << (sb->s_blocksize_bits - 9),
44abff2c 3637 GFP_NOFS, biop);
a0154344
DJ
3638 } else
3639 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
5c521830
JZ
3640}
3641
a0154344
DJ
3642static void ext4_free_data_in_buddy(struct super_block *sb,
3643 struct ext4_free_data *entry)
c9de560d 3644{
c9de560d 3645 struct ext4_buddy e4b;
c894058d 3646 struct ext4_group_info *db;
d9f34504 3647 int err, count = 0, count2 = 0;
c9de560d 3648
d3df1453 3649 mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
18aadd47 3650 entry->efd_count, entry->efd_group, entry);
c9de560d 3651
18aadd47
BJ
3652 err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
3653 /* we expect to find existing buddy because it's pinned */
3654 BUG_ON(err != 0);
b90f6870 3655
d08854f5
TT
3656 spin_lock(&EXT4_SB(sb)->s_md_lock);
3657 EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
3658 spin_unlock(&EXT4_SB(sb)->s_md_lock);
c9de560d 3659
18aadd47
BJ
3660 db = e4b.bd_info;
3661 /* there are blocks to put in buddy to make them really free */
3662 count += entry->efd_count;
3663 count2++;
3664 ext4_lock_group(sb, entry->efd_group);
3665 /* Take it out of per group rb tree */
3666 rb_erase(&entry->efd_node, &(db->bb_free_root));
3667 mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
c894058d 3668
18aadd47
BJ
3669 /*
3670 * Clear the trimmed flag for the group so that the next
3671 * ext4_trim_fs can trim it.
3672 * If the volume is mounted with -o discard, online discard
3673 * is supported and the free blocks will be trimmed online.
3674 */
3675 if (!test_opt(sb, DISCARD))
3676 EXT4_MB_GRP_CLEAR_TRIMMED(db);
3d56b8d2 3677
18aadd47
BJ
3678 if (!db->bb_free_root.rb_node) {
3679 /* No more items in the per group rb tree
3680 * balance refcounts from ext4_mb_free_metadata()
3681 */
09cbfeaf
KS
3682 put_page(e4b.bd_buddy_page);
3683 put_page(e4b.bd_bitmap_page);
3e624fc7 3684 }
18aadd47 3685 ext4_unlock_group(sb, entry->efd_group);
18aadd47 3686 ext4_mb_unload_buddy(&e4b);
c9de560d 3687
d3df1453
RH
3688 mb_debug(sb, "freed %d blocks in %d structures\n", count,
3689 count2);
c9de560d
AT
3690}
3691
a0154344
DJ
3692/*
3693 * This function is called by the jbd2 layer once the commit has finished,
3694 * so we know we can free the blocks that were released with that commit.
3695 */
3696void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
3697{
3698 struct ext4_sb_info *sbi = EXT4_SB(sb);
3699 struct ext4_free_data *entry, *tmp;
a0154344
DJ
3700 struct list_head freed_data_list;
3701 struct list_head *cut_pos = NULL;
55cdd0af 3702 bool wake;
a0154344
DJ
3703
3704 INIT_LIST_HEAD(&freed_data_list);
3705
3706 spin_lock(&sbi->s_md_lock);
3707 list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
3708 if (entry->efd_tid != commit_tid)
3709 break;
3710 cut_pos = &entry->efd_list;
3711 }
3712 if (cut_pos)
3713 list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
3714 cut_pos);
3715 spin_unlock(&sbi->s_md_lock);
3716
55cdd0af
WJ
3717 list_for_each_entry(entry, &freed_data_list, efd_list)
3718 ext4_free_data_in_buddy(sb, entry);
a0154344 3719
55cdd0af
WJ
3720 if (test_opt(sb, DISCARD)) {
3721 spin_lock(&sbi->s_md_lock);
3722 wake = list_empty(&sbi->s_discard_list);
3723 list_splice_tail(&freed_data_list, &sbi->s_discard_list);
3724 spin_unlock(&sbi->s_md_lock);
3725 if (wake)
3726 queue_work(system_unbound_wq, &sbi->s_discard_work);
3727 } else {
3728 list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
3729 kmem_cache_free(ext4_free_data_cachep, entry);
a0154344 3730 }
a0154344
DJ
3731}
3732
5dabfc78 3733int __init ext4_init_mballoc(void)
c9de560d 3734{
16828088
TT
3735 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
3736 SLAB_RECLAIM_ACCOUNT);
c9de560d 3737 if (ext4_pspace_cachep == NULL)
f283529a 3738 goto out;
c9de560d 3739
16828088
TT
3740 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
3741 SLAB_RECLAIM_ACCOUNT);
f283529a
RH
3742 if (ext4_ac_cachep == NULL)
3743 goto out_pa_free;
c894058d 3744
18aadd47
BJ
3745 ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
3746 SLAB_RECLAIM_ACCOUNT);
f283529a
RH
3747 if (ext4_free_data_cachep == NULL)
3748 goto out_ac_free;
3749
c9de560d 3750 return 0;
f283529a
RH
3751
3752out_ac_free:
3753 kmem_cache_destroy(ext4_ac_cachep);
3754out_pa_free:
3755 kmem_cache_destroy(ext4_pspace_cachep);
3756out:
3757 return -ENOMEM;
c9de560d
AT
3758}
3759
5dabfc78 3760void ext4_exit_mballoc(void)
c9de560d 3761{
60e6679e 3762 /*
3e03f9ca
JDB
3763 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
3764 * before destroying the slab cache.
3765 */
3766 rcu_barrier();
c9de560d 3767 kmem_cache_destroy(ext4_pspace_cachep);
256bdb49 3768 kmem_cache_destroy(ext4_ac_cachep);
18aadd47 3769 kmem_cache_destroy(ext4_free_data_cachep);
2892c15d 3770 ext4_groupinfo_destroy_slabs();
c9de560d
AT
3771}
3772
3773
3774/*
73b2c716 3775 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
c9de560d
AT
3776 * Returns 0 if success or error code
3777 */
4ddfef7b
ES
3778static noinline_for_stack int
3779ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
53accfa9 3780 handle_t *handle, unsigned int reserv_clstrs)
c9de560d
AT
3781{
3782 struct buffer_head *bitmap_bh = NULL;
c9de560d
AT
3783 struct ext4_group_desc *gdp;
3784 struct buffer_head *gdp_bh;
3785 struct ext4_sb_info *sbi;
3786 struct super_block *sb;
3787 ext4_fsblk_t block;
519deca0 3788 int err, len;
c9de560d
AT
3789
3790 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3791 BUG_ON(ac->ac_b_ex.fe_len <= 0);
3792
3793 sb = ac->ac_sb;
3794 sbi = EXT4_SB(sb);
c9de560d 3795
574ca174 3796 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
9008a58e
DW
3797 if (IS_ERR(bitmap_bh)) {
3798 err = PTR_ERR(bitmap_bh);
3799 bitmap_bh = NULL;
c9de560d 3800 goto out_err;
9008a58e 3801 }
c9de560d 3802
5d601255 3803 BUFFER_TRACE(bitmap_bh, "getting write access");
188c299e
JK
3804 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
3805 EXT4_JTR_NONE);
c9de560d
AT
3806 if (err)
3807 goto out_err;
3808
3809 err = -EIO;
3810 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3811 if (!gdp)
3812 goto out_err;
3813
a9df9a49 3814 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
021b65bb 3815 ext4_free_group_clusters(sb, gdp));
03cddb80 3816
5d601255 3817 BUFFER_TRACE(gdp_bh, "get_write_access");
188c299e 3818 err = ext4_journal_get_write_access(handle, sb, gdp_bh, EXT4_JTR_NONE);
c9de560d
AT
3819 if (err)
3820 goto out_err;
3821
bda00de7 3822 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
c9de560d 3823
53accfa9 3824 len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
ce9f24cc 3825 if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
12062ddd 3826 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
1084f252 3827 "fs metadata", block, block+len);
519deca0 3828 /* File system mounted not to panic on error
554a5ccc 3829 * Fix the bitmap and return EFSCORRUPTED
519deca0
AK
3830 * We leak some of the blocks here.
3831 */
955ce5f5 3832 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
123e3016 3833 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
c3e94d1d 3834 ac->ac_b_ex.fe_len);
955ce5f5 3835 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
0390131b 3836 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
519deca0 3837 if (!err)
554a5ccc 3838 err = -EFSCORRUPTED;
519deca0 3839 goto out_err;
c9de560d 3840 }
955ce5f5
AK
3841
3842 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
c9de560d
AT
3843#ifdef AGGRESSIVE_CHECK
3844 {
3845 int i;
3846 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3847 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3848 bitmap_bh->b_data));
3849 }
3850 }
3851#endif
123e3016 3852 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
c3e94d1d 3853 ac->ac_b_ex.fe_len);
8844618d
TT
3854 if (ext4_has_group_desc_csum(sb) &&
3855 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
c9de560d 3856 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
021b65bb 3857 ext4_free_group_clusters_set(sb, gdp,
cff1dfd7 3858 ext4_free_clusters_after_init(sb,
021b65bb 3859 ac->ac_b_ex.fe_group, gdp));
c9de560d 3860 }
021b65bb
TT
3861 len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
3862 ext4_free_group_clusters_set(sb, gdp, len);
79f1ba49 3863 ext4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);
feb0ab32 3864 ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
955ce5f5
AK
3865
3866 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
57042651 3867 percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
d2a17637 3868 /*
6bc6e63f 3869 * Now reduce the dirty block count also. Should not go negative
d2a17637 3870 */
6bc6e63f
AK
3871 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3872 /* release all the reserved blocks if non delalloc */
57042651
TT
3873 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
3874 reserv_clstrs);
c9de560d 3875
772cb7c8
JS
3876 if (sbi->s_log_groups_per_flex) {
3877 ext4_group_t flex_group = ext4_flex_group(sbi,
3878 ac->ac_b_ex.fe_group);
90ba983f 3879 atomic64_sub(ac->ac_b_ex.fe_len,
7c990728
SJS
3880 &sbi_array_rcu_deref(sbi, s_flex_groups,
3881 flex_group)->free_clusters);
772cb7c8
JS
3882 }
3883
0390131b 3884 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
c9de560d
AT
3885 if (err)
3886 goto out_err;
0390131b 3887 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
c9de560d
AT
3888
3889out_err:
42a10add 3890 brelse(bitmap_bh);
c9de560d
AT
3891 return err;
3892}
3893
8016e29f
HS
3894/*
3895 * Idempotent helper for Ext4 fast commit replay path to set the state of
3896 * blocks in bitmaps and update counters.
3897 */
3898void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
3899 int len, int state)
3900{
3901 struct buffer_head *bitmap_bh = NULL;
3902 struct ext4_group_desc *gdp;
3903 struct buffer_head *gdp_bh;
3904 struct ext4_sb_info *sbi = EXT4_SB(sb);
3905 ext4_group_t group;
3906 ext4_grpblk_t blkoff;
a5c0e2fd 3907 int i, err;
8016e29f 3908 int already;
bfdc502a 3909 unsigned int clen, clen_changed, thisgrp_len;
8016e29f 3910
bfdc502a
RH
3911 while (len > 0) {
3912 ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
8016e29f 3913
bfdc502a
RH
3914 /*
3915 * Check to see if we are freeing blocks across a group
3916 * boundary.
3917 * In case of flex_bg, this can happen that (block, len) may
3918 * span across more than one group. In that case we need to
3919 * get the corresponding group metadata to work with.
3920 * For this we have goto again loop.
3921 */
3922 thisgrp_len = min_t(unsigned int, (unsigned int)len,
3923 EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
3924 clen = EXT4_NUM_B2C(sbi, thisgrp_len);
3925
8c91c579
RH
3926 if (!ext4_sb_block_valid(sb, NULL, block, thisgrp_len)) {
3927 ext4_error(sb, "Marking blocks in system zone - "
3928 "Block = %llu, len = %u",
3929 block, thisgrp_len);
3930 bitmap_bh = NULL;
3931 break;
3932 }
3933
bfdc502a
RH
3934 bitmap_bh = ext4_read_block_bitmap(sb, group);
3935 if (IS_ERR(bitmap_bh)) {
3936 err = PTR_ERR(bitmap_bh);
3937 bitmap_bh = NULL;
3938 break;
3939 }
8016e29f 3940
bfdc502a
RH
3941 err = -EIO;
3942 gdp = ext4_get_group_desc(sb, group, &gdp_bh);
3943 if (!gdp)
3944 break;
8016e29f 3945
bfdc502a
RH
3946 ext4_lock_group(sb, group);
3947 already = 0;
3948 for (i = 0; i < clen; i++)
3949 if (!mb_test_bit(blkoff + i, bitmap_bh->b_data) ==
3950 !state)
3951 already++;
8016e29f 3952
bfdc502a
RH
3953 clen_changed = clen - already;
3954 if (state)
123e3016 3955 mb_set_bits(bitmap_bh->b_data, blkoff, clen);
bfdc502a 3956 else
bd8247ee 3957 mb_clear_bits(bitmap_bh->b_data, blkoff, clen);
bfdc502a
RH
3958 if (ext4_has_group_desc_csum(sb) &&
3959 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3960 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3961 ext4_free_group_clusters_set(sb, gdp,
3962 ext4_free_clusters_after_init(sb, group, gdp));
3963 }
3964 if (state)
3965 clen = ext4_free_group_clusters(sb, gdp) - clen_changed;
3966 else
3967 clen = ext4_free_group_clusters(sb, gdp) + clen_changed;
8016e29f 3968
bfdc502a
RH
3969 ext4_free_group_clusters_set(sb, gdp, clen);
3970 ext4_block_bitmap_csum_set(sb, group, gdp, bitmap_bh);
3971 ext4_group_desc_csum_set(sb, group, gdp);
8016e29f 3972
bfdc502a 3973 ext4_unlock_group(sb, group);
8016e29f 3974
bfdc502a
RH
3975 if (sbi->s_log_groups_per_flex) {
3976 ext4_group_t flex_group = ext4_flex_group(sbi, group);
3977 struct flex_groups *fg = sbi_array_rcu_deref(sbi,
3978 s_flex_groups, flex_group);
8016e29f 3979
bfdc502a
RH
3980 if (state)
3981 atomic64_sub(clen_changed, &fg->free_clusters);
3982 else
3983 atomic64_add(clen_changed, &fg->free_clusters);
3984
3985 }
3986
3987 err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
3988 if (err)
3989 break;
3990 sync_dirty_buffer(bitmap_bh);
3991 err = ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
3992 sync_dirty_buffer(gdp_bh);
3993 if (err)
3994 break;
3995
3996 block += thisgrp_len;
3997 len -= thisgrp_len;
3998 brelse(bitmap_bh);
3999 BUG_ON(len < 0);
8016e29f
HS
4000 }
4001
8016e29f 4002 if (err)
bfdc502a 4003 brelse(bitmap_bh);
8016e29f
HS
4004}
4005
c9de560d
AT
4006/*
4007 * here we normalize request for locality group
d7a1fee1
DE
4008 * Group request are normalized to s_mb_group_prealloc, which goes to
4009 * s_strip if we set the same via mount option.
4010 * s_mb_group_prealloc can be configured via
b713a5ec 4011 * /sys/fs/ext4/<partition>/mb_group_prealloc
c9de560d
AT
4012 *
4013 * XXX: should we try to preallocate more than the group has now?
4014 */
4015static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
4016{
4017 struct super_block *sb = ac->ac_sb;
4018 struct ext4_locality_group *lg = ac->ac_lg;
4019
4020 BUG_ON(lg == NULL);
d7a1fee1 4021 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
d3df1453 4022 mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
c9de560d
AT
4023}
4024
4025/*
4026 * Normalization means making request better in terms of
4027 * size and alignment
4028 */
4ddfef7b
ES
4029static noinline_for_stack void
4030ext4_mb_normalize_request(struct ext4_allocation_context *ac,
c9de560d
AT
4031 struct ext4_allocation_request *ar)
4032{
53accfa9 4033 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
c9de560d
AT
4034 int bsbits, max;
4035 ext4_lblk_t end;
1592d2c5
CW
4036 loff_t size, start_off;
4037 loff_t orig_size __maybe_unused;
5a0790c2 4038 ext4_lblk_t start;
c9de560d 4039 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
9a0762c5 4040 struct ext4_prealloc_space *pa;
c9de560d
AT
4041
4042 /* do normalize only data requests, metadata requests
4043 do not need preallocation */
4044 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4045 return;
4046
4047 /* sometime caller may want exact blocks */
4048 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4049 return;
4050
4051 /* caller may indicate that preallocation isn't
4052 * required (it's a tail, for example) */
4053 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
4054 return;
4055
4056 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
4057 ext4_mb_normalize_group_request(ac);
4058 return ;
4059 }
4060
4061 bsbits = ac->ac_sb->s_blocksize_bits;
4062
4063 /* first, let's learn actual file size
4064 * given current request is allocated */
53accfa9 4065 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
c9de560d
AT
4066 size = size << bsbits;
4067 if (size < i_size_read(ac->ac_inode))
4068 size = i_size_read(ac->ac_inode);
5a0790c2 4069 orig_size = size;
c9de560d 4070
1930479c
VC
4071 /* max size of free chunks */
4072 max = 2 << bsbits;
c9de560d 4073
1930479c
VC
4074#define NRL_CHECK_SIZE(req, size, max, chunk_size) \
4075 (req <= (size) || max <= (chunk_size))
c9de560d
AT
4076
4077 /* first, try to predict filesize */
4078 /* XXX: should this table be tunable? */
4079 start_off = 0;
4080 if (size <= 16 * 1024) {
4081 size = 16 * 1024;
4082 } else if (size <= 32 * 1024) {
4083 size = 32 * 1024;
4084 } else if (size <= 64 * 1024) {
4085 size = 64 * 1024;
4086 } else if (size <= 128 * 1024) {
4087 size = 128 * 1024;
4088 } else if (size <= 256 * 1024) {
4089 size = 256 * 1024;
4090 } else if (size <= 512 * 1024) {
4091 size = 512 * 1024;
4092 } else if (size <= 1024 * 1024) {
4093 size = 1024 * 1024;
1930479c 4094 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
c9de560d 4095 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
1930479c
VC
4096 (21 - bsbits)) << 21;
4097 size = 2 * 1024 * 1024;
4098 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
c9de560d
AT
4099 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4100 (22 - bsbits)) << 22;
4101 size = 4 * 1024 * 1024;
4102 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
1930479c 4103 (8<<20)>>bsbits, max, 8 * 1024)) {
c9de560d
AT
4104 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4105 (23 - bsbits)) << 23;
4106 size = 8 * 1024 * 1024;
4107 } else {
b27b1535
XW
4108 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
4109 size = (loff_t) EXT4_C2B(EXT4_SB(ac->ac_sb),
4110 ac->ac_o_ex.fe_len) << bsbits;
c9de560d 4111 }
5a0790c2
AK
4112 size = size >> bsbits;
4113 start = start_off >> bsbits;
c9de560d 4114
a08f789d
BL
4115 /*
4116 * For tiny groups (smaller than 8MB) the chosen allocation
4117 * alignment may be larger than group size. Make sure the
4118 * alignment does not move allocation to a different group which
4119 * makes mballoc fail assertions later.
4120 */
4121 start = max(start, rounddown(ac->ac_o_ex.fe_logical,
4122 (ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
4123
c9de560d
AT
4124 /* don't cover already allocated blocks in selected range */
4125 if (ar->pleft && start <= ar->lleft) {
4126 size -= ar->lleft + 1 - start;
4127 start = ar->lleft + 1;
4128 }
4129 if (ar->pright && start + size - 1 >= ar->lright)
4130 size -= start + size - ar->lright;
4131
cd648b8a
JK
4132 /*
4133 * Trim allocation request for filesystems with artificially small
4134 * groups.
4135 */
4136 if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
4137 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
4138
c9de560d
AT
4139 end = start + size;
4140
4141 /* check we don't cross already preallocated blocks */
4142 rcu_read_lock();
9a0762c5 4143 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
498e5f24 4144 ext4_lblk_t pa_end;
c9de560d 4145
c9de560d
AT
4146 if (pa->pa_deleted)
4147 continue;
4148 spin_lock(&pa->pa_lock);
4149 if (pa->pa_deleted) {
4150 spin_unlock(&pa->pa_lock);
4151 continue;
4152 }
4153
53accfa9
TT
4154 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
4155 pa->pa_len);
c9de560d
AT
4156
4157 /* PA must not overlap original request */
4158 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
4159 ac->ac_o_ex.fe_logical < pa->pa_lstart));
4160
38877f4e
ES
4161 /* skip PAs this normalized request doesn't overlap with */
4162 if (pa->pa_lstart >= end || pa_end <= start) {
c9de560d
AT
4163 spin_unlock(&pa->pa_lock);
4164 continue;
4165 }
4166 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
4167
38877f4e 4168 /* adjust start or end to be adjacent to this pa */
c9de560d
AT
4169 if (pa_end <= ac->ac_o_ex.fe_logical) {
4170 BUG_ON(pa_end < start);
4171 start = pa_end;
38877f4e 4172 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
c9de560d
AT
4173 BUG_ON(pa->pa_lstart > end);
4174 end = pa->pa_lstart;
4175 }
4176 spin_unlock(&pa->pa_lock);
4177 }
4178 rcu_read_unlock();
4179 size = end - start;
4180
4181 /* XXX: extra loop to check we really don't overlap preallocations */
4182 rcu_read_lock();
9a0762c5 4183 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
498e5f24 4184 ext4_lblk_t pa_end;
53accfa9 4185
c9de560d
AT
4186 spin_lock(&pa->pa_lock);
4187 if (pa->pa_deleted == 0) {
53accfa9
TT
4188 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
4189 pa->pa_len);
c9de560d
AT
4190 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
4191 }
4192 spin_unlock(&pa->pa_lock);
4193 }
4194 rcu_read_unlock();
4195
cf4ff938
BL
4196 /*
4197 * In this function "start" and "size" are normalized for better
4198 * alignment and length such that we could preallocate more blocks.
4199 * This normalization is done such that original request of
4200 * ac->ac_o_ex.fe_logical & fe_len should always lie within "start" and
4201 * "size" boundaries.
4202 * (Note fe_len can be relaxed since FS block allocation API does not
4203 * provide gurantee on number of contiguous blocks allocation since that
4204 * depends upon free space left, etc).
4205 * In case of inode pa, later we use the allocated blocks
4206 * [pa_start + fe_logical - pa_lstart, fe_len/size] from the preallocated
4207 * range of goal/best blocks [start, size] to put it at the
4208 * ac_o_ex.fe_logical extent of this inode.
4209 * (See ext4_mb_use_inode_pa() for more details)
4210 */
4211 if (start + size <= ac->ac_o_ex.fe_logical ||
c9de560d 4212 start > ac->ac_o_ex.fe_logical) {
9d8b9ec4
TT
4213 ext4_msg(ac->ac_sb, KERN_ERR,
4214 "start %lu, size %lu, fe_logical %lu",
4215 (unsigned long) start, (unsigned long) size,
4216 (unsigned long) ac->ac_o_ex.fe_logical);
dfe076c1 4217 BUG();
c9de560d 4218 }
b5b60778 4219 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
c9de560d
AT
4220
4221 /* now prepare goal request */
4222
4223 /* XXX: is it better to align blocks WRT to logical
4224 * placement or satisfy big request as is */
4225 ac->ac_g_ex.fe_logical = start;
53accfa9 4226 ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
c9de560d
AT
4227
4228 /* define goal start in order to merge */
4229 if (ar->pright && (ar->lright == (start + size))) {
4230 /* merge to the right */
4231 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
4232 &ac->ac_f_ex.fe_group,
4233 &ac->ac_f_ex.fe_start);
4234 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4235 }
4236 if (ar->pleft && (ar->lleft + 1 == start)) {
4237 /* merge to the left */
4238 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
4239 &ac->ac_f_ex.fe_group,
4240 &ac->ac_f_ex.fe_start);
4241 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4242 }
4243
d3df1453
RH
4244 mb_debug(ac->ac_sb, "goal: %lld(was %lld) blocks at %u\n", size,
4245 orig_size, start);
c9de560d
AT
4246}
4247
4248static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
4249{
4250 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4251
a6c75eaf 4252 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len >= 1) {
c9de560d
AT
4253 atomic_inc(&sbi->s_bal_reqs);
4254 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
291dae47 4255 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
c9de560d
AT
4256 atomic_inc(&sbi->s_bal_success);
4257 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
a6c75eaf 4258 atomic_add(ac->ac_groups_scanned, &sbi->s_bal_groups_scanned);
c9de560d
AT
4259 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
4260 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
4261 atomic_inc(&sbi->s_bal_goals);
4262 if (ac->ac_found > sbi->s_mb_max_to_scan)
4263 atomic_inc(&sbi->s_bal_breaks);
4264 }
4265
296c355c
TT
4266 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
4267 trace_ext4_mballoc_alloc(ac);
4268 else
4269 trace_ext4_mballoc_prealloc(ac);
c9de560d
AT
4270}
4271
b844167e
CW
4272/*
4273 * Called on failure; free up any blocks from the inode PA for this
4274 * context. We don't need this for MB_GROUP_PA because we only change
4275 * pa_free in ext4_mb_release_context(), but on failure, we've already
4276 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
4277 */
4278static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
4279{
4280 struct ext4_prealloc_space *pa = ac->ac_pa;
86f0afd4
TT
4281 struct ext4_buddy e4b;
4282 int err;
b844167e 4283
86f0afd4 4284 if (pa == NULL) {
c99d1e6e
TT
4285 if (ac->ac_f_ex.fe_len == 0)
4286 return;
86f0afd4
TT
4287 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
4288 if (err) {
4289 /*
4290 * This should never happen since we pin the
4291 * pages in the ext4_allocation_context so
4292 * ext4_mb_load_buddy() should never fail.
4293 */
4294 WARN(1, "mb_load_buddy failed (%d)", err);
4295 return;
4296 }
4297 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
4298 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
4299 ac->ac_f_ex.fe_len);
4300 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
c99d1e6e 4301 ext4_mb_unload_buddy(&e4b);
86f0afd4
TT
4302 return;
4303 }
4304 if (pa->pa_type == MB_INODE_PA)
400db9d3 4305 pa->pa_free += ac->ac_b_ex.fe_len;
b844167e
CW
4306}
4307
c9de560d
AT
4308/*
4309 * use blocks preallocated to inode
4310 */
4311static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
4312 struct ext4_prealloc_space *pa)
4313{
53accfa9 4314 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
c9de560d
AT
4315 ext4_fsblk_t start;
4316 ext4_fsblk_t end;
4317 int len;
4318
4319 /* found preallocated blocks, use them */
4320 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
53accfa9
TT
4321 end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
4322 start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
4323 len = EXT4_NUM_B2C(sbi, end - start);
c9de560d
AT
4324 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
4325 &ac->ac_b_ex.fe_start);
4326 ac->ac_b_ex.fe_len = len;
4327 ac->ac_status = AC_STATUS_FOUND;
4328 ac->ac_pa = pa;
4329
4330 BUG_ON(start < pa->pa_pstart);
53accfa9 4331 BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
c9de560d
AT
4332 BUG_ON(pa->pa_free < len);
4333 pa->pa_free -= len;
4334
d3df1453 4335 mb_debug(ac->ac_sb, "use %llu/%d from inode pa %p\n", start, len, pa);
c9de560d
AT
4336}
4337
4338/*
4339 * use blocks preallocated to locality group
4340 */
4341static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
4342 struct ext4_prealloc_space *pa)
4343{
03cddb80 4344 unsigned int len = ac->ac_o_ex.fe_len;
6be2ded1 4345
c9de560d
AT
4346 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
4347 &ac->ac_b_ex.fe_group,
4348 &ac->ac_b_ex.fe_start);
4349 ac->ac_b_ex.fe_len = len;
4350 ac->ac_status = AC_STATUS_FOUND;
4351 ac->ac_pa = pa;
4352
4353 /* we don't correct pa_pstart or pa_plen here to avoid
26346ff6 4354 * possible race when the group is being loaded concurrently
c9de560d 4355 * instead we correct pa later, after blocks are marked
26346ff6
AK
4356 * in on-disk bitmap -- see ext4_mb_release_context()
4357 * Other CPUs are prevented from allocating from this pa by lg_mutex
c9de560d 4358 */
d3df1453
RH
4359 mb_debug(ac->ac_sb, "use %u/%u from group pa %p\n",
4360 pa->pa_lstart-len, len, pa);
c9de560d
AT
4361}
4362
5e745b04
AK
4363/*
4364 * Return the prealloc space that have minimal distance
4365 * from the goal block. @cpa is the prealloc
4366 * space that is having currently known minimal distance
4367 * from the goal block.
4368 */
4369static struct ext4_prealloc_space *
4370ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
4371 struct ext4_prealloc_space *pa,
4372 struct ext4_prealloc_space *cpa)
4373{
4374 ext4_fsblk_t cur_distance, new_distance;
4375
4376 if (cpa == NULL) {
4377 atomic_inc(&pa->pa_count);
4378 return pa;
4379 }
79211c8e
AM
4380 cur_distance = abs(goal_block - cpa->pa_pstart);
4381 new_distance = abs(goal_block - pa->pa_pstart);
5e745b04 4382
5a54b2f1 4383 if (cur_distance <= new_distance)
5e745b04
AK
4384 return cpa;
4385
4386 /* drop the previous reference */
4387 atomic_dec(&cpa->pa_count);
4388 atomic_inc(&pa->pa_count);
4389 return pa;
4390}
4391
c9de560d
AT
4392/*
4393 * search goal blocks in preallocated space
4394 */
4fca8f07 4395static noinline_for_stack bool
4ddfef7b 4396ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
c9de560d 4397{
53accfa9 4398 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
6be2ded1 4399 int order, i;
c9de560d
AT
4400 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4401 struct ext4_locality_group *lg;
5e745b04
AK
4402 struct ext4_prealloc_space *pa, *cpa = NULL;
4403 ext4_fsblk_t goal_block;
c9de560d
AT
4404
4405 /* only data can be preallocated */
4406 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4fca8f07 4407 return false;
c9de560d
AT
4408
4409 /* first, try per-file preallocation */
4410 rcu_read_lock();
9a0762c5 4411 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
c9de560d
AT
4412
4413 /* all fields in this condition don't change,
4414 * so we can skip locking for them */
4415 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
53accfa9
TT
4416 ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
4417 EXT4_C2B(sbi, pa->pa_len)))
c9de560d
AT
4418 continue;
4419
fb0a387d 4420 /* non-extent files can't have physical blocks past 2^32 */
12e9b892 4421 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
53accfa9
TT
4422 (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
4423 EXT4_MAX_BLOCK_FILE_PHYS))
fb0a387d
ES
4424 continue;
4425
c9de560d
AT
4426 /* found preallocated blocks, use them */
4427 spin_lock(&pa->pa_lock);
4428 if (pa->pa_deleted == 0 && pa->pa_free) {
4429 atomic_inc(&pa->pa_count);
4430 ext4_mb_use_inode_pa(ac, pa);
4431 spin_unlock(&pa->pa_lock);
4432 ac->ac_criteria = 10;
4433 rcu_read_unlock();
4fca8f07 4434 return true;
c9de560d
AT
4435 }
4436 spin_unlock(&pa->pa_lock);
4437 }
4438 rcu_read_unlock();
4439
4440 /* can we use group allocation? */
4441 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
4fca8f07 4442 return false;
c9de560d
AT
4443
4444 /* inode may have no locality group for some reason */
4445 lg = ac->ac_lg;
4446 if (lg == NULL)
4fca8f07 4447 return false;
6be2ded1
AK
4448 order = fls(ac->ac_o_ex.fe_len) - 1;
4449 if (order > PREALLOC_TB_SIZE - 1)
4450 /* The max size of hash table is PREALLOC_TB_SIZE */
4451 order = PREALLOC_TB_SIZE - 1;
4452
bda00de7 4453 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
5e745b04
AK
4454 /*
4455 * search for the prealloc space that is having
4456 * minimal distance from the goal block.
4457 */
6be2ded1
AK
4458 for (i = order; i < PREALLOC_TB_SIZE; i++) {
4459 rcu_read_lock();
4460 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
4461 pa_inode_list) {
4462 spin_lock(&pa->pa_lock);
4463 if (pa->pa_deleted == 0 &&
4464 pa->pa_free >= ac->ac_o_ex.fe_len) {
5e745b04
AK
4465
4466 cpa = ext4_mb_check_group_pa(goal_block,
4467 pa, cpa);
6be2ded1 4468 }
c9de560d 4469 spin_unlock(&pa->pa_lock);
c9de560d 4470 }
6be2ded1 4471 rcu_read_unlock();
c9de560d 4472 }
5e745b04
AK
4473 if (cpa) {
4474 ext4_mb_use_group_pa(ac, cpa);
4475 ac->ac_criteria = 20;
4fca8f07 4476 return true;
5e745b04 4477 }
4fca8f07 4478 return false;
c9de560d
AT
4479}
4480
7a2fcbf7
AK
4481/*
4482 * the function goes through all block freed in the group
4483 * but not yet committed and marks them used in in-core bitmap.
4484 * buddy must be generated from this bitmap
955ce5f5 4485 * Need to be called with the ext4 group lock held
7a2fcbf7
AK
4486 */
4487static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
4488 ext4_group_t group)
4489{
4490 struct rb_node *n;
4491 struct ext4_group_info *grp;
4492 struct ext4_free_data *entry;
4493
4494 grp = ext4_get_group_info(sb, group);
4495 n = rb_first(&(grp->bb_free_root));
4496
4497 while (n) {
18aadd47 4498 entry = rb_entry(n, struct ext4_free_data, efd_node);
123e3016 4499 mb_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
7a2fcbf7
AK
4500 n = rb_next(n);
4501 }
4502 return;
4503}
4504
c9de560d
AT
4505/*
4506 * the function goes through all preallocation in this group and marks them
4507 * used in in-core bitmap. buddy must be generated from this bitmap
955ce5f5 4508 * Need to be called with ext4 group lock held
c9de560d 4509 */
089ceecc
ES
4510static noinline_for_stack
4511void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
c9de560d
AT
4512 ext4_group_t group)
4513{
4514 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
4515 struct ext4_prealloc_space *pa;
4516 struct list_head *cur;
4517 ext4_group_t groupnr;
4518 ext4_grpblk_t start;
4519 int preallocated = 0;
c9de560d
AT
4520 int len;
4521
4522 /* all form of preallocation discards first load group,
4523 * so the only competing code is preallocation use.
4524 * we don't need any locking here
4525 * notice we do NOT ignore preallocations with pa_deleted
4526 * otherwise we could leave used blocks available for
4527 * allocation in buddy when concurrent ext4_mb_put_pa()
4528 * is dropping preallocation
4529 */
4530 list_for_each(cur, &grp->bb_prealloc_list) {
4531 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
4532 spin_lock(&pa->pa_lock);
4533 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4534 &groupnr, &start);
4535 len = pa->pa_len;
4536 spin_unlock(&pa->pa_lock);
4537 if (unlikely(len == 0))
4538 continue;
4539 BUG_ON(groupnr != group);
123e3016 4540 mb_set_bits(bitmap, start, len);
c9de560d 4541 preallocated += len;
c9de560d 4542 }
d3df1453 4543 mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
c9de560d
AT
4544}
4545
27bc446e 4546static void ext4_mb_mark_pa_deleted(struct super_block *sb,
4547 struct ext4_prealloc_space *pa)
4548{
4549 struct ext4_inode_info *ei;
4550
4551 if (pa->pa_deleted) {
4552 ext4_warning(sb, "deleted pa, type:%d, pblk:%llu, lblk:%u, len:%d\n",
4553 pa->pa_type, pa->pa_pstart, pa->pa_lstart,
4554 pa->pa_len);
4555 return;
4556 }
4557
4558 pa->pa_deleted = 1;
4559
4560 if (pa->pa_type == MB_INODE_PA) {
4561 ei = EXT4_I(pa->pa_inode);
4562 atomic_dec(&ei->i_prealloc_active);
4563 }
4564}
4565
c9de560d
AT
4566static void ext4_mb_pa_callback(struct rcu_head *head)
4567{
4568 struct ext4_prealloc_space *pa;
4569 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
4e8d2139
JR
4570
4571 BUG_ON(atomic_read(&pa->pa_count));
4572 BUG_ON(pa->pa_deleted == 0);
c9de560d
AT
4573 kmem_cache_free(ext4_pspace_cachep, pa);
4574}
4575
4576/*
4577 * drops a reference to preallocated space descriptor
4578 * if this was the last reference and the space is consumed
4579 */
4580static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
4581 struct super_block *sb, struct ext4_prealloc_space *pa)
4582{
a9df9a49 4583 ext4_group_t grp;
d33a1976 4584 ext4_fsblk_t grp_blk;
c9de560d 4585
c9de560d
AT
4586 /* in this short window concurrent discard can set pa_deleted */
4587 spin_lock(&pa->pa_lock);
4e8d2139
JR
4588 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
4589 spin_unlock(&pa->pa_lock);
4590 return;
4591 }
4592
c9de560d
AT
4593 if (pa->pa_deleted == 1) {
4594 spin_unlock(&pa->pa_lock);
4595 return;
4596 }
4597
27bc446e 4598 ext4_mb_mark_pa_deleted(sb, pa);
c9de560d
AT
4599 spin_unlock(&pa->pa_lock);
4600
d33a1976 4601 grp_blk = pa->pa_pstart;
60e6679e 4602 /*
cc0fb9ad
AK
4603 * If doing group-based preallocation, pa_pstart may be in the
4604 * next group when pa is used up
4605 */
4606 if (pa->pa_type == MB_GROUP_PA)
d33a1976
ES
4607 grp_blk--;
4608
bd86298e 4609 grp = ext4_get_group_number(sb, grp_blk);
c9de560d
AT
4610
4611 /*
4612 * possible race:
4613 *
4614 * P1 (buddy init) P2 (regular allocation)
4615 * find block B in PA
4616 * copy on-disk bitmap to buddy
4617 * mark B in on-disk bitmap
4618 * drop PA from group
4619 * mark all PAs in buddy
4620 *
4621 * thus, P1 initializes buddy with B available. to prevent this
4622 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
4623 * against that pair
4624 */
4625 ext4_lock_group(sb, grp);
4626 list_del(&pa->pa_group_list);
4627 ext4_unlock_group(sb, grp);
4628
4629 spin_lock(pa->pa_obj_lock);
4630 list_del_rcu(&pa->pa_inode_list);
4631 spin_unlock(pa->pa_obj_lock);
4632
4633 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4634}
4635
4636/*
4637 * creates new preallocated space for given inode
4638 */
53f86b17 4639static noinline_for_stack void
4ddfef7b 4640ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
c9de560d
AT
4641{
4642 struct super_block *sb = ac->ac_sb;
53accfa9 4643 struct ext4_sb_info *sbi = EXT4_SB(sb);
c9de560d
AT
4644 struct ext4_prealloc_space *pa;
4645 struct ext4_group_info *grp;
4646 struct ext4_inode_info *ei;
4647
4648 /* preallocate only when found space is larger then requested */
4649 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
4650 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
4651 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
53f86b17 4652 BUG_ON(ac->ac_pa == NULL);
c9de560d 4653
53f86b17 4654 pa = ac->ac_pa;
c9de560d
AT
4655
4656 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
4657 int winl;
4658 int wins;
4659 int win;
4660 int offs;
4661
4662 /* we can't allocate as much as normalizer wants.
4663 * so, found space must get proper lstart
4664 * to cover original request */
4665 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
4666 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
4667
4668 /* we're limited by original request in that
4669 * logical block must be covered any way
4670 * winl is window we can move our chunk within */
4671 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
4672
4673 /* also, we should cover whole original request */
53accfa9 4674 wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
c9de560d
AT
4675
4676 /* the smallest one defines real window */
4677 win = min(winl, wins);
4678
53accfa9
TT
4679 offs = ac->ac_o_ex.fe_logical %
4680 EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
c9de560d
AT
4681 if (offs && offs < win)
4682 win = offs;
4683
53accfa9 4684 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
810da240 4685 EXT4_NUM_B2C(sbi, win);
c9de560d
AT
4686 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
4687 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
4688 }
4689
4690 /* preallocation can change ac_b_ex, thus we store actually
4691 * allocated blocks for history */
4692 ac->ac_f_ex = ac->ac_b_ex;
4693
4694 pa->pa_lstart = ac->ac_b_ex.fe_logical;
4695 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4696 pa->pa_len = ac->ac_b_ex.fe_len;
4697 pa->pa_free = pa->pa_len;
c9de560d 4698 spin_lock_init(&pa->pa_lock);
d794bf8e
AK
4699 INIT_LIST_HEAD(&pa->pa_inode_list);
4700 INIT_LIST_HEAD(&pa->pa_group_list);
c9de560d 4701 pa->pa_deleted = 0;
cc0fb9ad 4702 pa->pa_type = MB_INODE_PA;
c9de560d 4703
d3df1453
RH
4704 mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
4705 pa->pa_len, pa->pa_lstart);
9bffad1e 4706 trace_ext4_mb_new_inode_pa(ac, pa);
c9de560d
AT
4707
4708 ext4_mb_use_inode_pa(ac, pa);
53accfa9 4709 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
c9de560d
AT
4710
4711 ei = EXT4_I(ac->ac_inode);
4712 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
4713
4714 pa->pa_obj_lock = &ei->i_prealloc_lock;
4715 pa->pa_inode = ac->ac_inode;
4716
c9de560d 4717 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
c9de560d
AT
4718
4719 spin_lock(pa->pa_obj_lock);
4720 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
4721 spin_unlock(pa->pa_obj_lock);
27bc446e 4722 atomic_inc(&ei->i_prealloc_active);
c9de560d
AT
4723}
4724
4725/*
4726 * creates new preallocated space for locality group inodes belongs to
4727 */
53f86b17 4728static noinline_for_stack void
4ddfef7b 4729ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
c9de560d
AT
4730{
4731 struct super_block *sb = ac->ac_sb;
4732 struct ext4_locality_group *lg;
4733 struct ext4_prealloc_space *pa;
4734 struct ext4_group_info *grp;
4735
4736 /* preallocate only when found space is larger then requested */
4737 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
4738 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
4739 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
53f86b17 4740 BUG_ON(ac->ac_pa == NULL);
c9de560d 4741
53f86b17 4742 pa = ac->ac_pa;
c9de560d
AT
4743
4744 /* preallocation can change ac_b_ex, thus we store actually
4745 * allocated blocks for history */
4746 ac->ac_f_ex = ac->ac_b_ex;
4747
4748 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4749 pa->pa_lstart = pa->pa_pstart;
4750 pa->pa_len = ac->ac_b_ex.fe_len;
4751 pa->pa_free = pa->pa_len;
c9de560d 4752 spin_lock_init(&pa->pa_lock);
6be2ded1 4753 INIT_LIST_HEAD(&pa->pa_inode_list);
d794bf8e 4754 INIT_LIST_HEAD(&pa->pa_group_list);
c9de560d 4755 pa->pa_deleted = 0;
cc0fb9ad 4756 pa->pa_type = MB_GROUP_PA;
c9de560d 4757
d3df1453
RH
4758 mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
4759 pa->pa_len, pa->pa_lstart);
9bffad1e 4760 trace_ext4_mb_new_group_pa(ac, pa);
c9de560d
AT
4761
4762 ext4_mb_use_group_pa(ac, pa);
4763 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
4764
4765 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
4766 lg = ac->ac_lg;
4767 BUG_ON(lg == NULL);
4768
4769 pa->pa_obj_lock = &lg->lg_prealloc_lock;
4770 pa->pa_inode = NULL;
4771
c9de560d 4772 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
c9de560d 4773
6be2ded1
AK
4774 /*
4775 * We will later add the new pa to the right bucket
4776 * after updating the pa_free in ext4_mb_release_context
4777 */
c9de560d
AT
4778}
4779
53f86b17 4780static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
c9de560d 4781{
c9de560d 4782 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
53f86b17 4783 ext4_mb_new_group_pa(ac);
c9de560d 4784 else
53f86b17 4785 ext4_mb_new_inode_pa(ac);
c9de560d
AT
4786}
4787
4788/*
4789 * finds all unused blocks in on-disk bitmap, frees them in
4790 * in-core bitmap and buddy.
4791 * @pa must be unlinked from inode and group lists, so that
4792 * nobody else can find/use it.
4793 * the caller MUST hold group/inode locks.
4794 * TODO: optimize the case when there are no in-core structures yet
4795 */
4ddfef7b
ES
4796static noinline_for_stack int
4797ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3e1e5f50 4798 struct ext4_prealloc_space *pa)
c9de560d 4799{
c9de560d
AT
4800 struct super_block *sb = e4b->bd_sb;
4801 struct ext4_sb_info *sbi = EXT4_SB(sb);
498e5f24
TT
4802 unsigned int end;
4803 unsigned int next;
c9de560d
AT
4804 ext4_group_t group;
4805 ext4_grpblk_t bit;
ba80b101 4806 unsigned long long grp_blk_start;
c9de560d
AT
4807 int free = 0;
4808
4809 BUG_ON(pa->pa_deleted == 0);
4810 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
53accfa9 4811 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
c9de560d
AT
4812 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
4813 end = bit + pa->pa_len;
4814
c9de560d 4815 while (bit < end) {
ffad0a44 4816 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
c9de560d
AT
4817 if (bit >= end)
4818 break;
ffad0a44 4819 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
d3df1453 4820 mb_debug(sb, "free preallocated %u/%u in group %u\n",
5a0790c2
AK
4821 (unsigned) ext4_group_first_block_no(sb, group) + bit,
4822 (unsigned) next - bit, (unsigned) group);
c9de560d
AT
4823 free += next - bit;
4824
3e1e5f50 4825 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
53accfa9
TT
4826 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
4827 EXT4_C2B(sbi, bit)),
a9c667f8 4828 next - bit);
c9de560d
AT
4829 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
4830 bit = next + 1;
4831 }
4832 if (free != pa->pa_free) {
9d8b9ec4 4833 ext4_msg(e4b->bd_sb, KERN_CRIT,
36bad423 4834 "pa %p: logic %lu, phys. %lu, len %d",
9d8b9ec4
TT
4835 pa, (unsigned long) pa->pa_lstart,
4836 (unsigned long) pa->pa_pstart,
36bad423 4837 pa->pa_len);
e29136f8 4838 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
5d1b1b3f 4839 free, pa->pa_free);
e56eb659
AK
4840 /*
4841 * pa is already deleted so we use the value obtained
4842 * from the bitmap and continue.
4843 */
c9de560d 4844 }
c9de560d
AT
4845 atomic_add(free, &sbi->s_mb_discarded);
4846
863c37fc 4847 return 0;
c9de560d
AT
4848}
4849
4ddfef7b
ES
4850static noinline_for_stack int
4851ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3e1e5f50 4852 struct ext4_prealloc_space *pa)
c9de560d 4853{
c9de560d
AT
4854 struct super_block *sb = e4b->bd_sb;
4855 ext4_group_t group;
4856 ext4_grpblk_t bit;
4857
60e07cf5 4858 trace_ext4_mb_release_group_pa(sb, pa);
c9de560d
AT
4859 BUG_ON(pa->pa_deleted == 0);
4860 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
4861 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
4862 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
4863 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3e1e5f50 4864 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
c9de560d
AT
4865
4866 return 0;
4867}
4868
4869/*
4870 * releases all preallocations in given group
4871 *
4872 * first, we need to decide discard policy:
4873 * - when do we discard
4874 * 1) ENOSPC
4875 * - how many do we discard
4876 * 1) how many requested
4877 */
4ddfef7b
ES
4878static noinline_for_stack int
4879ext4_mb_discard_group_preallocations(struct super_block *sb,
8c80fb31 4880 ext4_group_t group, int *busy)
c9de560d
AT
4881{
4882 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
4883 struct buffer_head *bitmap_bh = NULL;
4884 struct ext4_prealloc_space *pa, *tmp;
4885 struct list_head list;
4886 struct ext4_buddy e4b;
4887 int err;
8c80fb31 4888 int free = 0;
c9de560d 4889
d3df1453 4890 mb_debug(sb, "discard preallocation for group %u\n", group);
c9de560d 4891 if (list_empty(&grp->bb_prealloc_list))
bbc4ec77 4892 goto out_dbg;
c9de560d 4893
574ca174 4894 bitmap_bh = ext4_read_block_bitmap(sb, group);
9008a58e
DW
4895 if (IS_ERR(bitmap_bh)) {
4896 err = PTR_ERR(bitmap_bh);
54d3adbc
TT
4897 ext4_error_err(sb, -err,
4898 "Error %d reading block bitmap for %u",
4899 err, group);
bbc4ec77 4900 goto out_dbg;
c9de560d
AT
4901 }
4902
4903 err = ext4_mb_load_buddy(sb, group, &e4b);
ce89f46c 4904 if (err) {
9651e6b2
KK
4905 ext4_warning(sb, "Error %d loading buddy information for %u",
4906 err, group);
ce89f46c 4907 put_bh(bitmap_bh);
bbc4ec77 4908 goto out_dbg;
ce89f46c 4909 }
c9de560d 4910
c9de560d 4911 INIT_LIST_HEAD(&list);
c9de560d
AT
4912 ext4_lock_group(sb, group);
4913 list_for_each_entry_safe(pa, tmp,
4914 &grp->bb_prealloc_list, pa_group_list) {
4915 spin_lock(&pa->pa_lock);
4916 if (atomic_read(&pa->pa_count)) {
4917 spin_unlock(&pa->pa_lock);
8c80fb31 4918 *busy = 1;
c9de560d
AT
4919 continue;
4920 }
4921 if (pa->pa_deleted) {
4922 spin_unlock(&pa->pa_lock);
4923 continue;
4924 }
4925
4926 /* seems this one can be freed ... */
27bc446e 4927 ext4_mb_mark_pa_deleted(sb, pa);
c9de560d 4928
70022da8
YB
4929 if (!free)
4930 this_cpu_inc(discard_pa_seq);
4931
c9de560d
AT
4932 /* we can trust pa_free ... */
4933 free += pa->pa_free;
4934
4935 spin_unlock(&pa->pa_lock);
4936
4937 list_del(&pa->pa_group_list);
4938 list_add(&pa->u.pa_tmp_list, &list);
4939 }
4940
c9de560d
AT
4941 /* now free all selected PAs */
4942 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4943
4944 /* remove from object (inode or locality group) */
4945 spin_lock(pa->pa_obj_lock);
4946 list_del_rcu(&pa->pa_inode_list);
4947 spin_unlock(pa->pa_obj_lock);
4948
cc0fb9ad 4949 if (pa->pa_type == MB_GROUP_PA)
3e1e5f50 4950 ext4_mb_release_group_pa(&e4b, pa);
c9de560d 4951 else
3e1e5f50 4952 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
c9de560d
AT
4953
4954 list_del(&pa->u.pa_tmp_list);
4955 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4956 }
4957
c9de560d 4958 ext4_unlock_group(sb, group);
e39e07fd 4959 ext4_mb_unload_buddy(&e4b);
c9de560d 4960 put_bh(bitmap_bh);
bbc4ec77 4961out_dbg:
d3df1453 4962 mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
8c80fb31
CX
4963 free, group, grp->bb_free);
4964 return free;
c9de560d
AT
4965}
4966
4967/*
4968 * releases all non-used preallocated blocks for given inode
4969 *
4970 * It's important to discard preallocations under i_data_sem
4971 * We don't want another block to be served from the prealloc
4972 * space when we are discarding the inode prealloc space.
4973 *
4974 * FIXME!! Make sure it is valid at all the call sites
4975 */
27bc446e 4976void ext4_discard_preallocations(struct inode *inode, unsigned int needed)
c9de560d
AT
4977{
4978 struct ext4_inode_info *ei = EXT4_I(inode);
4979 struct super_block *sb = inode->i_sb;
4980 struct buffer_head *bitmap_bh = NULL;
4981 struct ext4_prealloc_space *pa, *tmp;
4982 ext4_group_t group = 0;
4983 struct list_head list;
4984 struct ext4_buddy e4b;
4985 int err;
4986
c2ea3fde 4987 if (!S_ISREG(inode->i_mode)) {
c9de560d
AT
4988 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4989 return;
4990 }
4991
8016e29f
HS
4992 if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
4993 return;
4994
d3df1453
RH
4995 mb_debug(sb, "discard preallocation for inode %lu\n",
4996 inode->i_ino);
27bc446e 4997 trace_ext4_discard_preallocations(inode,
4998 atomic_read(&ei->i_prealloc_active), needed);
c9de560d
AT
4999
5000 INIT_LIST_HEAD(&list);
5001
27bc446e 5002 if (needed == 0)
5003 needed = UINT_MAX;
5004
c9de560d
AT
5005repeat:
5006 /* first, collect all pa's in the inode */
5007 spin_lock(&ei->i_prealloc_lock);
27bc446e 5008 while (!list_empty(&ei->i_prealloc_list) && needed) {
5009 pa = list_entry(ei->i_prealloc_list.prev,
c9de560d
AT
5010 struct ext4_prealloc_space, pa_inode_list);
5011 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
5012 spin_lock(&pa->pa_lock);
5013 if (atomic_read(&pa->pa_count)) {
5014 /* this shouldn't happen often - nobody should
5015 * use preallocation while we're discarding it */
5016 spin_unlock(&pa->pa_lock);
5017 spin_unlock(&ei->i_prealloc_lock);
9d8b9ec4
TT
5018 ext4_msg(sb, KERN_ERR,
5019 "uh-oh! used pa while discarding");
c9de560d
AT
5020 WARN_ON(1);
5021 schedule_timeout_uninterruptible(HZ);
5022 goto repeat;
5023
5024 }
5025 if (pa->pa_deleted == 0) {
27bc446e 5026 ext4_mb_mark_pa_deleted(sb, pa);
c9de560d
AT
5027 spin_unlock(&pa->pa_lock);
5028 list_del_rcu(&pa->pa_inode_list);
5029 list_add(&pa->u.pa_tmp_list, &list);
27bc446e 5030 needed--;
c9de560d
AT
5031 continue;
5032 }
5033
5034 /* someone is deleting pa right now */
5035 spin_unlock(&pa->pa_lock);
5036 spin_unlock(&ei->i_prealloc_lock);
5037
5038 /* we have to wait here because pa_deleted
5039 * doesn't mean pa is already unlinked from
5040 * the list. as we might be called from
5041 * ->clear_inode() the inode will get freed
5042 * and concurrent thread which is unlinking
5043 * pa from inode's list may access already
5044 * freed memory, bad-bad-bad */
5045
5046 /* XXX: if this happens too often, we can
5047 * add a flag to force wait only in case
5048 * of ->clear_inode(), but not in case of
5049 * regular truncate */
5050 schedule_timeout_uninterruptible(HZ);
5051 goto repeat;
5052 }
5053 spin_unlock(&ei->i_prealloc_lock);
5054
5055 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
cc0fb9ad 5056 BUG_ON(pa->pa_type != MB_INODE_PA);
bd86298e 5057 group = ext4_get_group_number(sb, pa->pa_pstart);
c9de560d 5058
9651e6b2
KK
5059 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
5060 GFP_NOFS|__GFP_NOFAIL);
ce89f46c 5061 if (err) {
54d3adbc
TT
5062 ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
5063 err, group);
ce89f46c
AK
5064 continue;
5065 }
c9de560d 5066
574ca174 5067 bitmap_bh = ext4_read_block_bitmap(sb, group);
9008a58e
DW
5068 if (IS_ERR(bitmap_bh)) {
5069 err = PTR_ERR(bitmap_bh);
54d3adbc
TT
5070 ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
5071 err, group);
e39e07fd 5072 ext4_mb_unload_buddy(&e4b);
ce89f46c 5073 continue;
c9de560d
AT
5074 }
5075
5076 ext4_lock_group(sb, group);
5077 list_del(&pa->pa_group_list);
3e1e5f50 5078 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
c9de560d
AT
5079 ext4_unlock_group(sb, group);
5080
e39e07fd 5081 ext4_mb_unload_buddy(&e4b);
c9de560d
AT
5082 put_bh(bitmap_bh);
5083
5084 list_del(&pa->u.pa_tmp_list);
5085 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5086 }
5087}
5088
53f86b17
RH
5089static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
5090{
5091 struct ext4_prealloc_space *pa;
5092
5093 BUG_ON(ext4_pspace_cachep == NULL);
5094 pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
5095 if (!pa)
5096 return -ENOMEM;
5097 atomic_set(&pa->pa_count, 1);
5098 ac->ac_pa = pa;
5099 return 0;
5100}
5101
5102static void ext4_mb_pa_free(struct ext4_allocation_context *ac)
5103{
5104 struct ext4_prealloc_space *pa = ac->ac_pa;
5105
5106 BUG_ON(!pa);
5107 ac->ac_pa = NULL;
5108 WARN_ON(!atomic_dec_and_test(&pa->pa_count));
5109 kmem_cache_free(ext4_pspace_cachep, pa);
5110}
5111
6ba495e9 5112#ifdef CONFIG_EXT4_DEBUG
e68cf40c 5113static inline void ext4_mb_show_pa(struct super_block *sb)
c9de560d 5114{
e68cf40c 5115 ext4_group_t i, ngroups;
c9de560d 5116
9b5f6c9b 5117 if (ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
e3570639
ES
5118 return;
5119
8df9675f 5120 ngroups = ext4_get_groups_count(sb);
d3df1453 5121 mb_debug(sb, "groups: ");
8df9675f 5122 for (i = 0; i < ngroups; i++) {
c9de560d
AT
5123 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
5124 struct ext4_prealloc_space *pa;
5125 ext4_grpblk_t start;
5126 struct list_head *cur;
5127 ext4_lock_group(sb, i);
5128 list_for_each(cur, &grp->bb_prealloc_list) {
5129 pa = list_entry(cur, struct ext4_prealloc_space,
5130 pa_group_list);
5131 spin_lock(&pa->pa_lock);
5132 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5133 NULL, &start);
5134 spin_unlock(&pa->pa_lock);
d3df1453
RH
5135 mb_debug(sb, "PA:%u:%d:%d\n", i, start,
5136 pa->pa_len);
c9de560d 5137 }
60bd63d1 5138 ext4_unlock_group(sb, i);
d3df1453
RH
5139 mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
5140 grp->bb_fragments);
c9de560d 5141 }
c9de560d 5142}
e68cf40c
RH
5143
5144static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5145{
5146 struct super_block *sb = ac->ac_sb;
5147
9b5f6c9b 5148 if (ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
e68cf40c
RH
5149 return;
5150
d3df1453 5151 mb_debug(sb, "Can't allocate:"
e68cf40c 5152 " Allocation context details:");
d3df1453 5153 mb_debug(sb, "status %u flags 0x%x",
e68cf40c 5154 ac->ac_status, ac->ac_flags);
d3df1453 5155 mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
e68cf40c
RH
5156 "goal %lu/%lu/%lu@%lu, "
5157 "best %lu/%lu/%lu@%lu cr %d",
5158 (unsigned long)ac->ac_o_ex.fe_group,
5159 (unsigned long)ac->ac_o_ex.fe_start,
5160 (unsigned long)ac->ac_o_ex.fe_len,
5161 (unsigned long)ac->ac_o_ex.fe_logical,
5162 (unsigned long)ac->ac_g_ex.fe_group,
5163 (unsigned long)ac->ac_g_ex.fe_start,
5164 (unsigned long)ac->ac_g_ex.fe_len,
5165 (unsigned long)ac->ac_g_ex.fe_logical,
5166 (unsigned long)ac->ac_b_ex.fe_group,
5167 (unsigned long)ac->ac_b_ex.fe_start,
5168 (unsigned long)ac->ac_b_ex.fe_len,
5169 (unsigned long)ac->ac_b_ex.fe_logical,
5170 (int)ac->ac_criteria);
d3df1453 5171 mb_debug(sb, "%u found", ac->ac_found);
e68cf40c
RH
5172 ext4_mb_show_pa(sb);
5173}
c9de560d 5174#else
e68cf40c
RH
5175static inline void ext4_mb_show_pa(struct super_block *sb)
5176{
5177 return;
5178}
c9de560d
AT
5179static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5180{
e68cf40c 5181 ext4_mb_show_pa(ac->ac_sb);
c9de560d
AT
5182 return;
5183}
5184#endif
5185
5186/*
5187 * We use locality group preallocation for small size file. The size of the
5188 * file is determined by the current size or the resulting size after
5189 * allocation which ever is larger
5190 *
b713a5ec 5191 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
c9de560d
AT
5192 */
5193static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
5194{
5195 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
5196 int bsbits = ac->ac_sb->s_blocksize_bits;
5197 loff_t size, isize;
a9f2a293 5198 bool inode_pa_eligible, group_pa_eligible;
c9de560d
AT
5199
5200 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
5201 return;
5202
4ba74d00
TT
5203 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
5204 return;
5205
a9f2a293
JK
5206 group_pa_eligible = sbi->s_mb_group_prealloc > 0;
5207 inode_pa_eligible = true;
53accfa9 5208 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
50797481
TT
5209 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
5210 >> bsbits;
c9de560d 5211
a9f2a293 5212 /* No point in using inode preallocation for closed files */
82dd124c 5213 if ((size == isize) && !ext4_fs_is_busy(sbi) &&
a9f2a293
JK
5214 !inode_is_open_for_write(ac->ac_inode))
5215 inode_pa_eligible = false;
50797481 5216
71780577 5217 size = max(size, isize);
a9f2a293
JK
5218 /* Don't use group allocation for large files */
5219 if (size > sbi->s_mb_stream_request)
5220 group_pa_eligible = false;
5221
5222 if (!group_pa_eligible) {
5223 if (inode_pa_eligible)
5224 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
5225 else
5226 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
c9de560d 5227 return;
4ba74d00 5228 }
c9de560d
AT
5229
5230 BUG_ON(ac->ac_lg != NULL);
5231 /*
5232 * locality group prealloc space are per cpu. The reason for having
5233 * per cpu locality group is to reduce the contention between block
5234 * request from multiple CPUs.
5235 */
a0b6bc63 5236 ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
c9de560d
AT
5237
5238 /* we're going to use group allocation */
5239 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
5240
5241 /* serialize all allocations in the group */
5242 mutex_lock(&ac->ac_lg->lg_mutex);
5243}
5244
4ddfef7b
ES
5245static noinline_for_stack int
5246ext4_mb_initialize_context(struct ext4_allocation_context *ac,
c9de560d
AT
5247 struct ext4_allocation_request *ar)
5248{
5249 struct super_block *sb = ar->inode->i_sb;
5250 struct ext4_sb_info *sbi = EXT4_SB(sb);
5251 struct ext4_super_block *es = sbi->s_es;
5252 ext4_group_t group;
498e5f24
TT
5253 unsigned int len;
5254 ext4_fsblk_t goal;
c9de560d
AT
5255 ext4_grpblk_t block;
5256
5257 /* we can't allocate > group size */
5258 len = ar->len;
5259
5260 /* just a dirty hack to filter too big requests */
40ae3487
TT
5261 if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
5262 len = EXT4_CLUSTERS_PER_GROUP(sb);
c9de560d
AT
5263
5264 /* start searching from the goal */
5265 goal = ar->goal;
5266 if (goal < le32_to_cpu(es->s_first_data_block) ||
5267 goal >= ext4_blocks_count(es))
5268 goal = le32_to_cpu(es->s_first_data_block);
5269 ext4_get_group_no_and_offset(sb, goal, &group, &block);
5270
5271 /* set up allocation goals */
f5a44db5 5272 ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
c9de560d 5273 ac->ac_status = AC_STATUS_CONTINUE;
c9de560d
AT
5274 ac->ac_sb = sb;
5275 ac->ac_inode = ar->inode;
53accfa9 5276 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
c9de560d
AT
5277 ac->ac_o_ex.fe_group = group;
5278 ac->ac_o_ex.fe_start = block;
5279 ac->ac_o_ex.fe_len = len;
53accfa9 5280 ac->ac_g_ex = ac->ac_o_ex;
c9de560d 5281 ac->ac_flags = ar->flags;
c9de560d 5282
3cb77bd2 5283 /* we have to define context: we'll work with a file or
c9de560d
AT
5284 * locality group. this is a policy, actually */
5285 ext4_mb_group_or_file(ac);
5286
d3df1453 5287 mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
c9de560d
AT
5288 "left: %u/%u, right %u/%u to %swritable\n",
5289 (unsigned) ar->len, (unsigned) ar->logical,
5290 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
5291 (unsigned) ar->lleft, (unsigned) ar->pleft,
5292 (unsigned) ar->lright, (unsigned) ar->pright,
82dd124c 5293 inode_is_open_for_write(ar->inode) ? "" : "non-");
c9de560d
AT
5294 return 0;
5295
5296}
5297
6be2ded1
AK
5298static noinline_for_stack void
5299ext4_mb_discard_lg_preallocations(struct super_block *sb,
5300 struct ext4_locality_group *lg,
5301 int order, int total_entries)
5302{
5303 ext4_group_t group = 0;
5304 struct ext4_buddy e4b;
5305 struct list_head discard_list;
5306 struct ext4_prealloc_space *pa, *tmp;
6be2ded1 5307
d3df1453 5308 mb_debug(sb, "discard locality group preallocation\n");
6be2ded1
AK
5309
5310 INIT_LIST_HEAD(&discard_list);
6be2ded1
AK
5311
5312 spin_lock(&lg->lg_prealloc_lock);
5313 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
92e9c58c
MB
5314 pa_inode_list,
5315 lockdep_is_held(&lg->lg_prealloc_lock)) {
6be2ded1
AK
5316 spin_lock(&pa->pa_lock);
5317 if (atomic_read(&pa->pa_count)) {
5318 /*
5319 * This is the pa that we just used
5320 * for block allocation. So don't
5321 * free that
5322 */
5323 spin_unlock(&pa->pa_lock);
5324 continue;
5325 }
5326 if (pa->pa_deleted) {
5327 spin_unlock(&pa->pa_lock);
5328 continue;
5329 }
5330 /* only lg prealloc space */
cc0fb9ad 5331 BUG_ON(pa->pa_type != MB_GROUP_PA);
6be2ded1
AK
5332
5333 /* seems this one can be freed ... */
27bc446e 5334 ext4_mb_mark_pa_deleted(sb, pa);
6be2ded1
AK
5335 spin_unlock(&pa->pa_lock);
5336
5337 list_del_rcu(&pa->pa_inode_list);
5338 list_add(&pa->u.pa_tmp_list, &discard_list);
5339
5340 total_entries--;
5341 if (total_entries <= 5) {
5342 /*
5343 * we want to keep only 5 entries
5344 * allowing it to grow to 8. This
5345 * mak sure we don't call discard
5346 * soon for this list.
5347 */
5348 break;
5349 }
5350 }
5351 spin_unlock(&lg->lg_prealloc_lock);
5352
5353 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
9651e6b2 5354 int err;
6be2ded1 5355
bd86298e 5356 group = ext4_get_group_number(sb, pa->pa_pstart);
9651e6b2
KK
5357 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
5358 GFP_NOFS|__GFP_NOFAIL);
5359 if (err) {
54d3adbc
TT
5360 ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
5361 err, group);
6be2ded1
AK
5362 continue;
5363 }
5364 ext4_lock_group(sb, group);
5365 list_del(&pa->pa_group_list);
3e1e5f50 5366 ext4_mb_release_group_pa(&e4b, pa);
6be2ded1
AK
5367 ext4_unlock_group(sb, group);
5368
e39e07fd 5369 ext4_mb_unload_buddy(&e4b);
6be2ded1
AK
5370 list_del(&pa->u.pa_tmp_list);
5371 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5372 }
6be2ded1
AK
5373}
5374
5375/*
5376 * We have incremented pa_count. So it cannot be freed at this
5377 * point. Also we hold lg_mutex. So no parallel allocation is
5378 * possible from this lg. That means pa_free cannot be updated.
5379 *
5380 * A parallel ext4_mb_discard_group_preallocations is possible.
5381 * which can cause the lg_prealloc_list to be updated.
5382 */
5383
5384static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
5385{
5386 int order, added = 0, lg_prealloc_count = 1;
5387 struct super_block *sb = ac->ac_sb;
5388 struct ext4_locality_group *lg = ac->ac_lg;
5389 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
5390
5391 order = fls(pa->pa_free) - 1;
5392 if (order > PREALLOC_TB_SIZE - 1)
5393 /* The max size of hash table is PREALLOC_TB_SIZE */
5394 order = PREALLOC_TB_SIZE - 1;
5395 /* Add the prealloc space to lg */
f1167009 5396 spin_lock(&lg->lg_prealloc_lock);
6be2ded1 5397 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
92e9c58c
MB
5398 pa_inode_list,
5399 lockdep_is_held(&lg->lg_prealloc_lock)) {
6be2ded1
AK
5400 spin_lock(&tmp_pa->pa_lock);
5401 if (tmp_pa->pa_deleted) {
e7c9e3e9 5402 spin_unlock(&tmp_pa->pa_lock);
6be2ded1
AK
5403 continue;
5404 }
5405 if (!added && pa->pa_free < tmp_pa->pa_free) {
5406 /* Add to the tail of the previous entry */
5407 list_add_tail_rcu(&pa->pa_inode_list,
5408 &tmp_pa->pa_inode_list);
5409 added = 1;
5410 /*
5411 * we want to count the total
5412 * number of entries in the list
5413 */
5414 }
5415 spin_unlock(&tmp_pa->pa_lock);
5416 lg_prealloc_count++;
5417 }
5418 if (!added)
5419 list_add_tail_rcu(&pa->pa_inode_list,
5420 &lg->lg_prealloc_list[order]);
f1167009 5421 spin_unlock(&lg->lg_prealloc_lock);
6be2ded1
AK
5422
5423 /* Now trim the list to be not more than 8 elements */
5424 if (lg_prealloc_count > 8) {
5425 ext4_mb_discard_lg_preallocations(sb, lg,
f1167009 5426 order, lg_prealloc_count);
6be2ded1
AK
5427 return;
5428 }
5429 return ;
5430}
5431
27bc446e 5432/*
5433 * if per-inode prealloc list is too long, trim some PA
5434 */
5435static void ext4_mb_trim_inode_pa(struct inode *inode)
5436{
5437 struct ext4_inode_info *ei = EXT4_I(inode);
5438 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5439 int count, delta;
5440
5441 count = atomic_read(&ei->i_prealloc_active);
5442 delta = (sbi->s_mb_max_inode_prealloc >> 2) + 1;
5443 if (count > sbi->s_mb_max_inode_prealloc + delta) {
5444 count -= sbi->s_mb_max_inode_prealloc;
5445 ext4_discard_preallocations(inode, count);
5446 }
5447}
5448
c9de560d
AT
5449/*
5450 * release all resource we used in allocation
5451 */
5452static int ext4_mb_release_context(struct ext4_allocation_context *ac)
5453{
27bc446e 5454 struct inode *inode = ac->ac_inode;
5455 struct ext4_inode_info *ei = EXT4_I(inode);
53accfa9 5456 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
6be2ded1
AK
5457 struct ext4_prealloc_space *pa = ac->ac_pa;
5458 if (pa) {
cc0fb9ad 5459 if (pa->pa_type == MB_GROUP_PA) {
c9de560d 5460 /* see comment in ext4_mb_use_group_pa() */
6be2ded1 5461 spin_lock(&pa->pa_lock);
53accfa9
TT
5462 pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
5463 pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
6be2ded1
AK
5464 pa->pa_free -= ac->ac_b_ex.fe_len;
5465 pa->pa_len -= ac->ac_b_ex.fe_len;
5466 spin_unlock(&pa->pa_lock);
66d5e027 5467
5468 /*
5469 * We want to add the pa to the right bucket.
5470 * Remove it from the list and while adding
5471 * make sure the list to which we are adding
5472 * doesn't grow big.
5473 */
5474 if (likely(pa->pa_free)) {
5475 spin_lock(pa->pa_obj_lock);
5476 list_del_rcu(&pa->pa_inode_list);
5477 spin_unlock(pa->pa_obj_lock);
5478 ext4_mb_add_n_trim(ac);
5479 }
ba443916 5480 }
27bc446e 5481
5482 if (pa->pa_type == MB_INODE_PA) {
5483 /*
5484 * treat per-inode prealloc list as a lru list, then try
5485 * to trim the least recently used PA.
5486 */
5487 spin_lock(pa->pa_obj_lock);
5488 list_move(&pa->pa_inode_list, &ei->i_prealloc_list);
5489 spin_unlock(pa->pa_obj_lock);
5490 }
5491
ba443916
AK
5492 ext4_mb_put_pa(ac, ac->ac_sb, pa);
5493 }
c9de560d 5494 if (ac->ac_bitmap_page)
09cbfeaf 5495 put_page(ac->ac_bitmap_page);
c9de560d 5496 if (ac->ac_buddy_page)
09cbfeaf 5497 put_page(ac->ac_buddy_page);
c9de560d
AT
5498 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
5499 mutex_unlock(&ac->ac_lg->lg_mutex);
5500 ext4_mb_collect_stats(ac);
27bc446e 5501 ext4_mb_trim_inode_pa(inode);
c9de560d
AT
5502 return 0;
5503}
5504
5505static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
5506{
8df9675f 5507 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
c9de560d 5508 int ret;
8c80fb31
CX
5509 int freed = 0, busy = 0;
5510 int retry = 0;
c9de560d 5511
9bffad1e 5512 trace_ext4_mb_discard_preallocations(sb, needed);
8c80fb31
CX
5513
5514 if (needed == 0)
5515 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
5516 repeat:
8df9675f 5517 for (i = 0; i < ngroups && needed > 0; i++) {
8c80fb31 5518 ret = ext4_mb_discard_group_preallocations(sb, i, &busy);
c9de560d
AT
5519 freed += ret;
5520 needed -= ret;
8c80fb31
CX
5521 cond_resched();
5522 }
5523
5524 if (needed > 0 && busy && ++retry < 3) {
5525 busy = 0;
5526 goto repeat;
c9de560d
AT
5527 }
5528
5529 return freed;
5530}
5531
cf5e2ca6 5532static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
07b5b8e1 5533 struct ext4_allocation_context *ac, u64 *seq)
cf5e2ca6
RH
5534{
5535 int freed;
07b5b8e1
RH
5536 u64 seq_retry = 0;
5537 bool ret = false;
cf5e2ca6
RH
5538
5539 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
07b5b8e1
RH
5540 if (freed) {
5541 ret = true;
5542 goto out_dbg;
5543 }
5544 seq_retry = ext4_get_discard_pa_seq_sum();
99377830
RH
5545 if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
5546 ac->ac_flags |= EXT4_MB_STRICT_CHECK;
07b5b8e1
RH
5547 *seq = seq_retry;
5548 ret = true;
5549 }
5550
5551out_dbg:
5552 mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
5553 return ret;
cf5e2ca6
RH
5554}
5555
8016e29f
HS
5556static ext4_fsblk_t ext4_mb_new_blocks_simple(handle_t *handle,
5557 struct ext4_allocation_request *ar, int *errp);
5558
c9de560d
AT
5559/*
5560 * Main entry point into mballoc to allocate blocks
5561 * it tries to use preallocation first, then falls back
5562 * to usual allocation
5563 */
5564ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
6c7a120a 5565 struct ext4_allocation_request *ar, int *errp)
c9de560d 5566{
256bdb49 5567 struct ext4_allocation_context *ac = NULL;
c9de560d
AT
5568 struct ext4_sb_info *sbi;
5569 struct super_block *sb;
5570 ext4_fsblk_t block = 0;
60e58e0f 5571 unsigned int inquota = 0;
53accfa9 5572 unsigned int reserv_clstrs = 0;
07b5b8e1 5573 u64 seq;
c9de560d 5574
b10a44c3 5575 might_sleep();
c9de560d
AT
5576 sb = ar->inode->i_sb;
5577 sbi = EXT4_SB(sb);
5578
9bffad1e 5579 trace_ext4_request_blocks(ar);
8016e29f
HS
5580 if (sbi->s_mount_state & EXT4_FC_REPLAY)
5581 return ext4_mb_new_blocks_simple(handle, ar, errp);
ba80b101 5582
45dc63e7 5583 /* Allow to use superuser reservation for quota file */
02749a4c 5584 if (ext4_is_quota_file(ar->inode))
45dc63e7
DM
5585 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
5586
e3cf5d5d 5587 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
60e58e0f
MC
5588 /* Without delayed allocation we need to verify
5589 * there is enough free blocks to do block allocation
5590 * and verify allocation doesn't exceed the quota limits.
d2a17637 5591 */
55f020db 5592 while (ar->len &&
e7d5f315 5593 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
55f020db 5594
030ba6bc 5595 /* let others to free the space */
bb8b20ed 5596 cond_resched();
030ba6bc
AK
5597 ar->len = ar->len >> 1;
5598 }
5599 if (!ar->len) {
bbc4ec77 5600 ext4_mb_show_pa(sb);
a30d542a
AK
5601 *errp = -ENOSPC;
5602 return 0;
5603 }
53accfa9 5604 reserv_clstrs = ar->len;
55f020db 5605 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
53accfa9
TT
5606 dquot_alloc_block_nofail(ar->inode,
5607 EXT4_C2B(sbi, ar->len));
55f020db
AH
5608 } else {
5609 while (ar->len &&
53accfa9
TT
5610 dquot_alloc_block(ar->inode,
5611 EXT4_C2B(sbi, ar->len))) {
55f020db
AH
5612
5613 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
5614 ar->len--;
5615 }
60e58e0f
MC
5616 }
5617 inquota = ar->len;
5618 if (ar->len == 0) {
5619 *errp = -EDQUOT;
6c7a120a 5620 goto out;
60e58e0f 5621 }
07031431 5622 }
d2a17637 5623
85556c9a 5624 ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
833576b3 5625 if (!ac) {
363d4251 5626 ar->len = 0;
256bdb49 5627 *errp = -ENOMEM;
6c7a120a 5628 goto out;
256bdb49
ES
5629 }
5630
256bdb49 5631 *errp = ext4_mb_initialize_context(ac, ar);
c9de560d
AT
5632 if (*errp) {
5633 ar->len = 0;
6c7a120a 5634 goto out;
c9de560d
AT
5635 }
5636
256bdb49 5637 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
81198536 5638 seq = this_cpu_read(discard_pa_seq);
256bdb49 5639 if (!ext4_mb_use_preallocated(ac)) {
256bdb49
ES
5640 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
5641 ext4_mb_normalize_request(ac, ar);
53f86b17
RH
5642
5643 *errp = ext4_mb_pa_alloc(ac);
5644 if (*errp)
5645 goto errout;
c9de560d
AT
5646repeat:
5647 /* allocate space in core */
6c7a120a 5648 *errp = ext4_mb_regular_allocator(ac);
53f86b17
RH
5649 /*
5650 * pa allocated above is added to grp->bb_prealloc_list only
5651 * when we were able to allocate some block i.e. when
5652 * ac->ac_status == AC_STATUS_FOUND.
5653 * And error from above mean ac->ac_status != AC_STATUS_FOUND
5654 * So we have to free this pa here itself.
5655 */
2c00ef3e 5656 if (*errp) {
53f86b17 5657 ext4_mb_pa_free(ac);
2c00ef3e
AK
5658 ext4_discard_allocated_blocks(ac);
5659 goto errout;
5660 }
53f86b17
RH
5661 if (ac->ac_status == AC_STATUS_FOUND &&
5662 ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
5663 ext4_mb_pa_free(ac);
c9de560d 5664 }
256bdb49 5665 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
53accfa9 5666 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
554a5ccc 5667 if (*errp) {
b844167e 5668 ext4_discard_allocated_blocks(ac);
6d138ced
ES
5669 goto errout;
5670 } else {
519deca0
AK
5671 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5672 ar->len = ac->ac_b_ex.fe_len;
5673 }
c9de560d 5674 } else {
07b5b8e1 5675 if (ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
c9de560d 5676 goto repeat;
53f86b17
RH
5677 /*
5678 * If block allocation fails then the pa allocated above
5679 * needs to be freed here itself.
5680 */
5681 ext4_mb_pa_free(ac);
c9de560d 5682 *errp = -ENOSPC;
6c7a120a
AK
5683 }
5684
6d138ced 5685errout:
6c7a120a 5686 if (*errp) {
256bdb49 5687 ac->ac_b_ex.fe_len = 0;
c9de560d 5688 ar->len = 0;
256bdb49 5689 ext4_mb_show_ac(ac);
c9de560d 5690 }
256bdb49 5691 ext4_mb_release_context(ac);
6c7a120a
AK
5692out:
5693 if (ac)
5694 kmem_cache_free(ext4_ac_cachep, ac);
60e58e0f 5695 if (inquota && ar->len < inquota)
53accfa9 5696 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
0087d9fb 5697 if (!ar->len) {
e3cf5d5d 5698 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
0087d9fb 5699 /* release all the reserved blocks if non delalloc */
57042651 5700 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
53accfa9 5701 reserv_clstrs);
0087d9fb 5702 }
c9de560d 5703
9bffad1e 5704 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
ba80b101 5705
c9de560d
AT
5706 return block;
5707}
c9de560d 5708
c894058d
AK
5709/*
5710 * We can merge two free data extents only if the physical blocks
5711 * are contiguous, AND the extents were freed by the same transaction,
5712 * AND the blocks are associated with the same group.
5713 */
a0154344
DJ
5714static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
5715 struct ext4_free_data *entry,
5716 struct ext4_free_data *new_entry,
5717 struct rb_root *entry_rb_root)
c894058d 5718{
a0154344
DJ
5719 if ((entry->efd_tid != new_entry->efd_tid) ||
5720 (entry->efd_group != new_entry->efd_group))
5721 return;
5722 if (entry->efd_start_cluster + entry->efd_count ==
5723 new_entry->efd_start_cluster) {
5724 new_entry->efd_start_cluster = entry->efd_start_cluster;
5725 new_entry->efd_count += entry->efd_count;
5726 } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
5727 entry->efd_start_cluster) {
5728 new_entry->efd_count += entry->efd_count;
5729 } else
5730 return;
5731 spin_lock(&sbi->s_md_lock);
5732 list_del(&entry->efd_list);
5733 spin_unlock(&sbi->s_md_lock);
5734 rb_erase(&entry->efd_node, entry_rb_root);
5735 kmem_cache_free(ext4_free_data_cachep, entry);
c894058d
AK
5736}
5737
4ddfef7b
ES
5738static noinline_for_stack int
5739ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
7a2fcbf7 5740 struct ext4_free_data *new_entry)
c9de560d 5741{
e29136f8 5742 ext4_group_t group = e4b->bd_group;
84130193 5743 ext4_grpblk_t cluster;
d08854f5 5744 ext4_grpblk_t clusters = new_entry->efd_count;
7a2fcbf7 5745 struct ext4_free_data *entry;
c9de560d
AT
5746 struct ext4_group_info *db = e4b->bd_info;
5747 struct super_block *sb = e4b->bd_sb;
5748 struct ext4_sb_info *sbi = EXT4_SB(sb);
c894058d
AK
5749 struct rb_node **n = &db->bb_free_root.rb_node, *node;
5750 struct rb_node *parent = NULL, *new_node;
5751
0390131b 5752 BUG_ON(!ext4_handle_valid(handle));
c9de560d
AT
5753 BUG_ON(e4b->bd_bitmap_page == NULL);
5754 BUG_ON(e4b->bd_buddy_page == NULL);
5755
18aadd47
BJ
5756 new_node = &new_entry->efd_node;
5757 cluster = new_entry->efd_start_cluster;
c894058d 5758
c894058d
AK
5759 if (!*n) {
5760 /* first free block exent. We need to
5761 protect buddy cache from being freed,
5762 * otherwise we'll refresh it from
5763 * on-disk bitmap and lose not-yet-available
5764 * blocks */
09cbfeaf
KS
5765 get_page(e4b->bd_buddy_page);
5766 get_page(e4b->bd_bitmap_page);
c894058d
AK
5767 }
5768 while (*n) {
5769 parent = *n;
18aadd47
BJ
5770 entry = rb_entry(parent, struct ext4_free_data, efd_node);
5771 if (cluster < entry->efd_start_cluster)
c894058d 5772 n = &(*n)->rb_left;
18aadd47 5773 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
c894058d
AK
5774 n = &(*n)->rb_right;
5775 else {
e29136f8 5776 ext4_grp_locked_error(sb, group, 0,
84130193
TT
5777 ext4_group_first_block_no(sb, group) +
5778 EXT4_C2B(sbi, cluster),
e29136f8 5779 "Block already on to-be-freed list");
cca41553 5780 kmem_cache_free(ext4_free_data_cachep, new_entry);
c894058d 5781 return 0;
c9de560d 5782 }
c894058d 5783 }
c9de560d 5784
c894058d
AK
5785 rb_link_node(new_node, parent, n);
5786 rb_insert_color(new_node, &db->bb_free_root);
5787
5788 /* Now try to see the extent can be merged to left and right */
5789 node = rb_prev(new_node);
5790 if (node) {
18aadd47 5791 entry = rb_entry(node, struct ext4_free_data, efd_node);
a0154344
DJ
5792 ext4_try_merge_freed_extent(sbi, entry, new_entry,
5793 &(db->bb_free_root));
c894058d 5794 }
c9de560d 5795
c894058d
AK
5796 node = rb_next(new_node);
5797 if (node) {
18aadd47 5798 entry = rb_entry(node, struct ext4_free_data, efd_node);
a0154344
DJ
5799 ext4_try_merge_freed_extent(sbi, entry, new_entry,
5800 &(db->bb_free_root));
c9de560d 5801 }
a0154344 5802
d08854f5 5803 spin_lock(&sbi->s_md_lock);
a0154344 5804 list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
d08854f5
TT
5805 sbi->s_mb_free_pending += clusters;
5806 spin_unlock(&sbi->s_md_lock);
c9de560d
AT
5807 return 0;
5808}
5809
8016e29f
HS
5810/*
5811 * Simple allocator for Ext4 fast commit replay path. It searches for blocks
5812 * linearly starting at the goal block and also excludes the blocks which
5813 * are going to be in use after fast commit replay.
5814 */
5815static ext4_fsblk_t ext4_mb_new_blocks_simple(handle_t *handle,
5816 struct ext4_allocation_request *ar, int *errp)
5817{
5818 struct buffer_head *bitmap_bh;
5819 struct super_block *sb = ar->inode->i_sb;
5820 ext4_group_t group;
5821 ext4_grpblk_t blkoff;
31a074a0
XY
5822 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
5823 ext4_grpblk_t i = 0;
8016e29f
HS
5824 ext4_fsblk_t goal, block;
5825 struct ext4_super_block *es = EXT4_SB(sb)->s_es;
5826
5827 goal = ar->goal;
5828 if (goal < le32_to_cpu(es->s_first_data_block) ||
5829 goal >= ext4_blocks_count(es))
5830 goal = le32_to_cpu(es->s_first_data_block);
5831
5832 ar->len = 0;
5833 ext4_get_group_no_and_offset(sb, goal, &group, &blkoff);
5834 for (; group < ext4_get_groups_count(sb); group++) {
5835 bitmap_bh = ext4_read_block_bitmap(sb, group);
5836 if (IS_ERR(bitmap_bh)) {
5837 *errp = PTR_ERR(bitmap_bh);
5838 pr_warn("Failed to read block bitmap\n");
5839 return 0;
5840 }
5841
5842 ext4_get_group_no_and_offset(sb,
5843 max(ext4_group_first_block_no(sb, group), goal),
5844 NULL, &blkoff);
31a074a0
XY
5845 while (1) {
5846 i = mb_find_next_zero_bit(bitmap_bh->b_data, max,
8016e29f 5847 blkoff);
31a074a0
XY
5848 if (i >= max)
5849 break;
5850 if (ext4_fc_replay_check_excluded(sb,
5851 ext4_group_first_block_no(sb, group) + i)) {
5852 blkoff = i + 1;
5853 } else
5854 break;
5855 }
8016e29f 5856 brelse(bitmap_bh);
31a074a0
XY
5857 if (i < max)
5858 break;
8016e29f
HS
5859 }
5860
31a074a0
XY
5861 if (group >= ext4_get_groups_count(sb) || i >= max) {
5862 *errp = -ENOSPC;
8016e29f 5863 return 0;
31a074a0 5864 }
8016e29f
HS
5865
5866 block = ext4_group_first_block_no(sb, group) + i;
5867 ext4_mb_mark_bb(sb, block, 1, 1);
5868 ar->len = 1;
5869
5870 return block;
5871}
5872
5873static void ext4_free_blocks_simple(struct inode *inode, ext4_fsblk_t block,
5874 unsigned long count)
5875{
5876 struct buffer_head *bitmap_bh;
5877 struct super_block *sb = inode->i_sb;
5878 struct ext4_group_desc *gdp;
5879 struct buffer_head *gdp_bh;
5880 ext4_group_t group;
5881 ext4_grpblk_t blkoff;
5882 int already_freed = 0, err, i;
5883
5884 ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
5885 bitmap_bh = ext4_read_block_bitmap(sb, group);
5886 if (IS_ERR(bitmap_bh)) {
5887 err = PTR_ERR(bitmap_bh);
5888 pr_warn("Failed to read block bitmap\n");
5889 return;
5890 }
5891 gdp = ext4_get_group_desc(sb, group, &gdp_bh);
5892 if (!gdp)
5893 return;
5894
5895 for (i = 0; i < count; i++) {
5896 if (!mb_test_bit(blkoff + i, bitmap_bh->b_data))
5897 already_freed++;
5898 }
5899 mb_clear_bits(bitmap_bh->b_data, blkoff, count);
5900 err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
5901 if (err)
5902 return;
5903 ext4_free_group_clusters_set(
5904 sb, gdp, ext4_free_group_clusters(sb, gdp) +
5905 count - already_freed);
5906 ext4_block_bitmap_csum_set(sb, group, gdp, bitmap_bh);
5907 ext4_group_desc_csum_set(sb, group, gdp);
5908 ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
5909 sync_dirty_buffer(bitmap_bh);
5910 sync_dirty_buffer(gdp_bh);
5911 brelse(bitmap_bh);
5912}
5913
44338711 5914/**
8ac3939d
RH
5915 * ext4_mb_clear_bb() -- helper function for freeing blocks.
5916 * Used by ext4_free_blocks()
44338711
TT
5917 * @handle: handle for this transaction
5918 * @inode: inode
c60990b3
TT
5919 * @block: starting physical block to be freed
5920 * @count: number of blocks to be freed
5def1360 5921 * @flags: flags used by ext4_free_blocks
c9de560d 5922 */
8ac3939d
RH
5923static void ext4_mb_clear_bb(handle_t *handle, struct inode *inode,
5924 ext4_fsblk_t block, unsigned long count,
5925 int flags)
c9de560d 5926{
26346ff6 5927 struct buffer_head *bitmap_bh = NULL;
c9de560d 5928 struct super_block *sb = inode->i_sb;
c9de560d 5929 struct ext4_group_desc *gdp;
498e5f24 5930 unsigned int overflow;
c9de560d
AT
5931 ext4_grpblk_t bit;
5932 struct buffer_head *gd_bh;
5933 ext4_group_t block_group;
5934 struct ext4_sb_info *sbi;
5935 struct ext4_buddy e4b;
84130193 5936 unsigned int count_clusters;
c9de560d
AT
5937 int err = 0;
5938 int ret;
5939
8016e29f
HS
5940 sbi = EXT4_SB(sb);
5941
1e1c2b86
LC
5942 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
5943 !ext4_inode_block_valid(inode, block, count)) {
5944 ext4_error(sb, "Freeing blocks in system zone - "
5945 "Block = %llu, count = %lu", block, count);
5946 /* err = 0. ext4_std_error should be a no op */
5947 goto error_return;
5948 }
5949 flags |= EXT4_FREE_BLOCKS_VALIDATED;
5950
c9de560d
AT
5951do_more:
5952 overflow = 0;
5953 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5954
163a203d
DW
5955 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
5956 ext4_get_group_info(sb, block_group))))
5957 return;
5958
c9de560d
AT
5959 /*
5960 * Check to see if we are freeing blocks across a group
5961 * boundary.
5962 */
84130193
TT
5963 if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
5964 overflow = EXT4_C2B(sbi, bit) + count -
5965 EXT4_BLOCKS_PER_GROUP(sb);
c9de560d 5966 count -= overflow;
1e1c2b86
LC
5967 /* The range changed so it's no longer validated */
5968 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
c9de560d 5969 }
810da240 5970 count_clusters = EXT4_NUM_B2C(sbi, count);
574ca174 5971 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
9008a58e
DW
5972 if (IS_ERR(bitmap_bh)) {
5973 err = PTR_ERR(bitmap_bh);
5974 bitmap_bh = NULL;
c9de560d 5975 goto error_return;
ce89f46c 5976 }
c9de560d 5977 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
ce89f46c
AK
5978 if (!gdp) {
5979 err = -EIO;
c9de560d 5980 goto error_return;
ce89f46c 5981 }
c9de560d 5982
1e1c2b86
LC
5983 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
5984 !ext4_inode_block_valid(inode, block, count)) {
12062ddd 5985 ext4_error(sb, "Freeing blocks in system zone - "
0610b6e9 5986 "Block = %llu, count = %lu", block, count);
519deca0
AK
5987 /* err = 0. ext4_std_error should be a no op */
5988 goto error_return;
c9de560d
AT
5989 }
5990
5991 BUFFER_TRACE(bitmap_bh, "getting write access");
188c299e
JK
5992 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
5993 EXT4_JTR_NONE);
c9de560d
AT
5994 if (err)
5995 goto error_return;
5996
5997 /*
5998 * We are about to modify some metadata. Call the journal APIs
5999 * to unshare ->b_data if a currently-committing transaction is
6000 * using it
6001 */
6002 BUFFER_TRACE(gd_bh, "get_write_access");
188c299e 6003 err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
c9de560d
AT
6004 if (err)
6005 goto error_return;
c9de560d
AT
6006#ifdef AGGRESSIVE_CHECK
6007 {
6008 int i;
84130193 6009 for (i = 0; i < count_clusters; i++)
c9de560d
AT
6010 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
6011 }
6012#endif
84130193 6013 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
c9de560d 6014
adb7ef60
KK
6015 /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
6016 err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
6017 GFP_NOFS|__GFP_NOFAIL);
920313a7
AK
6018 if (err)
6019 goto error_return;
e6362609 6020
f96c450d
DJ
6021 /*
6022 * We need to make sure we don't reuse the freed block until after the
6023 * transaction is committed. We make an exception if the inode is to be
6024 * written in writeback mode since writeback mode has weak data
6025 * consistency guarantees.
6026 */
6027 if (ext4_handle_valid(handle) &&
6028 ((flags & EXT4_FREE_BLOCKS_METADATA) ||
6029 !ext4_should_writeback_data(inode))) {
7a2fcbf7
AK
6030 struct ext4_free_data *new_entry;
6031 /*
7444a072
MH
6032 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
6033 * to fail.
7a2fcbf7 6034 */
7444a072
MH
6035 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
6036 GFP_NOFS|__GFP_NOFAIL);
18aadd47
BJ
6037 new_entry->efd_start_cluster = bit;
6038 new_entry->efd_group = block_group;
6039 new_entry->efd_count = count_clusters;
6040 new_entry->efd_tid = handle->h_transaction->t_tid;
955ce5f5 6041
7a2fcbf7 6042 ext4_lock_group(sb, block_group);
84130193 6043 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
7a2fcbf7 6044 ext4_mb_free_metadata(handle, &e4b, new_entry);
c9de560d 6045 } else {
7a2fcbf7
AK
6046 /* need to update group_info->bb_free and bitmap
6047 * with group lock held. generate_buddy look at
6048 * them with group lock_held
6049 */
d71c1ae2 6050 if (test_opt(sb, DISCARD)) {
a0154344
DJ
6051 err = ext4_issue_discard(sb, block_group, bit, count,
6052 NULL);
d71c1ae2
LC
6053 if (err && err != -EOPNOTSUPP)
6054 ext4_msg(sb, KERN_WARNING, "discard request in"
a00b482b 6055 " group:%u block:%d count:%lu failed"
d71c1ae2
LC
6056 " with %d", block_group, bit, count,
6057 err);
8f9ff189
LC
6058 } else
6059 EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
d71c1ae2 6060
955ce5f5 6061 ext4_lock_group(sb, block_group);
84130193
TT
6062 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
6063 mb_free_blocks(inode, &e4b, bit, count_clusters);
c9de560d
AT
6064 }
6065
021b65bb
TT
6066 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
6067 ext4_free_group_clusters_set(sb, gdp, ret);
79f1ba49 6068 ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
feb0ab32 6069 ext4_group_desc_csum_set(sb, block_group, gdp);
955ce5f5 6070 ext4_unlock_group(sb, block_group);
c9de560d 6071
772cb7c8
JS
6072 if (sbi->s_log_groups_per_flex) {
6073 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
90ba983f 6074 atomic64_add(count_clusters,
7c990728
SJS
6075 &sbi_array_rcu_deref(sbi, s_flex_groups,
6076 flex_group)->free_clusters);
772cb7c8
JS
6077 }
6078
9fe67149
EW
6079 /*
6080 * on a bigalloc file system, defer the s_freeclusters_counter
6081 * update to the caller (ext4_remove_space and friends) so they
6082 * can determine if a cluster freed here should be rereserved
6083 */
6084 if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
6085 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
6086 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
6087 percpu_counter_add(&sbi->s_freeclusters_counter,
6088 count_clusters);
6089 }
7d734532
JK
6090
6091 ext4_mb_unload_buddy(&e4b);
7b415bf6 6092
7a2fcbf7
AK
6093 /* We dirtied the bitmap block */
6094 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
6095 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
6096
c9de560d
AT
6097 /* And the group descriptor block */
6098 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
0390131b 6099 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
c9de560d
AT
6100 if (!err)
6101 err = ret;
6102
6103 if (overflow && !err) {
6104 block += count;
6105 count = overflow;
6106 put_bh(bitmap_bh);
1e1c2b86
LC
6107 /* The range changed so it's no longer validated */
6108 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
c9de560d
AT
6109 goto do_more;
6110 }
c9de560d
AT
6111error_return:
6112 brelse(bitmap_bh);
6113 ext4_std_error(sb, err);
6114 return;
6115}
7360d173 6116
8ac3939d
RH
6117/**
6118 * ext4_free_blocks() -- Free given blocks and update quota
6119 * @handle: handle for this transaction
6120 * @inode: inode
6121 * @bh: optional buffer of the block to be freed
6122 * @block: starting physical block to be freed
6123 * @count: number of blocks to be freed
6124 * @flags: flags used by ext4_free_blocks
6125 */
6126void ext4_free_blocks(handle_t *handle, struct inode *inode,
6127 struct buffer_head *bh, ext4_fsblk_t block,
6128 unsigned long count, int flags)
6129{
6130 struct super_block *sb = inode->i_sb;
6131 unsigned int overflow;
6132 struct ext4_sb_info *sbi;
6133
6134 sbi = EXT4_SB(sb);
6135
6136 if (sbi->s_mount_state & EXT4_FC_REPLAY) {
6137 ext4_free_blocks_simple(inode, block, count);
6138 return;
6139 }
6140
6141 might_sleep();
6142 if (bh) {
6143 if (block)
6144 BUG_ON(block != bh->b_blocknr);
6145 else
6146 block = bh->b_blocknr;
6147 }
6148
6149 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6150 !ext4_inode_block_valid(inode, block, count)) {
6151 ext4_error(sb, "Freeing blocks not in datazone - "
6152 "block = %llu, count = %lu", block, count);
6153 return;
6154 }
1e1c2b86 6155 flags |= EXT4_FREE_BLOCKS_VALIDATED;
8ac3939d
RH
6156
6157 ext4_debug("freeing block %llu\n", block);
6158 trace_ext4_free_blocks(inode, block, count, flags);
6159
6160 if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
6161 BUG_ON(count > 1);
6162
6163 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
6164 inode, bh, block);
6165 }
6166
6167 /*
6168 * If the extent to be freed does not begin on a cluster
6169 * boundary, we need to deal with partial clusters at the
6170 * beginning and end of the extent. Normally we will free
6171 * blocks at the beginning or the end unless we are explicitly
6172 * requested to avoid doing so.
6173 */
6174 overflow = EXT4_PBLK_COFF(sbi, block);
6175 if (overflow) {
6176 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
6177 overflow = sbi->s_cluster_ratio - overflow;
6178 block += overflow;
6179 if (count > overflow)
6180 count -= overflow;
6181 else
6182 return;
6183 } else {
6184 block -= overflow;
6185 count += overflow;
6186 }
1e1c2b86
LC
6187 /* The range changed so it's no longer validated */
6188 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
8ac3939d
RH
6189 }
6190 overflow = EXT4_LBLK_COFF(sbi, count);
6191 if (overflow) {
6192 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
6193 if (count > overflow)
6194 count -= overflow;
6195 else
6196 return;
6197 } else
6198 count += sbi->s_cluster_ratio - overflow;
1e1c2b86
LC
6199 /* The range changed so it's no longer validated */
6200 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
8ac3939d
RH
6201 }
6202
6203 if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
6204 int i;
6205 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
6206
6207 for (i = 0; i < count; i++) {
6208 cond_resched();
6209 if (is_metadata)
6210 bh = sb_find_get_block(inode->i_sb, block + i);
6211 ext4_forget(handle, is_metadata, inode, bh, block + i);
6212 }
6213 }
6214
6215 ext4_mb_clear_bb(handle, inode, block, count, flags);
6216 return;
6217}
6218
2846e820 6219/**
0529155e 6220 * ext4_group_add_blocks() -- Add given blocks to an existing group
2846e820
AG
6221 * @handle: handle to this transaction
6222 * @sb: super block
4907cb7b 6223 * @block: start physical block to add to the block group
2846e820
AG
6224 * @count: number of blocks to free
6225 *
e73a347b 6226 * This marks the blocks as free in the bitmap and buddy.
2846e820 6227 */
cc7365df 6228int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
2846e820
AG
6229 ext4_fsblk_t block, unsigned long count)
6230{
6231 struct buffer_head *bitmap_bh = NULL;
6232 struct buffer_head *gd_bh;
6233 ext4_group_t block_group;
6234 ext4_grpblk_t bit;
6235 unsigned int i;
6236 struct ext4_group_desc *desc;
6237 struct ext4_sb_info *sbi = EXT4_SB(sb);
e73a347b 6238 struct ext4_buddy e4b;
d77147ff 6239 int err = 0, ret, free_clusters_count;
6240 ext4_grpblk_t clusters_freed;
6241 ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
6242 ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
6243 unsigned long cluster_count = last_cluster - first_cluster + 1;
2846e820
AG
6244
6245 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
6246
4740b830
YY
6247 if (count == 0)
6248 return 0;
6249
2846e820 6250 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
2846e820
AG
6251 /*
6252 * Check to see if we are freeing blocks across a group
6253 * boundary.
6254 */
d77147ff 6255 if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
6256 ext4_warning(sb, "too many blocks added to group %u",
cc7365df
YY
6257 block_group);
6258 err = -EINVAL;
2846e820 6259 goto error_return;
cc7365df 6260 }
2cd05cc3 6261
2846e820 6262 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
9008a58e
DW
6263 if (IS_ERR(bitmap_bh)) {
6264 err = PTR_ERR(bitmap_bh);
6265 bitmap_bh = NULL;
2846e820 6266 goto error_return;
cc7365df
YY
6267 }
6268
2846e820 6269 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
cc7365df
YY
6270 if (!desc) {
6271 err = -EIO;
2846e820 6272 goto error_return;
cc7365df 6273 }
2846e820 6274
a00b482b 6275 if (!ext4_sb_block_valid(sb, NULL, block, count)) {
2846e820
AG
6276 ext4_error(sb, "Adding blocks in system zones - "
6277 "Block = %llu, count = %lu",
6278 block, count);
cc7365df 6279 err = -EINVAL;
2846e820
AG
6280 goto error_return;
6281 }
6282
2cd05cc3 6283 BUFFER_TRACE(bitmap_bh, "getting write access");
188c299e
JK
6284 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
6285 EXT4_JTR_NONE);
2846e820
AG
6286 if (err)
6287 goto error_return;
6288
6289 /*
6290 * We are about to modify some metadata. Call the journal APIs
6291 * to unshare ->b_data if a currently-committing transaction is
6292 * using it
6293 */
6294 BUFFER_TRACE(gd_bh, "get_write_access");
188c299e 6295 err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
2846e820
AG
6296 if (err)
6297 goto error_return;
e73a347b 6298
d77147ff 6299 for (i = 0, clusters_freed = 0; i < cluster_count; i++) {
2846e820 6300 BUFFER_TRACE(bitmap_bh, "clear bit");
e73a347b 6301 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
2846e820
AG
6302 ext4_error(sb, "bit already cleared for block %llu",
6303 (ext4_fsblk_t)(block + i));
6304 BUFFER_TRACE(bitmap_bh, "bit already cleared");
6305 } else {
d77147ff 6306 clusters_freed++;
2846e820
AG
6307 }
6308 }
e73a347b
AG
6309
6310 err = ext4_mb_load_buddy(sb, block_group, &e4b);
6311 if (err)
6312 goto error_return;
6313
6314 /*
6315 * need to update group_info->bb_free and bitmap
6316 * with group lock held. generate_buddy look at
6317 * them with group lock_held
6318 */
2846e820 6319 ext4_lock_group(sb, block_group);
d77147ff 6320 mb_clear_bits(bitmap_bh->b_data, bit, cluster_count);
6321 mb_free_blocks(NULL, &e4b, bit, cluster_count);
6322 free_clusters_count = clusters_freed +
6323 ext4_free_group_clusters(sb, desc);
6324 ext4_free_group_clusters_set(sb, desc, free_clusters_count);
79f1ba49 6325 ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
feb0ab32 6326 ext4_group_desc_csum_set(sb, block_group, desc);
2846e820 6327 ext4_unlock_group(sb, block_group);
57042651 6328 percpu_counter_add(&sbi->s_freeclusters_counter,
d77147ff 6329 clusters_freed);
2846e820
AG
6330
6331 if (sbi->s_log_groups_per_flex) {
6332 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
d77147ff 6333 atomic64_add(clusters_freed,
7c990728
SJS
6334 &sbi_array_rcu_deref(sbi, s_flex_groups,
6335 flex_group)->free_clusters);
2846e820 6336 }
e73a347b
AG
6337
6338 ext4_mb_unload_buddy(&e4b);
2846e820
AG
6339
6340 /* We dirtied the bitmap block */
6341 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
6342 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
6343
6344 /* And the group descriptor block */
6345 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
6346 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
6347 if (!err)
6348 err = ret;
6349
6350error_return:
6351 brelse(bitmap_bh);
6352 ext4_std_error(sb, err);
cc7365df 6353 return err;
2846e820
AG
6354}
6355
7360d173
LC
6356/**
6357 * ext4_trim_extent -- function to TRIM one single free extent in the group
6358 * @sb: super block for the file system
6359 * @start: starting block of the free extent in the alloc. group
6360 * @count: number of blocks to TRIM
7360d173
LC
6361 * @e4b: ext4 buddy for the group
6362 *
6363 * Trim "count" blocks starting at "start" in the "group". To assure that no
6364 * one will allocate those blocks, mark it as used in buddy bitmap. This must
6365 * be called with under the group lock.
6366 */
bd2eea8d
WJ
6367static int ext4_trim_extent(struct super_block *sb,
6368 int start, int count, struct ext4_buddy *e4b)
e2cbd587 6369__releases(bitlock)
6370__acquires(bitlock)
7360d173
LC
6371{
6372 struct ext4_free_extent ex;
bd2eea8d 6373 ext4_group_t group = e4b->bd_group;
d71c1ae2 6374 int ret = 0;
7360d173 6375
b3d4c2b1
TM
6376 trace_ext4_trim_extent(sb, group, start, count);
6377
7360d173
LC
6378 assert_spin_locked(ext4_group_lock_ptr(sb, group));
6379
6380 ex.fe_start = start;
6381 ex.fe_group = group;
6382 ex.fe_len = count;
6383
6384 /*
6385 * Mark blocks used, so no one can reuse them while
6386 * being trimmed.
6387 */
6388 mb_mark_used(e4b, &ex);
6389 ext4_unlock_group(sb, group);
a0154344 6390 ret = ext4_issue_discard(sb, group, start, count, NULL);
7360d173
LC
6391 ext4_lock_group(sb, group);
6392 mb_free_blocks(NULL, e4b, start, ex.fe_len);
d71c1ae2 6393 return ret;
7360d173
LC
6394}
6395
6920b391
WJ
6396static int ext4_try_to_trim_range(struct super_block *sb,
6397 struct ext4_buddy *e4b, ext4_grpblk_t start,
6398 ext4_grpblk_t max, ext4_grpblk_t minblocks)
a5fda113
TT
6399__acquires(ext4_group_lock_ptr(sb, e4b->bd_group))
6400__releases(ext4_group_lock_ptr(sb, e4b->bd_group))
6920b391
WJ
6401{
6402 ext4_grpblk_t next, count, free_count;
6403 void *bitmap;
6920b391
WJ
6404
6405 bitmap = e4b->bd_bitmap;
6406 start = (e4b->bd_info->bb_first_free > start) ?
6407 e4b->bd_info->bb_first_free : start;
6408 count = 0;
6409 free_count = 0;
6410
6411 while (start <= max) {
6412 start = mb_find_next_zero_bit(bitmap, max + 1, start);
6413 if (start > max)
6414 break;
6415 next = mb_find_next_bit(bitmap, max + 1, start);
6416
6417 if ((next - start) >= minblocks) {
afcc4e32
LB
6418 int ret = ext4_trim_extent(sb, start, next - start, e4b);
6419
6920b391
WJ
6420 if (ret && ret != -EOPNOTSUPP)
6421 break;
6920b391
WJ
6422 count += next - start;
6423 }
6424 free_count += next - start;
6425 start = next + 1;
6426
6427 if (fatal_signal_pending(current)) {
6428 count = -ERESTARTSYS;
6429 break;
6430 }
6431
6432 if (need_resched()) {
6433 ext4_unlock_group(sb, e4b->bd_group);
6434 cond_resched();
6435 ext4_lock_group(sb, e4b->bd_group);
6436 }
6437
6438 if ((e4b->bd_info->bb_free - free_count) < minblocks)
6439 break;
6440 }
6441
6442 return count;
6443}
6444
7360d173
LC
6445/**
6446 * ext4_trim_all_free -- function to trim all free space in alloc. group
6447 * @sb: super block for file system
22612283 6448 * @group: group to be trimmed
7360d173
LC
6449 * @start: first group block to examine
6450 * @max: last group block to examine
6451 * @minblocks: minimum extent block count
d63c00ea 6452 * @set_trimmed: set the trimmed flag if at least one block is trimmed
7360d173 6453 *
7360d173
LC
6454 * ext4_trim_all_free walks through group's block bitmap searching for free
6455 * extents. When the free extent is found, mark it as used in group buddy
6456 * bitmap. Then issue a TRIM command on this extent and free the extent in
b6f5558c 6457 * the group buddy bitmap.
7360d173 6458 */
0b75a840 6459static ext4_grpblk_t
78944086
LC
6460ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
6461 ext4_grpblk_t start, ext4_grpblk_t max,
d63c00ea 6462 ext4_grpblk_t minblocks, bool set_trimmed)
7360d173 6463{
78944086 6464 struct ext4_buddy e4b;
6920b391 6465 int ret;
7360d173 6466
b3d4c2b1
TM
6467 trace_ext4_trim_all_free(sb, group, start, max);
6468
78944086
LC
6469 ret = ext4_mb_load_buddy(sb, group, &e4b);
6470 if (ret) {
9651e6b2
KK
6471 ext4_warning(sb, "Error %d loading buddy information for %u",
6472 ret, group);
78944086
LC
6473 return ret;
6474 }
28739eea
LC
6475
6476 ext4_lock_group(sb, group);
7360d173 6477
6920b391 6478 if (!EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) ||
2327fb2e 6479 minblocks < EXT4_SB(sb)->s_last_trim_minblks) {
6920b391 6480 ret = ext4_try_to_trim_range(sb, &e4b, start, max, minblocks);
d63c00ea 6481 if (ret >= 0 && set_trimmed)
6920b391
WJ
6482 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
6483 } else {
6484 ret = 0;
7360d173 6485 }
3d56b8d2 6486
7360d173 6487 ext4_unlock_group(sb, group);
78944086 6488 ext4_mb_unload_buddy(&e4b);
7360d173
LC
6489
6490 ext4_debug("trimmed %d blocks in the group %d\n",
6920b391 6491 ret, group);
7360d173 6492
d71c1ae2 6493 return ret;
7360d173
LC
6494}
6495
6496/**
6497 * ext4_trim_fs() -- trim ioctl handle function
6498 * @sb: superblock for filesystem
6499 * @range: fstrim_range structure
6500 *
6501 * start: First Byte to trim
6502 * len: number of Bytes to trim from start
6503 * minlen: minimum extent length in Bytes
6504 * ext4_trim_fs goes through all allocation groups containing Bytes from
6505 * start to start+len. For each such a group ext4_trim_all_free function
6506 * is invoked to trim all free space.
6507 */
6508int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
6509{
7b47ef52 6510 unsigned int discard_granularity = bdev_discard_granularity(sb->s_bdev);
78944086 6511 struct ext4_group_info *grp;
913eed83 6512 ext4_group_t group, first_group, last_group;
7137d7a4 6513 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
913eed83 6514 uint64_t start, end, minlen, trimmed = 0;
0f0a25bf
JK
6515 ext4_fsblk_t first_data_blk =
6516 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
913eed83 6517 ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
d63c00ea 6518 bool whole_group, eof = false;
7360d173
LC
6519 int ret = 0;
6520
6521 start = range->start >> sb->s_blocksize_bits;
913eed83 6522 end = start + (range->len >> sb->s_blocksize_bits) - 1;
aaf7d73e
LC
6523 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
6524 range->minlen >> sb->s_blocksize_bits);
7360d173 6525
5de35e8d
LC
6526 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
6527 start >= max_blks ||
6528 range->len < sb->s_blocksize)
7360d173 6529 return -EINVAL;
173b6e38 6530 /* No point to try to trim less than discard granularity */
7b47ef52 6531 if (range->minlen < discard_granularity) {
173b6e38 6532 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
7b47ef52 6533 discard_granularity >> sb->s_blocksize_bits);
173b6e38
JK
6534 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
6535 goto out;
6536 }
d63c00ea 6537 if (end >= max_blks - 1) {
913eed83 6538 end = max_blks - 1;
d63c00ea
DM
6539 eof = true;
6540 }
913eed83 6541 if (end <= first_data_blk)
22f10457 6542 goto out;
913eed83 6543 if (start < first_data_blk)
0f0a25bf 6544 start = first_data_blk;
7360d173 6545
913eed83 6546 /* Determine first and last group to examine based on start and end */
7360d173 6547 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
7137d7a4 6548 &first_group, &first_cluster);
913eed83 6549 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
7137d7a4 6550 &last_group, &last_cluster);
7360d173 6551
913eed83
LC
6552 /* end now represents the last cluster to discard in this group */
6553 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
d63c00ea 6554 whole_group = true;
7360d173
LC
6555
6556 for (group = first_group; group <= last_group; group++) {
78944086
LC
6557 grp = ext4_get_group_info(sb, group);
6558 /* We only do this if the grp has never been initialized */
6559 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
adb7ef60 6560 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
78944086
LC
6561 if (ret)
6562 break;
7360d173
LC
6563 }
6564
0ba08517 6565 /*
913eed83
LC
6566 * For all the groups except the last one, last cluster will
6567 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
6568 * change it for the last group, note that last_cluster is
6569 * already computed earlier by ext4_get_group_no_and_offset()
0ba08517 6570 */
d63c00ea 6571 if (group == last_group) {
913eed83 6572 end = last_cluster;
d63c00ea
DM
6573 whole_group = eof ? true : end == EXT4_CLUSTERS_PER_GROUP(sb) - 1;
6574 }
78944086 6575 if (grp->bb_free >= minlen) {
7137d7a4 6576 cnt = ext4_trim_all_free(sb, group, first_cluster,
d63c00ea 6577 end, minlen, whole_group);
7360d173
LC
6578 if (cnt < 0) {
6579 ret = cnt;
7360d173
LC
6580 break;
6581 }
21e7fd22 6582 trimmed += cnt;
7360d173 6583 }
913eed83
LC
6584
6585 /*
6586 * For every group except the first one, we are sure
6587 * that the first cluster to discard will be cluster #0.
6588 */
7137d7a4 6589 first_cluster = 0;
7360d173 6590 }
7360d173 6591
3d56b8d2 6592 if (!ret)
2327fb2e 6593 EXT4_SB(sb)->s_last_trim_minblks = minlen;
3d56b8d2 6594
22f10457 6595out:
aaf7d73e 6596 range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
7360d173
LC
6597 return ret;
6598}
0c9ec4be
DW
6599
6600/* Iterate all the free extents in the group. */
6601int
6602ext4_mballoc_query_range(
6603 struct super_block *sb,
6604 ext4_group_t group,
6605 ext4_grpblk_t start,
6606 ext4_grpblk_t end,
6607 ext4_mballoc_query_range_fn formatter,
6608 void *priv)
6609{
6610 void *bitmap;
6611 ext4_grpblk_t next;
6612 struct ext4_buddy e4b;
6613 int error;
6614
6615 error = ext4_mb_load_buddy(sb, group, &e4b);
6616 if (error)
6617 return error;
6618 bitmap = e4b.bd_bitmap;
6619
6620 ext4_lock_group(sb, group);
6621
6622 start = (e4b.bd_info->bb_first_free > start) ?
6623 e4b.bd_info->bb_first_free : start;
6624 if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
6625 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
6626
6627 while (start <= end) {
6628 start = mb_find_next_zero_bit(bitmap, end + 1, start);
6629 if (start > end)
6630 break;
6631 next = mb_find_next_bit(bitmap, end + 1, start);
6632
6633 ext4_unlock_group(sb, group);
6634 error = formatter(sb, group, start, next - start, priv);
6635 if (error)
6636 goto out_unload;
6637 ext4_lock_group(sb, group);
6638
6639 start = next + 1;
6640 }
6641
6642 ext4_unlock_group(sb, group);
6643out_unload:
6644 ext4_mb_unload_buddy(&e4b);
6645
6646 return error;
6647}