1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
4 * Written by Alex Tomas <alex@clusterfs.com>
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 <linux/freezer.h>
20 #include <trace/events/ext4.h>
24 * - test ext4_ext_search_left() and ext4_ext_search_right()
25 * - search for metadata in few groups
28 * - normalization should take into account whether file is still open
29 * - discard preallocations if no free space left (policy?)
30 * - don't normalize tails
32 * - reservation for superuser
35 * - bitmap read-ahead (proposed by Oleg Drokin aka green)
36 * - track min/max extents in each group for better group selection
37 * - mb_mark_used() may allocate chunk right after splitting buddy
38 * - tree of groups sorted by number of free blocks
43 * The allocation request involve request for multiple number of blocks
44 * near to the goal(block) value specified.
46 * During initialization phase of the allocator we decide to use the
47 * group preallocation or inode preallocation depending on the size of
48 * the file. The size of the file could be the resulting file size we
49 * would have after allocation, or the current file size, which ever
50 * is larger. If the size is less than sbi->s_mb_stream_request we
51 * select to use the group preallocation. The default value of
52 * s_mb_stream_request is 16 blocks. This can also be tuned via
53 * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
54 * terms of number of blocks.
56 * The main motivation for having small file use group preallocation is to
57 * ensure that we have small files closer together on the disk.
59 * First stage the allocator looks at the inode prealloc list,
60 * ext4_inode_info->i_prealloc_list, which contains list of prealloc
61 * spaces for this particular inode. The inode prealloc space is
64 * pa_lstart -> the logical start block for this prealloc space
65 * pa_pstart -> the physical start block for this prealloc space
66 * pa_len -> length for this prealloc space (in clusters)
67 * pa_free -> free space available in this prealloc space (in clusters)
69 * The inode preallocation space is used looking at the _logical_ start
70 * block. If only the logical file block falls within the range of prealloc
71 * space we will consume the particular prealloc space. This makes sure that
72 * we have contiguous physical blocks representing the file blocks
74 * The important thing to be noted in case of inode prealloc space is that
75 * we don't modify the values associated to inode prealloc space except
78 * If we are not able to find blocks in the inode prealloc space and if we
79 * have the group allocation flag set then we look at the locality group
80 * prealloc space. These are per CPU prealloc list represented as
82 * ext4_sb_info.s_locality_groups[smp_processor_id()]
84 * The reason for having a per cpu locality group is to reduce the contention
85 * between CPUs. It is possible to get scheduled at this point.
87 * The locality group prealloc space is used looking at whether we have
88 * enough free space (pa_free) within the prealloc space.
90 * If we can't allocate blocks via inode prealloc or/and locality group
91 * prealloc then we look at the buddy cache. The buddy cache is represented
92 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
93 * mapped to the buddy and bitmap information regarding different
94 * groups. The buddy information is attached to buddy cache inode so that
95 * we can access them through the page cache. The information regarding
96 * each group is loaded via ext4_mb_load_buddy. The information involve
97 * block bitmap and buddy information. The information are stored in the
101 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
104 * one block each for bitmap and buddy information. So for each group we
105 * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
106 * blocksize) blocks. So it can have information regarding groups_per_page
107 * which is blocks_per_page/2
109 * The buddy cache inode is not stored on disk. The inode is thrown
110 * away when the filesystem is unmounted.
112 * We look for count number of blocks in the buddy cache. If we were able
113 * to locate that many free blocks we return with additional information
114 * regarding rest of the contiguous physical block available
116 * Before allocating blocks via buddy cache we normalize the request
117 * blocks. This ensure we ask for more blocks that we needed. The extra
118 * blocks that we get after allocation is added to the respective prealloc
119 * list. In case of inode preallocation we follow a list of heuristics
120 * based on file size. This can be found in ext4_mb_normalize_request. If
121 * we are doing a group prealloc we try to normalize the request to
122 * sbi->s_mb_group_prealloc. The default value of s_mb_group_prealloc is
123 * dependent on the cluster size; for non-bigalloc file systems, it is
124 * 512 blocks. This can be tuned via
125 * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
126 * terms of number of blocks. If we have mounted the file system with -O
127 * stripe=<value> option the group prealloc request is normalized to the
128 * smallest multiple of the stripe value (sbi->s_stripe) which is
129 * greater than the default mb_group_prealloc.
131 * If "mb_optimize_scan" mount option is set, we maintain in memory group info
132 * structures in two data structures:
134 * 1) Array of largest free order lists (sbi->s_mb_largest_free_orders)
136 * Locking: sbi->s_mb_largest_free_orders_locks(array of rw locks)
138 * This is an array of lists where the index in the array represents the
139 * largest free order in the buddy bitmap of the participating group infos of
140 * that list. So, there are exactly MB_NUM_ORDERS(sb) (which means total
141 * number of buddy bitmap orders possible) number of lists. Group-infos are
142 * placed in appropriate lists.
144 * 2) Average fragment size lists (sbi->s_mb_avg_fragment_size)
146 * Locking: sbi->s_mb_avg_fragment_size_locks(array of rw locks)
148 * This is an array of lists where in the i-th list there are groups with
149 * average fragment size >= 2^i and < 2^(i+1). The average fragment size
150 * is computed as ext4_group_info->bb_free / ext4_group_info->bb_fragments.
151 * Note that we don't bother with a special list for completely empty groups
152 * so we only have MB_NUM_ORDERS(sb) lists.
154 * When "mb_optimize_scan" mount option is set, mballoc consults the above data
155 * structures to decide the order in which groups are to be traversed for
156 * fulfilling an allocation request.
158 * At CR_POWER2_ALIGNED , we look for groups which have the largest_free_order
159 * >= the order of the request. We directly look at the largest free order list
160 * in the data structure (1) above where largest_free_order = order of the
161 * request. If that list is empty, we look at remaining list in the increasing
162 * order of largest_free_order. This allows us to perform CR_POWER2_ALIGNED
163 * lookup in O(1) time.
165 * At CR_GOAL_LEN_FAST, we only consider groups where
166 * average fragment size > request size. So, we lookup a group which has average
167 * fragment size just above or equal to request size using our average fragment
168 * size group lists (data structure 2) in O(1) time.
170 * At CR_BEST_AVAIL_LEN, we aim to optimize allocations which can't be satisfied
171 * in CR_GOAL_LEN_FAST. The fact that we couldn't find a group in
172 * CR_GOAL_LEN_FAST suggests that there is no BG that has avg
173 * fragment size > goal length. So before falling to the slower
174 * CR_GOAL_LEN_SLOW, in CR_BEST_AVAIL_LEN we proactively trim goal length and
175 * then use the same fragment lists as CR_GOAL_LEN_FAST to find a BG with a big
176 * enough average fragment size. This increases the chances of finding a
177 * suitable block group in O(1) time and results in faster allocation at the
178 * cost of reduced size of allocation.
180 * If "mb_optimize_scan" mount option is not set, mballoc traverses groups in
181 * linear order which requires O(N) search time for each CR_POWER2_ALIGNED and
182 * CR_GOAL_LEN_FAST phase.
184 * The regular allocator (using the buddy cache) supports a few tunables.
186 * /sys/fs/ext4/<partition>/mb_min_to_scan
187 * /sys/fs/ext4/<partition>/mb_max_to_scan
188 * /sys/fs/ext4/<partition>/mb_order2_req
189 * /sys/fs/ext4/<partition>/mb_linear_limit
191 * The regular allocator uses buddy scan only if the request len is power of
192 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
193 * value of s_mb_order2_reqs can be tuned via
194 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
195 * stripe size (sbi->s_stripe), we try to search for contiguous block in
196 * stripe size. This should result in better allocation on RAID setups. If
197 * not, we search in the specific group using bitmap for best extents. The
198 * tunable min_to_scan and max_to_scan control the behaviour here.
199 * min_to_scan indicate how long the mballoc __must__ look for a best
200 * extent and max_to_scan indicates how long the mballoc __can__ look for a
201 * best extent in the found extents. Searching for the blocks starts with
202 * the group specified as the goal value in allocation context via
203 * ac_g_ex. Each group is first checked based on the criteria whether it
204 * can be used for allocation. ext4_mb_good_group explains how the groups are
207 * When "mb_optimize_scan" is turned on, as mentioned above, the groups may not
208 * get traversed linearly. That may result in subsequent allocations being not
209 * close to each other. And so, the underlying device may get filled up in a
210 * non-linear fashion. While that may not matter on non-rotational devices, for
211 * rotational devices that may result in higher seek times. "mb_linear_limit"
212 * tells mballoc how many groups mballoc should search linearly before
213 * performing consulting above data structures for more efficient lookups. For
214 * non rotational devices, this value defaults to 0 and for rotational devices
215 * this is set to MB_DEFAULT_LINEAR_LIMIT.
217 * Both the prealloc space are getting populated as above. So for the first
218 * request we will hit the buddy cache which will result in this prealloc
219 * space getting filled. The prealloc space is then later used for the
220 * subsequent request.
224 * mballoc operates on the following data:
226 * - in-core buddy (actually includes buddy and bitmap)
227 * - preallocation descriptors (PAs)
229 * there are two types of preallocations:
231 * assiged to specific inode and can be used for this inode only.
232 * it describes part of inode's space preallocated to specific
233 * physical blocks. any block from that preallocated can be used
234 * independent. the descriptor just tracks number of blocks left
235 * unused. so, before taking some block from descriptor, one must
236 * make sure corresponded logical block isn't allocated yet. this
237 * also means that freeing any block within descriptor's range
238 * must discard all preallocated blocks.
240 * assigned to specific locality group which does not translate to
241 * permanent set of inodes: inode can join and leave group. space
242 * from this type of preallocation can be used for any inode. thus
243 * it's consumed from the beginning to the end.
245 * relation between them can be expressed as:
246 * in-core buddy = on-disk bitmap + preallocation descriptors
248 * this mean blocks mballoc considers used are:
249 * - allocated blocks (persistent)
250 * - preallocated blocks (non-persistent)
252 * consistency in mballoc world means that at any time a block is either
253 * free or used in ALL structures. notice: "any time" should not be read
254 * literally -- time is discrete and delimited by locks.
256 * to keep it simple, we don't use block numbers, instead we count number of
257 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
259 * all operations can be expressed as:
260 * - init buddy: buddy = on-disk + PAs
261 * - new PA: buddy += N; PA = N
262 * - use inode PA: on-disk += N; PA -= N
263 * - discard inode PA buddy -= on-disk - PA; PA = 0
264 * - use locality group PA on-disk += N; PA -= N
265 * - discard locality group PA buddy -= PA; PA = 0
266 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
267 * is used in real operation because we can't know actual used
268 * bits from PA, only from on-disk bitmap
270 * if we follow this strict logic, then all operations above should be atomic.
271 * given some of them can block, we'd have to use something like semaphores
272 * killing performance on high-end SMP hardware. let's try to relax it using
273 * the following knowledge:
274 * 1) if buddy is referenced, it's already initialized
275 * 2) while block is used in buddy and the buddy is referenced,
276 * nobody can re-allocate that block
277 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
278 * bit set and PA claims same block, it's OK. IOW, one can set bit in
279 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
282 * so, now we're building a concurrency table:
285 * blocks for PA are allocated in the buddy, buddy must be referenced
286 * until PA is linked to allocation group to avoid concurrent buddy init
288 * we need to make sure that either on-disk bitmap or PA has uptodate data
289 * given (3) we care that PA-=N operation doesn't interfere with init
291 * the simplest way would be to have buddy initialized by the discard
292 * - use locality group PA
293 * again PA-=N must be serialized with init
294 * - discard locality group PA
295 * the simplest way would be to have buddy initialized by the discard
298 * i_data_sem serializes them
300 * discard process must wait until PA isn't used by another process
301 * - use locality group PA
302 * some mutex should serialize them
303 * - discard locality group PA
304 * discard process must wait until PA isn't used by another process
307 * i_data_sem or another mutex should serializes them
309 * discard process must wait until PA isn't used by another process
310 * - use locality group PA
311 * nothing wrong here -- they're different PAs covering different blocks
312 * - discard locality group PA
313 * discard process must wait until PA isn't used by another process
315 * now we're ready to make few consequences:
316 * - PA is referenced and while it is no discard is possible
317 * - PA is referenced until block isn't marked in on-disk bitmap
318 * - PA changes only after on-disk bitmap
319 * - discard must not compete with init. either init is done before
320 * any discard or they're serialized somehow
321 * - buddy init as sum of on-disk bitmap and PAs is done atomically
323 * a special case when we've used PA to emptiness. no need to modify buddy
324 * in this case, but we should care about concurrent init
329 * Logic in few words:
334 * mark bits in on-disk bitmap
337 * - use preallocation:
338 * find proper PA (per-inode or group)
340 * mark bits in on-disk bitmap
346 * mark bits in on-disk bitmap
349 * - discard preallocations in group:
351 * move them onto local list
352 * load on-disk bitmap
354 * remove PA from object (inode or locality group)
355 * mark free blocks in-core
357 * - discard inode's preallocations:
364 * - bitlock on a group (group)
365 * - object (inode/locality) (object)
367 * - cr_power2_aligned lists lock (cr_power2_aligned)
368 * - cr_goal_len_fast lists lock (cr_goal_len_fast)
378 * - release consumed pa:
383 * - generate in-core bitmap:
387 * - discard all for given object (inode, locality group):
392 * - discard all for given group:
398 * - allocation path (ext4_mb_regular_allocator)
400 * cr_power2_aligned/cr_goal_len_fast
402 static struct kmem_cache *ext4_pspace_cachep;
403 static struct kmem_cache *ext4_ac_cachep;
404 static struct kmem_cache *ext4_free_data_cachep;
406 /* We create slab caches for groupinfo data structures based on the
407 * superblock block size. There will be one per mounted filesystem for
408 * each unique s_blocksize_bits */
409 #define NR_GRPINFO_CACHES 8
410 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
412 static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
413 "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
414 "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
415 "ext4_groupinfo_64k", "ext4_groupinfo_128k"
418 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
420 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
422 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac);
424 static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
425 ext4_group_t group, enum criteria cr);
427 static int ext4_try_to_trim_range(struct super_block *sb,
428 struct ext4_buddy *e4b, ext4_grpblk_t start,
429 ext4_grpblk_t max, ext4_grpblk_t minblocks);
432 * The algorithm using this percpu seq counter goes below:
433 * 1. We sample the percpu discard_pa_seq counter before trying for block
434 * allocation in ext4_mb_new_blocks().
435 * 2. We increment this percpu discard_pa_seq counter when we either allocate
436 * or free these blocks i.e. while marking those blocks as used/free in
437 * mb_mark_used()/mb_free_blocks().
438 * 3. We also increment this percpu seq counter when we successfully identify
439 * that the bb_prealloc_list is not empty and hence proceed for discarding
440 * of those PAs inside ext4_mb_discard_group_preallocations().
442 * Now to make sure that the regular fast path of block allocation is not
443 * affected, as a small optimization we only sample the percpu seq counter
444 * on that cpu. Only when the block allocation fails and when freed blocks
445 * found were 0, that is when we sample percpu seq counter for all cpus using
446 * below function ext4_get_discard_pa_seq_sum(). This happens after making
447 * sure that all the PAs on grp->bb_prealloc_list got freed or if it's empty.
449 static DEFINE_PER_CPU(u64, discard_pa_seq);
450 static inline u64 ext4_get_discard_pa_seq_sum(void)
455 for_each_possible_cpu(__cpu)
456 __seq += per_cpu(discard_pa_seq, __cpu);
460 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
462 #if BITS_PER_LONG == 64
463 *bit += ((unsigned long) addr & 7UL) << 3;
464 addr = (void *) ((unsigned long) addr & ~7UL);
465 #elif BITS_PER_LONG == 32
466 *bit += ((unsigned long) addr & 3UL) << 3;
467 addr = (void *) ((unsigned long) addr & ~3UL);
469 #error "how many bits you are?!"
474 static inline int mb_test_bit(int bit, void *addr)
477 * ext4_test_bit on architecture like powerpc
478 * needs unsigned long aligned address
480 addr = mb_correct_addr_and_bit(&bit, addr);
481 return ext4_test_bit(bit, addr);
484 static inline void mb_set_bit(int bit, void *addr)
486 addr = mb_correct_addr_and_bit(&bit, addr);
487 ext4_set_bit(bit, addr);
490 static inline void mb_clear_bit(int bit, void *addr)
492 addr = mb_correct_addr_and_bit(&bit, addr);
493 ext4_clear_bit(bit, addr);
496 static inline int mb_test_and_clear_bit(int bit, void *addr)
498 addr = mb_correct_addr_and_bit(&bit, addr);
499 return ext4_test_and_clear_bit(bit, addr);
502 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
504 int fix = 0, ret, tmpmax;
505 addr = mb_correct_addr_and_bit(&fix, addr);
509 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
515 static inline int mb_find_next_bit(void *addr, int max, int start)
517 int fix = 0, ret, tmpmax;
518 addr = mb_correct_addr_and_bit(&fix, addr);
522 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
528 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
532 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
535 if (order > e4b->bd_blkbits + 1) {
540 /* at order 0 we see each particular block */
542 *max = 1 << (e4b->bd_blkbits + 3);
543 return e4b->bd_bitmap;
546 bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
547 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
553 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
554 int first, int count)
557 struct super_block *sb = e4b->bd_sb;
559 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
561 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
562 for (i = 0; i < count; i++) {
563 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
564 ext4_fsblk_t blocknr;
566 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
567 blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
568 ext4_grp_locked_error(sb, e4b->bd_group,
569 inode ? inode->i_ino : 0,
571 "freeing block already freed "
574 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
575 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
577 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
581 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
585 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
587 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
588 for (i = 0; i < count; i++) {
589 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
590 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
594 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
596 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
598 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
599 unsigned char *b1, *b2;
601 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
602 b2 = (unsigned char *) bitmap;
603 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
604 if (b1[i] != b2[i]) {
605 ext4_msg(e4b->bd_sb, KERN_ERR,
606 "corruption in group %u "
607 "at byte %u(%u): %x in copy != %x "
609 e4b->bd_group, i, i * 8, b1[i], b2[i]);
616 static void mb_group_bb_bitmap_alloc(struct super_block *sb,
617 struct ext4_group_info *grp, ext4_group_t group)
619 struct buffer_head *bh;
621 grp->bb_bitmap = kmalloc(sb->s_blocksize, GFP_NOFS);
625 bh = ext4_read_block_bitmap(sb, group);
626 if (IS_ERR_OR_NULL(bh)) {
627 kfree(grp->bb_bitmap);
628 grp->bb_bitmap = NULL;
632 memcpy(grp->bb_bitmap, bh->b_data, sb->s_blocksize);
636 static void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
638 kfree(grp->bb_bitmap);
642 static inline void mb_free_blocks_double(struct inode *inode,
643 struct ext4_buddy *e4b, int first, int count)
647 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
648 int first, int count)
652 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
657 static inline void mb_group_bb_bitmap_alloc(struct super_block *sb,
658 struct ext4_group_info *grp, ext4_group_t group)
663 static inline void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
669 #ifdef AGGRESSIVE_CHECK
671 #define MB_CHECK_ASSERT(assert) \
675 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
676 function, file, line, # assert); \
681 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
682 const char *function, int line)
684 struct super_block *sb = e4b->bd_sb;
685 int order = e4b->bd_blkbits + 1;
692 struct ext4_group_info *grp;
695 struct list_head *cur;
699 if (e4b->bd_info->bb_check_counter++ % 10)
703 buddy = mb_find_buddy(e4b, order, &max);
704 MB_CHECK_ASSERT(buddy);
705 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
706 MB_CHECK_ASSERT(buddy2);
707 MB_CHECK_ASSERT(buddy != buddy2);
708 MB_CHECK_ASSERT(max * 2 == max2);
711 for (i = 0; i < max; i++) {
713 if (mb_test_bit(i, buddy)) {
714 /* only single bit in buddy2 may be 0 */
715 if (!mb_test_bit(i << 1, buddy2)) {
717 mb_test_bit((i<<1)+1, buddy2));
722 /* both bits in buddy2 must be 1 */
723 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
724 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
726 for (j = 0; j < (1 << order); j++) {
727 k = (i * (1 << order)) + j;
729 !mb_test_bit(k, e4b->bd_bitmap));
733 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
738 buddy = mb_find_buddy(e4b, 0, &max);
739 for (i = 0; i < max; i++) {
740 if (!mb_test_bit(i, buddy)) {
741 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
749 /* check used bits only */
750 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
751 buddy2 = mb_find_buddy(e4b, j, &max2);
753 MB_CHECK_ASSERT(k < max2);
754 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
757 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
758 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
760 grp = ext4_get_group_info(sb, e4b->bd_group);
763 list_for_each(cur, &grp->bb_prealloc_list) {
764 ext4_group_t groupnr;
765 struct ext4_prealloc_space *pa;
766 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
767 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
768 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
769 for (i = 0; i < pa->pa_len; i++)
770 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
774 #undef MB_CHECK_ASSERT
775 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
776 __FILE__, __func__, __LINE__)
778 #define mb_check_buddy(e4b)
782 * Divide blocks started from @first with length @len into
783 * smaller chunks with power of 2 blocks.
784 * Clear the bits in bitmap which the blocks of the chunk(s) covered,
785 * then increase bb_counters[] for corresponded chunk size.
787 static void ext4_mb_mark_free_simple(struct super_block *sb,
788 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
789 struct ext4_group_info *grp)
791 struct ext4_sb_info *sbi = EXT4_SB(sb);
797 BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
799 border = 2 << sb->s_blocksize_bits;
802 /* find how many blocks can be covered since this position */
803 max = ffs(first | border) - 1;
805 /* find how many blocks of power 2 we need to mark */
812 /* mark multiblock chunks only */
813 grp->bb_counters[min]++;
815 mb_clear_bit(first >> min,
816 buddy + sbi->s_mb_offsets[min]);
823 static int mb_avg_fragment_size_order(struct super_block *sb, ext4_grpblk_t len)
828 * We don't bother with a special lists groups with only 1 block free
829 * extents and for completely empty groups.
831 order = fls(len) - 2;
834 if (order == MB_NUM_ORDERS(sb))
839 /* Move group to appropriate avg_fragment_size list */
841 mb_update_avg_fragment_size(struct super_block *sb, struct ext4_group_info *grp)
843 struct ext4_sb_info *sbi = EXT4_SB(sb);
846 if (!test_opt2(sb, MB_OPTIMIZE_SCAN) || grp->bb_free == 0)
849 new_order = mb_avg_fragment_size_order(sb,
850 grp->bb_free / grp->bb_fragments);
851 if (new_order == grp->bb_avg_fragment_size_order)
854 if (grp->bb_avg_fragment_size_order != -1) {
855 write_lock(&sbi->s_mb_avg_fragment_size_locks[
856 grp->bb_avg_fragment_size_order]);
857 list_del(&grp->bb_avg_fragment_size_node);
858 write_unlock(&sbi->s_mb_avg_fragment_size_locks[
859 grp->bb_avg_fragment_size_order]);
861 grp->bb_avg_fragment_size_order = new_order;
862 write_lock(&sbi->s_mb_avg_fragment_size_locks[
863 grp->bb_avg_fragment_size_order]);
864 list_add_tail(&grp->bb_avg_fragment_size_node,
865 &sbi->s_mb_avg_fragment_size[grp->bb_avg_fragment_size_order]);
866 write_unlock(&sbi->s_mb_avg_fragment_size_locks[
867 grp->bb_avg_fragment_size_order]);
871 * Choose next group by traversing largest_free_order lists. Updates *new_cr if
872 * cr level needs an update.
874 static void ext4_mb_choose_next_group_p2_aligned(struct ext4_allocation_context *ac,
875 enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
877 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
878 struct ext4_group_info *iter;
881 if (ac->ac_status == AC_STATUS_FOUND)
884 if (unlikely(sbi->s_mb_stats && ac->ac_flags & EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED))
885 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]);
895 list_for_each_entry(iter, &sbi->s_mb_largest_free_orders[i],
896 bb_largest_free_order_node) {
898 atomic64_inc(&sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]);
899 if (likely(ext4_mb_good_group(ac, iter->bb_group, CR_POWER2_ALIGNED))) {
900 *group = iter->bb_group;
901 ac->ac_flags |= EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED;
902 read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
906 read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
909 /* Increment cr and search again if no group is found */
910 *new_cr = CR_GOAL_LEN_FAST;
914 * Find a suitable group of given order from the average fragments list.
916 static struct ext4_group_info *
917 ext4_mb_find_good_group_avg_frag_lists(struct ext4_allocation_context *ac, int order)
919 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
920 struct list_head *frag_list = &sbi->s_mb_avg_fragment_size[order];
921 rwlock_t *frag_list_lock = &sbi->s_mb_avg_fragment_size_locks[order];
922 struct ext4_group_info *grp = NULL, *iter;
923 enum criteria cr = ac->ac_criteria;
925 if (list_empty(frag_list))
927 read_lock(frag_list_lock);
928 if (list_empty(frag_list)) {
929 read_unlock(frag_list_lock);
932 list_for_each_entry(iter, frag_list, bb_avg_fragment_size_node) {
934 atomic64_inc(&sbi->s_bal_cX_groups_considered[cr]);
935 if (likely(ext4_mb_good_group(ac, iter->bb_group, cr))) {
940 read_unlock(frag_list_lock);
945 * Choose next group by traversing average fragment size list of suitable
946 * order. Updates *new_cr if cr level needs an update.
948 static void ext4_mb_choose_next_group_goal_fast(struct ext4_allocation_context *ac,
949 enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
951 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
952 struct ext4_group_info *grp = NULL;
955 if (unlikely(ac->ac_flags & EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED)) {
957 atomic_inc(&sbi->s_bal_goal_fast_bad_suggestions);
960 for (i = mb_avg_fragment_size_order(ac->ac_sb, ac->ac_g_ex.fe_len);
961 i < MB_NUM_ORDERS(ac->ac_sb); i++) {
962 grp = ext4_mb_find_good_group_avg_frag_lists(ac, i);
964 *group = grp->bb_group;
965 ac->ac_flags |= EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED;
971 * CR_BEST_AVAIL_LEN works based on the concept that we have
972 * a larger normalized goal len request which can be trimmed to
973 * a smaller goal len such that it can still satisfy original
974 * request len. However, allocation request for non-regular
975 * files never gets normalized.
976 * See function ext4_mb_normalize_request() (EXT4_MB_HINT_DATA).
978 if (ac->ac_flags & EXT4_MB_HINT_DATA)
979 *new_cr = CR_BEST_AVAIL_LEN;
981 *new_cr = CR_GOAL_LEN_SLOW;
985 * We couldn't find a group in CR_GOAL_LEN_FAST so try to find the highest free fragment
986 * order we have and proactively trim the goal request length to that order to
987 * find a suitable group faster.
989 * This optimizes allocation speed at the cost of slightly reduced
990 * preallocations. However, we make sure that we don't trim the request too
991 * much and fall to CR_GOAL_LEN_SLOW in that case.
993 static void ext4_mb_choose_next_group_best_avail(struct ext4_allocation_context *ac,
994 enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
996 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
997 struct ext4_group_info *grp = NULL;
998 int i, order, min_order;
999 unsigned long num_stripe_clusters = 0;
1001 if (unlikely(ac->ac_flags & EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED)) {
1002 if (sbi->s_mb_stats)
1003 atomic_inc(&sbi->s_bal_best_avail_bad_suggestions);
1007 * mb_avg_fragment_size_order() returns order in a way that makes
1008 * retrieving back the length using (1 << order) inaccurate. Hence, use
1009 * fls() instead since we need to know the actual length while modifying
1012 order = fls(ac->ac_g_ex.fe_len) - 1;
1013 min_order = order - sbi->s_mb_best_avail_max_trim_order;
1017 if (sbi->s_stripe > 0) {
1019 * We are assuming that stripe size is always a multiple of
1020 * cluster ratio otherwise __ext4_fill_super exists early.
1022 num_stripe_clusters = EXT4_NUM_B2C(sbi, sbi->s_stripe);
1023 if (1 << min_order < num_stripe_clusters)
1025 * We consider 1 order less because later we round
1026 * up the goal len to num_stripe_clusters
1028 min_order = fls(num_stripe_clusters) - 1;
1031 if (1 << min_order < ac->ac_o_ex.fe_len)
1032 min_order = fls(ac->ac_o_ex.fe_len);
1034 for (i = order; i >= min_order; i--) {
1037 * Scale down goal len to make sure we find something
1038 * in the free fragments list. Basically, reduce
1041 ac->ac_g_ex.fe_len = 1 << i;
1043 if (num_stripe_clusters > 0) {
1045 * Try to round up the adjusted goal length to
1046 * stripe size (in cluster units) multiple for
1049 ac->ac_g_ex.fe_len = roundup(ac->ac_g_ex.fe_len,
1050 num_stripe_clusters);
1053 frag_order = mb_avg_fragment_size_order(ac->ac_sb,
1054 ac->ac_g_ex.fe_len);
1056 grp = ext4_mb_find_good_group_avg_frag_lists(ac, frag_order);
1058 *group = grp->bb_group;
1059 ac->ac_flags |= EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED;
1064 /* Reset goal length to original goal length before falling into CR_GOAL_LEN_SLOW */
1065 ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
1066 *new_cr = CR_GOAL_LEN_SLOW;
1069 static inline int should_optimize_scan(struct ext4_allocation_context *ac)
1071 if (unlikely(!test_opt2(ac->ac_sb, MB_OPTIMIZE_SCAN)))
1073 if (ac->ac_criteria >= CR_GOAL_LEN_SLOW)
1075 if (!ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS))
1081 * Return next linear group for allocation. If linear traversal should not be
1082 * performed, this function just returns the same group
1085 next_linear_group(struct ext4_allocation_context *ac, ext4_group_t group,
1086 ext4_group_t ngroups)
1088 if (!should_optimize_scan(ac))
1089 goto inc_and_return;
1091 if (ac->ac_groups_linear_remaining) {
1092 ac->ac_groups_linear_remaining--;
1093 goto inc_and_return;
1099 * Artificially restricted ngroups for non-extent
1100 * files makes group > ngroups possible on first loop.
1102 return group + 1 >= ngroups ? 0 : group + 1;
1106 * ext4_mb_choose_next_group: choose next group for allocation.
1108 * @ac Allocation Context
1109 * @new_cr This is an output parameter. If the there is no good group
1110 * available at current CR level, this field is updated to indicate
1111 * the new cr level that should be used.
1112 * @group This is an input / output parameter. As an input it indicates the
1113 * next group that the allocator intends to use for allocation. As
1114 * output, this field indicates the next group that should be used as
1115 * determined by the optimization functions.
1116 * @ngroups Total number of groups
1118 static void ext4_mb_choose_next_group(struct ext4_allocation_context *ac,
1119 enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
1121 *new_cr = ac->ac_criteria;
1123 if (!should_optimize_scan(ac) || ac->ac_groups_linear_remaining) {
1124 *group = next_linear_group(ac, *group, ngroups);
1128 if (*new_cr == CR_POWER2_ALIGNED) {
1129 ext4_mb_choose_next_group_p2_aligned(ac, new_cr, group, ngroups);
1130 } else if (*new_cr == CR_GOAL_LEN_FAST) {
1131 ext4_mb_choose_next_group_goal_fast(ac, new_cr, group, ngroups);
1132 } else if (*new_cr == CR_BEST_AVAIL_LEN) {
1133 ext4_mb_choose_next_group_best_avail(ac, new_cr, group, ngroups);
1136 * TODO: For CR=2, we can arrange groups in an rb tree sorted by
1137 * bb_free. But until that happens, we should never come here.
1144 * Cache the order of the largest free extent we have available in this block
1148 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
1150 struct ext4_sb_info *sbi = EXT4_SB(sb);
1153 for (i = MB_NUM_ORDERS(sb) - 1; i >= 0; i--)
1154 if (grp->bb_counters[i] > 0)
1156 /* No need to move between order lists? */
1157 if (!test_opt2(sb, MB_OPTIMIZE_SCAN) ||
1158 i == grp->bb_largest_free_order) {
1159 grp->bb_largest_free_order = i;
1163 if (grp->bb_largest_free_order >= 0) {
1164 write_lock(&sbi->s_mb_largest_free_orders_locks[
1165 grp->bb_largest_free_order]);
1166 list_del_init(&grp->bb_largest_free_order_node);
1167 write_unlock(&sbi->s_mb_largest_free_orders_locks[
1168 grp->bb_largest_free_order]);
1170 grp->bb_largest_free_order = i;
1171 if (grp->bb_largest_free_order >= 0 && grp->bb_free) {
1172 write_lock(&sbi->s_mb_largest_free_orders_locks[
1173 grp->bb_largest_free_order]);
1174 list_add_tail(&grp->bb_largest_free_order_node,
1175 &sbi->s_mb_largest_free_orders[grp->bb_largest_free_order]);
1176 write_unlock(&sbi->s_mb_largest_free_orders_locks[
1177 grp->bb_largest_free_order]);
1181 static noinline_for_stack
1182 void ext4_mb_generate_buddy(struct super_block *sb,
1183 void *buddy, void *bitmap, ext4_group_t group,
1184 struct ext4_group_info *grp)
1186 struct ext4_sb_info *sbi = EXT4_SB(sb);
1187 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
1188 ext4_grpblk_t i = 0;
1189 ext4_grpblk_t first;
1192 unsigned fragments = 0;
1193 unsigned long long period = get_cycles();
1195 /* initialize buddy from bitmap which is aggregation
1196 * of on-disk bitmap and preallocations */
1197 i = mb_find_next_zero_bit(bitmap, max, 0);
1198 grp->bb_first_free = i;
1202 i = mb_find_next_bit(bitmap, max, i);
1206 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
1208 grp->bb_counters[0]++;
1210 i = mb_find_next_zero_bit(bitmap, max, i);
1212 grp->bb_fragments = fragments;
1214 if (free != grp->bb_free) {
1215 ext4_grp_locked_error(sb, group, 0, 0,
1216 "block bitmap and bg descriptor "
1217 "inconsistent: %u vs %u free clusters",
1218 free, grp->bb_free);
1220 * If we intend to continue, we consider group descriptor
1221 * corrupt and update bb_free using bitmap value
1223 grp->bb_free = free;
1224 ext4_mark_group_bitmap_corrupted(sb, group,
1225 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1227 mb_set_largest_free_order(sb, grp);
1228 mb_update_avg_fragment_size(sb, grp);
1230 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
1232 period = get_cycles() - period;
1233 atomic_inc(&sbi->s_mb_buddies_generated);
1234 atomic64_add(period, &sbi->s_mb_generation_time);
1237 /* The buddy information is attached the buddy cache inode
1238 * for convenience. The information regarding each group
1239 * is loaded via ext4_mb_load_buddy. The information involve
1240 * block bitmap and buddy information. The information are
1241 * stored in the inode as
1244 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
1247 * one block each for bitmap and buddy information.
1248 * So for each group we take up 2 blocks. A page can
1249 * contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
1250 * So it can have information regarding groups_per_page which
1251 * is blocks_per_page/2
1253 * Locking note: This routine takes the block group lock of all groups
1254 * for this page; do not hold this lock when calling this routine!
1257 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
1259 ext4_group_t ngroups;
1260 unsigned int blocksize;
1261 int blocks_per_page;
1262 int groups_per_page;
1265 ext4_group_t first_group, group;
1267 struct super_block *sb;
1268 struct buffer_head *bhs;
1269 struct buffer_head **bh = NULL;
1270 struct inode *inode;
1273 struct ext4_group_info *grinfo;
1275 inode = page->mapping->host;
1277 ngroups = ext4_get_groups_count(sb);
1278 blocksize = i_blocksize(inode);
1279 blocks_per_page = PAGE_SIZE / blocksize;
1281 mb_debug(sb, "init page %lu\n", page->index);
1283 groups_per_page = blocks_per_page >> 1;
1284 if (groups_per_page == 0)
1285 groups_per_page = 1;
1287 /* allocate buffer_heads to read bitmaps */
1288 if (groups_per_page > 1) {
1289 i = sizeof(struct buffer_head *) * groups_per_page;
1290 bh = kzalloc(i, gfp);
1296 first_group = page->index * blocks_per_page / 2;
1298 /* read all groups the page covers into the cache */
1299 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1300 if (group >= ngroups)
1303 grinfo = ext4_get_group_info(sb, group);
1307 * If page is uptodate then we came here after online resize
1308 * which added some new uninitialized group info structs, so
1309 * we must skip all initialized uptodate buddies on the page,
1310 * which may be currently in use by an allocating task.
1312 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
1316 bh[i] = ext4_read_block_bitmap_nowait(sb, group, false);
1317 if (IS_ERR(bh[i])) {
1318 err = PTR_ERR(bh[i]);
1322 mb_debug(sb, "read bitmap for group %u\n", group);
1325 /* wait for I/O completion */
1326 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1331 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
1336 first_block = page->index * blocks_per_page;
1337 for (i = 0; i < blocks_per_page; i++) {
1338 group = (first_block + i) >> 1;
1339 if (group >= ngroups)
1342 if (!bh[group - first_group])
1343 /* skip initialized uptodate buddy */
1346 if (!buffer_verified(bh[group - first_group]))
1347 /* Skip faulty bitmaps */
1352 * data carry information regarding this
1353 * particular group in the format specified
1357 data = page_address(page) + (i * blocksize);
1358 bitmap = bh[group - first_group]->b_data;
1361 * We place the buddy block and bitmap block
1364 if ((first_block + i) & 1) {
1365 /* this is block of buddy */
1366 BUG_ON(incore == NULL);
1367 mb_debug(sb, "put buddy for group %u in page %lu/%x\n",
1368 group, page->index, i * blocksize);
1369 trace_ext4_mb_buddy_bitmap_load(sb, group);
1370 grinfo = ext4_get_group_info(sb, group);
1372 err = -EFSCORRUPTED;
1375 grinfo->bb_fragments = 0;
1376 memset(grinfo->bb_counters, 0,
1377 sizeof(*grinfo->bb_counters) *
1378 (MB_NUM_ORDERS(sb)));
1380 * incore got set to the group block bitmap below
1382 ext4_lock_group(sb, group);
1383 /* init the buddy */
1384 memset(data, 0xff, blocksize);
1385 ext4_mb_generate_buddy(sb, data, incore, group, grinfo);
1386 ext4_unlock_group(sb, group);
1389 /* this is block of bitmap */
1390 BUG_ON(incore != NULL);
1391 mb_debug(sb, "put bitmap for group %u in page %lu/%x\n",
1392 group, page->index, i * blocksize);
1393 trace_ext4_mb_bitmap_load(sb, group);
1395 /* see comments in ext4_mb_put_pa() */
1396 ext4_lock_group(sb, group);
1397 memcpy(data, bitmap, blocksize);
1399 /* mark all preallocated blks used in in-core bitmap */
1400 ext4_mb_generate_from_pa(sb, data, group);
1401 ext4_mb_generate_from_freelist(sb, data, group);
1402 ext4_unlock_group(sb, group);
1404 /* set incore so that the buddy information can be
1405 * generated using this
1410 SetPageUptodate(page);
1414 for (i = 0; i < groups_per_page; i++)
1423 * Lock the buddy and bitmap pages. This make sure other parallel init_group
1424 * on the same buddy page doesn't happen whild holding the buddy page lock.
1425 * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
1426 * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
1428 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
1429 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
1431 struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
1432 int block, pnum, poff;
1433 int blocks_per_page;
1436 e4b->bd_buddy_page = NULL;
1437 e4b->bd_bitmap_page = NULL;
1439 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1441 * the buddy cache inode stores the block bitmap
1442 * and buddy information in consecutive blocks.
1443 * So for each group we need two blocks.
1446 pnum = block / blocks_per_page;
1447 poff = block % blocks_per_page;
1448 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1451 BUG_ON(page->mapping != inode->i_mapping);
1452 e4b->bd_bitmap_page = page;
1453 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1455 if (blocks_per_page >= 2) {
1456 /* buddy and bitmap are on the same page */
1461 pnum = block / blocks_per_page;
1462 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1465 BUG_ON(page->mapping != inode->i_mapping);
1466 e4b->bd_buddy_page = page;
1470 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1472 if (e4b->bd_bitmap_page) {
1473 unlock_page(e4b->bd_bitmap_page);
1474 put_page(e4b->bd_bitmap_page);
1476 if (e4b->bd_buddy_page) {
1477 unlock_page(e4b->bd_buddy_page);
1478 put_page(e4b->bd_buddy_page);
1483 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1484 * block group lock of all groups for this page; do not hold the BG lock when
1485 * calling this routine!
1487 static noinline_for_stack
1488 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1491 struct ext4_group_info *this_grp;
1492 struct ext4_buddy e4b;
1497 mb_debug(sb, "init group %u\n", group);
1498 this_grp = ext4_get_group_info(sb, group);
1500 return -EFSCORRUPTED;
1503 * This ensures that we don't reinit the buddy cache
1504 * page which map to the group from which we are already
1505 * allocating. If we are looking at the buddy cache we would
1506 * have taken a reference using ext4_mb_load_buddy and that
1507 * would have pinned buddy page to page cache.
1508 * The call to ext4_mb_get_buddy_page_lock will mark the
1511 ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1512 if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1514 * somebody initialized the group
1515 * return without doing anything
1520 page = e4b.bd_bitmap_page;
1521 ret = ext4_mb_init_cache(page, NULL, gfp);
1524 if (!PageUptodate(page)) {
1529 if (e4b.bd_buddy_page == NULL) {
1531 * If both the bitmap and buddy are in
1532 * the same page we don't need to force
1538 /* init buddy cache */
1539 page = e4b.bd_buddy_page;
1540 ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1543 if (!PageUptodate(page)) {
1548 ext4_mb_put_buddy_page_lock(&e4b);
1553 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1554 * block group lock of all groups for this page; do not hold the BG lock when
1555 * calling this routine!
1557 static noinline_for_stack int
1558 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1559 struct ext4_buddy *e4b, gfp_t gfp)
1561 int blocks_per_page;
1567 struct ext4_group_info *grp;
1568 struct ext4_sb_info *sbi = EXT4_SB(sb);
1569 struct inode *inode = sbi->s_buddy_cache;
1572 mb_debug(sb, "load group %u\n", group);
1574 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1575 grp = ext4_get_group_info(sb, group);
1577 return -EFSCORRUPTED;
1579 e4b->bd_blkbits = sb->s_blocksize_bits;
1582 e4b->bd_group = group;
1583 e4b->bd_buddy_page = NULL;
1584 e4b->bd_bitmap_page = NULL;
1586 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1588 * we need full data about the group
1589 * to make a good selection
1591 ret = ext4_mb_init_group(sb, group, gfp);
1597 * the buddy cache inode stores the block bitmap
1598 * and buddy information in consecutive blocks.
1599 * So for each group we need two blocks.
1602 pnum = block / blocks_per_page;
1603 poff = block % blocks_per_page;
1605 /* we could use find_or_create_page(), but it locks page
1606 * what we'd like to avoid in fast path ... */
1607 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1608 if (page == NULL || !PageUptodate(page)) {
1611 * drop the page reference and try
1612 * to get the page with lock. If we
1613 * are not uptodate that implies
1614 * somebody just created the page but
1615 * is yet to initialize the same. So
1616 * wait for it to initialize.
1619 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1621 if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
1622 "ext4: bitmap's paging->mapping != inode->i_mapping\n")) {
1623 /* should never happen */
1628 if (!PageUptodate(page)) {
1629 ret = ext4_mb_init_cache(page, NULL, gfp);
1634 mb_cmp_bitmaps(e4b, page_address(page) +
1635 (poff * sb->s_blocksize));
1644 if (!PageUptodate(page)) {
1649 /* Pages marked accessed already */
1650 e4b->bd_bitmap_page = page;
1651 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1654 pnum = block / blocks_per_page;
1655 poff = block % blocks_per_page;
1657 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1658 if (page == NULL || !PageUptodate(page)) {
1661 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1663 if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
1664 "ext4: buddy bitmap's page->mapping != inode->i_mapping\n")) {
1665 /* should never happen */
1670 if (!PageUptodate(page)) {
1671 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1685 if (!PageUptodate(page)) {
1690 /* Pages marked accessed already */
1691 e4b->bd_buddy_page = page;
1692 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1699 if (e4b->bd_bitmap_page)
1700 put_page(e4b->bd_bitmap_page);
1702 e4b->bd_buddy = NULL;
1703 e4b->bd_bitmap = NULL;
1707 static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1708 struct ext4_buddy *e4b)
1710 return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1713 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1715 if (e4b->bd_bitmap_page)
1716 put_page(e4b->bd_bitmap_page);
1717 if (e4b->bd_buddy_page)
1718 put_page(e4b->bd_buddy_page);
1722 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1727 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1728 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1730 while (order <= e4b->bd_blkbits + 1) {
1731 bb = mb_find_buddy(e4b, order, &max);
1732 if (!mb_test_bit(block >> order, bb)) {
1733 /* this block is part of buddy of order 'order' */
1741 static void mb_clear_bits(void *bm, int cur, int len)
1747 if ((cur & 31) == 0 && (len - cur) >= 32) {
1748 /* fast path: clear whole word at once */
1749 addr = bm + (cur >> 3);
1754 mb_clear_bit(cur, bm);
1759 /* clear bits in given range
1760 * will return first found zero bit if any, -1 otherwise
1762 static int mb_test_and_clear_bits(void *bm, int cur, int len)
1769 if ((cur & 31) == 0 && (len - cur) >= 32) {
1770 /* fast path: clear whole word at once */
1771 addr = bm + (cur >> 3);
1772 if (*addr != (__u32)(-1) && zero_bit == -1)
1773 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1778 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1786 void mb_set_bits(void *bm, int cur, int len)
1792 if ((cur & 31) == 0 && (len - cur) >= 32) {
1793 /* fast path: set whole word at once */
1794 addr = bm + (cur >> 3);
1799 mb_set_bit(cur, bm);
1804 static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1806 if (mb_test_bit(*bit + side, bitmap)) {
1807 mb_clear_bit(*bit, bitmap);
1813 mb_set_bit(*bit, bitmap);
1818 static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1822 void *buddy = mb_find_buddy(e4b, order, &max);
1827 /* Bits in range [first; last] are known to be set since
1828 * corresponding blocks were allocated. Bits in range
1829 * (first; last) will stay set because they form buddies on
1830 * upper layer. We just deal with borders if they don't
1831 * align with upper layer and then go up.
1832 * Releasing entire group is all about clearing
1833 * single bit of highest order buddy.
1837 * ---------------------------------
1839 * ---------------------------------
1840 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1841 * ---------------------------------
1843 * \_____________________/
1845 * Neither [1] nor [6] is aligned to above layer.
1846 * Left neighbour [0] is free, so mark it busy,
1847 * decrease bb_counters and extend range to
1849 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1850 * mark [6] free, increase bb_counters and shrink range to
1852 * Then shift range to [0; 2], go up and do the same.
1857 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1859 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1864 buddy2 = mb_find_buddy(e4b, order, &max);
1866 mb_clear_bits(buddy, first, last - first + 1);
1867 e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1876 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1877 int first, int count)
1879 int left_is_free = 0;
1880 int right_is_free = 0;
1882 int last = first + count - 1;
1883 struct super_block *sb = e4b->bd_sb;
1885 if (WARN_ON(count == 0))
1887 BUG_ON(last >= (sb->s_blocksize << 3));
1888 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1889 /* Don't bother if the block group is corrupt. */
1890 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1893 mb_check_buddy(e4b);
1894 mb_free_blocks_double(inode, e4b, first, count);
1896 this_cpu_inc(discard_pa_seq);
1897 e4b->bd_info->bb_free += count;
1898 if (first < e4b->bd_info->bb_first_free)
1899 e4b->bd_info->bb_first_free = first;
1901 /* access memory sequentially: check left neighbour,
1902 * clear range and then check right neighbour
1905 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1906 block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1907 if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1908 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1910 if (unlikely(block != -1)) {
1911 struct ext4_sb_info *sbi = EXT4_SB(sb);
1912 ext4_fsblk_t blocknr;
1914 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1915 blocknr += EXT4_C2B(sbi, block);
1916 if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
1917 ext4_grp_locked_error(sb, e4b->bd_group,
1918 inode ? inode->i_ino : 0,
1920 "freeing already freed block (bit %u); block bitmap corrupt.",
1922 ext4_mark_group_bitmap_corrupted(
1924 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1929 /* let's maintain fragments counter */
1930 if (left_is_free && right_is_free)
1931 e4b->bd_info->bb_fragments--;
1932 else if (!left_is_free && !right_is_free)
1933 e4b->bd_info->bb_fragments++;
1935 /* buddy[0] == bd_bitmap is a special case, so handle
1936 * it right away and let mb_buddy_mark_free stay free of
1937 * zero order checks.
1938 * Check if neighbours are to be coaleasced,
1939 * adjust bitmap bb_counters and borders appropriately.
1942 first += !left_is_free;
1943 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1946 last -= !right_is_free;
1947 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1951 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1954 mb_set_largest_free_order(sb, e4b->bd_info);
1955 mb_update_avg_fragment_size(sb, e4b->bd_info);
1956 mb_check_buddy(e4b);
1959 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1960 int needed, struct ext4_free_extent *ex)
1966 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1969 buddy = mb_find_buddy(e4b, 0, &max);
1970 BUG_ON(buddy == NULL);
1971 BUG_ON(block >= max);
1972 if (mb_test_bit(block, buddy)) {
1979 /* find actual order */
1980 order = mb_find_order_for_block(e4b, block);
1981 block = block >> order;
1983 ex->fe_len = 1 << order;
1984 ex->fe_start = block << order;
1985 ex->fe_group = e4b->bd_group;
1987 /* calc difference from given start */
1988 next = next - ex->fe_start;
1990 ex->fe_start += next;
1992 while (needed > ex->fe_len &&
1993 mb_find_buddy(e4b, order, &max)) {
1995 if (block + 1 >= max)
1998 next = (block + 1) * (1 << order);
1999 if (mb_test_bit(next, e4b->bd_bitmap))
2002 order = mb_find_order_for_block(e4b, next);
2004 block = next >> order;
2005 ex->fe_len += 1 << order;
2008 if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
2009 /* Should never happen! (but apparently sometimes does?!?) */
2011 ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
2012 "corruption or bug in mb_find_extent "
2013 "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
2014 block, order, needed, ex->fe_group, ex->fe_start,
2015 ex->fe_len, ex->fe_logical);
2023 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
2029 int start = ex->fe_start;
2030 int len = ex->fe_len;
2036 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
2037 BUG_ON(e4b->bd_group != ex->fe_group);
2038 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
2039 mb_check_buddy(e4b);
2040 mb_mark_used_double(e4b, start, len);
2042 this_cpu_inc(discard_pa_seq);
2043 e4b->bd_info->bb_free -= len;
2044 if (e4b->bd_info->bb_first_free == start)
2045 e4b->bd_info->bb_first_free += len;
2047 /* let's maintain fragments counter */
2049 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
2050 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
2051 max = !mb_test_bit(start + len, e4b->bd_bitmap);
2053 e4b->bd_info->bb_fragments++;
2054 else if (!mlen && !max)
2055 e4b->bd_info->bb_fragments--;
2057 /* let's maintain buddy itself */
2060 ord = mb_find_order_for_block(e4b, start);
2062 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
2063 /* the whole chunk may be allocated at once! */
2066 buddy = mb_find_buddy(e4b, ord, &max);
2069 BUG_ON((start >> ord) >= max);
2070 mb_set_bit(start >> ord, buddy);
2071 e4b->bd_info->bb_counters[ord]--;
2078 /* store for history */
2080 ret = len | (ord << 16);
2082 /* we have to split large buddy */
2084 buddy = mb_find_buddy(e4b, ord, &max);
2085 mb_set_bit(start >> ord, buddy);
2086 e4b->bd_info->bb_counters[ord]--;
2089 cur = (start >> ord) & ~1U;
2090 buddy = mb_find_buddy(e4b, ord, &max);
2091 mb_clear_bit(cur, buddy);
2092 mb_clear_bit(cur + 1, buddy);
2093 e4b->bd_info->bb_counters[ord]++;
2094 e4b->bd_info->bb_counters[ord]++;
2097 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
2099 mb_update_avg_fragment_size(e4b->bd_sb, e4b->bd_info);
2100 mb_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
2101 mb_check_buddy(e4b);
2107 * Must be called under group lock!
2109 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
2110 struct ext4_buddy *e4b)
2112 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2115 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
2116 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2118 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
2119 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
2120 ret = mb_mark_used(e4b, &ac->ac_b_ex);
2122 /* preallocation can change ac_b_ex, thus we store actually
2123 * allocated blocks for history */
2124 ac->ac_f_ex = ac->ac_b_ex;
2126 ac->ac_status = AC_STATUS_FOUND;
2127 ac->ac_tail = ret & 0xffff;
2128 ac->ac_buddy = ret >> 16;
2131 * take the page reference. We want the page to be pinned
2132 * so that we don't get a ext4_mb_init_cache_call for this
2133 * group until we update the bitmap. That would mean we
2134 * double allocate blocks. The reference is dropped
2135 * in ext4_mb_release_context
2137 ac->ac_bitmap_page = e4b->bd_bitmap_page;
2138 get_page(ac->ac_bitmap_page);
2139 ac->ac_buddy_page = e4b->bd_buddy_page;
2140 get_page(ac->ac_buddy_page);
2141 /* store last allocated for subsequent stream allocation */
2142 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2143 spin_lock(&sbi->s_md_lock);
2144 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
2145 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
2146 spin_unlock(&sbi->s_md_lock);
2149 * As we've just preallocated more space than
2150 * user requested originally, we store allocated
2151 * space in a special descriptor.
2153 if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
2154 ext4_mb_new_preallocation(ac);
2158 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
2159 struct ext4_buddy *e4b,
2162 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2163 struct ext4_free_extent *bex = &ac->ac_b_ex;
2164 struct ext4_free_extent *gex = &ac->ac_g_ex;
2166 if (ac->ac_status == AC_STATUS_FOUND)
2169 * We don't want to scan for a whole year
2171 if (ac->ac_found > sbi->s_mb_max_to_scan &&
2172 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2173 ac->ac_status = AC_STATUS_BREAK;
2178 * Haven't found good chunk so far, let's continue
2180 if (bex->fe_len < gex->fe_len)
2183 if (finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
2184 ext4_mb_use_best_found(ac, e4b);
2188 * The routine checks whether found extent is good enough. If it is,
2189 * then the extent gets marked used and flag is set to the context
2190 * to stop scanning. Otherwise, the extent is compared with the
2191 * previous found extent and if new one is better, then it's stored
2192 * in the context. Later, the best found extent will be used, if
2193 * mballoc can't find good enough extent.
2195 * The algorithm used is roughly as follows:
2197 * * If free extent found is exactly as big as goal, then
2198 * stop the scan and use it immediately
2200 * * If free extent found is smaller than goal, then keep retrying
2201 * upto a max of sbi->s_mb_max_to_scan times (default 200). After
2202 * that stop scanning and use whatever we have.
2204 * * If free extent found is bigger than goal, then keep retrying
2205 * upto a max of sbi->s_mb_min_to_scan times (default 10) before
2206 * stopping the scan and using the extent.
2209 * FIXME: real allocation policy is to be designed yet!
2211 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
2212 struct ext4_free_extent *ex,
2213 struct ext4_buddy *e4b)
2215 struct ext4_free_extent *bex = &ac->ac_b_ex;
2216 struct ext4_free_extent *gex = &ac->ac_g_ex;
2218 BUG_ON(ex->fe_len <= 0);
2219 BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2220 BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2221 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
2224 ac->ac_cX_found[ac->ac_criteria]++;
2227 * The special case - take what you catch first
2229 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2231 ext4_mb_use_best_found(ac, e4b);
2236 * Let's check whether the chuck is good enough
2238 if (ex->fe_len == gex->fe_len) {
2240 ext4_mb_use_best_found(ac, e4b);
2245 * If this is first found extent, just store it in the context
2247 if (bex->fe_len == 0) {
2253 * If new found extent is better, store it in the context
2255 if (bex->fe_len < gex->fe_len) {
2256 /* if the request isn't satisfied, any found extent
2257 * larger than previous best one is better */
2258 if (ex->fe_len > bex->fe_len)
2260 } else if (ex->fe_len > gex->fe_len) {
2261 /* if the request is satisfied, then we try to find
2262 * an extent that still satisfy the request, but is
2263 * smaller than previous one */
2264 if (ex->fe_len < bex->fe_len)
2268 ext4_mb_check_limits(ac, e4b, 0);
2271 static noinline_for_stack
2272 void ext4_mb_try_best_found(struct ext4_allocation_context *ac,
2273 struct ext4_buddy *e4b)
2275 struct ext4_free_extent ex = ac->ac_b_ex;
2276 ext4_group_t group = ex.fe_group;
2280 BUG_ON(ex.fe_len <= 0);
2281 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2285 ext4_lock_group(ac->ac_sb, group);
2286 max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
2290 ext4_mb_use_best_found(ac, e4b);
2293 ext4_unlock_group(ac->ac_sb, group);
2294 ext4_mb_unload_buddy(e4b);
2297 static noinline_for_stack
2298 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
2299 struct ext4_buddy *e4b)
2301 ext4_group_t group = ac->ac_g_ex.fe_group;
2304 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2305 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2306 struct ext4_free_extent ex;
2309 return -EFSCORRUPTED;
2310 if (!(ac->ac_flags & (EXT4_MB_HINT_TRY_GOAL | EXT4_MB_HINT_GOAL_ONLY)))
2312 if (grp->bb_free == 0)
2315 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2319 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
2320 ext4_mb_unload_buddy(e4b);
2324 ext4_lock_group(ac->ac_sb, group);
2325 max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
2326 ac->ac_g_ex.fe_len, &ex);
2327 ex.fe_logical = 0xDEADFA11; /* debug value */
2329 if (max >= ac->ac_g_ex.fe_len &&
2330 ac->ac_g_ex.fe_len == EXT4_B2C(sbi, sbi->s_stripe)) {
2333 start = ext4_grp_offs_to_block(ac->ac_sb, &ex);
2334 /* use do_div to get remainder (would be 64-bit modulo) */
2335 if (do_div(start, sbi->s_stripe) == 0) {
2338 ext4_mb_use_best_found(ac, e4b);
2340 } else if (max >= ac->ac_g_ex.fe_len) {
2341 BUG_ON(ex.fe_len <= 0);
2342 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2343 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2346 ext4_mb_use_best_found(ac, e4b);
2347 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
2348 /* Sometimes, caller may want to merge even small
2349 * number of blocks to an existing extent */
2350 BUG_ON(ex.fe_len <= 0);
2351 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2352 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2355 ext4_mb_use_best_found(ac, e4b);
2357 ext4_unlock_group(ac->ac_sb, group);
2358 ext4_mb_unload_buddy(e4b);
2364 * The routine scans buddy structures (not bitmap!) from given order
2365 * to max order and tries to find big enough chunk to satisfy the req
2367 static noinline_for_stack
2368 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
2369 struct ext4_buddy *e4b)
2371 struct super_block *sb = ac->ac_sb;
2372 struct ext4_group_info *grp = e4b->bd_info;
2378 BUG_ON(ac->ac_2order <= 0);
2379 for (i = ac->ac_2order; i < MB_NUM_ORDERS(sb); i++) {
2380 if (grp->bb_counters[i] == 0)
2383 buddy = mb_find_buddy(e4b, i, &max);
2384 if (WARN_RATELIMIT(buddy == NULL,
2385 "ext4: mb_simple_scan_group: mb_find_buddy failed, (%d)\n", i))
2388 k = mb_find_next_zero_bit(buddy, max, 0);
2390 ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
2391 "%d free clusters of order %d. But found 0",
2392 grp->bb_counters[i], i);
2393 ext4_mark_group_bitmap_corrupted(ac->ac_sb,
2395 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2399 ac->ac_cX_found[ac->ac_criteria]++;
2401 ac->ac_b_ex.fe_len = 1 << i;
2402 ac->ac_b_ex.fe_start = k << i;
2403 ac->ac_b_ex.fe_group = e4b->bd_group;
2405 ext4_mb_use_best_found(ac, e4b);
2407 BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
2409 if (EXT4_SB(sb)->s_mb_stats)
2410 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
2417 * The routine scans the group and measures all found extents.
2418 * In order to optimize scanning, caller must pass number of
2419 * free blocks in the group, so the routine can know upper limit.
2421 static noinline_for_stack
2422 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
2423 struct ext4_buddy *e4b)
2425 struct super_block *sb = ac->ac_sb;
2426 void *bitmap = e4b->bd_bitmap;
2427 struct ext4_free_extent ex;
2431 free = e4b->bd_info->bb_free;
2432 if (WARN_ON(free <= 0))
2435 i = e4b->bd_info->bb_first_free;
2437 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
2438 i = mb_find_next_zero_bit(bitmap,
2439 EXT4_CLUSTERS_PER_GROUP(sb), i);
2440 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
2442 * IF we have corrupt bitmap, we won't find any
2443 * free blocks even though group info says we
2446 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2447 "%d free clusters as per "
2448 "group info. But bitmap says 0",
2450 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2451 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2455 if (!ext4_mb_cr_expensive(ac->ac_criteria)) {
2457 * In CR_GOAL_LEN_FAST and CR_BEST_AVAIL_LEN, we are
2458 * sure that this group will have a large enough
2459 * continuous free extent, so skip over the smaller free
2462 j = mb_find_next_bit(bitmap,
2463 EXT4_CLUSTERS_PER_GROUP(sb), i);
2466 if (freelen < ac->ac_g_ex.fe_len) {
2473 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
2474 if (WARN_ON(ex.fe_len <= 0))
2476 if (free < ex.fe_len) {
2477 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2478 "%d free clusters as per "
2479 "group info. But got %d blocks",
2481 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2482 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2484 * The number of free blocks differs. This mostly
2485 * indicate that the bitmap is corrupt. So exit
2486 * without claiming the space.
2490 ex.fe_logical = 0xDEADC0DE; /* debug value */
2491 ext4_mb_measure_extent(ac, &ex, e4b);
2497 ext4_mb_check_limits(ac, e4b, 1);
2501 * This is a special case for storages like raid5
2502 * we try to find stripe-aligned chunks for stripe-size-multiple requests
2504 static noinline_for_stack
2505 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2506 struct ext4_buddy *e4b)
2508 struct super_block *sb = ac->ac_sb;
2509 struct ext4_sb_info *sbi = EXT4_SB(sb);
2510 void *bitmap = e4b->bd_bitmap;
2511 struct ext4_free_extent ex;
2512 ext4_fsblk_t first_group_block;
2514 ext4_grpblk_t i, stripe;
2517 BUG_ON(sbi->s_stripe == 0);
2519 /* find first stripe-aligned block in group */
2520 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2522 a = first_group_block + sbi->s_stripe - 1;
2523 do_div(a, sbi->s_stripe);
2524 i = (a * sbi->s_stripe) - first_group_block;
2526 stripe = EXT4_B2C(sbi, sbi->s_stripe);
2527 i = EXT4_B2C(sbi, i);
2528 while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2529 if (!mb_test_bit(i, bitmap)) {
2530 max = mb_find_extent(e4b, i, stripe, &ex);
2531 if (max >= stripe) {
2533 ac->ac_cX_found[ac->ac_criteria]++;
2534 ex.fe_logical = 0xDEADF00D; /* debug value */
2536 ext4_mb_use_best_found(ac, e4b);
2545 * This is also called BEFORE we load the buddy bitmap.
2546 * Returns either 1 or 0 indicating that the group is either suitable
2547 * for the allocation or not.
2549 static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
2550 ext4_group_t group, enum criteria cr)
2552 ext4_grpblk_t free, fragments;
2553 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2554 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2556 BUG_ON(cr < CR_POWER2_ALIGNED || cr >= EXT4_MB_NUM_CRS);
2558 if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2561 free = grp->bb_free;
2565 fragments = grp->bb_fragments;
2570 case CR_POWER2_ALIGNED:
2571 BUG_ON(ac->ac_2order == 0);
2573 /* Avoid using the first bg of a flexgroup for data files */
2574 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2575 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2576 ((group % flex_size) == 0))
2579 if (free < ac->ac_g_ex.fe_len)
2582 if (ac->ac_2order >= MB_NUM_ORDERS(ac->ac_sb))
2585 if (grp->bb_largest_free_order < ac->ac_2order)
2589 case CR_GOAL_LEN_FAST:
2590 case CR_BEST_AVAIL_LEN:
2591 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2594 case CR_GOAL_LEN_SLOW:
2595 if (free >= ac->ac_g_ex.fe_len)
2608 * This could return negative error code if something goes wrong
2609 * during ext4_mb_init_group(). This should not be called with
2610 * ext4_lock_group() held.
2612 * Note: because we are conditionally operating with the group lock in
2613 * the EXT4_MB_STRICT_CHECK case, we need to fake out sparse in this
2614 * function using __acquire and __release. This means we need to be
2615 * super careful before messing with the error path handling via "goto
2618 static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
2619 ext4_group_t group, enum criteria cr)
2621 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2622 struct super_block *sb = ac->ac_sb;
2623 struct ext4_sb_info *sbi = EXT4_SB(sb);
2624 bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
2629 return -EFSCORRUPTED;
2630 if (sbi->s_mb_stats)
2631 atomic64_inc(&sbi->s_bal_cX_groups_considered[ac->ac_criteria]);
2633 ext4_lock_group(sb, group);
2634 __release(ext4_group_lock_ptr(sb, group));
2636 free = grp->bb_free;
2640 * In all criterias except CR_ANY_FREE we try to avoid groups that
2641 * can't possibly satisfy the full goal request due to insufficient
2644 if (cr < CR_ANY_FREE && free < ac->ac_g_ex.fe_len)
2646 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2649 __acquire(ext4_group_lock_ptr(sb, group));
2650 ext4_unlock_group(sb, group);
2653 /* We only do this if the grp has never been initialized */
2654 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2655 struct ext4_group_desc *gdp =
2656 ext4_get_group_desc(sb, group, NULL);
2660 * cr=CR_POWER2_ALIGNED/CR_GOAL_LEN_FAST is a very optimistic
2661 * search to find large good chunks almost for free. If buddy
2662 * data is not ready, then this optimization makes no sense. But
2663 * we never skip the first block group in a flex_bg, since this
2664 * gets used for metadata block allocation, and we want to make
2665 * sure we locate metadata blocks in the first block group in
2666 * the flex_bg if possible.
2668 if (!ext4_mb_cr_expensive(cr) &&
2669 (!sbi->s_log_groups_per_flex ||
2670 ((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
2671 !(ext4_has_group_desc_csum(sb) &&
2672 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
2674 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
2680 ext4_lock_group(sb, group);
2681 __release(ext4_group_lock_ptr(sb, group));
2683 ret = ext4_mb_good_group(ac, group, cr);
2686 __acquire(ext4_group_lock_ptr(sb, group));
2687 ext4_unlock_group(sb, group);
2693 * Start prefetching @nr block bitmaps starting at @group.
2694 * Return the next group which needs to be prefetched.
2696 ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
2697 unsigned int nr, int *cnt)
2699 ext4_group_t ngroups = ext4_get_groups_count(sb);
2700 struct buffer_head *bh;
2701 struct blk_plug plug;
2703 blk_start_plug(&plug);
2705 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2707 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2710 * Prefetch block groups with free blocks; but don't
2711 * bother if it is marked uninitialized on disk, since
2712 * it won't require I/O to read. Also only try to
2713 * prefetch once, so we avoid getblk() call, which can
2716 if (gdp && grp && !EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
2717 EXT4_MB_GRP_NEED_INIT(grp) &&
2718 ext4_free_group_clusters(sb, gdp) > 0 ) {
2719 bh = ext4_read_block_bitmap_nowait(sb, group, true);
2720 if (bh && !IS_ERR(bh)) {
2721 if (!buffer_uptodate(bh) && cnt)
2726 if (++group >= ngroups)
2729 blk_finish_plug(&plug);
2734 * Prefetching reads the block bitmap into the buffer cache; but we
2735 * need to make sure that the buddy bitmap in the page cache has been
2736 * initialized. Note that ext4_mb_init_group() will block if the I/O
2737 * is not yet completed, or indeed if it was not initiated by
2738 * ext4_mb_prefetch did not start the I/O.
2740 * TODO: We should actually kick off the buddy bitmap setup in a work
2741 * queue when the buffer I/O is completed, so that we don't block
2742 * waiting for the block allocation bitmap read to finish when
2743 * ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
2745 void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
2748 struct ext4_group_desc *gdp;
2749 struct ext4_group_info *grp;
2753 group = ext4_get_groups_count(sb);
2755 gdp = ext4_get_group_desc(sb, group, NULL);
2756 grp = ext4_get_group_info(sb, group);
2758 if (grp && gdp && EXT4_MB_GRP_NEED_INIT(grp) &&
2759 ext4_free_group_clusters(sb, gdp) > 0) {
2760 if (ext4_mb_init_group(sb, group, GFP_NOFS))
2766 static noinline_for_stack int
2767 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2769 ext4_group_t prefetch_grp = 0, ngroups, group, i;
2770 enum criteria new_cr, cr = CR_GOAL_LEN_FAST;
2771 int err = 0, first_err = 0;
2772 unsigned int nr = 0, prefetch_ios = 0;
2773 struct ext4_sb_info *sbi;
2774 struct super_block *sb;
2775 struct ext4_buddy e4b;
2780 ngroups = ext4_get_groups_count(sb);
2781 /* non-extent files are limited to low blocks/groups */
2782 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2783 ngroups = sbi->s_blockfile_groups;
2785 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2787 /* first, try the goal */
2788 err = ext4_mb_find_by_goal(ac, &e4b);
2789 if (err || ac->ac_status == AC_STATUS_FOUND)
2792 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2796 * ac->ac_2order is set only if the fe_len is a power of 2
2797 * if ac->ac_2order is set we also set criteria to CR_POWER2_ALIGNED
2798 * so that we try exact allocation using buddy.
2800 i = fls(ac->ac_g_ex.fe_len);
2803 * We search using buddy data only if the order of the request
2804 * is greater than equal to the sbi_s_mb_order2_reqs
2805 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2806 * We also support searching for power-of-two requests only for
2807 * requests upto maximum buddy size we have constructed.
2809 if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) {
2810 if (is_power_of_2(ac->ac_g_ex.fe_len))
2811 ac->ac_2order = array_index_nospec(i - 1,
2815 /* if stream allocation is enabled, use global goal */
2816 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2817 /* TBD: may be hot point */
2818 spin_lock(&sbi->s_md_lock);
2819 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2820 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2821 spin_unlock(&sbi->s_md_lock);
2825 * Let's just scan groups to find more-less suitable blocks We
2826 * start with CR_GOAL_LEN_FAST, unless it is power of 2
2827 * aligned, in which case let's do that faster approach first.
2830 cr = CR_POWER2_ALIGNED;
2832 for (; cr < EXT4_MB_NUM_CRS && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2833 ac->ac_criteria = cr;
2835 * searching for the right group start
2836 * from the goal value specified
2838 group = ac->ac_g_ex.fe_group;
2839 ac->ac_groups_linear_remaining = sbi->s_mb_max_linear_groups;
2840 prefetch_grp = group;
2842 for (i = 0, new_cr = cr; i < ngroups; i++,
2843 ext4_mb_choose_next_group(ac, &new_cr, &group, ngroups)) {
2853 * Batch reads of the block allocation bitmaps
2854 * to get multiple READs in flight; limit
2855 * prefetching at inexpensive CR, otherwise mballoc
2856 * can spend a lot of time loading imperfect groups
2858 if ((prefetch_grp == group) &&
2859 (ext4_mb_cr_expensive(cr) ||
2860 prefetch_ios < sbi->s_mb_prefetch_limit)) {
2861 nr = sbi->s_mb_prefetch;
2862 if (ext4_has_feature_flex_bg(sb)) {
2863 nr = 1 << sbi->s_log_groups_per_flex;
2864 nr -= group & (nr - 1);
2865 nr = min(nr, sbi->s_mb_prefetch);
2867 prefetch_grp = ext4_mb_prefetch(sb, group,
2871 /* This now checks without needing the buddy page */
2872 ret = ext4_mb_good_group_nolock(ac, group, cr);
2879 err = ext4_mb_load_buddy(sb, group, &e4b);
2883 ext4_lock_group(sb, group);
2886 * We need to check again after locking the
2889 ret = ext4_mb_good_group(ac, group, cr);
2891 ext4_unlock_group(sb, group);
2892 ext4_mb_unload_buddy(&e4b);
2896 ac->ac_groups_scanned++;
2897 if (cr == CR_POWER2_ALIGNED)
2898 ext4_mb_simple_scan_group(ac, &e4b);
2899 else if ((cr == CR_GOAL_LEN_FAST ||
2900 cr == CR_BEST_AVAIL_LEN) &&
2902 !(ac->ac_g_ex.fe_len %
2903 EXT4_B2C(sbi, sbi->s_stripe)))
2904 ext4_mb_scan_aligned(ac, &e4b);
2906 ext4_mb_complex_scan_group(ac, &e4b);
2908 ext4_unlock_group(sb, group);
2909 ext4_mb_unload_buddy(&e4b);
2911 if (ac->ac_status != AC_STATUS_CONTINUE)
2914 /* Processed all groups and haven't found blocks */
2915 if (sbi->s_mb_stats && i == ngroups)
2916 atomic64_inc(&sbi->s_bal_cX_failed[cr]);
2918 if (i == ngroups && ac->ac_criteria == CR_BEST_AVAIL_LEN)
2919 /* Reset goal length to original goal length before
2920 * falling into CR_GOAL_LEN_SLOW */
2921 ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
2924 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2925 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2927 * We've been searching too long. Let's try to allocate
2928 * the best chunk we've found so far
2930 ext4_mb_try_best_found(ac, &e4b);
2931 if (ac->ac_status != AC_STATUS_FOUND) {
2933 * Someone more lucky has already allocated it.
2934 * The only thing we can do is just take first
2937 lost = atomic_inc_return(&sbi->s_mb_lost_chunks);
2938 mb_debug(sb, "lost chunk, group: %u, start: %d, len: %d, lost: %d\n",
2939 ac->ac_b_ex.fe_group, ac->ac_b_ex.fe_start,
2940 ac->ac_b_ex.fe_len, lost);
2942 ac->ac_b_ex.fe_group = 0;
2943 ac->ac_b_ex.fe_start = 0;
2944 ac->ac_b_ex.fe_len = 0;
2945 ac->ac_status = AC_STATUS_CONTINUE;
2946 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2952 if (sbi->s_mb_stats && ac->ac_status == AC_STATUS_FOUND)
2953 atomic64_inc(&sbi->s_bal_cX_hits[ac->ac_criteria]);
2955 if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2958 mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
2959 ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
2960 ac->ac_flags, cr, err);
2963 ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
2968 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2970 struct super_block *sb = pde_data(file_inode(seq->file));
2973 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2976 return (void *) ((unsigned long) group);
2979 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2981 struct super_block *sb = pde_data(file_inode(seq->file));
2985 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2988 return (void *) ((unsigned long) group);
2991 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2993 struct super_block *sb = pde_data(file_inode(seq->file));
2994 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2996 int err, buddy_loaded = 0;
2997 struct ext4_buddy e4b;
2998 struct ext4_group_info *grinfo;
2999 unsigned char blocksize_bits = min_t(unsigned char,
3000 sb->s_blocksize_bits,
3001 EXT4_MAX_BLOCK_LOG_SIZE);
3003 struct ext4_group_info info;
3004 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
3009 seq_puts(seq, "#group: free frags first ["
3010 " 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
3011 " 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
3013 i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
3014 sizeof(struct ext4_group_info);
3016 grinfo = ext4_get_group_info(sb, group);
3019 /* Load the group info in memory only if not already loaded. */
3020 if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
3021 err = ext4_mb_load_buddy(sb, group, &e4b);
3023 seq_printf(seq, "#%-5u: I/O error\n", group);
3029 memcpy(&sg, grinfo, i);
3032 ext4_mb_unload_buddy(&e4b);
3034 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
3035 sg.info.bb_fragments, sg.info.bb_first_free);
3036 for (i = 0; i <= 13; i++)
3037 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
3038 sg.info.bb_counters[i] : 0);
3039 seq_puts(seq, " ]\n");
3044 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
3048 const struct seq_operations ext4_mb_seq_groups_ops = {
3049 .start = ext4_mb_seq_groups_start,
3050 .next = ext4_mb_seq_groups_next,
3051 .stop = ext4_mb_seq_groups_stop,
3052 .show = ext4_mb_seq_groups_show,
3055 int ext4_seq_mb_stats_show(struct seq_file *seq, void *offset)
3057 struct super_block *sb = seq->private;
3058 struct ext4_sb_info *sbi = EXT4_SB(sb);
3060 seq_puts(seq, "mballoc:\n");
3061 if (!sbi->s_mb_stats) {
3062 seq_puts(seq, "\tmb stats collection turned off.\n");
3065 "\tTo enable, please write \"1\" to sysfs file mb_stats.\n");
3068 seq_printf(seq, "\treqs: %u\n", atomic_read(&sbi->s_bal_reqs));
3069 seq_printf(seq, "\tsuccess: %u\n", atomic_read(&sbi->s_bal_success));
3071 seq_printf(seq, "\tgroups_scanned: %u\n",
3072 atomic_read(&sbi->s_bal_groups_scanned));
3074 /* CR_POWER2_ALIGNED stats */
3075 seq_puts(seq, "\tcr_p2_aligned_stats:\n");
3076 seq_printf(seq, "\t\thits: %llu\n",
3077 atomic64_read(&sbi->s_bal_cX_hits[CR_POWER2_ALIGNED]));
3079 seq, "\t\tgroups_considered: %llu\n",
3081 &sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]));
3082 seq_printf(seq, "\t\textents_scanned: %u\n",
3083 atomic_read(&sbi->s_bal_cX_ex_scanned[CR_POWER2_ALIGNED]));
3084 seq_printf(seq, "\t\tuseless_loops: %llu\n",
3085 atomic64_read(&sbi->s_bal_cX_failed[CR_POWER2_ALIGNED]));
3086 seq_printf(seq, "\t\tbad_suggestions: %u\n",
3087 atomic_read(&sbi->s_bal_p2_aligned_bad_suggestions));
3089 /* CR_GOAL_LEN_FAST stats */
3090 seq_puts(seq, "\tcr_goal_fast_stats:\n");
3091 seq_printf(seq, "\t\thits: %llu\n",
3092 atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_FAST]));
3093 seq_printf(seq, "\t\tgroups_considered: %llu\n",
3095 &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_FAST]));
3096 seq_printf(seq, "\t\textents_scanned: %u\n",
3097 atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_FAST]));
3098 seq_printf(seq, "\t\tuseless_loops: %llu\n",
3099 atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_FAST]));
3100 seq_printf(seq, "\t\tbad_suggestions: %u\n",
3101 atomic_read(&sbi->s_bal_goal_fast_bad_suggestions));
3103 /* CR_BEST_AVAIL_LEN stats */
3104 seq_puts(seq, "\tcr_best_avail_stats:\n");
3105 seq_printf(seq, "\t\thits: %llu\n",
3106 atomic64_read(&sbi->s_bal_cX_hits[CR_BEST_AVAIL_LEN]));
3108 seq, "\t\tgroups_considered: %llu\n",
3110 &sbi->s_bal_cX_groups_considered[CR_BEST_AVAIL_LEN]));
3111 seq_printf(seq, "\t\textents_scanned: %u\n",
3112 atomic_read(&sbi->s_bal_cX_ex_scanned[CR_BEST_AVAIL_LEN]));
3113 seq_printf(seq, "\t\tuseless_loops: %llu\n",
3114 atomic64_read(&sbi->s_bal_cX_failed[CR_BEST_AVAIL_LEN]));
3115 seq_printf(seq, "\t\tbad_suggestions: %u\n",
3116 atomic_read(&sbi->s_bal_best_avail_bad_suggestions));
3118 /* CR_GOAL_LEN_SLOW stats */
3119 seq_puts(seq, "\tcr_goal_slow_stats:\n");
3120 seq_printf(seq, "\t\thits: %llu\n",
3121 atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_SLOW]));
3122 seq_printf(seq, "\t\tgroups_considered: %llu\n",
3124 &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_SLOW]));
3125 seq_printf(seq, "\t\textents_scanned: %u\n",
3126 atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_SLOW]));
3127 seq_printf(seq, "\t\tuseless_loops: %llu\n",
3128 atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_SLOW]));
3130 /* CR_ANY_FREE stats */
3131 seq_puts(seq, "\tcr_any_free_stats:\n");
3132 seq_printf(seq, "\t\thits: %llu\n",
3133 atomic64_read(&sbi->s_bal_cX_hits[CR_ANY_FREE]));
3135 seq, "\t\tgroups_considered: %llu\n",
3136 atomic64_read(&sbi->s_bal_cX_groups_considered[CR_ANY_FREE]));
3137 seq_printf(seq, "\t\textents_scanned: %u\n",
3138 atomic_read(&sbi->s_bal_cX_ex_scanned[CR_ANY_FREE]));
3139 seq_printf(seq, "\t\tuseless_loops: %llu\n",
3140 atomic64_read(&sbi->s_bal_cX_failed[CR_ANY_FREE]));
3143 seq_printf(seq, "\textents_scanned: %u\n",
3144 atomic_read(&sbi->s_bal_ex_scanned));
3145 seq_printf(seq, "\t\tgoal_hits: %u\n", atomic_read(&sbi->s_bal_goals));
3146 seq_printf(seq, "\t\tlen_goal_hits: %u\n",
3147 atomic_read(&sbi->s_bal_len_goals));
3148 seq_printf(seq, "\t\t2^n_hits: %u\n", atomic_read(&sbi->s_bal_2orders));
3149 seq_printf(seq, "\t\tbreaks: %u\n", atomic_read(&sbi->s_bal_breaks));
3150 seq_printf(seq, "\t\tlost: %u\n", atomic_read(&sbi->s_mb_lost_chunks));
3151 seq_printf(seq, "\tbuddies_generated: %u/%u\n",
3152 atomic_read(&sbi->s_mb_buddies_generated),
3153 ext4_get_groups_count(sb));
3154 seq_printf(seq, "\tbuddies_time_used: %llu\n",
3155 atomic64_read(&sbi->s_mb_generation_time));
3156 seq_printf(seq, "\tpreallocated: %u\n",
3157 atomic_read(&sbi->s_mb_preallocated));
3158 seq_printf(seq, "\tdiscarded: %u\n", atomic_read(&sbi->s_mb_discarded));
3162 static void *ext4_mb_seq_structs_summary_start(struct seq_file *seq, loff_t *pos)
3163 __acquires(&EXT4_SB(sb)->s_mb_rb_lock)
3165 struct super_block *sb = pde_data(file_inode(seq->file));
3166 unsigned long position;
3168 if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3170 position = *pos + 1;
3171 return (void *) ((unsigned long) position);
3174 static void *ext4_mb_seq_structs_summary_next(struct seq_file *seq, void *v, loff_t *pos)
3176 struct super_block *sb = pde_data(file_inode(seq->file));
3177 unsigned long position;
3180 if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
3182 position = *pos + 1;
3183 return (void *) ((unsigned long) position);
3186 static int ext4_mb_seq_structs_summary_show(struct seq_file *seq, void *v)
3188 struct super_block *sb = pde_data(file_inode(seq->file));
3189 struct ext4_sb_info *sbi = EXT4_SB(sb);
3190 unsigned long position = ((unsigned long) v);
3191 struct ext4_group_info *grp;
3195 if (position >= MB_NUM_ORDERS(sb)) {
3196 position -= MB_NUM_ORDERS(sb);
3198 seq_puts(seq, "avg_fragment_size_lists:\n");
3201 read_lock(&sbi->s_mb_avg_fragment_size_locks[position]);
3202 list_for_each_entry(grp, &sbi->s_mb_avg_fragment_size[position],
3203 bb_avg_fragment_size_node)
3205 read_unlock(&sbi->s_mb_avg_fragment_size_locks[position]);
3206 seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3207 (unsigned int)position, count);
3211 if (position == 0) {
3212 seq_printf(seq, "optimize_scan: %d\n",
3213 test_opt2(sb, MB_OPTIMIZE_SCAN) ? 1 : 0);
3214 seq_puts(seq, "max_free_order_lists:\n");
3217 read_lock(&sbi->s_mb_largest_free_orders_locks[position]);
3218 list_for_each_entry(grp, &sbi->s_mb_largest_free_orders[position],
3219 bb_largest_free_order_node)
3221 read_unlock(&sbi->s_mb_largest_free_orders_locks[position]);
3222 seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3223 (unsigned int)position, count);
3228 static void ext4_mb_seq_structs_summary_stop(struct seq_file *seq, void *v)
3232 const struct seq_operations ext4_mb_seq_structs_summary_ops = {
3233 .start = ext4_mb_seq_structs_summary_start,
3234 .next = ext4_mb_seq_structs_summary_next,
3235 .stop = ext4_mb_seq_structs_summary_stop,
3236 .show = ext4_mb_seq_structs_summary_show,
3239 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
3241 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3242 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
3249 * Allocate the top-level s_group_info array for the specified number
3252 int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
3254 struct ext4_sb_info *sbi = EXT4_SB(sb);
3256 struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
3258 size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
3259 EXT4_DESC_PER_BLOCK_BITS(sb);
3260 if (size <= sbi->s_group_info_size)
3263 size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
3264 new_groupinfo = kvzalloc(size, GFP_KERNEL);
3265 if (!new_groupinfo) {
3266 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
3270 old_groupinfo = rcu_dereference(sbi->s_group_info);
3272 memcpy(new_groupinfo, old_groupinfo,
3273 sbi->s_group_info_size * sizeof(*sbi->s_group_info));
3275 rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
3276 sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
3278 ext4_kvfree_array_rcu(old_groupinfo);
3279 ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
3280 sbi->s_group_info_size);
3284 /* Create and initialize ext4_group_info data for the given group. */
3285 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
3286 struct ext4_group_desc *desc)
3290 int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
3291 struct ext4_sb_info *sbi = EXT4_SB(sb);
3292 struct ext4_group_info **meta_group_info;
3293 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3296 * First check if this group is the first of a reserved block.
3297 * If it's true, we have to allocate a new table of pointers
3298 * to ext4_group_info structures
3300 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3301 metalen = sizeof(*meta_group_info) <<
3302 EXT4_DESC_PER_BLOCK_BITS(sb);
3303 meta_group_info = kmalloc(metalen, GFP_NOFS);
3304 if (meta_group_info == NULL) {
3305 ext4_msg(sb, KERN_ERR, "can't allocate mem "
3306 "for a buddy group");
3310 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
3314 meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
3315 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
3317 meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
3318 if (meta_group_info[i] == NULL) {
3319 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
3320 goto exit_group_info;
3322 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
3323 &(meta_group_info[i]->bb_state));
3326 * initialize bb_free to be able to skip
3327 * empty groups without initialization
3329 if (ext4_has_group_desc_csum(sb) &&
3330 (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3331 meta_group_info[i]->bb_free =
3332 ext4_free_clusters_after_init(sb, group, desc);
3334 meta_group_info[i]->bb_free =
3335 ext4_free_group_clusters(sb, desc);
3338 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
3339 init_rwsem(&meta_group_info[i]->alloc_sem);
3340 meta_group_info[i]->bb_free_root = RB_ROOT;
3341 INIT_LIST_HEAD(&meta_group_info[i]->bb_largest_free_order_node);
3342 INIT_LIST_HEAD(&meta_group_info[i]->bb_avg_fragment_size_node);
3343 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
3344 meta_group_info[i]->bb_avg_fragment_size_order = -1; /* uninit */
3345 meta_group_info[i]->bb_group = group;
3347 mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
3351 /* If a meta_group_info table has been allocated, release it now */
3352 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3353 struct ext4_group_info ***group_info;
3356 group_info = rcu_dereference(sbi->s_group_info);
3357 kfree(group_info[idx]);
3358 group_info[idx] = NULL;
3362 } /* ext4_mb_add_groupinfo */
3364 static int ext4_mb_init_backend(struct super_block *sb)
3366 ext4_group_t ngroups = ext4_get_groups_count(sb);
3368 struct ext4_sb_info *sbi = EXT4_SB(sb);
3370 struct ext4_group_desc *desc;
3371 struct ext4_group_info ***group_info;
3372 struct kmem_cache *cachep;
3374 err = ext4_mb_alloc_groupinfo(sb, ngroups);
3378 sbi->s_buddy_cache = new_inode(sb);
3379 if (sbi->s_buddy_cache == NULL) {
3380 ext4_msg(sb, KERN_ERR, "can't get new inode");
3383 /* To avoid potentially colliding with an valid on-disk inode number,
3384 * use EXT4_BAD_INO for the buddy cache inode number. This inode is
3385 * not in the inode hash, so it should never be found by iget(), but
3386 * this will avoid confusion if it ever shows up during debugging. */
3387 sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
3388 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
3389 for (i = 0; i < ngroups; i++) {
3391 desc = ext4_get_group_desc(sb, i, NULL);
3393 ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
3396 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
3400 if (ext4_has_feature_flex_bg(sb)) {
3401 /* a single flex group is supposed to be read by a single IO.
3402 * 2 ^ s_log_groups_per_flex != UINT_MAX as s_mb_prefetch is
3403 * unsigned integer, so the maximum shift is 32.
3405 if (sbi->s_es->s_log_groups_per_flex >= 32) {
3406 ext4_msg(sb, KERN_ERR, "too many log groups per flexible block group");
3409 sbi->s_mb_prefetch = min_t(uint, 1 << sbi->s_es->s_log_groups_per_flex,
3410 BLK_MAX_SEGMENT_SIZE >> (sb->s_blocksize_bits - 9));
3411 sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
3413 sbi->s_mb_prefetch = 32;
3415 if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
3416 sbi->s_mb_prefetch = ext4_get_groups_count(sb);
3417 /* now many real IOs to prefetch within a single allocation at cr=0
3418 * given cr=0 is an CPU-related optimization we shouldn't try to
3419 * load too many groups, at some point we should start to use what
3420 * we've got in memory.
3421 * with an average random access time 5ms, it'd take a second to get
3422 * 200 groups (* N with flex_bg), so let's make this limit 4
3424 sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
3425 if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
3426 sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
3431 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3433 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3436 kmem_cache_free(cachep, grp);
3438 i = sbi->s_group_info_size;
3440 group_info = rcu_dereference(sbi->s_group_info);
3442 kfree(group_info[i]);
3444 iput(sbi->s_buddy_cache);
3447 kvfree(rcu_dereference(sbi->s_group_info));
3452 static void ext4_groupinfo_destroy_slabs(void)
3456 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
3457 kmem_cache_destroy(ext4_groupinfo_caches[i]);
3458 ext4_groupinfo_caches[i] = NULL;
3462 static int ext4_groupinfo_create_slab(size_t size)
3464 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
3466 int blocksize_bits = order_base_2(size);
3467 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3468 struct kmem_cache *cachep;
3470 if (cache_index >= NR_GRPINFO_CACHES)
3473 if (unlikely(cache_index < 0))
3476 mutex_lock(&ext4_grpinfo_slab_create_mutex);
3477 if (ext4_groupinfo_caches[cache_index]) {
3478 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
3479 return 0; /* Already created */
3482 slab_size = offsetof(struct ext4_group_info,
3483 bb_counters[blocksize_bits + 2]);
3485 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
3486 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
3489 ext4_groupinfo_caches[cache_index] = cachep;
3491 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
3494 "EXT4-fs: no memory for groupinfo slab cache\n");
3501 static void ext4_discard_work(struct work_struct *work)
3503 struct ext4_sb_info *sbi = container_of(work,
3504 struct ext4_sb_info, s_discard_work);
3505 struct super_block *sb = sbi->s_sb;
3506 struct ext4_free_data *fd, *nfd;
3507 struct ext4_buddy e4b;
3508 LIST_HEAD(discard_list);
3509 ext4_group_t grp, load_grp;
3512 spin_lock(&sbi->s_md_lock);
3513 list_splice_init(&sbi->s_discard_list, &discard_list);
3514 spin_unlock(&sbi->s_md_lock);
3516 load_grp = UINT_MAX;
3517 list_for_each_entry_safe(fd, nfd, &discard_list, efd_list) {
3519 * If filesystem is umounting or no memory or suffering
3520 * from no space, give up the discard
3522 if ((sb->s_flags & SB_ACTIVE) && !err &&
3523 !atomic_read(&sbi->s_retry_alloc_pending)) {
3524 grp = fd->efd_group;
3525 if (grp != load_grp) {
3526 if (load_grp != UINT_MAX)
3527 ext4_mb_unload_buddy(&e4b);
3529 err = ext4_mb_load_buddy(sb, grp, &e4b);
3531 kmem_cache_free(ext4_free_data_cachep, fd);
3532 load_grp = UINT_MAX;
3539 ext4_lock_group(sb, grp);
3540 ext4_try_to_trim_range(sb, &e4b, fd->efd_start_cluster,
3541 fd->efd_start_cluster + fd->efd_count - 1, 1);
3542 ext4_unlock_group(sb, grp);
3544 kmem_cache_free(ext4_free_data_cachep, fd);
3547 if (load_grp != UINT_MAX)
3548 ext4_mb_unload_buddy(&e4b);
3551 int ext4_mb_init(struct super_block *sb)
3553 struct ext4_sb_info *sbi = EXT4_SB(sb);
3555 unsigned offset, offset_incr;
3559 i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_offsets);
3561 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
3562 if (sbi->s_mb_offsets == NULL) {
3567 i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_maxs);
3568 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
3569 if (sbi->s_mb_maxs == NULL) {
3574 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
3578 /* order 0 is regular bitmap */
3579 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
3580 sbi->s_mb_offsets[0] = 0;
3584 offset_incr = 1 << (sb->s_blocksize_bits - 1);
3585 max = sb->s_blocksize << 2;
3587 sbi->s_mb_offsets[i] = offset;
3588 sbi->s_mb_maxs[i] = max;
3589 offset += offset_incr;
3590 offset_incr = offset_incr >> 1;
3593 } while (i < MB_NUM_ORDERS(sb));
3595 sbi->s_mb_avg_fragment_size =
3596 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3598 if (!sbi->s_mb_avg_fragment_size) {
3602 sbi->s_mb_avg_fragment_size_locks =
3603 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3605 if (!sbi->s_mb_avg_fragment_size_locks) {
3609 for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3610 INIT_LIST_HEAD(&sbi->s_mb_avg_fragment_size[i]);
3611 rwlock_init(&sbi->s_mb_avg_fragment_size_locks[i]);
3613 sbi->s_mb_largest_free_orders =
3614 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3616 if (!sbi->s_mb_largest_free_orders) {
3620 sbi->s_mb_largest_free_orders_locks =
3621 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3623 if (!sbi->s_mb_largest_free_orders_locks) {
3627 for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3628 INIT_LIST_HEAD(&sbi->s_mb_largest_free_orders[i]);
3629 rwlock_init(&sbi->s_mb_largest_free_orders_locks[i]);
3632 spin_lock_init(&sbi->s_md_lock);
3633 sbi->s_mb_free_pending = 0;
3634 INIT_LIST_HEAD(&sbi->s_freed_data_list);
3635 INIT_LIST_HEAD(&sbi->s_discard_list);
3636 INIT_WORK(&sbi->s_discard_work, ext4_discard_work);
3637 atomic_set(&sbi->s_retry_alloc_pending, 0);
3639 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
3640 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
3641 sbi->s_mb_stats = MB_DEFAULT_STATS;
3642 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
3643 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
3644 sbi->s_mb_best_avail_max_trim_order = MB_DEFAULT_BEST_AVAIL_TRIM_ORDER;
3647 * The default group preallocation is 512, which for 4k block
3648 * sizes translates to 2 megabytes. However for bigalloc file
3649 * systems, this is probably too big (i.e, if the cluster size
3650 * is 1 megabyte, then group preallocation size becomes half a
3651 * gigabyte!). As a default, we will keep a two megabyte
3652 * group pralloc size for cluster sizes up to 64k, and after
3653 * that, we will force a minimum group preallocation size of
3654 * 32 clusters. This translates to 8 megs when the cluster
3655 * size is 256k, and 32 megs when the cluster size is 1 meg,
3656 * which seems reasonable as a default.
3658 sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
3659 sbi->s_cluster_bits, 32);
3661 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
3662 * to the lowest multiple of s_stripe which is bigger than
3663 * the s_mb_group_prealloc as determined above. We want
3664 * the preallocation size to be an exact multiple of the
3665 * RAID stripe size so that preallocations don't fragment
3668 if (sbi->s_stripe > 1) {
3669 sbi->s_mb_group_prealloc = roundup(
3670 sbi->s_mb_group_prealloc, EXT4_B2C(sbi, sbi->s_stripe));
3673 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
3674 if (sbi->s_locality_groups == NULL) {
3678 for_each_possible_cpu(i) {
3679 struct ext4_locality_group *lg;
3680 lg = per_cpu_ptr(sbi->s_locality_groups, i);
3681 mutex_init(&lg->lg_mutex);
3682 for (j = 0; j < PREALLOC_TB_SIZE; j++)
3683 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
3684 spin_lock_init(&lg->lg_prealloc_lock);
3687 if (bdev_nonrot(sb->s_bdev))
3688 sbi->s_mb_max_linear_groups = 0;
3690 sbi->s_mb_max_linear_groups = MB_DEFAULT_LINEAR_LIMIT;
3691 /* init file for buddy data */
3692 ret = ext4_mb_init_backend(sb);
3694 goto out_free_locality_groups;
3698 out_free_locality_groups:
3699 free_percpu(sbi->s_locality_groups);
3700 sbi->s_locality_groups = NULL;
3702 kfree(sbi->s_mb_avg_fragment_size);
3703 kfree(sbi->s_mb_avg_fragment_size_locks);
3704 kfree(sbi->s_mb_largest_free_orders);
3705 kfree(sbi->s_mb_largest_free_orders_locks);
3706 kfree(sbi->s_mb_offsets);
3707 sbi->s_mb_offsets = NULL;
3708 kfree(sbi->s_mb_maxs);
3709 sbi->s_mb_maxs = NULL;
3713 /* need to called with the ext4 group lock held */
3714 static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
3716 struct ext4_prealloc_space *pa;
3717 struct list_head *cur, *tmp;
3720 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
3721 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3722 list_del(&pa->pa_group_list);
3724 kmem_cache_free(ext4_pspace_cachep, pa);
3729 int ext4_mb_release(struct super_block *sb)
3731 ext4_group_t ngroups = ext4_get_groups_count(sb);
3733 int num_meta_group_infos;
3734 struct ext4_group_info *grinfo, ***group_info;
3735 struct ext4_sb_info *sbi = EXT4_SB(sb);
3736 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3739 if (test_opt(sb, DISCARD)) {
3741 * wait the discard work to drain all of ext4_free_data
3743 flush_work(&sbi->s_discard_work);
3744 WARN_ON_ONCE(!list_empty(&sbi->s_discard_list));
3747 if (sbi->s_group_info) {
3748 for (i = 0; i < ngroups; i++) {
3750 grinfo = ext4_get_group_info(sb, i);
3753 mb_group_bb_bitmap_free(grinfo);
3754 ext4_lock_group(sb, i);
3755 count = ext4_mb_cleanup_pa(grinfo);
3757 mb_debug(sb, "mballoc: %d PAs left\n",
3759 ext4_unlock_group(sb, i);
3760 kmem_cache_free(cachep, grinfo);
3762 num_meta_group_infos = (ngroups +
3763 EXT4_DESC_PER_BLOCK(sb) - 1) >>
3764 EXT4_DESC_PER_BLOCK_BITS(sb);
3766 group_info = rcu_dereference(sbi->s_group_info);
3767 for (i = 0; i < num_meta_group_infos; i++)
3768 kfree(group_info[i]);
3772 kfree(sbi->s_mb_avg_fragment_size);
3773 kfree(sbi->s_mb_avg_fragment_size_locks);
3774 kfree(sbi->s_mb_largest_free_orders);
3775 kfree(sbi->s_mb_largest_free_orders_locks);
3776 kfree(sbi->s_mb_offsets);
3777 kfree(sbi->s_mb_maxs);
3778 iput(sbi->s_buddy_cache);
3779 if (sbi->s_mb_stats) {
3780 ext4_msg(sb, KERN_INFO,
3781 "mballoc: %u blocks %u reqs (%u success)",
3782 atomic_read(&sbi->s_bal_allocated),
3783 atomic_read(&sbi->s_bal_reqs),
3784 atomic_read(&sbi->s_bal_success));
3785 ext4_msg(sb, KERN_INFO,
3786 "mballoc: %u extents scanned, %u groups scanned, %u goal hits, "
3787 "%u 2^N hits, %u breaks, %u lost",
3788 atomic_read(&sbi->s_bal_ex_scanned),
3789 atomic_read(&sbi->s_bal_groups_scanned),
3790 atomic_read(&sbi->s_bal_goals),
3791 atomic_read(&sbi->s_bal_2orders),
3792 atomic_read(&sbi->s_bal_breaks),
3793 atomic_read(&sbi->s_mb_lost_chunks));
3794 ext4_msg(sb, KERN_INFO,
3795 "mballoc: %u generated and it took %llu",
3796 atomic_read(&sbi->s_mb_buddies_generated),
3797 atomic64_read(&sbi->s_mb_generation_time));
3798 ext4_msg(sb, KERN_INFO,
3799 "mballoc: %u preallocated, %u discarded",
3800 atomic_read(&sbi->s_mb_preallocated),
3801 atomic_read(&sbi->s_mb_discarded));
3804 free_percpu(sbi->s_locality_groups);
3809 static inline int ext4_issue_discard(struct super_block *sb,
3810 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
3813 ext4_fsblk_t discard_block;
3815 discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
3816 ext4_group_first_block_no(sb, block_group));
3817 count = EXT4_C2B(EXT4_SB(sb), count);
3818 trace_ext4_discard_blocks(sb,
3819 (unsigned long long) discard_block, count);
3821 return __blkdev_issue_discard(sb->s_bdev,
3822 (sector_t)discard_block << (sb->s_blocksize_bits - 9),
3823 (sector_t)count << (sb->s_blocksize_bits - 9),
3826 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
3829 static void ext4_free_data_in_buddy(struct super_block *sb,
3830 struct ext4_free_data *entry)
3832 struct ext4_buddy e4b;
3833 struct ext4_group_info *db;
3836 mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
3837 entry->efd_count, entry->efd_group, entry);
3839 err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
3840 /* we expect to find existing buddy because it's pinned */
3843 spin_lock(&EXT4_SB(sb)->s_md_lock);
3844 EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
3845 spin_unlock(&EXT4_SB(sb)->s_md_lock);
3848 /* there are blocks to put in buddy to make them really free */
3849 count += entry->efd_count;
3850 ext4_lock_group(sb, entry->efd_group);
3851 /* Take it out of per group rb tree */
3852 rb_erase(&entry->efd_node, &(db->bb_free_root));
3853 mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
3856 * Clear the trimmed flag for the group so that the next
3857 * ext4_trim_fs can trim it.
3858 * If the volume is mounted with -o discard, online discard
3859 * is supported and the free blocks will be trimmed online.
3861 if (!test_opt(sb, DISCARD))
3862 EXT4_MB_GRP_CLEAR_TRIMMED(db);
3864 if (!db->bb_free_root.rb_node) {
3865 /* No more items in the per group rb tree
3866 * balance refcounts from ext4_mb_free_metadata()
3868 put_page(e4b.bd_buddy_page);
3869 put_page(e4b.bd_bitmap_page);
3871 ext4_unlock_group(sb, entry->efd_group);
3872 ext4_mb_unload_buddy(&e4b);
3874 mb_debug(sb, "freed %d blocks in 1 structures\n", count);
3878 * This function is called by the jbd2 layer once the commit has finished,
3879 * so we know we can free the blocks that were released with that commit.
3881 void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
3883 struct ext4_sb_info *sbi = EXT4_SB(sb);
3884 struct ext4_free_data *entry, *tmp;
3885 LIST_HEAD(freed_data_list);
3886 struct list_head *cut_pos = NULL;
3889 spin_lock(&sbi->s_md_lock);
3890 list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
3891 if (entry->efd_tid != commit_tid)
3893 cut_pos = &entry->efd_list;
3896 list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
3898 spin_unlock(&sbi->s_md_lock);
3900 list_for_each_entry(entry, &freed_data_list, efd_list)
3901 ext4_free_data_in_buddy(sb, entry);
3903 if (test_opt(sb, DISCARD)) {
3904 spin_lock(&sbi->s_md_lock);
3905 wake = list_empty(&sbi->s_discard_list);
3906 list_splice_tail(&freed_data_list, &sbi->s_discard_list);
3907 spin_unlock(&sbi->s_md_lock);
3909 queue_work(system_unbound_wq, &sbi->s_discard_work);
3911 list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
3912 kmem_cache_free(ext4_free_data_cachep, entry);
3916 int __init ext4_init_mballoc(void)
3918 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
3919 SLAB_RECLAIM_ACCOUNT);
3920 if (ext4_pspace_cachep == NULL)
3923 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
3924 SLAB_RECLAIM_ACCOUNT);
3925 if (ext4_ac_cachep == NULL)
3928 ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
3929 SLAB_RECLAIM_ACCOUNT);
3930 if (ext4_free_data_cachep == NULL)
3936 kmem_cache_destroy(ext4_ac_cachep);
3938 kmem_cache_destroy(ext4_pspace_cachep);
3943 void ext4_exit_mballoc(void)
3946 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
3947 * before destroying the slab cache.
3950 kmem_cache_destroy(ext4_pspace_cachep);
3951 kmem_cache_destroy(ext4_ac_cachep);
3952 kmem_cache_destroy(ext4_free_data_cachep);
3953 ext4_groupinfo_destroy_slabs();
3958 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
3959 * Returns 0 if success or error code
3961 static noinline_for_stack int
3962 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
3963 handle_t *handle, unsigned int reserv_clstrs)
3965 struct buffer_head *bitmap_bh = NULL;
3966 struct ext4_group_desc *gdp;
3967 struct buffer_head *gdp_bh;
3968 struct ext4_sb_info *sbi;
3969 struct super_block *sb;
3973 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3974 BUG_ON(ac->ac_b_ex.fe_len <= 0);
3979 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
3980 if (IS_ERR(bitmap_bh)) {
3981 return PTR_ERR(bitmap_bh);
3984 BUFFER_TRACE(bitmap_bh, "getting write access");
3985 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
3991 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3995 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
3996 ext4_free_group_clusters(sb, gdp));
3998 BUFFER_TRACE(gdp_bh, "get_write_access");
3999 err = ext4_journal_get_write_access(handle, sb, gdp_bh, EXT4_JTR_NONE);
4003 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4005 len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4006 if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
4007 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
4008 "fs metadata", block, block+len);
4009 /* File system mounted not to panic on error
4010 * Fix the bitmap and return EFSCORRUPTED
4011 * We leak some of the blocks here.
4013 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
4014 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
4015 ac->ac_b_ex.fe_len);
4016 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
4017 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4019 err = -EFSCORRUPTED;
4023 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
4024 #ifdef AGGRESSIVE_CHECK
4027 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
4028 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
4029 bitmap_bh->b_data));
4033 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
4034 ac->ac_b_ex.fe_len);
4035 if (ext4_has_group_desc_csum(sb) &&
4036 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
4037 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
4038 ext4_free_group_clusters_set(sb, gdp,
4039 ext4_free_clusters_after_init(sb,
4040 ac->ac_b_ex.fe_group, gdp));
4042 len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
4043 ext4_free_group_clusters_set(sb, gdp, len);
4044 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
4045 ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
4047 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
4048 percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
4050 * Now reduce the dirty block count also. Should not go negative
4052 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
4053 /* release all the reserved blocks if non delalloc */
4054 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4057 if (sbi->s_log_groups_per_flex) {
4058 ext4_group_t flex_group = ext4_flex_group(sbi,
4059 ac->ac_b_ex.fe_group);
4060 atomic64_sub(ac->ac_b_ex.fe_len,
4061 &sbi_array_rcu_deref(sbi, s_flex_groups,
4062 flex_group)->free_clusters);
4065 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4068 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
4076 * Idempotent helper for Ext4 fast commit replay path to set the state of
4077 * blocks in bitmaps and update counters.
4079 void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
4082 struct buffer_head *bitmap_bh = NULL;
4083 struct ext4_group_desc *gdp;
4084 struct buffer_head *gdp_bh;
4085 struct ext4_sb_info *sbi = EXT4_SB(sb);
4087 ext4_grpblk_t blkoff;
4090 unsigned int clen, clen_changed, thisgrp_len;
4093 ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
4096 * Check to see if we are freeing blocks across a group
4098 * In case of flex_bg, this can happen that (block, len) may
4099 * span across more than one group. In that case we need to
4100 * get the corresponding group metadata to work with.
4101 * For this we have goto again loop.
4103 thisgrp_len = min_t(unsigned int, (unsigned int)len,
4104 EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
4105 clen = EXT4_NUM_B2C(sbi, thisgrp_len);
4107 if (!ext4_sb_block_valid(sb, NULL, block, thisgrp_len)) {
4108 ext4_error(sb, "Marking blocks in system zone - "
4109 "Block = %llu, len = %u",
4110 block, thisgrp_len);
4115 bitmap_bh = ext4_read_block_bitmap(sb, group);
4116 if (IS_ERR(bitmap_bh)) {
4117 err = PTR_ERR(bitmap_bh);
4123 gdp = ext4_get_group_desc(sb, group, &gdp_bh);
4127 ext4_lock_group(sb, group);
4129 for (i = 0; i < clen; i++)
4130 if (!mb_test_bit(blkoff + i, bitmap_bh->b_data) ==
4134 clen_changed = clen - already;
4136 mb_set_bits(bitmap_bh->b_data, blkoff, clen);
4138 mb_clear_bits(bitmap_bh->b_data, blkoff, clen);
4139 if (ext4_has_group_desc_csum(sb) &&
4140 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
4141 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
4142 ext4_free_group_clusters_set(sb, gdp,
4143 ext4_free_clusters_after_init(sb, group, gdp));
4146 clen = ext4_free_group_clusters(sb, gdp) - clen_changed;
4148 clen = ext4_free_group_clusters(sb, gdp) + clen_changed;
4150 ext4_free_group_clusters_set(sb, gdp, clen);
4151 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
4152 ext4_group_desc_csum_set(sb, group, gdp);
4154 ext4_unlock_group(sb, group);
4156 if (sbi->s_log_groups_per_flex) {
4157 ext4_group_t flex_group = ext4_flex_group(sbi, group);
4158 struct flex_groups *fg = sbi_array_rcu_deref(sbi,
4159 s_flex_groups, flex_group);
4162 atomic64_sub(clen_changed, &fg->free_clusters);
4164 atomic64_add(clen_changed, &fg->free_clusters);
4168 err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
4171 sync_dirty_buffer(bitmap_bh);
4172 err = ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
4173 sync_dirty_buffer(gdp_bh);
4177 block += thisgrp_len;
4188 * here we normalize request for locality group
4189 * Group request are normalized to s_mb_group_prealloc, which goes to
4190 * s_strip if we set the same via mount option.
4191 * s_mb_group_prealloc can be configured via
4192 * /sys/fs/ext4/<partition>/mb_group_prealloc
4194 * XXX: should we try to preallocate more than the group has now?
4196 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
4198 struct super_block *sb = ac->ac_sb;
4199 struct ext4_locality_group *lg = ac->ac_lg;
4202 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
4203 mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
4207 * This function returns the next element to look at during inode
4208 * PA rbtree walk. We assume that we have held the inode PA rbtree lock
4209 * (ei->i_prealloc_lock)
4211 * new_start The start of the range we want to compare
4212 * cur_start The existing start that we are comparing against
4213 * node The node of the rb_tree
4215 static inline struct rb_node*
4216 ext4_mb_pa_rb_next_iter(ext4_lblk_t new_start, ext4_lblk_t cur_start, struct rb_node *node)
4218 if (new_start < cur_start)
4219 return node->rb_left;
4221 return node->rb_right;
4225 ext4_mb_pa_assert_overlap(struct ext4_allocation_context *ac,
4226 ext4_lblk_t start, loff_t end)
4228 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4229 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4230 struct ext4_prealloc_space *tmp_pa;
4231 ext4_lblk_t tmp_pa_start;
4233 struct rb_node *iter;
4235 read_lock(&ei->i_prealloc_lock);
4236 for (iter = ei->i_prealloc_node.rb_node; iter;
4237 iter = ext4_mb_pa_rb_next_iter(start, tmp_pa_start, iter)) {
4238 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4239 pa_node.inode_node);
4240 tmp_pa_start = tmp_pa->pa_lstart;
4241 tmp_pa_end = pa_logical_end(sbi, tmp_pa);
4243 spin_lock(&tmp_pa->pa_lock);
4244 if (tmp_pa->pa_deleted == 0)
4245 BUG_ON(!(start >= tmp_pa_end || end <= tmp_pa_start));
4246 spin_unlock(&tmp_pa->pa_lock);
4248 read_unlock(&ei->i_prealloc_lock);
4252 * Given an allocation context "ac" and a range "start", "end", check
4253 * and adjust boundaries if the range overlaps with any of the existing
4254 * preallocatoins stored in the corresponding inode of the allocation context.
4257 * ac allocation context
4258 * start start of the new range
4259 * end end of the new range
4262 ext4_mb_pa_adjust_overlap(struct ext4_allocation_context *ac,
4263 ext4_lblk_t *start, loff_t *end)
4265 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4266 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4267 struct ext4_prealloc_space *tmp_pa = NULL, *left_pa = NULL, *right_pa = NULL;
4268 struct rb_node *iter;
4269 ext4_lblk_t new_start, tmp_pa_start, right_pa_start = -1;
4270 loff_t new_end, tmp_pa_end, left_pa_end = -1;
4276 * Adjust the normalized range so that it doesn't overlap with any
4277 * existing preallocated blocks(PAs). Make sure to hold the rbtree lock
4278 * so it doesn't change underneath us.
4280 read_lock(&ei->i_prealloc_lock);
4282 /* Step 1: find any one immediate neighboring PA of the normalized range */
4283 for (iter = ei->i_prealloc_node.rb_node; iter;
4284 iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
4285 tmp_pa_start, iter)) {
4286 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4287 pa_node.inode_node);
4288 tmp_pa_start = tmp_pa->pa_lstart;
4289 tmp_pa_end = pa_logical_end(sbi, tmp_pa);
4291 /* PA must not overlap original request */
4292 spin_lock(&tmp_pa->pa_lock);
4293 if (tmp_pa->pa_deleted == 0)
4294 BUG_ON(!(ac->ac_o_ex.fe_logical >= tmp_pa_end ||
4295 ac->ac_o_ex.fe_logical < tmp_pa_start));
4296 spin_unlock(&tmp_pa->pa_lock);
4300 * Step 2: check if the found PA is left or right neighbor and
4301 * get the other neighbor
4304 if (tmp_pa->pa_lstart < ac->ac_o_ex.fe_logical) {
4305 struct rb_node *tmp;
4308 tmp = rb_next(&left_pa->pa_node.inode_node);
4310 right_pa = rb_entry(tmp,
4311 struct ext4_prealloc_space,
4312 pa_node.inode_node);
4315 struct rb_node *tmp;
4318 tmp = rb_prev(&right_pa->pa_node.inode_node);
4320 left_pa = rb_entry(tmp,
4321 struct ext4_prealloc_space,
4322 pa_node.inode_node);
4327 /* Step 3: get the non deleted neighbors */
4329 for (iter = &left_pa->pa_node.inode_node;;
4330 iter = rb_prev(iter)) {
4336 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4337 pa_node.inode_node);
4339 spin_lock(&tmp_pa->pa_lock);
4340 if (tmp_pa->pa_deleted == 0) {
4341 spin_unlock(&tmp_pa->pa_lock);
4344 spin_unlock(&tmp_pa->pa_lock);
4349 for (iter = &right_pa->pa_node.inode_node;;
4350 iter = rb_next(iter)) {
4356 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4357 pa_node.inode_node);
4359 spin_lock(&tmp_pa->pa_lock);
4360 if (tmp_pa->pa_deleted == 0) {
4361 spin_unlock(&tmp_pa->pa_lock);
4364 spin_unlock(&tmp_pa->pa_lock);
4369 left_pa_end = pa_logical_end(sbi, left_pa);
4370 BUG_ON(left_pa_end > ac->ac_o_ex.fe_logical);
4374 right_pa_start = right_pa->pa_lstart;
4375 BUG_ON(right_pa_start <= ac->ac_o_ex.fe_logical);
4378 /* Step 4: trim our normalized range to not overlap with the neighbors */
4380 if (left_pa_end > new_start)
4381 new_start = left_pa_end;
4385 if (right_pa_start < new_end)
4386 new_end = right_pa_start;
4388 read_unlock(&ei->i_prealloc_lock);
4390 /* XXX: extra loop to check we really don't overlap preallocations */
4391 ext4_mb_pa_assert_overlap(ac, new_start, new_end);
4398 * Normalization means making request better in terms of
4399 * size and alignment
4401 static noinline_for_stack void
4402 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
4403 struct ext4_allocation_request *ar)
4405 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4406 struct ext4_super_block *es = sbi->s_es;
4408 loff_t size, start_off, end;
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 = extent_logical_end(sbi, &ac->ac_o_ex);
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;
4769 struct rb_node *iter;
4770 ext4_fsblk_t goal_block;
4772 /* only data can be preallocated */
4773 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4777 * first, try per-file preallocation by searching the inode pa rbtree.
4779 * Here, we can't do a direct traversal of the tree because
4780 * ext4_mb_discard_group_preallocation() can paralelly mark the pa
4781 * deleted and that can cause direct traversal to skip some entries.
4783 read_lock(&ei->i_prealloc_lock);
4785 if (RB_EMPTY_ROOT(&ei->i_prealloc_node)) {
4790 * Step 1: Find a pa with logical start immediately adjacent to the
4791 * original logical start. This could be on the left or right.
4793 * (tmp_pa->pa_lstart never changes so we can skip locking for it).
4795 for (iter = ei->i_prealloc_node.rb_node; iter;
4796 iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
4797 tmp_pa->pa_lstart, iter)) {
4798 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4799 pa_node.inode_node);
4803 * Step 2: The adjacent pa might be to the right of logical start, find
4804 * the left adjacent pa. After this step we'd have a valid tmp_pa whose
4805 * logical start is towards the left of original request's logical start
4807 if (tmp_pa->pa_lstart > ac->ac_o_ex.fe_logical) {
4808 struct rb_node *tmp;
4809 tmp = rb_prev(&tmp_pa->pa_node.inode_node);
4812 tmp_pa = rb_entry(tmp, struct ext4_prealloc_space,
4813 pa_node.inode_node);
4816 * If there is no adjacent pa to the left then finding
4817 * an overlapping pa is not possible hence stop searching
4824 BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
4827 * Step 3: If the left adjacent pa is deleted, keep moving left to find
4828 * the first non deleted adjacent pa. After this step we should have a
4829 * valid tmp_pa which is guaranteed to be non deleted.
4831 for (iter = &tmp_pa->pa_node.inode_node;; iter = rb_prev(iter)) {
4834 * no non deleted left adjacent pa, so stop searching
4839 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4840 pa_node.inode_node);
4841 spin_lock(&tmp_pa->pa_lock);
4842 if (tmp_pa->pa_deleted == 0) {
4844 * We will keep holding the pa_lock from
4845 * this point on because we don't want group discard
4846 * to delete this pa underneath us. Since group
4847 * discard is anyways an ENOSPC operation it
4848 * should be okay for it to wait a few more cycles.
4852 spin_unlock(&tmp_pa->pa_lock);
4856 BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
4857 BUG_ON(tmp_pa->pa_deleted == 1);
4860 * Step 4: We now have the non deleted left adjacent pa. Only this
4861 * pa can possibly satisfy the request hence check if it overlaps
4862 * original logical start and stop searching if it doesn't.
4864 if (ac->ac_o_ex.fe_logical >= pa_logical_end(sbi, tmp_pa)) {
4865 spin_unlock(&tmp_pa->pa_lock);
4869 /* non-extent files can't have physical blocks past 2^32 */
4870 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
4871 (tmp_pa->pa_pstart + EXT4_C2B(sbi, tmp_pa->pa_len) >
4872 EXT4_MAX_BLOCK_FILE_PHYS)) {
4874 * Since PAs don't overlap, we won't find any other PA to
4877 spin_unlock(&tmp_pa->pa_lock);
4881 if (tmp_pa->pa_free && likely(ext4_mb_pa_goal_check(ac, tmp_pa))) {
4882 atomic_inc(&tmp_pa->pa_count);
4883 ext4_mb_use_inode_pa(ac, tmp_pa);
4884 spin_unlock(&tmp_pa->pa_lock);
4885 read_unlock(&ei->i_prealloc_lock);
4889 * We found a valid overlapping pa but couldn't use it because
4890 * it had no free blocks. This should ideally never happen
4893 * 1. When a new inode pa is added to rbtree it must have
4894 * pa_free > 0 since otherwise we won't actually need
4897 * 2. An inode pa that is in the rbtree can only have it's
4898 * pa_free become zero when another thread calls:
4899 * ext4_mb_new_blocks
4900 * ext4_mb_use_preallocated
4901 * ext4_mb_use_inode_pa
4903 * 3. Further, after the above calls make pa_free == 0, we will
4904 * immediately remove it from the rbtree in:
4905 * ext4_mb_new_blocks
4906 * ext4_mb_release_context
4909 * 4. Since the pa_free becoming 0 and pa_free getting removed
4910 * from tree both happen in ext4_mb_new_blocks, which is always
4911 * called with i_data_sem held for data allocations, we can be
4912 * sure that another process will never see a pa in rbtree with
4915 WARN_ON_ONCE(tmp_pa->pa_free == 0);
4917 spin_unlock(&tmp_pa->pa_lock);
4919 read_unlock(&ei->i_prealloc_lock);
4921 /* can we use group allocation? */
4922 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
4925 /* inode may have no locality group for some reason */
4929 order = fls(ac->ac_o_ex.fe_len) - 1;
4930 if (order > PREALLOC_TB_SIZE - 1)
4931 /* The max size of hash table is PREALLOC_TB_SIZE */
4932 order = PREALLOC_TB_SIZE - 1;
4934 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
4936 * search for the prealloc space that is having
4937 * minimal distance from the goal block.
4939 for (i = order; i < PREALLOC_TB_SIZE; i++) {
4941 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[i],
4943 spin_lock(&tmp_pa->pa_lock);
4944 if (tmp_pa->pa_deleted == 0 &&
4945 tmp_pa->pa_free >= ac->ac_o_ex.fe_len) {
4947 cpa = ext4_mb_check_group_pa(goal_block,
4950 spin_unlock(&tmp_pa->pa_lock);
4955 ext4_mb_use_group_pa(ac, cpa);
4962 * the function goes through all block freed in the group
4963 * but not yet committed and marks them used in in-core bitmap.
4964 * buddy must be generated from this bitmap
4965 * Need to be called with the ext4 group lock held
4967 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
4971 struct ext4_group_info *grp;
4972 struct ext4_free_data *entry;
4974 grp = ext4_get_group_info(sb, group);
4977 n = rb_first(&(grp->bb_free_root));
4980 entry = rb_entry(n, struct ext4_free_data, efd_node);
4981 mb_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
4987 * the function goes through all preallocation in this group and marks them
4988 * used in in-core bitmap. buddy must be generated from this bitmap
4989 * Need to be called with ext4 group lock held
4991 static noinline_for_stack
4992 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
4995 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
4996 struct ext4_prealloc_space *pa;
4997 struct list_head *cur;
4998 ext4_group_t groupnr;
4999 ext4_grpblk_t start;
5000 int preallocated = 0;
5006 /* all form of preallocation discards first load group,
5007 * so the only competing code is preallocation use.
5008 * we don't need any locking here
5009 * notice we do NOT ignore preallocations with pa_deleted
5010 * otherwise we could leave used blocks available for
5011 * allocation in buddy when concurrent ext4_mb_put_pa()
5012 * is dropping preallocation
5014 list_for_each(cur, &grp->bb_prealloc_list) {
5015 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
5016 spin_lock(&pa->pa_lock);
5017 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5020 spin_unlock(&pa->pa_lock);
5021 if (unlikely(len == 0))
5023 BUG_ON(groupnr != group);
5024 mb_set_bits(bitmap, start, len);
5025 preallocated += len;
5027 mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
5030 static void ext4_mb_mark_pa_deleted(struct super_block *sb,
5031 struct ext4_prealloc_space *pa)
5033 struct ext4_inode_info *ei;
5035 if (pa->pa_deleted) {
5036 ext4_warning(sb, "deleted pa, type:%d, pblk:%llu, lblk:%u, len:%d\n",
5037 pa->pa_type, pa->pa_pstart, pa->pa_lstart,
5044 if (pa->pa_type == MB_INODE_PA) {
5045 ei = EXT4_I(pa->pa_inode);
5046 atomic_dec(&ei->i_prealloc_active);
5050 static inline void ext4_mb_pa_free(struct ext4_prealloc_space *pa)
5053 BUG_ON(atomic_read(&pa->pa_count));
5054 BUG_ON(pa->pa_deleted == 0);
5055 kmem_cache_free(ext4_pspace_cachep, pa);
5058 static void ext4_mb_pa_callback(struct rcu_head *head)
5060 struct ext4_prealloc_space *pa;
5062 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
5063 ext4_mb_pa_free(pa);
5067 * drops a reference to preallocated space descriptor
5068 * if this was the last reference and the space is consumed
5070 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
5071 struct super_block *sb, struct ext4_prealloc_space *pa)
5074 ext4_fsblk_t grp_blk;
5075 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
5077 /* in this short window concurrent discard can set pa_deleted */
5078 spin_lock(&pa->pa_lock);
5079 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
5080 spin_unlock(&pa->pa_lock);
5084 if (pa->pa_deleted == 1) {
5085 spin_unlock(&pa->pa_lock);
5089 ext4_mb_mark_pa_deleted(sb, pa);
5090 spin_unlock(&pa->pa_lock);
5092 grp_blk = pa->pa_pstart;
5094 * If doing group-based preallocation, pa_pstart may be in the
5095 * next group when pa is used up
5097 if (pa->pa_type == MB_GROUP_PA)
5100 grp = ext4_get_group_number(sb, grp_blk);
5105 * P1 (buddy init) P2 (regular allocation)
5106 * find block B in PA
5107 * copy on-disk bitmap to buddy
5108 * mark B in on-disk bitmap
5109 * drop PA from group
5110 * mark all PAs in buddy
5112 * thus, P1 initializes buddy with B available. to prevent this
5113 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
5116 ext4_lock_group(sb, grp);
5117 list_del(&pa->pa_group_list);
5118 ext4_unlock_group(sb, grp);
5120 if (pa->pa_type == MB_INODE_PA) {
5121 write_lock(pa->pa_node_lock.inode_lock);
5122 rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5123 write_unlock(pa->pa_node_lock.inode_lock);
5124 ext4_mb_pa_free(pa);
5126 spin_lock(pa->pa_node_lock.lg_lock);
5127 list_del_rcu(&pa->pa_node.lg_list);
5128 spin_unlock(pa->pa_node_lock.lg_lock);
5129 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5133 static void ext4_mb_pa_rb_insert(struct rb_root *root, struct rb_node *new)
5135 struct rb_node **iter = &root->rb_node, *parent = NULL;
5136 struct ext4_prealloc_space *iter_pa, *new_pa;
5137 ext4_lblk_t iter_start, new_start;
5140 iter_pa = rb_entry(*iter, struct ext4_prealloc_space,
5141 pa_node.inode_node);
5142 new_pa = rb_entry(new, struct ext4_prealloc_space,
5143 pa_node.inode_node);
5144 iter_start = iter_pa->pa_lstart;
5145 new_start = new_pa->pa_lstart;
5148 if (new_start < iter_start)
5149 iter = &((*iter)->rb_left);
5151 iter = &((*iter)->rb_right);
5154 rb_link_node(new, parent, iter);
5155 rb_insert_color(new, root);
5159 * creates new preallocated space for given inode
5161 static noinline_for_stack void
5162 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
5164 struct super_block *sb = ac->ac_sb;
5165 struct ext4_sb_info *sbi = EXT4_SB(sb);
5166 struct ext4_prealloc_space *pa;
5167 struct ext4_group_info *grp;
5168 struct ext4_inode_info *ei;
5170 /* preallocate only when found space is larger then requested */
5171 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5172 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5173 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
5174 BUG_ON(ac->ac_pa == NULL);
5178 if (ac->ac_b_ex.fe_len < ac->ac_orig_goal_len) {
5179 struct ext4_free_extent ex = {
5180 .fe_logical = ac->ac_g_ex.fe_logical,
5181 .fe_len = ac->ac_orig_goal_len,
5183 loff_t orig_goal_end = extent_logical_end(sbi, &ex);
5185 /* we can't allocate as much as normalizer wants.
5186 * so, found space must get proper lstart
5187 * to cover original request */
5188 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
5189 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
5192 * Use the below logic for adjusting best extent as it keeps
5193 * fragmentation in check while ensuring logical range of best
5194 * extent doesn't overflow out of goal extent:
5196 * 1. Check if best ex can be kept at end of goal (before
5197 * cr_best_avail trimmed it) and still cover original start
5198 * 2. Else, check if best ex can be kept at start of goal and
5199 * still cover original start
5200 * 3. Else, keep the best ex at start of original request.
5202 ex.fe_len = ac->ac_b_ex.fe_len;
5204 ex.fe_logical = orig_goal_end - EXT4_C2B(sbi, ex.fe_len);
5205 if (ac->ac_o_ex.fe_logical >= ex.fe_logical)
5208 ex.fe_logical = ac->ac_g_ex.fe_logical;
5209 if (ac->ac_o_ex.fe_logical < extent_logical_end(sbi, &ex))
5212 ex.fe_logical = ac->ac_o_ex.fe_logical;
5214 ac->ac_b_ex.fe_logical = ex.fe_logical;
5216 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
5217 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
5218 BUG_ON(extent_logical_end(sbi, &ex) > orig_goal_end);
5221 pa->pa_lstart = ac->ac_b_ex.fe_logical;
5222 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5223 pa->pa_len = ac->ac_b_ex.fe_len;
5224 pa->pa_free = pa->pa_len;
5225 spin_lock_init(&pa->pa_lock);
5226 INIT_LIST_HEAD(&pa->pa_group_list);
5228 pa->pa_type = MB_INODE_PA;
5230 mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5231 pa->pa_len, pa->pa_lstart);
5232 trace_ext4_mb_new_inode_pa(ac, pa);
5234 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
5235 ext4_mb_use_inode_pa(ac, pa);
5237 ei = EXT4_I(ac->ac_inode);
5238 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
5242 pa->pa_node_lock.inode_lock = &ei->i_prealloc_lock;
5243 pa->pa_inode = ac->ac_inode;
5245 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5247 write_lock(pa->pa_node_lock.inode_lock);
5248 ext4_mb_pa_rb_insert(&ei->i_prealloc_node, &pa->pa_node.inode_node);
5249 write_unlock(pa->pa_node_lock.inode_lock);
5250 atomic_inc(&ei->i_prealloc_active);
5254 * creates new preallocated space for locality group inodes belongs to
5256 static noinline_for_stack void
5257 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
5259 struct super_block *sb = ac->ac_sb;
5260 struct ext4_locality_group *lg;
5261 struct ext4_prealloc_space *pa;
5262 struct ext4_group_info *grp;
5264 /* preallocate only when found space is larger then requested */
5265 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
5266 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
5267 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
5268 BUG_ON(ac->ac_pa == NULL);
5272 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5273 pa->pa_lstart = pa->pa_pstart;
5274 pa->pa_len = ac->ac_b_ex.fe_len;
5275 pa->pa_free = pa->pa_len;
5276 spin_lock_init(&pa->pa_lock);
5277 INIT_LIST_HEAD(&pa->pa_node.lg_list);
5278 INIT_LIST_HEAD(&pa->pa_group_list);
5280 pa->pa_type = MB_GROUP_PA;
5282 mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
5283 pa->pa_len, pa->pa_lstart);
5284 trace_ext4_mb_new_group_pa(ac, pa);
5286 ext4_mb_use_group_pa(ac, pa);
5287 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
5289 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
5295 pa->pa_node_lock.lg_lock = &lg->lg_prealloc_lock;
5296 pa->pa_inode = NULL;
5298 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
5301 * We will later add the new pa to the right bucket
5302 * after updating the pa_free in ext4_mb_release_context
5306 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
5308 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
5309 ext4_mb_new_group_pa(ac);
5311 ext4_mb_new_inode_pa(ac);
5315 * finds all unused blocks in on-disk bitmap, frees them in
5316 * in-core bitmap and buddy.
5317 * @pa must be unlinked from inode and group lists, so that
5318 * nobody else can find/use it.
5319 * the caller MUST hold group/inode locks.
5320 * TODO: optimize the case when there are no in-core structures yet
5322 static noinline_for_stack int
5323 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
5324 struct ext4_prealloc_space *pa)
5326 struct super_block *sb = e4b->bd_sb;
5327 struct ext4_sb_info *sbi = EXT4_SB(sb);
5332 unsigned long long grp_blk_start;
5335 BUG_ON(pa->pa_deleted == 0);
5336 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
5337 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
5338 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
5339 end = bit + pa->pa_len;
5342 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
5345 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
5346 mb_debug(sb, "free preallocated %u/%u in group %u\n",
5347 (unsigned) ext4_group_first_block_no(sb, group) + bit,
5348 (unsigned) next - bit, (unsigned) group);
5351 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
5352 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
5353 EXT4_C2B(sbi, bit)),
5355 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
5358 if (free != pa->pa_free) {
5359 ext4_msg(e4b->bd_sb, KERN_CRIT,
5360 "pa %p: logic %lu, phys. %lu, len %d",
5361 pa, (unsigned long) pa->pa_lstart,
5362 (unsigned long) pa->pa_pstart,
5364 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
5367 * pa is already deleted so we use the value obtained
5368 * from the bitmap and continue.
5371 atomic_add(free, &sbi->s_mb_discarded);
5376 static noinline_for_stack int
5377 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
5378 struct ext4_prealloc_space *pa)
5380 struct super_block *sb = e4b->bd_sb;
5384 trace_ext4_mb_release_group_pa(sb, pa);
5385 BUG_ON(pa->pa_deleted == 0);
5386 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
5387 if (unlikely(group != e4b->bd_group && pa->pa_len != 0)) {
5388 ext4_warning(sb, "bad group: expected %u, group %u, pa_start %llu",
5389 e4b->bd_group, group, pa->pa_pstart);
5392 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
5393 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
5394 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
5400 * releases all preallocations in given group
5402 * first, we need to decide discard policy:
5403 * - when do we discard
5405 * - how many do we discard
5406 * 1) how many requested
5408 static noinline_for_stack int
5409 ext4_mb_discard_group_preallocations(struct super_block *sb,
5410 ext4_group_t group, int *busy)
5412 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
5413 struct buffer_head *bitmap_bh = NULL;
5414 struct ext4_prealloc_space *pa, *tmp;
5416 struct ext4_buddy e4b;
5417 struct ext4_inode_info *ei;
5423 mb_debug(sb, "discard preallocation for group %u\n", group);
5424 if (list_empty(&grp->bb_prealloc_list))
5427 bitmap_bh = ext4_read_block_bitmap(sb, group);
5428 if (IS_ERR(bitmap_bh)) {
5429 err = PTR_ERR(bitmap_bh);
5430 ext4_error_err(sb, -err,
5431 "Error %d reading block bitmap for %u",
5436 err = ext4_mb_load_buddy(sb, group, &e4b);
5438 ext4_warning(sb, "Error %d loading buddy information for %u",
5444 ext4_lock_group(sb, group);
5445 list_for_each_entry_safe(pa, tmp,
5446 &grp->bb_prealloc_list, pa_group_list) {
5447 spin_lock(&pa->pa_lock);
5448 if (atomic_read(&pa->pa_count)) {
5449 spin_unlock(&pa->pa_lock);
5453 if (pa->pa_deleted) {
5454 spin_unlock(&pa->pa_lock);
5458 /* seems this one can be freed ... */
5459 ext4_mb_mark_pa_deleted(sb, pa);
5462 this_cpu_inc(discard_pa_seq);
5464 /* we can trust pa_free ... */
5465 free += pa->pa_free;
5467 spin_unlock(&pa->pa_lock);
5469 list_del(&pa->pa_group_list);
5470 list_add(&pa->u.pa_tmp_list, &list);
5473 /* now free all selected PAs */
5474 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5476 /* remove from object (inode or locality group) */
5477 if (pa->pa_type == MB_GROUP_PA) {
5478 spin_lock(pa->pa_node_lock.lg_lock);
5479 list_del_rcu(&pa->pa_node.lg_list);
5480 spin_unlock(pa->pa_node_lock.lg_lock);
5482 write_lock(pa->pa_node_lock.inode_lock);
5483 ei = EXT4_I(pa->pa_inode);
5484 rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5485 write_unlock(pa->pa_node_lock.inode_lock);
5488 list_del(&pa->u.pa_tmp_list);
5490 if (pa->pa_type == MB_GROUP_PA) {
5491 ext4_mb_release_group_pa(&e4b, pa);
5492 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5494 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
5495 ext4_mb_pa_free(pa);
5499 ext4_unlock_group(sb, group);
5500 ext4_mb_unload_buddy(&e4b);
5503 mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
5504 free, group, grp->bb_free);
5509 * releases all non-used preallocated blocks for given inode
5511 * It's important to discard preallocations under i_data_sem
5512 * We don't want another block to be served from the prealloc
5513 * space when we are discarding the inode prealloc space.
5515 * FIXME!! Make sure it is valid at all the call sites
5517 void ext4_discard_preallocations(struct inode *inode, unsigned int needed)
5519 struct ext4_inode_info *ei = EXT4_I(inode);
5520 struct super_block *sb = inode->i_sb;
5521 struct buffer_head *bitmap_bh = NULL;
5522 struct ext4_prealloc_space *pa, *tmp;
5523 ext4_group_t group = 0;
5525 struct ext4_buddy e4b;
5526 struct rb_node *iter;
5529 if (!S_ISREG(inode->i_mode)) {
5533 if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
5536 mb_debug(sb, "discard preallocation for inode %lu\n",
5538 trace_ext4_discard_preallocations(inode,
5539 atomic_read(&ei->i_prealloc_active), needed);
5545 /* first, collect all pa's in the inode */
5546 write_lock(&ei->i_prealloc_lock);
5547 for (iter = rb_first(&ei->i_prealloc_node); iter && needed;
5548 iter = rb_next(iter)) {
5549 pa = rb_entry(iter, struct ext4_prealloc_space,
5550 pa_node.inode_node);
5551 BUG_ON(pa->pa_node_lock.inode_lock != &ei->i_prealloc_lock);
5553 spin_lock(&pa->pa_lock);
5554 if (atomic_read(&pa->pa_count)) {
5555 /* this shouldn't happen often - nobody should
5556 * use preallocation while we're discarding it */
5557 spin_unlock(&pa->pa_lock);
5558 write_unlock(&ei->i_prealloc_lock);
5559 ext4_msg(sb, KERN_ERR,
5560 "uh-oh! used pa while discarding");
5562 schedule_timeout_uninterruptible(HZ);
5566 if (pa->pa_deleted == 0) {
5567 ext4_mb_mark_pa_deleted(sb, pa);
5568 spin_unlock(&pa->pa_lock);
5569 rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5570 list_add(&pa->u.pa_tmp_list, &list);
5575 /* someone is deleting pa right now */
5576 spin_unlock(&pa->pa_lock);
5577 write_unlock(&ei->i_prealloc_lock);
5579 /* we have to wait here because pa_deleted
5580 * doesn't mean pa is already unlinked from
5581 * the list. as we might be called from
5582 * ->clear_inode() the inode will get freed
5583 * and concurrent thread which is unlinking
5584 * pa from inode's list may access already
5585 * freed memory, bad-bad-bad */
5587 /* XXX: if this happens too often, we can
5588 * add a flag to force wait only in case
5589 * of ->clear_inode(), but not in case of
5590 * regular truncate */
5591 schedule_timeout_uninterruptible(HZ);
5594 write_unlock(&ei->i_prealloc_lock);
5596 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5597 BUG_ON(pa->pa_type != MB_INODE_PA);
5598 group = ext4_get_group_number(sb, pa->pa_pstart);
5600 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
5601 GFP_NOFS|__GFP_NOFAIL);
5603 ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
5608 bitmap_bh = ext4_read_block_bitmap(sb, group);
5609 if (IS_ERR(bitmap_bh)) {
5610 err = PTR_ERR(bitmap_bh);
5611 ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
5613 ext4_mb_unload_buddy(&e4b);
5617 ext4_lock_group(sb, group);
5618 list_del(&pa->pa_group_list);
5619 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
5620 ext4_unlock_group(sb, group);
5622 ext4_mb_unload_buddy(&e4b);
5625 list_del(&pa->u.pa_tmp_list);
5626 ext4_mb_pa_free(pa);
5630 static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
5632 struct ext4_prealloc_space *pa;
5634 BUG_ON(ext4_pspace_cachep == NULL);
5635 pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
5638 atomic_set(&pa->pa_count, 1);
5643 static void ext4_mb_pa_put_free(struct ext4_allocation_context *ac)
5645 struct ext4_prealloc_space *pa = ac->ac_pa;
5649 WARN_ON(!atomic_dec_and_test(&pa->pa_count));
5651 * current function is only called due to an error or due to
5652 * len of found blocks < len of requested blocks hence the PA has not
5653 * been added to grp->bb_prealloc_list. So we don't need to lock it
5656 ext4_mb_pa_free(pa);
5659 #ifdef CONFIG_EXT4_DEBUG
5660 static inline void ext4_mb_show_pa(struct super_block *sb)
5662 ext4_group_t i, ngroups;
5664 if (ext4_forced_shutdown(sb))
5667 ngroups = ext4_get_groups_count(sb);
5668 mb_debug(sb, "groups: ");
5669 for (i = 0; i < ngroups; i++) {
5670 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
5671 struct ext4_prealloc_space *pa;
5672 ext4_grpblk_t start;
5673 struct list_head *cur;
5677 ext4_lock_group(sb, i);
5678 list_for_each(cur, &grp->bb_prealloc_list) {
5679 pa = list_entry(cur, struct ext4_prealloc_space,
5681 spin_lock(&pa->pa_lock);
5682 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5684 spin_unlock(&pa->pa_lock);
5685 mb_debug(sb, "PA:%u:%d:%d\n", i, start,
5688 ext4_unlock_group(sb, i);
5689 mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
5694 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5696 struct super_block *sb = ac->ac_sb;
5698 if (ext4_forced_shutdown(sb))
5701 mb_debug(sb, "Can't allocate:"
5702 " Allocation context details:");
5703 mb_debug(sb, "status %u flags 0x%x",
5704 ac->ac_status, ac->ac_flags);
5705 mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
5706 "goal %lu/%lu/%lu@%lu, "
5707 "best %lu/%lu/%lu@%lu cr %d",
5708 (unsigned long)ac->ac_o_ex.fe_group,
5709 (unsigned long)ac->ac_o_ex.fe_start,
5710 (unsigned long)ac->ac_o_ex.fe_len,
5711 (unsigned long)ac->ac_o_ex.fe_logical,
5712 (unsigned long)ac->ac_g_ex.fe_group,
5713 (unsigned long)ac->ac_g_ex.fe_start,
5714 (unsigned long)ac->ac_g_ex.fe_len,
5715 (unsigned long)ac->ac_g_ex.fe_logical,
5716 (unsigned long)ac->ac_b_ex.fe_group,
5717 (unsigned long)ac->ac_b_ex.fe_start,
5718 (unsigned long)ac->ac_b_ex.fe_len,
5719 (unsigned long)ac->ac_b_ex.fe_logical,
5720 (int)ac->ac_criteria);
5721 mb_debug(sb, "%u found", ac->ac_found);
5722 mb_debug(sb, "used pa: %s, ", ac->ac_pa ? "yes" : "no");
5724 mb_debug(sb, "pa_type %s\n", ac->ac_pa->pa_type == MB_GROUP_PA ?
5725 "group pa" : "inode pa");
5726 ext4_mb_show_pa(sb);
5729 static inline void ext4_mb_show_pa(struct super_block *sb)
5732 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5734 ext4_mb_show_pa(ac->ac_sb);
5739 * We use locality group preallocation for small size file. The size of the
5740 * file is determined by the current size or the resulting size after
5741 * allocation which ever is larger
5743 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
5745 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
5747 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
5748 int bsbits = ac->ac_sb->s_blocksize_bits;
5750 bool inode_pa_eligible, group_pa_eligible;
5752 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
5755 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
5758 group_pa_eligible = sbi->s_mb_group_prealloc > 0;
5759 inode_pa_eligible = true;
5760 size = extent_logical_end(sbi, &ac->ac_o_ex);
5761 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
5764 /* No point in using inode preallocation for closed files */
5765 if ((size == isize) && !ext4_fs_is_busy(sbi) &&
5766 !inode_is_open_for_write(ac->ac_inode))
5767 inode_pa_eligible = false;
5769 size = max(size, isize);
5770 /* Don't use group allocation for large files */
5771 if (size > sbi->s_mb_stream_request)
5772 group_pa_eligible = false;
5774 if (!group_pa_eligible) {
5775 if (inode_pa_eligible)
5776 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
5778 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
5782 BUG_ON(ac->ac_lg != NULL);
5784 * locality group prealloc space are per cpu. The reason for having
5785 * per cpu locality group is to reduce the contention between block
5786 * request from multiple CPUs.
5788 ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
5790 /* we're going to use group allocation */
5791 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
5793 /* serialize all allocations in the group */
5794 mutex_lock(&ac->ac_lg->lg_mutex);
5797 static noinline_for_stack void
5798 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
5799 struct ext4_allocation_request *ar)
5801 struct super_block *sb = ar->inode->i_sb;
5802 struct ext4_sb_info *sbi = EXT4_SB(sb);
5803 struct ext4_super_block *es = sbi->s_es;
5807 ext4_grpblk_t block;
5809 /* we can't allocate > group size */
5812 /* just a dirty hack to filter too big requests */
5813 if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
5814 len = EXT4_CLUSTERS_PER_GROUP(sb);
5816 /* start searching from the goal */
5818 if (goal < le32_to_cpu(es->s_first_data_block) ||
5819 goal >= ext4_blocks_count(es))
5820 goal = le32_to_cpu(es->s_first_data_block);
5821 ext4_get_group_no_and_offset(sb, goal, &group, &block);
5823 /* set up allocation goals */
5824 ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
5825 ac->ac_status = AC_STATUS_CONTINUE;
5827 ac->ac_inode = ar->inode;
5828 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
5829 ac->ac_o_ex.fe_group = group;
5830 ac->ac_o_ex.fe_start = block;
5831 ac->ac_o_ex.fe_len = len;
5832 ac->ac_g_ex = ac->ac_o_ex;
5833 ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
5834 ac->ac_flags = ar->flags;
5836 /* we have to define context: we'll work with a file or
5837 * locality group. this is a policy, actually */
5838 ext4_mb_group_or_file(ac);
5840 mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
5841 "left: %u/%u, right %u/%u to %swritable\n",
5842 (unsigned) ar->len, (unsigned) ar->logical,
5843 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
5844 (unsigned) ar->lleft, (unsigned) ar->pleft,
5845 (unsigned) ar->lright, (unsigned) ar->pright,
5846 inode_is_open_for_write(ar->inode) ? "" : "non-");
5849 static noinline_for_stack void
5850 ext4_mb_discard_lg_preallocations(struct super_block *sb,
5851 struct ext4_locality_group *lg,
5852 int order, int total_entries)
5854 ext4_group_t group = 0;
5855 struct ext4_buddy e4b;
5856 LIST_HEAD(discard_list);
5857 struct ext4_prealloc_space *pa, *tmp;
5859 mb_debug(sb, "discard locality group preallocation\n");
5861 spin_lock(&lg->lg_prealloc_lock);
5862 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
5864 lockdep_is_held(&lg->lg_prealloc_lock)) {
5865 spin_lock(&pa->pa_lock);
5866 if (atomic_read(&pa->pa_count)) {
5868 * This is the pa that we just used
5869 * for block allocation. So don't
5872 spin_unlock(&pa->pa_lock);
5875 if (pa->pa_deleted) {
5876 spin_unlock(&pa->pa_lock);
5879 /* only lg prealloc space */
5880 BUG_ON(pa->pa_type != MB_GROUP_PA);
5882 /* seems this one can be freed ... */
5883 ext4_mb_mark_pa_deleted(sb, pa);
5884 spin_unlock(&pa->pa_lock);
5886 list_del_rcu(&pa->pa_node.lg_list);
5887 list_add(&pa->u.pa_tmp_list, &discard_list);
5890 if (total_entries <= 5) {
5892 * we want to keep only 5 entries
5893 * allowing it to grow to 8. This
5894 * mak sure we don't call discard
5895 * soon for this list.
5900 spin_unlock(&lg->lg_prealloc_lock);
5902 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
5905 group = ext4_get_group_number(sb, pa->pa_pstart);
5906 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
5907 GFP_NOFS|__GFP_NOFAIL);
5909 ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
5913 ext4_lock_group(sb, group);
5914 list_del(&pa->pa_group_list);
5915 ext4_mb_release_group_pa(&e4b, pa);
5916 ext4_unlock_group(sb, group);
5918 ext4_mb_unload_buddy(&e4b);
5919 list_del(&pa->u.pa_tmp_list);
5920 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5925 * We have incremented pa_count. So it cannot be freed at this
5926 * point. Also we hold lg_mutex. So no parallel allocation is
5927 * possible from this lg. That means pa_free cannot be updated.
5929 * A parallel ext4_mb_discard_group_preallocations is possible.
5930 * which can cause the lg_prealloc_list to be updated.
5933 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
5935 int order, added = 0, lg_prealloc_count = 1;
5936 struct super_block *sb = ac->ac_sb;
5937 struct ext4_locality_group *lg = ac->ac_lg;
5938 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
5940 order = fls(pa->pa_free) - 1;
5941 if (order > PREALLOC_TB_SIZE - 1)
5942 /* The max size of hash table is PREALLOC_TB_SIZE */
5943 order = PREALLOC_TB_SIZE - 1;
5944 /* Add the prealloc space to lg */
5945 spin_lock(&lg->lg_prealloc_lock);
5946 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
5948 lockdep_is_held(&lg->lg_prealloc_lock)) {
5949 spin_lock(&tmp_pa->pa_lock);
5950 if (tmp_pa->pa_deleted) {
5951 spin_unlock(&tmp_pa->pa_lock);
5954 if (!added && pa->pa_free < tmp_pa->pa_free) {
5955 /* Add to the tail of the previous entry */
5956 list_add_tail_rcu(&pa->pa_node.lg_list,
5957 &tmp_pa->pa_node.lg_list);
5960 * we want to count the total
5961 * number of entries in the list
5964 spin_unlock(&tmp_pa->pa_lock);
5965 lg_prealloc_count++;
5968 list_add_tail_rcu(&pa->pa_node.lg_list,
5969 &lg->lg_prealloc_list[order]);
5970 spin_unlock(&lg->lg_prealloc_lock);
5972 /* Now trim the list to be not more than 8 elements */
5973 if (lg_prealloc_count > 8)
5974 ext4_mb_discard_lg_preallocations(sb, lg,
5975 order, lg_prealloc_count);
5979 * release all resource we used in allocation
5981 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
5983 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
5984 struct ext4_prealloc_space *pa = ac->ac_pa;
5986 if (pa->pa_type == MB_GROUP_PA) {
5987 /* see comment in ext4_mb_use_group_pa() */
5988 spin_lock(&pa->pa_lock);
5989 pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
5990 pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
5991 pa->pa_free -= ac->ac_b_ex.fe_len;
5992 pa->pa_len -= ac->ac_b_ex.fe_len;
5993 spin_unlock(&pa->pa_lock);
5996 * We want to add the pa to the right bucket.
5997 * Remove it from the list and while adding
5998 * make sure the list to which we are adding
6001 if (likely(pa->pa_free)) {
6002 spin_lock(pa->pa_node_lock.lg_lock);
6003 list_del_rcu(&pa->pa_node.lg_list);
6004 spin_unlock(pa->pa_node_lock.lg_lock);
6005 ext4_mb_add_n_trim(ac);
6009 ext4_mb_put_pa(ac, ac->ac_sb, pa);
6011 if (ac->ac_bitmap_page)
6012 put_page(ac->ac_bitmap_page);
6013 if (ac->ac_buddy_page)
6014 put_page(ac->ac_buddy_page);
6015 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
6016 mutex_unlock(&ac->ac_lg->lg_mutex);
6017 ext4_mb_collect_stats(ac);
6021 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
6023 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
6025 int freed = 0, busy = 0;
6028 trace_ext4_mb_discard_preallocations(sb, needed);
6031 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
6033 for (i = 0; i < ngroups && needed > 0; i++) {
6034 ret = ext4_mb_discard_group_preallocations(sb, i, &busy);
6040 if (needed > 0 && busy && ++retry < 3) {
6048 static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
6049 struct ext4_allocation_context *ac, u64 *seq)
6055 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
6060 seq_retry = ext4_get_discard_pa_seq_sum();
6061 if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
6062 ac->ac_flags |= EXT4_MB_STRICT_CHECK;
6068 mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
6073 * Simple allocator for Ext4 fast commit replay path. It searches for blocks
6074 * linearly starting at the goal block and also excludes the blocks which
6075 * are going to be in use after fast commit replay.
6078 ext4_mb_new_blocks_simple(struct ext4_allocation_request *ar, int *errp)
6080 struct buffer_head *bitmap_bh;
6081 struct super_block *sb = ar->inode->i_sb;
6082 struct ext4_sb_info *sbi = EXT4_SB(sb);
6083 ext4_group_t group, nr;
6084 ext4_grpblk_t blkoff;
6085 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
6086 ext4_grpblk_t i = 0;
6087 ext4_fsblk_t goal, block;
6088 struct ext4_super_block *es = sbi->s_es;
6091 if (goal < le32_to_cpu(es->s_first_data_block) ||
6092 goal >= ext4_blocks_count(es))
6093 goal = le32_to_cpu(es->s_first_data_block);
6096 ext4_get_group_no_and_offset(sb, goal, &group, &blkoff);
6097 for (nr = ext4_get_groups_count(sb); nr > 0; nr--) {
6098 bitmap_bh = ext4_read_block_bitmap(sb, group);
6099 if (IS_ERR(bitmap_bh)) {
6100 *errp = PTR_ERR(bitmap_bh);
6101 pr_warn("Failed to read block bitmap\n");
6106 i = mb_find_next_zero_bit(bitmap_bh->b_data, max,
6110 if (ext4_fc_replay_check_excluded(sb,
6111 ext4_group_first_block_no(sb, group) +
6112 EXT4_C2B(sbi, i))) {
6121 if (++group >= ext4_get_groups_count(sb))
6132 block = ext4_group_first_block_no(sb, group) + EXT4_C2B(sbi, i);
6133 ext4_mb_mark_bb(sb, block, 1, 1);
6140 * Main entry point into mballoc to allocate blocks
6141 * it tries to use preallocation first, then falls back
6142 * to usual allocation
6144 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
6145 struct ext4_allocation_request *ar, int *errp)
6147 struct ext4_allocation_context *ac = NULL;
6148 struct ext4_sb_info *sbi;
6149 struct super_block *sb;
6150 ext4_fsblk_t block = 0;
6151 unsigned int inquota = 0;
6152 unsigned int reserv_clstrs = 0;
6157 sb = ar->inode->i_sb;
6160 trace_ext4_request_blocks(ar);
6161 if (sbi->s_mount_state & EXT4_FC_REPLAY)
6162 return ext4_mb_new_blocks_simple(ar, errp);
6164 /* Allow to use superuser reservation for quota file */
6165 if (ext4_is_quota_file(ar->inode))
6166 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
6168 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
6169 /* Without delayed allocation we need to verify
6170 * there is enough free blocks to do block allocation
6171 * and verify allocation doesn't exceed the quota limits.
6174 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
6176 /* let others to free the space */
6178 ar->len = ar->len >> 1;
6181 ext4_mb_show_pa(sb);
6185 reserv_clstrs = ar->len;
6186 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
6187 dquot_alloc_block_nofail(ar->inode,
6188 EXT4_C2B(sbi, ar->len));
6191 dquot_alloc_block(ar->inode,
6192 EXT4_C2B(sbi, ar->len))) {
6194 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
6205 ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
6212 ext4_mb_initialize_context(ac, ar);
6214 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
6215 seq = this_cpu_read(discard_pa_seq);
6216 if (!ext4_mb_use_preallocated(ac)) {
6217 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
6218 ext4_mb_normalize_request(ac, ar);
6220 *errp = ext4_mb_pa_alloc(ac);
6224 /* allocate space in core */
6225 *errp = ext4_mb_regular_allocator(ac);
6227 * pa allocated above is added to grp->bb_prealloc_list only
6228 * when we were able to allocate some block i.e. when
6229 * ac->ac_status == AC_STATUS_FOUND.
6230 * And error from above mean ac->ac_status != AC_STATUS_FOUND
6231 * So we have to free this pa here itself.
6234 ext4_mb_pa_put_free(ac);
6235 ext4_discard_allocated_blocks(ac);
6238 if (ac->ac_status == AC_STATUS_FOUND &&
6239 ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
6240 ext4_mb_pa_put_free(ac);
6242 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
6243 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
6245 ext4_discard_allocated_blocks(ac);
6248 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
6249 ar->len = ac->ac_b_ex.fe_len;
6252 if (++retries < 3 &&
6253 ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
6256 * If block allocation fails then the pa allocated above
6257 * needs to be freed here itself.
6259 ext4_mb_pa_put_free(ac);
6265 ac->ac_b_ex.fe_len = 0;
6267 ext4_mb_show_ac(ac);
6269 ext4_mb_release_context(ac);
6270 kmem_cache_free(ext4_ac_cachep, ac);
6272 if (inquota && ar->len < inquota)
6273 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
6275 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
6276 /* release all the reserved blocks if non delalloc */
6277 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
6281 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
6287 * We can merge two free data extents only if the physical blocks
6288 * are contiguous, AND the extents were freed by the same transaction,
6289 * AND the blocks are associated with the same group.
6291 static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
6292 struct ext4_free_data *entry,
6293 struct ext4_free_data *new_entry,
6294 struct rb_root *entry_rb_root)
6296 if ((entry->efd_tid != new_entry->efd_tid) ||
6297 (entry->efd_group != new_entry->efd_group))
6299 if (entry->efd_start_cluster + entry->efd_count ==
6300 new_entry->efd_start_cluster) {
6301 new_entry->efd_start_cluster = entry->efd_start_cluster;
6302 new_entry->efd_count += entry->efd_count;
6303 } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
6304 entry->efd_start_cluster) {
6305 new_entry->efd_count += entry->efd_count;
6308 spin_lock(&sbi->s_md_lock);
6309 list_del(&entry->efd_list);
6310 spin_unlock(&sbi->s_md_lock);
6311 rb_erase(&entry->efd_node, entry_rb_root);
6312 kmem_cache_free(ext4_free_data_cachep, entry);
6315 static noinline_for_stack void
6316 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
6317 struct ext4_free_data *new_entry)
6319 ext4_group_t group = e4b->bd_group;
6320 ext4_grpblk_t cluster;
6321 ext4_grpblk_t clusters = new_entry->efd_count;
6322 struct ext4_free_data *entry;
6323 struct ext4_group_info *db = e4b->bd_info;
6324 struct super_block *sb = e4b->bd_sb;
6325 struct ext4_sb_info *sbi = EXT4_SB(sb);
6326 struct rb_node **n = &db->bb_free_root.rb_node, *node;
6327 struct rb_node *parent = NULL, *new_node;
6329 BUG_ON(!ext4_handle_valid(handle));
6330 BUG_ON(e4b->bd_bitmap_page == NULL);
6331 BUG_ON(e4b->bd_buddy_page == NULL);
6333 new_node = &new_entry->efd_node;
6334 cluster = new_entry->efd_start_cluster;
6337 /* first free block exent. We need to
6338 protect buddy cache from being freed,
6339 * otherwise we'll refresh it from
6340 * on-disk bitmap and lose not-yet-available
6342 get_page(e4b->bd_buddy_page);
6343 get_page(e4b->bd_bitmap_page);
6347 entry = rb_entry(parent, struct ext4_free_data, efd_node);
6348 if (cluster < entry->efd_start_cluster)
6350 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
6351 n = &(*n)->rb_right;
6353 ext4_grp_locked_error(sb, group, 0,
6354 ext4_group_first_block_no(sb, group) +
6355 EXT4_C2B(sbi, cluster),
6356 "Block already on to-be-freed list");
6357 kmem_cache_free(ext4_free_data_cachep, new_entry);
6362 rb_link_node(new_node, parent, n);
6363 rb_insert_color(new_node, &db->bb_free_root);
6365 /* Now try to see the extent can be merged to left and right */
6366 node = rb_prev(new_node);
6368 entry = rb_entry(node, struct ext4_free_data, efd_node);
6369 ext4_try_merge_freed_extent(sbi, entry, new_entry,
6370 &(db->bb_free_root));
6373 node = rb_next(new_node);
6375 entry = rb_entry(node, struct ext4_free_data, efd_node);
6376 ext4_try_merge_freed_extent(sbi, entry, new_entry,
6377 &(db->bb_free_root));
6380 spin_lock(&sbi->s_md_lock);
6381 list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
6382 sbi->s_mb_free_pending += clusters;
6383 spin_unlock(&sbi->s_md_lock);
6386 static void ext4_free_blocks_simple(struct inode *inode, ext4_fsblk_t block,
6387 unsigned long count)
6389 struct buffer_head *bitmap_bh;
6390 struct super_block *sb = inode->i_sb;
6391 struct ext4_group_desc *gdp;
6392 struct buffer_head *gdp_bh;
6394 ext4_grpblk_t blkoff;
6395 int already_freed = 0, err, i;
6397 ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
6398 bitmap_bh = ext4_read_block_bitmap(sb, group);
6399 if (IS_ERR(bitmap_bh)) {
6400 pr_warn("Failed to read block bitmap\n");
6403 gdp = ext4_get_group_desc(sb, group, &gdp_bh);
6407 for (i = 0; i < count; i++) {
6408 if (!mb_test_bit(blkoff + i, bitmap_bh->b_data))
6411 mb_clear_bits(bitmap_bh->b_data, blkoff, count);
6412 err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
6415 ext4_free_group_clusters_set(
6416 sb, gdp, ext4_free_group_clusters(sb, gdp) +
6417 count - already_freed);
6418 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
6419 ext4_group_desc_csum_set(sb, group, gdp);
6420 ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
6421 sync_dirty_buffer(bitmap_bh);
6422 sync_dirty_buffer(gdp_bh);
6429 * ext4_mb_clear_bb() -- helper function for freeing blocks.
6430 * Used by ext4_free_blocks()
6431 * @handle: handle for this transaction
6433 * @block: starting physical block to be freed
6434 * @count: number of blocks to be freed
6435 * @flags: flags used by ext4_free_blocks
6437 static void ext4_mb_clear_bb(handle_t *handle, struct inode *inode,
6438 ext4_fsblk_t block, unsigned long count,
6441 struct buffer_head *bitmap_bh = NULL;
6442 struct super_block *sb = inode->i_sb;
6443 struct ext4_group_desc *gdp;
6444 struct ext4_group_info *grp;
6445 unsigned int overflow;
6447 struct buffer_head *gd_bh;
6448 ext4_group_t block_group;
6449 struct ext4_sb_info *sbi;
6450 struct ext4_buddy e4b;
6451 unsigned int count_clusters;
6457 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6458 !ext4_inode_block_valid(inode, block, count)) {
6459 ext4_error(sb, "Freeing blocks in system zone - "
6460 "Block = %llu, count = %lu", block, count);
6461 /* err = 0. ext4_std_error should be a no op */
6464 flags |= EXT4_FREE_BLOCKS_VALIDATED;
6468 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
6470 grp = ext4_get_group_info(sb, block_group);
6471 if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
6475 * Check to see if we are freeing blocks across a group
6478 if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
6479 overflow = EXT4_C2B(sbi, bit) + count -
6480 EXT4_BLOCKS_PER_GROUP(sb);
6482 /* The range changed so it's no longer validated */
6483 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6485 count_clusters = EXT4_NUM_B2C(sbi, count);
6486 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
6487 if (IS_ERR(bitmap_bh)) {
6488 err = PTR_ERR(bitmap_bh);
6492 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
6498 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6499 !ext4_inode_block_valid(inode, block, count)) {
6500 ext4_error(sb, "Freeing blocks in system zone - "
6501 "Block = %llu, count = %lu", block, count);
6502 /* err = 0. ext4_std_error should be a no op */
6506 BUFFER_TRACE(bitmap_bh, "getting write access");
6507 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
6513 * We are about to modify some metadata. Call the journal APIs
6514 * to unshare ->b_data if a currently-committing transaction is
6517 BUFFER_TRACE(gd_bh, "get_write_access");
6518 err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
6521 #ifdef AGGRESSIVE_CHECK
6524 for (i = 0; i < count_clusters; i++)
6525 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
6528 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
6530 /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
6531 err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
6532 GFP_NOFS|__GFP_NOFAIL);
6537 * We need to make sure we don't reuse the freed block until after the
6538 * transaction is committed. We make an exception if the inode is to be
6539 * written in writeback mode since writeback mode has weak data
6540 * consistency guarantees.
6542 if (ext4_handle_valid(handle) &&
6543 ((flags & EXT4_FREE_BLOCKS_METADATA) ||
6544 !ext4_should_writeback_data(inode))) {
6545 struct ext4_free_data *new_entry;
6547 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
6550 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
6551 GFP_NOFS|__GFP_NOFAIL);
6552 new_entry->efd_start_cluster = bit;
6553 new_entry->efd_group = block_group;
6554 new_entry->efd_count = count_clusters;
6555 new_entry->efd_tid = handle->h_transaction->t_tid;
6557 ext4_lock_group(sb, block_group);
6558 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
6559 ext4_mb_free_metadata(handle, &e4b, new_entry);
6561 /* need to update group_info->bb_free and bitmap
6562 * with group lock held. generate_buddy look at
6563 * them with group lock_held
6565 if (test_opt(sb, DISCARD)) {
6566 err = ext4_issue_discard(sb, block_group, bit,
6567 count_clusters, NULL);
6568 if (err && err != -EOPNOTSUPP)
6569 ext4_msg(sb, KERN_WARNING, "discard request in"
6570 " group:%u block:%d count:%lu failed"
6571 " with %d", block_group, bit, count,
6574 EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
6576 ext4_lock_group(sb, block_group);
6577 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
6578 mb_free_blocks(inode, &e4b, bit, count_clusters);
6581 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
6582 ext4_free_group_clusters_set(sb, gdp, ret);
6583 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
6584 ext4_group_desc_csum_set(sb, block_group, gdp);
6585 ext4_unlock_group(sb, block_group);
6587 if (sbi->s_log_groups_per_flex) {
6588 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
6589 atomic64_add(count_clusters,
6590 &sbi_array_rcu_deref(sbi, s_flex_groups,
6591 flex_group)->free_clusters);
6595 * on a bigalloc file system, defer the s_freeclusters_counter
6596 * update to the caller (ext4_remove_space and friends) so they
6597 * can determine if a cluster freed here should be rereserved
6599 if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
6600 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
6601 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
6602 percpu_counter_add(&sbi->s_freeclusters_counter,
6606 ext4_mb_unload_buddy(&e4b);
6608 /* We dirtied the bitmap block */
6609 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
6610 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
6612 /* And the group descriptor block */
6613 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
6614 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
6618 if (overflow && !err) {
6622 /* The range changed so it's no longer validated */
6623 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6628 ext4_std_error(sb, err);
6632 * ext4_free_blocks() -- Free given blocks and update quota
6633 * @handle: handle for this transaction
6635 * @bh: optional buffer of the block to be freed
6636 * @block: starting physical block to be freed
6637 * @count: number of blocks to be freed
6638 * @flags: flags used by ext4_free_blocks
6640 void ext4_free_blocks(handle_t *handle, struct inode *inode,
6641 struct buffer_head *bh, ext4_fsblk_t block,
6642 unsigned long count, int flags)
6644 struct super_block *sb = inode->i_sb;
6645 unsigned int overflow;
6646 struct ext4_sb_info *sbi;
6652 BUG_ON(block != bh->b_blocknr);
6654 block = bh->b_blocknr;
6657 if (sbi->s_mount_state & EXT4_FC_REPLAY) {
6658 ext4_free_blocks_simple(inode, block, EXT4_NUM_B2C(sbi, count));
6664 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6665 !ext4_inode_block_valid(inode, block, count)) {
6666 ext4_error(sb, "Freeing blocks not in datazone - "
6667 "block = %llu, count = %lu", block, count);
6670 flags |= EXT4_FREE_BLOCKS_VALIDATED;
6672 ext4_debug("freeing block %llu\n", block);
6673 trace_ext4_free_blocks(inode, block, count, flags);
6675 if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
6678 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
6683 * If the extent to be freed does not begin on a cluster
6684 * boundary, we need to deal with partial clusters at the
6685 * beginning and end of the extent. Normally we will free
6686 * blocks at the beginning or the end unless we are explicitly
6687 * requested to avoid doing so.
6689 overflow = EXT4_PBLK_COFF(sbi, block);
6691 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
6692 overflow = sbi->s_cluster_ratio - overflow;
6694 if (count > overflow)
6702 /* The range changed so it's no longer validated */
6703 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6705 overflow = EXT4_LBLK_COFF(sbi, count);
6707 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
6708 if (count > overflow)
6713 count += sbi->s_cluster_ratio - overflow;
6714 /* The range changed so it's no longer validated */
6715 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6718 if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
6720 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
6722 for (i = 0; i < count; i++) {
6725 bh = sb_find_get_block(inode->i_sb, block + i);
6726 ext4_forget(handle, is_metadata, inode, bh, block + i);
6730 ext4_mb_clear_bb(handle, inode, block, count, flags);
6734 * ext4_group_add_blocks() -- Add given blocks to an existing group
6735 * @handle: handle to this transaction
6737 * @block: start physical block to add to the block group
6738 * @count: number of blocks to free
6740 * This marks the blocks as free in the bitmap and buddy.
6742 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
6743 ext4_fsblk_t block, unsigned long count)
6745 struct buffer_head *bitmap_bh = NULL;
6746 struct buffer_head *gd_bh;
6747 ext4_group_t block_group;
6750 struct ext4_group_desc *desc;
6751 struct ext4_sb_info *sbi = EXT4_SB(sb);
6752 struct ext4_buddy e4b;
6753 int err = 0, ret, free_clusters_count;
6754 ext4_grpblk_t clusters_freed;
6755 ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
6756 ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
6757 unsigned long cluster_count = last_cluster - first_cluster + 1;
6759 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
6764 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
6766 * Check to see if we are freeing blocks across a group
6769 if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
6770 ext4_warning(sb, "too many blocks added to group %u",
6776 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
6777 if (IS_ERR(bitmap_bh)) {
6778 err = PTR_ERR(bitmap_bh);
6783 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
6789 if (!ext4_sb_block_valid(sb, NULL, block, count)) {
6790 ext4_error(sb, "Adding blocks in system zones - "
6791 "Block = %llu, count = %lu",
6797 BUFFER_TRACE(bitmap_bh, "getting write access");
6798 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
6804 * We are about to modify some metadata. Call the journal APIs
6805 * to unshare ->b_data if a currently-committing transaction is
6808 BUFFER_TRACE(gd_bh, "get_write_access");
6809 err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
6813 for (i = 0, clusters_freed = 0; i < cluster_count; i++) {
6814 BUFFER_TRACE(bitmap_bh, "clear bit");
6815 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
6816 ext4_error(sb, "bit already cleared for block %llu",
6817 (ext4_fsblk_t)(block + i));
6818 BUFFER_TRACE(bitmap_bh, "bit already cleared");
6824 err = ext4_mb_load_buddy(sb, block_group, &e4b);
6829 * need to update group_info->bb_free and bitmap
6830 * with group lock held. generate_buddy look at
6831 * them with group lock_held
6833 ext4_lock_group(sb, block_group);
6834 mb_clear_bits(bitmap_bh->b_data, bit, cluster_count);
6835 mb_free_blocks(NULL, &e4b, bit, cluster_count);
6836 free_clusters_count = clusters_freed +
6837 ext4_free_group_clusters(sb, desc);
6838 ext4_free_group_clusters_set(sb, desc, free_clusters_count);
6839 ext4_block_bitmap_csum_set(sb, desc, bitmap_bh);
6840 ext4_group_desc_csum_set(sb, block_group, desc);
6841 ext4_unlock_group(sb, block_group);
6842 percpu_counter_add(&sbi->s_freeclusters_counter,
6845 if (sbi->s_log_groups_per_flex) {
6846 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
6847 atomic64_add(clusters_freed,
6848 &sbi_array_rcu_deref(sbi, s_flex_groups,
6849 flex_group)->free_clusters);
6852 ext4_mb_unload_buddy(&e4b);
6854 /* We dirtied the bitmap block */
6855 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
6856 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
6858 /* And the group descriptor block */
6859 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
6860 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
6866 ext4_std_error(sb, err);
6871 * ext4_trim_extent -- function to TRIM one single free extent in the group
6872 * @sb: super block for the file system
6873 * @start: starting block of the free extent in the alloc. group
6874 * @count: number of blocks to TRIM
6875 * @e4b: ext4 buddy for the group
6877 * Trim "count" blocks starting at "start" in the "group". To assure that no
6878 * one will allocate those blocks, mark it as used in buddy bitmap. This must
6879 * be called with under the group lock.
6881 static int ext4_trim_extent(struct super_block *sb,
6882 int start, int count, struct ext4_buddy *e4b)
6886 struct ext4_free_extent ex;
6887 ext4_group_t group = e4b->bd_group;
6890 trace_ext4_trim_extent(sb, group, start, count);
6892 assert_spin_locked(ext4_group_lock_ptr(sb, group));
6894 ex.fe_start = start;
6895 ex.fe_group = group;
6899 * Mark blocks used, so no one can reuse them while
6902 mb_mark_used(e4b, &ex);
6903 ext4_unlock_group(sb, group);
6904 ret = ext4_issue_discard(sb, group, start, count, NULL);
6905 ext4_lock_group(sb, group);
6906 mb_free_blocks(NULL, e4b, start, ex.fe_len);
6910 static ext4_grpblk_t ext4_last_grp_cluster(struct super_block *sb,
6913 if (grp < ext4_get_groups_count(sb))
6914 return EXT4_CLUSTERS_PER_GROUP(sb) - 1;
6915 return (ext4_blocks_count(EXT4_SB(sb)->s_es) -
6916 ext4_group_first_block_no(sb, grp) - 1) >>
6917 EXT4_CLUSTER_BITS(sb);
6920 static bool ext4_trim_interrupted(void)
6922 return fatal_signal_pending(current) || freezing(current);
6925 static int ext4_try_to_trim_range(struct super_block *sb,
6926 struct ext4_buddy *e4b, ext4_grpblk_t start,
6927 ext4_grpblk_t max, ext4_grpblk_t minblocks)
6928 __acquires(ext4_group_lock_ptr(sb, e4b->bd_group))
6929 __releases(ext4_group_lock_ptr(sb, e4b->bd_group))
6931 ext4_grpblk_t next, count, free_count;
6932 bool set_trimmed = false;
6935 bitmap = e4b->bd_bitmap;
6936 if (start == 0 && max >= ext4_last_grp_cluster(sb, e4b->bd_group))
6938 start = max(e4b->bd_info->bb_first_free, start);
6942 while (start <= max) {
6943 start = mb_find_next_zero_bit(bitmap, max + 1, start);
6946 next = mb_find_next_bit(bitmap, max + 1, start);
6948 if ((next - start) >= minblocks) {
6949 int ret = ext4_trim_extent(sb, start, next - start, e4b);
6951 if (ret && ret != -EOPNOTSUPP)
6953 count += next - start;
6955 free_count += next - start;
6958 if (ext4_trim_interrupted())
6961 if (need_resched()) {
6962 ext4_unlock_group(sb, e4b->bd_group);
6964 ext4_lock_group(sb, e4b->bd_group);
6967 if ((e4b->bd_info->bb_free - free_count) < minblocks)
6972 EXT4_MB_GRP_SET_TRIMMED(e4b->bd_info);
6978 * ext4_trim_all_free -- function to trim all free space in alloc. group
6979 * @sb: super block for file system
6980 * @group: group to be trimmed
6981 * @start: first group block to examine
6982 * @max: last group block to examine
6983 * @minblocks: minimum extent block count
6985 * ext4_trim_all_free walks through group's block bitmap searching for free
6986 * extents. When the free extent is found, mark it as used in group buddy
6987 * bitmap. Then issue a TRIM command on this extent and free the extent in
6988 * the group buddy bitmap.
6990 static ext4_grpblk_t
6991 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
6992 ext4_grpblk_t start, ext4_grpblk_t max,
6993 ext4_grpblk_t minblocks)
6995 struct ext4_buddy e4b;
6998 trace_ext4_trim_all_free(sb, group, start, max);
7000 ret = ext4_mb_load_buddy(sb, group, &e4b);
7002 ext4_warning(sb, "Error %d loading buddy information for %u",
7007 ext4_lock_group(sb, group);
7009 if (!EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) ||
7010 minblocks < EXT4_SB(sb)->s_last_trim_minblks)
7011 ret = ext4_try_to_trim_range(sb, &e4b, start, max, minblocks);
7015 ext4_unlock_group(sb, group);
7016 ext4_mb_unload_buddy(&e4b);
7018 ext4_debug("trimmed %d blocks in the group %d\n",
7025 * ext4_trim_fs() -- trim ioctl handle function
7026 * @sb: superblock for filesystem
7027 * @range: fstrim_range structure
7029 * start: First Byte to trim
7030 * len: number of Bytes to trim from start
7031 * minlen: minimum extent length in Bytes
7032 * ext4_trim_fs goes through all allocation groups containing Bytes from
7033 * start to start+len. For each such a group ext4_trim_all_free function
7034 * is invoked to trim all free space.
7036 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
7038 unsigned int discard_granularity = bdev_discard_granularity(sb->s_bdev);
7039 struct ext4_group_info *grp;
7040 ext4_group_t group, first_group, last_group;
7041 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
7042 uint64_t start, end, minlen, trimmed = 0;
7043 ext4_fsblk_t first_data_blk =
7044 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
7045 ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
7048 start = range->start >> sb->s_blocksize_bits;
7049 end = start + (range->len >> sb->s_blocksize_bits) - 1;
7050 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
7051 range->minlen >> sb->s_blocksize_bits);
7053 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
7054 start >= max_blks ||
7055 range->len < sb->s_blocksize)
7057 /* No point to try to trim less than discard granularity */
7058 if (range->minlen < discard_granularity) {
7059 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
7060 discard_granularity >> sb->s_blocksize_bits);
7061 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
7064 if (end >= max_blks - 1)
7066 if (end <= first_data_blk)
7068 if (start < first_data_blk)
7069 start = first_data_blk;
7071 /* Determine first and last group to examine based on start and end */
7072 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
7073 &first_group, &first_cluster);
7074 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
7075 &last_group, &last_cluster);
7077 /* end now represents the last cluster to discard in this group */
7078 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
7080 for (group = first_group; group <= last_group; group++) {
7081 if (ext4_trim_interrupted())
7083 grp = ext4_get_group_info(sb, group);
7086 /* We only do this if the grp has never been initialized */
7087 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
7088 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
7094 * For all the groups except the last one, last cluster will
7095 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
7096 * change it for the last group, note that last_cluster is
7097 * already computed earlier by ext4_get_group_no_and_offset()
7099 if (group == last_group)
7101 if (grp->bb_free >= minlen) {
7102 cnt = ext4_trim_all_free(sb, group, first_cluster,
7112 * For every group except the first one, we are sure
7113 * that the first cluster to discard will be cluster #0.
7119 EXT4_SB(sb)->s_last_trim_minblks = minlen;
7122 range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
7126 /* Iterate all the free extents in the group. */
7128 ext4_mballoc_query_range(
7129 struct super_block *sb,
7131 ext4_grpblk_t start,
7133 ext4_mballoc_query_range_fn formatter,
7138 struct ext4_buddy e4b;
7141 error = ext4_mb_load_buddy(sb, group, &e4b);
7144 bitmap = e4b.bd_bitmap;
7146 ext4_lock_group(sb, group);
7148 start = max(e4b.bd_info->bb_first_free, start);
7149 if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
7150 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
7152 while (start <= end) {
7153 start = mb_find_next_zero_bit(bitmap, end + 1, start);
7156 next = mb_find_next_bit(bitmap, end + 1, start);
7158 ext4_unlock_group(sb, group);
7159 error = formatter(sb, group, start, next - start, priv);
7162 ext4_lock_group(sb, group);
7167 ext4_unlock_group(sb, group);
7169 ext4_mb_unload_buddy(&e4b);