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