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);
3119 struct ext4_super_block *es = sbi->s_es;
3122 loff_t size, start_off;
3123 loff_t orig_size __maybe_unused;
3125 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3126 struct ext4_prealloc_space *pa;
3128 /* do normalize only data requests, metadata requests
3129 do not need preallocation */
3130 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3133 /* sometime caller may want exact blocks */
3134 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3137 /* caller may indicate that preallocation isn't
3138 * required (it's a tail, for example) */
3139 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3142 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3143 ext4_mb_normalize_group_request(ac);
3147 bsbits = ac->ac_sb->s_blocksize_bits;
3149 /* first, let's learn actual file size
3150 * given current request is allocated */
3151 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
3152 size = size << bsbits;
3153 if (size < i_size_read(ac->ac_inode))
3154 size = i_size_read(ac->ac_inode);
3157 /* max size of free chunks */
3160 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
3161 (req <= (size) || max <= (chunk_size))
3163 /* first, try to predict filesize */
3164 /* XXX: should this table be tunable? */
3166 if (size <= 16 * 1024) {
3168 } else if (size <= 32 * 1024) {
3170 } else if (size <= 64 * 1024) {
3172 } else if (size <= 128 * 1024) {
3174 } else if (size <= 256 * 1024) {
3176 } else if (size <= 512 * 1024) {
3178 } else if (size <= 1024 * 1024) {
3180 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3181 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3182 (21 - bsbits)) << 21;
3183 size = 2 * 1024 * 1024;
3184 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3185 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3186 (22 - bsbits)) << 22;
3187 size = 4 * 1024 * 1024;
3188 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3189 (8<<20)>>bsbits, max, 8 * 1024)) {
3190 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3191 (23 - bsbits)) << 23;
3192 size = 8 * 1024 * 1024;
3194 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
3195 size = (loff_t) EXT4_C2B(EXT4_SB(ac->ac_sb),
3196 ac->ac_o_ex.fe_len) << bsbits;
3198 size = size >> bsbits;
3199 start = start_off >> bsbits;
3202 * For tiny groups (smaller than 8MB) the chosen allocation
3203 * alignment may be larger than group size. Make sure the
3204 * alignment does not move allocation to a different group which
3205 * makes mballoc fail assertions later.
3207 start = max(start, rounddown(ac->ac_o_ex.fe_logical,
3208 (ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
3210 /* don't cover already allocated blocks in selected range */
3211 if (ar->pleft && start <= ar->lleft) {
3212 size -= ar->lleft + 1 - start;
3213 start = ar->lleft + 1;
3215 if (ar->pright && start + size - 1 >= ar->lright)
3216 size -= start + size - ar->lright;
3219 * Trim allocation request for filesystems with artificially small
3222 if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
3223 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
3227 /* check we don't cross already preallocated blocks */
3229 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3234 spin_lock(&pa->pa_lock);
3235 if (pa->pa_deleted) {
3236 spin_unlock(&pa->pa_lock);
3240 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3243 /* PA must not overlap original request */
3244 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3245 ac->ac_o_ex.fe_logical < pa->pa_lstart));
3247 /* skip PAs this normalized request doesn't overlap with */
3248 if (pa->pa_lstart >= end || pa_end <= start) {
3249 spin_unlock(&pa->pa_lock);
3252 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3254 /* adjust start or end to be adjacent to this pa */
3255 if (pa_end <= ac->ac_o_ex.fe_logical) {
3256 BUG_ON(pa_end < start);
3258 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3259 BUG_ON(pa->pa_lstart > end);
3260 end = pa->pa_lstart;
3262 spin_unlock(&pa->pa_lock);
3267 /* XXX: extra loop to check we really don't overlap preallocations */
3269 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3272 spin_lock(&pa->pa_lock);
3273 if (pa->pa_deleted == 0) {
3274 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3276 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3278 spin_unlock(&pa->pa_lock);
3282 if (start + size <= ac->ac_o_ex.fe_logical &&
3283 start > ac->ac_o_ex.fe_logical) {
3284 ext4_msg(ac->ac_sb, KERN_ERR,
3285 "start %lu, size %lu, fe_logical %lu",
3286 (unsigned long) start, (unsigned long) size,
3287 (unsigned long) ac->ac_o_ex.fe_logical);
3290 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3292 /* now prepare goal request */
3294 /* XXX: is it better to align blocks WRT to logical
3295 * placement or satisfy big request as is */
3296 ac->ac_g_ex.fe_logical = start;
3297 ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3299 /* define goal start in order to merge */
3300 if (ar->pright && (ar->lright == (start + size)) &&
3301 ar->pright >= size &&
3302 ar->pright - size >= le32_to_cpu(es->s_first_data_block)) {
3303 /* merge to the right */
3304 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3305 &ac->ac_g_ex.fe_group,
3306 &ac->ac_g_ex.fe_start);
3307 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3309 if (ar->pleft && (ar->lleft + 1 == start) &&
3310 ar->pleft + 1 < ext4_blocks_count(es)) {
3311 /* merge to the left */
3312 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3313 &ac->ac_g_ex.fe_group,
3314 &ac->ac_g_ex.fe_start);
3315 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3318 mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3319 (unsigned) orig_size, (unsigned) start);
3322 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3324 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3326 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3327 atomic_inc(&sbi->s_bal_reqs);
3328 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3329 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3330 atomic_inc(&sbi->s_bal_success);
3331 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3332 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3333 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3334 atomic_inc(&sbi->s_bal_goals);
3335 if (ac->ac_found > sbi->s_mb_max_to_scan)
3336 atomic_inc(&sbi->s_bal_breaks);
3339 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3340 trace_ext4_mballoc_alloc(ac);
3342 trace_ext4_mballoc_prealloc(ac);
3346 * Called on failure; free up any blocks from the inode PA for this
3347 * context. We don't need this for MB_GROUP_PA because we only change
3348 * pa_free in ext4_mb_release_context(), but on failure, we've already
3349 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3351 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3353 struct ext4_prealloc_space *pa = ac->ac_pa;
3354 struct ext4_buddy e4b;
3358 if (ac->ac_f_ex.fe_len == 0)
3360 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
3363 * This should never happen since we pin the
3364 * pages in the ext4_allocation_context so
3365 * ext4_mb_load_buddy() should never fail.
3367 WARN(1, "mb_load_buddy failed (%d)", err);
3370 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3371 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
3372 ac->ac_f_ex.fe_len);
3373 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3374 ext4_mb_unload_buddy(&e4b);
3377 if (pa->pa_type == MB_INODE_PA)
3378 pa->pa_free += ac->ac_b_ex.fe_len;
3382 * use blocks preallocated to inode
3384 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3385 struct ext4_prealloc_space *pa)
3387 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3392 /* found preallocated blocks, use them */
3393 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3394 end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
3395 start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
3396 len = EXT4_NUM_B2C(sbi, end - start);
3397 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3398 &ac->ac_b_ex.fe_start);
3399 ac->ac_b_ex.fe_len = len;
3400 ac->ac_status = AC_STATUS_FOUND;
3403 BUG_ON(start < pa->pa_pstart);
3404 BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3405 BUG_ON(pa->pa_free < len);
3406 BUG_ON(ac->ac_b_ex.fe_len <= 0);
3409 mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3413 * use blocks preallocated to locality group
3415 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3416 struct ext4_prealloc_space *pa)
3418 unsigned int len = ac->ac_o_ex.fe_len;
3420 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3421 &ac->ac_b_ex.fe_group,
3422 &ac->ac_b_ex.fe_start);
3423 ac->ac_b_ex.fe_len = len;
3424 ac->ac_status = AC_STATUS_FOUND;
3427 /* we don't correct pa_pstart or pa_plen here to avoid
3428 * possible race when the group is being loaded concurrently
3429 * instead we correct pa later, after blocks are marked
3430 * in on-disk bitmap -- see ext4_mb_release_context()
3431 * Other CPUs are prevented from allocating from this pa by lg_mutex
3433 mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3437 * Return the prealloc space that have minimal distance
3438 * from the goal block. @cpa is the prealloc
3439 * space that is having currently known minimal distance
3440 * from the goal block.
3442 static struct ext4_prealloc_space *
3443 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3444 struct ext4_prealloc_space *pa,
3445 struct ext4_prealloc_space *cpa)
3447 ext4_fsblk_t cur_distance, new_distance;
3450 atomic_inc(&pa->pa_count);
3453 cur_distance = abs(goal_block - cpa->pa_pstart);
3454 new_distance = abs(goal_block - pa->pa_pstart);
3456 if (cur_distance <= new_distance)
3459 /* drop the previous reference */
3460 atomic_dec(&cpa->pa_count);
3461 atomic_inc(&pa->pa_count);
3466 * search goal blocks in preallocated space
3468 static noinline_for_stack int
3469 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3471 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3473 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3474 struct ext4_locality_group *lg;
3475 struct ext4_prealloc_space *pa, *cpa = NULL;
3476 ext4_fsblk_t goal_block;
3478 /* only data can be preallocated */
3479 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3482 /* first, try per-file preallocation */
3484 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3486 /* all fields in this condition don't change,
3487 * so we can skip locking for them */
3488 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3489 ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
3490 EXT4_C2B(sbi, pa->pa_len)))
3493 /* non-extent files can't have physical blocks past 2^32 */
3494 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3495 (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
3496 EXT4_MAX_BLOCK_FILE_PHYS))
3499 /* found preallocated blocks, use them */
3500 spin_lock(&pa->pa_lock);
3501 if (pa->pa_deleted == 0 && pa->pa_free) {
3502 atomic_inc(&pa->pa_count);
3503 ext4_mb_use_inode_pa(ac, pa);
3504 spin_unlock(&pa->pa_lock);
3505 ac->ac_criteria = 10;
3509 spin_unlock(&pa->pa_lock);
3513 /* can we use group allocation? */
3514 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3517 /* inode may have no locality group for some reason */
3521 order = fls(ac->ac_o_ex.fe_len) - 1;
3522 if (order > PREALLOC_TB_SIZE - 1)
3523 /* The max size of hash table is PREALLOC_TB_SIZE */
3524 order = PREALLOC_TB_SIZE - 1;
3526 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3528 * search for the prealloc space that is having
3529 * minimal distance from the goal block.
3531 for (i = order; i < PREALLOC_TB_SIZE; i++) {
3533 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3535 spin_lock(&pa->pa_lock);
3536 if (pa->pa_deleted == 0 &&
3537 pa->pa_free >= ac->ac_o_ex.fe_len) {
3539 cpa = ext4_mb_check_group_pa(goal_block,
3542 spin_unlock(&pa->pa_lock);
3547 ext4_mb_use_group_pa(ac, cpa);
3548 ac->ac_criteria = 20;
3555 * the function goes through all block freed in the group
3556 * but not yet committed and marks them used in in-core bitmap.
3557 * buddy must be generated from this bitmap
3558 * Need to be called with the ext4 group lock held
3560 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3564 struct ext4_group_info *grp;
3565 struct ext4_free_data *entry;
3567 grp = ext4_get_group_info(sb, group);
3568 n = rb_first(&(grp->bb_free_root));
3571 entry = rb_entry(n, struct ext4_free_data, efd_node);
3572 ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
3579 * the function goes through all preallocation in this group and marks them
3580 * used in in-core bitmap. buddy must be generated from this bitmap
3581 * Need to be called with ext4 group lock held
3583 static noinline_for_stack
3584 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3587 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3588 struct ext4_prealloc_space *pa;
3589 struct list_head *cur;
3590 ext4_group_t groupnr;
3591 ext4_grpblk_t start;
3592 int preallocated = 0;
3595 /* all form of preallocation discards first load group,
3596 * so the only competing code is preallocation use.
3597 * we don't need any locking here
3598 * notice we do NOT ignore preallocations with pa_deleted
3599 * otherwise we could leave used blocks available for
3600 * allocation in buddy when concurrent ext4_mb_put_pa()
3601 * is dropping preallocation
3603 list_for_each(cur, &grp->bb_prealloc_list) {
3604 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3605 spin_lock(&pa->pa_lock);
3606 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3609 spin_unlock(&pa->pa_lock);
3610 if (unlikely(len == 0))
3612 BUG_ON(groupnr != group);
3613 ext4_set_bits(bitmap, start, len);
3614 preallocated += len;
3616 mb_debug(1, "preallocated %u for group %u\n", preallocated, group);
3619 static void ext4_mb_pa_callback(struct rcu_head *head)
3621 struct ext4_prealloc_space *pa;
3622 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3624 BUG_ON(atomic_read(&pa->pa_count));
3625 BUG_ON(pa->pa_deleted == 0);
3626 kmem_cache_free(ext4_pspace_cachep, pa);
3630 * drops a reference to preallocated space descriptor
3631 * if this was the last reference and the space is consumed
3633 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3634 struct super_block *sb, struct ext4_prealloc_space *pa)
3637 ext4_fsblk_t grp_blk;
3639 /* in this short window concurrent discard can set pa_deleted */
3640 spin_lock(&pa->pa_lock);
3641 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
3642 spin_unlock(&pa->pa_lock);
3646 if (pa->pa_deleted == 1) {
3647 spin_unlock(&pa->pa_lock);
3652 spin_unlock(&pa->pa_lock);
3654 grp_blk = pa->pa_pstart;
3656 * If doing group-based preallocation, pa_pstart may be in the
3657 * next group when pa is used up
3659 if (pa->pa_type == MB_GROUP_PA)
3662 grp = ext4_get_group_number(sb, grp_blk);
3667 * P1 (buddy init) P2 (regular allocation)
3668 * find block B in PA
3669 * copy on-disk bitmap to buddy
3670 * mark B in on-disk bitmap
3671 * drop PA from group
3672 * mark all PAs in buddy
3674 * thus, P1 initializes buddy with B available. to prevent this
3675 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3678 ext4_lock_group(sb, grp);
3679 list_del(&pa->pa_group_list);
3680 ext4_unlock_group(sb, grp);
3682 spin_lock(pa->pa_obj_lock);
3683 list_del_rcu(&pa->pa_inode_list);
3684 spin_unlock(pa->pa_obj_lock);
3686 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3690 * creates new preallocated space for given inode
3692 static noinline_for_stack int
3693 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3695 struct super_block *sb = ac->ac_sb;
3696 struct ext4_sb_info *sbi = EXT4_SB(sb);
3697 struct ext4_prealloc_space *pa;
3698 struct ext4_group_info *grp;
3699 struct ext4_inode_info *ei;
3701 /* preallocate only when found space is larger then requested */
3702 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3703 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3704 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3706 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3710 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3714 /* we can't allocate as much as normalizer wants.
3715 * so, found space must get proper lstart
3716 * to cover original request */
3717 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3718 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3721 * Use the below logic for adjusting best extent as it keeps
3722 * fragmentation in check while ensuring logical range of best
3723 * extent doesn't overflow out of goal extent:
3725 * 1. Check if best ex can be kept at end of goal and still
3726 * cover original start
3727 * 2. Else, check if best ex can be kept at start of goal and
3728 * still cover original start
3729 * 3. Else, keep the best ex at start of original request.
3731 new_bex_end = ac->ac_g_ex.fe_logical +
3732 EXT4_C2B(sbi, ac->ac_g_ex.fe_len);
3733 new_bex_start = new_bex_end - EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3734 if (ac->ac_o_ex.fe_logical >= new_bex_start)
3737 new_bex_start = ac->ac_g_ex.fe_logical;
3739 new_bex_start + EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3740 if (ac->ac_o_ex.fe_logical < new_bex_end)
3743 new_bex_start = ac->ac_o_ex.fe_logical;
3745 new_bex_start + EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3748 ac->ac_b_ex.fe_logical = new_bex_start;
3750 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3751 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3752 BUG_ON(new_bex_end > (ac->ac_g_ex.fe_logical +
3753 EXT4_C2B(sbi, ac->ac_g_ex.fe_len)));
3756 /* preallocation can change ac_b_ex, thus we store actually
3757 * allocated blocks for history */
3758 ac->ac_f_ex = ac->ac_b_ex;
3760 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3761 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3762 pa->pa_len = ac->ac_b_ex.fe_len;
3763 pa->pa_free = pa->pa_len;
3764 atomic_set(&pa->pa_count, 1);
3765 spin_lock_init(&pa->pa_lock);
3766 INIT_LIST_HEAD(&pa->pa_inode_list);
3767 INIT_LIST_HEAD(&pa->pa_group_list);
3769 pa->pa_type = MB_INODE_PA;
3771 mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3772 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3773 trace_ext4_mb_new_inode_pa(ac, pa);
3775 ext4_mb_use_inode_pa(ac, pa);
3776 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
3778 ei = EXT4_I(ac->ac_inode);
3779 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3781 pa->pa_obj_lock = &ei->i_prealloc_lock;
3782 pa->pa_inode = ac->ac_inode;
3784 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3785 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3786 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3788 spin_lock(pa->pa_obj_lock);
3789 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3790 spin_unlock(pa->pa_obj_lock);
3796 * creates new preallocated space for locality group inodes belongs to
3798 static noinline_for_stack int
3799 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3801 struct super_block *sb = ac->ac_sb;
3802 struct ext4_locality_group *lg;
3803 struct ext4_prealloc_space *pa;
3804 struct ext4_group_info *grp;
3806 /* preallocate only when found space is larger then requested */
3807 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3808 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3809 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3811 BUG_ON(ext4_pspace_cachep == NULL);
3812 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3816 /* preallocation can change ac_b_ex, thus we store actually
3817 * allocated blocks for history */
3818 ac->ac_f_ex = ac->ac_b_ex;
3820 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3821 pa->pa_lstart = pa->pa_pstart;
3822 pa->pa_len = ac->ac_b_ex.fe_len;
3823 pa->pa_free = pa->pa_len;
3824 atomic_set(&pa->pa_count, 1);
3825 spin_lock_init(&pa->pa_lock);
3826 INIT_LIST_HEAD(&pa->pa_inode_list);
3827 INIT_LIST_HEAD(&pa->pa_group_list);
3829 pa->pa_type = MB_GROUP_PA;
3831 mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3832 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3833 trace_ext4_mb_new_group_pa(ac, pa);
3835 ext4_mb_use_group_pa(ac, pa);
3836 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3838 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3842 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3843 pa->pa_inode = NULL;
3845 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3846 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3847 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3850 * We will later add the new pa to the right bucket
3851 * after updating the pa_free in ext4_mb_release_context
3856 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3860 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3861 err = ext4_mb_new_group_pa(ac);
3863 err = ext4_mb_new_inode_pa(ac);
3868 * finds all unused blocks in on-disk bitmap, frees them in
3869 * in-core bitmap and buddy.
3870 * @pa must be unlinked from inode and group lists, so that
3871 * nobody else can find/use it.
3872 * the caller MUST hold group/inode locks.
3873 * TODO: optimize the case when there are no in-core structures yet
3875 static noinline_for_stack int
3876 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3877 struct ext4_prealloc_space *pa)
3879 struct super_block *sb = e4b->bd_sb;
3880 struct ext4_sb_info *sbi = EXT4_SB(sb);
3885 unsigned long long grp_blk_start;
3889 BUG_ON(pa->pa_deleted == 0);
3890 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3891 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
3892 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3893 end = bit + pa->pa_len;
3896 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3899 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3900 mb_debug(1, " free preallocated %u/%u in group %u\n",
3901 (unsigned) ext4_group_first_block_no(sb, group) + bit,
3902 (unsigned) next - bit, (unsigned) group);
3905 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
3906 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
3907 EXT4_C2B(sbi, bit)),
3909 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3912 if (free != pa->pa_free) {
3913 ext4_msg(e4b->bd_sb, KERN_CRIT,
3914 "pa %p: logic %lu, phys. %lu, len %lu",
3915 pa, (unsigned long) pa->pa_lstart,
3916 (unsigned long) pa->pa_pstart,
3917 (unsigned long) pa->pa_len);
3918 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
3921 * pa is already deleted so we use the value obtained
3922 * from the bitmap and continue.
3925 atomic_add(free, &sbi->s_mb_discarded);
3930 static noinline_for_stack int
3931 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3932 struct ext4_prealloc_space *pa)
3934 struct super_block *sb = e4b->bd_sb;
3938 trace_ext4_mb_release_group_pa(sb, pa);
3939 BUG_ON(pa->pa_deleted == 0);
3940 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3941 if (unlikely(group != e4b->bd_group && pa->pa_len != 0)) {
3942 ext4_warning(sb, "bad group: expected %u, group %u, pa_start %llu",
3943 e4b->bd_group, group, pa->pa_pstart);
3946 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3947 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3948 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3954 * releases all preallocations in given group
3956 * first, we need to decide discard policy:
3957 * - when do we discard
3959 * - how many do we discard
3960 * 1) how many requested
3962 static noinline_for_stack int
3963 ext4_mb_discard_group_preallocations(struct super_block *sb,
3964 ext4_group_t group, int needed)
3966 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3967 struct buffer_head *bitmap_bh = NULL;
3968 struct ext4_prealloc_space *pa, *tmp;
3969 struct list_head list;
3970 struct ext4_buddy e4b;
3975 mb_debug(1, "discard preallocation for group %u\n", group);
3977 if (list_empty(&grp->bb_prealloc_list))
3980 bitmap_bh = ext4_read_block_bitmap(sb, group);
3981 if (IS_ERR(bitmap_bh)) {
3982 err = PTR_ERR(bitmap_bh);
3983 ext4_error(sb, "Error %d reading block bitmap for %u",
3988 err = ext4_mb_load_buddy(sb, group, &e4b);
3990 ext4_warning(sb, "Error %d loading buddy information for %u",
3997 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
3999 INIT_LIST_HEAD(&list);
4001 ext4_lock_group(sb, group);
4002 list_for_each_entry_safe(pa, tmp,
4003 &grp->bb_prealloc_list, pa_group_list) {
4004 spin_lock(&pa->pa_lock);
4005 if (atomic_read(&pa->pa_count)) {
4006 spin_unlock(&pa->pa_lock);
4010 if (pa->pa_deleted) {
4011 spin_unlock(&pa->pa_lock);
4015 /* seems this one can be freed ... */
4018 /* we can trust pa_free ... */
4019 free += pa->pa_free;
4021 spin_unlock(&pa->pa_lock);
4023 list_del(&pa->pa_group_list);
4024 list_add(&pa->u.pa_tmp_list, &list);
4027 /* if we still need more blocks and some PAs were used, try again */
4028 if (free < needed && busy) {
4030 ext4_unlock_group(sb, group);
4035 /* found anything to free? */
4036 if (list_empty(&list)) {
4041 /* now free all selected PAs */
4042 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4044 /* remove from object (inode or locality group) */
4045 spin_lock(pa->pa_obj_lock);
4046 list_del_rcu(&pa->pa_inode_list);
4047 spin_unlock(pa->pa_obj_lock);
4049 if (pa->pa_type == MB_GROUP_PA)
4050 ext4_mb_release_group_pa(&e4b, pa);
4052 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4054 list_del(&pa->u.pa_tmp_list);
4055 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4059 ext4_unlock_group(sb, group);
4060 ext4_mb_unload_buddy(&e4b);
4066 * releases all non-used preallocated blocks for given inode
4068 * It's important to discard preallocations under i_data_sem
4069 * We don't want another block to be served from the prealloc
4070 * space when we are discarding the inode prealloc space.
4072 * FIXME!! Make sure it is valid at all the call sites
4074 void ext4_discard_preallocations(struct inode *inode)
4076 struct ext4_inode_info *ei = EXT4_I(inode);
4077 struct super_block *sb = inode->i_sb;
4078 struct buffer_head *bitmap_bh = NULL;
4079 struct ext4_prealloc_space *pa, *tmp;
4080 ext4_group_t group = 0;
4081 struct list_head list;
4082 struct ext4_buddy e4b;
4085 if (!S_ISREG(inode->i_mode)) {
4086 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4090 mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
4091 trace_ext4_discard_preallocations(inode);
4093 INIT_LIST_HEAD(&list);
4096 /* first, collect all pa's in the inode */
4097 spin_lock(&ei->i_prealloc_lock);
4098 while (!list_empty(&ei->i_prealloc_list)) {
4099 pa = list_entry(ei->i_prealloc_list.next,
4100 struct ext4_prealloc_space, pa_inode_list);
4101 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4102 spin_lock(&pa->pa_lock);
4103 if (atomic_read(&pa->pa_count)) {
4104 /* this shouldn't happen often - nobody should
4105 * use preallocation while we're discarding it */
4106 spin_unlock(&pa->pa_lock);
4107 spin_unlock(&ei->i_prealloc_lock);
4108 ext4_msg(sb, KERN_ERR,
4109 "uh-oh! used pa while discarding");
4111 schedule_timeout_uninterruptible(HZ);
4115 if (pa->pa_deleted == 0) {
4117 spin_unlock(&pa->pa_lock);
4118 list_del_rcu(&pa->pa_inode_list);
4119 list_add(&pa->u.pa_tmp_list, &list);
4123 /* someone is deleting pa right now */
4124 spin_unlock(&pa->pa_lock);
4125 spin_unlock(&ei->i_prealloc_lock);
4127 /* we have to wait here because pa_deleted
4128 * doesn't mean pa is already unlinked from
4129 * the list. as we might be called from
4130 * ->clear_inode() the inode will get freed
4131 * and concurrent thread which is unlinking
4132 * pa from inode's list may access already
4133 * freed memory, bad-bad-bad */
4135 /* XXX: if this happens too often, we can
4136 * add a flag to force wait only in case
4137 * of ->clear_inode(), but not in case of
4138 * regular truncate */
4139 schedule_timeout_uninterruptible(HZ);
4142 spin_unlock(&ei->i_prealloc_lock);
4144 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4145 BUG_ON(pa->pa_type != MB_INODE_PA);
4146 group = ext4_get_group_number(sb, pa->pa_pstart);
4148 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4149 GFP_NOFS|__GFP_NOFAIL);
4151 ext4_error(sb, "Error %d loading buddy information for %u",
4156 bitmap_bh = ext4_read_block_bitmap(sb, group);
4157 if (IS_ERR(bitmap_bh)) {
4158 err = PTR_ERR(bitmap_bh);
4159 ext4_error(sb, "Error %d reading block bitmap for %u",
4161 ext4_mb_unload_buddy(&e4b);
4165 ext4_lock_group(sb, group);
4166 list_del(&pa->pa_group_list);
4167 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4168 ext4_unlock_group(sb, group);
4170 ext4_mb_unload_buddy(&e4b);
4173 list_del(&pa->u.pa_tmp_list);
4174 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4178 #ifdef CONFIG_EXT4_DEBUG
4179 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4181 struct super_block *sb = ac->ac_sb;
4182 ext4_group_t ngroups, i;
4184 if (!ext4_mballoc_debug ||
4185 (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
4188 ext4_msg(ac->ac_sb, KERN_ERR, "Can't allocate:"
4189 " Allocation context details:");
4190 ext4_msg(ac->ac_sb, KERN_ERR, "status %d flags %d",
4191 ac->ac_status, ac->ac_flags);
4192 ext4_msg(ac->ac_sb, KERN_ERR, "orig %lu/%lu/%lu@%lu, "
4193 "goal %lu/%lu/%lu@%lu, "
4194 "best %lu/%lu/%lu@%lu cr %d",
4195 (unsigned long)ac->ac_o_ex.fe_group,
4196 (unsigned long)ac->ac_o_ex.fe_start,
4197 (unsigned long)ac->ac_o_ex.fe_len,
4198 (unsigned long)ac->ac_o_ex.fe_logical,
4199 (unsigned long)ac->ac_g_ex.fe_group,
4200 (unsigned long)ac->ac_g_ex.fe_start,
4201 (unsigned long)ac->ac_g_ex.fe_len,
4202 (unsigned long)ac->ac_g_ex.fe_logical,
4203 (unsigned long)ac->ac_b_ex.fe_group,
4204 (unsigned long)ac->ac_b_ex.fe_start,
4205 (unsigned long)ac->ac_b_ex.fe_len,
4206 (unsigned long)ac->ac_b_ex.fe_logical,
4207 (int)ac->ac_criteria);
4208 ext4_msg(ac->ac_sb, KERN_ERR, "%d found", ac->ac_found);
4209 ext4_msg(ac->ac_sb, KERN_ERR, "groups: ");
4210 ngroups = ext4_get_groups_count(sb);
4211 for (i = 0; i < ngroups; i++) {
4212 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4213 struct ext4_prealloc_space *pa;
4214 ext4_grpblk_t start;
4215 struct list_head *cur;
4216 ext4_lock_group(sb, i);
4217 list_for_each(cur, &grp->bb_prealloc_list) {
4218 pa = list_entry(cur, struct ext4_prealloc_space,
4220 spin_lock(&pa->pa_lock);
4221 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4223 spin_unlock(&pa->pa_lock);
4224 printk(KERN_ERR "PA:%u:%d:%u \n", i,
4227 ext4_unlock_group(sb, i);
4229 if (grp->bb_free == 0)
4231 printk(KERN_ERR "%u: %d/%d \n",
4232 i, grp->bb_free, grp->bb_fragments);
4234 printk(KERN_ERR "\n");
4237 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4244 * We use locality group preallocation for small size file. The size of the
4245 * file is determined by the current size or the resulting size after
4246 * allocation which ever is larger
4248 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4250 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4252 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4253 int bsbits = ac->ac_sb->s_blocksize_bits;
4256 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4259 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4262 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
4263 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
4266 if ((size == isize) &&
4267 !ext4_fs_is_busy(sbi) &&
4268 (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
4269 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
4273 if (sbi->s_mb_group_prealloc <= 0) {
4274 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4278 /* don't use group allocation for large files */
4279 size = max(size, isize);
4280 if (size > sbi->s_mb_stream_request) {
4281 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4285 BUG_ON(ac->ac_lg != NULL);
4287 * locality group prealloc space are per cpu. The reason for having
4288 * per cpu locality group is to reduce the contention between block
4289 * request from multiple CPUs.
4291 ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
4293 /* we're going to use group allocation */
4294 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4296 /* serialize all allocations in the group */
4297 mutex_lock(&ac->ac_lg->lg_mutex);
4300 static noinline_for_stack int
4301 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4302 struct ext4_allocation_request *ar)
4304 struct super_block *sb = ar->inode->i_sb;
4305 struct ext4_sb_info *sbi = EXT4_SB(sb);
4306 struct ext4_super_block *es = sbi->s_es;
4310 ext4_grpblk_t block;
4312 /* we can't allocate > group size */
4315 /* just a dirty hack to filter too big requests */
4316 if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
4317 len = EXT4_CLUSTERS_PER_GROUP(sb);
4319 /* start searching from the goal */
4321 if (goal < le32_to_cpu(es->s_first_data_block) ||
4322 goal >= ext4_blocks_count(es))
4323 goal = le32_to_cpu(es->s_first_data_block);
4324 ext4_get_group_no_and_offset(sb, goal, &group, &block);
4326 /* set up allocation goals */
4327 ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
4328 ac->ac_status = AC_STATUS_CONTINUE;
4330 ac->ac_inode = ar->inode;
4331 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4332 ac->ac_o_ex.fe_group = group;
4333 ac->ac_o_ex.fe_start = block;
4334 ac->ac_o_ex.fe_len = len;
4335 ac->ac_g_ex = ac->ac_o_ex;
4336 ac->ac_flags = ar->flags;
4338 /* we have to define context: we'll we work with a file or
4339 * locality group. this is a policy, actually */
4340 ext4_mb_group_or_file(ac);
4342 mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4343 "left: %u/%u, right %u/%u to %swritable\n",
4344 (unsigned) ar->len, (unsigned) ar->logical,
4345 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4346 (unsigned) ar->lleft, (unsigned) ar->pleft,
4347 (unsigned) ar->lright, (unsigned) ar->pright,
4348 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4353 static noinline_for_stack void
4354 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4355 struct ext4_locality_group *lg,
4356 int order, int total_entries)
4358 ext4_group_t group = 0;
4359 struct ext4_buddy e4b;
4360 struct list_head discard_list;
4361 struct ext4_prealloc_space *pa, *tmp;
4363 mb_debug(1, "discard locality group preallocation\n");
4365 INIT_LIST_HEAD(&discard_list);
4367 spin_lock(&lg->lg_prealloc_lock);
4368 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4370 spin_lock(&pa->pa_lock);
4371 if (atomic_read(&pa->pa_count)) {
4373 * This is the pa that we just used
4374 * for block allocation. So don't
4377 spin_unlock(&pa->pa_lock);
4380 if (pa->pa_deleted) {
4381 spin_unlock(&pa->pa_lock);
4384 /* only lg prealloc space */
4385 BUG_ON(pa->pa_type != MB_GROUP_PA);
4387 /* seems this one can be freed ... */
4389 spin_unlock(&pa->pa_lock);
4391 list_del_rcu(&pa->pa_inode_list);
4392 list_add(&pa->u.pa_tmp_list, &discard_list);
4395 if (total_entries <= 5) {
4397 * we want to keep only 5 entries
4398 * allowing it to grow to 8. This
4399 * mak sure we don't call discard
4400 * soon for this list.
4405 spin_unlock(&lg->lg_prealloc_lock);
4407 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4410 group = ext4_get_group_number(sb, pa->pa_pstart);
4411 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4412 GFP_NOFS|__GFP_NOFAIL);
4414 ext4_error(sb, "Error %d loading buddy information for %u",
4418 ext4_lock_group(sb, group);
4419 list_del(&pa->pa_group_list);
4420 ext4_mb_release_group_pa(&e4b, pa);
4421 ext4_unlock_group(sb, group);
4423 ext4_mb_unload_buddy(&e4b);
4424 list_del(&pa->u.pa_tmp_list);
4425 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4430 * We have incremented pa_count. So it cannot be freed at this
4431 * point. Also we hold lg_mutex. So no parallel allocation is
4432 * possible from this lg. That means pa_free cannot be updated.
4434 * A parallel ext4_mb_discard_group_preallocations is possible.
4435 * which can cause the lg_prealloc_list to be updated.
4438 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4440 int order, added = 0, lg_prealloc_count = 1;
4441 struct super_block *sb = ac->ac_sb;
4442 struct ext4_locality_group *lg = ac->ac_lg;
4443 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4445 order = fls(pa->pa_free) - 1;
4446 if (order > PREALLOC_TB_SIZE - 1)
4447 /* The max size of hash table is PREALLOC_TB_SIZE */
4448 order = PREALLOC_TB_SIZE - 1;
4449 /* Add the prealloc space to lg */
4450 spin_lock(&lg->lg_prealloc_lock);
4451 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4453 spin_lock(&tmp_pa->pa_lock);
4454 if (tmp_pa->pa_deleted) {
4455 spin_unlock(&tmp_pa->pa_lock);
4458 if (!added && pa->pa_free < tmp_pa->pa_free) {
4459 /* Add to the tail of the previous entry */
4460 list_add_tail_rcu(&pa->pa_inode_list,
4461 &tmp_pa->pa_inode_list);
4464 * we want to count the total
4465 * number of entries in the list
4468 spin_unlock(&tmp_pa->pa_lock);
4469 lg_prealloc_count++;
4472 list_add_tail_rcu(&pa->pa_inode_list,
4473 &lg->lg_prealloc_list[order]);
4474 spin_unlock(&lg->lg_prealloc_lock);
4476 /* Now trim the list to be not more than 8 elements */
4477 if (lg_prealloc_count > 8) {
4478 ext4_mb_discard_lg_preallocations(sb, lg,
4479 order, lg_prealloc_count);
4486 * release all resource we used in allocation
4488 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4490 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4491 struct ext4_prealloc_space *pa = ac->ac_pa;
4493 if (pa->pa_type == MB_GROUP_PA) {
4494 /* see comment in ext4_mb_use_group_pa() */
4495 spin_lock(&pa->pa_lock);
4496 pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4497 pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4498 pa->pa_free -= ac->ac_b_ex.fe_len;
4499 pa->pa_len -= ac->ac_b_ex.fe_len;
4500 spin_unlock(&pa->pa_lock);
4505 * We want to add the pa to the right bucket.
4506 * Remove it from the list and while adding
4507 * make sure the list to which we are adding
4510 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4511 spin_lock(pa->pa_obj_lock);
4512 list_del_rcu(&pa->pa_inode_list);
4513 spin_unlock(pa->pa_obj_lock);
4514 ext4_mb_add_n_trim(ac);
4516 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4518 if (ac->ac_bitmap_page)
4519 put_page(ac->ac_bitmap_page);
4520 if (ac->ac_buddy_page)
4521 put_page(ac->ac_buddy_page);
4522 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4523 mutex_unlock(&ac->ac_lg->lg_mutex);
4524 ext4_mb_collect_stats(ac);
4528 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4530 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4534 trace_ext4_mb_discard_preallocations(sb, needed);
4535 for (i = 0; i < ngroups && needed > 0; i++) {
4536 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4545 * Main entry point into mballoc to allocate blocks
4546 * it tries to use preallocation first, then falls back
4547 * to usual allocation
4549 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4550 struct ext4_allocation_request *ar, int *errp)
4553 struct ext4_allocation_context *ac = NULL;
4554 struct ext4_sb_info *sbi;
4555 struct super_block *sb;
4556 ext4_fsblk_t block = 0;
4557 unsigned int inquota = 0;
4558 unsigned int reserv_clstrs = 0;
4561 sb = ar->inode->i_sb;
4564 trace_ext4_request_blocks(ar);
4566 /* Allow to use superuser reservation for quota file */
4567 if (ext4_is_quota_file(ar->inode))
4568 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
4570 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
4571 /* Without delayed allocation we need to verify
4572 * there is enough free blocks to do block allocation
4573 * and verify allocation doesn't exceed the quota limits.
4576 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
4578 /* let others to free the space */
4580 ar->len = ar->len >> 1;
4586 reserv_clstrs = ar->len;
4587 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
4588 dquot_alloc_block_nofail(ar->inode,
4589 EXT4_C2B(sbi, ar->len));
4592 dquot_alloc_block(ar->inode,
4593 EXT4_C2B(sbi, ar->len))) {
4595 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4606 ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
4613 *errp = ext4_mb_initialize_context(ac, ar);
4619 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4620 if (!ext4_mb_use_preallocated(ac)) {
4621 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4622 ext4_mb_normalize_request(ac, ar);
4624 /* allocate space in core */
4625 *errp = ext4_mb_regular_allocator(ac);
4627 goto discard_and_exit;
4629 /* as we've just preallocated more space than
4630 * user requested originally, we store allocated
4631 * space in a special descriptor */
4632 if (ac->ac_status == AC_STATUS_FOUND &&
4633 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4634 *errp = ext4_mb_new_preallocation(ac);
4637 ext4_discard_allocated_blocks(ac);
4641 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4642 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4644 ext4_discard_allocated_blocks(ac);
4647 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4648 ar->len = ac->ac_b_ex.fe_len;
4651 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4659 ac->ac_b_ex.fe_len = 0;
4661 ext4_mb_show_ac(ac);
4663 ext4_mb_release_context(ac);
4666 kmem_cache_free(ext4_ac_cachep, ac);
4667 if (inquota && ar->len < inquota)
4668 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
4670 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
4671 /* release all the reserved blocks if non delalloc */
4672 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4676 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4682 * We can merge two free data extents only if the physical blocks
4683 * are contiguous, AND the extents were freed by the same transaction,
4684 * AND the blocks are associated with the same group.
4686 static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
4687 struct ext4_free_data *entry,
4688 struct ext4_free_data *new_entry,
4689 struct rb_root *entry_rb_root)
4691 if ((entry->efd_tid != new_entry->efd_tid) ||
4692 (entry->efd_group != new_entry->efd_group))
4694 if (entry->efd_start_cluster + entry->efd_count ==
4695 new_entry->efd_start_cluster) {
4696 new_entry->efd_start_cluster = entry->efd_start_cluster;
4697 new_entry->efd_count += entry->efd_count;
4698 } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
4699 entry->efd_start_cluster) {
4700 new_entry->efd_count += entry->efd_count;
4703 spin_lock(&sbi->s_md_lock);
4704 list_del(&entry->efd_list);
4705 spin_unlock(&sbi->s_md_lock);
4706 rb_erase(&entry->efd_node, entry_rb_root);
4707 kmem_cache_free(ext4_free_data_cachep, entry);
4710 static noinline_for_stack int
4711 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4712 struct ext4_free_data *new_entry)
4714 ext4_group_t group = e4b->bd_group;
4715 ext4_grpblk_t cluster;
4716 ext4_grpblk_t clusters = new_entry->efd_count;
4717 struct ext4_free_data *entry;
4718 struct ext4_group_info *db = e4b->bd_info;
4719 struct super_block *sb = e4b->bd_sb;
4720 struct ext4_sb_info *sbi = EXT4_SB(sb);
4721 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4722 struct rb_node *parent = NULL, *new_node;
4724 BUG_ON(!ext4_handle_valid(handle));
4725 BUG_ON(e4b->bd_bitmap_page == NULL);
4726 BUG_ON(e4b->bd_buddy_page == NULL);
4728 new_node = &new_entry->efd_node;
4729 cluster = new_entry->efd_start_cluster;
4732 /* first free block exent. We need to
4733 protect buddy cache from being freed,
4734 * otherwise we'll refresh it from
4735 * on-disk bitmap and lose not-yet-available
4737 get_page(e4b->bd_buddy_page);
4738 get_page(e4b->bd_bitmap_page);
4742 entry = rb_entry(parent, struct ext4_free_data, efd_node);
4743 if (cluster < entry->efd_start_cluster)
4745 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
4746 n = &(*n)->rb_right;
4748 ext4_grp_locked_error(sb, group, 0,
4749 ext4_group_first_block_no(sb, group) +
4750 EXT4_C2B(sbi, cluster),
4751 "Block already on to-be-freed list");
4752 kmem_cache_free(ext4_free_data_cachep, new_entry);
4757 rb_link_node(new_node, parent, n);
4758 rb_insert_color(new_node, &db->bb_free_root);
4760 /* Now try to see the extent can be merged to left and right */
4761 node = rb_prev(new_node);
4763 entry = rb_entry(node, struct ext4_free_data, efd_node);
4764 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4765 &(db->bb_free_root));
4768 node = rb_next(new_node);
4770 entry = rb_entry(node, struct ext4_free_data, efd_node);
4771 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4772 &(db->bb_free_root));
4775 spin_lock(&sbi->s_md_lock);
4776 list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
4777 sbi->s_mb_free_pending += clusters;
4778 spin_unlock(&sbi->s_md_lock);
4783 * ext4_free_blocks() -- Free given blocks and update quota
4784 * @handle: handle for this transaction
4786 * @block: start physical block to free
4787 * @count: number of blocks to count
4788 * @flags: flags used by ext4_free_blocks
4790 void ext4_free_blocks(handle_t *handle, struct inode *inode,
4791 struct buffer_head *bh, ext4_fsblk_t block,
4792 unsigned long count, int flags)
4794 struct buffer_head *bitmap_bh = NULL;
4795 struct super_block *sb = inode->i_sb;
4796 struct ext4_group_desc *gdp;
4797 unsigned int overflow;
4799 struct buffer_head *gd_bh;
4800 ext4_group_t block_group;
4801 struct ext4_sb_info *sbi;
4802 struct ext4_buddy e4b;
4803 unsigned int count_clusters;
4810 BUG_ON(block != bh->b_blocknr);
4812 block = bh->b_blocknr;
4816 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
4817 !ext4_inode_block_valid(inode, block, count)) {
4818 ext4_error(sb, "Freeing blocks not in datazone - "
4819 "block = %llu, count = %lu", block, count);
4823 ext4_debug("freeing block %llu\n", block);
4824 trace_ext4_free_blocks(inode, block, count, flags);
4826 if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4829 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4834 * If the extent to be freed does not begin on a cluster
4835 * boundary, we need to deal with partial clusters at the
4836 * beginning and end of the extent. Normally we will free
4837 * blocks at the beginning or the end unless we are explicitly
4838 * requested to avoid doing so.
4840 overflow = EXT4_PBLK_COFF(sbi, block);
4842 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
4843 overflow = sbi->s_cluster_ratio - overflow;
4845 if (count > overflow)
4854 overflow = EXT4_LBLK_COFF(sbi, count);
4856 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
4857 if (count > overflow)
4862 count += sbi->s_cluster_ratio - overflow;
4865 if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4867 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
4869 for (i = 0; i < count; i++) {
4872 bh = sb_find_get_block(inode->i_sb, block + i);
4873 ext4_forget(handle, is_metadata, inode, bh, block + i);
4879 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4881 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
4882 ext4_get_group_info(sb, block_group))))
4886 * Check to see if we are freeing blocks across a group
4889 if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4890 overflow = EXT4_C2B(sbi, bit) + count -
4891 EXT4_BLOCKS_PER_GROUP(sb);
4894 count_clusters = EXT4_NUM_B2C(sbi, count);
4895 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4896 if (IS_ERR(bitmap_bh)) {
4897 err = PTR_ERR(bitmap_bh);
4901 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4907 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4908 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4909 in_range(block, ext4_inode_table(sb, gdp),
4910 EXT4_SB(sb)->s_itb_per_group) ||
4911 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4912 EXT4_SB(sb)->s_itb_per_group)) {
4914 ext4_error(sb, "Freeing blocks in system zone - "
4915 "Block = %llu, count = %lu", block, count);
4916 /* err = 0. ext4_std_error should be a no op */
4920 BUFFER_TRACE(bitmap_bh, "getting write access");
4921 err = ext4_journal_get_write_access(handle, bitmap_bh);
4926 * We are about to modify some metadata. Call the journal APIs
4927 * to unshare ->b_data if a currently-committing transaction is
4930 BUFFER_TRACE(gd_bh, "get_write_access");
4931 err = ext4_journal_get_write_access(handle, gd_bh);
4934 #ifdef AGGRESSIVE_CHECK
4937 for (i = 0; i < count_clusters; i++)
4938 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4941 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
4943 /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
4944 err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
4945 GFP_NOFS|__GFP_NOFAIL);
4950 * We need to make sure we don't reuse the freed block until after the
4951 * transaction is committed. We make an exception if the inode is to be
4952 * written in writeback mode since writeback mode has weak data
4953 * consistency guarantees.
4955 if (ext4_handle_valid(handle) &&
4956 ((flags & EXT4_FREE_BLOCKS_METADATA) ||
4957 !ext4_should_writeback_data(inode))) {
4958 struct ext4_free_data *new_entry;
4960 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
4963 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
4964 GFP_NOFS|__GFP_NOFAIL);
4965 new_entry->efd_start_cluster = bit;
4966 new_entry->efd_group = block_group;
4967 new_entry->efd_count = count_clusters;
4968 new_entry->efd_tid = handle->h_transaction->t_tid;
4970 ext4_lock_group(sb, block_group);
4971 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4972 ext4_mb_free_metadata(handle, &e4b, new_entry);
4974 /* need to update group_info->bb_free and bitmap
4975 * with group lock held. generate_buddy look at
4976 * them with group lock_held
4978 if (test_opt(sb, DISCARD)) {
4979 err = ext4_issue_discard(sb, block_group, bit,
4980 count_clusters, NULL);
4981 if (err && err != -EOPNOTSUPP)
4982 ext4_msg(sb, KERN_WARNING, "discard request in"
4983 " group:%d block:%d count:%lu failed"
4984 " with %d", block_group, bit, count,
4987 EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
4989 ext4_lock_group(sb, block_group);
4990 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4991 mb_free_blocks(inode, &e4b, bit, count_clusters);
4994 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
4995 ext4_free_group_clusters_set(sb, gdp, ret);
4996 ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
4997 ext4_group_desc_csum_set(sb, block_group, gdp);
4998 ext4_unlock_group(sb, block_group);
5000 if (sbi->s_log_groups_per_flex) {
5001 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5002 atomic64_add(count_clusters,
5003 &sbi_array_rcu_deref(sbi, s_flex_groups,
5004 flex_group)->free_clusters);
5007 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
5008 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
5009 percpu_counter_add(&sbi->s_freeclusters_counter, count_clusters);
5011 ext4_mb_unload_buddy(&e4b);
5013 /* We dirtied the bitmap block */
5014 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5015 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5017 /* And the group descriptor block */
5018 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5019 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5023 if (overflow && !err) {
5031 ext4_std_error(sb, err);
5036 * ext4_group_add_blocks() -- Add given blocks to an existing group
5037 * @handle: handle to this transaction
5039 * @block: start physical block to add to the block group
5040 * @count: number of blocks to free
5042 * This marks the blocks as free in the bitmap and buddy.
5044 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
5045 ext4_fsblk_t block, unsigned long count)
5047 struct buffer_head *bitmap_bh = NULL;
5048 struct buffer_head *gd_bh;
5049 ext4_group_t block_group;
5052 struct ext4_group_desc *desc;
5053 struct ext4_sb_info *sbi = EXT4_SB(sb);
5054 struct ext4_buddy e4b;
5055 int err = 0, ret, blk_free_count;
5056 ext4_grpblk_t blocks_freed;
5058 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
5063 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5065 * Check to see if we are freeing blocks across a group
5068 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
5069 ext4_warning(sb, "too much blocks added to group %u",
5075 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
5076 if (IS_ERR(bitmap_bh)) {
5077 err = PTR_ERR(bitmap_bh);
5082 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
5088 if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
5089 in_range(ext4_inode_bitmap(sb, desc), block, count) ||
5090 in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
5091 in_range(block + count - 1, ext4_inode_table(sb, desc),
5092 sbi->s_itb_per_group)) {
5093 ext4_error(sb, "Adding blocks in system zones - "
5094 "Block = %llu, count = %lu",
5100 BUFFER_TRACE(bitmap_bh, "getting write access");
5101 err = ext4_journal_get_write_access(handle, bitmap_bh);
5106 * We are about to modify some metadata. Call the journal APIs
5107 * to unshare ->b_data if a currently-committing transaction is
5110 BUFFER_TRACE(gd_bh, "get_write_access");
5111 err = ext4_journal_get_write_access(handle, gd_bh);
5115 for (i = 0, blocks_freed = 0; i < count; i++) {
5116 BUFFER_TRACE(bitmap_bh, "clear bit");
5117 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
5118 ext4_error(sb, "bit already cleared for block %llu",
5119 (ext4_fsblk_t)(block + i));
5120 BUFFER_TRACE(bitmap_bh, "bit already cleared");
5126 err = ext4_mb_load_buddy(sb, block_group, &e4b);
5131 * need to update group_info->bb_free and bitmap
5132 * with group lock held. generate_buddy look at
5133 * them with group lock_held
5135 ext4_lock_group(sb, block_group);
5136 mb_clear_bits(bitmap_bh->b_data, bit, count);
5137 mb_free_blocks(NULL, &e4b, bit, count);
5138 blk_free_count = blocks_freed + ext4_free_group_clusters(sb, desc);
5139 ext4_free_group_clusters_set(sb, desc, blk_free_count);
5140 ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
5141 ext4_group_desc_csum_set(sb, block_group, desc);
5142 ext4_unlock_group(sb, block_group);
5143 percpu_counter_add(&sbi->s_freeclusters_counter,
5144 EXT4_NUM_B2C(sbi, blocks_freed));
5146 if (sbi->s_log_groups_per_flex) {
5147 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5148 atomic64_add(EXT4_NUM_B2C(sbi, blocks_freed),
5149 &sbi_array_rcu_deref(sbi, s_flex_groups,
5150 flex_group)->free_clusters);
5153 ext4_mb_unload_buddy(&e4b);
5155 /* We dirtied the bitmap block */
5156 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5157 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5159 /* And the group descriptor block */
5160 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5161 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5167 ext4_std_error(sb, err);
5172 * ext4_trim_extent -- function to TRIM one single free extent in the group
5173 * @sb: super block for the file system
5174 * @start: starting block of the free extent in the alloc. group
5175 * @count: number of blocks to TRIM
5176 * @group: alloc. group we are working with
5177 * @e4b: ext4 buddy for the group
5179 * Trim "count" blocks starting at "start" in the "group". To assure that no
5180 * one will allocate those blocks, mark it as used in buddy bitmap. This must
5181 * be called with under the group lock.
5183 static int ext4_trim_extent(struct super_block *sb, int start, int count,
5184 ext4_group_t group, struct ext4_buddy *e4b)
5188 struct ext4_free_extent ex;
5191 trace_ext4_trim_extent(sb, group, start, count);
5193 assert_spin_locked(ext4_group_lock_ptr(sb, group));
5195 ex.fe_start = start;
5196 ex.fe_group = group;
5200 * Mark blocks used, so no one can reuse them while
5203 mb_mark_used(e4b, &ex);
5204 ext4_unlock_group(sb, group);
5205 ret = ext4_issue_discard(sb, group, start, count, NULL);
5206 ext4_lock_group(sb, group);
5207 mb_free_blocks(NULL, e4b, start, ex.fe_len);
5212 * ext4_trim_all_free -- function to trim all free space in alloc. group
5213 * @sb: super block for file system
5214 * @group: group to be trimmed
5215 * @start: first group block to examine
5216 * @max: last group block to examine
5217 * @minblocks: minimum extent block count
5219 * ext4_trim_all_free walks through group's buddy bitmap searching for free
5220 * extents. When the free block is found, ext4_trim_extent is called to TRIM
5224 * ext4_trim_all_free walks through group's block bitmap searching for free
5225 * extents. When the free extent is found, mark it as used in group buddy
5226 * bitmap. Then issue a TRIM command on this extent and free the extent in
5227 * the group buddy bitmap. This is done until whole group is scanned.
5229 static ext4_grpblk_t
5230 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
5231 ext4_grpblk_t start, ext4_grpblk_t max,
5232 ext4_grpblk_t minblocks)
5235 ext4_grpblk_t next, count = 0, free_count = 0;
5236 struct ext4_buddy e4b;
5239 trace_ext4_trim_all_free(sb, group, start, max);
5241 ret = ext4_mb_load_buddy(sb, group, &e4b);
5243 ext4_warning(sb, "Error %d loading buddy information for %u",
5247 bitmap = e4b.bd_bitmap;
5249 ext4_lock_group(sb, group);
5250 if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
5251 minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
5254 start = (e4b.bd_info->bb_first_free > start) ?
5255 e4b.bd_info->bb_first_free : start;
5257 while (start <= max) {
5258 start = mb_find_next_zero_bit(bitmap, max + 1, start);
5261 next = mb_find_next_bit(bitmap, max + 1, start);
5263 if ((next - start) >= minblocks) {
5264 ret = ext4_trim_extent(sb, start,
5265 next - start, group, &e4b);
5266 if (ret && ret != -EOPNOTSUPP)
5269 count += next - start;
5271 free_count += next - start;
5274 if (fatal_signal_pending(current)) {
5275 count = -ERESTARTSYS;
5279 if (need_resched()) {
5280 ext4_unlock_group(sb, group);
5282 ext4_lock_group(sb, group);
5285 if ((e4b.bd_info->bb_free - free_count) < minblocks)
5291 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
5294 ext4_unlock_group(sb, group);
5295 ext4_mb_unload_buddy(&e4b);
5297 ext4_debug("trimmed %d blocks in the group %d\n",
5304 * ext4_trim_fs() -- trim ioctl handle function
5305 * @sb: superblock for filesystem
5306 * @range: fstrim_range structure
5308 * start: First Byte to trim
5309 * len: number of Bytes to trim from start
5310 * minlen: minimum extent length in Bytes
5311 * ext4_trim_fs goes through all allocation groups containing Bytes from
5312 * start to start+len. For each such a group ext4_trim_all_free function
5313 * is invoked to trim all free space.
5315 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
5317 struct request_queue *q = bdev_get_queue(sb->s_bdev);
5318 struct ext4_group_info *grp;
5319 ext4_group_t group, first_group, last_group;
5320 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5321 uint64_t start, end, minlen, trimmed = 0;
5322 ext4_fsblk_t first_data_blk =
5323 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5324 ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
5327 start = range->start >> sb->s_blocksize_bits;
5328 end = start + (range->len >> sb->s_blocksize_bits) - 1;
5329 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5330 range->minlen >> sb->s_blocksize_bits);
5332 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
5333 start >= max_blks ||
5334 range->len < sb->s_blocksize)
5336 /* No point to try to trim less than discard granularity */
5337 if (range->minlen < q->limits.discard_granularity) {
5338 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5339 q->limits.discard_granularity >> sb->s_blocksize_bits);
5340 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
5343 if (end >= max_blks)
5345 if (end <= first_data_blk)
5347 if (start < first_data_blk)
5348 start = first_data_blk;
5350 /* Determine first and last group to examine based on start and end */
5351 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
5352 &first_group, &first_cluster);
5353 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
5354 &last_group, &last_cluster);
5356 /* end now represents the last cluster to discard in this group */
5357 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5359 for (group = first_group; group <= last_group; group++) {
5360 grp = ext4_get_group_info(sb, group);
5361 /* We only do this if the grp has never been initialized */
5362 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
5363 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
5369 * For all the groups except the last one, last cluster will
5370 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
5371 * change it for the last group, note that last_cluster is
5372 * already computed earlier by ext4_get_group_no_and_offset()
5374 if (group == last_group)
5377 if (grp->bb_free >= minlen) {
5378 cnt = ext4_trim_all_free(sb, group, first_cluster,
5388 * For every group except the first one, we are sure
5389 * that the first cluster to discard will be cluster #0.
5395 atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
5398 range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
5402 /* Iterate all the free extents in the group. */
5404 ext4_mballoc_query_range(
5405 struct super_block *sb,
5407 ext4_grpblk_t start,
5409 ext4_mballoc_query_range_fn formatter,
5414 struct ext4_buddy e4b;
5417 error = ext4_mb_load_buddy(sb, group, &e4b);
5420 bitmap = e4b.bd_bitmap;
5422 ext4_lock_group(sb, group);
5424 start = (e4b.bd_info->bb_first_free > start) ?
5425 e4b.bd_info->bb_first_free : start;
5426 if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
5427 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5429 while (start <= end) {
5430 start = mb_find_next_zero_bit(bitmap, end + 1, start);
5433 next = mb_find_next_bit(bitmap, end + 1, start);
5435 ext4_unlock_group(sb, group);
5436 error = formatter(sb, group, start, next - start, priv);
5439 ext4_lock_group(sb, group);
5444 ext4_unlock_group(sb, group);
5446 ext4_mb_unload_buddy(&e4b);