2 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3 * Written by Alex Tomas <alex@clusterfs.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
21 * mballoc.c contains the multiblocks allocation routines
24 #include "ext4_jbd2.h"
26 #include <linux/log2.h>
27 #include <linux/module.h>
28 #include <linux/slab.h>
29 #include <linux/nospec.h>
30 #include <linux/backing-dev.h>
31 #include <trace/events/ext4.h>
33 #ifdef CONFIG_EXT4_DEBUG
34 ushort ext4_mballoc_debug __read_mostly;
36 module_param_named(mballoc_debug, ext4_mballoc_debug, ushort, 0644);
37 MODULE_PARM_DESC(mballoc_debug, "Debugging level for ext4's mballoc");
42 * - test ext4_ext_search_left() and ext4_ext_search_right()
43 * - search for metadata in few groups
46 * - normalization should take into account whether file is still open
47 * - discard preallocations if no free space left (policy?)
48 * - don't normalize tails
50 * - reservation for superuser
53 * - bitmap read-ahead (proposed by Oleg Drokin aka green)
54 * - track min/max extents in each group for better group selection
55 * - mb_mark_used() may allocate chunk right after splitting buddy
56 * - tree of groups sorted by number of free blocks
61 * The allocation request involve request for multiple number of blocks
62 * near to the goal(block) value specified.
64 * During initialization phase of the allocator we decide to use the
65 * group preallocation or inode preallocation depending on the size of
66 * the file. The size of the file could be the resulting file size we
67 * would have after allocation, or the current file size, which ever
68 * is larger. If the size is less than sbi->s_mb_stream_request we
69 * select to use the group preallocation. The default value of
70 * s_mb_stream_request is 16 blocks. This can also be tuned via
71 * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
72 * terms of number of blocks.
74 * The main motivation for having small file use group preallocation is to
75 * ensure that we have small files closer together on the disk.
77 * First stage the allocator looks at the inode prealloc list,
78 * ext4_inode_info->i_prealloc_list, which contains list of prealloc
79 * spaces for this particular inode. The inode prealloc space is
82 * pa_lstart -> the logical start block for this prealloc space
83 * pa_pstart -> the physical start block for this prealloc space
84 * pa_len -> length for this prealloc space (in clusters)
85 * pa_free -> free space available in this prealloc space (in clusters)
87 * The inode preallocation space is used looking at the _logical_ start
88 * block. If only the logical file block falls within the range of prealloc
89 * space we will consume the particular prealloc space. This makes sure that
90 * we have contiguous physical blocks representing the file blocks
92 * The important thing to be noted in case of inode prealloc space is that
93 * we don't modify the values associated to inode prealloc space except
96 * If we are not able to find blocks in the inode prealloc space and if we
97 * have the group allocation flag set then we look at the locality group
98 * prealloc space. These are per CPU prealloc list represented as
100 * ext4_sb_info.s_locality_groups[smp_processor_id()]
102 * The reason for having a per cpu locality group is to reduce the contention
103 * between CPUs. It is possible to get scheduled at this point.
105 * The locality group prealloc space is used looking at whether we have
106 * enough free space (pa_free) within the prealloc space.
108 * If we can't allocate blocks via inode prealloc or/and locality group
109 * prealloc then we look at the buddy cache. The buddy cache is represented
110 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
111 * mapped to the buddy and bitmap information regarding different
112 * groups. The buddy information is attached to buddy cache inode so that
113 * we can access them through the page cache. The information regarding
114 * each group is loaded via ext4_mb_load_buddy. The information involve
115 * block bitmap and buddy information. The information are stored in the
119 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
122 * one block each for bitmap and buddy information. So for each group we
123 * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
124 * blocksize) blocks. So it can have information regarding groups_per_page
125 * which is blocks_per_page/2
127 * The buddy cache inode is not stored on disk. The inode is thrown
128 * away when the filesystem is unmounted.
130 * We look for count number of blocks in the buddy cache. If we were able
131 * to locate that many free blocks we return with additional information
132 * regarding rest of the contiguous physical block available
134 * Before allocating blocks via buddy cache we normalize the request
135 * blocks. This ensure we ask for more blocks that we needed. The extra
136 * blocks that we get after allocation is added to the respective prealloc
137 * list. In case of inode preallocation we follow a list of heuristics
138 * based on file size. This can be found in ext4_mb_normalize_request. If
139 * we are doing a group prealloc we try to normalize the request to
140 * sbi->s_mb_group_prealloc. The default value of s_mb_group_prealloc is
141 * dependent on the cluster size; for non-bigalloc file systems, it is
142 * 512 blocks. This can be tuned via
143 * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
144 * terms of number of blocks. If we have mounted the file system with -O
145 * stripe=<value> option the group prealloc request is normalized to the
146 * the smallest multiple of the stripe value (sbi->s_stripe) which is
147 * greater than the default mb_group_prealloc.
149 * The regular allocator (using the buddy cache) supports a few tunables.
151 * /sys/fs/ext4/<partition>/mb_min_to_scan
152 * /sys/fs/ext4/<partition>/mb_max_to_scan
153 * /sys/fs/ext4/<partition>/mb_order2_req
155 * The regular allocator uses buddy scan only if the request len is power of
156 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
157 * value of s_mb_order2_reqs can be tuned via
158 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
159 * stripe size (sbi->s_stripe), we try to search for contiguous block in
160 * stripe size. This should result in better allocation on RAID setups. If
161 * not, we search in the specific group using bitmap for best extents. The
162 * tunable min_to_scan and max_to_scan control the behaviour here.
163 * min_to_scan indicate how long the mballoc __must__ look for a best
164 * extent and max_to_scan indicates how long the mballoc __can__ look for a
165 * best extent in the found extents. Searching for the blocks starts with
166 * the group specified as the goal value in allocation context via
167 * ac_g_ex. Each group is first checked based on the criteria whether it
168 * can be used for allocation. ext4_mb_good_group explains how the groups are
171 * Both the prealloc space are getting populated as above. So for the first
172 * request we will hit the buddy cache which will result in this prealloc
173 * space getting filled. The prealloc space is then later used for the
174 * subsequent request.
178 * mballoc operates on the following data:
180 * - in-core buddy (actually includes buddy and bitmap)
181 * - preallocation descriptors (PAs)
183 * there are two types of preallocations:
185 * assiged to specific inode and can be used for this inode only.
186 * it describes part of inode's space preallocated to specific
187 * physical blocks. any block from that preallocated can be used
188 * independent. the descriptor just tracks number of blocks left
189 * unused. so, before taking some block from descriptor, one must
190 * make sure corresponded logical block isn't allocated yet. this
191 * also means that freeing any block within descriptor's range
192 * must discard all preallocated blocks.
194 * assigned to specific locality group which does not translate to
195 * permanent set of inodes: inode can join and leave group. space
196 * from this type of preallocation can be used for any inode. thus
197 * it's consumed from the beginning to the end.
199 * relation between them can be expressed as:
200 * in-core buddy = on-disk bitmap + preallocation descriptors
202 * this mean blocks mballoc considers used are:
203 * - allocated blocks (persistent)
204 * - preallocated blocks (non-persistent)
206 * consistency in mballoc world means that at any time a block is either
207 * free or used in ALL structures. notice: "any time" should not be read
208 * literally -- time is discrete and delimited by locks.
210 * to keep it simple, we don't use block numbers, instead we count number of
211 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
213 * all operations can be expressed as:
214 * - init buddy: buddy = on-disk + PAs
215 * - new PA: buddy += N; PA = N
216 * - use inode PA: on-disk += N; PA -= N
217 * - discard inode PA buddy -= on-disk - PA; PA = 0
218 * - use locality group PA on-disk += N; PA -= N
219 * - discard locality group PA buddy -= PA; PA = 0
220 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
221 * is used in real operation because we can't know actual used
222 * bits from PA, only from on-disk bitmap
224 * if we follow this strict logic, then all operations above should be atomic.
225 * given some of them can block, we'd have to use something like semaphores
226 * killing performance on high-end SMP hardware. let's try to relax it using
227 * the following knowledge:
228 * 1) if buddy is referenced, it's already initialized
229 * 2) while block is used in buddy and the buddy is referenced,
230 * nobody can re-allocate that block
231 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
232 * bit set and PA claims same block, it's OK. IOW, one can set bit in
233 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
236 * so, now we're building a concurrency table:
239 * blocks for PA are allocated in the buddy, buddy must be referenced
240 * until PA is linked to allocation group to avoid concurrent buddy init
242 * we need to make sure that either on-disk bitmap or PA has uptodate data
243 * given (3) we care that PA-=N operation doesn't interfere with init
245 * the simplest way would be to have buddy initialized by the discard
246 * - use locality group PA
247 * again PA-=N must be serialized with init
248 * - discard locality group PA
249 * the simplest way would be to have buddy initialized by the discard
252 * i_data_sem serializes them
254 * discard process must wait until PA isn't used by another process
255 * - use locality group PA
256 * some mutex should serialize them
257 * - discard locality group PA
258 * discard process must wait until PA isn't used by another process
261 * i_data_sem or another mutex should serializes them
263 * discard process must wait until PA isn't used by another process
264 * - use locality group PA
265 * nothing wrong here -- they're different PAs covering different blocks
266 * - discard locality group PA
267 * discard process must wait until PA isn't used by another process
269 * now we're ready to make few consequences:
270 * - PA is referenced and while it is no discard is possible
271 * - PA is referenced until block isn't marked in on-disk bitmap
272 * - PA changes only after on-disk bitmap
273 * - discard must not compete with init. either init is done before
274 * any discard or they're serialized somehow
275 * - buddy init as sum of on-disk bitmap and PAs is done atomically
277 * a special case when we've used PA to emptiness. no need to modify buddy
278 * in this case, but we should care about concurrent init
283 * Logic in few words:
288 * mark bits in on-disk bitmap
291 * - use preallocation:
292 * find proper PA (per-inode or group)
294 * mark bits in on-disk bitmap
300 * mark bits in on-disk bitmap
303 * - discard preallocations in group:
305 * move them onto local list
306 * load on-disk bitmap
308 * remove PA from object (inode or locality group)
309 * mark free blocks in-core
311 * - discard inode's preallocations:
318 * - bitlock on a group (group)
319 * - object (inode/locality) (object)
330 * - release consumed pa:
335 * - generate in-core bitmap:
339 * - discard all for given object (inode, locality group):
344 * - discard all for given group:
351 static struct kmem_cache *ext4_pspace_cachep;
352 static struct kmem_cache *ext4_ac_cachep;
353 static struct kmem_cache *ext4_free_data_cachep;
355 /* We create slab caches for groupinfo data structures based on the
356 * superblock block size. There will be one per mounted filesystem for
357 * each unique s_blocksize_bits */
358 #define NR_GRPINFO_CACHES 8
359 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
361 static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
362 "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
363 "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
364 "ext4_groupinfo_64k", "ext4_groupinfo_128k"
367 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
369 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
372 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
374 #if BITS_PER_LONG == 64
375 *bit += ((unsigned long) addr & 7UL) << 3;
376 addr = (void *) ((unsigned long) addr & ~7UL);
377 #elif BITS_PER_LONG == 32
378 *bit += ((unsigned long) addr & 3UL) << 3;
379 addr = (void *) ((unsigned long) addr & ~3UL);
381 #error "how many bits you are?!"
386 static inline int mb_test_bit(int bit, void *addr)
389 * ext4_test_bit on architecture like powerpc
390 * needs unsigned long aligned address
392 addr = mb_correct_addr_and_bit(&bit, addr);
393 return ext4_test_bit(bit, addr);
396 static inline void mb_set_bit(int bit, void *addr)
398 addr = mb_correct_addr_and_bit(&bit, addr);
399 ext4_set_bit(bit, addr);
402 static inline void mb_clear_bit(int bit, void *addr)
404 addr = mb_correct_addr_and_bit(&bit, addr);
405 ext4_clear_bit(bit, addr);
408 static inline int mb_test_and_clear_bit(int bit, void *addr)
410 addr = mb_correct_addr_and_bit(&bit, addr);
411 return ext4_test_and_clear_bit(bit, addr);
414 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
416 int fix = 0, ret, tmpmax;
417 addr = mb_correct_addr_and_bit(&fix, addr);
421 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
427 static inline int mb_find_next_bit(void *addr, int max, int start)
429 int fix = 0, ret, tmpmax;
430 addr = mb_correct_addr_and_bit(&fix, addr);
434 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
440 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
444 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
447 if (order > e4b->bd_blkbits + 1) {
452 /* at order 0 we see each particular block */
454 *max = 1 << (e4b->bd_blkbits + 3);
455 return e4b->bd_bitmap;
458 bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
459 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
465 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
466 int first, int count)
469 struct super_block *sb = e4b->bd_sb;
471 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
473 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
474 for (i = 0; i < count; i++) {
475 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
476 ext4_fsblk_t blocknr;
478 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
479 blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
480 ext4_grp_locked_error(sb, e4b->bd_group,
481 inode ? inode->i_ino : 0,
483 "freeing block already freed "
487 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
491 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
495 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
497 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
498 for (i = 0; i < count; i++) {
499 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
500 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
504 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
506 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
507 unsigned char *b1, *b2;
509 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
510 b2 = (unsigned char *) bitmap;
511 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
512 if (b1[i] != b2[i]) {
513 ext4_msg(e4b->bd_sb, KERN_ERR,
514 "corruption in group %u "
515 "at byte %u(%u): %x in copy != %x "
517 e4b->bd_group, i, i * 8, b1[i], b2[i]);
525 static inline void mb_free_blocks_double(struct inode *inode,
526 struct ext4_buddy *e4b, int first, int count)
530 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
531 int first, int count)
535 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
541 #ifdef AGGRESSIVE_CHECK
543 #define MB_CHECK_ASSERT(assert) \
547 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
548 function, file, line, # assert); \
553 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
554 const char *function, int line)
556 struct super_block *sb = e4b->bd_sb;
557 int order = e4b->bd_blkbits + 1;
564 struct ext4_group_info *grp;
567 struct list_head *cur;
572 static int mb_check_counter;
573 if (mb_check_counter++ % 100 != 0)
578 buddy = mb_find_buddy(e4b, order, &max);
579 MB_CHECK_ASSERT(buddy);
580 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
581 MB_CHECK_ASSERT(buddy2);
582 MB_CHECK_ASSERT(buddy != buddy2);
583 MB_CHECK_ASSERT(max * 2 == max2);
586 for (i = 0; i < max; i++) {
588 if (mb_test_bit(i, buddy)) {
589 /* only single bit in buddy2 may be 1 */
590 if (!mb_test_bit(i << 1, buddy2)) {
592 mb_test_bit((i<<1)+1, buddy2));
593 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
595 mb_test_bit(i << 1, buddy2));
600 /* both bits in buddy2 must be 1 */
601 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
602 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
604 for (j = 0; j < (1 << order); j++) {
605 k = (i * (1 << order)) + j;
607 !mb_test_bit(k, e4b->bd_bitmap));
611 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
616 buddy = mb_find_buddy(e4b, 0, &max);
617 for (i = 0; i < max; i++) {
618 if (!mb_test_bit(i, buddy)) {
619 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
627 /* check used bits only */
628 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
629 buddy2 = mb_find_buddy(e4b, j, &max2);
631 MB_CHECK_ASSERT(k < max2);
632 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
635 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
636 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
638 grp = ext4_get_group_info(sb, e4b->bd_group);
639 list_for_each(cur, &grp->bb_prealloc_list) {
640 ext4_group_t groupnr;
641 struct ext4_prealloc_space *pa;
642 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
643 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
644 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
645 for (i = 0; i < pa->pa_len; i++)
646 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
650 #undef MB_CHECK_ASSERT
651 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
652 __FILE__, __func__, __LINE__)
654 #define mb_check_buddy(e4b)
658 * Divide blocks started from @first with length @len into
659 * smaller chunks with power of 2 blocks.
660 * Clear the bits in bitmap which the blocks of the chunk(s) covered,
661 * then increase bb_counters[] for corresponded chunk size.
663 static void ext4_mb_mark_free_simple(struct super_block *sb,
664 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
665 struct ext4_group_info *grp)
667 struct ext4_sb_info *sbi = EXT4_SB(sb);
673 BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
675 border = 2 << sb->s_blocksize_bits;
678 /* find how many blocks can be covered since this position */
679 max = ffs(first | border) - 1;
681 /* find how many blocks of power 2 we need to mark */
688 /* mark multiblock chunks only */
689 grp->bb_counters[min]++;
691 mb_clear_bit(first >> min,
692 buddy + sbi->s_mb_offsets[min]);
700 * Cache the order of the largest free extent we have available in this block
704 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
709 grp->bb_largest_free_order = -1; /* uninit */
711 bits = sb->s_blocksize_bits + 1;
712 for (i = bits; i >= 0; i--) {
713 if (grp->bb_counters[i] > 0) {
714 grp->bb_largest_free_order = i;
720 static noinline_for_stack
721 void ext4_mb_generate_buddy(struct super_block *sb,
722 void *buddy, void *bitmap, ext4_group_t group)
724 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
725 struct ext4_sb_info *sbi = EXT4_SB(sb);
726 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
731 unsigned fragments = 0;
732 unsigned long long period = get_cycles();
734 /* initialize buddy from bitmap which is aggregation
735 * of on-disk bitmap and preallocations */
736 i = mb_find_next_zero_bit(bitmap, max, 0);
737 grp->bb_first_free = i;
741 i = mb_find_next_bit(bitmap, max, i);
745 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
747 grp->bb_counters[0]++;
749 i = mb_find_next_zero_bit(bitmap, max, i);
751 grp->bb_fragments = fragments;
753 if (free != grp->bb_free) {
754 ext4_grp_locked_error(sb, group, 0, 0,
755 "block bitmap and bg descriptor "
756 "inconsistent: %u vs %u free clusters",
759 * If we intend to continue, we consider group descriptor
760 * corrupt and update bb_free using bitmap value
763 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
764 percpu_counter_sub(&sbi->s_freeclusters_counter,
766 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT, &grp->bb_state);
768 mb_set_largest_free_order(sb, grp);
770 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
772 period = get_cycles() - period;
773 spin_lock(&EXT4_SB(sb)->s_bal_lock);
774 EXT4_SB(sb)->s_mb_buddies_generated++;
775 EXT4_SB(sb)->s_mb_generation_time += period;
776 spin_unlock(&EXT4_SB(sb)->s_bal_lock);
779 static void mb_regenerate_buddy(struct ext4_buddy *e4b)
785 while ((buddy = mb_find_buddy(e4b, order++, &count))) {
786 ext4_set_bits(buddy, 0, count);
788 e4b->bd_info->bb_fragments = 0;
789 memset(e4b->bd_info->bb_counters, 0,
790 sizeof(*e4b->bd_info->bb_counters) *
791 (e4b->bd_sb->s_blocksize_bits + 2));
793 ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
794 e4b->bd_bitmap, e4b->bd_group);
797 /* The buddy information is attached the buddy cache inode
798 * for convenience. The information regarding each group
799 * is loaded via ext4_mb_load_buddy. The information involve
800 * block bitmap and buddy information. The information are
801 * stored in the inode as
804 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
807 * one block each for bitmap and buddy information.
808 * So for each group we take up 2 blocks. A page can
809 * contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
810 * So it can have information regarding groups_per_page which
811 * is blocks_per_page/2
813 * Locking note: This routine takes the block group lock of all groups
814 * for this page; do not hold this lock when calling this routine!
817 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
819 ext4_group_t ngroups;
825 ext4_group_t first_group, group;
827 struct super_block *sb;
828 struct buffer_head *bhs;
829 struct buffer_head **bh = NULL;
833 struct ext4_group_info *grinfo;
835 mb_debug(1, "init page %lu\n", page->index);
837 inode = page->mapping->host;
839 ngroups = ext4_get_groups_count(sb);
840 blocksize = i_blocksize(inode);
841 blocks_per_page = PAGE_SIZE / blocksize;
843 groups_per_page = blocks_per_page >> 1;
844 if (groups_per_page == 0)
847 /* allocate buffer_heads to read bitmaps */
848 if (groups_per_page > 1) {
849 i = sizeof(struct buffer_head *) * groups_per_page;
850 bh = kzalloc(i, gfp);
858 first_group = page->index * blocks_per_page / 2;
860 /* read all groups the page covers into the cache */
861 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
862 if (group >= ngroups)
865 grinfo = ext4_get_group_info(sb, group);
867 * If page is uptodate then we came here after online resize
868 * which added some new uninitialized group info structs, so
869 * we must skip all initialized uptodate buddies on the page,
870 * which may be currently in use by an allocating task.
872 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
876 bh[i] = ext4_read_block_bitmap_nowait(sb, group);
878 err = PTR_ERR(bh[i]);
882 mb_debug(1, "read bitmap for group %u\n", group);
885 /* wait for I/O completion */
886 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
891 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
896 first_block = page->index * blocks_per_page;
897 for (i = 0; i < blocks_per_page; i++) {
898 group = (first_block + i) >> 1;
899 if (group >= ngroups)
902 if (!bh[group - first_group])
903 /* skip initialized uptodate buddy */
906 if (!buffer_verified(bh[group - first_group]))
907 /* Skip faulty bitmaps */
912 * data carry information regarding this
913 * particular group in the format specified
917 data = page_address(page) + (i * blocksize);
918 bitmap = bh[group - first_group]->b_data;
921 * We place the buddy block and bitmap block
924 if ((first_block + i) & 1) {
925 /* this is block of buddy */
926 BUG_ON(incore == NULL);
927 mb_debug(1, "put buddy for group %u in page %lu/%x\n",
928 group, page->index, i * blocksize);
929 trace_ext4_mb_buddy_bitmap_load(sb, group);
930 grinfo = ext4_get_group_info(sb, group);
931 grinfo->bb_fragments = 0;
932 memset(grinfo->bb_counters, 0,
933 sizeof(*grinfo->bb_counters) *
934 (sb->s_blocksize_bits+2));
936 * incore got set to the group block bitmap below
938 ext4_lock_group(sb, group);
940 memset(data, 0xff, blocksize);
941 ext4_mb_generate_buddy(sb, data, incore, group);
942 ext4_unlock_group(sb, group);
945 /* this is block of bitmap */
946 BUG_ON(incore != NULL);
947 mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
948 group, page->index, i * blocksize);
949 trace_ext4_mb_bitmap_load(sb, group);
951 /* see comments in ext4_mb_put_pa() */
952 ext4_lock_group(sb, group);
953 memcpy(data, bitmap, blocksize);
955 /* mark all preallocated blks used in in-core bitmap */
956 ext4_mb_generate_from_pa(sb, data, group);
957 ext4_mb_generate_from_freelist(sb, data, group);
958 ext4_unlock_group(sb, group);
960 /* set incore so that the buddy information can be
961 * generated using this
966 SetPageUptodate(page);
970 for (i = 0; i < groups_per_page; i++)
979 * Lock the buddy and bitmap pages. This make sure other parallel init_group
980 * on the same buddy page doesn't happen whild holding the buddy page lock.
981 * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
982 * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
984 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
985 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
987 struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
988 int block, pnum, poff;
992 e4b->bd_buddy_page = NULL;
993 e4b->bd_bitmap_page = NULL;
995 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
997 * the buddy cache inode stores the block bitmap
998 * and buddy information in consecutive blocks.
999 * So for each group we need two blocks.
1002 pnum = block / blocks_per_page;
1003 poff = block % blocks_per_page;
1004 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1007 BUG_ON(page->mapping != inode->i_mapping);
1008 e4b->bd_bitmap_page = page;
1009 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1011 if (blocks_per_page >= 2) {
1012 /* buddy and bitmap are on the same page */
1017 pnum = block / blocks_per_page;
1018 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1021 BUG_ON(page->mapping != inode->i_mapping);
1022 e4b->bd_buddy_page = page;
1026 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1028 if (e4b->bd_bitmap_page) {
1029 unlock_page(e4b->bd_bitmap_page);
1030 put_page(e4b->bd_bitmap_page);
1032 if (e4b->bd_buddy_page) {
1033 unlock_page(e4b->bd_buddy_page);
1034 put_page(e4b->bd_buddy_page);
1039 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1040 * block group lock of all groups for this page; do not hold the BG lock when
1041 * calling this routine!
1043 static noinline_for_stack
1044 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1047 struct ext4_group_info *this_grp;
1048 struct ext4_buddy e4b;
1053 mb_debug(1, "init group %u\n", group);
1054 this_grp = ext4_get_group_info(sb, group);
1056 * This ensures that we don't reinit the buddy cache
1057 * page which map to the group from which we are already
1058 * allocating. If we are looking at the buddy cache we would
1059 * have taken a reference using ext4_mb_load_buddy and that
1060 * would have pinned buddy page to page cache.
1061 * The call to ext4_mb_get_buddy_page_lock will mark the
1064 ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1065 if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1067 * somebody initialized the group
1068 * return without doing anything
1073 page = e4b.bd_bitmap_page;
1074 ret = ext4_mb_init_cache(page, NULL, gfp);
1077 if (!PageUptodate(page)) {
1082 if (e4b.bd_buddy_page == NULL) {
1084 * If both the bitmap and buddy are in
1085 * the same page we don't need to force
1091 /* init buddy cache */
1092 page = e4b.bd_buddy_page;
1093 ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1096 if (!PageUptodate(page)) {
1101 ext4_mb_put_buddy_page_lock(&e4b);
1106 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1107 * block group lock of all groups for this page; do not hold the BG lock when
1108 * calling this routine!
1110 static noinline_for_stack int
1111 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1112 struct ext4_buddy *e4b, gfp_t gfp)
1114 int blocks_per_page;
1120 struct ext4_group_info *grp;
1121 struct ext4_sb_info *sbi = EXT4_SB(sb);
1122 struct inode *inode = sbi->s_buddy_cache;
1125 mb_debug(1, "load group %u\n", group);
1127 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1128 grp = ext4_get_group_info(sb, group);
1130 e4b->bd_blkbits = sb->s_blocksize_bits;
1133 e4b->bd_group = group;
1134 e4b->bd_buddy_page = NULL;
1135 e4b->bd_bitmap_page = NULL;
1137 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1139 * we need full data about the group
1140 * to make a good selection
1142 ret = ext4_mb_init_group(sb, group, gfp);
1148 * the buddy cache inode stores the block bitmap
1149 * and buddy information in consecutive blocks.
1150 * So for each group we need two blocks.
1153 pnum = block / blocks_per_page;
1154 poff = block % blocks_per_page;
1156 /* we could use find_or_create_page(), but it locks page
1157 * what we'd like to avoid in fast path ... */
1158 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1159 if (page == NULL || !PageUptodate(page)) {
1162 * drop the page reference and try
1163 * to get the page with lock. If we
1164 * are not uptodate that implies
1165 * somebody just created the page but
1166 * is yet to initialize the same. So
1167 * wait for it to initialize.
1170 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1172 BUG_ON(page->mapping != inode->i_mapping);
1173 if (!PageUptodate(page)) {
1174 ret = ext4_mb_init_cache(page, NULL, gfp);
1179 mb_cmp_bitmaps(e4b, page_address(page) +
1180 (poff * sb->s_blocksize));
1189 if (!PageUptodate(page)) {
1194 /* Pages marked accessed already */
1195 e4b->bd_bitmap_page = page;
1196 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1199 pnum = block / blocks_per_page;
1200 poff = block % blocks_per_page;
1202 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1203 if (page == NULL || !PageUptodate(page)) {
1206 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1208 BUG_ON(page->mapping != inode->i_mapping);
1209 if (!PageUptodate(page)) {
1210 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1224 if (!PageUptodate(page)) {
1229 /* Pages marked accessed already */
1230 e4b->bd_buddy_page = page;
1231 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1233 BUG_ON(e4b->bd_bitmap_page == NULL);
1234 BUG_ON(e4b->bd_buddy_page == NULL);
1241 if (e4b->bd_bitmap_page)
1242 put_page(e4b->bd_bitmap_page);
1243 if (e4b->bd_buddy_page)
1244 put_page(e4b->bd_buddy_page);
1245 e4b->bd_buddy = NULL;
1246 e4b->bd_bitmap = NULL;
1250 static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1251 struct ext4_buddy *e4b)
1253 return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1256 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1258 if (e4b->bd_bitmap_page)
1259 put_page(e4b->bd_bitmap_page);
1260 if (e4b->bd_buddy_page)
1261 put_page(e4b->bd_buddy_page);
1265 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1268 int bb_incr = 1 << (e4b->bd_blkbits - 1);
1271 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1272 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1275 while (order <= e4b->bd_blkbits + 1) {
1277 if (!mb_test_bit(block, bb)) {
1278 /* this block is part of buddy of order 'order' */
1288 static void mb_clear_bits(void *bm, int cur, int len)
1294 if ((cur & 31) == 0 && (len - cur) >= 32) {
1295 /* fast path: clear whole word at once */
1296 addr = bm + (cur >> 3);
1301 mb_clear_bit(cur, bm);
1306 /* clear bits in given range
1307 * will return first found zero bit if any, -1 otherwise
1309 static int mb_test_and_clear_bits(void *bm, int cur, int len)
1316 if ((cur & 31) == 0 && (len - cur) >= 32) {
1317 /* fast path: clear whole word at once */
1318 addr = bm + (cur >> 3);
1319 if (*addr != (__u32)(-1) && zero_bit == -1)
1320 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1325 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1333 void ext4_set_bits(void *bm, int cur, int len)
1339 if ((cur & 31) == 0 && (len - cur) >= 32) {
1340 /* fast path: set whole word at once */
1341 addr = bm + (cur >> 3);
1346 mb_set_bit(cur, bm);
1352 * _________________________________________________________________ */
1354 static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1356 if (mb_test_bit(*bit + side, bitmap)) {
1357 mb_clear_bit(*bit, bitmap);
1363 mb_set_bit(*bit, bitmap);
1368 static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1372 void *buddy = mb_find_buddy(e4b, order, &max);
1377 /* Bits in range [first; last] are known to be set since
1378 * corresponding blocks were allocated. Bits in range
1379 * (first; last) will stay set because they form buddies on
1380 * upper layer. We just deal with borders if they don't
1381 * align with upper layer and then go up.
1382 * Releasing entire group is all about clearing
1383 * single bit of highest order buddy.
1387 * ---------------------------------
1389 * ---------------------------------
1390 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1391 * ---------------------------------
1393 * \_____________________/
1395 * Neither [1] nor [6] is aligned to above layer.
1396 * Left neighbour [0] is free, so mark it busy,
1397 * decrease bb_counters and extend range to
1399 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1400 * mark [6] free, increase bb_counters and shrink range to
1402 * Then shift range to [0; 2], go up and do the same.
1407 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1409 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1414 if (first == last || !(buddy2 = mb_find_buddy(e4b, order, &max))) {
1415 mb_clear_bits(buddy, first, last - first + 1);
1416 e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1425 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1426 int first, int count)
1428 int left_is_free = 0;
1429 int right_is_free = 0;
1431 int last = first + count - 1;
1432 struct super_block *sb = e4b->bd_sb;
1434 if (WARN_ON(count == 0))
1436 BUG_ON(last >= (sb->s_blocksize << 3));
1437 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1438 /* Don't bother if the block group is corrupt. */
1439 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1442 mb_check_buddy(e4b);
1443 mb_free_blocks_double(inode, e4b, first, count);
1445 e4b->bd_info->bb_free += count;
1446 if (first < e4b->bd_info->bb_first_free)
1447 e4b->bd_info->bb_first_free = first;
1449 /* access memory sequentially: check left neighbour,
1450 * clear range and then check right neighbour
1453 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1454 block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1455 if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1456 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1458 if (unlikely(block != -1)) {
1459 struct ext4_sb_info *sbi = EXT4_SB(sb);
1460 ext4_fsblk_t blocknr;
1462 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1463 blocknr += EXT4_C2B(EXT4_SB(sb), block);
1464 ext4_grp_locked_error(sb, e4b->bd_group,
1465 inode ? inode->i_ino : 0,
1467 "freeing already freed block "
1468 "(bit %u); block bitmap corrupt.",
1470 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))
1471 percpu_counter_sub(&sbi->s_freeclusters_counter,
1472 e4b->bd_info->bb_free);
1473 /* Mark the block group as corrupt. */
1474 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT,
1475 &e4b->bd_info->bb_state);
1476 mb_regenerate_buddy(e4b);
1480 /* let's maintain fragments counter */
1481 if (left_is_free && right_is_free)
1482 e4b->bd_info->bb_fragments--;
1483 else if (!left_is_free && !right_is_free)
1484 e4b->bd_info->bb_fragments++;
1486 /* buddy[0] == bd_bitmap is a special case, so handle
1487 * it right away and let mb_buddy_mark_free stay free of
1488 * zero order checks.
1489 * Check if neighbours are to be coaleasced,
1490 * adjust bitmap bb_counters and borders appropriately.
1493 first += !left_is_free;
1494 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1497 last -= !right_is_free;
1498 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1502 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1505 mb_set_largest_free_order(sb, e4b->bd_info);
1506 mb_check_buddy(e4b);
1509 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1510 int needed, struct ext4_free_extent *ex)
1516 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1519 buddy = mb_find_buddy(e4b, 0, &max);
1520 BUG_ON(buddy == NULL);
1521 BUG_ON(block >= max);
1522 if (mb_test_bit(block, buddy)) {
1529 /* find actual order */
1530 order = mb_find_order_for_block(e4b, block);
1531 block = block >> order;
1533 ex->fe_len = 1 << order;
1534 ex->fe_start = block << order;
1535 ex->fe_group = e4b->bd_group;
1537 /* calc difference from given start */
1538 next = next - ex->fe_start;
1540 ex->fe_start += next;
1542 while (needed > ex->fe_len &&
1543 mb_find_buddy(e4b, order, &max)) {
1545 if (block + 1 >= max)
1548 next = (block + 1) * (1 << order);
1549 if (mb_test_bit(next, e4b->bd_bitmap))
1552 order = mb_find_order_for_block(e4b, next);
1554 block = next >> order;
1555 ex->fe_len += 1 << order;
1558 if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
1559 /* Should never happen! (but apparently sometimes does?!?) */
1561 ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
1562 "corruption or bug in mb_find_extent "
1563 "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
1564 block, order, needed, ex->fe_group, ex->fe_start,
1565 ex->fe_len, ex->fe_logical);
1573 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1579 int start = ex->fe_start;
1580 int len = ex->fe_len;
1585 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1586 BUG_ON(e4b->bd_group != ex->fe_group);
1587 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1588 mb_check_buddy(e4b);
1589 mb_mark_used_double(e4b, start, len);
1591 e4b->bd_info->bb_free -= len;
1592 if (e4b->bd_info->bb_first_free == start)
1593 e4b->bd_info->bb_first_free += len;
1595 /* let's maintain fragments counter */
1597 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1598 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1599 max = !mb_test_bit(start + len, e4b->bd_bitmap);
1601 e4b->bd_info->bb_fragments++;
1602 else if (!mlen && !max)
1603 e4b->bd_info->bb_fragments--;
1605 /* let's maintain buddy itself */
1607 ord = mb_find_order_for_block(e4b, start);
1609 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1610 /* the whole chunk may be allocated at once! */
1612 buddy = mb_find_buddy(e4b, ord, &max);
1613 BUG_ON((start >> ord) >= max);
1614 mb_set_bit(start >> ord, buddy);
1615 e4b->bd_info->bb_counters[ord]--;
1622 /* store for history */
1624 ret = len | (ord << 16);
1626 /* we have to split large buddy */
1628 buddy = mb_find_buddy(e4b, ord, &max);
1629 mb_set_bit(start >> ord, buddy);
1630 e4b->bd_info->bb_counters[ord]--;
1633 cur = (start >> ord) & ~1U;
1634 buddy = mb_find_buddy(e4b, ord, &max);
1635 mb_clear_bit(cur, buddy);
1636 mb_clear_bit(cur + 1, buddy);
1637 e4b->bd_info->bb_counters[ord]++;
1638 e4b->bd_info->bb_counters[ord]++;
1640 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1642 ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1643 mb_check_buddy(e4b);
1649 * Must be called under group lock!
1651 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1652 struct ext4_buddy *e4b)
1654 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1657 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1658 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1660 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1661 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1662 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1664 /* preallocation can change ac_b_ex, thus we store actually
1665 * allocated blocks for history */
1666 ac->ac_f_ex = ac->ac_b_ex;
1668 ac->ac_status = AC_STATUS_FOUND;
1669 ac->ac_tail = ret & 0xffff;
1670 ac->ac_buddy = ret >> 16;
1673 * take the page reference. We want the page to be pinned
1674 * so that we don't get a ext4_mb_init_cache_call for this
1675 * group until we update the bitmap. That would mean we
1676 * double allocate blocks. The reference is dropped
1677 * in ext4_mb_release_context
1679 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1680 get_page(ac->ac_bitmap_page);
1681 ac->ac_buddy_page = e4b->bd_buddy_page;
1682 get_page(ac->ac_buddy_page);
1683 /* store last allocated for subsequent stream allocation */
1684 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1685 spin_lock(&sbi->s_md_lock);
1686 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1687 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1688 spin_unlock(&sbi->s_md_lock);
1693 * regular allocator, for general purposes allocation
1696 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1697 struct ext4_buddy *e4b,
1700 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1701 struct ext4_free_extent *bex = &ac->ac_b_ex;
1702 struct ext4_free_extent *gex = &ac->ac_g_ex;
1703 struct ext4_free_extent ex;
1706 if (ac->ac_status == AC_STATUS_FOUND)
1709 * We don't want to scan for a whole year
1711 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1712 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1713 ac->ac_status = AC_STATUS_BREAK;
1718 * Haven't found good chunk so far, let's continue
1720 if (bex->fe_len < gex->fe_len)
1723 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1724 && bex->fe_group == e4b->bd_group) {
1725 /* recheck chunk's availability - we don't know
1726 * when it was found (within this lock-unlock
1728 max = mb_find_extent(e4b, bex->fe_start, gex->fe_len, &ex);
1729 if (max >= gex->fe_len) {
1730 ext4_mb_use_best_found(ac, e4b);
1737 * The routine checks whether found extent is good enough. If it is,
1738 * then the extent gets marked used and flag is set to the context
1739 * to stop scanning. Otherwise, the extent is compared with the
1740 * previous found extent and if new one is better, then it's stored
1741 * in the context. Later, the best found extent will be used, if
1742 * mballoc can't find good enough extent.
1744 * FIXME: real allocation policy is to be designed yet!
1746 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1747 struct ext4_free_extent *ex,
1748 struct ext4_buddy *e4b)
1750 struct ext4_free_extent *bex = &ac->ac_b_ex;
1751 struct ext4_free_extent *gex = &ac->ac_g_ex;
1753 BUG_ON(ex->fe_len <= 0);
1754 BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1755 BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1756 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1761 * The special case - take what you catch first
1763 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1765 ext4_mb_use_best_found(ac, e4b);
1770 * Let's check whether the chuck is good enough
1772 if (ex->fe_len == gex->fe_len) {
1774 ext4_mb_use_best_found(ac, e4b);
1779 * If this is first found extent, just store it in the context
1781 if (bex->fe_len == 0) {
1787 * If new found extent is better, store it in the context
1789 if (bex->fe_len < gex->fe_len) {
1790 /* if the request isn't satisfied, any found extent
1791 * larger than previous best one is better */
1792 if (ex->fe_len > bex->fe_len)
1794 } else if (ex->fe_len > gex->fe_len) {
1795 /* if the request is satisfied, then we try to find
1796 * an extent that still satisfy the request, but is
1797 * smaller than previous one */
1798 if (ex->fe_len < bex->fe_len)
1802 ext4_mb_check_limits(ac, e4b, 0);
1805 static noinline_for_stack
1806 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1807 struct ext4_buddy *e4b)
1809 struct ext4_free_extent ex = ac->ac_b_ex;
1810 ext4_group_t group = ex.fe_group;
1814 BUG_ON(ex.fe_len <= 0);
1815 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1819 ext4_lock_group(ac->ac_sb, group);
1820 max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
1824 ext4_mb_use_best_found(ac, e4b);
1827 ext4_unlock_group(ac->ac_sb, group);
1828 ext4_mb_unload_buddy(e4b);
1833 static noinline_for_stack
1834 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1835 struct ext4_buddy *e4b)
1837 ext4_group_t group = ac->ac_g_ex.fe_group;
1840 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1841 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1842 struct ext4_free_extent ex;
1844 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1846 if (grp->bb_free == 0)
1849 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1853 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
1854 ext4_mb_unload_buddy(e4b);
1858 ext4_lock_group(ac->ac_sb, group);
1859 max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
1860 ac->ac_g_ex.fe_len, &ex);
1861 ex.fe_logical = 0xDEADFA11; /* debug value */
1863 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1866 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
1868 /* use do_div to get remainder (would be 64-bit modulo) */
1869 if (do_div(start, sbi->s_stripe) == 0) {
1872 ext4_mb_use_best_found(ac, e4b);
1874 } else if (max >= ac->ac_g_ex.fe_len) {
1875 BUG_ON(ex.fe_len <= 0);
1876 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1877 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1880 ext4_mb_use_best_found(ac, e4b);
1881 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1882 /* Sometimes, caller may want to merge even small
1883 * number of blocks to an existing extent */
1884 BUG_ON(ex.fe_len <= 0);
1885 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1886 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1889 ext4_mb_use_best_found(ac, e4b);
1891 ext4_unlock_group(ac->ac_sb, group);
1892 ext4_mb_unload_buddy(e4b);
1898 * The routine scans buddy structures (not bitmap!) from given order
1899 * to max order and tries to find big enough chunk to satisfy the req
1901 static noinline_for_stack
1902 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1903 struct ext4_buddy *e4b)
1905 struct super_block *sb = ac->ac_sb;
1906 struct ext4_group_info *grp = e4b->bd_info;
1912 BUG_ON(ac->ac_2order <= 0);
1913 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1914 if (grp->bb_counters[i] == 0)
1917 buddy = mb_find_buddy(e4b, i, &max);
1918 BUG_ON(buddy == NULL);
1920 k = mb_find_next_zero_bit(buddy, max, 0);
1925 ac->ac_b_ex.fe_len = 1 << i;
1926 ac->ac_b_ex.fe_start = k << i;
1927 ac->ac_b_ex.fe_group = e4b->bd_group;
1929 ext4_mb_use_best_found(ac, e4b);
1931 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1933 if (EXT4_SB(sb)->s_mb_stats)
1934 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1941 * The routine scans the group and measures all found extents.
1942 * In order to optimize scanning, caller must pass number of
1943 * free blocks in the group, so the routine can know upper limit.
1945 static noinline_for_stack
1946 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1947 struct ext4_buddy *e4b)
1949 struct super_block *sb = ac->ac_sb;
1950 void *bitmap = e4b->bd_bitmap;
1951 struct ext4_free_extent ex;
1955 free = e4b->bd_info->bb_free;
1956 if (WARN_ON(free <= 0))
1959 i = e4b->bd_info->bb_first_free;
1961 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1962 i = mb_find_next_zero_bit(bitmap,
1963 EXT4_CLUSTERS_PER_GROUP(sb), i);
1964 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
1966 * IF we have corrupt bitmap, we won't find any
1967 * free blocks even though group info says we
1968 * we have free blocks
1970 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1971 "%d free clusters as per "
1972 "group info. But bitmap says 0",
1977 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
1978 if (WARN_ON(ex.fe_len <= 0))
1980 if (free < ex.fe_len) {
1981 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1982 "%d free clusters as per "
1983 "group info. But got %d blocks",
1986 * The number of free blocks differs. This mostly
1987 * indicate that the bitmap is corrupt. So exit
1988 * without claiming the space.
1992 ex.fe_logical = 0xDEADC0DE; /* debug value */
1993 ext4_mb_measure_extent(ac, &ex, e4b);
1999 ext4_mb_check_limits(ac, e4b, 1);
2003 * This is a special case for storages like raid5
2004 * we try to find stripe-aligned chunks for stripe-size-multiple requests
2006 static noinline_for_stack
2007 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2008 struct ext4_buddy *e4b)
2010 struct super_block *sb = ac->ac_sb;
2011 struct ext4_sb_info *sbi = EXT4_SB(sb);
2012 void *bitmap = e4b->bd_bitmap;
2013 struct ext4_free_extent ex;
2014 ext4_fsblk_t first_group_block;
2019 BUG_ON(sbi->s_stripe == 0);
2021 /* find first stripe-aligned block in group */
2022 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2024 a = first_group_block + sbi->s_stripe - 1;
2025 do_div(a, sbi->s_stripe);
2026 i = (a * sbi->s_stripe) - first_group_block;
2028 while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2029 if (!mb_test_bit(i, bitmap)) {
2030 max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
2031 if (max >= sbi->s_stripe) {
2033 ex.fe_logical = 0xDEADF00D; /* debug value */
2035 ext4_mb_use_best_found(ac, e4b);
2044 * This is now called BEFORE we load the buddy bitmap.
2045 * Returns either 1 or 0 indicating that the group is either suitable
2046 * for the allocation or not. In addition it can also return negative
2047 * error code when something goes wrong.
2049 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
2050 ext4_group_t group, int cr)
2052 unsigned free, fragments;
2053 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2054 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2056 BUG_ON(cr < 0 || cr >= 4);
2058 free = grp->bb_free;
2061 if (cr <= 2 && free < ac->ac_g_ex.fe_len)
2064 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2067 /* We only do this if the grp has never been initialized */
2068 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2069 int ret = ext4_mb_init_group(ac->ac_sb, group, GFP_NOFS);
2074 fragments = grp->bb_fragments;
2080 BUG_ON(ac->ac_2order == 0);
2082 /* Avoid using the first bg of a flexgroup for data files */
2083 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2084 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2085 ((group % flex_size) == 0))
2088 if ((ac->ac_2order > ac->ac_sb->s_blocksize_bits+1) ||
2089 (free / fragments) >= ac->ac_g_ex.fe_len)
2092 if (grp->bb_largest_free_order < ac->ac_2order)
2097 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2101 if (free >= ac->ac_g_ex.fe_len)
2113 static noinline_for_stack int
2114 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2116 ext4_group_t ngroups, group, i;
2118 int err = 0, first_err = 0;
2119 struct ext4_sb_info *sbi;
2120 struct super_block *sb;
2121 struct ext4_buddy e4b;
2125 ngroups = ext4_get_groups_count(sb);
2126 /* non-extent files are limited to low blocks/groups */
2127 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2128 ngroups = sbi->s_blockfile_groups;
2130 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2132 /* first, try the goal */
2133 err = ext4_mb_find_by_goal(ac, &e4b);
2134 if (err || ac->ac_status == AC_STATUS_FOUND)
2137 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2141 * ac->ac2_order is set only if the fe_len is a power of 2
2142 * if ac2_order is set we also set criteria to 0 so that we
2143 * try exact allocation using buddy.
2145 i = fls(ac->ac_g_ex.fe_len);
2148 * We search using buddy data only if the order of the request
2149 * is greater than equal to the sbi_s_mb_order2_reqs
2150 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2151 * We also support searching for power-of-two requests only for
2152 * requests upto maximum buddy size we have constructed.
2154 if (i >= sbi->s_mb_order2_reqs && i <= sb->s_blocksize_bits + 2) {
2156 * This should tell if fe_len is exactly power of 2
2158 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2159 ac->ac_2order = array_index_nospec(i - 1,
2160 sb->s_blocksize_bits + 2);
2163 /* if stream allocation is enabled, use global goal */
2164 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2165 /* TBD: may be hot point */
2166 spin_lock(&sbi->s_md_lock);
2167 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2168 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2169 spin_unlock(&sbi->s_md_lock);
2172 /* Let's just scan groups to find more-less suitable blocks */
2173 cr = ac->ac_2order ? 0 : 1;
2175 * cr == 0 try to get exact allocation,
2176 * cr == 3 try to get anything
2179 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2180 ac->ac_criteria = cr;
2182 * searching for the right group start
2183 * from the goal value specified
2185 group = ac->ac_g_ex.fe_group;
2187 for (i = 0; i < ngroups; group++, i++) {
2191 * Artificially restricted ngroups for non-extent
2192 * files makes group > ngroups possible on first loop.
2194 if (group >= ngroups)
2197 /* This now checks without needing the buddy page */
2198 ret = ext4_mb_good_group(ac, group, cr);
2205 err = ext4_mb_load_buddy(sb, group, &e4b);
2209 ext4_lock_group(sb, group);
2212 * We need to check again after locking the
2215 ret = ext4_mb_good_group(ac, group, cr);
2217 ext4_unlock_group(sb, group);
2218 ext4_mb_unload_buddy(&e4b);
2224 ac->ac_groups_scanned++;
2226 ext4_mb_simple_scan_group(ac, &e4b);
2227 else if (cr == 1 && sbi->s_stripe &&
2228 !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2229 ext4_mb_scan_aligned(ac, &e4b);
2231 ext4_mb_complex_scan_group(ac, &e4b);
2233 ext4_unlock_group(sb, group);
2234 ext4_mb_unload_buddy(&e4b);
2236 if (ac->ac_status != AC_STATUS_CONTINUE)
2241 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2242 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2244 * We've been searching too long. Let's try to allocate
2245 * the best chunk we've found so far
2248 ext4_mb_try_best_found(ac, &e4b);
2249 if (ac->ac_status != AC_STATUS_FOUND) {
2251 * Someone more lucky has already allocated it.
2252 * The only thing we can do is just take first
2254 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2256 ac->ac_b_ex.fe_group = 0;
2257 ac->ac_b_ex.fe_start = 0;
2258 ac->ac_b_ex.fe_len = 0;
2259 ac->ac_status = AC_STATUS_CONTINUE;
2260 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2262 atomic_inc(&sbi->s_mb_lost_chunks);
2267 if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2272 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2274 struct super_block *sb = seq->private;
2277 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2280 return (void *) ((unsigned long) group);
2283 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2285 struct super_block *sb = seq->private;
2289 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2292 return (void *) ((unsigned long) group);
2295 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2297 struct super_block *sb = seq->private;
2298 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2300 int err, buddy_loaded = 0;
2301 struct ext4_buddy e4b;
2302 struct ext4_group_info *grinfo;
2303 unsigned char blocksize_bits = min_t(unsigned char,
2304 sb->s_blocksize_bits,
2305 EXT4_MAX_BLOCK_LOG_SIZE);
2307 struct ext4_group_info info;
2308 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
2313 seq_puts(seq, "#group: free frags first ["
2314 " 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
2315 " 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
2317 i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2318 sizeof(struct ext4_group_info);
2320 grinfo = ext4_get_group_info(sb, group);
2321 /* Load the group info in memory only if not already loaded. */
2322 if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
2323 err = ext4_mb_load_buddy(sb, group, &e4b);
2325 seq_printf(seq, "#%-5u: I/O error\n", group);
2331 memcpy(&sg, ext4_get_group_info(sb, group), i);
2334 ext4_mb_unload_buddy(&e4b);
2336 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2337 sg.info.bb_fragments, sg.info.bb_first_free);
2338 for (i = 0; i <= 13; i++)
2339 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
2340 sg.info.bb_counters[i] : 0);
2341 seq_printf(seq, " ]\n");
2346 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2350 static const struct seq_operations ext4_mb_seq_groups_ops = {
2351 .start = ext4_mb_seq_groups_start,
2352 .next = ext4_mb_seq_groups_next,
2353 .stop = ext4_mb_seq_groups_stop,
2354 .show = ext4_mb_seq_groups_show,
2357 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2359 struct super_block *sb = PDE_DATA(inode);
2362 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2364 struct seq_file *m = file->private_data;
2371 const struct file_operations ext4_seq_mb_groups_fops = {
2372 .open = ext4_mb_seq_groups_open,
2374 .llseek = seq_lseek,
2375 .release = seq_release,
2378 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2380 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2381 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2388 * Allocate the top-level s_group_info array for the specified number
2391 int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
2393 struct ext4_sb_info *sbi = EXT4_SB(sb);
2395 struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
2397 size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
2398 EXT4_DESC_PER_BLOCK_BITS(sb);
2399 if (size <= sbi->s_group_info_size)
2402 size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
2403 new_groupinfo = kvzalloc(size, GFP_KERNEL);
2404 if (!new_groupinfo) {
2405 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
2409 old_groupinfo = rcu_dereference(sbi->s_group_info);
2411 memcpy(new_groupinfo, old_groupinfo,
2412 sbi->s_group_info_size * sizeof(*sbi->s_group_info));
2414 rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
2415 sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
2417 ext4_kvfree_array_rcu(old_groupinfo);
2418 ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
2419 sbi->s_group_info_size);
2423 /* Create and initialize ext4_group_info data for the given group. */
2424 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2425 struct ext4_group_desc *desc)
2429 int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
2430 struct ext4_sb_info *sbi = EXT4_SB(sb);
2431 struct ext4_group_info **meta_group_info;
2432 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2435 * First check if this group is the first of a reserved block.
2436 * If it's true, we have to allocate a new table of pointers
2437 * to ext4_group_info structures
2439 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2440 metalen = sizeof(*meta_group_info) <<
2441 EXT4_DESC_PER_BLOCK_BITS(sb);
2442 meta_group_info = kmalloc(metalen, GFP_NOFS);
2443 if (meta_group_info == NULL) {
2444 ext4_msg(sb, KERN_ERR, "can't allocate mem "
2445 "for a buddy group");
2446 goto exit_meta_group_info;
2449 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
2453 meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
2454 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2456 meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
2457 if (meta_group_info[i] == NULL) {
2458 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
2459 goto exit_group_info;
2461 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2462 &(meta_group_info[i]->bb_state));
2465 * initialize bb_free to be able to skip
2466 * empty groups without initialization
2468 if (ext4_has_group_desc_csum(sb) &&
2469 (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
2470 meta_group_info[i]->bb_free =
2471 ext4_free_clusters_after_init(sb, group, desc);
2473 meta_group_info[i]->bb_free =
2474 ext4_free_group_clusters(sb, desc);
2477 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2478 init_rwsem(&meta_group_info[i]->alloc_sem);
2479 meta_group_info[i]->bb_free_root = RB_ROOT;
2480 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
2484 struct buffer_head *bh;
2485 meta_group_info[i]->bb_bitmap =
2486 kmalloc(sb->s_blocksize, GFP_NOFS);
2487 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2488 bh = ext4_read_block_bitmap(sb, group);
2489 BUG_ON(IS_ERR_OR_NULL(bh));
2490 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2499 /* If a meta_group_info table has been allocated, release it now */
2500 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2501 struct ext4_group_info ***group_info;
2504 group_info = rcu_dereference(sbi->s_group_info);
2505 kfree(group_info[idx]);
2506 group_info[idx] = NULL;
2509 exit_meta_group_info:
2511 } /* ext4_mb_add_groupinfo */
2513 static int ext4_mb_init_backend(struct super_block *sb)
2515 ext4_group_t ngroups = ext4_get_groups_count(sb);
2517 struct ext4_sb_info *sbi = EXT4_SB(sb);
2519 struct ext4_group_desc *desc;
2520 struct ext4_group_info ***group_info;
2521 struct kmem_cache *cachep;
2523 err = ext4_mb_alloc_groupinfo(sb, ngroups);
2527 sbi->s_buddy_cache = new_inode(sb);
2528 if (sbi->s_buddy_cache == NULL) {
2529 ext4_msg(sb, KERN_ERR, "can't get new inode");
2532 /* To avoid potentially colliding with an valid on-disk inode number,
2533 * use EXT4_BAD_INO for the buddy cache inode number. This inode is
2534 * not in the inode hash, so it should never be found by iget(), but
2535 * this will avoid confusion if it ever shows up during debugging. */
2536 sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
2537 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2538 for (i = 0; i < ngroups; i++) {
2539 desc = ext4_get_group_desc(sb, i, NULL);
2541 ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2544 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2551 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2553 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2554 i = sbi->s_group_info_size;
2556 group_info = rcu_dereference(sbi->s_group_info);
2558 kfree(group_info[i]);
2560 iput(sbi->s_buddy_cache);
2563 kvfree(rcu_dereference(sbi->s_group_info));
2568 static void ext4_groupinfo_destroy_slabs(void)
2572 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
2573 if (ext4_groupinfo_caches[i])
2574 kmem_cache_destroy(ext4_groupinfo_caches[i]);
2575 ext4_groupinfo_caches[i] = NULL;
2579 static int ext4_groupinfo_create_slab(size_t size)
2581 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
2583 int blocksize_bits = order_base_2(size);
2584 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2585 struct kmem_cache *cachep;
2587 if (cache_index >= NR_GRPINFO_CACHES)
2590 if (unlikely(cache_index < 0))
2593 mutex_lock(&ext4_grpinfo_slab_create_mutex);
2594 if (ext4_groupinfo_caches[cache_index]) {
2595 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2596 return 0; /* Already created */
2599 slab_size = offsetof(struct ext4_group_info,
2600 bb_counters[blocksize_bits + 2]);
2602 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
2603 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
2606 ext4_groupinfo_caches[cache_index] = cachep;
2608 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2611 "EXT4-fs: no memory for groupinfo slab cache\n");
2618 int ext4_mb_init(struct super_block *sb)
2620 struct ext4_sb_info *sbi = EXT4_SB(sb);
2622 unsigned offset, offset_incr;
2626 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2628 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2629 if (sbi->s_mb_offsets == NULL) {
2634 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2635 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2636 if (sbi->s_mb_maxs == NULL) {
2641 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2645 /* order 0 is regular bitmap */
2646 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2647 sbi->s_mb_offsets[0] = 0;
2651 offset_incr = 1 << (sb->s_blocksize_bits - 1);
2652 max = sb->s_blocksize << 2;
2654 sbi->s_mb_offsets[i] = offset;
2655 sbi->s_mb_maxs[i] = max;
2656 offset += offset_incr;
2657 offset_incr = offset_incr >> 1;
2660 } while (i <= sb->s_blocksize_bits + 1);
2662 spin_lock_init(&sbi->s_md_lock);
2663 spin_lock_init(&sbi->s_bal_lock);
2664 sbi->s_mb_free_pending = 0;
2665 INIT_LIST_HEAD(&sbi->s_freed_data_list);
2667 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2668 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2669 sbi->s_mb_stats = MB_DEFAULT_STATS;
2670 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2671 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2673 * The default group preallocation is 512, which for 4k block
2674 * sizes translates to 2 megabytes. However for bigalloc file
2675 * systems, this is probably too big (i.e, if the cluster size
2676 * is 1 megabyte, then group preallocation size becomes half a
2677 * gigabyte!). As a default, we will keep a two megabyte
2678 * group pralloc size for cluster sizes up to 64k, and after
2679 * that, we will force a minimum group preallocation size of
2680 * 32 clusters. This translates to 8 megs when the cluster
2681 * size is 256k, and 32 megs when the cluster size is 1 meg,
2682 * which seems reasonable as a default.
2684 sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
2685 sbi->s_cluster_bits, 32);
2687 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
2688 * to the lowest multiple of s_stripe which is bigger than
2689 * the s_mb_group_prealloc as determined above. We want
2690 * the preallocation size to be an exact multiple of the
2691 * RAID stripe size so that preallocations don't fragment
2694 if (sbi->s_stripe > 1) {
2695 sbi->s_mb_group_prealloc = roundup(
2696 sbi->s_mb_group_prealloc, sbi->s_stripe);
2699 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2700 if (sbi->s_locality_groups == NULL) {
2704 for_each_possible_cpu(i) {
2705 struct ext4_locality_group *lg;
2706 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2707 mutex_init(&lg->lg_mutex);
2708 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2709 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2710 spin_lock_init(&lg->lg_prealloc_lock);
2713 /* init file for buddy data */
2714 ret = ext4_mb_init_backend(sb);
2716 goto out_free_locality_groups;
2720 out_free_locality_groups:
2721 free_percpu(sbi->s_locality_groups);
2722 sbi->s_locality_groups = NULL;
2724 kfree(sbi->s_mb_offsets);
2725 sbi->s_mb_offsets = NULL;
2726 kfree(sbi->s_mb_maxs);
2727 sbi->s_mb_maxs = NULL;
2731 /* need to called with the ext4 group lock held */
2732 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2734 struct ext4_prealloc_space *pa;
2735 struct list_head *cur, *tmp;
2738 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2739 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2740 list_del(&pa->pa_group_list);
2742 kmem_cache_free(ext4_pspace_cachep, pa);
2745 mb_debug(1, "mballoc: %u PAs left\n", count);
2749 int ext4_mb_release(struct super_block *sb)
2751 ext4_group_t ngroups = ext4_get_groups_count(sb);
2753 int num_meta_group_infos;
2754 struct ext4_group_info *grinfo, ***group_info;
2755 struct ext4_sb_info *sbi = EXT4_SB(sb);
2756 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2758 if (sbi->s_group_info) {
2759 for (i = 0; i < ngroups; i++) {
2760 grinfo = ext4_get_group_info(sb, i);
2762 kfree(grinfo->bb_bitmap);
2764 ext4_lock_group(sb, i);
2765 ext4_mb_cleanup_pa(grinfo);
2766 ext4_unlock_group(sb, i);
2767 kmem_cache_free(cachep, grinfo);
2769 num_meta_group_infos = (ngroups +
2770 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2771 EXT4_DESC_PER_BLOCK_BITS(sb);
2773 group_info = rcu_dereference(sbi->s_group_info);
2774 for (i = 0; i < num_meta_group_infos; i++)
2775 kfree(group_info[i]);
2779 kfree(sbi->s_mb_offsets);
2780 kfree(sbi->s_mb_maxs);
2781 iput(sbi->s_buddy_cache);
2782 if (sbi->s_mb_stats) {
2783 ext4_msg(sb, KERN_INFO,
2784 "mballoc: %u blocks %u reqs (%u success)",
2785 atomic_read(&sbi->s_bal_allocated),
2786 atomic_read(&sbi->s_bal_reqs),
2787 atomic_read(&sbi->s_bal_success));
2788 ext4_msg(sb, KERN_INFO,
2789 "mballoc: %u extents scanned, %u goal hits, "
2790 "%u 2^N hits, %u breaks, %u lost",
2791 atomic_read(&sbi->s_bal_ex_scanned),
2792 atomic_read(&sbi->s_bal_goals),
2793 atomic_read(&sbi->s_bal_2orders),
2794 atomic_read(&sbi->s_bal_breaks),
2795 atomic_read(&sbi->s_mb_lost_chunks));
2796 ext4_msg(sb, KERN_INFO,
2797 "mballoc: %lu generated and it took %Lu",
2798 sbi->s_mb_buddies_generated,
2799 sbi->s_mb_generation_time);
2800 ext4_msg(sb, KERN_INFO,
2801 "mballoc: %u preallocated, %u discarded",
2802 atomic_read(&sbi->s_mb_preallocated),
2803 atomic_read(&sbi->s_mb_discarded));
2806 free_percpu(sbi->s_locality_groups);
2811 static inline int ext4_issue_discard(struct super_block *sb,
2812 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
2815 ext4_fsblk_t discard_block;
2817 discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
2818 ext4_group_first_block_no(sb, block_group));
2819 count = EXT4_C2B(EXT4_SB(sb), count);
2820 trace_ext4_discard_blocks(sb,
2821 (unsigned long long) discard_block, count);
2823 return __blkdev_issue_discard(sb->s_bdev,
2824 (sector_t)discard_block << (sb->s_blocksize_bits - 9),
2825 (sector_t)count << (sb->s_blocksize_bits - 9),
2828 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
2831 static void ext4_free_data_in_buddy(struct super_block *sb,
2832 struct ext4_free_data *entry)
2834 struct ext4_buddy e4b;
2835 struct ext4_group_info *db;
2836 int err, count = 0, count2 = 0;
2838 mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2839 entry->efd_count, entry->efd_group, entry);
2841 err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
2842 /* we expect to find existing buddy because it's pinned */
2845 spin_lock(&EXT4_SB(sb)->s_md_lock);
2846 EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
2847 spin_unlock(&EXT4_SB(sb)->s_md_lock);
2850 /* there are blocks to put in buddy to make them really free */
2851 count += entry->efd_count;
2853 ext4_lock_group(sb, entry->efd_group);
2854 /* Take it out of per group rb tree */
2855 rb_erase(&entry->efd_node, &(db->bb_free_root));
2856 mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
2859 * Clear the trimmed flag for the group so that the next
2860 * ext4_trim_fs can trim it.
2861 * If the volume is mounted with -o discard, online discard
2862 * is supported and the free blocks will be trimmed online.
2864 if (!test_opt(sb, DISCARD))
2865 EXT4_MB_GRP_CLEAR_TRIMMED(db);
2867 if (!db->bb_free_root.rb_node) {
2868 /* No more items in the per group rb tree
2869 * balance refcounts from ext4_mb_free_metadata()
2871 put_page(e4b.bd_buddy_page);
2872 put_page(e4b.bd_bitmap_page);
2874 ext4_unlock_group(sb, entry->efd_group);
2875 kmem_cache_free(ext4_free_data_cachep, entry);
2876 ext4_mb_unload_buddy(&e4b);
2878 mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2882 * This function is called by the jbd2 layer once the commit has finished,
2883 * so we know we can free the blocks that were released with that commit.
2885 void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
2887 struct ext4_sb_info *sbi = EXT4_SB(sb);
2888 struct ext4_free_data *entry, *tmp;
2889 struct bio *discard_bio = NULL;
2890 struct list_head freed_data_list;
2891 struct list_head *cut_pos = NULL;
2894 INIT_LIST_HEAD(&freed_data_list);
2896 spin_lock(&sbi->s_md_lock);
2897 list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
2898 if (entry->efd_tid != commit_tid)
2900 cut_pos = &entry->efd_list;
2903 list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
2905 spin_unlock(&sbi->s_md_lock);
2907 if (test_opt(sb, DISCARD)) {
2908 list_for_each_entry(entry, &freed_data_list, efd_list) {
2909 err = ext4_issue_discard(sb, entry->efd_group,
2910 entry->efd_start_cluster,
2913 if (err && err != -EOPNOTSUPP) {
2914 ext4_msg(sb, KERN_WARNING, "discard request in"
2915 " group:%d block:%d count:%d failed"
2916 " with %d", entry->efd_group,
2917 entry->efd_start_cluster,
2918 entry->efd_count, err);
2919 } else if (err == -EOPNOTSUPP)
2924 submit_bio_wait(discard_bio);
2925 bio_put(discard_bio);
2929 list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
2930 ext4_free_data_in_buddy(sb, entry);
2933 int __init ext4_init_mballoc(void)
2935 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
2936 SLAB_RECLAIM_ACCOUNT);
2937 if (ext4_pspace_cachep == NULL)
2940 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
2941 SLAB_RECLAIM_ACCOUNT);
2942 if (ext4_ac_cachep == NULL) {
2943 kmem_cache_destroy(ext4_pspace_cachep);
2947 ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
2948 SLAB_RECLAIM_ACCOUNT);
2949 if (ext4_free_data_cachep == NULL) {
2950 kmem_cache_destroy(ext4_pspace_cachep);
2951 kmem_cache_destroy(ext4_ac_cachep);
2957 void ext4_exit_mballoc(void)
2960 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
2961 * before destroying the slab cache.
2964 kmem_cache_destroy(ext4_pspace_cachep);
2965 kmem_cache_destroy(ext4_ac_cachep);
2966 kmem_cache_destroy(ext4_free_data_cachep);
2967 ext4_groupinfo_destroy_slabs();
2972 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2973 * Returns 0 if success or error code
2975 static noinline_for_stack int
2976 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2977 handle_t *handle, unsigned int reserv_clstrs)
2979 struct buffer_head *bitmap_bh = NULL;
2980 struct ext4_group_desc *gdp;
2981 struct buffer_head *gdp_bh;
2982 struct ext4_sb_info *sbi;
2983 struct super_block *sb;
2987 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2988 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2993 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2994 if (IS_ERR(bitmap_bh)) {
2995 err = PTR_ERR(bitmap_bh);
3000 BUFFER_TRACE(bitmap_bh, "getting write access");
3001 err = ext4_journal_get_write_access(handle, bitmap_bh);
3006 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3010 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
3011 ext4_free_group_clusters(sb, gdp));
3013 BUFFER_TRACE(gdp_bh, "get_write_access");
3014 err = ext4_journal_get_write_access(handle, gdp_bh);
3018 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3020 len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3021 if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
3022 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
3023 "fs metadata", block, block+len);
3024 /* File system mounted not to panic on error
3025 * Fix the bitmap and return EFSCORRUPTED
3026 * We leak some of the blocks here.
3028 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3029 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3030 ac->ac_b_ex.fe_len);
3031 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3032 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3034 err = -EFSCORRUPTED;
3038 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3039 #ifdef AGGRESSIVE_CHECK
3042 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3043 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3044 bitmap_bh->b_data));
3048 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3049 ac->ac_b_ex.fe_len);
3050 if (ext4_has_group_desc_csum(sb) &&
3051 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3052 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3053 ext4_free_group_clusters_set(sb, gdp,
3054 ext4_free_clusters_after_init(sb,
3055 ac->ac_b_ex.fe_group, gdp));
3057 len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
3058 ext4_free_group_clusters_set(sb, gdp, len);
3059 ext4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);
3060 ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
3062 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3063 percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
3065 * Now reduce the dirty block count also. Should not go negative
3067 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3068 /* release all the reserved blocks if non delalloc */
3069 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
3072 if (sbi->s_log_groups_per_flex) {
3073 ext4_group_t flex_group = ext4_flex_group(sbi,
3074 ac->ac_b_ex.fe_group);
3075 atomic64_sub(ac->ac_b_ex.fe_len,
3076 &sbi_array_rcu_deref(sbi, s_flex_groups,
3077 flex_group)->free_clusters);
3080 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3083 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3091 * here we normalize request for locality group
3092 * Group request are normalized to s_mb_group_prealloc, which goes to
3093 * s_strip if we set the same via mount option.
3094 * s_mb_group_prealloc can be configured via
3095 * /sys/fs/ext4/<partition>/mb_group_prealloc
3097 * XXX: should we try to preallocate more than the group has now?
3099 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3101 struct super_block *sb = ac->ac_sb;
3102 struct ext4_locality_group *lg = ac->ac_lg;
3105 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3106 mb_debug(1, "#%u: goal %u blocks for locality group\n",
3107 current->pid, ac->ac_g_ex.fe_len);
3111 * Normalization means making request better in terms of
3112 * size and alignment
3114 static noinline_for_stack void
3115 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3116 struct ext4_allocation_request *ar)
3118 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3121 loff_t size, start_off;
3122 loff_t orig_size __maybe_unused;
3124 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3125 struct ext4_prealloc_space *pa;
3127 /* do normalize only data requests, metadata requests
3128 do not need preallocation */
3129 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3132 /* sometime caller may want exact blocks */
3133 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3136 /* caller may indicate that preallocation isn't
3137 * required (it's a tail, for example) */
3138 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3141 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3142 ext4_mb_normalize_group_request(ac);
3146 bsbits = ac->ac_sb->s_blocksize_bits;
3148 /* first, let's learn actual file size
3149 * given current request is allocated */
3150 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
3151 size = size << bsbits;
3152 if (size < i_size_read(ac->ac_inode))
3153 size = i_size_read(ac->ac_inode);
3156 /* max size of free chunks */
3159 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
3160 (req <= (size) || max <= (chunk_size))
3162 /* first, try to predict filesize */
3163 /* XXX: should this table be tunable? */
3165 if (size <= 16 * 1024) {
3167 } else if (size <= 32 * 1024) {
3169 } else if (size <= 64 * 1024) {
3171 } else if (size <= 128 * 1024) {
3173 } else if (size <= 256 * 1024) {
3175 } else if (size <= 512 * 1024) {
3177 } else if (size <= 1024 * 1024) {
3179 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3180 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3181 (21 - bsbits)) << 21;
3182 size = 2 * 1024 * 1024;
3183 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3184 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3185 (22 - bsbits)) << 22;
3186 size = 4 * 1024 * 1024;
3187 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3188 (8<<20)>>bsbits, max, 8 * 1024)) {
3189 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3190 (23 - bsbits)) << 23;
3191 size = 8 * 1024 * 1024;
3193 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
3194 size = (loff_t) EXT4_C2B(EXT4_SB(ac->ac_sb),
3195 ac->ac_o_ex.fe_len) << bsbits;
3197 size = size >> bsbits;
3198 start = start_off >> bsbits;
3201 * For tiny groups (smaller than 8MB) the chosen allocation
3202 * alignment may be larger than group size. Make sure the
3203 * alignment does not move allocation to a different group which
3204 * makes mballoc fail assertions later.
3206 start = max(start, rounddown(ac->ac_o_ex.fe_logical,
3207 (ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
3209 /* don't cover already allocated blocks in selected range */
3210 if (ar->pleft && start <= ar->lleft) {
3211 size -= ar->lleft + 1 - start;
3212 start = ar->lleft + 1;
3214 if (ar->pright && start + size - 1 >= ar->lright)
3215 size -= start + size - ar->lright;
3218 * Trim allocation request for filesystems with artificially small
3221 if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
3222 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
3226 /* check we don't cross already preallocated blocks */
3228 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3233 spin_lock(&pa->pa_lock);
3234 if (pa->pa_deleted) {
3235 spin_unlock(&pa->pa_lock);
3239 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3242 /* PA must not overlap original request */
3243 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3244 ac->ac_o_ex.fe_logical < pa->pa_lstart));
3246 /* skip PAs this normalized request doesn't overlap with */
3247 if (pa->pa_lstart >= end || pa_end <= start) {
3248 spin_unlock(&pa->pa_lock);
3251 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3253 /* adjust start or end to be adjacent to this pa */
3254 if (pa_end <= ac->ac_o_ex.fe_logical) {
3255 BUG_ON(pa_end < start);
3257 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3258 BUG_ON(pa->pa_lstart > end);
3259 end = pa->pa_lstart;
3261 spin_unlock(&pa->pa_lock);
3266 /* XXX: extra loop to check we really don't overlap preallocations */
3268 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3271 spin_lock(&pa->pa_lock);
3272 if (pa->pa_deleted == 0) {
3273 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3275 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3277 spin_unlock(&pa->pa_lock);
3281 if (start + size <= ac->ac_o_ex.fe_logical &&
3282 start > ac->ac_o_ex.fe_logical) {
3283 ext4_msg(ac->ac_sb, KERN_ERR,
3284 "start %lu, size %lu, fe_logical %lu",
3285 (unsigned long) start, (unsigned long) size,
3286 (unsigned long) ac->ac_o_ex.fe_logical);
3289 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3291 /* now prepare goal request */
3293 /* XXX: is it better to align blocks WRT to logical
3294 * placement or satisfy big request as is */
3295 ac->ac_g_ex.fe_logical = start;
3296 ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3298 /* define goal start in order to merge */
3299 if (ar->pright && (ar->lright == (start + size))) {
3300 /* merge to the right */
3301 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3302 &ac->ac_f_ex.fe_group,
3303 &ac->ac_f_ex.fe_start);
3304 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3306 if (ar->pleft && (ar->lleft + 1 == start)) {
3307 /* merge to the left */
3308 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3309 &ac->ac_f_ex.fe_group,
3310 &ac->ac_f_ex.fe_start);
3311 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3314 mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3315 (unsigned) orig_size, (unsigned) start);
3318 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3320 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3322 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3323 atomic_inc(&sbi->s_bal_reqs);
3324 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3325 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3326 atomic_inc(&sbi->s_bal_success);
3327 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3328 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3329 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3330 atomic_inc(&sbi->s_bal_goals);
3331 if (ac->ac_found > sbi->s_mb_max_to_scan)
3332 atomic_inc(&sbi->s_bal_breaks);
3335 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3336 trace_ext4_mballoc_alloc(ac);
3338 trace_ext4_mballoc_prealloc(ac);
3342 * Called on failure; free up any blocks from the inode PA for this
3343 * context. We don't need this for MB_GROUP_PA because we only change
3344 * pa_free in ext4_mb_release_context(), but on failure, we've already
3345 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3347 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3349 struct ext4_prealloc_space *pa = ac->ac_pa;
3350 struct ext4_buddy e4b;
3354 if (ac->ac_f_ex.fe_len == 0)
3356 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
3359 * This should never happen since we pin the
3360 * pages in the ext4_allocation_context so
3361 * ext4_mb_load_buddy() should never fail.
3363 WARN(1, "mb_load_buddy failed (%d)", err);
3366 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3367 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
3368 ac->ac_f_ex.fe_len);
3369 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3370 ext4_mb_unload_buddy(&e4b);
3373 if (pa->pa_type == MB_INODE_PA)
3374 pa->pa_free += ac->ac_b_ex.fe_len;
3378 * use blocks preallocated to inode
3380 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3381 struct ext4_prealloc_space *pa)
3383 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3388 /* found preallocated blocks, use them */
3389 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3390 end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
3391 start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
3392 len = EXT4_NUM_B2C(sbi, end - start);
3393 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3394 &ac->ac_b_ex.fe_start);
3395 ac->ac_b_ex.fe_len = len;
3396 ac->ac_status = AC_STATUS_FOUND;
3399 BUG_ON(start < pa->pa_pstart);
3400 BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3401 BUG_ON(pa->pa_free < len);
3404 mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3408 * use blocks preallocated to locality group
3410 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3411 struct ext4_prealloc_space *pa)
3413 unsigned int len = ac->ac_o_ex.fe_len;
3415 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3416 &ac->ac_b_ex.fe_group,
3417 &ac->ac_b_ex.fe_start);
3418 ac->ac_b_ex.fe_len = len;
3419 ac->ac_status = AC_STATUS_FOUND;
3422 /* we don't correct pa_pstart or pa_plen here to avoid
3423 * possible race when the group is being loaded concurrently
3424 * instead we correct pa later, after blocks are marked
3425 * in on-disk bitmap -- see ext4_mb_release_context()
3426 * Other CPUs are prevented from allocating from this pa by lg_mutex
3428 mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3432 * Return the prealloc space that have minimal distance
3433 * from the goal block. @cpa is the prealloc
3434 * space that is having currently known minimal distance
3435 * from the goal block.
3437 static struct ext4_prealloc_space *
3438 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3439 struct ext4_prealloc_space *pa,
3440 struct ext4_prealloc_space *cpa)
3442 ext4_fsblk_t cur_distance, new_distance;
3445 atomic_inc(&pa->pa_count);
3448 cur_distance = abs(goal_block - cpa->pa_pstart);
3449 new_distance = abs(goal_block - pa->pa_pstart);
3451 if (cur_distance <= new_distance)
3454 /* drop the previous reference */
3455 atomic_dec(&cpa->pa_count);
3456 atomic_inc(&pa->pa_count);
3461 * search goal blocks in preallocated space
3463 static noinline_for_stack int
3464 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3466 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3468 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3469 struct ext4_locality_group *lg;
3470 struct ext4_prealloc_space *pa, *cpa = NULL;
3471 ext4_fsblk_t goal_block;
3473 /* only data can be preallocated */
3474 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3477 /* first, try per-file preallocation */
3479 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3481 /* all fields in this condition don't change,
3482 * so we can skip locking for them */
3483 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3484 ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
3485 EXT4_C2B(sbi, pa->pa_len)))
3488 /* non-extent files can't have physical blocks past 2^32 */
3489 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3490 (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
3491 EXT4_MAX_BLOCK_FILE_PHYS))
3494 /* found preallocated blocks, use them */
3495 spin_lock(&pa->pa_lock);
3496 if (pa->pa_deleted == 0 && pa->pa_free) {
3497 atomic_inc(&pa->pa_count);
3498 ext4_mb_use_inode_pa(ac, pa);
3499 spin_unlock(&pa->pa_lock);
3500 ac->ac_criteria = 10;
3504 spin_unlock(&pa->pa_lock);
3508 /* can we use group allocation? */
3509 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3512 /* inode may have no locality group for some reason */
3516 order = fls(ac->ac_o_ex.fe_len) - 1;
3517 if (order > PREALLOC_TB_SIZE - 1)
3518 /* The max size of hash table is PREALLOC_TB_SIZE */
3519 order = PREALLOC_TB_SIZE - 1;
3521 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3523 * search for the prealloc space that is having
3524 * minimal distance from the goal block.
3526 for (i = order; i < PREALLOC_TB_SIZE; i++) {
3528 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3530 spin_lock(&pa->pa_lock);
3531 if (pa->pa_deleted == 0 &&
3532 pa->pa_free >= ac->ac_o_ex.fe_len) {
3534 cpa = ext4_mb_check_group_pa(goal_block,
3537 spin_unlock(&pa->pa_lock);
3542 ext4_mb_use_group_pa(ac, cpa);
3543 ac->ac_criteria = 20;
3550 * the function goes through all block freed in the group
3551 * but not yet committed and marks them used in in-core bitmap.
3552 * buddy must be generated from this bitmap
3553 * Need to be called with the ext4 group lock held
3555 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3559 struct ext4_group_info *grp;
3560 struct ext4_free_data *entry;
3562 grp = ext4_get_group_info(sb, group);
3563 n = rb_first(&(grp->bb_free_root));
3566 entry = rb_entry(n, struct ext4_free_data, efd_node);
3567 ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
3574 * the function goes through all preallocation in this group and marks them
3575 * used in in-core bitmap. buddy must be generated from this bitmap
3576 * Need to be called with ext4 group lock held
3578 static noinline_for_stack
3579 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3582 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3583 struct ext4_prealloc_space *pa;
3584 struct list_head *cur;
3585 ext4_group_t groupnr;
3586 ext4_grpblk_t start;
3587 int preallocated = 0;
3590 /* all form of preallocation discards first load group,
3591 * so the only competing code is preallocation use.
3592 * we don't need any locking here
3593 * notice we do NOT ignore preallocations with pa_deleted
3594 * otherwise we could leave used blocks available for
3595 * allocation in buddy when concurrent ext4_mb_put_pa()
3596 * is dropping preallocation
3598 list_for_each(cur, &grp->bb_prealloc_list) {
3599 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3600 spin_lock(&pa->pa_lock);
3601 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3604 spin_unlock(&pa->pa_lock);
3605 if (unlikely(len == 0))
3607 BUG_ON(groupnr != group);
3608 ext4_set_bits(bitmap, start, len);
3609 preallocated += len;
3611 mb_debug(1, "preallocated %u for group %u\n", preallocated, group);
3614 static void ext4_mb_pa_callback(struct rcu_head *head)
3616 struct ext4_prealloc_space *pa;
3617 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3619 BUG_ON(atomic_read(&pa->pa_count));
3620 BUG_ON(pa->pa_deleted == 0);
3621 kmem_cache_free(ext4_pspace_cachep, pa);
3625 * drops a reference to preallocated space descriptor
3626 * if this was the last reference and the space is consumed
3628 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3629 struct super_block *sb, struct ext4_prealloc_space *pa)
3632 ext4_fsblk_t grp_blk;
3634 /* in this short window concurrent discard can set pa_deleted */
3635 spin_lock(&pa->pa_lock);
3636 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
3637 spin_unlock(&pa->pa_lock);
3641 if (pa->pa_deleted == 1) {
3642 spin_unlock(&pa->pa_lock);
3647 spin_unlock(&pa->pa_lock);
3649 grp_blk = pa->pa_pstart;
3651 * If doing group-based preallocation, pa_pstart may be in the
3652 * next group when pa is used up
3654 if (pa->pa_type == MB_GROUP_PA)
3657 grp = ext4_get_group_number(sb, grp_blk);
3662 * P1 (buddy init) P2 (regular allocation)
3663 * find block B in PA
3664 * copy on-disk bitmap to buddy
3665 * mark B in on-disk bitmap
3666 * drop PA from group
3667 * mark all PAs in buddy
3669 * thus, P1 initializes buddy with B available. to prevent this
3670 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3673 ext4_lock_group(sb, grp);
3674 list_del(&pa->pa_group_list);
3675 ext4_unlock_group(sb, grp);
3677 spin_lock(pa->pa_obj_lock);
3678 list_del_rcu(&pa->pa_inode_list);
3679 spin_unlock(pa->pa_obj_lock);
3681 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3685 * creates new preallocated space for given inode
3687 static noinline_for_stack int
3688 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3690 struct super_block *sb = ac->ac_sb;
3691 struct ext4_sb_info *sbi = EXT4_SB(sb);
3692 struct ext4_prealloc_space *pa;
3693 struct ext4_group_info *grp;
3694 struct ext4_inode_info *ei;
3696 /* preallocate only when found space is larger then requested */
3697 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3698 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3699 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3701 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3705 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3711 /* we can't allocate as much as normalizer wants.
3712 * so, found space must get proper lstart
3713 * to cover original request */
3714 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3715 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3717 /* we're limited by original request in that
3718 * logical block must be covered any way
3719 * winl is window we can move our chunk within */
3720 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3722 /* also, we should cover whole original request */
3723 wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
3725 /* the smallest one defines real window */
3726 win = min(winl, wins);
3728 offs = ac->ac_o_ex.fe_logical %
3729 EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3730 if (offs && offs < win)
3733 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
3734 EXT4_NUM_B2C(sbi, win);
3735 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3736 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3739 /* preallocation can change ac_b_ex, thus we store actually
3740 * allocated blocks for history */
3741 ac->ac_f_ex = ac->ac_b_ex;
3743 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3744 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3745 pa->pa_len = ac->ac_b_ex.fe_len;
3746 pa->pa_free = pa->pa_len;
3747 atomic_set(&pa->pa_count, 1);
3748 spin_lock_init(&pa->pa_lock);
3749 INIT_LIST_HEAD(&pa->pa_inode_list);
3750 INIT_LIST_HEAD(&pa->pa_group_list);
3752 pa->pa_type = MB_INODE_PA;
3754 mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3755 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3756 trace_ext4_mb_new_inode_pa(ac, pa);
3758 ext4_mb_use_inode_pa(ac, pa);
3759 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
3761 ei = EXT4_I(ac->ac_inode);
3762 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3764 pa->pa_obj_lock = &ei->i_prealloc_lock;
3765 pa->pa_inode = ac->ac_inode;
3767 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3768 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3769 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3771 spin_lock(pa->pa_obj_lock);
3772 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3773 spin_unlock(pa->pa_obj_lock);
3779 * creates new preallocated space for locality group inodes belongs to
3781 static noinline_for_stack int
3782 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3784 struct super_block *sb = ac->ac_sb;
3785 struct ext4_locality_group *lg;
3786 struct ext4_prealloc_space *pa;
3787 struct ext4_group_info *grp;
3789 /* preallocate only when found space is larger then requested */
3790 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3791 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3792 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3794 BUG_ON(ext4_pspace_cachep == NULL);
3795 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3799 /* preallocation can change ac_b_ex, thus we store actually
3800 * allocated blocks for history */
3801 ac->ac_f_ex = ac->ac_b_ex;
3803 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3804 pa->pa_lstart = pa->pa_pstart;
3805 pa->pa_len = ac->ac_b_ex.fe_len;
3806 pa->pa_free = pa->pa_len;
3807 atomic_set(&pa->pa_count, 1);
3808 spin_lock_init(&pa->pa_lock);
3809 INIT_LIST_HEAD(&pa->pa_inode_list);
3810 INIT_LIST_HEAD(&pa->pa_group_list);
3812 pa->pa_type = MB_GROUP_PA;
3814 mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3815 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3816 trace_ext4_mb_new_group_pa(ac, pa);
3818 ext4_mb_use_group_pa(ac, pa);
3819 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3821 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3825 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3826 pa->pa_inode = NULL;
3828 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3829 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3830 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3833 * We will later add the new pa to the right bucket
3834 * after updating the pa_free in ext4_mb_release_context
3839 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3843 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3844 err = ext4_mb_new_group_pa(ac);
3846 err = ext4_mb_new_inode_pa(ac);
3851 * finds all unused blocks in on-disk bitmap, frees them in
3852 * in-core bitmap and buddy.
3853 * @pa must be unlinked from inode and group lists, so that
3854 * nobody else can find/use it.
3855 * the caller MUST hold group/inode locks.
3856 * TODO: optimize the case when there are no in-core structures yet
3858 static noinline_for_stack int
3859 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3860 struct ext4_prealloc_space *pa)
3862 struct super_block *sb = e4b->bd_sb;
3863 struct ext4_sb_info *sbi = EXT4_SB(sb);
3868 unsigned long long grp_blk_start;
3872 BUG_ON(pa->pa_deleted == 0);
3873 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3874 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
3875 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3876 end = bit + pa->pa_len;
3879 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3882 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3883 mb_debug(1, " free preallocated %u/%u in group %u\n",
3884 (unsigned) ext4_group_first_block_no(sb, group) + bit,
3885 (unsigned) next - bit, (unsigned) group);
3888 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
3889 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
3890 EXT4_C2B(sbi, bit)),
3892 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3895 if (free != pa->pa_free) {
3896 ext4_msg(e4b->bd_sb, KERN_CRIT,
3897 "pa %p: logic %lu, phys. %lu, len %lu",
3898 pa, (unsigned long) pa->pa_lstart,
3899 (unsigned long) pa->pa_pstart,
3900 (unsigned long) pa->pa_len);
3901 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
3904 * pa is already deleted so we use the value obtained
3905 * from the bitmap and continue.
3908 atomic_add(free, &sbi->s_mb_discarded);
3913 static noinline_for_stack int
3914 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3915 struct ext4_prealloc_space *pa)
3917 struct super_block *sb = e4b->bd_sb;
3921 trace_ext4_mb_release_group_pa(sb, pa);
3922 BUG_ON(pa->pa_deleted == 0);
3923 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3924 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3925 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3926 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3927 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3933 * releases all preallocations in given group
3935 * first, we need to decide discard policy:
3936 * - when do we discard
3938 * - how many do we discard
3939 * 1) how many requested
3941 static noinline_for_stack int
3942 ext4_mb_discard_group_preallocations(struct super_block *sb,
3943 ext4_group_t group, int needed)
3945 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3946 struct buffer_head *bitmap_bh = NULL;
3947 struct ext4_prealloc_space *pa, *tmp;
3948 struct list_head list;
3949 struct ext4_buddy e4b;
3954 mb_debug(1, "discard preallocation for group %u\n", group);
3956 if (list_empty(&grp->bb_prealloc_list))
3959 bitmap_bh = ext4_read_block_bitmap(sb, group);
3960 if (IS_ERR(bitmap_bh)) {
3961 err = PTR_ERR(bitmap_bh);
3962 ext4_error(sb, "Error %d reading block bitmap for %u",
3967 err = ext4_mb_load_buddy(sb, group, &e4b);
3969 ext4_warning(sb, "Error %d loading buddy information for %u",
3976 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
3978 INIT_LIST_HEAD(&list);
3980 ext4_lock_group(sb, group);
3981 list_for_each_entry_safe(pa, tmp,
3982 &grp->bb_prealloc_list, pa_group_list) {
3983 spin_lock(&pa->pa_lock);
3984 if (atomic_read(&pa->pa_count)) {
3985 spin_unlock(&pa->pa_lock);
3989 if (pa->pa_deleted) {
3990 spin_unlock(&pa->pa_lock);
3994 /* seems this one can be freed ... */
3997 /* we can trust pa_free ... */
3998 free += pa->pa_free;
4000 spin_unlock(&pa->pa_lock);
4002 list_del(&pa->pa_group_list);
4003 list_add(&pa->u.pa_tmp_list, &list);
4006 /* if we still need more blocks and some PAs were used, try again */
4007 if (free < needed && busy) {
4009 ext4_unlock_group(sb, group);
4014 /* found anything to free? */
4015 if (list_empty(&list)) {
4020 /* now free all selected PAs */
4021 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4023 /* remove from object (inode or locality group) */
4024 spin_lock(pa->pa_obj_lock);
4025 list_del_rcu(&pa->pa_inode_list);
4026 spin_unlock(pa->pa_obj_lock);
4028 if (pa->pa_type == MB_GROUP_PA)
4029 ext4_mb_release_group_pa(&e4b, pa);
4031 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4033 list_del(&pa->u.pa_tmp_list);
4034 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4038 ext4_unlock_group(sb, group);
4039 ext4_mb_unload_buddy(&e4b);
4045 * releases all non-used preallocated blocks for given inode
4047 * It's important to discard preallocations under i_data_sem
4048 * We don't want another block to be served from the prealloc
4049 * space when we are discarding the inode prealloc space.
4051 * FIXME!! Make sure it is valid at all the call sites
4053 void ext4_discard_preallocations(struct inode *inode)
4055 struct ext4_inode_info *ei = EXT4_I(inode);
4056 struct super_block *sb = inode->i_sb;
4057 struct buffer_head *bitmap_bh = NULL;
4058 struct ext4_prealloc_space *pa, *tmp;
4059 ext4_group_t group = 0;
4060 struct list_head list;
4061 struct ext4_buddy e4b;
4064 if (!S_ISREG(inode->i_mode)) {
4065 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4069 mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
4070 trace_ext4_discard_preallocations(inode);
4072 INIT_LIST_HEAD(&list);
4075 /* first, collect all pa's in the inode */
4076 spin_lock(&ei->i_prealloc_lock);
4077 while (!list_empty(&ei->i_prealloc_list)) {
4078 pa = list_entry(ei->i_prealloc_list.next,
4079 struct ext4_prealloc_space, pa_inode_list);
4080 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4081 spin_lock(&pa->pa_lock);
4082 if (atomic_read(&pa->pa_count)) {
4083 /* this shouldn't happen often - nobody should
4084 * use preallocation while we're discarding it */
4085 spin_unlock(&pa->pa_lock);
4086 spin_unlock(&ei->i_prealloc_lock);
4087 ext4_msg(sb, KERN_ERR,
4088 "uh-oh! used pa while discarding");
4090 schedule_timeout_uninterruptible(HZ);
4094 if (pa->pa_deleted == 0) {
4096 spin_unlock(&pa->pa_lock);
4097 list_del_rcu(&pa->pa_inode_list);
4098 list_add(&pa->u.pa_tmp_list, &list);
4102 /* someone is deleting pa right now */
4103 spin_unlock(&pa->pa_lock);
4104 spin_unlock(&ei->i_prealloc_lock);
4106 /* we have to wait here because pa_deleted
4107 * doesn't mean pa is already unlinked from
4108 * the list. as we might be called from
4109 * ->clear_inode() the inode will get freed
4110 * and concurrent thread which is unlinking
4111 * pa from inode's list may access already
4112 * freed memory, bad-bad-bad */
4114 /* XXX: if this happens too often, we can
4115 * add a flag to force wait only in case
4116 * of ->clear_inode(), but not in case of
4117 * regular truncate */
4118 schedule_timeout_uninterruptible(HZ);
4121 spin_unlock(&ei->i_prealloc_lock);
4123 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4124 BUG_ON(pa->pa_type != MB_INODE_PA);
4125 group = ext4_get_group_number(sb, pa->pa_pstart);
4127 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4128 GFP_NOFS|__GFP_NOFAIL);
4130 ext4_error(sb, "Error %d loading buddy information for %u",
4135 bitmap_bh = ext4_read_block_bitmap(sb, group);
4136 if (IS_ERR(bitmap_bh)) {
4137 err = PTR_ERR(bitmap_bh);
4138 ext4_error(sb, "Error %d reading block bitmap for %u",
4140 ext4_mb_unload_buddy(&e4b);
4144 ext4_lock_group(sb, group);
4145 list_del(&pa->pa_group_list);
4146 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4147 ext4_unlock_group(sb, group);
4149 ext4_mb_unload_buddy(&e4b);
4152 list_del(&pa->u.pa_tmp_list);
4153 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4157 #ifdef CONFIG_EXT4_DEBUG
4158 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4160 struct super_block *sb = ac->ac_sb;
4161 ext4_group_t ngroups, i;
4163 if (!ext4_mballoc_debug ||
4164 (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
4167 ext4_msg(ac->ac_sb, KERN_ERR, "Can't allocate:"
4168 " Allocation context details:");
4169 ext4_msg(ac->ac_sb, KERN_ERR, "status %d flags %d",
4170 ac->ac_status, ac->ac_flags);
4171 ext4_msg(ac->ac_sb, KERN_ERR, "orig %lu/%lu/%lu@%lu, "
4172 "goal %lu/%lu/%lu@%lu, "
4173 "best %lu/%lu/%lu@%lu cr %d",
4174 (unsigned long)ac->ac_o_ex.fe_group,
4175 (unsigned long)ac->ac_o_ex.fe_start,
4176 (unsigned long)ac->ac_o_ex.fe_len,
4177 (unsigned long)ac->ac_o_ex.fe_logical,
4178 (unsigned long)ac->ac_g_ex.fe_group,
4179 (unsigned long)ac->ac_g_ex.fe_start,
4180 (unsigned long)ac->ac_g_ex.fe_len,
4181 (unsigned long)ac->ac_g_ex.fe_logical,
4182 (unsigned long)ac->ac_b_ex.fe_group,
4183 (unsigned long)ac->ac_b_ex.fe_start,
4184 (unsigned long)ac->ac_b_ex.fe_len,
4185 (unsigned long)ac->ac_b_ex.fe_logical,
4186 (int)ac->ac_criteria);
4187 ext4_msg(ac->ac_sb, KERN_ERR, "%d found", ac->ac_found);
4188 ext4_msg(ac->ac_sb, KERN_ERR, "groups: ");
4189 ngroups = ext4_get_groups_count(sb);
4190 for (i = 0; i < ngroups; i++) {
4191 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4192 struct ext4_prealloc_space *pa;
4193 ext4_grpblk_t start;
4194 struct list_head *cur;
4195 ext4_lock_group(sb, i);
4196 list_for_each(cur, &grp->bb_prealloc_list) {
4197 pa = list_entry(cur, struct ext4_prealloc_space,
4199 spin_lock(&pa->pa_lock);
4200 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4202 spin_unlock(&pa->pa_lock);
4203 printk(KERN_ERR "PA:%u:%d:%u \n", i,
4206 ext4_unlock_group(sb, i);
4208 if (grp->bb_free == 0)
4210 printk(KERN_ERR "%u: %d/%d \n",
4211 i, grp->bb_free, grp->bb_fragments);
4213 printk(KERN_ERR "\n");
4216 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4223 * We use locality group preallocation for small size file. The size of the
4224 * file is determined by the current size or the resulting size after
4225 * allocation which ever is larger
4227 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4229 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4231 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4232 int bsbits = ac->ac_sb->s_blocksize_bits;
4235 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4238 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4241 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
4242 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
4245 if ((size == isize) &&
4246 !ext4_fs_is_busy(sbi) &&
4247 (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
4248 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
4252 if (sbi->s_mb_group_prealloc <= 0) {
4253 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4257 /* don't use group allocation for large files */
4258 size = max(size, isize);
4259 if (size > sbi->s_mb_stream_request) {
4260 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4264 BUG_ON(ac->ac_lg != NULL);
4266 * locality group prealloc space are per cpu. The reason for having
4267 * per cpu locality group is to reduce the contention between block
4268 * request from multiple CPUs.
4270 ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
4272 /* we're going to use group allocation */
4273 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4275 /* serialize all allocations in the group */
4276 mutex_lock(&ac->ac_lg->lg_mutex);
4279 static noinline_for_stack int
4280 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4281 struct ext4_allocation_request *ar)
4283 struct super_block *sb = ar->inode->i_sb;
4284 struct ext4_sb_info *sbi = EXT4_SB(sb);
4285 struct ext4_super_block *es = sbi->s_es;
4289 ext4_grpblk_t block;
4291 /* we can't allocate > group size */
4294 /* just a dirty hack to filter too big requests */
4295 if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
4296 len = EXT4_CLUSTERS_PER_GROUP(sb);
4298 /* start searching from the goal */
4300 if (goal < le32_to_cpu(es->s_first_data_block) ||
4301 goal >= ext4_blocks_count(es))
4302 goal = le32_to_cpu(es->s_first_data_block);
4303 ext4_get_group_no_and_offset(sb, goal, &group, &block);
4305 /* set up allocation goals */
4306 ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
4307 ac->ac_status = AC_STATUS_CONTINUE;
4309 ac->ac_inode = ar->inode;
4310 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4311 ac->ac_o_ex.fe_group = group;
4312 ac->ac_o_ex.fe_start = block;
4313 ac->ac_o_ex.fe_len = len;
4314 ac->ac_g_ex = ac->ac_o_ex;
4315 ac->ac_flags = ar->flags;
4317 /* we have to define context: we'll we work with a file or
4318 * locality group. this is a policy, actually */
4319 ext4_mb_group_or_file(ac);
4321 mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4322 "left: %u/%u, right %u/%u to %swritable\n",
4323 (unsigned) ar->len, (unsigned) ar->logical,
4324 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4325 (unsigned) ar->lleft, (unsigned) ar->pleft,
4326 (unsigned) ar->lright, (unsigned) ar->pright,
4327 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4332 static noinline_for_stack void
4333 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4334 struct ext4_locality_group *lg,
4335 int order, int total_entries)
4337 ext4_group_t group = 0;
4338 struct ext4_buddy e4b;
4339 struct list_head discard_list;
4340 struct ext4_prealloc_space *pa, *tmp;
4342 mb_debug(1, "discard locality group preallocation\n");
4344 INIT_LIST_HEAD(&discard_list);
4346 spin_lock(&lg->lg_prealloc_lock);
4347 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4349 spin_lock(&pa->pa_lock);
4350 if (atomic_read(&pa->pa_count)) {
4352 * This is the pa that we just used
4353 * for block allocation. So don't
4356 spin_unlock(&pa->pa_lock);
4359 if (pa->pa_deleted) {
4360 spin_unlock(&pa->pa_lock);
4363 /* only lg prealloc space */
4364 BUG_ON(pa->pa_type != MB_GROUP_PA);
4366 /* seems this one can be freed ... */
4368 spin_unlock(&pa->pa_lock);
4370 list_del_rcu(&pa->pa_inode_list);
4371 list_add(&pa->u.pa_tmp_list, &discard_list);
4374 if (total_entries <= 5) {
4376 * we want to keep only 5 entries
4377 * allowing it to grow to 8. This
4378 * mak sure we don't call discard
4379 * soon for this list.
4384 spin_unlock(&lg->lg_prealloc_lock);
4386 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4389 group = ext4_get_group_number(sb, pa->pa_pstart);
4390 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4391 GFP_NOFS|__GFP_NOFAIL);
4393 ext4_error(sb, "Error %d loading buddy information for %u",
4397 ext4_lock_group(sb, group);
4398 list_del(&pa->pa_group_list);
4399 ext4_mb_release_group_pa(&e4b, pa);
4400 ext4_unlock_group(sb, group);
4402 ext4_mb_unload_buddy(&e4b);
4403 list_del(&pa->u.pa_tmp_list);
4404 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4409 * We have incremented pa_count. So it cannot be freed at this
4410 * point. Also we hold lg_mutex. So no parallel allocation is
4411 * possible from this lg. That means pa_free cannot be updated.
4413 * A parallel ext4_mb_discard_group_preallocations is possible.
4414 * which can cause the lg_prealloc_list to be updated.
4417 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4419 int order, added = 0, lg_prealloc_count = 1;
4420 struct super_block *sb = ac->ac_sb;
4421 struct ext4_locality_group *lg = ac->ac_lg;
4422 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4424 order = fls(pa->pa_free) - 1;
4425 if (order > PREALLOC_TB_SIZE - 1)
4426 /* The max size of hash table is PREALLOC_TB_SIZE */
4427 order = PREALLOC_TB_SIZE - 1;
4428 /* Add the prealloc space to lg */
4429 spin_lock(&lg->lg_prealloc_lock);
4430 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4432 spin_lock(&tmp_pa->pa_lock);
4433 if (tmp_pa->pa_deleted) {
4434 spin_unlock(&tmp_pa->pa_lock);
4437 if (!added && pa->pa_free < tmp_pa->pa_free) {
4438 /* Add to the tail of the previous entry */
4439 list_add_tail_rcu(&pa->pa_inode_list,
4440 &tmp_pa->pa_inode_list);
4443 * we want to count the total
4444 * number of entries in the list
4447 spin_unlock(&tmp_pa->pa_lock);
4448 lg_prealloc_count++;
4451 list_add_tail_rcu(&pa->pa_inode_list,
4452 &lg->lg_prealloc_list[order]);
4453 spin_unlock(&lg->lg_prealloc_lock);
4455 /* Now trim the list to be not more than 8 elements */
4456 if (lg_prealloc_count > 8) {
4457 ext4_mb_discard_lg_preallocations(sb, lg,
4458 order, lg_prealloc_count);
4465 * release all resource we used in allocation
4467 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4469 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4470 struct ext4_prealloc_space *pa = ac->ac_pa;
4472 if (pa->pa_type == MB_GROUP_PA) {
4473 /* see comment in ext4_mb_use_group_pa() */
4474 spin_lock(&pa->pa_lock);
4475 pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4476 pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4477 pa->pa_free -= ac->ac_b_ex.fe_len;
4478 pa->pa_len -= ac->ac_b_ex.fe_len;
4479 spin_unlock(&pa->pa_lock);
4484 * We want to add the pa to the right bucket.
4485 * Remove it from the list and while adding
4486 * make sure the list to which we are adding
4489 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4490 spin_lock(pa->pa_obj_lock);
4491 list_del_rcu(&pa->pa_inode_list);
4492 spin_unlock(pa->pa_obj_lock);
4493 ext4_mb_add_n_trim(ac);
4495 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4497 if (ac->ac_bitmap_page)
4498 put_page(ac->ac_bitmap_page);
4499 if (ac->ac_buddy_page)
4500 put_page(ac->ac_buddy_page);
4501 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4502 mutex_unlock(&ac->ac_lg->lg_mutex);
4503 ext4_mb_collect_stats(ac);
4507 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4509 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4513 trace_ext4_mb_discard_preallocations(sb, needed);
4514 for (i = 0; i < ngroups && needed > 0; i++) {
4515 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4524 * Main entry point into mballoc to allocate blocks
4525 * it tries to use preallocation first, then falls back
4526 * to usual allocation
4528 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4529 struct ext4_allocation_request *ar, int *errp)
4532 struct ext4_allocation_context *ac = NULL;
4533 struct ext4_sb_info *sbi;
4534 struct super_block *sb;
4535 ext4_fsblk_t block = 0;
4536 unsigned int inquota = 0;
4537 unsigned int reserv_clstrs = 0;
4540 sb = ar->inode->i_sb;
4543 trace_ext4_request_blocks(ar);
4545 /* Allow to use superuser reservation for quota file */
4546 if (ext4_is_quota_file(ar->inode))
4547 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
4549 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
4550 /* Without delayed allocation we need to verify
4551 * there is enough free blocks to do block allocation
4552 * and verify allocation doesn't exceed the quota limits.
4555 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
4557 /* let others to free the space */
4559 ar->len = ar->len >> 1;
4565 reserv_clstrs = ar->len;
4566 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
4567 dquot_alloc_block_nofail(ar->inode,
4568 EXT4_C2B(sbi, ar->len));
4571 dquot_alloc_block(ar->inode,
4572 EXT4_C2B(sbi, ar->len))) {
4574 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4585 ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
4592 *errp = ext4_mb_initialize_context(ac, ar);
4598 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4599 if (!ext4_mb_use_preallocated(ac)) {
4600 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4601 ext4_mb_normalize_request(ac, ar);
4603 /* allocate space in core */
4604 *errp = ext4_mb_regular_allocator(ac);
4606 goto discard_and_exit;
4608 /* as we've just preallocated more space than
4609 * user requested originally, we store allocated
4610 * space in a special descriptor */
4611 if (ac->ac_status == AC_STATUS_FOUND &&
4612 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4613 *errp = ext4_mb_new_preallocation(ac);
4616 ext4_discard_allocated_blocks(ac);
4620 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4621 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4623 ext4_discard_allocated_blocks(ac);
4626 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4627 ar->len = ac->ac_b_ex.fe_len;
4630 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4638 ac->ac_b_ex.fe_len = 0;
4640 ext4_mb_show_ac(ac);
4642 ext4_mb_release_context(ac);
4645 kmem_cache_free(ext4_ac_cachep, ac);
4646 if (inquota && ar->len < inquota)
4647 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
4649 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
4650 /* release all the reserved blocks if non delalloc */
4651 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4655 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4661 * We can merge two free data extents only if the physical blocks
4662 * are contiguous, AND the extents were freed by the same transaction,
4663 * AND the blocks are associated with the same group.
4665 static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
4666 struct ext4_free_data *entry,
4667 struct ext4_free_data *new_entry,
4668 struct rb_root *entry_rb_root)
4670 if ((entry->efd_tid != new_entry->efd_tid) ||
4671 (entry->efd_group != new_entry->efd_group))
4673 if (entry->efd_start_cluster + entry->efd_count ==
4674 new_entry->efd_start_cluster) {
4675 new_entry->efd_start_cluster = entry->efd_start_cluster;
4676 new_entry->efd_count += entry->efd_count;
4677 } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
4678 entry->efd_start_cluster) {
4679 new_entry->efd_count += entry->efd_count;
4682 spin_lock(&sbi->s_md_lock);
4683 list_del(&entry->efd_list);
4684 spin_unlock(&sbi->s_md_lock);
4685 rb_erase(&entry->efd_node, entry_rb_root);
4686 kmem_cache_free(ext4_free_data_cachep, entry);
4689 static noinline_for_stack int
4690 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4691 struct ext4_free_data *new_entry)
4693 ext4_group_t group = e4b->bd_group;
4694 ext4_grpblk_t cluster;
4695 ext4_grpblk_t clusters = new_entry->efd_count;
4696 struct ext4_free_data *entry;
4697 struct ext4_group_info *db = e4b->bd_info;
4698 struct super_block *sb = e4b->bd_sb;
4699 struct ext4_sb_info *sbi = EXT4_SB(sb);
4700 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4701 struct rb_node *parent = NULL, *new_node;
4703 BUG_ON(!ext4_handle_valid(handle));
4704 BUG_ON(e4b->bd_bitmap_page == NULL);
4705 BUG_ON(e4b->bd_buddy_page == NULL);
4707 new_node = &new_entry->efd_node;
4708 cluster = new_entry->efd_start_cluster;
4711 /* first free block exent. We need to
4712 protect buddy cache from being freed,
4713 * otherwise we'll refresh it from
4714 * on-disk bitmap and lose not-yet-available
4716 get_page(e4b->bd_buddy_page);
4717 get_page(e4b->bd_bitmap_page);
4721 entry = rb_entry(parent, struct ext4_free_data, efd_node);
4722 if (cluster < entry->efd_start_cluster)
4724 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
4725 n = &(*n)->rb_right;
4727 ext4_grp_locked_error(sb, group, 0,
4728 ext4_group_first_block_no(sb, group) +
4729 EXT4_C2B(sbi, cluster),
4730 "Block already on to-be-freed list");
4731 kmem_cache_free(ext4_free_data_cachep, new_entry);
4736 rb_link_node(new_node, parent, n);
4737 rb_insert_color(new_node, &db->bb_free_root);
4739 /* Now try to see the extent can be merged to left and right */
4740 node = rb_prev(new_node);
4742 entry = rb_entry(node, struct ext4_free_data, efd_node);
4743 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4744 &(db->bb_free_root));
4747 node = rb_next(new_node);
4749 entry = rb_entry(node, struct ext4_free_data, efd_node);
4750 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4751 &(db->bb_free_root));
4754 spin_lock(&sbi->s_md_lock);
4755 list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
4756 sbi->s_mb_free_pending += clusters;
4757 spin_unlock(&sbi->s_md_lock);
4762 * ext4_free_blocks() -- Free given blocks and update quota
4763 * @handle: handle for this transaction
4765 * @block: start physical block to free
4766 * @count: number of blocks to count
4767 * @flags: flags used by ext4_free_blocks
4769 void ext4_free_blocks(handle_t *handle, struct inode *inode,
4770 struct buffer_head *bh, ext4_fsblk_t block,
4771 unsigned long count, int flags)
4773 struct buffer_head *bitmap_bh = NULL;
4774 struct super_block *sb = inode->i_sb;
4775 struct ext4_group_desc *gdp;
4776 unsigned int overflow;
4778 struct buffer_head *gd_bh;
4779 ext4_group_t block_group;
4780 struct ext4_sb_info *sbi;
4781 struct ext4_buddy e4b;
4782 unsigned int count_clusters;
4789 BUG_ON(block != bh->b_blocknr);
4791 block = bh->b_blocknr;
4795 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
4796 !ext4_inode_block_valid(inode, block, count)) {
4797 ext4_error(sb, "Freeing blocks not in datazone - "
4798 "block = %llu, count = %lu", block, count);
4802 ext4_debug("freeing block %llu\n", block);
4803 trace_ext4_free_blocks(inode, block, count, flags);
4805 if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4808 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4813 * If the extent to be freed does not begin on a cluster
4814 * boundary, we need to deal with partial clusters at the
4815 * beginning and end of the extent. Normally we will free
4816 * blocks at the beginning or the end unless we are explicitly
4817 * requested to avoid doing so.
4819 overflow = EXT4_PBLK_COFF(sbi, block);
4821 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
4822 overflow = sbi->s_cluster_ratio - overflow;
4824 if (count > overflow)
4833 overflow = EXT4_LBLK_COFF(sbi, count);
4835 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
4836 if (count > overflow)
4841 count += sbi->s_cluster_ratio - overflow;
4844 if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4846 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
4848 for (i = 0; i < count; i++) {
4851 bh = sb_find_get_block(inode->i_sb, block + i);
4852 ext4_forget(handle, is_metadata, inode, bh, block + i);
4858 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4860 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
4861 ext4_get_group_info(sb, block_group))))
4865 * Check to see if we are freeing blocks across a group
4868 if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4869 overflow = EXT4_C2B(sbi, bit) + count -
4870 EXT4_BLOCKS_PER_GROUP(sb);
4873 count_clusters = EXT4_NUM_B2C(sbi, count);
4874 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4875 if (IS_ERR(bitmap_bh)) {
4876 err = PTR_ERR(bitmap_bh);
4880 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4886 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4887 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4888 in_range(block, ext4_inode_table(sb, gdp),
4889 EXT4_SB(sb)->s_itb_per_group) ||
4890 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4891 EXT4_SB(sb)->s_itb_per_group)) {
4893 ext4_error(sb, "Freeing blocks in system zone - "
4894 "Block = %llu, count = %lu", block, count);
4895 /* err = 0. ext4_std_error should be a no op */
4899 BUFFER_TRACE(bitmap_bh, "getting write access");
4900 err = ext4_journal_get_write_access(handle, bitmap_bh);
4905 * We are about to modify some metadata. Call the journal APIs
4906 * to unshare ->b_data if a currently-committing transaction is
4909 BUFFER_TRACE(gd_bh, "get_write_access");
4910 err = ext4_journal_get_write_access(handle, gd_bh);
4913 #ifdef AGGRESSIVE_CHECK
4916 for (i = 0; i < count_clusters; i++)
4917 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4920 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
4922 /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
4923 err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
4924 GFP_NOFS|__GFP_NOFAIL);
4929 * We need to make sure we don't reuse the freed block until after the
4930 * transaction is committed. We make an exception if the inode is to be
4931 * written in writeback mode since writeback mode has weak data
4932 * consistency guarantees.
4934 if (ext4_handle_valid(handle) &&
4935 ((flags & EXT4_FREE_BLOCKS_METADATA) ||
4936 !ext4_should_writeback_data(inode))) {
4937 struct ext4_free_data *new_entry;
4939 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
4942 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
4943 GFP_NOFS|__GFP_NOFAIL);
4944 new_entry->efd_start_cluster = bit;
4945 new_entry->efd_group = block_group;
4946 new_entry->efd_count = count_clusters;
4947 new_entry->efd_tid = handle->h_transaction->t_tid;
4949 ext4_lock_group(sb, block_group);
4950 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4951 ext4_mb_free_metadata(handle, &e4b, new_entry);
4953 /* need to update group_info->bb_free and bitmap
4954 * with group lock held. generate_buddy look at
4955 * them with group lock_held
4957 if (test_opt(sb, DISCARD)) {
4958 err = ext4_issue_discard(sb, block_group, bit, count,
4960 if (err && err != -EOPNOTSUPP)
4961 ext4_msg(sb, KERN_WARNING, "discard request in"
4962 " group:%d block:%d count:%lu failed"
4963 " with %d", block_group, bit, count,
4966 EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
4968 ext4_lock_group(sb, block_group);
4969 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4970 mb_free_blocks(inode, &e4b, bit, count_clusters);
4973 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
4974 ext4_free_group_clusters_set(sb, gdp, ret);
4975 ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
4976 ext4_group_desc_csum_set(sb, block_group, gdp);
4977 ext4_unlock_group(sb, block_group);
4979 if (sbi->s_log_groups_per_flex) {
4980 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4981 atomic64_add(count_clusters,
4982 &sbi_array_rcu_deref(sbi, s_flex_groups,
4983 flex_group)->free_clusters);
4986 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
4987 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
4988 percpu_counter_add(&sbi->s_freeclusters_counter, count_clusters);
4990 ext4_mb_unload_buddy(&e4b);
4992 /* We dirtied the bitmap block */
4993 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4994 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4996 /* And the group descriptor block */
4997 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4998 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5002 if (overflow && !err) {
5010 ext4_std_error(sb, err);
5015 * ext4_group_add_blocks() -- Add given blocks to an existing group
5016 * @handle: handle to this transaction
5018 * @block: start physical block to add to the block group
5019 * @count: number of blocks to free
5021 * This marks the blocks as free in the bitmap and buddy.
5023 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
5024 ext4_fsblk_t block, unsigned long count)
5026 struct buffer_head *bitmap_bh = NULL;
5027 struct buffer_head *gd_bh;
5028 ext4_group_t block_group;
5031 struct ext4_group_desc *desc;
5032 struct ext4_sb_info *sbi = EXT4_SB(sb);
5033 struct ext4_buddy e4b;
5034 int err = 0, ret, blk_free_count;
5035 ext4_grpblk_t blocks_freed;
5037 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
5042 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5044 * Check to see if we are freeing blocks across a group
5047 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
5048 ext4_warning(sb, "too much blocks added to group %u",
5054 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
5055 if (IS_ERR(bitmap_bh)) {
5056 err = PTR_ERR(bitmap_bh);
5061 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
5067 if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
5068 in_range(ext4_inode_bitmap(sb, desc), block, count) ||
5069 in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
5070 in_range(block + count - 1, ext4_inode_table(sb, desc),
5071 sbi->s_itb_per_group)) {
5072 ext4_error(sb, "Adding blocks in system zones - "
5073 "Block = %llu, count = %lu",
5079 BUFFER_TRACE(bitmap_bh, "getting write access");
5080 err = ext4_journal_get_write_access(handle, bitmap_bh);
5085 * We are about to modify some metadata. Call the journal APIs
5086 * to unshare ->b_data if a currently-committing transaction is
5089 BUFFER_TRACE(gd_bh, "get_write_access");
5090 err = ext4_journal_get_write_access(handle, gd_bh);
5094 for (i = 0, blocks_freed = 0; i < count; i++) {
5095 BUFFER_TRACE(bitmap_bh, "clear bit");
5096 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
5097 ext4_error(sb, "bit already cleared for block %llu",
5098 (ext4_fsblk_t)(block + i));
5099 BUFFER_TRACE(bitmap_bh, "bit already cleared");
5105 err = ext4_mb_load_buddy(sb, block_group, &e4b);
5110 * need to update group_info->bb_free and bitmap
5111 * with group lock held. generate_buddy look at
5112 * them with group lock_held
5114 ext4_lock_group(sb, block_group);
5115 mb_clear_bits(bitmap_bh->b_data, bit, count);
5116 mb_free_blocks(NULL, &e4b, bit, count);
5117 blk_free_count = blocks_freed + ext4_free_group_clusters(sb, desc);
5118 ext4_free_group_clusters_set(sb, desc, blk_free_count);
5119 ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
5120 ext4_group_desc_csum_set(sb, block_group, desc);
5121 ext4_unlock_group(sb, block_group);
5122 percpu_counter_add(&sbi->s_freeclusters_counter,
5123 EXT4_NUM_B2C(sbi, blocks_freed));
5125 if (sbi->s_log_groups_per_flex) {
5126 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5127 atomic64_add(EXT4_NUM_B2C(sbi, blocks_freed),
5128 &sbi_array_rcu_deref(sbi, s_flex_groups,
5129 flex_group)->free_clusters);
5132 ext4_mb_unload_buddy(&e4b);
5134 /* We dirtied the bitmap block */
5135 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5136 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5138 /* And the group descriptor block */
5139 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5140 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5146 ext4_std_error(sb, err);
5151 * ext4_trim_extent -- function to TRIM one single free extent in the group
5152 * @sb: super block for the file system
5153 * @start: starting block of the free extent in the alloc. group
5154 * @count: number of blocks to TRIM
5155 * @group: alloc. group we are working with
5156 * @e4b: ext4 buddy for the group
5158 * Trim "count" blocks starting at "start" in the "group". To assure that no
5159 * one will allocate those blocks, mark it as used in buddy bitmap. This must
5160 * be called with under the group lock.
5162 static int ext4_trim_extent(struct super_block *sb, int start, int count,
5163 ext4_group_t group, struct ext4_buddy *e4b)
5167 struct ext4_free_extent ex;
5170 trace_ext4_trim_extent(sb, group, start, count);
5172 assert_spin_locked(ext4_group_lock_ptr(sb, group));
5174 ex.fe_start = start;
5175 ex.fe_group = group;
5179 * Mark blocks used, so no one can reuse them while
5182 mb_mark_used(e4b, &ex);
5183 ext4_unlock_group(sb, group);
5184 ret = ext4_issue_discard(sb, group, start, count, NULL);
5185 ext4_lock_group(sb, group);
5186 mb_free_blocks(NULL, e4b, start, ex.fe_len);
5191 * ext4_trim_all_free -- function to trim all free space in alloc. group
5192 * @sb: super block for file system
5193 * @group: group to be trimmed
5194 * @start: first group block to examine
5195 * @max: last group block to examine
5196 * @minblocks: minimum extent block count
5198 * ext4_trim_all_free walks through group's buddy bitmap searching for free
5199 * extents. When the free block is found, ext4_trim_extent is called to TRIM
5203 * ext4_trim_all_free walks through group's block bitmap searching for free
5204 * extents. When the free extent is found, mark it as used in group buddy
5205 * bitmap. Then issue a TRIM command on this extent and free the extent in
5206 * the group buddy bitmap. This is done until whole group is scanned.
5208 static ext4_grpblk_t
5209 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
5210 ext4_grpblk_t start, ext4_grpblk_t max,
5211 ext4_grpblk_t minblocks)
5214 ext4_grpblk_t next, count = 0, free_count = 0;
5215 struct ext4_buddy e4b;
5218 trace_ext4_trim_all_free(sb, group, start, max);
5220 ret = ext4_mb_load_buddy(sb, group, &e4b);
5222 ext4_warning(sb, "Error %d loading buddy information for %u",
5226 bitmap = e4b.bd_bitmap;
5228 ext4_lock_group(sb, group);
5229 if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
5230 minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
5233 start = (e4b.bd_info->bb_first_free > start) ?
5234 e4b.bd_info->bb_first_free : start;
5236 while (start <= max) {
5237 start = mb_find_next_zero_bit(bitmap, max + 1, start);
5240 next = mb_find_next_bit(bitmap, max + 1, start);
5242 if ((next - start) >= minblocks) {
5243 ret = ext4_trim_extent(sb, start,
5244 next - start, group, &e4b);
5245 if (ret && ret != -EOPNOTSUPP)
5248 count += next - start;
5250 free_count += next - start;
5253 if (fatal_signal_pending(current)) {
5254 count = -ERESTARTSYS;
5258 if (need_resched()) {
5259 ext4_unlock_group(sb, group);
5261 ext4_lock_group(sb, group);
5264 if ((e4b.bd_info->bb_free - free_count) < minblocks)
5270 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
5273 ext4_unlock_group(sb, group);
5274 ext4_mb_unload_buddy(&e4b);
5276 ext4_debug("trimmed %d blocks in the group %d\n",
5283 * ext4_trim_fs() -- trim ioctl handle function
5284 * @sb: superblock for filesystem
5285 * @range: fstrim_range structure
5287 * start: First Byte to trim
5288 * len: number of Bytes to trim from start
5289 * minlen: minimum extent length in Bytes
5290 * ext4_trim_fs goes through all allocation groups containing Bytes from
5291 * start to start+len. For each such a group ext4_trim_all_free function
5292 * is invoked to trim all free space.
5294 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
5296 struct request_queue *q = bdev_get_queue(sb->s_bdev);
5297 struct ext4_group_info *grp;
5298 ext4_group_t group, first_group, last_group;
5299 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5300 uint64_t start, end, minlen, trimmed = 0;
5301 ext4_fsblk_t first_data_blk =
5302 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5303 ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
5306 start = range->start >> sb->s_blocksize_bits;
5307 end = start + (range->len >> sb->s_blocksize_bits) - 1;
5308 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5309 range->minlen >> sb->s_blocksize_bits);
5311 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
5312 start >= max_blks ||
5313 range->len < sb->s_blocksize)
5315 /* No point to try to trim less than discard granularity */
5316 if (range->minlen < q->limits.discard_granularity) {
5317 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5318 q->limits.discard_granularity >> sb->s_blocksize_bits);
5319 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
5322 if (end >= max_blks)
5324 if (end <= first_data_blk)
5326 if (start < first_data_blk)
5327 start = first_data_blk;
5329 /* Determine first and last group to examine based on start and end */
5330 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
5331 &first_group, &first_cluster);
5332 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
5333 &last_group, &last_cluster);
5335 /* end now represents the last cluster to discard in this group */
5336 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5338 for (group = first_group; group <= last_group; group++) {
5339 grp = ext4_get_group_info(sb, group);
5340 /* We only do this if the grp has never been initialized */
5341 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
5342 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
5348 * For all the groups except the last one, last cluster will
5349 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
5350 * change it for the last group, note that last_cluster is
5351 * already computed earlier by ext4_get_group_no_and_offset()
5353 if (group == last_group)
5356 if (grp->bb_free >= minlen) {
5357 cnt = ext4_trim_all_free(sb, group, first_cluster,
5367 * For every group except the first one, we are sure
5368 * that the first cluster to discard will be cluster #0.
5374 atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
5377 range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
5381 /* Iterate all the free extents in the group. */
5383 ext4_mballoc_query_range(
5384 struct super_block *sb,
5386 ext4_grpblk_t start,
5388 ext4_mballoc_query_range_fn formatter,
5393 struct ext4_buddy e4b;
5396 error = ext4_mb_load_buddy(sb, group, &e4b);
5399 bitmap = e4b.bd_bitmap;
5401 ext4_lock_group(sb, group);
5403 start = (e4b.bd_info->bb_first_free > start) ?
5404 e4b.bd_info->bb_first_free : start;
5405 if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
5406 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5408 while (start <= end) {
5409 start = mb_find_next_zero_bit(bitmap, end + 1, start);
5412 next = mb_find_next_bit(bitmap, end + 1, start);
5414 ext4_unlock_group(sb, group);
5415 error = formatter(sb, group, start, next - start, priv);
5418 ext4_lock_group(sb, group);
5423 ext4_unlock_group(sb, group);
5425 ext4_mb_unload_buddy(&e4b);