xfs: remove block number from inode lookup code
[linux/fpc-iii.git] / fs / ext4 / mballoc.c
blob04e07e227278d0bc13b22fda9e5e9a04107e5b7b
1 /*
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
24 #include "mballoc.h"
25 #include <linux/debugfs.h>
26 #include <trace/events/ext4.h>
29 * MUSTDO:
30 * - test ext4_ext_search_left() and ext4_ext_search_right()
31 * - search for metadata in few groups
33 * TODO v4:
34 * - normalization should take into account whether file is still open
35 * - discard preallocations if no free space left (policy?)
36 * - don't normalize tails
37 * - quota
38 * - reservation for superuser
40 * TODO v3:
41 * - bitmap read-ahead (proposed by Oleg Drokin aka green)
42 * - track min/max extents in each group for better group selection
43 * - mb_mark_used() may allocate chunk right after splitting buddy
44 * - tree of groups sorted by number of free blocks
45 * - error handling
49 * The allocation request involve request for multiple number of blocks
50 * near to the goal(block) value specified.
52 * During initialization phase of the allocator we decide to use the
53 * group preallocation or inode preallocation depending on the size of
54 * the file. The size of the file could be the resulting file size we
55 * would have after allocation, or the current file size, which ever
56 * is larger. If the size is less than sbi->s_mb_stream_request we
57 * select to use the group preallocation. The default value of
58 * s_mb_stream_request is 16 blocks. This can also be tuned via
59 * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
60 * terms of number of blocks.
62 * The main motivation for having small file use group preallocation is to
63 * ensure that we have small files closer together on the disk.
65 * First stage the allocator looks at the inode prealloc list,
66 * ext4_inode_info->i_prealloc_list, which contains list of prealloc
67 * spaces for this particular inode. The inode prealloc space is
68 * represented as:
70 * pa_lstart -> the logical start block for this prealloc space
71 * pa_pstart -> the physical start block for this prealloc space
72 * pa_len -> lenght for this prealloc space
73 * pa_free -> free space available in this prealloc space
75 * The inode preallocation space is used looking at the _logical_ start
76 * block. If only the logical file block falls within the range of prealloc
77 * space we will consume the particular prealloc space. This make sure that
78 * that the we have contiguous physical blocks representing the file blocks
80 * The important thing to be noted in case of inode prealloc space is that
81 * we don't modify the values associated to inode prealloc space except
82 * pa_free.
84 * If we are not able to find blocks in the inode prealloc space and if we
85 * have the group allocation flag set then we look at the locality group
86 * prealloc space. These are per CPU prealloc list repreasented as
88 * ext4_sb_info.s_locality_groups[smp_processor_id()]
90 * The reason for having a per cpu locality group is to reduce the contention
91 * between CPUs. It is possible to get scheduled at this point.
93 * The locality group prealloc space is used looking at whether we have
94 * enough free space (pa_free) withing the prealloc space.
96 * If we can't allocate blocks via inode prealloc or/and locality group
97 * prealloc then we look at the buddy cache. The buddy cache is represented
98 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
99 * mapped to the buddy and bitmap information regarding different
100 * groups. The buddy information is attached to buddy cache inode so that
101 * we can access them through the page cache. The information regarding
102 * each group is loaded via ext4_mb_load_buddy. The information involve
103 * block bitmap and buddy information. The information are stored in the
104 * inode as:
106 * { page }
107 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
110 * one block each for bitmap and buddy information. So for each group we
111 * take up 2 blocks. A page can contain blocks_per_page (PAGE_CACHE_SIZE /
112 * blocksize) blocks. So it can have information regarding groups_per_page
113 * which is blocks_per_page/2
115 * The buddy cache inode is not stored on disk. The inode is thrown
116 * away when the filesystem is unmounted.
118 * We look for count number of blocks in the buddy cache. If we were able
119 * to locate that many free blocks we return with additional information
120 * regarding rest of the contiguous physical block available
122 * Before allocating blocks via buddy cache we normalize the request
123 * blocks. This ensure we ask for more blocks that we needed. The extra
124 * blocks that we get after allocation is added to the respective prealloc
125 * list. In case of inode preallocation we follow a list of heuristics
126 * based on file size. This can be found in ext4_mb_normalize_request. If
127 * we are doing a group prealloc we try to normalize the request to
128 * sbi->s_mb_group_prealloc. Default value of s_mb_group_prealloc is
129 * 512 blocks. This can be tuned via
130 * /sys/fs/ext4/<partition/mb_group_prealloc. The value is represented in
131 * terms of number of blocks. If we have mounted the file system with -O
132 * stripe=<value> option the group prealloc request is normalized to the
133 * stripe value (sbi->s_stripe)
135 * The regular allocator(using the buddy cache) supports few tunables.
137 * /sys/fs/ext4/<partition>/mb_min_to_scan
138 * /sys/fs/ext4/<partition>/mb_max_to_scan
139 * /sys/fs/ext4/<partition>/mb_order2_req
141 * The regular allocator uses buddy scan only if the request len is power of
142 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
143 * value of s_mb_order2_reqs can be tuned via
144 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
145 * stripe size (sbi->s_stripe), we try to search for contigous block in
146 * stripe size. This should result in better allocation on RAID setups. If
147 * not, we search in the specific group using bitmap for best extents. The
148 * tunable min_to_scan and max_to_scan control the behaviour here.
149 * min_to_scan indicate how long the mballoc __must__ look for a best
150 * extent and max_to_scan indicates how long the mballoc __can__ look for a
151 * best extent in the found extents. Searching for the blocks starts with
152 * the group specified as the goal value in allocation context via
153 * ac_g_ex. Each group is first checked based on the criteria whether it
154 * can used for allocation. ext4_mb_good_group explains how the groups are
155 * checked.
157 * Both the prealloc space are getting populated as above. So for the first
158 * request we will hit the buddy cache which will result in this prealloc
159 * space getting filled. The prealloc space is then later used for the
160 * subsequent request.
164 * mballoc operates on the following data:
165 * - on-disk bitmap
166 * - in-core buddy (actually includes buddy and bitmap)
167 * - preallocation descriptors (PAs)
169 * there are two types of preallocations:
170 * - inode
171 * assiged to specific inode and can be used for this inode only.
172 * it describes part of inode's space preallocated to specific
173 * physical blocks. any block from that preallocated can be used
174 * independent. the descriptor just tracks number of blocks left
175 * unused. so, before taking some block from descriptor, one must
176 * make sure corresponded logical block isn't allocated yet. this
177 * also means that freeing any block within descriptor's range
178 * must discard all preallocated blocks.
179 * - locality group
180 * assigned to specific locality group which does not translate to
181 * permanent set of inodes: inode can join and leave group. space
182 * from this type of preallocation can be used for any inode. thus
183 * it's consumed from the beginning to the end.
185 * relation between them can be expressed as:
186 * in-core buddy = on-disk bitmap + preallocation descriptors
188 * this mean blocks mballoc considers used are:
189 * - allocated blocks (persistent)
190 * - preallocated blocks (non-persistent)
192 * consistency in mballoc world means that at any time a block is either
193 * free or used in ALL structures. notice: "any time" should not be read
194 * literally -- time is discrete and delimited by locks.
196 * to keep it simple, we don't use block numbers, instead we count number of
197 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
199 * all operations can be expressed as:
200 * - init buddy: buddy = on-disk + PAs
201 * - new PA: buddy += N; PA = N
202 * - use inode PA: on-disk += N; PA -= N
203 * - discard inode PA buddy -= on-disk - PA; PA = 0
204 * - use locality group PA on-disk += N; PA -= N
205 * - discard locality group PA buddy -= PA; PA = 0
206 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
207 * is used in real operation because we can't know actual used
208 * bits from PA, only from on-disk bitmap
210 * if we follow this strict logic, then all operations above should be atomic.
211 * given some of them can block, we'd have to use something like semaphores
212 * killing performance on high-end SMP hardware. let's try to relax it using
213 * the following knowledge:
214 * 1) if buddy is referenced, it's already initialized
215 * 2) while block is used in buddy and the buddy is referenced,
216 * nobody can re-allocate that block
217 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
218 * bit set and PA claims same block, it's OK. IOW, one can set bit in
219 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
220 * block
222 * so, now we're building a concurrency table:
223 * - init buddy vs.
224 * - new PA
225 * blocks for PA are allocated in the buddy, buddy must be referenced
226 * until PA is linked to allocation group to avoid concurrent buddy init
227 * - use inode PA
228 * we need to make sure that either on-disk bitmap or PA has uptodate data
229 * given (3) we care that PA-=N operation doesn't interfere with init
230 * - discard inode PA
231 * the simplest way would be to have buddy initialized by the discard
232 * - use locality group PA
233 * again PA-=N must be serialized with init
234 * - discard locality group PA
235 * the simplest way would be to have buddy initialized by the discard
236 * - new PA vs.
237 * - use inode PA
238 * i_data_sem serializes them
239 * - discard inode PA
240 * discard process must wait until PA isn't used by another process
241 * - use locality group PA
242 * some mutex should serialize them
243 * - discard locality group PA
244 * discard process must wait until PA isn't used by another process
245 * - use inode PA
246 * - use inode PA
247 * i_data_sem or another mutex should serializes them
248 * - discard inode PA
249 * discard process must wait until PA isn't used by another process
250 * - use locality group PA
251 * nothing wrong here -- they're different PAs covering different blocks
252 * - discard locality group PA
253 * discard process must wait until PA isn't used by another process
255 * now we're ready to make few consequences:
256 * - PA is referenced and while it is no discard is possible
257 * - PA is referenced until block isn't marked in on-disk bitmap
258 * - PA changes only after on-disk bitmap
259 * - discard must not compete with init. either init is done before
260 * any discard or they're serialized somehow
261 * - buddy init as sum of on-disk bitmap and PAs is done atomically
263 * a special case when we've used PA to emptiness. no need to modify buddy
264 * in this case, but we should care about concurrent init
269 * Logic in few words:
271 * - allocation:
272 * load group
273 * find blocks
274 * mark bits in on-disk bitmap
275 * release group
277 * - use preallocation:
278 * find proper PA (per-inode or group)
279 * load group
280 * mark bits in on-disk bitmap
281 * release group
282 * release PA
284 * - free:
285 * load group
286 * mark bits in on-disk bitmap
287 * release group
289 * - discard preallocations in group:
290 * mark PAs deleted
291 * move them onto local list
292 * load on-disk bitmap
293 * load group
294 * remove PA from object (inode or locality group)
295 * mark free blocks in-core
297 * - discard inode's preallocations:
301 * Locking rules
303 * Locks:
304 * - bitlock on a group (group)
305 * - object (inode/locality) (object)
306 * - per-pa lock (pa)
308 * Paths:
309 * - new pa
310 * object
311 * group
313 * - find and use pa:
314 * pa
316 * - release consumed pa:
317 * pa
318 * group
319 * object
321 * - generate in-core bitmap:
322 * group
323 * pa
325 * - discard all for given object (inode, locality group):
326 * object
327 * pa
328 * group
330 * - discard all for given group:
331 * group
332 * pa
333 * group
334 * object
337 static struct kmem_cache *ext4_pspace_cachep;
338 static struct kmem_cache *ext4_ac_cachep;
339 static struct kmem_cache *ext4_free_ext_cachep;
340 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
341 ext4_group_t group);
342 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
343 ext4_group_t group);
344 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn);
346 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
348 #if BITS_PER_LONG == 64
349 *bit += ((unsigned long) addr & 7UL) << 3;
350 addr = (void *) ((unsigned long) addr & ~7UL);
351 #elif BITS_PER_LONG == 32
352 *bit += ((unsigned long) addr & 3UL) << 3;
353 addr = (void *) ((unsigned long) addr & ~3UL);
354 #else
355 #error "how many bits you are?!"
356 #endif
357 return addr;
360 static inline int mb_test_bit(int bit, void *addr)
363 * ext4_test_bit on architecture like powerpc
364 * needs unsigned long aligned address
366 addr = mb_correct_addr_and_bit(&bit, addr);
367 return ext4_test_bit(bit, addr);
370 static inline void mb_set_bit(int bit, void *addr)
372 addr = mb_correct_addr_and_bit(&bit, addr);
373 ext4_set_bit(bit, addr);
376 static inline void mb_clear_bit(int bit, void *addr)
378 addr = mb_correct_addr_and_bit(&bit, addr);
379 ext4_clear_bit(bit, addr);
382 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
384 int fix = 0, ret, tmpmax;
385 addr = mb_correct_addr_and_bit(&fix, addr);
386 tmpmax = max + fix;
387 start += fix;
389 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
390 if (ret > max)
391 return max;
392 return ret;
395 static inline int mb_find_next_bit(void *addr, int max, int start)
397 int fix = 0, ret, tmpmax;
398 addr = mb_correct_addr_and_bit(&fix, addr);
399 tmpmax = max + fix;
400 start += fix;
402 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
403 if (ret > max)
404 return max;
405 return ret;
408 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
410 char *bb;
412 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
413 BUG_ON(max == NULL);
415 if (order > e4b->bd_blkbits + 1) {
416 *max = 0;
417 return NULL;
420 /* at order 0 we see each particular block */
421 *max = 1 << (e4b->bd_blkbits + 3);
422 if (order == 0)
423 return EXT4_MB_BITMAP(e4b);
425 bb = EXT4_MB_BUDDY(e4b) + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
426 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
428 return bb;
431 #ifdef DOUBLE_CHECK
432 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
433 int first, int count)
435 int i;
436 struct super_block *sb = e4b->bd_sb;
438 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
439 return;
440 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
441 for (i = 0; i < count; i++) {
442 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
443 ext4_fsblk_t blocknr;
444 blocknr = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb);
445 blocknr += first + i;
446 blocknr +=
447 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
448 ext4_grp_locked_error(sb, e4b->bd_group,
449 __func__, "double-free of inode"
450 " %lu's block %llu(bit %u in group %u)",
451 inode ? inode->i_ino : 0, blocknr,
452 first + i, e4b->bd_group);
454 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
458 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
460 int i;
462 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
463 return;
464 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
465 for (i = 0; i < count; i++) {
466 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
467 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
471 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
473 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
474 unsigned char *b1, *b2;
475 int i;
476 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
477 b2 = (unsigned char *) bitmap;
478 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
479 if (b1[i] != b2[i]) {
480 printk(KERN_ERR "corruption in group %u "
481 "at byte %u(%u): %x in copy != %x "
482 "on disk/prealloc\n",
483 e4b->bd_group, i, i * 8, b1[i], b2[i]);
484 BUG();
490 #else
491 static inline void mb_free_blocks_double(struct inode *inode,
492 struct ext4_buddy *e4b, int first, int count)
494 return;
496 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
497 int first, int count)
499 return;
501 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
503 return;
505 #endif
507 #ifdef AGGRESSIVE_CHECK
509 #define MB_CHECK_ASSERT(assert) \
510 do { \
511 if (!(assert)) { \
512 printk(KERN_EMERG \
513 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
514 function, file, line, # assert); \
515 BUG(); \
517 } while (0)
519 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
520 const char *function, int line)
522 struct super_block *sb = e4b->bd_sb;
523 int order = e4b->bd_blkbits + 1;
524 int max;
525 int max2;
526 int i;
527 int j;
528 int k;
529 int count;
530 struct ext4_group_info *grp;
531 int fragments = 0;
532 int fstart;
533 struct list_head *cur;
534 void *buddy;
535 void *buddy2;
538 static int mb_check_counter;
539 if (mb_check_counter++ % 100 != 0)
540 return 0;
543 while (order > 1) {
544 buddy = mb_find_buddy(e4b, order, &max);
545 MB_CHECK_ASSERT(buddy);
546 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
547 MB_CHECK_ASSERT(buddy2);
548 MB_CHECK_ASSERT(buddy != buddy2);
549 MB_CHECK_ASSERT(max * 2 == max2);
551 count = 0;
552 for (i = 0; i < max; i++) {
554 if (mb_test_bit(i, buddy)) {
555 /* only single bit in buddy2 may be 1 */
556 if (!mb_test_bit(i << 1, buddy2)) {
557 MB_CHECK_ASSERT(
558 mb_test_bit((i<<1)+1, buddy2));
559 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
560 MB_CHECK_ASSERT(
561 mb_test_bit(i << 1, buddy2));
563 continue;
566 /* both bits in buddy2 must be 0 */
567 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
568 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
570 for (j = 0; j < (1 << order); j++) {
571 k = (i * (1 << order)) + j;
572 MB_CHECK_ASSERT(
573 !mb_test_bit(k, EXT4_MB_BITMAP(e4b)));
575 count++;
577 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
578 order--;
581 fstart = -1;
582 buddy = mb_find_buddy(e4b, 0, &max);
583 for (i = 0; i < max; i++) {
584 if (!mb_test_bit(i, buddy)) {
585 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
586 if (fstart == -1) {
587 fragments++;
588 fstart = i;
590 continue;
592 fstart = -1;
593 /* check used bits only */
594 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
595 buddy2 = mb_find_buddy(e4b, j, &max2);
596 k = i >> j;
597 MB_CHECK_ASSERT(k < max2);
598 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
601 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
602 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
604 grp = ext4_get_group_info(sb, e4b->bd_group);
605 buddy = mb_find_buddy(e4b, 0, &max);
606 list_for_each(cur, &grp->bb_prealloc_list) {
607 ext4_group_t groupnr;
608 struct ext4_prealloc_space *pa;
609 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
610 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
611 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
612 for (i = 0; i < pa->pa_len; i++)
613 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
615 return 0;
617 #undef MB_CHECK_ASSERT
618 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
619 __FILE__, __func__, __LINE__)
620 #else
621 #define mb_check_buddy(e4b)
622 #endif
624 /* FIXME!! need more doc */
625 static void ext4_mb_mark_free_simple(struct super_block *sb,
626 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
627 struct ext4_group_info *grp)
629 struct ext4_sb_info *sbi = EXT4_SB(sb);
630 ext4_grpblk_t min;
631 ext4_grpblk_t max;
632 ext4_grpblk_t chunk;
633 unsigned short border;
635 BUG_ON(len > EXT4_BLOCKS_PER_GROUP(sb));
637 border = 2 << sb->s_blocksize_bits;
639 while (len > 0) {
640 /* find how many blocks can be covered since this position */
641 max = ffs(first | border) - 1;
643 /* find how many blocks of power 2 we need to mark */
644 min = fls(len) - 1;
646 if (max < min)
647 min = max;
648 chunk = 1 << min;
650 /* mark multiblock chunks only */
651 grp->bb_counters[min]++;
652 if (min > 0)
653 mb_clear_bit(first >> min,
654 buddy + sbi->s_mb_offsets[min]);
656 len -= chunk;
657 first += chunk;
662 * Cache the order of the largest free extent we have available in this block
663 * group.
665 static void
666 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
668 int i;
669 int bits;
671 grp->bb_largest_free_order = -1; /* uninit */
673 bits = sb->s_blocksize_bits + 1;
674 for (i = bits; i >= 0; i--) {
675 if (grp->bb_counters[i] > 0) {
676 grp->bb_largest_free_order = i;
677 break;
682 static noinline_for_stack
683 void ext4_mb_generate_buddy(struct super_block *sb,
684 void *buddy, void *bitmap, ext4_group_t group)
686 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
687 ext4_grpblk_t max = EXT4_BLOCKS_PER_GROUP(sb);
688 ext4_grpblk_t i = 0;
689 ext4_grpblk_t first;
690 ext4_grpblk_t len;
691 unsigned free = 0;
692 unsigned fragments = 0;
693 unsigned long long period = get_cycles();
695 /* initialize buddy from bitmap which is aggregation
696 * of on-disk bitmap and preallocations */
697 i = mb_find_next_zero_bit(bitmap, max, 0);
698 grp->bb_first_free = i;
699 while (i < max) {
700 fragments++;
701 first = i;
702 i = mb_find_next_bit(bitmap, max, i);
703 len = i - first;
704 free += len;
705 if (len > 1)
706 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
707 else
708 grp->bb_counters[0]++;
709 if (i < max)
710 i = mb_find_next_zero_bit(bitmap, max, i);
712 grp->bb_fragments = fragments;
714 if (free != grp->bb_free) {
715 ext4_grp_locked_error(sb, group, __func__,
716 "EXT4-fs: group %u: %u blocks in bitmap, %u in gd",
717 group, free, grp->bb_free);
719 * If we intent to continue, we consider group descritor
720 * corrupt and update bb_free using bitmap value
722 grp->bb_free = free;
724 mb_set_largest_free_order(sb, grp);
726 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
728 period = get_cycles() - period;
729 spin_lock(&EXT4_SB(sb)->s_bal_lock);
730 EXT4_SB(sb)->s_mb_buddies_generated++;
731 EXT4_SB(sb)->s_mb_generation_time += period;
732 spin_unlock(&EXT4_SB(sb)->s_bal_lock);
735 /* The buddy information is attached the buddy cache inode
736 * for convenience. The information regarding each group
737 * is loaded via ext4_mb_load_buddy. The information involve
738 * block bitmap and buddy information. The information are
739 * stored in the inode as
741 * { page }
742 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
745 * one block each for bitmap and buddy information.
746 * So for each group we take up 2 blocks. A page can
747 * contain blocks_per_page (PAGE_CACHE_SIZE / blocksize) blocks.
748 * So it can have information regarding groups_per_page which
749 * is blocks_per_page/2
751 * Locking note: This routine takes the block group lock of all groups
752 * for this page; do not hold this lock when calling this routine!
755 static int ext4_mb_init_cache(struct page *page, char *incore)
757 ext4_group_t ngroups;
758 int blocksize;
759 int blocks_per_page;
760 int groups_per_page;
761 int err = 0;
762 int i;
763 ext4_group_t first_group;
764 int first_block;
765 struct super_block *sb;
766 struct buffer_head *bhs;
767 struct buffer_head **bh;
768 struct inode *inode;
769 char *data;
770 char *bitmap;
772 mb_debug(1, "init page %lu\n", page->index);
774 inode = page->mapping->host;
775 sb = inode->i_sb;
776 ngroups = ext4_get_groups_count(sb);
777 blocksize = 1 << inode->i_blkbits;
778 blocks_per_page = PAGE_CACHE_SIZE / blocksize;
780 groups_per_page = blocks_per_page >> 1;
781 if (groups_per_page == 0)
782 groups_per_page = 1;
784 /* allocate buffer_heads to read bitmaps */
785 if (groups_per_page > 1) {
786 err = -ENOMEM;
787 i = sizeof(struct buffer_head *) * groups_per_page;
788 bh = kzalloc(i, GFP_NOFS);
789 if (bh == NULL)
790 goto out;
791 } else
792 bh = &bhs;
794 first_group = page->index * blocks_per_page / 2;
796 /* read all groups the page covers into the cache */
797 for (i = 0; i < groups_per_page; i++) {
798 struct ext4_group_desc *desc;
800 if (first_group + i >= ngroups)
801 break;
803 err = -EIO;
804 desc = ext4_get_group_desc(sb, first_group + i, NULL);
805 if (desc == NULL)
806 goto out;
808 err = -ENOMEM;
809 bh[i] = sb_getblk(sb, ext4_block_bitmap(sb, desc));
810 if (bh[i] == NULL)
811 goto out;
813 if (bitmap_uptodate(bh[i]))
814 continue;
816 lock_buffer(bh[i]);
817 if (bitmap_uptodate(bh[i])) {
818 unlock_buffer(bh[i]);
819 continue;
821 ext4_lock_group(sb, first_group + i);
822 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
823 ext4_init_block_bitmap(sb, bh[i],
824 first_group + i, desc);
825 set_bitmap_uptodate(bh[i]);
826 set_buffer_uptodate(bh[i]);
827 ext4_unlock_group(sb, first_group + i);
828 unlock_buffer(bh[i]);
829 continue;
831 ext4_unlock_group(sb, first_group + i);
832 if (buffer_uptodate(bh[i])) {
834 * if not uninit if bh is uptodate,
835 * bitmap is also uptodate
837 set_bitmap_uptodate(bh[i]);
838 unlock_buffer(bh[i]);
839 continue;
841 get_bh(bh[i]);
843 * submit the buffer_head for read. We can
844 * safely mark the bitmap as uptodate now.
845 * We do it here so the bitmap uptodate bit
846 * get set with buffer lock held.
848 set_bitmap_uptodate(bh[i]);
849 bh[i]->b_end_io = end_buffer_read_sync;
850 submit_bh(READ, bh[i]);
851 mb_debug(1, "read bitmap for group %u\n", first_group + i);
854 /* wait for I/O completion */
855 for (i = 0; i < groups_per_page && bh[i]; i++)
856 wait_on_buffer(bh[i]);
858 err = -EIO;
859 for (i = 0; i < groups_per_page && bh[i]; i++)
860 if (!buffer_uptodate(bh[i]))
861 goto out;
863 err = 0;
864 first_block = page->index * blocks_per_page;
865 /* init the page */
866 memset(page_address(page), 0xff, PAGE_CACHE_SIZE);
867 for (i = 0; i < blocks_per_page; i++) {
868 int group;
869 struct ext4_group_info *grinfo;
871 group = (first_block + i) >> 1;
872 if (group >= ngroups)
873 break;
876 * data carry information regarding this
877 * particular group in the format specified
878 * above
881 data = page_address(page) + (i * blocksize);
882 bitmap = bh[group - first_group]->b_data;
885 * We place the buddy block and bitmap block
886 * close together
888 if ((first_block + i) & 1) {
889 /* this is block of buddy */
890 BUG_ON(incore == NULL);
891 mb_debug(1, "put buddy for group %u in page %lu/%x\n",
892 group, page->index, i * blocksize);
893 grinfo = ext4_get_group_info(sb, group);
894 grinfo->bb_fragments = 0;
895 memset(grinfo->bb_counters, 0,
896 sizeof(*grinfo->bb_counters) *
897 (sb->s_blocksize_bits+2));
899 * incore got set to the group block bitmap below
901 ext4_lock_group(sb, group);
902 ext4_mb_generate_buddy(sb, data, incore, group);
903 ext4_unlock_group(sb, group);
904 incore = NULL;
905 } else {
906 /* this is block of bitmap */
907 BUG_ON(incore != NULL);
908 mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
909 group, page->index, i * blocksize);
911 /* see comments in ext4_mb_put_pa() */
912 ext4_lock_group(sb, group);
913 memcpy(data, bitmap, blocksize);
915 /* mark all preallocated blks used in in-core bitmap */
916 ext4_mb_generate_from_pa(sb, data, group);
917 ext4_mb_generate_from_freelist(sb, data, group);
918 ext4_unlock_group(sb, group);
920 /* set incore so that the buddy information can be
921 * generated using this
923 incore = data;
926 SetPageUptodate(page);
928 out:
929 if (bh) {
930 for (i = 0; i < groups_per_page && bh[i]; i++)
931 brelse(bh[i]);
932 if (bh != &bhs)
933 kfree(bh);
935 return err;
939 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
940 * block group lock of all groups for this page; do not hold the BG lock when
941 * calling this routine!
943 static noinline_for_stack
944 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group)
947 int ret = 0;
948 void *bitmap;
949 int blocks_per_page;
950 int block, pnum, poff;
951 int num_grp_locked = 0;
952 struct ext4_group_info *this_grp;
953 struct ext4_sb_info *sbi = EXT4_SB(sb);
954 struct inode *inode = sbi->s_buddy_cache;
955 struct page *page = NULL, *bitmap_page = NULL;
957 mb_debug(1, "init group %u\n", group);
958 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
959 this_grp = ext4_get_group_info(sb, group);
961 * This ensures that we don't reinit the buddy cache
962 * page which map to the group from which we are already
963 * allocating. If we are looking at the buddy cache we would
964 * have taken a reference using ext4_mb_load_buddy and that
965 * would have taken the alloc_sem lock.
967 num_grp_locked = ext4_mb_get_buddy_cache_lock(sb, group);
968 if (!EXT4_MB_GRP_NEED_INIT(this_grp)) {
970 * somebody initialized the group
971 * return without doing anything
973 ret = 0;
974 goto err;
977 * the buddy cache inode stores the block bitmap
978 * and buddy information in consecutive blocks.
979 * So for each group we need two blocks.
981 block = group * 2;
982 pnum = block / blocks_per_page;
983 poff = block % blocks_per_page;
984 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
985 if (page) {
986 BUG_ON(page->mapping != inode->i_mapping);
987 ret = ext4_mb_init_cache(page, NULL);
988 if (ret) {
989 unlock_page(page);
990 goto err;
992 unlock_page(page);
994 if (page == NULL || !PageUptodate(page)) {
995 ret = -EIO;
996 goto err;
998 mark_page_accessed(page);
999 bitmap_page = page;
1000 bitmap = page_address(page) + (poff * sb->s_blocksize);
1002 /* init buddy cache */
1003 block++;
1004 pnum = block / blocks_per_page;
1005 poff = block % blocks_per_page;
1006 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1007 if (page == bitmap_page) {
1009 * If both the bitmap and buddy are in
1010 * the same page we don't need to force
1011 * init the buddy
1013 unlock_page(page);
1014 } else if (page) {
1015 BUG_ON(page->mapping != inode->i_mapping);
1016 ret = ext4_mb_init_cache(page, bitmap);
1017 if (ret) {
1018 unlock_page(page);
1019 goto err;
1021 unlock_page(page);
1023 if (page == NULL || !PageUptodate(page)) {
1024 ret = -EIO;
1025 goto err;
1027 mark_page_accessed(page);
1028 err:
1029 ext4_mb_put_buddy_cache_lock(sb, group, num_grp_locked);
1030 if (bitmap_page)
1031 page_cache_release(bitmap_page);
1032 if (page)
1033 page_cache_release(page);
1034 return ret;
1038 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1039 * block group lock of all groups for this page; do not hold the BG lock when
1040 * calling this routine!
1042 static noinline_for_stack int
1043 ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1044 struct ext4_buddy *e4b)
1046 int blocks_per_page;
1047 int block;
1048 int pnum;
1049 int poff;
1050 struct page *page;
1051 int ret;
1052 struct ext4_group_info *grp;
1053 struct ext4_sb_info *sbi = EXT4_SB(sb);
1054 struct inode *inode = sbi->s_buddy_cache;
1056 mb_debug(1, "load group %u\n", group);
1058 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1059 grp = ext4_get_group_info(sb, group);
1061 e4b->bd_blkbits = sb->s_blocksize_bits;
1062 e4b->bd_info = ext4_get_group_info(sb, group);
1063 e4b->bd_sb = sb;
1064 e4b->bd_group = group;
1065 e4b->bd_buddy_page = NULL;
1066 e4b->bd_bitmap_page = NULL;
1067 e4b->alloc_semp = &grp->alloc_sem;
1069 /* Take the read lock on the group alloc
1070 * sem. This would make sure a parallel
1071 * ext4_mb_init_group happening on other
1072 * groups mapped by the page is blocked
1073 * till we are done with allocation
1075 repeat_load_buddy:
1076 down_read(e4b->alloc_semp);
1078 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1079 /* we need to check for group need init flag
1080 * with alloc_semp held so that we can be sure
1081 * that new blocks didn't get added to the group
1082 * when we are loading the buddy cache
1084 up_read(e4b->alloc_semp);
1086 * we need full data about the group
1087 * to make a good selection
1089 ret = ext4_mb_init_group(sb, group);
1090 if (ret)
1091 return ret;
1092 goto repeat_load_buddy;
1096 * the buddy cache inode stores the block bitmap
1097 * and buddy information in consecutive blocks.
1098 * So for each group we need two blocks.
1100 block = group * 2;
1101 pnum = block / blocks_per_page;
1102 poff = block % blocks_per_page;
1104 /* we could use find_or_create_page(), but it locks page
1105 * what we'd like to avoid in fast path ... */
1106 page = find_get_page(inode->i_mapping, pnum);
1107 if (page == NULL || !PageUptodate(page)) {
1108 if (page)
1110 * drop the page reference and try
1111 * to get the page with lock. If we
1112 * are not uptodate that implies
1113 * somebody just created the page but
1114 * is yet to initialize the same. So
1115 * wait for it to initialize.
1117 page_cache_release(page);
1118 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1119 if (page) {
1120 BUG_ON(page->mapping != inode->i_mapping);
1121 if (!PageUptodate(page)) {
1122 ret = ext4_mb_init_cache(page, NULL);
1123 if (ret) {
1124 unlock_page(page);
1125 goto err;
1127 mb_cmp_bitmaps(e4b, page_address(page) +
1128 (poff * sb->s_blocksize));
1130 unlock_page(page);
1133 if (page == NULL || !PageUptodate(page)) {
1134 ret = -EIO;
1135 goto err;
1137 e4b->bd_bitmap_page = page;
1138 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1139 mark_page_accessed(page);
1141 block++;
1142 pnum = block / blocks_per_page;
1143 poff = block % blocks_per_page;
1145 page = find_get_page(inode->i_mapping, pnum);
1146 if (page == NULL || !PageUptodate(page)) {
1147 if (page)
1148 page_cache_release(page);
1149 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1150 if (page) {
1151 BUG_ON(page->mapping != inode->i_mapping);
1152 if (!PageUptodate(page)) {
1153 ret = ext4_mb_init_cache(page, e4b->bd_bitmap);
1154 if (ret) {
1155 unlock_page(page);
1156 goto err;
1159 unlock_page(page);
1162 if (page == NULL || !PageUptodate(page)) {
1163 ret = -EIO;
1164 goto err;
1166 e4b->bd_buddy_page = page;
1167 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1168 mark_page_accessed(page);
1170 BUG_ON(e4b->bd_bitmap_page == NULL);
1171 BUG_ON(e4b->bd_buddy_page == NULL);
1173 return 0;
1175 err:
1176 if (e4b->bd_bitmap_page)
1177 page_cache_release(e4b->bd_bitmap_page);
1178 if (e4b->bd_buddy_page)
1179 page_cache_release(e4b->bd_buddy_page);
1180 e4b->bd_buddy = NULL;
1181 e4b->bd_bitmap = NULL;
1183 /* Done with the buddy cache */
1184 up_read(e4b->alloc_semp);
1185 return ret;
1188 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1190 if (e4b->bd_bitmap_page)
1191 page_cache_release(e4b->bd_bitmap_page);
1192 if (e4b->bd_buddy_page)
1193 page_cache_release(e4b->bd_buddy_page);
1194 /* Done with the buddy cache */
1195 if (e4b->alloc_semp)
1196 up_read(e4b->alloc_semp);
1200 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1202 int order = 1;
1203 void *bb;
1205 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
1206 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1208 bb = EXT4_MB_BUDDY(e4b);
1209 while (order <= e4b->bd_blkbits + 1) {
1210 block = block >> 1;
1211 if (!mb_test_bit(block, bb)) {
1212 /* this block is part of buddy of order 'order' */
1213 return order;
1215 bb += 1 << (e4b->bd_blkbits - order);
1216 order++;
1218 return 0;
1221 static void mb_clear_bits(void *bm, int cur, int len)
1223 __u32 *addr;
1225 len = cur + len;
1226 while (cur < len) {
1227 if ((cur & 31) == 0 && (len - cur) >= 32) {
1228 /* fast path: clear whole word at once */
1229 addr = bm + (cur >> 3);
1230 *addr = 0;
1231 cur += 32;
1232 continue;
1234 mb_clear_bit(cur, bm);
1235 cur++;
1239 static void mb_set_bits(void *bm, int cur, int len)
1241 __u32 *addr;
1243 len = cur + len;
1244 while (cur < len) {
1245 if ((cur & 31) == 0 && (len - cur) >= 32) {
1246 /* fast path: set whole word at once */
1247 addr = bm + (cur >> 3);
1248 *addr = 0xffffffff;
1249 cur += 32;
1250 continue;
1252 mb_set_bit(cur, bm);
1253 cur++;
1257 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1258 int first, int count)
1260 int block = 0;
1261 int max = 0;
1262 int order;
1263 void *buddy;
1264 void *buddy2;
1265 struct super_block *sb = e4b->bd_sb;
1267 BUG_ON(first + count > (sb->s_blocksize << 3));
1268 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1269 mb_check_buddy(e4b);
1270 mb_free_blocks_double(inode, e4b, first, count);
1272 e4b->bd_info->bb_free += count;
1273 if (first < e4b->bd_info->bb_first_free)
1274 e4b->bd_info->bb_first_free = first;
1276 /* let's maintain fragments counter */
1277 if (first != 0)
1278 block = !mb_test_bit(first - 1, EXT4_MB_BITMAP(e4b));
1279 if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
1280 max = !mb_test_bit(first + count, EXT4_MB_BITMAP(e4b));
1281 if (block && max)
1282 e4b->bd_info->bb_fragments--;
1283 else if (!block && !max)
1284 e4b->bd_info->bb_fragments++;
1286 /* let's maintain buddy itself */
1287 while (count-- > 0) {
1288 block = first++;
1289 order = 0;
1291 if (!mb_test_bit(block, EXT4_MB_BITMAP(e4b))) {
1292 ext4_fsblk_t blocknr;
1293 blocknr = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb);
1294 blocknr += block;
1295 blocknr +=
1296 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
1297 ext4_grp_locked_error(sb, e4b->bd_group,
1298 __func__, "double-free of inode"
1299 " %lu's block %llu(bit %u in group %u)",
1300 inode ? inode->i_ino : 0, blocknr, block,
1301 e4b->bd_group);
1303 mb_clear_bit(block, EXT4_MB_BITMAP(e4b));
1304 e4b->bd_info->bb_counters[order]++;
1306 /* start of the buddy */
1307 buddy = mb_find_buddy(e4b, order, &max);
1309 do {
1310 block &= ~1UL;
1311 if (mb_test_bit(block, buddy) ||
1312 mb_test_bit(block + 1, buddy))
1313 break;
1315 /* both the buddies are free, try to coalesce them */
1316 buddy2 = mb_find_buddy(e4b, order + 1, &max);
1318 if (!buddy2)
1319 break;
1321 if (order > 0) {
1322 /* for special purposes, we don't set
1323 * free bits in bitmap */
1324 mb_set_bit(block, buddy);
1325 mb_set_bit(block + 1, buddy);
1327 e4b->bd_info->bb_counters[order]--;
1328 e4b->bd_info->bb_counters[order]--;
1330 block = block >> 1;
1331 order++;
1332 e4b->bd_info->bb_counters[order]++;
1334 mb_clear_bit(block, buddy2);
1335 buddy = buddy2;
1336 } while (1);
1338 mb_set_largest_free_order(sb, e4b->bd_info);
1339 mb_check_buddy(e4b);
1342 static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
1343 int needed, struct ext4_free_extent *ex)
1345 int next = block;
1346 int max;
1347 int ord;
1348 void *buddy;
1350 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1351 BUG_ON(ex == NULL);
1353 buddy = mb_find_buddy(e4b, order, &max);
1354 BUG_ON(buddy == NULL);
1355 BUG_ON(block >= max);
1356 if (mb_test_bit(block, buddy)) {
1357 ex->fe_len = 0;
1358 ex->fe_start = 0;
1359 ex->fe_group = 0;
1360 return 0;
1363 /* FIXME dorp order completely ? */
1364 if (likely(order == 0)) {
1365 /* find actual order */
1366 order = mb_find_order_for_block(e4b, block);
1367 block = block >> order;
1370 ex->fe_len = 1 << order;
1371 ex->fe_start = block << order;
1372 ex->fe_group = e4b->bd_group;
1374 /* calc difference from given start */
1375 next = next - ex->fe_start;
1376 ex->fe_len -= next;
1377 ex->fe_start += next;
1379 while (needed > ex->fe_len &&
1380 (buddy = mb_find_buddy(e4b, order, &max))) {
1382 if (block + 1 >= max)
1383 break;
1385 next = (block + 1) * (1 << order);
1386 if (mb_test_bit(next, EXT4_MB_BITMAP(e4b)))
1387 break;
1389 ord = mb_find_order_for_block(e4b, next);
1391 order = ord;
1392 block = next >> order;
1393 ex->fe_len += 1 << order;
1396 BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1397 return ex->fe_len;
1400 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1402 int ord;
1403 int mlen = 0;
1404 int max = 0;
1405 int cur;
1406 int start = ex->fe_start;
1407 int len = ex->fe_len;
1408 unsigned ret = 0;
1409 int len0 = len;
1410 void *buddy;
1412 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1413 BUG_ON(e4b->bd_group != ex->fe_group);
1414 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1415 mb_check_buddy(e4b);
1416 mb_mark_used_double(e4b, start, len);
1418 e4b->bd_info->bb_free -= len;
1419 if (e4b->bd_info->bb_first_free == start)
1420 e4b->bd_info->bb_first_free += len;
1422 /* let's maintain fragments counter */
1423 if (start != 0)
1424 mlen = !mb_test_bit(start - 1, EXT4_MB_BITMAP(e4b));
1425 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1426 max = !mb_test_bit(start + len, EXT4_MB_BITMAP(e4b));
1427 if (mlen && max)
1428 e4b->bd_info->bb_fragments++;
1429 else if (!mlen && !max)
1430 e4b->bd_info->bb_fragments--;
1432 /* let's maintain buddy itself */
1433 while (len) {
1434 ord = mb_find_order_for_block(e4b, start);
1436 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1437 /* the whole chunk may be allocated at once! */
1438 mlen = 1 << ord;
1439 buddy = mb_find_buddy(e4b, ord, &max);
1440 BUG_ON((start >> ord) >= max);
1441 mb_set_bit(start >> ord, buddy);
1442 e4b->bd_info->bb_counters[ord]--;
1443 start += mlen;
1444 len -= mlen;
1445 BUG_ON(len < 0);
1446 continue;
1449 /* store for history */
1450 if (ret == 0)
1451 ret = len | (ord << 16);
1453 /* we have to split large buddy */
1454 BUG_ON(ord <= 0);
1455 buddy = mb_find_buddy(e4b, ord, &max);
1456 mb_set_bit(start >> ord, buddy);
1457 e4b->bd_info->bb_counters[ord]--;
1459 ord--;
1460 cur = (start >> ord) & ~1U;
1461 buddy = mb_find_buddy(e4b, ord, &max);
1462 mb_clear_bit(cur, buddy);
1463 mb_clear_bit(cur + 1, buddy);
1464 e4b->bd_info->bb_counters[ord]++;
1465 e4b->bd_info->bb_counters[ord]++;
1467 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1469 mb_set_bits(EXT4_MB_BITMAP(e4b), ex->fe_start, len0);
1470 mb_check_buddy(e4b);
1472 return ret;
1476 * Must be called under group lock!
1478 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1479 struct ext4_buddy *e4b)
1481 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1482 int ret;
1484 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1485 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1487 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1488 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1489 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1491 /* preallocation can change ac_b_ex, thus we store actually
1492 * allocated blocks for history */
1493 ac->ac_f_ex = ac->ac_b_ex;
1495 ac->ac_status = AC_STATUS_FOUND;
1496 ac->ac_tail = ret & 0xffff;
1497 ac->ac_buddy = ret >> 16;
1500 * take the page reference. We want the page to be pinned
1501 * so that we don't get a ext4_mb_init_cache_call for this
1502 * group until we update the bitmap. That would mean we
1503 * double allocate blocks. The reference is dropped
1504 * in ext4_mb_release_context
1506 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1507 get_page(ac->ac_bitmap_page);
1508 ac->ac_buddy_page = e4b->bd_buddy_page;
1509 get_page(ac->ac_buddy_page);
1510 /* on allocation we use ac to track the held semaphore */
1511 ac->alloc_semp = e4b->alloc_semp;
1512 e4b->alloc_semp = NULL;
1513 /* store last allocated for subsequent stream allocation */
1514 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1515 spin_lock(&sbi->s_md_lock);
1516 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1517 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1518 spin_unlock(&sbi->s_md_lock);
1523 * regular allocator, for general purposes allocation
1526 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1527 struct ext4_buddy *e4b,
1528 int finish_group)
1530 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1531 struct ext4_free_extent *bex = &ac->ac_b_ex;
1532 struct ext4_free_extent *gex = &ac->ac_g_ex;
1533 struct ext4_free_extent ex;
1534 int max;
1536 if (ac->ac_status == AC_STATUS_FOUND)
1537 return;
1539 * We don't want to scan for a whole year
1541 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1542 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1543 ac->ac_status = AC_STATUS_BREAK;
1544 return;
1548 * Haven't found good chunk so far, let's continue
1550 if (bex->fe_len < gex->fe_len)
1551 return;
1553 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1554 && bex->fe_group == e4b->bd_group) {
1555 /* recheck chunk's availability - we don't know
1556 * when it was found (within this lock-unlock
1557 * period or not) */
1558 max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
1559 if (max >= gex->fe_len) {
1560 ext4_mb_use_best_found(ac, e4b);
1561 return;
1567 * The routine checks whether found extent is good enough. If it is,
1568 * then the extent gets marked used and flag is set to the context
1569 * to stop scanning. Otherwise, the extent is compared with the
1570 * previous found extent and if new one is better, then it's stored
1571 * in the context. Later, the best found extent will be used, if
1572 * mballoc can't find good enough extent.
1574 * FIXME: real allocation policy is to be designed yet!
1576 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1577 struct ext4_free_extent *ex,
1578 struct ext4_buddy *e4b)
1580 struct ext4_free_extent *bex = &ac->ac_b_ex;
1581 struct ext4_free_extent *gex = &ac->ac_g_ex;
1583 BUG_ON(ex->fe_len <= 0);
1584 BUG_ON(ex->fe_len > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1585 BUG_ON(ex->fe_start >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1586 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1588 ac->ac_found++;
1591 * The special case - take what you catch first
1593 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1594 *bex = *ex;
1595 ext4_mb_use_best_found(ac, e4b);
1596 return;
1600 * Let's check whether the chuck is good enough
1602 if (ex->fe_len == gex->fe_len) {
1603 *bex = *ex;
1604 ext4_mb_use_best_found(ac, e4b);
1605 return;
1609 * If this is first found extent, just store it in the context
1611 if (bex->fe_len == 0) {
1612 *bex = *ex;
1613 return;
1617 * If new found extent is better, store it in the context
1619 if (bex->fe_len < gex->fe_len) {
1620 /* if the request isn't satisfied, any found extent
1621 * larger than previous best one is better */
1622 if (ex->fe_len > bex->fe_len)
1623 *bex = *ex;
1624 } else if (ex->fe_len > gex->fe_len) {
1625 /* if the request is satisfied, then we try to find
1626 * an extent that still satisfy the request, but is
1627 * smaller than previous one */
1628 if (ex->fe_len < bex->fe_len)
1629 *bex = *ex;
1632 ext4_mb_check_limits(ac, e4b, 0);
1635 static noinline_for_stack
1636 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1637 struct ext4_buddy *e4b)
1639 struct ext4_free_extent ex = ac->ac_b_ex;
1640 ext4_group_t group = ex.fe_group;
1641 int max;
1642 int err;
1644 BUG_ON(ex.fe_len <= 0);
1645 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1646 if (err)
1647 return err;
1649 ext4_lock_group(ac->ac_sb, group);
1650 max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
1652 if (max > 0) {
1653 ac->ac_b_ex = ex;
1654 ext4_mb_use_best_found(ac, e4b);
1657 ext4_unlock_group(ac->ac_sb, group);
1658 ext4_mb_unload_buddy(e4b);
1660 return 0;
1663 static noinline_for_stack
1664 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1665 struct ext4_buddy *e4b)
1667 ext4_group_t group = ac->ac_g_ex.fe_group;
1668 int max;
1669 int err;
1670 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1671 struct ext4_super_block *es = sbi->s_es;
1672 struct ext4_free_extent ex;
1674 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1675 return 0;
1677 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1678 if (err)
1679 return err;
1681 ext4_lock_group(ac->ac_sb, group);
1682 max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
1683 ac->ac_g_ex.fe_len, &ex);
1685 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1686 ext4_fsblk_t start;
1688 start = (e4b->bd_group * EXT4_BLOCKS_PER_GROUP(ac->ac_sb)) +
1689 ex.fe_start + le32_to_cpu(es->s_first_data_block);
1690 /* use do_div to get remainder (would be 64-bit modulo) */
1691 if (do_div(start, sbi->s_stripe) == 0) {
1692 ac->ac_found++;
1693 ac->ac_b_ex = ex;
1694 ext4_mb_use_best_found(ac, e4b);
1696 } else if (max >= ac->ac_g_ex.fe_len) {
1697 BUG_ON(ex.fe_len <= 0);
1698 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1699 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1700 ac->ac_found++;
1701 ac->ac_b_ex = ex;
1702 ext4_mb_use_best_found(ac, e4b);
1703 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1704 /* Sometimes, caller may want to merge even small
1705 * number of blocks to an existing extent */
1706 BUG_ON(ex.fe_len <= 0);
1707 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1708 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1709 ac->ac_found++;
1710 ac->ac_b_ex = ex;
1711 ext4_mb_use_best_found(ac, e4b);
1713 ext4_unlock_group(ac->ac_sb, group);
1714 ext4_mb_unload_buddy(e4b);
1716 return 0;
1720 * The routine scans buddy structures (not bitmap!) from given order
1721 * to max order and tries to find big enough chunk to satisfy the req
1723 static noinline_for_stack
1724 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1725 struct ext4_buddy *e4b)
1727 struct super_block *sb = ac->ac_sb;
1728 struct ext4_group_info *grp = e4b->bd_info;
1729 void *buddy;
1730 int i;
1731 int k;
1732 int max;
1734 BUG_ON(ac->ac_2order <= 0);
1735 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1736 if (grp->bb_counters[i] == 0)
1737 continue;
1739 buddy = mb_find_buddy(e4b, i, &max);
1740 BUG_ON(buddy == NULL);
1742 k = mb_find_next_zero_bit(buddy, max, 0);
1743 BUG_ON(k >= max);
1745 ac->ac_found++;
1747 ac->ac_b_ex.fe_len = 1 << i;
1748 ac->ac_b_ex.fe_start = k << i;
1749 ac->ac_b_ex.fe_group = e4b->bd_group;
1751 ext4_mb_use_best_found(ac, e4b);
1753 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1755 if (EXT4_SB(sb)->s_mb_stats)
1756 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1758 break;
1763 * The routine scans the group and measures all found extents.
1764 * In order to optimize scanning, caller must pass number of
1765 * free blocks in the group, so the routine can know upper limit.
1767 static noinline_for_stack
1768 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1769 struct ext4_buddy *e4b)
1771 struct super_block *sb = ac->ac_sb;
1772 void *bitmap = EXT4_MB_BITMAP(e4b);
1773 struct ext4_free_extent ex;
1774 int i;
1775 int free;
1777 free = e4b->bd_info->bb_free;
1778 BUG_ON(free <= 0);
1780 i = e4b->bd_info->bb_first_free;
1782 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1783 i = mb_find_next_zero_bit(bitmap,
1784 EXT4_BLOCKS_PER_GROUP(sb), i);
1785 if (i >= EXT4_BLOCKS_PER_GROUP(sb)) {
1787 * IF we have corrupt bitmap, we won't find any
1788 * free blocks even though group info says we
1789 * we have free blocks
1791 ext4_grp_locked_error(sb, e4b->bd_group,
1792 __func__, "%d free blocks as per "
1793 "group info. But bitmap says 0",
1794 free);
1795 break;
1798 mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
1799 BUG_ON(ex.fe_len <= 0);
1800 if (free < ex.fe_len) {
1801 ext4_grp_locked_error(sb, e4b->bd_group,
1802 __func__, "%d free blocks as per "
1803 "group info. But got %d blocks",
1804 free, ex.fe_len);
1806 * The number of free blocks differs. This mostly
1807 * indicate that the bitmap is corrupt. So exit
1808 * without claiming the space.
1810 break;
1813 ext4_mb_measure_extent(ac, &ex, e4b);
1815 i += ex.fe_len;
1816 free -= ex.fe_len;
1819 ext4_mb_check_limits(ac, e4b, 1);
1823 * This is a special case for storages like raid5
1824 * we try to find stripe-aligned chunks for stripe-size requests
1825 * XXX should do so at least for multiples of stripe size as well
1827 static noinline_for_stack
1828 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1829 struct ext4_buddy *e4b)
1831 struct super_block *sb = ac->ac_sb;
1832 struct ext4_sb_info *sbi = EXT4_SB(sb);
1833 void *bitmap = EXT4_MB_BITMAP(e4b);
1834 struct ext4_free_extent ex;
1835 ext4_fsblk_t first_group_block;
1836 ext4_fsblk_t a;
1837 ext4_grpblk_t i;
1838 int max;
1840 BUG_ON(sbi->s_stripe == 0);
1842 /* find first stripe-aligned block in group */
1843 first_group_block = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb)
1844 + le32_to_cpu(sbi->s_es->s_first_data_block);
1845 a = first_group_block + sbi->s_stripe - 1;
1846 do_div(a, sbi->s_stripe);
1847 i = (a * sbi->s_stripe) - first_group_block;
1849 while (i < EXT4_BLOCKS_PER_GROUP(sb)) {
1850 if (!mb_test_bit(i, bitmap)) {
1851 max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
1852 if (max >= sbi->s_stripe) {
1853 ac->ac_found++;
1854 ac->ac_b_ex = ex;
1855 ext4_mb_use_best_found(ac, e4b);
1856 break;
1859 i += sbi->s_stripe;
1863 /* This is now called BEFORE we load the buddy bitmap. */
1864 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
1865 ext4_group_t group, int cr)
1867 unsigned free, fragments;
1868 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
1869 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1871 BUG_ON(cr < 0 || cr >= 4);
1873 /* We only do this if the grp has never been initialized */
1874 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1875 int ret = ext4_mb_init_group(ac->ac_sb, group);
1876 if (ret)
1877 return 0;
1880 free = grp->bb_free;
1881 fragments = grp->bb_fragments;
1882 if (free == 0)
1883 return 0;
1884 if (fragments == 0)
1885 return 0;
1887 switch (cr) {
1888 case 0:
1889 BUG_ON(ac->ac_2order == 0);
1891 if (grp->bb_largest_free_order < ac->ac_2order)
1892 return 0;
1894 /* Avoid using the first bg of a flexgroup for data files */
1895 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
1896 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
1897 ((group % flex_size) == 0))
1898 return 0;
1900 return 1;
1901 case 1:
1902 if ((free / fragments) >= ac->ac_g_ex.fe_len)
1903 return 1;
1904 break;
1905 case 2:
1906 if (free >= ac->ac_g_ex.fe_len)
1907 return 1;
1908 break;
1909 case 3:
1910 return 1;
1911 default:
1912 BUG();
1915 return 0;
1919 * lock the group_info alloc_sem of all the groups
1920 * belonging to the same buddy cache page. This
1921 * make sure other parallel operation on the buddy
1922 * cache doesn't happen whild holding the buddy cache
1923 * lock
1925 int ext4_mb_get_buddy_cache_lock(struct super_block *sb, ext4_group_t group)
1927 int i;
1928 int block, pnum;
1929 int blocks_per_page;
1930 int groups_per_page;
1931 ext4_group_t ngroups = ext4_get_groups_count(sb);
1932 ext4_group_t first_group;
1933 struct ext4_group_info *grp;
1935 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1937 * the buddy cache inode stores the block bitmap
1938 * and buddy information in consecutive blocks.
1939 * So for each group we need two blocks.
1941 block = group * 2;
1942 pnum = block / blocks_per_page;
1943 first_group = pnum * blocks_per_page / 2;
1945 groups_per_page = blocks_per_page >> 1;
1946 if (groups_per_page == 0)
1947 groups_per_page = 1;
1948 /* read all groups the page covers into the cache */
1949 for (i = 0; i < groups_per_page; i++) {
1951 if ((first_group + i) >= ngroups)
1952 break;
1953 grp = ext4_get_group_info(sb, first_group + i);
1954 /* take all groups write allocation
1955 * semaphore. This make sure there is
1956 * no block allocation going on in any
1957 * of that groups
1959 down_write_nested(&grp->alloc_sem, i);
1961 return i;
1964 void ext4_mb_put_buddy_cache_lock(struct super_block *sb,
1965 ext4_group_t group, int locked_group)
1967 int i;
1968 int block, pnum;
1969 int blocks_per_page;
1970 ext4_group_t first_group;
1971 struct ext4_group_info *grp;
1973 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1975 * the buddy cache inode stores the block bitmap
1976 * and buddy information in consecutive blocks.
1977 * So for each group we need two blocks.
1979 block = group * 2;
1980 pnum = block / blocks_per_page;
1981 first_group = pnum * blocks_per_page / 2;
1982 /* release locks on all the groups */
1983 for (i = 0; i < locked_group; i++) {
1985 grp = ext4_get_group_info(sb, first_group + i);
1986 /* take all groups write allocation
1987 * semaphore. This make sure there is
1988 * no block allocation going on in any
1989 * of that groups
1991 up_write(&grp->alloc_sem);
1996 static noinline_for_stack int
1997 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
1999 ext4_group_t ngroups, group, i;
2000 int cr;
2001 int err = 0;
2002 int bsbits;
2003 struct ext4_sb_info *sbi;
2004 struct super_block *sb;
2005 struct ext4_buddy e4b;
2007 sb = ac->ac_sb;
2008 sbi = EXT4_SB(sb);
2009 ngroups = ext4_get_groups_count(sb);
2010 /* non-extent files are limited to low blocks/groups */
2011 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2012 ngroups = sbi->s_blockfile_groups;
2014 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2016 /* first, try the goal */
2017 err = ext4_mb_find_by_goal(ac, &e4b);
2018 if (err || ac->ac_status == AC_STATUS_FOUND)
2019 goto out;
2021 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2022 goto out;
2025 * ac->ac2_order is set only if the fe_len is a power of 2
2026 * if ac2_order is set we also set criteria to 0 so that we
2027 * try exact allocation using buddy.
2029 i = fls(ac->ac_g_ex.fe_len);
2030 ac->ac_2order = 0;
2032 * We search using buddy data only if the order of the request
2033 * is greater than equal to the sbi_s_mb_order2_reqs
2034 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2036 if (i >= sbi->s_mb_order2_reqs) {
2038 * This should tell if fe_len is exactly power of 2
2040 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2041 ac->ac_2order = i - 1;
2044 bsbits = ac->ac_sb->s_blocksize_bits;
2046 /* if stream allocation is enabled, use global goal */
2047 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2048 /* TBD: may be hot point */
2049 spin_lock(&sbi->s_md_lock);
2050 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2051 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2052 spin_unlock(&sbi->s_md_lock);
2055 /* Let's just scan groups to find more-less suitable blocks */
2056 cr = ac->ac_2order ? 0 : 1;
2058 * cr == 0 try to get exact allocation,
2059 * cr == 3 try to get anything
2061 repeat:
2062 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2063 ac->ac_criteria = cr;
2065 * searching for the right group start
2066 * from the goal value specified
2068 group = ac->ac_g_ex.fe_group;
2070 for (i = 0; i < ngroups; group++, i++) {
2071 if (group == ngroups)
2072 group = 0;
2074 /* This now checks without needing the buddy page */
2075 if (!ext4_mb_good_group(ac, group, cr))
2076 continue;
2078 err = ext4_mb_load_buddy(sb, group, &e4b);
2079 if (err)
2080 goto out;
2082 ext4_lock_group(sb, group);
2085 * We need to check again after locking the
2086 * block group
2088 if (!ext4_mb_good_group(ac, group, cr)) {
2089 ext4_unlock_group(sb, group);
2090 ext4_mb_unload_buddy(&e4b);
2091 continue;
2094 ac->ac_groups_scanned++;
2095 if (cr == 0)
2096 ext4_mb_simple_scan_group(ac, &e4b);
2097 else if (cr == 1 &&
2098 ac->ac_g_ex.fe_len == sbi->s_stripe)
2099 ext4_mb_scan_aligned(ac, &e4b);
2100 else
2101 ext4_mb_complex_scan_group(ac, &e4b);
2103 ext4_unlock_group(sb, group);
2104 ext4_mb_unload_buddy(&e4b);
2106 if (ac->ac_status != AC_STATUS_CONTINUE)
2107 break;
2111 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2112 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2114 * We've been searching too long. Let's try to allocate
2115 * the best chunk we've found so far
2118 ext4_mb_try_best_found(ac, &e4b);
2119 if (ac->ac_status != AC_STATUS_FOUND) {
2121 * Someone more lucky has already allocated it.
2122 * The only thing we can do is just take first
2123 * found block(s)
2124 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2126 ac->ac_b_ex.fe_group = 0;
2127 ac->ac_b_ex.fe_start = 0;
2128 ac->ac_b_ex.fe_len = 0;
2129 ac->ac_status = AC_STATUS_CONTINUE;
2130 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2131 cr = 3;
2132 atomic_inc(&sbi->s_mb_lost_chunks);
2133 goto repeat;
2136 out:
2137 return err;
2140 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2142 struct super_block *sb = seq->private;
2143 ext4_group_t group;
2145 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2146 return NULL;
2147 group = *pos + 1;
2148 return (void *) ((unsigned long) group);
2151 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2153 struct super_block *sb = seq->private;
2154 ext4_group_t group;
2156 ++*pos;
2157 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2158 return NULL;
2159 group = *pos + 1;
2160 return (void *) ((unsigned long) group);
2163 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2165 struct super_block *sb = seq->private;
2166 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2167 int i;
2168 int err;
2169 struct ext4_buddy e4b;
2170 struct sg {
2171 struct ext4_group_info info;
2172 ext4_grpblk_t counters[16];
2173 } sg;
2175 group--;
2176 if (group == 0)
2177 seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
2178 "[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2179 "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2180 "group", "free", "frags", "first",
2181 "2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
2182 "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2184 i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2185 sizeof(struct ext4_group_info);
2186 err = ext4_mb_load_buddy(sb, group, &e4b);
2187 if (err) {
2188 seq_printf(seq, "#%-5u: I/O error\n", group);
2189 return 0;
2191 ext4_lock_group(sb, group);
2192 memcpy(&sg, ext4_get_group_info(sb, group), i);
2193 ext4_unlock_group(sb, group);
2194 ext4_mb_unload_buddy(&e4b);
2196 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2197 sg.info.bb_fragments, sg.info.bb_first_free);
2198 for (i = 0; i <= 13; i++)
2199 seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2200 sg.info.bb_counters[i] : 0);
2201 seq_printf(seq, " ]\n");
2203 return 0;
2206 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2210 static const struct seq_operations ext4_mb_seq_groups_ops = {
2211 .start = ext4_mb_seq_groups_start,
2212 .next = ext4_mb_seq_groups_next,
2213 .stop = ext4_mb_seq_groups_stop,
2214 .show = ext4_mb_seq_groups_show,
2217 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2219 struct super_block *sb = PDE(inode)->data;
2220 int rc;
2222 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2223 if (rc == 0) {
2224 struct seq_file *m = (struct seq_file *)file->private_data;
2225 m->private = sb;
2227 return rc;
2231 static const struct file_operations ext4_mb_seq_groups_fops = {
2232 .owner = THIS_MODULE,
2233 .open = ext4_mb_seq_groups_open,
2234 .read = seq_read,
2235 .llseek = seq_lseek,
2236 .release = seq_release,
2240 /* Create and initialize ext4_group_info data for the given group. */
2241 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2242 struct ext4_group_desc *desc)
2244 int i, len;
2245 int metalen = 0;
2246 struct ext4_sb_info *sbi = EXT4_SB(sb);
2247 struct ext4_group_info **meta_group_info;
2250 * First check if this group is the first of a reserved block.
2251 * If it's true, we have to allocate a new table of pointers
2252 * to ext4_group_info structures
2254 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2255 metalen = sizeof(*meta_group_info) <<
2256 EXT4_DESC_PER_BLOCK_BITS(sb);
2257 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2258 if (meta_group_info == NULL) {
2259 printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2260 "buddy group\n");
2261 goto exit_meta_group_info;
2263 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] =
2264 meta_group_info;
2268 * calculate needed size. if change bb_counters size,
2269 * don't forget about ext4_mb_generate_buddy()
2271 len = offsetof(typeof(**meta_group_info),
2272 bb_counters[sb->s_blocksize_bits + 2]);
2274 meta_group_info =
2275 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)];
2276 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2278 meta_group_info[i] = kzalloc(len, GFP_KERNEL);
2279 if (meta_group_info[i] == NULL) {
2280 printk(KERN_ERR "EXT4-fs: can't allocate buddy mem\n");
2281 goto exit_group_info;
2283 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2284 &(meta_group_info[i]->bb_state));
2287 * initialize bb_free to be able to skip
2288 * empty groups without initialization
2290 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2291 meta_group_info[i]->bb_free =
2292 ext4_free_blocks_after_init(sb, group, desc);
2293 } else {
2294 meta_group_info[i]->bb_free =
2295 ext4_free_blks_count(sb, desc);
2298 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2299 init_rwsem(&meta_group_info[i]->alloc_sem);
2300 meta_group_info[i]->bb_free_root.rb_node = NULL;
2301 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
2303 #ifdef DOUBLE_CHECK
2305 struct buffer_head *bh;
2306 meta_group_info[i]->bb_bitmap =
2307 kmalloc(sb->s_blocksize, GFP_KERNEL);
2308 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2309 bh = ext4_read_block_bitmap(sb, group);
2310 BUG_ON(bh == NULL);
2311 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2312 sb->s_blocksize);
2313 put_bh(bh);
2315 #endif
2317 return 0;
2319 exit_group_info:
2320 /* If a meta_group_info table has been allocated, release it now */
2321 if (group % EXT4_DESC_PER_BLOCK(sb) == 0)
2322 kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
2323 exit_meta_group_info:
2324 return -ENOMEM;
2325 } /* ext4_mb_add_groupinfo */
2327 static int ext4_mb_init_backend(struct super_block *sb)
2329 ext4_group_t ngroups = ext4_get_groups_count(sb);
2330 ext4_group_t i;
2331 struct ext4_sb_info *sbi = EXT4_SB(sb);
2332 struct ext4_super_block *es = sbi->s_es;
2333 int num_meta_group_infos;
2334 int num_meta_group_infos_max;
2335 int array_size;
2336 struct ext4_group_desc *desc;
2338 /* This is the number of blocks used by GDT */
2339 num_meta_group_infos = (ngroups + EXT4_DESC_PER_BLOCK(sb) -
2340 1) >> EXT4_DESC_PER_BLOCK_BITS(sb);
2343 * This is the total number of blocks used by GDT including
2344 * the number of reserved blocks for GDT.
2345 * The s_group_info array is allocated with this value
2346 * to allow a clean online resize without a complex
2347 * manipulation of pointer.
2348 * The drawback is the unused memory when no resize
2349 * occurs but it's very low in terms of pages
2350 * (see comments below)
2351 * Need to handle this properly when META_BG resizing is allowed
2353 num_meta_group_infos_max = num_meta_group_infos +
2354 le16_to_cpu(es->s_reserved_gdt_blocks);
2357 * array_size is the size of s_group_info array. We round it
2358 * to the next power of two because this approximation is done
2359 * internally by kmalloc so we can have some more memory
2360 * for free here (e.g. may be used for META_BG resize).
2362 array_size = 1;
2363 while (array_size < sizeof(*sbi->s_group_info) *
2364 num_meta_group_infos_max)
2365 array_size = array_size << 1;
2366 /* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2367 * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2368 * So a two level scheme suffices for now. */
2369 sbi->s_group_info = kmalloc(array_size, GFP_KERNEL);
2370 if (sbi->s_group_info == NULL) {
2371 printk(KERN_ERR "EXT4-fs: can't allocate buddy meta group\n");
2372 return -ENOMEM;
2374 sbi->s_buddy_cache = new_inode(sb);
2375 if (sbi->s_buddy_cache == NULL) {
2376 printk(KERN_ERR "EXT4-fs: can't get new inode\n");
2377 goto err_freesgi;
2379 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2380 for (i = 0; i < ngroups; i++) {
2381 desc = ext4_get_group_desc(sb, i, NULL);
2382 if (desc == NULL) {
2383 printk(KERN_ERR
2384 "EXT4-fs: can't read descriptor %u\n", i);
2385 goto err_freebuddy;
2387 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2388 goto err_freebuddy;
2391 return 0;
2393 err_freebuddy:
2394 while (i-- > 0)
2395 kfree(ext4_get_group_info(sb, i));
2396 i = num_meta_group_infos;
2397 while (i-- > 0)
2398 kfree(sbi->s_group_info[i]);
2399 iput(sbi->s_buddy_cache);
2400 err_freesgi:
2401 kfree(sbi->s_group_info);
2402 return -ENOMEM;
2405 int ext4_mb_init(struct super_block *sb, int needs_recovery)
2407 struct ext4_sb_info *sbi = EXT4_SB(sb);
2408 unsigned i, j;
2409 unsigned offset;
2410 unsigned max;
2411 int ret;
2413 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2415 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2416 if (sbi->s_mb_offsets == NULL) {
2417 return -ENOMEM;
2420 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2421 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2422 if (sbi->s_mb_maxs == NULL) {
2423 kfree(sbi->s_mb_offsets);
2424 return -ENOMEM;
2427 /* order 0 is regular bitmap */
2428 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2429 sbi->s_mb_offsets[0] = 0;
2431 i = 1;
2432 offset = 0;
2433 max = sb->s_blocksize << 2;
2434 do {
2435 sbi->s_mb_offsets[i] = offset;
2436 sbi->s_mb_maxs[i] = max;
2437 offset += 1 << (sb->s_blocksize_bits - i);
2438 max = max >> 1;
2439 i++;
2440 } while (i <= sb->s_blocksize_bits + 1);
2442 /* init file for buddy data */
2443 ret = ext4_mb_init_backend(sb);
2444 if (ret != 0) {
2445 kfree(sbi->s_mb_offsets);
2446 kfree(sbi->s_mb_maxs);
2447 return ret;
2450 spin_lock_init(&sbi->s_md_lock);
2451 spin_lock_init(&sbi->s_bal_lock);
2453 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2454 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2455 sbi->s_mb_stats = MB_DEFAULT_STATS;
2456 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2457 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2458 sbi->s_mb_group_prealloc = MB_DEFAULT_GROUP_PREALLOC;
2460 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2461 if (sbi->s_locality_groups == NULL) {
2462 kfree(sbi->s_mb_offsets);
2463 kfree(sbi->s_mb_maxs);
2464 return -ENOMEM;
2466 for_each_possible_cpu(i) {
2467 struct ext4_locality_group *lg;
2468 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2469 mutex_init(&lg->lg_mutex);
2470 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2471 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2472 spin_lock_init(&lg->lg_prealloc_lock);
2475 if (sbi->s_proc)
2476 proc_create_data("mb_groups", S_IRUGO, sbi->s_proc,
2477 &ext4_mb_seq_groups_fops, sb);
2479 if (sbi->s_journal)
2480 sbi->s_journal->j_commit_callback = release_blocks_on_commit;
2481 return 0;
2484 /* need to called with the ext4 group lock held */
2485 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2487 struct ext4_prealloc_space *pa;
2488 struct list_head *cur, *tmp;
2489 int count = 0;
2491 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2492 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2493 list_del(&pa->pa_group_list);
2494 count++;
2495 kmem_cache_free(ext4_pspace_cachep, pa);
2497 if (count)
2498 mb_debug(1, "mballoc: %u PAs left\n", count);
2502 int ext4_mb_release(struct super_block *sb)
2504 ext4_group_t ngroups = ext4_get_groups_count(sb);
2505 ext4_group_t i;
2506 int num_meta_group_infos;
2507 struct ext4_group_info *grinfo;
2508 struct ext4_sb_info *sbi = EXT4_SB(sb);
2510 if (sbi->s_group_info) {
2511 for (i = 0; i < ngroups; i++) {
2512 grinfo = ext4_get_group_info(sb, i);
2513 #ifdef DOUBLE_CHECK
2514 kfree(grinfo->bb_bitmap);
2515 #endif
2516 ext4_lock_group(sb, i);
2517 ext4_mb_cleanup_pa(grinfo);
2518 ext4_unlock_group(sb, i);
2519 kfree(grinfo);
2521 num_meta_group_infos = (ngroups +
2522 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2523 EXT4_DESC_PER_BLOCK_BITS(sb);
2524 for (i = 0; i < num_meta_group_infos; i++)
2525 kfree(sbi->s_group_info[i]);
2526 kfree(sbi->s_group_info);
2528 kfree(sbi->s_mb_offsets);
2529 kfree(sbi->s_mb_maxs);
2530 if (sbi->s_buddy_cache)
2531 iput(sbi->s_buddy_cache);
2532 if (sbi->s_mb_stats) {
2533 printk(KERN_INFO
2534 "EXT4-fs: mballoc: %u blocks %u reqs (%u success)\n",
2535 atomic_read(&sbi->s_bal_allocated),
2536 atomic_read(&sbi->s_bal_reqs),
2537 atomic_read(&sbi->s_bal_success));
2538 printk(KERN_INFO
2539 "EXT4-fs: mballoc: %u extents scanned, %u goal hits, "
2540 "%u 2^N hits, %u breaks, %u lost\n",
2541 atomic_read(&sbi->s_bal_ex_scanned),
2542 atomic_read(&sbi->s_bal_goals),
2543 atomic_read(&sbi->s_bal_2orders),
2544 atomic_read(&sbi->s_bal_breaks),
2545 atomic_read(&sbi->s_mb_lost_chunks));
2546 printk(KERN_INFO
2547 "EXT4-fs: mballoc: %lu generated and it took %Lu\n",
2548 sbi->s_mb_buddies_generated++,
2549 sbi->s_mb_generation_time);
2550 printk(KERN_INFO
2551 "EXT4-fs: mballoc: %u preallocated, %u discarded\n",
2552 atomic_read(&sbi->s_mb_preallocated),
2553 atomic_read(&sbi->s_mb_discarded));
2556 free_percpu(sbi->s_locality_groups);
2557 if (sbi->s_proc)
2558 remove_proc_entry("mb_groups", sbi->s_proc);
2560 return 0;
2564 * This function is called by the jbd2 layer once the commit has finished,
2565 * so we know we can free the blocks that were released with that commit.
2567 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn)
2569 struct super_block *sb = journal->j_private;
2570 struct ext4_buddy e4b;
2571 struct ext4_group_info *db;
2572 int err, count = 0, count2 = 0;
2573 struct ext4_free_data *entry;
2574 struct list_head *l, *ltmp;
2576 list_for_each_safe(l, ltmp, &txn->t_private_list) {
2577 entry = list_entry(l, struct ext4_free_data, list);
2579 mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2580 entry->count, entry->group, entry);
2582 if (test_opt(sb, DISCARD)) {
2583 int ret;
2584 ext4_fsblk_t discard_block;
2586 discard_block = entry->start_blk +
2587 ext4_group_first_block_no(sb, entry->group);
2588 trace_ext4_discard_blocks(sb,
2589 (unsigned long long)discard_block,
2590 entry->count);
2591 ret = sb_issue_discard(sb, discard_block, entry->count);
2592 if (ret == EOPNOTSUPP) {
2593 ext4_warning(sb, __func__,
2594 "discard not supported, disabling");
2595 clear_opt(EXT4_SB(sb)->s_mount_opt, DISCARD);
2599 err = ext4_mb_load_buddy(sb, entry->group, &e4b);
2600 /* we expect to find existing buddy because it's pinned */
2601 BUG_ON(err != 0);
2603 db = e4b.bd_info;
2604 /* there are blocks to put in buddy to make them really free */
2605 count += entry->count;
2606 count2++;
2607 ext4_lock_group(sb, entry->group);
2608 /* Take it out of per group rb tree */
2609 rb_erase(&entry->node, &(db->bb_free_root));
2610 mb_free_blocks(NULL, &e4b, entry->start_blk, entry->count);
2612 if (!db->bb_free_root.rb_node) {
2613 /* No more items in the per group rb tree
2614 * balance refcounts from ext4_mb_free_metadata()
2616 page_cache_release(e4b.bd_buddy_page);
2617 page_cache_release(e4b.bd_bitmap_page);
2619 ext4_unlock_group(sb, entry->group);
2620 kmem_cache_free(ext4_free_ext_cachep, entry);
2621 ext4_mb_unload_buddy(&e4b);
2624 mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2627 #ifdef CONFIG_EXT4_DEBUG
2628 u8 mb_enable_debug __read_mostly;
2630 static struct dentry *debugfs_dir;
2631 static struct dentry *debugfs_debug;
2633 static void __init ext4_create_debugfs_entry(void)
2635 debugfs_dir = debugfs_create_dir("ext4", NULL);
2636 if (debugfs_dir)
2637 debugfs_debug = debugfs_create_u8("mballoc-debug",
2638 S_IRUGO | S_IWUSR,
2639 debugfs_dir,
2640 &mb_enable_debug);
2643 static void ext4_remove_debugfs_entry(void)
2645 debugfs_remove(debugfs_debug);
2646 debugfs_remove(debugfs_dir);
2649 #else
2651 static void __init ext4_create_debugfs_entry(void)
2655 static void ext4_remove_debugfs_entry(void)
2659 #endif
2661 int __init init_ext4_mballoc(void)
2663 ext4_pspace_cachep =
2664 kmem_cache_create("ext4_prealloc_space",
2665 sizeof(struct ext4_prealloc_space),
2666 0, SLAB_RECLAIM_ACCOUNT, NULL);
2667 if (ext4_pspace_cachep == NULL)
2668 return -ENOMEM;
2670 ext4_ac_cachep =
2671 kmem_cache_create("ext4_alloc_context",
2672 sizeof(struct ext4_allocation_context),
2673 0, SLAB_RECLAIM_ACCOUNT, NULL);
2674 if (ext4_ac_cachep == NULL) {
2675 kmem_cache_destroy(ext4_pspace_cachep);
2676 return -ENOMEM;
2679 ext4_free_ext_cachep =
2680 kmem_cache_create("ext4_free_block_extents",
2681 sizeof(struct ext4_free_data),
2682 0, SLAB_RECLAIM_ACCOUNT, NULL);
2683 if (ext4_free_ext_cachep == NULL) {
2684 kmem_cache_destroy(ext4_pspace_cachep);
2685 kmem_cache_destroy(ext4_ac_cachep);
2686 return -ENOMEM;
2688 ext4_create_debugfs_entry();
2689 return 0;
2692 void exit_ext4_mballoc(void)
2695 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
2696 * before destroying the slab cache.
2698 rcu_barrier();
2699 kmem_cache_destroy(ext4_pspace_cachep);
2700 kmem_cache_destroy(ext4_ac_cachep);
2701 kmem_cache_destroy(ext4_free_ext_cachep);
2702 ext4_remove_debugfs_entry();
2707 * Check quota and mark choosed space (ac->ac_b_ex) non-free in bitmaps
2708 * Returns 0 if success or error code
2710 static noinline_for_stack int
2711 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2712 handle_t *handle, unsigned int reserv_blks)
2714 struct buffer_head *bitmap_bh = NULL;
2715 struct ext4_super_block *es;
2716 struct ext4_group_desc *gdp;
2717 struct buffer_head *gdp_bh;
2718 struct ext4_sb_info *sbi;
2719 struct super_block *sb;
2720 ext4_fsblk_t block;
2721 int err, len;
2723 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2724 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2726 sb = ac->ac_sb;
2727 sbi = EXT4_SB(sb);
2728 es = sbi->s_es;
2731 err = -EIO;
2732 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2733 if (!bitmap_bh)
2734 goto out_err;
2736 err = ext4_journal_get_write_access(handle, bitmap_bh);
2737 if (err)
2738 goto out_err;
2740 err = -EIO;
2741 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2742 if (!gdp)
2743 goto out_err;
2745 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
2746 ext4_free_blks_count(sb, gdp));
2748 err = ext4_journal_get_write_access(handle, gdp_bh);
2749 if (err)
2750 goto out_err;
2752 block = ac->ac_b_ex.fe_group * EXT4_BLOCKS_PER_GROUP(sb)
2753 + ac->ac_b_ex.fe_start
2754 + le32_to_cpu(es->s_first_data_block);
2756 len = ac->ac_b_ex.fe_len;
2757 if (!ext4_data_block_valid(sbi, block, len)) {
2758 ext4_error(sb, __func__,
2759 "Allocating blocks %llu-%llu which overlap "
2760 "fs metadata\n", block, block+len);
2761 /* File system mounted not to panic on error
2762 * Fix the bitmap and repeat the block allocation
2763 * We leak some of the blocks here.
2765 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2766 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2767 ac->ac_b_ex.fe_len);
2768 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
2769 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2770 if (!err)
2771 err = -EAGAIN;
2772 goto out_err;
2775 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2776 #ifdef AGGRESSIVE_CHECK
2778 int i;
2779 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
2780 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
2781 bitmap_bh->b_data));
2784 #endif
2785 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,ac->ac_b_ex.fe_len);
2786 if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2787 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
2788 ext4_free_blks_set(sb, gdp,
2789 ext4_free_blocks_after_init(sb,
2790 ac->ac_b_ex.fe_group, gdp));
2792 len = ext4_free_blks_count(sb, gdp) - ac->ac_b_ex.fe_len;
2793 ext4_free_blks_set(sb, gdp, len);
2794 gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
2796 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
2797 percpu_counter_sub(&sbi->s_freeblocks_counter, ac->ac_b_ex.fe_len);
2799 * Now reduce the dirty block count also. Should not go negative
2801 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
2802 /* release all the reserved blocks if non delalloc */
2803 percpu_counter_sub(&sbi->s_dirtyblocks_counter, reserv_blks);
2805 if (sbi->s_log_groups_per_flex) {
2806 ext4_group_t flex_group = ext4_flex_group(sbi,
2807 ac->ac_b_ex.fe_group);
2808 atomic_sub(ac->ac_b_ex.fe_len,
2809 &sbi->s_flex_groups[flex_group].free_blocks);
2812 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2813 if (err)
2814 goto out_err;
2815 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
2817 out_err:
2818 sb->s_dirt = 1;
2819 brelse(bitmap_bh);
2820 return err;
2824 * here we normalize request for locality group
2825 * Group request are normalized to s_strip size if we set the same via mount
2826 * option. If not we set it to s_mb_group_prealloc which can be configured via
2827 * /sys/fs/ext4/<partition>/mb_group_prealloc
2829 * XXX: should we try to preallocate more than the group has now?
2831 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
2833 struct super_block *sb = ac->ac_sb;
2834 struct ext4_locality_group *lg = ac->ac_lg;
2836 BUG_ON(lg == NULL);
2837 if (EXT4_SB(sb)->s_stripe)
2838 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_stripe;
2839 else
2840 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
2841 mb_debug(1, "#%u: goal %u blocks for locality group\n",
2842 current->pid, ac->ac_g_ex.fe_len);
2846 * Normalization means making request better in terms of
2847 * size and alignment
2849 static noinline_for_stack void
2850 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
2851 struct ext4_allocation_request *ar)
2853 int bsbits, max;
2854 ext4_lblk_t end;
2855 loff_t size, orig_size, start_off;
2856 ext4_lblk_t start, orig_start;
2857 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
2858 struct ext4_prealloc_space *pa;
2860 /* do normalize only data requests, metadata requests
2861 do not need preallocation */
2862 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
2863 return;
2865 /* sometime caller may want exact blocks */
2866 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2867 return;
2869 /* caller may indicate that preallocation isn't
2870 * required (it's a tail, for example) */
2871 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
2872 return;
2874 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
2875 ext4_mb_normalize_group_request(ac);
2876 return ;
2879 bsbits = ac->ac_sb->s_blocksize_bits;
2881 /* first, let's learn actual file size
2882 * given current request is allocated */
2883 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
2884 size = size << bsbits;
2885 if (size < i_size_read(ac->ac_inode))
2886 size = i_size_read(ac->ac_inode);
2888 /* max size of free chunks */
2889 max = 2 << bsbits;
2891 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
2892 (req <= (size) || max <= (chunk_size))
2894 /* first, try to predict filesize */
2895 /* XXX: should this table be tunable? */
2896 start_off = 0;
2897 if (size <= 16 * 1024) {
2898 size = 16 * 1024;
2899 } else if (size <= 32 * 1024) {
2900 size = 32 * 1024;
2901 } else if (size <= 64 * 1024) {
2902 size = 64 * 1024;
2903 } else if (size <= 128 * 1024) {
2904 size = 128 * 1024;
2905 } else if (size <= 256 * 1024) {
2906 size = 256 * 1024;
2907 } else if (size <= 512 * 1024) {
2908 size = 512 * 1024;
2909 } else if (size <= 1024 * 1024) {
2910 size = 1024 * 1024;
2911 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
2912 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2913 (21 - bsbits)) << 21;
2914 size = 2 * 1024 * 1024;
2915 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
2916 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2917 (22 - bsbits)) << 22;
2918 size = 4 * 1024 * 1024;
2919 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
2920 (8<<20)>>bsbits, max, 8 * 1024)) {
2921 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2922 (23 - bsbits)) << 23;
2923 size = 8 * 1024 * 1024;
2924 } else {
2925 start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
2926 size = ac->ac_o_ex.fe_len << bsbits;
2928 orig_size = size = size >> bsbits;
2929 orig_start = start = start_off >> bsbits;
2931 /* don't cover already allocated blocks in selected range */
2932 if (ar->pleft && start <= ar->lleft) {
2933 size -= ar->lleft + 1 - start;
2934 start = ar->lleft + 1;
2936 if (ar->pright && start + size - 1 >= ar->lright)
2937 size -= start + size - ar->lright;
2939 end = start + size;
2941 /* check we don't cross already preallocated blocks */
2942 rcu_read_lock();
2943 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
2944 ext4_lblk_t pa_end;
2946 if (pa->pa_deleted)
2947 continue;
2948 spin_lock(&pa->pa_lock);
2949 if (pa->pa_deleted) {
2950 spin_unlock(&pa->pa_lock);
2951 continue;
2954 pa_end = pa->pa_lstart + pa->pa_len;
2956 /* PA must not overlap original request */
2957 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
2958 ac->ac_o_ex.fe_logical < pa->pa_lstart));
2960 /* skip PAs this normalized request doesn't overlap with */
2961 if (pa->pa_lstart >= end || pa_end <= start) {
2962 spin_unlock(&pa->pa_lock);
2963 continue;
2965 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
2967 /* adjust start or end to be adjacent to this pa */
2968 if (pa_end <= ac->ac_o_ex.fe_logical) {
2969 BUG_ON(pa_end < start);
2970 start = pa_end;
2971 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
2972 BUG_ON(pa->pa_lstart > end);
2973 end = pa->pa_lstart;
2975 spin_unlock(&pa->pa_lock);
2977 rcu_read_unlock();
2978 size = end - start;
2980 /* XXX: extra loop to check we really don't overlap preallocations */
2981 rcu_read_lock();
2982 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
2983 ext4_lblk_t pa_end;
2984 spin_lock(&pa->pa_lock);
2985 if (pa->pa_deleted == 0) {
2986 pa_end = pa->pa_lstart + pa->pa_len;
2987 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
2989 spin_unlock(&pa->pa_lock);
2991 rcu_read_unlock();
2993 if (start + size <= ac->ac_o_ex.fe_logical &&
2994 start > ac->ac_o_ex.fe_logical) {
2995 printk(KERN_ERR "start %lu, size %lu, fe_logical %lu\n",
2996 (unsigned long) start, (unsigned long) size,
2997 (unsigned long) ac->ac_o_ex.fe_logical);
2999 BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3000 start > ac->ac_o_ex.fe_logical);
3001 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3003 /* now prepare goal request */
3005 /* XXX: is it better to align blocks WRT to logical
3006 * placement or satisfy big request as is */
3007 ac->ac_g_ex.fe_logical = start;
3008 ac->ac_g_ex.fe_len = size;
3010 /* define goal start in order to merge */
3011 if (ar->pright && (ar->lright == (start + size))) {
3012 /* merge to the right */
3013 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3014 &ac->ac_f_ex.fe_group,
3015 &ac->ac_f_ex.fe_start);
3016 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3018 if (ar->pleft && (ar->lleft + 1 == start)) {
3019 /* merge to the left */
3020 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3021 &ac->ac_f_ex.fe_group,
3022 &ac->ac_f_ex.fe_start);
3023 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3026 mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3027 (unsigned) orig_size, (unsigned) start);
3030 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3032 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3034 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3035 atomic_inc(&sbi->s_bal_reqs);
3036 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3037 if (ac->ac_o_ex.fe_len >= ac->ac_g_ex.fe_len)
3038 atomic_inc(&sbi->s_bal_success);
3039 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3040 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3041 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3042 atomic_inc(&sbi->s_bal_goals);
3043 if (ac->ac_found > sbi->s_mb_max_to_scan)
3044 atomic_inc(&sbi->s_bal_breaks);
3047 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3048 trace_ext4_mballoc_alloc(ac);
3049 else
3050 trace_ext4_mballoc_prealloc(ac);
3054 * Called on failure; free up any blocks from the inode PA for this
3055 * context. We don't need this for MB_GROUP_PA because we only change
3056 * pa_free in ext4_mb_release_context(), but on failure, we've already
3057 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3059 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3061 struct ext4_prealloc_space *pa = ac->ac_pa;
3062 int len;
3064 if (pa && pa->pa_type == MB_INODE_PA) {
3065 len = ac->ac_b_ex.fe_len;
3066 pa->pa_free += len;
3072 * use blocks preallocated to inode
3074 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3075 struct ext4_prealloc_space *pa)
3077 ext4_fsblk_t start;
3078 ext4_fsblk_t end;
3079 int len;
3081 /* found preallocated blocks, use them */
3082 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3083 end = min(pa->pa_pstart + pa->pa_len, start + ac->ac_o_ex.fe_len);
3084 len = end - start;
3085 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3086 &ac->ac_b_ex.fe_start);
3087 ac->ac_b_ex.fe_len = len;
3088 ac->ac_status = AC_STATUS_FOUND;
3089 ac->ac_pa = pa;
3091 BUG_ON(start < pa->pa_pstart);
3092 BUG_ON(start + len > pa->pa_pstart + pa->pa_len);
3093 BUG_ON(pa->pa_free < len);
3094 pa->pa_free -= len;
3096 mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3100 * use blocks preallocated to locality group
3102 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3103 struct ext4_prealloc_space *pa)
3105 unsigned int len = ac->ac_o_ex.fe_len;
3107 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3108 &ac->ac_b_ex.fe_group,
3109 &ac->ac_b_ex.fe_start);
3110 ac->ac_b_ex.fe_len = len;
3111 ac->ac_status = AC_STATUS_FOUND;
3112 ac->ac_pa = pa;
3114 /* we don't correct pa_pstart or pa_plen here to avoid
3115 * possible race when the group is being loaded concurrently
3116 * instead we correct pa later, after blocks are marked
3117 * in on-disk bitmap -- see ext4_mb_release_context()
3118 * Other CPUs are prevented from allocating from this pa by lg_mutex
3120 mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3124 * Return the prealloc space that have minimal distance
3125 * from the goal block. @cpa is the prealloc
3126 * space that is having currently known minimal distance
3127 * from the goal block.
3129 static struct ext4_prealloc_space *
3130 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3131 struct ext4_prealloc_space *pa,
3132 struct ext4_prealloc_space *cpa)
3134 ext4_fsblk_t cur_distance, new_distance;
3136 if (cpa == NULL) {
3137 atomic_inc(&pa->pa_count);
3138 return pa;
3140 cur_distance = abs(goal_block - cpa->pa_pstart);
3141 new_distance = abs(goal_block - pa->pa_pstart);
3143 if (cur_distance < new_distance)
3144 return cpa;
3146 /* drop the previous reference */
3147 atomic_dec(&cpa->pa_count);
3148 atomic_inc(&pa->pa_count);
3149 return pa;
3153 * search goal blocks in preallocated space
3155 static noinline_for_stack int
3156 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3158 int order, i;
3159 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3160 struct ext4_locality_group *lg;
3161 struct ext4_prealloc_space *pa, *cpa = NULL;
3162 ext4_fsblk_t goal_block;
3164 /* only data can be preallocated */
3165 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3166 return 0;
3168 /* first, try per-file preallocation */
3169 rcu_read_lock();
3170 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3172 /* all fields in this condition don't change,
3173 * so we can skip locking for them */
3174 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3175 ac->ac_o_ex.fe_logical >= pa->pa_lstart + pa->pa_len)
3176 continue;
3178 /* non-extent files can't have physical blocks past 2^32 */
3179 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3180 pa->pa_pstart + pa->pa_len > EXT4_MAX_BLOCK_FILE_PHYS)
3181 continue;
3183 /* found preallocated blocks, use them */
3184 spin_lock(&pa->pa_lock);
3185 if (pa->pa_deleted == 0 && pa->pa_free) {
3186 atomic_inc(&pa->pa_count);
3187 ext4_mb_use_inode_pa(ac, pa);
3188 spin_unlock(&pa->pa_lock);
3189 ac->ac_criteria = 10;
3190 rcu_read_unlock();
3191 return 1;
3193 spin_unlock(&pa->pa_lock);
3195 rcu_read_unlock();
3197 /* can we use group allocation? */
3198 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3199 return 0;
3201 /* inode may have no locality group for some reason */
3202 lg = ac->ac_lg;
3203 if (lg == NULL)
3204 return 0;
3205 order = fls(ac->ac_o_ex.fe_len) - 1;
3206 if (order > PREALLOC_TB_SIZE - 1)
3207 /* The max size of hash table is PREALLOC_TB_SIZE */
3208 order = PREALLOC_TB_SIZE - 1;
3210 goal_block = ac->ac_g_ex.fe_group * EXT4_BLOCKS_PER_GROUP(ac->ac_sb) +
3211 ac->ac_g_ex.fe_start +
3212 le32_to_cpu(EXT4_SB(ac->ac_sb)->s_es->s_first_data_block);
3214 * search for the prealloc space that is having
3215 * minimal distance from the goal block.
3217 for (i = order; i < PREALLOC_TB_SIZE; i++) {
3218 rcu_read_lock();
3219 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3220 pa_inode_list) {
3221 spin_lock(&pa->pa_lock);
3222 if (pa->pa_deleted == 0 &&
3223 pa->pa_free >= ac->ac_o_ex.fe_len) {
3225 cpa = ext4_mb_check_group_pa(goal_block,
3226 pa, cpa);
3228 spin_unlock(&pa->pa_lock);
3230 rcu_read_unlock();
3232 if (cpa) {
3233 ext4_mb_use_group_pa(ac, cpa);
3234 ac->ac_criteria = 20;
3235 return 1;
3237 return 0;
3241 * the function goes through all block freed in the group
3242 * but not yet committed and marks them used in in-core bitmap.
3243 * buddy must be generated from this bitmap
3244 * Need to be called with the ext4 group lock held
3246 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3247 ext4_group_t group)
3249 struct rb_node *n;
3250 struct ext4_group_info *grp;
3251 struct ext4_free_data *entry;
3253 grp = ext4_get_group_info(sb, group);
3254 n = rb_first(&(grp->bb_free_root));
3256 while (n) {
3257 entry = rb_entry(n, struct ext4_free_data, node);
3258 mb_set_bits(bitmap, entry->start_blk, entry->count);
3259 n = rb_next(n);
3261 return;
3265 * the function goes through all preallocation in this group and marks them
3266 * used in in-core bitmap. buddy must be generated from this bitmap
3267 * Need to be called with ext4 group lock held
3269 static noinline_for_stack
3270 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3271 ext4_group_t group)
3273 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3274 struct ext4_prealloc_space *pa;
3275 struct list_head *cur;
3276 ext4_group_t groupnr;
3277 ext4_grpblk_t start;
3278 int preallocated = 0;
3279 int count = 0;
3280 int len;
3282 /* all form of preallocation discards first load group,
3283 * so the only competing code is preallocation use.
3284 * we don't need any locking here
3285 * notice we do NOT ignore preallocations with pa_deleted
3286 * otherwise we could leave used blocks available for
3287 * allocation in buddy when concurrent ext4_mb_put_pa()
3288 * is dropping preallocation
3290 list_for_each(cur, &grp->bb_prealloc_list) {
3291 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3292 spin_lock(&pa->pa_lock);
3293 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3294 &groupnr, &start);
3295 len = pa->pa_len;
3296 spin_unlock(&pa->pa_lock);
3297 if (unlikely(len == 0))
3298 continue;
3299 BUG_ON(groupnr != group);
3300 mb_set_bits(bitmap, start, len);
3301 preallocated += len;
3302 count++;
3304 mb_debug(1, "prellocated %u for group %u\n", preallocated, group);
3307 static void ext4_mb_pa_callback(struct rcu_head *head)
3309 struct ext4_prealloc_space *pa;
3310 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3311 kmem_cache_free(ext4_pspace_cachep, pa);
3315 * drops a reference to preallocated space descriptor
3316 * if this was the last reference and the space is consumed
3318 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3319 struct super_block *sb, struct ext4_prealloc_space *pa)
3321 ext4_group_t grp;
3322 ext4_fsblk_t grp_blk;
3324 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3325 return;
3327 /* in this short window concurrent discard can set pa_deleted */
3328 spin_lock(&pa->pa_lock);
3329 if (pa->pa_deleted == 1) {
3330 spin_unlock(&pa->pa_lock);
3331 return;
3334 pa->pa_deleted = 1;
3335 spin_unlock(&pa->pa_lock);
3337 grp_blk = pa->pa_pstart;
3339 * If doing group-based preallocation, pa_pstart may be in the
3340 * next group when pa is used up
3342 if (pa->pa_type == MB_GROUP_PA)
3343 grp_blk--;
3345 ext4_get_group_no_and_offset(sb, grp_blk, &grp, NULL);
3348 * possible race:
3350 * P1 (buddy init) P2 (regular allocation)
3351 * find block B in PA
3352 * copy on-disk bitmap to buddy
3353 * mark B in on-disk bitmap
3354 * drop PA from group
3355 * mark all PAs in buddy
3357 * thus, P1 initializes buddy with B available. to prevent this
3358 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3359 * against that pair
3361 ext4_lock_group(sb, grp);
3362 list_del(&pa->pa_group_list);
3363 ext4_unlock_group(sb, grp);
3365 spin_lock(pa->pa_obj_lock);
3366 list_del_rcu(&pa->pa_inode_list);
3367 spin_unlock(pa->pa_obj_lock);
3369 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3373 * creates new preallocated space for given inode
3375 static noinline_for_stack int
3376 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3378 struct super_block *sb = ac->ac_sb;
3379 struct ext4_prealloc_space *pa;
3380 struct ext4_group_info *grp;
3381 struct ext4_inode_info *ei;
3383 /* preallocate only when found space is larger then requested */
3384 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3385 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3386 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3388 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3389 if (pa == NULL)
3390 return -ENOMEM;
3392 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3393 int winl;
3394 int wins;
3395 int win;
3396 int offs;
3398 /* we can't allocate as much as normalizer wants.
3399 * so, found space must get proper lstart
3400 * to cover original request */
3401 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3402 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3404 /* we're limited by original request in that
3405 * logical block must be covered any way
3406 * winl is window we can move our chunk within */
3407 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3409 /* also, we should cover whole original request */
3410 wins = ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len;
3412 /* the smallest one defines real window */
3413 win = min(winl, wins);
3415 offs = ac->ac_o_ex.fe_logical % ac->ac_b_ex.fe_len;
3416 if (offs && offs < win)
3417 win = offs;
3419 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical - win;
3420 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3421 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3424 /* preallocation can change ac_b_ex, thus we store actually
3425 * allocated blocks for history */
3426 ac->ac_f_ex = ac->ac_b_ex;
3428 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3429 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3430 pa->pa_len = ac->ac_b_ex.fe_len;
3431 pa->pa_free = pa->pa_len;
3432 atomic_set(&pa->pa_count, 1);
3433 spin_lock_init(&pa->pa_lock);
3434 INIT_LIST_HEAD(&pa->pa_inode_list);
3435 INIT_LIST_HEAD(&pa->pa_group_list);
3436 pa->pa_deleted = 0;
3437 pa->pa_type = MB_INODE_PA;
3439 mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3440 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3441 trace_ext4_mb_new_inode_pa(ac, pa);
3443 ext4_mb_use_inode_pa(ac, pa);
3444 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3446 ei = EXT4_I(ac->ac_inode);
3447 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3449 pa->pa_obj_lock = &ei->i_prealloc_lock;
3450 pa->pa_inode = ac->ac_inode;
3452 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3453 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3454 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3456 spin_lock(pa->pa_obj_lock);
3457 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3458 spin_unlock(pa->pa_obj_lock);
3460 return 0;
3464 * creates new preallocated space for locality group inodes belongs to
3466 static noinline_for_stack int
3467 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3469 struct super_block *sb = ac->ac_sb;
3470 struct ext4_locality_group *lg;
3471 struct ext4_prealloc_space *pa;
3472 struct ext4_group_info *grp;
3474 /* preallocate only when found space is larger then requested */
3475 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3476 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3477 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3479 BUG_ON(ext4_pspace_cachep == NULL);
3480 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3481 if (pa == NULL)
3482 return -ENOMEM;
3484 /* preallocation can change ac_b_ex, thus we store actually
3485 * allocated blocks for history */
3486 ac->ac_f_ex = ac->ac_b_ex;
3488 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3489 pa->pa_lstart = pa->pa_pstart;
3490 pa->pa_len = ac->ac_b_ex.fe_len;
3491 pa->pa_free = pa->pa_len;
3492 atomic_set(&pa->pa_count, 1);
3493 spin_lock_init(&pa->pa_lock);
3494 INIT_LIST_HEAD(&pa->pa_inode_list);
3495 INIT_LIST_HEAD(&pa->pa_group_list);
3496 pa->pa_deleted = 0;
3497 pa->pa_type = MB_GROUP_PA;
3499 mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3500 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3501 trace_ext4_mb_new_group_pa(ac, pa);
3503 ext4_mb_use_group_pa(ac, pa);
3504 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3506 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3507 lg = ac->ac_lg;
3508 BUG_ON(lg == NULL);
3510 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3511 pa->pa_inode = NULL;
3513 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3514 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3515 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3518 * We will later add the new pa to the right bucket
3519 * after updating the pa_free in ext4_mb_release_context
3521 return 0;
3524 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3526 int err;
3528 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3529 err = ext4_mb_new_group_pa(ac);
3530 else
3531 err = ext4_mb_new_inode_pa(ac);
3532 return err;
3536 * finds all unused blocks in on-disk bitmap, frees them in
3537 * in-core bitmap and buddy.
3538 * @pa must be unlinked from inode and group lists, so that
3539 * nobody else can find/use it.
3540 * the caller MUST hold group/inode locks.
3541 * TODO: optimize the case when there are no in-core structures yet
3543 static noinline_for_stack int
3544 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3545 struct ext4_prealloc_space *pa,
3546 struct ext4_allocation_context *ac)
3548 struct super_block *sb = e4b->bd_sb;
3549 struct ext4_sb_info *sbi = EXT4_SB(sb);
3550 unsigned int end;
3551 unsigned int next;
3552 ext4_group_t group;
3553 ext4_grpblk_t bit;
3554 unsigned long long grp_blk_start;
3555 sector_t start;
3556 int err = 0;
3557 int free = 0;
3559 BUG_ON(pa->pa_deleted == 0);
3560 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3561 grp_blk_start = pa->pa_pstart - bit;
3562 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3563 end = bit + pa->pa_len;
3565 if (ac) {
3566 ac->ac_sb = sb;
3567 ac->ac_inode = pa->pa_inode;
3570 while (bit < end) {
3571 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3572 if (bit >= end)
3573 break;
3574 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3575 start = group * EXT4_BLOCKS_PER_GROUP(sb) + bit +
3576 le32_to_cpu(sbi->s_es->s_first_data_block);
3577 mb_debug(1, " free preallocated %u/%u in group %u\n",
3578 (unsigned) start, (unsigned) next - bit,
3579 (unsigned) group);
3580 free += next - bit;
3582 if (ac) {
3583 ac->ac_b_ex.fe_group = group;
3584 ac->ac_b_ex.fe_start = bit;
3585 ac->ac_b_ex.fe_len = next - bit;
3586 ac->ac_b_ex.fe_logical = 0;
3587 trace_ext4_mballoc_discard(ac);
3590 trace_ext4_mb_release_inode_pa(ac, pa, grp_blk_start + bit,
3591 next - bit);
3592 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3593 bit = next + 1;
3595 if (free != pa->pa_free) {
3596 printk(KERN_CRIT "pa %p: logic %lu, phys. %lu, len %lu\n",
3597 pa, (unsigned long) pa->pa_lstart,
3598 (unsigned long) pa->pa_pstart,
3599 (unsigned long) pa->pa_len);
3600 ext4_grp_locked_error(sb, group,
3601 __func__, "free %u, pa_free %u",
3602 free, pa->pa_free);
3604 * pa is already deleted so we use the value obtained
3605 * from the bitmap and continue.
3608 atomic_add(free, &sbi->s_mb_discarded);
3610 return err;
3613 static noinline_for_stack int
3614 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3615 struct ext4_prealloc_space *pa,
3616 struct ext4_allocation_context *ac)
3618 struct super_block *sb = e4b->bd_sb;
3619 ext4_group_t group;
3620 ext4_grpblk_t bit;
3622 trace_ext4_mb_release_group_pa(ac, pa);
3623 BUG_ON(pa->pa_deleted == 0);
3624 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3625 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3626 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3627 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3629 if (ac) {
3630 ac->ac_sb = sb;
3631 ac->ac_inode = NULL;
3632 ac->ac_b_ex.fe_group = group;
3633 ac->ac_b_ex.fe_start = bit;
3634 ac->ac_b_ex.fe_len = pa->pa_len;
3635 ac->ac_b_ex.fe_logical = 0;
3636 trace_ext4_mballoc_discard(ac);
3639 return 0;
3643 * releases all preallocations in given group
3645 * first, we need to decide discard policy:
3646 * - when do we discard
3647 * 1) ENOSPC
3648 * - how many do we discard
3649 * 1) how many requested
3651 static noinline_for_stack int
3652 ext4_mb_discard_group_preallocations(struct super_block *sb,
3653 ext4_group_t group, int needed)
3655 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3656 struct buffer_head *bitmap_bh = NULL;
3657 struct ext4_prealloc_space *pa, *tmp;
3658 struct ext4_allocation_context *ac;
3659 struct list_head list;
3660 struct ext4_buddy e4b;
3661 int err;
3662 int busy = 0;
3663 int free = 0;
3665 mb_debug(1, "discard preallocation for group %u\n", group);
3667 if (list_empty(&grp->bb_prealloc_list))
3668 return 0;
3670 bitmap_bh = ext4_read_block_bitmap(sb, group);
3671 if (bitmap_bh == NULL) {
3672 ext4_error(sb, __func__, "Error in reading block "
3673 "bitmap for %u", group);
3674 return 0;
3677 err = ext4_mb_load_buddy(sb, group, &e4b);
3678 if (err) {
3679 ext4_error(sb, __func__, "Error in loading buddy "
3680 "information for %u", group);
3681 put_bh(bitmap_bh);
3682 return 0;
3685 if (needed == 0)
3686 needed = EXT4_BLOCKS_PER_GROUP(sb) + 1;
3688 INIT_LIST_HEAD(&list);
3689 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
3690 if (ac)
3691 ac->ac_sb = sb;
3692 repeat:
3693 ext4_lock_group(sb, group);
3694 list_for_each_entry_safe(pa, tmp,
3695 &grp->bb_prealloc_list, pa_group_list) {
3696 spin_lock(&pa->pa_lock);
3697 if (atomic_read(&pa->pa_count)) {
3698 spin_unlock(&pa->pa_lock);
3699 busy = 1;
3700 continue;
3702 if (pa->pa_deleted) {
3703 spin_unlock(&pa->pa_lock);
3704 continue;
3707 /* seems this one can be freed ... */
3708 pa->pa_deleted = 1;
3710 /* we can trust pa_free ... */
3711 free += pa->pa_free;
3713 spin_unlock(&pa->pa_lock);
3715 list_del(&pa->pa_group_list);
3716 list_add(&pa->u.pa_tmp_list, &list);
3719 /* if we still need more blocks and some PAs were used, try again */
3720 if (free < needed && busy) {
3721 busy = 0;
3722 ext4_unlock_group(sb, group);
3724 * Yield the CPU here so that we don't get soft lockup
3725 * in non preempt case.
3727 yield();
3728 goto repeat;
3731 /* found anything to free? */
3732 if (list_empty(&list)) {
3733 BUG_ON(free != 0);
3734 goto out;
3737 /* now free all selected PAs */
3738 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3740 /* remove from object (inode or locality group) */
3741 spin_lock(pa->pa_obj_lock);
3742 list_del_rcu(&pa->pa_inode_list);
3743 spin_unlock(pa->pa_obj_lock);
3745 if (pa->pa_type == MB_GROUP_PA)
3746 ext4_mb_release_group_pa(&e4b, pa, ac);
3747 else
3748 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
3750 list_del(&pa->u.pa_tmp_list);
3751 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3754 out:
3755 ext4_unlock_group(sb, group);
3756 if (ac)
3757 kmem_cache_free(ext4_ac_cachep, ac);
3758 ext4_mb_unload_buddy(&e4b);
3759 put_bh(bitmap_bh);
3760 return free;
3764 * releases all non-used preallocated blocks for given inode
3766 * It's important to discard preallocations under i_data_sem
3767 * We don't want another block to be served from the prealloc
3768 * space when we are discarding the inode prealloc space.
3770 * FIXME!! Make sure it is valid at all the call sites
3772 void ext4_discard_preallocations(struct inode *inode)
3774 struct ext4_inode_info *ei = EXT4_I(inode);
3775 struct super_block *sb = inode->i_sb;
3776 struct buffer_head *bitmap_bh = NULL;
3777 struct ext4_prealloc_space *pa, *tmp;
3778 struct ext4_allocation_context *ac;
3779 ext4_group_t group = 0;
3780 struct list_head list;
3781 struct ext4_buddy e4b;
3782 int err;
3784 if (!S_ISREG(inode->i_mode)) {
3785 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
3786 return;
3789 mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
3790 trace_ext4_discard_preallocations(inode);
3792 INIT_LIST_HEAD(&list);
3794 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
3795 if (ac) {
3796 ac->ac_sb = sb;
3797 ac->ac_inode = inode;
3799 repeat:
3800 /* first, collect all pa's in the inode */
3801 spin_lock(&ei->i_prealloc_lock);
3802 while (!list_empty(&ei->i_prealloc_list)) {
3803 pa = list_entry(ei->i_prealloc_list.next,
3804 struct ext4_prealloc_space, pa_inode_list);
3805 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
3806 spin_lock(&pa->pa_lock);
3807 if (atomic_read(&pa->pa_count)) {
3808 /* this shouldn't happen often - nobody should
3809 * use preallocation while we're discarding it */
3810 spin_unlock(&pa->pa_lock);
3811 spin_unlock(&ei->i_prealloc_lock);
3812 printk(KERN_ERR "uh-oh! used pa while discarding\n");
3813 WARN_ON(1);
3814 schedule_timeout_uninterruptible(HZ);
3815 goto repeat;
3818 if (pa->pa_deleted == 0) {
3819 pa->pa_deleted = 1;
3820 spin_unlock(&pa->pa_lock);
3821 list_del_rcu(&pa->pa_inode_list);
3822 list_add(&pa->u.pa_tmp_list, &list);
3823 continue;
3826 /* someone is deleting pa right now */
3827 spin_unlock(&pa->pa_lock);
3828 spin_unlock(&ei->i_prealloc_lock);
3830 /* we have to wait here because pa_deleted
3831 * doesn't mean pa is already unlinked from
3832 * the list. as we might be called from
3833 * ->clear_inode() the inode will get freed
3834 * and concurrent thread which is unlinking
3835 * pa from inode's list may access already
3836 * freed memory, bad-bad-bad */
3838 /* XXX: if this happens too often, we can
3839 * add a flag to force wait only in case
3840 * of ->clear_inode(), but not in case of
3841 * regular truncate */
3842 schedule_timeout_uninterruptible(HZ);
3843 goto repeat;
3845 spin_unlock(&ei->i_prealloc_lock);
3847 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3848 BUG_ON(pa->pa_type != MB_INODE_PA);
3849 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
3851 err = ext4_mb_load_buddy(sb, group, &e4b);
3852 if (err) {
3853 ext4_error(sb, __func__, "Error in loading buddy "
3854 "information for %u", group);
3855 continue;
3858 bitmap_bh = ext4_read_block_bitmap(sb, group);
3859 if (bitmap_bh == NULL) {
3860 ext4_error(sb, __func__, "Error in reading block "
3861 "bitmap for %u", group);
3862 ext4_mb_unload_buddy(&e4b);
3863 continue;
3866 ext4_lock_group(sb, group);
3867 list_del(&pa->pa_group_list);
3868 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa, ac);
3869 ext4_unlock_group(sb, group);
3871 ext4_mb_unload_buddy(&e4b);
3872 put_bh(bitmap_bh);
3874 list_del(&pa->u.pa_tmp_list);
3875 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3877 if (ac)
3878 kmem_cache_free(ext4_ac_cachep, ac);
3882 * finds all preallocated spaces and return blocks being freed to them
3883 * if preallocated space becomes full (no block is used from the space)
3884 * then the function frees space in buddy
3885 * XXX: at the moment, truncate (which is the only way to free blocks)
3886 * discards all preallocations
3888 static void ext4_mb_return_to_preallocation(struct inode *inode,
3889 struct ext4_buddy *e4b,
3890 sector_t block, int count)
3892 BUG_ON(!list_empty(&EXT4_I(inode)->i_prealloc_list));
3894 #ifdef CONFIG_EXT4_DEBUG
3895 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3897 struct super_block *sb = ac->ac_sb;
3898 ext4_group_t ngroups, i;
3900 printk(KERN_ERR "EXT4-fs: Can't allocate:"
3901 " Allocation context details:\n");
3902 printk(KERN_ERR "EXT4-fs: status %d flags %d\n",
3903 ac->ac_status, ac->ac_flags);
3904 printk(KERN_ERR "EXT4-fs: orig %lu/%lu/%lu@%lu, goal %lu/%lu/%lu@%lu, "
3905 "best %lu/%lu/%lu@%lu cr %d\n",
3906 (unsigned long)ac->ac_o_ex.fe_group,
3907 (unsigned long)ac->ac_o_ex.fe_start,
3908 (unsigned long)ac->ac_o_ex.fe_len,
3909 (unsigned long)ac->ac_o_ex.fe_logical,
3910 (unsigned long)ac->ac_g_ex.fe_group,
3911 (unsigned long)ac->ac_g_ex.fe_start,
3912 (unsigned long)ac->ac_g_ex.fe_len,
3913 (unsigned long)ac->ac_g_ex.fe_logical,
3914 (unsigned long)ac->ac_b_ex.fe_group,
3915 (unsigned long)ac->ac_b_ex.fe_start,
3916 (unsigned long)ac->ac_b_ex.fe_len,
3917 (unsigned long)ac->ac_b_ex.fe_logical,
3918 (int)ac->ac_criteria);
3919 printk(KERN_ERR "EXT4-fs: %lu scanned, %d found\n", ac->ac_ex_scanned,
3920 ac->ac_found);
3921 printk(KERN_ERR "EXT4-fs: groups: \n");
3922 ngroups = ext4_get_groups_count(sb);
3923 for (i = 0; i < ngroups; i++) {
3924 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3925 struct ext4_prealloc_space *pa;
3926 ext4_grpblk_t start;
3927 struct list_head *cur;
3928 ext4_lock_group(sb, i);
3929 list_for_each(cur, &grp->bb_prealloc_list) {
3930 pa = list_entry(cur, struct ext4_prealloc_space,
3931 pa_group_list);
3932 spin_lock(&pa->pa_lock);
3933 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3934 NULL, &start);
3935 spin_unlock(&pa->pa_lock);
3936 printk(KERN_ERR "PA:%u:%d:%u \n", i,
3937 start, pa->pa_len);
3939 ext4_unlock_group(sb, i);
3941 if (grp->bb_free == 0)
3942 continue;
3943 printk(KERN_ERR "%u: %d/%d \n",
3944 i, grp->bb_free, grp->bb_fragments);
3946 printk(KERN_ERR "\n");
3948 #else
3949 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3951 return;
3953 #endif
3956 * We use locality group preallocation for small size file. The size of the
3957 * file is determined by the current size or the resulting size after
3958 * allocation which ever is larger
3960 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
3962 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
3964 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3965 int bsbits = ac->ac_sb->s_blocksize_bits;
3966 loff_t size, isize;
3968 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3969 return;
3971 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3972 return;
3974 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
3975 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
3976 >> bsbits;
3978 if ((size == isize) &&
3979 !ext4_fs_is_busy(sbi) &&
3980 (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
3981 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
3982 return;
3985 /* don't use group allocation for large files */
3986 size = max(size, isize);
3987 if (size > sbi->s_mb_stream_request) {
3988 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
3989 return;
3992 BUG_ON(ac->ac_lg != NULL);
3994 * locality group prealloc space are per cpu. The reason for having
3995 * per cpu locality group is to reduce the contention between block
3996 * request from multiple CPUs.
3998 ac->ac_lg = per_cpu_ptr(sbi->s_locality_groups, raw_smp_processor_id());
4000 /* we're going to use group allocation */
4001 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4003 /* serialize all allocations in the group */
4004 mutex_lock(&ac->ac_lg->lg_mutex);
4007 static noinline_for_stack int
4008 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4009 struct ext4_allocation_request *ar)
4011 struct super_block *sb = ar->inode->i_sb;
4012 struct ext4_sb_info *sbi = EXT4_SB(sb);
4013 struct ext4_super_block *es = sbi->s_es;
4014 ext4_group_t group;
4015 unsigned int len;
4016 ext4_fsblk_t goal;
4017 ext4_grpblk_t block;
4019 /* we can't allocate > group size */
4020 len = ar->len;
4022 /* just a dirty hack to filter too big requests */
4023 if (len >= EXT4_BLOCKS_PER_GROUP(sb) - 10)
4024 len = EXT4_BLOCKS_PER_GROUP(sb) - 10;
4026 /* start searching from the goal */
4027 goal = ar->goal;
4028 if (goal < le32_to_cpu(es->s_first_data_block) ||
4029 goal >= ext4_blocks_count(es))
4030 goal = le32_to_cpu(es->s_first_data_block);
4031 ext4_get_group_no_and_offset(sb, goal, &group, &block);
4033 /* set up allocation goals */
4034 memset(ac, 0, sizeof(struct ext4_allocation_context));
4035 ac->ac_b_ex.fe_logical = ar->logical;
4036 ac->ac_status = AC_STATUS_CONTINUE;
4037 ac->ac_sb = sb;
4038 ac->ac_inode = ar->inode;
4039 ac->ac_o_ex.fe_logical = ar->logical;
4040 ac->ac_o_ex.fe_group = group;
4041 ac->ac_o_ex.fe_start = block;
4042 ac->ac_o_ex.fe_len = len;
4043 ac->ac_g_ex.fe_logical = ar->logical;
4044 ac->ac_g_ex.fe_group = group;
4045 ac->ac_g_ex.fe_start = block;
4046 ac->ac_g_ex.fe_len = len;
4047 ac->ac_flags = ar->flags;
4049 /* we have to define context: we'll we work with a file or
4050 * locality group. this is a policy, actually */
4051 ext4_mb_group_or_file(ac);
4053 mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4054 "left: %u/%u, right %u/%u to %swritable\n",
4055 (unsigned) ar->len, (unsigned) ar->logical,
4056 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4057 (unsigned) ar->lleft, (unsigned) ar->pleft,
4058 (unsigned) ar->lright, (unsigned) ar->pright,
4059 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4060 return 0;
4064 static noinline_for_stack void
4065 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4066 struct ext4_locality_group *lg,
4067 int order, int total_entries)
4069 ext4_group_t group = 0;
4070 struct ext4_buddy e4b;
4071 struct list_head discard_list;
4072 struct ext4_prealloc_space *pa, *tmp;
4073 struct ext4_allocation_context *ac;
4075 mb_debug(1, "discard locality group preallocation\n");
4077 INIT_LIST_HEAD(&discard_list);
4078 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4079 if (ac)
4080 ac->ac_sb = sb;
4082 spin_lock(&lg->lg_prealloc_lock);
4083 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4084 pa_inode_list) {
4085 spin_lock(&pa->pa_lock);
4086 if (atomic_read(&pa->pa_count)) {
4088 * This is the pa that we just used
4089 * for block allocation. So don't
4090 * free that
4092 spin_unlock(&pa->pa_lock);
4093 continue;
4095 if (pa->pa_deleted) {
4096 spin_unlock(&pa->pa_lock);
4097 continue;
4099 /* only lg prealloc space */
4100 BUG_ON(pa->pa_type != MB_GROUP_PA);
4102 /* seems this one can be freed ... */
4103 pa->pa_deleted = 1;
4104 spin_unlock(&pa->pa_lock);
4106 list_del_rcu(&pa->pa_inode_list);
4107 list_add(&pa->u.pa_tmp_list, &discard_list);
4109 total_entries--;
4110 if (total_entries <= 5) {
4112 * we want to keep only 5 entries
4113 * allowing it to grow to 8. This
4114 * mak sure we don't call discard
4115 * soon for this list.
4117 break;
4120 spin_unlock(&lg->lg_prealloc_lock);
4122 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4124 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
4125 if (ext4_mb_load_buddy(sb, group, &e4b)) {
4126 ext4_error(sb, __func__, "Error in loading buddy "
4127 "information for %u", group);
4128 continue;
4130 ext4_lock_group(sb, group);
4131 list_del(&pa->pa_group_list);
4132 ext4_mb_release_group_pa(&e4b, pa, ac);
4133 ext4_unlock_group(sb, group);
4135 ext4_mb_unload_buddy(&e4b);
4136 list_del(&pa->u.pa_tmp_list);
4137 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4139 if (ac)
4140 kmem_cache_free(ext4_ac_cachep, ac);
4144 * We have incremented pa_count. So it cannot be freed at this
4145 * point. Also we hold lg_mutex. So no parallel allocation is
4146 * possible from this lg. That means pa_free cannot be updated.
4148 * A parallel ext4_mb_discard_group_preallocations is possible.
4149 * which can cause the lg_prealloc_list to be updated.
4152 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4154 int order, added = 0, lg_prealloc_count = 1;
4155 struct super_block *sb = ac->ac_sb;
4156 struct ext4_locality_group *lg = ac->ac_lg;
4157 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4159 order = fls(pa->pa_free) - 1;
4160 if (order > PREALLOC_TB_SIZE - 1)
4161 /* The max size of hash table is PREALLOC_TB_SIZE */
4162 order = PREALLOC_TB_SIZE - 1;
4163 /* Add the prealloc space to lg */
4164 rcu_read_lock();
4165 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4166 pa_inode_list) {
4167 spin_lock(&tmp_pa->pa_lock);
4168 if (tmp_pa->pa_deleted) {
4169 spin_unlock(&tmp_pa->pa_lock);
4170 continue;
4172 if (!added && pa->pa_free < tmp_pa->pa_free) {
4173 /* Add to the tail of the previous entry */
4174 list_add_tail_rcu(&pa->pa_inode_list,
4175 &tmp_pa->pa_inode_list);
4176 added = 1;
4178 * we want to count the total
4179 * number of entries in the list
4182 spin_unlock(&tmp_pa->pa_lock);
4183 lg_prealloc_count++;
4185 if (!added)
4186 list_add_tail_rcu(&pa->pa_inode_list,
4187 &lg->lg_prealloc_list[order]);
4188 rcu_read_unlock();
4190 /* Now trim the list to be not more than 8 elements */
4191 if (lg_prealloc_count > 8) {
4192 ext4_mb_discard_lg_preallocations(sb, lg,
4193 order, lg_prealloc_count);
4194 return;
4196 return ;
4200 * release all resource we used in allocation
4202 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4204 struct ext4_prealloc_space *pa = ac->ac_pa;
4205 if (pa) {
4206 if (pa->pa_type == MB_GROUP_PA) {
4207 /* see comment in ext4_mb_use_group_pa() */
4208 spin_lock(&pa->pa_lock);
4209 pa->pa_pstart += ac->ac_b_ex.fe_len;
4210 pa->pa_lstart += ac->ac_b_ex.fe_len;
4211 pa->pa_free -= ac->ac_b_ex.fe_len;
4212 pa->pa_len -= ac->ac_b_ex.fe_len;
4213 spin_unlock(&pa->pa_lock);
4216 if (ac->alloc_semp)
4217 up_read(ac->alloc_semp);
4218 if (pa) {
4220 * We want to add the pa to the right bucket.
4221 * Remove it from the list and while adding
4222 * make sure the list to which we are adding
4223 * doesn't grow big. We need to release
4224 * alloc_semp before calling ext4_mb_add_n_trim()
4226 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4227 spin_lock(pa->pa_obj_lock);
4228 list_del_rcu(&pa->pa_inode_list);
4229 spin_unlock(pa->pa_obj_lock);
4230 ext4_mb_add_n_trim(ac);
4232 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4234 if (ac->ac_bitmap_page)
4235 page_cache_release(ac->ac_bitmap_page);
4236 if (ac->ac_buddy_page)
4237 page_cache_release(ac->ac_buddy_page);
4238 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4239 mutex_unlock(&ac->ac_lg->lg_mutex);
4240 ext4_mb_collect_stats(ac);
4241 return 0;
4244 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4246 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4247 int ret;
4248 int freed = 0;
4250 trace_ext4_mb_discard_preallocations(sb, needed);
4251 for (i = 0; i < ngroups && needed > 0; i++) {
4252 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4253 freed += ret;
4254 needed -= ret;
4257 return freed;
4261 * Main entry point into mballoc to allocate blocks
4262 * it tries to use preallocation first, then falls back
4263 * to usual allocation
4265 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4266 struct ext4_allocation_request *ar, int *errp)
4268 int freed;
4269 struct ext4_allocation_context *ac = NULL;
4270 struct ext4_sb_info *sbi;
4271 struct super_block *sb;
4272 ext4_fsblk_t block = 0;
4273 unsigned int inquota = 0;
4274 unsigned int reserv_blks = 0;
4276 sb = ar->inode->i_sb;
4277 sbi = EXT4_SB(sb);
4279 trace_ext4_request_blocks(ar);
4282 * For delayed allocation, we could skip the ENOSPC and
4283 * EDQUOT check, as blocks and quotas have been already
4284 * reserved when data being copied into pagecache.
4286 if (EXT4_I(ar->inode)->i_delalloc_reserved_flag)
4287 ar->flags |= EXT4_MB_DELALLOC_RESERVED;
4288 else {
4289 /* Without delayed allocation we need to verify
4290 * there is enough free blocks to do block allocation
4291 * and verify allocation doesn't exceed the quota limits.
4293 while (ar->len && ext4_claim_free_blocks(sbi, ar->len)) {
4294 /* let others to free the space */
4295 yield();
4296 ar->len = ar->len >> 1;
4298 if (!ar->len) {
4299 *errp = -ENOSPC;
4300 return 0;
4302 reserv_blks = ar->len;
4303 while (ar->len && vfs_dq_alloc_block(ar->inode, ar->len)) {
4304 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4305 ar->len--;
4307 inquota = ar->len;
4308 if (ar->len == 0) {
4309 *errp = -EDQUOT;
4310 goto out3;
4314 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4315 if (!ac) {
4316 ar->len = 0;
4317 *errp = -ENOMEM;
4318 goto out1;
4321 *errp = ext4_mb_initialize_context(ac, ar);
4322 if (*errp) {
4323 ar->len = 0;
4324 goto out2;
4327 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4328 if (!ext4_mb_use_preallocated(ac)) {
4329 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4330 ext4_mb_normalize_request(ac, ar);
4331 repeat:
4332 /* allocate space in core */
4333 ext4_mb_regular_allocator(ac);
4335 /* as we've just preallocated more space than
4336 * user requested orinally, we store allocated
4337 * space in a special descriptor */
4338 if (ac->ac_status == AC_STATUS_FOUND &&
4339 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4340 ext4_mb_new_preallocation(ac);
4342 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4343 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_blks);
4344 if (*errp == -EAGAIN) {
4346 * drop the reference that we took
4347 * in ext4_mb_use_best_found
4349 ext4_mb_release_context(ac);
4350 ac->ac_b_ex.fe_group = 0;
4351 ac->ac_b_ex.fe_start = 0;
4352 ac->ac_b_ex.fe_len = 0;
4353 ac->ac_status = AC_STATUS_CONTINUE;
4354 goto repeat;
4355 } else if (*errp) {
4356 ext4_discard_allocated_blocks(ac);
4357 ac->ac_b_ex.fe_len = 0;
4358 ar->len = 0;
4359 ext4_mb_show_ac(ac);
4360 } else {
4361 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4362 ar->len = ac->ac_b_ex.fe_len;
4364 } else {
4365 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4366 if (freed)
4367 goto repeat;
4368 *errp = -ENOSPC;
4369 ac->ac_b_ex.fe_len = 0;
4370 ar->len = 0;
4371 ext4_mb_show_ac(ac);
4374 ext4_mb_release_context(ac);
4376 out2:
4377 kmem_cache_free(ext4_ac_cachep, ac);
4378 out1:
4379 if (inquota && ar->len < inquota)
4380 vfs_dq_free_block(ar->inode, inquota - ar->len);
4381 out3:
4382 if (!ar->len) {
4383 if (!EXT4_I(ar->inode)->i_delalloc_reserved_flag)
4384 /* release all the reserved blocks if non delalloc */
4385 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
4386 reserv_blks);
4389 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4391 return block;
4395 * We can merge two free data extents only if the physical blocks
4396 * are contiguous, AND the extents were freed by the same transaction,
4397 * AND the blocks are associated with the same group.
4399 static int can_merge(struct ext4_free_data *entry1,
4400 struct ext4_free_data *entry2)
4402 if ((entry1->t_tid == entry2->t_tid) &&
4403 (entry1->group == entry2->group) &&
4404 ((entry1->start_blk + entry1->count) == entry2->start_blk))
4405 return 1;
4406 return 0;
4409 static noinline_for_stack int
4410 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4411 struct ext4_free_data *new_entry)
4413 ext4_grpblk_t block;
4414 struct ext4_free_data *entry;
4415 struct ext4_group_info *db = e4b->bd_info;
4416 struct super_block *sb = e4b->bd_sb;
4417 struct ext4_sb_info *sbi = EXT4_SB(sb);
4418 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4419 struct rb_node *parent = NULL, *new_node;
4421 BUG_ON(!ext4_handle_valid(handle));
4422 BUG_ON(e4b->bd_bitmap_page == NULL);
4423 BUG_ON(e4b->bd_buddy_page == NULL);
4425 new_node = &new_entry->node;
4426 block = new_entry->start_blk;
4428 if (!*n) {
4429 /* first free block exent. We need to
4430 protect buddy cache from being freed,
4431 * otherwise we'll refresh it from
4432 * on-disk bitmap and lose not-yet-available
4433 * blocks */
4434 page_cache_get(e4b->bd_buddy_page);
4435 page_cache_get(e4b->bd_bitmap_page);
4437 while (*n) {
4438 parent = *n;
4439 entry = rb_entry(parent, struct ext4_free_data, node);
4440 if (block < entry->start_blk)
4441 n = &(*n)->rb_left;
4442 else if (block >= (entry->start_blk + entry->count))
4443 n = &(*n)->rb_right;
4444 else {
4445 ext4_grp_locked_error(sb, e4b->bd_group, __func__,
4446 "Double free of blocks %d (%d %d)",
4447 block, entry->start_blk, entry->count);
4448 return 0;
4452 rb_link_node(new_node, parent, n);
4453 rb_insert_color(new_node, &db->bb_free_root);
4455 /* Now try to see the extent can be merged to left and right */
4456 node = rb_prev(new_node);
4457 if (node) {
4458 entry = rb_entry(node, struct ext4_free_data, node);
4459 if (can_merge(entry, new_entry)) {
4460 new_entry->start_blk = entry->start_blk;
4461 new_entry->count += entry->count;
4462 rb_erase(node, &(db->bb_free_root));
4463 spin_lock(&sbi->s_md_lock);
4464 list_del(&entry->list);
4465 spin_unlock(&sbi->s_md_lock);
4466 kmem_cache_free(ext4_free_ext_cachep, entry);
4470 node = rb_next(new_node);
4471 if (node) {
4472 entry = rb_entry(node, struct ext4_free_data, node);
4473 if (can_merge(new_entry, entry)) {
4474 new_entry->count += entry->count;
4475 rb_erase(node, &(db->bb_free_root));
4476 spin_lock(&sbi->s_md_lock);
4477 list_del(&entry->list);
4478 spin_unlock(&sbi->s_md_lock);
4479 kmem_cache_free(ext4_free_ext_cachep, entry);
4482 /* Add the extent to transaction's private list */
4483 spin_lock(&sbi->s_md_lock);
4484 list_add(&new_entry->list, &handle->h_transaction->t_private_list);
4485 spin_unlock(&sbi->s_md_lock);
4486 return 0;
4490 * Main entry point into mballoc to free blocks
4492 void ext4_mb_free_blocks(handle_t *handle, struct inode *inode,
4493 ext4_fsblk_t block, unsigned long count,
4494 int metadata, unsigned long *freed)
4496 struct buffer_head *bitmap_bh = NULL;
4497 struct super_block *sb = inode->i_sb;
4498 struct ext4_allocation_context *ac = NULL;
4499 struct ext4_group_desc *gdp;
4500 struct ext4_super_block *es;
4501 unsigned int overflow;
4502 ext4_grpblk_t bit;
4503 struct buffer_head *gd_bh;
4504 ext4_group_t block_group;
4505 struct ext4_sb_info *sbi;
4506 struct ext4_buddy e4b;
4507 int err = 0;
4508 int ret;
4510 *freed = 0;
4512 sbi = EXT4_SB(sb);
4513 es = EXT4_SB(sb)->s_es;
4514 if (block < le32_to_cpu(es->s_first_data_block) ||
4515 block + count < block ||
4516 block + count > ext4_blocks_count(es)) {
4517 ext4_error(sb, __func__,
4518 "Freeing blocks not in datazone - "
4519 "block = %llu, count = %lu", block, count);
4520 goto error_return;
4523 ext4_debug("freeing block %llu\n", block);
4524 trace_ext4_free_blocks(inode, block, count, metadata);
4526 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4527 if (ac) {
4528 ac->ac_inode = inode;
4529 ac->ac_sb = sb;
4532 do_more:
4533 overflow = 0;
4534 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4537 * Check to see if we are freeing blocks across a group
4538 * boundary.
4540 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4541 overflow = bit + count - EXT4_BLOCKS_PER_GROUP(sb);
4542 count -= overflow;
4544 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4545 if (!bitmap_bh) {
4546 err = -EIO;
4547 goto error_return;
4549 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4550 if (!gdp) {
4551 err = -EIO;
4552 goto error_return;
4555 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4556 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4557 in_range(block, ext4_inode_table(sb, gdp),
4558 EXT4_SB(sb)->s_itb_per_group) ||
4559 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4560 EXT4_SB(sb)->s_itb_per_group)) {
4562 ext4_error(sb, __func__,
4563 "Freeing blocks in system zone - "
4564 "Block = %llu, count = %lu", block, count);
4565 /* err = 0. ext4_std_error should be a no op */
4566 goto error_return;
4569 BUFFER_TRACE(bitmap_bh, "getting write access");
4570 err = ext4_journal_get_write_access(handle, bitmap_bh);
4571 if (err)
4572 goto error_return;
4575 * We are about to modify some metadata. Call the journal APIs
4576 * to unshare ->b_data if a currently-committing transaction is
4577 * using it
4579 BUFFER_TRACE(gd_bh, "get_write_access");
4580 err = ext4_journal_get_write_access(handle, gd_bh);
4581 if (err)
4582 goto error_return;
4583 #ifdef AGGRESSIVE_CHECK
4585 int i;
4586 for (i = 0; i < count; i++)
4587 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4589 #endif
4590 if (ac) {
4591 ac->ac_b_ex.fe_group = block_group;
4592 ac->ac_b_ex.fe_start = bit;
4593 ac->ac_b_ex.fe_len = count;
4594 trace_ext4_mballoc_free(ac);
4597 err = ext4_mb_load_buddy(sb, block_group, &e4b);
4598 if (err)
4599 goto error_return;
4600 if (metadata && ext4_handle_valid(handle)) {
4601 struct ext4_free_data *new_entry;
4603 * blocks being freed are metadata. these blocks shouldn't
4604 * be used until this transaction is committed
4606 new_entry = kmem_cache_alloc(ext4_free_ext_cachep, GFP_NOFS);
4607 new_entry->start_blk = bit;
4608 new_entry->group = block_group;
4609 new_entry->count = count;
4610 new_entry->t_tid = handle->h_transaction->t_tid;
4612 ext4_lock_group(sb, block_group);
4613 mb_clear_bits(bitmap_bh->b_data, bit, count);
4614 ext4_mb_free_metadata(handle, &e4b, new_entry);
4615 } else {
4616 /* need to update group_info->bb_free and bitmap
4617 * with group lock held. generate_buddy look at
4618 * them with group lock_held
4620 ext4_lock_group(sb, block_group);
4621 mb_clear_bits(bitmap_bh->b_data, bit, count);
4622 mb_free_blocks(inode, &e4b, bit, count);
4623 ext4_mb_return_to_preallocation(inode, &e4b, block, count);
4626 ret = ext4_free_blks_count(sb, gdp) + count;
4627 ext4_free_blks_set(sb, gdp, ret);
4628 gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4629 ext4_unlock_group(sb, block_group);
4630 percpu_counter_add(&sbi->s_freeblocks_counter, count);
4632 if (sbi->s_log_groups_per_flex) {
4633 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4634 atomic_add(count, &sbi->s_flex_groups[flex_group].free_blocks);
4637 ext4_mb_unload_buddy(&e4b);
4639 *freed += count;
4641 /* We dirtied the bitmap block */
4642 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4643 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4645 /* And the group descriptor block */
4646 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4647 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4648 if (!err)
4649 err = ret;
4651 if (overflow && !err) {
4652 block += count;
4653 count = overflow;
4654 put_bh(bitmap_bh);
4655 goto do_more;
4657 sb->s_dirt = 1;
4658 error_return:
4659 brelse(bitmap_bh);
4660 ext4_std_error(sb, err);
4661 if (ac)
4662 kmem_cache_free(ext4_ac_cachep, ac);
4663 return;