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)
385 addr = mb_correct_addr_and_bit(&fix, addr);
389 return ext4_find_next_zero_bit(addr, max, start) - fix;
392 static inline int mb_find_next_bit(void *addr, int max, int start)
395 addr = mb_correct_addr_and_bit(&fix, addr);
399 return ext4_find_next_bit(addr, max, start) - fix;
402 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
406 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
409 if (order > e4b->bd_blkbits + 1) {
414 /* at order 0 we see each particular block */
415 *max = 1 << (e4b->bd_blkbits + 3);
417 return EXT4_MB_BITMAP(e4b);
419 bb = EXT4_MB_BUDDY(e4b) + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
420 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
426 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
427 int first, int count)
430 struct super_block *sb = e4b->bd_sb;
432 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
434 BUG_ON(!ext4_is_group_locked(sb, e4b->bd_group));
435 for (i = 0; i < count; i++) {
436 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
437 ext4_fsblk_t blocknr;
438 blocknr = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb);
439 blocknr += first + i;
441 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
443 ext4_error(sb, __func__, "double-free of inode"
444 " %lu's block %llu(bit %u in group %lu)\n",
445 inode ? inode->i_ino : 0, blocknr,
446 first + i, e4b->bd_group);
448 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
452 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
456 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
458 BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
459 for (i = 0; i < count; i++) {
460 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
461 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
465 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
467 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
468 unsigned char *b1, *b2;
470 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
471 b2 = (unsigned char *) bitmap;
472 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
473 if (b1[i] != b2[i]) {
474 printk("corruption in group %lu at byte %u(%u):"
475 " %x in copy != %x on disk/prealloc\n",
476 e4b->bd_group, i, i * 8, b1[i], b2[i]);
484 static inline void mb_free_blocks_double(struct inode *inode,
485 struct ext4_buddy *e4b, int first, int count)
489 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
490 int first, int count)
494 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
500 #ifdef AGGRESSIVE_CHECK
502 #define MB_CHECK_ASSERT(assert) \
506 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
507 function, file, line, # assert); \
512 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
513 const char *function, int line)
515 struct super_block *sb = e4b->bd_sb;
516 int order = e4b->bd_blkbits + 1;
523 struct ext4_group_info *grp;
526 struct list_head *cur;
530 if (!test_opt(sb, MBALLOC))
534 static int mb_check_counter;
535 if (mb_check_counter++ % 100 != 0)
540 buddy = mb_find_buddy(e4b, order, &max);
541 MB_CHECK_ASSERT(buddy);
542 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
543 MB_CHECK_ASSERT(buddy2);
544 MB_CHECK_ASSERT(buddy != buddy2);
545 MB_CHECK_ASSERT(max * 2 == max2);
548 for (i = 0; i < max; i++) {
550 if (mb_test_bit(i, buddy)) {
551 /* only single bit in buddy2 may be 1 */
552 if (!mb_test_bit(i << 1, buddy2)) {
554 mb_test_bit((i<<1)+1, buddy2));
555 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
557 mb_test_bit(i << 1, buddy2));
562 /* both bits in buddy2 must be 0 */
563 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
564 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
566 for (j = 0; j < (1 << order); j++) {
567 k = (i * (1 << order)) + j;
569 !mb_test_bit(k, EXT4_MB_BITMAP(e4b)));
573 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
578 buddy = mb_find_buddy(e4b, 0, &max);
579 for (i = 0; i < max; i++) {
580 if (!mb_test_bit(i, buddy)) {
581 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
589 /* check used bits only */
590 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
591 buddy2 = mb_find_buddy(e4b, j, &max2);
593 MB_CHECK_ASSERT(k < max2);
594 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
597 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
598 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
600 grp = ext4_get_group_info(sb, e4b->bd_group);
601 buddy = mb_find_buddy(e4b, 0, &max);
602 list_for_each(cur, &grp->bb_prealloc_list) {
603 ext4_group_t groupnr;
604 struct ext4_prealloc_space *pa;
605 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
606 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
607 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
608 for (i = 0; i < pa->pa_len; i++)
609 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
613 #undef MB_CHECK_ASSERT
614 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
615 __FILE__, __func__, __LINE__)
617 #define mb_check_buddy(e4b)
620 /* FIXME!! need more doc */
621 static void ext4_mb_mark_free_simple(struct super_block *sb,
622 void *buddy, unsigned first, int len,
623 struct ext4_group_info *grp)
625 struct ext4_sb_info *sbi = EXT4_SB(sb);
628 unsigned short chunk;
629 unsigned short border;
631 BUG_ON(len > EXT4_BLOCKS_PER_GROUP(sb));
633 border = 2 << sb->s_blocksize_bits;
636 /* find how many blocks can be covered since this position */
637 max = ffs(first | border) - 1;
639 /* find how many blocks of power 2 we need to mark */
646 /* mark multiblock chunks only */
647 grp->bb_counters[min]++;
649 mb_clear_bit(first >> min,
650 buddy + sbi->s_mb_offsets[min]);
657 static void ext4_mb_generate_buddy(struct super_block *sb,
658 void *buddy, void *bitmap, ext4_group_t group)
660 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
661 unsigned short max = EXT4_BLOCKS_PER_GROUP(sb);
662 unsigned short i = 0;
663 unsigned short first;
666 unsigned fragments = 0;
667 unsigned long long period = get_cycles();
669 /* initialize buddy from bitmap which is aggregation
670 * of on-disk bitmap and preallocations */
671 i = mb_find_next_zero_bit(bitmap, max, 0);
672 grp->bb_first_free = i;
676 i = mb_find_next_bit(bitmap, max, i);
680 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
682 grp->bb_counters[0]++;
684 i = mb_find_next_zero_bit(bitmap, max, i);
686 grp->bb_fragments = fragments;
688 if (free != grp->bb_free) {
689 ext4_error(sb, __func__,
690 "EXT4-fs: group %lu: %u blocks in bitmap, %u in gd\n",
691 group, free, grp->bb_free);
693 * If we intent to continue, we consider group descritor
694 * corrupt and update bb_free using bitmap value
699 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
701 period = get_cycles() - period;
702 spin_lock(&EXT4_SB(sb)->s_bal_lock);
703 EXT4_SB(sb)->s_mb_buddies_generated++;
704 EXT4_SB(sb)->s_mb_generation_time += period;
705 spin_unlock(&EXT4_SB(sb)->s_bal_lock);
708 /* The buddy information is attached the buddy cache inode
709 * for convenience. The information regarding each group
710 * is loaded via ext4_mb_load_buddy. The information involve
711 * block bitmap and buddy information. The information are
712 * stored in the inode as
715 * [ group 0 buddy][ group 0 bitmap] [group 1][ group 1]...
718 * one block each for bitmap and buddy information.
719 * So for each group we take up 2 blocks. A page can
720 * contain blocks_per_page (PAGE_CACHE_SIZE / blocksize) blocks.
721 * So it can have information regarding groups_per_page which
722 * is blocks_per_page/2
725 static int ext4_mb_init_cache(struct page *page, char *incore)
732 ext4_group_t first_group;
734 struct super_block *sb;
735 struct buffer_head *bhs;
736 struct buffer_head **bh;
741 mb_debug("init page %lu\n", page->index);
743 inode = page->mapping->host;
745 blocksize = 1 << inode->i_blkbits;
746 blocks_per_page = PAGE_CACHE_SIZE / blocksize;
748 groups_per_page = blocks_per_page >> 1;
749 if (groups_per_page == 0)
752 /* allocate buffer_heads to read bitmaps */
753 if (groups_per_page > 1) {
755 i = sizeof(struct buffer_head *) * groups_per_page;
756 bh = kzalloc(i, GFP_NOFS);
762 first_group = page->index * blocks_per_page / 2;
764 /* read all groups the page covers into the cache */
765 for (i = 0; i < groups_per_page; i++) {
766 struct ext4_group_desc *desc;
768 if (first_group + i >= EXT4_SB(sb)->s_groups_count)
772 desc = ext4_get_group_desc(sb, first_group + i, NULL);
777 bh[i] = sb_getblk(sb, ext4_block_bitmap(sb, desc));
781 if (bh_uptodate_or_lock(bh[i]))
784 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
785 ext4_init_block_bitmap(sb, bh[i],
786 first_group + i, desc);
787 set_buffer_uptodate(bh[i]);
788 unlock_buffer(bh[i]);
792 bh[i]->b_end_io = end_buffer_read_sync;
793 submit_bh(READ, bh[i]);
794 mb_debug("read bitmap for group %lu\n", first_group + i);
797 /* wait for I/O completion */
798 for (i = 0; i < groups_per_page && bh[i]; i++)
799 wait_on_buffer(bh[i]);
802 for (i = 0; i < groups_per_page && bh[i]; i++)
803 if (!buffer_uptodate(bh[i]))
806 first_block = page->index * blocks_per_page;
807 for (i = 0; i < blocks_per_page; i++) {
809 struct ext4_group_info *grinfo;
811 group = (first_block + i) >> 1;
812 if (group >= EXT4_SB(sb)->s_groups_count)
816 * data carry information regarding this
817 * particular group in the format specified
821 data = page_address(page) + (i * blocksize);
822 bitmap = bh[group - first_group]->b_data;
825 * We place the buddy block and bitmap block
828 if ((first_block + i) & 1) {
829 /* this is block of buddy */
830 BUG_ON(incore == NULL);
831 mb_debug("put buddy for group %u in page %lu/%x\n",
832 group, page->index, i * blocksize);
833 memset(data, 0xff, blocksize);
834 grinfo = ext4_get_group_info(sb, group);
835 grinfo->bb_fragments = 0;
836 memset(grinfo->bb_counters, 0,
837 sizeof(unsigned short)*(sb->s_blocksize_bits+2));
839 * incore got set to the group block bitmap below
841 ext4_mb_generate_buddy(sb, data, incore, group);
844 /* this is block of bitmap */
845 BUG_ON(incore != NULL);
846 mb_debug("put bitmap for group %u in page %lu/%x\n",
847 group, page->index, i * blocksize);
849 /* see comments in ext4_mb_put_pa() */
850 ext4_lock_group(sb, group);
851 memcpy(data, bitmap, blocksize);
853 /* mark all preallocated blks used in in-core bitmap */
854 ext4_mb_generate_from_pa(sb, data, group);
855 ext4_unlock_group(sb, group);
857 /* set incore so that the buddy information can be
858 * generated using this
863 SetPageUptodate(page);
867 for (i = 0; i < groups_per_page && bh[i]; i++)
875 static noinline_for_stack int
876 ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
877 struct ext4_buddy *e4b)
879 struct ext4_sb_info *sbi = EXT4_SB(sb);
880 struct inode *inode = sbi->s_buddy_cache;
887 mb_debug("load group %lu\n", group);
889 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
891 e4b->bd_blkbits = sb->s_blocksize_bits;
892 e4b->bd_info = ext4_get_group_info(sb, group);
894 e4b->bd_group = group;
895 e4b->bd_buddy_page = NULL;
896 e4b->bd_bitmap_page = NULL;
899 * the buddy cache inode stores the block bitmap
900 * and buddy information in consecutive blocks.
901 * So for each group we need two blocks.
904 pnum = block / blocks_per_page;
905 poff = block % blocks_per_page;
907 /* we could use find_or_create_page(), but it locks page
908 * what we'd like to avoid in fast path ... */
909 page = find_get_page(inode->i_mapping, pnum);
910 if (page == NULL || !PageUptodate(page)) {
912 page_cache_release(page);
913 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
915 BUG_ON(page->mapping != inode->i_mapping);
916 if (!PageUptodate(page)) {
917 ext4_mb_init_cache(page, NULL);
918 mb_cmp_bitmaps(e4b, page_address(page) +
919 (poff * sb->s_blocksize));
924 if (page == NULL || !PageUptodate(page))
926 e4b->bd_bitmap_page = page;
927 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
928 mark_page_accessed(page);
931 pnum = block / blocks_per_page;
932 poff = block % blocks_per_page;
934 page = find_get_page(inode->i_mapping, pnum);
935 if (page == NULL || !PageUptodate(page)) {
937 page_cache_release(page);
938 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
940 BUG_ON(page->mapping != inode->i_mapping);
941 if (!PageUptodate(page))
942 ext4_mb_init_cache(page, e4b->bd_bitmap);
947 if (page == NULL || !PageUptodate(page))
949 e4b->bd_buddy_page = page;
950 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
951 mark_page_accessed(page);
953 BUG_ON(e4b->bd_bitmap_page == NULL);
954 BUG_ON(e4b->bd_buddy_page == NULL);
959 if (e4b->bd_bitmap_page)
960 page_cache_release(e4b->bd_bitmap_page);
961 if (e4b->bd_buddy_page)
962 page_cache_release(e4b->bd_buddy_page);
963 e4b->bd_buddy = NULL;
964 e4b->bd_bitmap = NULL;
968 static void ext4_mb_release_desc(struct ext4_buddy *e4b)
970 if (e4b->bd_bitmap_page)
971 page_cache_release(e4b->bd_bitmap_page);
972 if (e4b->bd_buddy_page)
973 page_cache_release(e4b->bd_buddy_page);
977 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
982 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
983 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
985 bb = EXT4_MB_BUDDY(e4b);
986 while (order <= e4b->bd_blkbits + 1) {
988 if (!mb_test_bit(block, bb)) {
989 /* this block is part of buddy of order 'order' */
992 bb += 1 << (e4b->bd_blkbits - order);
998 static void mb_clear_bits(spinlock_t *lock, void *bm, int cur, int len)
1004 if ((cur & 31) == 0 && (len - cur) >= 32) {
1005 /* fast path: clear whole word at once */
1006 addr = bm + (cur >> 3);
1011 mb_clear_bit_atomic(lock, cur, bm);
1016 static void mb_set_bits(spinlock_t *lock, void *bm, int cur, int len)
1022 if ((cur & 31) == 0 && (len - cur) >= 32) {
1023 /* fast path: set whole word at once */
1024 addr = bm + (cur >> 3);
1029 mb_set_bit_atomic(lock, cur, bm);
1034 static int mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1035 int first, int count)
1042 struct super_block *sb = e4b->bd_sb;
1044 BUG_ON(first + count > (sb->s_blocksize << 3));
1045 BUG_ON(!ext4_is_group_locked(sb, e4b->bd_group));
1046 mb_check_buddy(e4b);
1047 mb_free_blocks_double(inode, e4b, first, count);
1049 e4b->bd_info->bb_free += count;
1050 if (first < e4b->bd_info->bb_first_free)
1051 e4b->bd_info->bb_first_free = first;
1053 /* let's maintain fragments counter */
1055 block = !mb_test_bit(first - 1, EXT4_MB_BITMAP(e4b));
1056 if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
1057 max = !mb_test_bit(first + count, EXT4_MB_BITMAP(e4b));
1059 e4b->bd_info->bb_fragments--;
1060 else if (!block && !max)
1061 e4b->bd_info->bb_fragments++;
1063 /* let's maintain buddy itself */
1064 while (count-- > 0) {
1068 if (!mb_test_bit(block, EXT4_MB_BITMAP(e4b))) {
1069 ext4_fsblk_t blocknr;
1070 blocknr = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb);
1073 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
1075 ext4_error(sb, __func__, "double-free of inode"
1076 " %lu's block %llu(bit %u in group %lu)\n",
1077 inode ? inode->i_ino : 0, blocknr, block,
1080 mb_clear_bit(block, EXT4_MB_BITMAP(e4b));
1081 e4b->bd_info->bb_counters[order]++;
1083 /* start of the buddy */
1084 buddy = mb_find_buddy(e4b, order, &max);
1088 if (mb_test_bit(block, buddy) ||
1089 mb_test_bit(block + 1, buddy))
1092 /* both the buddies are free, try to coalesce them */
1093 buddy2 = mb_find_buddy(e4b, order + 1, &max);
1099 /* for special purposes, we don't set
1100 * free bits in bitmap */
1101 mb_set_bit(block, buddy);
1102 mb_set_bit(block + 1, buddy);
1104 e4b->bd_info->bb_counters[order]--;
1105 e4b->bd_info->bb_counters[order]--;
1109 e4b->bd_info->bb_counters[order]++;
1111 mb_clear_bit(block, buddy2);
1115 mb_check_buddy(e4b);
1120 static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
1121 int needed, struct ext4_free_extent *ex)
1128 BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
1131 buddy = mb_find_buddy(e4b, order, &max);
1132 BUG_ON(buddy == NULL);
1133 BUG_ON(block >= max);
1134 if (mb_test_bit(block, buddy)) {
1141 /* FIXME dorp order completely ? */
1142 if (likely(order == 0)) {
1143 /* find actual order */
1144 order = mb_find_order_for_block(e4b, block);
1145 block = block >> order;
1148 ex->fe_len = 1 << order;
1149 ex->fe_start = block << order;
1150 ex->fe_group = e4b->bd_group;
1152 /* calc difference from given start */
1153 next = next - ex->fe_start;
1155 ex->fe_start += next;
1157 while (needed > ex->fe_len &&
1158 (buddy = mb_find_buddy(e4b, order, &max))) {
1160 if (block + 1 >= max)
1163 next = (block + 1) * (1 << order);
1164 if (mb_test_bit(next, EXT4_MB_BITMAP(e4b)))
1167 ord = mb_find_order_for_block(e4b, next);
1170 block = next >> order;
1171 ex->fe_len += 1 << order;
1174 BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1178 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1184 int start = ex->fe_start;
1185 int len = ex->fe_len;
1190 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1191 BUG_ON(e4b->bd_group != ex->fe_group);
1192 BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
1193 mb_check_buddy(e4b);
1194 mb_mark_used_double(e4b, start, len);
1196 e4b->bd_info->bb_free -= len;
1197 if (e4b->bd_info->bb_first_free == start)
1198 e4b->bd_info->bb_first_free += len;
1200 /* let's maintain fragments counter */
1202 mlen = !mb_test_bit(start - 1, EXT4_MB_BITMAP(e4b));
1203 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1204 max = !mb_test_bit(start + len, EXT4_MB_BITMAP(e4b));
1206 e4b->bd_info->bb_fragments++;
1207 else if (!mlen && !max)
1208 e4b->bd_info->bb_fragments--;
1210 /* let's maintain buddy itself */
1212 ord = mb_find_order_for_block(e4b, start);
1214 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1215 /* the whole chunk may be allocated at once! */
1217 buddy = mb_find_buddy(e4b, ord, &max);
1218 BUG_ON((start >> ord) >= max);
1219 mb_set_bit(start >> ord, buddy);
1220 e4b->bd_info->bb_counters[ord]--;
1227 /* store for history */
1229 ret = len | (ord << 16);
1231 /* we have to split large buddy */
1233 buddy = mb_find_buddy(e4b, ord, &max);
1234 mb_set_bit(start >> ord, buddy);
1235 e4b->bd_info->bb_counters[ord]--;
1238 cur = (start >> ord) & ~1U;
1239 buddy = mb_find_buddy(e4b, ord, &max);
1240 mb_clear_bit(cur, buddy);
1241 mb_clear_bit(cur + 1, buddy);
1242 e4b->bd_info->bb_counters[ord]++;
1243 e4b->bd_info->bb_counters[ord]++;
1246 mb_set_bits(sb_bgl_lock(EXT4_SB(e4b->bd_sb), ex->fe_group),
1247 EXT4_MB_BITMAP(e4b), ex->fe_start, len0);
1248 mb_check_buddy(e4b);
1254 * Must be called under group lock!
1256 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1257 struct ext4_buddy *e4b)
1259 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1262 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1263 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1265 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1266 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1267 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1269 /* preallocation can change ac_b_ex, thus we store actually
1270 * allocated blocks for history */
1271 ac->ac_f_ex = ac->ac_b_ex;
1273 ac->ac_status = AC_STATUS_FOUND;
1274 ac->ac_tail = ret & 0xffff;
1275 ac->ac_buddy = ret >> 16;
1277 /* XXXXXXX: SUCH A HORRIBLE **CK */
1279 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1280 get_page(ac->ac_bitmap_page);
1281 ac->ac_buddy_page = e4b->bd_buddy_page;
1282 get_page(ac->ac_buddy_page);
1284 /* store last allocated for subsequent stream allocation */
1285 if ((ac->ac_flags & EXT4_MB_HINT_DATA)) {
1286 spin_lock(&sbi->s_md_lock);
1287 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1288 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1289 spin_unlock(&sbi->s_md_lock);
1294 * regular allocator, for general purposes allocation
1297 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1298 struct ext4_buddy *e4b,
1301 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1302 struct ext4_free_extent *bex = &ac->ac_b_ex;
1303 struct ext4_free_extent *gex = &ac->ac_g_ex;
1304 struct ext4_free_extent ex;
1308 * We don't want to scan for a whole year
1310 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1311 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1312 ac->ac_status = AC_STATUS_BREAK;
1317 * Haven't found good chunk so far, let's continue
1319 if (bex->fe_len < gex->fe_len)
1322 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1323 && bex->fe_group == e4b->bd_group) {
1324 /* recheck chunk's availability - we don't know
1325 * when it was found (within this lock-unlock
1327 max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
1328 if (max >= gex->fe_len) {
1329 ext4_mb_use_best_found(ac, e4b);
1336 * The routine checks whether found extent is good enough. If it is,
1337 * then the extent gets marked used and flag is set to the context
1338 * to stop scanning. Otherwise, the extent is compared with the
1339 * previous found extent and if new one is better, then it's stored
1340 * in the context. Later, the best found extent will be used, if
1341 * mballoc can't find good enough extent.
1343 * FIXME: real allocation policy is to be designed yet!
1345 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1346 struct ext4_free_extent *ex,
1347 struct ext4_buddy *e4b)
1349 struct ext4_free_extent *bex = &ac->ac_b_ex;
1350 struct ext4_free_extent *gex = &ac->ac_g_ex;
1352 BUG_ON(ex->fe_len <= 0);
1353 BUG_ON(ex->fe_len >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1354 BUG_ON(ex->fe_start >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1355 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1360 * The special case - take what you catch first
1362 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1364 ext4_mb_use_best_found(ac, e4b);
1369 * Let's check whether the chuck is good enough
1371 if (ex->fe_len == gex->fe_len) {
1373 ext4_mb_use_best_found(ac, e4b);
1378 * If this is first found extent, just store it in the context
1380 if (bex->fe_len == 0) {
1386 * If new found extent is better, store it in the context
1388 if (bex->fe_len < gex->fe_len) {
1389 /* if the request isn't satisfied, any found extent
1390 * larger than previous best one is better */
1391 if (ex->fe_len > bex->fe_len)
1393 } else if (ex->fe_len > gex->fe_len) {
1394 /* if the request is satisfied, then we try to find
1395 * an extent that still satisfy the request, but is
1396 * smaller than previous one */
1397 if (ex->fe_len < bex->fe_len)
1401 ext4_mb_check_limits(ac, e4b, 0);
1404 static int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1405 struct ext4_buddy *e4b)
1407 struct ext4_free_extent ex = ac->ac_b_ex;
1408 ext4_group_t group = ex.fe_group;
1412 BUG_ON(ex.fe_len <= 0);
1413 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1417 ext4_lock_group(ac->ac_sb, group);
1418 max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
1422 ext4_mb_use_best_found(ac, e4b);
1425 ext4_unlock_group(ac->ac_sb, group);
1426 ext4_mb_release_desc(e4b);
1431 static int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1432 struct ext4_buddy *e4b)
1434 ext4_group_t group = ac->ac_g_ex.fe_group;
1437 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1438 struct ext4_super_block *es = sbi->s_es;
1439 struct ext4_free_extent ex;
1441 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1444 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1448 ext4_lock_group(ac->ac_sb, group);
1449 max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
1450 ac->ac_g_ex.fe_len, &ex);
1452 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1455 start = (e4b->bd_group * EXT4_BLOCKS_PER_GROUP(ac->ac_sb)) +
1456 ex.fe_start + le32_to_cpu(es->s_first_data_block);
1457 /* use do_div to get remainder (would be 64-bit modulo) */
1458 if (do_div(start, sbi->s_stripe) == 0) {
1461 ext4_mb_use_best_found(ac, e4b);
1463 } else if (max >= ac->ac_g_ex.fe_len) {
1464 BUG_ON(ex.fe_len <= 0);
1465 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1466 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1469 ext4_mb_use_best_found(ac, e4b);
1470 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1471 /* Sometimes, caller may want to merge even small
1472 * number of blocks to an existing extent */
1473 BUG_ON(ex.fe_len <= 0);
1474 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1475 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1478 ext4_mb_use_best_found(ac, e4b);
1480 ext4_unlock_group(ac->ac_sb, group);
1481 ext4_mb_release_desc(e4b);
1487 * The routine scans buddy structures (not bitmap!) from given order
1488 * to max order and tries to find big enough chunk to satisfy the req
1490 static void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1491 struct ext4_buddy *e4b)
1493 struct super_block *sb = ac->ac_sb;
1494 struct ext4_group_info *grp = e4b->bd_info;
1500 BUG_ON(ac->ac_2order <= 0);
1501 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1502 if (grp->bb_counters[i] == 0)
1505 buddy = mb_find_buddy(e4b, i, &max);
1506 BUG_ON(buddy == NULL);
1508 k = mb_find_next_zero_bit(buddy, max, 0);
1513 ac->ac_b_ex.fe_len = 1 << i;
1514 ac->ac_b_ex.fe_start = k << i;
1515 ac->ac_b_ex.fe_group = e4b->bd_group;
1517 ext4_mb_use_best_found(ac, e4b);
1519 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1521 if (EXT4_SB(sb)->s_mb_stats)
1522 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1529 * The routine scans the group and measures all found extents.
1530 * In order to optimize scanning, caller must pass number of
1531 * free blocks in the group, so the routine can know upper limit.
1533 static void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1534 struct ext4_buddy *e4b)
1536 struct super_block *sb = ac->ac_sb;
1537 void *bitmap = EXT4_MB_BITMAP(e4b);
1538 struct ext4_free_extent ex;
1542 free = e4b->bd_info->bb_free;
1545 i = e4b->bd_info->bb_first_free;
1547 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1548 i = mb_find_next_zero_bit(bitmap,
1549 EXT4_BLOCKS_PER_GROUP(sb), i);
1550 if (i >= EXT4_BLOCKS_PER_GROUP(sb)) {
1552 * IF we have corrupt bitmap, we won't find any
1553 * free blocks even though group info says we
1554 * we have free blocks
1556 ext4_error(sb, __func__, "%d free blocks as per "
1557 "group info. But bitmap says 0\n",
1562 mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
1563 BUG_ON(ex.fe_len <= 0);
1564 if (free < ex.fe_len) {
1565 ext4_error(sb, __func__, "%d free blocks as per "
1566 "group info. But got %d blocks\n",
1569 * The number of free blocks differs. This mostly
1570 * indicate that the bitmap is corrupt. So exit
1571 * without claiming the space.
1576 ext4_mb_measure_extent(ac, &ex, e4b);
1582 ext4_mb_check_limits(ac, e4b, 1);
1586 * This is a special case for storages like raid5
1587 * we try to find stripe-aligned chunks for stripe-size requests
1588 * XXX should do so at least for multiples of stripe size as well
1590 static void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1591 struct ext4_buddy *e4b)
1593 struct super_block *sb = ac->ac_sb;
1594 struct ext4_sb_info *sbi = EXT4_SB(sb);
1595 void *bitmap = EXT4_MB_BITMAP(e4b);
1596 struct ext4_free_extent ex;
1597 ext4_fsblk_t first_group_block;
1602 BUG_ON(sbi->s_stripe == 0);
1604 /* find first stripe-aligned block in group */
1605 first_group_block = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb)
1606 + le32_to_cpu(sbi->s_es->s_first_data_block);
1607 a = first_group_block + sbi->s_stripe - 1;
1608 do_div(a, sbi->s_stripe);
1609 i = (a * sbi->s_stripe) - first_group_block;
1611 while (i < EXT4_BLOCKS_PER_GROUP(sb)) {
1612 if (!mb_test_bit(i, bitmap)) {
1613 max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
1614 if (max >= sbi->s_stripe) {
1617 ext4_mb_use_best_found(ac, e4b);
1625 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
1626 ext4_group_t group, int cr)
1628 unsigned free, fragments;
1630 struct ext4_group_desc *desc;
1631 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1633 BUG_ON(cr < 0 || cr >= 4);
1634 BUG_ON(EXT4_MB_GRP_NEED_INIT(grp));
1636 free = grp->bb_free;
1637 fragments = grp->bb_fragments;
1645 BUG_ON(ac->ac_2order == 0);
1646 /* If this group is uninitialized, skip it initially */
1647 desc = ext4_get_group_desc(ac->ac_sb, group, NULL);
1648 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))
1651 bits = ac->ac_sb->s_blocksize_bits + 1;
1652 for (i = ac->ac_2order; i <= bits; i++)
1653 if (grp->bb_counters[i] > 0)
1657 if ((free / fragments) >= ac->ac_g_ex.fe_len)
1661 if (free >= ac->ac_g_ex.fe_len)
1673 static noinline_for_stack int
1674 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
1681 struct ext4_sb_info *sbi;
1682 struct super_block *sb;
1683 struct ext4_buddy e4b;
1688 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1690 /* first, try the goal */
1691 err = ext4_mb_find_by_goal(ac, &e4b);
1692 if (err || ac->ac_status == AC_STATUS_FOUND)
1695 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
1699 * ac->ac2_order is set only if the fe_len is a power of 2
1700 * if ac2_order is set we also set criteria to 0 so that we
1701 * try exact allocation using buddy.
1703 i = fls(ac->ac_g_ex.fe_len);
1706 * We search using buddy data only if the order of the request
1707 * is greater than equal to the sbi_s_mb_order2_reqs
1708 * You can tune it via /proc/fs/ext4/<partition>/order2_req
1710 if (i >= sbi->s_mb_order2_reqs) {
1712 * This should tell if fe_len is exactly power of 2
1714 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
1715 ac->ac_2order = i - 1;
1718 bsbits = ac->ac_sb->s_blocksize_bits;
1719 /* if stream allocation is enabled, use global goal */
1720 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
1721 isize = i_size_read(ac->ac_inode) >> bsbits;
1725 if (size < sbi->s_mb_stream_request &&
1726 (ac->ac_flags & EXT4_MB_HINT_DATA)) {
1727 /* TBD: may be hot point */
1728 spin_lock(&sbi->s_md_lock);
1729 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
1730 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
1731 spin_unlock(&sbi->s_md_lock);
1734 /* searching for the right group start from the goal value specified */
1735 group = ac->ac_g_ex.fe_group;
1737 /* Let's just scan groups to find more-less suitable blocks */
1738 cr = ac->ac_2order ? 0 : 1;
1740 * cr == 0 try to get exact allocation,
1741 * cr == 3 try to get anything
1744 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
1745 ac->ac_criteria = cr;
1746 for (i = 0; i < EXT4_SB(sb)->s_groups_count; group++, i++) {
1747 struct ext4_group_info *grp;
1748 struct ext4_group_desc *desc;
1750 if (group == EXT4_SB(sb)->s_groups_count)
1753 /* quick check to skip empty groups */
1754 grp = ext4_get_group_info(ac->ac_sb, group);
1755 if (grp->bb_free == 0)
1759 * if the group is already init we check whether it is
1760 * a good group and if not we don't load the buddy
1762 if (EXT4_MB_GRP_NEED_INIT(grp)) {
1764 * we need full data about the group
1765 * to make a good selection
1767 err = ext4_mb_load_buddy(sb, group, &e4b);
1770 ext4_mb_release_desc(&e4b);
1774 * If the particular group doesn't satisfy our
1775 * criteria we continue with the next group
1777 if (!ext4_mb_good_group(ac, group, cr))
1780 err = ext4_mb_load_buddy(sb, group, &e4b);
1784 ext4_lock_group(sb, group);
1785 if (!ext4_mb_good_group(ac, group, cr)) {
1786 /* someone did allocation from this group */
1787 ext4_unlock_group(sb, group);
1788 ext4_mb_release_desc(&e4b);
1792 ac->ac_groups_scanned++;
1793 desc = ext4_get_group_desc(sb, group, NULL);
1794 if (cr == 0 || (desc->bg_flags &
1795 cpu_to_le16(EXT4_BG_BLOCK_UNINIT) &&
1796 ac->ac_2order != 0))
1797 ext4_mb_simple_scan_group(ac, &e4b);
1799 ac->ac_g_ex.fe_len == sbi->s_stripe)
1800 ext4_mb_scan_aligned(ac, &e4b);
1802 ext4_mb_complex_scan_group(ac, &e4b);
1804 ext4_unlock_group(sb, group);
1805 ext4_mb_release_desc(&e4b);
1807 if (ac->ac_status != AC_STATUS_CONTINUE)
1812 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
1813 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1815 * We've been searching too long. Let's try to allocate
1816 * the best chunk we've found so far
1819 ext4_mb_try_best_found(ac, &e4b);
1820 if (ac->ac_status != AC_STATUS_FOUND) {
1822 * Someone more lucky has already allocated it.
1823 * The only thing we can do is just take first
1825 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
1827 ac->ac_b_ex.fe_group = 0;
1828 ac->ac_b_ex.fe_start = 0;
1829 ac->ac_b_ex.fe_len = 0;
1830 ac->ac_status = AC_STATUS_CONTINUE;
1831 ac->ac_flags |= EXT4_MB_HINT_FIRST;
1833 atomic_inc(&sbi->s_mb_lost_chunks);
1841 #ifdef EXT4_MB_HISTORY
1842 struct ext4_mb_proc_session {
1843 struct ext4_mb_history *history;
1844 struct super_block *sb;
1849 static void *ext4_mb_history_skip_empty(struct ext4_mb_proc_session *s,
1850 struct ext4_mb_history *hs,
1853 if (hs == s->history + s->max)
1855 if (!first && hs == s->history + s->start)
1857 while (hs->orig.fe_len == 0) {
1859 if (hs == s->history + s->max)
1861 if (hs == s->history + s->start)
1867 static void *ext4_mb_seq_history_start(struct seq_file *seq, loff_t *pos)
1869 struct ext4_mb_proc_session *s = seq->private;
1870 struct ext4_mb_history *hs;
1874 return SEQ_START_TOKEN;
1875 hs = ext4_mb_history_skip_empty(s, s->history + s->start, 1);
1878 while (--l && (hs = ext4_mb_history_skip_empty(s, ++hs, 0)) != NULL);
1882 static void *ext4_mb_seq_history_next(struct seq_file *seq, void *v,
1885 struct ext4_mb_proc_session *s = seq->private;
1886 struct ext4_mb_history *hs = v;
1889 if (v == SEQ_START_TOKEN)
1890 return ext4_mb_history_skip_empty(s, s->history + s->start, 1);
1892 return ext4_mb_history_skip_empty(s, ++hs, 0);
1895 static int ext4_mb_seq_history_show(struct seq_file *seq, void *v)
1897 char buf[25], buf2[25], buf3[25], *fmt;
1898 struct ext4_mb_history *hs = v;
1900 if (v == SEQ_START_TOKEN) {
1901 seq_printf(seq, "%-5s %-8s %-23s %-23s %-23s %-5s "
1902 "%-5s %-2s %-5s %-5s %-5s %-6s\n",
1903 "pid", "inode", "original", "goal", "result", "found",
1904 "grps", "cr", "flags", "merge", "tail", "broken");
1908 if (hs->op == EXT4_MB_HISTORY_ALLOC) {
1909 fmt = "%-5u %-8u %-23s %-23s %-23s %-5u %-5u %-2u "
1910 "%-5u %-5s %-5u %-6u\n";
1911 sprintf(buf2, "%lu/%d/%u@%u", hs->result.fe_group,
1912 hs->result.fe_start, hs->result.fe_len,
1913 hs->result.fe_logical);
1914 sprintf(buf, "%lu/%d/%u@%u", hs->orig.fe_group,
1915 hs->orig.fe_start, hs->orig.fe_len,
1916 hs->orig.fe_logical);
1917 sprintf(buf3, "%lu/%d/%u@%u", hs->goal.fe_group,
1918 hs->goal.fe_start, hs->goal.fe_len,
1919 hs->goal.fe_logical);
1920 seq_printf(seq, fmt, hs->pid, hs->ino, buf, buf3, buf2,
1921 hs->found, hs->groups, hs->cr, hs->flags,
1922 hs->merged ? "M" : "", hs->tail,
1923 hs->buddy ? 1 << hs->buddy : 0);
1924 } else if (hs->op == EXT4_MB_HISTORY_PREALLOC) {
1925 fmt = "%-5u %-8u %-23s %-23s %-23s\n";
1926 sprintf(buf2, "%lu/%d/%u@%u", hs->result.fe_group,
1927 hs->result.fe_start, hs->result.fe_len,
1928 hs->result.fe_logical);
1929 sprintf(buf, "%lu/%d/%u@%u", hs->orig.fe_group,
1930 hs->orig.fe_start, hs->orig.fe_len,
1931 hs->orig.fe_logical);
1932 seq_printf(seq, fmt, hs->pid, hs->ino, buf, "", buf2);
1933 } else if (hs->op == EXT4_MB_HISTORY_DISCARD) {
1934 sprintf(buf2, "%lu/%d/%u", hs->result.fe_group,
1935 hs->result.fe_start, hs->result.fe_len);
1936 seq_printf(seq, "%-5u %-8u %-23s discard\n",
1937 hs->pid, hs->ino, buf2);
1938 } else if (hs->op == EXT4_MB_HISTORY_FREE) {
1939 sprintf(buf2, "%lu/%d/%u", hs->result.fe_group,
1940 hs->result.fe_start, hs->result.fe_len);
1941 seq_printf(seq, "%-5u %-8u %-23s free\n",
1942 hs->pid, hs->ino, buf2);
1947 static void ext4_mb_seq_history_stop(struct seq_file *seq, void *v)
1951 static struct seq_operations ext4_mb_seq_history_ops = {
1952 .start = ext4_mb_seq_history_start,
1953 .next = ext4_mb_seq_history_next,
1954 .stop = ext4_mb_seq_history_stop,
1955 .show = ext4_mb_seq_history_show,
1958 static int ext4_mb_seq_history_open(struct inode *inode, struct file *file)
1960 struct super_block *sb = PDE(inode)->data;
1961 struct ext4_sb_info *sbi = EXT4_SB(sb);
1962 struct ext4_mb_proc_session *s;
1966 s = kmalloc(sizeof(*s), GFP_KERNEL);
1970 size = sizeof(struct ext4_mb_history) * sbi->s_mb_history_max;
1971 s->history = kmalloc(size, GFP_KERNEL);
1972 if (s->history == NULL) {
1977 spin_lock(&sbi->s_mb_history_lock);
1978 memcpy(s->history, sbi->s_mb_history, size);
1979 s->max = sbi->s_mb_history_max;
1980 s->start = sbi->s_mb_history_cur % s->max;
1981 spin_unlock(&sbi->s_mb_history_lock);
1983 rc = seq_open(file, &ext4_mb_seq_history_ops);
1985 struct seq_file *m = (struct seq_file *)file->private_data;
1995 static int ext4_mb_seq_history_release(struct inode *inode, struct file *file)
1997 struct seq_file *seq = (struct seq_file *)file->private_data;
1998 struct ext4_mb_proc_session *s = seq->private;
2001 return seq_release(inode, file);
2004 static ssize_t ext4_mb_seq_history_write(struct file *file,
2005 const char __user *buffer,
2006 size_t count, loff_t *ppos)
2008 struct seq_file *seq = (struct seq_file *)file->private_data;
2009 struct ext4_mb_proc_session *s = seq->private;
2010 struct super_block *sb = s->sb;
2014 if (count >= sizeof(str)) {
2015 printk(KERN_ERR "EXT4-fs: %s string too long, max %u bytes\n",
2016 "mb_history", (int)sizeof(str));
2020 if (copy_from_user(str, buffer, count))
2023 value = simple_strtol(str, NULL, 0);
2026 EXT4_SB(sb)->s_mb_history_filter = value;
2031 static struct file_operations ext4_mb_seq_history_fops = {
2032 .owner = THIS_MODULE,
2033 .open = ext4_mb_seq_history_open,
2035 .write = ext4_mb_seq_history_write,
2036 .llseek = seq_lseek,
2037 .release = ext4_mb_seq_history_release,
2040 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2042 struct super_block *sb = seq->private;
2043 struct ext4_sb_info *sbi = EXT4_SB(sb);
2046 if (*pos < 0 || *pos >= sbi->s_groups_count)
2050 return (void *) group;
2053 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2055 struct super_block *sb = seq->private;
2056 struct ext4_sb_info *sbi = EXT4_SB(sb);
2060 if (*pos < 0 || *pos >= sbi->s_groups_count)
2063 return (void *) group;;
2066 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2068 struct super_block *sb = seq->private;
2069 long group = (long) v;
2072 struct ext4_buddy e4b;
2074 struct ext4_group_info info;
2075 unsigned short counters[16];
2080 seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
2081 "[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2082 "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2083 "group", "free", "frags", "first",
2084 "2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
2085 "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2087 i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2088 sizeof(struct ext4_group_info);
2089 err = ext4_mb_load_buddy(sb, group, &e4b);
2091 seq_printf(seq, "#%-5lu: I/O error\n", group);
2094 ext4_lock_group(sb, group);
2095 memcpy(&sg, ext4_get_group_info(sb, group), i);
2096 ext4_unlock_group(sb, group);
2097 ext4_mb_release_desc(&e4b);
2099 seq_printf(seq, "#%-5lu: %-5u %-5u %-5u [", group, sg.info.bb_free,
2100 sg.info.bb_fragments, sg.info.bb_first_free);
2101 for (i = 0; i <= 13; i++)
2102 seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2103 sg.info.bb_counters[i] : 0);
2104 seq_printf(seq, " ]\n");
2109 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2113 static struct seq_operations ext4_mb_seq_groups_ops = {
2114 .start = ext4_mb_seq_groups_start,
2115 .next = ext4_mb_seq_groups_next,
2116 .stop = ext4_mb_seq_groups_stop,
2117 .show = ext4_mb_seq_groups_show,
2120 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2122 struct super_block *sb = PDE(inode)->data;
2125 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2127 struct seq_file *m = (struct seq_file *)file->private_data;
2134 static struct file_operations ext4_mb_seq_groups_fops = {
2135 .owner = THIS_MODULE,
2136 .open = ext4_mb_seq_groups_open,
2138 .llseek = seq_lseek,
2139 .release = seq_release,
2142 static void ext4_mb_history_release(struct super_block *sb)
2144 struct ext4_sb_info *sbi = EXT4_SB(sb);
2146 remove_proc_entry("mb_groups", sbi->s_mb_proc);
2147 remove_proc_entry("mb_history", sbi->s_mb_proc);
2149 kfree(sbi->s_mb_history);
2152 static void ext4_mb_history_init(struct super_block *sb)
2154 struct ext4_sb_info *sbi = EXT4_SB(sb);
2157 if (sbi->s_mb_proc != NULL) {
2158 proc_create_data("mb_history", S_IRUGO, sbi->s_mb_proc,
2159 &ext4_mb_seq_history_fops, sb);
2160 proc_create_data("mb_groups", S_IRUGO, sbi->s_mb_proc,
2161 &ext4_mb_seq_groups_fops, sb);
2164 sbi->s_mb_history_max = 1000;
2165 sbi->s_mb_history_cur = 0;
2166 spin_lock_init(&sbi->s_mb_history_lock);
2167 i = sbi->s_mb_history_max * sizeof(struct ext4_mb_history);
2168 sbi->s_mb_history = kmalloc(i, GFP_KERNEL);
2169 if (likely(sbi->s_mb_history != NULL))
2170 memset(sbi->s_mb_history, 0, i);
2171 /* if we can't allocate history, then we simple won't use it */
2174 static noinline_for_stack void
2175 ext4_mb_store_history(struct ext4_allocation_context *ac)
2177 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2178 struct ext4_mb_history h;
2180 if (unlikely(sbi->s_mb_history == NULL))
2183 if (!(ac->ac_op & sbi->s_mb_history_filter))
2187 h.pid = current->pid;
2188 h.ino = ac->ac_inode ? ac->ac_inode->i_ino : 0;
2189 h.orig = ac->ac_o_ex;
2190 h.result = ac->ac_b_ex;
2191 h.flags = ac->ac_flags;
2192 h.found = ac->ac_found;
2193 h.groups = ac->ac_groups_scanned;
2194 h.cr = ac->ac_criteria;
2195 h.tail = ac->ac_tail;
2196 h.buddy = ac->ac_buddy;
2198 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC) {
2199 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
2200 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
2202 h.goal = ac->ac_g_ex;
2203 h.result = ac->ac_f_ex;
2206 spin_lock(&sbi->s_mb_history_lock);
2207 memcpy(sbi->s_mb_history + sbi->s_mb_history_cur, &h, sizeof(h));
2208 if (++sbi->s_mb_history_cur >= sbi->s_mb_history_max)
2209 sbi->s_mb_history_cur = 0;
2210 spin_unlock(&sbi->s_mb_history_lock);
2214 #define ext4_mb_history_release(sb)
2215 #define ext4_mb_history_init(sb)
2218 static int ext4_mb_init_backend(struct super_block *sb)
2221 int j, len, metalen;
2222 struct ext4_sb_info *sbi = EXT4_SB(sb);
2223 int num_meta_group_infos =
2224 (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) >>
2225 EXT4_DESC_PER_BLOCK_BITS(sb);
2226 struct ext4_group_info **meta_group_info;
2228 /* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2229 * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2230 * So a two level scheme suffices for now. */
2231 sbi->s_group_info = kmalloc(sizeof(*sbi->s_group_info) *
2232 num_meta_group_infos, GFP_KERNEL);
2233 if (sbi->s_group_info == NULL) {
2234 printk(KERN_ERR "EXT4-fs: can't allocate buddy meta group\n");
2237 sbi->s_buddy_cache = new_inode(sb);
2238 if (sbi->s_buddy_cache == NULL) {
2239 printk(KERN_ERR "EXT4-fs: can't get new inode\n");
2242 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2244 metalen = sizeof(*meta_group_info) << EXT4_DESC_PER_BLOCK_BITS(sb);
2245 for (i = 0; i < num_meta_group_infos; i++) {
2246 if ((i + 1) == num_meta_group_infos)
2247 metalen = sizeof(*meta_group_info) *
2248 (sbi->s_groups_count -
2249 (i << EXT4_DESC_PER_BLOCK_BITS(sb)));
2250 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2251 if (meta_group_info == NULL) {
2252 printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2256 sbi->s_group_info[i] = meta_group_info;
2260 * calculate needed size. if change bb_counters size,
2261 * don't forget about ext4_mb_generate_buddy()
2263 len = sizeof(struct ext4_group_info);
2264 len += sizeof(unsigned short) * (sb->s_blocksize_bits + 2);
2265 for (i = 0; i < sbi->s_groups_count; i++) {
2266 struct ext4_group_desc *desc;
2269 sbi->s_group_info[i >> EXT4_DESC_PER_BLOCK_BITS(sb)];
2270 j = i & (EXT4_DESC_PER_BLOCK(sb) - 1);
2272 meta_group_info[j] = kzalloc(len, GFP_KERNEL);
2273 if (meta_group_info[j] == NULL) {
2274 printk(KERN_ERR "EXT4-fs: can't allocate buddy mem\n");
2277 desc = ext4_get_group_desc(sb, i, NULL);
2280 "EXT4-fs: can't read descriptor %lu\n", i);
2284 memset(meta_group_info[j], 0, len);
2285 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2286 &(meta_group_info[j]->bb_state));
2289 * initialize bb_free to be able to skip
2290 * empty groups without initialization
2292 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2293 meta_group_info[j]->bb_free =
2294 ext4_free_blocks_after_init(sb, i, desc);
2296 meta_group_info[j]->bb_free =
2297 le16_to_cpu(desc->bg_free_blocks_count);
2300 INIT_LIST_HEAD(&meta_group_info[j]->bb_prealloc_list);
2304 struct buffer_head *bh;
2305 meta_group_info[j]->bb_bitmap =
2306 kmalloc(sb->s_blocksize, GFP_KERNEL);
2307 BUG_ON(meta_group_info[j]->bb_bitmap == NULL);
2308 bh = read_block_bitmap(sb, i);
2310 memcpy(meta_group_info[j]->bb_bitmap, bh->b_data,
2322 kfree(ext4_get_group_info(sb, i));
2323 i = num_meta_group_infos;
2326 kfree(sbi->s_group_info[i]);
2327 iput(sbi->s_buddy_cache);
2329 kfree(sbi->s_group_info);
2333 int ext4_mb_init(struct super_block *sb, int needs_recovery)
2335 struct ext4_sb_info *sbi = EXT4_SB(sb);
2340 if (!test_opt(sb, MBALLOC))
2343 i = (sb->s_blocksize_bits + 2) * sizeof(unsigned short);
2345 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2346 if (sbi->s_mb_offsets == NULL) {
2347 clear_opt(sbi->s_mount_opt, MBALLOC);
2350 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2351 if (sbi->s_mb_maxs == NULL) {
2352 clear_opt(sbi->s_mount_opt, MBALLOC);
2353 kfree(sbi->s_mb_maxs);
2357 /* order 0 is regular bitmap */
2358 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2359 sbi->s_mb_offsets[0] = 0;
2363 max = sb->s_blocksize << 2;
2365 sbi->s_mb_offsets[i] = offset;
2366 sbi->s_mb_maxs[i] = max;
2367 offset += 1 << (sb->s_blocksize_bits - i);
2370 } while (i <= sb->s_blocksize_bits + 1);
2372 /* init file for buddy data */
2373 i = ext4_mb_init_backend(sb);
2375 clear_opt(sbi->s_mount_opt, MBALLOC);
2376 kfree(sbi->s_mb_offsets);
2377 kfree(sbi->s_mb_maxs);
2381 spin_lock_init(&sbi->s_md_lock);
2382 INIT_LIST_HEAD(&sbi->s_active_transaction);
2383 INIT_LIST_HEAD(&sbi->s_closed_transaction);
2384 INIT_LIST_HEAD(&sbi->s_committed_transaction);
2385 spin_lock_init(&sbi->s_bal_lock);
2387 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2388 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2389 sbi->s_mb_stats = MB_DEFAULT_STATS;
2390 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2391 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2392 sbi->s_mb_history_filter = EXT4_MB_HISTORY_DEFAULT;
2393 sbi->s_mb_group_prealloc = MB_DEFAULT_GROUP_PREALLOC;
2395 i = sizeof(struct ext4_locality_group) * NR_CPUS;
2396 sbi->s_locality_groups = kmalloc(i, GFP_KERNEL);
2397 if (sbi->s_locality_groups == NULL) {
2398 clear_opt(sbi->s_mount_opt, MBALLOC);
2399 kfree(sbi->s_mb_offsets);
2400 kfree(sbi->s_mb_maxs);
2403 for (i = 0; i < NR_CPUS; i++) {
2404 struct ext4_locality_group *lg;
2405 lg = &sbi->s_locality_groups[i];
2406 mutex_init(&lg->lg_mutex);
2407 INIT_LIST_HEAD(&lg->lg_prealloc_list);
2408 spin_lock_init(&lg->lg_prealloc_lock);
2411 ext4_mb_init_per_dev_proc(sb);
2412 ext4_mb_history_init(sb);
2414 printk("EXT4-fs: mballoc enabled\n");
2418 /* need to called with ext4 group lock (ext4_lock_group) */
2419 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2421 struct ext4_prealloc_space *pa;
2422 struct list_head *cur, *tmp;
2425 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2426 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2427 list_del(&pa->pa_group_list);
2432 mb_debug("mballoc: %u PAs left\n", count);
2436 int ext4_mb_release(struct super_block *sb)
2439 int num_meta_group_infos;
2440 struct ext4_group_info *grinfo;
2441 struct ext4_sb_info *sbi = EXT4_SB(sb);
2443 if (!test_opt(sb, MBALLOC))
2446 /* release freed, non-committed blocks */
2447 spin_lock(&sbi->s_md_lock);
2448 list_splice_init(&sbi->s_closed_transaction,
2449 &sbi->s_committed_transaction);
2450 list_splice_init(&sbi->s_active_transaction,
2451 &sbi->s_committed_transaction);
2452 spin_unlock(&sbi->s_md_lock);
2453 ext4_mb_free_committed_blocks(sb);
2455 if (sbi->s_group_info) {
2456 for (i = 0; i < sbi->s_groups_count; i++) {
2457 grinfo = ext4_get_group_info(sb, i);
2459 kfree(grinfo->bb_bitmap);
2461 ext4_lock_group(sb, i);
2462 ext4_mb_cleanup_pa(grinfo);
2463 ext4_unlock_group(sb, i);
2466 num_meta_group_infos = (sbi->s_groups_count +
2467 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2468 EXT4_DESC_PER_BLOCK_BITS(sb);
2469 for (i = 0; i < num_meta_group_infos; i++)
2470 kfree(sbi->s_group_info[i]);
2471 kfree(sbi->s_group_info);
2473 kfree(sbi->s_mb_offsets);
2474 kfree(sbi->s_mb_maxs);
2475 if (sbi->s_buddy_cache)
2476 iput(sbi->s_buddy_cache);
2477 if (sbi->s_mb_stats) {
2479 "EXT4-fs: mballoc: %u blocks %u reqs (%u success)\n",
2480 atomic_read(&sbi->s_bal_allocated),
2481 atomic_read(&sbi->s_bal_reqs),
2482 atomic_read(&sbi->s_bal_success));
2484 "EXT4-fs: mballoc: %u extents scanned, %u goal hits, "
2485 "%u 2^N hits, %u breaks, %u lost\n",
2486 atomic_read(&sbi->s_bal_ex_scanned),
2487 atomic_read(&sbi->s_bal_goals),
2488 atomic_read(&sbi->s_bal_2orders),
2489 atomic_read(&sbi->s_bal_breaks),
2490 atomic_read(&sbi->s_mb_lost_chunks));
2492 "EXT4-fs: mballoc: %lu generated and it took %Lu\n",
2493 sbi->s_mb_buddies_generated++,
2494 sbi->s_mb_generation_time);
2496 "EXT4-fs: mballoc: %u preallocated, %u discarded\n",
2497 atomic_read(&sbi->s_mb_preallocated),
2498 atomic_read(&sbi->s_mb_discarded));
2501 kfree(sbi->s_locality_groups);
2503 ext4_mb_history_release(sb);
2504 ext4_mb_destroy_per_dev_proc(sb);
2509 static noinline_for_stack void
2510 ext4_mb_free_committed_blocks(struct super_block *sb)
2512 struct ext4_sb_info *sbi = EXT4_SB(sb);
2517 struct ext4_free_metadata *md;
2518 struct ext4_buddy e4b;
2520 if (list_empty(&sbi->s_committed_transaction))
2523 /* there is committed blocks to be freed yet */
2525 /* get next array of blocks */
2527 spin_lock(&sbi->s_md_lock);
2528 if (!list_empty(&sbi->s_committed_transaction)) {
2529 md = list_entry(sbi->s_committed_transaction.next,
2530 struct ext4_free_metadata, list);
2531 list_del(&md->list);
2533 spin_unlock(&sbi->s_md_lock);
2538 mb_debug("gonna free %u blocks in group %lu (0x%p):",
2539 md->num, md->group, md);
2541 err = ext4_mb_load_buddy(sb, md->group, &e4b);
2542 /* we expect to find existing buddy because it's pinned */
2545 /* there are blocks to put in buddy to make them really free */
2548 ext4_lock_group(sb, md->group);
2549 for (i = 0; i < md->num; i++) {
2550 mb_debug(" %u", md->blocks[i]);
2551 err = mb_free_blocks(NULL, &e4b, md->blocks[i], 1);
2555 ext4_unlock_group(sb, md->group);
2557 /* balance refcounts from ext4_mb_free_metadata() */
2558 page_cache_release(e4b.bd_buddy_page);
2559 page_cache_release(e4b.bd_bitmap_page);
2562 ext4_mb_release_desc(&e4b);
2566 mb_debug("freed %u blocks in %u structures\n", count, count2);
2569 #define EXT4_MB_STATS_NAME "stats"
2570 #define EXT4_MB_MAX_TO_SCAN_NAME "max_to_scan"
2571 #define EXT4_MB_MIN_TO_SCAN_NAME "min_to_scan"
2572 #define EXT4_MB_ORDER2_REQ "order2_req"
2573 #define EXT4_MB_STREAM_REQ "stream_req"
2574 #define EXT4_MB_GROUP_PREALLOC "group_prealloc"
2578 #define MB_PROC_VALUE_READ(name) \
2579 static int ext4_mb_read_##name(char *page, char **start, \
2580 off_t off, int count, int *eof, void *data) \
2582 struct ext4_sb_info *sbi = data; \
2587 len = sprintf(page, "%ld\n", sbi->s_mb_##name); \
2592 #define MB_PROC_VALUE_WRITE(name) \
2593 static int ext4_mb_write_##name(struct file *file, \
2594 const char __user *buf, unsigned long cnt, void *data) \
2596 struct ext4_sb_info *sbi = data; \
2599 if (cnt >= sizeof(str)) \
2601 if (copy_from_user(str, buf, cnt)) \
2603 value = simple_strtol(str, NULL, 0); \
2606 sbi->s_mb_##name = value; \
2610 MB_PROC_VALUE_READ(stats);
2611 MB_PROC_VALUE_WRITE(stats);
2612 MB_PROC_VALUE_READ(max_to_scan);
2613 MB_PROC_VALUE_WRITE(max_to_scan);
2614 MB_PROC_VALUE_READ(min_to_scan);
2615 MB_PROC_VALUE_WRITE(min_to_scan);
2616 MB_PROC_VALUE_READ(order2_reqs);
2617 MB_PROC_VALUE_WRITE(order2_reqs);
2618 MB_PROC_VALUE_READ(stream_request);
2619 MB_PROC_VALUE_WRITE(stream_request);
2620 MB_PROC_VALUE_READ(group_prealloc);
2621 MB_PROC_VALUE_WRITE(group_prealloc);
2623 #define MB_PROC_HANDLER(name, var) \
2625 proc = create_proc_entry(name, mode, sbi->s_mb_proc); \
2626 if (proc == NULL) { \
2627 printk(KERN_ERR "EXT4-fs: can't to create %s\n", name); \
2631 proc->read_proc = ext4_mb_read_##var ; \
2632 proc->write_proc = ext4_mb_write_##var; \
2635 static int ext4_mb_init_per_dev_proc(struct super_block *sb)
2637 mode_t mode = S_IFREG | S_IRUGO | S_IWUSR;
2638 struct ext4_sb_info *sbi = EXT4_SB(sb);
2639 struct proc_dir_entry *proc;
2642 bdevname(sb->s_bdev, devname);
2643 sbi->s_mb_proc = proc_mkdir(devname, proc_root_ext4);
2645 MB_PROC_HANDLER(EXT4_MB_STATS_NAME, stats);
2646 MB_PROC_HANDLER(EXT4_MB_MAX_TO_SCAN_NAME, max_to_scan);
2647 MB_PROC_HANDLER(EXT4_MB_MIN_TO_SCAN_NAME, min_to_scan);
2648 MB_PROC_HANDLER(EXT4_MB_ORDER2_REQ, order2_reqs);
2649 MB_PROC_HANDLER(EXT4_MB_STREAM_REQ, stream_request);
2650 MB_PROC_HANDLER(EXT4_MB_GROUP_PREALLOC, group_prealloc);
2655 printk(KERN_ERR "EXT4-fs: Unable to create %s\n", devname);
2656 remove_proc_entry(EXT4_MB_GROUP_PREALLOC, sbi->s_mb_proc);
2657 remove_proc_entry(EXT4_MB_STREAM_REQ, sbi->s_mb_proc);
2658 remove_proc_entry(EXT4_MB_ORDER2_REQ, sbi->s_mb_proc);
2659 remove_proc_entry(EXT4_MB_MIN_TO_SCAN_NAME, sbi->s_mb_proc);
2660 remove_proc_entry(EXT4_MB_MAX_TO_SCAN_NAME, sbi->s_mb_proc);
2661 remove_proc_entry(EXT4_MB_STATS_NAME, sbi->s_mb_proc);
2662 remove_proc_entry(devname, proc_root_ext4);
2663 sbi->s_mb_proc = NULL;
2668 static int ext4_mb_destroy_per_dev_proc(struct super_block *sb)
2670 struct ext4_sb_info *sbi = EXT4_SB(sb);
2673 if (sbi->s_mb_proc == NULL)
2676 bdevname(sb->s_bdev, devname);
2677 remove_proc_entry(EXT4_MB_GROUP_PREALLOC, sbi->s_mb_proc);
2678 remove_proc_entry(EXT4_MB_STREAM_REQ, sbi->s_mb_proc);
2679 remove_proc_entry(EXT4_MB_ORDER2_REQ, sbi->s_mb_proc);
2680 remove_proc_entry(EXT4_MB_MIN_TO_SCAN_NAME, sbi->s_mb_proc);
2681 remove_proc_entry(EXT4_MB_MAX_TO_SCAN_NAME, sbi->s_mb_proc);
2682 remove_proc_entry(EXT4_MB_STATS_NAME, sbi->s_mb_proc);
2683 remove_proc_entry(devname, proc_root_ext4);
2688 int __init init_ext4_mballoc(void)
2690 ext4_pspace_cachep =
2691 kmem_cache_create("ext4_prealloc_space",
2692 sizeof(struct ext4_prealloc_space),
2693 0, SLAB_RECLAIM_ACCOUNT, NULL);
2694 if (ext4_pspace_cachep == NULL)
2698 kmem_cache_create("ext4_alloc_context",
2699 sizeof(struct ext4_allocation_context),
2700 0, SLAB_RECLAIM_ACCOUNT, NULL);
2701 if (ext4_ac_cachep == NULL) {
2702 kmem_cache_destroy(ext4_pspace_cachep);
2705 #ifdef CONFIG_PROC_FS
2706 proc_root_ext4 = proc_mkdir("fs/ext4", NULL);
2707 if (proc_root_ext4 == NULL)
2708 printk(KERN_ERR "EXT4-fs: Unable to create fs/ext4\n");
2713 void exit_ext4_mballoc(void)
2715 /* XXX: synchronize_rcu(); */
2716 kmem_cache_destroy(ext4_pspace_cachep);
2717 kmem_cache_destroy(ext4_ac_cachep);
2718 #ifdef CONFIG_PROC_FS
2719 remove_proc_entry("fs/ext4", NULL);
2725 * Check quota and mark choosed space (ac->ac_b_ex) non-free in bitmaps
2726 * Returns 0 if success or error code
2728 static noinline_for_stack int
2729 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2732 struct buffer_head *bitmap_bh = NULL;
2733 struct ext4_super_block *es;
2734 struct ext4_group_desc *gdp;
2735 struct buffer_head *gdp_bh;
2736 struct ext4_sb_info *sbi;
2737 struct super_block *sb;
2741 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2742 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2750 bitmap_bh = read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2754 err = ext4_journal_get_write_access(handle, bitmap_bh);
2759 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2763 ext4_debug("using block group %lu(%d)\n", ac->ac_b_ex.fe_group,
2764 gdp->bg_free_blocks_count);
2766 err = ext4_journal_get_write_access(handle, gdp_bh);
2770 block = ac->ac_b_ex.fe_group * EXT4_BLOCKS_PER_GROUP(sb)
2771 + ac->ac_b_ex.fe_start
2772 + le32_to_cpu(es->s_first_data_block);
2774 len = ac->ac_b_ex.fe_len;
2775 if (in_range(ext4_block_bitmap(sb, gdp), block, len) ||
2776 in_range(ext4_inode_bitmap(sb, gdp), block, len) ||
2777 in_range(block, ext4_inode_table(sb, gdp),
2778 EXT4_SB(sb)->s_itb_per_group) ||
2779 in_range(block + len - 1, ext4_inode_table(sb, gdp),
2780 EXT4_SB(sb)->s_itb_per_group)) {
2781 ext4_error(sb, __func__,
2782 "Allocating block in system zone - block = %llu",
2784 /* File system mounted not to panic on error
2785 * Fix the bitmap and repeat the block allocation
2786 * We leak some of the blocks here.
2788 mb_set_bits(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group),
2789 bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2790 ac->ac_b_ex.fe_len);
2791 err = ext4_journal_dirty_metadata(handle, bitmap_bh);
2796 #ifdef AGGRESSIVE_CHECK
2799 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
2800 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
2801 bitmap_bh->b_data));
2805 mb_set_bits(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group), bitmap_bh->b_data,
2806 ac->ac_b_ex.fe_start, ac->ac_b_ex.fe_len);
2808 spin_lock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
2809 if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2810 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
2811 gdp->bg_free_blocks_count =
2812 cpu_to_le16(ext4_free_blocks_after_init(sb,
2813 ac->ac_b_ex.fe_group,
2816 le16_add_cpu(&gdp->bg_free_blocks_count, -ac->ac_b_ex.fe_len);
2817 gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
2818 spin_unlock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
2819 percpu_counter_sub(&sbi->s_freeblocks_counter, ac->ac_b_ex.fe_len);
2821 err = ext4_journal_dirty_metadata(handle, bitmap_bh);
2824 err = ext4_journal_dirty_metadata(handle, gdp_bh);
2833 * here we normalize request for locality group
2834 * Group request are normalized to s_strip size if we set the same via mount
2835 * option. If not we set it to s_mb_group_prealloc which can be configured via
2836 * /proc/fs/ext4/<partition>/group_prealloc
2838 * XXX: should we try to preallocate more than the group has now?
2840 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
2842 struct super_block *sb = ac->ac_sb;
2843 struct ext4_locality_group *lg = ac->ac_lg;
2846 if (EXT4_SB(sb)->s_stripe)
2847 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_stripe;
2849 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
2850 mb_debug("#%u: goal %u blocks for locality group\n",
2851 current->pid, ac->ac_g_ex.fe_len);
2855 * Normalization means making request better in terms of
2856 * size and alignment
2858 static noinline_for_stack void
2859 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
2860 struct ext4_allocation_request *ar)
2864 loff_t size, orig_size, start_off;
2865 ext4_lblk_t start, orig_start;
2866 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
2867 struct ext4_prealloc_space *pa;
2869 /* do normalize only data requests, metadata requests
2870 do not need preallocation */
2871 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
2874 /* sometime caller may want exact blocks */
2875 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2878 /* caller may indicate that preallocation isn't
2879 * required (it's a tail, for example) */
2880 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
2883 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
2884 ext4_mb_normalize_group_request(ac);
2888 bsbits = ac->ac_sb->s_blocksize_bits;
2890 /* first, let's learn actual file size
2891 * given current request is allocated */
2892 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
2893 size = size << bsbits;
2894 if (size < i_size_read(ac->ac_inode))
2895 size = i_size_read(ac->ac_inode);
2897 /* max size of free chunks */
2900 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
2901 (req <= (size) || max <= (chunk_size))
2903 /* first, try to predict filesize */
2904 /* XXX: should this table be tunable? */
2906 if (size <= 16 * 1024) {
2908 } else if (size <= 32 * 1024) {
2910 } else if (size <= 64 * 1024) {
2912 } else if (size <= 128 * 1024) {
2914 } else if (size <= 256 * 1024) {
2916 } else if (size <= 512 * 1024) {
2918 } else if (size <= 1024 * 1024) {
2920 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
2921 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2922 (21 - bsbits)) << 21;
2923 size = 2 * 1024 * 1024;
2924 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
2925 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2926 (22 - bsbits)) << 22;
2927 size = 4 * 1024 * 1024;
2928 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
2929 (8<<20)>>bsbits, max, 8 * 1024)) {
2930 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2931 (23 - bsbits)) << 23;
2932 size = 8 * 1024 * 1024;
2934 start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
2935 size = ac->ac_o_ex.fe_len << bsbits;
2937 orig_size = size = size >> bsbits;
2938 orig_start = start = start_off >> bsbits;
2940 /* don't cover already allocated blocks in selected range */
2941 if (ar->pleft && start <= ar->lleft) {
2942 size -= ar->lleft + 1 - start;
2943 start = ar->lleft + 1;
2945 if (ar->pright && start + size - 1 >= ar->lright)
2946 size -= start + size - ar->lright;
2950 /* check we don't cross already preallocated blocks */
2952 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
2953 unsigned long pa_end;
2957 spin_lock(&pa->pa_lock);
2958 if (pa->pa_deleted) {
2959 spin_unlock(&pa->pa_lock);
2963 pa_end = pa->pa_lstart + pa->pa_len;
2965 /* PA must not overlap original request */
2966 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
2967 ac->ac_o_ex.fe_logical < pa->pa_lstart));
2969 /* skip PA normalized request doesn't overlap with */
2970 if (pa->pa_lstart >= end) {
2971 spin_unlock(&pa->pa_lock);
2974 if (pa_end <= start) {
2975 spin_unlock(&pa->pa_lock);
2978 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
2980 if (pa_end <= ac->ac_o_ex.fe_logical) {
2981 BUG_ON(pa_end < start);
2985 if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
2986 BUG_ON(pa->pa_lstart > end);
2987 end = pa->pa_lstart;
2989 spin_unlock(&pa->pa_lock);
2994 /* XXX: extra loop to check we really don't overlap preallocations */
2996 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
2997 unsigned long pa_end;
2998 spin_lock(&pa->pa_lock);
2999 if (pa->pa_deleted == 0) {
3000 pa_end = pa->pa_lstart + pa->pa_len;
3001 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3003 spin_unlock(&pa->pa_lock);
3007 if (start + size <= ac->ac_o_ex.fe_logical &&
3008 start > ac->ac_o_ex.fe_logical) {
3009 printk(KERN_ERR "start %lu, size %lu, fe_logical %lu\n",
3010 (unsigned long) start, (unsigned long) size,
3011 (unsigned long) ac->ac_o_ex.fe_logical);
3013 BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3014 start > ac->ac_o_ex.fe_logical);
3015 BUG_ON(size <= 0 || size >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3017 /* now prepare goal request */
3019 /* XXX: is it better to align blocks WRT to logical
3020 * placement or satisfy big request as is */
3021 ac->ac_g_ex.fe_logical = start;
3022 ac->ac_g_ex.fe_len = size;
3024 /* define goal start in order to merge */
3025 if (ar->pright && (ar->lright == (start + size))) {
3026 /* merge to the right */
3027 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3028 &ac->ac_f_ex.fe_group,
3029 &ac->ac_f_ex.fe_start);
3030 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3032 if (ar->pleft && (ar->lleft + 1 == start)) {
3033 /* merge to the left */
3034 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3035 &ac->ac_f_ex.fe_group,
3036 &ac->ac_f_ex.fe_start);
3037 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3040 mb_debug("goal: %u(was %u) blocks at %u\n", (unsigned) size,
3041 (unsigned) orig_size, (unsigned) start);
3044 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3046 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3048 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3049 atomic_inc(&sbi->s_bal_reqs);
3050 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3051 if (ac->ac_o_ex.fe_len >= ac->ac_g_ex.fe_len)
3052 atomic_inc(&sbi->s_bal_success);
3053 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3054 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3055 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3056 atomic_inc(&sbi->s_bal_goals);
3057 if (ac->ac_found > sbi->s_mb_max_to_scan)
3058 atomic_inc(&sbi->s_bal_breaks);
3061 ext4_mb_store_history(ac);
3065 * use blocks preallocated to inode
3067 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3068 struct ext4_prealloc_space *pa)
3074 /* found preallocated blocks, use them */
3075 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3076 end = min(pa->pa_pstart + pa->pa_len, start + ac->ac_o_ex.fe_len);
3078 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3079 &ac->ac_b_ex.fe_start);
3080 ac->ac_b_ex.fe_len = len;
3081 ac->ac_status = AC_STATUS_FOUND;
3084 BUG_ON(start < pa->pa_pstart);
3085 BUG_ON(start + len > pa->pa_pstart + pa->pa_len);
3086 BUG_ON(pa->pa_free < len);
3089 mb_debug("use %llu/%u from inode pa %p\n", start, len, pa);
3093 * use blocks preallocated to locality group
3095 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3096 struct ext4_prealloc_space *pa)
3098 unsigned int len = ac->ac_o_ex.fe_len;
3099 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3100 &ac->ac_b_ex.fe_group,
3101 &ac->ac_b_ex.fe_start);
3102 ac->ac_b_ex.fe_len = len;
3103 ac->ac_status = AC_STATUS_FOUND;
3106 /* we don't correct pa_pstart or pa_plen here to avoid
3107 * possible race when the group is being loaded concurrently
3108 * instead we correct pa later, after blocks are marked
3109 * in on-disk bitmap -- see ext4_mb_release_context()
3110 * Other CPUs are prevented from allocating from this pa by lg_mutex
3112 mb_debug("use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3116 * search goal blocks in preallocated space
3118 static noinline_for_stack int
3119 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3121 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3122 struct ext4_locality_group *lg;
3123 struct ext4_prealloc_space *pa;
3125 /* only data can be preallocated */
3126 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3129 /* first, try per-file preallocation */
3131 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3133 /* all fields in this condition don't change,
3134 * so we can skip locking for them */
3135 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3136 ac->ac_o_ex.fe_logical >= pa->pa_lstart + pa->pa_len)
3139 /* found preallocated blocks, use them */
3140 spin_lock(&pa->pa_lock);
3141 if (pa->pa_deleted == 0 && pa->pa_free) {
3142 atomic_inc(&pa->pa_count);
3143 ext4_mb_use_inode_pa(ac, pa);
3144 spin_unlock(&pa->pa_lock);
3145 ac->ac_criteria = 10;
3149 spin_unlock(&pa->pa_lock);
3153 /* can we use group allocation? */
3154 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3157 /* inode may have no locality group for some reason */
3163 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list, pa_inode_list) {
3164 spin_lock(&pa->pa_lock);
3165 if (pa->pa_deleted == 0 && pa->pa_free >= ac->ac_o_ex.fe_len) {
3166 atomic_inc(&pa->pa_count);
3167 ext4_mb_use_group_pa(ac, pa);
3168 spin_unlock(&pa->pa_lock);
3169 ac->ac_criteria = 20;
3173 spin_unlock(&pa->pa_lock);
3181 * the function goes through all preallocation in this group and marks them
3182 * used in in-core bitmap. buddy must be generated from this bitmap
3183 * Need to be called with ext4 group lock (ext4_lock_group)
3185 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3188 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3189 struct ext4_prealloc_space *pa;
3190 struct list_head *cur;
3191 ext4_group_t groupnr;
3192 ext4_grpblk_t start;
3193 int preallocated = 0;
3197 /* all form of preallocation discards first load group,
3198 * so the only competing code is preallocation use.
3199 * we don't need any locking here
3200 * notice we do NOT ignore preallocations with pa_deleted
3201 * otherwise we could leave used blocks available for
3202 * allocation in buddy when concurrent ext4_mb_put_pa()
3203 * is dropping preallocation
3205 list_for_each(cur, &grp->bb_prealloc_list) {
3206 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3207 spin_lock(&pa->pa_lock);
3208 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3211 spin_unlock(&pa->pa_lock);
3212 if (unlikely(len == 0))
3214 BUG_ON(groupnr != group);
3215 mb_set_bits(sb_bgl_lock(EXT4_SB(sb), group),
3216 bitmap, start, len);
3217 preallocated += len;
3220 mb_debug("prellocated %u for group %lu\n", preallocated, group);
3223 static void ext4_mb_pa_callback(struct rcu_head *head)
3225 struct ext4_prealloc_space *pa;
3226 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3227 kmem_cache_free(ext4_pspace_cachep, pa);
3231 * drops a reference to preallocated space descriptor
3232 * if this was the last reference and the space is consumed
3234 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3235 struct super_block *sb, struct ext4_prealloc_space *pa)
3239 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3242 /* in this short window concurrent discard can set pa_deleted */
3243 spin_lock(&pa->pa_lock);
3244 if (pa->pa_deleted == 1) {
3245 spin_unlock(&pa->pa_lock);
3250 spin_unlock(&pa->pa_lock);
3252 /* -1 is to protect from crossing allocation group */
3253 ext4_get_group_no_and_offset(sb, pa->pa_pstart - 1, &grp, NULL);
3258 * P1 (buddy init) P2 (regular allocation)
3259 * find block B in PA
3260 * copy on-disk bitmap to buddy
3261 * mark B in on-disk bitmap
3262 * drop PA from group
3263 * mark all PAs in buddy
3265 * thus, P1 initializes buddy with B available. to prevent this
3266 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3269 ext4_lock_group(sb, grp);
3270 list_del(&pa->pa_group_list);
3271 ext4_unlock_group(sb, grp);
3273 spin_lock(pa->pa_obj_lock);
3274 list_del_rcu(&pa->pa_inode_list);
3275 spin_unlock(pa->pa_obj_lock);
3277 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3281 * creates new preallocated space for given inode
3283 static noinline_for_stack int
3284 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3286 struct super_block *sb = ac->ac_sb;
3287 struct ext4_prealloc_space *pa;
3288 struct ext4_group_info *grp;
3289 struct ext4_inode_info *ei;
3291 /* preallocate only when found space is larger then requested */
3292 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3293 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3294 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3296 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3300 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3306 /* we can't allocate as much as normalizer wants.
3307 * so, found space must get proper lstart
3308 * to cover original request */
3309 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3310 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3312 /* we're limited by original request in that
3313 * logical block must be covered any way
3314 * winl is window we can move our chunk within */
3315 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3317 /* also, we should cover whole original request */
3318 wins = ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len;
3320 /* the smallest one defines real window */
3321 win = min(winl, wins);
3323 offs = ac->ac_o_ex.fe_logical % ac->ac_b_ex.fe_len;
3324 if (offs && offs < win)
3327 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical - win;
3328 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3329 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3332 /* preallocation can change ac_b_ex, thus we store actually
3333 * allocated blocks for history */
3334 ac->ac_f_ex = ac->ac_b_ex;
3336 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3337 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3338 pa->pa_len = ac->ac_b_ex.fe_len;
3339 pa->pa_free = pa->pa_len;
3340 atomic_set(&pa->pa_count, 1);
3341 spin_lock_init(&pa->pa_lock);
3345 mb_debug("new inode pa %p: %llu/%u for %u\n", pa,
3346 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3348 ext4_mb_use_inode_pa(ac, pa);
3349 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3351 ei = EXT4_I(ac->ac_inode);
3352 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3354 pa->pa_obj_lock = &ei->i_prealloc_lock;
3355 pa->pa_inode = ac->ac_inode;
3357 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3358 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3359 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3361 spin_lock(pa->pa_obj_lock);
3362 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3363 spin_unlock(pa->pa_obj_lock);
3369 * creates new preallocated space for locality group inodes belongs to
3371 static noinline_for_stack int
3372 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3374 struct super_block *sb = ac->ac_sb;
3375 struct ext4_locality_group *lg;
3376 struct ext4_prealloc_space *pa;
3377 struct ext4_group_info *grp;
3379 /* preallocate only when found space is larger then requested */
3380 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3381 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3382 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3384 BUG_ON(ext4_pspace_cachep == NULL);
3385 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3389 /* preallocation can change ac_b_ex, thus we store actually
3390 * allocated blocks for history */
3391 ac->ac_f_ex = ac->ac_b_ex;
3393 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3394 pa->pa_lstart = pa->pa_pstart;
3395 pa->pa_len = ac->ac_b_ex.fe_len;
3396 pa->pa_free = pa->pa_len;
3397 atomic_set(&pa->pa_count, 1);
3398 spin_lock_init(&pa->pa_lock);
3402 mb_debug("new group pa %p: %llu/%u for %u\n", pa,
3403 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3405 ext4_mb_use_group_pa(ac, pa);
3406 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3408 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3412 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3413 pa->pa_inode = NULL;
3415 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3416 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3417 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3419 spin_lock(pa->pa_obj_lock);
3420 list_add_tail_rcu(&pa->pa_inode_list, &lg->lg_prealloc_list);
3421 spin_unlock(pa->pa_obj_lock);
3426 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3430 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3431 err = ext4_mb_new_group_pa(ac);
3433 err = ext4_mb_new_inode_pa(ac);
3438 * finds all unused blocks in on-disk bitmap, frees them in
3439 * in-core bitmap and buddy.
3440 * @pa must be unlinked from inode and group lists, so that
3441 * nobody else can find/use it.
3442 * the caller MUST hold group/inode locks.
3443 * TODO: optimize the case when there are no in-core structures yet
3445 static noinline_for_stack int
3446 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3447 struct ext4_prealloc_space *pa,
3448 struct ext4_allocation_context *ac)
3450 struct super_block *sb = e4b->bd_sb;
3451 struct ext4_sb_info *sbi = EXT4_SB(sb);
3460 BUG_ON(pa->pa_deleted == 0);
3461 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3462 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3463 end = bit + pa->pa_len;
3467 ac->ac_inode = pa->pa_inode;
3468 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3472 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3475 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3478 start = group * EXT4_BLOCKS_PER_GROUP(sb) + bit +
3479 le32_to_cpu(sbi->s_es->s_first_data_block);
3480 mb_debug(" free preallocated %u/%u in group %u\n",
3481 (unsigned) start, (unsigned) next - bit,
3486 ac->ac_b_ex.fe_group = group;
3487 ac->ac_b_ex.fe_start = bit;
3488 ac->ac_b_ex.fe_len = next - bit;
3489 ac->ac_b_ex.fe_logical = 0;
3490 ext4_mb_store_history(ac);
3493 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3496 if (free != pa->pa_free) {
3497 printk(KERN_CRIT "pa %p: logic %lu, phys. %lu, len %lu\n",
3498 pa, (unsigned long) pa->pa_lstart,
3499 (unsigned long) pa->pa_pstart,
3500 (unsigned long) pa->pa_len);
3501 ext4_error(sb, __func__, "free %u, pa_free %u\n",
3504 * pa is already deleted so we use the value obtained
3505 * from the bitmap and continue.
3508 atomic_add(free, &sbi->s_mb_discarded);
3513 static noinline_for_stack int
3514 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3515 struct ext4_prealloc_space *pa,
3516 struct ext4_allocation_context *ac)
3518 struct super_block *sb = e4b->bd_sb;
3523 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3525 BUG_ON(pa->pa_deleted == 0);
3526 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3527 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3528 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3529 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3533 ac->ac_inode = NULL;
3534 ac->ac_b_ex.fe_group = group;
3535 ac->ac_b_ex.fe_start = bit;
3536 ac->ac_b_ex.fe_len = pa->pa_len;
3537 ac->ac_b_ex.fe_logical = 0;
3538 ext4_mb_store_history(ac);
3545 * releases all preallocations in given group
3547 * first, we need to decide discard policy:
3548 * - when do we discard
3550 * - how many do we discard
3551 * 1) how many requested
3553 static noinline_for_stack int
3554 ext4_mb_discard_group_preallocations(struct super_block *sb,
3555 ext4_group_t group, int needed)
3557 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3558 struct buffer_head *bitmap_bh = NULL;
3559 struct ext4_prealloc_space *pa, *tmp;
3560 struct ext4_allocation_context *ac;
3561 struct list_head list;
3562 struct ext4_buddy e4b;
3567 mb_debug("discard preallocation for group %lu\n", group);
3569 if (list_empty(&grp->bb_prealloc_list))
3572 bitmap_bh = read_block_bitmap(sb, group);
3573 if (bitmap_bh == NULL) {
3574 /* error handling here */
3575 ext4_mb_release_desc(&e4b);
3576 BUG_ON(bitmap_bh == NULL);
3579 err = ext4_mb_load_buddy(sb, group, &e4b);
3580 BUG_ON(err != 0); /* error handling here */
3583 needed = EXT4_BLOCKS_PER_GROUP(sb) + 1;
3585 grp = ext4_get_group_info(sb, group);
3586 INIT_LIST_HEAD(&list);
3588 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
3590 ext4_lock_group(sb, group);
3591 list_for_each_entry_safe(pa, tmp,
3592 &grp->bb_prealloc_list, pa_group_list) {
3593 spin_lock(&pa->pa_lock);
3594 if (atomic_read(&pa->pa_count)) {
3595 spin_unlock(&pa->pa_lock);
3599 if (pa->pa_deleted) {
3600 spin_unlock(&pa->pa_lock);
3604 /* seems this one can be freed ... */
3607 /* we can trust pa_free ... */
3608 free += pa->pa_free;
3610 spin_unlock(&pa->pa_lock);
3612 list_del(&pa->pa_group_list);
3613 list_add(&pa->u.pa_tmp_list, &list);
3616 /* if we still need more blocks and some PAs were used, try again */
3617 if (free < needed && busy) {
3619 ext4_unlock_group(sb, group);
3621 * Yield the CPU here so that we don't get soft lockup
3622 * in non preempt case.
3628 /* found anything to free? */
3629 if (list_empty(&list)) {
3634 /* now free all selected PAs */
3635 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3637 /* remove from object (inode or locality group) */
3638 spin_lock(pa->pa_obj_lock);
3639 list_del_rcu(&pa->pa_inode_list);
3640 spin_unlock(pa->pa_obj_lock);
3643 ext4_mb_release_group_pa(&e4b, pa, ac);
3645 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
3647 list_del(&pa->u.pa_tmp_list);
3648 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3652 ext4_unlock_group(sb, group);
3654 kmem_cache_free(ext4_ac_cachep, ac);
3655 ext4_mb_release_desc(&e4b);
3661 * releases all non-used preallocated blocks for given inode
3663 * It's important to discard preallocations under i_data_sem
3664 * We don't want another block to be served from the prealloc
3665 * space when we are discarding the inode prealloc space.
3667 * FIXME!! Make sure it is valid at all the call sites
3669 void ext4_mb_discard_inode_preallocations(struct inode *inode)
3671 struct ext4_inode_info *ei = EXT4_I(inode);
3672 struct super_block *sb = inode->i_sb;
3673 struct buffer_head *bitmap_bh = NULL;
3674 struct ext4_prealloc_space *pa, *tmp;
3675 struct ext4_allocation_context *ac;
3676 ext4_group_t group = 0;
3677 struct list_head list;
3678 struct ext4_buddy e4b;
3681 if (!test_opt(sb, MBALLOC) || !S_ISREG(inode->i_mode)) {
3682 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
3686 mb_debug("discard preallocation for inode %lu\n", inode->i_ino);
3688 INIT_LIST_HEAD(&list);
3690 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
3692 /* first, collect all pa's in the inode */
3693 spin_lock(&ei->i_prealloc_lock);
3694 while (!list_empty(&ei->i_prealloc_list)) {
3695 pa = list_entry(ei->i_prealloc_list.next,
3696 struct ext4_prealloc_space, pa_inode_list);
3697 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
3698 spin_lock(&pa->pa_lock);
3699 if (atomic_read(&pa->pa_count)) {
3700 /* this shouldn't happen often - nobody should
3701 * use preallocation while we're discarding it */
3702 spin_unlock(&pa->pa_lock);
3703 spin_unlock(&ei->i_prealloc_lock);
3704 printk(KERN_ERR "uh-oh! used pa while discarding\n");
3706 schedule_timeout_uninterruptible(HZ);
3710 if (pa->pa_deleted == 0) {
3712 spin_unlock(&pa->pa_lock);
3713 list_del_rcu(&pa->pa_inode_list);
3714 list_add(&pa->u.pa_tmp_list, &list);
3718 /* someone is deleting pa right now */
3719 spin_unlock(&pa->pa_lock);
3720 spin_unlock(&ei->i_prealloc_lock);
3722 /* we have to wait here because pa_deleted
3723 * doesn't mean pa is already unlinked from
3724 * the list. as we might be called from
3725 * ->clear_inode() the inode will get freed
3726 * and concurrent thread which is unlinking
3727 * pa from inode's list may access already
3728 * freed memory, bad-bad-bad */
3730 /* XXX: if this happens too often, we can
3731 * add a flag to force wait only in case
3732 * of ->clear_inode(), but not in case of
3733 * regular truncate */
3734 schedule_timeout_uninterruptible(HZ);
3737 spin_unlock(&ei->i_prealloc_lock);
3739 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3740 BUG_ON(pa->pa_linear != 0);
3741 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
3743 err = ext4_mb_load_buddy(sb, group, &e4b);
3744 BUG_ON(err != 0); /* error handling here */
3746 bitmap_bh = read_block_bitmap(sb, group);
3747 if (bitmap_bh == NULL) {
3748 /* error handling here */
3749 ext4_mb_release_desc(&e4b);
3750 BUG_ON(bitmap_bh == NULL);
3753 ext4_lock_group(sb, group);
3754 list_del(&pa->pa_group_list);
3755 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
3756 ext4_unlock_group(sb, group);
3758 ext4_mb_release_desc(&e4b);
3761 list_del(&pa->u.pa_tmp_list);
3762 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3765 kmem_cache_free(ext4_ac_cachep, ac);
3769 * finds all preallocated spaces and return blocks being freed to them
3770 * if preallocated space becomes full (no block is used from the space)
3771 * then the function frees space in buddy
3772 * XXX: at the moment, truncate (which is the only way to free blocks)
3773 * discards all preallocations
3775 static void ext4_mb_return_to_preallocation(struct inode *inode,
3776 struct ext4_buddy *e4b,
3777 sector_t block, int count)
3779 BUG_ON(!list_empty(&EXT4_I(inode)->i_prealloc_list));
3782 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3784 struct super_block *sb = ac->ac_sb;
3787 printk(KERN_ERR "EXT4-fs: Can't allocate:"
3788 " Allocation context details:\n");
3789 printk(KERN_ERR "EXT4-fs: status %d flags %d\n",
3790 ac->ac_status, ac->ac_flags);
3791 printk(KERN_ERR "EXT4-fs: orig %lu/%lu/%lu@%lu, goal %lu/%lu/%lu@%lu, "
3792 "best %lu/%lu/%lu@%lu cr %d\n",
3793 (unsigned long)ac->ac_o_ex.fe_group,
3794 (unsigned long)ac->ac_o_ex.fe_start,
3795 (unsigned long)ac->ac_o_ex.fe_len,
3796 (unsigned long)ac->ac_o_ex.fe_logical,
3797 (unsigned long)ac->ac_g_ex.fe_group,
3798 (unsigned long)ac->ac_g_ex.fe_start,
3799 (unsigned long)ac->ac_g_ex.fe_len,
3800 (unsigned long)ac->ac_g_ex.fe_logical,
3801 (unsigned long)ac->ac_b_ex.fe_group,
3802 (unsigned long)ac->ac_b_ex.fe_start,
3803 (unsigned long)ac->ac_b_ex.fe_len,
3804 (unsigned long)ac->ac_b_ex.fe_logical,
3805 (int)ac->ac_criteria);
3806 printk(KERN_ERR "EXT4-fs: %lu scanned, %d found\n", ac->ac_ex_scanned,
3808 printk(KERN_ERR "EXT4-fs: groups: \n");
3809 for (i = 0; i < EXT4_SB(sb)->s_groups_count; i++) {
3810 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3811 struct ext4_prealloc_space *pa;
3812 ext4_grpblk_t start;
3813 struct list_head *cur;
3814 ext4_lock_group(sb, i);
3815 list_for_each(cur, &grp->bb_prealloc_list) {
3816 pa = list_entry(cur, struct ext4_prealloc_space,
3818 spin_lock(&pa->pa_lock);
3819 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3821 spin_unlock(&pa->pa_lock);
3822 printk(KERN_ERR "PA:%lu:%d:%u \n", i,
3825 ext4_unlock_group(sb, i);
3827 if (grp->bb_free == 0)
3829 printk(KERN_ERR "%lu: %d/%d \n",
3830 i, grp->bb_free, grp->bb_fragments);
3832 printk(KERN_ERR "\n");
3835 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3842 * We use locality group preallocation for small size file. The size of the
3843 * file is determined by the current size or the resulting size after
3844 * allocation which ever is larger
3846 * One can tune this size via /proc/fs/ext4/<partition>/stream_req
3848 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
3850 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3851 int bsbits = ac->ac_sb->s_blocksize_bits;
3854 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3857 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
3858 isize = i_size_read(ac->ac_inode) >> bsbits;
3859 size = max(size, isize);
3861 /* don't use group allocation for large files */
3862 if (size >= sbi->s_mb_stream_request)
3865 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3868 BUG_ON(ac->ac_lg != NULL);
3870 * locality group prealloc space are per cpu. The reason for having
3871 * per cpu locality group is to reduce the contention between block
3872 * request from multiple CPUs.
3874 ac->ac_lg = &sbi->s_locality_groups[get_cpu()];
3877 /* we're going to use group allocation */
3878 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
3880 /* serialize all allocations in the group */
3881 mutex_lock(&ac->ac_lg->lg_mutex);
3884 static noinline_for_stack int
3885 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
3886 struct ext4_allocation_request *ar)
3888 struct super_block *sb = ar->inode->i_sb;
3889 struct ext4_sb_info *sbi = EXT4_SB(sb);
3890 struct ext4_super_block *es = sbi->s_es;
3894 ext4_grpblk_t block;
3896 /* we can't allocate > group size */
3899 /* just a dirty hack to filter too big requests */
3900 if (len >= EXT4_BLOCKS_PER_GROUP(sb) - 10)
3901 len = EXT4_BLOCKS_PER_GROUP(sb) - 10;
3903 /* start searching from the goal */
3905 if (goal < le32_to_cpu(es->s_first_data_block) ||
3906 goal >= ext4_blocks_count(es))
3907 goal = le32_to_cpu(es->s_first_data_block);
3908 ext4_get_group_no_and_offset(sb, goal, &group, &block);
3910 /* set up allocation goals */
3911 ac->ac_b_ex.fe_logical = ar->logical;
3912 ac->ac_b_ex.fe_group = 0;
3913 ac->ac_b_ex.fe_start = 0;
3914 ac->ac_b_ex.fe_len = 0;
3915 ac->ac_status = AC_STATUS_CONTINUE;
3916 ac->ac_groups_scanned = 0;
3917 ac->ac_ex_scanned = 0;
3920 ac->ac_inode = ar->inode;
3921 ac->ac_o_ex.fe_logical = ar->logical;
3922 ac->ac_o_ex.fe_group = group;
3923 ac->ac_o_ex.fe_start = block;
3924 ac->ac_o_ex.fe_len = len;
3925 ac->ac_g_ex.fe_logical = ar->logical;
3926 ac->ac_g_ex.fe_group = group;
3927 ac->ac_g_ex.fe_start = block;
3928 ac->ac_g_ex.fe_len = len;
3929 ac->ac_f_ex.fe_len = 0;
3930 ac->ac_flags = ar->flags;
3932 ac->ac_criteria = 0;
3934 ac->ac_bitmap_page = NULL;
3935 ac->ac_buddy_page = NULL;
3938 /* we have to define context: we'll we work with a file or
3939 * locality group. this is a policy, actually */
3940 ext4_mb_group_or_file(ac);
3942 mb_debug("init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
3943 "left: %u/%u, right %u/%u to %swritable\n",
3944 (unsigned) ar->len, (unsigned) ar->logical,
3945 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
3946 (unsigned) ar->lleft, (unsigned) ar->pleft,
3947 (unsigned) ar->lright, (unsigned) ar->pright,
3948 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
3954 * release all resource we used in allocation
3956 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
3959 if (ac->ac_pa->pa_linear) {
3960 /* see comment in ext4_mb_use_group_pa() */
3961 spin_lock(&ac->ac_pa->pa_lock);
3962 ac->ac_pa->pa_pstart += ac->ac_b_ex.fe_len;
3963 ac->ac_pa->pa_lstart += ac->ac_b_ex.fe_len;
3964 ac->ac_pa->pa_free -= ac->ac_b_ex.fe_len;
3965 ac->ac_pa->pa_len -= ac->ac_b_ex.fe_len;
3966 spin_unlock(&ac->ac_pa->pa_lock);
3968 ext4_mb_put_pa(ac, ac->ac_sb, ac->ac_pa);
3970 if (ac->ac_bitmap_page)
3971 page_cache_release(ac->ac_bitmap_page);
3972 if (ac->ac_buddy_page)
3973 page_cache_release(ac->ac_buddy_page);
3974 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3975 mutex_unlock(&ac->ac_lg->lg_mutex);
3976 ext4_mb_collect_stats(ac);
3980 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
3986 for (i = 0; i < EXT4_SB(sb)->s_groups_count && needed > 0; i++) {
3987 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
3996 * Main entry point into mballoc to allocate blocks
3997 * it tries to use preallocation first, then falls back
3998 * to usual allocation
4000 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4001 struct ext4_allocation_request *ar, int *errp)
4003 struct ext4_allocation_context *ac = NULL;
4004 struct ext4_sb_info *sbi;
4005 struct super_block *sb;
4006 ext4_fsblk_t block = 0;
4010 sb = ar->inode->i_sb;
4013 if (!test_opt(sb, MBALLOC)) {
4014 block = ext4_new_blocks_old(handle, ar->inode, ar->goal,
4019 while (ar->len && DQUOT_ALLOC_BLOCK(ar->inode, ar->len)) {
4020 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4029 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4035 ext4_mb_poll_new_transaction(sb, handle);
4037 *errp = ext4_mb_initialize_context(ac, ar);
4043 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4044 if (!ext4_mb_use_preallocated(ac)) {
4046 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4047 ext4_mb_normalize_request(ac, ar);
4049 /* allocate space in core */
4050 ext4_mb_regular_allocator(ac);
4052 /* as we've just preallocated more space than
4053 * user requested orinally, we store allocated
4054 * space in a special descriptor */
4055 if (ac->ac_status == AC_STATUS_FOUND &&
4056 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4057 ext4_mb_new_preallocation(ac);
4060 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4061 *errp = ext4_mb_mark_diskspace_used(ac, handle);
4062 if (*errp == -EAGAIN) {
4063 ac->ac_b_ex.fe_group = 0;
4064 ac->ac_b_ex.fe_start = 0;
4065 ac->ac_b_ex.fe_len = 0;
4066 ac->ac_status = AC_STATUS_CONTINUE;
4069 ac->ac_b_ex.fe_len = 0;
4071 ext4_mb_show_ac(ac);
4073 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4074 ar->len = ac->ac_b_ex.fe_len;
4077 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4081 ac->ac_b_ex.fe_len = 0;
4083 ext4_mb_show_ac(ac);
4086 ext4_mb_release_context(ac);
4089 if (ar->len < inquota)
4090 DQUOT_FREE_BLOCK(ar->inode, inquota - ar->len);
4092 kmem_cache_free(ext4_ac_cachep, ac);
4095 static void ext4_mb_poll_new_transaction(struct super_block *sb,
4098 struct ext4_sb_info *sbi = EXT4_SB(sb);
4100 if (sbi->s_last_transaction == handle->h_transaction->t_tid)
4103 /* new transaction! time to close last one and free blocks for
4104 * committed transaction. we know that only transaction can be
4105 * active, so previos transaction can be being logged and we
4106 * know that transaction before previous is known to be already
4107 * logged. this means that now we may free blocks freed in all
4108 * transactions before previous one. hope I'm clear enough ... */
4110 spin_lock(&sbi->s_md_lock);
4111 if (sbi->s_last_transaction != handle->h_transaction->t_tid) {
4112 mb_debug("new transaction %lu, old %lu\n",
4113 (unsigned long) handle->h_transaction->t_tid,
4114 (unsigned long) sbi->s_last_transaction);
4115 list_splice_init(&sbi->s_closed_transaction,
4116 &sbi->s_committed_transaction);
4117 list_splice_init(&sbi->s_active_transaction,
4118 &sbi->s_closed_transaction);
4119 sbi->s_last_transaction = handle->h_transaction->t_tid;
4121 spin_unlock(&sbi->s_md_lock);
4123 ext4_mb_free_committed_blocks(sb);
4126 static noinline_for_stack int
4127 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4128 ext4_group_t group, ext4_grpblk_t block, int count)
4130 struct ext4_group_info *db = e4b->bd_info;
4131 struct super_block *sb = e4b->bd_sb;
4132 struct ext4_sb_info *sbi = EXT4_SB(sb);
4133 struct ext4_free_metadata *md;
4136 BUG_ON(e4b->bd_bitmap_page == NULL);
4137 BUG_ON(e4b->bd_buddy_page == NULL);
4139 ext4_lock_group(sb, group);
4140 for (i = 0; i < count; i++) {
4142 if (md && db->bb_tid != handle->h_transaction->t_tid) {
4143 db->bb_md_cur = NULL;
4148 ext4_unlock_group(sb, group);
4149 md = kmalloc(sizeof(*md), GFP_NOFS);
4155 ext4_lock_group(sb, group);
4156 if (db->bb_md_cur == NULL) {
4157 spin_lock(&sbi->s_md_lock);
4158 list_add(&md->list, &sbi->s_active_transaction);
4159 spin_unlock(&sbi->s_md_lock);
4160 /* protect buddy cache from being freed,
4161 * otherwise we'll refresh it from
4162 * on-disk bitmap and lose not-yet-available
4164 page_cache_get(e4b->bd_buddy_page);
4165 page_cache_get(e4b->bd_bitmap_page);
4167 db->bb_tid = handle->h_transaction->t_tid;
4168 mb_debug("new md 0x%p for group %lu\n",
4176 BUG_ON(md->num >= EXT4_BB_MAX_BLOCKS);
4177 md->blocks[md->num] = block + i;
4179 if (md->num == EXT4_BB_MAX_BLOCKS) {
4180 /* no more space, put full container on a sb's list */
4181 db->bb_md_cur = NULL;
4184 ext4_unlock_group(sb, group);
4189 * Main entry point into mballoc to free blocks
4191 void ext4_mb_free_blocks(handle_t *handle, struct inode *inode,
4192 unsigned long block, unsigned long count,
4193 int metadata, unsigned long *freed)
4195 struct buffer_head *bitmap_bh = NULL;
4196 struct super_block *sb = inode->i_sb;
4197 struct ext4_allocation_context *ac = NULL;
4198 struct ext4_group_desc *gdp;
4199 struct ext4_super_block *es;
4200 unsigned long overflow;
4202 struct buffer_head *gd_bh;
4203 ext4_group_t block_group;
4204 struct ext4_sb_info *sbi;
4205 struct ext4_buddy e4b;
4211 ext4_mb_poll_new_transaction(sb, handle);
4214 es = EXT4_SB(sb)->s_es;
4215 if (block < le32_to_cpu(es->s_first_data_block) ||
4216 block + count < block ||
4217 block + count > ext4_blocks_count(es)) {
4218 ext4_error(sb, __func__,
4219 "Freeing blocks not in datazone - "
4220 "block = %lu, count = %lu", block, count);
4224 ext4_debug("freeing block %lu\n", block);
4226 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4228 ac->ac_op = EXT4_MB_HISTORY_FREE;
4229 ac->ac_inode = inode;
4235 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4238 * Check to see if we are freeing blocks across a group
4241 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4242 overflow = bit + count - EXT4_BLOCKS_PER_GROUP(sb);
4245 bitmap_bh = read_block_bitmap(sb, block_group);
4248 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4252 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4253 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4254 in_range(block, ext4_inode_table(sb, gdp),
4255 EXT4_SB(sb)->s_itb_per_group) ||
4256 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4257 EXT4_SB(sb)->s_itb_per_group)) {
4259 ext4_error(sb, __func__,
4260 "Freeing blocks in system zone - "
4261 "Block = %lu, count = %lu", block, count);
4262 /* err = 0. ext4_std_error should be a no op */
4266 BUFFER_TRACE(bitmap_bh, "getting write access");
4267 err = ext4_journal_get_write_access(handle, bitmap_bh);
4272 * We are about to modify some metadata. Call the journal APIs
4273 * to unshare ->b_data if a currently-committing transaction is
4276 BUFFER_TRACE(gd_bh, "get_write_access");
4277 err = ext4_journal_get_write_access(handle, gd_bh);
4281 err = ext4_mb_load_buddy(sb, block_group, &e4b);
4285 #ifdef AGGRESSIVE_CHECK
4288 for (i = 0; i < count; i++)
4289 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4292 mb_clear_bits(sb_bgl_lock(sbi, block_group), bitmap_bh->b_data,
4295 /* We dirtied the bitmap block */
4296 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4297 err = ext4_journal_dirty_metadata(handle, bitmap_bh);
4300 ac->ac_b_ex.fe_group = block_group;
4301 ac->ac_b_ex.fe_start = bit;
4302 ac->ac_b_ex.fe_len = count;
4303 ext4_mb_store_history(ac);
4307 /* blocks being freed are metadata. these blocks shouldn't
4308 * be used until this transaction is committed */
4309 ext4_mb_free_metadata(handle, &e4b, block_group, bit, count);
4311 ext4_lock_group(sb, block_group);
4312 err = mb_free_blocks(inode, &e4b, bit, count);
4313 ext4_mb_return_to_preallocation(inode, &e4b, block, count);
4314 ext4_unlock_group(sb, block_group);
4318 spin_lock(sb_bgl_lock(sbi, block_group));
4319 le16_add_cpu(&gdp->bg_free_blocks_count, count);
4320 gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4321 spin_unlock(sb_bgl_lock(sbi, block_group));
4322 percpu_counter_add(&sbi->s_freeblocks_counter, count);
4324 ext4_mb_release_desc(&e4b);
4328 /* And the group descriptor block */
4329 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4330 ret = ext4_journal_dirty_metadata(handle, gd_bh);
4334 if (overflow && !err) {
4343 ext4_std_error(sb, err);
4345 kmem_cache_free(ext4_ac_cachep, ac);