2 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3 * Written by Alex Tomas <alex@clusterfs.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
21 * mballoc.c contains the multiblocks allocation routines
24 #include "ext4_jbd2.h"
26 #include <linux/log2.h>
27 #include <linux/module.h>
28 #include <linux/slab.h>
29 #include <linux/nospec.h>
30 #include <linux/backing-dev.h>
31 #include <trace/events/ext4.h>
33 #ifdef CONFIG_EXT4_DEBUG
34 ushort ext4_mballoc_debug __read_mostly;
36 module_param_named(mballoc_debug, ext4_mballoc_debug, ushort, 0644);
37 MODULE_PARM_DESC(mballoc_debug, "Debugging level for ext4's mballoc");
42 * - test ext4_ext_search_left() and ext4_ext_search_right()
43 * - search for metadata in few groups
46 * - normalization should take into account whether file is still open
47 * - discard preallocations if no free space left (policy?)
48 * - don't normalize tails
50 * - reservation for superuser
53 * - bitmap read-ahead (proposed by Oleg Drokin aka green)
54 * - track min/max extents in each group for better group selection
55 * - mb_mark_used() may allocate chunk right after splitting buddy
56 * - tree of groups sorted by number of free blocks
61 * The allocation request involve request for multiple number of blocks
62 * near to the goal(block) value specified.
64 * During initialization phase of the allocator we decide to use the
65 * group preallocation or inode preallocation depending on the size of
66 * the file. The size of the file could be the resulting file size we
67 * would have after allocation, or the current file size, which ever
68 * is larger. If the size is less than sbi->s_mb_stream_request we
69 * select to use the group preallocation. The default value of
70 * s_mb_stream_request is 16 blocks. This can also be tuned via
71 * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
72 * terms of number of blocks.
74 * The main motivation for having small file use group preallocation is to
75 * ensure that we have small files closer together on the disk.
77 * First stage the allocator looks at the inode prealloc list,
78 * ext4_inode_info->i_prealloc_list, which contains list of prealloc
79 * spaces for this particular inode. The inode prealloc space is
82 * pa_lstart -> the logical start block for this prealloc space
83 * pa_pstart -> the physical start block for this prealloc space
84 * pa_len -> length for this prealloc space (in clusters)
85 * pa_free -> free space available in this prealloc space (in clusters)
87 * The inode preallocation space is used looking at the _logical_ start
88 * block. If only the logical file block falls within the range of prealloc
89 * space we will consume the particular prealloc space. This makes sure that
90 * we have contiguous physical blocks representing the file blocks
92 * The important thing to be noted in case of inode prealloc space is that
93 * we don't modify the values associated to inode prealloc space except
96 * If we are not able to find blocks in the inode prealloc space and if we
97 * have the group allocation flag set then we look at the locality group
98 * prealloc space. These are per CPU prealloc list represented as
100 * ext4_sb_info.s_locality_groups[smp_processor_id()]
102 * The reason for having a per cpu locality group is to reduce the contention
103 * between CPUs. It is possible to get scheduled at this point.
105 * The locality group prealloc space is used looking at whether we have
106 * enough free space (pa_free) within the prealloc space.
108 * If we can't allocate blocks via inode prealloc or/and locality group
109 * prealloc then we look at the buddy cache. The buddy cache is represented
110 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
111 * mapped to the buddy and bitmap information regarding different
112 * groups. The buddy information is attached to buddy cache inode so that
113 * we can access them through the page cache. The information regarding
114 * each group is loaded via ext4_mb_load_buddy. The information involve
115 * block bitmap and buddy information. The information are stored in the
119 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
122 * one block each for bitmap and buddy information. So for each group we
123 * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
124 * blocksize) blocks. So it can have information regarding groups_per_page
125 * which is blocks_per_page/2
127 * The buddy cache inode is not stored on disk. The inode is thrown
128 * away when the filesystem is unmounted.
130 * We look for count number of blocks in the buddy cache. If we were able
131 * to locate that many free blocks we return with additional information
132 * regarding rest of the contiguous physical block available
134 * Before allocating blocks via buddy cache we normalize the request
135 * blocks. This ensure we ask for more blocks that we needed. The extra
136 * blocks that we get after allocation is added to the respective prealloc
137 * list. In case of inode preallocation we follow a list of heuristics
138 * based on file size. This can be found in ext4_mb_normalize_request. If
139 * we are doing a group prealloc we try to normalize the request to
140 * sbi->s_mb_group_prealloc. The default value of s_mb_group_prealloc is
141 * dependent on the cluster size; for non-bigalloc file systems, it is
142 * 512 blocks. This can be tuned via
143 * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
144 * terms of number of blocks. If we have mounted the file system with -O
145 * stripe=<value> option the group prealloc request is normalized to the
146 * the smallest multiple of the stripe value (sbi->s_stripe) which is
147 * greater than the default mb_group_prealloc.
149 * The regular allocator (using the buddy cache) supports a few tunables.
151 * /sys/fs/ext4/<partition>/mb_min_to_scan
152 * /sys/fs/ext4/<partition>/mb_max_to_scan
153 * /sys/fs/ext4/<partition>/mb_order2_req
155 * The regular allocator uses buddy scan only if the request len is power of
156 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
157 * value of s_mb_order2_reqs can be tuned via
158 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
159 * stripe size (sbi->s_stripe), we try to search for contiguous block in
160 * stripe size. This should result in better allocation on RAID setups. If
161 * not, we search in the specific group using bitmap for best extents. The
162 * tunable min_to_scan and max_to_scan control the behaviour here.
163 * min_to_scan indicate how long the mballoc __must__ look for a best
164 * extent and max_to_scan indicates how long the mballoc __can__ look for a
165 * best extent in the found extents. Searching for the blocks starts with
166 * the group specified as the goal value in allocation context via
167 * ac_g_ex. Each group is first checked based on the criteria whether it
168 * can be used for allocation. ext4_mb_good_group explains how the groups are
171 * Both the prealloc space are getting populated as above. So for the first
172 * request we will hit the buddy cache which will result in this prealloc
173 * space getting filled. The prealloc space is then later used for the
174 * subsequent request.
178 * mballoc operates on the following data:
180 * - in-core buddy (actually includes buddy and bitmap)
181 * - preallocation descriptors (PAs)
183 * there are two types of preallocations:
185 * assiged to specific inode and can be used for this inode only.
186 * it describes part of inode's space preallocated to specific
187 * physical blocks. any block from that preallocated can be used
188 * independent. the descriptor just tracks number of blocks left
189 * unused. so, before taking some block from descriptor, one must
190 * make sure corresponded logical block isn't allocated yet. this
191 * also means that freeing any block within descriptor's range
192 * must discard all preallocated blocks.
194 * assigned to specific locality group which does not translate to
195 * permanent set of inodes: inode can join and leave group. space
196 * from this type of preallocation can be used for any inode. thus
197 * it's consumed from the beginning to the end.
199 * relation between them can be expressed as:
200 * in-core buddy = on-disk bitmap + preallocation descriptors
202 * this mean blocks mballoc considers used are:
203 * - allocated blocks (persistent)
204 * - preallocated blocks (non-persistent)
206 * consistency in mballoc world means that at any time a block is either
207 * free or used in ALL structures. notice: "any time" should not be read
208 * literally -- time is discrete and delimited by locks.
210 * to keep it simple, we don't use block numbers, instead we count number of
211 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
213 * all operations can be expressed as:
214 * - init buddy: buddy = on-disk + PAs
215 * - new PA: buddy += N; PA = N
216 * - use inode PA: on-disk += N; PA -= N
217 * - discard inode PA buddy -= on-disk - PA; PA = 0
218 * - use locality group PA on-disk += N; PA -= N
219 * - discard locality group PA buddy -= PA; PA = 0
220 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
221 * is used in real operation because we can't know actual used
222 * bits from PA, only from on-disk bitmap
224 * if we follow this strict logic, then all operations above should be atomic.
225 * given some of them can block, we'd have to use something like semaphores
226 * killing performance on high-end SMP hardware. let's try to relax it using
227 * the following knowledge:
228 * 1) if buddy is referenced, it's already initialized
229 * 2) while block is used in buddy and the buddy is referenced,
230 * nobody can re-allocate that block
231 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
232 * bit set and PA claims same block, it's OK. IOW, one can set bit in
233 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
236 * so, now we're building a concurrency table:
239 * blocks for PA are allocated in the buddy, buddy must be referenced
240 * until PA is linked to allocation group to avoid concurrent buddy init
242 * we need to make sure that either on-disk bitmap or PA has uptodate data
243 * given (3) we care that PA-=N operation doesn't interfere with init
245 * the simplest way would be to have buddy initialized by the discard
246 * - use locality group PA
247 * again PA-=N must be serialized with init
248 * - discard locality group PA
249 * the simplest way would be to have buddy initialized by the discard
252 * i_data_sem serializes them
254 * discard process must wait until PA isn't used by another process
255 * - use locality group PA
256 * some mutex should serialize them
257 * - discard locality group PA
258 * discard process must wait until PA isn't used by another process
261 * i_data_sem or another mutex should serializes them
263 * discard process must wait until PA isn't used by another process
264 * - use locality group PA
265 * nothing wrong here -- they're different PAs covering different blocks
266 * - discard locality group PA
267 * discard process must wait until PA isn't used by another process
269 * now we're ready to make few consequences:
270 * - PA is referenced and while it is no discard is possible
271 * - PA is referenced until block isn't marked in on-disk bitmap
272 * - PA changes only after on-disk bitmap
273 * - discard must not compete with init. either init is done before
274 * any discard or they're serialized somehow
275 * - buddy init as sum of on-disk bitmap and PAs is done atomically
277 * a special case when we've used PA to emptiness. no need to modify buddy
278 * in this case, but we should care about concurrent init
283 * Logic in few words:
288 * mark bits in on-disk bitmap
291 * - use preallocation:
292 * find proper PA (per-inode or group)
294 * mark bits in on-disk bitmap
300 * mark bits in on-disk bitmap
303 * - discard preallocations in group:
305 * move them onto local list
306 * load on-disk bitmap
308 * remove PA from object (inode or locality group)
309 * mark free blocks in-core
311 * - discard inode's preallocations:
318 * - bitlock on a group (group)
319 * - object (inode/locality) (object)
330 * - release consumed pa:
335 * - generate in-core bitmap:
339 * - discard all for given object (inode, locality group):
344 * - discard all for given group:
351 static struct kmem_cache *ext4_pspace_cachep;
352 static struct kmem_cache *ext4_ac_cachep;
353 static struct kmem_cache *ext4_free_data_cachep;
355 /* We create slab caches for groupinfo data structures based on the
356 * superblock block size. There will be one per mounted filesystem for
357 * each unique s_blocksize_bits */
358 #define NR_GRPINFO_CACHES 8
359 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
361 static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
362 "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
363 "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
364 "ext4_groupinfo_64k", "ext4_groupinfo_128k"
367 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
369 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
372 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
374 #if BITS_PER_LONG == 64
375 *bit += ((unsigned long) addr & 7UL) << 3;
376 addr = (void *) ((unsigned long) addr & ~7UL);
377 #elif BITS_PER_LONG == 32
378 *bit += ((unsigned long) addr & 3UL) << 3;
379 addr = (void *) ((unsigned long) addr & ~3UL);
381 #error "how many bits you are?!"
386 static inline int mb_test_bit(int bit, void *addr)
389 * ext4_test_bit on architecture like powerpc
390 * needs unsigned long aligned address
392 addr = mb_correct_addr_and_bit(&bit, addr);
393 return ext4_test_bit(bit, addr);
396 static inline void mb_set_bit(int bit, void *addr)
398 addr = mb_correct_addr_and_bit(&bit, addr);
399 ext4_set_bit(bit, addr);
402 static inline void mb_clear_bit(int bit, void *addr)
404 addr = mb_correct_addr_and_bit(&bit, addr);
405 ext4_clear_bit(bit, addr);
408 static inline int mb_test_and_clear_bit(int bit, void *addr)
410 addr = mb_correct_addr_and_bit(&bit, addr);
411 return ext4_test_and_clear_bit(bit, addr);
414 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
416 int fix = 0, ret, tmpmax;
417 addr = mb_correct_addr_and_bit(&fix, addr);
421 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
427 static inline int mb_find_next_bit(void *addr, int max, int start)
429 int fix = 0, ret, tmpmax;
430 addr = mb_correct_addr_and_bit(&fix, addr);
434 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
440 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
444 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
447 if (order > e4b->bd_blkbits + 1) {
452 /* at order 0 we see each particular block */
454 *max = 1 << (e4b->bd_blkbits + 3);
455 return e4b->bd_bitmap;
458 bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
459 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
465 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
466 int first, int count)
469 struct super_block *sb = e4b->bd_sb;
471 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
473 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
474 for (i = 0; i < count; i++) {
475 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
476 ext4_fsblk_t blocknr;
478 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
479 blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
480 ext4_grp_locked_error(sb, e4b->bd_group,
481 inode ? inode->i_ino : 0,
483 "freeing block already freed "
487 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
491 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
495 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
497 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
498 for (i = 0; i < count; i++) {
499 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
500 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
504 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
506 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
507 unsigned char *b1, *b2;
509 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
510 b2 = (unsigned char *) bitmap;
511 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
512 if (b1[i] != b2[i]) {
513 ext4_msg(e4b->bd_sb, KERN_ERR,
514 "corruption in group %u "
515 "at byte %u(%u): %x in copy != %x "
517 e4b->bd_group, i, i * 8, b1[i], b2[i]);
525 static inline void mb_free_blocks_double(struct inode *inode,
526 struct ext4_buddy *e4b, int first, int count)
530 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
531 int first, int count)
535 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
541 #ifdef AGGRESSIVE_CHECK
543 #define MB_CHECK_ASSERT(assert) \
547 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
548 function, file, line, # assert); \
553 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
554 const char *function, int line)
556 struct super_block *sb = e4b->bd_sb;
557 int order = e4b->bd_blkbits + 1;
564 struct ext4_group_info *grp;
567 struct list_head *cur;
572 static int mb_check_counter;
573 if (mb_check_counter++ % 100 != 0)
578 buddy = mb_find_buddy(e4b, order, &max);
579 MB_CHECK_ASSERT(buddy);
580 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
581 MB_CHECK_ASSERT(buddy2);
582 MB_CHECK_ASSERT(buddy != buddy2);
583 MB_CHECK_ASSERT(max * 2 == max2);
586 for (i = 0; i < max; i++) {
588 if (mb_test_bit(i, buddy)) {
589 /* only single bit in buddy2 may be 1 */
590 if (!mb_test_bit(i << 1, buddy2)) {
592 mb_test_bit((i<<1)+1, buddy2));
593 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
595 mb_test_bit(i << 1, buddy2));
600 /* both bits in buddy2 must be 1 */
601 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
602 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
604 for (j = 0; j < (1 << order); j++) {
605 k = (i * (1 << order)) + j;
607 !mb_test_bit(k, e4b->bd_bitmap));
611 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
616 buddy = mb_find_buddy(e4b, 0, &max);
617 for (i = 0; i < max; i++) {
618 if (!mb_test_bit(i, buddy)) {
619 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
627 /* check used bits only */
628 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
629 buddy2 = mb_find_buddy(e4b, j, &max2);
631 MB_CHECK_ASSERT(k < max2);
632 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
635 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
636 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
638 grp = ext4_get_group_info(sb, e4b->bd_group);
639 list_for_each(cur, &grp->bb_prealloc_list) {
640 ext4_group_t groupnr;
641 struct ext4_prealloc_space *pa;
642 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
643 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
644 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
645 for (i = 0; i < pa->pa_len; i++)
646 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
650 #undef MB_CHECK_ASSERT
651 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
652 __FILE__, __func__, __LINE__)
654 #define mb_check_buddy(e4b)
658 * Divide blocks started from @first with length @len into
659 * smaller chunks with power of 2 blocks.
660 * Clear the bits in bitmap which the blocks of the chunk(s) covered,
661 * then increase bb_counters[] for corresponded chunk size.
663 static void ext4_mb_mark_free_simple(struct super_block *sb,
664 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
665 struct ext4_group_info *grp)
667 struct ext4_sb_info *sbi = EXT4_SB(sb);
673 BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
675 border = 2 << sb->s_blocksize_bits;
678 /* find how many blocks can be covered since this position */
679 max = ffs(first | border) - 1;
681 /* find how many blocks of power 2 we need to mark */
688 /* mark multiblock chunks only */
689 grp->bb_counters[min]++;
691 mb_clear_bit(first >> min,
692 buddy + sbi->s_mb_offsets[min]);
700 * Cache the order of the largest free extent we have available in this block
704 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
709 grp->bb_largest_free_order = -1; /* uninit */
711 bits = sb->s_blocksize_bits + 1;
712 for (i = bits; i >= 0; i--) {
713 if (grp->bb_counters[i] > 0) {
714 grp->bb_largest_free_order = i;
720 static noinline_for_stack
721 void ext4_mb_generate_buddy(struct super_block *sb,
722 void *buddy, void *bitmap, ext4_group_t group)
724 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
725 struct ext4_sb_info *sbi = EXT4_SB(sb);
726 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
731 unsigned fragments = 0;
732 unsigned long long period = get_cycles();
734 /* initialize buddy from bitmap which is aggregation
735 * of on-disk bitmap and preallocations */
736 i = mb_find_next_zero_bit(bitmap, max, 0);
737 grp->bb_first_free = i;
741 i = mb_find_next_bit(bitmap, max, i);
745 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
747 grp->bb_counters[0]++;
749 i = mb_find_next_zero_bit(bitmap, max, i);
751 grp->bb_fragments = fragments;
753 if (free != grp->bb_free) {
754 ext4_grp_locked_error(sb, group, 0, 0,
755 "block bitmap and bg descriptor "
756 "inconsistent: %u vs %u free clusters",
759 * If we intend to continue, we consider group descriptor
760 * corrupt and update bb_free using bitmap value
763 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
764 percpu_counter_sub(&sbi->s_freeclusters_counter,
766 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT, &grp->bb_state);
768 mb_set_largest_free_order(sb, grp);
770 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
772 period = get_cycles() - period;
773 spin_lock(&EXT4_SB(sb)->s_bal_lock);
774 EXT4_SB(sb)->s_mb_buddies_generated++;
775 EXT4_SB(sb)->s_mb_generation_time += period;
776 spin_unlock(&EXT4_SB(sb)->s_bal_lock);
779 static void mb_regenerate_buddy(struct ext4_buddy *e4b)
785 while ((buddy = mb_find_buddy(e4b, order++, &count))) {
786 ext4_set_bits(buddy, 0, count);
788 e4b->bd_info->bb_fragments = 0;
789 memset(e4b->bd_info->bb_counters, 0,
790 sizeof(*e4b->bd_info->bb_counters) *
791 (e4b->bd_sb->s_blocksize_bits + 2));
793 ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
794 e4b->bd_bitmap, e4b->bd_group);
797 /* The buddy information is attached the buddy cache inode
798 * for convenience. The information regarding each group
799 * is loaded via ext4_mb_load_buddy. The information involve
800 * block bitmap and buddy information. The information are
801 * stored in the inode as
804 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
807 * one block each for bitmap and buddy information.
808 * So for each group we take up 2 blocks. A page can
809 * contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
810 * So it can have information regarding groups_per_page which
811 * is blocks_per_page/2
813 * Locking note: This routine takes the block group lock of all groups
814 * for this page; do not hold this lock when calling this routine!
817 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
819 ext4_group_t ngroups;
825 ext4_group_t first_group, group;
827 struct super_block *sb;
828 struct buffer_head *bhs;
829 struct buffer_head **bh = NULL;
833 struct ext4_group_info *grinfo;
835 mb_debug(1, "init page %lu\n", page->index);
837 inode = page->mapping->host;
839 ngroups = ext4_get_groups_count(sb);
840 blocksize = i_blocksize(inode);
841 blocks_per_page = PAGE_SIZE / blocksize;
843 groups_per_page = blocks_per_page >> 1;
844 if (groups_per_page == 0)
847 /* allocate buffer_heads to read bitmaps */
848 if (groups_per_page > 1) {
849 i = sizeof(struct buffer_head *) * groups_per_page;
850 bh = kzalloc(i, gfp);
858 first_group = page->index * blocks_per_page / 2;
860 /* read all groups the page covers into the cache */
861 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
862 if (group >= ngroups)
865 grinfo = ext4_get_group_info(sb, group);
867 * If page is uptodate then we came here after online resize
868 * which added some new uninitialized group info structs, so
869 * we must skip all initialized uptodate buddies on the page,
870 * which may be currently in use by an allocating task.
872 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
876 bh[i] = ext4_read_block_bitmap_nowait(sb, group);
878 err = PTR_ERR(bh[i]);
882 mb_debug(1, "read bitmap for group %u\n", group);
885 /* wait for I/O completion */
886 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
891 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
896 first_block = page->index * blocks_per_page;
897 for (i = 0; i < blocks_per_page; i++) {
898 group = (first_block + i) >> 1;
899 if (group >= ngroups)
902 if (!bh[group - first_group])
903 /* skip initialized uptodate buddy */
906 if (!buffer_verified(bh[group - first_group]))
907 /* Skip faulty bitmaps */
912 * data carry information regarding this
913 * particular group in the format specified
917 data = page_address(page) + (i * blocksize);
918 bitmap = bh[group - first_group]->b_data;
921 * We place the buddy block and bitmap block
924 if ((first_block + i) & 1) {
925 /* this is block of buddy */
926 BUG_ON(incore == NULL);
927 mb_debug(1, "put buddy for group %u in page %lu/%x\n",
928 group, page->index, i * blocksize);
929 trace_ext4_mb_buddy_bitmap_load(sb, group);
930 grinfo = ext4_get_group_info(sb, group);
931 grinfo->bb_fragments = 0;
932 memset(grinfo->bb_counters, 0,
933 sizeof(*grinfo->bb_counters) *
934 (sb->s_blocksize_bits+2));
936 * incore got set to the group block bitmap below
938 ext4_lock_group(sb, group);
940 memset(data, 0xff, blocksize);
941 ext4_mb_generate_buddy(sb, data, incore, group);
942 ext4_unlock_group(sb, group);
945 /* this is block of bitmap */
946 BUG_ON(incore != NULL);
947 mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
948 group, page->index, i * blocksize);
949 trace_ext4_mb_bitmap_load(sb, group);
951 /* see comments in ext4_mb_put_pa() */
952 ext4_lock_group(sb, group);
953 memcpy(data, bitmap, blocksize);
955 /* mark all preallocated blks used in in-core bitmap */
956 ext4_mb_generate_from_pa(sb, data, group);
957 ext4_mb_generate_from_freelist(sb, data, group);
958 ext4_unlock_group(sb, group);
960 /* set incore so that the buddy information can be
961 * generated using this
966 SetPageUptodate(page);
970 for (i = 0; i < groups_per_page; i++)
979 * Lock the buddy and bitmap pages. This make sure other parallel init_group
980 * on the same buddy page doesn't happen whild holding the buddy page lock.
981 * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
982 * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
984 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
985 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
987 struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
988 int block, pnum, poff;
992 e4b->bd_buddy_page = NULL;
993 e4b->bd_bitmap_page = NULL;
995 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
997 * the buddy cache inode stores the block bitmap
998 * and buddy information in consecutive blocks.
999 * So for each group we need two blocks.
1002 pnum = block / blocks_per_page;
1003 poff = block % blocks_per_page;
1004 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1007 BUG_ON(page->mapping != inode->i_mapping);
1008 e4b->bd_bitmap_page = page;
1009 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1011 if (blocks_per_page >= 2) {
1012 /* buddy and bitmap are on the same page */
1017 pnum = block / blocks_per_page;
1018 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1021 BUG_ON(page->mapping != inode->i_mapping);
1022 e4b->bd_buddy_page = page;
1026 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1028 if (e4b->bd_bitmap_page) {
1029 unlock_page(e4b->bd_bitmap_page);
1030 put_page(e4b->bd_bitmap_page);
1032 if (e4b->bd_buddy_page) {
1033 unlock_page(e4b->bd_buddy_page);
1034 put_page(e4b->bd_buddy_page);
1039 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1040 * block group lock of all groups for this page; do not hold the BG lock when
1041 * calling this routine!
1043 static noinline_for_stack
1044 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1047 struct ext4_group_info *this_grp;
1048 struct ext4_buddy e4b;
1053 mb_debug(1, "init group %u\n", group);
1054 this_grp = ext4_get_group_info(sb, group);
1056 * This ensures that we don't reinit the buddy cache
1057 * page which map to the group from which we are already
1058 * allocating. If we are looking at the buddy cache we would
1059 * have taken a reference using ext4_mb_load_buddy and that
1060 * would have pinned buddy page to page cache.
1061 * The call to ext4_mb_get_buddy_page_lock will mark the
1064 ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1065 if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1067 * somebody initialized the group
1068 * return without doing anything
1073 page = e4b.bd_bitmap_page;
1074 ret = ext4_mb_init_cache(page, NULL, gfp);
1077 if (!PageUptodate(page)) {
1082 if (e4b.bd_buddy_page == NULL) {
1084 * If both the bitmap and buddy are in
1085 * the same page we don't need to force
1091 /* init buddy cache */
1092 page = e4b.bd_buddy_page;
1093 ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1096 if (!PageUptodate(page)) {
1101 ext4_mb_put_buddy_page_lock(&e4b);
1106 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1107 * block group lock of all groups for this page; do not hold the BG lock when
1108 * calling this routine!
1110 static noinline_for_stack int
1111 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1112 struct ext4_buddy *e4b, gfp_t gfp)
1114 int blocks_per_page;
1120 struct ext4_group_info *grp;
1121 struct ext4_sb_info *sbi = EXT4_SB(sb);
1122 struct inode *inode = sbi->s_buddy_cache;
1125 mb_debug(1, "load group %u\n", group);
1127 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1128 grp = ext4_get_group_info(sb, group);
1130 e4b->bd_blkbits = sb->s_blocksize_bits;
1133 e4b->bd_group = group;
1134 e4b->bd_buddy_page = NULL;
1135 e4b->bd_bitmap_page = NULL;
1137 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1139 * we need full data about the group
1140 * to make a good selection
1142 ret = ext4_mb_init_group(sb, group, gfp);
1148 * the buddy cache inode stores the block bitmap
1149 * and buddy information in consecutive blocks.
1150 * So for each group we need two blocks.
1153 pnum = block / blocks_per_page;
1154 poff = block % blocks_per_page;
1156 /* we could use find_or_create_page(), but it locks page
1157 * what we'd like to avoid in fast path ... */
1158 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1159 if (page == NULL || !PageUptodate(page)) {
1162 * drop the page reference and try
1163 * to get the page with lock. If we
1164 * are not uptodate that implies
1165 * somebody just created the page but
1166 * is yet to initialize the same. So
1167 * wait for it to initialize.
1170 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1172 BUG_ON(page->mapping != inode->i_mapping);
1173 if (!PageUptodate(page)) {
1174 ret = ext4_mb_init_cache(page, NULL, gfp);
1179 mb_cmp_bitmaps(e4b, page_address(page) +
1180 (poff * sb->s_blocksize));
1189 if (!PageUptodate(page)) {
1194 /* Pages marked accessed already */
1195 e4b->bd_bitmap_page = page;
1196 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1199 pnum = block / blocks_per_page;
1200 poff = block % blocks_per_page;
1202 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1203 if (page == NULL || !PageUptodate(page)) {
1206 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1208 BUG_ON(page->mapping != inode->i_mapping);
1209 if (!PageUptodate(page)) {
1210 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1224 if (!PageUptodate(page)) {
1229 /* Pages marked accessed already */
1230 e4b->bd_buddy_page = page;
1231 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1233 BUG_ON(e4b->bd_bitmap_page == NULL);
1234 BUG_ON(e4b->bd_buddy_page == NULL);
1241 if (e4b->bd_bitmap_page)
1242 put_page(e4b->bd_bitmap_page);
1243 if (e4b->bd_buddy_page)
1244 put_page(e4b->bd_buddy_page);
1245 e4b->bd_buddy = NULL;
1246 e4b->bd_bitmap = NULL;
1250 static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1251 struct ext4_buddy *e4b)
1253 return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1256 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1258 if (e4b->bd_bitmap_page)
1259 put_page(e4b->bd_bitmap_page);
1260 if (e4b->bd_buddy_page)
1261 put_page(e4b->bd_buddy_page);
1265 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1268 int bb_incr = 1 << (e4b->bd_blkbits - 1);
1271 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1272 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1275 while (order <= e4b->bd_blkbits + 1) {
1277 if (!mb_test_bit(block, bb)) {
1278 /* this block is part of buddy of order 'order' */
1288 static void mb_clear_bits(void *bm, int cur, int len)
1294 if ((cur & 31) == 0 && (len - cur) >= 32) {
1295 /* fast path: clear whole word at once */
1296 addr = bm + (cur >> 3);
1301 mb_clear_bit(cur, bm);
1306 /* clear bits in given range
1307 * will return first found zero bit if any, -1 otherwise
1309 static int mb_test_and_clear_bits(void *bm, int cur, int len)
1316 if ((cur & 31) == 0 && (len - cur) >= 32) {
1317 /* fast path: clear whole word at once */
1318 addr = bm + (cur >> 3);
1319 if (*addr != (__u32)(-1) && zero_bit == -1)
1320 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1325 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1333 void ext4_set_bits(void *bm, int cur, int len)
1339 if ((cur & 31) == 0 && (len - cur) >= 32) {
1340 /* fast path: set whole word at once */
1341 addr = bm + (cur >> 3);
1346 mb_set_bit(cur, bm);
1352 * _________________________________________________________________ */
1354 static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1356 if (mb_test_bit(*bit + side, bitmap)) {
1357 mb_clear_bit(*bit, bitmap);
1363 mb_set_bit(*bit, bitmap);
1368 static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1372 void *buddy = mb_find_buddy(e4b, order, &max);
1377 /* Bits in range [first; last] are known to be set since
1378 * corresponding blocks were allocated. Bits in range
1379 * (first; last) will stay set because they form buddies on
1380 * upper layer. We just deal with borders if they don't
1381 * align with upper layer and then go up.
1382 * Releasing entire group is all about clearing
1383 * single bit of highest order buddy.
1387 * ---------------------------------
1389 * ---------------------------------
1390 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1391 * ---------------------------------
1393 * \_____________________/
1395 * Neither [1] nor [6] is aligned to above layer.
1396 * Left neighbour [0] is free, so mark it busy,
1397 * decrease bb_counters and extend range to
1399 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1400 * mark [6] free, increase bb_counters and shrink range to
1402 * Then shift range to [0; 2], go up and do the same.
1407 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1409 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1414 if (first == last || !(buddy2 = mb_find_buddy(e4b, order, &max))) {
1415 mb_clear_bits(buddy, first, last - first + 1);
1416 e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1425 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1426 int first, int count)
1428 int left_is_free = 0;
1429 int right_is_free = 0;
1431 int last = first + count - 1;
1432 struct super_block *sb = e4b->bd_sb;
1434 if (WARN_ON(count == 0))
1436 BUG_ON(last >= (sb->s_blocksize << 3));
1437 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1438 /* Don't bother if the block group is corrupt. */
1439 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1442 mb_check_buddy(e4b);
1443 mb_free_blocks_double(inode, e4b, first, count);
1445 e4b->bd_info->bb_free += count;
1446 if (first < e4b->bd_info->bb_first_free)
1447 e4b->bd_info->bb_first_free = first;
1449 /* access memory sequentially: check left neighbour,
1450 * clear range and then check right neighbour
1453 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1454 block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1455 if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1456 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1458 if (unlikely(block != -1)) {
1459 struct ext4_sb_info *sbi = EXT4_SB(sb);
1460 ext4_fsblk_t blocknr;
1462 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1463 blocknr += EXT4_C2B(EXT4_SB(sb), block);
1464 ext4_grp_locked_error(sb, e4b->bd_group,
1465 inode ? inode->i_ino : 0,
1467 "freeing already freed block "
1468 "(bit %u); block bitmap corrupt.",
1470 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))
1471 percpu_counter_sub(&sbi->s_freeclusters_counter,
1472 e4b->bd_info->bb_free);
1473 /* Mark the block group as corrupt. */
1474 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT,
1475 &e4b->bd_info->bb_state);
1476 mb_regenerate_buddy(e4b);
1480 /* let's maintain fragments counter */
1481 if (left_is_free && right_is_free)
1482 e4b->bd_info->bb_fragments--;
1483 else if (!left_is_free && !right_is_free)
1484 e4b->bd_info->bb_fragments++;
1486 /* buddy[0] == bd_bitmap is a special case, so handle
1487 * it right away and let mb_buddy_mark_free stay free of
1488 * zero order checks.
1489 * Check if neighbours are to be coaleasced,
1490 * adjust bitmap bb_counters and borders appropriately.
1493 first += !left_is_free;
1494 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1497 last -= !right_is_free;
1498 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1502 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1505 mb_set_largest_free_order(sb, e4b->bd_info);
1506 mb_check_buddy(e4b);
1509 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1510 int needed, struct ext4_free_extent *ex)
1516 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1519 buddy = mb_find_buddy(e4b, 0, &max);
1520 BUG_ON(buddy == NULL);
1521 BUG_ON(block >= max);
1522 if (mb_test_bit(block, buddy)) {
1529 /* find actual order */
1530 order = mb_find_order_for_block(e4b, block);
1531 block = block >> order;
1533 ex->fe_len = 1 << order;
1534 ex->fe_start = block << order;
1535 ex->fe_group = e4b->bd_group;
1537 /* calc difference from given start */
1538 next = next - ex->fe_start;
1540 ex->fe_start += next;
1542 while (needed > ex->fe_len &&
1543 mb_find_buddy(e4b, order, &max)) {
1545 if (block + 1 >= max)
1548 next = (block + 1) * (1 << order);
1549 if (mb_test_bit(next, e4b->bd_bitmap))
1552 order = mb_find_order_for_block(e4b, next);
1554 block = next >> order;
1555 ex->fe_len += 1 << order;
1558 if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
1559 /* Should never happen! (but apparently sometimes does?!?) */
1561 ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
1562 "corruption or bug in mb_find_extent "
1563 "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
1564 block, order, needed, ex->fe_group, ex->fe_start,
1565 ex->fe_len, ex->fe_logical);
1573 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1579 int start = ex->fe_start;
1580 int len = ex->fe_len;
1585 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1586 BUG_ON(e4b->bd_group != ex->fe_group);
1587 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1588 mb_check_buddy(e4b);
1589 mb_mark_used_double(e4b, start, len);
1591 e4b->bd_info->bb_free -= len;
1592 if (e4b->bd_info->bb_first_free == start)
1593 e4b->bd_info->bb_first_free += len;
1595 /* let's maintain fragments counter */
1597 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1598 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1599 max = !mb_test_bit(start + len, e4b->bd_bitmap);
1601 e4b->bd_info->bb_fragments++;
1602 else if (!mlen && !max)
1603 e4b->bd_info->bb_fragments--;
1605 /* let's maintain buddy itself */
1607 ord = mb_find_order_for_block(e4b, start);
1609 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1610 /* the whole chunk may be allocated at once! */
1612 buddy = mb_find_buddy(e4b, ord, &max);
1613 BUG_ON((start >> ord) >= max);
1614 mb_set_bit(start >> ord, buddy);
1615 e4b->bd_info->bb_counters[ord]--;
1622 /* store for history */
1624 ret = len | (ord << 16);
1626 /* we have to split large buddy */
1628 buddy = mb_find_buddy(e4b, ord, &max);
1629 mb_set_bit(start >> ord, buddy);
1630 e4b->bd_info->bb_counters[ord]--;
1633 cur = (start >> ord) & ~1U;
1634 buddy = mb_find_buddy(e4b, ord, &max);
1635 mb_clear_bit(cur, buddy);
1636 mb_clear_bit(cur + 1, buddy);
1637 e4b->bd_info->bb_counters[ord]++;
1638 e4b->bd_info->bb_counters[ord]++;
1640 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1642 ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1643 mb_check_buddy(e4b);
1649 * Must be called under group lock!
1651 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1652 struct ext4_buddy *e4b)
1654 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1657 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1658 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1660 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1661 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1662 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1664 /* preallocation can change ac_b_ex, thus we store actually
1665 * allocated blocks for history */
1666 ac->ac_f_ex = ac->ac_b_ex;
1668 ac->ac_status = AC_STATUS_FOUND;
1669 ac->ac_tail = ret & 0xffff;
1670 ac->ac_buddy = ret >> 16;
1673 * take the page reference. We want the page to be pinned
1674 * so that we don't get a ext4_mb_init_cache_call for this
1675 * group until we update the bitmap. That would mean we
1676 * double allocate blocks. The reference is dropped
1677 * in ext4_mb_release_context
1679 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1680 get_page(ac->ac_bitmap_page);
1681 ac->ac_buddy_page = e4b->bd_buddy_page;
1682 get_page(ac->ac_buddy_page);
1683 /* store last allocated for subsequent stream allocation */
1684 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1685 spin_lock(&sbi->s_md_lock);
1686 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1687 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1688 spin_unlock(&sbi->s_md_lock);
1693 * regular allocator, for general purposes allocation
1696 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1697 struct ext4_buddy *e4b,
1700 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1701 struct ext4_free_extent *bex = &ac->ac_b_ex;
1702 struct ext4_free_extent *gex = &ac->ac_g_ex;
1703 struct ext4_free_extent ex;
1706 if (ac->ac_status == AC_STATUS_FOUND)
1709 * We don't want to scan for a whole year
1711 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1712 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1713 ac->ac_status = AC_STATUS_BREAK;
1718 * Haven't found good chunk so far, let's continue
1720 if (bex->fe_len < gex->fe_len)
1723 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1724 && bex->fe_group == e4b->bd_group) {
1725 /* recheck chunk's availability - we don't know
1726 * when it was found (within this lock-unlock
1728 max = mb_find_extent(e4b, bex->fe_start, gex->fe_len, &ex);
1729 if (max >= gex->fe_len) {
1730 ext4_mb_use_best_found(ac, e4b);
1737 * The routine checks whether found extent is good enough. If it is,
1738 * then the extent gets marked used and flag is set to the context
1739 * to stop scanning. Otherwise, the extent is compared with the
1740 * previous found extent and if new one is better, then it's stored
1741 * in the context. Later, the best found extent will be used, if
1742 * mballoc can't find good enough extent.
1744 * FIXME: real allocation policy is to be designed yet!
1746 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1747 struct ext4_free_extent *ex,
1748 struct ext4_buddy *e4b)
1750 struct ext4_free_extent *bex = &ac->ac_b_ex;
1751 struct ext4_free_extent *gex = &ac->ac_g_ex;
1753 BUG_ON(ex->fe_len <= 0);
1754 BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1755 BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1756 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1761 * The special case - take what you catch first
1763 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1765 ext4_mb_use_best_found(ac, e4b);
1770 * Let's check whether the chuck is good enough
1772 if (ex->fe_len == gex->fe_len) {
1774 ext4_mb_use_best_found(ac, e4b);
1779 * If this is first found extent, just store it in the context
1781 if (bex->fe_len == 0) {
1787 * If new found extent is better, store it in the context
1789 if (bex->fe_len < gex->fe_len) {
1790 /* if the request isn't satisfied, any found extent
1791 * larger than previous best one is better */
1792 if (ex->fe_len > bex->fe_len)
1794 } else if (ex->fe_len > gex->fe_len) {
1795 /* if the request is satisfied, then we try to find
1796 * an extent that still satisfy the request, but is
1797 * smaller than previous one */
1798 if (ex->fe_len < bex->fe_len)
1802 ext4_mb_check_limits(ac, e4b, 0);
1805 static noinline_for_stack
1806 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1807 struct ext4_buddy *e4b)
1809 struct ext4_free_extent ex = ac->ac_b_ex;
1810 ext4_group_t group = ex.fe_group;
1814 BUG_ON(ex.fe_len <= 0);
1815 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1819 ext4_lock_group(ac->ac_sb, group);
1820 max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
1824 ext4_mb_use_best_found(ac, e4b);
1827 ext4_unlock_group(ac->ac_sb, group);
1828 ext4_mb_unload_buddy(e4b);
1833 static noinline_for_stack
1834 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1835 struct ext4_buddy *e4b)
1837 ext4_group_t group = ac->ac_g_ex.fe_group;
1840 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1841 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1842 struct ext4_free_extent ex;
1844 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1846 if (grp->bb_free == 0)
1849 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1853 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
1854 ext4_mb_unload_buddy(e4b);
1858 ext4_lock_group(ac->ac_sb, group);
1859 max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
1860 ac->ac_g_ex.fe_len, &ex);
1861 ex.fe_logical = 0xDEADFA11; /* debug value */
1863 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1866 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
1868 /* use do_div to get remainder (would be 64-bit modulo) */
1869 if (do_div(start, sbi->s_stripe) == 0) {
1872 ext4_mb_use_best_found(ac, e4b);
1874 } else if (max >= ac->ac_g_ex.fe_len) {
1875 BUG_ON(ex.fe_len <= 0);
1876 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1877 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1880 ext4_mb_use_best_found(ac, e4b);
1881 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1882 /* Sometimes, caller may want to merge even small
1883 * number of blocks to an existing extent */
1884 BUG_ON(ex.fe_len <= 0);
1885 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1886 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1889 ext4_mb_use_best_found(ac, e4b);
1891 ext4_unlock_group(ac->ac_sb, group);
1892 ext4_mb_unload_buddy(e4b);
1898 * The routine scans buddy structures (not bitmap!) from given order
1899 * to max order and tries to find big enough chunk to satisfy the req
1901 static noinline_for_stack
1902 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1903 struct ext4_buddy *e4b)
1905 struct super_block *sb = ac->ac_sb;
1906 struct ext4_group_info *grp = e4b->bd_info;
1912 BUG_ON(ac->ac_2order <= 0);
1913 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1914 if (grp->bb_counters[i] == 0)
1917 buddy = mb_find_buddy(e4b, i, &max);
1918 BUG_ON(buddy == NULL);
1920 k = mb_find_next_zero_bit(buddy, max, 0);
1925 ac->ac_b_ex.fe_len = 1 << i;
1926 ac->ac_b_ex.fe_start = k << i;
1927 ac->ac_b_ex.fe_group = e4b->bd_group;
1929 ext4_mb_use_best_found(ac, e4b);
1931 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1933 if (EXT4_SB(sb)->s_mb_stats)
1934 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1941 * The routine scans the group and measures all found extents.
1942 * In order to optimize scanning, caller must pass number of
1943 * free blocks in the group, so the routine can know upper limit.
1945 static noinline_for_stack
1946 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1947 struct ext4_buddy *e4b)
1949 struct super_block *sb = ac->ac_sb;
1950 void *bitmap = e4b->bd_bitmap;
1951 struct ext4_free_extent ex;
1955 free = e4b->bd_info->bb_free;
1956 if (WARN_ON(free <= 0))
1959 i = e4b->bd_info->bb_first_free;
1961 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1962 i = mb_find_next_zero_bit(bitmap,
1963 EXT4_CLUSTERS_PER_GROUP(sb), i);
1964 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
1966 * IF we have corrupt bitmap, we won't find any
1967 * free blocks even though group info says we
1968 * we have free blocks
1970 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1971 "%d free clusters as per "
1972 "group info. But bitmap says 0",
1977 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
1978 if (WARN_ON(ex.fe_len <= 0))
1980 if (free < ex.fe_len) {
1981 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1982 "%d free clusters as per "
1983 "group info. But got %d blocks",
1986 * The number of free blocks differs. This mostly
1987 * indicate that the bitmap is corrupt. So exit
1988 * without claiming the space.
1992 ex.fe_logical = 0xDEADC0DE; /* debug value */
1993 ext4_mb_measure_extent(ac, &ex, e4b);
1999 ext4_mb_check_limits(ac, e4b, 1);
2003 * This is a special case for storages like raid5
2004 * we try to find stripe-aligned chunks for stripe-size-multiple requests
2006 static noinline_for_stack
2007 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2008 struct ext4_buddy *e4b)
2010 struct super_block *sb = ac->ac_sb;
2011 struct ext4_sb_info *sbi = EXT4_SB(sb);
2012 void *bitmap = e4b->bd_bitmap;
2013 struct ext4_free_extent ex;
2014 ext4_fsblk_t first_group_block;
2019 BUG_ON(sbi->s_stripe == 0);
2021 /* find first stripe-aligned block in group */
2022 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2024 a = first_group_block + sbi->s_stripe - 1;
2025 do_div(a, sbi->s_stripe);
2026 i = (a * sbi->s_stripe) - first_group_block;
2028 while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2029 if (!mb_test_bit(i, bitmap)) {
2030 max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
2031 if (max >= sbi->s_stripe) {
2033 ex.fe_logical = 0xDEADF00D; /* debug value */
2035 ext4_mb_use_best_found(ac, e4b);
2044 * This is now called BEFORE we load the buddy bitmap.
2045 * Returns either 1 or 0 indicating that the group is either suitable
2046 * for the allocation or not. In addition it can also return negative
2047 * error code when something goes wrong.
2049 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
2050 ext4_group_t group, int cr)
2052 unsigned free, fragments;
2053 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2054 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2056 BUG_ON(cr < 0 || cr >= 4);
2058 free = grp->bb_free;
2061 if (cr <= 2 && free < ac->ac_g_ex.fe_len)
2064 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2067 /* We only do this if the grp has never been initialized */
2068 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2069 int ret = ext4_mb_init_group(ac->ac_sb, group, GFP_NOFS);
2074 fragments = grp->bb_fragments;
2080 BUG_ON(ac->ac_2order == 0);
2082 /* Avoid using the first bg of a flexgroup for data files */
2083 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2084 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2085 ((group % flex_size) == 0))
2088 if ((ac->ac_2order > ac->ac_sb->s_blocksize_bits+1) ||
2089 (free / fragments) >= ac->ac_g_ex.fe_len)
2092 if (grp->bb_largest_free_order < ac->ac_2order)
2097 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2101 if (free >= ac->ac_g_ex.fe_len)
2113 static noinline_for_stack int
2114 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2116 ext4_group_t ngroups, group, i;
2118 int err = 0, first_err = 0;
2119 struct ext4_sb_info *sbi;
2120 struct super_block *sb;
2121 struct ext4_buddy e4b;
2125 ngroups = ext4_get_groups_count(sb);
2126 /* non-extent files are limited to low blocks/groups */
2127 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2128 ngroups = sbi->s_blockfile_groups;
2130 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2132 /* first, try the goal */
2133 err = ext4_mb_find_by_goal(ac, &e4b);
2134 if (err || ac->ac_status == AC_STATUS_FOUND)
2137 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2141 * ac->ac2_order is set only if the fe_len is a power of 2
2142 * if ac2_order is set we also set criteria to 0 so that we
2143 * try exact allocation using buddy.
2145 i = fls(ac->ac_g_ex.fe_len);
2148 * We search using buddy data only if the order of the request
2149 * is greater than equal to the sbi_s_mb_order2_reqs
2150 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2151 * We also support searching for power-of-two requests only for
2152 * requests upto maximum buddy size we have constructed.
2154 if (i >= sbi->s_mb_order2_reqs && i <= sb->s_blocksize_bits + 2) {
2156 * This should tell if fe_len is exactly power of 2
2158 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2159 ac->ac_2order = array_index_nospec(i - 1,
2160 sb->s_blocksize_bits + 2);
2163 /* if stream allocation is enabled, use global goal */
2164 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2165 /* TBD: may be hot point */
2166 spin_lock(&sbi->s_md_lock);
2167 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2168 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2169 spin_unlock(&sbi->s_md_lock);
2172 /* Let's just scan groups to find more-less suitable blocks */
2173 cr = ac->ac_2order ? 0 : 1;
2175 * cr == 0 try to get exact allocation,
2176 * cr == 3 try to get anything
2179 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2180 ac->ac_criteria = cr;
2182 * searching for the right group start
2183 * from the goal value specified
2185 group = ac->ac_g_ex.fe_group;
2187 for (i = 0; i < ngroups; group++, i++) {
2191 * Artificially restricted ngroups for non-extent
2192 * files makes group > ngroups possible on first loop.
2194 if (group >= ngroups)
2197 /* This now checks without needing the buddy page */
2198 ret = ext4_mb_good_group(ac, group, cr);
2205 err = ext4_mb_load_buddy(sb, group, &e4b);
2209 ext4_lock_group(sb, group);
2212 * We need to check again after locking the
2215 ret = ext4_mb_good_group(ac, group, cr);
2217 ext4_unlock_group(sb, group);
2218 ext4_mb_unload_buddy(&e4b);
2224 ac->ac_groups_scanned++;
2226 ext4_mb_simple_scan_group(ac, &e4b);
2227 else if (cr == 1 && sbi->s_stripe &&
2228 !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2229 ext4_mb_scan_aligned(ac, &e4b);
2231 ext4_mb_complex_scan_group(ac, &e4b);
2233 ext4_unlock_group(sb, group);
2234 ext4_mb_unload_buddy(&e4b);
2236 if (ac->ac_status != AC_STATUS_CONTINUE)
2241 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2242 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2244 * We've been searching too long. Let's try to allocate
2245 * the best chunk we've found so far
2248 ext4_mb_try_best_found(ac, &e4b);
2249 if (ac->ac_status != AC_STATUS_FOUND) {
2251 * Someone more lucky has already allocated it.
2252 * The only thing we can do is just take first
2254 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2256 ac->ac_b_ex.fe_group = 0;
2257 ac->ac_b_ex.fe_start = 0;
2258 ac->ac_b_ex.fe_len = 0;
2259 ac->ac_status = AC_STATUS_CONTINUE;
2260 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2262 atomic_inc(&sbi->s_mb_lost_chunks);
2267 if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2272 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2274 struct super_block *sb = seq->private;
2277 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2280 return (void *) ((unsigned long) group);
2283 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2285 struct super_block *sb = seq->private;
2289 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2292 return (void *) ((unsigned long) group);
2295 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2297 struct super_block *sb = seq->private;
2298 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2300 int err, buddy_loaded = 0;
2301 struct ext4_buddy e4b;
2302 struct ext4_group_info *grinfo;
2303 unsigned char blocksize_bits = min_t(unsigned char,
2304 sb->s_blocksize_bits,
2305 EXT4_MAX_BLOCK_LOG_SIZE);
2307 struct ext4_group_info info;
2308 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
2313 seq_puts(seq, "#group: free frags first ["
2314 " 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
2315 " 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
2317 i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2318 sizeof(struct ext4_group_info);
2320 grinfo = ext4_get_group_info(sb, group);
2321 /* Load the group info in memory only if not already loaded. */
2322 if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
2323 err = ext4_mb_load_buddy(sb, group, &e4b);
2325 seq_printf(seq, "#%-5u: I/O error\n", group);
2331 memcpy(&sg, ext4_get_group_info(sb, group), i);
2334 ext4_mb_unload_buddy(&e4b);
2336 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2337 sg.info.bb_fragments, sg.info.bb_first_free);
2338 for (i = 0; i <= 13; i++)
2339 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
2340 sg.info.bb_counters[i] : 0);
2341 seq_printf(seq, " ]\n");
2346 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2350 static const struct seq_operations ext4_mb_seq_groups_ops = {
2351 .start = ext4_mb_seq_groups_start,
2352 .next = ext4_mb_seq_groups_next,
2353 .stop = ext4_mb_seq_groups_stop,
2354 .show = ext4_mb_seq_groups_show,
2357 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2359 struct super_block *sb = PDE_DATA(inode);
2362 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2364 struct seq_file *m = file->private_data;
2371 const struct file_operations ext4_seq_mb_groups_fops = {
2372 .open = ext4_mb_seq_groups_open,
2374 .llseek = seq_lseek,
2375 .release = seq_release,
2378 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2380 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2381 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2388 * Allocate the top-level s_group_info array for the specified number
2391 int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
2393 struct ext4_sb_info *sbi = EXT4_SB(sb);
2395 struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
2397 size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
2398 EXT4_DESC_PER_BLOCK_BITS(sb);
2399 if (size <= sbi->s_group_info_size)
2402 size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
2403 new_groupinfo = kvzalloc(size, GFP_KERNEL);
2404 if (!new_groupinfo) {
2405 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
2409 old_groupinfo = rcu_dereference(sbi->s_group_info);
2411 memcpy(new_groupinfo, old_groupinfo,
2412 sbi->s_group_info_size * sizeof(*sbi->s_group_info));
2414 rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
2415 sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
2417 ext4_kvfree_array_rcu(old_groupinfo);
2418 ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
2419 sbi->s_group_info_size);
2423 /* Create and initialize ext4_group_info data for the given group. */
2424 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2425 struct ext4_group_desc *desc)
2429 int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
2430 struct ext4_sb_info *sbi = EXT4_SB(sb);
2431 struct ext4_group_info **meta_group_info;
2432 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2435 * First check if this group is the first of a reserved block.
2436 * If it's true, we have to allocate a new table of pointers
2437 * to ext4_group_info structures
2439 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2440 metalen = sizeof(*meta_group_info) <<
2441 EXT4_DESC_PER_BLOCK_BITS(sb);
2442 meta_group_info = kmalloc(metalen, GFP_NOFS);
2443 if (meta_group_info == NULL) {
2444 ext4_msg(sb, KERN_ERR, "can't allocate mem "
2445 "for a buddy group");
2446 goto exit_meta_group_info;
2449 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
2453 meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
2454 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2456 meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
2457 if (meta_group_info[i] == NULL) {
2458 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
2459 goto exit_group_info;
2461 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2462 &(meta_group_info[i]->bb_state));
2465 * initialize bb_free to be able to skip
2466 * empty groups without initialization
2468 if (ext4_has_group_desc_csum(sb) &&
2469 (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
2470 meta_group_info[i]->bb_free =
2471 ext4_free_clusters_after_init(sb, group, desc);
2473 meta_group_info[i]->bb_free =
2474 ext4_free_group_clusters(sb, desc);
2477 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2478 init_rwsem(&meta_group_info[i]->alloc_sem);
2479 meta_group_info[i]->bb_free_root = RB_ROOT;
2480 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
2484 struct buffer_head *bh;
2485 meta_group_info[i]->bb_bitmap =
2486 kmalloc(sb->s_blocksize, GFP_NOFS);
2487 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2488 bh = ext4_read_block_bitmap(sb, group);
2489 BUG_ON(IS_ERR_OR_NULL(bh));
2490 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2499 /* If a meta_group_info table has been allocated, release it now */
2500 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2501 struct ext4_group_info ***group_info;
2504 group_info = rcu_dereference(sbi->s_group_info);
2505 kfree(group_info[idx]);
2506 group_info[idx] = NULL;
2509 exit_meta_group_info:
2511 } /* ext4_mb_add_groupinfo */
2513 static int ext4_mb_init_backend(struct super_block *sb)
2515 ext4_group_t ngroups = ext4_get_groups_count(sb);
2517 struct ext4_sb_info *sbi = EXT4_SB(sb);
2519 struct ext4_group_desc *desc;
2520 struct ext4_group_info ***group_info;
2521 struct kmem_cache *cachep;
2523 err = ext4_mb_alloc_groupinfo(sb, ngroups);
2527 sbi->s_buddy_cache = new_inode(sb);
2528 if (sbi->s_buddy_cache == NULL) {
2529 ext4_msg(sb, KERN_ERR, "can't get new inode");
2532 /* To avoid potentially colliding with an valid on-disk inode number,
2533 * use EXT4_BAD_INO for the buddy cache inode number. This inode is
2534 * not in the inode hash, so it should never be found by iget(), but
2535 * this will avoid confusion if it ever shows up during debugging. */
2536 sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
2537 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2538 for (i = 0; i < ngroups; i++) {
2539 desc = ext4_get_group_desc(sb, i, NULL);
2541 ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2544 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2551 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2553 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2554 i = sbi->s_group_info_size;
2556 group_info = rcu_dereference(sbi->s_group_info);
2558 kfree(group_info[i]);
2560 iput(sbi->s_buddy_cache);
2563 kvfree(rcu_dereference(sbi->s_group_info));
2568 static void ext4_groupinfo_destroy_slabs(void)
2572 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
2573 if (ext4_groupinfo_caches[i])
2574 kmem_cache_destroy(ext4_groupinfo_caches[i]);
2575 ext4_groupinfo_caches[i] = NULL;
2579 static int ext4_groupinfo_create_slab(size_t size)
2581 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
2583 int blocksize_bits = order_base_2(size);
2584 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2585 struct kmem_cache *cachep;
2587 if (cache_index >= NR_GRPINFO_CACHES)
2590 if (unlikely(cache_index < 0))
2593 mutex_lock(&ext4_grpinfo_slab_create_mutex);
2594 if (ext4_groupinfo_caches[cache_index]) {
2595 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2596 return 0; /* Already created */
2599 slab_size = offsetof(struct ext4_group_info,
2600 bb_counters[blocksize_bits + 2]);
2602 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
2603 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
2606 ext4_groupinfo_caches[cache_index] = cachep;
2608 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2611 "EXT4-fs: no memory for groupinfo slab cache\n");
2618 int ext4_mb_init(struct super_block *sb)
2620 struct ext4_sb_info *sbi = EXT4_SB(sb);
2622 unsigned offset, offset_incr;
2626 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2628 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2629 if (sbi->s_mb_offsets == NULL) {
2634 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2635 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2636 if (sbi->s_mb_maxs == NULL) {
2641 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2645 /* order 0 is regular bitmap */
2646 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2647 sbi->s_mb_offsets[0] = 0;
2651 offset_incr = 1 << (sb->s_blocksize_bits - 1);
2652 max = sb->s_blocksize << 2;
2654 sbi->s_mb_offsets[i] = offset;
2655 sbi->s_mb_maxs[i] = max;
2656 offset += offset_incr;
2657 offset_incr = offset_incr >> 1;
2660 } while (i <= sb->s_blocksize_bits + 1);
2662 spin_lock_init(&sbi->s_md_lock);
2663 spin_lock_init(&sbi->s_bal_lock);
2664 sbi->s_mb_free_pending = 0;
2665 INIT_LIST_HEAD(&sbi->s_freed_data_list);
2667 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2668 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2669 sbi->s_mb_stats = MB_DEFAULT_STATS;
2670 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2671 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2673 * The default group preallocation is 512, which for 4k block
2674 * sizes translates to 2 megabytes. However for bigalloc file
2675 * systems, this is probably too big (i.e, if the cluster size
2676 * is 1 megabyte, then group preallocation size becomes half a
2677 * gigabyte!). As a default, we will keep a two megabyte
2678 * group pralloc size for cluster sizes up to 64k, and after
2679 * that, we will force a minimum group preallocation size of
2680 * 32 clusters. This translates to 8 megs when the cluster
2681 * size is 256k, and 32 megs when the cluster size is 1 meg,
2682 * which seems reasonable as a default.
2684 sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
2685 sbi->s_cluster_bits, 32);
2687 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
2688 * to the lowest multiple of s_stripe which is bigger than
2689 * the s_mb_group_prealloc as determined above. We want
2690 * the preallocation size to be an exact multiple of the
2691 * RAID stripe size so that preallocations don't fragment
2694 if (sbi->s_stripe > 1) {
2695 sbi->s_mb_group_prealloc = roundup(
2696 sbi->s_mb_group_prealloc, sbi->s_stripe);
2699 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2700 if (sbi->s_locality_groups == NULL) {
2704 for_each_possible_cpu(i) {
2705 struct ext4_locality_group *lg;
2706 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2707 mutex_init(&lg->lg_mutex);
2708 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2709 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2710 spin_lock_init(&lg->lg_prealloc_lock);
2713 /* init file for buddy data */
2714 ret = ext4_mb_init_backend(sb);
2716 goto out_free_locality_groups;
2720 out_free_locality_groups:
2721 free_percpu(sbi->s_locality_groups);
2722 sbi->s_locality_groups = NULL;
2724 kfree(sbi->s_mb_offsets);
2725 sbi->s_mb_offsets = NULL;
2726 kfree(sbi->s_mb_maxs);
2727 sbi->s_mb_maxs = NULL;
2731 /* need to called with the ext4 group lock held */
2732 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2734 struct ext4_prealloc_space *pa;
2735 struct list_head *cur, *tmp;
2738 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2739 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2740 list_del(&pa->pa_group_list);
2742 kmem_cache_free(ext4_pspace_cachep, pa);
2745 mb_debug(1, "mballoc: %u PAs left\n", count);
2749 int ext4_mb_release(struct super_block *sb)
2751 ext4_group_t ngroups = ext4_get_groups_count(sb);
2753 int num_meta_group_infos;
2754 struct ext4_group_info *grinfo, ***group_info;
2755 struct ext4_sb_info *sbi = EXT4_SB(sb);
2756 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2758 if (sbi->s_group_info) {
2759 for (i = 0; i < ngroups; i++) {
2760 grinfo = ext4_get_group_info(sb, i);
2762 kfree(grinfo->bb_bitmap);
2764 ext4_lock_group(sb, i);
2765 ext4_mb_cleanup_pa(grinfo);
2766 ext4_unlock_group(sb, i);
2767 kmem_cache_free(cachep, grinfo);
2769 num_meta_group_infos = (ngroups +
2770 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2771 EXT4_DESC_PER_BLOCK_BITS(sb);
2773 group_info = rcu_dereference(sbi->s_group_info);
2774 for (i = 0; i < num_meta_group_infos; i++)
2775 kfree(group_info[i]);
2779 kfree(sbi->s_mb_offsets);
2780 kfree(sbi->s_mb_maxs);
2781 iput(sbi->s_buddy_cache);
2782 if (sbi->s_mb_stats) {
2783 ext4_msg(sb, KERN_INFO,
2784 "mballoc: %u blocks %u reqs (%u success)",
2785 atomic_read(&sbi->s_bal_allocated),
2786 atomic_read(&sbi->s_bal_reqs),
2787 atomic_read(&sbi->s_bal_success));
2788 ext4_msg(sb, KERN_INFO,
2789 "mballoc: %u extents scanned, %u goal hits, "
2790 "%u 2^N hits, %u breaks, %u lost",
2791 atomic_read(&sbi->s_bal_ex_scanned),
2792 atomic_read(&sbi->s_bal_goals),
2793 atomic_read(&sbi->s_bal_2orders),
2794 atomic_read(&sbi->s_bal_breaks),
2795 atomic_read(&sbi->s_mb_lost_chunks));
2796 ext4_msg(sb, KERN_INFO,
2797 "mballoc: %lu generated and it took %Lu",
2798 sbi->s_mb_buddies_generated,
2799 sbi->s_mb_generation_time);
2800 ext4_msg(sb, KERN_INFO,
2801 "mballoc: %u preallocated, %u discarded",
2802 atomic_read(&sbi->s_mb_preallocated),
2803 atomic_read(&sbi->s_mb_discarded));
2806 free_percpu(sbi->s_locality_groups);
2811 static inline int ext4_issue_discard(struct super_block *sb,
2812 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
2815 ext4_fsblk_t discard_block;
2817 discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
2818 ext4_group_first_block_no(sb, block_group));
2819 count = EXT4_C2B(EXT4_SB(sb), count);
2820 trace_ext4_discard_blocks(sb,
2821 (unsigned long long) discard_block, count);
2823 return __blkdev_issue_discard(sb->s_bdev,
2824 (sector_t)discard_block << (sb->s_blocksize_bits - 9),
2825 (sector_t)count << (sb->s_blocksize_bits - 9),
2828 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
2831 static void ext4_free_data_in_buddy(struct super_block *sb,
2832 struct ext4_free_data *entry)
2834 struct ext4_buddy e4b;
2835 struct ext4_group_info *db;
2836 int err, count = 0, count2 = 0;
2838 mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2839 entry->efd_count, entry->efd_group, entry);
2841 err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
2842 /* we expect to find existing buddy because it's pinned */
2845 spin_lock(&EXT4_SB(sb)->s_md_lock);
2846 EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
2847 spin_unlock(&EXT4_SB(sb)->s_md_lock);
2850 /* there are blocks to put in buddy to make them really free */
2851 count += entry->efd_count;
2853 ext4_lock_group(sb, entry->efd_group);
2854 /* Take it out of per group rb tree */
2855 rb_erase(&entry->efd_node, &(db->bb_free_root));
2856 mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
2859 * Clear the trimmed flag for the group so that the next
2860 * ext4_trim_fs can trim it.
2861 * If the volume is mounted with -o discard, online discard
2862 * is supported and the free blocks will be trimmed online.
2864 if (!test_opt(sb, DISCARD))
2865 EXT4_MB_GRP_CLEAR_TRIMMED(db);
2867 if (!db->bb_free_root.rb_node) {
2868 /* No more items in the per group rb tree
2869 * balance refcounts from ext4_mb_free_metadata()
2871 put_page(e4b.bd_buddy_page);
2872 put_page(e4b.bd_bitmap_page);
2874 ext4_unlock_group(sb, entry->efd_group);
2875 kmem_cache_free(ext4_free_data_cachep, entry);
2876 ext4_mb_unload_buddy(&e4b);
2878 mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2882 * This function is called by the jbd2 layer once the commit has finished,
2883 * so we know we can free the blocks that were released with that commit.
2885 void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
2887 struct ext4_sb_info *sbi = EXT4_SB(sb);
2888 struct ext4_free_data *entry, *tmp;
2889 struct bio *discard_bio = NULL;
2890 struct list_head freed_data_list;
2891 struct list_head *cut_pos = NULL;
2894 INIT_LIST_HEAD(&freed_data_list);
2896 spin_lock(&sbi->s_md_lock);
2897 list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
2898 if (entry->efd_tid != commit_tid)
2900 cut_pos = &entry->efd_list;
2903 list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
2905 spin_unlock(&sbi->s_md_lock);
2907 if (test_opt(sb, DISCARD)) {
2908 list_for_each_entry(entry, &freed_data_list, efd_list) {
2909 err = ext4_issue_discard(sb, entry->efd_group,
2910 entry->efd_start_cluster,
2913 if (err && err != -EOPNOTSUPP) {
2914 ext4_msg(sb, KERN_WARNING, "discard request in"
2915 " group:%d block:%d count:%d failed"
2916 " with %d", entry->efd_group,
2917 entry->efd_start_cluster,
2918 entry->efd_count, err);
2919 } else if (err == -EOPNOTSUPP)
2924 submit_bio_wait(discard_bio);
2925 bio_put(discard_bio);
2929 list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
2930 ext4_free_data_in_buddy(sb, entry);
2933 int __init ext4_init_mballoc(void)
2935 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
2936 SLAB_RECLAIM_ACCOUNT);
2937 if (ext4_pspace_cachep == NULL)
2940 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
2941 SLAB_RECLAIM_ACCOUNT);
2942 if (ext4_ac_cachep == NULL) {
2943 kmem_cache_destroy(ext4_pspace_cachep);
2947 ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
2948 SLAB_RECLAIM_ACCOUNT);
2949 if (ext4_free_data_cachep == NULL) {
2950 kmem_cache_destroy(ext4_pspace_cachep);
2951 kmem_cache_destroy(ext4_ac_cachep);
2957 void ext4_exit_mballoc(void)
2960 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
2961 * before destroying the slab cache.
2964 kmem_cache_destroy(ext4_pspace_cachep);
2965 kmem_cache_destroy(ext4_ac_cachep);
2966 kmem_cache_destroy(ext4_free_data_cachep);
2967 ext4_groupinfo_destroy_slabs();
2972 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2973 * Returns 0 if success or error code
2975 static noinline_for_stack int
2976 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2977 handle_t *handle, unsigned int reserv_clstrs)
2979 struct buffer_head *bitmap_bh = NULL;
2980 struct ext4_group_desc *gdp;
2981 struct buffer_head *gdp_bh;
2982 struct ext4_sb_info *sbi;
2983 struct super_block *sb;
2987 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2988 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2993 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2994 if (IS_ERR(bitmap_bh)) {
2995 err = PTR_ERR(bitmap_bh);
3000 BUFFER_TRACE(bitmap_bh, "getting write access");
3001 err = ext4_journal_get_write_access(handle, bitmap_bh);
3006 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3010 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
3011 ext4_free_group_clusters(sb, gdp));
3013 BUFFER_TRACE(gdp_bh, "get_write_access");
3014 err = ext4_journal_get_write_access(handle, gdp_bh);
3018 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3020 len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3021 if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
3022 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
3023 "fs metadata", block, block+len);
3024 /* File system mounted not to panic on error
3025 * Fix the bitmap and return EFSCORRUPTED
3026 * We leak some of the blocks here.
3028 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3029 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3030 ac->ac_b_ex.fe_len);
3031 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3032 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3034 err = -EFSCORRUPTED;
3038 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3039 #ifdef AGGRESSIVE_CHECK
3042 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3043 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3044 bitmap_bh->b_data));
3048 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3049 ac->ac_b_ex.fe_len);
3050 if (ext4_has_group_desc_csum(sb) &&
3051 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3052 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3053 ext4_free_group_clusters_set(sb, gdp,
3054 ext4_free_clusters_after_init(sb,
3055 ac->ac_b_ex.fe_group, gdp));
3057 len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
3058 ext4_free_group_clusters_set(sb, gdp, len);
3059 ext4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);
3060 ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
3062 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3063 percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
3065 * Now reduce the dirty block count also. Should not go negative
3067 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3068 /* release all the reserved blocks if non delalloc */
3069 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
3072 if (sbi->s_log_groups_per_flex) {
3073 ext4_group_t flex_group = ext4_flex_group(sbi,
3074 ac->ac_b_ex.fe_group);
3075 atomic64_sub(ac->ac_b_ex.fe_len,
3076 &sbi_array_rcu_deref(sbi, s_flex_groups,
3077 flex_group)->free_clusters);
3080 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3083 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3091 * here we normalize request for locality group
3092 * Group request are normalized to s_mb_group_prealloc, which goes to
3093 * s_strip if we set the same via mount option.
3094 * s_mb_group_prealloc can be configured via
3095 * /sys/fs/ext4/<partition>/mb_group_prealloc
3097 * XXX: should we try to preallocate more than the group has now?
3099 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3101 struct super_block *sb = ac->ac_sb;
3102 struct ext4_locality_group *lg = ac->ac_lg;
3105 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3106 mb_debug(1, "#%u: goal %u blocks for locality group\n",
3107 current->pid, ac->ac_g_ex.fe_len);
3111 * Normalization means making request better in terms of
3112 * size and alignment
3114 static noinline_for_stack void
3115 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3116 struct ext4_allocation_request *ar)
3118 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3121 loff_t size, start_off;
3122 loff_t orig_size __maybe_unused;
3124 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3125 struct ext4_prealloc_space *pa;
3127 /* do normalize only data requests, metadata requests
3128 do not need preallocation */
3129 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3132 /* sometime caller may want exact blocks */
3133 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3136 /* caller may indicate that preallocation isn't
3137 * required (it's a tail, for example) */
3138 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3141 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3142 ext4_mb_normalize_group_request(ac);
3146 bsbits = ac->ac_sb->s_blocksize_bits;
3148 /* first, let's learn actual file size
3149 * given current request is allocated */
3150 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
3151 size = size << bsbits;
3152 if (size < i_size_read(ac->ac_inode))
3153 size = i_size_read(ac->ac_inode);
3156 /* max size of free chunks */
3159 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
3160 (req <= (size) || max <= (chunk_size))
3162 /* first, try to predict filesize */
3163 /* XXX: should this table be tunable? */
3165 if (size <= 16 * 1024) {
3167 } else if (size <= 32 * 1024) {
3169 } else if (size <= 64 * 1024) {
3171 } else if (size <= 128 * 1024) {
3173 } else if (size <= 256 * 1024) {
3175 } else if (size <= 512 * 1024) {
3177 } else if (size <= 1024 * 1024) {
3179 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3180 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3181 (21 - bsbits)) << 21;
3182 size = 2 * 1024 * 1024;
3183 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3184 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3185 (22 - bsbits)) << 22;
3186 size = 4 * 1024 * 1024;
3187 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3188 (8<<20)>>bsbits, max, 8 * 1024)) {
3189 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3190 (23 - bsbits)) << 23;
3191 size = 8 * 1024 * 1024;
3193 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
3194 size = (loff_t) EXT4_C2B(EXT4_SB(ac->ac_sb),
3195 ac->ac_o_ex.fe_len) << bsbits;
3197 size = size >> bsbits;
3198 start = start_off >> bsbits;
3200 /* don't cover already allocated blocks in selected range */
3201 if (ar->pleft && start <= ar->lleft) {
3202 size -= ar->lleft + 1 - start;
3203 start = ar->lleft + 1;
3205 if (ar->pright && start + size - 1 >= ar->lright)
3206 size -= start + size - ar->lright;
3209 * Trim allocation request for filesystems with artificially small
3212 if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
3213 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
3217 /* check we don't cross already preallocated blocks */
3219 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3224 spin_lock(&pa->pa_lock);
3225 if (pa->pa_deleted) {
3226 spin_unlock(&pa->pa_lock);
3230 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3233 /* PA must not overlap original request */
3234 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3235 ac->ac_o_ex.fe_logical < pa->pa_lstart));
3237 /* skip PAs this normalized request doesn't overlap with */
3238 if (pa->pa_lstart >= end || pa_end <= start) {
3239 spin_unlock(&pa->pa_lock);
3242 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3244 /* adjust start or end to be adjacent to this pa */
3245 if (pa_end <= ac->ac_o_ex.fe_logical) {
3246 BUG_ON(pa_end < start);
3248 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3249 BUG_ON(pa->pa_lstart > end);
3250 end = pa->pa_lstart;
3252 spin_unlock(&pa->pa_lock);
3257 /* XXX: extra loop to check we really don't overlap preallocations */
3259 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3262 spin_lock(&pa->pa_lock);
3263 if (pa->pa_deleted == 0) {
3264 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3266 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3268 spin_unlock(&pa->pa_lock);
3272 if (start + size <= ac->ac_o_ex.fe_logical &&
3273 start > ac->ac_o_ex.fe_logical) {
3274 ext4_msg(ac->ac_sb, KERN_ERR,
3275 "start %lu, size %lu, fe_logical %lu",
3276 (unsigned long) start, (unsigned long) size,
3277 (unsigned long) ac->ac_o_ex.fe_logical);
3280 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3282 /* now prepare goal request */
3284 /* XXX: is it better to align blocks WRT to logical
3285 * placement or satisfy big request as is */
3286 ac->ac_g_ex.fe_logical = start;
3287 ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3289 /* define goal start in order to merge */
3290 if (ar->pright && (ar->lright == (start + size))) {
3291 /* merge to the right */
3292 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3293 &ac->ac_f_ex.fe_group,
3294 &ac->ac_f_ex.fe_start);
3295 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3297 if (ar->pleft && (ar->lleft + 1 == start)) {
3298 /* merge to the left */
3299 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3300 &ac->ac_f_ex.fe_group,
3301 &ac->ac_f_ex.fe_start);
3302 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3305 mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3306 (unsigned) orig_size, (unsigned) start);
3309 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3311 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3313 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3314 atomic_inc(&sbi->s_bal_reqs);
3315 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3316 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3317 atomic_inc(&sbi->s_bal_success);
3318 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3319 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3320 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3321 atomic_inc(&sbi->s_bal_goals);
3322 if (ac->ac_found > sbi->s_mb_max_to_scan)
3323 atomic_inc(&sbi->s_bal_breaks);
3326 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3327 trace_ext4_mballoc_alloc(ac);
3329 trace_ext4_mballoc_prealloc(ac);
3333 * Called on failure; free up any blocks from the inode PA for this
3334 * context. We don't need this for MB_GROUP_PA because we only change
3335 * pa_free in ext4_mb_release_context(), but on failure, we've already
3336 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3338 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3340 struct ext4_prealloc_space *pa = ac->ac_pa;
3341 struct ext4_buddy e4b;
3345 if (ac->ac_f_ex.fe_len == 0)
3347 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
3350 * This should never happen since we pin the
3351 * pages in the ext4_allocation_context so
3352 * ext4_mb_load_buddy() should never fail.
3354 WARN(1, "mb_load_buddy failed (%d)", err);
3357 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3358 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
3359 ac->ac_f_ex.fe_len);
3360 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3361 ext4_mb_unload_buddy(&e4b);
3364 if (pa->pa_type == MB_INODE_PA)
3365 pa->pa_free += ac->ac_b_ex.fe_len;
3369 * use blocks preallocated to inode
3371 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3372 struct ext4_prealloc_space *pa)
3374 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3379 /* found preallocated blocks, use them */
3380 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3381 end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
3382 start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
3383 len = EXT4_NUM_B2C(sbi, end - start);
3384 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3385 &ac->ac_b_ex.fe_start);
3386 ac->ac_b_ex.fe_len = len;
3387 ac->ac_status = AC_STATUS_FOUND;
3390 BUG_ON(start < pa->pa_pstart);
3391 BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3392 BUG_ON(pa->pa_free < len);
3395 mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3399 * use blocks preallocated to locality group
3401 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3402 struct ext4_prealloc_space *pa)
3404 unsigned int len = ac->ac_o_ex.fe_len;
3406 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3407 &ac->ac_b_ex.fe_group,
3408 &ac->ac_b_ex.fe_start);
3409 ac->ac_b_ex.fe_len = len;
3410 ac->ac_status = AC_STATUS_FOUND;
3413 /* we don't correct pa_pstart or pa_plen here to avoid
3414 * possible race when the group is being loaded concurrently
3415 * instead we correct pa later, after blocks are marked
3416 * in on-disk bitmap -- see ext4_mb_release_context()
3417 * Other CPUs are prevented from allocating from this pa by lg_mutex
3419 mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3423 * Return the prealloc space that have minimal distance
3424 * from the goal block. @cpa is the prealloc
3425 * space that is having currently known minimal distance
3426 * from the goal block.
3428 static struct ext4_prealloc_space *
3429 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3430 struct ext4_prealloc_space *pa,
3431 struct ext4_prealloc_space *cpa)
3433 ext4_fsblk_t cur_distance, new_distance;
3436 atomic_inc(&pa->pa_count);
3439 cur_distance = abs(goal_block - cpa->pa_pstart);
3440 new_distance = abs(goal_block - pa->pa_pstart);
3442 if (cur_distance <= new_distance)
3445 /* drop the previous reference */
3446 atomic_dec(&cpa->pa_count);
3447 atomic_inc(&pa->pa_count);
3452 * search goal blocks in preallocated space
3454 static noinline_for_stack int
3455 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3457 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3459 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3460 struct ext4_locality_group *lg;
3461 struct ext4_prealloc_space *pa, *cpa = NULL;
3462 ext4_fsblk_t goal_block;
3464 /* only data can be preallocated */
3465 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3468 /* first, try per-file preallocation */
3470 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3472 /* all fields in this condition don't change,
3473 * so we can skip locking for them */
3474 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3475 ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
3476 EXT4_C2B(sbi, pa->pa_len)))
3479 /* non-extent files can't have physical blocks past 2^32 */
3480 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3481 (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
3482 EXT4_MAX_BLOCK_FILE_PHYS))
3485 /* found preallocated blocks, use them */
3486 spin_lock(&pa->pa_lock);
3487 if (pa->pa_deleted == 0 && pa->pa_free) {
3488 atomic_inc(&pa->pa_count);
3489 ext4_mb_use_inode_pa(ac, pa);
3490 spin_unlock(&pa->pa_lock);
3491 ac->ac_criteria = 10;
3495 spin_unlock(&pa->pa_lock);
3499 /* can we use group allocation? */
3500 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3503 /* inode may have no locality group for some reason */
3507 order = fls(ac->ac_o_ex.fe_len) - 1;
3508 if (order > PREALLOC_TB_SIZE - 1)
3509 /* The max size of hash table is PREALLOC_TB_SIZE */
3510 order = PREALLOC_TB_SIZE - 1;
3512 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3514 * search for the prealloc space that is having
3515 * minimal distance from the goal block.
3517 for (i = order; i < PREALLOC_TB_SIZE; i++) {
3519 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3521 spin_lock(&pa->pa_lock);
3522 if (pa->pa_deleted == 0 &&
3523 pa->pa_free >= ac->ac_o_ex.fe_len) {
3525 cpa = ext4_mb_check_group_pa(goal_block,
3528 spin_unlock(&pa->pa_lock);
3533 ext4_mb_use_group_pa(ac, cpa);
3534 ac->ac_criteria = 20;
3541 * the function goes through all block freed in the group
3542 * but not yet committed and marks them used in in-core bitmap.
3543 * buddy must be generated from this bitmap
3544 * Need to be called with the ext4 group lock held
3546 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3550 struct ext4_group_info *grp;
3551 struct ext4_free_data *entry;
3553 grp = ext4_get_group_info(sb, group);
3554 n = rb_first(&(grp->bb_free_root));
3557 entry = rb_entry(n, struct ext4_free_data, efd_node);
3558 ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
3565 * the function goes through all preallocation in this group and marks them
3566 * used in in-core bitmap. buddy must be generated from this bitmap
3567 * Need to be called with ext4 group lock held
3569 static noinline_for_stack
3570 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3573 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3574 struct ext4_prealloc_space *pa;
3575 struct list_head *cur;
3576 ext4_group_t groupnr;
3577 ext4_grpblk_t start;
3578 int preallocated = 0;
3581 /* all form of preallocation discards first load group,
3582 * so the only competing code is preallocation use.
3583 * we don't need any locking here
3584 * notice we do NOT ignore preallocations with pa_deleted
3585 * otherwise we could leave used blocks available for
3586 * allocation in buddy when concurrent ext4_mb_put_pa()
3587 * is dropping preallocation
3589 list_for_each(cur, &grp->bb_prealloc_list) {
3590 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3591 spin_lock(&pa->pa_lock);
3592 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3595 spin_unlock(&pa->pa_lock);
3596 if (unlikely(len == 0))
3598 BUG_ON(groupnr != group);
3599 ext4_set_bits(bitmap, start, len);
3600 preallocated += len;
3602 mb_debug(1, "preallocated %u for group %u\n", preallocated, group);
3605 static void ext4_mb_pa_callback(struct rcu_head *head)
3607 struct ext4_prealloc_space *pa;
3608 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3610 BUG_ON(atomic_read(&pa->pa_count));
3611 BUG_ON(pa->pa_deleted == 0);
3612 kmem_cache_free(ext4_pspace_cachep, pa);
3616 * drops a reference to preallocated space descriptor
3617 * if this was the last reference and the space is consumed
3619 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3620 struct super_block *sb, struct ext4_prealloc_space *pa)
3623 ext4_fsblk_t grp_blk;
3625 /* in this short window concurrent discard can set pa_deleted */
3626 spin_lock(&pa->pa_lock);
3627 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
3628 spin_unlock(&pa->pa_lock);
3632 if (pa->pa_deleted == 1) {
3633 spin_unlock(&pa->pa_lock);
3638 spin_unlock(&pa->pa_lock);
3640 grp_blk = pa->pa_pstart;
3642 * If doing group-based preallocation, pa_pstart may be in the
3643 * next group when pa is used up
3645 if (pa->pa_type == MB_GROUP_PA)
3648 grp = ext4_get_group_number(sb, grp_blk);
3653 * P1 (buddy init) P2 (regular allocation)
3654 * find block B in PA
3655 * copy on-disk bitmap to buddy
3656 * mark B in on-disk bitmap
3657 * drop PA from group
3658 * mark all PAs in buddy
3660 * thus, P1 initializes buddy with B available. to prevent this
3661 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3664 ext4_lock_group(sb, grp);
3665 list_del(&pa->pa_group_list);
3666 ext4_unlock_group(sb, grp);
3668 spin_lock(pa->pa_obj_lock);
3669 list_del_rcu(&pa->pa_inode_list);
3670 spin_unlock(pa->pa_obj_lock);
3672 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3676 * creates new preallocated space for given inode
3678 static noinline_for_stack int
3679 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3681 struct super_block *sb = ac->ac_sb;
3682 struct ext4_sb_info *sbi = EXT4_SB(sb);
3683 struct ext4_prealloc_space *pa;
3684 struct ext4_group_info *grp;
3685 struct ext4_inode_info *ei;
3687 /* preallocate only when found space is larger then requested */
3688 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3689 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3690 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3692 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3696 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3702 /* we can't allocate as much as normalizer wants.
3703 * so, found space must get proper lstart
3704 * to cover original request */
3705 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3706 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3708 /* we're limited by original request in that
3709 * logical block must be covered any way
3710 * winl is window we can move our chunk within */
3711 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3713 /* also, we should cover whole original request */
3714 wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
3716 /* the smallest one defines real window */
3717 win = min(winl, wins);
3719 offs = ac->ac_o_ex.fe_logical %
3720 EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3721 if (offs && offs < win)
3724 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
3725 EXT4_NUM_B2C(sbi, win);
3726 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3727 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3730 /* preallocation can change ac_b_ex, thus we store actually
3731 * allocated blocks for history */
3732 ac->ac_f_ex = ac->ac_b_ex;
3734 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3735 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3736 pa->pa_len = ac->ac_b_ex.fe_len;
3737 pa->pa_free = pa->pa_len;
3738 atomic_set(&pa->pa_count, 1);
3739 spin_lock_init(&pa->pa_lock);
3740 INIT_LIST_HEAD(&pa->pa_inode_list);
3741 INIT_LIST_HEAD(&pa->pa_group_list);
3743 pa->pa_type = MB_INODE_PA;
3745 mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3746 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3747 trace_ext4_mb_new_inode_pa(ac, pa);
3749 ext4_mb_use_inode_pa(ac, pa);
3750 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
3752 ei = EXT4_I(ac->ac_inode);
3753 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3755 pa->pa_obj_lock = &ei->i_prealloc_lock;
3756 pa->pa_inode = ac->ac_inode;
3758 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3759 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3760 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3762 spin_lock(pa->pa_obj_lock);
3763 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3764 spin_unlock(pa->pa_obj_lock);
3770 * creates new preallocated space for locality group inodes belongs to
3772 static noinline_for_stack int
3773 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3775 struct super_block *sb = ac->ac_sb;
3776 struct ext4_locality_group *lg;
3777 struct ext4_prealloc_space *pa;
3778 struct ext4_group_info *grp;
3780 /* preallocate only when found space is larger then requested */
3781 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3782 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3783 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3785 BUG_ON(ext4_pspace_cachep == NULL);
3786 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3790 /* preallocation can change ac_b_ex, thus we store actually
3791 * allocated blocks for history */
3792 ac->ac_f_ex = ac->ac_b_ex;
3794 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3795 pa->pa_lstart = pa->pa_pstart;
3796 pa->pa_len = ac->ac_b_ex.fe_len;
3797 pa->pa_free = pa->pa_len;
3798 atomic_set(&pa->pa_count, 1);
3799 spin_lock_init(&pa->pa_lock);
3800 INIT_LIST_HEAD(&pa->pa_inode_list);
3801 INIT_LIST_HEAD(&pa->pa_group_list);
3803 pa->pa_type = MB_GROUP_PA;
3805 mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3806 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3807 trace_ext4_mb_new_group_pa(ac, pa);
3809 ext4_mb_use_group_pa(ac, pa);
3810 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3812 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3816 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3817 pa->pa_inode = NULL;
3819 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3820 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3821 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3824 * We will later add the new pa to the right bucket
3825 * after updating the pa_free in ext4_mb_release_context
3830 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3834 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3835 err = ext4_mb_new_group_pa(ac);
3837 err = ext4_mb_new_inode_pa(ac);
3842 * finds all unused blocks in on-disk bitmap, frees them in
3843 * in-core bitmap and buddy.
3844 * @pa must be unlinked from inode and group lists, so that
3845 * nobody else can find/use it.
3846 * the caller MUST hold group/inode locks.
3847 * TODO: optimize the case when there are no in-core structures yet
3849 static noinline_for_stack int
3850 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3851 struct ext4_prealloc_space *pa)
3853 struct super_block *sb = e4b->bd_sb;
3854 struct ext4_sb_info *sbi = EXT4_SB(sb);
3859 unsigned long long grp_blk_start;
3863 BUG_ON(pa->pa_deleted == 0);
3864 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3865 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
3866 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3867 end = bit + pa->pa_len;
3870 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3873 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3874 mb_debug(1, " free preallocated %u/%u in group %u\n",
3875 (unsigned) ext4_group_first_block_no(sb, group) + bit,
3876 (unsigned) next - bit, (unsigned) group);
3879 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
3880 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
3881 EXT4_C2B(sbi, bit)),
3883 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3886 if (free != pa->pa_free) {
3887 ext4_msg(e4b->bd_sb, KERN_CRIT,
3888 "pa %p: logic %lu, phys. %lu, len %lu",
3889 pa, (unsigned long) pa->pa_lstart,
3890 (unsigned long) pa->pa_pstart,
3891 (unsigned long) pa->pa_len);
3892 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
3895 * pa is already deleted so we use the value obtained
3896 * from the bitmap and continue.
3899 atomic_add(free, &sbi->s_mb_discarded);
3904 static noinline_for_stack int
3905 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3906 struct ext4_prealloc_space *pa)
3908 struct super_block *sb = e4b->bd_sb;
3912 trace_ext4_mb_release_group_pa(sb, pa);
3913 BUG_ON(pa->pa_deleted == 0);
3914 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3915 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3916 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3917 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3918 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3924 * releases all preallocations in given group
3926 * first, we need to decide discard policy:
3927 * - when do we discard
3929 * - how many do we discard
3930 * 1) how many requested
3932 static noinline_for_stack int
3933 ext4_mb_discard_group_preallocations(struct super_block *sb,
3934 ext4_group_t group, int needed)
3936 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3937 struct buffer_head *bitmap_bh = NULL;
3938 struct ext4_prealloc_space *pa, *tmp;
3939 struct list_head list;
3940 struct ext4_buddy e4b;
3945 mb_debug(1, "discard preallocation for group %u\n", group);
3947 if (list_empty(&grp->bb_prealloc_list))
3950 bitmap_bh = ext4_read_block_bitmap(sb, group);
3951 if (IS_ERR(bitmap_bh)) {
3952 err = PTR_ERR(bitmap_bh);
3953 ext4_error(sb, "Error %d reading block bitmap for %u",
3958 err = ext4_mb_load_buddy(sb, group, &e4b);
3960 ext4_warning(sb, "Error %d loading buddy information for %u",
3967 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
3969 INIT_LIST_HEAD(&list);
3971 ext4_lock_group(sb, group);
3972 list_for_each_entry_safe(pa, tmp,
3973 &grp->bb_prealloc_list, pa_group_list) {
3974 spin_lock(&pa->pa_lock);
3975 if (atomic_read(&pa->pa_count)) {
3976 spin_unlock(&pa->pa_lock);
3980 if (pa->pa_deleted) {
3981 spin_unlock(&pa->pa_lock);
3985 /* seems this one can be freed ... */
3988 /* we can trust pa_free ... */
3989 free += pa->pa_free;
3991 spin_unlock(&pa->pa_lock);
3993 list_del(&pa->pa_group_list);
3994 list_add(&pa->u.pa_tmp_list, &list);
3997 /* if we still need more blocks and some PAs were used, try again */
3998 if (free < needed && busy) {
4000 ext4_unlock_group(sb, group);
4005 /* found anything to free? */
4006 if (list_empty(&list)) {
4011 /* now free all selected PAs */
4012 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4014 /* remove from object (inode or locality group) */
4015 spin_lock(pa->pa_obj_lock);
4016 list_del_rcu(&pa->pa_inode_list);
4017 spin_unlock(pa->pa_obj_lock);
4019 if (pa->pa_type == MB_GROUP_PA)
4020 ext4_mb_release_group_pa(&e4b, pa);
4022 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4024 list_del(&pa->u.pa_tmp_list);
4025 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4029 ext4_unlock_group(sb, group);
4030 ext4_mb_unload_buddy(&e4b);
4036 * releases all non-used preallocated blocks for given inode
4038 * It's important to discard preallocations under i_data_sem
4039 * We don't want another block to be served from the prealloc
4040 * space when we are discarding the inode prealloc space.
4042 * FIXME!! Make sure it is valid at all the call sites
4044 void ext4_discard_preallocations(struct inode *inode)
4046 struct ext4_inode_info *ei = EXT4_I(inode);
4047 struct super_block *sb = inode->i_sb;
4048 struct buffer_head *bitmap_bh = NULL;
4049 struct ext4_prealloc_space *pa, *tmp;
4050 ext4_group_t group = 0;
4051 struct list_head list;
4052 struct ext4_buddy e4b;
4055 if (!S_ISREG(inode->i_mode)) {
4056 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4060 mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
4061 trace_ext4_discard_preallocations(inode);
4063 INIT_LIST_HEAD(&list);
4066 /* first, collect all pa's in the inode */
4067 spin_lock(&ei->i_prealloc_lock);
4068 while (!list_empty(&ei->i_prealloc_list)) {
4069 pa = list_entry(ei->i_prealloc_list.next,
4070 struct ext4_prealloc_space, pa_inode_list);
4071 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4072 spin_lock(&pa->pa_lock);
4073 if (atomic_read(&pa->pa_count)) {
4074 /* this shouldn't happen often - nobody should
4075 * use preallocation while we're discarding it */
4076 spin_unlock(&pa->pa_lock);
4077 spin_unlock(&ei->i_prealloc_lock);
4078 ext4_msg(sb, KERN_ERR,
4079 "uh-oh! used pa while discarding");
4081 schedule_timeout_uninterruptible(HZ);
4085 if (pa->pa_deleted == 0) {
4087 spin_unlock(&pa->pa_lock);
4088 list_del_rcu(&pa->pa_inode_list);
4089 list_add(&pa->u.pa_tmp_list, &list);
4093 /* someone is deleting pa right now */
4094 spin_unlock(&pa->pa_lock);
4095 spin_unlock(&ei->i_prealloc_lock);
4097 /* we have to wait here because pa_deleted
4098 * doesn't mean pa is already unlinked from
4099 * the list. as we might be called from
4100 * ->clear_inode() the inode will get freed
4101 * and concurrent thread which is unlinking
4102 * pa from inode's list may access already
4103 * freed memory, bad-bad-bad */
4105 /* XXX: if this happens too often, we can
4106 * add a flag to force wait only in case
4107 * of ->clear_inode(), but not in case of
4108 * regular truncate */
4109 schedule_timeout_uninterruptible(HZ);
4112 spin_unlock(&ei->i_prealloc_lock);
4114 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4115 BUG_ON(pa->pa_type != MB_INODE_PA);
4116 group = ext4_get_group_number(sb, pa->pa_pstart);
4118 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4119 GFP_NOFS|__GFP_NOFAIL);
4121 ext4_error(sb, "Error %d loading buddy information for %u",
4126 bitmap_bh = ext4_read_block_bitmap(sb, group);
4127 if (IS_ERR(bitmap_bh)) {
4128 err = PTR_ERR(bitmap_bh);
4129 ext4_error(sb, "Error %d reading block bitmap for %u",
4131 ext4_mb_unload_buddy(&e4b);
4135 ext4_lock_group(sb, group);
4136 list_del(&pa->pa_group_list);
4137 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4138 ext4_unlock_group(sb, group);
4140 ext4_mb_unload_buddy(&e4b);
4143 list_del(&pa->u.pa_tmp_list);
4144 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4148 #ifdef CONFIG_EXT4_DEBUG
4149 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4151 struct super_block *sb = ac->ac_sb;
4152 ext4_group_t ngroups, i;
4154 if (!ext4_mballoc_debug ||
4155 (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
4158 ext4_msg(ac->ac_sb, KERN_ERR, "Can't allocate:"
4159 " Allocation context details:");
4160 ext4_msg(ac->ac_sb, KERN_ERR, "status %d flags %d",
4161 ac->ac_status, ac->ac_flags);
4162 ext4_msg(ac->ac_sb, KERN_ERR, "orig %lu/%lu/%lu@%lu, "
4163 "goal %lu/%lu/%lu@%lu, "
4164 "best %lu/%lu/%lu@%lu cr %d",
4165 (unsigned long)ac->ac_o_ex.fe_group,
4166 (unsigned long)ac->ac_o_ex.fe_start,
4167 (unsigned long)ac->ac_o_ex.fe_len,
4168 (unsigned long)ac->ac_o_ex.fe_logical,
4169 (unsigned long)ac->ac_g_ex.fe_group,
4170 (unsigned long)ac->ac_g_ex.fe_start,
4171 (unsigned long)ac->ac_g_ex.fe_len,
4172 (unsigned long)ac->ac_g_ex.fe_logical,
4173 (unsigned long)ac->ac_b_ex.fe_group,
4174 (unsigned long)ac->ac_b_ex.fe_start,
4175 (unsigned long)ac->ac_b_ex.fe_len,
4176 (unsigned long)ac->ac_b_ex.fe_logical,
4177 (int)ac->ac_criteria);
4178 ext4_msg(ac->ac_sb, KERN_ERR, "%d found", ac->ac_found);
4179 ext4_msg(ac->ac_sb, KERN_ERR, "groups: ");
4180 ngroups = ext4_get_groups_count(sb);
4181 for (i = 0; i < ngroups; i++) {
4182 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4183 struct ext4_prealloc_space *pa;
4184 ext4_grpblk_t start;
4185 struct list_head *cur;
4186 ext4_lock_group(sb, i);
4187 list_for_each(cur, &grp->bb_prealloc_list) {
4188 pa = list_entry(cur, struct ext4_prealloc_space,
4190 spin_lock(&pa->pa_lock);
4191 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4193 spin_unlock(&pa->pa_lock);
4194 printk(KERN_ERR "PA:%u:%d:%u \n", i,
4197 ext4_unlock_group(sb, i);
4199 if (grp->bb_free == 0)
4201 printk(KERN_ERR "%u: %d/%d \n",
4202 i, grp->bb_free, grp->bb_fragments);
4204 printk(KERN_ERR "\n");
4207 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4214 * We use locality group preallocation for small size file. The size of the
4215 * file is determined by the current size or the resulting size after
4216 * allocation which ever is larger
4218 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4220 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4222 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4223 int bsbits = ac->ac_sb->s_blocksize_bits;
4226 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4229 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4232 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
4233 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
4236 if ((size == isize) &&
4237 !ext4_fs_is_busy(sbi) &&
4238 (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
4239 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
4243 if (sbi->s_mb_group_prealloc <= 0) {
4244 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4248 /* don't use group allocation for large files */
4249 size = max(size, isize);
4250 if (size > sbi->s_mb_stream_request) {
4251 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4255 BUG_ON(ac->ac_lg != NULL);
4257 * locality group prealloc space are per cpu. The reason for having
4258 * per cpu locality group is to reduce the contention between block
4259 * request from multiple CPUs.
4261 ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
4263 /* we're going to use group allocation */
4264 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4266 /* serialize all allocations in the group */
4267 mutex_lock(&ac->ac_lg->lg_mutex);
4270 static noinline_for_stack int
4271 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4272 struct ext4_allocation_request *ar)
4274 struct super_block *sb = ar->inode->i_sb;
4275 struct ext4_sb_info *sbi = EXT4_SB(sb);
4276 struct ext4_super_block *es = sbi->s_es;
4280 ext4_grpblk_t block;
4282 /* we can't allocate > group size */
4285 /* just a dirty hack to filter too big requests */
4286 if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
4287 len = EXT4_CLUSTERS_PER_GROUP(sb);
4289 /* start searching from the goal */
4291 if (goal < le32_to_cpu(es->s_first_data_block) ||
4292 goal >= ext4_blocks_count(es))
4293 goal = le32_to_cpu(es->s_first_data_block);
4294 ext4_get_group_no_and_offset(sb, goal, &group, &block);
4296 /* set up allocation goals */
4297 ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
4298 ac->ac_status = AC_STATUS_CONTINUE;
4300 ac->ac_inode = ar->inode;
4301 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4302 ac->ac_o_ex.fe_group = group;
4303 ac->ac_o_ex.fe_start = block;
4304 ac->ac_o_ex.fe_len = len;
4305 ac->ac_g_ex = ac->ac_o_ex;
4306 ac->ac_flags = ar->flags;
4308 /* we have to define context: we'll we work with a file or
4309 * locality group. this is a policy, actually */
4310 ext4_mb_group_or_file(ac);
4312 mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4313 "left: %u/%u, right %u/%u to %swritable\n",
4314 (unsigned) ar->len, (unsigned) ar->logical,
4315 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4316 (unsigned) ar->lleft, (unsigned) ar->pleft,
4317 (unsigned) ar->lright, (unsigned) ar->pright,
4318 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4323 static noinline_for_stack void
4324 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4325 struct ext4_locality_group *lg,
4326 int order, int total_entries)
4328 ext4_group_t group = 0;
4329 struct ext4_buddy e4b;
4330 struct list_head discard_list;
4331 struct ext4_prealloc_space *pa, *tmp;
4333 mb_debug(1, "discard locality group preallocation\n");
4335 INIT_LIST_HEAD(&discard_list);
4337 spin_lock(&lg->lg_prealloc_lock);
4338 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4340 spin_lock(&pa->pa_lock);
4341 if (atomic_read(&pa->pa_count)) {
4343 * This is the pa that we just used
4344 * for block allocation. So don't
4347 spin_unlock(&pa->pa_lock);
4350 if (pa->pa_deleted) {
4351 spin_unlock(&pa->pa_lock);
4354 /* only lg prealloc space */
4355 BUG_ON(pa->pa_type != MB_GROUP_PA);
4357 /* seems this one can be freed ... */
4359 spin_unlock(&pa->pa_lock);
4361 list_del_rcu(&pa->pa_inode_list);
4362 list_add(&pa->u.pa_tmp_list, &discard_list);
4365 if (total_entries <= 5) {
4367 * we want to keep only 5 entries
4368 * allowing it to grow to 8. This
4369 * mak sure we don't call discard
4370 * soon for this list.
4375 spin_unlock(&lg->lg_prealloc_lock);
4377 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4380 group = ext4_get_group_number(sb, pa->pa_pstart);
4381 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4382 GFP_NOFS|__GFP_NOFAIL);
4384 ext4_error(sb, "Error %d loading buddy information for %u",
4388 ext4_lock_group(sb, group);
4389 list_del(&pa->pa_group_list);
4390 ext4_mb_release_group_pa(&e4b, pa);
4391 ext4_unlock_group(sb, group);
4393 ext4_mb_unload_buddy(&e4b);
4394 list_del(&pa->u.pa_tmp_list);
4395 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4400 * We have incremented pa_count. So it cannot be freed at this
4401 * point. Also we hold lg_mutex. So no parallel allocation is
4402 * possible from this lg. That means pa_free cannot be updated.
4404 * A parallel ext4_mb_discard_group_preallocations is possible.
4405 * which can cause the lg_prealloc_list to be updated.
4408 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4410 int order, added = 0, lg_prealloc_count = 1;
4411 struct super_block *sb = ac->ac_sb;
4412 struct ext4_locality_group *lg = ac->ac_lg;
4413 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4415 order = fls(pa->pa_free) - 1;
4416 if (order > PREALLOC_TB_SIZE - 1)
4417 /* The max size of hash table is PREALLOC_TB_SIZE */
4418 order = PREALLOC_TB_SIZE - 1;
4419 /* Add the prealloc space to lg */
4420 spin_lock(&lg->lg_prealloc_lock);
4421 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4423 spin_lock(&tmp_pa->pa_lock);
4424 if (tmp_pa->pa_deleted) {
4425 spin_unlock(&tmp_pa->pa_lock);
4428 if (!added && pa->pa_free < tmp_pa->pa_free) {
4429 /* Add to the tail of the previous entry */
4430 list_add_tail_rcu(&pa->pa_inode_list,
4431 &tmp_pa->pa_inode_list);
4434 * we want to count the total
4435 * number of entries in the list
4438 spin_unlock(&tmp_pa->pa_lock);
4439 lg_prealloc_count++;
4442 list_add_tail_rcu(&pa->pa_inode_list,
4443 &lg->lg_prealloc_list[order]);
4444 spin_unlock(&lg->lg_prealloc_lock);
4446 /* Now trim the list to be not more than 8 elements */
4447 if (lg_prealloc_count > 8) {
4448 ext4_mb_discard_lg_preallocations(sb, lg,
4449 order, lg_prealloc_count);
4456 * release all resource we used in allocation
4458 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4460 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4461 struct ext4_prealloc_space *pa = ac->ac_pa;
4463 if (pa->pa_type == MB_GROUP_PA) {
4464 /* see comment in ext4_mb_use_group_pa() */
4465 spin_lock(&pa->pa_lock);
4466 pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4467 pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4468 pa->pa_free -= ac->ac_b_ex.fe_len;
4469 pa->pa_len -= ac->ac_b_ex.fe_len;
4470 spin_unlock(&pa->pa_lock);
4475 * We want to add the pa to the right bucket.
4476 * Remove it from the list and while adding
4477 * make sure the list to which we are adding
4480 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4481 spin_lock(pa->pa_obj_lock);
4482 list_del_rcu(&pa->pa_inode_list);
4483 spin_unlock(pa->pa_obj_lock);
4484 ext4_mb_add_n_trim(ac);
4486 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4488 if (ac->ac_bitmap_page)
4489 put_page(ac->ac_bitmap_page);
4490 if (ac->ac_buddy_page)
4491 put_page(ac->ac_buddy_page);
4492 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4493 mutex_unlock(&ac->ac_lg->lg_mutex);
4494 ext4_mb_collect_stats(ac);
4498 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4500 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4504 trace_ext4_mb_discard_preallocations(sb, needed);
4505 for (i = 0; i < ngroups && needed > 0; i++) {
4506 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4515 * Main entry point into mballoc to allocate blocks
4516 * it tries to use preallocation first, then falls back
4517 * to usual allocation
4519 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4520 struct ext4_allocation_request *ar, int *errp)
4523 struct ext4_allocation_context *ac = NULL;
4524 struct ext4_sb_info *sbi;
4525 struct super_block *sb;
4526 ext4_fsblk_t block = 0;
4527 unsigned int inquota = 0;
4528 unsigned int reserv_clstrs = 0;
4531 sb = ar->inode->i_sb;
4534 trace_ext4_request_blocks(ar);
4536 /* Allow to use superuser reservation for quota file */
4537 if (ext4_is_quota_file(ar->inode))
4538 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
4540 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
4541 /* Without delayed allocation we need to verify
4542 * there is enough free blocks to do block allocation
4543 * and verify allocation doesn't exceed the quota limits.
4546 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
4548 /* let others to free the space */
4550 ar->len = ar->len >> 1;
4556 reserv_clstrs = ar->len;
4557 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
4558 dquot_alloc_block_nofail(ar->inode,
4559 EXT4_C2B(sbi, ar->len));
4562 dquot_alloc_block(ar->inode,
4563 EXT4_C2B(sbi, ar->len))) {
4565 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4576 ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
4583 *errp = ext4_mb_initialize_context(ac, ar);
4589 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4590 if (!ext4_mb_use_preallocated(ac)) {
4591 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4592 ext4_mb_normalize_request(ac, ar);
4594 /* allocate space in core */
4595 *errp = ext4_mb_regular_allocator(ac);
4597 goto discard_and_exit;
4599 /* as we've just preallocated more space than
4600 * user requested originally, we store allocated
4601 * space in a special descriptor */
4602 if (ac->ac_status == AC_STATUS_FOUND &&
4603 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4604 *errp = ext4_mb_new_preallocation(ac);
4607 ext4_discard_allocated_blocks(ac);
4611 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4612 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4614 ext4_discard_allocated_blocks(ac);
4617 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4618 ar->len = ac->ac_b_ex.fe_len;
4621 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4629 ac->ac_b_ex.fe_len = 0;
4631 ext4_mb_show_ac(ac);
4633 ext4_mb_release_context(ac);
4636 kmem_cache_free(ext4_ac_cachep, ac);
4637 if (inquota && ar->len < inquota)
4638 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
4640 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
4641 /* release all the reserved blocks if non delalloc */
4642 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4646 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4652 * We can merge two free data extents only if the physical blocks
4653 * are contiguous, AND the extents were freed by the same transaction,
4654 * AND the blocks are associated with the same group.
4656 static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
4657 struct ext4_free_data *entry,
4658 struct ext4_free_data *new_entry,
4659 struct rb_root *entry_rb_root)
4661 if ((entry->efd_tid != new_entry->efd_tid) ||
4662 (entry->efd_group != new_entry->efd_group))
4664 if (entry->efd_start_cluster + entry->efd_count ==
4665 new_entry->efd_start_cluster) {
4666 new_entry->efd_start_cluster = entry->efd_start_cluster;
4667 new_entry->efd_count += entry->efd_count;
4668 } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
4669 entry->efd_start_cluster) {
4670 new_entry->efd_count += entry->efd_count;
4673 spin_lock(&sbi->s_md_lock);
4674 list_del(&entry->efd_list);
4675 spin_unlock(&sbi->s_md_lock);
4676 rb_erase(&entry->efd_node, entry_rb_root);
4677 kmem_cache_free(ext4_free_data_cachep, entry);
4680 static noinline_for_stack int
4681 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4682 struct ext4_free_data *new_entry)
4684 ext4_group_t group = e4b->bd_group;
4685 ext4_grpblk_t cluster;
4686 ext4_grpblk_t clusters = new_entry->efd_count;
4687 struct ext4_free_data *entry;
4688 struct ext4_group_info *db = e4b->bd_info;
4689 struct super_block *sb = e4b->bd_sb;
4690 struct ext4_sb_info *sbi = EXT4_SB(sb);
4691 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4692 struct rb_node *parent = NULL, *new_node;
4694 BUG_ON(!ext4_handle_valid(handle));
4695 BUG_ON(e4b->bd_bitmap_page == NULL);
4696 BUG_ON(e4b->bd_buddy_page == NULL);
4698 new_node = &new_entry->efd_node;
4699 cluster = new_entry->efd_start_cluster;
4702 /* first free block exent. We need to
4703 protect buddy cache from being freed,
4704 * otherwise we'll refresh it from
4705 * on-disk bitmap and lose not-yet-available
4707 get_page(e4b->bd_buddy_page);
4708 get_page(e4b->bd_bitmap_page);
4712 entry = rb_entry(parent, struct ext4_free_data, efd_node);
4713 if (cluster < entry->efd_start_cluster)
4715 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
4716 n = &(*n)->rb_right;
4718 ext4_grp_locked_error(sb, group, 0,
4719 ext4_group_first_block_no(sb, group) +
4720 EXT4_C2B(sbi, cluster),
4721 "Block already on to-be-freed list");
4722 kmem_cache_free(ext4_free_data_cachep, new_entry);
4727 rb_link_node(new_node, parent, n);
4728 rb_insert_color(new_node, &db->bb_free_root);
4730 /* Now try to see the extent can be merged to left and right */
4731 node = rb_prev(new_node);
4733 entry = rb_entry(node, struct ext4_free_data, efd_node);
4734 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4735 &(db->bb_free_root));
4738 node = rb_next(new_node);
4740 entry = rb_entry(node, struct ext4_free_data, efd_node);
4741 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4742 &(db->bb_free_root));
4745 spin_lock(&sbi->s_md_lock);
4746 list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
4747 sbi->s_mb_free_pending += clusters;
4748 spin_unlock(&sbi->s_md_lock);
4753 * ext4_free_blocks() -- Free given blocks and update quota
4754 * @handle: handle for this transaction
4756 * @block: start physical block to free
4757 * @count: number of blocks to count
4758 * @flags: flags used by ext4_free_blocks
4760 void ext4_free_blocks(handle_t *handle, struct inode *inode,
4761 struct buffer_head *bh, ext4_fsblk_t block,
4762 unsigned long count, int flags)
4764 struct buffer_head *bitmap_bh = NULL;
4765 struct super_block *sb = inode->i_sb;
4766 struct ext4_group_desc *gdp;
4767 unsigned int overflow;
4769 struct buffer_head *gd_bh;
4770 ext4_group_t block_group;
4771 struct ext4_sb_info *sbi;
4772 struct ext4_buddy e4b;
4773 unsigned int count_clusters;
4780 BUG_ON(block != bh->b_blocknr);
4782 block = bh->b_blocknr;
4786 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
4787 !ext4_inode_block_valid(inode, block, count)) {
4788 ext4_error(sb, "Freeing blocks not in datazone - "
4789 "block = %llu, count = %lu", block, count);
4793 ext4_debug("freeing block %llu\n", block);
4794 trace_ext4_free_blocks(inode, block, count, flags);
4796 if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4799 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4804 * If the extent to be freed does not begin on a cluster
4805 * boundary, we need to deal with partial clusters at the
4806 * beginning and end of the extent. Normally we will free
4807 * blocks at the beginning or the end unless we are explicitly
4808 * requested to avoid doing so.
4810 overflow = EXT4_PBLK_COFF(sbi, block);
4812 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
4813 overflow = sbi->s_cluster_ratio - overflow;
4815 if (count > overflow)
4824 overflow = EXT4_LBLK_COFF(sbi, count);
4826 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
4827 if (count > overflow)
4832 count += sbi->s_cluster_ratio - overflow;
4835 if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4837 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
4839 for (i = 0; i < count; i++) {
4842 bh = sb_find_get_block(inode->i_sb, block + i);
4843 ext4_forget(handle, is_metadata, inode, bh, block + i);
4849 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4851 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
4852 ext4_get_group_info(sb, block_group))))
4856 * Check to see if we are freeing blocks across a group
4859 if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4860 overflow = EXT4_C2B(sbi, bit) + count -
4861 EXT4_BLOCKS_PER_GROUP(sb);
4864 count_clusters = EXT4_NUM_B2C(sbi, count);
4865 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4866 if (IS_ERR(bitmap_bh)) {
4867 err = PTR_ERR(bitmap_bh);
4871 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4877 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4878 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4879 in_range(block, ext4_inode_table(sb, gdp),
4880 EXT4_SB(sb)->s_itb_per_group) ||
4881 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4882 EXT4_SB(sb)->s_itb_per_group)) {
4884 ext4_error(sb, "Freeing blocks in system zone - "
4885 "Block = %llu, count = %lu", block, count);
4886 /* err = 0. ext4_std_error should be a no op */
4890 BUFFER_TRACE(bitmap_bh, "getting write access");
4891 err = ext4_journal_get_write_access(handle, bitmap_bh);
4896 * We are about to modify some metadata. Call the journal APIs
4897 * to unshare ->b_data if a currently-committing transaction is
4900 BUFFER_TRACE(gd_bh, "get_write_access");
4901 err = ext4_journal_get_write_access(handle, gd_bh);
4904 #ifdef AGGRESSIVE_CHECK
4907 for (i = 0; i < count_clusters; i++)
4908 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4911 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
4913 /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
4914 err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
4915 GFP_NOFS|__GFP_NOFAIL);
4920 * We need to make sure we don't reuse the freed block until after the
4921 * transaction is committed. We make an exception if the inode is to be
4922 * written in writeback mode since writeback mode has weak data
4923 * consistency guarantees.
4925 if (ext4_handle_valid(handle) &&
4926 ((flags & EXT4_FREE_BLOCKS_METADATA) ||
4927 !ext4_should_writeback_data(inode))) {
4928 struct ext4_free_data *new_entry;
4930 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
4933 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
4934 GFP_NOFS|__GFP_NOFAIL);
4935 new_entry->efd_start_cluster = bit;
4936 new_entry->efd_group = block_group;
4937 new_entry->efd_count = count_clusters;
4938 new_entry->efd_tid = handle->h_transaction->t_tid;
4940 ext4_lock_group(sb, block_group);
4941 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4942 ext4_mb_free_metadata(handle, &e4b, new_entry);
4944 /* need to update group_info->bb_free and bitmap
4945 * with group lock held. generate_buddy look at
4946 * them with group lock_held
4948 if (test_opt(sb, DISCARD)) {
4949 err = ext4_issue_discard(sb, block_group, bit, count,
4951 if (err && err != -EOPNOTSUPP)
4952 ext4_msg(sb, KERN_WARNING, "discard request in"
4953 " group:%d block:%d count:%lu failed"
4954 " with %d", block_group, bit, count,
4957 EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
4959 ext4_lock_group(sb, block_group);
4960 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4961 mb_free_blocks(inode, &e4b, bit, count_clusters);
4964 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
4965 ext4_free_group_clusters_set(sb, gdp, ret);
4966 ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
4967 ext4_group_desc_csum_set(sb, block_group, gdp);
4968 ext4_unlock_group(sb, block_group);
4970 if (sbi->s_log_groups_per_flex) {
4971 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4972 atomic64_add(count_clusters,
4973 &sbi_array_rcu_deref(sbi, s_flex_groups,
4974 flex_group)->free_clusters);
4977 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
4978 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
4979 percpu_counter_add(&sbi->s_freeclusters_counter, count_clusters);
4981 ext4_mb_unload_buddy(&e4b);
4983 /* We dirtied the bitmap block */
4984 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4985 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4987 /* And the group descriptor block */
4988 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4989 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4993 if (overflow && !err) {
5001 ext4_std_error(sb, err);
5006 * ext4_group_add_blocks() -- Add given blocks to an existing group
5007 * @handle: handle to this transaction
5009 * @block: start physical block to add to the block group
5010 * @count: number of blocks to free
5012 * This marks the blocks as free in the bitmap and buddy.
5014 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
5015 ext4_fsblk_t block, unsigned long count)
5017 struct buffer_head *bitmap_bh = NULL;
5018 struct buffer_head *gd_bh;
5019 ext4_group_t block_group;
5022 struct ext4_group_desc *desc;
5023 struct ext4_sb_info *sbi = EXT4_SB(sb);
5024 struct ext4_buddy e4b;
5025 int err = 0, ret, blk_free_count;
5026 ext4_grpblk_t blocks_freed;
5028 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
5033 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5035 * Check to see if we are freeing blocks across a group
5038 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
5039 ext4_warning(sb, "too much blocks added to group %u",
5045 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
5046 if (IS_ERR(bitmap_bh)) {
5047 err = PTR_ERR(bitmap_bh);
5052 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
5058 if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
5059 in_range(ext4_inode_bitmap(sb, desc), block, count) ||
5060 in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
5061 in_range(block + count - 1, ext4_inode_table(sb, desc),
5062 sbi->s_itb_per_group)) {
5063 ext4_error(sb, "Adding blocks in system zones - "
5064 "Block = %llu, count = %lu",
5070 BUFFER_TRACE(bitmap_bh, "getting write access");
5071 err = ext4_journal_get_write_access(handle, bitmap_bh);
5076 * We are about to modify some metadata. Call the journal APIs
5077 * to unshare ->b_data if a currently-committing transaction is
5080 BUFFER_TRACE(gd_bh, "get_write_access");
5081 err = ext4_journal_get_write_access(handle, gd_bh);
5085 for (i = 0, blocks_freed = 0; i < count; i++) {
5086 BUFFER_TRACE(bitmap_bh, "clear bit");
5087 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
5088 ext4_error(sb, "bit already cleared for block %llu",
5089 (ext4_fsblk_t)(block + i));
5090 BUFFER_TRACE(bitmap_bh, "bit already cleared");
5096 err = ext4_mb_load_buddy(sb, block_group, &e4b);
5101 * need to update group_info->bb_free and bitmap
5102 * with group lock held. generate_buddy look at
5103 * them with group lock_held
5105 ext4_lock_group(sb, block_group);
5106 mb_clear_bits(bitmap_bh->b_data, bit, count);
5107 mb_free_blocks(NULL, &e4b, bit, count);
5108 blk_free_count = blocks_freed + ext4_free_group_clusters(sb, desc);
5109 ext4_free_group_clusters_set(sb, desc, blk_free_count);
5110 ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
5111 ext4_group_desc_csum_set(sb, block_group, desc);
5112 ext4_unlock_group(sb, block_group);
5113 percpu_counter_add(&sbi->s_freeclusters_counter,
5114 EXT4_NUM_B2C(sbi, blocks_freed));
5116 if (sbi->s_log_groups_per_flex) {
5117 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5118 atomic64_add(EXT4_NUM_B2C(sbi, blocks_freed),
5119 &sbi_array_rcu_deref(sbi, s_flex_groups,
5120 flex_group)->free_clusters);
5123 ext4_mb_unload_buddy(&e4b);
5125 /* We dirtied the bitmap block */
5126 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5127 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5129 /* And the group descriptor block */
5130 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5131 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5137 ext4_std_error(sb, err);
5142 * ext4_trim_extent -- function to TRIM one single free extent in the group
5143 * @sb: super block for the file system
5144 * @start: starting block of the free extent in the alloc. group
5145 * @count: number of blocks to TRIM
5146 * @group: alloc. group we are working with
5147 * @e4b: ext4 buddy for the group
5149 * Trim "count" blocks starting at "start" in the "group". To assure that no
5150 * one will allocate those blocks, mark it as used in buddy bitmap. This must
5151 * be called with under the group lock.
5153 static int ext4_trim_extent(struct super_block *sb, int start, int count,
5154 ext4_group_t group, struct ext4_buddy *e4b)
5158 struct ext4_free_extent ex;
5161 trace_ext4_trim_extent(sb, group, start, count);
5163 assert_spin_locked(ext4_group_lock_ptr(sb, group));
5165 ex.fe_start = start;
5166 ex.fe_group = group;
5170 * Mark blocks used, so no one can reuse them while
5173 mb_mark_used(e4b, &ex);
5174 ext4_unlock_group(sb, group);
5175 ret = ext4_issue_discard(sb, group, start, count, NULL);
5176 ext4_lock_group(sb, group);
5177 mb_free_blocks(NULL, e4b, start, ex.fe_len);
5182 * ext4_trim_all_free -- function to trim all free space in alloc. group
5183 * @sb: super block for file system
5184 * @group: group to be trimmed
5185 * @start: first group block to examine
5186 * @max: last group block to examine
5187 * @minblocks: minimum extent block count
5189 * ext4_trim_all_free walks through group's buddy bitmap searching for free
5190 * extents. When the free block is found, ext4_trim_extent is called to TRIM
5194 * ext4_trim_all_free walks through group's block bitmap searching for free
5195 * extents. When the free extent is found, mark it as used in group buddy
5196 * bitmap. Then issue a TRIM command on this extent and free the extent in
5197 * the group buddy bitmap. This is done until whole group is scanned.
5199 static ext4_grpblk_t
5200 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
5201 ext4_grpblk_t start, ext4_grpblk_t max,
5202 ext4_grpblk_t minblocks)
5205 ext4_grpblk_t next, count = 0, free_count = 0;
5206 struct ext4_buddy e4b;
5209 trace_ext4_trim_all_free(sb, group, start, max);
5211 ret = ext4_mb_load_buddy(sb, group, &e4b);
5213 ext4_warning(sb, "Error %d loading buddy information for %u",
5217 bitmap = e4b.bd_bitmap;
5219 ext4_lock_group(sb, group);
5220 if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
5221 minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
5224 start = (e4b.bd_info->bb_first_free > start) ?
5225 e4b.bd_info->bb_first_free : start;
5227 while (start <= max) {
5228 start = mb_find_next_zero_bit(bitmap, max + 1, start);
5231 next = mb_find_next_bit(bitmap, max + 1, start);
5233 if ((next - start) >= minblocks) {
5234 ret = ext4_trim_extent(sb, start,
5235 next - start, group, &e4b);
5236 if (ret && ret != -EOPNOTSUPP)
5239 count += next - start;
5241 free_count += next - start;
5244 if (fatal_signal_pending(current)) {
5245 count = -ERESTARTSYS;
5249 if (need_resched()) {
5250 ext4_unlock_group(sb, group);
5252 ext4_lock_group(sb, group);
5255 if ((e4b.bd_info->bb_free - free_count) < minblocks)
5261 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
5264 ext4_unlock_group(sb, group);
5265 ext4_mb_unload_buddy(&e4b);
5267 ext4_debug("trimmed %d blocks in the group %d\n",
5274 * ext4_trim_fs() -- trim ioctl handle function
5275 * @sb: superblock for filesystem
5276 * @range: fstrim_range structure
5278 * start: First Byte to trim
5279 * len: number of Bytes to trim from start
5280 * minlen: minimum extent length in Bytes
5281 * ext4_trim_fs goes through all allocation groups containing Bytes from
5282 * start to start+len. For each such a group ext4_trim_all_free function
5283 * is invoked to trim all free space.
5285 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
5287 struct ext4_group_info *grp;
5288 ext4_group_t group, first_group, last_group;
5289 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5290 uint64_t start, end, minlen, trimmed = 0;
5291 ext4_fsblk_t first_data_blk =
5292 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5293 ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
5296 start = range->start >> sb->s_blocksize_bits;
5297 end = start + (range->len >> sb->s_blocksize_bits) - 1;
5298 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5299 range->minlen >> sb->s_blocksize_bits);
5301 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
5302 start >= max_blks ||
5303 range->len < sb->s_blocksize)
5305 if (end >= max_blks)
5307 if (end <= first_data_blk)
5309 if (start < first_data_blk)
5310 start = first_data_blk;
5312 /* Determine first and last group to examine based on start and end */
5313 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
5314 &first_group, &first_cluster);
5315 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
5316 &last_group, &last_cluster);
5318 /* end now represents the last cluster to discard in this group */
5319 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5321 for (group = first_group; group <= last_group; group++) {
5322 grp = ext4_get_group_info(sb, group);
5323 /* We only do this if the grp has never been initialized */
5324 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
5325 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
5331 * For all the groups except the last one, last cluster will
5332 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
5333 * change it for the last group, note that last_cluster is
5334 * already computed earlier by ext4_get_group_no_and_offset()
5336 if (group == last_group)
5339 if (grp->bb_free >= minlen) {
5340 cnt = ext4_trim_all_free(sb, group, first_cluster,
5350 * For every group except the first one, we are sure
5351 * that the first cluster to discard will be cluster #0.
5357 atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
5360 range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
5364 /* Iterate all the free extents in the group. */
5366 ext4_mballoc_query_range(
5367 struct super_block *sb,
5369 ext4_grpblk_t start,
5371 ext4_mballoc_query_range_fn formatter,
5376 struct ext4_buddy e4b;
5379 error = ext4_mb_load_buddy(sb, group, &e4b);
5382 bitmap = e4b.bd_bitmap;
5384 ext4_lock_group(sb, group);
5386 start = (e4b.bd_info->bb_first_free > start) ?
5387 e4b.bd_info->bb_first_free : start;
5388 if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
5389 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5391 while (start <= end) {
5392 start = mb_find_next_zero_bit(bitmap, end + 1, start);
5395 next = mb_find_next_bit(bitmap, end + 1, start);
5397 ext4_unlock_group(sb, group);
5398 error = formatter(sb, group, start, next - start, priv);
5401 ext4_lock_group(sb, group);
5406 ext4_unlock_group(sb, group);
5408 ext4_mb_unload_buddy(&e4b);