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
74 * pa_free -> free space available in this prealloc space
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 make sure that
79 * that the 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 repreasented 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. Default value of s_mb_group_prealloc is
130 * 512 blocks. This can be tuned via
131 * /sys/fs/ext4/<partition/mb_group_prealloc. The value is represented in
132 * terms of number of blocks. If we have mounted the file system with -O
133 * stripe=<value> option the group prealloc request is normalized to the
134 * stripe value (sbi->s_stripe)
136 * The regular allocator(using the buddy cache) supports few tunables.
138 * /sys/fs/ext4/<partition>/mb_min_to_scan
139 * /sys/fs/ext4/<partition>/mb_max_to_scan
140 * /sys/fs/ext4/<partition>/mb_order2_req
142 * The regular allocator uses buddy scan only if the request len is power of
143 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
144 * value of s_mb_order2_reqs can be tuned via
145 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
146 * stripe size (sbi->s_stripe), we try to search for contiguous block in
147 * stripe size. This should result in better allocation on RAID setups. If
148 * not, we search in the specific group using bitmap for best extents. The
149 * tunable min_to_scan and max_to_scan control the behaviour here.
150 * min_to_scan indicate how long the mballoc __must__ look for a best
151 * extent and max_to_scan indicates how long the mballoc __can__ look for a
152 * best extent in the found extents. Searching for the blocks starts with
153 * the group specified as the goal value in allocation context via
154 * ac_g_ex. Each group is first checked based on the criteria whether it
155 * can used for allocation. ext4_mb_good_group explains how the groups are
158 * Both the prealloc space are getting populated as above. So for the first
159 * request we will hit the buddy cache which will result in this prealloc
160 * space getting filled. The prealloc space is then later used for the
161 * subsequent request.
165 * mballoc operates on the following data:
167 * - in-core buddy (actually includes buddy and bitmap)
168 * - preallocation descriptors (PAs)
170 * there are two types of preallocations:
172 * assiged to specific inode and can be used for this inode only.
173 * it describes part of inode's space preallocated to specific
174 * physical blocks. any block from that preallocated can be used
175 * independent. the descriptor just tracks number of blocks left
176 * unused. so, before taking some block from descriptor, one must
177 * make sure corresponded logical block isn't allocated yet. this
178 * also means that freeing any block within descriptor's range
179 * must discard all preallocated blocks.
181 * assigned to specific locality group which does not translate to
182 * permanent set of inodes: inode can join and leave group. space
183 * from this type of preallocation can be used for any inode. thus
184 * it's consumed from the beginning to the end.
186 * relation between them can be expressed as:
187 * in-core buddy = on-disk bitmap + preallocation descriptors
189 * this mean blocks mballoc considers used are:
190 * - allocated blocks (persistent)
191 * - preallocated blocks (non-persistent)
193 * consistency in mballoc world means that at any time a block is either
194 * free or used in ALL structures. notice: "any time" should not be read
195 * literally -- time is discrete and delimited by locks.
197 * to keep it simple, we don't use block numbers, instead we count number of
198 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
200 * all operations can be expressed as:
201 * - init buddy: buddy = on-disk + PAs
202 * - new PA: buddy += N; PA = N
203 * - use inode PA: on-disk += N; PA -= N
204 * - discard inode PA buddy -= on-disk - PA; PA = 0
205 * - use locality group PA on-disk += N; PA -= N
206 * - discard locality group PA buddy -= PA; PA = 0
207 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
208 * is used in real operation because we can't know actual used
209 * bits from PA, only from on-disk bitmap
211 * if we follow this strict logic, then all operations above should be atomic.
212 * given some of them can block, we'd have to use something like semaphores
213 * killing performance on high-end SMP hardware. let's try to relax it using
214 * the following knowledge:
215 * 1) if buddy is referenced, it's already initialized
216 * 2) while block is used in buddy and the buddy is referenced,
217 * nobody can re-allocate that block
218 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
219 * bit set and PA claims same block, it's OK. IOW, one can set bit in
220 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
223 * so, now we're building a concurrency table:
226 * blocks for PA are allocated in the buddy, buddy must be referenced
227 * until PA is linked to allocation group to avoid concurrent buddy init
229 * we need to make sure that either on-disk bitmap or PA has uptodate data
230 * given (3) we care that PA-=N operation doesn't interfere with init
232 * the simplest way would be to have buddy initialized by the discard
233 * - use locality group PA
234 * again PA-=N must be serialized with init
235 * - discard locality group PA
236 * the simplest way would be to have buddy initialized by the discard
239 * i_data_sem serializes them
241 * discard process must wait until PA isn't used by another process
242 * - use locality group PA
243 * some mutex should serialize them
244 * - discard locality group PA
245 * discard process must wait until PA isn't used by another process
248 * i_data_sem or another mutex should serializes them
250 * discard process must wait until PA isn't used by another process
251 * - use locality group PA
252 * nothing wrong here -- they're different PAs covering different blocks
253 * - discard locality group PA
254 * discard process must wait until PA isn't used by another process
256 * now we're ready to make few consequences:
257 * - PA is referenced and while it is no discard is possible
258 * - PA is referenced until block isn't marked in on-disk bitmap
259 * - PA changes only after on-disk bitmap
260 * - discard must not compete with init. either init is done before
261 * any discard or they're serialized somehow
262 * - buddy init as sum of on-disk bitmap and PAs is done atomically
264 * a special case when we've used PA to emptiness. no need to modify buddy
265 * in this case, but we should care about concurrent init
270 * Logic in few words:
275 * mark bits in on-disk bitmap
278 * - use preallocation:
279 * find proper PA (per-inode or group)
281 * mark bits in on-disk bitmap
287 * mark bits in on-disk bitmap
290 * - discard preallocations in group:
292 * move them onto local list
293 * load on-disk bitmap
295 * remove PA from object (inode or locality group)
296 * mark free blocks in-core
298 * - discard inode's preallocations:
305 * - bitlock on a group (group)
306 * - object (inode/locality) (object)
317 * - release consumed pa:
322 * - generate in-core bitmap:
326 * - discard all for given object (inode, locality group):
331 * - discard all for given group:
338 static struct kmem_cache *ext4_pspace_cachep;
339 static struct kmem_cache *ext4_ac_cachep;
340 static struct kmem_cache *ext4_free_ext_cachep;
342 /* We create slab caches for groupinfo data structures based on the
343 * superblock block size. There will be one per mounted filesystem for
344 * each unique s_blocksize_bits */
345 #define NR_GRPINFO_CACHES 8
346 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
348 static const char *ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
349 "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
350 "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
351 "ext4_groupinfo_64k", "ext4_groupinfo_128k"
354 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
356 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
358 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn);
360 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
362 #if BITS_PER_LONG == 64
363 *bit += ((unsigned long) addr & 7UL) << 3;
364 addr = (void *) ((unsigned long) addr & ~7UL);
365 #elif BITS_PER_LONG == 32
366 *bit += ((unsigned long) addr & 3UL) << 3;
367 addr = (void *) ((unsigned long) addr & ~3UL);
369 #error "how many bits you are?!"
374 static inline int mb_test_bit(int bit, void *addr)
377 * ext4_test_bit on architecture like powerpc
378 * needs unsigned long aligned address
380 addr = mb_correct_addr_and_bit(&bit, addr);
381 return ext4_test_bit(bit, addr);
384 static inline void mb_set_bit(int bit, void *addr)
386 addr = mb_correct_addr_and_bit(&bit, addr);
387 ext4_set_bit(bit, addr);
390 static inline void mb_clear_bit(int bit, void *addr)
392 addr = mb_correct_addr_and_bit(&bit, addr);
393 ext4_clear_bit(bit, addr);
396 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
398 int fix = 0, ret, tmpmax;
399 addr = mb_correct_addr_and_bit(&fix, addr);
403 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
409 static inline int mb_find_next_bit(void *addr, int max, int start)
411 int fix = 0, ret, tmpmax;
412 addr = mb_correct_addr_and_bit(&fix, addr);
416 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
422 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
426 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
429 if (order > e4b->bd_blkbits + 1) {
434 /* at order 0 we see each particular block */
436 *max = 1 << (e4b->bd_blkbits + 3);
437 return EXT4_MB_BITMAP(e4b);
440 bb = EXT4_MB_BUDDY(e4b) + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
441 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
447 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
448 int first, int count)
451 struct super_block *sb = e4b->bd_sb;
453 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
455 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
456 for (i = 0; i < count; i++) {
457 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
458 ext4_fsblk_t blocknr;
460 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
461 blocknr += first + i;
462 ext4_grp_locked_error(sb, e4b->bd_group,
463 inode ? inode->i_ino : 0,
465 "freeing block already freed "
469 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
473 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
477 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
479 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
480 for (i = 0; i < count; i++) {
481 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
482 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
486 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
488 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
489 unsigned char *b1, *b2;
491 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
492 b2 = (unsigned char *) bitmap;
493 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
494 if (b1[i] != b2[i]) {
495 printk(KERN_ERR "corruption in group %u "
496 "at byte %u(%u): %x in copy != %x "
497 "on disk/prealloc\n",
498 e4b->bd_group, i, i * 8, b1[i], b2[i]);
506 static inline void mb_free_blocks_double(struct inode *inode,
507 struct ext4_buddy *e4b, int first, int count)
511 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
512 int first, int count)
516 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
522 #ifdef AGGRESSIVE_CHECK
524 #define MB_CHECK_ASSERT(assert) \
528 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
529 function, file, line, # assert); \
534 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
535 const char *function, int line)
537 struct super_block *sb = e4b->bd_sb;
538 int order = e4b->bd_blkbits + 1;
545 struct ext4_group_info *grp;
548 struct list_head *cur;
553 static int mb_check_counter;
554 if (mb_check_counter++ % 100 != 0)
559 buddy = mb_find_buddy(e4b, order, &max);
560 MB_CHECK_ASSERT(buddy);
561 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
562 MB_CHECK_ASSERT(buddy2);
563 MB_CHECK_ASSERT(buddy != buddy2);
564 MB_CHECK_ASSERT(max * 2 == max2);
567 for (i = 0; i < max; i++) {
569 if (mb_test_bit(i, buddy)) {
570 /* only single bit in buddy2 may be 1 */
571 if (!mb_test_bit(i << 1, buddy2)) {
573 mb_test_bit((i<<1)+1, buddy2));
574 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
576 mb_test_bit(i << 1, buddy2));
581 /* both bits in buddy2 must be 0 */
582 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
583 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
585 for (j = 0; j < (1 << order); j++) {
586 k = (i * (1 << order)) + j;
588 !mb_test_bit(k, EXT4_MB_BITMAP(e4b)));
592 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
597 buddy = mb_find_buddy(e4b, 0, &max);
598 for (i = 0; i < max; i++) {
599 if (!mb_test_bit(i, buddy)) {
600 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
608 /* check used bits only */
609 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
610 buddy2 = mb_find_buddy(e4b, j, &max2);
612 MB_CHECK_ASSERT(k < max2);
613 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
616 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
617 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
619 grp = ext4_get_group_info(sb, e4b->bd_group);
620 list_for_each(cur, &grp->bb_prealloc_list) {
621 ext4_group_t groupnr;
622 struct ext4_prealloc_space *pa;
623 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
624 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
625 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
626 for (i = 0; i < pa->pa_len; i++)
627 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
631 #undef MB_CHECK_ASSERT
632 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
633 __FILE__, __func__, __LINE__)
635 #define mb_check_buddy(e4b)
639 * Divide blocks started from @first with length @len into
640 * smaller chunks with power of 2 blocks.
641 * Clear the bits in bitmap which the blocks of the chunk(s) covered,
642 * then increase bb_counters[] for corresponded chunk size.
644 static void ext4_mb_mark_free_simple(struct super_block *sb,
645 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
646 struct ext4_group_info *grp)
648 struct ext4_sb_info *sbi = EXT4_SB(sb);
652 unsigned short border;
654 BUG_ON(len > EXT4_BLOCKS_PER_GROUP(sb));
656 border = 2 << sb->s_blocksize_bits;
659 /* find how many blocks can be covered since this position */
660 max = ffs(first | border) - 1;
662 /* find how many blocks of power 2 we need to mark */
669 /* mark multiblock chunks only */
670 grp->bb_counters[min]++;
672 mb_clear_bit(first >> min,
673 buddy + sbi->s_mb_offsets[min]);
681 * Cache the order of the largest free extent we have available in this block
685 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
690 grp->bb_largest_free_order = -1; /* uninit */
692 bits = sb->s_blocksize_bits + 1;
693 for (i = bits; i >= 0; i--) {
694 if (grp->bb_counters[i] > 0) {
695 grp->bb_largest_free_order = i;
701 static noinline_for_stack
702 void ext4_mb_generate_buddy(struct super_block *sb,
703 void *buddy, void *bitmap, ext4_group_t group)
705 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
706 ext4_grpblk_t max = EXT4_BLOCKS_PER_GROUP(sb);
711 unsigned fragments = 0;
712 unsigned long long period = get_cycles();
714 /* initialize buddy from bitmap which is aggregation
715 * of on-disk bitmap and preallocations */
716 i = mb_find_next_zero_bit(bitmap, max, 0);
717 grp->bb_first_free = i;
721 i = mb_find_next_bit(bitmap, max, i);
725 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
727 grp->bb_counters[0]++;
729 i = mb_find_next_zero_bit(bitmap, max, i);
731 grp->bb_fragments = fragments;
733 if (free != grp->bb_free) {
734 ext4_grp_locked_error(sb, group, 0, 0,
735 "%u blocks in bitmap, %u in gd",
738 * If we intent to continue, we consider group descritor
739 * corrupt and update bb_free using bitmap value
743 mb_set_largest_free_order(sb, grp);
745 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
747 period = get_cycles() - period;
748 spin_lock(&EXT4_SB(sb)->s_bal_lock);
749 EXT4_SB(sb)->s_mb_buddies_generated++;
750 EXT4_SB(sb)->s_mb_generation_time += period;
751 spin_unlock(&EXT4_SB(sb)->s_bal_lock);
754 /* The buddy information is attached the buddy cache inode
755 * for convenience. The information regarding each group
756 * is loaded via ext4_mb_load_buddy. The information involve
757 * block bitmap and buddy information. The information are
758 * stored in the inode as
761 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
764 * one block each for bitmap and buddy information.
765 * So for each group we take up 2 blocks. A page can
766 * contain blocks_per_page (PAGE_CACHE_SIZE / blocksize) blocks.
767 * So it can have information regarding groups_per_page which
768 * is blocks_per_page/2
770 * Locking note: This routine takes the block group lock of all groups
771 * for this page; do not hold this lock when calling this routine!
774 static int ext4_mb_init_cache(struct page *page, char *incore)
776 ext4_group_t ngroups;
782 ext4_group_t first_group;
784 struct super_block *sb;
785 struct buffer_head *bhs;
786 struct buffer_head **bh;
791 mb_debug(1, "init page %lu\n", page->index);
793 inode = page->mapping->host;
795 ngroups = ext4_get_groups_count(sb);
796 blocksize = 1 << inode->i_blkbits;
797 blocks_per_page = PAGE_CACHE_SIZE / blocksize;
799 groups_per_page = blocks_per_page >> 1;
800 if (groups_per_page == 0)
803 /* allocate buffer_heads to read bitmaps */
804 if (groups_per_page > 1) {
806 i = sizeof(struct buffer_head *) * groups_per_page;
807 bh = kzalloc(i, GFP_NOFS);
813 first_group = page->index * blocks_per_page / 2;
815 /* read all groups the page covers into the cache */
816 for (i = 0; i < groups_per_page; i++) {
817 struct ext4_group_desc *desc;
819 if (first_group + i >= ngroups)
823 desc = ext4_get_group_desc(sb, first_group + i, NULL);
828 bh[i] = sb_getblk(sb, ext4_block_bitmap(sb, desc));
832 if (bitmap_uptodate(bh[i]))
836 if (bitmap_uptodate(bh[i])) {
837 unlock_buffer(bh[i]);
840 ext4_lock_group(sb, first_group + i);
841 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
842 ext4_init_block_bitmap(sb, bh[i],
843 first_group + i, desc);
844 set_bitmap_uptodate(bh[i]);
845 set_buffer_uptodate(bh[i]);
846 ext4_unlock_group(sb, first_group + i);
847 unlock_buffer(bh[i]);
850 ext4_unlock_group(sb, first_group + i);
851 if (buffer_uptodate(bh[i])) {
853 * if not uninit if bh is uptodate,
854 * bitmap is also uptodate
856 set_bitmap_uptodate(bh[i]);
857 unlock_buffer(bh[i]);
862 * submit the buffer_head for read. We can
863 * safely mark the bitmap as uptodate now.
864 * We do it here so the bitmap uptodate bit
865 * get set with buffer lock held.
867 set_bitmap_uptodate(bh[i]);
868 bh[i]->b_end_io = end_buffer_read_sync;
869 submit_bh(READ, bh[i]);
870 mb_debug(1, "read bitmap for group %u\n", first_group + i);
873 /* wait for I/O completion */
874 for (i = 0; i < groups_per_page && bh[i]; i++)
875 wait_on_buffer(bh[i]);
878 for (i = 0; i < groups_per_page && bh[i]; i++)
879 if (!buffer_uptodate(bh[i]))
883 first_block = page->index * blocks_per_page;
885 memset(page_address(page), 0xff, PAGE_CACHE_SIZE);
886 for (i = 0; i < blocks_per_page; i++) {
888 struct ext4_group_info *grinfo;
890 group = (first_block + i) >> 1;
891 if (group >= ngroups)
895 * data carry information regarding this
896 * particular group in the format specified
900 data = page_address(page) + (i * blocksize);
901 bitmap = bh[group - first_group]->b_data;
904 * We place the buddy block and bitmap block
907 if ((first_block + i) & 1) {
908 /* this is block of buddy */
909 BUG_ON(incore == NULL);
910 mb_debug(1, "put buddy for group %u in page %lu/%x\n",
911 group, page->index, i * blocksize);
912 trace_ext4_mb_buddy_bitmap_load(sb, group);
913 grinfo = ext4_get_group_info(sb, group);
914 grinfo->bb_fragments = 0;
915 memset(grinfo->bb_counters, 0,
916 sizeof(*grinfo->bb_counters) *
917 (sb->s_blocksize_bits+2));
919 * incore got set to the group block bitmap below
921 ext4_lock_group(sb, group);
922 ext4_mb_generate_buddy(sb, data, incore, group);
923 ext4_unlock_group(sb, group);
926 /* this is block of bitmap */
927 BUG_ON(incore != NULL);
928 mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
929 group, page->index, i * blocksize);
930 trace_ext4_mb_bitmap_load(sb, group);
932 /* see comments in ext4_mb_put_pa() */
933 ext4_lock_group(sb, group);
934 memcpy(data, bitmap, blocksize);
936 /* mark all preallocated blks used in in-core bitmap */
937 ext4_mb_generate_from_pa(sb, data, group);
938 ext4_mb_generate_from_freelist(sb, data, group);
939 ext4_unlock_group(sb, group);
941 /* set incore so that the buddy information can be
942 * generated using this
947 SetPageUptodate(page);
951 for (i = 0; i < groups_per_page && bh[i]; i++)
960 * lock the group_info alloc_sem of all the groups
961 * belonging to the same buddy cache page. This
962 * make sure other parallel operation on the buddy
963 * cache doesn't happen whild holding the buddy cache
966 static int ext4_mb_get_buddy_cache_lock(struct super_block *sb,
973 ext4_group_t ngroups = ext4_get_groups_count(sb);
974 ext4_group_t first_group;
975 struct ext4_group_info *grp;
977 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
979 * the buddy cache inode stores the block bitmap
980 * and buddy information in consecutive blocks.
981 * So for each group we need two blocks.
984 pnum = block / blocks_per_page;
985 first_group = pnum * blocks_per_page / 2;
987 groups_per_page = blocks_per_page >> 1;
988 if (groups_per_page == 0)
990 /* read all groups the page covers into the cache */
991 for (i = 0; i < groups_per_page; i++) {
993 if ((first_group + i) >= ngroups)
995 grp = ext4_get_group_info(sb, first_group + i);
996 /* take all groups write allocation
997 * semaphore. This make sure there is
998 * no block allocation going on in any
1001 down_write_nested(&grp->alloc_sem, i);
1006 static void ext4_mb_put_buddy_cache_lock(struct super_block *sb,
1007 ext4_group_t group, int locked_group)
1011 int blocks_per_page;
1012 ext4_group_t first_group;
1013 struct ext4_group_info *grp;
1015 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1017 * the buddy cache inode stores the block bitmap
1018 * and buddy information in consecutive blocks.
1019 * So for each group we need two blocks.
1022 pnum = block / blocks_per_page;
1023 first_group = pnum * blocks_per_page / 2;
1024 /* release locks on all the groups */
1025 for (i = 0; i < locked_group; i++) {
1027 grp = ext4_get_group_info(sb, first_group + i);
1028 /* take all groups write allocation
1029 * semaphore. This make sure there is
1030 * no block allocation going on in any
1033 up_write(&grp->alloc_sem);
1039 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1040 * block group lock of all groups for this page; do not hold the BG lock when
1041 * calling this routine!
1043 static noinline_for_stack
1044 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group)
1049 int blocks_per_page;
1050 int block, pnum, poff;
1051 int num_grp_locked = 0;
1052 struct ext4_group_info *this_grp;
1053 struct ext4_sb_info *sbi = EXT4_SB(sb);
1054 struct inode *inode = sbi->s_buddy_cache;
1055 struct page *page = NULL, *bitmap_page = NULL;
1057 mb_debug(1, "init group %u\n", group);
1058 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1059 this_grp = ext4_get_group_info(sb, group);
1061 * This ensures that we don't reinit the buddy cache
1062 * page which map to the group from which we are already
1063 * allocating. If we are looking at the buddy cache we would
1064 * have taken a reference using ext4_mb_load_buddy and that
1065 * would have taken the alloc_sem lock.
1067 num_grp_locked = ext4_mb_get_buddy_cache_lock(sb, group);
1068 if (!EXT4_MB_GRP_NEED_INIT(this_grp)) {
1070 * somebody initialized the group
1071 * return without doing anything
1077 * the buddy cache inode stores the block bitmap
1078 * and buddy information in consecutive blocks.
1079 * So for each group we need two blocks.
1082 pnum = block / blocks_per_page;
1083 poff = block % blocks_per_page;
1084 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1086 BUG_ON(page->mapping != inode->i_mapping);
1087 ret = ext4_mb_init_cache(page, NULL);
1094 if (page == NULL || !PageUptodate(page)) {
1098 mark_page_accessed(page);
1100 bitmap = page_address(page) + (poff * sb->s_blocksize);
1102 /* init buddy cache */
1104 pnum = block / blocks_per_page;
1105 poff = block % blocks_per_page;
1106 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1107 if (page == bitmap_page) {
1109 * If both the bitmap and buddy are in
1110 * the same page we don't need to force
1115 BUG_ON(page->mapping != inode->i_mapping);
1116 ret = ext4_mb_init_cache(page, bitmap);
1123 if (page == NULL || !PageUptodate(page)) {
1127 mark_page_accessed(page);
1129 ext4_mb_put_buddy_cache_lock(sb, group, num_grp_locked);
1131 page_cache_release(bitmap_page);
1133 page_cache_release(page);
1138 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1139 * block group lock of all groups for this page; do not hold the BG lock when
1140 * calling this routine!
1142 static noinline_for_stack int
1143 ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1144 struct ext4_buddy *e4b)
1146 int blocks_per_page;
1152 struct ext4_group_info *grp;
1153 struct ext4_sb_info *sbi = EXT4_SB(sb);
1154 struct inode *inode = sbi->s_buddy_cache;
1156 mb_debug(1, "load group %u\n", group);
1158 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1159 grp = ext4_get_group_info(sb, group);
1161 e4b->bd_blkbits = sb->s_blocksize_bits;
1162 e4b->bd_info = ext4_get_group_info(sb, group);
1164 e4b->bd_group = group;
1165 e4b->bd_buddy_page = NULL;
1166 e4b->bd_bitmap_page = NULL;
1167 e4b->alloc_semp = &grp->alloc_sem;
1169 /* Take the read lock on the group alloc
1170 * sem. This would make sure a parallel
1171 * ext4_mb_init_group happening on other
1172 * groups mapped by the page is blocked
1173 * till we are done with allocation
1176 down_read(e4b->alloc_semp);
1178 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1179 /* we need to check for group need init flag
1180 * with alloc_semp held so that we can be sure
1181 * that new blocks didn't get added to the group
1182 * when we are loading the buddy cache
1184 up_read(e4b->alloc_semp);
1186 * we need full data about the group
1187 * to make a good selection
1189 ret = ext4_mb_init_group(sb, group);
1192 goto repeat_load_buddy;
1196 * the buddy cache inode stores the block bitmap
1197 * and buddy information in consecutive blocks.
1198 * So for each group we need two blocks.
1201 pnum = block / blocks_per_page;
1202 poff = block % blocks_per_page;
1204 /* we could use find_or_create_page(), but it locks page
1205 * what we'd like to avoid in fast path ... */
1206 page = find_get_page(inode->i_mapping, pnum);
1207 if (page == NULL || !PageUptodate(page)) {
1210 * drop the page reference and try
1211 * to get the page with lock. If we
1212 * are not uptodate that implies
1213 * somebody just created the page but
1214 * is yet to initialize the same. So
1215 * wait for it to initialize.
1217 page_cache_release(page);
1218 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1220 BUG_ON(page->mapping != inode->i_mapping);
1221 if (!PageUptodate(page)) {
1222 ret = ext4_mb_init_cache(page, NULL);
1227 mb_cmp_bitmaps(e4b, page_address(page) +
1228 (poff * sb->s_blocksize));
1233 if (page == NULL || !PageUptodate(page)) {
1237 e4b->bd_bitmap_page = page;
1238 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1239 mark_page_accessed(page);
1242 pnum = block / blocks_per_page;
1243 poff = block % blocks_per_page;
1245 page = find_get_page(inode->i_mapping, pnum);
1246 if (page == NULL || !PageUptodate(page)) {
1248 page_cache_release(page);
1249 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1251 BUG_ON(page->mapping != inode->i_mapping);
1252 if (!PageUptodate(page)) {
1253 ret = ext4_mb_init_cache(page, e4b->bd_bitmap);
1262 if (page == NULL || !PageUptodate(page)) {
1266 e4b->bd_buddy_page = page;
1267 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1268 mark_page_accessed(page);
1270 BUG_ON(e4b->bd_bitmap_page == NULL);
1271 BUG_ON(e4b->bd_buddy_page == NULL);
1277 page_cache_release(page);
1278 if (e4b->bd_bitmap_page)
1279 page_cache_release(e4b->bd_bitmap_page);
1280 if (e4b->bd_buddy_page)
1281 page_cache_release(e4b->bd_buddy_page);
1282 e4b->bd_buddy = NULL;
1283 e4b->bd_bitmap = NULL;
1285 /* Done with the buddy cache */
1286 up_read(e4b->alloc_semp);
1290 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1292 if (e4b->bd_bitmap_page)
1293 page_cache_release(e4b->bd_bitmap_page);
1294 if (e4b->bd_buddy_page)
1295 page_cache_release(e4b->bd_buddy_page);
1296 /* Done with the buddy cache */
1297 if (e4b->alloc_semp)
1298 up_read(e4b->alloc_semp);
1302 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1307 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
1308 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1310 bb = EXT4_MB_BUDDY(e4b);
1311 while (order <= e4b->bd_blkbits + 1) {
1313 if (!mb_test_bit(block, bb)) {
1314 /* this block is part of buddy of order 'order' */
1317 bb += 1 << (e4b->bd_blkbits - order);
1323 static void mb_clear_bits(void *bm, int cur, int len)
1329 if ((cur & 31) == 0 && (len - cur) >= 32) {
1330 /* fast path: clear whole word at once */
1331 addr = bm + (cur >> 3);
1336 mb_clear_bit(cur, bm);
1341 static void mb_set_bits(void *bm, int cur, int len)
1347 if ((cur & 31) == 0 && (len - cur) >= 32) {
1348 /* fast path: set whole word at once */
1349 addr = bm + (cur >> 3);
1354 mb_set_bit(cur, bm);
1359 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1360 int first, int count)
1367 struct super_block *sb = e4b->bd_sb;
1369 BUG_ON(first + count > (sb->s_blocksize << 3));
1370 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1371 mb_check_buddy(e4b);
1372 mb_free_blocks_double(inode, e4b, first, count);
1374 e4b->bd_info->bb_free += count;
1375 if (first < e4b->bd_info->bb_first_free)
1376 e4b->bd_info->bb_first_free = first;
1378 /* let's maintain fragments counter */
1380 block = !mb_test_bit(first - 1, EXT4_MB_BITMAP(e4b));
1381 if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
1382 max = !mb_test_bit(first + count, EXT4_MB_BITMAP(e4b));
1384 e4b->bd_info->bb_fragments--;
1385 else if (!block && !max)
1386 e4b->bd_info->bb_fragments++;
1388 /* let's maintain buddy itself */
1389 while (count-- > 0) {
1393 if (!mb_test_bit(block, EXT4_MB_BITMAP(e4b))) {
1394 ext4_fsblk_t blocknr;
1396 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1398 ext4_grp_locked_error(sb, e4b->bd_group,
1399 inode ? inode->i_ino : 0,
1401 "freeing already freed block "
1404 mb_clear_bit(block, EXT4_MB_BITMAP(e4b));
1405 e4b->bd_info->bb_counters[order]++;
1407 /* start of the buddy */
1408 buddy = mb_find_buddy(e4b, order, &max);
1412 if (mb_test_bit(block, buddy) ||
1413 mb_test_bit(block + 1, buddy))
1416 /* both the buddies are free, try to coalesce them */
1417 buddy2 = mb_find_buddy(e4b, order + 1, &max);
1423 /* for special purposes, we don't set
1424 * free bits in bitmap */
1425 mb_set_bit(block, buddy);
1426 mb_set_bit(block + 1, buddy);
1428 e4b->bd_info->bb_counters[order]--;
1429 e4b->bd_info->bb_counters[order]--;
1433 e4b->bd_info->bb_counters[order]++;
1435 mb_clear_bit(block, buddy2);
1439 mb_set_largest_free_order(sb, e4b->bd_info);
1440 mb_check_buddy(e4b);
1443 static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
1444 int needed, struct ext4_free_extent *ex)
1451 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1454 buddy = mb_find_buddy(e4b, order, &max);
1455 BUG_ON(buddy == NULL);
1456 BUG_ON(block >= max);
1457 if (mb_test_bit(block, buddy)) {
1464 /* FIXME dorp order completely ? */
1465 if (likely(order == 0)) {
1466 /* find actual order */
1467 order = mb_find_order_for_block(e4b, block);
1468 block = block >> order;
1471 ex->fe_len = 1 << order;
1472 ex->fe_start = block << order;
1473 ex->fe_group = e4b->bd_group;
1475 /* calc difference from given start */
1476 next = next - ex->fe_start;
1478 ex->fe_start += next;
1480 while (needed > ex->fe_len &&
1481 (buddy = mb_find_buddy(e4b, order, &max))) {
1483 if (block + 1 >= max)
1486 next = (block + 1) * (1 << order);
1487 if (mb_test_bit(next, EXT4_MB_BITMAP(e4b)))
1490 ord = mb_find_order_for_block(e4b, next);
1493 block = next >> order;
1494 ex->fe_len += 1 << order;
1497 BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1501 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1507 int start = ex->fe_start;
1508 int len = ex->fe_len;
1513 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1514 BUG_ON(e4b->bd_group != ex->fe_group);
1515 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1516 mb_check_buddy(e4b);
1517 mb_mark_used_double(e4b, start, len);
1519 e4b->bd_info->bb_free -= len;
1520 if (e4b->bd_info->bb_first_free == start)
1521 e4b->bd_info->bb_first_free += len;
1523 /* let's maintain fragments counter */
1525 mlen = !mb_test_bit(start - 1, EXT4_MB_BITMAP(e4b));
1526 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1527 max = !mb_test_bit(start + len, EXT4_MB_BITMAP(e4b));
1529 e4b->bd_info->bb_fragments++;
1530 else if (!mlen && !max)
1531 e4b->bd_info->bb_fragments--;
1533 /* let's maintain buddy itself */
1535 ord = mb_find_order_for_block(e4b, start);
1537 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1538 /* the whole chunk may be allocated at once! */
1540 buddy = mb_find_buddy(e4b, ord, &max);
1541 BUG_ON((start >> ord) >= max);
1542 mb_set_bit(start >> ord, buddy);
1543 e4b->bd_info->bb_counters[ord]--;
1550 /* store for history */
1552 ret = len | (ord << 16);
1554 /* we have to split large buddy */
1556 buddy = mb_find_buddy(e4b, ord, &max);
1557 mb_set_bit(start >> ord, buddy);
1558 e4b->bd_info->bb_counters[ord]--;
1561 cur = (start >> ord) & ~1U;
1562 buddy = mb_find_buddy(e4b, ord, &max);
1563 mb_clear_bit(cur, buddy);
1564 mb_clear_bit(cur + 1, buddy);
1565 e4b->bd_info->bb_counters[ord]++;
1566 e4b->bd_info->bb_counters[ord]++;
1568 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1570 mb_set_bits(EXT4_MB_BITMAP(e4b), ex->fe_start, len0);
1571 mb_check_buddy(e4b);
1577 * Must be called under group lock!
1579 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1580 struct ext4_buddy *e4b)
1582 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1585 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1586 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1588 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1589 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1590 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1592 /* preallocation can change ac_b_ex, thus we store actually
1593 * allocated blocks for history */
1594 ac->ac_f_ex = ac->ac_b_ex;
1596 ac->ac_status = AC_STATUS_FOUND;
1597 ac->ac_tail = ret & 0xffff;
1598 ac->ac_buddy = ret >> 16;
1601 * take the page reference. We want the page to be pinned
1602 * so that we don't get a ext4_mb_init_cache_call for this
1603 * group until we update the bitmap. That would mean we
1604 * double allocate blocks. The reference is dropped
1605 * in ext4_mb_release_context
1607 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1608 get_page(ac->ac_bitmap_page);
1609 ac->ac_buddy_page = e4b->bd_buddy_page;
1610 get_page(ac->ac_buddy_page);
1611 /* on allocation we use ac to track the held semaphore */
1612 ac->alloc_semp = e4b->alloc_semp;
1613 e4b->alloc_semp = NULL;
1614 /* store last allocated for subsequent stream allocation */
1615 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1616 spin_lock(&sbi->s_md_lock);
1617 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1618 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1619 spin_unlock(&sbi->s_md_lock);
1624 * regular allocator, for general purposes allocation
1627 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1628 struct ext4_buddy *e4b,
1631 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1632 struct ext4_free_extent *bex = &ac->ac_b_ex;
1633 struct ext4_free_extent *gex = &ac->ac_g_ex;
1634 struct ext4_free_extent ex;
1637 if (ac->ac_status == AC_STATUS_FOUND)
1640 * We don't want to scan for a whole year
1642 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1643 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1644 ac->ac_status = AC_STATUS_BREAK;
1649 * Haven't found good chunk so far, let's continue
1651 if (bex->fe_len < gex->fe_len)
1654 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1655 && bex->fe_group == e4b->bd_group) {
1656 /* recheck chunk's availability - we don't know
1657 * when it was found (within this lock-unlock
1659 max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
1660 if (max >= gex->fe_len) {
1661 ext4_mb_use_best_found(ac, e4b);
1668 * The routine checks whether found extent is good enough. If it is,
1669 * then the extent gets marked used and flag is set to the context
1670 * to stop scanning. Otherwise, the extent is compared with the
1671 * previous found extent and if new one is better, then it's stored
1672 * in the context. Later, the best found extent will be used, if
1673 * mballoc can't find good enough extent.
1675 * FIXME: real allocation policy is to be designed yet!
1677 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1678 struct ext4_free_extent *ex,
1679 struct ext4_buddy *e4b)
1681 struct ext4_free_extent *bex = &ac->ac_b_ex;
1682 struct ext4_free_extent *gex = &ac->ac_g_ex;
1684 BUG_ON(ex->fe_len <= 0);
1685 BUG_ON(ex->fe_len > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1686 BUG_ON(ex->fe_start >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1687 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1692 * The special case - take what you catch first
1694 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1696 ext4_mb_use_best_found(ac, e4b);
1701 * Let's check whether the chuck is good enough
1703 if (ex->fe_len == gex->fe_len) {
1705 ext4_mb_use_best_found(ac, e4b);
1710 * If this is first found extent, just store it in the context
1712 if (bex->fe_len == 0) {
1718 * If new found extent is better, store it in the context
1720 if (bex->fe_len < gex->fe_len) {
1721 /* if the request isn't satisfied, any found extent
1722 * larger than previous best one is better */
1723 if (ex->fe_len > bex->fe_len)
1725 } else if (ex->fe_len > gex->fe_len) {
1726 /* if the request is satisfied, then we try to find
1727 * an extent that still satisfy the request, but is
1728 * smaller than previous one */
1729 if (ex->fe_len < bex->fe_len)
1733 ext4_mb_check_limits(ac, e4b, 0);
1736 static noinline_for_stack
1737 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1738 struct ext4_buddy *e4b)
1740 struct ext4_free_extent ex = ac->ac_b_ex;
1741 ext4_group_t group = ex.fe_group;
1745 BUG_ON(ex.fe_len <= 0);
1746 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1750 ext4_lock_group(ac->ac_sb, group);
1751 max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
1755 ext4_mb_use_best_found(ac, e4b);
1758 ext4_unlock_group(ac->ac_sb, group);
1759 ext4_mb_unload_buddy(e4b);
1764 static noinline_for_stack
1765 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1766 struct ext4_buddy *e4b)
1768 ext4_group_t group = ac->ac_g_ex.fe_group;
1771 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1772 struct ext4_free_extent ex;
1774 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1777 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1781 ext4_lock_group(ac->ac_sb, group);
1782 max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
1783 ac->ac_g_ex.fe_len, &ex);
1785 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1788 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
1790 /* use do_div to get remainder (would be 64-bit modulo) */
1791 if (do_div(start, sbi->s_stripe) == 0) {
1794 ext4_mb_use_best_found(ac, e4b);
1796 } else if (max >= ac->ac_g_ex.fe_len) {
1797 BUG_ON(ex.fe_len <= 0);
1798 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1799 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1802 ext4_mb_use_best_found(ac, e4b);
1803 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1804 /* Sometimes, caller may want to merge even small
1805 * number of blocks to an existing extent */
1806 BUG_ON(ex.fe_len <= 0);
1807 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1808 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1811 ext4_mb_use_best_found(ac, e4b);
1813 ext4_unlock_group(ac->ac_sb, group);
1814 ext4_mb_unload_buddy(e4b);
1820 * The routine scans buddy structures (not bitmap!) from given order
1821 * to max order and tries to find big enough chunk to satisfy the req
1823 static noinline_for_stack
1824 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1825 struct ext4_buddy *e4b)
1827 struct super_block *sb = ac->ac_sb;
1828 struct ext4_group_info *grp = e4b->bd_info;
1834 BUG_ON(ac->ac_2order <= 0);
1835 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1836 if (grp->bb_counters[i] == 0)
1839 buddy = mb_find_buddy(e4b, i, &max);
1840 BUG_ON(buddy == NULL);
1842 k = mb_find_next_zero_bit(buddy, max, 0);
1847 ac->ac_b_ex.fe_len = 1 << i;
1848 ac->ac_b_ex.fe_start = k << i;
1849 ac->ac_b_ex.fe_group = e4b->bd_group;
1851 ext4_mb_use_best_found(ac, e4b);
1853 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1855 if (EXT4_SB(sb)->s_mb_stats)
1856 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1863 * The routine scans the group and measures all found extents.
1864 * In order to optimize scanning, caller must pass number of
1865 * free blocks in the group, so the routine can know upper limit.
1867 static noinline_for_stack
1868 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1869 struct ext4_buddy *e4b)
1871 struct super_block *sb = ac->ac_sb;
1872 void *bitmap = EXT4_MB_BITMAP(e4b);
1873 struct ext4_free_extent ex;
1877 free = e4b->bd_info->bb_free;
1880 i = e4b->bd_info->bb_first_free;
1882 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1883 i = mb_find_next_zero_bit(bitmap,
1884 EXT4_BLOCKS_PER_GROUP(sb), i);
1885 if (i >= EXT4_BLOCKS_PER_GROUP(sb)) {
1887 * IF we have corrupt bitmap, we won't find any
1888 * free blocks even though group info says we
1889 * we have free blocks
1891 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1892 "%d free blocks as per "
1893 "group info. But bitmap says 0",
1898 mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
1899 BUG_ON(ex.fe_len <= 0);
1900 if (free < ex.fe_len) {
1901 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1902 "%d free blocks as per "
1903 "group info. But got %d blocks",
1906 * The number of free blocks differs. This mostly
1907 * indicate that the bitmap is corrupt. So exit
1908 * without claiming the space.
1913 ext4_mb_measure_extent(ac, &ex, e4b);
1919 ext4_mb_check_limits(ac, e4b, 1);
1923 * This is a special case for storages like raid5
1924 * we try to find stripe-aligned chunks for stripe-size-multiple requests
1926 static noinline_for_stack
1927 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1928 struct ext4_buddy *e4b)
1930 struct super_block *sb = ac->ac_sb;
1931 struct ext4_sb_info *sbi = EXT4_SB(sb);
1932 void *bitmap = EXT4_MB_BITMAP(e4b);
1933 struct ext4_free_extent ex;
1934 ext4_fsblk_t first_group_block;
1939 BUG_ON(sbi->s_stripe == 0);
1941 /* find first stripe-aligned block in group */
1942 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
1944 a = first_group_block + sbi->s_stripe - 1;
1945 do_div(a, sbi->s_stripe);
1946 i = (a * sbi->s_stripe) - first_group_block;
1948 while (i < EXT4_BLOCKS_PER_GROUP(sb)) {
1949 if (!mb_test_bit(i, bitmap)) {
1950 max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
1951 if (max >= sbi->s_stripe) {
1954 ext4_mb_use_best_found(ac, e4b);
1962 /* This is now called BEFORE we load the buddy bitmap. */
1963 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
1964 ext4_group_t group, int cr)
1966 unsigned free, fragments;
1967 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
1968 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1970 BUG_ON(cr < 0 || cr >= 4);
1972 /* We only do this if the grp has never been initialized */
1973 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1974 int ret = ext4_mb_init_group(ac->ac_sb, group);
1979 free = grp->bb_free;
1980 fragments = grp->bb_fragments;
1988 BUG_ON(ac->ac_2order == 0);
1990 if (grp->bb_largest_free_order < ac->ac_2order)
1993 /* Avoid using the first bg of a flexgroup for data files */
1994 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
1995 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
1996 ((group % flex_size) == 0))
2001 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2005 if (free >= ac->ac_g_ex.fe_len)
2017 static noinline_for_stack int
2018 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2020 ext4_group_t ngroups, group, i;
2023 struct ext4_sb_info *sbi;
2024 struct super_block *sb;
2025 struct ext4_buddy e4b;
2029 ngroups = ext4_get_groups_count(sb);
2030 /* non-extent files are limited to low blocks/groups */
2031 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2032 ngroups = sbi->s_blockfile_groups;
2034 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2036 /* first, try the goal */
2037 err = ext4_mb_find_by_goal(ac, &e4b);
2038 if (err || ac->ac_status == AC_STATUS_FOUND)
2041 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2045 * ac->ac2_order is set only if the fe_len is a power of 2
2046 * if ac2_order is set we also set criteria to 0 so that we
2047 * try exact allocation using buddy.
2049 i = fls(ac->ac_g_ex.fe_len);
2052 * We search using buddy data only if the order of the request
2053 * is greater than equal to the sbi_s_mb_order2_reqs
2054 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2056 if (i >= sbi->s_mb_order2_reqs) {
2058 * This should tell if fe_len is exactly power of 2
2060 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2061 ac->ac_2order = i - 1;
2064 /* if stream allocation is enabled, use global goal */
2065 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2066 /* TBD: may be hot point */
2067 spin_lock(&sbi->s_md_lock);
2068 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2069 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2070 spin_unlock(&sbi->s_md_lock);
2073 /* Let's just scan groups to find more-less suitable blocks */
2074 cr = ac->ac_2order ? 0 : 1;
2076 * cr == 0 try to get exact allocation,
2077 * cr == 3 try to get anything
2080 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2081 ac->ac_criteria = cr;
2083 * searching for the right group start
2084 * from the goal value specified
2086 group = ac->ac_g_ex.fe_group;
2088 for (i = 0; i < ngroups; group++, i++) {
2089 if (group == ngroups)
2092 /* This now checks without needing the buddy page */
2093 if (!ext4_mb_good_group(ac, group, cr))
2096 err = ext4_mb_load_buddy(sb, group, &e4b);
2100 ext4_lock_group(sb, group);
2103 * We need to check again after locking the
2106 if (!ext4_mb_good_group(ac, group, cr)) {
2107 ext4_unlock_group(sb, group);
2108 ext4_mb_unload_buddy(&e4b);
2112 ac->ac_groups_scanned++;
2114 ext4_mb_simple_scan_group(ac, &e4b);
2115 else if (cr == 1 && sbi->s_stripe &&
2116 !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2117 ext4_mb_scan_aligned(ac, &e4b);
2119 ext4_mb_complex_scan_group(ac, &e4b);
2121 ext4_unlock_group(sb, group);
2122 ext4_mb_unload_buddy(&e4b);
2124 if (ac->ac_status != AC_STATUS_CONTINUE)
2129 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2130 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2132 * We've been searching too long. Let's try to allocate
2133 * the best chunk we've found so far
2136 ext4_mb_try_best_found(ac, &e4b);
2137 if (ac->ac_status != AC_STATUS_FOUND) {
2139 * Someone more lucky has already allocated it.
2140 * The only thing we can do is just take first
2142 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2144 ac->ac_b_ex.fe_group = 0;
2145 ac->ac_b_ex.fe_start = 0;
2146 ac->ac_b_ex.fe_len = 0;
2147 ac->ac_status = AC_STATUS_CONTINUE;
2148 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2150 atomic_inc(&sbi->s_mb_lost_chunks);
2158 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2160 struct super_block *sb = seq->private;
2163 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2166 return (void *) ((unsigned long) group);
2169 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2171 struct super_block *sb = seq->private;
2175 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2178 return (void *) ((unsigned long) group);
2181 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2183 struct super_block *sb = seq->private;
2184 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2187 struct ext4_buddy e4b;
2189 struct ext4_group_info info;
2190 ext4_grpblk_t counters[16];
2195 seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
2196 "[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2197 "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2198 "group", "free", "frags", "first",
2199 "2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
2200 "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2202 i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2203 sizeof(struct ext4_group_info);
2204 err = ext4_mb_load_buddy(sb, group, &e4b);
2206 seq_printf(seq, "#%-5u: I/O error\n", group);
2209 ext4_lock_group(sb, group);
2210 memcpy(&sg, ext4_get_group_info(sb, group), i);
2211 ext4_unlock_group(sb, group);
2212 ext4_mb_unload_buddy(&e4b);
2214 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2215 sg.info.bb_fragments, sg.info.bb_first_free);
2216 for (i = 0; i <= 13; i++)
2217 seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2218 sg.info.bb_counters[i] : 0);
2219 seq_printf(seq, " ]\n");
2224 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2228 static const struct seq_operations ext4_mb_seq_groups_ops = {
2229 .start = ext4_mb_seq_groups_start,
2230 .next = ext4_mb_seq_groups_next,
2231 .stop = ext4_mb_seq_groups_stop,
2232 .show = ext4_mb_seq_groups_show,
2235 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2237 struct super_block *sb = PDE(inode)->data;
2240 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2242 struct seq_file *m = file->private_data;
2249 static const struct file_operations ext4_mb_seq_groups_fops = {
2250 .owner = THIS_MODULE,
2251 .open = ext4_mb_seq_groups_open,
2253 .llseek = seq_lseek,
2254 .release = seq_release,
2257 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2259 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2260 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2266 /* Create and initialize ext4_group_info data for the given group. */
2267 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2268 struct ext4_group_desc *desc)
2272 struct ext4_sb_info *sbi = EXT4_SB(sb);
2273 struct ext4_group_info **meta_group_info;
2274 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2277 * First check if this group is the first of a reserved block.
2278 * If it's true, we have to allocate a new table of pointers
2279 * to ext4_group_info structures
2281 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2282 metalen = sizeof(*meta_group_info) <<
2283 EXT4_DESC_PER_BLOCK_BITS(sb);
2284 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2285 if (meta_group_info == NULL) {
2286 printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2288 goto exit_meta_group_info;
2290 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] =
2295 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)];
2296 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2298 meta_group_info[i] = kmem_cache_alloc(cachep, GFP_KERNEL);
2299 if (meta_group_info[i] == NULL) {
2300 printk(KERN_ERR "EXT4-fs: can't allocate buddy mem\n");
2301 goto exit_group_info;
2303 memset(meta_group_info[i], 0, kmem_cache_size(cachep));
2304 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2305 &(meta_group_info[i]->bb_state));
2308 * initialize bb_free to be able to skip
2309 * empty groups without initialization
2311 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2312 meta_group_info[i]->bb_free =
2313 ext4_free_blocks_after_init(sb, group, desc);
2315 meta_group_info[i]->bb_free =
2316 ext4_free_blks_count(sb, desc);
2319 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2320 init_rwsem(&meta_group_info[i]->alloc_sem);
2321 meta_group_info[i]->bb_free_root = RB_ROOT;
2322 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
2326 struct buffer_head *bh;
2327 meta_group_info[i]->bb_bitmap =
2328 kmalloc(sb->s_blocksize, GFP_KERNEL);
2329 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2330 bh = ext4_read_block_bitmap(sb, group);
2332 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2341 /* If a meta_group_info table has been allocated, release it now */
2342 if (group % EXT4_DESC_PER_BLOCK(sb) == 0)
2343 kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
2344 exit_meta_group_info:
2346 } /* ext4_mb_add_groupinfo */
2348 static int ext4_mb_init_backend(struct super_block *sb)
2350 ext4_group_t ngroups = ext4_get_groups_count(sb);
2352 struct ext4_sb_info *sbi = EXT4_SB(sb);
2353 struct ext4_super_block *es = sbi->s_es;
2354 int num_meta_group_infos;
2355 int num_meta_group_infos_max;
2357 struct ext4_group_desc *desc;
2358 struct kmem_cache *cachep;
2360 /* This is the number of blocks used by GDT */
2361 num_meta_group_infos = (ngroups + EXT4_DESC_PER_BLOCK(sb) -
2362 1) >> EXT4_DESC_PER_BLOCK_BITS(sb);
2365 * This is the total number of blocks used by GDT including
2366 * the number of reserved blocks for GDT.
2367 * The s_group_info array is allocated with this value
2368 * to allow a clean online resize without a complex
2369 * manipulation of pointer.
2370 * The drawback is the unused memory when no resize
2371 * occurs but it's very low in terms of pages
2372 * (see comments below)
2373 * Need to handle this properly when META_BG resizing is allowed
2375 num_meta_group_infos_max = num_meta_group_infos +
2376 le16_to_cpu(es->s_reserved_gdt_blocks);
2379 * array_size is the size of s_group_info array. We round it
2380 * to the next power of two because this approximation is done
2381 * internally by kmalloc so we can have some more memory
2382 * for free here (e.g. may be used for META_BG resize).
2385 while (array_size < sizeof(*sbi->s_group_info) *
2386 num_meta_group_infos_max)
2387 array_size = array_size << 1;
2388 /* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2389 * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2390 * So a two level scheme suffices for now. */
2391 sbi->s_group_info = kzalloc(array_size, GFP_KERNEL);
2392 if (sbi->s_group_info == NULL) {
2393 printk(KERN_ERR "EXT4-fs: can't allocate buddy meta group\n");
2396 sbi->s_buddy_cache = new_inode(sb);
2397 if (sbi->s_buddy_cache == NULL) {
2398 printk(KERN_ERR "EXT4-fs: can't get new inode\n");
2401 sbi->s_buddy_cache->i_ino = get_next_ino();
2402 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2403 for (i = 0; i < ngroups; i++) {
2404 desc = ext4_get_group_desc(sb, i, NULL);
2407 "EXT4-fs: can't read descriptor %u\n", i);
2410 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2417 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2419 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2420 i = num_meta_group_infos;
2422 kfree(sbi->s_group_info[i]);
2423 iput(sbi->s_buddy_cache);
2425 kfree(sbi->s_group_info);
2429 static void ext4_groupinfo_destroy_slabs(void)
2433 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
2434 if (ext4_groupinfo_caches[i])
2435 kmem_cache_destroy(ext4_groupinfo_caches[i]);
2436 ext4_groupinfo_caches[i] = NULL;
2440 static int ext4_groupinfo_create_slab(size_t size)
2442 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
2444 int blocksize_bits = order_base_2(size);
2445 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2446 struct kmem_cache *cachep;
2448 if (cache_index >= NR_GRPINFO_CACHES)
2451 if (unlikely(cache_index < 0))
2454 mutex_lock(&ext4_grpinfo_slab_create_mutex);
2455 if (ext4_groupinfo_caches[cache_index]) {
2456 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2457 return 0; /* Already created */
2460 slab_size = offsetof(struct ext4_group_info,
2461 bb_counters[blocksize_bits + 2]);
2463 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
2464 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
2467 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2469 printk(KERN_EMERG "EXT4: no memory for groupinfo slab cache\n");
2473 ext4_groupinfo_caches[cache_index] = cachep;
2478 int ext4_mb_init(struct super_block *sb, int needs_recovery)
2480 struct ext4_sb_info *sbi = EXT4_SB(sb);
2486 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2488 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2489 if (sbi->s_mb_offsets == NULL) {
2494 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2495 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2496 if (sbi->s_mb_maxs == NULL) {
2501 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2505 /* order 0 is regular bitmap */
2506 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2507 sbi->s_mb_offsets[0] = 0;
2511 max = sb->s_blocksize << 2;
2513 sbi->s_mb_offsets[i] = offset;
2514 sbi->s_mb_maxs[i] = max;
2515 offset += 1 << (sb->s_blocksize_bits - i);
2518 } while (i <= sb->s_blocksize_bits + 1);
2520 /* init file for buddy data */
2521 ret = ext4_mb_init_backend(sb);
2526 spin_lock_init(&sbi->s_md_lock);
2527 spin_lock_init(&sbi->s_bal_lock);
2529 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2530 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2531 sbi->s_mb_stats = MB_DEFAULT_STATS;
2532 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2533 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2534 sbi->s_mb_group_prealloc = MB_DEFAULT_GROUP_PREALLOC;
2536 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2537 if (sbi->s_locality_groups == NULL) {
2541 for_each_possible_cpu(i) {
2542 struct ext4_locality_group *lg;
2543 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2544 mutex_init(&lg->lg_mutex);
2545 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2546 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2547 spin_lock_init(&lg->lg_prealloc_lock);
2551 proc_create_data("mb_groups", S_IRUGO, sbi->s_proc,
2552 &ext4_mb_seq_groups_fops, sb);
2555 sbi->s_journal->j_commit_callback = release_blocks_on_commit;
2558 kfree(sbi->s_mb_offsets);
2559 kfree(sbi->s_mb_maxs);
2564 /* need to called with the ext4 group lock held */
2565 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2567 struct ext4_prealloc_space *pa;
2568 struct list_head *cur, *tmp;
2571 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2572 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2573 list_del(&pa->pa_group_list);
2575 kmem_cache_free(ext4_pspace_cachep, pa);
2578 mb_debug(1, "mballoc: %u PAs left\n", count);
2582 int ext4_mb_release(struct super_block *sb)
2584 ext4_group_t ngroups = ext4_get_groups_count(sb);
2586 int num_meta_group_infos;
2587 struct ext4_group_info *grinfo;
2588 struct ext4_sb_info *sbi = EXT4_SB(sb);
2589 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2591 if (sbi->s_group_info) {
2592 for (i = 0; i < ngroups; i++) {
2593 grinfo = ext4_get_group_info(sb, i);
2595 kfree(grinfo->bb_bitmap);
2597 ext4_lock_group(sb, i);
2598 ext4_mb_cleanup_pa(grinfo);
2599 ext4_unlock_group(sb, i);
2600 kmem_cache_free(cachep, grinfo);
2602 num_meta_group_infos = (ngroups +
2603 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2604 EXT4_DESC_PER_BLOCK_BITS(sb);
2605 for (i = 0; i < num_meta_group_infos; i++)
2606 kfree(sbi->s_group_info[i]);
2607 kfree(sbi->s_group_info);
2609 kfree(sbi->s_mb_offsets);
2610 kfree(sbi->s_mb_maxs);
2611 if (sbi->s_buddy_cache)
2612 iput(sbi->s_buddy_cache);
2613 if (sbi->s_mb_stats) {
2615 "EXT4-fs: mballoc: %u blocks %u reqs (%u success)\n",
2616 atomic_read(&sbi->s_bal_allocated),
2617 atomic_read(&sbi->s_bal_reqs),
2618 atomic_read(&sbi->s_bal_success));
2620 "EXT4-fs: mballoc: %u extents scanned, %u goal hits, "
2621 "%u 2^N hits, %u breaks, %u lost\n",
2622 atomic_read(&sbi->s_bal_ex_scanned),
2623 atomic_read(&sbi->s_bal_goals),
2624 atomic_read(&sbi->s_bal_2orders),
2625 atomic_read(&sbi->s_bal_breaks),
2626 atomic_read(&sbi->s_mb_lost_chunks));
2628 "EXT4-fs: mballoc: %lu generated and it took %Lu\n",
2629 sbi->s_mb_buddies_generated++,
2630 sbi->s_mb_generation_time);
2632 "EXT4-fs: mballoc: %u preallocated, %u discarded\n",
2633 atomic_read(&sbi->s_mb_preallocated),
2634 atomic_read(&sbi->s_mb_discarded));
2637 free_percpu(sbi->s_locality_groups);
2639 remove_proc_entry("mb_groups", sbi->s_proc);
2644 static inline int ext4_issue_discard(struct super_block *sb,
2645 ext4_group_t block_group, ext4_grpblk_t block, int count)
2647 ext4_fsblk_t discard_block;
2649 discard_block = block + ext4_group_first_block_no(sb, block_group);
2650 trace_ext4_discard_blocks(sb,
2651 (unsigned long long) discard_block, count);
2652 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
2656 * This function is called by the jbd2 layer once the commit has finished,
2657 * so we know we can free the blocks that were released with that commit.
2659 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn)
2661 struct super_block *sb = journal->j_private;
2662 struct ext4_buddy e4b;
2663 struct ext4_group_info *db;
2664 int err, count = 0, count2 = 0;
2665 struct ext4_free_data *entry;
2666 struct list_head *l, *ltmp;
2668 list_for_each_safe(l, ltmp, &txn->t_private_list) {
2669 entry = list_entry(l, struct ext4_free_data, list);
2671 mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2672 entry->count, entry->group, entry);
2674 if (test_opt(sb, DISCARD))
2675 ext4_issue_discard(sb, entry->group,
2676 entry->start_blk, entry->count);
2678 err = ext4_mb_load_buddy(sb, entry->group, &e4b);
2679 /* we expect to find existing buddy because it's pinned */
2683 /* there are blocks to put in buddy to make them really free */
2684 count += entry->count;
2686 ext4_lock_group(sb, entry->group);
2687 /* Take it out of per group rb tree */
2688 rb_erase(&entry->node, &(db->bb_free_root));
2689 mb_free_blocks(NULL, &e4b, entry->start_blk, entry->count);
2691 if (!db->bb_free_root.rb_node) {
2692 /* No more items in the per group rb tree
2693 * balance refcounts from ext4_mb_free_metadata()
2695 page_cache_release(e4b.bd_buddy_page);
2696 page_cache_release(e4b.bd_bitmap_page);
2698 ext4_unlock_group(sb, entry->group);
2699 kmem_cache_free(ext4_free_ext_cachep, entry);
2700 ext4_mb_unload_buddy(&e4b);
2703 mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2706 #ifdef CONFIG_EXT4_DEBUG
2707 u8 mb_enable_debug __read_mostly;
2709 static struct dentry *debugfs_dir;
2710 static struct dentry *debugfs_debug;
2712 static void __init ext4_create_debugfs_entry(void)
2714 debugfs_dir = debugfs_create_dir("ext4", NULL);
2716 debugfs_debug = debugfs_create_u8("mballoc-debug",
2722 static void ext4_remove_debugfs_entry(void)
2724 debugfs_remove(debugfs_debug);
2725 debugfs_remove(debugfs_dir);
2730 static void __init ext4_create_debugfs_entry(void)
2734 static void ext4_remove_debugfs_entry(void)
2740 int __init ext4_init_mballoc(void)
2742 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
2743 SLAB_RECLAIM_ACCOUNT);
2744 if (ext4_pspace_cachep == NULL)
2747 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
2748 SLAB_RECLAIM_ACCOUNT);
2749 if (ext4_ac_cachep == NULL) {
2750 kmem_cache_destroy(ext4_pspace_cachep);
2754 ext4_free_ext_cachep = KMEM_CACHE(ext4_free_data,
2755 SLAB_RECLAIM_ACCOUNT);
2756 if (ext4_free_ext_cachep == NULL) {
2757 kmem_cache_destroy(ext4_pspace_cachep);
2758 kmem_cache_destroy(ext4_ac_cachep);
2761 ext4_create_debugfs_entry();
2765 void ext4_exit_mballoc(void)
2768 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
2769 * before destroying the slab cache.
2772 kmem_cache_destroy(ext4_pspace_cachep);
2773 kmem_cache_destroy(ext4_ac_cachep);
2774 kmem_cache_destroy(ext4_free_ext_cachep);
2775 ext4_groupinfo_destroy_slabs();
2776 ext4_remove_debugfs_entry();
2781 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2782 * Returns 0 if success or error code
2784 static noinline_for_stack int
2785 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2786 handle_t *handle, unsigned int reserv_blks)
2788 struct buffer_head *bitmap_bh = NULL;
2789 struct ext4_group_desc *gdp;
2790 struct buffer_head *gdp_bh;
2791 struct ext4_sb_info *sbi;
2792 struct super_block *sb;
2796 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2797 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2803 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2807 err = ext4_journal_get_write_access(handle, bitmap_bh);
2812 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2816 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
2817 ext4_free_blks_count(sb, gdp));
2819 err = ext4_journal_get_write_access(handle, gdp_bh);
2823 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
2825 len = ac->ac_b_ex.fe_len;
2826 if (!ext4_data_block_valid(sbi, block, len)) {
2827 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
2828 "fs metadata\n", block, block+len);
2829 /* File system mounted not to panic on error
2830 * Fix the bitmap and repeat the block allocation
2831 * We leak some of the blocks here.
2833 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2834 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2835 ac->ac_b_ex.fe_len);
2836 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
2837 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2843 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2844 #ifdef AGGRESSIVE_CHECK
2847 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
2848 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
2849 bitmap_bh->b_data));
2853 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,ac->ac_b_ex.fe_len);
2854 if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2855 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
2856 ext4_free_blks_set(sb, gdp,
2857 ext4_free_blocks_after_init(sb,
2858 ac->ac_b_ex.fe_group, gdp));
2860 len = ext4_free_blks_count(sb, gdp) - ac->ac_b_ex.fe_len;
2861 ext4_free_blks_set(sb, gdp, len);
2862 gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
2864 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
2865 percpu_counter_sub(&sbi->s_freeblocks_counter, ac->ac_b_ex.fe_len);
2867 * Now reduce the dirty block count also. Should not go negative
2869 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
2870 /* release all the reserved blocks if non delalloc */
2871 percpu_counter_sub(&sbi->s_dirtyblocks_counter, reserv_blks);
2873 if (sbi->s_log_groups_per_flex) {
2874 ext4_group_t flex_group = ext4_flex_group(sbi,
2875 ac->ac_b_ex.fe_group);
2876 atomic_sub(ac->ac_b_ex.fe_len,
2877 &sbi->s_flex_groups[flex_group].free_blocks);
2880 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2883 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
2886 ext4_mark_super_dirty(sb);
2892 * here we normalize request for locality group
2893 * Group request are normalized to s_strip size if we set the same via mount
2894 * option. If not we set it to s_mb_group_prealloc which can be configured via
2895 * /sys/fs/ext4/<partition>/mb_group_prealloc
2897 * XXX: should we try to preallocate more than the group has now?
2899 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
2901 struct super_block *sb = ac->ac_sb;
2902 struct ext4_locality_group *lg = ac->ac_lg;
2905 if (EXT4_SB(sb)->s_stripe)
2906 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_stripe;
2908 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
2909 mb_debug(1, "#%u: goal %u blocks for locality group\n",
2910 current->pid, ac->ac_g_ex.fe_len);
2914 * Normalization means making request better in terms of
2915 * size and alignment
2917 static noinline_for_stack void
2918 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
2919 struct ext4_allocation_request *ar)
2923 loff_t size, orig_size, start_off;
2925 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
2926 struct ext4_prealloc_space *pa;
2928 /* do normalize only data requests, metadata requests
2929 do not need preallocation */
2930 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
2933 /* sometime caller may want exact blocks */
2934 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2937 /* caller may indicate that preallocation isn't
2938 * required (it's a tail, for example) */
2939 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
2942 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
2943 ext4_mb_normalize_group_request(ac);
2947 bsbits = ac->ac_sb->s_blocksize_bits;
2949 /* first, let's learn actual file size
2950 * given current request is allocated */
2951 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
2952 size = size << bsbits;
2953 if (size < i_size_read(ac->ac_inode))
2954 size = i_size_read(ac->ac_inode);
2957 /* max size of free chunks */
2960 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
2961 (req <= (size) || max <= (chunk_size))
2963 /* first, try to predict filesize */
2964 /* XXX: should this table be tunable? */
2966 if (size <= 16 * 1024) {
2968 } else if (size <= 32 * 1024) {
2970 } else if (size <= 64 * 1024) {
2972 } else if (size <= 128 * 1024) {
2974 } else if (size <= 256 * 1024) {
2976 } else if (size <= 512 * 1024) {
2978 } else if (size <= 1024 * 1024) {
2980 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
2981 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2982 (21 - bsbits)) << 21;
2983 size = 2 * 1024 * 1024;
2984 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
2985 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2986 (22 - bsbits)) << 22;
2987 size = 4 * 1024 * 1024;
2988 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
2989 (8<<20)>>bsbits, max, 8 * 1024)) {
2990 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2991 (23 - bsbits)) << 23;
2992 size = 8 * 1024 * 1024;
2994 start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
2995 size = ac->ac_o_ex.fe_len << bsbits;
2997 size = size >> bsbits;
2998 start = start_off >> bsbits;
3000 /* don't cover already allocated blocks in selected range */
3001 if (ar->pleft && start <= ar->lleft) {
3002 size -= ar->lleft + 1 - start;
3003 start = ar->lleft + 1;
3005 if (ar->pright && start + size - 1 >= ar->lright)
3006 size -= start + size - ar->lright;
3010 /* check we don't cross already preallocated blocks */
3012 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3017 spin_lock(&pa->pa_lock);
3018 if (pa->pa_deleted) {
3019 spin_unlock(&pa->pa_lock);
3023 pa_end = pa->pa_lstart + pa->pa_len;
3025 /* PA must not overlap original request */
3026 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3027 ac->ac_o_ex.fe_logical < pa->pa_lstart));
3029 /* skip PAs this normalized request doesn't overlap with */
3030 if (pa->pa_lstart >= end || pa_end <= start) {
3031 spin_unlock(&pa->pa_lock);
3034 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3036 /* adjust start or end to be adjacent to this pa */
3037 if (pa_end <= ac->ac_o_ex.fe_logical) {
3038 BUG_ON(pa_end < start);
3040 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3041 BUG_ON(pa->pa_lstart > end);
3042 end = pa->pa_lstart;
3044 spin_unlock(&pa->pa_lock);
3049 /* XXX: extra loop to check we really don't overlap preallocations */
3051 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3053 spin_lock(&pa->pa_lock);
3054 if (pa->pa_deleted == 0) {
3055 pa_end = pa->pa_lstart + pa->pa_len;
3056 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3058 spin_unlock(&pa->pa_lock);
3062 if (start + size <= ac->ac_o_ex.fe_logical &&
3063 start > ac->ac_o_ex.fe_logical) {
3064 printk(KERN_ERR "start %lu, size %lu, fe_logical %lu\n",
3065 (unsigned long) start, (unsigned long) size,
3066 (unsigned long) ac->ac_o_ex.fe_logical);
3068 BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3069 start > ac->ac_o_ex.fe_logical);
3070 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3072 /* now prepare goal request */
3074 /* XXX: is it better to align blocks WRT to logical
3075 * placement or satisfy big request as is */
3076 ac->ac_g_ex.fe_logical = start;
3077 ac->ac_g_ex.fe_len = size;
3079 /* define goal start in order to merge */
3080 if (ar->pright && (ar->lright == (start + size))) {
3081 /* merge to the right */
3082 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3083 &ac->ac_f_ex.fe_group,
3084 &ac->ac_f_ex.fe_start);
3085 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3087 if (ar->pleft && (ar->lleft + 1 == start)) {
3088 /* merge to the left */
3089 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3090 &ac->ac_f_ex.fe_group,
3091 &ac->ac_f_ex.fe_start);
3092 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3095 mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3096 (unsigned) orig_size, (unsigned) start);
3099 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3101 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3103 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3104 atomic_inc(&sbi->s_bal_reqs);
3105 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3106 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3107 atomic_inc(&sbi->s_bal_success);
3108 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3109 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3110 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3111 atomic_inc(&sbi->s_bal_goals);
3112 if (ac->ac_found > sbi->s_mb_max_to_scan)
3113 atomic_inc(&sbi->s_bal_breaks);
3116 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3117 trace_ext4_mballoc_alloc(ac);
3119 trace_ext4_mballoc_prealloc(ac);
3123 * Called on failure; free up any blocks from the inode PA for this
3124 * context. We don't need this for MB_GROUP_PA because we only change
3125 * pa_free in ext4_mb_release_context(), but on failure, we've already
3126 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3128 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3130 struct ext4_prealloc_space *pa = ac->ac_pa;
3133 if (pa && pa->pa_type == MB_INODE_PA) {
3134 len = ac->ac_b_ex.fe_len;
3141 * use blocks preallocated to inode
3143 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3144 struct ext4_prealloc_space *pa)
3150 /* found preallocated blocks, use them */
3151 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3152 end = min(pa->pa_pstart + pa->pa_len, start + ac->ac_o_ex.fe_len);
3154 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3155 &ac->ac_b_ex.fe_start);
3156 ac->ac_b_ex.fe_len = len;
3157 ac->ac_status = AC_STATUS_FOUND;
3160 BUG_ON(start < pa->pa_pstart);
3161 BUG_ON(start + len > pa->pa_pstart + pa->pa_len);
3162 BUG_ON(pa->pa_free < len);
3165 mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3169 * use blocks preallocated to locality group
3171 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3172 struct ext4_prealloc_space *pa)
3174 unsigned int len = ac->ac_o_ex.fe_len;
3176 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3177 &ac->ac_b_ex.fe_group,
3178 &ac->ac_b_ex.fe_start);
3179 ac->ac_b_ex.fe_len = len;
3180 ac->ac_status = AC_STATUS_FOUND;
3183 /* we don't correct pa_pstart or pa_plen here to avoid
3184 * possible race when the group is being loaded concurrently
3185 * instead we correct pa later, after blocks are marked
3186 * in on-disk bitmap -- see ext4_mb_release_context()
3187 * Other CPUs are prevented from allocating from this pa by lg_mutex
3189 mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3193 * Return the prealloc space that have minimal distance
3194 * from the goal block. @cpa is the prealloc
3195 * space that is having currently known minimal distance
3196 * from the goal block.
3198 static struct ext4_prealloc_space *
3199 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3200 struct ext4_prealloc_space *pa,
3201 struct ext4_prealloc_space *cpa)
3203 ext4_fsblk_t cur_distance, new_distance;
3206 atomic_inc(&pa->pa_count);
3209 cur_distance = abs(goal_block - cpa->pa_pstart);
3210 new_distance = abs(goal_block - pa->pa_pstart);
3212 if (cur_distance <= new_distance)
3215 /* drop the previous reference */
3216 atomic_dec(&cpa->pa_count);
3217 atomic_inc(&pa->pa_count);
3222 * search goal blocks in preallocated space
3224 static noinline_for_stack int
3225 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3228 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3229 struct ext4_locality_group *lg;
3230 struct ext4_prealloc_space *pa, *cpa = NULL;
3231 ext4_fsblk_t goal_block;
3233 /* only data can be preallocated */
3234 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3237 /* first, try per-file preallocation */
3239 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3241 /* all fields in this condition don't change,
3242 * so we can skip locking for them */
3243 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3244 ac->ac_o_ex.fe_logical >= pa->pa_lstart + 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 + pa->pa_len > EXT4_MAX_BLOCK_FILE_PHYS)
3252 /* found preallocated blocks, use them */
3253 spin_lock(&pa->pa_lock);
3254 if (pa->pa_deleted == 0 && pa->pa_free) {
3255 atomic_inc(&pa->pa_count);
3256 ext4_mb_use_inode_pa(ac, pa);
3257 spin_unlock(&pa->pa_lock);
3258 ac->ac_criteria = 10;
3262 spin_unlock(&pa->pa_lock);
3266 /* can we use group allocation? */
3267 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3270 /* inode may have no locality group for some reason */
3274 order = fls(ac->ac_o_ex.fe_len) - 1;
3275 if (order > PREALLOC_TB_SIZE - 1)
3276 /* The max size of hash table is PREALLOC_TB_SIZE */
3277 order = PREALLOC_TB_SIZE - 1;
3279 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3281 * search for the prealloc space that is having
3282 * minimal distance from the goal block.
3284 for (i = order; i < PREALLOC_TB_SIZE; i++) {
3286 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3288 spin_lock(&pa->pa_lock);
3289 if (pa->pa_deleted == 0 &&
3290 pa->pa_free >= ac->ac_o_ex.fe_len) {
3292 cpa = ext4_mb_check_group_pa(goal_block,
3295 spin_unlock(&pa->pa_lock);
3300 ext4_mb_use_group_pa(ac, cpa);
3301 ac->ac_criteria = 20;
3308 * the function goes through all block freed in the group
3309 * but not yet committed and marks them used in in-core bitmap.
3310 * buddy must be generated from this bitmap
3311 * Need to be called with the ext4 group lock held
3313 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3317 struct ext4_group_info *grp;
3318 struct ext4_free_data *entry;
3320 grp = ext4_get_group_info(sb, group);
3321 n = rb_first(&(grp->bb_free_root));
3324 entry = rb_entry(n, struct ext4_free_data, node);
3325 mb_set_bits(bitmap, entry->start_blk, entry->count);
3332 * the function goes through all preallocation in this group and marks them
3333 * used in in-core bitmap. buddy must be generated from this bitmap
3334 * Need to be called with ext4 group lock held
3336 static noinline_for_stack
3337 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3340 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3341 struct ext4_prealloc_space *pa;
3342 struct list_head *cur;
3343 ext4_group_t groupnr;
3344 ext4_grpblk_t start;
3345 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 mb_set_bits(bitmap, start, len);
3368 preallocated += len;
3371 mb_debug(1, "prellocated %u for group %u\n", preallocated, group);
3374 static void ext4_mb_pa_callback(struct rcu_head *head)
3376 struct ext4_prealloc_space *pa;
3377 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3378 kmem_cache_free(ext4_pspace_cachep, pa);
3382 * drops a reference to preallocated space descriptor
3383 * if this was the last reference and the space is consumed
3385 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3386 struct super_block *sb, struct ext4_prealloc_space *pa)
3389 ext4_fsblk_t grp_blk;
3391 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3394 /* in this short window concurrent discard can set pa_deleted */
3395 spin_lock(&pa->pa_lock);
3396 if (pa->pa_deleted == 1) {
3397 spin_unlock(&pa->pa_lock);
3402 spin_unlock(&pa->pa_lock);
3404 grp_blk = pa->pa_pstart;
3406 * If doing group-based preallocation, pa_pstart may be in the
3407 * next group when pa is used up
3409 if (pa->pa_type == MB_GROUP_PA)
3412 ext4_get_group_no_and_offset(sb, grp_blk, &grp, NULL);
3417 * P1 (buddy init) P2 (regular allocation)
3418 * find block B in PA
3419 * copy on-disk bitmap to buddy
3420 * mark B in on-disk bitmap
3421 * drop PA from group
3422 * mark all PAs in buddy
3424 * thus, P1 initializes buddy with B available. to prevent this
3425 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3428 ext4_lock_group(sb, grp);
3429 list_del(&pa->pa_group_list);
3430 ext4_unlock_group(sb, grp);
3432 spin_lock(pa->pa_obj_lock);
3433 list_del_rcu(&pa->pa_inode_list);
3434 spin_unlock(pa->pa_obj_lock);
3436 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3440 * creates new preallocated space for given inode
3442 static noinline_for_stack int
3443 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3445 struct super_block *sb = ac->ac_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 = 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 % ac->ac_b_ex.fe_len;
3483 if (offs && offs < win)
3486 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical - win;
3487 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3488 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3491 /* preallocation can change ac_b_ex, thus we store actually
3492 * allocated blocks for history */
3493 ac->ac_f_ex = ac->ac_b_ex;
3495 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3496 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3497 pa->pa_len = ac->ac_b_ex.fe_len;
3498 pa->pa_free = pa->pa_len;
3499 atomic_set(&pa->pa_count, 1);
3500 spin_lock_init(&pa->pa_lock);
3501 INIT_LIST_HEAD(&pa->pa_inode_list);
3502 INIT_LIST_HEAD(&pa->pa_group_list);
3504 pa->pa_type = MB_INODE_PA;
3506 mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3507 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3508 trace_ext4_mb_new_inode_pa(ac, pa);
3510 ext4_mb_use_inode_pa(ac, pa);
3511 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3513 ei = EXT4_I(ac->ac_inode);
3514 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3516 pa->pa_obj_lock = &ei->i_prealloc_lock;
3517 pa->pa_inode = ac->ac_inode;
3519 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3520 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3521 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3523 spin_lock(pa->pa_obj_lock);
3524 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3525 spin_unlock(pa->pa_obj_lock);
3531 * creates new preallocated space for locality group inodes belongs to
3533 static noinline_for_stack int
3534 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3536 struct super_block *sb = ac->ac_sb;
3537 struct ext4_locality_group *lg;
3538 struct ext4_prealloc_space *pa;
3539 struct ext4_group_info *grp;
3541 /* preallocate only when found space is larger then requested */
3542 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3543 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3544 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3546 BUG_ON(ext4_pspace_cachep == NULL);
3547 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3551 /* preallocation can change ac_b_ex, thus we store actually
3552 * allocated blocks for history */
3553 ac->ac_f_ex = ac->ac_b_ex;
3555 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3556 pa->pa_lstart = pa->pa_pstart;
3557 pa->pa_len = ac->ac_b_ex.fe_len;
3558 pa->pa_free = pa->pa_len;
3559 atomic_set(&pa->pa_count, 1);
3560 spin_lock_init(&pa->pa_lock);
3561 INIT_LIST_HEAD(&pa->pa_inode_list);
3562 INIT_LIST_HEAD(&pa->pa_group_list);
3564 pa->pa_type = MB_GROUP_PA;
3566 mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3567 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3568 trace_ext4_mb_new_group_pa(ac, pa);
3570 ext4_mb_use_group_pa(ac, pa);
3571 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3573 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3577 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3578 pa->pa_inode = NULL;
3580 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3581 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3582 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3585 * We will later add the new pa to the right bucket
3586 * after updating the pa_free in ext4_mb_release_context
3591 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3595 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3596 err = ext4_mb_new_group_pa(ac);
3598 err = ext4_mb_new_inode_pa(ac);
3603 * finds all unused blocks in on-disk bitmap, frees them in
3604 * in-core bitmap and buddy.
3605 * @pa must be unlinked from inode and group lists, so that
3606 * nobody else can find/use it.
3607 * the caller MUST hold group/inode locks.
3608 * TODO: optimize the case when there are no in-core structures yet
3610 static noinline_for_stack int
3611 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3612 struct ext4_prealloc_space *pa)
3614 struct super_block *sb = e4b->bd_sb;
3615 struct ext4_sb_info *sbi = EXT4_SB(sb);
3620 unsigned long long grp_blk_start;
3624 BUG_ON(pa->pa_deleted == 0);
3625 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3626 grp_blk_start = pa->pa_pstart - bit;
3627 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3628 end = bit + pa->pa_len;
3631 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3634 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3635 mb_debug(1, " free preallocated %u/%u in group %u\n",
3636 (unsigned) ext4_group_first_block_no(sb, group) + bit,
3637 (unsigned) next - bit, (unsigned) group);
3640 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
3641 trace_ext4_mb_release_inode_pa(sb, pa->pa_inode, pa,
3642 grp_blk_start + bit, next - bit);
3643 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3646 if (free != pa->pa_free) {
3647 printk(KERN_CRIT "pa %p: logic %lu, phys. %lu, len %lu\n",
3648 pa, (unsigned long) pa->pa_lstart,
3649 (unsigned long) pa->pa_pstart,
3650 (unsigned long) pa->pa_len);
3651 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
3654 * pa is already deleted so we use the value obtained
3655 * from the bitmap and continue.
3658 atomic_add(free, &sbi->s_mb_discarded);
3663 static noinline_for_stack int
3664 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3665 struct ext4_prealloc_space *pa)
3667 struct super_block *sb = e4b->bd_sb;
3671 trace_ext4_mb_release_group_pa(sb, pa);
3672 BUG_ON(pa->pa_deleted == 0);
3673 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3674 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3675 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3676 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3677 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3683 * releases all preallocations in given group
3685 * first, we need to decide discard policy:
3686 * - when do we discard
3688 * - how many do we discard
3689 * 1) how many requested
3691 static noinline_for_stack int
3692 ext4_mb_discard_group_preallocations(struct super_block *sb,
3693 ext4_group_t group, int needed)
3695 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3696 struct buffer_head *bitmap_bh = NULL;
3697 struct ext4_prealloc_space *pa, *tmp;
3698 struct list_head list;
3699 struct ext4_buddy e4b;
3704 mb_debug(1, "discard preallocation for group %u\n", group);
3706 if (list_empty(&grp->bb_prealloc_list))
3709 bitmap_bh = ext4_read_block_bitmap(sb, group);
3710 if (bitmap_bh == NULL) {
3711 ext4_error(sb, "Error reading block bitmap for %u", group);
3715 err = ext4_mb_load_buddy(sb, group, &e4b);
3717 ext4_error(sb, "Error loading buddy information for %u", group);
3723 needed = EXT4_BLOCKS_PER_GROUP(sb) + 1;
3725 INIT_LIST_HEAD(&list);
3727 ext4_lock_group(sb, group);
3728 list_for_each_entry_safe(pa, tmp,
3729 &grp->bb_prealloc_list, pa_group_list) {
3730 spin_lock(&pa->pa_lock);
3731 if (atomic_read(&pa->pa_count)) {
3732 spin_unlock(&pa->pa_lock);
3736 if (pa->pa_deleted) {
3737 spin_unlock(&pa->pa_lock);
3741 /* seems this one can be freed ... */
3744 /* we can trust pa_free ... */
3745 free += pa->pa_free;
3747 spin_unlock(&pa->pa_lock);
3749 list_del(&pa->pa_group_list);
3750 list_add(&pa->u.pa_tmp_list, &list);
3753 /* if we still need more blocks and some PAs were used, try again */
3754 if (free < needed && busy) {
3756 ext4_unlock_group(sb, group);
3758 * Yield the CPU here so that we don't get soft lockup
3759 * in non preempt case.
3765 /* found anything to free? */
3766 if (list_empty(&list)) {
3771 /* now free all selected PAs */
3772 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3774 /* remove from object (inode or locality group) */
3775 spin_lock(pa->pa_obj_lock);
3776 list_del_rcu(&pa->pa_inode_list);
3777 spin_unlock(pa->pa_obj_lock);
3779 if (pa->pa_type == MB_GROUP_PA)
3780 ext4_mb_release_group_pa(&e4b, pa);
3782 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3784 list_del(&pa->u.pa_tmp_list);
3785 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3789 ext4_unlock_group(sb, group);
3790 ext4_mb_unload_buddy(&e4b);
3796 * releases all non-used preallocated blocks for given inode
3798 * It's important to discard preallocations under i_data_sem
3799 * We don't want another block to be served from the prealloc
3800 * space when we are discarding the inode prealloc space.
3802 * FIXME!! Make sure it is valid at all the call sites
3804 void ext4_discard_preallocations(struct inode *inode)
3806 struct ext4_inode_info *ei = EXT4_I(inode);
3807 struct super_block *sb = inode->i_sb;
3808 struct buffer_head *bitmap_bh = NULL;
3809 struct ext4_prealloc_space *pa, *tmp;
3810 ext4_group_t group = 0;
3811 struct list_head list;
3812 struct ext4_buddy e4b;
3815 if (!S_ISREG(inode->i_mode)) {
3816 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
3820 mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
3821 trace_ext4_discard_preallocations(inode);
3823 INIT_LIST_HEAD(&list);
3826 /* first, collect all pa's in the inode */
3827 spin_lock(&ei->i_prealloc_lock);
3828 while (!list_empty(&ei->i_prealloc_list)) {
3829 pa = list_entry(ei->i_prealloc_list.next,
3830 struct ext4_prealloc_space, pa_inode_list);
3831 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
3832 spin_lock(&pa->pa_lock);
3833 if (atomic_read(&pa->pa_count)) {
3834 /* this shouldn't happen often - nobody should
3835 * use preallocation while we're discarding it */
3836 spin_unlock(&pa->pa_lock);
3837 spin_unlock(&ei->i_prealloc_lock);
3838 printk(KERN_ERR "uh-oh! used pa while discarding\n");
3840 schedule_timeout_uninterruptible(HZ);
3844 if (pa->pa_deleted == 0) {
3846 spin_unlock(&pa->pa_lock);
3847 list_del_rcu(&pa->pa_inode_list);
3848 list_add(&pa->u.pa_tmp_list, &list);
3852 /* someone is deleting pa right now */
3853 spin_unlock(&pa->pa_lock);
3854 spin_unlock(&ei->i_prealloc_lock);
3856 /* we have to wait here because pa_deleted
3857 * doesn't mean pa is already unlinked from
3858 * the list. as we might be called from
3859 * ->clear_inode() the inode will get freed
3860 * and concurrent thread which is unlinking
3861 * pa from inode's list may access already
3862 * freed memory, bad-bad-bad */
3864 /* XXX: if this happens too often, we can
3865 * add a flag to force wait only in case
3866 * of ->clear_inode(), but not in case of
3867 * regular truncate */
3868 schedule_timeout_uninterruptible(HZ);
3871 spin_unlock(&ei->i_prealloc_lock);
3873 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3874 BUG_ON(pa->pa_type != MB_INODE_PA);
3875 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
3877 err = ext4_mb_load_buddy(sb, group, &e4b);
3879 ext4_error(sb, "Error loading buddy information for %u",
3884 bitmap_bh = ext4_read_block_bitmap(sb, group);
3885 if (bitmap_bh == NULL) {
3886 ext4_error(sb, "Error reading block bitmap for %u",
3888 ext4_mb_unload_buddy(&e4b);
3892 ext4_lock_group(sb, group);
3893 list_del(&pa->pa_group_list);
3894 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3895 ext4_unlock_group(sb, group);
3897 ext4_mb_unload_buddy(&e4b);
3900 list_del(&pa->u.pa_tmp_list);
3901 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3905 #ifdef CONFIG_EXT4_DEBUG
3906 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3908 struct super_block *sb = ac->ac_sb;
3909 ext4_group_t ngroups, i;
3911 if (!mb_enable_debug ||
3912 (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
3915 printk(KERN_ERR "EXT4-fs: Can't allocate:"
3916 " Allocation context details:\n");
3917 printk(KERN_ERR "EXT4-fs: status %d flags %d\n",
3918 ac->ac_status, ac->ac_flags);
3919 printk(KERN_ERR "EXT4-fs: orig %lu/%lu/%lu@%lu, goal %lu/%lu/%lu@%lu, "
3920 "best %lu/%lu/%lu@%lu cr %d\n",
3921 (unsigned long)ac->ac_o_ex.fe_group,
3922 (unsigned long)ac->ac_o_ex.fe_start,
3923 (unsigned long)ac->ac_o_ex.fe_len,
3924 (unsigned long)ac->ac_o_ex.fe_logical,
3925 (unsigned long)ac->ac_g_ex.fe_group,
3926 (unsigned long)ac->ac_g_ex.fe_start,
3927 (unsigned long)ac->ac_g_ex.fe_len,
3928 (unsigned long)ac->ac_g_ex.fe_logical,
3929 (unsigned long)ac->ac_b_ex.fe_group,
3930 (unsigned long)ac->ac_b_ex.fe_start,
3931 (unsigned long)ac->ac_b_ex.fe_len,
3932 (unsigned long)ac->ac_b_ex.fe_logical,
3933 (int)ac->ac_criteria);
3934 printk(KERN_ERR "EXT4-fs: %lu scanned, %d found\n", ac->ac_ex_scanned,
3936 printk(KERN_ERR "EXT4-fs: groups: \n");
3937 ngroups = ext4_get_groups_count(sb);
3938 for (i = 0; i < ngroups; i++) {
3939 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3940 struct ext4_prealloc_space *pa;
3941 ext4_grpblk_t start;
3942 struct list_head *cur;
3943 ext4_lock_group(sb, i);
3944 list_for_each(cur, &grp->bb_prealloc_list) {
3945 pa = list_entry(cur, struct ext4_prealloc_space,
3947 spin_lock(&pa->pa_lock);
3948 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3950 spin_unlock(&pa->pa_lock);
3951 printk(KERN_ERR "PA:%u:%d:%u \n", i,
3954 ext4_unlock_group(sb, i);
3956 if (grp->bb_free == 0)
3958 printk(KERN_ERR "%u: %d/%d \n",
3959 i, grp->bb_free, grp->bb_fragments);
3961 printk(KERN_ERR "\n");
3964 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3971 * We use locality group preallocation for small size file. The size of the
3972 * file is determined by the current size or the resulting size after
3973 * allocation which ever is larger
3975 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
3977 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
3979 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3980 int bsbits = ac->ac_sb->s_blocksize_bits;
3983 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3986 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3989 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
3990 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
3993 if ((size == isize) &&
3994 !ext4_fs_is_busy(sbi) &&
3995 (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
3996 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
4000 /* don't use group allocation for large files */
4001 size = max(size, isize);
4002 if (size > sbi->s_mb_stream_request) {
4003 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4007 BUG_ON(ac->ac_lg != NULL);
4009 * locality group prealloc space are per cpu. The reason for having
4010 * per cpu locality group is to reduce the contention between block
4011 * request from multiple CPUs.
4013 ac->ac_lg = __this_cpu_ptr(sbi->s_locality_groups);
4015 /* we're going to use group allocation */
4016 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4018 /* serialize all allocations in the group */
4019 mutex_lock(&ac->ac_lg->lg_mutex);
4022 static noinline_for_stack int
4023 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4024 struct ext4_allocation_request *ar)
4026 struct super_block *sb = ar->inode->i_sb;
4027 struct ext4_sb_info *sbi = EXT4_SB(sb);
4028 struct ext4_super_block *es = sbi->s_es;
4032 ext4_grpblk_t block;
4034 /* we can't allocate > group size */
4037 /* just a dirty hack to filter too big requests */
4038 if (len >= EXT4_BLOCKS_PER_GROUP(sb) - 10)
4039 len = EXT4_BLOCKS_PER_GROUP(sb) - 10;
4041 /* start searching from the goal */
4043 if (goal < le32_to_cpu(es->s_first_data_block) ||
4044 goal >= ext4_blocks_count(es))
4045 goal = le32_to_cpu(es->s_first_data_block);
4046 ext4_get_group_no_and_offset(sb, goal, &group, &block);
4048 /* set up allocation goals */
4049 memset(ac, 0, sizeof(struct ext4_allocation_context));
4050 ac->ac_b_ex.fe_logical = ar->logical;
4051 ac->ac_status = AC_STATUS_CONTINUE;
4053 ac->ac_inode = ar->inode;
4054 ac->ac_o_ex.fe_logical = ar->logical;
4055 ac->ac_o_ex.fe_group = group;
4056 ac->ac_o_ex.fe_start = block;
4057 ac->ac_o_ex.fe_len = len;
4058 ac->ac_g_ex.fe_logical = ar->logical;
4059 ac->ac_g_ex.fe_group = group;
4060 ac->ac_g_ex.fe_start = block;
4061 ac->ac_g_ex.fe_len = len;
4062 ac->ac_flags = ar->flags;
4064 /* we have to define context: we'll we work with a file or
4065 * locality group. this is a policy, actually */
4066 ext4_mb_group_or_file(ac);
4068 mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4069 "left: %u/%u, right %u/%u to %swritable\n",
4070 (unsigned) ar->len, (unsigned) ar->logical,
4071 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4072 (unsigned) ar->lleft, (unsigned) ar->pleft,
4073 (unsigned) ar->lright, (unsigned) ar->pright,
4074 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4079 static noinline_for_stack void
4080 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4081 struct ext4_locality_group *lg,
4082 int order, int total_entries)
4084 ext4_group_t group = 0;
4085 struct ext4_buddy e4b;
4086 struct list_head discard_list;
4087 struct ext4_prealloc_space *pa, *tmp;
4089 mb_debug(1, "discard locality group preallocation\n");
4091 INIT_LIST_HEAD(&discard_list);
4093 spin_lock(&lg->lg_prealloc_lock);
4094 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4096 spin_lock(&pa->pa_lock);
4097 if (atomic_read(&pa->pa_count)) {
4099 * This is the pa that we just used
4100 * for block allocation. So don't
4103 spin_unlock(&pa->pa_lock);
4106 if (pa->pa_deleted) {
4107 spin_unlock(&pa->pa_lock);
4110 /* only lg prealloc space */
4111 BUG_ON(pa->pa_type != MB_GROUP_PA);
4113 /* seems this one can be freed ... */
4115 spin_unlock(&pa->pa_lock);
4117 list_del_rcu(&pa->pa_inode_list);
4118 list_add(&pa->u.pa_tmp_list, &discard_list);
4121 if (total_entries <= 5) {
4123 * we want to keep only 5 entries
4124 * allowing it to grow to 8. This
4125 * mak sure we don't call discard
4126 * soon for this list.
4131 spin_unlock(&lg->lg_prealloc_lock);
4133 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4135 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
4136 if (ext4_mb_load_buddy(sb, group, &e4b)) {
4137 ext4_error(sb, "Error loading buddy information for %u",
4141 ext4_lock_group(sb, group);
4142 list_del(&pa->pa_group_list);
4143 ext4_mb_release_group_pa(&e4b, pa);
4144 ext4_unlock_group(sb, group);
4146 ext4_mb_unload_buddy(&e4b);
4147 list_del(&pa->u.pa_tmp_list);
4148 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4153 * We have incremented pa_count. So it cannot be freed at this
4154 * point. Also we hold lg_mutex. So no parallel allocation is
4155 * possible from this lg. That means pa_free cannot be updated.
4157 * A parallel ext4_mb_discard_group_preallocations is possible.
4158 * which can cause the lg_prealloc_list to be updated.
4161 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4163 int order, added = 0, lg_prealloc_count = 1;
4164 struct super_block *sb = ac->ac_sb;
4165 struct ext4_locality_group *lg = ac->ac_lg;
4166 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4168 order = fls(pa->pa_free) - 1;
4169 if (order > PREALLOC_TB_SIZE - 1)
4170 /* The max size of hash table is PREALLOC_TB_SIZE */
4171 order = PREALLOC_TB_SIZE - 1;
4172 /* Add the prealloc space to lg */
4174 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4176 spin_lock(&tmp_pa->pa_lock);
4177 if (tmp_pa->pa_deleted) {
4178 spin_unlock(&tmp_pa->pa_lock);
4181 if (!added && pa->pa_free < tmp_pa->pa_free) {
4182 /* Add to the tail of the previous entry */
4183 list_add_tail_rcu(&pa->pa_inode_list,
4184 &tmp_pa->pa_inode_list);
4187 * we want to count the total
4188 * number of entries in the list
4191 spin_unlock(&tmp_pa->pa_lock);
4192 lg_prealloc_count++;
4195 list_add_tail_rcu(&pa->pa_inode_list,
4196 &lg->lg_prealloc_list[order]);
4199 /* Now trim the list to be not more than 8 elements */
4200 if (lg_prealloc_count > 8) {
4201 ext4_mb_discard_lg_preallocations(sb, lg,
4202 order, lg_prealloc_count);
4209 * release all resource we used in allocation
4211 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4213 struct ext4_prealloc_space *pa = ac->ac_pa;
4215 if (pa->pa_type == MB_GROUP_PA) {
4216 /* see comment in ext4_mb_use_group_pa() */
4217 spin_lock(&pa->pa_lock);
4218 pa->pa_pstart += ac->ac_b_ex.fe_len;
4219 pa->pa_lstart += ac->ac_b_ex.fe_len;
4220 pa->pa_free -= ac->ac_b_ex.fe_len;
4221 pa->pa_len -= ac->ac_b_ex.fe_len;
4222 spin_unlock(&pa->pa_lock);
4226 up_read(ac->alloc_semp);
4229 * We want to add the pa to the right bucket.
4230 * Remove it from the list and while adding
4231 * make sure the list to which we are adding
4232 * doesn't grow big. We need to release
4233 * alloc_semp before calling ext4_mb_add_n_trim()
4235 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4236 spin_lock(pa->pa_obj_lock);
4237 list_del_rcu(&pa->pa_inode_list);
4238 spin_unlock(pa->pa_obj_lock);
4239 ext4_mb_add_n_trim(ac);
4241 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4243 if (ac->ac_bitmap_page)
4244 page_cache_release(ac->ac_bitmap_page);
4245 if (ac->ac_buddy_page)
4246 page_cache_release(ac->ac_buddy_page);
4247 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4248 mutex_unlock(&ac->ac_lg->lg_mutex);
4249 ext4_mb_collect_stats(ac);
4253 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4255 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4259 trace_ext4_mb_discard_preallocations(sb, needed);
4260 for (i = 0; i < ngroups && needed > 0; i++) {
4261 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4270 * Main entry point into mballoc to allocate blocks
4271 * it tries to use preallocation first, then falls back
4272 * to usual allocation
4274 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4275 struct ext4_allocation_request *ar, int *errp)
4278 struct ext4_allocation_context *ac = NULL;
4279 struct ext4_sb_info *sbi;
4280 struct super_block *sb;
4281 ext4_fsblk_t block = 0;
4282 unsigned int inquota = 0;
4283 unsigned int reserv_blks = 0;
4285 sb = ar->inode->i_sb;
4288 trace_ext4_request_blocks(ar);
4291 * For delayed allocation, we could skip the ENOSPC and
4292 * EDQUOT check, as blocks and quotas have been already
4293 * reserved when data being copied into pagecache.
4295 if (ext4_test_inode_state(ar->inode, EXT4_STATE_DELALLOC_RESERVED))
4296 ar->flags |= EXT4_MB_DELALLOC_RESERVED;
4298 /* Without delayed allocation we need to verify
4299 * there is enough free blocks to do block allocation
4300 * and verify allocation doesn't exceed the quota limits.
4302 while (ar->len && ext4_claim_free_blocks(sbi, ar->len)) {
4303 /* let others to free the space */
4305 ar->len = ar->len >> 1;
4311 reserv_blks = ar->len;
4312 while (ar->len && dquot_alloc_block(ar->inode, ar->len)) {
4313 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4323 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4330 *errp = ext4_mb_initialize_context(ac, ar);
4336 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4337 if (!ext4_mb_use_preallocated(ac)) {
4338 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4339 ext4_mb_normalize_request(ac, ar);
4341 /* allocate space in core */
4342 *errp = ext4_mb_regular_allocator(ac);
4346 /* as we've just preallocated more space than
4347 * user requested orinally, we store allocated
4348 * space in a special descriptor */
4349 if (ac->ac_status == AC_STATUS_FOUND &&
4350 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4351 ext4_mb_new_preallocation(ac);
4353 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4354 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_blks);
4355 if (*errp == -EAGAIN) {
4357 * drop the reference that we took
4358 * in ext4_mb_use_best_found
4360 ext4_mb_release_context(ac);
4361 ac->ac_b_ex.fe_group = 0;
4362 ac->ac_b_ex.fe_start = 0;
4363 ac->ac_b_ex.fe_len = 0;
4364 ac->ac_status = AC_STATUS_CONTINUE;
4368 ext4_discard_allocated_blocks(ac);
4370 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4371 ar->len = ac->ac_b_ex.fe_len;
4374 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4381 ac->ac_b_ex.fe_len = 0;
4383 ext4_mb_show_ac(ac);
4385 ext4_mb_release_context(ac);
4388 kmem_cache_free(ext4_ac_cachep, ac);
4389 if (inquota && ar->len < inquota)
4390 dquot_free_block(ar->inode, inquota - ar->len);
4392 if (!ext4_test_inode_state(ar->inode,
4393 EXT4_STATE_DELALLOC_RESERVED))
4394 /* release all the reserved blocks if non delalloc */
4395 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
4399 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4405 * We can merge two free data extents only if the physical blocks
4406 * are contiguous, AND the extents were freed by the same transaction,
4407 * AND the blocks are associated with the same group.
4409 static int can_merge(struct ext4_free_data *entry1,
4410 struct ext4_free_data *entry2)
4412 if ((entry1->t_tid == entry2->t_tid) &&
4413 (entry1->group == entry2->group) &&
4414 ((entry1->start_blk + entry1->count) == entry2->start_blk))
4419 static noinline_for_stack int
4420 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4421 struct ext4_free_data *new_entry)
4423 ext4_group_t group = e4b->bd_group;
4424 ext4_grpblk_t block;
4425 struct ext4_free_data *entry;
4426 struct ext4_group_info *db = e4b->bd_info;
4427 struct super_block *sb = e4b->bd_sb;
4428 struct ext4_sb_info *sbi = EXT4_SB(sb);
4429 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4430 struct rb_node *parent = NULL, *new_node;
4432 BUG_ON(!ext4_handle_valid(handle));
4433 BUG_ON(e4b->bd_bitmap_page == NULL);
4434 BUG_ON(e4b->bd_buddy_page == NULL);
4436 new_node = &new_entry->node;
4437 block = new_entry->start_blk;
4440 /* first free block exent. We need to
4441 protect buddy cache from being freed,
4442 * otherwise we'll refresh it from
4443 * on-disk bitmap and lose not-yet-available
4445 page_cache_get(e4b->bd_buddy_page);
4446 page_cache_get(e4b->bd_bitmap_page);
4450 entry = rb_entry(parent, struct ext4_free_data, node);
4451 if (block < entry->start_blk)
4453 else if (block >= (entry->start_blk + entry->count))
4454 n = &(*n)->rb_right;
4456 ext4_grp_locked_error(sb, group, 0,
4457 ext4_group_first_block_no(sb, group) + block,
4458 "Block already on to-be-freed list");
4463 rb_link_node(new_node, parent, n);
4464 rb_insert_color(new_node, &db->bb_free_root);
4466 /* Now try to see the extent can be merged to left and right */
4467 node = rb_prev(new_node);
4469 entry = rb_entry(node, struct ext4_free_data, node);
4470 if (can_merge(entry, new_entry)) {
4471 new_entry->start_blk = entry->start_blk;
4472 new_entry->count += entry->count;
4473 rb_erase(node, &(db->bb_free_root));
4474 spin_lock(&sbi->s_md_lock);
4475 list_del(&entry->list);
4476 spin_unlock(&sbi->s_md_lock);
4477 kmem_cache_free(ext4_free_ext_cachep, entry);
4481 node = rb_next(new_node);
4483 entry = rb_entry(node, struct ext4_free_data, node);
4484 if (can_merge(new_entry, entry)) {
4485 new_entry->count += entry->count;
4486 rb_erase(node, &(db->bb_free_root));
4487 spin_lock(&sbi->s_md_lock);
4488 list_del(&entry->list);
4489 spin_unlock(&sbi->s_md_lock);
4490 kmem_cache_free(ext4_free_ext_cachep, entry);
4493 /* Add the extent to transaction's private list */
4494 spin_lock(&sbi->s_md_lock);
4495 list_add(&new_entry->list, &handle->h_transaction->t_private_list);
4496 spin_unlock(&sbi->s_md_lock);
4501 * ext4_free_blocks() -- Free given blocks and update quota
4502 * @handle: handle for this transaction
4504 * @block: start physical block to free
4505 * @count: number of blocks to count
4506 * @metadata: Are these metadata blocks
4508 void ext4_free_blocks(handle_t *handle, struct inode *inode,
4509 struct buffer_head *bh, ext4_fsblk_t block,
4510 unsigned long count, int flags)
4512 struct buffer_head *bitmap_bh = NULL;
4513 struct super_block *sb = inode->i_sb;
4514 struct ext4_group_desc *gdp;
4515 unsigned long freed = 0;
4516 unsigned int overflow;
4518 struct buffer_head *gd_bh;
4519 ext4_group_t block_group;
4520 struct ext4_sb_info *sbi;
4521 struct ext4_buddy e4b;
4527 BUG_ON(block != bh->b_blocknr);
4529 block = bh->b_blocknr;
4533 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
4534 !ext4_data_block_valid(sbi, block, count)) {
4535 ext4_error(sb, "Freeing blocks not in datazone - "
4536 "block = %llu, count = %lu", block, count);
4540 ext4_debug("freeing block %llu\n", block);
4541 trace_ext4_free_blocks(inode, block, count, flags);
4543 if (flags & EXT4_FREE_BLOCKS_FORGET) {
4544 struct buffer_head *tbh = bh;
4547 BUG_ON(bh && (count > 1));
4549 for (i = 0; i < count; i++) {
4551 tbh = sb_find_get_block(inode->i_sb,
4555 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4556 inode, tbh, block + i);
4561 * We need to make sure we don't reuse the freed block until
4562 * after the transaction is committed, which we can do by
4563 * treating the block as metadata, below. We make an
4564 * exception if the inode is to be written in writeback mode
4565 * since writeback mode has weak data consistency guarantees.
4567 if (!ext4_should_writeback_data(inode))
4568 flags |= EXT4_FREE_BLOCKS_METADATA;
4572 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4575 * Check to see if we are freeing blocks across a group
4578 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4579 overflow = bit + count - EXT4_BLOCKS_PER_GROUP(sb);
4582 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4587 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4593 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4594 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4595 in_range(block, ext4_inode_table(sb, gdp),
4596 EXT4_SB(sb)->s_itb_per_group) ||
4597 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4598 EXT4_SB(sb)->s_itb_per_group)) {
4600 ext4_error(sb, "Freeing blocks in system zone - "
4601 "Block = %llu, count = %lu", block, count);
4602 /* err = 0. ext4_std_error should be a no op */
4606 BUFFER_TRACE(bitmap_bh, "getting write access");
4607 err = ext4_journal_get_write_access(handle, bitmap_bh);
4612 * We are about to modify some metadata. Call the journal APIs
4613 * to unshare ->b_data if a currently-committing transaction is
4616 BUFFER_TRACE(gd_bh, "get_write_access");
4617 err = ext4_journal_get_write_access(handle, gd_bh);
4620 #ifdef AGGRESSIVE_CHECK
4623 for (i = 0; i < count; i++)
4624 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4627 trace_ext4_mballoc_free(sb, inode, block_group, bit, count);
4629 err = ext4_mb_load_buddy(sb, block_group, &e4b);
4633 if ((flags & EXT4_FREE_BLOCKS_METADATA) && ext4_handle_valid(handle)) {
4634 struct ext4_free_data *new_entry;
4636 * blocks being freed are metadata. these blocks shouldn't
4637 * be used until this transaction is committed
4639 new_entry = kmem_cache_alloc(ext4_free_ext_cachep, GFP_NOFS);
4644 new_entry->start_blk = bit;
4645 new_entry->group = block_group;
4646 new_entry->count = count;
4647 new_entry->t_tid = handle->h_transaction->t_tid;
4649 ext4_lock_group(sb, block_group);
4650 mb_clear_bits(bitmap_bh->b_data, bit, count);
4651 ext4_mb_free_metadata(handle, &e4b, new_entry);
4653 /* need to update group_info->bb_free and bitmap
4654 * with group lock held. generate_buddy look at
4655 * them with group lock_held
4657 ext4_lock_group(sb, block_group);
4658 mb_clear_bits(bitmap_bh->b_data, bit, count);
4659 mb_free_blocks(inode, &e4b, bit, count);
4662 ret = ext4_free_blks_count(sb, gdp) + count;
4663 ext4_free_blks_set(sb, gdp, ret);
4664 gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4665 ext4_unlock_group(sb, block_group);
4666 percpu_counter_add(&sbi->s_freeblocks_counter, count);
4668 if (sbi->s_log_groups_per_flex) {
4669 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4670 atomic_add(count, &sbi->s_flex_groups[flex_group].free_blocks);
4673 ext4_mb_unload_buddy(&e4b);
4677 /* We dirtied the bitmap block */
4678 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4679 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4681 /* And the group descriptor block */
4682 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4683 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4687 if (overflow && !err) {
4693 ext4_mark_super_dirty(sb);
4696 dquot_free_block(inode, freed);
4698 ext4_std_error(sb, err);
4703 * ext4_trim_extent -- function to TRIM one single free extent in the group
4704 * @sb: super block for the file system
4705 * @start: starting block of the free extent in the alloc. group
4706 * @count: number of blocks to TRIM
4707 * @group: alloc. group we are working with
4708 * @e4b: ext4 buddy for the group
4710 * Trim "count" blocks starting at "start" in the "group". To assure that no
4711 * one will allocate those blocks, mark it as used in buddy bitmap. This must
4712 * be called with under the group lock.
4714 static void ext4_trim_extent(struct super_block *sb, int start, int count,
4715 ext4_group_t group, struct ext4_buddy *e4b)
4717 struct ext4_free_extent ex;
4719 assert_spin_locked(ext4_group_lock_ptr(sb, group));
4721 ex.fe_start = start;
4722 ex.fe_group = group;
4726 * Mark blocks used, so no one can reuse them while
4729 mb_mark_used(e4b, &ex);
4730 ext4_unlock_group(sb, group);
4731 ext4_issue_discard(sb, group, start, count);
4732 ext4_lock_group(sb, group);
4733 mb_free_blocks(NULL, e4b, start, ex.fe_len);
4737 * ext4_trim_all_free -- function to trim all free space in alloc. group
4738 * @sb: super block for file system
4740 * @start: first group block to examine
4741 * @max: last group block to examine
4742 * @minblocks: minimum extent block count
4744 * ext4_trim_all_free walks through group's buddy bitmap searching for free
4745 * extents. When the free block is found, ext4_trim_extent is called to TRIM
4749 * ext4_trim_all_free walks through group's block bitmap searching for free
4750 * extents. When the free extent is found, mark it as used in group buddy
4751 * bitmap. Then issue a TRIM command on this extent and free the extent in
4752 * the group buddy bitmap. This is done until whole group is scanned.
4754 static ext4_grpblk_t
4755 ext4_trim_all_free(struct super_block *sb, struct ext4_buddy *e4b,
4756 ext4_grpblk_t start, ext4_grpblk_t max, ext4_grpblk_t minblocks)
4759 ext4_grpblk_t next, count = 0;
4762 BUG_ON(e4b == NULL);
4764 bitmap = e4b->bd_bitmap;
4765 group = e4b->bd_group;
4766 start = (e4b->bd_info->bb_first_free > start) ?
4767 e4b->bd_info->bb_first_free : start;
4768 ext4_lock_group(sb, group);
4770 while (start < max) {
4771 start = mb_find_next_zero_bit(bitmap, max, start);
4774 next = mb_find_next_bit(bitmap, max, start);
4776 if ((next - start) >= minblocks) {
4777 ext4_trim_extent(sb, start,
4778 next - start, group, e4b);
4779 count += next - start;
4783 if (fatal_signal_pending(current)) {
4784 count = -ERESTARTSYS;
4788 if (need_resched()) {
4789 ext4_unlock_group(sb, group);
4791 ext4_lock_group(sb, group);
4794 if ((e4b->bd_info->bb_free - count) < minblocks)
4797 ext4_unlock_group(sb, group);
4799 ext4_debug("trimmed %d blocks in the group %d\n",
4806 * ext4_trim_fs() -- trim ioctl handle function
4807 * @sb: superblock for filesystem
4808 * @range: fstrim_range structure
4810 * start: First Byte to trim
4811 * len: number of Bytes to trim from start
4812 * minlen: minimum extent length in Bytes
4813 * ext4_trim_fs goes through all allocation groups containing Bytes from
4814 * start to start+len. For each such a group ext4_trim_all_free function
4815 * is invoked to trim all free space.
4817 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
4819 struct ext4_buddy e4b;
4820 ext4_group_t first_group, last_group;
4821 ext4_group_t group, ngroups = ext4_get_groups_count(sb);
4822 ext4_grpblk_t cnt = 0, first_block, last_block;
4823 uint64_t start, len, minlen, trimmed;
4824 ext4_fsblk_t first_data_blk =
4825 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
4828 start = range->start >> sb->s_blocksize_bits;
4829 len = range->len >> sb->s_blocksize_bits;
4830 minlen = range->minlen >> sb->s_blocksize_bits;
4833 if (unlikely(minlen > EXT4_BLOCKS_PER_GROUP(sb)))
4835 if (start < first_data_blk) {
4836 len -= first_data_blk - start;
4837 start = first_data_blk;
4840 /* Determine first and last group to examine based on start and len */
4841 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
4842 &first_group, &first_block);
4843 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) (start + len),
4844 &last_group, &last_block);
4845 last_group = (last_group > ngroups - 1) ? ngroups - 1 : last_group;
4846 last_block = EXT4_BLOCKS_PER_GROUP(sb);
4848 if (first_group > last_group)
4851 for (group = first_group; group <= last_group; group++) {
4852 ret = ext4_mb_load_buddy(sb, group, &e4b);
4854 ext4_error(sb, "Error in loading buddy "
4855 "information for %u", group);
4860 * For all the groups except the last one, last block will
4861 * always be EXT4_BLOCKS_PER_GROUP(sb), so we only need to
4862 * change it for the last group in which case start +
4863 * len < EXT4_BLOCKS_PER_GROUP(sb).
4865 if (first_block + len < EXT4_BLOCKS_PER_GROUP(sb))
4866 last_block = first_block + len;
4867 len -= last_block - first_block;
4869 if (e4b.bd_info->bb_free >= minlen) {
4870 cnt = ext4_trim_all_free(sb, &e4b, first_block,
4871 last_block, minlen);
4874 ext4_mb_unload_buddy(&e4b);
4878 ext4_mb_unload_buddy(&e4b);
4882 range->len = trimmed * sb->s_blocksize;