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 <trace/events/ext4.h>
23 * - test ext4_ext_search_left() and ext4_ext_search_right()
24 * - search for metadata in few groups
27 * - normalization should take into account whether file is still open
28 * - discard preallocations if no free space left (policy?)
29 * - don't normalize tails
31 * - reservation for superuser
34 * - bitmap read-ahead (proposed by Oleg Drokin aka green)
35 * - track min/max extents in each group for better group selection
36 * - mb_mark_used() may allocate chunk right after splitting buddy
37 * - tree of groups sorted by number of free blocks
42 * The allocation request involve request for multiple number of blocks
43 * near to the goal(block) value specified.
45 * During initialization phase of the allocator we decide to use the
46 * group preallocation or inode preallocation depending on the size of
47 * the file. The size of the file could be the resulting file size we
48 * would have after allocation, or the current file size, which ever
49 * is larger. If the size is less than sbi->s_mb_stream_request we
50 * select to use the group preallocation. The default value of
51 * s_mb_stream_request is 16 blocks. This can also be tuned via
52 * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
53 * terms of number of blocks.
55 * The main motivation for having small file use group preallocation is to
56 * ensure that we have small files closer together on the disk.
58 * First stage the allocator looks at the inode prealloc list,
59 * ext4_inode_info->i_prealloc_list, which contains list of prealloc
60 * spaces for this particular inode. The inode prealloc space is
63 * pa_lstart -> the logical start block for this prealloc space
64 * pa_pstart -> the physical start block for this prealloc space
65 * pa_len -> length for this prealloc space (in clusters)
66 * pa_free -> free space available in this prealloc space (in clusters)
68 * The inode preallocation space is used looking at the _logical_ start
69 * block. If only the logical file block falls within the range of prealloc
70 * space we will consume the particular prealloc space. This makes sure that
71 * we have contiguous physical blocks representing the file blocks
73 * The important thing to be noted in case of inode prealloc space is that
74 * we don't modify the values associated to inode prealloc space except
77 * If we are not able to find blocks in the inode prealloc space and if we
78 * have the group allocation flag set then we look at the locality group
79 * prealloc space. These are per CPU prealloc list represented as
81 * ext4_sb_info.s_locality_groups[smp_processor_id()]
83 * The reason for having a per cpu locality group is to reduce the contention
84 * between CPUs. It is possible to get scheduled at this point.
86 * The locality group prealloc space is used looking at whether we have
87 * enough free space (pa_free) within the prealloc space.
89 * If we can't allocate blocks via inode prealloc or/and locality group
90 * prealloc then we look at the buddy cache. The buddy cache is represented
91 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
92 * mapped to the buddy and bitmap information regarding different
93 * groups. The buddy information is attached to buddy cache inode so that
94 * we can access them through the page cache. The information regarding
95 * each group is loaded via ext4_mb_load_buddy. The information involve
96 * block bitmap and buddy information. The information are stored in the
100 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
103 * one block each for bitmap and buddy information. So for each group we
104 * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
105 * blocksize) blocks. So it can have information regarding groups_per_page
106 * which is blocks_per_page/2
108 * The buddy cache inode is not stored on disk. The inode is thrown
109 * away when the filesystem is unmounted.
111 * We look for count number of blocks in the buddy cache. If we were able
112 * to locate that many free blocks we return with additional information
113 * regarding rest of the contiguous physical block available
115 * Before allocating blocks via buddy cache we normalize the request
116 * blocks. This ensure we ask for more blocks that we needed. The extra
117 * blocks that we get after allocation is added to the respective prealloc
118 * list. In case of inode preallocation we follow a list of heuristics
119 * based on file size. This can be found in ext4_mb_normalize_request. If
120 * we are doing a group prealloc we try to normalize the request to
121 * sbi->s_mb_group_prealloc. The default value of s_mb_group_prealloc is
122 * dependent on the cluster size; for non-bigalloc file systems, it is
123 * 512 blocks. This can be tuned via
124 * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
125 * terms of number of blocks. If we have mounted the file system with -O
126 * stripe=<value> option the group prealloc request is normalized to the
127 * smallest multiple of the stripe value (sbi->s_stripe) which is
128 * greater than the default mb_group_prealloc.
130 * If "mb_optimize_scan" mount option is set, we maintain in memory group info
131 * structures in two data structures:
133 * 1) Array of largest free order lists (sbi->s_mb_largest_free_orders)
135 * Locking: sbi->s_mb_largest_free_orders_locks(array of rw locks)
137 * This is an array of lists where the index in the array represents the
138 * largest free order in the buddy bitmap of the participating group infos of
139 * that list. So, there are exactly MB_NUM_ORDERS(sb) (which means total
140 * number of buddy bitmap orders possible) number of lists. Group-infos are
141 * placed in appropriate lists.
143 * 2) Average fragment size lists (sbi->s_mb_avg_fragment_size)
145 * Locking: sbi->s_mb_avg_fragment_size_locks(array of rw locks)
147 * This is an array of lists where in the i-th list there are groups with
148 * average fragment size >= 2^i and < 2^(i+1). The average fragment size
149 * is computed as ext4_group_info->bb_free / ext4_group_info->bb_fragments.
150 * Note that we don't bother with a special list for completely empty groups
151 * so we only have MB_NUM_ORDERS(sb) lists.
153 * When "mb_optimize_scan" mount option is set, mballoc consults the above data
154 * structures to decide the order in which groups are to be traversed for
155 * fulfilling an allocation request.
157 * At CR = 0, we look for groups which have the largest_free_order >= the order
158 * of the request. We directly look at the largest free order list in the data
159 * structure (1) above where largest_free_order = order of the request. If that
160 * list is empty, we look at remaining list in the increasing order of
161 * largest_free_order. This allows us to perform CR = 0 lookup in O(1) time.
163 * At CR = 1, we only consider groups where average fragment size > request
164 * size. So, we lookup a group which has average fragment size just above or
165 * equal to request size using our average fragment size group lists (data
166 * structure 2) in O(1) time.
168 * If "mb_optimize_scan" mount option is not set, mballoc traverses groups in
169 * linear order which requires O(N) search time for each CR 0 and CR 1 phase.
171 * The regular allocator (using the buddy cache) supports a few tunables.
173 * /sys/fs/ext4/<partition>/mb_min_to_scan
174 * /sys/fs/ext4/<partition>/mb_max_to_scan
175 * /sys/fs/ext4/<partition>/mb_order2_req
176 * /sys/fs/ext4/<partition>/mb_linear_limit
178 * The regular allocator uses buddy scan only if the request len is power of
179 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
180 * value of s_mb_order2_reqs can be tuned via
181 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
182 * stripe size (sbi->s_stripe), we try to search for contiguous block in
183 * stripe size. This should result in better allocation on RAID setups. If
184 * not, we search in the specific group using bitmap for best extents. The
185 * tunable min_to_scan and max_to_scan control the behaviour here.
186 * min_to_scan indicate how long the mballoc __must__ look for a best
187 * extent and max_to_scan indicates how long the mballoc __can__ look for a
188 * best extent in the found extents. Searching for the blocks starts with
189 * the group specified as the goal value in allocation context via
190 * ac_g_ex. Each group is first checked based on the criteria whether it
191 * can be used for allocation. ext4_mb_good_group explains how the groups are
194 * When "mb_optimize_scan" is turned on, as mentioned above, the groups may not
195 * get traversed linearly. That may result in subsequent allocations being not
196 * close to each other. And so, the underlying device may get filled up in a
197 * non-linear fashion. While that may not matter on non-rotational devices, for
198 * rotational devices that may result in higher seek times. "mb_linear_limit"
199 * tells mballoc how many groups mballoc should search linearly before
200 * performing consulting above data structures for more efficient lookups. For
201 * non rotational devices, this value defaults to 0 and for rotational devices
202 * this is set to MB_DEFAULT_LINEAR_LIMIT.
204 * Both the prealloc space are getting populated as above. So for the first
205 * request we will hit the buddy cache which will result in this prealloc
206 * space getting filled. The prealloc space is then later used for the
207 * subsequent request.
211 * mballoc operates on the following data:
213 * - in-core buddy (actually includes buddy and bitmap)
214 * - preallocation descriptors (PAs)
216 * there are two types of preallocations:
218 * assiged to specific inode and can be used for this inode only.
219 * it describes part of inode's space preallocated to specific
220 * physical blocks. any block from that preallocated can be used
221 * independent. the descriptor just tracks number of blocks left
222 * unused. so, before taking some block from descriptor, one must
223 * make sure corresponded logical block isn't allocated yet. this
224 * also means that freeing any block within descriptor's range
225 * must discard all preallocated blocks.
227 * assigned to specific locality group which does not translate to
228 * permanent set of inodes: inode can join and leave group. space
229 * from this type of preallocation can be used for any inode. thus
230 * it's consumed from the beginning to the end.
232 * relation between them can be expressed as:
233 * in-core buddy = on-disk bitmap + preallocation descriptors
235 * this mean blocks mballoc considers used are:
236 * - allocated blocks (persistent)
237 * - preallocated blocks (non-persistent)
239 * consistency in mballoc world means that at any time a block is either
240 * free or used in ALL structures. notice: "any time" should not be read
241 * literally -- time is discrete and delimited by locks.
243 * to keep it simple, we don't use block numbers, instead we count number of
244 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
246 * all operations can be expressed as:
247 * - init buddy: buddy = on-disk + PAs
248 * - new PA: buddy += N; PA = N
249 * - use inode PA: on-disk += N; PA -= N
250 * - discard inode PA buddy -= on-disk - PA; PA = 0
251 * - use locality group PA on-disk += N; PA -= N
252 * - discard locality group PA buddy -= PA; PA = 0
253 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
254 * is used in real operation because we can't know actual used
255 * bits from PA, only from on-disk bitmap
257 * if we follow this strict logic, then all operations above should be atomic.
258 * given some of them can block, we'd have to use something like semaphores
259 * killing performance on high-end SMP hardware. let's try to relax it using
260 * the following knowledge:
261 * 1) if buddy is referenced, it's already initialized
262 * 2) while block is used in buddy and the buddy is referenced,
263 * nobody can re-allocate that block
264 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
265 * bit set and PA claims same block, it's OK. IOW, one can set bit in
266 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
269 * so, now we're building a concurrency table:
272 * blocks for PA are allocated in the buddy, buddy must be referenced
273 * until PA is linked to allocation group to avoid concurrent buddy init
275 * we need to make sure that either on-disk bitmap or PA has uptodate data
276 * given (3) we care that PA-=N operation doesn't interfere with init
278 * the simplest way would be to have buddy initialized by the discard
279 * - use locality group PA
280 * again PA-=N must be serialized with init
281 * - discard locality group PA
282 * the simplest way would be to have buddy initialized by the discard
285 * i_data_sem serializes them
287 * discard process must wait until PA isn't used by another process
288 * - use locality group PA
289 * some mutex should serialize them
290 * - discard locality group PA
291 * discard process must wait until PA isn't used by another process
294 * i_data_sem or another mutex should serializes them
296 * discard process must wait until PA isn't used by another process
297 * - use locality group PA
298 * nothing wrong here -- they're different PAs covering different blocks
299 * - discard locality group PA
300 * discard process must wait until PA isn't used by another process
302 * now we're ready to make few consequences:
303 * - PA is referenced and while it is no discard is possible
304 * - PA is referenced until block isn't marked in on-disk bitmap
305 * - PA changes only after on-disk bitmap
306 * - discard must not compete with init. either init is done before
307 * any discard or they're serialized somehow
308 * - buddy init as sum of on-disk bitmap and PAs is done atomically
310 * a special case when we've used PA to emptiness. no need to modify buddy
311 * in this case, but we should care about concurrent init
316 * Logic in few words:
321 * mark bits in on-disk bitmap
324 * - use preallocation:
325 * find proper PA (per-inode or group)
327 * mark bits in on-disk bitmap
333 * mark bits in on-disk bitmap
336 * - discard preallocations in group:
338 * move them onto local list
339 * load on-disk bitmap
341 * remove PA from object (inode or locality group)
342 * mark free blocks in-core
344 * - discard inode's preallocations:
351 * - bitlock on a group (group)
352 * - object (inode/locality) (object)
354 * - cr0 lists lock (cr0)
355 * - cr1 tree lock (cr1)
365 * - release consumed pa:
370 * - generate in-core bitmap:
374 * - discard all for given object (inode, locality group):
379 * - discard all for given group:
385 * - allocation path (ext4_mb_regular_allocator)
389 static struct kmem_cache *ext4_pspace_cachep;
390 static struct kmem_cache *ext4_ac_cachep;
391 static struct kmem_cache *ext4_free_data_cachep;
393 /* We create slab caches for groupinfo data structures based on the
394 * superblock block size. There will be one per mounted filesystem for
395 * each unique s_blocksize_bits */
396 #define NR_GRPINFO_CACHES 8
397 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
399 static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
400 "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
401 "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
402 "ext4_groupinfo_64k", "ext4_groupinfo_128k"
405 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
407 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
409 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac);
411 static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
412 ext4_group_t group, int cr);
414 static int ext4_try_to_trim_range(struct super_block *sb,
415 struct ext4_buddy *e4b, ext4_grpblk_t start,
416 ext4_grpblk_t max, ext4_grpblk_t minblocks);
419 * The algorithm using this percpu seq counter goes below:
420 * 1. We sample the percpu discard_pa_seq counter before trying for block
421 * allocation in ext4_mb_new_blocks().
422 * 2. We increment this percpu discard_pa_seq counter when we either allocate
423 * or free these blocks i.e. while marking those blocks as used/free in
424 * mb_mark_used()/mb_free_blocks().
425 * 3. We also increment this percpu seq counter when we successfully identify
426 * that the bb_prealloc_list is not empty and hence proceed for discarding
427 * of those PAs inside ext4_mb_discard_group_preallocations().
429 * Now to make sure that the regular fast path of block allocation is not
430 * affected, as a small optimization we only sample the percpu seq counter
431 * on that cpu. Only when the block allocation fails and when freed blocks
432 * found were 0, that is when we sample percpu seq counter for all cpus using
433 * below function ext4_get_discard_pa_seq_sum(). This happens after making
434 * sure that all the PAs on grp->bb_prealloc_list got freed or if it's empty.
436 static DEFINE_PER_CPU(u64, discard_pa_seq);
437 static inline u64 ext4_get_discard_pa_seq_sum(void)
442 for_each_possible_cpu(__cpu)
443 __seq += per_cpu(discard_pa_seq, __cpu);
447 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
449 #if BITS_PER_LONG == 64
450 *bit += ((unsigned long) addr & 7UL) << 3;
451 addr = (void *) ((unsigned long) addr & ~7UL);
452 #elif BITS_PER_LONG == 32
453 *bit += ((unsigned long) addr & 3UL) << 3;
454 addr = (void *) ((unsigned long) addr & ~3UL);
456 #error "how many bits you are?!"
461 static inline int mb_test_bit(int bit, void *addr)
464 * ext4_test_bit on architecture like powerpc
465 * needs unsigned long aligned address
467 addr = mb_correct_addr_and_bit(&bit, addr);
468 return ext4_test_bit(bit, addr);
471 static inline void mb_set_bit(int bit, void *addr)
473 addr = mb_correct_addr_and_bit(&bit, addr);
474 ext4_set_bit(bit, addr);
477 static inline void mb_clear_bit(int bit, void *addr)
479 addr = mb_correct_addr_and_bit(&bit, addr);
480 ext4_clear_bit(bit, addr);
483 static inline int mb_test_and_clear_bit(int bit, void *addr)
485 addr = mb_correct_addr_and_bit(&bit, addr);
486 return ext4_test_and_clear_bit(bit, addr);
489 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
491 int fix = 0, ret, tmpmax;
492 addr = mb_correct_addr_and_bit(&fix, addr);
496 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
502 static inline int mb_find_next_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_bit(addr, tmpmax, start) - fix;
515 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
519 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
522 if (order > e4b->bd_blkbits + 1) {
527 /* at order 0 we see each particular block */
529 *max = 1 << (e4b->bd_blkbits + 3);
530 return e4b->bd_bitmap;
533 bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
534 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
540 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
541 int first, int count)
544 struct super_block *sb = e4b->bd_sb;
546 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
548 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
549 for (i = 0; i < count; i++) {
550 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
551 ext4_fsblk_t blocknr;
553 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
554 blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
555 ext4_grp_locked_error(sb, e4b->bd_group,
556 inode ? inode->i_ino : 0,
558 "freeing block already freed "
561 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
562 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
564 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
568 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
572 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
574 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
575 for (i = 0; i < count; i++) {
576 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
577 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
581 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
583 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
585 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
586 unsigned char *b1, *b2;
588 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
589 b2 = (unsigned char *) bitmap;
590 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
591 if (b1[i] != b2[i]) {
592 ext4_msg(e4b->bd_sb, KERN_ERR,
593 "corruption in group %u "
594 "at byte %u(%u): %x in copy != %x "
596 e4b->bd_group, i, i * 8, b1[i], b2[i]);
603 static void mb_group_bb_bitmap_alloc(struct super_block *sb,
604 struct ext4_group_info *grp, ext4_group_t group)
606 struct buffer_head *bh;
608 grp->bb_bitmap = kmalloc(sb->s_blocksize, GFP_NOFS);
612 bh = ext4_read_block_bitmap(sb, group);
613 if (IS_ERR_OR_NULL(bh)) {
614 kfree(grp->bb_bitmap);
615 grp->bb_bitmap = NULL;
619 memcpy(grp->bb_bitmap, bh->b_data, sb->s_blocksize);
623 static void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
625 kfree(grp->bb_bitmap);
629 static inline void mb_free_blocks_double(struct inode *inode,
630 struct ext4_buddy *e4b, int first, int count)
634 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
635 int first, int count)
639 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
644 static inline void mb_group_bb_bitmap_alloc(struct super_block *sb,
645 struct ext4_group_info *grp, ext4_group_t group)
650 static inline void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
656 #ifdef AGGRESSIVE_CHECK
658 #define MB_CHECK_ASSERT(assert) \
662 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
663 function, file, line, # assert); \
668 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
669 const char *function, int line)
671 struct super_block *sb = e4b->bd_sb;
672 int order = e4b->bd_blkbits + 1;
679 struct ext4_group_info *grp;
682 struct list_head *cur;
686 if (e4b->bd_info->bb_check_counter++ % 10)
690 buddy = mb_find_buddy(e4b, order, &max);
691 MB_CHECK_ASSERT(buddy);
692 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
693 MB_CHECK_ASSERT(buddy2);
694 MB_CHECK_ASSERT(buddy != buddy2);
695 MB_CHECK_ASSERT(max * 2 == max2);
698 for (i = 0; i < max; i++) {
700 if (mb_test_bit(i, buddy)) {
701 /* only single bit in buddy2 may be 0 */
702 if (!mb_test_bit(i << 1, buddy2)) {
704 mb_test_bit((i<<1)+1, buddy2));
709 /* both bits in buddy2 must be 1 */
710 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
711 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
713 for (j = 0; j < (1 << order); j++) {
714 k = (i * (1 << order)) + j;
716 !mb_test_bit(k, e4b->bd_bitmap));
720 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
725 buddy = mb_find_buddy(e4b, 0, &max);
726 for (i = 0; i < max; i++) {
727 if (!mb_test_bit(i, buddy)) {
728 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
736 /* check used bits only */
737 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
738 buddy2 = mb_find_buddy(e4b, j, &max2);
740 MB_CHECK_ASSERT(k < max2);
741 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
744 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
745 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
747 grp = ext4_get_group_info(sb, e4b->bd_group);
750 list_for_each(cur, &grp->bb_prealloc_list) {
751 ext4_group_t groupnr;
752 struct ext4_prealloc_space *pa;
753 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
754 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
755 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
756 for (i = 0; i < pa->pa_len; i++)
757 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
761 #undef MB_CHECK_ASSERT
762 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
763 __FILE__, __func__, __LINE__)
765 #define mb_check_buddy(e4b)
769 * Divide blocks started from @first with length @len into
770 * smaller chunks with power of 2 blocks.
771 * Clear the bits in bitmap which the blocks of the chunk(s) covered,
772 * then increase bb_counters[] for corresponded chunk size.
774 static void ext4_mb_mark_free_simple(struct super_block *sb,
775 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
776 struct ext4_group_info *grp)
778 struct ext4_sb_info *sbi = EXT4_SB(sb);
784 BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
786 border = 2 << sb->s_blocksize_bits;
789 /* find how many blocks can be covered since this position */
790 max = ffs(first | border) - 1;
792 /* find how many blocks of power 2 we need to mark */
799 /* mark multiblock chunks only */
800 grp->bb_counters[min]++;
802 mb_clear_bit(first >> min,
803 buddy + sbi->s_mb_offsets[min]);
810 static int mb_avg_fragment_size_order(struct super_block *sb, ext4_grpblk_t len)
815 * We don't bother with a special lists groups with only 1 block free
816 * extents and for completely empty groups.
818 order = fls(len) - 2;
821 if (order == MB_NUM_ORDERS(sb))
826 /* Move group to appropriate avg_fragment_size list */
828 mb_update_avg_fragment_size(struct super_block *sb, struct ext4_group_info *grp)
830 struct ext4_sb_info *sbi = EXT4_SB(sb);
833 if (!test_opt2(sb, MB_OPTIMIZE_SCAN) || grp->bb_free == 0)
836 new_order = mb_avg_fragment_size_order(sb,
837 grp->bb_free / grp->bb_fragments);
838 if (new_order == grp->bb_avg_fragment_size_order)
841 if (grp->bb_avg_fragment_size_order != -1) {
842 write_lock(&sbi->s_mb_avg_fragment_size_locks[
843 grp->bb_avg_fragment_size_order]);
844 list_del(&grp->bb_avg_fragment_size_node);
845 write_unlock(&sbi->s_mb_avg_fragment_size_locks[
846 grp->bb_avg_fragment_size_order]);
848 grp->bb_avg_fragment_size_order = new_order;
849 write_lock(&sbi->s_mb_avg_fragment_size_locks[
850 grp->bb_avg_fragment_size_order]);
851 list_add_tail(&grp->bb_avg_fragment_size_node,
852 &sbi->s_mb_avg_fragment_size[grp->bb_avg_fragment_size_order]);
853 write_unlock(&sbi->s_mb_avg_fragment_size_locks[
854 grp->bb_avg_fragment_size_order]);
858 * Choose next group by traversing largest_free_order lists. Updates *new_cr if
859 * cr level needs an update.
861 static void ext4_mb_choose_next_group_cr0(struct ext4_allocation_context *ac,
862 int *new_cr, ext4_group_t *group, ext4_group_t ngroups)
864 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
865 struct ext4_group_info *iter, *grp;
868 if (ac->ac_status == AC_STATUS_FOUND)
871 if (unlikely(sbi->s_mb_stats && ac->ac_flags & EXT4_MB_CR0_OPTIMIZED))
872 atomic_inc(&sbi->s_bal_cr0_bad_suggestions);
875 for (i = ac->ac_2order; i < MB_NUM_ORDERS(ac->ac_sb); i++) {
876 if (list_empty(&sbi->s_mb_largest_free_orders[i]))
878 read_lock(&sbi->s_mb_largest_free_orders_locks[i]);
879 if (list_empty(&sbi->s_mb_largest_free_orders[i])) {
880 read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
884 list_for_each_entry(iter, &sbi->s_mb_largest_free_orders[i],
885 bb_largest_free_order_node) {
887 atomic64_inc(&sbi->s_bal_cX_groups_considered[0]);
888 if (likely(ext4_mb_good_group(ac, iter->bb_group, 0))) {
893 read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
899 /* Increment cr and search again */
902 *group = grp->bb_group;
903 ac->ac_flags |= EXT4_MB_CR0_OPTIMIZED;
908 * Choose next group by traversing average fragment size list of suitable
909 * order. Updates *new_cr if cr level needs an update.
911 static void ext4_mb_choose_next_group_cr1(struct ext4_allocation_context *ac,
912 int *new_cr, ext4_group_t *group, ext4_group_t ngroups)
914 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
915 struct ext4_group_info *grp = NULL, *iter;
918 if (unlikely(ac->ac_flags & EXT4_MB_CR1_OPTIMIZED)) {
920 atomic_inc(&sbi->s_bal_cr1_bad_suggestions);
923 for (i = mb_avg_fragment_size_order(ac->ac_sb, ac->ac_g_ex.fe_len);
924 i < MB_NUM_ORDERS(ac->ac_sb); i++) {
925 if (list_empty(&sbi->s_mb_avg_fragment_size[i]))
927 read_lock(&sbi->s_mb_avg_fragment_size_locks[i]);
928 if (list_empty(&sbi->s_mb_avg_fragment_size[i])) {
929 read_unlock(&sbi->s_mb_avg_fragment_size_locks[i]);
932 list_for_each_entry(iter, &sbi->s_mb_avg_fragment_size[i],
933 bb_avg_fragment_size_node) {
935 atomic64_inc(&sbi->s_bal_cX_groups_considered[1]);
936 if (likely(ext4_mb_good_group(ac, iter->bb_group, 1))) {
941 read_unlock(&sbi->s_mb_avg_fragment_size_locks[i]);
947 *group = grp->bb_group;
948 ac->ac_flags |= EXT4_MB_CR1_OPTIMIZED;
954 static inline int should_optimize_scan(struct ext4_allocation_context *ac)
956 if (unlikely(!test_opt2(ac->ac_sb, MB_OPTIMIZE_SCAN)))
958 if (ac->ac_criteria >= 2)
960 if (!ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS))
966 * Return next linear group for allocation. If linear traversal should not be
967 * performed, this function just returns the same group
970 next_linear_group(struct ext4_allocation_context *ac, int group, int ngroups)
972 if (!should_optimize_scan(ac))
975 if (ac->ac_groups_linear_remaining) {
976 ac->ac_groups_linear_remaining--;
983 * Artificially restricted ngroups for non-extent
984 * files makes group > ngroups possible on first loop.
986 return group + 1 >= ngroups ? 0 : group + 1;
990 * ext4_mb_choose_next_group: choose next group for allocation.
992 * @ac Allocation Context
993 * @new_cr This is an output parameter. If the there is no good group
994 * available at current CR level, this field is updated to indicate
995 * the new cr level that should be used.
996 * @group This is an input / output parameter. As an input it indicates the
997 * next group that the allocator intends to use for allocation. As
998 * output, this field indicates the next group that should be used as
999 * determined by the optimization functions.
1000 * @ngroups Total number of groups
1002 static void ext4_mb_choose_next_group(struct ext4_allocation_context *ac,
1003 int *new_cr, ext4_group_t *group, ext4_group_t ngroups)
1005 *new_cr = ac->ac_criteria;
1007 if (!should_optimize_scan(ac) || ac->ac_groups_linear_remaining) {
1008 *group = next_linear_group(ac, *group, ngroups);
1013 ext4_mb_choose_next_group_cr0(ac, new_cr, group, ngroups);
1014 } else if (*new_cr == 1) {
1015 ext4_mb_choose_next_group_cr1(ac, new_cr, group, ngroups);
1018 * TODO: For CR=2, we can arrange groups in an rb tree sorted by
1019 * bb_free. But until that happens, we should never come here.
1026 * Cache the order of the largest free extent we have available in this block
1030 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
1032 struct ext4_sb_info *sbi = EXT4_SB(sb);
1035 for (i = MB_NUM_ORDERS(sb) - 1; i >= 0; i--)
1036 if (grp->bb_counters[i] > 0)
1038 /* No need to move between order lists? */
1039 if (!test_opt2(sb, MB_OPTIMIZE_SCAN) ||
1040 i == grp->bb_largest_free_order) {
1041 grp->bb_largest_free_order = i;
1045 if (grp->bb_largest_free_order >= 0) {
1046 write_lock(&sbi->s_mb_largest_free_orders_locks[
1047 grp->bb_largest_free_order]);
1048 list_del_init(&grp->bb_largest_free_order_node);
1049 write_unlock(&sbi->s_mb_largest_free_orders_locks[
1050 grp->bb_largest_free_order]);
1052 grp->bb_largest_free_order = i;
1053 if (grp->bb_largest_free_order >= 0 && grp->bb_free) {
1054 write_lock(&sbi->s_mb_largest_free_orders_locks[
1055 grp->bb_largest_free_order]);
1056 list_add_tail(&grp->bb_largest_free_order_node,
1057 &sbi->s_mb_largest_free_orders[grp->bb_largest_free_order]);
1058 write_unlock(&sbi->s_mb_largest_free_orders_locks[
1059 grp->bb_largest_free_order]);
1063 static noinline_for_stack
1064 void ext4_mb_generate_buddy(struct super_block *sb,
1065 void *buddy, void *bitmap, ext4_group_t group,
1066 struct ext4_group_info *grp)
1068 struct ext4_sb_info *sbi = EXT4_SB(sb);
1069 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
1070 ext4_grpblk_t i = 0;
1071 ext4_grpblk_t first;
1074 unsigned fragments = 0;
1075 unsigned long long period = get_cycles();
1077 /* initialize buddy from bitmap which is aggregation
1078 * of on-disk bitmap and preallocations */
1079 i = mb_find_next_zero_bit(bitmap, max, 0);
1080 grp->bb_first_free = i;
1084 i = mb_find_next_bit(bitmap, max, i);
1088 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
1090 grp->bb_counters[0]++;
1092 i = mb_find_next_zero_bit(bitmap, max, i);
1094 grp->bb_fragments = fragments;
1096 if (free != grp->bb_free) {
1097 ext4_grp_locked_error(sb, group, 0, 0,
1098 "block bitmap and bg descriptor "
1099 "inconsistent: %u vs %u free clusters",
1100 free, grp->bb_free);
1102 * If we intend to continue, we consider group descriptor
1103 * corrupt and update bb_free using bitmap value
1105 grp->bb_free = free;
1106 ext4_mark_group_bitmap_corrupted(sb, group,
1107 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1109 mb_set_largest_free_order(sb, grp);
1110 mb_update_avg_fragment_size(sb, grp);
1112 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
1114 period = get_cycles() - period;
1115 atomic_inc(&sbi->s_mb_buddies_generated);
1116 atomic64_add(period, &sbi->s_mb_generation_time);
1119 /* The buddy information is attached the buddy cache inode
1120 * for convenience. The information regarding each group
1121 * is loaded via ext4_mb_load_buddy. The information involve
1122 * block bitmap and buddy information. The information are
1123 * stored in the inode as
1126 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
1129 * one block each for bitmap and buddy information.
1130 * So for each group we take up 2 blocks. A page can
1131 * contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
1132 * So it can have information regarding groups_per_page which
1133 * is blocks_per_page/2
1135 * Locking note: This routine takes the block group lock of all groups
1136 * for this page; do not hold this lock when calling this routine!
1139 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
1141 ext4_group_t ngroups;
1143 int blocks_per_page;
1144 int groups_per_page;
1147 ext4_group_t first_group, group;
1149 struct super_block *sb;
1150 struct buffer_head *bhs;
1151 struct buffer_head **bh = NULL;
1152 struct inode *inode;
1155 struct ext4_group_info *grinfo;
1157 inode = page->mapping->host;
1159 ngroups = ext4_get_groups_count(sb);
1160 blocksize = i_blocksize(inode);
1161 blocks_per_page = PAGE_SIZE / blocksize;
1163 mb_debug(sb, "init page %lu\n", page->index);
1165 groups_per_page = blocks_per_page >> 1;
1166 if (groups_per_page == 0)
1167 groups_per_page = 1;
1169 /* allocate buffer_heads to read bitmaps */
1170 if (groups_per_page > 1) {
1171 i = sizeof(struct buffer_head *) * groups_per_page;
1172 bh = kzalloc(i, gfp);
1178 first_group = page->index * blocks_per_page / 2;
1180 /* read all groups the page covers into the cache */
1181 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1182 if (group >= ngroups)
1185 grinfo = ext4_get_group_info(sb, group);
1189 * If page is uptodate then we came here after online resize
1190 * which added some new uninitialized group info structs, so
1191 * we must skip all initialized uptodate buddies on the page,
1192 * which may be currently in use by an allocating task.
1194 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
1198 bh[i] = ext4_read_block_bitmap_nowait(sb, group, false);
1199 if (IS_ERR(bh[i])) {
1200 err = PTR_ERR(bh[i]);
1204 mb_debug(sb, "read bitmap for group %u\n", group);
1207 /* wait for I/O completion */
1208 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
1213 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
1218 first_block = page->index * blocks_per_page;
1219 for (i = 0; i < blocks_per_page; i++) {
1220 group = (first_block + i) >> 1;
1221 if (group >= ngroups)
1224 if (!bh[group - first_group])
1225 /* skip initialized uptodate buddy */
1228 if (!buffer_verified(bh[group - first_group]))
1229 /* Skip faulty bitmaps */
1234 * data carry information regarding this
1235 * particular group in the format specified
1239 data = page_address(page) + (i * blocksize);
1240 bitmap = bh[group - first_group]->b_data;
1243 * We place the buddy block and bitmap block
1246 if ((first_block + i) & 1) {
1247 /* this is block of buddy */
1248 BUG_ON(incore == NULL);
1249 mb_debug(sb, "put buddy for group %u in page %lu/%x\n",
1250 group, page->index, i * blocksize);
1251 trace_ext4_mb_buddy_bitmap_load(sb, group);
1252 grinfo = ext4_get_group_info(sb, group);
1254 err = -EFSCORRUPTED;
1257 grinfo->bb_fragments = 0;
1258 memset(grinfo->bb_counters, 0,
1259 sizeof(*grinfo->bb_counters) *
1260 (MB_NUM_ORDERS(sb)));
1262 * incore got set to the group block bitmap below
1264 ext4_lock_group(sb, group);
1265 /* init the buddy */
1266 memset(data, 0xff, blocksize);
1267 ext4_mb_generate_buddy(sb, data, incore, group, grinfo);
1268 ext4_unlock_group(sb, group);
1271 /* this is block of bitmap */
1272 BUG_ON(incore != NULL);
1273 mb_debug(sb, "put bitmap for group %u in page %lu/%x\n",
1274 group, page->index, i * blocksize);
1275 trace_ext4_mb_bitmap_load(sb, group);
1277 /* see comments in ext4_mb_put_pa() */
1278 ext4_lock_group(sb, group);
1279 memcpy(data, bitmap, blocksize);
1281 /* mark all preallocated blks used in in-core bitmap */
1282 ext4_mb_generate_from_pa(sb, data, group);
1283 ext4_mb_generate_from_freelist(sb, data, group);
1284 ext4_unlock_group(sb, group);
1286 /* set incore so that the buddy information can be
1287 * generated using this
1292 SetPageUptodate(page);
1296 for (i = 0; i < groups_per_page; i++)
1305 * Lock the buddy and bitmap pages. This make sure other parallel init_group
1306 * on the same buddy page doesn't happen whild holding the buddy page lock.
1307 * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
1308 * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
1310 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
1311 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
1313 struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
1314 int block, pnum, poff;
1315 int blocks_per_page;
1318 e4b->bd_buddy_page = NULL;
1319 e4b->bd_bitmap_page = NULL;
1321 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1323 * the buddy cache inode stores the block bitmap
1324 * and buddy information in consecutive blocks.
1325 * So for each group we need two blocks.
1328 pnum = block / blocks_per_page;
1329 poff = block % blocks_per_page;
1330 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1333 BUG_ON(page->mapping != inode->i_mapping);
1334 e4b->bd_bitmap_page = page;
1335 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1337 if (blocks_per_page >= 2) {
1338 /* buddy and bitmap are on the same page */
1343 pnum = block / blocks_per_page;
1344 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1347 BUG_ON(page->mapping != inode->i_mapping);
1348 e4b->bd_buddy_page = page;
1352 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1354 if (e4b->bd_bitmap_page) {
1355 unlock_page(e4b->bd_bitmap_page);
1356 put_page(e4b->bd_bitmap_page);
1358 if (e4b->bd_buddy_page) {
1359 unlock_page(e4b->bd_buddy_page);
1360 put_page(e4b->bd_buddy_page);
1365 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1366 * block group lock of all groups for this page; do not hold the BG lock when
1367 * calling this routine!
1369 static noinline_for_stack
1370 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1373 struct ext4_group_info *this_grp;
1374 struct ext4_buddy e4b;
1379 mb_debug(sb, "init group %u\n", group);
1380 this_grp = ext4_get_group_info(sb, group);
1382 return -EFSCORRUPTED;
1385 * This ensures that we don't reinit the buddy cache
1386 * page which map to the group from which we are already
1387 * allocating. If we are looking at the buddy cache we would
1388 * have taken a reference using ext4_mb_load_buddy and that
1389 * would have pinned buddy page to page cache.
1390 * The call to ext4_mb_get_buddy_page_lock will mark the
1393 ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1394 if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1396 * somebody initialized the group
1397 * return without doing anything
1402 page = e4b.bd_bitmap_page;
1403 ret = ext4_mb_init_cache(page, NULL, gfp);
1406 if (!PageUptodate(page)) {
1411 if (e4b.bd_buddy_page == NULL) {
1413 * If both the bitmap and buddy are in
1414 * the same page we don't need to force
1420 /* init buddy cache */
1421 page = e4b.bd_buddy_page;
1422 ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1425 if (!PageUptodate(page)) {
1430 ext4_mb_put_buddy_page_lock(&e4b);
1435 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1436 * block group lock of all groups for this page; do not hold the BG lock when
1437 * calling this routine!
1439 static noinline_for_stack int
1440 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1441 struct ext4_buddy *e4b, gfp_t gfp)
1443 int blocks_per_page;
1449 struct ext4_group_info *grp;
1450 struct ext4_sb_info *sbi = EXT4_SB(sb);
1451 struct inode *inode = sbi->s_buddy_cache;
1454 mb_debug(sb, "load group %u\n", group);
1456 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1457 grp = ext4_get_group_info(sb, group);
1459 return -EFSCORRUPTED;
1461 e4b->bd_blkbits = sb->s_blocksize_bits;
1464 e4b->bd_group = group;
1465 e4b->bd_buddy_page = NULL;
1466 e4b->bd_bitmap_page = NULL;
1468 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1470 * we need full data about the group
1471 * to make a good selection
1473 ret = ext4_mb_init_group(sb, group, gfp);
1479 * the buddy cache inode stores the block bitmap
1480 * and buddy information in consecutive blocks.
1481 * So for each group we need two blocks.
1484 pnum = block / blocks_per_page;
1485 poff = block % blocks_per_page;
1487 /* we could use find_or_create_page(), but it locks page
1488 * what we'd like to avoid in fast path ... */
1489 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1490 if (page == NULL || !PageUptodate(page)) {
1493 * drop the page reference and try
1494 * to get the page with lock. If we
1495 * are not uptodate that implies
1496 * somebody just created the page but
1497 * is yet to initialize the same. So
1498 * wait for it to initialize.
1501 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1503 if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
1504 "ext4: bitmap's paging->mapping != inode->i_mapping\n")) {
1505 /* should never happen */
1510 if (!PageUptodate(page)) {
1511 ret = ext4_mb_init_cache(page, NULL, gfp);
1516 mb_cmp_bitmaps(e4b, page_address(page) +
1517 (poff * sb->s_blocksize));
1526 if (!PageUptodate(page)) {
1531 /* Pages marked accessed already */
1532 e4b->bd_bitmap_page = page;
1533 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1536 pnum = block / blocks_per_page;
1537 poff = block % blocks_per_page;
1539 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1540 if (page == NULL || !PageUptodate(page)) {
1543 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1545 if (WARN_RATELIMIT(page->mapping != inode->i_mapping,
1546 "ext4: buddy bitmap's page->mapping != inode->i_mapping\n")) {
1547 /* should never happen */
1552 if (!PageUptodate(page)) {
1553 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1567 if (!PageUptodate(page)) {
1572 /* Pages marked accessed already */
1573 e4b->bd_buddy_page = page;
1574 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1581 if (e4b->bd_bitmap_page)
1582 put_page(e4b->bd_bitmap_page);
1584 e4b->bd_buddy = NULL;
1585 e4b->bd_bitmap = NULL;
1589 static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1590 struct ext4_buddy *e4b)
1592 return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1595 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1597 if (e4b->bd_bitmap_page)
1598 put_page(e4b->bd_bitmap_page);
1599 if (e4b->bd_buddy_page)
1600 put_page(e4b->bd_buddy_page);
1604 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1609 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1610 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1612 while (order <= e4b->bd_blkbits + 1) {
1613 bb = mb_find_buddy(e4b, order, &max);
1614 if (!mb_test_bit(block >> order, bb)) {
1615 /* this block is part of buddy of order 'order' */
1623 static void mb_clear_bits(void *bm, int cur, int len)
1629 if ((cur & 31) == 0 && (len - cur) >= 32) {
1630 /* fast path: clear whole word at once */
1631 addr = bm + (cur >> 3);
1636 mb_clear_bit(cur, bm);
1641 /* clear bits in given range
1642 * will return first found zero bit if any, -1 otherwise
1644 static int mb_test_and_clear_bits(void *bm, int cur, int len)
1651 if ((cur & 31) == 0 && (len - cur) >= 32) {
1652 /* fast path: clear whole word at once */
1653 addr = bm + (cur >> 3);
1654 if (*addr != (__u32)(-1) && zero_bit == -1)
1655 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1660 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1668 void mb_set_bits(void *bm, int cur, int len)
1674 if ((cur & 31) == 0 && (len - cur) >= 32) {
1675 /* fast path: set whole word at once */
1676 addr = bm + (cur >> 3);
1681 mb_set_bit(cur, bm);
1686 static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1688 if (mb_test_bit(*bit + side, bitmap)) {
1689 mb_clear_bit(*bit, bitmap);
1695 mb_set_bit(*bit, bitmap);
1700 static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1704 void *buddy = mb_find_buddy(e4b, order, &max);
1709 /* Bits in range [first; last] are known to be set since
1710 * corresponding blocks were allocated. Bits in range
1711 * (first; last) will stay set because they form buddies on
1712 * upper layer. We just deal with borders if they don't
1713 * align with upper layer and then go up.
1714 * Releasing entire group is all about clearing
1715 * single bit of highest order buddy.
1719 * ---------------------------------
1721 * ---------------------------------
1722 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1723 * ---------------------------------
1725 * \_____________________/
1727 * Neither [1] nor [6] is aligned to above layer.
1728 * Left neighbour [0] is free, so mark it busy,
1729 * decrease bb_counters and extend range to
1731 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1732 * mark [6] free, increase bb_counters and shrink range to
1734 * Then shift range to [0; 2], go up and do the same.
1739 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1741 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1746 buddy2 = mb_find_buddy(e4b, order, &max);
1748 mb_clear_bits(buddy, first, last - first + 1);
1749 e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1758 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1759 int first, int count)
1761 int left_is_free = 0;
1762 int right_is_free = 0;
1764 int last = first + count - 1;
1765 struct super_block *sb = e4b->bd_sb;
1767 if (WARN_ON(count == 0))
1769 BUG_ON(last >= (sb->s_blocksize << 3));
1770 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1771 /* Don't bother if the block group is corrupt. */
1772 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1775 mb_check_buddy(e4b);
1776 mb_free_blocks_double(inode, e4b, first, count);
1778 this_cpu_inc(discard_pa_seq);
1779 e4b->bd_info->bb_free += count;
1780 if (first < e4b->bd_info->bb_first_free)
1781 e4b->bd_info->bb_first_free = first;
1783 /* access memory sequentially: check left neighbour,
1784 * clear range and then check right neighbour
1787 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1788 block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1789 if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1790 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1792 if (unlikely(block != -1)) {
1793 struct ext4_sb_info *sbi = EXT4_SB(sb);
1794 ext4_fsblk_t blocknr;
1796 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1797 blocknr += EXT4_C2B(sbi, block);
1798 if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
1799 ext4_grp_locked_error(sb, e4b->bd_group,
1800 inode ? inode->i_ino : 0,
1802 "freeing already freed block (bit %u); block bitmap corrupt.",
1804 ext4_mark_group_bitmap_corrupted(
1806 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1811 /* let's maintain fragments counter */
1812 if (left_is_free && right_is_free)
1813 e4b->bd_info->bb_fragments--;
1814 else if (!left_is_free && !right_is_free)
1815 e4b->bd_info->bb_fragments++;
1817 /* buddy[0] == bd_bitmap is a special case, so handle
1818 * it right away and let mb_buddy_mark_free stay free of
1819 * zero order checks.
1820 * Check if neighbours are to be coaleasced,
1821 * adjust bitmap bb_counters and borders appropriately.
1824 first += !left_is_free;
1825 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1828 last -= !right_is_free;
1829 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1833 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1836 mb_set_largest_free_order(sb, e4b->bd_info);
1837 mb_update_avg_fragment_size(sb, e4b->bd_info);
1838 mb_check_buddy(e4b);
1841 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1842 int needed, struct ext4_free_extent *ex)
1848 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1851 buddy = mb_find_buddy(e4b, 0, &max);
1852 BUG_ON(buddy == NULL);
1853 BUG_ON(block >= max);
1854 if (mb_test_bit(block, buddy)) {
1861 /* find actual order */
1862 order = mb_find_order_for_block(e4b, block);
1863 block = block >> order;
1865 ex->fe_len = 1 << order;
1866 ex->fe_start = block << order;
1867 ex->fe_group = e4b->bd_group;
1869 /* calc difference from given start */
1870 next = next - ex->fe_start;
1872 ex->fe_start += next;
1874 while (needed > ex->fe_len &&
1875 mb_find_buddy(e4b, order, &max)) {
1877 if (block + 1 >= max)
1880 next = (block + 1) * (1 << order);
1881 if (mb_test_bit(next, e4b->bd_bitmap))
1884 order = mb_find_order_for_block(e4b, next);
1886 block = next >> order;
1887 ex->fe_len += 1 << order;
1890 if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
1891 /* Should never happen! (but apparently sometimes does?!?) */
1893 ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
1894 "corruption or bug in mb_find_extent "
1895 "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
1896 block, order, needed, ex->fe_group, ex->fe_start,
1897 ex->fe_len, ex->fe_logical);
1905 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1911 int start = ex->fe_start;
1912 int len = ex->fe_len;
1918 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1919 BUG_ON(e4b->bd_group != ex->fe_group);
1920 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1921 mb_check_buddy(e4b);
1922 mb_mark_used_double(e4b, start, len);
1924 this_cpu_inc(discard_pa_seq);
1925 e4b->bd_info->bb_free -= len;
1926 if (e4b->bd_info->bb_first_free == start)
1927 e4b->bd_info->bb_first_free += len;
1929 /* let's maintain fragments counter */
1931 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1932 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1933 max = !mb_test_bit(start + len, e4b->bd_bitmap);
1935 e4b->bd_info->bb_fragments++;
1936 else if (!mlen && !max)
1937 e4b->bd_info->bb_fragments--;
1939 /* let's maintain buddy itself */
1942 ord = mb_find_order_for_block(e4b, start);
1944 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1945 /* the whole chunk may be allocated at once! */
1948 buddy = mb_find_buddy(e4b, ord, &max);
1951 BUG_ON((start >> ord) >= max);
1952 mb_set_bit(start >> ord, buddy);
1953 e4b->bd_info->bb_counters[ord]--;
1960 /* store for history */
1962 ret = len | (ord << 16);
1964 /* we have to split large buddy */
1966 buddy = mb_find_buddy(e4b, ord, &max);
1967 mb_set_bit(start >> ord, buddy);
1968 e4b->bd_info->bb_counters[ord]--;
1971 cur = (start >> ord) & ~1U;
1972 buddy = mb_find_buddy(e4b, ord, &max);
1973 mb_clear_bit(cur, buddy);
1974 mb_clear_bit(cur + 1, buddy);
1975 e4b->bd_info->bb_counters[ord]++;
1976 e4b->bd_info->bb_counters[ord]++;
1979 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1981 mb_update_avg_fragment_size(e4b->bd_sb, e4b->bd_info);
1982 mb_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1983 mb_check_buddy(e4b);
1989 * Must be called under group lock!
1991 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1992 struct ext4_buddy *e4b)
1994 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1997 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1998 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2000 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
2001 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
2002 ret = mb_mark_used(e4b, &ac->ac_b_ex);
2004 /* preallocation can change ac_b_ex, thus we store actually
2005 * allocated blocks for history */
2006 ac->ac_f_ex = ac->ac_b_ex;
2008 ac->ac_status = AC_STATUS_FOUND;
2009 ac->ac_tail = ret & 0xffff;
2010 ac->ac_buddy = ret >> 16;
2013 * take the page reference. We want the page to be pinned
2014 * so that we don't get a ext4_mb_init_cache_call for this
2015 * group until we update the bitmap. That would mean we
2016 * double allocate blocks. The reference is dropped
2017 * in ext4_mb_release_context
2019 ac->ac_bitmap_page = e4b->bd_bitmap_page;
2020 get_page(ac->ac_bitmap_page);
2021 ac->ac_buddy_page = e4b->bd_buddy_page;
2022 get_page(ac->ac_buddy_page);
2023 /* store last allocated for subsequent stream allocation */
2024 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2025 spin_lock(&sbi->s_md_lock);
2026 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
2027 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
2028 spin_unlock(&sbi->s_md_lock);
2031 * As we've just preallocated more space than
2032 * user requested originally, we store allocated
2033 * space in a special descriptor.
2035 if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
2036 ext4_mb_new_preallocation(ac);
2040 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
2041 struct ext4_buddy *e4b,
2044 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2045 struct ext4_free_extent *bex = &ac->ac_b_ex;
2046 struct ext4_free_extent *gex = &ac->ac_g_ex;
2048 if (ac->ac_status == AC_STATUS_FOUND)
2051 * We don't want to scan for a whole year
2053 if (ac->ac_found > sbi->s_mb_max_to_scan &&
2054 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2055 ac->ac_status = AC_STATUS_BREAK;
2060 * Haven't found good chunk so far, let's continue
2062 if (bex->fe_len < gex->fe_len)
2066 ext4_mb_use_best_found(ac, e4b);
2070 * The routine checks whether found extent is good enough. If it is,
2071 * then the extent gets marked used and flag is set to the context
2072 * to stop scanning. Otherwise, the extent is compared with the
2073 * previous found extent and if new one is better, then it's stored
2074 * in the context. Later, the best found extent will be used, if
2075 * mballoc can't find good enough extent.
2077 * FIXME: real allocation policy is to be designed yet!
2079 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
2080 struct ext4_free_extent *ex,
2081 struct ext4_buddy *e4b)
2083 struct ext4_free_extent *bex = &ac->ac_b_ex;
2084 struct ext4_free_extent *gex = &ac->ac_g_ex;
2086 BUG_ON(ex->fe_len <= 0);
2087 BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2088 BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
2089 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
2094 * The special case - take what you catch first
2096 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2098 ext4_mb_use_best_found(ac, e4b);
2103 * Let's check whether the chuck is good enough
2105 if (ex->fe_len == gex->fe_len) {
2107 ext4_mb_use_best_found(ac, e4b);
2112 * If this is first found extent, just store it in the context
2114 if (bex->fe_len == 0) {
2120 * If new found extent is better, store it in the context
2122 if (bex->fe_len < gex->fe_len) {
2123 /* if the request isn't satisfied, any found extent
2124 * larger than previous best one is better */
2125 if (ex->fe_len > bex->fe_len)
2127 } else if (ex->fe_len > gex->fe_len) {
2128 /* if the request is satisfied, then we try to find
2129 * an extent that still satisfy the request, but is
2130 * smaller than previous one */
2131 if (ex->fe_len < bex->fe_len)
2135 ext4_mb_check_limits(ac, e4b, 0);
2138 static noinline_for_stack
2139 void ext4_mb_try_best_found(struct ext4_allocation_context *ac,
2140 struct ext4_buddy *e4b)
2142 struct ext4_free_extent ex = ac->ac_b_ex;
2143 ext4_group_t group = ex.fe_group;
2147 BUG_ON(ex.fe_len <= 0);
2148 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2152 ext4_lock_group(ac->ac_sb, group);
2153 max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
2157 ext4_mb_use_best_found(ac, e4b);
2160 ext4_unlock_group(ac->ac_sb, group);
2161 ext4_mb_unload_buddy(e4b);
2164 static noinline_for_stack
2165 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
2166 struct ext4_buddy *e4b)
2168 ext4_group_t group = ac->ac_g_ex.fe_group;
2171 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2172 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2173 struct ext4_free_extent ex;
2176 return -EFSCORRUPTED;
2177 if (!(ac->ac_flags & (EXT4_MB_HINT_TRY_GOAL | EXT4_MB_HINT_GOAL_ONLY)))
2179 if (grp->bb_free == 0)
2182 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
2186 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
2187 ext4_mb_unload_buddy(e4b);
2191 ext4_lock_group(ac->ac_sb, group);
2192 max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
2193 ac->ac_g_ex.fe_len, &ex);
2194 ex.fe_logical = 0xDEADFA11; /* debug value */
2196 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
2199 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
2201 /* use do_div to get remainder (would be 64-bit modulo) */
2202 if (do_div(start, sbi->s_stripe) == 0) {
2205 ext4_mb_use_best_found(ac, e4b);
2207 } else if (max >= ac->ac_g_ex.fe_len) {
2208 BUG_ON(ex.fe_len <= 0);
2209 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2210 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2213 ext4_mb_use_best_found(ac, e4b);
2214 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
2215 /* Sometimes, caller may want to merge even small
2216 * number of blocks to an existing extent */
2217 BUG_ON(ex.fe_len <= 0);
2218 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
2219 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
2222 ext4_mb_use_best_found(ac, e4b);
2224 ext4_unlock_group(ac->ac_sb, group);
2225 ext4_mb_unload_buddy(e4b);
2231 * The routine scans buddy structures (not bitmap!) from given order
2232 * to max order and tries to find big enough chunk to satisfy the req
2234 static noinline_for_stack
2235 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
2236 struct ext4_buddy *e4b)
2238 struct super_block *sb = ac->ac_sb;
2239 struct ext4_group_info *grp = e4b->bd_info;
2245 BUG_ON(ac->ac_2order <= 0);
2246 for (i = ac->ac_2order; i < MB_NUM_ORDERS(sb); i++) {
2247 if (grp->bb_counters[i] == 0)
2250 buddy = mb_find_buddy(e4b, i, &max);
2251 if (WARN_RATELIMIT(buddy == NULL,
2252 "ext4: mb_simple_scan_group: mb_find_buddy failed, (%d)\n", i))
2255 k = mb_find_next_zero_bit(buddy, max, 0);
2257 ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
2258 "%d free clusters of order %d. But found 0",
2259 grp->bb_counters[i], i);
2260 ext4_mark_group_bitmap_corrupted(ac->ac_sb,
2262 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2267 ac->ac_b_ex.fe_len = 1 << i;
2268 ac->ac_b_ex.fe_start = k << i;
2269 ac->ac_b_ex.fe_group = e4b->bd_group;
2271 ext4_mb_use_best_found(ac, e4b);
2273 BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
2275 if (EXT4_SB(sb)->s_mb_stats)
2276 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
2283 * The routine scans the group and measures all found extents.
2284 * In order to optimize scanning, caller must pass number of
2285 * free blocks in the group, so the routine can know upper limit.
2287 static noinline_for_stack
2288 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
2289 struct ext4_buddy *e4b)
2291 struct super_block *sb = ac->ac_sb;
2292 void *bitmap = e4b->bd_bitmap;
2293 struct ext4_free_extent ex;
2297 free = e4b->bd_info->bb_free;
2298 if (WARN_ON(free <= 0))
2301 i = e4b->bd_info->bb_first_free;
2303 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
2304 i = mb_find_next_zero_bit(bitmap,
2305 EXT4_CLUSTERS_PER_GROUP(sb), i);
2306 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
2308 * IF we have corrupt bitmap, we won't find any
2309 * free blocks even though group info says we
2312 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2313 "%d free clusters as per "
2314 "group info. But bitmap says 0",
2316 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2317 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2321 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
2322 if (WARN_ON(ex.fe_len <= 0))
2324 if (free < ex.fe_len) {
2325 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
2326 "%d free clusters as per "
2327 "group info. But got %d blocks",
2329 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
2330 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
2332 * The number of free blocks differs. This mostly
2333 * indicate that the bitmap is corrupt. So exit
2334 * without claiming the space.
2338 ex.fe_logical = 0xDEADC0DE; /* debug value */
2339 ext4_mb_measure_extent(ac, &ex, e4b);
2345 ext4_mb_check_limits(ac, e4b, 1);
2349 * This is a special case for storages like raid5
2350 * we try to find stripe-aligned chunks for stripe-size-multiple requests
2352 static noinline_for_stack
2353 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2354 struct ext4_buddy *e4b)
2356 struct super_block *sb = ac->ac_sb;
2357 struct ext4_sb_info *sbi = EXT4_SB(sb);
2358 void *bitmap = e4b->bd_bitmap;
2359 struct ext4_free_extent ex;
2360 ext4_fsblk_t first_group_block;
2365 BUG_ON(sbi->s_stripe == 0);
2367 /* find first stripe-aligned block in group */
2368 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2370 a = first_group_block + sbi->s_stripe - 1;
2371 do_div(a, sbi->s_stripe);
2372 i = (a * sbi->s_stripe) - first_group_block;
2374 while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2375 if (!mb_test_bit(i, bitmap)) {
2376 max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
2377 if (max >= sbi->s_stripe) {
2379 ex.fe_logical = 0xDEADF00D; /* debug value */
2381 ext4_mb_use_best_found(ac, e4b);
2390 * This is also called BEFORE we load the buddy bitmap.
2391 * Returns either 1 or 0 indicating that the group is either suitable
2392 * for the allocation or not.
2394 static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
2395 ext4_group_t group, int cr)
2397 ext4_grpblk_t free, fragments;
2398 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2399 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2401 BUG_ON(cr < 0 || cr >= 4);
2403 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp) || !grp))
2406 free = grp->bb_free;
2410 fragments = grp->bb_fragments;
2416 BUG_ON(ac->ac_2order == 0);
2418 /* Avoid using the first bg of a flexgroup for data files */
2419 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2420 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2421 ((group % flex_size) == 0))
2424 if (free < ac->ac_g_ex.fe_len)
2427 if (ac->ac_2order >= MB_NUM_ORDERS(ac->ac_sb))
2430 if (grp->bb_largest_free_order < ac->ac_2order)
2435 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2439 if (free >= ac->ac_g_ex.fe_len)
2452 * This could return negative error code if something goes wrong
2453 * during ext4_mb_init_group(). This should not be called with
2454 * ext4_lock_group() held.
2456 * Note: because we are conditionally operating with the group lock in
2457 * the EXT4_MB_STRICT_CHECK case, we need to fake out sparse in this
2458 * function using __acquire and __release. This means we need to be
2459 * super careful before messing with the error path handling via "goto
2462 static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
2463 ext4_group_t group, int cr)
2465 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2466 struct super_block *sb = ac->ac_sb;
2467 struct ext4_sb_info *sbi = EXT4_SB(sb);
2468 bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
2473 return -EFSCORRUPTED;
2474 if (sbi->s_mb_stats)
2475 atomic64_inc(&sbi->s_bal_cX_groups_considered[ac->ac_criteria]);
2477 ext4_lock_group(sb, group);
2478 __release(ext4_group_lock_ptr(sb, group));
2480 free = grp->bb_free;
2483 if (cr <= 2 && free < ac->ac_g_ex.fe_len)
2485 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2488 __acquire(ext4_group_lock_ptr(sb, group));
2489 ext4_unlock_group(sb, group);
2492 /* We only do this if the grp has never been initialized */
2493 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2494 struct ext4_group_desc *gdp =
2495 ext4_get_group_desc(sb, group, NULL);
2498 /* cr=0/1 is a very optimistic search to find large
2499 * good chunks almost for free. If buddy data is not
2500 * ready, then this optimization makes no sense. But
2501 * we never skip the first block group in a flex_bg,
2502 * since this gets used for metadata block allocation,
2503 * and we want to make sure we locate metadata blocks
2504 * in the first block group in the flex_bg if possible.
2507 (!sbi->s_log_groups_per_flex ||
2508 ((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
2509 !(ext4_has_group_desc_csum(sb) &&
2510 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
2512 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
2518 ext4_lock_group(sb, group);
2519 __release(ext4_group_lock_ptr(sb, group));
2521 ret = ext4_mb_good_group(ac, group, cr);
2524 __acquire(ext4_group_lock_ptr(sb, group));
2525 ext4_unlock_group(sb, group);
2531 * Start prefetching @nr block bitmaps starting at @group.
2532 * Return the next group which needs to be prefetched.
2534 ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
2535 unsigned int nr, int *cnt)
2537 ext4_group_t ngroups = ext4_get_groups_count(sb);
2538 struct buffer_head *bh;
2539 struct blk_plug plug;
2541 blk_start_plug(&plug);
2543 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
2545 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
2548 * Prefetch block groups with free blocks; but don't
2549 * bother if it is marked uninitialized on disk, since
2550 * it won't require I/O to read. Also only try to
2551 * prefetch once, so we avoid getblk() call, which can
2554 if (gdp && grp && !EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
2555 EXT4_MB_GRP_NEED_INIT(grp) &&
2556 ext4_free_group_clusters(sb, gdp) > 0 &&
2557 !(ext4_has_group_desc_csum(sb) &&
2558 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)))) {
2559 bh = ext4_read_block_bitmap_nowait(sb, group, true);
2560 if (bh && !IS_ERR(bh)) {
2561 if (!buffer_uptodate(bh) && cnt)
2566 if (++group >= ngroups)
2569 blk_finish_plug(&plug);
2574 * Prefetching reads the block bitmap into the buffer cache; but we
2575 * need to make sure that the buddy bitmap in the page cache has been
2576 * initialized. Note that ext4_mb_init_group() will block if the I/O
2577 * is not yet completed, or indeed if it was not initiated by
2578 * ext4_mb_prefetch did not start the I/O.
2580 * TODO: We should actually kick off the buddy bitmap setup in a work
2581 * queue when the buffer I/O is completed, so that we don't block
2582 * waiting for the block allocation bitmap read to finish when
2583 * ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
2585 void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
2588 struct ext4_group_desc *gdp;
2589 struct ext4_group_info *grp;
2593 group = ext4_get_groups_count(sb);
2595 gdp = ext4_get_group_desc(sb, group, NULL);
2596 grp = ext4_get_group_info(sb, group);
2598 if (grp && gdp && EXT4_MB_GRP_NEED_INIT(grp) &&
2599 ext4_free_group_clusters(sb, gdp) > 0 &&
2600 !(ext4_has_group_desc_csum(sb) &&
2601 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)))) {
2602 if (ext4_mb_init_group(sb, group, GFP_NOFS))
2608 static noinline_for_stack int
2609 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2611 ext4_group_t prefetch_grp = 0, ngroups, group, i;
2612 int cr = -1, new_cr;
2613 int err = 0, first_err = 0;
2614 unsigned int nr = 0, prefetch_ios = 0;
2615 struct ext4_sb_info *sbi;
2616 struct super_block *sb;
2617 struct ext4_buddy e4b;
2622 ngroups = ext4_get_groups_count(sb);
2623 /* non-extent files are limited to low blocks/groups */
2624 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2625 ngroups = sbi->s_blockfile_groups;
2627 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2629 /* first, try the goal */
2630 err = ext4_mb_find_by_goal(ac, &e4b);
2631 if (err || ac->ac_status == AC_STATUS_FOUND)
2634 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2638 * ac->ac_2order is set only if the fe_len is a power of 2
2639 * if ac->ac_2order is set we also set criteria to 0 so that we
2640 * try exact allocation using buddy.
2642 i = fls(ac->ac_g_ex.fe_len);
2645 * We search using buddy data only if the order of the request
2646 * is greater than equal to the sbi_s_mb_order2_reqs
2647 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2648 * We also support searching for power-of-two requests only for
2649 * requests upto maximum buddy size we have constructed.
2651 if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) {
2653 * This should tell if fe_len is exactly power of 2
2655 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2656 ac->ac_2order = array_index_nospec(i - 1,
2660 /* if stream allocation is enabled, use global goal */
2661 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2662 /* TBD: may be hot point */
2663 spin_lock(&sbi->s_md_lock);
2664 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2665 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2666 spin_unlock(&sbi->s_md_lock);
2669 /* Let's just scan groups to find more-less suitable blocks */
2670 cr = ac->ac_2order ? 0 : 1;
2672 * cr == 0 try to get exact allocation,
2673 * cr == 3 try to get anything
2676 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2677 ac->ac_criteria = cr;
2679 * searching for the right group start
2680 * from the goal value specified
2682 group = ac->ac_g_ex.fe_group;
2683 ac->ac_groups_linear_remaining = sbi->s_mb_max_linear_groups;
2684 prefetch_grp = group;
2686 for (i = 0, new_cr = cr; i < ngroups; i++,
2687 ext4_mb_choose_next_group(ac, &new_cr, &group, ngroups)) {
2697 * Batch reads of the block allocation bitmaps
2698 * to get multiple READs in flight; limit
2699 * prefetching at cr=0/1, otherwise mballoc can
2700 * spend a lot of time loading imperfect groups
2702 if ((prefetch_grp == group) &&
2704 prefetch_ios < sbi->s_mb_prefetch_limit)) {
2705 unsigned int curr_ios = prefetch_ios;
2707 nr = sbi->s_mb_prefetch;
2708 if (ext4_has_feature_flex_bg(sb)) {
2709 nr = 1 << sbi->s_log_groups_per_flex;
2710 nr -= group & (nr - 1);
2711 nr = min(nr, sbi->s_mb_prefetch);
2713 prefetch_grp = ext4_mb_prefetch(sb, group,
2715 if (prefetch_ios == curr_ios)
2719 /* This now checks without needing the buddy page */
2720 ret = ext4_mb_good_group_nolock(ac, group, cr);
2727 err = ext4_mb_load_buddy(sb, group, &e4b);
2731 ext4_lock_group(sb, group);
2734 * We need to check again after locking the
2737 ret = ext4_mb_good_group(ac, group, cr);
2739 ext4_unlock_group(sb, group);
2740 ext4_mb_unload_buddy(&e4b);
2744 ac->ac_groups_scanned++;
2746 ext4_mb_simple_scan_group(ac, &e4b);
2747 else if (cr == 1 && sbi->s_stripe &&
2748 !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2749 ext4_mb_scan_aligned(ac, &e4b);
2751 ext4_mb_complex_scan_group(ac, &e4b);
2753 ext4_unlock_group(sb, group);
2754 ext4_mb_unload_buddy(&e4b);
2756 if (ac->ac_status != AC_STATUS_CONTINUE)
2759 /* Processed all groups and haven't found blocks */
2760 if (sbi->s_mb_stats && i == ngroups)
2761 atomic64_inc(&sbi->s_bal_cX_failed[cr]);
2764 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2765 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2767 * We've been searching too long. Let's try to allocate
2768 * the best chunk we've found so far
2770 ext4_mb_try_best_found(ac, &e4b);
2771 if (ac->ac_status != AC_STATUS_FOUND) {
2773 * Someone more lucky has already allocated it.
2774 * The only thing we can do is just take first
2777 lost = atomic_inc_return(&sbi->s_mb_lost_chunks);
2778 mb_debug(sb, "lost chunk, group: %u, start: %d, len: %d, lost: %d\n",
2779 ac->ac_b_ex.fe_group, ac->ac_b_ex.fe_start,
2780 ac->ac_b_ex.fe_len, lost);
2782 ac->ac_b_ex.fe_group = 0;
2783 ac->ac_b_ex.fe_start = 0;
2784 ac->ac_b_ex.fe_len = 0;
2785 ac->ac_status = AC_STATUS_CONTINUE;
2786 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2792 if (sbi->s_mb_stats && ac->ac_status == AC_STATUS_FOUND)
2793 atomic64_inc(&sbi->s_bal_cX_hits[ac->ac_criteria]);
2795 if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2798 mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
2799 ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
2800 ac->ac_flags, cr, err);
2803 ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
2808 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2810 struct super_block *sb = pde_data(file_inode(seq->file));
2813 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2816 return (void *) ((unsigned long) group);
2819 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2821 struct super_block *sb = pde_data(file_inode(seq->file));
2825 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2828 return (void *) ((unsigned long) group);
2831 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2833 struct super_block *sb = pde_data(file_inode(seq->file));
2834 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2836 int err, buddy_loaded = 0;
2837 struct ext4_buddy e4b;
2838 struct ext4_group_info *grinfo;
2839 unsigned char blocksize_bits = min_t(unsigned char,
2840 sb->s_blocksize_bits,
2841 EXT4_MAX_BLOCK_LOG_SIZE);
2843 struct ext4_group_info info;
2844 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
2849 seq_puts(seq, "#group: free frags first ["
2850 " 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
2851 " 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
2853 i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2854 sizeof(struct ext4_group_info);
2856 grinfo = ext4_get_group_info(sb, group);
2859 /* Load the group info in memory only if not already loaded. */
2860 if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
2861 err = ext4_mb_load_buddy(sb, group, &e4b);
2863 seq_printf(seq, "#%-5u: I/O error\n", group);
2869 memcpy(&sg, grinfo, i);
2872 ext4_mb_unload_buddy(&e4b);
2874 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2875 sg.info.bb_fragments, sg.info.bb_first_free);
2876 for (i = 0; i <= 13; i++)
2877 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
2878 sg.info.bb_counters[i] : 0);
2879 seq_puts(seq, " ]\n");
2884 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2888 const struct seq_operations ext4_mb_seq_groups_ops = {
2889 .start = ext4_mb_seq_groups_start,
2890 .next = ext4_mb_seq_groups_next,
2891 .stop = ext4_mb_seq_groups_stop,
2892 .show = ext4_mb_seq_groups_show,
2895 int ext4_seq_mb_stats_show(struct seq_file *seq, void *offset)
2897 struct super_block *sb = seq->private;
2898 struct ext4_sb_info *sbi = EXT4_SB(sb);
2900 seq_puts(seq, "mballoc:\n");
2901 if (!sbi->s_mb_stats) {
2902 seq_puts(seq, "\tmb stats collection turned off.\n");
2903 seq_puts(seq, "\tTo enable, please write \"1\" to sysfs file mb_stats.\n");
2906 seq_printf(seq, "\treqs: %u\n", atomic_read(&sbi->s_bal_reqs));
2907 seq_printf(seq, "\tsuccess: %u\n", atomic_read(&sbi->s_bal_success));
2909 seq_printf(seq, "\tgroups_scanned: %u\n", atomic_read(&sbi->s_bal_groups_scanned));
2911 seq_puts(seq, "\tcr0_stats:\n");
2912 seq_printf(seq, "\t\thits: %llu\n", atomic64_read(&sbi->s_bal_cX_hits[0]));
2913 seq_printf(seq, "\t\tgroups_considered: %llu\n",
2914 atomic64_read(&sbi->s_bal_cX_groups_considered[0]));
2915 seq_printf(seq, "\t\tuseless_loops: %llu\n",
2916 atomic64_read(&sbi->s_bal_cX_failed[0]));
2917 seq_printf(seq, "\t\tbad_suggestions: %u\n",
2918 atomic_read(&sbi->s_bal_cr0_bad_suggestions));
2920 seq_puts(seq, "\tcr1_stats:\n");
2921 seq_printf(seq, "\t\thits: %llu\n", atomic64_read(&sbi->s_bal_cX_hits[1]));
2922 seq_printf(seq, "\t\tgroups_considered: %llu\n",
2923 atomic64_read(&sbi->s_bal_cX_groups_considered[1]));
2924 seq_printf(seq, "\t\tuseless_loops: %llu\n",
2925 atomic64_read(&sbi->s_bal_cX_failed[1]));
2926 seq_printf(seq, "\t\tbad_suggestions: %u\n",
2927 atomic_read(&sbi->s_bal_cr1_bad_suggestions));
2929 seq_puts(seq, "\tcr2_stats:\n");
2930 seq_printf(seq, "\t\thits: %llu\n", atomic64_read(&sbi->s_bal_cX_hits[2]));
2931 seq_printf(seq, "\t\tgroups_considered: %llu\n",
2932 atomic64_read(&sbi->s_bal_cX_groups_considered[2]));
2933 seq_printf(seq, "\t\tuseless_loops: %llu\n",
2934 atomic64_read(&sbi->s_bal_cX_failed[2]));
2936 seq_puts(seq, "\tcr3_stats:\n");
2937 seq_printf(seq, "\t\thits: %llu\n", atomic64_read(&sbi->s_bal_cX_hits[3]));
2938 seq_printf(seq, "\t\tgroups_considered: %llu\n",
2939 atomic64_read(&sbi->s_bal_cX_groups_considered[3]));
2940 seq_printf(seq, "\t\tuseless_loops: %llu\n",
2941 atomic64_read(&sbi->s_bal_cX_failed[3]));
2942 seq_printf(seq, "\textents_scanned: %u\n", atomic_read(&sbi->s_bal_ex_scanned));
2943 seq_printf(seq, "\t\tgoal_hits: %u\n", atomic_read(&sbi->s_bal_goals));
2944 seq_printf(seq, "\t\t2^n_hits: %u\n", atomic_read(&sbi->s_bal_2orders));
2945 seq_printf(seq, "\t\tbreaks: %u\n", atomic_read(&sbi->s_bal_breaks));
2946 seq_printf(seq, "\t\tlost: %u\n", atomic_read(&sbi->s_mb_lost_chunks));
2948 seq_printf(seq, "\tbuddies_generated: %u/%u\n",
2949 atomic_read(&sbi->s_mb_buddies_generated),
2950 ext4_get_groups_count(sb));
2951 seq_printf(seq, "\tbuddies_time_used: %llu\n",
2952 atomic64_read(&sbi->s_mb_generation_time));
2953 seq_printf(seq, "\tpreallocated: %u\n",
2954 atomic_read(&sbi->s_mb_preallocated));
2955 seq_printf(seq, "\tdiscarded: %u\n",
2956 atomic_read(&sbi->s_mb_discarded));
2960 static void *ext4_mb_seq_structs_summary_start(struct seq_file *seq, loff_t *pos)
2961 __acquires(&EXT4_SB(sb)->s_mb_rb_lock)
2963 struct super_block *sb = pde_data(file_inode(seq->file));
2964 unsigned long position;
2966 if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
2968 position = *pos + 1;
2969 return (void *) ((unsigned long) position);
2972 static void *ext4_mb_seq_structs_summary_next(struct seq_file *seq, void *v, loff_t *pos)
2974 struct super_block *sb = pde_data(file_inode(seq->file));
2975 unsigned long position;
2978 if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
2980 position = *pos + 1;
2981 return (void *) ((unsigned long) position);
2984 static int ext4_mb_seq_structs_summary_show(struct seq_file *seq, void *v)
2986 struct super_block *sb = pde_data(file_inode(seq->file));
2987 struct ext4_sb_info *sbi = EXT4_SB(sb);
2988 unsigned long position = ((unsigned long) v);
2989 struct ext4_group_info *grp;
2993 if (position >= MB_NUM_ORDERS(sb)) {
2994 position -= MB_NUM_ORDERS(sb);
2996 seq_puts(seq, "avg_fragment_size_lists:\n");
2999 read_lock(&sbi->s_mb_avg_fragment_size_locks[position]);
3000 list_for_each_entry(grp, &sbi->s_mb_avg_fragment_size[position],
3001 bb_avg_fragment_size_node)
3003 read_unlock(&sbi->s_mb_avg_fragment_size_locks[position]);
3004 seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3005 (unsigned int)position, count);
3009 if (position == 0) {
3010 seq_printf(seq, "optimize_scan: %d\n",
3011 test_opt2(sb, MB_OPTIMIZE_SCAN) ? 1 : 0);
3012 seq_puts(seq, "max_free_order_lists:\n");
3015 read_lock(&sbi->s_mb_largest_free_orders_locks[position]);
3016 list_for_each_entry(grp, &sbi->s_mb_largest_free_orders[position],
3017 bb_largest_free_order_node)
3019 read_unlock(&sbi->s_mb_largest_free_orders_locks[position]);
3020 seq_printf(seq, "\tlist_order_%u_groups: %u\n",
3021 (unsigned int)position, count);
3026 static void ext4_mb_seq_structs_summary_stop(struct seq_file *seq, void *v)
3030 const struct seq_operations ext4_mb_seq_structs_summary_ops = {
3031 .start = ext4_mb_seq_structs_summary_start,
3032 .next = ext4_mb_seq_structs_summary_next,
3033 .stop = ext4_mb_seq_structs_summary_stop,
3034 .show = ext4_mb_seq_structs_summary_show,
3037 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
3039 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3040 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
3047 * Allocate the top-level s_group_info array for the specified number
3050 int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
3052 struct ext4_sb_info *sbi = EXT4_SB(sb);
3054 struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
3056 size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
3057 EXT4_DESC_PER_BLOCK_BITS(sb);
3058 if (size <= sbi->s_group_info_size)
3061 size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
3062 new_groupinfo = kvzalloc(size, GFP_KERNEL);
3063 if (!new_groupinfo) {
3064 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
3068 old_groupinfo = rcu_dereference(sbi->s_group_info);
3070 memcpy(new_groupinfo, old_groupinfo,
3071 sbi->s_group_info_size * sizeof(*sbi->s_group_info));
3073 rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
3074 sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
3076 ext4_kvfree_array_rcu(old_groupinfo);
3077 ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
3078 sbi->s_group_info_size);
3082 /* Create and initialize ext4_group_info data for the given group. */
3083 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
3084 struct ext4_group_desc *desc)
3088 int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
3089 struct ext4_sb_info *sbi = EXT4_SB(sb);
3090 struct ext4_group_info **meta_group_info;
3091 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3094 * First check if this group is the first of a reserved block.
3095 * If it's true, we have to allocate a new table of pointers
3096 * to ext4_group_info structures
3098 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3099 metalen = sizeof(*meta_group_info) <<
3100 EXT4_DESC_PER_BLOCK_BITS(sb);
3101 meta_group_info = kmalloc(metalen, GFP_NOFS);
3102 if (meta_group_info == NULL) {
3103 ext4_msg(sb, KERN_ERR, "can't allocate mem "
3104 "for a buddy group");
3108 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
3112 meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
3113 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
3115 meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
3116 if (meta_group_info[i] == NULL) {
3117 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
3118 goto exit_group_info;
3120 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
3121 &(meta_group_info[i]->bb_state));
3124 * initialize bb_free to be able to skip
3125 * empty groups without initialization
3127 if (ext4_has_group_desc_csum(sb) &&
3128 (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3129 meta_group_info[i]->bb_free =
3130 ext4_free_clusters_after_init(sb, group, desc);
3132 meta_group_info[i]->bb_free =
3133 ext4_free_group_clusters(sb, desc);
3136 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
3137 init_rwsem(&meta_group_info[i]->alloc_sem);
3138 meta_group_info[i]->bb_free_root = RB_ROOT;
3139 INIT_LIST_HEAD(&meta_group_info[i]->bb_largest_free_order_node);
3140 INIT_LIST_HEAD(&meta_group_info[i]->bb_avg_fragment_size_node);
3141 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
3142 meta_group_info[i]->bb_avg_fragment_size_order = -1; /* uninit */
3143 meta_group_info[i]->bb_group = group;
3145 mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
3149 /* If a meta_group_info table has been allocated, release it now */
3150 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
3151 struct ext4_group_info ***group_info;
3154 group_info = rcu_dereference(sbi->s_group_info);
3155 kfree(group_info[idx]);
3156 group_info[idx] = NULL;
3160 } /* ext4_mb_add_groupinfo */
3162 static int ext4_mb_init_backend(struct super_block *sb)
3164 ext4_group_t ngroups = ext4_get_groups_count(sb);
3166 struct ext4_sb_info *sbi = EXT4_SB(sb);
3168 struct ext4_group_desc *desc;
3169 struct ext4_group_info ***group_info;
3170 struct kmem_cache *cachep;
3172 err = ext4_mb_alloc_groupinfo(sb, ngroups);
3176 sbi->s_buddy_cache = new_inode(sb);
3177 if (sbi->s_buddy_cache == NULL) {
3178 ext4_msg(sb, KERN_ERR, "can't get new inode");
3181 /* To avoid potentially colliding with an valid on-disk inode number,
3182 * use EXT4_BAD_INO for the buddy cache inode number. This inode is
3183 * not in the inode hash, so it should never be found by iget(), but
3184 * this will avoid confusion if it ever shows up during debugging. */
3185 sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
3186 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
3187 for (i = 0; i < ngroups; i++) {
3189 desc = ext4_get_group_desc(sb, i, NULL);
3191 ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
3194 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
3198 if (ext4_has_feature_flex_bg(sb)) {
3199 /* a single flex group is supposed to be read by a single IO.
3200 * 2 ^ s_log_groups_per_flex != UINT_MAX as s_mb_prefetch is
3201 * unsigned integer, so the maximum shift is 32.
3203 if (sbi->s_es->s_log_groups_per_flex >= 32) {
3204 ext4_msg(sb, KERN_ERR, "too many log groups per flexible block group");
3207 sbi->s_mb_prefetch = min_t(uint, 1 << sbi->s_es->s_log_groups_per_flex,
3208 BLK_MAX_SEGMENT_SIZE >> (sb->s_blocksize_bits - 9));
3209 sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
3211 sbi->s_mb_prefetch = 32;
3213 if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
3214 sbi->s_mb_prefetch = ext4_get_groups_count(sb);
3215 /* now many real IOs to prefetch within a single allocation at cr=0
3216 * given cr=0 is an CPU-related optimization we shouldn't try to
3217 * load too many groups, at some point we should start to use what
3218 * we've got in memory.
3219 * with an average random access time 5ms, it'd take a second to get
3220 * 200 groups (* N with flex_bg), so let's make this limit 4
3222 sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
3223 if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
3224 sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
3229 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3231 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3234 kmem_cache_free(cachep, grp);
3236 i = sbi->s_group_info_size;
3238 group_info = rcu_dereference(sbi->s_group_info);
3240 kfree(group_info[i]);
3242 iput(sbi->s_buddy_cache);
3245 kvfree(rcu_dereference(sbi->s_group_info));
3250 static void ext4_groupinfo_destroy_slabs(void)
3254 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
3255 kmem_cache_destroy(ext4_groupinfo_caches[i]);
3256 ext4_groupinfo_caches[i] = NULL;
3260 static int ext4_groupinfo_create_slab(size_t size)
3262 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
3264 int blocksize_bits = order_base_2(size);
3265 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
3266 struct kmem_cache *cachep;
3268 if (cache_index >= NR_GRPINFO_CACHES)
3271 if (unlikely(cache_index < 0))
3274 mutex_lock(&ext4_grpinfo_slab_create_mutex);
3275 if (ext4_groupinfo_caches[cache_index]) {
3276 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
3277 return 0; /* Already created */
3280 slab_size = offsetof(struct ext4_group_info,
3281 bb_counters[blocksize_bits + 2]);
3283 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
3284 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
3287 ext4_groupinfo_caches[cache_index] = cachep;
3289 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
3292 "EXT4-fs: no memory for groupinfo slab cache\n");
3299 static void ext4_discard_work(struct work_struct *work)
3301 struct ext4_sb_info *sbi = container_of(work,
3302 struct ext4_sb_info, s_discard_work);
3303 struct super_block *sb = sbi->s_sb;
3304 struct ext4_free_data *fd, *nfd;
3305 struct ext4_buddy e4b;
3306 struct list_head discard_list;
3307 ext4_group_t grp, load_grp;
3310 INIT_LIST_HEAD(&discard_list);
3311 spin_lock(&sbi->s_md_lock);
3312 list_splice_init(&sbi->s_discard_list, &discard_list);
3313 spin_unlock(&sbi->s_md_lock);
3315 load_grp = UINT_MAX;
3316 list_for_each_entry_safe(fd, nfd, &discard_list, efd_list) {
3318 * If filesystem is umounting or no memory or suffering
3319 * from no space, give up the discard
3321 if ((sb->s_flags & SB_ACTIVE) && !err &&
3322 !atomic_read(&sbi->s_retry_alloc_pending)) {
3323 grp = fd->efd_group;
3324 if (grp != load_grp) {
3325 if (load_grp != UINT_MAX)
3326 ext4_mb_unload_buddy(&e4b);
3328 err = ext4_mb_load_buddy(sb, grp, &e4b);
3330 kmem_cache_free(ext4_free_data_cachep, fd);
3331 load_grp = UINT_MAX;
3338 ext4_lock_group(sb, grp);
3339 ext4_try_to_trim_range(sb, &e4b, fd->efd_start_cluster,
3340 fd->efd_start_cluster + fd->efd_count - 1, 1);
3341 ext4_unlock_group(sb, grp);
3343 kmem_cache_free(ext4_free_data_cachep, fd);
3346 if (load_grp != UINT_MAX)
3347 ext4_mb_unload_buddy(&e4b);
3350 int ext4_mb_init(struct super_block *sb)
3352 struct ext4_sb_info *sbi = EXT4_SB(sb);
3354 unsigned offset, offset_incr;
3358 i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_offsets);
3360 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
3361 if (sbi->s_mb_offsets == NULL) {
3366 i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_maxs);
3367 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
3368 if (sbi->s_mb_maxs == NULL) {
3373 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
3377 /* order 0 is regular bitmap */
3378 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
3379 sbi->s_mb_offsets[0] = 0;
3383 offset_incr = 1 << (sb->s_blocksize_bits - 1);
3384 max = sb->s_blocksize << 2;
3386 sbi->s_mb_offsets[i] = offset;
3387 sbi->s_mb_maxs[i] = max;
3388 offset += offset_incr;
3389 offset_incr = offset_incr >> 1;
3392 } while (i < MB_NUM_ORDERS(sb));
3394 sbi->s_mb_avg_fragment_size =
3395 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3397 if (!sbi->s_mb_avg_fragment_size) {
3401 sbi->s_mb_avg_fragment_size_locks =
3402 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3404 if (!sbi->s_mb_avg_fragment_size_locks) {
3408 for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3409 INIT_LIST_HEAD(&sbi->s_mb_avg_fragment_size[i]);
3410 rwlock_init(&sbi->s_mb_avg_fragment_size_locks[i]);
3412 sbi->s_mb_largest_free_orders =
3413 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
3415 if (!sbi->s_mb_largest_free_orders) {
3419 sbi->s_mb_largest_free_orders_locks =
3420 kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
3422 if (!sbi->s_mb_largest_free_orders_locks) {
3426 for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
3427 INIT_LIST_HEAD(&sbi->s_mb_largest_free_orders[i]);
3428 rwlock_init(&sbi->s_mb_largest_free_orders_locks[i]);
3431 spin_lock_init(&sbi->s_md_lock);
3432 sbi->s_mb_free_pending = 0;
3433 INIT_LIST_HEAD(&sbi->s_freed_data_list);
3434 INIT_LIST_HEAD(&sbi->s_discard_list);
3435 INIT_WORK(&sbi->s_discard_work, ext4_discard_work);
3436 atomic_set(&sbi->s_retry_alloc_pending, 0);
3438 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
3439 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
3440 sbi->s_mb_stats = MB_DEFAULT_STATS;
3441 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
3442 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
3444 * The default group preallocation is 512, which for 4k block
3445 * sizes translates to 2 megabytes. However for bigalloc file
3446 * systems, this is probably too big (i.e, if the cluster size
3447 * is 1 megabyte, then group preallocation size becomes half a
3448 * gigabyte!). As a default, we will keep a two megabyte
3449 * group pralloc size for cluster sizes up to 64k, and after
3450 * that, we will force a minimum group preallocation size of
3451 * 32 clusters. This translates to 8 megs when the cluster
3452 * size is 256k, and 32 megs when the cluster size is 1 meg,
3453 * which seems reasonable as a default.
3455 sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
3456 sbi->s_cluster_bits, 32);
3458 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
3459 * to the lowest multiple of s_stripe which is bigger than
3460 * the s_mb_group_prealloc as determined above. We want
3461 * the preallocation size to be an exact multiple of the
3462 * RAID stripe size so that preallocations don't fragment
3465 if (sbi->s_stripe > 1) {
3466 sbi->s_mb_group_prealloc = roundup(
3467 sbi->s_mb_group_prealloc, sbi->s_stripe);
3470 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
3471 if (sbi->s_locality_groups == NULL) {
3475 for_each_possible_cpu(i) {
3476 struct ext4_locality_group *lg;
3477 lg = per_cpu_ptr(sbi->s_locality_groups, i);
3478 mutex_init(&lg->lg_mutex);
3479 for (j = 0; j < PREALLOC_TB_SIZE; j++)
3480 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
3481 spin_lock_init(&lg->lg_prealloc_lock);
3484 if (bdev_nonrot(sb->s_bdev))
3485 sbi->s_mb_max_linear_groups = 0;
3487 sbi->s_mb_max_linear_groups = MB_DEFAULT_LINEAR_LIMIT;
3488 /* init file for buddy data */
3489 ret = ext4_mb_init_backend(sb);
3491 goto out_free_locality_groups;
3495 out_free_locality_groups:
3496 free_percpu(sbi->s_locality_groups);
3497 sbi->s_locality_groups = NULL;
3499 kfree(sbi->s_mb_avg_fragment_size);
3500 kfree(sbi->s_mb_avg_fragment_size_locks);
3501 kfree(sbi->s_mb_largest_free_orders);
3502 kfree(sbi->s_mb_largest_free_orders_locks);
3503 kfree(sbi->s_mb_offsets);
3504 sbi->s_mb_offsets = NULL;
3505 kfree(sbi->s_mb_maxs);
3506 sbi->s_mb_maxs = NULL;
3510 /* need to called with the ext4 group lock held */
3511 static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
3513 struct ext4_prealloc_space *pa;
3514 struct list_head *cur, *tmp;
3517 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
3518 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3519 list_del(&pa->pa_group_list);
3521 kmem_cache_free(ext4_pspace_cachep, pa);
3526 int ext4_mb_release(struct super_block *sb)
3528 ext4_group_t ngroups = ext4_get_groups_count(sb);
3530 int num_meta_group_infos;
3531 struct ext4_group_info *grinfo, ***group_info;
3532 struct ext4_sb_info *sbi = EXT4_SB(sb);
3533 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
3536 if (test_opt(sb, DISCARD)) {
3538 * wait the discard work to drain all of ext4_free_data
3540 flush_work(&sbi->s_discard_work);
3541 WARN_ON_ONCE(!list_empty(&sbi->s_discard_list));
3544 if (sbi->s_group_info) {
3545 for (i = 0; i < ngroups; i++) {
3547 grinfo = ext4_get_group_info(sb, i);
3550 mb_group_bb_bitmap_free(grinfo);
3551 ext4_lock_group(sb, i);
3552 count = ext4_mb_cleanup_pa(grinfo);
3554 mb_debug(sb, "mballoc: %d PAs left\n",
3556 ext4_unlock_group(sb, i);
3557 kmem_cache_free(cachep, grinfo);
3559 num_meta_group_infos = (ngroups +
3560 EXT4_DESC_PER_BLOCK(sb) - 1) >>
3561 EXT4_DESC_PER_BLOCK_BITS(sb);
3563 group_info = rcu_dereference(sbi->s_group_info);
3564 for (i = 0; i < num_meta_group_infos; i++)
3565 kfree(group_info[i]);
3569 kfree(sbi->s_mb_avg_fragment_size);
3570 kfree(sbi->s_mb_avg_fragment_size_locks);
3571 kfree(sbi->s_mb_largest_free_orders);
3572 kfree(sbi->s_mb_largest_free_orders_locks);
3573 kfree(sbi->s_mb_offsets);
3574 kfree(sbi->s_mb_maxs);
3575 iput(sbi->s_buddy_cache);
3576 if (sbi->s_mb_stats) {
3577 ext4_msg(sb, KERN_INFO,
3578 "mballoc: %u blocks %u reqs (%u success)",
3579 atomic_read(&sbi->s_bal_allocated),
3580 atomic_read(&sbi->s_bal_reqs),
3581 atomic_read(&sbi->s_bal_success));
3582 ext4_msg(sb, KERN_INFO,
3583 "mballoc: %u extents scanned, %u groups scanned, %u goal hits, "
3584 "%u 2^N hits, %u breaks, %u lost",
3585 atomic_read(&sbi->s_bal_ex_scanned),
3586 atomic_read(&sbi->s_bal_groups_scanned),
3587 atomic_read(&sbi->s_bal_goals),
3588 atomic_read(&sbi->s_bal_2orders),
3589 atomic_read(&sbi->s_bal_breaks),
3590 atomic_read(&sbi->s_mb_lost_chunks));
3591 ext4_msg(sb, KERN_INFO,
3592 "mballoc: %u generated and it took %llu",
3593 atomic_read(&sbi->s_mb_buddies_generated),
3594 atomic64_read(&sbi->s_mb_generation_time));
3595 ext4_msg(sb, KERN_INFO,
3596 "mballoc: %u preallocated, %u discarded",
3597 atomic_read(&sbi->s_mb_preallocated),
3598 atomic_read(&sbi->s_mb_discarded));
3601 free_percpu(sbi->s_locality_groups);
3606 static inline int ext4_issue_discard(struct super_block *sb,
3607 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
3610 ext4_fsblk_t discard_block;
3612 discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
3613 ext4_group_first_block_no(sb, block_group));
3614 count = EXT4_C2B(EXT4_SB(sb), count);
3615 trace_ext4_discard_blocks(sb,
3616 (unsigned long long) discard_block, count);
3618 return __blkdev_issue_discard(sb->s_bdev,
3619 (sector_t)discard_block << (sb->s_blocksize_bits - 9),
3620 (sector_t)count << (sb->s_blocksize_bits - 9),
3623 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
3626 static void ext4_free_data_in_buddy(struct super_block *sb,
3627 struct ext4_free_data *entry)
3629 struct ext4_buddy e4b;
3630 struct ext4_group_info *db;
3633 mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
3634 entry->efd_count, entry->efd_group, entry);
3636 err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
3637 /* we expect to find existing buddy because it's pinned */
3640 spin_lock(&EXT4_SB(sb)->s_md_lock);
3641 EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
3642 spin_unlock(&EXT4_SB(sb)->s_md_lock);
3645 /* there are blocks to put in buddy to make them really free */
3646 count += entry->efd_count;
3647 ext4_lock_group(sb, entry->efd_group);
3648 /* Take it out of per group rb tree */
3649 rb_erase(&entry->efd_node, &(db->bb_free_root));
3650 mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
3653 * Clear the trimmed flag for the group so that the next
3654 * ext4_trim_fs can trim it.
3655 * If the volume is mounted with -o discard, online discard
3656 * is supported and the free blocks will be trimmed online.
3658 if (!test_opt(sb, DISCARD))
3659 EXT4_MB_GRP_CLEAR_TRIMMED(db);
3661 if (!db->bb_free_root.rb_node) {
3662 /* No more items in the per group rb tree
3663 * balance refcounts from ext4_mb_free_metadata()
3665 put_page(e4b.bd_buddy_page);
3666 put_page(e4b.bd_bitmap_page);
3668 ext4_unlock_group(sb, entry->efd_group);
3669 ext4_mb_unload_buddy(&e4b);
3671 mb_debug(sb, "freed %d blocks in 1 structures\n", count);
3675 * This function is called by the jbd2 layer once the commit has finished,
3676 * so we know we can free the blocks that were released with that commit.
3678 void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
3680 struct ext4_sb_info *sbi = EXT4_SB(sb);
3681 struct ext4_free_data *entry, *tmp;
3682 struct list_head freed_data_list;
3683 struct list_head *cut_pos = NULL;
3686 INIT_LIST_HEAD(&freed_data_list);
3688 spin_lock(&sbi->s_md_lock);
3689 list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
3690 if (entry->efd_tid != commit_tid)
3692 cut_pos = &entry->efd_list;
3695 list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
3697 spin_unlock(&sbi->s_md_lock);
3699 list_for_each_entry(entry, &freed_data_list, efd_list)
3700 ext4_free_data_in_buddy(sb, entry);
3702 if (test_opt(sb, DISCARD)) {
3703 spin_lock(&sbi->s_md_lock);
3704 wake = list_empty(&sbi->s_discard_list);
3705 list_splice_tail(&freed_data_list, &sbi->s_discard_list);
3706 spin_unlock(&sbi->s_md_lock);
3708 queue_work(system_unbound_wq, &sbi->s_discard_work);
3710 list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
3711 kmem_cache_free(ext4_free_data_cachep, entry);
3715 int __init ext4_init_mballoc(void)
3717 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
3718 SLAB_RECLAIM_ACCOUNT);
3719 if (ext4_pspace_cachep == NULL)
3722 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
3723 SLAB_RECLAIM_ACCOUNT);
3724 if (ext4_ac_cachep == NULL)
3727 ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
3728 SLAB_RECLAIM_ACCOUNT);
3729 if (ext4_free_data_cachep == NULL)
3735 kmem_cache_destroy(ext4_ac_cachep);
3737 kmem_cache_destroy(ext4_pspace_cachep);
3742 void ext4_exit_mballoc(void)
3745 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
3746 * before destroying the slab cache.
3749 kmem_cache_destroy(ext4_pspace_cachep);
3750 kmem_cache_destroy(ext4_ac_cachep);
3751 kmem_cache_destroy(ext4_free_data_cachep);
3752 ext4_groupinfo_destroy_slabs();
3757 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
3758 * Returns 0 if success or error code
3760 static noinline_for_stack int
3761 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
3762 handle_t *handle, unsigned int reserv_clstrs)
3764 struct buffer_head *bitmap_bh = NULL;
3765 struct ext4_group_desc *gdp;
3766 struct buffer_head *gdp_bh;
3767 struct ext4_sb_info *sbi;
3768 struct super_block *sb;
3772 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3773 BUG_ON(ac->ac_b_ex.fe_len <= 0);
3778 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
3779 if (IS_ERR(bitmap_bh)) {
3780 return PTR_ERR(bitmap_bh);
3783 BUFFER_TRACE(bitmap_bh, "getting write access");
3784 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
3790 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3794 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
3795 ext4_free_group_clusters(sb, gdp));
3797 BUFFER_TRACE(gdp_bh, "get_write_access");
3798 err = ext4_journal_get_write_access(handle, sb, gdp_bh, EXT4_JTR_NONE);
3802 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3804 len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3805 if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
3806 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
3807 "fs metadata", block, block+len);
3808 /* File system mounted not to panic on error
3809 * Fix the bitmap and return EFSCORRUPTED
3810 * We leak some of the blocks here.
3812 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3813 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3814 ac->ac_b_ex.fe_len);
3815 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3816 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3818 err = -EFSCORRUPTED;
3822 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3823 #ifdef AGGRESSIVE_CHECK
3826 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3827 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3828 bitmap_bh->b_data));
3832 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3833 ac->ac_b_ex.fe_len);
3834 if (ext4_has_group_desc_csum(sb) &&
3835 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3836 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3837 ext4_free_group_clusters_set(sb, gdp,
3838 ext4_free_clusters_after_init(sb,
3839 ac->ac_b_ex.fe_group, gdp));
3841 len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
3842 ext4_free_group_clusters_set(sb, gdp, len);
3843 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
3844 ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
3846 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3847 percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
3849 * Now reduce the dirty block count also. Should not go negative
3851 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3852 /* release all the reserved blocks if non delalloc */
3853 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
3856 if (sbi->s_log_groups_per_flex) {
3857 ext4_group_t flex_group = ext4_flex_group(sbi,
3858 ac->ac_b_ex.fe_group);
3859 atomic64_sub(ac->ac_b_ex.fe_len,
3860 &sbi_array_rcu_deref(sbi, s_flex_groups,
3861 flex_group)->free_clusters);
3864 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3867 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3875 * Idempotent helper for Ext4 fast commit replay path to set the state of
3876 * blocks in bitmaps and update counters.
3878 void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
3881 struct buffer_head *bitmap_bh = NULL;
3882 struct ext4_group_desc *gdp;
3883 struct buffer_head *gdp_bh;
3884 struct ext4_sb_info *sbi = EXT4_SB(sb);
3886 ext4_grpblk_t blkoff;
3889 unsigned int clen, clen_changed, thisgrp_len;
3892 ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
3895 * Check to see if we are freeing blocks across a group
3897 * In case of flex_bg, this can happen that (block, len) may
3898 * span across more than one group. In that case we need to
3899 * get the corresponding group metadata to work with.
3900 * For this we have goto again loop.
3902 thisgrp_len = min_t(unsigned int, (unsigned int)len,
3903 EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
3904 clen = EXT4_NUM_B2C(sbi, thisgrp_len);
3906 if (!ext4_sb_block_valid(sb, NULL, block, thisgrp_len)) {
3907 ext4_error(sb, "Marking blocks in system zone - "
3908 "Block = %llu, len = %u",
3909 block, thisgrp_len);
3914 bitmap_bh = ext4_read_block_bitmap(sb, group);
3915 if (IS_ERR(bitmap_bh)) {
3916 err = PTR_ERR(bitmap_bh);
3922 gdp = ext4_get_group_desc(sb, group, &gdp_bh);
3926 ext4_lock_group(sb, group);
3928 for (i = 0; i < clen; i++)
3929 if (!mb_test_bit(blkoff + i, bitmap_bh->b_data) ==
3933 clen_changed = clen - already;
3935 mb_set_bits(bitmap_bh->b_data, blkoff, clen);
3937 mb_clear_bits(bitmap_bh->b_data, blkoff, clen);
3938 if (ext4_has_group_desc_csum(sb) &&
3939 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3940 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3941 ext4_free_group_clusters_set(sb, gdp,
3942 ext4_free_clusters_after_init(sb, group, gdp));
3945 clen = ext4_free_group_clusters(sb, gdp) - clen_changed;
3947 clen = ext4_free_group_clusters(sb, gdp) + clen_changed;
3949 ext4_free_group_clusters_set(sb, gdp, clen);
3950 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
3951 ext4_group_desc_csum_set(sb, group, gdp);
3953 ext4_unlock_group(sb, group);
3955 if (sbi->s_log_groups_per_flex) {
3956 ext4_group_t flex_group = ext4_flex_group(sbi, group);
3957 struct flex_groups *fg = sbi_array_rcu_deref(sbi,
3958 s_flex_groups, flex_group);
3961 atomic64_sub(clen_changed, &fg->free_clusters);
3963 atomic64_add(clen_changed, &fg->free_clusters);
3967 err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
3970 sync_dirty_buffer(bitmap_bh);
3971 err = ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
3972 sync_dirty_buffer(gdp_bh);
3976 block += thisgrp_len;
3987 * here we normalize request for locality group
3988 * Group request are normalized to s_mb_group_prealloc, which goes to
3989 * s_strip if we set the same via mount option.
3990 * s_mb_group_prealloc can be configured via
3991 * /sys/fs/ext4/<partition>/mb_group_prealloc
3993 * XXX: should we try to preallocate more than the group has now?
3995 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3997 struct super_block *sb = ac->ac_sb;
3998 struct ext4_locality_group *lg = ac->ac_lg;
4001 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
4002 mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
4006 * This function returns the next element to look at during inode
4007 * PA rbtree walk. We assume that we have held the inode PA rbtree lock
4008 * (ei->i_prealloc_lock)
4010 * new_start The start of the range we want to compare
4011 * cur_start The existing start that we are comparing against
4012 * node The node of the rb_tree
4014 static inline struct rb_node*
4015 ext4_mb_pa_rb_next_iter(ext4_lblk_t new_start, ext4_lblk_t cur_start, struct rb_node *node)
4017 if (new_start < cur_start)
4018 return node->rb_left;
4020 return node->rb_right;
4024 ext4_mb_pa_assert_overlap(struct ext4_allocation_context *ac,
4025 ext4_lblk_t start, ext4_lblk_t end)
4027 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4028 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4029 struct ext4_prealloc_space *tmp_pa;
4030 ext4_lblk_t tmp_pa_start, tmp_pa_end;
4031 struct rb_node *iter;
4033 read_lock(&ei->i_prealloc_lock);
4034 for (iter = ei->i_prealloc_node.rb_node; iter;
4035 iter = ext4_mb_pa_rb_next_iter(start, tmp_pa_start, iter)) {
4036 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4037 pa_node.inode_node);
4038 tmp_pa_start = tmp_pa->pa_lstart;
4039 tmp_pa_end = tmp_pa->pa_lstart + EXT4_C2B(sbi, tmp_pa->pa_len);
4041 spin_lock(&tmp_pa->pa_lock);
4042 if (tmp_pa->pa_deleted == 0)
4043 BUG_ON(!(start >= tmp_pa_end || end <= tmp_pa_start));
4044 spin_unlock(&tmp_pa->pa_lock);
4046 read_unlock(&ei->i_prealloc_lock);
4050 * Given an allocation context "ac" and a range "start", "end", check
4051 * and adjust boundaries if the range overlaps with any of the existing
4052 * preallocatoins stored in the corresponding inode of the allocation context.
4055 * ac allocation context
4056 * start start of the new range
4057 * end end of the new range
4060 ext4_mb_pa_adjust_overlap(struct ext4_allocation_context *ac,
4061 ext4_lblk_t *start, ext4_lblk_t *end)
4063 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4064 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4065 struct ext4_prealloc_space *tmp_pa = NULL, *left_pa = NULL, *right_pa = NULL;
4066 struct rb_node *iter;
4067 ext4_lblk_t new_start, new_end;
4068 ext4_lblk_t tmp_pa_start, tmp_pa_end, left_pa_end = -1, right_pa_start = -1;
4074 * Adjust the normalized range so that it doesn't overlap with any
4075 * existing preallocated blocks(PAs). Make sure to hold the rbtree lock
4076 * so it doesn't change underneath us.
4078 read_lock(&ei->i_prealloc_lock);
4080 /* Step 1: find any one immediate neighboring PA of the normalized range */
4081 for (iter = ei->i_prealloc_node.rb_node; iter;
4082 iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
4083 tmp_pa_start, iter)) {
4084 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4085 pa_node.inode_node);
4086 tmp_pa_start = tmp_pa->pa_lstart;
4087 tmp_pa_end = tmp_pa->pa_lstart + EXT4_C2B(sbi, tmp_pa->pa_len);
4089 /* PA must not overlap original request */
4090 spin_lock(&tmp_pa->pa_lock);
4091 if (tmp_pa->pa_deleted == 0)
4092 BUG_ON(!(ac->ac_o_ex.fe_logical >= tmp_pa_end ||
4093 ac->ac_o_ex.fe_logical < tmp_pa_start));
4094 spin_unlock(&tmp_pa->pa_lock);
4098 * Step 2: check if the found PA is left or right neighbor and
4099 * get the other neighbor
4102 if (tmp_pa->pa_lstart < ac->ac_o_ex.fe_logical) {
4103 struct rb_node *tmp;
4106 tmp = rb_next(&left_pa->pa_node.inode_node);
4108 right_pa = rb_entry(tmp,
4109 struct ext4_prealloc_space,
4110 pa_node.inode_node);
4113 struct rb_node *tmp;
4116 tmp = rb_prev(&right_pa->pa_node.inode_node);
4118 left_pa = rb_entry(tmp,
4119 struct ext4_prealloc_space,
4120 pa_node.inode_node);
4125 /* Step 3: get the non deleted neighbors */
4127 for (iter = &left_pa->pa_node.inode_node;;
4128 iter = rb_prev(iter)) {
4134 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4135 pa_node.inode_node);
4137 spin_lock(&tmp_pa->pa_lock);
4138 if (tmp_pa->pa_deleted == 0) {
4139 spin_unlock(&tmp_pa->pa_lock);
4142 spin_unlock(&tmp_pa->pa_lock);
4147 for (iter = &right_pa->pa_node.inode_node;;
4148 iter = rb_next(iter)) {
4154 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4155 pa_node.inode_node);
4157 spin_lock(&tmp_pa->pa_lock);
4158 if (tmp_pa->pa_deleted == 0) {
4159 spin_unlock(&tmp_pa->pa_lock);
4162 spin_unlock(&tmp_pa->pa_lock);
4168 left_pa->pa_lstart + EXT4_C2B(sbi, left_pa->pa_len);
4169 BUG_ON(left_pa_end > ac->ac_o_ex.fe_logical);
4173 right_pa_start = right_pa->pa_lstart;
4174 BUG_ON(right_pa_start <= ac->ac_o_ex.fe_logical);
4177 /* Step 4: trim our normalized range to not overlap with the neighbors */
4179 if (left_pa_end > new_start)
4180 new_start = left_pa_end;
4184 if (right_pa_start < new_end)
4185 new_end = right_pa_start;
4187 read_unlock(&ei->i_prealloc_lock);
4189 /* XXX: extra loop to check we really don't overlap preallocations */
4190 ext4_mb_pa_assert_overlap(ac, new_start, new_end);
4197 * Normalization means making request better in terms of
4198 * size and alignment
4200 static noinline_for_stack void
4201 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
4202 struct ext4_allocation_request *ar)
4204 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4205 struct ext4_super_block *es = sbi->s_es;
4208 loff_t size, start_off;
4209 loff_t orig_size __maybe_unused;
4212 /* do normalize only data requests, metadata requests
4213 do not need preallocation */
4214 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4217 /* sometime caller may want exact blocks */
4218 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4221 /* caller may indicate that preallocation isn't
4222 * required (it's a tail, for example) */
4223 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
4226 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
4227 ext4_mb_normalize_group_request(ac);
4231 bsbits = ac->ac_sb->s_blocksize_bits;
4233 /* first, let's learn actual file size
4234 * given current request is allocated */
4235 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
4236 size = size << bsbits;
4237 if (size < i_size_read(ac->ac_inode))
4238 size = i_size_read(ac->ac_inode);
4241 /* max size of free chunks */
4244 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
4245 (req <= (size) || max <= (chunk_size))
4247 /* first, try to predict filesize */
4248 /* XXX: should this table be tunable? */
4250 if (size <= 16 * 1024) {
4252 } else if (size <= 32 * 1024) {
4254 } else if (size <= 64 * 1024) {
4256 } else if (size <= 128 * 1024) {
4258 } else if (size <= 256 * 1024) {
4260 } else if (size <= 512 * 1024) {
4262 } else if (size <= 1024 * 1024) {
4264 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
4265 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4266 (21 - bsbits)) << 21;
4267 size = 2 * 1024 * 1024;
4268 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
4269 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4270 (22 - bsbits)) << 22;
4271 size = 4 * 1024 * 1024;
4272 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
4273 (8<<20)>>bsbits, max, 8 * 1024)) {
4274 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
4275 (23 - bsbits)) << 23;
4276 size = 8 * 1024 * 1024;
4278 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
4279 size = (loff_t) EXT4_C2B(sbi,
4280 ac->ac_o_ex.fe_len) << bsbits;
4282 size = size >> bsbits;
4283 start = start_off >> bsbits;
4286 * For tiny groups (smaller than 8MB) the chosen allocation
4287 * alignment may be larger than group size. Make sure the
4288 * alignment does not move allocation to a different group which
4289 * makes mballoc fail assertions later.
4291 start = max(start, rounddown(ac->ac_o_ex.fe_logical,
4292 (ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
4294 /* don't cover already allocated blocks in selected range */
4295 if (ar->pleft && start <= ar->lleft) {
4296 size -= ar->lleft + 1 - start;
4297 start = ar->lleft + 1;
4299 if (ar->pright && start + size - 1 >= ar->lright)
4300 size -= start + size - ar->lright;
4303 * Trim allocation request for filesystems with artificially small
4306 if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
4307 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
4311 ext4_mb_pa_adjust_overlap(ac, &start, &end);
4316 * In this function "start" and "size" are normalized for better
4317 * alignment and length such that we could preallocate more blocks.
4318 * This normalization is done such that original request of
4319 * ac->ac_o_ex.fe_logical & fe_len should always lie within "start" and
4320 * "size" boundaries.
4321 * (Note fe_len can be relaxed since FS block allocation API does not
4322 * provide gurantee on number of contiguous blocks allocation since that
4323 * depends upon free space left, etc).
4324 * In case of inode pa, later we use the allocated blocks
4325 * [pa_pstart + fe_logical - pa_lstart, fe_len/size] from the preallocated
4326 * range of goal/best blocks [start, size] to put it at the
4327 * ac_o_ex.fe_logical extent of this inode.
4328 * (See ext4_mb_use_inode_pa() for more details)
4330 if (start + size <= ac->ac_o_ex.fe_logical ||
4331 start > ac->ac_o_ex.fe_logical) {
4332 ext4_msg(ac->ac_sb, KERN_ERR,
4333 "start %lu, size %lu, fe_logical %lu",
4334 (unsigned long) start, (unsigned long) size,
4335 (unsigned long) ac->ac_o_ex.fe_logical);
4338 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
4340 /* now prepare goal request */
4342 /* XXX: is it better to align blocks WRT to logical
4343 * placement or satisfy big request as is */
4344 ac->ac_g_ex.fe_logical = start;
4345 ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
4347 /* define goal start in order to merge */
4348 if (ar->pright && (ar->lright == (start + size)) &&
4349 ar->pright >= size &&
4350 ar->pright - size >= le32_to_cpu(es->s_first_data_block)) {
4351 /* merge to the right */
4352 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
4353 &ac->ac_g_ex.fe_group,
4354 &ac->ac_g_ex.fe_start);
4355 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4357 if (ar->pleft && (ar->lleft + 1 == start) &&
4358 ar->pleft + 1 < ext4_blocks_count(es)) {
4359 /* merge to the left */
4360 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
4361 &ac->ac_g_ex.fe_group,
4362 &ac->ac_g_ex.fe_start);
4363 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
4366 mb_debug(ac->ac_sb, "goal: %lld(was %lld) blocks at %u\n", size,
4370 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
4372 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4374 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len >= 1) {
4375 atomic_inc(&sbi->s_bal_reqs);
4376 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
4377 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
4378 atomic_inc(&sbi->s_bal_success);
4379 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
4380 atomic_add(ac->ac_groups_scanned, &sbi->s_bal_groups_scanned);
4381 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
4382 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
4383 atomic_inc(&sbi->s_bal_goals);
4384 if (ac->ac_found > sbi->s_mb_max_to_scan)
4385 atomic_inc(&sbi->s_bal_breaks);
4388 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
4389 trace_ext4_mballoc_alloc(ac);
4391 trace_ext4_mballoc_prealloc(ac);
4395 * Called on failure; free up any blocks from the inode PA for this
4396 * context. We don't need this for MB_GROUP_PA because we only change
4397 * pa_free in ext4_mb_release_context(), but on failure, we've already
4398 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
4400 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
4402 struct ext4_prealloc_space *pa = ac->ac_pa;
4403 struct ext4_buddy e4b;
4407 if (ac->ac_f_ex.fe_len == 0)
4409 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
4410 if (WARN_RATELIMIT(err,
4411 "ext4: mb_load_buddy failed (%d)", err))
4413 * This should never happen since we pin the
4414 * pages in the ext4_allocation_context so
4415 * ext4_mb_load_buddy() should never fail.
4418 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
4419 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
4420 ac->ac_f_ex.fe_len);
4421 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
4422 ext4_mb_unload_buddy(&e4b);
4425 if (pa->pa_type == MB_INODE_PA) {
4426 spin_lock(&pa->pa_lock);
4427 pa->pa_free += ac->ac_b_ex.fe_len;
4428 spin_unlock(&pa->pa_lock);
4433 * use blocks preallocated to inode
4435 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
4436 struct ext4_prealloc_space *pa)
4438 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4443 /* found preallocated blocks, use them */
4444 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
4445 end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
4446 start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
4447 len = EXT4_NUM_B2C(sbi, end - start);
4448 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
4449 &ac->ac_b_ex.fe_start);
4450 ac->ac_b_ex.fe_len = len;
4451 ac->ac_status = AC_STATUS_FOUND;
4454 BUG_ON(start < pa->pa_pstart);
4455 BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
4456 BUG_ON(pa->pa_free < len);
4457 BUG_ON(ac->ac_b_ex.fe_len <= 0);
4460 mb_debug(ac->ac_sb, "use %llu/%d from inode pa %p\n", start, len, pa);
4464 * use blocks preallocated to locality group
4466 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
4467 struct ext4_prealloc_space *pa)
4469 unsigned int len = ac->ac_o_ex.fe_len;
4471 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
4472 &ac->ac_b_ex.fe_group,
4473 &ac->ac_b_ex.fe_start);
4474 ac->ac_b_ex.fe_len = len;
4475 ac->ac_status = AC_STATUS_FOUND;
4478 /* we don't correct pa_pstart or pa_len here to avoid
4479 * possible race when the group is being loaded concurrently
4480 * instead we correct pa later, after blocks are marked
4481 * in on-disk bitmap -- see ext4_mb_release_context()
4482 * Other CPUs are prevented from allocating from this pa by lg_mutex
4484 mb_debug(ac->ac_sb, "use %u/%u from group pa %p\n",
4485 pa->pa_lstart, len, pa);
4489 * Return the prealloc space that have minimal distance
4490 * from the goal block. @cpa is the prealloc
4491 * space that is having currently known minimal distance
4492 * from the goal block.
4494 static struct ext4_prealloc_space *
4495 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
4496 struct ext4_prealloc_space *pa,
4497 struct ext4_prealloc_space *cpa)
4499 ext4_fsblk_t cur_distance, new_distance;
4502 atomic_inc(&pa->pa_count);
4505 cur_distance = abs(goal_block - cpa->pa_pstart);
4506 new_distance = abs(goal_block - pa->pa_pstart);
4508 if (cur_distance <= new_distance)
4511 /* drop the previous reference */
4512 atomic_dec(&cpa->pa_count);
4513 atomic_inc(&pa->pa_count);
4518 * search goal blocks in preallocated space
4520 static noinline_for_stack bool
4521 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
4523 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4525 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4526 struct ext4_locality_group *lg;
4527 struct ext4_prealloc_space *tmp_pa, *cpa = NULL;
4528 ext4_lblk_t tmp_pa_start, tmp_pa_end;
4529 struct rb_node *iter;
4530 ext4_fsblk_t goal_block;
4532 /* only data can be preallocated */
4533 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4536 /* first, try per-file preallocation */
4537 read_lock(&ei->i_prealloc_lock);
4538 for (iter = ei->i_prealloc_node.rb_node; iter;
4539 iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
4540 tmp_pa_start, iter)) {
4541 tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
4542 pa_node.inode_node);
4544 /* all fields in this condition don't change,
4545 * so we can skip locking for them */
4546 tmp_pa_start = tmp_pa->pa_lstart;
4547 tmp_pa_end = tmp_pa->pa_lstart + EXT4_C2B(sbi, tmp_pa->pa_len);
4549 /* original request start doesn't lie in this PA */
4550 if (ac->ac_o_ex.fe_logical < tmp_pa_start ||
4551 ac->ac_o_ex.fe_logical >= tmp_pa_end)
4554 /* non-extent files can't have physical blocks past 2^32 */
4555 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
4556 (tmp_pa->pa_pstart + EXT4_C2B(sbi, tmp_pa->pa_len) >
4557 EXT4_MAX_BLOCK_FILE_PHYS)) {
4559 * Since PAs don't overlap, we won't find any
4560 * other PA to satisfy this.
4565 /* found preallocated blocks, use them */
4566 spin_lock(&tmp_pa->pa_lock);
4567 if (tmp_pa->pa_deleted == 0 && tmp_pa->pa_free) {
4568 atomic_inc(&tmp_pa->pa_count);
4569 ext4_mb_use_inode_pa(ac, tmp_pa);
4570 spin_unlock(&tmp_pa->pa_lock);
4571 ac->ac_criteria = 10;
4572 read_unlock(&ei->i_prealloc_lock);
4575 spin_unlock(&tmp_pa->pa_lock);
4577 read_unlock(&ei->i_prealloc_lock);
4579 /* can we use group allocation? */
4580 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
4583 /* inode may have no locality group for some reason */
4587 order = fls(ac->ac_o_ex.fe_len) - 1;
4588 if (order > PREALLOC_TB_SIZE - 1)
4589 /* The max size of hash table is PREALLOC_TB_SIZE */
4590 order = PREALLOC_TB_SIZE - 1;
4592 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
4594 * search for the prealloc space that is having
4595 * minimal distance from the goal block.
4597 for (i = order; i < PREALLOC_TB_SIZE; i++) {
4599 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[i],
4601 spin_lock(&tmp_pa->pa_lock);
4602 if (tmp_pa->pa_deleted == 0 &&
4603 tmp_pa->pa_free >= ac->ac_o_ex.fe_len) {
4605 cpa = ext4_mb_check_group_pa(goal_block,
4608 spin_unlock(&tmp_pa->pa_lock);
4613 ext4_mb_use_group_pa(ac, cpa);
4614 ac->ac_criteria = 20;
4621 * the function goes through all block freed in the group
4622 * but not yet committed and marks them used in in-core bitmap.
4623 * buddy must be generated from this bitmap
4624 * Need to be called with the ext4 group lock held
4626 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
4630 struct ext4_group_info *grp;
4631 struct ext4_free_data *entry;
4633 grp = ext4_get_group_info(sb, group);
4636 n = rb_first(&(grp->bb_free_root));
4639 entry = rb_entry(n, struct ext4_free_data, efd_node);
4640 mb_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
4647 * the function goes through all preallocation in this group and marks them
4648 * used in in-core bitmap. buddy must be generated from this bitmap
4649 * Need to be called with ext4 group lock held
4651 static noinline_for_stack
4652 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
4655 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
4656 struct ext4_prealloc_space *pa;
4657 struct list_head *cur;
4658 ext4_group_t groupnr;
4659 ext4_grpblk_t start;
4660 int preallocated = 0;
4666 /* all form of preallocation discards first load group,
4667 * so the only competing code is preallocation use.
4668 * we don't need any locking here
4669 * notice we do NOT ignore preallocations with pa_deleted
4670 * otherwise we could leave used blocks available for
4671 * allocation in buddy when concurrent ext4_mb_put_pa()
4672 * is dropping preallocation
4674 list_for_each(cur, &grp->bb_prealloc_list) {
4675 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
4676 spin_lock(&pa->pa_lock);
4677 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4680 spin_unlock(&pa->pa_lock);
4681 if (unlikely(len == 0))
4683 BUG_ON(groupnr != group);
4684 mb_set_bits(bitmap, start, len);
4685 preallocated += len;
4687 mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
4690 static void ext4_mb_mark_pa_deleted(struct super_block *sb,
4691 struct ext4_prealloc_space *pa)
4693 struct ext4_inode_info *ei;
4695 if (pa->pa_deleted) {
4696 ext4_warning(sb, "deleted pa, type:%d, pblk:%llu, lblk:%u, len:%d\n",
4697 pa->pa_type, pa->pa_pstart, pa->pa_lstart,
4704 if (pa->pa_type == MB_INODE_PA) {
4705 ei = EXT4_I(pa->pa_inode);
4706 atomic_dec(&ei->i_prealloc_active);
4710 static inline void ext4_mb_pa_free(struct ext4_prealloc_space *pa)
4713 BUG_ON(atomic_read(&pa->pa_count));
4714 BUG_ON(pa->pa_deleted == 0);
4715 kmem_cache_free(ext4_pspace_cachep, pa);
4718 static void ext4_mb_pa_callback(struct rcu_head *head)
4720 struct ext4_prealloc_space *pa;
4722 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
4723 ext4_mb_pa_free(pa);
4727 * drops a reference to preallocated space descriptor
4728 * if this was the last reference and the space is consumed
4730 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
4731 struct super_block *sb, struct ext4_prealloc_space *pa)
4734 ext4_fsblk_t grp_blk;
4735 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
4737 /* in this short window concurrent discard can set pa_deleted */
4738 spin_lock(&pa->pa_lock);
4739 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
4740 spin_unlock(&pa->pa_lock);
4744 if (pa->pa_deleted == 1) {
4745 spin_unlock(&pa->pa_lock);
4749 ext4_mb_mark_pa_deleted(sb, pa);
4750 spin_unlock(&pa->pa_lock);
4752 grp_blk = pa->pa_pstart;
4754 * If doing group-based preallocation, pa_pstart may be in the
4755 * next group when pa is used up
4757 if (pa->pa_type == MB_GROUP_PA)
4760 grp = ext4_get_group_number(sb, grp_blk);
4765 * P1 (buddy init) P2 (regular allocation)
4766 * find block B in PA
4767 * copy on-disk bitmap to buddy
4768 * mark B in on-disk bitmap
4769 * drop PA from group
4770 * mark all PAs in buddy
4772 * thus, P1 initializes buddy with B available. to prevent this
4773 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
4776 ext4_lock_group(sb, grp);
4777 list_del(&pa->pa_group_list);
4778 ext4_unlock_group(sb, grp);
4780 if (pa->pa_type == MB_INODE_PA) {
4781 write_lock(pa->pa_node_lock.inode_lock);
4782 rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
4783 write_unlock(pa->pa_node_lock.inode_lock);
4784 ext4_mb_pa_free(pa);
4786 spin_lock(pa->pa_node_lock.lg_lock);
4787 list_del_rcu(&pa->pa_node.lg_list);
4788 spin_unlock(pa->pa_node_lock.lg_lock);
4789 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4793 static void ext4_mb_pa_rb_insert(struct rb_root *root, struct rb_node *new)
4795 struct rb_node **iter = &root->rb_node, *parent = NULL;
4796 struct ext4_prealloc_space *iter_pa, *new_pa;
4797 ext4_lblk_t iter_start, new_start;
4800 iter_pa = rb_entry(*iter, struct ext4_prealloc_space,
4801 pa_node.inode_node);
4802 new_pa = rb_entry(new, struct ext4_prealloc_space,
4803 pa_node.inode_node);
4804 iter_start = iter_pa->pa_lstart;
4805 new_start = new_pa->pa_lstart;
4808 if (new_start < iter_start)
4809 iter = &((*iter)->rb_left);
4811 iter = &((*iter)->rb_right);
4814 rb_link_node(new, parent, iter);
4815 rb_insert_color(new, root);
4819 * creates new preallocated space for given inode
4821 static noinline_for_stack void
4822 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
4824 struct super_block *sb = ac->ac_sb;
4825 struct ext4_sb_info *sbi = EXT4_SB(sb);
4826 struct ext4_prealloc_space *pa;
4827 struct ext4_group_info *grp;
4828 struct ext4_inode_info *ei;
4830 /* preallocate only when found space is larger then requested */
4831 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
4832 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
4833 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
4834 BUG_ON(ac->ac_pa == NULL);
4838 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
4842 /* we can't allocate as much as normalizer wants.
4843 * so, found space must get proper lstart
4844 * to cover original request */
4845 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
4846 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
4849 * Use the below logic for adjusting best extent as it keeps
4850 * fragmentation in check while ensuring logical range of best
4851 * extent doesn't overflow out of goal extent:
4853 * 1. Check if best ex can be kept at end of goal and still
4854 * cover original start
4855 * 2. Else, check if best ex can be kept at start of goal and
4856 * still cover original start
4857 * 3. Else, keep the best ex at start of original request.
4859 new_bex_end = ac->ac_g_ex.fe_logical +
4860 EXT4_C2B(sbi, ac->ac_g_ex.fe_len);
4861 new_bex_start = new_bex_end - EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4862 if (ac->ac_o_ex.fe_logical >= new_bex_start)
4865 new_bex_start = ac->ac_g_ex.fe_logical;
4867 new_bex_start + EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4868 if (ac->ac_o_ex.fe_logical < new_bex_end)
4871 new_bex_start = ac->ac_o_ex.fe_logical;
4873 new_bex_start + EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4876 ac->ac_b_ex.fe_logical = new_bex_start;
4878 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
4879 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
4880 BUG_ON(new_bex_end > (ac->ac_g_ex.fe_logical +
4881 EXT4_C2B(sbi, ac->ac_g_ex.fe_len)));
4884 pa->pa_lstart = ac->ac_b_ex.fe_logical;
4885 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4886 pa->pa_len = ac->ac_b_ex.fe_len;
4887 pa->pa_free = pa->pa_len;
4888 spin_lock_init(&pa->pa_lock);
4889 INIT_LIST_HEAD(&pa->pa_group_list);
4891 pa->pa_type = MB_INODE_PA;
4893 mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
4894 pa->pa_len, pa->pa_lstart);
4895 trace_ext4_mb_new_inode_pa(ac, pa);
4897 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
4898 ext4_mb_use_inode_pa(ac, pa);
4900 ei = EXT4_I(ac->ac_inode);
4901 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
4905 pa->pa_node_lock.inode_lock = &ei->i_prealloc_lock;
4906 pa->pa_inode = ac->ac_inode;
4908 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
4910 write_lock(pa->pa_node_lock.inode_lock);
4911 ext4_mb_pa_rb_insert(&ei->i_prealloc_node, &pa->pa_node.inode_node);
4912 write_unlock(pa->pa_node_lock.inode_lock);
4913 atomic_inc(&ei->i_prealloc_active);
4917 * creates new preallocated space for locality group inodes belongs to
4919 static noinline_for_stack void
4920 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
4922 struct super_block *sb = ac->ac_sb;
4923 struct ext4_locality_group *lg;
4924 struct ext4_prealloc_space *pa;
4925 struct ext4_group_info *grp;
4927 /* preallocate only when found space is larger then requested */
4928 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
4929 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
4930 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
4931 BUG_ON(ac->ac_pa == NULL);
4935 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4936 pa->pa_lstart = pa->pa_pstart;
4937 pa->pa_len = ac->ac_b_ex.fe_len;
4938 pa->pa_free = pa->pa_len;
4939 spin_lock_init(&pa->pa_lock);
4940 INIT_LIST_HEAD(&pa->pa_node.lg_list);
4941 INIT_LIST_HEAD(&pa->pa_group_list);
4943 pa->pa_type = MB_GROUP_PA;
4945 mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
4946 pa->pa_len, pa->pa_lstart);
4947 trace_ext4_mb_new_group_pa(ac, pa);
4949 ext4_mb_use_group_pa(ac, pa);
4950 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
4952 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
4958 pa->pa_node_lock.lg_lock = &lg->lg_prealloc_lock;
4959 pa->pa_inode = NULL;
4961 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
4964 * We will later add the new pa to the right bucket
4965 * after updating the pa_free in ext4_mb_release_context
4969 static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
4971 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4972 ext4_mb_new_group_pa(ac);
4974 ext4_mb_new_inode_pa(ac);
4978 * finds all unused blocks in on-disk bitmap, frees them in
4979 * in-core bitmap and buddy.
4980 * @pa must be unlinked from inode and group lists, so that
4981 * nobody else can find/use it.
4982 * the caller MUST hold group/inode locks.
4983 * TODO: optimize the case when there are no in-core structures yet
4985 static noinline_for_stack int
4986 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
4987 struct ext4_prealloc_space *pa)
4989 struct super_block *sb = e4b->bd_sb;
4990 struct ext4_sb_info *sbi = EXT4_SB(sb);
4995 unsigned long long grp_blk_start;
4998 BUG_ON(pa->pa_deleted == 0);
4999 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
5000 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
5001 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
5002 end = bit + pa->pa_len;
5005 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
5008 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
5009 mb_debug(sb, "free preallocated %u/%u in group %u\n",
5010 (unsigned) ext4_group_first_block_no(sb, group) + bit,
5011 (unsigned) next - bit, (unsigned) group);
5014 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
5015 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
5016 EXT4_C2B(sbi, bit)),
5018 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
5021 if (free != pa->pa_free) {
5022 ext4_msg(e4b->bd_sb, KERN_CRIT,
5023 "pa %p: logic %lu, phys. %lu, len %d",
5024 pa, (unsigned long) pa->pa_lstart,
5025 (unsigned long) pa->pa_pstart,
5027 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
5030 * pa is already deleted so we use the value obtained
5031 * from the bitmap and continue.
5034 atomic_add(free, &sbi->s_mb_discarded);
5039 static noinline_for_stack int
5040 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
5041 struct ext4_prealloc_space *pa)
5043 struct super_block *sb = e4b->bd_sb;
5047 trace_ext4_mb_release_group_pa(sb, pa);
5048 BUG_ON(pa->pa_deleted == 0);
5049 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
5050 if (unlikely(group != e4b->bd_group && pa->pa_len != 0)) {
5051 ext4_warning(sb, "bad group: expected %u, group %u, pa_start %llu",
5052 e4b->bd_group, group, pa->pa_pstart);
5055 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
5056 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
5057 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
5063 * releases all preallocations in given group
5065 * first, we need to decide discard policy:
5066 * - when do we discard
5068 * - how many do we discard
5069 * 1) how many requested
5071 static noinline_for_stack int
5072 ext4_mb_discard_group_preallocations(struct super_block *sb,
5073 ext4_group_t group, int *busy)
5075 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
5076 struct buffer_head *bitmap_bh = NULL;
5077 struct ext4_prealloc_space *pa, *tmp;
5078 struct list_head list;
5079 struct ext4_buddy e4b;
5080 struct ext4_inode_info *ei;
5086 mb_debug(sb, "discard preallocation for group %u\n", group);
5087 if (list_empty(&grp->bb_prealloc_list))
5090 bitmap_bh = ext4_read_block_bitmap(sb, group);
5091 if (IS_ERR(bitmap_bh)) {
5092 err = PTR_ERR(bitmap_bh);
5093 ext4_error_err(sb, -err,
5094 "Error %d reading block bitmap for %u",
5099 err = ext4_mb_load_buddy(sb, group, &e4b);
5101 ext4_warning(sb, "Error %d loading buddy information for %u",
5107 INIT_LIST_HEAD(&list);
5108 ext4_lock_group(sb, group);
5109 list_for_each_entry_safe(pa, tmp,
5110 &grp->bb_prealloc_list, pa_group_list) {
5111 spin_lock(&pa->pa_lock);
5112 if (atomic_read(&pa->pa_count)) {
5113 spin_unlock(&pa->pa_lock);
5117 if (pa->pa_deleted) {
5118 spin_unlock(&pa->pa_lock);
5122 /* seems this one can be freed ... */
5123 ext4_mb_mark_pa_deleted(sb, pa);
5126 this_cpu_inc(discard_pa_seq);
5128 /* we can trust pa_free ... */
5129 free += pa->pa_free;
5131 spin_unlock(&pa->pa_lock);
5133 list_del(&pa->pa_group_list);
5134 list_add(&pa->u.pa_tmp_list, &list);
5137 /* now free all selected PAs */
5138 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5140 /* remove from object (inode or locality group) */
5141 if (pa->pa_type == MB_GROUP_PA) {
5142 spin_lock(pa->pa_node_lock.lg_lock);
5143 list_del_rcu(&pa->pa_node.lg_list);
5144 spin_unlock(pa->pa_node_lock.lg_lock);
5146 write_lock(pa->pa_node_lock.inode_lock);
5147 ei = EXT4_I(pa->pa_inode);
5148 rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5149 write_unlock(pa->pa_node_lock.inode_lock);
5152 list_del(&pa->u.pa_tmp_list);
5154 if (pa->pa_type == MB_GROUP_PA) {
5155 ext4_mb_release_group_pa(&e4b, pa);
5156 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5158 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
5159 ext4_mb_pa_free(pa);
5163 ext4_unlock_group(sb, group);
5164 ext4_mb_unload_buddy(&e4b);
5167 mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
5168 free, group, grp->bb_free);
5173 * releases all non-used preallocated blocks for given inode
5175 * It's important to discard preallocations under i_data_sem
5176 * We don't want another block to be served from the prealloc
5177 * space when we are discarding the inode prealloc space.
5179 * FIXME!! Make sure it is valid at all the call sites
5181 void ext4_discard_preallocations(struct inode *inode, unsigned int needed)
5183 struct ext4_inode_info *ei = EXT4_I(inode);
5184 struct super_block *sb = inode->i_sb;
5185 struct buffer_head *bitmap_bh = NULL;
5186 struct ext4_prealloc_space *pa, *tmp;
5187 ext4_group_t group = 0;
5188 struct list_head list;
5189 struct ext4_buddy e4b;
5190 struct rb_node *iter;
5193 if (!S_ISREG(inode->i_mode)) {
5197 if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
5200 mb_debug(sb, "discard preallocation for inode %lu\n",
5202 trace_ext4_discard_preallocations(inode,
5203 atomic_read(&ei->i_prealloc_active), needed);
5205 INIT_LIST_HEAD(&list);
5211 /* first, collect all pa's in the inode */
5212 write_lock(&ei->i_prealloc_lock);
5213 for (iter = rb_first(&ei->i_prealloc_node); iter && needed;
5214 iter = rb_next(iter)) {
5215 pa = rb_entry(iter, struct ext4_prealloc_space,
5216 pa_node.inode_node);
5217 BUG_ON(pa->pa_node_lock.inode_lock != &ei->i_prealloc_lock);
5219 spin_lock(&pa->pa_lock);
5220 if (atomic_read(&pa->pa_count)) {
5221 /* this shouldn't happen often - nobody should
5222 * use preallocation while we're discarding it */
5223 spin_unlock(&pa->pa_lock);
5224 write_unlock(&ei->i_prealloc_lock);
5225 ext4_msg(sb, KERN_ERR,
5226 "uh-oh! used pa while discarding");
5228 schedule_timeout_uninterruptible(HZ);
5232 if (pa->pa_deleted == 0) {
5233 ext4_mb_mark_pa_deleted(sb, pa);
5234 spin_unlock(&pa->pa_lock);
5235 rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
5236 list_add(&pa->u.pa_tmp_list, &list);
5241 /* someone is deleting pa right now */
5242 spin_unlock(&pa->pa_lock);
5243 write_unlock(&ei->i_prealloc_lock);
5245 /* we have to wait here because pa_deleted
5246 * doesn't mean pa is already unlinked from
5247 * the list. as we might be called from
5248 * ->clear_inode() the inode will get freed
5249 * and concurrent thread which is unlinking
5250 * pa from inode's list may access already
5251 * freed memory, bad-bad-bad */
5253 /* XXX: if this happens too often, we can
5254 * add a flag to force wait only in case
5255 * of ->clear_inode(), but not in case of
5256 * regular truncate */
5257 schedule_timeout_uninterruptible(HZ);
5260 write_unlock(&ei->i_prealloc_lock);
5262 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
5263 BUG_ON(pa->pa_type != MB_INODE_PA);
5264 group = ext4_get_group_number(sb, pa->pa_pstart);
5266 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
5267 GFP_NOFS|__GFP_NOFAIL);
5269 ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
5274 bitmap_bh = ext4_read_block_bitmap(sb, group);
5275 if (IS_ERR(bitmap_bh)) {
5276 err = PTR_ERR(bitmap_bh);
5277 ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
5279 ext4_mb_unload_buddy(&e4b);
5283 ext4_lock_group(sb, group);
5284 list_del(&pa->pa_group_list);
5285 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
5286 ext4_unlock_group(sb, group);
5288 ext4_mb_unload_buddy(&e4b);
5291 list_del(&pa->u.pa_tmp_list);
5292 ext4_mb_pa_free(pa);
5296 static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
5298 struct ext4_prealloc_space *pa;
5300 BUG_ON(ext4_pspace_cachep == NULL);
5301 pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
5304 atomic_set(&pa->pa_count, 1);
5309 static void ext4_mb_pa_put_free(struct ext4_allocation_context *ac)
5311 struct ext4_prealloc_space *pa = ac->ac_pa;
5315 WARN_ON(!atomic_dec_and_test(&pa->pa_count));
5317 * current function is only called due to an error or due to
5318 * len of found blocks < len of requested blocks hence the PA has not
5319 * been added to grp->bb_prealloc_list. So we don't need to lock it
5322 ext4_mb_pa_free(pa);
5325 #ifdef CONFIG_EXT4_DEBUG
5326 static inline void ext4_mb_show_pa(struct super_block *sb)
5328 ext4_group_t i, ngroups;
5330 if (ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
5333 ngroups = ext4_get_groups_count(sb);
5334 mb_debug(sb, "groups: ");
5335 for (i = 0; i < ngroups; i++) {
5336 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
5337 struct ext4_prealloc_space *pa;
5338 ext4_grpblk_t start;
5339 struct list_head *cur;
5343 ext4_lock_group(sb, i);
5344 list_for_each(cur, &grp->bb_prealloc_list) {
5345 pa = list_entry(cur, struct ext4_prealloc_space,
5347 spin_lock(&pa->pa_lock);
5348 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
5350 spin_unlock(&pa->pa_lock);
5351 mb_debug(sb, "PA:%u:%d:%d\n", i, start,
5354 ext4_unlock_group(sb, i);
5355 mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
5360 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5362 struct super_block *sb = ac->ac_sb;
5364 if (ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
5367 mb_debug(sb, "Can't allocate:"
5368 " Allocation context details:");
5369 mb_debug(sb, "status %u flags 0x%x",
5370 ac->ac_status, ac->ac_flags);
5371 mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
5372 "goal %lu/%lu/%lu@%lu, "
5373 "best %lu/%lu/%lu@%lu cr %d",
5374 (unsigned long)ac->ac_o_ex.fe_group,
5375 (unsigned long)ac->ac_o_ex.fe_start,
5376 (unsigned long)ac->ac_o_ex.fe_len,
5377 (unsigned long)ac->ac_o_ex.fe_logical,
5378 (unsigned long)ac->ac_g_ex.fe_group,
5379 (unsigned long)ac->ac_g_ex.fe_start,
5380 (unsigned long)ac->ac_g_ex.fe_len,
5381 (unsigned long)ac->ac_g_ex.fe_logical,
5382 (unsigned long)ac->ac_b_ex.fe_group,
5383 (unsigned long)ac->ac_b_ex.fe_start,
5384 (unsigned long)ac->ac_b_ex.fe_len,
5385 (unsigned long)ac->ac_b_ex.fe_logical,
5386 (int)ac->ac_criteria);
5387 mb_debug(sb, "%u found", ac->ac_found);
5388 ext4_mb_show_pa(sb);
5391 static inline void ext4_mb_show_pa(struct super_block *sb)
5395 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
5397 ext4_mb_show_pa(ac->ac_sb);
5403 * We use locality group preallocation for small size file. The size of the
5404 * file is determined by the current size or the resulting size after
5405 * allocation which ever is larger
5407 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
5409 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
5411 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
5412 int bsbits = ac->ac_sb->s_blocksize_bits;
5414 bool inode_pa_eligible, group_pa_eligible;
5416 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
5419 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
5422 group_pa_eligible = sbi->s_mb_group_prealloc > 0;
5423 inode_pa_eligible = true;
5424 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
5425 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
5428 /* No point in using inode preallocation for closed files */
5429 if ((size == isize) && !ext4_fs_is_busy(sbi) &&
5430 !inode_is_open_for_write(ac->ac_inode))
5431 inode_pa_eligible = false;
5433 size = max(size, isize);
5434 /* Don't use group allocation for large files */
5435 if (size > sbi->s_mb_stream_request)
5436 group_pa_eligible = false;
5438 if (!group_pa_eligible) {
5439 if (inode_pa_eligible)
5440 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
5442 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
5446 BUG_ON(ac->ac_lg != NULL);
5448 * locality group prealloc space are per cpu. The reason for having
5449 * per cpu locality group is to reduce the contention between block
5450 * request from multiple CPUs.
5452 ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
5454 /* we're going to use group allocation */
5455 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
5457 /* serialize all allocations in the group */
5458 mutex_lock(&ac->ac_lg->lg_mutex);
5461 static noinline_for_stack void
5462 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
5463 struct ext4_allocation_request *ar)
5465 struct super_block *sb = ar->inode->i_sb;
5466 struct ext4_sb_info *sbi = EXT4_SB(sb);
5467 struct ext4_super_block *es = sbi->s_es;
5471 ext4_grpblk_t block;
5473 /* we can't allocate > group size */
5476 /* just a dirty hack to filter too big requests */
5477 if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
5478 len = EXT4_CLUSTERS_PER_GROUP(sb);
5480 /* start searching from the goal */
5482 if (goal < le32_to_cpu(es->s_first_data_block) ||
5483 goal >= ext4_blocks_count(es))
5484 goal = le32_to_cpu(es->s_first_data_block);
5485 ext4_get_group_no_and_offset(sb, goal, &group, &block);
5487 /* set up allocation goals */
5488 ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
5489 ac->ac_status = AC_STATUS_CONTINUE;
5491 ac->ac_inode = ar->inode;
5492 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
5493 ac->ac_o_ex.fe_group = group;
5494 ac->ac_o_ex.fe_start = block;
5495 ac->ac_o_ex.fe_len = len;
5496 ac->ac_g_ex = ac->ac_o_ex;
5497 ac->ac_flags = ar->flags;
5499 /* we have to define context: we'll work with a file or
5500 * locality group. this is a policy, actually */
5501 ext4_mb_group_or_file(ac);
5503 mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
5504 "left: %u/%u, right %u/%u to %swritable\n",
5505 (unsigned) ar->len, (unsigned) ar->logical,
5506 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
5507 (unsigned) ar->lleft, (unsigned) ar->pleft,
5508 (unsigned) ar->lright, (unsigned) ar->pright,
5509 inode_is_open_for_write(ar->inode) ? "" : "non-");
5512 static noinline_for_stack void
5513 ext4_mb_discard_lg_preallocations(struct super_block *sb,
5514 struct ext4_locality_group *lg,
5515 int order, int total_entries)
5517 ext4_group_t group = 0;
5518 struct ext4_buddy e4b;
5519 struct list_head discard_list;
5520 struct ext4_prealloc_space *pa, *tmp;
5522 mb_debug(sb, "discard locality group preallocation\n");
5524 INIT_LIST_HEAD(&discard_list);
5526 spin_lock(&lg->lg_prealloc_lock);
5527 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
5529 lockdep_is_held(&lg->lg_prealloc_lock)) {
5530 spin_lock(&pa->pa_lock);
5531 if (atomic_read(&pa->pa_count)) {
5533 * This is the pa that we just used
5534 * for block allocation. So don't
5537 spin_unlock(&pa->pa_lock);
5540 if (pa->pa_deleted) {
5541 spin_unlock(&pa->pa_lock);
5544 /* only lg prealloc space */
5545 BUG_ON(pa->pa_type != MB_GROUP_PA);
5547 /* seems this one can be freed ... */
5548 ext4_mb_mark_pa_deleted(sb, pa);
5549 spin_unlock(&pa->pa_lock);
5551 list_del_rcu(&pa->pa_node.lg_list);
5552 list_add(&pa->u.pa_tmp_list, &discard_list);
5555 if (total_entries <= 5) {
5557 * we want to keep only 5 entries
5558 * allowing it to grow to 8. This
5559 * mak sure we don't call discard
5560 * soon for this list.
5565 spin_unlock(&lg->lg_prealloc_lock);
5567 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
5570 group = ext4_get_group_number(sb, pa->pa_pstart);
5571 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
5572 GFP_NOFS|__GFP_NOFAIL);
5574 ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
5578 ext4_lock_group(sb, group);
5579 list_del(&pa->pa_group_list);
5580 ext4_mb_release_group_pa(&e4b, pa);
5581 ext4_unlock_group(sb, group);
5583 ext4_mb_unload_buddy(&e4b);
5584 list_del(&pa->u.pa_tmp_list);
5585 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
5590 * We have incremented pa_count. So it cannot be freed at this
5591 * point. Also we hold lg_mutex. So no parallel allocation is
5592 * possible from this lg. That means pa_free cannot be updated.
5594 * A parallel ext4_mb_discard_group_preallocations is possible.
5595 * which can cause the lg_prealloc_list to be updated.
5598 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
5600 int order, added = 0, lg_prealloc_count = 1;
5601 struct super_block *sb = ac->ac_sb;
5602 struct ext4_locality_group *lg = ac->ac_lg;
5603 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
5605 order = fls(pa->pa_free) - 1;
5606 if (order > PREALLOC_TB_SIZE - 1)
5607 /* The max size of hash table is PREALLOC_TB_SIZE */
5608 order = PREALLOC_TB_SIZE - 1;
5609 /* Add the prealloc space to lg */
5610 spin_lock(&lg->lg_prealloc_lock);
5611 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
5613 lockdep_is_held(&lg->lg_prealloc_lock)) {
5614 spin_lock(&tmp_pa->pa_lock);
5615 if (tmp_pa->pa_deleted) {
5616 spin_unlock(&tmp_pa->pa_lock);
5619 if (!added && pa->pa_free < tmp_pa->pa_free) {
5620 /* Add to the tail of the previous entry */
5621 list_add_tail_rcu(&pa->pa_node.lg_list,
5622 &tmp_pa->pa_node.lg_list);
5625 * we want to count the total
5626 * number of entries in the list
5629 spin_unlock(&tmp_pa->pa_lock);
5630 lg_prealloc_count++;
5633 list_add_tail_rcu(&pa->pa_node.lg_list,
5634 &lg->lg_prealloc_list[order]);
5635 spin_unlock(&lg->lg_prealloc_lock);
5637 /* Now trim the list to be not more than 8 elements */
5638 if (lg_prealloc_count > 8) {
5639 ext4_mb_discard_lg_preallocations(sb, lg,
5640 order, lg_prealloc_count);
5647 * release all resource we used in allocation
5649 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
5651 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
5652 struct ext4_prealloc_space *pa = ac->ac_pa;
5654 if (pa->pa_type == MB_GROUP_PA) {
5655 /* see comment in ext4_mb_use_group_pa() */
5656 spin_lock(&pa->pa_lock);
5657 pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
5658 pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
5659 pa->pa_free -= ac->ac_b_ex.fe_len;
5660 pa->pa_len -= ac->ac_b_ex.fe_len;
5661 spin_unlock(&pa->pa_lock);
5664 * We want to add the pa to the right bucket.
5665 * Remove it from the list and while adding
5666 * make sure the list to which we are adding
5669 if (likely(pa->pa_free)) {
5670 spin_lock(pa->pa_node_lock.lg_lock);
5671 list_del_rcu(&pa->pa_node.lg_list);
5672 spin_unlock(pa->pa_node_lock.lg_lock);
5673 ext4_mb_add_n_trim(ac);
5677 ext4_mb_put_pa(ac, ac->ac_sb, pa);
5679 if (ac->ac_bitmap_page)
5680 put_page(ac->ac_bitmap_page);
5681 if (ac->ac_buddy_page)
5682 put_page(ac->ac_buddy_page);
5683 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
5684 mutex_unlock(&ac->ac_lg->lg_mutex);
5685 ext4_mb_collect_stats(ac);
5689 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
5691 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
5693 int freed = 0, busy = 0;
5696 trace_ext4_mb_discard_preallocations(sb, needed);
5699 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
5701 for (i = 0; i < ngroups && needed > 0; i++) {
5702 ret = ext4_mb_discard_group_preallocations(sb, i, &busy);
5708 if (needed > 0 && busy && ++retry < 3) {
5716 static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
5717 struct ext4_allocation_context *ac, u64 *seq)
5723 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
5728 seq_retry = ext4_get_discard_pa_seq_sum();
5729 if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
5730 ac->ac_flags |= EXT4_MB_STRICT_CHECK;
5736 mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
5740 static ext4_fsblk_t ext4_mb_new_blocks_simple(handle_t *handle,
5741 struct ext4_allocation_request *ar, int *errp);
5744 * Main entry point into mballoc to allocate blocks
5745 * it tries to use preallocation first, then falls back
5746 * to usual allocation
5748 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
5749 struct ext4_allocation_request *ar, int *errp)
5751 struct ext4_allocation_context *ac = NULL;
5752 struct ext4_sb_info *sbi;
5753 struct super_block *sb;
5754 ext4_fsblk_t block = 0;
5755 unsigned int inquota = 0;
5756 unsigned int reserv_clstrs = 0;
5761 sb = ar->inode->i_sb;
5764 trace_ext4_request_blocks(ar);
5765 if (sbi->s_mount_state & EXT4_FC_REPLAY)
5766 return ext4_mb_new_blocks_simple(handle, ar, errp);
5768 /* Allow to use superuser reservation for quota file */
5769 if (ext4_is_quota_file(ar->inode))
5770 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
5772 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
5773 /* Without delayed allocation we need to verify
5774 * there is enough free blocks to do block allocation
5775 * and verify allocation doesn't exceed the quota limits.
5778 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
5780 /* let others to free the space */
5782 ar->len = ar->len >> 1;
5785 ext4_mb_show_pa(sb);
5789 reserv_clstrs = ar->len;
5790 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
5791 dquot_alloc_block_nofail(ar->inode,
5792 EXT4_C2B(sbi, ar->len));
5795 dquot_alloc_block(ar->inode,
5796 EXT4_C2B(sbi, ar->len))) {
5798 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
5809 ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
5816 ext4_mb_initialize_context(ac, ar);
5818 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
5819 seq = this_cpu_read(discard_pa_seq);
5820 if (!ext4_mb_use_preallocated(ac)) {
5821 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
5822 ext4_mb_normalize_request(ac, ar);
5824 *errp = ext4_mb_pa_alloc(ac);
5828 /* allocate space in core */
5829 *errp = ext4_mb_regular_allocator(ac);
5831 * pa allocated above is added to grp->bb_prealloc_list only
5832 * when we were able to allocate some block i.e. when
5833 * ac->ac_status == AC_STATUS_FOUND.
5834 * And error from above mean ac->ac_status != AC_STATUS_FOUND
5835 * So we have to free this pa here itself.
5838 ext4_mb_pa_put_free(ac);
5839 ext4_discard_allocated_blocks(ac);
5842 if (ac->ac_status == AC_STATUS_FOUND &&
5843 ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
5844 ext4_mb_pa_put_free(ac);
5846 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
5847 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
5849 ext4_discard_allocated_blocks(ac);
5852 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
5853 ar->len = ac->ac_b_ex.fe_len;
5856 if (++retries < 3 &&
5857 ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
5860 * If block allocation fails then the pa allocated above
5861 * needs to be freed here itself.
5863 ext4_mb_pa_put_free(ac);
5869 ac->ac_b_ex.fe_len = 0;
5871 ext4_mb_show_ac(ac);
5873 ext4_mb_release_context(ac);
5874 kmem_cache_free(ext4_ac_cachep, ac);
5876 if (inquota && ar->len < inquota)
5877 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
5879 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
5880 /* release all the reserved blocks if non delalloc */
5881 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
5885 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
5891 * We can merge two free data extents only if the physical blocks
5892 * are contiguous, AND the extents were freed by the same transaction,
5893 * AND the blocks are associated with the same group.
5895 static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
5896 struct ext4_free_data *entry,
5897 struct ext4_free_data *new_entry,
5898 struct rb_root *entry_rb_root)
5900 if ((entry->efd_tid != new_entry->efd_tid) ||
5901 (entry->efd_group != new_entry->efd_group))
5903 if (entry->efd_start_cluster + entry->efd_count ==
5904 new_entry->efd_start_cluster) {
5905 new_entry->efd_start_cluster = entry->efd_start_cluster;
5906 new_entry->efd_count += entry->efd_count;
5907 } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
5908 entry->efd_start_cluster) {
5909 new_entry->efd_count += entry->efd_count;
5912 spin_lock(&sbi->s_md_lock);
5913 list_del(&entry->efd_list);
5914 spin_unlock(&sbi->s_md_lock);
5915 rb_erase(&entry->efd_node, entry_rb_root);
5916 kmem_cache_free(ext4_free_data_cachep, entry);
5919 static noinline_for_stack void
5920 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
5921 struct ext4_free_data *new_entry)
5923 ext4_group_t group = e4b->bd_group;
5924 ext4_grpblk_t cluster;
5925 ext4_grpblk_t clusters = new_entry->efd_count;
5926 struct ext4_free_data *entry;
5927 struct ext4_group_info *db = e4b->bd_info;
5928 struct super_block *sb = e4b->bd_sb;
5929 struct ext4_sb_info *sbi = EXT4_SB(sb);
5930 struct rb_node **n = &db->bb_free_root.rb_node, *node;
5931 struct rb_node *parent = NULL, *new_node;
5933 BUG_ON(!ext4_handle_valid(handle));
5934 BUG_ON(e4b->bd_bitmap_page == NULL);
5935 BUG_ON(e4b->bd_buddy_page == NULL);
5937 new_node = &new_entry->efd_node;
5938 cluster = new_entry->efd_start_cluster;
5941 /* first free block exent. We need to
5942 protect buddy cache from being freed,
5943 * otherwise we'll refresh it from
5944 * on-disk bitmap and lose not-yet-available
5946 get_page(e4b->bd_buddy_page);
5947 get_page(e4b->bd_bitmap_page);
5951 entry = rb_entry(parent, struct ext4_free_data, efd_node);
5952 if (cluster < entry->efd_start_cluster)
5954 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
5955 n = &(*n)->rb_right;
5957 ext4_grp_locked_error(sb, group, 0,
5958 ext4_group_first_block_no(sb, group) +
5959 EXT4_C2B(sbi, cluster),
5960 "Block already on to-be-freed list");
5961 kmem_cache_free(ext4_free_data_cachep, new_entry);
5966 rb_link_node(new_node, parent, n);
5967 rb_insert_color(new_node, &db->bb_free_root);
5969 /* Now try to see the extent can be merged to left and right */
5970 node = rb_prev(new_node);
5972 entry = rb_entry(node, struct ext4_free_data, efd_node);
5973 ext4_try_merge_freed_extent(sbi, entry, new_entry,
5974 &(db->bb_free_root));
5977 node = rb_next(new_node);
5979 entry = rb_entry(node, struct ext4_free_data, efd_node);
5980 ext4_try_merge_freed_extent(sbi, entry, new_entry,
5981 &(db->bb_free_root));
5984 spin_lock(&sbi->s_md_lock);
5985 list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
5986 sbi->s_mb_free_pending += clusters;
5987 spin_unlock(&sbi->s_md_lock);
5991 * Simple allocator for Ext4 fast commit replay path. It searches for blocks
5992 * linearly starting at the goal block and also excludes the blocks which
5993 * are going to be in use after fast commit replay.
5995 static ext4_fsblk_t ext4_mb_new_blocks_simple(handle_t *handle,
5996 struct ext4_allocation_request *ar, int *errp)
5998 struct buffer_head *bitmap_bh;
5999 struct super_block *sb = ar->inode->i_sb;
6001 ext4_grpblk_t blkoff;
6002 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
6003 ext4_grpblk_t i = 0;
6004 ext4_fsblk_t goal, block;
6005 struct ext4_super_block *es = EXT4_SB(sb)->s_es;
6008 if (goal < le32_to_cpu(es->s_first_data_block) ||
6009 goal >= ext4_blocks_count(es))
6010 goal = le32_to_cpu(es->s_first_data_block);
6013 ext4_get_group_no_and_offset(sb, goal, &group, &blkoff);
6014 for (; group < ext4_get_groups_count(sb); group++) {
6015 bitmap_bh = ext4_read_block_bitmap(sb, group);
6016 if (IS_ERR(bitmap_bh)) {
6017 *errp = PTR_ERR(bitmap_bh);
6018 pr_warn("Failed to read block bitmap\n");
6023 i = mb_find_next_zero_bit(bitmap_bh->b_data, max,
6027 if (ext4_fc_replay_check_excluded(sb,
6028 ext4_group_first_block_no(sb, group) + i)) {
6040 if (group >= ext4_get_groups_count(sb) || i >= max) {
6045 block = ext4_group_first_block_no(sb, group) + i;
6046 ext4_mb_mark_bb(sb, block, 1, 1);
6052 static void ext4_free_blocks_simple(struct inode *inode, ext4_fsblk_t block,
6053 unsigned long count)
6055 struct buffer_head *bitmap_bh;
6056 struct super_block *sb = inode->i_sb;
6057 struct ext4_group_desc *gdp;
6058 struct buffer_head *gdp_bh;
6060 ext4_grpblk_t blkoff;
6061 int already_freed = 0, err, i;
6063 ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
6064 bitmap_bh = ext4_read_block_bitmap(sb, group);
6065 if (IS_ERR(bitmap_bh)) {
6066 pr_warn("Failed to read block bitmap\n");
6069 gdp = ext4_get_group_desc(sb, group, &gdp_bh);
6073 for (i = 0; i < count; i++) {
6074 if (!mb_test_bit(blkoff + i, bitmap_bh->b_data))
6077 mb_clear_bits(bitmap_bh->b_data, blkoff, count);
6078 err = ext4_handle_dirty_metadata(NULL, NULL, bitmap_bh);
6081 ext4_free_group_clusters_set(
6082 sb, gdp, ext4_free_group_clusters(sb, gdp) +
6083 count - already_freed);
6084 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
6085 ext4_group_desc_csum_set(sb, group, gdp);
6086 ext4_handle_dirty_metadata(NULL, NULL, gdp_bh);
6087 sync_dirty_buffer(bitmap_bh);
6088 sync_dirty_buffer(gdp_bh);
6095 * ext4_mb_clear_bb() -- helper function for freeing blocks.
6096 * Used by ext4_free_blocks()
6097 * @handle: handle for this transaction
6099 * @block: starting physical block to be freed
6100 * @count: number of blocks to be freed
6101 * @flags: flags used by ext4_free_blocks
6103 static void ext4_mb_clear_bb(handle_t *handle, struct inode *inode,
6104 ext4_fsblk_t block, unsigned long count,
6107 struct buffer_head *bitmap_bh = NULL;
6108 struct super_block *sb = inode->i_sb;
6109 struct ext4_group_desc *gdp;
6110 struct ext4_group_info *grp;
6111 unsigned int overflow;
6113 struct buffer_head *gd_bh;
6114 ext4_group_t block_group;
6115 struct ext4_sb_info *sbi;
6116 struct ext4_buddy e4b;
6117 unsigned int count_clusters;
6123 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6124 !ext4_inode_block_valid(inode, block, count)) {
6125 ext4_error(sb, "Freeing blocks in system zone - "
6126 "Block = %llu, count = %lu", block, count);
6127 /* err = 0. ext4_std_error should be a no op */
6130 flags |= EXT4_FREE_BLOCKS_VALIDATED;
6134 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
6136 grp = ext4_get_group_info(sb, block_group);
6137 if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
6141 * Check to see if we are freeing blocks across a group
6144 if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
6145 overflow = EXT4_C2B(sbi, bit) + count -
6146 EXT4_BLOCKS_PER_GROUP(sb);
6148 /* The range changed so it's no longer validated */
6149 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6151 count_clusters = EXT4_NUM_B2C(sbi, count);
6152 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
6153 if (IS_ERR(bitmap_bh)) {
6154 err = PTR_ERR(bitmap_bh);
6158 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
6164 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6165 !ext4_inode_block_valid(inode, block, count)) {
6166 ext4_error(sb, "Freeing blocks in system zone - "
6167 "Block = %llu, count = %lu", block, count);
6168 /* err = 0. ext4_std_error should be a no op */
6172 BUFFER_TRACE(bitmap_bh, "getting write access");
6173 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
6179 * We are about to modify some metadata. Call the journal APIs
6180 * to unshare ->b_data if a currently-committing transaction is
6183 BUFFER_TRACE(gd_bh, "get_write_access");
6184 err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
6187 #ifdef AGGRESSIVE_CHECK
6190 for (i = 0; i < count_clusters; i++)
6191 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
6194 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
6196 /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
6197 err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
6198 GFP_NOFS|__GFP_NOFAIL);
6203 * We need to make sure we don't reuse the freed block until after the
6204 * transaction is committed. We make an exception if the inode is to be
6205 * written in writeback mode since writeback mode has weak data
6206 * consistency guarantees.
6208 if (ext4_handle_valid(handle) &&
6209 ((flags & EXT4_FREE_BLOCKS_METADATA) ||
6210 !ext4_should_writeback_data(inode))) {
6211 struct ext4_free_data *new_entry;
6213 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
6216 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
6217 GFP_NOFS|__GFP_NOFAIL);
6218 new_entry->efd_start_cluster = bit;
6219 new_entry->efd_group = block_group;
6220 new_entry->efd_count = count_clusters;
6221 new_entry->efd_tid = handle->h_transaction->t_tid;
6223 ext4_lock_group(sb, block_group);
6224 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
6225 ext4_mb_free_metadata(handle, &e4b, new_entry);
6227 /* need to update group_info->bb_free and bitmap
6228 * with group lock held. generate_buddy look at
6229 * them with group lock_held
6231 if (test_opt(sb, DISCARD)) {
6232 err = ext4_issue_discard(sb, block_group, bit, count,
6234 if (err && err != -EOPNOTSUPP)
6235 ext4_msg(sb, KERN_WARNING, "discard request in"
6236 " group:%u block:%d count:%lu failed"
6237 " with %d", block_group, bit, count,
6240 EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
6242 ext4_lock_group(sb, block_group);
6243 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
6244 mb_free_blocks(inode, &e4b, bit, count_clusters);
6247 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
6248 ext4_free_group_clusters_set(sb, gdp, ret);
6249 ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
6250 ext4_group_desc_csum_set(sb, block_group, gdp);
6251 ext4_unlock_group(sb, block_group);
6253 if (sbi->s_log_groups_per_flex) {
6254 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
6255 atomic64_add(count_clusters,
6256 &sbi_array_rcu_deref(sbi, s_flex_groups,
6257 flex_group)->free_clusters);
6261 * on a bigalloc file system, defer the s_freeclusters_counter
6262 * update to the caller (ext4_remove_space and friends) so they
6263 * can determine if a cluster freed here should be rereserved
6265 if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
6266 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
6267 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
6268 percpu_counter_add(&sbi->s_freeclusters_counter,
6272 ext4_mb_unload_buddy(&e4b);
6274 /* We dirtied the bitmap block */
6275 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
6276 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
6278 /* And the group descriptor block */
6279 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
6280 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
6284 if (overflow && !err) {
6288 /* The range changed so it's no longer validated */
6289 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6294 ext4_std_error(sb, err);
6299 * ext4_free_blocks() -- Free given blocks and update quota
6300 * @handle: handle for this transaction
6302 * @bh: optional buffer of the block to be freed
6303 * @block: starting physical block to be freed
6304 * @count: number of blocks to be freed
6305 * @flags: flags used by ext4_free_blocks
6307 void ext4_free_blocks(handle_t *handle, struct inode *inode,
6308 struct buffer_head *bh, ext4_fsblk_t block,
6309 unsigned long count, int flags)
6311 struct super_block *sb = inode->i_sb;
6312 unsigned int overflow;
6313 struct ext4_sb_info *sbi;
6317 if (sbi->s_mount_state & EXT4_FC_REPLAY) {
6318 ext4_free_blocks_simple(inode, block, count);
6325 BUG_ON(block != bh->b_blocknr);
6327 block = bh->b_blocknr;
6330 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
6331 !ext4_inode_block_valid(inode, block, count)) {
6332 ext4_error(sb, "Freeing blocks not in datazone - "
6333 "block = %llu, count = %lu", block, count);
6336 flags |= EXT4_FREE_BLOCKS_VALIDATED;
6338 ext4_debug("freeing block %llu\n", block);
6339 trace_ext4_free_blocks(inode, block, count, flags);
6341 if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
6344 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
6349 * If the extent to be freed does not begin on a cluster
6350 * boundary, we need to deal with partial clusters at the
6351 * beginning and end of the extent. Normally we will free
6352 * blocks at the beginning or the end unless we are explicitly
6353 * requested to avoid doing so.
6355 overflow = EXT4_PBLK_COFF(sbi, block);
6357 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
6358 overflow = sbi->s_cluster_ratio - overflow;
6360 if (count > overflow)
6368 /* The range changed so it's no longer validated */
6369 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6371 overflow = EXT4_LBLK_COFF(sbi, count);
6373 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
6374 if (count > overflow)
6379 count += sbi->s_cluster_ratio - overflow;
6380 /* The range changed so it's no longer validated */
6381 flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
6384 if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
6386 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
6388 for (i = 0; i < count; i++) {
6391 bh = sb_find_get_block(inode->i_sb, block + i);
6392 ext4_forget(handle, is_metadata, inode, bh, block + i);
6396 ext4_mb_clear_bb(handle, inode, block, count, flags);
6401 * ext4_group_add_blocks() -- Add given blocks to an existing group
6402 * @handle: handle to this transaction
6404 * @block: start physical block to add to the block group
6405 * @count: number of blocks to free
6407 * This marks the blocks as free in the bitmap and buddy.
6409 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
6410 ext4_fsblk_t block, unsigned long count)
6412 struct buffer_head *bitmap_bh = NULL;
6413 struct buffer_head *gd_bh;
6414 ext4_group_t block_group;
6417 struct ext4_group_desc *desc;
6418 struct ext4_sb_info *sbi = EXT4_SB(sb);
6419 struct ext4_buddy e4b;
6420 int err = 0, ret, free_clusters_count;
6421 ext4_grpblk_t clusters_freed;
6422 ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
6423 ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
6424 unsigned long cluster_count = last_cluster - first_cluster + 1;
6426 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
6431 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
6433 * Check to see if we are freeing blocks across a group
6436 if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
6437 ext4_warning(sb, "too many blocks added to group %u",
6443 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
6444 if (IS_ERR(bitmap_bh)) {
6445 err = PTR_ERR(bitmap_bh);
6450 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
6456 if (!ext4_sb_block_valid(sb, NULL, block, count)) {
6457 ext4_error(sb, "Adding blocks in system zones - "
6458 "Block = %llu, count = %lu",
6464 BUFFER_TRACE(bitmap_bh, "getting write access");
6465 err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
6471 * We are about to modify some metadata. Call the journal APIs
6472 * to unshare ->b_data if a currently-committing transaction is
6475 BUFFER_TRACE(gd_bh, "get_write_access");
6476 err = ext4_journal_get_write_access(handle, sb, gd_bh, EXT4_JTR_NONE);
6480 for (i = 0, clusters_freed = 0; i < cluster_count; i++) {
6481 BUFFER_TRACE(bitmap_bh, "clear bit");
6482 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
6483 ext4_error(sb, "bit already cleared for block %llu",
6484 (ext4_fsblk_t)(block + i));
6485 BUFFER_TRACE(bitmap_bh, "bit already cleared");
6491 err = ext4_mb_load_buddy(sb, block_group, &e4b);
6496 * need to update group_info->bb_free and bitmap
6497 * with group lock held. generate_buddy look at
6498 * them with group lock_held
6500 ext4_lock_group(sb, block_group);
6501 mb_clear_bits(bitmap_bh->b_data, bit, cluster_count);
6502 mb_free_blocks(NULL, &e4b, bit, cluster_count);
6503 free_clusters_count = clusters_freed +
6504 ext4_free_group_clusters(sb, desc);
6505 ext4_free_group_clusters_set(sb, desc, free_clusters_count);
6506 ext4_block_bitmap_csum_set(sb, desc, bitmap_bh);
6507 ext4_group_desc_csum_set(sb, block_group, desc);
6508 ext4_unlock_group(sb, block_group);
6509 percpu_counter_add(&sbi->s_freeclusters_counter,
6512 if (sbi->s_log_groups_per_flex) {
6513 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
6514 atomic64_add(clusters_freed,
6515 &sbi_array_rcu_deref(sbi, s_flex_groups,
6516 flex_group)->free_clusters);
6519 ext4_mb_unload_buddy(&e4b);
6521 /* We dirtied the bitmap block */
6522 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
6523 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
6525 /* And the group descriptor block */
6526 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
6527 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
6533 ext4_std_error(sb, err);
6538 * ext4_trim_extent -- function to TRIM one single free extent in the group
6539 * @sb: super block for the file system
6540 * @start: starting block of the free extent in the alloc. group
6541 * @count: number of blocks to TRIM
6542 * @e4b: ext4 buddy for the group
6544 * Trim "count" blocks starting at "start" in the "group". To assure that no
6545 * one will allocate those blocks, mark it as used in buddy bitmap. This must
6546 * be called with under the group lock.
6548 static int ext4_trim_extent(struct super_block *sb,
6549 int start, int count, struct ext4_buddy *e4b)
6553 struct ext4_free_extent ex;
6554 ext4_group_t group = e4b->bd_group;
6557 trace_ext4_trim_extent(sb, group, start, count);
6559 assert_spin_locked(ext4_group_lock_ptr(sb, group));
6561 ex.fe_start = start;
6562 ex.fe_group = group;
6566 * Mark blocks used, so no one can reuse them while
6569 mb_mark_used(e4b, &ex);
6570 ext4_unlock_group(sb, group);
6571 ret = ext4_issue_discard(sb, group, start, count, NULL);
6572 ext4_lock_group(sb, group);
6573 mb_free_blocks(NULL, e4b, start, ex.fe_len);
6577 static int ext4_try_to_trim_range(struct super_block *sb,
6578 struct ext4_buddy *e4b, ext4_grpblk_t start,
6579 ext4_grpblk_t max, ext4_grpblk_t minblocks)
6580 __acquires(ext4_group_lock_ptr(sb, e4b->bd_group))
6581 __releases(ext4_group_lock_ptr(sb, e4b->bd_group))
6583 ext4_grpblk_t next, count, free_count;
6586 bitmap = e4b->bd_bitmap;
6587 start = (e4b->bd_info->bb_first_free > start) ?
6588 e4b->bd_info->bb_first_free : start;
6592 while (start <= max) {
6593 start = mb_find_next_zero_bit(bitmap, max + 1, start);
6596 next = mb_find_next_bit(bitmap, max + 1, start);
6598 if ((next - start) >= minblocks) {
6599 int ret = ext4_trim_extent(sb, start, next - start, e4b);
6601 if (ret && ret != -EOPNOTSUPP)
6603 count += next - start;
6605 free_count += next - start;
6608 if (fatal_signal_pending(current)) {
6609 count = -ERESTARTSYS;
6613 if (need_resched()) {
6614 ext4_unlock_group(sb, e4b->bd_group);
6616 ext4_lock_group(sb, e4b->bd_group);
6619 if ((e4b->bd_info->bb_free - free_count) < minblocks)
6627 * ext4_trim_all_free -- function to trim all free space in alloc. group
6628 * @sb: super block for file system
6629 * @group: group to be trimmed
6630 * @start: first group block to examine
6631 * @max: last group block to examine
6632 * @minblocks: minimum extent block count
6633 * @set_trimmed: set the trimmed flag if at least one block is trimmed
6635 * ext4_trim_all_free walks through group's block bitmap searching for free
6636 * extents. When the free extent is found, mark it as used in group buddy
6637 * bitmap. Then issue a TRIM command on this extent and free the extent in
6638 * the group buddy bitmap.
6640 static ext4_grpblk_t
6641 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
6642 ext4_grpblk_t start, ext4_grpblk_t max,
6643 ext4_grpblk_t minblocks, bool set_trimmed)
6645 struct ext4_buddy e4b;
6648 trace_ext4_trim_all_free(sb, group, start, max);
6650 ret = ext4_mb_load_buddy(sb, group, &e4b);
6652 ext4_warning(sb, "Error %d loading buddy information for %u",
6657 ext4_lock_group(sb, group);
6659 if (!EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) ||
6660 minblocks < EXT4_SB(sb)->s_last_trim_minblks) {
6661 ret = ext4_try_to_trim_range(sb, &e4b, start, max, minblocks);
6662 if (ret >= 0 && set_trimmed)
6663 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
6668 ext4_unlock_group(sb, group);
6669 ext4_mb_unload_buddy(&e4b);
6671 ext4_debug("trimmed %d blocks in the group %d\n",
6678 * ext4_trim_fs() -- trim ioctl handle function
6679 * @sb: superblock for filesystem
6680 * @range: fstrim_range structure
6682 * start: First Byte to trim
6683 * len: number of Bytes to trim from start
6684 * minlen: minimum extent length in Bytes
6685 * ext4_trim_fs goes through all allocation groups containing Bytes from
6686 * start to start+len. For each such a group ext4_trim_all_free function
6687 * is invoked to trim all free space.
6689 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
6691 unsigned int discard_granularity = bdev_discard_granularity(sb->s_bdev);
6692 struct ext4_group_info *grp;
6693 ext4_group_t group, first_group, last_group;
6694 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
6695 uint64_t start, end, minlen, trimmed = 0;
6696 ext4_fsblk_t first_data_blk =
6697 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
6698 ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
6699 bool whole_group, eof = false;
6702 start = range->start >> sb->s_blocksize_bits;
6703 end = start + (range->len >> sb->s_blocksize_bits) - 1;
6704 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
6705 range->minlen >> sb->s_blocksize_bits);
6707 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
6708 start >= max_blks ||
6709 range->len < sb->s_blocksize)
6711 /* No point to try to trim less than discard granularity */
6712 if (range->minlen < discard_granularity) {
6713 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
6714 discard_granularity >> sb->s_blocksize_bits);
6715 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
6718 if (end >= max_blks - 1) {
6722 if (end <= first_data_blk)
6724 if (start < first_data_blk)
6725 start = first_data_blk;
6727 /* Determine first and last group to examine based on start and end */
6728 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
6729 &first_group, &first_cluster);
6730 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
6731 &last_group, &last_cluster);
6733 /* end now represents the last cluster to discard in this group */
6734 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
6737 for (group = first_group; group <= last_group; group++) {
6738 grp = ext4_get_group_info(sb, group);
6741 /* We only do this if the grp has never been initialized */
6742 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
6743 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
6749 * For all the groups except the last one, last cluster will
6750 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
6751 * change it for the last group, note that last_cluster is
6752 * already computed earlier by ext4_get_group_no_and_offset()
6754 if (group == last_group) {
6756 whole_group = eof ? true : end == EXT4_CLUSTERS_PER_GROUP(sb) - 1;
6758 if (grp->bb_free >= minlen) {
6759 cnt = ext4_trim_all_free(sb, group, first_cluster,
6760 end, minlen, whole_group);
6769 * For every group except the first one, we are sure
6770 * that the first cluster to discard will be cluster #0.
6776 EXT4_SB(sb)->s_last_trim_minblks = minlen;
6779 range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
6783 /* Iterate all the free extents in the group. */
6785 ext4_mballoc_query_range(
6786 struct super_block *sb,
6788 ext4_grpblk_t start,
6790 ext4_mballoc_query_range_fn formatter,
6795 struct ext4_buddy e4b;
6798 error = ext4_mb_load_buddy(sb, group, &e4b);
6801 bitmap = e4b.bd_bitmap;
6803 ext4_lock_group(sb, group);
6805 start = (e4b.bd_info->bb_first_free > start) ?
6806 e4b.bd_info->bb_first_free : start;
6807 if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
6808 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
6810 while (start <= end) {
6811 start = mb_find_next_zero_bit(bitmap, end + 1, start);
6814 next = mb_find_next_bit(bitmap, end + 1, start);
6816 ext4_unlock_group(sb, group);
6817 error = formatter(sb, group, start, next - start, priv);
6820 ext4_lock_group(sb, group);
6825 ext4_unlock_group(sb, group);
6827 ext4_mb_unload_buddy(&e4b);