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 group
50 * preallocation or inode preallocation depending on the size file. The
51 * size of the file could be the resulting file size we would have after
52 * allocation or the current file size which ever is larger. If the size is
53 * less that sbi->s_mb_stream_request we select the group
54 * preallocation. The default value of s_mb_stream_request is 16
55 * blocks. This can also be tuned via
56 * /proc/fs/ext4/<partition>/stream_req. The value is represented in terms
57 * of number of blocks.
59 * The main motivation for having small file use group preallocation is to
60 * ensure that we have small file closer in the disk.
62 * First stage the allocator looks at the inode prealloc list
63 * ext4_inode_info->i_prealloc_list contain list of prealloc spaces for
64 * this particular inode. The inode prealloc space is represented as:
66 * pa_lstart -> the logical start block for this prealloc space
67 * pa_pstart -> the physical start block for this prealloc space
68 * pa_len -> lenght for this prealloc space
69 * pa_free -> free space available in this prealloc space
71 * The inode preallocation space is used looking at the _logical_ start
72 * block. If only the logical file block falls within the range of prealloc
73 * space we will consume the particular prealloc space. This make sure that
74 * that the we have contiguous physical blocks representing the file blocks
76 * The important thing to be noted in case of inode prealloc space is that
77 * we don't modify the values associated to inode prealloc space except
80 * If we are not able to find blocks in the inode prealloc space and if we
81 * have the group allocation flag set then we look at the locality group
82 * prealloc space. These are per CPU prealloc list repreasented as
84 * ext4_sb_info.s_locality_groups[smp_processor_id()]
86 * The reason for having a per cpu locality group is to reduce the contention
87 * between CPUs. It is possible to get scheduled at this point.
89 * The locality group prealloc space is used looking at whether we have
90 * enough free space (pa_free) withing the prealloc space.
92 * If we can't allocate blocks via inode prealloc or/and locality group
93 * prealloc then we look at the buddy cache. The buddy cache is represented
94 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
95 * mapped to the buddy and bitmap information regarding different
96 * groups. The buddy information is attached to buddy cache inode so that
97 * we can access them through the page cache. The information regarding
98 * each group is loaded via ext4_mb_load_buddy. The information involve
99 * block bitmap and buddy information. The information are stored in the
103 * [ group 0 buddy][ group 0 bitmap] [group 1][ group 1]...
106 * one block each for bitmap and buddy information. So for each group we
107 * take up 2 blocks. A page can contain blocks_per_page (PAGE_CACHE_SIZE /
108 * blocksize) blocks. So it can have information regarding groups_per_page
109 * which is blocks_per_page/2
111 * The buddy cache inode is not stored on disk. The inode is thrown
112 * away when the filesystem is unmounted.
114 * We look for count number of blocks in the buddy cache. If we were able
115 * to locate that many free blocks we return with additional information
116 * regarding rest of the contiguous physical block available
118 * Before allocating blocks via buddy cache we normalize the request
119 * blocks. This ensure we ask for more blocks that we needed. The extra
120 * blocks that we get after allocation is added to the respective prealloc
121 * list. In case of inode preallocation we follow a list of heuristics
122 * based on file size. This can be found in ext4_mb_normalize_request. If
123 * we are doing a group prealloc we try to normalize the request to
124 * sbi->s_mb_group_prealloc. Default value of s_mb_group_prealloc is set to
125 * 512 blocks. This can be tuned via
126 * /proc/fs/ext4/<partition/group_prealloc. The value is represented in
127 * terms of number of blocks. If we have mounted the file system with -O
128 * stripe=<value> option the group prealloc request is normalized to the
129 * stripe value (sbi->s_stripe)
131 * The regular allocator(using the buddy cache) support few tunables.
133 * /proc/fs/ext4/<partition>/min_to_scan
134 * /proc/fs/ext4/<partition>/max_to_scan
135 * /proc/fs/ext4/<partition>/order2_req
137 * The regular allocator use buddy scan only if the request len is power of
138 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
139 * value of s_mb_order2_reqs can be tuned via
140 * /proc/fs/ext4/<partition>/order2_req. If the request len is equal to
141 * stripe size (sbi->s_stripe), we try to search for contigous block in
142 * stripe size. This should result in better allocation on RAID setup. If
143 * not we search in the specific group using bitmap for best extents. The
144 * tunable min_to_scan and max_to_scan controll the behaviour here.
145 * min_to_scan indicate how long the mballoc __must__ look for a best
146 * extent and max_to_scanindicate how long the mballoc __can__ look for a
147 * best extent in the found extents. Searching for the blocks starts with
148 * the group specified as the goal value in allocation context via
149 * ac_g_ex. Each group is first checked based on the criteria whether it
150 * can used for allocation. ext4_mb_good_group explains how the groups are
153 * Both the prealloc space are getting populated as above. So for the first
154 * request we will hit the buddy cache which will result in this prealloc
155 * space getting filled. The prealloc space is then later used for the
156 * subsequent request.
160 * mballoc operates on the following data:
162 * - in-core buddy (actually includes buddy and bitmap)
163 * - preallocation descriptors (PAs)
165 * there are two types of preallocations:
167 * assiged to specific inode and can be used for this inode only.
168 * it describes part of inode's space preallocated to specific
169 * physical blocks. any block from that preallocated can be used
170 * independent. the descriptor just tracks number of blocks left
171 * unused. so, before taking some block from descriptor, one must
172 * make sure corresponded logical block isn't allocated yet. this
173 * also means that freeing any block within descriptor's range
174 * must discard all preallocated blocks.
176 * assigned to specific locality group which does not translate to
177 * permanent set of inodes: inode can join and leave group. space
178 * from this type of preallocation can be used for any inode. thus
179 * it's consumed from the beginning to the end.
181 * relation between them can be expressed as:
182 * in-core buddy = on-disk bitmap + preallocation descriptors
184 * this mean blocks mballoc considers used are:
185 * - allocated blocks (persistent)
186 * - preallocated blocks (non-persistent)
188 * consistency in mballoc world means that at any time a block is either
189 * free or used in ALL structures. notice: "any time" should not be read
190 * literally -- time is discrete and delimited by locks.
192 * to keep it simple, we don't use block numbers, instead we count number of
193 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
195 * all operations can be expressed as:
196 * - init buddy: buddy = on-disk + PAs
197 * - new PA: buddy += N; PA = N
198 * - use inode PA: on-disk += N; PA -= N
199 * - discard inode PA buddy -= on-disk - PA; PA = 0
200 * - use locality group PA on-disk += N; PA -= N
201 * - discard locality group PA buddy -= PA; PA = 0
202 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
203 * is used in real operation because we can't know actual used
204 * bits from PA, only from on-disk bitmap
206 * if we follow this strict logic, then all operations above should be atomic.
207 * given some of them can block, we'd have to use something like semaphores
208 * killing performance on high-end SMP hardware. let's try to relax it using
209 * the following knowledge:
210 * 1) if buddy is referenced, it's already initialized
211 * 2) while block is used in buddy and the buddy is referenced,
212 * nobody can re-allocate that block
213 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
214 * bit set and PA claims same block, it's OK. IOW, one can set bit in
215 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
218 * so, now we're building a concurrency table:
221 * blocks for PA are allocated in the buddy, buddy must be referenced
222 * until PA is linked to allocation group to avoid concurrent buddy init
224 * we need to make sure that either on-disk bitmap or PA has uptodate data
225 * given (3) we care that PA-=N operation doesn't interfere with init
227 * the simplest way would be to have buddy initialized by the discard
228 * - use locality group PA
229 * again PA-=N must be serialized with init
230 * - discard locality group PA
231 * the simplest way would be to have buddy initialized by the discard
234 * i_data_sem serializes them
236 * discard process must wait until PA isn't used by another process
237 * - use locality group PA
238 * some mutex should serialize them
239 * - discard locality group PA
240 * discard process must wait until PA isn't used by another process
243 * i_data_sem or another mutex should serializes them
245 * discard process must wait until PA isn't used by another process
246 * - use locality group PA
247 * nothing wrong here -- they're different PAs covering different blocks
248 * - discard locality group PA
249 * discard process must wait until PA isn't used by another process
251 * now we're ready to make few consequences:
252 * - PA is referenced and while it is no discard is possible
253 * - PA is referenced until block isn't marked in on-disk bitmap
254 * - PA changes only after on-disk bitmap
255 * - discard must not compete with init. either init is done before
256 * any discard or they're serialized somehow
257 * - buddy init as sum of on-disk bitmap and PAs is done atomically
259 * a special case when we've used PA to emptiness. no need to modify buddy
260 * in this case, but we should care about concurrent init
265 * Logic in few words:
270 * mark bits in on-disk bitmap
273 * - use preallocation:
274 * find proper PA (per-inode or group)
276 * mark bits in on-disk bitmap
282 * mark bits in on-disk bitmap
285 * - discard preallocations in group:
287 * move them onto local list
288 * load on-disk bitmap
290 * remove PA from object (inode or locality group)
291 * mark free blocks in-core
293 * - discard inode's preallocations:
300 * - bitlock on a group (group)
301 * - object (inode/locality) (object)
312 * - release consumed pa:
317 * - generate in-core bitmap:
321 * - discard all for given object (inode, locality group):
326 * - discard all for given group:
334 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
336 #if BITS_PER_LONG == 64
337 *bit += ((unsigned long) addr & 7UL) << 3;
338 addr = (void *) ((unsigned long) addr & ~7UL);
339 #elif BITS_PER_LONG == 32
340 *bit += ((unsigned long) addr & 3UL) << 3;
341 addr = (void *) ((unsigned long) addr & ~3UL);
343 #error "how many bits you are?!"
348 static inline int mb_test_bit(int bit, void *addr)
351 * ext4_test_bit on architecture like powerpc
352 * needs unsigned long aligned address
354 addr = mb_correct_addr_and_bit(&bit, addr);
355 return ext4_test_bit(bit, addr);
358 static inline void mb_set_bit(int bit, void *addr)
360 addr = mb_correct_addr_and_bit(&bit, addr);
361 ext4_set_bit(bit, addr);
364 static inline void mb_set_bit_atomic(spinlock_t *lock, int bit, void *addr)
366 addr = mb_correct_addr_and_bit(&bit, addr);
367 ext4_set_bit_atomic(lock, bit, addr);
370 static inline void mb_clear_bit(int bit, void *addr)
372 addr = mb_correct_addr_and_bit(&bit, addr);
373 ext4_clear_bit(bit, addr);
376 static inline void mb_clear_bit_atomic(spinlock_t *lock, int bit, void *addr)
378 addr = mb_correct_addr_and_bit(&bit, addr);
379 ext4_clear_bit_atomic(lock, bit, addr);
382 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
384 int fix = 0, ret, tmpmax;
385 addr = mb_correct_addr_and_bit(&fix, addr);
389 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
395 static inline int mb_find_next_bit(void *addr, int max, int start)
397 int fix = 0, ret, tmpmax;
398 addr = mb_correct_addr_and_bit(&fix, addr);
402 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
408 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
412 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
415 if (order > e4b->bd_blkbits + 1) {
420 /* at order 0 we see each particular block */
421 *max = 1 << (e4b->bd_blkbits + 3);
423 return EXT4_MB_BITMAP(e4b);
425 bb = EXT4_MB_BUDDY(e4b) + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
426 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
432 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
433 int first, int count)
436 struct super_block *sb = e4b->bd_sb;
438 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
440 BUG_ON(!ext4_is_group_locked(sb, e4b->bd_group));
441 for (i = 0; i < count; i++) {
442 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
443 ext4_fsblk_t blocknr;
444 blocknr = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb);
445 blocknr += first + i;
447 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
449 ext4_error(sb, __func__, "double-free of inode"
450 " %lu's block %llu(bit %u in group %lu)\n",
451 inode ? inode->i_ino : 0, blocknr,
452 first + i, e4b->bd_group);
454 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
458 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
462 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
464 BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
465 for (i = 0; i < count; i++) {
466 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
467 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
471 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
473 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
474 unsigned char *b1, *b2;
476 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
477 b2 = (unsigned char *) bitmap;
478 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
479 if (b1[i] != b2[i]) {
480 printk("corruption in group %lu at byte %u(%u):"
481 " %x in copy != %x on disk/prealloc\n",
482 e4b->bd_group, i, i * 8, b1[i], b2[i]);
490 static inline void mb_free_blocks_double(struct inode *inode,
491 struct ext4_buddy *e4b, int first, int count)
495 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
496 int first, int count)
500 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
506 #ifdef AGGRESSIVE_CHECK
508 #define MB_CHECK_ASSERT(assert) \
512 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
513 function, file, line, # assert); \
518 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
519 const char *function, int line)
521 struct super_block *sb = e4b->bd_sb;
522 int order = e4b->bd_blkbits + 1;
529 struct ext4_group_info *grp;
532 struct list_head *cur;
536 if (!test_opt(sb, MBALLOC))
540 static int mb_check_counter;
541 if (mb_check_counter++ % 100 != 0)
546 buddy = mb_find_buddy(e4b, order, &max);
547 MB_CHECK_ASSERT(buddy);
548 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
549 MB_CHECK_ASSERT(buddy2);
550 MB_CHECK_ASSERT(buddy != buddy2);
551 MB_CHECK_ASSERT(max * 2 == max2);
554 for (i = 0; i < max; i++) {
556 if (mb_test_bit(i, buddy)) {
557 /* only single bit in buddy2 may be 1 */
558 if (!mb_test_bit(i << 1, buddy2)) {
560 mb_test_bit((i<<1)+1, buddy2));
561 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
563 mb_test_bit(i << 1, buddy2));
568 /* both bits in buddy2 must be 0 */
569 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
570 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
572 for (j = 0; j < (1 << order); j++) {
573 k = (i * (1 << order)) + j;
575 !mb_test_bit(k, EXT4_MB_BITMAP(e4b)));
579 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
584 buddy = mb_find_buddy(e4b, 0, &max);
585 for (i = 0; i < max; i++) {
586 if (!mb_test_bit(i, buddy)) {
587 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
595 /* check used bits only */
596 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
597 buddy2 = mb_find_buddy(e4b, j, &max2);
599 MB_CHECK_ASSERT(k < max2);
600 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
603 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
604 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
606 grp = ext4_get_group_info(sb, e4b->bd_group);
607 buddy = mb_find_buddy(e4b, 0, &max);
608 list_for_each(cur, &grp->bb_prealloc_list) {
609 ext4_group_t groupnr;
610 struct ext4_prealloc_space *pa;
611 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
612 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
613 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
614 for (i = 0; i < pa->pa_len; i++)
615 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
619 #undef MB_CHECK_ASSERT
620 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
621 __FILE__, __func__, __LINE__)
623 #define mb_check_buddy(e4b)
626 /* FIXME!! need more doc */
627 static void ext4_mb_mark_free_simple(struct super_block *sb,
628 void *buddy, unsigned first, int len,
629 struct ext4_group_info *grp)
631 struct ext4_sb_info *sbi = EXT4_SB(sb);
634 unsigned short chunk;
635 unsigned short border;
637 BUG_ON(len > EXT4_BLOCKS_PER_GROUP(sb));
639 border = 2 << sb->s_blocksize_bits;
642 /* find how many blocks can be covered since this position */
643 max = ffs(first | border) - 1;
645 /* find how many blocks of power 2 we need to mark */
652 /* mark multiblock chunks only */
653 grp->bb_counters[min]++;
655 mb_clear_bit(first >> min,
656 buddy + sbi->s_mb_offsets[min]);
663 static void ext4_mb_generate_buddy(struct super_block *sb,
664 void *buddy, void *bitmap, ext4_group_t group)
666 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
667 unsigned short max = EXT4_BLOCKS_PER_GROUP(sb);
668 unsigned short i = 0;
669 unsigned short first;
672 unsigned fragments = 0;
673 unsigned long long period = get_cycles();
675 /* initialize buddy from bitmap which is aggregation
676 * of on-disk bitmap and preallocations */
677 i = mb_find_next_zero_bit(bitmap, max, 0);
678 grp->bb_first_free = i;
682 i = mb_find_next_bit(bitmap, max, i);
686 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
688 grp->bb_counters[0]++;
690 i = mb_find_next_zero_bit(bitmap, max, i);
692 grp->bb_fragments = fragments;
694 if (free != grp->bb_free) {
695 ext4_error(sb, __func__,
696 "EXT4-fs: group %lu: %u blocks in bitmap, %u in gd\n",
697 group, free, grp->bb_free);
699 * If we intent to continue, we consider group descritor
700 * corrupt and update bb_free using bitmap value
705 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
707 period = get_cycles() - period;
708 spin_lock(&EXT4_SB(sb)->s_bal_lock);
709 EXT4_SB(sb)->s_mb_buddies_generated++;
710 EXT4_SB(sb)->s_mb_generation_time += period;
711 spin_unlock(&EXT4_SB(sb)->s_bal_lock);
714 /* The buddy information is attached the buddy cache inode
715 * for convenience. The information regarding each group
716 * is loaded via ext4_mb_load_buddy. The information involve
717 * block bitmap and buddy information. The information are
718 * stored in the inode as
721 * [ group 0 buddy][ group 0 bitmap] [group 1][ group 1]...
724 * one block each for bitmap and buddy information.
725 * So for each group we take up 2 blocks. A page can
726 * contain blocks_per_page (PAGE_CACHE_SIZE / blocksize) blocks.
727 * So it can have information regarding groups_per_page which
728 * is blocks_per_page/2
731 static int ext4_mb_init_cache(struct page *page, char *incore)
738 ext4_group_t first_group;
740 struct super_block *sb;
741 struct buffer_head *bhs;
742 struct buffer_head **bh;
747 mb_debug("init page %lu\n", page->index);
749 inode = page->mapping->host;
751 blocksize = 1 << inode->i_blkbits;
752 blocks_per_page = PAGE_CACHE_SIZE / blocksize;
754 groups_per_page = blocks_per_page >> 1;
755 if (groups_per_page == 0)
758 /* allocate buffer_heads to read bitmaps */
759 if (groups_per_page > 1) {
761 i = sizeof(struct buffer_head *) * groups_per_page;
762 bh = kzalloc(i, GFP_NOFS);
768 first_group = page->index * blocks_per_page / 2;
770 /* read all groups the page covers into the cache */
771 for (i = 0; i < groups_per_page; i++) {
772 struct ext4_group_desc *desc;
774 if (first_group + i >= EXT4_SB(sb)->s_groups_count)
778 desc = ext4_get_group_desc(sb, first_group + i, NULL);
783 bh[i] = sb_getblk(sb, ext4_block_bitmap(sb, desc));
787 if (bh_uptodate_or_lock(bh[i]))
790 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
791 ext4_init_block_bitmap(sb, bh[i],
792 first_group + i, desc);
793 set_buffer_uptodate(bh[i]);
794 unlock_buffer(bh[i]);
798 bh[i]->b_end_io = end_buffer_read_sync;
799 submit_bh(READ, bh[i]);
800 mb_debug("read bitmap for group %lu\n", first_group + i);
803 /* wait for I/O completion */
804 for (i = 0; i < groups_per_page && bh[i]; i++)
805 wait_on_buffer(bh[i]);
808 for (i = 0; i < groups_per_page && bh[i]; i++)
809 if (!buffer_uptodate(bh[i]))
812 first_block = page->index * blocks_per_page;
813 for (i = 0; i < blocks_per_page; i++) {
815 struct ext4_group_info *grinfo;
817 group = (first_block + i) >> 1;
818 if (group >= EXT4_SB(sb)->s_groups_count)
822 * data carry information regarding this
823 * particular group in the format specified
827 data = page_address(page) + (i * blocksize);
828 bitmap = bh[group - first_group]->b_data;
831 * We place the buddy block and bitmap block
834 if ((first_block + i) & 1) {
835 /* this is block of buddy */
836 BUG_ON(incore == NULL);
837 mb_debug("put buddy for group %u in page %lu/%x\n",
838 group, page->index, i * blocksize);
839 memset(data, 0xff, blocksize);
840 grinfo = ext4_get_group_info(sb, group);
841 grinfo->bb_fragments = 0;
842 memset(grinfo->bb_counters, 0,
843 sizeof(unsigned short)*(sb->s_blocksize_bits+2));
845 * incore got set to the group block bitmap below
847 ext4_mb_generate_buddy(sb, data, incore, group);
850 /* this is block of bitmap */
851 BUG_ON(incore != NULL);
852 mb_debug("put bitmap for group %u in page %lu/%x\n",
853 group, page->index, i * blocksize);
855 /* see comments in ext4_mb_put_pa() */
856 ext4_lock_group(sb, group);
857 memcpy(data, bitmap, blocksize);
859 /* mark all preallocated blks used in in-core bitmap */
860 ext4_mb_generate_from_pa(sb, data, group);
861 ext4_unlock_group(sb, group);
863 /* set incore so that the buddy information can be
864 * generated using this
869 SetPageUptodate(page);
873 for (i = 0; i < groups_per_page && bh[i]; i++)
881 static noinline_for_stack int
882 ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
883 struct ext4_buddy *e4b)
885 struct ext4_sb_info *sbi = EXT4_SB(sb);
886 struct inode *inode = sbi->s_buddy_cache;
893 mb_debug("load group %lu\n", group);
895 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
897 e4b->bd_blkbits = sb->s_blocksize_bits;
898 e4b->bd_info = ext4_get_group_info(sb, group);
900 e4b->bd_group = group;
901 e4b->bd_buddy_page = NULL;
902 e4b->bd_bitmap_page = NULL;
905 * the buddy cache inode stores the block bitmap
906 * and buddy information in consecutive blocks.
907 * So for each group we need two blocks.
910 pnum = block / blocks_per_page;
911 poff = block % blocks_per_page;
913 /* we could use find_or_create_page(), but it locks page
914 * what we'd like to avoid in fast path ... */
915 page = find_get_page(inode->i_mapping, pnum);
916 if (page == NULL || !PageUptodate(page)) {
918 page_cache_release(page);
919 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
921 BUG_ON(page->mapping != inode->i_mapping);
922 if (!PageUptodate(page)) {
923 ext4_mb_init_cache(page, NULL);
924 mb_cmp_bitmaps(e4b, page_address(page) +
925 (poff * sb->s_blocksize));
930 if (page == NULL || !PageUptodate(page))
932 e4b->bd_bitmap_page = page;
933 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
934 mark_page_accessed(page);
937 pnum = block / blocks_per_page;
938 poff = block % blocks_per_page;
940 page = find_get_page(inode->i_mapping, pnum);
941 if (page == NULL || !PageUptodate(page)) {
943 page_cache_release(page);
944 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
946 BUG_ON(page->mapping != inode->i_mapping);
947 if (!PageUptodate(page))
948 ext4_mb_init_cache(page, e4b->bd_bitmap);
953 if (page == NULL || !PageUptodate(page))
955 e4b->bd_buddy_page = page;
956 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
957 mark_page_accessed(page);
959 BUG_ON(e4b->bd_bitmap_page == NULL);
960 BUG_ON(e4b->bd_buddy_page == NULL);
965 if (e4b->bd_bitmap_page)
966 page_cache_release(e4b->bd_bitmap_page);
967 if (e4b->bd_buddy_page)
968 page_cache_release(e4b->bd_buddy_page);
969 e4b->bd_buddy = NULL;
970 e4b->bd_bitmap = NULL;
974 static void ext4_mb_release_desc(struct ext4_buddy *e4b)
976 if (e4b->bd_bitmap_page)
977 page_cache_release(e4b->bd_bitmap_page);
978 if (e4b->bd_buddy_page)
979 page_cache_release(e4b->bd_buddy_page);
983 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
988 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
989 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
991 bb = EXT4_MB_BUDDY(e4b);
992 while (order <= e4b->bd_blkbits + 1) {
994 if (!mb_test_bit(block, bb)) {
995 /* this block is part of buddy of order 'order' */
998 bb += 1 << (e4b->bd_blkbits - order);
1004 static void mb_clear_bits(spinlock_t *lock, void *bm, int cur, int len)
1010 if ((cur & 31) == 0 && (len - cur) >= 32) {
1011 /* fast path: clear whole word at once */
1012 addr = bm + (cur >> 3);
1017 mb_clear_bit_atomic(lock, cur, bm);
1022 static void mb_set_bits(spinlock_t *lock, void *bm, int cur, int len)
1028 if ((cur & 31) == 0 && (len - cur) >= 32) {
1029 /* fast path: set whole word at once */
1030 addr = bm + (cur >> 3);
1035 mb_set_bit_atomic(lock, cur, bm);
1040 static int mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1041 int first, int count)
1048 struct super_block *sb = e4b->bd_sb;
1050 BUG_ON(first + count > (sb->s_blocksize << 3));
1051 BUG_ON(!ext4_is_group_locked(sb, e4b->bd_group));
1052 mb_check_buddy(e4b);
1053 mb_free_blocks_double(inode, e4b, first, count);
1055 e4b->bd_info->bb_free += count;
1056 if (first < e4b->bd_info->bb_first_free)
1057 e4b->bd_info->bb_first_free = first;
1059 /* let's maintain fragments counter */
1061 block = !mb_test_bit(first - 1, EXT4_MB_BITMAP(e4b));
1062 if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
1063 max = !mb_test_bit(first + count, EXT4_MB_BITMAP(e4b));
1065 e4b->bd_info->bb_fragments--;
1066 else if (!block && !max)
1067 e4b->bd_info->bb_fragments++;
1069 /* let's maintain buddy itself */
1070 while (count-- > 0) {
1074 if (!mb_test_bit(block, EXT4_MB_BITMAP(e4b))) {
1075 ext4_fsblk_t blocknr;
1076 blocknr = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb);
1079 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
1081 ext4_error(sb, __func__, "double-free of inode"
1082 " %lu's block %llu(bit %u in group %lu)\n",
1083 inode ? inode->i_ino : 0, blocknr, block,
1086 mb_clear_bit(block, EXT4_MB_BITMAP(e4b));
1087 e4b->bd_info->bb_counters[order]++;
1089 /* start of the buddy */
1090 buddy = mb_find_buddy(e4b, order, &max);
1094 if (mb_test_bit(block, buddy) ||
1095 mb_test_bit(block + 1, buddy))
1098 /* both the buddies are free, try to coalesce them */
1099 buddy2 = mb_find_buddy(e4b, order + 1, &max);
1105 /* for special purposes, we don't set
1106 * free bits in bitmap */
1107 mb_set_bit(block, buddy);
1108 mb_set_bit(block + 1, buddy);
1110 e4b->bd_info->bb_counters[order]--;
1111 e4b->bd_info->bb_counters[order]--;
1115 e4b->bd_info->bb_counters[order]++;
1117 mb_clear_bit(block, buddy2);
1121 mb_check_buddy(e4b);
1126 static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
1127 int needed, struct ext4_free_extent *ex)
1134 BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
1137 buddy = mb_find_buddy(e4b, order, &max);
1138 BUG_ON(buddy == NULL);
1139 BUG_ON(block >= max);
1140 if (mb_test_bit(block, buddy)) {
1147 /* FIXME dorp order completely ? */
1148 if (likely(order == 0)) {
1149 /* find actual order */
1150 order = mb_find_order_for_block(e4b, block);
1151 block = block >> order;
1154 ex->fe_len = 1 << order;
1155 ex->fe_start = block << order;
1156 ex->fe_group = e4b->bd_group;
1158 /* calc difference from given start */
1159 next = next - ex->fe_start;
1161 ex->fe_start += next;
1163 while (needed > ex->fe_len &&
1164 (buddy = mb_find_buddy(e4b, order, &max))) {
1166 if (block + 1 >= max)
1169 next = (block + 1) * (1 << order);
1170 if (mb_test_bit(next, EXT4_MB_BITMAP(e4b)))
1173 ord = mb_find_order_for_block(e4b, next);
1176 block = next >> order;
1177 ex->fe_len += 1 << order;
1180 BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1184 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1190 int start = ex->fe_start;
1191 int len = ex->fe_len;
1196 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1197 BUG_ON(e4b->bd_group != ex->fe_group);
1198 BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
1199 mb_check_buddy(e4b);
1200 mb_mark_used_double(e4b, start, len);
1202 e4b->bd_info->bb_free -= len;
1203 if (e4b->bd_info->bb_first_free == start)
1204 e4b->bd_info->bb_first_free += len;
1206 /* let's maintain fragments counter */
1208 mlen = !mb_test_bit(start - 1, EXT4_MB_BITMAP(e4b));
1209 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1210 max = !mb_test_bit(start + len, EXT4_MB_BITMAP(e4b));
1212 e4b->bd_info->bb_fragments++;
1213 else if (!mlen && !max)
1214 e4b->bd_info->bb_fragments--;
1216 /* let's maintain buddy itself */
1218 ord = mb_find_order_for_block(e4b, start);
1220 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1221 /* the whole chunk may be allocated at once! */
1223 buddy = mb_find_buddy(e4b, ord, &max);
1224 BUG_ON((start >> ord) >= max);
1225 mb_set_bit(start >> ord, buddy);
1226 e4b->bd_info->bb_counters[ord]--;
1233 /* store for history */
1235 ret = len | (ord << 16);
1237 /* we have to split large buddy */
1239 buddy = mb_find_buddy(e4b, ord, &max);
1240 mb_set_bit(start >> ord, buddy);
1241 e4b->bd_info->bb_counters[ord]--;
1244 cur = (start >> ord) & ~1U;
1245 buddy = mb_find_buddy(e4b, ord, &max);
1246 mb_clear_bit(cur, buddy);
1247 mb_clear_bit(cur + 1, buddy);
1248 e4b->bd_info->bb_counters[ord]++;
1249 e4b->bd_info->bb_counters[ord]++;
1252 mb_set_bits(sb_bgl_lock(EXT4_SB(e4b->bd_sb), ex->fe_group),
1253 EXT4_MB_BITMAP(e4b), ex->fe_start, len0);
1254 mb_check_buddy(e4b);
1260 * Must be called under group lock!
1262 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1263 struct ext4_buddy *e4b)
1265 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1268 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1269 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1271 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1272 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1273 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1275 /* preallocation can change ac_b_ex, thus we store actually
1276 * allocated blocks for history */
1277 ac->ac_f_ex = ac->ac_b_ex;
1279 ac->ac_status = AC_STATUS_FOUND;
1280 ac->ac_tail = ret & 0xffff;
1281 ac->ac_buddy = ret >> 16;
1283 /* XXXXXXX: SUCH A HORRIBLE **CK */
1285 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1286 get_page(ac->ac_bitmap_page);
1287 ac->ac_buddy_page = e4b->bd_buddy_page;
1288 get_page(ac->ac_buddy_page);
1290 /* store last allocated for subsequent stream allocation */
1291 if ((ac->ac_flags & EXT4_MB_HINT_DATA)) {
1292 spin_lock(&sbi->s_md_lock);
1293 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1294 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1295 spin_unlock(&sbi->s_md_lock);
1300 * regular allocator, for general purposes allocation
1303 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1304 struct ext4_buddy *e4b,
1307 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1308 struct ext4_free_extent *bex = &ac->ac_b_ex;
1309 struct ext4_free_extent *gex = &ac->ac_g_ex;
1310 struct ext4_free_extent ex;
1314 * We don't want to scan for a whole year
1316 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1317 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1318 ac->ac_status = AC_STATUS_BREAK;
1323 * Haven't found good chunk so far, let's continue
1325 if (bex->fe_len < gex->fe_len)
1328 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1329 && bex->fe_group == e4b->bd_group) {
1330 /* recheck chunk's availability - we don't know
1331 * when it was found (within this lock-unlock
1333 max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
1334 if (max >= gex->fe_len) {
1335 ext4_mb_use_best_found(ac, e4b);
1342 * The routine checks whether found extent is good enough. If it is,
1343 * then the extent gets marked used and flag is set to the context
1344 * to stop scanning. Otherwise, the extent is compared with the
1345 * previous found extent and if new one is better, then it's stored
1346 * in the context. Later, the best found extent will be used, if
1347 * mballoc can't find good enough extent.
1349 * FIXME: real allocation policy is to be designed yet!
1351 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1352 struct ext4_free_extent *ex,
1353 struct ext4_buddy *e4b)
1355 struct ext4_free_extent *bex = &ac->ac_b_ex;
1356 struct ext4_free_extent *gex = &ac->ac_g_ex;
1358 BUG_ON(ex->fe_len <= 0);
1359 BUG_ON(ex->fe_len >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1360 BUG_ON(ex->fe_start >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1361 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1366 * The special case - take what you catch first
1368 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1370 ext4_mb_use_best_found(ac, e4b);
1375 * Let's check whether the chuck is good enough
1377 if (ex->fe_len == gex->fe_len) {
1379 ext4_mb_use_best_found(ac, e4b);
1384 * If this is first found extent, just store it in the context
1386 if (bex->fe_len == 0) {
1392 * If new found extent is better, store it in the context
1394 if (bex->fe_len < gex->fe_len) {
1395 /* if the request isn't satisfied, any found extent
1396 * larger than previous best one is better */
1397 if (ex->fe_len > bex->fe_len)
1399 } else if (ex->fe_len > gex->fe_len) {
1400 /* if the request is satisfied, then we try to find
1401 * an extent that still satisfy the request, but is
1402 * smaller than previous one */
1403 if (ex->fe_len < bex->fe_len)
1407 ext4_mb_check_limits(ac, e4b, 0);
1410 static int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1411 struct ext4_buddy *e4b)
1413 struct ext4_free_extent ex = ac->ac_b_ex;
1414 ext4_group_t group = ex.fe_group;
1418 BUG_ON(ex.fe_len <= 0);
1419 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1423 ext4_lock_group(ac->ac_sb, group);
1424 max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
1428 ext4_mb_use_best_found(ac, e4b);
1431 ext4_unlock_group(ac->ac_sb, group);
1432 ext4_mb_release_desc(e4b);
1437 static int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1438 struct ext4_buddy *e4b)
1440 ext4_group_t group = ac->ac_g_ex.fe_group;
1443 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1444 struct ext4_super_block *es = sbi->s_es;
1445 struct ext4_free_extent ex;
1447 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1450 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1454 ext4_lock_group(ac->ac_sb, group);
1455 max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
1456 ac->ac_g_ex.fe_len, &ex);
1458 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1461 start = (e4b->bd_group * EXT4_BLOCKS_PER_GROUP(ac->ac_sb)) +
1462 ex.fe_start + le32_to_cpu(es->s_first_data_block);
1463 /* use do_div to get remainder (would be 64-bit modulo) */
1464 if (do_div(start, sbi->s_stripe) == 0) {
1467 ext4_mb_use_best_found(ac, e4b);
1469 } else if (max >= ac->ac_g_ex.fe_len) {
1470 BUG_ON(ex.fe_len <= 0);
1471 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1472 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1475 ext4_mb_use_best_found(ac, e4b);
1476 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1477 /* Sometimes, caller may want to merge even small
1478 * number of blocks to an existing extent */
1479 BUG_ON(ex.fe_len <= 0);
1480 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1481 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1484 ext4_mb_use_best_found(ac, e4b);
1486 ext4_unlock_group(ac->ac_sb, group);
1487 ext4_mb_release_desc(e4b);
1493 * The routine scans buddy structures (not bitmap!) from given order
1494 * to max order and tries to find big enough chunk to satisfy the req
1496 static void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1497 struct ext4_buddy *e4b)
1499 struct super_block *sb = ac->ac_sb;
1500 struct ext4_group_info *grp = e4b->bd_info;
1506 BUG_ON(ac->ac_2order <= 0);
1507 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1508 if (grp->bb_counters[i] == 0)
1511 buddy = mb_find_buddy(e4b, i, &max);
1512 BUG_ON(buddy == NULL);
1514 k = mb_find_next_zero_bit(buddy, max, 0);
1519 ac->ac_b_ex.fe_len = 1 << i;
1520 ac->ac_b_ex.fe_start = k << i;
1521 ac->ac_b_ex.fe_group = e4b->bd_group;
1523 ext4_mb_use_best_found(ac, e4b);
1525 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1527 if (EXT4_SB(sb)->s_mb_stats)
1528 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1535 * The routine scans the group and measures all found extents.
1536 * In order to optimize scanning, caller must pass number of
1537 * free blocks in the group, so the routine can know upper limit.
1539 static void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1540 struct ext4_buddy *e4b)
1542 struct super_block *sb = ac->ac_sb;
1543 void *bitmap = EXT4_MB_BITMAP(e4b);
1544 struct ext4_free_extent ex;
1548 free = e4b->bd_info->bb_free;
1551 i = e4b->bd_info->bb_first_free;
1553 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1554 i = mb_find_next_zero_bit(bitmap,
1555 EXT4_BLOCKS_PER_GROUP(sb), i);
1556 if (i >= EXT4_BLOCKS_PER_GROUP(sb)) {
1558 * IF we have corrupt bitmap, we won't find any
1559 * free blocks even though group info says we
1560 * we have free blocks
1562 ext4_error(sb, __func__, "%d free blocks as per "
1563 "group info. But bitmap says 0\n",
1568 mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
1569 BUG_ON(ex.fe_len <= 0);
1570 if (free < ex.fe_len) {
1571 ext4_error(sb, __func__, "%d free blocks as per "
1572 "group info. But got %d blocks\n",
1575 * The number of free blocks differs. This mostly
1576 * indicate that the bitmap is corrupt. So exit
1577 * without claiming the space.
1582 ext4_mb_measure_extent(ac, &ex, e4b);
1588 ext4_mb_check_limits(ac, e4b, 1);
1592 * This is a special case for storages like raid5
1593 * we try to find stripe-aligned chunks for stripe-size requests
1594 * XXX should do so at least for multiples of stripe size as well
1596 static void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1597 struct ext4_buddy *e4b)
1599 struct super_block *sb = ac->ac_sb;
1600 struct ext4_sb_info *sbi = EXT4_SB(sb);
1601 void *bitmap = EXT4_MB_BITMAP(e4b);
1602 struct ext4_free_extent ex;
1603 ext4_fsblk_t first_group_block;
1608 BUG_ON(sbi->s_stripe == 0);
1610 /* find first stripe-aligned block in group */
1611 first_group_block = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb)
1612 + le32_to_cpu(sbi->s_es->s_first_data_block);
1613 a = first_group_block + sbi->s_stripe - 1;
1614 do_div(a, sbi->s_stripe);
1615 i = (a * sbi->s_stripe) - first_group_block;
1617 while (i < EXT4_BLOCKS_PER_GROUP(sb)) {
1618 if (!mb_test_bit(i, bitmap)) {
1619 max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
1620 if (max >= sbi->s_stripe) {
1623 ext4_mb_use_best_found(ac, e4b);
1631 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
1632 ext4_group_t group, int cr)
1634 unsigned free, fragments;
1636 struct ext4_group_desc *desc;
1637 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1639 BUG_ON(cr < 0 || cr >= 4);
1640 BUG_ON(EXT4_MB_GRP_NEED_INIT(grp));
1642 free = grp->bb_free;
1643 fragments = grp->bb_fragments;
1651 BUG_ON(ac->ac_2order == 0);
1652 /* If this group is uninitialized, skip it initially */
1653 desc = ext4_get_group_desc(ac->ac_sb, group, NULL);
1654 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))
1657 bits = ac->ac_sb->s_blocksize_bits + 1;
1658 for (i = ac->ac_2order; i <= bits; i++)
1659 if (grp->bb_counters[i] > 0)
1663 if ((free / fragments) >= ac->ac_g_ex.fe_len)
1667 if (free >= ac->ac_g_ex.fe_len)
1679 static noinline_for_stack int
1680 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
1687 struct ext4_sb_info *sbi;
1688 struct super_block *sb;
1689 struct ext4_buddy e4b;
1694 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1696 /* first, try the goal */
1697 err = ext4_mb_find_by_goal(ac, &e4b);
1698 if (err || ac->ac_status == AC_STATUS_FOUND)
1701 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
1705 * ac->ac2_order is set only if the fe_len is a power of 2
1706 * if ac2_order is set we also set criteria to 0 so that we
1707 * try exact allocation using buddy.
1709 i = fls(ac->ac_g_ex.fe_len);
1712 * We search using buddy data only if the order of the request
1713 * is greater than equal to the sbi_s_mb_order2_reqs
1714 * You can tune it via /proc/fs/ext4/<partition>/order2_req
1716 if (i >= sbi->s_mb_order2_reqs) {
1718 * This should tell if fe_len is exactly power of 2
1720 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
1721 ac->ac_2order = i - 1;
1724 bsbits = ac->ac_sb->s_blocksize_bits;
1725 /* if stream allocation is enabled, use global goal */
1726 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
1727 isize = i_size_read(ac->ac_inode) >> bsbits;
1731 if (size < sbi->s_mb_stream_request &&
1732 (ac->ac_flags & EXT4_MB_HINT_DATA)) {
1733 /* TBD: may be hot point */
1734 spin_lock(&sbi->s_md_lock);
1735 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
1736 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
1737 spin_unlock(&sbi->s_md_lock);
1739 /* Let's just scan groups to find more-less suitable blocks */
1740 cr = ac->ac_2order ? 0 : 1;
1742 * cr == 0 try to get exact allocation,
1743 * cr == 3 try to get anything
1746 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
1747 ac->ac_criteria = cr;
1749 * searching for the right group start
1750 * from the goal value specified
1752 group = ac->ac_g_ex.fe_group;
1754 for (i = 0; i < EXT4_SB(sb)->s_groups_count; group++, i++) {
1755 struct ext4_group_info *grp;
1756 struct ext4_group_desc *desc;
1758 if (group == EXT4_SB(sb)->s_groups_count)
1761 /* quick check to skip empty groups */
1762 grp = ext4_get_group_info(ac->ac_sb, group);
1763 if (grp->bb_free == 0)
1767 * if the group is already init we check whether it is
1768 * a good group and if not we don't load the buddy
1770 if (EXT4_MB_GRP_NEED_INIT(grp)) {
1772 * we need full data about the group
1773 * to make a good selection
1775 err = ext4_mb_load_buddy(sb, group, &e4b);
1778 ext4_mb_release_desc(&e4b);
1782 * If the particular group doesn't satisfy our
1783 * criteria we continue with the next group
1785 if (!ext4_mb_good_group(ac, group, cr))
1788 err = ext4_mb_load_buddy(sb, group, &e4b);
1792 ext4_lock_group(sb, group);
1793 if (!ext4_mb_good_group(ac, group, cr)) {
1794 /* someone did allocation from this group */
1795 ext4_unlock_group(sb, group);
1796 ext4_mb_release_desc(&e4b);
1800 ac->ac_groups_scanned++;
1801 desc = ext4_get_group_desc(sb, group, NULL);
1802 if (cr == 0 || (desc->bg_flags &
1803 cpu_to_le16(EXT4_BG_BLOCK_UNINIT) &&
1804 ac->ac_2order != 0))
1805 ext4_mb_simple_scan_group(ac, &e4b);
1807 ac->ac_g_ex.fe_len == sbi->s_stripe)
1808 ext4_mb_scan_aligned(ac, &e4b);
1810 ext4_mb_complex_scan_group(ac, &e4b);
1812 ext4_unlock_group(sb, group);
1813 ext4_mb_release_desc(&e4b);
1815 if (ac->ac_status != AC_STATUS_CONTINUE)
1820 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
1821 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1823 * We've been searching too long. Let's try to allocate
1824 * the best chunk we've found so far
1827 ext4_mb_try_best_found(ac, &e4b);
1828 if (ac->ac_status != AC_STATUS_FOUND) {
1830 * Someone more lucky has already allocated it.
1831 * The only thing we can do is just take first
1833 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
1835 ac->ac_b_ex.fe_group = 0;
1836 ac->ac_b_ex.fe_start = 0;
1837 ac->ac_b_ex.fe_len = 0;
1838 ac->ac_status = AC_STATUS_CONTINUE;
1839 ac->ac_flags |= EXT4_MB_HINT_FIRST;
1841 atomic_inc(&sbi->s_mb_lost_chunks);
1849 #ifdef EXT4_MB_HISTORY
1850 struct ext4_mb_proc_session {
1851 struct ext4_mb_history *history;
1852 struct super_block *sb;
1857 static void *ext4_mb_history_skip_empty(struct ext4_mb_proc_session *s,
1858 struct ext4_mb_history *hs,
1861 if (hs == s->history + s->max)
1863 if (!first && hs == s->history + s->start)
1865 while (hs->orig.fe_len == 0) {
1867 if (hs == s->history + s->max)
1869 if (hs == s->history + s->start)
1875 static void *ext4_mb_seq_history_start(struct seq_file *seq, loff_t *pos)
1877 struct ext4_mb_proc_session *s = seq->private;
1878 struct ext4_mb_history *hs;
1882 return SEQ_START_TOKEN;
1883 hs = ext4_mb_history_skip_empty(s, s->history + s->start, 1);
1886 while (--l && (hs = ext4_mb_history_skip_empty(s, ++hs, 0)) != NULL);
1890 static void *ext4_mb_seq_history_next(struct seq_file *seq, void *v,
1893 struct ext4_mb_proc_session *s = seq->private;
1894 struct ext4_mb_history *hs = v;
1897 if (v == SEQ_START_TOKEN)
1898 return ext4_mb_history_skip_empty(s, s->history + s->start, 1);
1900 return ext4_mb_history_skip_empty(s, ++hs, 0);
1903 static int ext4_mb_seq_history_show(struct seq_file *seq, void *v)
1905 char buf[25], buf2[25], buf3[25], *fmt;
1906 struct ext4_mb_history *hs = v;
1908 if (v == SEQ_START_TOKEN) {
1909 seq_printf(seq, "%-5s %-8s %-23s %-23s %-23s %-5s "
1910 "%-5s %-2s %-5s %-5s %-5s %-6s\n",
1911 "pid", "inode", "original", "goal", "result", "found",
1912 "grps", "cr", "flags", "merge", "tail", "broken");
1916 if (hs->op == EXT4_MB_HISTORY_ALLOC) {
1917 fmt = "%-5u %-8u %-23s %-23s %-23s %-5u %-5u %-2u "
1918 "%-5u %-5s %-5u %-6u\n";
1919 sprintf(buf2, "%lu/%d/%u@%u", hs->result.fe_group,
1920 hs->result.fe_start, hs->result.fe_len,
1921 hs->result.fe_logical);
1922 sprintf(buf, "%lu/%d/%u@%u", hs->orig.fe_group,
1923 hs->orig.fe_start, hs->orig.fe_len,
1924 hs->orig.fe_logical);
1925 sprintf(buf3, "%lu/%d/%u@%u", hs->goal.fe_group,
1926 hs->goal.fe_start, hs->goal.fe_len,
1927 hs->goal.fe_logical);
1928 seq_printf(seq, fmt, hs->pid, hs->ino, buf, buf3, buf2,
1929 hs->found, hs->groups, hs->cr, hs->flags,
1930 hs->merged ? "M" : "", hs->tail,
1931 hs->buddy ? 1 << hs->buddy : 0);
1932 } else if (hs->op == EXT4_MB_HISTORY_PREALLOC) {
1933 fmt = "%-5u %-8u %-23s %-23s %-23s\n";
1934 sprintf(buf2, "%lu/%d/%u@%u", hs->result.fe_group,
1935 hs->result.fe_start, hs->result.fe_len,
1936 hs->result.fe_logical);
1937 sprintf(buf, "%lu/%d/%u@%u", hs->orig.fe_group,
1938 hs->orig.fe_start, hs->orig.fe_len,
1939 hs->orig.fe_logical);
1940 seq_printf(seq, fmt, hs->pid, hs->ino, buf, "", buf2);
1941 } else if (hs->op == EXT4_MB_HISTORY_DISCARD) {
1942 sprintf(buf2, "%lu/%d/%u", hs->result.fe_group,
1943 hs->result.fe_start, hs->result.fe_len);
1944 seq_printf(seq, "%-5u %-8u %-23s discard\n",
1945 hs->pid, hs->ino, buf2);
1946 } else if (hs->op == EXT4_MB_HISTORY_FREE) {
1947 sprintf(buf2, "%lu/%d/%u", hs->result.fe_group,
1948 hs->result.fe_start, hs->result.fe_len);
1949 seq_printf(seq, "%-5u %-8u %-23s free\n",
1950 hs->pid, hs->ino, buf2);
1955 static void ext4_mb_seq_history_stop(struct seq_file *seq, void *v)
1959 static struct seq_operations ext4_mb_seq_history_ops = {
1960 .start = ext4_mb_seq_history_start,
1961 .next = ext4_mb_seq_history_next,
1962 .stop = ext4_mb_seq_history_stop,
1963 .show = ext4_mb_seq_history_show,
1966 static int ext4_mb_seq_history_open(struct inode *inode, struct file *file)
1968 struct super_block *sb = PDE(inode)->data;
1969 struct ext4_sb_info *sbi = EXT4_SB(sb);
1970 struct ext4_mb_proc_session *s;
1974 s = kmalloc(sizeof(*s), GFP_KERNEL);
1978 size = sizeof(struct ext4_mb_history) * sbi->s_mb_history_max;
1979 s->history = kmalloc(size, GFP_KERNEL);
1980 if (s->history == NULL) {
1985 spin_lock(&sbi->s_mb_history_lock);
1986 memcpy(s->history, sbi->s_mb_history, size);
1987 s->max = sbi->s_mb_history_max;
1988 s->start = sbi->s_mb_history_cur % s->max;
1989 spin_unlock(&sbi->s_mb_history_lock);
1991 rc = seq_open(file, &ext4_mb_seq_history_ops);
1993 struct seq_file *m = (struct seq_file *)file->private_data;
2003 static int ext4_mb_seq_history_release(struct inode *inode, struct file *file)
2005 struct seq_file *seq = (struct seq_file *)file->private_data;
2006 struct ext4_mb_proc_session *s = seq->private;
2009 return seq_release(inode, file);
2012 static ssize_t ext4_mb_seq_history_write(struct file *file,
2013 const char __user *buffer,
2014 size_t count, loff_t *ppos)
2016 struct seq_file *seq = (struct seq_file *)file->private_data;
2017 struct ext4_mb_proc_session *s = seq->private;
2018 struct super_block *sb = s->sb;
2022 if (count >= sizeof(str)) {
2023 printk(KERN_ERR "EXT4-fs: %s string too long, max %u bytes\n",
2024 "mb_history", (int)sizeof(str));
2028 if (copy_from_user(str, buffer, count))
2031 value = simple_strtol(str, NULL, 0);
2034 EXT4_SB(sb)->s_mb_history_filter = value;
2039 static struct file_operations ext4_mb_seq_history_fops = {
2040 .owner = THIS_MODULE,
2041 .open = ext4_mb_seq_history_open,
2043 .write = ext4_mb_seq_history_write,
2044 .llseek = seq_lseek,
2045 .release = ext4_mb_seq_history_release,
2048 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2050 struct super_block *sb = seq->private;
2051 struct ext4_sb_info *sbi = EXT4_SB(sb);
2054 if (*pos < 0 || *pos >= sbi->s_groups_count)
2058 return (void *) group;
2061 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2063 struct super_block *sb = seq->private;
2064 struct ext4_sb_info *sbi = EXT4_SB(sb);
2068 if (*pos < 0 || *pos >= sbi->s_groups_count)
2071 return (void *) group;;
2074 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2076 struct super_block *sb = seq->private;
2077 long group = (long) v;
2080 struct ext4_buddy e4b;
2082 struct ext4_group_info info;
2083 unsigned short counters[16];
2088 seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
2089 "[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2090 "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2091 "group", "free", "frags", "first",
2092 "2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
2093 "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2095 i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2096 sizeof(struct ext4_group_info);
2097 err = ext4_mb_load_buddy(sb, group, &e4b);
2099 seq_printf(seq, "#%-5lu: I/O error\n", group);
2102 ext4_lock_group(sb, group);
2103 memcpy(&sg, ext4_get_group_info(sb, group), i);
2104 ext4_unlock_group(sb, group);
2105 ext4_mb_release_desc(&e4b);
2107 seq_printf(seq, "#%-5lu: %-5u %-5u %-5u [", group, sg.info.bb_free,
2108 sg.info.bb_fragments, sg.info.bb_first_free);
2109 for (i = 0; i <= 13; i++)
2110 seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2111 sg.info.bb_counters[i] : 0);
2112 seq_printf(seq, " ]\n");
2117 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2121 static struct seq_operations ext4_mb_seq_groups_ops = {
2122 .start = ext4_mb_seq_groups_start,
2123 .next = ext4_mb_seq_groups_next,
2124 .stop = ext4_mb_seq_groups_stop,
2125 .show = ext4_mb_seq_groups_show,
2128 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2130 struct super_block *sb = PDE(inode)->data;
2133 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2135 struct seq_file *m = (struct seq_file *)file->private_data;
2142 static struct file_operations ext4_mb_seq_groups_fops = {
2143 .owner = THIS_MODULE,
2144 .open = ext4_mb_seq_groups_open,
2146 .llseek = seq_lseek,
2147 .release = seq_release,
2150 static void ext4_mb_history_release(struct super_block *sb)
2152 struct ext4_sb_info *sbi = EXT4_SB(sb);
2154 remove_proc_entry("mb_groups", sbi->s_mb_proc);
2155 remove_proc_entry("mb_history", sbi->s_mb_proc);
2157 kfree(sbi->s_mb_history);
2160 static void ext4_mb_history_init(struct super_block *sb)
2162 struct ext4_sb_info *sbi = EXT4_SB(sb);
2165 if (sbi->s_mb_proc != NULL) {
2166 proc_create_data("mb_history", S_IRUGO, sbi->s_mb_proc,
2167 &ext4_mb_seq_history_fops, sb);
2168 proc_create_data("mb_groups", S_IRUGO, sbi->s_mb_proc,
2169 &ext4_mb_seq_groups_fops, sb);
2172 sbi->s_mb_history_max = 1000;
2173 sbi->s_mb_history_cur = 0;
2174 spin_lock_init(&sbi->s_mb_history_lock);
2175 i = sbi->s_mb_history_max * sizeof(struct ext4_mb_history);
2176 sbi->s_mb_history = kmalloc(i, GFP_KERNEL);
2177 if (likely(sbi->s_mb_history != NULL))
2178 memset(sbi->s_mb_history, 0, i);
2179 /* if we can't allocate history, then we simple won't use it */
2182 static noinline_for_stack void
2183 ext4_mb_store_history(struct ext4_allocation_context *ac)
2185 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2186 struct ext4_mb_history h;
2188 if (unlikely(sbi->s_mb_history == NULL))
2191 if (!(ac->ac_op & sbi->s_mb_history_filter))
2195 h.pid = current->pid;
2196 h.ino = ac->ac_inode ? ac->ac_inode->i_ino : 0;
2197 h.orig = ac->ac_o_ex;
2198 h.result = ac->ac_b_ex;
2199 h.flags = ac->ac_flags;
2200 h.found = ac->ac_found;
2201 h.groups = ac->ac_groups_scanned;
2202 h.cr = ac->ac_criteria;
2203 h.tail = ac->ac_tail;
2204 h.buddy = ac->ac_buddy;
2206 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC) {
2207 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
2208 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
2210 h.goal = ac->ac_g_ex;
2211 h.result = ac->ac_f_ex;
2214 spin_lock(&sbi->s_mb_history_lock);
2215 memcpy(sbi->s_mb_history + sbi->s_mb_history_cur, &h, sizeof(h));
2216 if (++sbi->s_mb_history_cur >= sbi->s_mb_history_max)
2217 sbi->s_mb_history_cur = 0;
2218 spin_unlock(&sbi->s_mb_history_lock);
2222 #define ext4_mb_history_release(sb)
2223 #define ext4_mb_history_init(sb)
2226 static int ext4_mb_init_backend(struct super_block *sb)
2229 int j, len, metalen;
2230 struct ext4_sb_info *sbi = EXT4_SB(sb);
2231 int num_meta_group_infos =
2232 (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) >>
2233 EXT4_DESC_PER_BLOCK_BITS(sb);
2234 struct ext4_group_info **meta_group_info;
2236 /* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2237 * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2238 * So a two level scheme suffices for now. */
2239 sbi->s_group_info = kmalloc(sizeof(*sbi->s_group_info) *
2240 num_meta_group_infos, GFP_KERNEL);
2241 if (sbi->s_group_info == NULL) {
2242 printk(KERN_ERR "EXT4-fs: can't allocate buddy meta group\n");
2245 sbi->s_buddy_cache = new_inode(sb);
2246 if (sbi->s_buddy_cache == NULL) {
2247 printk(KERN_ERR "EXT4-fs: can't get new inode\n");
2250 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2252 metalen = sizeof(*meta_group_info) << EXT4_DESC_PER_BLOCK_BITS(sb);
2253 for (i = 0; i < num_meta_group_infos; i++) {
2254 if ((i + 1) == num_meta_group_infos)
2255 metalen = sizeof(*meta_group_info) *
2256 (sbi->s_groups_count -
2257 (i << EXT4_DESC_PER_BLOCK_BITS(sb)));
2258 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2259 if (meta_group_info == NULL) {
2260 printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2264 sbi->s_group_info[i] = meta_group_info;
2268 * calculate needed size. if change bb_counters size,
2269 * don't forget about ext4_mb_generate_buddy()
2271 len = sizeof(struct ext4_group_info);
2272 len += sizeof(unsigned short) * (sb->s_blocksize_bits + 2);
2273 for (i = 0; i < sbi->s_groups_count; i++) {
2274 struct ext4_group_desc *desc;
2277 sbi->s_group_info[i >> EXT4_DESC_PER_BLOCK_BITS(sb)];
2278 j = i & (EXT4_DESC_PER_BLOCK(sb) - 1);
2280 meta_group_info[j] = kzalloc(len, GFP_KERNEL);
2281 if (meta_group_info[j] == NULL) {
2282 printk(KERN_ERR "EXT4-fs: can't allocate buddy mem\n");
2285 desc = ext4_get_group_desc(sb, i, NULL);
2288 "EXT4-fs: can't read descriptor %lu\n", i);
2292 memset(meta_group_info[j], 0, len);
2293 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2294 &(meta_group_info[j]->bb_state));
2297 * initialize bb_free to be able to skip
2298 * empty groups without initialization
2300 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2301 meta_group_info[j]->bb_free =
2302 ext4_free_blocks_after_init(sb, i, desc);
2304 meta_group_info[j]->bb_free =
2305 le16_to_cpu(desc->bg_free_blocks_count);
2308 INIT_LIST_HEAD(&meta_group_info[j]->bb_prealloc_list);
2312 struct buffer_head *bh;
2313 meta_group_info[j]->bb_bitmap =
2314 kmalloc(sb->s_blocksize, GFP_KERNEL);
2315 BUG_ON(meta_group_info[j]->bb_bitmap == NULL);
2316 bh = read_block_bitmap(sb, i);
2318 memcpy(meta_group_info[j]->bb_bitmap, bh->b_data,
2330 kfree(ext4_get_group_info(sb, i));
2331 i = num_meta_group_infos;
2334 kfree(sbi->s_group_info[i]);
2335 iput(sbi->s_buddy_cache);
2337 kfree(sbi->s_group_info);
2341 int ext4_mb_init(struct super_block *sb, int needs_recovery)
2343 struct ext4_sb_info *sbi = EXT4_SB(sb);
2348 if (!test_opt(sb, MBALLOC))
2351 i = (sb->s_blocksize_bits + 2) * sizeof(unsigned short);
2353 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2354 if (sbi->s_mb_offsets == NULL) {
2355 clear_opt(sbi->s_mount_opt, MBALLOC);
2358 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2359 if (sbi->s_mb_maxs == NULL) {
2360 clear_opt(sbi->s_mount_opt, MBALLOC);
2361 kfree(sbi->s_mb_maxs);
2365 /* order 0 is regular bitmap */
2366 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2367 sbi->s_mb_offsets[0] = 0;
2371 max = sb->s_blocksize << 2;
2373 sbi->s_mb_offsets[i] = offset;
2374 sbi->s_mb_maxs[i] = max;
2375 offset += 1 << (sb->s_blocksize_bits - i);
2378 } while (i <= sb->s_blocksize_bits + 1);
2380 /* init file for buddy data */
2381 i = ext4_mb_init_backend(sb);
2383 clear_opt(sbi->s_mount_opt, MBALLOC);
2384 kfree(sbi->s_mb_offsets);
2385 kfree(sbi->s_mb_maxs);
2389 spin_lock_init(&sbi->s_md_lock);
2390 INIT_LIST_HEAD(&sbi->s_active_transaction);
2391 INIT_LIST_HEAD(&sbi->s_closed_transaction);
2392 INIT_LIST_HEAD(&sbi->s_committed_transaction);
2393 spin_lock_init(&sbi->s_bal_lock);
2395 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2396 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2397 sbi->s_mb_stats = MB_DEFAULT_STATS;
2398 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2399 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2400 sbi->s_mb_history_filter = EXT4_MB_HISTORY_DEFAULT;
2401 sbi->s_mb_group_prealloc = MB_DEFAULT_GROUP_PREALLOC;
2403 i = sizeof(struct ext4_locality_group) * NR_CPUS;
2404 sbi->s_locality_groups = kmalloc(i, GFP_KERNEL);
2405 if (sbi->s_locality_groups == NULL) {
2406 clear_opt(sbi->s_mount_opt, MBALLOC);
2407 kfree(sbi->s_mb_offsets);
2408 kfree(sbi->s_mb_maxs);
2411 for (i = 0; i < NR_CPUS; i++) {
2412 struct ext4_locality_group *lg;
2413 lg = &sbi->s_locality_groups[i];
2414 mutex_init(&lg->lg_mutex);
2415 INIT_LIST_HEAD(&lg->lg_prealloc_list);
2416 spin_lock_init(&lg->lg_prealloc_lock);
2419 ext4_mb_init_per_dev_proc(sb);
2420 ext4_mb_history_init(sb);
2422 printk("EXT4-fs: mballoc enabled\n");
2426 /* need to called with ext4 group lock (ext4_lock_group) */
2427 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2429 struct ext4_prealloc_space *pa;
2430 struct list_head *cur, *tmp;
2433 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2434 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2435 list_del(&pa->pa_group_list);
2440 mb_debug("mballoc: %u PAs left\n", count);
2444 int ext4_mb_release(struct super_block *sb)
2447 int num_meta_group_infos;
2448 struct ext4_group_info *grinfo;
2449 struct ext4_sb_info *sbi = EXT4_SB(sb);
2451 if (!test_opt(sb, MBALLOC))
2454 /* release freed, non-committed blocks */
2455 spin_lock(&sbi->s_md_lock);
2456 list_splice_init(&sbi->s_closed_transaction,
2457 &sbi->s_committed_transaction);
2458 list_splice_init(&sbi->s_active_transaction,
2459 &sbi->s_committed_transaction);
2460 spin_unlock(&sbi->s_md_lock);
2461 ext4_mb_free_committed_blocks(sb);
2463 if (sbi->s_group_info) {
2464 for (i = 0; i < sbi->s_groups_count; i++) {
2465 grinfo = ext4_get_group_info(sb, i);
2467 kfree(grinfo->bb_bitmap);
2469 ext4_lock_group(sb, i);
2470 ext4_mb_cleanup_pa(grinfo);
2471 ext4_unlock_group(sb, i);
2474 num_meta_group_infos = (sbi->s_groups_count +
2475 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2476 EXT4_DESC_PER_BLOCK_BITS(sb);
2477 for (i = 0; i < num_meta_group_infos; i++)
2478 kfree(sbi->s_group_info[i]);
2479 kfree(sbi->s_group_info);
2481 kfree(sbi->s_mb_offsets);
2482 kfree(sbi->s_mb_maxs);
2483 if (sbi->s_buddy_cache)
2484 iput(sbi->s_buddy_cache);
2485 if (sbi->s_mb_stats) {
2487 "EXT4-fs: mballoc: %u blocks %u reqs (%u success)\n",
2488 atomic_read(&sbi->s_bal_allocated),
2489 atomic_read(&sbi->s_bal_reqs),
2490 atomic_read(&sbi->s_bal_success));
2492 "EXT4-fs: mballoc: %u extents scanned, %u goal hits, "
2493 "%u 2^N hits, %u breaks, %u lost\n",
2494 atomic_read(&sbi->s_bal_ex_scanned),
2495 atomic_read(&sbi->s_bal_goals),
2496 atomic_read(&sbi->s_bal_2orders),
2497 atomic_read(&sbi->s_bal_breaks),
2498 atomic_read(&sbi->s_mb_lost_chunks));
2500 "EXT4-fs: mballoc: %lu generated and it took %Lu\n",
2501 sbi->s_mb_buddies_generated++,
2502 sbi->s_mb_generation_time);
2504 "EXT4-fs: mballoc: %u preallocated, %u discarded\n",
2505 atomic_read(&sbi->s_mb_preallocated),
2506 atomic_read(&sbi->s_mb_discarded));
2509 kfree(sbi->s_locality_groups);
2511 ext4_mb_history_release(sb);
2512 ext4_mb_destroy_per_dev_proc(sb);
2517 static noinline_for_stack void
2518 ext4_mb_free_committed_blocks(struct super_block *sb)
2520 struct ext4_sb_info *sbi = EXT4_SB(sb);
2525 struct ext4_free_metadata *md;
2526 struct ext4_buddy e4b;
2528 if (list_empty(&sbi->s_committed_transaction))
2531 /* there is committed blocks to be freed yet */
2533 /* get next array of blocks */
2535 spin_lock(&sbi->s_md_lock);
2536 if (!list_empty(&sbi->s_committed_transaction)) {
2537 md = list_entry(sbi->s_committed_transaction.next,
2538 struct ext4_free_metadata, list);
2539 list_del(&md->list);
2541 spin_unlock(&sbi->s_md_lock);
2546 mb_debug("gonna free %u blocks in group %lu (0x%p):",
2547 md->num, md->group, md);
2549 err = ext4_mb_load_buddy(sb, md->group, &e4b);
2550 /* we expect to find existing buddy because it's pinned */
2553 /* there are blocks to put in buddy to make them really free */
2556 ext4_lock_group(sb, md->group);
2557 for (i = 0; i < md->num; i++) {
2558 mb_debug(" %u", md->blocks[i]);
2559 err = mb_free_blocks(NULL, &e4b, md->blocks[i], 1);
2563 ext4_unlock_group(sb, md->group);
2565 /* balance refcounts from ext4_mb_free_metadata() */
2566 page_cache_release(e4b.bd_buddy_page);
2567 page_cache_release(e4b.bd_bitmap_page);
2570 ext4_mb_release_desc(&e4b);
2574 mb_debug("freed %u blocks in %u structures\n", count, count2);
2577 #define EXT4_MB_STATS_NAME "stats"
2578 #define EXT4_MB_MAX_TO_SCAN_NAME "max_to_scan"
2579 #define EXT4_MB_MIN_TO_SCAN_NAME "min_to_scan"
2580 #define EXT4_MB_ORDER2_REQ "order2_req"
2581 #define EXT4_MB_STREAM_REQ "stream_req"
2582 #define EXT4_MB_GROUP_PREALLOC "group_prealloc"
2586 #define MB_PROC_VALUE_READ(name) \
2587 static int ext4_mb_read_##name(char *page, char **start, \
2588 off_t off, int count, int *eof, void *data) \
2590 struct ext4_sb_info *sbi = data; \
2595 len = sprintf(page, "%ld\n", sbi->s_mb_##name); \
2600 #define MB_PROC_VALUE_WRITE(name) \
2601 static int ext4_mb_write_##name(struct file *file, \
2602 const char __user *buf, unsigned long cnt, void *data) \
2604 struct ext4_sb_info *sbi = data; \
2607 if (cnt >= sizeof(str)) \
2609 if (copy_from_user(str, buf, cnt)) \
2611 value = simple_strtol(str, NULL, 0); \
2614 sbi->s_mb_##name = value; \
2618 MB_PROC_VALUE_READ(stats);
2619 MB_PROC_VALUE_WRITE(stats);
2620 MB_PROC_VALUE_READ(max_to_scan);
2621 MB_PROC_VALUE_WRITE(max_to_scan);
2622 MB_PROC_VALUE_READ(min_to_scan);
2623 MB_PROC_VALUE_WRITE(min_to_scan);
2624 MB_PROC_VALUE_READ(order2_reqs);
2625 MB_PROC_VALUE_WRITE(order2_reqs);
2626 MB_PROC_VALUE_READ(stream_request);
2627 MB_PROC_VALUE_WRITE(stream_request);
2628 MB_PROC_VALUE_READ(group_prealloc);
2629 MB_PROC_VALUE_WRITE(group_prealloc);
2631 #define MB_PROC_HANDLER(name, var) \
2633 proc = create_proc_entry(name, mode, sbi->s_mb_proc); \
2634 if (proc == NULL) { \
2635 printk(KERN_ERR "EXT4-fs: can't to create %s\n", name); \
2639 proc->read_proc = ext4_mb_read_##var ; \
2640 proc->write_proc = ext4_mb_write_##var; \
2643 static int ext4_mb_init_per_dev_proc(struct super_block *sb)
2645 mode_t mode = S_IFREG | S_IRUGO | S_IWUSR;
2646 struct ext4_sb_info *sbi = EXT4_SB(sb);
2647 struct proc_dir_entry *proc;
2650 bdevname(sb->s_bdev, devname);
2651 sbi->s_mb_proc = proc_mkdir(devname, proc_root_ext4);
2653 MB_PROC_HANDLER(EXT4_MB_STATS_NAME, stats);
2654 MB_PROC_HANDLER(EXT4_MB_MAX_TO_SCAN_NAME, max_to_scan);
2655 MB_PROC_HANDLER(EXT4_MB_MIN_TO_SCAN_NAME, min_to_scan);
2656 MB_PROC_HANDLER(EXT4_MB_ORDER2_REQ, order2_reqs);
2657 MB_PROC_HANDLER(EXT4_MB_STREAM_REQ, stream_request);
2658 MB_PROC_HANDLER(EXT4_MB_GROUP_PREALLOC, group_prealloc);
2663 printk(KERN_ERR "EXT4-fs: Unable to create %s\n", devname);
2664 remove_proc_entry(EXT4_MB_GROUP_PREALLOC, sbi->s_mb_proc);
2665 remove_proc_entry(EXT4_MB_STREAM_REQ, sbi->s_mb_proc);
2666 remove_proc_entry(EXT4_MB_ORDER2_REQ, sbi->s_mb_proc);
2667 remove_proc_entry(EXT4_MB_MIN_TO_SCAN_NAME, sbi->s_mb_proc);
2668 remove_proc_entry(EXT4_MB_MAX_TO_SCAN_NAME, sbi->s_mb_proc);
2669 remove_proc_entry(EXT4_MB_STATS_NAME, sbi->s_mb_proc);
2670 remove_proc_entry(devname, proc_root_ext4);
2671 sbi->s_mb_proc = NULL;
2676 static int ext4_mb_destroy_per_dev_proc(struct super_block *sb)
2678 struct ext4_sb_info *sbi = EXT4_SB(sb);
2681 if (sbi->s_mb_proc == NULL)
2684 bdevname(sb->s_bdev, devname);
2685 remove_proc_entry(EXT4_MB_GROUP_PREALLOC, sbi->s_mb_proc);
2686 remove_proc_entry(EXT4_MB_STREAM_REQ, sbi->s_mb_proc);
2687 remove_proc_entry(EXT4_MB_ORDER2_REQ, sbi->s_mb_proc);
2688 remove_proc_entry(EXT4_MB_MIN_TO_SCAN_NAME, sbi->s_mb_proc);
2689 remove_proc_entry(EXT4_MB_MAX_TO_SCAN_NAME, sbi->s_mb_proc);
2690 remove_proc_entry(EXT4_MB_STATS_NAME, sbi->s_mb_proc);
2691 remove_proc_entry(devname, proc_root_ext4);
2696 int __init init_ext4_mballoc(void)
2698 ext4_pspace_cachep =
2699 kmem_cache_create("ext4_prealloc_space",
2700 sizeof(struct ext4_prealloc_space),
2701 0, SLAB_RECLAIM_ACCOUNT, NULL);
2702 if (ext4_pspace_cachep == NULL)
2706 kmem_cache_create("ext4_alloc_context",
2707 sizeof(struct ext4_allocation_context),
2708 0, SLAB_RECLAIM_ACCOUNT, NULL);
2709 if (ext4_ac_cachep == NULL) {
2710 kmem_cache_destroy(ext4_pspace_cachep);
2713 #ifdef CONFIG_PROC_FS
2714 proc_root_ext4 = proc_mkdir("fs/ext4", NULL);
2715 if (proc_root_ext4 == NULL)
2716 printk(KERN_ERR "EXT4-fs: Unable to create fs/ext4\n");
2721 void exit_ext4_mballoc(void)
2723 /* XXX: synchronize_rcu(); */
2724 kmem_cache_destroy(ext4_pspace_cachep);
2725 kmem_cache_destroy(ext4_ac_cachep);
2726 #ifdef CONFIG_PROC_FS
2727 remove_proc_entry("fs/ext4", NULL);
2733 * Check quota and mark choosed space (ac->ac_b_ex) non-free in bitmaps
2734 * Returns 0 if success or error code
2736 static noinline_for_stack int
2737 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2740 struct buffer_head *bitmap_bh = NULL;
2741 struct ext4_super_block *es;
2742 struct ext4_group_desc *gdp;
2743 struct buffer_head *gdp_bh;
2744 struct ext4_sb_info *sbi;
2745 struct super_block *sb;
2749 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2750 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2758 bitmap_bh = read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2762 err = ext4_journal_get_write_access(handle, bitmap_bh);
2767 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2771 ext4_debug("using block group %lu(%d)\n", ac->ac_b_ex.fe_group,
2772 gdp->bg_free_blocks_count);
2774 err = ext4_journal_get_write_access(handle, gdp_bh);
2778 block = ac->ac_b_ex.fe_group * EXT4_BLOCKS_PER_GROUP(sb)
2779 + ac->ac_b_ex.fe_start
2780 + le32_to_cpu(es->s_first_data_block);
2782 len = ac->ac_b_ex.fe_len;
2783 if (in_range(ext4_block_bitmap(sb, gdp), block, len) ||
2784 in_range(ext4_inode_bitmap(sb, gdp), block, len) ||
2785 in_range(block, ext4_inode_table(sb, gdp),
2786 EXT4_SB(sb)->s_itb_per_group) ||
2787 in_range(block + len - 1, ext4_inode_table(sb, gdp),
2788 EXT4_SB(sb)->s_itb_per_group)) {
2789 ext4_error(sb, __func__,
2790 "Allocating block in system zone - block = %llu",
2792 /* File system mounted not to panic on error
2793 * Fix the bitmap and repeat the block allocation
2794 * We leak some of the blocks here.
2796 mb_set_bits(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group),
2797 bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2798 ac->ac_b_ex.fe_len);
2799 err = ext4_journal_dirty_metadata(handle, bitmap_bh);
2804 #ifdef AGGRESSIVE_CHECK
2807 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
2808 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
2809 bitmap_bh->b_data));
2813 mb_set_bits(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group), bitmap_bh->b_data,
2814 ac->ac_b_ex.fe_start, ac->ac_b_ex.fe_len);
2816 spin_lock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
2817 if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2818 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
2819 gdp->bg_free_blocks_count =
2820 cpu_to_le16(ext4_free_blocks_after_init(sb,
2821 ac->ac_b_ex.fe_group,
2824 le16_add_cpu(&gdp->bg_free_blocks_count, -ac->ac_b_ex.fe_len);
2825 gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
2826 spin_unlock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
2827 percpu_counter_sub(&sbi->s_freeblocks_counter, ac->ac_b_ex.fe_len);
2829 err = ext4_journal_dirty_metadata(handle, bitmap_bh);
2832 err = ext4_journal_dirty_metadata(handle, gdp_bh);
2841 * here we normalize request for locality group
2842 * Group request are normalized to s_strip size if we set the same via mount
2843 * option. If not we set it to s_mb_group_prealloc which can be configured via
2844 * /proc/fs/ext4/<partition>/group_prealloc
2846 * XXX: should we try to preallocate more than the group has now?
2848 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
2850 struct super_block *sb = ac->ac_sb;
2851 struct ext4_locality_group *lg = ac->ac_lg;
2854 if (EXT4_SB(sb)->s_stripe)
2855 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_stripe;
2857 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
2858 mb_debug("#%u: goal %u blocks for locality group\n",
2859 current->pid, ac->ac_g_ex.fe_len);
2863 * Normalization means making request better in terms of
2864 * size and alignment
2866 static noinline_for_stack void
2867 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
2868 struct ext4_allocation_request *ar)
2872 loff_t size, orig_size, start_off;
2873 ext4_lblk_t start, orig_start;
2874 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
2875 struct ext4_prealloc_space *pa;
2877 /* do normalize only data requests, metadata requests
2878 do not need preallocation */
2879 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
2882 /* sometime caller may want exact blocks */
2883 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2886 /* caller may indicate that preallocation isn't
2887 * required (it's a tail, for example) */
2888 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
2891 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
2892 ext4_mb_normalize_group_request(ac);
2896 bsbits = ac->ac_sb->s_blocksize_bits;
2898 /* first, let's learn actual file size
2899 * given current request is allocated */
2900 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
2901 size = size << bsbits;
2902 if (size < i_size_read(ac->ac_inode))
2903 size = i_size_read(ac->ac_inode);
2905 /* max size of free chunks */
2908 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
2909 (req <= (size) || max <= (chunk_size))
2911 /* first, try to predict filesize */
2912 /* XXX: should this table be tunable? */
2914 if (size <= 16 * 1024) {
2916 } else if (size <= 32 * 1024) {
2918 } else if (size <= 64 * 1024) {
2920 } else if (size <= 128 * 1024) {
2922 } else if (size <= 256 * 1024) {
2924 } else if (size <= 512 * 1024) {
2926 } else if (size <= 1024 * 1024) {
2928 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
2929 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2930 (21 - bsbits)) << 21;
2931 size = 2 * 1024 * 1024;
2932 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
2933 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2934 (22 - bsbits)) << 22;
2935 size = 4 * 1024 * 1024;
2936 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
2937 (8<<20)>>bsbits, max, 8 * 1024)) {
2938 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2939 (23 - bsbits)) << 23;
2940 size = 8 * 1024 * 1024;
2942 start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
2943 size = ac->ac_o_ex.fe_len << bsbits;
2945 orig_size = size = size >> bsbits;
2946 orig_start = start = start_off >> bsbits;
2948 /* don't cover already allocated blocks in selected range */
2949 if (ar->pleft && start <= ar->lleft) {
2950 size -= ar->lleft + 1 - start;
2951 start = ar->lleft + 1;
2953 if (ar->pright && start + size - 1 >= ar->lright)
2954 size -= start + size - ar->lright;
2958 /* check we don't cross already preallocated blocks */
2960 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
2961 unsigned long pa_end;
2965 spin_lock(&pa->pa_lock);
2966 if (pa->pa_deleted) {
2967 spin_unlock(&pa->pa_lock);
2971 pa_end = pa->pa_lstart + pa->pa_len;
2973 /* PA must not overlap original request */
2974 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
2975 ac->ac_o_ex.fe_logical < pa->pa_lstart));
2977 /* skip PA normalized request doesn't overlap with */
2978 if (pa->pa_lstart >= end) {
2979 spin_unlock(&pa->pa_lock);
2982 if (pa_end <= start) {
2983 spin_unlock(&pa->pa_lock);
2986 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
2988 if (pa_end <= ac->ac_o_ex.fe_logical) {
2989 BUG_ON(pa_end < start);
2993 if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
2994 BUG_ON(pa->pa_lstart > end);
2995 end = pa->pa_lstart;
2997 spin_unlock(&pa->pa_lock);
3002 /* XXX: extra loop to check we really don't overlap preallocations */
3004 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3005 unsigned long pa_end;
3006 spin_lock(&pa->pa_lock);
3007 if (pa->pa_deleted == 0) {
3008 pa_end = pa->pa_lstart + pa->pa_len;
3009 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3011 spin_unlock(&pa->pa_lock);
3015 if (start + size <= ac->ac_o_ex.fe_logical &&
3016 start > ac->ac_o_ex.fe_logical) {
3017 printk(KERN_ERR "start %lu, size %lu, fe_logical %lu\n",
3018 (unsigned long) start, (unsigned long) size,
3019 (unsigned long) ac->ac_o_ex.fe_logical);
3021 BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3022 start > ac->ac_o_ex.fe_logical);
3023 BUG_ON(size <= 0 || size >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3025 /* now prepare goal request */
3027 /* XXX: is it better to align blocks WRT to logical
3028 * placement or satisfy big request as is */
3029 ac->ac_g_ex.fe_logical = start;
3030 ac->ac_g_ex.fe_len = size;
3032 /* define goal start in order to merge */
3033 if (ar->pright && (ar->lright == (start + size))) {
3034 /* merge to the right */
3035 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3036 &ac->ac_f_ex.fe_group,
3037 &ac->ac_f_ex.fe_start);
3038 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3040 if (ar->pleft && (ar->lleft + 1 == start)) {
3041 /* merge to the left */
3042 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3043 &ac->ac_f_ex.fe_group,
3044 &ac->ac_f_ex.fe_start);
3045 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3048 mb_debug("goal: %u(was %u) blocks at %u\n", (unsigned) size,
3049 (unsigned) orig_size, (unsigned) start);
3052 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3054 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3056 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3057 atomic_inc(&sbi->s_bal_reqs);
3058 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3059 if (ac->ac_o_ex.fe_len >= ac->ac_g_ex.fe_len)
3060 atomic_inc(&sbi->s_bal_success);
3061 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3062 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3063 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3064 atomic_inc(&sbi->s_bal_goals);
3065 if (ac->ac_found > sbi->s_mb_max_to_scan)
3066 atomic_inc(&sbi->s_bal_breaks);
3069 ext4_mb_store_history(ac);
3073 * use blocks preallocated to inode
3075 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3076 struct ext4_prealloc_space *pa)
3082 /* found preallocated blocks, use them */
3083 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3084 end = min(pa->pa_pstart + pa->pa_len, start + ac->ac_o_ex.fe_len);
3086 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3087 &ac->ac_b_ex.fe_start);
3088 ac->ac_b_ex.fe_len = len;
3089 ac->ac_status = AC_STATUS_FOUND;
3092 BUG_ON(start < pa->pa_pstart);
3093 BUG_ON(start + len > pa->pa_pstart + pa->pa_len);
3094 BUG_ON(pa->pa_free < len);
3097 mb_debug("use %llu/%u from inode pa %p\n", start, len, pa);
3101 * use blocks preallocated to locality group
3103 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3104 struct ext4_prealloc_space *pa)
3106 unsigned int len = ac->ac_o_ex.fe_len;
3107 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3108 &ac->ac_b_ex.fe_group,
3109 &ac->ac_b_ex.fe_start);
3110 ac->ac_b_ex.fe_len = len;
3111 ac->ac_status = AC_STATUS_FOUND;
3114 /* we don't correct pa_pstart or pa_plen here to avoid
3115 * possible race when the group is being loaded concurrently
3116 * instead we correct pa later, after blocks are marked
3117 * in on-disk bitmap -- see ext4_mb_release_context()
3118 * Other CPUs are prevented from allocating from this pa by lg_mutex
3120 mb_debug("use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3124 * search goal blocks in preallocated space
3126 static noinline_for_stack int
3127 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3129 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3130 struct ext4_locality_group *lg;
3131 struct ext4_prealloc_space *pa;
3133 /* only data can be preallocated */
3134 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3137 /* first, try per-file preallocation */
3139 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3141 /* all fields in this condition don't change,
3142 * so we can skip locking for them */
3143 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3144 ac->ac_o_ex.fe_logical >= pa->pa_lstart + pa->pa_len)
3147 /* found preallocated blocks, use them */
3148 spin_lock(&pa->pa_lock);
3149 if (pa->pa_deleted == 0 && pa->pa_free) {
3150 atomic_inc(&pa->pa_count);
3151 ext4_mb_use_inode_pa(ac, pa);
3152 spin_unlock(&pa->pa_lock);
3153 ac->ac_criteria = 10;
3157 spin_unlock(&pa->pa_lock);
3161 /* can we use group allocation? */
3162 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3165 /* inode may have no locality group for some reason */
3171 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list, pa_inode_list) {
3172 spin_lock(&pa->pa_lock);
3173 if (pa->pa_deleted == 0 && pa->pa_free >= ac->ac_o_ex.fe_len) {
3174 atomic_inc(&pa->pa_count);
3175 ext4_mb_use_group_pa(ac, pa);
3176 spin_unlock(&pa->pa_lock);
3177 ac->ac_criteria = 20;
3181 spin_unlock(&pa->pa_lock);
3189 * the function goes through all preallocation in this group and marks them
3190 * used in in-core bitmap. buddy must be generated from this bitmap
3191 * Need to be called with ext4 group lock (ext4_lock_group)
3193 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3196 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3197 struct ext4_prealloc_space *pa;
3198 struct list_head *cur;
3199 ext4_group_t groupnr;
3200 ext4_grpblk_t start;
3201 int preallocated = 0;
3205 /* all form of preallocation discards first load group,
3206 * so the only competing code is preallocation use.
3207 * we don't need any locking here
3208 * notice we do NOT ignore preallocations with pa_deleted
3209 * otherwise we could leave used blocks available for
3210 * allocation in buddy when concurrent ext4_mb_put_pa()
3211 * is dropping preallocation
3213 list_for_each(cur, &grp->bb_prealloc_list) {
3214 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3215 spin_lock(&pa->pa_lock);
3216 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3219 spin_unlock(&pa->pa_lock);
3220 if (unlikely(len == 0))
3222 BUG_ON(groupnr != group);
3223 mb_set_bits(sb_bgl_lock(EXT4_SB(sb), group),
3224 bitmap, start, len);
3225 preallocated += len;
3228 mb_debug("prellocated %u for group %lu\n", preallocated, group);
3231 static void ext4_mb_pa_callback(struct rcu_head *head)
3233 struct ext4_prealloc_space *pa;
3234 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3235 kmem_cache_free(ext4_pspace_cachep, pa);
3239 * drops a reference to preallocated space descriptor
3240 * if this was the last reference and the space is consumed
3242 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3243 struct super_block *sb, struct ext4_prealloc_space *pa)
3247 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3250 /* in this short window concurrent discard can set pa_deleted */
3251 spin_lock(&pa->pa_lock);
3252 if (pa->pa_deleted == 1) {
3253 spin_unlock(&pa->pa_lock);
3258 spin_unlock(&pa->pa_lock);
3260 /* -1 is to protect from crossing allocation group */
3261 ext4_get_group_no_and_offset(sb, pa->pa_pstart - 1, &grp, NULL);
3266 * P1 (buddy init) P2 (regular allocation)
3267 * find block B in PA
3268 * copy on-disk bitmap to buddy
3269 * mark B in on-disk bitmap
3270 * drop PA from group
3271 * mark all PAs in buddy
3273 * thus, P1 initializes buddy with B available. to prevent this
3274 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3277 ext4_lock_group(sb, grp);
3278 list_del(&pa->pa_group_list);
3279 ext4_unlock_group(sb, grp);
3281 spin_lock(pa->pa_obj_lock);
3282 list_del_rcu(&pa->pa_inode_list);
3283 spin_unlock(pa->pa_obj_lock);
3285 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3289 * creates new preallocated space for given inode
3291 static noinline_for_stack int
3292 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3294 struct super_block *sb = ac->ac_sb;
3295 struct ext4_prealloc_space *pa;
3296 struct ext4_group_info *grp;
3297 struct ext4_inode_info *ei;
3299 /* preallocate only when found space is larger then requested */
3300 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3301 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3302 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3304 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3308 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3314 /* we can't allocate as much as normalizer wants.
3315 * so, found space must get proper lstart
3316 * to cover original request */
3317 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3318 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3320 /* we're limited by original request in that
3321 * logical block must be covered any way
3322 * winl is window we can move our chunk within */
3323 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3325 /* also, we should cover whole original request */
3326 wins = ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len;
3328 /* the smallest one defines real window */
3329 win = min(winl, wins);
3331 offs = ac->ac_o_ex.fe_logical % ac->ac_b_ex.fe_len;
3332 if (offs && offs < win)
3335 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical - win;
3336 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3337 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3340 /* preallocation can change ac_b_ex, thus we store actually
3341 * allocated blocks for history */
3342 ac->ac_f_ex = ac->ac_b_ex;
3344 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3345 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3346 pa->pa_len = ac->ac_b_ex.fe_len;
3347 pa->pa_free = pa->pa_len;
3348 atomic_set(&pa->pa_count, 1);
3349 spin_lock_init(&pa->pa_lock);
3353 mb_debug("new inode pa %p: %llu/%u for %u\n", pa,
3354 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3356 ext4_mb_use_inode_pa(ac, pa);
3357 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3359 ei = EXT4_I(ac->ac_inode);
3360 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3362 pa->pa_obj_lock = &ei->i_prealloc_lock;
3363 pa->pa_inode = ac->ac_inode;
3365 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3366 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3367 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3369 spin_lock(pa->pa_obj_lock);
3370 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3371 spin_unlock(pa->pa_obj_lock);
3377 * creates new preallocated space for locality group inodes belongs to
3379 static noinline_for_stack int
3380 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3382 struct super_block *sb = ac->ac_sb;
3383 struct ext4_locality_group *lg;
3384 struct ext4_prealloc_space *pa;
3385 struct ext4_group_info *grp;
3387 /* preallocate only when found space is larger then requested */
3388 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3389 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3390 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3392 BUG_ON(ext4_pspace_cachep == NULL);
3393 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3397 /* preallocation can change ac_b_ex, thus we store actually
3398 * allocated blocks for history */
3399 ac->ac_f_ex = ac->ac_b_ex;
3401 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3402 pa->pa_lstart = pa->pa_pstart;
3403 pa->pa_len = ac->ac_b_ex.fe_len;
3404 pa->pa_free = pa->pa_len;
3405 atomic_set(&pa->pa_count, 1);
3406 spin_lock_init(&pa->pa_lock);
3410 mb_debug("new group pa %p: %llu/%u for %u\n", pa,
3411 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3413 ext4_mb_use_group_pa(ac, pa);
3414 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3416 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3420 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3421 pa->pa_inode = NULL;
3423 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3424 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3425 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3427 spin_lock(pa->pa_obj_lock);
3428 list_add_tail_rcu(&pa->pa_inode_list, &lg->lg_prealloc_list);
3429 spin_unlock(pa->pa_obj_lock);
3434 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3438 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3439 err = ext4_mb_new_group_pa(ac);
3441 err = ext4_mb_new_inode_pa(ac);
3446 * finds all unused blocks in on-disk bitmap, frees them in
3447 * in-core bitmap and buddy.
3448 * @pa must be unlinked from inode and group lists, so that
3449 * nobody else can find/use it.
3450 * the caller MUST hold group/inode locks.
3451 * TODO: optimize the case when there are no in-core structures yet
3453 static noinline_for_stack int
3454 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3455 struct ext4_prealloc_space *pa,
3456 struct ext4_allocation_context *ac)
3458 struct super_block *sb = e4b->bd_sb;
3459 struct ext4_sb_info *sbi = EXT4_SB(sb);
3468 BUG_ON(pa->pa_deleted == 0);
3469 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3470 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3471 end = bit + pa->pa_len;
3475 ac->ac_inode = pa->pa_inode;
3476 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3480 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3483 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3484 start = group * EXT4_BLOCKS_PER_GROUP(sb) + bit +
3485 le32_to_cpu(sbi->s_es->s_first_data_block);
3486 mb_debug(" free preallocated %u/%u in group %u\n",
3487 (unsigned) start, (unsigned) next - bit,
3492 ac->ac_b_ex.fe_group = group;
3493 ac->ac_b_ex.fe_start = bit;
3494 ac->ac_b_ex.fe_len = next - bit;
3495 ac->ac_b_ex.fe_logical = 0;
3496 ext4_mb_store_history(ac);
3499 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3502 if (free != pa->pa_free) {
3503 printk(KERN_CRIT "pa %p: logic %lu, phys. %lu, len %lu\n",
3504 pa, (unsigned long) pa->pa_lstart,
3505 (unsigned long) pa->pa_pstart,
3506 (unsigned long) pa->pa_len);
3507 ext4_error(sb, __func__, "free %u, pa_free %u\n",
3510 * pa is already deleted so we use the value obtained
3511 * from the bitmap and continue.
3514 atomic_add(free, &sbi->s_mb_discarded);
3519 static noinline_for_stack int
3520 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3521 struct ext4_prealloc_space *pa,
3522 struct ext4_allocation_context *ac)
3524 struct super_block *sb = e4b->bd_sb;
3529 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3531 BUG_ON(pa->pa_deleted == 0);
3532 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3533 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3534 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3535 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3539 ac->ac_inode = NULL;
3540 ac->ac_b_ex.fe_group = group;
3541 ac->ac_b_ex.fe_start = bit;
3542 ac->ac_b_ex.fe_len = pa->pa_len;
3543 ac->ac_b_ex.fe_logical = 0;
3544 ext4_mb_store_history(ac);
3551 * releases all preallocations in given group
3553 * first, we need to decide discard policy:
3554 * - when do we discard
3556 * - how many do we discard
3557 * 1) how many requested
3559 static noinline_for_stack int
3560 ext4_mb_discard_group_preallocations(struct super_block *sb,
3561 ext4_group_t group, int needed)
3563 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3564 struct buffer_head *bitmap_bh = NULL;
3565 struct ext4_prealloc_space *pa, *tmp;
3566 struct ext4_allocation_context *ac;
3567 struct list_head list;
3568 struct ext4_buddy e4b;
3573 mb_debug("discard preallocation for group %lu\n", group);
3575 if (list_empty(&grp->bb_prealloc_list))
3578 bitmap_bh = read_block_bitmap(sb, group);
3579 if (bitmap_bh == NULL) {
3580 /* error handling here */
3581 ext4_mb_release_desc(&e4b);
3582 BUG_ON(bitmap_bh == NULL);
3585 err = ext4_mb_load_buddy(sb, group, &e4b);
3586 BUG_ON(err != 0); /* error handling here */
3589 needed = EXT4_BLOCKS_PER_GROUP(sb) + 1;
3591 grp = ext4_get_group_info(sb, group);
3592 INIT_LIST_HEAD(&list);
3594 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
3596 ext4_lock_group(sb, group);
3597 list_for_each_entry_safe(pa, tmp,
3598 &grp->bb_prealloc_list, pa_group_list) {
3599 spin_lock(&pa->pa_lock);
3600 if (atomic_read(&pa->pa_count)) {
3601 spin_unlock(&pa->pa_lock);
3605 if (pa->pa_deleted) {
3606 spin_unlock(&pa->pa_lock);
3610 /* seems this one can be freed ... */
3613 /* we can trust pa_free ... */
3614 free += pa->pa_free;
3616 spin_unlock(&pa->pa_lock);
3618 list_del(&pa->pa_group_list);
3619 list_add(&pa->u.pa_tmp_list, &list);
3622 /* if we still need more blocks and some PAs were used, try again */
3623 if (free < needed && busy) {
3625 ext4_unlock_group(sb, group);
3627 * Yield the CPU here so that we don't get soft lockup
3628 * in non preempt case.
3634 /* found anything to free? */
3635 if (list_empty(&list)) {
3640 /* now free all selected PAs */
3641 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3643 /* remove from object (inode or locality group) */
3644 spin_lock(pa->pa_obj_lock);
3645 list_del_rcu(&pa->pa_inode_list);
3646 spin_unlock(pa->pa_obj_lock);
3649 ext4_mb_release_group_pa(&e4b, pa, ac);
3651 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
3653 list_del(&pa->u.pa_tmp_list);
3654 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3658 ext4_unlock_group(sb, group);
3660 kmem_cache_free(ext4_ac_cachep, ac);
3661 ext4_mb_release_desc(&e4b);
3667 * releases all non-used preallocated blocks for given inode
3669 * It's important to discard preallocations under i_data_sem
3670 * We don't want another block to be served from the prealloc
3671 * space when we are discarding the inode prealloc space.
3673 * FIXME!! Make sure it is valid at all the call sites
3675 void ext4_mb_discard_inode_preallocations(struct inode *inode)
3677 struct ext4_inode_info *ei = EXT4_I(inode);
3678 struct super_block *sb = inode->i_sb;
3679 struct buffer_head *bitmap_bh = NULL;
3680 struct ext4_prealloc_space *pa, *tmp;
3681 struct ext4_allocation_context *ac;
3682 ext4_group_t group = 0;
3683 struct list_head list;
3684 struct ext4_buddy e4b;
3687 if (!test_opt(sb, MBALLOC) || !S_ISREG(inode->i_mode)) {
3688 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
3692 mb_debug("discard preallocation for inode %lu\n", inode->i_ino);
3694 INIT_LIST_HEAD(&list);
3696 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
3698 /* first, collect all pa's in the inode */
3699 spin_lock(&ei->i_prealloc_lock);
3700 while (!list_empty(&ei->i_prealloc_list)) {
3701 pa = list_entry(ei->i_prealloc_list.next,
3702 struct ext4_prealloc_space, pa_inode_list);
3703 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
3704 spin_lock(&pa->pa_lock);
3705 if (atomic_read(&pa->pa_count)) {
3706 /* this shouldn't happen often - nobody should
3707 * use preallocation while we're discarding it */
3708 spin_unlock(&pa->pa_lock);
3709 spin_unlock(&ei->i_prealloc_lock);
3710 printk(KERN_ERR "uh-oh! used pa while discarding\n");
3712 schedule_timeout_uninterruptible(HZ);
3716 if (pa->pa_deleted == 0) {
3718 spin_unlock(&pa->pa_lock);
3719 list_del_rcu(&pa->pa_inode_list);
3720 list_add(&pa->u.pa_tmp_list, &list);
3724 /* someone is deleting pa right now */
3725 spin_unlock(&pa->pa_lock);
3726 spin_unlock(&ei->i_prealloc_lock);
3728 /* we have to wait here because pa_deleted
3729 * doesn't mean pa is already unlinked from
3730 * the list. as we might be called from
3731 * ->clear_inode() the inode will get freed
3732 * and concurrent thread which is unlinking
3733 * pa from inode's list may access already
3734 * freed memory, bad-bad-bad */
3736 /* XXX: if this happens too often, we can
3737 * add a flag to force wait only in case
3738 * of ->clear_inode(), but not in case of
3739 * regular truncate */
3740 schedule_timeout_uninterruptible(HZ);
3743 spin_unlock(&ei->i_prealloc_lock);
3745 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3746 BUG_ON(pa->pa_linear != 0);
3747 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
3749 err = ext4_mb_load_buddy(sb, group, &e4b);
3750 BUG_ON(err != 0); /* error handling here */
3752 bitmap_bh = read_block_bitmap(sb, group);
3753 if (bitmap_bh == NULL) {
3754 /* error handling here */
3755 ext4_mb_release_desc(&e4b);
3756 BUG_ON(bitmap_bh == NULL);
3759 ext4_lock_group(sb, group);
3760 list_del(&pa->pa_group_list);
3761 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
3762 ext4_unlock_group(sb, group);
3764 ext4_mb_release_desc(&e4b);
3767 list_del(&pa->u.pa_tmp_list);
3768 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3771 kmem_cache_free(ext4_ac_cachep, ac);
3775 * finds all preallocated spaces and return blocks being freed to them
3776 * if preallocated space becomes full (no block is used from the space)
3777 * then the function frees space in buddy
3778 * XXX: at the moment, truncate (which is the only way to free blocks)
3779 * discards all preallocations
3781 static void ext4_mb_return_to_preallocation(struct inode *inode,
3782 struct ext4_buddy *e4b,
3783 sector_t block, int count)
3785 BUG_ON(!list_empty(&EXT4_I(inode)->i_prealloc_list));
3788 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3790 struct super_block *sb = ac->ac_sb;
3793 printk(KERN_ERR "EXT4-fs: Can't allocate:"
3794 " Allocation context details:\n");
3795 printk(KERN_ERR "EXT4-fs: status %d flags %d\n",
3796 ac->ac_status, ac->ac_flags);
3797 printk(KERN_ERR "EXT4-fs: orig %lu/%lu/%lu@%lu, goal %lu/%lu/%lu@%lu, "
3798 "best %lu/%lu/%lu@%lu cr %d\n",
3799 (unsigned long)ac->ac_o_ex.fe_group,
3800 (unsigned long)ac->ac_o_ex.fe_start,
3801 (unsigned long)ac->ac_o_ex.fe_len,
3802 (unsigned long)ac->ac_o_ex.fe_logical,
3803 (unsigned long)ac->ac_g_ex.fe_group,
3804 (unsigned long)ac->ac_g_ex.fe_start,
3805 (unsigned long)ac->ac_g_ex.fe_len,
3806 (unsigned long)ac->ac_g_ex.fe_logical,
3807 (unsigned long)ac->ac_b_ex.fe_group,
3808 (unsigned long)ac->ac_b_ex.fe_start,
3809 (unsigned long)ac->ac_b_ex.fe_len,
3810 (unsigned long)ac->ac_b_ex.fe_logical,
3811 (int)ac->ac_criteria);
3812 printk(KERN_ERR "EXT4-fs: %lu scanned, %d found\n", ac->ac_ex_scanned,
3814 printk(KERN_ERR "EXT4-fs: groups: \n");
3815 for (i = 0; i < EXT4_SB(sb)->s_groups_count; i++) {
3816 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3817 struct ext4_prealloc_space *pa;
3818 ext4_grpblk_t start;
3819 struct list_head *cur;
3820 ext4_lock_group(sb, i);
3821 list_for_each(cur, &grp->bb_prealloc_list) {
3822 pa = list_entry(cur, struct ext4_prealloc_space,
3824 spin_lock(&pa->pa_lock);
3825 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3827 spin_unlock(&pa->pa_lock);
3828 printk(KERN_ERR "PA:%lu:%d:%u \n", i,
3831 ext4_unlock_group(sb, i);
3833 if (grp->bb_free == 0)
3835 printk(KERN_ERR "%lu: %d/%d \n",
3836 i, grp->bb_free, grp->bb_fragments);
3838 printk(KERN_ERR "\n");
3841 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3848 * We use locality group preallocation for small size file. The size of the
3849 * file is determined by the current size or the resulting size after
3850 * allocation which ever is larger
3852 * One can tune this size via /proc/fs/ext4/<partition>/stream_req
3854 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
3856 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3857 int bsbits = ac->ac_sb->s_blocksize_bits;
3860 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3863 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
3864 isize = i_size_read(ac->ac_inode) >> bsbits;
3865 size = max(size, isize);
3867 /* don't use group allocation for large files */
3868 if (size >= sbi->s_mb_stream_request)
3871 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3874 BUG_ON(ac->ac_lg != NULL);
3876 * locality group prealloc space are per cpu. The reason for having
3877 * per cpu locality group is to reduce the contention between block
3878 * request from multiple CPUs.
3880 ac->ac_lg = &sbi->s_locality_groups[get_cpu()];
3883 /* we're going to use group allocation */
3884 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
3886 /* serialize all allocations in the group */
3887 mutex_lock(&ac->ac_lg->lg_mutex);
3890 static noinline_for_stack int
3891 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
3892 struct ext4_allocation_request *ar)
3894 struct super_block *sb = ar->inode->i_sb;
3895 struct ext4_sb_info *sbi = EXT4_SB(sb);
3896 struct ext4_super_block *es = sbi->s_es;
3900 ext4_grpblk_t block;
3902 /* we can't allocate > group size */
3905 /* just a dirty hack to filter too big requests */
3906 if (len >= EXT4_BLOCKS_PER_GROUP(sb) - 10)
3907 len = EXT4_BLOCKS_PER_GROUP(sb) - 10;
3909 /* start searching from the goal */
3911 if (goal < le32_to_cpu(es->s_first_data_block) ||
3912 goal >= ext4_blocks_count(es))
3913 goal = le32_to_cpu(es->s_first_data_block);
3914 ext4_get_group_no_and_offset(sb, goal, &group, &block);
3916 /* set up allocation goals */
3917 ac->ac_b_ex.fe_logical = ar->logical;
3918 ac->ac_b_ex.fe_group = 0;
3919 ac->ac_b_ex.fe_start = 0;
3920 ac->ac_b_ex.fe_len = 0;
3921 ac->ac_status = AC_STATUS_CONTINUE;
3922 ac->ac_groups_scanned = 0;
3923 ac->ac_ex_scanned = 0;
3926 ac->ac_inode = ar->inode;
3927 ac->ac_o_ex.fe_logical = ar->logical;
3928 ac->ac_o_ex.fe_group = group;
3929 ac->ac_o_ex.fe_start = block;
3930 ac->ac_o_ex.fe_len = len;
3931 ac->ac_g_ex.fe_logical = ar->logical;
3932 ac->ac_g_ex.fe_group = group;
3933 ac->ac_g_ex.fe_start = block;
3934 ac->ac_g_ex.fe_len = len;
3935 ac->ac_f_ex.fe_len = 0;
3936 ac->ac_flags = ar->flags;
3938 ac->ac_criteria = 0;
3940 ac->ac_bitmap_page = NULL;
3941 ac->ac_buddy_page = NULL;
3944 /* we have to define context: we'll we work with a file or
3945 * locality group. this is a policy, actually */
3946 ext4_mb_group_or_file(ac);
3948 mb_debug("init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
3949 "left: %u/%u, right %u/%u to %swritable\n",
3950 (unsigned) ar->len, (unsigned) ar->logical,
3951 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
3952 (unsigned) ar->lleft, (unsigned) ar->pleft,
3953 (unsigned) ar->lright, (unsigned) ar->pright,
3954 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
3960 * release all resource we used in allocation
3962 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
3965 if (ac->ac_pa->pa_linear) {
3966 /* see comment in ext4_mb_use_group_pa() */
3967 spin_lock(&ac->ac_pa->pa_lock);
3968 ac->ac_pa->pa_pstart += ac->ac_b_ex.fe_len;
3969 ac->ac_pa->pa_lstart += ac->ac_b_ex.fe_len;
3970 ac->ac_pa->pa_free -= ac->ac_b_ex.fe_len;
3971 ac->ac_pa->pa_len -= ac->ac_b_ex.fe_len;
3972 spin_unlock(&ac->ac_pa->pa_lock);
3974 ext4_mb_put_pa(ac, ac->ac_sb, ac->ac_pa);
3976 if (ac->ac_bitmap_page)
3977 page_cache_release(ac->ac_bitmap_page);
3978 if (ac->ac_buddy_page)
3979 page_cache_release(ac->ac_buddy_page);
3980 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3981 mutex_unlock(&ac->ac_lg->lg_mutex);
3982 ext4_mb_collect_stats(ac);
3986 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
3992 for (i = 0; i < EXT4_SB(sb)->s_groups_count && needed > 0; i++) {
3993 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4002 * Main entry point into mballoc to allocate blocks
4003 * it tries to use preallocation first, then falls back
4004 * to usual allocation
4006 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4007 struct ext4_allocation_request *ar, int *errp)
4009 struct ext4_allocation_context *ac = NULL;
4010 struct ext4_sb_info *sbi;
4011 struct super_block *sb;
4012 ext4_fsblk_t block = 0;
4016 sb = ar->inode->i_sb;
4019 if (!test_opt(sb, MBALLOC)) {
4020 block = ext4_new_blocks_old(handle, ar->inode, ar->goal,
4025 while (ar->len && DQUOT_ALLOC_BLOCK(ar->inode, ar->len)) {
4026 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4035 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4041 ext4_mb_poll_new_transaction(sb, handle);
4043 *errp = ext4_mb_initialize_context(ac, ar);
4049 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4050 if (!ext4_mb_use_preallocated(ac)) {
4052 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4053 ext4_mb_normalize_request(ac, ar);
4055 /* allocate space in core */
4056 ext4_mb_regular_allocator(ac);
4058 /* as we've just preallocated more space than
4059 * user requested orinally, we store allocated
4060 * space in a special descriptor */
4061 if (ac->ac_status == AC_STATUS_FOUND &&
4062 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4063 ext4_mb_new_preallocation(ac);
4066 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4067 *errp = ext4_mb_mark_diskspace_used(ac, handle);
4068 if (*errp == -EAGAIN) {
4069 ac->ac_b_ex.fe_group = 0;
4070 ac->ac_b_ex.fe_start = 0;
4071 ac->ac_b_ex.fe_len = 0;
4072 ac->ac_status = AC_STATUS_CONTINUE;
4075 ac->ac_b_ex.fe_len = 0;
4077 ext4_mb_show_ac(ac);
4079 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4080 ar->len = ac->ac_b_ex.fe_len;
4083 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4087 ac->ac_b_ex.fe_len = 0;
4089 ext4_mb_show_ac(ac);
4092 ext4_mb_release_context(ac);
4095 if (ar->len < inquota)
4096 DQUOT_FREE_BLOCK(ar->inode, inquota - ar->len);
4098 kmem_cache_free(ext4_ac_cachep, ac);
4101 static void ext4_mb_poll_new_transaction(struct super_block *sb,
4104 struct ext4_sb_info *sbi = EXT4_SB(sb);
4106 if (sbi->s_last_transaction == handle->h_transaction->t_tid)
4109 /* new transaction! time to close last one and free blocks for
4110 * committed transaction. we know that only transaction can be
4111 * active, so previos transaction can be being logged and we
4112 * know that transaction before previous is known to be already
4113 * logged. this means that now we may free blocks freed in all
4114 * transactions before previous one. hope I'm clear enough ... */
4116 spin_lock(&sbi->s_md_lock);
4117 if (sbi->s_last_transaction != handle->h_transaction->t_tid) {
4118 mb_debug("new transaction %lu, old %lu\n",
4119 (unsigned long) handle->h_transaction->t_tid,
4120 (unsigned long) sbi->s_last_transaction);
4121 list_splice_init(&sbi->s_closed_transaction,
4122 &sbi->s_committed_transaction);
4123 list_splice_init(&sbi->s_active_transaction,
4124 &sbi->s_closed_transaction);
4125 sbi->s_last_transaction = handle->h_transaction->t_tid;
4127 spin_unlock(&sbi->s_md_lock);
4129 ext4_mb_free_committed_blocks(sb);
4132 static noinline_for_stack int
4133 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4134 ext4_group_t group, ext4_grpblk_t block, int count)
4136 struct ext4_group_info *db = e4b->bd_info;
4137 struct super_block *sb = e4b->bd_sb;
4138 struct ext4_sb_info *sbi = EXT4_SB(sb);
4139 struct ext4_free_metadata *md;
4142 BUG_ON(e4b->bd_bitmap_page == NULL);
4143 BUG_ON(e4b->bd_buddy_page == NULL);
4145 ext4_lock_group(sb, group);
4146 for (i = 0; i < count; i++) {
4148 if (md && db->bb_tid != handle->h_transaction->t_tid) {
4149 db->bb_md_cur = NULL;
4154 ext4_unlock_group(sb, group);
4155 md = kmalloc(sizeof(*md), GFP_NOFS);
4161 ext4_lock_group(sb, group);
4162 if (db->bb_md_cur == NULL) {
4163 spin_lock(&sbi->s_md_lock);
4164 list_add(&md->list, &sbi->s_active_transaction);
4165 spin_unlock(&sbi->s_md_lock);
4166 /* protect buddy cache from being freed,
4167 * otherwise we'll refresh it from
4168 * on-disk bitmap and lose not-yet-available
4170 page_cache_get(e4b->bd_buddy_page);
4171 page_cache_get(e4b->bd_bitmap_page);
4173 db->bb_tid = handle->h_transaction->t_tid;
4174 mb_debug("new md 0x%p for group %lu\n",
4182 BUG_ON(md->num >= EXT4_BB_MAX_BLOCKS);
4183 md->blocks[md->num] = block + i;
4185 if (md->num == EXT4_BB_MAX_BLOCKS) {
4186 /* no more space, put full container on a sb's list */
4187 db->bb_md_cur = NULL;
4190 ext4_unlock_group(sb, group);
4195 * Main entry point into mballoc to free blocks
4197 void ext4_mb_free_blocks(handle_t *handle, struct inode *inode,
4198 unsigned long block, unsigned long count,
4199 int metadata, unsigned long *freed)
4201 struct buffer_head *bitmap_bh = NULL;
4202 struct super_block *sb = inode->i_sb;
4203 struct ext4_allocation_context *ac = NULL;
4204 struct ext4_group_desc *gdp;
4205 struct ext4_super_block *es;
4206 unsigned long overflow;
4208 struct buffer_head *gd_bh;
4209 ext4_group_t block_group;
4210 struct ext4_sb_info *sbi;
4211 struct ext4_buddy e4b;
4217 ext4_mb_poll_new_transaction(sb, handle);
4220 es = EXT4_SB(sb)->s_es;
4221 if (block < le32_to_cpu(es->s_first_data_block) ||
4222 block + count < block ||
4223 block + count > ext4_blocks_count(es)) {
4224 ext4_error(sb, __func__,
4225 "Freeing blocks not in datazone - "
4226 "block = %lu, count = %lu", block, count);
4230 ext4_debug("freeing block %lu\n", block);
4232 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4234 ac->ac_op = EXT4_MB_HISTORY_FREE;
4235 ac->ac_inode = inode;
4241 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4244 * Check to see if we are freeing blocks across a group
4247 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4248 overflow = bit + count - EXT4_BLOCKS_PER_GROUP(sb);
4251 bitmap_bh = read_block_bitmap(sb, block_group);
4254 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4258 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4259 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4260 in_range(block, ext4_inode_table(sb, gdp),
4261 EXT4_SB(sb)->s_itb_per_group) ||
4262 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4263 EXT4_SB(sb)->s_itb_per_group)) {
4265 ext4_error(sb, __func__,
4266 "Freeing blocks in system zone - "
4267 "Block = %lu, count = %lu", block, count);
4268 /* err = 0. ext4_std_error should be a no op */
4272 BUFFER_TRACE(bitmap_bh, "getting write access");
4273 err = ext4_journal_get_write_access(handle, bitmap_bh);
4278 * We are about to modify some metadata. Call the journal APIs
4279 * to unshare ->b_data if a currently-committing transaction is
4282 BUFFER_TRACE(gd_bh, "get_write_access");
4283 err = ext4_journal_get_write_access(handle, gd_bh);
4287 err = ext4_mb_load_buddy(sb, block_group, &e4b);
4291 #ifdef AGGRESSIVE_CHECK
4294 for (i = 0; i < count; i++)
4295 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4298 mb_clear_bits(sb_bgl_lock(sbi, block_group), bitmap_bh->b_data,
4301 /* We dirtied the bitmap block */
4302 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4303 err = ext4_journal_dirty_metadata(handle, bitmap_bh);
4306 ac->ac_b_ex.fe_group = block_group;
4307 ac->ac_b_ex.fe_start = bit;
4308 ac->ac_b_ex.fe_len = count;
4309 ext4_mb_store_history(ac);
4313 /* blocks being freed are metadata. these blocks shouldn't
4314 * be used until this transaction is committed */
4315 ext4_mb_free_metadata(handle, &e4b, block_group, bit, count);
4317 ext4_lock_group(sb, block_group);
4318 err = mb_free_blocks(inode, &e4b, bit, count);
4319 ext4_mb_return_to_preallocation(inode, &e4b, block, count);
4320 ext4_unlock_group(sb, block_group);
4324 spin_lock(sb_bgl_lock(sbi, block_group));
4325 le16_add_cpu(&gdp->bg_free_blocks_count, count);
4326 gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4327 spin_unlock(sb_bgl_lock(sbi, block_group));
4328 percpu_counter_add(&sbi->s_freeblocks_counter, count);
4330 ext4_mb_release_desc(&e4b);
4334 /* And the group descriptor block */
4335 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4336 ret = ext4_journal_dirty_metadata(handle, gd_bh);
4340 if (overflow && !err) {
4349 ext4_std_error(sb, err);
4351 kmem_cache_free(ext4_ac_cachep, ac);