xref: /openbmc/linux/fs/ext4/inode.c (revision bc12ac98ea2e1b70adc6478c8b473a0003b659d3)
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 
1806bc0d63dSJan Kara 	if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
1816bc0d63dSJan Kara 		ext4_evict_ea_inode(inode);
1820930fcc1SAl Viro 	if (inode->i_nlink) {
1832d859db3SJan Kara 		/*
1842d859db3SJan Kara 		 * When journalling data dirty buffers are tracked only in the
1852d859db3SJan Kara 		 * journal. So although mm thinks everything is clean and
1862d859db3SJan Kara 		 * ready for reaping the inode might still have some pages to
1872d859db3SJan Kara 		 * write in the running transaction or waiting to be
188ccd16945SMatthew Wilcox (Oracle) 		 * checkpointed. Thus calling jbd2_journal_invalidate_folio()
1892d859db3SJan Kara 		 * (via truncate_inode_pages()) to discard these buffers can
1902d859db3SJan Kara 		 * cause data loss. Also even if we did not discard these
1912d859db3SJan Kara 		 * buffers, we would have no way to find them after the inode
1922d859db3SJan Kara 		 * is reaped and thus user could see stale data if he tries to
1932d859db3SJan Kara 		 * read them before the transaction is checkpointed. So be
1942d859db3SJan Kara 		 * careful and force everything to disk here... We use
1952d859db3SJan Kara 		 * ei->i_datasync_tid to store the newest transaction
1962d859db3SJan Kara 		 * containing inode's data.
1972d859db3SJan Kara 		 *
1982d859db3SJan Kara 		 * Note that directories do not have this problem because they
1992d859db3SJan Kara 		 * don't use page cache.
2002d859db3SJan Kara 		 */
2016a7fd522SVegard Nossum 		if (inode->i_ino != EXT4_JOURNAL_INO &&
2026a7fd522SVegard Nossum 		    ext4_should_journal_data(inode) &&
2036493792dSZhang Yi 		    S_ISREG(inode->i_mode) && inode->i_data.nrpages) {
2042d859db3SJan Kara 			journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
2052d859db3SJan Kara 			tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
2062d859db3SJan Kara 
207d76a3a77STheodore Ts'o 			jbd2_complete_transaction(journal, commit_tid);
2082d859db3SJan Kara 			filemap_write_and_wait(&inode->i_data);
2092d859db3SJan Kara 		}
21091b0abe3SJohannes Weiner 		truncate_inode_pages_final(&inode->i_data);
2115dc23bddSJan Kara 
2120930fcc1SAl Viro 		goto no_delete;
2130930fcc1SAl Viro 	}
2140930fcc1SAl Viro 
215e2bfb088STheodore Ts'o 	if (is_bad_inode(inode))
216e2bfb088STheodore Ts'o 		goto no_delete;
217871a2931SChristoph Hellwig 	dquot_initialize(inode);
218907f4554SChristoph Hellwig 
219678aaf48SJan Kara 	if (ext4_should_order_data(inode))
220678aaf48SJan Kara 		ext4_begin_ordered_truncate(inode, 0);
22191b0abe3SJohannes Weiner 	truncate_inode_pages_final(&inode->i_data);
222ac27a0ecSDave Kleikamp 
2238e8ad8a5SJan Kara 	/*
224ceff86fdSJan Kara 	 * For inodes with journalled data, transaction commit could have
225*bc12ac98SZhang Yi 	 * dirtied the inode. And for inodes with dioread_nolock, unwritten
226*bc12ac98SZhang Yi 	 * extents converting worker could merge extents and also have dirtied
227*bc12ac98SZhang Yi 	 * the inode. Flush worker is ignoring it because of I_FREEING flag but
228*bc12ac98SZhang Yi 	 * we still need to remove the inode from the writeback lists.
229ceff86fdSJan Kara 	 */
230*bc12ac98SZhang Yi 	if (!list_empty_careful(&inode->i_io_list))
231ceff86fdSJan Kara 		inode_io_list_del(inode);
232ceff86fdSJan Kara 
233ceff86fdSJan Kara 	/*
2348e8ad8a5SJan Kara 	 * Protect us against freezing - iput() caller didn't have to have any
23546e294efSJan Kara 	 * protection against it. When we are in a running transaction though,
23646e294efSJan Kara 	 * we are already protected against freezing and we cannot grab further
23746e294efSJan Kara 	 * protection due to lock ordering constraints.
2388e8ad8a5SJan Kara 	 */
23946e294efSJan Kara 	if (!ext4_journal_current_handle()) {
2408e8ad8a5SJan Kara 		sb_start_intwrite(inode->i_sb);
24146e294efSJan Kara 		freeze_protected = true;
24246e294efSJan Kara 	}
243e50e5129SAndreas Dilger 
24430a7eb97STahsin Erdogan 	if (!IS_NOQUOTA(inode))
24530a7eb97STahsin Erdogan 		extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
24630a7eb97STahsin Erdogan 
24765db869cSJan Kara 	/*
24865db869cSJan Kara 	 * Block bitmap, group descriptor, and inode are accounted in both
24965db869cSJan Kara 	 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
25065db869cSJan Kara 	 */
25130a7eb97STahsin Erdogan 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
25265db869cSJan Kara 			 ext4_blocks_for_truncate(inode) + extra_credits - 3);
253ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
254bc965ab3STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
255ac27a0ecSDave Kleikamp 		/*
256ac27a0ecSDave Kleikamp 		 * If we're going to skip the normal cleanup, we still need to
257ac27a0ecSDave Kleikamp 		 * make sure that the in-core orphan linked list is properly
258ac27a0ecSDave Kleikamp 		 * cleaned up.
259ac27a0ecSDave Kleikamp 		 */
260617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
26146e294efSJan Kara 		if (freeze_protected)
2628e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
263ac27a0ecSDave Kleikamp 		goto no_delete;
264ac27a0ecSDave Kleikamp 	}
26530a7eb97STahsin Erdogan 
266ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
2670390131bSFrank Mayhar 		ext4_handle_sync(handle);
268407cd7fbSTahsin Erdogan 
269407cd7fbSTahsin Erdogan 	/*
270407cd7fbSTahsin Erdogan 	 * Set inode->i_size to 0 before calling ext4_truncate(). We need
271407cd7fbSTahsin Erdogan 	 * special handling of symlinks here because i_size is used to
272407cd7fbSTahsin Erdogan 	 * determine whether ext4_inode_info->i_data contains symlink data or
273407cd7fbSTahsin Erdogan 	 * block mappings. Setting i_size to 0 will remove its fast symlink
274407cd7fbSTahsin Erdogan 	 * status. Erase i_data so that it becomes a valid empty block map.
275407cd7fbSTahsin Erdogan 	 */
276407cd7fbSTahsin Erdogan 	if (ext4_inode_is_fast_symlink(inode))
277407cd7fbSTahsin Erdogan 		memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
278ac27a0ecSDave Kleikamp 	inode->i_size = 0;
279bc965ab3STheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
280bc965ab3STheodore Ts'o 	if (err) {
28112062dddSEric Sandeen 		ext4_warning(inode->i_sb,
282bc965ab3STheodore Ts'o 			     "couldn't mark inode dirty (err %d)", err);
283bc965ab3STheodore Ts'o 		goto stop_handle;
284bc965ab3STheodore Ts'o 	}
2852c98eb5eSTheodore Ts'o 	if (inode->i_blocks) {
2862c98eb5eSTheodore Ts'o 		err = ext4_truncate(inode);
2872c98eb5eSTheodore Ts'o 		if (err) {
28854d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err,
2892c98eb5eSTheodore Ts'o 				       "couldn't truncate inode %lu (err %d)",
2902c98eb5eSTheodore Ts'o 				       inode->i_ino, err);
2912c98eb5eSTheodore Ts'o 			goto stop_handle;
2922c98eb5eSTheodore Ts'o 		}
2932c98eb5eSTheodore Ts'o 	}
294bc965ab3STheodore Ts'o 
29530a7eb97STahsin Erdogan 	/* Remove xattr references. */
29630a7eb97STahsin Erdogan 	err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
29730a7eb97STahsin Erdogan 				      extra_credits);
29830a7eb97STahsin Erdogan 	if (err) {
29930a7eb97STahsin Erdogan 		ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
300bc965ab3STheodore Ts'o stop_handle:
301bc965ab3STheodore Ts'o 		ext4_journal_stop(handle);
30245388219STheodore Ts'o 		ext4_orphan_del(NULL, inode);
30346e294efSJan Kara 		if (freeze_protected)
3048e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
30530a7eb97STahsin Erdogan 		ext4_xattr_inode_array_free(ea_inode_array);
306bc965ab3STheodore Ts'o 		goto no_delete;
307bc965ab3STheodore Ts'o 	}
308bc965ab3STheodore Ts'o 
309ac27a0ecSDave Kleikamp 	/*
310617ba13bSMingming Cao 	 * Kill off the orphan record which ext4_truncate created.
311ac27a0ecSDave Kleikamp 	 * AKPM: I think this can be inside the above `if'.
312617ba13bSMingming Cao 	 * Note that ext4_orphan_del() has to be able to cope with the
313ac27a0ecSDave Kleikamp 	 * deletion of a non-existent orphan - this is because we don't
314617ba13bSMingming Cao 	 * know if ext4_truncate() actually created an orphan record.
315ac27a0ecSDave Kleikamp 	 * (Well, we could do this if we need to, but heck - it works)
316ac27a0ecSDave Kleikamp 	 */
317617ba13bSMingming Cao 	ext4_orphan_del(handle, inode);
3185ffff834SArnd Bergmann 	EXT4_I(inode)->i_dtime	= (__u32)ktime_get_real_seconds();
319ac27a0ecSDave Kleikamp 
320ac27a0ecSDave Kleikamp 	/*
321ac27a0ecSDave Kleikamp 	 * One subtle ordering requirement: if anything has gone wrong
322ac27a0ecSDave Kleikamp 	 * (transaction abort, IO errors, whatever), then we can still
323ac27a0ecSDave Kleikamp 	 * do these next steps (the fs will already have been marked as
324ac27a0ecSDave Kleikamp 	 * having errors), but we can't free the inode if the mark_dirty
325ac27a0ecSDave Kleikamp 	 * fails.
326ac27a0ecSDave Kleikamp 	 */
327617ba13bSMingming Cao 	if (ext4_mark_inode_dirty(handle, inode))
328ac27a0ecSDave Kleikamp 		/* If that failed, just do the required in-core inode clear. */
3290930fcc1SAl Viro 		ext4_clear_inode(inode);
330ac27a0ecSDave Kleikamp 	else
331617ba13bSMingming Cao 		ext4_free_inode(handle, inode);
332617ba13bSMingming Cao 	ext4_journal_stop(handle);
33346e294efSJan Kara 	if (freeze_protected)
3348e8ad8a5SJan Kara 		sb_end_intwrite(inode->i_sb);
3350421a189STahsin Erdogan 	ext4_xattr_inode_array_free(ea_inode_array);
336ac27a0ecSDave Kleikamp 	return;
337ac27a0ecSDave Kleikamp no_delete:
338b21ebf14SHarshad Shirwadkar 	if (!list_empty(&EXT4_I(inode)->i_fc_list))
339e85c81baSXin Yin 		ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
3400930fcc1SAl Viro 	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
341ac27a0ecSDave Kleikamp }
342ac27a0ecSDave Kleikamp 
343a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
344a9e7f447SDmitry Monakhov qsize_t *ext4_get_reserved_space(struct inode *inode)
34560e58e0fSMingming Cao {
346a9e7f447SDmitry Monakhov 	return &EXT4_I(inode)->i_reserved_quota;
34760e58e0fSMingming Cao }
348a9e7f447SDmitry Monakhov #endif
3499d0be502STheodore Ts'o 
35012219aeaSAneesh Kumar K.V /*
3510637c6f4STheodore Ts'o  * Called with i_data_sem down, which is important since we can call
3520637c6f4STheodore Ts'o  * ext4_discard_preallocations() from here.
3530637c6f4STheodore Ts'o  */
3545f634d06SAneesh Kumar K.V void ext4_da_update_reserve_space(struct inode *inode,
3555f634d06SAneesh Kumar K.V 					int used, int quota_claim)
35612219aeaSAneesh Kumar K.V {
35712219aeaSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3580637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
35912219aeaSAneesh Kumar K.V 
3600637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
361d8990240SAditya Kali 	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
3620637c6f4STheodore Ts'o 	if (unlikely(used > ei->i_reserved_data_blocks)) {
3638de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
3641084f252STheodore Ts'o 			 "with only %d reserved data blocks",
3650637c6f4STheodore Ts'o 			 __func__, inode->i_ino, used,
3660637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
3670637c6f4STheodore Ts'o 		WARN_ON(1);
3680637c6f4STheodore Ts'o 		used = ei->i_reserved_data_blocks;
3696bc6e63fSAneesh Kumar K.V 	}
37012219aeaSAneesh Kumar K.V 
3710637c6f4STheodore Ts'o 	/* Update per-inode reservations */
3720637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= used;
37371d4f7d0STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
3740637c6f4STheodore Ts'o 
375f9505c72Schenyichong 	spin_unlock(&ei->i_block_reservation_lock);
37660e58e0fSMingming Cao 
37772b8ab9dSEric Sandeen 	/* Update quota subsystem for data blocks */
37872b8ab9dSEric Sandeen 	if (quota_claim)
3797b415bf6SAditya Kali 		dquot_claim_block(inode, EXT4_C2B(sbi, used));
38072b8ab9dSEric Sandeen 	else {
3815f634d06SAneesh Kumar K.V 		/*
3825f634d06SAneesh Kumar K.V 		 * We did fallocate with an offset that is already delayed
3835f634d06SAneesh Kumar K.V 		 * allocated. So on delayed allocated writeback we should
38472b8ab9dSEric Sandeen 		 * not re-claim the quota for fallocated blocks.
3855f634d06SAneesh Kumar K.V 		 */
3867b415bf6SAditya Kali 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
3875f634d06SAneesh Kumar K.V 	}
388d6014301SAneesh Kumar K.V 
389d6014301SAneesh Kumar K.V 	/*
390d6014301SAneesh Kumar K.V 	 * If we have done all the pending block allocations and if
391d6014301SAneesh Kumar K.V 	 * there aren't any writers on the inode, we can discard the
392d6014301SAneesh Kumar K.V 	 * inode's preallocations.
393d6014301SAneesh Kumar K.V 	 */
3940637c6f4STheodore Ts'o 	if ((ei->i_reserved_data_blocks == 0) &&
39582dd124cSNikolay Borisov 	    !inode_is_open_for_write(inode))
39627bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
39712219aeaSAneesh Kumar K.V }
39812219aeaSAneesh Kumar K.V 
399e29136f8STheodore Ts'o static int __check_block_validity(struct inode *inode, const char *func,
400c398eda0STheodore Ts'o 				unsigned int line,
40124676da4STheodore Ts'o 				struct ext4_map_blocks *map)
4026fd058f7STheodore Ts'o {
403345c0dbfSTheodore Ts'o 	if (ext4_has_feature_journal(inode->i_sb) &&
404345c0dbfSTheodore Ts'o 	    (inode->i_ino ==
405345c0dbfSTheodore Ts'o 	     le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
406345c0dbfSTheodore Ts'o 		return 0;
407ce9f24ccSJan Kara 	if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
408c398eda0STheodore Ts'o 		ext4_error_inode(inode, func, line, map->m_pblk,
409bdbd6ce0STheodore Ts'o 				 "lblock %lu mapped to illegal pblock %llu "
41024676da4STheodore Ts'o 				 "(length %d)", (unsigned long) map->m_lblk,
411bdbd6ce0STheodore Ts'o 				 map->m_pblk, map->m_len);
4126a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4136fd058f7STheodore Ts'o 	}
4146fd058f7STheodore Ts'o 	return 0;
4156fd058f7STheodore Ts'o }
4166fd058f7STheodore Ts'o 
41753085facSJan Kara int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
41853085facSJan Kara 		       ext4_lblk_t len)
41953085facSJan Kara {
42053085facSJan Kara 	int ret;
42153085facSJan Kara 
42233b4cc25SEric Biggers 	if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
423a7550b30SJaegeuk Kim 		return fscrypt_zeroout_range(inode, lblk, pblk, len);
42453085facSJan Kara 
42553085facSJan Kara 	ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
42653085facSJan Kara 	if (ret > 0)
42753085facSJan Kara 		ret = 0;
42853085facSJan Kara 
42953085facSJan Kara 	return ret;
43053085facSJan Kara }
43153085facSJan Kara 
432e29136f8STheodore Ts'o #define check_block_validity(inode, map)	\
433c398eda0STheodore Ts'o 	__check_block_validity((inode), __func__, __LINE__, (map))
434e29136f8STheodore Ts'o 
435921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
436921f266bSDmitry Monakhov static void ext4_map_blocks_es_recheck(handle_t *handle,
437921f266bSDmitry Monakhov 				       struct inode *inode,
438921f266bSDmitry Monakhov 				       struct ext4_map_blocks *es_map,
439921f266bSDmitry Monakhov 				       struct ext4_map_blocks *map,
440921f266bSDmitry Monakhov 				       int flags)
441921f266bSDmitry Monakhov {
442921f266bSDmitry Monakhov 	int retval;
443921f266bSDmitry Monakhov 
444921f266bSDmitry Monakhov 	map->m_flags = 0;
445921f266bSDmitry Monakhov 	/*
446921f266bSDmitry Monakhov 	 * There is a race window that the result is not the same.
447921f266bSDmitry Monakhov 	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
448921f266bSDmitry Monakhov 	 * is that we lookup a block mapping in extent status tree with
449921f266bSDmitry Monakhov 	 * out taking i_data_sem.  So at the time the unwritten extent
450921f266bSDmitry Monakhov 	 * could be converted.
451921f266bSDmitry Monakhov 	 */
452c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
453921f266bSDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4549e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
455921f266bSDmitry Monakhov 	} else {
4569e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
457921f266bSDmitry Monakhov 	}
458921f266bSDmitry Monakhov 	up_read((&EXT4_I(inode)->i_data_sem));
459921f266bSDmitry Monakhov 
460921f266bSDmitry Monakhov 	/*
461921f266bSDmitry Monakhov 	 * We don't check m_len because extent will be collpased in status
462921f266bSDmitry Monakhov 	 * tree.  So the m_len might not equal.
463921f266bSDmitry Monakhov 	 */
464921f266bSDmitry Monakhov 	if (es_map->m_lblk != map->m_lblk ||
465921f266bSDmitry Monakhov 	    es_map->m_flags != map->m_flags ||
466921f266bSDmitry Monakhov 	    es_map->m_pblk != map->m_pblk) {
467bdafe42aSTheodore Ts'o 		printk("ES cache assertion failed for inode: %lu "
468921f266bSDmitry Monakhov 		       "es_cached ex [%d/%d/%llu/%x] != "
469921f266bSDmitry Monakhov 		       "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
470921f266bSDmitry Monakhov 		       inode->i_ino, es_map->m_lblk, es_map->m_len,
471921f266bSDmitry Monakhov 		       es_map->m_pblk, es_map->m_flags, map->m_lblk,
472921f266bSDmitry Monakhov 		       map->m_len, map->m_pblk, map->m_flags,
473921f266bSDmitry Monakhov 		       retval, flags);
474921f266bSDmitry Monakhov 	}
475921f266bSDmitry Monakhov }
476921f266bSDmitry Monakhov #endif /* ES_AGGRESSIVE_TEST */
477921f266bSDmitry Monakhov 
47855138e0bSTheodore Ts'o /*
479e35fd660STheodore Ts'o  * The ext4_map_blocks() function tries to look up the requested blocks,
4802b2d6d01STheodore Ts'o  * and returns if the blocks are already mapped.
481f5ab0d1fSMingming Cao  *
482f5ab0d1fSMingming Cao  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
483f5ab0d1fSMingming Cao  * and store the allocated blocks in the result buffer head and mark it
484f5ab0d1fSMingming Cao  * mapped.
485f5ab0d1fSMingming Cao  *
486e35fd660STheodore Ts'o  * If file type is extents based, it will call ext4_ext_map_blocks(),
487e35fd660STheodore Ts'o  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
488f5ab0d1fSMingming Cao  * based files
489f5ab0d1fSMingming Cao  *
490facab4d9SJan Kara  * On success, it returns the number of blocks being mapped or allocated.  if
491facab4d9SJan Kara  * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
492facab4d9SJan Kara  * is marked as unwritten. If the create == 1, it will mark @map as mapped.
493f5ab0d1fSMingming Cao  *
494f5ab0d1fSMingming Cao  * It returns 0 if plain look up failed (blocks have not been allocated), in
495facab4d9SJan Kara  * that case, @map is returned as unmapped but we still do fill map->m_len to
496facab4d9SJan Kara  * indicate the length of a hole starting at map->m_lblk.
497f5ab0d1fSMingming Cao  *
498f5ab0d1fSMingming Cao  * It returns the error in case of allocation failure.
499f5ab0d1fSMingming Cao  */
500e35fd660STheodore Ts'o int ext4_map_blocks(handle_t *handle, struct inode *inode,
501e35fd660STheodore Ts'o 		    struct ext4_map_blocks *map, int flags)
5020e855ac8SAneesh Kumar K.V {
503d100eef2SZheng Liu 	struct extent_status es;
5040e855ac8SAneesh Kumar K.V 	int retval;
505b8a86845SLukas Czerner 	int ret = 0;
506921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
507921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
508921f266bSDmitry Monakhov 
509921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
510921f266bSDmitry Monakhov #endif
511f5ab0d1fSMingming Cao 
512e35fd660STheodore Ts'o 	map->m_flags = 0;
51370aa1554SRitesh Harjani 	ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
51470aa1554SRitesh Harjani 		  flags, map->m_len, (unsigned long) map->m_lblk);
515d100eef2SZheng Liu 
516e861b5e9STheodore Ts'o 	/*
517e861b5e9STheodore Ts'o 	 * ext4_map_blocks returns an int, and m_len is an unsigned int
518e861b5e9STheodore Ts'o 	 */
519e861b5e9STheodore Ts'o 	if (unlikely(map->m_len > INT_MAX))
520e861b5e9STheodore Ts'o 		map->m_len = INT_MAX;
521e861b5e9STheodore Ts'o 
5224adb6ab3SKazuya Mio 	/* We can handle the block number less than EXT_MAX_BLOCKS */
5234adb6ab3SKazuya Mio 	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
5246a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
5254adb6ab3SKazuya Mio 
526d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
5278016e29fSHarshad Shirwadkar 	if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
5288016e29fSHarshad Shirwadkar 	    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
529d100eef2SZheng Liu 		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
530d100eef2SZheng Liu 			map->m_pblk = ext4_es_pblock(&es) +
531d100eef2SZheng Liu 					map->m_lblk - es.es_lblk;
532d100eef2SZheng Liu 			map->m_flags |= ext4_es_is_written(&es) ?
533d100eef2SZheng Liu 					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
534d100eef2SZheng Liu 			retval = es.es_len - (map->m_lblk - es.es_lblk);
535d100eef2SZheng Liu 			if (retval > map->m_len)
536d100eef2SZheng Liu 				retval = map->m_len;
537d100eef2SZheng Liu 			map->m_len = retval;
538d100eef2SZheng Liu 		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
539facab4d9SJan Kara 			map->m_pblk = 0;
540facab4d9SJan Kara 			retval = es.es_len - (map->m_lblk - es.es_lblk);
541facab4d9SJan Kara 			if (retval > map->m_len)
542facab4d9SJan Kara 				retval = map->m_len;
543facab4d9SJan Kara 			map->m_len = retval;
544d100eef2SZheng Liu 			retval = 0;
545d100eef2SZheng Liu 		} else {
5461e83bc81SArnd Bergmann 			BUG();
547d100eef2SZheng Liu 		}
5489558cf14SZhang Yi 
5499558cf14SZhang Yi 		if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5509558cf14SZhang Yi 			return retval;
551921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
552921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(handle, inode, map,
553921f266bSDmitry Monakhov 					   &orig_map, flags);
554921f266bSDmitry Monakhov #endif
555d100eef2SZheng Liu 		goto found;
556d100eef2SZheng Liu 	}
5579558cf14SZhang Yi 	/*
5589558cf14SZhang Yi 	 * In the query cache no-wait mode, nothing we can do more if we
5599558cf14SZhang Yi 	 * cannot find extent in the cache.
5609558cf14SZhang Yi 	 */
5619558cf14SZhang Yi 	if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5629558cf14SZhang Yi 		return 0;
563d100eef2SZheng Liu 
5644df3d265SAneesh Kumar K.V 	/*
565b920c755STheodore Ts'o 	 * Try to see if we can get the block without requesting a new
566b920c755STheodore Ts'o 	 * file system block.
5674df3d265SAneesh Kumar K.V 	 */
568c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
56912e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5709e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
5714df3d265SAneesh Kumar K.V 	} else {
5729e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
5730e855ac8SAneesh Kumar K.V 	}
574f7fec032SZheng Liu 	if (retval > 0) {
5753be78c73STheodore Ts'o 		unsigned int status;
576f7fec032SZheng Liu 
57744fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
57844fb851dSZheng Liu 			ext4_warning(inode->i_sb,
57944fb851dSZheng Liu 				     "ES len assertion failed for inode "
58044fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
58144fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
58244fb851dSZheng Liu 			WARN_ON(1);
583921f266bSDmitry Monakhov 		}
584921f266bSDmitry Monakhov 
585f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
586f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
587f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
588d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
589ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
590f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
591f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
592f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk,
593f7fec032SZheng Liu 					    map->m_len, map->m_pblk, status);
594f7fec032SZheng Liu 		if (ret < 0)
595f7fec032SZheng Liu 			retval = ret;
596f7fec032SZheng Liu 	}
5974df3d265SAneesh Kumar K.V 	up_read((&EXT4_I(inode)->i_data_sem));
598f5ab0d1fSMingming Cao 
599d100eef2SZheng Liu found:
600e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
601b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
6026fd058f7STheodore Ts'o 		if (ret != 0)
6036fd058f7STheodore Ts'o 			return ret;
6046fd058f7STheodore Ts'o 	}
6056fd058f7STheodore Ts'o 
606f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
607c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
6084df3d265SAneesh Kumar K.V 		return retval;
6094df3d265SAneesh Kumar K.V 
6104df3d265SAneesh Kumar K.V 	/*
611f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
612f5ab0d1fSMingming Cao 	 *
613f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
614df3ab170STao Ma 	 * ext4_ext_get_block() returns the create = 0
615f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
616f5ab0d1fSMingming Cao 	 */
617e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
618b8a86845SLukas Czerner 		/*
619b8a86845SLukas Czerner 		 * If we need to convert extent to unwritten
620b8a86845SLukas Czerner 		 * we continue and do the actual work in
621b8a86845SLukas Czerner 		 * ext4_ext_map_blocks()
622b8a86845SLukas Czerner 		 */
623b8a86845SLukas Czerner 		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
624f5ab0d1fSMingming Cao 			return retval;
625f5ab0d1fSMingming Cao 
626f5ab0d1fSMingming Cao 	/*
627a25a4e1aSZheng Liu 	 * Here we clear m_flags because after allocating an new extent,
628a25a4e1aSZheng Liu 	 * it will be set again.
6292a8964d6SAneesh Kumar K.V 	 */
630a25a4e1aSZheng Liu 	map->m_flags &= ~EXT4_MAP_FLAGS;
6312a8964d6SAneesh Kumar K.V 
6322a8964d6SAneesh Kumar K.V 	/*
633556615dcSLukas Czerner 	 * New blocks allocate and/or writing to unwritten extent
634f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
635d91bd2c1SSeunghun Lee 	 * the write lock of i_data_sem, and call get_block()
636f5ab0d1fSMingming Cao 	 * with create == 1 flag.
6374df3d265SAneesh Kumar K.V 	 */
638c8b459f4SLukas Czerner 	down_write(&EXT4_I(inode)->i_data_sem);
639d2a17637SMingming Cao 
640d2a17637SMingming Cao 	/*
6414df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
6424df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
6434df3d265SAneesh Kumar K.V 	 */
64412e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
645e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
6460e855ac8SAneesh Kumar K.V 	} else {
647e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
648267e4db9SAneesh Kumar K.V 
649e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
650267e4db9SAneesh Kumar K.V 			/*
651267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
652267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
653267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
654267e4db9SAneesh Kumar K.V 			 */
65519f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
656267e4db9SAneesh Kumar K.V 		}
6572ac3b6e0STheodore Ts'o 
658d2a17637SMingming Cao 		/*
6592ac3b6e0STheodore Ts'o 		 * Update reserved blocks/metadata blocks after successful
6605f634d06SAneesh Kumar K.V 		 * block allocation which had been deferred till now. We don't
6615f634d06SAneesh Kumar K.V 		 * support fallocate for non extent files. So we can update
6625f634d06SAneesh Kumar K.V 		 * reserve space here.
663d2a17637SMingming Cao 		 */
6645f634d06SAneesh Kumar K.V 		if ((retval > 0) &&
6651296cc85SAneesh Kumar K.V 			(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
6665f634d06SAneesh Kumar K.V 			ext4_da_update_reserve_space(inode, retval, 1);
6675f634d06SAneesh Kumar K.V 	}
668d2a17637SMingming Cao 
669f7fec032SZheng Liu 	if (retval > 0) {
6703be78c73STheodore Ts'o 		unsigned int status;
671f7fec032SZheng Liu 
67244fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
67344fb851dSZheng Liu 			ext4_warning(inode->i_sb,
67444fb851dSZheng Liu 				     "ES len assertion failed for inode "
67544fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
67644fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
67744fb851dSZheng Liu 			WARN_ON(1);
678921f266bSDmitry Monakhov 		}
679921f266bSDmitry Monakhov 
680adb23551SZheng Liu 		/*
681c86d8db3SJan Kara 		 * We have to zeroout blocks before inserting them into extent
682c86d8db3SJan Kara 		 * status tree. Otherwise someone could look them up there and
6839b623df6SJan Kara 		 * use them before they are really zeroed. We also have to
6849b623df6SJan Kara 		 * unmap metadata before zeroing as otherwise writeback can
6859b623df6SJan Kara 		 * overwrite zeros with stale data from block device.
686c86d8db3SJan Kara 		 */
687c86d8db3SJan Kara 		if (flags & EXT4_GET_BLOCKS_ZERO &&
688c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_MAPPED &&
689c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_NEW) {
690c86d8db3SJan Kara 			ret = ext4_issue_zeroout(inode, map->m_lblk,
691c86d8db3SJan Kara 						 map->m_pblk, map->m_len);
692c86d8db3SJan Kara 			if (ret) {
693c86d8db3SJan Kara 				retval = ret;
694c86d8db3SJan Kara 				goto out_sem;
695c86d8db3SJan Kara 			}
696c86d8db3SJan Kara 		}
697c86d8db3SJan Kara 
698c86d8db3SJan Kara 		/*
699adb23551SZheng Liu 		 * If the extent has been zeroed out, we don't need to update
700adb23551SZheng Liu 		 * extent status tree.
701adb23551SZheng Liu 		 */
702adb23551SZheng Liu 		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
703bb5835edSTheodore Ts'o 		    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
704adb23551SZheng Liu 			if (ext4_es_is_written(&es))
705c86d8db3SJan Kara 				goto out_sem;
706adb23551SZheng Liu 		}
707f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
708f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
709f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
710d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
711ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
712f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
713f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
714f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
715f7fec032SZheng Liu 					    map->m_pblk, status);
716c86d8db3SJan Kara 		if (ret < 0) {
71751865fdaSZheng Liu 			retval = ret;
718c86d8db3SJan Kara 			goto out_sem;
719c86d8db3SJan Kara 		}
72051865fdaSZheng Liu 	}
7215356f261SAditya Kali 
722c86d8db3SJan Kara out_sem:
7230e855ac8SAneesh Kumar K.V 	up_write((&EXT4_I(inode)->i_data_sem));
724e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
725b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
7266fd058f7STheodore Ts'o 		if (ret != 0)
7276fd058f7STheodore Ts'o 			return ret;
72806bd3c36SJan Kara 
72906bd3c36SJan Kara 		/*
73006bd3c36SJan Kara 		 * Inodes with freshly allocated blocks where contents will be
73106bd3c36SJan Kara 		 * visible after transaction commit must be on transaction's
73206bd3c36SJan Kara 		 * ordered data list.
73306bd3c36SJan Kara 		 */
73406bd3c36SJan Kara 		if (map->m_flags & EXT4_MAP_NEW &&
73506bd3c36SJan Kara 		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
73606bd3c36SJan Kara 		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
73702749a4cSTahsin Erdogan 		    !ext4_is_quota_file(inode) &&
73806bd3c36SJan Kara 		    ext4_should_order_data(inode)) {
73973131fbbSRoss Zwisler 			loff_t start_byte =
74073131fbbSRoss Zwisler 				(loff_t)map->m_lblk << inode->i_blkbits;
74173131fbbSRoss Zwisler 			loff_t length = (loff_t)map->m_len << inode->i_blkbits;
74273131fbbSRoss Zwisler 
743ee0876bcSJan Kara 			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
74473131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_wait(handle, inode,
74573131fbbSRoss Zwisler 						start_byte, length);
746ee0876bcSJan Kara 			else
74773131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_write(handle, inode,
74873131fbbSRoss Zwisler 						start_byte, length);
74906bd3c36SJan Kara 			if (ret)
75006bd3c36SJan Kara 				return ret;
75106bd3c36SJan Kara 		}
7525e4d0ebaSXin Yin 	}
7535e4d0ebaSXin Yin 	if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
7545e4d0ebaSXin Yin 				map->m_flags & EXT4_MAP_MAPPED))
755a80f7fcfSHarshad Shirwadkar 		ext4_fc_track_range(handle, inode, map->m_lblk,
756aa75f4d3SHarshad Shirwadkar 					map->m_lblk + map->m_len - 1);
757ec8c60beSRitesh Harjani 	if (retval < 0)
75870aa1554SRitesh Harjani 		ext_debug(inode, "failed with err %d\n", retval);
7590e855ac8SAneesh Kumar K.V 	return retval;
7600e855ac8SAneesh Kumar K.V }
7610e855ac8SAneesh Kumar K.V 
762ed8ad838SJan Kara /*
763ed8ad838SJan Kara  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
764ed8ad838SJan Kara  * we have to be careful as someone else may be manipulating b_state as well.
765ed8ad838SJan Kara  */
766ed8ad838SJan Kara static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
767ed8ad838SJan Kara {
768ed8ad838SJan Kara 	unsigned long old_state;
769ed8ad838SJan Kara 	unsigned long new_state;
770ed8ad838SJan Kara 
771ed8ad838SJan Kara 	flags &= EXT4_MAP_FLAGS;
772ed8ad838SJan Kara 
773ed8ad838SJan Kara 	/* Dummy buffer_head? Set non-atomically. */
774ed8ad838SJan Kara 	if (!bh->b_page) {
775ed8ad838SJan Kara 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
776ed8ad838SJan Kara 		return;
777ed8ad838SJan Kara 	}
778ed8ad838SJan Kara 	/*
779ed8ad838SJan Kara 	 * Someone else may be modifying b_state. Be careful! This is ugly but
780ed8ad838SJan Kara 	 * once we get rid of using bh as a container for mapping information
781ed8ad838SJan Kara 	 * to pass to / from get_block functions, this can go away.
782ed8ad838SJan Kara 	 */
783ed8ad838SJan Kara 	do {
784ed8ad838SJan Kara 		old_state = READ_ONCE(bh->b_state);
785ed8ad838SJan Kara 		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
786ed8ad838SJan Kara 	} while (unlikely(
787ed8ad838SJan Kara 		 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
788ed8ad838SJan Kara }
789ed8ad838SJan Kara 
7902ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
7912ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
792ac27a0ecSDave Kleikamp {
7932ed88685STheodore Ts'o 	struct ext4_map_blocks map;
794efe70c29SJan Kara 	int ret = 0;
795ac27a0ecSDave Kleikamp 
79646c7f254STao Ma 	if (ext4_has_inline_data(inode))
79746c7f254STao Ma 		return -ERANGE;
79846c7f254STao Ma 
7992ed88685STheodore Ts'o 	map.m_lblk = iblock;
8002ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
8012ed88685STheodore Ts'o 
802efe70c29SJan Kara 	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
803efe70c29SJan Kara 			      flags);
804ac27a0ecSDave Kleikamp 	if (ret > 0) {
8052ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
806ed8ad838SJan Kara 		ext4_update_bh_state(bh, map.m_flags);
8072ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
808ac27a0ecSDave Kleikamp 		ret = 0;
809547edce3SRoss Zwisler 	} else if (ret == 0) {
810547edce3SRoss Zwisler 		/* hole case, need to fill in bh->b_size */
811547edce3SRoss Zwisler 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
812ac27a0ecSDave Kleikamp 	}
813ac27a0ecSDave Kleikamp 	return ret;
814ac27a0ecSDave Kleikamp }
815ac27a0ecSDave Kleikamp 
8162ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
8172ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
8182ed88685STheodore Ts'o {
8192ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
8202ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
8212ed88685STheodore Ts'o }
8222ed88685STheodore Ts'o 
823ac27a0ecSDave Kleikamp /*
824705965bdSJan Kara  * Get block function used when preparing for buffered write if we require
825705965bdSJan Kara  * creating an unwritten extent if blocks haven't been allocated.  The extent
826705965bdSJan Kara  * will be converted to written after the IO is complete.
827705965bdSJan Kara  */
828705965bdSJan Kara int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
829705965bdSJan Kara 			     struct buffer_head *bh_result, int create)
830705965bdSJan Kara {
831705965bdSJan Kara 	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
832705965bdSJan Kara 		   inode->i_ino, create);
833705965bdSJan Kara 	return _ext4_get_block(inode, iblock, bh_result,
8348d5459c1SJan Kara 			       EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
835705965bdSJan Kara }
836705965bdSJan Kara 
837efe70c29SJan Kara /* Maximum number of blocks we map for direct IO at once. */
838efe70c29SJan Kara #define DIO_MAX_BLOCKS 4096
839efe70c29SJan Kara 
840e84dfbe2SJan Kara /*
841ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
842ac27a0ecSDave Kleikamp  */
843617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
844c5e298aeSTheodore Ts'o 				ext4_lblk_t block, int map_flags)
845ac27a0ecSDave Kleikamp {
8462ed88685STheodore Ts'o 	struct ext4_map_blocks map;
8472ed88685STheodore Ts'o 	struct buffer_head *bh;
848c5e298aeSTheodore Ts'o 	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
8499558cf14SZhang Yi 	bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
85010560082STheodore Ts'o 	int err;
851ac27a0ecSDave Kleikamp 
852837c23fbSChunguang Xu 	ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8538016e29fSHarshad Shirwadkar 		    || handle != NULL || create == 0);
8549558cf14SZhang Yi 	ASSERT(create == 0 || !nowait);
855ac27a0ecSDave Kleikamp 
8562ed88685STheodore Ts'o 	map.m_lblk = block;
8572ed88685STheodore Ts'o 	map.m_len = 1;
858c5e298aeSTheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map, map_flags);
8592ed88685STheodore Ts'o 
86010560082STheodore Ts'o 	if (err == 0)
86110560082STheodore Ts'o 		return create ? ERR_PTR(-ENOSPC) : NULL;
8622ed88685STheodore Ts'o 	if (err < 0)
86310560082STheodore Ts'o 		return ERR_PTR(err);
8642ed88685STheodore Ts'o 
8659558cf14SZhang Yi 	if (nowait)
8669558cf14SZhang Yi 		return sb_find_get_block(inode->i_sb, map.m_pblk);
8679558cf14SZhang Yi 
8682ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
86910560082STheodore Ts'o 	if (unlikely(!bh))
87010560082STheodore Ts'o 		return ERR_PTR(-ENOMEM);
8712ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
872837c23fbSChunguang Xu 		ASSERT(create != 0);
873837c23fbSChunguang Xu 		ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8748016e29fSHarshad Shirwadkar 			    || (handle != NULL));
875ac27a0ecSDave Kleikamp 
876ac27a0ecSDave Kleikamp 		/*
877ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
878ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
879ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
880617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
881ac27a0ecSDave Kleikamp 		 * problem.
882ac27a0ecSDave Kleikamp 		 */
883ac27a0ecSDave Kleikamp 		lock_buffer(bh);
884ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
885188c299eSJan Kara 		err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
886188c299eSJan Kara 						     EXT4_JTR_NONE);
88710560082STheodore Ts'o 		if (unlikely(err)) {
88810560082STheodore Ts'o 			unlock_buffer(bh);
88910560082STheodore Ts'o 			goto errout;
89010560082STheodore Ts'o 		}
89110560082STheodore Ts'o 		if (!buffer_uptodate(bh)) {
892ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
893ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
894ac27a0ecSDave Kleikamp 		}
895ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
8960390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
8970390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
89810560082STheodore Ts'o 		if (unlikely(err))
89910560082STheodore Ts'o 			goto errout;
90010560082STheodore Ts'o 	} else
901ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
902ac27a0ecSDave Kleikamp 	return bh;
90310560082STheodore Ts'o errout:
90410560082STheodore Ts'o 	brelse(bh);
90510560082STheodore Ts'o 	return ERR_PTR(err);
906ac27a0ecSDave Kleikamp }
907ac27a0ecSDave Kleikamp 
908617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
909c5e298aeSTheodore Ts'o 			       ext4_lblk_t block, int map_flags)
910ac27a0ecSDave Kleikamp {
911ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
9122d069c08Szhangyi (F) 	int ret;
913ac27a0ecSDave Kleikamp 
914c5e298aeSTheodore Ts'o 	bh = ext4_getblk(handle, inode, block, map_flags);
9151c215028STheodore Ts'o 	if (IS_ERR(bh))
916ac27a0ecSDave Kleikamp 		return bh;
9177963e5acSZhangXiaoxu 	if (!bh || ext4_buffer_uptodate(bh))
918ac27a0ecSDave Kleikamp 		return bh;
9192d069c08Szhangyi (F) 
9202d069c08Szhangyi (F) 	ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
9212d069c08Szhangyi (F) 	if (ret) {
922ac27a0ecSDave Kleikamp 		put_bh(bh);
9232d069c08Szhangyi (F) 		return ERR_PTR(ret);
9242d069c08Szhangyi (F) 	}
9252d069c08Szhangyi (F) 	return bh;
926ac27a0ecSDave Kleikamp }
927ac27a0ecSDave Kleikamp 
9289699d4f9STahsin Erdogan /* Read a contiguous batch of blocks. */
9299699d4f9STahsin Erdogan int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
9309699d4f9STahsin Erdogan 		     bool wait, struct buffer_head **bhs)
9319699d4f9STahsin Erdogan {
9329699d4f9STahsin Erdogan 	int i, err;
9339699d4f9STahsin Erdogan 
9349699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9359699d4f9STahsin Erdogan 		bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
9369699d4f9STahsin Erdogan 		if (IS_ERR(bhs[i])) {
9379699d4f9STahsin Erdogan 			err = PTR_ERR(bhs[i]);
9389699d4f9STahsin Erdogan 			bh_count = i;
9399699d4f9STahsin Erdogan 			goto out_brelse;
9409699d4f9STahsin Erdogan 		}
9419699d4f9STahsin Erdogan 	}
9429699d4f9STahsin Erdogan 
9439699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9449699d4f9STahsin Erdogan 		/* Note that NULL bhs[i] is valid because of holes. */
9452d069c08Szhangyi (F) 		if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
9462d069c08Szhangyi (F) 			ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
9479699d4f9STahsin Erdogan 
9489699d4f9STahsin Erdogan 	if (!wait)
9499699d4f9STahsin Erdogan 		return 0;
9509699d4f9STahsin Erdogan 
9519699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9529699d4f9STahsin Erdogan 		if (bhs[i])
9539699d4f9STahsin Erdogan 			wait_on_buffer(bhs[i]);
9549699d4f9STahsin Erdogan 
9559699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9569699d4f9STahsin Erdogan 		if (bhs[i] && !buffer_uptodate(bhs[i])) {
9579699d4f9STahsin Erdogan 			err = -EIO;
9589699d4f9STahsin Erdogan 			goto out_brelse;
9599699d4f9STahsin Erdogan 		}
9609699d4f9STahsin Erdogan 	}
9619699d4f9STahsin Erdogan 	return 0;
9629699d4f9STahsin Erdogan 
9639699d4f9STahsin Erdogan out_brelse:
9649699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9659699d4f9STahsin Erdogan 		brelse(bhs[i]);
9669699d4f9STahsin Erdogan 		bhs[i] = NULL;
9679699d4f9STahsin Erdogan 	}
9689699d4f9STahsin Erdogan 	return err;
9699699d4f9STahsin Erdogan }
9709699d4f9STahsin Erdogan 
971188c299eSJan Kara int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
972ac27a0ecSDave Kleikamp 			   struct buffer_head *head,
973ac27a0ecSDave Kleikamp 			   unsigned from,
974ac27a0ecSDave Kleikamp 			   unsigned to,
975ac27a0ecSDave Kleikamp 			   int *partial,
976188c299eSJan Kara 			   int (*fn)(handle_t *handle, struct inode *inode,
977ac27a0ecSDave Kleikamp 				     struct buffer_head *bh))
978ac27a0ecSDave Kleikamp {
979ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
980ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
981ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
982ac27a0ecSDave Kleikamp 	int err, ret = 0;
983ac27a0ecSDave Kleikamp 	struct buffer_head *next;
984ac27a0ecSDave Kleikamp 
985ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
986ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
987de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
988ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
989ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
990ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
991ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
992ac27a0ecSDave Kleikamp 				*partial = 1;
993ac27a0ecSDave Kleikamp 			continue;
994ac27a0ecSDave Kleikamp 		}
995188c299eSJan Kara 		err = (*fn)(handle, inode, bh);
996ac27a0ecSDave Kleikamp 		if (!ret)
997ac27a0ecSDave Kleikamp 			ret = err;
998ac27a0ecSDave Kleikamp 	}
999ac27a0ecSDave Kleikamp 	return ret;
1000ac27a0ecSDave Kleikamp }
1001ac27a0ecSDave Kleikamp 
1002ac27a0ecSDave Kleikamp /*
1003ac27a0ecSDave Kleikamp  * To preserve ordering, it is essential that the hole instantiation and
1004ac27a0ecSDave Kleikamp  * the data write be encapsulated in a single transaction.  We cannot
1005617ba13bSMingming Cao  * close off a transaction and start a new one between the ext4_get_block()
1006dab291afSMingming Cao  * and the commit_write().  So doing the jbd2_journal_start at the start of
1007ac27a0ecSDave Kleikamp  * prepare_write() is the right place.
1008ac27a0ecSDave Kleikamp  *
100936ade451SJan Kara  * Also, this function can nest inside ext4_writepage().  In that case, we
101036ade451SJan Kara  * *know* that ext4_writepage() has generated enough buffer credits to do the
101136ade451SJan Kara  * whole page.  So we won't block on the journal in that case, which is good,
101236ade451SJan Kara  * because the caller may be PF_MEMALLOC.
1013ac27a0ecSDave Kleikamp  *
1014617ba13bSMingming Cao  * By accident, ext4 can be reentered when a transaction is open via
1015ac27a0ecSDave Kleikamp  * quota file writes.  If we were to commit the transaction while thus
1016ac27a0ecSDave Kleikamp  * reentered, there can be a deadlock - we would be holding a quota
1017ac27a0ecSDave Kleikamp  * lock, and the commit would never complete if another thread had a
1018ac27a0ecSDave Kleikamp  * transaction open and was blocking on the quota lock - a ranking
1019ac27a0ecSDave Kleikamp  * violation.
1020ac27a0ecSDave Kleikamp  *
1021dab291afSMingming Cao  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1022ac27a0ecSDave Kleikamp  * will _not_ run commit under these circumstances because handle->h_ref
1023ac27a0ecSDave Kleikamp  * is elevated.  We'll still have enough credits for the tiny quotafile
1024ac27a0ecSDave Kleikamp  * write.
1025ac27a0ecSDave Kleikamp  */
1026188c299eSJan Kara int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1027ac27a0ecSDave Kleikamp 				struct buffer_head *bh)
1028ac27a0ecSDave Kleikamp {
102956d35a4cSJan Kara 	int dirty = buffer_dirty(bh);
103056d35a4cSJan Kara 	int ret;
103156d35a4cSJan Kara 
1032ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1033ac27a0ecSDave Kleikamp 		return 0;
103456d35a4cSJan Kara 	/*
1035ebdec241SChristoph Hellwig 	 * __block_write_begin() could have dirtied some buffers. Clean
103656d35a4cSJan Kara 	 * the dirty bit as jbd2_journal_get_write_access() could complain
103756d35a4cSJan Kara 	 * otherwise about fs integrity issues. Setting of the dirty bit
1038ebdec241SChristoph Hellwig 	 * by __block_write_begin() isn't a real problem here as we clear
103956d35a4cSJan Kara 	 * the bit before releasing a page lock and thus writeback cannot
104056d35a4cSJan Kara 	 * ever write the buffer.
104156d35a4cSJan Kara 	 */
104256d35a4cSJan Kara 	if (dirty)
104356d35a4cSJan Kara 		clear_buffer_dirty(bh);
10445d601255Sliang xie 	BUFFER_TRACE(bh, "get write access");
1045188c299eSJan Kara 	ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
1046188c299eSJan Kara 					    EXT4_JTR_NONE);
104756d35a4cSJan Kara 	if (!ret && dirty)
104856d35a4cSJan Kara 		ret = ext4_handle_dirty_metadata(handle, NULL, bh);
104956d35a4cSJan Kara 	return ret;
1050ac27a0ecSDave Kleikamp }
1051ac27a0ecSDave Kleikamp 
1052643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
10532058f83aSMichael Halcrow static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
10542058f83aSMichael Halcrow 				  get_block_t *get_block)
10552058f83aSMichael Halcrow {
105609cbfeafSKirill A. Shutemov 	unsigned from = pos & (PAGE_SIZE - 1);
10572058f83aSMichael Halcrow 	unsigned to = from + len;
10582058f83aSMichael Halcrow 	struct inode *inode = page->mapping->host;
10592058f83aSMichael Halcrow 	unsigned block_start, block_end;
10602058f83aSMichael Halcrow 	sector_t block;
10612058f83aSMichael Halcrow 	int err = 0;
10622058f83aSMichael Halcrow 	unsigned blocksize = inode->i_sb->s_blocksize;
10632058f83aSMichael Halcrow 	unsigned bbits;
10640b578f35SChandan Rajendra 	struct buffer_head *bh, *head, *wait[2];
10650b578f35SChandan Rajendra 	int nr_wait = 0;
10660b578f35SChandan Rajendra 	int i;
10672058f83aSMichael Halcrow 
10682058f83aSMichael Halcrow 	BUG_ON(!PageLocked(page));
106909cbfeafSKirill A. Shutemov 	BUG_ON(from > PAGE_SIZE);
107009cbfeafSKirill A. Shutemov 	BUG_ON(to > PAGE_SIZE);
10712058f83aSMichael Halcrow 	BUG_ON(from > to);
10722058f83aSMichael Halcrow 
10732058f83aSMichael Halcrow 	if (!page_has_buffers(page))
10742058f83aSMichael Halcrow 		create_empty_buffers(page, blocksize, 0);
10752058f83aSMichael Halcrow 	head = page_buffers(page);
10762058f83aSMichael Halcrow 	bbits = ilog2(blocksize);
107709cbfeafSKirill A. Shutemov 	block = (sector_t)page->index << (PAGE_SHIFT - bbits);
10782058f83aSMichael Halcrow 
10792058f83aSMichael Halcrow 	for (bh = head, block_start = 0; bh != head || !block_start;
10802058f83aSMichael Halcrow 	    block++, block_start = block_end, bh = bh->b_this_page) {
10812058f83aSMichael Halcrow 		block_end = block_start + blocksize;
10822058f83aSMichael Halcrow 		if (block_end <= from || block_start >= to) {
10832058f83aSMichael Halcrow 			if (PageUptodate(page)) {
10842058f83aSMichael Halcrow 				set_buffer_uptodate(bh);
10852058f83aSMichael Halcrow 			}
10862058f83aSMichael Halcrow 			continue;
10872058f83aSMichael Halcrow 		}
10882058f83aSMichael Halcrow 		if (buffer_new(bh))
10892058f83aSMichael Halcrow 			clear_buffer_new(bh);
10902058f83aSMichael Halcrow 		if (!buffer_mapped(bh)) {
10912058f83aSMichael Halcrow 			WARN_ON(bh->b_size != blocksize);
10922058f83aSMichael Halcrow 			err = get_block(inode, block, bh, 1);
10932058f83aSMichael Halcrow 			if (err)
10942058f83aSMichael Halcrow 				break;
10952058f83aSMichael Halcrow 			if (buffer_new(bh)) {
10962058f83aSMichael Halcrow 				if (PageUptodate(page)) {
10972058f83aSMichael Halcrow 					clear_buffer_new(bh);
10982058f83aSMichael Halcrow 					set_buffer_uptodate(bh);
10992058f83aSMichael Halcrow 					mark_buffer_dirty(bh);
11002058f83aSMichael Halcrow 					continue;
11012058f83aSMichael Halcrow 				}
11022058f83aSMichael Halcrow 				if (block_end > to || block_start < from)
11032058f83aSMichael Halcrow 					zero_user_segments(page, to, block_end,
11042058f83aSMichael Halcrow 							   block_start, from);
11052058f83aSMichael Halcrow 				continue;
11062058f83aSMichael Halcrow 			}
11072058f83aSMichael Halcrow 		}
11082058f83aSMichael Halcrow 		if (PageUptodate(page)) {
11092058f83aSMichael Halcrow 			set_buffer_uptodate(bh);
11102058f83aSMichael Halcrow 			continue;
11112058f83aSMichael Halcrow 		}
11122058f83aSMichael Halcrow 		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
11132058f83aSMichael Halcrow 		    !buffer_unwritten(bh) &&
11142058f83aSMichael Halcrow 		    (block_start < from || block_end > to)) {
11152d069c08Szhangyi (F) 			ext4_read_bh_lock(bh, 0, false);
11160b578f35SChandan Rajendra 			wait[nr_wait++] = bh;
11172058f83aSMichael Halcrow 		}
11182058f83aSMichael Halcrow 	}
11192058f83aSMichael Halcrow 	/*
11202058f83aSMichael Halcrow 	 * If we issued read requests, let them complete.
11212058f83aSMichael Halcrow 	 */
11220b578f35SChandan Rajendra 	for (i = 0; i < nr_wait; i++) {
11230b578f35SChandan Rajendra 		wait_on_buffer(wait[i]);
11240b578f35SChandan Rajendra 		if (!buffer_uptodate(wait[i]))
11252058f83aSMichael Halcrow 			err = -EIO;
11262058f83aSMichael Halcrow 	}
11277e0785fcSChandan Rajendra 	if (unlikely(err)) {
11282058f83aSMichael Halcrow 		page_zero_new_buffers(page, from, to);
11294f74d15fSEric Biggers 	} else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
11300b578f35SChandan Rajendra 		for (i = 0; i < nr_wait; i++) {
11310b578f35SChandan Rajendra 			int err2;
11320b578f35SChandan Rajendra 
11330b578f35SChandan Rajendra 			err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
11340b578f35SChandan Rajendra 								bh_offset(wait[i]));
11350b578f35SChandan Rajendra 			if (err2) {
11360b578f35SChandan Rajendra 				clear_buffer_uptodate(wait[i]);
11370b578f35SChandan Rajendra 				err = err2;
11380b578f35SChandan Rajendra 			}
11390b578f35SChandan Rajendra 		}
11407e0785fcSChandan Rajendra 	}
11417e0785fcSChandan Rajendra 
11422058f83aSMichael Halcrow 	return err;
11432058f83aSMichael Halcrow }
11442058f83aSMichael Halcrow #endif
11452058f83aSMichael Halcrow 
1146bfc1af65SNick Piggin static int ext4_write_begin(struct file *file, struct address_space *mapping,
11479d6b0cd7SMatthew Wilcox (Oracle) 			    loff_t pos, unsigned len,
1148bfc1af65SNick Piggin 			    struct page **pagep, void **fsdata)
1149ac27a0ecSDave Kleikamp {
1150bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
11511938a150SAneesh Kumar K.V 	int ret, needed_blocks;
1152ac27a0ecSDave Kleikamp 	handle_t *handle;
1153ac27a0ecSDave Kleikamp 	int retries = 0;
1154bfc1af65SNick Piggin 	struct page *page;
1155bfc1af65SNick Piggin 	pgoff_t index;
1156bfc1af65SNick Piggin 	unsigned from, to;
1157bfc1af65SNick Piggin 
11580db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
11590db1ff22STheodore Ts'o 		return -EIO;
11600db1ff22STheodore Ts'o 
11619d6b0cd7SMatthew Wilcox (Oracle) 	trace_ext4_write_begin(inode, pos, len);
11621938a150SAneesh Kumar K.V 	/*
11631938a150SAneesh Kumar K.V 	 * Reserve one block more for addition to orphan list in case
11641938a150SAneesh Kumar K.V 	 * we allocate blocks but write fails for some reason
11651938a150SAneesh Kumar K.V 	 */
11661938a150SAneesh Kumar K.V 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
116709cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
116809cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1169bfc1af65SNick Piggin 	to = from + len;
1170ac27a0ecSDave Kleikamp 
1171f19d5870STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1172f19d5870STao Ma 		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1173832ee62dSMatthew Wilcox (Oracle) 						    pagep);
1174f19d5870STao Ma 		if (ret < 0)
117547564bfbSTheodore Ts'o 			return ret;
117647564bfbSTheodore Ts'o 		if (ret == 1)
117747564bfbSTheodore Ts'o 			return 0;
1178f19d5870STao Ma 	}
1179f19d5870STao Ma 
118047564bfbSTheodore Ts'o 	/*
118147564bfbSTheodore Ts'o 	 * grab_cache_page_write_begin() can take a long time if the
118247564bfbSTheodore Ts'o 	 * system is thrashing due to memory pressure, or if the page
118347564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
118447564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
118547564bfbSTheodore Ts'o 	 * the page (if needed) without using GFP_NOFS.
118647564bfbSTheodore Ts'o 	 */
118747564bfbSTheodore Ts'o retry_grab:
1188b7446e7cSMatthew Wilcox (Oracle) 	page = grab_cache_page_write_begin(mapping, index);
118947564bfbSTheodore Ts'o 	if (!page)
119047564bfbSTheodore Ts'o 		return -ENOMEM;
1191d1052d23SJinke Han 	/*
1192d1052d23SJinke Han 	 * The same as page allocation, we prealloc buffer heads before
1193d1052d23SJinke Han 	 * starting the handle.
1194d1052d23SJinke Han 	 */
1195d1052d23SJinke Han 	if (!page_has_buffers(page))
1196d1052d23SJinke Han 		create_empty_buffers(page, inode->i_sb->s_blocksize, 0);
1197d1052d23SJinke Han 
119847564bfbSTheodore Ts'o 	unlock_page(page);
119947564bfbSTheodore Ts'o 
120047564bfbSTheodore Ts'o retry_journal:
12019924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
12027479d2b9SAndrew Morton 	if (IS_ERR(handle)) {
120309cbfeafSKirill A. Shutemov 		put_page(page);
120447564bfbSTheodore Ts'o 		return PTR_ERR(handle);
1205cf108bcaSJan Kara 	}
1206f19d5870STao Ma 
120747564bfbSTheodore Ts'o 	lock_page(page);
120847564bfbSTheodore Ts'o 	if (page->mapping != mapping) {
120947564bfbSTheodore Ts'o 		/* The page got truncated from under us */
121047564bfbSTheodore Ts'o 		unlock_page(page);
121109cbfeafSKirill A. Shutemov 		put_page(page);
1212cf108bcaSJan Kara 		ext4_journal_stop(handle);
121347564bfbSTheodore Ts'o 		goto retry_grab;
1214cf108bcaSJan Kara 	}
12157afe5aa5SDmitry Monakhov 	/* In case writeback began while the page was unlocked */
12167afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
1217cf108bcaSJan Kara 
1218643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
12192058f83aSMichael Halcrow 	if (ext4_should_dioread_nolock(inode))
12202058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
1221705965bdSJan Kara 					     ext4_get_block_unwritten);
12222058f83aSMichael Halcrow 	else
12232058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
12242058f83aSMichael Halcrow 					     ext4_get_block);
12252058f83aSMichael Halcrow #else
1226744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
1227705965bdSJan Kara 		ret = __block_write_begin(page, pos, len,
1228705965bdSJan Kara 					  ext4_get_block_unwritten);
1229744692dcSJiaying Zhang 	else
12306e1db88dSChristoph Hellwig 		ret = __block_write_begin(page, pos, len, ext4_get_block);
12312058f83aSMichael Halcrow #endif
1232bfc1af65SNick Piggin 	if (!ret && ext4_should_journal_data(inode)) {
1233188c299eSJan Kara 		ret = ext4_walk_page_buffers(handle, inode,
1234188c299eSJan Kara 					     page_buffers(page), from, to, NULL,
1235f19d5870STao Ma 					     do_journal_get_write_access);
1236b46be050SAndrey Savochkin 	}
1237bfc1af65SNick Piggin 
1238bfc1af65SNick Piggin 	if (ret) {
1239c93d8f88SEric Biggers 		bool extended = (pos + len > inode->i_size) &&
1240c93d8f88SEric Biggers 				!ext4_verity_in_progress(inode);
1241c93d8f88SEric Biggers 
1242bfc1af65SNick Piggin 		unlock_page(page);
1243ae4d5372SAneesh Kumar K.V 		/*
12446e1db88dSChristoph Hellwig 		 * __block_write_begin may have instantiated a few blocks
1245ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
1246f340b3d9Shongnanli 		 * i_size_read because we hold i_rwsem.
12471938a150SAneesh Kumar K.V 		 *
12481938a150SAneesh Kumar K.V 		 * Add inode to orphan list in case we crash before
12491938a150SAneesh Kumar K.V 		 * truncate finishes
1250ae4d5372SAneesh Kumar K.V 		 */
1251c93d8f88SEric Biggers 		if (extended && ext4_can_truncate(inode))
12521938a150SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
12531938a150SAneesh Kumar K.V 
12541938a150SAneesh Kumar K.V 		ext4_journal_stop(handle);
1255c93d8f88SEric Biggers 		if (extended) {
1256b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
12571938a150SAneesh Kumar K.V 			/*
1258ffacfa7aSJan Kara 			 * If truncate failed early the inode might
12591938a150SAneesh Kumar K.V 			 * still be on the orphan list; we need to
12601938a150SAneesh Kumar K.V 			 * make sure the inode is removed from the
12611938a150SAneesh Kumar K.V 			 * orphan list in that case.
12621938a150SAneesh Kumar K.V 			 */
12631938a150SAneesh Kumar K.V 			if (inode->i_nlink)
12641938a150SAneesh Kumar K.V 				ext4_orphan_del(NULL, inode);
12651938a150SAneesh Kumar K.V 		}
1266bfc1af65SNick Piggin 
126747564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
126847564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
126947564bfbSTheodore Ts'o 			goto retry_journal;
127009cbfeafSKirill A. Shutemov 		put_page(page);
127147564bfbSTheodore Ts'o 		return ret;
127247564bfbSTheodore Ts'o 	}
127347564bfbSTheodore Ts'o 	*pagep = page;
1274ac27a0ecSDave Kleikamp 	return ret;
1275ac27a0ecSDave Kleikamp }
1276ac27a0ecSDave Kleikamp 
1277bfc1af65SNick Piggin /* For write_end() in data=journal mode */
1278188c299eSJan Kara static int write_end_fn(handle_t *handle, struct inode *inode,
1279188c299eSJan Kara 			struct buffer_head *bh)
1280ac27a0ecSDave Kleikamp {
128113fca323STheodore Ts'o 	int ret;
1282ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1283ac27a0ecSDave Kleikamp 		return 0;
1284ac27a0ecSDave Kleikamp 	set_buffer_uptodate(bh);
128513fca323STheodore Ts'o 	ret = ext4_handle_dirty_metadata(handle, NULL, bh);
128613fca323STheodore Ts'o 	clear_buffer_meta(bh);
128713fca323STheodore Ts'o 	clear_buffer_prio(bh);
128813fca323STheodore Ts'o 	return ret;
1289ac27a0ecSDave Kleikamp }
1290ac27a0ecSDave Kleikamp 
1291eed4333fSZheng Liu /*
1292eed4333fSZheng Liu  * We need to pick up the new inode size which generic_commit_write gave us
1293eed4333fSZheng Liu  * `file' can be NULL - eg, when called from page_symlink().
1294eed4333fSZheng Liu  *
1295eed4333fSZheng Liu  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1296eed4333fSZheng Liu  * buffers are managed internally.
1297eed4333fSZheng Liu  */
1298eed4333fSZheng Liu static int ext4_write_end(struct file *file,
1299f8514083SAneesh Kumar K.V 			  struct address_space *mapping,
1300f8514083SAneesh Kumar K.V 			  loff_t pos, unsigned len, unsigned copied,
1301f8514083SAneesh Kumar K.V 			  struct page *page, void *fsdata)
1302f8514083SAneesh Kumar K.V {
1303f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
1304eed4333fSZheng Liu 	struct inode *inode = mapping->host;
13050572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1306eed4333fSZheng Liu 	int ret = 0, ret2;
1307eed4333fSZheng Liu 	int i_size_changed = 0;
1308c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1309eed4333fSZheng Liu 
1310eed4333fSZheng Liu 	trace_ext4_write_end(inode, pos, len, copied);
13116984aef5SZhang Yi 
13126984aef5SZhang Yi 	if (ext4_has_inline_data(inode))
13136984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
13146984aef5SZhang Yi 
13156984aef5SZhang Yi 	copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1316f8514083SAneesh Kumar K.V 	/*
13174631dbf6SDmitry Monakhov 	 * it's important to update i_size while still holding page lock:
1318f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
1319c93d8f88SEric Biggers 	 *
1320c93d8f88SEric Biggers 	 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1321c93d8f88SEric Biggers 	 * blocks are being written past EOF, so skip the i_size update.
1322f8514083SAneesh Kumar K.V 	 */
1323c93d8f88SEric Biggers 	if (!verity)
13244631dbf6SDmitry Monakhov 		i_size_changed = ext4_update_inode_size(inode, pos + copied);
1325f8514083SAneesh Kumar K.V 	unlock_page(page);
132609cbfeafSKirill A. Shutemov 	put_page(page);
1327f8514083SAneesh Kumar K.V 
1328c93d8f88SEric Biggers 	if (old_size < pos && !verity)
13290572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
1330f8514083SAneesh Kumar K.V 	/*
1331f8514083SAneesh Kumar K.V 	 * Don't mark the inode dirty under page lock. First, it unnecessarily
1332f8514083SAneesh Kumar K.V 	 * makes the holding time of page lock longer. Second, it forces lock
1333f8514083SAneesh Kumar K.V 	 * ordering of page lock and transaction start for journaling
1334f8514083SAneesh Kumar K.V 	 * filesystems.
1335f8514083SAneesh Kumar K.V 	 */
13366984aef5SZhang Yi 	if (i_size_changed)
13374209ae12SHarshad Shirwadkar 		ret = ext4_mark_inode_dirty(handle, inode);
1338f8514083SAneesh Kumar K.V 
1339c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1340f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1341f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1342f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1343f8514083SAneesh Kumar K.V 		 */
1344f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
134555ce2f64SZhang Yi 
1346617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1347ac27a0ecSDave Kleikamp 	if (!ret)
1348ac27a0ecSDave Kleikamp 		ret = ret2;
1349bfc1af65SNick Piggin 
1350c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1351b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1352f8514083SAneesh Kumar K.V 		/*
1353ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1354f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1355f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1356f8514083SAneesh Kumar K.V 		 */
1357f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1358f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1359f8514083SAneesh Kumar K.V 	}
1360f8514083SAneesh Kumar K.V 
1361bfc1af65SNick Piggin 	return ret ? ret : copied;
1362ac27a0ecSDave Kleikamp }
1363ac27a0ecSDave Kleikamp 
1364b90197b6STheodore Ts'o /*
1365b90197b6STheodore Ts'o  * This is a private version of page_zero_new_buffers() which doesn't
1366b90197b6STheodore Ts'o  * set the buffer to be dirty, since in data=journalled mode we need
1367b90197b6STheodore Ts'o  * to call ext4_handle_dirty_metadata() instead.
1368b90197b6STheodore Ts'o  */
13693b136499SJan Kara static void ext4_journalled_zero_new_buffers(handle_t *handle,
1370188c299eSJan Kara 					    struct inode *inode,
13713b136499SJan Kara 					    struct page *page,
13723b136499SJan Kara 					    unsigned from, unsigned to)
1373b90197b6STheodore Ts'o {
1374b90197b6STheodore Ts'o 	unsigned int block_start = 0, block_end;
1375b90197b6STheodore Ts'o 	struct buffer_head *head, *bh;
1376b90197b6STheodore Ts'o 
1377b90197b6STheodore Ts'o 	bh = head = page_buffers(page);
1378b90197b6STheodore Ts'o 	do {
1379b90197b6STheodore Ts'o 		block_end = block_start + bh->b_size;
1380b90197b6STheodore Ts'o 		if (buffer_new(bh)) {
1381b90197b6STheodore Ts'o 			if (block_end > from && block_start < to) {
1382b90197b6STheodore Ts'o 				if (!PageUptodate(page)) {
1383b90197b6STheodore Ts'o 					unsigned start, size;
1384b90197b6STheodore Ts'o 
1385b90197b6STheodore Ts'o 					start = max(from, block_start);
1386b90197b6STheodore Ts'o 					size = min(to, block_end) - start;
1387b90197b6STheodore Ts'o 
1388b90197b6STheodore Ts'o 					zero_user(page, start, size);
1389188c299eSJan Kara 					write_end_fn(handle, inode, bh);
1390b90197b6STheodore Ts'o 				}
1391b90197b6STheodore Ts'o 				clear_buffer_new(bh);
1392b90197b6STheodore Ts'o 			}
1393b90197b6STheodore Ts'o 		}
1394b90197b6STheodore Ts'o 		block_start = block_end;
1395b90197b6STheodore Ts'o 		bh = bh->b_this_page;
1396b90197b6STheodore Ts'o 	} while (bh != head);
1397b90197b6STheodore Ts'o }
1398b90197b6STheodore Ts'o 
1399bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
1400bfc1af65SNick Piggin 				     struct address_space *mapping,
1401bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
1402bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
1403ac27a0ecSDave Kleikamp {
1404617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1405bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
14060572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1407ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1408ac27a0ecSDave Kleikamp 	int partial = 0;
1409bfc1af65SNick Piggin 	unsigned from, to;
14104631dbf6SDmitry Monakhov 	int size_changed = 0;
1411c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1412ac27a0ecSDave Kleikamp 
14139bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
141409cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1415bfc1af65SNick Piggin 	to = from + len;
1416bfc1af65SNick Piggin 
1417441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1418441c8508SCurt Wohlgemuth 
14196984aef5SZhang Yi 	if (ext4_has_inline_data(inode))
14206984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
14216984aef5SZhang Yi 
14226984aef5SZhang Yi 	if (unlikely(copied < len) && !PageUptodate(page)) {
1423bfc1af65SNick Piggin 		copied = 0;
1424188c299eSJan Kara 		ext4_journalled_zero_new_buffers(handle, inode, page, from, to);
14253b136499SJan Kara 	} else {
14263b136499SJan Kara 		if (unlikely(copied < len))
1427188c299eSJan Kara 			ext4_journalled_zero_new_buffers(handle, inode, page,
14283b136499SJan Kara 							 from + copied, to);
1429188c299eSJan Kara 		ret = ext4_walk_page_buffers(handle, inode, page_buffers(page),
1430188c299eSJan Kara 					     from, from + copied, &partial,
14313b136499SJan Kara 					     write_end_fn);
1432ac27a0ecSDave Kleikamp 		if (!partial)
1433ac27a0ecSDave Kleikamp 			SetPageUptodate(page);
14343fdcfb66STao Ma 	}
1435c93d8f88SEric Biggers 	if (!verity)
14364631dbf6SDmitry Monakhov 		size_changed = ext4_update_inode_size(inode, pos + copied);
143719f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
14382d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
14394631dbf6SDmitry Monakhov 	unlock_page(page);
144009cbfeafSKirill A. Shutemov 	put_page(page);
14414631dbf6SDmitry Monakhov 
1442c93d8f88SEric Biggers 	if (old_size < pos && !verity)
14430572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
14440572639fSXiaoguang Wang 
14456984aef5SZhang Yi 	if (size_changed) {
1446617ba13bSMingming Cao 		ret2 = ext4_mark_inode_dirty(handle, inode);
1447ac27a0ecSDave Kleikamp 		if (!ret)
1448ac27a0ecSDave Kleikamp 			ret = ret2;
1449ac27a0ecSDave Kleikamp 	}
1450bfc1af65SNick Piggin 
1451c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1452f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1453f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1454f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1455f8514083SAneesh Kumar K.V 		 */
1456f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1457f8514083SAneesh Kumar K.V 
1458617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1459ac27a0ecSDave Kleikamp 	if (!ret)
1460ac27a0ecSDave Kleikamp 		ret = ret2;
1461c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1462b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1463f8514083SAneesh Kumar K.V 		/*
1464ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1465f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1466f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1467f8514083SAneesh Kumar K.V 		 */
1468f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1469f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1470f8514083SAneesh Kumar K.V 	}
1471bfc1af65SNick Piggin 
1472bfc1af65SNick Piggin 	return ret ? ret : copied;
1473ac27a0ecSDave Kleikamp }
1474d2a17637SMingming Cao 
14759d0be502STheodore Ts'o /*
1476c27e43a1SEric Whitney  * Reserve space for a single cluster
14779d0be502STheodore Ts'o  */
1478c27e43a1SEric Whitney static int ext4_da_reserve_space(struct inode *inode)
1479d2a17637SMingming Cao {
1480d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
14810637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
14825dd4056dSChristoph Hellwig 	int ret;
1483d2a17637SMingming Cao 
148460e58e0fSMingming Cao 	/*
148572b8ab9dSEric Sandeen 	 * We will charge metadata quota at writeout time; this saves
148672b8ab9dSEric Sandeen 	 * us from metadata over-estimation, though we may go over by
148772b8ab9dSEric Sandeen 	 * a small amount in the end.  Here we just reserve for data.
148860e58e0fSMingming Cao 	 */
14897b415bf6SAditya Kali 	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
14905dd4056dSChristoph Hellwig 	if (ret)
14915dd4056dSChristoph Hellwig 		return ret;
149203179fe9STheodore Ts'o 
149303179fe9STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
149471d4f7d0STheodore Ts'o 	if (ext4_claim_free_clusters(sbi, 1, 0)) {
149503179fe9STheodore Ts'o 		spin_unlock(&ei->i_block_reservation_lock);
149603179fe9STheodore Ts'o 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1497d2a17637SMingming Cao 		return -ENOSPC;
1498d2a17637SMingming Cao 	}
14999d0be502STheodore Ts'o 	ei->i_reserved_data_blocks++;
1500c27e43a1SEric Whitney 	trace_ext4_da_reserve_space(inode);
15010637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
150239bc680aSDmitry Monakhov 
1503d2a17637SMingming Cao 	return 0;       /* success */
1504d2a17637SMingming Cao }
1505d2a17637SMingming Cao 
1506f456767dSEric Whitney void ext4_da_release_space(struct inode *inode, int to_free)
1507d2a17637SMingming Cao {
1508d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
15090637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1510d2a17637SMingming Cao 
1511cd213226SMingming Cao 	if (!to_free)
1512cd213226SMingming Cao 		return;		/* Nothing to release, exit */
1513cd213226SMingming Cao 
1514d2a17637SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1515cd213226SMingming Cao 
15165a58ec87SLi Zefan 	trace_ext4_da_release_space(inode, to_free);
15170637c6f4STheodore Ts'o 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1518cd213226SMingming Cao 		/*
15190637c6f4STheodore Ts'o 		 * if there aren't enough reserved blocks, then the
15200637c6f4STheodore Ts'o 		 * counter is messed up somewhere.  Since this
15210637c6f4STheodore Ts'o 		 * function is called from invalidate page, it's
15220637c6f4STheodore Ts'o 		 * harmless to return without any action.
1523cd213226SMingming Cao 		 */
15248de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "ext4_da_release_space: "
15250637c6f4STheodore Ts'o 			 "ino %lu, to_free %d with only %d reserved "
15261084f252STheodore Ts'o 			 "data blocks", inode->i_ino, to_free,
15270637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
15280637c6f4STheodore Ts'o 		WARN_ON(1);
15290637c6f4STheodore Ts'o 		to_free = ei->i_reserved_data_blocks;
15300637c6f4STheodore Ts'o 	}
15310637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= to_free;
15320637c6f4STheodore Ts'o 
153372b8ab9dSEric Sandeen 	/* update fs dirty data blocks counter */
153457042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1535d2a17637SMingming Cao 
1536d2a17637SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
153760e58e0fSMingming Cao 
15387b415bf6SAditya Kali 	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1539d2a17637SMingming Cao }
1540d2a17637SMingming Cao 
1541ac27a0ecSDave Kleikamp /*
154264769240SAlex Tomas  * Delayed allocation stuff
154364769240SAlex Tomas  */
154464769240SAlex Tomas 
15454e7ea81dSJan Kara struct mpage_da_data {
15464e7ea81dSJan Kara 	struct inode *inode;
15474e7ea81dSJan Kara 	struct writeback_control *wbc;
15486b523df4SJan Kara 
15494e7ea81dSJan Kara 	pgoff_t first_page;	/* The first page to write */
15504e7ea81dSJan Kara 	pgoff_t next_page;	/* Current page to examine */
15514e7ea81dSJan Kara 	pgoff_t last_page;	/* Last page to examine */
155264769240SAlex Tomas 	/*
15534e7ea81dSJan Kara 	 * Extent to map - this can be after first_page because that can be
15544e7ea81dSJan Kara 	 * fully mapped. We somewhat abuse m_flags to store whether the extent
15554e7ea81dSJan Kara 	 * is delalloc or unwritten.
155664769240SAlex Tomas 	 */
15574e7ea81dSJan Kara 	struct ext4_map_blocks map;
15584e7ea81dSJan Kara 	struct ext4_io_submit io_submit;	/* IO submission data */
1559dddbd6acSJan Kara 	unsigned int do_map:1;
15606b8ed620SJan Kara 	unsigned int scanned_until_end:1;
15614e7ea81dSJan Kara };
156264769240SAlex Tomas 
15634e7ea81dSJan Kara static void mpage_release_unused_pages(struct mpage_da_data *mpd,
15644e7ea81dSJan Kara 				       bool invalidate)
1565c4a0c46eSAneesh Kumar K.V {
1566fb5a5be0SMatthew Wilcox (Oracle) 	unsigned nr, i;
1567c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
1568fb5a5be0SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
1569c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1570c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
15714e7ea81dSJan Kara 
15724e7ea81dSJan Kara 	/* This is necessary when next_page == 0. */
15734e7ea81dSJan Kara 	if (mpd->first_page >= mpd->next_page)
15744e7ea81dSJan Kara 		return;
1575c4a0c46eSAneesh Kumar K.V 
15766b8ed620SJan Kara 	mpd->scanned_until_end = 0;
1577c7f5938aSCurt Wohlgemuth 	index = mpd->first_page;
1578c7f5938aSCurt Wohlgemuth 	end   = mpd->next_page - 1;
15794e7ea81dSJan Kara 	if (invalidate) {
15804e7ea81dSJan Kara 		ext4_lblk_t start, last;
158109cbfeafSKirill A. Shutemov 		start = index << (PAGE_SHIFT - inode->i_blkbits);
158209cbfeafSKirill A. Shutemov 		last = end << (PAGE_SHIFT - inode->i_blkbits);
15837f0d8e1dSEric Whitney 
15847f0d8e1dSEric Whitney 		/*
15857f0d8e1dSEric Whitney 		 * avoid racing with extent status tree scans made by
15867f0d8e1dSEric Whitney 		 * ext4_insert_delayed_block()
15877f0d8e1dSEric Whitney 		 */
15887f0d8e1dSEric Whitney 		down_write(&EXT4_I(inode)->i_data_sem);
158951865fdaSZheng Liu 		ext4_es_remove_extent(inode, start, last - start + 1);
15907f0d8e1dSEric Whitney 		up_write(&EXT4_I(inode)->i_data_sem);
15914e7ea81dSJan Kara 	}
159251865fdaSZheng Liu 
1593fb5a5be0SMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
1594c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
1595fb5a5be0SMatthew Wilcox (Oracle) 		nr = filemap_get_folios(mapping, &index, end, &fbatch);
1596fb5a5be0SMatthew Wilcox (Oracle) 		if (nr == 0)
1597c4a0c46eSAneesh Kumar K.V 			break;
1598fb5a5be0SMatthew Wilcox (Oracle) 		for (i = 0; i < nr; i++) {
1599fb5a5be0SMatthew Wilcox (Oracle) 			struct folio *folio = fbatch.folios[i];
16002b85a617SJan Kara 
1601fb5a5be0SMatthew Wilcox (Oracle) 			if (folio->index < mpd->first_page)
1602fb5a5be0SMatthew Wilcox (Oracle) 				continue;
1603fb5a5be0SMatthew Wilcox (Oracle) 			if (folio->index + folio_nr_pages(folio) - 1 > end)
1604fb5a5be0SMatthew Wilcox (Oracle) 				continue;
16057ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(!folio_test_locked(folio));
16067ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(folio_test_writeback(folio));
16074e7ea81dSJan Kara 			if (invalidate) {
16087ba13abbSMatthew Wilcox (Oracle) 				if (folio_mapped(folio))
16097ba13abbSMatthew Wilcox (Oracle) 					folio_clear_dirty_for_io(folio);
16107ba13abbSMatthew Wilcox (Oracle) 				block_invalidate_folio(folio, 0,
16117ba13abbSMatthew Wilcox (Oracle) 						folio_size(folio));
16127ba13abbSMatthew Wilcox (Oracle) 				folio_clear_uptodate(folio);
16134e7ea81dSJan Kara 			}
16147ba13abbSMatthew Wilcox (Oracle) 			folio_unlock(folio);
1615c4a0c46eSAneesh Kumar K.V 		}
1616fb5a5be0SMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
1617c4a0c46eSAneesh Kumar K.V 	}
1618c4a0c46eSAneesh Kumar K.V }
1619c4a0c46eSAneesh Kumar K.V 
1620df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
1621df22291fSAneesh Kumar K.V {
1622df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
162392b97816STheodore Ts'o 	struct super_block *sb = inode->i_sb;
1624f78ee70dSLukas Czerner 	struct ext4_inode_info *ei = EXT4_I(inode);
162592b97816STheodore Ts'o 
162692b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
16275dee5437STheodore Ts'o 	       EXT4_C2B(EXT4_SB(inode->i_sb),
1628f78ee70dSLukas Czerner 			ext4_count_free_clusters(sb)));
162992b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
163092b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1631f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
163257042651STheodore Ts'o 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
163392b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1634f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
16357b415bf6SAditya Kali 		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
163692b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Block reservation details");
163792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1638f78ee70dSLukas Czerner 		 ei->i_reserved_data_blocks);
1639df22291fSAneesh Kumar K.V 	return;
1640df22291fSAneesh Kumar K.V }
1641df22291fSAneesh Kumar K.V 
1642188c299eSJan Kara static int ext4_bh_delay_or_unwritten(handle_t *handle, struct inode *inode,
1643188c299eSJan Kara 				      struct buffer_head *bh)
164429fa89d0SAneesh Kumar K.V {
1645c364b22cSAneesh Kumar K.V 	return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
164629fa89d0SAneesh Kumar K.V }
164729fa89d0SAneesh Kumar K.V 
164864769240SAlex Tomas /*
16490b02f4c0SEric Whitney  * ext4_insert_delayed_block - adds a delayed block to the extents status
16500b02f4c0SEric Whitney  *                             tree, incrementing the reserved cluster/block
16510b02f4c0SEric Whitney  *                             count or making a pending reservation
16520b02f4c0SEric Whitney  *                             where needed
16530b02f4c0SEric Whitney  *
16540b02f4c0SEric Whitney  * @inode - file containing the newly added block
16550b02f4c0SEric Whitney  * @lblk - logical block to be added
16560b02f4c0SEric Whitney  *
16570b02f4c0SEric Whitney  * Returns 0 on success, negative error code on failure.
16580b02f4c0SEric Whitney  */
16590b02f4c0SEric Whitney static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
16600b02f4c0SEric Whitney {
16610b02f4c0SEric Whitney 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
16620b02f4c0SEric Whitney 	int ret;
16630b02f4c0SEric Whitney 	bool allocated = false;
16646fed8395SJeffle Xu 	bool reserved = false;
16650b02f4c0SEric Whitney 
16660b02f4c0SEric Whitney 	/*
16670b02f4c0SEric Whitney 	 * If the cluster containing lblk is shared with a delayed,
16680b02f4c0SEric Whitney 	 * written, or unwritten extent in a bigalloc file system, it's
16690b02f4c0SEric Whitney 	 * already been accounted for and does not need to be reserved.
16700b02f4c0SEric Whitney 	 * A pending reservation must be made for the cluster if it's
16710b02f4c0SEric Whitney 	 * shared with a written or unwritten extent and doesn't already
16720b02f4c0SEric Whitney 	 * have one.  Written and unwritten extents can be purged from the
16730b02f4c0SEric Whitney 	 * extents status tree if the system is under memory pressure, so
16740b02f4c0SEric Whitney 	 * it's necessary to examine the extent tree if a search of the
16750b02f4c0SEric Whitney 	 * extents status tree doesn't get a match.
16760b02f4c0SEric Whitney 	 */
16770b02f4c0SEric Whitney 	if (sbi->s_cluster_ratio == 1) {
16780b02f4c0SEric Whitney 		ret = ext4_da_reserve_space(inode);
16790b02f4c0SEric Whitney 		if (ret != 0)   /* ENOSPC */
16800b02f4c0SEric Whitney 			goto errout;
16816fed8395SJeffle Xu 		reserved = true;
16820b02f4c0SEric Whitney 	} else {   /* bigalloc */
16830b02f4c0SEric Whitney 		if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
16840b02f4c0SEric Whitney 			if (!ext4_es_scan_clu(inode,
16850b02f4c0SEric Whitney 					      &ext4_es_is_mapped, lblk)) {
16860b02f4c0SEric Whitney 				ret = ext4_clu_mapped(inode,
16870b02f4c0SEric Whitney 						      EXT4_B2C(sbi, lblk));
16880b02f4c0SEric Whitney 				if (ret < 0)
16890b02f4c0SEric Whitney 					goto errout;
16900b02f4c0SEric Whitney 				if (ret == 0) {
16910b02f4c0SEric Whitney 					ret = ext4_da_reserve_space(inode);
16920b02f4c0SEric Whitney 					if (ret != 0)   /* ENOSPC */
16930b02f4c0SEric Whitney 						goto errout;
16946fed8395SJeffle Xu 					reserved = true;
16950b02f4c0SEric Whitney 				} else {
16960b02f4c0SEric Whitney 					allocated = true;
16970b02f4c0SEric Whitney 				}
16980b02f4c0SEric Whitney 			} else {
16990b02f4c0SEric Whitney 				allocated = true;
17000b02f4c0SEric Whitney 			}
17010b02f4c0SEric Whitney 		}
17020b02f4c0SEric Whitney 	}
17030b02f4c0SEric Whitney 
17040b02f4c0SEric Whitney 	ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
17056fed8395SJeffle Xu 	if (ret && reserved)
17066fed8395SJeffle Xu 		ext4_da_release_space(inode, 1);
17070b02f4c0SEric Whitney 
17080b02f4c0SEric Whitney errout:
17090b02f4c0SEric Whitney 	return ret;
17100b02f4c0SEric Whitney }
17110b02f4c0SEric Whitney 
17120b02f4c0SEric Whitney /*
17135356f261SAditya Kali  * This function is grabs code from the very beginning of
17145356f261SAditya Kali  * ext4_map_blocks, but assumes that the caller is from delayed write
17155356f261SAditya Kali  * time. This function looks up the requested blocks and sets the
17165356f261SAditya Kali  * buffer delay bit under the protection of i_data_sem.
17175356f261SAditya Kali  */
17185356f261SAditya Kali static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
17195356f261SAditya Kali 			      struct ext4_map_blocks *map,
17205356f261SAditya Kali 			      struct buffer_head *bh)
17215356f261SAditya Kali {
1722d100eef2SZheng Liu 	struct extent_status es;
17235356f261SAditya Kali 	int retval;
17245356f261SAditya Kali 	sector_t invalid_block = ~((sector_t) 0xffff);
1725921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1726921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
1727921f266bSDmitry Monakhov 
1728921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
1729921f266bSDmitry Monakhov #endif
17305356f261SAditya Kali 
17315356f261SAditya Kali 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
17325356f261SAditya Kali 		invalid_block = ~0;
17335356f261SAditya Kali 
17345356f261SAditya Kali 	map->m_flags = 0;
173570aa1554SRitesh Harjani 	ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
17365356f261SAditya Kali 		  (unsigned long) map->m_lblk);
1737d100eef2SZheng Liu 
1738d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
1739bb5835edSTheodore Ts'o 	if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1740d100eef2SZheng Liu 		if (ext4_es_is_hole(&es)) {
1741d100eef2SZheng Liu 			retval = 0;
1742c8b459f4SLukas Czerner 			down_read(&EXT4_I(inode)->i_data_sem);
1743d100eef2SZheng Liu 			goto add_delayed;
1744d100eef2SZheng Liu 		}
1745d100eef2SZheng Liu 
1746d100eef2SZheng Liu 		/*
17473eda41dfSEric Whitney 		 * Delayed extent could be allocated by fallocate.
17483eda41dfSEric Whitney 		 * So we need to check it.
1749d100eef2SZheng Liu 		 */
17503eda41dfSEric Whitney 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
17513eda41dfSEric Whitney 			map_bh(bh, inode->i_sb, invalid_block);
17523eda41dfSEric Whitney 			set_buffer_new(bh);
17533eda41dfSEric Whitney 			set_buffer_delay(bh);
1754d100eef2SZheng Liu 			return 0;
1755d100eef2SZheng Liu 		}
1756d100eef2SZheng Liu 
1757d100eef2SZheng Liu 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1758d100eef2SZheng Liu 		retval = es.es_len - (iblock - es.es_lblk);
1759d100eef2SZheng Liu 		if (retval > map->m_len)
1760d100eef2SZheng Liu 			retval = map->m_len;
1761d100eef2SZheng Liu 		map->m_len = retval;
1762d100eef2SZheng Liu 		if (ext4_es_is_written(&es))
1763d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_MAPPED;
1764d100eef2SZheng Liu 		else if (ext4_es_is_unwritten(&es))
1765d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1766d100eef2SZheng Liu 		else
17671e83bc81SArnd Bergmann 			BUG();
1768d100eef2SZheng Liu 
1769921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1770921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1771921f266bSDmitry Monakhov #endif
1772d100eef2SZheng Liu 		return retval;
1773d100eef2SZheng Liu 	}
1774d100eef2SZheng Liu 
17755356f261SAditya Kali 	/*
17765356f261SAditya Kali 	 * Try to see if we can get the block without requesting a new
17775356f261SAditya Kali 	 * file system block.
17785356f261SAditya Kali 	 */
1779c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
1780cbd7584eSJan Kara 	if (ext4_has_inline_data(inode))
17819c3569b5STao Ma 		retval = 0;
1782cbd7584eSJan Kara 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
17832f8e0a7cSZheng Liu 		retval = ext4_ext_map_blocks(NULL, inode, map, 0);
17845356f261SAditya Kali 	else
17852f8e0a7cSZheng Liu 		retval = ext4_ind_map_blocks(NULL, inode, map, 0);
17865356f261SAditya Kali 
1787d100eef2SZheng Liu add_delayed:
17885356f261SAditya Kali 	if (retval == 0) {
1789f7fec032SZheng Liu 		int ret;
1790ad431025SEric Whitney 
17915356f261SAditya Kali 		/*
17925356f261SAditya Kali 		 * XXX: __block_prepare_write() unmaps passed block,
17935356f261SAditya Kali 		 * is it OK?
17945356f261SAditya Kali 		 */
17955356f261SAditya Kali 
17960b02f4c0SEric Whitney 		ret = ext4_insert_delayed_block(inode, map->m_lblk);
17970b02f4c0SEric Whitney 		if (ret != 0) {
1798f7fec032SZheng Liu 			retval = ret;
179951865fdaSZheng Liu 			goto out_unlock;
1800f7fec032SZheng Liu 		}
180151865fdaSZheng Liu 
18025356f261SAditya Kali 		map_bh(bh, inode->i_sb, invalid_block);
18035356f261SAditya Kali 		set_buffer_new(bh);
18045356f261SAditya Kali 		set_buffer_delay(bh);
1805f7fec032SZheng Liu 	} else if (retval > 0) {
1806f7fec032SZheng Liu 		int ret;
18073be78c73STheodore Ts'o 		unsigned int status;
1808f7fec032SZheng Liu 
180944fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
181044fb851dSZheng Liu 			ext4_warning(inode->i_sb,
181144fb851dSZheng Liu 				     "ES len assertion failed for inode "
181244fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
181344fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
181444fb851dSZheng Liu 			WARN_ON(1);
1815921f266bSDmitry Monakhov 		}
1816921f266bSDmitry Monakhov 
1817f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1818f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1819f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1820f7fec032SZheng Liu 					    map->m_pblk, status);
1821f7fec032SZheng Liu 		if (ret != 0)
1822f7fec032SZheng Liu 			retval = ret;
18235356f261SAditya Kali 	}
18245356f261SAditya Kali 
18255356f261SAditya Kali out_unlock:
18265356f261SAditya Kali 	up_read((&EXT4_I(inode)->i_data_sem));
18275356f261SAditya Kali 
18285356f261SAditya Kali 	return retval;
18295356f261SAditya Kali }
18305356f261SAditya Kali 
18315356f261SAditya Kali /*
1832d91bd2c1SSeunghun Lee  * This is a special get_block_t callback which is used by
1833b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
1834b920c755STheodore Ts'o  * reserve space for a single block.
183529fa89d0SAneesh Kumar K.V  *
183629fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
183729fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
183829fa89d0SAneesh Kumar K.V  *
183929fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
184029fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
184129fa89d0SAneesh Kumar K.V  * initialized properly.
184264769240SAlex Tomas  */
18439c3569b5STao Ma int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
18442ed88685STheodore Ts'o 			   struct buffer_head *bh, int create)
184564769240SAlex Tomas {
18462ed88685STheodore Ts'o 	struct ext4_map_blocks map;
184764769240SAlex Tomas 	int ret = 0;
184864769240SAlex Tomas 
184964769240SAlex Tomas 	BUG_ON(create == 0);
18502ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
18512ed88685STheodore Ts'o 
18522ed88685STheodore Ts'o 	map.m_lblk = iblock;
18532ed88685STheodore Ts'o 	map.m_len = 1;
185464769240SAlex Tomas 
185564769240SAlex Tomas 	/*
185664769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
185764769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
185864769240SAlex Tomas 	 * the same as allocated blocks.
185964769240SAlex Tomas 	 */
18605356f261SAditya Kali 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
18615356f261SAditya Kali 	if (ret <= 0)
18622ed88685STheodore Ts'o 		return ret;
186364769240SAlex Tomas 
18642ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
1865ed8ad838SJan Kara 	ext4_update_bh_state(bh, map.m_flags);
18662ed88685STheodore Ts'o 
18672ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
18682ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
18692ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
18702ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
18712ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
18722ed88685STheodore Ts'o 		 * for partial write.
18732ed88685STheodore Ts'o 		 */
18742ed88685STheodore Ts'o 		set_buffer_new(bh);
1875c8205636STheodore Ts'o 		set_buffer_mapped(bh);
18762ed88685STheodore Ts'o 	}
18772ed88685STheodore Ts'o 	return 0;
187864769240SAlex Tomas }
187961628a3fSMingming Cao 
188062e086beSAneesh Kumar K.V static int __ext4_journalled_writepage(struct page *page,
188162e086beSAneesh Kumar K.V 				       unsigned int len)
188262e086beSAneesh Kumar K.V {
188362e086beSAneesh Kumar K.V 	struct address_space *mapping = page->mapping;
188462e086beSAneesh Kumar K.V 	struct inode *inode = mapping->host;
188562e086beSAneesh Kumar K.V 	handle_t *handle = NULL;
18863fdcfb66STao Ma 	int ret = 0, err = 0;
18873fdcfb66STao Ma 	int inline_data = ext4_has_inline_data(inode);
18883fdcfb66STao Ma 	struct buffer_head *inode_bh = NULL;
18895c48a7dfSZhang Yi 	loff_t size;
189062e086beSAneesh Kumar K.V 
1891cb20d518STheodore Ts'o 	ClearPageChecked(page);
18923fdcfb66STao Ma 
18933fdcfb66STao Ma 	if (inline_data) {
18943fdcfb66STao Ma 		BUG_ON(page->index != 0);
18953fdcfb66STao Ma 		BUG_ON(len > ext4_get_max_inline_size(inode));
18963fdcfb66STao Ma 		inode_bh = ext4_journalled_write_inline_data(inode, len, page);
18973fdcfb66STao Ma 		if (inode_bh == NULL)
18983fdcfb66STao Ma 			goto out;
18993fdcfb66STao Ma 	}
1900bdf96838STheodore Ts'o 	/*
1901bdf96838STheodore Ts'o 	 * We need to release the page lock before we start the
1902bdf96838STheodore Ts'o 	 * journal, so grab a reference so the page won't disappear
1903bdf96838STheodore Ts'o 	 * out from under us.
1904bdf96838STheodore Ts'o 	 */
1905bdf96838STheodore Ts'o 	get_page(page);
190662e086beSAneesh Kumar K.V 	unlock_page(page);
190762e086beSAneesh Kumar K.V 
19089924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
19099924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
191062e086beSAneesh Kumar K.V 	if (IS_ERR(handle)) {
191162e086beSAneesh Kumar K.V 		ret = PTR_ERR(handle);
1912bdf96838STheodore Ts'o 		put_page(page);
1913bdf96838STheodore Ts'o 		goto out_no_pagelock;
1914bdf96838STheodore Ts'o 	}
1915bdf96838STheodore Ts'o 	BUG_ON(!ext4_handle_valid(handle));
1916bdf96838STheodore Ts'o 
1917bdf96838STheodore Ts'o 	lock_page(page);
1918bdf96838STheodore Ts'o 	put_page(page);
19195c48a7dfSZhang Yi 	size = i_size_read(inode);
19205c48a7dfSZhang Yi 	if (page->mapping != mapping || page_offset(page) > size) {
1921bdf96838STheodore Ts'o 		/* The page got truncated from under us */
1922bdf96838STheodore Ts'o 		ext4_journal_stop(handle);
1923bdf96838STheodore Ts'o 		ret = 0;
192462e086beSAneesh Kumar K.V 		goto out;
192562e086beSAneesh Kumar K.V 	}
192662e086beSAneesh Kumar K.V 
19273fdcfb66STao Ma 	if (inline_data) {
1928362eca70STheodore Ts'o 		ret = ext4_mark_inode_dirty(handle, inode);
19293fdcfb66STao Ma 	} else {
19305c48a7dfSZhang Yi 		struct buffer_head *page_bufs = page_buffers(page);
19315c48a7dfSZhang Yi 
19325c48a7dfSZhang Yi 		if (page->index == size >> PAGE_SHIFT)
19335c48a7dfSZhang Yi 			len = size & ~PAGE_MASK;
19345c48a7dfSZhang Yi 		else
19355c48a7dfSZhang Yi 			len = PAGE_SIZE;
19365c48a7dfSZhang Yi 
1937188c299eSJan Kara 		ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1938188c299eSJan Kara 					     NULL, do_journal_get_write_access);
193962e086beSAneesh Kumar K.V 
1940188c299eSJan Kara 		err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1941188c299eSJan Kara 					     NULL, write_end_fn);
19423fdcfb66STao Ma 	}
194362e086beSAneesh Kumar K.V 	if (ret == 0)
194462e086beSAneesh Kumar K.V 		ret = err;
1945b5b18160SJan Kara 	err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
1946afb585a9SMauricio Faria de Oliveira 	if (ret == 0)
1947afb585a9SMauricio Faria de Oliveira 		ret = err;
19482d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
194962e086beSAneesh Kumar K.V 	err = ext4_journal_stop(handle);
195062e086beSAneesh Kumar K.V 	if (!ret)
195162e086beSAneesh Kumar K.V 		ret = err;
195262e086beSAneesh Kumar K.V 
195319f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
195462e086beSAneesh Kumar K.V out:
1955bdf96838STheodore Ts'o 	unlock_page(page);
1956bdf96838STheodore Ts'o out_no_pagelock:
19573fdcfb66STao Ma 	brelse(inode_bh);
195862e086beSAneesh Kumar K.V 	return ret;
195962e086beSAneesh Kumar K.V }
196062e086beSAneesh Kumar K.V 
196161628a3fSMingming Cao /*
196243ce1d23SAneesh Kumar K.V  * Note that we don't need to start a transaction unless we're journaling data
196343ce1d23SAneesh Kumar K.V  * because we should have holes filled from ext4_page_mkwrite(). We even don't
196443ce1d23SAneesh Kumar K.V  * need to file the inode to the transaction's list in ordered mode because if
196543ce1d23SAneesh Kumar K.V  * we are writing back data added by write(), the inode is already there and if
196643ce1d23SAneesh Kumar K.V  * we are writing back data modified via mmap(), no one guarantees in which
196743ce1d23SAneesh Kumar K.V  * transaction the data will hit the disk. In case we are journaling data, we
196843ce1d23SAneesh Kumar K.V  * cannot start transaction directly because transaction start ranks above page
196943ce1d23SAneesh Kumar K.V  * lock so we have to do some magic.
197043ce1d23SAneesh Kumar K.V  *
1971b920c755STheodore Ts'o  * This function can get called via...
197220970ba6STheodore Ts'o  *   - ext4_writepages after taking page lock (have journal handle)
1973b920c755STheodore Ts'o  *   - journal_submit_inode_data_buffers (no journal handle)
1974f6463b0dSArtem Bityutskiy  *   - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1975b920c755STheodore Ts'o  *   - grab_page_cache when doing write_begin (have journal handle)
197643ce1d23SAneesh Kumar K.V  *
197743ce1d23SAneesh Kumar K.V  * We don't do any block allocation in this function. If we have page with
197843ce1d23SAneesh Kumar K.V  * multiple blocks we need to write those buffer_heads that are mapped. This
197943ce1d23SAneesh Kumar K.V  * is important for mmaped based write. So if we do with blocksize 1K
198043ce1d23SAneesh Kumar K.V  * truncate(f, 1024);
198143ce1d23SAneesh Kumar K.V  * a = mmap(f, 0, 4096);
198243ce1d23SAneesh Kumar K.V  * a[0] = 'a';
198343ce1d23SAneesh Kumar K.V  * truncate(f, 4096);
198443ce1d23SAneesh Kumar K.V  * we have in the page first buffer_head mapped via page_mkwrite call back
198590802ed9SPaul Bolle  * but other buffer_heads would be unmapped but dirty (dirty done via the
198643ce1d23SAneesh Kumar K.V  * do_wp_page). So writepage should write the first block. If we modify
198743ce1d23SAneesh Kumar K.V  * the mmap area beyond 1024 we will again get a page_fault and the
198843ce1d23SAneesh Kumar K.V  * page_mkwrite callback will do the block allocation and mark the
198943ce1d23SAneesh Kumar K.V  * buffer_heads mapped.
199043ce1d23SAneesh Kumar K.V  *
199143ce1d23SAneesh Kumar K.V  * We redirty the page if we have any buffer_heads that is either delay or
199243ce1d23SAneesh Kumar K.V  * unwritten in the page.
199343ce1d23SAneesh Kumar K.V  *
199443ce1d23SAneesh Kumar K.V  * We can get recursively called as show below.
199543ce1d23SAneesh Kumar K.V  *
199643ce1d23SAneesh Kumar K.V  *	ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
199743ce1d23SAneesh Kumar K.V  *		ext4_writepage()
199843ce1d23SAneesh Kumar K.V  *
199943ce1d23SAneesh Kumar K.V  * But since we don't do any block allocation we should not deadlock.
200043ce1d23SAneesh Kumar K.V  * Page also have the dirty flag cleared so we don't get recurive page_lock.
200161628a3fSMingming Cao  */
200243ce1d23SAneesh Kumar K.V static int ext4_writepage(struct page *page,
200364769240SAlex Tomas 			  struct writeback_control *wbc)
200464769240SAlex Tomas {
2005020df9baSMatthew Wilcox (Oracle) 	struct folio *folio = page_folio(page);
2006f8bec370SJan Kara 	int ret = 0;
200761628a3fSMingming Cao 	loff_t size;
2008498e5f24STheodore Ts'o 	unsigned int len;
2009744692dcSJiaying Zhang 	struct buffer_head *page_bufs = NULL;
201061628a3fSMingming Cao 	struct inode *inode = page->mapping->host;
201136ade451SJan Kara 	struct ext4_io_submit io_submit;
20121c8349a1SNamjae Jeon 	bool keep_towrite = false;
201364769240SAlex Tomas 
20140db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
2015020df9baSMatthew Wilcox (Oracle) 		folio_invalidate(folio, 0, folio_size(folio));
2016020df9baSMatthew Wilcox (Oracle) 		folio_unlock(folio);
20170db1ff22STheodore Ts'o 		return -EIO;
20180db1ff22STheodore Ts'o 	}
20190db1ff22STheodore Ts'o 
2020a9c667f8SLukas Czerner 	trace_ext4_writepage(page);
202161628a3fSMingming Cao 	size = i_size_read(inode);
2022c93d8f88SEric Biggers 	if (page->index == size >> PAGE_SHIFT &&
2023c93d8f88SEric Biggers 	    !ext4_verity_in_progress(inode))
202409cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
202561628a3fSMingming Cao 	else
202609cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
202761628a3fSMingming Cao 
2028cc509574STheodore Ts'o 	/* Should never happen but for bugs in other kernel subsystems */
2029cc509574STheodore Ts'o 	if (!page_has_buffers(page)) {
2030cc509574STheodore Ts'o 		ext4_warning_inode(inode,
2031cc509574STheodore Ts'o 		   "page %lu does not have buffers attached", page->index);
2032cc509574STheodore Ts'o 		ClearPageDirty(page);
2033cc509574STheodore Ts'o 		unlock_page(page);
2034cc509574STheodore Ts'o 		return 0;
2035cc509574STheodore Ts'o 	}
2036cc509574STheodore Ts'o 
2037f0e6c985SAneesh Kumar K.V 	page_bufs = page_buffers(page);
203864769240SAlex Tomas 	/*
2039fe386132SJan Kara 	 * We cannot do block allocation or other extent handling in this
2040fe386132SJan Kara 	 * function. If there are buffers needing that, we have to redirty
2041fe386132SJan Kara 	 * the page. But we may reach here when we do a journal commit via
2042fe386132SJan Kara 	 * journal_submit_inode_data_buffers() and in that case we must write
2043fe386132SJan Kara 	 * allocated buffers to achieve data=ordered mode guarantees.
2044cccd147aSTheodore Ts'o 	 *
2045cccd147aSTheodore Ts'o 	 * Also, if there is only one buffer per page (the fs block
2046cccd147aSTheodore Ts'o 	 * size == the page size), if one buffer needs block
2047cccd147aSTheodore Ts'o 	 * allocation or needs to modify the extent tree to clear the
2048cccd147aSTheodore Ts'o 	 * unwritten flag, we know that the page can't be written at
2049cccd147aSTheodore Ts'o 	 * all, so we might as well refuse the write immediately.
2050cccd147aSTheodore Ts'o 	 * Unfortunately if the block size != page size, we can't as
2051cccd147aSTheodore Ts'o 	 * easily detect this case using ext4_walk_page_buffers(), but
2052cccd147aSTheodore Ts'o 	 * for the extremely common case, this is an optimization that
2053cccd147aSTheodore Ts'o 	 * skips a useless round trip through ext4_bio_write_page().
205464769240SAlex Tomas 	 */
2055188c299eSJan Kara 	if (ext4_walk_page_buffers(NULL, inode, page_bufs, 0, len, NULL,
2056c364b22cSAneesh Kumar K.V 				   ext4_bh_delay_or_unwritten)) {
205761628a3fSMingming Cao 		redirty_page_for_writepage(wbc, page);
2058cccd147aSTheodore Ts'o 		if ((current->flags & PF_MEMALLOC) ||
205909cbfeafSKirill A. Shutemov 		    (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2060fe386132SJan Kara 			/*
2061fe386132SJan Kara 			 * For memory cleaning there's no point in writing only
2062fe386132SJan Kara 			 * some buffers. So just bail out. Warn if we came here
2063fe386132SJan Kara 			 * from direct reclaim.
2064fe386132SJan Kara 			 */
2065fe386132SJan Kara 			WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2066fe386132SJan Kara 							== PF_MEMALLOC);
206761628a3fSMingming Cao 			unlock_page(page);
206861628a3fSMingming Cao 			return 0;
206961628a3fSMingming Cao 		}
20701c8349a1SNamjae Jeon 		keep_towrite = true;
2071f0e6c985SAneesh Kumar K.V 	}
207264769240SAlex Tomas 
2073cb20d518STheodore Ts'o 	if (PageChecked(page) && ext4_should_journal_data(inode))
207443ce1d23SAneesh Kumar K.V 		/*
207543ce1d23SAneesh Kumar K.V 		 * It's mmapped pagecache.  Add buffers and journal it.  There
207643ce1d23SAneesh Kumar K.V 		 * doesn't seem much point in redirtying the page here.
207743ce1d23SAneesh Kumar K.V 		 */
20783f0ca309SWu Fengguang 		return __ext4_journalled_writepage(page, len);
207943ce1d23SAneesh Kumar K.V 
208097a851edSJan Kara 	ext4_io_submit_init(&io_submit, wbc);
208197a851edSJan Kara 	io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
208297a851edSJan Kara 	if (!io_submit.io_end) {
208397a851edSJan Kara 		redirty_page_for_writepage(wbc, page);
208497a851edSJan Kara 		unlock_page(page);
208597a851edSJan Kara 		return -ENOMEM;
208697a851edSJan Kara 	}
2087be993933SLei Chen 	ret = ext4_bio_write_page(&io_submit, page, len, keep_towrite);
208836ade451SJan Kara 	ext4_io_submit(&io_submit);
208997a851edSJan Kara 	/* Drop io_end reference we got from init */
209097a851edSJan Kara 	ext4_put_io_end_defer(io_submit.io_end);
209164769240SAlex Tomas 	return ret;
209264769240SAlex Tomas }
209364769240SAlex Tomas 
20945f1132b2SJan Kara static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
20955f1132b2SJan Kara {
20965f1132b2SJan Kara 	int len;
2097a056bdaaSJan Kara 	loff_t size;
20985f1132b2SJan Kara 	int err;
20995f1132b2SJan Kara 
21005f1132b2SJan Kara 	BUG_ON(page->index != mpd->first_page);
2101a056bdaaSJan Kara 	clear_page_dirty_for_io(page);
2102a056bdaaSJan Kara 	/*
2103a056bdaaSJan Kara 	 * We have to be very careful here!  Nothing protects writeback path
2104a056bdaaSJan Kara 	 * against i_size changes and the page can be writeably mapped into
2105a056bdaaSJan Kara 	 * page tables. So an application can be growing i_size and writing
2106a056bdaaSJan Kara 	 * data through mmap while writeback runs. clear_page_dirty_for_io()
2107a056bdaaSJan Kara 	 * write-protects our page in page tables and the page cannot get
2108a056bdaaSJan Kara 	 * written to again until we release page lock. So only after
2109a056bdaaSJan Kara 	 * clear_page_dirty_for_io() we are safe to sample i_size for
2110a056bdaaSJan Kara 	 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2111a056bdaaSJan Kara 	 * on the barrier provided by TestClearPageDirty in
2112a056bdaaSJan Kara 	 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2113a056bdaaSJan Kara 	 * after page tables are updated.
2114a056bdaaSJan Kara 	 */
2115a056bdaaSJan Kara 	size = i_size_read(mpd->inode);
2116c93d8f88SEric Biggers 	if (page->index == size >> PAGE_SHIFT &&
2117c93d8f88SEric Biggers 	    !ext4_verity_in_progress(mpd->inode))
211809cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
21195f1132b2SJan Kara 	else
212009cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
2121be993933SLei Chen 	err = ext4_bio_write_page(&mpd->io_submit, page, len, false);
21225f1132b2SJan Kara 	if (!err)
21235f1132b2SJan Kara 		mpd->wbc->nr_to_write--;
21245f1132b2SJan Kara 	mpd->first_page++;
21255f1132b2SJan Kara 
21265f1132b2SJan Kara 	return err;
21275f1132b2SJan Kara }
21285f1132b2SJan Kara 
21296db07461SRitesh Harjani #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
21304e7ea81dSJan Kara 
213161628a3fSMingming Cao /*
2132fffb2739SJan Kara  * mballoc gives us at most this number of blocks...
2133fffb2739SJan Kara  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2134fffb2739SJan Kara  * The rest of mballoc seems to handle chunks up to full group size.
213561628a3fSMingming Cao  */
2136fffb2739SJan Kara #define MAX_WRITEPAGES_EXTENT_LEN 2048
2137525f4ed8SMingming Cao 
2138525f4ed8SMingming Cao /*
21394e7ea81dSJan Kara  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
21404e7ea81dSJan Kara  *
21414e7ea81dSJan Kara  * @mpd - extent of blocks
21424e7ea81dSJan Kara  * @lblk - logical number of the block in the file
214309930042SJan Kara  * @bh - buffer head we want to add to the extent
21444e7ea81dSJan Kara  *
214509930042SJan Kara  * The function is used to collect contig. blocks in the same state. If the
214609930042SJan Kara  * buffer doesn't require mapping for writeback and we haven't started the
214709930042SJan Kara  * extent of buffers to map yet, the function returns 'true' immediately - the
214809930042SJan Kara  * caller can write the buffer right away. Otherwise the function returns true
214909930042SJan Kara  * if the block has been added to the extent, false if the block couldn't be
215009930042SJan Kara  * added.
21514e7ea81dSJan Kara  */
215209930042SJan Kara static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
215309930042SJan Kara 				   struct buffer_head *bh)
21544e7ea81dSJan Kara {
21554e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
21564e7ea81dSJan Kara 
215709930042SJan Kara 	/* Buffer that doesn't need mapping for writeback? */
215809930042SJan Kara 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
215909930042SJan Kara 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
216009930042SJan Kara 		/* So far no extent to map => we write the buffer right away */
216109930042SJan Kara 		if (map->m_len == 0)
216209930042SJan Kara 			return true;
216309930042SJan Kara 		return false;
216409930042SJan Kara 	}
21654e7ea81dSJan Kara 
21664e7ea81dSJan Kara 	/* First block in the extent? */
21674e7ea81dSJan Kara 	if (map->m_len == 0) {
2168dddbd6acSJan Kara 		/* We cannot map unless handle is started... */
2169dddbd6acSJan Kara 		if (!mpd->do_map)
2170dddbd6acSJan Kara 			return false;
21714e7ea81dSJan Kara 		map->m_lblk = lblk;
21724e7ea81dSJan Kara 		map->m_len = 1;
217309930042SJan Kara 		map->m_flags = bh->b_state & BH_FLAGS;
217409930042SJan Kara 		return true;
21754e7ea81dSJan Kara 	}
21764e7ea81dSJan Kara 
217709930042SJan Kara 	/* Don't go larger than mballoc is willing to allocate */
217809930042SJan Kara 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
217909930042SJan Kara 		return false;
218009930042SJan Kara 
21814e7ea81dSJan Kara 	/* Can we merge the block to our big extent? */
21824e7ea81dSJan Kara 	if (lblk == map->m_lblk + map->m_len &&
218309930042SJan Kara 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
21844e7ea81dSJan Kara 		map->m_len++;
218509930042SJan Kara 		return true;
21864e7ea81dSJan Kara 	}
218709930042SJan Kara 	return false;
21884e7ea81dSJan Kara }
21894e7ea81dSJan Kara 
21905f1132b2SJan Kara /*
21915f1132b2SJan Kara  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
21925f1132b2SJan Kara  *
21935f1132b2SJan Kara  * @mpd - extent of blocks for mapping
21945f1132b2SJan Kara  * @head - the first buffer in the page
21955f1132b2SJan Kara  * @bh - buffer we should start processing from
21965f1132b2SJan Kara  * @lblk - logical number of the block in the file corresponding to @bh
21975f1132b2SJan Kara  *
21985f1132b2SJan Kara  * Walk through page buffers from @bh upto @head (exclusive) and either submit
21995f1132b2SJan Kara  * the page for IO if all buffers in this page were mapped and there's no
22005f1132b2SJan Kara  * accumulated extent of buffers to map or add buffers in the page to the
22015f1132b2SJan Kara  * extent of buffers to map. The function returns 1 if the caller can continue
22025f1132b2SJan Kara  * by processing the next page, 0 if it should stop adding buffers to the
22035f1132b2SJan Kara  * extent to map because we cannot extend it anymore. It can also return value
22045f1132b2SJan Kara  * < 0 in case of error during IO submission.
22055f1132b2SJan Kara  */
22065f1132b2SJan Kara static int mpage_process_page_bufs(struct mpage_da_data *mpd,
22074e7ea81dSJan Kara 				   struct buffer_head *head,
22084e7ea81dSJan Kara 				   struct buffer_head *bh,
22094e7ea81dSJan Kara 				   ext4_lblk_t lblk)
22104e7ea81dSJan Kara {
22114e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
22125f1132b2SJan Kara 	int err;
221393407472SFabian Frederick 	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
22144e7ea81dSJan Kara 							>> inode->i_blkbits;
22154e7ea81dSJan Kara 
2216c93d8f88SEric Biggers 	if (ext4_verity_in_progress(inode))
2217c93d8f88SEric Biggers 		blocks = EXT_MAX_BLOCKS;
2218c93d8f88SEric Biggers 
22194e7ea81dSJan Kara 	do {
22204e7ea81dSJan Kara 		BUG_ON(buffer_locked(bh));
22214e7ea81dSJan Kara 
222209930042SJan Kara 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
22234e7ea81dSJan Kara 			/* Found extent to map? */
22244e7ea81dSJan Kara 			if (mpd->map.m_len)
22255f1132b2SJan Kara 				return 0;
2226dddbd6acSJan Kara 			/* Buffer needs mapping and handle is not started? */
2227dddbd6acSJan Kara 			if (!mpd->do_map)
2228dddbd6acSJan Kara 				return 0;
222909930042SJan Kara 			/* Everything mapped so far and we hit EOF */
22305f1132b2SJan Kara 			break;
22314e7ea81dSJan Kara 		}
22324e7ea81dSJan Kara 	} while (lblk++, (bh = bh->b_this_page) != head);
22335f1132b2SJan Kara 	/* So far everything mapped? Submit the page for IO. */
22345f1132b2SJan Kara 	if (mpd->map.m_len == 0) {
22355f1132b2SJan Kara 		err = mpage_submit_page(mpd, head->b_page);
22365f1132b2SJan Kara 		if (err < 0)
22374e7ea81dSJan Kara 			return err;
22384e7ea81dSJan Kara 	}
22396b8ed620SJan Kara 	if (lblk >= blocks) {
22406b8ed620SJan Kara 		mpd->scanned_until_end = 1;
22416b8ed620SJan Kara 		return 0;
22426b8ed620SJan Kara 	}
22436b8ed620SJan Kara 	return 1;
22445f1132b2SJan Kara }
22454e7ea81dSJan Kara 
22464e7ea81dSJan Kara /*
22472943fdbcSRitesh Harjani  * mpage_process_page - update page buffers corresponding to changed extent and
22482943fdbcSRitesh Harjani  *		       may submit fully mapped page for IO
22492943fdbcSRitesh Harjani  *
22502943fdbcSRitesh Harjani  * @mpd		- description of extent to map, on return next extent to map
22512943fdbcSRitesh Harjani  * @m_lblk	- logical block mapping.
22522943fdbcSRitesh Harjani  * @m_pblk	- corresponding physical mapping.
22532943fdbcSRitesh Harjani  * @map_bh	- determines on return whether this page requires any further
22542943fdbcSRitesh Harjani  *		  mapping or not.
22552943fdbcSRitesh Harjani  * Scan given page buffers corresponding to changed extent and update buffer
22562943fdbcSRitesh Harjani  * state according to new extent state.
22572943fdbcSRitesh Harjani  * We map delalloc buffers to their physical location, clear unwritten bits.
22582943fdbcSRitesh Harjani  * If the given page is not fully mapped, we update @map to the next extent in
22592943fdbcSRitesh Harjani  * the given page that needs mapping & return @map_bh as true.
22602943fdbcSRitesh Harjani  */
22612943fdbcSRitesh Harjani static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
22622943fdbcSRitesh Harjani 			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
22632943fdbcSRitesh Harjani 			      bool *map_bh)
22642943fdbcSRitesh Harjani {
22652943fdbcSRitesh Harjani 	struct buffer_head *head, *bh;
22662943fdbcSRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
22672943fdbcSRitesh Harjani 	ext4_lblk_t lblk = *m_lblk;
22682943fdbcSRitesh Harjani 	ext4_fsblk_t pblock = *m_pblk;
22692943fdbcSRitesh Harjani 	int err = 0;
2270c8cc8816SRitesh Harjani 	int blkbits = mpd->inode->i_blkbits;
2271c8cc8816SRitesh Harjani 	ssize_t io_end_size = 0;
2272c8cc8816SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
22732943fdbcSRitesh Harjani 
22742943fdbcSRitesh Harjani 	bh = head = page_buffers(page);
22752943fdbcSRitesh Harjani 	do {
22762943fdbcSRitesh Harjani 		if (lblk < mpd->map.m_lblk)
22772943fdbcSRitesh Harjani 			continue;
22782943fdbcSRitesh Harjani 		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
22792943fdbcSRitesh Harjani 			/*
22802943fdbcSRitesh Harjani 			 * Buffer after end of mapped extent.
22812943fdbcSRitesh Harjani 			 * Find next buffer in the page to map.
22822943fdbcSRitesh Harjani 			 */
22832943fdbcSRitesh Harjani 			mpd->map.m_len = 0;
22842943fdbcSRitesh Harjani 			mpd->map.m_flags = 0;
2285c8cc8816SRitesh Harjani 			io_end_vec->size += io_end_size;
22862943fdbcSRitesh Harjani 
22872943fdbcSRitesh Harjani 			err = mpage_process_page_bufs(mpd, head, bh, lblk);
22882943fdbcSRitesh Harjani 			if (err > 0)
22892943fdbcSRitesh Harjani 				err = 0;
2290c8cc8816SRitesh Harjani 			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2291c8cc8816SRitesh Harjani 				io_end_vec = ext4_alloc_io_end_vec(io_end);
22924d06bfb9SRitesh Harjani 				if (IS_ERR(io_end_vec)) {
22934d06bfb9SRitesh Harjani 					err = PTR_ERR(io_end_vec);
22944d06bfb9SRitesh Harjani 					goto out;
22954d06bfb9SRitesh Harjani 				}
2296d1e18b88SRitesh Harjani 				io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2297c8cc8816SRitesh Harjani 			}
22982943fdbcSRitesh Harjani 			*map_bh = true;
22992943fdbcSRitesh Harjani 			goto out;
23002943fdbcSRitesh Harjani 		}
23012943fdbcSRitesh Harjani 		if (buffer_delay(bh)) {
23022943fdbcSRitesh Harjani 			clear_buffer_delay(bh);
23032943fdbcSRitesh Harjani 			bh->b_blocknr = pblock++;
23042943fdbcSRitesh Harjani 		}
23052943fdbcSRitesh Harjani 		clear_buffer_unwritten(bh);
2306c8cc8816SRitesh Harjani 		io_end_size += (1 << blkbits);
23072943fdbcSRitesh Harjani 	} while (lblk++, (bh = bh->b_this_page) != head);
2308c8cc8816SRitesh Harjani 
2309c8cc8816SRitesh Harjani 	io_end_vec->size += io_end_size;
23102943fdbcSRitesh Harjani 	*map_bh = false;
23112943fdbcSRitesh Harjani out:
23122943fdbcSRitesh Harjani 	*m_lblk = lblk;
23132943fdbcSRitesh Harjani 	*m_pblk = pblock;
23142943fdbcSRitesh Harjani 	return err;
23152943fdbcSRitesh Harjani }
23162943fdbcSRitesh Harjani 
23172943fdbcSRitesh Harjani /*
23184e7ea81dSJan Kara  * mpage_map_buffers - update buffers corresponding to changed extent and
23194e7ea81dSJan Kara  *		       submit fully mapped pages for IO
23204e7ea81dSJan Kara  *
23214e7ea81dSJan Kara  * @mpd - description of extent to map, on return next extent to map
23224e7ea81dSJan Kara  *
23234e7ea81dSJan Kara  * Scan buffers corresponding to changed extent (we expect corresponding pages
23244e7ea81dSJan Kara  * to be already locked) and update buffer state according to new extent state.
23254e7ea81dSJan Kara  * We map delalloc buffers to their physical location, clear unwritten bits,
2326556615dcSLukas Czerner  * and mark buffers as uninit when we perform writes to unwritten extents
23274e7ea81dSJan Kara  * and do extent conversion after IO is finished. If the last page is not fully
23284e7ea81dSJan Kara  * mapped, we update @map to the next extent in the last page that needs
23294e7ea81dSJan Kara  * mapping. Otherwise we submit the page for IO.
23304e7ea81dSJan Kara  */
23314e7ea81dSJan Kara static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
23324e7ea81dSJan Kara {
23337530d093SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
23347530d093SMatthew Wilcox (Oracle) 	unsigned nr, i;
23354e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
233609cbfeafSKirill A. Shutemov 	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
23374e7ea81dSJan Kara 	pgoff_t start, end;
23384e7ea81dSJan Kara 	ext4_lblk_t lblk;
23392943fdbcSRitesh Harjani 	ext4_fsblk_t pblock;
23404e7ea81dSJan Kara 	int err;
23412943fdbcSRitesh Harjani 	bool map_bh = false;
23424e7ea81dSJan Kara 
23434e7ea81dSJan Kara 	start = mpd->map.m_lblk >> bpp_bits;
23444e7ea81dSJan Kara 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
23454e7ea81dSJan Kara 	lblk = start << bpp_bits;
23464e7ea81dSJan Kara 	pblock = mpd->map.m_pblk;
23474e7ea81dSJan Kara 
23487530d093SMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
23494e7ea81dSJan Kara 	while (start <= end) {
23507530d093SMatthew Wilcox (Oracle) 		nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
23517530d093SMatthew Wilcox (Oracle) 		if (nr == 0)
23524e7ea81dSJan Kara 			break;
23537530d093SMatthew Wilcox (Oracle) 		for (i = 0; i < nr; i++) {
23547530d093SMatthew Wilcox (Oracle) 			struct page *page = &fbatch.folios[i]->page;
23554e7ea81dSJan Kara 
23562943fdbcSRitesh Harjani 			err = mpage_process_page(mpd, page, &lblk, &pblock,
23572943fdbcSRitesh Harjani 						 &map_bh);
23584e7ea81dSJan Kara 			/*
23592943fdbcSRitesh Harjani 			 * If map_bh is true, means page may require further bh
23602943fdbcSRitesh Harjani 			 * mapping, or maybe the page was submitted for IO.
23612943fdbcSRitesh Harjani 			 * So we return to call further extent mapping.
23624e7ea81dSJan Kara 			 */
236339c0ae16SJason Yan 			if (err < 0 || map_bh)
23642943fdbcSRitesh Harjani 				goto out;
23654e7ea81dSJan Kara 			/* Page fully mapped - let IO run! */
23664e7ea81dSJan Kara 			err = mpage_submit_page(mpd, page);
23672943fdbcSRitesh Harjani 			if (err < 0)
23682943fdbcSRitesh Harjani 				goto out;
23694e7ea81dSJan Kara 		}
23707530d093SMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
23714e7ea81dSJan Kara 	}
23724e7ea81dSJan Kara 	/* Extent fully mapped and matches with page boundary. We are done. */
23734e7ea81dSJan Kara 	mpd->map.m_len = 0;
23744e7ea81dSJan Kara 	mpd->map.m_flags = 0;
23754e7ea81dSJan Kara 	return 0;
23762943fdbcSRitesh Harjani out:
23777530d093SMatthew Wilcox (Oracle) 	folio_batch_release(&fbatch);
23782943fdbcSRitesh Harjani 	return err;
23794e7ea81dSJan Kara }
23804e7ea81dSJan Kara 
23814e7ea81dSJan Kara static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
23824e7ea81dSJan Kara {
23834e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
23844e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
23854e7ea81dSJan Kara 	int get_blocks_flags;
2386090f32eeSLukas Czerner 	int err, dioread_nolock;
23874e7ea81dSJan Kara 
23884e7ea81dSJan Kara 	trace_ext4_da_write_pages_extent(inode, map);
23894e7ea81dSJan Kara 	/*
23904e7ea81dSJan Kara 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2391556615dcSLukas Czerner 	 * to convert an unwritten extent to be initialized (in the case
23924e7ea81dSJan Kara 	 * where we have written into one or more preallocated blocks).  It is
23934e7ea81dSJan Kara 	 * possible that we're going to need more metadata blocks than
23944e7ea81dSJan Kara 	 * previously reserved. However we must not fail because we're in
23954e7ea81dSJan Kara 	 * writeback and there is nothing we can do about it so it might result
23964e7ea81dSJan Kara 	 * in data loss.  So use reserved blocks to allocate metadata if
23974e7ea81dSJan Kara 	 * possible.
23984e7ea81dSJan Kara 	 *
2399754cfed6STheodore Ts'o 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2400754cfed6STheodore Ts'o 	 * the blocks in question are delalloc blocks.  This indicates
2401754cfed6STheodore Ts'o 	 * that the blocks and quotas has already been checked when
2402754cfed6STheodore Ts'o 	 * the data was copied into the page cache.
24034e7ea81dSJan Kara 	 */
24044e7ea81dSJan Kara 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2405ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2406ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_IO_SUBMIT;
2407090f32eeSLukas Czerner 	dioread_nolock = ext4_should_dioread_nolock(inode);
2408090f32eeSLukas Czerner 	if (dioread_nolock)
24094e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
24106db07461SRitesh Harjani 	if (map->m_flags & BIT(BH_Delay))
24114e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
24124e7ea81dSJan Kara 
24134e7ea81dSJan Kara 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
24144e7ea81dSJan Kara 	if (err < 0)
24154e7ea81dSJan Kara 		return err;
2416090f32eeSLukas Czerner 	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
24176b523df4SJan Kara 		if (!mpd->io_submit.io_end->handle &&
24186b523df4SJan Kara 		    ext4_handle_valid(handle)) {
24196b523df4SJan Kara 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
24206b523df4SJan Kara 			handle->h_rsv_handle = NULL;
24216b523df4SJan Kara 		}
24223613d228SJan Kara 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
24236b523df4SJan Kara 	}
24244e7ea81dSJan Kara 
24254e7ea81dSJan Kara 	BUG_ON(map->m_len == 0);
24264e7ea81dSJan Kara 	return 0;
24274e7ea81dSJan Kara }
24284e7ea81dSJan Kara 
24294e7ea81dSJan Kara /*
24304e7ea81dSJan Kara  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
24314e7ea81dSJan Kara  *				 mpd->len and submit pages underlying it for IO
24324e7ea81dSJan Kara  *
24334e7ea81dSJan Kara  * @handle - handle for journal operations
24344e7ea81dSJan Kara  * @mpd - extent to map
24357534e854SJan Kara  * @give_up_on_write - we set this to true iff there is a fatal error and there
24367534e854SJan Kara  *                     is no hope of writing the data. The caller should discard
24377534e854SJan Kara  *                     dirty pages to avoid infinite loops.
24384e7ea81dSJan Kara  *
24394e7ea81dSJan Kara  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
24404e7ea81dSJan Kara  * delayed, blocks are allocated, if it is unwritten, we may need to convert
24414e7ea81dSJan Kara  * them to initialized or split the described range from larger unwritten
24424e7ea81dSJan Kara  * extent. Note that we need not map all the described range since allocation
24434e7ea81dSJan Kara  * can return less blocks or the range is covered by more unwritten extents. We
24444e7ea81dSJan Kara  * cannot map more because we are limited by reserved transaction credits. On
24454e7ea81dSJan Kara  * the other hand we always make sure that the last touched page is fully
24464e7ea81dSJan Kara  * mapped so that it can be written out (and thus forward progress is
24474e7ea81dSJan Kara  * guaranteed). After mapping we submit all mapped pages for IO.
24484e7ea81dSJan Kara  */
24494e7ea81dSJan Kara static int mpage_map_and_submit_extent(handle_t *handle,
2450cb530541STheodore Ts'o 				       struct mpage_da_data *mpd,
2451cb530541STheodore Ts'o 				       bool *give_up_on_write)
24524e7ea81dSJan Kara {
24534e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
24544e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
24554e7ea81dSJan Kara 	int err;
24564e7ea81dSJan Kara 	loff_t disksize;
24576603120eSDmitry Monakhov 	int progress = 0;
2458c8cc8816SRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
24594d06bfb9SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec;
24604e7ea81dSJan Kara 
24614d06bfb9SRitesh Harjani 	io_end_vec = ext4_alloc_io_end_vec(io_end);
24624d06bfb9SRitesh Harjani 	if (IS_ERR(io_end_vec))
24634d06bfb9SRitesh Harjani 		return PTR_ERR(io_end_vec);
2464c8cc8816SRitesh Harjani 	io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
246527d7c4edSJan Kara 	do {
24664e7ea81dSJan Kara 		err = mpage_map_one_extent(handle, mpd);
24674e7ea81dSJan Kara 		if (err < 0) {
24684e7ea81dSJan Kara 			struct super_block *sb = inode->i_sb;
24694e7ea81dSJan Kara 
24700db1ff22STheodore Ts'o 			if (ext4_forced_shutdown(EXT4_SB(sb)) ||
24719b5f6c9bSHarshad Shirwadkar 			    ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
2472cb530541STheodore Ts'o 				goto invalidate_dirty_pages;
24734e7ea81dSJan Kara 			/*
2474cb530541STheodore Ts'o 			 * Let the uper layers retry transient errors.
2475cb530541STheodore Ts'o 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2476cb530541STheodore Ts'o 			 * is non-zero, a commit should free up blocks.
24774e7ea81dSJan Kara 			 */
2478cb530541STheodore Ts'o 			if ((err == -ENOMEM) ||
24796603120eSDmitry Monakhov 			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
24806603120eSDmitry Monakhov 				if (progress)
24816603120eSDmitry Monakhov 					goto update_disksize;
2482cb530541STheodore Ts'o 				return err;
24836603120eSDmitry Monakhov 			}
24844e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24854e7ea81dSJan Kara 				 "Delayed block allocation failed for "
24864e7ea81dSJan Kara 				 "inode %lu at logical offset %llu with"
24874e7ea81dSJan Kara 				 " max blocks %u with error %d",
24884e7ea81dSJan Kara 				 inode->i_ino,
24894e7ea81dSJan Kara 				 (unsigned long long)map->m_lblk,
2490cb530541STheodore Ts'o 				 (unsigned)map->m_len, -err);
24914e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24924e7ea81dSJan Kara 				 "This should not happen!! Data will "
24934e7ea81dSJan Kara 				 "be lost\n");
24944e7ea81dSJan Kara 			if (err == -ENOSPC)
24954e7ea81dSJan Kara 				ext4_print_free_blocks(inode);
2496cb530541STheodore Ts'o 		invalidate_dirty_pages:
2497cb530541STheodore Ts'o 			*give_up_on_write = true;
24984e7ea81dSJan Kara 			return err;
24994e7ea81dSJan Kara 		}
25006603120eSDmitry Monakhov 		progress = 1;
25014e7ea81dSJan Kara 		/*
25024e7ea81dSJan Kara 		 * Update buffer state, submit mapped pages, and get us new
25034e7ea81dSJan Kara 		 * extent to map
25044e7ea81dSJan Kara 		 */
25054e7ea81dSJan Kara 		err = mpage_map_and_submit_buffers(mpd);
25064e7ea81dSJan Kara 		if (err < 0)
25076603120eSDmitry Monakhov 			goto update_disksize;
250827d7c4edSJan Kara 	} while (map->m_len);
25094e7ea81dSJan Kara 
25106603120eSDmitry Monakhov update_disksize:
2511622cad13STheodore Ts'o 	/*
2512622cad13STheodore Ts'o 	 * Update on-disk size after IO is submitted.  Races with
2513622cad13STheodore Ts'o 	 * truncate are avoided by checking i_size under i_data_sem.
2514622cad13STheodore Ts'o 	 */
251509cbfeafSKirill A. Shutemov 	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
251635df4299SQian Cai 	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
25174e7ea81dSJan Kara 		int err2;
2518622cad13STheodore Ts'o 		loff_t i_size;
25194e7ea81dSJan Kara 
2520622cad13STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
2521622cad13STheodore Ts'o 		i_size = i_size_read(inode);
2522622cad13STheodore Ts'o 		if (disksize > i_size)
2523622cad13STheodore Ts'o 			disksize = i_size;
2524622cad13STheodore Ts'o 		if (disksize > EXT4_I(inode)->i_disksize)
2525622cad13STheodore Ts'o 			EXT4_I(inode)->i_disksize = disksize;
2526622cad13STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
2527b907f2d5STheodore Ts'o 		err2 = ext4_mark_inode_dirty(handle, inode);
2528878520acSTheodore Ts'o 		if (err2) {
252954d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err2,
25304e7ea81dSJan Kara 				       "Failed to mark inode %lu dirty",
25314e7ea81dSJan Kara 				       inode->i_ino);
2532878520acSTheodore Ts'o 		}
25334e7ea81dSJan Kara 		if (!err)
25344e7ea81dSJan Kara 			err = err2;
25354e7ea81dSJan Kara 	}
25364e7ea81dSJan Kara 	return err;
25374e7ea81dSJan Kara }
25384e7ea81dSJan Kara 
25394e7ea81dSJan Kara /*
2540fffb2739SJan Kara  * Calculate the total number of credits to reserve for one writepages
254120970ba6STheodore Ts'o  * iteration. This is called from ext4_writepages(). We map an extent of
2542fffb2739SJan Kara  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2543fffb2739SJan Kara  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2544fffb2739SJan Kara  * bpp - 1 blocks in bpp different extents.
2545525f4ed8SMingming Cao  */
2546fffb2739SJan Kara static int ext4_da_writepages_trans_blocks(struct inode *inode)
2547fffb2739SJan Kara {
2548fffb2739SJan Kara 	int bpp = ext4_journal_blocks_per_page(inode);
2549525f4ed8SMingming Cao 
2550fffb2739SJan Kara 	return ext4_meta_trans_blocks(inode,
2551fffb2739SJan Kara 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2552525f4ed8SMingming Cao }
255361628a3fSMingming Cao 
25548e48dcfbSTheodore Ts'o /*
25554e7ea81dSJan Kara  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
25564e7ea81dSJan Kara  * 				 and underlying extent to map
25574e7ea81dSJan Kara  *
25584e7ea81dSJan Kara  * @mpd - where to look for pages
25594e7ea81dSJan Kara  *
25604e7ea81dSJan Kara  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
25614e7ea81dSJan Kara  * IO immediately. When we find a page which isn't mapped we start accumulating
25624e7ea81dSJan Kara  * extent of buffers underlying these pages that needs mapping (formed by
25634e7ea81dSJan Kara  * either delayed or unwritten buffers). We also lock the pages containing
25644e7ea81dSJan Kara  * these buffers. The extent found is returned in @mpd structure (starting at
25654e7ea81dSJan Kara  * mpd->lblk with length mpd->len blocks).
25664e7ea81dSJan Kara  *
25674e7ea81dSJan Kara  * Note that this function can attach bios to one io_end structure which are
25684e7ea81dSJan Kara  * neither logically nor physically contiguous. Although it may seem as an
25694e7ea81dSJan Kara  * unnecessary complication, it is actually inevitable in blocksize < pagesize
25704e7ea81dSJan Kara  * case as we need to track IO to all buffers underlying a page in one io_end.
25718e48dcfbSTheodore Ts'o  */
25724e7ea81dSJan Kara static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
25738e48dcfbSTheodore Ts'o {
25744e7ea81dSJan Kara 	struct address_space *mapping = mpd->inode->i_mapping;
25758e48dcfbSTheodore Ts'o 	struct pagevec pvec;
25764f01b02cSTheodore Ts'o 	unsigned int nr_pages;
2577aeac589aSMing Lei 	long left = mpd->wbc->nr_to_write;
25784e7ea81dSJan Kara 	pgoff_t index = mpd->first_page;
25794e7ea81dSJan Kara 	pgoff_t end = mpd->last_page;
258010bbd235SMatthew Wilcox 	xa_mark_t tag;
25814e7ea81dSJan Kara 	int i, err = 0;
25824e7ea81dSJan Kara 	int blkbits = mpd->inode->i_blkbits;
25834e7ea81dSJan Kara 	ext4_lblk_t lblk;
25844e7ea81dSJan Kara 	struct buffer_head *head;
25858e48dcfbSTheodore Ts'o 
25864e7ea81dSJan Kara 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
25875b41d924SEric Sandeen 		tag = PAGECACHE_TAG_TOWRITE;
25885b41d924SEric Sandeen 	else
25895b41d924SEric Sandeen 		tag = PAGECACHE_TAG_DIRTY;
25905b41d924SEric Sandeen 
259186679820SMel Gorman 	pagevec_init(&pvec);
25924e7ea81dSJan Kara 	mpd->map.m_len = 0;
25934e7ea81dSJan Kara 	mpd->next_page = index;
25944f01b02cSTheodore Ts'o 	while (index <= end) {
2595dc7f3e86SJan Kara 		nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
259667fd707fSJan Kara 				tag);
25978e48dcfbSTheodore Ts'o 		if (nr_pages == 0)
25986b8ed620SJan Kara 			break;
25998e48dcfbSTheodore Ts'o 
26008e48dcfbSTheodore Ts'o 		for (i = 0; i < nr_pages; i++) {
26018e48dcfbSTheodore Ts'o 			struct page *page = pvec.pages[i];
26028e48dcfbSTheodore Ts'o 
26038e48dcfbSTheodore Ts'o 			/*
2604aeac589aSMing Lei 			 * Accumulated enough dirty pages? This doesn't apply
2605aeac589aSMing Lei 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2606aeac589aSMing Lei 			 * keep going because someone may be concurrently
2607aeac589aSMing Lei 			 * dirtying pages, and we might have synced a lot of
2608aeac589aSMing Lei 			 * newly appeared dirty pages, but have not synced all
2609aeac589aSMing Lei 			 * of the old dirty pages.
2610aeac589aSMing Lei 			 */
2611aeac589aSMing Lei 			if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2612aeac589aSMing Lei 				goto out;
2613aeac589aSMing Lei 
26144e7ea81dSJan Kara 			/* If we can't merge this page, we are done. */
26154e7ea81dSJan Kara 			if (mpd->map.m_len > 0 && mpd->next_page != page->index)
26164e7ea81dSJan Kara 				goto out;
261778aaced3STheodore Ts'o 
26188e48dcfbSTheodore Ts'o 			lock_page(page);
26198e48dcfbSTheodore Ts'o 			/*
26204e7ea81dSJan Kara 			 * If the page is no longer dirty, or its mapping no
26214e7ea81dSJan Kara 			 * longer corresponds to inode we are writing (which
26224e7ea81dSJan Kara 			 * means it has been truncated or invalidated), or the
26234e7ea81dSJan Kara 			 * page is already under writeback and we are not doing
26244e7ea81dSJan Kara 			 * a data integrity writeback, skip the page
26258e48dcfbSTheodore Ts'o 			 */
26264f01b02cSTheodore Ts'o 			if (!PageDirty(page) ||
26274f01b02cSTheodore Ts'o 			    (PageWriteback(page) &&
26284e7ea81dSJan Kara 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
26294f01b02cSTheodore Ts'o 			    unlikely(page->mapping != mapping)) {
26308e48dcfbSTheodore Ts'o 				unlock_page(page);
26318e48dcfbSTheodore Ts'o 				continue;
26328e48dcfbSTheodore Ts'o 			}
26338e48dcfbSTheodore Ts'o 
26348e48dcfbSTheodore Ts'o 			wait_on_page_writeback(page);
26358e48dcfbSTheodore Ts'o 			BUG_ON(PageWriteback(page));
26368e48dcfbSTheodore Ts'o 
2637cc509574STheodore Ts'o 			/*
2638cc509574STheodore Ts'o 			 * Should never happen but for buggy code in
2639cc509574STheodore Ts'o 			 * other subsystems that call
2640cc509574STheodore Ts'o 			 * set_page_dirty() without properly warning
2641cc509574STheodore Ts'o 			 * the file system first.  See [1] for more
2642cc509574STheodore Ts'o 			 * information.
2643cc509574STheodore Ts'o 			 *
2644cc509574STheodore Ts'o 			 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2645cc509574STheodore Ts'o 			 */
2646cc509574STheodore Ts'o 			if (!page_has_buffers(page)) {
2647cc509574STheodore Ts'o 				ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", page->index);
2648cc509574STheodore Ts'o 				ClearPageDirty(page);
2649cc509574STheodore Ts'o 				unlock_page(page);
2650cc509574STheodore Ts'o 				continue;
2651cc509574STheodore Ts'o 			}
2652cc509574STheodore Ts'o 
26534e7ea81dSJan Kara 			if (mpd->map.m_len == 0)
26548eb9e5ceSTheodore Ts'o 				mpd->first_page = page->index;
26558eb9e5ceSTheodore Ts'o 			mpd->next_page = page->index + 1;
2656f8bec370SJan Kara 			/* Add all dirty buffers to mpd */
26574e7ea81dSJan Kara 			lblk = ((ext4_lblk_t)page->index) <<
265809cbfeafSKirill A. Shutemov 				(PAGE_SHIFT - blkbits);
26598eb9e5ceSTheodore Ts'o 			head = page_buffers(page);
26605f1132b2SJan Kara 			err = mpage_process_page_bufs(mpd, head, head, lblk);
26615f1132b2SJan Kara 			if (err <= 0)
26624e7ea81dSJan Kara 				goto out;
26635f1132b2SJan Kara 			err = 0;
2664aeac589aSMing Lei 			left--;
26658e48dcfbSTheodore Ts'o 		}
26668e48dcfbSTheodore Ts'o 		pagevec_release(&pvec);
26678e48dcfbSTheodore Ts'o 		cond_resched();
26688e48dcfbSTheodore Ts'o 	}
26696b8ed620SJan Kara 	mpd->scanned_until_end = 1;
26704f01b02cSTheodore Ts'o 	return 0;
26718eb9e5ceSTheodore Ts'o out:
26728eb9e5ceSTheodore Ts'o 	pagevec_release(&pvec);
26734e7ea81dSJan Kara 	return err;
26748e48dcfbSTheodore Ts'o }
26758e48dcfbSTheodore Ts'o 
267620970ba6STheodore Ts'o static int ext4_writepages(struct address_space *mapping,
267764769240SAlex Tomas 			   struct writeback_control *wbc)
267864769240SAlex Tomas {
26794e7ea81dSJan Kara 	pgoff_t	writeback_index = 0;
26804e7ea81dSJan Kara 	long nr_to_write = wbc->nr_to_write;
268122208dedSAneesh Kumar K.V 	int range_whole = 0;
26824e7ea81dSJan Kara 	int cycled = 1;
268361628a3fSMingming Cao 	handle_t *handle = NULL;
2684df22291fSAneesh Kumar K.V 	struct mpage_da_data mpd;
26855e745b04SAneesh Kumar K.V 	struct inode *inode = mapping->host;
26866b523df4SJan Kara 	int needed_blocks, rsv_blocks = 0, ret = 0;
26875e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
26881bce63d1SShaohua Li 	struct blk_plug plug;
2689cb530541STheodore Ts'o 	bool give_up_on_write = false;
269061628a3fSMingming Cao 
26910db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
26920db1ff22STheodore Ts'o 		return -EIO;
26930db1ff22STheodore Ts'o 
2694bbd55937SEric Biggers 	percpu_down_read(&sbi->s_writepages_rwsem);
269520970ba6STheodore Ts'o 	trace_ext4_writepages(inode, wbc);
2696ba80b101STheodore Ts'o 
269761628a3fSMingming Cao 	/*
269861628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
269961628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
270061628a3fSMingming Cao 	 * because that could violate lock ordering on umount
270161628a3fSMingming Cao 	 */
2702a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2703bbf023c7SMing Lei 		goto out_writepages;
27042a21e37eSTheodore Ts'o 
270520970ba6STheodore Ts'o 	if (ext4_should_journal_data(inode)) {
2706043d20d1SGoldwyn Rodrigues 		ret = generic_writepages(mapping, wbc);
2707bbf023c7SMing Lei 		goto out_writepages;
270820970ba6STheodore Ts'o 	}
270920970ba6STheodore Ts'o 
27102a21e37eSTheodore Ts'o 	/*
27112a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
27122a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
27132a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
27141751e8a6SLinus Torvalds 	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
27152a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
271620970ba6STheodore Ts'o 	 * read-only, and in that case, ext4_writepages should
27172a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
27182a21e37eSTheodore Ts'o 	 * the stack trace.
27192a21e37eSTheodore Ts'o 	 */
27200db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
27219b5f6c9bSHarshad Shirwadkar 		     ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
2722bbf023c7SMing Lei 		ret = -EROFS;
2723bbf023c7SMing Lei 		goto out_writepages;
2724bbf023c7SMing Lei 	}
27252a21e37eSTheodore Ts'o 
27264e7ea81dSJan Kara 	/*
27274e7ea81dSJan Kara 	 * If we have inline data and arrive here, it means that
27284e7ea81dSJan Kara 	 * we will soon create the block for the 1st page, so
27294e7ea81dSJan Kara 	 * we'd better clear the inline data here.
27304e7ea81dSJan Kara 	 */
27314e7ea81dSJan Kara 	if (ext4_has_inline_data(inode)) {
27324e7ea81dSJan Kara 		/* Just inode will be modified... */
27334e7ea81dSJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
27344e7ea81dSJan Kara 		if (IS_ERR(handle)) {
27354e7ea81dSJan Kara 			ret = PTR_ERR(handle);
27364e7ea81dSJan Kara 			goto out_writepages;
27374e7ea81dSJan Kara 		}
27384e7ea81dSJan Kara 		BUG_ON(ext4_test_inode_state(inode,
27394e7ea81dSJan Kara 				EXT4_STATE_MAY_INLINE_DATA));
27404e7ea81dSJan Kara 		ext4_destroy_inline_data(handle, inode);
27414e7ea81dSJan Kara 		ext4_journal_stop(handle);
27424e7ea81dSJan Kara 	}
27434e7ea81dSJan Kara 
27444e343231Syangerkun 	if (ext4_should_dioread_nolock(inode)) {
27454e343231Syangerkun 		/*
27464e343231Syangerkun 		 * We may need to convert up to one extent per block in
27474e343231Syangerkun 		 * the page and we may dirty the inode.
27484e343231Syangerkun 		 */
27494e343231Syangerkun 		rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
27504e343231Syangerkun 						PAGE_SIZE >> inode->i_blkbits);
27514e343231Syangerkun 	}
27524e343231Syangerkun 
275322208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
275422208dedSAneesh Kumar K.V 		range_whole = 1;
275561628a3fSMingming Cao 
27562acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
27574e7ea81dSJan Kara 		writeback_index = mapping->writeback_index;
27584e7ea81dSJan Kara 		if (writeback_index)
27592acf2c26SAneesh Kumar K.V 			cycled = 0;
27604e7ea81dSJan Kara 		mpd.first_page = writeback_index;
27614e7ea81dSJan Kara 		mpd.last_page = -1;
27625b41d924SEric Sandeen 	} else {
276309cbfeafSKirill A. Shutemov 		mpd.first_page = wbc->range_start >> PAGE_SHIFT;
276409cbfeafSKirill A. Shutemov 		mpd.last_page = wbc->range_end >> PAGE_SHIFT;
27655b41d924SEric Sandeen 	}
2766a1d6cc56SAneesh Kumar K.V 
27674e7ea81dSJan Kara 	mpd.inode = inode;
27684e7ea81dSJan Kara 	mpd.wbc = wbc;
27694e7ea81dSJan Kara 	ext4_io_submit_init(&mpd.io_submit, wbc);
27702acf2c26SAneesh Kumar K.V retry:
27716e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
27724e7ea81dSJan Kara 		tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
27731bce63d1SShaohua Li 	blk_start_plug(&plug);
2774dddbd6acSJan Kara 
2775dddbd6acSJan Kara 	/*
2776dddbd6acSJan Kara 	 * First writeback pages that don't need mapping - we can avoid
2777dddbd6acSJan Kara 	 * starting a transaction unnecessarily and also avoid being blocked
2778dddbd6acSJan Kara 	 * in the block layer on device congestion while having transaction
2779dddbd6acSJan Kara 	 * started.
2780dddbd6acSJan Kara 	 */
2781dddbd6acSJan Kara 	mpd.do_map = 0;
27826b8ed620SJan Kara 	mpd.scanned_until_end = 0;
2783dddbd6acSJan Kara 	mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2784dddbd6acSJan Kara 	if (!mpd.io_submit.io_end) {
2785dddbd6acSJan Kara 		ret = -ENOMEM;
2786dddbd6acSJan Kara 		goto unplug;
2787dddbd6acSJan Kara 	}
2788dddbd6acSJan Kara 	ret = mpage_prepare_extent_to_map(&mpd);
2789a297b2fcSXiaoguang Wang 	/* Unlock pages we didn't use */
2790a297b2fcSXiaoguang Wang 	mpage_release_unused_pages(&mpd, false);
2791dddbd6acSJan Kara 	/* Submit prepared bio */
2792dddbd6acSJan Kara 	ext4_io_submit(&mpd.io_submit);
2793dddbd6acSJan Kara 	ext4_put_io_end_defer(mpd.io_submit.io_end);
2794dddbd6acSJan Kara 	mpd.io_submit.io_end = NULL;
2795dddbd6acSJan Kara 	if (ret < 0)
2796dddbd6acSJan Kara 		goto unplug;
2797dddbd6acSJan Kara 
27986b8ed620SJan Kara 	while (!mpd.scanned_until_end && wbc->nr_to_write > 0) {
27994e7ea81dSJan Kara 		/* For each extent of pages we use new io_end */
28004e7ea81dSJan Kara 		mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
28014e7ea81dSJan Kara 		if (!mpd.io_submit.io_end) {
28024e7ea81dSJan Kara 			ret = -ENOMEM;
28034e7ea81dSJan Kara 			break;
28044e7ea81dSJan Kara 		}
2805a1d6cc56SAneesh Kumar K.V 
2806a1d6cc56SAneesh Kumar K.V 		/*
28074e7ea81dSJan Kara 		 * We have two constraints: We find one extent to map and we
28084e7ea81dSJan Kara 		 * must always write out whole page (makes a difference when
28094e7ea81dSJan Kara 		 * blocksize < pagesize) so that we don't block on IO when we
28104e7ea81dSJan Kara 		 * try to write out the rest of the page. Journalled mode is
28114e7ea81dSJan Kara 		 * not supported by delalloc.
2812a1d6cc56SAneesh Kumar K.V 		 */
2813a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
2814525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2815a1d6cc56SAneesh Kumar K.V 
281661628a3fSMingming Cao 		/* start a new transaction */
28176b523df4SJan Kara 		handle = ext4_journal_start_with_reserve(inode,
28186b523df4SJan Kara 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
281961628a3fSMingming Cao 		if (IS_ERR(handle)) {
282061628a3fSMingming Cao 			ret = PTR_ERR(handle);
28211693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2822fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
2823a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
28244e7ea81dSJan Kara 			/* Release allocated io_end */
28254e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
2826dddbd6acSJan Kara 			mpd.io_submit.io_end = NULL;
28274e7ea81dSJan Kara 			break;
282861628a3fSMingming Cao 		}
2829dddbd6acSJan Kara 		mpd.do_map = 1;
2830f63e6005STheodore Ts'o 
28314e7ea81dSJan Kara 		trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
28324e7ea81dSJan Kara 		ret = mpage_prepare_extent_to_map(&mpd);
28336b8ed620SJan Kara 		if (!ret && mpd.map.m_len)
2834cb530541STheodore Ts'o 			ret = mpage_map_and_submit_extent(handle, &mpd,
2835cb530541STheodore Ts'o 					&give_up_on_write);
2836646caa9cSJan Kara 		/*
2837646caa9cSJan Kara 		 * Caution: If the handle is synchronous,
2838646caa9cSJan Kara 		 * ext4_journal_stop() can wait for transaction commit
2839646caa9cSJan Kara 		 * to finish which may depend on writeback of pages to
2840646caa9cSJan Kara 		 * complete or on page lock to be released.  In that
2841b483bb77SRandy Dunlap 		 * case, we have to wait until after we have
2842646caa9cSJan Kara 		 * submitted all the IO, released page locks we hold,
2843646caa9cSJan Kara 		 * and dropped io_end reference (for extent conversion
2844646caa9cSJan Kara 		 * to be able to complete) before stopping the handle.
2845646caa9cSJan Kara 		 */
2846646caa9cSJan Kara 		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
284761628a3fSMingming Cao 			ext4_journal_stop(handle);
2848646caa9cSJan Kara 			handle = NULL;
2849dddbd6acSJan Kara 			mpd.do_map = 0;
2850646caa9cSJan Kara 		}
28514e7ea81dSJan Kara 		/* Unlock pages we didn't use */
2852cb530541STheodore Ts'o 		mpage_release_unused_pages(&mpd, give_up_on_write);
2853a297b2fcSXiaoguang Wang 		/* Submit prepared bio */
2854a297b2fcSXiaoguang Wang 		ext4_io_submit(&mpd.io_submit);
2855a297b2fcSXiaoguang Wang 
2856646caa9cSJan Kara 		/*
2857646caa9cSJan Kara 		 * Drop our io_end reference we got from init. We have
2858646caa9cSJan Kara 		 * to be careful and use deferred io_end finishing if
2859646caa9cSJan Kara 		 * we are still holding the transaction as we can
2860646caa9cSJan Kara 		 * release the last reference to io_end which may end
2861646caa9cSJan Kara 		 * up doing unwritten extent conversion.
2862646caa9cSJan Kara 		 */
2863646caa9cSJan Kara 		if (handle) {
2864646caa9cSJan Kara 			ext4_put_io_end_defer(mpd.io_submit.io_end);
2865646caa9cSJan Kara 			ext4_journal_stop(handle);
2866646caa9cSJan Kara 		} else
28674e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
2868dddbd6acSJan Kara 		mpd.io_submit.io_end = NULL;
2869df22291fSAneesh Kumar K.V 
28704e7ea81dSJan Kara 		if (ret == -ENOSPC && sbi->s_journal) {
28714e7ea81dSJan Kara 			/*
28724e7ea81dSJan Kara 			 * Commit the transaction which would
287322208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
287422208dedSAneesh Kumar K.V 			 * and try again
287522208dedSAneesh Kumar K.V 			 */
2876df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
287722208dedSAneesh Kumar K.V 			ret = 0;
28784e7ea81dSJan Kara 			continue;
28794e7ea81dSJan Kara 		}
28804e7ea81dSJan Kara 		/* Fatal error - ENOMEM, EIO... */
28814e7ea81dSJan Kara 		if (ret)
288261628a3fSMingming Cao 			break;
288361628a3fSMingming Cao 	}
2884dddbd6acSJan Kara unplug:
28851bce63d1SShaohua Li 	blk_finish_plug(&plug);
28869c12a831SJan Kara 	if (!ret && !cycled && wbc->nr_to_write > 0) {
28872acf2c26SAneesh Kumar K.V 		cycled = 1;
28884e7ea81dSJan Kara 		mpd.last_page = writeback_index - 1;
28894e7ea81dSJan Kara 		mpd.first_page = 0;
28902acf2c26SAneesh Kumar K.V 		goto retry;
28912acf2c26SAneesh Kumar K.V 	}
289261628a3fSMingming Cao 
289322208dedSAneesh Kumar K.V 	/* Update index */
289422208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
289522208dedSAneesh Kumar K.V 		/*
28964e7ea81dSJan Kara 		 * Set the writeback_index so that range_cyclic
289722208dedSAneesh Kumar K.V 		 * mode will write it back later
289822208dedSAneesh Kumar K.V 		 */
28994e7ea81dSJan Kara 		mapping->writeback_index = mpd.first_page;
2900a1d6cc56SAneesh Kumar K.V 
290161628a3fSMingming Cao out_writepages:
290220970ba6STheodore Ts'o 	trace_ext4_writepages_result(inode, wbc, ret,
29034e7ea81dSJan Kara 				     nr_to_write - wbc->nr_to_write);
2904bbd55937SEric Biggers 	percpu_up_read(&sbi->s_writepages_rwsem);
290561628a3fSMingming Cao 	return ret;
290664769240SAlex Tomas }
290764769240SAlex Tomas 
29085f0663bbSDan Williams static int ext4_dax_writepages(struct address_space *mapping,
29095f0663bbSDan Williams 			       struct writeback_control *wbc)
29105f0663bbSDan Williams {
29115f0663bbSDan Williams 	int ret;
29125f0663bbSDan Williams 	long nr_to_write = wbc->nr_to_write;
29135f0663bbSDan Williams 	struct inode *inode = mapping->host;
29145f0663bbSDan Williams 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
29155f0663bbSDan Williams 
29165f0663bbSDan Williams 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
29175f0663bbSDan Williams 		return -EIO;
29185f0663bbSDan Williams 
2919bbd55937SEric Biggers 	percpu_down_read(&sbi->s_writepages_rwsem);
29205f0663bbSDan Williams 	trace_ext4_writepages(inode, wbc);
29215f0663bbSDan Williams 
29223f666c56SVivek Goyal 	ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
29235f0663bbSDan Williams 	trace_ext4_writepages_result(inode, wbc, ret,
29245f0663bbSDan Williams 				     nr_to_write - wbc->nr_to_write);
2925bbd55937SEric Biggers 	percpu_up_read(&sbi->s_writepages_rwsem);
29265f0663bbSDan Williams 	return ret;
29275f0663bbSDan Williams }
29285f0663bbSDan Williams 
292979f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
293079f0be8dSAneesh Kumar K.V {
29315c1ff336SEric Whitney 	s64 free_clusters, dirty_clusters;
293279f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
293379f0be8dSAneesh Kumar K.V 
293479f0be8dSAneesh Kumar K.V 	/*
293579f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
293679f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
2937179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
293879f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
293979f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
294079f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
294179f0be8dSAneesh Kumar K.V 	 */
29425c1ff336SEric Whitney 	free_clusters =
29435c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
29445c1ff336SEric Whitney 	dirty_clusters =
29455c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
294600d4e736STheodore Ts'o 	/*
294700d4e736STheodore Ts'o 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
294800d4e736STheodore Ts'o 	 */
29495c1ff336SEric Whitney 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
295010ee27a0SMiao Xie 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
295100d4e736STheodore Ts'o 
29525c1ff336SEric Whitney 	if (2 * free_clusters < 3 * dirty_clusters ||
29535c1ff336SEric Whitney 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
295479f0be8dSAneesh Kumar K.V 		/*
2955c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
2956c8afb446SEric Sandeen 		 * or free blocks is less than watermark
295779f0be8dSAneesh Kumar K.V 		 */
295879f0be8dSAneesh Kumar K.V 		return 1;
295979f0be8dSAneesh Kumar K.V 	}
296079f0be8dSAneesh Kumar K.V 	return 0;
296179f0be8dSAneesh Kumar K.V }
296279f0be8dSAneesh Kumar K.V 
296364769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
29649d6b0cd7SMatthew Wilcox (Oracle) 			       loff_t pos, unsigned len,
296564769240SAlex Tomas 			       struct page **pagep, void **fsdata)
296664769240SAlex Tomas {
296772b8ab9dSEric Sandeen 	int ret, retries = 0;
296864769240SAlex Tomas 	struct page *page;
296964769240SAlex Tomas 	pgoff_t index;
297064769240SAlex Tomas 	struct inode *inode = mapping->host;
297164769240SAlex Tomas 
29720db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
29730db1ff22STheodore Ts'o 		return -EIO;
29740db1ff22STheodore Ts'o 
297509cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
297679f0be8dSAneesh Kumar K.V 
29776493792dSZhang Yi 	if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
297879f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
297979f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
29809d6b0cd7SMatthew Wilcox (Oracle) 					len, pagep, fsdata);
298179f0be8dSAneesh Kumar K.V 	}
298279f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
29839d6b0cd7SMatthew Wilcox (Oracle) 	trace_ext4_da_write_begin(inode, pos, len);
29849c3569b5STao Ma 
29859c3569b5STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
298636d116e9SMatthew Wilcox (Oracle) 		ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len,
29879c3569b5STao Ma 						      pagep, fsdata);
29889c3569b5STao Ma 		if (ret < 0)
298947564bfbSTheodore Ts'o 			return ret;
299047564bfbSTheodore Ts'o 		if (ret == 1)
299147564bfbSTheodore Ts'o 			return 0;
29929c3569b5STao Ma 	}
29939c3569b5STao Ma 
2994cc883236SZhang Yi retry:
2995b7446e7cSMatthew Wilcox (Oracle) 	page = grab_cache_page_write_begin(mapping, index);
299647564bfbSTheodore Ts'o 	if (!page)
299747564bfbSTheodore Ts'o 		return -ENOMEM;
299847564bfbSTheodore Ts'o 
299947564bfbSTheodore Ts'o 	/* In case writeback began while the page was unlocked */
30007afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
300164769240SAlex Tomas 
3002643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
30032058f83aSMichael Halcrow 	ret = ext4_block_write_begin(page, pos, len,
30042058f83aSMichael Halcrow 				     ext4_da_get_block_prep);
30052058f83aSMichael Halcrow #else
30066e1db88dSChristoph Hellwig 	ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
30072058f83aSMichael Halcrow #endif
300864769240SAlex Tomas 	if (ret < 0) {
300964769240SAlex Tomas 		unlock_page(page);
3010cc883236SZhang Yi 		put_page(page);
3011ae4d5372SAneesh Kumar K.V 		/*
3012ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
3013ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
3014cc883236SZhang Yi 		 * i_size_read because we hold inode lock.
3015ae4d5372SAneesh Kumar K.V 		 */
3016ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
3017b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
301847564bfbSTheodore Ts'o 
301947564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
302047564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
3021cc883236SZhang Yi 			goto retry;
302247564bfbSTheodore Ts'o 		return ret;
302364769240SAlex Tomas 	}
302464769240SAlex Tomas 
302547564bfbSTheodore Ts'o 	*pagep = page;
302664769240SAlex Tomas 	return ret;
302764769240SAlex Tomas }
302864769240SAlex Tomas 
3029632eaeabSMingming Cao /*
3030632eaeabSMingming Cao  * Check if we should update i_disksize
3031632eaeabSMingming Cao  * when write to the end of file but not require block allocation
3032632eaeabSMingming Cao  */
3033632eaeabSMingming Cao static int ext4_da_should_update_i_disksize(struct page *page,
3034632eaeabSMingming Cao 					    unsigned long offset)
3035632eaeabSMingming Cao {
3036632eaeabSMingming Cao 	struct buffer_head *bh;
3037632eaeabSMingming Cao 	struct inode *inode = page->mapping->host;
3038632eaeabSMingming Cao 	unsigned int idx;
3039632eaeabSMingming Cao 	int i;
3040632eaeabSMingming Cao 
3041632eaeabSMingming Cao 	bh = page_buffers(page);
3042632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
3043632eaeabSMingming Cao 
3044632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
3045632eaeabSMingming Cao 		bh = bh->b_this_page;
3046632eaeabSMingming Cao 
304729fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3048632eaeabSMingming Cao 		return 0;
3049632eaeabSMingming Cao 	return 1;
3050632eaeabSMingming Cao }
3051632eaeabSMingming Cao 
305264769240SAlex Tomas static int ext4_da_write_end(struct file *file,
305364769240SAlex Tomas 			     struct address_space *mapping,
305464769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
305564769240SAlex Tomas 			     struct page *page, void *fsdata)
305664769240SAlex Tomas {
305764769240SAlex Tomas 	struct inode *inode = mapping->host;
305864769240SAlex Tomas 	loff_t new_i_size;
3059632eaeabSMingming Cao 	unsigned long start, end;
306079f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
306179f0be8dSAneesh Kumar K.V 
306274d553aaSTheodore Ts'o 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
306374d553aaSTheodore Ts'o 		return ext4_write_end(file, mapping, pos,
306479f0be8dSAneesh Kumar K.V 				      len, copied, page, fsdata);
3065632eaeabSMingming Cao 
30669bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
30679c3569b5STao Ma 
30689c3569b5STao Ma 	if (write_mode != CONVERT_INLINE_DATA &&
30699c3569b5STao Ma 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
30709c3569b5STao Ma 	    ext4_has_inline_data(inode))
30716984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
30729c3569b5STao Ma 
307364769240SAlex Tomas 	start = pos & (PAGE_SIZE - 1);
307464769240SAlex Tomas 	end = start + copied - 1;
307564769240SAlex Tomas 
307664769240SAlex Tomas 	/*
30774df031ffSZhang Yi 	 * Since we are holding inode lock, we are sure i_disksize <=
30784df031ffSZhang Yi 	 * i_size. We also know that if i_disksize < i_size, there are
30794df031ffSZhang Yi 	 * delalloc writes pending in the range upto i_size. If the end of
30804df031ffSZhang Yi 	 * the current write is <= i_size, there's no need to touch
30814df031ffSZhang Yi 	 * i_disksize since writeback will push i_disksize upto i_size
30824df031ffSZhang Yi 	 * eventually. If the end of the current write is > i_size and
30834df031ffSZhang Yi 	 * inside an allocated block (ext4_da_should_update_i_disksize()
30844df031ffSZhang Yi 	 * check), we need to update i_disksize here as neither
30854df031ffSZhang Yi 	 * ext4_writepage() nor certain ext4_writepages() paths not
30864df031ffSZhang Yi 	 * allocating blocks update i_disksize.
30874df031ffSZhang Yi 	 *
30884df031ffSZhang Yi 	 * Note that we defer inode dirtying to generic_write_end() /
30894df031ffSZhang Yi 	 * ext4_da_write_inline_data_end().
3090d2a17637SMingming Cao 	 */
309164769240SAlex Tomas 	new_i_size = pos + copied;
30926984aef5SZhang Yi 	if (copied && new_i_size > inode->i_size &&
30934df031ffSZhang Yi 	    ext4_da_should_update_i_disksize(page, end))
309464769240SAlex Tomas 		ext4_update_i_disksize(inode, new_i_size);
3095ccd2506bSTheodore Ts'o 
3096cc883236SZhang Yi 	return generic_write_end(file, mapping, pos, len, copied, page, fsdata);
3097ac27a0ecSDave Kleikamp }
3098ac27a0ecSDave Kleikamp 
3099ccd2506bSTheodore Ts'o /*
3100ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
3101ccd2506bSTheodore Ts'o  */
3102ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
3103ccd2506bSTheodore Ts'o {
3104ccd2506bSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
3105ccd2506bSTheodore Ts'o 
310671d4f7d0STheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks)
3107ccd2506bSTheodore Ts'o 		return 0;
3108ccd2506bSTheodore Ts'o 
3109ccd2506bSTheodore Ts'o 	/*
3110ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
3111ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
3112ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
3113ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
3114ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
3115ccd2506bSTheodore Ts'o 	 *
311620970ba6STheodore Ts'o 	 * ext4_writepages() ->
3117ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
3118ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
3119ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
3120ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
3121ccd2506bSTheodore Ts'o 	 *
3122ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
3123ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
3124ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
3125ccd2506bSTheodore Ts'o 	 * doing I/O at all.
3126ccd2506bSTheodore Ts'o 	 *
3127ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
3128380cf090SWu Fengguang 	 * the pages by calling redirty_page_for_writepage() but that
3129ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
3130ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
313125985edcSLucas De Marchi 	 * simplifying them because we wouldn't actually intend to
3132ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
3133ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
3134ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
3135ccd2506bSTheodore Ts'o 	 *
3136ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
3137ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
3138ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
3139ccd2506bSTheodore Ts'o 	 */
3140ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
3141ccd2506bSTheodore Ts'o }
3142ac27a0ecSDave Kleikamp 
3143ac27a0ecSDave Kleikamp /*
3144ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
3145ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
3146ac27a0ecSDave Kleikamp  *
3147ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
3148ac27a0ecSDave Kleikamp  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3149ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
3150ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
3151ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
3152ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
3153ac27a0ecSDave Kleikamp  *
3154ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
3155ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
3156ac27a0ecSDave Kleikamp  */
3157ac27a0ecSDave Kleikamp static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3158ac27a0ecSDave Kleikamp {
3159ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
3160ac27a0ecSDave Kleikamp 	journal_t *journal;
316151ae846cSYe Bin 	sector_t ret = 0;
3162ac27a0ecSDave Kleikamp 	int err;
3163ac27a0ecSDave Kleikamp 
316451ae846cSYe Bin 	inode_lock_shared(inode);
316546c7f254STao Ma 	/*
316646c7f254STao Ma 	 * We can get here for an inline file via the FIBMAP ioctl
316746c7f254STao Ma 	 */
316846c7f254STao Ma 	if (ext4_has_inline_data(inode))
316951ae846cSYe Bin 		goto out;
317046c7f254STao Ma 
3171ac27a0ecSDave Kleikamp 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3172ac27a0ecSDave Kleikamp 			test_opt(inode->i_sb, DELALLOC)) {
3173ac27a0ecSDave Kleikamp 		/*
3174ac27a0ecSDave Kleikamp 		 * With delalloc we want to sync the file
3175ac27a0ecSDave Kleikamp 		 * so that we can make sure we allocate
3176ac27a0ecSDave Kleikamp 		 * blocks for file
3177ac27a0ecSDave Kleikamp 		 */
3178ac27a0ecSDave Kleikamp 		filemap_write_and_wait(mapping);
3179ac27a0ecSDave Kleikamp 	}
3180ac27a0ecSDave Kleikamp 
318119f5fb7aSTheodore Ts'o 	if (EXT4_JOURNAL(inode) &&
318219f5fb7aSTheodore Ts'o 	    ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3183ac27a0ecSDave Kleikamp 		/*
3184ac27a0ecSDave Kleikamp 		 * This is a REALLY heavyweight approach, but the use of
3185ac27a0ecSDave Kleikamp 		 * bmap on dirty files is expected to be extremely rare:
3186ac27a0ecSDave Kleikamp 		 * only if we run lilo or swapon on a freshly made file
3187ac27a0ecSDave Kleikamp 		 * do we expect this to happen.
3188ac27a0ecSDave Kleikamp 		 *
3189ac27a0ecSDave Kleikamp 		 * (bmap requires CAP_SYS_RAWIO so this does not
3190ac27a0ecSDave Kleikamp 		 * represent an unprivileged user DOS attack --- we'd be
3191ac27a0ecSDave Kleikamp 		 * in trouble if mortal users could trigger this path at
3192ac27a0ecSDave Kleikamp 		 * will.)
3193ac27a0ecSDave Kleikamp 		 *
3194ac27a0ecSDave Kleikamp 		 * NB. EXT4_STATE_JDATA is not set on files other than
3195ac27a0ecSDave Kleikamp 		 * regular files.  If somebody wants to bmap a directory
3196ac27a0ecSDave Kleikamp 		 * or symlink and gets confused because the buffer
3197ac27a0ecSDave Kleikamp 		 * hasn't yet been flushed to disk, they deserve
3198ac27a0ecSDave Kleikamp 		 * everything they get.
3199ac27a0ecSDave Kleikamp 		 */
3200ac27a0ecSDave Kleikamp 
320119f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3202ac27a0ecSDave Kleikamp 		journal = EXT4_JOURNAL(inode);
3203ac27a0ecSDave Kleikamp 		jbd2_journal_lock_updates(journal);
320401d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
3205ac27a0ecSDave Kleikamp 		jbd2_journal_unlock_updates(journal);
3206ac27a0ecSDave Kleikamp 
3207ac27a0ecSDave Kleikamp 		if (err)
320851ae846cSYe Bin 			goto out;
3209ac27a0ecSDave Kleikamp 	}
3210ac27a0ecSDave Kleikamp 
321151ae846cSYe Bin 	ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
321251ae846cSYe Bin 
321351ae846cSYe Bin out:
321451ae846cSYe Bin 	inode_unlock_shared(inode);
321551ae846cSYe Bin 	return ret;
3216ac27a0ecSDave Kleikamp }
3217ac27a0ecSDave Kleikamp 
3218fe5ddf6bSMatthew Wilcox (Oracle) static int ext4_read_folio(struct file *file, struct folio *folio)
3219ac27a0ecSDave Kleikamp {
3220fe5ddf6bSMatthew Wilcox (Oracle) 	struct page *page = &folio->page;
322146c7f254STao Ma 	int ret = -EAGAIN;
322246c7f254STao Ma 	struct inode *inode = page->mapping->host;
322346c7f254STao Ma 
32240562e0baSJiaying Zhang 	trace_ext4_readpage(page);
322546c7f254STao Ma 
322646c7f254STao Ma 	if (ext4_has_inline_data(inode))
322746c7f254STao Ma 		ret = ext4_readpage_inline(inode, page);
322846c7f254STao Ma 
322946c7f254STao Ma 	if (ret == -EAGAIN)
3230a07f624bSMatthew Wilcox (Oracle) 		return ext4_mpage_readpages(inode, NULL, page);
323146c7f254STao Ma 
323246c7f254STao Ma 	return ret;
3233ac27a0ecSDave Kleikamp }
3234ac27a0ecSDave Kleikamp 
32356311f91fSMatthew Wilcox (Oracle) static void ext4_readahead(struct readahead_control *rac)
3236ac27a0ecSDave Kleikamp {
32376311f91fSMatthew Wilcox (Oracle) 	struct inode *inode = rac->mapping->host;
323846c7f254STao Ma 
32396311f91fSMatthew Wilcox (Oracle) 	/* If the file has inline data, no need to do readahead. */
324046c7f254STao Ma 	if (ext4_has_inline_data(inode))
32416311f91fSMatthew Wilcox (Oracle) 		return;
324246c7f254STao Ma 
3243a07f624bSMatthew Wilcox (Oracle) 	ext4_mpage_readpages(inode, rac, NULL);
3244ac27a0ecSDave Kleikamp }
3245ac27a0ecSDave Kleikamp 
32467ba13abbSMatthew Wilcox (Oracle) static void ext4_invalidate_folio(struct folio *folio, size_t offset,
32477ba13abbSMatthew Wilcox (Oracle) 				size_t length)
3248ac27a0ecSDave Kleikamp {
3249ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_invalidate_folio(folio, offset, length);
32500562e0baSJiaying Zhang 
32514520fb3cSJan Kara 	/* No journalling happens on data buffers when this function is used */
32527ba13abbSMatthew Wilcox (Oracle) 	WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
32534520fb3cSJan Kara 
32547ba13abbSMatthew Wilcox (Oracle) 	block_invalidate_folio(folio, offset, length);
32554520fb3cSJan Kara }
32564520fb3cSJan Kara 
3257ccd16945SMatthew Wilcox (Oracle) static int __ext4_journalled_invalidate_folio(struct folio *folio,
3258ccd16945SMatthew Wilcox (Oracle) 					    size_t offset, size_t length)
32594520fb3cSJan Kara {
3260ccd16945SMatthew Wilcox (Oracle) 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
32614520fb3cSJan Kara 
3262ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_journalled_invalidate_folio(folio, offset, length);
32634520fb3cSJan Kara 
3264744692dcSJiaying Zhang 	/*
3265ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
3266ac27a0ecSDave Kleikamp 	 */
3267ccd16945SMatthew Wilcox (Oracle) 	if (offset == 0 && length == folio_size(folio))
3268ccd16945SMatthew Wilcox (Oracle) 		folio_clear_checked(folio);
3269ac27a0ecSDave Kleikamp 
3270ccd16945SMatthew Wilcox (Oracle) 	return jbd2_journal_invalidate_folio(journal, folio, offset, length);
327153e87268SJan Kara }
327253e87268SJan Kara 
327353e87268SJan Kara /* Wrapper for aops... */
3274ccd16945SMatthew Wilcox (Oracle) static void ext4_journalled_invalidate_folio(struct folio *folio,
3275ccd16945SMatthew Wilcox (Oracle) 					   size_t offset,
3276ccd16945SMatthew Wilcox (Oracle) 					   size_t length)
327753e87268SJan Kara {
3278ccd16945SMatthew Wilcox (Oracle) 	WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3279ac27a0ecSDave Kleikamp }
3280ac27a0ecSDave Kleikamp 
32813c402f15SMatthew Wilcox (Oracle) static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3282ac27a0ecSDave Kleikamp {
32833c402f15SMatthew Wilcox (Oracle) 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
3284ac27a0ecSDave Kleikamp 
32853c402f15SMatthew Wilcox (Oracle) 	trace_ext4_releasepage(&folio->page);
32860562e0baSJiaying Zhang 
3287e1c36595SJan Kara 	/* Page has dirty journalled data -> cannot release */
32883c402f15SMatthew Wilcox (Oracle) 	if (folio_test_checked(folio))
32893c402f15SMatthew Wilcox (Oracle) 		return false;
32900390131bSFrank Mayhar 	if (journal)
3291c56a6eb0SMatthew Wilcox (Oracle) 		return jbd2_journal_try_to_free_buffers(journal, folio);
32920390131bSFrank Mayhar 	else
329368189fefSMatthew Wilcox (Oracle) 		return try_to_free_buffers(folio);
3294ac27a0ecSDave Kleikamp }
3295ac27a0ecSDave Kleikamp 
3296b8a6176cSJan Kara static bool ext4_inode_datasync_dirty(struct inode *inode)
3297b8a6176cSJan Kara {
3298b8a6176cSJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3299b8a6176cSJan Kara 
3300aa75f4d3SHarshad Shirwadkar 	if (journal) {
3301aa75f4d3SHarshad Shirwadkar 		if (jbd2_transaction_committed(journal,
3302aa75f4d3SHarshad Shirwadkar 			EXT4_I(inode)->i_datasync_tid))
3303d0520df7SAndrea Righi 			return false;
3304d0520df7SAndrea Righi 		if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
33051ceecb53SHarshad Shirwadkar 			return !list_empty(&EXT4_I(inode)->i_fc_list);
3306d0520df7SAndrea Righi 		return true;
3307aa75f4d3SHarshad Shirwadkar 	}
3308aa75f4d3SHarshad Shirwadkar 
3309b8a6176cSJan Kara 	/* Any metadata buffers to write? */
3310b8a6176cSJan Kara 	if (!list_empty(&inode->i_mapping->private_list))
3311b8a6176cSJan Kara 		return true;
3312b8a6176cSJan Kara 	return inode->i_state & I_DIRTY_DATASYNC;
3313b8a6176cSJan Kara }
3314b8a6176cSJan Kara 
3315c8fdfe29SMatthew Bobrowski static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3316c8fdfe29SMatthew Bobrowski 			   struct ext4_map_blocks *map, loff_t offset,
3317de205114SChristoph Hellwig 			   loff_t length, unsigned int flags)
3318364443cbSJan Kara {
3319c8fdfe29SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3320c8fdfe29SMatthew Bobrowski 
3321c8fdfe29SMatthew Bobrowski 	/*
3322c8fdfe29SMatthew Bobrowski 	 * Writes that span EOF might trigger an I/O size update on completion,
3323c8fdfe29SMatthew Bobrowski 	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3324c8fdfe29SMatthew Bobrowski 	 * there is no other metadata changes being made or are pending.
3325c8fdfe29SMatthew Bobrowski 	 */
3326c8fdfe29SMatthew Bobrowski 	iomap->flags = 0;
3327c8fdfe29SMatthew Bobrowski 	if (ext4_inode_datasync_dirty(inode) ||
3328c8fdfe29SMatthew Bobrowski 	    offset + length > i_size_read(inode))
3329c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_DIRTY;
3330c8fdfe29SMatthew Bobrowski 
3331c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_NEW)
3332c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_NEW;
3333c8fdfe29SMatthew Bobrowski 
3334de205114SChristoph Hellwig 	if (flags & IOMAP_DAX)
3335c8fdfe29SMatthew Bobrowski 		iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3336de205114SChristoph Hellwig 	else
3337de205114SChristoph Hellwig 		iomap->bdev = inode->i_sb->s_bdev;
3338c8fdfe29SMatthew Bobrowski 	iomap->offset = (u64) map->m_lblk << blkbits;
3339c8fdfe29SMatthew Bobrowski 	iomap->length = (u64) map->m_len << blkbits;
3340c8fdfe29SMatthew Bobrowski 
33416386722aSRitesh Harjani 	if ((map->m_flags & EXT4_MAP_MAPPED) &&
33426386722aSRitesh Harjani 	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
33436386722aSRitesh Harjani 		iomap->flags |= IOMAP_F_MERGED;
33446386722aSRitesh Harjani 
3345c8fdfe29SMatthew Bobrowski 	/*
3346c8fdfe29SMatthew Bobrowski 	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3347c8fdfe29SMatthew Bobrowski 	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3348c8fdfe29SMatthew Bobrowski 	 * set. In order for any allocated unwritten extents to be converted
3349c8fdfe29SMatthew Bobrowski 	 * into written extents correctly within the ->end_io() handler, we
3350c8fdfe29SMatthew Bobrowski 	 * need to ensure that the iomap->type is set appropriately. Hence, the
3351c8fdfe29SMatthew Bobrowski 	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3352c8fdfe29SMatthew Bobrowski 	 * been set first.
3353c8fdfe29SMatthew Bobrowski 	 */
3354c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3355c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_UNWRITTEN;
3356c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3357de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3358de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3359c8fdfe29SMatthew Bobrowski 	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3360c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_MAPPED;
3361c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3362de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3363de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3364c8fdfe29SMatthew Bobrowski 	} else {
3365c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_HOLE;
3366c8fdfe29SMatthew Bobrowski 		iomap->addr = IOMAP_NULL_ADDR;
3367c8fdfe29SMatthew Bobrowski 	}
3368c8fdfe29SMatthew Bobrowski }
3369c8fdfe29SMatthew Bobrowski 
3370f063db5eSMatthew Bobrowski static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3371f063db5eSMatthew Bobrowski 			    unsigned int flags)
3372f063db5eSMatthew Bobrowski {
3373f063db5eSMatthew Bobrowski 	handle_t *handle;
3374378f32baSMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3375378f32baSMatthew Bobrowski 	int ret, dio_credits, m_flags = 0, retries = 0;
3376f063db5eSMatthew Bobrowski 
3377f063db5eSMatthew Bobrowski 	/*
3378f063db5eSMatthew Bobrowski 	 * Trim the mapping request to the maximum value that we can map at
3379f063db5eSMatthew Bobrowski 	 * once for direct I/O.
3380f063db5eSMatthew Bobrowski 	 */
3381f063db5eSMatthew Bobrowski 	if (map->m_len > DIO_MAX_BLOCKS)
3382f063db5eSMatthew Bobrowski 		map->m_len = DIO_MAX_BLOCKS;
3383f063db5eSMatthew Bobrowski 	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3384f063db5eSMatthew Bobrowski 
3385f063db5eSMatthew Bobrowski retry:
3386f063db5eSMatthew Bobrowski 	/*
3387f063db5eSMatthew Bobrowski 	 * Either we allocate blocks and then don't get an unwritten extent, so
3388f063db5eSMatthew Bobrowski 	 * in that case we have reserved enough credits. Or, the blocks are
3389f063db5eSMatthew Bobrowski 	 * already allocated and unwritten. In that case, the extent conversion
3390f063db5eSMatthew Bobrowski 	 * fits into the credits as well.
3391f063db5eSMatthew Bobrowski 	 */
3392f063db5eSMatthew Bobrowski 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3393f063db5eSMatthew Bobrowski 	if (IS_ERR(handle))
3394f063db5eSMatthew Bobrowski 		return PTR_ERR(handle);
3395f063db5eSMatthew Bobrowski 
3396378f32baSMatthew Bobrowski 	/*
3397378f32baSMatthew Bobrowski 	 * DAX and direct I/O are the only two operations that are currently
3398378f32baSMatthew Bobrowski 	 * supported with IOMAP_WRITE.
3399378f32baSMatthew Bobrowski 	 */
3400952da063SChristoph Hellwig 	WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3401952da063SChristoph Hellwig 	if (flags & IOMAP_DAX)
3402378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3403378f32baSMatthew Bobrowski 	/*
3404378f32baSMatthew Bobrowski 	 * We use i_size instead of i_disksize here because delalloc writeback
3405378f32baSMatthew Bobrowski 	 * can complete at any point during the I/O and subsequently push the
3406378f32baSMatthew Bobrowski 	 * i_disksize out to i_size. This could be beyond where direct I/O is
3407378f32baSMatthew Bobrowski 	 * happening and thus expose allocated blocks to direct I/O reads.
3408378f32baSMatthew Bobrowski 	 */
3409d0b040f5SJan Kara 	else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3410378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE;
3411378f32baSMatthew Bobrowski 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3412378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3413378f32baSMatthew Bobrowski 
3414378f32baSMatthew Bobrowski 	ret = ext4_map_blocks(handle, inode, map, m_flags);
3415378f32baSMatthew Bobrowski 
3416378f32baSMatthew Bobrowski 	/*
3417378f32baSMatthew Bobrowski 	 * We cannot fill holes in indirect tree based inodes as that could
3418378f32baSMatthew Bobrowski 	 * expose stale data in the case of a crash. Use the magic error code
3419378f32baSMatthew Bobrowski 	 * to fallback to buffered I/O.
3420378f32baSMatthew Bobrowski 	 */
3421378f32baSMatthew Bobrowski 	if (!m_flags && !ret)
3422378f32baSMatthew Bobrowski 		ret = -ENOTBLK;
3423f063db5eSMatthew Bobrowski 
3424f063db5eSMatthew Bobrowski 	ext4_journal_stop(handle);
3425f063db5eSMatthew Bobrowski 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3426f063db5eSMatthew Bobrowski 		goto retry;
3427f063db5eSMatthew Bobrowski 
3428f063db5eSMatthew Bobrowski 	return ret;
3429f063db5eSMatthew Bobrowski }
3430f063db5eSMatthew Bobrowski 
3431f063db5eSMatthew Bobrowski 
3432364443cbSJan Kara static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3433c039b997SGoldwyn Rodrigues 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3434364443cbSJan Kara {
3435364443cbSJan Kara 	int ret;
343609edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
343709edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3438364443cbSJan Kara 
3439bcd8e91fSTheodore Ts'o 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3440bcd8e91fSTheodore Ts'o 		return -EINVAL;
34417046ae35SAndreas Gruenbacher 
3442364443cbSJan Kara 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3443364443cbSJan Kara 		return -ERANGE;
3444364443cbSJan Kara 
344509edf4d3SMatthew Bobrowski 	/*
344609edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical blocks respectively.
344709edf4d3SMatthew Bobrowski 	 */
344809edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
344909edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
345009edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3451364443cbSJan Kara 
34529faac62dSRitesh Harjani 	if (flags & IOMAP_WRITE) {
34539faac62dSRitesh Harjani 		/*
34549faac62dSRitesh Harjani 		 * We check here if the blocks are already allocated, then we
34559faac62dSRitesh Harjani 		 * don't need to start a journal txn and we can directly return
34569faac62dSRitesh Harjani 		 * the mapping information. This could boost performance
34579faac62dSRitesh Harjani 		 * especially in multi-threaded overwrite requests.
34589faac62dSRitesh Harjani 		 */
34599faac62dSRitesh Harjani 		if (offset + length <= i_size_read(inode)) {
3460545052e9SChristoph Hellwig 			ret = ext4_map_blocks(NULL, inode, &map, 0);
34619faac62dSRitesh Harjani 			if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
34629faac62dSRitesh Harjani 				goto out;
34639faac62dSRitesh Harjani 		}
34649faac62dSRitesh Harjani 		ret = ext4_iomap_alloc(inode, &map, flags);
34659faac62dSRitesh Harjani 	} else {
34669faac62dSRitesh Harjani 		ret = ext4_map_blocks(NULL, inode, &map, 0);
34679faac62dSRitesh Harjani 	}
3468f063db5eSMatthew Bobrowski 
3469545052e9SChristoph Hellwig 	if (ret < 0)
3470545052e9SChristoph Hellwig 		return ret;
34719faac62dSRitesh Harjani out:
347238ea50daSEric Biggers 	/*
347338ea50daSEric Biggers 	 * When inline encryption is enabled, sometimes I/O to an encrypted file
347438ea50daSEric Biggers 	 * has to be broken up to guarantee DUN contiguity.  Handle this by
347538ea50daSEric Biggers 	 * limiting the length of the mapping returned.
347638ea50daSEric Biggers 	 */
347738ea50daSEric Biggers 	map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
347838ea50daSEric Biggers 
3479de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3480545052e9SChristoph Hellwig 
3481364443cbSJan Kara 	return 0;
3482364443cbSJan Kara }
3483364443cbSJan Kara 
34848cd115bdSJan Kara static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
34858cd115bdSJan Kara 		loff_t length, unsigned flags, struct iomap *iomap,
34868cd115bdSJan Kara 		struct iomap *srcmap)
34878cd115bdSJan Kara {
34888cd115bdSJan Kara 	int ret;
34898cd115bdSJan Kara 
34908cd115bdSJan Kara 	/*
34918cd115bdSJan Kara 	 * Even for writes we don't need to allocate blocks, so just pretend
34928cd115bdSJan Kara 	 * we are reading to save overhead of starting a transaction.
34938cd115bdSJan Kara 	 */
34948cd115bdSJan Kara 	flags &= ~IOMAP_WRITE;
34958cd115bdSJan Kara 	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
34968cd115bdSJan Kara 	WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
34978cd115bdSJan Kara 	return ret;
34988cd115bdSJan Kara }
34998cd115bdSJan Kara 
3500776722e8SJan Kara static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3501776722e8SJan Kara 			  ssize_t written, unsigned flags, struct iomap *iomap)
3502776722e8SJan Kara {
3503378f32baSMatthew Bobrowski 	/*
3504378f32baSMatthew Bobrowski 	 * Check to see whether an error occurred while writing out the data to
3505378f32baSMatthew Bobrowski 	 * the allocated blocks. If so, return the magic error code so that we
3506378f32baSMatthew Bobrowski 	 * fallback to buffered I/O and attempt to complete the remainder of
3507378f32baSMatthew Bobrowski 	 * the I/O. Any blocks that may have been allocated in preparation for
3508378f32baSMatthew Bobrowski 	 * the direct I/O will be reused during buffered I/O.
3509378f32baSMatthew Bobrowski 	 */
3510378f32baSMatthew Bobrowski 	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3511378f32baSMatthew Bobrowski 		return -ENOTBLK;
3512378f32baSMatthew Bobrowski 
3513776722e8SJan Kara 	return 0;
3514776722e8SJan Kara }
3515776722e8SJan Kara 
35168ff6daa1SChristoph Hellwig const struct iomap_ops ext4_iomap_ops = {
3517364443cbSJan Kara 	.iomap_begin		= ext4_iomap_begin,
3518776722e8SJan Kara 	.iomap_end		= ext4_iomap_end,
3519364443cbSJan Kara };
3520364443cbSJan Kara 
35218cd115bdSJan Kara const struct iomap_ops ext4_iomap_overwrite_ops = {
35228cd115bdSJan Kara 	.iomap_begin		= ext4_iomap_overwrite_begin,
35238cd115bdSJan Kara 	.iomap_end		= ext4_iomap_end,
35248cd115bdSJan Kara };
35258cd115bdSJan Kara 
352609edf4d3SMatthew Bobrowski static bool ext4_iomap_is_delalloc(struct inode *inode,
352709edf4d3SMatthew Bobrowski 				   struct ext4_map_blocks *map)
352809edf4d3SMatthew Bobrowski {
352909edf4d3SMatthew Bobrowski 	struct extent_status es;
353009edf4d3SMatthew Bobrowski 	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
353109edf4d3SMatthew Bobrowski 
353209edf4d3SMatthew Bobrowski 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
353309edf4d3SMatthew Bobrowski 				  map->m_lblk, end, &es);
353409edf4d3SMatthew Bobrowski 
353509edf4d3SMatthew Bobrowski 	if (!es.es_len || es.es_lblk > end)
353609edf4d3SMatthew Bobrowski 		return false;
353709edf4d3SMatthew Bobrowski 
353809edf4d3SMatthew Bobrowski 	if (es.es_lblk > map->m_lblk) {
353909edf4d3SMatthew Bobrowski 		map->m_len = es.es_lblk - map->m_lblk;
354009edf4d3SMatthew Bobrowski 		return false;
354109edf4d3SMatthew Bobrowski 	}
354209edf4d3SMatthew Bobrowski 
354309edf4d3SMatthew Bobrowski 	offset = map->m_lblk - es.es_lblk;
354409edf4d3SMatthew Bobrowski 	map->m_len = es.es_len - offset;
354509edf4d3SMatthew Bobrowski 
354609edf4d3SMatthew Bobrowski 	return true;
354709edf4d3SMatthew Bobrowski }
354809edf4d3SMatthew Bobrowski 
354909edf4d3SMatthew Bobrowski static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
355009edf4d3SMatthew Bobrowski 				   loff_t length, unsigned int flags,
355109edf4d3SMatthew Bobrowski 				   struct iomap *iomap, struct iomap *srcmap)
355209edf4d3SMatthew Bobrowski {
355309edf4d3SMatthew Bobrowski 	int ret;
355409edf4d3SMatthew Bobrowski 	bool delalloc = false;
355509edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
355609edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
355709edf4d3SMatthew Bobrowski 
355809edf4d3SMatthew Bobrowski 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
355909edf4d3SMatthew Bobrowski 		return -EINVAL;
356009edf4d3SMatthew Bobrowski 
35617cb476f8SJan Kara 	if (ext4_has_inline_data(inode)) {
35627cb476f8SJan Kara 		ret = ext4_inline_data_iomap(inode, iomap);
3563ba5843f5SJan Kara 		if (ret != -EAGAIN) {
3564ed923b57SMatthew Wilcox 			if (ret == 0 && offset >= iomap->length)
3565ba5843f5SJan Kara 				ret = -ENOENT;
3566ba5843f5SJan Kara 			return ret;
3567ba5843f5SJan Kara 		}
3568ba5843f5SJan Kara 	}
356912735f88SJan Kara 
357009edf4d3SMatthew Bobrowski 	/*
357109edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical block respectively.
357209edf4d3SMatthew Bobrowski 	 */
357309edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
357409edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
357509edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
357612735f88SJan Kara 
3577b2c57642SRitesh Harjani 	/*
3578b2c57642SRitesh Harjani 	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3579b2c57642SRitesh Harjani 	 * So handle it here itself instead of querying ext4_map_blocks().
3580b2c57642SRitesh Harjani 	 * Since ext4_map_blocks() will warn about it and will return
3581b2c57642SRitesh Harjani 	 * -EIO error.
3582b2c57642SRitesh Harjani 	 */
3583b2c57642SRitesh Harjani 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3584b2c57642SRitesh Harjani 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3585b2c57642SRitesh Harjani 
3586b2c57642SRitesh Harjani 		if (offset >= sbi->s_bitmap_maxbytes) {
3587b2c57642SRitesh Harjani 			map.m_flags = 0;
3588b2c57642SRitesh Harjani 			goto set_iomap;
3589b2c57642SRitesh Harjani 		}
3590b2c57642SRitesh Harjani 	}
3591b2c57642SRitesh Harjani 
359212735f88SJan Kara 	ret = ext4_map_blocks(NULL, inode, &map, 0);
3593ba5843f5SJan Kara 	if (ret < 0)
3594ba5843f5SJan Kara 		return ret;
3595914f82a3SJan Kara 	if (ret == 0)
359609edf4d3SMatthew Bobrowski 		delalloc = ext4_iomap_is_delalloc(inode, &map);
359709edf4d3SMatthew Bobrowski 
3598b2c57642SRitesh Harjani set_iomap:
3599de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
360009edf4d3SMatthew Bobrowski 	if (delalloc && iomap->type == IOMAP_HOLE)
360109edf4d3SMatthew Bobrowski 		iomap->type = IOMAP_DELALLOC;
360209edf4d3SMatthew Bobrowski 
360309edf4d3SMatthew Bobrowski 	return 0;
3604914f82a3SJan Kara }
3605914f82a3SJan Kara 
360609edf4d3SMatthew Bobrowski const struct iomap_ops ext4_iomap_report_ops = {
360709edf4d3SMatthew Bobrowski 	.iomap_begin = ext4_iomap_begin_report,
360809edf4d3SMatthew Bobrowski };
36094c0425ffSMingming Cao 
3610ac27a0ecSDave Kleikamp /*
36116b1f86f8SLinus Torvalds  * Whenever the folio is being dirtied, corresponding buffers should already
36126b1f86f8SLinus Torvalds  * be attached to the transaction (we take care of this in ext4_page_mkwrite()
36136b1f86f8SLinus Torvalds  * and ext4_write_begin()). However we cannot move buffers to dirty transaction
36146b1f86f8SLinus Torvalds  * lists here because ->dirty_folio is called under VFS locks and the folio
36152bb8dd40SJan Kara  * is not necessarily locked.
3616ac27a0ecSDave Kleikamp  *
3617187c82cbSMatthew Wilcox (Oracle)  * We cannot just dirty the folio and leave attached buffers clean, because the
3618ac27a0ecSDave Kleikamp  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3619ac27a0ecSDave Kleikamp  * or jbddirty because all the journalling code will explode.
3620ac27a0ecSDave Kleikamp  *
3621187c82cbSMatthew Wilcox (Oracle)  * So what we do is to mark the folio "pending dirty" and next time writepage
3622ac27a0ecSDave Kleikamp  * is called, propagate that into the buffers appropriately.
3623ac27a0ecSDave Kleikamp  */
3624187c82cbSMatthew Wilcox (Oracle) static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3625187c82cbSMatthew Wilcox (Oracle) 		struct folio *folio)
3626ac27a0ecSDave Kleikamp {
36270f252336SMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
3628187c82cbSMatthew Wilcox (Oracle) 	folio_set_checked(folio);
3629187c82cbSMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
3630ac27a0ecSDave Kleikamp }
3631ac27a0ecSDave Kleikamp 
3632e621900aSMatthew Wilcox (Oracle) static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
36336dcc693bSJan Kara {
3634e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3635e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
3636e621900aSMatthew Wilcox (Oracle) 	return block_dirty_folio(mapping, folio);
36376dcc693bSJan Kara }
36386dcc693bSJan Kara 
36390e6895baSRitesh Harjani static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
36400e6895baSRitesh Harjani 				    struct file *file, sector_t *span)
36410e6895baSRitesh Harjani {
36420e6895baSRitesh Harjani 	return iomap_swapfile_activate(sis, file, span,
36430e6895baSRitesh Harjani 				       &ext4_iomap_report_ops);
36440e6895baSRitesh Harjani }
36450e6895baSRitesh Harjani 
364674d553aaSTheodore Ts'o static const struct address_space_operations ext4_aops = {
3647fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
36486311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
364943ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
365020970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3651bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
365274d553aaSTheodore Ts'o 	.write_end		= ext4_write_end,
3653e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
3654617ba13bSMingming Cao 	.bmap			= ext4_bmap,
36557ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
36563c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3657378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
365867235182SMatthew Wilcox (Oracle) 	.migrate_folio		= buffer_migrate_folio,
36598ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3660aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36610e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3662ac27a0ecSDave Kleikamp };
3663ac27a0ecSDave Kleikamp 
3664617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
3665fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
36666311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
366743ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
366820970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3669bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
3670bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
3671187c82cbSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_journalled_dirty_folio,
3672617ba13bSMingming Cao 	.bmap			= ext4_bmap,
3673ccd16945SMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_journalled_invalidate_folio,
36743c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3675378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
36768ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3677aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36780e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3679ac27a0ecSDave Kleikamp };
3680ac27a0ecSDave Kleikamp 
368164769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
3682fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
36836311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
368443ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
368520970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
368664769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
368764769240SAlex Tomas 	.write_end		= ext4_da_write_end,
3688e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
368964769240SAlex Tomas 	.bmap			= ext4_bmap,
36907ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
36913c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3692378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
369367235182SMatthew Wilcox (Oracle) 	.migrate_folio		= buffer_migrate_folio,
36948ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3695aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36960e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
369764769240SAlex Tomas };
369864769240SAlex Tomas 
36995f0663bbSDan Williams static const struct address_space_operations ext4_dax_aops = {
37005f0663bbSDan Williams 	.writepages		= ext4_dax_writepages,
37015f0663bbSDan Williams 	.direct_IO		= noop_direct_IO,
370246de8b97SMatthew Wilcox (Oracle) 	.dirty_folio		= noop_dirty_folio,
370394dbb631SToshi Kani 	.bmap			= ext4_bmap,
37040e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
37055f0663bbSDan Williams };
37065f0663bbSDan Williams 
3707617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
3708ac27a0ecSDave Kleikamp {
37093d2b1582SLukas Czerner 	switch (ext4_inode_journal_mode(inode)) {
37103d2b1582SLukas Czerner 	case EXT4_INODE_ORDERED_DATA_MODE:
37113d2b1582SLukas Czerner 	case EXT4_INODE_WRITEBACK_DATA_MODE:
37123d2b1582SLukas Czerner 		break;
37133d2b1582SLukas Czerner 	case EXT4_INODE_JOURNAL_DATA_MODE:
3714617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
371574d553aaSTheodore Ts'o 		return;
37163d2b1582SLukas Czerner 	default:
37173d2b1582SLukas Czerner 		BUG();
37183d2b1582SLukas Czerner 	}
37195f0663bbSDan Williams 	if (IS_DAX(inode))
37205f0663bbSDan Williams 		inode->i_mapping->a_ops = &ext4_dax_aops;
37215f0663bbSDan Williams 	else if (test_opt(inode->i_sb, DELALLOC))
372274d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_da_aops;
372374d553aaSTheodore Ts'o 	else
372474d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_aops;
3725ac27a0ecSDave Kleikamp }
3726ac27a0ecSDave Kleikamp 
3727923ae0ffSRoss Zwisler static int __ext4_block_zero_page_range(handle_t *handle,
3728d863dc36SLukas Czerner 		struct address_space *mapping, loff_t from, loff_t length)
3729d863dc36SLukas Czerner {
373009cbfeafSKirill A. Shutemov 	ext4_fsblk_t index = from >> PAGE_SHIFT;
373109cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3732923ae0ffSRoss Zwisler 	unsigned blocksize, pos;
3733d863dc36SLukas Czerner 	ext4_lblk_t iblock;
3734d863dc36SLukas Czerner 	struct inode *inode = mapping->host;
3735d863dc36SLukas Czerner 	struct buffer_head *bh;
3736d863dc36SLukas Czerner 	struct page *page;
3737d863dc36SLukas Czerner 	int err = 0;
3738d863dc36SLukas Czerner 
373909cbfeafSKirill A. Shutemov 	page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3740c62d2555SMichal Hocko 				   mapping_gfp_constraint(mapping, ~__GFP_FS));
3741d863dc36SLukas Czerner 	if (!page)
3742d863dc36SLukas Czerner 		return -ENOMEM;
3743d863dc36SLukas Czerner 
3744d863dc36SLukas Czerner 	blocksize = inode->i_sb->s_blocksize;
3745d863dc36SLukas Czerner 
374609cbfeafSKirill A. Shutemov 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3747d863dc36SLukas Czerner 
3748d863dc36SLukas Czerner 	if (!page_has_buffers(page))
3749d863dc36SLukas Czerner 		create_empty_buffers(page, blocksize, 0);
3750d863dc36SLukas Czerner 
3751d863dc36SLukas Czerner 	/* Find the buffer that contains "offset" */
3752d863dc36SLukas Czerner 	bh = page_buffers(page);
3753d863dc36SLukas Czerner 	pos = blocksize;
3754d863dc36SLukas Czerner 	while (offset >= pos) {
3755d863dc36SLukas Czerner 		bh = bh->b_this_page;
3756d863dc36SLukas Czerner 		iblock++;
3757d863dc36SLukas Czerner 		pos += blocksize;
3758d863dc36SLukas Czerner 	}
3759d863dc36SLukas Czerner 	if (buffer_freed(bh)) {
3760d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "freed: skip");
3761d863dc36SLukas Czerner 		goto unlock;
3762d863dc36SLukas Czerner 	}
3763d863dc36SLukas Czerner 	if (!buffer_mapped(bh)) {
3764d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "unmapped");
3765d863dc36SLukas Czerner 		ext4_get_block(inode, iblock, bh, 0);
3766d863dc36SLukas Czerner 		/* unmapped? It's a hole - nothing to do */
3767d863dc36SLukas Czerner 		if (!buffer_mapped(bh)) {
3768d863dc36SLukas Czerner 			BUFFER_TRACE(bh, "still unmapped");
3769d863dc36SLukas Czerner 			goto unlock;
3770d863dc36SLukas Czerner 		}
3771d863dc36SLukas Czerner 	}
3772d863dc36SLukas Czerner 
3773d863dc36SLukas Czerner 	/* Ok, it's mapped. Make sure it's up-to-date */
3774d863dc36SLukas Czerner 	if (PageUptodate(page))
3775d863dc36SLukas Czerner 		set_buffer_uptodate(bh);
3776d863dc36SLukas Czerner 
3777d863dc36SLukas Czerner 	if (!buffer_uptodate(bh)) {
37782d069c08Szhangyi (F) 		err = ext4_read_bh_lock(bh, 0, true);
37792d069c08Szhangyi (F) 		if (err)
3780d863dc36SLukas Czerner 			goto unlock;
37814f74d15fSEric Biggers 		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3782c9c7429cSMichael Halcrow 			/* We expect the key to be set. */
3783a7550b30SJaegeuk Kim 			BUG_ON(!fscrypt_has_encryption_key(inode));
3784834f1565SEric Biggers 			err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3785834f1565SEric Biggers 							       bh_offset(bh));
3786834f1565SEric Biggers 			if (err) {
3787834f1565SEric Biggers 				clear_buffer_uptodate(bh);
3788834f1565SEric Biggers 				goto unlock;
3789834f1565SEric Biggers 			}
3790c9c7429cSMichael Halcrow 		}
3791d863dc36SLukas Czerner 	}
3792d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3793d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "get write access");
3794188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
3795188c299eSJan Kara 						    EXT4_JTR_NONE);
3796d863dc36SLukas Czerner 		if (err)
3797d863dc36SLukas Czerner 			goto unlock;
3798d863dc36SLukas Czerner 	}
3799d863dc36SLukas Czerner 	zero_user(page, offset, length);
3800d863dc36SLukas Czerner 	BUFFER_TRACE(bh, "zeroed end of block");
3801d863dc36SLukas Czerner 
3802d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3803d863dc36SLukas Czerner 		err = ext4_handle_dirty_metadata(handle, inode, bh);
38040713ed0cSLukas Czerner 	} else {
3805353eefd3Sjon ernst 		err = 0;
3806d863dc36SLukas Czerner 		mark_buffer_dirty(bh);
38073957ef53SJan Kara 		if (ext4_should_order_data(inode))
380873131fbbSRoss Zwisler 			err = ext4_jbd2_inode_add_write(handle, inode, from,
380973131fbbSRoss Zwisler 					length);
38100713ed0cSLukas Czerner 	}
3811d863dc36SLukas Czerner 
3812d863dc36SLukas Czerner unlock:
3813d863dc36SLukas Czerner 	unlock_page(page);
381409cbfeafSKirill A. Shutemov 	put_page(page);
3815d863dc36SLukas Czerner 	return err;
3816d863dc36SLukas Czerner }
3817d863dc36SLukas Czerner 
381894350ab5SMatthew Wilcox /*
3819923ae0ffSRoss Zwisler  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3820923ae0ffSRoss Zwisler  * starting from file offset 'from'.  The range to be zero'd must
3821923ae0ffSRoss Zwisler  * be contained with in one block.  If the specified range exceeds
3822923ae0ffSRoss Zwisler  * the end of the block it will be shortened to end of the block
38233088e5a5SBhaskar Chowdhury  * that corresponds to 'from'
3824923ae0ffSRoss Zwisler  */
3825923ae0ffSRoss Zwisler static int ext4_block_zero_page_range(handle_t *handle,
3826923ae0ffSRoss Zwisler 		struct address_space *mapping, loff_t from, loff_t length)
3827923ae0ffSRoss Zwisler {
3828923ae0ffSRoss Zwisler 	struct inode *inode = mapping->host;
382909cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3830923ae0ffSRoss Zwisler 	unsigned blocksize = inode->i_sb->s_blocksize;
3831923ae0ffSRoss Zwisler 	unsigned max = blocksize - (offset & (blocksize - 1));
3832923ae0ffSRoss Zwisler 
3833923ae0ffSRoss Zwisler 	/*
3834923ae0ffSRoss Zwisler 	 * correct length if it does not fall between
3835923ae0ffSRoss Zwisler 	 * 'from' and the end of the block
3836923ae0ffSRoss Zwisler 	 */
3837923ae0ffSRoss Zwisler 	if (length > max || length < 0)
3838923ae0ffSRoss Zwisler 		length = max;
3839923ae0ffSRoss Zwisler 
384047e69351SJan Kara 	if (IS_DAX(inode)) {
3841c6f40468SChristoph Hellwig 		return dax_zero_range(inode, from, length, NULL,
384247e69351SJan Kara 				      &ext4_iomap_ops);
384347e69351SJan Kara 	}
3844923ae0ffSRoss Zwisler 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3845923ae0ffSRoss Zwisler }
3846923ae0ffSRoss Zwisler 
3847923ae0ffSRoss Zwisler /*
384894350ab5SMatthew Wilcox  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
384994350ab5SMatthew Wilcox  * up to the end of the block which corresponds to `from'.
385094350ab5SMatthew Wilcox  * This required during truncate. We need to physically zero the tail end
385194350ab5SMatthew Wilcox  * of that block so it doesn't yield old data if the file is later grown.
385294350ab5SMatthew Wilcox  */
3853c197855eSStephen Hemminger static int ext4_block_truncate_page(handle_t *handle,
385494350ab5SMatthew Wilcox 		struct address_space *mapping, loff_t from)
385594350ab5SMatthew Wilcox {
385609cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
385794350ab5SMatthew Wilcox 	unsigned length;
385894350ab5SMatthew Wilcox 	unsigned blocksize;
385994350ab5SMatthew Wilcox 	struct inode *inode = mapping->host;
386094350ab5SMatthew Wilcox 
38610d06863fSTheodore Ts'o 	/* If we are processing an encrypted inode during orphan list handling */
3862592ddec7SChandan Rajendra 	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
38630d06863fSTheodore Ts'o 		return 0;
38640d06863fSTheodore Ts'o 
386594350ab5SMatthew Wilcox 	blocksize = inode->i_sb->s_blocksize;
386694350ab5SMatthew Wilcox 	length = blocksize - (offset & (blocksize - 1));
386794350ab5SMatthew Wilcox 
386894350ab5SMatthew Wilcox 	return ext4_block_zero_page_range(handle, mapping, from, length);
386994350ab5SMatthew Wilcox }
387094350ab5SMatthew Wilcox 
3871a87dd18cSLukas Czerner int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3872a87dd18cSLukas Czerner 			     loff_t lstart, loff_t length)
3873a87dd18cSLukas Czerner {
3874a87dd18cSLukas Czerner 	struct super_block *sb = inode->i_sb;
3875a87dd18cSLukas Czerner 	struct address_space *mapping = inode->i_mapping;
3876e1be3a92SLukas Czerner 	unsigned partial_start, partial_end;
3877a87dd18cSLukas Czerner 	ext4_fsblk_t start, end;
3878a87dd18cSLukas Czerner 	loff_t byte_end = (lstart + length - 1);
3879a87dd18cSLukas Czerner 	int err = 0;
3880a87dd18cSLukas Czerner 
3881e1be3a92SLukas Czerner 	partial_start = lstart & (sb->s_blocksize - 1);
3882e1be3a92SLukas Czerner 	partial_end = byte_end & (sb->s_blocksize - 1);
3883e1be3a92SLukas Czerner 
3884a87dd18cSLukas Czerner 	start = lstart >> sb->s_blocksize_bits;
3885a87dd18cSLukas Czerner 	end = byte_end >> sb->s_blocksize_bits;
3886a87dd18cSLukas Czerner 
3887a87dd18cSLukas Czerner 	/* Handle partial zero within the single block */
3888e1be3a92SLukas Czerner 	if (start == end &&
3889e1be3a92SLukas Czerner 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3890a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3891a87dd18cSLukas Czerner 						 lstart, length);
3892a87dd18cSLukas Czerner 		return err;
3893a87dd18cSLukas Czerner 	}
3894a87dd18cSLukas Czerner 	/* Handle partial zero out on the start of the range */
3895e1be3a92SLukas Czerner 	if (partial_start) {
3896a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3897a87dd18cSLukas Czerner 						 lstart, sb->s_blocksize);
3898a87dd18cSLukas Czerner 		if (err)
3899a87dd18cSLukas Czerner 			return err;
3900a87dd18cSLukas Czerner 	}
3901a87dd18cSLukas Czerner 	/* Handle partial zero out on the end of the range */
3902e1be3a92SLukas Czerner 	if (partial_end != sb->s_blocksize - 1)
3903a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3904e1be3a92SLukas Czerner 						 byte_end - partial_end,
3905e1be3a92SLukas Czerner 						 partial_end + 1);
3906a87dd18cSLukas Czerner 	return err;
3907a87dd18cSLukas Czerner }
3908a87dd18cSLukas Czerner 
390991ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
391091ef4cafSDuane Griffin {
391191ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
391291ef4cafSDuane Griffin 		return 1;
391391ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
391491ef4cafSDuane Griffin 		return 1;
391591ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
391691ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
391791ef4cafSDuane Griffin 	return 0;
391891ef4cafSDuane Griffin }
391991ef4cafSDuane Griffin 
3920ac27a0ecSDave Kleikamp /*
392101127848SJan Kara  * We have to make sure i_disksize gets properly updated before we truncate
392201127848SJan Kara  * page cache due to hole punching or zero range. Otherwise i_disksize update
392301127848SJan Kara  * can get lost as it may have been postponed to submission of writeback but
392401127848SJan Kara  * that will never happen after we truncate page cache.
392501127848SJan Kara  */
392601127848SJan Kara int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
392701127848SJan Kara 				      loff_t len)
392801127848SJan Kara {
392901127848SJan Kara 	handle_t *handle;
39304209ae12SHarshad Shirwadkar 	int ret;
39314209ae12SHarshad Shirwadkar 
393201127848SJan Kara 	loff_t size = i_size_read(inode);
393301127848SJan Kara 
39345955102cSAl Viro 	WARN_ON(!inode_is_locked(inode));
393501127848SJan Kara 	if (offset > size || offset + len < size)
393601127848SJan Kara 		return 0;
393701127848SJan Kara 
393801127848SJan Kara 	if (EXT4_I(inode)->i_disksize >= size)
393901127848SJan Kara 		return 0;
394001127848SJan Kara 
394101127848SJan Kara 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
394201127848SJan Kara 	if (IS_ERR(handle))
394301127848SJan Kara 		return PTR_ERR(handle);
394401127848SJan Kara 	ext4_update_i_disksize(inode, size);
39454209ae12SHarshad Shirwadkar 	ret = ext4_mark_inode_dirty(handle, inode);
394601127848SJan Kara 	ext4_journal_stop(handle);
394701127848SJan Kara 
39484209ae12SHarshad Shirwadkar 	return ret;
394901127848SJan Kara }
395001127848SJan Kara 
3951d4f5258eSJan Kara static void ext4_wait_dax_page(struct inode *inode)
3952430657b6SRoss Zwisler {
3953d4f5258eSJan Kara 	filemap_invalidate_unlock(inode->i_mapping);
3954430657b6SRoss Zwisler 	schedule();
3955d4f5258eSJan Kara 	filemap_invalidate_lock(inode->i_mapping);
3956430657b6SRoss Zwisler }
3957430657b6SRoss Zwisler 
3958430657b6SRoss Zwisler int ext4_break_layouts(struct inode *inode)
3959430657b6SRoss Zwisler {
3960430657b6SRoss Zwisler 	struct page *page;
3961430657b6SRoss Zwisler 	int error;
3962430657b6SRoss Zwisler 
3963d4f5258eSJan Kara 	if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
3964430657b6SRoss Zwisler 		return -EINVAL;
3965430657b6SRoss Zwisler 
3966430657b6SRoss Zwisler 	do {
3967430657b6SRoss Zwisler 		page = dax_layout_busy_page(inode->i_mapping);
3968430657b6SRoss Zwisler 		if (!page)
3969430657b6SRoss Zwisler 			return 0;
3970430657b6SRoss Zwisler 
3971430657b6SRoss Zwisler 		error = ___wait_var_event(&page->_refcount,
3972430657b6SRoss Zwisler 				atomic_read(&page->_refcount) == 1,
3973430657b6SRoss Zwisler 				TASK_INTERRUPTIBLE, 0, 0,
3974d4f5258eSJan Kara 				ext4_wait_dax_page(inode));
3975b1f38217SRoss Zwisler 	} while (error == 0);
3976430657b6SRoss Zwisler 
3977430657b6SRoss Zwisler 	return error;
3978430657b6SRoss Zwisler }
3979430657b6SRoss Zwisler 
398001127848SJan Kara /*
3981cca32b7eSRoss Zwisler  * ext4_punch_hole: punches a hole in a file by releasing the blocks
3982a4bb6b64SAllison Henderson  * associated with the given offset and length
3983a4bb6b64SAllison Henderson  *
3984a4bb6b64SAllison Henderson  * @inode:  File inode
3985a4bb6b64SAllison Henderson  * @offset: The offset where the hole will begin
3986a4bb6b64SAllison Henderson  * @len:    The length of the hole
3987a4bb6b64SAllison Henderson  *
39884907cb7bSAnatol Pomozov  * Returns: 0 on success or negative on failure
3989a4bb6b64SAllison Henderson  */
3990a4bb6b64SAllison Henderson 
3991ad5cd4f4SDarrick J. Wong int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3992a4bb6b64SAllison Henderson {
3993ad5cd4f4SDarrick J. Wong 	struct inode *inode = file_inode(file);
399426a4c0c6STheodore Ts'o 	struct super_block *sb = inode->i_sb;
399526a4c0c6STheodore Ts'o 	ext4_lblk_t first_block, stop_block;
399626a4c0c6STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
39972da37622STadeusz Struk 	loff_t first_block_offset, last_block_offset, max_length;
39982da37622STadeusz Struk 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
399926a4c0c6STheodore Ts'o 	handle_t *handle;
400026a4c0c6STheodore Ts'o 	unsigned int credits;
40014209ae12SHarshad Shirwadkar 	int ret = 0, ret2 = 0;
400226a4c0c6STheodore Ts'o 
4003b8a86845SLukas Czerner 	trace_ext4_punch_hole(inode, offset, length, 0);
4004aaddea81SZheng Liu 
400526a4c0c6STheodore Ts'o 	/*
400626a4c0c6STheodore Ts'o 	 * Write out all dirty pages to avoid race conditions
400726a4c0c6STheodore Ts'o 	 * Then release them.
400826a4c0c6STheodore Ts'o 	 */
4009cca32b7eSRoss Zwisler 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
401026a4c0c6STheodore Ts'o 		ret = filemap_write_and_wait_range(mapping, offset,
401126a4c0c6STheodore Ts'o 						   offset + length - 1);
401226a4c0c6STheodore Ts'o 		if (ret)
401326a4c0c6STheodore Ts'o 			return ret;
401426a4c0c6STheodore Ts'o 	}
401526a4c0c6STheodore Ts'o 
40165955102cSAl Viro 	inode_lock(inode);
40179ef06cecSLukas Czerner 
401826a4c0c6STheodore Ts'o 	/* No need to punch hole beyond i_size */
401926a4c0c6STheodore Ts'o 	if (offset >= inode->i_size)
402026a4c0c6STheodore Ts'o 		goto out_mutex;
402126a4c0c6STheodore Ts'o 
402226a4c0c6STheodore Ts'o 	/*
402326a4c0c6STheodore Ts'o 	 * If the hole extends beyond i_size, set the hole
402426a4c0c6STheodore Ts'o 	 * to end after the page that contains i_size
402526a4c0c6STheodore Ts'o 	 */
402626a4c0c6STheodore Ts'o 	if (offset + length > inode->i_size) {
402726a4c0c6STheodore Ts'o 		length = inode->i_size +
402809cbfeafSKirill A. Shutemov 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
402926a4c0c6STheodore Ts'o 		   offset;
403026a4c0c6STheodore Ts'o 	}
403126a4c0c6STheodore Ts'o 
40322da37622STadeusz Struk 	/*
40332da37622STadeusz Struk 	 * For punch hole the length + offset needs to be within one block
40342da37622STadeusz Struk 	 * before last range. Adjust the length if it goes beyond that limit.
40352da37622STadeusz Struk 	 */
40362da37622STadeusz Struk 	max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
40372da37622STadeusz Struk 	if (offset + length > max_length)
40382da37622STadeusz Struk 		length = max_length - offset;
40392da37622STadeusz Struk 
4040a361293fSJan Kara 	if (offset & (sb->s_blocksize - 1) ||
4041a361293fSJan Kara 	    (offset + length) & (sb->s_blocksize - 1)) {
4042a361293fSJan Kara 		/*
4043a361293fSJan Kara 		 * Attach jinode to inode for jbd2 if we do any zeroing of
4044a361293fSJan Kara 		 * partial block
4045a361293fSJan Kara 		 */
4046a361293fSJan Kara 		ret = ext4_inode_attach_jinode(inode);
4047a361293fSJan Kara 		if (ret < 0)
4048a361293fSJan Kara 			goto out_mutex;
4049a361293fSJan Kara 
4050a361293fSJan Kara 	}
4051a361293fSJan Kara 
4052f340b3d9Shongnanli 	/* Wait all existing dio workers, newcomers will block on i_rwsem */
4053ea3d7209SJan Kara 	inode_dio_wait(inode);
4054ea3d7209SJan Kara 
4055ad5cd4f4SDarrick J. Wong 	ret = file_modified(file);
4056ad5cd4f4SDarrick J. Wong 	if (ret)
4057ad5cd4f4SDarrick J. Wong 		goto out_mutex;
4058ad5cd4f4SDarrick J. Wong 
4059ea3d7209SJan Kara 	/*
4060ea3d7209SJan Kara 	 * Prevent page faults from reinstantiating pages we have released from
4061ea3d7209SJan Kara 	 * page cache.
4062ea3d7209SJan Kara 	 */
4063d4f5258eSJan Kara 	filemap_invalidate_lock(mapping);
4064430657b6SRoss Zwisler 
4065430657b6SRoss Zwisler 	ret = ext4_break_layouts(inode);
4066430657b6SRoss Zwisler 	if (ret)
4067430657b6SRoss Zwisler 		goto out_dio;
4068430657b6SRoss Zwisler 
4069a87dd18cSLukas Czerner 	first_block_offset = round_up(offset, sb->s_blocksize);
4070a87dd18cSLukas Czerner 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
407126a4c0c6STheodore Ts'o 
4072a87dd18cSLukas Czerner 	/* Now release the pages and zero block aligned part of pages*/
407301127848SJan Kara 	if (last_block_offset > first_block_offset) {
407401127848SJan Kara 		ret = ext4_update_disksize_before_punch(inode, offset, length);
407501127848SJan Kara 		if (ret)
407601127848SJan Kara 			goto out_dio;
4077a87dd18cSLukas Czerner 		truncate_pagecache_range(inode, first_block_offset,
4078a87dd18cSLukas Czerner 					 last_block_offset);
407901127848SJan Kara 	}
408026a4c0c6STheodore Ts'o 
408126a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
408226a4c0c6STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
408326a4c0c6STheodore Ts'o 	else
408426a4c0c6STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
408526a4c0c6STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
408626a4c0c6STheodore Ts'o 	if (IS_ERR(handle)) {
408726a4c0c6STheodore Ts'o 		ret = PTR_ERR(handle);
408826a4c0c6STheodore Ts'o 		ext4_std_error(sb, ret);
408926a4c0c6STheodore Ts'o 		goto out_dio;
409026a4c0c6STheodore Ts'o 	}
409126a4c0c6STheodore Ts'o 
4092a87dd18cSLukas Czerner 	ret = ext4_zero_partial_blocks(handle, inode, offset,
4093a87dd18cSLukas Czerner 				       length);
409426a4c0c6STheodore Ts'o 	if (ret)
409526a4c0c6STheodore Ts'o 		goto out_stop;
409626a4c0c6STheodore Ts'o 
409726a4c0c6STheodore Ts'o 	first_block = (offset + sb->s_blocksize - 1) >>
409826a4c0c6STheodore Ts'o 		EXT4_BLOCK_SIZE_BITS(sb);
409926a4c0c6STheodore Ts'o 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
410026a4c0c6STheodore Ts'o 
4101eee597acSLukas Czerner 	/* If there are blocks to remove, do it */
4102eee597acSLukas Czerner 	if (stop_block > first_block) {
410326a4c0c6STheodore Ts'o 
410426a4c0c6STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
410527bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
410626a4c0c6STheodore Ts'o 
410726a4c0c6STheodore Ts'o 		ret = ext4_es_remove_extent(inode, first_block,
410826a4c0c6STheodore Ts'o 					    stop_block - first_block);
410926a4c0c6STheodore Ts'o 		if (ret) {
411026a4c0c6STheodore Ts'o 			up_write(&EXT4_I(inode)->i_data_sem);
411126a4c0c6STheodore Ts'o 			goto out_stop;
411226a4c0c6STheodore Ts'o 		}
411326a4c0c6STheodore Ts'o 
411426a4c0c6STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
411526a4c0c6STheodore Ts'o 			ret = ext4_ext_remove_space(inode, first_block,
411626a4c0c6STheodore Ts'o 						    stop_block - 1);
411726a4c0c6STheodore Ts'o 		else
41184f579ae7SLukas Czerner 			ret = ext4_ind_remove_space(handle, inode, first_block,
411926a4c0c6STheodore Ts'o 						    stop_block);
412026a4c0c6STheodore Ts'o 
4121819c4920STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
4122eee597acSLukas Czerner 	}
4123a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_range(handle, inode, first_block, stop_block);
412426a4c0c6STheodore Ts'o 	if (IS_SYNC(inode))
412526a4c0c6STheodore Ts'o 		ext4_handle_sync(handle);
4126e251f9bcSMaxim Patlasov 
4127eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
41284209ae12SHarshad Shirwadkar 	ret2 = ext4_mark_inode_dirty(handle, inode);
41294209ae12SHarshad Shirwadkar 	if (unlikely(ret2))
41304209ae12SHarshad Shirwadkar 		ret = ret2;
413167a7d5f5SJan Kara 	if (ret >= 0)
413267a7d5f5SJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
413326a4c0c6STheodore Ts'o out_stop:
413426a4c0c6STheodore Ts'o 	ext4_journal_stop(handle);
413526a4c0c6STheodore Ts'o out_dio:
4136d4f5258eSJan Kara 	filemap_invalidate_unlock(mapping);
413726a4c0c6STheodore Ts'o out_mutex:
41385955102cSAl Viro 	inode_unlock(inode);
413926a4c0c6STheodore Ts'o 	return ret;
4140a4bb6b64SAllison Henderson }
4141a4bb6b64SAllison Henderson 
4142a361293fSJan Kara int ext4_inode_attach_jinode(struct inode *inode)
4143a361293fSJan Kara {
4144a361293fSJan Kara 	struct ext4_inode_info *ei = EXT4_I(inode);
4145a361293fSJan Kara 	struct jbd2_inode *jinode;
4146a361293fSJan Kara 
4147a361293fSJan Kara 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4148a361293fSJan Kara 		return 0;
4149a361293fSJan Kara 
4150a361293fSJan Kara 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4151a361293fSJan Kara 	spin_lock(&inode->i_lock);
4152a361293fSJan Kara 	if (!ei->jinode) {
4153a361293fSJan Kara 		if (!jinode) {
4154a361293fSJan Kara 			spin_unlock(&inode->i_lock);
4155a361293fSJan Kara 			return -ENOMEM;
4156a361293fSJan Kara 		}
4157a361293fSJan Kara 		ei->jinode = jinode;
4158a361293fSJan Kara 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4159a361293fSJan Kara 		jinode = NULL;
4160a361293fSJan Kara 	}
4161a361293fSJan Kara 	spin_unlock(&inode->i_lock);
4162a361293fSJan Kara 	if (unlikely(jinode != NULL))
4163a361293fSJan Kara 		jbd2_free_inode(jinode);
4164a361293fSJan Kara 	return 0;
4165a361293fSJan Kara }
4166a361293fSJan Kara 
4167a4bb6b64SAllison Henderson /*
4168617ba13bSMingming Cao  * ext4_truncate()
4169ac27a0ecSDave Kleikamp  *
4170617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
4171617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4172ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
4173ac27a0ecSDave Kleikamp  *
417442b2aa86SJustin P. Mattock  * As we work through the truncate and commit bits of it to the journal there
4175ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
4176ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
4177ac27a0ecSDave Kleikamp  *
4178ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
4179ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
4180ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
4181ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
4182ac27a0ecSDave Kleikamp  * left-to-right works OK too).
4183ac27a0ecSDave Kleikamp  *
4184ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
4185ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
4186ac27a0ecSDave Kleikamp  *
4187ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
4188617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4189ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
4190617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
4191617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
4192ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
4193617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
4194ac27a0ecSDave Kleikamp  */
41952c98eb5eSTheodore Ts'o int ext4_truncate(struct inode *inode)
4196ac27a0ecSDave Kleikamp {
4197819c4920STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
4198819c4920STheodore Ts'o 	unsigned int credits;
41994209ae12SHarshad Shirwadkar 	int err = 0, err2;
4200819c4920STheodore Ts'o 	handle_t *handle;
4201819c4920STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
4202819c4920STheodore Ts'o 
420319b5ef61STheodore Ts'o 	/*
420419b5ef61STheodore Ts'o 	 * There is a possibility that we're either freeing the inode
4205e04027e8SMatthew Wilcox 	 * or it's a completely new inode. In those cases we might not
4206f340b3d9Shongnanli 	 * have i_rwsem locked because it's not necessary.
420719b5ef61STheodore Ts'o 	 */
420819b5ef61STheodore Ts'o 	if (!(inode->i_state & (I_NEW|I_FREEING)))
42095955102cSAl Viro 		WARN_ON(!inode_is_locked(inode));
42100562e0baSJiaying Zhang 	trace_ext4_truncate_enter(inode);
42110562e0baSJiaying Zhang 
421291ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
42139a5d265fSzhengliang 		goto out_trace;
4214ac27a0ecSDave Kleikamp 
42155534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
421619f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
42177d8f9f7dSTheodore Ts'o 
4218aef1c851STao Ma 	if (ext4_has_inline_data(inode)) {
4219aef1c851STao Ma 		int has_inline = 1;
4220aef1c851STao Ma 
422101daf945STheodore Ts'o 		err = ext4_inline_data_truncate(inode, &has_inline);
42229a5d265fSzhengliang 		if (err || has_inline)
42239a5d265fSzhengliang 			goto out_trace;
4224aef1c851STao Ma 	}
4225aef1c851STao Ma 
4226a361293fSJan Kara 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4227a361293fSJan Kara 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4228a361293fSJan Kara 		if (ext4_inode_attach_jinode(inode) < 0)
42299a5d265fSzhengliang 			goto out_trace;
4230a361293fSJan Kara 	}
4231a361293fSJan Kara 
4232ff9893dcSAmir Goldstein 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4233819c4920STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
4234ff9893dcSAmir Goldstein 	else
4235819c4920STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
4236819c4920STheodore Ts'o 
4237819c4920STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
42389a5d265fSzhengliang 	if (IS_ERR(handle)) {
42399a5d265fSzhengliang 		err = PTR_ERR(handle);
42409a5d265fSzhengliang 		goto out_trace;
42419a5d265fSzhengliang 	}
4242819c4920STheodore Ts'o 
4243eb3544c6SLukas Czerner 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4244eb3544c6SLukas Czerner 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4245819c4920STheodore Ts'o 
4246819c4920STheodore Ts'o 	/*
4247819c4920STheodore Ts'o 	 * We add the inode to the orphan list, so that if this
4248819c4920STheodore Ts'o 	 * truncate spans multiple transactions, and we crash, we will
4249819c4920STheodore Ts'o 	 * resume the truncate when the filesystem recovers.  It also
4250819c4920STheodore Ts'o 	 * marks the inode dirty, to catch the new size.
4251819c4920STheodore Ts'o 	 *
4252819c4920STheodore Ts'o 	 * Implication: the file must always be in a sane, consistent
4253819c4920STheodore Ts'o 	 * truncatable state while each transaction commits.
4254819c4920STheodore Ts'o 	 */
42552c98eb5eSTheodore Ts'o 	err = ext4_orphan_add(handle, inode);
42562c98eb5eSTheodore Ts'o 	if (err)
4257819c4920STheodore Ts'o 		goto out_stop;
4258819c4920STheodore Ts'o 
4259819c4920STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
4260819c4920STheodore Ts'o 
426127bc446eSbrookxu 	ext4_discard_preallocations(inode, 0);
4262819c4920STheodore Ts'o 
4263819c4920STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4264d0abb36dSTheodore Ts'o 		err = ext4_ext_truncate(handle, inode);
4265819c4920STheodore Ts'o 	else
4266819c4920STheodore Ts'o 		ext4_ind_truncate(handle, inode);
4267819c4920STheodore Ts'o 
4268819c4920STheodore Ts'o 	up_write(&ei->i_data_sem);
4269d0abb36dSTheodore Ts'o 	if (err)
4270d0abb36dSTheodore Ts'o 		goto out_stop;
4271819c4920STheodore Ts'o 
4272819c4920STheodore Ts'o 	if (IS_SYNC(inode))
4273819c4920STheodore Ts'o 		ext4_handle_sync(handle);
4274819c4920STheodore Ts'o 
4275819c4920STheodore Ts'o out_stop:
4276819c4920STheodore Ts'o 	/*
4277819c4920STheodore Ts'o 	 * If this was a simple ftruncate() and the file will remain alive,
4278819c4920STheodore Ts'o 	 * then we need to clear up the orphan record which we created above.
4279819c4920STheodore Ts'o 	 * However, if this was a real unlink then we were called by
428058d86a50SWang Shilong 	 * ext4_evict_inode(), and we allow that function to clean up the
4281819c4920STheodore Ts'o 	 * orphan info for us.
4282819c4920STheodore Ts'o 	 */
4283819c4920STheodore Ts'o 	if (inode->i_nlink)
4284819c4920STheodore Ts'o 		ext4_orphan_del(handle, inode);
4285819c4920STheodore Ts'o 
4286eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
42874209ae12SHarshad Shirwadkar 	err2 = ext4_mark_inode_dirty(handle, inode);
42884209ae12SHarshad Shirwadkar 	if (unlikely(err2 && !err))
42894209ae12SHarshad Shirwadkar 		err = err2;
4290819c4920STheodore Ts'o 	ext4_journal_stop(handle);
4291a86c6181SAlex Tomas 
42929a5d265fSzhengliang out_trace:
42930562e0baSJiaying Zhang 	trace_ext4_truncate_exit(inode);
42942c98eb5eSTheodore Ts'o 	return err;
4295ac27a0ecSDave Kleikamp }
4296ac27a0ecSDave Kleikamp 
42979a1bf32cSZhang Yi static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
42989a1bf32cSZhang Yi {
42999a1bf32cSZhang Yi 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
43009a1bf32cSZhang Yi 		return inode_peek_iversion_raw(inode);
43019a1bf32cSZhang Yi 	else
43029a1bf32cSZhang Yi 		return inode_peek_iversion(inode);
43039a1bf32cSZhang Yi }
43049a1bf32cSZhang Yi 
43059a1bf32cSZhang Yi static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
43069a1bf32cSZhang Yi 				 struct ext4_inode_info *ei)
43079a1bf32cSZhang Yi {
43089a1bf32cSZhang Yi 	struct inode *inode = &(ei->vfs_inode);
43099a1bf32cSZhang Yi 	u64 i_blocks = READ_ONCE(inode->i_blocks);
43109a1bf32cSZhang Yi 	struct super_block *sb = inode->i_sb;
43119a1bf32cSZhang Yi 
43129a1bf32cSZhang Yi 	if (i_blocks <= ~0U) {
43139a1bf32cSZhang Yi 		/*
43149a1bf32cSZhang Yi 		 * i_blocks can be represented in a 32 bit variable
43159a1bf32cSZhang Yi 		 * as multiple of 512 bytes
43169a1bf32cSZhang Yi 		 */
43179a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
43189a1bf32cSZhang Yi 		raw_inode->i_blocks_high = 0;
43199a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
43209a1bf32cSZhang Yi 		return 0;
43219a1bf32cSZhang Yi 	}
43229a1bf32cSZhang Yi 
43239a1bf32cSZhang Yi 	/*
43249a1bf32cSZhang Yi 	 * This should never happen since sb->s_maxbytes should not have
43259a1bf32cSZhang Yi 	 * allowed this, sb->s_maxbytes was set according to the huge_file
43269a1bf32cSZhang Yi 	 * feature in ext4_fill_super().
43279a1bf32cSZhang Yi 	 */
43289a1bf32cSZhang Yi 	if (!ext4_has_feature_huge_file(sb))
43299a1bf32cSZhang Yi 		return -EFSCORRUPTED;
43309a1bf32cSZhang Yi 
43319a1bf32cSZhang Yi 	if (i_blocks <= 0xffffffffffffULL) {
43329a1bf32cSZhang Yi 		/*
43339a1bf32cSZhang Yi 		 * i_blocks can be represented in a 48 bit variable
43349a1bf32cSZhang Yi 		 * as multiple of 512 bytes
43359a1bf32cSZhang Yi 		 */
43369a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
43379a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
43389a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
43399a1bf32cSZhang Yi 	} else {
43409a1bf32cSZhang Yi 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
43419a1bf32cSZhang Yi 		/* i_block is stored in file system block size */
43429a1bf32cSZhang Yi 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
43439a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
43449a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
43459a1bf32cSZhang Yi 	}
43469a1bf32cSZhang Yi 	return 0;
43479a1bf32cSZhang Yi }
43489a1bf32cSZhang Yi 
43499a1bf32cSZhang Yi static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
43509a1bf32cSZhang Yi {
43519a1bf32cSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
43529a1bf32cSZhang Yi 	uid_t i_uid;
43539a1bf32cSZhang Yi 	gid_t i_gid;
43549a1bf32cSZhang Yi 	projid_t i_projid;
43559a1bf32cSZhang Yi 	int block;
43569a1bf32cSZhang Yi 	int err;
43579a1bf32cSZhang Yi 
43589a1bf32cSZhang Yi 	err = ext4_inode_blocks_set(raw_inode, ei);
43599a1bf32cSZhang Yi 
43609a1bf32cSZhang Yi 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
43619a1bf32cSZhang Yi 	i_uid = i_uid_read(inode);
43629a1bf32cSZhang Yi 	i_gid = i_gid_read(inode);
43639a1bf32cSZhang Yi 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
43649a1bf32cSZhang Yi 	if (!(test_opt(inode->i_sb, NO_UID32))) {
43659a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
43669a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
43679a1bf32cSZhang Yi 		/*
43689a1bf32cSZhang Yi 		 * Fix up interoperability with old kernels. Otherwise,
43699a1bf32cSZhang Yi 		 * old inodes get re-used with the upper 16 bits of the
43709a1bf32cSZhang Yi 		 * uid/gid intact.
43719a1bf32cSZhang Yi 		 */
43729a1bf32cSZhang Yi 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
43739a1bf32cSZhang Yi 			raw_inode->i_uid_high = 0;
43749a1bf32cSZhang Yi 			raw_inode->i_gid_high = 0;
43759a1bf32cSZhang Yi 		} else {
43769a1bf32cSZhang Yi 			raw_inode->i_uid_high =
43779a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_uid));
43789a1bf32cSZhang Yi 			raw_inode->i_gid_high =
43799a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_gid));
43809a1bf32cSZhang Yi 		}
43819a1bf32cSZhang Yi 	} else {
43829a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
43839a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
43849a1bf32cSZhang Yi 		raw_inode->i_uid_high = 0;
43859a1bf32cSZhang Yi 		raw_inode->i_gid_high = 0;
43869a1bf32cSZhang Yi 	}
43879a1bf32cSZhang Yi 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
43889a1bf32cSZhang Yi 
43899a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
43909a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
43919a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
43929a1bf32cSZhang Yi 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
43939a1bf32cSZhang Yi 
43949a1bf32cSZhang Yi 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
43959a1bf32cSZhang Yi 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
43969a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
43979a1bf32cSZhang Yi 		raw_inode->i_file_acl_high =
43989a1bf32cSZhang Yi 			cpu_to_le16(ei->i_file_acl >> 32);
43999a1bf32cSZhang Yi 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
44009a1bf32cSZhang Yi 	ext4_isize_set(raw_inode, ei->i_disksize);
44019a1bf32cSZhang Yi 
44029a1bf32cSZhang Yi 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
44039a1bf32cSZhang Yi 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
44049a1bf32cSZhang Yi 		if (old_valid_dev(inode->i_rdev)) {
44059a1bf32cSZhang Yi 			raw_inode->i_block[0] =
44069a1bf32cSZhang Yi 				cpu_to_le32(old_encode_dev(inode->i_rdev));
44079a1bf32cSZhang Yi 			raw_inode->i_block[1] = 0;
44089a1bf32cSZhang Yi 		} else {
44099a1bf32cSZhang Yi 			raw_inode->i_block[0] = 0;
44109a1bf32cSZhang Yi 			raw_inode->i_block[1] =
44119a1bf32cSZhang Yi 				cpu_to_le32(new_encode_dev(inode->i_rdev));
44129a1bf32cSZhang Yi 			raw_inode->i_block[2] = 0;
44139a1bf32cSZhang Yi 		}
44149a1bf32cSZhang Yi 	} else if (!ext4_has_inline_data(inode)) {
44159a1bf32cSZhang Yi 		for (block = 0; block < EXT4_N_BLOCKS; block++)
44169a1bf32cSZhang Yi 			raw_inode->i_block[block] = ei->i_data[block];
44179a1bf32cSZhang Yi 	}
44189a1bf32cSZhang Yi 
44199a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
44209a1bf32cSZhang Yi 		u64 ivers = ext4_inode_peek_iversion(inode);
44219a1bf32cSZhang Yi 
44229a1bf32cSZhang Yi 		raw_inode->i_disk_version = cpu_to_le32(ivers);
44239a1bf32cSZhang Yi 		if (ei->i_extra_isize) {
44249a1bf32cSZhang Yi 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
44259a1bf32cSZhang Yi 				raw_inode->i_version_hi =
44269a1bf32cSZhang Yi 					cpu_to_le32(ivers >> 32);
44279a1bf32cSZhang Yi 			raw_inode->i_extra_isize =
44289a1bf32cSZhang Yi 				cpu_to_le16(ei->i_extra_isize);
44299a1bf32cSZhang Yi 		}
44309a1bf32cSZhang Yi 	}
44319a1bf32cSZhang Yi 
44329a1bf32cSZhang Yi 	if (i_projid != EXT4_DEF_PROJID &&
44339a1bf32cSZhang Yi 	    !ext4_has_feature_project(inode->i_sb))
44349a1bf32cSZhang Yi 		err = err ?: -EFSCORRUPTED;
44359a1bf32cSZhang Yi 
44369a1bf32cSZhang Yi 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
44379a1bf32cSZhang Yi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
44389a1bf32cSZhang Yi 		raw_inode->i_projid = cpu_to_le32(i_projid);
44399a1bf32cSZhang Yi 
44409a1bf32cSZhang Yi 	ext4_inode_csum_set(inode, raw_inode, ei);
44419a1bf32cSZhang Yi 	return err;
44429a1bf32cSZhang Yi }
44439a1bf32cSZhang Yi 
4444ac27a0ecSDave Kleikamp /*
4445617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
4446de01f484SZhang Yi  * underlying buffer_head on success. If we pass 'inode' and it does not
4447de01f484SZhang Yi  * have in-inode xattr, we have all inode data in memory that is needed
4448de01f484SZhang Yi  * to recreate the on-disk version of this inode.
4449ac27a0ecSDave Kleikamp  */
44508016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4451de01f484SZhang Yi 				struct inode *inode, struct ext4_iloc *iloc,
44528016e29fSHarshad Shirwadkar 				ext4_fsblk_t *ret_block)
4453ac27a0ecSDave Kleikamp {
4454240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
4455ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
4456240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
445702f03c42SLinus Torvalds 	struct blk_plug		plug;
4458240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
4459ac27a0ecSDave Kleikamp 
44603a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
44618016e29fSHarshad Shirwadkar 	if (ino < EXT4_ROOT_INO ||
44628016e29fSHarshad Shirwadkar 	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
44636a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4464ac27a0ecSDave Kleikamp 
44658016e29fSHarshad Shirwadkar 	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4466240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4467240799cdSTheodore Ts'o 	if (!gdp)
4468240799cdSTheodore Ts'o 		return -EIO;
4469240799cdSTheodore Ts'o 
4470240799cdSTheodore Ts'o 	/*
4471240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
4472240799cdSTheodore Ts'o 	 */
447300d09882STao Ma 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
44748016e29fSHarshad Shirwadkar 	inode_offset = ((ino - 1) %
4475240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
4476240799cdSTheodore Ts'o 	block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4477240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4478240799cdSTheodore Ts'o 
4479240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
4480aebf0243SWang Shilong 	if (unlikely(!bh))
4481860d21e2STheodore Ts'o 		return -ENOMEM;
44828e33fadfSZhang Yi 	if (ext4_buffer_uptodate(bh))
4483ac27a0ecSDave Kleikamp 		goto has_buffer;
4484ac27a0ecSDave Kleikamp 
44858e33fadfSZhang Yi 	lock_buffer(bh);
4486f2c77973SZhang Yi 	if (ext4_buffer_uptodate(bh)) {
4487f2c77973SZhang Yi 		/* Someone brought it uptodate while we waited */
4488f2c77973SZhang Yi 		unlock_buffer(bh);
4489f2c77973SZhang Yi 		goto has_buffer;
4490f2c77973SZhang Yi 	}
4491f2c77973SZhang Yi 
4492ac27a0ecSDave Kleikamp 	/*
4493ac27a0ecSDave Kleikamp 	 * If we have all information of the inode in memory and this
4494ac27a0ecSDave Kleikamp 	 * is the only valid inode in the block, we need not read the
4495ac27a0ecSDave Kleikamp 	 * block.
4496ac27a0ecSDave Kleikamp 	 */
4497de01f484SZhang Yi 	if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4498ac27a0ecSDave Kleikamp 		struct buffer_head *bitmap_bh;
4499240799cdSTheodore Ts'o 		int i, start;
4500ac27a0ecSDave Kleikamp 
4501240799cdSTheodore Ts'o 		start = inode_offset & ~(inodes_per_block - 1);
4502ac27a0ecSDave Kleikamp 
4503ac27a0ecSDave Kleikamp 		/* Is the inode bitmap in cache? */
4504240799cdSTheodore Ts'o 		bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4505aebf0243SWang Shilong 		if (unlikely(!bitmap_bh))
4506ac27a0ecSDave Kleikamp 			goto make_io;
4507ac27a0ecSDave Kleikamp 
4508ac27a0ecSDave Kleikamp 		/*
4509ac27a0ecSDave Kleikamp 		 * If the inode bitmap isn't in cache then the
4510ac27a0ecSDave Kleikamp 		 * optimisation may end up performing two reads instead
4511ac27a0ecSDave Kleikamp 		 * of one, so skip it.
4512ac27a0ecSDave Kleikamp 		 */
4513ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bitmap_bh)) {
4514ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
4515ac27a0ecSDave Kleikamp 			goto make_io;
4516ac27a0ecSDave Kleikamp 		}
4517240799cdSTheodore Ts'o 		for (i = start; i < start + inodes_per_block; i++) {
4518ac27a0ecSDave Kleikamp 			if (i == inode_offset)
4519ac27a0ecSDave Kleikamp 				continue;
4520617ba13bSMingming Cao 			if (ext4_test_bit(i, bitmap_bh->b_data))
4521ac27a0ecSDave Kleikamp 				break;
4522ac27a0ecSDave Kleikamp 		}
4523ac27a0ecSDave Kleikamp 		brelse(bitmap_bh);
4524240799cdSTheodore Ts'o 		if (i == start + inodes_per_block) {
4525de01f484SZhang Yi 			struct ext4_inode *raw_inode =
4526de01f484SZhang Yi 				(struct ext4_inode *) (bh->b_data + iloc->offset);
4527de01f484SZhang Yi 
4528ac27a0ecSDave Kleikamp 			/* all other inodes are free, so skip I/O */
4529ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, bh->b_size);
4530de01f484SZhang Yi 			if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4531de01f484SZhang Yi 				ext4_fill_raw_inode(inode, raw_inode);
4532ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
4533ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
4534ac27a0ecSDave Kleikamp 			goto has_buffer;
4535ac27a0ecSDave Kleikamp 		}
4536ac27a0ecSDave Kleikamp 	}
4537ac27a0ecSDave Kleikamp 
4538ac27a0ecSDave Kleikamp make_io:
4539ac27a0ecSDave Kleikamp 	/*
4540240799cdSTheodore Ts'o 	 * If we need to do any I/O, try to pre-readahead extra
4541240799cdSTheodore Ts'o 	 * blocks from the inode table.
4542240799cdSTheodore Ts'o 	 */
454302f03c42SLinus Torvalds 	blk_start_plug(&plug);
4544240799cdSTheodore Ts'o 	if (EXT4_SB(sb)->s_inode_readahead_blks) {
4545240799cdSTheodore Ts'o 		ext4_fsblk_t b, end, table;
4546240799cdSTheodore Ts'o 		unsigned num;
45470d606e2cSTheodore Ts'o 		__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4548240799cdSTheodore Ts'o 
4549240799cdSTheodore Ts'o 		table = ext4_inode_table(sb, gdp);
4550b713a5ecSTheodore Ts'o 		/* s_inode_readahead_blks is always a power of 2 */
45510d606e2cSTheodore Ts'o 		b = block & ~((ext4_fsblk_t) ra_blks - 1);
4552240799cdSTheodore Ts'o 		if (table > b)
4553240799cdSTheodore Ts'o 			b = table;
45540d606e2cSTheodore Ts'o 		end = b + ra_blks;
4555240799cdSTheodore Ts'o 		num = EXT4_INODES_PER_GROUP(sb);
4556feb0ab32SDarrick J. Wong 		if (ext4_has_group_desc_csum(sb))
4557560671a0SAneesh Kumar K.V 			num -= ext4_itable_unused_count(sb, gdp);
4558240799cdSTheodore Ts'o 		table += num / inodes_per_block;
4559240799cdSTheodore Ts'o 		if (end > table)
4560240799cdSTheodore Ts'o 			end = table;
4561240799cdSTheodore Ts'o 		while (b <= end)
45625df1d412Szhangyi (F) 			ext4_sb_breadahead_unmovable(sb, b++);
4563240799cdSTheodore Ts'o 	}
4564240799cdSTheodore Ts'o 
4565240799cdSTheodore Ts'o 	/*
4566ac27a0ecSDave Kleikamp 	 * There are other valid inodes in the buffer, this inode
4567ac27a0ecSDave Kleikamp 	 * has in-inode xattrs, or we don't have this inode in memory.
4568ac27a0ecSDave Kleikamp 	 * Read the block from disk.
4569ac27a0ecSDave Kleikamp 	 */
45708016e29fSHarshad Shirwadkar 	trace_ext4_load_inode(sb, ino);
45712d069c08Szhangyi (F) 	ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
457202f03c42SLinus Torvalds 	blk_finish_plug(&plug);
4573ac27a0ecSDave Kleikamp 	wait_on_buffer(bh);
45740904c9aeSZhang Yi 	ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4575ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
45768016e29fSHarshad Shirwadkar 		if (ret_block)
45778016e29fSHarshad Shirwadkar 			*ret_block = block;
4578ac27a0ecSDave Kleikamp 		brelse(bh);
4579ac27a0ecSDave Kleikamp 		return -EIO;
4580ac27a0ecSDave Kleikamp 	}
4581ac27a0ecSDave Kleikamp has_buffer:
4582ac27a0ecSDave Kleikamp 	iloc->bh = bh;
4583ac27a0ecSDave Kleikamp 	return 0;
4584ac27a0ecSDave Kleikamp }
4585ac27a0ecSDave Kleikamp 
45868016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc_noinmem(struct inode *inode,
45878016e29fSHarshad Shirwadkar 					struct ext4_iloc *iloc)
45888016e29fSHarshad Shirwadkar {
4589c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
45908016e29fSHarshad Shirwadkar 	int ret;
45918016e29fSHarshad Shirwadkar 
4592de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
45938016e29fSHarshad Shirwadkar 					&err_blk);
45948016e29fSHarshad Shirwadkar 
45958016e29fSHarshad Shirwadkar 	if (ret == -EIO)
45968016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
45978016e29fSHarshad Shirwadkar 					"unable to read itable block");
45988016e29fSHarshad Shirwadkar 
45998016e29fSHarshad Shirwadkar 	return ret;
46008016e29fSHarshad Shirwadkar }
46018016e29fSHarshad Shirwadkar 
4602617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4603ac27a0ecSDave Kleikamp {
4604c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
46058016e29fSHarshad Shirwadkar 	int ret;
46068016e29fSHarshad Shirwadkar 
4607de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4608de01f484SZhang Yi 					&err_blk);
46098016e29fSHarshad Shirwadkar 
46108016e29fSHarshad Shirwadkar 	if (ret == -EIO)
46118016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
46128016e29fSHarshad Shirwadkar 					"unable to read itable block");
46138016e29fSHarshad Shirwadkar 
46148016e29fSHarshad Shirwadkar 	return ret;
46158016e29fSHarshad Shirwadkar }
46168016e29fSHarshad Shirwadkar 
46178016e29fSHarshad Shirwadkar 
46188016e29fSHarshad Shirwadkar int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
46198016e29fSHarshad Shirwadkar 			  struct ext4_iloc *iloc)
46208016e29fSHarshad Shirwadkar {
4621de01f484SZhang Yi 	return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4622ac27a0ecSDave Kleikamp }
4623ac27a0ecSDave Kleikamp 
4624a8ab6d38SIra Weiny static bool ext4_should_enable_dax(struct inode *inode)
46256642586bSRoss Zwisler {
4626a8ab6d38SIra Weiny 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4627a8ab6d38SIra Weiny 
46289cb20f94SIra Weiny 	if (test_opt2(inode->i_sb, DAX_NEVER))
46296642586bSRoss Zwisler 		return false;
46306642586bSRoss Zwisler 	if (!S_ISREG(inode->i_mode))
46316642586bSRoss Zwisler 		return false;
46326642586bSRoss Zwisler 	if (ext4_should_journal_data(inode))
46336642586bSRoss Zwisler 		return false;
46346642586bSRoss Zwisler 	if (ext4_has_inline_data(inode))
46356642586bSRoss Zwisler 		return false;
4636592ddec7SChandan Rajendra 	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
46376642586bSRoss Zwisler 		return false;
4638c93d8f88SEric Biggers 	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4639c93d8f88SEric Biggers 		return false;
4640a8ab6d38SIra Weiny 	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4641a8ab6d38SIra Weiny 		return false;
4642a8ab6d38SIra Weiny 	if (test_opt(inode->i_sb, DAX_ALWAYS))
46436642586bSRoss Zwisler 		return true;
4644a8ab6d38SIra Weiny 
4645b383a73fSIra Weiny 	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
46466642586bSRoss Zwisler }
46476642586bSRoss Zwisler 
4648043546e4SIra Weiny void ext4_set_inode_flags(struct inode *inode, bool init)
4649ac27a0ecSDave Kleikamp {
4650617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
465100a1a053STheodore Ts'o 	unsigned int new_fl = 0;
4652ac27a0ecSDave Kleikamp 
4653043546e4SIra Weiny 	WARN_ON_ONCE(IS_DAX(inode) && init);
4654043546e4SIra Weiny 
4655617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
465600a1a053STheodore Ts'o 		new_fl |= S_SYNC;
4657617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
465800a1a053STheodore Ts'o 		new_fl |= S_APPEND;
4659617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
466000a1a053STheodore Ts'o 		new_fl |= S_IMMUTABLE;
4661617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
466200a1a053STheodore Ts'o 		new_fl |= S_NOATIME;
4663617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
466400a1a053STheodore Ts'o 		new_fl |= S_DIRSYNC;
4665043546e4SIra Weiny 
4666043546e4SIra Weiny 	/* Because of the way inode_set_flags() works we must preserve S_DAX
4667043546e4SIra Weiny 	 * here if already set. */
4668043546e4SIra Weiny 	new_fl |= (inode->i_flags & S_DAX);
4669043546e4SIra Weiny 	if (init && ext4_should_enable_dax(inode))
4670923ae0ffSRoss Zwisler 		new_fl |= S_DAX;
4671043546e4SIra Weiny 
46722ee6a576SEric Biggers 	if (flags & EXT4_ENCRYPT_FL)
46732ee6a576SEric Biggers 		new_fl |= S_ENCRYPTED;
4674b886ee3eSGabriel Krisman Bertazi 	if (flags & EXT4_CASEFOLD_FL)
4675b886ee3eSGabriel Krisman Bertazi 		new_fl |= S_CASEFOLD;
4676c93d8f88SEric Biggers 	if (flags & EXT4_VERITY_FL)
4677c93d8f88SEric Biggers 		new_fl |= S_VERITY;
46785f16f322STheodore Ts'o 	inode_set_flags(inode, new_fl,
46792ee6a576SEric Biggers 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4680c93d8f88SEric Biggers 			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4681ac27a0ecSDave Kleikamp }
4682ac27a0ecSDave Kleikamp 
46830fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
46840fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
46850fc1b451SAneesh Kumar K.V {
46860fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
46878180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
46888180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
46890fc1b451SAneesh Kumar K.V 
4690e2b911c5SDarrick J. Wong 	if (ext4_has_feature_huge_file(sb)) {
46910fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
46920fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
46930fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
469407a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
46958180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
46968180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
46978180a562SAneesh Kumar K.V 		} else {
46980fc1b451SAneesh Kumar K.V 			return i_blocks;
46998180a562SAneesh Kumar K.V 		}
47000fc1b451SAneesh Kumar K.V 	} else {
47010fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
47020fc1b451SAneesh Kumar K.V 	}
47030fc1b451SAneesh Kumar K.V }
4704ff9ddf7eSJan Kara 
4705eb9b5f01STheodore Ts'o static inline int ext4_iget_extra_inode(struct inode *inode,
4706152a7b0aSTao Ma 					 struct ext4_inode *raw_inode,
4707152a7b0aSTao Ma 					 struct ext4_inode_info *ei)
4708152a7b0aSTao Ma {
4709152a7b0aSTao Ma 	__le32 *magic = (void *)raw_inode +
4710152a7b0aSTao Ma 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4711eb9b5f01STheodore Ts'o 
4712fd7e672eSBaokun Li 	if (EXT4_INODE_HAS_XATTR_SPACE(inode)  &&
4713290ab230SEric Biggers 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4714152a7b0aSTao Ma 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4715eb9b5f01STheodore Ts'o 		return ext4_find_inline_data_nolock(inode);
4716f19d5870STao Ma 	} else
4717f19d5870STao Ma 		EXT4_I(inode)->i_inline_off = 0;
4718eb9b5f01STheodore Ts'o 	return 0;
4719152a7b0aSTao Ma }
4720152a7b0aSTao Ma 
4721040cb378SLi Xi int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4722040cb378SLi Xi {
47230b7b7779SKaho Ng 	if (!ext4_has_feature_project(inode->i_sb))
4724040cb378SLi Xi 		return -EOPNOTSUPP;
4725040cb378SLi Xi 	*projid = EXT4_I(inode)->i_projid;
4726040cb378SLi Xi 	return 0;
4727040cb378SLi Xi }
4728040cb378SLi Xi 
4729e254d1afSEryu Guan /*
4730e254d1afSEryu Guan  * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4731e254d1afSEryu Guan  * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4732e254d1afSEryu Guan  * set.
4733e254d1afSEryu Guan  */
4734e254d1afSEryu Guan static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4735e254d1afSEryu Guan {
4736e254d1afSEryu Guan 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4737e254d1afSEryu Guan 		inode_set_iversion_raw(inode, val);
4738e254d1afSEryu Guan 	else
4739e254d1afSEryu Guan 		inode_set_iversion_queried(inode, val);
4740e254d1afSEryu Guan }
4741e254d1afSEryu Guan 
47428a363970STheodore Ts'o struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
47438a363970STheodore Ts'o 			  ext4_iget_flags flags, const char *function,
47448a363970STheodore Ts'o 			  unsigned int line)
4745ac27a0ecSDave Kleikamp {
4746617ba13bSMingming Cao 	struct ext4_iloc iloc;
4747617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
47481d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
4749bd2c38cfSJan Kara 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
47501d1fe1eeSDavid Howells 	struct inode *inode;
4751b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
47521d1fe1eeSDavid Howells 	long ret;
47537e6e1ef4SDarrick J. Wong 	loff_t size;
4754ac27a0ecSDave Kleikamp 	int block;
475508cefc7aSEric W. Biederman 	uid_t i_uid;
475608cefc7aSEric W. Biederman 	gid_t i_gid;
4757040cb378SLi Xi 	projid_t i_projid;
4758ac27a0ecSDave Kleikamp 
4759191ce178STheodore Ts'o 	if ((!(flags & EXT4_IGET_SPECIAL) &&
4760bd2c38cfSJan Kara 	     ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4761bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_usr_quota_inum) ||
4762bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_grp_quota_inum) ||
476302f310fcSJan Kara 	      ino == le32_to_cpu(es->s_prj_quota_inum) ||
476402f310fcSJan Kara 	      ino == le32_to_cpu(es->s_orphan_file_inum))) ||
47658a363970STheodore Ts'o 	    (ino < EXT4_ROOT_INO) ||
4766bd2c38cfSJan Kara 	    (ino > le32_to_cpu(es->s_inodes_count))) {
47678a363970STheodore Ts'o 		if (flags & EXT4_IGET_HANDLE)
47688a363970STheodore Ts'o 			return ERR_PTR(-ESTALE);
4769014c9caaSJan Kara 		__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
47708a363970STheodore Ts'o 			     "inode #%lu: comm %s: iget: illegal inode #",
47718a363970STheodore Ts'o 			     ino, current->comm);
47728a363970STheodore Ts'o 		return ERR_PTR(-EFSCORRUPTED);
47738a363970STheodore Ts'o 	}
47748a363970STheodore Ts'o 
47751d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
47761d1fe1eeSDavid Howells 	if (!inode)
47771d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
47781d1fe1eeSDavid Howells 	if (!(inode->i_state & I_NEW))
47791d1fe1eeSDavid Howells 		return inode;
47801d1fe1eeSDavid Howells 
47811d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
47827dc57615SPeter Huewe 	iloc.bh = NULL;
4783ac27a0ecSDave Kleikamp 
47848016e29fSHarshad Shirwadkar 	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
47851d1fe1eeSDavid Howells 	if (ret < 0)
4786ac27a0ecSDave Kleikamp 		goto bad_inode;
4787617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
4788814525f4SDarrick J. Wong 
47898e4b5eaeSTheodore Ts'o 	if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
47908a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
47918a363970STheodore Ts'o 				 "iget: root inode unallocated");
47928e4b5eaeSTheodore Ts'o 		ret = -EFSCORRUPTED;
47938e4b5eaeSTheodore Ts'o 		goto bad_inode;
47948e4b5eaeSTheodore Ts'o 	}
47958e4b5eaeSTheodore Ts'o 
47968a363970STheodore Ts'o 	if ((flags & EXT4_IGET_HANDLE) &&
47978a363970STheodore Ts'o 	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
47988a363970STheodore Ts'o 		ret = -ESTALE;
47998a363970STheodore Ts'o 		goto bad_inode;
48008a363970STheodore Ts'o 	}
48018a363970STheodore Ts'o 
4802814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4803814525f4SDarrick J. Wong 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4804814525f4SDarrick J. Wong 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
48052dc8d9e1SEric Biggers 			EXT4_INODE_SIZE(inode->i_sb) ||
48062dc8d9e1SEric Biggers 		    (ei->i_extra_isize & 3)) {
48078a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
48088a363970STheodore Ts'o 					 "iget: bad extra_isize %u "
48098a363970STheodore Ts'o 					 "(inode size %u)",
48102dc8d9e1SEric Biggers 					 ei->i_extra_isize,
4811814525f4SDarrick J. Wong 					 EXT4_INODE_SIZE(inode->i_sb));
48126a797d27SDarrick J. Wong 			ret = -EFSCORRUPTED;
4813814525f4SDarrick J. Wong 			goto bad_inode;
4814814525f4SDarrick J. Wong 		}
4815814525f4SDarrick J. Wong 	} else
4816814525f4SDarrick J. Wong 		ei->i_extra_isize = 0;
4817814525f4SDarrick J. Wong 
4818814525f4SDarrick J. Wong 	/* Precompute checksum seed for inode metadata */
48199aa5d32bSDmitry Monakhov 	if (ext4_has_metadata_csum(sb)) {
4820814525f4SDarrick J. Wong 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4821814525f4SDarrick J. Wong 		__u32 csum;
4822814525f4SDarrick J. Wong 		__le32 inum = cpu_to_le32(inode->i_ino);
4823814525f4SDarrick J. Wong 		__le32 gen = raw_inode->i_generation;
4824814525f4SDarrick J. Wong 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4825814525f4SDarrick J. Wong 				   sizeof(inum));
4826814525f4SDarrick J. Wong 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4827814525f4SDarrick J. Wong 					      sizeof(gen));
4828814525f4SDarrick J. Wong 	}
4829814525f4SDarrick J. Wong 
48308016e29fSHarshad Shirwadkar 	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
48318016e29fSHarshad Shirwadkar 	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
48328016e29fSHarshad Shirwadkar 	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
48338016e29fSHarshad Shirwadkar 		ext4_error_inode_err(inode, function, line, 0,
48348016e29fSHarshad Shirwadkar 				EFSBADCRC, "iget: checksum invalid");
48356a797d27SDarrick J. Wong 		ret = -EFSBADCRC;
4836814525f4SDarrick J. Wong 		goto bad_inode;
4837814525f4SDarrick J. Wong 	}
4838814525f4SDarrick J. Wong 
4839ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
484008cefc7aSEric W. Biederman 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
484108cefc7aSEric W. Biederman 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
48420b7b7779SKaho Ng 	if (ext4_has_feature_project(sb) &&
4843040cb378SLi Xi 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4844040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4845040cb378SLi Xi 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4846040cb378SLi Xi 	else
4847040cb378SLi Xi 		i_projid = EXT4_DEF_PROJID;
4848040cb378SLi Xi 
4849ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
485008cefc7aSEric W. Biederman 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
485108cefc7aSEric W. Biederman 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4852ac27a0ecSDave Kleikamp 	}
485308cefc7aSEric W. Biederman 	i_uid_write(inode, i_uid);
485408cefc7aSEric W. Biederman 	i_gid_write(inode, i_gid);
4855040cb378SLi Xi 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4856bfe86848SMiklos Szeredi 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4857ac27a0ecSDave Kleikamp 
4858353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
485967cf5b09STao Ma 	ei->i_inline_off = 0;
4860ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
4861ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4862ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
4863ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
4864ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
4865ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
4866ac27a0ecSDave Kleikamp 	 */
4867ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
4868393d1d1dSDr. Tilmann Bubeck 		if ((inode->i_mode == 0 ||
4869393d1d1dSDr. Tilmann Bubeck 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4870393d1d1dSDr. Tilmann Bubeck 		    ino != EXT4_BOOT_LOADER_INO) {
4871ac27a0ecSDave Kleikamp 			/* this inode is deleted */
48721d1fe1eeSDavid Howells 			ret = -ESTALE;
4873ac27a0ecSDave Kleikamp 			goto bad_inode;
4874ac27a0ecSDave Kleikamp 		}
4875ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
4876ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
4877ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
4878393d1d1dSDr. Tilmann Bubeck 		 * the process of deleting those.
4879393d1d1dSDr. Tilmann Bubeck 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4880393d1d1dSDr. Tilmann Bubeck 		 * not initialized on a new filesystem. */
4881ac27a0ecSDave Kleikamp 	}
4882ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4883043546e4SIra Weiny 	ext4_set_inode_flags(inode, true);
48840fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
48857973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4886e2b911c5SDarrick J. Wong 	if (ext4_has_feature_64bit(sb))
4887a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
4888a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4889e08ac99fSArtem Blagodarenko 	inode->i_size = ext4_isize(sb, raw_inode);
48907e6e1ef4SDarrick J. Wong 	if ((size = i_size_read(inode)) < 0) {
48918a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
48928a363970STheodore Ts'o 				 "iget: bad i_size value: %lld", size);
48937e6e1ef4SDarrick J. Wong 		ret = -EFSCORRUPTED;
48947e6e1ef4SDarrick J. Wong 		goto bad_inode;
48957e6e1ef4SDarrick J. Wong 	}
489648a34311SJan Kara 	/*
489748a34311SJan Kara 	 * If dir_index is not enabled but there's dir with INDEX flag set,
489848a34311SJan Kara 	 * we'd normally treat htree data as empty space. But with metadata
489948a34311SJan Kara 	 * checksumming that corrupts checksums so forbid that.
490048a34311SJan Kara 	 */
490148a34311SJan Kara 	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
490248a34311SJan Kara 	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
490348a34311SJan Kara 		ext4_error_inode(inode, function, line, 0,
490448a34311SJan Kara 			 "iget: Dir with htree data on filesystem without dir_index feature.");
490548a34311SJan Kara 		ret = -EFSCORRUPTED;
490648a34311SJan Kara 		goto bad_inode;
490748a34311SJan Kara 	}
4908ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
4909a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
4910a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
4911a9e7f447SDmitry Monakhov #endif
4912ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4913ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
4914a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
4915ac27a0ecSDave Kleikamp 	/*
4916ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
4917ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4918ac27a0ecSDave Kleikamp 	 */
4919617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4920ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
4921ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
4922aa75f4d3SHarshad Shirwadkar 	ext4_fc_init_inode(&ei->vfs_inode);
4923ac27a0ecSDave Kleikamp 
4924b436b9beSJan Kara 	/*
4925b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
4926b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
4927b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
4928b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
4929b436b9beSJan Kara 	 * now it is reread from disk.
4930b436b9beSJan Kara 	 */
4931b436b9beSJan Kara 	if (journal) {
4932b436b9beSJan Kara 		transaction_t *transaction;
4933b436b9beSJan Kara 		tid_t tid;
4934b436b9beSJan Kara 
4935a931da6aSTheodore Ts'o 		read_lock(&journal->j_state_lock);
4936b436b9beSJan Kara 		if (journal->j_running_transaction)
4937b436b9beSJan Kara 			transaction = journal->j_running_transaction;
4938b436b9beSJan Kara 		else
4939b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
4940b436b9beSJan Kara 		if (transaction)
4941b436b9beSJan Kara 			tid = transaction->t_tid;
4942b436b9beSJan Kara 		else
4943b436b9beSJan Kara 			tid = journal->j_commit_sequence;
4944a931da6aSTheodore Ts'o 		read_unlock(&journal->j_state_lock);
4945b436b9beSJan Kara 		ei->i_sync_tid = tid;
4946b436b9beSJan Kara 		ei->i_datasync_tid = tid;
4947b436b9beSJan Kara 	}
4948b436b9beSJan Kara 
49490040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4950ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
4951ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
49522dc8d9e1SEric Biggers 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4953617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4954617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
4955ac27a0ecSDave Kleikamp 		} else {
4956eb9b5f01STheodore Ts'o 			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4957eb9b5f01STheodore Ts'o 			if (ret)
4958eb9b5f01STheodore Ts'o 				goto bad_inode;
4959ac27a0ecSDave Kleikamp 		}
4960814525f4SDarrick J. Wong 	}
4961ac27a0ecSDave Kleikamp 
4962ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4963ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4964ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4965ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4966ef7f3835SKalpak Shah 
4967ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4968ee73f9a5SJeff Layton 		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4969ee73f9a5SJeff Layton 
497025ec56b5SJean Noel Cordenner 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
497125ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4972ee73f9a5SJeff Layton 				ivers |=
497325ec56b5SJean Noel Cordenner 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
497425ec56b5SJean Noel Cordenner 		}
4975e254d1afSEryu Guan 		ext4_inode_set_iversion_queried(inode, ivers);
4976c4f65706STheodore Ts'o 	}
497725ec56b5SJean Noel Cordenner 
4978c4b5a614STheodore Ts'o 	ret = 0;
4979485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
4980ce9f24ccSJan Kara 	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
49818a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
49828a363970STheodore Ts'o 				 "iget: bad extended attribute block %llu",
498324676da4STheodore Ts'o 				 ei->i_file_acl);
49846a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
4985485c26ecSTheodore Ts'o 		goto bad_inode;
4986f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
4987bc716523SLiu Song 		/* validate the block references in the inode */
49888016e29fSHarshad Shirwadkar 		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
49898016e29fSHarshad Shirwadkar 			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4990fe2c8191SThiemo Nagel 			(S_ISLNK(inode->i_mode) &&
49918016e29fSHarshad Shirwadkar 			!ext4_inode_is_fast_symlink(inode)))) {
4992bc716523SLiu Song 			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4993bc716523SLiu Song 				ret = ext4_ext_check_inode(inode);
4994bc716523SLiu Song 			else
49951f7d1e77STheodore Ts'o 				ret = ext4_ind_check_inode(inode);
4996fe2c8191SThiemo Nagel 		}
4997f19d5870STao Ma 	}
4998567f3e9aSTheodore Ts'o 	if (ret)
49997a262f7cSAneesh Kumar K.V 		goto bad_inode;
50007a262f7cSAneesh Kumar K.V 
5001ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
5002617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
5003617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
5004617ba13bSMingming Cao 		ext4_set_aops(inode);
5005ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
5006617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
5007617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
5008ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
50096390d33bSLuis R. Rodriguez 		/* VFS does not allow setting these so must be corruption */
50106390d33bSLuis R. Rodriguez 		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
50118a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
50128a363970STheodore Ts'o 					 "iget: immutable or append flags "
50138a363970STheodore Ts'o 					 "not allowed on symlinks");
50146390d33bSLuis R. Rodriguez 			ret = -EFSCORRUPTED;
50156390d33bSLuis R. Rodriguez 			goto bad_inode;
50166390d33bSLuis R. Rodriguez 		}
5017592ddec7SChandan Rajendra 		if (IS_ENCRYPTED(inode)) {
5018a7a67e8aSAl Viro 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
5019a7a67e8aSAl Viro 		} else if (ext4_inode_is_fast_symlink(inode)) {
502075e7566bSAl Viro 			inode->i_link = (char *)ei->i_data;
5021617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
5022e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
5023e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
5024e83c1397SDuane Griffin 		} else {
5025617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
5026ac27a0ecSDave Kleikamp 		}
5027563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5028563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5029617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
5030ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
5031ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5032ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5033ac27a0ecSDave Kleikamp 		else
5034ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5035ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5036393d1d1dSDr. Tilmann Bubeck 	} else if (ino == EXT4_BOOT_LOADER_INO) {
5037393d1d1dSDr. Tilmann Bubeck 		make_bad_inode(inode);
5038563bdd61STheodore Ts'o 	} else {
50396a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
50408a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
50418a363970STheodore Ts'o 				 "iget: bogus i_mode (%o)", inode->i_mode);
5042563bdd61STheodore Ts'o 		goto bad_inode;
5043ac27a0ecSDave Kleikamp 	}
50446456ca65STheodore Ts'o 	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
50456456ca65STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
50466456ca65STheodore Ts'o 				 "casefold flag without casefold feature");
5047ac27a0ecSDave Kleikamp 	brelse(iloc.bh);
5048dec214d0STahsin Erdogan 
50491d1fe1eeSDavid Howells 	unlock_new_inode(inode);
50501d1fe1eeSDavid Howells 	return inode;
5051ac27a0ecSDave Kleikamp 
5052ac27a0ecSDave Kleikamp bad_inode:
5053567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
50541d1fe1eeSDavid Howells 	iget_failed(inode);
50551d1fe1eeSDavid Howells 	return ERR_PTR(ret);
5056ac27a0ecSDave Kleikamp }
5057ac27a0ecSDave Kleikamp 
50583f19b2abSDavid Howells static void __ext4_update_other_inode_time(struct super_block *sb,
50593f19b2abSDavid Howells 					   unsigned long orig_ino,
50603f19b2abSDavid Howells 					   unsigned long ino,
50613f19b2abSDavid Howells 					   struct ext4_inode *raw_inode)
5062a26f4992STheodore Ts'o {
50633f19b2abSDavid Howells 	struct inode *inode;
5064a26f4992STheodore Ts'o 
50653f19b2abSDavid Howells 	inode = find_inode_by_ino_rcu(sb, ino);
50663f19b2abSDavid Howells 	if (!inode)
50673f19b2abSDavid Howells 		return;
50683f19b2abSDavid Howells 
5069ed296c6cSEric Biggers 	if (!inode_is_dirtytime_only(inode))
50703f19b2abSDavid Howells 		return;
50713f19b2abSDavid Howells 
5072a26f4992STheodore Ts'o 	spin_lock(&inode->i_lock);
5073ed296c6cSEric Biggers 	if (inode_is_dirtytime_only(inode)) {
5074a26f4992STheodore Ts'o 		struct ext4_inode_info	*ei = EXT4_I(inode);
5075a26f4992STheodore Ts'o 
50765fcd5750SJan Kara 		inode->i_state &= ~I_DIRTY_TIME;
5077a26f4992STheodore Ts'o 		spin_unlock(&inode->i_lock);
5078a26f4992STheodore Ts'o 
5079a26f4992STheodore Ts'o 		spin_lock(&ei->i_raw_lock);
50803f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
50813f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
50823f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
50833f19b2abSDavid Howells 		ext4_inode_csum_set(inode, raw_inode, ei);
5084a26f4992STheodore Ts'o 		spin_unlock(&ei->i_raw_lock);
50853f19b2abSDavid Howells 		trace_ext4_other_inode_update_time(inode, orig_ino);
50863f19b2abSDavid Howells 		return;
5087a26f4992STheodore Ts'o 	}
5088a26f4992STheodore Ts'o 	spin_unlock(&inode->i_lock);
5089a26f4992STheodore Ts'o }
5090a26f4992STheodore Ts'o 
5091a26f4992STheodore Ts'o /*
5092a26f4992STheodore Ts'o  * Opportunistically update the other time fields for other inodes in
5093a26f4992STheodore Ts'o  * the same inode table block.
5094a26f4992STheodore Ts'o  */
5095a26f4992STheodore Ts'o static void ext4_update_other_inodes_time(struct super_block *sb,
5096a26f4992STheodore Ts'o 					  unsigned long orig_ino, char *buf)
5097a26f4992STheodore Ts'o {
5098a26f4992STheodore Ts'o 	unsigned long ino;
5099a26f4992STheodore Ts'o 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5100a26f4992STheodore Ts'o 	int inode_size = EXT4_INODE_SIZE(sb);
5101a26f4992STheodore Ts'o 
51020f0ff9a9STheodore Ts'o 	/*
51030f0ff9a9STheodore Ts'o 	 * Calculate the first inode in the inode table block.  Inode
51040f0ff9a9STheodore Ts'o 	 * numbers are one-based.  That is, the first inode in a block
51050f0ff9a9STheodore Ts'o 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
51060f0ff9a9STheodore Ts'o 	 */
51070f0ff9a9STheodore Ts'o 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
51083f19b2abSDavid Howells 	rcu_read_lock();
5109a26f4992STheodore Ts'o 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5110a26f4992STheodore Ts'o 		if (ino == orig_ino)
5111a26f4992STheodore Ts'o 			continue;
51123f19b2abSDavid Howells 		__ext4_update_other_inode_time(sb, orig_ino, ino,
51133f19b2abSDavid Howells 					       (struct ext4_inode *)buf);
5114a26f4992STheodore Ts'o 	}
51153f19b2abSDavid Howells 	rcu_read_unlock();
5116a26f4992STheodore Ts'o }
5117a26f4992STheodore Ts'o 
5118664bd38bSZhang Yi /*
5119664bd38bSZhang Yi  * Post the struct inode info into an on-disk inode location in the
5120664bd38bSZhang Yi  * buffer-cache.  This gobbles the caller's reference to the
5121664bd38bSZhang Yi  * buffer_head in the inode location struct.
5122664bd38bSZhang Yi  *
5123664bd38bSZhang Yi  * The caller must have write access to iloc->bh.
5124664bd38bSZhang Yi  */
5125664bd38bSZhang Yi static int ext4_do_update_inode(handle_t *handle,
5126664bd38bSZhang Yi 				struct inode *inode,
5127664bd38bSZhang Yi 				struct ext4_iloc *iloc)
5128664bd38bSZhang Yi {
5129664bd38bSZhang Yi 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5130664bd38bSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
5131664bd38bSZhang Yi 	struct buffer_head *bh = iloc->bh;
5132664bd38bSZhang Yi 	struct super_block *sb = inode->i_sb;
5133664bd38bSZhang Yi 	int err;
5134664bd38bSZhang Yi 	int need_datasync = 0, set_large_file = 0;
5135664bd38bSZhang Yi 
5136664bd38bSZhang Yi 	spin_lock(&ei->i_raw_lock);
5137664bd38bSZhang Yi 
5138664bd38bSZhang Yi 	/*
5139664bd38bSZhang Yi 	 * For fields not tracked in the in-memory inode, initialise them
5140664bd38bSZhang Yi 	 * to zero for new inodes.
5141664bd38bSZhang Yi 	 */
5142664bd38bSZhang Yi 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5143664bd38bSZhang Yi 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5144664bd38bSZhang Yi 
5145664bd38bSZhang Yi 	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5146664bd38bSZhang Yi 		need_datasync = 1;
5147664bd38bSZhang Yi 	if (ei->i_disksize > 0x7fffffffULL) {
5148664bd38bSZhang Yi 		if (!ext4_has_feature_large_file(sb) ||
5149664bd38bSZhang Yi 		    EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5150664bd38bSZhang Yi 			set_large_file = 1;
5151664bd38bSZhang Yi 	}
5152664bd38bSZhang Yi 
5153664bd38bSZhang Yi 	err = ext4_fill_raw_inode(inode, raw_inode);
5154202ee5dfSTheodore Ts'o 	spin_unlock(&ei->i_raw_lock);
5155baaae979SZhang Yi 	if (err) {
5156baaae979SZhang Yi 		EXT4_ERROR_INODE(inode, "corrupted inode contents");
5157baaae979SZhang Yi 		goto out_brelse;
5158baaae979SZhang Yi 	}
5159baaae979SZhang Yi 
51601751e8a6SLinus Torvalds 	if (inode->i_sb->s_flags & SB_LAZYTIME)
5161a26f4992STheodore Ts'o 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5162a26f4992STheodore Ts'o 					      bh->b_data);
5163202ee5dfSTheodore Ts'o 
51640390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
51657d8bd3c7SShijie Luo 	err = ext4_handle_dirty_metadata(handle, NULL, bh);
51667d8bd3c7SShijie Luo 	if (err)
5167baaae979SZhang Yi 		goto out_error;
516819f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5169202ee5dfSTheodore Ts'o 	if (set_large_file) {
51705d601255Sliang xie 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5171188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, sb,
5172188c299eSJan Kara 						    EXT4_SB(sb)->s_sbh,
5173188c299eSJan Kara 						    EXT4_JTR_NONE);
5174202ee5dfSTheodore Ts'o 		if (err)
5175baaae979SZhang Yi 			goto out_error;
517605c2c00fSJan Kara 		lock_buffer(EXT4_SB(sb)->s_sbh);
5177e2b911c5SDarrick J. Wong 		ext4_set_feature_large_file(sb);
517805c2c00fSJan Kara 		ext4_superblock_csum_set(sb);
517905c2c00fSJan Kara 		unlock_buffer(EXT4_SB(sb)->s_sbh);
5180202ee5dfSTheodore Ts'o 		ext4_handle_sync(handle);
5181a3f5cf14SJan Kara 		err = ext4_handle_dirty_metadata(handle, NULL,
5182a3f5cf14SJan Kara 						 EXT4_SB(sb)->s_sbh);
5183202ee5dfSTheodore Ts'o 	}
5184b71fc079SJan Kara 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5185baaae979SZhang Yi out_error:
5186baaae979SZhang Yi 	ext4_std_error(inode->i_sb, err);
5187ac27a0ecSDave Kleikamp out_brelse:
5188ac27a0ecSDave Kleikamp 	brelse(bh);
5189ac27a0ecSDave Kleikamp 	return err;
5190ac27a0ecSDave Kleikamp }
5191ac27a0ecSDave Kleikamp 
5192ac27a0ecSDave Kleikamp /*
5193617ba13bSMingming Cao  * ext4_write_inode()
5194ac27a0ecSDave Kleikamp  *
5195ac27a0ecSDave Kleikamp  * We are called from a few places:
5196ac27a0ecSDave Kleikamp  *
519787f7e416STheodore Ts'o  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5198ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
51994907cb7bSAnatol Pomozov  *   transaction to commit.
5200ac27a0ecSDave Kleikamp  *
520187f7e416STheodore Ts'o  * - Within flush work (sys_sync(), kupdate and such).
520287f7e416STheodore Ts'o  *   We wait on commit, if told to.
5203ac27a0ecSDave Kleikamp  *
520487f7e416STheodore Ts'o  * - Within iput_final() -> write_inode_now()
520587f7e416STheodore Ts'o  *   We wait on commit, if told to.
5206ac27a0ecSDave Kleikamp  *
5207ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
5208ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
520987f7e416STheodore Ts'o  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
521087f7e416STheodore Ts'o  * writeback.
5211ac27a0ecSDave Kleikamp  *
5212ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
5213ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5214ac27a0ecSDave Kleikamp  * which we are interested.
5215ac27a0ecSDave Kleikamp  *
5216ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
5217ac27a0ecSDave Kleikamp  *
5218ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
5219ac27a0ecSDave Kleikamp  *	stuff();
5220ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
5221ac27a0ecSDave Kleikamp  *
522287f7e416STheodore Ts'o  * is in error because write_inode() could occur while `stuff()' is running,
522387f7e416STheodore Ts'o  * and the new i_size will be lost.  Plus the inode will no longer be on the
522487f7e416STheodore Ts'o  * superblock's dirty inode list.
5225ac27a0ecSDave Kleikamp  */
5226a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5227ac27a0ecSDave Kleikamp {
522891ac6f43SFrank Mayhar 	int err;
522991ac6f43SFrank Mayhar 
523018f2c4fcSTheodore Ts'o 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
523118f2c4fcSTheodore Ts'o 	    sb_rdonly(inode->i_sb))
5232ac27a0ecSDave Kleikamp 		return 0;
5233ac27a0ecSDave Kleikamp 
523418f2c4fcSTheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
523518f2c4fcSTheodore Ts'o 		return -EIO;
523618f2c4fcSTheodore Ts'o 
523791ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
5238617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
52394978c659SJan Kara 			ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5240ac27a0ecSDave Kleikamp 			dump_stack();
5241ac27a0ecSDave Kleikamp 			return -EIO;
5242ac27a0ecSDave Kleikamp 		}
5243ac27a0ecSDave Kleikamp 
524410542c22SJan Kara 		/*
524510542c22SJan Kara 		 * No need to force transaction in WB_SYNC_NONE mode. Also
524610542c22SJan Kara 		 * ext4_sync_fs() will force the commit after everything is
524710542c22SJan Kara 		 * written.
524810542c22SJan Kara 		 */
524910542c22SJan Kara 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5250ac27a0ecSDave Kleikamp 			return 0;
5251ac27a0ecSDave Kleikamp 
5252aa75f4d3SHarshad Shirwadkar 		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
525318f2c4fcSTheodore Ts'o 						EXT4_I(inode)->i_sync_tid);
525491ac6f43SFrank Mayhar 	} else {
525591ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
525691ac6f43SFrank Mayhar 
52578016e29fSHarshad Shirwadkar 		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
525891ac6f43SFrank Mayhar 		if (err)
525991ac6f43SFrank Mayhar 			return err;
526010542c22SJan Kara 		/*
526110542c22SJan Kara 		 * sync(2) will flush the whole buffer cache. No need to do
526210542c22SJan Kara 		 * it here separately for each inode.
526310542c22SJan Kara 		 */
526410542c22SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5265830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
5266830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
526754d3adbcSTheodore Ts'o 			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5268c398eda0STheodore Ts'o 					       "IO error syncing inode");
5269830156c7SFrank Mayhar 			err = -EIO;
5270830156c7SFrank Mayhar 		}
5271fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
527291ac6f43SFrank Mayhar 	}
527391ac6f43SFrank Mayhar 	return err;
5274ac27a0ecSDave Kleikamp }
5275ac27a0ecSDave Kleikamp 
5276ac27a0ecSDave Kleikamp /*
5277ccd16945SMatthew Wilcox (Oracle)  * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5278ccd16945SMatthew Wilcox (Oracle)  * buffers that are attached to a folio straddling i_size and are undergoing
527953e87268SJan Kara  * commit. In that case we have to wait for commit to finish and try again.
528053e87268SJan Kara  */
528153e87268SJan Kara static void ext4_wait_for_tail_page_commit(struct inode *inode)
528253e87268SJan Kara {
528353e87268SJan Kara 	unsigned offset;
528453e87268SJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
528553e87268SJan Kara 	tid_t commit_tid = 0;
528653e87268SJan Kara 	int ret;
528753e87268SJan Kara 
528809cbfeafSKirill A. Shutemov 	offset = inode->i_size & (PAGE_SIZE - 1);
528953e87268SJan Kara 	/*
5290ccd16945SMatthew Wilcox (Oracle) 	 * If the folio is fully truncated, we don't need to wait for any commit
5291ccd16945SMatthew Wilcox (Oracle) 	 * (and we even should not as __ext4_journalled_invalidate_folio() may
5292ccd16945SMatthew Wilcox (Oracle) 	 * strip all buffers from the folio but keep the folio dirty which can then
5293ccd16945SMatthew Wilcox (Oracle) 	 * confuse e.g. concurrent ext4_writepage() seeing dirty folio without
5294565333a1Syangerkun 	 * buffers). Also we don't need to wait for any commit if all buffers in
5295ccd16945SMatthew Wilcox (Oracle) 	 * the folio remain valid. This is most beneficial for the common case of
5296565333a1Syangerkun 	 * blocksize == PAGESIZE.
529753e87268SJan Kara 	 */
5298565333a1Syangerkun 	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
529953e87268SJan Kara 		return;
530053e87268SJan Kara 	while (1) {
5301ccd16945SMatthew Wilcox (Oracle) 		struct folio *folio = filemap_lock_folio(inode->i_mapping,
530209cbfeafSKirill A. Shutemov 				      inode->i_size >> PAGE_SHIFT);
5303ccd16945SMatthew Wilcox (Oracle) 		if (!folio)
530453e87268SJan Kara 			return;
5305ccd16945SMatthew Wilcox (Oracle) 		ret = __ext4_journalled_invalidate_folio(folio, offset,
5306ccd16945SMatthew Wilcox (Oracle) 						folio_size(folio) - offset);
5307ccd16945SMatthew Wilcox (Oracle) 		folio_unlock(folio);
5308ccd16945SMatthew Wilcox (Oracle) 		folio_put(folio);
530953e87268SJan Kara 		if (ret != -EBUSY)
531053e87268SJan Kara 			return;
531153e87268SJan Kara 		commit_tid = 0;
531253e87268SJan Kara 		read_lock(&journal->j_state_lock);
531353e87268SJan Kara 		if (journal->j_committing_transaction)
531453e87268SJan Kara 			commit_tid = journal->j_committing_transaction->t_tid;
531553e87268SJan Kara 		read_unlock(&journal->j_state_lock);
531653e87268SJan Kara 		if (commit_tid)
531753e87268SJan Kara 			jbd2_log_wait_commit(journal, commit_tid);
531853e87268SJan Kara 	}
531953e87268SJan Kara }
532053e87268SJan Kara 
532153e87268SJan Kara /*
5322617ba13bSMingming Cao  * ext4_setattr()
5323ac27a0ecSDave Kleikamp  *
5324ac27a0ecSDave Kleikamp  * Called from notify_change.
5325ac27a0ecSDave Kleikamp  *
5326ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
5327ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
5328ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
5329ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
5330ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
5331ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
5332ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
5333ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
5334ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
5335ac27a0ecSDave Kleikamp  *
5336678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
5337678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
5338678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
5339678aaf48SJan Kara  * This way we are sure that all the data written in the previous
5340678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
5341678aaf48SJan Kara  * writeback).
5342678aaf48SJan Kara  *
5343f340b3d9Shongnanli  * Called with inode->i_rwsem down.
5344ac27a0ecSDave Kleikamp  */
5345549c7297SChristian Brauner int ext4_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5346549c7297SChristian Brauner 		 struct iattr *attr)
5347ac27a0ecSDave Kleikamp {
53482b0143b5SDavid Howells 	struct inode *inode = d_inode(dentry);
5349ac27a0ecSDave Kleikamp 	int error, rc = 0;
53503d287de3SDmitry Monakhov 	int orphan = 0;
5351ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
5352a642c2c0SJeff Layton 	bool inc_ivers = true;
5353ac27a0ecSDave Kleikamp 
53540db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
53550db1ff22STheodore Ts'o 		return -EIO;
53560db1ff22STheodore Ts'o 
535702b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
535802b016caSTheodore Ts'o 		return -EPERM;
535902b016caSTheodore Ts'o 
536002b016caSTheodore Ts'o 	if (unlikely(IS_APPEND(inode) &&
536102b016caSTheodore Ts'o 		     (ia_valid & (ATTR_MODE | ATTR_UID |
536202b016caSTheodore Ts'o 				  ATTR_GID | ATTR_TIMES_SET))))
536302b016caSTheodore Ts'o 		return -EPERM;
536402b016caSTheodore Ts'o 
536514f3db55SChristian Brauner 	error = setattr_prepare(mnt_userns, dentry, attr);
5366ac27a0ecSDave Kleikamp 	if (error)
5367ac27a0ecSDave Kleikamp 		return error;
5368ac27a0ecSDave Kleikamp 
53693ce2b8ddSEric Biggers 	error = fscrypt_prepare_setattr(dentry, attr);
53703ce2b8ddSEric Biggers 	if (error)
53713ce2b8ddSEric Biggers 		return error;
53723ce2b8ddSEric Biggers 
5373c93d8f88SEric Biggers 	error = fsverity_prepare_setattr(dentry, attr);
5374c93d8f88SEric Biggers 	if (error)
5375c93d8f88SEric Biggers 		return error;
5376c93d8f88SEric Biggers 
5377b27c82e1SChristian Brauner 	if (is_quota_modification(mnt_userns, inode, attr)) {
5378a7cdadeeSJan Kara 		error = dquot_initialize(inode);
5379a7cdadeeSJan Kara 		if (error)
5380a7cdadeeSJan Kara 			return error;
5381a7cdadeeSJan Kara 	}
53822729cfdcSHarshad Shirwadkar 
5383b27c82e1SChristian Brauner 	if (i_uid_needs_update(mnt_userns, attr, inode) ||
5384b27c82e1SChristian Brauner 	    i_gid_needs_update(mnt_userns, attr, inode)) {
5385ac27a0ecSDave Kleikamp 		handle_t *handle;
5386ac27a0ecSDave Kleikamp 
5387ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
5388ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
53899924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
53909924a92aSTheodore Ts'o 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5391194074acSDmitry Monakhov 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5392ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
5393ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
5394ac27a0ecSDave Kleikamp 			goto err_out;
5395ac27a0ecSDave Kleikamp 		}
53967a9ca53aSTahsin Erdogan 
53977a9ca53aSTahsin Erdogan 		/* dquot_transfer() calls back ext4_get_inode_usage() which
53987a9ca53aSTahsin Erdogan 		 * counts xattr inode references.
53997a9ca53aSTahsin Erdogan 		 */
54007a9ca53aSTahsin Erdogan 		down_read(&EXT4_I(inode)->xattr_sem);
5401b27c82e1SChristian Brauner 		error = dquot_transfer(mnt_userns, inode, attr);
54027a9ca53aSTahsin Erdogan 		up_read(&EXT4_I(inode)->xattr_sem);
54037a9ca53aSTahsin Erdogan 
5404ac27a0ecSDave Kleikamp 		if (error) {
5405617ba13bSMingming Cao 			ext4_journal_stop(handle);
5406ac27a0ecSDave Kleikamp 			return error;
5407ac27a0ecSDave Kleikamp 		}
5408ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
5409ac27a0ecSDave Kleikamp 		 * one transaction */
5410b27c82e1SChristian Brauner 		i_uid_update(mnt_userns, attr, inode);
5411b27c82e1SChristian Brauner 		i_gid_update(mnt_userns, attr, inode);
5412617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
5413617ba13bSMingming Cao 		ext4_journal_stop(handle);
5414512c15efSPan Bian 		if (unlikely(error)) {
54154209ae12SHarshad Shirwadkar 			return error;
5416ac27a0ecSDave Kleikamp 		}
5417512c15efSPan Bian 	}
5418ac27a0ecSDave Kleikamp 
54193da40c7bSJosef Bacik 	if (attr->ia_valid & ATTR_SIZE) {
54205208386cSJan Kara 		handle_t *handle;
54213da40c7bSJosef Bacik 		loff_t oldsize = inode->i_size;
5422f4534c9fSYe Bin 		loff_t old_disksize;
5423b9c1c267SJan Kara 		int shrink = (attr->ia_size < inode->i_size);
5424562c72aaSChristoph Hellwig 
542512e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5426e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5427e2b46574SEric Sandeen 
5428aa75f4d3SHarshad Shirwadkar 			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
54290c095c7fSTheodore Ts'o 				return -EFBIG;
5430e2b46574SEric Sandeen 			}
5431aa75f4d3SHarshad Shirwadkar 		}
5432aa75f4d3SHarshad Shirwadkar 		if (!S_ISREG(inode->i_mode)) {
54333da40c7bSJosef Bacik 			return -EINVAL;
5434aa75f4d3SHarshad Shirwadkar 		}
5435dff6efc3SChristoph Hellwig 
5436a642c2c0SJeff Layton 		if (attr->ia_size == inode->i_size)
5437a642c2c0SJeff Layton 			inc_ivers = false;
5438dff6efc3SChristoph Hellwig 
5439b9c1c267SJan Kara 		if (shrink) {
5440b9c1c267SJan Kara 			if (ext4_should_order_data(inode)) {
54415208386cSJan Kara 				error = ext4_begin_ordered_truncate(inode,
54425208386cSJan Kara 							    attr->ia_size);
54435208386cSJan Kara 				if (error)
54445208386cSJan Kara 					goto err_out;
54455208386cSJan Kara 			}
5446b9c1c267SJan Kara 			/*
5447b9c1c267SJan Kara 			 * Blocks are going to be removed from the inode. Wait
5448b9c1c267SJan Kara 			 * for dio in flight.
5449b9c1c267SJan Kara 			 */
5450b9c1c267SJan Kara 			inode_dio_wait(inode);
5451b9c1c267SJan Kara 		}
5452b9c1c267SJan Kara 
5453d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
5454b9c1c267SJan Kara 
5455b9c1c267SJan Kara 		rc = ext4_break_layouts(inode);
5456b9c1c267SJan Kara 		if (rc) {
5457d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
5458aa75f4d3SHarshad Shirwadkar 			goto err_out;
5459b9c1c267SJan Kara 		}
5460b9c1c267SJan Kara 
54613da40c7bSJosef Bacik 		if (attr->ia_size != inode->i_size) {
54629924a92aSTheodore Ts'o 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5463ac27a0ecSDave Kleikamp 			if (IS_ERR(handle)) {
5464ac27a0ecSDave Kleikamp 				error = PTR_ERR(handle);
5465b9c1c267SJan Kara 				goto out_mmap_sem;
5466ac27a0ecSDave Kleikamp 			}
54673da40c7bSJosef Bacik 			if (ext4_handle_valid(handle) && shrink) {
5468617ba13bSMingming Cao 				error = ext4_orphan_add(handle, inode);
54693d287de3SDmitry Monakhov 				orphan = 1;
54703d287de3SDmitry Monakhov 			}
5471911af577SEryu Guan 			/*
5472911af577SEryu Guan 			 * Update c/mtime on truncate up, ext4_truncate() will
5473911af577SEryu Guan 			 * update c/mtime in shrink case below
5474911af577SEryu Guan 			 */
5475911af577SEryu Guan 			if (!shrink) {
5476eeca7ea1SDeepa Dinamani 				inode->i_mtime = current_time(inode);
5477911af577SEryu Guan 				inode->i_ctime = inode->i_mtime;
5478911af577SEryu Guan 			}
5479aa75f4d3SHarshad Shirwadkar 
5480aa75f4d3SHarshad Shirwadkar 			if (shrink)
5481a80f7fcfSHarshad Shirwadkar 				ext4_fc_track_range(handle, inode,
5482aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5483aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
54849725958bSXin Yin 					EXT_MAX_BLOCKS - 1);
5485aa75f4d3SHarshad Shirwadkar 			else
5486aa75f4d3SHarshad Shirwadkar 				ext4_fc_track_range(
5487a80f7fcfSHarshad Shirwadkar 					handle, inode,
5488aa75f4d3SHarshad Shirwadkar 					(oldsize > 0 ? oldsize - 1 : oldsize) >>
5489aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
5490aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5491aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits);
5492aa75f4d3SHarshad Shirwadkar 
549390e775b7SJan Kara 			down_write(&EXT4_I(inode)->i_data_sem);
5494f4534c9fSYe Bin 			old_disksize = EXT4_I(inode)->i_disksize;
5495617ba13bSMingming Cao 			EXT4_I(inode)->i_disksize = attr->ia_size;
5496617ba13bSMingming Cao 			rc = ext4_mark_inode_dirty(handle, inode);
5497ac27a0ecSDave Kleikamp 			if (!error)
5498ac27a0ecSDave Kleikamp 				error = rc;
549990e775b7SJan Kara 			/*
550090e775b7SJan Kara 			 * We have to update i_size under i_data_sem together
550190e775b7SJan Kara 			 * with i_disksize to avoid races with writeback code
550290e775b7SJan Kara 			 * running ext4_wb_update_i_disksize().
550390e775b7SJan Kara 			 */
550490e775b7SJan Kara 			if (!error)
550590e775b7SJan Kara 				i_size_write(inode, attr->ia_size);
5506f4534c9fSYe Bin 			else
5507f4534c9fSYe Bin 				EXT4_I(inode)->i_disksize = old_disksize;
550890e775b7SJan Kara 			up_write(&EXT4_I(inode)->i_data_sem);
5509617ba13bSMingming Cao 			ext4_journal_stop(handle);
5510b9c1c267SJan Kara 			if (error)
5511b9c1c267SJan Kara 				goto out_mmap_sem;
551282a25b02SJan Kara 			if (!shrink) {
5513b9c1c267SJan Kara 				pagecache_isize_extended(inode, oldsize,
5514b9c1c267SJan Kara 							 inode->i_size);
5515b9c1c267SJan Kara 			} else if (ext4_should_journal_data(inode)) {
551682a25b02SJan Kara 				ext4_wait_for_tail_page_commit(inode);
5517b9c1c267SJan Kara 			}
5518430657b6SRoss Zwisler 		}
5519430657b6SRoss Zwisler 
552053e87268SJan Kara 		/*
552153e87268SJan Kara 		 * Truncate pagecache after we've waited for commit
552253e87268SJan Kara 		 * in data=journal mode to make pages freeable.
552353e87268SJan Kara 		 */
55247caef267SKirill A. Shutemov 		truncate_pagecache(inode, inode->i_size);
5525b9c1c267SJan Kara 		/*
5526b9c1c267SJan Kara 		 * Call ext4_truncate() even if i_size didn't change to
5527b9c1c267SJan Kara 		 * truncate possible preallocated blocks.
5528b9c1c267SJan Kara 		 */
5529b9c1c267SJan Kara 		if (attr->ia_size <= oldsize) {
55302c98eb5eSTheodore Ts'o 			rc = ext4_truncate(inode);
55312c98eb5eSTheodore Ts'o 			if (rc)
55322c98eb5eSTheodore Ts'o 				error = rc;
55332c98eb5eSTheodore Ts'o 		}
5534b9c1c267SJan Kara out_mmap_sem:
5535d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
55363da40c7bSJosef Bacik 	}
5537ac27a0ecSDave Kleikamp 
55382c98eb5eSTheodore Ts'o 	if (!error) {
5539a642c2c0SJeff Layton 		if (inc_ivers)
5540a642c2c0SJeff Layton 			inode_inc_iversion(inode);
554114f3db55SChristian Brauner 		setattr_copy(mnt_userns, inode, attr);
55421025774cSChristoph Hellwig 		mark_inode_dirty(inode);
55431025774cSChristoph Hellwig 	}
55441025774cSChristoph Hellwig 
55451025774cSChristoph Hellwig 	/*
55461025774cSChristoph Hellwig 	 * If the call to ext4_truncate failed to get a transaction handle at
55471025774cSChristoph Hellwig 	 * all, we need to clean up the in-core orphan list manually.
55481025774cSChristoph Hellwig 	 */
55493d287de3SDmitry Monakhov 	if (orphan && inode->i_nlink)
5550617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
5551ac27a0ecSDave Kleikamp 
55522c98eb5eSTheodore Ts'o 	if (!error && (ia_valid & ATTR_MODE))
555314f3db55SChristian Brauner 		rc = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5554ac27a0ecSDave Kleikamp 
5555ac27a0ecSDave Kleikamp err_out:
5556aa75f4d3SHarshad Shirwadkar 	if  (error)
5557617ba13bSMingming Cao 		ext4_std_error(inode->i_sb, error);
5558ac27a0ecSDave Kleikamp 	if (!error)
5559ac27a0ecSDave Kleikamp 		error = rc;
5560ac27a0ecSDave Kleikamp 	return error;
5561ac27a0ecSDave Kleikamp }
5562ac27a0ecSDave Kleikamp 
55638434ef1dSEric Biggers u32 ext4_dio_alignment(struct inode *inode)
55648434ef1dSEric Biggers {
55658434ef1dSEric Biggers 	if (fsverity_active(inode))
55668434ef1dSEric Biggers 		return 0;
55678434ef1dSEric Biggers 	if (ext4_should_journal_data(inode))
55688434ef1dSEric Biggers 		return 0;
55698434ef1dSEric Biggers 	if (ext4_has_inline_data(inode))
55708434ef1dSEric Biggers 		return 0;
55718434ef1dSEric Biggers 	if (IS_ENCRYPTED(inode)) {
55728434ef1dSEric Biggers 		if (!fscrypt_dio_supported(inode))
55738434ef1dSEric Biggers 			return 0;
55748434ef1dSEric Biggers 		return i_blocksize(inode);
55758434ef1dSEric Biggers 	}
55768434ef1dSEric Biggers 	return 1; /* use the iomap defaults */
55778434ef1dSEric Biggers }
55788434ef1dSEric Biggers 
5579549c7297SChristian Brauner int ext4_getattr(struct user_namespace *mnt_userns, const struct path *path,
5580549c7297SChristian Brauner 		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
55813e3398a0SMingming Cao {
558299652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
558399652ea5SDavid Howells 	struct ext4_inode *raw_inode;
558499652ea5SDavid Howells 	struct ext4_inode_info *ei = EXT4_I(inode);
558599652ea5SDavid Howells 	unsigned int flags;
55863e3398a0SMingming Cao 
5587d4c5e960STheodore Ts'o 	if ((request_mask & STATX_BTIME) &&
5588d4c5e960STheodore Ts'o 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
558999652ea5SDavid Howells 		stat->result_mask |= STATX_BTIME;
559099652ea5SDavid Howells 		stat->btime.tv_sec = ei->i_crtime.tv_sec;
559199652ea5SDavid Howells 		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
559299652ea5SDavid Howells 	}
559399652ea5SDavid Howells 
55948434ef1dSEric Biggers 	/*
55958434ef1dSEric Biggers 	 * Return the DIO alignment restrictions if requested.  We only return
55968434ef1dSEric Biggers 	 * this information when requested, since on encrypted files it might
55978434ef1dSEric Biggers 	 * take a fair bit of work to get if the file wasn't opened recently.
55988434ef1dSEric Biggers 	 */
55998434ef1dSEric Biggers 	if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
56008434ef1dSEric Biggers 		u32 dio_align = ext4_dio_alignment(inode);
56018434ef1dSEric Biggers 
56028434ef1dSEric Biggers 		stat->result_mask |= STATX_DIOALIGN;
56038434ef1dSEric Biggers 		if (dio_align == 1) {
56048434ef1dSEric Biggers 			struct block_device *bdev = inode->i_sb->s_bdev;
56058434ef1dSEric Biggers 
56068434ef1dSEric Biggers 			/* iomap defaults */
56078434ef1dSEric Biggers 			stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
56088434ef1dSEric Biggers 			stat->dio_offset_align = bdev_logical_block_size(bdev);
56098434ef1dSEric Biggers 		} else {
56108434ef1dSEric Biggers 			stat->dio_mem_align = dio_align;
56118434ef1dSEric Biggers 			stat->dio_offset_align = dio_align;
56128434ef1dSEric Biggers 		}
56138434ef1dSEric Biggers 	}
56148434ef1dSEric Biggers 
561599652ea5SDavid Howells 	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
561699652ea5SDavid Howells 	if (flags & EXT4_APPEND_FL)
561799652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_APPEND;
561899652ea5SDavid Howells 	if (flags & EXT4_COMPR_FL)
561999652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_COMPRESSED;
562099652ea5SDavid Howells 	if (flags & EXT4_ENCRYPT_FL)
562199652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_ENCRYPTED;
562299652ea5SDavid Howells 	if (flags & EXT4_IMMUTABLE_FL)
562399652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_IMMUTABLE;
562499652ea5SDavid Howells 	if (flags & EXT4_NODUMP_FL)
562599652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_NODUMP;
56261f607195SEric Biggers 	if (flags & EXT4_VERITY_FL)
56271f607195SEric Biggers 		stat->attributes |= STATX_ATTR_VERITY;
562899652ea5SDavid Howells 
56293209f68bSDavid Howells 	stat->attributes_mask |= (STATX_ATTR_APPEND |
56303209f68bSDavid Howells 				  STATX_ATTR_COMPRESSED |
56313209f68bSDavid Howells 				  STATX_ATTR_ENCRYPTED |
56323209f68bSDavid Howells 				  STATX_ATTR_IMMUTABLE |
56331f607195SEric Biggers 				  STATX_ATTR_NODUMP |
56341f607195SEric Biggers 				  STATX_ATTR_VERITY);
56353209f68bSDavid Howells 
563614f3db55SChristian Brauner 	generic_fillattr(mnt_userns, inode, stat);
563799652ea5SDavid Howells 	return 0;
563899652ea5SDavid Howells }
563999652ea5SDavid Howells 
5640549c7297SChristian Brauner int ext4_file_getattr(struct user_namespace *mnt_userns,
5641549c7297SChristian Brauner 		      const struct path *path, struct kstat *stat,
564299652ea5SDavid Howells 		      u32 request_mask, unsigned int query_flags)
564399652ea5SDavid Howells {
564499652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
564599652ea5SDavid Howells 	u64 delalloc_blocks;
564699652ea5SDavid Howells 
564714f3db55SChristian Brauner 	ext4_getattr(mnt_userns, path, stat, request_mask, query_flags);
56483e3398a0SMingming Cao 
56493e3398a0SMingming Cao 	/*
56509206c561SAndreas Dilger 	 * If there is inline data in the inode, the inode will normally not
56519206c561SAndreas Dilger 	 * have data blocks allocated (it may have an external xattr block).
56529206c561SAndreas Dilger 	 * Report at least one sector for such files, so tools like tar, rsync,
5653d67d64f4STheodore Ts'o 	 * others don't incorrectly think the file is completely sparse.
56549206c561SAndreas Dilger 	 */
56559206c561SAndreas Dilger 	if (unlikely(ext4_has_inline_data(inode)))
56569206c561SAndreas Dilger 		stat->blocks += (stat->size + 511) >> 9;
56579206c561SAndreas Dilger 
56589206c561SAndreas Dilger 	/*
56593e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
56603e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
56613e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
56623e3398a0SMingming Cao 	 * on-disk file blocks.
56633e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
56643e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
56653e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
56663e3398a0SMingming Cao 	 * blocks for this file.
56673e3398a0SMingming Cao 	 */
566896607551STao Ma 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
566996607551STao Ma 				   EXT4_I(inode)->i_reserved_data_blocks);
56708af8eeccSJan Kara 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
56713e3398a0SMingming Cao 	return 0;
56723e3398a0SMingming Cao }
5673ac27a0ecSDave Kleikamp 
5674fffb2739SJan Kara static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5675fffb2739SJan Kara 				   int pextents)
5676a02908f1SMingming Cao {
567712e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5678fffb2739SJan Kara 		return ext4_ind_trans_blocks(inode, lblocks);
5679fffb2739SJan Kara 	return ext4_ext_index_trans_blocks(inode, pextents);
5680a02908f1SMingming Cao }
5681ac51d837STheodore Ts'o 
5682a02908f1SMingming Cao /*
5683a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
5684a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
5685a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
5686a02908f1SMingming Cao  *
5687a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
56884907cb7bSAnatol Pomozov  * different block groups too. If they are contiguous, with flexbg,
5689a02908f1SMingming Cao  * they could still across block group boundary.
5690a02908f1SMingming Cao  *
5691a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
5692a02908f1SMingming Cao  */
5693dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5694fffb2739SJan Kara 				  int pextents)
5695a02908f1SMingming Cao {
56968df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
56978df9675fSTheodore Ts'o 	int gdpblocks;
5698a02908f1SMingming Cao 	int idxblocks;
5699a02908f1SMingming Cao 	int ret = 0;
5700a02908f1SMingming Cao 
5701a02908f1SMingming Cao 	/*
5702fffb2739SJan Kara 	 * How many index blocks need to touch to map @lblocks logical blocks
5703fffb2739SJan Kara 	 * to @pextents physical extents?
5704a02908f1SMingming Cao 	 */
5705fffb2739SJan Kara 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5706a02908f1SMingming Cao 
5707a02908f1SMingming Cao 	ret = idxblocks;
5708a02908f1SMingming Cao 
5709a02908f1SMingming Cao 	/*
5710a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
5711a02908f1SMingming Cao 	 * to account
5712a02908f1SMingming Cao 	 */
5713fffb2739SJan Kara 	groups = idxblocks + pextents;
5714a02908f1SMingming Cao 	gdpblocks = groups;
57158df9675fSTheodore Ts'o 	if (groups > ngroups)
57168df9675fSTheodore Ts'o 		groups = ngroups;
5717a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5718a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5719a02908f1SMingming Cao 
5720a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
5721a02908f1SMingming Cao 	ret += groups + gdpblocks;
5722a02908f1SMingming Cao 
5723a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
5724a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5725ac27a0ecSDave Kleikamp 
5726ac27a0ecSDave Kleikamp 	return ret;
5727ac27a0ecSDave Kleikamp }
5728ac27a0ecSDave Kleikamp 
5729ac27a0ecSDave Kleikamp /*
573025985edcSLucas De Marchi  * Calculate the total number of credits to reserve to fit
5731f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
5732f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
5733a02908f1SMingming Cao  *
5734525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
5735a02908f1SMingming Cao  *
5736525f4ed8SMingming Cao  * We need to consider the worse case, when
5737a02908f1SMingming Cao  * one new block per extent.
5738a02908f1SMingming Cao  */
5739a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
5740a02908f1SMingming Cao {
5741a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
5742a02908f1SMingming Cao 	int ret;
5743a02908f1SMingming Cao 
5744fffb2739SJan Kara 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5745a02908f1SMingming Cao 
5746a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
5747a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
5748a02908f1SMingming Cao 		ret += bpp;
5749a02908f1SMingming Cao 	return ret;
5750a02908f1SMingming Cao }
5751f3bd1f3fSMingming Cao 
5752f3bd1f3fSMingming Cao /*
5753f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
5754f3bd1f3fSMingming Cao  *
5755f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
575679e83036SEric Sandeen  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5757f3bd1f3fSMingming Cao  *
5758f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
5759f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
5760f3bd1f3fSMingming Cao  */
5761f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5762f3bd1f3fSMingming Cao {
5763f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5764f3bd1f3fSMingming Cao }
5765f3bd1f3fSMingming Cao 
5766a02908f1SMingming Cao /*
5767617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
5768ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
5769ac27a0ecSDave Kleikamp  */
5770617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
5771617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
5772ac27a0ecSDave Kleikamp {
5773ac27a0ecSDave Kleikamp 	int err = 0;
5774ac27a0ecSDave Kleikamp 
5775a6758309SVasily Averin 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5776a6758309SVasily Averin 		put_bh(iloc->bh);
57770db1ff22STheodore Ts'o 		return -EIO;
5778a6758309SVasily Averin 	}
5779a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_inode(handle, inode);
5780aa75f4d3SHarshad Shirwadkar 
5781ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
5782ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
5783ac27a0ecSDave Kleikamp 
5784dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5785830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
5786ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
5787ac27a0ecSDave Kleikamp 	return err;
5788ac27a0ecSDave Kleikamp }
5789ac27a0ecSDave Kleikamp 
5790ac27a0ecSDave Kleikamp /*
5791ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
5792ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
5793ac27a0ecSDave Kleikamp  */
5794ac27a0ecSDave Kleikamp 
5795ac27a0ecSDave Kleikamp int
5796617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5797617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
5798ac27a0ecSDave Kleikamp {
57990390131bSFrank Mayhar 	int err;
58000390131bSFrank Mayhar 
58010db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
58020db1ff22STheodore Ts'o 		return -EIO;
58030db1ff22STheodore Ts'o 
5804617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
5805ac27a0ecSDave Kleikamp 	if (!err) {
5806ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
5807188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb,
5808188c299eSJan Kara 						    iloc->bh, EXT4_JTR_NONE);
5809ac27a0ecSDave Kleikamp 		if (err) {
5810ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
5811ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
5812ac27a0ecSDave Kleikamp 		}
5813ac27a0ecSDave Kleikamp 	}
5814617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5815ac27a0ecSDave Kleikamp 	return err;
5816ac27a0ecSDave Kleikamp }
5817ac27a0ecSDave Kleikamp 
5818c03b45b8SMiao Xie static int __ext4_expand_extra_isize(struct inode *inode,
5819c03b45b8SMiao Xie 				     unsigned int new_extra_isize,
5820c03b45b8SMiao Xie 				     struct ext4_iloc *iloc,
5821c03b45b8SMiao Xie 				     handle_t *handle, int *no_expand)
5822c03b45b8SMiao Xie {
5823c03b45b8SMiao Xie 	struct ext4_inode *raw_inode;
5824c03b45b8SMiao Xie 	struct ext4_xattr_ibody_header *header;
58254ea99936STheodore Ts'o 	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
58264ea99936STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
5827c03b45b8SMiao Xie 	int error;
5828c03b45b8SMiao Xie 
58294ea99936STheodore Ts'o 	/* this was checked at iget time, but double check for good measure */
58304ea99936STheodore Ts'o 	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
58314ea99936STheodore Ts'o 	    (ei->i_extra_isize & 3)) {
58324ea99936STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
58334ea99936STheodore Ts'o 				 ei->i_extra_isize,
58344ea99936STheodore Ts'o 				 EXT4_INODE_SIZE(inode->i_sb));
58354ea99936STheodore Ts'o 		return -EFSCORRUPTED;
58364ea99936STheodore Ts'o 	}
58374ea99936STheodore Ts'o 	if ((new_extra_isize < ei->i_extra_isize) ||
58384ea99936STheodore Ts'o 	    (new_extra_isize < 4) ||
58394ea99936STheodore Ts'o 	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
58404ea99936STheodore Ts'o 		return -EINVAL;	/* Should never happen */
58414ea99936STheodore Ts'o 
5842c03b45b8SMiao Xie 	raw_inode = ext4_raw_inode(iloc);
5843c03b45b8SMiao Xie 
5844c03b45b8SMiao Xie 	header = IHDR(inode, raw_inode);
5845c03b45b8SMiao Xie 
5846c03b45b8SMiao Xie 	/* No extended attributes present */
5847c03b45b8SMiao Xie 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5848c03b45b8SMiao Xie 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5849c03b45b8SMiao Xie 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5850c03b45b8SMiao Xie 		       EXT4_I(inode)->i_extra_isize, 0,
5851c03b45b8SMiao Xie 		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
5852c03b45b8SMiao Xie 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
5853c03b45b8SMiao Xie 		return 0;
5854c03b45b8SMiao Xie 	}
5855c03b45b8SMiao Xie 
5856c03b45b8SMiao Xie 	/* try to expand with EAs present */
5857c03b45b8SMiao Xie 	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5858c03b45b8SMiao Xie 					   raw_inode, handle);
5859c03b45b8SMiao Xie 	if (error) {
5860c03b45b8SMiao Xie 		/*
5861c03b45b8SMiao Xie 		 * Inode size expansion failed; don't try again
5862c03b45b8SMiao Xie 		 */
5863c03b45b8SMiao Xie 		*no_expand = 1;
5864c03b45b8SMiao Xie 	}
5865c03b45b8SMiao Xie 
5866c03b45b8SMiao Xie 	return error;
5867c03b45b8SMiao Xie }
5868c03b45b8SMiao Xie 
5869ac27a0ecSDave Kleikamp /*
58706dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
58716dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
58726dd4ee7cSKalpak Shah  */
5873cf0a5e81SMiao Xie static int ext4_try_to_expand_extra_isize(struct inode *inode,
58741d03ec98SAneesh Kumar K.V 					  unsigned int new_extra_isize,
58751d03ec98SAneesh Kumar K.V 					  struct ext4_iloc iloc,
58761d03ec98SAneesh Kumar K.V 					  handle_t *handle)
58776dd4ee7cSKalpak Shah {
58783b10fdc6SMiao Xie 	int no_expand;
58793b10fdc6SMiao Xie 	int error;
58806dd4ee7cSKalpak Shah 
5881cf0a5e81SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5882cf0a5e81SMiao Xie 		return -EOVERFLOW;
5883cf0a5e81SMiao Xie 
5884cf0a5e81SMiao Xie 	/*
5885cf0a5e81SMiao Xie 	 * In nojournal mode, we can immediately attempt to expand
5886cf0a5e81SMiao Xie 	 * the inode.  When journaled, we first need to obtain extra
5887cf0a5e81SMiao Xie 	 * buffer credits since we may write into the EA block
5888cf0a5e81SMiao Xie 	 * with this same handle. If journal_extend fails, then it will
5889cf0a5e81SMiao Xie 	 * only result in a minor loss of functionality for that inode.
5890cf0a5e81SMiao Xie 	 * If this is felt to be critical, then e2fsck should be run to
5891cf0a5e81SMiao Xie 	 * force a large enough s_min_extra_isize.
5892cf0a5e81SMiao Xie 	 */
58936cb367c2SJan Kara 	if (ext4_journal_extend(handle,
589483448bdfSJan Kara 				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5895cf0a5e81SMiao Xie 		return -ENOSPC;
58966dd4ee7cSKalpak Shah 
58973b10fdc6SMiao Xie 	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5898cf0a5e81SMiao Xie 		return -EBUSY;
58993b10fdc6SMiao Xie 
5900c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5901c03b45b8SMiao Xie 					  handle, &no_expand);
59023b10fdc6SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5903c03b45b8SMiao Xie 
5904c03b45b8SMiao Xie 	return error;
59056dd4ee7cSKalpak Shah }
59066dd4ee7cSKalpak Shah 
5907c03b45b8SMiao Xie int ext4_expand_extra_isize(struct inode *inode,
5908c03b45b8SMiao Xie 			    unsigned int new_extra_isize,
5909c03b45b8SMiao Xie 			    struct ext4_iloc *iloc)
5910c03b45b8SMiao Xie {
5911c03b45b8SMiao Xie 	handle_t *handle;
5912c03b45b8SMiao Xie 	int no_expand;
5913c03b45b8SMiao Xie 	int error, rc;
5914c03b45b8SMiao Xie 
5915c03b45b8SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5916c03b45b8SMiao Xie 		brelse(iloc->bh);
5917c03b45b8SMiao Xie 		return -EOVERFLOW;
5918c03b45b8SMiao Xie 	}
5919c03b45b8SMiao Xie 
5920c03b45b8SMiao Xie 	handle = ext4_journal_start(inode, EXT4_HT_INODE,
5921c03b45b8SMiao Xie 				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5922c03b45b8SMiao Xie 	if (IS_ERR(handle)) {
5923c03b45b8SMiao Xie 		error = PTR_ERR(handle);
5924c03b45b8SMiao Xie 		brelse(iloc->bh);
5925c03b45b8SMiao Xie 		return error;
5926c03b45b8SMiao Xie 	}
5927c03b45b8SMiao Xie 
5928c03b45b8SMiao Xie 	ext4_write_lock_xattr(inode, &no_expand);
5929c03b45b8SMiao Xie 
5930ddccb6dbSzhangyi (F) 	BUFFER_TRACE(iloc->bh, "get_write_access");
5931188c299eSJan Kara 	error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
5932188c299eSJan Kara 					      EXT4_JTR_NONE);
59333b10fdc6SMiao Xie 	if (error) {
5934c03b45b8SMiao Xie 		brelse(iloc->bh);
59357f420d64SDan Carpenter 		goto out_unlock;
59363b10fdc6SMiao Xie 	}
5937cf0a5e81SMiao Xie 
5938c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5939c03b45b8SMiao Xie 					  handle, &no_expand);
5940c03b45b8SMiao Xie 
5941c03b45b8SMiao Xie 	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5942c03b45b8SMiao Xie 	if (!error)
5943c03b45b8SMiao Xie 		error = rc;
5944c03b45b8SMiao Xie 
59457f420d64SDan Carpenter out_unlock:
5946c03b45b8SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5947c03b45b8SMiao Xie 	ext4_journal_stop(handle);
59483b10fdc6SMiao Xie 	return error;
59496dd4ee7cSKalpak Shah }
59506dd4ee7cSKalpak Shah 
59516dd4ee7cSKalpak Shah /*
5952ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
5953ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
5954ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
5955ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
5956ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
5957ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
5958ac27a0ecSDave Kleikamp  *
5959ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
5960ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
5961ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5962ac27a0ecSDave Kleikamp  * we start and wait on commits.
5963ac27a0ecSDave Kleikamp  */
59644209ae12SHarshad Shirwadkar int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
59654209ae12SHarshad Shirwadkar 				const char *func, unsigned int line)
5966ac27a0ecSDave Kleikamp {
5967617ba13bSMingming Cao 	struct ext4_iloc iloc;
59686dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5969cf0a5e81SMiao Xie 	int err;
5970ac27a0ecSDave Kleikamp 
5971ac27a0ecSDave Kleikamp 	might_sleep();
59727ff9c073STheodore Ts'o 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5973617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
59745e1021f2SEryu Guan 	if (err)
59754209ae12SHarshad Shirwadkar 		goto out;
5976cf0a5e81SMiao Xie 
5977cf0a5e81SMiao Xie 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5978cf0a5e81SMiao Xie 		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
59796dd4ee7cSKalpak Shah 					       iloc, handle);
5980cf0a5e81SMiao Xie 
59814209ae12SHarshad Shirwadkar 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
59824209ae12SHarshad Shirwadkar out:
59834209ae12SHarshad Shirwadkar 	if (unlikely(err))
59844209ae12SHarshad Shirwadkar 		ext4_error_inode_err(inode, func, line, 0, err,
59854209ae12SHarshad Shirwadkar 					"mark_inode_dirty error");
59864209ae12SHarshad Shirwadkar 	return err;
5987ac27a0ecSDave Kleikamp }
5988ac27a0ecSDave Kleikamp 
5989ac27a0ecSDave Kleikamp /*
5990617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
5991ac27a0ecSDave Kleikamp  *
5992ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
5993ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
5994ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
5995ac27a0ecSDave Kleikamp  *
59965dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
5997ac27a0ecSDave Kleikamp  * are allocated to the file.
5998ac27a0ecSDave Kleikamp  *
5999ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
6000ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
6001ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
6002ac27a0ecSDave Kleikamp  */
6003aa385729SChristoph Hellwig void ext4_dirty_inode(struct inode *inode, int flags)
6004ac27a0ecSDave Kleikamp {
6005ac27a0ecSDave Kleikamp 	handle_t *handle;
6006ac27a0ecSDave Kleikamp 
60079924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
6008ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
6009ac27a0ecSDave Kleikamp 		return;
6010e2728c56SEric Biggers 	ext4_mark_inode_dirty(handle, inode);
6011e2728c56SEric Biggers 	ext4_journal_stop(handle);
6012ac27a0ecSDave Kleikamp }
6013ac27a0ecSDave Kleikamp 
6014617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
6015ac27a0ecSDave Kleikamp {
6016ac27a0ecSDave Kleikamp 	journal_t *journal;
6017ac27a0ecSDave Kleikamp 	handle_t *handle;
6018ac27a0ecSDave Kleikamp 	int err;
6019c8585c6fSDaeho Jeong 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6020ac27a0ecSDave Kleikamp 
6021ac27a0ecSDave Kleikamp 	/*
6022ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
6023ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
6024ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
6025ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
6026ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
6027ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
6028ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
6029ac27a0ecSDave Kleikamp 	 */
6030ac27a0ecSDave Kleikamp 
6031617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
60320390131bSFrank Mayhar 	if (!journal)
60330390131bSFrank Mayhar 		return 0;
6034d699594dSDave Hansen 	if (is_journal_aborted(journal))
6035ac27a0ecSDave Kleikamp 		return -EROFS;
6036ac27a0ecSDave Kleikamp 
603717335dccSDmitry Monakhov 	/* Wait for all existing dio workers */
603817335dccSDmitry Monakhov 	inode_dio_wait(inode);
603917335dccSDmitry Monakhov 
60404c546592SDaeho Jeong 	/*
60414c546592SDaeho Jeong 	 * Before flushing the journal and switching inode's aops, we have
60424c546592SDaeho Jeong 	 * to flush all dirty data the inode has. There can be outstanding
60434c546592SDaeho Jeong 	 * delayed allocations, there can be unwritten extents created by
60444c546592SDaeho Jeong 	 * fallocate or buffered writes in dioread_nolock mode covered by
60454c546592SDaeho Jeong 	 * dirty data which can be converted only after flushing the dirty
60464c546592SDaeho Jeong 	 * data (and journalled aops don't know how to handle these cases).
60474c546592SDaeho Jeong 	 */
60484c546592SDaeho Jeong 	if (val) {
6049d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
60504c546592SDaeho Jeong 		err = filemap_write_and_wait(inode->i_mapping);
60514c546592SDaeho Jeong 		if (err < 0) {
6052d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
60534c546592SDaeho Jeong 			return err;
60544c546592SDaeho Jeong 		}
60554c546592SDaeho Jeong 	}
60564c546592SDaeho Jeong 
6057bbd55937SEric Biggers 	percpu_down_write(&sbi->s_writepages_rwsem);
6058dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
6059ac27a0ecSDave Kleikamp 
6060ac27a0ecSDave Kleikamp 	/*
6061ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
6062ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
6063ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
6064ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
6065ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
6066ac27a0ecSDave Kleikamp 	 */
6067ac27a0ecSDave Kleikamp 
6068ac27a0ecSDave Kleikamp 	if (val)
606912e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60705872ddaaSYongqiang Yang 	else {
607101d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
60724f879ca6SJan Kara 		if (err < 0) {
60734f879ca6SJan Kara 			jbd2_journal_unlock_updates(journal);
6074bbd55937SEric Biggers 			percpu_up_write(&sbi->s_writepages_rwsem);
60754f879ca6SJan Kara 			return err;
60764f879ca6SJan Kara 		}
607712e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60785872ddaaSYongqiang Yang 	}
6079617ba13bSMingming Cao 	ext4_set_aops(inode);
6080ac27a0ecSDave Kleikamp 
6081dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
6082bbd55937SEric Biggers 	percpu_up_write(&sbi->s_writepages_rwsem);
6083c8585c6fSDaeho Jeong 
60844c546592SDaeho Jeong 	if (val)
6085d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
6086ac27a0ecSDave Kleikamp 
6087ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
6088ac27a0ecSDave Kleikamp 
60899924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6090ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
6091ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
6092ac27a0ecSDave Kleikamp 
6093aa75f4d3SHarshad Shirwadkar 	ext4_fc_mark_ineligible(inode->i_sb,
6094e85c81baSXin Yin 		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6095617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
60960390131bSFrank Mayhar 	ext4_handle_sync(handle);
6097617ba13bSMingming Cao 	ext4_journal_stop(handle);
6098617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
6099ac27a0ecSDave Kleikamp 
6100ac27a0ecSDave Kleikamp 	return err;
6101ac27a0ecSDave Kleikamp }
61022e9ee850SAneesh Kumar K.V 
6103188c299eSJan Kara static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6104188c299eSJan Kara 			    struct buffer_head *bh)
61052e9ee850SAneesh Kumar K.V {
61062e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
61072e9ee850SAneesh Kumar K.V }
61082e9ee850SAneesh Kumar K.V 
6109401b25aaSSouptick Joarder vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
61102e9ee850SAneesh Kumar K.V {
611111bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
6112c2ec175cSNick Piggin 	struct page *page = vmf->page;
61132e9ee850SAneesh Kumar K.V 	loff_t size;
61142e9ee850SAneesh Kumar K.V 	unsigned long len;
6115401b25aaSSouptick Joarder 	int err;
6116401b25aaSSouptick Joarder 	vm_fault_t ret;
61172e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
6118496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
61192e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
61209ea7df53SJan Kara 	handle_t *handle;
61219ea7df53SJan Kara 	get_block_t *get_block;
61229ea7df53SJan Kara 	int retries = 0;
61232e9ee850SAneesh Kumar K.V 
612402b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
612502b016caSTheodore Ts'o 		return VM_FAULT_SIGBUS;
612602b016caSTheodore Ts'o 
61278e8ad8a5SJan Kara 	sb_start_pagefault(inode->i_sb);
6128041bbb6dSTheodore Ts'o 	file_update_time(vma->vm_file);
6129ea3d7209SJan Kara 
6130d4f5258eSJan Kara 	filemap_invalidate_lock_shared(mapping);
61317b4cc978SEric Biggers 
6132401b25aaSSouptick Joarder 	err = ext4_convert_inline_data(inode);
6133401b25aaSSouptick Joarder 	if (err)
61347b4cc978SEric Biggers 		goto out_ret;
61357b4cc978SEric Biggers 
613664a9f144SMauricio Faria de Oliveira 	/*
613764a9f144SMauricio Faria de Oliveira 	 * On data journalling we skip straight to the transaction handle:
613864a9f144SMauricio Faria de Oliveira 	 * there's no delalloc; page truncated will be checked later; the
613964a9f144SMauricio Faria de Oliveira 	 * early return w/ all buffers mapped (calculates size/len) can't
614064a9f144SMauricio Faria de Oliveira 	 * be used; and there's no dioread_nolock, so only ext4_get_block.
614164a9f144SMauricio Faria de Oliveira 	 */
614264a9f144SMauricio Faria de Oliveira 	if (ext4_should_journal_data(inode))
614364a9f144SMauricio Faria de Oliveira 		goto retry_alloc;
614464a9f144SMauricio Faria de Oliveira 
61459ea7df53SJan Kara 	/* Delalloc case is easy... */
61469ea7df53SJan Kara 	if (test_opt(inode->i_sb, DELALLOC) &&
61479ea7df53SJan Kara 	    !ext4_nonda_switch(inode->i_sb)) {
61489ea7df53SJan Kara 		do {
6149401b25aaSSouptick Joarder 			err = block_page_mkwrite(vma, vmf,
61509ea7df53SJan Kara 						   ext4_da_get_block_prep);
6151401b25aaSSouptick Joarder 		} while (err == -ENOSPC &&
61529ea7df53SJan Kara 		       ext4_should_retry_alloc(inode->i_sb, &retries));
61539ea7df53SJan Kara 		goto out_ret;
61542e9ee850SAneesh Kumar K.V 	}
61550e499890SDarrick J. Wong 
61560e499890SDarrick J. Wong 	lock_page(page);
61579ea7df53SJan Kara 	size = i_size_read(inode);
61589ea7df53SJan Kara 	/* Page got truncated from under us? */
61599ea7df53SJan Kara 	if (page->mapping != mapping || page_offset(page) > size) {
61609ea7df53SJan Kara 		unlock_page(page);
61619ea7df53SJan Kara 		ret = VM_FAULT_NOPAGE;
61629ea7df53SJan Kara 		goto out;
61630e499890SDarrick J. Wong 	}
61642e9ee850SAneesh Kumar K.V 
616509cbfeafSKirill A. Shutemov 	if (page->index == size >> PAGE_SHIFT)
616609cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
61672e9ee850SAneesh Kumar K.V 	else
616809cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
6169a827eaffSAneesh Kumar K.V 	/*
61709ea7df53SJan Kara 	 * Return if we have all the buffers mapped. This avoids the need to do
61719ea7df53SJan Kara 	 * journal_start/journal_stop which can block and take a long time
617264a9f144SMauricio Faria de Oliveira 	 *
617364a9f144SMauricio Faria de Oliveira 	 * This cannot be done for data journalling, as we have to add the
617464a9f144SMauricio Faria de Oliveira 	 * inode to the transaction's list to writeprotect pages on commit.
6175a827eaffSAneesh Kumar K.V 	 */
61762e9ee850SAneesh Kumar K.V 	if (page_has_buffers(page)) {
6177188c299eSJan Kara 		if (!ext4_walk_page_buffers(NULL, inode, page_buffers(page),
6178f19d5870STao Ma 					    0, len, NULL,
6179a827eaffSAneesh Kumar K.V 					    ext4_bh_unmapped)) {
61809ea7df53SJan Kara 			/* Wait so that we don't change page under IO */
61811d1d1a76SDarrick J. Wong 			wait_for_stable_page(page);
61829ea7df53SJan Kara 			ret = VM_FAULT_LOCKED;
61839ea7df53SJan Kara 			goto out;
61842e9ee850SAneesh Kumar K.V 		}
6185a827eaffSAneesh Kumar K.V 	}
6186a827eaffSAneesh Kumar K.V 	unlock_page(page);
61879ea7df53SJan Kara 	/* OK, we need to fill the hole... */
61889ea7df53SJan Kara 	if (ext4_should_dioread_nolock(inode))
6189705965bdSJan Kara 		get_block = ext4_get_block_unwritten;
61909ea7df53SJan Kara 	else
61919ea7df53SJan Kara 		get_block = ext4_get_block;
61929ea7df53SJan Kara retry_alloc:
61939924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
61949924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
61959ea7df53SJan Kara 	if (IS_ERR(handle)) {
6196c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
61979ea7df53SJan Kara 		goto out;
61989ea7df53SJan Kara 	}
619964a9f144SMauricio Faria de Oliveira 	/*
620064a9f144SMauricio Faria de Oliveira 	 * Data journalling can't use block_page_mkwrite() because it
620164a9f144SMauricio Faria de Oliveira 	 * will set_buffer_dirty() before do_journal_get_write_access()
620264a9f144SMauricio Faria de Oliveira 	 * thus might hit warning messages for dirty metadata buffers.
620364a9f144SMauricio Faria de Oliveira 	 */
620464a9f144SMauricio Faria de Oliveira 	if (!ext4_should_journal_data(inode)) {
6205401b25aaSSouptick Joarder 		err = block_page_mkwrite(vma, vmf, get_block);
620664a9f144SMauricio Faria de Oliveira 	} else {
620764a9f144SMauricio Faria de Oliveira 		lock_page(page);
620864a9f144SMauricio Faria de Oliveira 		size = i_size_read(inode);
620964a9f144SMauricio Faria de Oliveira 		/* Page got truncated from under us? */
621064a9f144SMauricio Faria de Oliveira 		if (page->mapping != mapping || page_offset(page) > size) {
621164a9f144SMauricio Faria de Oliveira 			ret = VM_FAULT_NOPAGE;
6212afb585a9SMauricio Faria de Oliveira 			goto out_error;
621364a9f144SMauricio Faria de Oliveira 		}
621464a9f144SMauricio Faria de Oliveira 
621564a9f144SMauricio Faria de Oliveira 		if (page->index == size >> PAGE_SHIFT)
621664a9f144SMauricio Faria de Oliveira 			len = size & ~PAGE_MASK;
621764a9f144SMauricio Faria de Oliveira 		else
621864a9f144SMauricio Faria de Oliveira 			len = PAGE_SIZE;
621964a9f144SMauricio Faria de Oliveira 
622064a9f144SMauricio Faria de Oliveira 		err = __block_write_begin(page, 0, len, ext4_get_block);
622164a9f144SMauricio Faria de Oliveira 		if (!err) {
62229ea7df53SJan Kara 			ret = VM_FAULT_SIGBUS;
6223188c299eSJan Kara 			if (ext4_walk_page_buffers(handle, inode,
6224188c299eSJan Kara 					page_buffers(page), 0, len, NULL,
6225188c299eSJan Kara 					do_journal_get_write_access))
6226afb585a9SMauricio Faria de Oliveira 				goto out_error;
6227188c299eSJan Kara 			if (ext4_walk_page_buffers(handle, inode,
6228188c299eSJan Kara 					page_buffers(page), 0, len, NULL,
6229188c299eSJan Kara 					write_end_fn))
6230afb585a9SMauricio Faria de Oliveira 				goto out_error;
6231b5b18160SJan Kara 			if (ext4_jbd2_inode_add_write(handle, inode,
6232b5b18160SJan Kara 						      page_offset(page), len))
6233afb585a9SMauricio Faria de Oliveira 				goto out_error;
62349ea7df53SJan Kara 			ext4_set_inode_state(inode, EXT4_STATE_JDATA);
623564a9f144SMauricio Faria de Oliveira 		} else {
623664a9f144SMauricio Faria de Oliveira 			unlock_page(page);
623764a9f144SMauricio Faria de Oliveira 		}
62389ea7df53SJan Kara 	}
62399ea7df53SJan Kara 	ext4_journal_stop(handle);
6240401b25aaSSouptick Joarder 	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
62419ea7df53SJan Kara 		goto retry_alloc;
62429ea7df53SJan Kara out_ret:
6243401b25aaSSouptick Joarder 	ret = block_page_mkwrite_return(err);
62449ea7df53SJan Kara out:
6245d4f5258eSJan Kara 	filemap_invalidate_unlock_shared(mapping);
62468e8ad8a5SJan Kara 	sb_end_pagefault(inode->i_sb);
62472e9ee850SAneesh Kumar K.V 	return ret;
6248afb585a9SMauricio Faria de Oliveira out_error:
6249afb585a9SMauricio Faria de Oliveira 	unlock_page(page);
6250afb585a9SMauricio Faria de Oliveira 	ext4_journal_stop(handle);
6251afb585a9SMauricio Faria de Oliveira 	goto out;
62522e9ee850SAneesh Kumar K.V }
6253