blob: 10611fffef90b85b1e12a6173ccda31ec8142461 [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
4 * Written by Alex Tomas <alex@clusterfs.com>
5 */
6
7
8/*
9 * mballoc.c contains the multiblocks allocation routines
10 */
11
12#include "ext4_jbd2.h"
13#include "mballoc.h"
14#include <linux/log2.h>
15#include <linux/module.h>
16#include <linux/slab.h>
17#include <linux/nospec.h>
18#include <linux/backing-dev.h>
19#include <linux/freezer.h>
20#include <trace/events/ext4.h>
21
22#ifdef CONFIG_EXT4_DEBUG
23ushort ext4_mballoc_debug __read_mostly;
24
25module_param_named(mballoc_debug, ext4_mballoc_debug, ushort, 0644);
26MODULE_PARM_DESC(mballoc_debug, "Debugging level for ext4's mballoc");
27#endif
28
29/*
30 * MUSTDO:
31 * - test ext4_ext_search_left() and ext4_ext_search_right()
32 * - search for metadata in few groups
33 *
34 * TODO v4:
35 * - normalization should take into account whether file is still open
36 * - discard preallocations if no free space left (policy?)
37 * - don't normalize tails
38 * - quota
39 * - reservation for superuser
40 *
41 * TODO v3:
42 * - bitmap read-ahead (proposed by Oleg Drokin aka green)
43 * - track min/max extents in each group for better group selection
44 * - mb_mark_used() may allocate chunk right after splitting buddy
45 * - tree of groups sorted by number of free blocks
46 * - error handling
47 */
48
49/*
50 * The allocation request involve request for multiple number of blocks
51 * near to the goal(block) value specified.
52 *
53 * During initialization phase of the allocator we decide to use the
54 * group preallocation or inode preallocation depending on the size of
55 * the file. The size of the file could be the resulting file size we
56 * would have after allocation, or the current file size, which ever
57 * is larger. If the size is less than sbi->s_mb_stream_request we
58 * select to use the group preallocation. The default value of
59 * s_mb_stream_request is 16 blocks. This can also be tuned via
60 * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
61 * terms of number of blocks.
62 *
63 * The main motivation for having small file use group preallocation is to
64 * ensure that we have small files closer together on the disk.
65 *
66 * First stage the allocator looks at the inode prealloc list,
67 * ext4_inode_info->i_prealloc_list, which contains list of prealloc
68 * spaces for this particular inode. The inode prealloc space is
69 * represented as:
70 *
71 * pa_lstart -> the logical start block for this prealloc space
72 * pa_pstart -> the physical start block for this prealloc space
73 * pa_len -> length for this prealloc space (in clusters)
74 * pa_free -> free space available in this prealloc space (in clusters)
75 *
76 * The inode preallocation space is used looking at the _logical_ start
77 * block. If only the logical file block falls within the range of prealloc
78 * space we will consume the particular prealloc space. This makes sure that
79 * we have contiguous physical blocks representing the file blocks
80 *
81 * The important thing to be noted in case of inode prealloc space is that
82 * we don't modify the values associated to inode prealloc space except
83 * pa_free.
84 *
85 * If we are not able to find blocks in the inode prealloc space and if we
86 * have the group allocation flag set then we look at the locality group
87 * prealloc space. These are per CPU prealloc list represented as
88 *
89 * ext4_sb_info.s_locality_groups[smp_processor_id()]
90 *
91 * The reason for having a per cpu locality group is to reduce the contention
92 * between CPUs. It is possible to get scheduled at this point.
93 *
94 * The locality group prealloc space is used looking at whether we have
95 * enough free space (pa_free) within the prealloc space.
96 *
97 * If we can't allocate blocks via inode prealloc or/and locality group
98 * prealloc then we look at the buddy cache. The buddy cache is represented
99 * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
100 * mapped to the buddy and bitmap information regarding different
101 * groups. The buddy information is attached to buddy cache inode so that
102 * we can access them through the page cache. The information regarding
103 * each group is loaded via ext4_mb_load_buddy. The information involve
104 * block bitmap and buddy information. The information are stored in the
105 * inode as:
106 *
107 * { page }
108 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
109 *
110 *
111 * one block each for bitmap and buddy information. So for each group we
112 * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
113 * blocksize) blocks. So it can have information regarding groups_per_page
114 * which is blocks_per_page/2
115 *
116 * The buddy cache inode is not stored on disk. The inode is thrown
117 * away when the filesystem is unmounted.
118 *
119 * We look for count number of blocks in the buddy cache. If we were able
120 * to locate that many free blocks we return with additional information
121 * regarding rest of the contiguous physical block available
122 *
123 * Before allocating blocks via buddy cache we normalize the request
124 * blocks. This ensure we ask for more blocks that we needed. The extra
125 * blocks that we get after allocation is added to the respective prealloc
126 * list. In case of inode preallocation we follow a list of heuristics
127 * based on file size. This can be found in ext4_mb_normalize_request. If
128 * we are doing a group prealloc we try to normalize the request to
129 * sbi->s_mb_group_prealloc. The default value of s_mb_group_prealloc is
130 * dependent on the cluster size; for non-bigalloc file systems, it is
131 * 512 blocks. This can be tuned via
132 * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
133 * terms of number of blocks. If we have mounted the file system with -O
134 * stripe=<value> option the group prealloc request is normalized to the
135 * the smallest multiple of the stripe value (sbi->s_stripe) which is
136 * greater than the default mb_group_prealloc.
137 *
138 * The regular allocator (using the buddy cache) supports a few tunables.
139 *
140 * /sys/fs/ext4/<partition>/mb_min_to_scan
141 * /sys/fs/ext4/<partition>/mb_max_to_scan
142 * /sys/fs/ext4/<partition>/mb_order2_req
143 *
144 * The regular allocator uses buddy scan only if the request len is power of
145 * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
146 * value of s_mb_order2_reqs can be tuned via
147 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
148 * stripe size (sbi->s_stripe), we try to search for contiguous block in
149 * stripe size. This should result in better allocation on RAID setups. If
150 * not, we search in the specific group using bitmap for best extents. The
151 * tunable min_to_scan and max_to_scan control the behaviour here.
152 * min_to_scan indicate how long the mballoc __must__ look for a best
153 * extent and max_to_scan indicates how long the mballoc __can__ look for a
154 * best extent in the found extents. Searching for the blocks starts with
155 * the group specified as the goal value in allocation context via
156 * ac_g_ex. Each group is first checked based on the criteria whether it
157 * can be used for allocation. ext4_mb_good_group explains how the groups are
158 * checked.
159 *
160 * Both the prealloc space are getting populated as above. So for the first
161 * request we will hit the buddy cache which will result in this prealloc
162 * space getting filled. The prealloc space is then later used for the
163 * subsequent request.
164 */
165
166/*
167 * mballoc operates on the following data:
168 * - on-disk bitmap
169 * - in-core buddy (actually includes buddy and bitmap)
170 * - preallocation descriptors (PAs)
171 *
172 * there are two types of preallocations:
173 * - inode
174 * assiged to specific inode and can be used for this inode only.
175 * it describes part of inode's space preallocated to specific
176 * physical blocks. any block from that preallocated can be used
177 * independent. the descriptor just tracks number of blocks left
178 * unused. so, before taking some block from descriptor, one must
179 * make sure corresponded logical block isn't allocated yet. this
180 * also means that freeing any block within descriptor's range
181 * must discard all preallocated blocks.
182 * - locality group
183 * assigned to specific locality group which does not translate to
184 * permanent set of inodes: inode can join and leave group. space
185 * from this type of preallocation can be used for any inode. thus
186 * it's consumed from the beginning to the end.
187 *
188 * relation between them can be expressed as:
189 * in-core buddy = on-disk bitmap + preallocation descriptors
190 *
191 * this mean blocks mballoc considers used are:
192 * - allocated blocks (persistent)
193 * - preallocated blocks (non-persistent)
194 *
195 * consistency in mballoc world means that at any time a block is either
196 * free or used in ALL structures. notice: "any time" should not be read
197 * literally -- time is discrete and delimited by locks.
198 *
199 * to keep it simple, we don't use block numbers, instead we count number of
200 * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
201 *
202 * all operations can be expressed as:
203 * - init buddy: buddy = on-disk + PAs
204 * - new PA: buddy += N; PA = N
205 * - use inode PA: on-disk += N; PA -= N
206 * - discard inode PA buddy -= on-disk - PA; PA = 0
207 * - use locality group PA on-disk += N; PA -= N
208 * - discard locality group PA buddy -= PA; PA = 0
209 * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
210 * is used in real operation because we can't know actual used
211 * bits from PA, only from on-disk bitmap
212 *
213 * if we follow this strict logic, then all operations above should be atomic.
214 * given some of them can block, we'd have to use something like semaphores
215 * killing performance on high-end SMP hardware. let's try to relax it using
216 * the following knowledge:
217 * 1) if buddy is referenced, it's already initialized
218 * 2) while block is used in buddy and the buddy is referenced,
219 * nobody can re-allocate that block
220 * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
221 * bit set and PA claims same block, it's OK. IOW, one can set bit in
222 * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
223 * block
224 *
225 * so, now we're building a concurrency table:
226 * - init buddy vs.
227 * - new PA
228 * blocks for PA are allocated in the buddy, buddy must be referenced
229 * until PA is linked to allocation group to avoid concurrent buddy init
230 * - use inode PA
231 * we need to make sure that either on-disk bitmap or PA has uptodate data
232 * given (3) we care that PA-=N operation doesn't interfere with init
233 * - discard inode PA
234 * the simplest way would be to have buddy initialized by the discard
235 * - use locality group PA
236 * again PA-=N must be serialized with init
237 * - discard locality group PA
238 * the simplest way would be to have buddy initialized by the discard
239 * - new PA vs.
240 * - use inode PA
241 * i_data_sem serializes them
242 * - discard inode PA
243 * discard process must wait until PA isn't used by another process
244 * - use locality group PA
245 * some mutex should serialize them
246 * - discard locality group PA
247 * discard process must wait until PA isn't used by another process
248 * - use inode PA
249 * - use inode PA
250 * i_data_sem or another mutex should serializes them
251 * - discard inode PA
252 * discard process must wait until PA isn't used by another process
253 * - use locality group PA
254 * nothing wrong here -- they're different PAs covering different blocks
255 * - discard locality group PA
256 * discard process must wait until PA isn't used by another process
257 *
258 * now we're ready to make few consequences:
259 * - PA is referenced and while it is no discard is possible
260 * - PA is referenced until block isn't marked in on-disk bitmap
261 * - PA changes only after on-disk bitmap
262 * - discard must not compete with init. either init is done before
263 * any discard or they're serialized somehow
264 * - buddy init as sum of on-disk bitmap and PAs is done atomically
265 *
266 * a special case when we've used PA to emptiness. no need to modify buddy
267 * in this case, but we should care about concurrent init
268 *
269 */
270
271 /*
272 * Logic in few words:
273 *
274 * - allocation:
275 * load group
276 * find blocks
277 * mark bits in on-disk bitmap
278 * release group
279 *
280 * - use preallocation:
281 * find proper PA (per-inode or group)
282 * load group
283 * mark bits in on-disk bitmap
284 * release group
285 * release PA
286 *
287 * - free:
288 * load group
289 * mark bits in on-disk bitmap
290 * release group
291 *
292 * - discard preallocations in group:
293 * mark PAs deleted
294 * move them onto local list
295 * load on-disk bitmap
296 * load group
297 * remove PA from object (inode or locality group)
298 * mark free blocks in-core
299 *
300 * - discard inode's preallocations:
301 */
302
303/*
304 * Locking rules
305 *
306 * Locks:
307 * - bitlock on a group (group)
308 * - object (inode/locality) (object)
309 * - per-pa lock (pa)
310 *
311 * Paths:
312 * - new pa
313 * object
314 * group
315 *
316 * - find and use pa:
317 * pa
318 *
319 * - release consumed pa:
320 * pa
321 * group
322 * object
323 *
324 * - generate in-core bitmap:
325 * group
326 * pa
327 *
328 * - discard all for given object (inode, locality group):
329 * object
330 * pa
331 * group
332 *
333 * - discard all for given group:
334 * group
335 * pa
336 * group
337 * object
338 *
339 */
340static struct kmem_cache *ext4_pspace_cachep;
341static struct kmem_cache *ext4_ac_cachep;
342static struct kmem_cache *ext4_free_data_cachep;
343
344/* We create slab caches for groupinfo data structures based on the
345 * superblock block size. There will be one per mounted filesystem for
346 * each unique s_blocksize_bits */
347#define NR_GRPINFO_CACHES 8
348static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
349
350static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
351 "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
352 "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
353 "ext4_groupinfo_64k", "ext4_groupinfo_128k"
354};
355
356static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
357 ext4_group_t group);
358static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
359 ext4_group_t group);
360
361static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
362{
363#if BITS_PER_LONG == 64
364 *bit += ((unsigned long) addr & 7UL) << 3;
365 addr = (void *) ((unsigned long) addr & ~7UL);
366#elif BITS_PER_LONG == 32
367 *bit += ((unsigned long) addr & 3UL) << 3;
368 addr = (void *) ((unsigned long) addr & ~3UL);
369#else
370#error "how many bits you are?!"
371#endif
372 return addr;
373}
374
375static inline int mb_test_bit(int bit, void *addr)
376{
377 /*
378 * ext4_test_bit on architecture like powerpc
379 * needs unsigned long aligned address
380 */
381 addr = mb_correct_addr_and_bit(&bit, addr);
382 return ext4_test_bit(bit, addr);
383}
384
385static inline void mb_set_bit(int bit, void *addr)
386{
387 addr = mb_correct_addr_and_bit(&bit, addr);
388 ext4_set_bit(bit, addr);
389}
390
391static inline void mb_clear_bit(int bit, void *addr)
392{
393 addr = mb_correct_addr_and_bit(&bit, addr);
394 ext4_clear_bit(bit, addr);
395}
396
397static inline int mb_test_and_clear_bit(int bit, void *addr)
398{
399 addr = mb_correct_addr_and_bit(&bit, addr);
400 return ext4_test_and_clear_bit(bit, addr);
401}
402
403static inline int mb_find_next_zero_bit(void *addr, int max, int start)
404{
405 int fix = 0, ret, tmpmax;
406 addr = mb_correct_addr_and_bit(&fix, addr);
407 tmpmax = max + fix;
408 start += fix;
409
410 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
411 if (ret > max)
412 return max;
413 return ret;
414}
415
416static inline int mb_find_next_bit(void *addr, int max, int start)
417{
418 int fix = 0, ret, tmpmax;
419 addr = mb_correct_addr_and_bit(&fix, addr);
420 tmpmax = max + fix;
421 start += fix;
422
423 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
424 if (ret > max)
425 return max;
426 return ret;
427}
428
429static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
430{
431 char *bb;
432
433 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
434 BUG_ON(max == NULL);
435
436 if (order > e4b->bd_blkbits + 1) {
437 *max = 0;
438 return NULL;
439 }
440
441 /* at order 0 we see each particular block */
442 if (order == 0) {
443 *max = 1 << (e4b->bd_blkbits + 3);
444 return e4b->bd_bitmap;
445 }
446
447 bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
448 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
449
450 return bb;
451}
452
453#ifdef DOUBLE_CHECK
454static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
455 int first, int count)
456{
457 int i;
458 struct super_block *sb = e4b->bd_sb;
459
460 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
461 return;
462 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
463 for (i = 0; i < count; i++) {
464 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
465 ext4_fsblk_t blocknr;
466
467 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
468 blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
469 ext4_grp_locked_error(sb, e4b->bd_group,
470 inode ? inode->i_ino : 0,
471 blocknr,
472 "freeing block already freed "
473 "(bit %u)",
474 first + i);
475 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
476 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
477 }
478 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
479 }
480}
481
482static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
483{
484 int i;
485
486 if (unlikely(e4b->bd_info->bb_bitmap == NULL))
487 return;
488 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
489 for (i = 0; i < count; i++) {
490 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
491 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
492 }
493}
494
495static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
496{
497 if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
498 unsigned char *b1, *b2;
499 int i;
500 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
501 b2 = (unsigned char *) bitmap;
502 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
503 if (b1[i] != b2[i]) {
504 ext4_msg(e4b->bd_sb, KERN_ERR,
505 "corruption in group %u "
506 "at byte %u(%u): %x in copy != %x "
507 "on disk/prealloc",
508 e4b->bd_group, i, i * 8, b1[i], b2[i]);
509 BUG();
510 }
511 }
512 }
513}
514
515#else
516static inline void mb_free_blocks_double(struct inode *inode,
517 struct ext4_buddy *e4b, int first, int count)
518{
519 return;
520}
521static inline void mb_mark_used_double(struct ext4_buddy *e4b,
522 int first, int count)
523{
524 return;
525}
526static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
527{
528 return;
529}
530#endif
531
532#ifdef AGGRESSIVE_CHECK
533
534#define MB_CHECK_ASSERT(assert) \
535do { \
536 if (!(assert)) { \
537 printk(KERN_EMERG \
538 "Assertion failure in %s() at %s:%d: \"%s\"\n", \
539 function, file, line, # assert); \
540 BUG(); \
541 } \
542} while (0)
543
544static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
545 const char *function, int line)
546{
547 struct super_block *sb = e4b->bd_sb;
548 int order = e4b->bd_blkbits + 1;
549 int max;
550 int max2;
551 int i;
552 int j;
553 int k;
554 int count;
555 struct ext4_group_info *grp;
556 int fragments = 0;
557 int fstart;
558 struct list_head *cur;
559 void *buddy;
560 void *buddy2;
561
562 {
563 static int mb_check_counter;
564 if (mb_check_counter++ % 100 != 0)
565 return 0;
566 }
567
568 while (order > 1) {
569 buddy = mb_find_buddy(e4b, order, &max);
570 MB_CHECK_ASSERT(buddy);
571 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
572 MB_CHECK_ASSERT(buddy2);
573 MB_CHECK_ASSERT(buddy != buddy2);
574 MB_CHECK_ASSERT(max * 2 == max2);
575
576 count = 0;
577 for (i = 0; i < max; i++) {
578
579 if (mb_test_bit(i, buddy)) {
580 /* only single bit in buddy2 may be 1 */
581 if (!mb_test_bit(i << 1, buddy2)) {
582 MB_CHECK_ASSERT(
583 mb_test_bit((i<<1)+1, buddy2));
584 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
585 MB_CHECK_ASSERT(
586 mb_test_bit(i << 1, buddy2));
587 }
588 continue;
589 }
590
591 /* both bits in buddy2 must be 1 */
592 MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
593 MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
594
595 for (j = 0; j < (1 << order); j++) {
596 k = (i * (1 << order)) + j;
597 MB_CHECK_ASSERT(
598 !mb_test_bit(k, e4b->bd_bitmap));
599 }
600 count++;
601 }
602 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
603 order--;
604 }
605
606 fstart = -1;
607 buddy = mb_find_buddy(e4b, 0, &max);
608 for (i = 0; i < max; i++) {
609 if (!mb_test_bit(i, buddy)) {
610 MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
611 if (fstart == -1) {
612 fragments++;
613 fstart = i;
614 }
615 continue;
616 }
617 fstart = -1;
618 /* check used bits only */
619 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
620 buddy2 = mb_find_buddy(e4b, j, &max2);
621 k = i >> j;
622 MB_CHECK_ASSERT(k < max2);
623 MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
624 }
625 }
626 MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
627 MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
628
629 grp = ext4_get_group_info(sb, e4b->bd_group);
630 list_for_each(cur, &grp->bb_prealloc_list) {
631 ext4_group_t groupnr;
632 struct ext4_prealloc_space *pa;
633 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
634 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
635 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
636 for (i = 0; i < pa->pa_len; i++)
637 MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
638 }
639 return 0;
640}
641#undef MB_CHECK_ASSERT
642#define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
643 __FILE__, __func__, __LINE__)
644#else
645#define mb_check_buddy(e4b)
646#endif
647
648/*
649 * Divide blocks started from @first with length @len into
650 * smaller chunks with power of 2 blocks.
651 * Clear the bits in bitmap which the blocks of the chunk(s) covered,
652 * then increase bb_counters[] for corresponded chunk size.
653 */
654static void ext4_mb_mark_free_simple(struct super_block *sb,
655 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
656 struct ext4_group_info *grp)
657{
658 struct ext4_sb_info *sbi = EXT4_SB(sb);
659 ext4_grpblk_t min;
660 ext4_grpblk_t max;
661 ext4_grpblk_t chunk;
662 unsigned int border;
663
664 BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
665
666 border = 2 << sb->s_blocksize_bits;
667
668 while (len > 0) {
669 /* find how many blocks can be covered since this position */
670 max = ffs(first | border) - 1;
671
672 /* find how many blocks of power 2 we need to mark */
673 min = fls(len) - 1;
674
675 if (max < min)
676 min = max;
677 chunk = 1 << min;
678
679 /* mark multiblock chunks only */
680 grp->bb_counters[min]++;
681 if (min > 0)
682 mb_clear_bit(first >> min,
683 buddy + sbi->s_mb_offsets[min]);
684
685 len -= chunk;
686 first += chunk;
687 }
688}
689
690/*
691 * Cache the order of the largest free extent we have available in this block
692 * group.
693 */
694static void
695mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
696{
697 int i;
698 int bits;
699
700 grp->bb_largest_free_order = -1; /* uninit */
701
702 bits = sb->s_blocksize_bits + 1;
703 for (i = bits; i >= 0; i--) {
704 if (grp->bb_counters[i] > 0) {
705 grp->bb_largest_free_order = i;
706 break;
707 }
708 }
709}
710
711static noinline_for_stack
712void ext4_mb_generate_buddy(struct super_block *sb,
713 void *buddy, void *bitmap, ext4_group_t group)
714{
715 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
716 struct ext4_sb_info *sbi = EXT4_SB(sb);
717 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
718 ext4_grpblk_t i = 0;
719 ext4_grpblk_t first;
720 ext4_grpblk_t len;
721 unsigned free = 0;
722 unsigned fragments = 0;
723 unsigned long long period = get_cycles();
724
725 /* initialize buddy from bitmap which is aggregation
726 * of on-disk bitmap and preallocations */
727 i = mb_find_next_zero_bit(bitmap, max, 0);
728 grp->bb_first_free = i;
729 while (i < max) {
730 fragments++;
731 first = i;
732 i = mb_find_next_bit(bitmap, max, i);
733 len = i - first;
734 free += len;
735 if (len > 1)
736 ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
737 else
738 grp->bb_counters[0]++;
739 if (i < max)
740 i = mb_find_next_zero_bit(bitmap, max, i);
741 }
742 grp->bb_fragments = fragments;
743
744 if (free != grp->bb_free) {
745 ext4_grp_locked_error(sb, group, 0, 0,
746 "block bitmap and bg descriptor "
747 "inconsistent: %u vs %u free clusters",
748 free, grp->bb_free);
749 /*
750 * If we intend to continue, we consider group descriptor
751 * corrupt and update bb_free using bitmap value
752 */
753 grp->bb_free = free;
754 ext4_mark_group_bitmap_corrupted(sb, group,
755 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
756 }
757 mb_set_largest_free_order(sb, grp);
758
759 clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
760
761 period = get_cycles() - period;
762 spin_lock(&sbi->s_bal_lock);
763 sbi->s_mb_buddies_generated++;
764 sbi->s_mb_generation_time += period;
765 spin_unlock(&sbi->s_bal_lock);
766}
767
768static void mb_regenerate_buddy(struct ext4_buddy *e4b)
769{
770 int count;
771 int order = 1;
772 void *buddy;
773
774 while ((buddy = mb_find_buddy(e4b, order++, &count))) {
775 ext4_set_bits(buddy, 0, count);
776 }
777 e4b->bd_info->bb_fragments = 0;
778 memset(e4b->bd_info->bb_counters, 0,
779 sizeof(*e4b->bd_info->bb_counters) *
780 (e4b->bd_sb->s_blocksize_bits + 2));
781
782 ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
783 e4b->bd_bitmap, e4b->bd_group);
784}
785
786/* The buddy information is attached the buddy cache inode
787 * for convenience. The information regarding each group
788 * is loaded via ext4_mb_load_buddy. The information involve
789 * block bitmap and buddy information. The information are
790 * stored in the inode as
791 *
792 * { page }
793 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
794 *
795 *
796 * one block each for bitmap and buddy information.
797 * So for each group we take up 2 blocks. A page can
798 * contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
799 * So it can have information regarding groups_per_page which
800 * is blocks_per_page/2
801 *
802 * Locking note: This routine takes the block group lock of all groups
803 * for this page; do not hold this lock when calling this routine!
804 */
805
806static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
807{
808 ext4_group_t ngroups;
809 int blocksize;
810 int blocks_per_page;
811 int groups_per_page;
812 int err = 0;
813 int i;
814 ext4_group_t first_group, group;
815 int first_block;
816 struct super_block *sb;
817 struct buffer_head *bhs;
818 struct buffer_head **bh = NULL;
819 struct inode *inode;
820 char *data;
821 char *bitmap;
822 struct ext4_group_info *grinfo;
823
824 mb_debug(1, "init page %lu\n", page->index);
825
826 inode = page->mapping->host;
827 sb = inode->i_sb;
828 ngroups = ext4_get_groups_count(sb);
829 blocksize = i_blocksize(inode);
830 blocks_per_page = PAGE_SIZE / blocksize;
831
832 groups_per_page = blocks_per_page >> 1;
833 if (groups_per_page == 0)
834 groups_per_page = 1;
835
836 /* allocate buffer_heads to read bitmaps */
837 if (groups_per_page > 1) {
838 i = sizeof(struct buffer_head *) * groups_per_page;
839 bh = kzalloc(i, gfp);
840 if (bh == NULL) {
841 err = -ENOMEM;
842 goto out;
843 }
844 } else
845 bh = &bhs;
846
847 first_group = page->index * blocks_per_page / 2;
848
849 /* read all groups the page covers into the cache */
850 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
851 if (group >= ngroups)
852 break;
853
854 grinfo = ext4_get_group_info(sb, group);
855 /*
856 * If page is uptodate then we came here after online resize
857 * which added some new uninitialized group info structs, so
858 * we must skip all initialized uptodate buddies on the page,
859 * which may be currently in use by an allocating task.
860 */
861 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
862 bh[i] = NULL;
863 continue;
864 }
865 bh[i] = ext4_read_block_bitmap_nowait(sb, group);
866 if (IS_ERR(bh[i])) {
867 err = PTR_ERR(bh[i]);
868 bh[i] = NULL;
869 goto out;
870 }
871 mb_debug(1, "read bitmap for group %u\n", group);
872 }
873
874 /* wait for I/O completion */
875 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
876 int err2;
877
878 if (!bh[i])
879 continue;
880 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
881 if (!err)
882 err = err2;
883 }
884
885 first_block = page->index * blocks_per_page;
886 for (i = 0; i < blocks_per_page; i++) {
887 group = (first_block + i) >> 1;
888 if (group >= ngroups)
889 break;
890
891 if (!bh[group - first_group])
892 /* skip initialized uptodate buddy */
893 continue;
894
895 if (!buffer_verified(bh[group - first_group]))
896 /* Skip faulty bitmaps */
897 continue;
898 err = 0;
899
900 /*
901 * data carry information regarding this
902 * particular group in the format specified
903 * above
904 *
905 */
906 data = page_address(page) + (i * blocksize);
907 bitmap = bh[group - first_group]->b_data;
908
909 /*
910 * We place the buddy block and bitmap block
911 * close together
912 */
913 if ((first_block + i) & 1) {
914 /* this is block of buddy */
915 BUG_ON(incore == NULL);
916 mb_debug(1, "put buddy for group %u in page %lu/%x\n",
917 group, page->index, i * blocksize);
918 trace_ext4_mb_buddy_bitmap_load(sb, group);
919 grinfo = ext4_get_group_info(sb, group);
920 grinfo->bb_fragments = 0;
921 memset(grinfo->bb_counters, 0,
922 sizeof(*grinfo->bb_counters) *
923 (sb->s_blocksize_bits+2));
924 /*
925 * incore got set to the group block bitmap below
926 */
927 ext4_lock_group(sb, group);
928 /* init the buddy */
929 memset(data, 0xff, blocksize);
930 ext4_mb_generate_buddy(sb, data, incore, group);
931 ext4_unlock_group(sb, group);
932 incore = NULL;
933 } else {
934 /* this is block of bitmap */
935 BUG_ON(incore != NULL);
936 mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
937 group, page->index, i * blocksize);
938 trace_ext4_mb_bitmap_load(sb, group);
939
940 /* see comments in ext4_mb_put_pa() */
941 ext4_lock_group(sb, group);
942 memcpy(data, bitmap, blocksize);
943
944 /* mark all preallocated blks used in in-core bitmap */
945 ext4_mb_generate_from_pa(sb, data, group);
946 ext4_mb_generate_from_freelist(sb, data, group);
947 ext4_unlock_group(sb, group);
948
949 /* set incore so that the buddy information can be
950 * generated using this
951 */
952 incore = data;
953 }
954 }
955 SetPageUptodate(page);
956
957out:
958 if (bh) {
959 for (i = 0; i < groups_per_page; i++)
960 brelse(bh[i]);
961 if (bh != &bhs)
962 kfree(bh);
963 }
964 return err;
965}
966
967/*
968 * Lock the buddy and bitmap pages. This make sure other parallel init_group
969 * on the same buddy page doesn't happen whild holding the buddy page lock.
970 * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
971 * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
972 */
973static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
974 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
975{
976 struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
977 int block, pnum, poff;
978 int blocks_per_page;
979 struct page *page;
980
981 e4b->bd_buddy_page = NULL;
982 e4b->bd_bitmap_page = NULL;
983
984 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
985 /*
986 * the buddy cache inode stores the block bitmap
987 * and buddy information in consecutive blocks.
988 * So for each group we need two blocks.
989 */
990 block = group * 2;
991 pnum = block / blocks_per_page;
992 poff = block % blocks_per_page;
993 page = find_or_create_page(inode->i_mapping, pnum, gfp);
994 if (!page)
995 return -ENOMEM;
996 BUG_ON(page->mapping != inode->i_mapping);
997 e4b->bd_bitmap_page = page;
998 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
999
1000 if (blocks_per_page >= 2) {
1001 /* buddy and bitmap are on the same page */
1002 return 0;
1003 }
1004
1005 block++;
1006 pnum = block / blocks_per_page;
1007 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1008 if (!page)
1009 return -ENOMEM;
1010 BUG_ON(page->mapping != inode->i_mapping);
1011 e4b->bd_buddy_page = page;
1012 return 0;
1013}
1014
1015static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1016{
1017 if (e4b->bd_bitmap_page) {
1018 unlock_page(e4b->bd_bitmap_page);
1019 put_page(e4b->bd_bitmap_page);
1020 }
1021 if (e4b->bd_buddy_page) {
1022 unlock_page(e4b->bd_buddy_page);
1023 put_page(e4b->bd_buddy_page);
1024 }
1025}
1026
1027/*
1028 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1029 * block group lock of all groups for this page; do not hold the BG lock when
1030 * calling this routine!
1031 */
1032static noinline_for_stack
1033int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1034{
1035
1036 struct ext4_group_info *this_grp;
1037 struct ext4_buddy e4b;
1038 struct page *page;
1039 int ret = 0;
1040
1041 might_sleep();
1042 mb_debug(1, "init group %u\n", group);
1043 this_grp = ext4_get_group_info(sb, group);
1044 /*
1045 * This ensures that we don't reinit the buddy cache
1046 * page which map to the group from which we are already
1047 * allocating. If we are looking at the buddy cache we would
1048 * have taken a reference using ext4_mb_load_buddy and that
1049 * would have pinned buddy page to page cache.
1050 * The call to ext4_mb_get_buddy_page_lock will mark the
1051 * page accessed.
1052 */
1053 ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1054 if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1055 /*
1056 * somebody initialized the group
1057 * return without doing anything
1058 */
1059 goto err;
1060 }
1061
1062 page = e4b.bd_bitmap_page;
1063 ret = ext4_mb_init_cache(page, NULL, gfp);
1064 if (ret)
1065 goto err;
1066 if (!PageUptodate(page)) {
1067 ret = -EIO;
1068 goto err;
1069 }
1070
1071 if (e4b.bd_buddy_page == NULL) {
1072 /*
1073 * If both the bitmap and buddy are in
1074 * the same page we don't need to force
1075 * init the buddy
1076 */
1077 ret = 0;
1078 goto err;
1079 }
1080 /* init buddy cache */
1081 page = e4b.bd_buddy_page;
1082 ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1083 if (ret)
1084 goto err;
1085 if (!PageUptodate(page)) {
1086 ret = -EIO;
1087 goto err;
1088 }
1089err:
1090 ext4_mb_put_buddy_page_lock(&e4b);
1091 return ret;
1092}
1093
1094/*
1095 * Locking note: This routine calls ext4_mb_init_cache(), which takes the
1096 * block group lock of all groups for this page; do not hold the BG lock when
1097 * calling this routine!
1098 */
1099static noinline_for_stack int
1100ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1101 struct ext4_buddy *e4b, gfp_t gfp)
1102{
1103 int blocks_per_page;
1104 int block;
1105 int pnum;
1106 int poff;
1107 struct page *page;
1108 int ret;
1109 struct ext4_group_info *grp;
1110 struct ext4_sb_info *sbi = EXT4_SB(sb);
1111 struct inode *inode = sbi->s_buddy_cache;
1112
1113 might_sleep();
1114 mb_debug(1, "load group %u\n", group);
1115
1116 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1117 grp = ext4_get_group_info(sb, group);
1118
1119 e4b->bd_blkbits = sb->s_blocksize_bits;
1120 e4b->bd_info = grp;
1121 e4b->bd_sb = sb;
1122 e4b->bd_group = group;
1123 e4b->bd_buddy_page = NULL;
1124 e4b->bd_bitmap_page = NULL;
1125
1126 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1127 /*
1128 * we need full data about the group
1129 * to make a good selection
1130 */
1131 ret = ext4_mb_init_group(sb, group, gfp);
1132 if (ret)
1133 return ret;
1134 }
1135
1136 /*
1137 * the buddy cache inode stores the block bitmap
1138 * and buddy information in consecutive blocks.
1139 * So for each group we need two blocks.
1140 */
1141 block = group * 2;
1142 pnum = block / blocks_per_page;
1143 poff = block % blocks_per_page;
1144
1145 /* we could use find_or_create_page(), but it locks page
1146 * what we'd like to avoid in fast path ... */
1147 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1148 if (page == NULL || !PageUptodate(page)) {
1149 if (page)
1150 /*
1151 * drop the page reference and try
1152 * to get the page with lock. If we
1153 * are not uptodate that implies
1154 * somebody just created the page but
1155 * is yet to initialize the same. So
1156 * wait for it to initialize.
1157 */
1158 put_page(page);
1159 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1160 if (page) {
1161 BUG_ON(page->mapping != inode->i_mapping);
1162 if (!PageUptodate(page)) {
1163 ret = ext4_mb_init_cache(page, NULL, gfp);
1164 if (ret) {
1165 unlock_page(page);
1166 goto err;
1167 }
1168 mb_cmp_bitmaps(e4b, page_address(page) +
1169 (poff * sb->s_blocksize));
1170 }
1171 unlock_page(page);
1172 }
1173 }
1174 if (page == NULL) {
1175 ret = -ENOMEM;
1176 goto err;
1177 }
1178 if (!PageUptodate(page)) {
1179 ret = -EIO;
1180 goto err;
1181 }
1182
1183 /* Pages marked accessed already */
1184 e4b->bd_bitmap_page = page;
1185 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1186
1187 block++;
1188 pnum = block / blocks_per_page;
1189 poff = block % blocks_per_page;
1190
1191 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1192 if (page == NULL || !PageUptodate(page)) {
1193 if (page)
1194 put_page(page);
1195 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1196 if (page) {
1197 BUG_ON(page->mapping != inode->i_mapping);
1198 if (!PageUptodate(page)) {
1199 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1200 gfp);
1201 if (ret) {
1202 unlock_page(page);
1203 goto err;
1204 }
1205 }
1206 unlock_page(page);
1207 }
1208 }
1209 if (page == NULL) {
1210 ret = -ENOMEM;
1211 goto err;
1212 }
1213 if (!PageUptodate(page)) {
1214 ret = -EIO;
1215 goto err;
1216 }
1217
1218 /* Pages marked accessed already */
1219 e4b->bd_buddy_page = page;
1220 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1221
1222 BUG_ON(e4b->bd_bitmap_page == NULL);
1223 BUG_ON(e4b->bd_buddy_page == NULL);
1224
1225 return 0;
1226
1227err:
1228 if (page)
1229 put_page(page);
1230 if (e4b->bd_bitmap_page)
1231 put_page(e4b->bd_bitmap_page);
1232 if (e4b->bd_buddy_page)
1233 put_page(e4b->bd_buddy_page);
1234 e4b->bd_buddy = NULL;
1235 e4b->bd_bitmap = NULL;
1236 return ret;
1237}
1238
1239static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1240 struct ext4_buddy *e4b)
1241{
1242 return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1243}
1244
1245static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1246{
1247 if (e4b->bd_bitmap_page)
1248 put_page(e4b->bd_bitmap_page);
1249 if (e4b->bd_buddy_page)
1250 put_page(e4b->bd_buddy_page);
1251}
1252
1253
1254static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1255{
1256 int order = 1;
1257 int bb_incr = 1 << (e4b->bd_blkbits - 1);
1258 void *bb;
1259
1260 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1261 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1262
1263 bb = e4b->bd_buddy;
1264 while (order <= e4b->bd_blkbits + 1) {
1265 block = block >> 1;
1266 if (!mb_test_bit(block, bb)) {
1267 /* this block is part of buddy of order 'order' */
1268 return order;
1269 }
1270 bb += bb_incr;
1271 bb_incr >>= 1;
1272 order++;
1273 }
1274 return 0;
1275}
1276
1277static void mb_clear_bits(void *bm, int cur, int len)
1278{
1279 __u32 *addr;
1280
1281 len = cur + len;
1282 while (cur < len) {
1283 if ((cur & 31) == 0 && (len - cur) >= 32) {
1284 /* fast path: clear whole word at once */
1285 addr = bm + (cur >> 3);
1286 *addr = 0;
1287 cur += 32;
1288 continue;
1289 }
1290 mb_clear_bit(cur, bm);
1291 cur++;
1292 }
1293}
1294
1295/* clear bits in given range
1296 * will return first found zero bit if any, -1 otherwise
1297 */
1298static int mb_test_and_clear_bits(void *bm, int cur, int len)
1299{
1300 __u32 *addr;
1301 int zero_bit = -1;
1302
1303 len = cur + len;
1304 while (cur < len) {
1305 if ((cur & 31) == 0 && (len - cur) >= 32) {
1306 /* fast path: clear whole word at once */
1307 addr = bm + (cur >> 3);
1308 if (*addr != (__u32)(-1) && zero_bit == -1)
1309 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1310 *addr = 0;
1311 cur += 32;
1312 continue;
1313 }
1314 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1315 zero_bit = cur;
1316 cur++;
1317 }
1318
1319 return zero_bit;
1320}
1321
1322void ext4_set_bits(void *bm, int cur, int len)
1323{
1324 __u32 *addr;
1325
1326 len = cur + len;
1327 while (cur < len) {
1328 if ((cur & 31) == 0 && (len - cur) >= 32) {
1329 /* fast path: set whole word at once */
1330 addr = bm + (cur >> 3);
1331 *addr = 0xffffffff;
1332 cur += 32;
1333 continue;
1334 }
1335 mb_set_bit(cur, bm);
1336 cur++;
1337 }
1338}
1339
1340/*
1341 * _________________________________________________________________ */
1342
1343static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1344{
1345 if (mb_test_bit(*bit + side, bitmap)) {
1346 mb_clear_bit(*bit, bitmap);
1347 (*bit) -= side;
1348 return 1;
1349 }
1350 else {
1351 (*bit) += side;
1352 mb_set_bit(*bit, bitmap);
1353 return -1;
1354 }
1355}
1356
1357static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1358{
1359 int max;
1360 int order = 1;
1361 void *buddy = mb_find_buddy(e4b, order, &max);
1362
1363 while (buddy) {
1364 void *buddy2;
1365
1366 /* Bits in range [first; last] are known to be set since
1367 * corresponding blocks were allocated. Bits in range
1368 * (first; last) will stay set because they form buddies on
1369 * upper layer. We just deal with borders if they don't
1370 * align with upper layer and then go up.
1371 * Releasing entire group is all about clearing
1372 * single bit of highest order buddy.
1373 */
1374
1375 /* Example:
1376 * ---------------------------------
1377 * | 1 | 1 | 1 | 1 |
1378 * ---------------------------------
1379 * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1380 * ---------------------------------
1381 * 0 1 2 3 4 5 6 7
1382 * \_____________________/
1383 *
1384 * Neither [1] nor [6] is aligned to above layer.
1385 * Left neighbour [0] is free, so mark it busy,
1386 * decrease bb_counters and extend range to
1387 * [0; 6]
1388 * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1389 * mark [6] free, increase bb_counters and shrink range to
1390 * [0; 5].
1391 * Then shift range to [0; 2], go up and do the same.
1392 */
1393
1394
1395 if (first & 1)
1396 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1397 if (!(last & 1))
1398 e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1399 if (first > last)
1400 break;
1401 order++;
1402
1403 if (first == last || !(buddy2 = mb_find_buddy(e4b, order, &max))) {
1404 mb_clear_bits(buddy, first, last - first + 1);
1405 e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1406 break;
1407 }
1408 first >>= 1;
1409 last >>= 1;
1410 buddy = buddy2;
1411 }
1412}
1413
1414static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1415 int first, int count)
1416{
1417 int left_is_free = 0;
1418 int right_is_free = 0;
1419 int block;
1420 int last = first + count - 1;
1421 struct super_block *sb = e4b->bd_sb;
1422
1423 if (WARN_ON(count == 0))
1424 return;
1425 BUG_ON(last >= (sb->s_blocksize << 3));
1426 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1427 /* Don't bother if the block group is corrupt. */
1428 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1429 return;
1430
1431 mb_check_buddy(e4b);
1432 mb_free_blocks_double(inode, e4b, first, count);
1433
1434 e4b->bd_info->bb_free += count;
1435 if (first < e4b->bd_info->bb_first_free)
1436 e4b->bd_info->bb_first_free = first;
1437
1438 /* access memory sequentially: check left neighbour,
1439 * clear range and then check right neighbour
1440 */
1441 if (first != 0)
1442 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1443 block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1444 if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1445 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1446
1447 if (unlikely(block != -1)) {
1448 struct ext4_sb_info *sbi = EXT4_SB(sb);
1449 ext4_fsblk_t blocknr;
1450
1451 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1452 blocknr += EXT4_C2B(sbi, block);
1453 ext4_grp_locked_error(sb, e4b->bd_group,
1454 inode ? inode->i_ino : 0,
1455 blocknr,
1456 "freeing already freed block "
1457 "(bit %u); block bitmap corrupt.",
1458 block);
1459 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
1460 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1461 mb_regenerate_buddy(e4b);
1462 goto done;
1463 }
1464
1465 /* let's maintain fragments counter */
1466 if (left_is_free && right_is_free)
1467 e4b->bd_info->bb_fragments--;
1468 else if (!left_is_free && !right_is_free)
1469 e4b->bd_info->bb_fragments++;
1470
1471 /* buddy[0] == bd_bitmap is a special case, so handle
1472 * it right away and let mb_buddy_mark_free stay free of
1473 * zero order checks.
1474 * Check if neighbours are to be coaleasced,
1475 * adjust bitmap bb_counters and borders appropriately.
1476 */
1477 if (first & 1) {
1478 first += !left_is_free;
1479 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1480 }
1481 if (!(last & 1)) {
1482 last -= !right_is_free;
1483 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1484 }
1485
1486 if (first <= last)
1487 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1488
1489done:
1490 mb_set_largest_free_order(sb, e4b->bd_info);
1491 mb_check_buddy(e4b);
1492}
1493
1494static int mb_find_extent(struct ext4_buddy *e4b, int block,
1495 int needed, struct ext4_free_extent *ex)
1496{
1497 int next = block;
1498 int max, order;
1499 void *buddy;
1500
1501 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1502 BUG_ON(ex == NULL);
1503
1504 buddy = mb_find_buddy(e4b, 0, &max);
1505 BUG_ON(buddy == NULL);
1506 BUG_ON(block >= max);
1507 if (mb_test_bit(block, buddy)) {
1508 ex->fe_len = 0;
1509 ex->fe_start = 0;
1510 ex->fe_group = 0;
1511 return 0;
1512 }
1513
1514 /* find actual order */
1515 order = mb_find_order_for_block(e4b, block);
1516 block = block >> order;
1517
1518 ex->fe_len = 1 << order;
1519 ex->fe_start = block << order;
1520 ex->fe_group = e4b->bd_group;
1521
1522 /* calc difference from given start */
1523 next = next - ex->fe_start;
1524 ex->fe_len -= next;
1525 ex->fe_start += next;
1526
1527 while (needed > ex->fe_len &&
1528 mb_find_buddy(e4b, order, &max)) {
1529
1530 if (block + 1 >= max)
1531 break;
1532
1533 next = (block + 1) * (1 << order);
1534 if (mb_test_bit(next, e4b->bd_bitmap))
1535 break;
1536
1537 order = mb_find_order_for_block(e4b, next);
1538
1539 block = next >> order;
1540 ex->fe_len += 1 << order;
1541 }
1542
1543 if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
1544 /* Should never happen! (but apparently sometimes does?!?) */
1545 WARN_ON(1);
1546 ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
1547 "corruption or bug in mb_find_extent "
1548 "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
1549 block, order, needed, ex->fe_group, ex->fe_start,
1550 ex->fe_len, ex->fe_logical);
1551 ex->fe_len = 0;
1552 ex->fe_start = 0;
1553 ex->fe_group = 0;
1554 }
1555 return ex->fe_len;
1556}
1557
1558static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1559{
1560 int ord;
1561 int mlen = 0;
1562 int max = 0;
1563 int cur;
1564 int start = ex->fe_start;
1565 int len = ex->fe_len;
1566 unsigned ret = 0;
1567 int len0 = len;
1568 void *buddy;
1569
1570 BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1571 BUG_ON(e4b->bd_group != ex->fe_group);
1572 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1573 mb_check_buddy(e4b);
1574 mb_mark_used_double(e4b, start, len);
1575
1576 e4b->bd_info->bb_free -= len;
1577 if (e4b->bd_info->bb_first_free == start)
1578 e4b->bd_info->bb_first_free += len;
1579
1580 /* let's maintain fragments counter */
1581 if (start != 0)
1582 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1583 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1584 max = !mb_test_bit(start + len, e4b->bd_bitmap);
1585 if (mlen && max)
1586 e4b->bd_info->bb_fragments++;
1587 else if (!mlen && !max)
1588 e4b->bd_info->bb_fragments--;
1589
1590 /* let's maintain buddy itself */
1591 while (len) {
1592 ord = mb_find_order_for_block(e4b, start);
1593
1594 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1595 /* the whole chunk may be allocated at once! */
1596 mlen = 1 << ord;
1597 buddy = mb_find_buddy(e4b, ord, &max);
1598 BUG_ON((start >> ord) >= max);
1599 mb_set_bit(start >> ord, buddy);
1600 e4b->bd_info->bb_counters[ord]--;
1601 start += mlen;
1602 len -= mlen;
1603 BUG_ON(len < 0);
1604 continue;
1605 }
1606
1607 /* store for history */
1608 if (ret == 0)
1609 ret = len | (ord << 16);
1610
1611 /* we have to split large buddy */
1612 BUG_ON(ord <= 0);
1613 buddy = mb_find_buddy(e4b, ord, &max);
1614 mb_set_bit(start >> ord, buddy);
1615 e4b->bd_info->bb_counters[ord]--;
1616
1617 ord--;
1618 cur = (start >> ord) & ~1U;
1619 buddy = mb_find_buddy(e4b, ord, &max);
1620 mb_clear_bit(cur, buddy);
1621 mb_clear_bit(cur + 1, buddy);
1622 e4b->bd_info->bb_counters[ord]++;
1623 e4b->bd_info->bb_counters[ord]++;
1624 }
1625 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1626
1627 ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1628 mb_check_buddy(e4b);
1629
1630 return ret;
1631}
1632
1633/*
1634 * Must be called under group lock!
1635 */
1636static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1637 struct ext4_buddy *e4b)
1638{
1639 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1640 int ret;
1641
1642 BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1643 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1644
1645 ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1646 ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1647 ret = mb_mark_used(e4b, &ac->ac_b_ex);
1648
1649 /* preallocation can change ac_b_ex, thus we store actually
1650 * allocated blocks for history */
1651 ac->ac_f_ex = ac->ac_b_ex;
1652
1653 ac->ac_status = AC_STATUS_FOUND;
1654 ac->ac_tail = ret & 0xffff;
1655 ac->ac_buddy = ret >> 16;
1656
1657 /*
1658 * take the page reference. We want the page to be pinned
1659 * so that we don't get a ext4_mb_init_cache_call for this
1660 * group until we update the bitmap. That would mean we
1661 * double allocate blocks. The reference is dropped
1662 * in ext4_mb_release_context
1663 */
1664 ac->ac_bitmap_page = e4b->bd_bitmap_page;
1665 get_page(ac->ac_bitmap_page);
1666 ac->ac_buddy_page = e4b->bd_buddy_page;
1667 get_page(ac->ac_buddy_page);
1668 /* store last allocated for subsequent stream allocation */
1669 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1670 spin_lock(&sbi->s_md_lock);
1671 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1672 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1673 spin_unlock(&sbi->s_md_lock);
1674 }
1675}
1676
1677/*
1678 * regular allocator, for general purposes allocation
1679 */
1680
1681static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1682 struct ext4_buddy *e4b,
1683 int finish_group)
1684{
1685 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1686 struct ext4_free_extent *bex = &ac->ac_b_ex;
1687 struct ext4_free_extent *gex = &ac->ac_g_ex;
1688 struct ext4_free_extent ex;
1689 int max;
1690
1691 if (ac->ac_status == AC_STATUS_FOUND)
1692 return;
1693 /*
1694 * We don't want to scan for a whole year
1695 */
1696 if (ac->ac_found > sbi->s_mb_max_to_scan &&
1697 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1698 ac->ac_status = AC_STATUS_BREAK;
1699 return;
1700 }
1701
1702 /*
1703 * Haven't found good chunk so far, let's continue
1704 */
1705 if (bex->fe_len < gex->fe_len)
1706 return;
1707
1708 if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1709 && bex->fe_group == e4b->bd_group) {
1710 /* recheck chunk's availability - we don't know
1711 * when it was found (within this lock-unlock
1712 * period or not) */
1713 max = mb_find_extent(e4b, bex->fe_start, gex->fe_len, &ex);
1714 if (max >= gex->fe_len) {
1715 ext4_mb_use_best_found(ac, e4b);
1716 return;
1717 }
1718 }
1719}
1720
1721/*
1722 * The routine checks whether found extent is good enough. If it is,
1723 * then the extent gets marked used and flag is set to the context
1724 * to stop scanning. Otherwise, the extent is compared with the
1725 * previous found extent and if new one is better, then it's stored
1726 * in the context. Later, the best found extent will be used, if
1727 * mballoc can't find good enough extent.
1728 *
1729 * FIXME: real allocation policy is to be designed yet!
1730 */
1731static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1732 struct ext4_free_extent *ex,
1733 struct ext4_buddy *e4b)
1734{
1735 struct ext4_free_extent *bex = &ac->ac_b_ex;
1736 struct ext4_free_extent *gex = &ac->ac_g_ex;
1737
1738 BUG_ON(ex->fe_len <= 0);
1739 BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1740 BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1741 BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1742
1743 ac->ac_found++;
1744
1745 /*
1746 * The special case - take what you catch first
1747 */
1748 if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1749 *bex = *ex;
1750 ext4_mb_use_best_found(ac, e4b);
1751 return;
1752 }
1753
1754 /*
1755 * Let's check whether the chuck is good enough
1756 */
1757 if (ex->fe_len == gex->fe_len) {
1758 *bex = *ex;
1759 ext4_mb_use_best_found(ac, e4b);
1760 return;
1761 }
1762
1763 /*
1764 * If this is first found extent, just store it in the context
1765 */
1766 if (bex->fe_len == 0) {
1767 *bex = *ex;
1768 return;
1769 }
1770
1771 /*
1772 * If new found extent is better, store it in the context
1773 */
1774 if (bex->fe_len < gex->fe_len) {
1775 /* if the request isn't satisfied, any found extent
1776 * larger than previous best one is better */
1777 if (ex->fe_len > bex->fe_len)
1778 *bex = *ex;
1779 } else if (ex->fe_len > gex->fe_len) {
1780 /* if the request is satisfied, then we try to find
1781 * an extent that still satisfy the request, but is
1782 * smaller than previous one */
1783 if (ex->fe_len < bex->fe_len)
1784 *bex = *ex;
1785 }
1786
1787 ext4_mb_check_limits(ac, e4b, 0);
1788}
1789
1790static noinline_for_stack
1791int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1792 struct ext4_buddy *e4b)
1793{
1794 struct ext4_free_extent ex = ac->ac_b_ex;
1795 ext4_group_t group = ex.fe_group;
1796 int max;
1797 int err;
1798
1799 BUG_ON(ex.fe_len <= 0);
1800 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1801 if (err)
1802 return err;
1803
1804 ext4_lock_group(ac->ac_sb, group);
1805 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1806 goto out;
1807
1808 max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
1809
1810 if (max > 0) {
1811 ac->ac_b_ex = ex;
1812 ext4_mb_use_best_found(ac, e4b);
1813 }
1814
1815out:
1816 ext4_unlock_group(ac->ac_sb, group);
1817 ext4_mb_unload_buddy(e4b);
1818
1819 return 0;
1820}
1821
1822static noinline_for_stack
1823int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1824 struct ext4_buddy *e4b)
1825{
1826 ext4_group_t group = ac->ac_g_ex.fe_group;
1827 int max;
1828 int err;
1829 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1830 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1831 struct ext4_free_extent ex;
1832
1833 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1834 return 0;
1835 if (grp->bb_free == 0)
1836 return 0;
1837
1838 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1839 if (err)
1840 return err;
1841
1842 ext4_lock_group(ac->ac_sb, group);
1843 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1844 goto out;
1845
1846 max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
1847 ac->ac_g_ex.fe_len, &ex);
1848 ex.fe_logical = 0xDEADFA11; /* debug value */
1849
1850 if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1851 ext4_fsblk_t start;
1852
1853 start = ext4_grp_offs_to_block(ac->ac_sb, &ex);
1854 /* use do_div to get remainder (would be 64-bit modulo) */
1855 if (do_div(start, sbi->s_stripe) == 0) {
1856 ac->ac_found++;
1857 ac->ac_b_ex = ex;
1858 ext4_mb_use_best_found(ac, e4b);
1859 }
1860 } else if (max >= ac->ac_g_ex.fe_len) {
1861 BUG_ON(ex.fe_len <= 0);
1862 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1863 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1864 ac->ac_found++;
1865 ac->ac_b_ex = ex;
1866 ext4_mb_use_best_found(ac, e4b);
1867 } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1868 /* Sometimes, caller may want to merge even small
1869 * number of blocks to an existing extent */
1870 BUG_ON(ex.fe_len <= 0);
1871 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1872 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1873 ac->ac_found++;
1874 ac->ac_b_ex = ex;
1875 ext4_mb_use_best_found(ac, e4b);
1876 }
1877out:
1878 ext4_unlock_group(ac->ac_sb, group);
1879 ext4_mb_unload_buddy(e4b);
1880
1881 return 0;
1882}
1883
1884/*
1885 * The routine scans buddy structures (not bitmap!) from given order
1886 * to max order and tries to find big enough chunk to satisfy the req
1887 */
1888static noinline_for_stack
1889void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1890 struct ext4_buddy *e4b)
1891{
1892 struct super_block *sb = ac->ac_sb;
1893 struct ext4_group_info *grp = e4b->bd_info;
1894 void *buddy;
1895 int i;
1896 int k;
1897 int max;
1898
1899 BUG_ON(ac->ac_2order <= 0);
1900 for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1901 if (grp->bb_counters[i] == 0)
1902 continue;
1903
1904 buddy = mb_find_buddy(e4b, i, &max);
1905 BUG_ON(buddy == NULL);
1906
1907 k = mb_find_next_zero_bit(buddy, max, 0);
1908 if (k >= max) {
1909 ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
1910 "%d free clusters of order %d. But found 0",
1911 grp->bb_counters[i], i);
1912 ext4_mark_group_bitmap_corrupted(ac->ac_sb,
1913 e4b->bd_group,
1914 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1915 break;
1916 }
1917 ac->ac_found++;
1918
1919 ac->ac_b_ex.fe_len = 1 << i;
1920 ac->ac_b_ex.fe_start = k << i;
1921 ac->ac_b_ex.fe_group = e4b->bd_group;
1922
1923 ext4_mb_use_best_found(ac, e4b);
1924
1925 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1926
1927 if (EXT4_SB(sb)->s_mb_stats)
1928 atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1929
1930 break;
1931 }
1932}
1933
1934/*
1935 * The routine scans the group and measures all found extents.
1936 * In order to optimize scanning, caller must pass number of
1937 * free blocks in the group, so the routine can know upper limit.
1938 */
1939static noinline_for_stack
1940void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1941 struct ext4_buddy *e4b)
1942{
1943 struct super_block *sb = ac->ac_sb;
1944 void *bitmap = e4b->bd_bitmap;
1945 struct ext4_free_extent ex;
1946 int i;
1947 int free;
1948
1949 free = e4b->bd_info->bb_free;
1950 if (WARN_ON(free <= 0))
1951 return;
1952
1953 i = e4b->bd_info->bb_first_free;
1954
1955 while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1956 i = mb_find_next_zero_bit(bitmap,
1957 EXT4_CLUSTERS_PER_GROUP(sb), i);
1958 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
1959 /*
1960 * IF we have corrupt bitmap, we won't find any
1961 * free blocks even though group info says we
1962 * we have free blocks
1963 */
1964 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1965 "%d free clusters as per "
1966 "group info. But bitmap says 0",
1967 free);
1968 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
1969 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1970 break;
1971 }
1972
1973 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
1974 if (WARN_ON(ex.fe_len <= 0))
1975 break;
1976 if (free < ex.fe_len) {
1977 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1978 "%d free clusters as per "
1979 "group info. But got %d blocks",
1980 free, ex.fe_len);
1981 ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
1982 EXT4_GROUP_INFO_BBITMAP_CORRUPT);
1983 /*
1984 * The number of free blocks differs. This mostly
1985 * indicate that the bitmap is corrupt. So exit
1986 * without claiming the space.
1987 */
1988 break;
1989 }
1990 ex.fe_logical = 0xDEADC0DE; /* debug value */
1991 ext4_mb_measure_extent(ac, &ex, e4b);
1992
1993 i += ex.fe_len;
1994 free -= ex.fe_len;
1995 }
1996
1997 ext4_mb_check_limits(ac, e4b, 1);
1998}
1999
2000/*
2001 * This is a special case for storages like raid5
2002 * we try to find stripe-aligned chunks for stripe-size-multiple requests
2003 */
2004static noinline_for_stack
2005void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2006 struct ext4_buddy *e4b)
2007{
2008 struct super_block *sb = ac->ac_sb;
2009 struct ext4_sb_info *sbi = EXT4_SB(sb);
2010 void *bitmap = e4b->bd_bitmap;
2011 struct ext4_free_extent ex;
2012 ext4_fsblk_t first_group_block;
2013 ext4_fsblk_t a;
2014 ext4_grpblk_t i;
2015 int max;
2016
2017 BUG_ON(sbi->s_stripe == 0);
2018
2019 /* find first stripe-aligned block in group */
2020 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2021
2022 a = first_group_block + sbi->s_stripe - 1;
2023 do_div(a, sbi->s_stripe);
2024 i = (a * sbi->s_stripe) - first_group_block;
2025
2026 while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2027 if (!mb_test_bit(i, bitmap)) {
2028 max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
2029 if (max >= sbi->s_stripe) {
2030 ac->ac_found++;
2031 ex.fe_logical = 0xDEADF00D; /* debug value */
2032 ac->ac_b_ex = ex;
2033 ext4_mb_use_best_found(ac, e4b);
2034 break;
2035 }
2036 }
2037 i += sbi->s_stripe;
2038 }
2039}
2040
2041/*
2042 * This is now called BEFORE we load the buddy bitmap.
2043 * Returns either 1 or 0 indicating that the group is either suitable
2044 * for the allocation or not. In addition it can also return negative
2045 * error code when something goes wrong.
2046 */
2047static int ext4_mb_good_group(struct ext4_allocation_context *ac,
2048 ext4_group_t group, int cr)
2049{
2050 unsigned free, fragments;
2051 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2052 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2053
2054 BUG_ON(cr < 0 || cr >= 4);
2055
2056 free = grp->bb_free;
2057 if (free == 0)
2058 return 0;
2059 if (cr <= 2 && free < ac->ac_g_ex.fe_len)
2060 return 0;
2061
2062 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2063 return 0;
2064
2065 /* We only do this if the grp has never been initialized */
2066 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2067 int ret = ext4_mb_init_group(ac->ac_sb, group, GFP_NOFS);
2068 if (ret)
2069 return ret;
2070 }
2071
2072 fragments = grp->bb_fragments;
2073 if (fragments == 0)
2074 return 0;
2075
2076 switch (cr) {
2077 case 0:
2078 BUG_ON(ac->ac_2order == 0);
2079
2080 /* Avoid using the first bg of a flexgroup for data files */
2081 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2082 (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2083 ((group % flex_size) == 0))
2084 return 0;
2085
2086 if ((ac->ac_2order > ac->ac_sb->s_blocksize_bits+1) ||
2087 (free / fragments) >= ac->ac_g_ex.fe_len)
2088 return 1;
2089
2090 if (grp->bb_largest_free_order < ac->ac_2order)
2091 return 0;
2092
2093 return 1;
2094 case 1:
2095 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2096 return 1;
2097 break;
2098 case 2:
2099 if (free >= ac->ac_g_ex.fe_len)
2100 return 1;
2101 break;
2102 case 3:
2103 return 1;
2104 default:
2105 BUG();
2106 }
2107
2108 return 0;
2109}
2110
2111static noinline_for_stack int
2112ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2113{
2114 ext4_group_t ngroups, group, i;
2115 int cr;
2116 int err = 0, first_err = 0;
2117 struct ext4_sb_info *sbi;
2118 struct super_block *sb;
2119 struct ext4_buddy e4b;
2120
2121 sb = ac->ac_sb;
2122 sbi = EXT4_SB(sb);
2123 ngroups = ext4_get_groups_count(sb);
2124 /* non-extent files are limited to low blocks/groups */
2125 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2126 ngroups = sbi->s_blockfile_groups;
2127
2128 BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2129
2130 /* first, try the goal */
2131 err = ext4_mb_find_by_goal(ac, &e4b);
2132 if (err || ac->ac_status == AC_STATUS_FOUND)
2133 goto out;
2134
2135 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2136 goto out;
2137
2138 /*
2139 * ac->ac2_order is set only if the fe_len is a power of 2
2140 * if ac2_order is set we also set criteria to 0 so that we
2141 * try exact allocation using buddy.
2142 */
2143 i = fls(ac->ac_g_ex.fe_len);
2144 ac->ac_2order = 0;
2145 /*
2146 * We search using buddy data only if the order of the request
2147 * is greater than equal to the sbi_s_mb_order2_reqs
2148 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2149 * We also support searching for power-of-two requests only for
2150 * requests upto maximum buddy size we have constructed.
2151 */
2152 if (i >= sbi->s_mb_order2_reqs && i <= sb->s_blocksize_bits + 2) {
2153 /*
2154 * This should tell if fe_len is exactly power of 2
2155 */
2156 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2157 ac->ac_2order = array_index_nospec(i - 1,
2158 sb->s_blocksize_bits + 2);
2159 }
2160
2161 /* if stream allocation is enabled, use global goal */
2162 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2163 /* TBD: may be hot point */
2164 spin_lock(&sbi->s_md_lock);
2165 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2166 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2167 spin_unlock(&sbi->s_md_lock);
2168 }
2169
2170 /* Let's just scan groups to find more-less suitable blocks */
2171 cr = ac->ac_2order ? 0 : 1;
2172 /*
2173 * cr == 0 try to get exact allocation,
2174 * cr == 3 try to get anything
2175 */
2176repeat:
2177 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2178 ac->ac_criteria = cr;
2179 /*
2180 * searching for the right group start
2181 * from the goal value specified
2182 */
2183 group = ac->ac_g_ex.fe_group;
2184
2185 for (i = 0; i < ngroups; group++, i++) {
2186 int ret = 0;
2187 cond_resched();
2188 /*
2189 * Artificially restricted ngroups for non-extent
2190 * files makes group > ngroups possible on first loop.
2191 */
2192 if (group >= ngroups)
2193 group = 0;
2194
2195 /* This now checks without needing the buddy page */
2196 ret = ext4_mb_good_group(ac, group, cr);
2197 if (ret <= 0) {
2198 if (!first_err)
2199 first_err = ret;
2200 continue;
2201 }
2202
2203 err = ext4_mb_load_buddy(sb, group, &e4b);
2204 if (err)
2205 goto out;
2206
2207 ext4_lock_group(sb, group);
2208
2209 /*
2210 * We need to check again after locking the
2211 * block group
2212 */
2213 ret = ext4_mb_good_group(ac, group, cr);
2214 if (ret <= 0) {
2215 ext4_unlock_group(sb, group);
2216 ext4_mb_unload_buddy(&e4b);
2217 if (!first_err)
2218 first_err = ret;
2219 continue;
2220 }
2221
2222 ac->ac_groups_scanned++;
2223 if (cr == 0)
2224 ext4_mb_simple_scan_group(ac, &e4b);
2225 else if (cr == 1 && sbi->s_stripe &&
2226 !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2227 ext4_mb_scan_aligned(ac, &e4b);
2228 else
2229 ext4_mb_complex_scan_group(ac, &e4b);
2230
2231 ext4_unlock_group(sb, group);
2232 ext4_mb_unload_buddy(&e4b);
2233
2234 if (ac->ac_status != AC_STATUS_CONTINUE)
2235 break;
2236 }
2237 }
2238
2239 if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2240 !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2241 /*
2242 * We've been searching too long. Let's try to allocate
2243 * the best chunk we've found so far
2244 */
2245
2246 ext4_mb_try_best_found(ac, &e4b);
2247 if (ac->ac_status != AC_STATUS_FOUND) {
2248 /*
2249 * Someone more lucky has already allocated it.
2250 * The only thing we can do is just take first
2251 * found block(s)
2252 printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2253 */
2254 ac->ac_b_ex.fe_group = 0;
2255 ac->ac_b_ex.fe_start = 0;
2256 ac->ac_b_ex.fe_len = 0;
2257 ac->ac_status = AC_STATUS_CONTINUE;
2258 ac->ac_flags |= EXT4_MB_HINT_FIRST;
2259 cr = 3;
2260 atomic_inc(&sbi->s_mb_lost_chunks);
2261 goto repeat;
2262 }
2263 }
2264out:
2265 if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2266 err = first_err;
2267 return err;
2268}
2269
2270static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2271{
2272 struct super_block *sb = PDE_DATA(file_inode(seq->file));
2273 ext4_group_t group;
2274
2275 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2276 return NULL;
2277 group = *pos + 1;
2278 return (void *) ((unsigned long) group);
2279}
2280
2281static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2282{
2283 struct super_block *sb = PDE_DATA(file_inode(seq->file));
2284 ext4_group_t group;
2285
2286 ++*pos;
2287 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2288 return NULL;
2289 group = *pos + 1;
2290 return (void *) ((unsigned long) group);
2291}
2292
2293static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2294{
2295 struct super_block *sb = PDE_DATA(file_inode(seq->file));
2296 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2297 int i;
2298 int err, buddy_loaded = 0;
2299 struct ext4_buddy e4b;
2300 struct ext4_group_info *grinfo;
2301 unsigned char blocksize_bits = min_t(unsigned char,
2302 sb->s_blocksize_bits,
2303 EXT4_MAX_BLOCK_LOG_SIZE);
2304 struct sg {
2305 struct ext4_group_info info;
2306 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
2307 } sg;
2308
2309 group--;
2310 if (group == 0)
2311 seq_puts(seq, "#group: free frags first ["
2312 " 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
2313 " 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
2314
2315 i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2316 sizeof(struct ext4_group_info);
2317
2318 grinfo = ext4_get_group_info(sb, group);
2319 /* Load the group info in memory only if not already loaded. */
2320 if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
2321 err = ext4_mb_load_buddy(sb, group, &e4b);
2322 if (err) {
2323 seq_printf(seq, "#%-5u: I/O error\n", group);
2324 return 0;
2325 }
2326 buddy_loaded = 1;
2327 }
2328
2329 memcpy(&sg, ext4_get_group_info(sb, group), i);
2330
2331 if (buddy_loaded)
2332 ext4_mb_unload_buddy(&e4b);
2333
2334 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2335 sg.info.bb_fragments, sg.info.bb_first_free);
2336 for (i = 0; i <= 13; i++)
2337 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
2338 sg.info.bb_counters[i] : 0);
2339 seq_printf(seq, " ]\n");
2340
2341 return 0;
2342}
2343
2344static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2345{
2346}
2347
2348const struct seq_operations ext4_mb_seq_groups_ops = {
2349 .start = ext4_mb_seq_groups_start,
2350 .next = ext4_mb_seq_groups_next,
2351 .stop = ext4_mb_seq_groups_stop,
2352 .show = ext4_mb_seq_groups_show,
2353};
2354
2355static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2356{
2357 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2358 struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2359
2360 BUG_ON(!cachep);
2361 return cachep;
2362}
2363
2364/*
2365 * Allocate the top-level s_group_info array for the specified number
2366 * of groups
2367 */
2368int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
2369{
2370 struct ext4_sb_info *sbi = EXT4_SB(sb);
2371 unsigned size;
2372 struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
2373
2374 size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
2375 EXT4_DESC_PER_BLOCK_BITS(sb);
2376 if (size <= sbi->s_group_info_size)
2377 return 0;
2378
2379 size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
2380 new_groupinfo = kvzalloc(size, GFP_KERNEL);
2381 if (!new_groupinfo) {
2382 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
2383 return -ENOMEM;
2384 }
2385 rcu_read_lock();
2386 old_groupinfo = rcu_dereference(sbi->s_group_info);
2387 if (old_groupinfo)
2388 memcpy(new_groupinfo, old_groupinfo,
2389 sbi->s_group_info_size * sizeof(*sbi->s_group_info));
2390 rcu_read_unlock();
2391 rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
2392 sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
2393 if (old_groupinfo)
2394 ext4_kvfree_array_rcu(old_groupinfo);
2395 ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
2396 sbi->s_group_info_size);
2397 return 0;
2398}
2399
2400/* Create and initialize ext4_group_info data for the given group. */
2401int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2402 struct ext4_group_desc *desc)
2403{
2404 int i;
2405 int metalen = 0;
2406 int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
2407 struct ext4_sb_info *sbi = EXT4_SB(sb);
2408 struct ext4_group_info **meta_group_info;
2409 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2410
2411 /*
2412 * First check if this group is the first of a reserved block.
2413 * If it's true, we have to allocate a new table of pointers
2414 * to ext4_group_info structures
2415 */
2416 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2417 metalen = sizeof(*meta_group_info) <<
2418 EXT4_DESC_PER_BLOCK_BITS(sb);
2419 meta_group_info = kmalloc(metalen, GFP_NOFS);
2420 if (meta_group_info == NULL) {
2421 ext4_msg(sb, KERN_ERR, "can't allocate mem "
2422 "for a buddy group");
2423 goto exit_meta_group_info;
2424 }
2425 rcu_read_lock();
2426 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
2427 rcu_read_unlock();
2428 }
2429
2430 meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
2431 i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2432
2433 meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
2434 if (meta_group_info[i] == NULL) {
2435 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
2436 goto exit_group_info;
2437 }
2438 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2439 &(meta_group_info[i]->bb_state));
2440
2441 /*
2442 * initialize bb_free to be able to skip
2443 * empty groups without initialization
2444 */
2445 if (ext4_has_group_desc_csum(sb) &&
2446 (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
2447 meta_group_info[i]->bb_free =
2448 ext4_free_clusters_after_init(sb, group, desc);
2449 } else {
2450 meta_group_info[i]->bb_free =
2451 ext4_free_group_clusters(sb, desc);
2452 }
2453
2454 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2455 init_rwsem(&meta_group_info[i]->alloc_sem);
2456 meta_group_info[i]->bb_free_root = RB_ROOT;
2457 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
2458
2459#ifdef DOUBLE_CHECK
2460 {
2461 struct buffer_head *bh;
2462 meta_group_info[i]->bb_bitmap =
2463 kmalloc(sb->s_blocksize, GFP_NOFS);
2464 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2465 bh = ext4_read_block_bitmap(sb, group);
2466 BUG_ON(IS_ERR_OR_NULL(bh));
2467 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2468 sb->s_blocksize);
2469 put_bh(bh);
2470 }
2471#endif
2472
2473 return 0;
2474
2475exit_group_info:
2476 /* If a meta_group_info table has been allocated, release it now */
2477 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2478 struct ext4_group_info ***group_info;
2479
2480 rcu_read_lock();
2481 group_info = rcu_dereference(sbi->s_group_info);
2482 kfree(group_info[idx]);
2483 group_info[idx] = NULL;
2484 rcu_read_unlock();
2485 }
2486exit_meta_group_info:
2487 return -ENOMEM;
2488} /* ext4_mb_add_groupinfo */
2489
2490static int ext4_mb_init_backend(struct super_block *sb)
2491{
2492 ext4_group_t ngroups = ext4_get_groups_count(sb);
2493 ext4_group_t i;
2494 struct ext4_sb_info *sbi = EXT4_SB(sb);
2495 int err;
2496 struct ext4_group_desc *desc;
2497 struct ext4_group_info ***group_info;
2498 struct kmem_cache *cachep;
2499
2500 err = ext4_mb_alloc_groupinfo(sb, ngroups);
2501 if (err)
2502 return err;
2503
2504 sbi->s_buddy_cache = new_inode(sb);
2505 if (sbi->s_buddy_cache == NULL) {
2506 ext4_msg(sb, KERN_ERR, "can't get new inode");
2507 goto err_freesgi;
2508 }
2509 /* To avoid potentially colliding with an valid on-disk inode number,
2510 * use EXT4_BAD_INO for the buddy cache inode number. This inode is
2511 * not in the inode hash, so it should never be found by iget(), but
2512 * this will avoid confusion if it ever shows up during debugging. */
2513 sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
2514 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2515 for (i = 0; i < ngroups; i++) {
2516 cond_resched();
2517 desc = ext4_get_group_desc(sb, i, NULL);
2518 if (desc == NULL) {
2519 ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2520 goto err_freebuddy;
2521 }
2522 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2523 goto err_freebuddy;
2524 }
2525
2526 return 0;
2527
2528err_freebuddy:
2529 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2530 while (i-- > 0)
2531 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2532 i = sbi->s_group_info_size;
2533 rcu_read_lock();
2534 group_info = rcu_dereference(sbi->s_group_info);
2535 while (i-- > 0)
2536 kfree(group_info[i]);
2537 rcu_read_unlock();
2538 iput(sbi->s_buddy_cache);
2539err_freesgi:
2540 rcu_read_lock();
2541 kvfree(rcu_dereference(sbi->s_group_info));
2542 rcu_read_unlock();
2543 return -ENOMEM;
2544}
2545
2546static void ext4_groupinfo_destroy_slabs(void)
2547{
2548 int i;
2549
2550 for (i = 0; i < NR_GRPINFO_CACHES; i++) {
2551 kmem_cache_destroy(ext4_groupinfo_caches[i]);
2552 ext4_groupinfo_caches[i] = NULL;
2553 }
2554}
2555
2556static int ext4_groupinfo_create_slab(size_t size)
2557{
2558 static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
2559 int slab_size;
2560 int blocksize_bits = order_base_2(size);
2561 int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2562 struct kmem_cache *cachep;
2563
2564 if (cache_index >= NR_GRPINFO_CACHES)
2565 return -EINVAL;
2566
2567 if (unlikely(cache_index < 0))
2568 cache_index = 0;
2569
2570 mutex_lock(&ext4_grpinfo_slab_create_mutex);
2571 if (ext4_groupinfo_caches[cache_index]) {
2572 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2573 return 0; /* Already created */
2574 }
2575
2576 slab_size = offsetof(struct ext4_group_info,
2577 bb_counters[blocksize_bits + 2]);
2578
2579 cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
2580 slab_size, 0, SLAB_RECLAIM_ACCOUNT,
2581 NULL);
2582
2583 ext4_groupinfo_caches[cache_index] = cachep;
2584
2585 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2586 if (!cachep) {
2587 printk(KERN_EMERG
2588 "EXT4-fs: no memory for groupinfo slab cache\n");
2589 return -ENOMEM;
2590 }
2591
2592 return 0;
2593}
2594
2595int ext4_mb_init(struct super_block *sb)
2596{
2597 struct ext4_sb_info *sbi = EXT4_SB(sb);
2598 unsigned i, j;
2599 unsigned offset, offset_incr;
2600 unsigned max;
2601 int ret;
2602
2603 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2604
2605 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2606 if (sbi->s_mb_offsets == NULL) {
2607 ret = -ENOMEM;
2608 goto out;
2609 }
2610
2611 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2612 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2613 if (sbi->s_mb_maxs == NULL) {
2614 ret = -ENOMEM;
2615 goto out;
2616 }
2617
2618 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2619 if (ret < 0)
2620 goto out;
2621
2622 /* order 0 is regular bitmap */
2623 sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2624 sbi->s_mb_offsets[0] = 0;
2625
2626 i = 1;
2627 offset = 0;
2628 offset_incr = 1 << (sb->s_blocksize_bits - 1);
2629 max = sb->s_blocksize << 2;
2630 do {
2631 sbi->s_mb_offsets[i] = offset;
2632 sbi->s_mb_maxs[i] = max;
2633 offset += offset_incr;
2634 offset_incr = offset_incr >> 1;
2635 max = max >> 1;
2636 i++;
2637 } while (i <= sb->s_blocksize_bits + 1);
2638
2639 spin_lock_init(&sbi->s_md_lock);
2640 spin_lock_init(&sbi->s_bal_lock);
2641 sbi->s_mb_free_pending = 0;
2642 INIT_LIST_HEAD(&sbi->s_freed_data_list);
2643
2644 sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2645 sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2646 sbi->s_mb_stats = MB_DEFAULT_STATS;
2647 sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2648 sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2649 /*
2650 * The default group preallocation is 512, which for 4k block
2651 * sizes translates to 2 megabytes. However for bigalloc file
2652 * systems, this is probably too big (i.e, if the cluster size
2653 * is 1 megabyte, then group preallocation size becomes half a
2654 * gigabyte!). As a default, we will keep a two megabyte
2655 * group pralloc size for cluster sizes up to 64k, and after
2656 * that, we will force a minimum group preallocation size of
2657 * 32 clusters. This translates to 8 megs when the cluster
2658 * size is 256k, and 32 megs when the cluster size is 1 meg,
2659 * which seems reasonable as a default.
2660 */
2661 sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
2662 sbi->s_cluster_bits, 32);
2663 /*
2664 * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
2665 * to the lowest multiple of s_stripe which is bigger than
2666 * the s_mb_group_prealloc as determined above. We want
2667 * the preallocation size to be an exact multiple of the
2668 * RAID stripe size so that preallocations don't fragment
2669 * the stripes.
2670 */
2671 if (sbi->s_stripe > 1) {
2672 sbi->s_mb_group_prealloc = roundup(
2673 sbi->s_mb_group_prealloc, sbi->s_stripe);
2674 }
2675
2676 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2677 if (sbi->s_locality_groups == NULL) {
2678 ret = -ENOMEM;
2679 goto out;
2680 }
2681 for_each_possible_cpu(i) {
2682 struct ext4_locality_group *lg;
2683 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2684 mutex_init(&lg->lg_mutex);
2685 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2686 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2687 spin_lock_init(&lg->lg_prealloc_lock);
2688 }
2689
2690 /* init file for buddy data */
2691 ret = ext4_mb_init_backend(sb);
2692 if (ret != 0)
2693 goto out_free_locality_groups;
2694
2695 return 0;
2696
2697out_free_locality_groups:
2698 free_percpu(sbi->s_locality_groups);
2699 sbi->s_locality_groups = NULL;
2700out:
2701 kfree(sbi->s_mb_offsets);
2702 sbi->s_mb_offsets = NULL;
2703 kfree(sbi->s_mb_maxs);
2704 sbi->s_mb_maxs = NULL;
2705 return ret;
2706}
2707
2708/* need to called with the ext4 group lock held */
2709static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2710{
2711 struct ext4_prealloc_space *pa;
2712 struct list_head *cur, *tmp;
2713 int count = 0;
2714
2715 list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2716 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2717 list_del(&pa->pa_group_list);
2718 count++;
2719 kmem_cache_free(ext4_pspace_cachep, pa);
2720 }
2721 if (count)
2722 mb_debug(1, "mballoc: %u PAs left\n", count);
2723
2724}
2725
2726int ext4_mb_release(struct super_block *sb)
2727{
2728 ext4_group_t ngroups = ext4_get_groups_count(sb);
2729 ext4_group_t i;
2730 int num_meta_group_infos;
2731 struct ext4_group_info *grinfo, ***group_info;
2732 struct ext4_sb_info *sbi = EXT4_SB(sb);
2733 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2734
2735 if (sbi->s_group_info) {
2736 for (i = 0; i < ngroups; i++) {
2737 cond_resched();
2738 grinfo = ext4_get_group_info(sb, i);
2739#ifdef DOUBLE_CHECK
2740 kfree(grinfo->bb_bitmap);
2741#endif
2742 ext4_lock_group(sb, i);
2743 ext4_mb_cleanup_pa(grinfo);
2744 ext4_unlock_group(sb, i);
2745 kmem_cache_free(cachep, grinfo);
2746 }
2747 num_meta_group_infos = (ngroups +
2748 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2749 EXT4_DESC_PER_BLOCK_BITS(sb);
2750 rcu_read_lock();
2751 group_info = rcu_dereference(sbi->s_group_info);
2752 for (i = 0; i < num_meta_group_infos; i++)
2753 kfree(group_info[i]);
2754 kvfree(group_info);
2755 rcu_read_unlock();
2756 }
2757 kfree(sbi->s_mb_offsets);
2758 kfree(sbi->s_mb_maxs);
2759 iput(sbi->s_buddy_cache);
2760 if (sbi->s_mb_stats) {
2761 ext4_msg(sb, KERN_INFO,
2762 "mballoc: %u blocks %u reqs (%u success)",
2763 atomic_read(&sbi->s_bal_allocated),
2764 atomic_read(&sbi->s_bal_reqs),
2765 atomic_read(&sbi->s_bal_success));
2766 ext4_msg(sb, KERN_INFO,
2767 "mballoc: %u extents scanned, %u goal hits, "
2768 "%u 2^N hits, %u breaks, %u lost",
2769 atomic_read(&sbi->s_bal_ex_scanned),
2770 atomic_read(&sbi->s_bal_goals),
2771 atomic_read(&sbi->s_bal_2orders),
2772 atomic_read(&sbi->s_bal_breaks),
2773 atomic_read(&sbi->s_mb_lost_chunks));
2774 ext4_msg(sb, KERN_INFO,
2775 "mballoc: %lu generated and it took %Lu",
2776 sbi->s_mb_buddies_generated,
2777 sbi->s_mb_generation_time);
2778 ext4_msg(sb, KERN_INFO,
2779 "mballoc: %u preallocated, %u discarded",
2780 atomic_read(&sbi->s_mb_preallocated),
2781 atomic_read(&sbi->s_mb_discarded));
2782 }
2783
2784 free_percpu(sbi->s_locality_groups);
2785
2786 return 0;
2787}
2788
2789static inline int ext4_issue_discard(struct super_block *sb,
2790 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
2791 struct bio **biop)
2792{
2793 ext4_fsblk_t discard_block;
2794
2795 discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
2796 ext4_group_first_block_no(sb, block_group));
2797 count = EXT4_C2B(EXT4_SB(sb), count);
2798 trace_ext4_discard_blocks(sb,
2799 (unsigned long long) discard_block, count);
2800 if (biop) {
2801 return __blkdev_issue_discard(sb->s_bdev,
2802 (sector_t)discard_block << (sb->s_blocksize_bits - 9),
2803 (sector_t)count << (sb->s_blocksize_bits - 9),
2804 GFP_NOFS, 0, biop);
2805 } else
2806 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
2807}
2808
2809static void ext4_free_data_in_buddy(struct super_block *sb,
2810 struct ext4_free_data *entry)
2811{
2812 struct ext4_buddy e4b;
2813 struct ext4_group_info *db;
2814 int err, count = 0, count2 = 0;
2815
2816 mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2817 entry->efd_count, entry->efd_group, entry);
2818
2819 err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
2820 /* we expect to find existing buddy because it's pinned */
2821 BUG_ON(err != 0);
2822
2823 spin_lock(&EXT4_SB(sb)->s_md_lock);
2824 EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
2825 spin_unlock(&EXT4_SB(sb)->s_md_lock);
2826
2827 db = e4b.bd_info;
2828 /* there are blocks to put in buddy to make them really free */
2829 count += entry->efd_count;
2830 count2++;
2831 ext4_lock_group(sb, entry->efd_group);
2832 /* Take it out of per group rb tree */
2833 rb_erase(&entry->efd_node, &(db->bb_free_root));
2834 mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
2835
2836 /*
2837 * Clear the trimmed flag for the group so that the next
2838 * ext4_trim_fs can trim it.
2839 */
2840 EXT4_MB_GRP_CLEAR_TRIMMED(db);
2841
2842 if (!db->bb_free_root.rb_node) {
2843 /* No more items in the per group rb tree
2844 * balance refcounts from ext4_mb_free_metadata()
2845 */
2846 put_page(e4b.bd_buddy_page);
2847 put_page(e4b.bd_bitmap_page);
2848 }
2849 ext4_unlock_group(sb, entry->efd_group);
2850 kmem_cache_free(ext4_free_data_cachep, entry);
2851 ext4_mb_unload_buddy(&e4b);
2852
2853 mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2854}
2855
2856/*
2857 * This function is called by the jbd2 layer once the commit has finished,
2858 * so we know we can free the blocks that were released with that commit.
2859 */
2860void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
2861{
2862 struct ext4_sb_info *sbi = EXT4_SB(sb);
2863 struct ext4_free_data *entry, *tmp;
2864 struct bio *discard_bio = NULL;
2865 struct list_head freed_data_list;
2866 struct list_head *cut_pos = NULL;
2867 int err;
2868
2869 INIT_LIST_HEAD(&freed_data_list);
2870
2871 spin_lock(&sbi->s_md_lock);
2872 list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
2873 if (entry->efd_tid != commit_tid)
2874 break;
2875 cut_pos = &entry->efd_list;
2876 }
2877 if (cut_pos)
2878 list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
2879 cut_pos);
2880 spin_unlock(&sbi->s_md_lock);
2881
2882 if (test_opt(sb, DISCARD)) {
2883 list_for_each_entry(entry, &freed_data_list, efd_list) {
2884 err = ext4_issue_discard(sb, entry->efd_group,
2885 entry->efd_start_cluster,
2886 entry->efd_count,
2887 &discard_bio);
2888 if (err && err != -EOPNOTSUPP) {
2889 ext4_msg(sb, KERN_WARNING, "discard request in"
2890 " group:%d block:%d count:%d failed"
2891 " with %d", entry->efd_group,
2892 entry->efd_start_cluster,
2893 entry->efd_count, err);
2894 } else if (err == -EOPNOTSUPP)
2895 break;
2896 }
2897
2898 if (discard_bio) {
2899 submit_bio_wait(discard_bio);
2900 bio_put(discard_bio);
2901 }
2902 }
2903
2904 list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
2905 ext4_free_data_in_buddy(sb, entry);
2906}
2907
2908int __init ext4_init_mballoc(void)
2909{
2910 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
2911 SLAB_RECLAIM_ACCOUNT);
2912 if (ext4_pspace_cachep == NULL)
2913 return -ENOMEM;
2914
2915 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
2916 SLAB_RECLAIM_ACCOUNT);
2917 if (ext4_ac_cachep == NULL) {
2918 kmem_cache_destroy(ext4_pspace_cachep);
2919 return -ENOMEM;
2920 }
2921
2922 ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
2923 SLAB_RECLAIM_ACCOUNT);
2924 if (ext4_free_data_cachep == NULL) {
2925 kmem_cache_destroy(ext4_pspace_cachep);
2926 kmem_cache_destroy(ext4_ac_cachep);
2927 return -ENOMEM;
2928 }
2929 return 0;
2930}
2931
2932void ext4_exit_mballoc(void)
2933{
2934 /*
2935 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
2936 * before destroying the slab cache.
2937 */
2938 rcu_barrier();
2939 kmem_cache_destroy(ext4_pspace_cachep);
2940 kmem_cache_destroy(ext4_ac_cachep);
2941 kmem_cache_destroy(ext4_free_data_cachep);
2942 ext4_groupinfo_destroy_slabs();
2943}
2944
2945
2946/*
2947 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2948 * Returns 0 if success or error code
2949 */
2950static noinline_for_stack int
2951ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2952 handle_t *handle, unsigned int reserv_clstrs)
2953{
2954 struct buffer_head *bitmap_bh = NULL;
2955 struct ext4_group_desc *gdp;
2956 struct buffer_head *gdp_bh;
2957 struct ext4_sb_info *sbi;
2958 struct super_block *sb;
2959 ext4_fsblk_t block;
2960 int err, len;
2961
2962 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2963 BUG_ON(ac->ac_b_ex.fe_len <= 0);
2964
2965 sb = ac->ac_sb;
2966 sbi = EXT4_SB(sb);
2967
2968 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2969 if (IS_ERR(bitmap_bh)) {
2970 err = PTR_ERR(bitmap_bh);
2971 bitmap_bh = NULL;
2972 goto out_err;
2973 }
2974
2975 BUFFER_TRACE(bitmap_bh, "getting write access");
2976 err = ext4_journal_get_write_access(handle, bitmap_bh);
2977 if (err)
2978 goto out_err;
2979
2980 err = -EIO;
2981 gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
2982 if (!gdp)
2983 goto out_err;
2984
2985 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
2986 ext4_free_group_clusters(sb, gdp));
2987
2988 BUFFER_TRACE(gdp_bh, "get_write_access");
2989 err = ext4_journal_get_write_access(handle, gdp_bh);
2990 if (err)
2991 goto out_err;
2992
2993 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
2994
2995 len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
2996 if (!ext4_data_block_valid(sbi, block, len)) {
2997 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
2998 "fs metadata", block, block+len);
2999 /* File system mounted not to panic on error
3000 * Fix the bitmap and return EFSCORRUPTED
3001 * We leak some of the blocks here.
3002 */
3003 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3004 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3005 ac->ac_b_ex.fe_len);
3006 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3007 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3008 if (!err)
3009 err = -EFSCORRUPTED;
3010 goto out_err;
3011 }
3012
3013 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3014#ifdef AGGRESSIVE_CHECK
3015 {
3016 int i;
3017 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3018 BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3019 bitmap_bh->b_data));
3020 }
3021 }
3022#endif
3023 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3024 ac->ac_b_ex.fe_len);
3025 if (ext4_has_group_desc_csum(sb) &&
3026 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3027 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3028 ext4_free_group_clusters_set(sb, gdp,
3029 ext4_free_clusters_after_init(sb,
3030 ac->ac_b_ex.fe_group, gdp));
3031 }
3032 len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
3033 ext4_free_group_clusters_set(sb, gdp, len);
3034 ext4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);
3035 ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
3036
3037 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3038 percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
3039 /*
3040 * Now reduce the dirty block count also. Should not go negative
3041 */
3042 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3043 /* release all the reserved blocks if non delalloc */
3044 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
3045 reserv_clstrs);
3046
3047 if (sbi->s_log_groups_per_flex) {
3048 ext4_group_t flex_group = ext4_flex_group(sbi,
3049 ac->ac_b_ex.fe_group);
3050 atomic64_sub(ac->ac_b_ex.fe_len,
3051 &sbi_array_rcu_deref(sbi, s_flex_groups,
3052 flex_group)->free_clusters);
3053 }
3054
3055 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3056 if (err)
3057 goto out_err;
3058 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3059
3060out_err:
3061 brelse(bitmap_bh);
3062 return err;
3063}
3064
3065/*
3066 * here we normalize request for locality group
3067 * Group request are normalized to s_mb_group_prealloc, which goes to
3068 * s_strip if we set the same via mount option.
3069 * s_mb_group_prealloc can be configured via
3070 * /sys/fs/ext4/<partition>/mb_group_prealloc
3071 *
3072 * XXX: should we try to preallocate more than the group has now?
3073 */
3074static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3075{
3076 struct super_block *sb = ac->ac_sb;
3077 struct ext4_locality_group *lg = ac->ac_lg;
3078
3079 BUG_ON(lg == NULL);
3080 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3081 mb_debug(1, "#%u: goal %u blocks for locality group\n",
3082 current->pid, ac->ac_g_ex.fe_len);
3083}
3084
3085/*
3086 * Normalization means making request better in terms of
3087 * size and alignment
3088 */
3089static noinline_for_stack void
3090ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3091 struct ext4_allocation_request *ar)
3092{
3093 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3094 struct ext4_super_block *es = sbi->s_es;
3095 int bsbits, max;
3096 loff_t size, start_off, end;
3097 loff_t orig_size __maybe_unused;
3098 ext4_lblk_t start;
3099 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3100 struct ext4_prealloc_space *pa;
3101
3102 /* do normalize only data requests, metadata requests
3103 do not need preallocation */
3104 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3105 return;
3106
3107 /* sometime caller may want exact blocks */
3108 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3109 return;
3110
3111 /* caller may indicate that preallocation isn't
3112 * required (it's a tail, for example) */
3113 if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3114 return;
3115
3116 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3117 ext4_mb_normalize_group_request(ac);
3118 return ;
3119 }
3120
3121 bsbits = ac->ac_sb->s_blocksize_bits;
3122
3123 /* first, let's learn actual file size
3124 * given current request is allocated */
3125 size = extent_logical_end(sbi, &ac->ac_o_ex);
3126 size = size << bsbits;
3127 if (size < i_size_read(ac->ac_inode))
3128 size = i_size_read(ac->ac_inode);
3129 orig_size = size;
3130
3131 /* max size of free chunks */
3132 max = 2 << bsbits;
3133
3134#define NRL_CHECK_SIZE(req, size, max, chunk_size) \
3135 (req <= (size) || max <= (chunk_size))
3136
3137 /* first, try to predict filesize */
3138 /* XXX: should this table be tunable? */
3139 start_off = 0;
3140 if (size <= 16 * 1024) {
3141 size = 16 * 1024;
3142 } else if (size <= 32 * 1024) {
3143 size = 32 * 1024;
3144 } else if (size <= 64 * 1024) {
3145 size = 64 * 1024;
3146 } else if (size <= 128 * 1024) {
3147 size = 128 * 1024;
3148 } else if (size <= 256 * 1024) {
3149 size = 256 * 1024;
3150 } else if (size <= 512 * 1024) {
3151 size = 512 * 1024;
3152 } else if (size <= 1024 * 1024) {
3153 size = 1024 * 1024;
3154 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3155 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3156 (21 - bsbits)) << 21;
3157 size = 2 * 1024 * 1024;
3158 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3159 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3160 (22 - bsbits)) << 22;
3161 size = 4 * 1024 * 1024;
3162 } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3163 (8<<20)>>bsbits, max, 8 * 1024)) {
3164 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3165 (23 - bsbits)) << 23;
3166 size = 8 * 1024 * 1024;
3167 } else {
3168 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
3169 size = (loff_t) EXT4_C2B(EXT4_SB(ac->ac_sb),
3170 ac->ac_o_ex.fe_len) << bsbits;
3171 }
3172 size = size >> bsbits;
3173 start = start_off >> bsbits;
3174
3175 /*
3176 * For tiny groups (smaller than 8MB) the chosen allocation
3177 * alignment may be larger than group size. Make sure the
3178 * alignment does not move allocation to a different group which
3179 * makes mballoc fail assertions later.
3180 */
3181 start = max(start, rounddown(ac->ac_o_ex.fe_logical,
3182 (ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
3183
3184 /* avoid unnecessary preallocation that may trigger assertions */
3185 if (start + size > EXT_MAX_BLOCKS)
3186 size = EXT_MAX_BLOCKS - start;
3187
3188 /* don't cover already allocated blocks in selected range */
3189 if (ar->pleft && start <= ar->lleft) {
3190 size -= ar->lleft + 1 - start;
3191 start = ar->lleft + 1;
3192 }
3193 if (ar->pright && start + size - 1 >= ar->lright)
3194 size -= start + size - ar->lright;
3195
3196 /*
3197 * Trim allocation request for filesystems with artificially small
3198 * groups.
3199 */
3200 if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
3201 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
3202
3203 end = start + size;
3204
3205 /* check we don't cross already preallocated blocks */
3206 rcu_read_lock();
3207 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3208 loff_t pa_end;
3209
3210 if (pa->pa_deleted)
3211 continue;
3212 spin_lock(&pa->pa_lock);
3213 if (pa->pa_deleted) {
3214 spin_unlock(&pa->pa_lock);
3215 continue;
3216 }
3217
3218 pa_end = pa_logical_end(EXT4_SB(ac->ac_sb), pa);
3219
3220 /* PA must not overlap original request */
3221 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3222 ac->ac_o_ex.fe_logical < pa->pa_lstart));
3223
3224 /* skip PAs this normalized request doesn't overlap with */
3225 if (pa->pa_lstart >= end || pa_end <= start) {
3226 spin_unlock(&pa->pa_lock);
3227 continue;
3228 }
3229 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3230
3231 /* adjust start or end to be adjacent to this pa */
3232 if (pa_end <= ac->ac_o_ex.fe_logical) {
3233 BUG_ON(pa_end < start);
3234 start = pa_end;
3235 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3236 BUG_ON(pa->pa_lstart > end);
3237 end = pa->pa_lstart;
3238 }
3239 spin_unlock(&pa->pa_lock);
3240 }
3241 rcu_read_unlock();
3242 size = end - start;
3243
3244 /* XXX: extra loop to check we really don't overlap preallocations */
3245 rcu_read_lock();
3246 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3247 loff_t pa_end;
3248
3249 spin_lock(&pa->pa_lock);
3250 if (pa->pa_deleted == 0) {
3251 pa_end = pa_logical_end(EXT4_SB(ac->ac_sb), pa);
3252 BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3253 }
3254 spin_unlock(&pa->pa_lock);
3255 }
3256 rcu_read_unlock();
3257
3258 if (start + size <= ac->ac_o_ex.fe_logical &&
3259 start > ac->ac_o_ex.fe_logical) {
3260 ext4_msg(ac->ac_sb, KERN_ERR,
3261 "start %lu, size %lu, fe_logical %lu",
3262 (unsigned long) start, (unsigned long) size,
3263 (unsigned long) ac->ac_o_ex.fe_logical);
3264 BUG();
3265 }
3266 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3267
3268 /* now prepare goal request */
3269
3270 /* XXX: is it better to align blocks WRT to logical
3271 * placement or satisfy big request as is */
3272 ac->ac_g_ex.fe_logical = start;
3273 ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3274
3275 /* define goal start in order to merge */
3276 if (ar->pright && (ar->lright == (start + size)) &&
3277 ar->pright >= size &&
3278 ar->pright - size >= le32_to_cpu(es->s_first_data_block)) {
3279 /* merge to the right */
3280 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3281 &ac->ac_g_ex.fe_group,
3282 &ac->ac_g_ex.fe_start);
3283 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3284 }
3285 if (ar->pleft && (ar->lleft + 1 == start) &&
3286 ar->pleft + 1 < ext4_blocks_count(es)) {
3287 /* merge to the left */
3288 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3289 &ac->ac_g_ex.fe_group,
3290 &ac->ac_g_ex.fe_start);
3291 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3292 }
3293
3294 mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3295 (unsigned) orig_size, (unsigned) start);
3296}
3297
3298static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3299{
3300 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3301
3302 if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3303 atomic_inc(&sbi->s_bal_reqs);
3304 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3305 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3306 atomic_inc(&sbi->s_bal_success);
3307 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3308 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3309 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3310 atomic_inc(&sbi->s_bal_goals);
3311 if (ac->ac_found > sbi->s_mb_max_to_scan)
3312 atomic_inc(&sbi->s_bal_breaks);
3313 }
3314
3315 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3316 trace_ext4_mballoc_alloc(ac);
3317 else
3318 trace_ext4_mballoc_prealloc(ac);
3319}
3320
3321/*
3322 * Called on failure; free up any blocks from the inode PA for this
3323 * context. We don't need this for MB_GROUP_PA because we only change
3324 * pa_free in ext4_mb_release_context(), but on failure, we've already
3325 * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3326 */
3327static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3328{
3329 struct ext4_prealloc_space *pa = ac->ac_pa;
3330 struct ext4_buddy e4b;
3331 int err;
3332
3333 if (pa == NULL) {
3334 if (ac->ac_f_ex.fe_len == 0)
3335 return;
3336 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
3337 if (err) {
3338 /*
3339 * This should never happen since we pin the
3340 * pages in the ext4_allocation_context so
3341 * ext4_mb_load_buddy() should never fail.
3342 */
3343 WARN(1, "mb_load_buddy failed (%d)", err);
3344 return;
3345 }
3346 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3347 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
3348 ac->ac_f_ex.fe_len);
3349 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3350 ext4_mb_unload_buddy(&e4b);
3351 return;
3352 }
3353 if (pa->pa_type == MB_INODE_PA)
3354 pa->pa_free += ac->ac_b_ex.fe_len;
3355}
3356
3357/*
3358 * use blocks preallocated to inode
3359 */
3360static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3361 struct ext4_prealloc_space *pa)
3362{
3363 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3364 ext4_fsblk_t start;
3365 ext4_fsblk_t end;
3366 int len;
3367
3368 /* found preallocated blocks, use them */
3369 start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3370 end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
3371 start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
3372 len = EXT4_NUM_B2C(sbi, end - start);
3373 ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3374 &ac->ac_b_ex.fe_start);
3375 ac->ac_b_ex.fe_len = len;
3376 ac->ac_status = AC_STATUS_FOUND;
3377 ac->ac_pa = pa;
3378
3379 BUG_ON(start < pa->pa_pstart);
3380 BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3381 BUG_ON(pa->pa_free < len);
3382 BUG_ON(ac->ac_b_ex.fe_len <= 0);
3383 pa->pa_free -= len;
3384
3385 mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3386}
3387
3388/*
3389 * use blocks preallocated to locality group
3390 */
3391static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3392 struct ext4_prealloc_space *pa)
3393{
3394 unsigned int len = ac->ac_o_ex.fe_len;
3395
3396 ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3397 &ac->ac_b_ex.fe_group,
3398 &ac->ac_b_ex.fe_start);
3399 ac->ac_b_ex.fe_len = len;
3400 ac->ac_status = AC_STATUS_FOUND;
3401 ac->ac_pa = pa;
3402
3403 /* we don't correct pa_pstart or pa_plen here to avoid
3404 * possible race when the group is being loaded concurrently
3405 * instead we correct pa later, after blocks are marked
3406 * in on-disk bitmap -- see ext4_mb_release_context()
3407 * Other CPUs are prevented from allocating from this pa by lg_mutex
3408 */
3409 mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3410}
3411
3412/*
3413 * Return the prealloc space that have minimal distance
3414 * from the goal block. @cpa is the prealloc
3415 * space that is having currently known minimal distance
3416 * from the goal block.
3417 */
3418static struct ext4_prealloc_space *
3419ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3420 struct ext4_prealloc_space *pa,
3421 struct ext4_prealloc_space *cpa)
3422{
3423 ext4_fsblk_t cur_distance, new_distance;
3424
3425 if (cpa == NULL) {
3426 atomic_inc(&pa->pa_count);
3427 return pa;
3428 }
3429 cur_distance = abs(goal_block - cpa->pa_pstart);
3430 new_distance = abs(goal_block - pa->pa_pstart);
3431
3432 if (cur_distance <= new_distance)
3433 return cpa;
3434
3435 /* drop the previous reference */
3436 atomic_dec(&cpa->pa_count);
3437 atomic_inc(&pa->pa_count);
3438 return pa;
3439}
3440
3441/*
3442 * search goal blocks in preallocated space
3443 */
3444static noinline_for_stack int
3445ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3446{
3447 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3448 int order, i;
3449 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3450 struct ext4_locality_group *lg;
3451 struct ext4_prealloc_space *pa, *cpa = NULL;
3452 ext4_fsblk_t goal_block;
3453
3454 /* only data can be preallocated */
3455 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3456 return 0;
3457
3458 /* first, try per-file preallocation */
3459 rcu_read_lock();
3460 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3461
3462 /* all fields in this condition don't change,
3463 * so we can skip locking for them */
3464 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3465 ac->ac_o_ex.fe_logical >= pa_logical_end(sbi, pa))
3466 continue;
3467
3468 /* non-extent files can't have physical blocks past 2^32 */
3469 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3470 (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
3471 EXT4_MAX_BLOCK_FILE_PHYS))
3472 continue;
3473
3474 /* found preallocated blocks, use them */
3475 spin_lock(&pa->pa_lock);
3476 if (pa->pa_deleted == 0 && pa->pa_free) {
3477 atomic_inc(&pa->pa_count);
3478 ext4_mb_use_inode_pa(ac, pa);
3479 spin_unlock(&pa->pa_lock);
3480 ac->ac_criteria = 10;
3481 rcu_read_unlock();
3482 return 1;
3483 }
3484 spin_unlock(&pa->pa_lock);
3485 }
3486 rcu_read_unlock();
3487
3488 /* can we use group allocation? */
3489 if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3490 return 0;
3491
3492 /* inode may have no locality group for some reason */
3493 lg = ac->ac_lg;
3494 if (lg == NULL)
3495 return 0;
3496 order = fls(ac->ac_o_ex.fe_len) - 1;
3497 if (order > PREALLOC_TB_SIZE - 1)
3498 /* The max size of hash table is PREALLOC_TB_SIZE */
3499 order = PREALLOC_TB_SIZE - 1;
3500
3501 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3502 /*
3503 * search for the prealloc space that is having
3504 * minimal distance from the goal block.
3505 */
3506 for (i = order; i < PREALLOC_TB_SIZE; i++) {
3507 rcu_read_lock();
3508 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3509 pa_inode_list) {
3510 spin_lock(&pa->pa_lock);
3511 if (pa->pa_deleted == 0 &&
3512 pa->pa_free >= ac->ac_o_ex.fe_len) {
3513
3514 cpa = ext4_mb_check_group_pa(goal_block,
3515 pa, cpa);
3516 }
3517 spin_unlock(&pa->pa_lock);
3518 }
3519 rcu_read_unlock();
3520 }
3521 if (cpa) {
3522 ext4_mb_use_group_pa(ac, cpa);
3523 ac->ac_criteria = 20;
3524 return 1;
3525 }
3526 return 0;
3527}
3528
3529/*
3530 * the function goes through all block freed in the group
3531 * but not yet committed and marks them used in in-core bitmap.
3532 * buddy must be generated from this bitmap
3533 * Need to be called with the ext4 group lock held
3534 */
3535static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3536 ext4_group_t group)
3537{
3538 struct rb_node *n;
3539 struct ext4_group_info *grp;
3540 struct ext4_free_data *entry;
3541
3542 grp = ext4_get_group_info(sb, group);
3543 n = rb_first(&(grp->bb_free_root));
3544
3545 while (n) {
3546 entry = rb_entry(n, struct ext4_free_data, efd_node);
3547 ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
3548 n = rb_next(n);
3549 }
3550 return;
3551}
3552
3553/*
3554 * the function goes through all preallocation in this group and marks them
3555 * used in in-core bitmap. buddy must be generated from this bitmap
3556 * Need to be called with ext4 group lock held
3557 */
3558static noinline_for_stack
3559void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3560 ext4_group_t group)
3561{
3562 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3563 struct ext4_prealloc_space *pa;
3564 struct list_head *cur;
3565 ext4_group_t groupnr;
3566 ext4_grpblk_t start;
3567 int preallocated = 0;
3568 int len;
3569
3570 /* all form of preallocation discards first load group,
3571 * so the only competing code is preallocation use.
3572 * we don't need any locking here
3573 * notice we do NOT ignore preallocations with pa_deleted
3574 * otherwise we could leave used blocks available for
3575 * allocation in buddy when concurrent ext4_mb_put_pa()
3576 * is dropping preallocation
3577 */
3578 list_for_each(cur, &grp->bb_prealloc_list) {
3579 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3580 spin_lock(&pa->pa_lock);
3581 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3582 &groupnr, &start);
3583 len = pa->pa_len;
3584 spin_unlock(&pa->pa_lock);
3585 if (unlikely(len == 0))
3586 continue;
3587 BUG_ON(groupnr != group);
3588 ext4_set_bits(bitmap, start, len);
3589 preallocated += len;
3590 }
3591 mb_debug(1, "preallocated %u for group %u\n", preallocated, group);
3592}
3593
3594static void ext4_mb_pa_callback(struct rcu_head *head)
3595{
3596 struct ext4_prealloc_space *pa;
3597 pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3598
3599 BUG_ON(atomic_read(&pa->pa_count));
3600 BUG_ON(pa->pa_deleted == 0);
3601 kmem_cache_free(ext4_pspace_cachep, pa);
3602}
3603
3604/*
3605 * drops a reference to preallocated space descriptor
3606 * if this was the last reference and the space is consumed
3607 */
3608static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3609 struct super_block *sb, struct ext4_prealloc_space *pa)
3610{
3611 ext4_group_t grp;
3612 ext4_fsblk_t grp_blk;
3613
3614 /* in this short window concurrent discard can set pa_deleted */
3615 spin_lock(&pa->pa_lock);
3616 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
3617 spin_unlock(&pa->pa_lock);
3618 return;
3619 }
3620
3621 if (pa->pa_deleted == 1) {
3622 spin_unlock(&pa->pa_lock);
3623 return;
3624 }
3625
3626 pa->pa_deleted = 1;
3627 spin_unlock(&pa->pa_lock);
3628
3629 grp_blk = pa->pa_pstart;
3630 /*
3631 * If doing group-based preallocation, pa_pstart may be in the
3632 * next group when pa is used up
3633 */
3634 if (pa->pa_type == MB_GROUP_PA)
3635 grp_blk--;
3636
3637 grp = ext4_get_group_number(sb, grp_blk);
3638
3639 /*
3640 * possible race:
3641 *
3642 * P1 (buddy init) P2 (regular allocation)
3643 * find block B in PA
3644 * copy on-disk bitmap to buddy
3645 * mark B in on-disk bitmap
3646 * drop PA from group
3647 * mark all PAs in buddy
3648 *
3649 * thus, P1 initializes buddy with B available. to prevent this
3650 * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3651 * against that pair
3652 */
3653 ext4_lock_group(sb, grp);
3654 list_del(&pa->pa_group_list);
3655 ext4_unlock_group(sb, grp);
3656
3657 spin_lock(pa->pa_obj_lock);
3658 list_del_rcu(&pa->pa_inode_list);
3659 spin_unlock(pa->pa_obj_lock);
3660
3661 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3662}
3663
3664/*
3665 * creates new preallocated space for given inode
3666 */
3667static noinline_for_stack int
3668ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3669{
3670 struct super_block *sb = ac->ac_sb;
3671 struct ext4_sb_info *sbi = EXT4_SB(sb);
3672 struct ext4_prealloc_space *pa;
3673 struct ext4_group_info *grp;
3674 struct ext4_inode_info *ei;
3675
3676 /* preallocate only when found space is larger then requested */
3677 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3678 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3679 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3680
3681 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3682 if (pa == NULL)
3683 return -ENOMEM;
3684
3685 if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3686 struct ext4_free_extent ex = {
3687 .fe_logical = ac->ac_g_ex.fe_logical,
3688 .fe_len = ac->ac_g_ex.fe_len,
3689 };
3690 loff_t orig_goal_end = extent_logical_end(sbi, &ex);
3691 loff_t o_ex_end = extent_logical_end(sbi, &ac->ac_o_ex);
3692
3693 /*
3694 * We can't allocate as much as normalizer wants, so we try
3695 * to get proper lstart to cover the original request, except
3696 * when the goal doesn't cover the original request as below:
3697 *
3698 * orig_ex:2045/2055(10), isize:8417280 -> normalized:0/2048
3699 * best_ex:0/200(200) -> adjusted: 1848/2048(200)
3700 */
3701 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3702 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3703
3704 /*
3705 * Use the below logic for adjusting best extent as it keeps
3706 * fragmentation in check while ensuring logical range of best
3707 * extent doesn't overflow out of goal extent:
3708 *
3709 * 1. Check if best ex can be kept at end of goal and still
3710 * cover original start
3711 * 2. Else, check if best ex can be kept at start of goal and
3712 * still cover original end
3713 * 3. Else, keep the best ex at start of original request.
3714 */
3715 ex.fe_len = ac->ac_b_ex.fe_len;
3716
3717 ex.fe_logical = orig_goal_end - EXT4_C2B(sbi, ex.fe_len);
3718 if (ac->ac_o_ex.fe_logical >= ex.fe_logical)
3719 goto adjust_bex;
3720
3721 ex.fe_logical = ac->ac_g_ex.fe_logical;
3722 if (o_ex_end <= extent_logical_end(sbi, &ex))
3723 goto adjust_bex;
3724
3725 ex.fe_logical = ac->ac_o_ex.fe_logical;
3726adjust_bex:
3727 ac->ac_b_ex.fe_logical = ex.fe_logical;
3728
3729 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3730 BUG_ON(extent_logical_end(sbi, &ex) > orig_goal_end);
3731 }
3732
3733 /* preallocation can change ac_b_ex, thus we store actually
3734 * allocated blocks for history */
3735 ac->ac_f_ex = ac->ac_b_ex;
3736
3737 pa->pa_lstart = ac->ac_b_ex.fe_logical;
3738 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3739 pa->pa_len = ac->ac_b_ex.fe_len;
3740 pa->pa_free = pa->pa_len;
3741 atomic_set(&pa->pa_count, 1);
3742 spin_lock_init(&pa->pa_lock);
3743 INIT_LIST_HEAD(&pa->pa_inode_list);
3744 INIT_LIST_HEAD(&pa->pa_group_list);
3745 pa->pa_deleted = 0;
3746 pa->pa_type = MB_INODE_PA;
3747
3748 mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3749 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3750 trace_ext4_mb_new_inode_pa(ac, pa);
3751
3752 ext4_mb_use_inode_pa(ac, pa);
3753 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
3754
3755 ei = EXT4_I(ac->ac_inode);
3756 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3757
3758 pa->pa_obj_lock = &ei->i_prealloc_lock;
3759 pa->pa_inode = ac->ac_inode;
3760
3761 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3762 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3763 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3764
3765 spin_lock(pa->pa_obj_lock);
3766 list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3767 spin_unlock(pa->pa_obj_lock);
3768
3769 return 0;
3770}
3771
3772/*
3773 * creates new preallocated space for locality group inodes belongs to
3774 */
3775static noinline_for_stack int
3776ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3777{
3778 struct super_block *sb = ac->ac_sb;
3779 struct ext4_locality_group *lg;
3780 struct ext4_prealloc_space *pa;
3781 struct ext4_group_info *grp;
3782
3783 /* preallocate only when found space is larger then requested */
3784 BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3785 BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3786 BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3787
3788 BUG_ON(ext4_pspace_cachep == NULL);
3789 pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3790 if (pa == NULL)
3791 return -ENOMEM;
3792
3793 /* preallocation can change ac_b_ex, thus we store actually
3794 * allocated blocks for history */
3795 ac->ac_f_ex = ac->ac_b_ex;
3796
3797 pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3798 pa->pa_lstart = pa->pa_pstart;
3799 pa->pa_len = ac->ac_b_ex.fe_len;
3800 pa->pa_free = pa->pa_len;
3801 atomic_set(&pa->pa_count, 1);
3802 spin_lock_init(&pa->pa_lock);
3803 INIT_LIST_HEAD(&pa->pa_inode_list);
3804 INIT_LIST_HEAD(&pa->pa_group_list);
3805 pa->pa_deleted = 0;
3806 pa->pa_type = MB_GROUP_PA;
3807
3808 mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3809 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3810 trace_ext4_mb_new_group_pa(ac, pa);
3811
3812 ext4_mb_use_group_pa(ac, pa);
3813 atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3814
3815 grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3816 lg = ac->ac_lg;
3817 BUG_ON(lg == NULL);
3818
3819 pa->pa_obj_lock = &lg->lg_prealloc_lock;
3820 pa->pa_inode = NULL;
3821
3822 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3823 list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3824 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3825
3826 /*
3827 * We will later add the new pa to the right bucket
3828 * after updating the pa_free in ext4_mb_release_context
3829 */
3830 return 0;
3831}
3832
3833static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3834{
3835 int err;
3836
3837 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3838 err = ext4_mb_new_group_pa(ac);
3839 else
3840 err = ext4_mb_new_inode_pa(ac);
3841 return err;
3842}
3843
3844/*
3845 * finds all unused blocks in on-disk bitmap, frees them in
3846 * in-core bitmap and buddy.
3847 * @pa must be unlinked from inode and group lists, so that
3848 * nobody else can find/use it.
3849 * the caller MUST hold group/inode locks.
3850 * TODO: optimize the case when there are no in-core structures yet
3851 */
3852static noinline_for_stack int
3853ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3854 struct ext4_prealloc_space *pa)
3855{
3856 struct super_block *sb = e4b->bd_sb;
3857 struct ext4_sb_info *sbi = EXT4_SB(sb);
3858 unsigned int end;
3859 unsigned int next;
3860 ext4_group_t group;
3861 ext4_grpblk_t bit;
3862 unsigned long long grp_blk_start;
3863 int free = 0;
3864
3865 BUG_ON(pa->pa_deleted == 0);
3866 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3867 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
3868 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3869 end = bit + pa->pa_len;
3870
3871 while (bit < end) {
3872 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3873 if (bit >= end)
3874 break;
3875 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3876 mb_debug(1, " free preallocated %u/%u in group %u\n",
3877 (unsigned) ext4_group_first_block_no(sb, group) + bit,
3878 (unsigned) next - bit, (unsigned) group);
3879 free += next - bit;
3880
3881 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
3882 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
3883 EXT4_C2B(sbi, bit)),
3884 next - bit);
3885 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3886 bit = next + 1;
3887 }
3888 if (free != pa->pa_free) {
3889 ext4_msg(e4b->bd_sb, KERN_CRIT,
3890 "pa %p: logic %lu, phys. %lu, len %lu",
3891 pa, (unsigned long) pa->pa_lstart,
3892 (unsigned long) pa->pa_pstart,
3893 (unsigned long) pa->pa_len);
3894 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
3895 free, pa->pa_free);
3896 /*
3897 * pa is already deleted so we use the value obtained
3898 * from the bitmap and continue.
3899 */
3900 }
3901 atomic_add(free, &sbi->s_mb_discarded);
3902
3903 return 0;
3904}
3905
3906static noinline_for_stack int
3907ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3908 struct ext4_prealloc_space *pa)
3909{
3910 struct super_block *sb = e4b->bd_sb;
3911 ext4_group_t group;
3912 ext4_grpblk_t bit;
3913
3914 trace_ext4_mb_release_group_pa(sb, pa);
3915 BUG_ON(pa->pa_deleted == 0);
3916 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3917 if (unlikely(group != e4b->bd_group && pa->pa_len != 0)) {
3918 ext4_warning(sb, "bad group: expected %u, group %u, pa_start %llu",
3919 e4b->bd_group, group, pa->pa_pstart);
3920 return 0;
3921 }
3922 mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3923 atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3924 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3925
3926 return 0;
3927}
3928
3929/*
3930 * releases all preallocations in given group
3931 *
3932 * first, we need to decide discard policy:
3933 * - when do we discard
3934 * 1) ENOSPC
3935 * - how many do we discard
3936 * 1) how many requested
3937 */
3938static noinline_for_stack int
3939ext4_mb_discard_group_preallocations(struct super_block *sb,
3940 ext4_group_t group, int needed)
3941{
3942 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3943 struct buffer_head *bitmap_bh = NULL;
3944 struct ext4_prealloc_space *pa, *tmp;
3945 struct list_head list;
3946 struct ext4_buddy e4b;
3947 int err;
3948 int busy = 0;
3949 int free = 0;
3950
3951 mb_debug(1, "discard preallocation for group %u\n", group);
3952
3953 if (list_empty(&grp->bb_prealloc_list))
3954 return 0;
3955
3956 bitmap_bh = ext4_read_block_bitmap(sb, group);
3957 if (IS_ERR(bitmap_bh)) {
3958 err = PTR_ERR(bitmap_bh);
3959 ext4_error(sb, "Error %d reading block bitmap for %u",
3960 err, group);
3961 return 0;
3962 }
3963
3964 err = ext4_mb_load_buddy(sb, group, &e4b);
3965 if (err) {
3966 ext4_warning(sb, "Error %d loading buddy information for %u",
3967 err, group);
3968 put_bh(bitmap_bh);
3969 return 0;
3970 }
3971
3972 if (needed == 0)
3973 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
3974
3975 INIT_LIST_HEAD(&list);
3976repeat:
3977 ext4_lock_group(sb, group);
3978 list_for_each_entry_safe(pa, tmp,
3979 &grp->bb_prealloc_list, pa_group_list) {
3980 spin_lock(&pa->pa_lock);
3981 if (atomic_read(&pa->pa_count)) {
3982 spin_unlock(&pa->pa_lock);
3983 busy = 1;
3984 continue;
3985 }
3986 if (pa->pa_deleted) {
3987 spin_unlock(&pa->pa_lock);
3988 continue;
3989 }
3990
3991 /* seems this one can be freed ... */
3992 pa->pa_deleted = 1;
3993
3994 /* we can trust pa_free ... */
3995 free += pa->pa_free;
3996
3997 spin_unlock(&pa->pa_lock);
3998
3999 list_del(&pa->pa_group_list);
4000 list_add(&pa->u.pa_tmp_list, &list);
4001 }
4002
4003 /* if we still need more blocks and some PAs were used, try again */
4004 if (free < needed && busy) {
4005 busy = 0;
4006 ext4_unlock_group(sb, group);
4007 cond_resched();
4008 goto repeat;
4009 }
4010
4011 /* found anything to free? */
4012 if (list_empty(&list)) {
4013 BUG_ON(free != 0);
4014 goto out;
4015 }
4016
4017 /* now free all selected PAs */
4018 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4019
4020 /* remove from object (inode or locality group) */
4021 spin_lock(pa->pa_obj_lock);
4022 list_del_rcu(&pa->pa_inode_list);
4023 spin_unlock(pa->pa_obj_lock);
4024
4025 if (pa->pa_type == MB_GROUP_PA)
4026 ext4_mb_release_group_pa(&e4b, pa);
4027 else
4028 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4029
4030 list_del(&pa->u.pa_tmp_list);
4031 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4032 }
4033
4034out:
4035 ext4_unlock_group(sb, group);
4036 ext4_mb_unload_buddy(&e4b);
4037 put_bh(bitmap_bh);
4038 return free;
4039}
4040
4041/*
4042 * releases all non-used preallocated blocks for given inode
4043 *
4044 * It's important to discard preallocations under i_data_sem
4045 * We don't want another block to be served from the prealloc
4046 * space when we are discarding the inode prealloc space.
4047 *
4048 * FIXME!! Make sure it is valid at all the call sites
4049 */
4050void ext4_discard_preallocations(struct inode *inode)
4051{
4052 struct ext4_inode_info *ei = EXT4_I(inode);
4053 struct super_block *sb = inode->i_sb;
4054 struct buffer_head *bitmap_bh = NULL;
4055 struct ext4_prealloc_space *pa, *tmp;
4056 ext4_group_t group = 0;
4057 struct list_head list;
4058 struct ext4_buddy e4b;
4059 int err;
4060
4061 if (!S_ISREG(inode->i_mode)) {
4062 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4063 return;
4064 }
4065
4066 mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
4067 trace_ext4_discard_preallocations(inode);
4068
4069 INIT_LIST_HEAD(&list);
4070
4071repeat:
4072 /* first, collect all pa's in the inode */
4073 spin_lock(&ei->i_prealloc_lock);
4074 while (!list_empty(&ei->i_prealloc_list)) {
4075 pa = list_entry(ei->i_prealloc_list.next,
4076 struct ext4_prealloc_space, pa_inode_list);
4077 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4078 spin_lock(&pa->pa_lock);
4079 if (atomic_read(&pa->pa_count)) {
4080 /* this shouldn't happen often - nobody should
4081 * use preallocation while we're discarding it */
4082 spin_unlock(&pa->pa_lock);
4083 spin_unlock(&ei->i_prealloc_lock);
4084 ext4_msg(sb, KERN_ERR,
4085 "uh-oh! used pa while discarding");
4086 WARN_ON(1);
4087 schedule_timeout_uninterruptible(HZ);
4088 goto repeat;
4089
4090 }
4091 if (pa->pa_deleted == 0) {
4092 pa->pa_deleted = 1;
4093 spin_unlock(&pa->pa_lock);
4094 list_del_rcu(&pa->pa_inode_list);
4095 list_add(&pa->u.pa_tmp_list, &list);
4096 continue;
4097 }
4098
4099 /* someone is deleting pa right now */
4100 spin_unlock(&pa->pa_lock);
4101 spin_unlock(&ei->i_prealloc_lock);
4102
4103 /* we have to wait here because pa_deleted
4104 * doesn't mean pa is already unlinked from
4105 * the list. as we might be called from
4106 * ->clear_inode() the inode will get freed
4107 * and concurrent thread which is unlinking
4108 * pa from inode's list may access already
4109 * freed memory, bad-bad-bad */
4110
4111 /* XXX: if this happens too often, we can
4112 * add a flag to force wait only in case
4113 * of ->clear_inode(), but not in case of
4114 * regular truncate */
4115 schedule_timeout_uninterruptible(HZ);
4116 goto repeat;
4117 }
4118 spin_unlock(&ei->i_prealloc_lock);
4119
4120 list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4121 BUG_ON(pa->pa_type != MB_INODE_PA);
4122 group = ext4_get_group_number(sb, pa->pa_pstart);
4123
4124 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4125 GFP_NOFS|__GFP_NOFAIL);
4126 if (err) {
4127 ext4_error(sb, "Error %d loading buddy information for %u",
4128 err, group);
4129 continue;
4130 }
4131
4132 bitmap_bh = ext4_read_block_bitmap(sb, group);
4133 if (IS_ERR(bitmap_bh)) {
4134 err = PTR_ERR(bitmap_bh);
4135 ext4_error(sb, "Error %d reading block bitmap for %u",
4136 err, group);
4137 ext4_mb_unload_buddy(&e4b);
4138 continue;
4139 }
4140
4141 ext4_lock_group(sb, group);
4142 list_del(&pa->pa_group_list);
4143 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4144 ext4_unlock_group(sb, group);
4145
4146 ext4_mb_unload_buddy(&e4b);
4147 put_bh(bitmap_bh);
4148
4149 list_del(&pa->u.pa_tmp_list);
4150 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4151 }
4152}
4153
4154#ifdef CONFIG_EXT4_DEBUG
4155static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4156{
4157 struct super_block *sb = ac->ac_sb;
4158 ext4_group_t ngroups, i;
4159
4160 if (!ext4_mballoc_debug ||
4161 (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
4162 return;
4163
4164 ext4_msg(ac->ac_sb, KERN_ERR, "Can't allocate:"
4165 " Allocation context details:");
4166 ext4_msg(ac->ac_sb, KERN_ERR, "status %d flags %d",
4167 ac->ac_status, ac->ac_flags);
4168 ext4_msg(ac->ac_sb, KERN_ERR, "orig %lu/%lu/%lu@%lu, "
4169 "goal %lu/%lu/%lu@%lu, "
4170 "best %lu/%lu/%lu@%lu cr %d",
4171 (unsigned long)ac->ac_o_ex.fe_group,
4172 (unsigned long)ac->ac_o_ex.fe_start,
4173 (unsigned long)ac->ac_o_ex.fe_len,
4174 (unsigned long)ac->ac_o_ex.fe_logical,
4175 (unsigned long)ac->ac_g_ex.fe_group,
4176 (unsigned long)ac->ac_g_ex.fe_start,
4177 (unsigned long)ac->ac_g_ex.fe_len,
4178 (unsigned long)ac->ac_g_ex.fe_logical,
4179 (unsigned long)ac->ac_b_ex.fe_group,
4180 (unsigned long)ac->ac_b_ex.fe_start,
4181 (unsigned long)ac->ac_b_ex.fe_len,
4182 (unsigned long)ac->ac_b_ex.fe_logical,
4183 (int)ac->ac_criteria);
4184 ext4_msg(ac->ac_sb, KERN_ERR, "%d found", ac->ac_found);
4185 ext4_msg(ac->ac_sb, KERN_ERR, "groups: ");
4186 ngroups = ext4_get_groups_count(sb);
4187 for (i = 0; i < ngroups; i++) {
4188 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4189 struct ext4_prealloc_space *pa;
4190 ext4_grpblk_t start;
4191 struct list_head *cur;
4192 ext4_lock_group(sb, i);
4193 list_for_each(cur, &grp->bb_prealloc_list) {
4194 pa = list_entry(cur, struct ext4_prealloc_space,
4195 pa_group_list);
4196 spin_lock(&pa->pa_lock);
4197 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4198 NULL, &start);
4199 spin_unlock(&pa->pa_lock);
4200 printk(KERN_ERR "PA:%u:%d:%u \n", i,
4201 start, pa->pa_len);
4202 }
4203 ext4_unlock_group(sb, i);
4204
4205 if (grp->bb_free == 0)
4206 continue;
4207 printk(KERN_ERR "%u: %d/%d \n",
4208 i, grp->bb_free, grp->bb_fragments);
4209 }
4210 printk(KERN_ERR "\n");
4211}
4212#else
4213static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4214{
4215 return;
4216}
4217#endif
4218
4219/*
4220 * We use locality group preallocation for small size file. The size of the
4221 * file is determined by the current size or the resulting size after
4222 * allocation which ever is larger
4223 *
4224 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4225 */
4226static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4227{
4228 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4229 int bsbits = ac->ac_sb->s_blocksize_bits;
4230 loff_t size, isize;
4231
4232 if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4233 return;
4234
4235 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4236 return;
4237
4238 size = extent_logical_end(sbi, &ac->ac_o_ex);
4239 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
4240 >> bsbits;
4241
4242 if ((size == isize) && !ext4_fs_is_busy(sbi) &&
4243 !inode_is_open_for_write(ac->ac_inode)) {
4244 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
4245 return;
4246 }
4247
4248 if (sbi->s_mb_group_prealloc <= 0) {
4249 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4250 return;
4251 }
4252
4253 /* don't use group allocation for large files */
4254 size = max(size, isize);
4255 if (size > sbi->s_mb_stream_request) {
4256 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4257 return;
4258 }
4259
4260 BUG_ON(ac->ac_lg != NULL);
4261 /*
4262 * locality group prealloc space are per cpu. The reason for having
4263 * per cpu locality group is to reduce the contention between block
4264 * request from multiple CPUs.
4265 */
4266 ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
4267
4268 /* we're going to use group allocation */
4269 ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4270
4271 /* serialize all allocations in the group */
4272 mutex_lock(&ac->ac_lg->lg_mutex);
4273}
4274
4275static noinline_for_stack int
4276ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4277 struct ext4_allocation_request *ar)
4278{
4279 struct super_block *sb = ar->inode->i_sb;
4280 struct ext4_sb_info *sbi = EXT4_SB(sb);
4281 struct ext4_super_block *es = sbi->s_es;
4282 ext4_group_t group;
4283 unsigned int len;
4284 ext4_fsblk_t goal;
4285 ext4_grpblk_t block;
4286
4287 /* we can't allocate > group size */
4288 len = ar->len;
4289
4290 /* just a dirty hack to filter too big requests */
4291 if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
4292 len = EXT4_CLUSTERS_PER_GROUP(sb);
4293
4294 /* start searching from the goal */
4295 goal = ar->goal;
4296 if (goal < le32_to_cpu(es->s_first_data_block) ||
4297 goal >= ext4_blocks_count(es))
4298 goal = le32_to_cpu(es->s_first_data_block);
4299 ext4_get_group_no_and_offset(sb, goal, &group, &block);
4300
4301 /* set up allocation goals */
4302 ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
4303 ac->ac_status = AC_STATUS_CONTINUE;
4304 ac->ac_sb = sb;
4305 ac->ac_inode = ar->inode;
4306 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4307 ac->ac_o_ex.fe_group = group;
4308 ac->ac_o_ex.fe_start = block;
4309 ac->ac_o_ex.fe_len = len;
4310 ac->ac_g_ex = ac->ac_o_ex;
4311 ac->ac_flags = ar->flags;
4312
4313 /* we have to define context: we'll we work with a file or
4314 * locality group. this is a policy, actually */
4315 ext4_mb_group_or_file(ac);
4316
4317 mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4318 "left: %u/%u, right %u/%u to %swritable\n",
4319 (unsigned) ar->len, (unsigned) ar->logical,
4320 (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4321 (unsigned) ar->lleft, (unsigned) ar->pleft,
4322 (unsigned) ar->lright, (unsigned) ar->pright,
4323 inode_is_open_for_write(ar->inode) ? "" : "non-");
4324 return 0;
4325
4326}
4327
4328static noinline_for_stack void
4329ext4_mb_discard_lg_preallocations(struct super_block *sb,
4330 struct ext4_locality_group *lg,
4331 int order, int total_entries)
4332{
4333 ext4_group_t group = 0;
4334 struct ext4_buddy e4b;
4335 struct list_head discard_list;
4336 struct ext4_prealloc_space *pa, *tmp;
4337
4338 mb_debug(1, "discard locality group preallocation\n");
4339
4340 INIT_LIST_HEAD(&discard_list);
4341
4342 spin_lock(&lg->lg_prealloc_lock);
4343 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4344 pa_inode_list) {
4345 spin_lock(&pa->pa_lock);
4346 if (atomic_read(&pa->pa_count)) {
4347 /*
4348 * This is the pa that we just used
4349 * for block allocation. So don't
4350 * free that
4351 */
4352 spin_unlock(&pa->pa_lock);
4353 continue;
4354 }
4355 if (pa->pa_deleted) {
4356 spin_unlock(&pa->pa_lock);
4357 continue;
4358 }
4359 /* only lg prealloc space */
4360 BUG_ON(pa->pa_type != MB_GROUP_PA);
4361
4362 /* seems this one can be freed ... */
4363 pa->pa_deleted = 1;
4364 spin_unlock(&pa->pa_lock);
4365
4366 list_del_rcu(&pa->pa_inode_list);
4367 list_add(&pa->u.pa_tmp_list, &discard_list);
4368
4369 total_entries--;
4370 if (total_entries <= 5) {
4371 /*
4372 * we want to keep only 5 entries
4373 * allowing it to grow to 8. This
4374 * mak sure we don't call discard
4375 * soon for this list.
4376 */
4377 break;
4378 }
4379 }
4380 spin_unlock(&lg->lg_prealloc_lock);
4381
4382 list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4383 int err;
4384
4385 group = ext4_get_group_number(sb, pa->pa_pstart);
4386 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4387 GFP_NOFS|__GFP_NOFAIL);
4388 if (err) {
4389 ext4_error(sb, "Error %d loading buddy information for %u",
4390 err, group);
4391 continue;
4392 }
4393 ext4_lock_group(sb, group);
4394 list_del(&pa->pa_group_list);
4395 ext4_mb_release_group_pa(&e4b, pa);
4396 ext4_unlock_group(sb, group);
4397
4398 ext4_mb_unload_buddy(&e4b);
4399 list_del(&pa->u.pa_tmp_list);
4400 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4401 }
4402}
4403
4404/*
4405 * We have incremented pa_count. So it cannot be freed at this
4406 * point. Also we hold lg_mutex. So no parallel allocation is
4407 * possible from this lg. That means pa_free cannot be updated.
4408 *
4409 * A parallel ext4_mb_discard_group_preallocations is possible.
4410 * which can cause the lg_prealloc_list to be updated.
4411 */
4412
4413static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4414{
4415 int order, added = 0, lg_prealloc_count = 1;
4416 struct super_block *sb = ac->ac_sb;
4417 struct ext4_locality_group *lg = ac->ac_lg;
4418 struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4419
4420 order = fls(pa->pa_free) - 1;
4421 if (order > PREALLOC_TB_SIZE - 1)
4422 /* The max size of hash table is PREALLOC_TB_SIZE */
4423 order = PREALLOC_TB_SIZE - 1;
4424 /* Add the prealloc space to lg */
4425 spin_lock(&lg->lg_prealloc_lock);
4426 list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4427 pa_inode_list) {
4428 spin_lock(&tmp_pa->pa_lock);
4429 if (tmp_pa->pa_deleted) {
4430 spin_unlock(&tmp_pa->pa_lock);
4431 continue;
4432 }
4433 if (!added && pa->pa_free < tmp_pa->pa_free) {
4434 /* Add to the tail of the previous entry */
4435 list_add_tail_rcu(&pa->pa_inode_list,
4436 &tmp_pa->pa_inode_list);
4437 added = 1;
4438 /*
4439 * we want to count the total
4440 * number of entries in the list
4441 */
4442 }
4443 spin_unlock(&tmp_pa->pa_lock);
4444 lg_prealloc_count++;
4445 }
4446 if (!added)
4447 list_add_tail_rcu(&pa->pa_inode_list,
4448 &lg->lg_prealloc_list[order]);
4449 spin_unlock(&lg->lg_prealloc_lock);
4450
4451 /* Now trim the list to be not more than 8 elements */
4452 if (lg_prealloc_count > 8) {
4453 ext4_mb_discard_lg_preallocations(sb, lg,
4454 order, lg_prealloc_count);
4455 return;
4456 }
4457 return ;
4458}
4459
4460/*
4461 * release all resource we used in allocation
4462 */
4463static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4464{
4465 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4466 struct ext4_prealloc_space *pa = ac->ac_pa;
4467 if (pa) {
4468 if (pa->pa_type == MB_GROUP_PA) {
4469 /* see comment in ext4_mb_use_group_pa() */
4470 spin_lock(&pa->pa_lock);
4471 pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4472 pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4473 pa->pa_free -= ac->ac_b_ex.fe_len;
4474 pa->pa_len -= ac->ac_b_ex.fe_len;
4475 spin_unlock(&pa->pa_lock);
4476 }
4477 }
4478 if (pa) {
4479 /*
4480 * We want to add the pa to the right bucket.
4481 * Remove it from the list and while adding
4482 * make sure the list to which we are adding
4483 * doesn't grow big.
4484 */
4485 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4486 spin_lock(pa->pa_obj_lock);
4487 list_del_rcu(&pa->pa_inode_list);
4488 spin_unlock(pa->pa_obj_lock);
4489 ext4_mb_add_n_trim(ac);
4490 }
4491 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4492 }
4493 if (ac->ac_bitmap_page)
4494 put_page(ac->ac_bitmap_page);
4495 if (ac->ac_buddy_page)
4496 put_page(ac->ac_buddy_page);
4497 if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4498 mutex_unlock(&ac->ac_lg->lg_mutex);
4499 ext4_mb_collect_stats(ac);
4500 return 0;
4501}
4502
4503static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4504{
4505 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4506 int ret;
4507 int freed = 0;
4508
4509 trace_ext4_mb_discard_preallocations(sb, needed);
4510 for (i = 0; i < ngroups && needed > 0; i++) {
4511 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4512 freed += ret;
4513 needed -= ret;
4514 }
4515
4516 return freed;
4517}
4518
4519/*
4520 * Main entry point into mballoc to allocate blocks
4521 * it tries to use preallocation first, then falls back
4522 * to usual allocation
4523 */
4524ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4525 struct ext4_allocation_request *ar, int *errp)
4526{
4527 int freed;
4528 struct ext4_allocation_context *ac = NULL;
4529 struct ext4_sb_info *sbi;
4530 struct super_block *sb;
4531 ext4_fsblk_t block = 0;
4532 unsigned int inquota = 0;
4533 unsigned int reserv_clstrs = 0;
4534
4535 might_sleep();
4536 sb = ar->inode->i_sb;
4537 sbi = EXT4_SB(sb);
4538
4539 trace_ext4_request_blocks(ar);
4540
4541 /* Allow to use superuser reservation for quota file */
4542 if (ext4_is_quota_file(ar->inode))
4543 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
4544
4545 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
4546 /* Without delayed allocation we need to verify
4547 * there is enough free blocks to do block allocation
4548 * and verify allocation doesn't exceed the quota limits.
4549 */
4550 while (ar->len &&
4551 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
4552
4553 /* let others to free the space */
4554 cond_resched();
4555 ar->len = ar->len >> 1;
4556 }
4557 if (!ar->len) {
4558 *errp = -ENOSPC;
4559 return 0;
4560 }
4561 reserv_clstrs = ar->len;
4562 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
4563 dquot_alloc_block_nofail(ar->inode,
4564 EXT4_C2B(sbi, ar->len));
4565 } else {
4566 while (ar->len &&
4567 dquot_alloc_block(ar->inode,
4568 EXT4_C2B(sbi, ar->len))) {
4569
4570 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4571 ar->len--;
4572 }
4573 }
4574 inquota = ar->len;
4575 if (ar->len == 0) {
4576 *errp = -EDQUOT;
4577 goto out;
4578 }
4579 }
4580
4581 ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
4582 if (!ac) {
4583 ar->len = 0;
4584 *errp = -ENOMEM;
4585 goto out;
4586 }
4587
4588 *errp = ext4_mb_initialize_context(ac, ar);
4589 if (*errp) {
4590 ar->len = 0;
4591 goto out;
4592 }
4593
4594 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4595 if (!ext4_mb_use_preallocated(ac)) {
4596 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4597 ext4_mb_normalize_request(ac, ar);
4598repeat:
4599 /* allocate space in core */
4600 *errp = ext4_mb_regular_allocator(ac);
4601 if (*errp)
4602 goto discard_and_exit;
4603
4604 /* as we've just preallocated more space than
4605 * user requested originally, we store allocated
4606 * space in a special descriptor */
4607 if (ac->ac_status == AC_STATUS_FOUND &&
4608 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4609 *errp = ext4_mb_new_preallocation(ac);
4610 if (*errp) {
4611 discard_and_exit:
4612 ext4_discard_allocated_blocks(ac);
4613 goto errout;
4614 }
4615 }
4616 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4617 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4618 if (*errp) {
4619 ext4_discard_allocated_blocks(ac);
4620 goto errout;
4621 } else {
4622 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4623 ar->len = ac->ac_b_ex.fe_len;
4624 }
4625 } else {
4626 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4627 if (freed)
4628 goto repeat;
4629 *errp = -ENOSPC;
4630 }
4631
4632errout:
4633 if (*errp) {
4634 ac->ac_b_ex.fe_len = 0;
4635 ar->len = 0;
4636 ext4_mb_show_ac(ac);
4637 }
4638 ext4_mb_release_context(ac);
4639out:
4640 if (ac)
4641 kmem_cache_free(ext4_ac_cachep, ac);
4642 if (inquota && ar->len < inquota)
4643 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
4644 if (!ar->len) {
4645 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
4646 /* release all the reserved blocks if non delalloc */
4647 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4648 reserv_clstrs);
4649 }
4650
4651 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4652
4653 return block;
4654}
4655
4656/*
4657 * We can merge two free data extents only if the physical blocks
4658 * are contiguous, AND the extents were freed by the same transaction,
4659 * AND the blocks are associated with the same group.
4660 */
4661static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
4662 struct ext4_free_data *entry,
4663 struct ext4_free_data *new_entry,
4664 struct rb_root *entry_rb_root)
4665{
4666 if ((entry->efd_tid != new_entry->efd_tid) ||
4667 (entry->efd_group != new_entry->efd_group))
4668 return;
4669 if (entry->efd_start_cluster + entry->efd_count ==
4670 new_entry->efd_start_cluster) {
4671 new_entry->efd_start_cluster = entry->efd_start_cluster;
4672 new_entry->efd_count += entry->efd_count;
4673 } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
4674 entry->efd_start_cluster) {
4675 new_entry->efd_count += entry->efd_count;
4676 } else
4677 return;
4678 spin_lock(&sbi->s_md_lock);
4679 list_del(&entry->efd_list);
4680 spin_unlock(&sbi->s_md_lock);
4681 rb_erase(&entry->efd_node, entry_rb_root);
4682 kmem_cache_free(ext4_free_data_cachep, entry);
4683}
4684
4685static noinline_for_stack int
4686ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4687 struct ext4_free_data *new_entry)
4688{
4689 ext4_group_t group = e4b->bd_group;
4690 ext4_grpblk_t cluster;
4691 ext4_grpblk_t clusters = new_entry->efd_count;
4692 struct ext4_free_data *entry;
4693 struct ext4_group_info *db = e4b->bd_info;
4694 struct super_block *sb = e4b->bd_sb;
4695 struct ext4_sb_info *sbi = EXT4_SB(sb);
4696 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4697 struct rb_node *parent = NULL, *new_node;
4698
4699 BUG_ON(!ext4_handle_valid(handle));
4700 BUG_ON(e4b->bd_bitmap_page == NULL);
4701 BUG_ON(e4b->bd_buddy_page == NULL);
4702
4703 new_node = &new_entry->efd_node;
4704 cluster = new_entry->efd_start_cluster;
4705
4706 if (!*n) {
4707 /* first free block exent. We need to
4708 protect buddy cache from being freed,
4709 * otherwise we'll refresh it from
4710 * on-disk bitmap and lose not-yet-available
4711 * blocks */
4712 get_page(e4b->bd_buddy_page);
4713 get_page(e4b->bd_bitmap_page);
4714 }
4715 while (*n) {
4716 parent = *n;
4717 entry = rb_entry(parent, struct ext4_free_data, efd_node);
4718 if (cluster < entry->efd_start_cluster)
4719 n = &(*n)->rb_left;
4720 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
4721 n = &(*n)->rb_right;
4722 else {
4723 ext4_grp_locked_error(sb, group, 0,
4724 ext4_group_first_block_no(sb, group) +
4725 EXT4_C2B(sbi, cluster),
4726 "Block already on to-be-freed list");
4727 kmem_cache_free(ext4_free_data_cachep, new_entry);
4728 return 0;
4729 }
4730 }
4731
4732 rb_link_node(new_node, parent, n);
4733 rb_insert_color(new_node, &db->bb_free_root);
4734
4735 /* Now try to see the extent can be merged to left and right */
4736 node = rb_prev(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));
4741 }
4742
4743 node = rb_next(new_node);
4744 if (node) {
4745 entry = rb_entry(node, struct ext4_free_data, efd_node);
4746 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4747 &(db->bb_free_root));
4748 }
4749
4750 spin_lock(&sbi->s_md_lock);
4751 list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
4752 sbi->s_mb_free_pending += clusters;
4753 spin_unlock(&sbi->s_md_lock);
4754 return 0;
4755}
4756
4757/**
4758 * ext4_free_blocks() -- Free given blocks and update quota
4759 * @handle: handle for this transaction
4760 * @inode: inode
4761 * @bh: optional buffer of the block to be freed
4762 * @block: starting physical block to be freed
4763 * @count: number of blocks to be freed
4764 * @flags: flags used by ext4_free_blocks
4765 */
4766void ext4_free_blocks(handle_t *handle, struct inode *inode,
4767 struct buffer_head *bh, ext4_fsblk_t block,
4768 unsigned long count, int flags)
4769{
4770 struct buffer_head *bitmap_bh = NULL;
4771 struct super_block *sb = inode->i_sb;
4772 struct ext4_group_desc *gdp;
4773 unsigned int overflow;
4774 ext4_grpblk_t bit;
4775 struct buffer_head *gd_bh;
4776 ext4_group_t block_group;
4777 struct ext4_sb_info *sbi;
4778 struct ext4_buddy e4b;
4779 unsigned int count_clusters;
4780 int err = 0;
4781 int ret;
4782
4783 might_sleep();
4784 if (bh) {
4785 if (block)
4786 BUG_ON(block != bh->b_blocknr);
4787 else
4788 block = bh->b_blocknr;
4789 }
4790
4791 sbi = EXT4_SB(sb);
4792 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
4793 !ext4_data_block_valid(sbi, block, count)) {
4794 ext4_error(sb, "Freeing blocks not in datazone - "
4795 "block = %llu, count = %lu", block, count);
4796 goto error_return;
4797 }
4798
4799 ext4_debug("freeing block %llu\n", block);
4800 trace_ext4_free_blocks(inode, block, count, flags);
4801
4802 if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4803 BUG_ON(count > 1);
4804
4805 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4806 inode, bh, block);
4807 }
4808
4809 /*
4810 * If the extent to be freed does not begin on a cluster
4811 * boundary, we need to deal with partial clusters at the
4812 * beginning and end of the extent. Normally we will free
4813 * blocks at the beginning or the end unless we are explicitly
4814 * requested to avoid doing so.
4815 */
4816 overflow = EXT4_PBLK_COFF(sbi, block);
4817 if (overflow) {
4818 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
4819 overflow = sbi->s_cluster_ratio - overflow;
4820 block += overflow;
4821 if (count > overflow)
4822 count -= overflow;
4823 else
4824 return;
4825 } else {
4826 block -= overflow;
4827 count += overflow;
4828 }
4829 }
4830 overflow = EXT4_LBLK_COFF(sbi, count);
4831 if (overflow) {
4832 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
4833 if (count > overflow)
4834 count -= overflow;
4835 else
4836 return;
4837 } else
4838 count += sbi->s_cluster_ratio - overflow;
4839 }
4840
4841 if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4842 int i;
4843 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
4844
4845 for (i = 0; i < count; i++) {
4846 cond_resched();
4847 if (is_metadata)
4848 bh = sb_find_get_block(inode->i_sb, block + i);
4849 ext4_forget(handle, is_metadata, inode, bh, block + i);
4850 }
4851 }
4852
4853do_more:
4854 overflow = 0;
4855 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4856
4857 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
4858 ext4_get_group_info(sb, block_group))))
4859 return;
4860
4861 /*
4862 * Check to see if we are freeing blocks across a group
4863 * boundary.
4864 */
4865 if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4866 overflow = EXT4_C2B(sbi, bit) + count -
4867 EXT4_BLOCKS_PER_GROUP(sb);
4868 count -= overflow;
4869 }
4870 count_clusters = EXT4_NUM_B2C(sbi, count);
4871 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4872 if (IS_ERR(bitmap_bh)) {
4873 err = PTR_ERR(bitmap_bh);
4874 bitmap_bh = NULL;
4875 goto error_return;
4876 }
4877 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4878 if (!gdp) {
4879 err = -EIO;
4880 goto error_return;
4881 }
4882
4883 if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4884 in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4885 in_range(block, ext4_inode_table(sb, gdp),
4886 sbi->s_itb_per_group) ||
4887 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4888 sbi->s_itb_per_group)) {
4889
4890 ext4_error(sb, "Freeing blocks in system zone - "
4891 "Block = %llu, count = %lu", block, count);
4892 /* err = 0. ext4_std_error should be a no op */
4893 goto error_return;
4894 }
4895
4896 BUFFER_TRACE(bitmap_bh, "getting write access");
4897 err = ext4_journal_get_write_access(handle, bitmap_bh);
4898 if (err)
4899 goto error_return;
4900
4901 /*
4902 * We are about to modify some metadata. Call the journal APIs
4903 * to unshare ->b_data if a currently-committing transaction is
4904 * using it
4905 */
4906 BUFFER_TRACE(gd_bh, "get_write_access");
4907 err = ext4_journal_get_write_access(handle, gd_bh);
4908 if (err)
4909 goto error_return;
4910#ifdef AGGRESSIVE_CHECK
4911 {
4912 int i;
4913 for (i = 0; i < count_clusters; i++)
4914 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4915 }
4916#endif
4917 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
4918
4919 /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
4920 err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
4921 GFP_NOFS|__GFP_NOFAIL);
4922 if (err)
4923 goto error_return;
4924
4925 /*
4926 * We need to make sure we don't reuse the freed block until after the
4927 * transaction is committed. We make an exception if the inode is to be
4928 * written in writeback mode since writeback mode has weak data
4929 * consistency guarantees.
4930 */
4931 if (ext4_handle_valid(handle) &&
4932 ((flags & EXT4_FREE_BLOCKS_METADATA) ||
4933 !ext4_should_writeback_data(inode))) {
4934 struct ext4_free_data *new_entry;
4935 /*
4936 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
4937 * to fail.
4938 */
4939 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
4940 GFP_NOFS|__GFP_NOFAIL);
4941 new_entry->efd_start_cluster = bit;
4942 new_entry->efd_group = block_group;
4943 new_entry->efd_count = count_clusters;
4944 new_entry->efd_tid = handle->h_transaction->t_tid;
4945
4946 ext4_lock_group(sb, block_group);
4947 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4948 ext4_mb_free_metadata(handle, &e4b, new_entry);
4949 } else {
4950 /* need to update group_info->bb_free and bitmap
4951 * with group lock held. generate_buddy look at
4952 * them with group lock_held
4953 */
4954 if (test_opt(sb, DISCARD)) {
4955 err = ext4_issue_discard(sb, block_group, bit,
4956 count_clusters, NULL);
4957 if (err && err != -EOPNOTSUPP)
4958 ext4_msg(sb, KERN_WARNING, "discard request in"
4959 " group:%d block:%d count:%lu failed"
4960 " with %d", block_group, bit, count,
4961 err);
4962 }
4963
4964 EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
4965
4966 ext4_lock_group(sb, block_group);
4967 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4968 mb_free_blocks(inode, &e4b, bit, count_clusters);
4969 }
4970
4971 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
4972 ext4_free_group_clusters_set(sb, gdp, ret);
4973 ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
4974 ext4_group_desc_csum_set(sb, block_group, gdp);
4975 ext4_unlock_group(sb, block_group);
4976
4977 if (sbi->s_log_groups_per_flex) {
4978 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4979 atomic64_add(count_clusters,
4980 &sbi_array_rcu_deref(sbi, s_flex_groups,
4981 flex_group)->free_clusters);
4982 }
4983
4984 /*
4985 * on a bigalloc file system, defer the s_freeclusters_counter
4986 * update to the caller (ext4_remove_space and friends) so they
4987 * can determine if a cluster freed here should be rereserved
4988 */
4989 if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
4990 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
4991 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
4992 percpu_counter_add(&sbi->s_freeclusters_counter,
4993 count_clusters);
4994 }
4995
4996 ext4_mb_unload_buddy(&e4b);
4997
4998 /* We dirtied the bitmap block */
4999 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5000 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5001
5002 /* And the group descriptor block */
5003 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5004 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5005 if (!err)
5006 err = ret;
5007
5008 if (overflow && !err) {
5009 block += count;
5010 count = overflow;
5011 put_bh(bitmap_bh);
5012 goto do_more;
5013 }
5014error_return:
5015 brelse(bitmap_bh);
5016 ext4_std_error(sb, err);
5017 return;
5018}
5019
5020/**
5021 * ext4_group_add_blocks() -- Add given blocks to an existing group
5022 * @handle: handle to this transaction
5023 * @sb: super block
5024 * @block: start physical block to add to the block group
5025 * @count: number of blocks to free
5026 *
5027 * This marks the blocks as free in the bitmap and buddy.
5028 */
5029int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
5030 ext4_fsblk_t block, unsigned long count)
5031{
5032 struct buffer_head *bitmap_bh = NULL;
5033 struct buffer_head *gd_bh;
5034 ext4_group_t block_group;
5035 ext4_grpblk_t bit;
5036 unsigned int i;
5037 struct ext4_group_desc *desc;
5038 struct ext4_sb_info *sbi = EXT4_SB(sb);
5039 struct ext4_buddy e4b;
5040 int err = 0, ret, free_clusters_count;
5041 ext4_grpblk_t clusters_freed;
5042 ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
5043 ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
5044 unsigned long cluster_count = last_cluster - first_cluster + 1;
5045
5046 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
5047
5048 if (count == 0)
5049 return 0;
5050
5051 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5052 /*
5053 * Check to see if we are freeing blocks across a group
5054 * boundary.
5055 */
5056 if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
5057 ext4_warning(sb, "too many blocks added to group %u",
5058 block_group);
5059 err = -EINVAL;
5060 goto error_return;
5061 }
5062
5063 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
5064 if (IS_ERR(bitmap_bh)) {
5065 err = PTR_ERR(bitmap_bh);
5066 bitmap_bh = NULL;
5067 goto error_return;
5068 }
5069
5070 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
5071 if (!desc) {
5072 err = -EIO;
5073 goto error_return;
5074 }
5075
5076 if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
5077 in_range(ext4_inode_bitmap(sb, desc), block, count) ||
5078 in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
5079 in_range(block + count - 1, ext4_inode_table(sb, desc),
5080 sbi->s_itb_per_group)) {
5081 ext4_error(sb, "Adding blocks in system zones - "
5082 "Block = %llu, count = %lu",
5083 block, count);
5084 err = -EINVAL;
5085 goto error_return;
5086 }
5087
5088 BUFFER_TRACE(bitmap_bh, "getting write access");
5089 err = ext4_journal_get_write_access(handle, bitmap_bh);
5090 if (err)
5091 goto error_return;
5092
5093 /*
5094 * We are about to modify some metadata. Call the journal APIs
5095 * to unshare ->b_data if a currently-committing transaction is
5096 * using it
5097 */
5098 BUFFER_TRACE(gd_bh, "get_write_access");
5099 err = ext4_journal_get_write_access(handle, gd_bh);
5100 if (err)
5101 goto error_return;
5102
5103 for (i = 0, clusters_freed = 0; i < cluster_count; i++) {
5104 BUFFER_TRACE(bitmap_bh, "clear bit");
5105 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
5106 ext4_error(sb, "bit already cleared for block %llu",
5107 (ext4_fsblk_t)(block + i));
5108 BUFFER_TRACE(bitmap_bh, "bit already cleared");
5109 } else {
5110 clusters_freed++;
5111 }
5112 }
5113
5114 err = ext4_mb_load_buddy(sb, block_group, &e4b);
5115 if (err)
5116 goto error_return;
5117
5118 /*
5119 * need to update group_info->bb_free and bitmap
5120 * with group lock held. generate_buddy look at
5121 * them with group lock_held
5122 */
5123 ext4_lock_group(sb, block_group);
5124 mb_clear_bits(bitmap_bh->b_data, bit, cluster_count);
5125 mb_free_blocks(NULL, &e4b, bit, cluster_count);
5126 free_clusters_count = clusters_freed +
5127 ext4_free_group_clusters(sb, desc);
5128 ext4_free_group_clusters_set(sb, desc, free_clusters_count);
5129 ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
5130 ext4_group_desc_csum_set(sb, block_group, desc);
5131 ext4_unlock_group(sb, block_group);
5132 percpu_counter_add(&sbi->s_freeclusters_counter,
5133 clusters_freed);
5134
5135 if (sbi->s_log_groups_per_flex) {
5136 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5137 atomic64_add(clusters_freed,
5138 &sbi_array_rcu_deref(sbi, s_flex_groups,
5139 flex_group)->free_clusters);
5140 }
5141
5142 ext4_mb_unload_buddy(&e4b);
5143
5144 /* We dirtied the bitmap block */
5145 BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5146 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5147
5148 /* And the group descriptor block */
5149 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5150 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5151 if (!err)
5152 err = ret;
5153
5154error_return:
5155 brelse(bitmap_bh);
5156 ext4_std_error(sb, err);
5157 return err;
5158}
5159
5160/**
5161 * ext4_trim_extent -- function to TRIM one single free extent in the group
5162 * @sb: super block for the file system
5163 * @start: starting block of the free extent in the alloc. group
5164 * @count: number of blocks to TRIM
5165 * @e4b: ext4 buddy for the group
5166 *
5167 * Trim "count" blocks starting at "start" in the "group". To assure that no
5168 * one will allocate those blocks, mark it as used in buddy bitmap. This must
5169 * be called with under the group lock.
5170 */
5171static int ext4_trim_extent(struct super_block *sb,
5172 int start, int count, struct ext4_buddy *e4b)
5173__releases(bitlock)
5174__acquires(bitlock)
5175{
5176 struct ext4_free_extent ex;
5177 ext4_group_t group = e4b->bd_group;
5178 int ret = 0;
5179
5180 trace_ext4_trim_extent(sb, group, start, count);
5181
5182 assert_spin_locked(ext4_group_lock_ptr(sb, group));
5183
5184 ex.fe_start = start;
5185 ex.fe_group = group;
5186 ex.fe_len = count;
5187
5188 /*
5189 * Mark blocks used, so no one can reuse them while
5190 * being trimmed.
5191 */
5192 mb_mark_used(e4b, &ex);
5193 ext4_unlock_group(sb, group);
5194 ret = ext4_issue_discard(sb, group, start, count, NULL);
5195 ext4_lock_group(sb, group);
5196 mb_free_blocks(NULL, e4b, start, ex.fe_len);
5197 return ret;
5198}
5199
5200static ext4_grpblk_t ext4_last_grp_cluster(struct super_block *sb,
5201 ext4_group_t grp)
5202{
5203 unsigned long nr_clusters_in_group;
5204
5205 if (grp < (ext4_get_groups_count(sb) - 1))
5206 nr_clusters_in_group = EXT4_CLUSTERS_PER_GROUP(sb);
5207 else
5208 nr_clusters_in_group = (ext4_blocks_count(EXT4_SB(sb)->s_es) -
5209 ext4_group_first_block_no(sb, grp))
5210 >> EXT4_CLUSTER_BITS(sb);
5211
5212 return nr_clusters_in_group - 1;
5213}
5214
5215static bool ext4_trim_interrupted(void)
5216{
5217 return fatal_signal_pending(current) || freezing(current);
5218}
5219
5220static int ext4_try_to_trim_range(struct super_block *sb,
5221 struct ext4_buddy *e4b, ext4_grpblk_t start,
5222 ext4_grpblk_t max, ext4_grpblk_t minblocks)
5223{
5224 ext4_grpblk_t next, count, free_count, last, origin_start;
5225 bool set_trimmed = false;
5226 void *bitmap;
5227
5228 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
5229 return 0;
5230
5231 last = ext4_last_grp_cluster(sb, e4b->bd_group);
5232 bitmap = e4b->bd_bitmap;
5233 if (start == 0 && max >= last)
5234 set_trimmed = true;
5235 origin_start = start;
5236 start = max(e4b->bd_info->bb_first_free, start);
5237 count = 0;
5238 free_count = 0;
5239
5240 while (start <= max) {
5241 start = mb_find_next_zero_bit(bitmap, max + 1, start);
5242 if (start > max)
5243 break;
5244
5245 next = mb_find_next_bit(bitmap, last + 1, start);
5246 if (origin_start == 0 && next >= last)
5247 set_trimmed = true;
5248
5249 if ((next - start) >= minblocks) {
5250 int ret = ext4_trim_extent(sb, start, next - start, e4b);
5251
5252 if (ret && ret != -EOPNOTSUPP)
5253 return count;
5254 count += next - start;
5255 }
5256 free_count += next - start;
5257 start = next + 1;
5258
5259 if (ext4_trim_interrupted())
5260 return count;
5261
5262 if (need_resched()) {
5263 ext4_unlock_group(sb, e4b->bd_group);
5264 cond_resched();
5265 ext4_lock_group(sb, e4b->bd_group);
5266 }
5267
5268 if ((e4b->bd_info->bb_free - free_count) < minblocks)
5269 break;
5270 }
5271
5272 if (set_trimmed)
5273 EXT4_MB_GRP_SET_TRIMMED(e4b->bd_info);
5274
5275 return count;
5276}
5277
5278/**
5279 * ext4_trim_all_free -- function to trim all free space in alloc. group
5280 * @sb: super block for file system
5281 * @group: group to be trimmed
5282 * @start: first group block to examine
5283 * @max: last group block to examine
5284 * @minblocks: minimum extent block count
5285 *
5286 * ext4_trim_all_free walks through group's buddy bitmap searching for free
5287 * extents. When the free block is found, ext4_trim_extent is called to TRIM
5288 * the extent.
5289 *
5290 *
5291 * ext4_trim_all_free walks through group's block bitmap searching for free
5292 * extents. When the free extent is found, mark it as used in group buddy
5293 * bitmap. Then issue a TRIM command on this extent and free the extent in
5294 * the group buddy bitmap. This is done until whole group is scanned.
5295 */
5296static ext4_grpblk_t
5297ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
5298 ext4_grpblk_t start, ext4_grpblk_t max,
5299 ext4_grpblk_t minblocks)
5300{
5301 struct ext4_buddy e4b;
5302 int ret;
5303
5304 trace_ext4_trim_all_free(sb, group, start, max);
5305
5306 ret = ext4_mb_load_buddy(sb, group, &e4b);
5307 if (ret) {
5308 ext4_warning(sb, "Error %d loading buddy information for %u",
5309 ret, group);
5310 return ret;
5311 }
5312
5313 ext4_lock_group(sb, group);
5314
5315 if (!EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) ||
5316 minblocks < EXT4_SB(sb)->s_last_trim_minblks)
5317 ret = ext4_try_to_trim_range(sb, &e4b, start, max, minblocks);
5318 else
5319 ret = 0;
5320
5321 ext4_unlock_group(sb, group);
5322 ext4_mb_unload_buddy(&e4b);
5323
5324 ext4_debug("trimmed %d blocks in the group %d\n",
5325 ret, group);
5326
5327 return ret;
5328}
5329
5330/**
5331 * ext4_trim_fs() -- trim ioctl handle function
5332 * @sb: superblock for filesystem
5333 * @range: fstrim_range structure
5334 *
5335 * start: First Byte to trim
5336 * len: number of Bytes to trim from start
5337 * minlen: minimum extent length in Bytes
5338 * ext4_trim_fs goes through all allocation groups containing Bytes from
5339 * start to start+len. For each such a group ext4_trim_all_free function
5340 * is invoked to trim all free space.
5341 */
5342int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
5343{
5344 struct request_queue *q = bdev_get_queue(sb->s_bdev);
5345 struct ext4_group_info *grp;
5346 ext4_group_t group, first_group, last_group;
5347 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5348 uint64_t start, end, minlen, trimmed = 0;
5349 ext4_fsblk_t first_data_blk =
5350 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5351 ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
5352 int ret = 0;
5353
5354 start = range->start >> sb->s_blocksize_bits;
5355 end = start + (range->len >> sb->s_blocksize_bits) - 1;
5356 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5357 range->minlen >> sb->s_blocksize_bits);
5358
5359 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
5360 start >= max_blks ||
5361 range->len < sb->s_blocksize)
5362 return -EINVAL;
5363 /* No point to try to trim less than discard granularity */
5364 if (range->minlen < q->limits.discard_granularity) {
5365 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5366 q->limits.discard_granularity >> sb->s_blocksize_bits);
5367 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
5368 goto out;
5369 }
5370 if (end >= max_blks - 1)
5371 end = max_blks - 1;
5372 if (end <= first_data_blk)
5373 goto out;
5374 if (start < first_data_blk)
5375 start = first_data_blk;
5376
5377 /* Determine first and last group to examine based on start and end */
5378 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
5379 &first_group, &first_cluster);
5380 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
5381 &last_group, &last_cluster);
5382
5383 /* end now represents the last cluster to discard in this group */
5384 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5385
5386 for (group = first_group; group <= last_group; group++) {
5387 if (ext4_trim_interrupted())
5388 break;
5389 grp = ext4_get_group_info(sb, group);
5390 /* We only do this if the grp has never been initialized */
5391 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
5392 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
5393 if (ret)
5394 break;
5395 }
5396
5397 /*
5398 * For all the groups except the last one, last cluster will
5399 * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
5400 * change it for the last group, note that last_cluster is
5401 * already computed earlier by ext4_get_group_no_and_offset()
5402 */
5403 if (group == last_group)
5404 end = last_cluster;
5405 if (grp->bb_free >= minlen) {
5406 cnt = ext4_trim_all_free(sb, group, first_cluster,
5407 end, minlen);
5408 if (cnt < 0) {
5409 ret = cnt;
5410 break;
5411 }
5412 trimmed += cnt;
5413 }
5414
5415 /*
5416 * For every group except the first one, we are sure
5417 * that the first cluster to discard will be cluster #0.
5418 */
5419 first_cluster = 0;
5420 }
5421
5422 if (!ret)
5423 EXT4_SB(sb)->s_last_trim_minblks = minlen;
5424
5425out:
5426 range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
5427 return ret;
5428}
5429
5430/* Iterate all the free extents in the group. */
5431int
5432ext4_mballoc_query_range(
5433 struct super_block *sb,
5434 ext4_group_t group,
5435 ext4_grpblk_t first,
5436 ext4_grpblk_t end,
5437 ext4_mballoc_query_range_fn meta_formatter,
5438 ext4_mballoc_query_range_fn formatter,
5439 void *priv)
5440{
5441 void *bitmap;
5442 ext4_grpblk_t start, next;
5443 struct ext4_buddy e4b;
5444 int error;
5445
5446 error = ext4_mb_load_buddy(sb, group, &e4b);
5447 if (error)
5448 return error;
5449 bitmap = e4b.bd_bitmap;
5450
5451 ext4_lock_group(sb, group);
5452
5453 start = max(e4b.bd_info->bb_first_free, first);
5454 if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
5455 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5456 if (meta_formatter && start != first) {
5457 if (start > end)
5458 start = end;
5459 ext4_unlock_group(sb, group);
5460 error = meta_formatter(sb, group, first, start - first,
5461 priv);
5462 if (error)
5463 goto out_unload;
5464 ext4_lock_group(sb, group);
5465 }
5466 while (start <= end) {
5467 start = mb_find_next_zero_bit(bitmap, end + 1, start);
5468 if (start > end)
5469 break;
5470 next = mb_find_next_bit(bitmap, end + 1, start);
5471
5472 ext4_unlock_group(sb, group);
5473 error = formatter(sb, group, start, next - start, priv);
5474 if (error)
5475 goto out_unload;
5476 ext4_lock_group(sb, group);
5477
5478 start = next + 1;
5479 }
5480
5481 ext4_unlock_group(sb, group);
5482out_unload:
5483 ext4_mb_unload_buddy(&e4b);
5484
5485 return error;
5486}