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
27 * - test ext4_ext_search_left() and ext4_ext_search_right()
28 * - search for metadata in few groups
31 * - normalization should take into account whether file is still open
32 * - discard preallocations if no free space left (policy?)
33 * - don't normalize tails
35 * - reservation for superuser
38 * - bitmap read-ahead (proposed by Oleg Drokin aka green)
39 * - track min/max extents in each group for better group selection
40 * - mb_mark_used() may allocate chunk right after splitting buddy
41 * - tree of groups sorted by number of free blocks
46 * The allocation request involve request for multiple number of blocks
47 * near to the goal(block) value specified.
49 * During initialization phase of the allocator we decide to use the
50 * group preallocation or inode preallocation depending on the size of
51 * the file. The size of the file could be the resulting file size we
52 * would have after allocation, or the current file size, which ever
53 * is larger. If the size is less than sbi->s_mb_stream_request we
54 * select to use the group preallocation. The default value of
55 * s_mb_stream_request is 16 blocks. This can also be tuned via
56 * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
57 * terms of number of blocks.
59 * The main motivation for having small file use group preallocation is to
60 * ensure that we have small files closer together on the disk.
62 * First stage the allocator looks at the inode prealloc list,
63 * ext4_inode_info->i_prealloc_list, which contains list of prealloc
64 * spaces for this particular inode. The inode prealloc space is
67 * pa_lstart -> the logical start block for this prealloc space
68 * pa_pstart -> the physical start block for this prealloc space
69 * pa_len -> lenght for this prealloc space
70 * pa_free -> free space available in this prealloc space
72 * The inode preallocation space is used looking at the _logical_ start
73 * block. If only the logical file block falls within the range of prealloc
74 * space we will consume the particular prealloc space. This make sure that
75 * that the we have contiguous physical blocks representing the file blocks
77 * The important thing to be noted in case of inode prealloc space is that
78 * we don't modify the values associated to inode prealloc space except
81 * If we are not able to find blocks in the inode prealloc space and if we
82 * have the group allocation flag set then we look at the locality group
83 * prealloc space. These are per CPU prealloc list repreasented as
85 * ext4_sb_info.s_locality_groups[smp_processor_id()]
87 * The reason for having a per cpu locality group is to reduce the contention
88 * between CPUs. It is possible to get scheduled at this point.
90 * The locality group prealloc space is used looking at whether we have
91 * enough free space (pa_free) withing the prealloc space.
93 * If we can't allocate blocks via inode prealloc or/and locality group
94 * prealloc then we look at the buddy cache. The buddy cache is represented
95 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
96 * mapped to the buddy and bitmap information regarding different
97 * groups. The buddy information is attached to buddy cache inode so that
98 * we can access them through the page cache. The information regarding
99 * each group is loaded via ext4_mb_load_buddy. The information involve
100 * block bitmap and buddy information. The information are stored in the
104 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
107 * one block each for bitmap and buddy information. So for each group we
108 * take up 2 blocks. A page can contain blocks_per_page (PAGE_CACHE_SIZE /
109 * blocksize) blocks. So it can have information regarding groups_per_page
110 * which is blocks_per_page/2
112 * The buddy cache inode is not stored on disk. The inode is thrown
113 * away when the filesystem is unmounted.
115 * We look for count number of blocks in the buddy cache. If we were able
116 * to locate that many free blocks we return with additional information
117 * regarding rest of the contiguous physical block available
119 * Before allocating blocks via buddy cache we normalize the request
120 * blocks. This ensure we ask for more blocks that we needed. The extra
121 * blocks that we get after allocation is added to the respective prealloc
122 * list. In case of inode preallocation we follow a list of heuristics
123 * based on file size. This can be found in ext4_mb_normalize_request. If
124 * we are doing a group prealloc we try to normalize the request to
125 * sbi->s_mb_group_prealloc. Default value of s_mb_group_prealloc is
126 * 512 blocks. This can be tuned via
127 * /sys/fs/ext4/<partition/mb_group_prealloc. The value is represented in
128 * terms of number of blocks. If we have mounted the file system with -O
129 * stripe=<value> option the group prealloc request is normalized to the
130 * stripe value (sbi->s_stripe)
132 * The regular allocator(using the buddy cache) supports few tunables.
134 * /sys/fs/ext4/<partition>/mb_min_to_scan
135 * /sys/fs/ext4/<partition>/mb_max_to_scan
136 * /sys/fs/ext4/<partition>/mb_order2_req
138 * The regular allocator uses buddy scan only if the request len is power of
139 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
140 * value of s_mb_order2_reqs can be tuned via
141 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
142 * stripe size (sbi->s_stripe), we try to search for contigous block in
143 * stripe size. This should result in better allocation on RAID setups. If
144 * not, we search in the specific group using bitmap for best extents. The
145 * tunable min_to_scan and max_to_scan control the behaviour here.
146 * min_to_scan indicate how long the mballoc __must__ look for a best
147 * extent and max_to_scan indicates how long the mballoc __can__ look for a
148 * best extent in the found extents. Searching for the blocks starts with
149 * the group specified as the goal value in allocation context via
150 * ac_g_ex. Each group is first checked based on the criteria whether it
151 * can used for allocation. ext4_mb_good_group explains how the groups are
154 * Both the prealloc space are getting populated as above. So for the first
155 * request we will hit the buddy cache which will result in this prealloc
156 * space getting filled. The prealloc space is then later used for the
157 * subsequent request.
161 * mballoc operates on the following data:
163 * - in-core buddy (actually includes buddy and bitmap)
164 * - preallocation descriptors (PAs)
166 * there are two types of preallocations:
168 * assiged to specific inode and can be used for this inode only.
169 * it describes part of inode's space preallocated to specific
170 * physical blocks. any block from that preallocated can be used
171 * independent. the descriptor just tracks number of blocks left
172 * unused. so, before taking some block from descriptor, one must
173 * make sure corresponded logical block isn't allocated yet. this
174 * also means that freeing any block within descriptor's range
175 * must discard all preallocated blocks.
177 * assigned to specific locality group which does not translate to
178 * permanent set of inodes: inode can join and leave group. space
179 * from this type of preallocation can be used for any inode. thus
180 * it's consumed from the beginning to the end.
182 * relation between them can be expressed as:
183 * in-core buddy = on-disk bitmap + preallocation descriptors
185 * this mean blocks mballoc considers used are:
186 * - allocated blocks (persistent)
187 * - preallocated blocks (non-persistent)
189 * consistency in mballoc world means that at any time a block is either
190 * free or used in ALL structures. notice: "any time" should not be read
191 * literally -- time is discrete and delimited by locks.
193 * to keep it simple, we don't use block numbers, instead we count number of
194 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
196 * all operations can be expressed as:
197 * - init buddy: buddy = on-disk + PAs
198 * - new PA: buddy += N; PA = N
199 * - use inode PA: on-disk += N; PA -= N
200 * - discard inode PA buddy -= on-disk - PA; PA = 0
201 * - use locality group PA on-disk += N; PA -= N
202 * - discard locality group PA buddy -= PA; PA = 0
203 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
204 * is used in real operation because we can't know actual used
205 * bits from PA, only from on-disk bitmap
207 * if we follow this strict logic, then all operations above should be atomic.
208 * given some of them can block, we'd have to use something like semaphores
209 * killing performance on high-end SMP hardware. let's try to relax it using
210 * the following knowledge:
211 * 1) if buddy is referenced, it's already initialized
212 * 2) while block is used in buddy and the buddy is referenced,
213 * nobody can re-allocate that block
214 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
215 * bit set and PA claims same block, it's OK. IOW, one can set bit in
216 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
219 * so, now we're building a concurrency table:
222 * blocks for PA are allocated in the buddy, buddy must be referenced
223 * until PA is linked to allocation group to avoid concurrent buddy init
225 * we need to make sure that either on-disk bitmap or PA has uptodate data
226 * given (3) we care that PA-=N operation doesn't interfere with init
228 * the simplest way would be to have buddy initialized by the discard
229 * - use locality group PA
230 * again PA-=N must be serialized with init
231 * - discard locality group PA
232 * the simplest way would be to have buddy initialized by the discard
235 * i_data_sem serializes them
237 * discard process must wait until PA isn't used by another process
238 * - use locality group PA
239 * some mutex should serialize them
240 * - discard locality group PA
241 * discard process must wait until PA isn't used by another process
244 * i_data_sem or another mutex should serializes them
246 * discard process must wait until PA isn't used by another process
247 * - use locality group PA
248 * nothing wrong here -- they're different PAs covering different blocks
249 * - discard locality group PA
250 * discard process must wait until PA isn't used by another process
252 * now we're ready to make few consequences:
253 * - PA is referenced and while it is no discard is possible
254 * - PA is referenced until block isn't marked in on-disk bitmap
255 * - PA changes only after on-disk bitmap
256 * - discard must not compete with init. either init is done before
257 * any discard or they're serialized somehow
258 * - buddy init as sum of on-disk bitmap and PAs is done atomically
260 * a special case when we've used PA to emptiness. no need to modify buddy
261 * in this case, but we should care about concurrent init
266 * Logic in few words:
271 * mark bits in on-disk bitmap
274 * - use preallocation:
275 * find proper PA (per-inode or group)
277 * mark bits in on-disk bitmap
283 * mark bits in on-disk bitmap
286 * - discard preallocations in group:
288 * move them onto local list
289 * load on-disk bitmap
291 * remove PA from object (inode or locality group)
292 * mark free blocks in-core
294 * - discard inode's preallocations:
301 * - bitlock on a group (group)
302 * - object (inode/locality) (object)
313 * - release consumed pa:
318 * - generate in-core bitmap:
322 * - discard all for given object (inode, locality group):
327 * - discard all for given group:
334 static struct kmem_cache *ext4_pspace_cachep;
335 static struct kmem_cache *ext4_ac_cachep;
336 static struct kmem_cache *ext4_free_ext_cachep;
337 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
339 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
341 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn);
345 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
347 #if BITS_PER_LONG == 64
348 *bit += ((unsigned long) addr & 7UL) << 3;
349 addr = (void *) ((unsigned long) addr & ~7UL);
350 #elif BITS_PER_LONG == 32
351 *bit += ((unsigned long) addr & 3UL) << 3;
352 addr = (void *) ((unsigned long) addr & ~3UL);
354 #error "how many bits you are?!"
359 static inline int mb_test_bit(int bit, void *addr)
362 * ext4_test_bit on architecture like powerpc
363 * needs unsigned long aligned address
365 addr = mb_correct_addr_and_bit(&bit, addr);
366 return ext4_test_bit(bit, addr);
369 static inline void mb_set_bit(int bit, void *addr)
371 addr = mb_correct_addr_and_bit(&bit, addr);
372 ext4_set_bit(bit, addr);
375 static inline void mb_set_bit_atomic(spinlock_t *lock, int bit, void *addr)
377 addr = mb_correct_addr_and_bit(&bit, addr);
378 ext4_set_bit_atomic(lock, bit, addr);
381 static inline void mb_clear_bit(int bit, void *addr)
383 addr = mb_correct_addr_and_bit(&bit, addr);
384 ext4_clear_bit(bit, addr);
387 static inline void mb_clear_bit_atomic(spinlock_t *lock, int bit, void *addr)
389 addr = mb_correct_addr_and_bit(&bit, addr);
390 ext4_clear_bit_atomic(lock, bit, addr);
393 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
395 int fix = 0, ret, tmpmax;
396 addr = mb_correct_addr_and_bit(&fix, addr);
400 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
406 static inline int mb_find_next_bit(void *addr, int max, int start)
408 int fix = 0, ret, tmpmax;
409 addr = mb_correct_addr_and_bit(&fix, addr);
413 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
419 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
423 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
426 if (order > e4b->bd_blkbits + 1) {
431 /* at order 0 we see each particular block */
432 *max = 1 << (e4b->bd_blkbits + 3);
434 return EXT4_MB_BITMAP(e4b);
436 bb = EXT4_MB_BUDDY(e4b) + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
437 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
443 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
444 int first, int count)
447 struct super_block *sb = e4b->bd_sb;
449 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
451 BUG_ON(!ext4_is_group_locked(sb, e4b->bd_group));
452 for (i = 0; i < count; i++) {
453 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
454 ext4_fsblk_t blocknr;
455 blocknr = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb);
456 blocknr += first + i;
458 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
459 ext4_grp_locked_error(sb, e4b->bd_group,
460 __func__, "double-free of inode"
461 " %lu's block %llu(bit %u in group %u)",
462 inode ? inode->i_ino : 0, blocknr,
463 first + i, e4b->bd_group);
465 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
469 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
473 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
475 BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
476 for (i = 0; i < count; i++) {
477 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
478 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
482 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
484 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
485 unsigned char *b1, *b2;
487 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
488 b2 = (unsigned char *) bitmap;
489 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
490 if (b1[i] != b2[i]) {
491 printk(KERN_ERR "corruption in group %u "
492 "at byte %u(%u): %x in copy != %x "
493 "on disk/prealloc\n",
494 e4b->bd_group, i, i * 8, b1[i], b2[i]);
502 static inline void mb_free_blocks_double(struct inode *inode,
503 struct ext4_buddy *e4b, int first, int count)
507 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
508 int first, int count)
512 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
518 #ifdef AGGRESSIVE_CHECK
520 #define MB_CHECK_ASSERT(assert) \
524 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
525 function, file, line, # assert); \
530 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
531 const char *function, int line)
533 struct super_block *sb = e4b->bd_sb;
534 int order = e4b->bd_blkbits + 1;
541 struct ext4_group_info *grp;
544 struct list_head *cur;
549 static int mb_check_counter;
550 if (mb_check_counter++ % 100 != 0)
555 buddy = mb_find_buddy(e4b, order, &max);
556 MB_CHECK_ASSERT(buddy);
557 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
558 MB_CHECK_ASSERT(buddy2);
559 MB_CHECK_ASSERT(buddy != buddy2);
560 MB_CHECK_ASSERT(max * 2 == max2);
563 for (i = 0; i < max; i++) {
565 if (mb_test_bit(i, buddy)) {
566 /* only single bit in buddy2 may be 1 */
567 if (!mb_test_bit(i << 1, buddy2)) {
569 mb_test_bit((i<<1)+1, buddy2));
570 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
572 mb_test_bit(i << 1, buddy2));
577 /* both bits in buddy2 must be 0 */
578 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
579 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
581 for (j = 0; j < (1 << order); j++) {
582 k = (i * (1 << order)) + j;
584 !mb_test_bit(k, EXT4_MB_BITMAP(e4b)));
588 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
593 buddy = mb_find_buddy(e4b, 0, &max);
594 for (i = 0; i < max; i++) {
595 if (!mb_test_bit(i, buddy)) {
596 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
604 /* check used bits only */
605 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
606 buddy2 = mb_find_buddy(e4b, j, &max2);
608 MB_CHECK_ASSERT(k < max2);
609 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
612 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
613 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
615 grp = ext4_get_group_info(sb, e4b->bd_group);
616 buddy = mb_find_buddy(e4b, 0, &max);
617 list_for_each(cur, &grp->bb_prealloc_list) {
618 ext4_group_t groupnr;
619 struct ext4_prealloc_space *pa;
620 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
621 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
622 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
623 for (i = 0; i < pa->pa_len; i++)
624 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
628 #undef MB_CHECK_ASSERT
629 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
630 __FILE__, __func__, __LINE__)
632 #define mb_check_buddy(e4b)
635 /* FIXME!! need more doc */
636 static void ext4_mb_mark_free_simple(struct super_block *sb,
637 void *buddy, unsigned first, int len,
638 struct ext4_group_info *grp)
640 struct ext4_sb_info *sbi = EXT4_SB(sb);
643 unsigned short chunk;
644 unsigned short border;
646 BUG_ON(len > EXT4_BLOCKS_PER_GROUP(sb));
648 border = 2 << sb->s_blocksize_bits;
651 /* find how many blocks can be covered since this position */
652 max = ffs(first | border) - 1;
654 /* find how many blocks of power 2 we need to mark */
661 /* mark multiblock chunks only */
662 grp->bb_counters[min]++;
664 mb_clear_bit(first >> min,
665 buddy + sbi->s_mb_offsets[min]);
672 static void ext4_mb_generate_buddy(struct super_block *sb,
673 void *buddy, void *bitmap, ext4_group_t group)
675 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
676 unsigned short max = EXT4_BLOCKS_PER_GROUP(sb);
677 unsigned short i = 0;
678 unsigned short first;
681 unsigned fragments = 0;
682 unsigned long long period = get_cycles();
684 /* initialize buddy from bitmap which is aggregation
685 * of on-disk bitmap and preallocations */
686 i = mb_find_next_zero_bit(bitmap, max, 0);
687 grp->bb_first_free = i;
691 i = mb_find_next_bit(bitmap, max, i);
695 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
697 grp->bb_counters[0]++;
699 i = mb_find_next_zero_bit(bitmap, max, i);
701 grp->bb_fragments = fragments;
703 if (free != grp->bb_free) {
704 ext4_grp_locked_error(sb, group, __func__,
705 "EXT4-fs: group %u: %u blocks in bitmap, %u in gd",
706 group, free, grp->bb_free);
708 * If we intent to continue, we consider group descritor
709 * corrupt and update bb_free using bitmap value
714 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
716 period = get_cycles() - period;
717 spin_lock(&EXT4_SB(sb)->s_bal_lock);
718 EXT4_SB(sb)->s_mb_buddies_generated++;
719 EXT4_SB(sb)->s_mb_generation_time += period;
720 spin_unlock(&EXT4_SB(sb)->s_bal_lock);
723 /* The buddy information is attached the buddy cache inode
724 * for convenience. The information regarding each group
725 * is loaded via ext4_mb_load_buddy. The information involve
726 * block bitmap and buddy information. The information are
727 * stored in the inode as
730 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
733 * one block each for bitmap and buddy information.
734 * So for each group we take up 2 blocks. A page can
735 * contain blocks_per_page (PAGE_CACHE_SIZE / blocksize) blocks.
736 * So it can have information regarding groups_per_page which
737 * is blocks_per_page/2
740 static int ext4_mb_init_cache(struct page *page, char *incore)
742 ext4_group_t ngroups;
748 ext4_group_t first_group;
750 struct super_block *sb;
751 struct buffer_head *bhs;
752 struct buffer_head **bh;
757 mb_debug("init page %lu\n", page->index);
759 inode = page->mapping->host;
761 ngroups = ext4_get_groups_count(sb);
762 blocksize = 1 << inode->i_blkbits;
763 blocks_per_page = PAGE_CACHE_SIZE / blocksize;
765 groups_per_page = blocks_per_page >> 1;
766 if (groups_per_page == 0)
769 /* allocate buffer_heads to read bitmaps */
770 if (groups_per_page > 1) {
772 i = sizeof(struct buffer_head *) * groups_per_page;
773 bh = kzalloc(i, GFP_NOFS);
779 first_group = page->index * blocks_per_page / 2;
781 /* read all groups the page covers into the cache */
782 for (i = 0; i < groups_per_page; i++) {
783 struct ext4_group_desc *desc;
785 if (first_group + i >= ngroups)
789 desc = ext4_get_group_desc(sb, first_group + i, NULL);
794 bh[i] = sb_getblk(sb, ext4_block_bitmap(sb, desc));
798 if (bitmap_uptodate(bh[i]))
802 if (bitmap_uptodate(bh[i])) {
803 unlock_buffer(bh[i]);
806 spin_lock(sb_bgl_lock(EXT4_SB(sb), first_group + i));
807 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
808 ext4_init_block_bitmap(sb, bh[i],
809 first_group + i, desc);
810 set_bitmap_uptodate(bh[i]);
811 set_buffer_uptodate(bh[i]);
812 spin_unlock(sb_bgl_lock(EXT4_SB(sb), first_group + i));
813 unlock_buffer(bh[i]);
816 spin_unlock(sb_bgl_lock(EXT4_SB(sb), first_group + i));
817 if (buffer_uptodate(bh[i])) {
819 * if not uninit if bh is uptodate,
820 * bitmap is also uptodate
822 set_bitmap_uptodate(bh[i]);
823 unlock_buffer(bh[i]);
828 * submit the buffer_head for read. We can
829 * safely mark the bitmap as uptodate now.
830 * We do it here so the bitmap uptodate bit
831 * get set with buffer lock held.
833 set_bitmap_uptodate(bh[i]);
834 bh[i]->b_end_io = end_buffer_read_sync;
835 submit_bh(READ, bh[i]);
836 mb_debug("read bitmap for group %u\n", first_group + i);
839 /* wait for I/O completion */
840 for (i = 0; i < groups_per_page && bh[i]; i++)
841 wait_on_buffer(bh[i]);
844 for (i = 0; i < groups_per_page && bh[i]; i++)
845 if (!buffer_uptodate(bh[i]))
849 first_block = page->index * blocks_per_page;
851 memset(page_address(page), 0xff, PAGE_CACHE_SIZE);
852 for (i = 0; i < blocks_per_page; i++) {
854 struct ext4_group_info *grinfo;
856 group = (first_block + i) >> 1;
857 if (group >= ngroups)
861 * data carry information regarding this
862 * particular group in the format specified
866 data = page_address(page) + (i * blocksize);
867 bitmap = bh[group - first_group]->b_data;
870 * We place the buddy block and bitmap block
873 if ((first_block + i) & 1) {
874 /* this is block of buddy */
875 BUG_ON(incore == NULL);
876 mb_debug("put buddy for group %u in page %lu/%x\n",
877 group, page->index, i * blocksize);
878 grinfo = ext4_get_group_info(sb, group);
879 grinfo->bb_fragments = 0;
880 memset(grinfo->bb_counters, 0,
881 sizeof(unsigned short)*(sb->s_blocksize_bits+2));
883 * incore got set to the group block bitmap below
885 ext4_lock_group(sb, group);
886 ext4_mb_generate_buddy(sb, data, incore, group);
887 ext4_unlock_group(sb, group);
890 /* this is block of bitmap */
891 BUG_ON(incore != NULL);
892 mb_debug("put bitmap for group %u in page %lu/%x\n",
893 group, page->index, i * blocksize);
895 /* see comments in ext4_mb_put_pa() */
896 ext4_lock_group(sb, group);
897 memcpy(data, bitmap, blocksize);
899 /* mark all preallocated blks used in in-core bitmap */
900 ext4_mb_generate_from_pa(sb, data, group);
901 ext4_mb_generate_from_freelist(sb, data, group);
902 ext4_unlock_group(sb, group);
904 /* set incore so that the buddy information can be
905 * generated using this
910 SetPageUptodate(page);
914 for (i = 0; i < groups_per_page && bh[i]; i++)
922 static noinline_for_stack int
923 ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
924 struct ext4_buddy *e4b)
932 struct ext4_group_info *grp;
933 struct ext4_sb_info *sbi = EXT4_SB(sb);
934 struct inode *inode = sbi->s_buddy_cache;
936 mb_debug("load group %u\n", group);
938 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
939 grp = ext4_get_group_info(sb, group);
941 e4b->bd_blkbits = sb->s_blocksize_bits;
942 e4b->bd_info = ext4_get_group_info(sb, group);
944 e4b->bd_group = group;
945 e4b->bd_buddy_page = NULL;
946 e4b->bd_bitmap_page = NULL;
947 e4b->alloc_semp = &grp->alloc_sem;
949 /* Take the read lock on the group alloc
950 * sem. This would make sure a parallel
951 * ext4_mb_init_group happening on other
952 * groups mapped by the page is blocked
953 * till we are done with allocation
955 down_read(e4b->alloc_semp);
958 * the buddy cache inode stores the block bitmap
959 * and buddy information in consecutive blocks.
960 * So for each group we need two blocks.
963 pnum = block / blocks_per_page;
964 poff = block % blocks_per_page;
966 /* we could use find_or_create_page(), but it locks page
967 * what we'd like to avoid in fast path ... */
968 page = find_get_page(inode->i_mapping, pnum);
969 if (page == NULL || !PageUptodate(page)) {
972 * drop the page reference and try
973 * to get the page with lock. If we
974 * are not uptodate that implies
975 * somebody just created the page but
976 * is yet to initialize the same. So
977 * wait for it to initialize.
979 page_cache_release(page);
980 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
982 BUG_ON(page->mapping != inode->i_mapping);
983 if (!PageUptodate(page)) {
984 ret = ext4_mb_init_cache(page, NULL);
989 mb_cmp_bitmaps(e4b, page_address(page) +
990 (poff * sb->s_blocksize));
995 if (page == NULL || !PageUptodate(page)) {
999 e4b->bd_bitmap_page = page;
1000 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1001 mark_page_accessed(page);
1004 pnum = block / blocks_per_page;
1005 poff = block % blocks_per_page;
1007 page = find_get_page(inode->i_mapping, pnum);
1008 if (page == NULL || !PageUptodate(page)) {
1010 page_cache_release(page);
1011 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1013 BUG_ON(page->mapping != inode->i_mapping);
1014 if (!PageUptodate(page)) {
1015 ret = ext4_mb_init_cache(page, e4b->bd_bitmap);
1024 if (page == NULL || !PageUptodate(page)) {
1028 e4b->bd_buddy_page = page;
1029 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1030 mark_page_accessed(page);
1032 BUG_ON(e4b->bd_bitmap_page == NULL);
1033 BUG_ON(e4b->bd_buddy_page == NULL);
1038 if (e4b->bd_bitmap_page)
1039 page_cache_release(e4b->bd_bitmap_page);
1040 if (e4b->bd_buddy_page)
1041 page_cache_release(e4b->bd_buddy_page);
1042 e4b->bd_buddy = NULL;
1043 e4b->bd_bitmap = NULL;
1045 /* Done with the buddy cache */
1046 up_read(e4b->alloc_semp);
1050 static void ext4_mb_release_desc(struct ext4_buddy *e4b)
1052 if (e4b->bd_bitmap_page)
1053 page_cache_release(e4b->bd_bitmap_page);
1054 if (e4b->bd_buddy_page)
1055 page_cache_release(e4b->bd_buddy_page);
1056 /* Done with the buddy cache */
1057 if (e4b->alloc_semp)
1058 up_read(e4b->alloc_semp);
1062 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1067 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
1068 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1070 bb = EXT4_MB_BUDDY(e4b);
1071 while (order <= e4b->bd_blkbits + 1) {
1073 if (!mb_test_bit(block, bb)) {
1074 /* this block is part of buddy of order 'order' */
1077 bb += 1 << (e4b->bd_blkbits - order);
1083 static void mb_clear_bits(spinlock_t *lock, void *bm, int cur, int len)
1089 if ((cur & 31) == 0 && (len - cur) >= 32) {
1090 /* fast path: clear whole word at once */
1091 addr = bm + (cur >> 3);
1097 mb_clear_bit_atomic(lock, cur, bm);
1099 mb_clear_bit(cur, bm);
1104 static void mb_set_bits(spinlock_t *lock, void *bm, int cur, int len)
1110 if ((cur & 31) == 0 && (len - cur) >= 32) {
1111 /* fast path: set whole word at once */
1112 addr = bm + (cur >> 3);
1118 mb_set_bit_atomic(lock, cur, bm);
1120 mb_set_bit(cur, bm);
1125 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1126 int first, int count)
1133 struct super_block *sb = e4b->bd_sb;
1135 BUG_ON(first + count > (sb->s_blocksize << 3));
1136 BUG_ON(!ext4_is_group_locked(sb, e4b->bd_group));
1137 mb_check_buddy(e4b);
1138 mb_free_blocks_double(inode, e4b, first, count);
1140 e4b->bd_info->bb_free += count;
1141 if (first < e4b->bd_info->bb_first_free)
1142 e4b->bd_info->bb_first_free = first;
1144 /* let's maintain fragments counter */
1146 block = !mb_test_bit(first - 1, EXT4_MB_BITMAP(e4b));
1147 if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
1148 max = !mb_test_bit(first + count, EXT4_MB_BITMAP(e4b));
1150 e4b->bd_info->bb_fragments--;
1151 else if (!block && !max)
1152 e4b->bd_info->bb_fragments++;
1154 /* let's maintain buddy itself */
1155 while (count-- > 0) {
1159 if (!mb_test_bit(block, EXT4_MB_BITMAP(e4b))) {
1160 ext4_fsblk_t blocknr;
1161 blocknr = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb);
1164 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
1165 ext4_grp_locked_error(sb, e4b->bd_group,
1166 __func__, "double-free of inode"
1167 " %lu's block %llu(bit %u in group %u)",
1168 inode ? inode->i_ino : 0, blocknr, block,
1171 mb_clear_bit(block, EXT4_MB_BITMAP(e4b));
1172 e4b->bd_info->bb_counters[order]++;
1174 /* start of the buddy */
1175 buddy = mb_find_buddy(e4b, order, &max);
1179 if (mb_test_bit(block, buddy) ||
1180 mb_test_bit(block + 1, buddy))
1183 /* both the buddies are free, try to coalesce them */
1184 buddy2 = mb_find_buddy(e4b, order + 1, &max);
1190 /* for special purposes, we don't set
1191 * free bits in bitmap */
1192 mb_set_bit(block, buddy);
1193 mb_set_bit(block + 1, buddy);
1195 e4b->bd_info->bb_counters[order]--;
1196 e4b->bd_info->bb_counters[order]--;
1200 e4b->bd_info->bb_counters[order]++;
1202 mb_clear_bit(block, buddy2);
1206 mb_check_buddy(e4b);
1209 static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
1210 int needed, struct ext4_free_extent *ex)
1217 BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
1220 buddy = mb_find_buddy(e4b, order, &max);
1221 BUG_ON(buddy == NULL);
1222 BUG_ON(block >= max);
1223 if (mb_test_bit(block, buddy)) {
1230 /* FIXME dorp order completely ? */
1231 if (likely(order == 0)) {
1232 /* find actual order */
1233 order = mb_find_order_for_block(e4b, block);
1234 block = block >> order;
1237 ex->fe_len = 1 << order;
1238 ex->fe_start = block << order;
1239 ex->fe_group = e4b->bd_group;
1241 /* calc difference from given start */
1242 next = next - ex->fe_start;
1244 ex->fe_start += next;
1246 while (needed > ex->fe_len &&
1247 (buddy = mb_find_buddy(e4b, order, &max))) {
1249 if (block + 1 >= max)
1252 next = (block + 1) * (1 << order);
1253 if (mb_test_bit(next, EXT4_MB_BITMAP(e4b)))
1256 ord = mb_find_order_for_block(e4b, next);
1259 block = next >> order;
1260 ex->fe_len += 1 << order;
1263 BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1267 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1273 int start = ex->fe_start;
1274 int len = ex->fe_len;
1279 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1280 BUG_ON(e4b->bd_group != ex->fe_group);
1281 BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
1282 mb_check_buddy(e4b);
1283 mb_mark_used_double(e4b, start, len);
1285 e4b->bd_info->bb_free -= len;
1286 if (e4b->bd_info->bb_first_free == start)
1287 e4b->bd_info->bb_first_free += len;
1289 /* let's maintain fragments counter */
1291 mlen = !mb_test_bit(start - 1, EXT4_MB_BITMAP(e4b));
1292 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1293 max = !mb_test_bit(start + len, EXT4_MB_BITMAP(e4b));
1295 e4b->bd_info->bb_fragments++;
1296 else if (!mlen && !max)
1297 e4b->bd_info->bb_fragments--;
1299 /* let's maintain buddy itself */
1301 ord = mb_find_order_for_block(e4b, start);
1303 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1304 /* the whole chunk may be allocated at once! */
1306 buddy = mb_find_buddy(e4b, ord, &max);
1307 BUG_ON((start >> ord) >= max);
1308 mb_set_bit(start >> ord, buddy);
1309 e4b->bd_info->bb_counters[ord]--;
1316 /* store for history */
1318 ret = len | (ord << 16);
1320 /* we have to split large buddy */
1322 buddy = mb_find_buddy(e4b, ord, &max);
1323 mb_set_bit(start >> ord, buddy);
1324 e4b->bd_info->bb_counters[ord]--;
1327 cur = (start >> ord) & ~1U;
1328 buddy = mb_find_buddy(e4b, ord, &max);
1329 mb_clear_bit(cur, buddy);
1330 mb_clear_bit(cur + 1, buddy);
1331 e4b->bd_info->bb_counters[ord]++;
1332 e4b->bd_info->bb_counters[ord]++;
1335 mb_set_bits(sb_bgl_lock(EXT4_SB(e4b->bd_sb), ex->fe_group),
1336 EXT4_MB_BITMAP(e4b), ex->fe_start, len0);
1337 mb_check_buddy(e4b);
1343 * Must be called under group lock!
1345 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1346 struct ext4_buddy *e4b)
1348 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1351 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1352 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1354 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1355 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1356 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1358 /* preallocation can change ac_b_ex, thus we store actually
1359 * allocated blocks for history */
1360 ac->ac_f_ex = ac->ac_b_ex;
1362 ac->ac_status = AC_STATUS_FOUND;
1363 ac->ac_tail = ret & 0xffff;
1364 ac->ac_buddy = ret >> 16;
1367 * take the page reference. We want the page to be pinned
1368 * so that we don't get a ext4_mb_init_cache_call for this
1369 * group until we update the bitmap. That would mean we
1370 * double allocate blocks. The reference is dropped
1371 * in ext4_mb_release_context
1373 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1374 get_page(ac->ac_bitmap_page);
1375 ac->ac_buddy_page = e4b->bd_buddy_page;
1376 get_page(ac->ac_buddy_page);
1377 /* on allocation we use ac to track the held semaphore */
1378 ac->alloc_semp = e4b->alloc_semp;
1379 e4b->alloc_semp = NULL;
1380 /* store last allocated for subsequent stream allocation */
1381 if ((ac->ac_flags & EXT4_MB_HINT_DATA)) {
1382 spin_lock(&sbi->s_md_lock);
1383 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1384 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1385 spin_unlock(&sbi->s_md_lock);
1390 * regular allocator, for general purposes allocation
1393 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1394 struct ext4_buddy *e4b,
1397 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1398 struct ext4_free_extent *bex = &ac->ac_b_ex;
1399 struct ext4_free_extent *gex = &ac->ac_g_ex;
1400 struct ext4_free_extent ex;
1403 if (ac->ac_status == AC_STATUS_FOUND)
1406 * We don't want to scan for a whole year
1408 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1409 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1410 ac->ac_status = AC_STATUS_BREAK;
1415 * Haven't found good chunk so far, let's continue
1417 if (bex->fe_len < gex->fe_len)
1420 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1421 && bex->fe_group == e4b->bd_group) {
1422 /* recheck chunk's availability - we don't know
1423 * when it was found (within this lock-unlock
1425 max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
1426 if (max >= gex->fe_len) {
1427 ext4_mb_use_best_found(ac, e4b);
1434 * The routine checks whether found extent is good enough. If it is,
1435 * then the extent gets marked used and flag is set to the context
1436 * to stop scanning. Otherwise, the extent is compared with the
1437 * previous found extent and if new one is better, then it's stored
1438 * in the context. Later, the best found extent will be used, if
1439 * mballoc can't find good enough extent.
1441 * FIXME: real allocation policy is to be designed yet!
1443 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1444 struct ext4_free_extent *ex,
1445 struct ext4_buddy *e4b)
1447 struct ext4_free_extent *bex = &ac->ac_b_ex;
1448 struct ext4_free_extent *gex = &ac->ac_g_ex;
1450 BUG_ON(ex->fe_len <= 0);
1451 BUG_ON(ex->fe_len > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1452 BUG_ON(ex->fe_start >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1453 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1458 * The special case - take what you catch first
1460 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1462 ext4_mb_use_best_found(ac, e4b);
1467 * Let's check whether the chuck is good enough
1469 if (ex->fe_len == gex->fe_len) {
1471 ext4_mb_use_best_found(ac, e4b);
1476 * If this is first found extent, just store it in the context
1478 if (bex->fe_len == 0) {
1484 * If new found extent is better, store it in the context
1486 if (bex->fe_len < gex->fe_len) {
1487 /* if the request isn't satisfied, any found extent
1488 * larger than previous best one is better */
1489 if (ex->fe_len > bex->fe_len)
1491 } else if (ex->fe_len > gex->fe_len) {
1492 /* if the request is satisfied, then we try to find
1493 * an extent that still satisfy the request, but is
1494 * smaller than previous one */
1495 if (ex->fe_len < bex->fe_len)
1499 ext4_mb_check_limits(ac, e4b, 0);
1502 static int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1503 struct ext4_buddy *e4b)
1505 struct ext4_free_extent ex = ac->ac_b_ex;
1506 ext4_group_t group = ex.fe_group;
1510 BUG_ON(ex.fe_len <= 0);
1511 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1515 ext4_lock_group(ac->ac_sb, group);
1516 max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
1520 ext4_mb_use_best_found(ac, e4b);
1523 ext4_unlock_group(ac->ac_sb, group);
1524 ext4_mb_release_desc(e4b);
1529 static int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1530 struct ext4_buddy *e4b)
1532 ext4_group_t group = ac->ac_g_ex.fe_group;
1535 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1536 struct ext4_super_block *es = sbi->s_es;
1537 struct ext4_free_extent ex;
1539 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1542 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1546 ext4_lock_group(ac->ac_sb, group);
1547 max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
1548 ac->ac_g_ex.fe_len, &ex);
1550 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1553 start = (e4b->bd_group * EXT4_BLOCKS_PER_GROUP(ac->ac_sb)) +
1554 ex.fe_start + le32_to_cpu(es->s_first_data_block);
1555 /* use do_div to get remainder (would be 64-bit modulo) */
1556 if (do_div(start, sbi->s_stripe) == 0) {
1559 ext4_mb_use_best_found(ac, e4b);
1561 } else if (max >= ac->ac_g_ex.fe_len) {
1562 BUG_ON(ex.fe_len <= 0);
1563 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1564 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1567 ext4_mb_use_best_found(ac, e4b);
1568 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1569 /* Sometimes, caller may want to merge even small
1570 * number of blocks to an existing extent */
1571 BUG_ON(ex.fe_len <= 0);
1572 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1573 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1576 ext4_mb_use_best_found(ac, e4b);
1578 ext4_unlock_group(ac->ac_sb, group);
1579 ext4_mb_release_desc(e4b);
1585 * The routine scans buddy structures (not bitmap!) from given order
1586 * to max order and tries to find big enough chunk to satisfy the req
1588 static void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1589 struct ext4_buddy *e4b)
1591 struct super_block *sb = ac->ac_sb;
1592 struct ext4_group_info *grp = e4b->bd_info;
1598 BUG_ON(ac->ac_2order <= 0);
1599 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1600 if (grp->bb_counters[i] == 0)
1603 buddy = mb_find_buddy(e4b, i, &max);
1604 BUG_ON(buddy == NULL);
1606 k = mb_find_next_zero_bit(buddy, max, 0);
1611 ac->ac_b_ex.fe_len = 1 << i;
1612 ac->ac_b_ex.fe_start = k << i;
1613 ac->ac_b_ex.fe_group = e4b->bd_group;
1615 ext4_mb_use_best_found(ac, e4b);
1617 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1619 if (EXT4_SB(sb)->s_mb_stats)
1620 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1627 * The routine scans the group and measures all found extents.
1628 * In order to optimize scanning, caller must pass number of
1629 * free blocks in the group, so the routine can know upper limit.
1631 static void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1632 struct ext4_buddy *e4b)
1634 struct super_block *sb = ac->ac_sb;
1635 void *bitmap = EXT4_MB_BITMAP(e4b);
1636 struct ext4_free_extent ex;
1640 free = e4b->bd_info->bb_free;
1643 i = e4b->bd_info->bb_first_free;
1645 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1646 i = mb_find_next_zero_bit(bitmap,
1647 EXT4_BLOCKS_PER_GROUP(sb), i);
1648 if (i >= EXT4_BLOCKS_PER_GROUP(sb)) {
1650 * IF we have corrupt bitmap, we won't find any
1651 * free blocks even though group info says we
1652 * we have free blocks
1654 ext4_grp_locked_error(sb, e4b->bd_group,
1655 __func__, "%d free blocks as per "
1656 "group info. But bitmap says 0",
1661 mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
1662 BUG_ON(ex.fe_len <= 0);
1663 if (free < ex.fe_len) {
1664 ext4_grp_locked_error(sb, e4b->bd_group,
1665 __func__, "%d free blocks as per "
1666 "group info. But got %d blocks",
1669 * The number of free blocks differs. This mostly
1670 * indicate that the bitmap is corrupt. So exit
1671 * without claiming the space.
1676 ext4_mb_measure_extent(ac, &ex, e4b);
1682 ext4_mb_check_limits(ac, e4b, 1);
1686 * This is a special case for storages like raid5
1687 * we try to find stripe-aligned chunks for stripe-size requests
1688 * XXX should do so at least for multiples of stripe size as well
1690 static void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1691 struct ext4_buddy *e4b)
1693 struct super_block *sb = ac->ac_sb;
1694 struct ext4_sb_info *sbi = EXT4_SB(sb);
1695 void *bitmap = EXT4_MB_BITMAP(e4b);
1696 struct ext4_free_extent ex;
1697 ext4_fsblk_t first_group_block;
1702 BUG_ON(sbi->s_stripe == 0);
1704 /* find first stripe-aligned block in group */
1705 first_group_block = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb)
1706 + le32_to_cpu(sbi->s_es->s_first_data_block);
1707 a = first_group_block + sbi->s_stripe - 1;
1708 do_div(a, sbi->s_stripe);
1709 i = (a * sbi->s_stripe) - first_group_block;
1711 while (i < EXT4_BLOCKS_PER_GROUP(sb)) {
1712 if (!mb_test_bit(i, bitmap)) {
1713 max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
1714 if (max >= sbi->s_stripe) {
1717 ext4_mb_use_best_found(ac, e4b);
1725 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
1726 ext4_group_t group, int cr)
1728 unsigned free, fragments;
1730 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
1731 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1733 BUG_ON(cr < 0 || cr >= 4);
1734 BUG_ON(EXT4_MB_GRP_NEED_INIT(grp));
1736 free = grp->bb_free;
1737 fragments = grp->bb_fragments;
1745 BUG_ON(ac->ac_2order == 0);
1747 /* Avoid using the first bg of a flexgroup for data files */
1748 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
1749 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
1750 ((group % flex_size) == 0))
1753 bits = ac->ac_sb->s_blocksize_bits + 1;
1754 for (i = ac->ac_2order; i <= bits; i++)
1755 if (grp->bb_counters[i] > 0)
1759 if ((free / fragments) >= ac->ac_g_ex.fe_len)
1763 if (free >= ac->ac_g_ex.fe_len)
1776 * lock the group_info alloc_sem of all the groups
1777 * belonging to the same buddy cache page. This
1778 * make sure other parallel operation on the buddy
1779 * cache doesn't happen whild holding the buddy cache
1782 int ext4_mb_get_buddy_cache_lock(struct super_block *sb, ext4_group_t group)
1786 int blocks_per_page;
1787 int groups_per_page;
1788 ext4_group_t ngroups = ext4_get_groups_count(sb);
1789 ext4_group_t first_group;
1790 struct ext4_group_info *grp;
1792 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1794 * the buddy cache inode stores the block bitmap
1795 * and buddy information in consecutive blocks.
1796 * So for each group we need two blocks.
1799 pnum = block / blocks_per_page;
1800 first_group = pnum * blocks_per_page / 2;
1802 groups_per_page = blocks_per_page >> 1;
1803 if (groups_per_page == 0)
1804 groups_per_page = 1;
1805 /* read all groups the page covers into the cache */
1806 for (i = 0; i < groups_per_page; i++) {
1808 if ((first_group + i) >= ngroups)
1810 grp = ext4_get_group_info(sb, first_group + i);
1811 /* take all groups write allocation
1812 * semaphore. This make sure there is
1813 * no block allocation going on in any
1816 down_write_nested(&grp->alloc_sem, i);
1821 void ext4_mb_put_buddy_cache_lock(struct super_block *sb,
1822 ext4_group_t group, int locked_group)
1826 int blocks_per_page;
1827 ext4_group_t first_group;
1828 struct ext4_group_info *grp;
1830 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1832 * the buddy cache inode stores the block bitmap
1833 * and buddy information in consecutive blocks.
1834 * So for each group we need two blocks.
1837 pnum = block / blocks_per_page;
1838 first_group = pnum * blocks_per_page / 2;
1839 /* release locks on all the groups */
1840 for (i = 0; i < locked_group; i++) {
1842 grp = ext4_get_group_info(sb, first_group + i);
1843 /* take all groups write allocation
1844 * semaphore. This make sure there is
1845 * no block allocation going on in any
1848 up_write(&grp->alloc_sem);
1853 static int ext4_mb_init_group(struct super_block *sb, ext4_group_t group)
1858 int blocks_per_page;
1859 int block, pnum, poff;
1860 int num_grp_locked = 0;
1861 struct ext4_group_info *this_grp;
1862 struct ext4_sb_info *sbi = EXT4_SB(sb);
1863 struct inode *inode = sbi->s_buddy_cache;
1864 struct page *page = NULL, *bitmap_page = NULL;
1866 mb_debug("init group %lu\n", group);
1867 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1868 this_grp = ext4_get_group_info(sb, group);
1870 * This ensures we don't add group
1871 * to this buddy cache via resize
1873 num_grp_locked = ext4_mb_get_buddy_cache_lock(sb, group);
1874 if (!EXT4_MB_GRP_NEED_INIT(this_grp)) {
1876 * somebody initialized the group
1877 * return without doing anything
1883 * the buddy cache inode stores the block bitmap
1884 * and buddy information in consecutive blocks.
1885 * So for each group we need two blocks.
1888 pnum = block / blocks_per_page;
1889 poff = block % blocks_per_page;
1890 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1892 BUG_ON(page->mapping != inode->i_mapping);
1893 ret = ext4_mb_init_cache(page, NULL);
1900 if (page == NULL || !PageUptodate(page)) {
1904 mark_page_accessed(page);
1906 bitmap = page_address(page) + (poff * sb->s_blocksize);
1908 /* init buddy cache */
1910 pnum = block / blocks_per_page;
1911 poff = block % blocks_per_page;
1912 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1913 if (page == bitmap_page) {
1915 * If both the bitmap and buddy are in
1916 * the same page we don't need to force
1921 BUG_ON(page->mapping != inode->i_mapping);
1922 ret = ext4_mb_init_cache(page, bitmap);
1929 if (page == NULL || !PageUptodate(page)) {
1933 mark_page_accessed(page);
1935 ext4_mb_put_buddy_cache_lock(sb, group, num_grp_locked);
1937 page_cache_release(bitmap_page);
1939 page_cache_release(page);
1943 static noinline_for_stack int
1944 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
1946 ext4_group_t ngroups, group, i;
1950 struct ext4_sb_info *sbi;
1951 struct super_block *sb;
1952 struct ext4_buddy e4b;
1957 ngroups = ext4_get_groups_count(sb);
1958 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1960 /* first, try the goal */
1961 err = ext4_mb_find_by_goal(ac, &e4b);
1962 if (err || ac->ac_status == AC_STATUS_FOUND)
1965 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
1969 * ac->ac2_order is set only if the fe_len is a power of 2
1970 * if ac2_order is set we also set criteria to 0 so that we
1971 * try exact allocation using buddy.
1973 i = fls(ac->ac_g_ex.fe_len);
1976 * We search using buddy data only if the order of the request
1977 * is greater than equal to the sbi_s_mb_order2_reqs
1978 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
1980 if (i >= sbi->s_mb_order2_reqs) {
1982 * This should tell if fe_len is exactly power of 2
1984 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
1985 ac->ac_2order = i - 1;
1988 bsbits = ac->ac_sb->s_blocksize_bits;
1989 /* if stream allocation is enabled, use global goal */
1990 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
1991 isize = i_size_read(ac->ac_inode) >> bsbits;
1995 if (size < sbi->s_mb_stream_request &&
1996 (ac->ac_flags & EXT4_MB_HINT_DATA)) {
1997 /* TBD: may be hot point */
1998 spin_lock(&sbi->s_md_lock);
1999 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2000 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2001 spin_unlock(&sbi->s_md_lock);
2003 /* Let's just scan groups to find more-less suitable blocks */
2004 cr = ac->ac_2order ? 0 : 1;
2006 * cr == 0 try to get exact allocation,
2007 * cr == 3 try to get anything
2010 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2011 ac->ac_criteria = cr;
2013 * searching for the right group start
2014 * from the goal value specified
2016 group = ac->ac_g_ex.fe_group;
2018 for (i = 0; i < ngroups; group++, i++) {
2019 struct ext4_group_info *grp;
2020 struct ext4_group_desc *desc;
2022 if (group == ngroups)
2025 /* quick check to skip empty groups */
2026 grp = ext4_get_group_info(sb, group);
2027 if (grp->bb_free == 0)
2031 * if the group is already init we check whether it is
2032 * a good group and if not we don't load the buddy
2034 if (EXT4_MB_GRP_NEED_INIT(grp)) {
2036 * we need full data about the group
2037 * to make a good selection
2039 err = ext4_mb_init_group(sb, group);
2045 * If the particular group doesn't satisfy our
2046 * criteria we continue with the next group
2048 if (!ext4_mb_good_group(ac, group, cr))
2051 err = ext4_mb_load_buddy(sb, group, &e4b);
2055 ext4_lock_group(sb, group);
2056 if (!ext4_mb_good_group(ac, group, cr)) {
2057 /* someone did allocation from this group */
2058 ext4_unlock_group(sb, group);
2059 ext4_mb_release_desc(&e4b);
2063 ac->ac_groups_scanned++;
2064 desc = ext4_get_group_desc(sb, group, NULL);
2066 ext4_mb_simple_scan_group(ac, &e4b);
2068 ac->ac_g_ex.fe_len == sbi->s_stripe)
2069 ext4_mb_scan_aligned(ac, &e4b);
2071 ext4_mb_complex_scan_group(ac, &e4b);
2073 ext4_unlock_group(sb, group);
2074 ext4_mb_release_desc(&e4b);
2076 if (ac->ac_status != AC_STATUS_CONTINUE)
2081 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2082 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2084 * We've been searching too long. Let's try to allocate
2085 * the best chunk we've found so far
2088 ext4_mb_try_best_found(ac, &e4b);
2089 if (ac->ac_status != AC_STATUS_FOUND) {
2091 * Someone more lucky has already allocated it.
2092 * The only thing we can do is just take first
2094 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2096 ac->ac_b_ex.fe_group = 0;
2097 ac->ac_b_ex.fe_start = 0;
2098 ac->ac_b_ex.fe_len = 0;
2099 ac->ac_status = AC_STATUS_CONTINUE;
2100 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2102 atomic_inc(&sbi->s_mb_lost_chunks);
2110 #ifdef EXT4_MB_HISTORY
2111 struct ext4_mb_proc_session {
2112 struct ext4_mb_history *history;
2113 struct super_block *sb;
2118 static void *ext4_mb_history_skip_empty(struct ext4_mb_proc_session *s,
2119 struct ext4_mb_history *hs,
2122 if (hs == s->history + s->max)
2124 if (!first && hs == s->history + s->start)
2126 while (hs->orig.fe_len == 0) {
2128 if (hs == s->history + s->max)
2130 if (hs == s->history + s->start)
2136 static void *ext4_mb_seq_history_start(struct seq_file *seq, loff_t *pos)
2138 struct ext4_mb_proc_session *s = seq->private;
2139 struct ext4_mb_history *hs;
2143 return SEQ_START_TOKEN;
2144 hs = ext4_mb_history_skip_empty(s, s->history + s->start, 1);
2147 while (--l && (hs = ext4_mb_history_skip_empty(s, ++hs, 0)) != NULL);
2151 static void *ext4_mb_seq_history_next(struct seq_file *seq, void *v,
2154 struct ext4_mb_proc_session *s = seq->private;
2155 struct ext4_mb_history *hs = v;
2158 if (v == SEQ_START_TOKEN)
2159 return ext4_mb_history_skip_empty(s, s->history + s->start, 1);
2161 return ext4_mb_history_skip_empty(s, ++hs, 0);
2164 static int ext4_mb_seq_history_show(struct seq_file *seq, void *v)
2166 char buf[25], buf2[25], buf3[25], *fmt;
2167 struct ext4_mb_history *hs = v;
2169 if (v == SEQ_START_TOKEN) {
2170 seq_printf(seq, "%-5s %-8s %-23s %-23s %-23s %-5s "
2171 "%-5s %-2s %-5s %-5s %-5s %-6s\n",
2172 "pid", "inode", "original", "goal", "result", "found",
2173 "grps", "cr", "flags", "merge", "tail", "broken");
2177 if (hs->op == EXT4_MB_HISTORY_ALLOC) {
2178 fmt = "%-5u %-8u %-23s %-23s %-23s %-5u %-5u %-2u "
2179 "%-5u %-5s %-5u %-6u\n";
2180 sprintf(buf2, "%u/%d/%u@%u", hs->result.fe_group,
2181 hs->result.fe_start, hs->result.fe_len,
2182 hs->result.fe_logical);
2183 sprintf(buf, "%u/%d/%u@%u", hs->orig.fe_group,
2184 hs->orig.fe_start, hs->orig.fe_len,
2185 hs->orig.fe_logical);
2186 sprintf(buf3, "%u/%d/%u@%u", hs->goal.fe_group,
2187 hs->goal.fe_start, hs->goal.fe_len,
2188 hs->goal.fe_logical);
2189 seq_printf(seq, fmt, hs->pid, hs->ino, buf, buf3, buf2,
2190 hs->found, hs->groups, hs->cr, hs->flags,
2191 hs->merged ? "M" : "", hs->tail,
2192 hs->buddy ? 1 << hs->buddy : 0);
2193 } else if (hs->op == EXT4_MB_HISTORY_PREALLOC) {
2194 fmt = "%-5u %-8u %-23s %-23s %-23s\n";
2195 sprintf(buf2, "%u/%d/%u@%u", hs->result.fe_group,
2196 hs->result.fe_start, hs->result.fe_len,
2197 hs->result.fe_logical);
2198 sprintf(buf, "%u/%d/%u@%u", hs->orig.fe_group,
2199 hs->orig.fe_start, hs->orig.fe_len,
2200 hs->orig.fe_logical);
2201 seq_printf(seq, fmt, hs->pid, hs->ino, buf, "", buf2);
2202 } else if (hs->op == EXT4_MB_HISTORY_DISCARD) {
2203 sprintf(buf2, "%u/%d/%u", hs->result.fe_group,
2204 hs->result.fe_start, hs->result.fe_len);
2205 seq_printf(seq, "%-5u %-8u %-23s discard\n",
2206 hs->pid, hs->ino, buf2);
2207 } else if (hs->op == EXT4_MB_HISTORY_FREE) {
2208 sprintf(buf2, "%u/%d/%u", hs->result.fe_group,
2209 hs->result.fe_start, hs->result.fe_len);
2210 seq_printf(seq, "%-5u %-8u %-23s free\n",
2211 hs->pid, hs->ino, buf2);
2216 static void ext4_mb_seq_history_stop(struct seq_file *seq, void *v)
2220 static struct seq_operations ext4_mb_seq_history_ops = {
2221 .start = ext4_mb_seq_history_start,
2222 .next = ext4_mb_seq_history_next,
2223 .stop = ext4_mb_seq_history_stop,
2224 .show = ext4_mb_seq_history_show,
2227 static int ext4_mb_seq_history_open(struct inode *inode, struct file *file)
2229 struct super_block *sb = PDE(inode)->data;
2230 struct ext4_sb_info *sbi = EXT4_SB(sb);
2231 struct ext4_mb_proc_session *s;
2235 if (unlikely(sbi->s_mb_history == NULL))
2237 s = kmalloc(sizeof(*s), GFP_KERNEL);
2241 size = sizeof(struct ext4_mb_history) * sbi->s_mb_history_max;
2242 s->history = kmalloc(size, GFP_KERNEL);
2243 if (s->history == NULL) {
2248 spin_lock(&sbi->s_mb_history_lock);
2249 memcpy(s->history, sbi->s_mb_history, size);
2250 s->max = sbi->s_mb_history_max;
2251 s->start = sbi->s_mb_history_cur % s->max;
2252 spin_unlock(&sbi->s_mb_history_lock);
2254 rc = seq_open(file, &ext4_mb_seq_history_ops);
2256 struct seq_file *m = (struct seq_file *)file->private_data;
2266 static int ext4_mb_seq_history_release(struct inode *inode, struct file *file)
2268 struct seq_file *seq = (struct seq_file *)file->private_data;
2269 struct ext4_mb_proc_session *s = seq->private;
2272 return seq_release(inode, file);
2275 static ssize_t ext4_mb_seq_history_write(struct file *file,
2276 const char __user *buffer,
2277 size_t count, loff_t *ppos)
2279 struct seq_file *seq = (struct seq_file *)file->private_data;
2280 struct ext4_mb_proc_session *s = seq->private;
2281 struct super_block *sb = s->sb;
2285 if (count >= sizeof(str)) {
2286 printk(KERN_ERR "EXT4-fs: %s string too long, max %u bytes\n",
2287 "mb_history", (int)sizeof(str));
2291 if (copy_from_user(str, buffer, count))
2294 value = simple_strtol(str, NULL, 0);
2297 EXT4_SB(sb)->s_mb_history_filter = value;
2302 static struct file_operations ext4_mb_seq_history_fops = {
2303 .owner = THIS_MODULE,
2304 .open = ext4_mb_seq_history_open,
2306 .write = ext4_mb_seq_history_write,
2307 .llseek = seq_lseek,
2308 .release = ext4_mb_seq_history_release,
2311 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2313 struct super_block *sb = seq->private;
2316 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2319 return (void *) ((unsigned long) group);
2322 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2324 struct super_block *sb = seq->private;
2328 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2331 return (void *) ((unsigned long) group);
2334 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2336 struct super_block *sb = seq->private;
2337 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2340 struct ext4_buddy e4b;
2342 struct ext4_group_info info;
2343 unsigned short counters[16];
2348 seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
2349 "[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2350 "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2351 "group", "free", "frags", "first",
2352 "2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
2353 "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2355 i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2356 sizeof(struct ext4_group_info);
2357 err = ext4_mb_load_buddy(sb, group, &e4b);
2359 seq_printf(seq, "#%-5u: I/O error\n", group);
2362 ext4_lock_group(sb, group);
2363 memcpy(&sg, ext4_get_group_info(sb, group), i);
2364 ext4_unlock_group(sb, group);
2365 ext4_mb_release_desc(&e4b);
2367 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2368 sg.info.bb_fragments, sg.info.bb_first_free);
2369 for (i = 0; i <= 13; i++)
2370 seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2371 sg.info.bb_counters[i] : 0);
2372 seq_printf(seq, " ]\n");
2377 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2381 static struct seq_operations ext4_mb_seq_groups_ops = {
2382 .start = ext4_mb_seq_groups_start,
2383 .next = ext4_mb_seq_groups_next,
2384 .stop = ext4_mb_seq_groups_stop,
2385 .show = ext4_mb_seq_groups_show,
2388 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2390 struct super_block *sb = PDE(inode)->data;
2393 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2395 struct seq_file *m = (struct seq_file *)file->private_data;
2402 static struct file_operations ext4_mb_seq_groups_fops = {
2403 .owner = THIS_MODULE,
2404 .open = ext4_mb_seq_groups_open,
2406 .llseek = seq_lseek,
2407 .release = seq_release,
2410 static void ext4_mb_history_release(struct super_block *sb)
2412 struct ext4_sb_info *sbi = EXT4_SB(sb);
2414 if (sbi->s_proc != NULL) {
2415 remove_proc_entry("mb_groups", sbi->s_proc);
2416 remove_proc_entry("mb_history", sbi->s_proc);
2418 kfree(sbi->s_mb_history);
2421 static void ext4_mb_history_init(struct super_block *sb)
2423 struct ext4_sb_info *sbi = EXT4_SB(sb);
2426 if (sbi->s_proc != NULL) {
2427 proc_create_data("mb_history", S_IRUGO, sbi->s_proc,
2428 &ext4_mb_seq_history_fops, sb);
2429 proc_create_data("mb_groups", S_IRUGO, sbi->s_proc,
2430 &ext4_mb_seq_groups_fops, sb);
2433 sbi->s_mb_history_max = 1000;
2434 sbi->s_mb_history_cur = 0;
2435 spin_lock_init(&sbi->s_mb_history_lock);
2436 i = sbi->s_mb_history_max * sizeof(struct ext4_mb_history);
2437 sbi->s_mb_history = kzalloc(i, GFP_KERNEL);
2438 /* if we can't allocate history, then we simple won't use it */
2441 static noinline_for_stack void
2442 ext4_mb_store_history(struct ext4_allocation_context *ac)
2444 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2445 struct ext4_mb_history h;
2447 if (unlikely(sbi->s_mb_history == NULL))
2450 if (!(ac->ac_op & sbi->s_mb_history_filter))
2454 h.pid = current->pid;
2455 h.ino = ac->ac_inode ? ac->ac_inode->i_ino : 0;
2456 h.orig = ac->ac_o_ex;
2457 h.result = ac->ac_b_ex;
2458 h.flags = ac->ac_flags;
2459 h.found = ac->ac_found;
2460 h.groups = ac->ac_groups_scanned;
2461 h.cr = ac->ac_criteria;
2462 h.tail = ac->ac_tail;
2463 h.buddy = ac->ac_buddy;
2465 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC) {
2466 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
2467 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
2469 h.goal = ac->ac_g_ex;
2470 h.result = ac->ac_f_ex;
2473 spin_lock(&sbi->s_mb_history_lock);
2474 memcpy(sbi->s_mb_history + sbi->s_mb_history_cur, &h, sizeof(h));
2475 if (++sbi->s_mb_history_cur >= sbi->s_mb_history_max)
2476 sbi->s_mb_history_cur = 0;
2477 spin_unlock(&sbi->s_mb_history_lock);
2481 #define ext4_mb_history_release(sb)
2482 #define ext4_mb_history_init(sb)
2486 /* Create and initialize ext4_group_info data for the given group. */
2487 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2488 struct ext4_group_desc *desc)
2492 struct ext4_sb_info *sbi = EXT4_SB(sb);
2493 struct ext4_group_info **meta_group_info;
2496 * First check if this group is the first of a reserved block.
2497 * If it's true, we have to allocate a new table of pointers
2498 * to ext4_group_info structures
2500 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2501 metalen = sizeof(*meta_group_info) <<
2502 EXT4_DESC_PER_BLOCK_BITS(sb);
2503 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2504 if (meta_group_info == NULL) {
2505 printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2507 goto exit_meta_group_info;
2509 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] =
2514 * calculate needed size. if change bb_counters size,
2515 * don't forget about ext4_mb_generate_buddy()
2517 len = offsetof(typeof(**meta_group_info),
2518 bb_counters[sb->s_blocksize_bits + 2]);
2521 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)];
2522 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2524 meta_group_info[i] = kzalloc(len, GFP_KERNEL);
2525 if (meta_group_info[i] == NULL) {
2526 printk(KERN_ERR "EXT4-fs: can't allocate buddy mem\n");
2527 goto exit_group_info;
2529 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2530 &(meta_group_info[i]->bb_state));
2533 * initialize bb_free to be able to skip
2534 * empty groups without initialization
2536 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2537 meta_group_info[i]->bb_free =
2538 ext4_free_blocks_after_init(sb, group, desc);
2540 meta_group_info[i]->bb_free =
2541 ext4_free_blks_count(sb, desc);
2544 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2545 init_rwsem(&meta_group_info[i]->alloc_sem);
2546 meta_group_info[i]->bb_free_root.rb_node = NULL;;
2550 struct buffer_head *bh;
2551 meta_group_info[i]->bb_bitmap =
2552 kmalloc(sb->s_blocksize, GFP_KERNEL);
2553 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2554 bh = ext4_read_block_bitmap(sb, group);
2556 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2565 /* If a meta_group_info table has been allocated, release it now */
2566 if (group % EXT4_DESC_PER_BLOCK(sb) == 0)
2567 kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
2568 exit_meta_group_info:
2570 } /* ext4_mb_add_groupinfo */
2573 * Update an existing group.
2574 * This function is used for online resize
2576 void ext4_mb_update_group_info(struct ext4_group_info *grp, ext4_grpblk_t add)
2578 grp->bb_free += add;
2581 static int ext4_mb_init_backend(struct super_block *sb)
2583 ext4_group_t ngroups = ext4_get_groups_count(sb);
2586 struct ext4_sb_info *sbi = EXT4_SB(sb);
2587 struct ext4_super_block *es = sbi->s_es;
2588 int num_meta_group_infos;
2589 int num_meta_group_infos_max;
2591 struct ext4_group_info **meta_group_info;
2592 struct ext4_group_desc *desc;
2594 /* This is the number of blocks used by GDT */
2595 num_meta_group_infos = (ngroups + EXT4_DESC_PER_BLOCK(sb) -
2596 1) >> EXT4_DESC_PER_BLOCK_BITS(sb);
2599 * This is the total number of blocks used by GDT including
2600 * the number of reserved blocks for GDT.
2601 * The s_group_info array is allocated with this value
2602 * to allow a clean online resize without a complex
2603 * manipulation of pointer.
2604 * The drawback is the unused memory when no resize
2605 * occurs but it's very low in terms of pages
2606 * (see comments below)
2607 * Need to handle this properly when META_BG resizing is allowed
2609 num_meta_group_infos_max = num_meta_group_infos +
2610 le16_to_cpu(es->s_reserved_gdt_blocks);
2613 * array_size is the size of s_group_info array. We round it
2614 * to the next power of two because this approximation is done
2615 * internally by kmalloc so we can have some more memory
2616 * for free here (e.g. may be used for META_BG resize).
2619 while (array_size < sizeof(*sbi->s_group_info) *
2620 num_meta_group_infos_max)
2621 array_size = array_size << 1;
2622 /* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2623 * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2624 * So a two level scheme suffices for now. */
2625 sbi->s_group_info = kmalloc(array_size, GFP_KERNEL);
2626 if (sbi->s_group_info == NULL) {
2627 printk(KERN_ERR "EXT4-fs: can't allocate buddy meta group\n");
2630 sbi->s_buddy_cache = new_inode(sb);
2631 if (sbi->s_buddy_cache == NULL) {
2632 printk(KERN_ERR "EXT4-fs: can't get new inode\n");
2635 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2637 metalen = sizeof(*meta_group_info) << EXT4_DESC_PER_BLOCK_BITS(sb);
2638 for (i = 0; i < num_meta_group_infos; i++) {
2639 if ((i + 1) == num_meta_group_infos)
2640 metalen = sizeof(*meta_group_info) *
2642 (i << EXT4_DESC_PER_BLOCK_BITS(sb)));
2643 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2644 if (meta_group_info == NULL) {
2645 printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2649 sbi->s_group_info[i] = meta_group_info;
2652 for (i = 0; i < ngroups; i++) {
2653 desc = ext4_get_group_desc(sb, i, NULL);
2656 "EXT4-fs: can't read descriptor %u\n", i);
2659 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2667 kfree(ext4_get_group_info(sb, i));
2668 i = num_meta_group_infos;
2671 kfree(sbi->s_group_info[i]);
2672 iput(sbi->s_buddy_cache);
2674 kfree(sbi->s_group_info);
2678 int ext4_mb_init(struct super_block *sb, int needs_recovery)
2680 struct ext4_sb_info *sbi = EXT4_SB(sb);
2686 i = (sb->s_blocksize_bits + 2) * sizeof(unsigned short);
2688 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2689 if (sbi->s_mb_offsets == NULL) {
2693 i = (sb->s_blocksize_bits + 2) * sizeof(unsigned int);
2694 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2695 if (sbi->s_mb_maxs == NULL) {
2696 kfree(sbi->s_mb_offsets);
2700 /* order 0 is regular bitmap */
2701 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2702 sbi->s_mb_offsets[0] = 0;
2706 max = sb->s_blocksize << 2;
2708 sbi->s_mb_offsets[i] = offset;
2709 sbi->s_mb_maxs[i] = max;
2710 offset += 1 << (sb->s_blocksize_bits - i);
2713 } while (i <= sb->s_blocksize_bits + 1);
2715 /* init file for buddy data */
2716 ret = ext4_mb_init_backend(sb);
2718 kfree(sbi->s_mb_offsets);
2719 kfree(sbi->s_mb_maxs);
2723 spin_lock_init(&sbi->s_md_lock);
2724 spin_lock_init(&sbi->s_bal_lock);
2726 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2727 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2728 sbi->s_mb_stats = MB_DEFAULT_STATS;
2729 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2730 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2731 sbi->s_mb_history_filter = EXT4_MB_HISTORY_DEFAULT;
2732 sbi->s_mb_group_prealloc = MB_DEFAULT_GROUP_PREALLOC;
2734 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2735 if (sbi->s_locality_groups == NULL) {
2736 kfree(sbi->s_mb_offsets);
2737 kfree(sbi->s_mb_maxs);
2740 for_each_possible_cpu(i) {
2741 struct ext4_locality_group *lg;
2742 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2743 mutex_init(&lg->lg_mutex);
2744 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2745 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2746 spin_lock_init(&lg->lg_prealloc_lock);
2749 ext4_mb_history_init(sb);
2752 sbi->s_journal->j_commit_callback = release_blocks_on_commit;
2754 printk(KERN_INFO "EXT4-fs: mballoc enabled\n");
2758 /* need to called with ext4 group lock (ext4_lock_group) */
2759 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2761 struct ext4_prealloc_space *pa;
2762 struct list_head *cur, *tmp;
2765 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2766 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2767 list_del(&pa->pa_group_list);
2769 kmem_cache_free(ext4_pspace_cachep, pa);
2772 mb_debug("mballoc: %u PAs left\n", count);
2776 int ext4_mb_release(struct super_block *sb)
2778 ext4_group_t ngroups = ext4_get_groups_count(sb);
2780 int num_meta_group_infos;
2781 struct ext4_group_info *grinfo;
2782 struct ext4_sb_info *sbi = EXT4_SB(sb);
2784 if (sbi->s_group_info) {
2785 for (i = 0; i < ngroups; i++) {
2786 grinfo = ext4_get_group_info(sb, i);
2788 kfree(grinfo->bb_bitmap);
2790 ext4_lock_group(sb, i);
2791 ext4_mb_cleanup_pa(grinfo);
2792 ext4_unlock_group(sb, i);
2795 num_meta_group_infos = (ngroups +
2796 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2797 EXT4_DESC_PER_BLOCK_BITS(sb);
2798 for (i = 0; i < num_meta_group_infos; i++)
2799 kfree(sbi->s_group_info[i]);
2800 kfree(sbi->s_group_info);
2802 kfree(sbi->s_mb_offsets);
2803 kfree(sbi->s_mb_maxs);
2804 if (sbi->s_buddy_cache)
2805 iput(sbi->s_buddy_cache);
2806 if (sbi->s_mb_stats) {
2808 "EXT4-fs: mballoc: %u blocks %u reqs (%u success)\n",
2809 atomic_read(&sbi->s_bal_allocated),
2810 atomic_read(&sbi->s_bal_reqs),
2811 atomic_read(&sbi->s_bal_success));
2813 "EXT4-fs: mballoc: %u extents scanned, %u goal hits, "
2814 "%u 2^N hits, %u breaks, %u lost\n",
2815 atomic_read(&sbi->s_bal_ex_scanned),
2816 atomic_read(&sbi->s_bal_goals),
2817 atomic_read(&sbi->s_bal_2orders),
2818 atomic_read(&sbi->s_bal_breaks),
2819 atomic_read(&sbi->s_mb_lost_chunks));
2821 "EXT4-fs: mballoc: %lu generated and it took %Lu\n",
2822 sbi->s_mb_buddies_generated++,
2823 sbi->s_mb_generation_time);
2825 "EXT4-fs: mballoc: %u preallocated, %u discarded\n",
2826 atomic_read(&sbi->s_mb_preallocated),
2827 atomic_read(&sbi->s_mb_discarded));
2830 free_percpu(sbi->s_locality_groups);
2831 ext4_mb_history_release(sb);
2837 * This function is called by the jbd2 layer once the commit has finished,
2838 * so we know we can free the blocks that were released with that commit.
2840 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn)
2842 struct super_block *sb = journal->j_private;
2843 struct ext4_buddy e4b;
2844 struct ext4_group_info *db;
2845 int err, count = 0, count2 = 0;
2846 struct ext4_free_data *entry;
2847 ext4_fsblk_t discard_block;
2848 struct list_head *l, *ltmp;
2850 list_for_each_safe(l, ltmp, &txn->t_private_list) {
2851 entry = list_entry(l, struct ext4_free_data, list);
2853 mb_debug("gonna free %u blocks in group %u (0x%p):",
2854 entry->count, entry->group, entry);
2856 err = ext4_mb_load_buddy(sb, entry->group, &e4b);
2857 /* we expect to find existing buddy because it's pinned */
2861 /* there are blocks to put in buddy to make them really free */
2862 count += entry->count;
2864 ext4_lock_group(sb, entry->group);
2865 /* Take it out of per group rb tree */
2866 rb_erase(&entry->node, &(db->bb_free_root));
2867 mb_free_blocks(NULL, &e4b, entry->start_blk, entry->count);
2869 if (!db->bb_free_root.rb_node) {
2870 /* No more items in the per group rb tree
2871 * balance refcounts from ext4_mb_free_metadata()
2873 page_cache_release(e4b.bd_buddy_page);
2874 page_cache_release(e4b.bd_bitmap_page);
2876 ext4_unlock_group(sb, entry->group);
2877 discard_block = (ext4_fsblk_t) entry->group * EXT4_BLOCKS_PER_GROUP(sb)
2879 + le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
2880 trace_mark(ext4_discard_blocks, "dev %s blk %llu count %u",
2881 sb->s_id, (unsigned long long) discard_block,
2883 sb_issue_discard(sb, discard_block, entry->count);
2885 kmem_cache_free(ext4_free_ext_cachep, entry);
2886 ext4_mb_release_desc(&e4b);
2889 mb_debug("freed %u blocks in %u structures\n", count, count2);
2892 int __init init_ext4_mballoc(void)
2894 ext4_pspace_cachep =
2895 kmem_cache_create("ext4_prealloc_space",
2896 sizeof(struct ext4_prealloc_space),
2897 0, SLAB_RECLAIM_ACCOUNT, NULL);
2898 if (ext4_pspace_cachep == NULL)
2902 kmem_cache_create("ext4_alloc_context",
2903 sizeof(struct ext4_allocation_context),
2904 0, SLAB_RECLAIM_ACCOUNT, NULL);
2905 if (ext4_ac_cachep == NULL) {
2906 kmem_cache_destroy(ext4_pspace_cachep);
2910 ext4_free_ext_cachep =
2911 kmem_cache_create("ext4_free_block_extents",
2912 sizeof(struct ext4_free_data),
2913 0, SLAB_RECLAIM_ACCOUNT, NULL);
2914 if (ext4_free_ext_cachep == NULL) {
2915 kmem_cache_destroy(ext4_pspace_cachep);
2916 kmem_cache_destroy(ext4_ac_cachep);
2922 void exit_ext4_mballoc(void)
2924 /* XXX: synchronize_rcu(); */
2925 kmem_cache_destroy(ext4_pspace_cachep);
2926 kmem_cache_destroy(ext4_ac_cachep);
2927 kmem_cache_destroy(ext4_free_ext_cachep);
2932 * Check quota and mark choosed space (ac->ac_b_ex) non-free in bitmaps
2933 * Returns 0 if success or error code
2935 static noinline_for_stack int
2936 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2937 handle_t *handle, unsigned int reserv_blks)
2939 struct buffer_head *bitmap_bh = NULL;
2940 struct ext4_super_block *es;
2941 struct ext4_group_desc *gdp;
2942 struct buffer_head *gdp_bh;
2943 struct ext4_sb_info *sbi;
2944 struct super_block *sb;
2948 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2949 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2957 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2961 err = ext4_journal_get_write_access(handle, bitmap_bh);
2966 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2970 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
2971 ext4_free_blks_count(sb, gdp));
2973 err = ext4_journal_get_write_access(handle, gdp_bh);
2977 block = ac->ac_b_ex.fe_group * EXT4_BLOCKS_PER_GROUP(sb)
2978 + ac->ac_b_ex.fe_start
2979 + le32_to_cpu(es->s_first_data_block);
2981 len = ac->ac_b_ex.fe_len;
2982 if (in_range(ext4_block_bitmap(sb, gdp), block, len) ||
2983 in_range(ext4_inode_bitmap(sb, gdp), block, len) ||
2984 in_range(block, ext4_inode_table(sb, gdp),
2985 EXT4_SB(sb)->s_itb_per_group) ||
2986 in_range(block + len - 1, ext4_inode_table(sb, gdp),
2987 EXT4_SB(sb)->s_itb_per_group)) {
2988 ext4_error(sb, __func__,
2989 "Allocating block %llu in system zone of %d group\n",
2990 block, ac->ac_b_ex.fe_group);
2991 /* File system mounted not to panic on error
2992 * Fix the bitmap and repeat the block allocation
2993 * We leak some of the blocks here.
2995 mb_set_bits(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group),
2996 bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2997 ac->ac_b_ex.fe_len);
2998 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3003 #ifdef AGGRESSIVE_CHECK
3006 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3007 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3008 bitmap_bh->b_data));
3012 spin_lock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
3013 mb_set_bits(NULL, bitmap_bh->b_data,
3014 ac->ac_b_ex.fe_start, ac->ac_b_ex.fe_len);
3015 if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
3016 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3017 ext4_free_blks_set(sb, gdp,
3018 ext4_free_blocks_after_init(sb,
3019 ac->ac_b_ex.fe_group, gdp));
3021 len = ext4_free_blks_count(sb, gdp) - ac->ac_b_ex.fe_len;
3022 ext4_free_blks_set(sb, gdp, len);
3023 gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
3024 spin_unlock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
3025 percpu_counter_sub(&sbi->s_freeblocks_counter, ac->ac_b_ex.fe_len);
3027 * Now reduce the dirty block count also. Should not go negative
3029 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3030 /* release all the reserved blocks if non delalloc */
3031 percpu_counter_sub(&sbi->s_dirtyblocks_counter, reserv_blks);
3033 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
3034 ac->ac_b_ex.fe_len);
3035 /* convert reserved quota blocks to real quota blocks */
3036 vfs_dq_claim_block(ac->ac_inode, ac->ac_b_ex.fe_len);
3039 if (sbi->s_log_groups_per_flex) {
3040 ext4_group_t flex_group = ext4_flex_group(sbi,
3041 ac->ac_b_ex.fe_group);
3042 atomic_sub(ac->ac_b_ex.fe_len,
3043 &sbi->s_flex_groups[flex_group].free_blocks);
3046 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3049 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3058 * here we normalize request for locality group
3059 * Group request are normalized to s_strip size if we set the same via mount
3060 * option. If not we set it to s_mb_group_prealloc which can be configured via
3061 * /sys/fs/ext4/<partition>/mb_group_prealloc
3063 * XXX: should we try to preallocate more than the group has now?
3065 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3067 struct super_block *sb = ac->ac_sb;
3068 struct ext4_locality_group *lg = ac->ac_lg;
3071 if (EXT4_SB(sb)->s_stripe)
3072 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_stripe;
3074 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3075 mb_debug("#%u: goal %u blocks for locality group\n",
3076 current->pid, ac->ac_g_ex.fe_len);
3080 * Normalization means making request better in terms of
3081 * size and alignment
3083 static noinline_for_stack void
3084 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3085 struct ext4_allocation_request *ar)
3089 loff_t size, orig_size, start_off;
3090 ext4_lblk_t start, orig_start;
3091 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3092 struct ext4_prealloc_space *pa;
3094 /* do normalize only data requests, metadata requests
3095 do not need preallocation */
3096 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3099 /* sometime caller may want exact blocks */
3100 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3103 /* caller may indicate that preallocation isn't
3104 * required (it's a tail, for example) */
3105 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3108 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3109 ext4_mb_normalize_group_request(ac);
3113 bsbits = ac->ac_sb->s_blocksize_bits;
3115 /* first, let's learn actual file size
3116 * given current request is allocated */
3117 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
3118 size = size << bsbits;
3119 if (size < i_size_read(ac->ac_inode))
3120 size = i_size_read(ac->ac_inode);
3122 /* max size of free chunks */
3125 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
3126 (req <= (size) || max <= (chunk_size))
3128 /* first, try to predict filesize */
3129 /* XXX: should this table be tunable? */
3131 if (size <= 16 * 1024) {
3133 } else if (size <= 32 * 1024) {
3135 } else if (size <= 64 * 1024) {
3137 } else if (size <= 128 * 1024) {
3139 } else if (size <= 256 * 1024) {
3141 } else if (size <= 512 * 1024) {
3143 } else if (size <= 1024 * 1024) {
3145 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3146 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3147 (21 - bsbits)) << 21;
3148 size = 2 * 1024 * 1024;
3149 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3150 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3151 (22 - bsbits)) << 22;
3152 size = 4 * 1024 * 1024;
3153 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3154 (8<<20)>>bsbits, max, 8 * 1024)) {
3155 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3156 (23 - bsbits)) << 23;
3157 size = 8 * 1024 * 1024;
3159 start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
3160 size = ac->ac_o_ex.fe_len << bsbits;
3162 orig_size = size = size >> bsbits;
3163 orig_start = start = start_off >> bsbits;
3165 /* don't cover already allocated blocks in selected range */
3166 if (ar->pleft && start <= ar->lleft) {
3167 size -= ar->lleft + 1 - start;
3168 start = ar->lleft + 1;
3170 if (ar->pright && start + size - 1 >= ar->lright)
3171 size -= start + size - ar->lright;
3175 /* check we don't cross already preallocated blocks */
3177 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3182 spin_lock(&pa->pa_lock);
3183 if (pa->pa_deleted) {
3184 spin_unlock(&pa->pa_lock);
3188 pa_end = pa->pa_lstart + pa->pa_len;
3190 /* PA must not overlap original request */
3191 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3192 ac->ac_o_ex.fe_logical < pa->pa_lstart));
3194 /* skip PA normalized request doesn't overlap with */
3195 if (pa->pa_lstart >= end) {
3196 spin_unlock(&pa->pa_lock);
3199 if (pa_end <= start) {
3200 spin_unlock(&pa->pa_lock);
3203 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3205 if (pa_end <= ac->ac_o_ex.fe_logical) {
3206 BUG_ON(pa_end < start);
3210 if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3211 BUG_ON(pa->pa_lstart > end);
3212 end = pa->pa_lstart;
3214 spin_unlock(&pa->pa_lock);
3219 /* XXX: extra loop to check we really don't overlap preallocations */
3221 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3223 spin_lock(&pa->pa_lock);
3224 if (pa->pa_deleted == 0) {
3225 pa_end = pa->pa_lstart + pa->pa_len;
3226 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3228 spin_unlock(&pa->pa_lock);
3232 if (start + size <= ac->ac_o_ex.fe_logical &&
3233 start > ac->ac_o_ex.fe_logical) {
3234 printk(KERN_ERR "start %lu, size %lu, fe_logical %lu\n",
3235 (unsigned long) start, (unsigned long) size,
3236 (unsigned long) ac->ac_o_ex.fe_logical);
3238 BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3239 start > ac->ac_o_ex.fe_logical);
3240 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3242 /* now prepare goal request */
3244 /* XXX: is it better to align blocks WRT to logical
3245 * placement or satisfy big request as is */
3246 ac->ac_g_ex.fe_logical = start;
3247 ac->ac_g_ex.fe_len = size;
3249 /* define goal start in order to merge */
3250 if (ar->pright && (ar->lright == (start + size))) {
3251 /* merge to the right */
3252 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3253 &ac->ac_f_ex.fe_group,
3254 &ac->ac_f_ex.fe_start);
3255 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3257 if (ar->pleft && (ar->lleft + 1 == start)) {
3258 /* merge to the left */
3259 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3260 &ac->ac_f_ex.fe_group,
3261 &ac->ac_f_ex.fe_start);
3262 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3265 mb_debug("goal: %u(was %u) blocks at %u\n", (unsigned) size,
3266 (unsigned) orig_size, (unsigned) start);
3269 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3271 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3273 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3274 atomic_inc(&sbi->s_bal_reqs);
3275 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3276 if (ac->ac_o_ex.fe_len >= ac->ac_g_ex.fe_len)
3277 atomic_inc(&sbi->s_bal_success);
3278 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3279 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3280 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3281 atomic_inc(&sbi->s_bal_goals);
3282 if (ac->ac_found > sbi->s_mb_max_to_scan)
3283 atomic_inc(&sbi->s_bal_breaks);
3286 ext4_mb_store_history(ac);
3290 * use blocks preallocated to inode
3292 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3293 struct ext4_prealloc_space *pa)
3299 /* found preallocated blocks, use them */
3300 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3301 end = min(pa->pa_pstart + pa->pa_len, start + ac->ac_o_ex.fe_len);
3303 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3304 &ac->ac_b_ex.fe_start);
3305 ac->ac_b_ex.fe_len = len;
3306 ac->ac_status = AC_STATUS_FOUND;
3309 BUG_ON(start < pa->pa_pstart);
3310 BUG_ON(start + len > pa->pa_pstart + pa->pa_len);
3311 BUG_ON(pa->pa_free < len);
3314 mb_debug("use %llu/%u from inode pa %p\n", start, len, pa);
3318 * use blocks preallocated to locality group
3320 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3321 struct ext4_prealloc_space *pa)
3323 unsigned int len = ac->ac_o_ex.fe_len;
3325 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3326 &ac->ac_b_ex.fe_group,
3327 &ac->ac_b_ex.fe_start);
3328 ac->ac_b_ex.fe_len = len;
3329 ac->ac_status = AC_STATUS_FOUND;
3332 /* we don't correct pa_pstart or pa_plen here to avoid
3333 * possible race when the group is being loaded concurrently
3334 * instead we correct pa later, after blocks are marked
3335 * in on-disk bitmap -- see ext4_mb_release_context()
3336 * Other CPUs are prevented from allocating from this pa by lg_mutex
3338 mb_debug("use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3342 * Return the prealloc space that have minimal distance
3343 * from the goal block. @cpa is the prealloc
3344 * space that is having currently known minimal distance
3345 * from the goal block.
3347 static struct ext4_prealloc_space *
3348 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3349 struct ext4_prealloc_space *pa,
3350 struct ext4_prealloc_space *cpa)
3352 ext4_fsblk_t cur_distance, new_distance;
3355 atomic_inc(&pa->pa_count);
3358 cur_distance = abs(goal_block - cpa->pa_pstart);
3359 new_distance = abs(goal_block - pa->pa_pstart);
3361 if (cur_distance < new_distance)
3364 /* drop the previous reference */
3365 atomic_dec(&cpa->pa_count);
3366 atomic_inc(&pa->pa_count);
3371 * search goal blocks in preallocated space
3373 static noinline_for_stack int
3374 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3377 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3378 struct ext4_locality_group *lg;
3379 struct ext4_prealloc_space *pa, *cpa = NULL;
3380 ext4_fsblk_t goal_block;
3382 /* only data can be preallocated */
3383 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3386 /* first, try per-file preallocation */
3388 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3390 /* all fields in this condition don't change,
3391 * so we can skip locking for them */
3392 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3393 ac->ac_o_ex.fe_logical >= pa->pa_lstart + pa->pa_len)
3396 /* found preallocated blocks, use them */
3397 spin_lock(&pa->pa_lock);
3398 if (pa->pa_deleted == 0 && pa->pa_free) {
3399 atomic_inc(&pa->pa_count);
3400 ext4_mb_use_inode_pa(ac, pa);
3401 spin_unlock(&pa->pa_lock);
3402 ac->ac_criteria = 10;
3406 spin_unlock(&pa->pa_lock);
3410 /* can we use group allocation? */
3411 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3414 /* inode may have no locality group for some reason */
3418 order = fls(ac->ac_o_ex.fe_len) - 1;
3419 if (order > PREALLOC_TB_SIZE - 1)
3420 /* The max size of hash table is PREALLOC_TB_SIZE */
3421 order = PREALLOC_TB_SIZE - 1;
3423 goal_block = ac->ac_g_ex.fe_group * EXT4_BLOCKS_PER_GROUP(ac->ac_sb) +
3424 ac->ac_g_ex.fe_start +
3425 le32_to_cpu(EXT4_SB(ac->ac_sb)->s_es->s_first_data_block);
3427 * search for the prealloc space that is having
3428 * minimal distance from the goal block.
3430 for (i = order; i < PREALLOC_TB_SIZE; i++) {
3432 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3434 spin_lock(&pa->pa_lock);
3435 if (pa->pa_deleted == 0 &&
3436 pa->pa_free >= ac->ac_o_ex.fe_len) {
3438 cpa = ext4_mb_check_group_pa(goal_block,
3441 spin_unlock(&pa->pa_lock);
3446 ext4_mb_use_group_pa(ac, cpa);
3447 ac->ac_criteria = 20;
3454 * the function goes through all block freed in the group
3455 * but not yet committed and marks them used in in-core bitmap.
3456 * buddy must be generated from this bitmap
3457 * Need to be called with ext4 group lock (ext4_lock_group)
3459 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3463 struct ext4_group_info *grp;
3464 struct ext4_free_data *entry;
3466 grp = ext4_get_group_info(sb, group);
3467 n = rb_first(&(grp->bb_free_root));
3470 entry = rb_entry(n, struct ext4_free_data, node);
3471 mb_set_bits(sb_bgl_lock(EXT4_SB(sb), group),
3472 bitmap, entry->start_blk,
3480 * the function goes through all preallocation in this group and marks them
3481 * used in in-core bitmap. buddy must be generated from this bitmap
3482 * Need to be called with ext4 group lock (ext4_lock_group)
3484 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3487 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3488 struct ext4_prealloc_space *pa;
3489 struct list_head *cur;
3490 ext4_group_t groupnr;
3491 ext4_grpblk_t start;
3492 int preallocated = 0;
3496 /* all form of preallocation discards first load group,
3497 * so the only competing code is preallocation use.
3498 * we don't need any locking here
3499 * notice we do NOT ignore preallocations with pa_deleted
3500 * otherwise we could leave used blocks available for
3501 * allocation in buddy when concurrent ext4_mb_put_pa()
3502 * is dropping preallocation
3504 list_for_each(cur, &grp->bb_prealloc_list) {
3505 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3506 spin_lock(&pa->pa_lock);
3507 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3510 spin_unlock(&pa->pa_lock);
3511 if (unlikely(len == 0))
3513 BUG_ON(groupnr != group);
3514 mb_set_bits(sb_bgl_lock(EXT4_SB(sb), group),
3515 bitmap, start, len);
3516 preallocated += len;
3519 mb_debug("prellocated %u for group %u\n", preallocated, group);
3522 static void ext4_mb_pa_callback(struct rcu_head *head)
3524 struct ext4_prealloc_space *pa;
3525 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3526 kmem_cache_free(ext4_pspace_cachep, pa);
3530 * drops a reference to preallocated space descriptor
3531 * if this was the last reference and the space is consumed
3533 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3534 struct super_block *sb, struct ext4_prealloc_space *pa)
3537 ext4_fsblk_t grp_blk;
3539 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3542 /* in this short window concurrent discard can set pa_deleted */
3543 spin_lock(&pa->pa_lock);
3544 if (pa->pa_deleted == 1) {
3545 spin_unlock(&pa->pa_lock);
3550 spin_unlock(&pa->pa_lock);
3552 grp_blk = pa->pa_pstart;
3554 * If doing group-based preallocation, pa_pstart may be in the
3555 * next group when pa is used up
3557 if (pa->pa_type == MB_GROUP_PA)
3560 ext4_get_group_no_and_offset(sb, grp_blk, &grp, NULL);
3565 * P1 (buddy init) P2 (regular allocation)
3566 * find block B in PA
3567 * copy on-disk bitmap to buddy
3568 * mark B in on-disk bitmap
3569 * drop PA from group
3570 * mark all PAs in buddy
3572 * thus, P1 initializes buddy with B available. to prevent this
3573 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3576 ext4_lock_group(sb, grp);
3577 list_del(&pa->pa_group_list);
3578 ext4_unlock_group(sb, grp);
3580 spin_lock(pa->pa_obj_lock);
3581 list_del_rcu(&pa->pa_inode_list);
3582 spin_unlock(pa->pa_obj_lock);
3584 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3588 * creates new preallocated space for given inode
3590 static noinline_for_stack int
3591 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3593 struct super_block *sb = ac->ac_sb;
3594 struct ext4_prealloc_space *pa;
3595 struct ext4_group_info *grp;
3596 struct ext4_inode_info *ei;
3598 /* preallocate only when found space is larger then requested */
3599 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3600 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3601 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3603 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3607 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3613 /* we can't allocate as much as normalizer wants.
3614 * so, found space must get proper lstart
3615 * to cover original request */
3616 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3617 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3619 /* we're limited by original request in that
3620 * logical block must be covered any way
3621 * winl is window we can move our chunk within */
3622 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3624 /* also, we should cover whole original request */
3625 wins = ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len;
3627 /* the smallest one defines real window */
3628 win = min(winl, wins);
3630 offs = ac->ac_o_ex.fe_logical % ac->ac_b_ex.fe_len;
3631 if (offs && offs < win)
3634 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical - win;
3635 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3636 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3639 /* preallocation can change ac_b_ex, thus we store actually
3640 * allocated blocks for history */
3641 ac->ac_f_ex = ac->ac_b_ex;
3643 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3644 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3645 pa->pa_len = ac->ac_b_ex.fe_len;
3646 pa->pa_free = pa->pa_len;
3647 atomic_set(&pa->pa_count, 1);
3648 spin_lock_init(&pa->pa_lock);
3649 INIT_LIST_HEAD(&pa->pa_inode_list);
3650 INIT_LIST_HEAD(&pa->pa_group_list);
3652 pa->pa_type = MB_INODE_PA;
3654 mb_debug("new inode pa %p: %llu/%u for %u\n", pa,
3655 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3656 trace_mark(ext4_mb_new_inode_pa,
3657 "dev %s ino %lu pstart %llu len %u lstart %u",
3658 sb->s_id, ac->ac_inode->i_ino,
3659 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3661 ext4_mb_use_inode_pa(ac, pa);
3662 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3664 ei = EXT4_I(ac->ac_inode);
3665 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3667 pa->pa_obj_lock = &ei->i_prealloc_lock;
3668 pa->pa_inode = ac->ac_inode;
3670 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3671 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3672 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3674 spin_lock(pa->pa_obj_lock);
3675 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3676 spin_unlock(pa->pa_obj_lock);
3682 * creates new preallocated space for locality group inodes belongs to
3684 static noinline_for_stack int
3685 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3687 struct super_block *sb = ac->ac_sb;
3688 struct ext4_locality_group *lg;
3689 struct ext4_prealloc_space *pa;
3690 struct ext4_group_info *grp;
3692 /* preallocate only when found space is larger then requested */
3693 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3694 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3695 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3697 BUG_ON(ext4_pspace_cachep == NULL);
3698 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3702 /* preallocation can change ac_b_ex, thus we store actually
3703 * allocated blocks for history */
3704 ac->ac_f_ex = ac->ac_b_ex;
3706 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3707 pa->pa_lstart = pa->pa_pstart;
3708 pa->pa_len = ac->ac_b_ex.fe_len;
3709 pa->pa_free = pa->pa_len;
3710 atomic_set(&pa->pa_count, 1);
3711 spin_lock_init(&pa->pa_lock);
3712 INIT_LIST_HEAD(&pa->pa_inode_list);
3713 INIT_LIST_HEAD(&pa->pa_group_list);
3715 pa->pa_type = MB_GROUP_PA;
3717 mb_debug("new group pa %p: %llu/%u for %u\n", pa,
3718 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3719 trace_mark(ext4_mb_new_group_pa, "dev %s pstart %llu len %u lstart %u",
3720 sb->s_id, pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3722 ext4_mb_use_group_pa(ac, pa);
3723 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3725 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3729 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3730 pa->pa_inode = NULL;
3732 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3733 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3734 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3737 * We will later add the new pa to the right bucket
3738 * after updating the pa_free in ext4_mb_release_context
3743 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3747 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3748 err = ext4_mb_new_group_pa(ac);
3750 err = ext4_mb_new_inode_pa(ac);
3755 * finds all unused blocks in on-disk bitmap, frees them in
3756 * in-core bitmap and buddy.
3757 * @pa must be unlinked from inode and group lists, so that
3758 * nobody else can find/use it.
3759 * the caller MUST hold group/inode locks.
3760 * TODO: optimize the case when there are no in-core structures yet
3762 static noinline_for_stack int
3763 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3764 struct ext4_prealloc_space *pa,
3765 struct ext4_allocation_context *ac)
3767 struct super_block *sb = e4b->bd_sb;
3768 struct ext4_sb_info *sbi = EXT4_SB(sb);
3773 unsigned long long grp_blk_start;
3778 BUG_ON(pa->pa_deleted == 0);
3779 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3780 grp_blk_start = pa->pa_pstart - bit;
3781 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3782 end = bit + pa->pa_len;
3786 ac->ac_inode = pa->pa_inode;
3787 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3791 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3794 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3795 start = group * EXT4_BLOCKS_PER_GROUP(sb) + bit +
3796 le32_to_cpu(sbi->s_es->s_first_data_block);
3797 mb_debug(" free preallocated %u/%u in group %u\n",
3798 (unsigned) start, (unsigned) next - bit,
3803 ac->ac_b_ex.fe_group = group;
3804 ac->ac_b_ex.fe_start = bit;
3805 ac->ac_b_ex.fe_len = next - bit;
3806 ac->ac_b_ex.fe_logical = 0;
3807 ext4_mb_store_history(ac);
3810 trace_mark(ext4_mb_release_inode_pa,
3811 "dev %s ino %lu block %llu count %u",
3812 sb->s_id, pa->pa_inode->i_ino, grp_blk_start + bit,
3814 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3817 if (free != pa->pa_free) {
3818 printk(KERN_CRIT "pa %p: logic %lu, phys. %lu, len %lu\n",
3819 pa, (unsigned long) pa->pa_lstart,
3820 (unsigned long) pa->pa_pstart,
3821 (unsigned long) pa->pa_len);
3822 ext4_grp_locked_error(sb, group,
3823 __func__, "free %u, pa_free %u",
3826 * pa is already deleted so we use the value obtained
3827 * from the bitmap and continue.
3830 atomic_add(free, &sbi->s_mb_discarded);
3835 static noinline_for_stack int
3836 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3837 struct ext4_prealloc_space *pa,
3838 struct ext4_allocation_context *ac)
3840 struct super_block *sb = e4b->bd_sb;
3845 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3847 trace_mark(ext4_mb_release_group_pa, "dev %s pstart %llu len %d",
3848 sb->s_id, pa->pa_pstart, pa->pa_len);
3849 BUG_ON(pa->pa_deleted == 0);
3850 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3851 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3852 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3853 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3857 ac->ac_inode = NULL;
3858 ac->ac_b_ex.fe_group = group;
3859 ac->ac_b_ex.fe_start = bit;
3860 ac->ac_b_ex.fe_len = pa->pa_len;
3861 ac->ac_b_ex.fe_logical = 0;
3862 ext4_mb_store_history(ac);
3869 * releases all preallocations in given group
3871 * first, we need to decide discard policy:
3872 * - when do we discard
3874 * - how many do we discard
3875 * 1) how many requested
3877 static noinline_for_stack int
3878 ext4_mb_discard_group_preallocations(struct super_block *sb,
3879 ext4_group_t group, int needed)
3881 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3882 struct buffer_head *bitmap_bh = NULL;
3883 struct ext4_prealloc_space *pa, *tmp;
3884 struct ext4_allocation_context *ac;
3885 struct list_head list;
3886 struct ext4_buddy e4b;
3891 mb_debug("discard preallocation for group %u\n", group);
3893 if (list_empty(&grp->bb_prealloc_list))
3896 bitmap_bh = ext4_read_block_bitmap(sb, group);
3897 if (bitmap_bh == NULL) {
3898 ext4_error(sb, __func__, "Error in reading block "
3899 "bitmap for %u", group);
3903 err = ext4_mb_load_buddy(sb, group, &e4b);
3905 ext4_error(sb, __func__, "Error in loading buddy "
3906 "information for %u", group);
3912 needed = EXT4_BLOCKS_PER_GROUP(sb) + 1;
3914 INIT_LIST_HEAD(&list);
3915 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
3917 ext4_lock_group(sb, group);
3918 list_for_each_entry_safe(pa, tmp,
3919 &grp->bb_prealloc_list, pa_group_list) {
3920 spin_lock(&pa->pa_lock);
3921 if (atomic_read(&pa->pa_count)) {
3922 spin_unlock(&pa->pa_lock);
3926 if (pa->pa_deleted) {
3927 spin_unlock(&pa->pa_lock);
3931 /* seems this one can be freed ... */
3934 /* we can trust pa_free ... */
3935 free += pa->pa_free;
3937 spin_unlock(&pa->pa_lock);
3939 list_del(&pa->pa_group_list);
3940 list_add(&pa->u.pa_tmp_list, &list);
3943 /* if we still need more blocks and some PAs were used, try again */
3944 if (free < needed && busy) {
3946 ext4_unlock_group(sb, group);
3948 * Yield the CPU here so that we don't get soft lockup
3949 * in non preempt case.
3955 /* found anything to free? */
3956 if (list_empty(&list)) {
3961 /* now free all selected PAs */
3962 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3964 /* remove from object (inode or locality group) */
3965 spin_lock(pa->pa_obj_lock);
3966 list_del_rcu(&pa->pa_inode_list);
3967 spin_unlock(pa->pa_obj_lock);
3969 if (pa->pa_type == MB_GROUP_PA)
3970 ext4_mb_release_group_pa(&e4b, pa, ac);
3972 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
3974 list_del(&pa->u.pa_tmp_list);
3975 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3979 ext4_unlock_group(sb, group);
3981 kmem_cache_free(ext4_ac_cachep, ac);
3982 ext4_mb_release_desc(&e4b);
3988 * releases all non-used preallocated blocks for given inode
3990 * It's important to discard preallocations under i_data_sem
3991 * We don't want another block to be served from the prealloc
3992 * space when we are discarding the inode prealloc space.
3994 * FIXME!! Make sure it is valid at all the call sites
3996 void ext4_discard_preallocations(struct inode *inode)
3998 struct ext4_inode_info *ei = EXT4_I(inode);
3999 struct super_block *sb = inode->i_sb;
4000 struct buffer_head *bitmap_bh = NULL;
4001 struct ext4_prealloc_space *pa, *tmp;
4002 struct ext4_allocation_context *ac;
4003 ext4_group_t group = 0;
4004 struct list_head list;
4005 struct ext4_buddy e4b;
4008 if (!S_ISREG(inode->i_mode)) {
4009 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4013 mb_debug("discard preallocation for inode %lu\n", inode->i_ino);
4014 trace_mark(ext4_discard_preallocations, "dev %s ino %lu", sb->s_id,
4017 INIT_LIST_HEAD(&list);
4019 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4021 /* first, collect all pa's in the inode */
4022 spin_lock(&ei->i_prealloc_lock);
4023 while (!list_empty(&ei->i_prealloc_list)) {
4024 pa = list_entry(ei->i_prealloc_list.next,
4025 struct ext4_prealloc_space, pa_inode_list);
4026 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4027 spin_lock(&pa->pa_lock);
4028 if (atomic_read(&pa->pa_count)) {
4029 /* this shouldn't happen often - nobody should
4030 * use preallocation while we're discarding it */
4031 spin_unlock(&pa->pa_lock);
4032 spin_unlock(&ei->i_prealloc_lock);
4033 printk(KERN_ERR "uh-oh! used pa while discarding\n");
4035 schedule_timeout_uninterruptible(HZ);
4039 if (pa->pa_deleted == 0) {
4041 spin_unlock(&pa->pa_lock);
4042 list_del_rcu(&pa->pa_inode_list);
4043 list_add(&pa->u.pa_tmp_list, &list);
4047 /* someone is deleting pa right now */
4048 spin_unlock(&pa->pa_lock);
4049 spin_unlock(&ei->i_prealloc_lock);
4051 /* we have to wait here because pa_deleted
4052 * doesn't mean pa is already unlinked from
4053 * the list. as we might be called from
4054 * ->clear_inode() the inode will get freed
4055 * and concurrent thread which is unlinking
4056 * pa from inode's list may access already
4057 * freed memory, bad-bad-bad */
4059 /* XXX: if this happens too often, we can
4060 * add a flag to force wait only in case
4061 * of ->clear_inode(), but not in case of
4062 * regular truncate */
4063 schedule_timeout_uninterruptible(HZ);
4066 spin_unlock(&ei->i_prealloc_lock);
4068 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4069 BUG_ON(pa->pa_type != MB_INODE_PA);
4070 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
4072 err = ext4_mb_load_buddy(sb, group, &e4b);
4074 ext4_error(sb, __func__, "Error in loading buddy "
4075 "information for %u", group);
4079 bitmap_bh = ext4_read_block_bitmap(sb, group);
4080 if (bitmap_bh == NULL) {
4081 ext4_error(sb, __func__, "Error in reading block "
4082 "bitmap for %u", group);
4083 ext4_mb_release_desc(&e4b);
4087 ext4_lock_group(sb, group);
4088 list_del(&pa->pa_group_list);
4089 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
4090 ext4_unlock_group(sb, group);
4092 ext4_mb_release_desc(&e4b);
4095 list_del(&pa->u.pa_tmp_list);
4096 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4099 kmem_cache_free(ext4_ac_cachep, ac);
4103 * finds all preallocated spaces and return blocks being freed to them
4104 * if preallocated space becomes full (no block is used from the space)
4105 * then the function frees space in buddy
4106 * XXX: at the moment, truncate (which is the only way to free blocks)
4107 * discards all preallocations
4109 static void ext4_mb_return_to_preallocation(struct inode *inode,
4110 struct ext4_buddy *e4b,
4111 sector_t block, int count)
4113 BUG_ON(!list_empty(&EXT4_I(inode)->i_prealloc_list));
4116 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4118 struct super_block *sb = ac->ac_sb;
4119 ext4_group_t ngroups, i;
4121 printk(KERN_ERR "EXT4-fs: Can't allocate:"
4122 " Allocation context details:\n");
4123 printk(KERN_ERR "EXT4-fs: status %d flags %d\n",
4124 ac->ac_status, ac->ac_flags);
4125 printk(KERN_ERR "EXT4-fs: orig %lu/%lu/%lu@%lu, goal %lu/%lu/%lu@%lu, "
4126 "best %lu/%lu/%lu@%lu cr %d\n",
4127 (unsigned long)ac->ac_o_ex.fe_group,
4128 (unsigned long)ac->ac_o_ex.fe_start,
4129 (unsigned long)ac->ac_o_ex.fe_len,
4130 (unsigned long)ac->ac_o_ex.fe_logical,
4131 (unsigned long)ac->ac_g_ex.fe_group,
4132 (unsigned long)ac->ac_g_ex.fe_start,
4133 (unsigned long)ac->ac_g_ex.fe_len,
4134 (unsigned long)ac->ac_g_ex.fe_logical,
4135 (unsigned long)ac->ac_b_ex.fe_group,
4136 (unsigned long)ac->ac_b_ex.fe_start,
4137 (unsigned long)ac->ac_b_ex.fe_len,
4138 (unsigned long)ac->ac_b_ex.fe_logical,
4139 (int)ac->ac_criteria);
4140 printk(KERN_ERR "EXT4-fs: %lu scanned, %d found\n", ac->ac_ex_scanned,
4142 printk(KERN_ERR "EXT4-fs: groups: \n");
4143 ngroups = ext4_get_groups_count(sb);
4144 for (i = 0; i < ngroups; i++) {
4145 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4146 struct ext4_prealloc_space *pa;
4147 ext4_grpblk_t start;
4148 struct list_head *cur;
4149 ext4_lock_group(sb, i);
4150 list_for_each(cur, &grp->bb_prealloc_list) {
4151 pa = list_entry(cur, struct ext4_prealloc_space,
4153 spin_lock(&pa->pa_lock);
4154 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4156 spin_unlock(&pa->pa_lock);
4157 printk(KERN_ERR "PA:%lu:%d:%u \n", i,
4160 ext4_unlock_group(sb, i);
4162 if (grp->bb_free == 0)
4164 printk(KERN_ERR "%lu: %d/%d \n",
4165 i, grp->bb_free, grp->bb_fragments);
4167 printk(KERN_ERR "\n");
4170 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4177 * We use locality group preallocation for small size file. The size of the
4178 * file is determined by the current size or the resulting size after
4179 * allocation which ever is larger
4181 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4183 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4185 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4186 int bsbits = ac->ac_sb->s_blocksize_bits;
4189 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4192 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
4193 isize = i_size_read(ac->ac_inode) >> bsbits;
4194 size = max(size, isize);
4196 /* don't use group allocation for large files */
4197 if (size >= sbi->s_mb_stream_request)
4200 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4203 BUG_ON(ac->ac_lg != NULL);
4205 * locality group prealloc space are per cpu. The reason for having
4206 * per cpu locality group is to reduce the contention between block
4207 * request from multiple CPUs.
4209 ac->ac_lg = per_cpu_ptr(sbi->s_locality_groups, raw_smp_processor_id());
4211 /* we're going to use group allocation */
4212 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4214 /* serialize all allocations in the group */
4215 mutex_lock(&ac->ac_lg->lg_mutex);
4218 static noinline_for_stack int
4219 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4220 struct ext4_allocation_request *ar)
4222 struct super_block *sb = ar->inode->i_sb;
4223 struct ext4_sb_info *sbi = EXT4_SB(sb);
4224 struct ext4_super_block *es = sbi->s_es;
4228 ext4_grpblk_t block;
4230 /* we can't allocate > group size */
4233 /* just a dirty hack to filter too big requests */
4234 if (len >= EXT4_BLOCKS_PER_GROUP(sb) - 10)
4235 len = EXT4_BLOCKS_PER_GROUP(sb) - 10;
4237 /* start searching from the goal */
4239 if (goal < le32_to_cpu(es->s_first_data_block) ||
4240 goal >= ext4_blocks_count(es))
4241 goal = le32_to_cpu(es->s_first_data_block);
4242 ext4_get_group_no_and_offset(sb, goal, &group, &block);
4244 /* set up allocation goals */
4245 ac->ac_b_ex.fe_logical = ar->logical;
4246 ac->ac_b_ex.fe_group = 0;
4247 ac->ac_b_ex.fe_start = 0;
4248 ac->ac_b_ex.fe_len = 0;
4249 ac->ac_status = AC_STATUS_CONTINUE;
4250 ac->ac_groups_scanned = 0;
4251 ac->ac_ex_scanned = 0;
4254 ac->ac_inode = ar->inode;
4255 ac->ac_o_ex.fe_logical = ar->logical;
4256 ac->ac_o_ex.fe_group = group;
4257 ac->ac_o_ex.fe_start = block;
4258 ac->ac_o_ex.fe_len = len;
4259 ac->ac_g_ex.fe_logical = ar->logical;
4260 ac->ac_g_ex.fe_group = group;
4261 ac->ac_g_ex.fe_start = block;
4262 ac->ac_g_ex.fe_len = len;
4263 ac->ac_f_ex.fe_len = 0;
4264 ac->ac_flags = ar->flags;
4266 ac->ac_criteria = 0;
4268 ac->ac_bitmap_page = NULL;
4269 ac->ac_buddy_page = NULL;
4270 ac->alloc_semp = NULL;
4273 /* we have to define context: we'll we work with a file or
4274 * locality group. this is a policy, actually */
4275 ext4_mb_group_or_file(ac);
4277 mb_debug("init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4278 "left: %u/%u, right %u/%u to %swritable\n",
4279 (unsigned) ar->len, (unsigned) ar->logical,
4280 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4281 (unsigned) ar->lleft, (unsigned) ar->pleft,
4282 (unsigned) ar->lright, (unsigned) ar->pright,
4283 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4288 static noinline_for_stack void
4289 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4290 struct ext4_locality_group *lg,
4291 int order, int total_entries)
4293 ext4_group_t group = 0;
4294 struct ext4_buddy e4b;
4295 struct list_head discard_list;
4296 struct ext4_prealloc_space *pa, *tmp;
4297 struct ext4_allocation_context *ac;
4299 mb_debug("discard locality group preallocation\n");
4301 INIT_LIST_HEAD(&discard_list);
4302 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4304 spin_lock(&lg->lg_prealloc_lock);
4305 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4307 spin_lock(&pa->pa_lock);
4308 if (atomic_read(&pa->pa_count)) {
4310 * This is the pa that we just used
4311 * for block allocation. So don't
4314 spin_unlock(&pa->pa_lock);
4317 if (pa->pa_deleted) {
4318 spin_unlock(&pa->pa_lock);
4321 /* only lg prealloc space */
4322 BUG_ON(pa->pa_type != MB_GROUP_PA);
4324 /* seems this one can be freed ... */
4326 spin_unlock(&pa->pa_lock);
4328 list_del_rcu(&pa->pa_inode_list);
4329 list_add(&pa->u.pa_tmp_list, &discard_list);
4332 if (total_entries <= 5) {
4334 * we want to keep only 5 entries
4335 * allowing it to grow to 8. This
4336 * mak sure we don't call discard
4337 * soon for this list.
4342 spin_unlock(&lg->lg_prealloc_lock);
4344 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4346 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
4347 if (ext4_mb_load_buddy(sb, group, &e4b)) {
4348 ext4_error(sb, __func__, "Error in loading buddy "
4349 "information for %u", group);
4352 ext4_lock_group(sb, group);
4353 list_del(&pa->pa_group_list);
4354 ext4_mb_release_group_pa(&e4b, pa, ac);
4355 ext4_unlock_group(sb, group);
4357 ext4_mb_release_desc(&e4b);
4358 list_del(&pa->u.pa_tmp_list);
4359 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4362 kmem_cache_free(ext4_ac_cachep, ac);
4366 * We have incremented pa_count. So it cannot be freed at this
4367 * point. Also we hold lg_mutex. So no parallel allocation is
4368 * possible from this lg. That means pa_free cannot be updated.
4370 * A parallel ext4_mb_discard_group_preallocations is possible.
4371 * which can cause the lg_prealloc_list to be updated.
4374 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4376 int order, added = 0, lg_prealloc_count = 1;
4377 struct super_block *sb = ac->ac_sb;
4378 struct ext4_locality_group *lg = ac->ac_lg;
4379 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4381 order = fls(pa->pa_free) - 1;
4382 if (order > PREALLOC_TB_SIZE - 1)
4383 /* The max size of hash table is PREALLOC_TB_SIZE */
4384 order = PREALLOC_TB_SIZE - 1;
4385 /* Add the prealloc space to lg */
4387 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4389 spin_lock(&tmp_pa->pa_lock);
4390 if (tmp_pa->pa_deleted) {
4391 spin_unlock(&tmp_pa->pa_lock);
4394 if (!added && pa->pa_free < tmp_pa->pa_free) {
4395 /* Add to the tail of the previous entry */
4396 list_add_tail_rcu(&pa->pa_inode_list,
4397 &tmp_pa->pa_inode_list);
4400 * we want to count the total
4401 * number of entries in the list
4404 spin_unlock(&tmp_pa->pa_lock);
4405 lg_prealloc_count++;
4408 list_add_tail_rcu(&pa->pa_inode_list,
4409 &lg->lg_prealloc_list[order]);
4412 /* Now trim the list to be not more than 8 elements */
4413 if (lg_prealloc_count > 8) {
4414 ext4_mb_discard_lg_preallocations(sb, lg,
4415 order, lg_prealloc_count);
4422 * release all resource we used in allocation
4424 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4426 struct ext4_prealloc_space *pa = ac->ac_pa;
4428 if (pa->pa_type == MB_GROUP_PA) {
4429 /* see comment in ext4_mb_use_group_pa() */
4430 spin_lock(&pa->pa_lock);
4431 pa->pa_pstart += ac->ac_b_ex.fe_len;
4432 pa->pa_lstart += ac->ac_b_ex.fe_len;
4433 pa->pa_free -= ac->ac_b_ex.fe_len;
4434 pa->pa_len -= ac->ac_b_ex.fe_len;
4435 spin_unlock(&pa->pa_lock);
4439 up_read(ac->alloc_semp);
4442 * We want to add the pa to the right bucket.
4443 * Remove it from the list and while adding
4444 * make sure the list to which we are adding
4445 * doesn't grow big. We need to release
4446 * alloc_semp before calling ext4_mb_add_n_trim()
4448 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4449 spin_lock(pa->pa_obj_lock);
4450 list_del_rcu(&pa->pa_inode_list);
4451 spin_unlock(pa->pa_obj_lock);
4452 ext4_mb_add_n_trim(ac);
4454 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4456 if (ac->ac_bitmap_page)
4457 page_cache_release(ac->ac_bitmap_page);
4458 if (ac->ac_buddy_page)
4459 page_cache_release(ac->ac_buddy_page);
4460 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4461 mutex_unlock(&ac->ac_lg->lg_mutex);
4462 ext4_mb_collect_stats(ac);
4466 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4468 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4472 trace_mark(ext4_mb_discard_preallocations, "dev %s needed %d",
4474 for (i = 0; i < ngroups && needed > 0; i++) {
4475 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4484 * Main entry point into mballoc to allocate blocks
4485 * it tries to use preallocation first, then falls back
4486 * to usual allocation
4488 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4489 struct ext4_allocation_request *ar, int *errp)
4492 struct ext4_allocation_context *ac = NULL;
4493 struct ext4_sb_info *sbi;
4494 struct super_block *sb;
4495 ext4_fsblk_t block = 0;
4496 unsigned int inquota = 0;
4497 unsigned int reserv_blks = 0;
4499 sb = ar->inode->i_sb;
4502 trace_mark(ext4_request_blocks, "dev %s flags %u len %u ino %lu "
4503 "lblk %llu goal %llu lleft %llu lright %llu "
4504 "pleft %llu pright %llu ",
4505 sb->s_id, ar->flags, ar->len,
4506 ar->inode ? ar->inode->i_ino : 0,
4507 (unsigned long long) ar->logical,
4508 (unsigned long long) ar->goal,
4509 (unsigned long long) ar->lleft,
4510 (unsigned long long) ar->lright,
4511 (unsigned long long) ar->pleft,
4512 (unsigned long long) ar->pright);
4515 * For delayed allocation, we could skip the ENOSPC and
4516 * EDQUOT check, as blocks and quotas have been already
4517 * reserved when data being copied into pagecache.
4519 if (EXT4_I(ar->inode)->i_delalloc_reserved_flag)
4520 ar->flags |= EXT4_MB_DELALLOC_RESERVED;
4522 /* Without delayed allocation we need to verify
4523 * there is enough free blocks to do block allocation
4524 * and verify allocation doesn't exceed the quota limits.
4526 while (ar->len && ext4_claim_free_blocks(sbi, ar->len)) {
4527 /* let others to free the space */
4529 ar->len = ar->len >> 1;
4535 reserv_blks = ar->len;
4536 while (ar->len && vfs_dq_alloc_block(ar->inode, ar->len)) {
4537 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4547 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4554 *errp = ext4_mb_initialize_context(ac, ar);
4560 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4561 if (!ext4_mb_use_preallocated(ac)) {
4562 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4563 ext4_mb_normalize_request(ac, ar);
4565 /* allocate space in core */
4566 ext4_mb_regular_allocator(ac);
4568 /* as we've just preallocated more space than
4569 * user requested orinally, we store allocated
4570 * space in a special descriptor */
4571 if (ac->ac_status == AC_STATUS_FOUND &&
4572 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4573 ext4_mb_new_preallocation(ac);
4575 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4576 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_blks);
4577 if (*errp == -EAGAIN) {
4579 * drop the reference that we took
4580 * in ext4_mb_use_best_found
4582 ext4_mb_release_context(ac);
4583 ac->ac_b_ex.fe_group = 0;
4584 ac->ac_b_ex.fe_start = 0;
4585 ac->ac_b_ex.fe_len = 0;
4586 ac->ac_status = AC_STATUS_CONTINUE;
4589 ac->ac_b_ex.fe_len = 0;
4591 ext4_mb_show_ac(ac);
4593 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4594 ar->len = ac->ac_b_ex.fe_len;
4597 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4601 ac->ac_b_ex.fe_len = 0;
4603 ext4_mb_show_ac(ac);
4606 ext4_mb_release_context(ac);
4609 kmem_cache_free(ext4_ac_cachep, ac);
4611 if (inquota && ar->len < inquota)
4612 vfs_dq_free_block(ar->inode, inquota - ar->len);
4615 if (!EXT4_I(ar->inode)->i_delalloc_reserved_flag)
4616 /* release all the reserved blocks if non delalloc */
4617 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
4621 trace_mark(ext4_allocate_blocks,
4622 "dev %s block %llu flags %u len %u ino %lu "
4623 "logical %llu goal %llu lleft %llu lright %llu "
4624 "pleft %llu pright %llu ",
4625 sb->s_id, (unsigned long long) block,
4626 ar->flags, ar->len, ar->inode ? ar->inode->i_ino : 0,
4627 (unsigned long long) ar->logical,
4628 (unsigned long long) ar->goal,
4629 (unsigned long long) ar->lleft,
4630 (unsigned long long) ar->lright,
4631 (unsigned long long) ar->pleft,
4632 (unsigned long long) ar->pright);
4638 * We can merge two free data extents only if the physical blocks
4639 * are contiguous, AND the extents were freed by the same transaction,
4640 * AND the blocks are associated with the same group.
4642 static int can_merge(struct ext4_free_data *entry1,
4643 struct ext4_free_data *entry2)
4645 if ((entry1->t_tid == entry2->t_tid) &&
4646 (entry1->group == entry2->group) &&
4647 ((entry1->start_blk + entry1->count) == entry2->start_blk))
4652 static noinline_for_stack int
4653 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4654 struct ext4_free_data *new_entry)
4656 ext4_grpblk_t block;
4657 struct ext4_free_data *entry;
4658 struct ext4_group_info *db = e4b->bd_info;
4659 struct super_block *sb = e4b->bd_sb;
4660 struct ext4_sb_info *sbi = EXT4_SB(sb);
4661 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4662 struct rb_node *parent = NULL, *new_node;
4664 BUG_ON(!ext4_handle_valid(handle));
4665 BUG_ON(e4b->bd_bitmap_page == NULL);
4666 BUG_ON(e4b->bd_buddy_page == NULL);
4668 new_node = &new_entry->node;
4669 block = new_entry->start_blk;
4672 /* first free block exent. We need to
4673 protect buddy cache from being freed,
4674 * otherwise we'll refresh it from
4675 * on-disk bitmap and lose not-yet-available
4677 page_cache_get(e4b->bd_buddy_page);
4678 page_cache_get(e4b->bd_bitmap_page);
4682 entry = rb_entry(parent, struct ext4_free_data, node);
4683 if (block < entry->start_blk)
4685 else if (block >= (entry->start_blk + entry->count))
4686 n = &(*n)->rb_right;
4688 ext4_grp_locked_error(sb, e4b->bd_group, __func__,
4689 "Double free of blocks %d (%d %d)",
4690 block, entry->start_blk, entry->count);
4695 rb_link_node(new_node, parent, n);
4696 rb_insert_color(new_node, &db->bb_free_root);
4698 /* Now try to see the extent can be merged to left and right */
4699 node = rb_prev(new_node);
4701 entry = rb_entry(node, struct ext4_free_data, node);
4702 if (can_merge(entry, new_entry)) {
4703 new_entry->start_blk = entry->start_blk;
4704 new_entry->count += entry->count;
4705 rb_erase(node, &(db->bb_free_root));
4706 spin_lock(&sbi->s_md_lock);
4707 list_del(&entry->list);
4708 spin_unlock(&sbi->s_md_lock);
4709 kmem_cache_free(ext4_free_ext_cachep, entry);
4713 node = rb_next(new_node);
4715 entry = rb_entry(node, struct ext4_free_data, node);
4716 if (can_merge(new_entry, entry)) {
4717 new_entry->count += entry->count;
4718 rb_erase(node, &(db->bb_free_root));
4719 spin_lock(&sbi->s_md_lock);
4720 list_del(&entry->list);
4721 spin_unlock(&sbi->s_md_lock);
4722 kmem_cache_free(ext4_free_ext_cachep, entry);
4725 /* Add the extent to transaction's private list */
4726 spin_lock(&sbi->s_md_lock);
4727 list_add(&new_entry->list, &handle->h_transaction->t_private_list);
4728 spin_unlock(&sbi->s_md_lock);
4733 * Main entry point into mballoc to free blocks
4735 void ext4_mb_free_blocks(handle_t *handle, struct inode *inode,
4736 unsigned long block, unsigned long count,
4737 int metadata, unsigned long *freed)
4739 struct buffer_head *bitmap_bh = NULL;
4740 struct super_block *sb = inode->i_sb;
4741 struct ext4_allocation_context *ac = NULL;
4742 struct ext4_group_desc *gdp;
4743 struct ext4_super_block *es;
4744 unsigned int overflow;
4746 struct buffer_head *gd_bh;
4747 ext4_group_t block_group;
4748 struct ext4_sb_info *sbi;
4749 struct ext4_buddy e4b;
4756 es = EXT4_SB(sb)->s_es;
4757 if (block < le32_to_cpu(es->s_first_data_block) ||
4758 block + count < block ||
4759 block + count > ext4_blocks_count(es)) {
4760 ext4_error(sb, __func__,
4761 "Freeing blocks not in datazone - "
4762 "block = %lu, count = %lu", block, count);
4766 ext4_debug("freeing block %lu\n", block);
4767 trace_mark(ext4_free_blocks,
4768 "dev %s block %llu count %lu metadata %d ino %lu",
4769 sb->s_id, (unsigned long long) block, count, metadata,
4770 inode ? inode->i_ino : 0);
4772 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4774 ac->ac_op = EXT4_MB_HISTORY_FREE;
4775 ac->ac_inode = inode;
4781 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4784 * Check to see if we are freeing blocks across a group
4787 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4788 overflow = bit + count - EXT4_BLOCKS_PER_GROUP(sb);
4791 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4796 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4802 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4803 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4804 in_range(block, ext4_inode_table(sb, gdp),
4805 EXT4_SB(sb)->s_itb_per_group) ||
4806 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4807 EXT4_SB(sb)->s_itb_per_group)) {
4809 ext4_error(sb, __func__,
4810 "Freeing blocks in system zone - "
4811 "Block = %lu, count = %lu", block, count);
4812 /* err = 0. ext4_std_error should be a no op */
4816 BUFFER_TRACE(bitmap_bh, "getting write access");
4817 err = ext4_journal_get_write_access(handle, bitmap_bh);
4822 * We are about to modify some metadata. Call the journal APIs
4823 * to unshare ->b_data if a currently-committing transaction is
4826 BUFFER_TRACE(gd_bh, "get_write_access");
4827 err = ext4_journal_get_write_access(handle, gd_bh);
4830 #ifdef AGGRESSIVE_CHECK
4833 for (i = 0; i < count; i++)
4834 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4838 ac->ac_b_ex.fe_group = block_group;
4839 ac->ac_b_ex.fe_start = bit;
4840 ac->ac_b_ex.fe_len = count;
4841 ext4_mb_store_history(ac);
4844 err = ext4_mb_load_buddy(sb, block_group, &e4b);
4847 if (metadata && ext4_handle_valid(handle)) {
4848 struct ext4_free_data *new_entry;
4850 * blocks being freed are metadata. these blocks shouldn't
4851 * be used until this transaction is committed
4853 new_entry = kmem_cache_alloc(ext4_free_ext_cachep, GFP_NOFS);
4854 new_entry->start_blk = bit;
4855 new_entry->group = block_group;
4856 new_entry->count = count;
4857 new_entry->t_tid = handle->h_transaction->t_tid;
4858 ext4_lock_group(sb, block_group);
4859 mb_clear_bits(sb_bgl_lock(sbi, block_group), bitmap_bh->b_data,
4861 ext4_mb_free_metadata(handle, &e4b, new_entry);
4862 ext4_unlock_group(sb, block_group);
4864 ext4_lock_group(sb, block_group);
4865 /* need to update group_info->bb_free and bitmap
4866 * with group lock held. generate_buddy look at
4867 * them with group lock_held
4869 mb_clear_bits(sb_bgl_lock(sbi, block_group), bitmap_bh->b_data,
4871 mb_free_blocks(inode, &e4b, bit, count);
4872 ext4_mb_return_to_preallocation(inode, &e4b, block, count);
4873 ext4_unlock_group(sb, block_group);
4876 spin_lock(sb_bgl_lock(sbi, block_group));
4877 ret = ext4_free_blks_count(sb, gdp) + count;
4878 ext4_free_blks_set(sb, gdp, ret);
4879 gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4880 spin_unlock(sb_bgl_lock(sbi, block_group));
4881 percpu_counter_add(&sbi->s_freeblocks_counter, count);
4883 if (sbi->s_log_groups_per_flex) {
4884 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4885 atomic_add(count, &sbi->s_flex_groups[flex_group].free_blocks);
4888 ext4_mb_release_desc(&e4b);
4892 /* We dirtied the bitmap block */
4893 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4894 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4896 /* And the group descriptor block */
4897 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4898 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4902 if (overflow && !err) {
4911 ext4_std_error(sb, err);
4913 kmem_cache_free(ext4_ac_cachep, ac);