1 // SPDX-License-Identifier: GPL-2.0
9 * mballoc.c contains the multiblocks allocation routines
12 #include "ext4_jbd2.h"
14 #include <linux/log2.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/nospec.h>
18 #include <linux/backing-dev.h>
19 #include <trace/events/ext4.h>
23 * - test ext4_ext_search_left() and ext4_ext_search_right()
24 * - search for metadata in few groups
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
31 * - reservation for superuser
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
42 * The allocation request involve request for multiple number of blocks
43 * near to the goal(block) value specified.
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.
55 * The main motivation for having small file use group preallocation is to
56 * ensure that we have small files closer together on the disk.
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
63 * pa_lstart -> the logical start block for this prealloc space
64 * pa_pstart -> the physical start block for this prealloc space
65 * pa_len -> length for this prealloc space (in clusters)
66 * pa_free -> free space available in this prealloc space (in clusters)
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
70 * space we will consume the particular prealloc space. This makes sure that
71 * we have contiguous physical blocks representing the file blocks
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
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
79 * prealloc space. These are per CPU prealloc list represented as
81 * ext4_sb_info.s_locality_groups[smp_processor_id()]
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.
86 * The locality group prealloc space is used looking at whether we have
87 * enough free space (pa_free) within the prealloc space.
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
100 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
103 * one block each for bitmap and buddy information. So for each group we
104 * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
105 * blocksize) blocks. So it can have information regarding groups_per_page
106 * which is blocks_per_page/2
108 * The buddy cache inode is not stored on disk. The inode is thrown
109 * away when the filesystem is unmounted.
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
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
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
123 * 512 blocks. This can be tuned via
124 * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
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
127 * smallest multiple of the stripe value (sbi->s_stripe) which is
128 * greater than the default mb_group_prealloc.
130 * If "mb_optimize_scan" mount option is set, we maintain in memory group info
131 * structures in two data structures:
133 * 1) Array of largest free order lists (sbi->s_mb_largest_free_orders)
135 * Locking: sbi->s_mb_largest_free_orders_locks(array of rw locks)
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.
143 * 2) Average fragment size lists (sbi->s_mb_avg_fragment_size)
145 * Locking: sbi->s_mb_avg_fragment_size_locks(array of rw locks)
147 * This is an array of lists where in the i-th list there are groups with
148 * average fragment size >= 2^i and < 2^(i+1). The average fragment size
149 * is computed as ext4_group_info->bb_free / ext4_group_info->bb_fragments.
150 * Note that we don't bother with a special list for completely empty groups
151 * so we only have MB_NUM_ORDERS(sb) lists.
153 * When "mb_optimize_scan" mount option is set, mballoc consults the above data
154 * structures to decide the order in which groups are to be traversed for
155 * fulfilling an allocation request.
157 * At CR_POWER2_ALIGNED , we look for groups which have the largest_free_order
158 * >= the order of the request. We directly look at the largest free order list
159 * in the data structure (1) above where largest_free_order = order of the
160 * request. If that list is empty, we look at remaining list in the increasing
161 * order of largest_free_order. This allows us to perform CR_POWER2_ALIGNED
162 * lookup in O(1) time.
164 * At CR_GOAL_LEN_FAST, we only consider groups where
165 * average fragment size > request size. So, we lookup a group which has average
166 * fragment size just above or equal to request size using our average fragment
167 * size group lists (data structure 2) in O(1) time.
169 * At CR_BEST_AVAIL_LEN, we aim to optimize allocations which can't be satisfied
170 * in CR_GOAL_LEN_FAST. The fact that we couldn't find a group in
171 * CR_GOAL_LEN_FAST suggests that there is no BG that has avg
172 * fragment size > goal length. So before falling to the slower
173 * CR_GOAL_LEN_SLOW, in CR_BEST_AVAIL_LEN we proactively trim goal length and
174 * then use the same fragment lists as CR_GOAL_LEN_FAST to find a BG with a big
175 * enough average fragment size. This increases the chances of finding a
176 * suitable block group in O(1) time and results in faster allocation at the
177 * cost of reduced size of allocation.
179 * If "mb_optimize_scan" mount option is not set, mballoc traverses groups in
180 * linear order which requires O(N) search time for each CR_POWER2_ALIGNED and
181 * CR_GOAL_LEN_FAST phase.
183 * The regular allocator (using the buddy cache) supports a few tunables.
185 * /sys/fs/ext4/<partition>/mb_min_to_scan
186 * /sys/fs/ext4/<partition>/mb_max_to_scan
187 * /sys/fs/ext4/<partition>/mb_order2_req
188 * /sys/fs/ext4/<partition>/mb_linear_limit
190 * The regular allocator uses buddy scan only if the request len is power of
191 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
192 * value of s_mb_order2_reqs can be tuned via
193 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
194 * stripe size (sbi->s_stripe), we try to search for contiguous block in
195 * stripe size. This should result in better allocation on RAID setups. If
196 * not, we search in the specific group using bitmap for best extents. The
197 * tunable min_to_scan and max_to_scan control the behaviour here.
198 * min_to_scan indicate how long the mballoc __must__ look for a best
199 * extent and max_to_scan indicates how long the mballoc __can__ look for a
200 * best extent in the found extents. Searching for the blocks starts with
201 * the group specified as the goal value in allocation context via
202 * ac_g_ex. Each group is first checked based on the criteria whether it
203 * can be used for allocation. ext4_mb_good_group explains how the groups are
206 * When "mb_optimize_scan" is turned on, as mentioned above, the groups may not
207 * get traversed linearly. That may result in subsequent allocations being not
208 * close to each other. And so, the underlying device may get filled up in a
209 * non-linear fashion. While that may not matter on non-rotational devices, for
210 * rotational devices that may result in higher seek times. "mb_linear_limit"
211 * tells mballoc how many groups mballoc should search linearly before
212 * performing consulting above data structures for more efficient lookups. For
213 * non rotational devices, this value defaults to 0 and for rotational devices
214 * this is set to MB_DEFAULT_LINEAR_LIMIT.
216 * Both the prealloc space are getting populated as above. So for the first
217 * request we will hit the buddy cache which will result in this prealloc
218 * space getting filled. The prealloc space is then later used for the
219 * subsequent request.
223 * mballoc operates on the following data:
225 * - in-core buddy (actually includes buddy and bitmap)
226 * - preallocation descriptors (PAs)
228 * there are two types of preallocations:
230 * assiged to specific inode and can be used for this inode only.
231 * it describes part of inode's space preallocated to specific
232 * physical blocks. any block from that preallocated can be used
233 * independent. the descriptor just tracks number of blocks left
234 * unused. so, before taking some block from descriptor, one must
235 * make sure corresponded logical block isn't allocated yet. this
236 * also means that freeing any block within descriptor's range
237 * must discard all preallocated blocks.
239 * assigned to specific locality group which does not translate to
240 * permanent set of inodes: inode can join and leave group. space
241 * from this type of preallocation can be used for any inode. thus
242 * it's consumed from the beginning to the end.
244 * relation between them can be expressed as:
245 * in-core buddy = on-disk bitmap + preallocation descriptors
247 * this mean blocks mballoc considers used are:
248 * - allocated blocks (persistent)
249 * - preallocated blocks (non-persistent)
251 * consistency in mballoc world means that at any time a block is either
252 * free or used in ALL structures. notice: "any time" should not be read
253 * literally -- time is discrete and delimited by locks.
255 * to keep it simple, we don't use block numbers, instead we count number of
256 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
258 * all operations can be expressed as:
259 * - init buddy: buddy = on-disk + PAs
260 * - new PA: buddy += N; PA = N
261 * - use inode PA: on-disk += N; PA -= N
262 * - discard inode PA buddy -= on-disk - PA; PA = 0
263 * - use locality group PA on-disk += N; PA -= N
264 * - discard locality group PA buddy -= PA; PA = 0
265 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
266 * is used in real operation because we can't know actual used
267 * bits from PA, only from on-disk bitmap
269 * if we follow this strict logic, then all operations above should be atomic.
270 * given some of them can block, we'd have to use something like semaphores
271 * killing performance on high-end SMP hardware. let's try to relax it using
272 * the following knowledge:
273 * 1) if buddy is referenced, it's already initialized
274 * 2) while block is used in buddy and the buddy is referenced,
275 * nobody can re-allocate that block
276 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
277 * bit set and PA claims same block, it's OK. IOW, one can set bit in
278 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
281 * so, now we're building a concurrency table:
284 * blocks for PA are allocated in the buddy, buddy must be referenced
285 * until PA is linked to allocation group to avoid concurrent buddy init
287 * we need to make sure that either on-disk bitmap or PA has uptodate data
288 * given (3) we care that PA-=N operation doesn't interfere with init
290 * the simplest way would be to have buddy initialized by the discard
291 * - use locality group PA
292 * again PA-=N must be serialized with init
293 * - discard locality group PA
294 * the simplest way would be to have buddy initialized by the discard
297 * i_data_sem serializes them
299 * discard process must wait until PA isn't used by another process
300 * - use locality group PA
301 * some mutex should serialize them
302 * - discard locality group PA
303 * discard process must wait until PA isn't used by another process
306 * i_data_sem or another mutex should serializes them
308 * discard process must wait until PA isn't used by another process
309 * - use locality group PA
310 * nothing wrong here -- they're different PAs covering different blocks
311 * - discard locality group PA
312 * discard process must wait until PA isn't used by another process
314 * now we're ready to make few consequences:
315 * - PA is referenced and while it is no discard is possible
316 * - PA is referenced until block isn't marked in on-disk bitmap
317 * - PA changes only after on-disk bitmap
318 * - discard must not compete with init. either init is done before
319 * any discard or they're serialized somehow
320 * - buddy init as sum of on-disk bitmap and PAs is done atomically
322 * a special case when we've used PA to emptiness. no need to modify buddy
323 * in this case, but we should care about concurrent init
328 * Logic in few words:
333 * mark bits in on-disk bitmap
336 * - use preallocation:
337 * find proper PA (per-inode or group)
339 * mark bits in on-disk bitmap
345 * mark bits in on-disk bitmap
348 * - discard preallocations in group:
350 * move them onto local list
351 * load on-disk bitmap
353 * remove PA from object (inode or locality group)
354 * mark free blocks in-core
356 * - discard inode's preallocations:
363 * - bitlock on a group (group)
364 * - object (inode/locality) (object)
366 * - cr_power2_aligned lists lock (cr_power2_aligned)
367 * - cr_goal_len_fast lists lock (cr_goal_len_fast)
377 * - release consumed pa:
382 * - generate in-core bitmap:
386 * - discard all for given object (inode, locality group):
391 * - discard all for given group:
397 * - allocation path (ext4_mb_regular_allocator)
399 * cr_power2_aligned/cr_goal_len_fast
401 static struct kmem_cache *ext4_pspace_cachep;
402 static struct kmem_cache *ext4_ac_cachep;
403 static struct kmem_cache *ext4_free_data_cachep;
405 /* We create slab caches for groupinfo data structures based on the
406 * superblock block size. There will be one per mounted filesystem for
407 * each unique s_blocksize_bits */
408 #define NR_GRPINFO_CACHES 8
409 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
411 static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
412 "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
413 "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
414 "ext4_groupinfo_64k", "ext4_groupinfo_128k"
417 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
419 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
421 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac);
423 static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
424 ext4_group_t group, enum criteria cr);
426 static int ext4_try_to_trim_range(struct super_block *sb,
427 struct ext4_buddy *e4b, ext4_grpblk_t start,
428 ext4_grpblk_t max, ext4_grpblk_t minblocks);
431 * The algorithm using this percpu seq counter goes below:
432 * 1. We sample the percpu discard_pa_seq counter before trying for block
433 * allocation in ext4_mb_new_blocks().
434 * 2. We increment this percpu discard_pa_seq counter when we either allocate
435 * or free these blocks i.e. while marking those blocks as used/free in
436 * mb_mark_used()/mb_free_blocks().
437 * 3. We also increment this percpu seq counter when we successfully identify
438 * that the bb_prealloc_list is not empty and hence proceed for discarding
439 * of those PAs inside ext4_mb_discard_group_preallocations().
441 * Now to make sure that the regular fast path of block allocation is not
442 * affected, as a small optimization we only sample the percpu seq counter
443 * on that cpu. Only when the block allocation fails and when freed blocks
444 * found were 0, that is when we sample percpu seq counter for all cpus using
445 * below function ext4_get_discard_pa_seq_sum(). This happens after making
446 * sure that all the PAs on grp->bb_prealloc_list got freed or if it's empty.
448 static DEFINE_PER_CPU(u64, discard_pa_seq);
449 static inline u64 ext4_get_discard_pa_seq_sum(void)
454 for_each_possible_cpu(__cpu)
455 __seq += per_cpu(discard_pa_seq, __cpu);
459 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
461 #if BITS_PER_LONG == 64
462 *bit += ((unsigned long) addr & 7UL) << 3;
463 addr = (void *) ((unsigned long) addr & ~7UL);
464 #elif BITS_PER_LONG == 32
465 *bit += ((unsigned long) addr & 3UL) << 3;
466 addr = (void *) ((unsigned long) addr & ~3UL);
468 #error "how many bits you are?!"
473 static inline int mb_test_bit(int bit, void *addr)
476 * ext4_test_bit on architecture like powerpc
477 * needs unsigned long aligned address
479 addr = mb_correct_addr_and_bit(&bit, addr);
480 return ext4_test_bit(bit, addr);
483 static inline void mb_set_bit(int bit, void *addr)
485 addr = mb_correct_addr_and_bit(&bit, addr);
486 ext4_set_bit(bit, addr);
489 static inline void mb_clear_bit(int bit, void *addr)
491 addr = mb_correct_addr_and_bit(&bit, addr);
492 ext4_clear_bit(bit, addr);
495 static inline int mb_test_and_clear_bit(int bit, void *addr)
497 addr = mb_correct_addr_and_bit(&bit, addr);
498 return ext4_test_and_clear_bit(bit, addr);
501 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
503 int fix = 0, ret, tmpmax;
504 addr = mb_correct_addr_and_bit(&fix, addr);
508 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
514 static inline int mb_find_next_bit(void *addr, int max, int start)
516 int fix = 0, ret, tmpmax;
517 addr = mb_correct_addr_and_bit(&fix, addr);
521 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
527 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
531 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
534 if (order > e4b->bd_blkbits + 1) {
539 /* at order 0 we see each particular block */
541 *max = 1 << (e4b->bd_blkbits + 3);
542 return e4b->bd_bitmap;
545 bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
546 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
552 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
553 int first, int count)
556 struct super_block *sb = e4b->bd_sb;
558 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
560 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
561 for (i = 0; i < count; i++) {
562 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
563 ext4_fsblk_t blocknr;
565 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
566 blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
567 ext4_grp_locked_error(sb, e4b->bd_group,
568 inode ? inode->i_ino : 0,
570 "freeing block already freed "
573 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
574 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
576 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
580 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
584 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
586 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
587 for (i = 0; i < count; i++) {
588 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
589 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
593 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
595 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
597 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
598 unsigned char *b1, *b2;
600 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
601 b2 = (unsigned char *) bitmap;
602 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
603 if (b1[i] != b2[i]) {
604 ext4_msg(e4b->bd_sb, KERN_ERR,
605 "corruption in group %u "
606 "at byte %u(%u): %x in copy != %x "
608 e4b->bd_group, i, i * 8, b1[i], b2[i]);
615 static void mb_group_bb_bitmap_alloc(struct super_block *sb,
616 struct ext4_group_info *grp, ext4_group_t group)
618 struct buffer_head *bh;
620 grp->bb_bitmap = kmalloc(sb->s_blocksize, GFP_NOFS);
624 bh = ext4_read_block_bitmap(sb, group);
625 if (IS_ERR_OR_NULL(bh)) {
626 kfree(grp->bb_bitmap);
627 grp->bb_bitmap = NULL;
631 memcpy(grp->bb_bitmap, bh->b_data, sb->s_blocksize);
635 static void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
637 kfree(grp->bb_bitmap);
641 static inline void mb_free_blocks_double(struct inode *inode,
642 struct ext4_buddy *e4b, int first, int count)
646 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
647 int first, int count)
651 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
656 static inline void mb_group_bb_bitmap_alloc(struct super_block *sb,
657 struct ext4_group_info *grp, ext4_group_t group)
662 static inline void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
668 #ifdef AGGRESSIVE_CHECK
670 #define MB_CHECK_ASSERT(assert) \
674 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
675 function, file, line, # assert); \
680 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
681 const char *function, int line)
683 struct super_block *sb = e4b->bd_sb;
684 int order = e4b->bd_blkbits + 1;
691 struct ext4_group_info *grp;
694 struct list_head *cur;
698 if (e4b->bd_info->bb_check_counter++ % 10)
702 buddy = mb_find_buddy(e4b, order, &max);
703 MB_CHECK_ASSERT(buddy);
704 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
705 MB_CHECK_ASSERT(buddy2);
706 MB_CHECK_ASSERT(buddy != buddy2);
707 MB_CHECK_ASSERT(max * 2 == max2);
710 for (i = 0; i < max; i++) {
712 if (mb_test_bit(i, buddy)) {
713 /* only single bit in buddy2 may be 0 */
714 if (!mb_test_bit(i << 1, buddy2)) {
716 mb_test_bit((i<<1)+1, buddy2));
721 /* both bits in buddy2 must be 1 */
722 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
723 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
725 for (j = 0; j < (1 << order); j++) {
726 k = (i * (1 << order)) + j;
728 !mb_test_bit(k, e4b->bd_bitmap));
732 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
737 buddy = mb_find_buddy(e4b, 0, &max);
738 for (i = 0; i < max; i++) {
739 if (!mb_test_bit(i, buddy)) {
740 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
748 /* check used bits only */
749 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
750 buddy2 = mb_find_buddy(e4b, j, &max2);
752 MB_CHECK_ASSERT(k < max2);
753 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
756 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
757 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
759 grp = ext4_get_group_info(sb, e4b->bd_group);
762 list_for_each(cur, &grp->bb_prealloc_list) {
763 ext4_group_t groupnr;
764 struct ext4_prealloc_space *pa;
765 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
766 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
767 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
768 for (i = 0; i < pa->pa_len; i++)
769 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
773 #undef MB_CHECK_ASSERT
774 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
775 __FILE__, __func__, __LINE__)
777 #define mb_check_buddy(e4b)
781 * Divide blocks started from @first with length @len into
782 * smaller chunks with power of 2 blocks.
783 * Clear the bits in bitmap which the blocks of the chunk(s) covered,
784 * then increase bb_counters[] for corresponded chunk size.
786 static void ext4_mb_mark_free_simple(struct super_block *sb,
787 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
788 struct ext4_group_info *grp)
790 struct ext4_sb_info *sbi = EXT4_SB(sb);
796 BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
798 border = 2 << sb->s_blocksize_bits;
801 /* find how many blocks can be covered since this position */
802 max = ffs(first | border) - 1;
804 /* find how many blocks of power 2 we need to mark */
811 /* mark multiblock chunks only */
812 grp->bb_counters[min]++;
814 mb_clear_bit(first >> min,
815 buddy + sbi->s_mb_offsets[min]);
822 static int mb_avg_fragment_size_order(struct super_block *sb, ext4_grpblk_t len)
827 * We don't bother with a special lists groups with only 1 block free
828 * extents and for completely empty groups.
830 order = fls(len) - 2;
833 if (order == MB_NUM_ORDERS(sb))
838 /* Move group to appropriate avg_fragment_size list */
840 mb_update_avg_fragment_size(struct super_block *sb, struct ext4_group_info *grp)
842 struct ext4_sb_info *sbi = EXT4_SB(sb);
845 if (!test_opt2(sb, MB_OPTIMIZE_SCAN) || grp->bb_free == 0)
848 new_order = mb_avg_fragment_size_order(sb,
849 grp->bb_free / grp->bb_fragments);
850 if (new_order == grp->bb_avg_fragment_size_order)
853 if (grp->bb_avg_fragment_size_order != -1) {
854 write_lock(&sbi->s_mb_avg_fragment_size_locks[
855 grp->bb_avg_fragment_size_order]);
856 list_del(&grp->bb_avg_fragment_size_node);
857 write_unlock(&sbi->s_mb_avg_fragment_size_locks[
858 grp->bb_avg_fragment_size_order]);
860 grp->bb_avg_fragment_size_order = new_order;
861 write_lock(&sbi->s_mb_avg_fragment_size_locks[
862 grp->bb_avg_fragment_size_order]);
863 list_add_tail(&grp->bb_avg_fragment_size_node,
864 &sbi->s_mb_avg_fragment_size[grp->bb_avg_fragment_size_order]);
865 write_unlock(&sbi->s_mb_avg_fragment_size_locks[
866 grp->bb_avg_fragment_size_order]);
870 * Choose next group by traversing largest_free_order lists. Updates *new_cr if
871 * cr level needs an update.
873 static void ext4_mb_choose_next_group_p2_aligned(struct ext4_allocation_context *ac,
874 enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
876 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
877 struct ext4_group_info *iter, *grp;
880 if (ac->ac_status == AC_STATUS_FOUND)
883 if (unlikely(sbi->s_mb_stats && ac->ac_flags & EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED))
884 atomic_inc(&sbi->s_bal_p2_aligned_bad_suggestions);
887 for (i = ac->ac_2order; i < MB_NUM_ORDERS(ac->ac_sb); i++) {
888 if (list_empty(&sbi->s_mb_largest_free_orders[i]))
890 read_lock(&sbi->s_mb_largest_free_orders_locks[i]);
891 if (list_empty(&sbi->s_mb_largest_free_orders[i])) {
892 read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
896 list_for_each_entry(iter, &sbi->s_mb_largest_free_orders[i],
897 bb_largest_free_order_node) {
899 atomic64_inc(&sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]);
900 if (likely(ext4_mb_good_group(ac, iter->bb_group, CR_POWER2_ALIGNED))) {
905 read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
911 /* Increment cr and search again */
912 *new_cr = CR_GOAL_LEN_FAST;
914 *group = grp->bb_group;
915 ac->ac_flags |= EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED;
920 * Find a suitable group of given order from the average fragments list.
922 static struct ext4_group_info *
923 ext4_mb_find_good_group_avg_frag_lists(struct ext4_allocation_context *ac, int order)
925 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
926 struct list_head *frag_list = &sbi->s_mb_avg_fragment_size[order];
927 rwlock_t *frag_list_lock = &sbi->s_mb_avg_fragment_size_locks[order];
928 struct ext4_group_info *grp = NULL, *iter;
929 enum criteria cr = ac->ac_criteria;
931 if (list_empty(frag_list))
933 read_lock(frag_list_lock);
934 if (list_empty(frag_list)) {
935 read_unlock(frag_list_lock);
938 list_for_each_entry(iter, frag_list, bb_avg_fragment_size_node) {
940 atomic64_inc(&sbi->s_bal_cX_groups_considered[cr]);
941 if (likely(ext4_mb_good_group(ac, iter->bb_group, cr))) {
946 read_unlock(frag_list_lock);
951 * Choose next group by traversing average fragment size list of suitable
952 * order. Updates *new_cr if cr level needs an update.
954 static void ext4_mb_choose_next_group_goal_fast(struct ext4_allocation_context *ac,
955 enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
957 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
958 struct ext4_group_info *grp = NULL;
961 if (unlikely(ac->ac_flags & EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED)) {
963 atomic_inc(&sbi->s_bal_goal_fast_bad_suggestions);
966 for (i = mb_avg_fragment_size_order(ac->ac_sb, ac->ac_g_ex.fe_len);
967 i < MB_NUM_ORDERS(ac->ac_sb); i++) {
968 grp = ext4_mb_find_good_group_avg_frag_lists(ac, i);
974 *group = grp->bb_group;
975 ac->ac_flags |= EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED;
977 *new_cr = CR_BEST_AVAIL_LEN;
982 * We couldn't find a group in CR_GOAL_LEN_FAST so try to find the highest free fragment
983 * order we have and proactively trim the goal request length to that order to
984 * find a suitable group faster.
986 * This optimizes allocation speed at the cost of slightly reduced
987 * preallocations. However, we make sure that we don't trim the request too
988 * much and fall to CR_GOAL_LEN_SLOW in that case.
990 static void ext4_mb_choose_next_group_best_avail(struct ext4_allocation_context *ac,
991 enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
993 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
994 struct ext4_group_info *grp = NULL;
995 int i, order, min_order;
996 unsigned long num_stripe_clusters = 0;
998 if (unlikely(ac->ac_flags & EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED)) {
1000 atomic_inc(&sbi->s_bal_best_avail_bad_suggestions);
1004 * mb_avg_fragment_size_order() returns order in a way that makes
1005 * retrieving back the length using (1 << order) inaccurate. Hence, use
1006 * fls() instead since we need to know the actual length while modifying
1009 order = fls(ac->ac_g_ex.fe_len) - 1;
1010 min_order = order - sbi->s_mb_best_avail_max_trim_order;
1014 if (sbi->s_stripe > 0) {
1016 * We are assuming that stripe size is always a multiple of
1017 * cluster ratio otherwise __ext4_fill_super exists early.
1019 num_stripe_clusters = EXT4_NUM_B2C(sbi, sbi->s_stripe);
1020 if (1 << min_order < num_stripe_clusters)
1022 * We consider 1 order less because later we round
1023 * up the goal len to num_stripe_clusters
1025 min_order = fls(num_stripe_clusters) - 1;
1028 if (1 << min_order < ac->ac_o_ex.fe_len)
1029 min_order = fls(ac->ac_o_ex.fe_len);
1031 for (i = order; i >= min_order; i--) {
1034 * Scale down goal len to make sure we find something
1035 * in the free fragments list. Basically, reduce
1038 ac->ac_g_ex.fe_len = 1 << i;
1040 if (num_stripe_clusters > 0) {
1042 * Try to round up the adjusted goal length to
1043 * stripe size (in cluster units) multiple for
1046 ac->ac_g_ex.fe_len = roundup(ac->ac_g_ex.fe_len,
1047 num_stripe_clusters);
1050 frag_order = mb_avg_fragment_size_order(ac->ac_sb,
1051 ac->ac_g_ex.fe_len);
1053 grp = ext4_mb_find_good_group_avg_frag_lists(ac, frag_order);
1059 *group = grp->bb_group;
1060 ac->ac_flags |= EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED;
1062 /* Reset goal length to original goal length before falling into CR_GOAL_LEN_SLOW */
1063 ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
1064 *new_cr = CR_GOAL_LEN_SLOW;
1068 static inline int should_optimize_scan(struct ext4_allocation_context *ac)
1070 if (unlikely(!test_opt2(ac->ac_sb, MB_OPTIMIZE_SCAN)))
1072 if (ac->ac_criteria >= CR_GOAL_LEN_SLOW)
1074 if (!ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS))
1080 * Return next linear group for allocation. If linear traversal should not be
1081 * performed, this function just returns the same group
1084 next_linear_group(struct ext4_allocation_context *ac, int group, int ngroups)
1086 if (!should_optimize_scan(ac))
1087 goto inc_and_return;
1089 if (ac->ac_groups_linear_remaining) {
1090 ac->ac_groups_linear_remaining--;
1091 goto inc_and_return;
1097 * Artificially restricted ngroups for non-extent
1098 * files makes group > ngroups possible on first loop.
1100 return group + 1 >= ngroups ? 0 : group + 1;
1104 * ext4_mb_choose_next_group: choose next group for allocation.
1106 * @ac Allocation Context
1107 * @new_cr This is an output parameter. If the there is no good group
1108 * available at current CR level, this field is updated to indicate
1109 * the new cr level that should be used.
1110 * @group This is an input / output parameter. As an input it indicates the
1111 * next group that the allocator intends to use for allocation. As
1112 * output, this field indicates the next group that should be used as
1113 * determined by the optimization functions.
1114 * @ngroups Total number of groups
1116 static void ext4_mb_choose_next_group(struct ext4_allocation_context *ac,
1117 enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
1119 *new_cr = ac->ac_criteria;
1121 if (!should_optimize_scan(ac) || ac->ac_groups_linear_remaining) {
1122 *group = next_linear_group(ac, *group, ngroups);
1126 if (*new_cr == CR_POWER2_ALIGNED) {
1127 ext4_mb_choose_next_group_p2_aligned(ac, new_cr, group, ngroups);
1128 } else if (*new_cr == CR_GOAL_LEN_FAST) {
1129 ext4_mb_choose_next_group_goal_fast(ac, new_cr, group, ngroups);
1130 } else if (*new_cr == CR_BEST_AVAIL_LEN) {
1131 ext4_mb_choose_next_group_best_avail(ac, new_cr, group, ngroups);
1134 * TODO: For CR=2, we can arrange groups in an rb tree sorted by
1135 * bb_free. But until that happens, we should never come here.
1142 * Cache the order of the largest free extent we have available in this block
1146 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
1148 struct ext4_sb_info *sbi = EXT4_SB(sb);
1151 for (i = MB_NUM_ORDERS(sb) - 1; i >= 0; i--)
1152 if (grp->bb_counters[i] > 0)
1154 /* No need to move between order lists? */
1155 if (!test_opt2(sb, MB_OPTIMIZE_SCAN) ||
1156 i == grp->bb_largest_free_order) {
1157 grp->bb_largest_free_order = i;
1161 if (grp->bb_largest_free_order >= 0) {
1162 write_lock(&sbi->s_mb_largest_free_orders_locks[
1163 grp->bb_largest_free_order]);
1164 list_del_init(&grp->bb_largest_free_order_node);
1165 write_unlock(&sbi->s_mb_largest_free_orders_locks[
1166 grp->bb_largest_free_order]);
1168 grp->bb_largest_free_order = i;
1169 if (grp->bb_largest_free_order >= 0 && grp->bb_free) {
1170 write_lock(&sbi->s_mb_largest_free_orders_locks[
1171 grp->bb_largest_free_order]);
1172 list_add_tail(&grp->bb_largest_free_order_node,
1173 &sbi->s_mb_largest_free_orders[grp->bb_largest_free_order]);
1174 write_unlock(&sbi->s_mb_largest_free_orders_locks[
1175 grp->bb_largest_free_order]);
1179 static noinline_for_stack
1180 void ext4_mb_generate_buddy(struct super_block *sb,
1181 void *buddy, void *bitmap, ext4_group_t group,
1182 struct ext4_group_info *grp)
1184 struct ext4_sb_info *sbi = EXT4_SB(sb);
1185 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
1186 ext4_grpblk_t i = 0;
1187 ext4_grpblk_t first;
1190 unsigned fragments = 0;
1191 unsigned long long period = get_cycles();
1193 /* initialize buddy from bitmap which is aggregation
1194 * of on-disk bitmap and preallocations */
1195 i = mb_find_next_zero_bit(bitmap, max, 0);
1196 grp->bb_first_free = i;
1200 i = mb_find_next_bit(bitmap, max, i);
1204 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
1206 grp->bb_counters[0]++;
1208 i = mb_find_next_zero_bit(bitmap, max, i);
1210 grp->bb_fragments = fragments;
1212 if (free != grp->bb_free) {
1213 ext4_grp_locked_error(sb, group, 0, 0,
1214 "block bitmap and bg descriptor "
1215 "inconsistent: %u vs %u free clusters",
1216 free, grp->bb_free);
1218 * If we intend to continue, we consider group descriptor
1219 * corrupt and update bb_free using bitmap value
1221 grp->bb_free = free;
1222 ext4_mark_group_bitmap_corrupted(sb, group,
1223 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1225 mb_set_largest_free_order(sb, grp);
1226 mb_update_avg_fragment_size(sb, grp);
1228 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
1230 period = get_cycles() - period;
1231 atomic_inc(&sbi->s_mb_buddies_generated);
1232 atomic64_add(period, &sbi->s_mb_generation_time);
1235 /* The buddy information is attached the buddy cache inode
1236 * for convenience. The information regarding each group
1237 * is loaded via ext4_mb_load_buddy. The information involve
1238 * block bitmap and buddy information. The information are
1239 * stored in the inode as
1242 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
1245 * one block each for bitmap and buddy information.
1246 * So for each group we take up 2 blocks. A page can
1247 * contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
1248 * So it can have information regarding groups_per_page which
1249 * is blocks_per_page/2
1251 * Locking note: This routine takes the block group lock of all groups
1252 * for this page; do not hold this lock when calling this routine!
1255 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
1257 ext4_group_t ngroups;
1259 int blocks_per_page;
1260 int groups_per_page;
1263 ext4_group_t first_group, group;
1265 struct super_block *sb;
1266 struct buffer_head *bhs;
1267 struct buffer_head **bh = NULL;
1268 struct inode *inode;
1271 struct ext4_group_info *grinfo;
1273 inode = page->mapping->host;
1275 ngroups = ext4_get_groups_count(sb);
1276 blocksize = i_blocksize(inode);
1277 blocks_per_page = PAGE_SIZE / blocksize;
1279 mb_debug(sb, "init page %lu\n", page->index);
1281 groups_per_page = blocks_per_page >> 1;
1282 if (groups_per_page == 0)
1283 groups_per_page = 1;
1285 /* allocate buffer_heads to read bitmaps */
1286 if (groups_per_page > 1) {
1287 i = sizeof(struct buffer_head *) * groups_per_page;
1288 bh = kzalloc(i, gfp);
1294 first_group = page->index * blocks_per_page / 2;
1296 /* read all groups the page covers into the cache */
1297 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1298 if (group >= ngroups)
1301 grinfo = ext4_get_group_info(sb, group);
1305 * If page is uptodate then we came here after online resize
1306 * which added some new uninitialized group info structs, so
1307 * we must skip all initialized uptodate buddies on the page,
1308 * which may be currently in use by an allocating task.
1310 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
1314 bh[i] = ext4_read_block_bitmap_nowait(sb, group, false);
1315 if (IS_ERR(bh[i])) {
1316 err = PTR_ERR(bh[i]);
1320 mb_debug(sb, "read bitmap for group %u\n", group);
1323 /* wait for I/O completion */
1324 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1329 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
1334 first_block = page->index * blocks_per_page;
1335 for (i = 0; i < blocks_per_page; i++) {
1336 group = (first_block + i) >> 1;
1337 if (group >= ngroups)
1340 if (!bh[group - first_group])
1341 /* skip initialized uptodate buddy */
1344 if (!buffer_verified(bh[group - first_group]))
1345 /* Skip faulty bitmaps */
1350 * data carry information regarding this
1351 * particular group in the format specified
1355 data = page_address(page) + (i * blocksize);
1356 bitmap = bh[group - first_group]->b_data;
1359 * We place the buddy block and bitmap block
1362 if ((first_block + i) & 1) {
1363 /* this is block of buddy */
1364 BUG_ON(incore == NULL);
1365 mb_debug(sb, "put buddy for group %u in page %lu/%x\n",
1366 group, page->index, i * blocksize);
1367 trace_ext4_mb_buddy_bitmap_load(sb, group);
1368 grinfo = ext4_get_group_info(sb, group);
1370 err = -EFSCORRUPTED;
1373 grinfo->bb_fragments = 0;
1374 memset(grinfo->bb_counters, 0,
1375 sizeof(*grinfo->bb_counters) *
1376 (MB_NUM_ORDERS(sb)));
1378 * incore got set to the group block bitmap below
1380 ext4_lock_group(sb, group);
1381 /* init the buddy */
1382 memset(data, 0xff, blocksize);
1383 ext4_mb_generate_buddy(sb, data, incore, group, grinfo);
1384 ext4_unlock_group(sb, group);
1387 /* this is block of bitmap */
1388 BUG_ON(incore != NULL);
1389 mb_debug(sb, "put bitmap for group %u in page %lu/%x\n",
1390 group, page->index, i * blocksize);
1391 trace_ext4_mb_bitmap_load(sb, group);
1393 /* see comments in ext4_mb_put_pa() */
1394 ext4_lock_group(sb, group);
1395 memcpy(data, bitmap, blocksize);
1397 /* mark all preallocated blks used in in-core bitmap */
1398 ext4_mb_generate_from_pa(sb, data, group);
1399 ext4_mb_generate_from_freelist(sb, data, group);
1400 ext4_unlock_group(sb, group);
1402 /* set incore so that the buddy information can be
1403 * generated using this
1408 SetPageUptodate(page);
1412 for (i = 0; i < groups_per_page; i++)
1421 * Lock the buddy and bitmap pages. This make sure other parallel init_group
1422 * on the same buddy page doesn't happen whild holding the buddy page lock.
1423 * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
1424 * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
1426 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
1427 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
1429 struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
1430 int block, pnum, poff;
1431 int blocks_per_page;
1434 e4b->bd_buddy_page = NULL;
1435 e4b->bd_bitmap_page = NULL;
1437 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1439 * the buddy cache inode stores the block bitmap
1440 * and buddy information in consecutive blocks.
1441 * So for each group we need two blocks.
1444 pnum = block / blocks_per_page;
1445 poff = block % blocks_per_page;
1446 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1449 BUG_ON(page->mapping != inode->i_mapping);
1450 e4b->bd_bitmap_page = page;
1451 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1453 if (blocks_per_page >= 2) {
1454 /* buddy and bitmap are on the same page */
1459 pnum = block / blocks_per_page;
1460 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1463 BUG_ON(page->mapping != inode->i_mapping);
1464 e4b->bd_buddy_page = page;
1468 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1470 if (e4b->bd_bitmap_page) {
1471 unlock_page(e4b->bd_bitmap_page);
1472 put_page(e4b->bd_bitmap_page);
1474 if (e4b->bd_buddy_page) {
1475 unlock_page(e4b->bd_buddy_page);
1476 put_page(e4b->bd_buddy_page);
1481 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1482 * block group lock of all groups for this page; do not hold the BG lock when
1483 * calling this routine!
1485 static noinline_for_stack
1486 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1489 struct ext4_group_info *this_grp;
1490 struct ext4_buddy e4b;
1495 mb_debug(sb, "init group %u\n", group);
1496 this_grp = ext4_get_group_info(sb, group);
1498 return -EFSCORRUPTED;
1501 * This ensures that we don't reinit the buddy cache
1502 * page which map to the group from which we are already
1503 * allocating. If we are looking at the buddy cache we would
1504 * have taken a reference using ext4_mb_load_buddy and that
1505 * would have pinned buddy page to page cache.
1506 * The call to ext4_mb_get_buddy_page_lock will mark the
1509 ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1510 if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1512 * somebody initialized the group
1513 * return without doing anything
1518 page = e4b.bd_bitmap_page;
1519 ret = ext4_mb_init_cache(page, NULL, gfp);
1522 if (!PageUptodate(page)) {
1527 if (e4b.bd_buddy_page == NULL) {
1529 * If both the bitmap and buddy are in
1530 * the same page we don't need to force
1536 /* init buddy cache */
1537 page = e4b.bd_buddy_page;
1538 ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1541 if (!PageUptodate(page)) {
1546 ext4_mb_put_buddy_page_lock(&e4b);
1551 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1552 * block group lock of all groups for this page; do not hold the BG lock when
1553 * calling this routine!
1555 static noinline_for_stack int
1556 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1557 struct ext4_buddy *e4b, gfp_t gfp)
1559 int blocks_per_page;
1565 struct ext4_group_info *grp;
1566 struct ext4_sb_info *sbi = EXT4_SB(sb);
1567 struct inode *inode = sbi->s_buddy_cache;
1570 mb_debug(sb, "load group %u\n", group);
1572 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1573 grp = ext4_get_group_info(sb, group);
1575 return -EFSCORRUPTED;
1577 e4b->bd_blkbits = sb->s_blocksize_bits;
1580 e4b->bd_group = group;
1581 e4b->bd_buddy_page = NULL;
1582 e4b->bd_bitmap_page = NULL;
1584 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1586 * we need full data about the group
1587 * to make a good selection
1589 ret = ext4_mb_init_group(sb, group, gfp);
1595 * the buddy cache inode stores the block bitmap
1596 * and buddy information in consecutive blocks.
1597 * So for each group we need two blocks.
1600 pnum = block / blocks_per_page;
1601 poff = block % blocks_per_page;
1603 /* we could use find_or_create_page(), but it locks page
1604 * what we'd like to avoid in fast path ... */
1605 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1606 if (page == NULL || !PageUptodate(page)) {
1609 * drop the page reference and try
1610 * to get the page with lock. If we
1611 * are not uptodate that implies
1612 * somebody just created the page but
1613 * is yet to initialize the same. So
1614 * wait for it to initialize.
1617 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1619 if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
1620 "ext4: bitmap's paging->mapping != inode->i_mapping\n")) {
1621 /* should never happen */
1626 if (!PageUptodate(page)) {
1627 ret = ext4_mb_init_cache(page, NULL, gfp);
1632 mb_cmp_bitmaps(e4b, page_address(page) +
1633 (poff * sb->s_blocksize));
1642 if (!PageUptodate(page)) {
1647 /* Pages marked accessed already */
1648 e4b->bd_bitmap_page = page;
1649 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1652 pnum = block / blocks_per_page;
1653 poff = block % blocks_per_page;
1655 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1656 if (page == NULL || !PageUptodate(page)) {
1659 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1661 if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
1662 "ext4: buddy bitmap's page->mapping != inode->i_mapping\n")) {
1663 /* should never happen */
1668 if (!PageUptodate(page)) {
1669 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1683 if (!PageUptodate(page)) {
1688 /* Pages marked accessed already */
1689 e4b->bd_buddy_page = page;
1690 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1697 if (e4b->bd_bitmap_page)
1698 put_page(e4b->bd_bitmap_page);
1700 e4b->bd_buddy = NULL;
1701 e4b->bd_bitmap = NULL;
1705 static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1706 struct ext4_buddy *e4b)
1708 return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1711 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1713 if (e4b->bd_bitmap_page)
1714 put_page(e4b->bd_bitmap_page);
1715 if (e4b->bd_buddy_page)
1716 put_page(e4b->bd_buddy_page);
1720 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1725 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1726 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1728 while (order <= e4b->bd_blkbits + 1) {
1729 bb = mb_find_buddy(e4b, order, &max);
1730 if (!mb_test_bit(block >> order, bb)) {
1731 /* this block is part of buddy of order 'order' */
1739 static void mb_clear_bits(void *bm, int cur, int len)
1745 if ((cur & 31) == 0 && (len - cur) >= 32) {
1746 /* fast path: clear whole word at once */
1747 addr = bm + (cur >> 3);
1752 mb_clear_bit(cur, bm);
1757 /* clear bits in given range
1758 * will return first found zero bit if any, -1 otherwise
1760 static int mb_test_and_clear_bits(void *bm, int cur, int len)
1767 if ((cur & 31) == 0 && (len - cur) >= 32) {
1768 /* fast path: clear whole word at once */
1769 addr = bm + (cur >> 3);
1770 if (*addr != (__u32)(-1) && zero_bit == -1)
1771 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1776 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1784 void mb_set_bits(void *bm, int cur, int len)
1790 if ((cur & 31) == 0 && (len - cur) >= 32) {
1791 /* fast path: set whole word at once */
1792 addr = bm + (cur >> 3);
1797 mb_set_bit(cur, bm);
1802 static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1804 if (mb_test_bit(*bit + side, bitmap)) {
1805 mb_clear_bit(*bit, bitmap);
1811 mb_set_bit(*bit, bitmap);
1816 static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1820 void *buddy = mb_find_buddy(e4b, order, &max);
1825 /* Bits in range [first; last] are known to be set since
1826 * corresponding blocks were allocated. Bits in range
1827 * (first; last) will stay set because they form buddies on
1828 * upper layer. We just deal with borders if they don't
1829 * align with upper layer and then go up.
1830 * Releasing entire group is all about clearing
1831 * single bit of highest order buddy.
1835 * ---------------------------------
1837 * ---------------------------------
1838 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1839 * ---------------------------------
1841 * \_____________________/
1843 * Neither [1] nor [6] is aligned to above layer.
1844 * Left neighbour [0] is free, so mark it busy,
1845 * decrease bb_counters and extend range to
1847 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1848 * mark [6] free, increase bb_counters and shrink range to
1850 * Then shift range to [0; 2], go up and do the same.
1855 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1857 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1862 buddy2 = mb_find_buddy(e4b, order, &max);
1864 mb_clear_bits(buddy, first, last - first + 1);
1865 e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1874 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1875 int first, int count)
1877 int left_is_free = 0;
1878 int right_is_free = 0;
1880 int last = first + count - 1;
1881 struct super_block *sb = e4b->bd_sb;
1883 if (WARN_ON(count == 0))
1885 BUG_ON(last >= (sb->s_blocksize << 3));
1886 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1887 /* Don't bother if the block group is corrupt. */
1888 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1891 mb_check_buddy(e4b);
1892 mb_free_blocks_double(inode, e4b, first, count);
1894 this_cpu_inc(discard_pa_seq);
1895 e4b->bd_info->bb_free += count;
1896 if (first < e4b->bd_info->bb_first_free)
1897 e4b->bd_info->bb_first_free = first;
1899 /* access memory sequentially: check left neighbour,
1900 * clear range and then check right neighbour
1903 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1904 block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1905 if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1906 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1908 if (unlikely(block != -1)) {
1909 struct ext4_sb_info *sbi = EXT4_SB(sb);
1910 ext4_fsblk_t blocknr;
1912 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1913 blocknr += EXT4_C2B(sbi, block);
1914 if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
1915 ext4_grp_locked_error(sb, e4b->bd_group,
1916 inode ? inode->i_ino : 0,
1918 "freeing already freed block (bit %u); block bitmap corrupt.",
1920 ext4_mark_group_bitmap_corrupted(
1922 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1927 /* let's maintain fragments counter */
1928 if (left_is_free && right_is_free)
1929 e4b->bd_info->bb_fragments--;
1930 else if (!left_is_free && !right_is_free)
1931 e4b->bd_info->bb_fragments++;
1933 /* buddy[0] == bd_bitmap is a special case, so handle
1934 * it right away and let mb_buddy_mark_free stay free of
1935 * zero order checks.
1936 * Check if neighbours are to be coaleasced,
1937 * adjust bitmap bb_counters and borders appropriately.
1940 first += !left_is_free;
1941 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1944 last -= !right_is_free;
1945 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1949 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1952 mb_set_largest_free_order(sb, e4b->bd_info);
1953 mb_update_avg_fragment_size(sb, e4b->bd_info);
1954 mb_check_buddy(e4b);
1957 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1958 int needed, struct ext4_free_extent *ex)
1964 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1967 buddy = mb_find_buddy(e4b, 0, &max);
1968 BUG_ON(buddy == NULL);
1969 BUG_ON(block >= max);
1970 if (mb_test_bit(block, buddy)) {
1977 /* find actual order */
1978 order = mb_find_order_for_block(e4b, block);
1979 block = block >> order;
1981 ex->fe_len = 1 << order;
1982 ex->fe_start = block << order;
1983 ex->fe_group = e4b->bd_group;
1985 /* calc difference from given start */
1986 next = next - ex->fe_start;
1988 ex->fe_start += next;
1990 while (needed > ex->fe_len &&
1991 mb_find_buddy(e4b, order, &max)) {
1993 if (block + 1 >= max)
1996 next = (block + 1) * (1 << order);
1997 if (mb_test_bit(next, e4b->bd_bitmap))
2000 order = mb_find_order_for_block(e4b, next);
2002 block = next >> order;
2003 ex->fe_len += 1 << order;
2006 if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
2007 /* Should never happen! (but apparently sometimes does?!?) */
2009 ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
2010 "corruption or bug in mb_find_extent "
2011 "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
2012 block, order, needed, ex->fe_group, ex->fe_start,
2013 ex->fe_len, ex->fe_logical);
2021 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
2027 int start = ex->fe_start;
2028 int len = ex->fe_len;
2034 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
2035 BUG_ON(e4b->bd_group != ex->fe_group);
2036 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
2037 mb_check_buddy(e4b);
2038 mb_mark_used_double(e4b, start, len);
2040 this_cpu_inc(discard_pa_seq);
2041 e4b->bd_info->bb_free -= len;
2042 if (e4b->bd_info->bb_first_free == start)
2043 e4b->bd_info->bb_first_free += len;
2045 /* let's maintain fragments counter */
2047 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
2048 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
2049 max = !mb_test_bit(start + len, e4b->bd_bitmap);
2051 e4b->bd_info->bb_fragments++;
2052 else if (!mlen && !max)
2053 e4b->bd_info->bb_fragments--;
2055 /* let's maintain buddy itself */
2058 ord = mb_find_order_for_block(e4b, start);
2060 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
2061 /* the whole chunk may be allocated at once! */
2064 buddy = mb_find_buddy(e4b, ord, &max);
2067 BUG_ON((start >> ord) >= max);
2068 mb_set_bit(start >> ord, buddy);
2069 e4b->bd_info->bb_counters[ord]--;
2076 /* store for history */
2078 ret = len | (ord << 16);
2080 /* we have to split large buddy */
2082 buddy = mb_find_buddy(e4b, ord, &max);
2083 mb_set_bit(start >> ord, buddy);
2084 e4b->bd_info->bb_counters[ord]--;
2087 cur = (start >> ord) & ~1U;
2088 buddy = mb_find_buddy(e4b, ord, &max);
2089 mb_clear_bit(cur, buddy);
2090 mb_clear_bit(cur + 1, buddy);
2091 e4b->bd_info->bb_counters[ord]++;
2092 e4b->bd_info->bb_counters[ord]++;
2095 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
2097 mb_update_avg_fragment_size(e4b->bd_sb, e4b->bd_info);
2098 mb_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
2099 mb_check_buddy(e4b);
2105 * Must be called under group lock!
2107 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
2108 struct ext4_buddy *e4b)
2110 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2113 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
2114 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2116 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
2117 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
2118 ret = mb_mark_used(e4b, &ac->ac_b_ex);
2120 /* preallocation can change ac_b_ex, thus we store actually
2121 * allocated blocks for history */
2122 ac->ac_f_ex = ac->ac_b_ex;
2124 ac->ac_status = AC_STATUS_FOUND;
2125 ac->ac_tail = ret & 0xffff;
2126 ac->ac_buddy = ret >> 16;
2129 * take the page reference. We want the page to be pinned
2130 * so that we don't get a ext4_mb_init_cache_call for this
2131 * group until we update the bitmap. That would mean we
2132 * double allocate blocks. The reference is dropped
2133 * in ext4_mb_release_context
2135 ac->ac_bitmap_page = e4b->bd_bitmap_page;
2136 get_page(ac->ac_bitmap_page);
2137 ac->ac_buddy_page = e4b->bd_buddy_page;
2138 get_page(ac->ac_buddy_page);
2139 /* store last allocated for subsequent stream allocation */
2140 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2141 spin_lock(&sbi->s_md_lock);
2142 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
2143 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
2144 spin_unlock(&sbi->s_md_lock);
2147 * As we've just preallocated more space than
2148 * user requested originally, we store allocated
2149 * space in a special descriptor.
2151 if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
2152 ext4_mb_new_preallocation(ac);
2156 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
2157 struct ext4_buddy *e4b,
2160 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2161 struct ext4_free_extent *bex = &ac->ac_b_ex;
2162 struct ext4_free_extent *gex = &ac->ac_g_ex;
2164 if (ac->ac_status == AC_STATUS_FOUND)
2167 * We don't want to scan for a whole year
2169 if (ac->ac_found > sbi->s_mb_max_to_scan &&
2170 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2171 ac->ac_status = AC_STATUS_BREAK;
2176 * Haven't found good chunk so far, let's continue
2178 if (bex->fe_len < gex->fe_len)
2181 if (finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
2182 ext4_mb_use_best_found(ac, e4b);
2186 * The routine checks whether found extent is good enough. If it is,
2187 * then the extent gets marked used and flag is set to the context
2188 * to stop scanning. Otherwise, the extent is compared with the
2189 * previous found extent and if new one is better, then it's stored
2190 * in the context. Later, the best found extent will be used, if
2191 * mballoc can't find good enough extent.
2193 * The algorithm used is roughly as follows:
2195 * * If free extent found is exactly as big as goal, then
2196 * stop the scan and use it immediately
2198 * * If free extent found is smaller than goal, then keep retrying
2199 * upto a max of sbi->s_mb_max_to_scan times (default 200). After
2200 * that stop scanning and use whatever we have.
2202 * * If free extent found is bigger than goal, then keep retrying
2203 * upto a max of sbi->s_mb_min_to_scan times (default 10) before
2204 * stopping the scan and using the extent.
2207 * FIXME: real allocation policy is to be designed yet!
2209 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
2210 struct ext4_free_extent *ex,
2211 struct ext4_buddy *e4b)
2213 struct ext4_free_extent *bex = &ac->ac_b_ex;
2214 struct ext4_free_extent *gex = &ac->ac_g_ex;
2216 BUG_ON(ex->fe_len <= 0);
2217 BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2218 BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2219 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
2222 ac->ac_cX_found[ac->ac_criteria]++;
2225 * The special case - take what you catch first
2227 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2229 ext4_mb_use_best_found(ac, e4b);
2234 * Let's check whether the chuck is good enough
2236 if (ex->fe_len == gex->fe_len) {
2238 ext4_mb_use_best_found(ac, e4b);
2243 * If this is first found extent, just store it in the context
2245 if (bex->fe_len == 0) {
2251 * If new found extent is better, store it in the context
2253 if (bex->fe_len < gex->fe_len) {
2254 /* if the request isn't satisfied, any found extent
2255 * larger than previous best one is better */
2256 if (ex->fe_len > bex->fe_len)
2258 } else if (ex->fe_len > gex->fe_len) {
2259 /* if the request is satisfied, then we try to find
2260 * an extent that still satisfy the request, but is
2261 * smaller than previous one */
2262 if (ex->fe_len < bex->fe_len)
2266 ext4_mb_check_limits(ac, e4b, 0);
2269 static noinline_for_stack
2270 void ext4_mb_try_best_found(struct ext4_allocation_context *ac,
2271 struct ext4_buddy *e4b)
2273 struct ext4_free_extent ex = ac->ac_b_ex;
2274 ext4_group_t group = ex.fe_group;
2278 BUG_ON(ex.fe_len <= 0);
2279 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2283 ext4_lock_group(ac->ac_sb, group);
2284 max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
2288 ext4_mb_use_best_found(ac, e4b);
2291 ext4_unlock_group(ac->ac_sb, group);
2292 ext4_mb_unload_buddy(e4b);
2295 static noinline_for_stack
2296 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
2297 struct ext4_buddy *e4b)
2299 ext4_group_t group = ac->ac_g_ex.fe_group;
2302 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2303 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2304 struct ext4_free_extent ex;
2307 return -EFSCORRUPTED;
2308 if (!(ac->ac_flags & (EXT4_MB_HINT_TRY_GOAL | EXT4_MB_HINT_GOAL_ONLY)))
2310 if (grp->bb_free == 0)
2313 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2317 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
2318 ext4_mb_unload_buddy(e4b);
2322 ext4_lock_group(ac->ac_sb, group);
2323 max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
2324 ac->ac_g_ex.fe_len, &ex);
2325 ex.fe_logical = 0xDEADFA11; /* debug value */
2327 if (max >= ac->ac_g_ex.fe_len &&
2328 ac->ac_g_ex.fe_len == EXT4_B2C(sbi, sbi->s_stripe)) {
2331 start = ext4_grp_offs_to_block(ac->ac_sb, &ex);
2332 /* use do_div to get remainder (would be 64-bit modulo) */
2333 if (do_div(start, sbi->s_stripe) == 0) {
2336 ext4_mb_use_best_found(ac, e4b);
2338 } else if (max >= ac->ac_g_ex.fe_len) {
2339 BUG_ON(ex.fe_len <= 0);
2340 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2341 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2344 ext4_mb_use_best_found(ac, e4b);
2345 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
2346 /* Sometimes, caller may want to merge even small
2347 * number of blocks to an existing extent */
2348 BUG_ON(ex.fe_len <= 0);
2349 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2350 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2353 ext4_mb_use_best_found(ac, e4b);
2355 ext4_unlock_group(ac->ac_sb, group);
2356 ext4_mb_unload_buddy(e4b);
2362 * The routine scans buddy structures (not bitmap!) from given order
2363 * to max order and tries to find big enough chunk to satisfy the req
2365 static noinline_for_stack
2366 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
2367 struct ext4_buddy *e4b)
2369 struct super_block *sb = ac->ac_sb;
2370 struct ext4_group_info *grp = e4b->bd_info;
2376 BUG_ON(ac->ac_2order <= 0);
2377 for (i = ac->ac_2order; i < MB_NUM_ORDERS(sb); i++) {
2378 if (grp->bb_counters[i] == 0)
2381 buddy = mb_find_buddy(e4b, i, &max);
2382 if (WARN_RATELIMIT(buddy == NULL,
2383 "ext4: mb_simple_scan_group: mb_find_buddy failed, (%d)\n", i))
2386 k = mb_find_next_zero_bit(buddy, max, 0);
2388 ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
2389 "%d free clusters of order %d. But found 0",
2390 grp->bb_counters[i], i);
2391 ext4_mark_group_bitmap_corrupted(ac->ac_sb,
2393 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2397 ac->ac_cX_found[ac->ac_criteria]++;
2399 ac->ac_b_ex.fe_len = 1 << i;
2400 ac->ac_b_ex.fe_start = k << i;
2401 ac->ac_b_ex.fe_group = e4b->bd_group;
2403 ext4_mb_use_best_found(ac, e4b);
2405 BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
2407 if (EXT4_SB(sb)->s_mb_stats)
2408 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
2415 * The routine scans the group and measures all found extents.
2416 * In order to optimize scanning, caller must pass number of
2417 * free blocks in the group, so the routine can know upper limit.
2419 static noinline_for_stack
2420 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
2421 struct ext4_buddy *e4b)
2423 struct super_block *sb = ac->ac_sb;
2424 void *bitmap = e4b->bd_bitmap;
2425 struct ext4_free_extent ex;
2429 free = e4b->bd_info->bb_free;
2430 if (WARN_ON(free <= 0))
2433 i = e4b->bd_info->bb_first_free;
2435 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
2436 i = mb_find_next_zero_bit(bitmap,
2437 EXT4_CLUSTERS_PER_GROUP(sb), i);
2438 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
2440 * IF we have corrupt bitmap, we won't find any
2441 * free blocks even though group info says we
2444 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2445 "%d free clusters as per "
2446 "group info. But bitmap says 0",
2448 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2449 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2453 if (ac->ac_criteria < CR_FAST) {
2455 * In CR_GOAL_LEN_FAST and CR_BEST_AVAIL_LEN, we are
2456 * sure that this group will have a large enough
2457 * continuous free extent, so skip over the smaller free
2460 j = mb_find_next_bit(bitmap,
2461 EXT4_CLUSTERS_PER_GROUP(sb), i);
2464 if (freelen < ac->ac_g_ex.fe_len) {
2471 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
2472 if (WARN_ON(ex.fe_len <= 0))
2474 if (free < ex.fe_len) {
2475 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2476 "%d free clusters as per "
2477 "group info. But got %d blocks",
2479 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2480 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2482 * The number of free blocks differs. This mostly
2483 * indicate that the bitmap is corrupt. So exit
2484 * without claiming the space.
2488 ex.fe_logical = 0xDEADC0DE; /* debug value */
2489 ext4_mb_measure_extent(ac, &ex, e4b);
2495 ext4_mb_check_limits(ac, e4b, 1);
2499 * This is a special case for storages like raid5
2500 * we try to find stripe-aligned chunks for stripe-size-multiple requests
2502 static noinline_for_stack
2503 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2504 struct ext4_buddy *e4b)
2506 struct super_block *sb = ac->ac_sb;
2507 struct ext4_sb_info *sbi = EXT4_SB(sb);
2508 void *bitmap = e4b->bd_bitmap;
2509 struct ext4_free_extent ex;
2510 ext4_fsblk_t first_group_block;
2512 ext4_grpblk_t i, stripe;
2515 BUG_ON(sbi->s_stripe == 0);
2517 /* find first stripe-aligned block in group */
2518 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2520 a = first_group_block + sbi->s_stripe - 1;
2521 do_div(a, sbi->s_stripe);
2522 i = (a * sbi->s_stripe) - first_group_block;
2524 stripe = EXT4_B2C(sbi, sbi->s_stripe);
2525 i = EXT4_B2C(sbi, i);
2526 while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2527 if (!mb_test_bit(i, bitmap)) {
2528 max = mb_find_extent(e4b, i, stripe, &ex);
2529 if (max >= stripe) {
2531 ac->ac_cX_found[ac->ac_criteria]++;
2532 ex.fe_logical = 0xDEADF00D; /* debug value */
2534 ext4_mb_use_best_found(ac, e4b);
2543 * This is also called BEFORE we load the buddy bitmap.
2544 * Returns either 1 or 0 indicating that the group is either suitable
2545 * for the allocation or not.
2547 static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
2548 ext4_group_t group, enum criteria cr)
2550 ext4_grpblk_t free, fragments;
2551 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2552 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2554 BUG_ON(cr < CR_POWER2_ALIGNED || cr >= EXT4_MB_NUM_CRS);
2556 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp) || !grp))
2559 free = grp->bb_free;
2563 fragments = grp->bb_fragments;
2568 case CR_POWER2_ALIGNED:
2569 BUG_ON(ac->ac_2order == 0);
2571 /* Avoid using the first bg of a flexgroup for data files */
2572 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2573 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2574 ((group % flex_size) == 0))
2577 if (free < ac->ac_g_ex.fe_len)
2580 if (ac->ac_2order >= MB_NUM_ORDERS(ac->ac_sb))
2583 if (grp->bb_largest_free_order < ac->ac_2order)
2587 case CR_GOAL_LEN_FAST:
2588 case CR_BEST_AVAIL_LEN:
2589 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2592 case CR_GOAL_LEN_SLOW:
2593 if (free >= ac->ac_g_ex.fe_len)
2606 * This could return negative error code if something goes wrong
2607 * during ext4_mb_init_group(). This should not be called with
2608 * ext4_lock_group() held.
2610 * Note: because we are conditionally operating with the group lock in
2611 * the EXT4_MB_STRICT_CHECK case, we need to fake out sparse in this
2612 * function using __acquire and __release. This means we need to be
2613 * super careful before messing with the error path handling via "goto
2616 static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
2617 ext4_group_t group, enum criteria cr)
2619 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2620 struct super_block *sb = ac->ac_sb;
2621 struct ext4_sb_info *sbi = EXT4_SB(sb);
2622 bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
2627 return -EFSCORRUPTED;
2628 if (sbi->s_mb_stats)
2629 atomic64_inc(&sbi->s_bal_cX_groups_considered[ac->ac_criteria]);
2631 ext4_lock_group(sb, group);
2632 __release(ext4_group_lock_ptr(sb, group));
2634 free = grp->bb_free;
2637 if (cr <= CR_FAST && free < ac->ac_g_ex.fe_len)
2639 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2642 __acquire(ext4_group_lock_ptr(sb, group));
2643 ext4_unlock_group(sb, group);
2646 /* We only do this if the grp has never been initialized */
2647 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2648 struct ext4_group_desc *gdp =
2649 ext4_get_group_desc(sb, group, NULL);
2653 * cr=CR_POWER2_ALIGNED/CR_GOAL_LEN_FAST is a very optimistic
2654 * search to find large good chunks almost for free. If buddy
2655 * data is not ready, then this optimization makes no sense. But
2656 * we never skip the first block group in a flex_bg, since this
2657 * gets used for metadata block allocation, and we want to make
2658 * sure we locate metadata blocks in the first block group in
2659 * the flex_bg if possible.
2662 (!sbi->s_log_groups_per_flex ||
2663 ((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
2664 !(ext4_has_group_desc_csum(sb) &&
2665 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
2667 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
2673 ext4_lock_group(sb, group);
2674 __release(ext4_group_lock_ptr(sb, group));
2676 ret = ext4_mb_good_group(ac, group, cr);
2679 __acquire(ext4_group_lock_ptr(sb, group));
2680 ext4_unlock_group(sb, group);
2686 * Start prefetching @nr block bitmaps starting at @group.
2687 * Return the next group which needs to be prefetched.
2689 ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
2690 unsigned int nr, int *cnt)
2692 ext4_group_t ngroups = ext4_get_groups_count(sb);
2693 struct buffer_head *bh;
2694 struct blk_plug plug;
2696 blk_start_plug(&plug);
2698 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2700 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2703 * Prefetch block groups with free blocks; but don't
2704 * bother if it is marked uninitialized on disk, since
2705 * it won't require I/O to read. Also only try to
2706 * prefetch once, so we avoid getblk() call, which can
2709 if (gdp && grp && !EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
2710 EXT4_MB_GRP_NEED_INIT(grp) &&
2711 ext4_free_group_clusters(sb, gdp) > 0 ) {
2712 bh = ext4_read_block_bitmap_nowait(sb, group, true);
2713 if (bh && !IS_ERR(bh)) {
2714 if (!buffer_uptodate(bh) && cnt)
2719 if (++group >= ngroups)
2722 blk_finish_plug(&plug);
2727 * Prefetching reads the block bitmap into the buffer cache; but we
2728 * need to make sure that the buddy bitmap in the page cache has been
2729 * initialized. Note that ext4_mb_init_group() will block if the I/O
2730 * is not yet completed, or indeed if it was not initiated by
2731 * ext4_mb_prefetch did not start the I/O.
2733 * TODO: We should actually kick off the buddy bitmap setup in a work
2734 * queue when the buffer I/O is completed, so that we don't block
2735 * waiting for the block allocation bitmap read to finish when
2736 * ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
2738 void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
2741 struct ext4_group_desc *gdp;
2742 struct ext4_group_info *grp;
2746 group = ext4_get_groups_count(sb);
2748 gdp = ext4_get_group_desc(sb, group, NULL);
2749 grp = ext4_get_group_info(sb, group);
2751 if (grp && gdp && EXT4_MB_GRP_NEED_INIT(grp) &&
2752 ext4_free_group_clusters(sb, gdp) > 0) {
2753 if (ext4_mb_init_group(sb, group, GFP_NOFS))
2759 static noinline_for_stack int
2760 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2762 ext4_group_t prefetch_grp = 0, ngroups, group, i;
2763 enum criteria new_cr, cr = CR_GOAL_LEN_FAST;
2764 int err = 0, first_err = 0;
2765 unsigned int nr = 0, prefetch_ios = 0;
2766 struct ext4_sb_info *sbi;
2767 struct super_block *sb;
2768 struct ext4_buddy e4b;
2773 ngroups = ext4_get_groups_count(sb);
2774 /* non-extent files are limited to low blocks/groups */
2775 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2776 ngroups = sbi->s_blockfile_groups;
2778 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2780 /* first, try the goal */
2781 err = ext4_mb_find_by_goal(ac, &e4b);
2782 if (err || ac->ac_status == AC_STATUS_FOUND)
2785 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2789 * ac->ac_2order is set only if the fe_len is a power of 2
2790 * if ac->ac_2order is set we also set criteria to 0 so that we
2791 * try exact allocation using buddy.
2793 i = fls(ac->ac_g_ex.fe_len);
2796 * We search using buddy data only if the order of the request
2797 * is greater than equal to the sbi_s_mb_order2_reqs
2798 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2799 * We also support searching for power-of-two requests only for
2800 * requests upto maximum buddy size we have constructed.
2802 if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) {
2804 * This should tell if fe_len is exactly power of 2
2806 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2807 ac->ac_2order = array_index_nospec(i - 1,
2811 /* if stream allocation is enabled, use global goal */
2812 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2813 /* TBD: may be hot point */
2814 spin_lock(&sbi->s_md_lock);
2815 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2816 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2817 spin_unlock(&sbi->s_md_lock);
2821 * Let's just scan groups to find more-less suitable blocks We
2822 * start with CR_GOAL_LEN_FAST, unless it is power of 2
2823 * aligned, in which case let's do that faster approach first.
2826 cr = CR_POWER2_ALIGNED;
2828 for (; cr < EXT4_MB_NUM_CRS && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2829 ac->ac_criteria = cr;
2831 * searching for the right group start
2832 * from the goal value specified
2834 group = ac->ac_g_ex.fe_group;
2835 ac->ac_groups_linear_remaining = sbi->s_mb_max_linear_groups;
2836 prefetch_grp = group;
2838 for (i = 0, new_cr = cr; i < ngroups; i++,
2839 ext4_mb_choose_next_group(ac, &new_cr, &group, ngroups)) {
2849 * Batch reads of the block allocation bitmaps
2850 * to get multiple READs in flight; limit
2851 * prefetching at cr=0/1, otherwise mballoc can
2852 * spend a lot of time loading imperfect groups
2854 if ((prefetch_grp == group) &&
2856 prefetch_ios < sbi->s_mb_prefetch_limit)) {
2857 nr = sbi->s_mb_prefetch;
2858 if (ext4_has_feature_flex_bg(sb)) {
2859 nr = 1 << sbi->s_log_groups_per_flex;
2860 nr -= group & (nr - 1);
2861 nr = min(nr, sbi->s_mb_prefetch);
2863 prefetch_grp = ext4_mb_prefetch(sb, group,
2867 /* This now checks without needing the buddy page */
2868 ret = ext4_mb_good_group_nolock(ac, group, cr);
2875 err = ext4_mb_load_buddy(sb, group, &e4b);
2879 ext4_lock_group(sb, group);
2882 * We need to check again after locking the
2885 ret = ext4_mb_good_group(ac, group, cr);
2887 ext4_unlock_group(sb, group);
2888 ext4_mb_unload_buddy(&e4b);
2892 ac->ac_groups_scanned++;
2893 if (cr == CR_POWER2_ALIGNED)
2894 ext4_mb_simple_scan_group(ac, &e4b);
2895 else if ((cr == CR_GOAL_LEN_FAST ||
2896 cr == CR_BEST_AVAIL_LEN) &&
2898 !(ac->ac_g_ex.fe_len %
2899 EXT4_B2C(sbi, sbi->s_stripe)))
2900 ext4_mb_scan_aligned(ac, &e4b);
2902 ext4_mb_complex_scan_group(ac, &e4b);
2904 ext4_unlock_group(sb, group);
2905 ext4_mb_unload_buddy(&e4b);
2907 if (ac->ac_status != AC_STATUS_CONTINUE)
2910 /* Processed all groups and haven't found blocks */
2911 if (sbi->s_mb_stats && i == ngroups)
2912 atomic64_inc(&sbi->s_bal_cX_failed[cr]);
2914 if (i == ngroups && ac->ac_criteria == CR_BEST_AVAIL_LEN)
2915 /* Reset goal length to original goal length before
2916 * falling into CR_GOAL_LEN_SLOW */
2917 ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
2920 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2921 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2923 * We've been searching too long. Let's try to allocate
2924 * the best chunk we've found so far
2926 ext4_mb_try_best_found(ac, &e4b);
2927 if (ac->ac_status != AC_STATUS_FOUND) {
2929 * Someone more lucky has already allocated it.
2930 * The only thing we can do is just take first
2933 lost = atomic_inc_return(&sbi->s_mb_lost_chunks);
2934 mb_debug(sb, "lost chunk, group: %u, start: %d, len: %d, lost: %d\n",
2935 ac->ac_b_ex.fe_group, ac->ac_b_ex.fe_start,
2936 ac->ac_b_ex.fe_len, lost);
2938 ac->ac_b_ex.fe_group = 0;
2939 ac->ac_b_ex.fe_start = 0;
2940 ac->ac_b_ex.fe_len = 0;
2941 ac->ac_status = AC_STATUS_CONTINUE;
2942 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2948 if (sbi->s_mb_stats && ac->ac_status == AC_STATUS_FOUND)
2949 atomic64_inc(&sbi->s_bal_cX_hits[ac->ac_criteria]);
2951 if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2954 mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
2955 ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
2956 ac->ac_flags, cr, err);
2959 ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
2964 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2966 struct super_block *sb = pde_data(file_inode(seq->file));
2969 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2972 return (void *) ((unsigned long) group);
2975 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2977 struct super_block *sb = pde_data(file_inode(seq->file));
2981 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2984 return (void *) ((unsigned long) group);
2987 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2989 struct super_block *sb = pde_data(file_inode(seq->file));
2990 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2992 int err, buddy_loaded = 0;
2993 struct ext4_buddy e4b;
2994 struct ext4_group_info *grinfo;
2995 unsigned char blocksize_bits = min_t(unsigned char,
2996 sb->s_blocksize_bits,
2997 EXT4_MAX_BLOCK_LOG_SIZE);
2999 struct ext4_group_info info;
3000 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
3005 seq_puts(seq, "#group: free frags first ["
3006 " 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
3007 " 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
3009 i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
3010 sizeof(struct ext4_group_info);
3012 grinfo = ext4_get_group_info(sb, group);
3015 /* Load the group info in memory only if not already loaded. */
3016 if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
3017 err = ext4_mb_load_buddy(sb, group, &e4b);
3019 seq_printf(seq, "#%-5u: I/O error\n", group);
3025 memcpy(&sg, grinfo, i);
3028 ext4_mb_unload_buddy(&e4b);
3030 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
3031 sg.info.bb_fragments, sg.info.bb_first_free);
3032 for (i = 0; i <= 13; i++)
3033 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
3034 sg.info.bb_counters[i] : 0);
3035 seq_puts(seq, " ]\n");
3040 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
3044 const struct seq_operations ext4_mb_seq_groups_ops = {
3045 .start = ext4_mb_seq_groups_start,
3046 .next = ext4_mb_seq_groups_next,
3047 .stop = ext4_mb_seq_groups_stop,
3048 .show = ext4_mb_seq_groups_show,
3051 int ext4_seq_mb_stats_show(struct seq_file *seq, void *offset)
3053 struct super_block *sb = seq->private;
3054 struct ext4_sb_info *sbi = EXT4_SB(sb);
3056 seq_puts(seq, "mballoc:\n");
3057 if (!sbi->s_mb_stats) {
3058 seq_puts(seq, "\tmb stats collection turned off.\n");
3061 "\tTo enable, please write \"1\" to sysfs file mb_stats.\n");
3064 seq_printf(seq, "\treqs: %u\n", atomic_read(&sbi->s_bal_reqs));
3065 seq_printf(seq, "\tsuccess: %u\n", atomic_read(&sbi->s_bal_success));
3067 seq_printf(seq, "\tgroups_scanned: %u\n",
3068 atomic_read(&sbi->s_bal_groups_scanned));
3070 /* CR_POWER2_ALIGNED stats */
3071 seq_puts(seq, "\tcr_p2_aligned_stats:\n");
3072 seq_printf(seq, "\t\thits: %llu\n",
3073 atomic64_read(&sbi->s_bal_cX_hits[CR_POWER2_ALIGNED]));
3075 seq, "\t\tgroups_considered: %llu\n",
3077 &sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]));
3078 seq_printf(seq, "\t\textents_scanned: %u\n",
3079 atomic_read(&sbi->s_bal_cX_ex_scanned[CR_POWER2_ALIGNED]));
3080 seq_printf(seq, "\t\tuseless_loops: %llu\n",
3081 atomic64_read(&sbi->s_bal_cX_failed[CR_POWER2_ALIGNED]));
3082 seq_printf(seq, "\t\tbad_suggestions: %u\n",
3083 atomic_read(&sbi->s_bal_p2_aligned_bad_suggestions));
3085 /* CR_GOAL_LEN_FAST stats */
3086 seq_puts(seq, "\tcr_goal_fast_stats:\n");
3087 seq_printf(seq, "\t\thits: %llu\n",
3088 atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_FAST]));
3089 seq_printf(seq, "\t\tgroups_considered: %llu\n",
3091 &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_FAST]));
3092 seq_printf(seq, "\t\textents_scanned: %u\n",
3093 atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_FAST]));
3094 seq_printf(seq, "\t\tuseless_loops: %llu\n",
3095 atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_FAST]));
3096 seq_printf(seq, "\t\tbad_suggestions: %u\n",
3097 atomic_read(&sbi->s_bal_goal_fast_bad_suggestions));
3099 /* CR_BEST_AVAIL_LEN stats */
3100 seq_puts(seq, "\tcr_best_avail_stats:\n");
3101 seq_printf(seq, "\t\thits: %llu\n",
3102 atomic64_read(&sbi->s_bal_cX_hits[CR_BEST_AVAIL_LEN]));
3104 seq, "\t\tgroups_considered: %llu\n",
3106 &sbi->s_bal_cX_groups_considered[CR_BEST_AVAIL_LEN]));
3107 seq_printf(seq, "\t\textents_scanned: %u\n",
3108 atomic_read(&sbi->s_bal_cX_ex_scanned[CR_BEST_AVAIL_LEN]));
3109 seq_printf(seq, "\t\tuseless_loops: %llu\n",
3110 atomic64_read(&sbi->s_bal_cX_failed[CR_BEST_AVAIL_LEN]));
3111 seq_printf(seq, "\t\tbad_suggestions: %u\n",
3112 atomic_read(&sbi->s_bal_best_avail_bad_suggestions));
3114 /* CR_GOAL_LEN_SLOW stats */
3115 seq_puts(seq, "\tcr_goal_slow_stats:\n");
3116 seq_printf(seq, "\t\thits: %llu\n",
3117 atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_SLOW]));
3118 seq_printf(seq, "\t\tgroups_considered: %llu\n",
3120 &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_SLOW]));
3121 seq_printf(seq, "\t\textents_scanned: %u\n",
3122 atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_SLOW]));
3123 seq_printf(seq, "\t\tuseless_loops: %llu\n",
3124 atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_SLOW]));
3126 /* CR_ANY_FREE stats */
3127 seq_puts(seq, "\tcr_any_free_stats:\n");
3128 seq_printf(seq, "\t\thits: %llu\n",
3129 atomic64_read(&sbi->s_bal_cX_hits[CR_ANY_FREE]));
3131 seq, "\t\tgroups_considered: %llu\n",
3132 atomic64_read(&sbi->s_bal_cX_groups_considered[CR_ANY_FREE]));
3133 seq_printf(seq, "\t\textents_scanned: %u\n",
3134 atomic_read(&sbi->s_bal_cX_ex_scanned[CR_ANY_FREE]));
3135 seq_printf(seq, "\t\tuseless_loops: %llu\n",
3136 atomic64_read(&sbi->s_bal_cX_failed[CR_ANY_FREE]));
3139 seq_printf(seq, "\textents_scanned: %u\n",
3140 atomic_read(&sbi->s_bal_ex_scanned));
3141 seq_printf(seq, "\t\tgoal_hits: %u\n", atomic_read(&sbi->s_bal_goals));
3142 seq_printf(seq, "\t\tlen_goal_hits: %u\n",
3143 atomic_read(&sbi->s_bal_len_goals));
3144 seq_printf(seq, "\t\t2^n_hits: %u\n", atomic_read(&sbi->s_bal_2orders));
3145 seq_printf(seq, "\t\tbreaks: %u\n", atomic_read(&sbi->s_bal_breaks));
3146 seq_printf(seq, "\t\tlost: %u\n", atomic_read(&sbi->s_mb_lost_chunks));
3147 seq_printf(seq, "\tbuddies_generated: %u/%u\n",
3148 atomic_read(&sbi->s_mb_buddies_generated),
3149 ext4_get_groups_count(sb));
3150 seq_printf(seq, "\tbuddies_time_used: %llu\n",
3151 atomic64_read(&sbi->s_mb_generation_time));
3152 seq_printf(seq, "\tpreallocated: %u\n",
3153 atomic_read(&sbi->s_mb_preallocated));
3154 seq_printf(seq, "\tdiscarded: %u\n", atomic_read(&sbi->s_mb_discarded));
3158 static void *ext4_mb_seq_structs_summary_start(struct seq_file *seq, loff_t *pos)
3159 __acquires(&EXT4_SB(sb)->s_mb_rb_lock)
3161 struct super_block *sb = pde_data(file_inode(seq->file));
3162 unsigned long position;
3164 if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3166 position = *pos + 1;
3167 return (void *) ((unsigned long) position);
3170 static void *ext4_mb_seq_structs_summary_next(struct seq_file *seq, void *v, loff_t *pos)
3172 struct super_block *sb = pde_data(file_inode(seq->file));
3173 unsigned long position;
3176 if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3178 position = *pos + 1;
3179 return (void *) ((unsigned long) position);
3182 static int ext4_mb_seq_structs_summary_show(struct seq_file *seq, void *v)
3184 struct super_block *sb = pde_data(file_inode(seq->file));
3185 struct ext4_sb_info *sbi = EXT4_SB(sb);
3186 unsigned long position = ((unsigned long) v);
3187 struct ext4_group_info *grp;
3191 if (position >= MB_NUM_ORDERS(sb)) {
3192 position -= MB_NUM_ORDERS(sb);
3194 seq_puts(seq, "avg_fragment_size_lists:\n");
3197 read_lock(&sbi->s_mb_avg_fragment_size_locks[position]);
3198 list_for_each_entry(grp, &sbi->s_mb_avg_fragment_size[position],
3199 bb_avg_fragment_size_node)
3201 read_unlock(&sbi->s_mb_avg_fragment_size_locks[position]);
3202 seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3203 (unsigned int)position, count);
3207 if (position == 0) {
3208 seq_printf(seq, "optimize_scan: %d\n",
3209 test_opt2(sb, MB_OPTIMIZE_SCAN) ? 1 : 0);
3210 seq_puts(seq, "max_free_order_lists:\n");
3213 read_lock(&sbi->s_mb_largest_free_orders_locks[position]);
3214 list_for_each_entry(grp, &sbi->s_mb_largest_free_orders[position],
3215 bb_largest_free_order_node)
3217 read_unlock(&sbi->s_mb_largest_free_orders_locks[position]);
3218 seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3219 (unsigned int)position, count);
3224 static void ext4_mb_seq_structs_summary_stop(struct seq_file *seq, void *v)
3228 const struct seq_operations ext4_mb_seq_structs_summary_ops = {
3229 .start = ext4_mb_seq_structs_summary_start,
3230 .next = ext4_mb_seq_structs_summary_next,
3231 .stop = ext4_mb_seq_structs_summary_stop,
3232 .show = ext4_mb_seq_structs_summary_show,
3235 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
3237 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3238 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
3245 * Allocate the top-level s_group_info array for the specified number
3248 int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
3250 struct ext4_sb_info *sbi = EXT4_SB(sb);
3252 struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
3254 size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
3255 EXT4_DESC_PER_BLOCK_BITS(sb);
3256 if (size <= sbi->s_group_info_size)
3259 size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
3260 new_groupinfo = kvzalloc(size, GFP_KERNEL);
3261 if (!new_groupinfo) {
3262 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
3266 old_groupinfo = rcu_dereference(sbi->s_group_info);
3268 memcpy(new_groupinfo, old_groupinfo,
3269 sbi->s_group_info_size * sizeof(*sbi->s_group_info));
3271 rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
3272 sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
3274 ext4_kvfree_array_rcu(old_groupinfo);
3275 ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
3276 sbi->s_group_info_size);
3280 /* Create and initialize ext4_group_info data for the given group. */
3281 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
3282 struct ext4_group_desc *desc)
3286 int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
3287 struct ext4_sb_info *sbi = EXT4_SB(sb);
3288 struct ext4_group_info **meta_group_info;
3289 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3292 * First check if this group is the first of a reserved block.
3293 * If it's true, we have to allocate a new table of pointers
3294 * to ext4_group_info structures
3296 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3297 metalen = sizeof(*meta_group_info) <<
3298 EXT4_DESC_PER_BLOCK_BITS(sb);
3299 meta_group_info = kmalloc(metalen, GFP_NOFS);
3300 if (meta_group_info == NULL) {
3301 ext4_msg(sb, KERN_ERR, "can't allocate mem "
3302 "for a buddy group");
3306 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
3310 meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
3311 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
3313 meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
3314 if (meta_group_info[i] == NULL) {
3315 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
3316 goto exit_group_info;
3318 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
3319 &(meta_group_info[i]->bb_state));
3322 * initialize bb_free to be able to skip
3323 * empty groups without initialization
3325 if (ext4_has_group_desc_csum(sb) &&
3326 (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3327 meta_group_info[i]->bb_free =
3328 ext4_free_clusters_after_init(sb, group, desc);
3330 meta_group_info[i]->bb_free =
3331 ext4_free_group_clusters(sb, desc);
3334 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
3335 init_rwsem(&meta_group_info[i]->alloc_sem);
3336 meta_group_info[i]->bb_free_root = RB_ROOT;
3337 INIT_LIST_HEAD(&meta_group_info[i]->bb_largest_free_order_node);
3338 INIT_LIST_HEAD(&meta_group_info[i]->bb_avg_fragment_size_node);
3339 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
3340 meta_group_info[i]->bb_avg_fragment_size_order = -1; /* uninit */
3341 meta_group_info[i]->bb_group = group;
3343 mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
3347 /* If a meta_group_info table has been allocated, release it now */
3348 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3349 struct ext4_group_info ***group_info;
3352 group_info = rcu_dereference(sbi->s_group_info);
3353 kfree(group_info[idx]);
3354 group_info[idx] = NULL;
3358 } /* ext4_mb_add_groupinfo */
3360 static int ext4_mb_init_backend(struct super_block *sb)
3362 ext4_group_t ngroups = ext4_get_groups_count(sb);
3364 struct ext4_sb_info *sbi = EXT4_SB(sb);
3366 struct ext4_group_desc *desc;
3367 struct ext4_group_info ***group_info;
3368 struct kmem_cache *cachep;
3370 err = ext4_mb_alloc_groupinfo(sb, ngroups);
3374 sbi->s_buddy_cache = new_inode(sb);
3375 if (sbi->s_buddy_cache == NULL) {
3376 ext4_msg(sb, KERN_ERR, "can't get new inode");
3379 /* To avoid potentially colliding with an valid on-disk inode number,
3380 * use EXT4_BAD_INO for the buddy cache inode number. This inode is
3381 * not in the inode hash, so it should never be found by iget(), but
3382 * this will avoid confusion if it ever shows up during debugging. */
3383 sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
3384 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
3385 for (i = 0; i < ngroups; i++) {
3387 desc = ext4_get_group_desc(sb, i, NULL);
3389 ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
3392 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
3396 if (ext4_has_feature_flex_bg(sb)) {
3397 /* a single flex group is supposed to be read by a single IO.
3398 * 2 ^ s_log_groups_per_flex != UINT_MAX as s_mb_prefetch is
3399 * unsigned integer, so the maximum shift is 32.
3401 if (sbi->s_es->s_log_groups_per_flex >= 32) {
3402 ext4_msg(sb, KERN_ERR, "too many log groups per flexible block group");
3405 sbi->s_mb_prefetch = min_t(uint, 1 << sbi->s_es->s_log_groups_per_flex,
3406 BLK_MAX_SEGMENT_SIZE >> (sb->s_blocksize_bits - 9));
3407 sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
3409 sbi->s_mb_prefetch = 32;
3411 if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
3412 sbi->s_mb_prefetch = ext4_get_groups_count(sb);
3413 /* now many real IOs to prefetch within a single allocation at cr=0
3414 * given cr=0 is an CPU-related optimization we shouldn't try to
3415 * load too many groups, at some point we should start to use what
3416 * we've got in memory.
3417 * with an average random access time 5ms, it'd take a second to get
3418 * 200 groups (* N with flex_bg), so let's make this limit 4
3420 sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
3421 if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
3422 sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
3427 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3429 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3432 kmem_cache_free(cachep, grp);
3434 i = sbi->s_group_info_size;
3436 group_info = rcu_dereference(sbi->s_group_info);
3438 kfree(group_info[i]);
3440 iput(sbi->s_buddy_cache);
3443 kvfree(rcu_dereference(sbi->s_group_info));
3448 static void ext4_groupinfo_destroy_slabs(void)
3452 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
3453 kmem_cache_destroy(ext4_groupinfo_caches[i]);
3454 ext4_groupinfo_caches[i] = NULL;
3458 static int ext4_groupinfo_create_slab(size_t size)
3460 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
3462 int blocksize_bits = order_base_2(size);
3463 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3464 struct kmem_cache *cachep;
3466 if (cache_index >= NR_GRPINFO_CACHES)
3469 if (unlikely(cache_index < 0))
3472 mutex_lock(&ext4_grpinfo_slab_create_mutex);
3473 if (ext4_groupinfo_caches[cache_index]) {
3474 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
3475 return 0; /* Already created */
3478 slab_size = offsetof(struct ext4_group_info,
3479 bb_counters[blocksize_bits + 2]);
3481 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
3482 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
3485 ext4_groupinfo_caches[cache_index] = cachep;
3487 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
3490 "EXT4-fs: no memory for groupinfo slab cache\n");
3497 static void ext4_discard_work(struct work_struct *work)
3499 struct ext4_sb_info *sbi = container_of(work,
3500 struct ext4_sb_info, s_discard_work);
3501 struct super_block *sb = sbi->s_sb;
3502 struct ext4_free_data *fd, *nfd;
3503 struct ext4_buddy e4b;
3504 struct list_head discard_list;
3505 ext4_group_t grp, load_grp;
3508 INIT_LIST_HEAD(&discard_list);
3509 spin_lock(&sbi->s_md_lock);
3510 list_splice_init(&sbi->s_discard_list, &discard_list);
3511 spin_unlock(&sbi->s_md_lock);
3513 load_grp = UINT_MAX;
3514 list_for_each_entry_safe(fd, nfd, &discard_list, efd_list) {
3516 * If filesystem is umounting or no memory or suffering
3517 * from no space, give up the discard
3519 if ((sb->s_flags & SB_ACTIVE) && !err &&
3520 !atomic_read(&sbi->s_retry_alloc_pending)) {
3521 grp = fd->efd_group;
3522 if (grp != load_grp) {
3523 if (load_grp != UINT_MAX)
3524 ext4_mb_unload_buddy(&e4b);
3526 err = ext4_mb_load_buddy(sb, grp, &e4b);
3528 kmem_cache_free(ext4_free_data_cachep, fd);
3529 load_grp = UINT_MAX;
3536 ext4_lock_group(sb, grp);
3537 ext4_try_to_trim_range(sb, &e4b, fd->efd_start_cluster,
3538 fd->efd_start_cluster + fd->efd_count - 1, 1);
3539 ext4_unlock_group(sb, grp);
3541 kmem_cache_free(ext4_free_data_cachep, fd);
3544 if (load_grp != UINT_MAX)
3545 ext4_mb_unload_buddy(&e4b);
3548 int ext4_mb_init(struct super_block *sb)
3550 struct ext4_sb_info *sbi = EXT4_SB(sb);
3552 unsigned offset, offset_incr;
3556 i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_offsets);
3558 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
3559 if (sbi->s_mb_offsets == NULL) {
3564 i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_maxs);
3565 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
3566 if (sbi->s_mb_maxs == NULL) {
3571 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
3575 /* order 0 is regular bitmap */
3576 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
3577 sbi->s_mb_offsets[0] = 0;
3581 offset_incr = 1 << (sb->s_blocksize_bits - 1);
3582 max = sb->s_blocksize << 2;
3584 sbi->s_mb_offsets[i] = offset;
3585 sbi->s_mb_maxs[i] = max;
3586 offset += offset_incr;
3587 offset_incr = offset_incr >> 1;
3590 } while (i < MB_NUM_ORDERS(sb));
3592 sbi->s_mb_avg_fragment_size =
3593 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3595 if (!sbi->s_mb_avg_fragment_size) {
3599 sbi->s_mb_avg_fragment_size_locks =
3600 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3602 if (!sbi->s_mb_avg_fragment_size_locks) {
3606 for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3607 INIT_LIST_HEAD(&sbi->s_mb_avg_fragment_size[i]);
3608 rwlock_init(&sbi->s_mb_avg_fragment_size_locks[i]);
3610 sbi->s_mb_largest_free_orders =
3611 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3613 if (!sbi->s_mb_largest_free_orders) {
3617 sbi->s_mb_largest_free_orders_locks =
3618 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3620 if (!sbi->s_mb_largest_free_orders_locks) {
3624 for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3625 INIT_LIST_HEAD(&sbi->s_mb_largest_free_orders[i]);
3626 rwlock_init(&sbi->s_mb_largest_free_orders_locks[i]);
3629 spin_lock_init(&sbi->s_md_lock);
3630 sbi->s_mb_free_pending = 0;
3631 INIT_LIST_HEAD(&sbi->s_freed_data_list);
3632 INIT_LIST_HEAD(&sbi->s_discard_list);
3633 INIT_WORK(&sbi->s_discard_work, ext4_discard_work);
3634 atomic_set(&sbi->s_retry_alloc_pending, 0);
3636 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
3637 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
3638 sbi->s_mb_stats = MB_DEFAULT_STATS;
3639 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
3640 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
3641 sbi->s_mb_best_avail_max_trim_order = MB_DEFAULT_BEST_AVAIL_TRIM_ORDER;
3644 * The default group preallocation is 512, which for 4k block
3645 * sizes translates to 2 megabytes. However for bigalloc file
3646 * systems, this is probably too big (i.e, if the cluster size
3647 * is 1 megabyte, then group preallocation size becomes half a
3648 * gigabyte!). As a default, we will keep a two megabyte
3649 * group pralloc size for cluster sizes up to 64k, and after
3650 * that, we will force a minimum group preallocation size of
3651 * 32 clusters. This translates to 8 megs when the cluster
3652 * size is 256k, and 32 megs when the cluster size is 1 meg,
3653 * which seems reasonable as a default.
3655 sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
3656 sbi->s_cluster_bits, 32);
3658 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
3659 * to the lowest multiple of s_stripe which is bigger than
3660 * the s_mb_group_prealloc as determined above. We want
3661 * the preallocation size to be an exact multiple of the
3662 * RAID stripe size so that preallocations don't fragment
3665 if (sbi->s_stripe > 1) {
3666 sbi->s_mb_group_prealloc = roundup(
3667 sbi->s_mb_group_prealloc, EXT4_B2C(sbi, sbi->s_stripe));
3670 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
3671 if (sbi->s_locality_groups == NULL) {
3675 for_each_possible_cpu(i) {
3676 struct ext4_locality_group *lg;
3677 lg = per_cpu_ptr(sbi->s_locality_groups, i);
3678 mutex_init(&lg->lg_mutex);
3679 for (j = 0; j < PREALLOC_TB_SIZE; j++)
3680 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
3681 spin_lock_init(&lg->lg_prealloc_lock);
3684 if (bdev_nonrot(sb->s_bdev))
3685 sbi->s_mb_max_linear_groups = 0;
3687 sbi->s_mb_max_linear_groups = MB_DEFAULT_LINEAR_LIMIT;
3688 /* init file for buddy data */
3689 ret = ext4_mb_init_backend(sb);
3691 goto out_free_locality_groups;
3695 out_free_locality_groups:
3696 free_percpu(sbi->s_locality_groups);
3697 sbi->s_locality_groups = NULL;
3699 kfree(sbi->s_mb_avg_fragment_size);
3700 kfree(sbi->s_mb_avg_fragment_size_locks);
3701 kfree(sbi->s_mb_largest_free_orders);
3702 kfree(sbi->s_mb_largest_free_orders_locks);
3703 kfree(sbi->s_mb_offsets);
3704 sbi->s_mb_offsets = NULL;
3705 kfree(sbi->s_mb_maxs);
3706 sbi->s_mb_maxs = NULL;
3710 /* need to called with the ext4 group lock held */
3711 static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
3713 struct ext4_prealloc_space *pa;
3714 struct list_head *cur, *tmp;
3717 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
3718 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3719 list_del(&pa->pa_group_list);
3721 kmem_cache_free(ext4_pspace_cachep, pa);
3726 int ext4_mb_release(struct super_block *sb)
3728 ext4_group_t ngroups = ext4_get_groups_count(sb);
3730 int num_meta_group_infos;
3731 struct ext4_group_info *grinfo, ***group_info;
3732 struct ext4_sb_info *sbi = EXT4_SB(sb);
3733 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3736 if (test_opt(sb, DISCARD)) {
3738 * wait the discard work to drain all of ext4_free_data
3740 flush_work(&sbi->s_discard_work);
3741 WARN_ON_ONCE(!list_empty(&sbi->s_discard_list));
3744 if (sbi->s_group_info) {
3745 for (i = 0; i < ngroups; i++) {
3747 grinfo = ext4_get_group_info(sb, i);
3750 mb_group_bb_bitmap_free(grinfo);
3751 ext4_lock_group(sb, i);
3752 count = ext4_mb_cleanup_pa(grinfo);
3754 mb_debug(sb, "mballoc: %d PAs left\n",
3756 ext4_unlock_group(sb, i);
3757 kmem_cache_free(cachep, grinfo);
3759 num_meta_group_infos = (ngroups +
3760 EXT4_DESC_PER_BLOCK(sb) - 1) >>
3761 EXT4_DESC_PER_BLOCK_BITS(sb);
3763 group_info = rcu_dereference(sbi->s_group_info);
3764 for (i = 0; i < num_meta_group_infos; i++)
3765 kfree(group_info[i]);
3769 kfree(sbi->s_mb_avg_fragment_size);
3770 kfree(sbi->s_mb_avg_fragment_size_locks);
3771 kfree(sbi->s_mb_largest_free_orders);
3772 kfree(sbi->s_mb_largest_free_orders_locks);
3773 kfree(sbi->s_mb_offsets);
3774 kfree(sbi->s_mb_maxs);
3775 iput(sbi->s_buddy_cache);
3776 if (sbi->s_mb_stats) {
3777 ext4_msg(sb, KERN_INFO,
3778 "mballoc: %u blocks %u reqs (%u success)",
3779 atomic_read(&sbi->s_bal_allocated),
3780 atomic_read(&sbi->s_bal_reqs),
3781 atomic_read(&sbi->s_bal_success));
3782 ext4_msg(sb, KERN_INFO,
3783 "mballoc: %u extents scanned, %u groups scanned, %u goal hits, "
3784 "%u 2^N hits, %u breaks, %u lost",
3785 atomic_read(&sbi->s_bal_ex_scanned),
3786 atomic_read(&sbi->s_bal_groups_scanned),
3787 atomic_read(&sbi->s_bal_goals),
3788 atomic_read(&sbi->s_bal_2orders),
3789 atomic_read(&sbi->s_bal_breaks),
3790 atomic_read(&sbi->s_mb_lost_chunks));
3791 ext4_msg(sb, KERN_INFO,
3792 "mballoc: %u generated and it took %llu",
3793 atomic_read(&sbi->s_mb_buddies_generated),
3794 atomic64_read(&sbi->s_mb_generation_time));
3795 ext4_msg(sb, KERN_INFO,
3796 "mballoc: %u preallocated, %u discarded",
3797 atomic_read(&sbi->s_mb_preallocated),
3798 atomic_read(&sbi->s_mb_discarded));
3801 free_percpu(sbi->s_locality_groups);
3806 static inline int ext4_issue_discard(struct super_block *sb,
3807 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
3810 ext4_fsblk_t discard_block;
3812 discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
3813 ext4_group_first_block_no(sb, block_group));
3814 count = EXT4_C2B(EXT4_SB(sb), count);
3815 trace_ext4_discard_blocks(sb,
3816 (unsigned long long) discard_block, count);
3818 return __blkdev_issue_discard(sb->s_bdev,
3819 (sector_t)discard_block << (sb->s_blocksize_bits - 9),
3820 (sector_t)count << (sb->s_blocksize_bits - 9),
3823 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
3826 static void ext4_free_data_in_buddy(struct super_block *sb,
3827 struct ext4_free_data *entry)
3829 struct ext4_buddy e4b;
3830 struct ext4_group_info *db;
3833 mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
3834 entry->efd_count, entry->efd_group, entry);
3836 err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
3837 /* we expect to find existing buddy because it's pinned */
3840 spin_lock(&EXT4_SB(sb)->s_md_lock);
3841 EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
3842 spin_unlock(&EXT4_SB(sb)->s_md_lock);
3845 /* there are blocks to put in buddy to make them really free */
3846 count += entry->efd_count;
3847 ext4_lock_group(sb, entry->efd_group);
3848 /* Take it out of per group rb tree */
3849 rb_erase(&entry->efd_node, &(db->bb_free_root));
3850 mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
3853 * Clear the trimmed flag for the group so that the next
3854 * ext4_trim_fs can trim it.
3855 * If the volume is mounted with -o discard, online discard
3856 * is supported and the free blocks will be trimmed online.
3858 if (!test_opt(sb, DISCARD))
3859 EXT4_MB_GRP_CLEAR_TRIMMED(db);
3861 if (!db->bb_free_root.rb_node) {
3862 /* No more items in the per group rb tree
3863 * balance refcounts from ext4_mb_free_metadata()
3865 put_page(e4b.bd_buddy_page);
3866 put_page(e4b.bd_bitmap_page);
3868 ext4_unlock_group(sb, entry->efd_group);
3869 ext4_mb_unload_buddy(&e4b);
3871 mb_debug(sb, "freed %d blocks in 1 structures\n", count);
3875 * This function is called by the jbd2 layer once the commit has finished,
3876 * so we know we can free the blocks that were released with that commit.
3878 void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
3880 struct ext4_sb_info *sbi = EXT4_SB(sb);
3881 struct ext4_free_data *entry, *tmp;
3882 struct list_head freed_data_list;
3883 struct list_head *cut_pos = NULL;
3886 INIT_LIST_HEAD(&freed_data_list);
3888 spin_lock(&sbi->s_md_lock);
3889 list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
3890 if (entry->efd_tid != commit_tid)
3892 cut_pos = &entry->efd_list;
3895 list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
3897 spin_unlock(&sbi->s_md_lock);
3899 list_for_each_entry(entry, &freed_data_list, efd_list)
3900 ext4_free_data_in_buddy(sb, entry);
3902 if (test_opt(sb, DISCARD)) {
3903 spin_lock(&sbi->s_md_lock);
3904 wake = list_empty(&sbi->s_discard_list);
3905 list_splice_tail(&freed_data_list, &sbi->s_discard_list);
3906 spin_unlock(&sbi->s_md_lock);
3908 queue_work(system_unbound_wq, &sbi->s_discard_work);
3910 list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
3911 kmem_cache_free(ext4_free_data_cachep, entry);
3915 int __init ext4_init_mballoc(void)
3917 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
3918 SLAB_RECLAIM_ACCOUNT);
3919 if (ext4_pspace_cachep == NULL)
3922 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
3923 SLAB_RECLAIM_ACCOUNT);
3924 if (ext4_ac_cachep == NULL)
3927 ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
3928 SLAB_RECLAIM_ACCOUNT);
3929 if (ext4_free_data_cachep == NULL)
3935 kmem_cache_destroy(ext4_ac_cachep);
3937 kmem_cache_destroy(ext4_pspace_cachep);
3942 void ext4_exit_mballoc(void)
3945 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
3946 * before destroying the slab cache.
3949 kmem_cache_destroy(ext4_pspace_cachep);
3950 kmem_cache_destroy(ext4_ac_cachep);
3951 kmem_cache_destroy(ext4_free_data_cachep);
3952 ext4_groupinfo_destroy_slabs();
3957 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
3958 * Returns 0 if success or error code
3960 static noinline_for_stack int
3961 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
3962 handle_t *handle, unsigned int reserv_clstrs)
3964 struct buffer_head *bitmap_bh = NULL;
3965 struct ext4_group_desc *gdp;
3966 struct buffer_head *gdp_bh;
3967 struct ext4_sb_info *sbi;
3968 struct super_block *sb;
3972 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3973 BUG_ON(ac->ac_b_ex.fe_len <= 0);
3978 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
3979 if (IS_ERR(bitmap_bh)) {
3980 return PTR_ERR(bitmap_bh);
3983 BUFFER_TRACE(bitmap_bh, "getting write access");
3984 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
3990 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3994 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
3995 ext4_free_group_clusters(sb, gdp));
3997 BUFFER_TRACE(gdp_bh, "get_write_access");
3998 err = ext4_journal_get_write_access(handle, sb, gdp_bh, EXT4_JTR_NONE);
4002 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4004 len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4005 if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
4006 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
4007 "fs metadata", block, block+len);
4008 /* File system mounted not to panic on error
4009 * Fix the bitmap and return EFSCORRUPTED
4010 * We leak some of the blocks here.
4012 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
4013 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
4014 ac->ac_b_ex.fe_len);
4015 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
4016 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4018 err = -EFSCORRUPTED;
4022 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
4023 #ifdef AGGRESSIVE_CHECK
4026 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
4027 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
4028 bitmap_bh->b_data));
4032 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
4033 ac->ac_b_ex.fe_len);
4034 if (ext4_has_group_desc_csum(sb) &&
4035 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
4036 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
4037 ext4_free_group_clusters_set(sb, gdp,
4038 ext4_free_clusters_after_init(sb,
4039 ac->ac_b_ex.fe_group, gdp));
4041 len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
4042 ext4_free_group_clusters_set(sb, gdp, len);
4043 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
4044 ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
4046 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
4047 percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
4049 * Now reduce the dirty block count also. Should not go negative
4051 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
4052 /* release all the reserved blocks if non delalloc */
4053 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4056 if (sbi->s_log_groups_per_flex) {
4057 ext4_group_t flex_group = ext4_flex_group(sbi,
4058 ac->ac_b_ex.fe_group);
4059 atomic64_sub(ac->ac_b_ex.fe_len,
4060 &sbi_array_rcu_deref(sbi, s_flex_groups,
4061 flex_group)->free_clusters);
4064 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4067 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
4075 * Idempotent helper for Ext4 fast commit replay path to set the state of
4076 * blocks in bitmaps and update counters.
4078 void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
4081 struct buffer_head *bitmap_bh = NULL;
4082 struct ext4_group_desc *gdp;
4083 struct buffer_head *gdp_bh;
4084 struct ext4_sb_info *sbi = EXT4_SB(sb);
4086 ext4_grpblk_t blkoff;
4089 unsigned int clen, clen_changed, thisgrp_len;
4092 ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
4095 * Check to see if we are freeing blocks across a group
4097 * In case of flex_bg, this can happen that (block, len) may
4098 * span across more than one group. In that case we need to
4099 * get the corresponding group metadata to work with.
4100 * For this we have goto again loop.
4102 thisgrp_len = min_t(unsigned int, (unsigned int)len,
4103 EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
4104 clen = EXT4_NUM_B2C(sbi, thisgrp_len);
4106 if (!ext4_sb_block_valid(sb, NULL, block, thisgrp_len)) {
4107 ext4_error(sb, "Marking blocks in system zone - "
4108 "Block = %llu, len = %u",
4109 block, thisgrp_len);
4114 bitmap_bh = ext4_read_block_bitmap(sb, group);
4115 if (IS_ERR(bitmap_bh)) {
4116 err = PTR_ERR(bitmap_bh);
4122 gdp = ext4_get_group_desc(sb, group, &gdp_bh);
4126 ext4_lock_group(sb, group);
4128 for (i = 0; i < clen; i++)
4129 if (!mb_test_bit(blkoff + i, bitmap_bh->b_data) ==
4133 clen_changed = clen - already;
4135 mb_set_bits(bitmap_bh->b_data, blkoff, clen);
4137 mb_clear_bits(bitmap_bh->b_data, blkoff, clen);
4138 if (ext4_has_group_desc_csum(sb) &&
4139 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
4140 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
4141 ext4_free_group_clusters_set(sb, gdp,
4142 ext4_free_clusters_after_init(sb, group, gdp));
4145 clen = ext4_free_group_clusters(sb, gdp) - clen_changed;
4147 clen = ext4_free_group_clusters(sb, gdp) + clen_changed;
4149 ext4_free_group_clusters_set(sb, gdp, clen);
4150 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
4151 ext4_group_desc_csum_set(sb, group, gdp);
4153 ext4_unlock_group(sb, group);
4155 if (sbi->s_log_groups_per_flex) {
4156 ext4_group_t flex_group = ext4_flex_group(sbi, group);
4157 struct flex_groups *fg = sbi_array_rcu_deref(sbi,
4158 s_flex_groups, flex_group);
4161 atomic64_sub(clen_changed, &fg->free_clusters);
4163 atomic64_add(clen_changed, &fg->free_clusters);
4167 err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
4170 sync_dirty_buffer(bitmap_bh);
4171 err = ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
4172 sync_dirty_buffer(gdp_bh);
4176 block += thisgrp_len;
4187 * here we normalize request for locality group
4188 * Group request are normalized to s_mb_group_prealloc, which goes to
4189 * s_strip if we set the same via mount option.
4190 * s_mb_group_prealloc can be configured via
4191 * /sys/fs/ext4/<partition>/mb_group_prealloc
4193 * XXX: should we try to preallocate more than the group has now?
4195 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
4197 struct super_block *sb = ac->ac_sb;
4198 struct ext4_locality_group *lg = ac->ac_lg;
4201 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
4202 mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
4206 * This function returns the next element to look at during inode
4207 * PA rbtree walk. We assume that we have held the inode PA rbtree lock
4208 * (ei->i_prealloc_lock)
4210 * new_start The start of the range we want to compare
4211 * cur_start The existing start that we are comparing against
4212 * node The node of the rb_tree
4214 static inline struct rb_node*
4215 ext4_mb_pa_rb_next_iter(ext4_lblk_t new_start, ext4_lblk_t cur_start, struct rb_node *node)
4217 if (new_start < cur_start)
4218 return node->rb_left;
4220 return node->rb_right;
4224 ext4_mb_pa_assert_overlap(struct ext4_allocation_context *ac,
4225 ext4_lblk_t start, ext4_lblk_t end)
4227 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4228 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4229 struct ext4_prealloc_space *tmp_pa;
4230 ext4_lblk_t tmp_pa_start, tmp_pa_end;
4231 struct rb_node *iter;
4233 read_lock(&ei->i_prealloc_lock);
4234 for (iter = ei->i_prealloc_node.rb_node; iter;
4235 iter = ext4_mb_pa_rb_next_iter(start, tmp_pa_start, iter)) {
4236 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4237 pa_node.inode_node);
4238 tmp_pa_start = tmp_pa->pa_lstart;
4239 tmp_pa_end = tmp_pa->pa_lstart + EXT4_C2B(sbi, tmp_pa->pa_len);
4241 spin_lock(&tmp_pa->pa_lock);
4242 if (tmp_pa->pa_deleted == 0)
4243 BUG_ON(!(start >= tmp_pa_end || end <= tmp_pa_start));
4244 spin_unlock(&tmp_pa->pa_lock);
4246 read_unlock(&ei->i_prealloc_lock);
4250 * Given an allocation context "ac" and a range "start", "end", check
4251 * and adjust boundaries if the range overlaps with any of the existing
4252 * preallocatoins stored in the corresponding inode of the allocation context.
4255 * ac allocation context
4256 * start start of the new range
4257 * end end of the new range
4260 ext4_mb_pa_adjust_overlap(struct ext4_allocation_context *ac,
4261 ext4_lblk_t *start, ext4_lblk_t *end)
4263 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4264 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4265 struct ext4_prealloc_space *tmp_pa = NULL, *left_pa = NULL, *right_pa = NULL;
4266 struct rb_node *iter;
4267 ext4_lblk_t new_start, new_end;
4268 ext4_lblk_t tmp_pa_start, tmp_pa_end, left_pa_end = -1, right_pa_start = -1;
4274 * Adjust the normalized range so that it doesn't overlap with any
4275 * existing preallocated blocks(PAs). Make sure to hold the rbtree lock
4276 * so it doesn't change underneath us.
4278 read_lock(&ei->i_prealloc_lock);
4280 /* Step 1: find any one immediate neighboring PA of the normalized range */
4281 for (iter = ei->i_prealloc_node.rb_node; iter;
4282 iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
4283 tmp_pa_start, iter)) {
4284 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4285 pa_node.inode_node);
4286 tmp_pa_start = tmp_pa->pa_lstart;
4287 tmp_pa_end = tmp_pa->pa_lstart + EXT4_C2B(sbi, tmp_pa->pa_len);
4289 /* PA must not overlap original request */
4290 spin_lock(&tmp_pa->pa_lock);
4291 if (tmp_pa->pa_deleted == 0)
4292 BUG_ON(!(ac->ac_o_ex.fe_logical >= tmp_pa_end ||
4293 ac->ac_o_ex.fe_logical < tmp_pa_start));
4294 spin_unlock(&tmp_pa->pa_lock);
4298 * Step 2: check if the found PA is left or right neighbor and
4299 * get the other neighbor
4302 if (tmp_pa->pa_lstart < ac->ac_o_ex.fe_logical) {
4303 struct rb_node *tmp;
4306 tmp = rb_next(&left_pa->pa_node.inode_node);
4308 right_pa = rb_entry(tmp,
4309 struct ext4_prealloc_space,
4310 pa_node.inode_node);
4313 struct rb_node *tmp;
4316 tmp = rb_prev(&right_pa->pa_node.inode_node);
4318 left_pa = rb_entry(tmp,
4319 struct ext4_prealloc_space,
4320 pa_node.inode_node);
4325 /* Step 3: get the non deleted neighbors */
4327 for (iter = &left_pa->pa_node.inode_node;;
4328 iter = rb_prev(iter)) {
4334 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4335 pa_node.inode_node);
4337 spin_lock(&tmp_pa->pa_lock);
4338 if (tmp_pa->pa_deleted == 0) {
4339 spin_unlock(&tmp_pa->pa_lock);
4342 spin_unlock(&tmp_pa->pa_lock);
4347 for (iter = &right_pa->pa_node.inode_node;;
4348 iter = rb_next(iter)) {
4354 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4355 pa_node.inode_node);
4357 spin_lock(&tmp_pa->pa_lock);
4358 if (tmp_pa->pa_deleted == 0) {
4359 spin_unlock(&tmp_pa->pa_lock);
4362 spin_unlock(&tmp_pa->pa_lock);
4368 left_pa->pa_lstart + EXT4_C2B(sbi, left_pa->pa_len);
4369 BUG_ON(left_pa_end > ac->ac_o_ex.fe_logical);
4373 right_pa_start = right_pa->pa_lstart;
4374 BUG_ON(right_pa_start <= ac->ac_o_ex.fe_logical);
4377 /* Step 4: trim our normalized range to not overlap with the neighbors */
4379 if (left_pa_end > new_start)
4380 new_start = left_pa_end;
4384 if (right_pa_start < new_end)
4385 new_end = right_pa_start;
4387 read_unlock(&ei->i_prealloc_lock);
4389 /* XXX: extra loop to check we really don't overlap preallocations */
4390 ext4_mb_pa_assert_overlap(ac, new_start, new_end);
4397 * Normalization means making request better in terms of
4398 * size and alignment
4400 static noinline_for_stack void
4401 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
4402 struct ext4_allocation_request *ar)
4404 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4405 struct ext4_super_block *es = sbi->s_es;
4408 loff_t size, start_off;
4409 loff_t orig_size __maybe_unused;
4412 /* do normalize only data requests, metadata requests
4413 do not need preallocation */
4414 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4417 /* sometime caller may want exact blocks */
4418 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4421 /* caller may indicate that preallocation isn't
4422 * required (it's a tail, for example) */
4423 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
4426 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
4427 ext4_mb_normalize_group_request(ac);
4431 bsbits = ac->ac_sb->s_blocksize_bits;
4433 /* first, let's learn actual file size
4434 * given current request is allocated */
4435 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
4436 size = size << bsbits;
4437 if (size < i_size_read(ac->ac_inode))
4438 size = i_size_read(ac->ac_inode);
4441 /* max size of free chunks */
4444 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
4445 (req <= (size) || max <= (chunk_size))
4447 /* first, try to predict filesize */
4448 /* XXX: should this table be tunable? */
4450 if (size <= 16 * 1024) {
4452 } else if (size <= 32 * 1024) {
4454 } else if (size <= 64 * 1024) {
4456 } else if (size <= 128 * 1024) {
4458 } else if (size <= 256 * 1024) {
4460 } else if (size <= 512 * 1024) {
4462 } else if (size <= 1024 * 1024) {
4464 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
4465 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4466 (21 - bsbits)) << 21;
4467 size = 2 * 1024 * 1024;
4468 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
4469 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4470 (22 - bsbits)) << 22;
4471 size = 4 * 1024 * 1024;
4472 } else if (NRL_CHECK_SIZE(EXT4_C2B(sbi, ac->ac_o_ex.fe_len),
4473 (8<<20)>>bsbits, max, 8 * 1024)) {
4474 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4475 (23 - bsbits)) << 23;
4476 size = 8 * 1024 * 1024;
4478 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
4479 size = (loff_t) EXT4_C2B(sbi,
4480 ac->ac_o_ex.fe_len) << bsbits;
4482 size = size >> bsbits;
4483 start = start_off >> bsbits;
4486 * For tiny groups (smaller than 8MB) the chosen allocation
4487 * alignment may be larger than group size. Make sure the
4488 * alignment does not move allocation to a different group which
4489 * makes mballoc fail assertions later.
4491 start = max(start, rounddown(ac->ac_o_ex.fe_logical,
4492 (ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
4494 /* don't cover already allocated blocks in selected range */
4495 if (ar->pleft && start <= ar->lleft) {
4496 size -= ar->lleft + 1 - start;
4497 start = ar->lleft + 1;
4499 if (ar->pright && start + size - 1 >= ar->lright)
4500 size -= start + size - ar->lright;
4503 * Trim allocation request for filesystems with artificially small
4506 if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
4507 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
4511 ext4_mb_pa_adjust_overlap(ac, &start, &end);
4516 * In this function "start" and "size" are normalized for better
4517 * alignment and length such that we could preallocate more blocks.
4518 * This normalization is done such that original request of
4519 * ac->ac_o_ex.fe_logical & fe_len should always lie within "start" and
4520 * "size" boundaries.
4521 * (Note fe_len can be relaxed since FS block allocation API does not
4522 * provide gurantee on number of contiguous blocks allocation since that
4523 * depends upon free space left, etc).
4524 * In case of inode pa, later we use the allocated blocks
4525 * [pa_pstart + fe_logical - pa_lstart, fe_len/size] from the preallocated
4526 * range of goal/best blocks [start, size] to put it at the
4527 * ac_o_ex.fe_logical extent of this inode.
4528 * (See ext4_mb_use_inode_pa() for more details)
4530 if (start + size <= ac->ac_o_ex.fe_logical ||
4531 start > ac->ac_o_ex.fe_logical) {
4532 ext4_msg(ac->ac_sb, KERN_ERR,
4533 "start %lu, size %lu, fe_logical %lu",
4534 (unsigned long) start, (unsigned long) size,
4535 (unsigned long) ac->ac_o_ex.fe_logical);
4538 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
4540 /* now prepare goal request */
4542 /* XXX: is it better to align blocks WRT to logical
4543 * placement or satisfy big request as is */
4544 ac->ac_g_ex.fe_logical = start;
4545 ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
4546 ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
4548 /* define goal start in order to merge */
4549 if (ar->pright && (ar->lright == (start + size)) &&
4550 ar->pright >= size &&
4551 ar->pright - size >= le32_to_cpu(es->s_first_data_block)) {
4552 /* merge to the right */
4553 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
4554 &ac->ac_g_ex.fe_group,
4555 &ac->ac_g_ex.fe_start);
4556 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4558 if (ar->pleft && (ar->lleft + 1 == start) &&
4559 ar->pleft + 1 < ext4_blocks_count(es)) {
4560 /* merge to the left */
4561 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
4562 &ac->ac_g_ex.fe_group,
4563 &ac->ac_g_ex.fe_start);
4564 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4567 mb_debug(ac->ac_sb, "goal: %lld(was %lld) blocks at %u\n", size,
4571 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
4573 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4575 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len >= 1) {
4576 atomic_inc(&sbi->s_bal_reqs);
4577 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
4578 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
4579 atomic_inc(&sbi->s_bal_success);
4581 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
4582 for (int i=0; i<EXT4_MB_NUM_CRS; i++) {
4583 atomic_add(ac->ac_cX_found[i], &sbi->s_bal_cX_ex_scanned[i]);
4586 atomic_add(ac->ac_groups_scanned, &sbi->s_bal_groups_scanned);
4587 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
4588 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
4589 atomic_inc(&sbi->s_bal_goals);
4590 /* did we allocate as much as normalizer originally wanted? */
4591 if (ac->ac_f_ex.fe_len == ac->ac_orig_goal_len)
4592 atomic_inc(&sbi->s_bal_len_goals);
4594 if (ac->ac_found > sbi->s_mb_max_to_scan)
4595 atomic_inc(&sbi->s_bal_breaks);
4598 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
4599 trace_ext4_mballoc_alloc(ac);
4601 trace_ext4_mballoc_prealloc(ac);
4605 * Called on failure; free up any blocks from the inode PA for this
4606 * context. We don't need this for MB_GROUP_PA because we only change
4607 * pa_free in ext4_mb_release_context(), but on failure, we've already
4608 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
4610 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
4612 struct ext4_prealloc_space *pa = ac->ac_pa;
4613 struct ext4_buddy e4b;
4617 if (ac->ac_f_ex.fe_len == 0)
4619 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
4620 if (WARN_RATELIMIT(err,
4621 "ext4: mb_load_buddy failed (%d)", err))
4623 * This should never happen since we pin the
4624 * pages in the ext4_allocation_context so
4625 * ext4_mb_load_buddy() should never fail.
4628 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
4629 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
4630 ac->ac_f_ex.fe_len);
4631 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
4632 ext4_mb_unload_buddy(&e4b);
4635 if (pa->pa_type == MB_INODE_PA) {
4636 spin_lock(&pa->pa_lock);
4637 pa->pa_free += ac->ac_b_ex.fe_len;
4638 spin_unlock(&pa->pa_lock);
4643 * use blocks preallocated to inode
4645 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
4646 struct ext4_prealloc_space *pa)
4648 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4653 /* found preallocated blocks, use them */
4654 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
4655 end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
4656 start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
4657 len = EXT4_NUM_B2C(sbi, end - start);
4658 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
4659 &ac->ac_b_ex.fe_start);
4660 ac->ac_b_ex.fe_len = len;
4661 ac->ac_status = AC_STATUS_FOUND;
4664 BUG_ON(start < pa->pa_pstart);
4665 BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
4666 BUG_ON(pa->pa_free < len);
4667 BUG_ON(ac->ac_b_ex.fe_len <= 0);
4670 mb_debug(ac->ac_sb, "use %llu/%d from inode pa %p\n", start, len, pa);
4674 * use blocks preallocated to locality group
4676 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
4677 struct ext4_prealloc_space *pa)
4679 unsigned int len = ac->ac_o_ex.fe_len;
4681 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
4682 &ac->ac_b_ex.fe_group,
4683 &ac->ac_b_ex.fe_start);
4684 ac->ac_b_ex.fe_len = len;
4685 ac->ac_status = AC_STATUS_FOUND;
4688 /* we don't correct pa_pstart or pa_len here to avoid
4689 * possible race when the group is being loaded concurrently
4690 * instead we correct pa later, after blocks are marked
4691 * in on-disk bitmap -- see ext4_mb_release_context()
4692 * Other CPUs are prevented from allocating from this pa by lg_mutex
4694 mb_debug(ac->ac_sb, "use %u/%u from group pa %p\n",
4695 pa->pa_lstart, len, pa);
4699 * Return the prealloc space that have minimal distance
4700 * from the goal block. @cpa is the prealloc
4701 * space that is having currently known minimal distance
4702 * from the goal block.
4704 static struct ext4_prealloc_space *
4705 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
4706 struct ext4_prealloc_space *pa,
4707 struct ext4_prealloc_space *cpa)
4709 ext4_fsblk_t cur_distance, new_distance;
4712 atomic_inc(&pa->pa_count);
4715 cur_distance = abs(goal_block - cpa->pa_pstart);
4716 new_distance = abs(goal_block - pa->pa_pstart);
4718 if (cur_distance <= new_distance)
4721 /* drop the previous reference */
4722 atomic_dec(&cpa->pa_count);
4723 atomic_inc(&pa->pa_count);
4728 * check if found pa meets EXT4_MB_HINT_GOAL_ONLY
4731 ext4_mb_pa_goal_check(struct ext4_allocation_context *ac,
4732 struct ext4_prealloc_space *pa)
4734 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4737 if (likely(!(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY)))
4741 * If EXT4_MB_HINT_GOAL_ONLY is set, ac_g_ex will not be adjusted
4742 * in ext4_mb_normalize_request and will keep same with ac_o_ex
4743 * from ext4_mb_initialize_context. Choose ac_g_ex here to keep
4744 * consistent with ext4_mb_find_by_goal.
4746 start = pa->pa_pstart +
4747 (ac->ac_g_ex.fe_logical - pa->pa_lstart);
4748 if (ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex) != start)
4751 if (ac->ac_g_ex.fe_len > pa->pa_len -
4752 EXT4_B2C(sbi, ac->ac_g_ex.fe_logical - pa->pa_lstart))
4759 * search goal blocks in preallocated space
4761 static noinline_for_stack bool
4762 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
4764 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4766 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4767 struct ext4_locality_group *lg;
4768 struct ext4_prealloc_space *tmp_pa = NULL, *cpa = NULL;
4770 struct rb_node *iter;
4771 ext4_fsblk_t goal_block;
4773 /* only data can be preallocated */
4774 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4778 * first, try per-file preallocation by searching the inode pa rbtree.
4780 * Here, we can't do a direct traversal of the tree because
4781 * ext4_mb_discard_group_preallocation() can paralelly mark the pa
4782 * deleted and that can cause direct traversal to skip some entries.
4784 read_lock(&ei->i_prealloc_lock);
4786 if (RB_EMPTY_ROOT(&ei->i_prealloc_node)) {
4791 * Step 1: Find a pa with logical start immediately adjacent to the
4792 * original logical start. This could be on the left or right.
4794 * (tmp_pa->pa_lstart never changes so we can skip locking for it).
4796 for (iter = ei->i_prealloc_node.rb_node; iter;
4797 iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
4798 tmp_pa->pa_lstart, iter)) {
4799 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4800 pa_node.inode_node);
4804 * Step 2: The adjacent pa might be to the right of logical start, find
4805 * the left adjacent pa. After this step we'd have a valid tmp_pa whose
4806 * logical start is towards the left of original request's logical start
4808 if (tmp_pa->pa_lstart > ac->ac_o_ex.fe_logical) {
4809 struct rb_node *tmp;
4810 tmp = rb_prev(&tmp_pa->pa_node.inode_node);
4813 tmp_pa = rb_entry(tmp, struct ext4_prealloc_space,
4814 pa_node.inode_node);
4817 * If there is no adjacent pa to the left then finding
4818 * an overlapping pa is not possible hence stop searching
4825 BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
4828 * Step 3: If the left adjacent pa is deleted, keep moving left to find
4829 * the first non deleted adjacent pa. After this step we should have a
4830 * valid tmp_pa which is guaranteed to be non deleted.
4832 for (iter = &tmp_pa->pa_node.inode_node;; iter = rb_prev(iter)) {
4835 * no non deleted left adjacent pa, so stop searching
4840 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4841 pa_node.inode_node);
4842 spin_lock(&tmp_pa->pa_lock);
4843 if (tmp_pa->pa_deleted == 0) {
4845 * We will keep holding the pa_lock from
4846 * this point on because we don't want group discard
4847 * to delete this pa underneath us. Since group
4848 * discard is anyways an ENOSPC operation it
4849 * should be okay for it to wait a few more cycles.
4853 spin_unlock(&tmp_pa->pa_lock);
4857 BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
4858 BUG_ON(tmp_pa->pa_deleted == 1);
4861 * Step 4: We now have the non deleted left adjacent pa. Only this
4862 * pa can possibly satisfy the request hence check if it overlaps
4863 * original logical start and stop searching if it doesn't.
4865 tmp_pa_end = (loff_t)tmp_pa->pa_lstart + EXT4_C2B(sbi, tmp_pa->pa_len);
4867 if (ac->ac_o_ex.fe_logical >= tmp_pa_end) {
4868 spin_unlock(&tmp_pa->pa_lock);
4872 /* non-extent files can't have physical blocks past 2^32 */
4873 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
4874 (tmp_pa->pa_pstart + EXT4_C2B(sbi, tmp_pa->pa_len) >
4875 EXT4_MAX_BLOCK_FILE_PHYS)) {
4877 * Since PAs don't overlap, we won't find any other PA to
4880 spin_unlock(&tmp_pa->pa_lock);
4884 if (tmp_pa->pa_free && likely(ext4_mb_pa_goal_check(ac, tmp_pa))) {
4885 atomic_inc(&tmp_pa->pa_count);
4886 ext4_mb_use_inode_pa(ac, tmp_pa);
4887 spin_unlock(&tmp_pa->pa_lock);
4888 read_unlock(&ei->i_prealloc_lock);
4892 * We found a valid overlapping pa but couldn't use it because
4893 * it had no free blocks. This should ideally never happen
4896 * 1. When a new inode pa is added to rbtree it must have
4897 * pa_free > 0 since otherwise we won't actually need
4900 * 2. An inode pa that is in the rbtree can only have it's
4901 * pa_free become zero when another thread calls:
4902 * ext4_mb_new_blocks
4903 * ext4_mb_use_preallocated
4904 * ext4_mb_use_inode_pa
4906 * 3. Further, after the above calls make pa_free == 0, we will
4907 * immediately remove it from the rbtree in:
4908 * ext4_mb_new_blocks
4909 * ext4_mb_release_context
4912 * 4. Since the pa_free becoming 0 and pa_free getting removed
4913 * from tree both happen in ext4_mb_new_blocks, which is always
4914 * called with i_data_sem held for data allocations, we can be
4915 * sure that another process will never see a pa in rbtree with
4918 WARN_ON_ONCE(tmp_pa->pa_free == 0);
4920 spin_unlock(&tmp_pa->pa_lock);
4922 read_unlock(&ei->i_prealloc_lock);
4924 /* can we use group allocation? */
4925 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
4928 /* inode may have no locality group for some reason */
4932 order = fls(ac->ac_o_ex.fe_len) - 1;
4933 if (order > PREALLOC_TB_SIZE - 1)
4934 /* The max size of hash table is PREALLOC_TB_SIZE */
4935 order = PREALLOC_TB_SIZE - 1;
4937 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
4939 * search for the prealloc space that is having
4940 * minimal distance from the goal block.
4942 for (i = order; i < PREALLOC_TB_SIZE; i++) {
4944 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[i],
4946 spin_lock(&tmp_pa->pa_lock);
4947 if (tmp_pa->pa_deleted == 0 &&
4948 tmp_pa->pa_free >= ac->ac_o_ex.fe_len) {
4950 cpa = ext4_mb_check_group_pa(goal_block,
4953 spin_unlock(&tmp_pa->pa_lock);
4958 ext4_mb_use_group_pa(ac, cpa);
4965 * the function goes through all block freed in the group
4966 * but not yet committed and marks them used in in-core bitmap.
4967 * buddy must be generated from this bitmap
4968 * Need to be called with the ext4 group lock held
4970 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
4974 struct ext4_group_info *grp;
4975 struct ext4_free_data *entry;
4977 grp = ext4_get_group_info(sb, group);
4980 n = rb_first(&(grp->bb_free_root));
4983 entry = rb_entry(n, struct ext4_free_data, efd_node);
4984 mb_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
4991 * the function goes through all preallocation in this group and marks them
4992 * used in in-core bitmap. buddy must be generated from this bitmap
4993 * Need to be called with ext4 group lock held
4995 static noinline_for_stack
4996 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
4999 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
5000 struct ext4_prealloc_space *pa;
5001 struct list_head *cur;
5002 ext4_group_t groupnr;
5003 ext4_grpblk_t start;
5004 int preallocated = 0;
5010 /* all form of preallocation discards first load group,
5011 * so the only competing code is preallocation use.
5012 * we don't need any locking here
5013 * notice we do NOT ignore preallocations with pa_deleted
5014 * otherwise we could leave used blocks available for
5015 * allocation in buddy when concurrent ext4_mb_put_pa()
5016 * is dropping preallocation
5018 list_for_each(cur, &grp->bb_prealloc_list) {
5019 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
5020 spin_lock(&pa->pa_lock);
5021 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5024 spin_unlock(&pa->pa_lock);
5025 if (unlikely(len == 0))
5027 BUG_ON(groupnr != group);
5028 mb_set_bits(bitmap, start, len);
5029 preallocated += len;
5031 mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
5034 static void ext4_mb_mark_pa_deleted(struct super_block *sb,
5035 struct ext4_prealloc_space *pa)
5037 struct ext4_inode_info *ei;
5039 if (pa->pa_deleted) {
5040 ext4_warning(sb, "deleted pa, type:%d, pblk:%llu, lblk:%u, len:%d\n",
5041 pa->pa_type, pa->pa_pstart, pa->pa_lstart,
5048 if (pa->pa_type == MB_INODE_PA) {
5049 ei = EXT4_I(pa->pa_inode);
5050 atomic_dec(&ei->i_prealloc_active);
5054 static inline void ext4_mb_pa_free(struct ext4_prealloc_space *pa)
5057 BUG_ON(atomic_read(&pa->pa_count));
5058 BUG_ON(pa->pa_deleted == 0);
5059 kmem_cache_free(ext4_pspace_cachep, pa);
5062 static void ext4_mb_pa_callback(struct rcu_head *head)
5064 struct ext4_prealloc_space *pa;
5066 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
5067 ext4_mb_pa_free(pa);
5071 * drops a reference to preallocated space descriptor
5072 * if this was the last reference and the space is consumed
5074 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
5075 struct super_block *sb, struct ext4_prealloc_space *pa)
5078 ext4_fsblk_t grp_blk;
5079 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
5081 /* in this short window concurrent discard can set pa_deleted */
5082 spin_lock(&pa->pa_lock);
5083 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
5084 spin_unlock(&pa->pa_lock);
5088 if (pa->pa_deleted == 1) {
5089 spin_unlock(&pa->pa_lock);
5093 ext4_mb_mark_pa_deleted(sb, pa);
5094 spin_unlock(&pa->pa_lock);
5096 grp_blk = pa->pa_pstart;
5098 * If doing group-based preallocation, pa_pstart may be in the
5099 * next group when pa is used up
5101 if (pa->pa_type == MB_GROUP_PA)
5104 grp = ext4_get_group_number(sb, grp_blk);
5109 * P1 (buddy init) P2 (regular allocation)
5110 * find block B in PA
5111 * copy on-disk bitmap to buddy
5112 * mark B in on-disk bitmap
5113 * drop PA from group
5114 * mark all PAs in buddy
5116 * thus, P1 initializes buddy with B available. to prevent this
5117 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
5120 ext4_lock_group(sb, grp);
5121 list_del(&pa->pa_group_list);
5122 ext4_unlock_group(sb, grp);
5124 if (pa->pa_type == MB_INODE_PA) {
5125 write_lock(pa->pa_node_lock.inode_lock);
5126 rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5127 write_unlock(pa->pa_node_lock.inode_lock);
5128 ext4_mb_pa_free(pa);
5130 spin_lock(pa->pa_node_lock.lg_lock);
5131 list_del_rcu(&pa->pa_node.lg_list);
5132 spin_unlock(pa->pa_node_lock.lg_lock);
5133 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5137 static void ext4_mb_pa_rb_insert(struct rb_root *root, struct rb_node *new)
5139 struct rb_node **iter = &root->rb_node, *parent = NULL;
5140 struct ext4_prealloc_space *iter_pa, *new_pa;
5141 ext4_lblk_t iter_start, new_start;
5144 iter_pa = rb_entry(*iter, struct ext4_prealloc_space,
5145 pa_node.inode_node);
5146 new_pa = rb_entry(new, struct ext4_prealloc_space,
5147 pa_node.inode_node);
5148 iter_start = iter_pa->pa_lstart;
5149 new_start = new_pa->pa_lstart;
5152 if (new_start < iter_start)
5153 iter = &((*iter)->rb_left);
5155 iter = &((*iter)->rb_right);
5158 rb_link_node(new, parent, iter);
5159 rb_insert_color(new, root);
5163 * creates new preallocated space for given inode
5165 static noinline_for_stack void
5166 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
5168 struct super_block *sb = ac->ac_sb;
5169 struct ext4_sb_info *sbi = EXT4_SB(sb);
5170 struct ext4_prealloc_space *pa;
5171 struct ext4_group_info *grp;
5172 struct ext4_inode_info *ei;
5174 /* preallocate only when found space is larger then requested */
5175 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5176 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5177 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
5178 BUG_ON(ac->ac_pa == NULL);
5182 if (ac->ac_b_ex.fe_len < ac->ac_orig_goal_len) {
5186 /* we can't allocate as much as normalizer wants.
5187 * so, found space must get proper lstart
5188 * to cover original request */
5189 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
5190 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
5193 * Use the below logic for adjusting best extent as it keeps
5194 * fragmentation in check while ensuring logical range of best
5195 * extent doesn't overflow out of goal extent:
5197 * 1. Check if best ex can be kept at end of goal (before
5198 * cr_best_avail trimmed it) and still cover original start
5199 * 2. Else, check if best ex can be kept at start of goal and
5200 * still cover original start
5201 * 3. Else, keep the best ex at start of original request.
5203 new_bex_end = ac->ac_g_ex.fe_logical +
5204 EXT4_C2B(sbi, ac->ac_orig_goal_len);
5205 new_bex_start = new_bex_end - EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
5206 if (ac->ac_o_ex.fe_logical >= new_bex_start)
5209 new_bex_start = ac->ac_g_ex.fe_logical;
5211 new_bex_start + EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
5212 if (ac->ac_o_ex.fe_logical < new_bex_end)
5215 new_bex_start = ac->ac_o_ex.fe_logical;
5217 new_bex_start + EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
5220 ac->ac_b_ex.fe_logical = new_bex_start;
5222 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
5223 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
5224 BUG_ON(new_bex_end > (ac->ac_g_ex.fe_logical +
5225 EXT4_C2B(sbi, ac->ac_orig_goal_len)));
5228 pa->pa_lstart = ac->ac_b_ex.fe_logical;
5229 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5230 pa->pa_len = ac->ac_b_ex.fe_len;
5231 pa->pa_free = pa->pa_len;
5232 spin_lock_init(&pa->pa_lock);
5233 INIT_LIST_HEAD(&pa->pa_group_list);
5235 pa->pa_type = MB_INODE_PA;
5237 mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5238 pa->pa_len, pa->pa_lstart);
5239 trace_ext4_mb_new_inode_pa(ac, pa);
5241 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
5242 ext4_mb_use_inode_pa(ac, pa);
5244 ei = EXT4_I(ac->ac_inode);
5245 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
5249 pa->pa_node_lock.inode_lock = &ei->i_prealloc_lock;
5250 pa->pa_inode = ac->ac_inode;
5252 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5254 write_lock(pa->pa_node_lock.inode_lock);
5255 ext4_mb_pa_rb_insert(&ei->i_prealloc_node, &pa->pa_node.inode_node);
5256 write_unlock(pa->pa_node_lock.inode_lock);
5257 atomic_inc(&ei->i_prealloc_active);
5261 * creates new preallocated space for locality group inodes belongs to
5263 static noinline_for_stack void
5264 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
5266 struct super_block *sb = ac->ac_sb;
5267 struct ext4_locality_group *lg;
5268 struct ext4_prealloc_space *pa;
5269 struct ext4_group_info *grp;
5271 /* preallocate only when found space is larger then requested */
5272 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5273 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5274 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
5275 BUG_ON(ac->ac_pa == NULL);
5279 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5280 pa->pa_lstart = pa->pa_pstart;
5281 pa->pa_len = ac->ac_b_ex.fe_len;
5282 pa->pa_free = pa->pa_len;
5283 spin_lock_init(&pa->pa_lock);
5284 INIT_LIST_HEAD(&pa->pa_node.lg_list);
5285 INIT_LIST_HEAD(&pa->pa_group_list);
5287 pa->pa_type = MB_GROUP_PA;
5289 mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5290 pa->pa_len, pa->pa_lstart);
5291 trace_ext4_mb_new_group_pa(ac, pa);
5293 ext4_mb_use_group_pa(ac, pa);
5294 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
5296 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
5302 pa->pa_node_lock.lg_lock = &lg->lg_prealloc_lock;
5303 pa->pa_inode = NULL;
5305 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5308 * We will later add the new pa to the right bucket
5309 * after updating the pa_free in ext4_mb_release_context
5313 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
5315 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
5316 ext4_mb_new_group_pa(ac);
5318 ext4_mb_new_inode_pa(ac);
5322 * finds all unused blocks in on-disk bitmap, frees them in
5323 * in-core bitmap and buddy.
5324 * @pa must be unlinked from inode and group lists, so that
5325 * nobody else can find/use it.
5326 * the caller MUST hold group/inode locks.
5327 * TODO: optimize the case when there are no in-core structures yet
5329 static noinline_for_stack int
5330 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
5331 struct ext4_prealloc_space *pa)
5333 struct super_block *sb = e4b->bd_sb;
5334 struct ext4_sb_info *sbi = EXT4_SB(sb);
5339 unsigned long long grp_blk_start;
5342 BUG_ON(pa->pa_deleted == 0);
5343 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
5344 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
5345 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
5346 end = bit + pa->pa_len;
5349 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
5352 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
5353 mb_debug(sb, "free preallocated %u/%u in group %u\n",
5354 (unsigned) ext4_group_first_block_no(sb, group) + bit,
5355 (unsigned) next - bit, (unsigned) group);
5358 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
5359 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
5360 EXT4_C2B(sbi, bit)),
5362 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
5365 if (free != pa->pa_free) {
5366 ext4_msg(e4b->bd_sb, KERN_CRIT,
5367 "pa %p: logic %lu, phys. %lu, len %d",
5368 pa, (unsigned long) pa->pa_lstart,
5369 (unsigned long) pa->pa_pstart,
5371 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
5374 * pa is already deleted so we use the value obtained
5375 * from the bitmap and continue.
5378 atomic_add(free, &sbi->s_mb_discarded);
5383 static noinline_for_stack int
5384 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
5385 struct ext4_prealloc_space *pa)
5387 struct super_block *sb = e4b->bd_sb;
5391 trace_ext4_mb_release_group_pa(sb, pa);
5392 BUG_ON(pa->pa_deleted == 0);
5393 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
5394 if (unlikely(group != e4b->bd_group && pa->pa_len != 0)) {
5395 ext4_warning(sb, "bad group: expected %u, group %u, pa_start %llu",
5396 e4b->bd_group, group, pa->pa_pstart);
5399 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
5400 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
5401 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
5407 * releases all preallocations in given group
5409 * first, we need to decide discard policy:
5410 * - when do we discard
5412 * - how many do we discard
5413 * 1) how many requested
5415 static noinline_for_stack int
5416 ext4_mb_discard_group_preallocations(struct super_block *sb,
5417 ext4_group_t group, int *busy)
5419 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
5420 struct buffer_head *bitmap_bh = NULL;
5421 struct ext4_prealloc_space *pa, *tmp;
5422 struct list_head list;
5423 struct ext4_buddy e4b;
5424 struct ext4_inode_info *ei;
5430 mb_debug(sb, "discard preallocation for group %u\n", group);
5431 if (list_empty(&grp->bb_prealloc_list))
5434 bitmap_bh = ext4_read_block_bitmap(sb, group);
5435 if (IS_ERR(bitmap_bh)) {
5436 err = PTR_ERR(bitmap_bh);
5437 ext4_error_err(sb, -err,
5438 "Error %d reading block bitmap for %u",
5443 err = ext4_mb_load_buddy(sb, group, &e4b);
5445 ext4_warning(sb, "Error %d loading buddy information for %u",
5451 INIT_LIST_HEAD(&list);
5452 ext4_lock_group(sb, group);
5453 list_for_each_entry_safe(pa, tmp,
5454 &grp->bb_prealloc_list, pa_group_list) {
5455 spin_lock(&pa->pa_lock);
5456 if (atomic_read(&pa->pa_count)) {
5457 spin_unlock(&pa->pa_lock);
5461 if (pa->pa_deleted) {
5462 spin_unlock(&pa->pa_lock);
5466 /* seems this one can be freed ... */
5467 ext4_mb_mark_pa_deleted(sb, pa);
5470 this_cpu_inc(discard_pa_seq);
5472 /* we can trust pa_free ... */
5473 free += pa->pa_free;
5475 spin_unlock(&pa->pa_lock);
5477 list_del(&pa->pa_group_list);
5478 list_add(&pa->u.pa_tmp_list, &list);
5481 /* now free all selected PAs */
5482 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5484 /* remove from object (inode or locality group) */
5485 if (pa->pa_type == MB_GROUP_PA) {
5486 spin_lock(pa->pa_node_lock.lg_lock);
5487 list_del_rcu(&pa->pa_node.lg_list);
5488 spin_unlock(pa->pa_node_lock.lg_lock);
5490 write_lock(pa->pa_node_lock.inode_lock);
5491 ei = EXT4_I(pa->pa_inode);
5492 rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5493 write_unlock(pa->pa_node_lock.inode_lock);
5496 list_del(&pa->u.pa_tmp_list);
5498 if (pa->pa_type == MB_GROUP_PA) {
5499 ext4_mb_release_group_pa(&e4b, pa);
5500 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5502 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
5503 ext4_mb_pa_free(pa);
5507 ext4_unlock_group(sb, group);
5508 ext4_mb_unload_buddy(&e4b);
5511 mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
5512 free, group, grp->bb_free);
5517 * releases all non-used preallocated blocks for given inode
5519 * It's important to discard preallocations under i_data_sem
5520 * We don't want another block to be served from the prealloc
5521 * space when we are discarding the inode prealloc space.
5523 * FIXME!! Make sure it is valid at all the call sites
5525 void ext4_discard_preallocations(struct inode *inode, unsigned int needed)
5527 struct ext4_inode_info *ei = EXT4_I(inode);
5528 struct super_block *sb = inode->i_sb;
5529 struct buffer_head *bitmap_bh = NULL;
5530 struct ext4_prealloc_space *pa, *tmp;
5531 ext4_group_t group = 0;
5532 struct list_head list;
5533 struct ext4_buddy e4b;
5534 struct rb_node *iter;
5537 if (!S_ISREG(inode->i_mode)) {
5541 if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
5544 mb_debug(sb, "discard preallocation for inode %lu\n",
5546 trace_ext4_discard_preallocations(inode,
5547 atomic_read(&ei->i_prealloc_active), needed);
5549 INIT_LIST_HEAD(&list);
5555 /* first, collect all pa's in the inode */
5556 write_lock(&ei->i_prealloc_lock);
5557 for (iter = rb_first(&ei->i_prealloc_node); iter && needed;
5558 iter = rb_next(iter)) {
5559 pa = rb_entry(iter, struct ext4_prealloc_space,
5560 pa_node.inode_node);
5561 BUG_ON(pa->pa_node_lock.inode_lock != &ei->i_prealloc_lock);
5563 spin_lock(&pa->pa_lock);
5564 if (atomic_read(&pa->pa_count)) {
5565 /* this shouldn't happen often - nobody should
5566 * use preallocation while we're discarding it */
5567 spin_unlock(&pa->pa_lock);
5568 write_unlock(&ei->i_prealloc_lock);
5569 ext4_msg(sb, KERN_ERR,
5570 "uh-oh! used pa while discarding");
5572 schedule_timeout_uninterruptible(HZ);
5576 if (pa->pa_deleted == 0) {
5577 ext4_mb_mark_pa_deleted(sb, pa);
5578 spin_unlock(&pa->pa_lock);
5579 rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5580 list_add(&pa->u.pa_tmp_list, &list);
5585 /* someone is deleting pa right now */
5586 spin_unlock(&pa->pa_lock);
5587 write_unlock(&ei->i_prealloc_lock);
5589 /* we have to wait here because pa_deleted
5590 * doesn't mean pa is already unlinked from
5591 * the list. as we might be called from
5592 * ->clear_inode() the inode will get freed
5593 * and concurrent thread which is unlinking
5594 * pa from inode's list may access already
5595 * freed memory, bad-bad-bad */
5597 /* XXX: if this happens too often, we can
5598 * add a flag to force wait only in case
5599 * of ->clear_inode(), but not in case of
5600 * regular truncate */
5601 schedule_timeout_uninterruptible(HZ);
5604 write_unlock(&ei->i_prealloc_lock);
5606 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5607 BUG_ON(pa->pa_type != MB_INODE_PA);
5608 group = ext4_get_group_number(sb, pa->pa_pstart);
5610 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
5611 GFP_NOFS|__GFP_NOFAIL);
5613 ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
5618 bitmap_bh = ext4_read_block_bitmap(sb, group);
5619 if (IS_ERR(bitmap_bh)) {
5620 err = PTR_ERR(bitmap_bh);
5621 ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
5623 ext4_mb_unload_buddy(&e4b);
5627 ext4_lock_group(sb, group);
5628 list_del(&pa->pa_group_list);
5629 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
5630 ext4_unlock_group(sb, group);
5632 ext4_mb_unload_buddy(&e4b);
5635 list_del(&pa->u.pa_tmp_list);
5636 ext4_mb_pa_free(pa);
5640 static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
5642 struct ext4_prealloc_space *pa;
5644 BUG_ON(ext4_pspace_cachep == NULL);
5645 pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
5648 atomic_set(&pa->pa_count, 1);
5653 static void ext4_mb_pa_put_free(struct ext4_allocation_context *ac)
5655 struct ext4_prealloc_space *pa = ac->ac_pa;
5659 WARN_ON(!atomic_dec_and_test(&pa->pa_count));
5661 * current function is only called due to an error or due to
5662 * len of found blocks < len of requested blocks hence the PA has not
5663 * been added to grp->bb_prealloc_list. So we don't need to lock it
5666 ext4_mb_pa_free(pa);
5669 #ifdef CONFIG_EXT4_DEBUG
5670 static inline void ext4_mb_show_pa(struct super_block *sb)
5672 ext4_group_t i, ngroups;
5674 if (ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
5677 ngroups = ext4_get_groups_count(sb);
5678 mb_debug(sb, "groups: ");
5679 for (i = 0; i < ngroups; i++) {
5680 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
5681 struct ext4_prealloc_space *pa;
5682 ext4_grpblk_t start;
5683 struct list_head *cur;
5687 ext4_lock_group(sb, i);
5688 list_for_each(cur, &grp->bb_prealloc_list) {
5689 pa = list_entry(cur, struct ext4_prealloc_space,
5691 spin_lock(&pa->pa_lock);
5692 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5694 spin_unlock(&pa->pa_lock);
5695 mb_debug(sb, "PA:%u:%d:%d\n", i, start,
5698 ext4_unlock_group(sb, i);
5699 mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
5704 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5706 struct super_block *sb = ac->ac_sb;
5708 if (ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
5711 mb_debug(sb, "Can't allocate:"
5712 " Allocation context details:");
5713 mb_debug(sb, "status %u flags 0x%x",
5714 ac->ac_status, ac->ac_flags);
5715 mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
5716 "goal %lu/%lu/%lu@%lu, "
5717 "best %lu/%lu/%lu@%lu cr %d",
5718 (unsigned long)ac->ac_o_ex.fe_group,
5719 (unsigned long)ac->ac_o_ex.fe_start,
5720 (unsigned long)ac->ac_o_ex.fe_len,
5721 (unsigned long)ac->ac_o_ex.fe_logical,
5722 (unsigned long)ac->ac_g_ex.fe_group,
5723 (unsigned long)ac->ac_g_ex.fe_start,
5724 (unsigned long)ac->ac_g_ex.fe_len,
5725 (unsigned long)ac->ac_g_ex.fe_logical,
5726 (unsigned long)ac->ac_b_ex.fe_group,
5727 (unsigned long)ac->ac_b_ex.fe_start,
5728 (unsigned long)ac->ac_b_ex.fe_len,
5729 (unsigned long)ac->ac_b_ex.fe_logical,
5730 (int)ac->ac_criteria);
5731 mb_debug(sb, "%u found", ac->ac_found);
5732 mb_debug(sb, "used pa: %s, ", ac->ac_pa ? "yes" : "no");
5734 mb_debug(sb, "pa_type %s\n", ac->ac_pa->pa_type == MB_GROUP_PA ?
5735 "group pa" : "inode pa");
5736 ext4_mb_show_pa(sb);
5739 static inline void ext4_mb_show_pa(struct super_block *sb)
5743 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5745 ext4_mb_show_pa(ac->ac_sb);
5751 * We use locality group preallocation for small size file. The size of the
5752 * file is determined by the current size or the resulting size after
5753 * allocation which ever is larger
5755 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
5757 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
5759 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
5760 int bsbits = ac->ac_sb->s_blocksize_bits;
5762 bool inode_pa_eligible, group_pa_eligible;
5764 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
5767 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
5770 group_pa_eligible = sbi->s_mb_group_prealloc > 0;
5771 inode_pa_eligible = true;
5772 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
5773 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
5776 /* No point in using inode preallocation for closed files */
5777 if ((size == isize) && !ext4_fs_is_busy(sbi) &&
5778 !inode_is_open_for_write(ac->ac_inode))
5779 inode_pa_eligible = false;
5781 size = max(size, isize);
5782 /* Don't use group allocation for large files */
5783 if (size > sbi->s_mb_stream_request)
5784 group_pa_eligible = false;
5786 if (!group_pa_eligible) {
5787 if (inode_pa_eligible)
5788 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
5790 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
5794 BUG_ON(ac->ac_lg != NULL);
5796 * locality group prealloc space are per cpu. The reason for having
5797 * per cpu locality group is to reduce the contention between block
5798 * request from multiple CPUs.
5800 ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
5802 /* we're going to use group allocation */
5803 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
5805 /* serialize all allocations in the group */
5806 mutex_lock(&ac->ac_lg->lg_mutex);
5809 static noinline_for_stack void
5810 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
5811 struct ext4_allocation_request *ar)
5813 struct super_block *sb = ar->inode->i_sb;
5814 struct ext4_sb_info *sbi = EXT4_SB(sb);
5815 struct ext4_super_block *es = sbi->s_es;
5819 ext4_grpblk_t block;
5821 /* we can't allocate > group size */
5824 /* just a dirty hack to filter too big requests */
5825 if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
5826 len = EXT4_CLUSTERS_PER_GROUP(sb);
5828 /* start searching from the goal */
5830 if (goal < le32_to_cpu(es->s_first_data_block) ||
5831 goal >= ext4_blocks_count(es))
5832 goal = le32_to_cpu(es->s_first_data_block);
5833 ext4_get_group_no_and_offset(sb, goal, &group, &block);
5835 /* set up allocation goals */
5836 ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
5837 ac->ac_status = AC_STATUS_CONTINUE;
5839 ac->ac_inode = ar->inode;
5840 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
5841 ac->ac_o_ex.fe_group = group;
5842 ac->ac_o_ex.fe_start = block;
5843 ac->ac_o_ex.fe_len = len;
5844 ac->ac_g_ex = ac->ac_o_ex;
5845 ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
5846 ac->ac_flags = ar->flags;
5848 /* we have to define context: we'll work with a file or
5849 * locality group. this is a policy, actually */
5850 ext4_mb_group_or_file(ac);
5852 mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
5853 "left: %u/%u, right %u/%u to %swritable\n",
5854 (unsigned) ar->len, (unsigned) ar->logical,
5855 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
5856 (unsigned) ar->lleft, (unsigned) ar->pleft,
5857 (unsigned) ar->lright, (unsigned) ar->pright,
5858 inode_is_open_for_write(ar->inode) ? "" : "non-");
5861 static noinline_for_stack void
5862 ext4_mb_discard_lg_preallocations(struct super_block *sb,
5863 struct ext4_locality_group *lg,
5864 int order, int total_entries)
5866 ext4_group_t group = 0;
5867 struct ext4_buddy e4b;
5868 struct list_head discard_list;
5869 struct ext4_prealloc_space *pa, *tmp;
5871 mb_debug(sb, "discard locality group preallocation\n");
5873 INIT_LIST_HEAD(&discard_list);
5875 spin_lock(&lg->lg_prealloc_lock);
5876 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
5878 lockdep_is_held(&lg->lg_prealloc_lock)) {
5879 spin_lock(&pa->pa_lock);
5880 if (atomic_read(&pa->pa_count)) {
5882 * This is the pa that we just used
5883 * for block allocation. So don't
5886 spin_unlock(&pa->pa_lock);
5889 if (pa->pa_deleted) {
5890 spin_unlock(&pa->pa_lock);
5893 /* only lg prealloc space */
5894 BUG_ON(pa->pa_type != MB_GROUP_PA);
5896 /* seems this one can be freed ... */
5897 ext4_mb_mark_pa_deleted(sb, pa);
5898 spin_unlock(&pa->pa_lock);
5900 list_del_rcu(&pa->pa_node.lg_list);
5901 list_add(&pa->u.pa_tmp_list, &discard_list);
5904 if (total_entries <= 5) {
5906 * we want to keep only 5 entries
5907 * allowing it to grow to 8. This
5908 * mak sure we don't call discard
5909 * soon for this list.
5914 spin_unlock(&lg->lg_prealloc_lock);
5916 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
5919 group = ext4_get_group_number(sb, pa->pa_pstart);
5920 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
5921 GFP_NOFS|__GFP_NOFAIL);
5923 ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
5927 ext4_lock_group(sb, group);
5928 list_del(&pa->pa_group_list);
5929 ext4_mb_release_group_pa(&e4b, pa);
5930 ext4_unlock_group(sb, group);
5932 ext4_mb_unload_buddy(&e4b);
5933 list_del(&pa->u.pa_tmp_list);
5934 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5939 * We have incremented pa_count. So it cannot be freed at this
5940 * point. Also we hold lg_mutex. So no parallel allocation is
5941 * possible from this lg. That means pa_free cannot be updated.
5943 * A parallel ext4_mb_discard_group_preallocations is possible.
5944 * which can cause the lg_prealloc_list to be updated.
5947 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
5949 int order, added = 0, lg_prealloc_count = 1;
5950 struct super_block *sb = ac->ac_sb;
5951 struct ext4_locality_group *lg = ac->ac_lg;
5952 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
5954 order = fls(pa->pa_free) - 1;
5955 if (order > PREALLOC_TB_SIZE - 1)
5956 /* The max size of hash table is PREALLOC_TB_SIZE */
5957 order = PREALLOC_TB_SIZE - 1;
5958 /* Add the prealloc space to lg */
5959 spin_lock(&lg->lg_prealloc_lock);
5960 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
5962 lockdep_is_held(&lg->lg_prealloc_lock)) {
5963 spin_lock(&tmp_pa->pa_lock);
5964 if (tmp_pa->pa_deleted) {
5965 spin_unlock(&tmp_pa->pa_lock);
5968 if (!added && pa->pa_free < tmp_pa->pa_free) {
5969 /* Add to the tail of the previous entry */
5970 list_add_tail_rcu(&pa->pa_node.lg_list,
5971 &tmp_pa->pa_node.lg_list);
5974 * we want to count the total
5975 * number of entries in the list
5978 spin_unlock(&tmp_pa->pa_lock);
5979 lg_prealloc_count++;
5982 list_add_tail_rcu(&pa->pa_node.lg_list,
5983 &lg->lg_prealloc_list[order]);
5984 spin_unlock(&lg->lg_prealloc_lock);
5986 /* Now trim the list to be not more than 8 elements */
5987 if (lg_prealloc_count > 8) {
5988 ext4_mb_discard_lg_preallocations(sb, lg,
5989 order, lg_prealloc_count);
5996 * release all resource we used in allocation
5998 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
6000 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
6001 struct ext4_prealloc_space *pa = ac->ac_pa;
6003 if (pa->pa_type == MB_GROUP_PA) {
6004 /* see comment in ext4_mb_use_group_pa() */
6005 spin_lock(&pa->pa_lock);
6006 pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
6007 pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
6008 pa->pa_free -= ac->ac_b_ex.fe_len;
6009 pa->pa_len -= ac->ac_b_ex.fe_len;
6010 spin_unlock(&pa->pa_lock);
6013 * We want to add the pa to the right bucket.
6014 * Remove it from the list and while adding
6015 * make sure the list to which we are adding
6018 if (likely(pa->pa_free)) {
6019 spin_lock(pa->pa_node_lock.lg_lock);
6020 list_del_rcu(&pa->pa_node.lg_list);
6021 spin_unlock(pa->pa_node_lock.lg_lock);
6022 ext4_mb_add_n_trim(ac);
6026 ext4_mb_put_pa(ac, ac->ac_sb, pa);
6028 if (ac->ac_bitmap_page)
6029 put_page(ac->ac_bitmap_page);
6030 if (ac->ac_buddy_page)
6031 put_page(ac->ac_buddy_page);
6032 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
6033 mutex_unlock(&ac->ac_lg->lg_mutex);
6034 ext4_mb_collect_stats(ac);
6038 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
6040 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
6042 int freed = 0, busy = 0;
6045 trace_ext4_mb_discard_preallocations(sb, needed);
6048 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
6050 for (i = 0; i < ngroups && needed > 0; i++) {
6051 ret = ext4_mb_discard_group_preallocations(sb, i, &busy);
6057 if (needed > 0 && busy && ++retry < 3) {
6065 static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
6066 struct ext4_allocation_context *ac, u64 *seq)
6072 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
6077 seq_retry = ext4_get_discard_pa_seq_sum();
6078 if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
6079 ac->ac_flags |= EXT4_MB_STRICT_CHECK;
6085 mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
6090 * Simple allocator for Ext4 fast commit replay path. It searches for blocks
6091 * linearly starting at the goal block and also excludes the blocks which
6092 * are going to be in use after fast commit replay.
6095 ext4_mb_new_blocks_simple(struct ext4_allocation_request *ar, int *errp)
6097 struct buffer_head *bitmap_bh;
6098 struct super_block *sb = ar->inode->i_sb;
6099 struct ext4_sb_info *sbi = EXT4_SB(sb);
6100 ext4_group_t group, nr;
6101 ext4_grpblk_t blkoff;
6102 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
6103 ext4_grpblk_t i = 0;
6104 ext4_fsblk_t goal, block;
6105 struct ext4_super_block *es = EXT4_SB(sb)->s_es;
6108 if (goal < le32_to_cpu(es->s_first_data_block) ||
6109 goal >= ext4_blocks_count(es))
6110 goal = le32_to_cpu(es->s_first_data_block);
6113 ext4_get_group_no_and_offset(sb, goal, &group, &blkoff);
6114 for (nr = ext4_get_groups_count(sb); nr > 0; nr--) {
6115 bitmap_bh = ext4_read_block_bitmap(sb, group);
6116 if (IS_ERR(bitmap_bh)) {
6117 *errp = PTR_ERR(bitmap_bh);
6118 pr_warn("Failed to read block bitmap\n");
6123 i = mb_find_next_zero_bit(bitmap_bh->b_data, max,
6127 if (ext4_fc_replay_check_excluded(sb,
6128 ext4_group_first_block_no(sb, group) +
6129 EXT4_C2B(sbi, i))) {
6138 if (++group >= ext4_get_groups_count(sb))
6149 block = ext4_group_first_block_no(sb, group) + EXT4_C2B(sbi, i);
6150 ext4_mb_mark_bb(sb, block, 1, 1);
6157 * Main entry point into mballoc to allocate blocks
6158 * it tries to use preallocation first, then falls back
6159 * to usual allocation
6161 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
6162 struct ext4_allocation_request *ar, int *errp)
6164 struct ext4_allocation_context *ac = NULL;
6165 struct ext4_sb_info *sbi;
6166 struct super_block *sb;
6167 ext4_fsblk_t block = 0;
6168 unsigned int inquota = 0;
6169 unsigned int reserv_clstrs = 0;
6174 sb = ar->inode->i_sb;
6177 trace_ext4_request_blocks(ar);
6178 if (sbi->s_mount_state & EXT4_FC_REPLAY)
6179 return ext4_mb_new_blocks_simple(ar, errp);
6181 /* Allow to use superuser reservation for quota file */
6182 if (ext4_is_quota_file(ar->inode))
6183 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
6185 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
6186 /* Without delayed allocation we need to verify
6187 * there is enough free blocks to do block allocation
6188 * and verify allocation doesn't exceed the quota limits.
6191 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
6193 /* let others to free the space */
6195 ar->len = ar->len >> 1;
6198 ext4_mb_show_pa(sb);
6202 reserv_clstrs = ar->len;
6203 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
6204 dquot_alloc_block_nofail(ar->inode,
6205 EXT4_C2B(sbi, ar->len));
6208 dquot_alloc_block(ar->inode,
6209 EXT4_C2B(sbi, ar->len))) {
6211 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
6222 ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
6229 ext4_mb_initialize_context(ac, ar);
6231 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
6232 seq = this_cpu_read(discard_pa_seq);
6233 if (!ext4_mb_use_preallocated(ac)) {
6234 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
6235 ext4_mb_normalize_request(ac, ar);
6237 *errp = ext4_mb_pa_alloc(ac);
6241 /* allocate space in core */
6242 *errp = ext4_mb_regular_allocator(ac);
6244 * pa allocated above is added to grp->bb_prealloc_list only
6245 * when we were able to allocate some block i.e. when
6246 * ac->ac_status == AC_STATUS_FOUND.
6247 * And error from above mean ac->ac_status != AC_STATUS_FOUND
6248 * So we have to free this pa here itself.
6251 ext4_mb_pa_put_free(ac);
6252 ext4_discard_allocated_blocks(ac);
6255 if (ac->ac_status == AC_STATUS_FOUND &&
6256 ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
6257 ext4_mb_pa_put_free(ac);
6259 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
6260 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
6262 ext4_discard_allocated_blocks(ac);
6265 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
6266 ar->len = ac->ac_b_ex.fe_len;
6269 if (++retries < 3 &&
6270 ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
6273 * If block allocation fails then the pa allocated above
6274 * needs to be freed here itself.
6276 ext4_mb_pa_put_free(ac);
6282 ac->ac_b_ex.fe_len = 0;
6284 ext4_mb_show_ac(ac);
6286 ext4_mb_release_context(ac);
6287 kmem_cache_free(ext4_ac_cachep, ac);
6289 if (inquota && ar->len < inquota)
6290 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
6292 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
6293 /* release all the reserved blocks if non delalloc */
6294 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
6298 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
6304 * We can merge two free data extents only if the physical blocks
6305 * are contiguous, AND the extents were freed by the same transaction,
6306 * AND the blocks are associated with the same group.
6308 static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
6309 struct ext4_free_data *entry,
6310 struct ext4_free_data *new_entry,
6311 struct rb_root *entry_rb_root)
6313 if ((entry->efd_tid != new_entry->efd_tid) ||
6314 (entry->efd_group != new_entry->efd_group))
6316 if (entry->efd_start_cluster + entry->efd_count ==
6317 new_entry->efd_start_cluster) {
6318 new_entry->efd_start_cluster = entry->efd_start_cluster;
6319 new_entry->efd_count += entry->efd_count;
6320 } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
6321 entry->efd_start_cluster) {
6322 new_entry->efd_count += entry->efd_count;
6325 spin_lock(&sbi->s_md_lock);
6326 list_del(&entry->efd_list);
6327 spin_unlock(&sbi->s_md_lock);
6328 rb_erase(&entry->efd_node, entry_rb_root);
6329 kmem_cache_free(ext4_free_data_cachep, entry);
6332 static noinline_for_stack void
6333 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
6334 struct ext4_free_data *new_entry)
6336 ext4_group_t group = e4b->bd_group;
6337 ext4_grpblk_t cluster;
6338 ext4_grpblk_t clusters = new_entry->efd_count;
6339 struct ext4_free_data *entry;
6340 struct ext4_group_info *db = e4b->bd_info;
6341 struct super_block *sb = e4b->bd_sb;
6342 struct ext4_sb_info *sbi = EXT4_SB(sb);
6343 struct rb_node **n = &db->bb_free_root.rb_node, *node;
6344 struct rb_node *parent = NULL, *new_node;
6346 BUG_ON(!ext4_handle_valid(handle));
6347 BUG_ON(e4b->bd_bitmap_page == NULL);
6348 BUG_ON(e4b->bd_buddy_page == NULL);
6350 new_node = &new_entry->efd_node;
6351 cluster = new_entry->efd_start_cluster;
6354 /* first free block exent. We need to
6355 protect buddy cache from being freed,
6356 * otherwise we'll refresh it from
6357 * on-disk bitmap and lose not-yet-available
6359 get_page(e4b->bd_buddy_page);
6360 get_page(e4b->bd_bitmap_page);
6364 entry = rb_entry(parent, struct ext4_free_data, efd_node);
6365 if (cluster < entry->efd_start_cluster)
6367 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
6368 n = &(*n)->rb_right;
6370 ext4_grp_locked_error(sb, group, 0,
6371 ext4_group_first_block_no(sb, group) +
6372 EXT4_C2B(sbi, cluster),
6373 "Block already on to-be-freed list");
6374 kmem_cache_free(ext4_free_data_cachep, new_entry);
6379 rb_link_node(new_node, parent, n);
6380 rb_insert_color(new_node, &db->bb_free_root);
6382 /* Now try to see the extent can be merged to left and right */
6383 node = rb_prev(new_node);
6385 entry = rb_entry(node, struct ext4_free_data, efd_node);
6386 ext4_try_merge_freed_extent(sbi, entry, new_entry,
6387 &(db->bb_free_root));
6390 node = rb_next(new_node);
6392 entry = rb_entry(node, struct ext4_free_data, efd_node);
6393 ext4_try_merge_freed_extent(sbi, entry, new_entry,
6394 &(db->bb_free_root));
6397 spin_lock(&sbi->s_md_lock);
6398 list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
6399 sbi->s_mb_free_pending += clusters;
6400 spin_unlock(&sbi->s_md_lock);
6403 static void ext4_free_blocks_simple(struct inode *inode, ext4_fsblk_t block,
6404 unsigned long count)
6406 struct buffer_head *bitmap_bh;
6407 struct super_block *sb = inode->i_sb;
6408 struct ext4_group_desc *gdp;
6409 struct buffer_head *gdp_bh;
6411 ext4_grpblk_t blkoff;
6412 int already_freed = 0, err, i;
6414 ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
6415 bitmap_bh = ext4_read_block_bitmap(sb, group);
6416 if (IS_ERR(bitmap_bh)) {
6417 pr_warn("Failed to read block bitmap\n");
6420 gdp = ext4_get_group_desc(sb, group, &gdp_bh);
6424 for (i = 0; i < count; i++) {
6425 if (!mb_test_bit(blkoff + i, bitmap_bh->b_data))
6428 mb_clear_bits(bitmap_bh->b_data, blkoff, count);
6429 err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
6432 ext4_free_group_clusters_set(
6433 sb, gdp, ext4_free_group_clusters(sb, gdp) +
6434 count - already_freed);
6435 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
6436 ext4_group_desc_csum_set(sb, group, gdp);
6437 ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
6438 sync_dirty_buffer(bitmap_bh);
6439 sync_dirty_buffer(gdp_bh);
6446 * ext4_mb_clear_bb() -- helper function for freeing blocks.
6447 * Used by ext4_free_blocks()
6448 * @handle: handle for this transaction
6450 * @block: starting physical block to be freed
6451 * @count: number of blocks to be freed
6452 * @flags: flags used by ext4_free_blocks
6454 static void ext4_mb_clear_bb(handle_t *handle, struct inode *inode,
6455 ext4_fsblk_t block, unsigned long count,
6458 struct buffer_head *bitmap_bh = NULL;
6459 struct super_block *sb = inode->i_sb;
6460 struct ext4_group_desc *gdp;
6461 struct ext4_group_info *grp;
6462 unsigned int overflow;
6464 struct buffer_head *gd_bh;
6465 ext4_group_t block_group;
6466 struct ext4_sb_info *sbi;
6467 struct ext4_buddy e4b;
6468 unsigned int count_clusters;
6474 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6475 !ext4_inode_block_valid(inode, block, count)) {
6476 ext4_error(sb, "Freeing blocks in system zone - "
6477 "Block = %llu, count = %lu", block, count);
6478 /* err = 0. ext4_std_error should be a no op */
6481 flags |= EXT4_FREE_BLOCKS_VALIDATED;
6485 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
6487 grp = ext4_get_group_info(sb, block_group);
6488 if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
6492 * Check to see if we are freeing blocks across a group
6495 if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
6496 overflow = EXT4_C2B(sbi, bit) + count -
6497 EXT4_BLOCKS_PER_GROUP(sb);
6499 /* The range changed so it's no longer validated */
6500 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6502 count_clusters = EXT4_NUM_B2C(sbi, count);
6503 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
6504 if (IS_ERR(bitmap_bh)) {
6505 err = PTR_ERR(bitmap_bh);
6509 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
6515 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6516 !ext4_inode_block_valid(inode, block, count)) {
6517 ext4_error(sb, "Freeing blocks in system zone - "
6518 "Block = %llu, count = %lu", block, count);
6519 /* err = 0. ext4_std_error should be a no op */
6523 BUFFER_TRACE(bitmap_bh, "getting write access");
6524 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
6530 * We are about to modify some metadata. Call the journal APIs
6531 * to unshare ->b_data if a currently-committing transaction is
6534 BUFFER_TRACE(gd_bh, "get_write_access");
6535 err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
6538 #ifdef AGGRESSIVE_CHECK
6541 for (i = 0; i < count_clusters; i++)
6542 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
6545 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
6547 /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
6548 err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
6549 GFP_NOFS|__GFP_NOFAIL);
6554 * We need to make sure we don't reuse the freed block until after the
6555 * transaction is committed. We make an exception if the inode is to be
6556 * written in writeback mode since writeback mode has weak data
6557 * consistency guarantees.
6559 if (ext4_handle_valid(handle) &&
6560 ((flags & EXT4_FREE_BLOCKS_METADATA) ||
6561 !ext4_should_writeback_data(inode))) {
6562 struct ext4_free_data *new_entry;
6564 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
6567 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
6568 GFP_NOFS|__GFP_NOFAIL);
6569 new_entry->efd_start_cluster = bit;
6570 new_entry->efd_group = block_group;
6571 new_entry->efd_count = count_clusters;
6572 new_entry->efd_tid = handle->h_transaction->t_tid;
6574 ext4_lock_group(sb, block_group);
6575 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
6576 ext4_mb_free_metadata(handle, &e4b, new_entry);
6578 /* need to update group_info->bb_free and bitmap
6579 * with group lock held. generate_buddy look at
6580 * them with group lock_held
6582 if (test_opt(sb, DISCARD)) {
6583 err = ext4_issue_discard(sb, block_group, bit,
6584 count_clusters, NULL);
6585 if (err && err != -EOPNOTSUPP)
6586 ext4_msg(sb, KERN_WARNING, "discard request in"
6587 " group:%u block:%d count:%lu failed"
6588 " with %d", block_group, bit, count,
6591 EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
6593 ext4_lock_group(sb, block_group);
6594 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
6595 mb_free_blocks(inode, &e4b, bit, count_clusters);
6598 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
6599 ext4_free_group_clusters_set(sb, gdp, ret);
6600 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
6601 ext4_group_desc_csum_set(sb, block_group, gdp);
6602 ext4_unlock_group(sb, block_group);
6604 if (sbi->s_log_groups_per_flex) {
6605 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
6606 atomic64_add(count_clusters,
6607 &sbi_array_rcu_deref(sbi, s_flex_groups,
6608 flex_group)->free_clusters);
6612 * on a bigalloc file system, defer the s_freeclusters_counter
6613 * update to the caller (ext4_remove_space and friends) so they
6614 * can determine if a cluster freed here should be rereserved
6616 if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
6617 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
6618 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
6619 percpu_counter_add(&sbi->s_freeclusters_counter,
6623 ext4_mb_unload_buddy(&e4b);
6625 /* We dirtied the bitmap block */
6626 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
6627 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
6629 /* And the group descriptor block */
6630 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
6631 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
6635 if (overflow && !err) {
6639 /* The range changed so it's no longer validated */
6640 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6645 ext4_std_error(sb, err);
6650 * ext4_free_blocks() -- Free given blocks and update quota
6651 * @handle: handle for this transaction
6653 * @bh: optional buffer of the block to be freed
6654 * @block: starting physical block to be freed
6655 * @count: number of blocks to be freed
6656 * @flags: flags used by ext4_free_blocks
6658 void ext4_free_blocks(handle_t *handle, struct inode *inode,
6659 struct buffer_head *bh, ext4_fsblk_t block,
6660 unsigned long count, int flags)
6662 struct super_block *sb = inode->i_sb;
6663 unsigned int overflow;
6664 struct ext4_sb_info *sbi;
6670 BUG_ON(block != bh->b_blocknr);
6672 block = bh->b_blocknr;
6675 if (sbi->s_mount_state & EXT4_FC_REPLAY) {
6676 ext4_free_blocks_simple(inode, block, EXT4_NUM_B2C(sbi, count));
6682 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6683 !ext4_inode_block_valid(inode, block, count)) {
6684 ext4_error(sb, "Freeing blocks not in datazone - "
6685 "block = %llu, count = %lu", block, count);
6688 flags |= EXT4_FREE_BLOCKS_VALIDATED;
6690 ext4_debug("freeing block %llu\n", block);
6691 trace_ext4_free_blocks(inode, block, count, flags);
6693 if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
6696 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
6701 * If the extent to be freed does not begin on a cluster
6702 * boundary, we need to deal with partial clusters at the
6703 * beginning and end of the extent. Normally we will free
6704 * blocks at the beginning or the end unless we are explicitly
6705 * requested to avoid doing so.
6707 overflow = EXT4_PBLK_COFF(sbi, block);
6709 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
6710 overflow = sbi->s_cluster_ratio - overflow;
6712 if (count > overflow)
6720 /* The range changed so it's no longer validated */
6721 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6723 overflow = EXT4_LBLK_COFF(sbi, count);
6725 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
6726 if (count > overflow)
6731 count += sbi->s_cluster_ratio - overflow;
6732 /* The range changed so it's no longer validated */
6733 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6736 if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
6738 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
6740 for (i = 0; i < count; i++) {
6743 bh = sb_find_get_block(inode->i_sb, block + i);
6744 ext4_forget(handle, is_metadata, inode, bh, block + i);
6748 ext4_mb_clear_bb(handle, inode, block, count, flags);
6753 * ext4_group_add_blocks() -- Add given blocks to an existing group
6754 * @handle: handle to this transaction
6756 * @block: start physical block to add to the block group
6757 * @count: number of blocks to free
6759 * This marks the blocks as free in the bitmap and buddy.
6761 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
6762 ext4_fsblk_t block, unsigned long count)
6764 struct buffer_head *bitmap_bh = NULL;
6765 struct buffer_head *gd_bh;
6766 ext4_group_t block_group;
6769 struct ext4_group_desc *desc;
6770 struct ext4_sb_info *sbi = EXT4_SB(sb);
6771 struct ext4_buddy e4b;
6772 int err = 0, ret, free_clusters_count;
6773 ext4_grpblk_t clusters_freed;
6774 ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
6775 ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
6776 unsigned long cluster_count = last_cluster - first_cluster + 1;
6778 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
6783 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
6785 * Check to see if we are freeing blocks across a group
6788 if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
6789 ext4_warning(sb, "too many blocks added to group %u",
6795 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
6796 if (IS_ERR(bitmap_bh)) {
6797 err = PTR_ERR(bitmap_bh);
6802 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
6808 if (!ext4_sb_block_valid(sb, NULL, block, count)) {
6809 ext4_error(sb, "Adding blocks in system zones - "
6810 "Block = %llu, count = %lu",
6816 BUFFER_TRACE(bitmap_bh, "getting write access");
6817 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
6823 * We are about to modify some metadata. Call the journal APIs
6824 * to unshare ->b_data if a currently-committing transaction is
6827 BUFFER_TRACE(gd_bh, "get_write_access");
6828 err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
6832 for (i = 0, clusters_freed = 0; i < cluster_count; i++) {
6833 BUFFER_TRACE(bitmap_bh, "clear bit");
6834 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
6835 ext4_error(sb, "bit already cleared for block %llu",
6836 (ext4_fsblk_t)(block + i));
6837 BUFFER_TRACE(bitmap_bh, "bit already cleared");
6843 err = ext4_mb_load_buddy(sb, block_group, &e4b);
6848 * need to update group_info->bb_free and bitmap
6849 * with group lock held. generate_buddy look at
6850 * them with group lock_held
6852 ext4_lock_group(sb, block_group);
6853 mb_clear_bits(bitmap_bh->b_data, bit, cluster_count);
6854 mb_free_blocks(NULL, &e4b, bit, cluster_count);
6855 free_clusters_count = clusters_freed +
6856 ext4_free_group_clusters(sb, desc);
6857 ext4_free_group_clusters_set(sb, desc, free_clusters_count);
6858 ext4_block_bitmap_csum_set(sb, desc, bitmap_bh);
6859 ext4_group_desc_csum_set(sb, block_group, desc);
6860 ext4_unlock_group(sb, block_group);
6861 percpu_counter_add(&sbi->s_freeclusters_counter,
6864 if (sbi->s_log_groups_per_flex) {
6865 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
6866 atomic64_add(clusters_freed,
6867 &sbi_array_rcu_deref(sbi, s_flex_groups,
6868 flex_group)->free_clusters);
6871 ext4_mb_unload_buddy(&e4b);
6873 /* We dirtied the bitmap block */
6874 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
6875 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
6877 /* And the group descriptor block */
6878 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
6879 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
6885 ext4_std_error(sb, err);
6890 * ext4_trim_extent -- function to TRIM one single free extent in the group
6891 * @sb: super block for the file system
6892 * @start: starting block of the free extent in the alloc. group
6893 * @count: number of blocks to TRIM
6894 * @e4b: ext4 buddy for the group
6896 * Trim "count" blocks starting at "start" in the "group". To assure that no
6897 * one will allocate those blocks, mark it as used in buddy bitmap. This must
6898 * be called with under the group lock.
6900 static int ext4_trim_extent(struct super_block *sb,
6901 int start, int count, struct ext4_buddy *e4b)
6905 struct ext4_free_extent ex;
6906 ext4_group_t group = e4b->bd_group;
6909 trace_ext4_trim_extent(sb, group, start, count);
6911 assert_spin_locked(ext4_group_lock_ptr(sb, group));
6913 ex.fe_start = start;
6914 ex.fe_group = group;
6918 * Mark blocks used, so no one can reuse them while
6921 mb_mark_used(e4b, &ex);
6922 ext4_unlock_group(sb, group);
6923 ret = ext4_issue_discard(sb, group, start, count, NULL);
6924 ext4_lock_group(sb, group);
6925 mb_free_blocks(NULL, e4b, start, ex.fe_len);
6929 static int ext4_try_to_trim_range(struct super_block *sb,
6930 struct ext4_buddy *e4b, ext4_grpblk_t start,
6931 ext4_grpblk_t max, ext4_grpblk_t minblocks)
6932 __acquires(ext4_group_lock_ptr(sb, e4b->bd_group))
6933 __releases(ext4_group_lock_ptr(sb, e4b->bd_group))
6935 ext4_grpblk_t next, count, free_count;
6938 bitmap = e4b->bd_bitmap;
6939 start = (e4b->bd_info->bb_first_free > start) ?
6940 e4b->bd_info->bb_first_free : start;
6944 while (start <= max) {
6945 start = mb_find_next_zero_bit(bitmap, max + 1, start);
6948 next = mb_find_next_bit(bitmap, max + 1, start);
6950 if ((next - start) >= minblocks) {
6951 int ret = ext4_trim_extent(sb, start, next - start, e4b);
6953 if (ret && ret != -EOPNOTSUPP)
6955 count += next - start;
6957 free_count += next - start;
6960 if (fatal_signal_pending(current)) {
6961 count = -ERESTARTSYS;
6965 if (need_resched()) {
6966 ext4_unlock_group(sb, e4b->bd_group);
6968 ext4_lock_group(sb, e4b->bd_group);
6971 if ((e4b->bd_info->bb_free - free_count) < minblocks)
6979 * ext4_trim_all_free -- function to trim all free space in alloc. group
6980 * @sb: super block for file system
6981 * @group: group to be trimmed
6982 * @start: first group block to examine
6983 * @max: last group block to examine
6984 * @minblocks: minimum extent block count
6985 * @set_trimmed: set the trimmed flag if at least one block is trimmed
6987 * ext4_trim_all_free walks through group's block bitmap searching for free
6988 * extents. When the free extent is found, mark it as used in group buddy
6989 * bitmap. Then issue a TRIM command on this extent and free the extent in
6990 * the group buddy bitmap.
6992 static ext4_grpblk_t
6993 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
6994 ext4_grpblk_t start, ext4_grpblk_t max,
6995 ext4_grpblk_t minblocks, bool set_trimmed)
6997 struct ext4_buddy e4b;
7000 trace_ext4_trim_all_free(sb, group, start, max);
7002 ret = ext4_mb_load_buddy(sb, group, &e4b);
7004 ext4_warning(sb, "Error %d loading buddy information for %u",
7009 ext4_lock_group(sb, group);
7011 if (!EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) ||
7012 minblocks < EXT4_SB(sb)->s_last_trim_minblks) {
7013 ret = ext4_try_to_trim_range(sb, &e4b, start, max, minblocks);
7014 if (ret >= 0 && set_trimmed)
7015 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
7020 ext4_unlock_group(sb, group);
7021 ext4_mb_unload_buddy(&e4b);
7023 ext4_debug("trimmed %d blocks in the group %d\n",
7030 * ext4_trim_fs() -- trim ioctl handle function
7031 * @sb: superblock for filesystem
7032 * @range: fstrim_range structure
7034 * start: First Byte to trim
7035 * len: number of Bytes to trim from start
7036 * minlen: minimum extent length in Bytes
7037 * ext4_trim_fs goes through all allocation groups containing Bytes from
7038 * start to start+len. For each such a group ext4_trim_all_free function
7039 * is invoked to trim all free space.
7041 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
7043 unsigned int discard_granularity = bdev_discard_granularity(sb->s_bdev);
7044 struct ext4_group_info *grp;
7045 ext4_group_t group, first_group, last_group;
7046 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
7047 uint64_t start, end, minlen, trimmed = 0;
7048 ext4_fsblk_t first_data_blk =
7049 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
7050 ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
7051 bool whole_group, eof = false;
7054 start = range->start >> sb->s_blocksize_bits;
7055 end = start + (range->len >> sb->s_blocksize_bits) - 1;
7056 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
7057 range->minlen >> sb->s_blocksize_bits);
7059 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
7060 start >= max_blks ||
7061 range->len < sb->s_blocksize)
7063 /* No point to try to trim less than discard granularity */
7064 if (range->minlen < discard_granularity) {
7065 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
7066 discard_granularity >> sb->s_blocksize_bits);
7067 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
7070 if (end >= max_blks - 1) {
7074 if (end <= first_data_blk)
7076 if (start < first_data_blk)
7077 start = first_data_blk;
7079 /* Determine first and last group to examine based on start and end */
7080 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
7081 &first_group, &first_cluster);
7082 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
7083 &last_group, &last_cluster);
7085 /* end now represents the last cluster to discard in this group */
7086 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
7089 for (group = first_group; group <= last_group; group++) {
7090 grp = ext4_get_group_info(sb, group);
7093 /* We only do this if the grp has never been initialized */
7094 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
7095 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
7101 * For all the groups except the last one, last cluster will
7102 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
7103 * change it for the last group, note that last_cluster is
7104 * already computed earlier by ext4_get_group_no_and_offset()
7106 if (group == last_group) {
7108 whole_group = eof ? true : end == EXT4_CLUSTERS_PER_GROUP(sb) - 1;
7110 if (grp->bb_free >= minlen) {
7111 cnt = ext4_trim_all_free(sb, group, first_cluster,
7112 end, minlen, whole_group);
7121 * For every group except the first one, we are sure
7122 * that the first cluster to discard will be cluster #0.
7128 EXT4_SB(sb)->s_last_trim_minblks = minlen;
7131 range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
7135 /* Iterate all the free extents in the group. */
7137 ext4_mballoc_query_range(
7138 struct super_block *sb,
7140 ext4_grpblk_t start,
7142 ext4_mballoc_query_range_fn formatter,
7147 struct ext4_buddy e4b;
7150 error = ext4_mb_load_buddy(sb, group, &e4b);
7153 bitmap = e4b.bd_bitmap;
7155 ext4_lock_group(sb, group);
7157 start = (e4b.bd_info->bb_first_free > start) ?
7158 e4b.bd_info->bb_first_free : start;
7159 if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
7160 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
7162 while (start <= end) {
7163 start = mb_find_next_zero_bit(bitmap, end + 1, start);
7166 next = mb_find_next_bit(bitmap, end + 1, start);
7168 ext4_unlock_group(sb, group);
7169 error = formatter(sb, group, start, next - start, priv);
7172 ext4_lock_group(sb, group);
7177 ext4_unlock_group(sb, group);
7179 ext4_mb_unload_buddy(&e4b);