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