xref: /openbmc/linux/fs/ext4/balloc.c (revision a5961bed)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/ext4/balloc.c
4  *
5  * Copyright (C) 1992, 1993, 1994, 1995
6  * Remy Card (card@masi.ibp.fr)
7  * Laboratoire MASI - Institut Blaise Pascal
8  * Universite Pierre et Marie Curie (Paris VI)
9  *
10  *  Enhanced block allocation by Stephen Tweedie (sct@redhat.com), 1993
11  *  Big-endian to little-endian byte-swapping/bitmaps by
12  *        David S. Miller (davem@caip.rutgers.edu), 1995
13  */
14 
15 #include <linux/time.h>
16 #include <linux/capability.h>
17 #include <linux/fs.h>
18 #include <linux/quotaops.h>
19 #include <linux/buffer_head.h>
20 #include "ext4.h"
21 #include "ext4_jbd2.h"
22 #include "mballoc.h"
23 
24 #include <trace/events/ext4.h>
25 
26 static unsigned ext4_num_base_meta_clusters(struct super_block *sb,
27 					    ext4_group_t block_group);
28 /*
29  * balloc.c contains the blocks allocation and deallocation routines
30  */
31 
32 /*
33  * Calculate block group number for a given block number
34  */
35 ext4_group_t ext4_get_group_number(struct super_block *sb,
36 				   ext4_fsblk_t block)
37 {
38 	ext4_group_t group;
39 
40 	if (test_opt2(sb, STD_GROUP_SIZE))
41 		group = (block -
42 			 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) >>
43 			(EXT4_BLOCK_SIZE_BITS(sb) + EXT4_CLUSTER_BITS(sb) + 3);
44 	else
45 		ext4_get_group_no_and_offset(sb, block, &group, NULL);
46 	return group;
47 }
48 
49 /*
50  * Calculate the block group number and offset into the block/cluster
51  * allocation bitmap, given a block number
52  */
53 void ext4_get_group_no_and_offset(struct super_block *sb, ext4_fsblk_t blocknr,
54 		ext4_group_t *blockgrpp, ext4_grpblk_t *offsetp)
55 {
56 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
57 	ext4_grpblk_t offset;
58 
59 	blocknr = blocknr - le32_to_cpu(es->s_first_data_block);
60 	offset = do_div(blocknr, EXT4_BLOCKS_PER_GROUP(sb)) >>
61 		EXT4_SB(sb)->s_cluster_bits;
62 	if (offsetp)
63 		*offsetp = offset;
64 	if (blockgrpp)
65 		*blockgrpp = blocknr;
66 
67 }
68 
69 /*
70  * Check whether the 'block' lives within the 'block_group'. Returns 1 if so
71  * and 0 otherwise.
72  */
73 static inline int ext4_block_in_group(struct super_block *sb,
74 				      ext4_fsblk_t block,
75 				      ext4_group_t block_group)
76 {
77 	ext4_group_t actual_group;
78 
79 	actual_group = ext4_get_group_number(sb, block);
80 	return (actual_group == block_group) ? 1 : 0;
81 }
82 
83 /*
84  * Return the number of clusters used for file system metadata; this
85  * represents the overhead needed by the file system.
86  */
87 static unsigned ext4_num_overhead_clusters(struct super_block *sb,
88 					   ext4_group_t block_group,
89 					   struct ext4_group_desc *gdp)
90 {
91 	unsigned base_clusters, num_clusters;
92 	int block_cluster = -1, inode_cluster;
93 	int itbl_cluster_start = -1, itbl_cluster_end = -1;
94 	ext4_fsblk_t start = ext4_group_first_block_no(sb, block_group);
95 	ext4_fsblk_t end = start + EXT4_BLOCKS_PER_GROUP(sb) - 1;
96 	ext4_fsblk_t itbl_blk_start, itbl_blk_end;
97 	struct ext4_sb_info *sbi = EXT4_SB(sb);
98 
99 	/* This is the number of clusters used by the superblock,
100 	 * block group descriptors, and reserved block group
101 	 * descriptor blocks */
102 	base_clusters = ext4_num_base_meta_clusters(sb, block_group);
103 	num_clusters = base_clusters;
104 
105 	/*
106 	 * Account and record inode table clusters if any cluster
107 	 * is in the block group, or inode table cluster range is
108 	 * [-1, -1] and won't overlap with block/inode bitmap cluster
109 	 * accounted below.
110 	 */
111 	itbl_blk_start = ext4_inode_table(sb, gdp);
112 	itbl_blk_end = itbl_blk_start + sbi->s_itb_per_group - 1;
113 	if (itbl_blk_start <= end && itbl_blk_end >= start) {
114 		itbl_blk_start = itbl_blk_start >= start ?
115 			itbl_blk_start : start;
116 		itbl_blk_end = itbl_blk_end <= end ?
117 			itbl_blk_end : end;
118 
119 		itbl_cluster_start = EXT4_B2C(sbi, itbl_blk_start - start);
120 		itbl_cluster_end = EXT4_B2C(sbi, itbl_blk_end - start);
121 
122 		num_clusters += itbl_cluster_end - itbl_cluster_start + 1;
123 		/* check if border cluster is overlapped */
124 		if (itbl_cluster_start == base_clusters - 1)
125 			num_clusters--;
126 	}
127 
128 	/*
129 	 * For the allocation bitmaps, we first need to check to see
130 	 * if the block is in the block group.  If it is, then check
131 	 * to see if the cluster is already accounted for in the clusters
132 	 * used for the base metadata cluster and inode tables cluster.
133 	 * Normally all of these blocks are contiguous, so the special
134 	 * case handling shouldn't be necessary except for *very*
135 	 * unusual file system layouts.
136 	 */
137 	if (ext4_block_in_group(sb, ext4_block_bitmap(sb, gdp), block_group)) {
138 		block_cluster = EXT4_B2C(sbi,
139 					 ext4_block_bitmap(sb, gdp) - start);
140 		if (block_cluster >= base_clusters &&
141 		    (block_cluster < itbl_cluster_start ||
142 		    block_cluster > itbl_cluster_end))
143 			num_clusters++;
144 	}
145 
146 	if (ext4_block_in_group(sb, ext4_inode_bitmap(sb, gdp), block_group)) {
147 		inode_cluster = EXT4_B2C(sbi,
148 					 ext4_inode_bitmap(sb, gdp) - start);
149 		/*
150 		 * Additional check if inode bitmap is in just accounted
151 		 * block_cluster
152 		 */
153 		if (inode_cluster != block_cluster &&
154 		    inode_cluster >= base_clusters &&
155 		    (inode_cluster < itbl_cluster_start ||
156 		    inode_cluster > itbl_cluster_end))
157 			num_clusters++;
158 	}
159 
160 	return num_clusters;
161 }
162 
163 static unsigned int num_clusters_in_group(struct super_block *sb,
164 					  ext4_group_t block_group)
165 {
166 	unsigned int blocks;
167 
168 	if (block_group == ext4_get_groups_count(sb) - 1) {
169 		/*
170 		 * Even though mke2fs always initializes the first and
171 		 * last group, just in case some other tool was used,
172 		 * we need to make sure we calculate the right free
173 		 * blocks.
174 		 */
175 		blocks = ext4_blocks_count(EXT4_SB(sb)->s_es) -
176 			ext4_group_first_block_no(sb, block_group);
177 	} else
178 		blocks = EXT4_BLOCKS_PER_GROUP(sb);
179 	return EXT4_NUM_B2C(EXT4_SB(sb), blocks);
180 }
181 
182 /* Initializes an uninitialized block bitmap */
183 static int ext4_init_block_bitmap(struct super_block *sb,
184 				   struct buffer_head *bh,
185 				   ext4_group_t block_group,
186 				   struct ext4_group_desc *gdp)
187 {
188 	unsigned int bit, bit_max;
189 	struct ext4_sb_info *sbi = EXT4_SB(sb);
190 	ext4_fsblk_t start, tmp;
191 
192 	ASSERT(buffer_locked(bh));
193 
194 	if (!ext4_group_desc_csum_verify(sb, block_group, gdp)) {
195 		ext4_mark_group_bitmap_corrupted(sb, block_group,
196 					EXT4_GROUP_INFO_BBITMAP_CORRUPT |
197 					EXT4_GROUP_INFO_IBITMAP_CORRUPT);
198 		return -EFSBADCRC;
199 	}
200 	memset(bh->b_data, 0, sb->s_blocksize);
201 
202 	bit_max = ext4_num_base_meta_clusters(sb, block_group);
203 	if ((bit_max >> 3) >= bh->b_size)
204 		return -EFSCORRUPTED;
205 
206 	for (bit = 0; bit < bit_max; bit++)
207 		ext4_set_bit(bit, bh->b_data);
208 
209 	start = ext4_group_first_block_no(sb, block_group);
210 
211 	/* Set bits for block and inode bitmaps, and inode table */
212 	tmp = ext4_block_bitmap(sb, gdp);
213 	if (ext4_block_in_group(sb, tmp, block_group))
214 		ext4_set_bit(EXT4_B2C(sbi, tmp - start), bh->b_data);
215 
216 	tmp = ext4_inode_bitmap(sb, gdp);
217 	if (ext4_block_in_group(sb, tmp, block_group))
218 		ext4_set_bit(EXT4_B2C(sbi, tmp - start), bh->b_data);
219 
220 	tmp = ext4_inode_table(sb, gdp);
221 	for (; tmp < ext4_inode_table(sb, gdp) +
222 		     sbi->s_itb_per_group; tmp++) {
223 		if (ext4_block_in_group(sb, tmp, block_group))
224 			ext4_set_bit(EXT4_B2C(sbi, tmp - start), bh->b_data);
225 	}
226 
227 	/*
228 	 * Also if the number of blocks within the group is less than
229 	 * the blocksize * 8 ( which is the size of bitmap ), set rest
230 	 * of the block bitmap to 1
231 	 */
232 	ext4_mark_bitmap_end(num_clusters_in_group(sb, block_group),
233 			     sb->s_blocksize * 8, bh->b_data);
234 	return 0;
235 }
236 
237 /* Return the number of free blocks in a block group.  It is used when
238  * the block bitmap is uninitialized, so we can't just count the bits
239  * in the bitmap. */
240 unsigned ext4_free_clusters_after_init(struct super_block *sb,
241 				       ext4_group_t block_group,
242 				       struct ext4_group_desc *gdp)
243 {
244 	return num_clusters_in_group(sb, block_group) -
245 		ext4_num_overhead_clusters(sb, block_group, gdp);
246 }
247 
248 /*
249  * The free blocks are managed by bitmaps.  A file system contains several
250  * blocks groups.  Each group contains 1 bitmap block for blocks, 1 bitmap
251  * block for inodes, N blocks for the inode table and data blocks.
252  *
253  * The file system contains group descriptors which are located after the
254  * super block.  Each descriptor contains the number of the bitmap block and
255  * the free blocks count in the block.  The descriptors are loaded in memory
256  * when a file system is mounted (see ext4_fill_super).
257  */
258 
259 /**
260  * ext4_get_group_desc() -- load group descriptor from disk
261  * @sb:			super block
262  * @block_group:	given block group
263  * @bh:			pointer to the buffer head to store the block
264  *			group descriptor
265  */
266 struct ext4_group_desc * ext4_get_group_desc(struct super_block *sb,
267 					     ext4_group_t block_group,
268 					     struct buffer_head **bh)
269 {
270 	unsigned int group_desc;
271 	unsigned int offset;
272 	ext4_group_t ngroups = ext4_get_groups_count(sb);
273 	struct ext4_group_desc *desc;
274 	struct ext4_sb_info *sbi = EXT4_SB(sb);
275 	struct buffer_head *bh_p;
276 
277 	if (block_group >= ngroups) {
278 		ext4_error(sb, "block_group >= groups_count - block_group = %u,"
279 			   " groups_count = %u", block_group, ngroups);
280 
281 		return NULL;
282 	}
283 
284 	group_desc = block_group >> EXT4_DESC_PER_BLOCK_BITS(sb);
285 	offset = block_group & (EXT4_DESC_PER_BLOCK(sb) - 1);
286 	bh_p = sbi_array_rcu_deref(sbi, s_group_desc, group_desc);
287 	/*
288 	 * sbi_array_rcu_deref returns with rcu unlocked, this is ok since
289 	 * the pointer being dereferenced won't be dereferenced again. By
290 	 * looking at the usage in add_new_gdb() the value isn't modified,
291 	 * just the pointer, and so it remains valid.
292 	 */
293 	if (!bh_p) {
294 		ext4_error(sb, "Group descriptor not loaded - "
295 			   "block_group = %u, group_desc = %u, desc = %u",
296 			   block_group, group_desc, offset);
297 		return NULL;
298 	}
299 
300 	desc = (struct ext4_group_desc *)(
301 		(__u8 *)bh_p->b_data +
302 		offset * EXT4_DESC_SIZE(sb));
303 	if (bh)
304 		*bh = bh_p;
305 	return desc;
306 }
307 
308 /*
309  * Return the block number which was discovered to be invalid, or 0 if
310  * the block bitmap is valid.
311  */
312 static ext4_fsblk_t ext4_valid_block_bitmap(struct super_block *sb,
313 					    struct ext4_group_desc *desc,
314 					    ext4_group_t block_group,
315 					    struct buffer_head *bh)
316 {
317 	struct ext4_sb_info *sbi = EXT4_SB(sb);
318 	ext4_grpblk_t offset;
319 	ext4_grpblk_t next_zero_bit;
320 	ext4_grpblk_t max_bit = EXT4_CLUSTERS_PER_GROUP(sb);
321 	ext4_fsblk_t blk;
322 	ext4_fsblk_t group_first_block;
323 
324 	if (ext4_has_feature_flex_bg(sb)) {
325 		/* with FLEX_BG, the inode/block bitmaps and itable
326 		 * blocks may not be in the group at all
327 		 * so the bitmap validation will be skipped for those groups
328 		 * or it has to also read the block group where the bitmaps
329 		 * are located to verify they are set.
330 		 */
331 		return 0;
332 	}
333 	group_first_block = ext4_group_first_block_no(sb, block_group);
334 
335 	/* check whether block bitmap block number is set */
336 	blk = ext4_block_bitmap(sb, desc);
337 	offset = blk - group_first_block;
338 	if (offset < 0 || EXT4_B2C(sbi, offset) >= max_bit ||
339 	    !ext4_test_bit(EXT4_B2C(sbi, offset), bh->b_data))
340 		/* bad block bitmap */
341 		return blk;
342 
343 	/* check whether the inode bitmap block number is set */
344 	blk = ext4_inode_bitmap(sb, desc);
345 	offset = blk - group_first_block;
346 	if (offset < 0 || EXT4_B2C(sbi, offset) >= max_bit ||
347 	    !ext4_test_bit(EXT4_B2C(sbi, offset), bh->b_data))
348 		/* bad block bitmap */
349 		return blk;
350 
351 	/* check whether the inode table block number is set */
352 	blk = ext4_inode_table(sb, desc);
353 	offset = blk - group_first_block;
354 	if (offset < 0 || EXT4_B2C(sbi, offset) >= max_bit ||
355 	    EXT4_B2C(sbi, offset + sbi->s_itb_per_group - 1) >= max_bit)
356 		return blk;
357 	next_zero_bit = ext4_find_next_zero_bit(bh->b_data,
358 			EXT4_B2C(sbi, offset + sbi->s_itb_per_group - 1) + 1,
359 			EXT4_B2C(sbi, offset));
360 	if (next_zero_bit <
361 	    EXT4_B2C(sbi, offset + sbi->s_itb_per_group - 1) + 1)
362 		/* bad bitmap for inode tables */
363 		return blk;
364 	return 0;
365 }
366 
367 static int ext4_validate_block_bitmap(struct super_block *sb,
368 				      struct ext4_group_desc *desc,
369 				      ext4_group_t block_group,
370 				      struct buffer_head *bh)
371 {
372 	ext4_fsblk_t	blk;
373 	struct ext4_group_info *grp;
374 
375 	if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
376 		return 0;
377 
378 	grp = ext4_get_group_info(sb, block_group);
379 
380 	if (buffer_verified(bh))
381 		return 0;
382 	if (EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
383 		return -EFSCORRUPTED;
384 
385 	ext4_lock_group(sb, block_group);
386 	if (buffer_verified(bh))
387 		goto verified;
388 	if (unlikely(!ext4_block_bitmap_csum_verify(sb, desc, bh) ||
389 		     ext4_simulate_fail(sb, EXT4_SIM_BBITMAP_CRC))) {
390 		ext4_unlock_group(sb, block_group);
391 		ext4_error(sb, "bg %u: bad block bitmap checksum", block_group);
392 		ext4_mark_group_bitmap_corrupted(sb, block_group,
393 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
394 		return -EFSBADCRC;
395 	}
396 	blk = ext4_valid_block_bitmap(sb, desc, block_group, bh);
397 	if (unlikely(blk != 0)) {
398 		ext4_unlock_group(sb, block_group);
399 		ext4_error(sb, "bg %u: block %llu: invalid block bitmap",
400 			   block_group, blk);
401 		ext4_mark_group_bitmap_corrupted(sb, block_group,
402 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
403 		return -EFSCORRUPTED;
404 	}
405 	set_buffer_verified(bh);
406 verified:
407 	ext4_unlock_group(sb, block_group);
408 	return 0;
409 }
410 
411 /**
412  * ext4_read_block_bitmap_nowait()
413  * @sb:			super block
414  * @block_group:	given block group
415  * @ignore_locked:	ignore locked buffers
416  *
417  * Read the bitmap for a given block_group,and validate the
418  * bits for block/inode/inode tables are set in the bitmaps
419  *
420  * Return buffer_head on success or an ERR_PTR in case of failure.
421  */
422 struct buffer_head *
423 ext4_read_block_bitmap_nowait(struct super_block *sb, ext4_group_t block_group,
424 			      bool ignore_locked)
425 {
426 	struct ext4_group_desc *desc;
427 	struct ext4_sb_info *sbi = EXT4_SB(sb);
428 	struct buffer_head *bh;
429 	ext4_fsblk_t bitmap_blk;
430 	int err;
431 
432 	desc = ext4_get_group_desc(sb, block_group, NULL);
433 	if (!desc)
434 		return ERR_PTR(-EFSCORRUPTED);
435 	bitmap_blk = ext4_block_bitmap(sb, desc);
436 	if ((bitmap_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
437 	    (bitmap_blk >= ext4_blocks_count(sbi->s_es))) {
438 		ext4_error(sb, "Invalid block bitmap block %llu in "
439 			   "block_group %u", bitmap_blk, block_group);
440 		ext4_mark_group_bitmap_corrupted(sb, block_group,
441 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
442 		return ERR_PTR(-EFSCORRUPTED);
443 	}
444 	bh = sb_getblk(sb, bitmap_blk);
445 	if (unlikely(!bh)) {
446 		ext4_warning(sb, "Cannot get buffer for block bitmap - "
447 			     "block_group = %u, block_bitmap = %llu",
448 			     block_group, bitmap_blk);
449 		return ERR_PTR(-ENOMEM);
450 	}
451 
452 	if (ignore_locked && buffer_locked(bh)) {
453 		/* buffer under IO already, return if called for prefetching */
454 		put_bh(bh);
455 		return NULL;
456 	}
457 
458 	if (bitmap_uptodate(bh))
459 		goto verify;
460 
461 	lock_buffer(bh);
462 	if (bitmap_uptodate(bh)) {
463 		unlock_buffer(bh);
464 		goto verify;
465 	}
466 	ext4_lock_group(sb, block_group);
467 	if (ext4_has_group_desc_csum(sb) &&
468 	    (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
469 		if (block_group == 0) {
470 			ext4_unlock_group(sb, block_group);
471 			unlock_buffer(bh);
472 			ext4_error(sb, "Block bitmap for bg 0 marked "
473 				   "uninitialized");
474 			err = -EFSCORRUPTED;
475 			goto out;
476 		}
477 		err = ext4_init_block_bitmap(sb, bh, block_group, desc);
478 		if (err) {
479 			ext4_unlock_group(sb, block_group);
480 			unlock_buffer(bh);
481 			ext4_error(sb, "Failed to init block bitmap for group "
482 				   "%u: %d", block_group, err);
483 			goto out;
484 		}
485 		set_bitmap_uptodate(bh);
486 		set_buffer_uptodate(bh);
487 		set_buffer_verified(bh);
488 		ext4_unlock_group(sb, block_group);
489 		unlock_buffer(bh);
490 		return bh;
491 	}
492 	ext4_unlock_group(sb, block_group);
493 	if (buffer_uptodate(bh)) {
494 		/*
495 		 * if not uninit if bh is uptodate,
496 		 * bitmap is also uptodate
497 		 */
498 		set_bitmap_uptodate(bh);
499 		unlock_buffer(bh);
500 		goto verify;
501 	}
502 	/*
503 	 * submit the buffer_head for reading
504 	 */
505 	set_buffer_new(bh);
506 	trace_ext4_read_block_bitmap_load(sb, block_group, ignore_locked);
507 	ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO |
508 			    (ignore_locked ? REQ_RAHEAD : 0),
509 			    ext4_end_bitmap_read);
510 	return bh;
511 verify:
512 	err = ext4_validate_block_bitmap(sb, desc, block_group, bh);
513 	if (err)
514 		goto out;
515 	return bh;
516 out:
517 	put_bh(bh);
518 	return ERR_PTR(err);
519 }
520 
521 /* Returns 0 on success, -errno on error */
522 int ext4_wait_block_bitmap(struct super_block *sb, ext4_group_t block_group,
523 			   struct buffer_head *bh)
524 {
525 	struct ext4_group_desc *desc;
526 
527 	if (!buffer_new(bh))
528 		return 0;
529 	desc = ext4_get_group_desc(sb, block_group, NULL);
530 	if (!desc)
531 		return -EFSCORRUPTED;
532 	wait_on_buffer(bh);
533 	ext4_simulate_fail_bh(sb, bh, EXT4_SIM_BBITMAP_EIO);
534 	if (!buffer_uptodate(bh)) {
535 		ext4_error_err(sb, EIO, "Cannot read block bitmap - "
536 			       "block_group = %u, block_bitmap = %llu",
537 			       block_group, (unsigned long long) bh->b_blocknr);
538 		ext4_mark_group_bitmap_corrupted(sb, block_group,
539 					EXT4_GROUP_INFO_BBITMAP_CORRUPT);
540 		return -EIO;
541 	}
542 	clear_buffer_new(bh);
543 	/* Panic or remount fs read-only if block bitmap is invalid */
544 	return ext4_validate_block_bitmap(sb, desc, block_group, bh);
545 }
546 
547 struct buffer_head *
548 ext4_read_block_bitmap(struct super_block *sb, ext4_group_t block_group)
549 {
550 	struct buffer_head *bh;
551 	int err;
552 
553 	bh = ext4_read_block_bitmap_nowait(sb, block_group, false);
554 	if (IS_ERR(bh))
555 		return bh;
556 	err = ext4_wait_block_bitmap(sb, block_group, bh);
557 	if (err) {
558 		put_bh(bh);
559 		return ERR_PTR(err);
560 	}
561 	return bh;
562 }
563 
564 /**
565  * ext4_has_free_clusters()
566  * @sbi:	in-core super block structure.
567  * @nclusters:	number of needed blocks
568  * @flags:	flags from ext4_mb_new_blocks()
569  *
570  * Check if filesystem has nclusters free & available for allocation.
571  * On success return 1, return 0 on failure.
572  */
573 static int ext4_has_free_clusters(struct ext4_sb_info *sbi,
574 				  s64 nclusters, unsigned int flags)
575 {
576 	s64 free_clusters, dirty_clusters, rsv, resv_clusters;
577 	struct percpu_counter *fcc = &sbi->s_freeclusters_counter;
578 	struct percpu_counter *dcc = &sbi->s_dirtyclusters_counter;
579 
580 	free_clusters  = percpu_counter_read_positive(fcc);
581 	dirty_clusters = percpu_counter_read_positive(dcc);
582 	resv_clusters = atomic64_read(&sbi->s_resv_clusters);
583 
584 	/*
585 	 * r_blocks_count should always be multiple of the cluster ratio so
586 	 * we are safe to do a plane bit shift only.
587 	 */
588 	rsv = (ext4_r_blocks_count(sbi->s_es) >> sbi->s_cluster_bits) +
589 	      resv_clusters;
590 
591 	if (free_clusters - (nclusters + rsv + dirty_clusters) <
592 					EXT4_FREECLUSTERS_WATERMARK) {
593 		free_clusters  = percpu_counter_sum_positive(fcc);
594 		dirty_clusters = percpu_counter_sum_positive(dcc);
595 	}
596 	/* Check whether we have space after accounting for current
597 	 * dirty clusters & root reserved clusters.
598 	 */
599 	if (free_clusters >= (rsv + nclusters + dirty_clusters))
600 		return 1;
601 
602 	/* Hm, nope.  Are (enough) root reserved clusters available? */
603 	if (uid_eq(sbi->s_resuid, current_fsuid()) ||
604 	    (!gid_eq(sbi->s_resgid, GLOBAL_ROOT_GID) && in_group_p(sbi->s_resgid)) ||
605 	    capable(CAP_SYS_RESOURCE) ||
606 	    (flags & EXT4_MB_USE_ROOT_BLOCKS)) {
607 
608 		if (free_clusters >= (nclusters + dirty_clusters +
609 				      resv_clusters))
610 			return 1;
611 	}
612 	/* No free blocks. Let's see if we can dip into reserved pool */
613 	if (flags & EXT4_MB_USE_RESERVED) {
614 		if (free_clusters >= (nclusters + dirty_clusters))
615 			return 1;
616 	}
617 
618 	return 0;
619 }
620 
621 int ext4_claim_free_clusters(struct ext4_sb_info *sbi,
622 			     s64 nclusters, unsigned int flags)
623 {
624 	if (ext4_has_free_clusters(sbi, nclusters, flags)) {
625 		percpu_counter_add(&sbi->s_dirtyclusters_counter, nclusters);
626 		return 0;
627 	} else
628 		return -ENOSPC;
629 }
630 
631 /**
632  * ext4_should_retry_alloc() - check if a block allocation should be retried
633  * @sb:			superblock
634  * @retries:		number of retry attempts made so far
635  *
636  * ext4_should_retry_alloc() is called when ENOSPC is returned while
637  * attempting to allocate blocks.  If there's an indication that a pending
638  * journal transaction might free some space and allow another attempt to
639  * succeed, this function will wait for the current or committing transaction
640  * to complete and then return TRUE.
641  */
642 int ext4_should_retry_alloc(struct super_block *sb, int *retries)
643 {
644 	struct ext4_sb_info *sbi = EXT4_SB(sb);
645 
646 	if (!sbi->s_journal)
647 		return 0;
648 
649 	if (++(*retries) > 3) {
650 		percpu_counter_inc(&sbi->s_sra_exceeded_retry_limit);
651 		return 0;
652 	}
653 
654 	/*
655 	 * if there's no indication that blocks are about to be freed it's
656 	 * possible we just missed a transaction commit that did so
657 	 */
658 	smp_mb();
659 	if (sbi->s_mb_free_pending == 0) {
660 		if (test_opt(sb, DISCARD)) {
661 			atomic_inc(&sbi->s_retry_alloc_pending);
662 			flush_work(&sbi->s_discard_work);
663 			atomic_dec(&sbi->s_retry_alloc_pending);
664 		}
665 		return ext4_has_free_clusters(sbi, 1, 0);
666 	}
667 
668 	/*
669 	 * it's possible we've just missed a transaction commit here,
670 	 * so ignore the returned status
671 	 */
672 	ext4_debug("%s: retrying operation after ENOSPC\n", sb->s_id);
673 	(void) jbd2_journal_force_commit_nested(sbi->s_journal);
674 	return 1;
675 }
676 
677 /*
678  * ext4_new_meta_blocks() -- allocate block for meta data (indexing) blocks
679  *
680  * @handle:             handle to this transaction
681  * @inode:              file inode
682  * @goal:               given target block(filesystem wide)
683  * @count:		pointer to total number of clusters needed
684  * @errp:               error code
685  *
686  * Return 1st allocated block number on success, *count stores total account
687  * error stores in errp pointer
688  */
689 ext4_fsblk_t ext4_new_meta_blocks(handle_t *handle, struct inode *inode,
690 				  ext4_fsblk_t goal, unsigned int flags,
691 				  unsigned long *count, int *errp)
692 {
693 	struct ext4_allocation_request ar;
694 	ext4_fsblk_t ret;
695 
696 	memset(&ar, 0, sizeof(ar));
697 	/* Fill with neighbour allocated blocks */
698 	ar.inode = inode;
699 	ar.goal = goal;
700 	ar.len = count ? *count : 1;
701 	ar.flags = flags;
702 
703 	ret = ext4_mb_new_blocks(handle, &ar, errp);
704 	if (count)
705 		*count = ar.len;
706 	/*
707 	 * Account for the allocated meta blocks.  We will never
708 	 * fail EDQUOT for metdata, but we do account for it.
709 	 */
710 	if (!(*errp) && (flags & EXT4_MB_DELALLOC_RESERVED)) {
711 		dquot_alloc_block_nofail(inode,
712 				EXT4_C2B(EXT4_SB(inode->i_sb), ar.len));
713 	}
714 	return ret;
715 }
716 
717 /**
718  * ext4_count_free_clusters() -- count filesystem free clusters
719  * @sb:		superblock
720  *
721  * Adds up the number of free clusters from each block group.
722  */
723 ext4_fsblk_t ext4_count_free_clusters(struct super_block *sb)
724 {
725 	ext4_fsblk_t desc_count;
726 	struct ext4_group_desc *gdp;
727 	ext4_group_t i;
728 	ext4_group_t ngroups = ext4_get_groups_count(sb);
729 	struct ext4_group_info *grp;
730 #ifdef EXT4FS_DEBUG
731 	struct ext4_super_block *es;
732 	ext4_fsblk_t bitmap_count;
733 	unsigned int x;
734 	struct buffer_head *bitmap_bh = NULL;
735 
736 	es = EXT4_SB(sb)->s_es;
737 	desc_count = 0;
738 	bitmap_count = 0;
739 	gdp = NULL;
740 
741 	for (i = 0; i < ngroups; i++) {
742 		gdp = ext4_get_group_desc(sb, i, NULL);
743 		if (!gdp)
744 			continue;
745 		grp = NULL;
746 		if (EXT4_SB(sb)->s_group_info)
747 			grp = ext4_get_group_info(sb, i);
748 		if (!grp || !EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
749 			desc_count += ext4_free_group_clusters(sb, gdp);
750 		brelse(bitmap_bh);
751 		bitmap_bh = ext4_read_block_bitmap(sb, i);
752 		if (IS_ERR(bitmap_bh)) {
753 			bitmap_bh = NULL;
754 			continue;
755 		}
756 
757 		x = ext4_count_free(bitmap_bh->b_data,
758 				    EXT4_CLUSTERS_PER_GROUP(sb) / 8);
759 		printk(KERN_DEBUG "group %u: stored = %d, counted = %u\n",
760 			i, ext4_free_group_clusters(sb, gdp), x);
761 		bitmap_count += x;
762 	}
763 	brelse(bitmap_bh);
764 	printk(KERN_DEBUG "ext4_count_free_clusters: stored = %llu"
765 	       ", computed = %llu, %llu\n",
766 	       EXT4_NUM_B2C(EXT4_SB(sb), ext4_free_blocks_count(es)),
767 	       desc_count, bitmap_count);
768 	return bitmap_count;
769 #else
770 	desc_count = 0;
771 	for (i = 0; i < ngroups; i++) {
772 		gdp = ext4_get_group_desc(sb, i, NULL);
773 		if (!gdp)
774 			continue;
775 		grp = NULL;
776 		if (EXT4_SB(sb)->s_group_info)
777 			grp = ext4_get_group_info(sb, i);
778 		if (!grp || !EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
779 			desc_count += ext4_free_group_clusters(sb, gdp);
780 	}
781 
782 	return desc_count;
783 #endif
784 }
785 
786 static inline int test_root(ext4_group_t a, int b)
787 {
788 	while (1) {
789 		if (a < b)
790 			return 0;
791 		if (a == b)
792 			return 1;
793 		if ((a % b) != 0)
794 			return 0;
795 		a = a / b;
796 	}
797 }
798 
799 /**
800  *	ext4_bg_has_super - number of blocks used by the superblock in group
801  *	@sb: superblock for filesystem
802  *	@group: group number to check
803  *
804  *	Return the number of blocks used by the superblock (primary or backup)
805  *	in this group.  Currently this will be only 0 or 1.
806  */
807 int ext4_bg_has_super(struct super_block *sb, ext4_group_t group)
808 {
809 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
810 
811 	if (group == 0)
812 		return 1;
813 	if (ext4_has_feature_sparse_super2(sb)) {
814 		if (group == le32_to_cpu(es->s_backup_bgs[0]) ||
815 		    group == le32_to_cpu(es->s_backup_bgs[1]))
816 			return 1;
817 		return 0;
818 	}
819 	if ((group <= 1) || !ext4_has_feature_sparse_super(sb))
820 		return 1;
821 	if (!(group & 1))
822 		return 0;
823 	if (test_root(group, 3) || (test_root(group, 5)) ||
824 	    test_root(group, 7))
825 		return 1;
826 
827 	return 0;
828 }
829 
830 static unsigned long ext4_bg_num_gdb_meta(struct super_block *sb,
831 					ext4_group_t group)
832 {
833 	unsigned long metagroup = group / EXT4_DESC_PER_BLOCK(sb);
834 	ext4_group_t first = metagroup * EXT4_DESC_PER_BLOCK(sb);
835 	ext4_group_t last = first + EXT4_DESC_PER_BLOCK(sb) - 1;
836 
837 	if (group == first || group == first + 1 || group == last)
838 		return 1;
839 	return 0;
840 }
841 
842 static unsigned long ext4_bg_num_gdb_nometa(struct super_block *sb,
843 					ext4_group_t group)
844 {
845 	if (!ext4_bg_has_super(sb, group))
846 		return 0;
847 
848 	return EXT4_SB(sb)->s_gdb_count;
849 }
850 
851 /**
852  *	ext4_bg_num_gdb - number of blocks used by the group table in group
853  *	@sb: superblock for filesystem
854  *	@group: group number to check
855  *
856  *	Return the number of blocks used by the group descriptor table
857  *	(primary or backup) in this group.  In the future there may be a
858  *	different number of descriptor blocks in each group.
859  */
860 unsigned long ext4_bg_num_gdb(struct super_block *sb, ext4_group_t group)
861 {
862 	unsigned long first_meta_bg =
863 			le32_to_cpu(EXT4_SB(sb)->s_es->s_first_meta_bg);
864 	unsigned long metagroup = group / EXT4_DESC_PER_BLOCK(sb);
865 
866 	if (!ext4_has_feature_meta_bg(sb) || metagroup < first_meta_bg)
867 		return ext4_bg_num_gdb_nometa(sb, group);
868 
869 	return ext4_bg_num_gdb_meta(sb,group);
870 
871 }
872 
873 /*
874  * This function returns the number of file system metadata clusters at
875  * the beginning of a block group, including the reserved gdt blocks.
876  */
877 static unsigned ext4_num_base_meta_clusters(struct super_block *sb,
878 				     ext4_group_t block_group)
879 {
880 	struct ext4_sb_info *sbi = EXT4_SB(sb);
881 	unsigned num;
882 
883 	/* Check for superblock and gdt backups in this group */
884 	num = ext4_bg_has_super(sb, block_group);
885 
886 	if (!ext4_has_feature_meta_bg(sb) ||
887 	    block_group < le32_to_cpu(sbi->s_es->s_first_meta_bg) *
888 			  sbi->s_desc_per_block) {
889 		if (num) {
890 			num += ext4_bg_num_gdb_nometa(sb, block_group);
891 			num += le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks);
892 		}
893 	} else { /* For META_BG_BLOCK_GROUPS */
894 		num += ext4_bg_num_gdb_meta(sb, block_group);
895 	}
896 	return EXT4_NUM_B2C(sbi, num);
897 }
898 /**
899  *	ext4_inode_to_goal_block - return a hint for block allocation
900  *	@inode: inode for block allocation
901  *
902  *	Return the ideal location to start allocating blocks for a
903  *	newly created inode.
904  */
905 ext4_fsblk_t ext4_inode_to_goal_block(struct inode *inode)
906 {
907 	struct ext4_inode_info *ei = EXT4_I(inode);
908 	ext4_group_t block_group;
909 	ext4_grpblk_t colour;
910 	int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
911 	ext4_fsblk_t bg_start;
912 	ext4_fsblk_t last_block;
913 
914 	block_group = ei->i_block_group;
915 	if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
916 		/*
917 		 * If there are at least EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME
918 		 * block groups per flexgroup, reserve the first block
919 		 * group for directories and special files.  Regular
920 		 * files will start at the second block group.  This
921 		 * tends to speed up directory access and improves
922 		 * fsck times.
923 		 */
924 		block_group &= ~(flex_size-1);
925 		if (S_ISREG(inode->i_mode))
926 			block_group++;
927 	}
928 	bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
929 	last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
930 
931 	/*
932 	 * If we are doing delayed allocation, we don't need take
933 	 * colour into account.
934 	 */
935 	if (test_opt(inode->i_sb, DELALLOC))
936 		return bg_start;
937 
938 	if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
939 		colour = (task_pid_nr(current) % 16) *
940 			(EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
941 	else
942 		colour = (task_pid_nr(current) % 16) *
943 			((last_block - bg_start) / 16);
944 	return bg_start + colour;
945 }
946 
947