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