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 *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,
371 static void ext4_free_data_callback(struct super_block *sb,
372 struct ext4_journal_cb_entry *jce, int rc);
374 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
376 #if BITS_PER_LONG == 64
377 *bit += ((unsigned long) addr & 7UL) << 3;
378 addr = (void *) ((unsigned long) addr & ~7UL);
379 #elif BITS_PER_LONG == 32
380 *bit += ((unsigned long) addr & 3UL) << 3;
381 addr = (void *) ((unsigned long) addr & ~3UL);
383 #error "how many bits you are?!"
388 static inline int mb_test_bit(int bit, void *addr)
391 * ext4_test_bit on architecture like powerpc
392 * needs unsigned long aligned address
394 addr = mb_correct_addr_and_bit(&bit, addr);
395 return ext4_test_bit(bit, addr);
398 static inline void mb_set_bit(int bit, void *addr)
400 addr = mb_correct_addr_and_bit(&bit, addr);
401 ext4_set_bit(bit, addr);
404 static inline void mb_clear_bit(int bit, void *addr)
406 addr = mb_correct_addr_and_bit(&bit, addr);
407 ext4_clear_bit(bit, addr);
410 static inline int mb_test_and_clear_bit(int bit, void *addr)
412 addr = mb_correct_addr_and_bit(&bit, addr);
413 return ext4_test_and_clear_bit(bit, addr);
416 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
418 int fix = 0, ret, tmpmax;
419 addr = mb_correct_addr_and_bit(&fix, addr);
423 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
429 static inline int mb_find_next_bit(void *addr, int max, int start)
431 int fix = 0, ret, tmpmax;
432 addr = mb_correct_addr_and_bit(&fix, addr);
436 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
442 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
446 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
449 if (order > e4b->bd_blkbits + 1) {
454 /* at order 0 we see each particular block */
456 *max = 1 << (e4b->bd_blkbits + 3);
457 return e4b->bd_bitmap;
460 bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
461 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
467 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
468 int first, int count)
471 struct super_block *sb = e4b->bd_sb;
473 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
475 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
476 for (i = 0; i < count; i++) {
477 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
478 ext4_fsblk_t blocknr;
480 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
481 blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
482 ext4_grp_locked_error(sb, e4b->bd_group,
483 inode ? inode->i_ino : 0,
485 "freeing block already freed "
489 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
493 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
497 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
499 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
500 for (i = 0; i < count; i++) {
501 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
502 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
506 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
508 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
509 unsigned char *b1, *b2;
511 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
512 b2 = (unsigned char *) bitmap;
513 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
514 if (b1[i] != b2[i]) {
515 ext4_msg(e4b->bd_sb, KERN_ERR,
516 "corruption in group %u "
517 "at byte %u(%u): %x in copy != %x "
519 e4b->bd_group, i, i * 8, b1[i], b2[i]);
527 static inline void mb_free_blocks_double(struct inode *inode,
528 struct ext4_buddy *e4b, int first, int count)
532 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
533 int first, int count)
537 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
543 #ifdef AGGRESSIVE_CHECK
545 #define MB_CHECK_ASSERT(assert) \
549 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
550 function, file, line, # assert); \
555 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
556 const char *function, int line)
558 struct super_block *sb = e4b->bd_sb;
559 int order = e4b->bd_blkbits + 1;
566 struct ext4_group_info *grp;
569 struct list_head *cur;
574 static int mb_check_counter;
575 if (mb_check_counter++ % 100 != 0)
580 buddy = mb_find_buddy(e4b, order, &max);
581 MB_CHECK_ASSERT(buddy);
582 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
583 MB_CHECK_ASSERT(buddy2);
584 MB_CHECK_ASSERT(buddy != buddy2);
585 MB_CHECK_ASSERT(max * 2 == max2);
588 for (i = 0; i < max; i++) {
590 if (mb_test_bit(i, buddy)) {
591 /* only single bit in buddy2 may be 1 */
592 if (!mb_test_bit(i << 1, buddy2)) {
594 mb_test_bit((i<<1)+1, buddy2));
595 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
597 mb_test_bit(i << 1, buddy2));
602 /* both bits in buddy2 must be 1 */
603 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
604 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
606 for (j = 0; j < (1 << order); j++) {
607 k = (i * (1 << order)) + j;
609 !mb_test_bit(k, e4b->bd_bitmap));
613 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
618 buddy = mb_find_buddy(e4b, 0, &max);
619 for (i = 0; i < max; i++) {
620 if (!mb_test_bit(i, buddy)) {
621 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
629 /* check used bits only */
630 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
631 buddy2 = mb_find_buddy(e4b, j, &max2);
633 MB_CHECK_ASSERT(k < max2);
634 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
637 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
638 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
640 grp = ext4_get_group_info(sb, e4b->bd_group);
641 list_for_each(cur, &grp->bb_prealloc_list) {
642 ext4_group_t groupnr;
643 struct ext4_prealloc_space *pa;
644 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
645 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
646 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
647 for (i = 0; i < pa->pa_len; i++)
648 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
652 #undef MB_CHECK_ASSERT
653 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
654 __FILE__, __func__, __LINE__)
656 #define mb_check_buddy(e4b)
660 * Divide blocks started from @first with length @len into
661 * smaller chunks with power of 2 blocks.
662 * Clear the bits in bitmap which the blocks of the chunk(s) covered,
663 * then increase bb_counters[] for corresponded chunk size.
665 static void ext4_mb_mark_free_simple(struct super_block *sb,
666 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
667 struct ext4_group_info *grp)
669 struct ext4_sb_info *sbi = EXT4_SB(sb);
675 BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
677 border = 2 << sb->s_blocksize_bits;
680 /* find how many blocks can be covered since this position */
681 max = ffs(first | border) - 1;
683 /* find how many blocks of power 2 we need to mark */
690 /* mark multiblock chunks only */
691 grp->bb_counters[min]++;
693 mb_clear_bit(first >> min,
694 buddy + sbi->s_mb_offsets[min]);
702 * Cache the order of the largest free extent we have available in this block
706 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
711 grp->bb_largest_free_order = -1; /* uninit */
713 bits = sb->s_blocksize_bits + 1;
714 for (i = bits; i >= 0; i--) {
715 if (grp->bb_counters[i] > 0) {
716 grp->bb_largest_free_order = i;
722 static noinline_for_stack
723 void ext4_mb_generate_buddy(struct super_block *sb,
724 void *buddy, void *bitmap, ext4_group_t group)
726 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
727 struct ext4_sb_info *sbi = EXT4_SB(sb);
728 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
733 unsigned fragments = 0;
734 unsigned long long period = get_cycles();
736 /* initialize buddy from bitmap which is aggregation
737 * of on-disk bitmap and preallocations */
738 i = mb_find_next_zero_bit(bitmap, max, 0);
739 grp->bb_first_free = i;
743 i = mb_find_next_bit(bitmap, max, i);
747 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
749 grp->bb_counters[0]++;
751 i = mb_find_next_zero_bit(bitmap, max, i);
753 grp->bb_fragments = fragments;
755 if (free != grp->bb_free) {
756 ext4_grp_locked_error(sb, group, 0, 0,
757 "block bitmap and bg descriptor "
758 "inconsistent: %u vs %u free clusters",
761 * If we intend to continue, we consider group descriptor
762 * corrupt and update bb_free using bitmap value
765 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
766 percpu_counter_sub(&sbi->s_freeclusters_counter,
768 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT, &grp->bb_state);
770 mb_set_largest_free_order(sb, grp);
772 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
774 period = get_cycles() - period;
775 spin_lock(&EXT4_SB(sb)->s_bal_lock);
776 EXT4_SB(sb)->s_mb_buddies_generated++;
777 EXT4_SB(sb)->s_mb_generation_time += period;
778 spin_unlock(&EXT4_SB(sb)->s_bal_lock);
781 static void mb_regenerate_buddy(struct ext4_buddy *e4b)
787 while ((buddy = mb_find_buddy(e4b, order++, &count))) {
788 ext4_set_bits(buddy, 0, count);
790 e4b->bd_info->bb_fragments = 0;
791 memset(e4b->bd_info->bb_counters, 0,
792 sizeof(*e4b->bd_info->bb_counters) *
793 (e4b->bd_sb->s_blocksize_bits + 2));
795 ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
796 e4b->bd_bitmap, e4b->bd_group);
799 /* The buddy information is attached the buddy cache inode
800 * for convenience. The information regarding each group
801 * is loaded via ext4_mb_load_buddy. The information involve
802 * block bitmap and buddy information. The information are
803 * stored in the inode as
806 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
809 * one block each for bitmap and buddy information.
810 * So for each group we take up 2 blocks. A page can
811 * contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
812 * So it can have information regarding groups_per_page which
813 * is blocks_per_page/2
815 * Locking note: This routine takes the block group lock of all groups
816 * for this page; do not hold this lock when calling this routine!
819 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
821 ext4_group_t ngroups;
827 ext4_group_t first_group, group;
829 struct super_block *sb;
830 struct buffer_head *bhs;
831 struct buffer_head **bh = NULL;
835 struct ext4_group_info *grinfo;
837 mb_debug(1, "init page %lu\n", page->index);
839 inode = page->mapping->host;
841 ngroups = ext4_get_groups_count(sb);
842 blocksize = i_blocksize(inode);
843 blocks_per_page = PAGE_SIZE / blocksize;
845 groups_per_page = blocks_per_page >> 1;
846 if (groups_per_page == 0)
849 /* allocate buffer_heads to read bitmaps */
850 if (groups_per_page > 1) {
851 i = sizeof(struct buffer_head *) * groups_per_page;
852 bh = kzalloc(i, gfp);
860 first_group = page->index * blocks_per_page / 2;
862 /* read all groups the page covers into the cache */
863 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
864 if (group >= ngroups)
867 grinfo = ext4_get_group_info(sb, group);
869 * If page is uptodate then we came here after online resize
870 * which added some new uninitialized group info structs, so
871 * we must skip all initialized uptodate buddies on the page,
872 * which may be currently in use by an allocating task.
874 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
878 bh[i] = ext4_read_block_bitmap_nowait(sb, group);
880 err = PTR_ERR(bh[i]);
884 mb_debug(1, "read bitmap for group %u\n", group);
887 /* wait for I/O completion */
888 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
893 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
898 first_block = page->index * blocks_per_page;
899 for (i = 0; i < blocks_per_page; i++) {
900 group = (first_block + i) >> 1;
901 if (group >= ngroups)
904 if (!bh[group - first_group])
905 /* skip initialized uptodate buddy */
908 if (!buffer_verified(bh[group - first_group]))
909 /* Skip faulty bitmaps */
914 * data carry information regarding this
915 * particular group in the format specified
919 data = page_address(page) + (i * blocksize);
920 bitmap = bh[group - first_group]->b_data;
923 * We place the buddy block and bitmap block
926 if ((first_block + i) & 1) {
927 /* this is block of buddy */
928 BUG_ON(incore == NULL);
929 mb_debug(1, "put buddy for group %u in page %lu/%x\n",
930 group, page->index, i * blocksize);
931 trace_ext4_mb_buddy_bitmap_load(sb, group);
932 grinfo = ext4_get_group_info(sb, group);
933 grinfo->bb_fragments = 0;
934 memset(grinfo->bb_counters, 0,
935 sizeof(*grinfo->bb_counters) *
936 (sb->s_blocksize_bits+2));
938 * incore got set to the group block bitmap below
940 ext4_lock_group(sb, group);
942 memset(data, 0xff, blocksize);
943 ext4_mb_generate_buddy(sb, data, incore, group);
944 ext4_unlock_group(sb, group);
947 /* this is block of bitmap */
948 BUG_ON(incore != NULL);
949 mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
950 group, page->index, i * blocksize);
951 trace_ext4_mb_bitmap_load(sb, group);
953 /* see comments in ext4_mb_put_pa() */
954 ext4_lock_group(sb, group);
955 memcpy(data, bitmap, blocksize);
957 /* mark all preallocated blks used in in-core bitmap */
958 ext4_mb_generate_from_pa(sb, data, group);
959 ext4_mb_generate_from_freelist(sb, data, group);
960 ext4_unlock_group(sb, group);
962 /* set incore so that the buddy information can be
963 * generated using this
968 SetPageUptodate(page);
972 for (i = 0; i < groups_per_page; i++)
981 * Lock the buddy and bitmap pages. This make sure other parallel init_group
982 * on the same buddy page doesn't happen whild holding the buddy page lock.
983 * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
984 * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
986 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
987 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
989 struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
990 int block, pnum, poff;
994 e4b->bd_buddy_page = NULL;
995 e4b->bd_bitmap_page = NULL;
997 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
999 * the buddy cache inode stores the block bitmap
1000 * and buddy information in consecutive blocks.
1001 * So for each group we need two blocks.
1004 pnum = block / blocks_per_page;
1005 poff = block % blocks_per_page;
1006 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1009 BUG_ON(page->mapping != inode->i_mapping);
1010 e4b->bd_bitmap_page = page;
1011 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1013 if (blocks_per_page >= 2) {
1014 /* buddy and bitmap are on the same page */
1019 pnum = block / blocks_per_page;
1020 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1023 BUG_ON(page->mapping != inode->i_mapping);
1024 e4b->bd_buddy_page = page;
1028 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1030 if (e4b->bd_bitmap_page) {
1031 unlock_page(e4b->bd_bitmap_page);
1032 put_page(e4b->bd_bitmap_page);
1034 if (e4b->bd_buddy_page) {
1035 unlock_page(e4b->bd_buddy_page);
1036 put_page(e4b->bd_buddy_page);
1041 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1042 * block group lock of all groups for this page; do not hold the BG lock when
1043 * calling this routine!
1045 static noinline_for_stack
1046 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1049 struct ext4_group_info *this_grp;
1050 struct ext4_buddy e4b;
1055 mb_debug(1, "init group %u\n", group);
1056 this_grp = ext4_get_group_info(sb, group);
1058 * This ensures that we don't reinit the buddy cache
1059 * page which map to the group from which we are already
1060 * allocating. If we are looking at the buddy cache we would
1061 * have taken a reference using ext4_mb_load_buddy and that
1062 * would have pinned buddy page to page cache.
1063 * The call to ext4_mb_get_buddy_page_lock will mark the
1066 ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1067 if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1069 * somebody initialized the group
1070 * return without doing anything
1075 page = e4b.bd_bitmap_page;
1076 ret = ext4_mb_init_cache(page, NULL, gfp);
1079 if (!PageUptodate(page)) {
1084 if (e4b.bd_buddy_page == NULL) {
1086 * If both the bitmap and buddy are in
1087 * the same page we don't need to force
1093 /* init buddy cache */
1094 page = e4b.bd_buddy_page;
1095 ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1098 if (!PageUptodate(page)) {
1103 ext4_mb_put_buddy_page_lock(&e4b);
1108 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1109 * block group lock of all groups for this page; do not hold the BG lock when
1110 * calling this routine!
1112 static noinline_for_stack int
1113 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1114 struct ext4_buddy *e4b, gfp_t gfp)
1116 int blocks_per_page;
1122 struct ext4_group_info *grp;
1123 struct ext4_sb_info *sbi = EXT4_SB(sb);
1124 struct inode *inode = sbi->s_buddy_cache;
1127 mb_debug(1, "load group %u\n", group);
1129 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1130 grp = ext4_get_group_info(sb, group);
1132 e4b->bd_blkbits = sb->s_blocksize_bits;
1135 e4b->bd_group = group;
1136 e4b->bd_buddy_page = NULL;
1137 e4b->bd_bitmap_page = NULL;
1139 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1141 * we need full data about the group
1142 * to make a good selection
1144 ret = ext4_mb_init_group(sb, group, gfp);
1150 * the buddy cache inode stores the block bitmap
1151 * and buddy information in consecutive blocks.
1152 * So for each group we need two blocks.
1155 pnum = block / blocks_per_page;
1156 poff = block % blocks_per_page;
1158 /* we could use find_or_create_page(), but it locks page
1159 * what we'd like to avoid in fast path ... */
1160 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1161 if (page == NULL || !PageUptodate(page)) {
1164 * drop the page reference and try
1165 * to get the page with lock. If we
1166 * are not uptodate that implies
1167 * somebody just created the page but
1168 * is yet to initialize the same. So
1169 * wait for it to initialize.
1172 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1174 BUG_ON(page->mapping != inode->i_mapping);
1175 if (!PageUptodate(page)) {
1176 ret = ext4_mb_init_cache(page, NULL, gfp);
1181 mb_cmp_bitmaps(e4b, page_address(page) +
1182 (poff * sb->s_blocksize));
1191 if (!PageUptodate(page)) {
1196 /* Pages marked accessed already */
1197 e4b->bd_bitmap_page = page;
1198 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1201 pnum = block / blocks_per_page;
1202 poff = block % blocks_per_page;
1204 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1205 if (page == NULL || !PageUptodate(page)) {
1208 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1210 BUG_ON(page->mapping != inode->i_mapping);
1211 if (!PageUptodate(page)) {
1212 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1226 if (!PageUptodate(page)) {
1231 /* Pages marked accessed already */
1232 e4b->bd_buddy_page = page;
1233 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1235 BUG_ON(e4b->bd_bitmap_page == NULL);
1236 BUG_ON(e4b->bd_buddy_page == NULL);
1243 if (e4b->bd_bitmap_page)
1244 put_page(e4b->bd_bitmap_page);
1245 if (e4b->bd_buddy_page)
1246 put_page(e4b->bd_buddy_page);
1247 e4b->bd_buddy = NULL;
1248 e4b->bd_bitmap = NULL;
1252 static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1253 struct ext4_buddy *e4b)
1255 return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1258 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1260 if (e4b->bd_bitmap_page)
1261 put_page(e4b->bd_bitmap_page);
1262 if (e4b->bd_buddy_page)
1263 put_page(e4b->bd_buddy_page);
1267 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1270 int bb_incr = 1 << (e4b->bd_blkbits - 1);
1273 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1274 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1277 while (order <= e4b->bd_blkbits + 1) {
1279 if (!mb_test_bit(block, bb)) {
1280 /* this block is part of buddy of order 'order' */
1290 static void mb_clear_bits(void *bm, int cur, int len)
1296 if ((cur & 31) == 0 && (len - cur) >= 32) {
1297 /* fast path: clear whole word at once */
1298 addr = bm + (cur >> 3);
1303 mb_clear_bit(cur, bm);
1308 /* clear bits in given range
1309 * will return first found zero bit if any, -1 otherwise
1311 static int mb_test_and_clear_bits(void *bm, int cur, int len)
1318 if ((cur & 31) == 0 && (len - cur) >= 32) {
1319 /* fast path: clear whole word at once */
1320 addr = bm + (cur >> 3);
1321 if (*addr != (__u32)(-1) && zero_bit == -1)
1322 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1327 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1335 void ext4_set_bits(void *bm, int cur, int len)
1341 if ((cur & 31) == 0 && (len - cur) >= 32) {
1342 /* fast path: set whole word at once */
1343 addr = bm + (cur >> 3);
1348 mb_set_bit(cur, bm);
1354 * _________________________________________________________________ */
1356 static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1358 if (mb_test_bit(*bit + side, bitmap)) {
1359 mb_clear_bit(*bit, bitmap);
1365 mb_set_bit(*bit, bitmap);
1370 static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1374 void *buddy = mb_find_buddy(e4b, order, &max);
1379 /* Bits in range [first; last] are known to be set since
1380 * corresponding blocks were allocated. Bits in range
1381 * (first; last) will stay set because they form buddies on
1382 * upper layer. We just deal with borders if they don't
1383 * align with upper layer and then go up.
1384 * Releasing entire group is all about clearing
1385 * single bit of highest order buddy.
1389 * ---------------------------------
1391 * ---------------------------------
1392 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1393 * ---------------------------------
1395 * \_____________________/
1397 * Neither [1] nor [6] is aligned to above layer.
1398 * Left neighbour [0] is free, so mark it busy,
1399 * decrease bb_counters and extend range to
1401 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1402 * mark [6] free, increase bb_counters and shrink range to
1404 * Then shift range to [0; 2], go up and do the same.
1409 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1411 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1416 if (first == last || !(buddy2 = mb_find_buddy(e4b, order, &max))) {
1417 mb_clear_bits(buddy, first, last - first + 1);
1418 e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1427 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1428 int first, int count)
1430 int left_is_free = 0;
1431 int right_is_free = 0;
1433 int last = first + count - 1;
1434 struct super_block *sb = e4b->bd_sb;
1436 if (WARN_ON(count == 0))
1438 BUG_ON(last >= (sb->s_blocksize << 3));
1439 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1440 /* Don't bother if the block group is corrupt. */
1441 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1444 mb_check_buddy(e4b);
1445 mb_free_blocks_double(inode, e4b, first, count);
1447 e4b->bd_info->bb_free += count;
1448 if (first < e4b->bd_info->bb_first_free)
1449 e4b->bd_info->bb_first_free = first;
1451 /* access memory sequentially: check left neighbour,
1452 * clear range and then check right neighbour
1455 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1456 block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1457 if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1458 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1460 if (unlikely(block != -1)) {
1461 struct ext4_sb_info *sbi = EXT4_SB(sb);
1462 ext4_fsblk_t blocknr;
1464 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1465 blocknr += EXT4_C2B(EXT4_SB(sb), block);
1466 ext4_grp_locked_error(sb, e4b->bd_group,
1467 inode ? inode->i_ino : 0,
1469 "freeing already freed block "
1470 "(bit %u); block bitmap corrupt.",
1472 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))
1473 percpu_counter_sub(&sbi->s_freeclusters_counter,
1474 e4b->bd_info->bb_free);
1475 /* Mark the block group as corrupt. */
1476 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT,
1477 &e4b->bd_info->bb_state);
1478 mb_regenerate_buddy(e4b);
1482 /* let's maintain fragments counter */
1483 if (left_is_free && right_is_free)
1484 e4b->bd_info->bb_fragments--;
1485 else if (!left_is_free && !right_is_free)
1486 e4b->bd_info->bb_fragments++;
1488 /* buddy[0] == bd_bitmap is a special case, so handle
1489 * it right away and let mb_buddy_mark_free stay free of
1490 * zero order checks.
1491 * Check if neighbours are to be coaleasced,
1492 * adjust bitmap bb_counters and borders appropriately.
1495 first += !left_is_free;
1496 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1499 last -= !right_is_free;
1500 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1504 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1507 mb_set_largest_free_order(sb, e4b->bd_info);
1508 mb_check_buddy(e4b);
1511 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1512 int needed, struct ext4_free_extent *ex)
1518 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1521 buddy = mb_find_buddy(e4b, 0, &max);
1522 BUG_ON(buddy == NULL);
1523 BUG_ON(block >= max);
1524 if (mb_test_bit(block, buddy)) {
1531 /* find actual order */
1532 order = mb_find_order_for_block(e4b, block);
1533 block = block >> order;
1535 ex->fe_len = 1 << order;
1536 ex->fe_start = block << order;
1537 ex->fe_group = e4b->bd_group;
1539 /* calc difference from given start */
1540 next = next - ex->fe_start;
1542 ex->fe_start += next;
1544 while (needed > ex->fe_len &&
1545 mb_find_buddy(e4b, order, &max)) {
1547 if (block + 1 >= max)
1550 next = (block + 1) * (1 << order);
1551 if (mb_test_bit(next, e4b->bd_bitmap))
1554 order = mb_find_order_for_block(e4b, next);
1556 block = next >> order;
1557 ex->fe_len += 1 << order;
1560 BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1564 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1570 int start = ex->fe_start;
1571 int len = ex->fe_len;
1576 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1577 BUG_ON(e4b->bd_group != ex->fe_group);
1578 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1579 mb_check_buddy(e4b);
1580 mb_mark_used_double(e4b, start, len);
1582 e4b->bd_info->bb_free -= len;
1583 if (e4b->bd_info->bb_first_free == start)
1584 e4b->bd_info->bb_first_free += len;
1586 /* let's maintain fragments counter */
1588 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1589 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1590 max = !mb_test_bit(start + len, e4b->bd_bitmap);
1592 e4b->bd_info->bb_fragments++;
1593 else if (!mlen && !max)
1594 e4b->bd_info->bb_fragments--;
1596 /* let's maintain buddy itself */
1598 ord = mb_find_order_for_block(e4b, start);
1600 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1601 /* the whole chunk may be allocated at once! */
1603 buddy = mb_find_buddy(e4b, ord, &max);
1604 BUG_ON((start >> ord) >= max);
1605 mb_set_bit(start >> ord, buddy);
1606 e4b->bd_info->bb_counters[ord]--;
1613 /* store for history */
1615 ret = len | (ord << 16);
1617 /* we have to split large buddy */
1619 buddy = mb_find_buddy(e4b, ord, &max);
1620 mb_set_bit(start >> ord, buddy);
1621 e4b->bd_info->bb_counters[ord]--;
1624 cur = (start >> ord) & ~1U;
1625 buddy = mb_find_buddy(e4b, ord, &max);
1626 mb_clear_bit(cur, buddy);
1627 mb_clear_bit(cur + 1, buddy);
1628 e4b->bd_info->bb_counters[ord]++;
1629 e4b->bd_info->bb_counters[ord]++;
1631 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1633 ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1634 mb_check_buddy(e4b);
1640 * Must be called under group lock!
1642 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1643 struct ext4_buddy *e4b)
1645 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1648 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1649 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1651 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1652 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1653 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1655 /* preallocation can change ac_b_ex, thus we store actually
1656 * allocated blocks for history */
1657 ac->ac_f_ex = ac->ac_b_ex;
1659 ac->ac_status = AC_STATUS_FOUND;
1660 ac->ac_tail = ret & 0xffff;
1661 ac->ac_buddy = ret >> 16;
1664 * take the page reference. We want the page to be pinned
1665 * so that we don't get a ext4_mb_init_cache_call for this
1666 * group until we update the bitmap. That would mean we
1667 * double allocate blocks. The reference is dropped
1668 * in ext4_mb_release_context
1670 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1671 get_page(ac->ac_bitmap_page);
1672 ac->ac_buddy_page = e4b->bd_buddy_page;
1673 get_page(ac->ac_buddy_page);
1674 /* store last allocated for subsequent stream allocation */
1675 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1676 spin_lock(&sbi->s_md_lock);
1677 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1678 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1679 spin_unlock(&sbi->s_md_lock);
1684 * regular allocator, for general purposes allocation
1687 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1688 struct ext4_buddy *e4b,
1691 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1692 struct ext4_free_extent *bex = &ac->ac_b_ex;
1693 struct ext4_free_extent *gex = &ac->ac_g_ex;
1694 struct ext4_free_extent ex;
1697 if (ac->ac_status == AC_STATUS_FOUND)
1700 * We don't want to scan for a whole year
1702 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1703 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1704 ac->ac_status = AC_STATUS_BREAK;
1709 * Haven't found good chunk so far, let's continue
1711 if (bex->fe_len < gex->fe_len)
1714 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1715 && bex->fe_group == e4b->bd_group) {
1716 /* recheck chunk's availability - we don't know
1717 * when it was found (within this lock-unlock
1719 max = mb_find_extent(e4b, bex->fe_start, gex->fe_len, &ex);
1720 if (max >= gex->fe_len) {
1721 ext4_mb_use_best_found(ac, e4b);
1728 * The routine checks whether found extent is good enough. If it is,
1729 * then the extent gets marked used and flag is set to the context
1730 * to stop scanning. Otherwise, the extent is compared with the
1731 * previous found extent and if new one is better, then it's stored
1732 * in the context. Later, the best found extent will be used, if
1733 * mballoc can't find good enough extent.
1735 * FIXME: real allocation policy is to be designed yet!
1737 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1738 struct ext4_free_extent *ex,
1739 struct ext4_buddy *e4b)
1741 struct ext4_free_extent *bex = &ac->ac_b_ex;
1742 struct ext4_free_extent *gex = &ac->ac_g_ex;
1744 BUG_ON(ex->fe_len <= 0);
1745 BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1746 BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1747 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1752 * The special case - take what you catch first
1754 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1756 ext4_mb_use_best_found(ac, e4b);
1761 * Let's check whether the chuck is good enough
1763 if (ex->fe_len == gex->fe_len) {
1765 ext4_mb_use_best_found(ac, e4b);
1770 * If this is first found extent, just store it in the context
1772 if (bex->fe_len == 0) {
1778 * If new found extent is better, store it in the context
1780 if (bex->fe_len < gex->fe_len) {
1781 /* if the request isn't satisfied, any found extent
1782 * larger than previous best one is better */
1783 if (ex->fe_len > bex->fe_len)
1785 } else if (ex->fe_len > gex->fe_len) {
1786 /* if the request is satisfied, then we try to find
1787 * an extent that still satisfy the request, but is
1788 * smaller than previous one */
1789 if (ex->fe_len < bex->fe_len)
1793 ext4_mb_check_limits(ac, e4b, 0);
1796 static noinline_for_stack
1797 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1798 struct ext4_buddy *e4b)
1800 struct ext4_free_extent ex = ac->ac_b_ex;
1801 ext4_group_t group = ex.fe_group;
1805 BUG_ON(ex.fe_len <= 0);
1806 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1810 ext4_lock_group(ac->ac_sb, group);
1811 max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
1815 ext4_mb_use_best_found(ac, e4b);
1818 ext4_unlock_group(ac->ac_sb, group);
1819 ext4_mb_unload_buddy(e4b);
1824 static noinline_for_stack
1825 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1826 struct ext4_buddy *e4b)
1828 ext4_group_t group = ac->ac_g_ex.fe_group;
1831 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1832 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1833 struct ext4_free_extent ex;
1835 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1837 if (grp->bb_free == 0)
1840 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1844 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
1845 ext4_mb_unload_buddy(e4b);
1849 ext4_lock_group(ac->ac_sb, group);
1850 max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
1851 ac->ac_g_ex.fe_len, &ex);
1852 ex.fe_logical = 0xDEADFA11; /* debug value */
1854 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1857 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
1859 /* use do_div to get remainder (would be 64-bit modulo) */
1860 if (do_div(start, sbi->s_stripe) == 0) {
1863 ext4_mb_use_best_found(ac, e4b);
1865 } else if (max >= ac->ac_g_ex.fe_len) {
1866 BUG_ON(ex.fe_len <= 0);
1867 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1868 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1871 ext4_mb_use_best_found(ac, e4b);
1872 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1873 /* Sometimes, caller may want to merge even small
1874 * number of blocks to an existing extent */
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);
1882 ext4_unlock_group(ac->ac_sb, group);
1883 ext4_mb_unload_buddy(e4b);
1889 * The routine scans buddy structures (not bitmap!) from given order
1890 * to max order and tries to find big enough chunk to satisfy the req
1892 static noinline_for_stack
1893 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1894 struct ext4_buddy *e4b)
1896 struct super_block *sb = ac->ac_sb;
1897 struct ext4_group_info *grp = e4b->bd_info;
1903 BUG_ON(ac->ac_2order <= 0);
1904 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1905 if (grp->bb_counters[i] == 0)
1908 buddy = mb_find_buddy(e4b, i, &max);
1909 BUG_ON(buddy == NULL);
1911 k = mb_find_next_zero_bit(buddy, max, 0);
1916 ac->ac_b_ex.fe_len = 1 << i;
1917 ac->ac_b_ex.fe_start = k << i;
1918 ac->ac_b_ex.fe_group = e4b->bd_group;
1920 ext4_mb_use_best_found(ac, e4b);
1922 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1924 if (EXT4_SB(sb)->s_mb_stats)
1925 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1932 * The routine scans the group and measures all found extents.
1933 * In order to optimize scanning, caller must pass number of
1934 * free blocks in the group, so the routine can know upper limit.
1936 static noinline_for_stack
1937 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1938 struct ext4_buddy *e4b)
1940 struct super_block *sb = ac->ac_sb;
1941 void *bitmap = e4b->bd_bitmap;
1942 struct ext4_free_extent ex;
1946 free = e4b->bd_info->bb_free;
1947 if (WARN_ON(free <= 0))
1950 i = e4b->bd_info->bb_first_free;
1952 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1953 i = mb_find_next_zero_bit(bitmap,
1954 EXT4_CLUSTERS_PER_GROUP(sb), i);
1955 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
1957 * IF we have corrupt bitmap, we won't find any
1958 * free blocks even though group info says we
1959 * we have free blocks
1961 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1962 "%d free clusters as per "
1963 "group info. But bitmap says 0",
1968 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
1969 if (WARN_ON(ex.fe_len <= 0))
1971 if (free < ex.fe_len) {
1972 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1973 "%d free clusters as per "
1974 "group info. But got %d blocks",
1977 * The number of free blocks differs. This mostly
1978 * indicate that the bitmap is corrupt. So exit
1979 * without claiming the space.
1983 ex.fe_logical = 0xDEADC0DE; /* debug value */
1984 ext4_mb_measure_extent(ac, &ex, e4b);
1990 ext4_mb_check_limits(ac, e4b, 1);
1994 * This is a special case for storages like raid5
1995 * we try to find stripe-aligned chunks for stripe-size-multiple requests
1997 static noinline_for_stack
1998 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1999 struct ext4_buddy *e4b)
2001 struct super_block *sb = ac->ac_sb;
2002 struct ext4_sb_info *sbi = EXT4_SB(sb);
2003 void *bitmap = e4b->bd_bitmap;
2004 struct ext4_free_extent ex;
2005 ext4_fsblk_t first_group_block;
2010 BUG_ON(sbi->s_stripe == 0);
2012 /* find first stripe-aligned block in group */
2013 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2015 a = first_group_block + sbi->s_stripe - 1;
2016 do_div(a, sbi->s_stripe);
2017 i = (a * sbi->s_stripe) - first_group_block;
2019 while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2020 if (!mb_test_bit(i, bitmap)) {
2021 max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
2022 if (max >= sbi->s_stripe) {
2024 ex.fe_logical = 0xDEADF00D; /* debug value */
2026 ext4_mb_use_best_found(ac, e4b);
2035 * This is now called BEFORE we load the buddy bitmap.
2036 * Returns either 1 or 0 indicating that the group is either suitable
2037 * for the allocation or not. In addition it can also return negative
2038 * error code when something goes wrong.
2040 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
2041 ext4_group_t group, int cr)
2043 unsigned free, fragments;
2044 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2045 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2047 BUG_ON(cr < 0 || cr >= 4);
2049 free = grp->bb_free;
2052 if (cr <= 2 && free < ac->ac_g_ex.fe_len)
2055 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2058 /* We only do this if the grp has never been initialized */
2059 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2060 int ret = ext4_mb_init_group(ac->ac_sb, group, GFP_NOFS);
2065 fragments = grp->bb_fragments;
2071 BUG_ON(ac->ac_2order == 0);
2073 /* Avoid using the first bg of a flexgroup for data files */
2074 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2075 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2076 ((group % flex_size) == 0))
2079 if ((ac->ac_2order > ac->ac_sb->s_blocksize_bits+1) ||
2080 (free / fragments) >= ac->ac_g_ex.fe_len)
2083 if (grp->bb_largest_free_order < ac->ac_2order)
2088 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2092 if (free >= ac->ac_g_ex.fe_len)
2104 static noinline_for_stack int
2105 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2107 ext4_group_t ngroups, group, i;
2109 int err = 0, first_err = 0;
2110 struct ext4_sb_info *sbi;
2111 struct super_block *sb;
2112 struct ext4_buddy e4b;
2116 ngroups = ext4_get_groups_count(sb);
2117 /* non-extent files are limited to low blocks/groups */
2118 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2119 ngroups = sbi->s_blockfile_groups;
2121 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2123 /* first, try the goal */
2124 err = ext4_mb_find_by_goal(ac, &e4b);
2125 if (err || ac->ac_status == AC_STATUS_FOUND)
2128 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2132 * ac->ac2_order is set only if the fe_len is a power of 2
2133 * if ac2_order is set we also set criteria to 0 so that we
2134 * try exact allocation using buddy.
2136 i = fls(ac->ac_g_ex.fe_len);
2139 * We search using buddy data only if the order of the request
2140 * is greater than equal to the sbi_s_mb_order2_reqs
2141 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2142 * We also support searching for power-of-two requests only for
2143 * requests upto maximum buddy size we have constructed.
2145 if (i >= sbi->s_mb_order2_reqs && i <= sb->s_blocksize_bits + 2) {
2147 * This should tell if fe_len is exactly power of 2
2149 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2150 ac->ac_2order = array_index_nospec(i - 1,
2151 sb->s_blocksize_bits + 2);
2154 /* if stream allocation is enabled, use global goal */
2155 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2156 /* TBD: may be hot point */
2157 spin_lock(&sbi->s_md_lock);
2158 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2159 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2160 spin_unlock(&sbi->s_md_lock);
2163 /* Let's just scan groups to find more-less suitable blocks */
2164 cr = ac->ac_2order ? 0 : 1;
2166 * cr == 0 try to get exact allocation,
2167 * cr == 3 try to get anything
2170 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2171 ac->ac_criteria = cr;
2173 * searching for the right group start
2174 * from the goal value specified
2176 group = ac->ac_g_ex.fe_group;
2178 for (i = 0; i < ngroups; group++, i++) {
2182 * Artificially restricted ngroups for non-extent
2183 * files makes group > ngroups possible on first loop.
2185 if (group >= ngroups)
2188 /* This now checks without needing the buddy page */
2189 ret = ext4_mb_good_group(ac, group, cr);
2196 err = ext4_mb_load_buddy(sb, group, &e4b);
2200 ext4_lock_group(sb, group);
2203 * We need to check again after locking the
2206 ret = ext4_mb_good_group(ac, group, cr);
2208 ext4_unlock_group(sb, group);
2209 ext4_mb_unload_buddy(&e4b);
2215 ac->ac_groups_scanned++;
2217 ext4_mb_simple_scan_group(ac, &e4b);
2218 else if (cr == 1 && sbi->s_stripe &&
2219 !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2220 ext4_mb_scan_aligned(ac, &e4b);
2222 ext4_mb_complex_scan_group(ac, &e4b);
2224 ext4_unlock_group(sb, group);
2225 ext4_mb_unload_buddy(&e4b);
2227 if (ac->ac_status != AC_STATUS_CONTINUE)
2232 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2233 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2235 * We've been searching too long. Let's try to allocate
2236 * the best chunk we've found so far
2239 ext4_mb_try_best_found(ac, &e4b);
2240 if (ac->ac_status != AC_STATUS_FOUND) {
2242 * Someone more lucky has already allocated it.
2243 * The only thing we can do is just take first
2245 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2247 ac->ac_b_ex.fe_group = 0;
2248 ac->ac_b_ex.fe_start = 0;
2249 ac->ac_b_ex.fe_len = 0;
2250 ac->ac_status = AC_STATUS_CONTINUE;
2251 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2253 atomic_inc(&sbi->s_mb_lost_chunks);
2258 if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2263 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2265 struct super_block *sb = seq->private;
2268 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2271 return (void *) ((unsigned long) group);
2274 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2276 struct super_block *sb = seq->private;
2280 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2283 return (void *) ((unsigned long) group);
2286 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2288 struct super_block *sb = seq->private;
2289 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2291 int err, buddy_loaded = 0;
2292 struct ext4_buddy e4b;
2293 struct ext4_group_info *grinfo;
2295 struct ext4_group_info info;
2296 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
2301 seq_puts(seq, "#group: free frags first ["
2302 " 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
2303 " 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
2305 i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2306 sizeof(struct ext4_group_info);
2307 grinfo = ext4_get_group_info(sb, group);
2308 /* Load the group info in memory only if not already loaded. */
2309 if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
2310 err = ext4_mb_load_buddy(sb, group, &e4b);
2312 seq_printf(seq, "#%-5u: I/O error\n", group);
2318 memcpy(&sg, ext4_get_group_info(sb, group), i);
2321 ext4_mb_unload_buddy(&e4b);
2323 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2324 sg.info.bb_fragments, sg.info.bb_first_free);
2325 for (i = 0; i <= 13; i++)
2326 seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2327 sg.info.bb_counters[i] : 0);
2328 seq_printf(seq, " ]\n");
2333 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2337 static const struct seq_operations ext4_mb_seq_groups_ops = {
2338 .start = ext4_mb_seq_groups_start,
2339 .next = ext4_mb_seq_groups_next,
2340 .stop = ext4_mb_seq_groups_stop,
2341 .show = ext4_mb_seq_groups_show,
2344 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2346 struct super_block *sb = PDE_DATA(inode);
2349 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2351 struct seq_file *m = file->private_data;
2358 const struct file_operations ext4_seq_mb_groups_fops = {
2359 .open = ext4_mb_seq_groups_open,
2361 .llseek = seq_lseek,
2362 .release = seq_release,
2365 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2367 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2368 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2375 * Allocate the top-level s_group_info array for the specified number
2378 int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
2380 struct ext4_sb_info *sbi = EXT4_SB(sb);
2382 struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
2384 size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
2385 EXT4_DESC_PER_BLOCK_BITS(sb);
2386 if (size <= sbi->s_group_info_size)
2389 size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
2390 new_groupinfo = ext4_kvzalloc(size, GFP_KERNEL);
2391 if (!new_groupinfo) {
2392 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
2396 old_groupinfo = rcu_dereference(sbi->s_group_info);
2398 memcpy(new_groupinfo, old_groupinfo,
2399 sbi->s_group_info_size * sizeof(*sbi->s_group_info));
2401 rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
2402 sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
2404 ext4_kvfree_array_rcu(old_groupinfo);
2405 ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
2406 sbi->s_group_info_size);
2410 /* Create and initialize ext4_group_info data for the given group. */
2411 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2412 struct ext4_group_desc *desc)
2416 int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
2417 struct ext4_sb_info *sbi = EXT4_SB(sb);
2418 struct ext4_group_info **meta_group_info;
2419 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2422 * First check if this group is the first of a reserved block.
2423 * If it's true, we have to allocate a new table of pointers
2424 * to ext4_group_info structures
2426 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2427 metalen = sizeof(*meta_group_info) <<
2428 EXT4_DESC_PER_BLOCK_BITS(sb);
2429 meta_group_info = kmalloc(metalen, GFP_NOFS);
2430 if (meta_group_info == NULL) {
2431 ext4_msg(sb, KERN_ERR, "can't allocate mem "
2432 "for a buddy group");
2433 goto exit_meta_group_info;
2436 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
2440 meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
2441 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2443 meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
2444 if (meta_group_info[i] == NULL) {
2445 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
2446 goto exit_group_info;
2448 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2449 &(meta_group_info[i]->bb_state));
2452 * initialize bb_free to be able to skip
2453 * empty groups without initialization
2455 if (ext4_has_group_desc_csum(sb) &&
2456 (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
2457 meta_group_info[i]->bb_free =
2458 ext4_free_clusters_after_init(sb, group, desc);
2460 meta_group_info[i]->bb_free =
2461 ext4_free_group_clusters(sb, desc);
2464 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2465 init_rwsem(&meta_group_info[i]->alloc_sem);
2466 meta_group_info[i]->bb_free_root = RB_ROOT;
2467 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
2471 struct buffer_head *bh;
2472 meta_group_info[i]->bb_bitmap =
2473 kmalloc(sb->s_blocksize, GFP_NOFS);
2474 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2475 bh = ext4_read_block_bitmap(sb, group);
2476 BUG_ON(IS_ERR_OR_NULL(bh));
2477 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2486 /* If a meta_group_info table has been allocated, release it now */
2487 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2488 struct ext4_group_info ***group_info;
2491 group_info = rcu_dereference(sbi->s_group_info);
2492 kfree(group_info[idx]);
2493 group_info[idx] = NULL;
2496 exit_meta_group_info:
2498 } /* ext4_mb_add_groupinfo */
2500 static int ext4_mb_init_backend(struct super_block *sb)
2502 ext4_group_t ngroups = ext4_get_groups_count(sb);
2504 struct ext4_sb_info *sbi = EXT4_SB(sb);
2506 struct ext4_group_desc *desc;
2507 struct ext4_group_info ***group_info;
2508 struct kmem_cache *cachep;
2510 err = ext4_mb_alloc_groupinfo(sb, ngroups);
2514 sbi->s_buddy_cache = new_inode(sb);
2515 if (sbi->s_buddy_cache == NULL) {
2516 ext4_msg(sb, KERN_ERR, "can't get new inode");
2519 /* To avoid potentially colliding with an valid on-disk inode number,
2520 * use EXT4_BAD_INO for the buddy cache inode number. This inode is
2521 * not in the inode hash, so it should never be found by iget(), but
2522 * this will avoid confusion if it ever shows up during debugging. */
2523 sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
2524 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2525 for (i = 0; i < ngroups; i++) {
2526 desc = ext4_get_group_desc(sb, i, NULL);
2528 ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2531 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2538 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2540 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2541 i = sbi->s_group_info_size;
2543 group_info = rcu_dereference(sbi->s_group_info);
2545 kfree(group_info[i]);
2547 iput(sbi->s_buddy_cache);
2550 kvfree(rcu_dereference(sbi->s_group_info));
2555 static void ext4_groupinfo_destroy_slabs(void)
2559 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
2560 if (ext4_groupinfo_caches[i])
2561 kmem_cache_destroy(ext4_groupinfo_caches[i]);
2562 ext4_groupinfo_caches[i] = NULL;
2566 static int ext4_groupinfo_create_slab(size_t size)
2568 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
2570 int blocksize_bits = order_base_2(size);
2571 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2572 struct kmem_cache *cachep;
2574 if (cache_index >= NR_GRPINFO_CACHES)
2577 if (unlikely(cache_index < 0))
2580 mutex_lock(&ext4_grpinfo_slab_create_mutex);
2581 if (ext4_groupinfo_caches[cache_index]) {
2582 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2583 return 0; /* Already created */
2586 slab_size = offsetof(struct ext4_group_info,
2587 bb_counters[blocksize_bits + 2]);
2589 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
2590 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
2593 ext4_groupinfo_caches[cache_index] = cachep;
2595 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2598 "EXT4-fs: no memory for groupinfo slab cache\n");
2605 int ext4_mb_init(struct super_block *sb)
2607 struct ext4_sb_info *sbi = EXT4_SB(sb);
2609 unsigned offset, offset_incr;
2613 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2615 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2616 if (sbi->s_mb_offsets == NULL) {
2621 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2622 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2623 if (sbi->s_mb_maxs == NULL) {
2628 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2632 /* order 0 is regular bitmap */
2633 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2634 sbi->s_mb_offsets[0] = 0;
2638 offset_incr = 1 << (sb->s_blocksize_bits - 1);
2639 max = sb->s_blocksize << 2;
2641 sbi->s_mb_offsets[i] = offset;
2642 sbi->s_mb_maxs[i] = max;
2643 offset += offset_incr;
2644 offset_incr = offset_incr >> 1;
2647 } while (i <= sb->s_blocksize_bits + 1);
2649 spin_lock_init(&sbi->s_md_lock);
2650 spin_lock_init(&sbi->s_bal_lock);
2651 sbi->s_mb_free_pending = 0;
2653 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2654 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2655 sbi->s_mb_stats = MB_DEFAULT_STATS;
2656 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2657 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2659 * The default group preallocation is 512, which for 4k block
2660 * sizes translates to 2 megabytes. However for bigalloc file
2661 * systems, this is probably too big (i.e, if the cluster size
2662 * is 1 megabyte, then group preallocation size becomes half a
2663 * gigabyte!). As a default, we will keep a two megabyte
2664 * group pralloc size for cluster sizes up to 64k, and after
2665 * that, we will force a minimum group preallocation size of
2666 * 32 clusters. This translates to 8 megs when the cluster
2667 * size is 256k, and 32 megs when the cluster size is 1 meg,
2668 * which seems reasonable as a default.
2670 sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
2671 sbi->s_cluster_bits, 32);
2673 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
2674 * to the lowest multiple of s_stripe which is bigger than
2675 * the s_mb_group_prealloc as determined above. We want
2676 * the preallocation size to be an exact multiple of the
2677 * RAID stripe size so that preallocations don't fragment
2680 if (sbi->s_stripe > 1) {
2681 sbi->s_mb_group_prealloc = roundup(
2682 sbi->s_mb_group_prealloc, sbi->s_stripe);
2685 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2686 if (sbi->s_locality_groups == NULL) {
2690 for_each_possible_cpu(i) {
2691 struct ext4_locality_group *lg;
2692 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2693 mutex_init(&lg->lg_mutex);
2694 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2695 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2696 spin_lock_init(&lg->lg_prealloc_lock);
2699 /* init file for buddy data */
2700 ret = ext4_mb_init_backend(sb);
2702 goto out_free_locality_groups;
2706 out_free_locality_groups:
2707 free_percpu(sbi->s_locality_groups);
2708 sbi->s_locality_groups = NULL;
2710 kfree(sbi->s_mb_offsets);
2711 sbi->s_mb_offsets = NULL;
2712 kfree(sbi->s_mb_maxs);
2713 sbi->s_mb_maxs = NULL;
2717 /* need to called with the ext4 group lock held */
2718 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2720 struct ext4_prealloc_space *pa;
2721 struct list_head *cur, *tmp;
2724 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2725 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2726 list_del(&pa->pa_group_list);
2728 kmem_cache_free(ext4_pspace_cachep, pa);
2731 mb_debug(1, "mballoc: %u PAs left\n", count);
2735 int ext4_mb_release(struct super_block *sb)
2737 ext4_group_t ngroups = ext4_get_groups_count(sb);
2739 int num_meta_group_infos;
2740 struct ext4_group_info *grinfo, ***group_info;
2741 struct ext4_sb_info *sbi = EXT4_SB(sb);
2742 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2744 if (sbi->s_group_info) {
2745 for (i = 0; i < ngroups; i++) {
2746 grinfo = ext4_get_group_info(sb, i);
2748 kfree(grinfo->bb_bitmap);
2750 ext4_lock_group(sb, i);
2751 ext4_mb_cleanup_pa(grinfo);
2752 ext4_unlock_group(sb, i);
2753 kmem_cache_free(cachep, grinfo);
2755 num_meta_group_infos = (ngroups +
2756 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2757 EXT4_DESC_PER_BLOCK_BITS(sb);
2759 group_info = rcu_dereference(sbi->s_group_info);
2760 for (i = 0; i < num_meta_group_infos; i++)
2761 kfree(group_info[i]);
2765 kfree(sbi->s_mb_offsets);
2766 kfree(sbi->s_mb_maxs);
2767 iput(sbi->s_buddy_cache);
2768 if (sbi->s_mb_stats) {
2769 ext4_msg(sb, KERN_INFO,
2770 "mballoc: %u blocks %u reqs (%u success)",
2771 atomic_read(&sbi->s_bal_allocated),
2772 atomic_read(&sbi->s_bal_reqs),
2773 atomic_read(&sbi->s_bal_success));
2774 ext4_msg(sb, KERN_INFO,
2775 "mballoc: %u extents scanned, %u goal hits, "
2776 "%u 2^N hits, %u breaks, %u lost",
2777 atomic_read(&sbi->s_bal_ex_scanned),
2778 atomic_read(&sbi->s_bal_goals),
2779 atomic_read(&sbi->s_bal_2orders),
2780 atomic_read(&sbi->s_bal_breaks),
2781 atomic_read(&sbi->s_mb_lost_chunks));
2782 ext4_msg(sb, KERN_INFO,
2783 "mballoc: %lu generated and it took %Lu",
2784 sbi->s_mb_buddies_generated,
2785 sbi->s_mb_generation_time);
2786 ext4_msg(sb, KERN_INFO,
2787 "mballoc: %u preallocated, %u discarded",
2788 atomic_read(&sbi->s_mb_preallocated),
2789 atomic_read(&sbi->s_mb_discarded));
2792 free_percpu(sbi->s_locality_groups);
2797 static inline int ext4_issue_discard(struct super_block *sb,
2798 ext4_group_t block_group, ext4_grpblk_t cluster, int count)
2800 ext4_fsblk_t discard_block;
2802 discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
2803 ext4_group_first_block_no(sb, block_group));
2804 count = EXT4_C2B(EXT4_SB(sb), count);
2805 trace_ext4_discard_blocks(sb,
2806 (unsigned long long) discard_block, count);
2807 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
2811 * This function is called by the jbd2 layer once the commit has finished,
2812 * so we know we can free the blocks that were released with that commit.
2814 static void ext4_free_data_callback(struct super_block *sb,
2815 struct ext4_journal_cb_entry *jce,
2818 struct ext4_free_data *entry = (struct ext4_free_data *)jce;
2819 struct ext4_buddy e4b;
2820 struct ext4_group_info *db;
2821 int err, count = 0, count2 = 0;
2823 mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2824 entry->efd_count, entry->efd_group, entry);
2826 if (test_opt(sb, DISCARD)) {
2827 err = ext4_issue_discard(sb, entry->efd_group,
2828 entry->efd_start_cluster,
2830 if (err && err != -EOPNOTSUPP)
2831 ext4_msg(sb, KERN_WARNING, "discard request in"
2832 " group:%d block:%d count:%d failed"
2833 " with %d", entry->efd_group,
2834 entry->efd_start_cluster,
2835 entry->efd_count, err);
2838 err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
2839 /* we expect to find existing buddy because it's pinned */
2842 spin_lock(&EXT4_SB(sb)->s_md_lock);
2843 EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
2844 spin_unlock(&EXT4_SB(sb)->s_md_lock);
2847 /* there are blocks to put in buddy to make them really free */
2848 count += entry->efd_count;
2850 ext4_lock_group(sb, entry->efd_group);
2851 /* Take it out of per group rb tree */
2852 rb_erase(&entry->efd_node, &(db->bb_free_root));
2853 mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
2856 * Clear the trimmed flag for the group so that the next
2857 * ext4_trim_fs can trim it.
2858 * If the volume is mounted with -o discard, online discard
2859 * is supported and the free blocks will be trimmed online.
2861 if (!test_opt(sb, DISCARD))
2862 EXT4_MB_GRP_CLEAR_TRIMMED(db);
2864 if (!db->bb_free_root.rb_node) {
2865 /* No more items in the per group rb tree
2866 * balance refcounts from ext4_mb_free_metadata()
2868 put_page(e4b.bd_buddy_page);
2869 put_page(e4b.bd_bitmap_page);
2871 ext4_unlock_group(sb, entry->efd_group);
2872 kmem_cache_free(ext4_free_data_cachep, entry);
2873 ext4_mb_unload_buddy(&e4b);
2875 mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2878 int __init ext4_init_mballoc(void)
2880 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
2881 SLAB_RECLAIM_ACCOUNT);
2882 if (ext4_pspace_cachep == NULL)
2885 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
2886 SLAB_RECLAIM_ACCOUNT);
2887 if (ext4_ac_cachep == NULL) {
2888 kmem_cache_destroy(ext4_pspace_cachep);
2892 ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
2893 SLAB_RECLAIM_ACCOUNT);
2894 if (ext4_free_data_cachep == NULL) {
2895 kmem_cache_destroy(ext4_pspace_cachep);
2896 kmem_cache_destroy(ext4_ac_cachep);
2902 void ext4_exit_mballoc(void)
2905 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
2906 * before destroying the slab cache.
2909 kmem_cache_destroy(ext4_pspace_cachep);
2910 kmem_cache_destroy(ext4_ac_cachep);
2911 kmem_cache_destroy(ext4_free_data_cachep);
2912 ext4_groupinfo_destroy_slabs();
2917 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2918 * Returns 0 if success or error code
2920 static noinline_for_stack int
2921 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2922 handle_t *handle, unsigned int reserv_clstrs)
2924 struct buffer_head *bitmap_bh = NULL;
2925 struct ext4_group_desc *gdp;
2926 struct buffer_head *gdp_bh;
2927 struct ext4_sb_info *sbi;
2928 struct super_block *sb;
2932 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2933 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2938 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2939 if (IS_ERR(bitmap_bh)) {
2940 err = PTR_ERR(bitmap_bh);
2945 BUFFER_TRACE(bitmap_bh, "getting write access");
2946 err = ext4_journal_get_write_access(handle, bitmap_bh);
2951 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2955 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
2956 ext4_free_group_clusters(sb, gdp));
2958 BUFFER_TRACE(gdp_bh, "get_write_access");
2959 err = ext4_journal_get_write_access(handle, gdp_bh);
2963 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
2965 len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
2966 if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
2967 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
2968 "fs metadata", block, block+len);
2969 /* File system mounted not to panic on error
2970 * Fix the bitmap and return EFSCORRUPTED
2971 * We leak some of the blocks here.
2973 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2974 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2975 ac->ac_b_ex.fe_len);
2976 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
2977 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2979 err = -EFSCORRUPTED;
2983 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2984 #ifdef AGGRESSIVE_CHECK
2987 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
2988 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
2989 bitmap_bh->b_data));
2993 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2994 ac->ac_b_ex.fe_len);
2995 if (ext4_has_group_desc_csum(sb) &&
2996 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
2997 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
2998 ext4_free_group_clusters_set(sb, gdp,
2999 ext4_free_clusters_after_init(sb,
3000 ac->ac_b_ex.fe_group, gdp));
3002 len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
3003 ext4_free_group_clusters_set(sb, gdp, len);
3004 ext4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);
3005 ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
3007 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3008 percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
3010 * Now reduce the dirty block count also. Should not go negative
3012 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3013 /* release all the reserved blocks if non delalloc */
3014 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
3017 if (sbi->s_log_groups_per_flex) {
3018 ext4_group_t flex_group = ext4_flex_group(sbi,
3019 ac->ac_b_ex.fe_group);
3020 atomic64_sub(ac->ac_b_ex.fe_len,
3021 &sbi_array_rcu_deref(sbi, s_flex_groups,
3022 flex_group)->free_clusters);
3025 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3028 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3036 * here we normalize request for locality group
3037 * Group request are normalized to s_mb_group_prealloc, which goes to
3038 * s_strip if we set the same via mount option.
3039 * s_mb_group_prealloc can be configured via
3040 * /sys/fs/ext4/<partition>/mb_group_prealloc
3042 * XXX: should we try to preallocate more than the group has now?
3044 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3046 struct super_block *sb = ac->ac_sb;
3047 struct ext4_locality_group *lg = ac->ac_lg;
3050 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3051 mb_debug(1, "#%u: goal %u blocks for locality group\n",
3052 current->pid, ac->ac_g_ex.fe_len);
3056 * Normalization means making request better in terms of
3057 * size and alignment
3059 static noinline_for_stack void
3060 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3061 struct ext4_allocation_request *ar)
3063 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3066 loff_t size, start_off;
3067 loff_t orig_size __maybe_unused;
3069 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3070 struct ext4_prealloc_space *pa;
3072 /* do normalize only data requests, metadata requests
3073 do not need preallocation */
3074 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3077 /* sometime caller may want exact blocks */
3078 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3081 /* caller may indicate that preallocation isn't
3082 * required (it's a tail, for example) */
3083 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3086 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3087 ext4_mb_normalize_group_request(ac);
3091 bsbits = ac->ac_sb->s_blocksize_bits;
3093 /* first, let's learn actual file size
3094 * given current request is allocated */
3095 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
3096 size = size << bsbits;
3097 if (size < i_size_read(ac->ac_inode))
3098 size = i_size_read(ac->ac_inode);
3101 /* max size of free chunks */
3104 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
3105 (req <= (size) || max <= (chunk_size))
3107 /* first, try to predict filesize */
3108 /* XXX: should this table be tunable? */
3110 if (size <= 16 * 1024) {
3112 } else if (size <= 32 * 1024) {
3114 } else if (size <= 64 * 1024) {
3116 } else if (size <= 128 * 1024) {
3118 } else if (size <= 256 * 1024) {
3120 } else if (size <= 512 * 1024) {
3122 } else if (size <= 1024 * 1024) {
3124 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3125 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3126 (21 - bsbits)) << 21;
3127 size = 2 * 1024 * 1024;
3128 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3129 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3130 (22 - bsbits)) << 22;
3131 size = 4 * 1024 * 1024;
3132 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3133 (8<<20)>>bsbits, max, 8 * 1024)) {
3134 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3135 (23 - bsbits)) << 23;
3136 size = 8 * 1024 * 1024;
3138 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
3139 size = (loff_t) EXT4_C2B(EXT4_SB(ac->ac_sb),
3140 ac->ac_o_ex.fe_len) << bsbits;
3142 size = size >> bsbits;
3143 start = start_off >> bsbits;
3146 * For tiny groups (smaller than 8MB) the chosen allocation
3147 * alignment may be larger than group size. Make sure the
3148 * alignment does not move allocation to a different group which
3149 * makes mballoc fail assertions later.
3151 start = max(start, rounddown(ac->ac_o_ex.fe_logical,
3152 (ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
3154 /* don't cover already allocated blocks in selected range */
3155 if (ar->pleft && start <= ar->lleft) {
3156 size -= ar->lleft + 1 - start;
3157 start = ar->lleft + 1;
3159 if (ar->pright && start + size - 1 >= ar->lright)
3160 size -= start + size - ar->lright;
3163 * Trim allocation request for filesystems with artificially small
3166 if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
3167 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
3171 /* check we don't cross already preallocated blocks */
3173 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3178 spin_lock(&pa->pa_lock);
3179 if (pa->pa_deleted) {
3180 spin_unlock(&pa->pa_lock);
3184 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3187 /* PA must not overlap original request */
3188 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3189 ac->ac_o_ex.fe_logical < pa->pa_lstart));
3191 /* skip PAs this normalized request doesn't overlap with */
3192 if (pa->pa_lstart >= end || pa_end <= start) {
3193 spin_unlock(&pa->pa_lock);
3196 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3198 /* adjust start or end to be adjacent to this pa */
3199 if (pa_end <= ac->ac_o_ex.fe_logical) {
3200 BUG_ON(pa_end < start);
3202 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3203 BUG_ON(pa->pa_lstart > end);
3204 end = pa->pa_lstart;
3206 spin_unlock(&pa->pa_lock);
3211 /* XXX: extra loop to check we really don't overlap preallocations */
3213 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3216 spin_lock(&pa->pa_lock);
3217 if (pa->pa_deleted == 0) {
3218 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3220 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3222 spin_unlock(&pa->pa_lock);
3226 if (start + size <= ac->ac_o_ex.fe_logical &&
3227 start > ac->ac_o_ex.fe_logical) {
3228 ext4_msg(ac->ac_sb, KERN_ERR,
3229 "start %lu, size %lu, fe_logical %lu",
3230 (unsigned long) start, (unsigned long) size,
3231 (unsigned long) ac->ac_o_ex.fe_logical);
3234 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3236 /* now prepare goal request */
3238 /* XXX: is it better to align blocks WRT to logical
3239 * placement or satisfy big request as is */
3240 ac->ac_g_ex.fe_logical = start;
3241 ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3243 /* define goal start in order to merge */
3244 if (ar->pright && (ar->lright == (start + size))) {
3245 /* merge to the right */
3246 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3247 &ac->ac_f_ex.fe_group,
3248 &ac->ac_f_ex.fe_start);
3249 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3251 if (ar->pleft && (ar->lleft + 1 == start)) {
3252 /* merge to the left */
3253 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3254 &ac->ac_f_ex.fe_group,
3255 &ac->ac_f_ex.fe_start);
3256 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3259 mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3260 (unsigned) orig_size, (unsigned) start);
3263 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3265 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3267 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3268 atomic_inc(&sbi->s_bal_reqs);
3269 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3270 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3271 atomic_inc(&sbi->s_bal_success);
3272 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3273 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3274 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3275 atomic_inc(&sbi->s_bal_goals);
3276 if (ac->ac_found > sbi->s_mb_max_to_scan)
3277 atomic_inc(&sbi->s_bal_breaks);
3280 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3281 trace_ext4_mballoc_alloc(ac);
3283 trace_ext4_mballoc_prealloc(ac);
3287 * Called on failure; free up any blocks from the inode PA for this
3288 * context. We don't need this for MB_GROUP_PA because we only change
3289 * pa_free in ext4_mb_release_context(), but on failure, we've already
3290 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3292 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3294 struct ext4_prealloc_space *pa = ac->ac_pa;
3295 struct ext4_buddy e4b;
3299 if (ac->ac_f_ex.fe_len == 0)
3301 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
3304 * This should never happen since we pin the
3305 * pages in the ext4_allocation_context so
3306 * ext4_mb_load_buddy() should never fail.
3308 WARN(1, "mb_load_buddy failed (%d)", err);
3311 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3312 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
3313 ac->ac_f_ex.fe_len);
3314 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3315 ext4_mb_unload_buddy(&e4b);
3318 if (pa->pa_type == MB_INODE_PA)
3319 pa->pa_free += ac->ac_b_ex.fe_len;
3323 * use blocks preallocated to inode
3325 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3326 struct ext4_prealloc_space *pa)
3328 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3333 /* found preallocated blocks, use them */
3334 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3335 end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
3336 start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
3337 len = EXT4_NUM_B2C(sbi, end - start);
3338 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3339 &ac->ac_b_ex.fe_start);
3340 ac->ac_b_ex.fe_len = len;
3341 ac->ac_status = AC_STATUS_FOUND;
3344 BUG_ON(start < pa->pa_pstart);
3345 BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3346 BUG_ON(pa->pa_free < len);
3349 mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3353 * use blocks preallocated to locality group
3355 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3356 struct ext4_prealloc_space *pa)
3358 unsigned int len = ac->ac_o_ex.fe_len;
3360 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3361 &ac->ac_b_ex.fe_group,
3362 &ac->ac_b_ex.fe_start);
3363 ac->ac_b_ex.fe_len = len;
3364 ac->ac_status = AC_STATUS_FOUND;
3367 /* we don't correct pa_pstart or pa_plen here to avoid
3368 * possible race when the group is being loaded concurrently
3369 * instead we correct pa later, after blocks are marked
3370 * in on-disk bitmap -- see ext4_mb_release_context()
3371 * Other CPUs are prevented from allocating from this pa by lg_mutex
3373 mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3377 * Return the prealloc space that have minimal distance
3378 * from the goal block. @cpa is the prealloc
3379 * space that is having currently known minimal distance
3380 * from the goal block.
3382 static struct ext4_prealloc_space *
3383 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3384 struct ext4_prealloc_space *pa,
3385 struct ext4_prealloc_space *cpa)
3387 ext4_fsblk_t cur_distance, new_distance;
3390 atomic_inc(&pa->pa_count);
3393 cur_distance = abs(goal_block - cpa->pa_pstart);
3394 new_distance = abs(goal_block - pa->pa_pstart);
3396 if (cur_distance <= new_distance)
3399 /* drop the previous reference */
3400 atomic_dec(&cpa->pa_count);
3401 atomic_inc(&pa->pa_count);
3406 * search goal blocks in preallocated space
3408 static noinline_for_stack int
3409 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3411 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3413 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3414 struct ext4_locality_group *lg;
3415 struct ext4_prealloc_space *pa, *cpa = NULL;
3416 ext4_fsblk_t goal_block;
3418 /* only data can be preallocated */
3419 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3422 /* first, try per-file preallocation */
3424 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3426 /* all fields in this condition don't change,
3427 * so we can skip locking for them */
3428 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3429 ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
3430 EXT4_C2B(sbi, pa->pa_len)))
3433 /* non-extent files can't have physical blocks past 2^32 */
3434 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3435 (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
3436 EXT4_MAX_BLOCK_FILE_PHYS))
3439 /* found preallocated blocks, use them */
3440 spin_lock(&pa->pa_lock);
3441 if (pa->pa_deleted == 0 && pa->pa_free) {
3442 atomic_inc(&pa->pa_count);
3443 ext4_mb_use_inode_pa(ac, pa);
3444 spin_unlock(&pa->pa_lock);
3445 ac->ac_criteria = 10;
3449 spin_unlock(&pa->pa_lock);
3453 /* can we use group allocation? */
3454 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3457 /* inode may have no locality group for some reason */
3461 order = fls(ac->ac_o_ex.fe_len) - 1;
3462 if (order > PREALLOC_TB_SIZE - 1)
3463 /* The max size of hash table is PREALLOC_TB_SIZE */
3464 order = PREALLOC_TB_SIZE - 1;
3466 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3468 * search for the prealloc space that is having
3469 * minimal distance from the goal block.
3471 for (i = order; i < PREALLOC_TB_SIZE; i++) {
3473 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3475 spin_lock(&pa->pa_lock);
3476 if (pa->pa_deleted == 0 &&
3477 pa->pa_free >= ac->ac_o_ex.fe_len) {
3479 cpa = ext4_mb_check_group_pa(goal_block,
3482 spin_unlock(&pa->pa_lock);
3487 ext4_mb_use_group_pa(ac, cpa);
3488 ac->ac_criteria = 20;
3495 * the function goes through all block freed in the group
3496 * but not yet committed and marks them used in in-core bitmap.
3497 * buddy must be generated from this bitmap
3498 * Need to be called with the ext4 group lock held
3500 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3504 struct ext4_group_info *grp;
3505 struct ext4_free_data *entry;
3507 grp = ext4_get_group_info(sb, group);
3508 n = rb_first(&(grp->bb_free_root));
3511 entry = rb_entry(n, struct ext4_free_data, efd_node);
3512 ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
3519 * the function goes through all preallocation in this group and marks them
3520 * used in in-core bitmap. buddy must be generated from this bitmap
3521 * Need to be called with ext4 group lock held
3523 static noinline_for_stack
3524 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3527 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3528 struct ext4_prealloc_space *pa;
3529 struct list_head *cur;
3530 ext4_group_t groupnr;
3531 ext4_grpblk_t start;
3532 int preallocated = 0;
3535 /* all form of preallocation discards first load group,
3536 * so the only competing code is preallocation use.
3537 * we don't need any locking here
3538 * notice we do NOT ignore preallocations with pa_deleted
3539 * otherwise we could leave used blocks available for
3540 * allocation in buddy when concurrent ext4_mb_put_pa()
3541 * is dropping preallocation
3543 list_for_each(cur, &grp->bb_prealloc_list) {
3544 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3545 spin_lock(&pa->pa_lock);
3546 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3549 spin_unlock(&pa->pa_lock);
3550 if (unlikely(len == 0))
3552 BUG_ON(groupnr != group);
3553 ext4_set_bits(bitmap, start, len);
3554 preallocated += len;
3556 mb_debug(1, "prellocated %u for group %u\n", preallocated, group);
3559 static void ext4_mb_pa_callback(struct rcu_head *head)
3561 struct ext4_prealloc_space *pa;
3562 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3564 BUG_ON(atomic_read(&pa->pa_count));
3565 BUG_ON(pa->pa_deleted == 0);
3566 kmem_cache_free(ext4_pspace_cachep, pa);
3570 * drops a reference to preallocated space descriptor
3571 * if this was the last reference and the space is consumed
3573 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3574 struct super_block *sb, struct ext4_prealloc_space *pa)
3577 ext4_fsblk_t grp_blk;
3579 /* in this short window concurrent discard can set pa_deleted */
3580 spin_lock(&pa->pa_lock);
3581 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
3582 spin_unlock(&pa->pa_lock);
3586 if (pa->pa_deleted == 1) {
3587 spin_unlock(&pa->pa_lock);
3592 spin_unlock(&pa->pa_lock);
3594 grp_blk = pa->pa_pstart;
3596 * If doing group-based preallocation, pa_pstart may be in the
3597 * next group when pa is used up
3599 if (pa->pa_type == MB_GROUP_PA)
3602 grp = ext4_get_group_number(sb, grp_blk);
3607 * P1 (buddy init) P2 (regular allocation)
3608 * find block B in PA
3609 * copy on-disk bitmap to buddy
3610 * mark B in on-disk bitmap
3611 * drop PA from group
3612 * mark all PAs in buddy
3614 * thus, P1 initializes buddy with B available. to prevent this
3615 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3618 ext4_lock_group(sb, grp);
3619 list_del(&pa->pa_group_list);
3620 ext4_unlock_group(sb, grp);
3622 spin_lock(pa->pa_obj_lock);
3623 list_del_rcu(&pa->pa_inode_list);
3624 spin_unlock(pa->pa_obj_lock);
3626 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3630 * creates new preallocated space for given inode
3632 static noinline_for_stack int
3633 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3635 struct super_block *sb = ac->ac_sb;
3636 struct ext4_sb_info *sbi = EXT4_SB(sb);
3637 struct ext4_prealloc_space *pa;
3638 struct ext4_group_info *grp;
3639 struct ext4_inode_info *ei;
3641 /* preallocate only when found space is larger then requested */
3642 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3643 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3644 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3646 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3650 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3656 /* we can't allocate as much as normalizer wants.
3657 * so, found space must get proper lstart
3658 * to cover original request */
3659 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3660 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3662 /* we're limited by original request in that
3663 * logical block must be covered any way
3664 * winl is window we can move our chunk within */
3665 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3667 /* also, we should cover whole original request */
3668 wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
3670 /* the smallest one defines real window */
3671 win = min(winl, wins);
3673 offs = ac->ac_o_ex.fe_logical %
3674 EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3675 if (offs && offs < win)
3678 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
3679 EXT4_NUM_B2C(sbi, win);
3680 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3681 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3684 /* preallocation can change ac_b_ex, thus we store actually
3685 * allocated blocks for history */
3686 ac->ac_f_ex = ac->ac_b_ex;
3688 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3689 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3690 pa->pa_len = ac->ac_b_ex.fe_len;
3691 pa->pa_free = pa->pa_len;
3692 atomic_set(&pa->pa_count, 1);
3693 spin_lock_init(&pa->pa_lock);
3694 INIT_LIST_HEAD(&pa->pa_inode_list);
3695 INIT_LIST_HEAD(&pa->pa_group_list);
3697 pa->pa_type = MB_INODE_PA;
3699 mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3700 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3701 trace_ext4_mb_new_inode_pa(ac, pa);
3703 ext4_mb_use_inode_pa(ac, pa);
3704 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
3706 ei = EXT4_I(ac->ac_inode);
3707 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3709 pa->pa_obj_lock = &ei->i_prealloc_lock;
3710 pa->pa_inode = ac->ac_inode;
3712 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3713 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3714 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3716 spin_lock(pa->pa_obj_lock);
3717 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3718 spin_unlock(pa->pa_obj_lock);
3724 * creates new preallocated space for locality group inodes belongs to
3726 static noinline_for_stack int
3727 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3729 struct super_block *sb = ac->ac_sb;
3730 struct ext4_locality_group *lg;
3731 struct ext4_prealloc_space *pa;
3732 struct ext4_group_info *grp;
3734 /* preallocate only when found space is larger then requested */
3735 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3736 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3737 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3739 BUG_ON(ext4_pspace_cachep == NULL);
3740 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3744 /* preallocation can change ac_b_ex, thus we store actually
3745 * allocated blocks for history */
3746 ac->ac_f_ex = ac->ac_b_ex;
3748 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3749 pa->pa_lstart = pa->pa_pstart;
3750 pa->pa_len = ac->ac_b_ex.fe_len;
3751 pa->pa_free = pa->pa_len;
3752 atomic_set(&pa->pa_count, 1);
3753 spin_lock_init(&pa->pa_lock);
3754 INIT_LIST_HEAD(&pa->pa_inode_list);
3755 INIT_LIST_HEAD(&pa->pa_group_list);
3757 pa->pa_type = MB_GROUP_PA;
3759 mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3760 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3761 trace_ext4_mb_new_group_pa(ac, pa);
3763 ext4_mb_use_group_pa(ac, pa);
3764 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3766 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3770 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3771 pa->pa_inode = NULL;
3773 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3774 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3775 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3778 * We will later add the new pa to the right bucket
3779 * after updating the pa_free in ext4_mb_release_context
3784 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3788 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3789 err = ext4_mb_new_group_pa(ac);
3791 err = ext4_mb_new_inode_pa(ac);
3796 * finds all unused blocks in on-disk bitmap, frees them in
3797 * in-core bitmap and buddy.
3798 * @pa must be unlinked from inode and group lists, so that
3799 * nobody else can find/use it.
3800 * the caller MUST hold group/inode locks.
3801 * TODO: optimize the case when there are no in-core structures yet
3803 static noinline_for_stack int
3804 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3805 struct ext4_prealloc_space *pa)
3807 struct super_block *sb = e4b->bd_sb;
3808 struct ext4_sb_info *sbi = EXT4_SB(sb);
3813 unsigned long long grp_blk_start;
3817 BUG_ON(pa->pa_deleted == 0);
3818 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3819 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
3820 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3821 end = bit + pa->pa_len;
3824 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3827 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3828 mb_debug(1, " free preallocated %u/%u in group %u\n",
3829 (unsigned) ext4_group_first_block_no(sb, group) + bit,
3830 (unsigned) next - bit, (unsigned) group);
3833 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
3834 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
3835 EXT4_C2B(sbi, bit)),
3837 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3840 if (free != pa->pa_free) {
3841 ext4_msg(e4b->bd_sb, KERN_CRIT,
3842 "pa %p: logic %lu, phys. %lu, len %lu",
3843 pa, (unsigned long) pa->pa_lstart,
3844 (unsigned long) pa->pa_pstart,
3845 (unsigned long) pa->pa_len);
3846 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
3849 * pa is already deleted so we use the value obtained
3850 * from the bitmap and continue.
3853 atomic_add(free, &sbi->s_mb_discarded);
3858 static noinline_for_stack int
3859 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3860 struct ext4_prealloc_space *pa)
3862 struct super_block *sb = e4b->bd_sb;
3866 trace_ext4_mb_release_group_pa(sb, pa);
3867 BUG_ON(pa->pa_deleted == 0);
3868 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3869 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3870 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3871 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3872 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3878 * releases all preallocations in given group
3880 * first, we need to decide discard policy:
3881 * - when do we discard
3883 * - how many do we discard
3884 * 1) how many requested
3886 static noinline_for_stack int
3887 ext4_mb_discard_group_preallocations(struct super_block *sb,
3888 ext4_group_t group, int needed)
3890 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3891 struct buffer_head *bitmap_bh = NULL;
3892 struct ext4_prealloc_space *pa, *tmp;
3893 struct list_head list;
3894 struct ext4_buddy e4b;
3899 mb_debug(1, "discard preallocation for group %u\n", group);
3901 if (list_empty(&grp->bb_prealloc_list))
3904 bitmap_bh = ext4_read_block_bitmap(sb, group);
3905 if (IS_ERR(bitmap_bh)) {
3906 err = PTR_ERR(bitmap_bh);
3907 ext4_error(sb, "Error %d reading block bitmap for %u",
3912 err = ext4_mb_load_buddy(sb, group, &e4b);
3914 ext4_warning(sb, "Error %d loading buddy information for %u",
3921 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
3923 INIT_LIST_HEAD(&list);
3925 ext4_lock_group(sb, group);
3926 list_for_each_entry_safe(pa, tmp,
3927 &grp->bb_prealloc_list, pa_group_list) {
3928 spin_lock(&pa->pa_lock);
3929 if (atomic_read(&pa->pa_count)) {
3930 spin_unlock(&pa->pa_lock);
3934 if (pa->pa_deleted) {
3935 spin_unlock(&pa->pa_lock);
3939 /* seems this one can be freed ... */
3942 /* we can trust pa_free ... */
3943 free += pa->pa_free;
3945 spin_unlock(&pa->pa_lock);
3947 list_del(&pa->pa_group_list);
3948 list_add(&pa->u.pa_tmp_list, &list);
3951 /* if we still need more blocks and some PAs were used, try again */
3952 if (free < needed && busy) {
3954 ext4_unlock_group(sb, group);
3959 /* found anything to free? */
3960 if (list_empty(&list)) {
3965 /* now free all selected PAs */
3966 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3968 /* remove from object (inode or locality group) */
3969 spin_lock(pa->pa_obj_lock);
3970 list_del_rcu(&pa->pa_inode_list);
3971 spin_unlock(pa->pa_obj_lock);
3973 if (pa->pa_type == MB_GROUP_PA)
3974 ext4_mb_release_group_pa(&e4b, pa);
3976 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3978 list_del(&pa->u.pa_tmp_list);
3979 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3983 ext4_unlock_group(sb, group);
3984 ext4_mb_unload_buddy(&e4b);
3990 * releases all non-used preallocated blocks for given inode
3992 * It's important to discard preallocations under i_data_sem
3993 * We don't want another block to be served from the prealloc
3994 * space when we are discarding the inode prealloc space.
3996 * FIXME!! Make sure it is valid at all the call sites
3998 void ext4_discard_preallocations(struct inode *inode)
4000 struct ext4_inode_info *ei = EXT4_I(inode);
4001 struct super_block *sb = inode->i_sb;
4002 struct buffer_head *bitmap_bh = NULL;
4003 struct ext4_prealloc_space *pa, *tmp;
4004 ext4_group_t group = 0;
4005 struct list_head list;
4006 struct ext4_buddy e4b;
4009 if (!S_ISREG(inode->i_mode)) {
4010 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4014 mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
4015 trace_ext4_discard_preallocations(inode);
4017 INIT_LIST_HEAD(&list);
4020 /* first, collect all pa's in the inode */
4021 spin_lock(&ei->i_prealloc_lock);
4022 while (!list_empty(&ei->i_prealloc_list)) {
4023 pa = list_entry(ei->i_prealloc_list.next,
4024 struct ext4_prealloc_space, pa_inode_list);
4025 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4026 spin_lock(&pa->pa_lock);
4027 if (atomic_read(&pa->pa_count)) {
4028 /* this shouldn't happen often - nobody should
4029 * use preallocation while we're discarding it */
4030 spin_unlock(&pa->pa_lock);
4031 spin_unlock(&ei->i_prealloc_lock);
4032 ext4_msg(sb, KERN_ERR,
4033 "uh-oh! used pa while discarding");
4035 schedule_timeout_uninterruptible(HZ);
4039 if (pa->pa_deleted == 0) {
4041 spin_unlock(&pa->pa_lock);
4042 list_del_rcu(&pa->pa_inode_list);
4043 list_add(&pa->u.pa_tmp_list, &list);
4047 /* someone is deleting pa right now */
4048 spin_unlock(&pa->pa_lock);
4049 spin_unlock(&ei->i_prealloc_lock);
4051 /* we have to wait here because pa_deleted
4052 * doesn't mean pa is already unlinked from
4053 * the list. as we might be called from
4054 * ->clear_inode() the inode will get freed
4055 * and concurrent thread which is unlinking
4056 * pa from inode's list may access already
4057 * freed memory, bad-bad-bad */
4059 /* XXX: if this happens too often, we can
4060 * add a flag to force wait only in case
4061 * of ->clear_inode(), but not in case of
4062 * regular truncate */
4063 schedule_timeout_uninterruptible(HZ);
4066 spin_unlock(&ei->i_prealloc_lock);
4068 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4069 BUG_ON(pa->pa_type != MB_INODE_PA);
4070 group = ext4_get_group_number(sb, pa->pa_pstart);
4072 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4073 GFP_NOFS|__GFP_NOFAIL);
4075 ext4_error(sb, "Error %d loading buddy information for %u",
4080 bitmap_bh = ext4_read_block_bitmap(sb, group);
4081 if (IS_ERR(bitmap_bh)) {
4082 err = PTR_ERR(bitmap_bh);
4083 ext4_error(sb, "Error %d reading block bitmap for %u",
4085 ext4_mb_unload_buddy(&e4b);
4089 ext4_lock_group(sb, group);
4090 list_del(&pa->pa_group_list);
4091 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4092 ext4_unlock_group(sb, group);
4094 ext4_mb_unload_buddy(&e4b);
4097 list_del(&pa->u.pa_tmp_list);
4098 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4102 #ifdef CONFIG_EXT4_DEBUG
4103 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4105 struct super_block *sb = ac->ac_sb;
4106 ext4_group_t ngroups, i;
4108 if (!ext4_mballoc_debug ||
4109 (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
4112 ext4_msg(ac->ac_sb, KERN_ERR, "Can't allocate:"
4113 " Allocation context details:");
4114 ext4_msg(ac->ac_sb, KERN_ERR, "status %d flags %d",
4115 ac->ac_status, ac->ac_flags);
4116 ext4_msg(ac->ac_sb, KERN_ERR, "orig %lu/%lu/%lu@%lu, "
4117 "goal %lu/%lu/%lu@%lu, "
4118 "best %lu/%lu/%lu@%lu cr %d",
4119 (unsigned long)ac->ac_o_ex.fe_group,
4120 (unsigned long)ac->ac_o_ex.fe_start,
4121 (unsigned long)ac->ac_o_ex.fe_len,
4122 (unsigned long)ac->ac_o_ex.fe_logical,
4123 (unsigned long)ac->ac_g_ex.fe_group,
4124 (unsigned long)ac->ac_g_ex.fe_start,
4125 (unsigned long)ac->ac_g_ex.fe_len,
4126 (unsigned long)ac->ac_g_ex.fe_logical,
4127 (unsigned long)ac->ac_b_ex.fe_group,
4128 (unsigned long)ac->ac_b_ex.fe_start,
4129 (unsigned long)ac->ac_b_ex.fe_len,
4130 (unsigned long)ac->ac_b_ex.fe_logical,
4131 (int)ac->ac_criteria);
4132 ext4_msg(ac->ac_sb, KERN_ERR, "%d found", ac->ac_found);
4133 ext4_msg(ac->ac_sb, KERN_ERR, "groups: ");
4134 ngroups = ext4_get_groups_count(sb);
4135 for (i = 0; i < ngroups; i++) {
4136 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4137 struct ext4_prealloc_space *pa;
4138 ext4_grpblk_t start;
4139 struct list_head *cur;
4140 ext4_lock_group(sb, i);
4141 list_for_each(cur, &grp->bb_prealloc_list) {
4142 pa = list_entry(cur, struct ext4_prealloc_space,
4144 spin_lock(&pa->pa_lock);
4145 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4147 spin_unlock(&pa->pa_lock);
4148 printk(KERN_ERR "PA:%u:%d:%u \n", i,
4151 ext4_unlock_group(sb, i);
4153 if (grp->bb_free == 0)
4155 printk(KERN_ERR "%u: %d/%d \n",
4156 i, grp->bb_free, grp->bb_fragments);
4158 printk(KERN_ERR "\n");
4161 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4168 * We use locality group preallocation for small size file. The size of the
4169 * file is determined by the current size or the resulting size after
4170 * allocation which ever is larger
4172 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4174 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4176 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4177 int bsbits = ac->ac_sb->s_blocksize_bits;
4180 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4183 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4186 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
4187 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
4190 if ((size == isize) &&
4191 !ext4_fs_is_busy(sbi) &&
4192 (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
4193 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
4197 if (sbi->s_mb_group_prealloc <= 0) {
4198 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4202 /* don't use group allocation for large files */
4203 size = max(size, isize);
4204 if (size > sbi->s_mb_stream_request) {
4205 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4209 BUG_ON(ac->ac_lg != NULL);
4211 * locality group prealloc space are per cpu. The reason for having
4212 * per cpu locality group is to reduce the contention between block
4213 * request from multiple CPUs.
4215 ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
4217 /* we're going to use group allocation */
4218 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4220 /* serialize all allocations in the group */
4221 mutex_lock(&ac->ac_lg->lg_mutex);
4224 static noinline_for_stack int
4225 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4226 struct ext4_allocation_request *ar)
4228 struct super_block *sb = ar->inode->i_sb;
4229 struct ext4_sb_info *sbi = EXT4_SB(sb);
4230 struct ext4_super_block *es = sbi->s_es;
4234 ext4_grpblk_t block;
4236 /* we can't allocate > group size */
4239 /* just a dirty hack to filter too big requests */
4240 if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
4241 len = EXT4_CLUSTERS_PER_GROUP(sb);
4243 /* start searching from the goal */
4245 if (goal < le32_to_cpu(es->s_first_data_block) ||
4246 goal >= ext4_blocks_count(es))
4247 goal = le32_to_cpu(es->s_first_data_block);
4248 ext4_get_group_no_and_offset(sb, goal, &group, &block);
4250 /* set up allocation goals */
4251 ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
4252 ac->ac_status = AC_STATUS_CONTINUE;
4254 ac->ac_inode = ar->inode;
4255 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4256 ac->ac_o_ex.fe_group = group;
4257 ac->ac_o_ex.fe_start = block;
4258 ac->ac_o_ex.fe_len = len;
4259 ac->ac_g_ex = ac->ac_o_ex;
4260 ac->ac_flags = ar->flags;
4262 /* we have to define context: we'll we work with a file or
4263 * locality group. this is a policy, actually */
4264 ext4_mb_group_or_file(ac);
4266 mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4267 "left: %u/%u, right %u/%u to %swritable\n",
4268 (unsigned) ar->len, (unsigned) ar->logical,
4269 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4270 (unsigned) ar->lleft, (unsigned) ar->pleft,
4271 (unsigned) ar->lright, (unsigned) ar->pright,
4272 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4277 static noinline_for_stack void
4278 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4279 struct ext4_locality_group *lg,
4280 int order, int total_entries)
4282 ext4_group_t group = 0;
4283 struct ext4_buddy e4b;
4284 struct list_head discard_list;
4285 struct ext4_prealloc_space *pa, *tmp;
4287 mb_debug(1, "discard locality group preallocation\n");
4289 INIT_LIST_HEAD(&discard_list);
4291 spin_lock(&lg->lg_prealloc_lock);
4292 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4294 spin_lock(&pa->pa_lock);
4295 if (atomic_read(&pa->pa_count)) {
4297 * This is the pa that we just used
4298 * for block allocation. So don't
4301 spin_unlock(&pa->pa_lock);
4304 if (pa->pa_deleted) {
4305 spin_unlock(&pa->pa_lock);
4308 /* only lg prealloc space */
4309 BUG_ON(pa->pa_type != MB_GROUP_PA);
4311 /* seems this one can be freed ... */
4313 spin_unlock(&pa->pa_lock);
4315 list_del_rcu(&pa->pa_inode_list);
4316 list_add(&pa->u.pa_tmp_list, &discard_list);
4319 if (total_entries <= 5) {
4321 * we want to keep only 5 entries
4322 * allowing it to grow to 8. This
4323 * mak sure we don't call discard
4324 * soon for this list.
4329 spin_unlock(&lg->lg_prealloc_lock);
4331 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4334 group = ext4_get_group_number(sb, pa->pa_pstart);
4335 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4336 GFP_NOFS|__GFP_NOFAIL);
4338 ext4_error(sb, "Error %d loading buddy information for %u",
4342 ext4_lock_group(sb, group);
4343 list_del(&pa->pa_group_list);
4344 ext4_mb_release_group_pa(&e4b, pa);
4345 ext4_unlock_group(sb, group);
4347 ext4_mb_unload_buddy(&e4b);
4348 list_del(&pa->u.pa_tmp_list);
4349 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4354 * We have incremented pa_count. So it cannot be freed at this
4355 * point. Also we hold lg_mutex. So no parallel allocation is
4356 * possible from this lg. That means pa_free cannot be updated.
4358 * A parallel ext4_mb_discard_group_preallocations is possible.
4359 * which can cause the lg_prealloc_list to be updated.
4362 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4364 int order, added = 0, lg_prealloc_count = 1;
4365 struct super_block *sb = ac->ac_sb;
4366 struct ext4_locality_group *lg = ac->ac_lg;
4367 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4369 order = fls(pa->pa_free) - 1;
4370 if (order > PREALLOC_TB_SIZE - 1)
4371 /* The max size of hash table is PREALLOC_TB_SIZE */
4372 order = PREALLOC_TB_SIZE - 1;
4373 /* Add the prealloc space to lg */
4374 spin_lock(&lg->lg_prealloc_lock);
4375 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4377 spin_lock(&tmp_pa->pa_lock);
4378 if (tmp_pa->pa_deleted) {
4379 spin_unlock(&tmp_pa->pa_lock);
4382 if (!added && pa->pa_free < tmp_pa->pa_free) {
4383 /* Add to the tail of the previous entry */
4384 list_add_tail_rcu(&pa->pa_inode_list,
4385 &tmp_pa->pa_inode_list);
4388 * we want to count the total
4389 * number of entries in the list
4392 spin_unlock(&tmp_pa->pa_lock);
4393 lg_prealloc_count++;
4396 list_add_tail_rcu(&pa->pa_inode_list,
4397 &lg->lg_prealloc_list[order]);
4398 spin_unlock(&lg->lg_prealloc_lock);
4400 /* Now trim the list to be not more than 8 elements */
4401 if (lg_prealloc_count > 8) {
4402 ext4_mb_discard_lg_preallocations(sb, lg,
4403 order, lg_prealloc_count);
4410 * release all resource we used in allocation
4412 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4414 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4415 struct ext4_prealloc_space *pa = ac->ac_pa;
4417 if (pa->pa_type == MB_GROUP_PA) {
4418 /* see comment in ext4_mb_use_group_pa() */
4419 spin_lock(&pa->pa_lock);
4420 pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4421 pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4422 pa->pa_free -= ac->ac_b_ex.fe_len;
4423 pa->pa_len -= ac->ac_b_ex.fe_len;
4424 spin_unlock(&pa->pa_lock);
4429 * We want to add the pa to the right bucket.
4430 * Remove it from the list and while adding
4431 * make sure the list to which we are adding
4434 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4435 spin_lock(pa->pa_obj_lock);
4436 list_del_rcu(&pa->pa_inode_list);
4437 spin_unlock(pa->pa_obj_lock);
4438 ext4_mb_add_n_trim(ac);
4440 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4442 if (ac->ac_bitmap_page)
4443 put_page(ac->ac_bitmap_page);
4444 if (ac->ac_buddy_page)
4445 put_page(ac->ac_buddy_page);
4446 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4447 mutex_unlock(&ac->ac_lg->lg_mutex);
4448 ext4_mb_collect_stats(ac);
4452 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4454 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4458 trace_ext4_mb_discard_preallocations(sb, needed);
4459 for (i = 0; i < ngroups && needed > 0; i++) {
4460 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4469 * Main entry point into mballoc to allocate blocks
4470 * it tries to use preallocation first, then falls back
4471 * to usual allocation
4473 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4474 struct ext4_allocation_request *ar, int *errp)
4477 struct ext4_allocation_context *ac = NULL;
4478 struct ext4_sb_info *sbi;
4479 struct super_block *sb;
4480 ext4_fsblk_t block = 0;
4481 unsigned int inquota = 0;
4482 unsigned int reserv_clstrs = 0;
4485 sb = ar->inode->i_sb;
4488 trace_ext4_request_blocks(ar);
4490 /* Allow to use superuser reservation for quota file */
4491 if (IS_NOQUOTA(ar->inode))
4492 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
4494 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
4495 /* Without delayed allocation we need to verify
4496 * there is enough free blocks to do block allocation
4497 * and verify allocation doesn't exceed the quota limits.
4500 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
4502 /* let others to free the space */
4504 ar->len = ar->len >> 1;
4510 reserv_clstrs = ar->len;
4511 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
4512 dquot_alloc_block_nofail(ar->inode,
4513 EXT4_C2B(sbi, ar->len));
4516 dquot_alloc_block(ar->inode,
4517 EXT4_C2B(sbi, ar->len))) {
4519 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4530 ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
4537 *errp = ext4_mb_initialize_context(ac, ar);
4543 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4544 if (!ext4_mb_use_preallocated(ac)) {
4545 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4546 ext4_mb_normalize_request(ac, ar);
4548 /* allocate space in core */
4549 *errp = ext4_mb_regular_allocator(ac);
4551 goto discard_and_exit;
4553 /* as we've just preallocated more space than
4554 * user requested originally, we store allocated
4555 * space in a special descriptor */
4556 if (ac->ac_status == AC_STATUS_FOUND &&
4557 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4558 *errp = ext4_mb_new_preallocation(ac);
4561 ext4_discard_allocated_blocks(ac);
4565 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4566 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4568 ext4_discard_allocated_blocks(ac);
4571 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4572 ar->len = ac->ac_b_ex.fe_len;
4575 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4583 ac->ac_b_ex.fe_len = 0;
4585 ext4_mb_show_ac(ac);
4587 ext4_mb_release_context(ac);
4590 kmem_cache_free(ext4_ac_cachep, ac);
4591 if (inquota && ar->len < inquota)
4592 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
4594 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
4595 /* release all the reserved blocks if non delalloc */
4596 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4600 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4606 * We can merge two free data extents only if the physical blocks
4607 * are contiguous, AND the extents were freed by the same transaction,
4608 * AND the blocks are associated with the same group.
4610 static int can_merge(struct ext4_free_data *entry1,
4611 struct ext4_free_data *entry2)
4613 if ((entry1->efd_tid == entry2->efd_tid) &&
4614 (entry1->efd_group == entry2->efd_group) &&
4615 ((entry1->efd_start_cluster + entry1->efd_count) == entry2->efd_start_cluster))
4620 static noinline_for_stack int
4621 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4622 struct ext4_free_data *new_entry)
4624 ext4_group_t group = e4b->bd_group;
4625 ext4_grpblk_t cluster;
4626 ext4_grpblk_t clusters = new_entry->efd_count;
4627 struct ext4_free_data *entry;
4628 struct ext4_group_info *db = e4b->bd_info;
4629 struct super_block *sb = e4b->bd_sb;
4630 struct ext4_sb_info *sbi = EXT4_SB(sb);
4631 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4632 struct rb_node *parent = NULL, *new_node;
4634 BUG_ON(!ext4_handle_valid(handle));
4635 BUG_ON(e4b->bd_bitmap_page == NULL);
4636 BUG_ON(e4b->bd_buddy_page == NULL);
4638 new_node = &new_entry->efd_node;
4639 cluster = new_entry->efd_start_cluster;
4642 /* first free block exent. We need to
4643 protect buddy cache from being freed,
4644 * otherwise we'll refresh it from
4645 * on-disk bitmap and lose not-yet-available
4647 get_page(e4b->bd_buddy_page);
4648 get_page(e4b->bd_bitmap_page);
4652 entry = rb_entry(parent, struct ext4_free_data, efd_node);
4653 if (cluster < entry->efd_start_cluster)
4655 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
4656 n = &(*n)->rb_right;
4658 ext4_grp_locked_error(sb, group, 0,
4659 ext4_group_first_block_no(sb, group) +
4660 EXT4_C2B(sbi, cluster),
4661 "Block already on to-be-freed list");
4662 kmem_cache_free(ext4_free_data_cachep, new_entry);
4667 rb_link_node(new_node, parent, n);
4668 rb_insert_color(new_node, &db->bb_free_root);
4670 /* Now try to see the extent can be merged to left and right */
4671 node = rb_prev(new_node);
4673 entry = rb_entry(node, struct ext4_free_data, efd_node);
4674 if (can_merge(entry, new_entry) &&
4675 ext4_journal_callback_try_del(handle, &entry->efd_jce)) {
4676 new_entry->efd_start_cluster = entry->efd_start_cluster;
4677 new_entry->efd_count += entry->efd_count;
4678 rb_erase(node, &(db->bb_free_root));
4679 kmem_cache_free(ext4_free_data_cachep, entry);
4683 node = rb_next(new_node);
4685 entry = rb_entry(node, struct ext4_free_data, efd_node);
4686 if (can_merge(new_entry, entry) &&
4687 ext4_journal_callback_try_del(handle, &entry->efd_jce)) {
4688 new_entry->efd_count += entry->efd_count;
4689 rb_erase(node, &(db->bb_free_root));
4690 kmem_cache_free(ext4_free_data_cachep, entry);
4693 /* Add the extent to transaction's private list */
4694 new_entry->efd_jce.jce_func = ext4_free_data_callback;
4695 spin_lock(&sbi->s_md_lock);
4696 _ext4_journal_callback_add(handle, &new_entry->efd_jce);
4697 sbi->s_mb_free_pending += clusters;
4698 spin_unlock(&sbi->s_md_lock);
4703 * ext4_free_blocks() -- Free given blocks and update quota
4704 * @handle: handle for this transaction
4706 * @block: start physical block to free
4707 * @count: number of blocks to count
4708 * @flags: flags used by ext4_free_blocks
4710 void ext4_free_blocks(handle_t *handle, struct inode *inode,
4711 struct buffer_head *bh, ext4_fsblk_t block,
4712 unsigned long count, int flags)
4714 struct buffer_head *bitmap_bh = NULL;
4715 struct super_block *sb = inode->i_sb;
4716 struct ext4_group_desc *gdp;
4717 unsigned int overflow;
4719 struct buffer_head *gd_bh;
4720 ext4_group_t block_group;
4721 struct ext4_sb_info *sbi;
4722 struct ext4_buddy e4b;
4723 unsigned int count_clusters;
4730 BUG_ON(block != bh->b_blocknr);
4732 block = bh->b_blocknr;
4736 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
4737 !ext4_inode_block_valid(inode, block, count)) {
4738 ext4_error(sb, "Freeing blocks not in datazone - "
4739 "block = %llu, count = %lu", block, count);
4743 ext4_debug("freeing block %llu\n", block);
4744 trace_ext4_free_blocks(inode, block, count, flags);
4746 if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4749 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4754 * If the extent to be freed does not begin on a cluster
4755 * boundary, we need to deal with partial clusters at the
4756 * beginning and end of the extent. Normally we will free
4757 * blocks at the beginning or the end unless we are explicitly
4758 * requested to avoid doing so.
4760 overflow = EXT4_PBLK_COFF(sbi, block);
4762 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
4763 overflow = sbi->s_cluster_ratio - overflow;
4765 if (count > overflow)
4774 overflow = EXT4_LBLK_COFF(sbi, count);
4776 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
4777 if (count > overflow)
4782 count += sbi->s_cluster_ratio - overflow;
4785 if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4787 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
4789 for (i = 0; i < count; i++) {
4792 bh = sb_find_get_block(inode->i_sb, block + i);
4793 ext4_forget(handle, is_metadata, inode, bh, block + i);
4799 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4801 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
4802 ext4_get_group_info(sb, block_group))))
4806 * Check to see if we are freeing blocks across a group
4809 if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4810 overflow = EXT4_C2B(sbi, bit) + count -
4811 EXT4_BLOCKS_PER_GROUP(sb);
4814 count_clusters = EXT4_NUM_B2C(sbi, count);
4815 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4816 if (IS_ERR(bitmap_bh)) {
4817 err = PTR_ERR(bitmap_bh);
4821 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4827 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4828 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4829 in_range(block, ext4_inode_table(sb, gdp),
4830 EXT4_SB(sb)->s_itb_per_group) ||
4831 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4832 EXT4_SB(sb)->s_itb_per_group)) {
4834 ext4_error(sb, "Freeing blocks in system zone - "
4835 "Block = %llu, count = %lu", block, count);
4836 /* err = 0. ext4_std_error should be a no op */
4840 BUFFER_TRACE(bitmap_bh, "getting write access");
4841 err = ext4_journal_get_write_access(handle, bitmap_bh);
4846 * We are about to modify some metadata. Call the journal APIs
4847 * to unshare ->b_data if a currently-committing transaction is
4850 BUFFER_TRACE(gd_bh, "get_write_access");
4851 err = ext4_journal_get_write_access(handle, gd_bh);
4854 #ifdef AGGRESSIVE_CHECK
4857 for (i = 0; i < count_clusters; i++)
4858 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4861 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
4863 /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
4864 err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
4865 GFP_NOFS|__GFP_NOFAIL);
4870 * We need to make sure we don't reuse the freed block until after the
4871 * transaction is committed. We make an exception if the inode is to be
4872 * written in writeback mode since writeback mode has weak data
4873 * consistency guarantees.
4875 if (ext4_handle_valid(handle) &&
4876 ((flags & EXT4_FREE_BLOCKS_METADATA) ||
4877 !ext4_should_writeback_data(inode))) {
4878 struct ext4_free_data *new_entry;
4880 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
4883 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
4884 GFP_NOFS|__GFP_NOFAIL);
4885 new_entry->efd_start_cluster = bit;
4886 new_entry->efd_group = block_group;
4887 new_entry->efd_count = count_clusters;
4888 new_entry->efd_tid = handle->h_transaction->t_tid;
4890 ext4_lock_group(sb, block_group);
4891 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4892 ext4_mb_free_metadata(handle, &e4b, new_entry);
4894 /* need to update group_info->bb_free and bitmap
4895 * with group lock held. generate_buddy look at
4896 * them with group lock_held
4898 if (test_opt(sb, DISCARD)) {
4899 err = ext4_issue_discard(sb, block_group, bit, count);
4900 if (err && err != -EOPNOTSUPP)
4901 ext4_msg(sb, KERN_WARNING, "discard request in"
4902 " group:%d block:%d count:%lu failed"
4903 " with %d", block_group, bit, count,
4906 EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
4908 ext4_lock_group(sb, block_group);
4909 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4910 mb_free_blocks(inode, &e4b, bit, count_clusters);
4913 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
4914 ext4_free_group_clusters_set(sb, gdp, ret);
4915 ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
4916 ext4_group_desc_csum_set(sb, block_group, gdp);
4917 ext4_unlock_group(sb, block_group);
4919 if (sbi->s_log_groups_per_flex) {
4920 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4921 atomic64_add(count_clusters,
4922 &sbi_array_rcu_deref(sbi, s_flex_groups,
4923 flex_group)->free_clusters);
4926 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
4927 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
4928 percpu_counter_add(&sbi->s_freeclusters_counter, count_clusters);
4930 ext4_mb_unload_buddy(&e4b);
4932 /* We dirtied the bitmap block */
4933 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4934 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4936 /* And the group descriptor block */
4937 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4938 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4942 if (overflow && !err) {
4950 ext4_std_error(sb, err);
4955 * ext4_group_add_blocks() -- Add given blocks to an existing group
4956 * @handle: handle to this transaction
4958 * @block: start physical block to add to the block group
4959 * @count: number of blocks to free
4961 * This marks the blocks as free in the bitmap and buddy.
4963 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
4964 ext4_fsblk_t block, unsigned long count)
4966 struct buffer_head *bitmap_bh = NULL;
4967 struct buffer_head *gd_bh;
4968 ext4_group_t block_group;
4971 struct ext4_group_desc *desc;
4972 struct ext4_sb_info *sbi = EXT4_SB(sb);
4973 struct ext4_buddy e4b;
4974 int err = 0, ret, blk_free_count;
4975 ext4_grpblk_t blocks_freed;
4977 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
4982 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4984 * Check to see if we are freeing blocks across a group
4987 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4988 ext4_warning(sb, "too much blocks added to group %u",
4994 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4995 if (IS_ERR(bitmap_bh)) {
4996 err = PTR_ERR(bitmap_bh);
5001 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
5007 if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
5008 in_range(ext4_inode_bitmap(sb, desc), block, count) ||
5009 in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
5010 in_range(block + count - 1, ext4_inode_table(sb, desc),
5011 sbi->s_itb_per_group)) {
5012 ext4_error(sb, "Adding blocks in system zones - "
5013 "Block = %llu, count = %lu",
5019 BUFFER_TRACE(bitmap_bh, "getting write access");
5020 err = ext4_journal_get_write_access(handle, bitmap_bh);
5025 * We are about to modify some metadata. Call the journal APIs
5026 * to unshare ->b_data if a currently-committing transaction is
5029 BUFFER_TRACE(gd_bh, "get_write_access");
5030 err = ext4_journal_get_write_access(handle, gd_bh);
5034 for (i = 0, blocks_freed = 0; i < count; i++) {
5035 BUFFER_TRACE(bitmap_bh, "clear bit");
5036 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
5037 ext4_error(sb, "bit already cleared for block %llu",
5038 (ext4_fsblk_t)(block + i));
5039 BUFFER_TRACE(bitmap_bh, "bit already cleared");
5045 err = ext4_mb_load_buddy(sb, block_group, &e4b);
5050 * need to update group_info->bb_free and bitmap
5051 * with group lock held. generate_buddy look at
5052 * them with group lock_held
5054 ext4_lock_group(sb, block_group);
5055 mb_clear_bits(bitmap_bh->b_data, bit, count);
5056 mb_free_blocks(NULL, &e4b, bit, count);
5057 blk_free_count = blocks_freed + ext4_free_group_clusters(sb, desc);
5058 ext4_free_group_clusters_set(sb, desc, blk_free_count);
5059 ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
5060 ext4_group_desc_csum_set(sb, block_group, desc);
5061 ext4_unlock_group(sb, block_group);
5062 percpu_counter_add(&sbi->s_freeclusters_counter,
5063 EXT4_NUM_B2C(sbi, blocks_freed));
5065 if (sbi->s_log_groups_per_flex) {
5066 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5067 atomic64_add(EXT4_NUM_B2C(sbi, blocks_freed),
5068 &sbi_array_rcu_deref(sbi, s_flex_groups,
5069 flex_group)->free_clusters);
5072 ext4_mb_unload_buddy(&e4b);
5074 /* We dirtied the bitmap block */
5075 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5076 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5078 /* And the group descriptor block */
5079 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5080 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5086 ext4_std_error(sb, err);
5091 * ext4_trim_extent -- function to TRIM one single free extent in the group
5092 * @sb: super block for the file system
5093 * @start: starting block of the free extent in the alloc. group
5094 * @count: number of blocks to TRIM
5095 * @group: alloc. group we are working with
5096 * @e4b: ext4 buddy for the group
5098 * Trim "count" blocks starting at "start" in the "group". To assure that no
5099 * one will allocate those blocks, mark it as used in buddy bitmap. This must
5100 * be called with under the group lock.
5102 static int ext4_trim_extent(struct super_block *sb, int start, int count,
5103 ext4_group_t group, struct ext4_buddy *e4b)
5107 struct ext4_free_extent ex;
5110 trace_ext4_trim_extent(sb, group, start, count);
5112 assert_spin_locked(ext4_group_lock_ptr(sb, group));
5114 ex.fe_start = start;
5115 ex.fe_group = group;
5119 * Mark blocks used, so no one can reuse them while
5122 mb_mark_used(e4b, &ex);
5123 ext4_unlock_group(sb, group);
5124 ret = ext4_issue_discard(sb, group, start, count);
5125 ext4_lock_group(sb, group);
5126 mb_free_blocks(NULL, e4b, start, ex.fe_len);
5131 * ext4_trim_all_free -- function to trim all free space in alloc. group
5132 * @sb: super block for file system
5133 * @group: group to be trimmed
5134 * @start: first group block to examine
5135 * @max: last group block to examine
5136 * @minblocks: minimum extent block count
5138 * ext4_trim_all_free walks through group's buddy bitmap searching for free
5139 * extents. When the free block is found, ext4_trim_extent is called to TRIM
5143 * ext4_trim_all_free walks through group's block bitmap searching for free
5144 * extents. When the free extent is found, mark it as used in group buddy
5145 * bitmap. Then issue a TRIM command on this extent and free the extent in
5146 * the group buddy bitmap. This is done until whole group is scanned.
5148 static ext4_grpblk_t
5149 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
5150 ext4_grpblk_t start, ext4_grpblk_t max,
5151 ext4_grpblk_t minblocks)
5154 ext4_grpblk_t next, count = 0, free_count = 0;
5155 struct ext4_buddy e4b;
5158 trace_ext4_trim_all_free(sb, group, start, max);
5160 ret = ext4_mb_load_buddy(sb, group, &e4b);
5162 ext4_warning(sb, "Error %d loading buddy information for %u",
5166 bitmap = e4b.bd_bitmap;
5168 ext4_lock_group(sb, group);
5169 if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
5170 minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
5173 start = (e4b.bd_info->bb_first_free > start) ?
5174 e4b.bd_info->bb_first_free : start;
5176 while (start <= max) {
5177 start = mb_find_next_zero_bit(bitmap, max + 1, start);
5180 next = mb_find_next_bit(bitmap, max + 1, start);
5182 if ((next - start) >= minblocks) {
5183 ret = ext4_trim_extent(sb, start,
5184 next - start, group, &e4b);
5185 if (ret && ret != -EOPNOTSUPP)
5188 count += next - start;
5190 free_count += next - start;
5193 if (fatal_signal_pending(current)) {
5194 count = -ERESTARTSYS;
5198 if (need_resched()) {
5199 ext4_unlock_group(sb, group);
5201 ext4_lock_group(sb, group);
5204 if ((e4b.bd_info->bb_free - free_count) < minblocks)
5210 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
5213 ext4_unlock_group(sb, group);
5214 ext4_mb_unload_buddy(&e4b);
5216 ext4_debug("trimmed %d blocks in the group %d\n",
5223 * ext4_trim_fs() -- trim ioctl handle function
5224 * @sb: superblock for filesystem
5225 * @range: fstrim_range structure
5227 * start: First Byte to trim
5228 * len: number of Bytes to trim from start
5229 * minlen: minimum extent length in Bytes
5230 * ext4_trim_fs goes through all allocation groups containing Bytes from
5231 * start to start+len. For each such a group ext4_trim_all_free function
5232 * is invoked to trim all free space.
5234 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
5236 struct request_queue *q = bdev_get_queue(sb->s_bdev);
5237 struct ext4_group_info *grp;
5238 ext4_group_t group, first_group, last_group;
5239 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5240 uint64_t start, end, minlen, trimmed = 0;
5241 ext4_fsblk_t first_data_blk =
5242 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5243 ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
5246 start = range->start >> sb->s_blocksize_bits;
5247 end = start + (range->len >> sb->s_blocksize_bits) - 1;
5248 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5249 range->minlen >> sb->s_blocksize_bits);
5251 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
5252 start >= max_blks ||
5253 range->len < sb->s_blocksize)
5255 /* No point to try to trim less than discard granularity */
5256 if (range->minlen < q->limits.discard_granularity) {
5257 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5258 q->limits.discard_granularity >> sb->s_blocksize_bits);
5259 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
5262 if (end >= max_blks)
5264 if (end <= first_data_blk)
5266 if (start < first_data_blk)
5267 start = first_data_blk;
5269 /* Determine first and last group to examine based on start and end */
5270 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
5271 &first_group, &first_cluster);
5272 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
5273 &last_group, &last_cluster);
5275 /* end now represents the last cluster to discard in this group */
5276 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5278 for (group = first_group; group <= last_group; group++) {
5279 grp = ext4_get_group_info(sb, group);
5280 /* We only do this if the grp has never been initialized */
5281 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
5282 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
5288 * For all the groups except the last one, last cluster will
5289 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
5290 * change it for the last group, note that last_cluster is
5291 * already computed earlier by ext4_get_group_no_and_offset()
5293 if (group == last_group)
5296 if (grp->bb_free >= minlen) {
5297 cnt = ext4_trim_all_free(sb, group, first_cluster,
5307 * For every group except the first one, we are sure
5308 * that the first cluster to discard will be cluster #0.
5314 atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
5317 range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;