mm: fix exec activate_mm vs TLB shootdown and lazy tlb switching race
[linux/fpc-iii.git] / fs / ext4 / mballoc.c
blobd7cedfaa1cc08b7ef239b67e268c8634345caebb
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 License
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 "ext4_jbd2.h"
25 #include "mballoc.h"
26 #include <linux/log2.h>
27 #include <linux/module.h>
28 #include <linux/slab.h>
29 #include <linux/nospec.h>
30 #include <linux/backing-dev.h>
31 #include <trace/events/ext4.h>
33 #ifdef CONFIG_EXT4_DEBUG
34 ushort ext4_mballoc_debug __read_mostly;
36 module_param_named(mballoc_debug, ext4_mballoc_debug, ushort, 0644);
37 MODULE_PARM_DESC(mballoc_debug, "Debugging level for ext4's mballoc");
38 #endif
41 * MUSTDO:
42 * - test ext4_ext_search_left() and ext4_ext_search_right()
43 * - search for metadata in few groups
45 * TODO v4:
46 * - normalization should take into account whether file is still open
47 * - discard preallocations if no free space left (policy?)
48 * - don't normalize tails
49 * - quota
50 * - reservation for superuser
52 * TODO v3:
53 * - bitmap read-ahead (proposed by Oleg Drokin aka green)
54 * - track min/max extents in each group for better group selection
55 * - mb_mark_used() may allocate chunk right after splitting buddy
56 * - tree of groups sorted by number of free blocks
57 * - error handling
61 * The allocation request involve request for multiple number of blocks
62 * near to the goal(block) value specified.
64 * During initialization phase of the allocator we decide to use the
65 * group preallocation or inode preallocation depending on the size of
66 * the file. The size of the file could be the resulting file size we
67 * would have after allocation, or the current file size, which ever
68 * is larger. If the size is less than sbi->s_mb_stream_request we
69 * select to use the group preallocation. The default value of
70 * s_mb_stream_request is 16 blocks. This can also be tuned via
71 * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
72 * terms of number of blocks.
74 * The main motivation for having small file use group preallocation is to
75 * ensure that we have small files closer together on the disk.
77 * First stage the allocator looks at the inode prealloc list,
78 * ext4_inode_info->i_prealloc_list, which contains list of prealloc
79 * spaces for this particular inode. The inode prealloc space is
80 * represented as:
82 * pa_lstart -> the logical start block for this prealloc space
83 * pa_pstart -> the physical start block for this prealloc space
84 * pa_len -> length for this prealloc space (in clusters)
85 * pa_free -> free space available in this prealloc space (in clusters)
87 * The inode preallocation space is used looking at the _logical_ start
88 * block. If only the logical file block falls within the range of prealloc
89 * space we will consume the particular prealloc space. This makes sure that
90 * we have contiguous physical blocks representing the file blocks
92 * The important thing to be noted in case of inode prealloc space is that
93 * we don't modify the values associated to inode prealloc space except
94 * pa_free.
96 * If we are not able to find blocks in the inode prealloc space and if we
97 * have the group allocation flag set then we look at the locality group
98 * prealloc space. These are per CPU prealloc list represented as
100 * ext4_sb_info.s_locality_groups[smp_processor_id()]
102 * The reason for having a per cpu locality group is to reduce the contention
103 * between CPUs. It is possible to get scheduled at this point.
105 * The locality group prealloc space is used looking at whether we have
106 * enough free space (pa_free) within the prealloc space.
108 * If we can't allocate blocks via inode prealloc or/and locality group
109 * prealloc then we look at the buddy cache. The buddy cache is represented
110 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
111 * mapped to the buddy and bitmap information regarding different
112 * groups. The buddy information is attached to buddy cache inode so that
113 * we can access them through the page cache. The information regarding
114 * each group is loaded via ext4_mb_load_buddy. The information involve
115 * block bitmap and buddy information. The information are stored in the
116 * inode as:
118 * { page }
119 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
122 * one block each for bitmap and buddy information. So for each group we
123 * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
124 * blocksize) blocks. So it can have information regarding groups_per_page
125 * which is blocks_per_page/2
127 * The buddy cache inode is not stored on disk. The inode is thrown
128 * away when the filesystem is unmounted.
130 * We look for count number of blocks in the buddy cache. If we were able
131 * to locate that many free blocks we return with additional information
132 * regarding rest of the contiguous physical block available
134 * Before allocating blocks via buddy cache we normalize the request
135 * blocks. This ensure we ask for more blocks that we needed. The extra
136 * blocks that we get after allocation is added to the respective prealloc
137 * list. In case of inode preallocation we follow a list of heuristics
138 * based on file size. This can be found in ext4_mb_normalize_request. If
139 * we are doing a group prealloc we try to normalize the request to
140 * sbi->s_mb_group_prealloc. The default value of s_mb_group_prealloc is
141 * dependent on the cluster size; for non-bigalloc file systems, it is
142 * 512 blocks. This can be tuned via
143 * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
144 * terms of number of blocks. If we have mounted the file system with -O
145 * stripe=<value> option the group prealloc request is normalized to the
146 * the smallest multiple of the stripe value (sbi->s_stripe) which is
147 * greater than the default mb_group_prealloc.
149 * The regular allocator (using the buddy cache) supports a few tunables.
151 * /sys/fs/ext4/<partition>/mb_min_to_scan
152 * /sys/fs/ext4/<partition>/mb_max_to_scan
153 * /sys/fs/ext4/<partition>/mb_order2_req
155 * The regular allocator uses buddy scan only if the request len is power of
156 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
157 * value of s_mb_order2_reqs can be tuned via
158 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
159 * stripe size (sbi->s_stripe), we try to search for contiguous block in
160 * stripe size. This should result in better allocation on RAID setups. If
161 * not, we search in the specific group using bitmap for best extents. The
162 * tunable min_to_scan and max_to_scan control the behaviour here.
163 * min_to_scan indicate how long the mballoc __must__ look for a best
164 * extent and max_to_scan indicates how long the mballoc __can__ look for a
165 * best extent in the found extents. Searching for the blocks starts with
166 * the group specified as the goal value in allocation context via
167 * ac_g_ex. Each group is first checked based on the criteria whether it
168 * can be used for allocation. ext4_mb_good_group explains how the groups are
169 * checked.
171 * Both the prealloc space are getting populated as above. So for the first
172 * request we will hit the buddy cache which will result in this prealloc
173 * space getting filled. The prealloc space is then later used for the
174 * subsequent request.
178 * mballoc operates on the following data:
179 * - on-disk bitmap
180 * - in-core buddy (actually includes buddy and bitmap)
181 * - preallocation descriptors (PAs)
183 * there are two types of preallocations:
184 * - inode
185 * assiged to specific inode and can be used for this inode only.
186 * it describes part of inode's space preallocated to specific
187 * physical blocks. any block from that preallocated can be used
188 * independent. the descriptor just tracks number of blocks left
189 * unused. so, before taking some block from descriptor, one must
190 * make sure corresponded logical block isn't allocated yet. this
191 * also means that freeing any block within descriptor's range
192 * must discard all preallocated blocks.
193 * - locality group
194 * assigned to specific locality group which does not translate to
195 * permanent set of inodes: inode can join and leave group. space
196 * from this type of preallocation can be used for any inode. thus
197 * it's consumed from the beginning to the end.
199 * relation between them can be expressed as:
200 * in-core buddy = on-disk bitmap + preallocation descriptors
202 * this mean blocks mballoc considers used are:
203 * - allocated blocks (persistent)
204 * - preallocated blocks (non-persistent)
206 * consistency in mballoc world means that at any time a block is either
207 * free or used in ALL structures. notice: "any time" should not be read
208 * literally -- time is discrete and delimited by locks.
210 * to keep it simple, we don't use block numbers, instead we count number of
211 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
213 * all operations can be expressed as:
214 * - init buddy: buddy = on-disk + PAs
215 * - new PA: buddy += N; PA = N
216 * - use inode PA: on-disk += N; PA -= N
217 * - discard inode PA buddy -= on-disk - PA; PA = 0
218 * - use locality group PA on-disk += N; PA -= N
219 * - discard locality group PA buddy -= PA; PA = 0
220 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
221 * is used in real operation because we can't know actual used
222 * bits from PA, only from on-disk bitmap
224 * if we follow this strict logic, then all operations above should be atomic.
225 * given some of them can block, we'd have to use something like semaphores
226 * killing performance on high-end SMP hardware. let's try to relax it using
227 * the following knowledge:
228 * 1) if buddy is referenced, it's already initialized
229 * 2) while block is used in buddy and the buddy is referenced,
230 * nobody can re-allocate that block
231 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
232 * bit set and PA claims same block, it's OK. IOW, one can set bit in
233 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
234 * block
236 * so, now we're building a concurrency table:
237 * - init buddy vs.
238 * - new PA
239 * blocks for PA are allocated in the buddy, buddy must be referenced
240 * until PA is linked to allocation group to avoid concurrent buddy init
241 * - use inode PA
242 * we need to make sure that either on-disk bitmap or PA has uptodate data
243 * given (3) we care that PA-=N operation doesn't interfere with init
244 * - discard inode PA
245 * the simplest way would be to have buddy initialized by the discard
246 * - use locality group PA
247 * again PA-=N must be serialized with init
248 * - discard locality group PA
249 * the simplest way would be to have buddy initialized by the discard
250 * - new PA vs.
251 * - use inode PA
252 * i_data_sem serializes them
253 * - discard inode PA
254 * discard process must wait until PA isn't used by another process
255 * - use locality group PA
256 * some mutex should serialize them
257 * - discard locality group PA
258 * discard process must wait until PA isn't used by another process
259 * - use inode PA
260 * - use inode PA
261 * i_data_sem or another mutex should serializes them
262 * - discard inode PA
263 * discard process must wait until PA isn't used by another process
264 * - use locality group PA
265 * nothing wrong here -- they're different PAs covering different blocks
266 * - discard locality group PA
267 * discard process must wait until PA isn't used by another process
269 * now we're ready to make few consequences:
270 * - PA is referenced and while it is no discard is possible
271 * - PA is referenced until block isn't marked in on-disk bitmap
272 * - PA changes only after on-disk bitmap
273 * - discard must not compete with init. either init is done before
274 * any discard or they're serialized somehow
275 * - buddy init as sum of on-disk bitmap and PAs is done atomically
277 * a special case when we've used PA to emptiness. no need to modify buddy
278 * in this case, but we should care about concurrent init
283 * Logic in few words:
285 * - allocation:
286 * load group
287 * find blocks
288 * mark bits in on-disk bitmap
289 * release group
291 * - use preallocation:
292 * find proper PA (per-inode or group)
293 * load group
294 * mark bits in on-disk bitmap
295 * release group
296 * release PA
298 * - free:
299 * load group
300 * mark bits in on-disk bitmap
301 * release group
303 * - discard preallocations in group:
304 * mark PAs deleted
305 * move them onto local list
306 * load on-disk bitmap
307 * load group
308 * remove PA from object (inode or locality group)
309 * mark free blocks in-core
311 * - discard inode's preallocations:
315 * Locking rules
317 * Locks:
318 * - bitlock on a group (group)
319 * - object (inode/locality) (object)
320 * - per-pa lock (pa)
322 * Paths:
323 * - new pa
324 * object
325 * group
327 * - find and use pa:
328 * pa
330 * - release consumed pa:
331 * pa
332 * group
333 * object
335 * - generate in-core bitmap:
336 * group
337 * pa
339 * - discard all for given object (inode, locality group):
340 * object
341 * pa
342 * group
344 * - discard all for given group:
345 * group
346 * pa
347 * group
348 * object
351 static struct kmem_cache *ext4_pspace_cachep;
352 static struct kmem_cache *ext4_ac_cachep;
353 static struct kmem_cache *ext4_free_data_cachep;
355 /* We create slab caches for groupinfo data structures based on the
356 * superblock block size. There will be one per mounted filesystem for
357 * each unique s_blocksize_bits */
358 #define NR_GRPINFO_CACHES 8
359 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
361 static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
362 "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
363 "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
364 "ext4_groupinfo_64k", "ext4_groupinfo_128k"
367 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
368 ext4_group_t group);
369 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
370 ext4_group_t group);
372 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
374 #if BITS_PER_LONG == 64
375 *bit += ((unsigned long) addr & 7UL) << 3;
376 addr = (void *) ((unsigned long) addr & ~7UL);
377 #elif BITS_PER_LONG == 32
378 *bit += ((unsigned long) addr & 3UL) << 3;
379 addr = (void *) ((unsigned long) addr & ~3UL);
380 #else
381 #error "how many bits you are?!"
382 #endif
383 return addr;
386 static inline int mb_test_bit(int bit, void *addr)
389 * ext4_test_bit on architecture like powerpc
390 * needs unsigned long aligned address
392 addr = mb_correct_addr_and_bit(&bit, addr);
393 return ext4_test_bit(bit, addr);
396 static inline void mb_set_bit(int bit, void *addr)
398 addr = mb_correct_addr_and_bit(&bit, addr);
399 ext4_set_bit(bit, addr);
402 static inline void mb_clear_bit(int bit, void *addr)
404 addr = mb_correct_addr_and_bit(&bit, addr);
405 ext4_clear_bit(bit, addr);
408 static inline int mb_test_and_clear_bit(int bit, void *addr)
410 addr = mb_correct_addr_and_bit(&bit, addr);
411 return ext4_test_and_clear_bit(bit, addr);
414 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
416 int fix = 0, ret, tmpmax;
417 addr = mb_correct_addr_and_bit(&fix, addr);
418 tmpmax = max + fix;
419 start += fix;
421 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
422 if (ret > max)
423 return max;
424 return ret;
427 static inline int mb_find_next_bit(void *addr, int max, int start)
429 int fix = 0, ret, tmpmax;
430 addr = mb_correct_addr_and_bit(&fix, addr);
431 tmpmax = max + fix;
432 start += fix;
434 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
435 if (ret > max)
436 return max;
437 return ret;
440 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
442 char *bb;
444 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
445 BUG_ON(max == NULL);
447 if (order > e4b->bd_blkbits + 1) {
448 *max = 0;
449 return NULL;
452 /* at order 0 we see each particular block */
453 if (order == 0) {
454 *max = 1 << (e4b->bd_blkbits + 3);
455 return e4b->bd_bitmap;
458 bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
459 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
461 return bb;
464 #ifdef DOUBLE_CHECK
465 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
466 int first, int count)
468 int i;
469 struct super_block *sb = e4b->bd_sb;
471 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
472 return;
473 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
474 for (i = 0; i < count; i++) {
475 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
476 ext4_fsblk_t blocknr;
478 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
479 blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
480 ext4_grp_locked_error(sb, e4b->bd_group,
481 inode ? inode->i_ino : 0,
482 blocknr,
483 "freeing block already freed "
484 "(bit %u)",
485 first + i);
487 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
491 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
493 int i;
495 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
496 return;
497 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
498 for (i = 0; i < count; i++) {
499 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
500 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
504 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
506 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
507 unsigned char *b1, *b2;
508 int i;
509 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
510 b2 = (unsigned char *) bitmap;
511 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
512 if (b1[i] != b2[i]) {
513 ext4_msg(e4b->bd_sb, KERN_ERR,
514 "corruption in group %u "
515 "at byte %u(%u): %x in copy != %x "
516 "on disk/prealloc",
517 e4b->bd_group, i, i * 8, b1[i], b2[i]);
518 BUG();
524 #else
525 static inline void mb_free_blocks_double(struct inode *inode,
526 struct ext4_buddy *e4b, int first, int count)
528 return;
530 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
531 int first, int count)
533 return;
535 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
537 return;
539 #endif
541 #ifdef AGGRESSIVE_CHECK
543 #define MB_CHECK_ASSERT(assert) \
544 do { \
545 if (!(assert)) { \
546 printk(KERN_EMERG \
547 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
548 function, file, line, # assert); \
549 BUG(); \
551 } while (0)
553 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
554 const char *function, int line)
556 struct super_block *sb = e4b->bd_sb;
557 int order = e4b->bd_blkbits + 1;
558 int max;
559 int max2;
560 int i;
561 int j;
562 int k;
563 int count;
564 struct ext4_group_info *grp;
565 int fragments = 0;
566 int fstart;
567 struct list_head *cur;
568 void *buddy;
569 void *buddy2;
572 static int mb_check_counter;
573 if (mb_check_counter++ % 100 != 0)
574 return 0;
577 while (order > 1) {
578 buddy = mb_find_buddy(e4b, order, &max);
579 MB_CHECK_ASSERT(buddy);
580 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
581 MB_CHECK_ASSERT(buddy2);
582 MB_CHECK_ASSERT(buddy != buddy2);
583 MB_CHECK_ASSERT(max * 2 == max2);
585 count = 0;
586 for (i = 0; i < max; i++) {
588 if (mb_test_bit(i, buddy)) {
589 /* only single bit in buddy2 may be 1 */
590 if (!mb_test_bit(i << 1, buddy2)) {
591 MB_CHECK_ASSERT(
592 mb_test_bit((i<<1)+1, buddy2));
593 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
594 MB_CHECK_ASSERT(
595 mb_test_bit(i << 1, buddy2));
597 continue;
600 /* both bits in buddy2 must be 1 */
601 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
602 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
604 for (j = 0; j < (1 << order); j++) {
605 k = (i * (1 << order)) + j;
606 MB_CHECK_ASSERT(
607 !mb_test_bit(k, e4b->bd_bitmap));
609 count++;
611 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
612 order--;
615 fstart = -1;
616 buddy = mb_find_buddy(e4b, 0, &max);
617 for (i = 0; i < max; i++) {
618 if (!mb_test_bit(i, buddy)) {
619 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
620 if (fstart == -1) {
621 fragments++;
622 fstart = i;
624 continue;
626 fstart = -1;
627 /* check used bits only */
628 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
629 buddy2 = mb_find_buddy(e4b, j, &max2);
630 k = i >> j;
631 MB_CHECK_ASSERT(k < max2);
632 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
635 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
636 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
638 grp = ext4_get_group_info(sb, e4b->bd_group);
639 list_for_each(cur, &grp->bb_prealloc_list) {
640 ext4_group_t groupnr;
641 struct ext4_prealloc_space *pa;
642 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
643 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
644 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
645 for (i = 0; i < pa->pa_len; i++)
646 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
648 return 0;
650 #undef MB_CHECK_ASSERT
651 #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
652 __FILE__, __func__, __LINE__)
653 #else
654 #define mb_check_buddy(e4b)
655 #endif
658 * Divide blocks started from @first with length @len into
659 * smaller chunks with power of 2 blocks.
660 * Clear the bits in bitmap which the blocks of the chunk(s) covered,
661 * then increase bb_counters[] for corresponded chunk size.
663 static void ext4_mb_mark_free_simple(struct super_block *sb,
664 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
665 struct ext4_group_info *grp)
667 struct ext4_sb_info *sbi = EXT4_SB(sb);
668 ext4_grpblk_t min;
669 ext4_grpblk_t max;
670 ext4_grpblk_t chunk;
671 unsigned int border;
673 BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
675 border = 2 << sb->s_blocksize_bits;
677 while (len > 0) {
678 /* find how many blocks can be covered since this position */
679 max = ffs(first | border) - 1;
681 /* find how many blocks of power 2 we need to mark */
682 min = fls(len) - 1;
684 if (max < min)
685 min = max;
686 chunk = 1 << min;
688 /* mark multiblock chunks only */
689 grp->bb_counters[min]++;
690 if (min > 0)
691 mb_clear_bit(first >> min,
692 buddy + sbi->s_mb_offsets[min]);
694 len -= chunk;
695 first += chunk;
700 * Cache the order of the largest free extent we have available in this block
701 * group.
703 static void
704 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
706 int i;
707 int bits;
709 grp->bb_largest_free_order = -1; /* uninit */
711 bits = sb->s_blocksize_bits + 1;
712 for (i = bits; i >= 0; i--) {
713 if (grp->bb_counters[i] > 0) {
714 grp->bb_largest_free_order = i;
715 break;
720 static noinline_for_stack
721 void ext4_mb_generate_buddy(struct super_block *sb,
722 void *buddy, void *bitmap, ext4_group_t group)
724 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
725 struct ext4_sb_info *sbi = EXT4_SB(sb);
726 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
727 ext4_grpblk_t i = 0;
728 ext4_grpblk_t first;
729 ext4_grpblk_t len;
730 unsigned free = 0;
731 unsigned fragments = 0;
732 unsigned long long period = get_cycles();
734 /* initialize buddy from bitmap which is aggregation
735 * of on-disk bitmap and preallocations */
736 i = mb_find_next_zero_bit(bitmap, max, 0);
737 grp->bb_first_free = i;
738 while (i < max) {
739 fragments++;
740 first = i;
741 i = mb_find_next_bit(bitmap, max, i);
742 len = i - first;
743 free += len;
744 if (len > 1)
745 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
746 else
747 grp->bb_counters[0]++;
748 if (i < max)
749 i = mb_find_next_zero_bit(bitmap, max, i);
751 grp->bb_fragments = fragments;
753 if (free != grp->bb_free) {
754 ext4_grp_locked_error(sb, group, 0, 0,
755 "block bitmap and bg descriptor "
756 "inconsistent: %u vs %u free clusters",
757 free, grp->bb_free);
759 * If we intend to continue, we consider group descriptor
760 * corrupt and update bb_free using bitmap value
762 grp->bb_free = free;
763 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
764 percpu_counter_sub(&sbi->s_freeclusters_counter,
765 grp->bb_free);
766 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT, &grp->bb_state);
768 mb_set_largest_free_order(sb, grp);
770 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
772 period = get_cycles() - period;
773 spin_lock(&EXT4_SB(sb)->s_bal_lock);
774 EXT4_SB(sb)->s_mb_buddies_generated++;
775 EXT4_SB(sb)->s_mb_generation_time += period;
776 spin_unlock(&EXT4_SB(sb)->s_bal_lock);
779 static void mb_regenerate_buddy(struct ext4_buddy *e4b)
781 int count;
782 int order = 1;
783 void *buddy;
785 while ((buddy = mb_find_buddy(e4b, order++, &count))) {
786 ext4_set_bits(buddy, 0, count);
788 e4b->bd_info->bb_fragments = 0;
789 memset(e4b->bd_info->bb_counters, 0,
790 sizeof(*e4b->bd_info->bb_counters) *
791 (e4b->bd_sb->s_blocksize_bits + 2));
793 ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
794 e4b->bd_bitmap, e4b->bd_group);
797 /* The buddy information is attached the buddy cache inode
798 * for convenience. The information regarding each group
799 * is loaded via ext4_mb_load_buddy. The information involve
800 * block bitmap and buddy information. The information are
801 * stored in the inode as
803 * { page }
804 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
807 * one block each for bitmap and buddy information.
808 * So for each group we take up 2 blocks. A page can
809 * contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
810 * So it can have information regarding groups_per_page which
811 * is blocks_per_page/2
813 * Locking note: This routine takes the block group lock of all groups
814 * for this page; do not hold this lock when calling this routine!
817 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
819 ext4_group_t ngroups;
820 int blocksize;
821 int blocks_per_page;
822 int groups_per_page;
823 int err = 0;
824 int i;
825 ext4_group_t first_group, group;
826 int first_block;
827 struct super_block *sb;
828 struct buffer_head *bhs;
829 struct buffer_head **bh = NULL;
830 struct inode *inode;
831 char *data;
832 char *bitmap;
833 struct ext4_group_info *grinfo;
835 mb_debug(1, "init page %lu\n", page->index);
837 inode = page->mapping->host;
838 sb = inode->i_sb;
839 ngroups = ext4_get_groups_count(sb);
840 blocksize = i_blocksize(inode);
841 blocks_per_page = PAGE_SIZE / blocksize;
843 groups_per_page = blocks_per_page >> 1;
844 if (groups_per_page == 0)
845 groups_per_page = 1;
847 /* allocate buffer_heads to read bitmaps */
848 if (groups_per_page > 1) {
849 i = sizeof(struct buffer_head *) * groups_per_page;
850 bh = kzalloc(i, gfp);
851 if (bh == NULL) {
852 err = -ENOMEM;
853 goto out;
855 } else
856 bh = &bhs;
858 first_group = page->index * blocks_per_page / 2;
860 /* read all groups the page covers into the cache */
861 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
862 if (group >= ngroups)
863 break;
865 grinfo = ext4_get_group_info(sb, group);
867 * If page is uptodate then we came here after online resize
868 * which added some new uninitialized group info structs, so
869 * we must skip all initialized uptodate buddies on the page,
870 * which may be currently in use by an allocating task.
872 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
873 bh[i] = NULL;
874 continue;
876 bh[i] = ext4_read_block_bitmap_nowait(sb, group);
877 if (IS_ERR(bh[i])) {
878 err = PTR_ERR(bh[i]);
879 bh[i] = NULL;
880 goto out;
882 mb_debug(1, "read bitmap for group %u\n", group);
885 /* wait for I/O completion */
886 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
887 int err2;
889 if (!bh[i])
890 continue;
891 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
892 if (!err)
893 err = err2;
896 first_block = page->index * blocks_per_page;
897 for (i = 0; i < blocks_per_page; i++) {
898 group = (first_block + i) >> 1;
899 if (group >= ngroups)
900 break;
902 if (!bh[group - first_group])
903 /* skip initialized uptodate buddy */
904 continue;
906 if (!buffer_verified(bh[group - first_group]))
907 /* Skip faulty bitmaps */
908 continue;
909 err = 0;
912 * data carry information regarding this
913 * particular group in the format specified
914 * above
917 data = page_address(page) + (i * blocksize);
918 bitmap = bh[group - first_group]->b_data;
921 * We place the buddy block and bitmap block
922 * close together
924 if ((first_block + i) & 1) {
925 /* this is block of buddy */
926 BUG_ON(incore == NULL);
927 mb_debug(1, "put buddy for group %u in page %lu/%x\n",
928 group, page->index, i * blocksize);
929 trace_ext4_mb_buddy_bitmap_load(sb, group);
930 grinfo = ext4_get_group_info(sb, group);
931 grinfo->bb_fragments = 0;
932 memset(grinfo->bb_counters, 0,
933 sizeof(*grinfo->bb_counters) *
934 (sb->s_blocksize_bits+2));
936 * incore got set to the group block bitmap below
938 ext4_lock_group(sb, group);
939 /* init the buddy */
940 memset(data, 0xff, blocksize);
941 ext4_mb_generate_buddy(sb, data, incore, group);
942 ext4_unlock_group(sb, group);
943 incore = NULL;
944 } else {
945 /* this is block of bitmap */
946 BUG_ON(incore != NULL);
947 mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
948 group, page->index, i * blocksize);
949 trace_ext4_mb_bitmap_load(sb, group);
951 /* see comments in ext4_mb_put_pa() */
952 ext4_lock_group(sb, group);
953 memcpy(data, bitmap, blocksize);
955 /* mark all preallocated blks used in in-core bitmap */
956 ext4_mb_generate_from_pa(sb, data, group);
957 ext4_mb_generate_from_freelist(sb, data, group);
958 ext4_unlock_group(sb, group);
960 /* set incore so that the buddy information can be
961 * generated using this
963 incore = data;
966 SetPageUptodate(page);
968 out:
969 if (bh) {
970 for (i = 0; i < groups_per_page; i++)
971 brelse(bh[i]);
972 if (bh != &bhs)
973 kfree(bh);
975 return err;
979 * Lock the buddy and bitmap pages. This make sure other parallel init_group
980 * on the same buddy page doesn't happen whild holding the buddy page lock.
981 * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
982 * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
984 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
985 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
987 struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
988 int block, pnum, poff;
989 int blocks_per_page;
990 struct page *page;
992 e4b->bd_buddy_page = NULL;
993 e4b->bd_bitmap_page = NULL;
995 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
997 * the buddy cache inode stores the block bitmap
998 * and buddy information in consecutive blocks.
999 * So for each group we need two blocks.
1001 block = group * 2;
1002 pnum = block / blocks_per_page;
1003 poff = block % blocks_per_page;
1004 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1005 if (!page)
1006 return -ENOMEM;
1007 BUG_ON(page->mapping != inode->i_mapping);
1008 e4b->bd_bitmap_page = page;
1009 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1011 if (blocks_per_page >= 2) {
1012 /* buddy and bitmap are on the same page */
1013 return 0;
1016 block++;
1017 pnum = block / blocks_per_page;
1018 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1019 if (!page)
1020 return -ENOMEM;
1021 BUG_ON(page->mapping != inode->i_mapping);
1022 e4b->bd_buddy_page = page;
1023 return 0;
1026 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1028 if (e4b->bd_bitmap_page) {
1029 unlock_page(e4b->bd_bitmap_page);
1030 put_page(e4b->bd_bitmap_page);
1032 if (e4b->bd_buddy_page) {
1033 unlock_page(e4b->bd_buddy_page);
1034 put_page(e4b->bd_buddy_page);
1039 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1040 * block group lock of all groups for this page; do not hold the BG lock when
1041 * calling this routine!
1043 static noinline_for_stack
1044 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1047 struct ext4_group_info *this_grp;
1048 struct ext4_buddy e4b;
1049 struct page *page;
1050 int ret = 0;
1052 might_sleep();
1053 mb_debug(1, "init group %u\n", group);
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 pinned buddy page to page cache.
1061 * The call to ext4_mb_get_buddy_page_lock will mark the
1062 * page accessed.
1064 ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1065 if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1067 * somebody initialized the group
1068 * return without doing anything
1070 goto err;
1073 page = e4b.bd_bitmap_page;
1074 ret = ext4_mb_init_cache(page, NULL, gfp);
1075 if (ret)
1076 goto err;
1077 if (!PageUptodate(page)) {
1078 ret = -EIO;
1079 goto err;
1082 if (e4b.bd_buddy_page == NULL) {
1084 * If both the bitmap and buddy are in
1085 * the same page we don't need to force
1086 * init the buddy
1088 ret = 0;
1089 goto err;
1091 /* init buddy cache */
1092 page = e4b.bd_buddy_page;
1093 ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1094 if (ret)
1095 goto err;
1096 if (!PageUptodate(page)) {
1097 ret = -EIO;
1098 goto err;
1100 err:
1101 ext4_mb_put_buddy_page_lock(&e4b);
1102 return ret;
1106 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1107 * block group lock of all groups for this page; do not hold the BG lock when
1108 * calling this routine!
1110 static noinline_for_stack int
1111 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1112 struct ext4_buddy *e4b, gfp_t gfp)
1114 int blocks_per_page;
1115 int block;
1116 int pnum;
1117 int poff;
1118 struct page *page;
1119 int ret;
1120 struct ext4_group_info *grp;
1121 struct ext4_sb_info *sbi = EXT4_SB(sb);
1122 struct inode *inode = sbi->s_buddy_cache;
1124 might_sleep();
1125 mb_debug(1, "load group %u\n", group);
1127 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1128 grp = ext4_get_group_info(sb, group);
1130 e4b->bd_blkbits = sb->s_blocksize_bits;
1131 e4b->bd_info = grp;
1132 e4b->bd_sb = sb;
1133 e4b->bd_group = group;
1134 e4b->bd_buddy_page = NULL;
1135 e4b->bd_bitmap_page = NULL;
1137 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1139 * we need full data about the group
1140 * to make a good selection
1142 ret = ext4_mb_init_group(sb, group, gfp);
1143 if (ret)
1144 return ret;
1148 * the buddy cache inode stores the block bitmap
1149 * and buddy information in consecutive blocks.
1150 * So for each group we need two blocks.
1152 block = group * 2;
1153 pnum = block / blocks_per_page;
1154 poff = block % blocks_per_page;
1156 /* we could use find_or_create_page(), but it locks page
1157 * what we'd like to avoid in fast path ... */
1158 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1159 if (page == NULL || !PageUptodate(page)) {
1160 if (page)
1162 * drop the page reference and try
1163 * to get the page with lock. If we
1164 * are not uptodate that implies
1165 * somebody just created the page but
1166 * is yet to initialize the same. So
1167 * wait for it to initialize.
1169 put_page(page);
1170 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1171 if (page) {
1172 BUG_ON(page->mapping != inode->i_mapping);
1173 if (!PageUptodate(page)) {
1174 ret = ext4_mb_init_cache(page, NULL, gfp);
1175 if (ret) {
1176 unlock_page(page);
1177 goto err;
1179 mb_cmp_bitmaps(e4b, page_address(page) +
1180 (poff * sb->s_blocksize));
1182 unlock_page(page);
1185 if (page == NULL) {
1186 ret = -ENOMEM;
1187 goto err;
1189 if (!PageUptodate(page)) {
1190 ret = -EIO;
1191 goto err;
1194 /* Pages marked accessed already */
1195 e4b->bd_bitmap_page = page;
1196 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1198 block++;
1199 pnum = block / blocks_per_page;
1200 poff = block % blocks_per_page;
1202 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1203 if (page == NULL || !PageUptodate(page)) {
1204 if (page)
1205 put_page(page);
1206 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1207 if (page) {
1208 BUG_ON(page->mapping != inode->i_mapping);
1209 if (!PageUptodate(page)) {
1210 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1211 gfp);
1212 if (ret) {
1213 unlock_page(page);
1214 goto err;
1217 unlock_page(page);
1220 if (page == NULL) {
1221 ret = -ENOMEM;
1222 goto err;
1224 if (!PageUptodate(page)) {
1225 ret = -EIO;
1226 goto err;
1229 /* Pages marked accessed already */
1230 e4b->bd_buddy_page = page;
1231 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1233 BUG_ON(e4b->bd_bitmap_page == NULL);
1234 BUG_ON(e4b->bd_buddy_page == NULL);
1236 return 0;
1238 err:
1239 if (page)
1240 put_page(page);
1241 if (e4b->bd_bitmap_page)
1242 put_page(e4b->bd_bitmap_page);
1243 if (e4b->bd_buddy_page)
1244 put_page(e4b->bd_buddy_page);
1245 e4b->bd_buddy = NULL;
1246 e4b->bd_bitmap = NULL;
1247 return ret;
1250 static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1251 struct ext4_buddy *e4b)
1253 return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1256 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1258 if (e4b->bd_bitmap_page)
1259 put_page(e4b->bd_bitmap_page);
1260 if (e4b->bd_buddy_page)
1261 put_page(e4b->bd_buddy_page);
1265 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1267 int order = 1;
1268 int bb_incr = 1 << (e4b->bd_blkbits - 1);
1269 void *bb;
1271 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1272 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1274 bb = e4b->bd_buddy;
1275 while (order <= e4b->bd_blkbits + 1) {
1276 block = block >> 1;
1277 if (!mb_test_bit(block, bb)) {
1278 /* this block is part of buddy of order 'order' */
1279 return order;
1281 bb += bb_incr;
1282 bb_incr >>= 1;
1283 order++;
1285 return 0;
1288 static void mb_clear_bits(void *bm, int cur, int len)
1290 __u32 *addr;
1292 len = cur + len;
1293 while (cur < len) {
1294 if ((cur & 31) == 0 && (len - cur) >= 32) {
1295 /* fast path: clear whole word at once */
1296 addr = bm + (cur >> 3);
1297 *addr = 0;
1298 cur += 32;
1299 continue;
1301 mb_clear_bit(cur, bm);
1302 cur++;
1306 /* clear bits in given range
1307 * will return first found zero bit if any, -1 otherwise
1309 static int mb_test_and_clear_bits(void *bm, int cur, int len)
1311 __u32 *addr;
1312 int zero_bit = -1;
1314 len = cur + len;
1315 while (cur < len) {
1316 if ((cur & 31) == 0 && (len - cur) >= 32) {
1317 /* fast path: clear whole word at once */
1318 addr = bm + (cur >> 3);
1319 if (*addr != (__u32)(-1) && zero_bit == -1)
1320 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1321 *addr = 0;
1322 cur += 32;
1323 continue;
1325 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1326 zero_bit = cur;
1327 cur++;
1330 return zero_bit;
1333 void ext4_set_bits(void *bm, int cur, int len)
1335 __u32 *addr;
1337 len = cur + len;
1338 while (cur < len) {
1339 if ((cur & 31) == 0 && (len - cur) >= 32) {
1340 /* fast path: set whole word at once */
1341 addr = bm + (cur >> 3);
1342 *addr = 0xffffffff;
1343 cur += 32;
1344 continue;
1346 mb_set_bit(cur, bm);
1347 cur++;
1352 * _________________________________________________________________ */
1354 static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1356 if (mb_test_bit(*bit + side, bitmap)) {
1357 mb_clear_bit(*bit, bitmap);
1358 (*bit) -= side;
1359 return 1;
1361 else {
1362 (*bit) += side;
1363 mb_set_bit(*bit, bitmap);
1364 return -1;
1368 static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1370 int max;
1371 int order = 1;
1372 void *buddy = mb_find_buddy(e4b, order, &max);
1374 while (buddy) {
1375 void *buddy2;
1377 /* Bits in range [first; last] are known to be set since
1378 * corresponding blocks were allocated. Bits in range
1379 * (first; last) will stay set because they form buddies on
1380 * upper layer. We just deal with borders if they don't
1381 * align with upper layer and then go up.
1382 * Releasing entire group is all about clearing
1383 * single bit of highest order buddy.
1386 /* Example:
1387 * ---------------------------------
1388 * | 1 | 1 | 1 | 1 |
1389 * ---------------------------------
1390 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1391 * ---------------------------------
1392 * 0 1 2 3 4 5 6 7
1393 * \_____________________/
1395 * Neither [1] nor [6] is aligned to above layer.
1396 * Left neighbour [0] is free, so mark it busy,
1397 * decrease bb_counters and extend range to
1398 * [0; 6]
1399 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1400 * mark [6] free, increase bb_counters and shrink range to
1401 * [0; 5].
1402 * Then shift range to [0; 2], go up and do the same.
1406 if (first & 1)
1407 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1408 if (!(last & 1))
1409 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1410 if (first > last)
1411 break;
1412 order++;
1414 if (first == last || !(buddy2 = mb_find_buddy(e4b, order, &max))) {
1415 mb_clear_bits(buddy, first, last - first + 1);
1416 e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1417 break;
1419 first >>= 1;
1420 last >>= 1;
1421 buddy = buddy2;
1425 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1426 int first, int count)
1428 int left_is_free = 0;
1429 int right_is_free = 0;
1430 int block;
1431 int last = first + count - 1;
1432 struct super_block *sb = e4b->bd_sb;
1434 if (WARN_ON(count == 0))
1435 return;
1436 BUG_ON(last >= (sb->s_blocksize << 3));
1437 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1438 /* Don't bother if the block group is corrupt. */
1439 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1440 return;
1442 mb_check_buddy(e4b);
1443 mb_free_blocks_double(inode, e4b, first, count);
1445 e4b->bd_info->bb_free += count;
1446 if (first < e4b->bd_info->bb_first_free)
1447 e4b->bd_info->bb_first_free = first;
1449 /* access memory sequentially: check left neighbour,
1450 * clear range and then check right neighbour
1452 if (first != 0)
1453 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1454 block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1455 if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1456 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1458 if (unlikely(block != -1)) {
1459 struct ext4_sb_info *sbi = EXT4_SB(sb);
1460 ext4_fsblk_t blocknr;
1462 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1463 blocknr += EXT4_C2B(EXT4_SB(sb), block);
1464 ext4_grp_locked_error(sb, e4b->bd_group,
1465 inode ? inode->i_ino : 0,
1466 blocknr,
1467 "freeing already freed block "
1468 "(bit %u); block bitmap corrupt.",
1469 block);
1470 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))
1471 percpu_counter_sub(&sbi->s_freeclusters_counter,
1472 e4b->bd_info->bb_free);
1473 /* Mark the block group as corrupt. */
1474 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT,
1475 &e4b->bd_info->bb_state);
1476 mb_regenerate_buddy(e4b);
1477 goto done;
1480 /* let's maintain fragments counter */
1481 if (left_is_free && right_is_free)
1482 e4b->bd_info->bb_fragments--;
1483 else if (!left_is_free && !right_is_free)
1484 e4b->bd_info->bb_fragments++;
1486 /* buddy[0] == bd_bitmap is a special case, so handle
1487 * it right away and let mb_buddy_mark_free stay free of
1488 * zero order checks.
1489 * Check if neighbours are to be coaleasced,
1490 * adjust bitmap bb_counters and borders appropriately.
1492 if (first & 1) {
1493 first += !left_is_free;
1494 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1496 if (!(last & 1)) {
1497 last -= !right_is_free;
1498 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1501 if (first <= last)
1502 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1504 done:
1505 mb_set_largest_free_order(sb, e4b->bd_info);
1506 mb_check_buddy(e4b);
1509 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1510 int needed, struct ext4_free_extent *ex)
1512 int next = block;
1513 int max, order;
1514 void *buddy;
1516 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1517 BUG_ON(ex == NULL);
1519 buddy = mb_find_buddy(e4b, 0, &max);
1520 BUG_ON(buddy == NULL);
1521 BUG_ON(block >= max);
1522 if (mb_test_bit(block, buddy)) {
1523 ex->fe_len = 0;
1524 ex->fe_start = 0;
1525 ex->fe_group = 0;
1526 return 0;
1529 /* find actual order */
1530 order = mb_find_order_for_block(e4b, block);
1531 block = block >> order;
1533 ex->fe_len = 1 << order;
1534 ex->fe_start = block << order;
1535 ex->fe_group = e4b->bd_group;
1537 /* calc difference from given start */
1538 next = next - ex->fe_start;
1539 ex->fe_len -= next;
1540 ex->fe_start += next;
1542 while (needed > ex->fe_len &&
1543 mb_find_buddy(e4b, order, &max)) {
1545 if (block + 1 >= max)
1546 break;
1548 next = (block + 1) * (1 << order);
1549 if (mb_test_bit(next, e4b->bd_bitmap))
1550 break;
1552 order = mb_find_order_for_block(e4b, next);
1554 block = next >> order;
1555 ex->fe_len += 1 << order;
1558 if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
1559 /* Should never happen! (but apparently sometimes does?!?) */
1560 WARN_ON(1);
1561 ext4_error(e4b->bd_sb, "corruption or bug in mb_find_extent "
1562 "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
1563 block, order, needed, ex->fe_group, ex->fe_start,
1564 ex->fe_len, ex->fe_logical);
1565 ex->fe_len = 0;
1566 ex->fe_start = 0;
1567 ex->fe_group = 0;
1569 return ex->fe_len;
1572 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1574 int ord;
1575 int mlen = 0;
1576 int max = 0;
1577 int cur;
1578 int start = ex->fe_start;
1579 int len = ex->fe_len;
1580 unsigned ret = 0;
1581 int len0 = len;
1582 void *buddy;
1584 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1585 BUG_ON(e4b->bd_group != ex->fe_group);
1586 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1587 mb_check_buddy(e4b);
1588 mb_mark_used_double(e4b, start, len);
1590 e4b->bd_info->bb_free -= len;
1591 if (e4b->bd_info->bb_first_free == start)
1592 e4b->bd_info->bb_first_free += len;
1594 /* let's maintain fragments counter */
1595 if (start != 0)
1596 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1597 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1598 max = !mb_test_bit(start + len, e4b->bd_bitmap);
1599 if (mlen && max)
1600 e4b->bd_info->bb_fragments++;
1601 else if (!mlen && !max)
1602 e4b->bd_info->bb_fragments--;
1604 /* let's maintain buddy itself */
1605 while (len) {
1606 ord = mb_find_order_for_block(e4b, start);
1608 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1609 /* the whole chunk may be allocated at once! */
1610 mlen = 1 << ord;
1611 buddy = mb_find_buddy(e4b, ord, &max);
1612 BUG_ON((start >> ord) >= max);
1613 mb_set_bit(start >> ord, buddy);
1614 e4b->bd_info->bb_counters[ord]--;
1615 start += mlen;
1616 len -= mlen;
1617 BUG_ON(len < 0);
1618 continue;
1621 /* store for history */
1622 if (ret == 0)
1623 ret = len | (ord << 16);
1625 /* we have to split large buddy */
1626 BUG_ON(ord <= 0);
1627 buddy = mb_find_buddy(e4b, ord, &max);
1628 mb_set_bit(start >> ord, buddy);
1629 e4b->bd_info->bb_counters[ord]--;
1631 ord--;
1632 cur = (start >> ord) & ~1U;
1633 buddy = mb_find_buddy(e4b, ord, &max);
1634 mb_clear_bit(cur, buddy);
1635 mb_clear_bit(cur + 1, buddy);
1636 e4b->bd_info->bb_counters[ord]++;
1637 e4b->bd_info->bb_counters[ord]++;
1639 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1641 ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1642 mb_check_buddy(e4b);
1644 return ret;
1648 * Must be called under group lock!
1650 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1651 struct ext4_buddy *e4b)
1653 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1654 int ret;
1656 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1657 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1659 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1660 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1661 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1663 /* preallocation can change ac_b_ex, thus we store actually
1664 * allocated blocks for history */
1665 ac->ac_f_ex = ac->ac_b_ex;
1667 ac->ac_status = AC_STATUS_FOUND;
1668 ac->ac_tail = ret & 0xffff;
1669 ac->ac_buddy = ret >> 16;
1672 * take the page reference. We want the page to be pinned
1673 * so that we don't get a ext4_mb_init_cache_call for this
1674 * group until we update the bitmap. That would mean we
1675 * double allocate blocks. The reference is dropped
1676 * in ext4_mb_release_context
1678 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1679 get_page(ac->ac_bitmap_page);
1680 ac->ac_buddy_page = e4b->bd_buddy_page;
1681 get_page(ac->ac_buddy_page);
1682 /* store last allocated for subsequent stream allocation */
1683 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1684 spin_lock(&sbi->s_md_lock);
1685 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1686 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1687 spin_unlock(&sbi->s_md_lock);
1692 * regular allocator, for general purposes allocation
1695 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1696 struct ext4_buddy *e4b,
1697 int finish_group)
1699 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1700 struct ext4_free_extent *bex = &ac->ac_b_ex;
1701 struct ext4_free_extent *gex = &ac->ac_g_ex;
1702 struct ext4_free_extent ex;
1703 int max;
1705 if (ac->ac_status == AC_STATUS_FOUND)
1706 return;
1708 * We don't want to scan for a whole year
1710 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1711 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1712 ac->ac_status = AC_STATUS_BREAK;
1713 return;
1717 * Haven't found good chunk so far, let's continue
1719 if (bex->fe_len < gex->fe_len)
1720 return;
1722 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1723 && bex->fe_group == e4b->bd_group) {
1724 /* recheck chunk's availability - we don't know
1725 * when it was found (within this lock-unlock
1726 * period or not) */
1727 max = mb_find_extent(e4b, bex->fe_start, gex->fe_len, &ex);
1728 if (max >= gex->fe_len) {
1729 ext4_mb_use_best_found(ac, e4b);
1730 return;
1736 * The routine checks whether found extent is good enough. If it is,
1737 * then the extent gets marked used and flag is set to the context
1738 * to stop scanning. Otherwise, the extent is compared with the
1739 * previous found extent and if new one is better, then it's stored
1740 * in the context. Later, the best found extent will be used, if
1741 * mballoc can't find good enough extent.
1743 * FIXME: real allocation policy is to be designed yet!
1745 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1746 struct ext4_free_extent *ex,
1747 struct ext4_buddy *e4b)
1749 struct ext4_free_extent *bex = &ac->ac_b_ex;
1750 struct ext4_free_extent *gex = &ac->ac_g_ex;
1752 BUG_ON(ex->fe_len <= 0);
1753 BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1754 BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1755 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1757 ac->ac_found++;
1760 * The special case - take what you catch first
1762 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1763 *bex = *ex;
1764 ext4_mb_use_best_found(ac, e4b);
1765 return;
1769 * Let's check whether the chuck is good enough
1771 if (ex->fe_len == gex->fe_len) {
1772 *bex = *ex;
1773 ext4_mb_use_best_found(ac, e4b);
1774 return;
1778 * If this is first found extent, just store it in the context
1780 if (bex->fe_len == 0) {
1781 *bex = *ex;
1782 return;
1786 * If new found extent is better, store it in the context
1788 if (bex->fe_len < gex->fe_len) {
1789 /* if the request isn't satisfied, any found extent
1790 * larger than previous best one is better */
1791 if (ex->fe_len > bex->fe_len)
1792 *bex = *ex;
1793 } else if (ex->fe_len > gex->fe_len) {
1794 /* if the request is satisfied, then we try to find
1795 * an extent that still satisfy the request, but is
1796 * smaller than previous one */
1797 if (ex->fe_len < bex->fe_len)
1798 *bex = *ex;
1801 ext4_mb_check_limits(ac, e4b, 0);
1804 static noinline_for_stack
1805 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1806 struct ext4_buddy *e4b)
1808 struct ext4_free_extent ex = ac->ac_b_ex;
1809 ext4_group_t group = ex.fe_group;
1810 int max;
1811 int err;
1813 BUG_ON(ex.fe_len <= 0);
1814 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1815 if (err)
1816 return err;
1818 ext4_lock_group(ac->ac_sb, group);
1819 max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
1821 if (max > 0) {
1822 ac->ac_b_ex = ex;
1823 ext4_mb_use_best_found(ac, e4b);
1826 ext4_unlock_group(ac->ac_sb, group);
1827 ext4_mb_unload_buddy(e4b);
1829 return 0;
1832 static noinline_for_stack
1833 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1834 struct ext4_buddy *e4b)
1836 ext4_group_t group = ac->ac_g_ex.fe_group;
1837 int max;
1838 int err;
1839 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1840 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1841 struct ext4_free_extent ex;
1843 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1844 return 0;
1845 if (grp->bb_free == 0)
1846 return 0;
1848 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1849 if (err)
1850 return err;
1852 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
1853 ext4_mb_unload_buddy(e4b);
1854 return 0;
1857 ext4_lock_group(ac->ac_sb, group);
1858 max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
1859 ac->ac_g_ex.fe_len, &ex);
1860 ex.fe_logical = 0xDEADFA11; /* debug value */
1862 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1863 ext4_fsblk_t start;
1865 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
1866 ex.fe_start;
1867 /* use do_div to get remainder (would be 64-bit modulo) */
1868 if (do_div(start, sbi->s_stripe) == 0) {
1869 ac->ac_found++;
1870 ac->ac_b_ex = ex;
1871 ext4_mb_use_best_found(ac, e4b);
1873 } else if (max >= ac->ac_g_ex.fe_len) {
1874 BUG_ON(ex.fe_len <= 0);
1875 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1876 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1877 ac->ac_found++;
1878 ac->ac_b_ex = ex;
1879 ext4_mb_use_best_found(ac, e4b);
1880 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1881 /* Sometimes, caller may want to merge even small
1882 * number of blocks to an existing extent */
1883 BUG_ON(ex.fe_len <= 0);
1884 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1885 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1886 ac->ac_found++;
1887 ac->ac_b_ex = ex;
1888 ext4_mb_use_best_found(ac, e4b);
1890 ext4_unlock_group(ac->ac_sb, group);
1891 ext4_mb_unload_buddy(e4b);
1893 return 0;
1897 * The routine scans buddy structures (not bitmap!) from given order
1898 * to max order and tries to find big enough chunk to satisfy the req
1900 static noinline_for_stack
1901 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1902 struct ext4_buddy *e4b)
1904 struct super_block *sb = ac->ac_sb;
1905 struct ext4_group_info *grp = e4b->bd_info;
1906 void *buddy;
1907 int i;
1908 int k;
1909 int max;
1911 BUG_ON(ac->ac_2order <= 0);
1912 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1913 if (grp->bb_counters[i] == 0)
1914 continue;
1916 buddy = mb_find_buddy(e4b, i, &max);
1917 BUG_ON(buddy == NULL);
1919 k = mb_find_next_zero_bit(buddy, max, 0);
1920 BUG_ON(k >= max);
1922 ac->ac_found++;
1924 ac->ac_b_ex.fe_len = 1 << i;
1925 ac->ac_b_ex.fe_start = k << i;
1926 ac->ac_b_ex.fe_group = e4b->bd_group;
1928 ext4_mb_use_best_found(ac, e4b);
1930 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1932 if (EXT4_SB(sb)->s_mb_stats)
1933 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1935 break;
1940 * The routine scans the group and measures all found extents.
1941 * In order to optimize scanning, caller must pass number of
1942 * free blocks in the group, so the routine can know upper limit.
1944 static noinline_for_stack
1945 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1946 struct ext4_buddy *e4b)
1948 struct super_block *sb = ac->ac_sb;
1949 void *bitmap = e4b->bd_bitmap;
1950 struct ext4_free_extent ex;
1951 int i;
1952 int free;
1954 free = e4b->bd_info->bb_free;
1955 if (WARN_ON(free <= 0))
1956 return;
1958 i = e4b->bd_info->bb_first_free;
1960 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1961 i = mb_find_next_zero_bit(bitmap,
1962 EXT4_CLUSTERS_PER_GROUP(sb), i);
1963 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
1965 * IF we have corrupt bitmap, we won't find any
1966 * free blocks even though group info says we
1967 * we have free blocks
1969 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1970 "%d free clusters as per "
1971 "group info. But bitmap says 0",
1972 free);
1973 break;
1976 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
1977 if (WARN_ON(ex.fe_len <= 0))
1978 break;
1979 if (free < ex.fe_len) {
1980 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1981 "%d free clusters as per "
1982 "group info. But got %d blocks",
1983 free, ex.fe_len);
1985 * The number of free blocks differs. This mostly
1986 * indicate that the bitmap is corrupt. So exit
1987 * without claiming the space.
1989 break;
1991 ex.fe_logical = 0xDEADC0DE; /* debug value */
1992 ext4_mb_measure_extent(ac, &ex, e4b);
1994 i += ex.fe_len;
1995 free -= ex.fe_len;
1998 ext4_mb_check_limits(ac, e4b, 1);
2002 * This is a special case for storages like raid5
2003 * we try to find stripe-aligned chunks for stripe-size-multiple requests
2005 static noinline_for_stack
2006 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2007 struct ext4_buddy *e4b)
2009 struct super_block *sb = ac->ac_sb;
2010 struct ext4_sb_info *sbi = EXT4_SB(sb);
2011 void *bitmap = e4b->bd_bitmap;
2012 struct ext4_free_extent ex;
2013 ext4_fsblk_t first_group_block;
2014 ext4_fsblk_t a;
2015 ext4_grpblk_t i;
2016 int max;
2018 BUG_ON(sbi->s_stripe == 0);
2020 /* find first stripe-aligned block in group */
2021 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2023 a = first_group_block + sbi->s_stripe - 1;
2024 do_div(a, sbi->s_stripe);
2025 i = (a * sbi->s_stripe) - first_group_block;
2027 while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2028 if (!mb_test_bit(i, bitmap)) {
2029 max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
2030 if (max >= sbi->s_stripe) {
2031 ac->ac_found++;
2032 ex.fe_logical = 0xDEADF00D; /* debug value */
2033 ac->ac_b_ex = ex;
2034 ext4_mb_use_best_found(ac, e4b);
2035 break;
2038 i += sbi->s_stripe;
2043 * This is now called BEFORE we load the buddy bitmap.
2044 * Returns either 1 or 0 indicating that the group is either suitable
2045 * for the allocation or not. In addition it can also return negative
2046 * error code when something goes wrong.
2048 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
2049 ext4_group_t group, int cr)
2051 unsigned free, fragments;
2052 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2053 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2055 BUG_ON(cr < 0 || cr >= 4);
2057 free = grp->bb_free;
2058 if (free == 0)
2059 return 0;
2060 if (cr <= 2 && free < ac->ac_g_ex.fe_len)
2061 return 0;
2063 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2064 return 0;
2066 /* We only do this if the grp has never been initialized */
2067 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2068 int ret = ext4_mb_init_group(ac->ac_sb, group, GFP_NOFS);
2069 if (ret)
2070 return ret;
2073 fragments = grp->bb_fragments;
2074 if (fragments == 0)
2075 return 0;
2077 switch (cr) {
2078 case 0:
2079 BUG_ON(ac->ac_2order == 0);
2081 /* Avoid using the first bg of a flexgroup for data files */
2082 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2083 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2084 ((group % flex_size) == 0))
2085 return 0;
2087 if ((ac->ac_2order > ac->ac_sb->s_blocksize_bits+1) ||
2088 (free / fragments) >= ac->ac_g_ex.fe_len)
2089 return 1;
2091 if (grp->bb_largest_free_order < ac->ac_2order)
2092 return 0;
2094 return 1;
2095 case 1:
2096 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2097 return 1;
2098 break;
2099 case 2:
2100 if (free >= ac->ac_g_ex.fe_len)
2101 return 1;
2102 break;
2103 case 3:
2104 return 1;
2105 default:
2106 BUG();
2109 return 0;
2112 static noinline_for_stack int
2113 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2115 ext4_group_t ngroups, group, i;
2116 int cr;
2117 int err = 0, first_err = 0;
2118 struct ext4_sb_info *sbi;
2119 struct super_block *sb;
2120 struct ext4_buddy e4b;
2122 sb = ac->ac_sb;
2123 sbi = EXT4_SB(sb);
2124 ngroups = ext4_get_groups_count(sb);
2125 /* non-extent files are limited to low blocks/groups */
2126 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2127 ngroups = sbi->s_blockfile_groups;
2129 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2131 /* first, try the goal */
2132 err = ext4_mb_find_by_goal(ac, &e4b);
2133 if (err || ac->ac_status == AC_STATUS_FOUND)
2134 goto out;
2136 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2137 goto out;
2140 * ac->ac2_order is set only if the fe_len is a power of 2
2141 * if ac2_order is set we also set criteria to 0 so that we
2142 * try exact allocation using buddy.
2144 i = fls(ac->ac_g_ex.fe_len);
2145 ac->ac_2order = 0;
2147 * We search using buddy data only if the order of the request
2148 * is greater than equal to the sbi_s_mb_order2_reqs
2149 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2150 * We also support searching for power-of-two requests only for
2151 * requests upto maximum buddy size we have constructed.
2153 if (i >= sbi->s_mb_order2_reqs && i <= sb->s_blocksize_bits + 2) {
2155 * This should tell if fe_len is exactly power of 2
2157 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2158 ac->ac_2order = array_index_nospec(i - 1,
2159 sb->s_blocksize_bits + 2);
2162 /* if stream allocation is enabled, use global goal */
2163 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2164 /* TBD: may be hot point */
2165 spin_lock(&sbi->s_md_lock);
2166 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2167 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2168 spin_unlock(&sbi->s_md_lock);
2171 /* Let's just scan groups to find more-less suitable blocks */
2172 cr = ac->ac_2order ? 0 : 1;
2174 * cr == 0 try to get exact allocation,
2175 * cr == 3 try to get anything
2177 repeat:
2178 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2179 ac->ac_criteria = cr;
2181 * searching for the right group start
2182 * from the goal value specified
2184 group = ac->ac_g_ex.fe_group;
2186 for (i = 0; i < ngroups; group++, i++) {
2187 int ret = 0;
2188 cond_resched();
2190 * Artificially restricted ngroups for non-extent
2191 * files makes group > ngroups possible on first loop.
2193 if (group >= ngroups)
2194 group = 0;
2196 /* This now checks without needing the buddy page */
2197 ret = ext4_mb_good_group(ac, group, cr);
2198 if (ret <= 0) {
2199 if (!first_err)
2200 first_err = ret;
2201 continue;
2204 err = ext4_mb_load_buddy(sb, group, &e4b);
2205 if (err)
2206 goto out;
2208 ext4_lock_group(sb, group);
2211 * We need to check again after locking the
2212 * block group
2214 ret = ext4_mb_good_group(ac, group, cr);
2215 if (ret <= 0) {
2216 ext4_unlock_group(sb, group);
2217 ext4_mb_unload_buddy(&e4b);
2218 if (!first_err)
2219 first_err = ret;
2220 continue;
2223 ac->ac_groups_scanned++;
2224 if (cr == 0)
2225 ext4_mb_simple_scan_group(ac, &e4b);
2226 else if (cr == 1 && sbi->s_stripe &&
2227 !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2228 ext4_mb_scan_aligned(ac, &e4b);
2229 else
2230 ext4_mb_complex_scan_group(ac, &e4b);
2232 ext4_unlock_group(sb, group);
2233 ext4_mb_unload_buddy(&e4b);
2235 if (ac->ac_status != AC_STATUS_CONTINUE)
2236 break;
2240 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2241 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2243 * We've been searching too long. Let's try to allocate
2244 * the best chunk we've found so far
2247 ext4_mb_try_best_found(ac, &e4b);
2248 if (ac->ac_status != AC_STATUS_FOUND) {
2250 * Someone more lucky has already allocated it.
2251 * The only thing we can do is just take first
2252 * found block(s)
2253 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2255 ac->ac_b_ex.fe_group = 0;
2256 ac->ac_b_ex.fe_start = 0;
2257 ac->ac_b_ex.fe_len = 0;
2258 ac->ac_status = AC_STATUS_CONTINUE;
2259 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2260 cr = 3;
2261 atomic_inc(&sbi->s_mb_lost_chunks);
2262 goto repeat;
2265 out:
2266 if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2267 err = first_err;
2268 return err;
2271 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2273 struct super_block *sb = seq->private;
2274 ext4_group_t group;
2276 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2277 return NULL;
2278 group = *pos + 1;
2279 return (void *) ((unsigned long) group);
2282 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2284 struct super_block *sb = seq->private;
2285 ext4_group_t group;
2287 ++*pos;
2288 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2289 return NULL;
2290 group = *pos + 1;
2291 return (void *) ((unsigned long) group);
2294 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2296 struct super_block *sb = seq->private;
2297 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2298 int i;
2299 int err, buddy_loaded = 0;
2300 struct ext4_buddy e4b;
2301 struct ext4_group_info *grinfo;
2302 unsigned char blocksize_bits = min_t(unsigned char,
2303 sb->s_blocksize_bits,
2304 EXT4_MAX_BLOCK_LOG_SIZE);
2305 struct sg {
2306 struct ext4_group_info info;
2307 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
2308 } sg;
2310 group--;
2311 if (group == 0)
2312 seq_puts(seq, "#group: free frags first ["
2313 " 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
2314 " 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
2316 i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2317 sizeof(struct ext4_group_info);
2319 grinfo = ext4_get_group_info(sb, group);
2320 /* Load the group info in memory only if not already loaded. */
2321 if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
2322 err = ext4_mb_load_buddy(sb, group, &e4b);
2323 if (err) {
2324 seq_printf(seq, "#%-5u: I/O error\n", group);
2325 return 0;
2327 buddy_loaded = 1;
2330 memcpy(&sg, ext4_get_group_info(sb, group), i);
2332 if (buddy_loaded)
2333 ext4_mb_unload_buddy(&e4b);
2335 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2336 sg.info.bb_fragments, sg.info.bb_first_free);
2337 for (i = 0; i <= 13; i++)
2338 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
2339 sg.info.bb_counters[i] : 0);
2340 seq_printf(seq, " ]\n");
2342 return 0;
2345 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2349 static const struct seq_operations ext4_mb_seq_groups_ops = {
2350 .start = ext4_mb_seq_groups_start,
2351 .next = ext4_mb_seq_groups_next,
2352 .stop = ext4_mb_seq_groups_stop,
2353 .show = ext4_mb_seq_groups_show,
2356 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2358 struct super_block *sb = PDE_DATA(inode);
2359 int rc;
2361 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2362 if (rc == 0) {
2363 struct seq_file *m = file->private_data;
2364 m->private = sb;
2366 return rc;
2370 const struct file_operations ext4_seq_mb_groups_fops = {
2371 .open = ext4_mb_seq_groups_open,
2372 .read = seq_read,
2373 .llseek = seq_lseek,
2374 .release = seq_release,
2377 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2379 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2380 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2382 BUG_ON(!cachep);
2383 return cachep;
2387 * Allocate the top-level s_group_info array for the specified number
2388 * of groups
2390 int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
2392 struct ext4_sb_info *sbi = EXT4_SB(sb);
2393 unsigned size;
2394 struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
2396 size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
2397 EXT4_DESC_PER_BLOCK_BITS(sb);
2398 if (size <= sbi->s_group_info_size)
2399 return 0;
2401 size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
2402 new_groupinfo = kvzalloc(size, GFP_KERNEL);
2403 if (!new_groupinfo) {
2404 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
2405 return -ENOMEM;
2407 rcu_read_lock();
2408 old_groupinfo = rcu_dereference(sbi->s_group_info);
2409 if (old_groupinfo)
2410 memcpy(new_groupinfo, old_groupinfo,
2411 sbi->s_group_info_size * sizeof(*sbi->s_group_info));
2412 rcu_read_unlock();
2413 rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
2414 sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
2415 if (old_groupinfo)
2416 ext4_kvfree_array_rcu(old_groupinfo);
2417 ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
2418 sbi->s_group_info_size);
2419 return 0;
2422 /* Create and initialize ext4_group_info data for the given group. */
2423 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2424 struct ext4_group_desc *desc)
2426 int i;
2427 int metalen = 0;
2428 int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
2429 struct ext4_sb_info *sbi = EXT4_SB(sb);
2430 struct ext4_group_info **meta_group_info;
2431 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2434 * First check if this group is the first of a reserved block.
2435 * If it's true, we have to allocate a new table of pointers
2436 * to ext4_group_info structures
2438 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2439 metalen = sizeof(*meta_group_info) <<
2440 EXT4_DESC_PER_BLOCK_BITS(sb);
2441 meta_group_info = kmalloc(metalen, GFP_NOFS);
2442 if (meta_group_info == NULL) {
2443 ext4_msg(sb, KERN_ERR, "can't allocate mem "
2444 "for a buddy group");
2445 goto exit_meta_group_info;
2447 rcu_read_lock();
2448 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
2449 rcu_read_unlock();
2452 meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
2453 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2455 meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
2456 if (meta_group_info[i] == NULL) {
2457 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
2458 goto exit_group_info;
2460 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2461 &(meta_group_info[i]->bb_state));
2464 * initialize bb_free to be able to skip
2465 * empty groups without initialization
2467 if (ext4_has_group_desc_csum(sb) &&
2468 (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
2469 meta_group_info[i]->bb_free =
2470 ext4_free_clusters_after_init(sb, group, desc);
2471 } else {
2472 meta_group_info[i]->bb_free =
2473 ext4_free_group_clusters(sb, desc);
2476 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2477 init_rwsem(&meta_group_info[i]->alloc_sem);
2478 meta_group_info[i]->bb_free_root = RB_ROOT;
2479 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
2481 #ifdef DOUBLE_CHECK
2483 struct buffer_head *bh;
2484 meta_group_info[i]->bb_bitmap =
2485 kmalloc(sb->s_blocksize, GFP_NOFS);
2486 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2487 bh = ext4_read_block_bitmap(sb, group);
2488 BUG_ON(IS_ERR_OR_NULL(bh));
2489 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2490 sb->s_blocksize);
2491 put_bh(bh);
2493 #endif
2495 return 0;
2497 exit_group_info:
2498 /* If a meta_group_info table has been allocated, release it now */
2499 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2500 struct ext4_group_info ***group_info;
2502 rcu_read_lock();
2503 group_info = rcu_dereference(sbi->s_group_info);
2504 kfree(group_info[idx]);
2505 group_info[idx] = NULL;
2506 rcu_read_unlock();
2508 exit_meta_group_info:
2509 return -ENOMEM;
2510 } /* ext4_mb_add_groupinfo */
2512 static int ext4_mb_init_backend(struct super_block *sb)
2514 ext4_group_t ngroups = ext4_get_groups_count(sb);
2515 ext4_group_t i;
2516 struct ext4_sb_info *sbi = EXT4_SB(sb);
2517 int err;
2518 struct ext4_group_desc *desc;
2519 struct ext4_group_info ***group_info;
2520 struct kmem_cache *cachep;
2522 err = ext4_mb_alloc_groupinfo(sb, ngroups);
2523 if (err)
2524 return err;
2526 sbi->s_buddy_cache = new_inode(sb);
2527 if (sbi->s_buddy_cache == NULL) {
2528 ext4_msg(sb, KERN_ERR, "can't get new inode");
2529 goto err_freesgi;
2531 /* To avoid potentially colliding with an valid on-disk inode number,
2532 * use EXT4_BAD_INO for the buddy cache inode number. This inode is
2533 * not in the inode hash, so it should never be found by iget(), but
2534 * this will avoid confusion if it ever shows up during debugging. */
2535 sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
2536 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2537 for (i = 0; i < ngroups; i++) {
2538 desc = ext4_get_group_desc(sb, i, NULL);
2539 if (desc == NULL) {
2540 ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2541 goto err_freebuddy;
2543 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2544 goto err_freebuddy;
2547 return 0;
2549 err_freebuddy:
2550 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2551 while (i-- > 0)
2552 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2553 i = sbi->s_group_info_size;
2554 rcu_read_lock();
2555 group_info = rcu_dereference(sbi->s_group_info);
2556 while (i-- > 0)
2557 kfree(group_info[i]);
2558 rcu_read_unlock();
2559 iput(sbi->s_buddy_cache);
2560 err_freesgi:
2561 rcu_read_lock();
2562 kvfree(rcu_dereference(sbi->s_group_info));
2563 rcu_read_unlock();
2564 return -ENOMEM;
2567 static void ext4_groupinfo_destroy_slabs(void)
2569 int i;
2571 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
2572 if (ext4_groupinfo_caches[i])
2573 kmem_cache_destroy(ext4_groupinfo_caches[i]);
2574 ext4_groupinfo_caches[i] = NULL;
2578 static int ext4_groupinfo_create_slab(size_t size)
2580 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
2581 int slab_size;
2582 int blocksize_bits = order_base_2(size);
2583 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2584 struct kmem_cache *cachep;
2586 if (cache_index >= NR_GRPINFO_CACHES)
2587 return -EINVAL;
2589 if (unlikely(cache_index < 0))
2590 cache_index = 0;
2592 mutex_lock(&ext4_grpinfo_slab_create_mutex);
2593 if (ext4_groupinfo_caches[cache_index]) {
2594 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2595 return 0; /* Already created */
2598 slab_size = offsetof(struct ext4_group_info,
2599 bb_counters[blocksize_bits + 2]);
2601 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
2602 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
2603 NULL);
2605 ext4_groupinfo_caches[cache_index] = cachep;
2607 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2608 if (!cachep) {
2609 printk(KERN_EMERG
2610 "EXT4-fs: no memory for groupinfo slab cache\n");
2611 return -ENOMEM;
2614 return 0;
2617 int ext4_mb_init(struct super_block *sb)
2619 struct ext4_sb_info *sbi = EXT4_SB(sb);
2620 unsigned i, j;
2621 unsigned offset, offset_incr;
2622 unsigned max;
2623 int ret;
2625 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2627 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2628 if (sbi->s_mb_offsets == NULL) {
2629 ret = -ENOMEM;
2630 goto out;
2633 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2634 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2635 if (sbi->s_mb_maxs == NULL) {
2636 ret = -ENOMEM;
2637 goto out;
2640 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2641 if (ret < 0)
2642 goto out;
2644 /* order 0 is regular bitmap */
2645 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2646 sbi->s_mb_offsets[0] = 0;
2648 i = 1;
2649 offset = 0;
2650 offset_incr = 1 << (sb->s_blocksize_bits - 1);
2651 max = sb->s_blocksize << 2;
2652 do {
2653 sbi->s_mb_offsets[i] = offset;
2654 sbi->s_mb_maxs[i] = max;
2655 offset += offset_incr;
2656 offset_incr = offset_incr >> 1;
2657 max = max >> 1;
2658 i++;
2659 } while (i <= sb->s_blocksize_bits + 1);
2661 spin_lock_init(&sbi->s_md_lock);
2662 spin_lock_init(&sbi->s_bal_lock);
2663 sbi->s_mb_free_pending = 0;
2664 INIT_LIST_HEAD(&sbi->s_freed_data_list);
2666 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2667 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2668 sbi->s_mb_stats = MB_DEFAULT_STATS;
2669 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2670 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2672 * The default group preallocation is 512, which for 4k block
2673 * sizes translates to 2 megabytes. However for bigalloc file
2674 * systems, this is probably too big (i.e, if the cluster size
2675 * is 1 megabyte, then group preallocation size becomes half a
2676 * gigabyte!). As a default, we will keep a two megabyte
2677 * group pralloc size for cluster sizes up to 64k, and after
2678 * that, we will force a minimum group preallocation size of
2679 * 32 clusters. This translates to 8 megs when the cluster
2680 * size is 256k, and 32 megs when the cluster size is 1 meg,
2681 * which seems reasonable as a default.
2683 sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
2684 sbi->s_cluster_bits, 32);
2686 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
2687 * to the lowest multiple of s_stripe which is bigger than
2688 * the s_mb_group_prealloc as determined above. We want
2689 * the preallocation size to be an exact multiple of the
2690 * RAID stripe size so that preallocations don't fragment
2691 * the stripes.
2693 if (sbi->s_stripe > 1) {
2694 sbi->s_mb_group_prealloc = roundup(
2695 sbi->s_mb_group_prealloc, sbi->s_stripe);
2698 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2699 if (sbi->s_locality_groups == NULL) {
2700 ret = -ENOMEM;
2701 goto out;
2703 for_each_possible_cpu(i) {
2704 struct ext4_locality_group *lg;
2705 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2706 mutex_init(&lg->lg_mutex);
2707 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2708 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2709 spin_lock_init(&lg->lg_prealloc_lock);
2712 /* init file for buddy data */
2713 ret = ext4_mb_init_backend(sb);
2714 if (ret != 0)
2715 goto out_free_locality_groups;
2717 return 0;
2719 out_free_locality_groups:
2720 free_percpu(sbi->s_locality_groups);
2721 sbi->s_locality_groups = NULL;
2722 out:
2723 kfree(sbi->s_mb_offsets);
2724 sbi->s_mb_offsets = NULL;
2725 kfree(sbi->s_mb_maxs);
2726 sbi->s_mb_maxs = NULL;
2727 return ret;
2730 /* need to called with the ext4 group lock held */
2731 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2733 struct ext4_prealloc_space *pa;
2734 struct list_head *cur, *tmp;
2735 int count = 0;
2737 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2738 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2739 list_del(&pa->pa_group_list);
2740 count++;
2741 kmem_cache_free(ext4_pspace_cachep, pa);
2743 if (count)
2744 mb_debug(1, "mballoc: %u PAs left\n", count);
2748 int ext4_mb_release(struct super_block *sb)
2750 ext4_group_t ngroups = ext4_get_groups_count(sb);
2751 ext4_group_t i;
2752 int num_meta_group_infos;
2753 struct ext4_group_info *grinfo, ***group_info;
2754 struct ext4_sb_info *sbi = EXT4_SB(sb);
2755 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2757 if (sbi->s_group_info) {
2758 for (i = 0; i < ngroups; i++) {
2759 grinfo = ext4_get_group_info(sb, i);
2760 #ifdef DOUBLE_CHECK
2761 kfree(grinfo->bb_bitmap);
2762 #endif
2763 ext4_lock_group(sb, i);
2764 ext4_mb_cleanup_pa(grinfo);
2765 ext4_unlock_group(sb, i);
2766 kmem_cache_free(cachep, grinfo);
2768 num_meta_group_infos = (ngroups +
2769 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2770 EXT4_DESC_PER_BLOCK_BITS(sb);
2771 rcu_read_lock();
2772 group_info = rcu_dereference(sbi->s_group_info);
2773 for (i = 0; i < num_meta_group_infos; i++)
2774 kfree(group_info[i]);
2775 kvfree(group_info);
2776 rcu_read_unlock();
2778 kfree(sbi->s_mb_offsets);
2779 kfree(sbi->s_mb_maxs);
2780 iput(sbi->s_buddy_cache);
2781 if (sbi->s_mb_stats) {
2782 ext4_msg(sb, KERN_INFO,
2783 "mballoc: %u blocks %u reqs (%u success)",
2784 atomic_read(&sbi->s_bal_allocated),
2785 atomic_read(&sbi->s_bal_reqs),
2786 atomic_read(&sbi->s_bal_success));
2787 ext4_msg(sb, KERN_INFO,
2788 "mballoc: %u extents scanned, %u goal hits, "
2789 "%u 2^N hits, %u breaks, %u lost",
2790 atomic_read(&sbi->s_bal_ex_scanned),
2791 atomic_read(&sbi->s_bal_goals),
2792 atomic_read(&sbi->s_bal_2orders),
2793 atomic_read(&sbi->s_bal_breaks),
2794 atomic_read(&sbi->s_mb_lost_chunks));
2795 ext4_msg(sb, KERN_INFO,
2796 "mballoc: %lu generated and it took %Lu",
2797 sbi->s_mb_buddies_generated,
2798 sbi->s_mb_generation_time);
2799 ext4_msg(sb, KERN_INFO,
2800 "mballoc: %u preallocated, %u discarded",
2801 atomic_read(&sbi->s_mb_preallocated),
2802 atomic_read(&sbi->s_mb_discarded));
2805 free_percpu(sbi->s_locality_groups);
2807 return 0;
2810 static inline int ext4_issue_discard(struct super_block *sb,
2811 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
2812 struct bio **biop)
2814 ext4_fsblk_t discard_block;
2816 discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
2817 ext4_group_first_block_no(sb, block_group));
2818 count = EXT4_C2B(EXT4_SB(sb), count);
2819 trace_ext4_discard_blocks(sb,
2820 (unsigned long long) discard_block, count);
2821 if (biop) {
2822 return __blkdev_issue_discard(sb->s_bdev,
2823 (sector_t)discard_block << (sb->s_blocksize_bits - 9),
2824 (sector_t)count << (sb->s_blocksize_bits - 9),
2825 GFP_NOFS, 0, biop);
2826 } else
2827 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
2830 static void ext4_free_data_in_buddy(struct super_block *sb,
2831 struct ext4_free_data *entry)
2833 struct ext4_buddy e4b;
2834 struct ext4_group_info *db;
2835 int err, count = 0, count2 = 0;
2837 mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2838 entry->efd_count, entry->efd_group, entry);
2840 err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
2841 /* we expect to find existing buddy because it's pinned */
2842 BUG_ON(err != 0);
2844 spin_lock(&EXT4_SB(sb)->s_md_lock);
2845 EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
2846 spin_unlock(&EXT4_SB(sb)->s_md_lock);
2848 db = e4b.bd_info;
2849 /* there are blocks to put in buddy to make them really free */
2850 count += entry->efd_count;
2851 count2++;
2852 ext4_lock_group(sb, entry->efd_group);
2853 /* Take it out of per group rb tree */
2854 rb_erase(&entry->efd_node, &(db->bb_free_root));
2855 mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
2858 * Clear the trimmed flag for the group so that the next
2859 * ext4_trim_fs can trim it.
2860 * If the volume is mounted with -o discard, online discard
2861 * is supported and the free blocks will be trimmed online.
2863 if (!test_opt(sb, DISCARD))
2864 EXT4_MB_GRP_CLEAR_TRIMMED(db);
2866 if (!db->bb_free_root.rb_node) {
2867 /* No more items in the per group rb tree
2868 * balance refcounts from ext4_mb_free_metadata()
2870 put_page(e4b.bd_buddy_page);
2871 put_page(e4b.bd_bitmap_page);
2873 ext4_unlock_group(sb, entry->efd_group);
2874 kmem_cache_free(ext4_free_data_cachep, entry);
2875 ext4_mb_unload_buddy(&e4b);
2877 mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2881 * This function is called by the jbd2 layer once the commit has finished,
2882 * so we know we can free the blocks that were released with that commit.
2884 void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
2886 struct ext4_sb_info *sbi = EXT4_SB(sb);
2887 struct ext4_free_data *entry, *tmp;
2888 struct bio *discard_bio = NULL;
2889 struct list_head freed_data_list;
2890 struct list_head *cut_pos = NULL;
2891 int err;
2893 INIT_LIST_HEAD(&freed_data_list);
2895 spin_lock(&sbi->s_md_lock);
2896 list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
2897 if (entry->efd_tid != commit_tid)
2898 break;
2899 cut_pos = &entry->efd_list;
2901 if (cut_pos)
2902 list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
2903 cut_pos);
2904 spin_unlock(&sbi->s_md_lock);
2906 if (test_opt(sb, DISCARD)) {
2907 list_for_each_entry(entry, &freed_data_list, efd_list) {
2908 err = ext4_issue_discard(sb, entry->efd_group,
2909 entry->efd_start_cluster,
2910 entry->efd_count,
2911 &discard_bio);
2912 if (err && err != -EOPNOTSUPP) {
2913 ext4_msg(sb, KERN_WARNING, "discard request in"
2914 " group:%d block:%d count:%d failed"
2915 " with %d", entry->efd_group,
2916 entry->efd_start_cluster,
2917 entry->efd_count, err);
2918 } else if (err == -EOPNOTSUPP)
2919 break;
2922 if (discard_bio) {
2923 submit_bio_wait(discard_bio);
2924 bio_put(discard_bio);
2928 list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
2929 ext4_free_data_in_buddy(sb, entry);
2932 int __init ext4_init_mballoc(void)
2934 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
2935 SLAB_RECLAIM_ACCOUNT);
2936 if (ext4_pspace_cachep == NULL)
2937 return -ENOMEM;
2939 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
2940 SLAB_RECLAIM_ACCOUNT);
2941 if (ext4_ac_cachep == NULL) {
2942 kmem_cache_destroy(ext4_pspace_cachep);
2943 return -ENOMEM;
2946 ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
2947 SLAB_RECLAIM_ACCOUNT);
2948 if (ext4_free_data_cachep == NULL) {
2949 kmem_cache_destroy(ext4_pspace_cachep);
2950 kmem_cache_destroy(ext4_ac_cachep);
2951 return -ENOMEM;
2953 return 0;
2956 void ext4_exit_mballoc(void)
2959 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
2960 * before destroying the slab cache.
2962 rcu_barrier();
2963 kmem_cache_destroy(ext4_pspace_cachep);
2964 kmem_cache_destroy(ext4_ac_cachep);
2965 kmem_cache_destroy(ext4_free_data_cachep);
2966 ext4_groupinfo_destroy_slabs();
2971 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2972 * Returns 0 if success or error code
2974 static noinline_for_stack int
2975 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2976 handle_t *handle, unsigned int reserv_clstrs)
2978 struct buffer_head *bitmap_bh = NULL;
2979 struct ext4_group_desc *gdp;
2980 struct buffer_head *gdp_bh;
2981 struct ext4_sb_info *sbi;
2982 struct super_block *sb;
2983 ext4_fsblk_t block;
2984 int err, len;
2986 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2987 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2989 sb = ac->ac_sb;
2990 sbi = EXT4_SB(sb);
2992 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2993 if (IS_ERR(bitmap_bh)) {
2994 err = PTR_ERR(bitmap_bh);
2995 bitmap_bh = NULL;
2996 goto out_err;
2999 BUFFER_TRACE(bitmap_bh, "getting write access");
3000 err = ext4_journal_get_write_access(handle, bitmap_bh);
3001 if (err)
3002 goto out_err;
3004 err = -EIO;
3005 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3006 if (!gdp)
3007 goto out_err;
3009 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
3010 ext4_free_group_clusters(sb, gdp));
3012 BUFFER_TRACE(gdp_bh, "get_write_access");
3013 err = ext4_journal_get_write_access(handle, gdp_bh);
3014 if (err)
3015 goto out_err;
3017 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3019 len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3020 if (!ext4_data_block_valid(sbi, block, len)) {
3021 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
3022 "fs metadata", block, block+len);
3023 /* File system mounted not to panic on error
3024 * Fix the bitmap and return EFSCORRUPTED
3025 * We leak some of the blocks here.
3027 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3028 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3029 ac->ac_b_ex.fe_len);
3030 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3031 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3032 if (!err)
3033 err = -EFSCORRUPTED;
3034 goto out_err;
3037 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3038 #ifdef AGGRESSIVE_CHECK
3040 int i;
3041 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3042 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3043 bitmap_bh->b_data));
3046 #endif
3047 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3048 ac->ac_b_ex.fe_len);
3049 if (ext4_has_group_desc_csum(sb) &&
3050 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3051 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3052 ext4_free_group_clusters_set(sb, gdp,
3053 ext4_free_clusters_after_init(sb,
3054 ac->ac_b_ex.fe_group, gdp));
3056 len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
3057 ext4_free_group_clusters_set(sb, gdp, len);
3058 ext4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);
3059 ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
3061 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3062 percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
3064 * Now reduce the dirty block count also. Should not go negative
3066 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3067 /* release all the reserved blocks if non delalloc */
3068 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
3069 reserv_clstrs);
3071 if (sbi->s_log_groups_per_flex) {
3072 ext4_group_t flex_group = ext4_flex_group(sbi,
3073 ac->ac_b_ex.fe_group);
3074 atomic64_sub(ac->ac_b_ex.fe_len,
3075 &sbi_array_rcu_deref(sbi, s_flex_groups,
3076 flex_group)->free_clusters);
3079 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3080 if (err)
3081 goto out_err;
3082 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3084 out_err:
3085 brelse(bitmap_bh);
3086 return err;
3090 * here we normalize request for locality group
3091 * Group request are normalized to s_mb_group_prealloc, which goes to
3092 * s_strip if we set the same via mount option.
3093 * s_mb_group_prealloc can be configured via
3094 * /sys/fs/ext4/<partition>/mb_group_prealloc
3096 * XXX: should we try to preallocate more than the group has now?
3098 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3100 struct super_block *sb = ac->ac_sb;
3101 struct ext4_locality_group *lg = ac->ac_lg;
3103 BUG_ON(lg == NULL);
3104 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3105 mb_debug(1, "#%u: goal %u blocks for locality group\n",
3106 current->pid, ac->ac_g_ex.fe_len);
3110 * Normalization means making request better in terms of
3111 * size and alignment
3113 static noinline_for_stack void
3114 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3115 struct ext4_allocation_request *ar)
3117 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3118 int bsbits, max;
3119 ext4_lblk_t end;
3120 loff_t size, start_off;
3121 loff_t orig_size __maybe_unused;
3122 ext4_lblk_t start;
3123 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3124 struct ext4_prealloc_space *pa;
3126 /* do normalize only data requests, metadata requests
3127 do not need preallocation */
3128 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3129 return;
3131 /* sometime caller may want exact blocks */
3132 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3133 return;
3135 /* caller may indicate that preallocation isn't
3136 * required (it's a tail, for example) */
3137 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3138 return;
3140 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3141 ext4_mb_normalize_group_request(ac);
3142 return ;
3145 bsbits = ac->ac_sb->s_blocksize_bits;
3147 /* first, let's learn actual file size
3148 * given current request is allocated */
3149 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
3150 size = size << bsbits;
3151 if (size < i_size_read(ac->ac_inode))
3152 size = i_size_read(ac->ac_inode);
3153 orig_size = size;
3155 /* max size of free chunks */
3156 max = 2 << bsbits;
3158 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
3159 (req <= (size) || max <= (chunk_size))
3161 /* first, try to predict filesize */
3162 /* XXX: should this table be tunable? */
3163 start_off = 0;
3164 if (size <= 16 * 1024) {
3165 size = 16 * 1024;
3166 } else if (size <= 32 * 1024) {
3167 size = 32 * 1024;
3168 } else if (size <= 64 * 1024) {
3169 size = 64 * 1024;
3170 } else if (size <= 128 * 1024) {
3171 size = 128 * 1024;
3172 } else if (size <= 256 * 1024) {
3173 size = 256 * 1024;
3174 } else if (size <= 512 * 1024) {
3175 size = 512 * 1024;
3176 } else if (size <= 1024 * 1024) {
3177 size = 1024 * 1024;
3178 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3179 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3180 (21 - bsbits)) << 21;
3181 size = 2 * 1024 * 1024;
3182 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3183 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3184 (22 - bsbits)) << 22;
3185 size = 4 * 1024 * 1024;
3186 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3187 (8<<20)>>bsbits, max, 8 * 1024)) {
3188 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3189 (23 - bsbits)) << 23;
3190 size = 8 * 1024 * 1024;
3191 } else {
3192 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
3193 size = (loff_t) EXT4_C2B(EXT4_SB(ac->ac_sb),
3194 ac->ac_o_ex.fe_len) << bsbits;
3196 size = size >> bsbits;
3197 start = start_off >> bsbits;
3199 /* don't cover already allocated blocks in selected range */
3200 if (ar->pleft && start <= ar->lleft) {
3201 size -= ar->lleft + 1 - start;
3202 start = ar->lleft + 1;
3204 if (ar->pright && start + size - 1 >= ar->lright)
3205 size -= start + size - ar->lright;
3208 * Trim allocation request for filesystems with artificially small
3209 * groups.
3211 if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
3212 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
3214 end = start + size;
3216 /* check we don't cross already preallocated blocks */
3217 rcu_read_lock();
3218 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3219 ext4_lblk_t pa_end;
3221 if (pa->pa_deleted)
3222 continue;
3223 spin_lock(&pa->pa_lock);
3224 if (pa->pa_deleted) {
3225 spin_unlock(&pa->pa_lock);
3226 continue;
3229 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3230 pa->pa_len);
3232 /* PA must not overlap original request */
3233 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3234 ac->ac_o_ex.fe_logical < pa->pa_lstart));
3236 /* skip PAs this normalized request doesn't overlap with */
3237 if (pa->pa_lstart >= end || pa_end <= start) {
3238 spin_unlock(&pa->pa_lock);
3239 continue;
3241 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3243 /* adjust start or end to be adjacent to this pa */
3244 if (pa_end <= ac->ac_o_ex.fe_logical) {
3245 BUG_ON(pa_end < start);
3246 start = pa_end;
3247 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3248 BUG_ON(pa->pa_lstart > end);
3249 end = pa->pa_lstart;
3251 spin_unlock(&pa->pa_lock);
3253 rcu_read_unlock();
3254 size = end - start;
3256 /* XXX: extra loop to check we really don't overlap preallocations */
3257 rcu_read_lock();
3258 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3259 ext4_lblk_t pa_end;
3261 spin_lock(&pa->pa_lock);
3262 if (pa->pa_deleted == 0) {
3263 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3264 pa->pa_len);
3265 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3267 spin_unlock(&pa->pa_lock);
3269 rcu_read_unlock();
3271 if (start + size <= ac->ac_o_ex.fe_logical &&
3272 start > ac->ac_o_ex.fe_logical) {
3273 ext4_msg(ac->ac_sb, KERN_ERR,
3274 "start %lu, size %lu, fe_logical %lu",
3275 (unsigned long) start, (unsigned long) size,
3276 (unsigned long) ac->ac_o_ex.fe_logical);
3277 BUG();
3279 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3281 /* now prepare goal request */
3283 /* XXX: is it better to align blocks WRT to logical
3284 * placement or satisfy big request as is */
3285 ac->ac_g_ex.fe_logical = start;
3286 ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3288 /* define goal start in order to merge */
3289 if (ar->pright && (ar->lright == (start + size))) {
3290 /* merge to the right */
3291 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3292 &ac->ac_f_ex.fe_group,
3293 &ac->ac_f_ex.fe_start);
3294 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3296 if (ar->pleft && (ar->lleft + 1 == start)) {
3297 /* merge to the left */
3298 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3299 &ac->ac_f_ex.fe_group,
3300 &ac->ac_f_ex.fe_start);
3301 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3304 mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3305 (unsigned) orig_size, (unsigned) start);
3308 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3310 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3312 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3313 atomic_inc(&sbi->s_bal_reqs);
3314 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3315 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3316 atomic_inc(&sbi->s_bal_success);
3317 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3318 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3319 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3320 atomic_inc(&sbi->s_bal_goals);
3321 if (ac->ac_found > sbi->s_mb_max_to_scan)
3322 atomic_inc(&sbi->s_bal_breaks);
3325 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3326 trace_ext4_mballoc_alloc(ac);
3327 else
3328 trace_ext4_mballoc_prealloc(ac);
3332 * Called on failure; free up any blocks from the inode PA for this
3333 * context. We don't need this for MB_GROUP_PA because we only change
3334 * pa_free in ext4_mb_release_context(), but on failure, we've already
3335 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3337 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3339 struct ext4_prealloc_space *pa = ac->ac_pa;
3340 struct ext4_buddy e4b;
3341 int err;
3343 if (pa == NULL) {
3344 if (ac->ac_f_ex.fe_len == 0)
3345 return;
3346 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
3347 if (err) {
3349 * This should never happen since we pin the
3350 * pages in the ext4_allocation_context so
3351 * ext4_mb_load_buddy() should never fail.
3353 WARN(1, "mb_load_buddy failed (%d)", err);
3354 return;
3356 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3357 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
3358 ac->ac_f_ex.fe_len);
3359 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3360 ext4_mb_unload_buddy(&e4b);
3361 return;
3363 if (pa->pa_type == MB_INODE_PA)
3364 pa->pa_free += ac->ac_b_ex.fe_len;
3368 * use blocks preallocated to inode
3370 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3371 struct ext4_prealloc_space *pa)
3373 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3374 ext4_fsblk_t start;
3375 ext4_fsblk_t end;
3376 int len;
3378 /* found preallocated blocks, use them */
3379 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3380 end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
3381 start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
3382 len = EXT4_NUM_B2C(sbi, end - start);
3383 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3384 &ac->ac_b_ex.fe_start);
3385 ac->ac_b_ex.fe_len = len;
3386 ac->ac_status = AC_STATUS_FOUND;
3387 ac->ac_pa = pa;
3389 BUG_ON(start < pa->pa_pstart);
3390 BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3391 BUG_ON(pa->pa_free < len);
3392 pa->pa_free -= len;
3394 mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3398 * use blocks preallocated to locality group
3400 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3401 struct ext4_prealloc_space *pa)
3403 unsigned int len = ac->ac_o_ex.fe_len;
3405 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3406 &ac->ac_b_ex.fe_group,
3407 &ac->ac_b_ex.fe_start);
3408 ac->ac_b_ex.fe_len = len;
3409 ac->ac_status = AC_STATUS_FOUND;
3410 ac->ac_pa = pa;
3412 /* we don't correct pa_pstart or pa_plen here to avoid
3413 * possible race when the group is being loaded concurrently
3414 * instead we correct pa later, after blocks are marked
3415 * in on-disk bitmap -- see ext4_mb_release_context()
3416 * Other CPUs are prevented from allocating from this pa by lg_mutex
3418 mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3422 * Return the prealloc space that have minimal distance
3423 * from the goal block. @cpa is the prealloc
3424 * space that is having currently known minimal distance
3425 * from the goal block.
3427 static struct ext4_prealloc_space *
3428 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3429 struct ext4_prealloc_space *pa,
3430 struct ext4_prealloc_space *cpa)
3432 ext4_fsblk_t cur_distance, new_distance;
3434 if (cpa == NULL) {
3435 atomic_inc(&pa->pa_count);
3436 return pa;
3438 cur_distance = abs(goal_block - cpa->pa_pstart);
3439 new_distance = abs(goal_block - pa->pa_pstart);
3441 if (cur_distance <= new_distance)
3442 return cpa;
3444 /* drop the previous reference */
3445 atomic_dec(&cpa->pa_count);
3446 atomic_inc(&pa->pa_count);
3447 return pa;
3451 * search goal blocks in preallocated space
3453 static noinline_for_stack int
3454 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3456 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3457 int order, i;
3458 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3459 struct ext4_locality_group *lg;
3460 struct ext4_prealloc_space *pa, *cpa = NULL;
3461 ext4_fsblk_t goal_block;
3463 /* only data can be preallocated */
3464 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3465 return 0;
3467 /* first, try per-file preallocation */
3468 rcu_read_lock();
3469 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3471 /* all fields in this condition don't change,
3472 * so we can skip locking for them */
3473 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3474 ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
3475 EXT4_C2B(sbi, pa->pa_len)))
3476 continue;
3478 /* non-extent files can't have physical blocks past 2^32 */
3479 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3480 (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
3481 EXT4_MAX_BLOCK_FILE_PHYS))
3482 continue;
3484 /* found preallocated blocks, use them */
3485 spin_lock(&pa->pa_lock);
3486 if (pa->pa_deleted == 0 && pa->pa_free) {
3487 atomic_inc(&pa->pa_count);
3488 ext4_mb_use_inode_pa(ac, pa);
3489 spin_unlock(&pa->pa_lock);
3490 ac->ac_criteria = 10;
3491 rcu_read_unlock();
3492 return 1;
3494 spin_unlock(&pa->pa_lock);
3496 rcu_read_unlock();
3498 /* can we use group allocation? */
3499 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3500 return 0;
3502 /* inode may have no locality group for some reason */
3503 lg = ac->ac_lg;
3504 if (lg == NULL)
3505 return 0;
3506 order = fls(ac->ac_o_ex.fe_len) - 1;
3507 if (order > PREALLOC_TB_SIZE - 1)
3508 /* The max size of hash table is PREALLOC_TB_SIZE */
3509 order = PREALLOC_TB_SIZE - 1;
3511 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3513 * search for the prealloc space that is having
3514 * minimal distance from the goal block.
3516 for (i = order; i < PREALLOC_TB_SIZE; i++) {
3517 rcu_read_lock();
3518 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3519 pa_inode_list) {
3520 spin_lock(&pa->pa_lock);
3521 if (pa->pa_deleted == 0 &&
3522 pa->pa_free >= ac->ac_o_ex.fe_len) {
3524 cpa = ext4_mb_check_group_pa(goal_block,
3525 pa, cpa);
3527 spin_unlock(&pa->pa_lock);
3529 rcu_read_unlock();
3531 if (cpa) {
3532 ext4_mb_use_group_pa(ac, cpa);
3533 ac->ac_criteria = 20;
3534 return 1;
3536 return 0;
3540 * the function goes through all block freed in the group
3541 * but not yet committed and marks them used in in-core bitmap.
3542 * buddy must be generated from this bitmap
3543 * Need to be called with the ext4 group lock held
3545 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3546 ext4_group_t group)
3548 struct rb_node *n;
3549 struct ext4_group_info *grp;
3550 struct ext4_free_data *entry;
3552 grp = ext4_get_group_info(sb, group);
3553 n = rb_first(&(grp->bb_free_root));
3555 while (n) {
3556 entry = rb_entry(n, struct ext4_free_data, efd_node);
3557 ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
3558 n = rb_next(n);
3560 return;
3564 * the function goes through all preallocation in this group and marks them
3565 * used in in-core bitmap. buddy must be generated from this bitmap
3566 * Need to be called with ext4 group lock held
3568 static noinline_for_stack
3569 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3570 ext4_group_t group)
3572 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3573 struct ext4_prealloc_space *pa;
3574 struct list_head *cur;
3575 ext4_group_t groupnr;
3576 ext4_grpblk_t start;
3577 int preallocated = 0;
3578 int len;
3580 /* all form of preallocation discards first load group,
3581 * so the only competing code is preallocation use.
3582 * we don't need any locking here
3583 * notice we do NOT ignore preallocations with pa_deleted
3584 * otherwise we could leave used blocks available for
3585 * allocation in buddy when concurrent ext4_mb_put_pa()
3586 * is dropping preallocation
3588 list_for_each(cur, &grp->bb_prealloc_list) {
3589 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3590 spin_lock(&pa->pa_lock);
3591 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3592 &groupnr, &start);
3593 len = pa->pa_len;
3594 spin_unlock(&pa->pa_lock);
3595 if (unlikely(len == 0))
3596 continue;
3597 BUG_ON(groupnr != group);
3598 ext4_set_bits(bitmap, start, len);
3599 preallocated += len;
3601 mb_debug(1, "preallocated %u for group %u\n", preallocated, group);
3604 static void ext4_mb_pa_callback(struct rcu_head *head)
3606 struct ext4_prealloc_space *pa;
3607 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3609 BUG_ON(atomic_read(&pa->pa_count));
3610 BUG_ON(pa->pa_deleted == 0);
3611 kmem_cache_free(ext4_pspace_cachep, pa);
3615 * drops a reference to preallocated space descriptor
3616 * if this was the last reference and the space is consumed
3618 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3619 struct super_block *sb, struct ext4_prealloc_space *pa)
3621 ext4_group_t grp;
3622 ext4_fsblk_t grp_blk;
3624 /* in this short window concurrent discard can set pa_deleted */
3625 spin_lock(&pa->pa_lock);
3626 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
3627 spin_unlock(&pa->pa_lock);
3628 return;
3631 if (pa->pa_deleted == 1) {
3632 spin_unlock(&pa->pa_lock);
3633 return;
3636 pa->pa_deleted = 1;
3637 spin_unlock(&pa->pa_lock);
3639 grp_blk = pa->pa_pstart;
3641 * If doing group-based preallocation, pa_pstart may be in the
3642 * next group when pa is used up
3644 if (pa->pa_type == MB_GROUP_PA)
3645 grp_blk--;
3647 grp = ext4_get_group_number(sb, grp_blk);
3650 * possible race:
3652 * P1 (buddy init) P2 (regular allocation)
3653 * find block B in PA
3654 * copy on-disk bitmap to buddy
3655 * mark B in on-disk bitmap
3656 * drop PA from group
3657 * mark all PAs in buddy
3659 * thus, P1 initializes buddy with B available. to prevent this
3660 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3661 * against that pair
3663 ext4_lock_group(sb, grp);
3664 list_del(&pa->pa_group_list);
3665 ext4_unlock_group(sb, grp);
3667 spin_lock(pa->pa_obj_lock);
3668 list_del_rcu(&pa->pa_inode_list);
3669 spin_unlock(pa->pa_obj_lock);
3671 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3675 * creates new preallocated space for given inode
3677 static noinline_for_stack int
3678 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3680 struct super_block *sb = ac->ac_sb;
3681 struct ext4_sb_info *sbi = EXT4_SB(sb);
3682 struct ext4_prealloc_space *pa;
3683 struct ext4_group_info *grp;
3684 struct ext4_inode_info *ei;
3686 /* preallocate only when found space is larger then requested */
3687 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3688 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3689 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3691 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3692 if (pa == NULL)
3693 return -ENOMEM;
3695 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3696 int winl;
3697 int wins;
3698 int win;
3699 int offs;
3701 /* we can't allocate as much as normalizer wants.
3702 * so, found space must get proper lstart
3703 * to cover original request */
3704 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3705 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3707 /* we're limited by original request in that
3708 * logical block must be covered any way
3709 * winl is window we can move our chunk within */
3710 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3712 /* also, we should cover whole original request */
3713 wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
3715 /* the smallest one defines real window */
3716 win = min(winl, wins);
3718 offs = ac->ac_o_ex.fe_logical %
3719 EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3720 if (offs && offs < win)
3721 win = offs;
3723 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
3724 EXT4_NUM_B2C(sbi, win);
3725 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3726 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3729 /* preallocation can change ac_b_ex, thus we store actually
3730 * allocated blocks for history */
3731 ac->ac_f_ex = ac->ac_b_ex;
3733 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3734 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3735 pa->pa_len = ac->ac_b_ex.fe_len;
3736 pa->pa_free = pa->pa_len;
3737 atomic_set(&pa->pa_count, 1);
3738 spin_lock_init(&pa->pa_lock);
3739 INIT_LIST_HEAD(&pa->pa_inode_list);
3740 INIT_LIST_HEAD(&pa->pa_group_list);
3741 pa->pa_deleted = 0;
3742 pa->pa_type = MB_INODE_PA;
3744 mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3745 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3746 trace_ext4_mb_new_inode_pa(ac, pa);
3748 ext4_mb_use_inode_pa(ac, pa);
3749 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
3751 ei = EXT4_I(ac->ac_inode);
3752 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3754 pa->pa_obj_lock = &ei->i_prealloc_lock;
3755 pa->pa_inode = ac->ac_inode;
3757 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3758 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3759 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3761 spin_lock(pa->pa_obj_lock);
3762 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3763 spin_unlock(pa->pa_obj_lock);
3765 return 0;
3769 * creates new preallocated space for locality group inodes belongs to
3771 static noinline_for_stack int
3772 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3774 struct super_block *sb = ac->ac_sb;
3775 struct ext4_locality_group *lg;
3776 struct ext4_prealloc_space *pa;
3777 struct ext4_group_info *grp;
3779 /* preallocate only when found space is larger then requested */
3780 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3781 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3782 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3784 BUG_ON(ext4_pspace_cachep == NULL);
3785 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3786 if (pa == NULL)
3787 return -ENOMEM;
3789 /* preallocation can change ac_b_ex, thus we store actually
3790 * allocated blocks for history */
3791 ac->ac_f_ex = ac->ac_b_ex;
3793 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3794 pa->pa_lstart = pa->pa_pstart;
3795 pa->pa_len = ac->ac_b_ex.fe_len;
3796 pa->pa_free = pa->pa_len;
3797 atomic_set(&pa->pa_count, 1);
3798 spin_lock_init(&pa->pa_lock);
3799 INIT_LIST_HEAD(&pa->pa_inode_list);
3800 INIT_LIST_HEAD(&pa->pa_group_list);
3801 pa->pa_deleted = 0;
3802 pa->pa_type = MB_GROUP_PA;
3804 mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3805 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3806 trace_ext4_mb_new_group_pa(ac, pa);
3808 ext4_mb_use_group_pa(ac, pa);
3809 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3811 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3812 lg = ac->ac_lg;
3813 BUG_ON(lg == NULL);
3815 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3816 pa->pa_inode = NULL;
3818 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3819 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3820 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3823 * We will later add the new pa to the right bucket
3824 * after updating the pa_free in ext4_mb_release_context
3826 return 0;
3829 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3831 int err;
3833 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3834 err = ext4_mb_new_group_pa(ac);
3835 else
3836 err = ext4_mb_new_inode_pa(ac);
3837 return err;
3841 * finds all unused blocks in on-disk bitmap, frees them in
3842 * in-core bitmap and buddy.
3843 * @pa must be unlinked from inode and group lists, so that
3844 * nobody else can find/use it.
3845 * the caller MUST hold group/inode locks.
3846 * TODO: optimize the case when there are no in-core structures yet
3848 static noinline_for_stack int
3849 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3850 struct ext4_prealloc_space *pa)
3852 struct super_block *sb = e4b->bd_sb;
3853 struct ext4_sb_info *sbi = EXT4_SB(sb);
3854 unsigned int end;
3855 unsigned int next;
3856 ext4_group_t group;
3857 ext4_grpblk_t bit;
3858 unsigned long long grp_blk_start;
3859 int err = 0;
3860 int free = 0;
3862 BUG_ON(pa->pa_deleted == 0);
3863 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3864 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
3865 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3866 end = bit + pa->pa_len;
3868 while (bit < end) {
3869 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3870 if (bit >= end)
3871 break;
3872 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3873 mb_debug(1, " free preallocated %u/%u in group %u\n",
3874 (unsigned) ext4_group_first_block_no(sb, group) + bit,
3875 (unsigned) next - bit, (unsigned) group);
3876 free += next - bit;
3878 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
3879 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
3880 EXT4_C2B(sbi, bit)),
3881 next - bit);
3882 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3883 bit = next + 1;
3885 if (free != pa->pa_free) {
3886 ext4_msg(e4b->bd_sb, KERN_CRIT,
3887 "pa %p: logic %lu, phys. %lu, len %lu",
3888 pa, (unsigned long) pa->pa_lstart,
3889 (unsigned long) pa->pa_pstart,
3890 (unsigned long) pa->pa_len);
3891 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
3892 free, pa->pa_free);
3894 * pa is already deleted so we use the value obtained
3895 * from the bitmap and continue.
3898 atomic_add(free, &sbi->s_mb_discarded);
3900 return err;
3903 static noinline_for_stack int
3904 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3905 struct ext4_prealloc_space *pa)
3907 struct super_block *sb = e4b->bd_sb;
3908 ext4_group_t group;
3909 ext4_grpblk_t bit;
3911 trace_ext4_mb_release_group_pa(sb, pa);
3912 BUG_ON(pa->pa_deleted == 0);
3913 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3914 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3915 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3916 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3917 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3919 return 0;
3923 * releases all preallocations in given group
3925 * first, we need to decide discard policy:
3926 * - when do we discard
3927 * 1) ENOSPC
3928 * - how many do we discard
3929 * 1) how many requested
3931 static noinline_for_stack int
3932 ext4_mb_discard_group_preallocations(struct super_block *sb,
3933 ext4_group_t group, int needed)
3935 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3936 struct buffer_head *bitmap_bh = NULL;
3937 struct ext4_prealloc_space *pa, *tmp;
3938 struct list_head list;
3939 struct ext4_buddy e4b;
3940 int err;
3941 int busy = 0;
3942 int free = 0;
3944 mb_debug(1, "discard preallocation for group %u\n", group);
3946 if (list_empty(&grp->bb_prealloc_list))
3947 return 0;
3949 bitmap_bh = ext4_read_block_bitmap(sb, group);
3950 if (IS_ERR(bitmap_bh)) {
3951 err = PTR_ERR(bitmap_bh);
3952 ext4_error(sb, "Error %d reading block bitmap for %u",
3953 err, group);
3954 return 0;
3957 err = ext4_mb_load_buddy(sb, group, &e4b);
3958 if (err) {
3959 ext4_warning(sb, "Error %d loading buddy information for %u",
3960 err, group);
3961 put_bh(bitmap_bh);
3962 return 0;
3965 if (needed == 0)
3966 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
3968 INIT_LIST_HEAD(&list);
3969 repeat:
3970 ext4_lock_group(sb, group);
3971 list_for_each_entry_safe(pa, tmp,
3972 &grp->bb_prealloc_list, pa_group_list) {
3973 spin_lock(&pa->pa_lock);
3974 if (atomic_read(&pa->pa_count)) {
3975 spin_unlock(&pa->pa_lock);
3976 busy = 1;
3977 continue;
3979 if (pa->pa_deleted) {
3980 spin_unlock(&pa->pa_lock);
3981 continue;
3984 /* seems this one can be freed ... */
3985 pa->pa_deleted = 1;
3987 /* we can trust pa_free ... */
3988 free += pa->pa_free;
3990 spin_unlock(&pa->pa_lock);
3992 list_del(&pa->pa_group_list);
3993 list_add(&pa->u.pa_tmp_list, &list);
3996 /* if we still need more blocks and some PAs were used, try again */
3997 if (free < needed && busy) {
3998 busy = 0;
3999 ext4_unlock_group(sb, group);
4000 cond_resched();
4001 goto repeat;
4004 /* found anything to free? */
4005 if (list_empty(&list)) {
4006 BUG_ON(free != 0);
4007 goto out;
4010 /* now free all selected PAs */
4011 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4013 /* remove from object (inode or locality group) */
4014 spin_lock(pa->pa_obj_lock);
4015 list_del_rcu(&pa->pa_inode_list);
4016 spin_unlock(pa->pa_obj_lock);
4018 if (pa->pa_type == MB_GROUP_PA)
4019 ext4_mb_release_group_pa(&e4b, pa);
4020 else
4021 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4023 list_del(&pa->u.pa_tmp_list);
4024 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4027 out:
4028 ext4_unlock_group(sb, group);
4029 ext4_mb_unload_buddy(&e4b);
4030 put_bh(bitmap_bh);
4031 return free;
4035 * releases all non-used preallocated blocks for given inode
4037 * It's important to discard preallocations under i_data_sem
4038 * We don't want another block to be served from the prealloc
4039 * space when we are discarding the inode prealloc space.
4041 * FIXME!! Make sure it is valid at all the call sites
4043 void ext4_discard_preallocations(struct inode *inode)
4045 struct ext4_inode_info *ei = EXT4_I(inode);
4046 struct super_block *sb = inode->i_sb;
4047 struct buffer_head *bitmap_bh = NULL;
4048 struct ext4_prealloc_space *pa, *tmp;
4049 ext4_group_t group = 0;
4050 struct list_head list;
4051 struct ext4_buddy e4b;
4052 int err;
4054 if (!S_ISREG(inode->i_mode)) {
4055 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4056 return;
4059 mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
4060 trace_ext4_discard_preallocations(inode);
4062 INIT_LIST_HEAD(&list);
4064 repeat:
4065 /* first, collect all pa's in the inode */
4066 spin_lock(&ei->i_prealloc_lock);
4067 while (!list_empty(&ei->i_prealloc_list)) {
4068 pa = list_entry(ei->i_prealloc_list.next,
4069 struct ext4_prealloc_space, pa_inode_list);
4070 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4071 spin_lock(&pa->pa_lock);
4072 if (atomic_read(&pa->pa_count)) {
4073 /* this shouldn't happen often - nobody should
4074 * use preallocation while we're discarding it */
4075 spin_unlock(&pa->pa_lock);
4076 spin_unlock(&ei->i_prealloc_lock);
4077 ext4_msg(sb, KERN_ERR,
4078 "uh-oh! used pa while discarding");
4079 WARN_ON(1);
4080 schedule_timeout_uninterruptible(HZ);
4081 goto repeat;
4084 if (pa->pa_deleted == 0) {
4085 pa->pa_deleted = 1;
4086 spin_unlock(&pa->pa_lock);
4087 list_del_rcu(&pa->pa_inode_list);
4088 list_add(&pa->u.pa_tmp_list, &list);
4089 continue;
4092 /* someone is deleting pa right now */
4093 spin_unlock(&pa->pa_lock);
4094 spin_unlock(&ei->i_prealloc_lock);
4096 /* we have to wait here because pa_deleted
4097 * doesn't mean pa is already unlinked from
4098 * the list. as we might be called from
4099 * ->clear_inode() the inode will get freed
4100 * and concurrent thread which is unlinking
4101 * pa from inode's list may access already
4102 * freed memory, bad-bad-bad */
4104 /* XXX: if this happens too often, we can
4105 * add a flag to force wait only in case
4106 * of ->clear_inode(), but not in case of
4107 * regular truncate */
4108 schedule_timeout_uninterruptible(HZ);
4109 goto repeat;
4111 spin_unlock(&ei->i_prealloc_lock);
4113 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4114 BUG_ON(pa->pa_type != MB_INODE_PA);
4115 group = ext4_get_group_number(sb, pa->pa_pstart);
4117 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4118 GFP_NOFS|__GFP_NOFAIL);
4119 if (err) {
4120 ext4_error(sb, "Error %d loading buddy information for %u",
4121 err, group);
4122 continue;
4125 bitmap_bh = ext4_read_block_bitmap(sb, group);
4126 if (IS_ERR(bitmap_bh)) {
4127 err = PTR_ERR(bitmap_bh);
4128 ext4_error(sb, "Error %d reading block bitmap for %u",
4129 err, group);
4130 ext4_mb_unload_buddy(&e4b);
4131 continue;
4134 ext4_lock_group(sb, group);
4135 list_del(&pa->pa_group_list);
4136 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4137 ext4_unlock_group(sb, group);
4139 ext4_mb_unload_buddy(&e4b);
4140 put_bh(bitmap_bh);
4142 list_del(&pa->u.pa_tmp_list);
4143 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4147 #ifdef CONFIG_EXT4_DEBUG
4148 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4150 struct super_block *sb = ac->ac_sb;
4151 ext4_group_t ngroups, i;
4153 if (!ext4_mballoc_debug ||
4154 (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
4155 return;
4157 ext4_msg(ac->ac_sb, KERN_ERR, "Can't allocate:"
4158 " Allocation context details:");
4159 ext4_msg(ac->ac_sb, KERN_ERR, "status %d flags %d",
4160 ac->ac_status, ac->ac_flags);
4161 ext4_msg(ac->ac_sb, KERN_ERR, "orig %lu/%lu/%lu@%lu, "
4162 "goal %lu/%lu/%lu@%lu, "
4163 "best %lu/%lu/%lu@%lu cr %d",
4164 (unsigned long)ac->ac_o_ex.fe_group,
4165 (unsigned long)ac->ac_o_ex.fe_start,
4166 (unsigned long)ac->ac_o_ex.fe_len,
4167 (unsigned long)ac->ac_o_ex.fe_logical,
4168 (unsigned long)ac->ac_g_ex.fe_group,
4169 (unsigned long)ac->ac_g_ex.fe_start,
4170 (unsigned long)ac->ac_g_ex.fe_len,
4171 (unsigned long)ac->ac_g_ex.fe_logical,
4172 (unsigned long)ac->ac_b_ex.fe_group,
4173 (unsigned long)ac->ac_b_ex.fe_start,
4174 (unsigned long)ac->ac_b_ex.fe_len,
4175 (unsigned long)ac->ac_b_ex.fe_logical,
4176 (int)ac->ac_criteria);
4177 ext4_msg(ac->ac_sb, KERN_ERR, "%d found", ac->ac_found);
4178 ext4_msg(ac->ac_sb, KERN_ERR, "groups: ");
4179 ngroups = ext4_get_groups_count(sb);
4180 for (i = 0; i < ngroups; i++) {
4181 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4182 struct ext4_prealloc_space *pa;
4183 ext4_grpblk_t start;
4184 struct list_head *cur;
4185 ext4_lock_group(sb, i);
4186 list_for_each(cur, &grp->bb_prealloc_list) {
4187 pa = list_entry(cur, struct ext4_prealloc_space,
4188 pa_group_list);
4189 spin_lock(&pa->pa_lock);
4190 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4191 NULL, &start);
4192 spin_unlock(&pa->pa_lock);
4193 printk(KERN_ERR "PA:%u:%d:%u \n", i,
4194 start, pa->pa_len);
4196 ext4_unlock_group(sb, i);
4198 if (grp->bb_free == 0)
4199 continue;
4200 printk(KERN_ERR "%u: %d/%d \n",
4201 i, grp->bb_free, grp->bb_fragments);
4203 printk(KERN_ERR "\n");
4205 #else
4206 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4208 return;
4210 #endif
4213 * We use locality group preallocation for small size file. The size of the
4214 * file is determined by the current size or the resulting size after
4215 * allocation which ever is larger
4217 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4219 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4221 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4222 int bsbits = ac->ac_sb->s_blocksize_bits;
4223 loff_t size, isize;
4225 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4226 return;
4228 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4229 return;
4231 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
4232 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
4233 >> bsbits;
4235 if ((size == isize) &&
4236 !ext4_fs_is_busy(sbi) &&
4237 (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
4238 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
4239 return;
4242 if (sbi->s_mb_group_prealloc <= 0) {
4243 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4244 return;
4247 /* don't use group allocation for large files */
4248 size = max(size, isize);
4249 if (size > sbi->s_mb_stream_request) {
4250 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4251 return;
4254 BUG_ON(ac->ac_lg != NULL);
4256 * locality group prealloc space are per cpu. The reason for having
4257 * per cpu locality group is to reduce the contention between block
4258 * request from multiple CPUs.
4260 ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
4262 /* we're going to use group allocation */
4263 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4265 /* serialize all allocations in the group */
4266 mutex_lock(&ac->ac_lg->lg_mutex);
4269 static noinline_for_stack int
4270 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4271 struct ext4_allocation_request *ar)
4273 struct super_block *sb = ar->inode->i_sb;
4274 struct ext4_sb_info *sbi = EXT4_SB(sb);
4275 struct ext4_super_block *es = sbi->s_es;
4276 ext4_group_t group;
4277 unsigned int len;
4278 ext4_fsblk_t goal;
4279 ext4_grpblk_t block;
4281 /* we can't allocate > group size */
4282 len = ar->len;
4284 /* just a dirty hack to filter too big requests */
4285 if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
4286 len = EXT4_CLUSTERS_PER_GROUP(sb);
4288 /* start searching from the goal */
4289 goal = ar->goal;
4290 if (goal < le32_to_cpu(es->s_first_data_block) ||
4291 goal >= ext4_blocks_count(es))
4292 goal = le32_to_cpu(es->s_first_data_block);
4293 ext4_get_group_no_and_offset(sb, goal, &group, &block);
4295 /* set up allocation goals */
4296 ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
4297 ac->ac_status = AC_STATUS_CONTINUE;
4298 ac->ac_sb = sb;
4299 ac->ac_inode = ar->inode;
4300 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4301 ac->ac_o_ex.fe_group = group;
4302 ac->ac_o_ex.fe_start = block;
4303 ac->ac_o_ex.fe_len = len;
4304 ac->ac_g_ex = ac->ac_o_ex;
4305 ac->ac_flags = ar->flags;
4307 /* we have to define context: we'll we work with a file or
4308 * locality group. this is a policy, actually */
4309 ext4_mb_group_or_file(ac);
4311 mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4312 "left: %u/%u, right %u/%u to %swritable\n",
4313 (unsigned) ar->len, (unsigned) ar->logical,
4314 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4315 (unsigned) ar->lleft, (unsigned) ar->pleft,
4316 (unsigned) ar->lright, (unsigned) ar->pright,
4317 atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4318 return 0;
4322 static noinline_for_stack void
4323 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4324 struct ext4_locality_group *lg,
4325 int order, int total_entries)
4327 ext4_group_t group = 0;
4328 struct ext4_buddy e4b;
4329 struct list_head discard_list;
4330 struct ext4_prealloc_space *pa, *tmp;
4332 mb_debug(1, "discard locality group preallocation\n");
4334 INIT_LIST_HEAD(&discard_list);
4336 spin_lock(&lg->lg_prealloc_lock);
4337 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4338 pa_inode_list) {
4339 spin_lock(&pa->pa_lock);
4340 if (atomic_read(&pa->pa_count)) {
4342 * This is the pa that we just used
4343 * for block allocation. So don't
4344 * free that
4346 spin_unlock(&pa->pa_lock);
4347 continue;
4349 if (pa->pa_deleted) {
4350 spin_unlock(&pa->pa_lock);
4351 continue;
4353 /* only lg prealloc space */
4354 BUG_ON(pa->pa_type != MB_GROUP_PA);
4356 /* seems this one can be freed ... */
4357 pa->pa_deleted = 1;
4358 spin_unlock(&pa->pa_lock);
4360 list_del_rcu(&pa->pa_inode_list);
4361 list_add(&pa->u.pa_tmp_list, &discard_list);
4363 total_entries--;
4364 if (total_entries <= 5) {
4366 * we want to keep only 5 entries
4367 * allowing it to grow to 8. This
4368 * mak sure we don't call discard
4369 * soon for this list.
4371 break;
4374 spin_unlock(&lg->lg_prealloc_lock);
4376 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4377 int err;
4379 group = ext4_get_group_number(sb, pa->pa_pstart);
4380 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4381 GFP_NOFS|__GFP_NOFAIL);
4382 if (err) {
4383 ext4_error(sb, "Error %d loading buddy information for %u",
4384 err, group);
4385 continue;
4387 ext4_lock_group(sb, group);
4388 list_del(&pa->pa_group_list);
4389 ext4_mb_release_group_pa(&e4b, pa);
4390 ext4_unlock_group(sb, group);
4392 ext4_mb_unload_buddy(&e4b);
4393 list_del(&pa->u.pa_tmp_list);
4394 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4399 * We have incremented pa_count. So it cannot be freed at this
4400 * point. Also we hold lg_mutex. So no parallel allocation is
4401 * possible from this lg. That means pa_free cannot be updated.
4403 * A parallel ext4_mb_discard_group_preallocations is possible.
4404 * which can cause the lg_prealloc_list to be updated.
4407 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4409 int order, added = 0, lg_prealloc_count = 1;
4410 struct super_block *sb = ac->ac_sb;
4411 struct ext4_locality_group *lg = ac->ac_lg;
4412 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4414 order = fls(pa->pa_free) - 1;
4415 if (order > PREALLOC_TB_SIZE - 1)
4416 /* The max size of hash table is PREALLOC_TB_SIZE */
4417 order = PREALLOC_TB_SIZE - 1;
4418 /* Add the prealloc space to lg */
4419 spin_lock(&lg->lg_prealloc_lock);
4420 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4421 pa_inode_list) {
4422 spin_lock(&tmp_pa->pa_lock);
4423 if (tmp_pa->pa_deleted) {
4424 spin_unlock(&tmp_pa->pa_lock);
4425 continue;
4427 if (!added && pa->pa_free < tmp_pa->pa_free) {
4428 /* Add to the tail of the previous entry */
4429 list_add_tail_rcu(&pa->pa_inode_list,
4430 &tmp_pa->pa_inode_list);
4431 added = 1;
4433 * we want to count the total
4434 * number of entries in the list
4437 spin_unlock(&tmp_pa->pa_lock);
4438 lg_prealloc_count++;
4440 if (!added)
4441 list_add_tail_rcu(&pa->pa_inode_list,
4442 &lg->lg_prealloc_list[order]);
4443 spin_unlock(&lg->lg_prealloc_lock);
4445 /* Now trim the list to be not more than 8 elements */
4446 if (lg_prealloc_count > 8) {
4447 ext4_mb_discard_lg_preallocations(sb, lg,
4448 order, lg_prealloc_count);
4449 return;
4451 return ;
4455 * release all resource we used in allocation
4457 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4459 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4460 struct ext4_prealloc_space *pa = ac->ac_pa;
4461 if (pa) {
4462 if (pa->pa_type == MB_GROUP_PA) {
4463 /* see comment in ext4_mb_use_group_pa() */
4464 spin_lock(&pa->pa_lock);
4465 pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4466 pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4467 pa->pa_free -= ac->ac_b_ex.fe_len;
4468 pa->pa_len -= ac->ac_b_ex.fe_len;
4469 spin_unlock(&pa->pa_lock);
4472 if (pa) {
4474 * We want to add the pa to the right bucket.
4475 * Remove it from the list and while adding
4476 * make sure the list to which we are adding
4477 * doesn't grow big.
4479 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4480 spin_lock(pa->pa_obj_lock);
4481 list_del_rcu(&pa->pa_inode_list);
4482 spin_unlock(pa->pa_obj_lock);
4483 ext4_mb_add_n_trim(ac);
4485 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4487 if (ac->ac_bitmap_page)
4488 put_page(ac->ac_bitmap_page);
4489 if (ac->ac_buddy_page)
4490 put_page(ac->ac_buddy_page);
4491 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4492 mutex_unlock(&ac->ac_lg->lg_mutex);
4493 ext4_mb_collect_stats(ac);
4494 return 0;
4497 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4499 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4500 int ret;
4501 int freed = 0;
4503 trace_ext4_mb_discard_preallocations(sb, needed);
4504 for (i = 0; i < ngroups && needed > 0; i++) {
4505 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4506 freed += ret;
4507 needed -= ret;
4510 return freed;
4514 * Main entry point into mballoc to allocate blocks
4515 * it tries to use preallocation first, then falls back
4516 * to usual allocation
4518 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4519 struct ext4_allocation_request *ar, int *errp)
4521 int freed;
4522 struct ext4_allocation_context *ac = NULL;
4523 struct ext4_sb_info *sbi;
4524 struct super_block *sb;
4525 ext4_fsblk_t block = 0;
4526 unsigned int inquota = 0;
4527 unsigned int reserv_clstrs = 0;
4529 might_sleep();
4530 sb = ar->inode->i_sb;
4531 sbi = EXT4_SB(sb);
4533 trace_ext4_request_blocks(ar);
4535 /* Allow to use superuser reservation for quota file */
4536 if (ext4_is_quota_file(ar->inode))
4537 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
4539 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
4540 /* Without delayed allocation we need to verify
4541 * there is enough free blocks to do block allocation
4542 * and verify allocation doesn't exceed the quota limits.
4544 while (ar->len &&
4545 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
4547 /* let others to free the space */
4548 cond_resched();
4549 ar->len = ar->len >> 1;
4551 if (!ar->len) {
4552 *errp = -ENOSPC;
4553 return 0;
4555 reserv_clstrs = ar->len;
4556 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
4557 dquot_alloc_block_nofail(ar->inode,
4558 EXT4_C2B(sbi, ar->len));
4559 } else {
4560 while (ar->len &&
4561 dquot_alloc_block(ar->inode,
4562 EXT4_C2B(sbi, ar->len))) {
4564 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4565 ar->len--;
4568 inquota = ar->len;
4569 if (ar->len == 0) {
4570 *errp = -EDQUOT;
4571 goto out;
4575 ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
4576 if (!ac) {
4577 ar->len = 0;
4578 *errp = -ENOMEM;
4579 goto out;
4582 *errp = ext4_mb_initialize_context(ac, ar);
4583 if (*errp) {
4584 ar->len = 0;
4585 goto out;
4588 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4589 if (!ext4_mb_use_preallocated(ac)) {
4590 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4591 ext4_mb_normalize_request(ac, ar);
4592 repeat:
4593 /* allocate space in core */
4594 *errp = ext4_mb_regular_allocator(ac);
4595 if (*errp)
4596 goto discard_and_exit;
4598 /* as we've just preallocated more space than
4599 * user requested originally, we store allocated
4600 * space in a special descriptor */
4601 if (ac->ac_status == AC_STATUS_FOUND &&
4602 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4603 *errp = ext4_mb_new_preallocation(ac);
4604 if (*errp) {
4605 discard_and_exit:
4606 ext4_discard_allocated_blocks(ac);
4607 goto errout;
4610 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4611 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4612 if (*errp) {
4613 ext4_discard_allocated_blocks(ac);
4614 goto errout;
4615 } else {
4616 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4617 ar->len = ac->ac_b_ex.fe_len;
4619 } else {
4620 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4621 if (freed)
4622 goto repeat;
4623 *errp = -ENOSPC;
4626 errout:
4627 if (*errp) {
4628 ac->ac_b_ex.fe_len = 0;
4629 ar->len = 0;
4630 ext4_mb_show_ac(ac);
4632 ext4_mb_release_context(ac);
4633 out:
4634 if (ac)
4635 kmem_cache_free(ext4_ac_cachep, ac);
4636 if (inquota && ar->len < inquota)
4637 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
4638 if (!ar->len) {
4639 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
4640 /* release all the reserved blocks if non delalloc */
4641 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4642 reserv_clstrs);
4645 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4647 return block;
4651 * We can merge two free data extents only if the physical blocks
4652 * are contiguous, AND the extents were freed by the same transaction,
4653 * AND the blocks are associated with the same group.
4655 static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
4656 struct ext4_free_data *entry,
4657 struct ext4_free_data *new_entry,
4658 struct rb_root *entry_rb_root)
4660 if ((entry->efd_tid != new_entry->efd_tid) ||
4661 (entry->efd_group != new_entry->efd_group))
4662 return;
4663 if (entry->efd_start_cluster + entry->efd_count ==
4664 new_entry->efd_start_cluster) {
4665 new_entry->efd_start_cluster = entry->efd_start_cluster;
4666 new_entry->efd_count += entry->efd_count;
4667 } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
4668 entry->efd_start_cluster) {
4669 new_entry->efd_count += entry->efd_count;
4670 } else
4671 return;
4672 spin_lock(&sbi->s_md_lock);
4673 list_del(&entry->efd_list);
4674 spin_unlock(&sbi->s_md_lock);
4675 rb_erase(&entry->efd_node, entry_rb_root);
4676 kmem_cache_free(ext4_free_data_cachep, entry);
4679 static noinline_for_stack int
4680 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4681 struct ext4_free_data *new_entry)
4683 ext4_group_t group = e4b->bd_group;
4684 ext4_grpblk_t cluster;
4685 ext4_grpblk_t clusters = new_entry->efd_count;
4686 struct ext4_free_data *entry;
4687 struct ext4_group_info *db = e4b->bd_info;
4688 struct super_block *sb = e4b->bd_sb;
4689 struct ext4_sb_info *sbi = EXT4_SB(sb);
4690 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4691 struct rb_node *parent = NULL, *new_node;
4693 BUG_ON(!ext4_handle_valid(handle));
4694 BUG_ON(e4b->bd_bitmap_page == NULL);
4695 BUG_ON(e4b->bd_buddy_page == NULL);
4697 new_node = &new_entry->efd_node;
4698 cluster = new_entry->efd_start_cluster;
4700 if (!*n) {
4701 /* first free block exent. We need to
4702 protect buddy cache from being freed,
4703 * otherwise we'll refresh it from
4704 * on-disk bitmap and lose not-yet-available
4705 * blocks */
4706 get_page(e4b->bd_buddy_page);
4707 get_page(e4b->bd_bitmap_page);
4709 while (*n) {
4710 parent = *n;
4711 entry = rb_entry(parent, struct ext4_free_data, efd_node);
4712 if (cluster < entry->efd_start_cluster)
4713 n = &(*n)->rb_left;
4714 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
4715 n = &(*n)->rb_right;
4716 else {
4717 ext4_grp_locked_error(sb, group, 0,
4718 ext4_group_first_block_no(sb, group) +
4719 EXT4_C2B(sbi, cluster),
4720 "Block already on to-be-freed list");
4721 return 0;
4725 rb_link_node(new_node, parent, n);
4726 rb_insert_color(new_node, &db->bb_free_root);
4728 /* Now try to see the extent can be merged to left and right */
4729 node = rb_prev(new_node);
4730 if (node) {
4731 entry = rb_entry(node, struct ext4_free_data, efd_node);
4732 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4733 &(db->bb_free_root));
4736 node = rb_next(new_node);
4737 if (node) {
4738 entry = rb_entry(node, struct ext4_free_data, efd_node);
4739 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4740 &(db->bb_free_root));
4743 spin_lock(&sbi->s_md_lock);
4744 list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
4745 sbi->s_mb_free_pending += clusters;
4746 spin_unlock(&sbi->s_md_lock);
4747 return 0;
4751 * ext4_free_blocks() -- Free given blocks and update quota
4752 * @handle: handle for this transaction
4753 * @inode: inode
4754 * @block: start physical block to free
4755 * @count: number of blocks to count
4756 * @flags: flags used by ext4_free_blocks
4758 void ext4_free_blocks(handle_t *handle, struct inode *inode,
4759 struct buffer_head *bh, ext4_fsblk_t block,
4760 unsigned long count, int flags)
4762 struct buffer_head *bitmap_bh = NULL;
4763 struct super_block *sb = inode->i_sb;
4764 struct ext4_group_desc *gdp;
4765 unsigned int overflow;
4766 ext4_grpblk_t bit;
4767 struct buffer_head *gd_bh;
4768 ext4_group_t block_group;
4769 struct ext4_sb_info *sbi;
4770 struct ext4_buddy e4b;
4771 unsigned int count_clusters;
4772 int err = 0;
4773 int ret;
4775 might_sleep();
4776 if (bh) {
4777 if (block)
4778 BUG_ON(block != bh->b_blocknr);
4779 else
4780 block = bh->b_blocknr;
4783 sbi = EXT4_SB(sb);
4784 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
4785 !ext4_data_block_valid(sbi, block, count)) {
4786 ext4_error(sb, "Freeing blocks not in datazone - "
4787 "block = %llu, count = %lu", block, count);
4788 goto error_return;
4791 ext4_debug("freeing block %llu\n", block);
4792 trace_ext4_free_blocks(inode, block, count, flags);
4794 if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4795 BUG_ON(count > 1);
4797 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4798 inode, bh, block);
4802 * If the extent to be freed does not begin on a cluster
4803 * boundary, we need to deal with partial clusters at the
4804 * beginning and end of the extent. Normally we will free
4805 * blocks at the beginning or the end unless we are explicitly
4806 * requested to avoid doing so.
4808 overflow = EXT4_PBLK_COFF(sbi, block);
4809 if (overflow) {
4810 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
4811 overflow = sbi->s_cluster_ratio - overflow;
4812 block += overflow;
4813 if (count > overflow)
4814 count -= overflow;
4815 else
4816 return;
4817 } else {
4818 block -= overflow;
4819 count += overflow;
4822 overflow = EXT4_LBLK_COFF(sbi, count);
4823 if (overflow) {
4824 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
4825 if (count > overflow)
4826 count -= overflow;
4827 else
4828 return;
4829 } else
4830 count += sbi->s_cluster_ratio - overflow;
4833 if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4834 int i;
4835 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
4837 for (i = 0; i < count; i++) {
4838 cond_resched();
4839 if (is_metadata)
4840 bh = sb_find_get_block(inode->i_sb, block + i);
4841 ext4_forget(handle, is_metadata, inode, bh, block + i);
4845 do_more:
4846 overflow = 0;
4847 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4849 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
4850 ext4_get_group_info(sb, block_group))))
4851 return;
4854 * Check to see if we are freeing blocks across a group
4855 * boundary.
4857 if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4858 overflow = EXT4_C2B(sbi, bit) + count -
4859 EXT4_BLOCKS_PER_GROUP(sb);
4860 count -= overflow;
4862 count_clusters = EXT4_NUM_B2C(sbi, count);
4863 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4864 if (IS_ERR(bitmap_bh)) {
4865 err = PTR_ERR(bitmap_bh);
4866 bitmap_bh = NULL;
4867 goto error_return;
4869 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4870 if (!gdp) {
4871 err = -EIO;
4872 goto error_return;
4875 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4876 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4877 in_range(block, ext4_inode_table(sb, gdp),
4878 EXT4_SB(sb)->s_itb_per_group) ||
4879 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4880 EXT4_SB(sb)->s_itb_per_group)) {
4882 ext4_error(sb, "Freeing blocks in system zone - "
4883 "Block = %llu, count = %lu", block, count);
4884 /* err = 0. ext4_std_error should be a no op */
4885 goto error_return;
4888 BUFFER_TRACE(bitmap_bh, "getting write access");
4889 err = ext4_journal_get_write_access(handle, bitmap_bh);
4890 if (err)
4891 goto error_return;
4894 * We are about to modify some metadata. Call the journal APIs
4895 * to unshare ->b_data if a currently-committing transaction is
4896 * using it
4898 BUFFER_TRACE(gd_bh, "get_write_access");
4899 err = ext4_journal_get_write_access(handle, gd_bh);
4900 if (err)
4901 goto error_return;
4902 #ifdef AGGRESSIVE_CHECK
4904 int i;
4905 for (i = 0; i < count_clusters; i++)
4906 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4908 #endif
4909 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
4911 /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
4912 err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
4913 GFP_NOFS|__GFP_NOFAIL);
4914 if (err)
4915 goto error_return;
4918 * We need to make sure we don't reuse the freed block until after the
4919 * transaction is committed. We make an exception if the inode is to be
4920 * written in writeback mode since writeback mode has weak data
4921 * consistency guarantees.
4923 if (ext4_handle_valid(handle) &&
4924 ((flags & EXT4_FREE_BLOCKS_METADATA) ||
4925 !ext4_should_writeback_data(inode))) {
4926 struct ext4_free_data *new_entry;
4928 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
4929 * to fail.
4931 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
4932 GFP_NOFS|__GFP_NOFAIL);
4933 new_entry->efd_start_cluster = bit;
4934 new_entry->efd_group = block_group;
4935 new_entry->efd_count = count_clusters;
4936 new_entry->efd_tid = handle->h_transaction->t_tid;
4938 ext4_lock_group(sb, block_group);
4939 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4940 ext4_mb_free_metadata(handle, &e4b, new_entry);
4941 } else {
4942 /* need to update group_info->bb_free and bitmap
4943 * with group lock held. generate_buddy look at
4944 * them with group lock_held
4946 if (test_opt(sb, DISCARD)) {
4947 err = ext4_issue_discard(sb, block_group, bit, count,
4948 NULL);
4949 if (err && err != -EOPNOTSUPP)
4950 ext4_msg(sb, KERN_WARNING, "discard request in"
4951 " group:%d block:%d count:%lu failed"
4952 " with %d", block_group, bit, count,
4953 err);
4954 } else
4955 EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
4957 ext4_lock_group(sb, block_group);
4958 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4959 mb_free_blocks(inode, &e4b, bit, count_clusters);
4962 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
4963 ext4_free_group_clusters_set(sb, gdp, ret);
4964 ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
4965 ext4_group_desc_csum_set(sb, block_group, gdp);
4966 ext4_unlock_group(sb, block_group);
4968 if (sbi->s_log_groups_per_flex) {
4969 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4970 atomic64_add(count_clusters,
4971 &sbi_array_rcu_deref(sbi, s_flex_groups,
4972 flex_group)->free_clusters);
4975 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
4976 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
4977 percpu_counter_add(&sbi->s_freeclusters_counter, count_clusters);
4979 ext4_mb_unload_buddy(&e4b);
4981 /* We dirtied the bitmap block */
4982 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4983 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4985 /* And the group descriptor block */
4986 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4987 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4988 if (!err)
4989 err = ret;
4991 if (overflow && !err) {
4992 block += count;
4993 count = overflow;
4994 put_bh(bitmap_bh);
4995 goto do_more;
4997 error_return:
4998 brelse(bitmap_bh);
4999 ext4_std_error(sb, err);
5000 return;
5004 * ext4_group_add_blocks() -- Add given blocks to an existing group
5005 * @handle: handle to this transaction
5006 * @sb: super block
5007 * @block: start physical block to add to the block group
5008 * @count: number of blocks to free
5010 * This marks the blocks as free in the bitmap and buddy.
5012 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
5013 ext4_fsblk_t block, unsigned long count)
5015 struct buffer_head *bitmap_bh = NULL;
5016 struct buffer_head *gd_bh;
5017 ext4_group_t block_group;
5018 ext4_grpblk_t bit;
5019 unsigned int i;
5020 struct ext4_group_desc *desc;
5021 struct ext4_sb_info *sbi = EXT4_SB(sb);
5022 struct ext4_buddy e4b;
5023 int err = 0, ret, blk_free_count;
5024 ext4_grpblk_t blocks_freed;
5026 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
5028 if (count == 0)
5029 return 0;
5031 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5033 * Check to see if we are freeing blocks across a group
5034 * boundary.
5036 if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
5037 ext4_warning(sb, "too much blocks added to group %u",
5038 block_group);
5039 err = -EINVAL;
5040 goto error_return;
5043 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
5044 if (IS_ERR(bitmap_bh)) {
5045 err = PTR_ERR(bitmap_bh);
5046 bitmap_bh = NULL;
5047 goto error_return;
5050 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
5051 if (!desc) {
5052 err = -EIO;
5053 goto error_return;
5056 if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
5057 in_range(ext4_inode_bitmap(sb, desc), block, count) ||
5058 in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
5059 in_range(block + count - 1, ext4_inode_table(sb, desc),
5060 sbi->s_itb_per_group)) {
5061 ext4_error(sb, "Adding blocks in system zones - "
5062 "Block = %llu, count = %lu",
5063 block, count);
5064 err = -EINVAL;
5065 goto error_return;
5068 BUFFER_TRACE(bitmap_bh, "getting write access");
5069 err = ext4_journal_get_write_access(handle, bitmap_bh);
5070 if (err)
5071 goto error_return;
5074 * We are about to modify some metadata. Call the journal APIs
5075 * to unshare ->b_data if a currently-committing transaction is
5076 * using it
5078 BUFFER_TRACE(gd_bh, "get_write_access");
5079 err = ext4_journal_get_write_access(handle, gd_bh);
5080 if (err)
5081 goto error_return;
5083 for (i = 0, blocks_freed = 0; i < count; i++) {
5084 BUFFER_TRACE(bitmap_bh, "clear bit");
5085 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
5086 ext4_error(sb, "bit already cleared for block %llu",
5087 (ext4_fsblk_t)(block + i));
5088 BUFFER_TRACE(bitmap_bh, "bit already cleared");
5089 } else {
5090 blocks_freed++;
5094 err = ext4_mb_load_buddy(sb, block_group, &e4b);
5095 if (err)
5096 goto error_return;
5099 * need to update group_info->bb_free and bitmap
5100 * with group lock held. generate_buddy look at
5101 * them with group lock_held
5103 ext4_lock_group(sb, block_group);
5104 mb_clear_bits(bitmap_bh->b_data, bit, count);
5105 mb_free_blocks(NULL, &e4b, bit, count);
5106 blk_free_count = blocks_freed + ext4_free_group_clusters(sb, desc);
5107 ext4_free_group_clusters_set(sb, desc, blk_free_count);
5108 ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
5109 ext4_group_desc_csum_set(sb, block_group, desc);
5110 ext4_unlock_group(sb, block_group);
5111 percpu_counter_add(&sbi->s_freeclusters_counter,
5112 EXT4_NUM_B2C(sbi, blocks_freed));
5114 if (sbi->s_log_groups_per_flex) {
5115 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5116 atomic64_add(EXT4_NUM_B2C(sbi, blocks_freed),
5117 &sbi_array_rcu_deref(sbi, s_flex_groups,
5118 flex_group)->free_clusters);
5121 ext4_mb_unload_buddy(&e4b);
5123 /* We dirtied the bitmap block */
5124 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5125 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5127 /* And the group descriptor block */
5128 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5129 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5130 if (!err)
5131 err = ret;
5133 error_return:
5134 brelse(bitmap_bh);
5135 ext4_std_error(sb, err);
5136 return err;
5140 * ext4_trim_extent -- function to TRIM one single free extent in the group
5141 * @sb: super block for the file system
5142 * @start: starting block of the free extent in the alloc. group
5143 * @count: number of blocks to TRIM
5144 * @group: alloc. group we are working with
5145 * @e4b: ext4 buddy for the group
5147 * Trim "count" blocks starting at "start" in the "group". To assure that no
5148 * one will allocate those blocks, mark it as used in buddy bitmap. This must
5149 * be called with under the group lock.
5151 static int ext4_trim_extent(struct super_block *sb, int start, int count,
5152 ext4_group_t group, struct ext4_buddy *e4b)
5153 __releases(bitlock)
5154 __acquires(bitlock)
5156 struct ext4_free_extent ex;
5157 int ret = 0;
5159 trace_ext4_trim_extent(sb, group, start, count);
5161 assert_spin_locked(ext4_group_lock_ptr(sb, group));
5163 ex.fe_start = start;
5164 ex.fe_group = group;
5165 ex.fe_len = count;
5168 * Mark blocks used, so no one can reuse them while
5169 * being trimmed.
5171 mb_mark_used(e4b, &ex);
5172 ext4_unlock_group(sb, group);
5173 ret = ext4_issue_discard(sb, group, start, count, NULL);
5174 ext4_lock_group(sb, group);
5175 mb_free_blocks(NULL, e4b, start, ex.fe_len);
5176 return ret;
5180 * ext4_trim_all_free -- function to trim all free space in alloc. group
5181 * @sb: super block for file system
5182 * @group: group to be trimmed
5183 * @start: first group block to examine
5184 * @max: last group block to examine
5185 * @minblocks: minimum extent block count
5187 * ext4_trim_all_free walks through group's buddy bitmap searching for free
5188 * extents. When the free block is found, ext4_trim_extent is called to TRIM
5189 * the extent.
5192 * ext4_trim_all_free walks through group's block bitmap searching for free
5193 * extents. When the free extent is found, mark it as used in group buddy
5194 * bitmap. Then issue a TRIM command on this extent and free the extent in
5195 * the group buddy bitmap. This is done until whole group is scanned.
5197 static ext4_grpblk_t
5198 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
5199 ext4_grpblk_t start, ext4_grpblk_t max,
5200 ext4_grpblk_t minblocks)
5202 void *bitmap;
5203 ext4_grpblk_t next, count = 0, free_count = 0;
5204 struct ext4_buddy e4b;
5205 int ret = 0;
5207 trace_ext4_trim_all_free(sb, group, start, max);
5209 ret = ext4_mb_load_buddy(sb, group, &e4b);
5210 if (ret) {
5211 ext4_warning(sb, "Error %d loading buddy information for %u",
5212 ret, group);
5213 return ret;
5215 bitmap = e4b.bd_bitmap;
5217 ext4_lock_group(sb, group);
5218 if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
5219 minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
5220 goto out;
5222 start = (e4b.bd_info->bb_first_free > start) ?
5223 e4b.bd_info->bb_first_free : start;
5225 while (start <= max) {
5226 start = mb_find_next_zero_bit(bitmap, max + 1, start);
5227 if (start > max)
5228 break;
5229 next = mb_find_next_bit(bitmap, max + 1, start);
5231 if ((next - start) >= minblocks) {
5232 ret = ext4_trim_extent(sb, start,
5233 next - start, group, &e4b);
5234 if (ret && ret != -EOPNOTSUPP)
5235 break;
5236 ret = 0;
5237 count += next - start;
5239 free_count += next - start;
5240 start = next + 1;
5242 if (fatal_signal_pending(current)) {
5243 count = -ERESTARTSYS;
5244 break;
5247 if (need_resched()) {
5248 ext4_unlock_group(sb, group);
5249 cond_resched();
5250 ext4_lock_group(sb, group);
5253 if ((e4b.bd_info->bb_free - free_count) < minblocks)
5254 break;
5257 if (!ret) {
5258 ret = count;
5259 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
5261 out:
5262 ext4_unlock_group(sb, group);
5263 ext4_mb_unload_buddy(&e4b);
5265 ext4_debug("trimmed %d blocks in the group %d\n",
5266 count, group);
5268 return ret;
5272 * ext4_trim_fs() -- trim ioctl handle function
5273 * @sb: superblock for filesystem
5274 * @range: fstrim_range structure
5276 * start: First Byte to trim
5277 * len: number of Bytes to trim from start
5278 * minlen: minimum extent length in Bytes
5279 * ext4_trim_fs goes through all allocation groups containing Bytes from
5280 * start to start+len. For each such a group ext4_trim_all_free function
5281 * is invoked to trim all free space.
5283 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
5285 struct ext4_group_info *grp;
5286 ext4_group_t group, first_group, last_group;
5287 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5288 uint64_t start, end, minlen, trimmed = 0;
5289 ext4_fsblk_t first_data_blk =
5290 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5291 ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
5292 int ret = 0;
5294 start = range->start >> sb->s_blocksize_bits;
5295 end = start + (range->len >> sb->s_blocksize_bits) - 1;
5296 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5297 range->minlen >> sb->s_blocksize_bits);
5299 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
5300 start >= max_blks ||
5301 range->len < sb->s_blocksize)
5302 return -EINVAL;
5303 if (end >= max_blks)
5304 end = max_blks - 1;
5305 if (end <= first_data_blk)
5306 goto out;
5307 if (start < first_data_blk)
5308 start = first_data_blk;
5310 /* Determine first and last group to examine based on start and end */
5311 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
5312 &first_group, &first_cluster);
5313 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
5314 &last_group, &last_cluster);
5316 /* end now represents the last cluster to discard in this group */
5317 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5319 for (group = first_group; group <= last_group; group++) {
5320 grp = ext4_get_group_info(sb, group);
5321 /* We only do this if the grp has never been initialized */
5322 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
5323 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
5324 if (ret)
5325 break;
5329 * For all the groups except the last one, last cluster will
5330 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
5331 * change it for the last group, note that last_cluster is
5332 * already computed earlier by ext4_get_group_no_and_offset()
5334 if (group == last_group)
5335 end = last_cluster;
5337 if (grp->bb_free >= minlen) {
5338 cnt = ext4_trim_all_free(sb, group, first_cluster,
5339 end, minlen);
5340 if (cnt < 0) {
5341 ret = cnt;
5342 break;
5344 trimmed += cnt;
5348 * For every group except the first one, we are sure
5349 * that the first cluster to discard will be cluster #0.
5351 first_cluster = 0;
5354 if (!ret)
5355 atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
5357 out:
5358 range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
5359 return ret;
5362 /* Iterate all the free extents in the group. */
5364 ext4_mballoc_query_range(
5365 struct super_block *sb,
5366 ext4_group_t group,
5367 ext4_grpblk_t start,
5368 ext4_grpblk_t end,
5369 ext4_mballoc_query_range_fn formatter,
5370 void *priv)
5372 void *bitmap;
5373 ext4_grpblk_t next;
5374 struct ext4_buddy e4b;
5375 int error;
5377 error = ext4_mb_load_buddy(sb, group, &e4b);
5378 if (error)
5379 return error;
5380 bitmap = e4b.bd_bitmap;
5382 ext4_lock_group(sb, group);
5384 start = (e4b.bd_info->bb_first_free > start) ?
5385 e4b.bd_info->bb_first_free : start;
5386 if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
5387 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5389 while (start <= end) {
5390 start = mb_find_next_zero_bit(bitmap, end + 1, start);
5391 if (start > end)
5392 break;
5393 next = mb_find_next_bit(bitmap, end + 1, start);
5395 ext4_unlock_group(sb, group);
5396 error = formatter(sb, group, start, next - start, priv);
5397 if (error)
5398 goto out_unload;
5399 ext4_lock_group(sb, group);
5401 start = next + 1;
5404 ext4_unlock_group(sb, group);
5405 out_unload:
5406 ext4_mb_unload_buddy(&e4b);
5408 return error;