xref: /openbmc/linux/fs/ext4/inode.c (revision b27c82e1296572cfa3997e58db3118a33915f85c)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2ac27a0ecSDave Kleikamp /*
3617ba13bSMingming Cao  *  linux/fs/ext4/inode.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  *  from
11ac27a0ecSDave Kleikamp  *
12ac27a0ecSDave Kleikamp  *  linux/fs/minix/inode.c
13ac27a0ecSDave Kleikamp  *
14ac27a0ecSDave Kleikamp  *  Copyright (C) 1991, 1992  Linus Torvalds
15ac27a0ecSDave Kleikamp  *
16ac27a0ecSDave Kleikamp  *  64-bit file support on 64-bit platforms by Jakub Jelinek
17ac27a0ecSDave Kleikamp  *	(jj@sunsite.ms.mff.cuni.cz)
18ac27a0ecSDave Kleikamp  *
19617ba13bSMingming Cao  *  Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
20ac27a0ecSDave Kleikamp  */
21ac27a0ecSDave Kleikamp 
22ac27a0ecSDave Kleikamp #include <linux/fs.h>
2314f3db55SChristian Brauner #include <linux/mount.h>
24ac27a0ecSDave Kleikamp #include <linux/time.h>
25ac27a0ecSDave Kleikamp #include <linux/highuid.h>
26ac27a0ecSDave Kleikamp #include <linux/pagemap.h>
27c94c2acfSMatthew Wilcox #include <linux/dax.h>
28ac27a0ecSDave Kleikamp #include <linux/quotaops.h>
29ac27a0ecSDave Kleikamp #include <linux/string.h>
30ac27a0ecSDave Kleikamp #include <linux/buffer_head.h>
31ac27a0ecSDave Kleikamp #include <linux/writeback.h>
3264769240SAlex Tomas #include <linux/pagevec.h>
33ac27a0ecSDave Kleikamp #include <linux/mpage.h>
34e83c1397SDuane Griffin #include <linux/namei.h>
35ac27a0ecSDave Kleikamp #include <linux/uio.h>
36ac27a0ecSDave Kleikamp #include <linux/bio.h>
374c0425ffSMingming Cao #include <linux/workqueue.h>
38744692dcSJiaying Zhang #include <linux/kernel.h>
396db26ffcSAndrew Morton #include <linux/printk.h>
405a0e3ad6STejun Heo #include <linux/slab.h>
4100a1a053STheodore Ts'o #include <linux/bitops.h>
42364443cbSJan Kara #include <linux/iomap.h>
43ae5e165dSJeff Layton #include <linux/iversion.h>
449bffad1eSTheodore Ts'o 
453dcf5451SChristoph Hellwig #include "ext4_jbd2.h"
46ac27a0ecSDave Kleikamp #include "xattr.h"
47ac27a0ecSDave Kleikamp #include "acl.h"
489f125d64STheodore Ts'o #include "truncate.h"
49ac27a0ecSDave Kleikamp 
509bffad1eSTheodore Ts'o #include <trace/events/ext4.h>
519bffad1eSTheodore Ts'o 
52814525f4SDarrick J. Wong static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
53814525f4SDarrick J. Wong 			      struct ext4_inode_info *ei)
54814525f4SDarrick J. Wong {
55814525f4SDarrick J. Wong 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
56814525f4SDarrick J. Wong 	__u32 csum;
57b47820edSDaeho Jeong 	__u16 dummy_csum = 0;
58b47820edSDaeho Jeong 	int offset = offsetof(struct ext4_inode, i_checksum_lo);
59b47820edSDaeho Jeong 	unsigned int csum_size = sizeof(dummy_csum);
60814525f4SDarrick J. Wong 
61b47820edSDaeho Jeong 	csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
62b47820edSDaeho Jeong 	csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
63b47820edSDaeho Jeong 	offset += csum_size;
64b47820edSDaeho Jeong 	csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
65b47820edSDaeho Jeong 			   EXT4_GOOD_OLD_INODE_SIZE - offset);
66b47820edSDaeho Jeong 
67b47820edSDaeho Jeong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
68b47820edSDaeho Jeong 		offset = offsetof(struct ext4_inode, i_checksum_hi);
69b47820edSDaeho Jeong 		csum = ext4_chksum(sbi, csum, (__u8 *)raw +
70b47820edSDaeho Jeong 				   EXT4_GOOD_OLD_INODE_SIZE,
71b47820edSDaeho Jeong 				   offset - EXT4_GOOD_OLD_INODE_SIZE);
72b47820edSDaeho Jeong 		if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
73b47820edSDaeho Jeong 			csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
74b47820edSDaeho Jeong 					   csum_size);
75b47820edSDaeho Jeong 			offset += csum_size;
76814525f4SDarrick J. Wong 		}
7705ac5aa1SDaeho Jeong 		csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
7805ac5aa1SDaeho Jeong 				   EXT4_INODE_SIZE(inode->i_sb) - offset);
79b47820edSDaeho Jeong 	}
80814525f4SDarrick J. Wong 
81814525f4SDarrick J. Wong 	return csum;
82814525f4SDarrick J. Wong }
83814525f4SDarrick J. Wong 
84814525f4SDarrick J. Wong static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
85814525f4SDarrick J. Wong 				  struct ext4_inode_info *ei)
86814525f4SDarrick J. Wong {
87814525f4SDarrick J. Wong 	__u32 provided, calculated;
88814525f4SDarrick J. Wong 
89814525f4SDarrick J. Wong 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
90814525f4SDarrick J. Wong 	    cpu_to_le32(EXT4_OS_LINUX) ||
919aa5d32bSDmitry Monakhov 	    !ext4_has_metadata_csum(inode->i_sb))
92814525f4SDarrick J. Wong 		return 1;
93814525f4SDarrick J. Wong 
94814525f4SDarrick J. Wong 	provided = le16_to_cpu(raw->i_checksum_lo);
95814525f4SDarrick J. Wong 	calculated = ext4_inode_csum(inode, raw, ei);
96814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
97814525f4SDarrick J. Wong 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
98814525f4SDarrick J. Wong 		provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
99814525f4SDarrick J. Wong 	else
100814525f4SDarrick J. Wong 		calculated &= 0xFFFF;
101814525f4SDarrick J. Wong 
102814525f4SDarrick J. Wong 	return provided == calculated;
103814525f4SDarrick J. Wong }
104814525f4SDarrick J. Wong 
1058016e29fSHarshad Shirwadkar void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
106814525f4SDarrick J. Wong 			 struct ext4_inode_info *ei)
107814525f4SDarrick J. Wong {
108814525f4SDarrick J. Wong 	__u32 csum;
109814525f4SDarrick J. Wong 
110814525f4SDarrick J. Wong 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
111814525f4SDarrick J. Wong 	    cpu_to_le32(EXT4_OS_LINUX) ||
1129aa5d32bSDmitry Monakhov 	    !ext4_has_metadata_csum(inode->i_sb))
113814525f4SDarrick J. Wong 		return;
114814525f4SDarrick J. Wong 
115814525f4SDarrick J. Wong 	csum = ext4_inode_csum(inode, raw, ei);
116814525f4SDarrick J. Wong 	raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
117814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
118814525f4SDarrick J. Wong 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
119814525f4SDarrick J. Wong 		raw->i_checksum_hi = cpu_to_le16(csum >> 16);
120814525f4SDarrick J. Wong }
121814525f4SDarrick J. Wong 
122678aaf48SJan Kara static inline int ext4_begin_ordered_truncate(struct inode *inode,
123678aaf48SJan Kara 					      loff_t new_size)
124678aaf48SJan Kara {
1257ff9c073STheodore Ts'o 	trace_ext4_begin_ordered_truncate(inode, new_size);
1268aefcd55STheodore Ts'o 	/*
1278aefcd55STheodore Ts'o 	 * If jinode is zero, then we never opened the file for
1288aefcd55STheodore Ts'o 	 * writing, so there's no need to call
1298aefcd55STheodore Ts'o 	 * jbd2_journal_begin_ordered_truncate() since there's no
1308aefcd55STheodore Ts'o 	 * outstanding writes we need to flush.
1318aefcd55STheodore Ts'o 	 */
1328aefcd55STheodore Ts'o 	if (!EXT4_I(inode)->jinode)
1338aefcd55STheodore Ts'o 		return 0;
1348aefcd55STheodore Ts'o 	return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
1358aefcd55STheodore Ts'o 						   EXT4_I(inode)->jinode,
136678aaf48SJan Kara 						   new_size);
137678aaf48SJan Kara }
138678aaf48SJan Kara 
139cb20d518STheodore Ts'o static int __ext4_journalled_writepage(struct page *page, unsigned int len);
140dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
141dec214d0STahsin Erdogan 				  int pextents);
14264769240SAlex Tomas 
143ac27a0ecSDave Kleikamp /*
144ac27a0ecSDave Kleikamp  * Test whether an inode is a fast symlink.
145407cd7fbSTahsin Erdogan  * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
146ac27a0ecSDave Kleikamp  */
147f348c252STheodore Ts'o int ext4_inode_is_fast_symlink(struct inode *inode)
148ac27a0ecSDave Kleikamp {
149fc82228aSAndi Kleen 	if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
150fc82228aSAndi Kleen 		int ea_blocks = EXT4_I(inode)->i_file_acl ?
151fc82228aSAndi Kleen 				EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
152fc82228aSAndi Kleen 
153fc82228aSAndi Kleen 		if (ext4_has_inline_data(inode))
154fc82228aSAndi Kleen 			return 0;
155fc82228aSAndi Kleen 
156fc82228aSAndi Kleen 		return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
157fc82228aSAndi Kleen 	}
158407cd7fbSTahsin Erdogan 	return S_ISLNK(inode->i_mode) && inode->i_size &&
159407cd7fbSTahsin Erdogan 	       (inode->i_size < EXT4_N_BLOCKS * 4);
160ac27a0ecSDave Kleikamp }
161ac27a0ecSDave Kleikamp 
162ac27a0ecSDave Kleikamp /*
163ac27a0ecSDave Kleikamp  * Called at the last iput() if i_nlink is zero.
164ac27a0ecSDave Kleikamp  */
1650930fcc1SAl Viro void ext4_evict_inode(struct inode *inode)
166ac27a0ecSDave Kleikamp {
167ac27a0ecSDave Kleikamp 	handle_t *handle;
168bc965ab3STheodore Ts'o 	int err;
16965db869cSJan Kara 	/*
17065db869cSJan Kara 	 * Credits for final inode cleanup and freeing:
17165db869cSJan Kara 	 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
17265db869cSJan Kara 	 * (xattr block freeing), bitmap, group descriptor (inode freeing)
17365db869cSJan Kara 	 */
17465db869cSJan Kara 	int extra_credits = 6;
1750421a189STahsin Erdogan 	struct ext4_xattr_inode_array *ea_inode_array = NULL;
17646e294efSJan Kara 	bool freeze_protected = false;
177ac27a0ecSDave Kleikamp 
1787ff9c073STheodore Ts'o 	trace_ext4_evict_inode(inode);
1792581fdc8SJiaying Zhang 
1800930fcc1SAl Viro 	if (inode->i_nlink) {
1812d859db3SJan Kara 		/*
1822d859db3SJan Kara 		 * When journalling data dirty buffers are tracked only in the
1832d859db3SJan Kara 		 * journal. So although mm thinks everything is clean and
1842d859db3SJan Kara 		 * ready for reaping the inode might still have some pages to
1852d859db3SJan Kara 		 * write in the running transaction or waiting to be
186ccd16945SMatthew Wilcox (Oracle) 		 * checkpointed. Thus calling jbd2_journal_invalidate_folio()
1872d859db3SJan Kara 		 * (via truncate_inode_pages()) to discard these buffers can
1882d859db3SJan Kara 		 * cause data loss. Also even if we did not discard these
1892d859db3SJan Kara 		 * buffers, we would have no way to find them after the inode
1902d859db3SJan Kara 		 * is reaped and thus user could see stale data if he tries to
1912d859db3SJan Kara 		 * read them before the transaction is checkpointed. So be
1922d859db3SJan Kara 		 * careful and force everything to disk here... We use
1932d859db3SJan Kara 		 * ei->i_datasync_tid to store the newest transaction
1942d859db3SJan Kara 		 * containing inode's data.
1952d859db3SJan Kara 		 *
1962d859db3SJan Kara 		 * Note that directories do not have this problem because they
1972d859db3SJan Kara 		 * don't use page cache.
1982d859db3SJan Kara 		 */
1996a7fd522SVegard Nossum 		if (inode->i_ino != EXT4_JOURNAL_INO &&
2006a7fd522SVegard Nossum 		    ext4_should_journal_data(inode) &&
2016493792dSZhang Yi 		    S_ISREG(inode->i_mode) && inode->i_data.nrpages) {
2022d859db3SJan Kara 			journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
2032d859db3SJan Kara 			tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
2042d859db3SJan Kara 
205d76a3a77STheodore Ts'o 			jbd2_complete_transaction(journal, commit_tid);
2062d859db3SJan Kara 			filemap_write_and_wait(&inode->i_data);
2072d859db3SJan Kara 		}
20891b0abe3SJohannes Weiner 		truncate_inode_pages_final(&inode->i_data);
2095dc23bddSJan Kara 
2100930fcc1SAl Viro 		goto no_delete;
2110930fcc1SAl Viro 	}
2120930fcc1SAl Viro 
213e2bfb088STheodore Ts'o 	if (is_bad_inode(inode))
214e2bfb088STheodore Ts'o 		goto no_delete;
215871a2931SChristoph Hellwig 	dquot_initialize(inode);
216907f4554SChristoph Hellwig 
217678aaf48SJan Kara 	if (ext4_should_order_data(inode))
218678aaf48SJan Kara 		ext4_begin_ordered_truncate(inode, 0);
21991b0abe3SJohannes Weiner 	truncate_inode_pages_final(&inode->i_data);
220ac27a0ecSDave Kleikamp 
2218e8ad8a5SJan Kara 	/*
222ceff86fdSJan Kara 	 * For inodes with journalled data, transaction commit could have
223ceff86fdSJan Kara 	 * dirtied the inode. Flush worker is ignoring it because of I_FREEING
224ceff86fdSJan Kara 	 * flag but we still need to remove the inode from the writeback lists.
225ceff86fdSJan Kara 	 */
226ceff86fdSJan Kara 	if (!list_empty_careful(&inode->i_io_list)) {
227ceff86fdSJan Kara 		WARN_ON_ONCE(!ext4_should_journal_data(inode));
228ceff86fdSJan Kara 		inode_io_list_del(inode);
229ceff86fdSJan Kara 	}
230ceff86fdSJan Kara 
231ceff86fdSJan Kara 	/*
2328e8ad8a5SJan Kara 	 * Protect us against freezing - iput() caller didn't have to have any
23346e294efSJan Kara 	 * protection against it. When we are in a running transaction though,
23446e294efSJan Kara 	 * we are already protected against freezing and we cannot grab further
23546e294efSJan Kara 	 * protection due to lock ordering constraints.
2368e8ad8a5SJan Kara 	 */
23746e294efSJan Kara 	if (!ext4_journal_current_handle()) {
2388e8ad8a5SJan Kara 		sb_start_intwrite(inode->i_sb);
23946e294efSJan Kara 		freeze_protected = true;
24046e294efSJan Kara 	}
241e50e5129SAndreas Dilger 
24230a7eb97STahsin Erdogan 	if (!IS_NOQUOTA(inode))
24330a7eb97STahsin Erdogan 		extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
24430a7eb97STahsin Erdogan 
24565db869cSJan Kara 	/*
24665db869cSJan Kara 	 * Block bitmap, group descriptor, and inode are accounted in both
24765db869cSJan Kara 	 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
24865db869cSJan Kara 	 */
24930a7eb97STahsin Erdogan 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
25065db869cSJan Kara 			 ext4_blocks_for_truncate(inode) + extra_credits - 3);
251ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
252bc965ab3STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
253ac27a0ecSDave Kleikamp 		/*
254ac27a0ecSDave Kleikamp 		 * If we're going to skip the normal cleanup, we still need to
255ac27a0ecSDave Kleikamp 		 * make sure that the in-core orphan linked list is properly
256ac27a0ecSDave Kleikamp 		 * cleaned up.
257ac27a0ecSDave Kleikamp 		 */
258617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
25946e294efSJan Kara 		if (freeze_protected)
2608e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
261ac27a0ecSDave Kleikamp 		goto no_delete;
262ac27a0ecSDave Kleikamp 	}
26330a7eb97STahsin Erdogan 
264ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
2650390131bSFrank Mayhar 		ext4_handle_sync(handle);
266407cd7fbSTahsin Erdogan 
267407cd7fbSTahsin Erdogan 	/*
268407cd7fbSTahsin Erdogan 	 * Set inode->i_size to 0 before calling ext4_truncate(). We need
269407cd7fbSTahsin Erdogan 	 * special handling of symlinks here because i_size is used to
270407cd7fbSTahsin Erdogan 	 * determine whether ext4_inode_info->i_data contains symlink data or
271407cd7fbSTahsin Erdogan 	 * block mappings. Setting i_size to 0 will remove its fast symlink
272407cd7fbSTahsin Erdogan 	 * status. Erase i_data so that it becomes a valid empty block map.
273407cd7fbSTahsin Erdogan 	 */
274407cd7fbSTahsin Erdogan 	if (ext4_inode_is_fast_symlink(inode))
275407cd7fbSTahsin Erdogan 		memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
276ac27a0ecSDave Kleikamp 	inode->i_size = 0;
277bc965ab3STheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
278bc965ab3STheodore Ts'o 	if (err) {
27912062dddSEric Sandeen 		ext4_warning(inode->i_sb,
280bc965ab3STheodore Ts'o 			     "couldn't mark inode dirty (err %d)", err);
281bc965ab3STheodore Ts'o 		goto stop_handle;
282bc965ab3STheodore Ts'o 	}
2832c98eb5eSTheodore Ts'o 	if (inode->i_blocks) {
2842c98eb5eSTheodore Ts'o 		err = ext4_truncate(inode);
2852c98eb5eSTheodore Ts'o 		if (err) {
28654d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err,
2872c98eb5eSTheodore Ts'o 				       "couldn't truncate inode %lu (err %d)",
2882c98eb5eSTheodore Ts'o 				       inode->i_ino, err);
2892c98eb5eSTheodore Ts'o 			goto stop_handle;
2902c98eb5eSTheodore Ts'o 		}
2912c98eb5eSTheodore Ts'o 	}
292bc965ab3STheodore Ts'o 
29330a7eb97STahsin Erdogan 	/* Remove xattr references. */
29430a7eb97STahsin Erdogan 	err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
29530a7eb97STahsin Erdogan 				      extra_credits);
29630a7eb97STahsin Erdogan 	if (err) {
29730a7eb97STahsin Erdogan 		ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
298bc965ab3STheodore Ts'o stop_handle:
299bc965ab3STheodore Ts'o 		ext4_journal_stop(handle);
30045388219STheodore Ts'o 		ext4_orphan_del(NULL, inode);
30146e294efSJan Kara 		if (freeze_protected)
3028e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
30330a7eb97STahsin Erdogan 		ext4_xattr_inode_array_free(ea_inode_array);
304bc965ab3STheodore Ts'o 		goto no_delete;
305bc965ab3STheodore Ts'o 	}
306bc965ab3STheodore Ts'o 
307ac27a0ecSDave Kleikamp 	/*
308617ba13bSMingming Cao 	 * Kill off the orphan record which ext4_truncate created.
309ac27a0ecSDave Kleikamp 	 * AKPM: I think this can be inside the above `if'.
310617ba13bSMingming Cao 	 * Note that ext4_orphan_del() has to be able to cope with the
311ac27a0ecSDave Kleikamp 	 * deletion of a non-existent orphan - this is because we don't
312617ba13bSMingming Cao 	 * know if ext4_truncate() actually created an orphan record.
313ac27a0ecSDave Kleikamp 	 * (Well, we could do this if we need to, but heck - it works)
314ac27a0ecSDave Kleikamp 	 */
315617ba13bSMingming Cao 	ext4_orphan_del(handle, inode);
3165ffff834SArnd Bergmann 	EXT4_I(inode)->i_dtime	= (__u32)ktime_get_real_seconds();
317ac27a0ecSDave Kleikamp 
318ac27a0ecSDave Kleikamp 	/*
319ac27a0ecSDave Kleikamp 	 * One subtle ordering requirement: if anything has gone wrong
320ac27a0ecSDave Kleikamp 	 * (transaction abort, IO errors, whatever), then we can still
321ac27a0ecSDave Kleikamp 	 * do these next steps (the fs will already have been marked as
322ac27a0ecSDave Kleikamp 	 * having errors), but we can't free the inode if the mark_dirty
323ac27a0ecSDave Kleikamp 	 * fails.
324ac27a0ecSDave Kleikamp 	 */
325617ba13bSMingming Cao 	if (ext4_mark_inode_dirty(handle, inode))
326ac27a0ecSDave Kleikamp 		/* If that failed, just do the required in-core inode clear. */
3270930fcc1SAl Viro 		ext4_clear_inode(inode);
328ac27a0ecSDave Kleikamp 	else
329617ba13bSMingming Cao 		ext4_free_inode(handle, inode);
330617ba13bSMingming Cao 	ext4_journal_stop(handle);
33146e294efSJan Kara 	if (freeze_protected)
3328e8ad8a5SJan Kara 		sb_end_intwrite(inode->i_sb);
3330421a189STahsin Erdogan 	ext4_xattr_inode_array_free(ea_inode_array);
334ac27a0ecSDave Kleikamp 	return;
335ac27a0ecSDave Kleikamp no_delete:
336b21ebf14SHarshad Shirwadkar 	if (!list_empty(&EXT4_I(inode)->i_fc_list))
337e85c81baSXin Yin 		ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
3380930fcc1SAl Viro 	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
339ac27a0ecSDave Kleikamp }
340ac27a0ecSDave Kleikamp 
341a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
342a9e7f447SDmitry Monakhov qsize_t *ext4_get_reserved_space(struct inode *inode)
34360e58e0fSMingming Cao {
344a9e7f447SDmitry Monakhov 	return &EXT4_I(inode)->i_reserved_quota;
34560e58e0fSMingming Cao }
346a9e7f447SDmitry Monakhov #endif
3479d0be502STheodore Ts'o 
34812219aeaSAneesh Kumar K.V /*
3490637c6f4STheodore Ts'o  * Called with i_data_sem down, which is important since we can call
3500637c6f4STheodore Ts'o  * ext4_discard_preallocations() from here.
3510637c6f4STheodore Ts'o  */
3525f634d06SAneesh Kumar K.V void ext4_da_update_reserve_space(struct inode *inode,
3535f634d06SAneesh Kumar K.V 					int used, int quota_claim)
35412219aeaSAneesh Kumar K.V {
35512219aeaSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3560637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
35712219aeaSAneesh Kumar K.V 
3580637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
359d8990240SAditya Kali 	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
3600637c6f4STheodore Ts'o 	if (unlikely(used > ei->i_reserved_data_blocks)) {
3618de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
3621084f252STheodore Ts'o 			 "with only %d reserved data blocks",
3630637c6f4STheodore Ts'o 			 __func__, inode->i_ino, used,
3640637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
3650637c6f4STheodore Ts'o 		WARN_ON(1);
3660637c6f4STheodore Ts'o 		used = ei->i_reserved_data_blocks;
3676bc6e63fSAneesh Kumar K.V 	}
36812219aeaSAneesh Kumar K.V 
3690637c6f4STheodore Ts'o 	/* Update per-inode reservations */
3700637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= used;
37171d4f7d0STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
3720637c6f4STheodore Ts'o 
373f9505c72Schenyichong 	spin_unlock(&ei->i_block_reservation_lock);
37460e58e0fSMingming Cao 
37572b8ab9dSEric Sandeen 	/* Update quota subsystem for data blocks */
37672b8ab9dSEric Sandeen 	if (quota_claim)
3777b415bf6SAditya Kali 		dquot_claim_block(inode, EXT4_C2B(sbi, used));
37872b8ab9dSEric Sandeen 	else {
3795f634d06SAneesh Kumar K.V 		/*
3805f634d06SAneesh Kumar K.V 		 * We did fallocate with an offset that is already delayed
3815f634d06SAneesh Kumar K.V 		 * allocated. So on delayed allocated writeback we should
38272b8ab9dSEric Sandeen 		 * not re-claim the quota for fallocated blocks.
3835f634d06SAneesh Kumar K.V 		 */
3847b415bf6SAditya Kali 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
3855f634d06SAneesh Kumar K.V 	}
386d6014301SAneesh Kumar K.V 
387d6014301SAneesh Kumar K.V 	/*
388d6014301SAneesh Kumar K.V 	 * If we have done all the pending block allocations and if
389d6014301SAneesh Kumar K.V 	 * there aren't any writers on the inode, we can discard the
390d6014301SAneesh Kumar K.V 	 * inode's preallocations.
391d6014301SAneesh Kumar K.V 	 */
3920637c6f4STheodore Ts'o 	if ((ei->i_reserved_data_blocks == 0) &&
39382dd124cSNikolay Borisov 	    !inode_is_open_for_write(inode))
39427bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
39512219aeaSAneesh Kumar K.V }
39612219aeaSAneesh Kumar K.V 
397e29136f8STheodore Ts'o static int __check_block_validity(struct inode *inode, const char *func,
398c398eda0STheodore Ts'o 				unsigned int line,
39924676da4STheodore Ts'o 				struct ext4_map_blocks *map)
4006fd058f7STheodore Ts'o {
401345c0dbfSTheodore Ts'o 	if (ext4_has_feature_journal(inode->i_sb) &&
402345c0dbfSTheodore Ts'o 	    (inode->i_ino ==
403345c0dbfSTheodore Ts'o 	     le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
404345c0dbfSTheodore Ts'o 		return 0;
405ce9f24ccSJan Kara 	if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
406c398eda0STheodore Ts'o 		ext4_error_inode(inode, func, line, map->m_pblk,
407bdbd6ce0STheodore Ts'o 				 "lblock %lu mapped to illegal pblock %llu "
40824676da4STheodore Ts'o 				 "(length %d)", (unsigned long) map->m_lblk,
409bdbd6ce0STheodore Ts'o 				 map->m_pblk, map->m_len);
4106a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4116fd058f7STheodore Ts'o 	}
4126fd058f7STheodore Ts'o 	return 0;
4136fd058f7STheodore Ts'o }
4146fd058f7STheodore Ts'o 
41553085facSJan Kara int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
41653085facSJan Kara 		       ext4_lblk_t len)
41753085facSJan Kara {
41853085facSJan Kara 	int ret;
41953085facSJan Kara 
42033b4cc25SEric Biggers 	if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
421a7550b30SJaegeuk Kim 		return fscrypt_zeroout_range(inode, lblk, pblk, len);
42253085facSJan Kara 
42353085facSJan Kara 	ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
42453085facSJan Kara 	if (ret > 0)
42553085facSJan Kara 		ret = 0;
42653085facSJan Kara 
42753085facSJan Kara 	return ret;
42853085facSJan Kara }
42953085facSJan Kara 
430e29136f8STheodore Ts'o #define check_block_validity(inode, map)	\
431c398eda0STheodore Ts'o 	__check_block_validity((inode), __func__, __LINE__, (map))
432e29136f8STheodore Ts'o 
433921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
434921f266bSDmitry Monakhov static void ext4_map_blocks_es_recheck(handle_t *handle,
435921f266bSDmitry Monakhov 				       struct inode *inode,
436921f266bSDmitry Monakhov 				       struct ext4_map_blocks *es_map,
437921f266bSDmitry Monakhov 				       struct ext4_map_blocks *map,
438921f266bSDmitry Monakhov 				       int flags)
439921f266bSDmitry Monakhov {
440921f266bSDmitry Monakhov 	int retval;
441921f266bSDmitry Monakhov 
442921f266bSDmitry Monakhov 	map->m_flags = 0;
443921f266bSDmitry Monakhov 	/*
444921f266bSDmitry Monakhov 	 * There is a race window that the result is not the same.
445921f266bSDmitry Monakhov 	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
446921f266bSDmitry Monakhov 	 * is that we lookup a block mapping in extent status tree with
447921f266bSDmitry Monakhov 	 * out taking i_data_sem.  So at the time the unwritten extent
448921f266bSDmitry Monakhov 	 * could be converted.
449921f266bSDmitry Monakhov 	 */
450c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
451921f266bSDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4529e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
453921f266bSDmitry Monakhov 	} else {
4549e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
455921f266bSDmitry Monakhov 	}
456921f266bSDmitry Monakhov 	up_read((&EXT4_I(inode)->i_data_sem));
457921f266bSDmitry Monakhov 
458921f266bSDmitry Monakhov 	/*
459921f266bSDmitry Monakhov 	 * We don't check m_len because extent will be collpased in status
460921f266bSDmitry Monakhov 	 * tree.  So the m_len might not equal.
461921f266bSDmitry Monakhov 	 */
462921f266bSDmitry Monakhov 	if (es_map->m_lblk != map->m_lblk ||
463921f266bSDmitry Monakhov 	    es_map->m_flags != map->m_flags ||
464921f266bSDmitry Monakhov 	    es_map->m_pblk != map->m_pblk) {
465bdafe42aSTheodore Ts'o 		printk("ES cache assertion failed for inode: %lu "
466921f266bSDmitry Monakhov 		       "es_cached ex [%d/%d/%llu/%x] != "
467921f266bSDmitry Monakhov 		       "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
468921f266bSDmitry Monakhov 		       inode->i_ino, es_map->m_lblk, es_map->m_len,
469921f266bSDmitry Monakhov 		       es_map->m_pblk, es_map->m_flags, map->m_lblk,
470921f266bSDmitry Monakhov 		       map->m_len, map->m_pblk, map->m_flags,
471921f266bSDmitry Monakhov 		       retval, flags);
472921f266bSDmitry Monakhov 	}
473921f266bSDmitry Monakhov }
474921f266bSDmitry Monakhov #endif /* ES_AGGRESSIVE_TEST */
475921f266bSDmitry Monakhov 
47655138e0bSTheodore Ts'o /*
477e35fd660STheodore Ts'o  * The ext4_map_blocks() function tries to look up the requested blocks,
4782b2d6d01STheodore Ts'o  * and returns if the blocks are already mapped.
479f5ab0d1fSMingming Cao  *
480f5ab0d1fSMingming Cao  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
481f5ab0d1fSMingming Cao  * and store the allocated blocks in the result buffer head and mark it
482f5ab0d1fSMingming Cao  * mapped.
483f5ab0d1fSMingming Cao  *
484e35fd660STheodore Ts'o  * If file type is extents based, it will call ext4_ext_map_blocks(),
485e35fd660STheodore Ts'o  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
486f5ab0d1fSMingming Cao  * based files
487f5ab0d1fSMingming Cao  *
488facab4d9SJan Kara  * On success, it returns the number of blocks being mapped or allocated.  if
489facab4d9SJan Kara  * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
490facab4d9SJan Kara  * is marked as unwritten. If the create == 1, it will mark @map as mapped.
491f5ab0d1fSMingming Cao  *
492f5ab0d1fSMingming Cao  * It returns 0 if plain look up failed (blocks have not been allocated), in
493facab4d9SJan Kara  * that case, @map is returned as unmapped but we still do fill map->m_len to
494facab4d9SJan Kara  * indicate the length of a hole starting at map->m_lblk.
495f5ab0d1fSMingming Cao  *
496f5ab0d1fSMingming Cao  * It returns the error in case of allocation failure.
497f5ab0d1fSMingming Cao  */
498e35fd660STheodore Ts'o int ext4_map_blocks(handle_t *handle, struct inode *inode,
499e35fd660STheodore Ts'o 		    struct ext4_map_blocks *map, int flags)
5000e855ac8SAneesh Kumar K.V {
501d100eef2SZheng Liu 	struct extent_status es;
5020e855ac8SAneesh Kumar K.V 	int retval;
503b8a86845SLukas Czerner 	int ret = 0;
504921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
505921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
506921f266bSDmitry Monakhov 
507921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
508921f266bSDmitry Monakhov #endif
509f5ab0d1fSMingming Cao 
510e35fd660STheodore Ts'o 	map->m_flags = 0;
51170aa1554SRitesh Harjani 	ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
51270aa1554SRitesh Harjani 		  flags, map->m_len, (unsigned long) map->m_lblk);
513d100eef2SZheng Liu 
514e861b5e9STheodore Ts'o 	/*
515e861b5e9STheodore Ts'o 	 * ext4_map_blocks returns an int, and m_len is an unsigned int
516e861b5e9STheodore Ts'o 	 */
517e861b5e9STheodore Ts'o 	if (unlikely(map->m_len > INT_MAX))
518e861b5e9STheodore Ts'o 		map->m_len = INT_MAX;
519e861b5e9STheodore Ts'o 
5204adb6ab3SKazuya Mio 	/* We can handle the block number less than EXT_MAX_BLOCKS */
5214adb6ab3SKazuya Mio 	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
5226a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
5234adb6ab3SKazuya Mio 
524d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
5258016e29fSHarshad Shirwadkar 	if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
5268016e29fSHarshad Shirwadkar 	    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
527d100eef2SZheng Liu 		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
528d100eef2SZheng Liu 			map->m_pblk = ext4_es_pblock(&es) +
529d100eef2SZheng Liu 					map->m_lblk - es.es_lblk;
530d100eef2SZheng Liu 			map->m_flags |= ext4_es_is_written(&es) ?
531d100eef2SZheng Liu 					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
532d100eef2SZheng Liu 			retval = es.es_len - (map->m_lblk - es.es_lblk);
533d100eef2SZheng Liu 			if (retval > map->m_len)
534d100eef2SZheng Liu 				retval = map->m_len;
535d100eef2SZheng Liu 			map->m_len = retval;
536d100eef2SZheng Liu 		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
537facab4d9SJan Kara 			map->m_pblk = 0;
538facab4d9SJan Kara 			retval = es.es_len - (map->m_lblk - es.es_lblk);
539facab4d9SJan Kara 			if (retval > map->m_len)
540facab4d9SJan Kara 				retval = map->m_len;
541facab4d9SJan Kara 			map->m_len = retval;
542d100eef2SZheng Liu 			retval = 0;
543d100eef2SZheng Liu 		} else {
5441e83bc81SArnd Bergmann 			BUG();
545d100eef2SZheng Liu 		}
5469558cf14SZhang Yi 
5479558cf14SZhang Yi 		if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5489558cf14SZhang Yi 			return retval;
549921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
550921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(handle, inode, map,
551921f266bSDmitry Monakhov 					   &orig_map, flags);
552921f266bSDmitry Monakhov #endif
553d100eef2SZheng Liu 		goto found;
554d100eef2SZheng Liu 	}
5559558cf14SZhang Yi 	/*
5569558cf14SZhang Yi 	 * In the query cache no-wait mode, nothing we can do more if we
5579558cf14SZhang Yi 	 * cannot find extent in the cache.
5589558cf14SZhang Yi 	 */
5599558cf14SZhang Yi 	if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5609558cf14SZhang Yi 		return 0;
561d100eef2SZheng Liu 
5624df3d265SAneesh Kumar K.V 	/*
563b920c755STheodore Ts'o 	 * Try to see if we can get the block without requesting a new
564b920c755STheodore Ts'o 	 * file system block.
5654df3d265SAneesh Kumar K.V 	 */
566c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
56712e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5689e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
5694df3d265SAneesh Kumar K.V 	} else {
5709e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
5710e855ac8SAneesh Kumar K.V 	}
572f7fec032SZheng Liu 	if (retval > 0) {
5733be78c73STheodore Ts'o 		unsigned int status;
574f7fec032SZheng Liu 
57544fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
57644fb851dSZheng Liu 			ext4_warning(inode->i_sb,
57744fb851dSZheng Liu 				     "ES len assertion failed for inode "
57844fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
57944fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
58044fb851dSZheng Liu 			WARN_ON(1);
581921f266bSDmitry Monakhov 		}
582921f266bSDmitry Monakhov 
583f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
584f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
585f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
586d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
587ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
588f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
589f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
590f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk,
591f7fec032SZheng Liu 					    map->m_len, map->m_pblk, status);
592f7fec032SZheng Liu 		if (ret < 0)
593f7fec032SZheng Liu 			retval = ret;
594f7fec032SZheng Liu 	}
5954df3d265SAneesh Kumar K.V 	up_read((&EXT4_I(inode)->i_data_sem));
596f5ab0d1fSMingming Cao 
597d100eef2SZheng Liu found:
598e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
599b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
6006fd058f7STheodore Ts'o 		if (ret != 0)
6016fd058f7STheodore Ts'o 			return ret;
6026fd058f7STheodore Ts'o 	}
6036fd058f7STheodore Ts'o 
604f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
605c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
6064df3d265SAneesh Kumar K.V 		return retval;
6074df3d265SAneesh Kumar K.V 
6084df3d265SAneesh Kumar K.V 	/*
609f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
610f5ab0d1fSMingming Cao 	 *
611f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
612df3ab170STao Ma 	 * ext4_ext_get_block() returns the create = 0
613f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
614f5ab0d1fSMingming Cao 	 */
615e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
616b8a86845SLukas Czerner 		/*
617b8a86845SLukas Czerner 		 * If we need to convert extent to unwritten
618b8a86845SLukas Czerner 		 * we continue and do the actual work in
619b8a86845SLukas Czerner 		 * ext4_ext_map_blocks()
620b8a86845SLukas Czerner 		 */
621b8a86845SLukas Czerner 		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
622f5ab0d1fSMingming Cao 			return retval;
623f5ab0d1fSMingming Cao 
624f5ab0d1fSMingming Cao 	/*
625a25a4e1aSZheng Liu 	 * Here we clear m_flags because after allocating an new extent,
626a25a4e1aSZheng Liu 	 * it will be set again.
6272a8964d6SAneesh Kumar K.V 	 */
628a25a4e1aSZheng Liu 	map->m_flags &= ~EXT4_MAP_FLAGS;
6292a8964d6SAneesh Kumar K.V 
6302a8964d6SAneesh Kumar K.V 	/*
631556615dcSLukas Czerner 	 * New blocks allocate and/or writing to unwritten extent
632f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
633d91bd2c1SSeunghun Lee 	 * the write lock of i_data_sem, and call get_block()
634f5ab0d1fSMingming Cao 	 * with create == 1 flag.
6354df3d265SAneesh Kumar K.V 	 */
636c8b459f4SLukas Czerner 	down_write(&EXT4_I(inode)->i_data_sem);
637d2a17637SMingming Cao 
638d2a17637SMingming Cao 	/*
6394df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
6404df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
6414df3d265SAneesh Kumar K.V 	 */
64212e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
643e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
6440e855ac8SAneesh Kumar K.V 	} else {
645e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
646267e4db9SAneesh Kumar K.V 
647e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
648267e4db9SAneesh Kumar K.V 			/*
649267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
650267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
651267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
652267e4db9SAneesh Kumar K.V 			 */
65319f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
654267e4db9SAneesh Kumar K.V 		}
6552ac3b6e0STheodore Ts'o 
656d2a17637SMingming Cao 		/*
6572ac3b6e0STheodore Ts'o 		 * Update reserved blocks/metadata blocks after successful
6585f634d06SAneesh Kumar K.V 		 * block allocation which had been deferred till now. We don't
6595f634d06SAneesh Kumar K.V 		 * support fallocate for non extent files. So we can update
6605f634d06SAneesh Kumar K.V 		 * reserve space here.
661d2a17637SMingming Cao 		 */
6625f634d06SAneesh Kumar K.V 		if ((retval > 0) &&
6631296cc85SAneesh Kumar K.V 			(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
6645f634d06SAneesh Kumar K.V 			ext4_da_update_reserve_space(inode, retval, 1);
6655f634d06SAneesh Kumar K.V 	}
666d2a17637SMingming Cao 
667f7fec032SZheng Liu 	if (retval > 0) {
6683be78c73STheodore Ts'o 		unsigned int status;
669f7fec032SZheng Liu 
67044fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
67144fb851dSZheng Liu 			ext4_warning(inode->i_sb,
67244fb851dSZheng Liu 				     "ES len assertion failed for inode "
67344fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
67444fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
67544fb851dSZheng Liu 			WARN_ON(1);
676921f266bSDmitry Monakhov 		}
677921f266bSDmitry Monakhov 
678adb23551SZheng Liu 		/*
679c86d8db3SJan Kara 		 * We have to zeroout blocks before inserting them into extent
680c86d8db3SJan Kara 		 * status tree. Otherwise someone could look them up there and
6819b623df6SJan Kara 		 * use them before they are really zeroed. We also have to
6829b623df6SJan Kara 		 * unmap metadata before zeroing as otherwise writeback can
6839b623df6SJan Kara 		 * overwrite zeros with stale data from block device.
684c86d8db3SJan Kara 		 */
685c86d8db3SJan Kara 		if (flags & EXT4_GET_BLOCKS_ZERO &&
686c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_MAPPED &&
687c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_NEW) {
688c86d8db3SJan Kara 			ret = ext4_issue_zeroout(inode, map->m_lblk,
689c86d8db3SJan Kara 						 map->m_pblk, map->m_len);
690c86d8db3SJan Kara 			if (ret) {
691c86d8db3SJan Kara 				retval = ret;
692c86d8db3SJan Kara 				goto out_sem;
693c86d8db3SJan Kara 			}
694c86d8db3SJan Kara 		}
695c86d8db3SJan Kara 
696c86d8db3SJan Kara 		/*
697adb23551SZheng Liu 		 * If the extent has been zeroed out, we don't need to update
698adb23551SZheng Liu 		 * extent status tree.
699adb23551SZheng Liu 		 */
700adb23551SZheng Liu 		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
701bb5835edSTheodore Ts'o 		    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
702adb23551SZheng Liu 			if (ext4_es_is_written(&es))
703c86d8db3SJan Kara 				goto out_sem;
704adb23551SZheng Liu 		}
705f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
706f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
707f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
708d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
709ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
710f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
711f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
712f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
713f7fec032SZheng Liu 					    map->m_pblk, status);
714c86d8db3SJan Kara 		if (ret < 0) {
71551865fdaSZheng Liu 			retval = ret;
716c86d8db3SJan Kara 			goto out_sem;
717c86d8db3SJan Kara 		}
71851865fdaSZheng Liu 	}
7195356f261SAditya Kali 
720c86d8db3SJan Kara out_sem:
7210e855ac8SAneesh Kumar K.V 	up_write((&EXT4_I(inode)->i_data_sem));
722e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
723b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
7246fd058f7STheodore Ts'o 		if (ret != 0)
7256fd058f7STheodore Ts'o 			return ret;
72606bd3c36SJan Kara 
72706bd3c36SJan Kara 		/*
72806bd3c36SJan Kara 		 * Inodes with freshly allocated blocks where contents will be
72906bd3c36SJan Kara 		 * visible after transaction commit must be on transaction's
73006bd3c36SJan Kara 		 * ordered data list.
73106bd3c36SJan Kara 		 */
73206bd3c36SJan Kara 		if (map->m_flags & EXT4_MAP_NEW &&
73306bd3c36SJan Kara 		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
73406bd3c36SJan Kara 		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
73502749a4cSTahsin Erdogan 		    !ext4_is_quota_file(inode) &&
73606bd3c36SJan Kara 		    ext4_should_order_data(inode)) {
73773131fbbSRoss Zwisler 			loff_t start_byte =
73873131fbbSRoss Zwisler 				(loff_t)map->m_lblk << inode->i_blkbits;
73973131fbbSRoss Zwisler 			loff_t length = (loff_t)map->m_len << inode->i_blkbits;
74073131fbbSRoss Zwisler 
741ee0876bcSJan Kara 			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
74273131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_wait(handle, inode,
74373131fbbSRoss Zwisler 						start_byte, length);
744ee0876bcSJan Kara 			else
74573131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_write(handle, inode,
74673131fbbSRoss Zwisler 						start_byte, length);
74706bd3c36SJan Kara 			if (ret)
74806bd3c36SJan Kara 				return ret;
74906bd3c36SJan Kara 		}
7505e4d0ebaSXin Yin 	}
7515e4d0ebaSXin Yin 	if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
7525e4d0ebaSXin Yin 				map->m_flags & EXT4_MAP_MAPPED))
753a80f7fcfSHarshad Shirwadkar 		ext4_fc_track_range(handle, inode, map->m_lblk,
754aa75f4d3SHarshad Shirwadkar 					map->m_lblk + map->m_len - 1);
755ec8c60beSRitesh Harjani 	if (retval < 0)
75670aa1554SRitesh Harjani 		ext_debug(inode, "failed with err %d\n", retval);
7570e855ac8SAneesh Kumar K.V 	return retval;
7580e855ac8SAneesh Kumar K.V }
7590e855ac8SAneesh Kumar K.V 
760ed8ad838SJan Kara /*
761ed8ad838SJan Kara  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
762ed8ad838SJan Kara  * we have to be careful as someone else may be manipulating b_state as well.
763ed8ad838SJan Kara  */
764ed8ad838SJan Kara static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
765ed8ad838SJan Kara {
766ed8ad838SJan Kara 	unsigned long old_state;
767ed8ad838SJan Kara 	unsigned long new_state;
768ed8ad838SJan Kara 
769ed8ad838SJan Kara 	flags &= EXT4_MAP_FLAGS;
770ed8ad838SJan Kara 
771ed8ad838SJan Kara 	/* Dummy buffer_head? Set non-atomically. */
772ed8ad838SJan Kara 	if (!bh->b_page) {
773ed8ad838SJan Kara 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
774ed8ad838SJan Kara 		return;
775ed8ad838SJan Kara 	}
776ed8ad838SJan Kara 	/*
777ed8ad838SJan Kara 	 * Someone else may be modifying b_state. Be careful! This is ugly but
778ed8ad838SJan Kara 	 * once we get rid of using bh as a container for mapping information
779ed8ad838SJan Kara 	 * to pass to / from get_block functions, this can go away.
780ed8ad838SJan Kara 	 */
781ed8ad838SJan Kara 	do {
782ed8ad838SJan Kara 		old_state = READ_ONCE(bh->b_state);
783ed8ad838SJan Kara 		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
784ed8ad838SJan Kara 	} while (unlikely(
785ed8ad838SJan Kara 		 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
786ed8ad838SJan Kara }
787ed8ad838SJan Kara 
7882ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
7892ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
790ac27a0ecSDave Kleikamp {
7912ed88685STheodore Ts'o 	struct ext4_map_blocks map;
792efe70c29SJan Kara 	int ret = 0;
793ac27a0ecSDave Kleikamp 
79446c7f254STao Ma 	if (ext4_has_inline_data(inode))
79546c7f254STao Ma 		return -ERANGE;
79646c7f254STao Ma 
7972ed88685STheodore Ts'o 	map.m_lblk = iblock;
7982ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
7992ed88685STheodore Ts'o 
800efe70c29SJan Kara 	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
801efe70c29SJan Kara 			      flags);
802ac27a0ecSDave Kleikamp 	if (ret > 0) {
8032ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
804ed8ad838SJan Kara 		ext4_update_bh_state(bh, map.m_flags);
8052ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
806ac27a0ecSDave Kleikamp 		ret = 0;
807547edce3SRoss Zwisler 	} else if (ret == 0) {
808547edce3SRoss Zwisler 		/* hole case, need to fill in bh->b_size */
809547edce3SRoss Zwisler 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
810ac27a0ecSDave Kleikamp 	}
811ac27a0ecSDave Kleikamp 	return ret;
812ac27a0ecSDave Kleikamp }
813ac27a0ecSDave Kleikamp 
8142ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
8152ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
8162ed88685STheodore Ts'o {
8172ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
8182ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
8192ed88685STheodore Ts'o }
8202ed88685STheodore Ts'o 
821ac27a0ecSDave Kleikamp /*
822705965bdSJan Kara  * Get block function used when preparing for buffered write if we require
823705965bdSJan Kara  * creating an unwritten extent if blocks haven't been allocated.  The extent
824705965bdSJan Kara  * will be converted to written after the IO is complete.
825705965bdSJan Kara  */
826705965bdSJan Kara int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
827705965bdSJan Kara 			     struct buffer_head *bh_result, int create)
828705965bdSJan Kara {
829705965bdSJan Kara 	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
830705965bdSJan Kara 		   inode->i_ino, create);
831705965bdSJan Kara 	return _ext4_get_block(inode, iblock, bh_result,
8328d5459c1SJan Kara 			       EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
833705965bdSJan Kara }
834705965bdSJan Kara 
835efe70c29SJan Kara /* Maximum number of blocks we map for direct IO at once. */
836efe70c29SJan Kara #define DIO_MAX_BLOCKS 4096
837efe70c29SJan Kara 
838e84dfbe2SJan Kara /*
839ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
840ac27a0ecSDave Kleikamp  */
841617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
842c5e298aeSTheodore Ts'o 				ext4_lblk_t block, int map_flags)
843ac27a0ecSDave Kleikamp {
8442ed88685STheodore Ts'o 	struct ext4_map_blocks map;
8452ed88685STheodore Ts'o 	struct buffer_head *bh;
846c5e298aeSTheodore Ts'o 	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
8479558cf14SZhang Yi 	bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
84810560082STheodore Ts'o 	int err;
849ac27a0ecSDave Kleikamp 
850837c23fbSChunguang Xu 	ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8518016e29fSHarshad Shirwadkar 		    || handle != NULL || create == 0);
8529558cf14SZhang Yi 	ASSERT(create == 0 || !nowait);
853ac27a0ecSDave Kleikamp 
8542ed88685STheodore Ts'o 	map.m_lblk = block;
8552ed88685STheodore Ts'o 	map.m_len = 1;
856c5e298aeSTheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map, map_flags);
8572ed88685STheodore Ts'o 
85810560082STheodore Ts'o 	if (err == 0)
85910560082STheodore Ts'o 		return create ? ERR_PTR(-ENOSPC) : NULL;
8602ed88685STheodore Ts'o 	if (err < 0)
86110560082STheodore Ts'o 		return ERR_PTR(err);
8622ed88685STheodore Ts'o 
8639558cf14SZhang Yi 	if (nowait)
8649558cf14SZhang Yi 		return sb_find_get_block(inode->i_sb, map.m_pblk);
8659558cf14SZhang Yi 
8662ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
86710560082STheodore Ts'o 	if (unlikely(!bh))
86810560082STheodore Ts'o 		return ERR_PTR(-ENOMEM);
8692ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
870837c23fbSChunguang Xu 		ASSERT(create != 0);
871837c23fbSChunguang Xu 		ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8728016e29fSHarshad Shirwadkar 			    || (handle != NULL));
873ac27a0ecSDave Kleikamp 
874ac27a0ecSDave Kleikamp 		/*
875ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
876ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
877ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
878617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
879ac27a0ecSDave Kleikamp 		 * problem.
880ac27a0ecSDave Kleikamp 		 */
881ac27a0ecSDave Kleikamp 		lock_buffer(bh);
882ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
883188c299eSJan Kara 		err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
884188c299eSJan Kara 						     EXT4_JTR_NONE);
88510560082STheodore Ts'o 		if (unlikely(err)) {
88610560082STheodore Ts'o 			unlock_buffer(bh);
88710560082STheodore Ts'o 			goto errout;
88810560082STheodore Ts'o 		}
88910560082STheodore Ts'o 		if (!buffer_uptodate(bh)) {
890ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
891ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
892ac27a0ecSDave Kleikamp 		}
893ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
8940390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
8950390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
89610560082STheodore Ts'o 		if (unlikely(err))
89710560082STheodore Ts'o 			goto errout;
89810560082STheodore Ts'o 	} else
899ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
900ac27a0ecSDave Kleikamp 	return bh;
90110560082STheodore Ts'o errout:
90210560082STheodore Ts'o 	brelse(bh);
90310560082STheodore Ts'o 	return ERR_PTR(err);
904ac27a0ecSDave Kleikamp }
905ac27a0ecSDave Kleikamp 
906617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
907c5e298aeSTheodore Ts'o 			       ext4_lblk_t block, int map_flags)
908ac27a0ecSDave Kleikamp {
909ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
9102d069c08Szhangyi (F) 	int ret;
911ac27a0ecSDave Kleikamp 
912c5e298aeSTheodore Ts'o 	bh = ext4_getblk(handle, inode, block, map_flags);
9131c215028STheodore Ts'o 	if (IS_ERR(bh))
914ac27a0ecSDave Kleikamp 		return bh;
9157963e5acSZhangXiaoxu 	if (!bh || ext4_buffer_uptodate(bh))
916ac27a0ecSDave Kleikamp 		return bh;
9172d069c08Szhangyi (F) 
9182d069c08Szhangyi (F) 	ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
9192d069c08Szhangyi (F) 	if (ret) {
920ac27a0ecSDave Kleikamp 		put_bh(bh);
9212d069c08Szhangyi (F) 		return ERR_PTR(ret);
9222d069c08Szhangyi (F) 	}
9232d069c08Szhangyi (F) 	return bh;
924ac27a0ecSDave Kleikamp }
925ac27a0ecSDave Kleikamp 
9269699d4f9STahsin Erdogan /* Read a contiguous batch of blocks. */
9279699d4f9STahsin Erdogan int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
9289699d4f9STahsin Erdogan 		     bool wait, struct buffer_head **bhs)
9299699d4f9STahsin Erdogan {
9309699d4f9STahsin Erdogan 	int i, err;
9319699d4f9STahsin Erdogan 
9329699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9339699d4f9STahsin Erdogan 		bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
9349699d4f9STahsin Erdogan 		if (IS_ERR(bhs[i])) {
9359699d4f9STahsin Erdogan 			err = PTR_ERR(bhs[i]);
9369699d4f9STahsin Erdogan 			bh_count = i;
9379699d4f9STahsin Erdogan 			goto out_brelse;
9389699d4f9STahsin Erdogan 		}
9399699d4f9STahsin Erdogan 	}
9409699d4f9STahsin Erdogan 
9419699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9429699d4f9STahsin Erdogan 		/* Note that NULL bhs[i] is valid because of holes. */
9432d069c08Szhangyi (F) 		if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
9442d069c08Szhangyi (F) 			ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
9459699d4f9STahsin Erdogan 
9469699d4f9STahsin Erdogan 	if (!wait)
9479699d4f9STahsin Erdogan 		return 0;
9489699d4f9STahsin Erdogan 
9499699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9509699d4f9STahsin Erdogan 		if (bhs[i])
9519699d4f9STahsin Erdogan 			wait_on_buffer(bhs[i]);
9529699d4f9STahsin Erdogan 
9539699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9549699d4f9STahsin Erdogan 		if (bhs[i] && !buffer_uptodate(bhs[i])) {
9559699d4f9STahsin Erdogan 			err = -EIO;
9569699d4f9STahsin Erdogan 			goto out_brelse;
9579699d4f9STahsin Erdogan 		}
9589699d4f9STahsin Erdogan 	}
9599699d4f9STahsin Erdogan 	return 0;
9609699d4f9STahsin Erdogan 
9619699d4f9STahsin Erdogan out_brelse:
9629699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9639699d4f9STahsin Erdogan 		brelse(bhs[i]);
9649699d4f9STahsin Erdogan 		bhs[i] = NULL;
9659699d4f9STahsin Erdogan 	}
9669699d4f9STahsin Erdogan 	return err;
9679699d4f9STahsin Erdogan }
9689699d4f9STahsin Erdogan 
969188c299eSJan Kara int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
970ac27a0ecSDave Kleikamp 			   struct buffer_head *head,
971ac27a0ecSDave Kleikamp 			   unsigned from,
972ac27a0ecSDave Kleikamp 			   unsigned to,
973ac27a0ecSDave Kleikamp 			   int *partial,
974188c299eSJan Kara 			   int (*fn)(handle_t *handle, struct inode *inode,
975ac27a0ecSDave Kleikamp 				     struct buffer_head *bh))
976ac27a0ecSDave Kleikamp {
977ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
978ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
979ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
980ac27a0ecSDave Kleikamp 	int err, ret = 0;
981ac27a0ecSDave Kleikamp 	struct buffer_head *next;
982ac27a0ecSDave Kleikamp 
983ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
984ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
985de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
986ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
987ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
988ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
989ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
990ac27a0ecSDave Kleikamp 				*partial = 1;
991ac27a0ecSDave Kleikamp 			continue;
992ac27a0ecSDave Kleikamp 		}
993188c299eSJan Kara 		err = (*fn)(handle, inode, bh);
994ac27a0ecSDave Kleikamp 		if (!ret)
995ac27a0ecSDave Kleikamp 			ret = err;
996ac27a0ecSDave Kleikamp 	}
997ac27a0ecSDave Kleikamp 	return ret;
998ac27a0ecSDave Kleikamp }
999ac27a0ecSDave Kleikamp 
1000ac27a0ecSDave Kleikamp /*
1001ac27a0ecSDave Kleikamp  * To preserve ordering, it is essential that the hole instantiation and
1002ac27a0ecSDave Kleikamp  * the data write be encapsulated in a single transaction.  We cannot
1003617ba13bSMingming Cao  * close off a transaction and start a new one between the ext4_get_block()
1004dab291afSMingming Cao  * and the commit_write().  So doing the jbd2_journal_start at the start of
1005ac27a0ecSDave Kleikamp  * prepare_write() is the right place.
1006ac27a0ecSDave Kleikamp  *
100736ade451SJan Kara  * Also, this function can nest inside ext4_writepage().  In that case, we
100836ade451SJan Kara  * *know* that ext4_writepage() has generated enough buffer credits to do the
100936ade451SJan Kara  * whole page.  So we won't block on the journal in that case, which is good,
101036ade451SJan Kara  * because the caller may be PF_MEMALLOC.
1011ac27a0ecSDave Kleikamp  *
1012617ba13bSMingming Cao  * By accident, ext4 can be reentered when a transaction is open via
1013ac27a0ecSDave Kleikamp  * quota file writes.  If we were to commit the transaction while thus
1014ac27a0ecSDave Kleikamp  * reentered, there can be a deadlock - we would be holding a quota
1015ac27a0ecSDave Kleikamp  * lock, and the commit would never complete if another thread had a
1016ac27a0ecSDave Kleikamp  * transaction open and was blocking on the quota lock - a ranking
1017ac27a0ecSDave Kleikamp  * violation.
1018ac27a0ecSDave Kleikamp  *
1019dab291afSMingming Cao  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1020ac27a0ecSDave Kleikamp  * will _not_ run commit under these circumstances because handle->h_ref
1021ac27a0ecSDave Kleikamp  * is elevated.  We'll still have enough credits for the tiny quotafile
1022ac27a0ecSDave Kleikamp  * write.
1023ac27a0ecSDave Kleikamp  */
1024188c299eSJan Kara int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1025ac27a0ecSDave Kleikamp 				struct buffer_head *bh)
1026ac27a0ecSDave Kleikamp {
102756d35a4cSJan Kara 	int dirty = buffer_dirty(bh);
102856d35a4cSJan Kara 	int ret;
102956d35a4cSJan Kara 
1030ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1031ac27a0ecSDave Kleikamp 		return 0;
103256d35a4cSJan Kara 	/*
1033ebdec241SChristoph Hellwig 	 * __block_write_begin() could have dirtied some buffers. Clean
103456d35a4cSJan Kara 	 * the dirty bit as jbd2_journal_get_write_access() could complain
103556d35a4cSJan Kara 	 * otherwise about fs integrity issues. Setting of the dirty bit
1036ebdec241SChristoph Hellwig 	 * by __block_write_begin() isn't a real problem here as we clear
103756d35a4cSJan Kara 	 * the bit before releasing a page lock and thus writeback cannot
103856d35a4cSJan Kara 	 * ever write the buffer.
103956d35a4cSJan Kara 	 */
104056d35a4cSJan Kara 	if (dirty)
104156d35a4cSJan Kara 		clear_buffer_dirty(bh);
10425d601255Sliang xie 	BUFFER_TRACE(bh, "get write access");
1043188c299eSJan Kara 	ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
1044188c299eSJan Kara 					    EXT4_JTR_NONE);
104556d35a4cSJan Kara 	if (!ret && dirty)
104656d35a4cSJan Kara 		ret = ext4_handle_dirty_metadata(handle, NULL, bh);
104756d35a4cSJan Kara 	return ret;
1048ac27a0ecSDave Kleikamp }
1049ac27a0ecSDave Kleikamp 
1050643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
10512058f83aSMichael Halcrow static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
10522058f83aSMichael Halcrow 				  get_block_t *get_block)
10532058f83aSMichael Halcrow {
105409cbfeafSKirill A. Shutemov 	unsigned from = pos & (PAGE_SIZE - 1);
10552058f83aSMichael Halcrow 	unsigned to = from + len;
10562058f83aSMichael Halcrow 	struct inode *inode = page->mapping->host;
10572058f83aSMichael Halcrow 	unsigned block_start, block_end;
10582058f83aSMichael Halcrow 	sector_t block;
10592058f83aSMichael Halcrow 	int err = 0;
10602058f83aSMichael Halcrow 	unsigned blocksize = inode->i_sb->s_blocksize;
10612058f83aSMichael Halcrow 	unsigned bbits;
10620b578f35SChandan Rajendra 	struct buffer_head *bh, *head, *wait[2];
10630b578f35SChandan Rajendra 	int nr_wait = 0;
10640b578f35SChandan Rajendra 	int i;
10652058f83aSMichael Halcrow 
10662058f83aSMichael Halcrow 	BUG_ON(!PageLocked(page));
106709cbfeafSKirill A. Shutemov 	BUG_ON(from > PAGE_SIZE);
106809cbfeafSKirill A. Shutemov 	BUG_ON(to > PAGE_SIZE);
10692058f83aSMichael Halcrow 	BUG_ON(from > to);
10702058f83aSMichael Halcrow 
10712058f83aSMichael Halcrow 	if (!page_has_buffers(page))
10722058f83aSMichael Halcrow 		create_empty_buffers(page, blocksize, 0);
10732058f83aSMichael Halcrow 	head = page_buffers(page);
10742058f83aSMichael Halcrow 	bbits = ilog2(blocksize);
107509cbfeafSKirill A. Shutemov 	block = (sector_t)page->index << (PAGE_SHIFT - bbits);
10762058f83aSMichael Halcrow 
10772058f83aSMichael Halcrow 	for (bh = head, block_start = 0; bh != head || !block_start;
10782058f83aSMichael Halcrow 	    block++, block_start = block_end, bh = bh->b_this_page) {
10792058f83aSMichael Halcrow 		block_end = block_start + blocksize;
10802058f83aSMichael Halcrow 		if (block_end <= from || block_start >= to) {
10812058f83aSMichael Halcrow 			if (PageUptodate(page)) {
10822058f83aSMichael Halcrow 				set_buffer_uptodate(bh);
10832058f83aSMichael Halcrow 			}
10842058f83aSMichael Halcrow 			continue;
10852058f83aSMichael Halcrow 		}
10862058f83aSMichael Halcrow 		if (buffer_new(bh))
10872058f83aSMichael Halcrow 			clear_buffer_new(bh);
10882058f83aSMichael Halcrow 		if (!buffer_mapped(bh)) {
10892058f83aSMichael Halcrow 			WARN_ON(bh->b_size != blocksize);
10902058f83aSMichael Halcrow 			err = get_block(inode, block, bh, 1);
10912058f83aSMichael Halcrow 			if (err)
10922058f83aSMichael Halcrow 				break;
10932058f83aSMichael Halcrow 			if (buffer_new(bh)) {
10942058f83aSMichael Halcrow 				if (PageUptodate(page)) {
10952058f83aSMichael Halcrow 					clear_buffer_new(bh);
10962058f83aSMichael Halcrow 					set_buffer_uptodate(bh);
10972058f83aSMichael Halcrow 					mark_buffer_dirty(bh);
10982058f83aSMichael Halcrow 					continue;
10992058f83aSMichael Halcrow 				}
11002058f83aSMichael Halcrow 				if (block_end > to || block_start < from)
11012058f83aSMichael Halcrow 					zero_user_segments(page, to, block_end,
11022058f83aSMichael Halcrow 							   block_start, from);
11032058f83aSMichael Halcrow 				continue;
11042058f83aSMichael Halcrow 			}
11052058f83aSMichael Halcrow 		}
11062058f83aSMichael Halcrow 		if (PageUptodate(page)) {
11072058f83aSMichael Halcrow 			set_buffer_uptodate(bh);
11082058f83aSMichael Halcrow 			continue;
11092058f83aSMichael Halcrow 		}
11102058f83aSMichael Halcrow 		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
11112058f83aSMichael Halcrow 		    !buffer_unwritten(bh) &&
11122058f83aSMichael Halcrow 		    (block_start < from || block_end > to)) {
11132d069c08Szhangyi (F) 			ext4_read_bh_lock(bh, 0, false);
11140b578f35SChandan Rajendra 			wait[nr_wait++] = bh;
11152058f83aSMichael Halcrow 		}
11162058f83aSMichael Halcrow 	}
11172058f83aSMichael Halcrow 	/*
11182058f83aSMichael Halcrow 	 * If we issued read requests, let them complete.
11192058f83aSMichael Halcrow 	 */
11200b578f35SChandan Rajendra 	for (i = 0; i < nr_wait; i++) {
11210b578f35SChandan Rajendra 		wait_on_buffer(wait[i]);
11220b578f35SChandan Rajendra 		if (!buffer_uptodate(wait[i]))
11232058f83aSMichael Halcrow 			err = -EIO;
11242058f83aSMichael Halcrow 	}
11257e0785fcSChandan Rajendra 	if (unlikely(err)) {
11262058f83aSMichael Halcrow 		page_zero_new_buffers(page, from, to);
11274f74d15fSEric Biggers 	} else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
11280b578f35SChandan Rajendra 		for (i = 0; i < nr_wait; i++) {
11290b578f35SChandan Rajendra 			int err2;
11300b578f35SChandan Rajendra 
11310b578f35SChandan Rajendra 			err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
11320b578f35SChandan Rajendra 								bh_offset(wait[i]));
11330b578f35SChandan Rajendra 			if (err2) {
11340b578f35SChandan Rajendra 				clear_buffer_uptodate(wait[i]);
11350b578f35SChandan Rajendra 				err = err2;
11360b578f35SChandan Rajendra 			}
11370b578f35SChandan Rajendra 		}
11387e0785fcSChandan Rajendra 	}
11397e0785fcSChandan Rajendra 
11402058f83aSMichael Halcrow 	return err;
11412058f83aSMichael Halcrow }
11422058f83aSMichael Halcrow #endif
11432058f83aSMichael Halcrow 
1144bfc1af65SNick Piggin static int ext4_write_begin(struct file *file, struct address_space *mapping,
11459d6b0cd7SMatthew Wilcox (Oracle) 			    loff_t pos, unsigned len,
1146bfc1af65SNick Piggin 			    struct page **pagep, void **fsdata)
1147ac27a0ecSDave Kleikamp {
1148bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
11491938a150SAneesh Kumar K.V 	int ret, needed_blocks;
1150ac27a0ecSDave Kleikamp 	handle_t *handle;
1151ac27a0ecSDave Kleikamp 	int retries = 0;
1152bfc1af65SNick Piggin 	struct page *page;
1153bfc1af65SNick Piggin 	pgoff_t index;
1154bfc1af65SNick Piggin 	unsigned from, to;
1155bfc1af65SNick Piggin 
11560db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
11570db1ff22STheodore Ts'o 		return -EIO;
11580db1ff22STheodore Ts'o 
11599d6b0cd7SMatthew Wilcox (Oracle) 	trace_ext4_write_begin(inode, pos, len);
11601938a150SAneesh Kumar K.V 	/*
11611938a150SAneesh Kumar K.V 	 * Reserve one block more for addition to orphan list in case
11621938a150SAneesh Kumar K.V 	 * we allocate blocks but write fails for some reason
11631938a150SAneesh Kumar K.V 	 */
11641938a150SAneesh Kumar K.V 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
116509cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
116609cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1167bfc1af65SNick Piggin 	to = from + len;
1168ac27a0ecSDave Kleikamp 
1169f19d5870STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1170f19d5870STao Ma 		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1171832ee62dSMatthew Wilcox (Oracle) 						    pagep);
1172f19d5870STao Ma 		if (ret < 0)
117347564bfbSTheodore Ts'o 			return ret;
117447564bfbSTheodore Ts'o 		if (ret == 1)
117547564bfbSTheodore Ts'o 			return 0;
1176f19d5870STao Ma 	}
1177f19d5870STao Ma 
117847564bfbSTheodore Ts'o 	/*
117947564bfbSTheodore Ts'o 	 * grab_cache_page_write_begin() can take a long time if the
118047564bfbSTheodore Ts'o 	 * system is thrashing due to memory pressure, or if the page
118147564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
118247564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
118347564bfbSTheodore Ts'o 	 * the page (if needed) without using GFP_NOFS.
118447564bfbSTheodore Ts'o 	 */
118547564bfbSTheodore Ts'o retry_grab:
1186b7446e7cSMatthew Wilcox (Oracle) 	page = grab_cache_page_write_begin(mapping, index);
118747564bfbSTheodore Ts'o 	if (!page)
118847564bfbSTheodore Ts'o 		return -ENOMEM;
118947564bfbSTheodore Ts'o 	unlock_page(page);
119047564bfbSTheodore Ts'o 
119147564bfbSTheodore Ts'o retry_journal:
11929924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
11937479d2b9SAndrew Morton 	if (IS_ERR(handle)) {
119409cbfeafSKirill A. Shutemov 		put_page(page);
119547564bfbSTheodore Ts'o 		return PTR_ERR(handle);
1196cf108bcaSJan Kara 	}
1197f19d5870STao Ma 
119847564bfbSTheodore Ts'o 	lock_page(page);
119947564bfbSTheodore Ts'o 	if (page->mapping != mapping) {
120047564bfbSTheodore Ts'o 		/* The page got truncated from under us */
120147564bfbSTheodore Ts'o 		unlock_page(page);
120209cbfeafSKirill A. Shutemov 		put_page(page);
1203cf108bcaSJan Kara 		ext4_journal_stop(handle);
120447564bfbSTheodore Ts'o 		goto retry_grab;
1205cf108bcaSJan Kara 	}
12067afe5aa5SDmitry Monakhov 	/* In case writeback began while the page was unlocked */
12077afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
1208cf108bcaSJan Kara 
1209643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
12102058f83aSMichael Halcrow 	if (ext4_should_dioread_nolock(inode))
12112058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
1212705965bdSJan Kara 					     ext4_get_block_unwritten);
12132058f83aSMichael Halcrow 	else
12142058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
12152058f83aSMichael Halcrow 					     ext4_get_block);
12162058f83aSMichael Halcrow #else
1217744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
1218705965bdSJan Kara 		ret = __block_write_begin(page, pos, len,
1219705965bdSJan Kara 					  ext4_get_block_unwritten);
1220744692dcSJiaying Zhang 	else
12216e1db88dSChristoph Hellwig 		ret = __block_write_begin(page, pos, len, ext4_get_block);
12222058f83aSMichael Halcrow #endif
1223bfc1af65SNick Piggin 	if (!ret && ext4_should_journal_data(inode)) {
1224188c299eSJan Kara 		ret = ext4_walk_page_buffers(handle, inode,
1225188c299eSJan Kara 					     page_buffers(page), from, to, NULL,
1226f19d5870STao Ma 					     do_journal_get_write_access);
1227b46be050SAndrey Savochkin 	}
1228bfc1af65SNick Piggin 
1229bfc1af65SNick Piggin 	if (ret) {
1230c93d8f88SEric Biggers 		bool extended = (pos + len > inode->i_size) &&
1231c93d8f88SEric Biggers 				!ext4_verity_in_progress(inode);
1232c93d8f88SEric Biggers 
1233bfc1af65SNick Piggin 		unlock_page(page);
1234ae4d5372SAneesh Kumar K.V 		/*
12356e1db88dSChristoph Hellwig 		 * __block_write_begin may have instantiated a few blocks
1236ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
1237f340b3d9Shongnanli 		 * i_size_read because we hold i_rwsem.
12381938a150SAneesh Kumar K.V 		 *
12391938a150SAneesh Kumar K.V 		 * Add inode to orphan list in case we crash before
12401938a150SAneesh Kumar K.V 		 * truncate finishes
1241ae4d5372SAneesh Kumar K.V 		 */
1242c93d8f88SEric Biggers 		if (extended && ext4_can_truncate(inode))
12431938a150SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
12441938a150SAneesh Kumar K.V 
12451938a150SAneesh Kumar K.V 		ext4_journal_stop(handle);
1246c93d8f88SEric Biggers 		if (extended) {
1247b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
12481938a150SAneesh Kumar K.V 			/*
1249ffacfa7aSJan Kara 			 * If truncate failed early the inode might
12501938a150SAneesh Kumar K.V 			 * still be on the orphan list; we need to
12511938a150SAneesh Kumar K.V 			 * make sure the inode is removed from the
12521938a150SAneesh Kumar K.V 			 * orphan list in that case.
12531938a150SAneesh Kumar K.V 			 */
12541938a150SAneesh Kumar K.V 			if (inode->i_nlink)
12551938a150SAneesh Kumar K.V 				ext4_orphan_del(NULL, inode);
12561938a150SAneesh Kumar K.V 		}
1257bfc1af65SNick Piggin 
125847564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
125947564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
126047564bfbSTheodore Ts'o 			goto retry_journal;
126109cbfeafSKirill A. Shutemov 		put_page(page);
126247564bfbSTheodore Ts'o 		return ret;
126347564bfbSTheodore Ts'o 	}
126447564bfbSTheodore Ts'o 	*pagep = page;
1265ac27a0ecSDave Kleikamp 	return ret;
1266ac27a0ecSDave Kleikamp }
1267ac27a0ecSDave Kleikamp 
1268bfc1af65SNick Piggin /* For write_end() in data=journal mode */
1269188c299eSJan Kara static int write_end_fn(handle_t *handle, struct inode *inode,
1270188c299eSJan Kara 			struct buffer_head *bh)
1271ac27a0ecSDave Kleikamp {
127213fca323STheodore Ts'o 	int ret;
1273ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1274ac27a0ecSDave Kleikamp 		return 0;
1275ac27a0ecSDave Kleikamp 	set_buffer_uptodate(bh);
127613fca323STheodore Ts'o 	ret = ext4_handle_dirty_metadata(handle, NULL, bh);
127713fca323STheodore Ts'o 	clear_buffer_meta(bh);
127813fca323STheodore Ts'o 	clear_buffer_prio(bh);
127913fca323STheodore Ts'o 	return ret;
1280ac27a0ecSDave Kleikamp }
1281ac27a0ecSDave Kleikamp 
1282eed4333fSZheng Liu /*
1283eed4333fSZheng Liu  * We need to pick up the new inode size which generic_commit_write gave us
1284eed4333fSZheng Liu  * `file' can be NULL - eg, when called from page_symlink().
1285eed4333fSZheng Liu  *
1286eed4333fSZheng Liu  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1287eed4333fSZheng Liu  * buffers are managed internally.
1288eed4333fSZheng Liu  */
1289eed4333fSZheng Liu static int ext4_write_end(struct file *file,
1290f8514083SAneesh Kumar K.V 			  struct address_space *mapping,
1291f8514083SAneesh Kumar K.V 			  loff_t pos, unsigned len, unsigned copied,
1292f8514083SAneesh Kumar K.V 			  struct page *page, void *fsdata)
1293f8514083SAneesh Kumar K.V {
1294f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
1295eed4333fSZheng Liu 	struct inode *inode = mapping->host;
12960572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1297eed4333fSZheng Liu 	int ret = 0, ret2;
1298eed4333fSZheng Liu 	int i_size_changed = 0;
1299c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1300eed4333fSZheng Liu 
1301eed4333fSZheng Liu 	trace_ext4_write_end(inode, pos, len, copied);
13026984aef5SZhang Yi 
13036984aef5SZhang Yi 	if (ext4_has_inline_data(inode))
13046984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
13056984aef5SZhang Yi 
13066984aef5SZhang Yi 	copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1307f8514083SAneesh Kumar K.V 	/*
13084631dbf6SDmitry Monakhov 	 * it's important to update i_size while still holding page lock:
1309f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
1310c93d8f88SEric Biggers 	 *
1311c93d8f88SEric Biggers 	 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1312c93d8f88SEric Biggers 	 * blocks are being written past EOF, so skip the i_size update.
1313f8514083SAneesh Kumar K.V 	 */
1314c93d8f88SEric Biggers 	if (!verity)
13154631dbf6SDmitry Monakhov 		i_size_changed = ext4_update_inode_size(inode, pos + copied);
1316f8514083SAneesh Kumar K.V 	unlock_page(page);
131709cbfeafSKirill A. Shutemov 	put_page(page);
1318f8514083SAneesh Kumar K.V 
1319c93d8f88SEric Biggers 	if (old_size < pos && !verity)
13200572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
1321f8514083SAneesh Kumar K.V 	/*
1322f8514083SAneesh Kumar K.V 	 * Don't mark the inode dirty under page lock. First, it unnecessarily
1323f8514083SAneesh Kumar K.V 	 * makes the holding time of page lock longer. Second, it forces lock
1324f8514083SAneesh Kumar K.V 	 * ordering of page lock and transaction start for journaling
1325f8514083SAneesh Kumar K.V 	 * filesystems.
1326f8514083SAneesh Kumar K.V 	 */
13276984aef5SZhang Yi 	if (i_size_changed)
13284209ae12SHarshad Shirwadkar 		ret = ext4_mark_inode_dirty(handle, inode);
1329f8514083SAneesh Kumar K.V 
1330c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1331f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1332f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1333f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1334f8514083SAneesh Kumar K.V 		 */
1335f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
133655ce2f64SZhang Yi 
1337617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1338ac27a0ecSDave Kleikamp 	if (!ret)
1339ac27a0ecSDave Kleikamp 		ret = ret2;
1340bfc1af65SNick Piggin 
1341c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1342b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1343f8514083SAneesh Kumar K.V 		/*
1344ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1345f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1346f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1347f8514083SAneesh Kumar K.V 		 */
1348f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1349f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1350f8514083SAneesh Kumar K.V 	}
1351f8514083SAneesh Kumar K.V 
1352bfc1af65SNick Piggin 	return ret ? ret : copied;
1353ac27a0ecSDave Kleikamp }
1354ac27a0ecSDave Kleikamp 
1355b90197b6STheodore Ts'o /*
1356b90197b6STheodore Ts'o  * This is a private version of page_zero_new_buffers() which doesn't
1357b90197b6STheodore Ts'o  * set the buffer to be dirty, since in data=journalled mode we need
1358b90197b6STheodore Ts'o  * to call ext4_handle_dirty_metadata() instead.
1359b90197b6STheodore Ts'o  */
13603b136499SJan Kara static void ext4_journalled_zero_new_buffers(handle_t *handle,
1361188c299eSJan Kara 					    struct inode *inode,
13623b136499SJan Kara 					    struct page *page,
13633b136499SJan Kara 					    unsigned from, unsigned to)
1364b90197b6STheodore Ts'o {
1365b90197b6STheodore Ts'o 	unsigned int block_start = 0, block_end;
1366b90197b6STheodore Ts'o 	struct buffer_head *head, *bh;
1367b90197b6STheodore Ts'o 
1368b90197b6STheodore Ts'o 	bh = head = page_buffers(page);
1369b90197b6STheodore Ts'o 	do {
1370b90197b6STheodore Ts'o 		block_end = block_start + bh->b_size;
1371b90197b6STheodore Ts'o 		if (buffer_new(bh)) {
1372b90197b6STheodore Ts'o 			if (block_end > from && block_start < to) {
1373b90197b6STheodore Ts'o 				if (!PageUptodate(page)) {
1374b90197b6STheodore Ts'o 					unsigned start, size;
1375b90197b6STheodore Ts'o 
1376b90197b6STheodore Ts'o 					start = max(from, block_start);
1377b90197b6STheodore Ts'o 					size = min(to, block_end) - start;
1378b90197b6STheodore Ts'o 
1379b90197b6STheodore Ts'o 					zero_user(page, start, size);
1380188c299eSJan Kara 					write_end_fn(handle, inode, bh);
1381b90197b6STheodore Ts'o 				}
1382b90197b6STheodore Ts'o 				clear_buffer_new(bh);
1383b90197b6STheodore Ts'o 			}
1384b90197b6STheodore Ts'o 		}
1385b90197b6STheodore Ts'o 		block_start = block_end;
1386b90197b6STheodore Ts'o 		bh = bh->b_this_page;
1387b90197b6STheodore Ts'o 	} while (bh != head);
1388b90197b6STheodore Ts'o }
1389b90197b6STheodore Ts'o 
1390bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
1391bfc1af65SNick Piggin 				     struct address_space *mapping,
1392bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
1393bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
1394ac27a0ecSDave Kleikamp {
1395617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1396bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
13970572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1398ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1399ac27a0ecSDave Kleikamp 	int partial = 0;
1400bfc1af65SNick Piggin 	unsigned from, to;
14014631dbf6SDmitry Monakhov 	int size_changed = 0;
1402c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1403ac27a0ecSDave Kleikamp 
14049bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
140509cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1406bfc1af65SNick Piggin 	to = from + len;
1407bfc1af65SNick Piggin 
1408441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1409441c8508SCurt Wohlgemuth 
14106984aef5SZhang Yi 	if (ext4_has_inline_data(inode))
14116984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
14126984aef5SZhang Yi 
14136984aef5SZhang Yi 	if (unlikely(copied < len) && !PageUptodate(page)) {
1414bfc1af65SNick Piggin 		copied = 0;
1415188c299eSJan Kara 		ext4_journalled_zero_new_buffers(handle, inode, page, from, to);
14163b136499SJan Kara 	} else {
14173b136499SJan Kara 		if (unlikely(copied < len))
1418188c299eSJan Kara 			ext4_journalled_zero_new_buffers(handle, inode, page,
14193b136499SJan Kara 							 from + copied, to);
1420188c299eSJan Kara 		ret = ext4_walk_page_buffers(handle, inode, page_buffers(page),
1421188c299eSJan Kara 					     from, from + copied, &partial,
14223b136499SJan Kara 					     write_end_fn);
1423ac27a0ecSDave Kleikamp 		if (!partial)
1424ac27a0ecSDave Kleikamp 			SetPageUptodate(page);
14253fdcfb66STao Ma 	}
1426c93d8f88SEric Biggers 	if (!verity)
14274631dbf6SDmitry Monakhov 		size_changed = ext4_update_inode_size(inode, pos + copied);
142819f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
14292d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
14304631dbf6SDmitry Monakhov 	unlock_page(page);
143109cbfeafSKirill A. Shutemov 	put_page(page);
14324631dbf6SDmitry Monakhov 
1433c93d8f88SEric Biggers 	if (old_size < pos && !verity)
14340572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
14350572639fSXiaoguang Wang 
14366984aef5SZhang Yi 	if (size_changed) {
1437617ba13bSMingming Cao 		ret2 = ext4_mark_inode_dirty(handle, inode);
1438ac27a0ecSDave Kleikamp 		if (!ret)
1439ac27a0ecSDave Kleikamp 			ret = ret2;
1440ac27a0ecSDave Kleikamp 	}
1441bfc1af65SNick Piggin 
1442c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1443f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1444f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1445f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1446f8514083SAneesh Kumar K.V 		 */
1447f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1448f8514083SAneesh Kumar K.V 
1449617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1450ac27a0ecSDave Kleikamp 	if (!ret)
1451ac27a0ecSDave Kleikamp 		ret = ret2;
1452c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1453b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1454f8514083SAneesh Kumar K.V 		/*
1455ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1456f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1457f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1458f8514083SAneesh Kumar K.V 		 */
1459f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1460f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1461f8514083SAneesh Kumar K.V 	}
1462bfc1af65SNick Piggin 
1463bfc1af65SNick Piggin 	return ret ? ret : copied;
1464ac27a0ecSDave Kleikamp }
1465d2a17637SMingming Cao 
14669d0be502STheodore Ts'o /*
1467c27e43a1SEric Whitney  * Reserve space for a single cluster
14689d0be502STheodore Ts'o  */
1469c27e43a1SEric Whitney static int ext4_da_reserve_space(struct inode *inode)
1470d2a17637SMingming Cao {
1471d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
14720637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
14735dd4056dSChristoph Hellwig 	int ret;
1474d2a17637SMingming Cao 
147560e58e0fSMingming Cao 	/*
147672b8ab9dSEric Sandeen 	 * We will charge metadata quota at writeout time; this saves
147772b8ab9dSEric Sandeen 	 * us from metadata over-estimation, though we may go over by
147872b8ab9dSEric Sandeen 	 * a small amount in the end.  Here we just reserve for data.
147960e58e0fSMingming Cao 	 */
14807b415bf6SAditya Kali 	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
14815dd4056dSChristoph Hellwig 	if (ret)
14825dd4056dSChristoph Hellwig 		return ret;
148303179fe9STheodore Ts'o 
148403179fe9STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
148571d4f7d0STheodore Ts'o 	if (ext4_claim_free_clusters(sbi, 1, 0)) {
148603179fe9STheodore Ts'o 		spin_unlock(&ei->i_block_reservation_lock);
148703179fe9STheodore Ts'o 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1488d2a17637SMingming Cao 		return -ENOSPC;
1489d2a17637SMingming Cao 	}
14909d0be502STheodore Ts'o 	ei->i_reserved_data_blocks++;
1491c27e43a1SEric Whitney 	trace_ext4_da_reserve_space(inode);
14920637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
149339bc680aSDmitry Monakhov 
1494d2a17637SMingming Cao 	return 0;       /* success */
1495d2a17637SMingming Cao }
1496d2a17637SMingming Cao 
1497f456767dSEric Whitney void ext4_da_release_space(struct inode *inode, int to_free)
1498d2a17637SMingming Cao {
1499d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
15000637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1501d2a17637SMingming Cao 
1502cd213226SMingming Cao 	if (!to_free)
1503cd213226SMingming Cao 		return;		/* Nothing to release, exit */
1504cd213226SMingming Cao 
1505d2a17637SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1506cd213226SMingming Cao 
15075a58ec87SLi Zefan 	trace_ext4_da_release_space(inode, to_free);
15080637c6f4STheodore Ts'o 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1509cd213226SMingming Cao 		/*
15100637c6f4STheodore Ts'o 		 * if there aren't enough reserved blocks, then the
15110637c6f4STheodore Ts'o 		 * counter is messed up somewhere.  Since this
15120637c6f4STheodore Ts'o 		 * function is called from invalidate page, it's
15130637c6f4STheodore Ts'o 		 * harmless to return without any action.
1514cd213226SMingming Cao 		 */
15158de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "ext4_da_release_space: "
15160637c6f4STheodore Ts'o 			 "ino %lu, to_free %d with only %d reserved "
15171084f252STheodore Ts'o 			 "data blocks", inode->i_ino, to_free,
15180637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
15190637c6f4STheodore Ts'o 		WARN_ON(1);
15200637c6f4STheodore Ts'o 		to_free = ei->i_reserved_data_blocks;
15210637c6f4STheodore Ts'o 	}
15220637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= to_free;
15230637c6f4STheodore Ts'o 
152472b8ab9dSEric Sandeen 	/* update fs dirty data blocks counter */
152557042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1526d2a17637SMingming Cao 
1527d2a17637SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
152860e58e0fSMingming Cao 
15297b415bf6SAditya Kali 	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1530d2a17637SMingming Cao }
1531d2a17637SMingming Cao 
1532ac27a0ecSDave Kleikamp /*
153364769240SAlex Tomas  * Delayed allocation stuff
153464769240SAlex Tomas  */
153564769240SAlex Tomas 
15364e7ea81dSJan Kara struct mpage_da_data {
15374e7ea81dSJan Kara 	struct inode *inode;
15384e7ea81dSJan Kara 	struct writeback_control *wbc;
15396b523df4SJan Kara 
15404e7ea81dSJan Kara 	pgoff_t first_page;	/* The first page to write */
15414e7ea81dSJan Kara 	pgoff_t next_page;	/* Current page to examine */
15424e7ea81dSJan Kara 	pgoff_t last_page;	/* Last page to examine */
154364769240SAlex Tomas 	/*
15444e7ea81dSJan Kara 	 * Extent to map - this can be after first_page because that can be
15454e7ea81dSJan Kara 	 * fully mapped. We somewhat abuse m_flags to store whether the extent
15464e7ea81dSJan Kara 	 * is delalloc or unwritten.
154764769240SAlex Tomas 	 */
15484e7ea81dSJan Kara 	struct ext4_map_blocks map;
15494e7ea81dSJan Kara 	struct ext4_io_submit io_submit;	/* IO submission data */
1550dddbd6acSJan Kara 	unsigned int do_map:1;
15516b8ed620SJan Kara 	unsigned int scanned_until_end:1;
15524e7ea81dSJan Kara };
155364769240SAlex Tomas 
15544e7ea81dSJan Kara static void mpage_release_unused_pages(struct mpage_da_data *mpd,
15554e7ea81dSJan Kara 				       bool invalidate)
1556c4a0c46eSAneesh Kumar K.V {
1557c4a0c46eSAneesh Kumar K.V 	int nr_pages, i;
1558c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
1559c4a0c46eSAneesh Kumar K.V 	struct pagevec pvec;
1560c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1561c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
15624e7ea81dSJan Kara 
15634e7ea81dSJan Kara 	/* This is necessary when next_page == 0. */
15644e7ea81dSJan Kara 	if (mpd->first_page >= mpd->next_page)
15654e7ea81dSJan Kara 		return;
1566c4a0c46eSAneesh Kumar K.V 
15676b8ed620SJan Kara 	mpd->scanned_until_end = 0;
1568c7f5938aSCurt Wohlgemuth 	index = mpd->first_page;
1569c7f5938aSCurt Wohlgemuth 	end   = mpd->next_page - 1;
15704e7ea81dSJan Kara 	if (invalidate) {
15714e7ea81dSJan Kara 		ext4_lblk_t start, last;
157209cbfeafSKirill A. Shutemov 		start = index << (PAGE_SHIFT - inode->i_blkbits);
157309cbfeafSKirill A. Shutemov 		last = end << (PAGE_SHIFT - inode->i_blkbits);
157451865fdaSZheng Liu 		ext4_es_remove_extent(inode, start, last - start + 1);
15754e7ea81dSJan Kara 	}
157651865fdaSZheng Liu 
157786679820SMel Gorman 	pagevec_init(&pvec);
1578c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
1579397162ffSJan Kara 		nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1580c4a0c46eSAneesh Kumar K.V 		if (nr_pages == 0)
1581c4a0c46eSAneesh Kumar K.V 			break;
1582c4a0c46eSAneesh Kumar K.V 		for (i = 0; i < nr_pages; i++) {
1583c4a0c46eSAneesh Kumar K.V 			struct page *page = pvec.pages[i];
15847ba13abbSMatthew Wilcox (Oracle) 			struct folio *folio = page_folio(page);
15852b85a617SJan Kara 
15867ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(!folio_test_locked(folio));
15877ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(folio_test_writeback(folio));
15884e7ea81dSJan Kara 			if (invalidate) {
15897ba13abbSMatthew Wilcox (Oracle) 				if (folio_mapped(folio))
15907ba13abbSMatthew Wilcox (Oracle) 					folio_clear_dirty_for_io(folio);
15917ba13abbSMatthew Wilcox (Oracle) 				block_invalidate_folio(folio, 0,
15927ba13abbSMatthew Wilcox (Oracle) 						folio_size(folio));
15937ba13abbSMatthew Wilcox (Oracle) 				folio_clear_uptodate(folio);
15944e7ea81dSJan Kara 			}
15957ba13abbSMatthew Wilcox (Oracle) 			folio_unlock(folio);
1596c4a0c46eSAneesh Kumar K.V 		}
15979b1d0998SJan Kara 		pagevec_release(&pvec);
1598c4a0c46eSAneesh Kumar K.V 	}
1599c4a0c46eSAneesh Kumar K.V }
1600c4a0c46eSAneesh Kumar K.V 
1601df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
1602df22291fSAneesh Kumar K.V {
1603df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
160492b97816STheodore Ts'o 	struct super_block *sb = inode->i_sb;
1605f78ee70dSLukas Czerner 	struct ext4_inode_info *ei = EXT4_I(inode);
160692b97816STheodore Ts'o 
160792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
16085dee5437STheodore Ts'o 	       EXT4_C2B(EXT4_SB(inode->i_sb),
1609f78ee70dSLukas Czerner 			ext4_count_free_clusters(sb)));
161092b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
161192b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1612f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
161357042651STheodore Ts'o 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
161492b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1615f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
16167b415bf6SAditya Kali 		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
161792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Block reservation details");
161892b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1619f78ee70dSLukas Czerner 		 ei->i_reserved_data_blocks);
1620df22291fSAneesh Kumar K.V 	return;
1621df22291fSAneesh Kumar K.V }
1622df22291fSAneesh Kumar K.V 
1623188c299eSJan Kara static int ext4_bh_delay_or_unwritten(handle_t *handle, struct inode *inode,
1624188c299eSJan Kara 				      struct buffer_head *bh)
162529fa89d0SAneesh Kumar K.V {
1626c364b22cSAneesh Kumar K.V 	return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
162729fa89d0SAneesh Kumar K.V }
162829fa89d0SAneesh Kumar K.V 
162964769240SAlex Tomas /*
16300b02f4c0SEric Whitney  * ext4_insert_delayed_block - adds a delayed block to the extents status
16310b02f4c0SEric Whitney  *                             tree, incrementing the reserved cluster/block
16320b02f4c0SEric Whitney  *                             count or making a pending reservation
16330b02f4c0SEric Whitney  *                             where needed
16340b02f4c0SEric Whitney  *
16350b02f4c0SEric Whitney  * @inode - file containing the newly added block
16360b02f4c0SEric Whitney  * @lblk - logical block to be added
16370b02f4c0SEric Whitney  *
16380b02f4c0SEric Whitney  * Returns 0 on success, negative error code on failure.
16390b02f4c0SEric Whitney  */
16400b02f4c0SEric Whitney static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
16410b02f4c0SEric Whitney {
16420b02f4c0SEric Whitney 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
16430b02f4c0SEric Whitney 	int ret;
16440b02f4c0SEric Whitney 	bool allocated = false;
16456fed8395SJeffle Xu 	bool reserved = false;
16460b02f4c0SEric Whitney 
16470b02f4c0SEric Whitney 	/*
16480b02f4c0SEric Whitney 	 * If the cluster containing lblk is shared with a delayed,
16490b02f4c0SEric Whitney 	 * written, or unwritten extent in a bigalloc file system, it's
16500b02f4c0SEric Whitney 	 * already been accounted for and does not need to be reserved.
16510b02f4c0SEric Whitney 	 * A pending reservation must be made for the cluster if it's
16520b02f4c0SEric Whitney 	 * shared with a written or unwritten extent and doesn't already
16530b02f4c0SEric Whitney 	 * have one.  Written and unwritten extents can be purged from the
16540b02f4c0SEric Whitney 	 * extents status tree if the system is under memory pressure, so
16550b02f4c0SEric Whitney 	 * it's necessary to examine the extent tree if a search of the
16560b02f4c0SEric Whitney 	 * extents status tree doesn't get a match.
16570b02f4c0SEric Whitney 	 */
16580b02f4c0SEric Whitney 	if (sbi->s_cluster_ratio == 1) {
16590b02f4c0SEric Whitney 		ret = ext4_da_reserve_space(inode);
16600b02f4c0SEric Whitney 		if (ret != 0)   /* ENOSPC */
16610b02f4c0SEric Whitney 			goto errout;
16626fed8395SJeffle Xu 		reserved = true;
16630b02f4c0SEric Whitney 	} else {   /* bigalloc */
16640b02f4c0SEric Whitney 		if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
16650b02f4c0SEric Whitney 			if (!ext4_es_scan_clu(inode,
16660b02f4c0SEric Whitney 					      &ext4_es_is_mapped, lblk)) {
16670b02f4c0SEric Whitney 				ret = ext4_clu_mapped(inode,
16680b02f4c0SEric Whitney 						      EXT4_B2C(sbi, lblk));
16690b02f4c0SEric Whitney 				if (ret < 0)
16700b02f4c0SEric Whitney 					goto errout;
16710b02f4c0SEric Whitney 				if (ret == 0) {
16720b02f4c0SEric Whitney 					ret = ext4_da_reserve_space(inode);
16730b02f4c0SEric Whitney 					if (ret != 0)   /* ENOSPC */
16740b02f4c0SEric Whitney 						goto errout;
16756fed8395SJeffle Xu 					reserved = true;
16760b02f4c0SEric Whitney 				} else {
16770b02f4c0SEric Whitney 					allocated = true;
16780b02f4c0SEric Whitney 				}
16790b02f4c0SEric Whitney 			} else {
16800b02f4c0SEric Whitney 				allocated = true;
16810b02f4c0SEric Whitney 			}
16820b02f4c0SEric Whitney 		}
16830b02f4c0SEric Whitney 	}
16840b02f4c0SEric Whitney 
16850b02f4c0SEric Whitney 	ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
16866fed8395SJeffle Xu 	if (ret && reserved)
16876fed8395SJeffle Xu 		ext4_da_release_space(inode, 1);
16880b02f4c0SEric Whitney 
16890b02f4c0SEric Whitney errout:
16900b02f4c0SEric Whitney 	return ret;
16910b02f4c0SEric Whitney }
16920b02f4c0SEric Whitney 
16930b02f4c0SEric Whitney /*
16945356f261SAditya Kali  * This function is grabs code from the very beginning of
16955356f261SAditya Kali  * ext4_map_blocks, but assumes that the caller is from delayed write
16965356f261SAditya Kali  * time. This function looks up the requested blocks and sets the
16975356f261SAditya Kali  * buffer delay bit under the protection of i_data_sem.
16985356f261SAditya Kali  */
16995356f261SAditya Kali static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
17005356f261SAditya Kali 			      struct ext4_map_blocks *map,
17015356f261SAditya Kali 			      struct buffer_head *bh)
17025356f261SAditya Kali {
1703d100eef2SZheng Liu 	struct extent_status es;
17045356f261SAditya Kali 	int retval;
17055356f261SAditya Kali 	sector_t invalid_block = ~((sector_t) 0xffff);
1706921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1707921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
1708921f266bSDmitry Monakhov 
1709921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
1710921f266bSDmitry Monakhov #endif
17115356f261SAditya Kali 
17125356f261SAditya Kali 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
17135356f261SAditya Kali 		invalid_block = ~0;
17145356f261SAditya Kali 
17155356f261SAditya Kali 	map->m_flags = 0;
171670aa1554SRitesh Harjani 	ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
17175356f261SAditya Kali 		  (unsigned long) map->m_lblk);
1718d100eef2SZheng Liu 
1719d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
1720bb5835edSTheodore Ts'o 	if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1721d100eef2SZheng Liu 		if (ext4_es_is_hole(&es)) {
1722d100eef2SZheng Liu 			retval = 0;
1723c8b459f4SLukas Czerner 			down_read(&EXT4_I(inode)->i_data_sem);
1724d100eef2SZheng Liu 			goto add_delayed;
1725d100eef2SZheng Liu 		}
1726d100eef2SZheng Liu 
1727d100eef2SZheng Liu 		/*
17283eda41dfSEric Whitney 		 * Delayed extent could be allocated by fallocate.
17293eda41dfSEric Whitney 		 * So we need to check it.
1730d100eef2SZheng Liu 		 */
17313eda41dfSEric Whitney 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
17323eda41dfSEric Whitney 			map_bh(bh, inode->i_sb, invalid_block);
17333eda41dfSEric Whitney 			set_buffer_new(bh);
17343eda41dfSEric Whitney 			set_buffer_delay(bh);
1735d100eef2SZheng Liu 			return 0;
1736d100eef2SZheng Liu 		}
1737d100eef2SZheng Liu 
1738d100eef2SZheng Liu 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1739d100eef2SZheng Liu 		retval = es.es_len - (iblock - es.es_lblk);
1740d100eef2SZheng Liu 		if (retval > map->m_len)
1741d100eef2SZheng Liu 			retval = map->m_len;
1742d100eef2SZheng Liu 		map->m_len = retval;
1743d100eef2SZheng Liu 		if (ext4_es_is_written(&es))
1744d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_MAPPED;
1745d100eef2SZheng Liu 		else if (ext4_es_is_unwritten(&es))
1746d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1747d100eef2SZheng Liu 		else
17481e83bc81SArnd Bergmann 			BUG();
1749d100eef2SZheng Liu 
1750921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1751921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1752921f266bSDmitry Monakhov #endif
1753d100eef2SZheng Liu 		return retval;
1754d100eef2SZheng Liu 	}
1755d100eef2SZheng Liu 
17565356f261SAditya Kali 	/*
17575356f261SAditya Kali 	 * Try to see if we can get the block without requesting a new
17585356f261SAditya Kali 	 * file system block.
17595356f261SAditya Kali 	 */
1760c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
1761cbd7584eSJan Kara 	if (ext4_has_inline_data(inode))
17629c3569b5STao Ma 		retval = 0;
1763cbd7584eSJan Kara 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
17642f8e0a7cSZheng Liu 		retval = ext4_ext_map_blocks(NULL, inode, map, 0);
17655356f261SAditya Kali 	else
17662f8e0a7cSZheng Liu 		retval = ext4_ind_map_blocks(NULL, inode, map, 0);
17675356f261SAditya Kali 
1768d100eef2SZheng Liu add_delayed:
17695356f261SAditya Kali 	if (retval == 0) {
1770f7fec032SZheng Liu 		int ret;
1771ad431025SEric Whitney 
17725356f261SAditya Kali 		/*
17735356f261SAditya Kali 		 * XXX: __block_prepare_write() unmaps passed block,
17745356f261SAditya Kali 		 * is it OK?
17755356f261SAditya Kali 		 */
17765356f261SAditya Kali 
17770b02f4c0SEric Whitney 		ret = ext4_insert_delayed_block(inode, map->m_lblk);
17780b02f4c0SEric Whitney 		if (ret != 0) {
1779f7fec032SZheng Liu 			retval = ret;
178051865fdaSZheng Liu 			goto out_unlock;
1781f7fec032SZheng Liu 		}
178251865fdaSZheng Liu 
17835356f261SAditya Kali 		map_bh(bh, inode->i_sb, invalid_block);
17845356f261SAditya Kali 		set_buffer_new(bh);
17855356f261SAditya Kali 		set_buffer_delay(bh);
1786f7fec032SZheng Liu 	} else if (retval > 0) {
1787f7fec032SZheng Liu 		int ret;
17883be78c73STheodore Ts'o 		unsigned int status;
1789f7fec032SZheng Liu 
179044fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
179144fb851dSZheng Liu 			ext4_warning(inode->i_sb,
179244fb851dSZheng Liu 				     "ES len assertion failed for inode "
179344fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
179444fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
179544fb851dSZheng Liu 			WARN_ON(1);
1796921f266bSDmitry Monakhov 		}
1797921f266bSDmitry Monakhov 
1798f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1799f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1800f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1801f7fec032SZheng Liu 					    map->m_pblk, status);
1802f7fec032SZheng Liu 		if (ret != 0)
1803f7fec032SZheng Liu 			retval = ret;
18045356f261SAditya Kali 	}
18055356f261SAditya Kali 
18065356f261SAditya Kali out_unlock:
18075356f261SAditya Kali 	up_read((&EXT4_I(inode)->i_data_sem));
18085356f261SAditya Kali 
18095356f261SAditya Kali 	return retval;
18105356f261SAditya Kali }
18115356f261SAditya Kali 
18125356f261SAditya Kali /*
1813d91bd2c1SSeunghun Lee  * This is a special get_block_t callback which is used by
1814b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
1815b920c755STheodore Ts'o  * reserve space for a single block.
181629fa89d0SAneesh Kumar K.V  *
181729fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
181829fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
181929fa89d0SAneesh Kumar K.V  *
182029fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
182129fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
182229fa89d0SAneesh Kumar K.V  * initialized properly.
182364769240SAlex Tomas  */
18249c3569b5STao Ma int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
18252ed88685STheodore Ts'o 			   struct buffer_head *bh, int create)
182664769240SAlex Tomas {
18272ed88685STheodore Ts'o 	struct ext4_map_blocks map;
182864769240SAlex Tomas 	int ret = 0;
182964769240SAlex Tomas 
183064769240SAlex Tomas 	BUG_ON(create == 0);
18312ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
18322ed88685STheodore Ts'o 
18332ed88685STheodore Ts'o 	map.m_lblk = iblock;
18342ed88685STheodore Ts'o 	map.m_len = 1;
183564769240SAlex Tomas 
183664769240SAlex Tomas 	/*
183764769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
183864769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
183964769240SAlex Tomas 	 * the same as allocated blocks.
184064769240SAlex Tomas 	 */
18415356f261SAditya Kali 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
18425356f261SAditya Kali 	if (ret <= 0)
18432ed88685STheodore Ts'o 		return ret;
184464769240SAlex Tomas 
18452ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
1846ed8ad838SJan Kara 	ext4_update_bh_state(bh, map.m_flags);
18472ed88685STheodore Ts'o 
18482ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
18492ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
18502ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
18512ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
18522ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
18532ed88685STheodore Ts'o 		 * for partial write.
18542ed88685STheodore Ts'o 		 */
18552ed88685STheodore Ts'o 		set_buffer_new(bh);
1856c8205636STheodore Ts'o 		set_buffer_mapped(bh);
18572ed88685STheodore Ts'o 	}
18582ed88685STheodore Ts'o 	return 0;
185964769240SAlex Tomas }
186061628a3fSMingming Cao 
186162e086beSAneesh Kumar K.V static int __ext4_journalled_writepage(struct page *page,
186262e086beSAneesh Kumar K.V 				       unsigned int len)
186362e086beSAneesh Kumar K.V {
186462e086beSAneesh Kumar K.V 	struct address_space *mapping = page->mapping;
186562e086beSAneesh Kumar K.V 	struct inode *inode = mapping->host;
186662e086beSAneesh Kumar K.V 	handle_t *handle = NULL;
18673fdcfb66STao Ma 	int ret = 0, err = 0;
18683fdcfb66STao Ma 	int inline_data = ext4_has_inline_data(inode);
18693fdcfb66STao Ma 	struct buffer_head *inode_bh = NULL;
18705c48a7dfSZhang Yi 	loff_t size;
187162e086beSAneesh Kumar K.V 
1872cb20d518STheodore Ts'o 	ClearPageChecked(page);
18733fdcfb66STao Ma 
18743fdcfb66STao Ma 	if (inline_data) {
18753fdcfb66STao Ma 		BUG_ON(page->index != 0);
18763fdcfb66STao Ma 		BUG_ON(len > ext4_get_max_inline_size(inode));
18773fdcfb66STao Ma 		inode_bh = ext4_journalled_write_inline_data(inode, len, page);
18783fdcfb66STao Ma 		if (inode_bh == NULL)
18793fdcfb66STao Ma 			goto out;
18803fdcfb66STao Ma 	}
1881bdf96838STheodore Ts'o 	/*
1882bdf96838STheodore Ts'o 	 * We need to release the page lock before we start the
1883bdf96838STheodore Ts'o 	 * journal, so grab a reference so the page won't disappear
1884bdf96838STheodore Ts'o 	 * out from under us.
1885bdf96838STheodore Ts'o 	 */
1886bdf96838STheodore Ts'o 	get_page(page);
188762e086beSAneesh Kumar K.V 	unlock_page(page);
188862e086beSAneesh Kumar K.V 
18899924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
18909924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
189162e086beSAneesh Kumar K.V 	if (IS_ERR(handle)) {
189262e086beSAneesh Kumar K.V 		ret = PTR_ERR(handle);
1893bdf96838STheodore Ts'o 		put_page(page);
1894bdf96838STheodore Ts'o 		goto out_no_pagelock;
1895bdf96838STheodore Ts'o 	}
1896bdf96838STheodore Ts'o 	BUG_ON(!ext4_handle_valid(handle));
1897bdf96838STheodore Ts'o 
1898bdf96838STheodore Ts'o 	lock_page(page);
1899bdf96838STheodore Ts'o 	put_page(page);
19005c48a7dfSZhang Yi 	size = i_size_read(inode);
19015c48a7dfSZhang Yi 	if (page->mapping != mapping || page_offset(page) > size) {
1902bdf96838STheodore Ts'o 		/* The page got truncated from under us */
1903bdf96838STheodore Ts'o 		ext4_journal_stop(handle);
1904bdf96838STheodore Ts'o 		ret = 0;
190562e086beSAneesh Kumar K.V 		goto out;
190662e086beSAneesh Kumar K.V 	}
190762e086beSAneesh Kumar K.V 
19083fdcfb66STao Ma 	if (inline_data) {
1909362eca70STheodore Ts'o 		ret = ext4_mark_inode_dirty(handle, inode);
19103fdcfb66STao Ma 	} else {
19115c48a7dfSZhang Yi 		struct buffer_head *page_bufs = page_buffers(page);
19125c48a7dfSZhang Yi 
19135c48a7dfSZhang Yi 		if (page->index == size >> PAGE_SHIFT)
19145c48a7dfSZhang Yi 			len = size & ~PAGE_MASK;
19155c48a7dfSZhang Yi 		else
19165c48a7dfSZhang Yi 			len = PAGE_SIZE;
19175c48a7dfSZhang Yi 
1918188c299eSJan Kara 		ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1919188c299eSJan Kara 					     NULL, do_journal_get_write_access);
192062e086beSAneesh Kumar K.V 
1921188c299eSJan Kara 		err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1922188c299eSJan Kara 					     NULL, write_end_fn);
19233fdcfb66STao Ma 	}
192462e086beSAneesh Kumar K.V 	if (ret == 0)
192562e086beSAneesh Kumar K.V 		ret = err;
1926b5b18160SJan Kara 	err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
1927afb585a9SMauricio Faria de Oliveira 	if (ret == 0)
1928afb585a9SMauricio Faria de Oliveira 		ret = err;
19292d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
193062e086beSAneesh Kumar K.V 	err = ext4_journal_stop(handle);
193162e086beSAneesh Kumar K.V 	if (!ret)
193262e086beSAneesh Kumar K.V 		ret = err;
193362e086beSAneesh Kumar K.V 
193419f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
193562e086beSAneesh Kumar K.V out:
1936bdf96838STheodore Ts'o 	unlock_page(page);
1937bdf96838STheodore Ts'o out_no_pagelock:
19383fdcfb66STao Ma 	brelse(inode_bh);
193962e086beSAneesh Kumar K.V 	return ret;
194062e086beSAneesh Kumar K.V }
194162e086beSAneesh Kumar K.V 
194261628a3fSMingming Cao /*
194343ce1d23SAneesh Kumar K.V  * Note that we don't need to start a transaction unless we're journaling data
194443ce1d23SAneesh Kumar K.V  * because we should have holes filled from ext4_page_mkwrite(). We even don't
194543ce1d23SAneesh Kumar K.V  * need to file the inode to the transaction's list in ordered mode because if
194643ce1d23SAneesh Kumar K.V  * we are writing back data added by write(), the inode is already there and if
194743ce1d23SAneesh Kumar K.V  * we are writing back data modified via mmap(), no one guarantees in which
194843ce1d23SAneesh Kumar K.V  * transaction the data will hit the disk. In case we are journaling data, we
194943ce1d23SAneesh Kumar K.V  * cannot start transaction directly because transaction start ranks above page
195043ce1d23SAneesh Kumar K.V  * lock so we have to do some magic.
195143ce1d23SAneesh Kumar K.V  *
1952b920c755STheodore Ts'o  * This function can get called via...
195320970ba6STheodore Ts'o  *   - ext4_writepages after taking page lock (have journal handle)
1954b920c755STheodore Ts'o  *   - journal_submit_inode_data_buffers (no journal handle)
1955f6463b0dSArtem Bityutskiy  *   - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1956b920c755STheodore Ts'o  *   - grab_page_cache when doing write_begin (have journal handle)
195743ce1d23SAneesh Kumar K.V  *
195843ce1d23SAneesh Kumar K.V  * We don't do any block allocation in this function. If we have page with
195943ce1d23SAneesh Kumar K.V  * multiple blocks we need to write those buffer_heads that are mapped. This
196043ce1d23SAneesh Kumar K.V  * is important for mmaped based write. So if we do with blocksize 1K
196143ce1d23SAneesh Kumar K.V  * truncate(f, 1024);
196243ce1d23SAneesh Kumar K.V  * a = mmap(f, 0, 4096);
196343ce1d23SAneesh Kumar K.V  * a[0] = 'a';
196443ce1d23SAneesh Kumar K.V  * truncate(f, 4096);
196543ce1d23SAneesh Kumar K.V  * we have in the page first buffer_head mapped via page_mkwrite call back
196690802ed9SPaul Bolle  * but other buffer_heads would be unmapped but dirty (dirty done via the
196743ce1d23SAneesh Kumar K.V  * do_wp_page). So writepage should write the first block. If we modify
196843ce1d23SAneesh Kumar K.V  * the mmap area beyond 1024 we will again get a page_fault and the
196943ce1d23SAneesh Kumar K.V  * page_mkwrite callback will do the block allocation and mark the
197043ce1d23SAneesh Kumar K.V  * buffer_heads mapped.
197143ce1d23SAneesh Kumar K.V  *
197243ce1d23SAneesh Kumar K.V  * We redirty the page if we have any buffer_heads that is either delay or
197343ce1d23SAneesh Kumar K.V  * unwritten in the page.
197443ce1d23SAneesh Kumar K.V  *
197543ce1d23SAneesh Kumar K.V  * We can get recursively called as show below.
197643ce1d23SAneesh Kumar K.V  *
197743ce1d23SAneesh Kumar K.V  *	ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
197843ce1d23SAneesh Kumar K.V  *		ext4_writepage()
197943ce1d23SAneesh Kumar K.V  *
198043ce1d23SAneesh Kumar K.V  * But since we don't do any block allocation we should not deadlock.
198143ce1d23SAneesh Kumar K.V  * Page also have the dirty flag cleared so we don't get recurive page_lock.
198261628a3fSMingming Cao  */
198343ce1d23SAneesh Kumar K.V static int ext4_writepage(struct page *page,
198464769240SAlex Tomas 			  struct writeback_control *wbc)
198564769240SAlex Tomas {
1986020df9baSMatthew Wilcox (Oracle) 	struct folio *folio = page_folio(page);
1987f8bec370SJan Kara 	int ret = 0;
198861628a3fSMingming Cao 	loff_t size;
1989498e5f24STheodore Ts'o 	unsigned int len;
1990744692dcSJiaying Zhang 	struct buffer_head *page_bufs = NULL;
199161628a3fSMingming Cao 	struct inode *inode = page->mapping->host;
199236ade451SJan Kara 	struct ext4_io_submit io_submit;
19931c8349a1SNamjae Jeon 	bool keep_towrite = false;
199464769240SAlex Tomas 
19950db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
1996020df9baSMatthew Wilcox (Oracle) 		folio_invalidate(folio, 0, folio_size(folio));
1997020df9baSMatthew Wilcox (Oracle) 		folio_unlock(folio);
19980db1ff22STheodore Ts'o 		return -EIO;
19990db1ff22STheodore Ts'o 	}
20000db1ff22STheodore Ts'o 
2001a9c667f8SLukas Czerner 	trace_ext4_writepage(page);
200261628a3fSMingming Cao 	size = i_size_read(inode);
2003c93d8f88SEric Biggers 	if (page->index == size >> PAGE_SHIFT &&
2004c93d8f88SEric Biggers 	    !ext4_verity_in_progress(inode))
200509cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
200661628a3fSMingming Cao 	else
200709cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
200861628a3fSMingming Cao 
2009cc509574STheodore Ts'o 	/* Should never happen but for bugs in other kernel subsystems */
2010cc509574STheodore Ts'o 	if (!page_has_buffers(page)) {
2011cc509574STheodore Ts'o 		ext4_warning_inode(inode,
2012cc509574STheodore Ts'o 		   "page %lu does not have buffers attached", page->index);
2013cc509574STheodore Ts'o 		ClearPageDirty(page);
2014cc509574STheodore Ts'o 		unlock_page(page);
2015cc509574STheodore Ts'o 		return 0;
2016cc509574STheodore Ts'o 	}
2017cc509574STheodore Ts'o 
2018f0e6c985SAneesh Kumar K.V 	page_bufs = page_buffers(page);
201964769240SAlex Tomas 	/*
2020fe386132SJan Kara 	 * We cannot do block allocation or other extent handling in this
2021fe386132SJan Kara 	 * function. If there are buffers needing that, we have to redirty
2022fe386132SJan Kara 	 * the page. But we may reach here when we do a journal commit via
2023fe386132SJan Kara 	 * journal_submit_inode_data_buffers() and in that case we must write
2024fe386132SJan Kara 	 * allocated buffers to achieve data=ordered mode guarantees.
2025cccd147aSTheodore Ts'o 	 *
2026cccd147aSTheodore Ts'o 	 * Also, if there is only one buffer per page (the fs block
2027cccd147aSTheodore Ts'o 	 * size == the page size), if one buffer needs block
2028cccd147aSTheodore Ts'o 	 * allocation or needs to modify the extent tree to clear the
2029cccd147aSTheodore Ts'o 	 * unwritten flag, we know that the page can't be written at
2030cccd147aSTheodore Ts'o 	 * all, so we might as well refuse the write immediately.
2031cccd147aSTheodore Ts'o 	 * Unfortunately if the block size != page size, we can't as
2032cccd147aSTheodore Ts'o 	 * easily detect this case using ext4_walk_page_buffers(), but
2033cccd147aSTheodore Ts'o 	 * for the extremely common case, this is an optimization that
2034cccd147aSTheodore Ts'o 	 * skips a useless round trip through ext4_bio_write_page().
203564769240SAlex Tomas 	 */
2036188c299eSJan Kara 	if (ext4_walk_page_buffers(NULL, inode, page_bufs, 0, len, NULL,
2037c364b22cSAneesh Kumar K.V 				   ext4_bh_delay_or_unwritten)) {
203861628a3fSMingming Cao 		redirty_page_for_writepage(wbc, page);
2039cccd147aSTheodore Ts'o 		if ((current->flags & PF_MEMALLOC) ||
204009cbfeafSKirill A. Shutemov 		    (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2041fe386132SJan Kara 			/*
2042fe386132SJan Kara 			 * For memory cleaning there's no point in writing only
2043fe386132SJan Kara 			 * some buffers. So just bail out. Warn if we came here
2044fe386132SJan Kara 			 * from direct reclaim.
2045fe386132SJan Kara 			 */
2046fe386132SJan Kara 			WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2047fe386132SJan Kara 							== PF_MEMALLOC);
204861628a3fSMingming Cao 			unlock_page(page);
204961628a3fSMingming Cao 			return 0;
205061628a3fSMingming Cao 		}
20511c8349a1SNamjae Jeon 		keep_towrite = true;
2052f0e6c985SAneesh Kumar K.V 	}
205364769240SAlex Tomas 
2054cb20d518STheodore Ts'o 	if (PageChecked(page) && ext4_should_journal_data(inode))
205543ce1d23SAneesh Kumar K.V 		/*
205643ce1d23SAneesh Kumar K.V 		 * It's mmapped pagecache.  Add buffers and journal it.  There
205743ce1d23SAneesh Kumar K.V 		 * doesn't seem much point in redirtying the page here.
205843ce1d23SAneesh Kumar K.V 		 */
20593f0ca309SWu Fengguang 		return __ext4_journalled_writepage(page, len);
206043ce1d23SAneesh Kumar K.V 
206197a851edSJan Kara 	ext4_io_submit_init(&io_submit, wbc);
206297a851edSJan Kara 	io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
206397a851edSJan Kara 	if (!io_submit.io_end) {
206497a851edSJan Kara 		redirty_page_for_writepage(wbc, page);
206597a851edSJan Kara 		unlock_page(page);
206697a851edSJan Kara 		return -ENOMEM;
206797a851edSJan Kara 	}
2068be993933SLei Chen 	ret = ext4_bio_write_page(&io_submit, page, len, keep_towrite);
206936ade451SJan Kara 	ext4_io_submit(&io_submit);
207097a851edSJan Kara 	/* Drop io_end reference we got from init */
207197a851edSJan Kara 	ext4_put_io_end_defer(io_submit.io_end);
207264769240SAlex Tomas 	return ret;
207364769240SAlex Tomas }
207464769240SAlex Tomas 
20755f1132b2SJan Kara static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
20765f1132b2SJan Kara {
20775f1132b2SJan Kara 	int len;
2078a056bdaaSJan Kara 	loff_t size;
20795f1132b2SJan Kara 	int err;
20805f1132b2SJan Kara 
20815f1132b2SJan Kara 	BUG_ON(page->index != mpd->first_page);
2082a056bdaaSJan Kara 	clear_page_dirty_for_io(page);
2083a056bdaaSJan Kara 	/*
2084a056bdaaSJan Kara 	 * We have to be very careful here!  Nothing protects writeback path
2085a056bdaaSJan Kara 	 * against i_size changes and the page can be writeably mapped into
2086a056bdaaSJan Kara 	 * page tables. So an application can be growing i_size and writing
2087a056bdaaSJan Kara 	 * data through mmap while writeback runs. clear_page_dirty_for_io()
2088a056bdaaSJan Kara 	 * write-protects our page in page tables and the page cannot get
2089a056bdaaSJan Kara 	 * written to again until we release page lock. So only after
2090a056bdaaSJan Kara 	 * clear_page_dirty_for_io() we are safe to sample i_size for
2091a056bdaaSJan Kara 	 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2092a056bdaaSJan Kara 	 * on the barrier provided by TestClearPageDirty in
2093a056bdaaSJan Kara 	 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2094a056bdaaSJan Kara 	 * after page tables are updated.
2095a056bdaaSJan Kara 	 */
2096a056bdaaSJan Kara 	size = i_size_read(mpd->inode);
2097c93d8f88SEric Biggers 	if (page->index == size >> PAGE_SHIFT &&
2098c93d8f88SEric Biggers 	    !ext4_verity_in_progress(mpd->inode))
209909cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
21005f1132b2SJan Kara 	else
210109cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
2102be993933SLei Chen 	err = ext4_bio_write_page(&mpd->io_submit, page, len, false);
21035f1132b2SJan Kara 	if (!err)
21045f1132b2SJan Kara 		mpd->wbc->nr_to_write--;
21055f1132b2SJan Kara 	mpd->first_page++;
21065f1132b2SJan Kara 
21075f1132b2SJan Kara 	return err;
21085f1132b2SJan Kara }
21095f1132b2SJan Kara 
21106db07461SRitesh Harjani #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
21114e7ea81dSJan Kara 
211261628a3fSMingming Cao /*
2113fffb2739SJan Kara  * mballoc gives us at most this number of blocks...
2114fffb2739SJan Kara  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2115fffb2739SJan Kara  * The rest of mballoc seems to handle chunks up to full group size.
211661628a3fSMingming Cao  */
2117fffb2739SJan Kara #define MAX_WRITEPAGES_EXTENT_LEN 2048
2118525f4ed8SMingming Cao 
2119525f4ed8SMingming Cao /*
21204e7ea81dSJan Kara  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
21214e7ea81dSJan Kara  *
21224e7ea81dSJan Kara  * @mpd - extent of blocks
21234e7ea81dSJan Kara  * @lblk - logical number of the block in the file
212409930042SJan Kara  * @bh - buffer head we want to add to the extent
21254e7ea81dSJan Kara  *
212609930042SJan Kara  * The function is used to collect contig. blocks in the same state. If the
212709930042SJan Kara  * buffer doesn't require mapping for writeback and we haven't started the
212809930042SJan Kara  * extent of buffers to map yet, the function returns 'true' immediately - the
212909930042SJan Kara  * caller can write the buffer right away. Otherwise the function returns true
213009930042SJan Kara  * if the block has been added to the extent, false if the block couldn't be
213109930042SJan Kara  * added.
21324e7ea81dSJan Kara  */
213309930042SJan Kara static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
213409930042SJan Kara 				   struct buffer_head *bh)
21354e7ea81dSJan Kara {
21364e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
21374e7ea81dSJan Kara 
213809930042SJan Kara 	/* Buffer that doesn't need mapping for writeback? */
213909930042SJan Kara 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
214009930042SJan Kara 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
214109930042SJan Kara 		/* So far no extent to map => we write the buffer right away */
214209930042SJan Kara 		if (map->m_len == 0)
214309930042SJan Kara 			return true;
214409930042SJan Kara 		return false;
214509930042SJan Kara 	}
21464e7ea81dSJan Kara 
21474e7ea81dSJan Kara 	/* First block in the extent? */
21484e7ea81dSJan Kara 	if (map->m_len == 0) {
2149dddbd6acSJan Kara 		/* We cannot map unless handle is started... */
2150dddbd6acSJan Kara 		if (!mpd->do_map)
2151dddbd6acSJan Kara 			return false;
21524e7ea81dSJan Kara 		map->m_lblk = lblk;
21534e7ea81dSJan Kara 		map->m_len = 1;
215409930042SJan Kara 		map->m_flags = bh->b_state & BH_FLAGS;
215509930042SJan Kara 		return true;
21564e7ea81dSJan Kara 	}
21574e7ea81dSJan Kara 
215809930042SJan Kara 	/* Don't go larger than mballoc is willing to allocate */
215909930042SJan Kara 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
216009930042SJan Kara 		return false;
216109930042SJan Kara 
21624e7ea81dSJan Kara 	/* Can we merge the block to our big extent? */
21634e7ea81dSJan Kara 	if (lblk == map->m_lblk + map->m_len &&
216409930042SJan Kara 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
21654e7ea81dSJan Kara 		map->m_len++;
216609930042SJan Kara 		return true;
21674e7ea81dSJan Kara 	}
216809930042SJan Kara 	return false;
21694e7ea81dSJan Kara }
21704e7ea81dSJan Kara 
21715f1132b2SJan Kara /*
21725f1132b2SJan Kara  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
21735f1132b2SJan Kara  *
21745f1132b2SJan Kara  * @mpd - extent of blocks for mapping
21755f1132b2SJan Kara  * @head - the first buffer in the page
21765f1132b2SJan Kara  * @bh - buffer we should start processing from
21775f1132b2SJan Kara  * @lblk - logical number of the block in the file corresponding to @bh
21785f1132b2SJan Kara  *
21795f1132b2SJan Kara  * Walk through page buffers from @bh upto @head (exclusive) and either submit
21805f1132b2SJan Kara  * the page for IO if all buffers in this page were mapped and there's no
21815f1132b2SJan Kara  * accumulated extent of buffers to map or add buffers in the page to the
21825f1132b2SJan Kara  * extent of buffers to map. The function returns 1 if the caller can continue
21835f1132b2SJan Kara  * by processing the next page, 0 if it should stop adding buffers to the
21845f1132b2SJan Kara  * extent to map because we cannot extend it anymore. It can also return value
21855f1132b2SJan Kara  * < 0 in case of error during IO submission.
21865f1132b2SJan Kara  */
21875f1132b2SJan Kara static int mpage_process_page_bufs(struct mpage_da_data *mpd,
21884e7ea81dSJan Kara 				   struct buffer_head *head,
21894e7ea81dSJan Kara 				   struct buffer_head *bh,
21904e7ea81dSJan Kara 				   ext4_lblk_t lblk)
21914e7ea81dSJan Kara {
21924e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
21935f1132b2SJan Kara 	int err;
219493407472SFabian Frederick 	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
21954e7ea81dSJan Kara 							>> inode->i_blkbits;
21964e7ea81dSJan Kara 
2197c93d8f88SEric Biggers 	if (ext4_verity_in_progress(inode))
2198c93d8f88SEric Biggers 		blocks = EXT_MAX_BLOCKS;
2199c93d8f88SEric Biggers 
22004e7ea81dSJan Kara 	do {
22014e7ea81dSJan Kara 		BUG_ON(buffer_locked(bh));
22024e7ea81dSJan Kara 
220309930042SJan Kara 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
22044e7ea81dSJan Kara 			/* Found extent to map? */
22054e7ea81dSJan Kara 			if (mpd->map.m_len)
22065f1132b2SJan Kara 				return 0;
2207dddbd6acSJan Kara 			/* Buffer needs mapping and handle is not started? */
2208dddbd6acSJan Kara 			if (!mpd->do_map)
2209dddbd6acSJan Kara 				return 0;
221009930042SJan Kara 			/* Everything mapped so far and we hit EOF */
22115f1132b2SJan Kara 			break;
22124e7ea81dSJan Kara 		}
22134e7ea81dSJan Kara 	} while (lblk++, (bh = bh->b_this_page) != head);
22145f1132b2SJan Kara 	/* So far everything mapped? Submit the page for IO. */
22155f1132b2SJan Kara 	if (mpd->map.m_len == 0) {
22165f1132b2SJan Kara 		err = mpage_submit_page(mpd, head->b_page);
22175f1132b2SJan Kara 		if (err < 0)
22184e7ea81dSJan Kara 			return err;
22194e7ea81dSJan Kara 	}
22206b8ed620SJan Kara 	if (lblk >= blocks) {
22216b8ed620SJan Kara 		mpd->scanned_until_end = 1;
22226b8ed620SJan Kara 		return 0;
22236b8ed620SJan Kara 	}
22246b8ed620SJan Kara 	return 1;
22255f1132b2SJan Kara }
22264e7ea81dSJan Kara 
22274e7ea81dSJan Kara /*
22282943fdbcSRitesh Harjani  * mpage_process_page - update page buffers corresponding to changed extent and
22292943fdbcSRitesh Harjani  *		       may submit fully mapped page for IO
22302943fdbcSRitesh Harjani  *
22312943fdbcSRitesh Harjani  * @mpd		- description of extent to map, on return next extent to map
22322943fdbcSRitesh Harjani  * @m_lblk	- logical block mapping.
22332943fdbcSRitesh Harjani  * @m_pblk	- corresponding physical mapping.
22342943fdbcSRitesh Harjani  * @map_bh	- determines on return whether this page requires any further
22352943fdbcSRitesh Harjani  *		  mapping or not.
22362943fdbcSRitesh Harjani  * Scan given page buffers corresponding to changed extent and update buffer
22372943fdbcSRitesh Harjani  * state according to new extent state.
22382943fdbcSRitesh Harjani  * We map delalloc buffers to their physical location, clear unwritten bits.
22392943fdbcSRitesh Harjani  * If the given page is not fully mapped, we update @map to the next extent in
22402943fdbcSRitesh Harjani  * the given page that needs mapping & return @map_bh as true.
22412943fdbcSRitesh Harjani  */
22422943fdbcSRitesh Harjani static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
22432943fdbcSRitesh Harjani 			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
22442943fdbcSRitesh Harjani 			      bool *map_bh)
22452943fdbcSRitesh Harjani {
22462943fdbcSRitesh Harjani 	struct buffer_head *head, *bh;
22472943fdbcSRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
22482943fdbcSRitesh Harjani 	ext4_lblk_t lblk = *m_lblk;
22492943fdbcSRitesh Harjani 	ext4_fsblk_t pblock = *m_pblk;
22502943fdbcSRitesh Harjani 	int err = 0;
2251c8cc8816SRitesh Harjani 	int blkbits = mpd->inode->i_blkbits;
2252c8cc8816SRitesh Harjani 	ssize_t io_end_size = 0;
2253c8cc8816SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
22542943fdbcSRitesh Harjani 
22552943fdbcSRitesh Harjani 	bh = head = page_buffers(page);
22562943fdbcSRitesh Harjani 	do {
22572943fdbcSRitesh Harjani 		if (lblk < mpd->map.m_lblk)
22582943fdbcSRitesh Harjani 			continue;
22592943fdbcSRitesh Harjani 		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
22602943fdbcSRitesh Harjani 			/*
22612943fdbcSRitesh Harjani 			 * Buffer after end of mapped extent.
22622943fdbcSRitesh Harjani 			 * Find next buffer in the page to map.
22632943fdbcSRitesh Harjani 			 */
22642943fdbcSRitesh Harjani 			mpd->map.m_len = 0;
22652943fdbcSRitesh Harjani 			mpd->map.m_flags = 0;
2266c8cc8816SRitesh Harjani 			io_end_vec->size += io_end_size;
22672943fdbcSRitesh Harjani 
22682943fdbcSRitesh Harjani 			err = mpage_process_page_bufs(mpd, head, bh, lblk);
22692943fdbcSRitesh Harjani 			if (err > 0)
22702943fdbcSRitesh Harjani 				err = 0;
2271c8cc8816SRitesh Harjani 			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2272c8cc8816SRitesh Harjani 				io_end_vec = ext4_alloc_io_end_vec(io_end);
22734d06bfb9SRitesh Harjani 				if (IS_ERR(io_end_vec)) {
22744d06bfb9SRitesh Harjani 					err = PTR_ERR(io_end_vec);
22754d06bfb9SRitesh Harjani 					goto out;
22764d06bfb9SRitesh Harjani 				}
2277d1e18b88SRitesh Harjani 				io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2278c8cc8816SRitesh Harjani 			}
22792943fdbcSRitesh Harjani 			*map_bh = true;
22802943fdbcSRitesh Harjani 			goto out;
22812943fdbcSRitesh Harjani 		}
22822943fdbcSRitesh Harjani 		if (buffer_delay(bh)) {
22832943fdbcSRitesh Harjani 			clear_buffer_delay(bh);
22842943fdbcSRitesh Harjani 			bh->b_blocknr = pblock++;
22852943fdbcSRitesh Harjani 		}
22862943fdbcSRitesh Harjani 		clear_buffer_unwritten(bh);
2287c8cc8816SRitesh Harjani 		io_end_size += (1 << blkbits);
22882943fdbcSRitesh Harjani 	} while (lblk++, (bh = bh->b_this_page) != head);
2289c8cc8816SRitesh Harjani 
2290c8cc8816SRitesh Harjani 	io_end_vec->size += io_end_size;
22912943fdbcSRitesh Harjani 	*map_bh = false;
22922943fdbcSRitesh Harjani out:
22932943fdbcSRitesh Harjani 	*m_lblk = lblk;
22942943fdbcSRitesh Harjani 	*m_pblk = pblock;
22952943fdbcSRitesh Harjani 	return err;
22962943fdbcSRitesh Harjani }
22972943fdbcSRitesh Harjani 
22982943fdbcSRitesh Harjani /*
22994e7ea81dSJan Kara  * mpage_map_buffers - update buffers corresponding to changed extent and
23004e7ea81dSJan Kara  *		       submit fully mapped pages for IO
23014e7ea81dSJan Kara  *
23024e7ea81dSJan Kara  * @mpd - description of extent to map, on return next extent to map
23034e7ea81dSJan Kara  *
23044e7ea81dSJan Kara  * Scan buffers corresponding to changed extent (we expect corresponding pages
23054e7ea81dSJan Kara  * to be already locked) and update buffer state according to new extent state.
23064e7ea81dSJan Kara  * We map delalloc buffers to their physical location, clear unwritten bits,
2307556615dcSLukas Czerner  * and mark buffers as uninit when we perform writes to unwritten extents
23084e7ea81dSJan Kara  * and do extent conversion after IO is finished. If the last page is not fully
23094e7ea81dSJan Kara  * mapped, we update @map to the next extent in the last page that needs
23104e7ea81dSJan Kara  * mapping. Otherwise we submit the page for IO.
23114e7ea81dSJan Kara  */
23124e7ea81dSJan Kara static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
23134e7ea81dSJan Kara {
23144e7ea81dSJan Kara 	struct pagevec pvec;
23154e7ea81dSJan Kara 	int nr_pages, i;
23164e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
231709cbfeafSKirill A. Shutemov 	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
23184e7ea81dSJan Kara 	pgoff_t start, end;
23194e7ea81dSJan Kara 	ext4_lblk_t lblk;
23202943fdbcSRitesh Harjani 	ext4_fsblk_t pblock;
23214e7ea81dSJan Kara 	int err;
23222943fdbcSRitesh Harjani 	bool map_bh = false;
23234e7ea81dSJan Kara 
23244e7ea81dSJan Kara 	start = mpd->map.m_lblk >> bpp_bits;
23254e7ea81dSJan Kara 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
23264e7ea81dSJan Kara 	lblk = start << bpp_bits;
23274e7ea81dSJan Kara 	pblock = mpd->map.m_pblk;
23284e7ea81dSJan Kara 
232986679820SMel Gorman 	pagevec_init(&pvec);
23304e7ea81dSJan Kara 	while (start <= end) {
23312b85a617SJan Kara 		nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2332397162ffSJan Kara 						&start, end);
23334e7ea81dSJan Kara 		if (nr_pages == 0)
23344e7ea81dSJan Kara 			break;
23354e7ea81dSJan Kara 		for (i = 0; i < nr_pages; i++) {
23364e7ea81dSJan Kara 			struct page *page = pvec.pages[i];
23374e7ea81dSJan Kara 
23382943fdbcSRitesh Harjani 			err = mpage_process_page(mpd, page, &lblk, &pblock,
23392943fdbcSRitesh Harjani 						 &map_bh);
23404e7ea81dSJan Kara 			/*
23412943fdbcSRitesh Harjani 			 * If map_bh is true, means page may require further bh
23422943fdbcSRitesh Harjani 			 * mapping, or maybe the page was submitted for IO.
23432943fdbcSRitesh Harjani 			 * So we return to call further extent mapping.
23444e7ea81dSJan Kara 			 */
234539c0ae16SJason Yan 			if (err < 0 || map_bh)
23462943fdbcSRitesh Harjani 				goto out;
23474e7ea81dSJan Kara 			/* Page fully mapped - let IO run! */
23484e7ea81dSJan Kara 			err = mpage_submit_page(mpd, page);
23492943fdbcSRitesh Harjani 			if (err < 0)
23502943fdbcSRitesh Harjani 				goto out;
23514e7ea81dSJan Kara 		}
23524e7ea81dSJan Kara 		pagevec_release(&pvec);
23534e7ea81dSJan Kara 	}
23544e7ea81dSJan Kara 	/* Extent fully mapped and matches with page boundary. We are done. */
23554e7ea81dSJan Kara 	mpd->map.m_len = 0;
23564e7ea81dSJan Kara 	mpd->map.m_flags = 0;
23574e7ea81dSJan Kara 	return 0;
23582943fdbcSRitesh Harjani out:
23592943fdbcSRitesh Harjani 	pagevec_release(&pvec);
23602943fdbcSRitesh Harjani 	return err;
23614e7ea81dSJan Kara }
23624e7ea81dSJan Kara 
23634e7ea81dSJan Kara static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
23644e7ea81dSJan Kara {
23654e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
23664e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
23674e7ea81dSJan Kara 	int get_blocks_flags;
2368090f32eeSLukas Czerner 	int err, dioread_nolock;
23694e7ea81dSJan Kara 
23704e7ea81dSJan Kara 	trace_ext4_da_write_pages_extent(inode, map);
23714e7ea81dSJan Kara 	/*
23724e7ea81dSJan Kara 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2373556615dcSLukas Czerner 	 * to convert an unwritten extent to be initialized (in the case
23744e7ea81dSJan Kara 	 * where we have written into one or more preallocated blocks).  It is
23754e7ea81dSJan Kara 	 * possible that we're going to need more metadata blocks than
23764e7ea81dSJan Kara 	 * previously reserved. However we must not fail because we're in
23774e7ea81dSJan Kara 	 * writeback and there is nothing we can do about it so it might result
23784e7ea81dSJan Kara 	 * in data loss.  So use reserved blocks to allocate metadata if
23794e7ea81dSJan Kara 	 * possible.
23804e7ea81dSJan Kara 	 *
2381754cfed6STheodore Ts'o 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2382754cfed6STheodore Ts'o 	 * the blocks in question are delalloc blocks.  This indicates
2383754cfed6STheodore Ts'o 	 * that the blocks and quotas has already been checked when
2384754cfed6STheodore Ts'o 	 * the data was copied into the page cache.
23854e7ea81dSJan Kara 	 */
23864e7ea81dSJan Kara 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2387ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2388ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_IO_SUBMIT;
2389090f32eeSLukas Czerner 	dioread_nolock = ext4_should_dioread_nolock(inode);
2390090f32eeSLukas Czerner 	if (dioread_nolock)
23914e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
23926db07461SRitesh Harjani 	if (map->m_flags & BIT(BH_Delay))
23934e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
23944e7ea81dSJan Kara 
23954e7ea81dSJan Kara 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
23964e7ea81dSJan Kara 	if (err < 0)
23974e7ea81dSJan Kara 		return err;
2398090f32eeSLukas Czerner 	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
23996b523df4SJan Kara 		if (!mpd->io_submit.io_end->handle &&
24006b523df4SJan Kara 		    ext4_handle_valid(handle)) {
24016b523df4SJan Kara 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
24026b523df4SJan Kara 			handle->h_rsv_handle = NULL;
24036b523df4SJan Kara 		}
24043613d228SJan Kara 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
24056b523df4SJan Kara 	}
24064e7ea81dSJan Kara 
24074e7ea81dSJan Kara 	BUG_ON(map->m_len == 0);
24084e7ea81dSJan Kara 	return 0;
24094e7ea81dSJan Kara }
24104e7ea81dSJan Kara 
24114e7ea81dSJan Kara /*
24124e7ea81dSJan Kara  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
24134e7ea81dSJan Kara  *				 mpd->len and submit pages underlying it for IO
24144e7ea81dSJan Kara  *
24154e7ea81dSJan Kara  * @handle - handle for journal operations
24164e7ea81dSJan Kara  * @mpd - extent to map
24177534e854SJan Kara  * @give_up_on_write - we set this to true iff there is a fatal error and there
24187534e854SJan Kara  *                     is no hope of writing the data. The caller should discard
24197534e854SJan Kara  *                     dirty pages to avoid infinite loops.
24204e7ea81dSJan Kara  *
24214e7ea81dSJan Kara  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
24224e7ea81dSJan Kara  * delayed, blocks are allocated, if it is unwritten, we may need to convert
24234e7ea81dSJan Kara  * them to initialized or split the described range from larger unwritten
24244e7ea81dSJan Kara  * extent. Note that we need not map all the described range since allocation
24254e7ea81dSJan Kara  * can return less blocks or the range is covered by more unwritten extents. We
24264e7ea81dSJan Kara  * cannot map more because we are limited by reserved transaction credits. On
24274e7ea81dSJan Kara  * the other hand we always make sure that the last touched page is fully
24284e7ea81dSJan Kara  * mapped so that it can be written out (and thus forward progress is
24294e7ea81dSJan Kara  * guaranteed). After mapping we submit all mapped pages for IO.
24304e7ea81dSJan Kara  */
24314e7ea81dSJan Kara static int mpage_map_and_submit_extent(handle_t *handle,
2432cb530541STheodore Ts'o 				       struct mpage_da_data *mpd,
2433cb530541STheodore Ts'o 				       bool *give_up_on_write)
24344e7ea81dSJan Kara {
24354e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
24364e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
24374e7ea81dSJan Kara 	int err;
24384e7ea81dSJan Kara 	loff_t disksize;
24396603120eSDmitry Monakhov 	int progress = 0;
2440c8cc8816SRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
24414d06bfb9SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec;
24424e7ea81dSJan Kara 
24434d06bfb9SRitesh Harjani 	io_end_vec = ext4_alloc_io_end_vec(io_end);
24444d06bfb9SRitesh Harjani 	if (IS_ERR(io_end_vec))
24454d06bfb9SRitesh Harjani 		return PTR_ERR(io_end_vec);
2446c8cc8816SRitesh Harjani 	io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
244727d7c4edSJan Kara 	do {
24484e7ea81dSJan Kara 		err = mpage_map_one_extent(handle, mpd);
24494e7ea81dSJan Kara 		if (err < 0) {
24504e7ea81dSJan Kara 			struct super_block *sb = inode->i_sb;
24514e7ea81dSJan Kara 
24520db1ff22STheodore Ts'o 			if (ext4_forced_shutdown(EXT4_SB(sb)) ||
24539b5f6c9bSHarshad Shirwadkar 			    ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
2454cb530541STheodore Ts'o 				goto invalidate_dirty_pages;
24554e7ea81dSJan Kara 			/*
2456cb530541STheodore Ts'o 			 * Let the uper layers retry transient errors.
2457cb530541STheodore Ts'o 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2458cb530541STheodore Ts'o 			 * is non-zero, a commit should free up blocks.
24594e7ea81dSJan Kara 			 */
2460cb530541STheodore Ts'o 			if ((err == -ENOMEM) ||
24616603120eSDmitry Monakhov 			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
24626603120eSDmitry Monakhov 				if (progress)
24636603120eSDmitry Monakhov 					goto update_disksize;
2464cb530541STheodore Ts'o 				return err;
24656603120eSDmitry Monakhov 			}
24664e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24674e7ea81dSJan Kara 				 "Delayed block allocation failed for "
24684e7ea81dSJan Kara 				 "inode %lu at logical offset %llu with"
24694e7ea81dSJan Kara 				 " max blocks %u with error %d",
24704e7ea81dSJan Kara 				 inode->i_ino,
24714e7ea81dSJan Kara 				 (unsigned long long)map->m_lblk,
2472cb530541STheodore Ts'o 				 (unsigned)map->m_len, -err);
24734e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24744e7ea81dSJan Kara 				 "This should not happen!! Data will "
24754e7ea81dSJan Kara 				 "be lost\n");
24764e7ea81dSJan Kara 			if (err == -ENOSPC)
24774e7ea81dSJan Kara 				ext4_print_free_blocks(inode);
2478cb530541STheodore Ts'o 		invalidate_dirty_pages:
2479cb530541STheodore Ts'o 			*give_up_on_write = true;
24804e7ea81dSJan Kara 			return err;
24814e7ea81dSJan Kara 		}
24826603120eSDmitry Monakhov 		progress = 1;
24834e7ea81dSJan Kara 		/*
24844e7ea81dSJan Kara 		 * Update buffer state, submit mapped pages, and get us new
24854e7ea81dSJan Kara 		 * extent to map
24864e7ea81dSJan Kara 		 */
24874e7ea81dSJan Kara 		err = mpage_map_and_submit_buffers(mpd);
24884e7ea81dSJan Kara 		if (err < 0)
24896603120eSDmitry Monakhov 			goto update_disksize;
249027d7c4edSJan Kara 	} while (map->m_len);
24914e7ea81dSJan Kara 
24926603120eSDmitry Monakhov update_disksize:
2493622cad13STheodore Ts'o 	/*
2494622cad13STheodore Ts'o 	 * Update on-disk size after IO is submitted.  Races with
2495622cad13STheodore Ts'o 	 * truncate are avoided by checking i_size under i_data_sem.
2496622cad13STheodore Ts'o 	 */
249709cbfeafSKirill A. Shutemov 	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
249835df4299SQian Cai 	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
24994e7ea81dSJan Kara 		int err2;
2500622cad13STheodore Ts'o 		loff_t i_size;
25014e7ea81dSJan Kara 
2502622cad13STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
2503622cad13STheodore Ts'o 		i_size = i_size_read(inode);
2504622cad13STheodore Ts'o 		if (disksize > i_size)
2505622cad13STheodore Ts'o 			disksize = i_size;
2506622cad13STheodore Ts'o 		if (disksize > EXT4_I(inode)->i_disksize)
2507622cad13STheodore Ts'o 			EXT4_I(inode)->i_disksize = disksize;
2508622cad13STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
2509b907f2d5STheodore Ts'o 		err2 = ext4_mark_inode_dirty(handle, inode);
2510878520acSTheodore Ts'o 		if (err2) {
251154d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err2,
25124e7ea81dSJan Kara 				       "Failed to mark inode %lu dirty",
25134e7ea81dSJan Kara 				       inode->i_ino);
2514878520acSTheodore Ts'o 		}
25154e7ea81dSJan Kara 		if (!err)
25164e7ea81dSJan Kara 			err = err2;
25174e7ea81dSJan Kara 	}
25184e7ea81dSJan Kara 	return err;
25194e7ea81dSJan Kara }
25204e7ea81dSJan Kara 
25214e7ea81dSJan Kara /*
2522fffb2739SJan Kara  * Calculate the total number of credits to reserve for one writepages
252320970ba6STheodore Ts'o  * iteration. This is called from ext4_writepages(). We map an extent of
2524fffb2739SJan Kara  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2525fffb2739SJan Kara  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2526fffb2739SJan Kara  * bpp - 1 blocks in bpp different extents.
2527525f4ed8SMingming Cao  */
2528fffb2739SJan Kara static int ext4_da_writepages_trans_blocks(struct inode *inode)
2529fffb2739SJan Kara {
2530fffb2739SJan Kara 	int bpp = ext4_journal_blocks_per_page(inode);
2531525f4ed8SMingming Cao 
2532fffb2739SJan Kara 	return ext4_meta_trans_blocks(inode,
2533fffb2739SJan Kara 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2534525f4ed8SMingming Cao }
253561628a3fSMingming Cao 
25368e48dcfbSTheodore Ts'o /*
25374e7ea81dSJan Kara  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
25384e7ea81dSJan Kara  * 				 and underlying extent to map
25394e7ea81dSJan Kara  *
25404e7ea81dSJan Kara  * @mpd - where to look for pages
25414e7ea81dSJan Kara  *
25424e7ea81dSJan Kara  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
25434e7ea81dSJan Kara  * IO immediately. When we find a page which isn't mapped we start accumulating
25444e7ea81dSJan Kara  * extent of buffers underlying these pages that needs mapping (formed by
25454e7ea81dSJan Kara  * either delayed or unwritten buffers). We also lock the pages containing
25464e7ea81dSJan Kara  * these buffers. The extent found is returned in @mpd structure (starting at
25474e7ea81dSJan Kara  * mpd->lblk with length mpd->len blocks).
25484e7ea81dSJan Kara  *
25494e7ea81dSJan Kara  * Note that this function can attach bios to one io_end structure which are
25504e7ea81dSJan Kara  * neither logically nor physically contiguous. Although it may seem as an
25514e7ea81dSJan Kara  * unnecessary complication, it is actually inevitable in blocksize < pagesize
25524e7ea81dSJan Kara  * case as we need to track IO to all buffers underlying a page in one io_end.
25538e48dcfbSTheodore Ts'o  */
25544e7ea81dSJan Kara static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
25558e48dcfbSTheodore Ts'o {
25564e7ea81dSJan Kara 	struct address_space *mapping = mpd->inode->i_mapping;
25578e48dcfbSTheodore Ts'o 	struct pagevec pvec;
25584f01b02cSTheodore Ts'o 	unsigned int nr_pages;
2559aeac589aSMing Lei 	long left = mpd->wbc->nr_to_write;
25604e7ea81dSJan Kara 	pgoff_t index = mpd->first_page;
25614e7ea81dSJan Kara 	pgoff_t end = mpd->last_page;
256210bbd235SMatthew Wilcox 	xa_mark_t tag;
25634e7ea81dSJan Kara 	int i, err = 0;
25644e7ea81dSJan Kara 	int blkbits = mpd->inode->i_blkbits;
25654e7ea81dSJan Kara 	ext4_lblk_t lblk;
25664e7ea81dSJan Kara 	struct buffer_head *head;
25678e48dcfbSTheodore Ts'o 
25684e7ea81dSJan Kara 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
25695b41d924SEric Sandeen 		tag = PAGECACHE_TAG_TOWRITE;
25705b41d924SEric Sandeen 	else
25715b41d924SEric Sandeen 		tag = PAGECACHE_TAG_DIRTY;
25725b41d924SEric Sandeen 
257386679820SMel Gorman 	pagevec_init(&pvec);
25744e7ea81dSJan Kara 	mpd->map.m_len = 0;
25754e7ea81dSJan Kara 	mpd->next_page = index;
25764f01b02cSTheodore Ts'o 	while (index <= end) {
2577dc7f3e86SJan Kara 		nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
257867fd707fSJan Kara 				tag);
25798e48dcfbSTheodore Ts'o 		if (nr_pages == 0)
25806b8ed620SJan Kara 			break;
25818e48dcfbSTheodore Ts'o 
25828e48dcfbSTheodore Ts'o 		for (i = 0; i < nr_pages; i++) {
25838e48dcfbSTheodore Ts'o 			struct page *page = pvec.pages[i];
25848e48dcfbSTheodore Ts'o 
25858e48dcfbSTheodore Ts'o 			/*
2586aeac589aSMing Lei 			 * Accumulated enough dirty pages? This doesn't apply
2587aeac589aSMing Lei 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2588aeac589aSMing Lei 			 * keep going because someone may be concurrently
2589aeac589aSMing Lei 			 * dirtying pages, and we might have synced a lot of
2590aeac589aSMing Lei 			 * newly appeared dirty pages, but have not synced all
2591aeac589aSMing Lei 			 * of the old dirty pages.
2592aeac589aSMing Lei 			 */
2593aeac589aSMing Lei 			if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2594aeac589aSMing Lei 				goto out;
2595aeac589aSMing Lei 
25964e7ea81dSJan Kara 			/* If we can't merge this page, we are done. */
25974e7ea81dSJan Kara 			if (mpd->map.m_len > 0 && mpd->next_page != page->index)
25984e7ea81dSJan Kara 				goto out;
259978aaced3STheodore Ts'o 
26008e48dcfbSTheodore Ts'o 			lock_page(page);
26018e48dcfbSTheodore Ts'o 			/*
26024e7ea81dSJan Kara 			 * If the page is no longer dirty, or its mapping no
26034e7ea81dSJan Kara 			 * longer corresponds to inode we are writing (which
26044e7ea81dSJan Kara 			 * means it has been truncated or invalidated), or the
26054e7ea81dSJan Kara 			 * page is already under writeback and we are not doing
26064e7ea81dSJan Kara 			 * a data integrity writeback, skip the page
26078e48dcfbSTheodore Ts'o 			 */
26084f01b02cSTheodore Ts'o 			if (!PageDirty(page) ||
26094f01b02cSTheodore Ts'o 			    (PageWriteback(page) &&
26104e7ea81dSJan Kara 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
26114f01b02cSTheodore Ts'o 			    unlikely(page->mapping != mapping)) {
26128e48dcfbSTheodore Ts'o 				unlock_page(page);
26138e48dcfbSTheodore Ts'o 				continue;
26148e48dcfbSTheodore Ts'o 			}
26158e48dcfbSTheodore Ts'o 
26168e48dcfbSTheodore Ts'o 			wait_on_page_writeback(page);
26178e48dcfbSTheodore Ts'o 			BUG_ON(PageWriteback(page));
26188e48dcfbSTheodore Ts'o 
2619cc509574STheodore Ts'o 			/*
2620cc509574STheodore Ts'o 			 * Should never happen but for buggy code in
2621cc509574STheodore Ts'o 			 * other subsystems that call
2622cc509574STheodore Ts'o 			 * set_page_dirty() without properly warning
2623cc509574STheodore Ts'o 			 * the file system first.  See [1] for more
2624cc509574STheodore Ts'o 			 * information.
2625cc509574STheodore Ts'o 			 *
2626cc509574STheodore Ts'o 			 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2627cc509574STheodore Ts'o 			 */
2628cc509574STheodore Ts'o 			if (!page_has_buffers(page)) {
2629cc509574STheodore Ts'o 				ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", page->index);
2630cc509574STheodore Ts'o 				ClearPageDirty(page);
2631cc509574STheodore Ts'o 				unlock_page(page);
2632cc509574STheodore Ts'o 				continue;
2633cc509574STheodore Ts'o 			}
2634cc509574STheodore Ts'o 
26354e7ea81dSJan Kara 			if (mpd->map.m_len == 0)
26368eb9e5ceSTheodore Ts'o 				mpd->first_page = page->index;
26378eb9e5ceSTheodore Ts'o 			mpd->next_page = page->index + 1;
2638f8bec370SJan Kara 			/* Add all dirty buffers to mpd */
26394e7ea81dSJan Kara 			lblk = ((ext4_lblk_t)page->index) <<
264009cbfeafSKirill A. Shutemov 				(PAGE_SHIFT - blkbits);
26418eb9e5ceSTheodore Ts'o 			head = page_buffers(page);
26425f1132b2SJan Kara 			err = mpage_process_page_bufs(mpd, head, head, lblk);
26435f1132b2SJan Kara 			if (err <= 0)
26444e7ea81dSJan Kara 				goto out;
26455f1132b2SJan Kara 			err = 0;
2646aeac589aSMing Lei 			left--;
26478e48dcfbSTheodore Ts'o 		}
26488e48dcfbSTheodore Ts'o 		pagevec_release(&pvec);
26498e48dcfbSTheodore Ts'o 		cond_resched();
26508e48dcfbSTheodore Ts'o 	}
26516b8ed620SJan Kara 	mpd->scanned_until_end = 1;
26524f01b02cSTheodore Ts'o 	return 0;
26538eb9e5ceSTheodore Ts'o out:
26548eb9e5ceSTheodore Ts'o 	pagevec_release(&pvec);
26554e7ea81dSJan Kara 	return err;
26568e48dcfbSTheodore Ts'o }
26578e48dcfbSTheodore Ts'o 
265820970ba6STheodore Ts'o static int ext4_writepages(struct address_space *mapping,
265964769240SAlex Tomas 			   struct writeback_control *wbc)
266064769240SAlex Tomas {
26614e7ea81dSJan Kara 	pgoff_t	writeback_index = 0;
26624e7ea81dSJan Kara 	long nr_to_write = wbc->nr_to_write;
266322208dedSAneesh Kumar K.V 	int range_whole = 0;
26644e7ea81dSJan Kara 	int cycled = 1;
266561628a3fSMingming Cao 	handle_t *handle = NULL;
2666df22291fSAneesh Kumar K.V 	struct mpage_da_data mpd;
26675e745b04SAneesh Kumar K.V 	struct inode *inode = mapping->host;
26686b523df4SJan Kara 	int needed_blocks, rsv_blocks = 0, ret = 0;
26695e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
26701bce63d1SShaohua Li 	struct blk_plug plug;
2671cb530541STheodore Ts'o 	bool give_up_on_write = false;
267261628a3fSMingming Cao 
26730db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
26740db1ff22STheodore Ts'o 		return -EIO;
26750db1ff22STheodore Ts'o 
2676bbd55937SEric Biggers 	percpu_down_read(&sbi->s_writepages_rwsem);
267720970ba6STheodore Ts'o 	trace_ext4_writepages(inode, wbc);
2678ba80b101STheodore Ts'o 
267961628a3fSMingming Cao 	/*
268061628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
268161628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
268261628a3fSMingming Cao 	 * because that could violate lock ordering on umount
268361628a3fSMingming Cao 	 */
2684a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2685bbf023c7SMing Lei 		goto out_writepages;
26862a21e37eSTheodore Ts'o 
268720970ba6STheodore Ts'o 	if (ext4_should_journal_data(inode)) {
2688043d20d1SGoldwyn Rodrigues 		ret = generic_writepages(mapping, wbc);
2689bbf023c7SMing Lei 		goto out_writepages;
269020970ba6STheodore Ts'o 	}
269120970ba6STheodore Ts'o 
26922a21e37eSTheodore Ts'o 	/*
26932a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
26942a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
26952a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
26961751e8a6SLinus Torvalds 	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
26972a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
269820970ba6STheodore Ts'o 	 * read-only, and in that case, ext4_writepages should
26992a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
27002a21e37eSTheodore Ts'o 	 * the stack trace.
27012a21e37eSTheodore Ts'o 	 */
27020db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
27039b5f6c9bSHarshad Shirwadkar 		     ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
2704bbf023c7SMing Lei 		ret = -EROFS;
2705bbf023c7SMing Lei 		goto out_writepages;
2706bbf023c7SMing Lei 	}
27072a21e37eSTheodore Ts'o 
27084e7ea81dSJan Kara 	/*
27094e7ea81dSJan Kara 	 * If we have inline data and arrive here, it means that
27104e7ea81dSJan Kara 	 * we will soon create the block for the 1st page, so
27114e7ea81dSJan Kara 	 * we'd better clear the inline data here.
27124e7ea81dSJan Kara 	 */
27134e7ea81dSJan Kara 	if (ext4_has_inline_data(inode)) {
27144e7ea81dSJan Kara 		/* Just inode will be modified... */
27154e7ea81dSJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
27164e7ea81dSJan Kara 		if (IS_ERR(handle)) {
27174e7ea81dSJan Kara 			ret = PTR_ERR(handle);
27184e7ea81dSJan Kara 			goto out_writepages;
27194e7ea81dSJan Kara 		}
27204e7ea81dSJan Kara 		BUG_ON(ext4_test_inode_state(inode,
27214e7ea81dSJan Kara 				EXT4_STATE_MAY_INLINE_DATA));
27224e7ea81dSJan Kara 		ext4_destroy_inline_data(handle, inode);
27234e7ea81dSJan Kara 		ext4_journal_stop(handle);
27244e7ea81dSJan Kara 	}
27254e7ea81dSJan Kara 
27264e343231Syangerkun 	if (ext4_should_dioread_nolock(inode)) {
27274e343231Syangerkun 		/*
27284e343231Syangerkun 		 * We may need to convert up to one extent per block in
27294e343231Syangerkun 		 * the page and we may dirty the inode.
27304e343231Syangerkun 		 */
27314e343231Syangerkun 		rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
27324e343231Syangerkun 						PAGE_SIZE >> inode->i_blkbits);
27334e343231Syangerkun 	}
27344e343231Syangerkun 
273522208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
273622208dedSAneesh Kumar K.V 		range_whole = 1;
273761628a3fSMingming Cao 
27382acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
27394e7ea81dSJan Kara 		writeback_index = mapping->writeback_index;
27404e7ea81dSJan Kara 		if (writeback_index)
27412acf2c26SAneesh Kumar K.V 			cycled = 0;
27424e7ea81dSJan Kara 		mpd.first_page = writeback_index;
27434e7ea81dSJan Kara 		mpd.last_page = -1;
27445b41d924SEric Sandeen 	} else {
274509cbfeafSKirill A. Shutemov 		mpd.first_page = wbc->range_start >> PAGE_SHIFT;
274609cbfeafSKirill A. Shutemov 		mpd.last_page = wbc->range_end >> PAGE_SHIFT;
27475b41d924SEric Sandeen 	}
2748a1d6cc56SAneesh Kumar K.V 
27494e7ea81dSJan Kara 	mpd.inode = inode;
27504e7ea81dSJan Kara 	mpd.wbc = wbc;
27514e7ea81dSJan Kara 	ext4_io_submit_init(&mpd.io_submit, wbc);
27522acf2c26SAneesh Kumar K.V retry:
27536e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
27544e7ea81dSJan Kara 		tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
27551bce63d1SShaohua Li 	blk_start_plug(&plug);
2756dddbd6acSJan Kara 
2757dddbd6acSJan Kara 	/*
2758dddbd6acSJan Kara 	 * First writeback pages that don't need mapping - we can avoid
2759dddbd6acSJan Kara 	 * starting a transaction unnecessarily and also avoid being blocked
2760dddbd6acSJan Kara 	 * in the block layer on device congestion while having transaction
2761dddbd6acSJan Kara 	 * started.
2762dddbd6acSJan Kara 	 */
2763dddbd6acSJan Kara 	mpd.do_map = 0;
27646b8ed620SJan Kara 	mpd.scanned_until_end = 0;
2765dddbd6acSJan Kara 	mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2766dddbd6acSJan Kara 	if (!mpd.io_submit.io_end) {
2767dddbd6acSJan Kara 		ret = -ENOMEM;
2768dddbd6acSJan Kara 		goto unplug;
2769dddbd6acSJan Kara 	}
2770dddbd6acSJan Kara 	ret = mpage_prepare_extent_to_map(&mpd);
2771a297b2fcSXiaoguang Wang 	/* Unlock pages we didn't use */
2772a297b2fcSXiaoguang Wang 	mpage_release_unused_pages(&mpd, false);
2773dddbd6acSJan Kara 	/* Submit prepared bio */
2774dddbd6acSJan Kara 	ext4_io_submit(&mpd.io_submit);
2775dddbd6acSJan Kara 	ext4_put_io_end_defer(mpd.io_submit.io_end);
2776dddbd6acSJan Kara 	mpd.io_submit.io_end = NULL;
2777dddbd6acSJan Kara 	if (ret < 0)
2778dddbd6acSJan Kara 		goto unplug;
2779dddbd6acSJan Kara 
27806b8ed620SJan Kara 	while (!mpd.scanned_until_end && wbc->nr_to_write > 0) {
27814e7ea81dSJan Kara 		/* For each extent of pages we use new io_end */
27824e7ea81dSJan Kara 		mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
27834e7ea81dSJan Kara 		if (!mpd.io_submit.io_end) {
27844e7ea81dSJan Kara 			ret = -ENOMEM;
27854e7ea81dSJan Kara 			break;
27864e7ea81dSJan Kara 		}
2787a1d6cc56SAneesh Kumar K.V 
2788a1d6cc56SAneesh Kumar K.V 		/*
27894e7ea81dSJan Kara 		 * We have two constraints: We find one extent to map and we
27904e7ea81dSJan Kara 		 * must always write out whole page (makes a difference when
27914e7ea81dSJan Kara 		 * blocksize < pagesize) so that we don't block on IO when we
27924e7ea81dSJan Kara 		 * try to write out the rest of the page. Journalled mode is
27934e7ea81dSJan Kara 		 * not supported by delalloc.
2794a1d6cc56SAneesh Kumar K.V 		 */
2795a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
2796525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2797a1d6cc56SAneesh Kumar K.V 
279861628a3fSMingming Cao 		/* start a new transaction */
27996b523df4SJan Kara 		handle = ext4_journal_start_with_reserve(inode,
28006b523df4SJan Kara 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
280161628a3fSMingming Cao 		if (IS_ERR(handle)) {
280261628a3fSMingming Cao 			ret = PTR_ERR(handle);
28031693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2804fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
2805a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
28064e7ea81dSJan Kara 			/* Release allocated io_end */
28074e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
2808dddbd6acSJan Kara 			mpd.io_submit.io_end = NULL;
28094e7ea81dSJan Kara 			break;
281061628a3fSMingming Cao 		}
2811dddbd6acSJan Kara 		mpd.do_map = 1;
2812f63e6005STheodore Ts'o 
28134e7ea81dSJan Kara 		trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
28144e7ea81dSJan Kara 		ret = mpage_prepare_extent_to_map(&mpd);
28156b8ed620SJan Kara 		if (!ret && mpd.map.m_len)
2816cb530541STheodore Ts'o 			ret = mpage_map_and_submit_extent(handle, &mpd,
2817cb530541STheodore Ts'o 					&give_up_on_write);
2818646caa9cSJan Kara 		/*
2819646caa9cSJan Kara 		 * Caution: If the handle is synchronous,
2820646caa9cSJan Kara 		 * ext4_journal_stop() can wait for transaction commit
2821646caa9cSJan Kara 		 * to finish which may depend on writeback of pages to
2822646caa9cSJan Kara 		 * complete or on page lock to be released.  In that
2823b483bb77SRandy Dunlap 		 * case, we have to wait until after we have
2824646caa9cSJan Kara 		 * submitted all the IO, released page locks we hold,
2825646caa9cSJan Kara 		 * and dropped io_end reference (for extent conversion
2826646caa9cSJan Kara 		 * to be able to complete) before stopping the handle.
2827646caa9cSJan Kara 		 */
2828646caa9cSJan Kara 		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
282961628a3fSMingming Cao 			ext4_journal_stop(handle);
2830646caa9cSJan Kara 			handle = NULL;
2831dddbd6acSJan Kara 			mpd.do_map = 0;
2832646caa9cSJan Kara 		}
28334e7ea81dSJan Kara 		/* Unlock pages we didn't use */
2834cb530541STheodore Ts'o 		mpage_release_unused_pages(&mpd, give_up_on_write);
2835a297b2fcSXiaoguang Wang 		/* Submit prepared bio */
2836a297b2fcSXiaoguang Wang 		ext4_io_submit(&mpd.io_submit);
2837a297b2fcSXiaoguang Wang 
2838646caa9cSJan Kara 		/*
2839646caa9cSJan Kara 		 * Drop our io_end reference we got from init. We have
2840646caa9cSJan Kara 		 * to be careful and use deferred io_end finishing if
2841646caa9cSJan Kara 		 * we are still holding the transaction as we can
2842646caa9cSJan Kara 		 * release the last reference to io_end which may end
2843646caa9cSJan Kara 		 * up doing unwritten extent conversion.
2844646caa9cSJan Kara 		 */
2845646caa9cSJan Kara 		if (handle) {
2846646caa9cSJan Kara 			ext4_put_io_end_defer(mpd.io_submit.io_end);
2847646caa9cSJan Kara 			ext4_journal_stop(handle);
2848646caa9cSJan Kara 		} else
28494e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
2850dddbd6acSJan Kara 		mpd.io_submit.io_end = NULL;
2851df22291fSAneesh Kumar K.V 
28524e7ea81dSJan Kara 		if (ret == -ENOSPC && sbi->s_journal) {
28534e7ea81dSJan Kara 			/*
28544e7ea81dSJan Kara 			 * Commit the transaction which would
285522208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
285622208dedSAneesh Kumar K.V 			 * and try again
285722208dedSAneesh Kumar K.V 			 */
2858df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
285922208dedSAneesh Kumar K.V 			ret = 0;
28604e7ea81dSJan Kara 			continue;
28614e7ea81dSJan Kara 		}
28624e7ea81dSJan Kara 		/* Fatal error - ENOMEM, EIO... */
28634e7ea81dSJan Kara 		if (ret)
286461628a3fSMingming Cao 			break;
286561628a3fSMingming Cao 	}
2866dddbd6acSJan Kara unplug:
28671bce63d1SShaohua Li 	blk_finish_plug(&plug);
28689c12a831SJan Kara 	if (!ret && !cycled && wbc->nr_to_write > 0) {
28692acf2c26SAneesh Kumar K.V 		cycled = 1;
28704e7ea81dSJan Kara 		mpd.last_page = writeback_index - 1;
28714e7ea81dSJan Kara 		mpd.first_page = 0;
28722acf2c26SAneesh Kumar K.V 		goto retry;
28732acf2c26SAneesh Kumar K.V 	}
287461628a3fSMingming Cao 
287522208dedSAneesh Kumar K.V 	/* Update index */
287622208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
287722208dedSAneesh Kumar K.V 		/*
28784e7ea81dSJan Kara 		 * Set the writeback_index so that range_cyclic
287922208dedSAneesh Kumar K.V 		 * mode will write it back later
288022208dedSAneesh Kumar K.V 		 */
28814e7ea81dSJan Kara 		mapping->writeback_index = mpd.first_page;
2882a1d6cc56SAneesh Kumar K.V 
288361628a3fSMingming Cao out_writepages:
288420970ba6STheodore Ts'o 	trace_ext4_writepages_result(inode, wbc, ret,
28854e7ea81dSJan Kara 				     nr_to_write - wbc->nr_to_write);
2886bbd55937SEric Biggers 	percpu_up_read(&sbi->s_writepages_rwsem);
288761628a3fSMingming Cao 	return ret;
288864769240SAlex Tomas }
288964769240SAlex Tomas 
28905f0663bbSDan Williams static int ext4_dax_writepages(struct address_space *mapping,
28915f0663bbSDan Williams 			       struct writeback_control *wbc)
28925f0663bbSDan Williams {
28935f0663bbSDan Williams 	int ret;
28945f0663bbSDan Williams 	long nr_to_write = wbc->nr_to_write;
28955f0663bbSDan Williams 	struct inode *inode = mapping->host;
28965f0663bbSDan Williams 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
28975f0663bbSDan Williams 
28985f0663bbSDan Williams 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
28995f0663bbSDan Williams 		return -EIO;
29005f0663bbSDan Williams 
2901bbd55937SEric Biggers 	percpu_down_read(&sbi->s_writepages_rwsem);
29025f0663bbSDan Williams 	trace_ext4_writepages(inode, wbc);
29035f0663bbSDan Williams 
29043f666c56SVivek Goyal 	ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
29055f0663bbSDan Williams 	trace_ext4_writepages_result(inode, wbc, ret,
29065f0663bbSDan Williams 				     nr_to_write - wbc->nr_to_write);
2907bbd55937SEric Biggers 	percpu_up_read(&sbi->s_writepages_rwsem);
29085f0663bbSDan Williams 	return ret;
29095f0663bbSDan Williams }
29105f0663bbSDan Williams 
291179f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
291279f0be8dSAneesh Kumar K.V {
29135c1ff336SEric Whitney 	s64 free_clusters, dirty_clusters;
291479f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
291579f0be8dSAneesh Kumar K.V 
291679f0be8dSAneesh Kumar K.V 	/*
291779f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
291879f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
2919179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
292079f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
292179f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
292279f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
292379f0be8dSAneesh Kumar K.V 	 */
29245c1ff336SEric Whitney 	free_clusters =
29255c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
29265c1ff336SEric Whitney 	dirty_clusters =
29275c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
292800d4e736STheodore Ts'o 	/*
292900d4e736STheodore Ts'o 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
293000d4e736STheodore Ts'o 	 */
29315c1ff336SEric Whitney 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
293210ee27a0SMiao Xie 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
293300d4e736STheodore Ts'o 
29345c1ff336SEric Whitney 	if (2 * free_clusters < 3 * dirty_clusters ||
29355c1ff336SEric Whitney 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
293679f0be8dSAneesh Kumar K.V 		/*
2937c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
2938c8afb446SEric Sandeen 		 * or free blocks is less than watermark
293979f0be8dSAneesh Kumar K.V 		 */
294079f0be8dSAneesh Kumar K.V 		return 1;
294179f0be8dSAneesh Kumar K.V 	}
294279f0be8dSAneesh Kumar K.V 	return 0;
294379f0be8dSAneesh Kumar K.V }
294479f0be8dSAneesh Kumar K.V 
294564769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
29469d6b0cd7SMatthew Wilcox (Oracle) 			       loff_t pos, unsigned len,
294764769240SAlex Tomas 			       struct page **pagep, void **fsdata)
294864769240SAlex Tomas {
294972b8ab9dSEric Sandeen 	int ret, retries = 0;
295064769240SAlex Tomas 	struct page *page;
295164769240SAlex Tomas 	pgoff_t index;
295264769240SAlex Tomas 	struct inode *inode = mapping->host;
295364769240SAlex Tomas 
29540db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
29550db1ff22STheodore Ts'o 		return -EIO;
29560db1ff22STheodore Ts'o 
295709cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
295879f0be8dSAneesh Kumar K.V 
29596493792dSZhang Yi 	if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
296079f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
296179f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
29629d6b0cd7SMatthew Wilcox (Oracle) 					len, pagep, fsdata);
296379f0be8dSAneesh Kumar K.V 	}
296479f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
29659d6b0cd7SMatthew Wilcox (Oracle) 	trace_ext4_da_write_begin(inode, pos, len);
29669c3569b5STao Ma 
29679c3569b5STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
296836d116e9SMatthew Wilcox (Oracle) 		ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len,
29699c3569b5STao Ma 						      pagep, fsdata);
29709c3569b5STao Ma 		if (ret < 0)
297147564bfbSTheodore Ts'o 			return ret;
297247564bfbSTheodore Ts'o 		if (ret == 1)
297347564bfbSTheodore Ts'o 			return 0;
29749c3569b5STao Ma 	}
29759c3569b5STao Ma 
2976cc883236SZhang Yi retry:
2977b7446e7cSMatthew Wilcox (Oracle) 	page = grab_cache_page_write_begin(mapping, index);
297847564bfbSTheodore Ts'o 	if (!page)
297947564bfbSTheodore Ts'o 		return -ENOMEM;
298047564bfbSTheodore Ts'o 
298147564bfbSTheodore Ts'o 	/* In case writeback began while the page was unlocked */
29827afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
298364769240SAlex Tomas 
2984643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
29852058f83aSMichael Halcrow 	ret = ext4_block_write_begin(page, pos, len,
29862058f83aSMichael Halcrow 				     ext4_da_get_block_prep);
29872058f83aSMichael Halcrow #else
29886e1db88dSChristoph Hellwig 	ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
29892058f83aSMichael Halcrow #endif
299064769240SAlex Tomas 	if (ret < 0) {
299164769240SAlex Tomas 		unlock_page(page);
2992cc883236SZhang Yi 		put_page(page);
2993ae4d5372SAneesh Kumar K.V 		/*
2994ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
2995ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
2996cc883236SZhang Yi 		 * i_size_read because we hold inode lock.
2997ae4d5372SAneesh Kumar K.V 		 */
2998ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
2999b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
300047564bfbSTheodore Ts'o 
300147564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
300247564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
3003cc883236SZhang Yi 			goto retry;
300447564bfbSTheodore Ts'o 		return ret;
300564769240SAlex Tomas 	}
300664769240SAlex Tomas 
300747564bfbSTheodore Ts'o 	*pagep = page;
300864769240SAlex Tomas 	return ret;
300964769240SAlex Tomas }
301064769240SAlex Tomas 
3011632eaeabSMingming Cao /*
3012632eaeabSMingming Cao  * Check if we should update i_disksize
3013632eaeabSMingming Cao  * when write to the end of file but not require block allocation
3014632eaeabSMingming Cao  */
3015632eaeabSMingming Cao static int ext4_da_should_update_i_disksize(struct page *page,
3016632eaeabSMingming Cao 					    unsigned long offset)
3017632eaeabSMingming Cao {
3018632eaeabSMingming Cao 	struct buffer_head *bh;
3019632eaeabSMingming Cao 	struct inode *inode = page->mapping->host;
3020632eaeabSMingming Cao 	unsigned int idx;
3021632eaeabSMingming Cao 	int i;
3022632eaeabSMingming Cao 
3023632eaeabSMingming Cao 	bh = page_buffers(page);
3024632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
3025632eaeabSMingming Cao 
3026632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
3027632eaeabSMingming Cao 		bh = bh->b_this_page;
3028632eaeabSMingming Cao 
302929fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3030632eaeabSMingming Cao 		return 0;
3031632eaeabSMingming Cao 	return 1;
3032632eaeabSMingming Cao }
3033632eaeabSMingming Cao 
303464769240SAlex Tomas static int ext4_da_write_end(struct file *file,
303564769240SAlex Tomas 			     struct address_space *mapping,
303664769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
303764769240SAlex Tomas 			     struct page *page, void *fsdata)
303864769240SAlex Tomas {
303964769240SAlex Tomas 	struct inode *inode = mapping->host;
304064769240SAlex Tomas 	loff_t new_i_size;
3041632eaeabSMingming Cao 	unsigned long start, end;
304279f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
304379f0be8dSAneesh Kumar K.V 
304474d553aaSTheodore Ts'o 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
304574d553aaSTheodore Ts'o 		return ext4_write_end(file, mapping, pos,
304679f0be8dSAneesh Kumar K.V 				      len, copied, page, fsdata);
3047632eaeabSMingming Cao 
30489bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
30499c3569b5STao Ma 
30509c3569b5STao Ma 	if (write_mode != CONVERT_INLINE_DATA &&
30519c3569b5STao Ma 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
30529c3569b5STao Ma 	    ext4_has_inline_data(inode))
30536984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
30549c3569b5STao Ma 
305564769240SAlex Tomas 	start = pos & (PAGE_SIZE - 1);
305664769240SAlex Tomas 	end = start + copied - 1;
305764769240SAlex Tomas 
305864769240SAlex Tomas 	/*
30594df031ffSZhang Yi 	 * Since we are holding inode lock, we are sure i_disksize <=
30604df031ffSZhang Yi 	 * i_size. We also know that if i_disksize < i_size, there are
30614df031ffSZhang Yi 	 * delalloc writes pending in the range upto i_size. If the end of
30624df031ffSZhang Yi 	 * the current write is <= i_size, there's no need to touch
30634df031ffSZhang Yi 	 * i_disksize since writeback will push i_disksize upto i_size
30644df031ffSZhang Yi 	 * eventually. If the end of the current write is > i_size and
30654df031ffSZhang Yi 	 * inside an allocated block (ext4_da_should_update_i_disksize()
30664df031ffSZhang Yi 	 * check), we need to update i_disksize here as neither
30674df031ffSZhang Yi 	 * ext4_writepage() nor certain ext4_writepages() paths not
30684df031ffSZhang Yi 	 * allocating blocks update i_disksize.
30694df031ffSZhang Yi 	 *
30704df031ffSZhang Yi 	 * Note that we defer inode dirtying to generic_write_end() /
30714df031ffSZhang Yi 	 * ext4_da_write_inline_data_end().
3072d2a17637SMingming Cao 	 */
307364769240SAlex Tomas 	new_i_size = pos + copied;
30746984aef5SZhang Yi 	if (copied && new_i_size > inode->i_size &&
30754df031ffSZhang Yi 	    ext4_da_should_update_i_disksize(page, end))
307664769240SAlex Tomas 		ext4_update_i_disksize(inode, new_i_size);
3077ccd2506bSTheodore Ts'o 
3078cc883236SZhang Yi 	return generic_write_end(file, mapping, pos, len, copied, page, fsdata);
3079ac27a0ecSDave Kleikamp }
3080ac27a0ecSDave Kleikamp 
3081ccd2506bSTheodore Ts'o /*
3082ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
3083ccd2506bSTheodore Ts'o  */
3084ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
3085ccd2506bSTheodore Ts'o {
3086ccd2506bSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
3087ccd2506bSTheodore Ts'o 
308871d4f7d0STheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks)
3089ccd2506bSTheodore Ts'o 		return 0;
3090ccd2506bSTheodore Ts'o 
3091ccd2506bSTheodore Ts'o 	/*
3092ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
3093ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
3094ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
3095ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
3096ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
3097ccd2506bSTheodore Ts'o 	 *
309820970ba6STheodore Ts'o 	 * ext4_writepages() ->
3099ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
3100ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
3101ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
3102ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
3103ccd2506bSTheodore Ts'o 	 *
3104ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
3105ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
3106ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
3107ccd2506bSTheodore Ts'o 	 * doing I/O at all.
3108ccd2506bSTheodore Ts'o 	 *
3109ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
3110380cf090SWu Fengguang 	 * the pages by calling redirty_page_for_writepage() but that
3111ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
3112ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
311325985edcSLucas De Marchi 	 * simplifying them because we wouldn't actually intend to
3114ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
3115ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
3116ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
3117ccd2506bSTheodore Ts'o 	 *
3118ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
3119ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
3120ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
3121ccd2506bSTheodore Ts'o 	 */
3122ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
3123ccd2506bSTheodore Ts'o }
3124ac27a0ecSDave Kleikamp 
3125ac27a0ecSDave Kleikamp /*
3126ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
3127ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
3128ac27a0ecSDave Kleikamp  *
3129ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
3130ac27a0ecSDave Kleikamp  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3131ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
3132ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
3133ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
3134ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
3135ac27a0ecSDave Kleikamp  *
3136ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
3137ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
3138ac27a0ecSDave Kleikamp  */
3139ac27a0ecSDave Kleikamp static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3140ac27a0ecSDave Kleikamp {
3141ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
3142ac27a0ecSDave Kleikamp 	journal_t *journal;
3143ac27a0ecSDave Kleikamp 	int err;
3144ac27a0ecSDave Kleikamp 
314546c7f254STao Ma 	/*
314646c7f254STao Ma 	 * We can get here for an inline file via the FIBMAP ioctl
314746c7f254STao Ma 	 */
314846c7f254STao Ma 	if (ext4_has_inline_data(inode))
314946c7f254STao Ma 		return 0;
315046c7f254STao Ma 
3151ac27a0ecSDave Kleikamp 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3152ac27a0ecSDave Kleikamp 			test_opt(inode->i_sb, DELALLOC)) {
3153ac27a0ecSDave Kleikamp 		/*
3154ac27a0ecSDave Kleikamp 		 * With delalloc we want to sync the file
3155ac27a0ecSDave Kleikamp 		 * so that we can make sure we allocate
3156ac27a0ecSDave Kleikamp 		 * blocks for file
3157ac27a0ecSDave Kleikamp 		 */
3158ac27a0ecSDave Kleikamp 		filemap_write_and_wait(mapping);
3159ac27a0ecSDave Kleikamp 	}
3160ac27a0ecSDave Kleikamp 
316119f5fb7aSTheodore Ts'o 	if (EXT4_JOURNAL(inode) &&
316219f5fb7aSTheodore Ts'o 	    ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3163ac27a0ecSDave Kleikamp 		/*
3164ac27a0ecSDave Kleikamp 		 * This is a REALLY heavyweight approach, but the use of
3165ac27a0ecSDave Kleikamp 		 * bmap on dirty files is expected to be extremely rare:
3166ac27a0ecSDave Kleikamp 		 * only if we run lilo or swapon on a freshly made file
3167ac27a0ecSDave Kleikamp 		 * do we expect this to happen.
3168ac27a0ecSDave Kleikamp 		 *
3169ac27a0ecSDave Kleikamp 		 * (bmap requires CAP_SYS_RAWIO so this does not
3170ac27a0ecSDave Kleikamp 		 * represent an unprivileged user DOS attack --- we'd be
3171ac27a0ecSDave Kleikamp 		 * in trouble if mortal users could trigger this path at
3172ac27a0ecSDave Kleikamp 		 * will.)
3173ac27a0ecSDave Kleikamp 		 *
3174ac27a0ecSDave Kleikamp 		 * NB. EXT4_STATE_JDATA is not set on files other than
3175ac27a0ecSDave Kleikamp 		 * regular files.  If somebody wants to bmap a directory
3176ac27a0ecSDave Kleikamp 		 * or symlink and gets confused because the buffer
3177ac27a0ecSDave Kleikamp 		 * hasn't yet been flushed to disk, they deserve
3178ac27a0ecSDave Kleikamp 		 * everything they get.
3179ac27a0ecSDave Kleikamp 		 */
3180ac27a0ecSDave Kleikamp 
318119f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3182ac27a0ecSDave Kleikamp 		journal = EXT4_JOURNAL(inode);
3183ac27a0ecSDave Kleikamp 		jbd2_journal_lock_updates(journal);
318401d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
3185ac27a0ecSDave Kleikamp 		jbd2_journal_unlock_updates(journal);
3186ac27a0ecSDave Kleikamp 
3187ac27a0ecSDave Kleikamp 		if (err)
3188ac27a0ecSDave Kleikamp 			return 0;
3189ac27a0ecSDave Kleikamp 	}
3190ac27a0ecSDave Kleikamp 
3191ac58e4fbSRitesh Harjani 	return iomap_bmap(mapping, block, &ext4_iomap_ops);
3192ac27a0ecSDave Kleikamp }
3193ac27a0ecSDave Kleikamp 
3194fe5ddf6bSMatthew Wilcox (Oracle) static int ext4_read_folio(struct file *file, struct folio *folio)
3195ac27a0ecSDave Kleikamp {
3196fe5ddf6bSMatthew Wilcox (Oracle) 	struct page *page = &folio->page;
319746c7f254STao Ma 	int ret = -EAGAIN;
319846c7f254STao Ma 	struct inode *inode = page->mapping->host;
319946c7f254STao Ma 
32000562e0baSJiaying Zhang 	trace_ext4_readpage(page);
320146c7f254STao Ma 
320246c7f254STao Ma 	if (ext4_has_inline_data(inode))
320346c7f254STao Ma 		ret = ext4_readpage_inline(inode, page);
320446c7f254STao Ma 
320546c7f254STao Ma 	if (ret == -EAGAIN)
3206a07f624bSMatthew Wilcox (Oracle) 		return ext4_mpage_readpages(inode, NULL, page);
320746c7f254STao Ma 
320846c7f254STao Ma 	return ret;
3209ac27a0ecSDave Kleikamp }
3210ac27a0ecSDave Kleikamp 
32116311f91fSMatthew Wilcox (Oracle) static void ext4_readahead(struct readahead_control *rac)
3212ac27a0ecSDave Kleikamp {
32136311f91fSMatthew Wilcox (Oracle) 	struct inode *inode = rac->mapping->host;
321446c7f254STao Ma 
32156311f91fSMatthew Wilcox (Oracle) 	/* If the file has inline data, no need to do readahead. */
321646c7f254STao Ma 	if (ext4_has_inline_data(inode))
32176311f91fSMatthew Wilcox (Oracle) 		return;
321846c7f254STao Ma 
3219a07f624bSMatthew Wilcox (Oracle) 	ext4_mpage_readpages(inode, rac, NULL);
3220ac27a0ecSDave Kleikamp }
3221ac27a0ecSDave Kleikamp 
32227ba13abbSMatthew Wilcox (Oracle) static void ext4_invalidate_folio(struct folio *folio, size_t offset,
32237ba13abbSMatthew Wilcox (Oracle) 				size_t length)
3224ac27a0ecSDave Kleikamp {
3225ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_invalidate_folio(folio, offset, length);
32260562e0baSJiaying Zhang 
32274520fb3cSJan Kara 	/* No journalling happens on data buffers when this function is used */
32287ba13abbSMatthew Wilcox (Oracle) 	WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
32294520fb3cSJan Kara 
32307ba13abbSMatthew Wilcox (Oracle) 	block_invalidate_folio(folio, offset, length);
32314520fb3cSJan Kara }
32324520fb3cSJan Kara 
3233ccd16945SMatthew Wilcox (Oracle) static int __ext4_journalled_invalidate_folio(struct folio *folio,
3234ccd16945SMatthew Wilcox (Oracle) 					    size_t offset, size_t length)
32354520fb3cSJan Kara {
3236ccd16945SMatthew Wilcox (Oracle) 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
32374520fb3cSJan Kara 
3238ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_journalled_invalidate_folio(folio, offset, length);
32394520fb3cSJan Kara 
3240744692dcSJiaying Zhang 	/*
3241ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
3242ac27a0ecSDave Kleikamp 	 */
3243ccd16945SMatthew Wilcox (Oracle) 	if (offset == 0 && length == folio_size(folio))
3244ccd16945SMatthew Wilcox (Oracle) 		folio_clear_checked(folio);
3245ac27a0ecSDave Kleikamp 
3246ccd16945SMatthew Wilcox (Oracle) 	return jbd2_journal_invalidate_folio(journal, folio, offset, length);
324753e87268SJan Kara }
324853e87268SJan Kara 
324953e87268SJan Kara /* Wrapper for aops... */
3250ccd16945SMatthew Wilcox (Oracle) static void ext4_journalled_invalidate_folio(struct folio *folio,
3251ccd16945SMatthew Wilcox (Oracle) 					   size_t offset,
3252ccd16945SMatthew Wilcox (Oracle) 					   size_t length)
325353e87268SJan Kara {
3254ccd16945SMatthew Wilcox (Oracle) 	WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3255ac27a0ecSDave Kleikamp }
3256ac27a0ecSDave Kleikamp 
32573c402f15SMatthew Wilcox (Oracle) static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3258ac27a0ecSDave Kleikamp {
32593c402f15SMatthew Wilcox (Oracle) 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
3260ac27a0ecSDave Kleikamp 
32613c402f15SMatthew Wilcox (Oracle) 	trace_ext4_releasepage(&folio->page);
32620562e0baSJiaying Zhang 
3263e1c36595SJan Kara 	/* Page has dirty journalled data -> cannot release */
32643c402f15SMatthew Wilcox (Oracle) 	if (folio_test_checked(folio))
32653c402f15SMatthew Wilcox (Oracle) 		return false;
32660390131bSFrank Mayhar 	if (journal)
3267c56a6eb0SMatthew Wilcox (Oracle) 		return jbd2_journal_try_to_free_buffers(journal, folio);
32680390131bSFrank Mayhar 	else
326968189fefSMatthew Wilcox (Oracle) 		return try_to_free_buffers(folio);
3270ac27a0ecSDave Kleikamp }
3271ac27a0ecSDave Kleikamp 
3272b8a6176cSJan Kara static bool ext4_inode_datasync_dirty(struct inode *inode)
3273b8a6176cSJan Kara {
3274b8a6176cSJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3275b8a6176cSJan Kara 
3276aa75f4d3SHarshad Shirwadkar 	if (journal) {
3277aa75f4d3SHarshad Shirwadkar 		if (jbd2_transaction_committed(journal,
3278aa75f4d3SHarshad Shirwadkar 			EXT4_I(inode)->i_datasync_tid))
3279d0520df7SAndrea Righi 			return false;
3280d0520df7SAndrea Righi 		if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
32811ceecb53SHarshad Shirwadkar 			return !list_empty(&EXT4_I(inode)->i_fc_list);
3282d0520df7SAndrea Righi 		return true;
3283aa75f4d3SHarshad Shirwadkar 	}
3284aa75f4d3SHarshad Shirwadkar 
3285b8a6176cSJan Kara 	/* Any metadata buffers to write? */
3286b8a6176cSJan Kara 	if (!list_empty(&inode->i_mapping->private_list))
3287b8a6176cSJan Kara 		return true;
3288b8a6176cSJan Kara 	return inode->i_state & I_DIRTY_DATASYNC;
3289b8a6176cSJan Kara }
3290b8a6176cSJan Kara 
3291c8fdfe29SMatthew Bobrowski static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3292c8fdfe29SMatthew Bobrowski 			   struct ext4_map_blocks *map, loff_t offset,
3293de205114SChristoph Hellwig 			   loff_t length, unsigned int flags)
3294364443cbSJan Kara {
3295c8fdfe29SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3296c8fdfe29SMatthew Bobrowski 
3297c8fdfe29SMatthew Bobrowski 	/*
3298c8fdfe29SMatthew Bobrowski 	 * Writes that span EOF might trigger an I/O size update on completion,
3299c8fdfe29SMatthew Bobrowski 	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3300c8fdfe29SMatthew Bobrowski 	 * there is no other metadata changes being made or are pending.
3301c8fdfe29SMatthew Bobrowski 	 */
3302c8fdfe29SMatthew Bobrowski 	iomap->flags = 0;
3303c8fdfe29SMatthew Bobrowski 	if (ext4_inode_datasync_dirty(inode) ||
3304c8fdfe29SMatthew Bobrowski 	    offset + length > i_size_read(inode))
3305c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_DIRTY;
3306c8fdfe29SMatthew Bobrowski 
3307c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_NEW)
3308c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_NEW;
3309c8fdfe29SMatthew Bobrowski 
3310de205114SChristoph Hellwig 	if (flags & IOMAP_DAX)
3311c8fdfe29SMatthew Bobrowski 		iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3312de205114SChristoph Hellwig 	else
3313de205114SChristoph Hellwig 		iomap->bdev = inode->i_sb->s_bdev;
3314c8fdfe29SMatthew Bobrowski 	iomap->offset = (u64) map->m_lblk << blkbits;
3315c8fdfe29SMatthew Bobrowski 	iomap->length = (u64) map->m_len << blkbits;
3316c8fdfe29SMatthew Bobrowski 
33176386722aSRitesh Harjani 	if ((map->m_flags & EXT4_MAP_MAPPED) &&
33186386722aSRitesh Harjani 	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
33196386722aSRitesh Harjani 		iomap->flags |= IOMAP_F_MERGED;
33206386722aSRitesh Harjani 
3321c8fdfe29SMatthew Bobrowski 	/*
3322c8fdfe29SMatthew Bobrowski 	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3323c8fdfe29SMatthew Bobrowski 	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3324c8fdfe29SMatthew Bobrowski 	 * set. In order for any allocated unwritten extents to be converted
3325c8fdfe29SMatthew Bobrowski 	 * into written extents correctly within the ->end_io() handler, we
3326c8fdfe29SMatthew Bobrowski 	 * need to ensure that the iomap->type is set appropriately. Hence, the
3327c8fdfe29SMatthew Bobrowski 	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3328c8fdfe29SMatthew Bobrowski 	 * been set first.
3329c8fdfe29SMatthew Bobrowski 	 */
3330c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3331c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_UNWRITTEN;
3332c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3333de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3334de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3335c8fdfe29SMatthew Bobrowski 	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3336c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_MAPPED;
3337c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3338de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3339de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3340c8fdfe29SMatthew Bobrowski 	} else {
3341c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_HOLE;
3342c8fdfe29SMatthew Bobrowski 		iomap->addr = IOMAP_NULL_ADDR;
3343c8fdfe29SMatthew Bobrowski 	}
3344c8fdfe29SMatthew Bobrowski }
3345c8fdfe29SMatthew Bobrowski 
3346f063db5eSMatthew Bobrowski static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3347f063db5eSMatthew Bobrowski 			    unsigned int flags)
3348f063db5eSMatthew Bobrowski {
3349f063db5eSMatthew Bobrowski 	handle_t *handle;
3350378f32baSMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3351378f32baSMatthew Bobrowski 	int ret, dio_credits, m_flags = 0, retries = 0;
3352f063db5eSMatthew Bobrowski 
3353f063db5eSMatthew Bobrowski 	/*
3354f063db5eSMatthew Bobrowski 	 * Trim the mapping request to the maximum value that we can map at
3355f063db5eSMatthew Bobrowski 	 * once for direct I/O.
3356f063db5eSMatthew Bobrowski 	 */
3357f063db5eSMatthew Bobrowski 	if (map->m_len > DIO_MAX_BLOCKS)
3358f063db5eSMatthew Bobrowski 		map->m_len = DIO_MAX_BLOCKS;
3359f063db5eSMatthew Bobrowski 	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3360f063db5eSMatthew Bobrowski 
3361f063db5eSMatthew Bobrowski retry:
3362f063db5eSMatthew Bobrowski 	/*
3363f063db5eSMatthew Bobrowski 	 * Either we allocate blocks and then don't get an unwritten extent, so
3364f063db5eSMatthew Bobrowski 	 * in that case we have reserved enough credits. Or, the blocks are
3365f063db5eSMatthew Bobrowski 	 * already allocated and unwritten. In that case, the extent conversion
3366f063db5eSMatthew Bobrowski 	 * fits into the credits as well.
3367f063db5eSMatthew Bobrowski 	 */
3368f063db5eSMatthew Bobrowski 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3369f063db5eSMatthew Bobrowski 	if (IS_ERR(handle))
3370f063db5eSMatthew Bobrowski 		return PTR_ERR(handle);
3371f063db5eSMatthew Bobrowski 
3372378f32baSMatthew Bobrowski 	/*
3373378f32baSMatthew Bobrowski 	 * DAX and direct I/O are the only two operations that are currently
3374378f32baSMatthew Bobrowski 	 * supported with IOMAP_WRITE.
3375378f32baSMatthew Bobrowski 	 */
3376952da063SChristoph Hellwig 	WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3377952da063SChristoph Hellwig 	if (flags & IOMAP_DAX)
3378378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3379378f32baSMatthew Bobrowski 	/*
3380378f32baSMatthew Bobrowski 	 * We use i_size instead of i_disksize here because delalloc writeback
3381378f32baSMatthew Bobrowski 	 * can complete at any point during the I/O and subsequently push the
3382378f32baSMatthew Bobrowski 	 * i_disksize out to i_size. This could be beyond where direct I/O is
3383378f32baSMatthew Bobrowski 	 * happening and thus expose allocated blocks to direct I/O reads.
3384378f32baSMatthew Bobrowski 	 */
3385d0b040f5SJan Kara 	else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3386378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE;
3387378f32baSMatthew Bobrowski 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3388378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3389378f32baSMatthew Bobrowski 
3390378f32baSMatthew Bobrowski 	ret = ext4_map_blocks(handle, inode, map, m_flags);
3391378f32baSMatthew Bobrowski 
3392378f32baSMatthew Bobrowski 	/*
3393378f32baSMatthew Bobrowski 	 * We cannot fill holes in indirect tree based inodes as that could
3394378f32baSMatthew Bobrowski 	 * expose stale data in the case of a crash. Use the magic error code
3395378f32baSMatthew Bobrowski 	 * to fallback to buffered I/O.
3396378f32baSMatthew Bobrowski 	 */
3397378f32baSMatthew Bobrowski 	if (!m_flags && !ret)
3398378f32baSMatthew Bobrowski 		ret = -ENOTBLK;
3399f063db5eSMatthew Bobrowski 
3400f063db5eSMatthew Bobrowski 	ext4_journal_stop(handle);
3401f063db5eSMatthew Bobrowski 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3402f063db5eSMatthew Bobrowski 		goto retry;
3403f063db5eSMatthew Bobrowski 
3404f063db5eSMatthew Bobrowski 	return ret;
3405f063db5eSMatthew Bobrowski }
3406f063db5eSMatthew Bobrowski 
3407f063db5eSMatthew Bobrowski 
3408364443cbSJan Kara static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3409c039b997SGoldwyn Rodrigues 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3410364443cbSJan Kara {
3411364443cbSJan Kara 	int ret;
341209edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
341309edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3414364443cbSJan Kara 
3415bcd8e91fSTheodore Ts'o 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3416bcd8e91fSTheodore Ts'o 		return -EINVAL;
34177046ae35SAndreas Gruenbacher 
3418364443cbSJan Kara 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3419364443cbSJan Kara 		return -ERANGE;
3420364443cbSJan Kara 
342109edf4d3SMatthew Bobrowski 	/*
342209edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical blocks respectively.
342309edf4d3SMatthew Bobrowski 	 */
342409edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
342509edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
342609edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3427364443cbSJan Kara 
34289faac62dSRitesh Harjani 	if (flags & IOMAP_WRITE) {
34299faac62dSRitesh Harjani 		/*
34309faac62dSRitesh Harjani 		 * We check here if the blocks are already allocated, then we
34319faac62dSRitesh Harjani 		 * don't need to start a journal txn and we can directly return
34329faac62dSRitesh Harjani 		 * the mapping information. This could boost performance
34339faac62dSRitesh Harjani 		 * especially in multi-threaded overwrite requests.
34349faac62dSRitesh Harjani 		 */
34359faac62dSRitesh Harjani 		if (offset + length <= i_size_read(inode)) {
3436545052e9SChristoph Hellwig 			ret = ext4_map_blocks(NULL, inode, &map, 0);
34379faac62dSRitesh Harjani 			if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
34389faac62dSRitesh Harjani 				goto out;
34399faac62dSRitesh Harjani 		}
34409faac62dSRitesh Harjani 		ret = ext4_iomap_alloc(inode, &map, flags);
34419faac62dSRitesh Harjani 	} else {
34429faac62dSRitesh Harjani 		ret = ext4_map_blocks(NULL, inode, &map, 0);
34439faac62dSRitesh Harjani 	}
3444f063db5eSMatthew Bobrowski 
3445545052e9SChristoph Hellwig 	if (ret < 0)
3446545052e9SChristoph Hellwig 		return ret;
34479faac62dSRitesh Harjani out:
344838ea50daSEric Biggers 	/*
344938ea50daSEric Biggers 	 * When inline encryption is enabled, sometimes I/O to an encrypted file
345038ea50daSEric Biggers 	 * has to be broken up to guarantee DUN contiguity.  Handle this by
345138ea50daSEric Biggers 	 * limiting the length of the mapping returned.
345238ea50daSEric Biggers 	 */
345338ea50daSEric Biggers 	map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
345438ea50daSEric Biggers 
3455de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3456545052e9SChristoph Hellwig 
3457364443cbSJan Kara 	return 0;
3458364443cbSJan Kara }
3459364443cbSJan Kara 
34608cd115bdSJan Kara static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
34618cd115bdSJan Kara 		loff_t length, unsigned flags, struct iomap *iomap,
34628cd115bdSJan Kara 		struct iomap *srcmap)
34638cd115bdSJan Kara {
34648cd115bdSJan Kara 	int ret;
34658cd115bdSJan Kara 
34668cd115bdSJan Kara 	/*
34678cd115bdSJan Kara 	 * Even for writes we don't need to allocate blocks, so just pretend
34688cd115bdSJan Kara 	 * we are reading to save overhead of starting a transaction.
34698cd115bdSJan Kara 	 */
34708cd115bdSJan Kara 	flags &= ~IOMAP_WRITE;
34718cd115bdSJan Kara 	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
34728cd115bdSJan Kara 	WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
34738cd115bdSJan Kara 	return ret;
34748cd115bdSJan Kara }
34758cd115bdSJan Kara 
3476776722e8SJan Kara static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3477776722e8SJan Kara 			  ssize_t written, unsigned flags, struct iomap *iomap)
3478776722e8SJan Kara {
3479378f32baSMatthew Bobrowski 	/*
3480378f32baSMatthew Bobrowski 	 * Check to see whether an error occurred while writing out the data to
3481378f32baSMatthew Bobrowski 	 * the allocated blocks. If so, return the magic error code so that we
3482378f32baSMatthew Bobrowski 	 * fallback to buffered I/O and attempt to complete the remainder of
3483378f32baSMatthew Bobrowski 	 * the I/O. Any blocks that may have been allocated in preparation for
3484378f32baSMatthew Bobrowski 	 * the direct I/O will be reused during buffered I/O.
3485378f32baSMatthew Bobrowski 	 */
3486378f32baSMatthew Bobrowski 	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3487378f32baSMatthew Bobrowski 		return -ENOTBLK;
3488378f32baSMatthew Bobrowski 
3489776722e8SJan Kara 	return 0;
3490776722e8SJan Kara }
3491776722e8SJan Kara 
34928ff6daa1SChristoph Hellwig const struct iomap_ops ext4_iomap_ops = {
3493364443cbSJan Kara 	.iomap_begin		= ext4_iomap_begin,
3494776722e8SJan Kara 	.iomap_end		= ext4_iomap_end,
3495364443cbSJan Kara };
3496364443cbSJan Kara 
34978cd115bdSJan Kara const struct iomap_ops ext4_iomap_overwrite_ops = {
34988cd115bdSJan Kara 	.iomap_begin		= ext4_iomap_overwrite_begin,
34998cd115bdSJan Kara 	.iomap_end		= ext4_iomap_end,
35008cd115bdSJan Kara };
35018cd115bdSJan Kara 
350209edf4d3SMatthew Bobrowski static bool ext4_iomap_is_delalloc(struct inode *inode,
350309edf4d3SMatthew Bobrowski 				   struct ext4_map_blocks *map)
350409edf4d3SMatthew Bobrowski {
350509edf4d3SMatthew Bobrowski 	struct extent_status es;
350609edf4d3SMatthew Bobrowski 	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
350709edf4d3SMatthew Bobrowski 
350809edf4d3SMatthew Bobrowski 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
350909edf4d3SMatthew Bobrowski 				  map->m_lblk, end, &es);
351009edf4d3SMatthew Bobrowski 
351109edf4d3SMatthew Bobrowski 	if (!es.es_len || es.es_lblk > end)
351209edf4d3SMatthew Bobrowski 		return false;
351309edf4d3SMatthew Bobrowski 
351409edf4d3SMatthew Bobrowski 	if (es.es_lblk > map->m_lblk) {
351509edf4d3SMatthew Bobrowski 		map->m_len = es.es_lblk - map->m_lblk;
351609edf4d3SMatthew Bobrowski 		return false;
351709edf4d3SMatthew Bobrowski 	}
351809edf4d3SMatthew Bobrowski 
351909edf4d3SMatthew Bobrowski 	offset = map->m_lblk - es.es_lblk;
352009edf4d3SMatthew Bobrowski 	map->m_len = es.es_len - offset;
352109edf4d3SMatthew Bobrowski 
352209edf4d3SMatthew Bobrowski 	return true;
352309edf4d3SMatthew Bobrowski }
352409edf4d3SMatthew Bobrowski 
352509edf4d3SMatthew Bobrowski static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
352609edf4d3SMatthew Bobrowski 				   loff_t length, unsigned int flags,
352709edf4d3SMatthew Bobrowski 				   struct iomap *iomap, struct iomap *srcmap)
352809edf4d3SMatthew Bobrowski {
352909edf4d3SMatthew Bobrowski 	int ret;
353009edf4d3SMatthew Bobrowski 	bool delalloc = false;
353109edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
353209edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
353309edf4d3SMatthew Bobrowski 
353409edf4d3SMatthew Bobrowski 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
353509edf4d3SMatthew Bobrowski 		return -EINVAL;
353609edf4d3SMatthew Bobrowski 
35377cb476f8SJan Kara 	if (ext4_has_inline_data(inode)) {
35387cb476f8SJan Kara 		ret = ext4_inline_data_iomap(inode, iomap);
3539ba5843f5SJan Kara 		if (ret != -EAGAIN) {
3540ed923b57SMatthew Wilcox 			if (ret == 0 && offset >= iomap->length)
3541ba5843f5SJan Kara 				ret = -ENOENT;
3542ba5843f5SJan Kara 			return ret;
3543ba5843f5SJan Kara 		}
3544ba5843f5SJan Kara 	}
354512735f88SJan Kara 
354609edf4d3SMatthew Bobrowski 	/*
354709edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical block respectively.
354809edf4d3SMatthew Bobrowski 	 */
354909edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
355009edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
355109edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
355212735f88SJan Kara 
3553b2c57642SRitesh Harjani 	/*
3554b2c57642SRitesh Harjani 	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3555b2c57642SRitesh Harjani 	 * So handle it here itself instead of querying ext4_map_blocks().
3556b2c57642SRitesh Harjani 	 * Since ext4_map_blocks() will warn about it and will return
3557b2c57642SRitesh Harjani 	 * -EIO error.
3558b2c57642SRitesh Harjani 	 */
3559b2c57642SRitesh Harjani 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3560b2c57642SRitesh Harjani 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3561b2c57642SRitesh Harjani 
3562b2c57642SRitesh Harjani 		if (offset >= sbi->s_bitmap_maxbytes) {
3563b2c57642SRitesh Harjani 			map.m_flags = 0;
3564b2c57642SRitesh Harjani 			goto set_iomap;
3565b2c57642SRitesh Harjani 		}
3566b2c57642SRitesh Harjani 	}
3567b2c57642SRitesh Harjani 
356812735f88SJan Kara 	ret = ext4_map_blocks(NULL, inode, &map, 0);
3569ba5843f5SJan Kara 	if (ret < 0)
3570ba5843f5SJan Kara 		return ret;
3571914f82a3SJan Kara 	if (ret == 0)
357209edf4d3SMatthew Bobrowski 		delalloc = ext4_iomap_is_delalloc(inode, &map);
357309edf4d3SMatthew Bobrowski 
3574b2c57642SRitesh Harjani set_iomap:
3575de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
357609edf4d3SMatthew Bobrowski 	if (delalloc && iomap->type == IOMAP_HOLE)
357709edf4d3SMatthew Bobrowski 		iomap->type = IOMAP_DELALLOC;
357809edf4d3SMatthew Bobrowski 
357909edf4d3SMatthew Bobrowski 	return 0;
3580914f82a3SJan Kara }
3581914f82a3SJan Kara 
358209edf4d3SMatthew Bobrowski const struct iomap_ops ext4_iomap_report_ops = {
358309edf4d3SMatthew Bobrowski 	.iomap_begin = ext4_iomap_begin_report,
358409edf4d3SMatthew Bobrowski };
35854c0425ffSMingming Cao 
3586ac27a0ecSDave Kleikamp /*
35876b1f86f8SLinus Torvalds  * Whenever the folio is being dirtied, corresponding buffers should already
35886b1f86f8SLinus Torvalds  * be attached to the transaction (we take care of this in ext4_page_mkwrite()
35896b1f86f8SLinus Torvalds  * and ext4_write_begin()). However we cannot move buffers to dirty transaction
35906b1f86f8SLinus Torvalds  * lists here because ->dirty_folio is called under VFS locks and the folio
35912bb8dd40SJan Kara  * is not necessarily locked.
3592ac27a0ecSDave Kleikamp  *
3593187c82cbSMatthew Wilcox (Oracle)  * We cannot just dirty the folio and leave attached buffers clean, because the
3594ac27a0ecSDave Kleikamp  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3595ac27a0ecSDave Kleikamp  * or jbddirty because all the journalling code will explode.
3596ac27a0ecSDave Kleikamp  *
3597187c82cbSMatthew Wilcox (Oracle)  * So what we do is to mark the folio "pending dirty" and next time writepage
3598ac27a0ecSDave Kleikamp  * is called, propagate that into the buffers appropriately.
3599ac27a0ecSDave Kleikamp  */
3600187c82cbSMatthew Wilcox (Oracle) static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3601187c82cbSMatthew Wilcox (Oracle) 		struct folio *folio)
3602ac27a0ecSDave Kleikamp {
36030f252336SMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
3604187c82cbSMatthew Wilcox (Oracle) 	folio_set_checked(folio);
3605187c82cbSMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
3606ac27a0ecSDave Kleikamp }
3607ac27a0ecSDave Kleikamp 
3608e621900aSMatthew Wilcox (Oracle) static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
36096dcc693bSJan Kara {
3610e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3611e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
3612e621900aSMatthew Wilcox (Oracle) 	return block_dirty_folio(mapping, folio);
36136dcc693bSJan Kara }
36146dcc693bSJan Kara 
36150e6895baSRitesh Harjani static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
36160e6895baSRitesh Harjani 				    struct file *file, sector_t *span)
36170e6895baSRitesh Harjani {
36180e6895baSRitesh Harjani 	return iomap_swapfile_activate(sis, file, span,
36190e6895baSRitesh Harjani 				       &ext4_iomap_report_ops);
36200e6895baSRitesh Harjani }
36210e6895baSRitesh Harjani 
362274d553aaSTheodore Ts'o static const struct address_space_operations ext4_aops = {
3623fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
36246311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
362543ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
362620970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3627bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
362874d553aaSTheodore Ts'o 	.write_end		= ext4_write_end,
3629e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
3630617ba13bSMingming Cao 	.bmap			= ext4_bmap,
36317ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
36323c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3633378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
3634ac27a0ecSDave Kleikamp 	.migratepage		= buffer_migrate_page,
36358ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3636aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36370e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3638ac27a0ecSDave Kleikamp };
3639ac27a0ecSDave Kleikamp 
3640617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
3641fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
36426311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
364343ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
364420970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3645bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
3646bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
3647187c82cbSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_journalled_dirty_folio,
3648617ba13bSMingming Cao 	.bmap			= ext4_bmap,
3649ccd16945SMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_journalled_invalidate_folio,
36503c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3651378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
36528ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3653aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36540e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3655ac27a0ecSDave Kleikamp };
3656ac27a0ecSDave Kleikamp 
365764769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
3658fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
36596311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
366043ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
366120970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
366264769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
366364769240SAlex Tomas 	.write_end		= ext4_da_write_end,
3664e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
366564769240SAlex Tomas 	.bmap			= ext4_bmap,
36667ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
36673c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3668378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
366964769240SAlex Tomas 	.migratepage		= buffer_migrate_page,
36708ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3671aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36720e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
367364769240SAlex Tomas };
367464769240SAlex Tomas 
36755f0663bbSDan Williams static const struct address_space_operations ext4_dax_aops = {
36765f0663bbSDan Williams 	.writepages		= ext4_dax_writepages,
36775f0663bbSDan Williams 	.direct_IO		= noop_direct_IO,
367846de8b97SMatthew Wilcox (Oracle) 	.dirty_folio		= noop_dirty_folio,
367994dbb631SToshi Kani 	.bmap			= ext4_bmap,
36800e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
36815f0663bbSDan Williams };
36825f0663bbSDan Williams 
3683617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
3684ac27a0ecSDave Kleikamp {
36853d2b1582SLukas Czerner 	switch (ext4_inode_journal_mode(inode)) {
36863d2b1582SLukas Czerner 	case EXT4_INODE_ORDERED_DATA_MODE:
36873d2b1582SLukas Czerner 	case EXT4_INODE_WRITEBACK_DATA_MODE:
36883d2b1582SLukas Czerner 		break;
36893d2b1582SLukas Czerner 	case EXT4_INODE_JOURNAL_DATA_MODE:
3690617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
369174d553aaSTheodore Ts'o 		return;
36923d2b1582SLukas Czerner 	default:
36933d2b1582SLukas Czerner 		BUG();
36943d2b1582SLukas Czerner 	}
36955f0663bbSDan Williams 	if (IS_DAX(inode))
36965f0663bbSDan Williams 		inode->i_mapping->a_ops = &ext4_dax_aops;
36975f0663bbSDan Williams 	else if (test_opt(inode->i_sb, DELALLOC))
369874d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_da_aops;
369974d553aaSTheodore Ts'o 	else
370074d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_aops;
3701ac27a0ecSDave Kleikamp }
3702ac27a0ecSDave Kleikamp 
3703923ae0ffSRoss Zwisler static int __ext4_block_zero_page_range(handle_t *handle,
3704d863dc36SLukas Czerner 		struct address_space *mapping, loff_t from, loff_t length)
3705d863dc36SLukas Czerner {
370609cbfeafSKirill A. Shutemov 	ext4_fsblk_t index = from >> PAGE_SHIFT;
370709cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3708923ae0ffSRoss Zwisler 	unsigned blocksize, pos;
3709d863dc36SLukas Czerner 	ext4_lblk_t iblock;
3710d863dc36SLukas Czerner 	struct inode *inode = mapping->host;
3711d863dc36SLukas Czerner 	struct buffer_head *bh;
3712d863dc36SLukas Czerner 	struct page *page;
3713d863dc36SLukas Czerner 	int err = 0;
3714d863dc36SLukas Czerner 
371509cbfeafSKirill A. Shutemov 	page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3716c62d2555SMichal Hocko 				   mapping_gfp_constraint(mapping, ~__GFP_FS));
3717d863dc36SLukas Czerner 	if (!page)
3718d863dc36SLukas Czerner 		return -ENOMEM;
3719d863dc36SLukas Czerner 
3720d863dc36SLukas Czerner 	blocksize = inode->i_sb->s_blocksize;
3721d863dc36SLukas Czerner 
372209cbfeafSKirill A. Shutemov 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3723d863dc36SLukas Czerner 
3724d863dc36SLukas Czerner 	if (!page_has_buffers(page))
3725d863dc36SLukas Czerner 		create_empty_buffers(page, blocksize, 0);
3726d863dc36SLukas Czerner 
3727d863dc36SLukas Czerner 	/* Find the buffer that contains "offset" */
3728d863dc36SLukas Czerner 	bh = page_buffers(page);
3729d863dc36SLukas Czerner 	pos = blocksize;
3730d863dc36SLukas Czerner 	while (offset >= pos) {
3731d863dc36SLukas Czerner 		bh = bh->b_this_page;
3732d863dc36SLukas Czerner 		iblock++;
3733d863dc36SLukas Czerner 		pos += blocksize;
3734d863dc36SLukas Czerner 	}
3735d863dc36SLukas Czerner 	if (buffer_freed(bh)) {
3736d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "freed: skip");
3737d863dc36SLukas Czerner 		goto unlock;
3738d863dc36SLukas Czerner 	}
3739d863dc36SLukas Czerner 	if (!buffer_mapped(bh)) {
3740d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "unmapped");
3741d863dc36SLukas Czerner 		ext4_get_block(inode, iblock, bh, 0);
3742d863dc36SLukas Czerner 		/* unmapped? It's a hole - nothing to do */
3743d863dc36SLukas Czerner 		if (!buffer_mapped(bh)) {
3744d863dc36SLukas Czerner 			BUFFER_TRACE(bh, "still unmapped");
3745d863dc36SLukas Czerner 			goto unlock;
3746d863dc36SLukas Czerner 		}
3747d863dc36SLukas Czerner 	}
3748d863dc36SLukas Czerner 
3749d863dc36SLukas Czerner 	/* Ok, it's mapped. Make sure it's up-to-date */
3750d863dc36SLukas Czerner 	if (PageUptodate(page))
3751d863dc36SLukas Czerner 		set_buffer_uptodate(bh);
3752d863dc36SLukas Czerner 
3753d863dc36SLukas Czerner 	if (!buffer_uptodate(bh)) {
37542d069c08Szhangyi (F) 		err = ext4_read_bh_lock(bh, 0, true);
37552d069c08Szhangyi (F) 		if (err)
3756d863dc36SLukas Czerner 			goto unlock;
37574f74d15fSEric Biggers 		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3758c9c7429cSMichael Halcrow 			/* We expect the key to be set. */
3759a7550b30SJaegeuk Kim 			BUG_ON(!fscrypt_has_encryption_key(inode));
3760834f1565SEric Biggers 			err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3761834f1565SEric Biggers 							       bh_offset(bh));
3762834f1565SEric Biggers 			if (err) {
3763834f1565SEric Biggers 				clear_buffer_uptodate(bh);
3764834f1565SEric Biggers 				goto unlock;
3765834f1565SEric Biggers 			}
3766c9c7429cSMichael Halcrow 		}
3767d863dc36SLukas Czerner 	}
3768d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3769d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "get write access");
3770188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
3771188c299eSJan Kara 						    EXT4_JTR_NONE);
3772d863dc36SLukas Czerner 		if (err)
3773d863dc36SLukas Czerner 			goto unlock;
3774d863dc36SLukas Czerner 	}
3775d863dc36SLukas Czerner 	zero_user(page, offset, length);
3776d863dc36SLukas Czerner 	BUFFER_TRACE(bh, "zeroed end of block");
3777d863dc36SLukas Czerner 
3778d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3779d863dc36SLukas Czerner 		err = ext4_handle_dirty_metadata(handle, inode, bh);
37800713ed0cSLukas Czerner 	} else {
3781353eefd3Sjon ernst 		err = 0;
3782d863dc36SLukas Czerner 		mark_buffer_dirty(bh);
37833957ef53SJan Kara 		if (ext4_should_order_data(inode))
378473131fbbSRoss Zwisler 			err = ext4_jbd2_inode_add_write(handle, inode, from,
378573131fbbSRoss Zwisler 					length);
37860713ed0cSLukas Czerner 	}
3787d863dc36SLukas Czerner 
3788d863dc36SLukas Czerner unlock:
3789d863dc36SLukas Czerner 	unlock_page(page);
379009cbfeafSKirill A. Shutemov 	put_page(page);
3791d863dc36SLukas Czerner 	return err;
3792d863dc36SLukas Czerner }
3793d863dc36SLukas Czerner 
379494350ab5SMatthew Wilcox /*
3795923ae0ffSRoss Zwisler  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3796923ae0ffSRoss Zwisler  * starting from file offset 'from'.  The range to be zero'd must
3797923ae0ffSRoss Zwisler  * be contained with in one block.  If the specified range exceeds
3798923ae0ffSRoss Zwisler  * the end of the block it will be shortened to end of the block
37993088e5a5SBhaskar Chowdhury  * that corresponds to 'from'
3800923ae0ffSRoss Zwisler  */
3801923ae0ffSRoss Zwisler static int ext4_block_zero_page_range(handle_t *handle,
3802923ae0ffSRoss Zwisler 		struct address_space *mapping, loff_t from, loff_t length)
3803923ae0ffSRoss Zwisler {
3804923ae0ffSRoss Zwisler 	struct inode *inode = mapping->host;
380509cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3806923ae0ffSRoss Zwisler 	unsigned blocksize = inode->i_sb->s_blocksize;
3807923ae0ffSRoss Zwisler 	unsigned max = blocksize - (offset & (blocksize - 1));
3808923ae0ffSRoss Zwisler 
3809923ae0ffSRoss Zwisler 	/*
3810923ae0ffSRoss Zwisler 	 * correct length if it does not fall between
3811923ae0ffSRoss Zwisler 	 * 'from' and the end of the block
3812923ae0ffSRoss Zwisler 	 */
3813923ae0ffSRoss Zwisler 	if (length > max || length < 0)
3814923ae0ffSRoss Zwisler 		length = max;
3815923ae0ffSRoss Zwisler 
381647e69351SJan Kara 	if (IS_DAX(inode)) {
3817c6f40468SChristoph Hellwig 		return dax_zero_range(inode, from, length, NULL,
381847e69351SJan Kara 				      &ext4_iomap_ops);
381947e69351SJan Kara 	}
3820923ae0ffSRoss Zwisler 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3821923ae0ffSRoss Zwisler }
3822923ae0ffSRoss Zwisler 
3823923ae0ffSRoss Zwisler /*
382494350ab5SMatthew Wilcox  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
382594350ab5SMatthew Wilcox  * up to the end of the block which corresponds to `from'.
382694350ab5SMatthew Wilcox  * This required during truncate. We need to physically zero the tail end
382794350ab5SMatthew Wilcox  * of that block so it doesn't yield old data if the file is later grown.
382894350ab5SMatthew Wilcox  */
3829c197855eSStephen Hemminger static int ext4_block_truncate_page(handle_t *handle,
383094350ab5SMatthew Wilcox 		struct address_space *mapping, loff_t from)
383194350ab5SMatthew Wilcox {
383209cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
383394350ab5SMatthew Wilcox 	unsigned length;
383494350ab5SMatthew Wilcox 	unsigned blocksize;
383594350ab5SMatthew Wilcox 	struct inode *inode = mapping->host;
383694350ab5SMatthew Wilcox 
38370d06863fSTheodore Ts'o 	/* If we are processing an encrypted inode during orphan list handling */
3838592ddec7SChandan Rajendra 	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
38390d06863fSTheodore Ts'o 		return 0;
38400d06863fSTheodore Ts'o 
384194350ab5SMatthew Wilcox 	blocksize = inode->i_sb->s_blocksize;
384294350ab5SMatthew Wilcox 	length = blocksize - (offset & (blocksize - 1));
384394350ab5SMatthew Wilcox 
384494350ab5SMatthew Wilcox 	return ext4_block_zero_page_range(handle, mapping, from, length);
384594350ab5SMatthew Wilcox }
384694350ab5SMatthew Wilcox 
3847a87dd18cSLukas Czerner int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3848a87dd18cSLukas Czerner 			     loff_t lstart, loff_t length)
3849a87dd18cSLukas Czerner {
3850a87dd18cSLukas Czerner 	struct super_block *sb = inode->i_sb;
3851a87dd18cSLukas Czerner 	struct address_space *mapping = inode->i_mapping;
3852e1be3a92SLukas Czerner 	unsigned partial_start, partial_end;
3853a87dd18cSLukas Czerner 	ext4_fsblk_t start, end;
3854a87dd18cSLukas Czerner 	loff_t byte_end = (lstart + length - 1);
3855a87dd18cSLukas Czerner 	int err = 0;
3856a87dd18cSLukas Czerner 
3857e1be3a92SLukas Czerner 	partial_start = lstart & (sb->s_blocksize - 1);
3858e1be3a92SLukas Czerner 	partial_end = byte_end & (sb->s_blocksize - 1);
3859e1be3a92SLukas Czerner 
3860a87dd18cSLukas Czerner 	start = lstart >> sb->s_blocksize_bits;
3861a87dd18cSLukas Czerner 	end = byte_end >> sb->s_blocksize_bits;
3862a87dd18cSLukas Czerner 
3863a87dd18cSLukas Czerner 	/* Handle partial zero within the single block */
3864e1be3a92SLukas Czerner 	if (start == end &&
3865e1be3a92SLukas Czerner 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3866a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3867a87dd18cSLukas Czerner 						 lstart, length);
3868a87dd18cSLukas Czerner 		return err;
3869a87dd18cSLukas Czerner 	}
3870a87dd18cSLukas Czerner 	/* Handle partial zero out on the start of the range */
3871e1be3a92SLukas Czerner 	if (partial_start) {
3872a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3873a87dd18cSLukas Czerner 						 lstart, sb->s_blocksize);
3874a87dd18cSLukas Czerner 		if (err)
3875a87dd18cSLukas Czerner 			return err;
3876a87dd18cSLukas Czerner 	}
3877a87dd18cSLukas Czerner 	/* Handle partial zero out on the end of the range */
3878e1be3a92SLukas Czerner 	if (partial_end != sb->s_blocksize - 1)
3879a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3880e1be3a92SLukas Czerner 						 byte_end - partial_end,
3881e1be3a92SLukas Czerner 						 partial_end + 1);
3882a87dd18cSLukas Czerner 	return err;
3883a87dd18cSLukas Czerner }
3884a87dd18cSLukas Czerner 
388591ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
388691ef4cafSDuane Griffin {
388791ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
388891ef4cafSDuane Griffin 		return 1;
388991ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
389091ef4cafSDuane Griffin 		return 1;
389191ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
389291ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
389391ef4cafSDuane Griffin 	return 0;
389491ef4cafSDuane Griffin }
389591ef4cafSDuane Griffin 
3896ac27a0ecSDave Kleikamp /*
389701127848SJan Kara  * We have to make sure i_disksize gets properly updated before we truncate
389801127848SJan Kara  * page cache due to hole punching or zero range. Otherwise i_disksize update
389901127848SJan Kara  * can get lost as it may have been postponed to submission of writeback but
390001127848SJan Kara  * that will never happen after we truncate page cache.
390101127848SJan Kara  */
390201127848SJan Kara int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
390301127848SJan Kara 				      loff_t len)
390401127848SJan Kara {
390501127848SJan Kara 	handle_t *handle;
39064209ae12SHarshad Shirwadkar 	int ret;
39074209ae12SHarshad Shirwadkar 
390801127848SJan Kara 	loff_t size = i_size_read(inode);
390901127848SJan Kara 
39105955102cSAl Viro 	WARN_ON(!inode_is_locked(inode));
391101127848SJan Kara 	if (offset > size || offset + len < size)
391201127848SJan Kara 		return 0;
391301127848SJan Kara 
391401127848SJan Kara 	if (EXT4_I(inode)->i_disksize >= size)
391501127848SJan Kara 		return 0;
391601127848SJan Kara 
391701127848SJan Kara 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
391801127848SJan Kara 	if (IS_ERR(handle))
391901127848SJan Kara 		return PTR_ERR(handle);
392001127848SJan Kara 	ext4_update_i_disksize(inode, size);
39214209ae12SHarshad Shirwadkar 	ret = ext4_mark_inode_dirty(handle, inode);
392201127848SJan Kara 	ext4_journal_stop(handle);
392301127848SJan Kara 
39244209ae12SHarshad Shirwadkar 	return ret;
392501127848SJan Kara }
392601127848SJan Kara 
3927d4f5258eSJan Kara static void ext4_wait_dax_page(struct inode *inode)
3928430657b6SRoss Zwisler {
3929d4f5258eSJan Kara 	filemap_invalidate_unlock(inode->i_mapping);
3930430657b6SRoss Zwisler 	schedule();
3931d4f5258eSJan Kara 	filemap_invalidate_lock(inode->i_mapping);
3932430657b6SRoss Zwisler }
3933430657b6SRoss Zwisler 
3934430657b6SRoss Zwisler int ext4_break_layouts(struct inode *inode)
3935430657b6SRoss Zwisler {
3936430657b6SRoss Zwisler 	struct page *page;
3937430657b6SRoss Zwisler 	int error;
3938430657b6SRoss Zwisler 
3939d4f5258eSJan Kara 	if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
3940430657b6SRoss Zwisler 		return -EINVAL;
3941430657b6SRoss Zwisler 
3942430657b6SRoss Zwisler 	do {
3943430657b6SRoss Zwisler 		page = dax_layout_busy_page(inode->i_mapping);
3944430657b6SRoss Zwisler 		if (!page)
3945430657b6SRoss Zwisler 			return 0;
3946430657b6SRoss Zwisler 
3947430657b6SRoss Zwisler 		error = ___wait_var_event(&page->_refcount,
3948430657b6SRoss Zwisler 				atomic_read(&page->_refcount) == 1,
3949430657b6SRoss Zwisler 				TASK_INTERRUPTIBLE, 0, 0,
3950d4f5258eSJan Kara 				ext4_wait_dax_page(inode));
3951b1f38217SRoss Zwisler 	} while (error == 0);
3952430657b6SRoss Zwisler 
3953430657b6SRoss Zwisler 	return error;
3954430657b6SRoss Zwisler }
3955430657b6SRoss Zwisler 
395601127848SJan Kara /*
3957cca32b7eSRoss Zwisler  * ext4_punch_hole: punches a hole in a file by releasing the blocks
3958a4bb6b64SAllison Henderson  * associated with the given offset and length
3959a4bb6b64SAllison Henderson  *
3960a4bb6b64SAllison Henderson  * @inode:  File inode
3961a4bb6b64SAllison Henderson  * @offset: The offset where the hole will begin
3962a4bb6b64SAllison Henderson  * @len:    The length of the hole
3963a4bb6b64SAllison Henderson  *
39644907cb7bSAnatol Pomozov  * Returns: 0 on success or negative on failure
3965a4bb6b64SAllison Henderson  */
3966a4bb6b64SAllison Henderson 
3967ad5cd4f4SDarrick J. Wong int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3968a4bb6b64SAllison Henderson {
3969ad5cd4f4SDarrick J. Wong 	struct inode *inode = file_inode(file);
397026a4c0c6STheodore Ts'o 	struct super_block *sb = inode->i_sb;
397126a4c0c6STheodore Ts'o 	ext4_lblk_t first_block, stop_block;
397226a4c0c6STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
39732da37622STadeusz Struk 	loff_t first_block_offset, last_block_offset, max_length;
39742da37622STadeusz Struk 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
397526a4c0c6STheodore Ts'o 	handle_t *handle;
397626a4c0c6STheodore Ts'o 	unsigned int credits;
39774209ae12SHarshad Shirwadkar 	int ret = 0, ret2 = 0;
397826a4c0c6STheodore Ts'o 
3979b8a86845SLukas Czerner 	trace_ext4_punch_hole(inode, offset, length, 0);
3980aaddea81SZheng Liu 
398126a4c0c6STheodore Ts'o 	/*
398226a4c0c6STheodore Ts'o 	 * Write out all dirty pages to avoid race conditions
398326a4c0c6STheodore Ts'o 	 * Then release them.
398426a4c0c6STheodore Ts'o 	 */
3985cca32b7eSRoss Zwisler 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
398626a4c0c6STheodore Ts'o 		ret = filemap_write_and_wait_range(mapping, offset,
398726a4c0c6STheodore Ts'o 						   offset + length - 1);
398826a4c0c6STheodore Ts'o 		if (ret)
398926a4c0c6STheodore Ts'o 			return ret;
399026a4c0c6STheodore Ts'o 	}
399126a4c0c6STheodore Ts'o 
39925955102cSAl Viro 	inode_lock(inode);
39939ef06cecSLukas Czerner 
399426a4c0c6STheodore Ts'o 	/* No need to punch hole beyond i_size */
399526a4c0c6STheodore Ts'o 	if (offset >= inode->i_size)
399626a4c0c6STheodore Ts'o 		goto out_mutex;
399726a4c0c6STheodore Ts'o 
399826a4c0c6STheodore Ts'o 	/*
399926a4c0c6STheodore Ts'o 	 * If the hole extends beyond i_size, set the hole
400026a4c0c6STheodore Ts'o 	 * to end after the page that contains i_size
400126a4c0c6STheodore Ts'o 	 */
400226a4c0c6STheodore Ts'o 	if (offset + length > inode->i_size) {
400326a4c0c6STheodore Ts'o 		length = inode->i_size +
400409cbfeafSKirill A. Shutemov 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
400526a4c0c6STheodore Ts'o 		   offset;
400626a4c0c6STheodore Ts'o 	}
400726a4c0c6STheodore Ts'o 
40082da37622STadeusz Struk 	/*
40092da37622STadeusz Struk 	 * For punch hole the length + offset needs to be within one block
40102da37622STadeusz Struk 	 * before last range. Adjust the length if it goes beyond that limit.
40112da37622STadeusz Struk 	 */
40122da37622STadeusz Struk 	max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
40132da37622STadeusz Struk 	if (offset + length > max_length)
40142da37622STadeusz Struk 		length = max_length - offset;
40152da37622STadeusz Struk 
4016a361293fSJan Kara 	if (offset & (sb->s_blocksize - 1) ||
4017a361293fSJan Kara 	    (offset + length) & (sb->s_blocksize - 1)) {
4018a361293fSJan Kara 		/*
4019a361293fSJan Kara 		 * Attach jinode to inode for jbd2 if we do any zeroing of
4020a361293fSJan Kara 		 * partial block
4021a361293fSJan Kara 		 */
4022a361293fSJan Kara 		ret = ext4_inode_attach_jinode(inode);
4023a361293fSJan Kara 		if (ret < 0)
4024a361293fSJan Kara 			goto out_mutex;
4025a361293fSJan Kara 
4026a361293fSJan Kara 	}
4027a361293fSJan Kara 
4028f340b3d9Shongnanli 	/* Wait all existing dio workers, newcomers will block on i_rwsem */
4029ea3d7209SJan Kara 	inode_dio_wait(inode);
4030ea3d7209SJan Kara 
4031ad5cd4f4SDarrick J. Wong 	ret = file_modified(file);
4032ad5cd4f4SDarrick J. Wong 	if (ret)
4033ad5cd4f4SDarrick J. Wong 		goto out_mutex;
4034ad5cd4f4SDarrick J. Wong 
4035ea3d7209SJan Kara 	/*
4036ea3d7209SJan Kara 	 * Prevent page faults from reinstantiating pages we have released from
4037ea3d7209SJan Kara 	 * page cache.
4038ea3d7209SJan Kara 	 */
4039d4f5258eSJan Kara 	filemap_invalidate_lock(mapping);
4040430657b6SRoss Zwisler 
4041430657b6SRoss Zwisler 	ret = ext4_break_layouts(inode);
4042430657b6SRoss Zwisler 	if (ret)
4043430657b6SRoss Zwisler 		goto out_dio;
4044430657b6SRoss Zwisler 
4045a87dd18cSLukas Czerner 	first_block_offset = round_up(offset, sb->s_blocksize);
4046a87dd18cSLukas Czerner 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
404726a4c0c6STheodore Ts'o 
4048a87dd18cSLukas Czerner 	/* Now release the pages and zero block aligned part of pages*/
404901127848SJan Kara 	if (last_block_offset > first_block_offset) {
405001127848SJan Kara 		ret = ext4_update_disksize_before_punch(inode, offset, length);
405101127848SJan Kara 		if (ret)
405201127848SJan Kara 			goto out_dio;
4053a87dd18cSLukas Czerner 		truncate_pagecache_range(inode, first_block_offset,
4054a87dd18cSLukas Czerner 					 last_block_offset);
405501127848SJan Kara 	}
405626a4c0c6STheodore Ts'o 
405726a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
405826a4c0c6STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
405926a4c0c6STheodore Ts'o 	else
406026a4c0c6STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
406126a4c0c6STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
406226a4c0c6STheodore Ts'o 	if (IS_ERR(handle)) {
406326a4c0c6STheodore Ts'o 		ret = PTR_ERR(handle);
406426a4c0c6STheodore Ts'o 		ext4_std_error(sb, ret);
406526a4c0c6STheodore Ts'o 		goto out_dio;
406626a4c0c6STheodore Ts'o 	}
406726a4c0c6STheodore Ts'o 
4068a87dd18cSLukas Czerner 	ret = ext4_zero_partial_blocks(handle, inode, offset,
4069a87dd18cSLukas Czerner 				       length);
407026a4c0c6STheodore Ts'o 	if (ret)
407126a4c0c6STheodore Ts'o 		goto out_stop;
407226a4c0c6STheodore Ts'o 
407326a4c0c6STheodore Ts'o 	first_block = (offset + sb->s_blocksize - 1) >>
407426a4c0c6STheodore Ts'o 		EXT4_BLOCK_SIZE_BITS(sb);
407526a4c0c6STheodore Ts'o 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
407626a4c0c6STheodore Ts'o 
4077eee597acSLukas Czerner 	/* If there are blocks to remove, do it */
4078eee597acSLukas Czerner 	if (stop_block > first_block) {
407926a4c0c6STheodore Ts'o 
408026a4c0c6STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
408127bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
408226a4c0c6STheodore Ts'o 
408326a4c0c6STheodore Ts'o 		ret = ext4_es_remove_extent(inode, first_block,
408426a4c0c6STheodore Ts'o 					    stop_block - first_block);
408526a4c0c6STheodore Ts'o 		if (ret) {
408626a4c0c6STheodore Ts'o 			up_write(&EXT4_I(inode)->i_data_sem);
408726a4c0c6STheodore Ts'o 			goto out_stop;
408826a4c0c6STheodore Ts'o 		}
408926a4c0c6STheodore Ts'o 
409026a4c0c6STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
409126a4c0c6STheodore Ts'o 			ret = ext4_ext_remove_space(inode, first_block,
409226a4c0c6STheodore Ts'o 						    stop_block - 1);
409326a4c0c6STheodore Ts'o 		else
40944f579ae7SLukas Czerner 			ret = ext4_ind_remove_space(handle, inode, first_block,
409526a4c0c6STheodore Ts'o 						    stop_block);
409626a4c0c6STheodore Ts'o 
4097819c4920STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
4098eee597acSLukas Czerner 	}
4099a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_range(handle, inode, first_block, stop_block);
410026a4c0c6STheodore Ts'o 	if (IS_SYNC(inode))
410126a4c0c6STheodore Ts'o 		ext4_handle_sync(handle);
4102e251f9bcSMaxim Patlasov 
4103eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
41044209ae12SHarshad Shirwadkar 	ret2 = ext4_mark_inode_dirty(handle, inode);
41054209ae12SHarshad Shirwadkar 	if (unlikely(ret2))
41064209ae12SHarshad Shirwadkar 		ret = ret2;
410767a7d5f5SJan Kara 	if (ret >= 0)
410867a7d5f5SJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
410926a4c0c6STheodore Ts'o out_stop:
411026a4c0c6STheodore Ts'o 	ext4_journal_stop(handle);
411126a4c0c6STheodore Ts'o out_dio:
4112d4f5258eSJan Kara 	filemap_invalidate_unlock(mapping);
411326a4c0c6STheodore Ts'o out_mutex:
41145955102cSAl Viro 	inode_unlock(inode);
411526a4c0c6STheodore Ts'o 	return ret;
4116a4bb6b64SAllison Henderson }
4117a4bb6b64SAllison Henderson 
4118a361293fSJan Kara int ext4_inode_attach_jinode(struct inode *inode)
4119a361293fSJan Kara {
4120a361293fSJan Kara 	struct ext4_inode_info *ei = EXT4_I(inode);
4121a361293fSJan Kara 	struct jbd2_inode *jinode;
4122a361293fSJan Kara 
4123a361293fSJan Kara 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4124a361293fSJan Kara 		return 0;
4125a361293fSJan Kara 
4126a361293fSJan Kara 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4127a361293fSJan Kara 	spin_lock(&inode->i_lock);
4128a361293fSJan Kara 	if (!ei->jinode) {
4129a361293fSJan Kara 		if (!jinode) {
4130a361293fSJan Kara 			spin_unlock(&inode->i_lock);
4131a361293fSJan Kara 			return -ENOMEM;
4132a361293fSJan Kara 		}
4133a361293fSJan Kara 		ei->jinode = jinode;
4134a361293fSJan Kara 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4135a361293fSJan Kara 		jinode = NULL;
4136a361293fSJan Kara 	}
4137a361293fSJan Kara 	spin_unlock(&inode->i_lock);
4138a361293fSJan Kara 	if (unlikely(jinode != NULL))
4139a361293fSJan Kara 		jbd2_free_inode(jinode);
4140a361293fSJan Kara 	return 0;
4141a361293fSJan Kara }
4142a361293fSJan Kara 
4143a4bb6b64SAllison Henderson /*
4144617ba13bSMingming Cao  * ext4_truncate()
4145ac27a0ecSDave Kleikamp  *
4146617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
4147617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4148ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
4149ac27a0ecSDave Kleikamp  *
415042b2aa86SJustin P. Mattock  * As we work through the truncate and commit bits of it to the journal there
4151ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
4152ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
4153ac27a0ecSDave Kleikamp  *
4154ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
4155ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
4156ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
4157ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
4158ac27a0ecSDave Kleikamp  * left-to-right works OK too).
4159ac27a0ecSDave Kleikamp  *
4160ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
4161ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
4162ac27a0ecSDave Kleikamp  *
4163ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
4164617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4165ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
4166617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
4167617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
4168ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
4169617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
4170ac27a0ecSDave Kleikamp  */
41712c98eb5eSTheodore Ts'o int ext4_truncate(struct inode *inode)
4172ac27a0ecSDave Kleikamp {
4173819c4920STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
4174819c4920STheodore Ts'o 	unsigned int credits;
41754209ae12SHarshad Shirwadkar 	int err = 0, err2;
4176819c4920STheodore Ts'o 	handle_t *handle;
4177819c4920STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
4178819c4920STheodore Ts'o 
417919b5ef61STheodore Ts'o 	/*
418019b5ef61STheodore Ts'o 	 * There is a possibility that we're either freeing the inode
4181e04027e8SMatthew Wilcox 	 * or it's a completely new inode. In those cases we might not
4182f340b3d9Shongnanli 	 * have i_rwsem locked because it's not necessary.
418319b5ef61STheodore Ts'o 	 */
418419b5ef61STheodore Ts'o 	if (!(inode->i_state & (I_NEW|I_FREEING)))
41855955102cSAl Viro 		WARN_ON(!inode_is_locked(inode));
41860562e0baSJiaying Zhang 	trace_ext4_truncate_enter(inode);
41870562e0baSJiaying Zhang 
418891ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
41899a5d265fSzhengliang 		goto out_trace;
4190ac27a0ecSDave Kleikamp 
41915534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
419219f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
41937d8f9f7dSTheodore Ts'o 
4194aef1c851STao Ma 	if (ext4_has_inline_data(inode)) {
4195aef1c851STao Ma 		int has_inline = 1;
4196aef1c851STao Ma 
419701daf945STheodore Ts'o 		err = ext4_inline_data_truncate(inode, &has_inline);
41989a5d265fSzhengliang 		if (err || has_inline)
41999a5d265fSzhengliang 			goto out_trace;
4200aef1c851STao Ma 	}
4201aef1c851STao Ma 
4202a361293fSJan Kara 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4203a361293fSJan Kara 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4204a361293fSJan Kara 		if (ext4_inode_attach_jinode(inode) < 0)
42059a5d265fSzhengliang 			goto out_trace;
4206a361293fSJan Kara 	}
4207a361293fSJan Kara 
4208ff9893dcSAmir Goldstein 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4209819c4920STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
4210ff9893dcSAmir Goldstein 	else
4211819c4920STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
4212819c4920STheodore Ts'o 
4213819c4920STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
42149a5d265fSzhengliang 	if (IS_ERR(handle)) {
42159a5d265fSzhengliang 		err = PTR_ERR(handle);
42169a5d265fSzhengliang 		goto out_trace;
42179a5d265fSzhengliang 	}
4218819c4920STheodore Ts'o 
4219eb3544c6SLukas Czerner 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4220eb3544c6SLukas Czerner 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4221819c4920STheodore Ts'o 
4222819c4920STheodore Ts'o 	/*
4223819c4920STheodore Ts'o 	 * We add the inode to the orphan list, so that if this
4224819c4920STheodore Ts'o 	 * truncate spans multiple transactions, and we crash, we will
4225819c4920STheodore Ts'o 	 * resume the truncate when the filesystem recovers.  It also
4226819c4920STheodore Ts'o 	 * marks the inode dirty, to catch the new size.
4227819c4920STheodore Ts'o 	 *
4228819c4920STheodore Ts'o 	 * Implication: the file must always be in a sane, consistent
4229819c4920STheodore Ts'o 	 * truncatable state while each transaction commits.
4230819c4920STheodore Ts'o 	 */
42312c98eb5eSTheodore Ts'o 	err = ext4_orphan_add(handle, inode);
42322c98eb5eSTheodore Ts'o 	if (err)
4233819c4920STheodore Ts'o 		goto out_stop;
4234819c4920STheodore Ts'o 
4235819c4920STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
4236819c4920STheodore Ts'o 
423727bc446eSbrookxu 	ext4_discard_preallocations(inode, 0);
4238819c4920STheodore Ts'o 
4239819c4920STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4240d0abb36dSTheodore Ts'o 		err = ext4_ext_truncate(handle, inode);
4241819c4920STheodore Ts'o 	else
4242819c4920STheodore Ts'o 		ext4_ind_truncate(handle, inode);
4243819c4920STheodore Ts'o 
4244819c4920STheodore Ts'o 	up_write(&ei->i_data_sem);
4245d0abb36dSTheodore Ts'o 	if (err)
4246d0abb36dSTheodore Ts'o 		goto out_stop;
4247819c4920STheodore Ts'o 
4248819c4920STheodore Ts'o 	if (IS_SYNC(inode))
4249819c4920STheodore Ts'o 		ext4_handle_sync(handle);
4250819c4920STheodore Ts'o 
4251819c4920STheodore Ts'o out_stop:
4252819c4920STheodore Ts'o 	/*
4253819c4920STheodore Ts'o 	 * If this was a simple ftruncate() and the file will remain alive,
4254819c4920STheodore Ts'o 	 * then we need to clear up the orphan record which we created above.
4255819c4920STheodore Ts'o 	 * However, if this was a real unlink then we were called by
425658d86a50SWang Shilong 	 * ext4_evict_inode(), and we allow that function to clean up the
4257819c4920STheodore Ts'o 	 * orphan info for us.
4258819c4920STheodore Ts'o 	 */
4259819c4920STheodore Ts'o 	if (inode->i_nlink)
4260819c4920STheodore Ts'o 		ext4_orphan_del(handle, inode);
4261819c4920STheodore Ts'o 
4262eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
42634209ae12SHarshad Shirwadkar 	err2 = ext4_mark_inode_dirty(handle, inode);
42644209ae12SHarshad Shirwadkar 	if (unlikely(err2 && !err))
42654209ae12SHarshad Shirwadkar 		err = err2;
4266819c4920STheodore Ts'o 	ext4_journal_stop(handle);
4267a86c6181SAlex Tomas 
42689a5d265fSzhengliang out_trace:
42690562e0baSJiaying Zhang 	trace_ext4_truncate_exit(inode);
42702c98eb5eSTheodore Ts'o 	return err;
4271ac27a0ecSDave Kleikamp }
4272ac27a0ecSDave Kleikamp 
42739a1bf32cSZhang Yi static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
42749a1bf32cSZhang Yi {
42759a1bf32cSZhang Yi 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
42769a1bf32cSZhang Yi 		return inode_peek_iversion_raw(inode);
42779a1bf32cSZhang Yi 	else
42789a1bf32cSZhang Yi 		return inode_peek_iversion(inode);
42799a1bf32cSZhang Yi }
42809a1bf32cSZhang Yi 
42819a1bf32cSZhang Yi static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
42829a1bf32cSZhang Yi 				 struct ext4_inode_info *ei)
42839a1bf32cSZhang Yi {
42849a1bf32cSZhang Yi 	struct inode *inode = &(ei->vfs_inode);
42859a1bf32cSZhang Yi 	u64 i_blocks = READ_ONCE(inode->i_blocks);
42869a1bf32cSZhang Yi 	struct super_block *sb = inode->i_sb;
42879a1bf32cSZhang Yi 
42889a1bf32cSZhang Yi 	if (i_blocks <= ~0U) {
42899a1bf32cSZhang Yi 		/*
42909a1bf32cSZhang Yi 		 * i_blocks can be represented in a 32 bit variable
42919a1bf32cSZhang Yi 		 * as multiple of 512 bytes
42929a1bf32cSZhang Yi 		 */
42939a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42949a1bf32cSZhang Yi 		raw_inode->i_blocks_high = 0;
42959a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
42969a1bf32cSZhang Yi 		return 0;
42979a1bf32cSZhang Yi 	}
42989a1bf32cSZhang Yi 
42999a1bf32cSZhang Yi 	/*
43009a1bf32cSZhang Yi 	 * This should never happen since sb->s_maxbytes should not have
43019a1bf32cSZhang Yi 	 * allowed this, sb->s_maxbytes was set according to the huge_file
43029a1bf32cSZhang Yi 	 * feature in ext4_fill_super().
43039a1bf32cSZhang Yi 	 */
43049a1bf32cSZhang Yi 	if (!ext4_has_feature_huge_file(sb))
43059a1bf32cSZhang Yi 		return -EFSCORRUPTED;
43069a1bf32cSZhang Yi 
43079a1bf32cSZhang Yi 	if (i_blocks <= 0xffffffffffffULL) {
43089a1bf32cSZhang Yi 		/*
43099a1bf32cSZhang Yi 		 * i_blocks can be represented in a 48 bit variable
43109a1bf32cSZhang Yi 		 * as multiple of 512 bytes
43119a1bf32cSZhang Yi 		 */
43129a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
43139a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
43149a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
43159a1bf32cSZhang Yi 	} else {
43169a1bf32cSZhang Yi 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
43179a1bf32cSZhang Yi 		/* i_block is stored in file system block size */
43189a1bf32cSZhang Yi 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
43199a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
43209a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
43219a1bf32cSZhang Yi 	}
43229a1bf32cSZhang Yi 	return 0;
43239a1bf32cSZhang Yi }
43249a1bf32cSZhang Yi 
43259a1bf32cSZhang Yi static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
43269a1bf32cSZhang Yi {
43279a1bf32cSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
43289a1bf32cSZhang Yi 	uid_t i_uid;
43299a1bf32cSZhang Yi 	gid_t i_gid;
43309a1bf32cSZhang Yi 	projid_t i_projid;
43319a1bf32cSZhang Yi 	int block;
43329a1bf32cSZhang Yi 	int err;
43339a1bf32cSZhang Yi 
43349a1bf32cSZhang Yi 	err = ext4_inode_blocks_set(raw_inode, ei);
43359a1bf32cSZhang Yi 
43369a1bf32cSZhang Yi 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
43379a1bf32cSZhang Yi 	i_uid = i_uid_read(inode);
43389a1bf32cSZhang Yi 	i_gid = i_gid_read(inode);
43399a1bf32cSZhang Yi 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
43409a1bf32cSZhang Yi 	if (!(test_opt(inode->i_sb, NO_UID32))) {
43419a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
43429a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
43439a1bf32cSZhang Yi 		/*
43449a1bf32cSZhang Yi 		 * Fix up interoperability with old kernels. Otherwise,
43459a1bf32cSZhang Yi 		 * old inodes get re-used with the upper 16 bits of the
43469a1bf32cSZhang Yi 		 * uid/gid intact.
43479a1bf32cSZhang Yi 		 */
43489a1bf32cSZhang Yi 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
43499a1bf32cSZhang Yi 			raw_inode->i_uid_high = 0;
43509a1bf32cSZhang Yi 			raw_inode->i_gid_high = 0;
43519a1bf32cSZhang Yi 		} else {
43529a1bf32cSZhang Yi 			raw_inode->i_uid_high =
43539a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_uid));
43549a1bf32cSZhang Yi 			raw_inode->i_gid_high =
43559a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_gid));
43569a1bf32cSZhang Yi 		}
43579a1bf32cSZhang Yi 	} else {
43589a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
43599a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
43609a1bf32cSZhang Yi 		raw_inode->i_uid_high = 0;
43619a1bf32cSZhang Yi 		raw_inode->i_gid_high = 0;
43629a1bf32cSZhang Yi 	}
43639a1bf32cSZhang Yi 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
43649a1bf32cSZhang Yi 
43659a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
43669a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
43679a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
43689a1bf32cSZhang Yi 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
43699a1bf32cSZhang Yi 
43709a1bf32cSZhang Yi 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
43719a1bf32cSZhang Yi 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
43729a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
43739a1bf32cSZhang Yi 		raw_inode->i_file_acl_high =
43749a1bf32cSZhang Yi 			cpu_to_le16(ei->i_file_acl >> 32);
43759a1bf32cSZhang Yi 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
43769a1bf32cSZhang Yi 	ext4_isize_set(raw_inode, ei->i_disksize);
43779a1bf32cSZhang Yi 
43789a1bf32cSZhang Yi 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
43799a1bf32cSZhang Yi 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
43809a1bf32cSZhang Yi 		if (old_valid_dev(inode->i_rdev)) {
43819a1bf32cSZhang Yi 			raw_inode->i_block[0] =
43829a1bf32cSZhang Yi 				cpu_to_le32(old_encode_dev(inode->i_rdev));
43839a1bf32cSZhang Yi 			raw_inode->i_block[1] = 0;
43849a1bf32cSZhang Yi 		} else {
43859a1bf32cSZhang Yi 			raw_inode->i_block[0] = 0;
43869a1bf32cSZhang Yi 			raw_inode->i_block[1] =
43879a1bf32cSZhang Yi 				cpu_to_le32(new_encode_dev(inode->i_rdev));
43889a1bf32cSZhang Yi 			raw_inode->i_block[2] = 0;
43899a1bf32cSZhang Yi 		}
43909a1bf32cSZhang Yi 	} else if (!ext4_has_inline_data(inode)) {
43919a1bf32cSZhang Yi 		for (block = 0; block < EXT4_N_BLOCKS; block++)
43929a1bf32cSZhang Yi 			raw_inode->i_block[block] = ei->i_data[block];
43939a1bf32cSZhang Yi 	}
43949a1bf32cSZhang Yi 
43959a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
43969a1bf32cSZhang Yi 		u64 ivers = ext4_inode_peek_iversion(inode);
43979a1bf32cSZhang Yi 
43989a1bf32cSZhang Yi 		raw_inode->i_disk_version = cpu_to_le32(ivers);
43999a1bf32cSZhang Yi 		if (ei->i_extra_isize) {
44009a1bf32cSZhang Yi 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
44019a1bf32cSZhang Yi 				raw_inode->i_version_hi =
44029a1bf32cSZhang Yi 					cpu_to_le32(ivers >> 32);
44039a1bf32cSZhang Yi 			raw_inode->i_extra_isize =
44049a1bf32cSZhang Yi 				cpu_to_le16(ei->i_extra_isize);
44059a1bf32cSZhang Yi 		}
44069a1bf32cSZhang Yi 	}
44079a1bf32cSZhang Yi 
44089a1bf32cSZhang Yi 	if (i_projid != EXT4_DEF_PROJID &&
44099a1bf32cSZhang Yi 	    !ext4_has_feature_project(inode->i_sb))
44109a1bf32cSZhang Yi 		err = err ?: -EFSCORRUPTED;
44119a1bf32cSZhang Yi 
44129a1bf32cSZhang Yi 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
44139a1bf32cSZhang Yi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
44149a1bf32cSZhang Yi 		raw_inode->i_projid = cpu_to_le32(i_projid);
44159a1bf32cSZhang Yi 
44169a1bf32cSZhang Yi 	ext4_inode_csum_set(inode, raw_inode, ei);
44179a1bf32cSZhang Yi 	return err;
44189a1bf32cSZhang Yi }
44199a1bf32cSZhang Yi 
4420ac27a0ecSDave Kleikamp /*
4421617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
4422de01f484SZhang Yi  * underlying buffer_head on success. If we pass 'inode' and it does not
4423de01f484SZhang Yi  * have in-inode xattr, we have all inode data in memory that is needed
4424de01f484SZhang Yi  * to recreate the on-disk version of this inode.
4425ac27a0ecSDave Kleikamp  */
44268016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4427de01f484SZhang Yi 				struct inode *inode, struct ext4_iloc *iloc,
44288016e29fSHarshad Shirwadkar 				ext4_fsblk_t *ret_block)
4429ac27a0ecSDave Kleikamp {
4430240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
4431ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
4432240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
443302f03c42SLinus Torvalds 	struct blk_plug		plug;
4434240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
4435ac27a0ecSDave Kleikamp 
44363a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
44378016e29fSHarshad Shirwadkar 	if (ino < EXT4_ROOT_INO ||
44388016e29fSHarshad Shirwadkar 	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
44396a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4440ac27a0ecSDave Kleikamp 
44418016e29fSHarshad Shirwadkar 	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4442240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4443240799cdSTheodore Ts'o 	if (!gdp)
4444240799cdSTheodore Ts'o 		return -EIO;
4445240799cdSTheodore Ts'o 
4446240799cdSTheodore Ts'o 	/*
4447240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
4448240799cdSTheodore Ts'o 	 */
444900d09882STao Ma 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
44508016e29fSHarshad Shirwadkar 	inode_offset = ((ino - 1) %
4451240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
4452240799cdSTheodore Ts'o 	block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4453240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4454240799cdSTheodore Ts'o 
4455240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
4456aebf0243SWang Shilong 	if (unlikely(!bh))
4457860d21e2STheodore Ts'o 		return -ENOMEM;
44588e33fadfSZhang Yi 	if (ext4_buffer_uptodate(bh))
4459ac27a0ecSDave Kleikamp 		goto has_buffer;
4460ac27a0ecSDave Kleikamp 
44618e33fadfSZhang Yi 	lock_buffer(bh);
4462f2c77973SZhang Yi 	if (ext4_buffer_uptodate(bh)) {
4463f2c77973SZhang Yi 		/* Someone brought it uptodate while we waited */
4464f2c77973SZhang Yi 		unlock_buffer(bh);
4465f2c77973SZhang Yi 		goto has_buffer;
4466f2c77973SZhang Yi 	}
4467f2c77973SZhang Yi 
4468ac27a0ecSDave Kleikamp 	/*
4469ac27a0ecSDave Kleikamp 	 * If we have all information of the inode in memory and this
4470ac27a0ecSDave Kleikamp 	 * is the only valid inode in the block, we need not read the
4471ac27a0ecSDave Kleikamp 	 * block.
4472ac27a0ecSDave Kleikamp 	 */
4473de01f484SZhang Yi 	if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4474ac27a0ecSDave Kleikamp 		struct buffer_head *bitmap_bh;
4475240799cdSTheodore Ts'o 		int i, start;
4476ac27a0ecSDave Kleikamp 
4477240799cdSTheodore Ts'o 		start = inode_offset & ~(inodes_per_block - 1);
4478ac27a0ecSDave Kleikamp 
4479ac27a0ecSDave Kleikamp 		/* Is the inode bitmap in cache? */
4480240799cdSTheodore Ts'o 		bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4481aebf0243SWang Shilong 		if (unlikely(!bitmap_bh))
4482ac27a0ecSDave Kleikamp 			goto make_io;
4483ac27a0ecSDave Kleikamp 
4484ac27a0ecSDave Kleikamp 		/*
4485ac27a0ecSDave Kleikamp 		 * If the inode bitmap isn't in cache then the
4486ac27a0ecSDave Kleikamp 		 * optimisation may end up performing two reads instead
4487ac27a0ecSDave Kleikamp 		 * of one, so skip it.
4488ac27a0ecSDave Kleikamp 		 */
4489ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bitmap_bh)) {
4490ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
4491ac27a0ecSDave Kleikamp 			goto make_io;
4492ac27a0ecSDave Kleikamp 		}
4493240799cdSTheodore Ts'o 		for (i = start; i < start + inodes_per_block; i++) {
4494ac27a0ecSDave Kleikamp 			if (i == inode_offset)
4495ac27a0ecSDave Kleikamp 				continue;
4496617ba13bSMingming Cao 			if (ext4_test_bit(i, bitmap_bh->b_data))
4497ac27a0ecSDave Kleikamp 				break;
4498ac27a0ecSDave Kleikamp 		}
4499ac27a0ecSDave Kleikamp 		brelse(bitmap_bh);
4500240799cdSTheodore Ts'o 		if (i == start + inodes_per_block) {
4501de01f484SZhang Yi 			struct ext4_inode *raw_inode =
4502de01f484SZhang Yi 				(struct ext4_inode *) (bh->b_data + iloc->offset);
4503de01f484SZhang Yi 
4504ac27a0ecSDave Kleikamp 			/* all other inodes are free, so skip I/O */
4505ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, bh->b_size);
4506de01f484SZhang Yi 			if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4507de01f484SZhang Yi 				ext4_fill_raw_inode(inode, raw_inode);
4508ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
4509ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
4510ac27a0ecSDave Kleikamp 			goto has_buffer;
4511ac27a0ecSDave Kleikamp 		}
4512ac27a0ecSDave Kleikamp 	}
4513ac27a0ecSDave Kleikamp 
4514ac27a0ecSDave Kleikamp make_io:
4515ac27a0ecSDave Kleikamp 	/*
4516240799cdSTheodore Ts'o 	 * If we need to do any I/O, try to pre-readahead extra
4517240799cdSTheodore Ts'o 	 * blocks from the inode table.
4518240799cdSTheodore Ts'o 	 */
451902f03c42SLinus Torvalds 	blk_start_plug(&plug);
4520240799cdSTheodore Ts'o 	if (EXT4_SB(sb)->s_inode_readahead_blks) {
4521240799cdSTheodore Ts'o 		ext4_fsblk_t b, end, table;
4522240799cdSTheodore Ts'o 		unsigned num;
45230d606e2cSTheodore Ts'o 		__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4524240799cdSTheodore Ts'o 
4525240799cdSTheodore Ts'o 		table = ext4_inode_table(sb, gdp);
4526b713a5ecSTheodore Ts'o 		/* s_inode_readahead_blks is always a power of 2 */
45270d606e2cSTheodore Ts'o 		b = block & ~((ext4_fsblk_t) ra_blks - 1);
4528240799cdSTheodore Ts'o 		if (table > b)
4529240799cdSTheodore Ts'o 			b = table;
45300d606e2cSTheodore Ts'o 		end = b + ra_blks;
4531240799cdSTheodore Ts'o 		num = EXT4_INODES_PER_GROUP(sb);
4532feb0ab32SDarrick J. Wong 		if (ext4_has_group_desc_csum(sb))
4533560671a0SAneesh Kumar K.V 			num -= ext4_itable_unused_count(sb, gdp);
4534240799cdSTheodore Ts'o 		table += num / inodes_per_block;
4535240799cdSTheodore Ts'o 		if (end > table)
4536240799cdSTheodore Ts'o 			end = table;
4537240799cdSTheodore Ts'o 		while (b <= end)
45385df1d412Szhangyi (F) 			ext4_sb_breadahead_unmovable(sb, b++);
4539240799cdSTheodore Ts'o 	}
4540240799cdSTheodore Ts'o 
4541240799cdSTheodore Ts'o 	/*
4542ac27a0ecSDave Kleikamp 	 * There are other valid inodes in the buffer, this inode
4543ac27a0ecSDave Kleikamp 	 * has in-inode xattrs, or we don't have this inode in memory.
4544ac27a0ecSDave Kleikamp 	 * Read the block from disk.
4545ac27a0ecSDave Kleikamp 	 */
45468016e29fSHarshad Shirwadkar 	trace_ext4_load_inode(sb, ino);
45472d069c08Szhangyi (F) 	ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
454802f03c42SLinus Torvalds 	blk_finish_plug(&plug);
4549ac27a0ecSDave Kleikamp 	wait_on_buffer(bh);
45500904c9aeSZhang Yi 	ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4551ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
45528016e29fSHarshad Shirwadkar 		if (ret_block)
45538016e29fSHarshad Shirwadkar 			*ret_block = block;
4554ac27a0ecSDave Kleikamp 		brelse(bh);
4555ac27a0ecSDave Kleikamp 		return -EIO;
4556ac27a0ecSDave Kleikamp 	}
4557ac27a0ecSDave Kleikamp has_buffer:
4558ac27a0ecSDave Kleikamp 	iloc->bh = bh;
4559ac27a0ecSDave Kleikamp 	return 0;
4560ac27a0ecSDave Kleikamp }
4561ac27a0ecSDave Kleikamp 
45628016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc_noinmem(struct inode *inode,
45638016e29fSHarshad Shirwadkar 					struct ext4_iloc *iloc)
45648016e29fSHarshad Shirwadkar {
4565c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
45668016e29fSHarshad Shirwadkar 	int ret;
45678016e29fSHarshad Shirwadkar 
4568de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
45698016e29fSHarshad Shirwadkar 					&err_blk);
45708016e29fSHarshad Shirwadkar 
45718016e29fSHarshad Shirwadkar 	if (ret == -EIO)
45728016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
45738016e29fSHarshad Shirwadkar 					"unable to read itable block");
45748016e29fSHarshad Shirwadkar 
45758016e29fSHarshad Shirwadkar 	return ret;
45768016e29fSHarshad Shirwadkar }
45778016e29fSHarshad Shirwadkar 
4578617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4579ac27a0ecSDave Kleikamp {
4580c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
45818016e29fSHarshad Shirwadkar 	int ret;
45828016e29fSHarshad Shirwadkar 
4583de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4584de01f484SZhang Yi 					&err_blk);
45858016e29fSHarshad Shirwadkar 
45868016e29fSHarshad Shirwadkar 	if (ret == -EIO)
45878016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
45888016e29fSHarshad Shirwadkar 					"unable to read itable block");
45898016e29fSHarshad Shirwadkar 
45908016e29fSHarshad Shirwadkar 	return ret;
45918016e29fSHarshad Shirwadkar }
45928016e29fSHarshad Shirwadkar 
45938016e29fSHarshad Shirwadkar 
45948016e29fSHarshad Shirwadkar int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
45958016e29fSHarshad Shirwadkar 			  struct ext4_iloc *iloc)
45968016e29fSHarshad Shirwadkar {
4597de01f484SZhang Yi 	return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4598ac27a0ecSDave Kleikamp }
4599ac27a0ecSDave Kleikamp 
4600a8ab6d38SIra Weiny static bool ext4_should_enable_dax(struct inode *inode)
46016642586bSRoss Zwisler {
4602a8ab6d38SIra Weiny 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4603a8ab6d38SIra Weiny 
46049cb20f94SIra Weiny 	if (test_opt2(inode->i_sb, DAX_NEVER))
46056642586bSRoss Zwisler 		return false;
46066642586bSRoss Zwisler 	if (!S_ISREG(inode->i_mode))
46076642586bSRoss Zwisler 		return false;
46086642586bSRoss Zwisler 	if (ext4_should_journal_data(inode))
46096642586bSRoss Zwisler 		return false;
46106642586bSRoss Zwisler 	if (ext4_has_inline_data(inode))
46116642586bSRoss Zwisler 		return false;
4612592ddec7SChandan Rajendra 	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
46136642586bSRoss Zwisler 		return false;
4614c93d8f88SEric Biggers 	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4615c93d8f88SEric Biggers 		return false;
4616a8ab6d38SIra Weiny 	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4617a8ab6d38SIra Weiny 		return false;
4618a8ab6d38SIra Weiny 	if (test_opt(inode->i_sb, DAX_ALWAYS))
46196642586bSRoss Zwisler 		return true;
4620a8ab6d38SIra Weiny 
4621b383a73fSIra Weiny 	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
46226642586bSRoss Zwisler }
46236642586bSRoss Zwisler 
4624043546e4SIra Weiny void ext4_set_inode_flags(struct inode *inode, bool init)
4625ac27a0ecSDave Kleikamp {
4626617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
462700a1a053STheodore Ts'o 	unsigned int new_fl = 0;
4628ac27a0ecSDave Kleikamp 
4629043546e4SIra Weiny 	WARN_ON_ONCE(IS_DAX(inode) && init);
4630043546e4SIra Weiny 
4631617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
463200a1a053STheodore Ts'o 		new_fl |= S_SYNC;
4633617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
463400a1a053STheodore Ts'o 		new_fl |= S_APPEND;
4635617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
463600a1a053STheodore Ts'o 		new_fl |= S_IMMUTABLE;
4637617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
463800a1a053STheodore Ts'o 		new_fl |= S_NOATIME;
4639617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
464000a1a053STheodore Ts'o 		new_fl |= S_DIRSYNC;
4641043546e4SIra Weiny 
4642043546e4SIra Weiny 	/* Because of the way inode_set_flags() works we must preserve S_DAX
4643043546e4SIra Weiny 	 * here if already set. */
4644043546e4SIra Weiny 	new_fl |= (inode->i_flags & S_DAX);
4645043546e4SIra Weiny 	if (init && ext4_should_enable_dax(inode))
4646923ae0ffSRoss Zwisler 		new_fl |= S_DAX;
4647043546e4SIra Weiny 
46482ee6a576SEric Biggers 	if (flags & EXT4_ENCRYPT_FL)
46492ee6a576SEric Biggers 		new_fl |= S_ENCRYPTED;
4650b886ee3eSGabriel Krisman Bertazi 	if (flags & EXT4_CASEFOLD_FL)
4651b886ee3eSGabriel Krisman Bertazi 		new_fl |= S_CASEFOLD;
4652c93d8f88SEric Biggers 	if (flags & EXT4_VERITY_FL)
4653c93d8f88SEric Biggers 		new_fl |= S_VERITY;
46545f16f322STheodore Ts'o 	inode_set_flags(inode, new_fl,
46552ee6a576SEric Biggers 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4656c93d8f88SEric Biggers 			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4657ac27a0ecSDave Kleikamp }
4658ac27a0ecSDave Kleikamp 
46590fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
46600fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
46610fc1b451SAneesh Kumar K.V {
46620fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
46638180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
46648180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
46650fc1b451SAneesh Kumar K.V 
4666e2b911c5SDarrick J. Wong 	if (ext4_has_feature_huge_file(sb)) {
46670fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
46680fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
46690fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
467007a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
46718180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
46728180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
46738180a562SAneesh Kumar K.V 		} else {
46740fc1b451SAneesh Kumar K.V 			return i_blocks;
46758180a562SAneesh Kumar K.V 		}
46760fc1b451SAneesh Kumar K.V 	} else {
46770fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
46780fc1b451SAneesh Kumar K.V 	}
46790fc1b451SAneesh Kumar K.V }
4680ff9ddf7eSJan Kara 
4681eb9b5f01STheodore Ts'o static inline int ext4_iget_extra_inode(struct inode *inode,
4682152a7b0aSTao Ma 					 struct ext4_inode *raw_inode,
4683152a7b0aSTao Ma 					 struct ext4_inode_info *ei)
4684152a7b0aSTao Ma {
4685152a7b0aSTao Ma 	__le32 *magic = (void *)raw_inode +
4686152a7b0aSTao Ma 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4687eb9b5f01STheodore Ts'o 
4688290ab230SEric Biggers 	if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
4689290ab230SEric Biggers 	    EXT4_INODE_SIZE(inode->i_sb) &&
4690290ab230SEric Biggers 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4691152a7b0aSTao Ma 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4692eb9b5f01STheodore Ts'o 		return ext4_find_inline_data_nolock(inode);
4693f19d5870STao Ma 	} else
4694f19d5870STao Ma 		EXT4_I(inode)->i_inline_off = 0;
4695eb9b5f01STheodore Ts'o 	return 0;
4696152a7b0aSTao Ma }
4697152a7b0aSTao Ma 
4698040cb378SLi Xi int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4699040cb378SLi Xi {
47000b7b7779SKaho Ng 	if (!ext4_has_feature_project(inode->i_sb))
4701040cb378SLi Xi 		return -EOPNOTSUPP;
4702040cb378SLi Xi 	*projid = EXT4_I(inode)->i_projid;
4703040cb378SLi Xi 	return 0;
4704040cb378SLi Xi }
4705040cb378SLi Xi 
4706e254d1afSEryu Guan /*
4707e254d1afSEryu Guan  * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4708e254d1afSEryu Guan  * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4709e254d1afSEryu Guan  * set.
4710e254d1afSEryu Guan  */
4711e254d1afSEryu Guan static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4712e254d1afSEryu Guan {
4713e254d1afSEryu Guan 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4714e254d1afSEryu Guan 		inode_set_iversion_raw(inode, val);
4715e254d1afSEryu Guan 	else
4716e254d1afSEryu Guan 		inode_set_iversion_queried(inode, val);
4717e254d1afSEryu Guan }
4718e254d1afSEryu Guan 
47198a363970STheodore Ts'o struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
47208a363970STheodore Ts'o 			  ext4_iget_flags flags, const char *function,
47218a363970STheodore Ts'o 			  unsigned int line)
4722ac27a0ecSDave Kleikamp {
4723617ba13bSMingming Cao 	struct ext4_iloc iloc;
4724617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
47251d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
4726bd2c38cfSJan Kara 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
47271d1fe1eeSDavid Howells 	struct inode *inode;
4728b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
47291d1fe1eeSDavid Howells 	long ret;
47307e6e1ef4SDarrick J. Wong 	loff_t size;
4731ac27a0ecSDave Kleikamp 	int block;
473208cefc7aSEric W. Biederman 	uid_t i_uid;
473308cefc7aSEric W. Biederman 	gid_t i_gid;
4734040cb378SLi Xi 	projid_t i_projid;
4735ac27a0ecSDave Kleikamp 
4736191ce178STheodore Ts'o 	if ((!(flags & EXT4_IGET_SPECIAL) &&
4737bd2c38cfSJan Kara 	     ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4738bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_usr_quota_inum) ||
4739bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_grp_quota_inum) ||
474002f310fcSJan Kara 	      ino == le32_to_cpu(es->s_prj_quota_inum) ||
474102f310fcSJan Kara 	      ino == le32_to_cpu(es->s_orphan_file_inum))) ||
47428a363970STheodore Ts'o 	    (ino < EXT4_ROOT_INO) ||
4743bd2c38cfSJan Kara 	    (ino > le32_to_cpu(es->s_inodes_count))) {
47448a363970STheodore Ts'o 		if (flags & EXT4_IGET_HANDLE)
47458a363970STheodore Ts'o 			return ERR_PTR(-ESTALE);
4746014c9caaSJan Kara 		__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
47478a363970STheodore Ts'o 			     "inode #%lu: comm %s: iget: illegal inode #",
47488a363970STheodore Ts'o 			     ino, current->comm);
47498a363970STheodore Ts'o 		return ERR_PTR(-EFSCORRUPTED);
47508a363970STheodore Ts'o 	}
47518a363970STheodore Ts'o 
47521d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
47531d1fe1eeSDavid Howells 	if (!inode)
47541d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
47551d1fe1eeSDavid Howells 	if (!(inode->i_state & I_NEW))
47561d1fe1eeSDavid Howells 		return inode;
47571d1fe1eeSDavid Howells 
47581d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
47597dc57615SPeter Huewe 	iloc.bh = NULL;
4760ac27a0ecSDave Kleikamp 
47618016e29fSHarshad Shirwadkar 	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
47621d1fe1eeSDavid Howells 	if (ret < 0)
4763ac27a0ecSDave Kleikamp 		goto bad_inode;
4764617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
4765814525f4SDarrick J. Wong 
47668e4b5eaeSTheodore Ts'o 	if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
47678a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
47688a363970STheodore Ts'o 				 "iget: root inode unallocated");
47698e4b5eaeSTheodore Ts'o 		ret = -EFSCORRUPTED;
47708e4b5eaeSTheodore Ts'o 		goto bad_inode;
47718e4b5eaeSTheodore Ts'o 	}
47728e4b5eaeSTheodore Ts'o 
47738a363970STheodore Ts'o 	if ((flags & EXT4_IGET_HANDLE) &&
47748a363970STheodore Ts'o 	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
47758a363970STheodore Ts'o 		ret = -ESTALE;
47768a363970STheodore Ts'o 		goto bad_inode;
47778a363970STheodore Ts'o 	}
47788a363970STheodore Ts'o 
4779814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4780814525f4SDarrick J. Wong 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4781814525f4SDarrick J. Wong 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
47822dc8d9e1SEric Biggers 			EXT4_INODE_SIZE(inode->i_sb) ||
47832dc8d9e1SEric Biggers 		    (ei->i_extra_isize & 3)) {
47848a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
47858a363970STheodore Ts'o 					 "iget: bad extra_isize %u "
47868a363970STheodore Ts'o 					 "(inode size %u)",
47872dc8d9e1SEric Biggers 					 ei->i_extra_isize,
4788814525f4SDarrick J. Wong 					 EXT4_INODE_SIZE(inode->i_sb));
47896a797d27SDarrick J. Wong 			ret = -EFSCORRUPTED;
4790814525f4SDarrick J. Wong 			goto bad_inode;
4791814525f4SDarrick J. Wong 		}
4792814525f4SDarrick J. Wong 	} else
4793814525f4SDarrick J. Wong 		ei->i_extra_isize = 0;
4794814525f4SDarrick J. Wong 
4795814525f4SDarrick J. Wong 	/* Precompute checksum seed for inode metadata */
47969aa5d32bSDmitry Monakhov 	if (ext4_has_metadata_csum(sb)) {
4797814525f4SDarrick J. Wong 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4798814525f4SDarrick J. Wong 		__u32 csum;
4799814525f4SDarrick J. Wong 		__le32 inum = cpu_to_le32(inode->i_ino);
4800814525f4SDarrick J. Wong 		__le32 gen = raw_inode->i_generation;
4801814525f4SDarrick J. Wong 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4802814525f4SDarrick J. Wong 				   sizeof(inum));
4803814525f4SDarrick J. Wong 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4804814525f4SDarrick J. Wong 					      sizeof(gen));
4805814525f4SDarrick J. Wong 	}
4806814525f4SDarrick J. Wong 
48078016e29fSHarshad Shirwadkar 	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
48088016e29fSHarshad Shirwadkar 	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
48098016e29fSHarshad Shirwadkar 	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
48108016e29fSHarshad Shirwadkar 		ext4_error_inode_err(inode, function, line, 0,
48118016e29fSHarshad Shirwadkar 				EFSBADCRC, "iget: checksum invalid");
48126a797d27SDarrick J. Wong 		ret = -EFSBADCRC;
4813814525f4SDarrick J. Wong 		goto bad_inode;
4814814525f4SDarrick J. Wong 	}
4815814525f4SDarrick J. Wong 
4816ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
481708cefc7aSEric W. Biederman 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
481808cefc7aSEric W. Biederman 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
48190b7b7779SKaho Ng 	if (ext4_has_feature_project(sb) &&
4820040cb378SLi Xi 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4821040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4822040cb378SLi Xi 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4823040cb378SLi Xi 	else
4824040cb378SLi Xi 		i_projid = EXT4_DEF_PROJID;
4825040cb378SLi Xi 
4826ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
482708cefc7aSEric W. Biederman 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
482808cefc7aSEric W. Biederman 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4829ac27a0ecSDave Kleikamp 	}
483008cefc7aSEric W. Biederman 	i_uid_write(inode, i_uid);
483108cefc7aSEric W. Biederman 	i_gid_write(inode, i_gid);
4832040cb378SLi Xi 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4833bfe86848SMiklos Szeredi 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4834ac27a0ecSDave Kleikamp 
4835353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
483667cf5b09STao Ma 	ei->i_inline_off = 0;
4837ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
4838ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4839ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
4840ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
4841ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
4842ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
4843ac27a0ecSDave Kleikamp 	 */
4844ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
4845393d1d1dSDr. Tilmann Bubeck 		if ((inode->i_mode == 0 ||
4846393d1d1dSDr. Tilmann Bubeck 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4847393d1d1dSDr. Tilmann Bubeck 		    ino != EXT4_BOOT_LOADER_INO) {
4848ac27a0ecSDave Kleikamp 			/* this inode is deleted */
48491d1fe1eeSDavid Howells 			ret = -ESTALE;
4850ac27a0ecSDave Kleikamp 			goto bad_inode;
4851ac27a0ecSDave Kleikamp 		}
4852ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
4853ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
4854ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
4855393d1d1dSDr. Tilmann Bubeck 		 * the process of deleting those.
4856393d1d1dSDr. Tilmann Bubeck 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4857393d1d1dSDr. Tilmann Bubeck 		 * not initialized on a new filesystem. */
4858ac27a0ecSDave Kleikamp 	}
4859ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4860043546e4SIra Weiny 	ext4_set_inode_flags(inode, true);
48610fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
48627973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4863e2b911c5SDarrick J. Wong 	if (ext4_has_feature_64bit(sb))
4864a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
4865a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4866e08ac99fSArtem Blagodarenko 	inode->i_size = ext4_isize(sb, raw_inode);
48677e6e1ef4SDarrick J. Wong 	if ((size = i_size_read(inode)) < 0) {
48688a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
48698a363970STheodore Ts'o 				 "iget: bad i_size value: %lld", size);
48707e6e1ef4SDarrick J. Wong 		ret = -EFSCORRUPTED;
48717e6e1ef4SDarrick J. Wong 		goto bad_inode;
48727e6e1ef4SDarrick J. Wong 	}
487348a34311SJan Kara 	/*
487448a34311SJan Kara 	 * If dir_index is not enabled but there's dir with INDEX flag set,
487548a34311SJan Kara 	 * we'd normally treat htree data as empty space. But with metadata
487648a34311SJan Kara 	 * checksumming that corrupts checksums so forbid that.
487748a34311SJan Kara 	 */
487848a34311SJan Kara 	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
487948a34311SJan Kara 	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
488048a34311SJan Kara 		ext4_error_inode(inode, function, line, 0,
488148a34311SJan Kara 			 "iget: Dir with htree data on filesystem without dir_index feature.");
488248a34311SJan Kara 		ret = -EFSCORRUPTED;
488348a34311SJan Kara 		goto bad_inode;
488448a34311SJan Kara 	}
4885ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
4886a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
4887a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
4888a9e7f447SDmitry Monakhov #endif
4889ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4890ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
4891a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
4892ac27a0ecSDave Kleikamp 	/*
4893ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
4894ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4895ac27a0ecSDave Kleikamp 	 */
4896617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4897ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
4898ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
4899aa75f4d3SHarshad Shirwadkar 	ext4_fc_init_inode(&ei->vfs_inode);
4900ac27a0ecSDave Kleikamp 
4901b436b9beSJan Kara 	/*
4902b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
4903b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
4904b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
4905b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
4906b436b9beSJan Kara 	 * now it is reread from disk.
4907b436b9beSJan Kara 	 */
4908b436b9beSJan Kara 	if (journal) {
4909b436b9beSJan Kara 		transaction_t *transaction;
4910b436b9beSJan Kara 		tid_t tid;
4911b436b9beSJan Kara 
4912a931da6aSTheodore Ts'o 		read_lock(&journal->j_state_lock);
4913b436b9beSJan Kara 		if (journal->j_running_transaction)
4914b436b9beSJan Kara 			transaction = journal->j_running_transaction;
4915b436b9beSJan Kara 		else
4916b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
4917b436b9beSJan Kara 		if (transaction)
4918b436b9beSJan Kara 			tid = transaction->t_tid;
4919b436b9beSJan Kara 		else
4920b436b9beSJan Kara 			tid = journal->j_commit_sequence;
4921a931da6aSTheodore Ts'o 		read_unlock(&journal->j_state_lock);
4922b436b9beSJan Kara 		ei->i_sync_tid = tid;
4923b436b9beSJan Kara 		ei->i_datasync_tid = tid;
4924b436b9beSJan Kara 	}
4925b436b9beSJan Kara 
49260040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4927ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
4928ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
49292dc8d9e1SEric Biggers 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4930617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4931617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
4932ac27a0ecSDave Kleikamp 		} else {
4933eb9b5f01STheodore Ts'o 			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4934eb9b5f01STheodore Ts'o 			if (ret)
4935eb9b5f01STheodore Ts'o 				goto bad_inode;
4936ac27a0ecSDave Kleikamp 		}
4937814525f4SDarrick J. Wong 	}
4938ac27a0ecSDave Kleikamp 
4939ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4940ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4941ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4942ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4943ef7f3835SKalpak Shah 
4944ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4945ee73f9a5SJeff Layton 		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4946ee73f9a5SJeff Layton 
494725ec56b5SJean Noel Cordenner 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
494825ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4949ee73f9a5SJeff Layton 				ivers |=
495025ec56b5SJean Noel Cordenner 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
495125ec56b5SJean Noel Cordenner 		}
4952e254d1afSEryu Guan 		ext4_inode_set_iversion_queried(inode, ivers);
4953c4f65706STheodore Ts'o 	}
495425ec56b5SJean Noel Cordenner 
4955c4b5a614STheodore Ts'o 	ret = 0;
4956485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
4957ce9f24ccSJan Kara 	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
49588a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
49598a363970STheodore Ts'o 				 "iget: bad extended attribute block %llu",
496024676da4STheodore Ts'o 				 ei->i_file_acl);
49616a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
4962485c26ecSTheodore Ts'o 		goto bad_inode;
4963f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
4964bc716523SLiu Song 		/* validate the block references in the inode */
49658016e29fSHarshad Shirwadkar 		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
49668016e29fSHarshad Shirwadkar 			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4967fe2c8191SThiemo Nagel 			(S_ISLNK(inode->i_mode) &&
49688016e29fSHarshad Shirwadkar 			!ext4_inode_is_fast_symlink(inode)))) {
4969bc716523SLiu Song 			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4970bc716523SLiu Song 				ret = ext4_ext_check_inode(inode);
4971bc716523SLiu Song 			else
49721f7d1e77STheodore Ts'o 				ret = ext4_ind_check_inode(inode);
4973fe2c8191SThiemo Nagel 		}
4974f19d5870STao Ma 	}
4975567f3e9aSTheodore Ts'o 	if (ret)
49767a262f7cSAneesh Kumar K.V 		goto bad_inode;
49777a262f7cSAneesh Kumar K.V 
4978ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
4979617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
4980617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
4981617ba13bSMingming Cao 		ext4_set_aops(inode);
4982ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
4983617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
4984617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
4985ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
49866390d33bSLuis R. Rodriguez 		/* VFS does not allow setting these so must be corruption */
49876390d33bSLuis R. Rodriguez 		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
49888a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
49898a363970STheodore Ts'o 					 "iget: immutable or append flags "
49908a363970STheodore Ts'o 					 "not allowed on symlinks");
49916390d33bSLuis R. Rodriguez 			ret = -EFSCORRUPTED;
49926390d33bSLuis R. Rodriguez 			goto bad_inode;
49936390d33bSLuis R. Rodriguez 		}
4994592ddec7SChandan Rajendra 		if (IS_ENCRYPTED(inode)) {
4995a7a67e8aSAl Viro 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
4996a7a67e8aSAl Viro 		} else if (ext4_inode_is_fast_symlink(inode)) {
499775e7566bSAl Viro 			inode->i_link = (char *)ei->i_data;
4998617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
4999e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
5000e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
5001e83c1397SDuane Griffin 		} else {
5002617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
5003ac27a0ecSDave Kleikamp 		}
5004563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5005563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5006617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
5007ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
5008ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5009ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5010ac27a0ecSDave Kleikamp 		else
5011ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5012ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5013393d1d1dSDr. Tilmann Bubeck 	} else if (ino == EXT4_BOOT_LOADER_INO) {
5014393d1d1dSDr. Tilmann Bubeck 		make_bad_inode(inode);
5015563bdd61STheodore Ts'o 	} else {
50166a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
50178a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
50188a363970STheodore Ts'o 				 "iget: bogus i_mode (%o)", inode->i_mode);
5019563bdd61STheodore Ts'o 		goto bad_inode;
5020ac27a0ecSDave Kleikamp 	}
50216456ca65STheodore Ts'o 	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
50226456ca65STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
50236456ca65STheodore Ts'o 				 "casefold flag without casefold feature");
5024ac27a0ecSDave Kleikamp 	brelse(iloc.bh);
5025dec214d0STahsin Erdogan 
50261d1fe1eeSDavid Howells 	unlock_new_inode(inode);
50271d1fe1eeSDavid Howells 	return inode;
5028ac27a0ecSDave Kleikamp 
5029ac27a0ecSDave Kleikamp bad_inode:
5030567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
50311d1fe1eeSDavid Howells 	iget_failed(inode);
50321d1fe1eeSDavid Howells 	return ERR_PTR(ret);
5033ac27a0ecSDave Kleikamp }
5034ac27a0ecSDave Kleikamp 
50353f19b2abSDavid Howells static void __ext4_update_other_inode_time(struct super_block *sb,
50363f19b2abSDavid Howells 					   unsigned long orig_ino,
50373f19b2abSDavid Howells 					   unsigned long ino,
50383f19b2abSDavid Howells 					   struct ext4_inode *raw_inode)
5039a26f4992STheodore Ts'o {
50403f19b2abSDavid Howells 	struct inode *inode;
5041a26f4992STheodore Ts'o 
50423f19b2abSDavid Howells 	inode = find_inode_by_ino_rcu(sb, ino);
50433f19b2abSDavid Howells 	if (!inode)
50443f19b2abSDavid Howells 		return;
50453f19b2abSDavid Howells 
5046ed296c6cSEric Biggers 	if (!inode_is_dirtytime_only(inode))
50473f19b2abSDavid Howells 		return;
50483f19b2abSDavid Howells 
5049a26f4992STheodore Ts'o 	spin_lock(&inode->i_lock);
5050ed296c6cSEric Biggers 	if (inode_is_dirtytime_only(inode)) {
5051a26f4992STheodore Ts'o 		struct ext4_inode_info	*ei = EXT4_I(inode);
5052a26f4992STheodore Ts'o 
50535fcd5750SJan Kara 		inode->i_state &= ~I_DIRTY_TIME;
5054a26f4992STheodore Ts'o 		spin_unlock(&inode->i_lock);
5055a26f4992STheodore Ts'o 
5056a26f4992STheodore Ts'o 		spin_lock(&ei->i_raw_lock);
50573f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
50583f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
50593f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
50603f19b2abSDavid Howells 		ext4_inode_csum_set(inode, raw_inode, ei);
5061a26f4992STheodore Ts'o 		spin_unlock(&ei->i_raw_lock);
50623f19b2abSDavid Howells 		trace_ext4_other_inode_update_time(inode, orig_ino);
50633f19b2abSDavid Howells 		return;
5064a26f4992STheodore Ts'o 	}
5065a26f4992STheodore Ts'o 	spin_unlock(&inode->i_lock);
5066a26f4992STheodore Ts'o }
5067a26f4992STheodore Ts'o 
5068a26f4992STheodore Ts'o /*
5069a26f4992STheodore Ts'o  * Opportunistically update the other time fields for other inodes in
5070a26f4992STheodore Ts'o  * the same inode table block.
5071a26f4992STheodore Ts'o  */
5072a26f4992STheodore Ts'o static void ext4_update_other_inodes_time(struct super_block *sb,
5073a26f4992STheodore Ts'o 					  unsigned long orig_ino, char *buf)
5074a26f4992STheodore Ts'o {
5075a26f4992STheodore Ts'o 	unsigned long ino;
5076a26f4992STheodore Ts'o 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5077a26f4992STheodore Ts'o 	int inode_size = EXT4_INODE_SIZE(sb);
5078a26f4992STheodore Ts'o 
50790f0ff9a9STheodore Ts'o 	/*
50800f0ff9a9STheodore Ts'o 	 * Calculate the first inode in the inode table block.  Inode
50810f0ff9a9STheodore Ts'o 	 * numbers are one-based.  That is, the first inode in a block
50820f0ff9a9STheodore Ts'o 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
50830f0ff9a9STheodore Ts'o 	 */
50840f0ff9a9STheodore Ts'o 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
50853f19b2abSDavid Howells 	rcu_read_lock();
5086a26f4992STheodore Ts'o 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5087a26f4992STheodore Ts'o 		if (ino == orig_ino)
5088a26f4992STheodore Ts'o 			continue;
50893f19b2abSDavid Howells 		__ext4_update_other_inode_time(sb, orig_ino, ino,
50903f19b2abSDavid Howells 					       (struct ext4_inode *)buf);
5091a26f4992STheodore Ts'o 	}
50923f19b2abSDavid Howells 	rcu_read_unlock();
5093a26f4992STheodore Ts'o }
5094a26f4992STheodore Ts'o 
5095664bd38bSZhang Yi /*
5096664bd38bSZhang Yi  * Post the struct inode info into an on-disk inode location in the
5097664bd38bSZhang Yi  * buffer-cache.  This gobbles the caller's reference to the
5098664bd38bSZhang Yi  * buffer_head in the inode location struct.
5099664bd38bSZhang Yi  *
5100664bd38bSZhang Yi  * The caller must have write access to iloc->bh.
5101664bd38bSZhang Yi  */
5102664bd38bSZhang Yi static int ext4_do_update_inode(handle_t *handle,
5103664bd38bSZhang Yi 				struct inode *inode,
5104664bd38bSZhang Yi 				struct ext4_iloc *iloc)
5105664bd38bSZhang Yi {
5106664bd38bSZhang Yi 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5107664bd38bSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
5108664bd38bSZhang Yi 	struct buffer_head *bh = iloc->bh;
5109664bd38bSZhang Yi 	struct super_block *sb = inode->i_sb;
5110664bd38bSZhang Yi 	int err;
5111664bd38bSZhang Yi 	int need_datasync = 0, set_large_file = 0;
5112664bd38bSZhang Yi 
5113664bd38bSZhang Yi 	spin_lock(&ei->i_raw_lock);
5114664bd38bSZhang Yi 
5115664bd38bSZhang Yi 	/*
5116664bd38bSZhang Yi 	 * For fields not tracked in the in-memory inode, initialise them
5117664bd38bSZhang Yi 	 * to zero for new inodes.
5118664bd38bSZhang Yi 	 */
5119664bd38bSZhang Yi 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5120664bd38bSZhang Yi 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5121664bd38bSZhang Yi 
5122664bd38bSZhang Yi 	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5123664bd38bSZhang Yi 		need_datasync = 1;
5124664bd38bSZhang Yi 	if (ei->i_disksize > 0x7fffffffULL) {
5125664bd38bSZhang Yi 		if (!ext4_has_feature_large_file(sb) ||
5126664bd38bSZhang Yi 		    EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5127664bd38bSZhang Yi 			set_large_file = 1;
5128664bd38bSZhang Yi 	}
5129664bd38bSZhang Yi 
5130664bd38bSZhang Yi 	err = ext4_fill_raw_inode(inode, raw_inode);
5131202ee5dfSTheodore Ts'o 	spin_unlock(&ei->i_raw_lock);
5132baaae979SZhang Yi 	if (err) {
5133baaae979SZhang Yi 		EXT4_ERROR_INODE(inode, "corrupted inode contents");
5134baaae979SZhang Yi 		goto out_brelse;
5135baaae979SZhang Yi 	}
5136baaae979SZhang Yi 
51371751e8a6SLinus Torvalds 	if (inode->i_sb->s_flags & SB_LAZYTIME)
5138a26f4992STheodore Ts'o 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5139a26f4992STheodore Ts'o 					      bh->b_data);
5140202ee5dfSTheodore Ts'o 
51410390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
51427d8bd3c7SShijie Luo 	err = ext4_handle_dirty_metadata(handle, NULL, bh);
51437d8bd3c7SShijie Luo 	if (err)
5144baaae979SZhang Yi 		goto out_error;
514519f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5146202ee5dfSTheodore Ts'o 	if (set_large_file) {
51475d601255Sliang xie 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5148188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, sb,
5149188c299eSJan Kara 						    EXT4_SB(sb)->s_sbh,
5150188c299eSJan Kara 						    EXT4_JTR_NONE);
5151202ee5dfSTheodore Ts'o 		if (err)
5152baaae979SZhang Yi 			goto out_error;
515305c2c00fSJan Kara 		lock_buffer(EXT4_SB(sb)->s_sbh);
5154e2b911c5SDarrick J. Wong 		ext4_set_feature_large_file(sb);
515505c2c00fSJan Kara 		ext4_superblock_csum_set(sb);
515605c2c00fSJan Kara 		unlock_buffer(EXT4_SB(sb)->s_sbh);
5157202ee5dfSTheodore Ts'o 		ext4_handle_sync(handle);
5158a3f5cf14SJan Kara 		err = ext4_handle_dirty_metadata(handle, NULL,
5159a3f5cf14SJan Kara 						 EXT4_SB(sb)->s_sbh);
5160202ee5dfSTheodore Ts'o 	}
5161b71fc079SJan Kara 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5162baaae979SZhang Yi out_error:
5163baaae979SZhang Yi 	ext4_std_error(inode->i_sb, err);
5164ac27a0ecSDave Kleikamp out_brelse:
5165ac27a0ecSDave Kleikamp 	brelse(bh);
5166ac27a0ecSDave Kleikamp 	return err;
5167ac27a0ecSDave Kleikamp }
5168ac27a0ecSDave Kleikamp 
5169ac27a0ecSDave Kleikamp /*
5170617ba13bSMingming Cao  * ext4_write_inode()
5171ac27a0ecSDave Kleikamp  *
5172ac27a0ecSDave Kleikamp  * We are called from a few places:
5173ac27a0ecSDave Kleikamp  *
517487f7e416STheodore Ts'o  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5175ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
51764907cb7bSAnatol Pomozov  *   transaction to commit.
5177ac27a0ecSDave Kleikamp  *
517887f7e416STheodore Ts'o  * - Within flush work (sys_sync(), kupdate and such).
517987f7e416STheodore Ts'o  *   We wait on commit, if told to.
5180ac27a0ecSDave Kleikamp  *
518187f7e416STheodore Ts'o  * - Within iput_final() -> write_inode_now()
518287f7e416STheodore Ts'o  *   We wait on commit, if told to.
5183ac27a0ecSDave Kleikamp  *
5184ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
5185ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
518687f7e416STheodore Ts'o  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
518787f7e416STheodore Ts'o  * writeback.
5188ac27a0ecSDave Kleikamp  *
5189ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
5190ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5191ac27a0ecSDave Kleikamp  * which we are interested.
5192ac27a0ecSDave Kleikamp  *
5193ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
5194ac27a0ecSDave Kleikamp  *
5195ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
5196ac27a0ecSDave Kleikamp  *	stuff();
5197ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
5198ac27a0ecSDave Kleikamp  *
519987f7e416STheodore Ts'o  * is in error because write_inode() could occur while `stuff()' is running,
520087f7e416STheodore Ts'o  * and the new i_size will be lost.  Plus the inode will no longer be on the
520187f7e416STheodore Ts'o  * superblock's dirty inode list.
5202ac27a0ecSDave Kleikamp  */
5203a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5204ac27a0ecSDave Kleikamp {
520591ac6f43SFrank Mayhar 	int err;
520691ac6f43SFrank Mayhar 
520718f2c4fcSTheodore Ts'o 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
520818f2c4fcSTheodore Ts'o 	    sb_rdonly(inode->i_sb))
5209ac27a0ecSDave Kleikamp 		return 0;
5210ac27a0ecSDave Kleikamp 
521118f2c4fcSTheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
521218f2c4fcSTheodore Ts'o 		return -EIO;
521318f2c4fcSTheodore Ts'o 
521491ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
5215617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
5216b38bd33aSMingming Cao 			jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5217ac27a0ecSDave Kleikamp 			dump_stack();
5218ac27a0ecSDave Kleikamp 			return -EIO;
5219ac27a0ecSDave Kleikamp 		}
5220ac27a0ecSDave Kleikamp 
522110542c22SJan Kara 		/*
522210542c22SJan Kara 		 * No need to force transaction in WB_SYNC_NONE mode. Also
522310542c22SJan Kara 		 * ext4_sync_fs() will force the commit after everything is
522410542c22SJan Kara 		 * written.
522510542c22SJan Kara 		 */
522610542c22SJan Kara 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5227ac27a0ecSDave Kleikamp 			return 0;
5228ac27a0ecSDave Kleikamp 
5229aa75f4d3SHarshad Shirwadkar 		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
523018f2c4fcSTheodore Ts'o 						EXT4_I(inode)->i_sync_tid);
523191ac6f43SFrank Mayhar 	} else {
523291ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
523391ac6f43SFrank Mayhar 
52348016e29fSHarshad Shirwadkar 		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
523591ac6f43SFrank Mayhar 		if (err)
523691ac6f43SFrank Mayhar 			return err;
523710542c22SJan Kara 		/*
523810542c22SJan Kara 		 * sync(2) will flush the whole buffer cache. No need to do
523910542c22SJan Kara 		 * it here separately for each inode.
524010542c22SJan Kara 		 */
524110542c22SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5242830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
5243830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
524454d3adbcSTheodore Ts'o 			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5245c398eda0STheodore Ts'o 					       "IO error syncing inode");
5246830156c7SFrank Mayhar 			err = -EIO;
5247830156c7SFrank Mayhar 		}
5248fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
524991ac6f43SFrank Mayhar 	}
525091ac6f43SFrank Mayhar 	return err;
5251ac27a0ecSDave Kleikamp }
5252ac27a0ecSDave Kleikamp 
5253ac27a0ecSDave Kleikamp /*
5254ccd16945SMatthew Wilcox (Oracle)  * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5255ccd16945SMatthew Wilcox (Oracle)  * buffers that are attached to a folio straddling i_size and are undergoing
525653e87268SJan Kara  * commit. In that case we have to wait for commit to finish and try again.
525753e87268SJan Kara  */
525853e87268SJan Kara static void ext4_wait_for_tail_page_commit(struct inode *inode)
525953e87268SJan Kara {
526053e87268SJan Kara 	unsigned offset;
526153e87268SJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
526253e87268SJan Kara 	tid_t commit_tid = 0;
526353e87268SJan Kara 	int ret;
526453e87268SJan Kara 
526509cbfeafSKirill A. Shutemov 	offset = inode->i_size & (PAGE_SIZE - 1);
526653e87268SJan Kara 	/*
5267ccd16945SMatthew Wilcox (Oracle) 	 * If the folio is fully truncated, we don't need to wait for any commit
5268ccd16945SMatthew Wilcox (Oracle) 	 * (and we even should not as __ext4_journalled_invalidate_folio() may
5269ccd16945SMatthew Wilcox (Oracle) 	 * strip all buffers from the folio but keep the folio dirty which can then
5270ccd16945SMatthew Wilcox (Oracle) 	 * confuse e.g. concurrent ext4_writepage() seeing dirty folio without
5271565333a1Syangerkun 	 * buffers). Also we don't need to wait for any commit if all buffers in
5272ccd16945SMatthew Wilcox (Oracle) 	 * the folio remain valid. This is most beneficial for the common case of
5273565333a1Syangerkun 	 * blocksize == PAGESIZE.
527453e87268SJan Kara 	 */
5275565333a1Syangerkun 	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
527653e87268SJan Kara 		return;
527753e87268SJan Kara 	while (1) {
5278ccd16945SMatthew Wilcox (Oracle) 		struct folio *folio = filemap_lock_folio(inode->i_mapping,
527909cbfeafSKirill A. Shutemov 				      inode->i_size >> PAGE_SHIFT);
5280ccd16945SMatthew Wilcox (Oracle) 		if (!folio)
528153e87268SJan Kara 			return;
5282ccd16945SMatthew Wilcox (Oracle) 		ret = __ext4_journalled_invalidate_folio(folio, offset,
5283ccd16945SMatthew Wilcox (Oracle) 						folio_size(folio) - offset);
5284ccd16945SMatthew Wilcox (Oracle) 		folio_unlock(folio);
5285ccd16945SMatthew Wilcox (Oracle) 		folio_put(folio);
528653e87268SJan Kara 		if (ret != -EBUSY)
528753e87268SJan Kara 			return;
528853e87268SJan Kara 		commit_tid = 0;
528953e87268SJan Kara 		read_lock(&journal->j_state_lock);
529053e87268SJan Kara 		if (journal->j_committing_transaction)
529153e87268SJan Kara 			commit_tid = journal->j_committing_transaction->t_tid;
529253e87268SJan Kara 		read_unlock(&journal->j_state_lock);
529353e87268SJan Kara 		if (commit_tid)
529453e87268SJan Kara 			jbd2_log_wait_commit(journal, commit_tid);
529553e87268SJan Kara 	}
529653e87268SJan Kara }
529753e87268SJan Kara 
529853e87268SJan Kara /*
5299617ba13bSMingming Cao  * ext4_setattr()
5300ac27a0ecSDave Kleikamp  *
5301ac27a0ecSDave Kleikamp  * Called from notify_change.
5302ac27a0ecSDave Kleikamp  *
5303ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
5304ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
5305ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
5306ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
5307ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
5308ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
5309ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
5310ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
5311ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
5312ac27a0ecSDave Kleikamp  *
5313678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
5314678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
5315678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
5316678aaf48SJan Kara  * This way we are sure that all the data written in the previous
5317678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
5318678aaf48SJan Kara  * writeback).
5319678aaf48SJan Kara  *
5320f340b3d9Shongnanli  * Called with inode->i_rwsem down.
5321ac27a0ecSDave Kleikamp  */
5322549c7297SChristian Brauner int ext4_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5323549c7297SChristian Brauner 		 struct iattr *attr)
5324ac27a0ecSDave Kleikamp {
53252b0143b5SDavid Howells 	struct inode *inode = d_inode(dentry);
5326ac27a0ecSDave Kleikamp 	int error, rc = 0;
53273d287de3SDmitry Monakhov 	int orphan = 0;
5328ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
5329ac27a0ecSDave Kleikamp 
53300db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
53310db1ff22STheodore Ts'o 		return -EIO;
53320db1ff22STheodore Ts'o 
533302b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
533402b016caSTheodore Ts'o 		return -EPERM;
533502b016caSTheodore Ts'o 
533602b016caSTheodore Ts'o 	if (unlikely(IS_APPEND(inode) &&
533702b016caSTheodore Ts'o 		     (ia_valid & (ATTR_MODE | ATTR_UID |
533802b016caSTheodore Ts'o 				  ATTR_GID | ATTR_TIMES_SET))))
533902b016caSTheodore Ts'o 		return -EPERM;
534002b016caSTheodore Ts'o 
534114f3db55SChristian Brauner 	error = setattr_prepare(mnt_userns, dentry, attr);
5342ac27a0ecSDave Kleikamp 	if (error)
5343ac27a0ecSDave Kleikamp 		return error;
5344ac27a0ecSDave Kleikamp 
53453ce2b8ddSEric Biggers 	error = fscrypt_prepare_setattr(dentry, attr);
53463ce2b8ddSEric Biggers 	if (error)
53473ce2b8ddSEric Biggers 		return error;
53483ce2b8ddSEric Biggers 
5349c93d8f88SEric Biggers 	error = fsverity_prepare_setattr(dentry, attr);
5350c93d8f88SEric Biggers 	if (error)
5351c93d8f88SEric Biggers 		return error;
5352c93d8f88SEric Biggers 
5353*b27c82e1SChristian Brauner 	if (is_quota_modification(mnt_userns, inode, attr)) {
5354a7cdadeeSJan Kara 		error = dquot_initialize(inode);
5355a7cdadeeSJan Kara 		if (error)
5356a7cdadeeSJan Kara 			return error;
5357a7cdadeeSJan Kara 	}
53582729cfdcSHarshad Shirwadkar 
5359*b27c82e1SChristian Brauner 	if (i_uid_needs_update(mnt_userns, attr, inode) ||
5360*b27c82e1SChristian Brauner 	    i_gid_needs_update(mnt_userns, attr, inode)) {
5361ac27a0ecSDave Kleikamp 		handle_t *handle;
5362ac27a0ecSDave Kleikamp 
5363ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
5364ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
53659924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
53669924a92aSTheodore Ts'o 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5367194074acSDmitry Monakhov 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5368ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
5369ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
5370ac27a0ecSDave Kleikamp 			goto err_out;
5371ac27a0ecSDave Kleikamp 		}
53727a9ca53aSTahsin Erdogan 
53737a9ca53aSTahsin Erdogan 		/* dquot_transfer() calls back ext4_get_inode_usage() which
53747a9ca53aSTahsin Erdogan 		 * counts xattr inode references.
53757a9ca53aSTahsin Erdogan 		 */
53767a9ca53aSTahsin Erdogan 		down_read(&EXT4_I(inode)->xattr_sem);
5377*b27c82e1SChristian Brauner 		error = dquot_transfer(mnt_userns, inode, attr);
53787a9ca53aSTahsin Erdogan 		up_read(&EXT4_I(inode)->xattr_sem);
53797a9ca53aSTahsin Erdogan 
5380ac27a0ecSDave Kleikamp 		if (error) {
5381617ba13bSMingming Cao 			ext4_journal_stop(handle);
5382ac27a0ecSDave Kleikamp 			return error;
5383ac27a0ecSDave Kleikamp 		}
5384ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
5385ac27a0ecSDave Kleikamp 		 * one transaction */
5386*b27c82e1SChristian Brauner 		i_uid_update(mnt_userns, attr, inode);
5387*b27c82e1SChristian Brauner 		i_gid_update(mnt_userns, attr, inode);
5388617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
5389617ba13bSMingming Cao 		ext4_journal_stop(handle);
5390512c15efSPan Bian 		if (unlikely(error)) {
53914209ae12SHarshad Shirwadkar 			return error;
5392ac27a0ecSDave Kleikamp 		}
5393512c15efSPan Bian 	}
5394ac27a0ecSDave Kleikamp 
53953da40c7bSJosef Bacik 	if (attr->ia_valid & ATTR_SIZE) {
53965208386cSJan Kara 		handle_t *handle;
53973da40c7bSJosef Bacik 		loff_t oldsize = inode->i_size;
5398f4534c9fSYe Bin 		loff_t old_disksize;
5399b9c1c267SJan Kara 		int shrink = (attr->ia_size < inode->i_size);
5400562c72aaSChristoph Hellwig 
540112e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5402e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5403e2b46574SEric Sandeen 
5404aa75f4d3SHarshad Shirwadkar 			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
54050c095c7fSTheodore Ts'o 				return -EFBIG;
5406e2b46574SEric Sandeen 			}
5407aa75f4d3SHarshad Shirwadkar 		}
5408aa75f4d3SHarshad Shirwadkar 		if (!S_ISREG(inode->i_mode)) {
54093da40c7bSJosef Bacik 			return -EINVAL;
5410aa75f4d3SHarshad Shirwadkar 		}
5411dff6efc3SChristoph Hellwig 
5412dff6efc3SChristoph Hellwig 		if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5413dff6efc3SChristoph Hellwig 			inode_inc_iversion(inode);
5414dff6efc3SChristoph Hellwig 
5415b9c1c267SJan Kara 		if (shrink) {
5416b9c1c267SJan Kara 			if (ext4_should_order_data(inode)) {
54175208386cSJan Kara 				error = ext4_begin_ordered_truncate(inode,
54185208386cSJan Kara 							    attr->ia_size);
54195208386cSJan Kara 				if (error)
54205208386cSJan Kara 					goto err_out;
54215208386cSJan Kara 			}
5422b9c1c267SJan Kara 			/*
5423b9c1c267SJan Kara 			 * Blocks are going to be removed from the inode. Wait
5424b9c1c267SJan Kara 			 * for dio in flight.
5425b9c1c267SJan Kara 			 */
5426b9c1c267SJan Kara 			inode_dio_wait(inode);
5427b9c1c267SJan Kara 		}
5428b9c1c267SJan Kara 
5429d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
5430b9c1c267SJan Kara 
5431b9c1c267SJan Kara 		rc = ext4_break_layouts(inode);
5432b9c1c267SJan Kara 		if (rc) {
5433d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
5434aa75f4d3SHarshad Shirwadkar 			goto err_out;
5435b9c1c267SJan Kara 		}
5436b9c1c267SJan Kara 
54373da40c7bSJosef Bacik 		if (attr->ia_size != inode->i_size) {
54389924a92aSTheodore Ts'o 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5439ac27a0ecSDave Kleikamp 			if (IS_ERR(handle)) {
5440ac27a0ecSDave Kleikamp 				error = PTR_ERR(handle);
5441b9c1c267SJan Kara 				goto out_mmap_sem;
5442ac27a0ecSDave Kleikamp 			}
54433da40c7bSJosef Bacik 			if (ext4_handle_valid(handle) && shrink) {
5444617ba13bSMingming Cao 				error = ext4_orphan_add(handle, inode);
54453d287de3SDmitry Monakhov 				orphan = 1;
54463d287de3SDmitry Monakhov 			}
5447911af577SEryu Guan 			/*
5448911af577SEryu Guan 			 * Update c/mtime on truncate up, ext4_truncate() will
5449911af577SEryu Guan 			 * update c/mtime in shrink case below
5450911af577SEryu Guan 			 */
5451911af577SEryu Guan 			if (!shrink) {
5452eeca7ea1SDeepa Dinamani 				inode->i_mtime = current_time(inode);
5453911af577SEryu Guan 				inode->i_ctime = inode->i_mtime;
5454911af577SEryu Guan 			}
5455aa75f4d3SHarshad Shirwadkar 
5456aa75f4d3SHarshad Shirwadkar 			if (shrink)
5457a80f7fcfSHarshad Shirwadkar 				ext4_fc_track_range(handle, inode,
5458aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5459aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
54609725958bSXin Yin 					EXT_MAX_BLOCKS - 1);
5461aa75f4d3SHarshad Shirwadkar 			else
5462aa75f4d3SHarshad Shirwadkar 				ext4_fc_track_range(
5463a80f7fcfSHarshad Shirwadkar 					handle, inode,
5464aa75f4d3SHarshad Shirwadkar 					(oldsize > 0 ? oldsize - 1 : oldsize) >>
5465aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
5466aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5467aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits);
5468aa75f4d3SHarshad Shirwadkar 
546990e775b7SJan Kara 			down_write(&EXT4_I(inode)->i_data_sem);
5470f4534c9fSYe Bin 			old_disksize = EXT4_I(inode)->i_disksize;
5471617ba13bSMingming Cao 			EXT4_I(inode)->i_disksize = attr->ia_size;
5472617ba13bSMingming Cao 			rc = ext4_mark_inode_dirty(handle, inode);
5473ac27a0ecSDave Kleikamp 			if (!error)
5474ac27a0ecSDave Kleikamp 				error = rc;
547590e775b7SJan Kara 			/*
547690e775b7SJan Kara 			 * We have to update i_size under i_data_sem together
547790e775b7SJan Kara 			 * with i_disksize to avoid races with writeback code
547890e775b7SJan Kara 			 * running ext4_wb_update_i_disksize().
547990e775b7SJan Kara 			 */
548090e775b7SJan Kara 			if (!error)
548190e775b7SJan Kara 				i_size_write(inode, attr->ia_size);
5482f4534c9fSYe Bin 			else
5483f4534c9fSYe Bin 				EXT4_I(inode)->i_disksize = old_disksize;
548490e775b7SJan Kara 			up_write(&EXT4_I(inode)->i_data_sem);
5485617ba13bSMingming Cao 			ext4_journal_stop(handle);
5486b9c1c267SJan Kara 			if (error)
5487b9c1c267SJan Kara 				goto out_mmap_sem;
548882a25b02SJan Kara 			if (!shrink) {
5489b9c1c267SJan Kara 				pagecache_isize_extended(inode, oldsize,
5490b9c1c267SJan Kara 							 inode->i_size);
5491b9c1c267SJan Kara 			} else if (ext4_should_journal_data(inode)) {
549282a25b02SJan Kara 				ext4_wait_for_tail_page_commit(inode);
5493b9c1c267SJan Kara 			}
5494430657b6SRoss Zwisler 		}
5495430657b6SRoss Zwisler 
549653e87268SJan Kara 		/*
549753e87268SJan Kara 		 * Truncate pagecache after we've waited for commit
549853e87268SJan Kara 		 * in data=journal mode to make pages freeable.
549953e87268SJan Kara 		 */
55007caef267SKirill A. Shutemov 		truncate_pagecache(inode, inode->i_size);
5501b9c1c267SJan Kara 		/*
5502b9c1c267SJan Kara 		 * Call ext4_truncate() even if i_size didn't change to
5503b9c1c267SJan Kara 		 * truncate possible preallocated blocks.
5504b9c1c267SJan Kara 		 */
5505b9c1c267SJan Kara 		if (attr->ia_size <= oldsize) {
55062c98eb5eSTheodore Ts'o 			rc = ext4_truncate(inode);
55072c98eb5eSTheodore Ts'o 			if (rc)
55082c98eb5eSTheodore Ts'o 				error = rc;
55092c98eb5eSTheodore Ts'o 		}
5510b9c1c267SJan Kara out_mmap_sem:
5511d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
55123da40c7bSJosef Bacik 	}
5513ac27a0ecSDave Kleikamp 
55142c98eb5eSTheodore Ts'o 	if (!error) {
551514f3db55SChristian Brauner 		setattr_copy(mnt_userns, inode, attr);
55161025774cSChristoph Hellwig 		mark_inode_dirty(inode);
55171025774cSChristoph Hellwig 	}
55181025774cSChristoph Hellwig 
55191025774cSChristoph Hellwig 	/*
55201025774cSChristoph Hellwig 	 * If the call to ext4_truncate failed to get a transaction handle at
55211025774cSChristoph Hellwig 	 * all, we need to clean up the in-core orphan list manually.
55221025774cSChristoph Hellwig 	 */
55233d287de3SDmitry Monakhov 	if (orphan && inode->i_nlink)
5524617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
5525ac27a0ecSDave Kleikamp 
55262c98eb5eSTheodore Ts'o 	if (!error && (ia_valid & ATTR_MODE))
552714f3db55SChristian Brauner 		rc = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5528ac27a0ecSDave Kleikamp 
5529ac27a0ecSDave Kleikamp err_out:
5530aa75f4d3SHarshad Shirwadkar 	if  (error)
5531617ba13bSMingming Cao 		ext4_std_error(inode->i_sb, error);
5532ac27a0ecSDave Kleikamp 	if (!error)
5533ac27a0ecSDave Kleikamp 		error = rc;
5534ac27a0ecSDave Kleikamp 	return error;
5535ac27a0ecSDave Kleikamp }
5536ac27a0ecSDave Kleikamp 
5537549c7297SChristian Brauner int ext4_getattr(struct user_namespace *mnt_userns, const struct path *path,
5538549c7297SChristian Brauner 		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
55393e3398a0SMingming Cao {
554099652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
554199652ea5SDavid Howells 	struct ext4_inode *raw_inode;
554299652ea5SDavid Howells 	struct ext4_inode_info *ei = EXT4_I(inode);
554399652ea5SDavid Howells 	unsigned int flags;
55443e3398a0SMingming Cao 
5545d4c5e960STheodore Ts'o 	if ((request_mask & STATX_BTIME) &&
5546d4c5e960STheodore Ts'o 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
554799652ea5SDavid Howells 		stat->result_mask |= STATX_BTIME;
554899652ea5SDavid Howells 		stat->btime.tv_sec = ei->i_crtime.tv_sec;
554999652ea5SDavid Howells 		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
555099652ea5SDavid Howells 	}
555199652ea5SDavid Howells 
555299652ea5SDavid Howells 	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
555399652ea5SDavid Howells 	if (flags & EXT4_APPEND_FL)
555499652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_APPEND;
555599652ea5SDavid Howells 	if (flags & EXT4_COMPR_FL)
555699652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_COMPRESSED;
555799652ea5SDavid Howells 	if (flags & EXT4_ENCRYPT_FL)
555899652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_ENCRYPTED;
555999652ea5SDavid Howells 	if (flags & EXT4_IMMUTABLE_FL)
556099652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_IMMUTABLE;
556199652ea5SDavid Howells 	if (flags & EXT4_NODUMP_FL)
556299652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_NODUMP;
55631f607195SEric Biggers 	if (flags & EXT4_VERITY_FL)
55641f607195SEric Biggers 		stat->attributes |= STATX_ATTR_VERITY;
556599652ea5SDavid Howells 
55663209f68bSDavid Howells 	stat->attributes_mask |= (STATX_ATTR_APPEND |
55673209f68bSDavid Howells 				  STATX_ATTR_COMPRESSED |
55683209f68bSDavid Howells 				  STATX_ATTR_ENCRYPTED |
55693209f68bSDavid Howells 				  STATX_ATTR_IMMUTABLE |
55701f607195SEric Biggers 				  STATX_ATTR_NODUMP |
55711f607195SEric Biggers 				  STATX_ATTR_VERITY);
55723209f68bSDavid Howells 
557314f3db55SChristian Brauner 	generic_fillattr(mnt_userns, inode, stat);
557499652ea5SDavid Howells 	return 0;
557599652ea5SDavid Howells }
557699652ea5SDavid Howells 
5577549c7297SChristian Brauner int ext4_file_getattr(struct user_namespace *mnt_userns,
5578549c7297SChristian Brauner 		      const struct path *path, struct kstat *stat,
557999652ea5SDavid Howells 		      u32 request_mask, unsigned int query_flags)
558099652ea5SDavid Howells {
558199652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
558299652ea5SDavid Howells 	u64 delalloc_blocks;
558399652ea5SDavid Howells 
558414f3db55SChristian Brauner 	ext4_getattr(mnt_userns, path, stat, request_mask, query_flags);
55853e3398a0SMingming Cao 
55863e3398a0SMingming Cao 	/*
55879206c561SAndreas Dilger 	 * If there is inline data in the inode, the inode will normally not
55889206c561SAndreas Dilger 	 * have data blocks allocated (it may have an external xattr block).
55899206c561SAndreas Dilger 	 * Report at least one sector for such files, so tools like tar, rsync,
5590d67d64f4STheodore Ts'o 	 * others don't incorrectly think the file is completely sparse.
55919206c561SAndreas Dilger 	 */
55929206c561SAndreas Dilger 	if (unlikely(ext4_has_inline_data(inode)))
55939206c561SAndreas Dilger 		stat->blocks += (stat->size + 511) >> 9;
55949206c561SAndreas Dilger 
55959206c561SAndreas Dilger 	/*
55963e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
55973e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
55983e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
55993e3398a0SMingming Cao 	 * on-disk file blocks.
56003e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
56013e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
56023e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
56033e3398a0SMingming Cao 	 * blocks for this file.
56043e3398a0SMingming Cao 	 */
560596607551STao Ma 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
560696607551STao Ma 				   EXT4_I(inode)->i_reserved_data_blocks);
56078af8eeccSJan Kara 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
56083e3398a0SMingming Cao 	return 0;
56093e3398a0SMingming Cao }
5610ac27a0ecSDave Kleikamp 
5611fffb2739SJan Kara static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5612fffb2739SJan Kara 				   int pextents)
5613a02908f1SMingming Cao {
561412e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5615fffb2739SJan Kara 		return ext4_ind_trans_blocks(inode, lblocks);
5616fffb2739SJan Kara 	return ext4_ext_index_trans_blocks(inode, pextents);
5617a02908f1SMingming Cao }
5618ac51d837STheodore Ts'o 
5619a02908f1SMingming Cao /*
5620a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
5621a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
5622a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
5623a02908f1SMingming Cao  *
5624a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
56254907cb7bSAnatol Pomozov  * different block groups too. If they are contiguous, with flexbg,
5626a02908f1SMingming Cao  * they could still across block group boundary.
5627a02908f1SMingming Cao  *
5628a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
5629a02908f1SMingming Cao  */
5630dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5631fffb2739SJan Kara 				  int pextents)
5632a02908f1SMingming Cao {
56338df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
56348df9675fSTheodore Ts'o 	int gdpblocks;
5635a02908f1SMingming Cao 	int idxblocks;
5636a02908f1SMingming Cao 	int ret = 0;
5637a02908f1SMingming Cao 
5638a02908f1SMingming Cao 	/*
5639fffb2739SJan Kara 	 * How many index blocks need to touch to map @lblocks logical blocks
5640fffb2739SJan Kara 	 * to @pextents physical extents?
5641a02908f1SMingming Cao 	 */
5642fffb2739SJan Kara 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5643a02908f1SMingming Cao 
5644a02908f1SMingming Cao 	ret = idxblocks;
5645a02908f1SMingming Cao 
5646a02908f1SMingming Cao 	/*
5647a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
5648a02908f1SMingming Cao 	 * to account
5649a02908f1SMingming Cao 	 */
5650fffb2739SJan Kara 	groups = idxblocks + pextents;
5651a02908f1SMingming Cao 	gdpblocks = groups;
56528df9675fSTheodore Ts'o 	if (groups > ngroups)
56538df9675fSTheodore Ts'o 		groups = ngroups;
5654a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5655a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5656a02908f1SMingming Cao 
5657a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
5658a02908f1SMingming Cao 	ret += groups + gdpblocks;
5659a02908f1SMingming Cao 
5660a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
5661a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5662ac27a0ecSDave Kleikamp 
5663ac27a0ecSDave Kleikamp 	return ret;
5664ac27a0ecSDave Kleikamp }
5665ac27a0ecSDave Kleikamp 
5666ac27a0ecSDave Kleikamp /*
566725985edcSLucas De Marchi  * Calculate the total number of credits to reserve to fit
5668f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
5669f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
5670a02908f1SMingming Cao  *
5671525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
5672a02908f1SMingming Cao  *
5673525f4ed8SMingming Cao  * We need to consider the worse case, when
5674a02908f1SMingming Cao  * one new block per extent.
5675a02908f1SMingming Cao  */
5676a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
5677a02908f1SMingming Cao {
5678a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
5679a02908f1SMingming Cao 	int ret;
5680a02908f1SMingming Cao 
5681fffb2739SJan Kara 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5682a02908f1SMingming Cao 
5683a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
5684a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
5685a02908f1SMingming Cao 		ret += bpp;
5686a02908f1SMingming Cao 	return ret;
5687a02908f1SMingming Cao }
5688f3bd1f3fSMingming Cao 
5689f3bd1f3fSMingming Cao /*
5690f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
5691f3bd1f3fSMingming Cao  *
5692f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
569379e83036SEric Sandeen  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5694f3bd1f3fSMingming Cao  *
5695f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
5696f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
5697f3bd1f3fSMingming Cao  */
5698f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5699f3bd1f3fSMingming Cao {
5700f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5701f3bd1f3fSMingming Cao }
5702f3bd1f3fSMingming Cao 
5703a02908f1SMingming Cao /*
5704617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
5705ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
5706ac27a0ecSDave Kleikamp  */
5707617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
5708617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
5709ac27a0ecSDave Kleikamp {
5710ac27a0ecSDave Kleikamp 	int err = 0;
5711ac27a0ecSDave Kleikamp 
5712a6758309SVasily Averin 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5713a6758309SVasily Averin 		put_bh(iloc->bh);
57140db1ff22STheodore Ts'o 		return -EIO;
5715a6758309SVasily Averin 	}
5716a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_inode(handle, inode);
5717aa75f4d3SHarshad Shirwadkar 
5718c64db50eSTheodore Ts'o 	if (IS_I_VERSION(inode))
571925ec56b5SJean Noel Cordenner 		inode_inc_iversion(inode);
572025ec56b5SJean Noel Cordenner 
5721ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
5722ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
5723ac27a0ecSDave Kleikamp 
5724dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5725830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
5726ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
5727ac27a0ecSDave Kleikamp 	return err;
5728ac27a0ecSDave Kleikamp }
5729ac27a0ecSDave Kleikamp 
5730ac27a0ecSDave Kleikamp /*
5731ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
5732ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
5733ac27a0ecSDave Kleikamp  */
5734ac27a0ecSDave Kleikamp 
5735ac27a0ecSDave Kleikamp int
5736617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5737617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
5738ac27a0ecSDave Kleikamp {
57390390131bSFrank Mayhar 	int err;
57400390131bSFrank Mayhar 
57410db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
57420db1ff22STheodore Ts'o 		return -EIO;
57430db1ff22STheodore Ts'o 
5744617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
5745ac27a0ecSDave Kleikamp 	if (!err) {
5746ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
5747188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb,
5748188c299eSJan Kara 						    iloc->bh, EXT4_JTR_NONE);
5749ac27a0ecSDave Kleikamp 		if (err) {
5750ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
5751ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
5752ac27a0ecSDave Kleikamp 		}
5753ac27a0ecSDave Kleikamp 	}
5754617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5755ac27a0ecSDave Kleikamp 	return err;
5756ac27a0ecSDave Kleikamp }
5757ac27a0ecSDave Kleikamp 
5758c03b45b8SMiao Xie static int __ext4_expand_extra_isize(struct inode *inode,
5759c03b45b8SMiao Xie 				     unsigned int new_extra_isize,
5760c03b45b8SMiao Xie 				     struct ext4_iloc *iloc,
5761c03b45b8SMiao Xie 				     handle_t *handle, int *no_expand)
5762c03b45b8SMiao Xie {
5763c03b45b8SMiao Xie 	struct ext4_inode *raw_inode;
5764c03b45b8SMiao Xie 	struct ext4_xattr_ibody_header *header;
57654ea99936STheodore Ts'o 	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
57664ea99936STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
5767c03b45b8SMiao Xie 	int error;
5768c03b45b8SMiao Xie 
57694ea99936STheodore Ts'o 	/* this was checked at iget time, but double check for good measure */
57704ea99936STheodore Ts'o 	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
57714ea99936STheodore Ts'o 	    (ei->i_extra_isize & 3)) {
57724ea99936STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
57734ea99936STheodore Ts'o 				 ei->i_extra_isize,
57744ea99936STheodore Ts'o 				 EXT4_INODE_SIZE(inode->i_sb));
57754ea99936STheodore Ts'o 		return -EFSCORRUPTED;
57764ea99936STheodore Ts'o 	}
57774ea99936STheodore Ts'o 	if ((new_extra_isize < ei->i_extra_isize) ||
57784ea99936STheodore Ts'o 	    (new_extra_isize < 4) ||
57794ea99936STheodore Ts'o 	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
57804ea99936STheodore Ts'o 		return -EINVAL;	/* Should never happen */
57814ea99936STheodore Ts'o 
5782c03b45b8SMiao Xie 	raw_inode = ext4_raw_inode(iloc);
5783c03b45b8SMiao Xie 
5784c03b45b8SMiao Xie 	header = IHDR(inode, raw_inode);
5785c03b45b8SMiao Xie 
5786c03b45b8SMiao Xie 	/* No extended attributes present */
5787c03b45b8SMiao Xie 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5788c03b45b8SMiao Xie 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5789c03b45b8SMiao Xie 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5790c03b45b8SMiao Xie 		       EXT4_I(inode)->i_extra_isize, 0,
5791c03b45b8SMiao Xie 		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
5792c03b45b8SMiao Xie 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
5793c03b45b8SMiao Xie 		return 0;
5794c03b45b8SMiao Xie 	}
5795c03b45b8SMiao Xie 
5796c03b45b8SMiao Xie 	/* try to expand with EAs present */
5797c03b45b8SMiao Xie 	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5798c03b45b8SMiao Xie 					   raw_inode, handle);
5799c03b45b8SMiao Xie 	if (error) {
5800c03b45b8SMiao Xie 		/*
5801c03b45b8SMiao Xie 		 * Inode size expansion failed; don't try again
5802c03b45b8SMiao Xie 		 */
5803c03b45b8SMiao Xie 		*no_expand = 1;
5804c03b45b8SMiao Xie 	}
5805c03b45b8SMiao Xie 
5806c03b45b8SMiao Xie 	return error;
5807c03b45b8SMiao Xie }
5808c03b45b8SMiao Xie 
5809ac27a0ecSDave Kleikamp /*
58106dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
58116dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
58126dd4ee7cSKalpak Shah  */
5813cf0a5e81SMiao Xie static int ext4_try_to_expand_extra_isize(struct inode *inode,
58141d03ec98SAneesh Kumar K.V 					  unsigned int new_extra_isize,
58151d03ec98SAneesh Kumar K.V 					  struct ext4_iloc iloc,
58161d03ec98SAneesh Kumar K.V 					  handle_t *handle)
58176dd4ee7cSKalpak Shah {
58183b10fdc6SMiao Xie 	int no_expand;
58193b10fdc6SMiao Xie 	int error;
58206dd4ee7cSKalpak Shah 
5821cf0a5e81SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5822cf0a5e81SMiao Xie 		return -EOVERFLOW;
5823cf0a5e81SMiao Xie 
5824cf0a5e81SMiao Xie 	/*
5825cf0a5e81SMiao Xie 	 * In nojournal mode, we can immediately attempt to expand
5826cf0a5e81SMiao Xie 	 * the inode.  When journaled, we first need to obtain extra
5827cf0a5e81SMiao Xie 	 * buffer credits since we may write into the EA block
5828cf0a5e81SMiao Xie 	 * with this same handle. If journal_extend fails, then it will
5829cf0a5e81SMiao Xie 	 * only result in a minor loss of functionality for that inode.
5830cf0a5e81SMiao Xie 	 * If this is felt to be critical, then e2fsck should be run to
5831cf0a5e81SMiao Xie 	 * force a large enough s_min_extra_isize.
5832cf0a5e81SMiao Xie 	 */
58336cb367c2SJan Kara 	if (ext4_journal_extend(handle,
583483448bdfSJan Kara 				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5835cf0a5e81SMiao Xie 		return -ENOSPC;
58366dd4ee7cSKalpak Shah 
58373b10fdc6SMiao Xie 	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5838cf0a5e81SMiao Xie 		return -EBUSY;
58393b10fdc6SMiao Xie 
5840c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5841c03b45b8SMiao Xie 					  handle, &no_expand);
58423b10fdc6SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5843c03b45b8SMiao Xie 
5844c03b45b8SMiao Xie 	return error;
58456dd4ee7cSKalpak Shah }
58466dd4ee7cSKalpak Shah 
5847c03b45b8SMiao Xie int ext4_expand_extra_isize(struct inode *inode,
5848c03b45b8SMiao Xie 			    unsigned int new_extra_isize,
5849c03b45b8SMiao Xie 			    struct ext4_iloc *iloc)
5850c03b45b8SMiao Xie {
5851c03b45b8SMiao Xie 	handle_t *handle;
5852c03b45b8SMiao Xie 	int no_expand;
5853c03b45b8SMiao Xie 	int error, rc;
5854c03b45b8SMiao Xie 
5855c03b45b8SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5856c03b45b8SMiao Xie 		brelse(iloc->bh);
5857c03b45b8SMiao Xie 		return -EOVERFLOW;
5858c03b45b8SMiao Xie 	}
5859c03b45b8SMiao Xie 
5860c03b45b8SMiao Xie 	handle = ext4_journal_start(inode, EXT4_HT_INODE,
5861c03b45b8SMiao Xie 				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5862c03b45b8SMiao Xie 	if (IS_ERR(handle)) {
5863c03b45b8SMiao Xie 		error = PTR_ERR(handle);
5864c03b45b8SMiao Xie 		brelse(iloc->bh);
5865c03b45b8SMiao Xie 		return error;
5866c03b45b8SMiao Xie 	}
5867c03b45b8SMiao Xie 
5868c03b45b8SMiao Xie 	ext4_write_lock_xattr(inode, &no_expand);
5869c03b45b8SMiao Xie 
5870ddccb6dbSzhangyi (F) 	BUFFER_TRACE(iloc->bh, "get_write_access");
5871188c299eSJan Kara 	error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
5872188c299eSJan Kara 					      EXT4_JTR_NONE);
58733b10fdc6SMiao Xie 	if (error) {
5874c03b45b8SMiao Xie 		brelse(iloc->bh);
58757f420d64SDan Carpenter 		goto out_unlock;
58763b10fdc6SMiao Xie 	}
5877cf0a5e81SMiao Xie 
5878c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5879c03b45b8SMiao Xie 					  handle, &no_expand);
5880c03b45b8SMiao Xie 
5881c03b45b8SMiao Xie 	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5882c03b45b8SMiao Xie 	if (!error)
5883c03b45b8SMiao Xie 		error = rc;
5884c03b45b8SMiao Xie 
58857f420d64SDan Carpenter out_unlock:
5886c03b45b8SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5887c03b45b8SMiao Xie 	ext4_journal_stop(handle);
58883b10fdc6SMiao Xie 	return error;
58896dd4ee7cSKalpak Shah }
58906dd4ee7cSKalpak Shah 
58916dd4ee7cSKalpak Shah /*
5892ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
5893ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
5894ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
5895ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
5896ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
5897ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
5898ac27a0ecSDave Kleikamp  *
5899ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
5900ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
5901ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5902ac27a0ecSDave Kleikamp  * we start and wait on commits.
5903ac27a0ecSDave Kleikamp  */
59044209ae12SHarshad Shirwadkar int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
59054209ae12SHarshad Shirwadkar 				const char *func, unsigned int line)
5906ac27a0ecSDave Kleikamp {
5907617ba13bSMingming Cao 	struct ext4_iloc iloc;
59086dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5909cf0a5e81SMiao Xie 	int err;
5910ac27a0ecSDave Kleikamp 
5911ac27a0ecSDave Kleikamp 	might_sleep();
59127ff9c073STheodore Ts'o 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5913617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
59145e1021f2SEryu Guan 	if (err)
59154209ae12SHarshad Shirwadkar 		goto out;
5916cf0a5e81SMiao Xie 
5917cf0a5e81SMiao Xie 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5918cf0a5e81SMiao Xie 		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
59196dd4ee7cSKalpak Shah 					       iloc, handle);
5920cf0a5e81SMiao Xie 
59214209ae12SHarshad Shirwadkar 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
59224209ae12SHarshad Shirwadkar out:
59234209ae12SHarshad Shirwadkar 	if (unlikely(err))
59244209ae12SHarshad Shirwadkar 		ext4_error_inode_err(inode, func, line, 0, err,
59254209ae12SHarshad Shirwadkar 					"mark_inode_dirty error");
59264209ae12SHarshad Shirwadkar 	return err;
5927ac27a0ecSDave Kleikamp }
5928ac27a0ecSDave Kleikamp 
5929ac27a0ecSDave Kleikamp /*
5930617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
5931ac27a0ecSDave Kleikamp  *
5932ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
5933ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
5934ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
5935ac27a0ecSDave Kleikamp  *
59365dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
5937ac27a0ecSDave Kleikamp  * are allocated to the file.
5938ac27a0ecSDave Kleikamp  *
5939ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
5940ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
5941ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
5942ac27a0ecSDave Kleikamp  */
5943aa385729SChristoph Hellwig void ext4_dirty_inode(struct inode *inode, int flags)
5944ac27a0ecSDave Kleikamp {
5945ac27a0ecSDave Kleikamp 	handle_t *handle;
5946ac27a0ecSDave Kleikamp 
59479924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5948ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5949ac27a0ecSDave Kleikamp 		return;
5950e2728c56SEric Biggers 	ext4_mark_inode_dirty(handle, inode);
5951e2728c56SEric Biggers 	ext4_journal_stop(handle);
5952ac27a0ecSDave Kleikamp }
5953ac27a0ecSDave Kleikamp 
5954617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
5955ac27a0ecSDave Kleikamp {
5956ac27a0ecSDave Kleikamp 	journal_t *journal;
5957ac27a0ecSDave Kleikamp 	handle_t *handle;
5958ac27a0ecSDave Kleikamp 	int err;
5959c8585c6fSDaeho Jeong 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5960ac27a0ecSDave Kleikamp 
5961ac27a0ecSDave Kleikamp 	/*
5962ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
5963ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
5964ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
5965ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
5966ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
5967ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
5968ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
5969ac27a0ecSDave Kleikamp 	 */
5970ac27a0ecSDave Kleikamp 
5971617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
59720390131bSFrank Mayhar 	if (!journal)
59730390131bSFrank Mayhar 		return 0;
5974d699594dSDave Hansen 	if (is_journal_aborted(journal))
5975ac27a0ecSDave Kleikamp 		return -EROFS;
5976ac27a0ecSDave Kleikamp 
597717335dccSDmitry Monakhov 	/* Wait for all existing dio workers */
597817335dccSDmitry Monakhov 	inode_dio_wait(inode);
597917335dccSDmitry Monakhov 
59804c546592SDaeho Jeong 	/*
59814c546592SDaeho Jeong 	 * Before flushing the journal and switching inode's aops, we have
59824c546592SDaeho Jeong 	 * to flush all dirty data the inode has. There can be outstanding
59834c546592SDaeho Jeong 	 * delayed allocations, there can be unwritten extents created by
59844c546592SDaeho Jeong 	 * fallocate or buffered writes in dioread_nolock mode covered by
59854c546592SDaeho Jeong 	 * dirty data which can be converted only after flushing the dirty
59864c546592SDaeho Jeong 	 * data (and journalled aops don't know how to handle these cases).
59874c546592SDaeho Jeong 	 */
59884c546592SDaeho Jeong 	if (val) {
5989d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
59904c546592SDaeho Jeong 		err = filemap_write_and_wait(inode->i_mapping);
59914c546592SDaeho Jeong 		if (err < 0) {
5992d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
59934c546592SDaeho Jeong 			return err;
59944c546592SDaeho Jeong 		}
59954c546592SDaeho Jeong 	}
59964c546592SDaeho Jeong 
5997bbd55937SEric Biggers 	percpu_down_write(&sbi->s_writepages_rwsem);
5998dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
5999ac27a0ecSDave Kleikamp 
6000ac27a0ecSDave Kleikamp 	/*
6001ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
6002ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
6003ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
6004ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
6005ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
6006ac27a0ecSDave Kleikamp 	 */
6007ac27a0ecSDave Kleikamp 
6008ac27a0ecSDave Kleikamp 	if (val)
600912e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60105872ddaaSYongqiang Yang 	else {
601101d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
60124f879ca6SJan Kara 		if (err < 0) {
60134f879ca6SJan Kara 			jbd2_journal_unlock_updates(journal);
6014bbd55937SEric Biggers 			percpu_up_write(&sbi->s_writepages_rwsem);
60154f879ca6SJan Kara 			return err;
60164f879ca6SJan Kara 		}
601712e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60185872ddaaSYongqiang Yang 	}
6019617ba13bSMingming Cao 	ext4_set_aops(inode);
6020ac27a0ecSDave Kleikamp 
6021dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
6022bbd55937SEric Biggers 	percpu_up_write(&sbi->s_writepages_rwsem);
6023c8585c6fSDaeho Jeong 
60244c546592SDaeho Jeong 	if (val)
6025d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
6026ac27a0ecSDave Kleikamp 
6027ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
6028ac27a0ecSDave Kleikamp 
60299924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6030ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
6031ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
6032ac27a0ecSDave Kleikamp 
6033aa75f4d3SHarshad Shirwadkar 	ext4_fc_mark_ineligible(inode->i_sb,
6034e85c81baSXin Yin 		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6035617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
60360390131bSFrank Mayhar 	ext4_handle_sync(handle);
6037617ba13bSMingming Cao 	ext4_journal_stop(handle);
6038617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
6039ac27a0ecSDave Kleikamp 
6040ac27a0ecSDave Kleikamp 	return err;
6041ac27a0ecSDave Kleikamp }
60422e9ee850SAneesh Kumar K.V 
6043188c299eSJan Kara static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6044188c299eSJan Kara 			    struct buffer_head *bh)
60452e9ee850SAneesh Kumar K.V {
60462e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
60472e9ee850SAneesh Kumar K.V }
60482e9ee850SAneesh Kumar K.V 
6049401b25aaSSouptick Joarder vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
60502e9ee850SAneesh Kumar K.V {
605111bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
6052c2ec175cSNick Piggin 	struct page *page = vmf->page;
60532e9ee850SAneesh Kumar K.V 	loff_t size;
60542e9ee850SAneesh Kumar K.V 	unsigned long len;
6055401b25aaSSouptick Joarder 	int err;
6056401b25aaSSouptick Joarder 	vm_fault_t ret;
60572e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
6058496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
60592e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
60609ea7df53SJan Kara 	handle_t *handle;
60619ea7df53SJan Kara 	get_block_t *get_block;
60629ea7df53SJan Kara 	int retries = 0;
60632e9ee850SAneesh Kumar K.V 
606402b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
606502b016caSTheodore Ts'o 		return VM_FAULT_SIGBUS;
606602b016caSTheodore Ts'o 
60678e8ad8a5SJan Kara 	sb_start_pagefault(inode->i_sb);
6068041bbb6dSTheodore Ts'o 	file_update_time(vma->vm_file);
6069ea3d7209SJan Kara 
6070d4f5258eSJan Kara 	filemap_invalidate_lock_shared(mapping);
60717b4cc978SEric Biggers 
6072401b25aaSSouptick Joarder 	err = ext4_convert_inline_data(inode);
6073401b25aaSSouptick Joarder 	if (err)
60747b4cc978SEric Biggers 		goto out_ret;
60757b4cc978SEric Biggers 
607664a9f144SMauricio Faria de Oliveira 	/*
607764a9f144SMauricio Faria de Oliveira 	 * On data journalling we skip straight to the transaction handle:
607864a9f144SMauricio Faria de Oliveira 	 * there's no delalloc; page truncated will be checked later; the
607964a9f144SMauricio Faria de Oliveira 	 * early return w/ all buffers mapped (calculates size/len) can't
608064a9f144SMauricio Faria de Oliveira 	 * be used; and there's no dioread_nolock, so only ext4_get_block.
608164a9f144SMauricio Faria de Oliveira 	 */
608264a9f144SMauricio Faria de Oliveira 	if (ext4_should_journal_data(inode))
608364a9f144SMauricio Faria de Oliveira 		goto retry_alloc;
608464a9f144SMauricio Faria de Oliveira 
60859ea7df53SJan Kara 	/* Delalloc case is easy... */
60869ea7df53SJan Kara 	if (test_opt(inode->i_sb, DELALLOC) &&
60879ea7df53SJan Kara 	    !ext4_nonda_switch(inode->i_sb)) {
60889ea7df53SJan Kara 		do {
6089401b25aaSSouptick Joarder 			err = block_page_mkwrite(vma, vmf,
60909ea7df53SJan Kara 						   ext4_da_get_block_prep);
6091401b25aaSSouptick Joarder 		} while (err == -ENOSPC &&
60929ea7df53SJan Kara 		       ext4_should_retry_alloc(inode->i_sb, &retries));
60939ea7df53SJan Kara 		goto out_ret;
60942e9ee850SAneesh Kumar K.V 	}
60950e499890SDarrick J. Wong 
60960e499890SDarrick J. Wong 	lock_page(page);
60979ea7df53SJan Kara 	size = i_size_read(inode);
60989ea7df53SJan Kara 	/* Page got truncated from under us? */
60999ea7df53SJan Kara 	if (page->mapping != mapping || page_offset(page) > size) {
61009ea7df53SJan Kara 		unlock_page(page);
61019ea7df53SJan Kara 		ret = VM_FAULT_NOPAGE;
61029ea7df53SJan Kara 		goto out;
61030e499890SDarrick J. Wong 	}
61042e9ee850SAneesh Kumar K.V 
610509cbfeafSKirill A. Shutemov 	if (page->index == size >> PAGE_SHIFT)
610609cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
61072e9ee850SAneesh Kumar K.V 	else
610809cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
6109a827eaffSAneesh Kumar K.V 	/*
61109ea7df53SJan Kara 	 * Return if we have all the buffers mapped. This avoids the need to do
61119ea7df53SJan Kara 	 * journal_start/journal_stop which can block and take a long time
611264a9f144SMauricio Faria de Oliveira 	 *
611364a9f144SMauricio Faria de Oliveira 	 * This cannot be done for data journalling, as we have to add the
611464a9f144SMauricio Faria de Oliveira 	 * inode to the transaction's list to writeprotect pages on commit.
6115a827eaffSAneesh Kumar K.V 	 */
61162e9ee850SAneesh Kumar K.V 	if (page_has_buffers(page)) {
6117188c299eSJan Kara 		if (!ext4_walk_page_buffers(NULL, inode, page_buffers(page),
6118f19d5870STao Ma 					    0, len, NULL,
6119a827eaffSAneesh Kumar K.V 					    ext4_bh_unmapped)) {
61209ea7df53SJan Kara 			/* Wait so that we don't change page under IO */
61211d1d1a76SDarrick J. Wong 			wait_for_stable_page(page);
61229ea7df53SJan Kara 			ret = VM_FAULT_LOCKED;
61239ea7df53SJan Kara 			goto out;
61242e9ee850SAneesh Kumar K.V 		}
6125a827eaffSAneesh Kumar K.V 	}
6126a827eaffSAneesh Kumar K.V 	unlock_page(page);
61279ea7df53SJan Kara 	/* OK, we need to fill the hole... */
61289ea7df53SJan Kara 	if (ext4_should_dioread_nolock(inode))
6129705965bdSJan Kara 		get_block = ext4_get_block_unwritten;
61309ea7df53SJan Kara 	else
61319ea7df53SJan Kara 		get_block = ext4_get_block;
61329ea7df53SJan Kara retry_alloc:
61339924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
61349924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
61359ea7df53SJan Kara 	if (IS_ERR(handle)) {
6136c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
61379ea7df53SJan Kara 		goto out;
61389ea7df53SJan Kara 	}
613964a9f144SMauricio Faria de Oliveira 	/*
614064a9f144SMauricio Faria de Oliveira 	 * Data journalling can't use block_page_mkwrite() because it
614164a9f144SMauricio Faria de Oliveira 	 * will set_buffer_dirty() before do_journal_get_write_access()
614264a9f144SMauricio Faria de Oliveira 	 * thus might hit warning messages for dirty metadata buffers.
614364a9f144SMauricio Faria de Oliveira 	 */
614464a9f144SMauricio Faria de Oliveira 	if (!ext4_should_journal_data(inode)) {
6145401b25aaSSouptick Joarder 		err = block_page_mkwrite(vma, vmf, get_block);
614664a9f144SMauricio Faria de Oliveira 	} else {
614764a9f144SMauricio Faria de Oliveira 		lock_page(page);
614864a9f144SMauricio Faria de Oliveira 		size = i_size_read(inode);
614964a9f144SMauricio Faria de Oliveira 		/* Page got truncated from under us? */
615064a9f144SMauricio Faria de Oliveira 		if (page->mapping != mapping || page_offset(page) > size) {
615164a9f144SMauricio Faria de Oliveira 			ret = VM_FAULT_NOPAGE;
6152afb585a9SMauricio Faria de Oliveira 			goto out_error;
615364a9f144SMauricio Faria de Oliveira 		}
615464a9f144SMauricio Faria de Oliveira 
615564a9f144SMauricio Faria de Oliveira 		if (page->index == size >> PAGE_SHIFT)
615664a9f144SMauricio Faria de Oliveira 			len = size & ~PAGE_MASK;
615764a9f144SMauricio Faria de Oliveira 		else
615864a9f144SMauricio Faria de Oliveira 			len = PAGE_SIZE;
615964a9f144SMauricio Faria de Oliveira 
616064a9f144SMauricio Faria de Oliveira 		err = __block_write_begin(page, 0, len, ext4_get_block);
616164a9f144SMauricio Faria de Oliveira 		if (!err) {
61629ea7df53SJan Kara 			ret = VM_FAULT_SIGBUS;
6163188c299eSJan Kara 			if (ext4_walk_page_buffers(handle, inode,
6164188c299eSJan Kara 					page_buffers(page), 0, len, NULL,
6165188c299eSJan Kara 					do_journal_get_write_access))
6166afb585a9SMauricio Faria de Oliveira 				goto out_error;
6167188c299eSJan Kara 			if (ext4_walk_page_buffers(handle, inode,
6168188c299eSJan Kara 					page_buffers(page), 0, len, NULL,
6169188c299eSJan Kara 					write_end_fn))
6170afb585a9SMauricio Faria de Oliveira 				goto out_error;
6171b5b18160SJan Kara 			if (ext4_jbd2_inode_add_write(handle, inode,
6172b5b18160SJan Kara 						      page_offset(page), len))
6173afb585a9SMauricio Faria de Oliveira 				goto out_error;
61749ea7df53SJan Kara 			ext4_set_inode_state(inode, EXT4_STATE_JDATA);
617564a9f144SMauricio Faria de Oliveira 		} else {
617664a9f144SMauricio Faria de Oliveira 			unlock_page(page);
617764a9f144SMauricio Faria de Oliveira 		}
61789ea7df53SJan Kara 	}
61799ea7df53SJan Kara 	ext4_journal_stop(handle);
6180401b25aaSSouptick Joarder 	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
61819ea7df53SJan Kara 		goto retry_alloc;
61829ea7df53SJan Kara out_ret:
6183401b25aaSSouptick Joarder 	ret = block_page_mkwrite_return(err);
61849ea7df53SJan Kara out:
6185d4f5258eSJan Kara 	filemap_invalidate_unlock_shared(mapping);
61868e8ad8a5SJan Kara 	sb_end_pagefault(inode->i_sb);
61872e9ee850SAneesh Kumar K.V 	return ret;
6188afb585a9SMauricio Faria de Oliveira out_error:
6189afb585a9SMauricio Faria de Oliveira 	unlock_page(page);
6190afb585a9SMauricio Faria de Oliveira 	ext4_journal_stop(handle);
6191afb585a9SMauricio Faria de Oliveira 	goto out;
61922e9ee850SAneesh Kumar K.V }
6193