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