xref: /linux/fs/ext4/ialloc.c (revision 8016e29f4362e285f0f7e38fadc61a5b7bdfdfa2)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2ac27a0ecSDave Kleikamp /*
3617ba13bSMingming Cao  *  linux/fs/ext4/ialloc.c
4ac27a0ecSDave Kleikamp  *
5ac27a0ecSDave Kleikamp  * Copyright (C) 1992, 1993, 1994, 1995
6ac27a0ecSDave Kleikamp  * Remy Card (card@masi.ibp.fr)
7ac27a0ecSDave Kleikamp  * Laboratoire MASI - Institut Blaise Pascal
8ac27a0ecSDave Kleikamp  * Universite Pierre et Marie Curie (Paris VI)
9ac27a0ecSDave Kleikamp  *
10ac27a0ecSDave Kleikamp  *  BSD ufs-inspired inode and directory allocation by
11ac27a0ecSDave Kleikamp  *  Stephen Tweedie (sct@redhat.com), 1993
12ac27a0ecSDave Kleikamp  *  Big-endian to little-endian byte-swapping/bitmaps by
13ac27a0ecSDave Kleikamp  *        David S. Miller (davem@caip.rutgers.edu), 1995
14ac27a0ecSDave Kleikamp  */
15ac27a0ecSDave Kleikamp 
16ac27a0ecSDave Kleikamp #include <linux/time.h>
17ac27a0ecSDave Kleikamp #include <linux/fs.h>
18ac27a0ecSDave Kleikamp #include <linux/stat.h>
19ac27a0ecSDave Kleikamp #include <linux/string.h>
20ac27a0ecSDave Kleikamp #include <linux/quotaops.h>
21ac27a0ecSDave Kleikamp #include <linux/buffer_head.h>
22ac27a0ecSDave Kleikamp #include <linux/random.h>
23ac27a0ecSDave Kleikamp #include <linux/bitops.h>
243a5b2ecdSMingming Cao #include <linux/blkdev.h>
255b825c3aSIngo Molnar #include <linux/cred.h>
265b825c3aSIngo Molnar 
27ac27a0ecSDave Kleikamp #include <asm/byteorder.h>
289bffad1eSTheodore Ts'o 
293dcf5451SChristoph Hellwig #include "ext4.h"
303dcf5451SChristoph Hellwig #include "ext4_jbd2.h"
31ac27a0ecSDave Kleikamp #include "xattr.h"
32ac27a0ecSDave Kleikamp #include "acl.h"
33ac27a0ecSDave Kleikamp 
349bffad1eSTheodore Ts'o #include <trace/events/ext4.h>
359bffad1eSTheodore Ts'o 
36ac27a0ecSDave Kleikamp /*
37ac27a0ecSDave Kleikamp  * ialloc.c contains the inodes allocation and deallocation routines
38ac27a0ecSDave Kleikamp  */
39ac27a0ecSDave Kleikamp 
40ac27a0ecSDave Kleikamp /*
41ac27a0ecSDave Kleikamp  * The free inodes are managed by bitmaps.  A file system contains several
42ac27a0ecSDave Kleikamp  * blocks groups.  Each group contains 1 bitmap block for blocks, 1 bitmap
43ac27a0ecSDave Kleikamp  * block for inodes, N blocks for the inode table and data blocks.
44ac27a0ecSDave Kleikamp  *
45ac27a0ecSDave Kleikamp  * The file system contains group descriptors which are located after the
46ac27a0ecSDave Kleikamp  * super block.  Each descriptor contains the number of the bitmap block and
47ac27a0ecSDave Kleikamp  * the free blocks count in the block.
48ac27a0ecSDave Kleikamp  */
49ac27a0ecSDave Kleikamp 
50717d50e4SAndreas Dilger /*
51717d50e4SAndreas Dilger  * To avoid calling the atomic setbit hundreds or thousands of times, we only
52717d50e4SAndreas Dilger  * need to use it within a single byte (to ensure we get endianness right).
53717d50e4SAndreas Dilger  * We can use memset for the rest of the bitmap as there are no other users.
54717d50e4SAndreas Dilger  */
5561d08673STheodore Ts'o void ext4_mark_bitmap_end(int start_bit, int end_bit, char *bitmap)
56717d50e4SAndreas Dilger {
57717d50e4SAndreas Dilger 	int i;
58717d50e4SAndreas Dilger 
59717d50e4SAndreas Dilger 	if (start_bit >= end_bit)
60717d50e4SAndreas Dilger 		return;
61717d50e4SAndreas Dilger 
62717d50e4SAndreas Dilger 	ext4_debug("mark end bits +%d through +%d used\n", start_bit, end_bit);
63717d50e4SAndreas Dilger 	for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
64717d50e4SAndreas Dilger 		ext4_set_bit(i, bitmap);
65717d50e4SAndreas Dilger 	if (i < end_bit)
66717d50e4SAndreas Dilger 		memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
67717d50e4SAndreas Dilger }
68717d50e4SAndreas Dilger 
69813e5727STheodore Ts'o void ext4_end_bitmap_read(struct buffer_head *bh, int uptodate)
70813e5727STheodore Ts'o {
71813e5727STheodore Ts'o 	if (uptodate) {
72813e5727STheodore Ts'o 		set_buffer_uptodate(bh);
73813e5727STheodore Ts'o 		set_bitmap_uptodate(bh);
74813e5727STheodore Ts'o 	}
75813e5727STheodore Ts'o 	unlock_buffer(bh);
76813e5727STheodore Ts'o 	put_bh(bh);
77813e5727STheodore Ts'o }
78813e5727STheodore Ts'o 
799008a58eSDarrick J. Wong static int ext4_validate_inode_bitmap(struct super_block *sb,
809008a58eSDarrick J. Wong 				      struct ext4_group_desc *desc,
819008a58eSDarrick J. Wong 				      ext4_group_t block_group,
829008a58eSDarrick J. Wong 				      struct buffer_head *bh)
839008a58eSDarrick J. Wong {
849008a58eSDarrick J. Wong 	ext4_fsblk_t	blk;
85*8016e29fSHarshad Shirwadkar 	struct ext4_group_info *grp;
86*8016e29fSHarshad Shirwadkar 
87*8016e29fSHarshad Shirwadkar 	if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
88*8016e29fSHarshad Shirwadkar 		return 0;
89*8016e29fSHarshad Shirwadkar 
90*8016e29fSHarshad Shirwadkar 	grp = ext4_get_group_info(sb, block_group);
919008a58eSDarrick J. Wong 
929008a58eSDarrick J. Wong 	if (buffer_verified(bh))
939008a58eSDarrick J. Wong 		return 0;
949008a58eSDarrick J. Wong 	if (EXT4_MB_GRP_IBITMAP_CORRUPT(grp))
959008a58eSDarrick J. Wong 		return -EFSCORRUPTED;
969008a58eSDarrick J. Wong 
979008a58eSDarrick J. Wong 	ext4_lock_group(sb, block_group);
988d5a803cSTheodore Ts'o 	if (buffer_verified(bh))
998d5a803cSTheodore Ts'o 		goto verified;
1009008a58eSDarrick J. Wong 	blk = ext4_inode_bitmap(sb, desc);
1019008a58eSDarrick J. Wong 	if (!ext4_inode_bitmap_csum_verify(sb, block_group, desc, bh,
10246f870d6STheodore Ts'o 					   EXT4_INODES_PER_GROUP(sb) / 8) ||
10346f870d6STheodore Ts'o 	    ext4_simulate_fail(sb, EXT4_SIM_IBITMAP_CRC)) {
1049008a58eSDarrick J. Wong 		ext4_unlock_group(sb, block_group);
1059008a58eSDarrick J. Wong 		ext4_error(sb, "Corrupt inode bitmap - block_group = %u, "
1069008a58eSDarrick J. Wong 			   "inode_bitmap = %llu", block_group, blk);
107db79e6d1SWang Shilong 		ext4_mark_group_bitmap_corrupted(sb, block_group,
108db79e6d1SWang Shilong 					EXT4_GROUP_INFO_IBITMAP_CORRUPT);
1099008a58eSDarrick J. Wong 		return -EFSBADCRC;
1109008a58eSDarrick J. Wong 	}
1119008a58eSDarrick J. Wong 	set_buffer_verified(bh);
1128d5a803cSTheodore Ts'o verified:
1139008a58eSDarrick J. Wong 	ext4_unlock_group(sb, block_group);
1149008a58eSDarrick J. Wong 	return 0;
1159008a58eSDarrick J. Wong }
1169008a58eSDarrick J. Wong 
117ac27a0ecSDave Kleikamp /*
118ac27a0ecSDave Kleikamp  * Read the inode allocation bitmap for a given block_group, reading
119ac27a0ecSDave Kleikamp  * into the specified slot in the superblock's bitmap cache.
120ac27a0ecSDave Kleikamp  *
1219033783cSJosh Triplett  * Return buffer_head of bitmap on success, or an ERR_PTR on error.
122ac27a0ecSDave Kleikamp  */
123ac27a0ecSDave Kleikamp static struct buffer_head *
124e29d1cdeSEric Sandeen ext4_read_inode_bitmap(struct super_block *sb, ext4_group_t block_group)
125ac27a0ecSDave Kleikamp {
126617ba13bSMingming Cao 	struct ext4_group_desc *desc;
1277dac4a17STheodore Ts'o 	struct ext4_sb_info *sbi = EXT4_SB(sb);
128ac27a0ecSDave Kleikamp 	struct buffer_head *bh = NULL;
129e29d1cdeSEric Sandeen 	ext4_fsblk_t bitmap_blk;
1309008a58eSDarrick J. Wong 	int err;
131ac27a0ecSDave Kleikamp 
132617ba13bSMingming Cao 	desc = ext4_get_group_desc(sb, block_group, NULL);
133ac27a0ecSDave Kleikamp 	if (!desc)
1349008a58eSDarrick J. Wong 		return ERR_PTR(-EFSCORRUPTED);
135bfff6873SLukas Czerner 
136e29d1cdeSEric Sandeen 	bitmap_blk = ext4_inode_bitmap(sb, desc);
1377dac4a17STheodore Ts'o 	if ((bitmap_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
1387dac4a17STheodore Ts'o 	    (bitmap_blk >= ext4_blocks_count(sbi->s_es))) {
1397dac4a17STheodore Ts'o 		ext4_error(sb, "Invalid inode bitmap blk %llu in "
1407dac4a17STheodore Ts'o 			   "block_group %u", bitmap_blk, block_group);
141206f6d55SWang Shilong 		ext4_mark_group_bitmap_corrupted(sb, block_group,
142206f6d55SWang Shilong 					EXT4_GROUP_INFO_IBITMAP_CORRUPT);
1437dac4a17STheodore Ts'o 		return ERR_PTR(-EFSCORRUPTED);
1447dac4a17STheodore Ts'o 	}
145e29d1cdeSEric Sandeen 	bh = sb_getblk(sb, bitmap_blk);
146e29d1cdeSEric Sandeen 	if (unlikely(!bh)) {
1475ef2a699SWang Shilong 		ext4_warning(sb, "Cannot read inode bitmap - "
148a9df9a49STheodore Ts'o 			     "block_group = %u, inode_bitmap = %llu",
149e29d1cdeSEric Sandeen 			     block_group, bitmap_blk);
1500db9fdebSWang Shilong 		return ERR_PTR(-ENOMEM);
151e29d1cdeSEric Sandeen 	}
1522ccb5fb9SAneesh Kumar K.V 	if (bitmap_uptodate(bh))
15341a246d1SDarrick J. Wong 		goto verify;
154e29d1cdeSEric Sandeen 
155c806e68fSFrederic Bohe 	lock_buffer(bh);
1562ccb5fb9SAneesh Kumar K.V 	if (bitmap_uptodate(bh)) {
1572ccb5fb9SAneesh Kumar K.V 		unlock_buffer(bh);
15841a246d1SDarrick J. Wong 		goto verify;
1592ccb5fb9SAneesh Kumar K.V 	}
160bfff6873SLukas Czerner 
161955ce5f5SAneesh Kumar K.V 	ext4_lock_group(sb, block_group);
1628844618dSTheodore Ts'o 	if (ext4_has_group_desc_csum(sb) &&
1638844618dSTheodore Ts'o 	    (desc->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT))) {
1648844618dSTheodore Ts'o 		if (block_group == 0) {
1658844618dSTheodore Ts'o 			ext4_unlock_group(sb, block_group);
1668844618dSTheodore Ts'o 			unlock_buffer(bh);
1678844618dSTheodore Ts'o 			ext4_error(sb, "Inode bitmap for bg 0 marked "
1688844618dSTheodore Ts'o 				   "uninitialized");
1698844618dSTheodore Ts'o 			err = -EFSCORRUPTED;
1708844618dSTheodore Ts'o 			goto out;
1718844618dSTheodore Ts'o 		}
172044e6e3dSTheodore Ts'o 		memset(bh->b_data, 0, (EXT4_INODES_PER_GROUP(sb) + 7) / 8);
173044e6e3dSTheodore Ts'o 		ext4_mark_bitmap_end(EXT4_INODES_PER_GROUP(sb),
174044e6e3dSTheodore Ts'o 				     sb->s_blocksize * 8, bh->b_data);
1752ccb5fb9SAneesh Kumar K.V 		set_bitmap_uptodate(bh);
176e29d1cdeSEric Sandeen 		set_buffer_uptodate(bh);
17741a246d1SDarrick J. Wong 		set_buffer_verified(bh);
178955ce5f5SAneesh Kumar K.V 		ext4_unlock_group(sb, block_group);
1793300bedaSAneesh Kumar K.V 		unlock_buffer(bh);
180e29d1cdeSEric Sandeen 		return bh;
181e29d1cdeSEric Sandeen 	}
182955ce5f5SAneesh Kumar K.V 	ext4_unlock_group(sb, block_group);
183bfff6873SLukas Czerner 
1842ccb5fb9SAneesh Kumar K.V 	if (buffer_uptodate(bh)) {
1852ccb5fb9SAneesh Kumar K.V 		/*
1862ccb5fb9SAneesh Kumar K.V 		 * if not uninit if bh is uptodate,
1872ccb5fb9SAneesh Kumar K.V 		 * bitmap is also uptodate
1882ccb5fb9SAneesh Kumar K.V 		 */
1892ccb5fb9SAneesh Kumar K.V 		set_bitmap_uptodate(bh);
1902ccb5fb9SAneesh Kumar K.V 		unlock_buffer(bh);
19141a246d1SDarrick J. Wong 		goto verify;
1922ccb5fb9SAneesh Kumar K.V 	}
1932ccb5fb9SAneesh Kumar K.V 	/*
194813e5727STheodore Ts'o 	 * submit the buffer_head for reading
1952ccb5fb9SAneesh Kumar K.V 	 */
1960562e0baSJiaying Zhang 	trace_ext4_load_inode_bitmap(sb, block_group);
1972d069c08Szhangyi (F) 	ext4_read_bh(bh, REQ_META | REQ_PRIO, ext4_end_bitmap_read);
19846f870d6STheodore Ts'o 	ext4_simulate_fail_bh(sb, bh, EXT4_SIM_IBITMAP_EIO);
199813e5727STheodore Ts'o 	if (!buffer_uptodate(bh)) {
200e29d1cdeSEric Sandeen 		put_bh(bh);
20154d3adbcSTheodore Ts'o 		ext4_error_err(sb, EIO, "Cannot read inode bitmap - "
202a9df9a49STheodore Ts'o 			       "block_group = %u, inode_bitmap = %llu",
203e29d1cdeSEric Sandeen 			       block_group, bitmap_blk);
204206f6d55SWang Shilong 		ext4_mark_group_bitmap_corrupted(sb, block_group,
205206f6d55SWang Shilong 				EXT4_GROUP_INFO_IBITMAP_CORRUPT);
2069008a58eSDarrick J. Wong 		return ERR_PTR(-EIO);
207e29d1cdeSEric Sandeen 	}
20841a246d1SDarrick J. Wong 
20941a246d1SDarrick J. Wong verify:
2109008a58eSDarrick J. Wong 	err = ext4_validate_inode_bitmap(sb, desc, block_group, bh);
2119008a58eSDarrick J. Wong 	if (err)
2129008a58eSDarrick J. Wong 		goto out;
213ac27a0ecSDave Kleikamp 	return bh;
2149008a58eSDarrick J. Wong out:
2159008a58eSDarrick J. Wong 	put_bh(bh);
2169008a58eSDarrick J. Wong 	return ERR_PTR(err);
217ac27a0ecSDave Kleikamp }
218ac27a0ecSDave Kleikamp 
219ac27a0ecSDave Kleikamp /*
220ac27a0ecSDave Kleikamp  * NOTE! When we get the inode, we're the only people
221ac27a0ecSDave Kleikamp  * that have access to it, and as such there are no
222ac27a0ecSDave Kleikamp  * race conditions we have to worry about. The inode
223ac27a0ecSDave Kleikamp  * is not on the hash-lists, and it cannot be reached
224ac27a0ecSDave Kleikamp  * through the filesystem because the directory entry
225ac27a0ecSDave Kleikamp  * has been deleted earlier.
226ac27a0ecSDave Kleikamp  *
227ac27a0ecSDave Kleikamp  * HOWEVER: we must make sure that we get no aliases,
228ac27a0ecSDave Kleikamp  * which means that we have to call "clear_inode()"
229ac27a0ecSDave Kleikamp  * _before_ we mark the inode not in use in the inode
230ac27a0ecSDave Kleikamp  * bitmaps. Otherwise a newly created file might use
231ac27a0ecSDave Kleikamp  * the same inode number (not actually the same pointer
232ac27a0ecSDave Kleikamp  * though), and then we'd have two inodes sharing the
233ac27a0ecSDave Kleikamp  * same inode number and space on the harddisk.
234ac27a0ecSDave Kleikamp  */
235617ba13bSMingming Cao void ext4_free_inode(handle_t *handle, struct inode *inode)
236ac27a0ecSDave Kleikamp {
237ac27a0ecSDave Kleikamp 	struct super_block *sb = inode->i_sb;
238ac27a0ecSDave Kleikamp 	int is_directory;
239ac27a0ecSDave Kleikamp 	unsigned long ino;
240ac27a0ecSDave Kleikamp 	struct buffer_head *bitmap_bh = NULL;
241ac27a0ecSDave Kleikamp 	struct buffer_head *bh2;
242fd2d4291SAvantika Mathur 	ext4_group_t block_group;
243ac27a0ecSDave Kleikamp 	unsigned long bit;
244617ba13bSMingming Cao 	struct ext4_group_desc *gdp;
245617ba13bSMingming Cao 	struct ext4_super_block *es;
246617ba13bSMingming Cao 	struct ext4_sb_info *sbi;
2477ce9d5d1SEric Sandeen 	int fatal = 0, err, count, cleared;
24887a39389SDarrick J. Wong 	struct ext4_group_info *grp;
249ac27a0ecSDave Kleikamp 
25092b97816STheodore Ts'o 	if (!sb) {
25192b97816STheodore Ts'o 		printk(KERN_ERR "EXT4-fs: %s:%d: inode on "
25292b97816STheodore Ts'o 		       "nonexistent device\n", __func__, __LINE__);
25392b97816STheodore Ts'o 		return;
25492b97816STheodore Ts'o 	}
255ac27a0ecSDave Kleikamp 	if (atomic_read(&inode->i_count) > 1) {
25692b97816STheodore Ts'o 		ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: count=%d",
25792b97816STheodore Ts'o 			 __func__, __LINE__, inode->i_ino,
258ac27a0ecSDave Kleikamp 			 atomic_read(&inode->i_count));
259ac27a0ecSDave Kleikamp 		return;
260ac27a0ecSDave Kleikamp 	}
261ac27a0ecSDave Kleikamp 	if (inode->i_nlink) {
26292b97816STheodore Ts'o 		ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: nlink=%d\n",
26392b97816STheodore Ts'o 			 __func__, __LINE__, inode->i_ino, inode->i_nlink);
264ac27a0ecSDave Kleikamp 		return;
265ac27a0ecSDave Kleikamp 	}
266617ba13bSMingming Cao 	sbi = EXT4_SB(sb);
267ac27a0ecSDave Kleikamp 
268ac27a0ecSDave Kleikamp 	ino = inode->i_ino;
269617ba13bSMingming Cao 	ext4_debug("freeing inode %lu\n", ino);
2709bffad1eSTheodore Ts'o 	trace_ext4_free_inode(inode);
271ac27a0ecSDave Kleikamp 
272871a2931SChristoph Hellwig 	dquot_initialize(inode);
27363936ddaSChristoph Hellwig 	dquot_free_inode(inode);
274ac27a0ecSDave Kleikamp 
275ac27a0ecSDave Kleikamp 	is_directory = S_ISDIR(inode->i_mode);
276ac27a0ecSDave Kleikamp 
277ac27a0ecSDave Kleikamp 	/* Do this BEFORE marking the inode not in use or returning an error */
2780930fcc1SAl Viro 	ext4_clear_inode(inode);
279ac27a0ecSDave Kleikamp 
28049598e04SJun Piao 	es = sbi->s_es;
281617ba13bSMingming Cao 	if (ino < EXT4_FIRST_INO(sb) || ino > le32_to_cpu(es->s_inodes_count)) {
28212062dddSEric Sandeen 		ext4_error(sb, "reserved or nonexistent inode %lu", ino);
283ac27a0ecSDave Kleikamp 		goto error_return;
284ac27a0ecSDave Kleikamp 	}
285617ba13bSMingming Cao 	block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
286617ba13bSMingming Cao 	bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
287e29d1cdeSEric Sandeen 	bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
28887a39389SDarrick J. Wong 	/* Don't bother if the inode bitmap is corrupt. */
2899008a58eSDarrick J. Wong 	if (IS_ERR(bitmap_bh)) {
2909008a58eSDarrick J. Wong 		fatal = PTR_ERR(bitmap_bh);
2919008a58eSDarrick J. Wong 		bitmap_bh = NULL;
292ac27a0ecSDave Kleikamp 		goto error_return;
2939008a58eSDarrick J. Wong 	}
294*8016e29fSHarshad Shirwadkar 	if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
295*8016e29fSHarshad Shirwadkar 		grp = ext4_get_group_info(sb, block_group);
2969008a58eSDarrick J. Wong 		if (unlikely(EXT4_MB_GRP_IBITMAP_CORRUPT(grp))) {
2979008a58eSDarrick J. Wong 			fatal = -EFSCORRUPTED;
2989008a58eSDarrick J. Wong 			goto error_return;
2999008a58eSDarrick J. Wong 		}
300*8016e29fSHarshad Shirwadkar 	}
301ac27a0ecSDave Kleikamp 
302ac27a0ecSDave Kleikamp 	BUFFER_TRACE(bitmap_bh, "get_write_access");
303617ba13bSMingming Cao 	fatal = ext4_journal_get_write_access(handle, bitmap_bh);
304ac27a0ecSDave Kleikamp 	if (fatal)
305ac27a0ecSDave Kleikamp 		goto error_return;
306ac27a0ecSDave Kleikamp 
307d17413c0SDmitry Monakhov 	fatal = -ESRCH;
308617ba13bSMingming Cao 	gdp = ext4_get_group_desc(sb, block_group, &bh2);
309d17413c0SDmitry Monakhov 	if (gdp) {
310ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh2, "get_write_access");
311617ba13bSMingming Cao 		fatal = ext4_journal_get_write_access(handle, bh2);
312d17413c0SDmitry Monakhov 	}
313955ce5f5SAneesh Kumar K.V 	ext4_lock_group(sb, block_group);
314597d508cSAkinobu Mita 	cleared = ext4_test_and_clear_bit(bit, bitmap_bh->b_data);
315d17413c0SDmitry Monakhov 	if (fatal || !cleared) {
316d17413c0SDmitry Monakhov 		ext4_unlock_group(sb, block_group);
317d17413c0SDmitry Monakhov 		goto out;
318d17413c0SDmitry Monakhov 	}
319d17413c0SDmitry Monakhov 
320560671a0SAneesh Kumar K.V 	count = ext4_free_inodes_count(sb, gdp) + 1;
321560671a0SAneesh Kumar K.V 	ext4_free_inodes_set(sb, gdp, count);
322560671a0SAneesh Kumar K.V 	if (is_directory) {
323560671a0SAneesh Kumar K.V 		count = ext4_used_dirs_count(sb, gdp) - 1;
324560671a0SAneesh Kumar K.V 		ext4_used_dirs_set(sb, gdp, count);
325d17413c0SDmitry Monakhov 		percpu_counter_dec(&sbi->s_dirs_counter);
326d17413c0SDmitry Monakhov 	}
32741a246d1SDarrick J. Wong 	ext4_inode_bitmap_csum_set(sb, block_group, gdp, bitmap_bh,
32841a246d1SDarrick J. Wong 				   EXT4_INODES_PER_GROUP(sb) / 8);
329feb0ab32SDarrick J. Wong 	ext4_group_desc_csum_set(sb, block_group, gdp);
330d17413c0SDmitry Monakhov 	ext4_unlock_group(sb, block_group);
3317d39db14STheodore Ts'o 
332d17413c0SDmitry Monakhov 	percpu_counter_inc(&sbi->s_freeinodes_counter);
333d17413c0SDmitry Monakhov 	if (sbi->s_log_groups_per_flex) {
3347c990728SSuraj Jitindar Singh 		struct flex_groups *fg;
335d17413c0SDmitry Monakhov 
3367c990728SSuraj Jitindar Singh 		fg = sbi_array_rcu_deref(sbi, s_flex_groups,
3377c990728SSuraj Jitindar Singh 					 ext4_flex_group(sbi, block_group));
3387c990728SSuraj Jitindar Singh 		atomic_inc(&fg->free_inodes);
339d17413c0SDmitry Monakhov 		if (is_directory)
3407c990728SSuraj Jitindar Singh 			atomic_dec(&fg->used_dirs);
3417d39db14STheodore Ts'o 	}
3420390131bSFrank Mayhar 	BUFFER_TRACE(bh2, "call ext4_handle_dirty_metadata");
343d17413c0SDmitry Monakhov 	fatal = ext4_handle_dirty_metadata(handle, NULL, bh2);
344d17413c0SDmitry Monakhov out:
345d17413c0SDmitry Monakhov 	if (cleared) {
3460390131bSFrank Mayhar 		BUFFER_TRACE(bitmap_bh, "call ext4_handle_dirty_metadata");
3470390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
348ac27a0ecSDave Kleikamp 		if (!fatal)
349ac27a0ecSDave Kleikamp 			fatal = err;
35087a39389SDarrick J. Wong 	} else {
351d17413c0SDmitry Monakhov 		ext4_error(sb, "bit already cleared for inode %lu", ino);
352db79e6d1SWang Shilong 		ext4_mark_group_bitmap_corrupted(sb, block_group,
353db79e6d1SWang Shilong 					EXT4_GROUP_INFO_IBITMAP_CORRUPT);
35487a39389SDarrick J. Wong 	}
355d17413c0SDmitry Monakhov 
356ac27a0ecSDave Kleikamp error_return:
357ac27a0ecSDave Kleikamp 	brelse(bitmap_bh);
358617ba13bSMingming Cao 	ext4_std_error(sb, fatal);
359ac27a0ecSDave Kleikamp }
360ac27a0ecSDave Kleikamp 
361a4912123STheodore Ts'o struct orlov_stats {
36290ba983fSTheodore Ts'o 	__u64 free_clusters;
363a4912123STheodore Ts'o 	__u32 free_inodes;
364a4912123STheodore Ts'o 	__u32 used_dirs;
365a4912123STheodore Ts'o };
366a4912123STheodore Ts'o 
367a4912123STheodore Ts'o /*
368a4912123STheodore Ts'o  * Helper function for Orlov's allocator; returns critical information
369a4912123STheodore Ts'o  * for a particular block group or flex_bg.  If flex_size is 1, then g
370a4912123STheodore Ts'o  * is a block group number; otherwise it is flex_bg number.
371a4912123STheodore Ts'o  */
3721f109d5aSTheodore Ts'o static void get_orlov_stats(struct super_block *sb, ext4_group_t g,
373a4912123STheodore Ts'o 			    int flex_size, struct orlov_stats *stats)
374a4912123STheodore Ts'o {
375a4912123STheodore Ts'o 	struct ext4_group_desc *desc;
376a4912123STheodore Ts'o 
3777d39db14STheodore Ts'o 	if (flex_size > 1) {
3787c990728SSuraj Jitindar Singh 		struct flex_groups *fg = sbi_array_rcu_deref(EXT4_SB(sb),
3797c990728SSuraj Jitindar Singh 							     s_flex_groups, g);
3807c990728SSuraj Jitindar Singh 		stats->free_inodes = atomic_read(&fg->free_inodes);
3817c990728SSuraj Jitindar Singh 		stats->free_clusters = atomic64_read(&fg->free_clusters);
3827c990728SSuraj Jitindar Singh 		stats->used_dirs = atomic_read(&fg->used_dirs);
3837d39db14STheodore Ts'o 		return;
3847d39db14STheodore Ts'o 	}
3857d39db14STheodore Ts'o 
3867d39db14STheodore Ts'o 	desc = ext4_get_group_desc(sb, g, NULL);
3877d39db14STheodore Ts'o 	if (desc) {
3887d39db14STheodore Ts'o 		stats->free_inodes = ext4_free_inodes_count(sb, desc);
389021b65bbSTheodore Ts'o 		stats->free_clusters = ext4_free_group_clusters(sb, desc);
3907d39db14STheodore Ts'o 		stats->used_dirs = ext4_used_dirs_count(sb, desc);
3917d39db14STheodore Ts'o 	} else {
392a4912123STheodore Ts'o 		stats->free_inodes = 0;
39324aaa8efSTheodore Ts'o 		stats->free_clusters = 0;
394a4912123STheodore Ts'o 		stats->used_dirs = 0;
395a4912123STheodore Ts'o 	}
396a4912123STheodore Ts'o }
397a4912123STheodore Ts'o 
398ac27a0ecSDave Kleikamp /*
399ac27a0ecSDave Kleikamp  * Orlov's allocator for directories.
400ac27a0ecSDave Kleikamp  *
401ac27a0ecSDave Kleikamp  * We always try to spread first-level directories.
402ac27a0ecSDave Kleikamp  *
403ac27a0ecSDave Kleikamp  * If there are blockgroups with both free inodes and free blocks counts
404ac27a0ecSDave Kleikamp  * not worse than average we return one with smallest directory count.
405ac27a0ecSDave Kleikamp  * Otherwise we simply return a random group.
406ac27a0ecSDave Kleikamp  *
407ac27a0ecSDave Kleikamp  * For the rest rules look so:
408ac27a0ecSDave Kleikamp  *
409ac27a0ecSDave Kleikamp  * It's OK to put directory into a group unless
410ac27a0ecSDave Kleikamp  * it has too many directories already (max_dirs) or
411ac27a0ecSDave Kleikamp  * it has too few free inodes left (min_inodes) or
412ac27a0ecSDave Kleikamp  * it has too few free blocks left (min_blocks) or
4131cc8dcf5SBenoit Boissinot  * Parent's group is preferred, if it doesn't satisfy these
414ac27a0ecSDave Kleikamp  * conditions we search cyclically through the rest. If none
415ac27a0ecSDave Kleikamp  * of the groups look good we just look for a group with more
416ac27a0ecSDave Kleikamp  * free inodes than average (starting at parent's group).
417ac27a0ecSDave Kleikamp  */
418ac27a0ecSDave Kleikamp 
4192aa9fc4cSAvantika Mathur static int find_group_orlov(struct super_block *sb, struct inode *parent,
420dcca3fecSAl Viro 			    ext4_group_t *group, umode_t mode,
421f157a4aaSTheodore Ts'o 			    const struct qstr *qstr)
422ac27a0ecSDave Kleikamp {
423fd2d4291SAvantika Mathur 	ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
424617ba13bSMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(sb);
4258df9675fSTheodore Ts'o 	ext4_group_t real_ngroups = ext4_get_groups_count(sb);
426617ba13bSMingming Cao 	int inodes_per_group = EXT4_INODES_PER_GROUP(sb);
42714c83c9fSTheodore Ts'o 	unsigned int freei, avefreei, grp_free;
42824aaa8efSTheodore Ts'o 	ext4_fsblk_t freeb, avefreec;
429ac27a0ecSDave Kleikamp 	unsigned int ndirs;
430a4912123STheodore Ts'o 	int max_dirs, min_inodes;
43124aaa8efSTheodore Ts'o 	ext4_grpblk_t min_clusters;
4328df9675fSTheodore Ts'o 	ext4_group_t i, grp, g, ngroups;
433617ba13bSMingming Cao 	struct ext4_group_desc *desc;
434a4912123STheodore Ts'o 	struct orlov_stats stats;
435a4912123STheodore Ts'o 	int flex_size = ext4_flex_bg_size(sbi);
436f157a4aaSTheodore Ts'o 	struct dx_hash_info hinfo;
437a4912123STheodore Ts'o 
4388df9675fSTheodore Ts'o 	ngroups = real_ngroups;
439a4912123STheodore Ts'o 	if (flex_size > 1) {
4408df9675fSTheodore Ts'o 		ngroups = (real_ngroups + flex_size - 1) >>
441a4912123STheodore Ts'o 			sbi->s_log_groups_per_flex;
442a4912123STheodore Ts'o 		parent_group >>= sbi->s_log_groups_per_flex;
443a4912123STheodore Ts'o 	}
444ac27a0ecSDave Kleikamp 
445ac27a0ecSDave Kleikamp 	freei = percpu_counter_read_positive(&sbi->s_freeinodes_counter);
446ac27a0ecSDave Kleikamp 	avefreei = freei / ngroups;
44757042651STheodore Ts'o 	freeb = EXT4_C2B(sbi,
44857042651STheodore Ts'o 		percpu_counter_read_positive(&sbi->s_freeclusters_counter));
44924aaa8efSTheodore Ts'o 	avefreec = freeb;
45024aaa8efSTheodore Ts'o 	do_div(avefreec, ngroups);
451ac27a0ecSDave Kleikamp 	ndirs = percpu_counter_read_positive(&sbi->s_dirs_counter);
452ac27a0ecSDave Kleikamp 
453a4912123STheodore Ts'o 	if (S_ISDIR(mode) &&
4542b0143b5SDavid Howells 	    ((parent == d_inode(sb->s_root)) ||
45512e9b892SDmitry Monakhov 	     (ext4_test_inode_flag(parent, EXT4_INODE_TOPDIR)))) {
456ac27a0ecSDave Kleikamp 		int best_ndir = inodes_per_group;
4572aa9fc4cSAvantika Mathur 		int ret = -1;
458ac27a0ecSDave Kleikamp 
459f157a4aaSTheodore Ts'o 		if (qstr) {
460f157a4aaSTheodore Ts'o 			hinfo.hash_version = DX_HASH_HALF_MD4;
461f157a4aaSTheodore Ts'o 			hinfo.seed = sbi->s_hash_seed;
462b886ee3eSGabriel Krisman Bertazi 			ext4fs_dirhash(parent, qstr->name, qstr->len, &hinfo);
463f157a4aaSTheodore Ts'o 			grp = hinfo.hash;
464f157a4aaSTheodore Ts'o 		} else
465dd1f723bSTheodore Ts'o 			grp = prandom_u32();
4662aa9fc4cSAvantika Mathur 		parent_group = (unsigned)grp % ngroups;
467ac27a0ecSDave Kleikamp 		for (i = 0; i < ngroups; i++) {
468a4912123STheodore Ts'o 			g = (parent_group + i) % ngroups;
469a4912123STheodore Ts'o 			get_orlov_stats(sb, g, flex_size, &stats);
470a4912123STheodore Ts'o 			if (!stats.free_inodes)
471ac27a0ecSDave Kleikamp 				continue;
472a4912123STheodore Ts'o 			if (stats.used_dirs >= best_ndir)
473ac27a0ecSDave Kleikamp 				continue;
474a4912123STheodore Ts'o 			if (stats.free_inodes < avefreei)
475ac27a0ecSDave Kleikamp 				continue;
47624aaa8efSTheodore Ts'o 			if (stats.free_clusters < avefreec)
477ac27a0ecSDave Kleikamp 				continue;
478a4912123STheodore Ts'o 			grp = g;
4792aa9fc4cSAvantika Mathur 			ret = 0;
480a4912123STheodore Ts'o 			best_ndir = stats.used_dirs;
481ac27a0ecSDave Kleikamp 		}
482a4912123STheodore Ts'o 		if (ret)
483a4912123STheodore Ts'o 			goto fallback;
484a4912123STheodore Ts'o 	found_flex_bg:
485a4912123STheodore Ts'o 		if (flex_size == 1) {
486a4912123STheodore Ts'o 			*group = grp;
487a4912123STheodore Ts'o 			return 0;
488a4912123STheodore Ts'o 		}
489a4912123STheodore Ts'o 
490a4912123STheodore Ts'o 		/*
491a4912123STheodore Ts'o 		 * We pack inodes at the beginning of the flexgroup's
492a4912123STheodore Ts'o 		 * inode tables.  Block allocation decisions will do
493a4912123STheodore Ts'o 		 * something similar, although regular files will
494a4912123STheodore Ts'o 		 * start at 2nd block group of the flexgroup.  See
495a4912123STheodore Ts'o 		 * ext4_ext_find_goal() and ext4_find_near().
496a4912123STheodore Ts'o 		 */
497a4912123STheodore Ts'o 		grp *= flex_size;
498a4912123STheodore Ts'o 		for (i = 0; i < flex_size; i++) {
4998df9675fSTheodore Ts'o 			if (grp+i >= real_ngroups)
500a4912123STheodore Ts'o 				break;
501a4912123STheodore Ts'o 			desc = ext4_get_group_desc(sb, grp+i, NULL);
502a4912123STheodore Ts'o 			if (desc && ext4_free_inodes_count(sb, desc)) {
503a4912123STheodore Ts'o 				*group = grp+i;
504a4912123STheodore Ts'o 				return 0;
505a4912123STheodore Ts'o 			}
506a4912123STheodore Ts'o 		}
507ac27a0ecSDave Kleikamp 		goto fallback;
508ac27a0ecSDave Kleikamp 	}
509ac27a0ecSDave Kleikamp 
510ac27a0ecSDave Kleikamp 	max_dirs = ndirs / ngroups + inodes_per_group / 16;
511a4912123STheodore Ts'o 	min_inodes = avefreei - inodes_per_group*flex_size / 4;
512a4912123STheodore Ts'o 	if (min_inodes < 1)
513a4912123STheodore Ts'o 		min_inodes = 1;
51424aaa8efSTheodore Ts'o 	min_clusters = avefreec - EXT4_CLUSTERS_PER_GROUP(sb)*flex_size / 4;
515ac27a0ecSDave Kleikamp 
516a4912123STheodore Ts'o 	/*
517a4912123STheodore Ts'o 	 * Start looking in the flex group where we last allocated an
518a4912123STheodore Ts'o 	 * inode for this parent directory
519a4912123STheodore Ts'o 	 */
520a4912123STheodore Ts'o 	if (EXT4_I(parent)->i_last_alloc_group != ~0) {
521a4912123STheodore Ts'o 		parent_group = EXT4_I(parent)->i_last_alloc_group;
522a4912123STheodore Ts'o 		if (flex_size > 1)
523a4912123STheodore Ts'o 			parent_group >>= sbi->s_log_groups_per_flex;
524a4912123STheodore Ts'o 	}
525ac27a0ecSDave Kleikamp 
526ac27a0ecSDave Kleikamp 	for (i = 0; i < ngroups; i++) {
527a4912123STheodore Ts'o 		grp = (parent_group + i) % ngroups;
528a4912123STheodore Ts'o 		get_orlov_stats(sb, grp, flex_size, &stats);
529a4912123STheodore Ts'o 		if (stats.used_dirs >= max_dirs)
530ac27a0ecSDave Kleikamp 			continue;
531a4912123STheodore Ts'o 		if (stats.free_inodes < min_inodes)
532ac27a0ecSDave Kleikamp 			continue;
53324aaa8efSTheodore Ts'o 		if (stats.free_clusters < min_clusters)
534ac27a0ecSDave Kleikamp 			continue;
535a4912123STheodore Ts'o 		goto found_flex_bg;
536ac27a0ecSDave Kleikamp 	}
537ac27a0ecSDave Kleikamp 
538ac27a0ecSDave Kleikamp fallback:
5398df9675fSTheodore Ts'o 	ngroups = real_ngroups;
540a4912123STheodore Ts'o 	avefreei = freei / ngroups;
541b5451f7bSTheodore Ts'o fallback_retry:
542a4912123STheodore Ts'o 	parent_group = EXT4_I(parent)->i_block_group;
543ac27a0ecSDave Kleikamp 	for (i = 0; i < ngroups; i++) {
544a4912123STheodore Ts'o 		grp = (parent_group + i) % ngroups;
545a4912123STheodore Ts'o 		desc = ext4_get_group_desc(sb, grp, NULL);
546bb3d132aSDan Carpenter 		if (desc) {
54714c83c9fSTheodore Ts'o 			grp_free = ext4_free_inodes_count(sb, desc);
548bb3d132aSDan Carpenter 			if (grp_free && grp_free >= avefreei) {
549a4912123STheodore Ts'o 				*group = grp;
5502aa9fc4cSAvantika Mathur 				return 0;
551ac27a0ecSDave Kleikamp 			}
552a4912123STheodore Ts'o 		}
553bb3d132aSDan Carpenter 	}
554ac27a0ecSDave Kleikamp 
555ac27a0ecSDave Kleikamp 	if (avefreei) {
556ac27a0ecSDave Kleikamp 		/*
557ac27a0ecSDave Kleikamp 		 * The free-inodes counter is approximate, and for really small
558ac27a0ecSDave Kleikamp 		 * filesystems the above test can fail to find any blockgroups
559ac27a0ecSDave Kleikamp 		 */
560ac27a0ecSDave Kleikamp 		avefreei = 0;
561b5451f7bSTheodore Ts'o 		goto fallback_retry;
562ac27a0ecSDave Kleikamp 	}
563ac27a0ecSDave Kleikamp 
564ac27a0ecSDave Kleikamp 	return -1;
565ac27a0ecSDave Kleikamp }
566ac27a0ecSDave Kleikamp 
5672aa9fc4cSAvantika Mathur static int find_group_other(struct super_block *sb, struct inode *parent,
568dcca3fecSAl Viro 			    ext4_group_t *group, umode_t mode)
569ac27a0ecSDave Kleikamp {
570fd2d4291SAvantika Mathur 	ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
5718df9675fSTheodore Ts'o 	ext4_group_t i, last, ngroups = ext4_get_groups_count(sb);
572617ba13bSMingming Cao 	struct ext4_group_desc *desc;
573a4912123STheodore Ts'o 	int flex_size = ext4_flex_bg_size(EXT4_SB(sb));
574a4912123STheodore Ts'o 
575a4912123STheodore Ts'o 	/*
576a4912123STheodore Ts'o 	 * Try to place the inode is the same flex group as its
577a4912123STheodore Ts'o 	 * parent.  If we can't find space, use the Orlov algorithm to
578a4912123STheodore Ts'o 	 * find another flex group, and store that information in the
579a4912123STheodore Ts'o 	 * parent directory's inode information so that use that flex
580a4912123STheodore Ts'o 	 * group for future allocations.
581a4912123STheodore Ts'o 	 */
582a4912123STheodore Ts'o 	if (flex_size > 1) {
583a4912123STheodore Ts'o 		int retry = 0;
584a4912123STheodore Ts'o 
585a4912123STheodore Ts'o 	try_again:
586a4912123STheodore Ts'o 		parent_group &= ~(flex_size-1);
587a4912123STheodore Ts'o 		last = parent_group + flex_size;
588a4912123STheodore Ts'o 		if (last > ngroups)
589a4912123STheodore Ts'o 			last = ngroups;
590a4912123STheodore Ts'o 		for  (i = parent_group; i < last; i++) {
591a4912123STheodore Ts'o 			desc = ext4_get_group_desc(sb, i, NULL);
592a4912123STheodore Ts'o 			if (desc && ext4_free_inodes_count(sb, desc)) {
593a4912123STheodore Ts'o 				*group = i;
594a4912123STheodore Ts'o 				return 0;
595a4912123STheodore Ts'o 			}
596a4912123STheodore Ts'o 		}
597a4912123STheodore Ts'o 		if (!retry && EXT4_I(parent)->i_last_alloc_group != ~0) {
598a4912123STheodore Ts'o 			retry = 1;
599a4912123STheodore Ts'o 			parent_group = EXT4_I(parent)->i_last_alloc_group;
600a4912123STheodore Ts'o 			goto try_again;
601a4912123STheodore Ts'o 		}
602a4912123STheodore Ts'o 		/*
603a4912123STheodore Ts'o 		 * If this didn't work, use the Orlov search algorithm
604a4912123STheodore Ts'o 		 * to find a new flex group; we pass in the mode to
605a4912123STheodore Ts'o 		 * avoid the topdir algorithms.
606a4912123STheodore Ts'o 		 */
607a4912123STheodore Ts'o 		*group = parent_group + flex_size;
608a4912123STheodore Ts'o 		if (*group > ngroups)
609a4912123STheodore Ts'o 			*group = 0;
6107dc57615SPeter Huewe 		return find_group_orlov(sb, parent, group, mode, NULL);
611a4912123STheodore Ts'o 	}
612ac27a0ecSDave Kleikamp 
613ac27a0ecSDave Kleikamp 	/*
614ac27a0ecSDave Kleikamp 	 * Try to place the inode in its parent directory
615ac27a0ecSDave Kleikamp 	 */
6162aa9fc4cSAvantika Mathur 	*group = parent_group;
6172aa9fc4cSAvantika Mathur 	desc = ext4_get_group_desc(sb, *group, NULL);
618560671a0SAneesh Kumar K.V 	if (desc && ext4_free_inodes_count(sb, desc) &&
619021b65bbSTheodore Ts'o 	    ext4_free_group_clusters(sb, desc))
6202aa9fc4cSAvantika Mathur 		return 0;
621ac27a0ecSDave Kleikamp 
622ac27a0ecSDave Kleikamp 	/*
623ac27a0ecSDave Kleikamp 	 * We're going to place this inode in a different blockgroup from its
624ac27a0ecSDave Kleikamp 	 * parent.  We want to cause files in a common directory to all land in
625ac27a0ecSDave Kleikamp 	 * the same blockgroup.  But we want files which are in a different
626ac27a0ecSDave Kleikamp 	 * directory which shares a blockgroup with our parent to land in a
627ac27a0ecSDave Kleikamp 	 * different blockgroup.
628ac27a0ecSDave Kleikamp 	 *
629ac27a0ecSDave Kleikamp 	 * So add our directory's i_ino into the starting point for the hash.
630ac27a0ecSDave Kleikamp 	 */
6312aa9fc4cSAvantika Mathur 	*group = (*group + parent->i_ino) % ngroups;
632ac27a0ecSDave Kleikamp 
633ac27a0ecSDave Kleikamp 	/*
634ac27a0ecSDave Kleikamp 	 * Use a quadratic hash to find a group with a free inode and some free
635ac27a0ecSDave Kleikamp 	 * blocks.
636ac27a0ecSDave Kleikamp 	 */
637ac27a0ecSDave Kleikamp 	for (i = 1; i < ngroups; i <<= 1) {
6382aa9fc4cSAvantika Mathur 		*group += i;
6392aa9fc4cSAvantika Mathur 		if (*group >= ngroups)
6402aa9fc4cSAvantika Mathur 			*group -= ngroups;
6412aa9fc4cSAvantika Mathur 		desc = ext4_get_group_desc(sb, *group, NULL);
642560671a0SAneesh Kumar K.V 		if (desc && ext4_free_inodes_count(sb, desc) &&
643021b65bbSTheodore Ts'o 		    ext4_free_group_clusters(sb, desc))
6442aa9fc4cSAvantika Mathur 			return 0;
645ac27a0ecSDave Kleikamp 	}
646ac27a0ecSDave Kleikamp 
647ac27a0ecSDave Kleikamp 	/*
648ac27a0ecSDave Kleikamp 	 * That failed: try linear search for a free inode, even if that group
649ac27a0ecSDave Kleikamp 	 * has no free blocks.
650ac27a0ecSDave Kleikamp 	 */
6512aa9fc4cSAvantika Mathur 	*group = parent_group;
652ac27a0ecSDave Kleikamp 	for (i = 0; i < ngroups; i++) {
6532aa9fc4cSAvantika Mathur 		if (++*group >= ngroups)
6542aa9fc4cSAvantika Mathur 			*group = 0;
6552aa9fc4cSAvantika Mathur 		desc = ext4_get_group_desc(sb, *group, NULL);
656560671a0SAneesh Kumar K.V 		if (desc && ext4_free_inodes_count(sb, desc))
6572aa9fc4cSAvantika Mathur 			return 0;
658ac27a0ecSDave Kleikamp 	}
659ac27a0ecSDave Kleikamp 
660ac27a0ecSDave Kleikamp 	return -1;
661ac27a0ecSDave Kleikamp }
662ac27a0ecSDave Kleikamp 
663ac27a0ecSDave Kleikamp /*
66419883bd9STheodore Ts'o  * In no journal mode, if an inode has recently been deleted, we want
66519883bd9STheodore Ts'o  * to avoid reusing it until we're reasonably sure the inode table
66619883bd9STheodore Ts'o  * block has been written back to disk.  (Yes, these values are
66719883bd9STheodore Ts'o  * somewhat arbitrary...)
66819883bd9STheodore Ts'o  */
669a17a9d93STheodore Ts'o #define RECENTCY_MIN	60
670b5f51573SAndreas Dilger #define RECENTCY_DIRTY	300
67119883bd9STheodore Ts'o 
67219883bd9STheodore Ts'o static int recently_deleted(struct super_block *sb, ext4_group_t group, int ino)
67319883bd9STheodore Ts'o {
67419883bd9STheodore Ts'o 	struct ext4_group_desc	*gdp;
67519883bd9STheodore Ts'o 	struct ext4_inode	*raw_inode;
67619883bd9STheodore Ts'o 	struct buffer_head	*bh;
67719883bd9STheodore Ts'o 	int inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
678b5f51573SAndreas Dilger 	int offset, ret = 0;
679b5f51573SAndreas Dilger 	int recentcy = RECENTCY_MIN;
680b5f51573SAndreas Dilger 	u32 dtime, now;
68119883bd9STheodore Ts'o 
68219883bd9STheodore Ts'o 	gdp = ext4_get_group_desc(sb, group, NULL);
68319883bd9STheodore Ts'o 	if (unlikely(!gdp))
68419883bd9STheodore Ts'o 		return 0;
68519883bd9STheodore Ts'o 
6864f9d956dSJan Kara 	bh = sb_find_get_block(sb, ext4_inode_table(sb, gdp) +
68719883bd9STheodore Ts'o 		       (ino / inodes_per_block));
6884f9d956dSJan Kara 	if (!bh || !buffer_uptodate(bh))
68919883bd9STheodore Ts'o 		/*
69019883bd9STheodore Ts'o 		 * If the block is not in the buffer cache, then it
69119883bd9STheodore Ts'o 		 * must have been written out.
69219883bd9STheodore Ts'o 		 */
69319883bd9STheodore Ts'o 		goto out;
69419883bd9STheodore Ts'o 
69519883bd9STheodore Ts'o 	offset = (ino % inodes_per_block) * EXT4_INODE_SIZE(sb);
69619883bd9STheodore Ts'o 	raw_inode = (struct ext4_inode *) (bh->b_data + offset);
697b5f51573SAndreas Dilger 
698b5f51573SAndreas Dilger 	/* i_dtime is only 32 bits on disk, but we only care about relative
699b5f51573SAndreas Dilger 	 * times in the range of a few minutes (i.e. long enough to sync a
700b5f51573SAndreas Dilger 	 * recently-deleted inode to disk), so using the low 32 bits of the
701b5f51573SAndreas Dilger 	 * clock (a 68 year range) is enough, see time_before32() */
70219883bd9STheodore Ts'o 	dtime = le32_to_cpu(raw_inode->i_dtime);
703b5f51573SAndreas Dilger 	now = ktime_get_real_seconds();
70419883bd9STheodore Ts'o 	if (buffer_dirty(bh))
70519883bd9STheodore Ts'o 		recentcy += RECENTCY_DIRTY;
70619883bd9STheodore Ts'o 
707b5f51573SAndreas Dilger 	if (dtime && time_before32(dtime, now) &&
708b5f51573SAndreas Dilger 	    time_before32(now, dtime + recentcy))
70919883bd9STheodore Ts'o 		ret = 1;
71019883bd9STheodore Ts'o out:
71119883bd9STheodore Ts'o 	brelse(bh);
71219883bd9STheodore Ts'o 	return ret;
71319883bd9STheodore Ts'o }
71419883bd9STheodore Ts'o 
715901ed070SWang Shilong static int find_inode_bit(struct super_block *sb, ext4_group_t group,
716901ed070SWang Shilong 			  struct buffer_head *bitmap, unsigned long *ino)
717901ed070SWang Shilong {
718d05466b2SJan Kara 	bool check_recently_deleted = EXT4_SB(sb)->s_journal == NULL;
719d05466b2SJan Kara 	unsigned long recently_deleted_ino = EXT4_INODES_PER_GROUP(sb);
720d05466b2SJan Kara 
721901ed070SWang Shilong next:
722901ed070SWang Shilong 	*ino = ext4_find_next_zero_bit((unsigned long *)
723901ed070SWang Shilong 				       bitmap->b_data,
724901ed070SWang Shilong 				       EXT4_INODES_PER_GROUP(sb), *ino);
725901ed070SWang Shilong 	if (*ino >= EXT4_INODES_PER_GROUP(sb))
726d05466b2SJan Kara 		goto not_found;
727901ed070SWang Shilong 
728d05466b2SJan Kara 	if (check_recently_deleted && recently_deleted(sb, group, *ino)) {
729d05466b2SJan Kara 		recently_deleted_ino = *ino;
730901ed070SWang Shilong 		*ino = *ino + 1;
731901ed070SWang Shilong 		if (*ino < EXT4_INODES_PER_GROUP(sb))
732901ed070SWang Shilong 			goto next;
733d05466b2SJan Kara 		goto not_found;
734901ed070SWang Shilong 	}
735d05466b2SJan Kara 	return 1;
736d05466b2SJan Kara not_found:
737d05466b2SJan Kara 	if (recently_deleted_ino >= EXT4_INODES_PER_GROUP(sb))
738d05466b2SJan Kara 		return 0;
739d05466b2SJan Kara 	/*
740d05466b2SJan Kara 	 * Not reusing recently deleted inodes is mostly a preference. We don't
741d05466b2SJan Kara 	 * want to report ENOSPC or skew allocation patterns because of that.
742d05466b2SJan Kara 	 * So return even recently deleted inode if we could find better in the
743d05466b2SJan Kara 	 * given range.
744d05466b2SJan Kara 	 */
745d05466b2SJan Kara 	*ino = recently_deleted_ino;
746901ed070SWang Shilong 	return 1;
747901ed070SWang Shilong }
748901ed070SWang Shilong 
749*8016e29fSHarshad Shirwadkar int ext4_mark_inode_used(struct super_block *sb, int ino)
750*8016e29fSHarshad Shirwadkar {
751*8016e29fSHarshad Shirwadkar 	unsigned long max_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count);
752*8016e29fSHarshad Shirwadkar 	struct buffer_head *inode_bitmap_bh = NULL, *group_desc_bh = NULL;
753*8016e29fSHarshad Shirwadkar 	struct ext4_group_desc *gdp;
754*8016e29fSHarshad Shirwadkar 	ext4_group_t group;
755*8016e29fSHarshad Shirwadkar 	int bit;
756*8016e29fSHarshad Shirwadkar 	int err = -EFSCORRUPTED;
757*8016e29fSHarshad Shirwadkar 
758*8016e29fSHarshad Shirwadkar 	if (ino < EXT4_FIRST_INO(sb) || ino > max_ino)
759*8016e29fSHarshad Shirwadkar 		goto out;
760*8016e29fSHarshad Shirwadkar 
761*8016e29fSHarshad Shirwadkar 	group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
762*8016e29fSHarshad Shirwadkar 	bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
763*8016e29fSHarshad Shirwadkar 	inode_bitmap_bh = ext4_read_inode_bitmap(sb, group);
764*8016e29fSHarshad Shirwadkar 	if (IS_ERR(inode_bitmap_bh))
765*8016e29fSHarshad Shirwadkar 		return PTR_ERR(inode_bitmap_bh);
766*8016e29fSHarshad Shirwadkar 
767*8016e29fSHarshad Shirwadkar 	if (ext4_test_bit(bit, inode_bitmap_bh->b_data)) {
768*8016e29fSHarshad Shirwadkar 		err = 0;
769*8016e29fSHarshad Shirwadkar 		goto out;
770*8016e29fSHarshad Shirwadkar 	}
771*8016e29fSHarshad Shirwadkar 
772*8016e29fSHarshad Shirwadkar 	gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
773*8016e29fSHarshad Shirwadkar 	if (!gdp || !group_desc_bh) {
774*8016e29fSHarshad Shirwadkar 		err = -EINVAL;
775*8016e29fSHarshad Shirwadkar 		goto out;
776*8016e29fSHarshad Shirwadkar 	}
777*8016e29fSHarshad Shirwadkar 
778*8016e29fSHarshad Shirwadkar 	ext4_set_bit(bit, inode_bitmap_bh->b_data);
779*8016e29fSHarshad Shirwadkar 
780*8016e29fSHarshad Shirwadkar 	BUFFER_TRACE(inode_bitmap_bh, "call ext4_handle_dirty_metadata");
781*8016e29fSHarshad Shirwadkar 	err = ext4_handle_dirty_metadata(NULL, NULL, inode_bitmap_bh);
782*8016e29fSHarshad Shirwadkar 	if (err) {
783*8016e29fSHarshad Shirwadkar 		ext4_std_error(sb, err);
784*8016e29fSHarshad Shirwadkar 		goto out;
785*8016e29fSHarshad Shirwadkar 	}
786*8016e29fSHarshad Shirwadkar 	err = sync_dirty_buffer(inode_bitmap_bh);
787*8016e29fSHarshad Shirwadkar 	if (err) {
788*8016e29fSHarshad Shirwadkar 		ext4_std_error(sb, err);
789*8016e29fSHarshad Shirwadkar 		goto out;
790*8016e29fSHarshad Shirwadkar 	}
791*8016e29fSHarshad Shirwadkar 
792*8016e29fSHarshad Shirwadkar 	/* We may have to initialize the block bitmap if it isn't already */
793*8016e29fSHarshad Shirwadkar 	if (ext4_has_group_desc_csum(sb) &&
794*8016e29fSHarshad Shirwadkar 	    gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
795*8016e29fSHarshad Shirwadkar 		struct buffer_head *block_bitmap_bh;
796*8016e29fSHarshad Shirwadkar 
797*8016e29fSHarshad Shirwadkar 		block_bitmap_bh = ext4_read_block_bitmap(sb, group);
798*8016e29fSHarshad Shirwadkar 		if (IS_ERR(block_bitmap_bh)) {
799*8016e29fSHarshad Shirwadkar 			err = PTR_ERR(block_bitmap_bh);
800*8016e29fSHarshad Shirwadkar 			goto out;
801*8016e29fSHarshad Shirwadkar 		}
802*8016e29fSHarshad Shirwadkar 
803*8016e29fSHarshad Shirwadkar 		BUFFER_TRACE(block_bitmap_bh, "dirty block bitmap");
804*8016e29fSHarshad Shirwadkar 		err = ext4_handle_dirty_metadata(NULL, NULL, block_bitmap_bh);
805*8016e29fSHarshad Shirwadkar 		sync_dirty_buffer(block_bitmap_bh);
806*8016e29fSHarshad Shirwadkar 
807*8016e29fSHarshad Shirwadkar 		/* recheck and clear flag under lock if we still need to */
808*8016e29fSHarshad Shirwadkar 		ext4_lock_group(sb, group);
809*8016e29fSHarshad Shirwadkar 		if (ext4_has_group_desc_csum(sb) &&
810*8016e29fSHarshad Shirwadkar 		    (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
811*8016e29fSHarshad Shirwadkar 			gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
812*8016e29fSHarshad Shirwadkar 			ext4_free_group_clusters_set(sb, gdp,
813*8016e29fSHarshad Shirwadkar 				ext4_free_clusters_after_init(sb, group, gdp));
814*8016e29fSHarshad Shirwadkar 			ext4_block_bitmap_csum_set(sb, group, gdp,
815*8016e29fSHarshad Shirwadkar 						   block_bitmap_bh);
816*8016e29fSHarshad Shirwadkar 			ext4_group_desc_csum_set(sb, group, gdp);
817*8016e29fSHarshad Shirwadkar 		}
818*8016e29fSHarshad Shirwadkar 		ext4_unlock_group(sb, group);
819*8016e29fSHarshad Shirwadkar 		brelse(block_bitmap_bh);
820*8016e29fSHarshad Shirwadkar 
821*8016e29fSHarshad Shirwadkar 		if (err) {
822*8016e29fSHarshad Shirwadkar 			ext4_std_error(sb, err);
823*8016e29fSHarshad Shirwadkar 			goto out;
824*8016e29fSHarshad Shirwadkar 		}
825*8016e29fSHarshad Shirwadkar 	}
826*8016e29fSHarshad Shirwadkar 
827*8016e29fSHarshad Shirwadkar 	/* Update the relevant bg descriptor fields */
828*8016e29fSHarshad Shirwadkar 	if (ext4_has_group_desc_csum(sb)) {
829*8016e29fSHarshad Shirwadkar 		int free;
830*8016e29fSHarshad Shirwadkar 
831*8016e29fSHarshad Shirwadkar 		ext4_lock_group(sb, group); /* while we modify the bg desc */
832*8016e29fSHarshad Shirwadkar 		free = EXT4_INODES_PER_GROUP(sb) -
833*8016e29fSHarshad Shirwadkar 			ext4_itable_unused_count(sb, gdp);
834*8016e29fSHarshad Shirwadkar 		if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
835*8016e29fSHarshad Shirwadkar 			gdp->bg_flags &= cpu_to_le16(~EXT4_BG_INODE_UNINIT);
836*8016e29fSHarshad Shirwadkar 			free = 0;
837*8016e29fSHarshad Shirwadkar 		}
838*8016e29fSHarshad Shirwadkar 
839*8016e29fSHarshad Shirwadkar 		/*
840*8016e29fSHarshad Shirwadkar 		 * Check the relative inode number against the last used
841*8016e29fSHarshad Shirwadkar 		 * relative inode number in this group. if it is greater
842*8016e29fSHarshad Shirwadkar 		 * we need to update the bg_itable_unused count
843*8016e29fSHarshad Shirwadkar 		 */
844*8016e29fSHarshad Shirwadkar 		if (bit >= free)
845*8016e29fSHarshad Shirwadkar 			ext4_itable_unused_set(sb, gdp,
846*8016e29fSHarshad Shirwadkar 					(EXT4_INODES_PER_GROUP(sb) - bit - 1));
847*8016e29fSHarshad Shirwadkar 	} else {
848*8016e29fSHarshad Shirwadkar 		ext4_lock_group(sb, group);
849*8016e29fSHarshad Shirwadkar 	}
850*8016e29fSHarshad Shirwadkar 
851*8016e29fSHarshad Shirwadkar 	ext4_free_inodes_set(sb, gdp, ext4_free_inodes_count(sb, gdp) - 1);
852*8016e29fSHarshad Shirwadkar 	if (ext4_has_group_desc_csum(sb)) {
853*8016e29fSHarshad Shirwadkar 		ext4_inode_bitmap_csum_set(sb, group, gdp, inode_bitmap_bh,
854*8016e29fSHarshad Shirwadkar 					   EXT4_INODES_PER_GROUP(sb) / 8);
855*8016e29fSHarshad Shirwadkar 		ext4_group_desc_csum_set(sb, group, gdp);
856*8016e29fSHarshad Shirwadkar 	}
857*8016e29fSHarshad Shirwadkar 
858*8016e29fSHarshad Shirwadkar 	ext4_unlock_group(sb, group);
859*8016e29fSHarshad Shirwadkar 	err = ext4_handle_dirty_metadata(NULL, NULL, group_desc_bh);
860*8016e29fSHarshad Shirwadkar 	sync_dirty_buffer(group_desc_bh);
861*8016e29fSHarshad Shirwadkar out:
862*8016e29fSHarshad Shirwadkar 	return err;
863*8016e29fSHarshad Shirwadkar }
864*8016e29fSHarshad Shirwadkar 
86519883bd9STheodore Ts'o /*
866ac27a0ecSDave Kleikamp  * There are two policies for allocating an inode.  If the new inode is
867ac27a0ecSDave Kleikamp  * a directory, then a forward search is made for a block group with both
868ac27a0ecSDave Kleikamp  * free space and a low directory-to-inode ratio; if that fails, then of
869ac27a0ecSDave Kleikamp  * the groups with above-average free space, that group with the fewest
870ac27a0ecSDave Kleikamp  * directories already is chosen.
871ac27a0ecSDave Kleikamp  *
872ac27a0ecSDave Kleikamp  * For other inodes, search forward from the parent directory's block
873ac27a0ecSDave Kleikamp  * group to find a free inode.
874ac27a0ecSDave Kleikamp  */
8751139575aSTheodore Ts'o struct inode *__ext4_new_inode(handle_t *handle, struct inode *dir,
8761139575aSTheodore Ts'o 			       umode_t mode, const struct qstr *qstr,
8771b917ed8STahsin Erdogan 			       __u32 goal, uid_t *owner, __u32 i_flags,
8781b917ed8STahsin Erdogan 			       int handle_type, unsigned int line_no,
8791b917ed8STahsin Erdogan 			       int nblocks)
880ac27a0ecSDave Kleikamp {
881ac27a0ecSDave Kleikamp 	struct super_block *sb;
8823300bedaSAneesh Kumar K.V 	struct buffer_head *inode_bitmap_bh = NULL;
8833300bedaSAneesh Kumar K.V 	struct buffer_head *group_desc_bh;
8848df9675fSTheodore Ts'o 	ext4_group_t ngroups, group = 0;
885ac27a0ecSDave Kleikamp 	unsigned long ino = 0;
886ac27a0ecSDave Kleikamp 	struct inode *inode;
887617ba13bSMingming Cao 	struct ext4_group_desc *gdp = NULL;
888617ba13bSMingming Cao 	struct ext4_inode_info *ei;
889617ba13bSMingming Cao 	struct ext4_sb_info *sbi;
890a7cdadeeSJan Kara 	int ret2, err;
891ac27a0ecSDave Kleikamp 	struct inode *ret;
8922aa9fc4cSAvantika Mathur 	ext4_group_t i;
893772cb7c8SJose R. Santos 	ext4_group_t flex_group;
894*8016e29fSHarshad Shirwadkar 	struct ext4_group_info *grp = NULL;
895e709e9dfSTheodore Ts'o 	int encrypt = 0;
896ac27a0ecSDave Kleikamp 
897ac27a0ecSDave Kleikamp 	/* Cannot create files in a deleted directory */
898ac27a0ecSDave Kleikamp 	if (!dir || !dir->i_nlink)
899ac27a0ecSDave Kleikamp 		return ERR_PTR(-EPERM);
900ac27a0ecSDave Kleikamp 
901af65207cSTahsin Erdogan 	sb = dir->i_sb;
902af65207cSTahsin Erdogan 	sbi = EXT4_SB(sb);
903af65207cSTahsin Erdogan 
904af65207cSTahsin Erdogan 	if (unlikely(ext4_forced_shutdown(sbi)))
9050db1ff22STheodore Ts'o 		return ERR_PTR(-EIO);
9060db1ff22STheodore Ts'o 
907592ddec7SChandan Rajendra 	if ((IS_ENCRYPTED(dir) || DUMMY_ENCRYPTION_ENABLED(sbi)) &&
908ad47f953STahsin Erdogan 	    (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)) &&
909ad47f953STahsin Erdogan 	    !(i_flags & EXT4_EA_INODE_FL)) {
910a7550b30SJaegeuk Kim 		err = fscrypt_get_encryption_info(dir);
911e709e9dfSTheodore Ts'o 		if (err)
912e709e9dfSTheodore Ts'o 			return ERR_PTR(err);
913a7550b30SJaegeuk Kim 		if (!fscrypt_has_encryption_key(dir))
91454475f53SEric Biggers 			return ERR_PTR(-ENOKEY);
915e709e9dfSTheodore Ts'o 		encrypt = 1;
916e709e9dfSTheodore Ts'o 	}
917e709e9dfSTheodore Ts'o 
918af65207cSTahsin Erdogan 	if (!handle && sbi->s_journal && !(i_flags & EXT4_EA_INODE_FL)) {
919af65207cSTahsin Erdogan #ifdef CONFIG_EXT4_FS_POSIX_ACL
920af65207cSTahsin Erdogan 		struct posix_acl *p = get_acl(dir, ACL_TYPE_DEFAULT);
921af65207cSTahsin Erdogan 
922996fc447STheodore Ts'o 		if (IS_ERR(p))
923996fc447STheodore Ts'o 			return ERR_CAST(p);
924af65207cSTahsin Erdogan 		if (p) {
925af65207cSTahsin Erdogan 			int acl_size = p->a_count * sizeof(ext4_acl_entry);
926af65207cSTahsin Erdogan 
927af65207cSTahsin Erdogan 			nblocks += (S_ISDIR(mode) ? 2 : 1) *
928af65207cSTahsin Erdogan 				__ext4_xattr_set_credits(sb, NULL /* inode */,
929af65207cSTahsin Erdogan 					NULL /* block_bh */, acl_size,
930af65207cSTahsin Erdogan 					true /* is_create */);
931af65207cSTahsin Erdogan 			posix_acl_release(p);
932af65207cSTahsin Erdogan 		}
933af65207cSTahsin Erdogan #endif
934af65207cSTahsin Erdogan 
935af65207cSTahsin Erdogan #ifdef CONFIG_SECURITY
936af65207cSTahsin Erdogan 		{
937af65207cSTahsin Erdogan 			int num_security_xattrs = 1;
938af65207cSTahsin Erdogan 
939af65207cSTahsin Erdogan #ifdef CONFIG_INTEGRITY
940af65207cSTahsin Erdogan 			num_security_xattrs++;
941af65207cSTahsin Erdogan #endif
942af65207cSTahsin Erdogan 			/*
943af65207cSTahsin Erdogan 			 * We assume that security xattrs are never
944af65207cSTahsin Erdogan 			 * more than 1k.  In practice they are under
945af65207cSTahsin Erdogan 			 * 128 bytes.
946af65207cSTahsin Erdogan 			 */
947af65207cSTahsin Erdogan 			nblocks += num_security_xattrs *
948af65207cSTahsin Erdogan 				__ext4_xattr_set_credits(sb, NULL /* inode */,
949af65207cSTahsin Erdogan 					NULL /* block_bh */, 1024,
950af65207cSTahsin Erdogan 					true /* is_create */);
951af65207cSTahsin Erdogan 		}
952af65207cSTahsin Erdogan #endif
953af65207cSTahsin Erdogan 		if (encrypt)
954af65207cSTahsin Erdogan 			nblocks += __ext4_xattr_set_credits(sb,
955af65207cSTahsin Erdogan 					NULL /* inode */, NULL /* block_bh */,
956af65207cSTahsin Erdogan 					FSCRYPT_SET_CONTEXT_MAX_SIZE,
957af65207cSTahsin Erdogan 					true /* is_create */);
958af65207cSTahsin Erdogan 	}
959af65207cSTahsin Erdogan 
9608df9675fSTheodore Ts'o 	ngroups = ext4_get_groups_count(sb);
9619bffad1eSTheodore Ts'o 	trace_ext4_request_inode(dir, mode);
962ac27a0ecSDave Kleikamp 	inode = new_inode(sb);
963ac27a0ecSDave Kleikamp 	if (!inode)
964ac27a0ecSDave Kleikamp 		return ERR_PTR(-ENOMEM);
965617ba13bSMingming Cao 	ei = EXT4_I(inode);
966772cb7c8SJose R. Santos 
967eb9cc7e1SJan Kara 	/*
968b8a07463SAdam Buchbinder 	 * Initialize owners and quota early so that we don't have to account
969eb9cc7e1SJan Kara 	 * for quota initialization worst case in standard inode creating
970eb9cc7e1SJan Kara 	 * transaction
971eb9cc7e1SJan Kara 	 */
972eb9cc7e1SJan Kara 	if (owner) {
973eb9cc7e1SJan Kara 		inode->i_mode = mode;
974eb9cc7e1SJan Kara 		i_uid_write(inode, owner[0]);
975eb9cc7e1SJan Kara 		i_gid_write(inode, owner[1]);
976eb9cc7e1SJan Kara 	} else if (test_opt(sb, GRPID)) {
977eb9cc7e1SJan Kara 		inode->i_mode = mode;
978eb9cc7e1SJan Kara 		inode->i_uid = current_fsuid();
979eb9cc7e1SJan Kara 		inode->i_gid = dir->i_gid;
980eb9cc7e1SJan Kara 	} else
981eb9cc7e1SJan Kara 		inode_init_owner(inode, dir, mode);
982040cb378SLi Xi 
9830b7b7779SKaho Ng 	if (ext4_has_feature_project(sb) &&
984040cb378SLi Xi 	    ext4_test_inode_flag(dir, EXT4_INODE_PROJINHERIT))
985040cb378SLi Xi 		ei->i_projid = EXT4_I(dir)->i_projid;
986040cb378SLi Xi 	else
987040cb378SLi Xi 		ei->i_projid = make_kprojid(&init_user_ns, EXT4_DEF_PROJID);
988040cb378SLi Xi 
989a7cdadeeSJan Kara 	err = dquot_initialize(inode);
990a7cdadeeSJan Kara 	if (err)
991a7cdadeeSJan Kara 		goto out;
992eb9cc7e1SJan Kara 
99311013911SAndreas Dilger 	if (!goal)
99411013911SAndreas Dilger 		goal = sbi->s_inode_goal;
99511013911SAndreas Dilger 
996e6462869SJohann Lombardi 	if (goal && goal <= le32_to_cpu(sbi->s_es->s_inodes_count)) {
99711013911SAndreas Dilger 		group = (goal - 1) / EXT4_INODES_PER_GROUP(sb);
99811013911SAndreas Dilger 		ino = (goal - 1) % EXT4_INODES_PER_GROUP(sb);
99911013911SAndreas Dilger 		ret2 = 0;
100011013911SAndreas Dilger 		goto got_group;
100111013911SAndreas Dilger 	}
100211013911SAndreas Dilger 
10034113c4caSLukas Czerner 	if (S_ISDIR(mode))
1004f157a4aaSTheodore Ts'o 		ret2 = find_group_orlov(sb, dir, &group, mode, qstr);
10054113c4caSLukas Czerner 	else
1006a4912123STheodore Ts'o 		ret2 = find_group_other(sb, dir, &group, mode);
1007ac27a0ecSDave Kleikamp 
1008772cb7c8SJose R. Santos got_group:
1009a4912123STheodore Ts'o 	EXT4_I(dir)->i_last_alloc_group = group;
1010ac27a0ecSDave Kleikamp 	err = -ENOSPC;
10112aa9fc4cSAvantika Mathur 	if (ret2 == -1)
1012ac27a0ecSDave Kleikamp 		goto out;
1013ac27a0ecSDave Kleikamp 
1014119c0d44STheodore Ts'o 	/*
1015119c0d44STheodore Ts'o 	 * Normally we will only go through one pass of this loop,
1016119c0d44STheodore Ts'o 	 * unless we get unlucky and it turns out the group we selected
1017119c0d44STheodore Ts'o 	 * had its last inode grabbed by someone else.
1018119c0d44STheodore Ts'o 	 */
101911013911SAndreas Dilger 	for (i = 0; i < ngroups; i++, ino = 0) {
1020ac27a0ecSDave Kleikamp 		err = -EIO;
1021ac27a0ecSDave Kleikamp 
10223300bedaSAneesh Kumar K.V 		gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
1023ac27a0ecSDave Kleikamp 		if (!gdp)
1024eb9cc7e1SJan Kara 			goto out;
1025ac27a0ecSDave Kleikamp 
1026f2a09af6SYongqiang Yang 		/*
1027f2a09af6SYongqiang Yang 		 * Check free inodes count before loading bitmap.
1028f2a09af6SYongqiang Yang 		 */
10292fe435d8SWang Shilong 		if (ext4_free_inodes_count(sb, gdp) == 0)
10302fe435d8SWang Shilong 			goto next_group;
1031f2a09af6SYongqiang Yang 
1032*8016e29fSHarshad Shirwadkar 		if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
103387a39389SDarrick J. Wong 			grp = ext4_get_group_info(sb, group);
1034*8016e29fSHarshad Shirwadkar 			/*
1035*8016e29fSHarshad Shirwadkar 			 * Skip groups with already-known suspicious inode
1036*8016e29fSHarshad Shirwadkar 			 * tables
1037*8016e29fSHarshad Shirwadkar 			 */
10382fe435d8SWang Shilong 			if (EXT4_MB_GRP_IBITMAP_CORRUPT(grp))
10392fe435d8SWang Shilong 				goto next_group;
1040*8016e29fSHarshad Shirwadkar 		}
104187a39389SDarrick J. Wong 
10423300bedaSAneesh Kumar K.V 		brelse(inode_bitmap_bh);
10433300bedaSAneesh Kumar K.V 		inode_bitmap_bh = ext4_read_inode_bitmap(sb, group);
104487a39389SDarrick J. Wong 		/* Skip groups with suspicious inode tables */
1045*8016e29fSHarshad Shirwadkar 		if (((!(sbi->s_mount_state & EXT4_FC_REPLAY))
1046*8016e29fSHarshad Shirwadkar 		     && EXT4_MB_GRP_IBITMAP_CORRUPT(grp)) ||
10479008a58eSDarrick J. Wong 		    IS_ERR(inode_bitmap_bh)) {
10489008a58eSDarrick J. Wong 			inode_bitmap_bh = NULL;
10492fe435d8SWang Shilong 			goto next_group;
105087a39389SDarrick J. Wong 		}
1051ac27a0ecSDave Kleikamp 
1052ac27a0ecSDave Kleikamp repeat_in_this_group:
1053901ed070SWang Shilong 		ret2 = find_inode_bit(sb, group, inode_bitmap_bh, &ino);
1054901ed070SWang Shilong 		if (!ret2)
1055a34eb503STheodore Ts'o 			goto next_group;
1056901ed070SWang Shilong 
1057119c0d44STheodore Ts'o 		if (group == 0 && (ino + 1) < EXT4_FIRST_INO(sb)) {
1058119c0d44STheodore Ts'o 			ext4_error(sb, "reserved inode found cleared - "
1059119c0d44STheodore Ts'o 				   "inode=%lu", ino + 1);
1060206f6d55SWang Shilong 			ext4_mark_group_bitmap_corrupted(sb, group,
1061206f6d55SWang Shilong 					EXT4_GROUP_INFO_IBITMAP_CORRUPT);
10622fe435d8SWang Shilong 			goto next_group;
1063119c0d44STheodore Ts'o 		}
1064901ed070SWang Shilong 
1065*8016e29fSHarshad Shirwadkar 		if ((!(sbi->s_mount_state & EXT4_FC_REPLAY)) && !handle) {
10661139575aSTheodore Ts'o 			BUG_ON(nblocks <= 0);
10671139575aSTheodore Ts'o 			handle = __ext4_journal_start_sb(dir->i_sb, line_no,
1068a70fd5acSyangerkun 				 handle_type, nblocks, 0,
1069a70fd5acSyangerkun 				 ext4_trans_default_revoke_credits(sb));
10701139575aSTheodore Ts'o 			if (IS_ERR(handle)) {
10711139575aSTheodore Ts'o 				err = PTR_ERR(handle);
1072eb9cc7e1SJan Kara 				ext4_std_error(sb, err);
1073eb9cc7e1SJan Kara 				goto out;
10741139575aSTheodore Ts'o 			}
10751139575aSTheodore Ts'o 		}
1076ffb5387eSEric Sandeen 		BUFFER_TRACE(inode_bitmap_bh, "get_write_access");
1077ffb5387eSEric Sandeen 		err = ext4_journal_get_write_access(handle, inode_bitmap_bh);
1078eb9cc7e1SJan Kara 		if (err) {
1079eb9cc7e1SJan Kara 			ext4_std_error(sb, err);
1080eb9cc7e1SJan Kara 			goto out;
1081eb9cc7e1SJan Kara 		}
1082119c0d44STheodore Ts'o 		ext4_lock_group(sb, group);
1083119c0d44STheodore Ts'o 		ret2 = ext4_test_and_set_bit(ino, inode_bitmap_bh->b_data);
1084901ed070SWang Shilong 		if (ret2) {
1085901ed070SWang Shilong 			/* Someone already took the bit. Repeat the search
1086901ed070SWang Shilong 			 * with lock held.
1087901ed070SWang Shilong 			 */
1088901ed070SWang Shilong 			ret2 = find_inode_bit(sb, group, inode_bitmap_bh, &ino);
1089901ed070SWang Shilong 			if (ret2) {
1090901ed070SWang Shilong 				ext4_set_bit(ino, inode_bitmap_bh->b_data);
1091901ed070SWang Shilong 				ret2 = 0;
1092901ed070SWang Shilong 			} else {
1093901ed070SWang Shilong 				ret2 = 1; /* we didn't grab the inode */
1094901ed070SWang Shilong 			}
1095901ed070SWang Shilong 		}
1096119c0d44STheodore Ts'o 		ext4_unlock_group(sb, group);
1097119c0d44STheodore Ts'o 		ino++;		/* the inode bitmap is zero-based */
1098119c0d44STheodore Ts'o 		if (!ret2)
1099119c0d44STheodore Ts'o 			goto got; /* we grabbed the inode! */
1100901ed070SWang Shilong 
1101119c0d44STheodore Ts'o 		if (ino < EXT4_INODES_PER_GROUP(sb))
1102119c0d44STheodore Ts'o 			goto repeat_in_this_group;
1103a34eb503STheodore Ts'o next_group:
1104a34eb503STheodore Ts'o 		if (++group == ngroups)
1105a34eb503STheodore Ts'o 			group = 0;
1106ac27a0ecSDave Kleikamp 	}
1107ac27a0ecSDave Kleikamp 	err = -ENOSPC;
1108ac27a0ecSDave Kleikamp 	goto out;
1109ac27a0ecSDave Kleikamp 
1110ac27a0ecSDave Kleikamp got:
1111ffb5387eSEric Sandeen 	BUFFER_TRACE(inode_bitmap_bh, "call ext4_handle_dirty_metadata");
1112ffb5387eSEric Sandeen 	err = ext4_handle_dirty_metadata(handle, NULL, inode_bitmap_bh);
1113eb9cc7e1SJan Kara 	if (err) {
1114eb9cc7e1SJan Kara 		ext4_std_error(sb, err);
1115eb9cc7e1SJan Kara 		goto out;
1116eb9cc7e1SJan Kara 	}
1117ffb5387eSEric Sandeen 
111861c219f5STheodore Ts'o 	BUFFER_TRACE(group_desc_bh, "get_write_access");
111961c219f5STheodore Ts'o 	err = ext4_journal_get_write_access(handle, group_desc_bh);
112061c219f5STheodore Ts'o 	if (err) {
112161c219f5STheodore Ts'o 		ext4_std_error(sb, err);
112261c219f5STheodore Ts'o 		goto out;
112361c219f5STheodore Ts'o 	}
112461c219f5STheodore Ts'o 
1125717d50e4SAndreas Dilger 	/* We may have to initialize the block bitmap if it isn't already */
1126feb0ab32SDarrick J. Wong 	if (ext4_has_group_desc_csum(sb) &&
1127717d50e4SAndreas Dilger 	    gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
11283300bedaSAneesh Kumar K.V 		struct buffer_head *block_bitmap_bh;
1129717d50e4SAndreas Dilger 
11303300bedaSAneesh Kumar K.V 		block_bitmap_bh = ext4_read_block_bitmap(sb, group);
11319008a58eSDarrick J. Wong 		if (IS_ERR(block_bitmap_bh)) {
11329008a58eSDarrick J. Wong 			err = PTR_ERR(block_bitmap_bh);
1133599a9b77SJan Kara 			goto out;
1134599a9b77SJan Kara 		}
11353300bedaSAneesh Kumar K.V 		BUFFER_TRACE(block_bitmap_bh, "get block bitmap access");
11363300bedaSAneesh Kumar K.V 		err = ext4_journal_get_write_access(handle, block_bitmap_bh);
1137717d50e4SAndreas Dilger 		if (err) {
11383300bedaSAneesh Kumar K.V 			brelse(block_bitmap_bh);
1139eb9cc7e1SJan Kara 			ext4_std_error(sb, err);
1140eb9cc7e1SJan Kara 			goto out;
1141717d50e4SAndreas Dilger 		}
1142717d50e4SAndreas Dilger 
1143fd034a84STheodore Ts'o 		BUFFER_TRACE(block_bitmap_bh, "dirty block bitmap");
1144fd034a84STheodore Ts'o 		err = ext4_handle_dirty_metadata(handle, NULL, block_bitmap_bh);
1145fd034a84STheodore Ts'o 
1146717d50e4SAndreas Dilger 		/* recheck and clear flag under lock if we still need to */
1147fd034a84STheodore Ts'o 		ext4_lock_group(sb, group);
11488844618dSTheodore Ts'o 		if (ext4_has_group_desc_csum(sb) &&
11498844618dSTheodore Ts'o 		    (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
11503300bedaSAneesh Kumar K.V 			gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
1151021b65bbSTheodore Ts'o 			ext4_free_group_clusters_set(sb, gdp,
1152cff1dfd7STheodore Ts'o 				ext4_free_clusters_after_init(sb, group, gdp));
1153fa77dcfaSDarrick J. Wong 			ext4_block_bitmap_csum_set(sb, group, gdp,
115479f1ba49STao Ma 						   block_bitmap_bh);
1155feb0ab32SDarrick J. Wong 			ext4_group_desc_csum_set(sb, group, gdp);
1156717d50e4SAndreas Dilger 		}
1157955ce5f5SAneesh Kumar K.V 		ext4_unlock_group(sb, group);
1158aeb1e5d6STheodore Ts'o 		brelse(block_bitmap_bh);
1159717d50e4SAndreas Dilger 
1160eb9cc7e1SJan Kara 		if (err) {
1161eb9cc7e1SJan Kara 			ext4_std_error(sb, err);
1162eb9cc7e1SJan Kara 			goto out;
1163eb9cc7e1SJan Kara 		}
1164717d50e4SAndreas Dilger 	}
1165119c0d44STheodore Ts'o 
1166119c0d44STheodore Ts'o 	/* Update the relevant bg descriptor fields */
116741a246d1SDarrick J. Wong 	if (ext4_has_group_desc_csum(sb)) {
1168119c0d44STheodore Ts'o 		int free;
1169*8016e29fSHarshad Shirwadkar 		struct ext4_group_info *grp = NULL;
1170119c0d44STheodore Ts'o 
1171*8016e29fSHarshad Shirwadkar 		if (!(sbi->s_mount_state & EXT4_FC_REPLAY)) {
1172*8016e29fSHarshad Shirwadkar 			grp = ext4_get_group_info(sb, group);
1173*8016e29fSHarshad Shirwadkar 			down_read(&grp->alloc_sem); /*
1174*8016e29fSHarshad Shirwadkar 						     * protect vs itable
1175*8016e29fSHarshad Shirwadkar 						     * lazyinit
1176*8016e29fSHarshad Shirwadkar 						     */
1177*8016e29fSHarshad Shirwadkar 		}
1178119c0d44STheodore Ts'o 		ext4_lock_group(sb, group); /* while we modify the bg desc */
1179119c0d44STheodore Ts'o 		free = EXT4_INODES_PER_GROUP(sb) -
1180119c0d44STheodore Ts'o 			ext4_itable_unused_count(sb, gdp);
1181119c0d44STheodore Ts'o 		if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {
1182119c0d44STheodore Ts'o 			gdp->bg_flags &= cpu_to_le16(~EXT4_BG_INODE_UNINIT);
1183119c0d44STheodore Ts'o 			free = 0;
1184119c0d44STheodore Ts'o 		}
1185119c0d44STheodore Ts'o 		/*
1186119c0d44STheodore Ts'o 		 * Check the relative inode number against the last used
1187119c0d44STheodore Ts'o 		 * relative inode number in this group. if it is greater
1188119c0d44STheodore Ts'o 		 * we need to update the bg_itable_unused count
1189119c0d44STheodore Ts'o 		 */
1190119c0d44STheodore Ts'o 		if (ino > free)
1191119c0d44STheodore Ts'o 			ext4_itable_unused_set(sb, gdp,
1192119c0d44STheodore Ts'o 					(EXT4_INODES_PER_GROUP(sb) - ino));
1193*8016e29fSHarshad Shirwadkar 		if (!(sbi->s_mount_state & EXT4_FC_REPLAY))
1194119c0d44STheodore Ts'o 			up_read(&grp->alloc_sem);
11956f2e9f0eSTao Ma 	} else {
11966f2e9f0eSTao Ma 		ext4_lock_group(sb, group);
1197119c0d44STheodore Ts'o 	}
11986f2e9f0eSTao Ma 
1199119c0d44STheodore Ts'o 	ext4_free_inodes_set(sb, gdp, ext4_free_inodes_count(sb, gdp) - 1);
1200119c0d44STheodore Ts'o 	if (S_ISDIR(mode)) {
1201119c0d44STheodore Ts'o 		ext4_used_dirs_set(sb, gdp, ext4_used_dirs_count(sb, gdp) + 1);
1202119c0d44STheodore Ts'o 		if (sbi->s_log_groups_per_flex) {
1203119c0d44STheodore Ts'o 			ext4_group_t f = ext4_flex_group(sbi, group);
1204119c0d44STheodore Ts'o 
12057c990728SSuraj Jitindar Singh 			atomic_inc(&sbi_array_rcu_deref(sbi, s_flex_groups,
12067c990728SSuraj Jitindar Singh 							f)->used_dirs);
1207119c0d44STheodore Ts'o 		}
1208119c0d44STheodore Ts'o 	}
120941a246d1SDarrick J. Wong 	if (ext4_has_group_desc_csum(sb)) {
121041a246d1SDarrick J. Wong 		ext4_inode_bitmap_csum_set(sb, group, gdp, inode_bitmap_bh,
121141a246d1SDarrick J. Wong 					   EXT4_INODES_PER_GROUP(sb) / 8);
1212feb0ab32SDarrick J. Wong 		ext4_group_desc_csum_set(sb, group, gdp);
1213119c0d44STheodore Ts'o 	}
12146f2e9f0eSTao Ma 	ext4_unlock_group(sb, group);
1215119c0d44STheodore Ts'o 
12163300bedaSAneesh Kumar K.V 	BUFFER_TRACE(group_desc_bh, "call ext4_handle_dirty_metadata");
12173300bedaSAneesh Kumar K.V 	err = ext4_handle_dirty_metadata(handle, NULL, group_desc_bh);
1218eb9cc7e1SJan Kara 	if (err) {
1219eb9cc7e1SJan Kara 		ext4_std_error(sb, err);
1220eb9cc7e1SJan Kara 		goto out;
1221eb9cc7e1SJan Kara 	}
1222ac27a0ecSDave Kleikamp 
1223ac27a0ecSDave Kleikamp 	percpu_counter_dec(&sbi->s_freeinodes_counter);
1224ac27a0ecSDave Kleikamp 	if (S_ISDIR(mode))
1225ac27a0ecSDave Kleikamp 		percpu_counter_inc(&sbi->s_dirs_counter);
1226ac27a0ecSDave Kleikamp 
1227772cb7c8SJose R. Santos 	if (sbi->s_log_groups_per_flex) {
1228772cb7c8SJose R. Santos 		flex_group = ext4_flex_group(sbi, group);
12297c990728SSuraj Jitindar Singh 		atomic_dec(&sbi_array_rcu_deref(sbi, s_flex_groups,
12307c990728SSuraj Jitindar Singh 						flex_group)->free_inodes);
1231772cb7c8SJose R. Santos 	}
1232ac27a0ecSDave Kleikamp 
1233717d50e4SAndreas Dilger 	inode->i_ino = ino + group * EXT4_INODES_PER_GROUP(sb);
1234ac27a0ecSDave Kleikamp 	/* This is the optimal IO size (for stat), not the fs block size */
1235ac27a0ecSDave Kleikamp 	inode->i_blocks = 0;
123695582b00SDeepa Dinamani 	inode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode);
12377b62b293SArnd Bergmann 	ei->i_crtime = inode->i_mtime;
1238ac27a0ecSDave Kleikamp 
1239ac27a0ecSDave Kleikamp 	memset(ei->i_data, 0, sizeof(ei->i_data));
1240ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
1241ac27a0ecSDave Kleikamp 	ei->i_disksize = 0;
1242ac27a0ecSDave Kleikamp 
12434af83508SEryu Guan 	/* Don't inherit extent flag from directory, amongst others. */
12442dc6b0d4SDuane Griffin 	ei->i_flags =
12452dc6b0d4SDuane Griffin 		ext4_mask_flags(mode, EXT4_I(dir)->i_flags & EXT4_FL_INHERITED);
12461b917ed8STahsin Erdogan 	ei->i_flags |= i_flags;
1247ac27a0ecSDave Kleikamp 	ei->i_file_acl = 0;
1248ac27a0ecSDave Kleikamp 	ei->i_dtime = 0;
1249ac27a0ecSDave Kleikamp 	ei->i_block_group = group;
1250a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
1251ac27a0ecSDave Kleikamp 
1252043546e4SIra Weiny 	ext4_set_inode_flags(inode, true);
1253ac27a0ecSDave Kleikamp 	if (IS_DIRSYNC(inode))
12540390131bSFrank Mayhar 		ext4_handle_sync(handle);
12556b38e842SAl Viro 	if (insert_inode_locked(inode) < 0) {
1256acd6ad83SJan Kara 		/*
1257acd6ad83SJan Kara 		 * Likely a bitmap corruption causing inode to be allocated
1258acd6ad83SJan Kara 		 * twice.
1259acd6ad83SJan Kara 		 */
1260acd6ad83SJan Kara 		err = -EIO;
1261eb9cc7e1SJan Kara 		ext4_error(sb, "failed to insert inode %lu: doubly allocated?",
1262eb9cc7e1SJan Kara 			   inode->i_ino);
1263206f6d55SWang Shilong 		ext4_mark_group_bitmap_corrupted(sb, group,
1264206f6d55SWang Shilong 					EXT4_GROUP_INFO_IBITMAP_CORRUPT);
1265eb9cc7e1SJan Kara 		goto out;
12666b38e842SAl Viro 	}
126723253068STheodore Ts'o 	inode->i_generation = prandom_u32();
1268ac27a0ecSDave Kleikamp 
1269814525f4SDarrick J. Wong 	/* Precompute checksum seed for inode metadata */
12709aa5d32bSDmitry Monakhov 	if (ext4_has_metadata_csum(sb)) {
1271814525f4SDarrick J. Wong 		__u32 csum;
1272814525f4SDarrick J. Wong 		__le32 inum = cpu_to_le32(inode->i_ino);
1273814525f4SDarrick J. Wong 		__le32 gen = cpu_to_le32(inode->i_generation);
1274814525f4SDarrick J. Wong 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
1275814525f4SDarrick J. Wong 				   sizeof(inum));
1276814525f4SDarrick J. Wong 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
1277814525f4SDarrick J. Wong 					      sizeof(gen));
1278814525f4SDarrick J. Wong 	}
1279814525f4SDarrick J. Wong 
1280353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
128119f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_NEW);
1282ef7f3835SKalpak Shah 
128349598e04SJun Piao 	ei->i_extra_isize = sbi->s_want_extra_isize;
1284f08225d1STao Ma 	ei->i_inline_off = 0;
1285e2b911c5SDarrick J. Wong 	if (ext4_has_feature_inline_data(sb))
1286f08225d1STao Ma 		ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
1287ac27a0ecSDave Kleikamp 	ret = inode;
128863936ddaSChristoph Hellwig 	err = dquot_alloc_inode(inode);
128963936ddaSChristoph Hellwig 	if (err)
1290ac27a0ecSDave Kleikamp 		goto fail_drop;
1291ac27a0ecSDave Kleikamp 
1292aa1dca3bSEric Biggers 	/*
1293aa1dca3bSEric Biggers 	 * Since the encryption xattr will always be unique, create it first so
1294aa1dca3bSEric Biggers 	 * that it's less likely to end up in an external xattr block and
1295aa1dca3bSEric Biggers 	 * prevent its deduplication.
1296aa1dca3bSEric Biggers 	 */
1297aa1dca3bSEric Biggers 	if (encrypt) {
1298aa1dca3bSEric Biggers 		err = fscrypt_inherit_context(dir, inode, handle, true);
1299aa1dca3bSEric Biggers 		if (err)
1300aa1dca3bSEric Biggers 			goto fail_free_drop;
1301aa1dca3bSEric Biggers 	}
1302aa1dca3bSEric Biggers 
13031b917ed8STahsin Erdogan 	if (!(ei->i_flags & EXT4_EA_INODE_FL)) {
1304617ba13bSMingming Cao 		err = ext4_init_acl(handle, inode, dir);
1305ac27a0ecSDave Kleikamp 		if (err)
1306ac27a0ecSDave Kleikamp 			goto fail_free_drop;
1307ac27a0ecSDave Kleikamp 
13082a7dba39SEric Paris 		err = ext4_init_security(handle, inode, dir, qstr);
1309ac27a0ecSDave Kleikamp 		if (err)
1310ac27a0ecSDave Kleikamp 			goto fail_free_drop;
1311ad47f953STahsin Erdogan 	}
1312ac27a0ecSDave Kleikamp 
1313e2b911c5SDarrick J. Wong 	if (ext4_has_feature_extents(sb)) {
1314e4079a11SEric Sandeen 		/* set extent flag only for directory, file and normal symlink*/
1315e65187e6SAneesh Kumar K.V 		if (S_ISDIR(mode) || S_ISREG(mode) || S_ISLNK(mode)) {
131612e9b892SDmitry Monakhov 			ext4_set_inode_flag(inode, EXT4_INODE_EXTENTS);
1317a86c6181SAlex Tomas 			ext4_ext_tree_init(handle, inode);
1318a86c6181SAlex Tomas 		}
131942bf0383SAneesh Kumar K.V 	}
1320ac27a0ecSDave Kleikamp 
1321688f869cSTheodore Ts'o 	if (ext4_handle_valid(handle)) {
1322688f869cSTheodore Ts'o 		ei->i_sync_tid = handle->h_transaction->t_tid;
1323688f869cSTheodore Ts'o 		ei->i_datasync_tid = handle->h_transaction->t_tid;
1324688f869cSTheodore Ts'o 	}
1325688f869cSTheodore Ts'o 
13268753e88fSAneesh Kumar K.V 	err = ext4_mark_inode_dirty(handle, inode);
13278753e88fSAneesh Kumar K.V 	if (err) {
13288753e88fSAneesh Kumar K.V 		ext4_std_error(sb, err);
13298753e88fSAneesh Kumar K.V 		goto fail_free_drop;
13308753e88fSAneesh Kumar K.V 	}
13318753e88fSAneesh Kumar K.V 
1332617ba13bSMingming Cao 	ext4_debug("allocating inode %lu\n", inode->i_ino);
13339bffad1eSTheodore Ts'o 	trace_ext4_allocate_inode(inode, dir, mode);
13343300bedaSAneesh Kumar K.V 	brelse(inode_bitmap_bh);
1335ac27a0ecSDave Kleikamp 	return ret;
1336ac27a0ecSDave Kleikamp 
1337ac27a0ecSDave Kleikamp fail_free_drop:
133863936ddaSChristoph Hellwig 	dquot_free_inode(inode);
1339ac27a0ecSDave Kleikamp fail_drop:
13406d6b77f1SMiklos Szeredi 	clear_nlink(inode);
13416b38e842SAl Viro 	unlock_new_inode(inode);
1342eb9cc7e1SJan Kara out:
1343eb9cc7e1SJan Kara 	dquot_drop(inode);
1344eb9cc7e1SJan Kara 	inode->i_flags |= S_NOQUOTA;
1345ac27a0ecSDave Kleikamp 	iput(inode);
13463300bedaSAneesh Kumar K.V 	brelse(inode_bitmap_bh);
1347ac27a0ecSDave Kleikamp 	return ERR_PTR(err);
1348ac27a0ecSDave Kleikamp }
1349ac27a0ecSDave Kleikamp 
1350ac27a0ecSDave Kleikamp /* Verify that we are loading a valid orphan from disk */
1351617ba13bSMingming Cao struct inode *ext4_orphan_get(struct super_block *sb, unsigned long ino)
1352ac27a0ecSDave Kleikamp {
1353617ba13bSMingming Cao 	unsigned long max_ino = le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count);
1354fd2d4291SAvantika Mathur 	ext4_group_t block_group;
1355ac27a0ecSDave Kleikamp 	int bit;
13567827a7f6STheodore Ts'o 	struct buffer_head *bitmap_bh = NULL;
1357ac27a0ecSDave Kleikamp 	struct inode *inode = NULL;
13587827a7f6STheodore Ts'o 	int err = -EFSCORRUPTED;
1359ac27a0ecSDave Kleikamp 
13607827a7f6STheodore Ts'o 	if (ino < EXT4_FIRST_INO(sb) || ino > max_ino)
13617827a7f6STheodore Ts'o 		goto bad_orphan;
1362ac27a0ecSDave Kleikamp 
1363617ba13bSMingming Cao 	block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
1364617ba13bSMingming Cao 	bit = (ino - 1) % EXT4_INODES_PER_GROUP(sb);
1365e29d1cdeSEric Sandeen 	bitmap_bh = ext4_read_inode_bitmap(sb, block_group);
1366206f6d55SWang Shilong 	if (IS_ERR(bitmap_bh))
1367e884bce1SAl Viro 		return ERR_CAST(bitmap_bh);
1368ac27a0ecSDave Kleikamp 
1369ac27a0ecSDave Kleikamp 	/* Having the inode bit set should be a 100% indicator that this
1370ac27a0ecSDave Kleikamp 	 * is a valid orphan (no e2fsck run on fs).  Orphans also include
1371ac27a0ecSDave Kleikamp 	 * inodes that were being truncated, so we can't check i_nlink==0.
1372ac27a0ecSDave Kleikamp 	 */
13731d1fe1eeSDavid Howells 	if (!ext4_test_bit(bit, bitmap_bh->b_data))
13741d1fe1eeSDavid Howells 		goto bad_orphan;
13751d1fe1eeSDavid Howells 
13768a363970STheodore Ts'o 	inode = ext4_iget(sb, ino, EXT4_IGET_NORMAL);
13777827a7f6STheodore Ts'o 	if (IS_ERR(inode)) {
13787827a7f6STheodore Ts'o 		err = PTR_ERR(inode);
137954d3adbcSTheodore Ts'o 		ext4_error_err(sb, -err,
138054d3adbcSTheodore Ts'o 			       "couldn't read orphan inode %lu (err %d)",
13817827a7f6STheodore Ts'o 			       ino, err);
13823bbd0ef2SXiyu Yang 		brelse(bitmap_bh);
13837827a7f6STheodore Ts'o 		return inode;
13847827a7f6STheodore Ts'o 	}
13851d1fe1eeSDavid Howells 
138691ef4cafSDuane Griffin 	/*
1387c9eb13a9STheodore Ts'o 	 * If the orphans has i_nlinks > 0 then it should be able to
1388c9eb13a9STheodore Ts'o 	 * be truncated, otherwise it won't be removed from the orphan
1389c9eb13a9STheodore Ts'o 	 * list during processing and an infinite loop will result.
1390c9eb13a9STheodore Ts'o 	 * Similarly, it must not be a bad inode.
139191ef4cafSDuane Griffin 	 */
1392c9eb13a9STheodore Ts'o 	if ((inode->i_nlink && !ext4_can_truncate(inode)) ||
1393c9eb13a9STheodore Ts'o 	    is_bad_inode(inode))
139491ef4cafSDuane Griffin 		goto bad_orphan;
139591ef4cafSDuane Griffin 
13961d1fe1eeSDavid Howells 	if (NEXT_ORPHAN(inode) > max_ino)
13971d1fe1eeSDavid Howells 		goto bad_orphan;
13981d1fe1eeSDavid Howells 	brelse(bitmap_bh);
13991d1fe1eeSDavid Howells 	return inode;
14001d1fe1eeSDavid Howells 
14011d1fe1eeSDavid Howells bad_orphan:
14027827a7f6STheodore Ts'o 	ext4_error(sb, "bad orphan inode %lu", ino);
14037827a7f6STheodore Ts'o 	if (bitmap_bh)
14047827a7f6STheodore Ts'o 		printk(KERN_ERR "ext4_test_bit(bit=%d, block=%llu) = %d\n",
1405ac27a0ecSDave Kleikamp 		       bit, (unsigned long long)bitmap_bh->b_blocknr,
1406617ba13bSMingming Cao 		       ext4_test_bit(bit, bitmap_bh->b_data));
1407ac27a0ecSDave Kleikamp 	if (inode) {
14087827a7f6STheodore Ts'o 		printk(KERN_ERR "is_bad_inode(inode)=%d\n",
1409ac27a0ecSDave Kleikamp 		       is_bad_inode(inode));
14107827a7f6STheodore Ts'o 		printk(KERN_ERR "NEXT_ORPHAN(inode)=%u\n",
1411ac27a0ecSDave Kleikamp 		       NEXT_ORPHAN(inode));
14127827a7f6STheodore Ts'o 		printk(KERN_ERR "max_ino=%lu\n", max_ino);
14137827a7f6STheodore Ts'o 		printk(KERN_ERR "i_nlink=%u\n", inode->i_nlink);
1414ac27a0ecSDave Kleikamp 		/* Avoid freeing blocks if we got a bad deleted inode */
14151d1fe1eeSDavid Howells 		if (inode->i_nlink == 0)
1416ac27a0ecSDave Kleikamp 			inode->i_blocks = 0;
1417ac27a0ecSDave Kleikamp 		iput(inode);
1418ac27a0ecSDave Kleikamp 	}
1419ac27a0ecSDave Kleikamp 	brelse(bitmap_bh);
14201d1fe1eeSDavid Howells 	return ERR_PTR(err);
1421ac27a0ecSDave Kleikamp }
1422ac27a0ecSDave Kleikamp 
1423617ba13bSMingming Cao unsigned long ext4_count_free_inodes(struct super_block *sb)
1424ac27a0ecSDave Kleikamp {
1425ac27a0ecSDave Kleikamp 	unsigned long desc_count;
1426617ba13bSMingming Cao 	struct ext4_group_desc *gdp;
14278df9675fSTheodore Ts'o 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
1428617ba13bSMingming Cao #ifdef EXT4FS_DEBUG
1429617ba13bSMingming Cao 	struct ext4_super_block *es;
1430ac27a0ecSDave Kleikamp 	unsigned long bitmap_count, x;
1431ac27a0ecSDave Kleikamp 	struct buffer_head *bitmap_bh = NULL;
1432ac27a0ecSDave Kleikamp 
1433617ba13bSMingming Cao 	es = EXT4_SB(sb)->s_es;
1434ac27a0ecSDave Kleikamp 	desc_count = 0;
1435ac27a0ecSDave Kleikamp 	bitmap_count = 0;
1436ac27a0ecSDave Kleikamp 	gdp = NULL;
14378df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
1438617ba13bSMingming Cao 		gdp = ext4_get_group_desc(sb, i, NULL);
1439ac27a0ecSDave Kleikamp 		if (!gdp)
1440ac27a0ecSDave Kleikamp 			continue;
1441560671a0SAneesh Kumar K.V 		desc_count += ext4_free_inodes_count(sb, gdp);
1442ac27a0ecSDave Kleikamp 		brelse(bitmap_bh);
1443e29d1cdeSEric Sandeen 		bitmap_bh = ext4_read_inode_bitmap(sb, i);
14449008a58eSDarrick J. Wong 		if (IS_ERR(bitmap_bh)) {
14459008a58eSDarrick J. Wong 			bitmap_bh = NULL;
1446ac27a0ecSDave Kleikamp 			continue;
14479008a58eSDarrick J. Wong 		}
1448ac27a0ecSDave Kleikamp 
1449f6fb99caSTheodore Ts'o 		x = ext4_count_free(bitmap_bh->b_data,
1450f6fb99caSTheodore Ts'o 				    EXT4_INODES_PER_GROUP(sb) / 8);
1451c549a95dSEric Sandeen 		printk(KERN_DEBUG "group %lu: stored = %d, counted = %lu\n",
1452785b4b3aSPeng Tao 			(unsigned long) i, ext4_free_inodes_count(sb, gdp), x);
1453ac27a0ecSDave Kleikamp 		bitmap_count += x;
1454ac27a0ecSDave Kleikamp 	}
1455ac27a0ecSDave Kleikamp 	brelse(bitmap_bh);
14564776004fSTheodore Ts'o 	printk(KERN_DEBUG "ext4_count_free_inodes: "
14574776004fSTheodore Ts'o 	       "stored = %u, computed = %lu, %lu\n",
1458ac27a0ecSDave Kleikamp 	       le32_to_cpu(es->s_free_inodes_count), desc_count, bitmap_count);
1459ac27a0ecSDave Kleikamp 	return desc_count;
1460ac27a0ecSDave Kleikamp #else
1461ac27a0ecSDave Kleikamp 	desc_count = 0;
14628df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
1463617ba13bSMingming Cao 		gdp = ext4_get_group_desc(sb, i, NULL);
1464ac27a0ecSDave Kleikamp 		if (!gdp)
1465ac27a0ecSDave Kleikamp 			continue;
1466560671a0SAneesh Kumar K.V 		desc_count += ext4_free_inodes_count(sb, gdp);
1467ac27a0ecSDave Kleikamp 		cond_resched();
1468ac27a0ecSDave Kleikamp 	}
1469ac27a0ecSDave Kleikamp 	return desc_count;
1470ac27a0ecSDave Kleikamp #endif
1471ac27a0ecSDave Kleikamp }
1472ac27a0ecSDave Kleikamp 
1473ac27a0ecSDave Kleikamp /* Called at mount-time, super-block is locked */
1474617ba13bSMingming Cao unsigned long ext4_count_dirs(struct super_block * sb)
1475ac27a0ecSDave Kleikamp {
1476ac27a0ecSDave Kleikamp 	unsigned long count = 0;
14778df9675fSTheodore Ts'o 	ext4_group_t i, ngroups = ext4_get_groups_count(sb);
1478ac27a0ecSDave Kleikamp 
14798df9675fSTheodore Ts'o 	for (i = 0; i < ngroups; i++) {
1480617ba13bSMingming Cao 		struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
1481ac27a0ecSDave Kleikamp 		if (!gdp)
1482ac27a0ecSDave Kleikamp 			continue;
1483560671a0SAneesh Kumar K.V 		count += ext4_used_dirs_count(sb, gdp);
1484ac27a0ecSDave Kleikamp 	}
1485ac27a0ecSDave Kleikamp 	return count;
1486ac27a0ecSDave Kleikamp }
1487bfff6873SLukas Czerner 
1488bfff6873SLukas Czerner /*
1489bfff6873SLukas Czerner  * Zeroes not yet zeroed inode table - just write zeroes through the whole
1490bfff6873SLukas Czerner  * inode table. Must be called without any spinlock held. The only place
1491bfff6873SLukas Czerner  * where it is called from on active part of filesystem is ext4lazyinit
1492bfff6873SLukas Czerner  * thread, so we do not need any special locks, however we have to prevent
1493bfff6873SLukas Czerner  * inode allocation from the current group, so we take alloc_sem lock, to
1494119c0d44STheodore Ts'o  * block ext4_new_inode() until we are finished.
1495bfff6873SLukas Czerner  */
1496e0cbee3eSH Hartley Sweeten int ext4_init_inode_table(struct super_block *sb, ext4_group_t group,
1497bfff6873SLukas Czerner 				 int barrier)
1498bfff6873SLukas Czerner {
1499bfff6873SLukas Czerner 	struct ext4_group_info *grp = ext4_get_group_info(sb, group);
1500bfff6873SLukas Czerner 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1501bfff6873SLukas Czerner 	struct ext4_group_desc *gdp = NULL;
1502bfff6873SLukas Czerner 	struct buffer_head *group_desc_bh;
1503bfff6873SLukas Czerner 	handle_t *handle;
1504bfff6873SLukas Czerner 	ext4_fsblk_t blk;
1505bfff6873SLukas Czerner 	int num, ret = 0, used_blks = 0;
1506bfff6873SLukas Czerner 
1507bfff6873SLukas Czerner 	/* This should not happen, but just to be sure check this */
1508bc98a42cSDavid Howells 	if (sb_rdonly(sb)) {
1509bfff6873SLukas Czerner 		ret = 1;
1510bfff6873SLukas Czerner 		goto out;
1511bfff6873SLukas Czerner 	}
1512bfff6873SLukas Czerner 
1513bfff6873SLukas Czerner 	gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
1514bfff6873SLukas Czerner 	if (!gdp)
1515bfff6873SLukas Czerner 		goto out;
1516bfff6873SLukas Czerner 
1517bfff6873SLukas Czerner 	/*
1518bfff6873SLukas Czerner 	 * We do not need to lock this, because we are the only one
1519bfff6873SLukas Czerner 	 * handling this flag.
1520bfff6873SLukas Czerner 	 */
1521bfff6873SLukas Czerner 	if (gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED))
1522bfff6873SLukas Czerner 		goto out;
1523bfff6873SLukas Czerner 
15249924a92aSTheodore Ts'o 	handle = ext4_journal_start_sb(sb, EXT4_HT_MISC, 1);
1525bfff6873SLukas Czerner 	if (IS_ERR(handle)) {
1526bfff6873SLukas Czerner 		ret = PTR_ERR(handle);
1527bfff6873SLukas Czerner 		goto out;
1528bfff6873SLukas Czerner 	}
1529bfff6873SLukas Czerner 
1530bfff6873SLukas Czerner 	down_write(&grp->alloc_sem);
1531bfff6873SLukas Czerner 	/*
1532bfff6873SLukas Czerner 	 * If inode bitmap was already initialized there may be some
1533bfff6873SLukas Czerner 	 * used inodes so we need to skip blocks with used inodes in
1534bfff6873SLukas Czerner 	 * inode table.
1535bfff6873SLukas Czerner 	 */
1536bfff6873SLukas Czerner 	if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)))
1537bfff6873SLukas Czerner 		used_blks = DIV_ROUND_UP((EXT4_INODES_PER_GROUP(sb) -
1538bfff6873SLukas Czerner 			    ext4_itable_unused_count(sb, gdp)),
1539bfff6873SLukas Czerner 			    sbi->s_inodes_per_block);
1540bfff6873SLukas Czerner 
154150122847STheodore Ts'o 	if ((used_blks < 0) || (used_blks > sbi->s_itb_per_group) ||
154250122847STheodore Ts'o 	    ((group == 0) && ((EXT4_INODES_PER_GROUP(sb) -
154350122847STheodore Ts'o 			       ext4_itable_unused_count(sb, gdp)) <
154450122847STheodore Ts'o 			      EXT4_FIRST_INO(sb)))) {
15451084f252STheodore Ts'o 		ext4_error(sb, "Something is wrong with group %u: "
15461084f252STheodore Ts'o 			   "used itable blocks: %d; "
15471084f252STheodore Ts'o 			   "itable unused count: %u",
1548857ac889SLukas Czerner 			   group, used_blks,
1549857ac889SLukas Czerner 			   ext4_itable_unused_count(sb, gdp));
1550857ac889SLukas Czerner 		ret = 1;
155133853a0dSYongqiang Yang 		goto err_out;
1552857ac889SLukas Czerner 	}
1553857ac889SLukas Czerner 
1554bfff6873SLukas Czerner 	blk = ext4_inode_table(sb, gdp) + used_blks;
1555bfff6873SLukas Czerner 	num = sbi->s_itb_per_group - used_blks;
1556bfff6873SLukas Czerner 
1557bfff6873SLukas Czerner 	BUFFER_TRACE(group_desc_bh, "get_write_access");
1558bfff6873SLukas Czerner 	ret = ext4_journal_get_write_access(handle,
1559bfff6873SLukas Czerner 					    group_desc_bh);
1560bfff6873SLukas Czerner 	if (ret)
1561bfff6873SLukas Czerner 		goto err_out;
1562bfff6873SLukas Czerner 
1563bfff6873SLukas Czerner 	/*
1564bfff6873SLukas Czerner 	 * Skip zeroout if the inode table is full. But we set the ZEROED
1565bfff6873SLukas Czerner 	 * flag anyway, because obviously, when it is full it does not need
1566bfff6873SLukas Czerner 	 * further zeroing.
1567bfff6873SLukas Czerner 	 */
1568bfff6873SLukas Czerner 	if (unlikely(num == 0))
1569bfff6873SLukas Czerner 		goto skip_zeroout;
1570bfff6873SLukas Czerner 
1571bfff6873SLukas Czerner 	ext4_debug("going to zero out inode table in group %d\n",
1572bfff6873SLukas Czerner 		   group);
1573a107e5a3STheodore Ts'o 	ret = sb_issue_zeroout(sb, blk, num, GFP_NOFS);
1574bfff6873SLukas Czerner 	if (ret < 0)
1575bfff6873SLukas Czerner 		goto err_out;
1576a107e5a3STheodore Ts'o 	if (barrier)
15779398554fSChristoph Hellwig 		blkdev_issue_flush(sb->s_bdev, GFP_NOFS);
1578bfff6873SLukas Czerner 
1579bfff6873SLukas Czerner skip_zeroout:
1580bfff6873SLukas Czerner 	ext4_lock_group(sb, group);
1581bfff6873SLukas Czerner 	gdp->bg_flags |= cpu_to_le16(EXT4_BG_INODE_ZEROED);
1582feb0ab32SDarrick J. Wong 	ext4_group_desc_csum_set(sb, group, gdp);
1583bfff6873SLukas Czerner 	ext4_unlock_group(sb, group);
1584bfff6873SLukas Czerner 
1585bfff6873SLukas Czerner 	BUFFER_TRACE(group_desc_bh,
1586bfff6873SLukas Czerner 		     "call ext4_handle_dirty_metadata");
1587bfff6873SLukas Czerner 	ret = ext4_handle_dirty_metadata(handle, NULL,
1588bfff6873SLukas Czerner 					 group_desc_bh);
1589bfff6873SLukas Czerner 
1590bfff6873SLukas Czerner err_out:
1591bfff6873SLukas Czerner 	up_write(&grp->alloc_sem);
1592bfff6873SLukas Czerner 	ext4_journal_stop(handle);
1593bfff6873SLukas Czerner out:
1594bfff6873SLukas Czerner 	return ret;
1595bfff6873SLukas Czerner }
1596