xref: /openbmc/linux/fs/ext4/ialloc.c (revision e1cd7b80)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/ext4/ialloc.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  *  BSD ufs-inspired inode and directory allocation by
11  *  Stephen Tweedie (sct@redhat.com), 1993
12  *  Big-endian to little-endian byte-swapping/bitmaps by
13  *        David S. Miller (davem@caip.rutgers.edu), 1995
14  */
15 
16 #include <linux/time.h>
17 #include <linux/fs.h>
18 #include <linux/stat.h>
19 #include <linux/string.h>
20 #include <linux/quotaops.h>
21 #include <linux/buffer_head.h>
22 #include <linux/random.h>
23 #include <linux/bitops.h>
24 #include <linux/blkdev.h>
25 #include <linux/cred.h>
26 
27 #include <asm/byteorder.h>
28 
29 #include "ext4.h"
30 #include "ext4_jbd2.h"
31 #include "xattr.h"
32 #include "acl.h"
33 
34 #include <trace/events/ext4.h>
35 
36 /*
37  * ialloc.c contains the inodes allocation and deallocation routines
38  */
39 
40 /*
41  * The free inodes are managed by bitmaps.  A file system contains several
42  * blocks groups.  Each group contains 1 bitmap block for blocks, 1 bitmap
43  * block for inodes, N blocks for the inode table and data blocks.
44  *
45  * The file system contains group descriptors which are located after the
46  * super block.  Each descriptor contains the number of the bitmap block and
47  * the free blocks count in the block.
48  */
49 
50 /*
51  * To avoid calling the atomic setbit hundreds or thousands of times, we only
52  * need to use it within a single byte (to ensure we get endianness right).
53  * We can use memset for the rest of the bitmap as there are no other users.
54  */
55 void ext4_mark_bitmap_end(int start_bit, int end_bit, char *bitmap)
56 {
57 	int i;
58 
59 	if (start_bit >= end_bit)
60 		return;
61 
62 	ext4_debug("mark end bits +%d through +%d used\n", start_bit, end_bit);
63 	for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
64 		ext4_set_bit(i, bitmap);
65 	if (i < end_bit)
66 		memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
67 }
68 
69 void ext4_end_bitmap_read(struct buffer_head *bh, int uptodate)
70 {
71 	if (uptodate) {
72 		set_buffer_uptodate(bh);
73 		set_bitmap_uptodate(bh);
74 	}
75 	unlock_buffer(bh);
76 	put_bh(bh);
77 }
78 
79 static int ext4_validate_inode_bitmap(struct super_block *sb,
80 				      struct ext4_group_desc *desc,
81 				      ext4_group_t block_group,
82 				      struct buffer_head *bh)
83 {
84 	ext4_fsblk_t	blk;
85 	struct ext4_group_info *grp = ext4_get_group_info(sb, block_group);
86 
87 	if (buffer_verified(bh))
88 		return 0;
89 	if (EXT4_MB_GRP_IBITMAP_CORRUPT(grp))
90 		return -EFSCORRUPTED;
91 
92 	ext4_lock_group(sb, block_group);
93 	if (buffer_verified(bh))
94 		goto verified;
95 	blk = ext4_inode_bitmap(sb, desc);
96 	if (!ext4_inode_bitmap_csum_verify(sb, block_group, desc, bh,
97 					   EXT4_INODES_PER_GROUP(sb) / 8)) {
98 		ext4_unlock_group(sb, block_group);
99 		ext4_error(sb, "Corrupt inode bitmap - block_group = %u, "
100 			   "inode_bitmap = %llu", block_group, blk);
101 		ext4_mark_group_bitmap_corrupted(sb, block_group,
102 					EXT4_GROUP_INFO_IBITMAP_CORRUPT);
103 		return -EFSBADCRC;
104 	}
105 	set_buffer_verified(bh);
106 verified:
107 	ext4_unlock_group(sb, block_group);
108 	return 0;
109 }
110 
111 /*
112  * Read the inode allocation bitmap for a given block_group, reading
113  * into the specified slot in the superblock's bitmap cache.
114  *
115  * Return buffer_head of bitmap on success or NULL.
116  */
117 static struct buffer_head *
118 ext4_read_inode_bitmap(struct super_block *sb, ext4_group_t block_group)
119 {
120 	struct ext4_group_desc *desc;
121 	struct ext4_sb_info *sbi = EXT4_SB(sb);
122 	struct buffer_head *bh = NULL;
123 	ext4_fsblk_t bitmap_blk;
124 	int err;
125 
126 	desc = ext4_get_group_desc(sb, block_group, NULL);
127 	if (!desc)
128 		return ERR_PTR(-EFSCORRUPTED);
129 
130 	bitmap_blk = ext4_inode_bitmap(sb, desc);
131 	if ((bitmap_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
132 	    (bitmap_blk >= ext4_blocks_count(sbi->s_es))) {
133 		ext4_error(sb, "Invalid inode bitmap blk %llu in "
134 			   "block_group %u", bitmap_blk, block_group);
135 		ext4_mark_group_bitmap_corrupted(sb, block_group,
136 					EXT4_GROUP_INFO_IBITMAP_CORRUPT);
137 		return ERR_PTR(-EFSCORRUPTED);
138 	}
139 	bh = sb_getblk(sb, bitmap_blk);
140 	if (unlikely(!bh)) {
141 		ext4_warning(sb, "Cannot read inode bitmap - "
142 			     "block_group = %u, inode_bitmap = %llu",
143 			     block_group, bitmap_blk);
144 		return ERR_PTR(-ENOMEM);
145 	}
146 	if (bitmap_uptodate(bh))
147 		goto verify;
148 
149 	lock_buffer(bh);
150 	if (bitmap_uptodate(bh)) {
151 		unlock_buffer(bh);
152 		goto verify;
153 	}
154 
155 	ext4_lock_group(sb, block_group);
156 	if (ext4_has_group_desc_csum(sb) &&
157 	    (desc->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT))) {
158 		if (block_group == 0) {
159 			ext4_unlock_group(sb, block_group);
160 			unlock_buffer(bh);
161 			ext4_error(sb, "Inode bitmap for bg 0 marked "
162 				   "uninitialized");
163 			err = -EFSCORRUPTED;
164 			goto out;
165 		}
166 		memset(bh->b_data, 0, (EXT4_INODES_PER_GROUP(sb) + 7) / 8);
167 		ext4_mark_bitmap_end(EXT4_INODES_PER_GROUP(sb),
168 				     sb->s_blocksize * 8, bh->b_data);
169 		set_bitmap_uptodate(bh);
170 		set_buffer_uptodate(bh);
171 		set_buffer_verified(bh);
172 		ext4_unlock_group(sb, block_group);
173 		unlock_buffer(bh);
174 		return bh;
175 	}
176 	ext4_unlock_group(sb, block_group);
177 
178 	if (buffer_uptodate(bh)) {
179 		/*
180 		 * if not uninit if bh is uptodate,
181 		 * bitmap is also uptodate
182 		 */
183 		set_bitmap_uptodate(bh);
184 		unlock_buffer(bh);
185 		goto verify;
186 	}
187 	/*
188 	 * submit the buffer_head for reading
189 	 */
190 	trace_ext4_load_inode_bitmap(sb, block_group);
191 	bh->b_end_io = ext4_end_bitmap_read;
192 	get_bh(bh);
193 	submit_bh(REQ_OP_READ, REQ_META | REQ_PRIO, bh);
194 	wait_on_buffer(bh);
195 	if (!buffer_uptodate(bh)) {
196 		put_bh(bh);
197 		ext4_error(sb, "Cannot read inode bitmap - "
198 			   "block_group = %u, inode_bitmap = %llu",
199 			   block_group, bitmap_blk);
200 		ext4_mark_group_bitmap_corrupted(sb, block_group,
201 				EXT4_GROUP_INFO_IBITMAP_CORRUPT);
202 		return ERR_PTR(-EIO);
203 	}
204 
205 verify:
206 	err = ext4_validate_inode_bitmap(sb, desc, block_group, bh);
207 	if (err)
208 		goto out;
209 	return bh;
210 out:
211 	put_bh(bh);
212 	return ERR_PTR(err);
213 }
214 
215 /*
216  * NOTE! When we get the inode, we're the only people
217  * that have access to it, and as such there are no
218  * race conditions we have to worry about. The inode
219  * is not on the hash-lists, and it cannot be reached
220  * through the filesystem because the directory entry
221  * has been deleted earlier.
222  *
223  * HOWEVER: we must make sure that we get no aliases,
224  * which means that we have to call "clear_inode()"
225  * _before_ we mark the inode not in use in the inode
226  * bitmaps. Otherwise a newly created file might use
227  * the same inode number (not actually the same pointer
228  * though), and then we'd have two inodes sharing the
229  * same inode number and space on the harddisk.
230  */
231 void ext4_free_inode(handle_t *handle, struct inode *inode)
232 {
233 	struct super_block *sb = inode->i_sb;
234 	int is_directory;
235 	unsigned long ino;
236 	struct buffer_head *bitmap_bh = NULL;
237 	struct buffer_head *bh2;
238 	ext4_group_t block_group;
239 	unsigned long bit;
240 	struct ext4_group_desc *gdp;
241 	struct ext4_super_block *es;
242 	struct ext4_sb_info *sbi;
243 	int fatal = 0, err, count, cleared;
244 	struct ext4_group_info *grp;
245 
246 	if (!sb) {
247 		printk(KERN_ERR "EXT4-fs: %s:%d: inode on "
248 		       "nonexistent device\n", __func__, __LINE__);
249 		return;
250 	}
251 	if (atomic_read(&inode->i_count) > 1) {
252 		ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: count=%d",
253 			 __func__, __LINE__, inode->i_ino,
254 			 atomic_read(&inode->i_count));
255 		return;
256 	}
257 	if (inode->i_nlink) {
258 		ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: nlink=%d\n",
259 			 __func__, __LINE__, inode->i_ino, inode->i_nlink);
260 		return;
261 	}
262 	sbi = EXT4_SB(sb);
263 
264 	ino = inode->i_ino;
265 	ext4_debug("freeing inode %lu\n", ino);
266 	trace_ext4_free_inode(inode);
267 
268 	dquot_initialize(inode);
269 	dquot_free_inode(inode);
270 
271 	is_directory = S_ISDIR(inode->i_mode);
272 
273 	/* Do this BEFORE marking the inode not in use or returning an error */
274 	ext4_clear_inode(inode);
275 
276 	es = sbi->s_es;
277 	if (ino < EXT4_FIRST_INO(sb) || ino > le32_to_cpu(es->s_inodes_count)) {
278 		ext4_error(sb, "reserved or nonexistent inode %lu", ino);
279 		goto error_return;
280 	}
281 	block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
282 	bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
283 	bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
284 	/* Don't bother if the inode bitmap is corrupt. */
285 	grp = ext4_get_group_info(sb, block_group);
286 	if (IS_ERR(bitmap_bh)) {
287 		fatal = PTR_ERR(bitmap_bh);
288 		bitmap_bh = NULL;
289 		goto error_return;
290 	}
291 	if (unlikely(EXT4_MB_GRP_IBITMAP_CORRUPT(grp))) {
292 		fatal = -EFSCORRUPTED;
293 		goto error_return;
294 	}
295 
296 	BUFFER_TRACE(bitmap_bh, "get_write_access");
297 	fatal = ext4_journal_get_write_access(handle, bitmap_bh);
298 	if (fatal)
299 		goto error_return;
300 
301 	fatal = -ESRCH;
302 	gdp = ext4_get_group_desc(sb, block_group, &bh2);
303 	if (gdp) {
304 		BUFFER_TRACE(bh2, "get_write_access");
305 		fatal = ext4_journal_get_write_access(handle, bh2);
306 	}
307 	ext4_lock_group(sb, block_group);
308 	cleared = ext4_test_and_clear_bit(bit, bitmap_bh->b_data);
309 	if (fatal || !cleared) {
310 		ext4_unlock_group(sb, block_group);
311 		goto out;
312 	}
313 
314 	count = ext4_free_inodes_count(sb, gdp) + 1;
315 	ext4_free_inodes_set(sb, gdp, count);
316 	if (is_directory) {
317 		count = ext4_used_dirs_count(sb, gdp) - 1;
318 		ext4_used_dirs_set(sb, gdp, count);
319 		percpu_counter_dec(&sbi->s_dirs_counter);
320 	}
321 	ext4_inode_bitmap_csum_set(sb, block_group, gdp, bitmap_bh,
322 				   EXT4_INODES_PER_GROUP(sb) / 8);
323 	ext4_group_desc_csum_set(sb, block_group, gdp);
324 	ext4_unlock_group(sb, block_group);
325 
326 	percpu_counter_inc(&sbi->s_freeinodes_counter);
327 	if (sbi->s_log_groups_per_flex) {
328 		ext4_group_t f = ext4_flex_group(sbi, block_group);
329 
330 		atomic_inc(&sbi->s_flex_groups[f].free_inodes);
331 		if (is_directory)
332 			atomic_dec(&sbi->s_flex_groups[f].used_dirs);
333 	}
334 	BUFFER_TRACE(bh2, "call ext4_handle_dirty_metadata");
335 	fatal = ext4_handle_dirty_metadata(handle, NULL, bh2);
336 out:
337 	if (cleared) {
338 		BUFFER_TRACE(bitmap_bh, "call ext4_handle_dirty_metadata");
339 		err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
340 		if (!fatal)
341 			fatal = err;
342 	} else {
343 		ext4_error(sb, "bit already cleared for inode %lu", ino);
344 		ext4_mark_group_bitmap_corrupted(sb, block_group,
345 					EXT4_GROUP_INFO_IBITMAP_CORRUPT);
346 	}
347 
348 error_return:
349 	brelse(bitmap_bh);
350 	ext4_std_error(sb, fatal);
351 }
352 
353 struct orlov_stats {
354 	__u64 free_clusters;
355 	__u32 free_inodes;
356 	__u32 used_dirs;
357 };
358 
359 /*
360  * Helper function for Orlov's allocator; returns critical information
361  * for a particular block group or flex_bg.  If flex_size is 1, then g
362  * is a block group number; otherwise it is flex_bg number.
363  */
364 static void get_orlov_stats(struct super_block *sb, ext4_group_t g,
365 			    int flex_size, struct orlov_stats *stats)
366 {
367 	struct ext4_group_desc *desc;
368 	struct flex_groups *flex_group = EXT4_SB(sb)->s_flex_groups;
369 
370 	if (flex_size > 1) {
371 		stats->free_inodes = atomic_read(&flex_group[g].free_inodes);
372 		stats->free_clusters = atomic64_read(&flex_group[g].free_clusters);
373 		stats->used_dirs = atomic_read(&flex_group[g].used_dirs);
374 		return;
375 	}
376 
377 	desc = ext4_get_group_desc(sb, g, NULL);
378 	if (desc) {
379 		stats->free_inodes = ext4_free_inodes_count(sb, desc);
380 		stats->free_clusters = ext4_free_group_clusters(sb, desc);
381 		stats->used_dirs = ext4_used_dirs_count(sb, desc);
382 	} else {
383 		stats->free_inodes = 0;
384 		stats->free_clusters = 0;
385 		stats->used_dirs = 0;
386 	}
387 }
388 
389 /*
390  * Orlov's allocator for directories.
391  *
392  * We always try to spread first-level directories.
393  *
394  * If there are blockgroups with both free inodes and free blocks counts
395  * not worse than average we return one with smallest directory count.
396  * Otherwise we simply return a random group.
397  *
398  * For the rest rules look so:
399  *
400  * It's OK to put directory into a group unless
401  * it has too many directories already (max_dirs) or
402  * it has too few free inodes left (min_inodes) or
403  * it has too few free blocks left (min_blocks) or
404  * Parent's group is preferred, if it doesn't satisfy these
405  * conditions we search cyclically through the rest. If none
406  * of the groups look good we just look for a group with more
407  * free inodes than average (starting at parent's group).
408  */
409 
410 static int find_group_orlov(struct super_block *sb, struct inode *parent,
411 			    ext4_group_t *group, umode_t mode,
412 			    const struct qstr *qstr)
413 {
414 	ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
415 	struct ext4_sb_info *sbi = EXT4_SB(sb);
416 	ext4_group_t real_ngroups = ext4_get_groups_count(sb);
417 	int inodes_per_group = EXT4_INODES_PER_GROUP(sb);
418 	unsigned int freei, avefreei, grp_free;
419 	ext4_fsblk_t freeb, avefreec;
420 	unsigned int ndirs;
421 	int max_dirs, min_inodes;
422 	ext4_grpblk_t min_clusters;
423 	ext4_group_t i, grp, g, ngroups;
424 	struct ext4_group_desc *desc;
425 	struct orlov_stats stats;
426 	int flex_size = ext4_flex_bg_size(sbi);
427 	struct dx_hash_info hinfo;
428 
429 	ngroups = real_ngroups;
430 	if (flex_size > 1) {
431 		ngroups = (real_ngroups + flex_size - 1) >>
432 			sbi->s_log_groups_per_flex;
433 		parent_group >>= sbi->s_log_groups_per_flex;
434 	}
435 
436 	freei = percpu_counter_read_positive(&sbi->s_freeinodes_counter);
437 	avefreei = freei / ngroups;
438 	freeb = EXT4_C2B(sbi,
439 		percpu_counter_read_positive(&sbi->s_freeclusters_counter));
440 	avefreec = freeb;
441 	do_div(avefreec, ngroups);
442 	ndirs = percpu_counter_read_positive(&sbi->s_dirs_counter);
443 
444 	if (S_ISDIR(mode) &&
445 	    ((parent == d_inode(sb->s_root)) ||
446 	     (ext4_test_inode_flag(parent, EXT4_INODE_TOPDIR)))) {
447 		int best_ndir = inodes_per_group;
448 		int ret = -1;
449 
450 		if (qstr) {
451 			hinfo.hash_version = DX_HASH_HALF_MD4;
452 			hinfo.seed = sbi->s_hash_seed;
453 			ext4fs_dirhash(parent, qstr->name, qstr->len, &hinfo);
454 			grp = hinfo.hash;
455 		} else
456 			grp = prandom_u32();
457 		parent_group = (unsigned)grp % ngroups;
458 		for (i = 0; i < ngroups; i++) {
459 			g = (parent_group + i) % ngroups;
460 			get_orlov_stats(sb, g, flex_size, &stats);
461 			if (!stats.free_inodes)
462 				continue;
463 			if (stats.used_dirs >= best_ndir)
464 				continue;
465 			if (stats.free_inodes < avefreei)
466 				continue;
467 			if (stats.free_clusters < avefreec)
468 				continue;
469 			grp = g;
470 			ret = 0;
471 			best_ndir = stats.used_dirs;
472 		}
473 		if (ret)
474 			goto fallback;
475 	found_flex_bg:
476 		if (flex_size == 1) {
477 			*group = grp;
478 			return 0;
479 		}
480 
481 		/*
482 		 * We pack inodes at the beginning of the flexgroup's
483 		 * inode tables.  Block allocation decisions will do
484 		 * something similar, although regular files will
485 		 * start at 2nd block group of the flexgroup.  See
486 		 * ext4_ext_find_goal() and ext4_find_near().
487 		 */
488 		grp *= flex_size;
489 		for (i = 0; i < flex_size; i++) {
490 			if (grp+i >= real_ngroups)
491 				break;
492 			desc = ext4_get_group_desc(sb, grp+i, NULL);
493 			if (desc && ext4_free_inodes_count(sb, desc)) {
494 				*group = grp+i;
495 				return 0;
496 			}
497 		}
498 		goto fallback;
499 	}
500 
501 	max_dirs = ndirs / ngroups + inodes_per_group / 16;
502 	min_inodes = avefreei - inodes_per_group*flex_size / 4;
503 	if (min_inodes < 1)
504 		min_inodes = 1;
505 	min_clusters = avefreec - EXT4_CLUSTERS_PER_GROUP(sb)*flex_size / 4;
506 
507 	/*
508 	 * Start looking in the flex group where we last allocated an
509 	 * inode for this parent directory
510 	 */
511 	if (EXT4_I(parent)->i_last_alloc_group != ~0) {
512 		parent_group = EXT4_I(parent)->i_last_alloc_group;
513 		if (flex_size > 1)
514 			parent_group >>= sbi->s_log_groups_per_flex;
515 	}
516 
517 	for (i = 0; i < ngroups; i++) {
518 		grp = (parent_group + i) % ngroups;
519 		get_orlov_stats(sb, grp, flex_size, &stats);
520 		if (stats.used_dirs >= max_dirs)
521 			continue;
522 		if (stats.free_inodes < min_inodes)
523 			continue;
524 		if (stats.free_clusters < min_clusters)
525 			continue;
526 		goto found_flex_bg;
527 	}
528 
529 fallback:
530 	ngroups = real_ngroups;
531 	avefreei = freei / ngroups;
532 fallback_retry:
533 	parent_group = EXT4_I(parent)->i_block_group;
534 	for (i = 0; i < ngroups; i++) {
535 		grp = (parent_group + i) % ngroups;
536 		desc = ext4_get_group_desc(sb, grp, NULL);
537 		if (desc) {
538 			grp_free = ext4_free_inodes_count(sb, desc);
539 			if (grp_free && grp_free >= avefreei) {
540 				*group = grp;
541 				return 0;
542 			}
543 		}
544 	}
545 
546 	if (avefreei) {
547 		/*
548 		 * The free-inodes counter is approximate, and for really small
549 		 * filesystems the above test can fail to find any blockgroups
550 		 */
551 		avefreei = 0;
552 		goto fallback_retry;
553 	}
554 
555 	return -1;
556 }
557 
558 static int find_group_other(struct super_block *sb, struct inode *parent,
559 			    ext4_group_t *group, umode_t mode)
560 {
561 	ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
562 	ext4_group_t i, last, ngroups = ext4_get_groups_count(sb);
563 	struct ext4_group_desc *desc;
564 	int flex_size = ext4_flex_bg_size(EXT4_SB(sb));
565 
566 	/*
567 	 * Try to place the inode is the same flex group as its
568 	 * parent.  If we can't find space, use the Orlov algorithm to
569 	 * find another flex group, and store that information in the
570 	 * parent directory's inode information so that use that flex
571 	 * group for future allocations.
572 	 */
573 	if (flex_size > 1) {
574 		int retry = 0;
575 
576 	try_again:
577 		parent_group &= ~(flex_size-1);
578 		last = parent_group + flex_size;
579 		if (last > ngroups)
580 			last = ngroups;
581 		for  (i = parent_group; i < last; i++) {
582 			desc = ext4_get_group_desc(sb, i, NULL);
583 			if (desc && ext4_free_inodes_count(sb, desc)) {
584 				*group = i;
585 				return 0;
586 			}
587 		}
588 		if (!retry && EXT4_I(parent)->i_last_alloc_group != ~0) {
589 			retry = 1;
590 			parent_group = EXT4_I(parent)->i_last_alloc_group;
591 			goto try_again;
592 		}
593 		/*
594 		 * If this didn't work, use the Orlov search algorithm
595 		 * to find a new flex group; we pass in the mode to
596 		 * avoid the topdir algorithms.
597 		 */
598 		*group = parent_group + flex_size;
599 		if (*group > ngroups)
600 			*group = 0;
601 		return find_group_orlov(sb, parent, group, mode, NULL);
602 	}
603 
604 	/*
605 	 * Try to place the inode in its parent directory
606 	 */
607 	*group = parent_group;
608 	desc = ext4_get_group_desc(sb, *group, NULL);
609 	if (desc && ext4_free_inodes_count(sb, desc) &&
610 	    ext4_free_group_clusters(sb, desc))
611 		return 0;
612 
613 	/*
614 	 * We're going to place this inode in a different blockgroup from its
615 	 * parent.  We want to cause files in a common directory to all land in
616 	 * the same blockgroup.  But we want files which are in a different
617 	 * directory which shares a blockgroup with our parent to land in a
618 	 * different blockgroup.
619 	 *
620 	 * So add our directory's i_ino into the starting point for the hash.
621 	 */
622 	*group = (*group + parent->i_ino) % ngroups;
623 
624 	/*
625 	 * Use a quadratic hash to find a group with a free inode and some free
626 	 * blocks.
627 	 */
628 	for (i = 1; i < ngroups; i <<= 1) {
629 		*group += i;
630 		if (*group >= ngroups)
631 			*group -= ngroups;
632 		desc = ext4_get_group_desc(sb, *group, NULL);
633 		if (desc && ext4_free_inodes_count(sb, desc) &&
634 		    ext4_free_group_clusters(sb, desc))
635 			return 0;
636 	}
637 
638 	/*
639 	 * That failed: try linear search for a free inode, even if that group
640 	 * has no free blocks.
641 	 */
642 	*group = parent_group;
643 	for (i = 0; i < ngroups; i++) {
644 		if (++*group >= ngroups)
645 			*group = 0;
646 		desc = ext4_get_group_desc(sb, *group, NULL);
647 		if (desc && ext4_free_inodes_count(sb, desc))
648 			return 0;
649 	}
650 
651 	return -1;
652 }
653 
654 /*
655  * In no journal mode, if an inode has recently been deleted, we want
656  * to avoid reusing it until we're reasonably sure the inode table
657  * block has been written back to disk.  (Yes, these values are
658  * somewhat arbitrary...)
659  */
660 #define RECENTCY_MIN	5
661 #define RECENTCY_DIRTY	300
662 
663 static int recently_deleted(struct super_block *sb, ext4_group_t group, int ino)
664 {
665 	struct ext4_group_desc	*gdp;
666 	struct ext4_inode	*raw_inode;
667 	struct buffer_head	*bh;
668 	int inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
669 	int offset, ret = 0;
670 	int recentcy = RECENTCY_MIN;
671 	u32 dtime, now;
672 
673 	gdp = ext4_get_group_desc(sb, group, NULL);
674 	if (unlikely(!gdp))
675 		return 0;
676 
677 	bh = sb_find_get_block(sb, ext4_inode_table(sb, gdp) +
678 		       (ino / inodes_per_block));
679 	if (!bh || !buffer_uptodate(bh))
680 		/*
681 		 * If the block is not in the buffer cache, then it
682 		 * must have been written out.
683 		 */
684 		goto out;
685 
686 	offset = (ino % inodes_per_block) * EXT4_INODE_SIZE(sb);
687 	raw_inode = (struct ext4_inode *) (bh->b_data + offset);
688 
689 	/* i_dtime is only 32 bits on disk, but we only care about relative
690 	 * times in the range of a few minutes (i.e. long enough to sync a
691 	 * recently-deleted inode to disk), so using the low 32 bits of the
692 	 * clock (a 68 year range) is enough, see time_before32() */
693 	dtime = le32_to_cpu(raw_inode->i_dtime);
694 	now = ktime_get_real_seconds();
695 	if (buffer_dirty(bh))
696 		recentcy += RECENTCY_DIRTY;
697 
698 	if (dtime && time_before32(dtime, now) &&
699 	    time_before32(now, dtime + recentcy))
700 		ret = 1;
701 out:
702 	brelse(bh);
703 	return ret;
704 }
705 
706 static int find_inode_bit(struct super_block *sb, ext4_group_t group,
707 			  struct buffer_head *bitmap, unsigned long *ino)
708 {
709 next:
710 	*ino = ext4_find_next_zero_bit((unsigned long *)
711 				       bitmap->b_data,
712 				       EXT4_INODES_PER_GROUP(sb), *ino);
713 	if (*ino >= EXT4_INODES_PER_GROUP(sb))
714 		return 0;
715 
716 	if ((EXT4_SB(sb)->s_journal == NULL) &&
717 	    recently_deleted(sb, group, *ino)) {
718 		*ino = *ino + 1;
719 		if (*ino < EXT4_INODES_PER_GROUP(sb))
720 			goto next;
721 		return 0;
722 	}
723 
724 	return 1;
725 }
726 
727 /*
728  * There are two policies for allocating an inode.  If the new inode is
729  * a directory, then a forward search is made for a block group with both
730  * free space and a low directory-to-inode ratio; if that fails, then of
731  * the groups with above-average free space, that group with the fewest
732  * directories already is chosen.
733  *
734  * For other inodes, search forward from the parent directory's block
735  * group to find a free inode.
736  */
737 struct inode *__ext4_new_inode(handle_t *handle, struct inode *dir,
738 			       umode_t mode, const struct qstr *qstr,
739 			       __u32 goal, uid_t *owner, __u32 i_flags,
740 			       int handle_type, unsigned int line_no,
741 			       int nblocks)
742 {
743 	struct super_block *sb;
744 	struct buffer_head *inode_bitmap_bh = NULL;
745 	struct buffer_head *group_desc_bh;
746 	ext4_group_t ngroups, group = 0;
747 	unsigned long ino = 0;
748 	struct inode *inode;
749 	struct ext4_group_desc *gdp = NULL;
750 	struct ext4_inode_info *ei;
751 	struct ext4_sb_info *sbi;
752 	int ret2, err;
753 	struct inode *ret;
754 	ext4_group_t i;
755 	ext4_group_t flex_group;
756 	struct ext4_group_info *grp;
757 	int encrypt = 0;
758 
759 	/* Cannot create files in a deleted directory */
760 	if (!dir || !dir->i_nlink)
761 		return ERR_PTR(-EPERM);
762 
763 	sb = dir->i_sb;
764 	sbi = EXT4_SB(sb);
765 
766 	if (unlikely(ext4_forced_shutdown(sbi)))
767 		return ERR_PTR(-EIO);
768 
769 	if ((IS_ENCRYPTED(dir) || DUMMY_ENCRYPTION_ENABLED(sbi)) &&
770 	    (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)) &&
771 	    !(i_flags & EXT4_EA_INODE_FL)) {
772 		err = fscrypt_get_encryption_info(dir);
773 		if (err)
774 			return ERR_PTR(err);
775 		if (!fscrypt_has_encryption_key(dir))
776 			return ERR_PTR(-ENOKEY);
777 		encrypt = 1;
778 	}
779 
780 	if (!handle && sbi->s_journal && !(i_flags & EXT4_EA_INODE_FL)) {
781 #ifdef CONFIG_EXT4_FS_POSIX_ACL
782 		struct posix_acl *p = get_acl(dir, ACL_TYPE_DEFAULT);
783 
784 		if (IS_ERR(p))
785 			return ERR_CAST(p);
786 		if (p) {
787 			int acl_size = p->a_count * sizeof(ext4_acl_entry);
788 
789 			nblocks += (S_ISDIR(mode) ? 2 : 1) *
790 				__ext4_xattr_set_credits(sb, NULL /* inode */,
791 					NULL /* block_bh */, acl_size,
792 					true /* is_create */);
793 			posix_acl_release(p);
794 		}
795 #endif
796 
797 #ifdef CONFIG_SECURITY
798 		{
799 			int num_security_xattrs = 1;
800 
801 #ifdef CONFIG_INTEGRITY
802 			num_security_xattrs++;
803 #endif
804 			/*
805 			 * We assume that security xattrs are never
806 			 * more than 1k.  In practice they are under
807 			 * 128 bytes.
808 			 */
809 			nblocks += num_security_xattrs *
810 				__ext4_xattr_set_credits(sb, NULL /* inode */,
811 					NULL /* block_bh */, 1024,
812 					true /* is_create */);
813 		}
814 #endif
815 		if (encrypt)
816 			nblocks += __ext4_xattr_set_credits(sb,
817 					NULL /* inode */, NULL /* block_bh */,
818 					FSCRYPT_SET_CONTEXT_MAX_SIZE,
819 					true /* is_create */);
820 	}
821 
822 	ngroups = ext4_get_groups_count(sb);
823 	trace_ext4_request_inode(dir, mode);
824 	inode = new_inode(sb);
825 	if (!inode)
826 		return ERR_PTR(-ENOMEM);
827 	ei = EXT4_I(inode);
828 
829 	/*
830 	 * Initialize owners and quota early so that we don't have to account
831 	 * for quota initialization worst case in standard inode creating
832 	 * transaction
833 	 */
834 	if (owner) {
835 		inode->i_mode = mode;
836 		i_uid_write(inode, owner[0]);
837 		i_gid_write(inode, owner[1]);
838 	} else if (test_opt(sb, GRPID)) {
839 		inode->i_mode = mode;
840 		inode->i_uid = current_fsuid();
841 		inode->i_gid = dir->i_gid;
842 	} else
843 		inode_init_owner(inode, dir, mode);
844 
845 	if (ext4_has_feature_project(sb) &&
846 	    ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT))
847 		ei->i_projid = EXT4_I(dir)->i_projid;
848 	else
849 		ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID);
850 
851 	err = dquot_initialize(inode);
852 	if (err)
853 		goto out;
854 
855 	if (!goal)
856 		goal = sbi->s_inode_goal;
857 
858 	if (goal && goal <= le32_to_cpu(sbi->s_es->s_inodes_count)) {
859 		group = (goal - 1) / EXT4_INODES_PER_GROUP(sb);
860 		ino = (goal - 1) % EXT4_INODES_PER_GROUP(sb);
861 		ret2 = 0;
862 		goto got_group;
863 	}
864 
865 	if (S_ISDIR(mode))
866 		ret2 = find_group_orlov(sb, dir, &group, mode, qstr);
867 	else
868 		ret2 = find_group_other(sb, dir, &group, mode);
869 
870 got_group:
871 	EXT4_I(dir)->i_last_alloc_group = group;
872 	err = -ENOSPC;
873 	if (ret2 == -1)
874 		goto out;
875 
876 	/*
877 	 * Normally we will only go through one pass of this loop,
878 	 * unless we get unlucky and it turns out the group we selected
879 	 * had its last inode grabbed by someone else.
880 	 */
881 	for (i = 0; i < ngroups; i++, ino = 0) {
882 		err = -EIO;
883 
884 		gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
885 		if (!gdp)
886 			goto out;
887 
888 		/*
889 		 * Check free inodes count before loading bitmap.
890 		 */
891 		if (ext4_free_inodes_count(sb, gdp) == 0)
892 			goto next_group;
893 
894 		grp = ext4_get_group_info(sb, group);
895 		/* Skip groups with already-known suspicious inode tables */
896 		if (EXT4_MB_GRP_IBITMAP_CORRUPT(grp))
897 			goto next_group;
898 
899 		brelse(inode_bitmap_bh);
900 		inode_bitmap_bh = ext4_read_inode_bitmap(sb, group);
901 		/* Skip groups with suspicious inode tables */
902 		if (EXT4_MB_GRP_IBITMAP_CORRUPT(grp) ||
903 		    IS_ERR(inode_bitmap_bh)) {
904 			inode_bitmap_bh = NULL;
905 			goto next_group;
906 		}
907 
908 repeat_in_this_group:
909 		ret2 = find_inode_bit(sb, group, inode_bitmap_bh, &ino);
910 		if (!ret2)
911 			goto next_group;
912 
913 		if (group == 0 && (ino + 1) < EXT4_FIRST_INO(sb)) {
914 			ext4_error(sb, "reserved inode found cleared - "
915 				   "inode=%lu", ino + 1);
916 			ext4_mark_group_bitmap_corrupted(sb, group,
917 					EXT4_GROUP_INFO_IBITMAP_CORRUPT);
918 			goto next_group;
919 		}
920 
921 		if (!handle) {
922 			BUG_ON(nblocks <= 0);
923 			handle = __ext4_journal_start_sb(dir->i_sb, line_no,
924 							 handle_type, nblocks,
925 							 0, 0);
926 			if (IS_ERR(handle)) {
927 				err = PTR_ERR(handle);
928 				ext4_std_error(sb, err);
929 				goto out;
930 			}
931 		}
932 		BUFFER_TRACE(inode_bitmap_bh, "get_write_access");
933 		err = ext4_journal_get_write_access(handle, inode_bitmap_bh);
934 		if (err) {
935 			ext4_std_error(sb, err);
936 			goto out;
937 		}
938 		ext4_lock_group(sb, group);
939 		ret2 = ext4_test_and_set_bit(ino, inode_bitmap_bh->b_data);
940 		if (ret2) {
941 			/* Someone already took the bit. Repeat the search
942 			 * with lock held.
943 			 */
944 			ret2 = find_inode_bit(sb, group, inode_bitmap_bh, &ino);
945 			if (ret2) {
946 				ext4_set_bit(ino, inode_bitmap_bh->b_data);
947 				ret2 = 0;
948 			} else {
949 				ret2 = 1; /* we didn't grab the inode */
950 			}
951 		}
952 		ext4_unlock_group(sb, group);
953 		ino++;		/* the inode bitmap is zero-based */
954 		if (!ret2)
955 			goto got; /* we grabbed the inode! */
956 
957 		if (ino < EXT4_INODES_PER_GROUP(sb))
958 			goto repeat_in_this_group;
959 next_group:
960 		if (++group == ngroups)
961 			group = 0;
962 	}
963 	err = -ENOSPC;
964 	goto out;
965 
966 got:
967 	BUFFER_TRACE(inode_bitmap_bh, "call ext4_handle_dirty_metadata");
968 	err = ext4_handle_dirty_metadata(handle, NULL, inode_bitmap_bh);
969 	if (err) {
970 		ext4_std_error(sb, err);
971 		goto out;
972 	}
973 
974 	BUFFER_TRACE(group_desc_bh, "get_write_access");
975 	err = ext4_journal_get_write_access(handle, group_desc_bh);
976 	if (err) {
977 		ext4_std_error(sb, err);
978 		goto out;
979 	}
980 
981 	/* We may have to initialize the block bitmap if it isn't already */
982 	if (ext4_has_group_desc_csum(sb) &&
983 	    gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
984 		struct buffer_head *block_bitmap_bh;
985 
986 		block_bitmap_bh = ext4_read_block_bitmap(sb, group);
987 		if (IS_ERR(block_bitmap_bh)) {
988 			err = PTR_ERR(block_bitmap_bh);
989 			goto out;
990 		}
991 		BUFFER_TRACE(block_bitmap_bh, "get block bitmap access");
992 		err = ext4_journal_get_write_access(handle, block_bitmap_bh);
993 		if (err) {
994 			brelse(block_bitmap_bh);
995 			ext4_std_error(sb, err);
996 			goto out;
997 		}
998 
999 		BUFFER_TRACE(block_bitmap_bh, "dirty block bitmap");
1000 		err = ext4_handle_dirty_metadata(handle, NULL, block_bitmap_bh);
1001 
1002 		/* recheck and clear flag under lock if we still need to */
1003 		ext4_lock_group(sb, group);
1004 		if (ext4_has_group_desc_csum(sb) &&
1005 		    (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
1006 			gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
1007 			ext4_free_group_clusters_set(sb, gdp,
1008 				ext4_free_clusters_after_init(sb, group, gdp));
1009 			ext4_block_bitmap_csum_set(sb, group, gdp,
1010 						   block_bitmap_bh);
1011 			ext4_group_desc_csum_set(sb, group, gdp);
1012 		}
1013 		ext4_unlock_group(sb, group);
1014 		brelse(block_bitmap_bh);
1015 
1016 		if (err) {
1017 			ext4_std_error(sb, err);
1018 			goto out;
1019 		}
1020 	}
1021 
1022 	/* Update the relevant bg descriptor fields */
1023 	if (ext4_has_group_desc_csum(sb)) {
1024 		int free;
1025 		struct ext4_group_info *grp = ext4_get_group_info(sb, group);
1026 
1027 		down_read(&grp->alloc_sem); /* protect vs itable lazyinit */
1028 		ext4_lock_group(sb, group); /* while we modify the bg desc */
1029 		free = EXT4_INODES_PER_GROUP(sb) -
1030 			ext4_itable_unused_count(sb, gdp);
1031 		if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
1032 			gdp->bg_flags &= cpu_to_le16(~EXT4_BG_INODE_UNINIT);
1033 			free = 0;
1034 		}
1035 		/*
1036 		 * Check the relative inode number against the last used
1037 		 * relative inode number in this group. if it is greater
1038 		 * we need to update the bg_itable_unused count
1039 		 */
1040 		if (ino > free)
1041 			ext4_itable_unused_set(sb, gdp,
1042 					(EXT4_INODES_PER_GROUP(sb) - ino));
1043 		up_read(&grp->alloc_sem);
1044 	} else {
1045 		ext4_lock_group(sb, group);
1046 	}
1047 
1048 	ext4_free_inodes_set(sb, gdp, ext4_free_inodes_count(sb, gdp) - 1);
1049 	if (S_ISDIR(mode)) {
1050 		ext4_used_dirs_set(sb, gdp, ext4_used_dirs_count(sb, gdp) + 1);
1051 		if (sbi->s_log_groups_per_flex) {
1052 			ext4_group_t f = ext4_flex_group(sbi, group);
1053 
1054 			atomic_inc(&sbi->s_flex_groups[f].used_dirs);
1055 		}
1056 	}
1057 	if (ext4_has_group_desc_csum(sb)) {
1058 		ext4_inode_bitmap_csum_set(sb, group, gdp, inode_bitmap_bh,
1059 					   EXT4_INODES_PER_GROUP(sb) / 8);
1060 		ext4_group_desc_csum_set(sb, group, gdp);
1061 	}
1062 	ext4_unlock_group(sb, group);
1063 
1064 	BUFFER_TRACE(group_desc_bh, "call ext4_handle_dirty_metadata");
1065 	err = ext4_handle_dirty_metadata(handle, NULL, group_desc_bh);
1066 	if (err) {
1067 		ext4_std_error(sb, err);
1068 		goto out;
1069 	}
1070 
1071 	percpu_counter_dec(&sbi->s_freeinodes_counter);
1072 	if (S_ISDIR(mode))
1073 		percpu_counter_inc(&sbi->s_dirs_counter);
1074 
1075 	if (sbi->s_log_groups_per_flex) {
1076 		flex_group = ext4_flex_group(sbi, group);
1077 		atomic_dec(&sbi->s_flex_groups[flex_group].free_inodes);
1078 	}
1079 
1080 	inode->i_ino = ino + group * EXT4_INODES_PER_GROUP(sb);
1081 	/* This is the optimal IO size (for stat), not the fs block size */
1082 	inode->i_blocks = 0;
1083 	inode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode);
1084 	ei->i_crtime = inode->i_mtime;
1085 
1086 	memset(ei->i_data, 0, sizeof(ei->i_data));
1087 	ei->i_dir_start_lookup = 0;
1088 	ei->i_disksize = 0;
1089 
1090 	/* Don't inherit extent flag from directory, amongst others. */
1091 	ei->i_flags =
1092 		ext4_mask_flags(mode, EXT4_I(dir)->i_flags & EXT4_FL_INHERITED);
1093 	ei->i_flags |= i_flags;
1094 	ei->i_file_acl = 0;
1095 	ei->i_dtime = 0;
1096 	ei->i_block_group = group;
1097 	ei->i_last_alloc_group = ~0;
1098 
1099 	ext4_set_inode_flags(inode);
1100 	if (IS_DIRSYNC(inode))
1101 		ext4_handle_sync(handle);
1102 	if (insert_inode_locked(inode) < 0) {
1103 		/*
1104 		 * Likely a bitmap corruption causing inode to be allocated
1105 		 * twice.
1106 		 */
1107 		err = -EIO;
1108 		ext4_error(sb, "failed to insert inode %lu: doubly allocated?",
1109 			   inode->i_ino);
1110 		ext4_mark_group_bitmap_corrupted(sb, group,
1111 					EXT4_GROUP_INFO_IBITMAP_CORRUPT);
1112 		goto out;
1113 	}
1114 	inode->i_generation = prandom_u32();
1115 
1116 	/* Precompute checksum seed for inode metadata */
1117 	if (ext4_has_metadata_csum(sb)) {
1118 		__u32 csum;
1119 		__le32 inum = cpu_to_le32(inode->i_ino);
1120 		__le32 gen = cpu_to_le32(inode->i_generation);
1121 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
1122 				   sizeof(inum));
1123 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
1124 					      sizeof(gen));
1125 	}
1126 
1127 	ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
1128 	ext4_set_inode_state(inode, EXT4_STATE_NEW);
1129 
1130 	ei->i_extra_isize = sbi->s_want_extra_isize;
1131 	ei->i_inline_off = 0;
1132 	if (ext4_has_feature_inline_data(sb))
1133 		ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
1134 	ret = inode;
1135 	err = dquot_alloc_inode(inode);
1136 	if (err)
1137 		goto fail_drop;
1138 
1139 	/*
1140 	 * Since the encryption xattr will always be unique, create it first so
1141 	 * that it's less likely to end up in an external xattr block and
1142 	 * prevent its deduplication.
1143 	 */
1144 	if (encrypt) {
1145 		err = fscrypt_inherit_context(dir, inode, handle, true);
1146 		if (err)
1147 			goto fail_free_drop;
1148 	}
1149 
1150 	if (!(ei->i_flags & EXT4_EA_INODE_FL)) {
1151 		err = ext4_init_acl(handle, inode, dir);
1152 		if (err)
1153 			goto fail_free_drop;
1154 
1155 		err = ext4_init_security(handle, inode, dir, qstr);
1156 		if (err)
1157 			goto fail_free_drop;
1158 	}
1159 
1160 	if (ext4_has_feature_extents(sb)) {
1161 		/* set extent flag only for directory, file and normal symlink*/
1162 		if (S_ISDIR(mode) || S_ISREG(mode) || S_ISLNK(mode)) {
1163 			ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS);
1164 			ext4_ext_tree_init(handle, inode);
1165 		}
1166 	}
1167 
1168 	if (ext4_handle_valid(handle)) {
1169 		ei->i_sync_tid = handle->h_transaction->t_tid;
1170 		ei->i_datasync_tid = handle->h_transaction->t_tid;
1171 	}
1172 
1173 	err = ext4_mark_inode_dirty(handle, inode);
1174 	if (err) {
1175 		ext4_std_error(sb, err);
1176 		goto fail_free_drop;
1177 	}
1178 
1179 	ext4_debug("allocating inode %lu\n", inode->i_ino);
1180 	trace_ext4_allocate_inode(inode, dir, mode);
1181 	brelse(inode_bitmap_bh);
1182 	return ret;
1183 
1184 fail_free_drop:
1185 	dquot_free_inode(inode);
1186 fail_drop:
1187 	clear_nlink(inode);
1188 	unlock_new_inode(inode);
1189 out:
1190 	dquot_drop(inode);
1191 	inode->i_flags |= S_NOQUOTA;
1192 	iput(inode);
1193 	brelse(inode_bitmap_bh);
1194 	return ERR_PTR(err);
1195 }
1196 
1197 /* Verify that we are loading a valid orphan from disk */
1198 struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino)
1199 {
1200 	unsigned long max_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count);
1201 	ext4_group_t block_group;
1202 	int bit;
1203 	struct buffer_head *bitmap_bh = NULL;
1204 	struct inode *inode = NULL;
1205 	int err = -EFSCORRUPTED;
1206 
1207 	if (ino < EXT4_FIRST_INO(sb) || ino > max_ino)
1208 		goto bad_orphan;
1209 
1210 	block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
1211 	bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
1212 	bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
1213 	if (IS_ERR(bitmap_bh))
1214 		return ERR_CAST(bitmap_bh);
1215 
1216 	/* Having the inode bit set should be a 100% indicator that this
1217 	 * is a valid orphan (no e2fsck run on fs).  Orphans also include
1218 	 * inodes that were being truncated, so we can't check i_nlink==0.
1219 	 */
1220 	if (!ext4_test_bit(bit, bitmap_bh->b_data))
1221 		goto bad_orphan;
1222 
1223 	inode = ext4_iget(sb, ino, EXT4_IGET_NORMAL);
1224 	if (IS_ERR(inode)) {
1225 		err = PTR_ERR(inode);
1226 		ext4_error(sb, "couldn't read orphan inode %lu (err %d)",
1227 			   ino, err);
1228 		return inode;
1229 	}
1230 
1231 	/*
1232 	 * If the orphans has i_nlinks > 0 then it should be able to
1233 	 * be truncated, otherwise it won't be removed from the orphan
1234 	 * list during processing and an infinite loop will result.
1235 	 * Similarly, it must not be a bad inode.
1236 	 */
1237 	if ((inode->i_nlink && !ext4_can_truncate(inode)) ||
1238 	    is_bad_inode(inode))
1239 		goto bad_orphan;
1240 
1241 	if (NEXT_ORPHAN(inode) > max_ino)
1242 		goto bad_orphan;
1243 	brelse(bitmap_bh);
1244 	return inode;
1245 
1246 bad_orphan:
1247 	ext4_error(sb, "bad orphan inode %lu", ino);
1248 	if (bitmap_bh)
1249 		printk(KERN_ERR "ext4_test_bit(bit=%d, block=%llu) = %d\n",
1250 		       bit, (unsigned long long)bitmap_bh->b_blocknr,
1251 		       ext4_test_bit(bit, bitmap_bh->b_data));
1252 	if (inode) {
1253 		printk(KERN_ERR "is_bad_inode(inode)=%d\n",
1254 		       is_bad_inode(inode));
1255 		printk(KERN_ERR "NEXT_ORPHAN(inode)=%u\n",
1256 		       NEXT_ORPHAN(inode));
1257 		printk(KERN_ERR "max_ino=%lu\n", max_ino);
1258 		printk(KERN_ERR "i_nlink=%u\n", inode->i_nlink);
1259 		/* Avoid freeing blocks if we got a bad deleted inode */
1260 		if (inode->i_nlink == 0)
1261 			inode->i_blocks = 0;
1262 		iput(inode);
1263 	}
1264 	brelse(bitmap_bh);
1265 	return ERR_PTR(err);
1266 }
1267 
1268 unsigned long ext4_count_free_inodes(struct super_block *sb)
1269 {
1270 	unsigned long desc_count;
1271 	struct ext4_group_desc *gdp;
1272 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
1273 #ifdef EXT4FS_DEBUG
1274 	struct ext4_super_block *es;
1275 	unsigned long bitmap_count, x;
1276 	struct buffer_head *bitmap_bh = NULL;
1277 
1278 	es = EXT4_SB(sb)->s_es;
1279 	desc_count = 0;
1280 	bitmap_count = 0;
1281 	gdp = NULL;
1282 	for (i = 0; i < ngroups; i++) {
1283 		gdp = ext4_get_group_desc(sb, i, NULL);
1284 		if (!gdp)
1285 			continue;
1286 		desc_count += ext4_free_inodes_count(sb, gdp);
1287 		brelse(bitmap_bh);
1288 		bitmap_bh = ext4_read_inode_bitmap(sb, i);
1289 		if (IS_ERR(bitmap_bh)) {
1290 			bitmap_bh = NULL;
1291 			continue;
1292 		}
1293 
1294 		x = ext4_count_free(bitmap_bh->b_data,
1295 				    EXT4_INODES_PER_GROUP(sb) / 8);
1296 		printk(KERN_DEBUG "group %lu: stored = %d, counted = %lu\n",
1297 			(unsigned long) i, ext4_free_inodes_count(sb, gdp), x);
1298 		bitmap_count += x;
1299 	}
1300 	brelse(bitmap_bh);
1301 	printk(KERN_DEBUG "ext4_count_free_inodes: "
1302 	       "stored = %u, computed = %lu, %lu\n",
1303 	       le32_to_cpu(es->s_free_inodes_count), desc_count, bitmap_count);
1304 	return desc_count;
1305 #else
1306 	desc_count = 0;
1307 	for (i = 0; i < ngroups; i++) {
1308 		gdp = ext4_get_group_desc(sb, i, NULL);
1309 		if (!gdp)
1310 			continue;
1311 		desc_count += ext4_free_inodes_count(sb, gdp);
1312 		cond_resched();
1313 	}
1314 	return desc_count;
1315 #endif
1316 }
1317 
1318 /* Called at mount-time, super-block is locked */
1319 unsigned long ext4_count_dirs(struct super_block * sb)
1320 {
1321 	unsigned long count = 0;
1322 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
1323 
1324 	for (i = 0; i < ngroups; i++) {
1325 		struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
1326 		if (!gdp)
1327 			continue;
1328 		count += ext4_used_dirs_count(sb, gdp);
1329 	}
1330 	return count;
1331 }
1332 
1333 /*
1334  * Zeroes not yet zeroed inode table - just write zeroes through the whole
1335  * inode table. Must be called without any spinlock held. The only place
1336  * where it is called from on active part of filesystem is ext4lazyinit
1337  * thread, so we do not need any special locks, however we have to prevent
1338  * inode allocation from the current group, so we take alloc_sem lock, to
1339  * block ext4_new_inode() until we are finished.
1340  */
1341 int ext4_init_inode_table(struct super_block *sb, ext4_group_t group,
1342 				 int barrier)
1343 {
1344 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
1345 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1346 	struct ext4_group_desc *gdp = NULL;
1347 	struct buffer_head *group_desc_bh;
1348 	handle_t *handle;
1349 	ext4_fsblk_t blk;
1350 	int num, ret = 0, used_blks = 0;
1351 
1352 	/* This should not happen, but just to be sure check this */
1353 	if (sb_rdonly(sb)) {
1354 		ret = 1;
1355 		goto out;
1356 	}
1357 
1358 	gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
1359 	if (!gdp)
1360 		goto out;
1361 
1362 	/*
1363 	 * We do not need to lock this, because we are the only one
1364 	 * handling this flag.
1365 	 */
1366 	if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED))
1367 		goto out;
1368 
1369 	handle = ext4_journal_start_sb(sb, EXT4_HT_MISC, 1);
1370 	if (IS_ERR(handle)) {
1371 		ret = PTR_ERR(handle);
1372 		goto out;
1373 	}
1374 
1375 	down_write(&grp->alloc_sem);
1376 	/*
1377 	 * If inode bitmap was already initialized there may be some
1378 	 * used inodes so we need to skip blocks with used inodes in
1379 	 * inode table.
1380 	 */
1381 	if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)))
1382 		used_blks = DIV_ROUND_UP((EXT4_INODES_PER_GROUP(sb) -
1383 			    ext4_itable_unused_count(sb, gdp)),
1384 			    sbi->s_inodes_per_block);
1385 
1386 	if ((used_blks < 0) || (used_blks > sbi->s_itb_per_group) ||
1387 	    ((group == 0) && ((EXT4_INODES_PER_GROUP(sb) -
1388 			       ext4_itable_unused_count(sb, gdp)) <
1389 			      EXT4_FIRST_INO(sb)))) {
1390 		ext4_error(sb, "Something is wrong with group %u: "
1391 			   "used itable blocks: %d; "
1392 			   "itable unused count: %u",
1393 			   group, used_blks,
1394 			   ext4_itable_unused_count(sb, gdp));
1395 		ret = 1;
1396 		goto err_out;
1397 	}
1398 
1399 	blk = ext4_inode_table(sb, gdp) + used_blks;
1400 	num = sbi->s_itb_per_group - used_blks;
1401 
1402 	BUFFER_TRACE(group_desc_bh, "get_write_access");
1403 	ret = ext4_journal_get_write_access(handle,
1404 					    group_desc_bh);
1405 	if (ret)
1406 		goto err_out;
1407 
1408 	/*
1409 	 * Skip zeroout if the inode table is full. But we set the ZEROED
1410 	 * flag anyway, because obviously, when it is full it does not need
1411 	 * further zeroing.
1412 	 */
1413 	if (unlikely(num == 0))
1414 		goto skip_zeroout;
1415 
1416 	ext4_debug("going to zero out inode table in group %d\n",
1417 		   group);
1418 	ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS);
1419 	if (ret < 0)
1420 		goto err_out;
1421 	if (barrier)
1422 		blkdev_issue_flush(sb->s_bdev, GFP_NOFS, NULL);
1423 
1424 skip_zeroout:
1425 	ext4_lock_group(sb, group);
1426 	gdp->bg_flags |= cpu_to_le16(EXT4_BG_INODE_ZEROED);
1427 	ext4_group_desc_csum_set(sb, group, gdp);
1428 	ext4_unlock_group(sb, group);
1429 
1430 	BUFFER_TRACE(group_desc_bh,
1431 		     "call ext4_handle_dirty_metadata");
1432 	ret = ext4_handle_dirty_metadata(handle, NULL,
1433 					 group_desc_bh);
1434 
1435 err_out:
1436 	up_write(&grp->alloc_sem);
1437 	ext4_journal_stop(handle);
1438 out:
1439 	return ret;
1440 }
1441