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 Licens
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
25 #include <linux/debugfs.h>
26 #include <linux/slab.h>
27 #include <trace/events/ext4.h>
31 * - test ext4_ext_search_left() and ext4_ext_search_right()
32 * - search for metadata in few groups
35 * - normalization should take into account whether file is still open
36 * - discard preallocations if no free space left (policy?)
37 * - don't normalize tails
39 * - reservation for superuser
42 * - bitmap read-ahead (proposed by Oleg Drokin aka green)
43 * - track min/max extents in each group for better group selection
44 * - mb_mark_used() may allocate chunk right after splitting buddy
45 * - tree of groups sorted by number of free blocks
50 * The allocation request involve request for multiple number of blocks
51 * near to the goal(block) value specified.
53 * During initialization phase of the allocator we decide to use the
54 * group preallocation or inode preallocation depending on the size of
55 * the file. The size of the file could be the resulting file size we
56 * would have after allocation, or the current file size, which ever
57 * is larger. If the size is less than sbi->s_mb_stream_request we
58 * select to use the group preallocation. The default value of
59 * s_mb_stream_request is 16 blocks. This can also be tuned via
60 * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
61 * terms of number of blocks.
63 * The main motivation for having small file use group preallocation is to
64 * ensure that we have small files closer together on the disk.
66 * First stage the allocator looks at the inode prealloc list,
67 * ext4_inode_info->i_prealloc_list, which contains list of prealloc
68 * spaces for this particular inode. The inode prealloc space is
71 * pa_lstart -> the logical start block for this prealloc space
72 * pa_pstart -> the physical start block for this prealloc space
73 * pa_len -> length for this prealloc space (in clusters)
74 * pa_free -> free space available in this prealloc space (in clusters)
76 * The inode preallocation space is used looking at the _logical_ start
77 * block. If only the logical file block falls within the range of prealloc
78 * space we will consume the particular prealloc space. This makes sure that
79 * we have contiguous physical blocks representing the file blocks
81 * The important thing to be noted in case of inode prealloc space is that
82 * we don't modify the values associated to inode prealloc space except
85 * If we are not able to find blocks in the inode prealloc space and if we
86 * have the group allocation flag set then we look at the locality group
87 * prealloc space. These are per CPU prealloc list represented as
89 * ext4_sb_info.s_locality_groups[smp_processor_id()]
91 * The reason for having a per cpu locality group is to reduce the contention
92 * between CPUs. It is possible to get scheduled at this point.
94 * The locality group prealloc space is used looking at whether we have
95 * enough free space (pa_free) within the prealloc space.
97 * If we can't allocate blocks via inode prealloc or/and locality group
98 * prealloc then we look at the buddy cache. The buddy cache is represented
99 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
100 * mapped to the buddy and bitmap information regarding different
101 * groups. The buddy information is attached to buddy cache inode so that
102 * we can access them through the page cache. The information regarding
103 * each group is loaded via ext4_mb_load_buddy. The information involve
104 * block bitmap and buddy information. The information are stored in the
108 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
111 * one block each for bitmap and buddy information. So for each group we
112 * take up 2 blocks. A page can contain blocks_per_page (PAGE_CACHE_SIZE /
113 * blocksize) blocks. So it can have information regarding groups_per_page
114 * which is blocks_per_page/2
116 * The buddy cache inode is not stored on disk. The inode is thrown
117 * away when the filesystem is unmounted.
119 * We look for count number of blocks in the buddy cache. If we were able
120 * to locate that many free blocks we return with additional information
121 * regarding rest of the contiguous physical block available
123 * Before allocating blocks via buddy cache we normalize the request
124 * blocks. This ensure we ask for more blocks that we needed. The extra
125 * blocks that we get after allocation is added to the respective prealloc
126 * list. In case of inode preallocation we follow a list of heuristics
127 * based on file size. This can be found in ext4_mb_normalize_request. If
128 * we are doing a group prealloc we try to normalize the request to
129 * sbi->s_mb_group_prealloc. The default value of s_mb_group_prealloc is
130 * dependent on the cluster size; for non-bigalloc file systems, it is
131 * 512 blocks. This can be tuned via
132 * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
133 * terms of number of blocks. If we have mounted the file system with -O
134 * stripe=<value> option the group prealloc request is normalized to the
135 * the smallest multiple of the stripe value (sbi->s_stripe) which is
136 * greater than the default mb_group_prealloc.
138 * The regular allocator (using the buddy cache) supports a few tunables.
140 * /sys/fs/ext4/<partition>/mb_min_to_scan
141 * /sys/fs/ext4/<partition>/mb_max_to_scan
142 * /sys/fs/ext4/<partition>/mb_order2_req
144 * The regular allocator uses buddy scan only if the request len is power of
145 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
146 * value of s_mb_order2_reqs can be tuned via
147 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
148 * stripe size (sbi->s_stripe), we try to search for contiguous block in
149 * stripe size. This should result in better allocation on RAID setups. If
150 * not, we search in the specific group using bitmap for best extents. The
151 * tunable min_to_scan and max_to_scan control the behaviour here.
152 * min_to_scan indicate how long the mballoc __must__ look for a best
153 * extent and max_to_scan indicates how long the mballoc __can__ look for a
154 * best extent in the found extents. Searching for the blocks starts with
155 * the group specified as the goal value in allocation context via
156 * ac_g_ex. Each group is first checked based on the criteria whether it
157 * can be used for allocation. ext4_mb_good_group explains how the groups are
160 * Both the prealloc space are getting populated as above. So for the first
161 * request we will hit the buddy cache which will result in this prealloc
162 * space getting filled. The prealloc space is then later used for the
163 * subsequent request.
167 * mballoc operates on the following data:
169 * - in-core buddy (actually includes buddy and bitmap)
170 * - preallocation descriptors (PAs)
172 * there are two types of preallocations:
174 * assiged to specific inode and can be used for this inode only.
175 * it describes part of inode's space preallocated to specific
176 * physical blocks. any block from that preallocated can be used
177 * independent. the descriptor just tracks number of blocks left
178 * unused. so, before taking some block from descriptor, one must
179 * make sure corresponded logical block isn't allocated yet. this
180 * also means that freeing any block within descriptor's range
181 * must discard all preallocated blocks.
183 * assigned to specific locality group which does not translate to
184 * permanent set of inodes: inode can join and leave group. space
185 * from this type of preallocation can be used for any inode. thus
186 * it's consumed from the beginning to the end.
188 * relation between them can be expressed as:
189 * in-core buddy = on-disk bitmap + preallocation descriptors
191 * this mean blocks mballoc considers used are:
192 * - allocated blocks (persistent)
193 * - preallocated blocks (non-persistent)
195 * consistency in mballoc world means that at any time a block is either
196 * free or used in ALL structures. notice: "any time" should not be read
197 * literally -- time is discrete and delimited by locks.
199 * to keep it simple, we don't use block numbers, instead we count number of
200 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
202 * all operations can be expressed as:
203 * - init buddy: buddy = on-disk + PAs
204 * - new PA: buddy += N; PA = N
205 * - use inode PA: on-disk += N; PA -= N
206 * - discard inode PA buddy -= on-disk - PA; PA = 0
207 * - use locality group PA on-disk += N; PA -= N
208 * - discard locality group PA buddy -= PA; PA = 0
209 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
210 * is used in real operation because we can't know actual used
211 * bits from PA, only from on-disk bitmap
213 * if we follow this strict logic, then all operations above should be atomic.
214 * given some of them can block, we'd have to use something like semaphores
215 * killing performance on high-end SMP hardware. let's try to relax it using
216 * the following knowledge:
217 * 1) if buddy is referenced, it's already initialized
218 * 2) while block is used in buddy and the buddy is referenced,
219 * nobody can re-allocate that block
220 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
221 * bit set and PA claims same block, it's OK. IOW, one can set bit in
222 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
225 * so, now we're building a concurrency table:
228 * blocks for PA are allocated in the buddy, buddy must be referenced
229 * until PA is linked to allocation group to avoid concurrent buddy init
231 * we need to make sure that either on-disk bitmap or PA has uptodate data
232 * given (3) we care that PA-=N operation doesn't interfere with init
234 * the simplest way would be to have buddy initialized by the discard
235 * - use locality group PA
236 * again PA-=N must be serialized with init
237 * - discard locality group PA
238 * the simplest way would be to have buddy initialized by the discard
241 * i_data_sem serializes them
243 * discard process must wait until PA isn't used by another process
244 * - use locality group PA
245 * some mutex should serialize them
246 * - discard locality group PA
247 * discard process must wait until PA isn't used by another process
250 * i_data_sem or another mutex should serializes them
252 * discard process must wait until PA isn't used by another process
253 * - use locality group PA
254 * nothing wrong here -- they're different PAs covering different blocks
255 * - discard locality group PA
256 * discard process must wait until PA isn't used by another process
258 * now we're ready to make few consequences:
259 * - PA is referenced and while it is no discard is possible
260 * - PA is referenced until block isn't marked in on-disk bitmap
261 * - PA changes only after on-disk bitmap
262 * - discard must not compete with init. either init is done before
263 * any discard or they're serialized somehow
264 * - buddy init as sum of on-disk bitmap and PAs is done atomically
266 * a special case when we've used PA to emptiness. no need to modify buddy
267 * in this case, but we should care about concurrent init
272 * Logic in few words:
277 * mark bits in on-disk bitmap
280 * - use preallocation:
281 * find proper PA (per-inode or group)
283 * mark bits in on-disk bitmap
289 * mark bits in on-disk bitmap
292 * - discard preallocations in group:
294 * move them onto local list
295 * load on-disk bitmap
297 * remove PA from object (inode or locality group)
298 * mark free blocks in-core
300 * - discard inode's preallocations:
307 * - bitlock on a group (group)
308 * - object (inode/locality) (object)
319 * - release consumed pa:
324 * - generate in-core bitmap:
328 * - discard all for given object (inode, locality group):
333 * - discard all for given group:
340 static struct kmem_cache *ext4_pspace_cachep;
341 static struct kmem_cache *ext4_ac_cachep;
342 static struct kmem_cache *ext4_free_ext_cachep;
344 /* We create slab caches for groupinfo data structures based on the
345 * superblock block size. There will be one per mounted filesystem for
346 * each unique s_blocksize_bits */
347 #define NR_GRPINFO_CACHES 8
348 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
350 static const char *ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
351 "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
352 "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
353 "ext4_groupinfo_64k", "ext4_groupinfo_128k"
356 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
358 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
360 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn);
362 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
364 #if BITS_PER_LONG == 64
365 *bit += ((unsigned long) addr & 7UL) << 3;
366 addr = (void *) ((unsigned long) addr & ~7UL);
367 #elif BITS_PER_LONG == 32
368 *bit += ((unsigned long) addr & 3UL) << 3;
369 addr = (void *) ((unsigned long) addr & ~3UL);
371 #error "how many bits you are?!"
376 static inline int mb_test_bit(int bit, void *addr)
379 * ext4_test_bit on architecture like powerpc
380 * needs unsigned long aligned address
382 addr = mb_correct_addr_and_bit(&bit, addr);
383 return ext4_test_bit(bit, addr);
386 static inline void mb_set_bit(int bit, void *addr)
388 addr = mb_correct_addr_and_bit(&bit, addr);
389 ext4_set_bit(bit, addr);
392 static inline void mb_clear_bit(int bit, void *addr)
394 addr = mb_correct_addr_and_bit(&bit, addr);
395 ext4_clear_bit(bit, addr);
398 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
400 int fix = 0, ret, tmpmax;
401 addr = mb_correct_addr_and_bit(&fix, addr);
405 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
411 static inline int mb_find_next_bit(void *addr, int max, int start)
413 int fix = 0, ret, tmpmax;
414 addr = mb_correct_addr_and_bit(&fix, addr);
418 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
424 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
428 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
431 if (order > e4b->bd_blkbits + 1) {
436 /* at order 0 we see each particular block */
438 *max = 1 << (e4b->bd_blkbits + 3);
439 return EXT4_MB_BITMAP(e4b);
442 bb = EXT4_MB_BUDDY(e4b) + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
443 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
449 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
450 int first, int count)
453 struct super_block *sb = e4b->bd_sb;
455 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
457 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
458 for (i = 0; i < count; i++) {
459 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
460 ext4_fsblk_t blocknr;
462 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
463 blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
464 ext4_grp_locked_error(sb, e4b->bd_group,
465 inode ? inode->i_ino : 0,
467 "freeing block already freed "
471 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
475 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
479 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
481 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
482 for (i = 0; i < count; i++) {
483 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
484 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
488 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
490 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
491 unsigned char *b1, *b2;
493 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
494 b2 = (unsigned char *) bitmap;
495 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
496 if (b1[i] != b2[i]) {
497 ext4_msg(e4b->bd_sb, KERN_ERR,
498 "corruption in group %u "
499 "at byte %u(%u): %x in copy != %x "
501 e4b->bd_group, i, i * 8, b1[i], b2[i]);
509 static inline void mb_free_blocks_double(struct inode *inode,
510 struct ext4_buddy *e4b, int first, int count)
514 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
515 int first, int count)
519 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
525 #ifdef AGGRESSIVE_CHECK
527 #define MB_CHECK_ASSERT(assert) \
531 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
532 function, file, line, # assert); \
537 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
538 const char *function, int line)
540 struct super_block *sb = e4b->bd_sb;
541 int order = e4b->bd_blkbits + 1;
548 struct ext4_group_info *grp;
551 struct list_head *cur;
556 static int mb_check_counter;
557 if (mb_check_counter++ % 100 != 0)
562 buddy = mb_find_buddy(e4b, order, &max);
563 MB_CHECK_ASSERT(buddy);
564 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
565 MB_CHECK_ASSERT(buddy2);
566 MB_CHECK_ASSERT(buddy != buddy2);
567 MB_CHECK_ASSERT(max * 2 == max2);
570 for (i = 0; i < max; i++) {
572 if (mb_test_bit(i, buddy)) {
573 /* only single bit in buddy2 may be 1 */
574 if (!mb_test_bit(i << 1, buddy2)) {
576 mb_test_bit((i<<1)+1, buddy2));
577 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
579 mb_test_bit(i << 1, buddy2));
584 /* both bits in buddy2 must be 1 */
585 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
586 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
588 for (j = 0; j < (1 << order); j++) {
589 k = (i * (1 << order)) + j;
591 !mb_test_bit(k, EXT4_MB_BITMAP(e4b)));
595 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
600 buddy = mb_find_buddy(e4b, 0, &max);
601 for (i = 0; i < max; i++) {
602 if (!mb_test_bit(i, buddy)) {
603 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
611 /* check used bits only */
612 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
613 buddy2 = mb_find_buddy(e4b, j, &max2);
615 MB_CHECK_ASSERT(k < max2);
616 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
619 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
620 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
622 grp = ext4_get_group_info(sb, e4b->bd_group);
623 list_for_each(cur, &grp->bb_prealloc_list) {
624 ext4_group_t groupnr;
625 struct ext4_prealloc_space *pa;
626 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
627 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
628 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
629 for (i = 0; i < pa->pa_len; i++)
630 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
634 #undef MB_CHECK_ASSERT
635 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
636 __FILE__, __func__, __LINE__)
638 #define mb_check_buddy(e4b)
642 * Divide blocks started from @first with length @len into
643 * smaller chunks with power of 2 blocks.
644 * Clear the bits in bitmap which the blocks of the chunk(s) covered,
645 * then increase bb_counters[] for corresponded chunk size.
647 static void ext4_mb_mark_free_simple(struct super_block *sb,
648 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
649 struct ext4_group_info *grp)
651 struct ext4_sb_info *sbi = EXT4_SB(sb);
655 unsigned short border;
657 BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
659 border = 2 << sb->s_blocksize_bits;
662 /* find how many blocks can be covered since this position */
663 max = ffs(first | border) - 1;
665 /* find how many blocks of power 2 we need to mark */
672 /* mark multiblock chunks only */
673 grp->bb_counters[min]++;
675 mb_clear_bit(first >> min,
676 buddy + sbi->s_mb_offsets[min]);
684 * Cache the order of the largest free extent we have available in this block
688 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
693 grp->bb_largest_free_order = -1; /* uninit */
695 bits = sb->s_blocksize_bits + 1;
696 for (i = bits; i >= 0; i--) {
697 if (grp->bb_counters[i] > 0) {
698 grp->bb_largest_free_order = i;
704 static noinline_for_stack
705 void ext4_mb_generate_buddy(struct super_block *sb,
706 void *buddy, void *bitmap, ext4_group_t group)
708 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
709 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
714 unsigned fragments = 0;
715 unsigned long long period = get_cycles();
717 /* initialize buddy from bitmap which is aggregation
718 * of on-disk bitmap and preallocations */
719 i = mb_find_next_zero_bit(bitmap, max, 0);
720 grp->bb_first_free = i;
724 i = mb_find_next_bit(bitmap, max, i);
728 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
730 grp->bb_counters[0]++;
732 i = mb_find_next_zero_bit(bitmap, max, i);
734 grp->bb_fragments = fragments;
736 if (free != grp->bb_free) {
737 ext4_grp_locked_error(sb, group, 0, 0,
738 "%u clusters in bitmap, %u in gd",
741 * If we intent to continue, we consider group descritor
742 * corrupt and update bb_free using bitmap value
746 mb_set_largest_free_order(sb, grp);
748 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
750 period = get_cycles() - period;
751 spin_lock(&EXT4_SB(sb)->s_bal_lock);
752 EXT4_SB(sb)->s_mb_buddies_generated++;
753 EXT4_SB(sb)->s_mb_generation_time += period;
754 spin_unlock(&EXT4_SB(sb)->s_bal_lock);
757 /* The buddy information is attached the buddy cache inode
758 * for convenience. The information regarding each group
759 * is loaded via ext4_mb_load_buddy. The information involve
760 * block bitmap and buddy information. The information are
761 * stored in the inode as
764 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
767 * one block each for bitmap and buddy information.
768 * So for each group we take up 2 blocks. A page can
769 * contain blocks_per_page (PAGE_CACHE_SIZE / blocksize) blocks.
770 * So it can have information regarding groups_per_page which
771 * is blocks_per_page/2
773 * Locking note: This routine takes the block group lock of all groups
774 * for this page; do not hold this lock when calling this routine!
777 static int ext4_mb_init_cache(struct page *page, char *incore)
779 ext4_group_t ngroups;
785 ext4_group_t first_group;
787 struct super_block *sb;
788 struct buffer_head *bhs;
789 struct buffer_head **bh;
793 struct ext4_group_info *grinfo;
795 mb_debug(1, "init page %lu\n", page->index);
797 inode = page->mapping->host;
799 ngroups = ext4_get_groups_count(sb);
800 blocksize = 1 << inode->i_blkbits;
801 blocks_per_page = PAGE_CACHE_SIZE / blocksize;
803 groups_per_page = blocks_per_page >> 1;
804 if (groups_per_page == 0)
807 /* allocate buffer_heads to read bitmaps */
808 if (groups_per_page > 1) {
810 i = sizeof(struct buffer_head *) * groups_per_page;
811 bh = kzalloc(i, GFP_NOFS);
817 first_group = page->index * blocks_per_page / 2;
819 /* read all groups the page covers into the cache */
820 for (i = 0; i < groups_per_page; i++) {
821 struct ext4_group_desc *desc;
823 if (first_group + i >= ngroups)
826 grinfo = ext4_get_group_info(sb, first_group + i);
828 * If page is uptodate then we came here after online resize
829 * which added some new uninitialized group info structs, so
830 * we must skip all initialized uptodate buddies on the page,
831 * which may be currently in use by an allocating task.
833 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
839 desc = ext4_get_group_desc(sb, first_group + i, NULL);
844 bh[i] = sb_getblk(sb, ext4_block_bitmap(sb, desc));
848 if (bitmap_uptodate(bh[i]))
852 if (bitmap_uptodate(bh[i])) {
853 unlock_buffer(bh[i]);
856 ext4_lock_group(sb, first_group + i);
857 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
858 ext4_init_block_bitmap(sb, bh[i],
859 first_group + i, desc);
860 set_bitmap_uptodate(bh[i]);
861 set_buffer_uptodate(bh[i]);
862 ext4_unlock_group(sb, first_group + i);
863 unlock_buffer(bh[i]);
866 ext4_unlock_group(sb, first_group + i);
867 if (buffer_uptodate(bh[i])) {
869 * if not uninit if bh is uptodate,
870 * bitmap is also uptodate
872 set_bitmap_uptodate(bh[i]);
873 unlock_buffer(bh[i]);
878 * submit the buffer_head for read. We can
879 * safely mark the bitmap as uptodate now.
880 * We do it here so the bitmap uptodate bit
881 * get set with buffer lock held.
883 set_bitmap_uptodate(bh[i]);
884 bh[i]->b_end_io = end_buffer_read_sync;
885 submit_bh(READ, bh[i]);
886 mb_debug(1, "read bitmap for group %u\n", first_group + i);
889 /* wait for I/O completion */
890 for (i = 0; i < groups_per_page; i++)
892 wait_on_buffer(bh[i]);
895 for (i = 0; i < groups_per_page; i++)
896 if (bh[i] && !buffer_uptodate(bh[i]))
900 first_block = page->index * blocks_per_page;
901 for (i = 0; i < blocks_per_page; i++) {
904 group = (first_block + i) >> 1;
905 if (group >= ngroups)
908 if (!bh[group - first_group])
909 /* skip initialized uptodate buddy */
913 * data carry information regarding this
914 * particular group in the format specified
918 data = page_address(page) + (i * blocksize);
919 bitmap = bh[group - first_group]->b_data;
922 * We place the buddy block and bitmap block
925 if ((first_block + i) & 1) {
926 /* this is block of buddy */
927 BUG_ON(incore == NULL);
928 mb_debug(1, "put buddy for group %u in page %lu/%x\n",
929 group, page->index, i * blocksize);
930 trace_ext4_mb_buddy_bitmap_load(sb, group);
931 grinfo = ext4_get_group_info(sb, group);
932 grinfo->bb_fragments = 0;
933 memset(grinfo->bb_counters, 0,
934 sizeof(*grinfo->bb_counters) *
935 (sb->s_blocksize_bits+2));
937 * incore got set to the group block bitmap below
939 ext4_lock_group(sb, group);
941 memset(data, 0xff, blocksize);
942 ext4_mb_generate_buddy(sb, data, incore, group);
943 ext4_unlock_group(sb, group);
946 /* this is block of bitmap */
947 BUG_ON(incore != NULL);
948 mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
949 group, page->index, i * blocksize);
950 trace_ext4_mb_bitmap_load(sb, group);
952 /* see comments in ext4_mb_put_pa() */
953 ext4_lock_group(sb, group);
954 memcpy(data, bitmap, blocksize);
956 /* mark all preallocated blks used in in-core bitmap */
957 ext4_mb_generate_from_pa(sb, data, group);
958 ext4_mb_generate_from_freelist(sb, data, group);
959 ext4_unlock_group(sb, group);
961 /* set incore so that the buddy information can be
962 * generated using this
967 SetPageUptodate(page);
971 for (i = 0; i < groups_per_page; i++)
980 * Lock the buddy and bitmap pages. This make sure other parallel init_group
981 * on the same buddy page doesn't happen whild holding the buddy page lock.
982 * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
983 * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
985 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
986 ext4_group_t group, struct ext4_buddy *e4b)
988 struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
989 int block, pnum, poff;
993 e4b->bd_buddy_page = NULL;
994 e4b->bd_bitmap_page = NULL;
996 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
998 * the buddy cache inode stores the block bitmap
999 * and buddy information in consecutive blocks.
1000 * So for each group we need two blocks.
1003 pnum = block / blocks_per_page;
1004 poff = block % blocks_per_page;
1005 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1008 BUG_ON(page->mapping != inode->i_mapping);
1009 e4b->bd_bitmap_page = page;
1010 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1012 if (blocks_per_page >= 2) {
1013 /* buddy and bitmap are on the same page */
1018 pnum = block / blocks_per_page;
1019 poff = block % blocks_per_page;
1020 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
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 page_cache_release(e4b->bd_bitmap_page);
1034 if (e4b->bd_buddy_page) {
1035 unlock_page(e4b->bd_buddy_page);
1036 page_cache_release(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)
1049 struct ext4_group_info *this_grp;
1050 struct ext4_buddy e4b;
1054 mb_debug(1, "init group %u\n", group);
1055 this_grp = ext4_get_group_info(sb, group);
1057 * This ensures that we don't reinit the buddy cache
1058 * page which map to the group from which we are already
1059 * allocating. If we are looking at the buddy cache we would
1060 * have taken a reference using ext4_mb_load_buddy and that
1061 * would have pinned buddy page to page cache.
1063 ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b);
1064 if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1066 * somebody initialized the group
1067 * return without doing anything
1072 page = e4b.bd_bitmap_page;
1073 ret = ext4_mb_init_cache(page, NULL);
1076 if (!PageUptodate(page)) {
1080 mark_page_accessed(page);
1082 if (e4b.bd_buddy_page == NULL) {
1084 * If both the bitmap and buddy are in
1085 * the same page we don't need to force
1091 /* init buddy cache */
1092 page = e4b.bd_buddy_page;
1093 ret = ext4_mb_init_cache(page, e4b.bd_bitmap);
1096 if (!PageUptodate(page)) {
1100 mark_page_accessed(page);
1102 ext4_mb_put_buddy_page_lock(&e4b);
1107 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1108 * block group lock of all groups for this page; do not hold the BG lock when
1109 * calling this routine!
1111 static noinline_for_stack int
1112 ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1113 struct ext4_buddy *e4b)
1115 int blocks_per_page;
1121 struct ext4_group_info *grp;
1122 struct ext4_sb_info *sbi = EXT4_SB(sb);
1123 struct inode *inode = sbi->s_buddy_cache;
1125 mb_debug(1, "load group %u\n", group);
1127 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1128 grp = ext4_get_group_info(sb, group);
1130 e4b->bd_blkbits = sb->s_blocksize_bits;
1133 e4b->bd_group = group;
1134 e4b->bd_buddy_page = NULL;
1135 e4b->bd_bitmap_page = NULL;
1137 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1139 * we need full data about the group
1140 * to make a good selection
1142 ret = ext4_mb_init_group(sb, group);
1148 * the buddy cache inode stores the block bitmap
1149 * and buddy information in consecutive blocks.
1150 * So for each group we need two blocks.
1153 pnum = block / blocks_per_page;
1154 poff = block % blocks_per_page;
1156 /* we could use find_or_create_page(), but it locks page
1157 * what we'd like to avoid in fast path ... */
1158 page = find_get_page(inode->i_mapping, pnum);
1159 if (page == NULL || !PageUptodate(page)) {
1162 * drop the page reference and try
1163 * to get the page with lock. If we
1164 * are not uptodate that implies
1165 * somebody just created the page but
1166 * is yet to initialize the same. So
1167 * wait for it to initialize.
1169 page_cache_release(page);
1170 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1172 BUG_ON(page->mapping != inode->i_mapping);
1173 if (!PageUptodate(page)) {
1174 ret = ext4_mb_init_cache(page, NULL);
1179 mb_cmp_bitmaps(e4b, page_address(page) +
1180 (poff * sb->s_blocksize));
1185 if (page == NULL || !PageUptodate(page)) {
1189 e4b->bd_bitmap_page = page;
1190 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1191 mark_page_accessed(page);
1194 pnum = block / blocks_per_page;
1195 poff = block % blocks_per_page;
1197 page = find_get_page(inode->i_mapping, pnum);
1198 if (page == NULL || !PageUptodate(page)) {
1200 page_cache_release(page);
1201 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1203 BUG_ON(page->mapping != inode->i_mapping);
1204 if (!PageUptodate(page)) {
1205 ret = ext4_mb_init_cache(page, e4b->bd_bitmap);
1214 if (page == NULL || !PageUptodate(page)) {
1218 e4b->bd_buddy_page = page;
1219 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1220 mark_page_accessed(page);
1222 BUG_ON(e4b->bd_bitmap_page == NULL);
1223 BUG_ON(e4b->bd_buddy_page == NULL);
1229 page_cache_release(page);
1230 if (e4b->bd_bitmap_page)
1231 page_cache_release(e4b->bd_bitmap_page);
1232 if (e4b->bd_buddy_page)
1233 page_cache_release(e4b->bd_buddy_page);
1234 e4b->bd_buddy = NULL;
1235 e4b->bd_bitmap = NULL;
1239 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1241 if (e4b->bd_bitmap_page)
1242 page_cache_release(e4b->bd_bitmap_page);
1243 if (e4b->bd_buddy_page)
1244 page_cache_release(e4b->bd_buddy_page);
1248 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1253 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
1254 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1256 bb = EXT4_MB_BUDDY(e4b);
1257 while (order <= e4b->bd_blkbits + 1) {
1259 if (!mb_test_bit(block, bb)) {
1260 /* this block is part of buddy of order 'order' */
1263 bb += 1 << (e4b->bd_blkbits - order);
1269 static void mb_clear_bits(void *bm, int cur, int len)
1275 if ((cur & 31) == 0 && (len - cur) >= 32) {
1276 /* fast path: clear whole word at once */
1277 addr = bm + (cur >> 3);
1282 mb_clear_bit(cur, bm);
1287 void ext4_set_bits(void *bm, int cur, int len)
1293 if ((cur & 31) == 0 && (len - cur) >= 32) {
1294 /* fast path: set whole word at once */
1295 addr = bm + (cur >> 3);
1300 mb_set_bit(cur, bm);
1305 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1306 int first, int count)
1313 struct super_block *sb = e4b->bd_sb;
1315 BUG_ON(first + count > (sb->s_blocksize << 3));
1316 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1317 mb_check_buddy(e4b);
1318 mb_free_blocks_double(inode, e4b, first, count);
1320 e4b->bd_info->bb_free += count;
1321 if (first < e4b->bd_info->bb_first_free)
1322 e4b->bd_info->bb_first_free = first;
1324 /* let's maintain fragments counter */
1326 block = !mb_test_bit(first - 1, EXT4_MB_BITMAP(e4b));
1327 if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
1328 max = !mb_test_bit(first + count, EXT4_MB_BITMAP(e4b));
1330 e4b->bd_info->bb_fragments--;
1331 else if (!block && !max)
1332 e4b->bd_info->bb_fragments++;
1334 /* let's maintain buddy itself */
1335 while (count-- > 0) {
1339 if (!mb_test_bit(block, EXT4_MB_BITMAP(e4b))) {
1340 ext4_fsblk_t blocknr;
1342 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1343 blocknr += EXT4_C2B(EXT4_SB(sb), block);
1344 ext4_grp_locked_error(sb, e4b->bd_group,
1345 inode ? inode->i_ino : 0,
1347 "freeing already freed block "
1350 mb_clear_bit(block, EXT4_MB_BITMAP(e4b));
1351 e4b->bd_info->bb_counters[order]++;
1353 /* start of the buddy */
1354 buddy = mb_find_buddy(e4b, order, &max);
1358 if (mb_test_bit(block, buddy) ||
1359 mb_test_bit(block + 1, buddy))
1362 /* both the buddies are free, try to coalesce them */
1363 buddy2 = mb_find_buddy(e4b, order + 1, &max);
1369 /* for special purposes, we don't set
1370 * free bits in bitmap */
1371 mb_set_bit(block, buddy);
1372 mb_set_bit(block + 1, buddy);
1374 e4b->bd_info->bb_counters[order]--;
1375 e4b->bd_info->bb_counters[order]--;
1379 e4b->bd_info->bb_counters[order]++;
1381 mb_clear_bit(block, buddy2);
1385 mb_set_largest_free_order(sb, e4b->bd_info);
1386 mb_check_buddy(e4b);
1389 static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
1390 int needed, struct ext4_free_extent *ex)
1396 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1399 buddy = mb_find_buddy(e4b, order, &max);
1400 BUG_ON(buddy == NULL);
1401 BUG_ON(block >= max);
1402 if (mb_test_bit(block, buddy)) {
1409 /* FIXME dorp order completely ? */
1410 if (likely(order == 0)) {
1411 /* find actual order */
1412 order = mb_find_order_for_block(e4b, block);
1413 block = block >> order;
1416 ex->fe_len = 1 << order;
1417 ex->fe_start = block << order;
1418 ex->fe_group = e4b->bd_group;
1420 /* calc difference from given start */
1421 next = next - ex->fe_start;
1423 ex->fe_start += next;
1425 while (needed > ex->fe_len &&
1426 (buddy = mb_find_buddy(e4b, order, &max))) {
1428 if (block + 1 >= max)
1431 next = (block + 1) * (1 << order);
1432 if (mb_test_bit(next, EXT4_MB_BITMAP(e4b)))
1435 order = mb_find_order_for_block(e4b, next);
1437 block = next >> order;
1438 ex->fe_len += 1 << order;
1441 BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1445 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1451 int start = ex->fe_start;
1452 int len = ex->fe_len;
1457 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1458 BUG_ON(e4b->bd_group != ex->fe_group);
1459 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1460 mb_check_buddy(e4b);
1461 mb_mark_used_double(e4b, start, len);
1463 e4b->bd_info->bb_free -= len;
1464 if (e4b->bd_info->bb_first_free == start)
1465 e4b->bd_info->bb_first_free += len;
1467 /* let's maintain fragments counter */
1469 mlen = !mb_test_bit(start - 1, EXT4_MB_BITMAP(e4b));
1470 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1471 max = !mb_test_bit(start + len, EXT4_MB_BITMAP(e4b));
1473 e4b->bd_info->bb_fragments++;
1474 else if (!mlen && !max)
1475 e4b->bd_info->bb_fragments--;
1477 /* let's maintain buddy itself */
1479 ord = mb_find_order_for_block(e4b, start);
1481 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1482 /* the whole chunk may be allocated at once! */
1484 buddy = mb_find_buddy(e4b, ord, &max);
1485 BUG_ON((start >> ord) >= max);
1486 mb_set_bit(start >> ord, buddy);
1487 e4b->bd_info->bb_counters[ord]--;
1494 /* store for history */
1496 ret = len | (ord << 16);
1498 /* we have to split large buddy */
1500 buddy = mb_find_buddy(e4b, ord, &max);
1501 mb_set_bit(start >> ord, buddy);
1502 e4b->bd_info->bb_counters[ord]--;
1505 cur = (start >> ord) & ~1U;
1506 buddy = mb_find_buddy(e4b, ord, &max);
1507 mb_clear_bit(cur, buddy);
1508 mb_clear_bit(cur + 1, buddy);
1509 e4b->bd_info->bb_counters[ord]++;
1510 e4b->bd_info->bb_counters[ord]++;
1512 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1514 ext4_set_bits(EXT4_MB_BITMAP(e4b), ex->fe_start, len0);
1515 mb_check_buddy(e4b);
1521 * Must be called under group lock!
1523 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1524 struct ext4_buddy *e4b)
1526 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1529 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1530 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1532 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1533 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1534 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1536 /* preallocation can change ac_b_ex, thus we store actually
1537 * allocated blocks for history */
1538 ac->ac_f_ex = ac->ac_b_ex;
1540 ac->ac_status = AC_STATUS_FOUND;
1541 ac->ac_tail = ret & 0xffff;
1542 ac->ac_buddy = ret >> 16;
1545 * take the page reference. We want the page to be pinned
1546 * so that we don't get a ext4_mb_init_cache_call for this
1547 * group until we update the bitmap. That would mean we
1548 * double allocate blocks. The reference is dropped
1549 * in ext4_mb_release_context
1551 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1552 get_page(ac->ac_bitmap_page);
1553 ac->ac_buddy_page = e4b->bd_buddy_page;
1554 get_page(ac->ac_buddy_page);
1555 /* store last allocated for subsequent stream allocation */
1556 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1557 spin_lock(&sbi->s_md_lock);
1558 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1559 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1560 spin_unlock(&sbi->s_md_lock);
1565 * regular allocator, for general purposes allocation
1568 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1569 struct ext4_buddy *e4b,
1572 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1573 struct ext4_free_extent *bex = &ac->ac_b_ex;
1574 struct ext4_free_extent *gex = &ac->ac_g_ex;
1575 struct ext4_free_extent ex;
1578 if (ac->ac_status == AC_STATUS_FOUND)
1581 * We don't want to scan for a whole year
1583 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1584 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1585 ac->ac_status = AC_STATUS_BREAK;
1590 * Haven't found good chunk so far, let's continue
1592 if (bex->fe_len < gex->fe_len)
1595 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1596 && bex->fe_group == e4b->bd_group) {
1597 /* recheck chunk's availability - we don't know
1598 * when it was found (within this lock-unlock
1600 max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
1601 if (max >= gex->fe_len) {
1602 ext4_mb_use_best_found(ac, e4b);
1609 * The routine checks whether found extent is good enough. If it is,
1610 * then the extent gets marked used and flag is set to the context
1611 * to stop scanning. Otherwise, the extent is compared with the
1612 * previous found extent and if new one is better, then it's stored
1613 * in the context. Later, the best found extent will be used, if
1614 * mballoc can't find good enough extent.
1616 * FIXME: real allocation policy is to be designed yet!
1618 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1619 struct ext4_free_extent *ex,
1620 struct ext4_buddy *e4b)
1622 struct ext4_free_extent *bex = &ac->ac_b_ex;
1623 struct ext4_free_extent *gex = &ac->ac_g_ex;
1625 BUG_ON(ex->fe_len <= 0);
1626 BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1627 BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1628 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1633 * The special case - take what you catch first
1635 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1637 ext4_mb_use_best_found(ac, e4b);
1642 * Let's check whether the chuck is good enough
1644 if (ex->fe_len == gex->fe_len) {
1646 ext4_mb_use_best_found(ac, e4b);
1651 * If this is first found extent, just store it in the context
1653 if (bex->fe_len == 0) {
1659 * If new found extent is better, store it in the context
1661 if (bex->fe_len < gex->fe_len) {
1662 /* if the request isn't satisfied, any found extent
1663 * larger than previous best one is better */
1664 if (ex->fe_len > bex->fe_len)
1666 } else if (ex->fe_len > gex->fe_len) {
1667 /* if the request is satisfied, then we try to find
1668 * an extent that still satisfy the request, but is
1669 * smaller than previous one */
1670 if (ex->fe_len < bex->fe_len)
1674 ext4_mb_check_limits(ac, e4b, 0);
1677 static noinline_for_stack
1678 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1679 struct ext4_buddy *e4b)
1681 struct ext4_free_extent ex = ac->ac_b_ex;
1682 ext4_group_t group = ex.fe_group;
1686 BUG_ON(ex.fe_len <= 0);
1687 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1691 ext4_lock_group(ac->ac_sb, group);
1692 max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
1696 ext4_mb_use_best_found(ac, e4b);
1699 ext4_unlock_group(ac->ac_sb, group);
1700 ext4_mb_unload_buddy(e4b);
1705 static noinline_for_stack
1706 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1707 struct ext4_buddy *e4b)
1709 ext4_group_t group = ac->ac_g_ex.fe_group;
1712 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1713 struct ext4_free_extent ex;
1715 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1718 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1722 ext4_lock_group(ac->ac_sb, group);
1723 max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
1724 ac->ac_g_ex.fe_len, &ex);
1726 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1729 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
1731 /* use do_div to get remainder (would be 64-bit modulo) */
1732 if (do_div(start, sbi->s_stripe) == 0) {
1735 ext4_mb_use_best_found(ac, e4b);
1737 } else if (max >= ac->ac_g_ex.fe_len) {
1738 BUG_ON(ex.fe_len <= 0);
1739 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1740 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1743 ext4_mb_use_best_found(ac, e4b);
1744 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1745 /* Sometimes, caller may want to merge even small
1746 * number of blocks to an existing extent */
1747 BUG_ON(ex.fe_len <= 0);
1748 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1749 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1752 ext4_mb_use_best_found(ac, e4b);
1754 ext4_unlock_group(ac->ac_sb, group);
1755 ext4_mb_unload_buddy(e4b);
1761 * The routine scans buddy structures (not bitmap!) from given order
1762 * to max order and tries to find big enough chunk to satisfy the req
1764 static noinline_for_stack
1765 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1766 struct ext4_buddy *e4b)
1768 struct super_block *sb = ac->ac_sb;
1769 struct ext4_group_info *grp = e4b->bd_info;
1775 BUG_ON(ac->ac_2order <= 0);
1776 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1777 if (grp->bb_counters[i] == 0)
1780 buddy = mb_find_buddy(e4b, i, &max);
1781 BUG_ON(buddy == NULL);
1783 k = mb_find_next_zero_bit(buddy, max, 0);
1788 ac->ac_b_ex.fe_len = 1 << i;
1789 ac->ac_b_ex.fe_start = k << i;
1790 ac->ac_b_ex.fe_group = e4b->bd_group;
1792 ext4_mb_use_best_found(ac, e4b);
1794 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1796 if (EXT4_SB(sb)->s_mb_stats)
1797 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1804 * The routine scans the group and measures all found extents.
1805 * In order to optimize scanning, caller must pass number of
1806 * free blocks in the group, so the routine can know upper limit.
1808 static noinline_for_stack
1809 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1810 struct ext4_buddy *e4b)
1812 struct super_block *sb = ac->ac_sb;
1813 void *bitmap = EXT4_MB_BITMAP(e4b);
1814 struct ext4_free_extent ex;
1818 free = e4b->bd_info->bb_free;
1821 i = e4b->bd_info->bb_first_free;
1823 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1824 i = mb_find_next_zero_bit(bitmap,
1825 EXT4_CLUSTERS_PER_GROUP(sb), i);
1826 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
1828 * IF we have corrupt bitmap, we won't find any
1829 * free blocks even though group info says we
1830 * we have free blocks
1832 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1833 "%d free clusters as per "
1834 "group info. But bitmap says 0",
1839 mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
1840 BUG_ON(ex.fe_len <= 0);
1841 if (free < ex.fe_len) {
1842 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1843 "%d free clusters as per "
1844 "group info. But got %d blocks",
1847 * The number of free blocks differs. This mostly
1848 * indicate that the bitmap is corrupt. So exit
1849 * without claiming the space.
1854 ext4_mb_measure_extent(ac, &ex, e4b);
1860 ext4_mb_check_limits(ac, e4b, 1);
1864 * This is a special case for storages like raid5
1865 * we try to find stripe-aligned chunks for stripe-size-multiple requests
1867 static noinline_for_stack
1868 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1869 struct ext4_buddy *e4b)
1871 struct super_block *sb = ac->ac_sb;
1872 struct ext4_sb_info *sbi = EXT4_SB(sb);
1873 void *bitmap = EXT4_MB_BITMAP(e4b);
1874 struct ext4_free_extent ex;
1875 ext4_fsblk_t first_group_block;
1880 BUG_ON(sbi->s_stripe == 0);
1882 /* find first stripe-aligned block in group */
1883 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
1885 a = first_group_block + sbi->s_stripe - 1;
1886 do_div(a, sbi->s_stripe);
1887 i = (a * sbi->s_stripe) - first_group_block;
1889 while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
1890 if (!mb_test_bit(i, bitmap)) {
1891 max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
1892 if (max >= sbi->s_stripe) {
1895 ext4_mb_use_best_found(ac, e4b);
1903 /* This is now called BEFORE we load the buddy bitmap. */
1904 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
1905 ext4_group_t group, int cr)
1907 unsigned free, fragments;
1908 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
1909 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1911 BUG_ON(cr < 0 || cr >= 4);
1913 /* We only do this if the grp has never been initialized */
1914 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1915 int ret = ext4_mb_init_group(ac->ac_sb, group);
1920 free = grp->bb_free;
1921 fragments = grp->bb_fragments;
1929 BUG_ON(ac->ac_2order == 0);
1931 if (grp->bb_largest_free_order < ac->ac_2order)
1934 /* Avoid using the first bg of a flexgroup for data files */
1935 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
1936 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
1937 ((group % flex_size) == 0))
1942 if ((free / fragments) >= ac->ac_g_ex.fe_len)
1946 if (free >= ac->ac_g_ex.fe_len)
1958 static noinline_for_stack int
1959 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
1961 ext4_group_t ngroups, group, i;
1964 struct ext4_sb_info *sbi;
1965 struct super_block *sb;
1966 struct ext4_buddy e4b;
1970 ngroups = ext4_get_groups_count(sb);
1971 /* non-extent files are limited to low blocks/groups */
1972 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
1973 ngroups = sbi->s_blockfile_groups;
1975 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1977 /* first, try the goal */
1978 err = ext4_mb_find_by_goal(ac, &e4b);
1979 if (err || ac->ac_status == AC_STATUS_FOUND)
1982 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
1986 * ac->ac2_order is set only if the fe_len is a power of 2
1987 * if ac2_order is set we also set criteria to 0 so that we
1988 * try exact allocation using buddy.
1990 i = fls(ac->ac_g_ex.fe_len);
1993 * We search using buddy data only if the order of the request
1994 * is greater than equal to the sbi_s_mb_order2_reqs
1995 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
1997 if (i >= sbi->s_mb_order2_reqs) {
1999 * This should tell if fe_len is exactly power of 2
2001 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2002 ac->ac_2order = i - 1;
2005 /* if stream allocation is enabled, use global goal */
2006 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2007 /* TBD: may be hot point */
2008 spin_lock(&sbi->s_md_lock);
2009 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2010 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2011 spin_unlock(&sbi->s_md_lock);
2014 /* Let's just scan groups to find more-less suitable blocks */
2015 cr = ac->ac_2order ? 0 : 1;
2017 * cr == 0 try to get exact allocation,
2018 * cr == 3 try to get anything
2021 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2022 ac->ac_criteria = cr;
2024 * searching for the right group start
2025 * from the goal value specified
2027 group = ac->ac_g_ex.fe_group;
2029 for (i = 0; i < ngroups; group++, i++) {
2030 if (group == ngroups)
2033 /* This now checks without needing the buddy page */
2034 if (!ext4_mb_good_group(ac, group, cr))
2037 err = ext4_mb_load_buddy(sb, group, &e4b);
2041 ext4_lock_group(sb, group);
2044 * We need to check again after locking the
2047 if (!ext4_mb_good_group(ac, group, cr)) {
2048 ext4_unlock_group(sb, group);
2049 ext4_mb_unload_buddy(&e4b);
2053 ac->ac_groups_scanned++;
2055 ext4_mb_simple_scan_group(ac, &e4b);
2056 else if (cr == 1 && sbi->s_stripe &&
2057 !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2058 ext4_mb_scan_aligned(ac, &e4b);
2060 ext4_mb_complex_scan_group(ac, &e4b);
2062 ext4_unlock_group(sb, group);
2063 ext4_mb_unload_buddy(&e4b);
2065 if (ac->ac_status != AC_STATUS_CONTINUE)
2070 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2071 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2073 * We've been searching too long. Let's try to allocate
2074 * the best chunk we've found so far
2077 ext4_mb_try_best_found(ac, &e4b);
2078 if (ac->ac_status != AC_STATUS_FOUND) {
2080 * Someone more lucky has already allocated it.
2081 * The only thing we can do is just take first
2083 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2085 ac->ac_b_ex.fe_group = 0;
2086 ac->ac_b_ex.fe_start = 0;
2087 ac->ac_b_ex.fe_len = 0;
2088 ac->ac_status = AC_STATUS_CONTINUE;
2089 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2091 atomic_inc(&sbi->s_mb_lost_chunks);
2099 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2101 struct super_block *sb = seq->private;
2104 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2107 return (void *) ((unsigned long) group);
2110 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2112 struct super_block *sb = seq->private;
2116 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2119 return (void *) ((unsigned long) group);
2122 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2124 struct super_block *sb = seq->private;
2125 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2128 struct ext4_buddy e4b;
2130 struct ext4_group_info info;
2131 ext4_grpblk_t counters[16];
2136 seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
2137 "[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2138 "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2139 "group", "free", "frags", "first",
2140 "2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
2141 "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2143 i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2144 sizeof(struct ext4_group_info);
2145 err = ext4_mb_load_buddy(sb, group, &e4b);
2147 seq_printf(seq, "#%-5u: I/O error\n", group);
2150 ext4_lock_group(sb, group);
2151 memcpy(&sg, ext4_get_group_info(sb, group), i);
2152 ext4_unlock_group(sb, group);
2153 ext4_mb_unload_buddy(&e4b);
2155 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2156 sg.info.bb_fragments, sg.info.bb_first_free);
2157 for (i = 0; i <= 13; i++)
2158 seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2159 sg.info.bb_counters[i] : 0);
2160 seq_printf(seq, " ]\n");
2165 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2169 static const struct seq_operations ext4_mb_seq_groups_ops = {
2170 .start = ext4_mb_seq_groups_start,
2171 .next = ext4_mb_seq_groups_next,
2172 .stop = ext4_mb_seq_groups_stop,
2173 .show = ext4_mb_seq_groups_show,
2176 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2178 struct super_block *sb = PDE(inode)->data;
2181 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2183 struct seq_file *m = file->private_data;
2190 static const struct file_operations ext4_mb_seq_groups_fops = {
2191 .owner = THIS_MODULE,
2192 .open = ext4_mb_seq_groups_open,
2194 .llseek = seq_lseek,
2195 .release = seq_release,
2198 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2200 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2201 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2207 /* Create and initialize ext4_group_info data for the given group. */
2208 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2209 struct ext4_group_desc *desc)
2213 struct ext4_sb_info *sbi = EXT4_SB(sb);
2214 struct ext4_group_info **meta_group_info;
2215 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2218 * First check if this group is the first of a reserved block.
2219 * If it's true, we have to allocate a new table of pointers
2220 * to ext4_group_info structures
2222 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2223 metalen = sizeof(*meta_group_info) <<
2224 EXT4_DESC_PER_BLOCK_BITS(sb);
2225 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2226 if (meta_group_info == NULL) {
2227 ext4_msg(sb, KERN_ERR, "EXT4-fs: can't allocate mem "
2228 "for a buddy group");
2229 goto exit_meta_group_info;
2231 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] =
2236 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)];
2237 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2239 meta_group_info[i] = kmem_cache_alloc(cachep, GFP_KERNEL);
2240 if (meta_group_info[i] == NULL) {
2241 ext4_msg(sb, KERN_ERR, "EXT4-fs: can't allocate buddy mem");
2242 goto exit_group_info;
2244 memset(meta_group_info[i], 0, kmem_cache_size(cachep));
2245 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2246 &(meta_group_info[i]->bb_state));
2249 * initialize bb_free to be able to skip
2250 * empty groups without initialization
2252 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2253 meta_group_info[i]->bb_free =
2254 ext4_free_clusters_after_init(sb, group, desc);
2256 meta_group_info[i]->bb_free =
2257 ext4_free_group_clusters(sb, desc);
2260 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2261 init_rwsem(&meta_group_info[i]->alloc_sem);
2262 meta_group_info[i]->bb_free_root = RB_ROOT;
2263 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
2267 struct buffer_head *bh;
2268 meta_group_info[i]->bb_bitmap =
2269 kmalloc(sb->s_blocksize, GFP_KERNEL);
2270 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2271 bh = ext4_read_block_bitmap(sb, group);
2273 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2282 /* If a meta_group_info table has been allocated, release it now */
2283 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2284 kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
2285 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] = NULL;
2287 exit_meta_group_info:
2289 } /* ext4_mb_add_groupinfo */
2291 static int ext4_mb_init_backend(struct super_block *sb)
2293 ext4_group_t ngroups = ext4_get_groups_count(sb);
2295 struct ext4_sb_info *sbi = EXT4_SB(sb);
2296 struct ext4_super_block *es = sbi->s_es;
2297 int num_meta_group_infos;
2298 int num_meta_group_infos_max;
2300 struct ext4_group_desc *desc;
2301 struct kmem_cache *cachep;
2303 /* This is the number of blocks used by GDT */
2304 num_meta_group_infos = (ngroups + EXT4_DESC_PER_BLOCK(sb) -
2305 1) >> EXT4_DESC_PER_BLOCK_BITS(sb);
2308 * This is the total number of blocks used by GDT including
2309 * the number of reserved blocks for GDT.
2310 * The s_group_info array is allocated with this value
2311 * to allow a clean online resize without a complex
2312 * manipulation of pointer.
2313 * The drawback is the unused memory when no resize
2314 * occurs but it's very low in terms of pages
2315 * (see comments below)
2316 * Need to handle this properly when META_BG resizing is allowed
2318 num_meta_group_infos_max = num_meta_group_infos +
2319 le16_to_cpu(es->s_reserved_gdt_blocks);
2322 * array_size is the size of s_group_info array. We round it
2323 * to the next power of two because this approximation is done
2324 * internally by kmalloc so we can have some more memory
2325 * for free here (e.g. may be used for META_BG resize).
2328 while (array_size < sizeof(*sbi->s_group_info) *
2329 num_meta_group_infos_max)
2330 array_size = array_size << 1;
2331 /* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2332 * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2333 * So a two level scheme suffices for now. */
2334 sbi->s_group_info = ext4_kvzalloc(array_size, GFP_KERNEL);
2335 if (sbi->s_group_info == NULL) {
2336 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
2339 sbi->s_buddy_cache = new_inode(sb);
2340 if (sbi->s_buddy_cache == NULL) {
2341 ext4_msg(sb, KERN_ERR, "can't get new inode");
2344 /* To avoid potentially colliding with an valid on-disk inode number,
2345 * use EXT4_BAD_INO for the buddy cache inode number. This inode is
2346 * not in the inode hash, so it should never be found by iget(), but
2347 * this will avoid confusion if it ever shows up during debugging. */
2348 sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
2349 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2350 for (i = 0; i < ngroups; i++) {
2351 desc = ext4_get_group_desc(sb, i, NULL);
2353 ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2356 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2363 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2365 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2366 i = num_meta_group_infos;
2368 kfree(sbi->s_group_info[i]);
2369 iput(sbi->s_buddy_cache);
2371 ext4_kvfree(sbi->s_group_info);
2375 static void ext4_groupinfo_destroy_slabs(void)
2379 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
2380 if (ext4_groupinfo_caches[i])
2381 kmem_cache_destroy(ext4_groupinfo_caches[i]);
2382 ext4_groupinfo_caches[i] = NULL;
2386 static int ext4_groupinfo_create_slab(size_t size)
2388 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
2390 int blocksize_bits = order_base_2(size);
2391 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2392 struct kmem_cache *cachep;
2394 if (cache_index >= NR_GRPINFO_CACHES)
2397 if (unlikely(cache_index < 0))
2400 mutex_lock(&ext4_grpinfo_slab_create_mutex);
2401 if (ext4_groupinfo_caches[cache_index]) {
2402 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2403 return 0; /* Already created */
2406 slab_size = offsetof(struct ext4_group_info,
2407 bb_counters[blocksize_bits + 2]);
2409 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
2410 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
2413 ext4_groupinfo_caches[cache_index] = cachep;
2415 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2418 "EXT4-fs: no memory for groupinfo slab cache\n");
2425 int ext4_mb_init(struct super_block *sb, int needs_recovery)
2427 struct ext4_sb_info *sbi = EXT4_SB(sb);
2433 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2435 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2436 if (sbi->s_mb_offsets == NULL) {
2441 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2442 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2443 if (sbi->s_mb_maxs == NULL) {
2448 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2452 /* order 0 is regular bitmap */
2453 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2454 sbi->s_mb_offsets[0] = 0;
2458 max = sb->s_blocksize << 2;
2460 sbi->s_mb_offsets[i] = offset;
2461 sbi->s_mb_maxs[i] = max;
2462 offset += 1 << (sb->s_blocksize_bits - i);
2465 } while (i <= sb->s_blocksize_bits + 1);
2467 spin_lock_init(&sbi->s_md_lock);
2468 spin_lock_init(&sbi->s_bal_lock);
2470 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2471 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2472 sbi->s_mb_stats = MB_DEFAULT_STATS;
2473 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2474 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2476 * The default group preallocation is 512, which for 4k block
2477 * sizes translates to 2 megabytes. However for bigalloc file
2478 * systems, this is probably too big (i.e, if the cluster size
2479 * is 1 megabyte, then group preallocation size becomes half a
2480 * gigabyte!). As a default, we will keep a two megabyte
2481 * group pralloc size for cluster sizes up to 64k, and after
2482 * that, we will force a minimum group preallocation size of
2483 * 32 clusters. This translates to 8 megs when the cluster
2484 * size is 256k, and 32 megs when the cluster size is 1 meg,
2485 * which seems reasonable as a default.
2487 sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
2488 sbi->s_cluster_bits, 32);
2490 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
2491 * to the lowest multiple of s_stripe which is bigger than
2492 * the s_mb_group_prealloc as determined above. We want
2493 * the preallocation size to be an exact multiple of the
2494 * RAID stripe size so that preallocations don't fragment
2497 if (sbi->s_stripe > 1) {
2498 sbi->s_mb_group_prealloc = roundup(
2499 sbi->s_mb_group_prealloc, sbi->s_stripe);
2502 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2503 if (sbi->s_locality_groups == NULL) {
2505 goto out_free_groupinfo_slab;
2507 for_each_possible_cpu(i) {
2508 struct ext4_locality_group *lg;
2509 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2510 mutex_init(&lg->lg_mutex);
2511 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2512 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2513 spin_lock_init(&lg->lg_prealloc_lock);
2516 /* init file for buddy data */
2517 ret = ext4_mb_init_backend(sb);
2519 goto out_free_locality_groups;
2522 proc_create_data("mb_groups", S_IRUGO, sbi->s_proc,
2523 &ext4_mb_seq_groups_fops, sb);
2526 sbi->s_journal->j_commit_callback = release_blocks_on_commit;
2530 out_free_locality_groups:
2531 free_percpu(sbi->s_locality_groups);
2532 sbi->s_locality_groups = NULL;
2533 out_free_groupinfo_slab:
2534 ext4_groupinfo_destroy_slabs();
2536 kfree(sbi->s_mb_offsets);
2537 sbi->s_mb_offsets = NULL;
2538 kfree(sbi->s_mb_maxs);
2539 sbi->s_mb_maxs = NULL;
2543 /* need to called with the ext4 group lock held */
2544 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2546 struct ext4_prealloc_space *pa;
2547 struct list_head *cur, *tmp;
2550 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2551 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2552 list_del(&pa->pa_group_list);
2554 kmem_cache_free(ext4_pspace_cachep, pa);
2557 mb_debug(1, "mballoc: %u PAs left\n", count);
2561 int ext4_mb_release(struct super_block *sb)
2563 ext4_group_t ngroups = ext4_get_groups_count(sb);
2565 int num_meta_group_infos;
2566 struct ext4_group_info *grinfo;
2567 struct ext4_sb_info *sbi = EXT4_SB(sb);
2568 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2571 remove_proc_entry("mb_groups", sbi->s_proc);
2573 if (sbi->s_group_info) {
2574 for (i = 0; i < ngroups; i++) {
2575 grinfo = ext4_get_group_info(sb, i);
2577 kfree(grinfo->bb_bitmap);
2579 ext4_lock_group(sb, i);
2580 ext4_mb_cleanup_pa(grinfo);
2581 ext4_unlock_group(sb, i);
2582 kmem_cache_free(cachep, grinfo);
2584 num_meta_group_infos = (ngroups +
2585 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2586 EXT4_DESC_PER_BLOCK_BITS(sb);
2587 for (i = 0; i < num_meta_group_infos; i++)
2588 kfree(sbi->s_group_info[i]);
2589 ext4_kvfree(sbi->s_group_info);
2591 kfree(sbi->s_mb_offsets);
2592 kfree(sbi->s_mb_maxs);
2593 if (sbi->s_buddy_cache)
2594 iput(sbi->s_buddy_cache);
2595 if (sbi->s_mb_stats) {
2596 ext4_msg(sb, KERN_INFO,
2597 "mballoc: %u blocks %u reqs (%u success)",
2598 atomic_read(&sbi->s_bal_allocated),
2599 atomic_read(&sbi->s_bal_reqs),
2600 atomic_read(&sbi->s_bal_success));
2601 ext4_msg(sb, KERN_INFO,
2602 "mballoc: %u extents scanned, %u goal hits, "
2603 "%u 2^N hits, %u breaks, %u lost",
2604 atomic_read(&sbi->s_bal_ex_scanned),
2605 atomic_read(&sbi->s_bal_goals),
2606 atomic_read(&sbi->s_bal_2orders),
2607 atomic_read(&sbi->s_bal_breaks),
2608 atomic_read(&sbi->s_mb_lost_chunks));
2609 ext4_msg(sb, KERN_INFO,
2610 "mballoc: %lu generated and it took %Lu",
2611 sbi->s_mb_buddies_generated,
2612 sbi->s_mb_generation_time);
2613 ext4_msg(sb, KERN_INFO,
2614 "mballoc: %u preallocated, %u discarded",
2615 atomic_read(&sbi->s_mb_preallocated),
2616 atomic_read(&sbi->s_mb_discarded));
2619 free_percpu(sbi->s_locality_groups);
2624 static inline int ext4_issue_discard(struct super_block *sb,
2625 ext4_group_t block_group, ext4_grpblk_t cluster, int count)
2627 ext4_fsblk_t discard_block;
2629 discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
2630 ext4_group_first_block_no(sb, block_group));
2631 count = EXT4_C2B(EXT4_SB(sb), count);
2632 trace_ext4_discard_blocks(sb,
2633 (unsigned long long) discard_block, count);
2634 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
2638 * This function is called by the jbd2 layer once the commit has finished,
2639 * so we know we can free the blocks that were released with that commit.
2641 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn)
2643 struct super_block *sb = journal->j_private;
2644 struct ext4_buddy e4b;
2645 struct ext4_group_info *db;
2646 int err, count = 0, count2 = 0;
2647 struct ext4_free_data *entry;
2648 struct list_head *l, *ltmp;
2650 list_for_each_safe(l, ltmp, &txn->t_private_list) {
2651 entry = list_entry(l, struct ext4_free_data, list);
2653 mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2654 entry->count, entry->group, entry);
2656 if (test_opt(sb, DISCARD))
2657 ext4_issue_discard(sb, entry->group,
2658 entry->start_cluster, entry->count);
2660 err = ext4_mb_load_buddy(sb, entry->group, &e4b);
2661 /* we expect to find existing buddy because it's pinned */
2665 /* there are blocks to put in buddy to make them really free */
2666 count += entry->count;
2668 ext4_lock_group(sb, entry->group);
2669 /* Take it out of per group rb tree */
2670 rb_erase(&entry->node, &(db->bb_free_root));
2671 mb_free_blocks(NULL, &e4b, entry->start_cluster, entry->count);
2674 * Clear the trimmed flag for the group so that the next
2675 * ext4_trim_fs can trim it.
2676 * If the volume is mounted with -o discard, online discard
2677 * is supported and the free blocks will be trimmed online.
2679 if (!test_opt(sb, DISCARD))
2680 EXT4_MB_GRP_CLEAR_TRIMMED(db);
2682 if (!db->bb_free_root.rb_node) {
2683 /* No more items in the per group rb tree
2684 * balance refcounts from ext4_mb_free_metadata()
2686 page_cache_release(e4b.bd_buddy_page);
2687 page_cache_release(e4b.bd_bitmap_page);
2689 ext4_unlock_group(sb, entry->group);
2690 kmem_cache_free(ext4_free_ext_cachep, entry);
2691 ext4_mb_unload_buddy(&e4b);
2694 mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2697 #ifdef CONFIG_EXT4_DEBUG
2698 u8 mb_enable_debug __read_mostly;
2700 static struct dentry *debugfs_dir;
2701 static struct dentry *debugfs_debug;
2703 static void __init ext4_create_debugfs_entry(void)
2705 debugfs_dir = debugfs_create_dir("ext4", NULL);
2707 debugfs_debug = debugfs_create_u8("mballoc-debug",
2713 static void ext4_remove_debugfs_entry(void)
2715 debugfs_remove(debugfs_debug);
2716 debugfs_remove(debugfs_dir);
2721 static void __init ext4_create_debugfs_entry(void)
2725 static void ext4_remove_debugfs_entry(void)
2731 int __init ext4_init_mballoc(void)
2733 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
2734 SLAB_RECLAIM_ACCOUNT);
2735 if (ext4_pspace_cachep == NULL)
2738 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
2739 SLAB_RECLAIM_ACCOUNT);
2740 if (ext4_ac_cachep == NULL) {
2741 kmem_cache_destroy(ext4_pspace_cachep);
2745 ext4_free_ext_cachep = KMEM_CACHE(ext4_free_data,
2746 SLAB_RECLAIM_ACCOUNT);
2747 if (ext4_free_ext_cachep == NULL) {
2748 kmem_cache_destroy(ext4_pspace_cachep);
2749 kmem_cache_destroy(ext4_ac_cachep);
2752 ext4_create_debugfs_entry();
2756 void ext4_exit_mballoc(void)
2759 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
2760 * before destroying the slab cache.
2763 kmem_cache_destroy(ext4_pspace_cachep);
2764 kmem_cache_destroy(ext4_ac_cachep);
2765 kmem_cache_destroy(ext4_free_ext_cachep);
2766 ext4_groupinfo_destroy_slabs();
2767 ext4_remove_debugfs_entry();
2772 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2773 * Returns 0 if success or error code
2775 static noinline_for_stack int
2776 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2777 handle_t *handle, unsigned int reserv_clstrs)
2779 struct buffer_head *bitmap_bh = NULL;
2780 struct ext4_group_desc *gdp;
2781 struct buffer_head *gdp_bh;
2782 struct ext4_sb_info *sbi;
2783 struct super_block *sb;
2787 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2788 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2794 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2798 err = ext4_journal_get_write_access(handle, bitmap_bh);
2803 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2807 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
2808 ext4_free_group_clusters(sb, gdp));
2810 err = ext4_journal_get_write_access(handle, gdp_bh);
2814 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
2816 len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
2817 if (!ext4_data_block_valid(sbi, block, len)) {
2818 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
2819 "fs metadata\n", block, block+len);
2820 /* File system mounted not to panic on error
2821 * Fix the bitmap and repeat the block allocation
2822 * We leak some of the blocks here.
2824 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2825 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2826 ac->ac_b_ex.fe_len);
2827 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
2828 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2834 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2835 #ifdef AGGRESSIVE_CHECK
2838 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
2839 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
2840 bitmap_bh->b_data));
2844 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2845 ac->ac_b_ex.fe_len);
2846 if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2847 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
2848 ext4_free_group_clusters_set(sb, gdp,
2849 ext4_free_clusters_after_init(sb,
2850 ac->ac_b_ex.fe_group, gdp));
2852 len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
2853 ext4_free_group_clusters_set(sb, gdp, len);
2854 gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
2856 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
2857 percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
2859 * Now reduce the dirty block count also. Should not go negative
2861 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
2862 /* release all the reserved blocks if non delalloc */
2863 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
2866 if (sbi->s_log_groups_per_flex) {
2867 ext4_group_t flex_group = ext4_flex_group(sbi,
2868 ac->ac_b_ex.fe_group);
2869 atomic_sub(ac->ac_b_ex.fe_len,
2870 &sbi->s_flex_groups[flex_group].free_clusters);
2873 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2876 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
2879 ext4_mark_super_dirty(sb);
2885 * here we normalize request for locality group
2886 * Group request are normalized to s_mb_group_prealloc, which goes to
2887 * s_strip if we set the same via mount option.
2888 * s_mb_group_prealloc can be configured via
2889 * /sys/fs/ext4/<partition>/mb_group_prealloc
2891 * XXX: should we try to preallocate more than the group has now?
2893 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
2895 struct super_block *sb = ac->ac_sb;
2896 struct ext4_locality_group *lg = ac->ac_lg;
2899 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
2900 mb_debug(1, "#%u: goal %u blocks for locality group\n",
2901 current->pid, ac->ac_g_ex.fe_len);
2905 * Normalization means making request better in terms of
2906 * size and alignment
2908 static noinline_for_stack void
2909 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
2910 struct ext4_allocation_request *ar)
2912 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2915 loff_t size, orig_size, start_off;
2917 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
2918 struct ext4_prealloc_space *pa;
2920 /* do normalize only data requests, metadata requests
2921 do not need preallocation */
2922 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
2925 /* sometime caller may want exact blocks */
2926 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2929 /* caller may indicate that preallocation isn't
2930 * required (it's a tail, for example) */
2931 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
2934 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
2935 ext4_mb_normalize_group_request(ac);
2939 bsbits = ac->ac_sb->s_blocksize_bits;
2941 /* first, let's learn actual file size
2942 * given current request is allocated */
2943 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
2944 size = size << bsbits;
2945 if (size < i_size_read(ac->ac_inode))
2946 size = i_size_read(ac->ac_inode);
2949 /* max size of free chunks */
2952 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
2953 (req <= (size) || max <= (chunk_size))
2955 /* first, try to predict filesize */
2956 /* XXX: should this table be tunable? */
2958 if (size <= 16 * 1024) {
2960 } else if (size <= 32 * 1024) {
2962 } else if (size <= 64 * 1024) {
2964 } else if (size <= 128 * 1024) {
2966 } else if (size <= 256 * 1024) {
2968 } else if (size <= 512 * 1024) {
2970 } else if (size <= 1024 * 1024) {
2972 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
2973 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2974 (21 - bsbits)) << 21;
2975 size = 2 * 1024 * 1024;
2976 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
2977 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2978 (22 - bsbits)) << 22;
2979 size = 4 * 1024 * 1024;
2980 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
2981 (8<<20)>>bsbits, max, 8 * 1024)) {
2982 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2983 (23 - bsbits)) << 23;
2984 size = 8 * 1024 * 1024;
2986 start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
2987 size = ac->ac_o_ex.fe_len << bsbits;
2989 size = size >> bsbits;
2990 start = start_off >> bsbits;
2992 /* don't cover already allocated blocks in selected range */
2993 if (ar->pleft && start <= ar->lleft) {
2994 size -= ar->lleft + 1 - start;
2995 start = ar->lleft + 1;
2997 if (ar->pright && start + size - 1 >= ar->lright)
2998 size -= start + size - ar->lright;
3002 /* check we don't cross already preallocated blocks */
3004 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3009 spin_lock(&pa->pa_lock);
3010 if (pa->pa_deleted) {
3011 spin_unlock(&pa->pa_lock);
3015 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3018 /* PA must not overlap original request */
3019 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3020 ac->ac_o_ex.fe_logical < pa->pa_lstart));
3022 /* skip PAs this normalized request doesn't overlap with */
3023 if (pa->pa_lstart >= end || pa_end <= start) {
3024 spin_unlock(&pa->pa_lock);
3027 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3029 /* adjust start or end to be adjacent to this pa */
3030 if (pa_end <= ac->ac_o_ex.fe_logical) {
3031 BUG_ON(pa_end < start);
3033 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3034 BUG_ON(pa->pa_lstart > end);
3035 end = pa->pa_lstart;
3037 spin_unlock(&pa->pa_lock);
3042 /* XXX: extra loop to check we really don't overlap preallocations */
3044 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3047 spin_lock(&pa->pa_lock);
3048 if (pa->pa_deleted == 0) {
3049 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3051 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3053 spin_unlock(&pa->pa_lock);
3057 if (start + size <= ac->ac_o_ex.fe_logical &&
3058 start > ac->ac_o_ex.fe_logical) {
3059 ext4_msg(ac->ac_sb, KERN_ERR,
3060 "start %lu, size %lu, fe_logical %lu",
3061 (unsigned long) start, (unsigned long) size,
3062 (unsigned long) ac->ac_o_ex.fe_logical);
3064 BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3065 start > ac->ac_o_ex.fe_logical);
3066 BUG_ON(size <= 0 || size > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
3068 /* now prepare goal request */
3070 /* XXX: is it better to align blocks WRT to logical
3071 * placement or satisfy big request as is */
3072 ac->ac_g_ex.fe_logical = start;
3073 ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3075 /* define goal start in order to merge */
3076 if (ar->pright && (ar->lright == (start + size))) {
3077 /* merge to the right */
3078 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3079 &ac->ac_f_ex.fe_group,
3080 &ac->ac_f_ex.fe_start);
3081 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3083 if (ar->pleft && (ar->lleft + 1 == start)) {
3084 /* merge to the left */
3085 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3086 &ac->ac_f_ex.fe_group,
3087 &ac->ac_f_ex.fe_start);
3088 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3091 mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3092 (unsigned) orig_size, (unsigned) start);
3095 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3097 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3099 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3100 atomic_inc(&sbi->s_bal_reqs);
3101 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3102 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3103 atomic_inc(&sbi->s_bal_success);
3104 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3105 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3106 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3107 atomic_inc(&sbi->s_bal_goals);
3108 if (ac->ac_found > sbi->s_mb_max_to_scan)
3109 atomic_inc(&sbi->s_bal_breaks);
3112 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3113 trace_ext4_mballoc_alloc(ac);
3115 trace_ext4_mballoc_prealloc(ac);
3119 * Called on failure; free up any blocks from the inode PA for this
3120 * context. We don't need this for MB_GROUP_PA because we only change
3121 * pa_free in ext4_mb_release_context(), but on failure, we've already
3122 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3124 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3126 struct ext4_prealloc_space *pa = ac->ac_pa;
3129 if (pa && pa->pa_type == MB_INODE_PA) {
3130 len = ac->ac_b_ex.fe_len;
3137 * use blocks preallocated to inode
3139 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3140 struct ext4_prealloc_space *pa)
3142 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3147 /* found preallocated blocks, use them */
3148 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3149 end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
3150 start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
3151 len = EXT4_NUM_B2C(sbi, end - start);
3152 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3153 &ac->ac_b_ex.fe_start);
3154 ac->ac_b_ex.fe_len = len;
3155 ac->ac_status = AC_STATUS_FOUND;
3158 BUG_ON(start < pa->pa_pstart);
3159 BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3160 BUG_ON(pa->pa_free < len);
3163 mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3167 * use blocks preallocated to locality group
3169 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3170 struct ext4_prealloc_space *pa)
3172 unsigned int len = ac->ac_o_ex.fe_len;
3174 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3175 &ac->ac_b_ex.fe_group,
3176 &ac->ac_b_ex.fe_start);
3177 ac->ac_b_ex.fe_len = len;
3178 ac->ac_status = AC_STATUS_FOUND;
3181 /* we don't correct pa_pstart or pa_plen here to avoid
3182 * possible race when the group is being loaded concurrently
3183 * instead we correct pa later, after blocks are marked
3184 * in on-disk bitmap -- see ext4_mb_release_context()
3185 * Other CPUs are prevented from allocating from this pa by lg_mutex
3187 mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3191 * Return the prealloc space that have minimal distance
3192 * from the goal block. @cpa is the prealloc
3193 * space that is having currently known minimal distance
3194 * from the goal block.
3196 static struct ext4_prealloc_space *
3197 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3198 struct ext4_prealloc_space *pa,
3199 struct ext4_prealloc_space *cpa)
3201 ext4_fsblk_t cur_distance, new_distance;
3204 atomic_inc(&pa->pa_count);
3207 cur_distance = abs(goal_block - cpa->pa_pstart);
3208 new_distance = abs(goal_block - pa->pa_pstart);
3210 if (cur_distance <= new_distance)
3213 /* drop the previous reference */
3214 atomic_dec(&cpa->pa_count);
3215 atomic_inc(&pa->pa_count);
3220 * search goal blocks in preallocated space
3222 static noinline_for_stack int
3223 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3225 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3227 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3228 struct ext4_locality_group *lg;
3229 struct ext4_prealloc_space *pa, *cpa = NULL;
3230 ext4_fsblk_t goal_block;
3232 /* only data can be preallocated */
3233 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3236 /* first, try per-file preallocation */
3238 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3240 /* all fields in this condition don't change,
3241 * so we can skip locking for them */
3242 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3243 ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
3244 EXT4_C2B(sbi, pa->pa_len)))
3247 /* non-extent files can't have physical blocks past 2^32 */
3248 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3249 (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
3250 EXT4_MAX_BLOCK_FILE_PHYS))
3253 /* found preallocated blocks, use them */
3254 spin_lock(&pa->pa_lock);
3255 if (pa->pa_deleted == 0 && pa->pa_free) {
3256 atomic_inc(&pa->pa_count);
3257 ext4_mb_use_inode_pa(ac, pa);
3258 spin_unlock(&pa->pa_lock);
3259 ac->ac_criteria = 10;
3263 spin_unlock(&pa->pa_lock);
3267 /* can we use group allocation? */
3268 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3271 /* inode may have no locality group for some reason */
3275 order = fls(ac->ac_o_ex.fe_len) - 1;
3276 if (order > PREALLOC_TB_SIZE - 1)
3277 /* The max size of hash table is PREALLOC_TB_SIZE */
3278 order = PREALLOC_TB_SIZE - 1;
3280 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3282 * search for the prealloc space that is having
3283 * minimal distance from the goal block.
3285 for (i = order; i < PREALLOC_TB_SIZE; i++) {
3287 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3289 spin_lock(&pa->pa_lock);
3290 if (pa->pa_deleted == 0 &&
3291 pa->pa_free >= ac->ac_o_ex.fe_len) {
3293 cpa = ext4_mb_check_group_pa(goal_block,
3296 spin_unlock(&pa->pa_lock);
3301 ext4_mb_use_group_pa(ac, cpa);
3302 ac->ac_criteria = 20;
3309 * the function goes through all block freed in the group
3310 * but not yet committed and marks them used in in-core bitmap.
3311 * buddy must be generated from this bitmap
3312 * Need to be called with the ext4 group lock held
3314 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3318 struct ext4_group_info *grp;
3319 struct ext4_free_data *entry;
3321 grp = ext4_get_group_info(sb, group);
3322 n = rb_first(&(grp->bb_free_root));
3325 entry = rb_entry(n, struct ext4_free_data, node);
3326 ext4_set_bits(bitmap, entry->start_cluster, entry->count);
3333 * the function goes through all preallocation in this group and marks them
3334 * used in in-core bitmap. buddy must be generated from this bitmap
3335 * Need to be called with ext4 group lock held
3337 static noinline_for_stack
3338 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3341 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3342 struct ext4_prealloc_space *pa;
3343 struct list_head *cur;
3344 ext4_group_t groupnr;
3345 ext4_grpblk_t start;
3346 int preallocated = 0;
3349 /* all form of preallocation discards first load group,
3350 * so the only competing code is preallocation use.
3351 * we don't need any locking here
3352 * notice we do NOT ignore preallocations with pa_deleted
3353 * otherwise we could leave used blocks available for
3354 * allocation in buddy when concurrent ext4_mb_put_pa()
3355 * is dropping preallocation
3357 list_for_each(cur, &grp->bb_prealloc_list) {
3358 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3359 spin_lock(&pa->pa_lock);
3360 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3363 spin_unlock(&pa->pa_lock);
3364 if (unlikely(len == 0))
3366 BUG_ON(groupnr != group);
3367 ext4_set_bits(bitmap, start, len);
3368 preallocated += len;
3370 mb_debug(1, "prellocated %u for group %u\n", preallocated, group);
3373 static void ext4_mb_pa_callback(struct rcu_head *head)
3375 struct ext4_prealloc_space *pa;
3376 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3377 kmem_cache_free(ext4_pspace_cachep, pa);
3381 * drops a reference to preallocated space descriptor
3382 * if this was the last reference and the space is consumed
3384 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3385 struct super_block *sb, struct ext4_prealloc_space *pa)
3388 ext4_fsblk_t grp_blk;
3390 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3393 /* in this short window concurrent discard can set pa_deleted */
3394 spin_lock(&pa->pa_lock);
3395 if (pa->pa_deleted == 1) {
3396 spin_unlock(&pa->pa_lock);
3401 spin_unlock(&pa->pa_lock);
3403 grp_blk = pa->pa_pstart;
3405 * If doing group-based preallocation, pa_pstart may be in the
3406 * next group when pa is used up
3408 if (pa->pa_type == MB_GROUP_PA)
3411 ext4_get_group_no_and_offset(sb, grp_blk, &grp, NULL);
3416 * P1 (buddy init) P2 (regular allocation)
3417 * find block B in PA
3418 * copy on-disk bitmap to buddy
3419 * mark B in on-disk bitmap
3420 * drop PA from group
3421 * mark all PAs in buddy
3423 * thus, P1 initializes buddy with B available. to prevent this
3424 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3427 ext4_lock_group(sb, grp);
3428 list_del(&pa->pa_group_list);
3429 ext4_unlock_group(sb, grp);
3431 spin_lock(pa->pa_obj_lock);
3432 list_del_rcu(&pa->pa_inode_list);
3433 spin_unlock(pa->pa_obj_lock);
3435 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3439 * creates new preallocated space for given inode
3441 static noinline_for_stack int
3442 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3444 struct super_block *sb = ac->ac_sb;
3445 struct ext4_sb_info *sbi = EXT4_SB(sb);
3446 struct ext4_prealloc_space *pa;
3447 struct ext4_group_info *grp;
3448 struct ext4_inode_info *ei;
3450 /* preallocate only when found space is larger then requested */
3451 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3452 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3453 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3455 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3459 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3465 /* we can't allocate as much as normalizer wants.
3466 * so, found space must get proper lstart
3467 * to cover original request */
3468 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3469 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3471 /* we're limited by original request in that
3472 * logical block must be covered any way
3473 * winl is window we can move our chunk within */
3474 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3476 /* also, we should cover whole original request */
3477 wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
3479 /* the smallest one defines real window */
3480 win = min(winl, wins);
3482 offs = ac->ac_o_ex.fe_logical %
3483 EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3484 if (offs && offs < win)
3487 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
3489 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3490 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3493 /* preallocation can change ac_b_ex, thus we store actually
3494 * allocated blocks for history */
3495 ac->ac_f_ex = ac->ac_b_ex;
3497 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3498 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3499 pa->pa_len = ac->ac_b_ex.fe_len;
3500 pa->pa_free = pa->pa_len;
3501 atomic_set(&pa->pa_count, 1);
3502 spin_lock_init(&pa->pa_lock);
3503 INIT_LIST_HEAD(&pa->pa_inode_list);
3504 INIT_LIST_HEAD(&pa->pa_group_list);
3506 pa->pa_type = MB_INODE_PA;
3508 mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3509 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3510 trace_ext4_mb_new_inode_pa(ac, pa);
3512 ext4_mb_use_inode_pa(ac, pa);
3513 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
3515 ei = EXT4_I(ac->ac_inode);
3516 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3518 pa->pa_obj_lock = &ei->i_prealloc_lock;
3519 pa->pa_inode = ac->ac_inode;
3521 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3522 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3523 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3525 spin_lock(pa->pa_obj_lock);
3526 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3527 spin_unlock(pa->pa_obj_lock);
3533 * creates new preallocated space for locality group inodes belongs to
3535 static noinline_for_stack int
3536 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3538 struct super_block *sb = ac->ac_sb;
3539 struct ext4_locality_group *lg;
3540 struct ext4_prealloc_space *pa;
3541 struct ext4_group_info *grp;
3543 /* preallocate only when found space is larger then requested */
3544 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3545 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3546 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3548 BUG_ON(ext4_pspace_cachep == NULL);
3549 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3553 /* preallocation can change ac_b_ex, thus we store actually
3554 * allocated blocks for history */
3555 ac->ac_f_ex = ac->ac_b_ex;
3557 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3558 pa->pa_lstart = pa->pa_pstart;
3559 pa->pa_len = ac->ac_b_ex.fe_len;
3560 pa->pa_free = pa->pa_len;
3561 atomic_set(&pa->pa_count, 1);
3562 spin_lock_init(&pa->pa_lock);
3563 INIT_LIST_HEAD(&pa->pa_inode_list);
3564 INIT_LIST_HEAD(&pa->pa_group_list);
3566 pa->pa_type = MB_GROUP_PA;
3568 mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3569 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3570 trace_ext4_mb_new_group_pa(ac, pa);
3572 ext4_mb_use_group_pa(ac, pa);
3573 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3575 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3579 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3580 pa->pa_inode = NULL;
3582 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3583 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3584 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3587 * We will later add the new pa to the right bucket
3588 * after updating the pa_free in ext4_mb_release_context
3593 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3597 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3598 err = ext4_mb_new_group_pa(ac);
3600 err = ext4_mb_new_inode_pa(ac);
3605 * finds all unused blocks in on-disk bitmap, frees them in
3606 * in-core bitmap and buddy.
3607 * @pa must be unlinked from inode and group lists, so that
3608 * nobody else can find/use it.
3609 * the caller MUST hold group/inode locks.
3610 * TODO: optimize the case when there are no in-core structures yet
3612 static noinline_for_stack int
3613 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3614 struct ext4_prealloc_space *pa)
3616 struct super_block *sb = e4b->bd_sb;
3617 struct ext4_sb_info *sbi = EXT4_SB(sb);
3622 unsigned long long grp_blk_start;
3626 BUG_ON(pa->pa_deleted == 0);
3627 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3628 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
3629 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3630 end = bit + pa->pa_len;
3633 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3636 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3637 mb_debug(1, " free preallocated %u/%u in group %u\n",
3638 (unsigned) ext4_group_first_block_no(sb, group) + bit,
3639 (unsigned) next - bit, (unsigned) group);
3642 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
3643 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
3644 EXT4_C2B(sbi, bit)),
3646 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3649 if (free != pa->pa_free) {
3650 ext4_msg(e4b->bd_sb, KERN_CRIT,
3651 "pa %p: logic %lu, phys. %lu, len %lu",
3652 pa, (unsigned long) pa->pa_lstart,
3653 (unsigned long) pa->pa_pstart,
3654 (unsigned long) pa->pa_len);
3655 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
3658 * pa is already deleted so we use the value obtained
3659 * from the bitmap and continue.
3662 atomic_add(free, &sbi->s_mb_discarded);
3667 static noinline_for_stack int
3668 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3669 struct ext4_prealloc_space *pa)
3671 struct super_block *sb = e4b->bd_sb;
3675 trace_ext4_mb_release_group_pa(pa);
3676 BUG_ON(pa->pa_deleted == 0);
3677 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3678 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3679 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3680 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3681 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3687 * releases all preallocations in given group
3689 * first, we need to decide discard policy:
3690 * - when do we discard
3692 * - how many do we discard
3693 * 1) how many requested
3695 static noinline_for_stack int
3696 ext4_mb_discard_group_preallocations(struct super_block *sb,
3697 ext4_group_t group, int needed)
3699 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3700 struct buffer_head *bitmap_bh = NULL;
3701 struct ext4_prealloc_space *pa, *tmp;
3702 struct list_head list;
3703 struct ext4_buddy e4b;
3708 mb_debug(1, "discard preallocation for group %u\n", group);
3710 if (list_empty(&grp->bb_prealloc_list))
3713 bitmap_bh = ext4_read_block_bitmap(sb, group);
3714 if (bitmap_bh == NULL) {
3715 ext4_error(sb, "Error reading block bitmap for %u", group);
3719 err = ext4_mb_load_buddy(sb, group, &e4b);
3721 ext4_error(sb, "Error loading buddy information for %u", group);
3727 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
3729 INIT_LIST_HEAD(&list);
3731 ext4_lock_group(sb, group);
3732 list_for_each_entry_safe(pa, tmp,
3733 &grp->bb_prealloc_list, pa_group_list) {
3734 spin_lock(&pa->pa_lock);
3735 if (atomic_read(&pa->pa_count)) {
3736 spin_unlock(&pa->pa_lock);
3740 if (pa->pa_deleted) {
3741 spin_unlock(&pa->pa_lock);
3745 /* seems this one can be freed ... */
3748 /* we can trust pa_free ... */
3749 free += pa->pa_free;
3751 spin_unlock(&pa->pa_lock);
3753 list_del(&pa->pa_group_list);
3754 list_add(&pa->u.pa_tmp_list, &list);
3757 /* if we still need more blocks and some PAs were used, try again */
3758 if (free < needed && busy) {
3760 ext4_unlock_group(sb, group);
3762 * Yield the CPU here so that we don't get soft lockup
3763 * in non preempt case.
3769 /* found anything to free? */
3770 if (list_empty(&list)) {
3775 /* now free all selected PAs */
3776 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3778 /* remove from object (inode or locality group) */
3779 spin_lock(pa->pa_obj_lock);
3780 list_del_rcu(&pa->pa_inode_list);
3781 spin_unlock(pa->pa_obj_lock);
3783 if (pa->pa_type == MB_GROUP_PA)
3784 ext4_mb_release_group_pa(&e4b, pa);
3786 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3788 list_del(&pa->u.pa_tmp_list);
3789 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3793 ext4_unlock_group(sb, group);
3794 ext4_mb_unload_buddy(&e4b);
3800 * releases all non-used preallocated blocks for given inode
3802 * It's important to discard preallocations under i_data_sem
3803 * We don't want another block to be served from the prealloc
3804 * space when we are discarding the inode prealloc space.
3806 * FIXME!! Make sure it is valid at all the call sites
3808 void ext4_discard_preallocations(struct inode *inode)
3810 struct ext4_inode_info *ei = EXT4_I(inode);
3811 struct super_block *sb = inode->i_sb;
3812 struct buffer_head *bitmap_bh = NULL;
3813 struct ext4_prealloc_space *pa, *tmp;
3814 ext4_group_t group = 0;
3815 struct list_head list;
3816 struct ext4_buddy e4b;
3819 if (!S_ISREG(inode->i_mode)) {
3820 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
3824 mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
3825 trace_ext4_discard_preallocations(inode);
3827 INIT_LIST_HEAD(&list);
3830 /* first, collect all pa's in the inode */
3831 spin_lock(&ei->i_prealloc_lock);
3832 while (!list_empty(&ei->i_prealloc_list)) {
3833 pa = list_entry(ei->i_prealloc_list.next,
3834 struct ext4_prealloc_space, pa_inode_list);
3835 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
3836 spin_lock(&pa->pa_lock);
3837 if (atomic_read(&pa->pa_count)) {
3838 /* this shouldn't happen often - nobody should
3839 * use preallocation while we're discarding it */
3840 spin_unlock(&pa->pa_lock);
3841 spin_unlock(&ei->i_prealloc_lock);
3842 ext4_msg(sb, KERN_ERR,
3843 "uh-oh! used pa while discarding");
3845 schedule_timeout_uninterruptible(HZ);
3849 if (pa->pa_deleted == 0) {
3851 spin_unlock(&pa->pa_lock);
3852 list_del_rcu(&pa->pa_inode_list);
3853 list_add(&pa->u.pa_tmp_list, &list);
3857 /* someone is deleting pa right now */
3858 spin_unlock(&pa->pa_lock);
3859 spin_unlock(&ei->i_prealloc_lock);
3861 /* we have to wait here because pa_deleted
3862 * doesn't mean pa is already unlinked from
3863 * the list. as we might be called from
3864 * ->clear_inode() the inode will get freed
3865 * and concurrent thread which is unlinking
3866 * pa from inode's list may access already
3867 * freed memory, bad-bad-bad */
3869 /* XXX: if this happens too often, we can
3870 * add a flag to force wait only in case
3871 * of ->clear_inode(), but not in case of
3872 * regular truncate */
3873 schedule_timeout_uninterruptible(HZ);
3876 spin_unlock(&ei->i_prealloc_lock);
3878 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3879 BUG_ON(pa->pa_type != MB_INODE_PA);
3880 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
3882 err = ext4_mb_load_buddy(sb, group, &e4b);
3884 ext4_error(sb, "Error loading buddy information for %u",
3889 bitmap_bh = ext4_read_block_bitmap(sb, group);
3890 if (bitmap_bh == NULL) {
3891 ext4_error(sb, "Error reading block bitmap for %u",
3893 ext4_mb_unload_buddy(&e4b);
3897 ext4_lock_group(sb, group);
3898 list_del(&pa->pa_group_list);
3899 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3900 ext4_unlock_group(sb, group);
3902 ext4_mb_unload_buddy(&e4b);
3905 list_del(&pa->u.pa_tmp_list);
3906 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3910 #ifdef CONFIG_EXT4_DEBUG
3911 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3913 struct super_block *sb = ac->ac_sb;
3914 ext4_group_t ngroups, i;
3916 if (!mb_enable_debug ||
3917 (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
3920 ext4_msg(ac->ac_sb, KERN_ERR, "EXT4-fs: Can't allocate:"
3921 " Allocation context details:");
3922 ext4_msg(ac->ac_sb, KERN_ERR, "EXT4-fs: status %d flags %d",
3923 ac->ac_status, ac->ac_flags);
3924 ext4_msg(ac->ac_sb, KERN_ERR, "EXT4-fs: orig %lu/%lu/%lu@%lu, "
3925 "goal %lu/%lu/%lu@%lu, "
3926 "best %lu/%lu/%lu@%lu cr %d",
3927 (unsigned long)ac->ac_o_ex.fe_group,
3928 (unsigned long)ac->ac_o_ex.fe_start,
3929 (unsigned long)ac->ac_o_ex.fe_len,
3930 (unsigned long)ac->ac_o_ex.fe_logical,
3931 (unsigned long)ac->ac_g_ex.fe_group,
3932 (unsigned long)ac->ac_g_ex.fe_start,
3933 (unsigned long)ac->ac_g_ex.fe_len,
3934 (unsigned long)ac->ac_g_ex.fe_logical,
3935 (unsigned long)ac->ac_b_ex.fe_group,
3936 (unsigned long)ac->ac_b_ex.fe_start,
3937 (unsigned long)ac->ac_b_ex.fe_len,
3938 (unsigned long)ac->ac_b_ex.fe_logical,
3939 (int)ac->ac_criteria);
3940 ext4_msg(ac->ac_sb, KERN_ERR, "EXT4-fs: %lu scanned, %d found",
3941 ac->ac_ex_scanned, ac->ac_found);
3942 ext4_msg(ac->ac_sb, KERN_ERR, "EXT4-fs: groups: ");
3943 ngroups = ext4_get_groups_count(sb);
3944 for (i = 0; i < ngroups; i++) {
3945 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3946 struct ext4_prealloc_space *pa;
3947 ext4_grpblk_t start;
3948 struct list_head *cur;
3949 ext4_lock_group(sb, i);
3950 list_for_each(cur, &grp->bb_prealloc_list) {
3951 pa = list_entry(cur, struct ext4_prealloc_space,
3953 spin_lock(&pa->pa_lock);
3954 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3956 spin_unlock(&pa->pa_lock);
3957 printk(KERN_ERR "PA:%u:%d:%u \n", i,
3960 ext4_unlock_group(sb, i);
3962 if (grp->bb_free == 0)
3964 printk(KERN_ERR "%u: %d/%d \n",
3965 i, grp->bb_free, grp->bb_fragments);
3967 printk(KERN_ERR "\n");
3970 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3977 * We use locality group preallocation for small size file. The size of the
3978 * file is determined by the current size or the resulting size after
3979 * allocation which ever is larger
3981 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
3983 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
3985 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3986 int bsbits = ac->ac_sb->s_blocksize_bits;
3989 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3992 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3995 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
3996 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
3999 if ((size == isize) &&
4000 !ext4_fs_is_busy(sbi) &&
4001 (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
4002 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
4006 if (sbi->s_mb_group_prealloc <= 0) {
4007 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4011 /* don't use group allocation for large files */
4012 size = max(size, isize);
4013 if (size > sbi->s_mb_stream_request) {
4014 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4018 BUG_ON(ac->ac_lg != NULL);
4020 * locality group prealloc space are per cpu. The reason for having
4021 * per cpu locality group is to reduce the contention between block
4022 * request from multiple CPUs.
4024 ac->ac_lg = __this_cpu_ptr(sbi->s_locality_groups);
4026 /* we're going to use group allocation */
4027 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4029 /* serialize all allocations in the group */
4030 mutex_lock(&ac->ac_lg->lg_mutex);
4033 static noinline_for_stack int
4034 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4035 struct ext4_allocation_request *ar)
4037 struct super_block *sb = ar->inode->i_sb;
4038 struct ext4_sb_info *sbi = EXT4_SB(sb);
4039 struct ext4_super_block *es = sbi->s_es;
4043 ext4_grpblk_t block;
4045 /* we can't allocate > group size */
4048 /* just a dirty hack to filter too big requests */
4049 if (len >= EXT4_CLUSTERS_PER_GROUP(sb) - 10)
4050 len = EXT4_CLUSTERS_PER_GROUP(sb) - 10;
4052 /* start searching from the goal */
4054 if (goal < le32_to_cpu(es->s_first_data_block) ||
4055 goal >= ext4_blocks_count(es))
4056 goal = le32_to_cpu(es->s_first_data_block);
4057 ext4_get_group_no_and_offset(sb, goal, &group, &block);
4059 /* set up allocation goals */
4060 memset(ac, 0, sizeof(struct ext4_allocation_context));
4061 ac->ac_b_ex.fe_logical = ar->logical & ~(sbi->s_cluster_ratio - 1);
4062 ac->ac_status = AC_STATUS_CONTINUE;
4064 ac->ac_inode = ar->inode;
4065 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4066 ac->ac_o_ex.fe_group = group;
4067 ac->ac_o_ex.fe_start = block;
4068 ac->ac_o_ex.fe_len = len;
4069 ac->ac_g_ex = ac->ac_o_ex;
4070 ac->ac_flags = ar->flags;
4072 /* we have to define context: we'll we work with a file or
4073 * locality group. this is a policy, actually */
4074 ext4_mb_group_or_file(ac);
4076 mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4077 "left: %u/%u, right %u/%u to %swritable\n",
4078 (unsigned) ar->len, (unsigned) ar->logical,
4079 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4080 (unsigned) ar->lleft, (unsigned) ar->pleft,
4081 (unsigned) ar->lright, (unsigned) ar->pright,
4082 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4087 static noinline_for_stack void
4088 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4089 struct ext4_locality_group *lg,
4090 int order, int total_entries)
4092 ext4_group_t group = 0;
4093 struct ext4_buddy e4b;
4094 struct list_head discard_list;
4095 struct ext4_prealloc_space *pa, *tmp;
4097 mb_debug(1, "discard locality group preallocation\n");
4099 INIT_LIST_HEAD(&discard_list);
4101 spin_lock(&lg->lg_prealloc_lock);
4102 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4104 spin_lock(&pa->pa_lock);
4105 if (atomic_read(&pa->pa_count)) {
4107 * This is the pa that we just used
4108 * for block allocation. So don't
4111 spin_unlock(&pa->pa_lock);
4114 if (pa->pa_deleted) {
4115 spin_unlock(&pa->pa_lock);
4118 /* only lg prealloc space */
4119 BUG_ON(pa->pa_type != MB_GROUP_PA);
4121 /* seems this one can be freed ... */
4123 spin_unlock(&pa->pa_lock);
4125 list_del_rcu(&pa->pa_inode_list);
4126 list_add(&pa->u.pa_tmp_list, &discard_list);
4129 if (total_entries <= 5) {
4131 * we want to keep only 5 entries
4132 * allowing it to grow to 8. This
4133 * mak sure we don't call discard
4134 * soon for this list.
4139 spin_unlock(&lg->lg_prealloc_lock);
4141 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4143 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
4144 if (ext4_mb_load_buddy(sb, group, &e4b)) {
4145 ext4_error(sb, "Error loading buddy information for %u",
4149 ext4_lock_group(sb, group);
4150 list_del(&pa->pa_group_list);
4151 ext4_mb_release_group_pa(&e4b, pa);
4152 ext4_unlock_group(sb, group);
4154 ext4_mb_unload_buddy(&e4b);
4155 list_del(&pa->u.pa_tmp_list);
4156 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4161 * We have incremented pa_count. So it cannot be freed at this
4162 * point. Also we hold lg_mutex. So no parallel allocation is
4163 * possible from this lg. That means pa_free cannot be updated.
4165 * A parallel ext4_mb_discard_group_preallocations is possible.
4166 * which can cause the lg_prealloc_list to be updated.
4169 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4171 int order, added = 0, lg_prealloc_count = 1;
4172 struct super_block *sb = ac->ac_sb;
4173 struct ext4_locality_group *lg = ac->ac_lg;
4174 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4176 order = fls(pa->pa_free) - 1;
4177 if (order > PREALLOC_TB_SIZE - 1)
4178 /* The max size of hash table is PREALLOC_TB_SIZE */
4179 order = PREALLOC_TB_SIZE - 1;
4180 /* Add the prealloc space to lg */
4182 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4184 spin_lock(&tmp_pa->pa_lock);
4185 if (tmp_pa->pa_deleted) {
4186 spin_unlock(&tmp_pa->pa_lock);
4189 if (!added && pa->pa_free < tmp_pa->pa_free) {
4190 /* Add to the tail of the previous entry */
4191 list_add_tail_rcu(&pa->pa_inode_list,
4192 &tmp_pa->pa_inode_list);
4195 * we want to count the total
4196 * number of entries in the list
4199 spin_unlock(&tmp_pa->pa_lock);
4200 lg_prealloc_count++;
4203 list_add_tail_rcu(&pa->pa_inode_list,
4204 &lg->lg_prealloc_list[order]);
4207 /* Now trim the list to be not more than 8 elements */
4208 if (lg_prealloc_count > 8) {
4209 ext4_mb_discard_lg_preallocations(sb, lg,
4210 order, lg_prealloc_count);
4217 * release all resource we used in allocation
4219 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4221 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4222 struct ext4_prealloc_space *pa = ac->ac_pa;
4224 if (pa->pa_type == MB_GROUP_PA) {
4225 /* see comment in ext4_mb_use_group_pa() */
4226 spin_lock(&pa->pa_lock);
4227 pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4228 pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4229 pa->pa_free -= ac->ac_b_ex.fe_len;
4230 pa->pa_len -= ac->ac_b_ex.fe_len;
4231 spin_unlock(&pa->pa_lock);
4236 * We want to add the pa to the right bucket.
4237 * Remove it from the list and while adding
4238 * make sure the list to which we are adding
4241 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4242 spin_lock(pa->pa_obj_lock);
4243 list_del_rcu(&pa->pa_inode_list);
4244 spin_unlock(pa->pa_obj_lock);
4245 ext4_mb_add_n_trim(ac);
4247 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4249 if (ac->ac_bitmap_page)
4250 page_cache_release(ac->ac_bitmap_page);
4251 if (ac->ac_buddy_page)
4252 page_cache_release(ac->ac_buddy_page);
4253 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4254 mutex_unlock(&ac->ac_lg->lg_mutex);
4255 ext4_mb_collect_stats(ac);
4259 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4261 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4265 trace_ext4_mb_discard_preallocations(sb, needed);
4266 for (i = 0; i < ngroups && needed > 0; i++) {
4267 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4276 * Main entry point into mballoc to allocate blocks
4277 * it tries to use preallocation first, then falls back
4278 * to usual allocation
4280 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4281 struct ext4_allocation_request *ar, int *errp)
4284 struct ext4_allocation_context *ac = NULL;
4285 struct ext4_sb_info *sbi;
4286 struct super_block *sb;
4287 ext4_fsblk_t block = 0;
4288 unsigned int inquota = 0;
4289 unsigned int reserv_clstrs = 0;
4291 sb = ar->inode->i_sb;
4294 trace_ext4_request_blocks(ar);
4296 /* Allow to use superuser reservation for quota file */
4297 if (IS_NOQUOTA(ar->inode))
4298 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
4301 * For delayed allocation, we could skip the ENOSPC and
4302 * EDQUOT check, as blocks and quotas have been already
4303 * reserved when data being copied into pagecache.
4305 if (ext4_test_inode_state(ar->inode, EXT4_STATE_DELALLOC_RESERVED))
4306 ar->flags |= EXT4_MB_DELALLOC_RESERVED;
4308 /* Without delayed allocation we need to verify
4309 * there is enough free blocks to do block allocation
4310 * and verify allocation doesn't exceed the quota limits.
4313 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
4315 /* let others to free the space */
4317 ar->len = ar->len >> 1;
4323 reserv_clstrs = ar->len;
4324 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
4325 dquot_alloc_block_nofail(ar->inode,
4326 EXT4_C2B(sbi, ar->len));
4329 dquot_alloc_block(ar->inode,
4330 EXT4_C2B(sbi, ar->len))) {
4332 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4343 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4350 *errp = ext4_mb_initialize_context(ac, ar);
4356 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4357 if (!ext4_mb_use_preallocated(ac)) {
4358 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4359 ext4_mb_normalize_request(ac, ar);
4361 /* allocate space in core */
4362 *errp = ext4_mb_regular_allocator(ac);
4366 /* as we've just preallocated more space than
4367 * user requested orinally, we store allocated
4368 * space in a special descriptor */
4369 if (ac->ac_status == AC_STATUS_FOUND &&
4370 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4371 ext4_mb_new_preallocation(ac);
4373 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4374 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4375 if (*errp == -EAGAIN) {
4377 * drop the reference that we took
4378 * in ext4_mb_use_best_found
4380 ext4_mb_release_context(ac);
4381 ac->ac_b_ex.fe_group = 0;
4382 ac->ac_b_ex.fe_start = 0;
4383 ac->ac_b_ex.fe_len = 0;
4384 ac->ac_status = AC_STATUS_CONTINUE;
4388 ext4_discard_allocated_blocks(ac);
4390 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4391 ar->len = ac->ac_b_ex.fe_len;
4394 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4401 ac->ac_b_ex.fe_len = 0;
4403 ext4_mb_show_ac(ac);
4405 ext4_mb_release_context(ac);
4408 kmem_cache_free(ext4_ac_cachep, ac);
4409 if (inquota && ar->len < inquota)
4410 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
4412 if (!ext4_test_inode_state(ar->inode,
4413 EXT4_STATE_DELALLOC_RESERVED))
4414 /* release all the reserved blocks if non delalloc */
4415 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4419 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4425 * We can merge two free data extents only if the physical blocks
4426 * are contiguous, AND the extents were freed by the same transaction,
4427 * AND the blocks are associated with the same group.
4429 static int can_merge(struct ext4_free_data *entry1,
4430 struct ext4_free_data *entry2)
4432 if ((entry1->t_tid == entry2->t_tid) &&
4433 (entry1->group == entry2->group) &&
4434 ((entry1->start_cluster + entry1->count) == entry2->start_cluster))
4439 static noinline_for_stack int
4440 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4441 struct ext4_free_data *new_entry)
4443 ext4_group_t group = e4b->bd_group;
4444 ext4_grpblk_t cluster;
4445 struct ext4_free_data *entry;
4446 struct ext4_group_info *db = e4b->bd_info;
4447 struct super_block *sb = e4b->bd_sb;
4448 struct ext4_sb_info *sbi = EXT4_SB(sb);
4449 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4450 struct rb_node *parent = NULL, *new_node;
4452 BUG_ON(!ext4_handle_valid(handle));
4453 BUG_ON(e4b->bd_bitmap_page == NULL);
4454 BUG_ON(e4b->bd_buddy_page == NULL);
4456 new_node = &new_entry->node;
4457 cluster = new_entry->start_cluster;
4460 /* first free block exent. We need to
4461 protect buddy cache from being freed,
4462 * otherwise we'll refresh it from
4463 * on-disk bitmap and lose not-yet-available
4465 page_cache_get(e4b->bd_buddy_page);
4466 page_cache_get(e4b->bd_bitmap_page);
4470 entry = rb_entry(parent, struct ext4_free_data, node);
4471 if (cluster < entry->start_cluster)
4473 else if (cluster >= (entry->start_cluster + entry->count))
4474 n = &(*n)->rb_right;
4476 ext4_grp_locked_error(sb, group, 0,
4477 ext4_group_first_block_no(sb, group) +
4478 EXT4_C2B(sbi, cluster),
4479 "Block already on to-be-freed list");
4484 rb_link_node(new_node, parent, n);
4485 rb_insert_color(new_node, &db->bb_free_root);
4487 /* Now try to see the extent can be merged to left and right */
4488 node = rb_prev(new_node);
4490 entry = rb_entry(node, struct ext4_free_data, node);
4491 if (can_merge(entry, new_entry)) {
4492 new_entry->start_cluster = entry->start_cluster;
4493 new_entry->count += entry->count;
4494 rb_erase(node, &(db->bb_free_root));
4495 spin_lock(&sbi->s_md_lock);
4496 list_del(&entry->list);
4497 spin_unlock(&sbi->s_md_lock);
4498 kmem_cache_free(ext4_free_ext_cachep, entry);
4502 node = rb_next(new_node);
4504 entry = rb_entry(node, struct ext4_free_data, node);
4505 if (can_merge(new_entry, entry)) {
4506 new_entry->count += entry->count;
4507 rb_erase(node, &(db->bb_free_root));
4508 spin_lock(&sbi->s_md_lock);
4509 list_del(&entry->list);
4510 spin_unlock(&sbi->s_md_lock);
4511 kmem_cache_free(ext4_free_ext_cachep, entry);
4514 /* Add the extent to transaction's private list */
4515 spin_lock(&sbi->s_md_lock);
4516 list_add(&new_entry->list, &handle->h_transaction->t_private_list);
4517 spin_unlock(&sbi->s_md_lock);
4522 * ext4_free_blocks() -- Free given blocks and update quota
4523 * @handle: handle for this transaction
4525 * @block: start physical block to free
4526 * @count: number of blocks to count
4527 * @flags: flags used by ext4_free_blocks
4529 void ext4_free_blocks(handle_t *handle, struct inode *inode,
4530 struct buffer_head *bh, ext4_fsblk_t block,
4531 unsigned long count, int flags)
4533 struct buffer_head *bitmap_bh = NULL;
4534 struct super_block *sb = inode->i_sb;
4535 struct ext4_group_desc *gdp;
4536 unsigned long freed = 0;
4537 unsigned int overflow;
4539 struct buffer_head *gd_bh;
4540 ext4_group_t block_group;
4541 struct ext4_sb_info *sbi;
4542 struct ext4_buddy e4b;
4543 unsigned int count_clusters;
4549 BUG_ON(block != bh->b_blocknr);
4551 block = bh->b_blocknr;
4555 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
4556 !ext4_data_block_valid(sbi, block, count)) {
4557 ext4_error(sb, "Freeing blocks not in datazone - "
4558 "block = %llu, count = %lu", block, count);
4562 ext4_debug("freeing block %llu\n", block);
4563 trace_ext4_free_blocks(inode, block, count, flags);
4565 if (flags & EXT4_FREE_BLOCKS_FORGET) {
4566 struct buffer_head *tbh = bh;
4569 BUG_ON(bh && (count > 1));
4571 for (i = 0; i < count; i++) {
4573 tbh = sb_find_get_block(inode->i_sb,
4577 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4578 inode, tbh, block + i);
4583 * We need to make sure we don't reuse the freed block until
4584 * after the transaction is committed, which we can do by
4585 * treating the block as metadata, below. We make an
4586 * exception if the inode is to be written in writeback mode
4587 * since writeback mode has weak data consistency guarantees.
4589 if (!ext4_should_writeback_data(inode))
4590 flags |= EXT4_FREE_BLOCKS_METADATA;
4593 * If the extent to be freed does not begin on a cluster
4594 * boundary, we need to deal with partial clusters at the
4595 * beginning and end of the extent. Normally we will free
4596 * blocks at the beginning or the end unless we are explicitly
4597 * requested to avoid doing so.
4599 overflow = block & (sbi->s_cluster_ratio - 1);
4601 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
4602 overflow = sbi->s_cluster_ratio - overflow;
4604 if (count > overflow)
4613 overflow = count & (sbi->s_cluster_ratio - 1);
4615 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
4616 if (count > overflow)
4621 count += sbi->s_cluster_ratio - overflow;
4626 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4629 * Check to see if we are freeing blocks across a group
4632 if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4633 overflow = EXT4_C2B(sbi, bit) + count -
4634 EXT4_BLOCKS_PER_GROUP(sb);
4637 count_clusters = EXT4_B2C(sbi, count);
4638 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4643 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4649 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4650 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4651 in_range(block, ext4_inode_table(sb, gdp),
4652 EXT4_SB(sb)->s_itb_per_group) ||
4653 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4654 EXT4_SB(sb)->s_itb_per_group)) {
4656 ext4_error(sb, "Freeing blocks in system zone - "
4657 "Block = %llu, count = %lu", block, count);
4658 /* err = 0. ext4_std_error should be a no op */
4662 BUFFER_TRACE(bitmap_bh, "getting write access");
4663 err = ext4_journal_get_write_access(handle, bitmap_bh);
4668 * We are about to modify some metadata. Call the journal APIs
4669 * to unshare ->b_data if a currently-committing transaction is
4672 BUFFER_TRACE(gd_bh, "get_write_access");
4673 err = ext4_journal_get_write_access(handle, gd_bh);
4676 #ifdef AGGRESSIVE_CHECK
4679 for (i = 0; i < count_clusters; i++)
4680 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4683 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
4685 err = ext4_mb_load_buddy(sb, block_group, &e4b);
4689 if ((flags & EXT4_FREE_BLOCKS_METADATA) && ext4_handle_valid(handle)) {
4690 struct ext4_free_data *new_entry;
4692 * blocks being freed are metadata. these blocks shouldn't
4693 * be used until this transaction is committed
4695 new_entry = kmem_cache_alloc(ext4_free_ext_cachep, GFP_NOFS);
4697 ext4_mb_unload_buddy(&e4b);
4701 new_entry->start_cluster = bit;
4702 new_entry->group = block_group;
4703 new_entry->count = count_clusters;
4704 new_entry->t_tid = handle->h_transaction->t_tid;
4706 ext4_lock_group(sb, block_group);
4707 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4708 ext4_mb_free_metadata(handle, &e4b, new_entry);
4710 /* need to update group_info->bb_free and bitmap
4711 * with group lock held. generate_buddy look at
4712 * them with group lock_held
4714 ext4_lock_group(sb, block_group);
4715 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4716 mb_free_blocks(inode, &e4b, bit, count_clusters);
4719 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
4720 ext4_free_group_clusters_set(sb, gdp, ret);
4721 gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4722 ext4_unlock_group(sb, block_group);
4723 percpu_counter_add(&sbi->s_freeclusters_counter, count_clusters);
4725 if (sbi->s_log_groups_per_flex) {
4726 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4727 atomic_add(count_clusters,
4728 &sbi->s_flex_groups[flex_group].free_clusters);
4731 ext4_mb_unload_buddy(&e4b);
4735 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
4736 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
4738 /* We dirtied the bitmap block */
4739 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4740 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4742 /* And the group descriptor block */
4743 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4744 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4748 if (overflow && !err) {
4754 ext4_mark_super_dirty(sb);
4757 ext4_std_error(sb, err);
4762 * ext4_group_add_blocks() -- Add given blocks to an existing group
4763 * @handle: handle to this transaction
4765 * @block: start physcial block to add to the block group
4766 * @count: number of blocks to free
4768 * This marks the blocks as free in the bitmap and buddy.
4770 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
4771 ext4_fsblk_t block, unsigned long count)
4773 struct buffer_head *bitmap_bh = NULL;
4774 struct buffer_head *gd_bh;
4775 ext4_group_t block_group;
4778 struct ext4_group_desc *desc;
4779 struct ext4_sb_info *sbi = EXT4_SB(sb);
4780 struct ext4_buddy e4b;
4781 int err = 0, ret, blk_free_count;
4782 ext4_grpblk_t blocks_freed;
4784 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
4789 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4791 * Check to see if we are freeing blocks across a group
4794 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4795 ext4_warning(sb, "too much blocks added to group %u\n",
4801 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4807 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
4813 if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
4814 in_range(ext4_inode_bitmap(sb, desc), block, count) ||
4815 in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
4816 in_range(block + count - 1, ext4_inode_table(sb, desc),
4817 sbi->s_itb_per_group)) {
4818 ext4_error(sb, "Adding blocks in system zones - "
4819 "Block = %llu, count = %lu",
4825 BUFFER_TRACE(bitmap_bh, "getting write access");
4826 err = ext4_journal_get_write_access(handle, bitmap_bh);
4831 * We are about to modify some metadata. Call the journal APIs
4832 * to unshare ->b_data if a currently-committing transaction is
4835 BUFFER_TRACE(gd_bh, "get_write_access");
4836 err = ext4_journal_get_write_access(handle, gd_bh);
4840 for (i = 0, blocks_freed = 0; i < count; i++) {
4841 BUFFER_TRACE(bitmap_bh, "clear bit");
4842 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
4843 ext4_error(sb, "bit already cleared for block %llu",
4844 (ext4_fsblk_t)(block + i));
4845 BUFFER_TRACE(bitmap_bh, "bit already cleared");
4851 err = ext4_mb_load_buddy(sb, block_group, &e4b);
4856 * need to update group_info->bb_free and bitmap
4857 * with group lock held. generate_buddy look at
4858 * them with group lock_held
4860 ext4_lock_group(sb, block_group);
4861 mb_clear_bits(bitmap_bh->b_data, bit, count);
4862 mb_free_blocks(NULL, &e4b, bit, count);
4863 blk_free_count = blocks_freed + ext4_free_group_clusters(sb, desc);
4864 ext4_free_group_clusters_set(sb, desc, blk_free_count);
4865 desc->bg_checksum = ext4_group_desc_csum(sbi, block_group, desc);
4866 ext4_unlock_group(sb, block_group);
4867 percpu_counter_add(&sbi->s_freeclusters_counter,
4868 EXT4_B2C(sbi, blocks_freed));
4870 if (sbi->s_log_groups_per_flex) {
4871 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4872 atomic_add(EXT4_B2C(sbi, blocks_freed),
4873 &sbi->s_flex_groups[flex_group].free_clusters);
4876 ext4_mb_unload_buddy(&e4b);
4878 /* We dirtied the bitmap block */
4879 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4880 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4882 /* And the group descriptor block */
4883 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4884 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4890 ext4_std_error(sb, err);
4895 * ext4_trim_extent -- function to TRIM one single free extent in the group
4896 * @sb: super block for the file system
4897 * @start: starting block of the free extent in the alloc. group
4898 * @count: number of blocks to TRIM
4899 * @group: alloc. group we are working with
4900 * @e4b: ext4 buddy for the group
4902 * Trim "count" blocks starting at "start" in the "group". To assure that no
4903 * one will allocate those blocks, mark it as used in buddy bitmap. This must
4904 * be called with under the group lock.
4906 static void ext4_trim_extent(struct super_block *sb, int start, int count,
4907 ext4_group_t group, struct ext4_buddy *e4b)
4909 struct ext4_free_extent ex;
4911 trace_ext4_trim_extent(sb, group, start, count);
4913 assert_spin_locked(ext4_group_lock_ptr(sb, group));
4915 ex.fe_start = start;
4916 ex.fe_group = group;
4920 * Mark blocks used, so no one can reuse them while
4923 mb_mark_used(e4b, &ex);
4924 ext4_unlock_group(sb, group);
4925 ext4_issue_discard(sb, group, start, count);
4926 ext4_lock_group(sb, group);
4927 mb_free_blocks(NULL, e4b, start, ex.fe_len);
4931 * ext4_trim_all_free -- function to trim all free space in alloc. group
4932 * @sb: super block for file system
4933 * @group: group to be trimmed
4934 * @start: first group block to examine
4935 * @max: last group block to examine
4936 * @minblocks: minimum extent block count
4938 * ext4_trim_all_free walks through group's buddy bitmap searching for free
4939 * extents. When the free block is found, ext4_trim_extent is called to TRIM
4943 * ext4_trim_all_free walks through group's block bitmap searching for free
4944 * extents. When the free extent is found, mark it as used in group buddy
4945 * bitmap. Then issue a TRIM command on this extent and free the extent in
4946 * the group buddy bitmap. This is done until whole group is scanned.
4948 static ext4_grpblk_t
4949 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
4950 ext4_grpblk_t start, ext4_grpblk_t max,
4951 ext4_grpblk_t minblocks)
4954 ext4_grpblk_t next, count = 0, free_count = 0;
4955 struct ext4_buddy e4b;
4958 trace_ext4_trim_all_free(sb, group, start, max);
4960 ret = ext4_mb_load_buddy(sb, group, &e4b);
4962 ext4_error(sb, "Error in loading buddy "
4963 "information for %u", group);
4966 bitmap = e4b.bd_bitmap;
4968 ext4_lock_group(sb, group);
4969 if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
4970 minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
4973 start = (e4b.bd_info->bb_first_free > start) ?
4974 e4b.bd_info->bb_first_free : start;
4976 while (start < max) {
4977 start = mb_find_next_zero_bit(bitmap, max, start);
4980 next = mb_find_next_bit(bitmap, max, start);
4982 if ((next - start) >= minblocks) {
4983 ext4_trim_extent(sb, start,
4984 next - start, group, &e4b);
4985 count += next - start;
4987 free_count += next - start;
4990 if (fatal_signal_pending(current)) {
4991 count = -ERESTARTSYS;
4995 if (need_resched()) {
4996 ext4_unlock_group(sb, group);
4998 ext4_lock_group(sb, group);
5001 if ((e4b.bd_info->bb_free - free_count) < minblocks)
5006 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
5008 ext4_unlock_group(sb, group);
5009 ext4_mb_unload_buddy(&e4b);
5011 ext4_debug("trimmed %d blocks in the group %d\n",
5018 * ext4_trim_fs() -- trim ioctl handle function
5019 * @sb: superblock for filesystem
5020 * @range: fstrim_range structure
5022 * start: First Byte to trim
5023 * len: number of Bytes to trim from start
5024 * minlen: minimum extent length in Bytes
5025 * ext4_trim_fs goes through all allocation groups containing Bytes from
5026 * start to start+len. For each such a group ext4_trim_all_free function
5027 * is invoked to trim all free space.
5029 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
5031 struct ext4_group_info *grp;
5032 ext4_group_t first_group, last_group;
5033 ext4_group_t group, ngroups = ext4_get_groups_count(sb);
5034 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5035 uint64_t start, len, minlen, trimmed = 0;
5036 ext4_fsblk_t first_data_blk =
5037 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5040 start = range->start >> sb->s_blocksize_bits;
5041 len = range->len >> sb->s_blocksize_bits;
5042 minlen = range->minlen >> sb->s_blocksize_bits;
5044 if (unlikely(minlen > EXT4_CLUSTERS_PER_GROUP(sb)))
5046 if (start + len <= first_data_blk)
5048 if (start < first_data_blk) {
5049 len -= first_data_blk - start;
5050 start = first_data_blk;
5053 /* Determine first and last group to examine based on start and len */
5054 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
5055 &first_group, &first_cluster);
5056 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) (start + len),
5057 &last_group, &last_cluster);
5058 last_group = (last_group > ngroups - 1) ? ngroups - 1 : last_group;
5059 last_cluster = EXT4_CLUSTERS_PER_GROUP(sb);
5061 if (first_group > last_group)
5064 for (group = first_group; group <= last_group; group++) {
5065 grp = ext4_get_group_info(sb, group);
5066 /* We only do this if the grp has never been initialized */
5067 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
5068 ret = ext4_mb_init_group(sb, group);
5074 * For all the groups except the last one, last block will
5075 * always be EXT4_BLOCKS_PER_GROUP(sb), so we only need to
5076 * change it for the last group in which case start +
5077 * len < EXT4_BLOCKS_PER_GROUP(sb).
5079 if (first_cluster + len < EXT4_CLUSTERS_PER_GROUP(sb))
5080 last_cluster = first_cluster + len;
5081 len -= last_cluster - first_cluster;
5083 if (grp->bb_free >= minlen) {
5084 cnt = ext4_trim_all_free(sb, group, first_cluster,
5085 last_cluster, minlen);
5094 range->len = trimmed * sb->s_blocksize;
5097 atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);