ext4: release page cache in ext4_mb_load_buddy error path
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / fs / ext4 / mballoc.c
blob1738236a51060375ce2611bdaa134481fd34692c
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 <linux/slab.h>
27 #include <trace/events/ext4.h>
30 * MUSTDO:
31 * - test ext4_ext_search_left() and ext4_ext_search_right()
32 * - search for metadata in few groups
34 * TODO v4:
35 * - normalization should take into account whether file is still open
36 * - discard preallocations if no free space left (policy?)
37 * - don't normalize tails
38 * - quota
39 * - reservation for superuser
41 * TODO v3:
42 * - bitmap read-ahead (proposed by Oleg Drokin aka green)
43 * - track min/max extents in each group for better group selection
44 * - mb_mark_used() may allocate chunk right after splitting buddy
45 * - tree of groups sorted by number of free blocks
46 * - error handling
50 * The allocation request involve request for multiple number of blocks
51 * near to the goal(block) value specified.
53 * During initialization phase of the allocator we decide to use the
54 * group preallocation or inode preallocation depending on the size of
55 * the file. The size of the file could be the resulting file size we
56 * would have after allocation, or the current file size, which ever
57 * is larger. If the size is less than sbi->s_mb_stream_request we
58 * select to use the group preallocation. The default value of
59 * s_mb_stream_request is 16 blocks. This can also be tuned via
60 * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
61 * terms of number of blocks.
63 * The main motivation for having small file use group preallocation is to
64 * ensure that we have small files closer together on the disk.
66 * First stage the allocator looks at the inode prealloc list,
67 * ext4_inode_info->i_prealloc_list, which contains list of prealloc
68 * spaces for this particular inode. The inode prealloc space is
69 * represented as:
71 * pa_lstart -> the logical start block for this prealloc space
72 * pa_pstart -> the physical start block for this prealloc space
73 * pa_len -> length for this prealloc space
74 * pa_free -> free space available in this prealloc space
76 * The inode preallocation space is used looking at the _logical_ start
77 * block. If only the logical file block falls within the range of prealloc
78 * space we will consume the particular prealloc space. This make sure that
79 * that the we have contiguous physical blocks representing the file blocks
81 * The important thing to be noted in case of inode prealloc space is that
82 * we don't modify the values associated to inode prealloc space except
83 * pa_free.
85 * If we are not able to find blocks in the inode prealloc space and if we
86 * have the group allocation flag set then we look at the locality group
87 * prealloc space. These are per CPU prealloc list repreasented as
89 * ext4_sb_info.s_locality_groups[smp_processor_id()]
91 * The reason for having a per cpu locality group is to reduce the contention
92 * between CPUs. It is possible to get scheduled at this point.
94 * The locality group prealloc space is used looking at whether we have
95 * enough free space (pa_free) withing the prealloc space.
97 * If we can't allocate blocks via inode prealloc or/and locality group
98 * prealloc then we look at the buddy cache. The buddy cache is represented
99 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
100 * mapped to the buddy and bitmap information regarding different
101 * groups. The buddy information is attached to buddy cache inode so that
102 * we can access them through the page cache. The information regarding
103 * each group is loaded via ext4_mb_load_buddy. The information involve
104 * block bitmap and buddy information. The information are stored in the
105 * inode as:
107 * { page }
108 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
111 * one block each for bitmap and buddy information. So for each group we
112 * take up 2 blocks. A page can contain blocks_per_page (PAGE_CACHE_SIZE /
113 * blocksize) blocks. So it can have information regarding groups_per_page
114 * which is blocks_per_page/2
116 * The buddy cache inode is not stored on disk. The inode is thrown
117 * away when the filesystem is unmounted.
119 * We look for count number of blocks in the buddy cache. If we were able
120 * to locate that many free blocks we return with additional information
121 * regarding rest of the contiguous physical block available
123 * Before allocating blocks via buddy cache we normalize the request
124 * blocks. This ensure we ask for more blocks that we needed. The extra
125 * blocks that we get after allocation is added to the respective prealloc
126 * list. In case of inode preallocation we follow a list of heuristics
127 * based on file size. This can be found in ext4_mb_normalize_request. If
128 * we are doing a group prealloc we try to normalize the request to
129 * sbi->s_mb_group_prealloc. Default value of s_mb_group_prealloc is
130 * 512 blocks. This can be tuned via
131 * /sys/fs/ext4/<partition/mb_group_prealloc. The value is represented in
132 * terms of number of blocks. If we have mounted the file system with -O
133 * stripe=<value> option the group prealloc request is normalized to the
134 * stripe value (sbi->s_stripe)
136 * The regular allocator(using the buddy cache) supports few tunables.
138 * /sys/fs/ext4/<partition>/mb_min_to_scan
139 * /sys/fs/ext4/<partition>/mb_max_to_scan
140 * /sys/fs/ext4/<partition>/mb_order2_req
142 * The regular allocator uses buddy scan only if the request len is power of
143 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
144 * value of s_mb_order2_reqs can be tuned via
145 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
146 * stripe size (sbi->s_stripe), we try to search for contiguous block in
147 * stripe size. This should result in better allocation on RAID setups. If
148 * not, we search in the specific group using bitmap for best extents. The
149 * tunable min_to_scan and max_to_scan control the behaviour here.
150 * min_to_scan indicate how long the mballoc __must__ look for a best
151 * extent and max_to_scan indicates how long the mballoc __can__ look for a
152 * best extent in the found extents. Searching for the blocks starts with
153 * the group specified as the goal value in allocation context via
154 * ac_g_ex. Each group is first checked based on the criteria whether it
155 * can used for allocation. ext4_mb_good_group explains how the groups are
156 * checked.
158 * Both the prealloc space are getting populated as above. So for the first
159 * request we will hit the buddy cache which will result in this prealloc
160 * space getting filled. The prealloc space is then later used for the
161 * subsequent request.
165 * mballoc operates on the following data:
166 * - on-disk bitmap
167 * - in-core buddy (actually includes buddy and bitmap)
168 * - preallocation descriptors (PAs)
170 * there are two types of preallocations:
171 * - inode
172 * assiged to specific inode and can be used for this inode only.
173 * it describes part of inode's space preallocated to specific
174 * physical blocks. any block from that preallocated can be used
175 * independent. the descriptor just tracks number of blocks left
176 * unused. so, before taking some block from descriptor, one must
177 * make sure corresponded logical block isn't allocated yet. this
178 * also means that freeing any block within descriptor's range
179 * must discard all preallocated blocks.
180 * - locality group
181 * assigned to specific locality group which does not translate to
182 * permanent set of inodes: inode can join and leave group. space
183 * from this type of preallocation can be used for any inode. thus
184 * it's consumed from the beginning to the end.
186 * relation between them can be expressed as:
187 * in-core buddy = on-disk bitmap + preallocation descriptors
189 * this mean blocks mballoc considers used are:
190 * - allocated blocks (persistent)
191 * - preallocated blocks (non-persistent)
193 * consistency in mballoc world means that at any time a block is either
194 * free or used in ALL structures. notice: "any time" should not be read
195 * literally -- time is discrete and delimited by locks.
197 * to keep it simple, we don't use block numbers, instead we count number of
198 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
200 * all operations can be expressed as:
201 * - init buddy: buddy = on-disk + PAs
202 * - new PA: buddy += N; PA = N
203 * - use inode PA: on-disk += N; PA -= N
204 * - discard inode PA buddy -= on-disk - PA; PA = 0
205 * - use locality group PA on-disk += N; PA -= N
206 * - discard locality group PA buddy -= PA; PA = 0
207 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
208 * is used in real operation because we can't know actual used
209 * bits from PA, only from on-disk bitmap
211 * if we follow this strict logic, then all operations above should be atomic.
212 * given some of them can block, we'd have to use something like semaphores
213 * killing performance on high-end SMP hardware. let's try to relax it using
214 * the following knowledge:
215 * 1) if buddy is referenced, it's already initialized
216 * 2) while block is used in buddy and the buddy is referenced,
217 * nobody can re-allocate that block
218 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
219 * bit set and PA claims same block, it's OK. IOW, one can set bit in
220 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
221 * block
223 * so, now we're building a concurrency table:
224 * - init buddy vs.
225 * - new PA
226 * blocks for PA are allocated in the buddy, buddy must be referenced
227 * until PA is linked to allocation group to avoid concurrent buddy init
228 * - use inode PA
229 * we need to make sure that either on-disk bitmap or PA has uptodate data
230 * given (3) we care that PA-=N operation doesn't interfere with init
231 * - discard inode PA
232 * the simplest way would be to have buddy initialized by the discard
233 * - use locality group PA
234 * again PA-=N must be serialized with init
235 * - discard locality group PA
236 * the simplest way would be to have buddy initialized by the discard
237 * - new PA vs.
238 * - use inode PA
239 * i_data_sem serializes them
240 * - discard inode PA
241 * discard process must wait until PA isn't used by another process
242 * - use locality group PA
243 * some mutex should serialize them
244 * - discard locality group PA
245 * discard process must wait until PA isn't used by another process
246 * - use inode PA
247 * - use inode PA
248 * i_data_sem or another mutex should serializes them
249 * - discard inode PA
250 * discard process must wait until PA isn't used by another process
251 * - use locality group PA
252 * nothing wrong here -- they're different PAs covering different blocks
253 * - discard locality group PA
254 * discard process must wait until PA isn't used by another process
256 * now we're ready to make few consequences:
257 * - PA is referenced and while it is no discard is possible
258 * - PA is referenced until block isn't marked in on-disk bitmap
259 * - PA changes only after on-disk bitmap
260 * - discard must not compete with init. either init is done before
261 * any discard or they're serialized somehow
262 * - buddy init as sum of on-disk bitmap and PAs is done atomically
264 * a special case when we've used PA to emptiness. no need to modify buddy
265 * in this case, but we should care about concurrent init
270 * Logic in few words:
272 * - allocation:
273 * load group
274 * find blocks
275 * mark bits in on-disk bitmap
276 * release group
278 * - use preallocation:
279 * find proper PA (per-inode or group)
280 * load group
281 * mark bits in on-disk bitmap
282 * release group
283 * release PA
285 * - free:
286 * load group
287 * mark bits in on-disk bitmap
288 * release group
290 * - discard preallocations in group:
291 * mark PAs deleted
292 * move them onto local list
293 * load on-disk bitmap
294 * load group
295 * remove PA from object (inode or locality group)
296 * mark free blocks in-core
298 * - discard inode's preallocations:
302 * Locking rules
304 * Locks:
305 * - bitlock on a group (group)
306 * - object (inode/locality) (object)
307 * - per-pa lock (pa)
309 * Paths:
310 * - new pa
311 * object
312 * group
314 * - find and use pa:
315 * pa
317 * - release consumed pa:
318 * pa
319 * group
320 * object
322 * - generate in-core bitmap:
323 * group
324 * pa
326 * - discard all for given object (inode, locality group):
327 * object
328 * pa
329 * group
331 * - discard all for given group:
332 * group
333 * pa
334 * group
335 * object
338 static struct kmem_cache *ext4_pspace_cachep;
339 static struct kmem_cache *ext4_ac_cachep;
340 static struct kmem_cache *ext4_free_ext_cachep;
342 /* We create slab caches for groupinfo data structures based on the
343 * superblock block size. There will be one per mounted filesystem for
344 * each unique s_blocksize_bits */
345 #define NR_GRPINFO_CACHES 8
346 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
348 static const char *ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
349 "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
350 "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
351 "ext4_groupinfo_64k", "ext4_groupinfo_128k"
354 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
355 ext4_group_t group);
356 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
357 ext4_group_t group);
358 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn);
360 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
362 #if BITS_PER_LONG == 64
363 *bit += ((unsigned long) addr & 7UL) << 3;
364 addr = (void *) ((unsigned long) addr & ~7UL);
365 #elif BITS_PER_LONG == 32
366 *bit += ((unsigned long) addr & 3UL) << 3;
367 addr = (void *) ((unsigned long) addr & ~3UL);
368 #else
369 #error "how many bits you are?!"
370 #endif
371 return addr;
374 static inline int mb_test_bit(int bit, void *addr)
377 * ext4_test_bit on architecture like powerpc
378 * needs unsigned long aligned address
380 addr = mb_correct_addr_and_bit(&bit, addr);
381 return ext4_test_bit(bit, addr);
384 static inline void mb_set_bit(int bit, void *addr)
386 addr = mb_correct_addr_and_bit(&bit, addr);
387 ext4_set_bit(bit, addr);
390 static inline void mb_clear_bit(int bit, void *addr)
392 addr = mb_correct_addr_and_bit(&bit, addr);
393 ext4_clear_bit(bit, addr);
396 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
398 int fix = 0, ret, tmpmax;
399 addr = mb_correct_addr_and_bit(&fix, addr);
400 tmpmax = max + fix;
401 start += fix;
403 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
404 if (ret > max)
405 return max;
406 return ret;
409 static inline int mb_find_next_bit(void *addr, int max, int start)
411 int fix = 0, ret, tmpmax;
412 addr = mb_correct_addr_and_bit(&fix, addr);
413 tmpmax = max + fix;
414 start += fix;
416 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
417 if (ret > max)
418 return max;
419 return ret;
422 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
424 char *bb;
426 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
427 BUG_ON(max == NULL);
429 if (order > e4b->bd_blkbits + 1) {
430 *max = 0;
431 return NULL;
434 /* at order 0 we see each particular block */
435 *max = 1 << (e4b->bd_blkbits + 3);
436 if (order == 0)
437 return EXT4_MB_BITMAP(e4b);
439 bb = EXT4_MB_BUDDY(e4b) + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
440 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
442 return bb;
445 #ifdef DOUBLE_CHECK
446 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
447 int first, int count)
449 int i;
450 struct super_block *sb = e4b->bd_sb;
452 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
453 return;
454 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
455 for (i = 0; i < count; i++) {
456 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
457 ext4_fsblk_t blocknr;
459 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
460 blocknr += first + i;
461 ext4_grp_locked_error(sb, e4b->bd_group,
462 inode ? inode->i_ino : 0,
463 blocknr,
464 "freeing block already freed "
465 "(bit %u)",
466 first + i);
468 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
472 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
474 int i;
476 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
477 return;
478 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
479 for (i = 0; i < count; i++) {
480 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
481 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
485 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
487 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
488 unsigned char *b1, *b2;
489 int i;
490 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
491 b2 = (unsigned char *) bitmap;
492 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
493 if (b1[i] != b2[i]) {
494 printk(KERN_ERR "corruption in group %u "
495 "at byte %u(%u): %x in copy != %x "
496 "on disk/prealloc\n",
497 e4b->bd_group, i, i * 8, b1[i], b2[i]);
498 BUG();
504 #else
505 static inline void mb_free_blocks_double(struct inode *inode,
506 struct ext4_buddy *e4b, int first, int count)
508 return;
510 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
511 int first, int count)
513 return;
515 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
517 return;
519 #endif
521 #ifdef AGGRESSIVE_CHECK
523 #define MB_CHECK_ASSERT(assert) \
524 do { \
525 if (!(assert)) { \
526 printk(KERN_EMERG \
527 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
528 function, file, line, # assert); \
529 BUG(); \
531 } while (0)
533 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
534 const char *function, int line)
536 struct super_block *sb = e4b->bd_sb;
537 int order = e4b->bd_blkbits + 1;
538 int max;
539 int max2;
540 int i;
541 int j;
542 int k;
543 int count;
544 struct ext4_group_info *grp;
545 int fragments = 0;
546 int fstart;
547 struct list_head *cur;
548 void *buddy;
549 void *buddy2;
552 static int mb_check_counter;
553 if (mb_check_counter++ % 100 != 0)
554 return 0;
557 while (order > 1) {
558 buddy = mb_find_buddy(e4b, order, &max);
559 MB_CHECK_ASSERT(buddy);
560 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
561 MB_CHECK_ASSERT(buddy2);
562 MB_CHECK_ASSERT(buddy != buddy2);
563 MB_CHECK_ASSERT(max * 2 == max2);
565 count = 0;
566 for (i = 0; i < max; i++) {
568 if (mb_test_bit(i, buddy)) {
569 /* only single bit in buddy2 may be 1 */
570 if (!mb_test_bit(i << 1, buddy2)) {
571 MB_CHECK_ASSERT(
572 mb_test_bit((i<<1)+1, buddy2));
573 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
574 MB_CHECK_ASSERT(
575 mb_test_bit(i << 1, buddy2));
577 continue;
580 /* both bits in buddy2 must be 0 */
581 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
582 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
584 for (j = 0; j < (1 << order); j++) {
585 k = (i * (1 << order)) + j;
586 MB_CHECK_ASSERT(
587 !mb_test_bit(k, EXT4_MB_BITMAP(e4b)));
589 count++;
591 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
592 order--;
595 fstart = -1;
596 buddy = mb_find_buddy(e4b, 0, &max);
597 for (i = 0; i < max; i++) {
598 if (!mb_test_bit(i, buddy)) {
599 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
600 if (fstart == -1) {
601 fragments++;
602 fstart = i;
604 continue;
606 fstart = -1;
607 /* check used bits only */
608 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
609 buddy2 = mb_find_buddy(e4b, j, &max2);
610 k = i >> j;
611 MB_CHECK_ASSERT(k < max2);
612 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
615 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
616 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
618 grp = ext4_get_group_info(sb, e4b->bd_group);
619 buddy = mb_find_buddy(e4b, 0, &max);
620 list_for_each(cur, &grp->bb_prealloc_list) {
621 ext4_group_t groupnr;
622 struct ext4_prealloc_space *pa;
623 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
624 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
625 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
626 for (i = 0; i < pa->pa_len; i++)
627 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
629 return 0;
631 #undef MB_CHECK_ASSERT
632 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
633 __FILE__, __func__, __LINE__)
634 #else
635 #define mb_check_buddy(e4b)
636 #endif
638 /* FIXME!! need more doc */
639 static void ext4_mb_mark_free_simple(struct super_block *sb,
640 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
641 struct ext4_group_info *grp)
643 struct ext4_sb_info *sbi = EXT4_SB(sb);
644 ext4_grpblk_t min;
645 ext4_grpblk_t max;
646 ext4_grpblk_t chunk;
647 unsigned short border;
649 BUG_ON(len > EXT4_BLOCKS_PER_GROUP(sb));
651 border = 2 << sb->s_blocksize_bits;
653 while (len > 0) {
654 /* find how many blocks can be covered since this position */
655 max = ffs(first | border) - 1;
657 /* find how many blocks of power 2 we need to mark */
658 min = fls(len) - 1;
660 if (max < min)
661 min = max;
662 chunk = 1 << min;
664 /* mark multiblock chunks only */
665 grp->bb_counters[min]++;
666 if (min > 0)
667 mb_clear_bit(first >> min,
668 buddy + sbi->s_mb_offsets[min]);
670 len -= chunk;
671 first += chunk;
676 * Cache the order of the largest free extent we have available in this block
677 * group.
679 static void
680 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
682 int i;
683 int bits;
685 grp->bb_largest_free_order = -1; /* uninit */
687 bits = sb->s_blocksize_bits + 1;
688 for (i = bits; i >= 0; i--) {
689 if (grp->bb_counters[i] > 0) {
690 grp->bb_largest_free_order = i;
691 break;
696 static noinline_for_stack
697 void ext4_mb_generate_buddy(struct super_block *sb,
698 void *buddy, void *bitmap, ext4_group_t group)
700 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
701 ext4_grpblk_t max = EXT4_BLOCKS_PER_GROUP(sb);
702 ext4_grpblk_t i = 0;
703 ext4_grpblk_t first;
704 ext4_grpblk_t len;
705 unsigned free = 0;
706 unsigned fragments = 0;
707 unsigned long long period = get_cycles();
709 /* initialize buddy from bitmap which is aggregation
710 * of on-disk bitmap and preallocations */
711 i = mb_find_next_zero_bit(bitmap, max, 0);
712 grp->bb_first_free = i;
713 while (i < max) {
714 fragments++;
715 first = i;
716 i = mb_find_next_bit(bitmap, max, i);
717 len = i - first;
718 free += len;
719 if (len > 1)
720 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
721 else
722 grp->bb_counters[0]++;
723 if (i < max)
724 i = mb_find_next_zero_bit(bitmap, max, i);
726 grp->bb_fragments = fragments;
728 if (free != grp->bb_free) {
729 ext4_grp_locked_error(sb, group, 0, 0,
730 "%u blocks in bitmap, %u in gd",
731 free, grp->bb_free);
733 * If we intent to continue, we consider group descritor
734 * corrupt and update bb_free using bitmap value
736 grp->bb_free = free;
738 mb_set_largest_free_order(sb, grp);
740 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
742 period = get_cycles() - period;
743 spin_lock(&EXT4_SB(sb)->s_bal_lock);
744 EXT4_SB(sb)->s_mb_buddies_generated++;
745 EXT4_SB(sb)->s_mb_generation_time += period;
746 spin_unlock(&EXT4_SB(sb)->s_bal_lock);
749 /* The buddy information is attached the buddy cache inode
750 * for convenience. The information regarding each group
751 * is loaded via ext4_mb_load_buddy. The information involve
752 * block bitmap and buddy information. The information are
753 * stored in the inode as
755 * { page }
756 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
759 * one block each for bitmap and buddy information.
760 * So for each group we take up 2 blocks. A page can
761 * contain blocks_per_page (PAGE_CACHE_SIZE / blocksize) blocks.
762 * So it can have information regarding groups_per_page which
763 * is blocks_per_page/2
765 * Locking note: This routine takes the block group lock of all groups
766 * for this page; do not hold this lock when calling this routine!
769 static int ext4_mb_init_cache(struct page *page, char *incore)
771 ext4_group_t ngroups;
772 int blocksize;
773 int blocks_per_page;
774 int groups_per_page;
775 int err = 0;
776 int i;
777 ext4_group_t first_group;
778 int first_block;
779 struct super_block *sb;
780 struct buffer_head *bhs;
781 struct buffer_head **bh;
782 struct inode *inode;
783 char *data;
784 char *bitmap;
786 mb_debug(1, "init page %lu\n", page->index);
788 inode = page->mapping->host;
789 sb = inode->i_sb;
790 ngroups = ext4_get_groups_count(sb);
791 blocksize = 1 << inode->i_blkbits;
792 blocks_per_page = PAGE_CACHE_SIZE / blocksize;
794 groups_per_page = blocks_per_page >> 1;
795 if (groups_per_page == 0)
796 groups_per_page = 1;
798 /* allocate buffer_heads to read bitmaps */
799 if (groups_per_page > 1) {
800 err = -ENOMEM;
801 i = sizeof(struct buffer_head *) * groups_per_page;
802 bh = kzalloc(i, GFP_NOFS);
803 if (bh == NULL)
804 goto out;
805 } else
806 bh = &bhs;
808 first_group = page->index * blocks_per_page / 2;
810 /* read all groups the page covers into the cache */
811 for (i = 0; i < groups_per_page; i++) {
812 struct ext4_group_desc *desc;
814 if (first_group + i >= ngroups)
815 break;
817 err = -EIO;
818 desc = ext4_get_group_desc(sb, first_group + i, NULL);
819 if (desc == NULL)
820 goto out;
822 err = -ENOMEM;
823 bh[i] = sb_getblk(sb, ext4_block_bitmap(sb, desc));
824 if (bh[i] == NULL)
825 goto out;
827 if (bitmap_uptodate(bh[i]))
828 continue;
830 lock_buffer(bh[i]);
831 if (bitmap_uptodate(bh[i])) {
832 unlock_buffer(bh[i]);
833 continue;
835 ext4_lock_group(sb, first_group + i);
836 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
837 ext4_init_block_bitmap(sb, bh[i],
838 first_group + i, desc);
839 set_bitmap_uptodate(bh[i]);
840 set_buffer_uptodate(bh[i]);
841 ext4_unlock_group(sb, first_group + i);
842 unlock_buffer(bh[i]);
843 continue;
845 ext4_unlock_group(sb, first_group + i);
846 if (buffer_uptodate(bh[i])) {
848 * if not uninit if bh is uptodate,
849 * bitmap is also uptodate
851 set_bitmap_uptodate(bh[i]);
852 unlock_buffer(bh[i]);
853 continue;
855 get_bh(bh[i]);
857 * submit the buffer_head for read. We can
858 * safely mark the bitmap as uptodate now.
859 * We do it here so the bitmap uptodate bit
860 * get set with buffer lock held.
862 set_bitmap_uptodate(bh[i]);
863 bh[i]->b_end_io = end_buffer_read_sync;
864 submit_bh(READ, bh[i]);
865 mb_debug(1, "read bitmap for group %u\n", first_group + i);
868 /* wait for I/O completion */
869 for (i = 0; i < groups_per_page && bh[i]; i++)
870 wait_on_buffer(bh[i]);
872 err = -EIO;
873 for (i = 0; i < groups_per_page && bh[i]; i++)
874 if (!buffer_uptodate(bh[i]))
875 goto out;
877 err = 0;
878 first_block = page->index * blocks_per_page;
879 /* init the page */
880 memset(page_address(page), 0xff, PAGE_CACHE_SIZE);
881 for (i = 0; i < blocks_per_page; i++) {
882 int group;
883 struct ext4_group_info *grinfo;
885 group = (first_block + i) >> 1;
886 if (group >= ngroups)
887 break;
890 * data carry information regarding this
891 * particular group in the format specified
892 * above
895 data = page_address(page) + (i * blocksize);
896 bitmap = bh[group - first_group]->b_data;
899 * We place the buddy block and bitmap block
900 * close together
902 if ((first_block + i) & 1) {
903 /* this is block of buddy */
904 BUG_ON(incore == NULL);
905 mb_debug(1, "put buddy for group %u in page %lu/%x\n",
906 group, page->index, i * blocksize);
907 trace_ext4_mb_buddy_bitmap_load(sb, group);
908 grinfo = ext4_get_group_info(sb, group);
909 grinfo->bb_fragments = 0;
910 memset(grinfo->bb_counters, 0,
911 sizeof(*grinfo->bb_counters) *
912 (sb->s_blocksize_bits+2));
914 * incore got set to the group block bitmap below
916 ext4_lock_group(sb, group);
917 ext4_mb_generate_buddy(sb, data, incore, group);
918 ext4_unlock_group(sb, group);
919 incore = NULL;
920 } else {
921 /* this is block of bitmap */
922 BUG_ON(incore != NULL);
923 mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
924 group, page->index, i * blocksize);
925 trace_ext4_mb_bitmap_load(sb, group);
927 /* see comments in ext4_mb_put_pa() */
928 ext4_lock_group(sb, group);
929 memcpy(data, bitmap, blocksize);
931 /* mark all preallocated blks used in in-core bitmap */
932 ext4_mb_generate_from_pa(sb, data, group);
933 ext4_mb_generate_from_freelist(sb, data, group);
934 ext4_unlock_group(sb, group);
936 /* set incore so that the buddy information can be
937 * generated using this
939 incore = data;
942 SetPageUptodate(page);
944 out:
945 if (bh) {
946 for (i = 0; i < groups_per_page && bh[i]; i++)
947 brelse(bh[i]);
948 if (bh != &bhs)
949 kfree(bh);
951 return err;
955 * lock the group_info alloc_sem of all the groups
956 * belonging to the same buddy cache page. This
957 * make sure other parallel operation on the buddy
958 * cache doesn't happen whild holding the buddy cache
959 * lock
961 static int ext4_mb_get_buddy_cache_lock(struct super_block *sb,
962 ext4_group_t group)
964 int i;
965 int block, pnum;
966 int blocks_per_page;
967 int groups_per_page;
968 ext4_group_t ngroups = ext4_get_groups_count(sb);
969 ext4_group_t first_group;
970 struct ext4_group_info *grp;
972 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
974 * the buddy cache inode stores the block bitmap
975 * and buddy information in consecutive blocks.
976 * So for each group we need two blocks.
978 block = group * 2;
979 pnum = block / blocks_per_page;
980 first_group = pnum * blocks_per_page / 2;
982 groups_per_page = blocks_per_page >> 1;
983 if (groups_per_page == 0)
984 groups_per_page = 1;
985 /* read all groups the page covers into the cache */
986 for (i = 0; i < groups_per_page; i++) {
988 if ((first_group + i) >= ngroups)
989 break;
990 grp = ext4_get_group_info(sb, first_group + i);
991 /* take all groups write allocation
992 * semaphore. This make sure there is
993 * no block allocation going on in any
994 * of that groups
996 down_write_nested(&grp->alloc_sem, i);
998 return i;
1001 static void ext4_mb_put_buddy_cache_lock(struct super_block *sb,
1002 ext4_group_t group, int locked_group)
1004 int i;
1005 int block, pnum;
1006 int blocks_per_page;
1007 ext4_group_t first_group;
1008 struct ext4_group_info *grp;
1010 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1012 * the buddy cache inode stores the block bitmap
1013 * and buddy information in consecutive blocks.
1014 * So for each group we need two blocks.
1016 block = group * 2;
1017 pnum = block / blocks_per_page;
1018 first_group = pnum * blocks_per_page / 2;
1019 /* release locks on all the groups */
1020 for (i = 0; i < locked_group; i++) {
1022 grp = ext4_get_group_info(sb, first_group + i);
1023 /* take all groups write allocation
1024 * semaphore. This make sure there is
1025 * no block allocation going on in any
1026 * of that groups
1028 up_write(&grp->alloc_sem);
1034 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1035 * block group lock of all groups for this page; do not hold the BG lock when
1036 * calling this routine!
1038 static noinline_for_stack
1039 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group)
1042 int ret = 0;
1043 void *bitmap;
1044 int blocks_per_page;
1045 int block, pnum, poff;
1046 int num_grp_locked = 0;
1047 struct ext4_group_info *this_grp;
1048 struct ext4_sb_info *sbi = EXT4_SB(sb);
1049 struct inode *inode = sbi->s_buddy_cache;
1050 struct page *page = NULL, *bitmap_page = NULL;
1052 mb_debug(1, "init group %u\n", group);
1053 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1054 this_grp = ext4_get_group_info(sb, group);
1056 * This ensures that we don't reinit the buddy cache
1057 * page which map to the group from which we are already
1058 * allocating. If we are looking at the buddy cache we would
1059 * have taken a reference using ext4_mb_load_buddy and that
1060 * would have taken the alloc_sem lock.
1062 num_grp_locked = ext4_mb_get_buddy_cache_lock(sb, group);
1063 if (!EXT4_MB_GRP_NEED_INIT(this_grp)) {
1065 * somebody initialized the group
1066 * return without doing anything
1068 ret = 0;
1069 goto err;
1072 * the buddy cache inode stores the block bitmap
1073 * and buddy information in consecutive blocks.
1074 * So for each group we need two blocks.
1076 block = group * 2;
1077 pnum = block / blocks_per_page;
1078 poff = block % blocks_per_page;
1079 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1080 if (page) {
1081 BUG_ON(page->mapping != inode->i_mapping);
1082 ret = ext4_mb_init_cache(page, NULL);
1083 if (ret) {
1084 unlock_page(page);
1085 goto err;
1087 unlock_page(page);
1089 if (page == NULL || !PageUptodate(page)) {
1090 ret = -EIO;
1091 goto err;
1093 mark_page_accessed(page);
1094 bitmap_page = page;
1095 bitmap = page_address(page) + (poff * sb->s_blocksize);
1097 /* init buddy cache */
1098 block++;
1099 pnum = block / blocks_per_page;
1100 poff = block % blocks_per_page;
1101 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1102 if (page == bitmap_page) {
1104 * If both the bitmap and buddy are in
1105 * the same page we don't need to force
1106 * init the buddy
1108 unlock_page(page);
1109 } else if (page) {
1110 BUG_ON(page->mapping != inode->i_mapping);
1111 ret = ext4_mb_init_cache(page, bitmap);
1112 if (ret) {
1113 unlock_page(page);
1114 goto err;
1116 unlock_page(page);
1118 if (page == NULL || !PageUptodate(page)) {
1119 ret = -EIO;
1120 goto err;
1122 mark_page_accessed(page);
1123 err:
1124 ext4_mb_put_buddy_cache_lock(sb, group, num_grp_locked);
1125 if (bitmap_page)
1126 page_cache_release(bitmap_page);
1127 if (page)
1128 page_cache_release(page);
1129 return ret;
1133 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1134 * block group lock of all groups for this page; do not hold the BG lock when
1135 * calling this routine!
1137 static noinline_for_stack int
1138 ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1139 struct ext4_buddy *e4b)
1141 int blocks_per_page;
1142 int block;
1143 int pnum;
1144 int poff;
1145 struct page *page;
1146 int ret;
1147 struct ext4_group_info *grp;
1148 struct ext4_sb_info *sbi = EXT4_SB(sb);
1149 struct inode *inode = sbi->s_buddy_cache;
1151 mb_debug(1, "load group %u\n", group);
1153 blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1154 grp = ext4_get_group_info(sb, group);
1156 e4b->bd_blkbits = sb->s_blocksize_bits;
1157 e4b->bd_info = ext4_get_group_info(sb, group);
1158 e4b->bd_sb = sb;
1159 e4b->bd_group = group;
1160 e4b->bd_buddy_page = NULL;
1161 e4b->bd_bitmap_page = NULL;
1162 e4b->alloc_semp = &grp->alloc_sem;
1164 /* Take the read lock on the group alloc
1165 * sem. This would make sure a parallel
1166 * ext4_mb_init_group happening on other
1167 * groups mapped by the page is blocked
1168 * till we are done with allocation
1170 repeat_load_buddy:
1171 down_read(e4b->alloc_semp);
1173 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1174 /* we need to check for group need init flag
1175 * with alloc_semp held so that we can be sure
1176 * that new blocks didn't get added to the group
1177 * when we are loading the buddy cache
1179 up_read(e4b->alloc_semp);
1181 * we need full data about the group
1182 * to make a good selection
1184 ret = ext4_mb_init_group(sb, group);
1185 if (ret)
1186 return ret;
1187 goto repeat_load_buddy;
1191 * the buddy cache inode stores the block bitmap
1192 * and buddy information in consecutive blocks.
1193 * So for each group we need two blocks.
1195 block = group * 2;
1196 pnum = block / blocks_per_page;
1197 poff = block % blocks_per_page;
1199 /* we could use find_or_create_page(), but it locks page
1200 * what we'd like to avoid in fast path ... */
1201 page = find_get_page(inode->i_mapping, pnum);
1202 if (page == NULL || !PageUptodate(page)) {
1203 if (page)
1205 * drop the page reference and try
1206 * to get the page with lock. If we
1207 * are not uptodate that implies
1208 * somebody just created the page but
1209 * is yet to initialize the same. So
1210 * wait for it to initialize.
1212 page_cache_release(page);
1213 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1214 if (page) {
1215 BUG_ON(page->mapping != inode->i_mapping);
1216 if (!PageUptodate(page)) {
1217 ret = ext4_mb_init_cache(page, NULL);
1218 if (ret) {
1219 unlock_page(page);
1220 goto err;
1222 mb_cmp_bitmaps(e4b, page_address(page) +
1223 (poff * sb->s_blocksize));
1225 unlock_page(page);
1228 if (page == NULL || !PageUptodate(page)) {
1229 ret = -EIO;
1230 goto err;
1232 e4b->bd_bitmap_page = page;
1233 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1234 mark_page_accessed(page);
1236 block++;
1237 pnum = block / blocks_per_page;
1238 poff = block % blocks_per_page;
1240 page = find_get_page(inode->i_mapping, pnum);
1241 if (page == NULL || !PageUptodate(page)) {
1242 if (page)
1243 page_cache_release(page);
1244 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1245 if (page) {
1246 BUG_ON(page->mapping != inode->i_mapping);
1247 if (!PageUptodate(page)) {
1248 ret = ext4_mb_init_cache(page, e4b->bd_bitmap);
1249 if (ret) {
1250 unlock_page(page);
1251 goto err;
1254 unlock_page(page);
1257 if (page == NULL || !PageUptodate(page)) {
1258 ret = -EIO;
1259 goto err;
1261 e4b->bd_buddy_page = page;
1262 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1263 mark_page_accessed(page);
1265 BUG_ON(e4b->bd_bitmap_page == NULL);
1266 BUG_ON(e4b->bd_buddy_page == NULL);
1268 return 0;
1270 err:
1271 if (page)
1272 page_cache_release(page);
1273 if (e4b->bd_bitmap_page)
1274 page_cache_release(e4b->bd_bitmap_page);
1275 if (e4b->bd_buddy_page)
1276 page_cache_release(e4b->bd_buddy_page);
1277 e4b->bd_buddy = NULL;
1278 e4b->bd_bitmap = NULL;
1280 /* Done with the buddy cache */
1281 up_read(e4b->alloc_semp);
1282 return ret;
1285 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1287 if (e4b->bd_bitmap_page)
1288 page_cache_release(e4b->bd_bitmap_page);
1289 if (e4b->bd_buddy_page)
1290 page_cache_release(e4b->bd_buddy_page);
1291 /* Done with the buddy cache */
1292 if (e4b->alloc_semp)
1293 up_read(e4b->alloc_semp);
1297 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1299 int order = 1;
1300 void *bb;
1302 BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
1303 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1305 bb = EXT4_MB_BUDDY(e4b);
1306 while (order <= e4b->bd_blkbits + 1) {
1307 block = block >> 1;
1308 if (!mb_test_bit(block, bb)) {
1309 /* this block is part of buddy of order 'order' */
1310 return order;
1312 bb += 1 << (e4b->bd_blkbits - order);
1313 order++;
1315 return 0;
1318 static void mb_clear_bits(void *bm, int cur, int len)
1320 __u32 *addr;
1322 len = cur + len;
1323 while (cur < len) {
1324 if ((cur & 31) == 0 && (len - cur) >= 32) {
1325 /* fast path: clear whole word at once */
1326 addr = bm + (cur >> 3);
1327 *addr = 0;
1328 cur += 32;
1329 continue;
1331 mb_clear_bit(cur, bm);
1332 cur++;
1336 static void mb_set_bits(void *bm, int cur, int len)
1338 __u32 *addr;
1340 len = cur + len;
1341 while (cur < len) {
1342 if ((cur & 31) == 0 && (len - cur) >= 32) {
1343 /* fast path: set whole word at once */
1344 addr = bm + (cur >> 3);
1345 *addr = 0xffffffff;
1346 cur += 32;
1347 continue;
1349 mb_set_bit(cur, bm);
1350 cur++;
1354 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1355 int first, int count)
1357 int block = 0;
1358 int max = 0;
1359 int order;
1360 void *buddy;
1361 void *buddy2;
1362 struct super_block *sb = e4b->bd_sb;
1364 BUG_ON(first + count > (sb->s_blocksize << 3));
1365 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1366 mb_check_buddy(e4b);
1367 mb_free_blocks_double(inode, e4b, first, count);
1369 e4b->bd_info->bb_free += count;
1370 if (first < e4b->bd_info->bb_first_free)
1371 e4b->bd_info->bb_first_free = first;
1373 /* let's maintain fragments counter */
1374 if (first != 0)
1375 block = !mb_test_bit(first - 1, EXT4_MB_BITMAP(e4b));
1376 if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
1377 max = !mb_test_bit(first + count, EXT4_MB_BITMAP(e4b));
1378 if (block && max)
1379 e4b->bd_info->bb_fragments--;
1380 else if (!block && !max)
1381 e4b->bd_info->bb_fragments++;
1383 /* let's maintain buddy itself */
1384 while (count-- > 0) {
1385 block = first++;
1386 order = 0;
1388 if (!mb_test_bit(block, EXT4_MB_BITMAP(e4b))) {
1389 ext4_fsblk_t blocknr;
1391 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1392 blocknr += block;
1393 ext4_grp_locked_error(sb, e4b->bd_group,
1394 inode ? inode->i_ino : 0,
1395 blocknr,
1396 "freeing already freed block "
1397 "(bit %u)", block);
1399 mb_clear_bit(block, EXT4_MB_BITMAP(e4b));
1400 e4b->bd_info->bb_counters[order]++;
1402 /* start of the buddy */
1403 buddy = mb_find_buddy(e4b, order, &max);
1405 do {
1406 block &= ~1UL;
1407 if (mb_test_bit(block, buddy) ||
1408 mb_test_bit(block + 1, buddy))
1409 break;
1411 /* both the buddies are free, try to coalesce them */
1412 buddy2 = mb_find_buddy(e4b, order + 1, &max);
1414 if (!buddy2)
1415 break;
1417 if (order > 0) {
1418 /* for special purposes, we don't set
1419 * free bits in bitmap */
1420 mb_set_bit(block, buddy);
1421 mb_set_bit(block + 1, buddy);
1423 e4b->bd_info->bb_counters[order]--;
1424 e4b->bd_info->bb_counters[order]--;
1426 block = block >> 1;
1427 order++;
1428 e4b->bd_info->bb_counters[order]++;
1430 mb_clear_bit(block, buddy2);
1431 buddy = buddy2;
1432 } while (1);
1434 mb_set_largest_free_order(sb, e4b->bd_info);
1435 mb_check_buddy(e4b);
1438 static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
1439 int needed, struct ext4_free_extent *ex)
1441 int next = block;
1442 int max;
1443 int ord;
1444 void *buddy;
1446 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1447 BUG_ON(ex == NULL);
1449 buddy = mb_find_buddy(e4b, order, &max);
1450 BUG_ON(buddy == NULL);
1451 BUG_ON(block >= max);
1452 if (mb_test_bit(block, buddy)) {
1453 ex->fe_len = 0;
1454 ex->fe_start = 0;
1455 ex->fe_group = 0;
1456 return 0;
1459 /* FIXME dorp order completely ? */
1460 if (likely(order == 0)) {
1461 /* find actual order */
1462 order = mb_find_order_for_block(e4b, block);
1463 block = block >> order;
1466 ex->fe_len = 1 << order;
1467 ex->fe_start = block << order;
1468 ex->fe_group = e4b->bd_group;
1470 /* calc difference from given start */
1471 next = next - ex->fe_start;
1472 ex->fe_len -= next;
1473 ex->fe_start += next;
1475 while (needed > ex->fe_len &&
1476 (buddy = mb_find_buddy(e4b, order, &max))) {
1478 if (block + 1 >= max)
1479 break;
1481 next = (block + 1) * (1 << order);
1482 if (mb_test_bit(next, EXT4_MB_BITMAP(e4b)))
1483 break;
1485 ord = mb_find_order_for_block(e4b, next);
1487 order = ord;
1488 block = next >> order;
1489 ex->fe_len += 1 << order;
1492 BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1493 return ex->fe_len;
1496 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1498 int ord;
1499 int mlen = 0;
1500 int max = 0;
1501 int cur;
1502 int start = ex->fe_start;
1503 int len = ex->fe_len;
1504 unsigned ret = 0;
1505 int len0 = len;
1506 void *buddy;
1508 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1509 BUG_ON(e4b->bd_group != ex->fe_group);
1510 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1511 mb_check_buddy(e4b);
1512 mb_mark_used_double(e4b, start, len);
1514 e4b->bd_info->bb_free -= len;
1515 if (e4b->bd_info->bb_first_free == start)
1516 e4b->bd_info->bb_first_free += len;
1518 /* let's maintain fragments counter */
1519 if (start != 0)
1520 mlen = !mb_test_bit(start - 1, EXT4_MB_BITMAP(e4b));
1521 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1522 max = !mb_test_bit(start + len, EXT4_MB_BITMAP(e4b));
1523 if (mlen && max)
1524 e4b->bd_info->bb_fragments++;
1525 else if (!mlen && !max)
1526 e4b->bd_info->bb_fragments--;
1528 /* let's maintain buddy itself */
1529 while (len) {
1530 ord = mb_find_order_for_block(e4b, start);
1532 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1533 /* the whole chunk may be allocated at once! */
1534 mlen = 1 << ord;
1535 buddy = mb_find_buddy(e4b, ord, &max);
1536 BUG_ON((start >> ord) >= max);
1537 mb_set_bit(start >> ord, buddy);
1538 e4b->bd_info->bb_counters[ord]--;
1539 start += mlen;
1540 len -= mlen;
1541 BUG_ON(len < 0);
1542 continue;
1545 /* store for history */
1546 if (ret == 0)
1547 ret = len | (ord << 16);
1549 /* we have to split large buddy */
1550 BUG_ON(ord <= 0);
1551 buddy = mb_find_buddy(e4b, ord, &max);
1552 mb_set_bit(start >> ord, buddy);
1553 e4b->bd_info->bb_counters[ord]--;
1555 ord--;
1556 cur = (start >> ord) & ~1U;
1557 buddy = mb_find_buddy(e4b, ord, &max);
1558 mb_clear_bit(cur, buddy);
1559 mb_clear_bit(cur + 1, buddy);
1560 e4b->bd_info->bb_counters[ord]++;
1561 e4b->bd_info->bb_counters[ord]++;
1563 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1565 mb_set_bits(EXT4_MB_BITMAP(e4b), ex->fe_start, len0);
1566 mb_check_buddy(e4b);
1568 return ret;
1572 * Must be called under group lock!
1574 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1575 struct ext4_buddy *e4b)
1577 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1578 int ret;
1580 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1581 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1583 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1584 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1585 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1587 /* preallocation can change ac_b_ex, thus we store actually
1588 * allocated blocks for history */
1589 ac->ac_f_ex = ac->ac_b_ex;
1591 ac->ac_status = AC_STATUS_FOUND;
1592 ac->ac_tail = ret & 0xffff;
1593 ac->ac_buddy = ret >> 16;
1596 * take the page reference. We want the page to be pinned
1597 * so that we don't get a ext4_mb_init_cache_call for this
1598 * group until we update the bitmap. That would mean we
1599 * double allocate blocks. The reference is dropped
1600 * in ext4_mb_release_context
1602 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1603 get_page(ac->ac_bitmap_page);
1604 ac->ac_buddy_page = e4b->bd_buddy_page;
1605 get_page(ac->ac_buddy_page);
1606 /* on allocation we use ac to track the held semaphore */
1607 ac->alloc_semp = e4b->alloc_semp;
1608 e4b->alloc_semp = NULL;
1609 /* store last allocated for subsequent stream allocation */
1610 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1611 spin_lock(&sbi->s_md_lock);
1612 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1613 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1614 spin_unlock(&sbi->s_md_lock);
1619 * regular allocator, for general purposes allocation
1622 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1623 struct ext4_buddy *e4b,
1624 int finish_group)
1626 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1627 struct ext4_free_extent *bex = &ac->ac_b_ex;
1628 struct ext4_free_extent *gex = &ac->ac_g_ex;
1629 struct ext4_free_extent ex;
1630 int max;
1632 if (ac->ac_status == AC_STATUS_FOUND)
1633 return;
1635 * We don't want to scan for a whole year
1637 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1638 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1639 ac->ac_status = AC_STATUS_BREAK;
1640 return;
1644 * Haven't found good chunk so far, let's continue
1646 if (bex->fe_len < gex->fe_len)
1647 return;
1649 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1650 && bex->fe_group == e4b->bd_group) {
1651 /* recheck chunk's availability - we don't know
1652 * when it was found (within this lock-unlock
1653 * period or not) */
1654 max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
1655 if (max >= gex->fe_len) {
1656 ext4_mb_use_best_found(ac, e4b);
1657 return;
1663 * The routine checks whether found extent is good enough. If it is,
1664 * then the extent gets marked used and flag is set to the context
1665 * to stop scanning. Otherwise, the extent is compared with the
1666 * previous found extent and if new one is better, then it's stored
1667 * in the context. Later, the best found extent will be used, if
1668 * mballoc can't find good enough extent.
1670 * FIXME: real allocation policy is to be designed yet!
1672 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1673 struct ext4_free_extent *ex,
1674 struct ext4_buddy *e4b)
1676 struct ext4_free_extent *bex = &ac->ac_b_ex;
1677 struct ext4_free_extent *gex = &ac->ac_g_ex;
1679 BUG_ON(ex->fe_len <= 0);
1680 BUG_ON(ex->fe_len > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1681 BUG_ON(ex->fe_start >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1682 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1684 ac->ac_found++;
1687 * The special case - take what you catch first
1689 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1690 *bex = *ex;
1691 ext4_mb_use_best_found(ac, e4b);
1692 return;
1696 * Let's check whether the chuck is good enough
1698 if (ex->fe_len == gex->fe_len) {
1699 *bex = *ex;
1700 ext4_mb_use_best_found(ac, e4b);
1701 return;
1705 * If this is first found extent, just store it in the context
1707 if (bex->fe_len == 0) {
1708 *bex = *ex;
1709 return;
1713 * If new found extent is better, store it in the context
1715 if (bex->fe_len < gex->fe_len) {
1716 /* if the request isn't satisfied, any found extent
1717 * larger than previous best one is better */
1718 if (ex->fe_len > bex->fe_len)
1719 *bex = *ex;
1720 } else if (ex->fe_len > gex->fe_len) {
1721 /* if the request is satisfied, then we try to find
1722 * an extent that still satisfy the request, but is
1723 * smaller than previous one */
1724 if (ex->fe_len < bex->fe_len)
1725 *bex = *ex;
1728 ext4_mb_check_limits(ac, e4b, 0);
1731 static noinline_for_stack
1732 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1733 struct ext4_buddy *e4b)
1735 struct ext4_free_extent ex = ac->ac_b_ex;
1736 ext4_group_t group = ex.fe_group;
1737 int max;
1738 int err;
1740 BUG_ON(ex.fe_len <= 0);
1741 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1742 if (err)
1743 return err;
1745 ext4_lock_group(ac->ac_sb, group);
1746 max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
1748 if (max > 0) {
1749 ac->ac_b_ex = ex;
1750 ext4_mb_use_best_found(ac, e4b);
1753 ext4_unlock_group(ac->ac_sb, group);
1754 ext4_mb_unload_buddy(e4b);
1756 return 0;
1759 static noinline_for_stack
1760 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1761 struct ext4_buddy *e4b)
1763 ext4_group_t group = ac->ac_g_ex.fe_group;
1764 int max;
1765 int err;
1766 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1767 struct ext4_free_extent ex;
1769 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1770 return 0;
1772 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1773 if (err)
1774 return err;
1776 ext4_lock_group(ac->ac_sb, group);
1777 max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
1778 ac->ac_g_ex.fe_len, &ex);
1780 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1781 ext4_fsblk_t start;
1783 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
1784 ex.fe_start;
1785 /* use do_div to get remainder (would be 64-bit modulo) */
1786 if (do_div(start, sbi->s_stripe) == 0) {
1787 ac->ac_found++;
1788 ac->ac_b_ex = ex;
1789 ext4_mb_use_best_found(ac, e4b);
1791 } else if (max >= ac->ac_g_ex.fe_len) {
1792 BUG_ON(ex.fe_len <= 0);
1793 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1794 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1795 ac->ac_found++;
1796 ac->ac_b_ex = ex;
1797 ext4_mb_use_best_found(ac, e4b);
1798 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1799 /* Sometimes, caller may want to merge even small
1800 * number of blocks to an existing extent */
1801 BUG_ON(ex.fe_len <= 0);
1802 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1803 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1804 ac->ac_found++;
1805 ac->ac_b_ex = ex;
1806 ext4_mb_use_best_found(ac, e4b);
1808 ext4_unlock_group(ac->ac_sb, group);
1809 ext4_mb_unload_buddy(e4b);
1811 return 0;
1815 * The routine scans buddy structures (not bitmap!) from given order
1816 * to max order and tries to find big enough chunk to satisfy the req
1818 static noinline_for_stack
1819 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1820 struct ext4_buddy *e4b)
1822 struct super_block *sb = ac->ac_sb;
1823 struct ext4_group_info *grp = e4b->bd_info;
1824 void *buddy;
1825 int i;
1826 int k;
1827 int max;
1829 BUG_ON(ac->ac_2order <= 0);
1830 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1831 if (grp->bb_counters[i] == 0)
1832 continue;
1834 buddy = mb_find_buddy(e4b, i, &max);
1835 BUG_ON(buddy == NULL);
1837 k = mb_find_next_zero_bit(buddy, max, 0);
1838 BUG_ON(k >= max);
1840 ac->ac_found++;
1842 ac->ac_b_ex.fe_len = 1 << i;
1843 ac->ac_b_ex.fe_start = k << i;
1844 ac->ac_b_ex.fe_group = e4b->bd_group;
1846 ext4_mb_use_best_found(ac, e4b);
1848 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1850 if (EXT4_SB(sb)->s_mb_stats)
1851 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1853 break;
1858 * The routine scans the group and measures all found extents.
1859 * In order to optimize scanning, caller must pass number of
1860 * free blocks in the group, so the routine can know upper limit.
1862 static noinline_for_stack
1863 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1864 struct ext4_buddy *e4b)
1866 struct super_block *sb = ac->ac_sb;
1867 void *bitmap = EXT4_MB_BITMAP(e4b);
1868 struct ext4_free_extent ex;
1869 int i;
1870 int free;
1872 free = e4b->bd_info->bb_free;
1873 BUG_ON(free <= 0);
1875 i = e4b->bd_info->bb_first_free;
1877 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1878 i = mb_find_next_zero_bit(bitmap,
1879 EXT4_BLOCKS_PER_GROUP(sb), i);
1880 if (i >= EXT4_BLOCKS_PER_GROUP(sb)) {
1882 * IF we have corrupt bitmap, we won't find any
1883 * free blocks even though group info says we
1884 * we have free blocks
1886 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1887 "%d free blocks as per "
1888 "group info. But bitmap says 0",
1889 free);
1890 break;
1893 mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
1894 BUG_ON(ex.fe_len <= 0);
1895 if (free < ex.fe_len) {
1896 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1897 "%d free blocks as per "
1898 "group info. But got %d blocks",
1899 free, ex.fe_len);
1901 * The number of free blocks differs. This mostly
1902 * indicate that the bitmap is corrupt. So exit
1903 * without claiming the space.
1905 break;
1908 ext4_mb_measure_extent(ac, &ex, e4b);
1910 i += ex.fe_len;
1911 free -= ex.fe_len;
1914 ext4_mb_check_limits(ac, e4b, 1);
1918 * This is a special case for storages like raid5
1919 * we try to find stripe-aligned chunks for stripe-size-multiple requests
1921 static noinline_for_stack
1922 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1923 struct ext4_buddy *e4b)
1925 struct super_block *sb = ac->ac_sb;
1926 struct ext4_sb_info *sbi = EXT4_SB(sb);
1927 void *bitmap = EXT4_MB_BITMAP(e4b);
1928 struct ext4_free_extent ex;
1929 ext4_fsblk_t first_group_block;
1930 ext4_fsblk_t a;
1931 ext4_grpblk_t i;
1932 int max;
1934 BUG_ON(sbi->s_stripe == 0);
1936 /* find first stripe-aligned block in group */
1937 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
1939 a = first_group_block + sbi->s_stripe - 1;
1940 do_div(a, sbi->s_stripe);
1941 i = (a * sbi->s_stripe) - first_group_block;
1943 while (i < EXT4_BLOCKS_PER_GROUP(sb)) {
1944 if (!mb_test_bit(i, bitmap)) {
1945 max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
1946 if (max >= sbi->s_stripe) {
1947 ac->ac_found++;
1948 ac->ac_b_ex = ex;
1949 ext4_mb_use_best_found(ac, e4b);
1950 break;
1953 i += sbi->s_stripe;
1957 /* This is now called BEFORE we load the buddy bitmap. */
1958 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
1959 ext4_group_t group, int cr)
1961 unsigned free, fragments;
1962 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
1963 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1965 BUG_ON(cr < 0 || cr >= 4);
1967 /* We only do this if the grp has never been initialized */
1968 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1969 int ret = ext4_mb_init_group(ac->ac_sb, group);
1970 if (ret)
1971 return 0;
1974 free = grp->bb_free;
1975 fragments = grp->bb_fragments;
1976 if (free == 0)
1977 return 0;
1978 if (fragments == 0)
1979 return 0;
1981 switch (cr) {
1982 case 0:
1983 BUG_ON(ac->ac_2order == 0);
1985 if (grp->bb_largest_free_order < ac->ac_2order)
1986 return 0;
1988 /* Avoid using the first bg of a flexgroup for data files */
1989 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
1990 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
1991 ((group % flex_size) == 0))
1992 return 0;
1994 return 1;
1995 case 1:
1996 if ((free / fragments) >= ac->ac_g_ex.fe_len)
1997 return 1;
1998 break;
1999 case 2:
2000 if (free >= ac->ac_g_ex.fe_len)
2001 return 1;
2002 break;
2003 case 3:
2004 return 1;
2005 default:
2006 BUG();
2009 return 0;
2012 static noinline_for_stack int
2013 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2015 ext4_group_t ngroups, group, i;
2016 int cr;
2017 int err = 0;
2018 struct ext4_sb_info *sbi;
2019 struct super_block *sb;
2020 struct ext4_buddy e4b;
2022 sb = ac->ac_sb;
2023 sbi = EXT4_SB(sb);
2024 ngroups = ext4_get_groups_count(sb);
2025 /* non-extent files are limited to low blocks/groups */
2026 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2027 ngroups = sbi->s_blockfile_groups;
2029 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2031 /* first, try the goal */
2032 err = ext4_mb_find_by_goal(ac, &e4b);
2033 if (err || ac->ac_status == AC_STATUS_FOUND)
2034 goto out;
2036 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2037 goto out;
2040 * ac->ac2_order is set only if the fe_len is a power of 2
2041 * if ac2_order is set we also set criteria to 0 so that we
2042 * try exact allocation using buddy.
2044 i = fls(ac->ac_g_ex.fe_len);
2045 ac->ac_2order = 0;
2047 * We search using buddy data only if the order of the request
2048 * is greater than equal to the sbi_s_mb_order2_reqs
2049 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2051 if (i >= sbi->s_mb_order2_reqs) {
2053 * This should tell if fe_len is exactly power of 2
2055 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2056 ac->ac_2order = i - 1;
2059 /* if stream allocation is enabled, use global goal */
2060 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2061 /* TBD: may be hot point */
2062 spin_lock(&sbi->s_md_lock);
2063 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2064 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2065 spin_unlock(&sbi->s_md_lock);
2068 /* Let's just scan groups to find more-less suitable blocks */
2069 cr = ac->ac_2order ? 0 : 1;
2071 * cr == 0 try to get exact allocation,
2072 * cr == 3 try to get anything
2074 repeat:
2075 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2076 ac->ac_criteria = cr;
2078 * searching for the right group start
2079 * from the goal value specified
2081 group = ac->ac_g_ex.fe_group;
2083 for (i = 0; i < ngroups; group++, i++) {
2084 if (group == ngroups)
2085 group = 0;
2087 /* This now checks without needing the buddy page */
2088 if (!ext4_mb_good_group(ac, group, cr))
2089 continue;
2091 err = ext4_mb_load_buddy(sb, group, &e4b);
2092 if (err)
2093 goto out;
2095 ext4_lock_group(sb, group);
2098 * We need to check again after locking the
2099 * block group
2101 if (!ext4_mb_good_group(ac, group, cr)) {
2102 ext4_unlock_group(sb, group);
2103 ext4_mb_unload_buddy(&e4b);
2104 continue;
2107 ac->ac_groups_scanned++;
2108 if (cr == 0)
2109 ext4_mb_simple_scan_group(ac, &e4b);
2110 else if (cr == 1 && sbi->s_stripe &&
2111 !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2112 ext4_mb_scan_aligned(ac, &e4b);
2113 else
2114 ext4_mb_complex_scan_group(ac, &e4b);
2116 ext4_unlock_group(sb, group);
2117 ext4_mb_unload_buddy(&e4b);
2119 if (ac->ac_status != AC_STATUS_CONTINUE)
2120 break;
2124 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2125 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2127 * We've been searching too long. Let's try to allocate
2128 * the best chunk we've found so far
2131 ext4_mb_try_best_found(ac, &e4b);
2132 if (ac->ac_status != AC_STATUS_FOUND) {
2134 * Someone more lucky has already allocated it.
2135 * The only thing we can do is just take first
2136 * found block(s)
2137 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2139 ac->ac_b_ex.fe_group = 0;
2140 ac->ac_b_ex.fe_start = 0;
2141 ac->ac_b_ex.fe_len = 0;
2142 ac->ac_status = AC_STATUS_CONTINUE;
2143 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2144 cr = 3;
2145 atomic_inc(&sbi->s_mb_lost_chunks);
2146 goto repeat;
2149 out:
2150 return err;
2153 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2155 struct super_block *sb = seq->private;
2156 ext4_group_t group;
2158 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2159 return NULL;
2160 group = *pos + 1;
2161 return (void *) ((unsigned long) group);
2164 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2166 struct super_block *sb = seq->private;
2167 ext4_group_t group;
2169 ++*pos;
2170 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2171 return NULL;
2172 group = *pos + 1;
2173 return (void *) ((unsigned long) group);
2176 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2178 struct super_block *sb = seq->private;
2179 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2180 int i;
2181 int err;
2182 struct ext4_buddy e4b;
2183 struct sg {
2184 struct ext4_group_info info;
2185 ext4_grpblk_t counters[16];
2186 } sg;
2188 group--;
2189 if (group == 0)
2190 seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
2191 "[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2192 "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2193 "group", "free", "frags", "first",
2194 "2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
2195 "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2197 i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2198 sizeof(struct ext4_group_info);
2199 err = ext4_mb_load_buddy(sb, group, &e4b);
2200 if (err) {
2201 seq_printf(seq, "#%-5u: I/O error\n", group);
2202 return 0;
2204 ext4_lock_group(sb, group);
2205 memcpy(&sg, ext4_get_group_info(sb, group), i);
2206 ext4_unlock_group(sb, group);
2207 ext4_mb_unload_buddy(&e4b);
2209 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2210 sg.info.bb_fragments, sg.info.bb_first_free);
2211 for (i = 0; i <= 13; i++)
2212 seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2213 sg.info.bb_counters[i] : 0);
2214 seq_printf(seq, " ]\n");
2216 return 0;
2219 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2223 static const struct seq_operations ext4_mb_seq_groups_ops = {
2224 .start = ext4_mb_seq_groups_start,
2225 .next = ext4_mb_seq_groups_next,
2226 .stop = ext4_mb_seq_groups_stop,
2227 .show = ext4_mb_seq_groups_show,
2230 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2232 struct super_block *sb = PDE(inode)->data;
2233 int rc;
2235 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2236 if (rc == 0) {
2237 struct seq_file *m = file->private_data;
2238 m->private = sb;
2240 return rc;
2244 static const struct file_operations ext4_mb_seq_groups_fops = {
2245 .owner = THIS_MODULE,
2246 .open = ext4_mb_seq_groups_open,
2247 .read = seq_read,
2248 .llseek = seq_lseek,
2249 .release = seq_release,
2252 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2254 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2255 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2257 BUG_ON(!cachep);
2258 return cachep;
2261 /* Create and initialize ext4_group_info data for the given group. */
2262 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2263 struct ext4_group_desc *desc)
2265 int i;
2266 int metalen = 0;
2267 struct ext4_sb_info *sbi = EXT4_SB(sb);
2268 struct ext4_group_info **meta_group_info;
2269 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2272 * First check if this group is the first of a reserved block.
2273 * If it's true, we have to allocate a new table of pointers
2274 * to ext4_group_info structures
2276 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2277 metalen = sizeof(*meta_group_info) <<
2278 EXT4_DESC_PER_BLOCK_BITS(sb);
2279 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2280 if (meta_group_info == NULL) {
2281 printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2282 "buddy group\n");
2283 goto exit_meta_group_info;
2285 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] =
2286 meta_group_info;
2289 meta_group_info =
2290 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)];
2291 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2293 meta_group_info[i] = kmem_cache_alloc(cachep, GFP_KERNEL);
2294 if (meta_group_info[i] == NULL) {
2295 printk(KERN_ERR "EXT4-fs: can't allocate buddy mem\n");
2296 goto exit_group_info;
2298 memset(meta_group_info[i], 0, kmem_cache_size(cachep));
2299 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2300 &(meta_group_info[i]->bb_state));
2303 * initialize bb_free to be able to skip
2304 * empty groups without initialization
2306 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2307 meta_group_info[i]->bb_free =
2308 ext4_free_blocks_after_init(sb, group, desc);
2309 } else {
2310 meta_group_info[i]->bb_free =
2311 ext4_free_blks_count(sb, desc);
2314 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2315 init_rwsem(&meta_group_info[i]->alloc_sem);
2316 meta_group_info[i]->bb_free_root = RB_ROOT;
2317 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
2319 #ifdef DOUBLE_CHECK
2321 struct buffer_head *bh;
2322 meta_group_info[i]->bb_bitmap =
2323 kmalloc(sb->s_blocksize, GFP_KERNEL);
2324 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2325 bh = ext4_read_block_bitmap(sb, group);
2326 BUG_ON(bh == NULL);
2327 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2328 sb->s_blocksize);
2329 put_bh(bh);
2331 #endif
2333 return 0;
2335 exit_group_info:
2336 /* If a meta_group_info table has been allocated, release it now */
2337 if (group % EXT4_DESC_PER_BLOCK(sb) == 0)
2338 kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
2339 exit_meta_group_info:
2340 return -ENOMEM;
2341 } /* ext4_mb_add_groupinfo */
2343 static int ext4_mb_init_backend(struct super_block *sb)
2345 ext4_group_t ngroups = ext4_get_groups_count(sb);
2346 ext4_group_t i;
2347 struct ext4_sb_info *sbi = EXT4_SB(sb);
2348 struct ext4_super_block *es = sbi->s_es;
2349 int num_meta_group_infos;
2350 int num_meta_group_infos_max;
2351 int array_size;
2352 struct ext4_group_desc *desc;
2353 struct kmem_cache *cachep;
2355 /* This is the number of blocks used by GDT */
2356 num_meta_group_infos = (ngroups + EXT4_DESC_PER_BLOCK(sb) -
2357 1) >> EXT4_DESC_PER_BLOCK_BITS(sb);
2360 * This is the total number of blocks used by GDT including
2361 * the number of reserved blocks for GDT.
2362 * The s_group_info array is allocated with this value
2363 * to allow a clean online resize without a complex
2364 * manipulation of pointer.
2365 * The drawback is the unused memory when no resize
2366 * occurs but it's very low in terms of pages
2367 * (see comments below)
2368 * Need to handle this properly when META_BG resizing is allowed
2370 num_meta_group_infos_max = num_meta_group_infos +
2371 le16_to_cpu(es->s_reserved_gdt_blocks);
2374 * array_size is the size of s_group_info array. We round it
2375 * to the next power of two because this approximation is done
2376 * internally by kmalloc so we can have some more memory
2377 * for free here (e.g. may be used for META_BG resize).
2379 array_size = 1;
2380 while (array_size < sizeof(*sbi->s_group_info) *
2381 num_meta_group_infos_max)
2382 array_size = array_size << 1;
2383 /* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2384 * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2385 * So a two level scheme suffices for now. */
2386 sbi->s_group_info = kmalloc(array_size, GFP_KERNEL);
2387 if (sbi->s_group_info == NULL) {
2388 printk(KERN_ERR "EXT4-fs: can't allocate buddy meta group\n");
2389 return -ENOMEM;
2391 sbi->s_buddy_cache = new_inode(sb);
2392 if (sbi->s_buddy_cache == NULL) {
2393 printk(KERN_ERR "EXT4-fs: can't get new inode\n");
2394 goto err_freesgi;
2396 sbi->s_buddy_cache->i_ino = get_next_ino();
2397 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2398 for (i = 0; i < ngroups; i++) {
2399 desc = ext4_get_group_desc(sb, i, NULL);
2400 if (desc == NULL) {
2401 printk(KERN_ERR
2402 "EXT4-fs: can't read descriptor %u\n", i);
2403 goto err_freebuddy;
2405 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2406 goto err_freebuddy;
2409 return 0;
2411 err_freebuddy:
2412 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2413 while (i-- > 0)
2414 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2415 i = num_meta_group_infos;
2416 while (i-- > 0)
2417 kfree(sbi->s_group_info[i]);
2418 iput(sbi->s_buddy_cache);
2419 err_freesgi:
2420 kfree(sbi->s_group_info);
2421 return -ENOMEM;
2424 static void ext4_groupinfo_destroy_slabs(void)
2426 int i;
2428 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
2429 if (ext4_groupinfo_caches[i])
2430 kmem_cache_destroy(ext4_groupinfo_caches[i]);
2431 ext4_groupinfo_caches[i] = NULL;
2435 static int ext4_groupinfo_create_slab(size_t size)
2437 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
2438 int slab_size;
2439 int blocksize_bits = order_base_2(size);
2440 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2441 struct kmem_cache *cachep;
2443 if (cache_index >= NR_GRPINFO_CACHES)
2444 return -EINVAL;
2446 if (unlikely(cache_index < 0))
2447 cache_index = 0;
2449 mutex_lock(&ext4_grpinfo_slab_create_mutex);
2450 if (ext4_groupinfo_caches[cache_index]) {
2451 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2452 return 0; /* Already created */
2455 slab_size = offsetof(struct ext4_group_info,
2456 bb_counters[blocksize_bits + 2]);
2458 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
2459 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
2460 NULL);
2462 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2463 if (!cachep) {
2464 printk(KERN_EMERG "EXT4: no memory for groupinfo slab cache\n");
2465 return -ENOMEM;
2468 ext4_groupinfo_caches[cache_index] = cachep;
2470 return 0;
2473 int ext4_mb_init(struct super_block *sb, int needs_recovery)
2475 struct ext4_sb_info *sbi = EXT4_SB(sb);
2476 unsigned i, j;
2477 unsigned offset;
2478 unsigned max;
2479 int ret;
2481 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2483 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2484 if (sbi->s_mb_offsets == NULL) {
2485 ret = -ENOMEM;
2486 goto out;
2489 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2490 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2491 if (sbi->s_mb_maxs == NULL) {
2492 ret = -ENOMEM;
2493 goto out;
2496 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2497 if (ret < 0)
2498 goto out;
2500 /* order 0 is regular bitmap */
2501 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2502 sbi->s_mb_offsets[0] = 0;
2504 i = 1;
2505 offset = 0;
2506 max = sb->s_blocksize << 2;
2507 do {
2508 sbi->s_mb_offsets[i] = offset;
2509 sbi->s_mb_maxs[i] = max;
2510 offset += 1 << (sb->s_blocksize_bits - i);
2511 max = max >> 1;
2512 i++;
2513 } while (i <= sb->s_blocksize_bits + 1);
2515 /* init file for buddy data */
2516 ret = ext4_mb_init_backend(sb);
2517 if (ret != 0) {
2518 goto out;
2521 spin_lock_init(&sbi->s_md_lock);
2522 spin_lock_init(&sbi->s_bal_lock);
2524 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2525 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2526 sbi->s_mb_stats = MB_DEFAULT_STATS;
2527 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2528 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2529 sbi->s_mb_group_prealloc = MB_DEFAULT_GROUP_PREALLOC;
2531 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2532 if (sbi->s_locality_groups == NULL) {
2533 ret = -ENOMEM;
2534 goto out;
2536 for_each_possible_cpu(i) {
2537 struct ext4_locality_group *lg;
2538 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2539 mutex_init(&lg->lg_mutex);
2540 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2541 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2542 spin_lock_init(&lg->lg_prealloc_lock);
2545 if (sbi->s_proc)
2546 proc_create_data("mb_groups", S_IRUGO, sbi->s_proc,
2547 &ext4_mb_seq_groups_fops, sb);
2549 if (sbi->s_journal)
2550 sbi->s_journal->j_commit_callback = release_blocks_on_commit;
2551 out:
2552 if (ret) {
2553 kfree(sbi->s_mb_offsets);
2554 kfree(sbi->s_mb_maxs);
2556 return ret;
2559 /* need to called with the ext4 group lock held */
2560 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2562 struct ext4_prealloc_space *pa;
2563 struct list_head *cur, *tmp;
2564 int count = 0;
2566 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2567 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2568 list_del(&pa->pa_group_list);
2569 count++;
2570 kmem_cache_free(ext4_pspace_cachep, pa);
2572 if (count)
2573 mb_debug(1, "mballoc: %u PAs left\n", count);
2577 int ext4_mb_release(struct super_block *sb)
2579 ext4_group_t ngroups = ext4_get_groups_count(sb);
2580 ext4_group_t i;
2581 int num_meta_group_infos;
2582 struct ext4_group_info *grinfo;
2583 struct ext4_sb_info *sbi = EXT4_SB(sb);
2584 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2586 if (sbi->s_group_info) {
2587 for (i = 0; i < ngroups; i++) {
2588 grinfo = ext4_get_group_info(sb, i);
2589 #ifdef DOUBLE_CHECK
2590 kfree(grinfo->bb_bitmap);
2591 #endif
2592 ext4_lock_group(sb, i);
2593 ext4_mb_cleanup_pa(grinfo);
2594 ext4_unlock_group(sb, i);
2595 kmem_cache_free(cachep, grinfo);
2597 num_meta_group_infos = (ngroups +
2598 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2599 EXT4_DESC_PER_BLOCK_BITS(sb);
2600 for (i = 0; i < num_meta_group_infos; i++)
2601 kfree(sbi->s_group_info[i]);
2602 kfree(sbi->s_group_info);
2604 kfree(sbi->s_mb_offsets);
2605 kfree(sbi->s_mb_maxs);
2606 if (sbi->s_buddy_cache)
2607 iput(sbi->s_buddy_cache);
2608 if (sbi->s_mb_stats) {
2609 printk(KERN_INFO
2610 "EXT4-fs: mballoc: %u blocks %u reqs (%u success)\n",
2611 atomic_read(&sbi->s_bal_allocated),
2612 atomic_read(&sbi->s_bal_reqs),
2613 atomic_read(&sbi->s_bal_success));
2614 printk(KERN_INFO
2615 "EXT4-fs: mballoc: %u extents scanned, %u goal hits, "
2616 "%u 2^N hits, %u breaks, %u lost\n",
2617 atomic_read(&sbi->s_bal_ex_scanned),
2618 atomic_read(&sbi->s_bal_goals),
2619 atomic_read(&sbi->s_bal_2orders),
2620 atomic_read(&sbi->s_bal_breaks),
2621 atomic_read(&sbi->s_mb_lost_chunks));
2622 printk(KERN_INFO
2623 "EXT4-fs: mballoc: %lu generated and it took %Lu\n",
2624 sbi->s_mb_buddies_generated++,
2625 sbi->s_mb_generation_time);
2626 printk(KERN_INFO
2627 "EXT4-fs: mballoc: %u preallocated, %u discarded\n",
2628 atomic_read(&sbi->s_mb_preallocated),
2629 atomic_read(&sbi->s_mb_discarded));
2632 free_percpu(sbi->s_locality_groups);
2633 if (sbi->s_proc)
2634 remove_proc_entry("mb_groups", sbi->s_proc);
2636 return 0;
2639 static inline int ext4_issue_discard(struct super_block *sb,
2640 ext4_group_t block_group, ext4_grpblk_t block, int count)
2642 ext4_fsblk_t discard_block;
2644 discard_block = block + ext4_group_first_block_no(sb, block_group);
2645 trace_ext4_discard_blocks(sb,
2646 (unsigned long long) discard_block, count);
2647 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
2651 * This function is called by the jbd2 layer once the commit has finished,
2652 * so we know we can free the blocks that were released with that commit.
2654 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn)
2656 struct super_block *sb = journal->j_private;
2657 struct ext4_buddy e4b;
2658 struct ext4_group_info *db;
2659 int err, ret, count = 0, count2 = 0;
2660 struct ext4_free_data *entry;
2661 struct list_head *l, *ltmp;
2663 list_for_each_safe(l, ltmp, &txn->t_private_list) {
2664 entry = list_entry(l, struct ext4_free_data, list);
2666 mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2667 entry->count, entry->group, entry);
2669 if (test_opt(sb, DISCARD)) {
2670 ret = ext4_issue_discard(sb, entry->group,
2671 entry->start_blk, entry->count);
2672 if (unlikely(ret == -EOPNOTSUPP)) {
2673 ext4_warning(sb, "discard not supported, "
2674 "disabling");
2675 clear_opt(sb, DISCARD);
2679 err = ext4_mb_load_buddy(sb, entry->group, &e4b);
2680 /* we expect to find existing buddy because it's pinned */
2681 BUG_ON(err != 0);
2683 db = e4b.bd_info;
2684 /* there are blocks to put in buddy to make them really free */
2685 count += entry->count;
2686 count2++;
2687 ext4_lock_group(sb, entry->group);
2688 /* Take it out of per group rb tree */
2689 rb_erase(&entry->node, &(db->bb_free_root));
2690 mb_free_blocks(NULL, &e4b, entry->start_blk, entry->count);
2692 if (!db->bb_free_root.rb_node) {
2693 /* No more items in the per group rb tree
2694 * balance refcounts from ext4_mb_free_metadata()
2696 page_cache_release(e4b.bd_buddy_page);
2697 page_cache_release(e4b.bd_bitmap_page);
2699 ext4_unlock_group(sb, entry->group);
2700 kmem_cache_free(ext4_free_ext_cachep, entry);
2701 ext4_mb_unload_buddy(&e4b);
2704 mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2707 #ifdef CONFIG_EXT4_DEBUG
2708 u8 mb_enable_debug __read_mostly;
2710 static struct dentry *debugfs_dir;
2711 static struct dentry *debugfs_debug;
2713 static void __init ext4_create_debugfs_entry(void)
2715 debugfs_dir = debugfs_create_dir("ext4", NULL);
2716 if (debugfs_dir)
2717 debugfs_debug = debugfs_create_u8("mballoc-debug",
2718 S_IRUGO | S_IWUSR,
2719 debugfs_dir,
2720 &mb_enable_debug);
2723 static void ext4_remove_debugfs_entry(void)
2725 debugfs_remove(debugfs_debug);
2726 debugfs_remove(debugfs_dir);
2729 #else
2731 static void __init ext4_create_debugfs_entry(void)
2735 static void ext4_remove_debugfs_entry(void)
2739 #endif
2741 int __init ext4_init_mballoc(void)
2743 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
2744 SLAB_RECLAIM_ACCOUNT);
2745 if (ext4_pspace_cachep == NULL)
2746 return -ENOMEM;
2748 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
2749 SLAB_RECLAIM_ACCOUNT);
2750 if (ext4_ac_cachep == NULL) {
2751 kmem_cache_destroy(ext4_pspace_cachep);
2752 return -ENOMEM;
2755 ext4_free_ext_cachep = KMEM_CACHE(ext4_free_data,
2756 SLAB_RECLAIM_ACCOUNT);
2757 if (ext4_free_ext_cachep == NULL) {
2758 kmem_cache_destroy(ext4_pspace_cachep);
2759 kmem_cache_destroy(ext4_ac_cachep);
2760 return -ENOMEM;
2762 ext4_create_debugfs_entry();
2763 return 0;
2766 void ext4_exit_mballoc(void)
2769 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
2770 * before destroying the slab cache.
2772 rcu_barrier();
2773 kmem_cache_destroy(ext4_pspace_cachep);
2774 kmem_cache_destroy(ext4_ac_cachep);
2775 kmem_cache_destroy(ext4_free_ext_cachep);
2776 ext4_groupinfo_destroy_slabs();
2777 ext4_remove_debugfs_entry();
2782 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2783 * Returns 0 if success or error code
2785 static noinline_for_stack int
2786 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2787 handle_t *handle, unsigned int reserv_blks)
2789 struct buffer_head *bitmap_bh = NULL;
2790 struct ext4_group_desc *gdp;
2791 struct buffer_head *gdp_bh;
2792 struct ext4_sb_info *sbi;
2793 struct super_block *sb;
2794 ext4_fsblk_t block;
2795 int err, len;
2797 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2798 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2800 sb = ac->ac_sb;
2801 sbi = EXT4_SB(sb);
2803 err = -EIO;
2804 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2805 if (!bitmap_bh)
2806 goto out_err;
2808 err = ext4_journal_get_write_access(handle, bitmap_bh);
2809 if (err)
2810 goto out_err;
2812 err = -EIO;
2813 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2814 if (!gdp)
2815 goto out_err;
2817 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
2818 ext4_free_blks_count(sb, gdp));
2820 err = ext4_journal_get_write_access(handle, gdp_bh);
2821 if (err)
2822 goto out_err;
2824 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
2826 len = ac->ac_b_ex.fe_len;
2827 if (!ext4_data_block_valid(sbi, block, len)) {
2828 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
2829 "fs metadata\n", block, block+len);
2830 /* File system mounted not to panic on error
2831 * Fix the bitmap and repeat the block allocation
2832 * We leak some of the blocks here.
2834 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2835 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
2836 ac->ac_b_ex.fe_len);
2837 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
2838 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2839 if (!err)
2840 err = -EAGAIN;
2841 goto out_err;
2844 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
2845 #ifdef AGGRESSIVE_CHECK
2847 int i;
2848 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
2849 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
2850 bitmap_bh->b_data));
2853 #endif
2854 mb_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,ac->ac_b_ex.fe_len);
2855 if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2856 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
2857 ext4_free_blks_set(sb, gdp,
2858 ext4_free_blocks_after_init(sb,
2859 ac->ac_b_ex.fe_group, gdp));
2861 len = ext4_free_blks_count(sb, gdp) - ac->ac_b_ex.fe_len;
2862 ext4_free_blks_set(sb, gdp, len);
2863 gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
2865 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
2866 percpu_counter_sub(&sbi->s_freeblocks_counter, ac->ac_b_ex.fe_len);
2868 * Now reduce the dirty block count also. Should not go negative
2870 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
2871 /* release all the reserved blocks if non delalloc */
2872 percpu_counter_sub(&sbi->s_dirtyblocks_counter, reserv_blks);
2874 if (sbi->s_log_groups_per_flex) {
2875 ext4_group_t flex_group = ext4_flex_group(sbi,
2876 ac->ac_b_ex.fe_group);
2877 atomic_sub(ac->ac_b_ex.fe_len,
2878 &sbi->s_flex_groups[flex_group].free_blocks);
2881 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
2882 if (err)
2883 goto out_err;
2884 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
2886 out_err:
2887 ext4_mark_super_dirty(sb);
2888 brelse(bitmap_bh);
2889 return err;
2893 * here we normalize request for locality group
2894 * Group request are normalized to s_strip size if we set the same via mount
2895 * option. If not we set it to s_mb_group_prealloc which can be configured via
2896 * /sys/fs/ext4/<partition>/mb_group_prealloc
2898 * XXX: should we try to preallocate more than the group has now?
2900 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
2902 struct super_block *sb = ac->ac_sb;
2903 struct ext4_locality_group *lg = ac->ac_lg;
2905 BUG_ON(lg == NULL);
2906 if (EXT4_SB(sb)->s_stripe)
2907 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_stripe;
2908 else
2909 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
2910 mb_debug(1, "#%u: goal %u blocks for locality group\n",
2911 current->pid, ac->ac_g_ex.fe_len);
2915 * Normalization means making request better in terms of
2916 * size and alignment
2918 static noinline_for_stack void
2919 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
2920 struct ext4_allocation_request *ar)
2922 int bsbits, max;
2923 ext4_lblk_t end;
2924 loff_t size, orig_size, start_off;
2925 ext4_lblk_t start;
2926 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
2927 struct ext4_prealloc_space *pa;
2929 /* do normalize only data requests, metadata requests
2930 do not need preallocation */
2931 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
2932 return;
2934 /* sometime caller may want exact blocks */
2935 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2936 return;
2938 /* caller may indicate that preallocation isn't
2939 * required (it's a tail, for example) */
2940 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
2941 return;
2943 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
2944 ext4_mb_normalize_group_request(ac);
2945 return ;
2948 bsbits = ac->ac_sb->s_blocksize_bits;
2950 /* first, let's learn actual file size
2951 * given current request is allocated */
2952 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
2953 size = size << bsbits;
2954 if (size < i_size_read(ac->ac_inode))
2955 size = i_size_read(ac->ac_inode);
2956 orig_size = size;
2958 /* max size of free chunks */
2959 max = 2 << bsbits;
2961 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
2962 (req <= (size) || max <= (chunk_size))
2964 /* first, try to predict filesize */
2965 /* XXX: should this table be tunable? */
2966 start_off = 0;
2967 if (size <= 16 * 1024) {
2968 size = 16 * 1024;
2969 } else if (size <= 32 * 1024) {
2970 size = 32 * 1024;
2971 } else if (size <= 64 * 1024) {
2972 size = 64 * 1024;
2973 } else if (size <= 128 * 1024) {
2974 size = 128 * 1024;
2975 } else if (size <= 256 * 1024) {
2976 size = 256 * 1024;
2977 } else if (size <= 512 * 1024) {
2978 size = 512 * 1024;
2979 } else if (size <= 1024 * 1024) {
2980 size = 1024 * 1024;
2981 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
2982 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2983 (21 - bsbits)) << 21;
2984 size = 2 * 1024 * 1024;
2985 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
2986 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2987 (22 - bsbits)) << 22;
2988 size = 4 * 1024 * 1024;
2989 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
2990 (8<<20)>>bsbits, max, 8 * 1024)) {
2991 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
2992 (23 - bsbits)) << 23;
2993 size = 8 * 1024 * 1024;
2994 } else {
2995 start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
2996 size = ac->ac_o_ex.fe_len << bsbits;
2998 size = size >> bsbits;
2999 start = start_off >> bsbits;
3001 /* don't cover already allocated blocks in selected range */
3002 if (ar->pleft && start <= ar->lleft) {
3003 size -= ar->lleft + 1 - start;
3004 start = ar->lleft + 1;
3006 if (ar->pright && start + size - 1 >= ar->lright)
3007 size -= start + size - ar->lright;
3009 end = start + size;
3011 /* check we don't cross already preallocated blocks */
3012 rcu_read_lock();
3013 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3014 ext4_lblk_t pa_end;
3016 if (pa->pa_deleted)
3017 continue;
3018 spin_lock(&pa->pa_lock);
3019 if (pa->pa_deleted) {
3020 spin_unlock(&pa->pa_lock);
3021 continue;
3024 pa_end = pa->pa_lstart + pa->pa_len;
3026 /* PA must not overlap original request */
3027 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3028 ac->ac_o_ex.fe_logical < pa->pa_lstart));
3030 /* skip PAs this normalized request doesn't overlap with */
3031 if (pa->pa_lstart >= end || pa_end <= start) {
3032 spin_unlock(&pa->pa_lock);
3033 continue;
3035 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3037 /* adjust start or end to be adjacent to this pa */
3038 if (pa_end <= ac->ac_o_ex.fe_logical) {
3039 BUG_ON(pa_end < start);
3040 start = pa_end;
3041 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3042 BUG_ON(pa->pa_lstart > end);
3043 end = pa->pa_lstart;
3045 spin_unlock(&pa->pa_lock);
3047 rcu_read_unlock();
3048 size = end - start;
3050 /* XXX: extra loop to check we really don't overlap preallocations */
3051 rcu_read_lock();
3052 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3053 ext4_lblk_t pa_end;
3054 spin_lock(&pa->pa_lock);
3055 if (pa->pa_deleted == 0) {
3056 pa_end = pa->pa_lstart + pa->pa_len;
3057 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3059 spin_unlock(&pa->pa_lock);
3061 rcu_read_unlock();
3063 if (start + size <= ac->ac_o_ex.fe_logical &&
3064 start > ac->ac_o_ex.fe_logical) {
3065 printk(KERN_ERR "start %lu, size %lu, fe_logical %lu\n",
3066 (unsigned long) start, (unsigned long) size,
3067 (unsigned long) ac->ac_o_ex.fe_logical);
3069 BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3070 start > ac->ac_o_ex.fe_logical);
3071 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3073 /* now prepare goal request */
3075 /* XXX: is it better to align blocks WRT to logical
3076 * placement or satisfy big request as is */
3077 ac->ac_g_ex.fe_logical = start;
3078 ac->ac_g_ex.fe_len = size;
3080 /* define goal start in order to merge */
3081 if (ar->pright && (ar->lright == (start + size))) {
3082 /* merge to the right */
3083 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3084 &ac->ac_f_ex.fe_group,
3085 &ac->ac_f_ex.fe_start);
3086 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3088 if (ar->pleft && (ar->lleft + 1 == start)) {
3089 /* merge to the left */
3090 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3091 &ac->ac_f_ex.fe_group,
3092 &ac->ac_f_ex.fe_start);
3093 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3096 mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3097 (unsigned) orig_size, (unsigned) start);
3100 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3102 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3104 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3105 atomic_inc(&sbi->s_bal_reqs);
3106 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3107 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3108 atomic_inc(&sbi->s_bal_success);
3109 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3110 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3111 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3112 atomic_inc(&sbi->s_bal_goals);
3113 if (ac->ac_found > sbi->s_mb_max_to_scan)
3114 atomic_inc(&sbi->s_bal_breaks);
3117 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3118 trace_ext4_mballoc_alloc(ac);
3119 else
3120 trace_ext4_mballoc_prealloc(ac);
3124 * Called on failure; free up any blocks from the inode PA for this
3125 * context. We don't need this for MB_GROUP_PA because we only change
3126 * pa_free in ext4_mb_release_context(), but on failure, we've already
3127 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3129 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3131 struct ext4_prealloc_space *pa = ac->ac_pa;
3132 int len;
3134 if (pa && pa->pa_type == MB_INODE_PA) {
3135 len = ac->ac_b_ex.fe_len;
3136 pa->pa_free += len;
3142 * use blocks preallocated to inode
3144 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3145 struct ext4_prealloc_space *pa)
3147 ext4_fsblk_t start;
3148 ext4_fsblk_t end;
3149 int len;
3151 /* found preallocated blocks, use them */
3152 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3153 end = min(pa->pa_pstart + pa->pa_len, start + ac->ac_o_ex.fe_len);
3154 len = end - start;
3155 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3156 &ac->ac_b_ex.fe_start);
3157 ac->ac_b_ex.fe_len = len;
3158 ac->ac_status = AC_STATUS_FOUND;
3159 ac->ac_pa = pa;
3161 BUG_ON(start < pa->pa_pstart);
3162 BUG_ON(start + len > pa->pa_pstart + pa->pa_len);
3163 BUG_ON(pa->pa_free < len);
3164 pa->pa_free -= len;
3166 mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3170 * use blocks preallocated to locality group
3172 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3173 struct ext4_prealloc_space *pa)
3175 unsigned int len = ac->ac_o_ex.fe_len;
3177 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3178 &ac->ac_b_ex.fe_group,
3179 &ac->ac_b_ex.fe_start);
3180 ac->ac_b_ex.fe_len = len;
3181 ac->ac_status = AC_STATUS_FOUND;
3182 ac->ac_pa = pa;
3184 /* we don't correct pa_pstart or pa_plen here to avoid
3185 * possible race when the group is being loaded concurrently
3186 * instead we correct pa later, after blocks are marked
3187 * in on-disk bitmap -- see ext4_mb_release_context()
3188 * Other CPUs are prevented from allocating from this pa by lg_mutex
3190 mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3194 * Return the prealloc space that have minimal distance
3195 * from the goal block. @cpa is the prealloc
3196 * space that is having currently known minimal distance
3197 * from the goal block.
3199 static struct ext4_prealloc_space *
3200 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3201 struct ext4_prealloc_space *pa,
3202 struct ext4_prealloc_space *cpa)
3204 ext4_fsblk_t cur_distance, new_distance;
3206 if (cpa == NULL) {
3207 atomic_inc(&pa->pa_count);
3208 return pa;
3210 cur_distance = abs(goal_block - cpa->pa_pstart);
3211 new_distance = abs(goal_block - pa->pa_pstart);
3213 if (cur_distance < new_distance)
3214 return cpa;
3216 /* drop the previous reference */
3217 atomic_dec(&cpa->pa_count);
3218 atomic_inc(&pa->pa_count);
3219 return pa;
3223 * search goal blocks in preallocated space
3225 static noinline_for_stack int
3226 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3228 int order, i;
3229 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3230 struct ext4_locality_group *lg;
3231 struct ext4_prealloc_space *pa, *cpa = NULL;
3232 ext4_fsblk_t goal_block;
3234 /* only data can be preallocated */
3235 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3236 return 0;
3238 /* first, try per-file preallocation */
3239 rcu_read_lock();
3240 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3242 /* all fields in this condition don't change,
3243 * so we can skip locking for them */
3244 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3245 ac->ac_o_ex.fe_logical >= pa->pa_lstart + pa->pa_len)
3246 continue;
3248 /* non-extent files can't have physical blocks past 2^32 */
3249 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3250 pa->pa_pstart + pa->pa_len > EXT4_MAX_BLOCK_FILE_PHYS)
3251 continue;
3253 /* found preallocated blocks, use them */
3254 spin_lock(&pa->pa_lock);
3255 if (pa->pa_deleted == 0 && pa->pa_free) {
3256 atomic_inc(&pa->pa_count);
3257 ext4_mb_use_inode_pa(ac, pa);
3258 spin_unlock(&pa->pa_lock);
3259 ac->ac_criteria = 10;
3260 rcu_read_unlock();
3261 return 1;
3263 spin_unlock(&pa->pa_lock);
3265 rcu_read_unlock();
3267 /* can we use group allocation? */
3268 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3269 return 0;
3271 /* inode may have no locality group for some reason */
3272 lg = ac->ac_lg;
3273 if (lg == NULL)
3274 return 0;
3275 order = fls(ac->ac_o_ex.fe_len) - 1;
3276 if (order > PREALLOC_TB_SIZE - 1)
3277 /* The max size of hash table is PREALLOC_TB_SIZE */
3278 order = PREALLOC_TB_SIZE - 1;
3280 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3282 * search for the prealloc space that is having
3283 * minimal distance from the goal block.
3285 for (i = order; i < PREALLOC_TB_SIZE; i++) {
3286 rcu_read_lock();
3287 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3288 pa_inode_list) {
3289 spin_lock(&pa->pa_lock);
3290 if (pa->pa_deleted == 0 &&
3291 pa->pa_free >= ac->ac_o_ex.fe_len) {
3293 cpa = ext4_mb_check_group_pa(goal_block,
3294 pa, cpa);
3296 spin_unlock(&pa->pa_lock);
3298 rcu_read_unlock();
3300 if (cpa) {
3301 ext4_mb_use_group_pa(ac, cpa);
3302 ac->ac_criteria = 20;
3303 return 1;
3305 return 0;
3309 * the function goes through all block freed in the group
3310 * but not yet committed and marks them used in in-core bitmap.
3311 * buddy must be generated from this bitmap
3312 * Need to be called with the ext4 group lock held
3314 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3315 ext4_group_t group)
3317 struct rb_node *n;
3318 struct ext4_group_info *grp;
3319 struct ext4_free_data *entry;
3321 grp = ext4_get_group_info(sb, group);
3322 n = rb_first(&(grp->bb_free_root));
3324 while (n) {
3325 entry = rb_entry(n, struct ext4_free_data, node);
3326 mb_set_bits(bitmap, entry->start_blk, entry->count);
3327 n = rb_next(n);
3329 return;
3333 * the function goes through all preallocation in this group and marks them
3334 * used in in-core bitmap. buddy must be generated from this bitmap
3335 * Need to be called with ext4 group lock held
3337 static noinline_for_stack
3338 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3339 ext4_group_t group)
3341 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3342 struct ext4_prealloc_space *pa;
3343 struct list_head *cur;
3344 ext4_group_t groupnr;
3345 ext4_grpblk_t start;
3346 int preallocated = 0;
3347 int count = 0;
3348 int len;
3350 /* all form of preallocation discards first load group,
3351 * so the only competing code is preallocation use.
3352 * we don't need any locking here
3353 * notice we do NOT ignore preallocations with pa_deleted
3354 * otherwise we could leave used blocks available for
3355 * allocation in buddy when concurrent ext4_mb_put_pa()
3356 * is dropping preallocation
3358 list_for_each(cur, &grp->bb_prealloc_list) {
3359 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3360 spin_lock(&pa->pa_lock);
3361 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3362 &groupnr, &start);
3363 len = pa->pa_len;
3364 spin_unlock(&pa->pa_lock);
3365 if (unlikely(len == 0))
3366 continue;
3367 BUG_ON(groupnr != group);
3368 mb_set_bits(bitmap, start, len);
3369 preallocated += len;
3370 count++;
3372 mb_debug(1, "prellocated %u for group %u\n", preallocated, group);
3375 static void ext4_mb_pa_callback(struct rcu_head *head)
3377 struct ext4_prealloc_space *pa;
3378 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3379 kmem_cache_free(ext4_pspace_cachep, pa);
3383 * drops a reference to preallocated space descriptor
3384 * if this was the last reference and the space is consumed
3386 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3387 struct super_block *sb, struct ext4_prealloc_space *pa)
3389 ext4_group_t grp;
3390 ext4_fsblk_t grp_blk;
3392 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3393 return;
3395 /* in this short window concurrent discard can set pa_deleted */
3396 spin_lock(&pa->pa_lock);
3397 if (pa->pa_deleted == 1) {
3398 spin_unlock(&pa->pa_lock);
3399 return;
3402 pa->pa_deleted = 1;
3403 spin_unlock(&pa->pa_lock);
3405 grp_blk = pa->pa_pstart;
3407 * If doing group-based preallocation, pa_pstart may be in the
3408 * next group when pa is used up
3410 if (pa->pa_type == MB_GROUP_PA)
3411 grp_blk--;
3413 ext4_get_group_no_and_offset(sb, grp_blk, &grp, NULL);
3416 * possible race:
3418 * P1 (buddy init) P2 (regular allocation)
3419 * find block B in PA
3420 * copy on-disk bitmap to buddy
3421 * mark B in on-disk bitmap
3422 * drop PA from group
3423 * mark all PAs in buddy
3425 * thus, P1 initializes buddy with B available. to prevent this
3426 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3427 * against that pair
3429 ext4_lock_group(sb, grp);
3430 list_del(&pa->pa_group_list);
3431 ext4_unlock_group(sb, grp);
3433 spin_lock(pa->pa_obj_lock);
3434 list_del_rcu(&pa->pa_inode_list);
3435 spin_unlock(pa->pa_obj_lock);
3437 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3441 * creates new preallocated space for given inode
3443 static noinline_for_stack int
3444 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3446 struct super_block *sb = ac->ac_sb;
3447 struct ext4_prealloc_space *pa;
3448 struct ext4_group_info *grp;
3449 struct ext4_inode_info *ei;
3451 /* preallocate only when found space is larger then requested */
3452 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3453 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3454 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3456 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3457 if (pa == NULL)
3458 return -ENOMEM;
3460 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3461 int winl;
3462 int wins;
3463 int win;
3464 int offs;
3466 /* we can't allocate as much as normalizer wants.
3467 * so, found space must get proper lstart
3468 * to cover original request */
3469 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3470 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3472 /* we're limited by original request in that
3473 * logical block must be covered any way
3474 * winl is window we can move our chunk within */
3475 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3477 /* also, we should cover whole original request */
3478 wins = ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len;
3480 /* the smallest one defines real window */
3481 win = min(winl, wins);
3483 offs = ac->ac_o_ex.fe_logical % ac->ac_b_ex.fe_len;
3484 if (offs && offs < win)
3485 win = offs;
3487 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical - win;
3488 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3489 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3492 /* preallocation can change ac_b_ex, thus we store actually
3493 * allocated blocks for history */
3494 ac->ac_f_ex = ac->ac_b_ex;
3496 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3497 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3498 pa->pa_len = ac->ac_b_ex.fe_len;
3499 pa->pa_free = pa->pa_len;
3500 atomic_set(&pa->pa_count, 1);
3501 spin_lock_init(&pa->pa_lock);
3502 INIT_LIST_HEAD(&pa->pa_inode_list);
3503 INIT_LIST_HEAD(&pa->pa_group_list);
3504 pa->pa_deleted = 0;
3505 pa->pa_type = MB_INODE_PA;
3507 mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3508 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3509 trace_ext4_mb_new_inode_pa(ac, pa);
3511 ext4_mb_use_inode_pa(ac, pa);
3512 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3514 ei = EXT4_I(ac->ac_inode);
3515 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3517 pa->pa_obj_lock = &ei->i_prealloc_lock;
3518 pa->pa_inode = ac->ac_inode;
3520 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3521 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3522 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3524 spin_lock(pa->pa_obj_lock);
3525 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3526 spin_unlock(pa->pa_obj_lock);
3528 return 0;
3532 * creates new preallocated space for locality group inodes belongs to
3534 static noinline_for_stack int
3535 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3537 struct super_block *sb = ac->ac_sb;
3538 struct ext4_locality_group *lg;
3539 struct ext4_prealloc_space *pa;
3540 struct ext4_group_info *grp;
3542 /* preallocate only when found space is larger then requested */
3543 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3544 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3545 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3547 BUG_ON(ext4_pspace_cachep == NULL);
3548 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3549 if (pa == NULL)
3550 return -ENOMEM;
3552 /* preallocation can change ac_b_ex, thus we store actually
3553 * allocated blocks for history */
3554 ac->ac_f_ex = ac->ac_b_ex;
3556 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3557 pa->pa_lstart = pa->pa_pstart;
3558 pa->pa_len = ac->ac_b_ex.fe_len;
3559 pa->pa_free = pa->pa_len;
3560 atomic_set(&pa->pa_count, 1);
3561 spin_lock_init(&pa->pa_lock);
3562 INIT_LIST_HEAD(&pa->pa_inode_list);
3563 INIT_LIST_HEAD(&pa->pa_group_list);
3564 pa->pa_deleted = 0;
3565 pa->pa_type = MB_GROUP_PA;
3567 mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3568 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3569 trace_ext4_mb_new_group_pa(ac, pa);
3571 ext4_mb_use_group_pa(ac, pa);
3572 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3574 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3575 lg = ac->ac_lg;
3576 BUG_ON(lg == NULL);
3578 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3579 pa->pa_inode = NULL;
3581 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3582 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3583 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3586 * We will later add the new pa to the right bucket
3587 * after updating the pa_free in ext4_mb_release_context
3589 return 0;
3592 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3594 int err;
3596 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3597 err = ext4_mb_new_group_pa(ac);
3598 else
3599 err = ext4_mb_new_inode_pa(ac);
3600 return err;
3604 * finds all unused blocks in on-disk bitmap, frees them in
3605 * in-core bitmap and buddy.
3606 * @pa must be unlinked from inode and group lists, so that
3607 * nobody else can find/use it.
3608 * the caller MUST hold group/inode locks.
3609 * TODO: optimize the case when there are no in-core structures yet
3611 static noinline_for_stack int
3612 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3613 struct ext4_prealloc_space *pa)
3615 struct super_block *sb = e4b->bd_sb;
3616 struct ext4_sb_info *sbi = EXT4_SB(sb);
3617 unsigned int end;
3618 unsigned int next;
3619 ext4_group_t group;
3620 ext4_grpblk_t bit;
3621 unsigned long long grp_blk_start;
3622 int err = 0;
3623 int free = 0;
3625 BUG_ON(pa->pa_deleted == 0);
3626 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3627 grp_blk_start = pa->pa_pstart - bit;
3628 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3629 end = bit + pa->pa_len;
3631 while (bit < end) {
3632 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3633 if (bit >= end)
3634 break;
3635 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3636 mb_debug(1, " free preallocated %u/%u in group %u\n",
3637 (unsigned) ext4_group_first_block_no(sb, group) + bit,
3638 (unsigned) next - bit, (unsigned) group);
3639 free += next - bit;
3641 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
3642 trace_ext4_mb_release_inode_pa(sb, pa->pa_inode, pa,
3643 grp_blk_start + bit, next - bit);
3644 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3645 bit = next + 1;
3647 if (free != pa->pa_free) {
3648 printk(KERN_CRIT "pa %p: logic %lu, phys. %lu, len %lu\n",
3649 pa, (unsigned long) pa->pa_lstart,
3650 (unsigned long) pa->pa_pstart,
3651 (unsigned long) pa->pa_len);
3652 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
3653 free, pa->pa_free);
3655 * pa is already deleted so we use the value obtained
3656 * from the bitmap and continue.
3659 atomic_add(free, &sbi->s_mb_discarded);
3661 return err;
3664 static noinline_for_stack int
3665 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3666 struct ext4_prealloc_space *pa)
3668 struct super_block *sb = e4b->bd_sb;
3669 ext4_group_t group;
3670 ext4_grpblk_t bit;
3672 trace_ext4_mb_release_group_pa(sb, pa);
3673 BUG_ON(pa->pa_deleted == 0);
3674 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3675 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3676 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3677 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3678 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3680 return 0;
3684 * releases all preallocations in given group
3686 * first, we need to decide discard policy:
3687 * - when do we discard
3688 * 1) ENOSPC
3689 * - how many do we discard
3690 * 1) how many requested
3692 static noinline_for_stack int
3693 ext4_mb_discard_group_preallocations(struct super_block *sb,
3694 ext4_group_t group, int needed)
3696 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3697 struct buffer_head *bitmap_bh = NULL;
3698 struct ext4_prealloc_space *pa, *tmp;
3699 struct list_head list;
3700 struct ext4_buddy e4b;
3701 int err;
3702 int busy = 0;
3703 int free = 0;
3705 mb_debug(1, "discard preallocation for group %u\n", group);
3707 if (list_empty(&grp->bb_prealloc_list))
3708 return 0;
3710 bitmap_bh = ext4_read_block_bitmap(sb, group);
3711 if (bitmap_bh == NULL) {
3712 ext4_error(sb, "Error reading block bitmap for %u", group);
3713 return 0;
3716 err = ext4_mb_load_buddy(sb, group, &e4b);
3717 if (err) {
3718 ext4_error(sb, "Error loading buddy information for %u", group);
3719 put_bh(bitmap_bh);
3720 return 0;
3723 if (needed == 0)
3724 needed = EXT4_BLOCKS_PER_GROUP(sb) + 1;
3726 INIT_LIST_HEAD(&list);
3727 repeat:
3728 ext4_lock_group(sb, group);
3729 list_for_each_entry_safe(pa, tmp,
3730 &grp->bb_prealloc_list, pa_group_list) {
3731 spin_lock(&pa->pa_lock);
3732 if (atomic_read(&pa->pa_count)) {
3733 spin_unlock(&pa->pa_lock);
3734 busy = 1;
3735 continue;
3737 if (pa->pa_deleted) {
3738 spin_unlock(&pa->pa_lock);
3739 continue;
3742 /* seems this one can be freed ... */
3743 pa->pa_deleted = 1;
3745 /* we can trust pa_free ... */
3746 free += pa->pa_free;
3748 spin_unlock(&pa->pa_lock);
3750 list_del(&pa->pa_group_list);
3751 list_add(&pa->u.pa_tmp_list, &list);
3754 /* if we still need more blocks and some PAs were used, try again */
3755 if (free < needed && busy) {
3756 busy = 0;
3757 ext4_unlock_group(sb, group);
3759 * Yield the CPU here so that we don't get soft lockup
3760 * in non preempt case.
3762 yield();
3763 goto repeat;
3766 /* found anything to free? */
3767 if (list_empty(&list)) {
3768 BUG_ON(free != 0);
3769 goto out;
3772 /* now free all selected PAs */
3773 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3775 /* remove from object (inode or locality group) */
3776 spin_lock(pa->pa_obj_lock);
3777 list_del_rcu(&pa->pa_inode_list);
3778 spin_unlock(pa->pa_obj_lock);
3780 if (pa->pa_type == MB_GROUP_PA)
3781 ext4_mb_release_group_pa(&e4b, pa);
3782 else
3783 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3785 list_del(&pa->u.pa_tmp_list);
3786 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3789 out:
3790 ext4_unlock_group(sb, group);
3791 ext4_mb_unload_buddy(&e4b);
3792 put_bh(bitmap_bh);
3793 return free;
3797 * releases all non-used preallocated blocks for given inode
3799 * It's important to discard preallocations under i_data_sem
3800 * We don't want another block to be served from the prealloc
3801 * space when we are discarding the inode prealloc space.
3803 * FIXME!! Make sure it is valid at all the call sites
3805 void ext4_discard_preallocations(struct inode *inode)
3807 struct ext4_inode_info *ei = EXT4_I(inode);
3808 struct super_block *sb = inode->i_sb;
3809 struct buffer_head *bitmap_bh = NULL;
3810 struct ext4_prealloc_space *pa, *tmp;
3811 ext4_group_t group = 0;
3812 struct list_head list;
3813 struct ext4_buddy e4b;
3814 int err;
3816 if (!S_ISREG(inode->i_mode)) {
3817 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
3818 return;
3821 mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
3822 trace_ext4_discard_preallocations(inode);
3824 INIT_LIST_HEAD(&list);
3826 repeat:
3827 /* first, collect all pa's in the inode */
3828 spin_lock(&ei->i_prealloc_lock);
3829 while (!list_empty(&ei->i_prealloc_list)) {
3830 pa = list_entry(ei->i_prealloc_list.next,
3831 struct ext4_prealloc_space, pa_inode_list);
3832 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
3833 spin_lock(&pa->pa_lock);
3834 if (atomic_read(&pa->pa_count)) {
3835 /* this shouldn't happen often - nobody should
3836 * use preallocation while we're discarding it */
3837 spin_unlock(&pa->pa_lock);
3838 spin_unlock(&ei->i_prealloc_lock);
3839 printk(KERN_ERR "uh-oh! used pa while discarding\n");
3840 WARN_ON(1);
3841 schedule_timeout_uninterruptible(HZ);
3842 goto repeat;
3845 if (pa->pa_deleted == 0) {
3846 pa->pa_deleted = 1;
3847 spin_unlock(&pa->pa_lock);
3848 list_del_rcu(&pa->pa_inode_list);
3849 list_add(&pa->u.pa_tmp_list, &list);
3850 continue;
3853 /* someone is deleting pa right now */
3854 spin_unlock(&pa->pa_lock);
3855 spin_unlock(&ei->i_prealloc_lock);
3857 /* we have to wait here because pa_deleted
3858 * doesn't mean pa is already unlinked from
3859 * the list. as we might be called from
3860 * ->clear_inode() the inode will get freed
3861 * and concurrent thread which is unlinking
3862 * pa from inode's list may access already
3863 * freed memory, bad-bad-bad */
3865 /* XXX: if this happens too often, we can
3866 * add a flag to force wait only in case
3867 * of ->clear_inode(), but not in case of
3868 * regular truncate */
3869 schedule_timeout_uninterruptible(HZ);
3870 goto repeat;
3872 spin_unlock(&ei->i_prealloc_lock);
3874 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3875 BUG_ON(pa->pa_type != MB_INODE_PA);
3876 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
3878 err = ext4_mb_load_buddy(sb, group, &e4b);
3879 if (err) {
3880 ext4_error(sb, "Error loading buddy information for %u",
3881 group);
3882 continue;
3885 bitmap_bh = ext4_read_block_bitmap(sb, group);
3886 if (bitmap_bh == NULL) {
3887 ext4_error(sb, "Error reading block bitmap for %u",
3888 group);
3889 ext4_mb_unload_buddy(&e4b);
3890 continue;
3893 ext4_lock_group(sb, group);
3894 list_del(&pa->pa_group_list);
3895 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3896 ext4_unlock_group(sb, group);
3898 ext4_mb_unload_buddy(&e4b);
3899 put_bh(bitmap_bh);
3901 list_del(&pa->u.pa_tmp_list);
3902 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3906 #ifdef CONFIG_EXT4_DEBUG
3907 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3909 struct super_block *sb = ac->ac_sb;
3910 ext4_group_t ngroups, i;
3912 if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
3913 return;
3915 printk(KERN_ERR "EXT4-fs: Can't allocate:"
3916 " Allocation context details:\n");
3917 printk(KERN_ERR "EXT4-fs: status %d flags %d\n",
3918 ac->ac_status, ac->ac_flags);
3919 printk(KERN_ERR "EXT4-fs: orig %lu/%lu/%lu@%lu, goal %lu/%lu/%lu@%lu, "
3920 "best %lu/%lu/%lu@%lu cr %d\n",
3921 (unsigned long)ac->ac_o_ex.fe_group,
3922 (unsigned long)ac->ac_o_ex.fe_start,
3923 (unsigned long)ac->ac_o_ex.fe_len,
3924 (unsigned long)ac->ac_o_ex.fe_logical,
3925 (unsigned long)ac->ac_g_ex.fe_group,
3926 (unsigned long)ac->ac_g_ex.fe_start,
3927 (unsigned long)ac->ac_g_ex.fe_len,
3928 (unsigned long)ac->ac_g_ex.fe_logical,
3929 (unsigned long)ac->ac_b_ex.fe_group,
3930 (unsigned long)ac->ac_b_ex.fe_start,
3931 (unsigned long)ac->ac_b_ex.fe_len,
3932 (unsigned long)ac->ac_b_ex.fe_logical,
3933 (int)ac->ac_criteria);
3934 printk(KERN_ERR "EXT4-fs: %lu scanned, %d found\n", ac->ac_ex_scanned,
3935 ac->ac_found);
3936 printk(KERN_ERR "EXT4-fs: groups: \n");
3937 ngroups = ext4_get_groups_count(sb);
3938 for (i = 0; i < ngroups; i++) {
3939 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
3940 struct ext4_prealloc_space *pa;
3941 ext4_grpblk_t start;
3942 struct list_head *cur;
3943 ext4_lock_group(sb, i);
3944 list_for_each(cur, &grp->bb_prealloc_list) {
3945 pa = list_entry(cur, struct ext4_prealloc_space,
3946 pa_group_list);
3947 spin_lock(&pa->pa_lock);
3948 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3949 NULL, &start);
3950 spin_unlock(&pa->pa_lock);
3951 printk(KERN_ERR "PA:%u:%d:%u \n", i,
3952 start, pa->pa_len);
3954 ext4_unlock_group(sb, i);
3956 if (grp->bb_free == 0)
3957 continue;
3958 printk(KERN_ERR "%u: %d/%d \n",
3959 i, grp->bb_free, grp->bb_fragments);
3961 printk(KERN_ERR "\n");
3963 #else
3964 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
3966 return;
3968 #endif
3971 * We use locality group preallocation for small size file. The size of the
3972 * file is determined by the current size or the resulting size after
3973 * allocation which ever is larger
3975 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
3977 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
3979 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3980 int bsbits = ac->ac_sb->s_blocksize_bits;
3981 loff_t size, isize;
3983 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3984 return;
3986 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3987 return;
3989 size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
3990 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
3991 >> bsbits;
3993 if ((size == isize) &&
3994 !ext4_fs_is_busy(sbi) &&
3995 (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
3996 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
3997 return;
4000 /* don't use group allocation for large files */
4001 size = max(size, isize);
4002 if (size > sbi->s_mb_stream_request) {
4003 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4004 return;
4007 BUG_ON(ac->ac_lg != NULL);
4009 * locality group prealloc space are per cpu. The reason for having
4010 * per cpu locality group is to reduce the contention between block
4011 * request from multiple CPUs.
4013 ac->ac_lg = __this_cpu_ptr(sbi->s_locality_groups);
4015 /* we're going to use group allocation */
4016 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4018 /* serialize all allocations in the group */
4019 mutex_lock(&ac->ac_lg->lg_mutex);
4022 static noinline_for_stack int
4023 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4024 struct ext4_allocation_request *ar)
4026 struct super_block *sb = ar->inode->i_sb;
4027 struct ext4_sb_info *sbi = EXT4_SB(sb);
4028 struct ext4_super_block *es = sbi->s_es;
4029 ext4_group_t group;
4030 unsigned int len;
4031 ext4_fsblk_t goal;
4032 ext4_grpblk_t block;
4034 /* we can't allocate > group size */
4035 len = ar->len;
4037 /* just a dirty hack to filter too big requests */
4038 if (len >= EXT4_BLOCKS_PER_GROUP(sb) - 10)
4039 len = EXT4_BLOCKS_PER_GROUP(sb) - 10;
4041 /* start searching from the goal */
4042 goal = ar->goal;
4043 if (goal < le32_to_cpu(es->s_first_data_block) ||
4044 goal >= ext4_blocks_count(es))
4045 goal = le32_to_cpu(es->s_first_data_block);
4046 ext4_get_group_no_and_offset(sb, goal, &group, &block);
4048 /* set up allocation goals */
4049 memset(ac, 0, sizeof(struct ext4_allocation_context));
4050 ac->ac_b_ex.fe_logical = ar->logical;
4051 ac->ac_status = AC_STATUS_CONTINUE;
4052 ac->ac_sb = sb;
4053 ac->ac_inode = ar->inode;
4054 ac->ac_o_ex.fe_logical = ar->logical;
4055 ac->ac_o_ex.fe_group = group;
4056 ac->ac_o_ex.fe_start = block;
4057 ac->ac_o_ex.fe_len = len;
4058 ac->ac_g_ex.fe_logical = ar->logical;
4059 ac->ac_g_ex.fe_group = group;
4060 ac->ac_g_ex.fe_start = block;
4061 ac->ac_g_ex.fe_len = len;
4062 ac->ac_flags = ar->flags;
4064 /* we have to define context: we'll we work with a file or
4065 * locality group. this is a policy, actually */
4066 ext4_mb_group_or_file(ac);
4068 mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4069 "left: %u/%u, right %u/%u to %swritable\n",
4070 (unsigned) ar->len, (unsigned) ar->logical,
4071 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4072 (unsigned) ar->lleft, (unsigned) ar->pleft,
4073 (unsigned) ar->lright, (unsigned) ar->pright,
4074 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4075 return 0;
4079 static noinline_for_stack void
4080 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4081 struct ext4_locality_group *lg,
4082 int order, int total_entries)
4084 ext4_group_t group = 0;
4085 struct ext4_buddy e4b;
4086 struct list_head discard_list;
4087 struct ext4_prealloc_space *pa, *tmp;
4089 mb_debug(1, "discard locality group preallocation\n");
4091 INIT_LIST_HEAD(&discard_list);
4093 spin_lock(&lg->lg_prealloc_lock);
4094 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4095 pa_inode_list) {
4096 spin_lock(&pa->pa_lock);
4097 if (atomic_read(&pa->pa_count)) {
4099 * This is the pa that we just used
4100 * for block allocation. So don't
4101 * free that
4103 spin_unlock(&pa->pa_lock);
4104 continue;
4106 if (pa->pa_deleted) {
4107 spin_unlock(&pa->pa_lock);
4108 continue;
4110 /* only lg prealloc space */
4111 BUG_ON(pa->pa_type != MB_GROUP_PA);
4113 /* seems this one can be freed ... */
4114 pa->pa_deleted = 1;
4115 spin_unlock(&pa->pa_lock);
4117 list_del_rcu(&pa->pa_inode_list);
4118 list_add(&pa->u.pa_tmp_list, &discard_list);
4120 total_entries--;
4121 if (total_entries <= 5) {
4123 * we want to keep only 5 entries
4124 * allowing it to grow to 8. This
4125 * mak sure we don't call discard
4126 * soon for this list.
4128 break;
4131 spin_unlock(&lg->lg_prealloc_lock);
4133 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4135 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
4136 if (ext4_mb_load_buddy(sb, group, &e4b)) {
4137 ext4_error(sb, "Error loading buddy information for %u",
4138 group);
4139 continue;
4141 ext4_lock_group(sb, group);
4142 list_del(&pa->pa_group_list);
4143 ext4_mb_release_group_pa(&e4b, pa);
4144 ext4_unlock_group(sb, group);
4146 ext4_mb_unload_buddy(&e4b);
4147 list_del(&pa->u.pa_tmp_list);
4148 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4153 * We have incremented pa_count. So it cannot be freed at this
4154 * point. Also we hold lg_mutex. So no parallel allocation is
4155 * possible from this lg. That means pa_free cannot be updated.
4157 * A parallel ext4_mb_discard_group_preallocations is possible.
4158 * which can cause the lg_prealloc_list to be updated.
4161 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4163 int order, added = 0, lg_prealloc_count = 1;
4164 struct super_block *sb = ac->ac_sb;
4165 struct ext4_locality_group *lg = ac->ac_lg;
4166 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4168 order = fls(pa->pa_free) - 1;
4169 if (order > PREALLOC_TB_SIZE - 1)
4170 /* The max size of hash table is PREALLOC_TB_SIZE */
4171 order = PREALLOC_TB_SIZE - 1;
4172 /* Add the prealloc space to lg */
4173 rcu_read_lock();
4174 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4175 pa_inode_list) {
4176 spin_lock(&tmp_pa->pa_lock);
4177 if (tmp_pa->pa_deleted) {
4178 spin_unlock(&tmp_pa->pa_lock);
4179 continue;
4181 if (!added && pa->pa_free < tmp_pa->pa_free) {
4182 /* Add to the tail of the previous entry */
4183 list_add_tail_rcu(&pa->pa_inode_list,
4184 &tmp_pa->pa_inode_list);
4185 added = 1;
4187 * we want to count the total
4188 * number of entries in the list
4191 spin_unlock(&tmp_pa->pa_lock);
4192 lg_prealloc_count++;
4194 if (!added)
4195 list_add_tail_rcu(&pa->pa_inode_list,
4196 &lg->lg_prealloc_list[order]);
4197 rcu_read_unlock();
4199 /* Now trim the list to be not more than 8 elements */
4200 if (lg_prealloc_count > 8) {
4201 ext4_mb_discard_lg_preallocations(sb, lg,
4202 order, lg_prealloc_count);
4203 return;
4205 return ;
4209 * release all resource we used in allocation
4211 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4213 struct ext4_prealloc_space *pa = ac->ac_pa;
4214 if (pa) {
4215 if (pa->pa_type == MB_GROUP_PA) {
4216 /* see comment in ext4_mb_use_group_pa() */
4217 spin_lock(&pa->pa_lock);
4218 pa->pa_pstart += ac->ac_b_ex.fe_len;
4219 pa->pa_lstart += ac->ac_b_ex.fe_len;
4220 pa->pa_free -= ac->ac_b_ex.fe_len;
4221 pa->pa_len -= ac->ac_b_ex.fe_len;
4222 spin_unlock(&pa->pa_lock);
4225 if (ac->alloc_semp)
4226 up_read(ac->alloc_semp);
4227 if (pa) {
4229 * We want to add the pa to the right bucket.
4230 * Remove it from the list and while adding
4231 * make sure the list to which we are adding
4232 * doesn't grow big. We need to release
4233 * alloc_semp before calling ext4_mb_add_n_trim()
4235 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4236 spin_lock(pa->pa_obj_lock);
4237 list_del_rcu(&pa->pa_inode_list);
4238 spin_unlock(pa->pa_obj_lock);
4239 ext4_mb_add_n_trim(ac);
4241 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4243 if (ac->ac_bitmap_page)
4244 page_cache_release(ac->ac_bitmap_page);
4245 if (ac->ac_buddy_page)
4246 page_cache_release(ac->ac_buddy_page);
4247 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4248 mutex_unlock(&ac->ac_lg->lg_mutex);
4249 ext4_mb_collect_stats(ac);
4250 return 0;
4253 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4255 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4256 int ret;
4257 int freed = 0;
4259 trace_ext4_mb_discard_preallocations(sb, needed);
4260 for (i = 0; i < ngroups && needed > 0; i++) {
4261 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4262 freed += ret;
4263 needed -= ret;
4266 return freed;
4270 * Main entry point into mballoc to allocate blocks
4271 * it tries to use preallocation first, then falls back
4272 * to usual allocation
4274 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4275 struct ext4_allocation_request *ar, int *errp)
4277 int freed;
4278 struct ext4_allocation_context *ac = NULL;
4279 struct ext4_sb_info *sbi;
4280 struct super_block *sb;
4281 ext4_fsblk_t block = 0;
4282 unsigned int inquota = 0;
4283 unsigned int reserv_blks = 0;
4285 sb = ar->inode->i_sb;
4286 sbi = EXT4_SB(sb);
4288 trace_ext4_request_blocks(ar);
4291 * For delayed allocation, we could skip the ENOSPC and
4292 * EDQUOT check, as blocks and quotas have been already
4293 * reserved when data being copied into pagecache.
4295 if (ext4_test_inode_state(ar->inode, EXT4_STATE_DELALLOC_RESERVED))
4296 ar->flags |= EXT4_MB_DELALLOC_RESERVED;
4297 else {
4298 /* Without delayed allocation we need to verify
4299 * there is enough free blocks to do block allocation
4300 * and verify allocation doesn't exceed the quota limits.
4302 while (ar->len && ext4_claim_free_blocks(sbi, ar->len)) {
4303 /* let others to free the space */
4304 yield();
4305 ar->len = ar->len >> 1;
4307 if (!ar->len) {
4308 *errp = -ENOSPC;
4309 return 0;
4311 reserv_blks = ar->len;
4312 while (ar->len && dquot_alloc_block(ar->inode, ar->len)) {
4313 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4314 ar->len--;
4316 inquota = ar->len;
4317 if (ar->len == 0) {
4318 *errp = -EDQUOT;
4319 goto out;
4323 ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4324 if (!ac) {
4325 ar->len = 0;
4326 *errp = -ENOMEM;
4327 goto out;
4330 *errp = ext4_mb_initialize_context(ac, ar);
4331 if (*errp) {
4332 ar->len = 0;
4333 goto out;
4336 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4337 if (!ext4_mb_use_preallocated(ac)) {
4338 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4339 ext4_mb_normalize_request(ac, ar);
4340 repeat:
4341 /* allocate space in core */
4342 *errp = ext4_mb_regular_allocator(ac);
4343 if (*errp)
4344 goto errout;
4346 /* as we've just preallocated more space than
4347 * user requested orinally, we store allocated
4348 * space in a special descriptor */
4349 if (ac->ac_status == AC_STATUS_FOUND &&
4350 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4351 ext4_mb_new_preallocation(ac);
4353 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4354 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_blks);
4355 if (*errp == -EAGAIN) {
4357 * drop the reference that we took
4358 * in ext4_mb_use_best_found
4360 ext4_mb_release_context(ac);
4361 ac->ac_b_ex.fe_group = 0;
4362 ac->ac_b_ex.fe_start = 0;
4363 ac->ac_b_ex.fe_len = 0;
4364 ac->ac_status = AC_STATUS_CONTINUE;
4365 goto repeat;
4366 } else if (*errp)
4367 errout:
4368 ext4_discard_allocated_blocks(ac);
4369 else {
4370 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4371 ar->len = ac->ac_b_ex.fe_len;
4373 } else {
4374 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4375 if (freed)
4376 goto repeat;
4377 *errp = -ENOSPC;
4380 if (*errp) {
4381 ac->ac_b_ex.fe_len = 0;
4382 ar->len = 0;
4383 ext4_mb_show_ac(ac);
4385 ext4_mb_release_context(ac);
4386 out:
4387 if (ac)
4388 kmem_cache_free(ext4_ac_cachep, ac);
4389 if (inquota && ar->len < inquota)
4390 dquot_free_block(ar->inode, inquota - ar->len);
4391 if (!ar->len) {
4392 if (!ext4_test_inode_state(ar->inode,
4393 EXT4_STATE_DELALLOC_RESERVED))
4394 /* release all the reserved blocks if non delalloc */
4395 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
4396 reserv_blks);
4399 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4401 return block;
4405 * We can merge two free data extents only if the physical blocks
4406 * are contiguous, AND the extents were freed by the same transaction,
4407 * AND the blocks are associated with the same group.
4409 static int can_merge(struct ext4_free_data *entry1,
4410 struct ext4_free_data *entry2)
4412 if ((entry1->t_tid == entry2->t_tid) &&
4413 (entry1->group == entry2->group) &&
4414 ((entry1->start_blk + entry1->count) == entry2->start_blk))
4415 return 1;
4416 return 0;
4419 static noinline_for_stack int
4420 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4421 struct ext4_free_data *new_entry)
4423 ext4_group_t group = e4b->bd_group;
4424 ext4_grpblk_t block;
4425 struct ext4_free_data *entry;
4426 struct ext4_group_info *db = e4b->bd_info;
4427 struct super_block *sb = e4b->bd_sb;
4428 struct ext4_sb_info *sbi = EXT4_SB(sb);
4429 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4430 struct rb_node *parent = NULL, *new_node;
4432 BUG_ON(!ext4_handle_valid(handle));
4433 BUG_ON(e4b->bd_bitmap_page == NULL);
4434 BUG_ON(e4b->bd_buddy_page == NULL);
4436 new_node = &new_entry->node;
4437 block = new_entry->start_blk;
4439 if (!*n) {
4440 /* first free block exent. We need to
4441 protect buddy cache from being freed,
4442 * otherwise we'll refresh it from
4443 * on-disk bitmap and lose not-yet-available
4444 * blocks */
4445 page_cache_get(e4b->bd_buddy_page);
4446 page_cache_get(e4b->bd_bitmap_page);
4448 while (*n) {
4449 parent = *n;
4450 entry = rb_entry(parent, struct ext4_free_data, node);
4451 if (block < entry->start_blk)
4452 n = &(*n)->rb_left;
4453 else if (block >= (entry->start_blk + entry->count))
4454 n = &(*n)->rb_right;
4455 else {
4456 ext4_grp_locked_error(sb, group, 0,
4457 ext4_group_first_block_no(sb, group) + block,
4458 "Block already on to-be-freed list");
4459 return 0;
4463 rb_link_node(new_node, parent, n);
4464 rb_insert_color(new_node, &db->bb_free_root);
4466 /* Now try to see the extent can be merged to left and right */
4467 node = rb_prev(new_node);
4468 if (node) {
4469 entry = rb_entry(node, struct ext4_free_data, node);
4470 if (can_merge(entry, new_entry)) {
4471 new_entry->start_blk = entry->start_blk;
4472 new_entry->count += entry->count;
4473 rb_erase(node, &(db->bb_free_root));
4474 spin_lock(&sbi->s_md_lock);
4475 list_del(&entry->list);
4476 spin_unlock(&sbi->s_md_lock);
4477 kmem_cache_free(ext4_free_ext_cachep, entry);
4481 node = rb_next(new_node);
4482 if (node) {
4483 entry = rb_entry(node, struct ext4_free_data, node);
4484 if (can_merge(new_entry, entry)) {
4485 new_entry->count += entry->count;
4486 rb_erase(node, &(db->bb_free_root));
4487 spin_lock(&sbi->s_md_lock);
4488 list_del(&entry->list);
4489 spin_unlock(&sbi->s_md_lock);
4490 kmem_cache_free(ext4_free_ext_cachep, entry);
4493 /* Add the extent to transaction's private list */
4494 spin_lock(&sbi->s_md_lock);
4495 list_add(&new_entry->list, &handle->h_transaction->t_private_list);
4496 spin_unlock(&sbi->s_md_lock);
4497 return 0;
4501 * ext4_free_blocks() -- Free given blocks and update quota
4502 * @handle: handle for this transaction
4503 * @inode: inode
4504 * @block: start physical block to free
4505 * @count: number of blocks to count
4506 * @metadata: Are these metadata blocks
4508 void ext4_free_blocks(handle_t *handle, struct inode *inode,
4509 struct buffer_head *bh, ext4_fsblk_t block,
4510 unsigned long count, int flags)
4512 struct buffer_head *bitmap_bh = NULL;
4513 struct super_block *sb = inode->i_sb;
4514 struct ext4_group_desc *gdp;
4515 unsigned long freed = 0;
4516 unsigned int overflow;
4517 ext4_grpblk_t bit;
4518 struct buffer_head *gd_bh;
4519 ext4_group_t block_group;
4520 struct ext4_sb_info *sbi;
4521 struct ext4_buddy e4b;
4522 int err = 0;
4523 int ret;
4525 if (bh) {
4526 if (block)
4527 BUG_ON(block != bh->b_blocknr);
4528 else
4529 block = bh->b_blocknr;
4532 sbi = EXT4_SB(sb);
4533 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
4534 !ext4_data_block_valid(sbi, block, count)) {
4535 ext4_error(sb, "Freeing blocks not in datazone - "
4536 "block = %llu, count = %lu", block, count);
4537 goto error_return;
4540 ext4_debug("freeing block %llu\n", block);
4541 trace_ext4_free_blocks(inode, block, count, flags);
4543 if (flags & EXT4_FREE_BLOCKS_FORGET) {
4544 struct buffer_head *tbh = bh;
4545 int i;
4547 BUG_ON(bh && (count > 1));
4549 for (i = 0; i < count; i++) {
4550 if (!bh)
4551 tbh = sb_find_get_block(inode->i_sb,
4552 block + i);
4553 if (unlikely(!tbh))
4554 continue;
4555 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4556 inode, tbh, block + i);
4561 * We need to make sure we don't reuse the freed block until
4562 * after the transaction is committed, which we can do by
4563 * treating the block as metadata, below. We make an
4564 * exception if the inode is to be written in writeback mode
4565 * since writeback mode has weak data consistency guarantees.
4567 if (!ext4_should_writeback_data(inode))
4568 flags |= EXT4_FREE_BLOCKS_METADATA;
4570 do_more:
4571 overflow = 0;
4572 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4575 * Check to see if we are freeing blocks across a group
4576 * boundary.
4578 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4579 overflow = bit + count - EXT4_BLOCKS_PER_GROUP(sb);
4580 count -= overflow;
4582 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4583 if (!bitmap_bh) {
4584 err = -EIO;
4585 goto error_return;
4587 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4588 if (!gdp) {
4589 err = -EIO;
4590 goto error_return;
4593 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4594 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4595 in_range(block, ext4_inode_table(sb, gdp),
4596 EXT4_SB(sb)->s_itb_per_group) ||
4597 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4598 EXT4_SB(sb)->s_itb_per_group)) {
4600 ext4_error(sb, "Freeing blocks in system zone - "
4601 "Block = %llu, count = %lu", block, count);
4602 /* err = 0. ext4_std_error should be a no op */
4603 goto error_return;
4606 BUFFER_TRACE(bitmap_bh, "getting write access");
4607 err = ext4_journal_get_write_access(handle, bitmap_bh);
4608 if (err)
4609 goto error_return;
4612 * We are about to modify some metadata. Call the journal APIs
4613 * to unshare ->b_data if a currently-committing transaction is
4614 * using it
4616 BUFFER_TRACE(gd_bh, "get_write_access");
4617 err = ext4_journal_get_write_access(handle, gd_bh);
4618 if (err)
4619 goto error_return;
4620 #ifdef AGGRESSIVE_CHECK
4622 int i;
4623 for (i = 0; i < count; i++)
4624 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4626 #endif
4627 trace_ext4_mballoc_free(sb, inode, block_group, bit, count);
4629 err = ext4_mb_load_buddy(sb, block_group, &e4b);
4630 if (err)
4631 goto error_return;
4633 if ((flags & EXT4_FREE_BLOCKS_METADATA) && ext4_handle_valid(handle)) {
4634 struct ext4_free_data *new_entry;
4636 * blocks being freed are metadata. these blocks shouldn't
4637 * be used until this transaction is committed
4639 new_entry = kmem_cache_alloc(ext4_free_ext_cachep, GFP_NOFS);
4640 if (!new_entry) {
4641 err = -ENOMEM;
4642 goto error_return;
4644 new_entry->start_blk = bit;
4645 new_entry->group = block_group;
4646 new_entry->count = count;
4647 new_entry->t_tid = handle->h_transaction->t_tid;
4649 ext4_lock_group(sb, block_group);
4650 mb_clear_bits(bitmap_bh->b_data, bit, count);
4651 ext4_mb_free_metadata(handle, &e4b, new_entry);
4652 } else {
4653 /* need to update group_info->bb_free and bitmap
4654 * with group lock held. generate_buddy look at
4655 * them with group lock_held
4657 ext4_lock_group(sb, block_group);
4658 mb_clear_bits(bitmap_bh->b_data, bit, count);
4659 mb_free_blocks(inode, &e4b, bit, count);
4662 ret = ext4_free_blks_count(sb, gdp) + count;
4663 ext4_free_blks_set(sb, gdp, ret);
4664 gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4665 ext4_unlock_group(sb, block_group);
4666 percpu_counter_add(&sbi->s_freeblocks_counter, count);
4668 if (sbi->s_log_groups_per_flex) {
4669 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4670 atomic_add(count, &sbi->s_flex_groups[flex_group].free_blocks);
4673 ext4_mb_unload_buddy(&e4b);
4675 freed += count;
4677 /* We dirtied the bitmap block */
4678 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4679 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4681 /* And the group descriptor block */
4682 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4683 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4684 if (!err)
4685 err = ret;
4687 if (overflow && !err) {
4688 block += count;
4689 count = overflow;
4690 put_bh(bitmap_bh);
4691 goto do_more;
4693 ext4_mark_super_dirty(sb);
4694 error_return:
4695 if (freed)
4696 dquot_free_block(inode, freed);
4697 brelse(bitmap_bh);
4698 ext4_std_error(sb, err);
4699 return;
4703 * ext4_trim_extent -- function to TRIM one single free extent in the group
4704 * @sb: super block for the file system
4705 * @start: starting block of the free extent in the alloc. group
4706 * @count: number of blocks to TRIM
4707 * @group: alloc. group we are working with
4708 * @e4b: ext4 buddy for the group
4710 * Trim "count" blocks starting at "start" in the "group". To assure that no
4711 * one will allocate those blocks, mark it as used in buddy bitmap. This must
4712 * be called with under the group lock.
4714 static int ext4_trim_extent(struct super_block *sb, int start, int count,
4715 ext4_group_t group, struct ext4_buddy *e4b)
4717 struct ext4_free_extent ex;
4718 int ret = 0;
4720 assert_spin_locked(ext4_group_lock_ptr(sb, group));
4722 ex.fe_start = start;
4723 ex.fe_group = group;
4724 ex.fe_len = count;
4727 * Mark blocks used, so no one can reuse them while
4728 * being trimmed.
4730 mb_mark_used(e4b, &ex);
4731 ext4_unlock_group(sb, group);
4733 ret = ext4_issue_discard(sb, group, start, count);
4735 ext4_lock_group(sb, group);
4736 mb_free_blocks(NULL, e4b, start, ex.fe_len);
4737 return ret;
4741 * ext4_trim_all_free -- function to trim all free space in alloc. group
4742 * @sb: super block for file system
4743 * @e4b: ext4 buddy
4744 * @start: first group block to examine
4745 * @max: last group block to examine
4746 * @minblocks: minimum extent block count
4748 * ext4_trim_all_free walks through group's buddy bitmap searching for free
4749 * extents. When the free block is found, ext4_trim_extent is called to TRIM
4750 * the extent.
4753 * ext4_trim_all_free walks through group's block bitmap searching for free
4754 * extents. When the free extent is found, mark it as used in group buddy
4755 * bitmap. Then issue a TRIM command on this extent and free the extent in
4756 * the group buddy bitmap. This is done until whole group is scanned.
4758 ext4_grpblk_t ext4_trim_all_free(struct super_block *sb, struct ext4_buddy *e4b,
4759 ext4_grpblk_t start, ext4_grpblk_t max, ext4_grpblk_t minblocks)
4761 void *bitmap;
4762 ext4_grpblk_t next, count = 0;
4763 ext4_group_t group;
4764 int ret = 0;
4766 BUG_ON(e4b == NULL);
4768 bitmap = e4b->bd_bitmap;
4769 group = e4b->bd_group;
4770 start = (e4b->bd_info->bb_first_free > start) ?
4771 e4b->bd_info->bb_first_free : start;
4772 ext4_lock_group(sb, group);
4774 while (start < max) {
4775 start = mb_find_next_zero_bit(bitmap, max, start);
4776 if (start >= max)
4777 break;
4778 next = mb_find_next_bit(bitmap, max, start);
4780 if ((next - start) >= minblocks) {
4781 ret = ext4_trim_extent(sb, start,
4782 next - start, group, e4b);
4783 if (ret < 0)
4784 break;
4785 count += next - start;
4787 start = next + 1;
4789 if (fatal_signal_pending(current)) {
4790 count = -ERESTARTSYS;
4791 break;
4794 if (need_resched()) {
4795 ext4_unlock_group(sb, group);
4796 cond_resched();
4797 ext4_lock_group(sb, group);
4800 if ((e4b->bd_info->bb_free - count) < minblocks)
4801 break;
4803 ext4_unlock_group(sb, group);
4805 ext4_debug("trimmed %d blocks in the group %d\n",
4806 count, group);
4808 if (ret < 0)
4809 count = ret;
4811 return count;
4815 * ext4_trim_fs() -- trim ioctl handle function
4816 * @sb: superblock for filesystem
4817 * @range: fstrim_range structure
4819 * start: First Byte to trim
4820 * len: number of Bytes to trim from start
4821 * minlen: minimum extent length in Bytes
4822 * ext4_trim_fs goes through all allocation groups containing Bytes from
4823 * start to start+len. For each such a group ext4_trim_all_free function
4824 * is invoked to trim all free space.
4826 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
4828 struct ext4_buddy e4b;
4829 ext4_group_t first_group, last_group;
4830 ext4_group_t group, ngroups = ext4_get_groups_count(sb);
4831 ext4_grpblk_t cnt = 0, first_block, last_block;
4832 uint64_t start, len, minlen, trimmed;
4833 ext4_fsblk_t first_data_blk =
4834 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
4835 int ret = 0;
4837 start = range->start >> sb->s_blocksize_bits;
4838 len = range->len >> sb->s_blocksize_bits;
4839 minlen = range->minlen >> sb->s_blocksize_bits;
4840 trimmed = 0;
4842 if (unlikely(minlen > EXT4_BLOCKS_PER_GROUP(sb)))
4843 return -EINVAL;
4844 if (start < first_data_blk) {
4845 len -= first_data_blk - start;
4846 start = first_data_blk;
4849 /* Determine first and last group to examine based on start and len */
4850 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
4851 &first_group, &first_block);
4852 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) (start + len),
4853 &last_group, &last_block);
4854 last_group = (last_group > ngroups - 1) ? ngroups - 1 : last_group;
4855 last_block = EXT4_BLOCKS_PER_GROUP(sb);
4857 if (first_group > last_group)
4858 return -EINVAL;
4860 for (group = first_group; group <= last_group; group++) {
4861 ret = ext4_mb_load_buddy(sb, group, &e4b);
4862 if (ret) {
4863 ext4_error(sb, "Error in loading buddy "
4864 "information for %u", group);
4865 break;
4868 if (len >= EXT4_BLOCKS_PER_GROUP(sb))
4869 len -= (EXT4_BLOCKS_PER_GROUP(sb) - first_block);
4870 else
4871 last_block = first_block + len;
4873 if (e4b.bd_info->bb_free >= minlen) {
4874 cnt = ext4_trim_all_free(sb, &e4b, first_block,
4875 last_block, minlen);
4876 if (cnt < 0) {
4877 ret = cnt;
4878 ext4_mb_unload_buddy(&e4b);
4879 break;
4882 ext4_mb_unload_buddy(&e4b);
4883 trimmed += cnt;
4884 first_block = 0;
4886 range->len = trimmed * sb->s_blocksize;
4888 return ret;