xref: /openbmc/linux/fs/ext4/inode.c (revision 3f6bbe6e07e5239294ecc3d2efa70d1f98aed52e)
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 
139dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
140dec214d0STahsin Erdogan 				  int pextents);
14164769240SAlex Tomas 
142ac27a0ecSDave Kleikamp /*
143ac27a0ecSDave Kleikamp  * Test whether an inode is a fast symlink.
144407cd7fbSTahsin Erdogan  * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
145ac27a0ecSDave Kleikamp  */
146f348c252STheodore Ts'o int ext4_inode_is_fast_symlink(struct inode *inode)
147ac27a0ecSDave Kleikamp {
148fc82228aSAndi Kleen 	if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
149fc82228aSAndi Kleen 		int ea_blocks = EXT4_I(inode)->i_file_acl ?
150fc82228aSAndi Kleen 				EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
151fc82228aSAndi Kleen 
152fc82228aSAndi Kleen 		if (ext4_has_inline_data(inode))
153fc82228aSAndi Kleen 			return 0;
154fc82228aSAndi Kleen 
155fc82228aSAndi Kleen 		return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
156fc82228aSAndi Kleen 	}
157407cd7fbSTahsin Erdogan 	return S_ISLNK(inode->i_mode) && inode->i_size &&
158407cd7fbSTahsin Erdogan 	       (inode->i_size < EXT4_N_BLOCKS * 4);
159ac27a0ecSDave Kleikamp }
160ac27a0ecSDave Kleikamp 
161ac27a0ecSDave Kleikamp /*
162ac27a0ecSDave Kleikamp  * Called at the last iput() if i_nlink is zero.
163ac27a0ecSDave Kleikamp  */
1640930fcc1SAl Viro void ext4_evict_inode(struct inode *inode)
165ac27a0ecSDave Kleikamp {
166ac27a0ecSDave Kleikamp 	handle_t *handle;
167bc965ab3STheodore Ts'o 	int err;
16865db869cSJan Kara 	/*
16965db869cSJan Kara 	 * Credits for final inode cleanup and freeing:
17065db869cSJan Kara 	 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
17165db869cSJan Kara 	 * (xattr block freeing), bitmap, group descriptor (inode freeing)
17265db869cSJan Kara 	 */
17365db869cSJan Kara 	int extra_credits = 6;
1740421a189STahsin Erdogan 	struct ext4_xattr_inode_array *ea_inode_array = NULL;
17546e294efSJan Kara 	bool freeze_protected = false;
176ac27a0ecSDave Kleikamp 
1777ff9c073STheodore Ts'o 	trace_ext4_evict_inode(inode);
1782581fdc8SJiaying Zhang 
1796bc0d63dSJan Kara 	if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
1806bc0d63dSJan Kara 		ext4_evict_ea_inode(inode);
1810930fcc1SAl Viro 	if (inode->i_nlink) {
18291b0abe3SJohannes Weiner 		truncate_inode_pages_final(&inode->i_data);
1835dc23bddSJan Kara 
1840930fcc1SAl Viro 		goto no_delete;
1850930fcc1SAl Viro 	}
1860930fcc1SAl Viro 
187e2bfb088STheodore Ts'o 	if (is_bad_inode(inode))
188e2bfb088STheodore Ts'o 		goto no_delete;
189871a2931SChristoph Hellwig 	dquot_initialize(inode);
190907f4554SChristoph Hellwig 
191678aaf48SJan Kara 	if (ext4_should_order_data(inode))
192678aaf48SJan Kara 		ext4_begin_ordered_truncate(inode, 0);
19391b0abe3SJohannes Weiner 	truncate_inode_pages_final(&inode->i_data);
194ac27a0ecSDave Kleikamp 
1958e8ad8a5SJan Kara 	/*
196ceff86fdSJan Kara 	 * For inodes with journalled data, transaction commit could have
197bc12ac98SZhang Yi 	 * dirtied the inode. And for inodes with dioread_nolock, unwritten
198bc12ac98SZhang Yi 	 * extents converting worker could merge extents and also have dirtied
199bc12ac98SZhang Yi 	 * the inode. Flush worker is ignoring it because of I_FREEING flag but
200bc12ac98SZhang Yi 	 * we still need to remove the inode from the writeback lists.
201ceff86fdSJan Kara 	 */
202bc12ac98SZhang Yi 	if (!list_empty_careful(&inode->i_io_list))
203ceff86fdSJan Kara 		inode_io_list_del(inode);
204ceff86fdSJan Kara 
205ceff86fdSJan Kara 	/*
2068e8ad8a5SJan Kara 	 * Protect us against freezing - iput() caller didn't have to have any
20746e294efSJan Kara 	 * protection against it. When we are in a running transaction though,
20846e294efSJan Kara 	 * we are already protected against freezing and we cannot grab further
20946e294efSJan Kara 	 * protection due to lock ordering constraints.
2108e8ad8a5SJan Kara 	 */
21146e294efSJan Kara 	if (!ext4_journal_current_handle()) {
2128e8ad8a5SJan Kara 		sb_start_intwrite(inode->i_sb);
21346e294efSJan Kara 		freeze_protected = true;
21446e294efSJan Kara 	}
215e50e5129SAndreas Dilger 
21630a7eb97STahsin Erdogan 	if (!IS_NOQUOTA(inode))
21730a7eb97STahsin Erdogan 		extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
21830a7eb97STahsin Erdogan 
21965db869cSJan Kara 	/*
22065db869cSJan Kara 	 * Block bitmap, group descriptor, and inode are accounted in both
22165db869cSJan Kara 	 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
22265db869cSJan Kara 	 */
22330a7eb97STahsin Erdogan 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
22465db869cSJan Kara 			 ext4_blocks_for_truncate(inode) + extra_credits - 3);
225ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
226bc965ab3STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
227ac27a0ecSDave Kleikamp 		/*
228ac27a0ecSDave Kleikamp 		 * If we're going to skip the normal cleanup, we still need to
229ac27a0ecSDave Kleikamp 		 * make sure that the in-core orphan linked list is properly
230ac27a0ecSDave Kleikamp 		 * cleaned up.
231ac27a0ecSDave Kleikamp 		 */
232617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
23346e294efSJan Kara 		if (freeze_protected)
2348e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
235ac27a0ecSDave Kleikamp 		goto no_delete;
236ac27a0ecSDave Kleikamp 	}
23730a7eb97STahsin Erdogan 
238ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
2390390131bSFrank Mayhar 		ext4_handle_sync(handle);
240407cd7fbSTahsin Erdogan 
241407cd7fbSTahsin Erdogan 	/*
242407cd7fbSTahsin Erdogan 	 * Set inode->i_size to 0 before calling ext4_truncate(). We need
243407cd7fbSTahsin Erdogan 	 * special handling of symlinks here because i_size is used to
244407cd7fbSTahsin Erdogan 	 * determine whether ext4_inode_info->i_data contains symlink data or
245407cd7fbSTahsin Erdogan 	 * block mappings. Setting i_size to 0 will remove its fast symlink
246407cd7fbSTahsin Erdogan 	 * status. Erase i_data so that it becomes a valid empty block map.
247407cd7fbSTahsin Erdogan 	 */
248407cd7fbSTahsin Erdogan 	if (ext4_inode_is_fast_symlink(inode))
249407cd7fbSTahsin Erdogan 		memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
250ac27a0ecSDave Kleikamp 	inode->i_size = 0;
251bc965ab3STheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
252bc965ab3STheodore Ts'o 	if (err) {
25312062dddSEric Sandeen 		ext4_warning(inode->i_sb,
254bc965ab3STheodore Ts'o 			     "couldn't mark inode dirty (err %d)", err);
255bc965ab3STheodore Ts'o 		goto stop_handle;
256bc965ab3STheodore Ts'o 	}
2572c98eb5eSTheodore Ts'o 	if (inode->i_blocks) {
2582c98eb5eSTheodore Ts'o 		err = ext4_truncate(inode);
2592c98eb5eSTheodore Ts'o 		if (err) {
26054d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err,
2612c98eb5eSTheodore Ts'o 				       "couldn't truncate inode %lu (err %d)",
2622c98eb5eSTheodore Ts'o 				       inode->i_ino, err);
2632c98eb5eSTheodore Ts'o 			goto stop_handle;
2642c98eb5eSTheodore Ts'o 		}
2652c98eb5eSTheodore Ts'o 	}
266bc965ab3STheodore Ts'o 
26730a7eb97STahsin Erdogan 	/* Remove xattr references. */
26830a7eb97STahsin Erdogan 	err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
26930a7eb97STahsin Erdogan 				      extra_credits);
27030a7eb97STahsin Erdogan 	if (err) {
27130a7eb97STahsin Erdogan 		ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
272bc965ab3STheodore Ts'o stop_handle:
273bc965ab3STheodore Ts'o 		ext4_journal_stop(handle);
27445388219STheodore Ts'o 		ext4_orphan_del(NULL, inode);
27546e294efSJan Kara 		if (freeze_protected)
2768e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
27730a7eb97STahsin Erdogan 		ext4_xattr_inode_array_free(ea_inode_array);
278bc965ab3STheodore Ts'o 		goto no_delete;
279bc965ab3STheodore Ts'o 	}
280bc965ab3STheodore Ts'o 
281ac27a0ecSDave Kleikamp 	/*
282617ba13bSMingming Cao 	 * Kill off the orphan record which ext4_truncate created.
283ac27a0ecSDave Kleikamp 	 * AKPM: I think this can be inside the above `if'.
284617ba13bSMingming Cao 	 * Note that ext4_orphan_del() has to be able to cope with the
285ac27a0ecSDave Kleikamp 	 * deletion of a non-existent orphan - this is because we don't
286617ba13bSMingming Cao 	 * know if ext4_truncate() actually created an orphan record.
287ac27a0ecSDave Kleikamp 	 * (Well, we could do this if we need to, but heck - it works)
288ac27a0ecSDave Kleikamp 	 */
289617ba13bSMingming Cao 	ext4_orphan_del(handle, inode);
2905ffff834SArnd Bergmann 	EXT4_I(inode)->i_dtime	= (__u32)ktime_get_real_seconds();
291ac27a0ecSDave Kleikamp 
292ac27a0ecSDave Kleikamp 	/*
293ac27a0ecSDave Kleikamp 	 * One subtle ordering requirement: if anything has gone wrong
294ac27a0ecSDave Kleikamp 	 * (transaction abort, IO errors, whatever), then we can still
295ac27a0ecSDave Kleikamp 	 * do these next steps (the fs will already have been marked as
296ac27a0ecSDave Kleikamp 	 * having errors), but we can't free the inode if the mark_dirty
297ac27a0ecSDave Kleikamp 	 * fails.
298ac27a0ecSDave Kleikamp 	 */
299617ba13bSMingming Cao 	if (ext4_mark_inode_dirty(handle, inode))
300ac27a0ecSDave Kleikamp 		/* If that failed, just do the required in-core inode clear. */
3010930fcc1SAl Viro 		ext4_clear_inode(inode);
302ac27a0ecSDave Kleikamp 	else
303617ba13bSMingming Cao 		ext4_free_inode(handle, inode);
304617ba13bSMingming Cao 	ext4_journal_stop(handle);
30546e294efSJan Kara 	if (freeze_protected)
3068e8ad8a5SJan Kara 		sb_end_intwrite(inode->i_sb);
3070421a189STahsin Erdogan 	ext4_xattr_inode_array_free(ea_inode_array);
308ac27a0ecSDave Kleikamp 	return;
309ac27a0ecSDave Kleikamp no_delete:
310318cdc82SZhang Yi 	/*
311318cdc82SZhang Yi 	 * Check out some where else accidentally dirty the evicting inode,
312318cdc82SZhang Yi 	 * which may probably cause inode use-after-free issues later.
313318cdc82SZhang Yi 	 */
314318cdc82SZhang Yi 	WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));
315318cdc82SZhang Yi 
316b21ebf14SHarshad Shirwadkar 	if (!list_empty(&EXT4_I(inode)->i_fc_list))
317e85c81baSXin Yin 		ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
3180930fcc1SAl Viro 	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
319ac27a0ecSDave Kleikamp }
320ac27a0ecSDave Kleikamp 
321a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
322a9e7f447SDmitry Monakhov qsize_t *ext4_get_reserved_space(struct inode *inode)
32360e58e0fSMingming Cao {
324a9e7f447SDmitry Monakhov 	return &EXT4_I(inode)->i_reserved_quota;
32560e58e0fSMingming Cao }
326a9e7f447SDmitry Monakhov #endif
3279d0be502STheodore Ts'o 
32812219aeaSAneesh Kumar K.V /*
3290637c6f4STheodore Ts'o  * Called with i_data_sem down, which is important since we can call
3300637c6f4STheodore Ts'o  * ext4_discard_preallocations() from here.
3310637c6f4STheodore Ts'o  */
3325f634d06SAneesh Kumar K.V void ext4_da_update_reserve_space(struct inode *inode,
3335f634d06SAneesh Kumar K.V 					int used, int quota_claim)
33412219aeaSAneesh Kumar K.V {
33512219aeaSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3360637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
33712219aeaSAneesh Kumar K.V 
3380637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
339d8990240SAditya Kali 	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
3400637c6f4STheodore Ts'o 	if (unlikely(used > ei->i_reserved_data_blocks)) {
3418de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
3421084f252STheodore Ts'o 			 "with only %d reserved data blocks",
3430637c6f4STheodore Ts'o 			 __func__, inode->i_ino, used,
3440637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
3450637c6f4STheodore Ts'o 		WARN_ON(1);
3460637c6f4STheodore Ts'o 		used = ei->i_reserved_data_blocks;
3476bc6e63fSAneesh Kumar K.V 	}
34812219aeaSAneesh Kumar K.V 
3490637c6f4STheodore Ts'o 	/* Update per-inode reservations */
3500637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= used;
35171d4f7d0STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
3520637c6f4STheodore Ts'o 
353f9505c72Schenyichong 	spin_unlock(&ei->i_block_reservation_lock);
35460e58e0fSMingming Cao 
35572b8ab9dSEric Sandeen 	/* Update quota subsystem for data blocks */
35672b8ab9dSEric Sandeen 	if (quota_claim)
3577b415bf6SAditya Kali 		dquot_claim_block(inode, EXT4_C2B(sbi, used));
35872b8ab9dSEric Sandeen 	else {
3595f634d06SAneesh Kumar K.V 		/*
3605f634d06SAneesh Kumar K.V 		 * We did fallocate with an offset that is already delayed
3615f634d06SAneesh Kumar K.V 		 * allocated. So on delayed allocated writeback we should
36272b8ab9dSEric Sandeen 		 * not re-claim the quota for fallocated blocks.
3635f634d06SAneesh Kumar K.V 		 */
3647b415bf6SAditya Kali 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
3655f634d06SAneesh Kumar K.V 	}
366d6014301SAneesh Kumar K.V 
367d6014301SAneesh Kumar K.V 	/*
368d6014301SAneesh Kumar K.V 	 * If we have done all the pending block allocations and if
369d6014301SAneesh Kumar K.V 	 * there aren't any writers on the inode, we can discard the
370d6014301SAneesh Kumar K.V 	 * inode's preallocations.
371d6014301SAneesh Kumar K.V 	 */
3720637c6f4STheodore Ts'o 	if ((ei->i_reserved_data_blocks == 0) &&
37382dd124cSNikolay Borisov 	    !inode_is_open_for_write(inode))
37427bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
37512219aeaSAneesh Kumar K.V }
37612219aeaSAneesh Kumar K.V 
377e29136f8STheodore Ts'o static int __check_block_validity(struct inode *inode, const char *func,
378c398eda0STheodore Ts'o 				unsigned int line,
37924676da4STheodore Ts'o 				struct ext4_map_blocks *map)
3806fd058f7STheodore Ts'o {
381345c0dbfSTheodore Ts'o 	if (ext4_has_feature_journal(inode->i_sb) &&
382345c0dbfSTheodore Ts'o 	    (inode->i_ino ==
383345c0dbfSTheodore Ts'o 	     le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
384345c0dbfSTheodore Ts'o 		return 0;
385ce9f24ccSJan Kara 	if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
386c398eda0STheodore Ts'o 		ext4_error_inode(inode, func, line, map->m_pblk,
387bdbd6ce0STheodore Ts'o 				 "lblock %lu mapped to illegal pblock %llu "
38824676da4STheodore Ts'o 				 "(length %d)", (unsigned long) map->m_lblk,
389bdbd6ce0STheodore Ts'o 				 map->m_pblk, map->m_len);
3906a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
3916fd058f7STheodore Ts'o 	}
3926fd058f7STheodore Ts'o 	return 0;
3936fd058f7STheodore Ts'o }
3946fd058f7STheodore Ts'o 
39553085facSJan Kara int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
39653085facSJan Kara 		       ext4_lblk_t len)
39753085facSJan Kara {
39853085facSJan Kara 	int ret;
39953085facSJan Kara 
40033b4cc25SEric Biggers 	if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
401a7550b30SJaegeuk Kim 		return fscrypt_zeroout_range(inode, lblk, pblk, len);
40253085facSJan Kara 
40353085facSJan Kara 	ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
40453085facSJan Kara 	if (ret > 0)
40553085facSJan Kara 		ret = 0;
40653085facSJan Kara 
40753085facSJan Kara 	return ret;
40853085facSJan Kara }
40953085facSJan Kara 
410e29136f8STheodore Ts'o #define check_block_validity(inode, map)	\
411c398eda0STheodore Ts'o 	__check_block_validity((inode), __func__, __LINE__, (map))
412e29136f8STheodore Ts'o 
413921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
414921f266bSDmitry Monakhov static void ext4_map_blocks_es_recheck(handle_t *handle,
415921f266bSDmitry Monakhov 				       struct inode *inode,
416921f266bSDmitry Monakhov 				       struct ext4_map_blocks *es_map,
417921f266bSDmitry Monakhov 				       struct ext4_map_blocks *map,
418921f266bSDmitry Monakhov 				       int flags)
419921f266bSDmitry Monakhov {
420921f266bSDmitry Monakhov 	int retval;
421921f266bSDmitry Monakhov 
422921f266bSDmitry Monakhov 	map->m_flags = 0;
423921f266bSDmitry Monakhov 	/*
424921f266bSDmitry Monakhov 	 * There is a race window that the result is not the same.
425921f266bSDmitry Monakhov 	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
426921f266bSDmitry Monakhov 	 * is that we lookup a block mapping in extent status tree with
427921f266bSDmitry Monakhov 	 * out taking i_data_sem.  So at the time the unwritten extent
428921f266bSDmitry Monakhov 	 * could be converted.
429921f266bSDmitry Monakhov 	 */
430c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
431921f266bSDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4329e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
433921f266bSDmitry Monakhov 	} else {
4349e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
435921f266bSDmitry Monakhov 	}
436921f266bSDmitry Monakhov 	up_read((&EXT4_I(inode)->i_data_sem));
437921f266bSDmitry Monakhov 
438921f266bSDmitry Monakhov 	/*
439921f266bSDmitry Monakhov 	 * We don't check m_len because extent will be collpased in status
440921f266bSDmitry Monakhov 	 * tree.  So the m_len might not equal.
441921f266bSDmitry Monakhov 	 */
442921f266bSDmitry Monakhov 	if (es_map->m_lblk != map->m_lblk ||
443921f266bSDmitry Monakhov 	    es_map->m_flags != map->m_flags ||
444921f266bSDmitry Monakhov 	    es_map->m_pblk != map->m_pblk) {
445bdafe42aSTheodore Ts'o 		printk("ES cache assertion failed for inode: %lu "
446921f266bSDmitry Monakhov 		       "es_cached ex [%d/%d/%llu/%x] != "
447921f266bSDmitry Monakhov 		       "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
448921f266bSDmitry Monakhov 		       inode->i_ino, es_map->m_lblk, es_map->m_len,
449921f266bSDmitry Monakhov 		       es_map->m_pblk, es_map->m_flags, map->m_lblk,
450921f266bSDmitry Monakhov 		       map->m_len, map->m_pblk, map->m_flags,
451921f266bSDmitry Monakhov 		       retval, flags);
452921f266bSDmitry Monakhov 	}
453921f266bSDmitry Monakhov }
454921f266bSDmitry Monakhov #endif /* ES_AGGRESSIVE_TEST */
455921f266bSDmitry Monakhov 
456f12fbb95SZhang Yi static int ext4_map_query_blocks(handle_t *handle, struct inode *inode,
457f12fbb95SZhang Yi 				 struct ext4_map_blocks *map)
458f12fbb95SZhang Yi {
459f12fbb95SZhang Yi 	unsigned int status;
460f12fbb95SZhang Yi 	int retval;
461f12fbb95SZhang Yi 
462f12fbb95SZhang Yi 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
463f12fbb95SZhang Yi 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
464f12fbb95SZhang Yi 	else
465f12fbb95SZhang Yi 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
466f12fbb95SZhang Yi 
467f12fbb95SZhang Yi 	if (retval <= 0)
468f12fbb95SZhang Yi 		return retval;
469f12fbb95SZhang Yi 
470f12fbb95SZhang Yi 	if (unlikely(retval != map->m_len)) {
471f12fbb95SZhang Yi 		ext4_warning(inode->i_sb,
472f12fbb95SZhang Yi 			     "ES len assertion failed for inode "
473f12fbb95SZhang Yi 			     "%lu: retval %d != map->m_len %d",
474f12fbb95SZhang Yi 			     inode->i_ino, retval, map->m_len);
475f12fbb95SZhang Yi 		WARN_ON(1);
476f12fbb95SZhang Yi 	}
477f12fbb95SZhang Yi 
478f12fbb95SZhang Yi 	status = map->m_flags & EXT4_MAP_UNWRITTEN ?
479f12fbb95SZhang Yi 			EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
480f12fbb95SZhang Yi 	ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
481f12fbb95SZhang Yi 			      map->m_pblk, status);
482f12fbb95SZhang Yi 	return retval;
483f12fbb95SZhang Yi }
484f12fbb95SZhang Yi 
48555138e0bSTheodore Ts'o /*
486e35fd660STheodore Ts'o  * The ext4_map_blocks() function tries to look up the requested blocks,
4872b2d6d01STheodore Ts'o  * and returns if the blocks are already mapped.
488f5ab0d1fSMingming Cao  *
489f5ab0d1fSMingming Cao  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
490f5ab0d1fSMingming Cao  * and store the allocated blocks in the result buffer head and mark it
491f5ab0d1fSMingming Cao  * mapped.
492f5ab0d1fSMingming Cao  *
493e35fd660STheodore Ts'o  * If file type is extents based, it will call ext4_ext_map_blocks(),
494e35fd660STheodore Ts'o  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
495f5ab0d1fSMingming Cao  * based files
496f5ab0d1fSMingming Cao  *
497facab4d9SJan Kara  * On success, it returns the number of blocks being mapped or allocated.  if
498facab4d9SJan Kara  * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
499facab4d9SJan Kara  * is marked as unwritten. If the create == 1, it will mark @map as mapped.
500f5ab0d1fSMingming Cao  *
501f5ab0d1fSMingming Cao  * It returns 0 if plain look up failed (blocks have not been allocated), in
502facab4d9SJan Kara  * that case, @map is returned as unmapped but we still do fill map->m_len to
503facab4d9SJan Kara  * indicate the length of a hole starting at map->m_lblk.
504f5ab0d1fSMingming Cao  *
505f5ab0d1fSMingming Cao  * It returns the error in case of allocation failure.
506f5ab0d1fSMingming Cao  */
507e35fd660STheodore Ts'o int ext4_map_blocks(handle_t *handle, struct inode *inode,
508e35fd660STheodore Ts'o 		    struct ext4_map_blocks *map, int flags)
5090e855ac8SAneesh Kumar K.V {
510d100eef2SZheng Liu 	struct extent_status es;
5110e855ac8SAneesh Kumar K.V 	int retval;
512b8a86845SLukas Czerner 	int ret = 0;
513921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
514921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
515921f266bSDmitry Monakhov 
516921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
517921f266bSDmitry Monakhov #endif
518f5ab0d1fSMingming Cao 
519e35fd660STheodore Ts'o 	map->m_flags = 0;
52070aa1554SRitesh Harjani 	ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
52170aa1554SRitesh Harjani 		  flags, map->m_len, (unsigned long) map->m_lblk);
522d100eef2SZheng Liu 
523e861b5e9STheodore Ts'o 	/*
524e861b5e9STheodore Ts'o 	 * ext4_map_blocks returns an int, and m_len is an unsigned int
525e861b5e9STheodore Ts'o 	 */
526e861b5e9STheodore Ts'o 	if (unlikely(map->m_len > INT_MAX))
527e861b5e9STheodore Ts'o 		map->m_len = INT_MAX;
528e861b5e9STheodore Ts'o 
5294adb6ab3SKazuya Mio 	/* We can handle the block number less than EXT_MAX_BLOCKS */
5304adb6ab3SKazuya Mio 	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
5316a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
5324adb6ab3SKazuya Mio 
533d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
5348016e29fSHarshad Shirwadkar 	if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
5358016e29fSHarshad Shirwadkar 	    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
536d100eef2SZheng Liu 		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
537d100eef2SZheng Liu 			map->m_pblk = ext4_es_pblock(&es) +
538d100eef2SZheng Liu 					map->m_lblk - es.es_lblk;
539d100eef2SZheng Liu 			map->m_flags |= ext4_es_is_written(&es) ?
540d100eef2SZheng Liu 					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
541d100eef2SZheng Liu 			retval = es.es_len - (map->m_lblk - es.es_lblk);
542d100eef2SZheng Liu 			if (retval > map->m_len)
543d100eef2SZheng Liu 				retval = map->m_len;
544d100eef2SZheng Liu 			map->m_len = retval;
545d100eef2SZheng Liu 		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
546facab4d9SJan Kara 			map->m_pblk = 0;
547facab4d9SJan Kara 			retval = es.es_len - (map->m_lblk - es.es_lblk);
548facab4d9SJan Kara 			if (retval > map->m_len)
549facab4d9SJan Kara 				retval = map->m_len;
550facab4d9SJan Kara 			map->m_len = retval;
551d100eef2SZheng Liu 			retval = 0;
552d100eef2SZheng Liu 		} else {
5531e83bc81SArnd Bergmann 			BUG();
554d100eef2SZheng Liu 		}
5559558cf14SZhang Yi 
5569558cf14SZhang Yi 		if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5579558cf14SZhang Yi 			return retval;
558921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
559921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(handle, inode, map,
560921f266bSDmitry Monakhov 					   &orig_map, flags);
561921f266bSDmitry Monakhov #endif
562d100eef2SZheng Liu 		goto found;
563d100eef2SZheng Liu 	}
5649558cf14SZhang Yi 	/*
5659558cf14SZhang Yi 	 * In the query cache no-wait mode, nothing we can do more if we
5669558cf14SZhang Yi 	 * cannot find extent in the cache.
5679558cf14SZhang Yi 	 */
5689558cf14SZhang Yi 	if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5699558cf14SZhang Yi 		return 0;
570d100eef2SZheng Liu 
5714df3d265SAneesh Kumar K.V 	/*
572b920c755STheodore Ts'o 	 * Try to see if we can get the block without requesting a new
573b920c755STheodore Ts'o 	 * file system block.
5744df3d265SAneesh Kumar K.V 	 */
575c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
57612e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5779e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
5784df3d265SAneesh Kumar K.V 	} else {
5799e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
5800e855ac8SAneesh Kumar K.V 	}
581f7fec032SZheng Liu 	if (retval > 0) {
5823be78c73STheodore Ts'o 		unsigned int status;
583f7fec032SZheng Liu 
58444fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
58544fb851dSZheng Liu 			ext4_warning(inode->i_sb,
58644fb851dSZheng Liu 				     "ES len assertion failed for inode "
58744fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
58844fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
58944fb851dSZheng Liu 			WARN_ON(1);
590921f266bSDmitry Monakhov 		}
591921f266bSDmitry Monakhov 
592f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
593f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
594f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
595d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
596ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
597f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
598f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
5996c120399SBaokun Li 		ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
6006c120399SBaokun Li 				      map->m_pblk, status);
601f7fec032SZheng Liu 	}
6024df3d265SAneesh Kumar K.V 	up_read((&EXT4_I(inode)->i_data_sem));
603f5ab0d1fSMingming Cao 
604d100eef2SZheng Liu found:
605e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
606b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
6076fd058f7STheodore Ts'o 		if (ret != 0)
6086fd058f7STheodore Ts'o 			return ret;
6096fd058f7STheodore Ts'o 	}
6106fd058f7STheodore Ts'o 
611f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
612c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
6134df3d265SAneesh Kumar K.V 		return retval;
6144df3d265SAneesh Kumar K.V 
6154df3d265SAneesh Kumar K.V 	/*
616f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
617f5ab0d1fSMingming Cao 	 *
618f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
619df3ab170STao Ma 	 * ext4_ext_get_block() returns the create = 0
620f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
621f5ab0d1fSMingming Cao 	 */
622e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
623b8a86845SLukas Czerner 		/*
624b8a86845SLukas Czerner 		 * If we need to convert extent to unwritten
625b8a86845SLukas Czerner 		 * we continue and do the actual work in
626b8a86845SLukas Czerner 		 * ext4_ext_map_blocks()
627b8a86845SLukas Czerner 		 */
628b8a86845SLukas Czerner 		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
629f5ab0d1fSMingming Cao 			return retval;
630f5ab0d1fSMingming Cao 
631f5ab0d1fSMingming Cao 	/*
632a25a4e1aSZheng Liu 	 * Here we clear m_flags because after allocating an new extent,
633a25a4e1aSZheng Liu 	 * it will be set again.
6342a8964d6SAneesh Kumar K.V 	 */
635a25a4e1aSZheng Liu 	map->m_flags &= ~EXT4_MAP_FLAGS;
6362a8964d6SAneesh Kumar K.V 
6372a8964d6SAneesh Kumar K.V 	/*
638556615dcSLukas Czerner 	 * New blocks allocate and/or writing to unwritten extent
639f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
640d91bd2c1SSeunghun Lee 	 * the write lock of i_data_sem, and call get_block()
641f5ab0d1fSMingming Cao 	 * with create == 1 flag.
6424df3d265SAneesh Kumar K.V 	 */
643c8b459f4SLukas Czerner 	down_write(&EXT4_I(inode)->i_data_sem);
644d2a17637SMingming Cao 
645d2a17637SMingming Cao 	/*
6464df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
6474df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
6484df3d265SAneesh Kumar K.V 	 */
64912e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
650e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
6510e855ac8SAneesh Kumar K.V 	} else {
652e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
653267e4db9SAneesh Kumar K.V 
654e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
655267e4db9SAneesh Kumar K.V 			/*
656267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
657267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
658267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
659267e4db9SAneesh Kumar K.V 			 */
66019f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
661267e4db9SAneesh Kumar K.V 		}
6625f634d06SAneesh Kumar K.V 	}
663d2a17637SMingming Cao 
664f7fec032SZheng Liu 	if (retval > 0) {
6653be78c73STheodore Ts'o 		unsigned int status;
666f7fec032SZheng Liu 
66744fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
66844fb851dSZheng Liu 			ext4_warning(inode->i_sb,
66944fb851dSZheng Liu 				     "ES len assertion failed for inode "
67044fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
67144fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
67244fb851dSZheng Liu 			WARN_ON(1);
673921f266bSDmitry Monakhov 		}
674921f266bSDmitry Monakhov 
675adb23551SZheng Liu 		/*
676c86d8db3SJan Kara 		 * We have to zeroout blocks before inserting them into extent
677c86d8db3SJan Kara 		 * status tree. Otherwise someone could look them up there and
6789b623df6SJan Kara 		 * use them before they are really zeroed. We also have to
6799b623df6SJan Kara 		 * unmap metadata before zeroing as otherwise writeback can
6809b623df6SJan Kara 		 * overwrite zeros with stale data from block device.
681c86d8db3SJan Kara 		 */
682c86d8db3SJan Kara 		if (flags & EXT4_GET_BLOCKS_ZERO &&
683c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_MAPPED &&
684c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_NEW) {
685c86d8db3SJan Kara 			ret = ext4_issue_zeroout(inode, map->m_lblk,
686c86d8db3SJan Kara 						 map->m_pblk, map->m_len);
687c86d8db3SJan Kara 			if (ret) {
688c86d8db3SJan Kara 				retval = ret;
689c86d8db3SJan Kara 				goto out_sem;
690c86d8db3SJan Kara 			}
691c86d8db3SJan Kara 		}
692c86d8db3SJan Kara 
693c86d8db3SJan Kara 		/*
694adb23551SZheng Liu 		 * If the extent has been zeroed out, we don't need to update
695adb23551SZheng Liu 		 * extent status tree.
696adb23551SZheng Liu 		 */
697adb23551SZheng Liu 		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
698bb5835edSTheodore Ts'o 		    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
699adb23551SZheng Liu 			if (ext4_es_is_written(&es))
700c86d8db3SJan Kara 				goto out_sem;
701adb23551SZheng Liu 		}
702f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
703f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
704f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
705d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
706ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
707f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
708f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
7096c120399SBaokun Li 		ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
710f7fec032SZheng Liu 				      map->m_pblk, status);
71151865fdaSZheng Liu 	}
7125356f261SAditya Kali 
713c86d8db3SJan Kara out_sem:
7140e855ac8SAneesh Kumar K.V 	up_write((&EXT4_I(inode)->i_data_sem));
715e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
716b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
7176fd058f7STheodore Ts'o 		if (ret != 0)
7186fd058f7STheodore Ts'o 			return ret;
71906bd3c36SJan Kara 
72006bd3c36SJan Kara 		/*
72106bd3c36SJan Kara 		 * Inodes with freshly allocated blocks where contents will be
72206bd3c36SJan Kara 		 * visible after transaction commit must be on transaction's
72306bd3c36SJan Kara 		 * ordered data list.
72406bd3c36SJan Kara 		 */
72506bd3c36SJan Kara 		if (map->m_flags & EXT4_MAP_NEW &&
72606bd3c36SJan Kara 		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
72706bd3c36SJan Kara 		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
72802749a4cSTahsin Erdogan 		    !ext4_is_quota_file(inode) &&
72906bd3c36SJan Kara 		    ext4_should_order_data(inode)) {
73073131fbbSRoss Zwisler 			loff_t start_byte =
73173131fbbSRoss Zwisler 				(loff_t)map->m_lblk << inode->i_blkbits;
73273131fbbSRoss Zwisler 			loff_t length = (loff_t)map->m_len << inode->i_blkbits;
73373131fbbSRoss Zwisler 
734ee0876bcSJan Kara 			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
73573131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_wait(handle, inode,
73673131fbbSRoss Zwisler 						start_byte, length);
737ee0876bcSJan Kara 			else
73873131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_write(handle, inode,
73973131fbbSRoss Zwisler 						start_byte, length);
74006bd3c36SJan Kara 			if (ret)
74106bd3c36SJan Kara 				return ret;
74206bd3c36SJan Kara 		}
7435e4d0ebaSXin Yin 	}
7445e4d0ebaSXin Yin 	if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
7455e4d0ebaSXin Yin 				map->m_flags & EXT4_MAP_MAPPED))
746a80f7fcfSHarshad Shirwadkar 		ext4_fc_track_range(handle, inode, map->m_lblk,
747aa75f4d3SHarshad Shirwadkar 					map->m_lblk + map->m_len - 1);
748ec8c60beSRitesh Harjani 	if (retval < 0)
74970aa1554SRitesh Harjani 		ext_debug(inode, "failed with err %d\n", retval);
7500e855ac8SAneesh Kumar K.V 	return retval;
7510e855ac8SAneesh Kumar K.V }
7520e855ac8SAneesh Kumar K.V 
753ed8ad838SJan Kara /*
754ed8ad838SJan Kara  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
755ed8ad838SJan Kara  * we have to be careful as someone else may be manipulating b_state as well.
756ed8ad838SJan Kara  */
757ed8ad838SJan Kara static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
758ed8ad838SJan Kara {
759ed8ad838SJan Kara 	unsigned long old_state;
760ed8ad838SJan Kara 	unsigned long new_state;
761ed8ad838SJan Kara 
762ed8ad838SJan Kara 	flags &= EXT4_MAP_FLAGS;
763ed8ad838SJan Kara 
764ed8ad838SJan Kara 	/* Dummy buffer_head? Set non-atomically. */
765ed8ad838SJan Kara 	if (!bh->b_page) {
766ed8ad838SJan Kara 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
767ed8ad838SJan Kara 		return;
768ed8ad838SJan Kara 	}
769ed8ad838SJan Kara 	/*
770ed8ad838SJan Kara 	 * Someone else may be modifying b_state. Be careful! This is ugly but
771ed8ad838SJan Kara 	 * once we get rid of using bh as a container for mapping information
772ed8ad838SJan Kara 	 * to pass to / from get_block functions, this can go away.
773ed8ad838SJan Kara 	 */
774ed8ad838SJan Kara 	old_state = READ_ONCE(bh->b_state);
7753ee2a3e7SUros Bizjak 	do {
776ed8ad838SJan Kara 		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
7773ee2a3e7SUros Bizjak 	} while (unlikely(!try_cmpxchg(&bh->b_state, &old_state, new_state)));
778ed8ad838SJan Kara }
779ed8ad838SJan Kara 
7802ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
7812ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
782ac27a0ecSDave Kleikamp {
7832ed88685STheodore Ts'o 	struct ext4_map_blocks map;
784efe70c29SJan Kara 	int ret = 0;
785ac27a0ecSDave Kleikamp 
78646c7f254STao Ma 	if (ext4_has_inline_data(inode))
78746c7f254STao Ma 		return -ERANGE;
78846c7f254STao Ma 
7892ed88685STheodore Ts'o 	map.m_lblk = iblock;
7902ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
7912ed88685STheodore Ts'o 
792efe70c29SJan Kara 	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
793efe70c29SJan Kara 			      flags);
794ac27a0ecSDave Kleikamp 	if (ret > 0) {
7952ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
796ed8ad838SJan Kara 		ext4_update_bh_state(bh, map.m_flags);
7972ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
798ac27a0ecSDave Kleikamp 		ret = 0;
799547edce3SRoss Zwisler 	} else if (ret == 0) {
800547edce3SRoss Zwisler 		/* hole case, need to fill in bh->b_size */
801547edce3SRoss Zwisler 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
802ac27a0ecSDave Kleikamp 	}
803ac27a0ecSDave Kleikamp 	return ret;
804ac27a0ecSDave Kleikamp }
805ac27a0ecSDave Kleikamp 
8062ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
8072ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
8082ed88685STheodore Ts'o {
8092ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
8102ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
8112ed88685STheodore Ts'o }
8122ed88685STheodore Ts'o 
813ac27a0ecSDave Kleikamp /*
814705965bdSJan Kara  * Get block function used when preparing for buffered write if we require
815705965bdSJan Kara  * creating an unwritten extent if blocks haven't been allocated.  The extent
816705965bdSJan Kara  * will be converted to written after the IO is complete.
817705965bdSJan Kara  */
818705965bdSJan Kara int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
819705965bdSJan Kara 			     struct buffer_head *bh_result, int create)
820705965bdSJan Kara {
821c26e3adcSOjaswin Mujoo 	int ret = 0;
822c26e3adcSOjaswin Mujoo 
823705965bdSJan Kara 	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
824705965bdSJan Kara 		   inode->i_ino, create);
825c26e3adcSOjaswin Mujoo 	ret = _ext4_get_block(inode, iblock, bh_result,
8268d5459c1SJan Kara 			       EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
827c26e3adcSOjaswin Mujoo 
828c26e3adcSOjaswin Mujoo 	/*
829c26e3adcSOjaswin Mujoo 	 * If the buffer is marked unwritten, mark it as new to make sure it is
830c26e3adcSOjaswin Mujoo 	 * zeroed out correctly in case of partial writes. Otherwise, there is
831c26e3adcSOjaswin Mujoo 	 * a chance of stale data getting exposed.
832c26e3adcSOjaswin Mujoo 	 */
833c26e3adcSOjaswin Mujoo 	if (ret == 0 && buffer_unwritten(bh_result))
834c26e3adcSOjaswin Mujoo 		set_buffer_new(bh_result);
835c26e3adcSOjaswin Mujoo 
836c26e3adcSOjaswin Mujoo 	return ret;
837705965bdSJan Kara }
838705965bdSJan Kara 
839efe70c29SJan Kara /* Maximum number of blocks we map for direct IO at once. */
840efe70c29SJan Kara #define DIO_MAX_BLOCKS 4096
841efe70c29SJan Kara 
842e84dfbe2SJan Kara /*
843ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
844ac27a0ecSDave Kleikamp  */
845617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
846c5e298aeSTheodore Ts'o 				ext4_lblk_t block, int map_flags)
847ac27a0ecSDave Kleikamp {
8482ed88685STheodore Ts'o 	struct ext4_map_blocks map;
8492ed88685STheodore Ts'o 	struct buffer_head *bh;
850c5e298aeSTheodore Ts'o 	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
8519558cf14SZhang Yi 	bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
85210560082STheodore Ts'o 	int err;
853ac27a0ecSDave Kleikamp 
854837c23fbSChunguang Xu 	ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8558016e29fSHarshad Shirwadkar 		    || handle != NULL || create == 0);
8569558cf14SZhang Yi 	ASSERT(create == 0 || !nowait);
857ac27a0ecSDave Kleikamp 
8582ed88685STheodore Ts'o 	map.m_lblk = block;
8592ed88685STheodore Ts'o 	map.m_len = 1;
860c5e298aeSTheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map, map_flags);
8612ed88685STheodore Ts'o 
86210560082STheodore Ts'o 	if (err == 0)
86310560082STheodore Ts'o 		return create ? ERR_PTR(-ENOSPC) : NULL;
8642ed88685STheodore Ts'o 	if (err < 0)
86510560082STheodore Ts'o 		return ERR_PTR(err);
8662ed88685STheodore Ts'o 
8679558cf14SZhang Yi 	if (nowait)
8689558cf14SZhang Yi 		return sb_find_get_block(inode->i_sb, map.m_pblk);
8699558cf14SZhang Yi 
8702ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
87110560082STheodore Ts'o 	if (unlikely(!bh))
87210560082STheodore Ts'o 		return ERR_PTR(-ENOMEM);
8732ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
874837c23fbSChunguang Xu 		ASSERT(create != 0);
875837c23fbSChunguang Xu 		ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8768016e29fSHarshad Shirwadkar 			    || (handle != NULL));
877ac27a0ecSDave Kleikamp 
878ac27a0ecSDave Kleikamp 		/*
879ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
880ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
881ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
882617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
883ac27a0ecSDave Kleikamp 		 * problem.
884ac27a0ecSDave Kleikamp 		 */
885ac27a0ecSDave Kleikamp 		lock_buffer(bh);
886ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
887188c299eSJan Kara 		err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
888188c299eSJan Kara 						     EXT4_JTR_NONE);
88910560082STheodore Ts'o 		if (unlikely(err)) {
89010560082STheodore Ts'o 			unlock_buffer(bh);
89110560082STheodore Ts'o 			goto errout;
89210560082STheodore Ts'o 		}
89310560082STheodore Ts'o 		if (!buffer_uptodate(bh)) {
894ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
895ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
896ac27a0ecSDave Kleikamp 		}
897ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
8980390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
8990390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
90010560082STheodore Ts'o 		if (unlikely(err))
90110560082STheodore Ts'o 			goto errout;
90210560082STheodore Ts'o 	} else
903ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
904ac27a0ecSDave Kleikamp 	return bh;
90510560082STheodore Ts'o errout:
90610560082STheodore Ts'o 	brelse(bh);
90710560082STheodore Ts'o 	return ERR_PTR(err);
908ac27a0ecSDave Kleikamp }
909ac27a0ecSDave Kleikamp 
910617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
911c5e298aeSTheodore Ts'o 			       ext4_lblk_t block, int map_flags)
912ac27a0ecSDave Kleikamp {
913ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
9142d069c08Szhangyi (F) 	int ret;
915ac27a0ecSDave Kleikamp 
916c5e298aeSTheodore Ts'o 	bh = ext4_getblk(handle, inode, block, map_flags);
9171c215028STheodore Ts'o 	if (IS_ERR(bh))
918ac27a0ecSDave Kleikamp 		return bh;
9197963e5acSZhangXiaoxu 	if (!bh || ext4_buffer_uptodate(bh))
920ac27a0ecSDave Kleikamp 		return bh;
9212d069c08Szhangyi (F) 
9222d069c08Szhangyi (F) 	ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
9232d069c08Szhangyi (F) 	if (ret) {
924ac27a0ecSDave Kleikamp 		put_bh(bh);
9252d069c08Szhangyi (F) 		return ERR_PTR(ret);
9262d069c08Szhangyi (F) 	}
9272d069c08Szhangyi (F) 	return bh;
928ac27a0ecSDave Kleikamp }
929ac27a0ecSDave Kleikamp 
9309699d4f9STahsin Erdogan /* Read a contiguous batch of blocks. */
9319699d4f9STahsin Erdogan int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
9329699d4f9STahsin Erdogan 		     bool wait, struct buffer_head **bhs)
9339699d4f9STahsin Erdogan {
9349699d4f9STahsin Erdogan 	int i, err;
9359699d4f9STahsin Erdogan 
9369699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9379699d4f9STahsin Erdogan 		bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
9389699d4f9STahsin Erdogan 		if (IS_ERR(bhs[i])) {
9399699d4f9STahsin Erdogan 			err = PTR_ERR(bhs[i]);
9409699d4f9STahsin Erdogan 			bh_count = i;
9419699d4f9STahsin Erdogan 			goto out_brelse;
9429699d4f9STahsin Erdogan 		}
9439699d4f9STahsin Erdogan 	}
9449699d4f9STahsin Erdogan 
9459699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9469699d4f9STahsin Erdogan 		/* Note that NULL bhs[i] is valid because of holes. */
9472d069c08Szhangyi (F) 		if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
9482d069c08Szhangyi (F) 			ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
9499699d4f9STahsin Erdogan 
9509699d4f9STahsin Erdogan 	if (!wait)
9519699d4f9STahsin Erdogan 		return 0;
9529699d4f9STahsin Erdogan 
9539699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9549699d4f9STahsin Erdogan 		if (bhs[i])
9559699d4f9STahsin Erdogan 			wait_on_buffer(bhs[i]);
9569699d4f9STahsin Erdogan 
9579699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9589699d4f9STahsin Erdogan 		if (bhs[i] && !buffer_uptodate(bhs[i])) {
9599699d4f9STahsin Erdogan 			err = -EIO;
9609699d4f9STahsin Erdogan 			goto out_brelse;
9619699d4f9STahsin Erdogan 		}
9629699d4f9STahsin Erdogan 	}
9639699d4f9STahsin Erdogan 	return 0;
9649699d4f9STahsin Erdogan 
9659699d4f9STahsin Erdogan out_brelse:
9669699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9679699d4f9STahsin Erdogan 		brelse(bhs[i]);
9689699d4f9STahsin Erdogan 		bhs[i] = NULL;
9699699d4f9STahsin Erdogan 	}
9709699d4f9STahsin Erdogan 	return err;
9719699d4f9STahsin Erdogan }
9729699d4f9STahsin Erdogan 
973188c299eSJan Kara int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
974ac27a0ecSDave Kleikamp 			   struct buffer_head *head,
975ac27a0ecSDave Kleikamp 			   unsigned from,
976ac27a0ecSDave Kleikamp 			   unsigned to,
977ac27a0ecSDave Kleikamp 			   int *partial,
978188c299eSJan Kara 			   int (*fn)(handle_t *handle, struct inode *inode,
979ac27a0ecSDave Kleikamp 				     struct buffer_head *bh))
980ac27a0ecSDave Kleikamp {
981ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
982ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
983ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
984ac27a0ecSDave Kleikamp 	int err, ret = 0;
985ac27a0ecSDave Kleikamp 	struct buffer_head *next;
986ac27a0ecSDave Kleikamp 
987ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
988ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
989de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
990ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
991ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
992ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
993ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
994ac27a0ecSDave Kleikamp 				*partial = 1;
995ac27a0ecSDave Kleikamp 			continue;
996ac27a0ecSDave Kleikamp 		}
997188c299eSJan Kara 		err = (*fn)(handle, inode, bh);
998ac27a0ecSDave Kleikamp 		if (!ret)
999ac27a0ecSDave Kleikamp 			ret = err;
1000ac27a0ecSDave Kleikamp 	}
1001ac27a0ecSDave Kleikamp 	return ret;
1002ac27a0ecSDave Kleikamp }
1003ac27a0ecSDave Kleikamp 
1004d84c9ebdSJan Kara /*
1005d84c9ebdSJan Kara  * Helper for handling dirtying of journalled data. We also mark the folio as
1006d84c9ebdSJan Kara  * dirty so that writeback code knows about this page (and inode) contains
1007d84c9ebdSJan Kara  * dirty data. ext4_writepages() then commits appropriate transaction to
1008d84c9ebdSJan Kara  * make data stable.
1009d84c9ebdSJan Kara  */
1010d84c9ebdSJan Kara static int ext4_dirty_journalled_data(handle_t *handle, struct buffer_head *bh)
1011d84c9ebdSJan Kara {
1012d84c9ebdSJan Kara 	folio_mark_dirty(bh->b_folio);
1013d84c9ebdSJan Kara 	return ext4_handle_dirty_metadata(handle, NULL, bh);
1014d84c9ebdSJan Kara }
1015d84c9ebdSJan Kara 
1016188c299eSJan Kara int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1017ac27a0ecSDave Kleikamp 				struct buffer_head *bh)
1018ac27a0ecSDave Kleikamp {
101956d35a4cSJan Kara 	int dirty = buffer_dirty(bh);
102056d35a4cSJan Kara 	int ret;
102156d35a4cSJan Kara 
1022ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1023ac27a0ecSDave Kleikamp 		return 0;
102456d35a4cSJan Kara 	/*
1025ebdec241SChristoph Hellwig 	 * __block_write_begin() could have dirtied some buffers. Clean
102656d35a4cSJan Kara 	 * the dirty bit as jbd2_journal_get_write_access() could complain
102756d35a4cSJan Kara 	 * otherwise about fs integrity issues. Setting of the dirty bit
1028ebdec241SChristoph Hellwig 	 * by __block_write_begin() isn't a real problem here as we clear
102956d35a4cSJan Kara 	 * the bit before releasing a page lock and thus writeback cannot
103056d35a4cSJan Kara 	 * ever write the buffer.
103156d35a4cSJan Kara 	 */
103256d35a4cSJan Kara 	if (dirty)
103356d35a4cSJan Kara 		clear_buffer_dirty(bh);
10345d601255Sliang xie 	BUFFER_TRACE(bh, "get write access");
1035188c299eSJan Kara 	ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
1036188c299eSJan Kara 					    EXT4_JTR_NONE);
103756d35a4cSJan Kara 	if (!ret && dirty)
1038d84c9ebdSJan Kara 		ret = ext4_dirty_journalled_data(handle, bh);
103956d35a4cSJan Kara 	return ret;
1040ac27a0ecSDave Kleikamp }
1041ac27a0ecSDave Kleikamp 
1042643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
104386b38c27SMatthew Wilcox static int ext4_block_write_begin(struct folio *folio, loff_t pos, unsigned len,
10442058f83aSMichael Halcrow 				  get_block_t *get_block)
10452058f83aSMichael Halcrow {
104609cbfeafSKirill A. Shutemov 	unsigned from = pos & (PAGE_SIZE - 1);
10472058f83aSMichael Halcrow 	unsigned to = from + len;
104886b38c27SMatthew Wilcox 	struct inode *inode = folio->mapping->host;
10492058f83aSMichael Halcrow 	unsigned block_start, block_end;
10502058f83aSMichael Halcrow 	sector_t block;
10512058f83aSMichael Halcrow 	int err = 0;
10522058f83aSMichael Halcrow 	unsigned blocksize = inode->i_sb->s_blocksize;
10532058f83aSMichael Halcrow 	unsigned bbits;
10540b578f35SChandan Rajendra 	struct buffer_head *bh, *head, *wait[2];
10550b578f35SChandan Rajendra 	int nr_wait = 0;
10560b578f35SChandan Rajendra 	int i;
10572058f83aSMichael Halcrow 
105886b38c27SMatthew Wilcox 	BUG_ON(!folio_test_locked(folio));
105909cbfeafSKirill A. Shutemov 	BUG_ON(from > PAGE_SIZE);
106009cbfeafSKirill A. Shutemov 	BUG_ON(to > PAGE_SIZE);
10612058f83aSMichael Halcrow 	BUG_ON(from > to);
10622058f83aSMichael Halcrow 
106386b38c27SMatthew Wilcox 	head = folio_buffers(folio);
106486b38c27SMatthew Wilcox 	if (!head) {
106586b38c27SMatthew Wilcox 		create_empty_buffers(&folio->page, blocksize, 0);
106686b38c27SMatthew Wilcox 		head = folio_buffers(folio);
106786b38c27SMatthew Wilcox 	}
10682058f83aSMichael Halcrow 	bbits = ilog2(blocksize);
106986b38c27SMatthew Wilcox 	block = (sector_t)folio->index << (PAGE_SHIFT - bbits);
10702058f83aSMichael Halcrow 
10712058f83aSMichael Halcrow 	for (bh = head, block_start = 0; bh != head || !block_start;
10722058f83aSMichael Halcrow 	    block++, block_start = block_end, bh = bh->b_this_page) {
10732058f83aSMichael Halcrow 		block_end = block_start + blocksize;
10742058f83aSMichael Halcrow 		if (block_end <= from || block_start >= to) {
107586b38c27SMatthew Wilcox 			if (folio_test_uptodate(folio)) {
10762058f83aSMichael Halcrow 				set_buffer_uptodate(bh);
10772058f83aSMichael Halcrow 			}
10782058f83aSMichael Halcrow 			continue;
10792058f83aSMichael Halcrow 		}
10802058f83aSMichael Halcrow 		if (buffer_new(bh))
10812058f83aSMichael Halcrow 			clear_buffer_new(bh);
10822058f83aSMichael Halcrow 		if (!buffer_mapped(bh)) {
10832058f83aSMichael Halcrow 			WARN_ON(bh->b_size != blocksize);
10842058f83aSMichael Halcrow 			err = get_block(inode, block, bh, 1);
10852058f83aSMichael Halcrow 			if (err)
10862058f83aSMichael Halcrow 				break;
10872058f83aSMichael Halcrow 			if (buffer_new(bh)) {
108886b38c27SMatthew Wilcox 				if (folio_test_uptodate(folio)) {
10892058f83aSMichael Halcrow 					clear_buffer_new(bh);
10902058f83aSMichael Halcrow 					set_buffer_uptodate(bh);
10912058f83aSMichael Halcrow 					mark_buffer_dirty(bh);
10922058f83aSMichael Halcrow 					continue;
10932058f83aSMichael Halcrow 				}
10942058f83aSMichael Halcrow 				if (block_end > to || block_start < from)
109586b38c27SMatthew Wilcox 					folio_zero_segments(folio, to,
109686b38c27SMatthew Wilcox 							    block_end,
10972058f83aSMichael Halcrow 							    block_start, from);
10982058f83aSMichael Halcrow 				continue;
10992058f83aSMichael Halcrow 			}
11002058f83aSMichael Halcrow 		}
110186b38c27SMatthew Wilcox 		if (folio_test_uptodate(folio)) {
11022058f83aSMichael Halcrow 			set_buffer_uptodate(bh);
11032058f83aSMichael Halcrow 			continue;
11042058f83aSMichael Halcrow 		}
11052058f83aSMichael Halcrow 		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
11062058f83aSMichael Halcrow 		    !buffer_unwritten(bh) &&
11072058f83aSMichael Halcrow 		    (block_start < from || block_end > to)) {
11082d069c08Szhangyi (F) 			ext4_read_bh_lock(bh, 0, false);
11090b578f35SChandan Rajendra 			wait[nr_wait++] = bh;
11102058f83aSMichael Halcrow 		}
11112058f83aSMichael Halcrow 	}
11122058f83aSMichael Halcrow 	/*
11132058f83aSMichael Halcrow 	 * If we issued read requests, let them complete.
11142058f83aSMichael Halcrow 	 */
11150b578f35SChandan Rajendra 	for (i = 0; i < nr_wait; i++) {
11160b578f35SChandan Rajendra 		wait_on_buffer(wait[i]);
11170b578f35SChandan Rajendra 		if (!buffer_uptodate(wait[i]))
11182058f83aSMichael Halcrow 			err = -EIO;
11192058f83aSMichael Halcrow 	}
11207e0785fcSChandan Rajendra 	if (unlikely(err)) {
11214a9622f2SMatthew Wilcox (Oracle) 		folio_zero_new_buffers(folio, from, to);
11224f74d15fSEric Biggers 	} else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
11230b578f35SChandan Rajendra 		for (i = 0; i < nr_wait; i++) {
11240b578f35SChandan Rajendra 			int err2;
11250b578f35SChandan Rajendra 
112686b38c27SMatthew Wilcox 			err2 = fscrypt_decrypt_pagecache_blocks(folio,
112786b38c27SMatthew Wilcox 						blocksize, bh_offset(wait[i]));
11280b578f35SChandan Rajendra 			if (err2) {
11290b578f35SChandan Rajendra 				clear_buffer_uptodate(wait[i]);
11300b578f35SChandan Rajendra 				err = err2;
11310b578f35SChandan Rajendra 			}
11320b578f35SChandan Rajendra 		}
11337e0785fcSChandan Rajendra 	}
11347e0785fcSChandan Rajendra 
11352058f83aSMichael Halcrow 	return err;
11362058f83aSMichael Halcrow }
11372058f83aSMichael Halcrow #endif
11382058f83aSMichael Halcrow 
11399462f770SJan Kara /*
11409462f770SJan Kara  * To preserve ordering, it is essential that the hole instantiation and
11419462f770SJan Kara  * the data write be encapsulated in a single transaction.  We cannot
11429462f770SJan Kara  * close off a transaction and start a new one between the ext4_get_block()
11439462f770SJan Kara  * and the ext4_write_end().  So doing the jbd2_journal_start at the start of
11449462f770SJan Kara  * ext4_write_begin() is the right place.
11459462f770SJan Kara  */
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;
11544d934a5eSMatthew Wilcox 	struct folio *folio;
1155bfc1af65SNick Piggin 	pgoff_t index;
1156bfc1af65SNick Piggin 	unsigned from, to;
1157bfc1af65SNick Piggin 
1158eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(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 	/*
11814d934a5eSMatthew Wilcox 	 * __filemap_get_folio() can take a long time if the
11824d934a5eSMatthew Wilcox 	 * system is thrashing due to memory pressure, or if the folio
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
11854d934a5eSMatthew Wilcox 	 * the folio (if needed) without using GFP_NOFS.
118647564bfbSTheodore Ts'o 	 */
118747564bfbSTheodore Ts'o retry_grab:
11884d934a5eSMatthew Wilcox 	folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
11894d934a5eSMatthew Wilcox 					mapping_gfp_mask(mapping));
11907fa8a8eeSLinus Torvalds 	if (IS_ERR(folio))
11917fa8a8eeSLinus Torvalds 		return PTR_ERR(folio);
1192d1052d23SJinke Han 	/*
1193d1052d23SJinke Han 	 * The same as page allocation, we prealloc buffer heads before
1194d1052d23SJinke Han 	 * starting the handle.
1195d1052d23SJinke Han 	 */
11964d934a5eSMatthew Wilcox 	if (!folio_buffers(folio))
11974d934a5eSMatthew Wilcox 		create_empty_buffers(&folio->page, inode->i_sb->s_blocksize, 0);
1198d1052d23SJinke Han 
11994d934a5eSMatthew Wilcox 	folio_unlock(folio);
120047564bfbSTheodore Ts'o 
120147564bfbSTheodore Ts'o retry_journal:
12029924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
12037479d2b9SAndrew Morton 	if (IS_ERR(handle)) {
12044d934a5eSMatthew Wilcox 		folio_put(folio);
120547564bfbSTheodore Ts'o 		return PTR_ERR(handle);
1206cf108bcaSJan Kara 	}
1207f19d5870STao Ma 
12084d934a5eSMatthew Wilcox 	folio_lock(folio);
12094d934a5eSMatthew Wilcox 	if (folio->mapping != mapping) {
12104d934a5eSMatthew Wilcox 		/* The folio got truncated from under us */
12114d934a5eSMatthew Wilcox 		folio_unlock(folio);
12124d934a5eSMatthew Wilcox 		folio_put(folio);
1213cf108bcaSJan Kara 		ext4_journal_stop(handle);
121447564bfbSTheodore Ts'o 		goto retry_grab;
1215cf108bcaSJan Kara 	}
12164d934a5eSMatthew Wilcox 	/* In case writeback began while the folio was unlocked */
12174d934a5eSMatthew Wilcox 	folio_wait_stable(folio);
1218cf108bcaSJan Kara 
1219643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
12202058f83aSMichael Halcrow 	if (ext4_should_dioread_nolock(inode))
122186b38c27SMatthew Wilcox 		ret = ext4_block_write_begin(folio, pos, len,
1222705965bdSJan Kara 					     ext4_get_block_unwritten);
12232058f83aSMichael Halcrow 	else
122486b38c27SMatthew Wilcox 		ret = ext4_block_write_begin(folio, pos, len, ext4_get_block);
12252058f83aSMichael Halcrow #else
1226744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
12274d934a5eSMatthew Wilcox 		ret = __block_write_begin(&folio->page, pos, len,
1228705965bdSJan Kara 					  ext4_get_block_unwritten);
1229744692dcSJiaying Zhang 	else
12304d934a5eSMatthew Wilcox 		ret = __block_write_begin(&folio->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,
12344d934a5eSMatthew Wilcox 					     folio_buffers(folio), from, to,
12354d934a5eSMatthew Wilcox 					     NULL, 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 
12424d934a5eSMatthew Wilcox 		folio_unlock(folio);
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;
12704d934a5eSMatthew Wilcox 		folio_put(folio);
127147564bfbSTheodore Ts'o 		return ret;
127247564bfbSTheodore Ts'o 	}
12734d934a5eSMatthew Wilcox 	*pagep = &folio->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);
1285d84c9ebdSJan Kara 	ret = ext4_dirty_journalled_data(handle, 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 {
130364fb3136SMatthew Wilcox 	struct folio *folio = page_folio(page);
1304f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
1305eed4333fSZheng Liu 	struct inode *inode = mapping->host;
13060572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1307eed4333fSZheng Liu 	int ret = 0, ret2;
1308eed4333fSZheng Liu 	int i_size_changed = 0;
1309c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1310eed4333fSZheng Liu 
1311eed4333fSZheng Liu 	trace_ext4_write_end(inode, pos, len, copied);
13126984aef5SZhang Yi 
13135c099c4fSYe Bin 	if (ext4_has_inline_data(inode) &&
13145c099c4fSYe Bin 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
1315d19500daSRitesh Harjani 		return ext4_write_inline_data_end(inode, pos, len, copied,
1316d19500daSRitesh Harjani 						  folio);
13176984aef5SZhang Yi 
13186984aef5SZhang Yi 	copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1319f8514083SAneesh Kumar K.V 	/*
132064fb3136SMatthew Wilcox 	 * it's important to update i_size while still holding folio lock:
1321f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
1322c93d8f88SEric Biggers 	 *
1323c93d8f88SEric Biggers 	 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1324c93d8f88SEric Biggers 	 * blocks are being written past EOF, so skip the i_size update.
1325f8514083SAneesh Kumar K.V 	 */
1326c93d8f88SEric Biggers 	if (!verity)
13274631dbf6SDmitry Monakhov 		i_size_changed = ext4_update_inode_size(inode, pos + copied);
132864fb3136SMatthew Wilcox 	folio_unlock(folio);
132964fb3136SMatthew Wilcox 	folio_put(folio);
1330f8514083SAneesh Kumar K.V 
1331c93d8f88SEric Biggers 	if (old_size < pos && !verity)
13320572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
1333f8514083SAneesh Kumar K.V 	/*
133464fb3136SMatthew Wilcox 	 * Don't mark the inode dirty under folio lock. First, it unnecessarily
133564fb3136SMatthew Wilcox 	 * makes the holding time of folio lock longer. Second, it forces lock
133664fb3136SMatthew Wilcox 	 * ordering of folio lock and transaction start for journaling
1337f8514083SAneesh Kumar K.V 	 * filesystems.
1338f8514083SAneesh Kumar K.V 	 */
13396984aef5SZhang Yi 	if (i_size_changed)
13404209ae12SHarshad Shirwadkar 		ret = ext4_mark_inode_dirty(handle, inode);
1341f8514083SAneesh Kumar K.V 
1342c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1343f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1344f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1345f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1346f8514083SAneesh Kumar K.V 		 */
1347f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
134855ce2f64SZhang Yi 
1349617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1350ac27a0ecSDave Kleikamp 	if (!ret)
1351ac27a0ecSDave Kleikamp 		ret = ret2;
1352bfc1af65SNick Piggin 
1353c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1354b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1355f8514083SAneesh Kumar K.V 		/*
1356ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1357f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1358f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1359f8514083SAneesh Kumar K.V 		 */
1360f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1361f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1362f8514083SAneesh Kumar K.V 	}
1363f8514083SAneesh Kumar K.V 
1364bfc1af65SNick Piggin 	return ret ? ret : copied;
1365ac27a0ecSDave Kleikamp }
1366ac27a0ecSDave Kleikamp 
1367b90197b6STheodore Ts'o /*
13684a9622f2SMatthew Wilcox (Oracle)  * This is a private version of folio_zero_new_buffers() which doesn't
1369b90197b6STheodore Ts'o  * set the buffer to be dirty, since in data=journalled mode we need
1370d84c9ebdSJan Kara  * to call ext4_dirty_journalled_data() instead.
1371b90197b6STheodore Ts'o  */
13723b136499SJan Kara static void ext4_journalled_zero_new_buffers(handle_t *handle,
1373188c299eSJan Kara 					    struct inode *inode,
137486324a21SMatthew Wilcox 					    struct folio *folio,
13753b136499SJan Kara 					    unsigned from, unsigned to)
1376b90197b6STheodore Ts'o {
1377b90197b6STheodore Ts'o 	unsigned int block_start = 0, block_end;
1378b90197b6STheodore Ts'o 	struct buffer_head *head, *bh;
1379b90197b6STheodore Ts'o 
138086324a21SMatthew Wilcox 	bh = head = folio_buffers(folio);
1381b90197b6STheodore Ts'o 	do {
1382b90197b6STheodore Ts'o 		block_end = block_start + bh->b_size;
1383b90197b6STheodore Ts'o 		if (buffer_new(bh)) {
1384b90197b6STheodore Ts'o 			if (block_end > from && block_start < to) {
138586324a21SMatthew Wilcox 				if (!folio_test_uptodate(folio)) {
1386b90197b6STheodore Ts'o 					unsigned start, size;
1387b90197b6STheodore Ts'o 
1388b90197b6STheodore Ts'o 					start = max(from, block_start);
1389b90197b6STheodore Ts'o 					size = min(to, block_end) - start;
1390b90197b6STheodore Ts'o 
139186324a21SMatthew Wilcox 					folio_zero_range(folio, start, size);
1392188c299eSJan Kara 					write_end_fn(handle, inode, bh);
1393b90197b6STheodore Ts'o 				}
1394b90197b6STheodore Ts'o 				clear_buffer_new(bh);
1395b90197b6STheodore Ts'o 			}
1396b90197b6STheodore Ts'o 		}
1397b90197b6STheodore Ts'o 		block_start = block_end;
1398b90197b6STheodore Ts'o 		bh = bh->b_this_page;
1399b90197b6STheodore Ts'o 	} while (bh != head);
1400b90197b6STheodore Ts'o }
1401b90197b6STheodore Ts'o 
1402bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
1403bfc1af65SNick Piggin 				     struct address_space *mapping,
1404bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
1405bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
1406ac27a0ecSDave Kleikamp {
1407feb22b77SMatthew Wilcox 	struct folio *folio = page_folio(page);
1408617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1409bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
14100572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1411ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1412ac27a0ecSDave Kleikamp 	int partial = 0;
1413bfc1af65SNick Piggin 	unsigned from, to;
14144631dbf6SDmitry Monakhov 	int size_changed = 0;
1415c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1416ac27a0ecSDave Kleikamp 
14179bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
141809cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1419bfc1af65SNick Piggin 	to = from + len;
1420bfc1af65SNick Piggin 
1421441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1422441c8508SCurt Wohlgemuth 
14236984aef5SZhang Yi 	if (ext4_has_inline_data(inode))
1424d19500daSRitesh Harjani 		return ext4_write_inline_data_end(inode, pos, len, copied,
1425d19500daSRitesh Harjani 						  folio);
14266984aef5SZhang Yi 
1427feb22b77SMatthew Wilcox 	if (unlikely(copied < len) && !folio_test_uptodate(folio)) {
1428bfc1af65SNick Piggin 		copied = 0;
142986324a21SMatthew Wilcox 		ext4_journalled_zero_new_buffers(handle, inode, folio,
143086324a21SMatthew Wilcox 						 from, to);
14313b136499SJan Kara 	} else {
14323b136499SJan Kara 		if (unlikely(copied < len))
143386324a21SMatthew Wilcox 			ext4_journalled_zero_new_buffers(handle, inode, folio,
14343b136499SJan Kara 							 from + copied, to);
1435feb22b77SMatthew Wilcox 		ret = ext4_walk_page_buffers(handle, inode,
1436feb22b77SMatthew Wilcox 					     folio_buffers(folio),
1437188c299eSJan Kara 					     from, from + copied, &partial,
14383b136499SJan Kara 					     write_end_fn);
1439ac27a0ecSDave Kleikamp 		if (!partial)
1440feb22b77SMatthew Wilcox 			folio_mark_uptodate(folio);
14413fdcfb66STao Ma 	}
1442c93d8f88SEric Biggers 	if (!verity)
14434631dbf6SDmitry Monakhov 		size_changed = ext4_update_inode_size(inode, pos + copied);
14442d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1445feb22b77SMatthew Wilcox 	folio_unlock(folio);
1446feb22b77SMatthew Wilcox 	folio_put(folio);
14474631dbf6SDmitry Monakhov 
1448c93d8f88SEric Biggers 	if (old_size < pos && !verity)
14490572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
14500572639fSXiaoguang Wang 
14516984aef5SZhang Yi 	if (size_changed) {
1452617ba13bSMingming Cao 		ret2 = ext4_mark_inode_dirty(handle, inode);
1453ac27a0ecSDave Kleikamp 		if (!ret)
1454ac27a0ecSDave Kleikamp 			ret = ret2;
1455ac27a0ecSDave Kleikamp 	}
1456bfc1af65SNick Piggin 
1457c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1458f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1459f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1460f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1461f8514083SAneesh Kumar K.V 		 */
1462f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1463f8514083SAneesh Kumar K.V 
1464617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1465ac27a0ecSDave Kleikamp 	if (!ret)
1466ac27a0ecSDave Kleikamp 		ret = ret2;
1467c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1468b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1469f8514083SAneesh Kumar K.V 		/*
1470ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1471f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1472f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1473f8514083SAneesh Kumar K.V 		 */
1474f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1475f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1476f8514083SAneesh Kumar K.V 	}
1477bfc1af65SNick Piggin 
1478bfc1af65SNick Piggin 	return ret ? ret : copied;
1479ac27a0ecSDave Kleikamp }
1480d2a17637SMingming Cao 
14819d0be502STheodore Ts'o /*
1482c27e43a1SEric Whitney  * Reserve space for a single cluster
14839d0be502STheodore Ts'o  */
1484c27e43a1SEric Whitney static int ext4_da_reserve_space(struct inode *inode)
1485d2a17637SMingming Cao {
1486d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
14870637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
14885dd4056dSChristoph Hellwig 	int ret;
1489d2a17637SMingming Cao 
149060e58e0fSMingming Cao 	/*
149172b8ab9dSEric Sandeen 	 * We will charge metadata quota at writeout time; this saves
149272b8ab9dSEric Sandeen 	 * us from metadata over-estimation, though we may go over by
149372b8ab9dSEric Sandeen 	 * a small amount in the end.  Here we just reserve for data.
149460e58e0fSMingming Cao 	 */
14957b415bf6SAditya Kali 	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
14965dd4056dSChristoph Hellwig 	if (ret)
14975dd4056dSChristoph Hellwig 		return ret;
149803179fe9STheodore Ts'o 
149903179fe9STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
150071d4f7d0STheodore Ts'o 	if (ext4_claim_free_clusters(sbi, 1, 0)) {
150103179fe9STheodore Ts'o 		spin_unlock(&ei->i_block_reservation_lock);
150203179fe9STheodore Ts'o 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1503d2a17637SMingming Cao 		return -ENOSPC;
1504d2a17637SMingming Cao 	}
15059d0be502STheodore Ts'o 	ei->i_reserved_data_blocks++;
1506c27e43a1SEric Whitney 	trace_ext4_da_reserve_space(inode);
15070637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
150839bc680aSDmitry Monakhov 
1509d2a17637SMingming Cao 	return 0;       /* success */
1510d2a17637SMingming Cao }
1511d2a17637SMingming Cao 
1512f456767dSEric Whitney void ext4_da_release_space(struct inode *inode, int to_free)
1513d2a17637SMingming Cao {
1514d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
15150637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1516d2a17637SMingming Cao 
1517cd213226SMingming Cao 	if (!to_free)
1518cd213226SMingming Cao 		return;		/* Nothing to release, exit */
1519cd213226SMingming Cao 
1520d2a17637SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1521cd213226SMingming Cao 
15225a58ec87SLi Zefan 	trace_ext4_da_release_space(inode, to_free);
15230637c6f4STheodore Ts'o 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1524cd213226SMingming Cao 		/*
15250637c6f4STheodore Ts'o 		 * if there aren't enough reserved blocks, then the
15260637c6f4STheodore Ts'o 		 * counter is messed up somewhere.  Since this
15270637c6f4STheodore Ts'o 		 * function is called from invalidate page, it's
15280637c6f4STheodore Ts'o 		 * harmless to return without any action.
1529cd213226SMingming Cao 		 */
15308de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "ext4_da_release_space: "
15310637c6f4STheodore Ts'o 			 "ino %lu, to_free %d with only %d reserved "
15321084f252STheodore Ts'o 			 "data blocks", inode->i_ino, to_free,
15330637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
15340637c6f4STheodore Ts'o 		WARN_ON(1);
15350637c6f4STheodore Ts'o 		to_free = ei->i_reserved_data_blocks;
15360637c6f4STheodore Ts'o 	}
15370637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= to_free;
15380637c6f4STheodore Ts'o 
153972b8ab9dSEric Sandeen 	/* update fs dirty data blocks counter */
154057042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1541d2a17637SMingming Cao 
1542d2a17637SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
154360e58e0fSMingming Cao 
15447b415bf6SAditya Kali 	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1545d2a17637SMingming Cao }
1546d2a17637SMingming Cao 
1547ac27a0ecSDave Kleikamp /*
154864769240SAlex Tomas  * Delayed allocation stuff
154964769240SAlex Tomas  */
155064769240SAlex Tomas 
15514e7ea81dSJan Kara struct mpage_da_data {
155215648d59SJan Kara 	/* These are input fields for ext4_do_writepages() */
15534e7ea81dSJan Kara 	struct inode *inode;
15544e7ea81dSJan Kara 	struct writeback_control *wbc;
155515648d59SJan Kara 	unsigned int can_map:1;	/* Can writepages call map blocks? */
15566b523df4SJan Kara 
155715648d59SJan Kara 	/* These are internal state of ext4_do_writepages() */
15584e7ea81dSJan Kara 	pgoff_t first_page;	/* The first page to write */
15594e7ea81dSJan Kara 	pgoff_t next_page;	/* Current page to examine */
15604e7ea81dSJan Kara 	pgoff_t last_page;	/* Last page to examine */
156164769240SAlex Tomas 	/*
15624e7ea81dSJan Kara 	 * Extent to map - this can be after first_page because that can be
15634e7ea81dSJan Kara 	 * fully mapped. We somewhat abuse m_flags to store whether the extent
15644e7ea81dSJan Kara 	 * is delalloc or unwritten.
156564769240SAlex Tomas 	 */
15664e7ea81dSJan Kara 	struct ext4_map_blocks map;
15674e7ea81dSJan Kara 	struct ext4_io_submit io_submit;	/* IO submission data */
1568dddbd6acSJan Kara 	unsigned int do_map:1;
15696b8ed620SJan Kara 	unsigned int scanned_until_end:1;
15701f1a55f0SJan Kara 	unsigned int journalled_more_data:1;
15714e7ea81dSJan Kara };
157264769240SAlex Tomas 
15734e7ea81dSJan Kara static void mpage_release_unused_pages(struct mpage_da_data *mpd,
15744e7ea81dSJan Kara 				       bool invalidate)
1575c4a0c46eSAneesh Kumar K.V {
1576fb5a5be0SMatthew Wilcox (Oracle) 	unsigned nr, i;
1577c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
1578fb5a5be0SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
1579c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1580c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
15814e7ea81dSJan Kara 
15824e7ea81dSJan Kara 	/* This is necessary when next_page == 0. */
15834e7ea81dSJan Kara 	if (mpd->first_page >= mpd->next_page)
15844e7ea81dSJan Kara 		return;
1585c4a0c46eSAneesh Kumar K.V 
15866b8ed620SJan Kara 	mpd->scanned_until_end = 0;
1587c7f5938aSCurt Wohlgemuth 	index = mpd->first_page;
1588c7f5938aSCurt Wohlgemuth 	end   = mpd->next_page - 1;
15894e7ea81dSJan Kara 	if (invalidate) {
15904e7ea81dSJan Kara 		ext4_lblk_t start, last;
159109cbfeafSKirill A. Shutemov 		start = index << (PAGE_SHIFT - inode->i_blkbits);
159209cbfeafSKirill A. Shutemov 		last = end << (PAGE_SHIFT - inode->i_blkbits);
15937f0d8e1dSEric Whitney 
15947f0d8e1dSEric Whitney 		/*
15957f0d8e1dSEric Whitney 		 * avoid racing with extent status tree scans made by
15967f0d8e1dSEric Whitney 		 * ext4_insert_delayed_block()
15977f0d8e1dSEric Whitney 		 */
15987f0d8e1dSEric Whitney 		down_write(&EXT4_I(inode)->i_data_sem);
159951865fdaSZheng Liu 		ext4_es_remove_extent(inode, start, last - start + 1);
16007f0d8e1dSEric Whitney 		up_write(&EXT4_I(inode)->i_data_sem);
16014e7ea81dSJan Kara 	}
160251865fdaSZheng Liu 
1603fb5a5be0SMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
1604c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
1605fb5a5be0SMatthew Wilcox (Oracle) 		nr = filemap_get_folios(mapping, &index, end, &fbatch);
1606fb5a5be0SMatthew Wilcox (Oracle) 		if (nr == 0)
1607c4a0c46eSAneesh Kumar K.V 			break;
1608fb5a5be0SMatthew Wilcox (Oracle) 		for (i = 0; i < nr; i++) {
1609fb5a5be0SMatthew Wilcox (Oracle) 			struct folio *folio = fbatch.folios[i];
16102b85a617SJan Kara 
1611fb5a5be0SMatthew Wilcox (Oracle) 			if (folio->index < mpd->first_page)
1612fb5a5be0SMatthew Wilcox (Oracle) 				continue;
161387b11f86SSidhartha Kumar 			if (folio_next_index(folio) - 1 > end)
1614fb5a5be0SMatthew Wilcox (Oracle) 				continue;
16157ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(!folio_test_locked(folio));
16167ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(folio_test_writeback(folio));
16174e7ea81dSJan Kara 			if (invalidate) {
16187ba13abbSMatthew Wilcox (Oracle) 				if (folio_mapped(folio))
16197ba13abbSMatthew Wilcox (Oracle) 					folio_clear_dirty_for_io(folio);
16207ba13abbSMatthew Wilcox (Oracle) 				block_invalidate_folio(folio, 0,
16217ba13abbSMatthew Wilcox (Oracle) 						folio_size(folio));
16227ba13abbSMatthew Wilcox (Oracle) 				folio_clear_uptodate(folio);
16234e7ea81dSJan Kara 			}
16247ba13abbSMatthew Wilcox (Oracle) 			folio_unlock(folio);
1625c4a0c46eSAneesh Kumar K.V 		}
1626fb5a5be0SMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
1627c4a0c46eSAneesh Kumar K.V 	}
1628c4a0c46eSAneesh Kumar K.V }
1629c4a0c46eSAneesh Kumar K.V 
1630df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
1631df22291fSAneesh Kumar K.V {
1632df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
163392b97816STheodore Ts'o 	struct super_block *sb = inode->i_sb;
1634f78ee70dSLukas Czerner 	struct ext4_inode_info *ei = EXT4_I(inode);
163592b97816STheodore Ts'o 
163692b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
16375dee5437STheodore Ts'o 	       EXT4_C2B(EXT4_SB(inode->i_sb),
1638f78ee70dSLukas Czerner 			ext4_count_free_clusters(sb)));
163992b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
164092b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1641f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
164257042651STheodore Ts'o 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
164392b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1644f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
16457b415bf6SAditya Kali 		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
164692b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Block reservation details");
164792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1648f78ee70dSLukas Czerner 		 ei->i_reserved_data_blocks);
1649df22291fSAneesh Kumar K.V 	return;
1650df22291fSAneesh Kumar K.V }
1651df22291fSAneesh Kumar K.V 
165264769240SAlex Tomas /*
16530b02f4c0SEric Whitney  * ext4_insert_delayed_block - adds a delayed block to the extents status
16540b02f4c0SEric Whitney  *                             tree, incrementing the reserved cluster/block
16550b02f4c0SEric Whitney  *                             count or making a pending reservation
16560b02f4c0SEric Whitney  *                             where needed
16570b02f4c0SEric Whitney  *
16580b02f4c0SEric Whitney  * @inode - file containing the newly added block
16590b02f4c0SEric Whitney  * @lblk - logical block to be added
16600b02f4c0SEric Whitney  *
16610b02f4c0SEric Whitney  * Returns 0 on success, negative error code on failure.
16620b02f4c0SEric Whitney  */
16630b02f4c0SEric Whitney static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
16640b02f4c0SEric Whitney {
16650b02f4c0SEric Whitney 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
16660b02f4c0SEric Whitney 	int ret;
16670b02f4c0SEric Whitney 	bool allocated = false;
16680b02f4c0SEric Whitney 
16690b02f4c0SEric Whitney 	/*
16700b02f4c0SEric Whitney 	 * If the cluster containing lblk is shared with a delayed,
16710b02f4c0SEric Whitney 	 * written, or unwritten extent in a bigalloc file system, it's
16720b02f4c0SEric Whitney 	 * already been accounted for and does not need to be reserved.
16730b02f4c0SEric Whitney 	 * A pending reservation must be made for the cluster if it's
16740b02f4c0SEric Whitney 	 * shared with a written or unwritten extent and doesn't already
16750b02f4c0SEric Whitney 	 * have one.  Written and unwritten extents can be purged from the
16760b02f4c0SEric Whitney 	 * extents status tree if the system is under memory pressure, so
16770b02f4c0SEric Whitney 	 * it's necessary to examine the extent tree if a search of the
16780b02f4c0SEric Whitney 	 * extents status tree doesn't get a match.
16790b02f4c0SEric Whitney 	 */
16800b02f4c0SEric Whitney 	if (sbi->s_cluster_ratio == 1) {
16810b02f4c0SEric Whitney 		ret = ext4_da_reserve_space(inode);
16820b02f4c0SEric Whitney 		if (ret != 0)   /* ENOSPC */
16838782b020SBaokun Li 			return ret;
16840b02f4c0SEric Whitney 	} else {   /* bigalloc */
16850b02f4c0SEric Whitney 		if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
16860b02f4c0SEric Whitney 			if (!ext4_es_scan_clu(inode,
16870b02f4c0SEric Whitney 					      &ext4_es_is_mapped, lblk)) {
16880b02f4c0SEric Whitney 				ret = ext4_clu_mapped(inode,
16890b02f4c0SEric Whitney 						      EXT4_B2C(sbi, lblk));
16900b02f4c0SEric Whitney 				if (ret < 0)
16918782b020SBaokun Li 					return ret;
16920b02f4c0SEric Whitney 				if (ret == 0) {
16930b02f4c0SEric Whitney 					ret = ext4_da_reserve_space(inode);
16940b02f4c0SEric Whitney 					if (ret != 0)   /* ENOSPC */
16950b02f4c0SEric Whitney 						return ret;
16968782b020SBaokun Li 				} else {
16978782b020SBaokun Li 					allocated = true;
16988782b020SBaokun Li 				}
16998782b020SBaokun Li 			} else {
17008782b020SBaokun Li 				allocated = true;
17018782b020SBaokun Li 			}
17028782b020SBaokun Li 		}
17038782b020SBaokun Li 	}
17048782b020SBaokun Li 
17058782b020SBaokun Li 	ext4_es_insert_delayed_block(inode, lblk, allocated);
17068782b020SBaokun Li 	return 0;
17070b02f4c0SEric Whitney }
17080b02f4c0SEric Whitney 
17090b02f4c0SEric Whitney /*
17105356f261SAditya Kali  * This function is grabs code from the very beginning of
17115356f261SAditya Kali  * ext4_map_blocks, but assumes that the caller is from delayed write
17125356f261SAditya Kali  * time. This function looks up the requested blocks and sets the
17135356f261SAditya Kali  * buffer delay bit under the protection of i_data_sem.
17145356f261SAditya Kali  */
17155356f261SAditya Kali static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
17165356f261SAditya Kali 			      struct ext4_map_blocks *map,
17175356f261SAditya Kali 			      struct buffer_head *bh)
17185356f261SAditya Kali {
1719d100eef2SZheng Liu 	struct extent_status es;
17205356f261SAditya Kali 	int retval;
17215356f261SAditya Kali 	sector_t invalid_block = ~((sector_t) 0xffff);
1722921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1723921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
1724921f266bSDmitry Monakhov 
1725921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
1726921f266bSDmitry Monakhov #endif
17275356f261SAditya Kali 
17285356f261SAditya Kali 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
17295356f261SAditya Kali 		invalid_block = ~0;
17305356f261SAditya Kali 
17315356f261SAditya Kali 	map->m_flags = 0;
173270aa1554SRitesh Harjani 	ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
17335356f261SAditya Kali 		  (unsigned long) map->m_lblk);
1734d100eef2SZheng Liu 
1735d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
1736bb5835edSTheodore Ts'o 	if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1737c6cba590SZhang Yi 		if (ext4_es_is_hole(&es))
1738d100eef2SZheng Liu 			goto add_delayed;
1739d100eef2SZheng Liu 
1740df736330SZhang Yi found:
1741d100eef2SZheng Liu 		/*
17423eda41dfSEric Whitney 		 * Delayed extent could be allocated by fallocate.
17433eda41dfSEric Whitney 		 * So we need to check it.
1744d100eef2SZheng Liu 		 */
17453eda41dfSEric Whitney 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
17463eda41dfSEric Whitney 			map_bh(bh, inode->i_sb, invalid_block);
17473eda41dfSEric Whitney 			set_buffer_new(bh);
17483eda41dfSEric Whitney 			set_buffer_delay(bh);
1749d100eef2SZheng Liu 			return 0;
1750d100eef2SZheng Liu 		}
1751d100eef2SZheng Liu 
1752d100eef2SZheng Liu 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1753d100eef2SZheng Liu 		retval = es.es_len - (iblock - es.es_lblk);
1754d100eef2SZheng Liu 		if (retval > map->m_len)
1755d100eef2SZheng Liu 			retval = map->m_len;
1756d100eef2SZheng Liu 		map->m_len = retval;
1757d100eef2SZheng Liu 		if (ext4_es_is_written(&es))
1758d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_MAPPED;
1759d100eef2SZheng Liu 		else if (ext4_es_is_unwritten(&es))
1760d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1761d100eef2SZheng Liu 		else
17621e83bc81SArnd Bergmann 			BUG();
1763d100eef2SZheng Liu 
1764921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1765921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1766921f266bSDmitry Monakhov #endif
1767d100eef2SZheng Liu 		return retval;
1768d100eef2SZheng Liu 	}
1769d100eef2SZheng Liu 
17705356f261SAditya Kali 	/*
17715356f261SAditya Kali 	 * Try to see if we can get the block without requesting a new
17725356f261SAditya Kali 	 * file system block.
17735356f261SAditya Kali 	 */
1774c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
1775cbd7584eSJan Kara 	if (ext4_has_inline_data(inode))
17769c3569b5STao Ma 		retval = 0;
17775356f261SAditya Kali 	else
1778f12fbb95SZhang Yi 		retval = ext4_map_query_blocks(NULL, inode, map);
1779c6cba590SZhang Yi 	up_read(&EXT4_I(inode)->i_data_sem);
1780f12fbb95SZhang Yi 	if (retval)
1781c6cba590SZhang Yi 		return retval;
17825356f261SAditya Kali 
17837849e9b5SZhang Yi add_delayed:
1784c6cba590SZhang Yi 	down_write(&EXT4_I(inode)->i_data_sem);
1785df736330SZhang Yi 	/*
1786df736330SZhang Yi 	 * Page fault path (ext4_page_mkwrite does not take i_rwsem)
1787df736330SZhang Yi 	 * and fallocate path (no folio lock) can race. Make sure we
1788df736330SZhang Yi 	 * lookup the extent status tree here again while i_data_sem
1789df736330SZhang Yi 	 * is held in write mode, before inserting a new da entry in
1790df736330SZhang Yi 	 * the extent status tree.
1791df736330SZhang Yi 	 */
1792df736330SZhang Yi 	if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1793df736330SZhang Yi 		if (!ext4_es_is_hole(&es)) {
1794df736330SZhang Yi 			up_write(&EXT4_I(inode)->i_data_sem);
1795df736330SZhang Yi 			goto found;
1796df736330SZhang Yi 		}
1797df736330SZhang Yi 	} else if (!ext4_has_inline_data(inode)) {
1798df736330SZhang Yi 		retval = ext4_map_query_blocks(NULL, inode, map);
1799df736330SZhang Yi 		if (retval) {
1800df736330SZhang Yi 			up_write(&EXT4_I(inode)->i_data_sem);
1801df736330SZhang Yi 			return retval;
1802df736330SZhang Yi 		}
1803df736330SZhang Yi 	}
1804df736330SZhang Yi 
18057849e9b5SZhang Yi 	retval = ext4_insert_delayed_block(inode, map->m_lblk);
1806c6cba590SZhang Yi 	up_write(&EXT4_I(inode)->i_data_sem);
18077849e9b5SZhang Yi 	if (retval)
1808c6cba590SZhang Yi 		return retval;
18097849e9b5SZhang Yi 
18107849e9b5SZhang Yi 	map_bh(bh, inode->i_sb, invalid_block);
18117849e9b5SZhang Yi 	set_buffer_new(bh);
18127849e9b5SZhang Yi 	set_buffer_delay(bh);
18135356f261SAditya Kali 	return retval;
18145356f261SAditya Kali }
18155356f261SAditya Kali 
18165356f261SAditya Kali /*
1817d91bd2c1SSeunghun Lee  * This is a special get_block_t callback which is used by
1818b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
1819b920c755STheodore Ts'o  * reserve space for a single block.
182029fa89d0SAneesh Kumar K.V  *
182129fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
182229fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
182329fa89d0SAneesh Kumar K.V  *
182429fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
182529fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
182629fa89d0SAneesh Kumar K.V  * initialized properly.
182764769240SAlex Tomas  */
18289c3569b5STao Ma int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
18292ed88685STheodore Ts'o 			   struct buffer_head *bh, int create)
183064769240SAlex Tomas {
18312ed88685STheodore Ts'o 	struct ext4_map_blocks map;
183264769240SAlex Tomas 	int ret = 0;
183364769240SAlex Tomas 
183464769240SAlex Tomas 	BUG_ON(create == 0);
18352ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
18362ed88685STheodore Ts'o 
18372ed88685STheodore Ts'o 	map.m_lblk = iblock;
18382ed88685STheodore Ts'o 	map.m_len = 1;
183964769240SAlex Tomas 
184064769240SAlex Tomas 	/*
184164769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
184264769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
184364769240SAlex Tomas 	 * the same as allocated blocks.
184464769240SAlex Tomas 	 */
18455356f261SAditya Kali 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
18465356f261SAditya Kali 	if (ret <= 0)
18472ed88685STheodore Ts'o 		return ret;
184864769240SAlex Tomas 
18492ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
1850ed8ad838SJan Kara 	ext4_update_bh_state(bh, map.m_flags);
18512ed88685STheodore Ts'o 
18522ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
18532ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
18542ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
18552ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
18562ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
18572ed88685STheodore Ts'o 		 * for partial write.
18582ed88685STheodore Ts'o 		 */
18592ed88685STheodore Ts'o 		set_buffer_new(bh);
1860c8205636STheodore Ts'o 		set_buffer_mapped(bh);
18612ed88685STheodore Ts'o 	}
18622ed88685STheodore Ts'o 	return 0;
186364769240SAlex Tomas }
186461628a3fSMingming Cao 
186533483b3bSMatthew Wilcox static void mpage_folio_done(struct mpage_da_data *mpd, struct folio *folio)
1866eaf2ca10SJan Kara {
186733483b3bSMatthew Wilcox 	mpd->first_page += folio_nr_pages(folio);
186833483b3bSMatthew Wilcox 	folio_unlock(folio);
1869eaf2ca10SJan Kara }
1870eaf2ca10SJan Kara 
187181a0d3e1SMatthew Wilcox static int mpage_submit_folio(struct mpage_da_data *mpd, struct folio *folio)
18725f1132b2SJan Kara {
187381a0d3e1SMatthew Wilcox 	size_t len;
1874a056bdaaSJan Kara 	loff_t size;
18755f1132b2SJan Kara 	int err;
18765f1132b2SJan Kara 
187781a0d3e1SMatthew Wilcox 	BUG_ON(folio->index != mpd->first_page);
187881a0d3e1SMatthew Wilcox 	folio_clear_dirty_for_io(folio);
1879a056bdaaSJan Kara 	/*
1880a056bdaaSJan Kara 	 * We have to be very careful here!  Nothing protects writeback path
1881a056bdaaSJan Kara 	 * against i_size changes and the page can be writeably mapped into
1882a056bdaaSJan Kara 	 * page tables. So an application can be growing i_size and writing
188381a0d3e1SMatthew Wilcox 	 * data through mmap while writeback runs. folio_clear_dirty_for_io()
1884a056bdaaSJan Kara 	 * write-protects our page in page tables and the page cannot get
188581a0d3e1SMatthew Wilcox 	 * written to again until we release folio lock. So only after
188681a0d3e1SMatthew Wilcox 	 * folio_clear_dirty_for_io() we are safe to sample i_size for
1887e8d6062cSMatthew Wilcox 	 * ext4_bio_write_folio() to zero-out tail of the written page. We rely
1888e8d6062cSMatthew Wilcox 	 * on the barrier provided by folio_test_clear_dirty() in
188981a0d3e1SMatthew Wilcox 	 * folio_clear_dirty_for_io() to make sure i_size is really sampled only
1890a056bdaaSJan Kara 	 * after page tables are updated.
1891a056bdaaSJan Kara 	 */
1892a056bdaaSJan Kara 	size = i_size_read(mpd->inode);
189381a0d3e1SMatthew Wilcox 	len = folio_size(folio);
189481a0d3e1SMatthew Wilcox 	if (folio_pos(folio) + len > size &&
1895c93d8f88SEric Biggers 	    !ext4_verity_in_progress(mpd->inode))
189609cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
1897e8d6062cSMatthew Wilcox 	err = ext4_bio_write_folio(&mpd->io_submit, folio, len);
18985f1132b2SJan Kara 	if (!err)
18995f1132b2SJan Kara 		mpd->wbc->nr_to_write--;
19005f1132b2SJan Kara 
19015f1132b2SJan Kara 	return err;
19025f1132b2SJan Kara }
19035f1132b2SJan Kara 
19046db07461SRitesh Harjani #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
19054e7ea81dSJan Kara 
190661628a3fSMingming Cao /*
1907fffb2739SJan Kara  * mballoc gives us at most this number of blocks...
1908fffb2739SJan Kara  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1909fffb2739SJan Kara  * The rest of mballoc seems to handle chunks up to full group size.
191061628a3fSMingming Cao  */
1911fffb2739SJan Kara #define MAX_WRITEPAGES_EXTENT_LEN 2048
1912525f4ed8SMingming Cao 
1913525f4ed8SMingming Cao /*
19144e7ea81dSJan Kara  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
19154e7ea81dSJan Kara  *
19164e7ea81dSJan Kara  * @mpd - extent of blocks
19174e7ea81dSJan Kara  * @lblk - logical number of the block in the file
191809930042SJan Kara  * @bh - buffer head we want to add to the extent
19194e7ea81dSJan Kara  *
192009930042SJan Kara  * The function is used to collect contig. blocks in the same state. If the
192109930042SJan Kara  * buffer doesn't require mapping for writeback and we haven't started the
192209930042SJan Kara  * extent of buffers to map yet, the function returns 'true' immediately - the
192309930042SJan Kara  * caller can write the buffer right away. Otherwise the function returns true
192409930042SJan Kara  * if the block has been added to the extent, false if the block couldn't be
192509930042SJan Kara  * added.
19264e7ea81dSJan Kara  */
192709930042SJan Kara static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
192809930042SJan Kara 				   struct buffer_head *bh)
19294e7ea81dSJan Kara {
19304e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
19314e7ea81dSJan Kara 
193209930042SJan Kara 	/* Buffer that doesn't need mapping for writeback? */
193309930042SJan Kara 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
193409930042SJan Kara 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
193509930042SJan Kara 		/* So far no extent to map => we write the buffer right away */
193609930042SJan Kara 		if (map->m_len == 0)
193709930042SJan Kara 			return true;
193809930042SJan Kara 		return false;
193909930042SJan Kara 	}
19404e7ea81dSJan Kara 
19414e7ea81dSJan Kara 	/* First block in the extent? */
19424e7ea81dSJan Kara 	if (map->m_len == 0) {
1943dddbd6acSJan Kara 		/* We cannot map unless handle is started... */
1944dddbd6acSJan Kara 		if (!mpd->do_map)
1945dddbd6acSJan Kara 			return false;
19464e7ea81dSJan Kara 		map->m_lblk = lblk;
19474e7ea81dSJan Kara 		map->m_len = 1;
194809930042SJan Kara 		map->m_flags = bh->b_state & BH_FLAGS;
194909930042SJan Kara 		return true;
19504e7ea81dSJan Kara 	}
19514e7ea81dSJan Kara 
195209930042SJan Kara 	/* Don't go larger than mballoc is willing to allocate */
195309930042SJan Kara 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
195409930042SJan Kara 		return false;
195509930042SJan Kara 
19564e7ea81dSJan Kara 	/* Can we merge the block to our big extent? */
19574e7ea81dSJan Kara 	if (lblk == map->m_lblk + map->m_len &&
195809930042SJan Kara 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
19594e7ea81dSJan Kara 		map->m_len++;
196009930042SJan Kara 		return true;
19614e7ea81dSJan Kara 	}
196209930042SJan Kara 	return false;
19634e7ea81dSJan Kara }
19644e7ea81dSJan Kara 
19655f1132b2SJan Kara /*
19665f1132b2SJan Kara  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
19675f1132b2SJan Kara  *
19685f1132b2SJan Kara  * @mpd - extent of blocks for mapping
19695f1132b2SJan Kara  * @head - the first buffer in the page
19705f1132b2SJan Kara  * @bh - buffer we should start processing from
19715f1132b2SJan Kara  * @lblk - logical number of the block in the file corresponding to @bh
19725f1132b2SJan Kara  *
19735f1132b2SJan Kara  * Walk through page buffers from @bh upto @head (exclusive) and either submit
19745f1132b2SJan Kara  * the page for IO if all buffers in this page were mapped and there's no
19755f1132b2SJan Kara  * accumulated extent of buffers to map or add buffers in the page to the
19765f1132b2SJan Kara  * extent of buffers to map. The function returns 1 if the caller can continue
19775f1132b2SJan Kara  * by processing the next page, 0 if it should stop adding buffers to the
19785f1132b2SJan Kara  * extent to map because we cannot extend it anymore. It can also return value
19795f1132b2SJan Kara  * < 0 in case of error during IO submission.
19805f1132b2SJan Kara  */
19815f1132b2SJan Kara static int mpage_process_page_bufs(struct mpage_da_data *mpd,
19824e7ea81dSJan Kara 				   struct buffer_head *head,
19834e7ea81dSJan Kara 				   struct buffer_head *bh,
19844e7ea81dSJan Kara 				   ext4_lblk_t lblk)
19854e7ea81dSJan Kara {
19864e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
19875f1132b2SJan Kara 	int err;
198893407472SFabian Frederick 	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
19894e7ea81dSJan Kara 							>> inode->i_blkbits;
19904e7ea81dSJan Kara 
1991c93d8f88SEric Biggers 	if (ext4_verity_in_progress(inode))
1992c93d8f88SEric Biggers 		blocks = EXT_MAX_BLOCKS;
1993c93d8f88SEric Biggers 
19944e7ea81dSJan Kara 	do {
19954e7ea81dSJan Kara 		BUG_ON(buffer_locked(bh));
19964e7ea81dSJan Kara 
199709930042SJan Kara 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
19984e7ea81dSJan Kara 			/* Found extent to map? */
19994e7ea81dSJan Kara 			if (mpd->map.m_len)
20005f1132b2SJan Kara 				return 0;
2001dddbd6acSJan Kara 			/* Buffer needs mapping and handle is not started? */
2002dddbd6acSJan Kara 			if (!mpd->do_map)
2003dddbd6acSJan Kara 				return 0;
200409930042SJan Kara 			/* Everything mapped so far and we hit EOF */
20055f1132b2SJan Kara 			break;
20064e7ea81dSJan Kara 		}
20074e7ea81dSJan Kara 	} while (lblk++, (bh = bh->b_this_page) != head);
20085f1132b2SJan Kara 	/* So far everything mapped? Submit the page for IO. */
20095f1132b2SJan Kara 	if (mpd->map.m_len == 0) {
201081a0d3e1SMatthew Wilcox 		err = mpage_submit_folio(mpd, head->b_folio);
20115f1132b2SJan Kara 		if (err < 0)
20124e7ea81dSJan Kara 			return err;
201333483b3bSMatthew Wilcox 		mpage_folio_done(mpd, head->b_folio);
20144e7ea81dSJan Kara 	}
20156b8ed620SJan Kara 	if (lblk >= blocks) {
20166b8ed620SJan Kara 		mpd->scanned_until_end = 1;
20176b8ed620SJan Kara 		return 0;
20186b8ed620SJan Kara 	}
20196b8ed620SJan Kara 	return 1;
20205f1132b2SJan Kara }
20214e7ea81dSJan Kara 
20224e7ea81dSJan Kara /*
20234da2f6e3SMatthew Wilcox  * mpage_process_folio - update folio buffers corresponding to changed extent
20244da2f6e3SMatthew Wilcox  *			 and may submit fully mapped page for IO
20254da2f6e3SMatthew Wilcox  * @mpd: description of extent to map, on return next extent to map
20264da2f6e3SMatthew Wilcox  * @folio: Contains these buffers.
20274da2f6e3SMatthew Wilcox  * @m_lblk: logical block mapping.
20284da2f6e3SMatthew Wilcox  * @m_pblk: corresponding physical mapping.
20294da2f6e3SMatthew Wilcox  * @map_bh: determines on return whether this page requires any further
20302943fdbcSRitesh Harjani  *		  mapping or not.
20314da2f6e3SMatthew Wilcox  *
20324da2f6e3SMatthew Wilcox  * Scan given folio buffers corresponding to changed extent and update buffer
20332943fdbcSRitesh Harjani  * state according to new extent state.
20342943fdbcSRitesh Harjani  * We map delalloc buffers to their physical location, clear unwritten bits.
20354da2f6e3SMatthew Wilcox  * If the given folio is not fully mapped, we update @mpd to the next extent in
20364da2f6e3SMatthew Wilcox  * the given folio that needs mapping & return @map_bh as true.
20372943fdbcSRitesh Harjani  */
20384da2f6e3SMatthew Wilcox static int mpage_process_folio(struct mpage_da_data *mpd, struct folio *folio,
20392943fdbcSRitesh Harjani 			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
20402943fdbcSRitesh Harjani 			      bool *map_bh)
20412943fdbcSRitesh Harjani {
20422943fdbcSRitesh Harjani 	struct buffer_head *head, *bh;
20432943fdbcSRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
20442943fdbcSRitesh Harjani 	ext4_lblk_t lblk = *m_lblk;
20452943fdbcSRitesh Harjani 	ext4_fsblk_t pblock = *m_pblk;
20462943fdbcSRitesh Harjani 	int err = 0;
2047c8cc8816SRitesh Harjani 	int blkbits = mpd->inode->i_blkbits;
2048c8cc8816SRitesh Harjani 	ssize_t io_end_size = 0;
2049c8cc8816SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
20502943fdbcSRitesh Harjani 
20514da2f6e3SMatthew Wilcox 	bh = head = folio_buffers(folio);
20522943fdbcSRitesh Harjani 	do {
20532943fdbcSRitesh Harjani 		if (lblk < mpd->map.m_lblk)
20542943fdbcSRitesh Harjani 			continue;
20552943fdbcSRitesh Harjani 		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
20562943fdbcSRitesh Harjani 			/*
20572943fdbcSRitesh Harjani 			 * Buffer after end of mapped extent.
20584da2f6e3SMatthew Wilcox 			 * Find next buffer in the folio to map.
20592943fdbcSRitesh Harjani 			 */
20602943fdbcSRitesh Harjani 			mpd->map.m_len = 0;
20612943fdbcSRitesh Harjani 			mpd->map.m_flags = 0;
2062c8cc8816SRitesh Harjani 			io_end_vec->size += io_end_size;
20632943fdbcSRitesh Harjani 
20642943fdbcSRitesh Harjani 			err = mpage_process_page_bufs(mpd, head, bh, lblk);
20652943fdbcSRitesh Harjani 			if (err > 0)
20662943fdbcSRitesh Harjani 				err = 0;
2067c8cc8816SRitesh Harjani 			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2068c8cc8816SRitesh Harjani 				io_end_vec = ext4_alloc_io_end_vec(io_end);
20694d06bfb9SRitesh Harjani 				if (IS_ERR(io_end_vec)) {
20704d06bfb9SRitesh Harjani 					err = PTR_ERR(io_end_vec);
20714d06bfb9SRitesh Harjani 					goto out;
20724d06bfb9SRitesh Harjani 				}
2073d1e18b88SRitesh Harjani 				io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2074c8cc8816SRitesh Harjani 			}
20752943fdbcSRitesh Harjani 			*map_bh = true;
20762943fdbcSRitesh Harjani 			goto out;
20772943fdbcSRitesh Harjani 		}
20782943fdbcSRitesh Harjani 		if (buffer_delay(bh)) {
20792943fdbcSRitesh Harjani 			clear_buffer_delay(bh);
20802943fdbcSRitesh Harjani 			bh->b_blocknr = pblock++;
20812943fdbcSRitesh Harjani 		}
20822943fdbcSRitesh Harjani 		clear_buffer_unwritten(bh);
2083c8cc8816SRitesh Harjani 		io_end_size += (1 << blkbits);
20842943fdbcSRitesh Harjani 	} while (lblk++, (bh = bh->b_this_page) != head);
2085c8cc8816SRitesh Harjani 
2086c8cc8816SRitesh Harjani 	io_end_vec->size += io_end_size;
20872943fdbcSRitesh Harjani 	*map_bh = false;
20882943fdbcSRitesh Harjani out:
20892943fdbcSRitesh Harjani 	*m_lblk = lblk;
20902943fdbcSRitesh Harjani 	*m_pblk = pblock;
20912943fdbcSRitesh Harjani 	return err;
20922943fdbcSRitesh Harjani }
20932943fdbcSRitesh Harjani 
20942943fdbcSRitesh Harjani /*
20954e7ea81dSJan Kara  * mpage_map_buffers - update buffers corresponding to changed extent and
20964e7ea81dSJan Kara  *		       submit fully mapped pages for IO
20974e7ea81dSJan Kara  *
20984e7ea81dSJan Kara  * @mpd - description of extent to map, on return next extent to map
20994e7ea81dSJan Kara  *
21004e7ea81dSJan Kara  * Scan buffers corresponding to changed extent (we expect corresponding pages
21014e7ea81dSJan Kara  * to be already locked) and update buffer state according to new extent state.
21024e7ea81dSJan Kara  * We map delalloc buffers to their physical location, clear unwritten bits,
2103556615dcSLukas Czerner  * and mark buffers as uninit when we perform writes to unwritten extents
21044e7ea81dSJan Kara  * and do extent conversion after IO is finished. If the last page is not fully
21054e7ea81dSJan Kara  * mapped, we update @map to the next extent in the last page that needs
21064e7ea81dSJan Kara  * mapping. Otherwise we submit the page for IO.
21074e7ea81dSJan Kara  */
21084e7ea81dSJan Kara static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
21094e7ea81dSJan Kara {
21107530d093SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
21117530d093SMatthew Wilcox (Oracle) 	unsigned nr, i;
21124e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
211309cbfeafSKirill A. Shutemov 	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
21144e7ea81dSJan Kara 	pgoff_t start, end;
21154e7ea81dSJan Kara 	ext4_lblk_t lblk;
21162943fdbcSRitesh Harjani 	ext4_fsblk_t pblock;
21174e7ea81dSJan Kara 	int err;
21182943fdbcSRitesh Harjani 	bool map_bh = false;
21194e7ea81dSJan Kara 
21204e7ea81dSJan Kara 	start = mpd->map.m_lblk >> bpp_bits;
21214e7ea81dSJan Kara 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
21224e7ea81dSJan Kara 	lblk = start << bpp_bits;
21234e7ea81dSJan Kara 	pblock = mpd->map.m_pblk;
21244e7ea81dSJan Kara 
21257530d093SMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
21264e7ea81dSJan Kara 	while (start <= end) {
21277530d093SMatthew Wilcox (Oracle) 		nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
21287530d093SMatthew Wilcox (Oracle) 		if (nr == 0)
21294e7ea81dSJan Kara 			break;
21307530d093SMatthew Wilcox (Oracle) 		for (i = 0; i < nr; i++) {
21314da2f6e3SMatthew Wilcox 			struct folio *folio = fbatch.folios[i];
21324e7ea81dSJan Kara 
21334da2f6e3SMatthew Wilcox 			err = mpage_process_folio(mpd, folio, &lblk, &pblock,
21342943fdbcSRitesh Harjani 						 &map_bh);
21354e7ea81dSJan Kara 			/*
21362943fdbcSRitesh Harjani 			 * If map_bh is true, means page may require further bh
21372943fdbcSRitesh Harjani 			 * mapping, or maybe the page was submitted for IO.
21382943fdbcSRitesh Harjani 			 * So we return to call further extent mapping.
21394e7ea81dSJan Kara 			 */
214039c0ae16SJason Yan 			if (err < 0 || map_bh)
21412943fdbcSRitesh Harjani 				goto out;
21424e7ea81dSJan Kara 			/* Page fully mapped - let IO run! */
214381a0d3e1SMatthew Wilcox 			err = mpage_submit_folio(mpd, folio);
21442943fdbcSRitesh Harjani 			if (err < 0)
21452943fdbcSRitesh Harjani 				goto out;
214633483b3bSMatthew Wilcox 			mpage_folio_done(mpd, folio);
21474e7ea81dSJan Kara 		}
21487530d093SMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
21494e7ea81dSJan Kara 	}
21504e7ea81dSJan Kara 	/* Extent fully mapped and matches with page boundary. We are done. */
21514e7ea81dSJan Kara 	mpd->map.m_len = 0;
21524e7ea81dSJan Kara 	mpd->map.m_flags = 0;
21534e7ea81dSJan Kara 	return 0;
21542943fdbcSRitesh Harjani out:
21557530d093SMatthew Wilcox (Oracle) 	folio_batch_release(&fbatch);
21562943fdbcSRitesh Harjani 	return err;
21574e7ea81dSJan Kara }
21584e7ea81dSJan Kara 
21594e7ea81dSJan Kara static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
21604e7ea81dSJan Kara {
21614e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
21624e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
21634e7ea81dSJan Kara 	int get_blocks_flags;
2164090f32eeSLukas Czerner 	int err, dioread_nolock;
21654e7ea81dSJan Kara 
21664e7ea81dSJan Kara 	trace_ext4_da_write_pages_extent(inode, map);
21674e7ea81dSJan Kara 	/*
21684e7ea81dSJan Kara 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2169556615dcSLukas Czerner 	 * to convert an unwritten extent to be initialized (in the case
21704e7ea81dSJan Kara 	 * where we have written into one or more preallocated blocks).  It is
21714e7ea81dSJan Kara 	 * possible that we're going to need more metadata blocks than
21724e7ea81dSJan Kara 	 * previously reserved. However we must not fail because we're in
21734e7ea81dSJan Kara 	 * writeback and there is nothing we can do about it so it might result
21744e7ea81dSJan Kara 	 * in data loss.  So use reserved blocks to allocate metadata if
21754e7ea81dSJan Kara 	 * possible.
21764e7ea81dSJan Kara 	 *
2177754cfed6STheodore Ts'o 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2178754cfed6STheodore Ts'o 	 * the blocks in question are delalloc blocks.  This indicates
2179754cfed6STheodore Ts'o 	 * that the blocks and quotas has already been checked when
2180754cfed6STheodore Ts'o 	 * the data was copied into the page cache.
21814e7ea81dSJan Kara 	 */
21824e7ea81dSJan Kara 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2183ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2184ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_IO_SUBMIT;
2185090f32eeSLukas Czerner 	dioread_nolock = ext4_should_dioread_nolock(inode);
2186090f32eeSLukas Czerner 	if (dioread_nolock)
21874e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
21886db07461SRitesh Harjani 	if (map->m_flags & BIT(BH_Delay))
21894e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
21904e7ea81dSJan Kara 
21914e7ea81dSJan Kara 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
21924e7ea81dSJan Kara 	if (err < 0)
21934e7ea81dSJan Kara 		return err;
2194090f32eeSLukas Czerner 	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
21956b523df4SJan Kara 		if (!mpd->io_submit.io_end->handle &&
21966b523df4SJan Kara 		    ext4_handle_valid(handle)) {
21976b523df4SJan Kara 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
21986b523df4SJan Kara 			handle->h_rsv_handle = NULL;
21996b523df4SJan Kara 		}
22003613d228SJan Kara 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
22016b523df4SJan Kara 	}
22024e7ea81dSJan Kara 
22034e7ea81dSJan Kara 	BUG_ON(map->m_len == 0);
22044e7ea81dSJan Kara 	return 0;
22054e7ea81dSJan Kara }
22064e7ea81dSJan Kara 
22074e7ea81dSJan Kara /*
22084e7ea81dSJan Kara  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
22094e7ea81dSJan Kara  *				 mpd->len and submit pages underlying it for IO
22104e7ea81dSJan Kara  *
22114e7ea81dSJan Kara  * @handle - handle for journal operations
22124e7ea81dSJan Kara  * @mpd - extent to map
22137534e854SJan Kara  * @give_up_on_write - we set this to true iff there is a fatal error and there
22147534e854SJan Kara  *                     is no hope of writing the data. The caller should discard
22157534e854SJan Kara  *                     dirty pages to avoid infinite loops.
22164e7ea81dSJan Kara  *
22174e7ea81dSJan Kara  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
22184e7ea81dSJan Kara  * delayed, blocks are allocated, if it is unwritten, we may need to convert
22194e7ea81dSJan Kara  * them to initialized or split the described range from larger unwritten
22204e7ea81dSJan Kara  * extent. Note that we need not map all the described range since allocation
22214e7ea81dSJan Kara  * can return less blocks or the range is covered by more unwritten extents. We
22224e7ea81dSJan Kara  * cannot map more because we are limited by reserved transaction credits. On
22234e7ea81dSJan Kara  * the other hand we always make sure that the last touched page is fully
22244e7ea81dSJan Kara  * mapped so that it can be written out (and thus forward progress is
22254e7ea81dSJan Kara  * guaranteed). After mapping we submit all mapped pages for IO.
22264e7ea81dSJan Kara  */
22274e7ea81dSJan Kara static int mpage_map_and_submit_extent(handle_t *handle,
2228cb530541STheodore Ts'o 				       struct mpage_da_data *mpd,
2229cb530541STheodore Ts'o 				       bool *give_up_on_write)
22304e7ea81dSJan Kara {
22314e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
22324e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
22334e7ea81dSJan Kara 	int err;
22344e7ea81dSJan Kara 	loff_t disksize;
22356603120eSDmitry Monakhov 	int progress = 0;
2236c8cc8816SRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
22374d06bfb9SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec;
22384e7ea81dSJan Kara 
22394d06bfb9SRitesh Harjani 	io_end_vec = ext4_alloc_io_end_vec(io_end);
22404d06bfb9SRitesh Harjani 	if (IS_ERR(io_end_vec))
22414d06bfb9SRitesh Harjani 		return PTR_ERR(io_end_vec);
2242c8cc8816SRitesh Harjani 	io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
224327d7c4edSJan Kara 	do {
22444e7ea81dSJan Kara 		err = mpage_map_one_extent(handle, mpd);
22454e7ea81dSJan Kara 		if (err < 0) {
22464e7ea81dSJan Kara 			struct super_block *sb = inode->i_sb;
22474e7ea81dSJan Kara 
224895257987SJan Kara 			if (ext4_forced_shutdown(sb))
2249cb530541STheodore Ts'o 				goto invalidate_dirty_pages;
22504e7ea81dSJan Kara 			/*
2251cb530541STheodore Ts'o 			 * Let the uper layers retry transient errors.
2252cb530541STheodore Ts'o 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2253cb530541STheodore Ts'o 			 * is non-zero, a commit should free up blocks.
22544e7ea81dSJan Kara 			 */
2255cb530541STheodore Ts'o 			if ((err == -ENOMEM) ||
22566603120eSDmitry Monakhov 			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
22576603120eSDmitry Monakhov 				if (progress)
22586603120eSDmitry Monakhov 					goto update_disksize;
2259cb530541STheodore Ts'o 				return err;
22606603120eSDmitry Monakhov 			}
22614e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
22624e7ea81dSJan Kara 				 "Delayed block allocation failed for "
22634e7ea81dSJan Kara 				 "inode %lu at logical offset %llu with"
22644e7ea81dSJan Kara 				 " max blocks %u with error %d",
22654e7ea81dSJan Kara 				 inode->i_ino,
22664e7ea81dSJan Kara 				 (unsigned long long)map->m_lblk,
2267cb530541STheodore Ts'o 				 (unsigned)map->m_len, -err);
22684e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
22694e7ea81dSJan Kara 				 "This should not happen!! Data will "
22704e7ea81dSJan Kara 				 "be lost\n");
22714e7ea81dSJan Kara 			if (err == -ENOSPC)
22724e7ea81dSJan Kara 				ext4_print_free_blocks(inode);
2273cb530541STheodore Ts'o 		invalidate_dirty_pages:
2274cb530541STheodore Ts'o 			*give_up_on_write = true;
22754e7ea81dSJan Kara 			return err;
22764e7ea81dSJan Kara 		}
22776603120eSDmitry Monakhov 		progress = 1;
22784e7ea81dSJan Kara 		/*
22794e7ea81dSJan Kara 		 * Update buffer state, submit mapped pages, and get us new
22804e7ea81dSJan Kara 		 * extent to map
22814e7ea81dSJan Kara 		 */
22824e7ea81dSJan Kara 		err = mpage_map_and_submit_buffers(mpd);
22834e7ea81dSJan Kara 		if (err < 0)
22846603120eSDmitry Monakhov 			goto update_disksize;
228527d7c4edSJan Kara 	} while (map->m_len);
22864e7ea81dSJan Kara 
22876603120eSDmitry Monakhov update_disksize:
2288622cad13STheodore Ts'o 	/*
2289622cad13STheodore Ts'o 	 * Update on-disk size after IO is submitted.  Races with
2290622cad13STheodore Ts'o 	 * truncate are avoided by checking i_size under i_data_sem.
2291622cad13STheodore Ts'o 	 */
229209cbfeafSKirill A. Shutemov 	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
229335df4299SQian Cai 	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
22944e7ea81dSJan Kara 		int err2;
2295622cad13STheodore Ts'o 		loff_t i_size;
22964e7ea81dSJan Kara 
2297622cad13STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
2298622cad13STheodore Ts'o 		i_size = i_size_read(inode);
2299622cad13STheodore Ts'o 		if (disksize > i_size)
2300622cad13STheodore Ts'o 			disksize = i_size;
2301622cad13STheodore Ts'o 		if (disksize > EXT4_I(inode)->i_disksize)
2302622cad13STheodore Ts'o 			EXT4_I(inode)->i_disksize = disksize;
2303622cad13STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
2304b907f2d5STheodore Ts'o 		err2 = ext4_mark_inode_dirty(handle, inode);
2305878520acSTheodore Ts'o 		if (err2) {
230654d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err2,
23074e7ea81dSJan Kara 				       "Failed to mark inode %lu dirty",
23084e7ea81dSJan Kara 				       inode->i_ino);
2309878520acSTheodore Ts'o 		}
23104e7ea81dSJan Kara 		if (!err)
23114e7ea81dSJan Kara 			err = err2;
23124e7ea81dSJan Kara 	}
23134e7ea81dSJan Kara 	return err;
23144e7ea81dSJan Kara }
23154e7ea81dSJan Kara 
23164e7ea81dSJan Kara /*
2317fffb2739SJan Kara  * Calculate the total number of credits to reserve for one writepages
231820970ba6STheodore Ts'o  * iteration. This is called from ext4_writepages(). We map an extent of
2319fffb2739SJan Kara  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2320fffb2739SJan Kara  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2321fffb2739SJan Kara  * bpp - 1 blocks in bpp different extents.
2322525f4ed8SMingming Cao  */
2323fffb2739SJan Kara static int ext4_da_writepages_trans_blocks(struct inode *inode)
2324fffb2739SJan Kara {
2325fffb2739SJan Kara 	int bpp = ext4_journal_blocks_per_page(inode);
2326525f4ed8SMingming Cao 
2327fffb2739SJan Kara 	return ext4_meta_trans_blocks(inode,
2328fffb2739SJan Kara 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2329525f4ed8SMingming Cao }
233061628a3fSMingming Cao 
233180be8c5cSRitesh Harjani static int ext4_journal_folio_buffers(handle_t *handle, struct folio *folio,
233280be8c5cSRitesh Harjani 				     size_t len)
23333f079114SJan Kara {
233480be8c5cSRitesh Harjani 	struct buffer_head *page_bufs = folio_buffers(folio);
233580be8c5cSRitesh Harjani 	struct inode *inode = folio->mapping->host;
23363f079114SJan Kara 	int ret, err;
23373f079114SJan Kara 
23383f079114SJan Kara 	ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
23393f079114SJan Kara 				     NULL, do_journal_get_write_access);
23403f079114SJan Kara 	err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
23413f079114SJan Kara 				     NULL, write_end_fn);
23423f079114SJan Kara 	if (ret == 0)
23433f079114SJan Kara 		ret = err;
234480be8c5cSRitesh Harjani 	err = ext4_jbd2_inode_add_write(handle, inode, folio_pos(folio), len);
23453f079114SJan Kara 	if (ret == 0)
23463f079114SJan Kara 		ret = err;
23473f079114SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
23483f079114SJan Kara 
23493f079114SJan Kara 	return ret;
23503f079114SJan Kara }
23513f079114SJan Kara 
23523f079114SJan Kara static int mpage_journal_page_buffers(handle_t *handle,
23533f079114SJan Kara 				      struct mpage_da_data *mpd,
235480be8c5cSRitesh Harjani 				      struct folio *folio)
23553f079114SJan Kara {
23563f079114SJan Kara 	struct inode *inode = mpd->inode;
23573f079114SJan Kara 	loff_t size = i_size_read(inode);
235880be8c5cSRitesh Harjani 	size_t len = folio_size(folio);
23593f079114SJan Kara 
236080be8c5cSRitesh Harjani 	folio_clear_checked(folio);
23613f079114SJan Kara 	mpd->wbc->nr_to_write--;
23623f079114SJan Kara 
236380be8c5cSRitesh Harjani 	if (folio_pos(folio) + len > size &&
23643f079114SJan Kara 	    !ext4_verity_in_progress(inode))
23653093e586SRitesh Harjani (IBM) 		len = size & (len - 1);
23663f079114SJan Kara 
236780be8c5cSRitesh Harjani 	return ext4_journal_folio_buffers(handle, folio, len);
23683f079114SJan Kara }
23693f079114SJan Kara 
23708e48dcfbSTheodore Ts'o /*
23714e7ea81dSJan Kara  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2372de0039f6SJan Kara  * 				 needing mapping, submit mapped pages
23734e7ea81dSJan Kara  *
23744e7ea81dSJan Kara  * @mpd - where to look for pages
23754e7ea81dSJan Kara  *
23764e7ea81dSJan Kara  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2377de0039f6SJan Kara  * IO immediately. If we cannot map blocks, we submit just already mapped
2378de0039f6SJan Kara  * buffers in the page for IO and keep page dirty. When we can map blocks and
2379de0039f6SJan Kara  * we find a page which isn't mapped we start accumulating extent of buffers
2380de0039f6SJan Kara  * underlying these pages that needs mapping (formed by either delayed or
2381de0039f6SJan Kara  * unwritten buffers). We also lock the pages containing these buffers. The
2382de0039f6SJan Kara  * extent found is returned in @mpd structure (starting at mpd->lblk with
2383de0039f6SJan Kara  * length mpd->len blocks).
23844e7ea81dSJan Kara  *
23854e7ea81dSJan Kara  * Note that this function can attach bios to one io_end structure which are
23864e7ea81dSJan Kara  * neither logically nor physically contiguous. Although it may seem as an
23874e7ea81dSJan Kara  * unnecessary complication, it is actually inevitable in blocksize < pagesize
23884e7ea81dSJan Kara  * case as we need to track IO to all buffers underlying a page in one io_end.
23898e48dcfbSTheodore Ts'o  */
23904e7ea81dSJan Kara static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
23918e48dcfbSTheodore Ts'o {
23924e7ea81dSJan Kara 	struct address_space *mapping = mpd->inode->i_mapping;
239350ead253SVishal Moola (Oracle) 	struct folio_batch fbatch;
239450ead253SVishal Moola (Oracle) 	unsigned int nr_folios;
23954e7ea81dSJan Kara 	pgoff_t index = mpd->first_page;
23964e7ea81dSJan Kara 	pgoff_t end = mpd->last_page;
239710bbd235SMatthew Wilcox 	xa_mark_t tag;
23984e7ea81dSJan Kara 	int i, err = 0;
23994e7ea81dSJan Kara 	int blkbits = mpd->inode->i_blkbits;
24004e7ea81dSJan Kara 	ext4_lblk_t lblk;
24014e7ea81dSJan Kara 	struct buffer_head *head;
24023f079114SJan Kara 	handle_t *handle = NULL;
24033f079114SJan Kara 	int bpp = ext4_journal_blocks_per_page(mpd->inode);
24048e48dcfbSTheodore Ts'o 
24054e7ea81dSJan Kara 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
24065b41d924SEric Sandeen 		tag = PAGECACHE_TAG_TOWRITE;
24075b41d924SEric Sandeen 	else
24085b41d924SEric Sandeen 		tag = PAGECACHE_TAG_DIRTY;
24093f079114SJan Kara 
2410e6c28a26SJan Kara 	mpd->map.m_len = 0;
2411e6c28a26SJan Kara 	mpd->next_page = index;
2412d0ab8368SJan Kara 	if (ext4_should_journal_data(mpd->inode)) {
24133f079114SJan Kara 		handle = ext4_journal_start(mpd->inode, EXT4_HT_WRITE_PAGE,
24143f079114SJan Kara 					    bpp);
24153f079114SJan Kara 		if (IS_ERR(handle))
24163f079114SJan Kara 			return PTR_ERR(handle);
24173f079114SJan Kara 	}
241850ead253SVishal Moola (Oracle) 	folio_batch_init(&fbatch);
24194f01b02cSTheodore Ts'o 	while (index <= end) {
242050ead253SVishal Moola (Oracle) 		nr_folios = filemap_get_folios_tag(mapping, &index, end,
242150ead253SVishal Moola (Oracle) 				tag, &fbatch);
242250ead253SVishal Moola (Oracle) 		if (nr_folios == 0)
24236b8ed620SJan Kara 			break;
24248e48dcfbSTheodore Ts'o 
242550ead253SVishal Moola (Oracle) 		for (i = 0; i < nr_folios; i++) {
242650ead253SVishal Moola (Oracle) 			struct folio *folio = fbatch.folios[i];
24278e48dcfbSTheodore Ts'o 
24288e48dcfbSTheodore Ts'o 			/*
2429aeac589aSMing Lei 			 * Accumulated enough dirty pages? This doesn't apply
2430aeac589aSMing Lei 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2431aeac589aSMing Lei 			 * keep going because someone may be concurrently
2432aeac589aSMing Lei 			 * dirtying pages, and we might have synced a lot of
2433aeac589aSMing Lei 			 * newly appeared dirty pages, but have not synced all
2434aeac589aSMing Lei 			 * of the old dirty pages.
2435aeac589aSMing Lei 			 */
2436c8e8e16dSJan Kara 			if (mpd->wbc->sync_mode == WB_SYNC_NONE &&
2437c8e8e16dSJan Kara 			    mpd->wbc->nr_to_write <=
2438c8e8e16dSJan Kara 			    mpd->map.m_len >> (PAGE_SHIFT - blkbits))
2439aeac589aSMing Lei 				goto out;
2440aeac589aSMing Lei 
24414e7ea81dSJan Kara 			/* If we can't merge this page, we are done. */
244250ead253SVishal Moola (Oracle) 			if (mpd->map.m_len > 0 && mpd->next_page != folio->index)
24434e7ea81dSJan Kara 				goto out;
244478aaced3STheodore Ts'o 
24453f079114SJan Kara 			if (handle) {
24463f079114SJan Kara 				err = ext4_journal_ensure_credits(handle, bpp,
24473f079114SJan Kara 								  0);
24483f079114SJan Kara 				if (err < 0)
24493f079114SJan Kara 					goto out;
24503f079114SJan Kara 			}
24513f079114SJan Kara 
245250ead253SVishal Moola (Oracle) 			folio_lock(folio);
24538e48dcfbSTheodore Ts'o 			/*
24544e7ea81dSJan Kara 			 * If the page is no longer dirty, or its mapping no
24554e7ea81dSJan Kara 			 * longer corresponds to inode we are writing (which
24564e7ea81dSJan Kara 			 * means it has been truncated or invalidated), or the
24574e7ea81dSJan Kara 			 * page is already under writeback and we are not doing
24584e7ea81dSJan Kara 			 * a data integrity writeback, skip the page
24598e48dcfbSTheodore Ts'o 			 */
246050ead253SVishal Moola (Oracle) 			if (!folio_test_dirty(folio) ||
246150ead253SVishal Moola (Oracle) 			    (folio_test_writeback(folio) &&
24624e7ea81dSJan Kara 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
246350ead253SVishal Moola (Oracle) 			    unlikely(folio->mapping != mapping)) {
246450ead253SVishal Moola (Oracle) 				folio_unlock(folio);
24658e48dcfbSTheodore Ts'o 				continue;
24668e48dcfbSTheodore Ts'o 			}
24678e48dcfbSTheodore Ts'o 
246850ead253SVishal Moola (Oracle) 			folio_wait_writeback(folio);
246950ead253SVishal Moola (Oracle) 			BUG_ON(folio_test_writeback(folio));
24708e48dcfbSTheodore Ts'o 
2471cc509574STheodore Ts'o 			/*
2472cc509574STheodore Ts'o 			 * Should never happen but for buggy code in
2473cc509574STheodore Ts'o 			 * other subsystems that call
2474cc509574STheodore Ts'o 			 * set_page_dirty() without properly warning
2475cc509574STheodore Ts'o 			 * the file system first.  See [1] for more
2476cc509574STheodore Ts'o 			 * information.
2477cc509574STheodore Ts'o 			 *
2478cc509574STheodore Ts'o 			 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2479cc509574STheodore Ts'o 			 */
248050ead253SVishal Moola (Oracle) 			if (!folio_buffers(folio)) {
248150ead253SVishal Moola (Oracle) 				ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", folio->index);
248250ead253SVishal Moola (Oracle) 				folio_clear_dirty(folio);
248350ead253SVishal Moola (Oracle) 				folio_unlock(folio);
2484cc509574STheodore Ts'o 				continue;
2485cc509574STheodore Ts'o 			}
2486cc509574STheodore Ts'o 
24874e7ea81dSJan Kara 			if (mpd->map.m_len == 0)
248850ead253SVishal Moola (Oracle) 				mpd->first_page = folio->index;
248987b11f86SSidhartha Kumar 			mpd->next_page = folio_next_index(folio);
2490de0039f6SJan Kara 			/*
24913f079114SJan Kara 			 * Writeout when we cannot modify metadata is simple.
24923f079114SJan Kara 			 * Just submit the page. For data=journal mode we
24933f079114SJan Kara 			 * first handle writeout of the page for checkpoint and
24943f079114SJan Kara 			 * only after that handle delayed page dirtying. This
2495ab382539SJan Kara 			 * makes sure current data is checkpointed to the final
2496ab382539SJan Kara 			 * location before possibly journalling it again which
2497ab382539SJan Kara 			 * is desirable when the page is frequently dirtied
2498ab382539SJan Kara 			 * through a pin.
2499de0039f6SJan Kara 			 */
2500de0039f6SJan Kara 			if (!mpd->can_map) {
250181a0d3e1SMatthew Wilcox 				err = mpage_submit_folio(mpd, folio);
2502de0039f6SJan Kara 				if (err < 0)
2503de0039f6SJan Kara 					goto out;
25043f079114SJan Kara 				/* Pending dirtying of journalled data? */
250581a0d3e1SMatthew Wilcox 				if (folio_test_checked(folio)) {
25063f079114SJan Kara 					err = mpage_journal_page_buffers(handle,
250780be8c5cSRitesh Harjani 						mpd, folio);
25083f079114SJan Kara 					if (err < 0)
25093f079114SJan Kara 						goto out;
25101f1a55f0SJan Kara 					mpd->journalled_more_data = 1;
25113f079114SJan Kara 				}
251233483b3bSMatthew Wilcox 				mpage_folio_done(mpd, folio);
2513de0039f6SJan Kara 			} else {
2514f8bec370SJan Kara 				/* Add all dirty buffers to mpd */
251550ead253SVishal Moola (Oracle) 				lblk = ((ext4_lblk_t)folio->index) <<
251609cbfeafSKirill A. Shutemov 					(PAGE_SHIFT - blkbits);
251750ead253SVishal Moola (Oracle) 				head = folio_buffers(folio);
2518de0039f6SJan Kara 				err = mpage_process_page_bufs(mpd, head, head,
2519de0039f6SJan Kara 						lblk);
25205f1132b2SJan Kara 				if (err <= 0)
25214e7ea81dSJan Kara 					goto out;
25225f1132b2SJan Kara 				err = 0;
2523de0039f6SJan Kara 			}
25248e48dcfbSTheodore Ts'o 		}
252550ead253SVishal Moola (Oracle) 		folio_batch_release(&fbatch);
25268e48dcfbSTheodore Ts'o 		cond_resched();
25278e48dcfbSTheodore Ts'o 	}
25286b8ed620SJan Kara 	mpd->scanned_until_end = 1;
25293f079114SJan Kara 	if (handle)
25303f079114SJan Kara 		ext4_journal_stop(handle);
25314f01b02cSTheodore Ts'o 	return 0;
25328eb9e5ceSTheodore Ts'o out:
253350ead253SVishal Moola (Oracle) 	folio_batch_release(&fbatch);
25343f079114SJan Kara 	if (handle)
25353f079114SJan Kara 		ext4_journal_stop(handle);
25364e7ea81dSJan Kara 	return err;
25378e48dcfbSTheodore Ts'o }
25388e48dcfbSTheodore Ts'o 
253915648d59SJan Kara static int ext4_do_writepages(struct mpage_da_data *mpd)
254064769240SAlex Tomas {
254115648d59SJan Kara 	struct writeback_control *wbc = mpd->wbc;
25424e7ea81dSJan Kara 	pgoff_t	writeback_index = 0;
25434e7ea81dSJan Kara 	long nr_to_write = wbc->nr_to_write;
254422208dedSAneesh Kumar K.V 	int range_whole = 0;
25454e7ea81dSJan Kara 	int cycled = 1;
254661628a3fSMingming Cao 	handle_t *handle = NULL;
254715648d59SJan Kara 	struct inode *inode = mpd->inode;
254815648d59SJan Kara 	struct address_space *mapping = inode->i_mapping;
25496b523df4SJan Kara 	int needed_blocks, rsv_blocks = 0, ret = 0;
25505e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
25511bce63d1SShaohua Li 	struct blk_plug plug;
2552cb530541STheodore Ts'o 	bool give_up_on_write = false;
255361628a3fSMingming Cao 
255420970ba6STheodore Ts'o 	trace_ext4_writepages(inode, wbc);
2555ba80b101STheodore Ts'o 
255661628a3fSMingming Cao 	/*
255761628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
255861628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
255961628a3fSMingming Cao 	 * because that could violate lock ordering on umount
256061628a3fSMingming Cao 	 */
2561a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2562bbf023c7SMing Lei 		goto out_writepages;
25632a21e37eSTheodore Ts'o 
25642a21e37eSTheodore Ts'o 	/*
25652a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
25662a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
25672a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
256895257987SJan Kara 	 * fs shutdown state instead of sb->s_flag's SB_RDONLY because
25692a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
257020970ba6STheodore Ts'o 	 * read-only, and in that case, ext4_writepages should
25712a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
25722a21e37eSTheodore Ts'o 	 * the stack trace.
25732a21e37eSTheodore Ts'o 	 */
257495257987SJan Kara 	if (unlikely(ext4_forced_shutdown(mapping->host->i_sb))) {
2575bbf023c7SMing Lei 		ret = -EROFS;
2576bbf023c7SMing Lei 		goto out_writepages;
2577bbf023c7SMing Lei 	}
25782a21e37eSTheodore Ts'o 
25794e7ea81dSJan Kara 	/*
25804e7ea81dSJan Kara 	 * If we have inline data and arrive here, it means that
25814e7ea81dSJan Kara 	 * we will soon create the block for the 1st page, so
25824e7ea81dSJan Kara 	 * we'd better clear the inline data here.
25834e7ea81dSJan Kara 	 */
25844e7ea81dSJan Kara 	if (ext4_has_inline_data(inode)) {
25854e7ea81dSJan Kara 		/* Just inode will be modified... */
25864e7ea81dSJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
25874e7ea81dSJan Kara 		if (IS_ERR(handle)) {
25884e7ea81dSJan Kara 			ret = PTR_ERR(handle);
25894e7ea81dSJan Kara 			goto out_writepages;
25904e7ea81dSJan Kara 		}
25914e7ea81dSJan Kara 		BUG_ON(ext4_test_inode_state(inode,
25924e7ea81dSJan Kara 				EXT4_STATE_MAY_INLINE_DATA));
25934e7ea81dSJan Kara 		ext4_destroy_inline_data(handle, inode);
25944e7ea81dSJan Kara 		ext4_journal_stop(handle);
25954e7ea81dSJan Kara 	}
25964e7ea81dSJan Kara 
25973f079114SJan Kara 	/*
25983f079114SJan Kara 	 * data=journal mode does not do delalloc so we just need to writeout /
25991f1a55f0SJan Kara 	 * journal already mapped buffers. On the other hand we need to commit
26001f1a55f0SJan Kara 	 * transaction to make data stable. We expect all the data to be
26011f1a55f0SJan Kara 	 * already in the journal (the only exception are DMA pinned pages
26021f1a55f0SJan Kara 	 * dirtied behind our back) so we commit transaction here and run the
26031f1a55f0SJan Kara 	 * writeback loop to checkpoint them. The checkpointing is not actually
26041f1a55f0SJan Kara 	 * necessary to make data persistent *but* quite a few places (extent
26051f1a55f0SJan Kara 	 * shifting operations, fsverity, ...) depend on being able to drop
26061f1a55f0SJan Kara 	 * pagecache pages after calling filemap_write_and_wait() and for that
26071f1a55f0SJan Kara 	 * checkpointing needs to happen.
26083f079114SJan Kara 	 */
26091f1a55f0SJan Kara 	if (ext4_should_journal_data(inode)) {
26103f079114SJan Kara 		mpd->can_map = 0;
26111f1a55f0SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL)
26121f1a55f0SJan Kara 			ext4_fc_commit(sbi->s_journal,
26131f1a55f0SJan Kara 				       EXT4_I(inode)->i_datasync_tid);
26141f1a55f0SJan Kara 	}
26151f1a55f0SJan Kara 	mpd->journalled_more_data = 0;
26163f079114SJan Kara 
26174e343231Syangerkun 	if (ext4_should_dioread_nolock(inode)) {
26184e343231Syangerkun 		/*
26194e343231Syangerkun 		 * We may need to convert up to one extent per block in
26204e343231Syangerkun 		 * the page and we may dirty the inode.
26214e343231Syangerkun 		 */
26224e343231Syangerkun 		rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
26234e343231Syangerkun 						PAGE_SIZE >> inode->i_blkbits);
26244e343231Syangerkun 	}
26254e343231Syangerkun 
262622208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
262722208dedSAneesh Kumar K.V 		range_whole = 1;
262861628a3fSMingming Cao 
26292acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
26304e7ea81dSJan Kara 		writeback_index = mapping->writeback_index;
26314e7ea81dSJan Kara 		if (writeback_index)
26322acf2c26SAneesh Kumar K.V 			cycled = 0;
263315648d59SJan Kara 		mpd->first_page = writeback_index;
263415648d59SJan Kara 		mpd->last_page = -1;
26355b41d924SEric Sandeen 	} else {
263615648d59SJan Kara 		mpd->first_page = wbc->range_start >> PAGE_SHIFT;
263715648d59SJan Kara 		mpd->last_page = wbc->range_end >> PAGE_SHIFT;
26385b41d924SEric Sandeen 	}
2639a1d6cc56SAneesh Kumar K.V 
264015648d59SJan Kara 	ext4_io_submit_init(&mpd->io_submit, wbc);
26412acf2c26SAneesh Kumar K.V retry:
26426e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
264315648d59SJan Kara 		tag_pages_for_writeback(mapping, mpd->first_page,
264415648d59SJan Kara 					mpd->last_page);
26451bce63d1SShaohua Li 	blk_start_plug(&plug);
2646dddbd6acSJan Kara 
2647dddbd6acSJan Kara 	/*
2648dddbd6acSJan Kara 	 * First writeback pages that don't need mapping - we can avoid
2649dddbd6acSJan Kara 	 * starting a transaction unnecessarily and also avoid being blocked
2650dddbd6acSJan Kara 	 * in the block layer on device congestion while having transaction
2651dddbd6acSJan Kara 	 * started.
2652dddbd6acSJan Kara 	 */
265315648d59SJan Kara 	mpd->do_map = 0;
265415648d59SJan Kara 	mpd->scanned_until_end = 0;
265515648d59SJan Kara 	mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
265615648d59SJan Kara 	if (!mpd->io_submit.io_end) {
2657dddbd6acSJan Kara 		ret = -ENOMEM;
2658dddbd6acSJan Kara 		goto unplug;
2659dddbd6acSJan Kara 	}
266015648d59SJan Kara 	ret = mpage_prepare_extent_to_map(mpd);
2661a297b2fcSXiaoguang Wang 	/* Unlock pages we didn't use */
266215648d59SJan Kara 	mpage_release_unused_pages(mpd, false);
2663dddbd6acSJan Kara 	/* Submit prepared bio */
266415648d59SJan Kara 	ext4_io_submit(&mpd->io_submit);
266515648d59SJan Kara 	ext4_put_io_end_defer(mpd->io_submit.io_end);
266615648d59SJan Kara 	mpd->io_submit.io_end = NULL;
2667dddbd6acSJan Kara 	if (ret < 0)
2668dddbd6acSJan Kara 		goto unplug;
2669dddbd6acSJan Kara 
267015648d59SJan Kara 	while (!mpd->scanned_until_end && wbc->nr_to_write > 0) {
26714e7ea81dSJan Kara 		/* For each extent of pages we use new io_end */
267215648d59SJan Kara 		mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
267315648d59SJan Kara 		if (!mpd->io_submit.io_end) {
26744e7ea81dSJan Kara 			ret = -ENOMEM;
26754e7ea81dSJan Kara 			break;
26764e7ea81dSJan Kara 		}
2677a1d6cc56SAneesh Kumar K.V 
2678de0039f6SJan Kara 		WARN_ON_ONCE(!mpd->can_map);
2679a1d6cc56SAneesh Kumar K.V 		/*
26804e7ea81dSJan Kara 		 * We have two constraints: We find one extent to map and we
26814e7ea81dSJan Kara 		 * must always write out whole page (makes a difference when
26824e7ea81dSJan Kara 		 * blocksize < pagesize) so that we don't block on IO when we
26834e7ea81dSJan Kara 		 * try to write out the rest of the page. Journalled mode is
26844e7ea81dSJan Kara 		 * not supported by delalloc.
2685a1d6cc56SAneesh Kumar K.V 		 */
2686a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
2687525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2688a1d6cc56SAneesh Kumar K.V 
268961628a3fSMingming Cao 		/* start a new transaction */
26906b523df4SJan Kara 		handle = ext4_journal_start_with_reserve(inode,
26916b523df4SJan Kara 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
269261628a3fSMingming Cao 		if (IS_ERR(handle)) {
269361628a3fSMingming Cao 			ret = PTR_ERR(handle);
26941693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2695fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
2696a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
26974e7ea81dSJan Kara 			/* Release allocated io_end */
269815648d59SJan Kara 			ext4_put_io_end(mpd->io_submit.io_end);
269915648d59SJan Kara 			mpd->io_submit.io_end = NULL;
27004e7ea81dSJan Kara 			break;
270161628a3fSMingming Cao 		}
270215648d59SJan Kara 		mpd->do_map = 1;
2703f63e6005STheodore Ts'o 
270415648d59SJan Kara 		trace_ext4_da_write_pages(inode, mpd->first_page, wbc);
270515648d59SJan Kara 		ret = mpage_prepare_extent_to_map(mpd);
270615648d59SJan Kara 		if (!ret && mpd->map.m_len)
270715648d59SJan Kara 			ret = mpage_map_and_submit_extent(handle, mpd,
2708cb530541STheodore Ts'o 					&give_up_on_write);
2709646caa9cSJan Kara 		/*
2710646caa9cSJan Kara 		 * Caution: If the handle is synchronous,
2711646caa9cSJan Kara 		 * ext4_journal_stop() can wait for transaction commit
2712646caa9cSJan Kara 		 * to finish which may depend on writeback of pages to
2713646caa9cSJan Kara 		 * complete or on page lock to be released.  In that
2714b483bb77SRandy Dunlap 		 * case, we have to wait until after we have
2715646caa9cSJan Kara 		 * submitted all the IO, released page locks we hold,
2716646caa9cSJan Kara 		 * and dropped io_end reference (for extent conversion
2717646caa9cSJan Kara 		 * to be able to complete) before stopping the handle.
2718646caa9cSJan Kara 		 */
2719646caa9cSJan Kara 		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
272061628a3fSMingming Cao 			ext4_journal_stop(handle);
2721646caa9cSJan Kara 			handle = NULL;
272215648d59SJan Kara 			mpd->do_map = 0;
2723646caa9cSJan Kara 		}
27244e7ea81dSJan Kara 		/* Unlock pages we didn't use */
272515648d59SJan Kara 		mpage_release_unused_pages(mpd, give_up_on_write);
2726a297b2fcSXiaoguang Wang 		/* Submit prepared bio */
272715648d59SJan Kara 		ext4_io_submit(&mpd->io_submit);
2728a297b2fcSXiaoguang Wang 
2729646caa9cSJan Kara 		/*
2730646caa9cSJan Kara 		 * Drop our io_end reference we got from init. We have
2731646caa9cSJan Kara 		 * to be careful and use deferred io_end finishing if
2732646caa9cSJan Kara 		 * we are still holding the transaction as we can
2733646caa9cSJan Kara 		 * release the last reference to io_end which may end
2734646caa9cSJan Kara 		 * up doing unwritten extent conversion.
2735646caa9cSJan Kara 		 */
2736646caa9cSJan Kara 		if (handle) {
273715648d59SJan Kara 			ext4_put_io_end_defer(mpd->io_submit.io_end);
2738646caa9cSJan Kara 			ext4_journal_stop(handle);
2739646caa9cSJan Kara 		} else
274015648d59SJan Kara 			ext4_put_io_end(mpd->io_submit.io_end);
274115648d59SJan Kara 		mpd->io_submit.io_end = NULL;
2742df22291fSAneesh Kumar K.V 
27434e7ea81dSJan Kara 		if (ret == -ENOSPC && sbi->s_journal) {
27444e7ea81dSJan Kara 			/*
27454e7ea81dSJan Kara 			 * Commit the transaction which would
274622208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
274722208dedSAneesh Kumar K.V 			 * and try again
274822208dedSAneesh Kumar K.V 			 */
2749df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
275022208dedSAneesh Kumar K.V 			ret = 0;
27514e7ea81dSJan Kara 			continue;
27524e7ea81dSJan Kara 		}
27534e7ea81dSJan Kara 		/* Fatal error - ENOMEM, EIO... */
27544e7ea81dSJan Kara 		if (ret)
275561628a3fSMingming Cao 			break;
275661628a3fSMingming Cao 	}
2757dddbd6acSJan Kara unplug:
27581bce63d1SShaohua Li 	blk_finish_plug(&plug);
27599c12a831SJan Kara 	if (!ret && !cycled && wbc->nr_to_write > 0) {
27602acf2c26SAneesh Kumar K.V 		cycled = 1;
276115648d59SJan Kara 		mpd->last_page = writeback_index - 1;
276215648d59SJan Kara 		mpd->first_page = 0;
27632acf2c26SAneesh Kumar K.V 		goto retry;
27642acf2c26SAneesh Kumar K.V 	}
276561628a3fSMingming Cao 
276622208dedSAneesh Kumar K.V 	/* Update index */
276722208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
276822208dedSAneesh Kumar K.V 		/*
27694e7ea81dSJan Kara 		 * Set the writeback_index so that range_cyclic
277022208dedSAneesh Kumar K.V 		 * mode will write it back later
277122208dedSAneesh Kumar K.V 		 */
277215648d59SJan Kara 		mapping->writeback_index = mpd->first_page;
2773a1d6cc56SAneesh Kumar K.V 
277461628a3fSMingming Cao out_writepages:
277520970ba6STheodore Ts'o 	trace_ext4_writepages_result(inode, wbc, ret,
27764e7ea81dSJan Kara 				     nr_to_write - wbc->nr_to_write);
277761628a3fSMingming Cao 	return ret;
277864769240SAlex Tomas }
277964769240SAlex Tomas 
278015648d59SJan Kara static int ext4_writepages(struct address_space *mapping,
278115648d59SJan Kara 			   struct writeback_control *wbc)
278215648d59SJan Kara {
278329bc9ceaSJan Kara 	struct super_block *sb = mapping->host->i_sb;
278415648d59SJan Kara 	struct mpage_da_data mpd = {
278515648d59SJan Kara 		.inode = mapping->host,
278615648d59SJan Kara 		.wbc = wbc,
278715648d59SJan Kara 		.can_map = 1,
278815648d59SJan Kara 	};
278929bc9ceaSJan Kara 	int ret;
279000d873c1SJan Kara 	int alloc_ctx;
279115648d59SJan Kara 
2792eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(sb)))
279329bc9ceaSJan Kara 		return -EIO;
279429bc9ceaSJan Kara 
279500d873c1SJan Kara 	alloc_ctx = ext4_writepages_down_read(sb);
279629bc9ceaSJan Kara 	ret = ext4_do_writepages(&mpd);
27971f1a55f0SJan Kara 	/*
27981f1a55f0SJan Kara 	 * For data=journal writeback we could have come across pages marked
27991f1a55f0SJan Kara 	 * for delayed dirtying (PageChecked) which were just added to the
28001f1a55f0SJan Kara 	 * running transaction. Try once more to get them to stable storage.
28011f1a55f0SJan Kara 	 */
28021f1a55f0SJan Kara 	if (!ret && mpd.journalled_more_data)
28031f1a55f0SJan Kara 		ret = ext4_do_writepages(&mpd);
280400d873c1SJan Kara 	ext4_writepages_up_read(sb, alloc_ctx);
280529bc9ceaSJan Kara 
280629bc9ceaSJan Kara 	return ret;
280715648d59SJan Kara }
280815648d59SJan Kara 
280959205c8dSJan Kara int ext4_normal_submit_inode_data_buffers(struct jbd2_inode *jinode)
281059205c8dSJan Kara {
281159205c8dSJan Kara 	struct writeback_control wbc = {
281259205c8dSJan Kara 		.sync_mode = WB_SYNC_ALL,
281359205c8dSJan Kara 		.nr_to_write = LONG_MAX,
281459205c8dSJan Kara 		.range_start = jinode->i_dirty_start,
281559205c8dSJan Kara 		.range_end = jinode->i_dirty_end,
281659205c8dSJan Kara 	};
281759205c8dSJan Kara 	struct mpage_da_data mpd = {
281859205c8dSJan Kara 		.inode = jinode->i_vfs_inode,
281959205c8dSJan Kara 		.wbc = &wbc,
282059205c8dSJan Kara 		.can_map = 0,
282159205c8dSJan Kara 	};
282259205c8dSJan Kara 	return ext4_do_writepages(&mpd);
282359205c8dSJan Kara }
282459205c8dSJan Kara 
28255f0663bbSDan Williams static int ext4_dax_writepages(struct address_space *mapping,
28265f0663bbSDan Williams 			       struct writeback_control *wbc)
28275f0663bbSDan Williams {
28285f0663bbSDan Williams 	int ret;
28295f0663bbSDan Williams 	long nr_to_write = wbc->nr_to_write;
28305f0663bbSDan Williams 	struct inode *inode = mapping->host;
283100d873c1SJan Kara 	int alloc_ctx;
28325f0663bbSDan Williams 
2833eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
28345f0663bbSDan Williams 		return -EIO;
28355f0663bbSDan Williams 
283600d873c1SJan Kara 	alloc_ctx = ext4_writepages_down_read(inode->i_sb);
28375f0663bbSDan Williams 	trace_ext4_writepages(inode, wbc);
28385f0663bbSDan Williams 
2839eb8ab444SJan Kara 	ret = dax_writeback_mapping_range(mapping,
2840eb8ab444SJan Kara 					  EXT4_SB(inode->i_sb)->s_daxdev, wbc);
28415f0663bbSDan Williams 	trace_ext4_writepages_result(inode, wbc, ret,
28425f0663bbSDan Williams 				     nr_to_write - wbc->nr_to_write);
284300d873c1SJan Kara 	ext4_writepages_up_read(inode->i_sb, alloc_ctx);
28445f0663bbSDan Williams 	return ret;
28455f0663bbSDan Williams }
28465f0663bbSDan Williams 
284779f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
284879f0be8dSAneesh Kumar K.V {
28495c1ff336SEric Whitney 	s64 free_clusters, dirty_clusters;
285079f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
285179f0be8dSAneesh Kumar K.V 
285279f0be8dSAneesh Kumar K.V 	/*
285379f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
285479f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
2855179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
285679f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
285779f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
285879f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
285979f0be8dSAneesh Kumar K.V 	 */
28605c1ff336SEric Whitney 	free_clusters =
28615c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
28625c1ff336SEric Whitney 	dirty_clusters =
28635c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
286400d4e736STheodore Ts'o 	/*
286500d4e736STheodore Ts'o 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
286600d4e736STheodore Ts'o 	 */
28675c1ff336SEric Whitney 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
286810ee27a0SMiao Xie 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
286900d4e736STheodore Ts'o 
28705c1ff336SEric Whitney 	if (2 * free_clusters < 3 * dirty_clusters ||
28715c1ff336SEric Whitney 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
287279f0be8dSAneesh Kumar K.V 		/*
2873c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
2874c8afb446SEric Sandeen 		 * or free blocks is less than watermark
287579f0be8dSAneesh Kumar K.V 		 */
287679f0be8dSAneesh Kumar K.V 		return 1;
287779f0be8dSAneesh Kumar K.V 	}
287879f0be8dSAneesh Kumar K.V 	return 0;
287979f0be8dSAneesh Kumar K.V }
288079f0be8dSAneesh Kumar K.V 
288164769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
28829d6b0cd7SMatthew Wilcox (Oracle) 			       loff_t pos, unsigned len,
288364769240SAlex Tomas 			       struct page **pagep, void **fsdata)
288464769240SAlex Tomas {
288572b8ab9dSEric Sandeen 	int ret, retries = 0;
28860b5a2543SMatthew Wilcox 	struct folio *folio;
288764769240SAlex Tomas 	pgoff_t index;
288864769240SAlex Tomas 	struct inode *inode = mapping->host;
288964769240SAlex Tomas 
2890eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
28910db1ff22STheodore Ts'o 		return -EIO;
28920db1ff22STheodore Ts'o 
289309cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
289479f0be8dSAneesh Kumar K.V 
28956493792dSZhang Yi 	if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
289679f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
289779f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
28989d6b0cd7SMatthew Wilcox (Oracle) 					len, pagep, fsdata);
289979f0be8dSAneesh Kumar K.V 	}
290079f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
29019d6b0cd7SMatthew Wilcox (Oracle) 	trace_ext4_da_write_begin(inode, pos, len);
29029c3569b5STao Ma 
29039c3569b5STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
290436d116e9SMatthew Wilcox (Oracle) 		ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len,
29059c3569b5STao Ma 						      pagep, fsdata);
29069c3569b5STao Ma 		if (ret < 0)
290747564bfbSTheodore Ts'o 			return ret;
290847564bfbSTheodore Ts'o 		if (ret == 1)
290947564bfbSTheodore Ts'o 			return 0;
29109c3569b5STao Ma 	}
29119c3569b5STao Ma 
2912cc883236SZhang Yi retry:
29130b5a2543SMatthew Wilcox 	folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
29140b5a2543SMatthew Wilcox 			mapping_gfp_mask(mapping));
29157fa8a8eeSLinus Torvalds 	if (IS_ERR(folio))
29167fa8a8eeSLinus Torvalds 		return PTR_ERR(folio);
291747564bfbSTheodore Ts'o 
2918643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
291986b38c27SMatthew Wilcox 	ret = ext4_block_write_begin(folio, pos, len, ext4_da_get_block_prep);
29202058f83aSMichael Halcrow #else
29210b5a2543SMatthew Wilcox 	ret = __block_write_begin(&folio->page, pos, len, ext4_da_get_block_prep);
29222058f83aSMichael Halcrow #endif
292364769240SAlex Tomas 	if (ret < 0) {
29240b5a2543SMatthew Wilcox 		folio_unlock(folio);
29250b5a2543SMatthew Wilcox 		folio_put(folio);
2926ae4d5372SAneesh Kumar K.V 		/*
2927ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
2928ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
2929cc883236SZhang Yi 		 * i_size_read because we hold inode lock.
2930ae4d5372SAneesh Kumar K.V 		 */
2931ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
2932b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
293347564bfbSTheodore Ts'o 
293447564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
293547564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
2936cc883236SZhang Yi 			goto retry;
293747564bfbSTheodore Ts'o 		return ret;
293864769240SAlex Tomas 	}
293964769240SAlex Tomas 
29400b5a2543SMatthew Wilcox 	*pagep = &folio->page;
294164769240SAlex Tomas 	return ret;
294264769240SAlex Tomas }
294364769240SAlex Tomas 
2944632eaeabSMingming Cao /*
2945632eaeabSMingming Cao  * Check if we should update i_disksize
2946632eaeabSMingming Cao  * when write to the end of file but not require block allocation
2947632eaeabSMingming Cao  */
2948d19500daSRitesh Harjani static int ext4_da_should_update_i_disksize(struct folio *folio,
2949632eaeabSMingming Cao 					    unsigned long offset)
2950632eaeabSMingming Cao {
2951632eaeabSMingming Cao 	struct buffer_head *bh;
2952d19500daSRitesh Harjani 	struct inode *inode = folio->mapping->host;
2953632eaeabSMingming Cao 	unsigned int idx;
2954632eaeabSMingming Cao 	int i;
2955632eaeabSMingming Cao 
2956d19500daSRitesh Harjani 	bh = folio_buffers(folio);
2957632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
2958632eaeabSMingming Cao 
2959632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
2960632eaeabSMingming Cao 		bh = bh->b_this_page;
2961632eaeabSMingming Cao 
296229fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2963632eaeabSMingming Cao 		return 0;
2964632eaeabSMingming Cao 	return 1;
2965632eaeabSMingming Cao }
2966632eaeabSMingming Cao 
296703de20beSLiu Song static int ext4_da_do_write_end(struct address_space *mapping,
296803de20beSLiu Song 			loff_t pos, unsigned len, unsigned copied,
29693a2c70baSMatthew Wilcox (Oracle) 			struct folio *folio)
297003de20beSLiu Song {
297103de20beSLiu Song 	struct inode *inode = mapping->host;
297203de20beSLiu Song 	loff_t old_size = inode->i_size;
297303de20beSLiu Song 	bool disksize_changed = false;
297403de20beSLiu Song 	loff_t new_i_size;
297503de20beSLiu Song 
2976*3f6bbe6eSWojciech Gładysz 	if (unlikely(!folio_buffers(folio))) {
2977*3f6bbe6eSWojciech Gładysz 		folio_unlock(folio);
2978*3f6bbe6eSWojciech Gładysz 		folio_put(folio);
2979*3f6bbe6eSWojciech Gładysz 		return -EIO;
2980*3f6bbe6eSWojciech Gładysz 	}
298103de20beSLiu Song 	/*
298203de20beSLiu Song 	 * block_write_end() will mark the inode as dirty with I_DIRTY_PAGES
298303de20beSLiu Song 	 * flag, which all that's needed to trigger page writeback.
298403de20beSLiu Song 	 */
29853a2c70baSMatthew Wilcox (Oracle) 	copied = block_write_end(NULL, mapping, pos, len, copied,
29863a2c70baSMatthew Wilcox (Oracle) 			&folio->page, NULL);
298703de20beSLiu Song 	new_i_size = pos + copied;
298803de20beSLiu Song 
298903de20beSLiu Song 	/*
29903a2c70baSMatthew Wilcox (Oracle) 	 * It's important to update i_size while still holding folio lock,
29913a2c70baSMatthew Wilcox (Oracle) 	 * because folio writeout could otherwise come in and zero beyond
299203de20beSLiu Song 	 * i_size.
299303de20beSLiu Song 	 *
299403de20beSLiu Song 	 * Since we are holding inode lock, we are sure i_disksize <=
299503de20beSLiu Song 	 * i_size. We also know that if i_disksize < i_size, there are
299603de20beSLiu Song 	 * delalloc writes pending in the range up to i_size. If the end of
299703de20beSLiu Song 	 * the current write is <= i_size, there's no need to touch
299803de20beSLiu Song 	 * i_disksize since writeback will push i_disksize up to i_size
299903de20beSLiu Song 	 * eventually. If the end of the current write is > i_size and
300003de20beSLiu Song 	 * inside an allocated block which ext4_da_should_update_i_disksize()
300103de20beSLiu Song 	 * checked, we need to update i_disksize here as certain
300203de20beSLiu Song 	 * ext4_writepages() paths not allocating blocks and update i_disksize.
300303de20beSLiu Song 	 */
300403de20beSLiu Song 	if (new_i_size > inode->i_size) {
300503de20beSLiu Song 		unsigned long end;
300603de20beSLiu Song 
300703de20beSLiu Song 		i_size_write(inode, new_i_size);
300803de20beSLiu Song 		end = (new_i_size - 1) & (PAGE_SIZE - 1);
30093a2c70baSMatthew Wilcox (Oracle) 		if (copied && ext4_da_should_update_i_disksize(folio, end)) {
301003de20beSLiu Song 			ext4_update_i_disksize(inode, new_i_size);
301103de20beSLiu Song 			disksize_changed = true;
301203de20beSLiu Song 		}
301303de20beSLiu Song 	}
301403de20beSLiu Song 
30153a2c70baSMatthew Wilcox (Oracle) 	folio_unlock(folio);
30163a2c70baSMatthew Wilcox (Oracle) 	folio_put(folio);
301703de20beSLiu Song 
301803de20beSLiu Song 	if (old_size < pos)
301903de20beSLiu Song 		pagecache_isize_extended(inode, old_size, pos);
302003de20beSLiu Song 
302103de20beSLiu Song 	if (disksize_changed) {
302203de20beSLiu Song 		handle_t *handle;
302303de20beSLiu Song 
302403de20beSLiu Song 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
302503de20beSLiu Song 		if (IS_ERR(handle))
302603de20beSLiu Song 			return PTR_ERR(handle);
302703de20beSLiu Song 		ext4_mark_inode_dirty(handle, inode);
302803de20beSLiu Song 		ext4_journal_stop(handle);
302903de20beSLiu Song 	}
303003de20beSLiu Song 
303103de20beSLiu Song 	return copied;
303203de20beSLiu Song }
303303de20beSLiu Song 
303464769240SAlex Tomas static int ext4_da_write_end(struct file *file,
303564769240SAlex Tomas 			     struct address_space *mapping,
303664769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
303764769240SAlex Tomas 			     struct page *page, void *fsdata)
303864769240SAlex Tomas {
303964769240SAlex Tomas 	struct inode *inode = mapping->host;
304079f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
3041d19500daSRitesh Harjani 	struct folio *folio = page_folio(page);
304279f0be8dSAneesh Kumar K.V 
304374d553aaSTheodore Ts'o 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
304474d553aaSTheodore Ts'o 		return ext4_write_end(file, mapping, pos,
3045d19500daSRitesh Harjani 				      len, copied, &folio->page, fsdata);
3046632eaeabSMingming Cao 
30479bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
30489c3569b5STao Ma 
30499c3569b5STao Ma 	if (write_mode != CONVERT_INLINE_DATA &&
30509c3569b5STao Ma 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
30519c3569b5STao Ma 	    ext4_has_inline_data(inode))
3052d19500daSRitesh Harjani 		return ext4_write_inline_data_end(inode, pos, len, copied,
3053d19500daSRitesh Harjani 						  folio);
30549c3569b5STao Ma 
30553a2c70baSMatthew Wilcox (Oracle) 	if (unlikely(copied < len) && !folio_test_uptodate(folio))
30561dedde69SZhihao Cheng 		copied = 0;
30571dedde69SZhihao Cheng 
30583a2c70baSMatthew Wilcox (Oracle) 	return ext4_da_do_write_end(mapping, pos, len, copied, folio);
305964769240SAlex Tomas }
306064769240SAlex Tomas 
3061ccd2506bSTheodore Ts'o /*
3062ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
3063ccd2506bSTheodore Ts'o  */
3064ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
3065ccd2506bSTheodore Ts'o {
3066fb40ba0dSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
3067fb40ba0dSTheodore Ts'o 
306871d4f7d0STheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks)
3069ccd2506bSTheodore Ts'o 		return 0;
3070ccd2506bSTheodore Ts'o 
3071ccd2506bSTheodore Ts'o 	/*
3072ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
3073ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
3074ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
3075ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
3076ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
3077ccd2506bSTheodore Ts'o 	 *
307820970ba6STheodore Ts'o 	 * ext4_writepages() ->
3079ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
3080ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
3081ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
3082ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
3083ccd2506bSTheodore Ts'o 	 *
3084ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
3085ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
3086ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
3087ccd2506bSTheodore Ts'o 	 * doing I/O at all.
3088ccd2506bSTheodore Ts'o 	 *
3089ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
3090380cf090SWu Fengguang 	 * the pages by calling redirty_page_for_writepage() but that
3091ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
3092ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
309325985edcSLucas De Marchi 	 * simplifying them because we wouldn't actually intend to
3094ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
3095ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
3096ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
3097ccd2506bSTheodore Ts'o 	 *
3098ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
3099ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
3100ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
3101ccd2506bSTheodore Ts'o 	 */
3102ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
3103ccd2506bSTheodore Ts'o }
310464769240SAlex Tomas 
310564769240SAlex Tomas /*
3106ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
3107ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
3108ac27a0ecSDave Kleikamp  *
3109ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
3110617ba13bSMingming Cao  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3111ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
3112ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
3113ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
3114ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
3115ac27a0ecSDave Kleikamp  *
3116ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
3117ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
3118ac27a0ecSDave Kleikamp  */
3119617ba13bSMingming Cao static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3120ac27a0ecSDave Kleikamp {
3121ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
312251ae846cSYe Bin 	sector_t ret = 0;
3123ac27a0ecSDave Kleikamp 
312451ae846cSYe Bin 	inode_lock_shared(inode);
312546c7f254STao Ma 	/*
312646c7f254STao Ma 	 * We can get here for an inline file via the FIBMAP ioctl
312746c7f254STao Ma 	 */
312846c7f254STao Ma 	if (ext4_has_inline_data(inode))
312951ae846cSYe Bin 		goto out;
313046c7f254STao Ma 
313164769240SAlex Tomas 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3132951cafa6SJan Kara 	    (test_opt(inode->i_sb, DELALLOC) ||
3133951cafa6SJan Kara 	     ext4_should_journal_data(inode))) {
313464769240SAlex Tomas 		/*
3135951cafa6SJan Kara 		 * With delalloc or journalled data we want to sync the file so
3136951cafa6SJan Kara 		 * that we can make sure we allocate blocks for file and data
3137951cafa6SJan Kara 		 * is in place for the user to see it
313864769240SAlex Tomas 		 */
313964769240SAlex Tomas 		filemap_write_and_wait(mapping);
314064769240SAlex Tomas 	}
314164769240SAlex Tomas 
314251ae846cSYe Bin 	ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
314351ae846cSYe Bin 
314451ae846cSYe Bin out:
314551ae846cSYe Bin 	inode_unlock_shared(inode);
314651ae846cSYe Bin 	return ret;
3147ac27a0ecSDave Kleikamp }
3148ac27a0ecSDave Kleikamp 
3149fe5ddf6bSMatthew Wilcox (Oracle) static int ext4_read_folio(struct file *file, struct folio *folio)
3150ac27a0ecSDave Kleikamp {
315146c7f254STao Ma 	int ret = -EAGAIN;
3152c0be8e6fSMatthew Wilcox 	struct inode *inode = folio->mapping->host;
315346c7f254STao Ma 
315436c9b450SRitesh Harjani 	trace_ext4_read_folio(inode, folio);
315546c7f254STao Ma 
315646c7f254STao Ma 	if (ext4_has_inline_data(inode))
31573edde93eSMatthew Wilcox 		ret = ext4_readpage_inline(inode, folio);
315846c7f254STao Ma 
315946c7f254STao Ma 	if (ret == -EAGAIN)
3160c0be8e6fSMatthew Wilcox 		return ext4_mpage_readpages(inode, NULL, folio);
316146c7f254STao Ma 
316246c7f254STao Ma 	return ret;
3163ac27a0ecSDave Kleikamp }
3164ac27a0ecSDave Kleikamp 
31656311f91fSMatthew Wilcox (Oracle) static void ext4_readahead(struct readahead_control *rac)
3166ac27a0ecSDave Kleikamp {
31676311f91fSMatthew Wilcox (Oracle) 	struct inode *inode = rac->mapping->host;
316846c7f254STao Ma 
31696311f91fSMatthew Wilcox (Oracle) 	/* If the file has inline data, no need to do readahead. */
317046c7f254STao Ma 	if (ext4_has_inline_data(inode))
31716311f91fSMatthew Wilcox (Oracle) 		return;
317246c7f254STao Ma 
3173a07f624bSMatthew Wilcox (Oracle) 	ext4_mpage_readpages(inode, rac, NULL);
3174ac27a0ecSDave Kleikamp }
3175ac27a0ecSDave Kleikamp 
31767ba13abbSMatthew Wilcox (Oracle) static void ext4_invalidate_folio(struct folio *folio, size_t offset,
31777ba13abbSMatthew Wilcox (Oracle) 				size_t length)
3178ac27a0ecSDave Kleikamp {
3179ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_invalidate_folio(folio, offset, length);
31800562e0baSJiaying Zhang 
31814520fb3cSJan Kara 	/* No journalling happens on data buffers when this function is used */
31827ba13abbSMatthew Wilcox (Oracle) 	WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
31834520fb3cSJan Kara 
31847ba13abbSMatthew Wilcox (Oracle) 	block_invalidate_folio(folio, offset, length);
31854520fb3cSJan Kara }
31864520fb3cSJan Kara 
3187ccd16945SMatthew Wilcox (Oracle) static int __ext4_journalled_invalidate_folio(struct folio *folio,
3188ccd16945SMatthew Wilcox (Oracle) 					    size_t offset, size_t length)
31894520fb3cSJan Kara {
3190ccd16945SMatthew Wilcox (Oracle) 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
31914520fb3cSJan Kara 
3192ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_journalled_invalidate_folio(folio, offset, length);
31934520fb3cSJan Kara 
3194744692dcSJiaying Zhang 	/*
3195ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
3196ac27a0ecSDave Kleikamp 	 */
3197ccd16945SMatthew Wilcox (Oracle) 	if (offset == 0 && length == folio_size(folio))
3198ccd16945SMatthew Wilcox (Oracle) 		folio_clear_checked(folio);
3199ac27a0ecSDave Kleikamp 
3200ccd16945SMatthew Wilcox (Oracle) 	return jbd2_journal_invalidate_folio(journal, folio, offset, length);
320153e87268SJan Kara }
320253e87268SJan Kara 
320353e87268SJan Kara /* Wrapper for aops... */
3204ccd16945SMatthew Wilcox (Oracle) static void ext4_journalled_invalidate_folio(struct folio *folio,
3205ccd16945SMatthew Wilcox (Oracle) 					   size_t offset,
3206ccd16945SMatthew Wilcox (Oracle) 					   size_t length)
320753e87268SJan Kara {
3208ccd16945SMatthew Wilcox (Oracle) 	WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3209ac27a0ecSDave Kleikamp }
3210ac27a0ecSDave Kleikamp 
32113c402f15SMatthew Wilcox (Oracle) static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3212ac27a0ecSDave Kleikamp {
321336c9b450SRitesh Harjani 	struct inode *inode = folio->mapping->host;
321436c9b450SRitesh Harjani 	journal_t *journal = EXT4_JOURNAL(inode);
3215ac27a0ecSDave Kleikamp 
321636c9b450SRitesh Harjani 	trace_ext4_release_folio(inode, folio);
32170562e0baSJiaying Zhang 
3218e1c36595SJan Kara 	/* Page has dirty journalled data -> cannot release */
32193c402f15SMatthew Wilcox (Oracle) 	if (folio_test_checked(folio))
32203c402f15SMatthew Wilcox (Oracle) 		return false;
32210390131bSFrank Mayhar 	if (journal)
3222c56a6eb0SMatthew Wilcox (Oracle) 		return jbd2_journal_try_to_free_buffers(journal, folio);
32230390131bSFrank Mayhar 	else
322468189fefSMatthew Wilcox (Oracle) 		return try_to_free_buffers(folio);
3225ac27a0ecSDave Kleikamp }
3226ac27a0ecSDave Kleikamp 
3227b8a6176cSJan Kara static bool ext4_inode_datasync_dirty(struct inode *inode)
3228b8a6176cSJan Kara {
3229b8a6176cSJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3230b8a6176cSJan Kara 
3231aa75f4d3SHarshad Shirwadkar 	if (journal) {
3232aa75f4d3SHarshad Shirwadkar 		if (jbd2_transaction_committed(journal,
3233aa75f4d3SHarshad Shirwadkar 			EXT4_I(inode)->i_datasync_tid))
3234d0520df7SAndrea Righi 			return false;
3235d0520df7SAndrea Righi 		if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
32361ceecb53SHarshad Shirwadkar 			return !list_empty(&EXT4_I(inode)->i_fc_list);
3237d0520df7SAndrea Righi 		return true;
3238aa75f4d3SHarshad Shirwadkar 	}
3239aa75f4d3SHarshad Shirwadkar 
3240b8a6176cSJan Kara 	/* Any metadata buffers to write? */
3241b8a6176cSJan Kara 	if (!list_empty(&inode->i_mapping->private_list))
3242b8a6176cSJan Kara 		return true;
3243b8a6176cSJan Kara 	return inode->i_state & I_DIRTY_DATASYNC;
3244b8a6176cSJan Kara }
3245b8a6176cSJan Kara 
3246c8fdfe29SMatthew Bobrowski static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3247c8fdfe29SMatthew Bobrowski 			   struct ext4_map_blocks *map, loff_t offset,
3248de205114SChristoph Hellwig 			   loff_t length, unsigned int flags)
3249364443cbSJan Kara {
3250c8fdfe29SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3251c8fdfe29SMatthew Bobrowski 
3252c8fdfe29SMatthew Bobrowski 	/*
3253c8fdfe29SMatthew Bobrowski 	 * Writes that span EOF might trigger an I/O size update on completion,
3254c8fdfe29SMatthew Bobrowski 	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3255c8fdfe29SMatthew Bobrowski 	 * there is no other metadata changes being made or are pending.
3256c8fdfe29SMatthew Bobrowski 	 */
3257c8fdfe29SMatthew Bobrowski 	iomap->flags = 0;
3258c8fdfe29SMatthew Bobrowski 	if (ext4_inode_datasync_dirty(inode) ||
3259c8fdfe29SMatthew Bobrowski 	    offset + length > i_size_read(inode))
3260c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_DIRTY;
3261c8fdfe29SMatthew Bobrowski 
3262c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_NEW)
3263c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_NEW;
3264c8fdfe29SMatthew Bobrowski 
3265de205114SChristoph Hellwig 	if (flags & IOMAP_DAX)
3266c8fdfe29SMatthew Bobrowski 		iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3267de205114SChristoph Hellwig 	else
3268de205114SChristoph Hellwig 		iomap->bdev = inode->i_sb->s_bdev;
3269c8fdfe29SMatthew Bobrowski 	iomap->offset = (u64) map->m_lblk << blkbits;
3270c8fdfe29SMatthew Bobrowski 	iomap->length = (u64) map->m_len << blkbits;
3271c8fdfe29SMatthew Bobrowski 
32726386722aSRitesh Harjani 	if ((map->m_flags & EXT4_MAP_MAPPED) &&
32736386722aSRitesh Harjani 	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
32746386722aSRitesh Harjani 		iomap->flags |= IOMAP_F_MERGED;
32756386722aSRitesh Harjani 
3276c8fdfe29SMatthew Bobrowski 	/*
3277c8fdfe29SMatthew Bobrowski 	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3278c8fdfe29SMatthew Bobrowski 	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3279c8fdfe29SMatthew Bobrowski 	 * set. In order for any allocated unwritten extents to be converted
3280c8fdfe29SMatthew Bobrowski 	 * into written extents correctly within the ->end_io() handler, we
3281c8fdfe29SMatthew Bobrowski 	 * need to ensure that the iomap->type is set appropriately. Hence, the
3282c8fdfe29SMatthew Bobrowski 	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3283c8fdfe29SMatthew Bobrowski 	 * been set first.
3284c8fdfe29SMatthew Bobrowski 	 */
3285c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3286c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_UNWRITTEN;
3287c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3288de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3289de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3290c8fdfe29SMatthew Bobrowski 	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3291c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_MAPPED;
3292c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3293de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3294de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3295c8fdfe29SMatthew Bobrowski 	} else {
3296c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_HOLE;
3297c8fdfe29SMatthew Bobrowski 		iomap->addr = IOMAP_NULL_ADDR;
3298c8fdfe29SMatthew Bobrowski 	}
3299c8fdfe29SMatthew Bobrowski }
3300c8fdfe29SMatthew Bobrowski 
3301f063db5eSMatthew Bobrowski static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3302f063db5eSMatthew Bobrowski 			    unsigned int flags)
3303f063db5eSMatthew Bobrowski {
3304f063db5eSMatthew Bobrowski 	handle_t *handle;
3305378f32baSMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3306378f32baSMatthew Bobrowski 	int ret, dio_credits, m_flags = 0, retries = 0;
3307f063db5eSMatthew Bobrowski 
3308f063db5eSMatthew Bobrowski 	/*
3309f063db5eSMatthew Bobrowski 	 * Trim the mapping request to the maximum value that we can map at
3310f063db5eSMatthew Bobrowski 	 * once for direct I/O.
3311f063db5eSMatthew Bobrowski 	 */
3312f063db5eSMatthew Bobrowski 	if (map->m_len > DIO_MAX_BLOCKS)
3313f063db5eSMatthew Bobrowski 		map->m_len = DIO_MAX_BLOCKS;
3314f063db5eSMatthew Bobrowski 	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3315f063db5eSMatthew Bobrowski 
3316f063db5eSMatthew Bobrowski retry:
3317f063db5eSMatthew Bobrowski 	/*
3318f063db5eSMatthew Bobrowski 	 * Either we allocate blocks and then don't get an unwritten extent, so
3319f063db5eSMatthew Bobrowski 	 * in that case we have reserved enough credits. Or, the blocks are
3320f063db5eSMatthew Bobrowski 	 * already allocated and unwritten. In that case, the extent conversion
3321f063db5eSMatthew Bobrowski 	 * fits into the credits as well.
3322f063db5eSMatthew Bobrowski 	 */
3323f063db5eSMatthew Bobrowski 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3324f063db5eSMatthew Bobrowski 	if (IS_ERR(handle))
3325f063db5eSMatthew Bobrowski 		return PTR_ERR(handle);
3326f063db5eSMatthew Bobrowski 
3327378f32baSMatthew Bobrowski 	/*
3328378f32baSMatthew Bobrowski 	 * DAX and direct I/O are the only two operations that are currently
3329378f32baSMatthew Bobrowski 	 * supported with IOMAP_WRITE.
3330378f32baSMatthew Bobrowski 	 */
3331952da063SChristoph Hellwig 	WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3332952da063SChristoph Hellwig 	if (flags & IOMAP_DAX)
3333378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3334378f32baSMatthew Bobrowski 	/*
3335378f32baSMatthew Bobrowski 	 * We use i_size instead of i_disksize here because delalloc writeback
3336378f32baSMatthew Bobrowski 	 * can complete at any point during the I/O and subsequently push the
3337378f32baSMatthew Bobrowski 	 * i_disksize out to i_size. This could be beyond where direct I/O is
3338378f32baSMatthew Bobrowski 	 * happening and thus expose allocated blocks to direct I/O reads.
3339378f32baSMatthew Bobrowski 	 */
3340d0b040f5SJan Kara 	else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3341378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE;
3342378f32baSMatthew Bobrowski 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3343378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3344378f32baSMatthew Bobrowski 
3345378f32baSMatthew Bobrowski 	ret = ext4_map_blocks(handle, inode, map, m_flags);
3346378f32baSMatthew Bobrowski 
3347378f32baSMatthew Bobrowski 	/*
3348378f32baSMatthew Bobrowski 	 * We cannot fill holes in indirect tree based inodes as that could
3349378f32baSMatthew Bobrowski 	 * expose stale data in the case of a crash. Use the magic error code
3350378f32baSMatthew Bobrowski 	 * to fallback to buffered I/O.
3351378f32baSMatthew Bobrowski 	 */
3352378f32baSMatthew Bobrowski 	if (!m_flags && !ret)
3353378f32baSMatthew Bobrowski 		ret = -ENOTBLK;
3354f063db5eSMatthew Bobrowski 
3355f063db5eSMatthew Bobrowski 	ext4_journal_stop(handle);
3356f063db5eSMatthew Bobrowski 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3357f063db5eSMatthew Bobrowski 		goto retry;
3358f063db5eSMatthew Bobrowski 
3359f063db5eSMatthew Bobrowski 	return ret;
3360f063db5eSMatthew Bobrowski }
3361f063db5eSMatthew Bobrowski 
3362f063db5eSMatthew Bobrowski 
3363364443cbSJan Kara static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3364c039b997SGoldwyn Rodrigues 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3365364443cbSJan Kara {
3366364443cbSJan Kara 	int ret;
336709edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
336809edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3369364443cbSJan Kara 
3370bcd8e91fSTheodore Ts'o 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3371bcd8e91fSTheodore Ts'o 		return -EINVAL;
33727046ae35SAndreas Gruenbacher 
3373364443cbSJan Kara 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3374364443cbSJan Kara 		return -ERANGE;
3375364443cbSJan Kara 
337609edf4d3SMatthew Bobrowski 	/*
337709edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical blocks respectively.
337809edf4d3SMatthew Bobrowski 	 */
337909edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
338009edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
338109edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3382364443cbSJan Kara 
33839faac62dSRitesh Harjani 	if (flags & IOMAP_WRITE) {
33849faac62dSRitesh Harjani 		/*
33859faac62dSRitesh Harjani 		 * We check here if the blocks are already allocated, then we
33869faac62dSRitesh Harjani 		 * don't need to start a journal txn and we can directly return
33879faac62dSRitesh Harjani 		 * the mapping information. This could boost performance
33889faac62dSRitesh Harjani 		 * especially in multi-threaded overwrite requests.
33899faac62dSRitesh Harjani 		 */
33909faac62dSRitesh Harjani 		if (offset + length <= i_size_read(inode)) {
3391545052e9SChristoph Hellwig 			ret = ext4_map_blocks(NULL, inode, &map, 0);
33929faac62dSRitesh Harjani 			if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
33939faac62dSRitesh Harjani 				goto out;
33949faac62dSRitesh Harjani 		}
33959faac62dSRitesh Harjani 		ret = ext4_iomap_alloc(inode, &map, flags);
33969faac62dSRitesh Harjani 	} else {
33979faac62dSRitesh Harjani 		ret = ext4_map_blocks(NULL, inode, &map, 0);
33989faac62dSRitesh Harjani 	}
3399f063db5eSMatthew Bobrowski 
3400545052e9SChristoph Hellwig 	if (ret < 0)
3401545052e9SChristoph Hellwig 		return ret;
34029faac62dSRitesh Harjani out:
340338ea50daSEric Biggers 	/*
340438ea50daSEric Biggers 	 * When inline encryption is enabled, sometimes I/O to an encrypted file
340538ea50daSEric Biggers 	 * has to be broken up to guarantee DUN contiguity.  Handle this by
340638ea50daSEric Biggers 	 * limiting the length of the mapping returned.
340738ea50daSEric Biggers 	 */
340838ea50daSEric Biggers 	map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
340938ea50daSEric Biggers 
3410de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3411545052e9SChristoph Hellwig 
3412364443cbSJan Kara 	return 0;
3413364443cbSJan Kara }
3414364443cbSJan Kara 
34158cd115bdSJan Kara static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
34168cd115bdSJan Kara 		loff_t length, unsigned flags, struct iomap *iomap,
34178cd115bdSJan Kara 		struct iomap *srcmap)
34188cd115bdSJan Kara {
34198cd115bdSJan Kara 	int ret;
34208cd115bdSJan Kara 
34218cd115bdSJan Kara 	/*
34228cd115bdSJan Kara 	 * Even for writes we don't need to allocate blocks, so just pretend
34238cd115bdSJan Kara 	 * we are reading to save overhead of starting a transaction.
34248cd115bdSJan Kara 	 */
34258cd115bdSJan Kara 	flags &= ~IOMAP_WRITE;
34268cd115bdSJan Kara 	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3427fa83c34eSBaokun Li 	WARN_ON_ONCE(!ret && iomap->type != IOMAP_MAPPED);
34288cd115bdSJan Kara 	return ret;
34298cd115bdSJan Kara }
34308cd115bdSJan Kara 
3431776722e8SJan Kara static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3432776722e8SJan Kara 			  ssize_t written, unsigned flags, struct iomap *iomap)
3433776722e8SJan Kara {
3434378f32baSMatthew Bobrowski 	/*
3435378f32baSMatthew Bobrowski 	 * Check to see whether an error occurred while writing out the data to
3436378f32baSMatthew Bobrowski 	 * the allocated blocks. If so, return the magic error code so that we
3437378f32baSMatthew Bobrowski 	 * fallback to buffered I/O and attempt to complete the remainder of
3438378f32baSMatthew Bobrowski 	 * the I/O. Any blocks that may have been allocated in preparation for
3439378f32baSMatthew Bobrowski 	 * the direct I/O will be reused during buffered I/O.
3440378f32baSMatthew Bobrowski 	 */
3441378f32baSMatthew Bobrowski 	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3442378f32baSMatthew Bobrowski 		return -ENOTBLK;
3443378f32baSMatthew Bobrowski 
3444776722e8SJan Kara 	return 0;
3445776722e8SJan Kara }
3446776722e8SJan Kara 
34478ff6daa1SChristoph Hellwig const struct iomap_ops ext4_iomap_ops = {
3448364443cbSJan Kara 	.iomap_begin		= ext4_iomap_begin,
3449776722e8SJan Kara 	.iomap_end		= ext4_iomap_end,
3450364443cbSJan Kara };
3451364443cbSJan Kara 
34528cd115bdSJan Kara const struct iomap_ops ext4_iomap_overwrite_ops = {
34538cd115bdSJan Kara 	.iomap_begin		= ext4_iomap_overwrite_begin,
34548cd115bdSJan Kara 	.iomap_end		= ext4_iomap_end,
34558cd115bdSJan Kara };
34568cd115bdSJan Kara 
345709edf4d3SMatthew Bobrowski static bool ext4_iomap_is_delalloc(struct inode *inode,
345809edf4d3SMatthew Bobrowski 				   struct ext4_map_blocks *map)
345909edf4d3SMatthew Bobrowski {
346009edf4d3SMatthew Bobrowski 	struct extent_status es;
346109edf4d3SMatthew Bobrowski 	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
346209edf4d3SMatthew Bobrowski 
346309edf4d3SMatthew Bobrowski 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
346409edf4d3SMatthew Bobrowski 				  map->m_lblk, end, &es);
346509edf4d3SMatthew Bobrowski 
346609edf4d3SMatthew Bobrowski 	if (!es.es_len || es.es_lblk > end)
346709edf4d3SMatthew Bobrowski 		return false;
346809edf4d3SMatthew Bobrowski 
346909edf4d3SMatthew Bobrowski 	if (es.es_lblk > map->m_lblk) {
347009edf4d3SMatthew Bobrowski 		map->m_len = es.es_lblk - map->m_lblk;
347109edf4d3SMatthew Bobrowski 		return false;
347209edf4d3SMatthew Bobrowski 	}
347309edf4d3SMatthew Bobrowski 
347409edf4d3SMatthew Bobrowski 	offset = map->m_lblk - es.es_lblk;
347509edf4d3SMatthew Bobrowski 	map->m_len = es.es_len - offset;
347609edf4d3SMatthew Bobrowski 
347709edf4d3SMatthew Bobrowski 	return true;
347809edf4d3SMatthew Bobrowski }
347909edf4d3SMatthew Bobrowski 
348009edf4d3SMatthew Bobrowski static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
348109edf4d3SMatthew Bobrowski 				   loff_t length, unsigned int flags,
348209edf4d3SMatthew Bobrowski 				   struct iomap *iomap, struct iomap *srcmap)
348309edf4d3SMatthew Bobrowski {
348409edf4d3SMatthew Bobrowski 	int ret;
348509edf4d3SMatthew Bobrowski 	bool delalloc = false;
348609edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
348709edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
348809edf4d3SMatthew Bobrowski 
348909edf4d3SMatthew Bobrowski 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
349009edf4d3SMatthew Bobrowski 		return -EINVAL;
349109edf4d3SMatthew Bobrowski 
34927cb476f8SJan Kara 	if (ext4_has_inline_data(inode)) {
34937cb476f8SJan Kara 		ret = ext4_inline_data_iomap(inode, iomap);
3494ba5843f5SJan Kara 		if (ret != -EAGAIN) {
3495ed923b57SMatthew Wilcox 			if (ret == 0 && offset >= iomap->length)
3496ba5843f5SJan Kara 				ret = -ENOENT;
3497ba5843f5SJan Kara 			return ret;
3498ba5843f5SJan Kara 		}
3499ba5843f5SJan Kara 	}
350012735f88SJan Kara 
350109edf4d3SMatthew Bobrowski 	/*
350209edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical block respectively.
350309edf4d3SMatthew Bobrowski 	 */
350409edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
350509edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
350609edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
350712735f88SJan Kara 
3508b2c57642SRitesh Harjani 	/*
3509b2c57642SRitesh Harjani 	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3510b2c57642SRitesh Harjani 	 * So handle it here itself instead of querying ext4_map_blocks().
3511b2c57642SRitesh Harjani 	 * Since ext4_map_blocks() will warn about it and will return
3512b2c57642SRitesh Harjani 	 * -EIO error.
3513b2c57642SRitesh Harjani 	 */
3514b2c57642SRitesh Harjani 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3515b2c57642SRitesh Harjani 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3516b2c57642SRitesh Harjani 
3517b2c57642SRitesh Harjani 		if (offset >= sbi->s_bitmap_maxbytes) {
3518b2c57642SRitesh Harjani 			map.m_flags = 0;
3519b2c57642SRitesh Harjani 			goto set_iomap;
3520b2c57642SRitesh Harjani 		}
3521b2c57642SRitesh Harjani 	}
3522b2c57642SRitesh Harjani 
352312735f88SJan Kara 	ret = ext4_map_blocks(NULL, inode, &map, 0);
3524ba5843f5SJan Kara 	if (ret < 0)
3525ba5843f5SJan Kara 		return ret;
3526914f82a3SJan Kara 	if (ret == 0)
352709edf4d3SMatthew Bobrowski 		delalloc = ext4_iomap_is_delalloc(inode, &map);
352809edf4d3SMatthew Bobrowski 
3529b2c57642SRitesh Harjani set_iomap:
3530de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
353109edf4d3SMatthew Bobrowski 	if (delalloc && iomap->type == IOMAP_HOLE)
353209edf4d3SMatthew Bobrowski 		iomap->type = IOMAP_DELALLOC;
353309edf4d3SMatthew Bobrowski 
353409edf4d3SMatthew Bobrowski 	return 0;
3535914f82a3SJan Kara }
3536914f82a3SJan Kara 
353709edf4d3SMatthew Bobrowski const struct iomap_ops ext4_iomap_report_ops = {
353809edf4d3SMatthew Bobrowski 	.iomap_begin = ext4_iomap_begin_report,
353909edf4d3SMatthew Bobrowski };
35404c0425ffSMingming Cao 
3541ac27a0ecSDave Kleikamp /*
35423f5d3063SJan Kara  * For data=journal mode, folio should be marked dirty only when it was
35433f5d3063SJan Kara  * writeably mapped. When that happens, it was already attached to the
35443f5d3063SJan Kara  * transaction and marked as jbddirty (we take care of this in
35453f5d3063SJan Kara  * ext4_page_mkwrite()). On transaction commit, we writeprotect page mappings
35463f5d3063SJan Kara  * so we should have nothing to do here, except for the case when someone
35473f5d3063SJan Kara  * had the page pinned and dirtied the page through this pin (e.g. by doing
35483f5d3063SJan Kara  * direct IO to it). In that case we'd need to attach buffers here to the
35493f5d3063SJan Kara  * transaction but we cannot due to lock ordering.  We cannot just dirty the
35503f5d3063SJan Kara  * folio and leave attached buffers clean, because the buffers' dirty state is
35513f5d3063SJan Kara  * "definitive".  We cannot just set the buffers dirty or jbddirty because all
35523f5d3063SJan Kara  * the journalling code will explode.  So what we do is to mark the folio
35533f5d3063SJan Kara  * "pending dirty" and next time ext4_writepages() is called, attach buffers
35543f5d3063SJan Kara  * to the transaction appropriately.
3555ac27a0ecSDave Kleikamp  */
3556187c82cbSMatthew Wilcox (Oracle) static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3557187c82cbSMatthew Wilcox (Oracle) 		struct folio *folio)
3558ac27a0ecSDave Kleikamp {
35590f252336SMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
35603f5d3063SJan Kara 	if (folio_maybe_dma_pinned(folio))
3561187c82cbSMatthew Wilcox (Oracle) 		folio_set_checked(folio);
3562187c82cbSMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
3563ac27a0ecSDave Kleikamp }
3564ac27a0ecSDave Kleikamp 
3565e621900aSMatthew Wilcox (Oracle) static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
35666dcc693bSJan Kara {
3567e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3568e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
3569e621900aSMatthew Wilcox (Oracle) 	return block_dirty_folio(mapping, folio);
35706dcc693bSJan Kara }
35716dcc693bSJan Kara 
35720e6895baSRitesh Harjani static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
35730e6895baSRitesh Harjani 				    struct file *file, sector_t *span)
35740e6895baSRitesh Harjani {
35750e6895baSRitesh Harjani 	return iomap_swapfile_activate(sis, file, span,
35760e6895baSRitesh Harjani 				       &ext4_iomap_report_ops);
35770e6895baSRitesh Harjani }
35780e6895baSRitesh Harjani 
357974d553aaSTheodore Ts'o static const struct address_space_operations ext4_aops = {
3580fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
35816311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
358220970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3583bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
358474d553aaSTheodore Ts'o 	.write_end		= ext4_write_end,
3585e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
3586617ba13bSMingming Cao 	.bmap			= ext4_bmap,
35877ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
35883c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3589378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
359067235182SMatthew Wilcox (Oracle) 	.migrate_folio		= buffer_migrate_folio,
35918ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3592aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
35930e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3594ac27a0ecSDave Kleikamp };
3595ac27a0ecSDave Kleikamp 
3596617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
3597fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
35986311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
359920970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3600bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
3601bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
3602187c82cbSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_journalled_dirty_folio,
3603617ba13bSMingming Cao 	.bmap			= ext4_bmap,
3604ccd16945SMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_journalled_invalidate_folio,
36053c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3606378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
3607dae99960SJan Kara 	.migrate_folio		= buffer_migrate_folio_norefs,
36088ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3609aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36100e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3611ac27a0ecSDave Kleikamp };
3612ac27a0ecSDave Kleikamp 
361364769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
3614fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
36156311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
361620970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
361764769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
361864769240SAlex Tomas 	.write_end		= ext4_da_write_end,
3619e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
362064769240SAlex Tomas 	.bmap			= ext4_bmap,
36217ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
36223c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3623378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
362467235182SMatthew Wilcox (Oracle) 	.migrate_folio		= buffer_migrate_folio,
36258ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3626aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36270e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
362864769240SAlex Tomas };
362964769240SAlex Tomas 
36305f0663bbSDan Williams static const struct address_space_operations ext4_dax_aops = {
36315f0663bbSDan Williams 	.writepages		= ext4_dax_writepages,
36325f0663bbSDan Williams 	.direct_IO		= noop_direct_IO,
363346de8b97SMatthew Wilcox (Oracle) 	.dirty_folio		= noop_dirty_folio,
363494dbb631SToshi Kani 	.bmap			= ext4_bmap,
36350e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
36365f0663bbSDan Williams };
36375f0663bbSDan Williams 
3638617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
3639ac27a0ecSDave Kleikamp {
36403d2b1582SLukas Czerner 	switch (ext4_inode_journal_mode(inode)) {
36413d2b1582SLukas Czerner 	case EXT4_INODE_ORDERED_DATA_MODE:
36423d2b1582SLukas Czerner 	case EXT4_INODE_WRITEBACK_DATA_MODE:
36433d2b1582SLukas Czerner 		break;
36443d2b1582SLukas Czerner 	case EXT4_INODE_JOURNAL_DATA_MODE:
3645617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
364674d553aaSTheodore Ts'o 		return;
36473d2b1582SLukas Czerner 	default:
36483d2b1582SLukas Czerner 		BUG();
36493d2b1582SLukas Czerner 	}
36505f0663bbSDan Williams 	if (IS_DAX(inode))
36515f0663bbSDan Williams 		inode->i_mapping->a_ops = &ext4_dax_aops;
36525f0663bbSDan Williams 	else if (test_opt(inode->i_sb, DELALLOC))
365374d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_da_aops;
365474d553aaSTheodore Ts'o 	else
365574d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_aops;
3656ac27a0ecSDave Kleikamp }
3657ac27a0ecSDave Kleikamp 
3658923ae0ffSRoss Zwisler static int __ext4_block_zero_page_range(handle_t *handle,
3659d863dc36SLukas Czerner 		struct address_space *mapping, loff_t from, loff_t length)
3660d863dc36SLukas Czerner {
366109cbfeafSKirill A. Shutemov 	ext4_fsblk_t index = from >> PAGE_SHIFT;
366209cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3663923ae0ffSRoss Zwisler 	unsigned blocksize, pos;
3664d863dc36SLukas Czerner 	ext4_lblk_t iblock;
3665d863dc36SLukas Czerner 	struct inode *inode = mapping->host;
3666d863dc36SLukas Czerner 	struct buffer_head *bh;
36679d3973deSMatthew Wilcox 	struct folio *folio;
3668d863dc36SLukas Czerner 	int err = 0;
3669d863dc36SLukas Czerner 
36709d3973deSMatthew Wilcox 	folio = __filemap_get_folio(mapping, from >> PAGE_SHIFT,
36719d3973deSMatthew Wilcox 				    FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
3672c62d2555SMichal Hocko 				    mapping_gfp_constraint(mapping, ~__GFP_FS));
36737fa8a8eeSLinus Torvalds 	if (IS_ERR(folio))
36747fa8a8eeSLinus Torvalds 		return PTR_ERR(folio);
3675d863dc36SLukas Czerner 
3676d863dc36SLukas Czerner 	blocksize = inode->i_sb->s_blocksize;
3677d863dc36SLukas Czerner 
367809cbfeafSKirill A. Shutemov 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3679d863dc36SLukas Czerner 
36809d3973deSMatthew Wilcox 	bh = folio_buffers(folio);
36819d3973deSMatthew Wilcox 	if (!bh) {
36829d3973deSMatthew Wilcox 		create_empty_buffers(&folio->page, blocksize, 0);
36839d3973deSMatthew Wilcox 		bh = folio_buffers(folio);
36849d3973deSMatthew Wilcox 	}
3685d863dc36SLukas Czerner 
3686d863dc36SLukas Czerner 	/* Find the buffer that contains "offset" */
3687d863dc36SLukas Czerner 	pos = blocksize;
3688d863dc36SLukas Czerner 	while (offset >= pos) {
3689d863dc36SLukas Czerner 		bh = bh->b_this_page;
3690d863dc36SLukas Czerner 		iblock++;
3691d863dc36SLukas Czerner 		pos += blocksize;
3692d863dc36SLukas Czerner 	}
3693d863dc36SLukas Czerner 	if (buffer_freed(bh)) {
3694d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "freed: skip");
3695d863dc36SLukas Czerner 		goto unlock;
3696d863dc36SLukas Czerner 	}
3697d863dc36SLukas Czerner 	if (!buffer_mapped(bh)) {
3698d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "unmapped");
3699d863dc36SLukas Czerner 		ext4_get_block(inode, iblock, bh, 0);
3700d863dc36SLukas Czerner 		/* unmapped? It's a hole - nothing to do */
3701d863dc36SLukas Czerner 		if (!buffer_mapped(bh)) {
3702d863dc36SLukas Czerner 			BUFFER_TRACE(bh, "still unmapped");
3703d863dc36SLukas Czerner 			goto unlock;
3704d863dc36SLukas Czerner 		}
3705d863dc36SLukas Czerner 	}
3706d863dc36SLukas Czerner 
3707d863dc36SLukas Czerner 	/* Ok, it's mapped. Make sure it's up-to-date */
37089d3973deSMatthew Wilcox 	if (folio_test_uptodate(folio))
3709d863dc36SLukas Czerner 		set_buffer_uptodate(bh);
3710d863dc36SLukas Czerner 
3711d863dc36SLukas Czerner 	if (!buffer_uptodate(bh)) {
37122d069c08Szhangyi (F) 		err = ext4_read_bh_lock(bh, 0, true);
37132d069c08Szhangyi (F) 		if (err)
3714d863dc36SLukas Czerner 			goto unlock;
37154f74d15fSEric Biggers 		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3716c9c7429cSMichael Halcrow 			/* We expect the key to be set. */
3717a7550b30SJaegeuk Kim 			BUG_ON(!fscrypt_has_encryption_key(inode));
37189d3973deSMatthew Wilcox 			err = fscrypt_decrypt_pagecache_blocks(folio,
371951e4e315SEric Biggers 							       blocksize,
3720834f1565SEric Biggers 							       bh_offset(bh));
3721834f1565SEric Biggers 			if (err) {
3722834f1565SEric Biggers 				clear_buffer_uptodate(bh);
3723834f1565SEric Biggers 				goto unlock;
3724834f1565SEric Biggers 			}
3725c9c7429cSMichael Halcrow 		}
3726d863dc36SLukas Czerner 	}
3727d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3728d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "get write access");
3729188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
3730188c299eSJan Kara 						    EXT4_JTR_NONE);
3731d863dc36SLukas Czerner 		if (err)
3732d863dc36SLukas Czerner 			goto unlock;
3733d863dc36SLukas Czerner 	}
37349d3973deSMatthew Wilcox 	folio_zero_range(folio, offset, length);
3735d863dc36SLukas Czerner 	BUFFER_TRACE(bh, "zeroed end of block");
3736d863dc36SLukas Czerner 
3737d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3738d84c9ebdSJan Kara 		err = ext4_dirty_journalled_data(handle, bh);
37390713ed0cSLukas Czerner 	} else {
3740353eefd3Sjon ernst 		err = 0;
3741d863dc36SLukas Czerner 		mark_buffer_dirty(bh);
37423957ef53SJan Kara 		if (ext4_should_order_data(inode))
374373131fbbSRoss Zwisler 			err = ext4_jbd2_inode_add_write(handle, inode, from,
374473131fbbSRoss Zwisler 					length);
37450713ed0cSLukas Czerner 	}
3746d863dc36SLukas Czerner 
3747d863dc36SLukas Czerner unlock:
37489d3973deSMatthew Wilcox 	folio_unlock(folio);
37499d3973deSMatthew Wilcox 	folio_put(folio);
3750d863dc36SLukas Czerner 	return err;
3751d863dc36SLukas Czerner }
3752d863dc36SLukas Czerner 
375394350ab5SMatthew Wilcox /*
3754923ae0ffSRoss Zwisler  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3755923ae0ffSRoss Zwisler  * starting from file offset 'from'.  The range to be zero'd must
3756923ae0ffSRoss Zwisler  * be contained with in one block.  If the specified range exceeds
3757923ae0ffSRoss Zwisler  * the end of the block it will be shortened to end of the block
37583088e5a5SBhaskar Chowdhury  * that corresponds to 'from'
3759923ae0ffSRoss Zwisler  */
3760923ae0ffSRoss Zwisler static int ext4_block_zero_page_range(handle_t *handle,
3761923ae0ffSRoss Zwisler 		struct address_space *mapping, loff_t from, loff_t length)
3762923ae0ffSRoss Zwisler {
3763923ae0ffSRoss Zwisler 	struct inode *inode = mapping->host;
376409cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3765923ae0ffSRoss Zwisler 	unsigned blocksize = inode->i_sb->s_blocksize;
3766923ae0ffSRoss Zwisler 	unsigned max = blocksize - (offset & (blocksize - 1));
3767923ae0ffSRoss Zwisler 
3768923ae0ffSRoss Zwisler 	/*
3769923ae0ffSRoss Zwisler 	 * correct length if it does not fall between
3770923ae0ffSRoss Zwisler 	 * 'from' and the end of the block
3771923ae0ffSRoss Zwisler 	 */
3772923ae0ffSRoss Zwisler 	if (length > max || length < 0)
3773923ae0ffSRoss Zwisler 		length = max;
3774923ae0ffSRoss Zwisler 
377547e69351SJan Kara 	if (IS_DAX(inode)) {
3776c6f40468SChristoph Hellwig 		return dax_zero_range(inode, from, length, NULL,
377747e69351SJan Kara 				      &ext4_iomap_ops);
377847e69351SJan Kara 	}
3779923ae0ffSRoss Zwisler 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3780923ae0ffSRoss Zwisler }
3781923ae0ffSRoss Zwisler 
3782923ae0ffSRoss Zwisler /*
378394350ab5SMatthew Wilcox  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
378494350ab5SMatthew Wilcox  * up to the end of the block which corresponds to `from'.
378594350ab5SMatthew Wilcox  * This required during truncate. We need to physically zero the tail end
378694350ab5SMatthew Wilcox  * of that block so it doesn't yield old data if the file is later grown.
378794350ab5SMatthew Wilcox  */
3788c197855eSStephen Hemminger static int ext4_block_truncate_page(handle_t *handle,
378994350ab5SMatthew Wilcox 		struct address_space *mapping, loff_t from)
379094350ab5SMatthew Wilcox {
379109cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
379294350ab5SMatthew Wilcox 	unsigned length;
379394350ab5SMatthew Wilcox 	unsigned blocksize;
379494350ab5SMatthew Wilcox 	struct inode *inode = mapping->host;
379594350ab5SMatthew Wilcox 
37960d06863fSTheodore Ts'o 	/* If we are processing an encrypted inode during orphan list handling */
3797592ddec7SChandan Rajendra 	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
37980d06863fSTheodore Ts'o 		return 0;
37990d06863fSTheodore Ts'o 
380094350ab5SMatthew Wilcox 	blocksize = inode->i_sb->s_blocksize;
380194350ab5SMatthew Wilcox 	length = blocksize - (offset & (blocksize - 1));
380294350ab5SMatthew Wilcox 
380394350ab5SMatthew Wilcox 	return ext4_block_zero_page_range(handle, mapping, from, length);
380494350ab5SMatthew Wilcox }
380594350ab5SMatthew Wilcox 
3806a87dd18cSLukas Czerner int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3807a87dd18cSLukas Czerner 			     loff_t lstart, loff_t length)
3808a87dd18cSLukas Czerner {
3809a87dd18cSLukas Czerner 	struct super_block *sb = inode->i_sb;
3810a87dd18cSLukas Czerner 	struct address_space *mapping = inode->i_mapping;
3811e1be3a92SLukas Czerner 	unsigned partial_start, partial_end;
3812a87dd18cSLukas Czerner 	ext4_fsblk_t start, end;
3813a87dd18cSLukas Czerner 	loff_t byte_end = (lstart + length - 1);
3814a87dd18cSLukas Czerner 	int err = 0;
3815a87dd18cSLukas Czerner 
3816e1be3a92SLukas Czerner 	partial_start = lstart & (sb->s_blocksize - 1);
3817e1be3a92SLukas Czerner 	partial_end = byte_end & (sb->s_blocksize - 1);
3818e1be3a92SLukas Czerner 
3819a87dd18cSLukas Czerner 	start = lstart >> sb->s_blocksize_bits;
3820a87dd18cSLukas Czerner 	end = byte_end >> sb->s_blocksize_bits;
3821a87dd18cSLukas Czerner 
3822a87dd18cSLukas Czerner 	/* Handle partial zero within the single block */
3823e1be3a92SLukas Czerner 	if (start == end &&
3824e1be3a92SLukas Czerner 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3825a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3826a87dd18cSLukas Czerner 						 lstart, length);
3827a87dd18cSLukas Czerner 		return err;
3828a87dd18cSLukas Czerner 	}
3829a87dd18cSLukas Czerner 	/* Handle partial zero out on the start of the range */
3830e1be3a92SLukas Czerner 	if (partial_start) {
3831a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3832a87dd18cSLukas Czerner 						 lstart, sb->s_blocksize);
3833a87dd18cSLukas Czerner 		if (err)
3834a87dd18cSLukas Czerner 			return err;
3835a87dd18cSLukas Czerner 	}
3836a87dd18cSLukas Czerner 	/* Handle partial zero out on the end of the range */
3837e1be3a92SLukas Czerner 	if (partial_end != sb->s_blocksize - 1)
3838a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3839e1be3a92SLukas Czerner 						 byte_end - partial_end,
3840e1be3a92SLukas Czerner 						 partial_end + 1);
3841a87dd18cSLukas Czerner 	return err;
3842a87dd18cSLukas Czerner }
3843a87dd18cSLukas Czerner 
384491ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
384591ef4cafSDuane Griffin {
384691ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
384791ef4cafSDuane Griffin 		return 1;
384891ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
384991ef4cafSDuane Griffin 		return 1;
385091ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
385191ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
385291ef4cafSDuane Griffin 	return 0;
385391ef4cafSDuane Griffin }
385491ef4cafSDuane Griffin 
3855ac27a0ecSDave Kleikamp /*
385601127848SJan Kara  * We have to make sure i_disksize gets properly updated before we truncate
385701127848SJan Kara  * page cache due to hole punching or zero range. Otherwise i_disksize update
385801127848SJan Kara  * can get lost as it may have been postponed to submission of writeback but
385901127848SJan Kara  * that will never happen after we truncate page cache.
386001127848SJan Kara  */
386101127848SJan Kara int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
386201127848SJan Kara 				      loff_t len)
386301127848SJan Kara {
386401127848SJan Kara 	handle_t *handle;
38654209ae12SHarshad Shirwadkar 	int ret;
38664209ae12SHarshad Shirwadkar 
386701127848SJan Kara 	loff_t size = i_size_read(inode);
386801127848SJan Kara 
38695955102cSAl Viro 	WARN_ON(!inode_is_locked(inode));
387001127848SJan Kara 	if (offset > size || offset + len < size)
387101127848SJan Kara 		return 0;
387201127848SJan Kara 
387301127848SJan Kara 	if (EXT4_I(inode)->i_disksize >= size)
387401127848SJan Kara 		return 0;
387501127848SJan Kara 
387601127848SJan Kara 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
387701127848SJan Kara 	if (IS_ERR(handle))
387801127848SJan Kara 		return PTR_ERR(handle);
387901127848SJan Kara 	ext4_update_i_disksize(inode, size);
38804209ae12SHarshad Shirwadkar 	ret = ext4_mark_inode_dirty(handle, inode);
388101127848SJan Kara 	ext4_journal_stop(handle);
388201127848SJan Kara 
38834209ae12SHarshad Shirwadkar 	return ret;
388401127848SJan Kara }
388501127848SJan Kara 
3886d4f5258eSJan Kara static void ext4_wait_dax_page(struct inode *inode)
3887430657b6SRoss Zwisler {
3888d4f5258eSJan Kara 	filemap_invalidate_unlock(inode->i_mapping);
3889430657b6SRoss Zwisler 	schedule();
3890d4f5258eSJan Kara 	filemap_invalidate_lock(inode->i_mapping);
3891430657b6SRoss Zwisler }
3892430657b6SRoss Zwisler 
3893430657b6SRoss Zwisler int ext4_break_layouts(struct inode *inode)
3894430657b6SRoss Zwisler {
3895430657b6SRoss Zwisler 	struct page *page;
3896430657b6SRoss Zwisler 	int error;
3897430657b6SRoss Zwisler 
3898d4f5258eSJan Kara 	if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
3899430657b6SRoss Zwisler 		return -EINVAL;
3900430657b6SRoss Zwisler 
3901430657b6SRoss Zwisler 	do {
3902430657b6SRoss Zwisler 		page = dax_layout_busy_page(inode->i_mapping);
3903430657b6SRoss Zwisler 		if (!page)
3904430657b6SRoss Zwisler 			return 0;
3905430657b6SRoss Zwisler 
3906430657b6SRoss Zwisler 		error = ___wait_var_event(&page->_refcount,
3907430657b6SRoss Zwisler 				atomic_read(&page->_refcount) == 1,
3908430657b6SRoss Zwisler 				TASK_INTERRUPTIBLE, 0, 0,
3909d4f5258eSJan Kara 				ext4_wait_dax_page(inode));
3910b1f38217SRoss Zwisler 	} while (error == 0);
3911430657b6SRoss Zwisler 
3912430657b6SRoss Zwisler 	return error;
3913430657b6SRoss Zwisler }
3914430657b6SRoss Zwisler 
391501127848SJan Kara /*
3916cca32b7eSRoss Zwisler  * ext4_punch_hole: punches a hole in a file by releasing the blocks
3917a4bb6b64SAllison Henderson  * associated with the given offset and length
3918a4bb6b64SAllison Henderson  *
3919a4bb6b64SAllison Henderson  * @inode:  File inode
3920a4bb6b64SAllison Henderson  * @offset: The offset where the hole will begin
3921a4bb6b64SAllison Henderson  * @len:    The length of the hole
3922a4bb6b64SAllison Henderson  *
39234907cb7bSAnatol Pomozov  * Returns: 0 on success or negative on failure
3924a4bb6b64SAllison Henderson  */
3925a4bb6b64SAllison Henderson 
3926ad5cd4f4SDarrick J. Wong int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3927a4bb6b64SAllison Henderson {
3928ad5cd4f4SDarrick J. Wong 	struct inode *inode = file_inode(file);
392926a4c0c6STheodore Ts'o 	struct super_block *sb = inode->i_sb;
393026a4c0c6STheodore Ts'o 	ext4_lblk_t first_block, stop_block;
393126a4c0c6STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
39322da37622STadeusz Struk 	loff_t first_block_offset, last_block_offset, max_length;
39332da37622STadeusz Struk 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
393426a4c0c6STheodore Ts'o 	handle_t *handle;
393526a4c0c6STheodore Ts'o 	unsigned int credits;
39364209ae12SHarshad Shirwadkar 	int ret = 0, ret2 = 0;
393726a4c0c6STheodore Ts'o 
3938b8a86845SLukas Czerner 	trace_ext4_punch_hole(inode, offset, length, 0);
3939aaddea81SZheng Liu 
394026a4c0c6STheodore Ts'o 	/*
394126a4c0c6STheodore Ts'o 	 * Write out all dirty pages to avoid race conditions
394226a4c0c6STheodore Ts'o 	 * Then release them.
394326a4c0c6STheodore Ts'o 	 */
3944cca32b7eSRoss Zwisler 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
394526a4c0c6STheodore Ts'o 		ret = filemap_write_and_wait_range(mapping, offset,
394626a4c0c6STheodore Ts'o 						   offset + length - 1);
394726a4c0c6STheodore Ts'o 		if (ret)
394826a4c0c6STheodore Ts'o 			return ret;
394926a4c0c6STheodore Ts'o 	}
395026a4c0c6STheodore Ts'o 
39515955102cSAl Viro 	inode_lock(inode);
39529ef06cecSLukas Czerner 
395326a4c0c6STheodore Ts'o 	/* No need to punch hole beyond i_size */
395426a4c0c6STheodore Ts'o 	if (offset >= inode->i_size)
395526a4c0c6STheodore Ts'o 		goto out_mutex;
395626a4c0c6STheodore Ts'o 
395726a4c0c6STheodore Ts'o 	/*
395826a4c0c6STheodore Ts'o 	 * If the hole extends beyond i_size, set the hole
395926a4c0c6STheodore Ts'o 	 * to end after the page that contains i_size
396026a4c0c6STheodore Ts'o 	 */
396126a4c0c6STheodore Ts'o 	if (offset + length > inode->i_size) {
396226a4c0c6STheodore Ts'o 		length = inode->i_size +
396309cbfeafSKirill A. Shutemov 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
396426a4c0c6STheodore Ts'o 		   offset;
396526a4c0c6STheodore Ts'o 	}
396626a4c0c6STheodore Ts'o 
39672da37622STadeusz Struk 	/*
39682da37622STadeusz Struk 	 * For punch hole the length + offset needs to be within one block
39692da37622STadeusz Struk 	 * before last range. Adjust the length if it goes beyond that limit.
39702da37622STadeusz Struk 	 */
39712da37622STadeusz Struk 	max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
39722da37622STadeusz Struk 	if (offset + length > max_length)
39732da37622STadeusz Struk 		length = max_length - offset;
39742da37622STadeusz Struk 
3975a361293fSJan Kara 	if (offset & (sb->s_blocksize - 1) ||
3976a361293fSJan Kara 	    (offset + length) & (sb->s_blocksize - 1)) {
3977a361293fSJan Kara 		/*
3978a361293fSJan Kara 		 * Attach jinode to inode for jbd2 if we do any zeroing of
3979a361293fSJan Kara 		 * partial block
3980a361293fSJan Kara 		 */
3981a361293fSJan Kara 		ret = ext4_inode_attach_jinode(inode);
3982a361293fSJan Kara 		if (ret < 0)
3983a361293fSJan Kara 			goto out_mutex;
3984a361293fSJan Kara 
3985a361293fSJan Kara 	}
3986a361293fSJan Kara 
3987f340b3d9Shongnanli 	/* Wait all existing dio workers, newcomers will block on i_rwsem */
3988ea3d7209SJan Kara 	inode_dio_wait(inode);
3989ea3d7209SJan Kara 
3990ad5cd4f4SDarrick J. Wong 	ret = file_modified(file);
3991ad5cd4f4SDarrick J. Wong 	if (ret)
3992ad5cd4f4SDarrick J. Wong 		goto out_mutex;
3993ad5cd4f4SDarrick J. Wong 
3994ea3d7209SJan Kara 	/*
3995ea3d7209SJan Kara 	 * Prevent page faults from reinstantiating pages we have released from
3996ea3d7209SJan Kara 	 * page cache.
3997ea3d7209SJan Kara 	 */
3998d4f5258eSJan Kara 	filemap_invalidate_lock(mapping);
3999430657b6SRoss Zwisler 
4000430657b6SRoss Zwisler 	ret = ext4_break_layouts(inode);
4001430657b6SRoss Zwisler 	if (ret)
4002430657b6SRoss Zwisler 		goto out_dio;
4003430657b6SRoss Zwisler 
4004a87dd18cSLukas Czerner 	first_block_offset = round_up(offset, sb->s_blocksize);
4005a87dd18cSLukas Czerner 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
400626a4c0c6STheodore Ts'o 
4007a87dd18cSLukas Czerner 	/* Now release the pages and zero block aligned part of pages*/
400801127848SJan Kara 	if (last_block_offset > first_block_offset) {
400901127848SJan Kara 		ret = ext4_update_disksize_before_punch(inode, offset, length);
401001127848SJan Kara 		if (ret)
401101127848SJan Kara 			goto out_dio;
4012a87dd18cSLukas Czerner 		truncate_pagecache_range(inode, first_block_offset,
4013a87dd18cSLukas Czerner 					 last_block_offset);
401401127848SJan Kara 	}
401526a4c0c6STheodore Ts'o 
401626a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
401726a4c0c6STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
401826a4c0c6STheodore Ts'o 	else
401926a4c0c6STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
402026a4c0c6STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
402126a4c0c6STheodore Ts'o 	if (IS_ERR(handle)) {
402226a4c0c6STheodore Ts'o 		ret = PTR_ERR(handle);
402326a4c0c6STheodore Ts'o 		ext4_std_error(sb, ret);
402426a4c0c6STheodore Ts'o 		goto out_dio;
402526a4c0c6STheodore Ts'o 	}
402626a4c0c6STheodore Ts'o 
4027a87dd18cSLukas Czerner 	ret = ext4_zero_partial_blocks(handle, inode, offset,
4028a87dd18cSLukas Czerner 				       length);
402926a4c0c6STheodore Ts'o 	if (ret)
403026a4c0c6STheodore Ts'o 		goto out_stop;
403126a4c0c6STheodore Ts'o 
403226a4c0c6STheodore Ts'o 	first_block = (offset + sb->s_blocksize - 1) >>
403326a4c0c6STheodore Ts'o 		EXT4_BLOCK_SIZE_BITS(sb);
403426a4c0c6STheodore Ts'o 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
403526a4c0c6STheodore Ts'o 
4036eee597acSLukas Czerner 	/* If there are blocks to remove, do it */
4037eee597acSLukas Czerner 	if (stop_block > first_block) {
403826a4c0c6STheodore Ts'o 
403926a4c0c6STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
404027bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
404126a4c0c6STheodore Ts'o 
4042ed5d285bSBaokun Li 		ext4_es_remove_extent(inode, first_block,
404326a4c0c6STheodore Ts'o 				      stop_block - first_block);
404426a4c0c6STheodore Ts'o 
404526a4c0c6STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
404626a4c0c6STheodore Ts'o 			ret = ext4_ext_remove_space(inode, first_block,
404726a4c0c6STheodore Ts'o 						    stop_block - 1);
404826a4c0c6STheodore Ts'o 		else
40494f579ae7SLukas Czerner 			ret = ext4_ind_remove_space(handle, inode, first_block,
405026a4c0c6STheodore Ts'o 						    stop_block);
405126a4c0c6STheodore Ts'o 
4052819c4920STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
4053eee597acSLukas Czerner 	}
4054a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_range(handle, inode, first_block, stop_block);
405526a4c0c6STheodore Ts'o 	if (IS_SYNC(inode))
405626a4c0c6STheodore Ts'o 		ext4_handle_sync(handle);
4057e251f9bcSMaxim Patlasov 
40581bc33893SJeff Layton 	inode->i_mtime = inode_set_ctime_current(inode);
40594209ae12SHarshad Shirwadkar 	ret2 = ext4_mark_inode_dirty(handle, inode);
40604209ae12SHarshad Shirwadkar 	if (unlikely(ret2))
40614209ae12SHarshad Shirwadkar 		ret = ret2;
406267a7d5f5SJan Kara 	if (ret >= 0)
406367a7d5f5SJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
406426a4c0c6STheodore Ts'o out_stop:
406526a4c0c6STheodore Ts'o 	ext4_journal_stop(handle);
406626a4c0c6STheodore Ts'o out_dio:
4067d4f5258eSJan Kara 	filemap_invalidate_unlock(mapping);
406826a4c0c6STheodore Ts'o out_mutex:
40695955102cSAl Viro 	inode_unlock(inode);
407026a4c0c6STheodore Ts'o 	return ret;
4071a4bb6b64SAllison Henderson }
4072a4bb6b64SAllison Henderson 
4073a361293fSJan Kara int ext4_inode_attach_jinode(struct inode *inode)
4074a361293fSJan Kara {
4075a361293fSJan Kara 	struct ext4_inode_info *ei = EXT4_I(inode);
4076a361293fSJan Kara 	struct jbd2_inode *jinode;
4077a361293fSJan Kara 
4078a361293fSJan Kara 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4079a361293fSJan Kara 		return 0;
4080a361293fSJan Kara 
4081a361293fSJan Kara 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4082a361293fSJan Kara 	spin_lock(&inode->i_lock);
4083a361293fSJan Kara 	if (!ei->jinode) {
4084a361293fSJan Kara 		if (!jinode) {
4085a361293fSJan Kara 			spin_unlock(&inode->i_lock);
4086a361293fSJan Kara 			return -ENOMEM;
4087a361293fSJan Kara 		}
4088a361293fSJan Kara 		ei->jinode = jinode;
4089a361293fSJan Kara 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4090a361293fSJan Kara 		jinode = NULL;
4091a361293fSJan Kara 	}
4092a361293fSJan Kara 	spin_unlock(&inode->i_lock);
4093a361293fSJan Kara 	if (unlikely(jinode != NULL))
4094a361293fSJan Kara 		jbd2_free_inode(jinode);
4095a361293fSJan Kara 	return 0;
4096a361293fSJan Kara }
4097a361293fSJan Kara 
4098a4bb6b64SAllison Henderson /*
4099617ba13bSMingming Cao  * ext4_truncate()
4100ac27a0ecSDave Kleikamp  *
4101617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
4102617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4103ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
4104ac27a0ecSDave Kleikamp  *
410542b2aa86SJustin P. Mattock  * As we work through the truncate and commit bits of it to the journal there
4106ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
4107ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
4108ac27a0ecSDave Kleikamp  *
4109ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
4110ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
4111ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
4112ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
4113ac27a0ecSDave Kleikamp  * left-to-right works OK too).
4114ac27a0ecSDave Kleikamp  *
4115ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
4116ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
4117ac27a0ecSDave Kleikamp  *
4118ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
4119617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4120ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
4121617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
4122617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
4123ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
4124617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
4125ac27a0ecSDave Kleikamp  */
41262c98eb5eSTheodore Ts'o int ext4_truncate(struct inode *inode)
4127ac27a0ecSDave Kleikamp {
4128819c4920STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
4129819c4920STheodore Ts'o 	unsigned int credits;
41304209ae12SHarshad Shirwadkar 	int err = 0, err2;
4131819c4920STheodore Ts'o 	handle_t *handle;
4132819c4920STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
4133819c4920STheodore Ts'o 
413419b5ef61STheodore Ts'o 	/*
413519b5ef61STheodore Ts'o 	 * There is a possibility that we're either freeing the inode
4136e04027e8SMatthew Wilcox 	 * or it's a completely new inode. In those cases we might not
4137f340b3d9Shongnanli 	 * have i_rwsem locked because it's not necessary.
413819b5ef61STheodore Ts'o 	 */
413919b5ef61STheodore Ts'o 	if (!(inode->i_state & (I_NEW|I_FREEING)))
41405955102cSAl Viro 		WARN_ON(!inode_is_locked(inode));
41410562e0baSJiaying Zhang 	trace_ext4_truncate_enter(inode);
41420562e0baSJiaying Zhang 
414391ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
41449a5d265fSzhengliang 		goto out_trace;
4145ac27a0ecSDave Kleikamp 
41465534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
414719f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
41487d8f9f7dSTheodore Ts'o 
4149aef1c851STao Ma 	if (ext4_has_inline_data(inode)) {
4150aef1c851STao Ma 		int has_inline = 1;
4151aef1c851STao Ma 
415201daf945STheodore Ts'o 		err = ext4_inline_data_truncate(inode, &has_inline);
41539a5d265fSzhengliang 		if (err || has_inline)
41549a5d265fSzhengliang 			goto out_trace;
4155aef1c851STao Ma 	}
4156aef1c851STao Ma 
4157a361293fSJan Kara 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4158a361293fSJan Kara 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4159a71248b1SBaokun Li 		err = ext4_inode_attach_jinode(inode);
4160a71248b1SBaokun Li 		if (err)
41619a5d265fSzhengliang 			goto out_trace;
4162a361293fSJan Kara 	}
4163a361293fSJan Kara 
4164ff9893dcSAmir Goldstein 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4165819c4920STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
4166ff9893dcSAmir Goldstein 	else
4167819c4920STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
4168819c4920STheodore Ts'o 
4169819c4920STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
41709a5d265fSzhengliang 	if (IS_ERR(handle)) {
41719a5d265fSzhengliang 		err = PTR_ERR(handle);
41729a5d265fSzhengliang 		goto out_trace;
41739a5d265fSzhengliang 	}
4174819c4920STheodore Ts'o 
4175eb3544c6SLukas Czerner 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4176eb3544c6SLukas Czerner 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4177819c4920STheodore Ts'o 
4178819c4920STheodore Ts'o 	/*
4179819c4920STheodore Ts'o 	 * We add the inode to the orphan list, so that if this
4180819c4920STheodore Ts'o 	 * truncate spans multiple transactions, and we crash, we will
4181819c4920STheodore Ts'o 	 * resume the truncate when the filesystem recovers.  It also
4182819c4920STheodore Ts'o 	 * marks the inode dirty, to catch the new size.
4183819c4920STheodore Ts'o 	 *
4184819c4920STheodore Ts'o 	 * Implication: the file must always be in a sane, consistent
4185819c4920STheodore Ts'o 	 * truncatable state while each transaction commits.
4186819c4920STheodore Ts'o 	 */
41872c98eb5eSTheodore Ts'o 	err = ext4_orphan_add(handle, inode);
41882c98eb5eSTheodore Ts'o 	if (err)
4189819c4920STheodore Ts'o 		goto out_stop;
4190819c4920STheodore Ts'o 
4191819c4920STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
4192819c4920STheodore Ts'o 
419327bc446eSbrookxu 	ext4_discard_preallocations(inode, 0);
4194819c4920STheodore Ts'o 
4195819c4920STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4196d0abb36dSTheodore Ts'o 		err = ext4_ext_truncate(handle, inode);
4197819c4920STheodore Ts'o 	else
4198819c4920STheodore Ts'o 		ext4_ind_truncate(handle, inode);
4199819c4920STheodore Ts'o 
4200819c4920STheodore Ts'o 	up_write(&ei->i_data_sem);
4201d0abb36dSTheodore Ts'o 	if (err)
4202d0abb36dSTheodore Ts'o 		goto out_stop;
4203819c4920STheodore Ts'o 
4204819c4920STheodore Ts'o 	if (IS_SYNC(inode))
4205819c4920STheodore Ts'o 		ext4_handle_sync(handle);
4206819c4920STheodore Ts'o 
4207819c4920STheodore Ts'o out_stop:
4208819c4920STheodore Ts'o 	/*
4209819c4920STheodore Ts'o 	 * If this was a simple ftruncate() and the file will remain alive,
4210819c4920STheodore Ts'o 	 * then we need to clear up the orphan record which we created above.
4211819c4920STheodore Ts'o 	 * However, if this was a real unlink then we were called by
421258d86a50SWang Shilong 	 * ext4_evict_inode(), and we allow that function to clean up the
4213819c4920STheodore Ts'o 	 * orphan info for us.
4214819c4920STheodore Ts'o 	 */
4215819c4920STheodore Ts'o 	if (inode->i_nlink)
4216819c4920STheodore Ts'o 		ext4_orphan_del(handle, inode);
4217819c4920STheodore Ts'o 
42181bc33893SJeff Layton 	inode->i_mtime = inode_set_ctime_current(inode);
42194209ae12SHarshad Shirwadkar 	err2 = ext4_mark_inode_dirty(handle, inode);
42204209ae12SHarshad Shirwadkar 	if (unlikely(err2 && !err))
42214209ae12SHarshad Shirwadkar 		err = err2;
4222819c4920STheodore Ts'o 	ext4_journal_stop(handle);
4223a86c6181SAlex Tomas 
42249a5d265fSzhengliang out_trace:
42250562e0baSJiaying Zhang 	trace_ext4_truncate_exit(inode);
42262c98eb5eSTheodore Ts'o 	return err;
4227ac27a0ecSDave Kleikamp }
4228ac27a0ecSDave Kleikamp 
42299a1bf32cSZhang Yi static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
42309a1bf32cSZhang Yi {
42319a1bf32cSZhang Yi 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
42329a1bf32cSZhang Yi 		return inode_peek_iversion_raw(inode);
42339a1bf32cSZhang Yi 	else
42349a1bf32cSZhang Yi 		return inode_peek_iversion(inode);
42359a1bf32cSZhang Yi }
42369a1bf32cSZhang Yi 
42379a1bf32cSZhang Yi static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
42389a1bf32cSZhang Yi 				 struct ext4_inode_info *ei)
42399a1bf32cSZhang Yi {
42409a1bf32cSZhang Yi 	struct inode *inode = &(ei->vfs_inode);
42419a1bf32cSZhang Yi 	u64 i_blocks = READ_ONCE(inode->i_blocks);
42429a1bf32cSZhang Yi 	struct super_block *sb = inode->i_sb;
42439a1bf32cSZhang Yi 
42449a1bf32cSZhang Yi 	if (i_blocks <= ~0U) {
42459a1bf32cSZhang Yi 		/*
42469a1bf32cSZhang Yi 		 * i_blocks can be represented in a 32 bit variable
42479a1bf32cSZhang Yi 		 * as multiple of 512 bytes
42489a1bf32cSZhang Yi 		 */
42499a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42509a1bf32cSZhang Yi 		raw_inode->i_blocks_high = 0;
42519a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
42529a1bf32cSZhang Yi 		return 0;
42539a1bf32cSZhang Yi 	}
42549a1bf32cSZhang Yi 
42559a1bf32cSZhang Yi 	/*
42569a1bf32cSZhang Yi 	 * This should never happen since sb->s_maxbytes should not have
42579a1bf32cSZhang Yi 	 * allowed this, sb->s_maxbytes was set according to the huge_file
42589a1bf32cSZhang Yi 	 * feature in ext4_fill_super().
42599a1bf32cSZhang Yi 	 */
42609a1bf32cSZhang Yi 	if (!ext4_has_feature_huge_file(sb))
42619a1bf32cSZhang Yi 		return -EFSCORRUPTED;
42629a1bf32cSZhang Yi 
42639a1bf32cSZhang Yi 	if (i_blocks <= 0xffffffffffffULL) {
42649a1bf32cSZhang Yi 		/*
42659a1bf32cSZhang Yi 		 * i_blocks can be represented in a 48 bit variable
42669a1bf32cSZhang Yi 		 * as multiple of 512 bytes
42679a1bf32cSZhang Yi 		 */
42689a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42699a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
42709a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
42719a1bf32cSZhang Yi 	} else {
42729a1bf32cSZhang Yi 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
42739a1bf32cSZhang Yi 		/* i_block is stored in file system block size */
42749a1bf32cSZhang Yi 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
42759a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42769a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
42779a1bf32cSZhang Yi 	}
42789a1bf32cSZhang Yi 	return 0;
42799a1bf32cSZhang Yi }
42809a1bf32cSZhang Yi 
42819a1bf32cSZhang Yi static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
42829a1bf32cSZhang Yi {
42839a1bf32cSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
42849a1bf32cSZhang Yi 	uid_t i_uid;
42859a1bf32cSZhang Yi 	gid_t i_gid;
42869a1bf32cSZhang Yi 	projid_t i_projid;
42879a1bf32cSZhang Yi 	int block;
42889a1bf32cSZhang Yi 	int err;
42899a1bf32cSZhang Yi 
42909a1bf32cSZhang Yi 	err = ext4_inode_blocks_set(raw_inode, ei);
42919a1bf32cSZhang Yi 
42929a1bf32cSZhang Yi 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
42939a1bf32cSZhang Yi 	i_uid = i_uid_read(inode);
42949a1bf32cSZhang Yi 	i_gid = i_gid_read(inode);
42959a1bf32cSZhang Yi 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
42969a1bf32cSZhang Yi 	if (!(test_opt(inode->i_sb, NO_UID32))) {
42979a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
42989a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
42999a1bf32cSZhang Yi 		/*
43009a1bf32cSZhang Yi 		 * Fix up interoperability with old kernels. Otherwise,
43019a1bf32cSZhang Yi 		 * old inodes get re-used with the upper 16 bits of the
43029a1bf32cSZhang Yi 		 * uid/gid intact.
43039a1bf32cSZhang Yi 		 */
43049a1bf32cSZhang Yi 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
43059a1bf32cSZhang Yi 			raw_inode->i_uid_high = 0;
43069a1bf32cSZhang Yi 			raw_inode->i_gid_high = 0;
43079a1bf32cSZhang Yi 		} else {
43089a1bf32cSZhang Yi 			raw_inode->i_uid_high =
43099a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_uid));
43109a1bf32cSZhang Yi 			raw_inode->i_gid_high =
43119a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_gid));
43129a1bf32cSZhang Yi 		}
43139a1bf32cSZhang Yi 	} else {
43149a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
43159a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
43169a1bf32cSZhang Yi 		raw_inode->i_uid_high = 0;
43179a1bf32cSZhang Yi 		raw_inode->i_gid_high = 0;
43189a1bf32cSZhang Yi 	}
43199a1bf32cSZhang Yi 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
43209a1bf32cSZhang Yi 
43211bc33893SJeff Layton 	EXT4_INODE_SET_CTIME(inode, raw_inode);
43229a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
43239a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
43249a1bf32cSZhang Yi 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
43259a1bf32cSZhang Yi 
43269a1bf32cSZhang Yi 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
43279a1bf32cSZhang Yi 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
43289a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
43299a1bf32cSZhang Yi 		raw_inode->i_file_acl_high =
43309a1bf32cSZhang Yi 			cpu_to_le16(ei->i_file_acl >> 32);
43319a1bf32cSZhang Yi 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
43329a1bf32cSZhang Yi 	ext4_isize_set(raw_inode, ei->i_disksize);
43339a1bf32cSZhang Yi 
43349a1bf32cSZhang Yi 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
43359a1bf32cSZhang Yi 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
43369a1bf32cSZhang Yi 		if (old_valid_dev(inode->i_rdev)) {
43379a1bf32cSZhang Yi 			raw_inode->i_block[0] =
43389a1bf32cSZhang Yi 				cpu_to_le32(old_encode_dev(inode->i_rdev));
43399a1bf32cSZhang Yi 			raw_inode->i_block[1] = 0;
43409a1bf32cSZhang Yi 		} else {
43419a1bf32cSZhang Yi 			raw_inode->i_block[0] = 0;
43429a1bf32cSZhang Yi 			raw_inode->i_block[1] =
43439a1bf32cSZhang Yi 				cpu_to_le32(new_encode_dev(inode->i_rdev));
43449a1bf32cSZhang Yi 			raw_inode->i_block[2] = 0;
43459a1bf32cSZhang Yi 		}
43469a1bf32cSZhang Yi 	} else if (!ext4_has_inline_data(inode)) {
43479a1bf32cSZhang Yi 		for (block = 0; block < EXT4_N_BLOCKS; block++)
43489a1bf32cSZhang Yi 			raw_inode->i_block[block] = ei->i_data[block];
43499a1bf32cSZhang Yi 	}
43509a1bf32cSZhang Yi 
43519a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
43529a1bf32cSZhang Yi 		u64 ivers = ext4_inode_peek_iversion(inode);
43539a1bf32cSZhang Yi 
43549a1bf32cSZhang Yi 		raw_inode->i_disk_version = cpu_to_le32(ivers);
43559a1bf32cSZhang Yi 		if (ei->i_extra_isize) {
43569a1bf32cSZhang Yi 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
43579a1bf32cSZhang Yi 				raw_inode->i_version_hi =
43589a1bf32cSZhang Yi 					cpu_to_le32(ivers >> 32);
43599a1bf32cSZhang Yi 			raw_inode->i_extra_isize =
43609a1bf32cSZhang Yi 				cpu_to_le16(ei->i_extra_isize);
43619a1bf32cSZhang Yi 		}
43629a1bf32cSZhang Yi 	}
43639a1bf32cSZhang Yi 
43649a1bf32cSZhang Yi 	if (i_projid != EXT4_DEF_PROJID &&
43659a1bf32cSZhang Yi 	    !ext4_has_feature_project(inode->i_sb))
43669a1bf32cSZhang Yi 		err = err ?: -EFSCORRUPTED;
43679a1bf32cSZhang Yi 
43689a1bf32cSZhang Yi 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
43699a1bf32cSZhang Yi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
43709a1bf32cSZhang Yi 		raw_inode->i_projid = cpu_to_le32(i_projid);
43719a1bf32cSZhang Yi 
43729a1bf32cSZhang Yi 	ext4_inode_csum_set(inode, raw_inode, ei);
43739a1bf32cSZhang Yi 	return err;
43749a1bf32cSZhang Yi }
43759a1bf32cSZhang Yi 
4376ac27a0ecSDave Kleikamp /*
4377617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
4378de01f484SZhang Yi  * underlying buffer_head on success. If we pass 'inode' and it does not
4379de01f484SZhang Yi  * have in-inode xattr, we have all inode data in memory that is needed
4380de01f484SZhang Yi  * to recreate the on-disk version of this inode.
4381ac27a0ecSDave Kleikamp  */
43828016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4383de01f484SZhang Yi 				struct inode *inode, struct ext4_iloc *iloc,
43848016e29fSHarshad Shirwadkar 				ext4_fsblk_t *ret_block)
4385ac27a0ecSDave Kleikamp {
4386240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
4387ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
4388240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
438902f03c42SLinus Torvalds 	struct blk_plug		plug;
4390240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
4391ac27a0ecSDave Kleikamp 
43923a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
43938016e29fSHarshad Shirwadkar 	if (ino < EXT4_ROOT_INO ||
43948016e29fSHarshad Shirwadkar 	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
43956a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4396ac27a0ecSDave Kleikamp 
43978016e29fSHarshad Shirwadkar 	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4398240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4399240799cdSTheodore Ts'o 	if (!gdp)
4400240799cdSTheodore Ts'o 		return -EIO;
4401240799cdSTheodore Ts'o 
4402240799cdSTheodore Ts'o 	/*
4403240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
4404240799cdSTheodore Ts'o 	 */
440500d09882STao Ma 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
44068016e29fSHarshad Shirwadkar 	inode_offset = ((ino - 1) %
4407240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
4408240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4409240799cdSTheodore Ts'o 
4410eee22187SBaokun Li 	block = ext4_inode_table(sb, gdp);
4411eee22187SBaokun Li 	if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4412eee22187SBaokun Li 	    (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4413eee22187SBaokun Li 		ext4_error(sb, "Invalid inode table block %llu in "
4414eee22187SBaokun Li 			   "block_group %u", block, iloc->block_group);
4415eee22187SBaokun Li 		return -EFSCORRUPTED;
4416eee22187SBaokun Li 	}
4417eee22187SBaokun Li 	block += (inode_offset / inodes_per_block);
4418eee22187SBaokun Li 
4419240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
4420aebf0243SWang Shilong 	if (unlikely(!bh))
4421860d21e2STheodore Ts'o 		return -ENOMEM;
44228e33fadfSZhang Yi 	if (ext4_buffer_uptodate(bh))
4423ac27a0ecSDave Kleikamp 		goto has_buffer;
4424ac27a0ecSDave Kleikamp 
44258e33fadfSZhang Yi 	lock_buffer(bh);
4426f2c77973SZhang Yi 	if (ext4_buffer_uptodate(bh)) {
4427f2c77973SZhang Yi 		/* Someone brought it uptodate while we waited */
4428f2c77973SZhang Yi 		unlock_buffer(bh);
4429f2c77973SZhang Yi 		goto has_buffer;
4430f2c77973SZhang Yi 	}
4431f2c77973SZhang Yi 
4432ac27a0ecSDave Kleikamp 	/*
4433ac27a0ecSDave Kleikamp 	 * If we have all information of the inode in memory and this
4434ac27a0ecSDave Kleikamp 	 * is the only valid inode in the block, we need not read the
4435ac27a0ecSDave Kleikamp 	 * block.
4436ac27a0ecSDave Kleikamp 	 */
4437de01f484SZhang Yi 	if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4438ac27a0ecSDave Kleikamp 		struct buffer_head *bitmap_bh;
4439240799cdSTheodore Ts'o 		int i, start;
4440ac27a0ecSDave Kleikamp 
4441240799cdSTheodore Ts'o 		start = inode_offset & ~(inodes_per_block - 1);
4442ac27a0ecSDave Kleikamp 
4443ac27a0ecSDave Kleikamp 		/* Is the inode bitmap in cache? */
4444240799cdSTheodore Ts'o 		bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4445aebf0243SWang Shilong 		if (unlikely(!bitmap_bh))
4446ac27a0ecSDave Kleikamp 			goto make_io;
4447ac27a0ecSDave Kleikamp 
4448ac27a0ecSDave Kleikamp 		/*
4449ac27a0ecSDave Kleikamp 		 * If the inode bitmap isn't in cache then the
4450ac27a0ecSDave Kleikamp 		 * optimisation may end up performing two reads instead
4451ac27a0ecSDave Kleikamp 		 * of one, so skip it.
4452ac27a0ecSDave Kleikamp 		 */
4453ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bitmap_bh)) {
4454ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
4455ac27a0ecSDave Kleikamp 			goto make_io;
4456ac27a0ecSDave Kleikamp 		}
4457240799cdSTheodore Ts'o 		for (i = start; i < start + inodes_per_block; i++) {
4458ac27a0ecSDave Kleikamp 			if (i == inode_offset)
4459ac27a0ecSDave Kleikamp 				continue;
4460617ba13bSMingming Cao 			if (ext4_test_bit(i, bitmap_bh->b_data))
4461ac27a0ecSDave Kleikamp 				break;
4462ac27a0ecSDave Kleikamp 		}
4463ac27a0ecSDave Kleikamp 		brelse(bitmap_bh);
4464240799cdSTheodore Ts'o 		if (i == start + inodes_per_block) {
4465de01f484SZhang Yi 			struct ext4_inode *raw_inode =
4466de01f484SZhang Yi 				(struct ext4_inode *) (bh->b_data + iloc->offset);
4467de01f484SZhang Yi 
4468ac27a0ecSDave Kleikamp 			/* all other inodes are free, so skip I/O */
4469ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, bh->b_size);
4470de01f484SZhang Yi 			if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4471de01f484SZhang Yi 				ext4_fill_raw_inode(inode, raw_inode);
4472ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
4473ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
4474ac27a0ecSDave Kleikamp 			goto has_buffer;
4475ac27a0ecSDave Kleikamp 		}
4476ac27a0ecSDave Kleikamp 	}
4477ac27a0ecSDave Kleikamp 
4478ac27a0ecSDave Kleikamp make_io:
4479ac27a0ecSDave Kleikamp 	/*
4480240799cdSTheodore Ts'o 	 * If we need to do any I/O, try to pre-readahead extra
4481240799cdSTheodore Ts'o 	 * blocks from the inode table.
4482240799cdSTheodore Ts'o 	 */
448302f03c42SLinus Torvalds 	blk_start_plug(&plug);
4484240799cdSTheodore Ts'o 	if (EXT4_SB(sb)->s_inode_readahead_blks) {
4485240799cdSTheodore Ts'o 		ext4_fsblk_t b, end, table;
4486240799cdSTheodore Ts'o 		unsigned num;
44870d606e2cSTheodore Ts'o 		__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4488240799cdSTheodore Ts'o 
4489240799cdSTheodore Ts'o 		table = ext4_inode_table(sb, gdp);
4490b713a5ecSTheodore Ts'o 		/* s_inode_readahead_blks is always a power of 2 */
44910d606e2cSTheodore Ts'o 		b = block & ~((ext4_fsblk_t) ra_blks - 1);
4492240799cdSTheodore Ts'o 		if (table > b)
4493240799cdSTheodore Ts'o 			b = table;
44940d606e2cSTheodore Ts'o 		end = b + ra_blks;
4495240799cdSTheodore Ts'o 		num = EXT4_INODES_PER_GROUP(sb);
4496feb0ab32SDarrick J. Wong 		if (ext4_has_group_desc_csum(sb))
4497560671a0SAneesh Kumar K.V 			num -= ext4_itable_unused_count(sb, gdp);
4498240799cdSTheodore Ts'o 		table += num / inodes_per_block;
4499240799cdSTheodore Ts'o 		if (end > table)
4500240799cdSTheodore Ts'o 			end = table;
4501240799cdSTheodore Ts'o 		while (b <= end)
45025df1d412Szhangyi (F) 			ext4_sb_breadahead_unmovable(sb, b++);
4503240799cdSTheodore Ts'o 	}
4504240799cdSTheodore Ts'o 
4505240799cdSTheodore Ts'o 	/*
4506ac27a0ecSDave Kleikamp 	 * There are other valid inodes in the buffer, this inode
4507ac27a0ecSDave Kleikamp 	 * has in-inode xattrs, or we don't have this inode in memory.
4508ac27a0ecSDave Kleikamp 	 * Read the block from disk.
4509ac27a0ecSDave Kleikamp 	 */
45108016e29fSHarshad Shirwadkar 	trace_ext4_load_inode(sb, ino);
45112d069c08Szhangyi (F) 	ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
451202f03c42SLinus Torvalds 	blk_finish_plug(&plug);
4513ac27a0ecSDave Kleikamp 	wait_on_buffer(bh);
45140904c9aeSZhang Yi 	ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4515ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
45168016e29fSHarshad Shirwadkar 		if (ret_block)
45178016e29fSHarshad Shirwadkar 			*ret_block = block;
4518ac27a0ecSDave Kleikamp 		brelse(bh);
4519ac27a0ecSDave Kleikamp 		return -EIO;
4520ac27a0ecSDave Kleikamp 	}
4521ac27a0ecSDave Kleikamp has_buffer:
4522ac27a0ecSDave Kleikamp 	iloc->bh = bh;
4523ac27a0ecSDave Kleikamp 	return 0;
4524ac27a0ecSDave Kleikamp }
4525ac27a0ecSDave Kleikamp 
45268016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc_noinmem(struct inode *inode,
45278016e29fSHarshad Shirwadkar 					struct ext4_iloc *iloc)
45288016e29fSHarshad Shirwadkar {
4529c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
45308016e29fSHarshad Shirwadkar 	int ret;
45318016e29fSHarshad Shirwadkar 
4532de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
45338016e29fSHarshad Shirwadkar 					&err_blk);
45348016e29fSHarshad Shirwadkar 
45358016e29fSHarshad Shirwadkar 	if (ret == -EIO)
45368016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
45378016e29fSHarshad Shirwadkar 					"unable to read itable block");
45388016e29fSHarshad Shirwadkar 
45398016e29fSHarshad Shirwadkar 	return ret;
45408016e29fSHarshad Shirwadkar }
45418016e29fSHarshad Shirwadkar 
4542617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4543ac27a0ecSDave Kleikamp {
4544c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
45458016e29fSHarshad Shirwadkar 	int ret;
45468016e29fSHarshad Shirwadkar 
4547de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4548de01f484SZhang Yi 					&err_blk);
45498016e29fSHarshad Shirwadkar 
45508016e29fSHarshad Shirwadkar 	if (ret == -EIO)
45518016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
45528016e29fSHarshad Shirwadkar 					"unable to read itable block");
45538016e29fSHarshad Shirwadkar 
45548016e29fSHarshad Shirwadkar 	return ret;
45558016e29fSHarshad Shirwadkar }
45568016e29fSHarshad Shirwadkar 
45578016e29fSHarshad Shirwadkar 
45588016e29fSHarshad Shirwadkar int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
45598016e29fSHarshad Shirwadkar 			  struct ext4_iloc *iloc)
45608016e29fSHarshad Shirwadkar {
4561de01f484SZhang Yi 	return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4562ac27a0ecSDave Kleikamp }
4563ac27a0ecSDave Kleikamp 
4564a8ab6d38SIra Weiny static bool ext4_should_enable_dax(struct inode *inode)
45656642586bSRoss Zwisler {
4566a8ab6d38SIra Weiny 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4567a8ab6d38SIra Weiny 
45689cb20f94SIra Weiny 	if (test_opt2(inode->i_sb, DAX_NEVER))
45696642586bSRoss Zwisler 		return false;
45706642586bSRoss Zwisler 	if (!S_ISREG(inode->i_mode))
45716642586bSRoss Zwisler 		return false;
45726642586bSRoss Zwisler 	if (ext4_should_journal_data(inode))
45736642586bSRoss Zwisler 		return false;
45746642586bSRoss Zwisler 	if (ext4_has_inline_data(inode))
45756642586bSRoss Zwisler 		return false;
4576592ddec7SChandan Rajendra 	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
45776642586bSRoss Zwisler 		return false;
4578c93d8f88SEric Biggers 	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4579c93d8f88SEric Biggers 		return false;
4580a8ab6d38SIra Weiny 	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4581a8ab6d38SIra Weiny 		return false;
4582a8ab6d38SIra Weiny 	if (test_opt(inode->i_sb, DAX_ALWAYS))
45836642586bSRoss Zwisler 		return true;
4584a8ab6d38SIra Weiny 
4585b383a73fSIra Weiny 	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
45866642586bSRoss Zwisler }
45876642586bSRoss Zwisler 
4588043546e4SIra Weiny void ext4_set_inode_flags(struct inode *inode, bool init)
4589ac27a0ecSDave Kleikamp {
4590617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
459100a1a053STheodore Ts'o 	unsigned int new_fl = 0;
4592ac27a0ecSDave Kleikamp 
4593043546e4SIra Weiny 	WARN_ON_ONCE(IS_DAX(inode) && init);
4594043546e4SIra Weiny 
4595617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
459600a1a053STheodore Ts'o 		new_fl |= S_SYNC;
4597617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
459800a1a053STheodore Ts'o 		new_fl |= S_APPEND;
4599617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
460000a1a053STheodore Ts'o 		new_fl |= S_IMMUTABLE;
4601617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
460200a1a053STheodore Ts'o 		new_fl |= S_NOATIME;
4603617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
460400a1a053STheodore Ts'o 		new_fl |= S_DIRSYNC;
4605043546e4SIra Weiny 
4606043546e4SIra Weiny 	/* Because of the way inode_set_flags() works we must preserve S_DAX
4607043546e4SIra Weiny 	 * here if already set. */
4608043546e4SIra Weiny 	new_fl |= (inode->i_flags & S_DAX);
4609043546e4SIra Weiny 	if (init && ext4_should_enable_dax(inode))
4610923ae0ffSRoss Zwisler 		new_fl |= S_DAX;
4611043546e4SIra Weiny 
46122ee6a576SEric Biggers 	if (flags & EXT4_ENCRYPT_FL)
46132ee6a576SEric Biggers 		new_fl |= S_ENCRYPTED;
4614b886ee3eSGabriel Krisman Bertazi 	if (flags & EXT4_CASEFOLD_FL)
4615b886ee3eSGabriel Krisman Bertazi 		new_fl |= S_CASEFOLD;
4616c93d8f88SEric Biggers 	if (flags & EXT4_VERITY_FL)
4617c93d8f88SEric Biggers 		new_fl |= S_VERITY;
46185f16f322STheodore Ts'o 	inode_set_flags(inode, new_fl,
46192ee6a576SEric Biggers 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4620c93d8f88SEric Biggers 			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4621ac27a0ecSDave Kleikamp }
4622ac27a0ecSDave Kleikamp 
46230fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
46240fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
46250fc1b451SAneesh Kumar K.V {
46260fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
46278180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
46288180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
46290fc1b451SAneesh Kumar K.V 
4630e2b911c5SDarrick J. Wong 	if (ext4_has_feature_huge_file(sb)) {
46310fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
46320fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
46330fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
463407a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
46358180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
46368180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
46378180a562SAneesh Kumar K.V 		} else {
46380fc1b451SAneesh Kumar K.V 			return i_blocks;
46398180a562SAneesh Kumar K.V 		}
46400fc1b451SAneesh Kumar K.V 	} else {
46410fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
46420fc1b451SAneesh Kumar K.V 	}
46430fc1b451SAneesh Kumar K.V }
4644ff9ddf7eSJan Kara 
4645eb9b5f01STheodore Ts'o static inline int ext4_iget_extra_inode(struct inode *inode,
4646152a7b0aSTao Ma 					 struct ext4_inode *raw_inode,
4647152a7b0aSTao Ma 					 struct ext4_inode_info *ei)
4648152a7b0aSTao Ma {
4649152a7b0aSTao Ma 	__le32 *magic = (void *)raw_inode +
4650152a7b0aSTao Ma 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4651eb9b5f01STheodore Ts'o 
4652fd7e672eSBaokun Li 	if (EXT4_INODE_HAS_XATTR_SPACE(inode)  &&
4653290ab230SEric Biggers 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
46541dcdce59SYe Bin 		int err;
46551dcdce59SYe Bin 
4656152a7b0aSTao Ma 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
46571dcdce59SYe Bin 		err = ext4_find_inline_data_nolock(inode);
46581dcdce59SYe Bin 		if (!err && ext4_has_inline_data(inode))
46591dcdce59SYe Bin 			ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
46601dcdce59SYe Bin 		return err;
4661f19d5870STao Ma 	} else
4662f19d5870STao Ma 		EXT4_I(inode)->i_inline_off = 0;
4663eb9b5f01STheodore Ts'o 	return 0;
4664152a7b0aSTao Ma }
4665152a7b0aSTao Ma 
4666040cb378SLi Xi int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4667040cb378SLi Xi {
46680b7b7779SKaho Ng 	if (!ext4_has_feature_project(inode->i_sb))
4669040cb378SLi Xi 		return -EOPNOTSUPP;
4670040cb378SLi Xi 	*projid = EXT4_I(inode)->i_projid;
4671040cb378SLi Xi 	return 0;
4672040cb378SLi Xi }
4673040cb378SLi Xi 
4674e254d1afSEryu Guan /*
4675e254d1afSEryu Guan  * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4676e254d1afSEryu Guan  * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4677e254d1afSEryu Guan  * set.
4678e254d1afSEryu Guan  */
4679e254d1afSEryu Guan static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4680e254d1afSEryu Guan {
4681e254d1afSEryu Guan 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4682e254d1afSEryu Guan 		inode_set_iversion_raw(inode, val);
4683e254d1afSEryu Guan 	else
4684e254d1afSEryu Guan 		inode_set_iversion_queried(inode, val);
4685e254d1afSEryu Guan }
4686e254d1afSEryu Guan 
4687b3e6bcb9STheodore Ts'o static const char *check_igot_inode(struct inode *inode, ext4_iget_flags flags)
4688b3e6bcb9STheodore Ts'o 
4689b3e6bcb9STheodore Ts'o {
4690b3e6bcb9STheodore Ts'o 	if (flags & EXT4_IGET_EA_INODE) {
4691b3e6bcb9STheodore Ts'o 		if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4692b3e6bcb9STheodore Ts'o 			return "missing EA_INODE flag";
46932bc7e7c1STheodore Ts'o 		if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
46942bc7e7c1STheodore Ts'o 		    EXT4_I(inode)->i_file_acl)
46952bc7e7c1STheodore Ts'o 			return "ea_inode with extended attributes";
4696b3e6bcb9STheodore Ts'o 	} else {
4697b3e6bcb9STheodore Ts'o 		if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4698b3e6bcb9STheodore Ts'o 			return "unexpected EA_INODE flag";
4699b3e6bcb9STheodore Ts'o 	}
4700b3e6bcb9STheodore Ts'o 	if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD))
4701b3e6bcb9STheodore Ts'o 		return "unexpected bad inode w/o EXT4_IGET_BAD";
4702b3e6bcb9STheodore Ts'o 	return NULL;
4703b3e6bcb9STheodore Ts'o }
4704b3e6bcb9STheodore Ts'o 
47058a363970STheodore Ts'o struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
47068a363970STheodore Ts'o 			  ext4_iget_flags flags, const char *function,
47078a363970STheodore Ts'o 			  unsigned int line)
4708ac27a0ecSDave Kleikamp {
4709617ba13bSMingming Cao 	struct ext4_iloc iloc;
4710617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
47111d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
4712bd2c38cfSJan Kara 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
47131d1fe1eeSDavid Howells 	struct inode *inode;
4714b3e6bcb9STheodore Ts'o 	const char *err_str;
4715b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
47161d1fe1eeSDavid Howells 	long ret;
47177e6e1ef4SDarrick J. Wong 	loff_t size;
4718ac27a0ecSDave Kleikamp 	int block;
471908cefc7aSEric W. Biederman 	uid_t i_uid;
472008cefc7aSEric W. Biederman 	gid_t i_gid;
4721040cb378SLi Xi 	projid_t i_projid;
4722ac27a0ecSDave Kleikamp 
4723191ce178STheodore Ts'o 	if ((!(flags & EXT4_IGET_SPECIAL) &&
4724bd2c38cfSJan Kara 	     ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4725bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_usr_quota_inum) ||
4726bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_grp_quota_inum) ||
472702f310fcSJan Kara 	      ino == le32_to_cpu(es->s_prj_quota_inum) ||
472802f310fcSJan Kara 	      ino == le32_to_cpu(es->s_orphan_file_inum))) ||
47298a363970STheodore Ts'o 	    (ino < EXT4_ROOT_INO) ||
4730bd2c38cfSJan Kara 	    (ino > le32_to_cpu(es->s_inodes_count))) {
47318a363970STheodore Ts'o 		if (flags & EXT4_IGET_HANDLE)
47328a363970STheodore Ts'o 			return ERR_PTR(-ESTALE);
4733014c9caaSJan Kara 		__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
47348a363970STheodore Ts'o 			     "inode #%lu: comm %s: iget: illegal inode #",
47358a363970STheodore Ts'o 			     ino, current->comm);
47368a363970STheodore Ts'o 		return ERR_PTR(-EFSCORRUPTED);
47378a363970STheodore Ts'o 	}
47388a363970STheodore Ts'o 
47391d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
47401d1fe1eeSDavid Howells 	if (!inode)
47411d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
4742b3e6bcb9STheodore Ts'o 	if (!(inode->i_state & I_NEW)) {
4743b3e6bcb9STheodore Ts'o 		if ((err_str = check_igot_inode(inode, flags)) != NULL) {
4744b3e6bcb9STheodore Ts'o 			ext4_error_inode(inode, function, line, 0, err_str);
4745b3e6bcb9STheodore Ts'o 			iput(inode);
4746b3e6bcb9STheodore Ts'o 			return ERR_PTR(-EFSCORRUPTED);
4747b3e6bcb9STheodore Ts'o 		}
47481d1fe1eeSDavid Howells 		return inode;
4749b3e6bcb9STheodore Ts'o 	}
47501d1fe1eeSDavid Howells 
47511d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
47527dc57615SPeter Huewe 	iloc.bh = NULL;
4753ac27a0ecSDave Kleikamp 
47548016e29fSHarshad Shirwadkar 	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
47551d1fe1eeSDavid Howells 	if (ret < 0)
4756ac27a0ecSDave Kleikamp 		goto bad_inode;
4757617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
4758814525f4SDarrick J. Wong 
47598a363970STheodore Ts'o 	if ((flags & EXT4_IGET_HANDLE) &&
47608a363970STheodore Ts'o 	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
47618a363970STheodore Ts'o 		ret = -ESTALE;
47628a363970STheodore Ts'o 		goto bad_inode;
47638a363970STheodore Ts'o 	}
47648a363970STheodore Ts'o 
4765814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4766814525f4SDarrick J. Wong 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4767814525f4SDarrick J. Wong 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
47682dc8d9e1SEric Biggers 			EXT4_INODE_SIZE(inode->i_sb) ||
47692dc8d9e1SEric Biggers 		    (ei->i_extra_isize & 3)) {
47708a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
47718a363970STheodore Ts'o 					 "iget: bad extra_isize %u "
47728a363970STheodore Ts'o 					 "(inode size %u)",
47732dc8d9e1SEric Biggers 					 ei->i_extra_isize,
4774814525f4SDarrick J. Wong 					 EXT4_INODE_SIZE(inode->i_sb));
47756a797d27SDarrick J. Wong 			ret = -EFSCORRUPTED;
4776814525f4SDarrick J. Wong 			goto bad_inode;
4777814525f4SDarrick J. Wong 		}
4778814525f4SDarrick J. Wong 	} else
4779814525f4SDarrick J. Wong 		ei->i_extra_isize = 0;
4780814525f4SDarrick J. Wong 
4781814525f4SDarrick J. Wong 	/* Precompute checksum seed for inode metadata */
47829aa5d32bSDmitry Monakhov 	if (ext4_has_metadata_csum(sb)) {
4783814525f4SDarrick J. Wong 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4784814525f4SDarrick J. Wong 		__u32 csum;
4785814525f4SDarrick J. Wong 		__le32 inum = cpu_to_le32(inode->i_ino);
4786814525f4SDarrick J. Wong 		__le32 gen = raw_inode->i_generation;
4787814525f4SDarrick J. Wong 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4788814525f4SDarrick J. Wong 				   sizeof(inum));
4789814525f4SDarrick J. Wong 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4790814525f4SDarrick J. Wong 					      sizeof(gen));
4791814525f4SDarrick J. Wong 	}
4792814525f4SDarrick J. Wong 
47938016e29fSHarshad Shirwadkar 	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
47948016e29fSHarshad Shirwadkar 	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
47958016e29fSHarshad Shirwadkar 	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
47968016e29fSHarshad Shirwadkar 		ext4_error_inode_err(inode, function, line, 0,
47978016e29fSHarshad Shirwadkar 				EFSBADCRC, "iget: checksum invalid");
47986a797d27SDarrick J. Wong 		ret = -EFSBADCRC;
4799814525f4SDarrick J. Wong 		goto bad_inode;
4800814525f4SDarrick J. Wong 	}
4801814525f4SDarrick J. Wong 
4802ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
480308cefc7aSEric W. Biederman 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
480408cefc7aSEric W. Biederman 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
48050b7b7779SKaho Ng 	if (ext4_has_feature_project(sb) &&
4806040cb378SLi Xi 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4807040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4808040cb378SLi Xi 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4809040cb378SLi Xi 	else
4810040cb378SLi Xi 		i_projid = EXT4_DEF_PROJID;
4811040cb378SLi Xi 
4812ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
481308cefc7aSEric W. Biederman 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
481408cefc7aSEric W. Biederman 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4815ac27a0ecSDave Kleikamp 	}
481608cefc7aSEric W. Biederman 	i_uid_write(inode, i_uid);
481708cefc7aSEric W. Biederman 	i_gid_write(inode, i_gid);
4818040cb378SLi Xi 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4819bfe86848SMiklos Szeredi 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4820ac27a0ecSDave Kleikamp 
4821353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
482267cf5b09STao Ma 	ei->i_inline_off = 0;
4823ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
4824ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4825ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
4826ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
4827ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
4828ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
4829ac27a0ecSDave Kleikamp 	 */
4830ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
48315cd74028SBaokun Li 		if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
4832393d1d1dSDr. Tilmann Bubeck 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4833393d1d1dSDr. Tilmann Bubeck 		    ino != EXT4_BOOT_LOADER_INO) {
48345cd74028SBaokun Li 			/* this inode is deleted or unallocated */
48355cd74028SBaokun Li 			if (flags & EXT4_IGET_SPECIAL) {
48365cd74028SBaokun Li 				ext4_error_inode(inode, function, line, 0,
48375cd74028SBaokun Li 						 "iget: special inode unallocated");
48385cd74028SBaokun Li 				ret = -EFSCORRUPTED;
48395cd74028SBaokun Li 			} else
48401d1fe1eeSDavid Howells 				ret = -ESTALE;
4841ac27a0ecSDave Kleikamp 			goto bad_inode;
4842ac27a0ecSDave Kleikamp 		}
4843ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
4844ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
4845ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
4846393d1d1dSDr. Tilmann Bubeck 		 * the process of deleting those.
4847393d1d1dSDr. Tilmann Bubeck 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4848393d1d1dSDr. Tilmann Bubeck 		 * not initialized on a new filesystem. */
4849ac27a0ecSDave Kleikamp 	}
4850ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4851043546e4SIra Weiny 	ext4_set_inode_flags(inode, true);
48520fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
48537973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4854e2b911c5SDarrick J. Wong 	if (ext4_has_feature_64bit(sb))
4855a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
4856a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4857e08ac99fSArtem Blagodarenko 	inode->i_size = ext4_isize(sb, raw_inode);
48587e6e1ef4SDarrick J. Wong 	if ((size = i_size_read(inode)) < 0) {
48598a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
48608a363970STheodore Ts'o 				 "iget: bad i_size value: %lld", size);
48617e6e1ef4SDarrick J. Wong 		ret = -EFSCORRUPTED;
48627e6e1ef4SDarrick J. Wong 		goto bad_inode;
48637e6e1ef4SDarrick J. Wong 	}
486448a34311SJan Kara 	/*
486548a34311SJan Kara 	 * If dir_index is not enabled but there's dir with INDEX flag set,
486648a34311SJan Kara 	 * we'd normally treat htree data as empty space. But with metadata
486748a34311SJan Kara 	 * checksumming that corrupts checksums so forbid that.
486848a34311SJan Kara 	 */
486948a34311SJan Kara 	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
487048a34311SJan Kara 	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
487148a34311SJan Kara 		ext4_error_inode(inode, function, line, 0,
487248a34311SJan Kara 			 "iget: Dir with htree data on filesystem without dir_index feature.");
487348a34311SJan Kara 		ret = -EFSCORRUPTED;
487448a34311SJan Kara 		goto bad_inode;
487548a34311SJan Kara 	}
4876ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
4877a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
4878a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
4879a9e7f447SDmitry Monakhov #endif
4880ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4881ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
4882a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
4883ac27a0ecSDave Kleikamp 	/*
4884ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
4885ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4886ac27a0ecSDave Kleikamp 	 */
4887617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4888ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
4889ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
4890aa75f4d3SHarshad Shirwadkar 	ext4_fc_init_inode(&ei->vfs_inode);
4891ac27a0ecSDave Kleikamp 
4892b436b9beSJan Kara 	/*
4893b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
4894b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
4895b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
4896b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
4897b436b9beSJan Kara 	 * now it is reread from disk.
4898b436b9beSJan Kara 	 */
4899b436b9beSJan Kara 	if (journal) {
4900b436b9beSJan Kara 		transaction_t *transaction;
4901b436b9beSJan Kara 		tid_t tid;
4902b436b9beSJan Kara 
4903a931da6aSTheodore Ts'o 		read_lock(&journal->j_state_lock);
4904b436b9beSJan Kara 		if (journal->j_running_transaction)
4905b436b9beSJan Kara 			transaction = journal->j_running_transaction;
4906b436b9beSJan Kara 		else
4907b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
4908b436b9beSJan Kara 		if (transaction)
4909b436b9beSJan Kara 			tid = transaction->t_tid;
4910b436b9beSJan Kara 		else
4911b436b9beSJan Kara 			tid = journal->j_commit_sequence;
4912a931da6aSTheodore Ts'o 		read_unlock(&journal->j_state_lock);
4913b436b9beSJan Kara 		ei->i_sync_tid = tid;
4914b436b9beSJan Kara 		ei->i_datasync_tid = tid;
4915b436b9beSJan Kara 	}
4916b436b9beSJan Kara 
49170040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4918ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
4919ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
49202dc8d9e1SEric Biggers 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4921617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4922617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
4923ac27a0ecSDave Kleikamp 		} else {
4924eb9b5f01STheodore Ts'o 			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4925eb9b5f01STheodore Ts'o 			if (ret)
4926eb9b5f01STheodore Ts'o 				goto bad_inode;
4927ac27a0ecSDave Kleikamp 		}
4928814525f4SDarrick J. Wong 	}
4929ac27a0ecSDave Kleikamp 
49301bc33893SJeff Layton 	EXT4_INODE_GET_CTIME(inode, raw_inode);
4931ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4932ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4933ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4934ef7f3835SKalpak Shah 
4935ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4936ee73f9a5SJeff Layton 		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4937ee73f9a5SJeff Layton 
493825ec56b5SJean Noel Cordenner 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
493925ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4940ee73f9a5SJeff Layton 				ivers |=
494125ec56b5SJean Noel Cordenner 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
494225ec56b5SJean Noel Cordenner 		}
4943e254d1afSEryu Guan 		ext4_inode_set_iversion_queried(inode, ivers);
4944c4f65706STheodore Ts'o 	}
494525ec56b5SJean Noel Cordenner 
4946c4b5a614STheodore Ts'o 	ret = 0;
4947485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
4948ce9f24ccSJan Kara 	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
49498a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
49508a363970STheodore Ts'o 				 "iget: bad extended attribute block %llu",
495124676da4STheodore Ts'o 				 ei->i_file_acl);
49526a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
4953485c26ecSTheodore Ts'o 		goto bad_inode;
4954f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
4955bc716523SLiu Song 		/* validate the block references in the inode */
49568016e29fSHarshad Shirwadkar 		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
49578016e29fSHarshad Shirwadkar 			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4958fe2c8191SThiemo Nagel 			(S_ISLNK(inode->i_mode) &&
49598016e29fSHarshad Shirwadkar 			!ext4_inode_is_fast_symlink(inode)))) {
4960bc716523SLiu Song 			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4961bc716523SLiu Song 				ret = ext4_ext_check_inode(inode);
4962bc716523SLiu Song 			else
49631f7d1e77STheodore Ts'o 				ret = ext4_ind_check_inode(inode);
4964fe2c8191SThiemo Nagel 		}
4965f19d5870STao Ma 	}
4966567f3e9aSTheodore Ts'o 	if (ret)
49677a262f7cSAneesh Kumar K.V 		goto bad_inode;
49687a262f7cSAneesh Kumar K.V 
4969ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
4970617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
4971617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
4972617ba13bSMingming Cao 		ext4_set_aops(inode);
4973ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
4974617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
4975617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
4976ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
49776390d33bSLuis R. Rodriguez 		/* VFS does not allow setting these so must be corruption */
49786390d33bSLuis R. Rodriguez 		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
49798a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
49808a363970STheodore Ts'o 					 "iget: immutable or append flags "
49818a363970STheodore Ts'o 					 "not allowed on symlinks");
49826390d33bSLuis R. Rodriguez 			ret = -EFSCORRUPTED;
49836390d33bSLuis R. Rodriguez 			goto bad_inode;
49846390d33bSLuis R. Rodriguez 		}
4985592ddec7SChandan Rajendra 		if (IS_ENCRYPTED(inode)) {
4986a7a67e8aSAl Viro 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
4987a7a67e8aSAl Viro 		} else if (ext4_inode_is_fast_symlink(inode)) {
498875e7566bSAl Viro 			inode->i_link = (char *)ei->i_data;
4989617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
4990e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
4991e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
4992e83c1397SDuane Griffin 		} else {
4993617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
4994ac27a0ecSDave Kleikamp 		}
4995563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4996563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4997617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
4998ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
4999ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5000ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5001ac27a0ecSDave Kleikamp 		else
5002ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5003ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5004393d1d1dSDr. Tilmann Bubeck 	} else if (ino == EXT4_BOOT_LOADER_INO) {
5005393d1d1dSDr. Tilmann Bubeck 		make_bad_inode(inode);
5006563bdd61STheodore Ts'o 	} else {
50076a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
50088a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
50098a363970STheodore Ts'o 				 "iget: bogus i_mode (%o)", inode->i_mode);
5010563bdd61STheodore Ts'o 		goto bad_inode;
5011ac27a0ecSDave Kleikamp 	}
50128216776cSEric Biggers 	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb)) {
50136456ca65STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
50146456ca65STheodore Ts'o 				 "casefold flag without casefold feature");
50158216776cSEric Biggers 		ret = -EFSCORRUPTED;
50168216776cSEric Biggers 		goto bad_inode;
50178216776cSEric Biggers 	}
5018b3e6bcb9STheodore Ts'o 	if ((err_str = check_igot_inode(inode, flags)) != NULL) {
5019b3e6bcb9STheodore Ts'o 		ext4_error_inode(inode, function, line, 0, err_str);
5020b3e6bcb9STheodore Ts'o 		ret = -EFSCORRUPTED;
502163b1e9bcSBaokun Li 		goto bad_inode;
502263b1e9bcSBaokun Li 	}
5023dec214d0STahsin Erdogan 
502463b1e9bcSBaokun Li 	brelse(iloc.bh);
50251d1fe1eeSDavid Howells 	unlock_new_inode(inode);
50261d1fe1eeSDavid Howells 	return inode;
5027ac27a0ecSDave Kleikamp 
5028ac27a0ecSDave Kleikamp bad_inode:
5029567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
50301d1fe1eeSDavid Howells 	iget_failed(inode);
50311d1fe1eeSDavid Howells 	return ERR_PTR(ret);
5032ac27a0ecSDave Kleikamp }
5033ac27a0ecSDave Kleikamp 
50343f19b2abSDavid Howells static void __ext4_update_other_inode_time(struct super_block *sb,
50353f19b2abSDavid Howells 					   unsigned long orig_ino,
50363f19b2abSDavid Howells 					   unsigned long ino,
50373f19b2abSDavid Howells 					   struct ext4_inode *raw_inode)
5038a26f4992STheodore Ts'o {
50393f19b2abSDavid Howells 	struct inode *inode;
5040a26f4992STheodore Ts'o 
50413f19b2abSDavid Howells 	inode = find_inode_by_ino_rcu(sb, ino);
50423f19b2abSDavid Howells 	if (!inode)
50433f19b2abSDavid Howells 		return;
50443f19b2abSDavid Howells 
5045ed296c6cSEric Biggers 	if (!inode_is_dirtytime_only(inode))
50463f19b2abSDavid Howells 		return;
50473f19b2abSDavid Howells 
5048a26f4992STheodore Ts'o 	spin_lock(&inode->i_lock);
5049ed296c6cSEric Biggers 	if (inode_is_dirtytime_only(inode)) {
5050a26f4992STheodore Ts'o 		struct ext4_inode_info	*ei = EXT4_I(inode);
5051a26f4992STheodore Ts'o 
50525fcd5750SJan Kara 		inode->i_state &= ~I_DIRTY_TIME;
5053a26f4992STheodore Ts'o 		spin_unlock(&inode->i_lock);
5054a26f4992STheodore Ts'o 
5055a26f4992STheodore Ts'o 		spin_lock(&ei->i_raw_lock);
50561bc33893SJeff Layton 		EXT4_INODE_SET_CTIME(inode, raw_inode);
50573f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
50583f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
50593f19b2abSDavid Howells 		ext4_inode_csum_set(inode, raw_inode, ei);
5060a26f4992STheodore Ts'o 		spin_unlock(&ei->i_raw_lock);
50613f19b2abSDavid Howells 		trace_ext4_other_inode_update_time(inode, orig_ino);
50623f19b2abSDavid Howells 		return;
5063a26f4992STheodore Ts'o 	}
5064a26f4992STheodore Ts'o 	spin_unlock(&inode->i_lock);
5065a26f4992STheodore Ts'o }
5066a26f4992STheodore Ts'o 
5067a26f4992STheodore Ts'o /*
5068a26f4992STheodore Ts'o  * Opportunistically update the other time fields for other inodes in
5069a26f4992STheodore Ts'o  * the same inode table block.
5070a26f4992STheodore Ts'o  */
5071a26f4992STheodore Ts'o static void ext4_update_other_inodes_time(struct super_block *sb,
5072a26f4992STheodore Ts'o 					  unsigned long orig_ino, char *buf)
5073a26f4992STheodore Ts'o {
5074a26f4992STheodore Ts'o 	unsigned long ino;
5075a26f4992STheodore Ts'o 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5076a26f4992STheodore Ts'o 	int inode_size = EXT4_INODE_SIZE(sb);
5077a26f4992STheodore Ts'o 
50780f0ff9a9STheodore Ts'o 	/*
50790f0ff9a9STheodore Ts'o 	 * Calculate the first inode in the inode table block.  Inode
50800f0ff9a9STheodore Ts'o 	 * numbers are one-based.  That is, the first inode in a block
50810f0ff9a9STheodore Ts'o 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
50820f0ff9a9STheodore Ts'o 	 */
50830f0ff9a9STheodore Ts'o 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
50843f19b2abSDavid Howells 	rcu_read_lock();
5085a26f4992STheodore Ts'o 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5086a26f4992STheodore Ts'o 		if (ino == orig_ino)
5087a26f4992STheodore Ts'o 			continue;
50883f19b2abSDavid Howells 		__ext4_update_other_inode_time(sb, orig_ino, ino,
50893f19b2abSDavid Howells 					       (struct ext4_inode *)buf);
5090a26f4992STheodore Ts'o 	}
50913f19b2abSDavid Howells 	rcu_read_unlock();
5092a26f4992STheodore Ts'o }
5093a26f4992STheodore Ts'o 
5094664bd38bSZhang Yi /*
5095664bd38bSZhang Yi  * Post the struct inode info into an on-disk inode location in the
5096664bd38bSZhang Yi  * buffer-cache.  This gobbles the caller's reference to the
5097664bd38bSZhang Yi  * buffer_head in the inode location struct.
5098664bd38bSZhang Yi  *
5099664bd38bSZhang Yi  * The caller must have write access to iloc->bh.
5100664bd38bSZhang Yi  */
5101664bd38bSZhang Yi static int ext4_do_update_inode(handle_t *handle,
5102664bd38bSZhang Yi 				struct inode *inode,
5103664bd38bSZhang Yi 				struct ext4_iloc *iloc)
5104664bd38bSZhang Yi {
5105664bd38bSZhang Yi 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5106664bd38bSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
5107664bd38bSZhang Yi 	struct buffer_head *bh = iloc->bh;
5108664bd38bSZhang Yi 	struct super_block *sb = inode->i_sb;
5109664bd38bSZhang Yi 	int err;
5110664bd38bSZhang Yi 	int need_datasync = 0, set_large_file = 0;
5111664bd38bSZhang Yi 
5112664bd38bSZhang Yi 	spin_lock(&ei->i_raw_lock);
5113664bd38bSZhang Yi 
5114664bd38bSZhang Yi 	/*
5115664bd38bSZhang Yi 	 * For fields not tracked in the in-memory inode, initialise them
5116664bd38bSZhang Yi 	 * to zero for new inodes.
5117664bd38bSZhang Yi 	 */
5118664bd38bSZhang Yi 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5119664bd38bSZhang Yi 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5120664bd38bSZhang Yi 
5121664bd38bSZhang Yi 	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5122664bd38bSZhang Yi 		need_datasync = 1;
5123664bd38bSZhang Yi 	if (ei->i_disksize > 0x7fffffffULL) {
5124664bd38bSZhang Yi 		if (!ext4_has_feature_large_file(sb) ||
5125664bd38bSZhang Yi 		    EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5126664bd38bSZhang Yi 			set_large_file = 1;
5127664bd38bSZhang Yi 	}
5128664bd38bSZhang Yi 
5129664bd38bSZhang Yi 	err = ext4_fill_raw_inode(inode, raw_inode);
5130202ee5dfSTheodore Ts'o 	spin_unlock(&ei->i_raw_lock);
5131baaae979SZhang Yi 	if (err) {
5132baaae979SZhang Yi 		EXT4_ERROR_INODE(inode, "corrupted inode contents");
5133baaae979SZhang Yi 		goto out_brelse;
5134baaae979SZhang Yi 	}
5135baaae979SZhang Yi 
51361751e8a6SLinus Torvalds 	if (inode->i_sb->s_flags & SB_LAZYTIME)
5137a26f4992STheodore Ts'o 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5138a26f4992STheodore Ts'o 					      bh->b_data);
5139202ee5dfSTheodore Ts'o 
51400390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
51417d8bd3c7SShijie Luo 	err = ext4_handle_dirty_metadata(handle, NULL, bh);
51427d8bd3c7SShijie Luo 	if (err)
5143baaae979SZhang Yi 		goto out_error;
514419f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5145202ee5dfSTheodore Ts'o 	if (set_large_file) {
51465d601255Sliang xie 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5147188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, sb,
5148188c299eSJan Kara 						    EXT4_SB(sb)->s_sbh,
5149188c299eSJan Kara 						    EXT4_JTR_NONE);
5150202ee5dfSTheodore Ts'o 		if (err)
5151baaae979SZhang Yi 			goto out_error;
515205c2c00fSJan Kara 		lock_buffer(EXT4_SB(sb)->s_sbh);
5153e2b911c5SDarrick J. Wong 		ext4_set_feature_large_file(sb);
515405c2c00fSJan Kara 		ext4_superblock_csum_set(sb);
515505c2c00fSJan Kara 		unlock_buffer(EXT4_SB(sb)->s_sbh);
5156202ee5dfSTheodore Ts'o 		ext4_handle_sync(handle);
5157a3f5cf14SJan Kara 		err = ext4_handle_dirty_metadata(handle, NULL,
5158a3f5cf14SJan Kara 						 EXT4_SB(sb)->s_sbh);
5159202ee5dfSTheodore Ts'o 	}
5160b71fc079SJan Kara 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5161baaae979SZhang Yi out_error:
5162baaae979SZhang Yi 	ext4_std_error(inode->i_sb, err);
5163ac27a0ecSDave Kleikamp out_brelse:
5164ac27a0ecSDave Kleikamp 	brelse(bh);
5165ac27a0ecSDave Kleikamp 	return err;
5166ac27a0ecSDave Kleikamp }
5167ac27a0ecSDave Kleikamp 
5168ac27a0ecSDave Kleikamp /*
5169617ba13bSMingming Cao  * ext4_write_inode()
5170ac27a0ecSDave Kleikamp  *
5171ac27a0ecSDave Kleikamp  * We are called from a few places:
5172ac27a0ecSDave Kleikamp  *
517387f7e416STheodore Ts'o  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5174ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
51754907cb7bSAnatol Pomozov  *   transaction to commit.
5176ac27a0ecSDave Kleikamp  *
517787f7e416STheodore Ts'o  * - Within flush work (sys_sync(), kupdate and such).
517887f7e416STheodore Ts'o  *   We wait on commit, if told to.
5179ac27a0ecSDave Kleikamp  *
518087f7e416STheodore Ts'o  * - Within iput_final() -> write_inode_now()
518187f7e416STheodore Ts'o  *   We wait on commit, if told to.
5182ac27a0ecSDave Kleikamp  *
5183ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
5184ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
518587f7e416STheodore Ts'o  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
518687f7e416STheodore Ts'o  * writeback.
5187ac27a0ecSDave Kleikamp  *
5188ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
5189ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5190ac27a0ecSDave Kleikamp  * which we are interested.
5191ac27a0ecSDave Kleikamp  *
5192ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
5193ac27a0ecSDave Kleikamp  *
5194ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
5195ac27a0ecSDave Kleikamp  *	stuff();
5196ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
5197ac27a0ecSDave Kleikamp  *
519887f7e416STheodore Ts'o  * is in error because write_inode() could occur while `stuff()' is running,
519987f7e416STheodore Ts'o  * and the new i_size will be lost.  Plus the inode will no longer be on the
520087f7e416STheodore Ts'o  * superblock's dirty inode list.
5201ac27a0ecSDave Kleikamp  */
5202a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5203ac27a0ecSDave Kleikamp {
520491ac6f43SFrank Mayhar 	int err;
520591ac6f43SFrank Mayhar 
5206f1128084SJan Kara 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
5207ac27a0ecSDave Kleikamp 		return 0;
5208ac27a0ecSDave Kleikamp 
5209eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
521018f2c4fcSTheodore Ts'o 		return -EIO;
521118f2c4fcSTheodore Ts'o 
521291ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
5213617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
52144978c659SJan Kara 			ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5215ac27a0ecSDave Kleikamp 			dump_stack();
5216ac27a0ecSDave Kleikamp 			return -EIO;
5217ac27a0ecSDave Kleikamp 		}
5218ac27a0ecSDave Kleikamp 
521910542c22SJan Kara 		/*
522010542c22SJan Kara 		 * No need to force transaction in WB_SYNC_NONE mode. Also
522110542c22SJan Kara 		 * ext4_sync_fs() will force the commit after everything is
522210542c22SJan Kara 		 * written.
522310542c22SJan Kara 		 */
522410542c22SJan Kara 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5225ac27a0ecSDave Kleikamp 			return 0;
5226ac27a0ecSDave Kleikamp 
5227aa75f4d3SHarshad Shirwadkar 		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
522818f2c4fcSTheodore Ts'o 						EXT4_I(inode)->i_sync_tid);
522991ac6f43SFrank Mayhar 	} else {
523091ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
523191ac6f43SFrank Mayhar 
52328016e29fSHarshad Shirwadkar 		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
523391ac6f43SFrank Mayhar 		if (err)
523491ac6f43SFrank Mayhar 			return err;
523510542c22SJan Kara 		/*
523610542c22SJan Kara 		 * sync(2) will flush the whole buffer cache. No need to do
523710542c22SJan Kara 		 * it here separately for each inode.
523810542c22SJan Kara 		 */
523910542c22SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5240830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
5241830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
524254d3adbcSTheodore Ts'o 			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5243c398eda0STheodore Ts'o 					       "IO error syncing inode");
5244830156c7SFrank Mayhar 			err = -EIO;
5245830156c7SFrank Mayhar 		}
5246fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
524791ac6f43SFrank Mayhar 	}
524891ac6f43SFrank Mayhar 	return err;
5249ac27a0ecSDave Kleikamp }
5250ac27a0ecSDave Kleikamp 
5251ac27a0ecSDave Kleikamp /*
5252ccd16945SMatthew Wilcox (Oracle)  * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5253ccd16945SMatthew Wilcox (Oracle)  * buffers that are attached to a folio straddling i_size and are undergoing
525453e87268SJan Kara  * commit. In that case we have to wait for commit to finish and try again.
525553e87268SJan Kara  */
525653e87268SJan Kara static void ext4_wait_for_tail_page_commit(struct inode *inode)
525753e87268SJan Kara {
525853e87268SJan Kara 	unsigned offset;
525953e87268SJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
526053e87268SJan Kara 	tid_t commit_tid = 0;
526153e87268SJan Kara 	int ret;
526253e87268SJan Kara 
526309cbfeafSKirill A. Shutemov 	offset = inode->i_size & (PAGE_SIZE - 1);
526453e87268SJan Kara 	/*
5265ccd16945SMatthew Wilcox (Oracle) 	 * If the folio is fully truncated, we don't need to wait for any commit
5266ccd16945SMatthew Wilcox (Oracle) 	 * (and we even should not as __ext4_journalled_invalidate_folio() may
5267ccd16945SMatthew Wilcox (Oracle) 	 * strip all buffers from the folio but keep the folio dirty which can then
52683f079114SJan Kara 	 * confuse e.g. concurrent ext4_writepages() seeing dirty folio without
5269565333a1Syangerkun 	 * buffers). Also we don't need to wait for any commit if all buffers in
5270ccd16945SMatthew Wilcox (Oracle) 	 * the folio remain valid. This is most beneficial for the common case of
5271565333a1Syangerkun 	 * blocksize == PAGESIZE.
527253e87268SJan Kara 	 */
5273565333a1Syangerkun 	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
527453e87268SJan Kara 		return;
527553e87268SJan Kara 	while (1) {
5276ccd16945SMatthew Wilcox (Oracle) 		struct folio *folio = filemap_lock_folio(inode->i_mapping,
527709cbfeafSKirill A. Shutemov 				      inode->i_size >> PAGE_SHIFT);
527866dabbb6SChristoph Hellwig 		if (IS_ERR(folio))
527953e87268SJan Kara 			return;
5280ccd16945SMatthew Wilcox (Oracle) 		ret = __ext4_journalled_invalidate_folio(folio, offset,
5281ccd16945SMatthew Wilcox (Oracle) 						folio_size(folio) - offset);
5282ccd16945SMatthew Wilcox (Oracle) 		folio_unlock(folio);
5283ccd16945SMatthew Wilcox (Oracle) 		folio_put(folio);
528453e87268SJan Kara 		if (ret != -EBUSY)
528553e87268SJan Kara 			return;
528653e87268SJan Kara 		commit_tid = 0;
528753e87268SJan Kara 		read_lock(&journal->j_state_lock);
528853e87268SJan Kara 		if (journal->j_committing_transaction)
528953e87268SJan Kara 			commit_tid = journal->j_committing_transaction->t_tid;
529053e87268SJan Kara 		read_unlock(&journal->j_state_lock);
529153e87268SJan Kara 		if (commit_tid)
529253e87268SJan Kara 			jbd2_log_wait_commit(journal, commit_tid);
529353e87268SJan Kara 	}
529453e87268SJan Kara }
529553e87268SJan Kara 
529653e87268SJan Kara /*
5297617ba13bSMingming Cao  * ext4_setattr()
5298ac27a0ecSDave Kleikamp  *
5299ac27a0ecSDave Kleikamp  * Called from notify_change.
5300ac27a0ecSDave Kleikamp  *
5301ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
5302ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
5303ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
5304ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
5305ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
5306ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
5307ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
5308ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
5309ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
5310ac27a0ecSDave Kleikamp  *
5311678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
5312678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
5313678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
5314678aaf48SJan Kara  * This way we are sure that all the data written in the previous
5315678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
5316678aaf48SJan Kara  * writeback).
5317678aaf48SJan Kara  *
5318f340b3d9Shongnanli  * Called with inode->i_rwsem down.
5319ac27a0ecSDave Kleikamp  */
5320c1632a0fSChristian Brauner int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5321549c7297SChristian Brauner 		 struct iattr *attr)
5322ac27a0ecSDave Kleikamp {
53232b0143b5SDavid Howells 	struct inode *inode = d_inode(dentry);
5324ac27a0ecSDave Kleikamp 	int error, rc = 0;
53253d287de3SDmitry Monakhov 	int orphan = 0;
5326ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
5327a642c2c0SJeff Layton 	bool inc_ivers = true;
5328ac27a0ecSDave Kleikamp 
5329eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
53300db1ff22STheodore Ts'o 		return -EIO;
53310db1ff22STheodore Ts'o 
533202b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
533302b016caSTheodore Ts'o 		return -EPERM;
533402b016caSTheodore Ts'o 
533502b016caSTheodore Ts'o 	if (unlikely(IS_APPEND(inode) &&
533602b016caSTheodore Ts'o 		     (ia_valid & (ATTR_MODE | ATTR_UID |
533702b016caSTheodore Ts'o 				  ATTR_GID | ATTR_TIMES_SET))))
533802b016caSTheodore Ts'o 		return -EPERM;
533902b016caSTheodore Ts'o 
5340c1632a0fSChristian Brauner 	error = setattr_prepare(idmap, dentry, attr);
5341ac27a0ecSDave Kleikamp 	if (error)
5342ac27a0ecSDave Kleikamp 		return error;
5343ac27a0ecSDave Kleikamp 
53443ce2b8ddSEric Biggers 	error = fscrypt_prepare_setattr(dentry, attr);
53453ce2b8ddSEric Biggers 	if (error)
53463ce2b8ddSEric Biggers 		return error;
53473ce2b8ddSEric Biggers 
5348c93d8f88SEric Biggers 	error = fsverity_prepare_setattr(dentry, attr);
5349c93d8f88SEric Biggers 	if (error)
5350c93d8f88SEric Biggers 		return error;
5351c93d8f88SEric Biggers 
5352f861646aSChristian Brauner 	if (is_quota_modification(idmap, inode, attr)) {
5353a7cdadeeSJan Kara 		error = dquot_initialize(inode);
5354a7cdadeeSJan Kara 		if (error)
5355a7cdadeeSJan Kara 			return error;
5356a7cdadeeSJan Kara 	}
53572729cfdcSHarshad Shirwadkar 
53580dbe12f2SChristian Brauner 	if (i_uid_needs_update(idmap, attr, inode) ||
53590dbe12f2SChristian Brauner 	    i_gid_needs_update(idmap, attr, inode)) {
5360ac27a0ecSDave Kleikamp 		handle_t *handle;
5361ac27a0ecSDave Kleikamp 
5362ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
5363ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
53649924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
53659924a92aSTheodore Ts'o 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5366194074acSDmitry Monakhov 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5367ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
5368ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
5369ac27a0ecSDave Kleikamp 			goto err_out;
5370ac27a0ecSDave Kleikamp 		}
53717a9ca53aSTahsin Erdogan 
53727a9ca53aSTahsin Erdogan 		/* dquot_transfer() calls back ext4_get_inode_usage() which
53737a9ca53aSTahsin Erdogan 		 * counts xattr inode references.
53747a9ca53aSTahsin Erdogan 		 */
53757a9ca53aSTahsin Erdogan 		down_read(&EXT4_I(inode)->xattr_sem);
5376f861646aSChristian Brauner 		error = dquot_transfer(idmap, inode, attr);
53777a9ca53aSTahsin Erdogan 		up_read(&EXT4_I(inode)->xattr_sem);
53787a9ca53aSTahsin Erdogan 
5379ac27a0ecSDave Kleikamp 		if (error) {
5380617ba13bSMingming Cao 			ext4_journal_stop(handle);
5381ac27a0ecSDave Kleikamp 			return error;
5382ac27a0ecSDave Kleikamp 		}
5383ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
5384ac27a0ecSDave Kleikamp 		 * one transaction */
53850dbe12f2SChristian Brauner 		i_uid_update(idmap, attr, inode);
53860dbe12f2SChristian Brauner 		i_gid_update(idmap, attr, inode);
5387617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
5388617ba13bSMingming Cao 		ext4_journal_stop(handle);
5389512c15efSPan Bian 		if (unlikely(error)) {
53904209ae12SHarshad Shirwadkar 			return error;
5391ac27a0ecSDave Kleikamp 		}
5392512c15efSPan Bian 	}
5393ac27a0ecSDave Kleikamp 
53943da40c7bSJosef Bacik 	if (attr->ia_valid & ATTR_SIZE) {
53955208386cSJan Kara 		handle_t *handle;
53963da40c7bSJosef Bacik 		loff_t oldsize = inode->i_size;
5397f4534c9fSYe Bin 		loff_t old_disksize;
5398b9c1c267SJan Kara 		int shrink = (attr->ia_size < inode->i_size);
5399562c72aaSChristoph Hellwig 
540012e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5401e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5402e2b46574SEric Sandeen 
5403aa75f4d3SHarshad Shirwadkar 			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
54040c095c7fSTheodore Ts'o 				return -EFBIG;
5405e2b46574SEric Sandeen 			}
5406aa75f4d3SHarshad Shirwadkar 		}
5407aa75f4d3SHarshad Shirwadkar 		if (!S_ISREG(inode->i_mode)) {
54083da40c7bSJosef Bacik 			return -EINVAL;
5409aa75f4d3SHarshad Shirwadkar 		}
5410dff6efc3SChristoph Hellwig 
5411a642c2c0SJeff Layton 		if (attr->ia_size == inode->i_size)
5412a642c2c0SJeff Layton 			inc_ivers = false;
5413dff6efc3SChristoph Hellwig 
5414b9c1c267SJan Kara 		if (shrink) {
5415b9c1c267SJan Kara 			if (ext4_should_order_data(inode)) {
54165208386cSJan Kara 				error = ext4_begin_ordered_truncate(inode,
54175208386cSJan Kara 							    attr->ia_size);
54185208386cSJan Kara 				if (error)
54195208386cSJan Kara 					goto err_out;
54205208386cSJan Kara 			}
5421b9c1c267SJan Kara 			/*
5422b9c1c267SJan Kara 			 * Blocks are going to be removed from the inode. Wait
5423b9c1c267SJan Kara 			 * for dio in flight.
5424b9c1c267SJan Kara 			 */
5425b9c1c267SJan Kara 			inode_dio_wait(inode);
5426b9c1c267SJan Kara 		}
5427b9c1c267SJan Kara 
5428d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
5429b9c1c267SJan Kara 
5430b9c1c267SJan Kara 		rc = ext4_break_layouts(inode);
5431b9c1c267SJan Kara 		if (rc) {
5432d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
5433aa75f4d3SHarshad Shirwadkar 			goto err_out;
5434b9c1c267SJan Kara 		}
5435b9c1c267SJan Kara 
54363da40c7bSJosef Bacik 		if (attr->ia_size != inode->i_size) {
54379924a92aSTheodore Ts'o 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5438ac27a0ecSDave Kleikamp 			if (IS_ERR(handle)) {
5439ac27a0ecSDave Kleikamp 				error = PTR_ERR(handle);
5440b9c1c267SJan Kara 				goto out_mmap_sem;
5441ac27a0ecSDave Kleikamp 			}
54423da40c7bSJosef Bacik 			if (ext4_handle_valid(handle) && shrink) {
5443617ba13bSMingming Cao 				error = ext4_orphan_add(handle, inode);
54443d287de3SDmitry Monakhov 				orphan = 1;
54453d287de3SDmitry Monakhov 			}
5446911af577SEryu Guan 			/*
5447911af577SEryu Guan 			 * Update c/mtime on truncate up, ext4_truncate() will
5448911af577SEryu Guan 			 * update c/mtime in shrink case below
5449911af577SEryu Guan 			 */
54501bc33893SJeff Layton 			if (!shrink)
54511bc33893SJeff Layton 				inode->i_mtime = inode_set_ctime_current(inode);
5452aa75f4d3SHarshad Shirwadkar 
5453aa75f4d3SHarshad Shirwadkar 			if (shrink)
5454a80f7fcfSHarshad Shirwadkar 				ext4_fc_track_range(handle, inode,
5455aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5456aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
54579725958bSXin Yin 					EXT_MAX_BLOCKS - 1);
5458aa75f4d3SHarshad Shirwadkar 			else
5459aa75f4d3SHarshad Shirwadkar 				ext4_fc_track_range(
5460a80f7fcfSHarshad Shirwadkar 					handle, inode,
5461aa75f4d3SHarshad Shirwadkar 					(oldsize > 0 ? oldsize - 1 : oldsize) >>
5462aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
5463aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5464aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits);
5465aa75f4d3SHarshad Shirwadkar 
546690e775b7SJan Kara 			down_write(&EXT4_I(inode)->i_data_sem);
5467f4534c9fSYe Bin 			old_disksize = EXT4_I(inode)->i_disksize;
5468617ba13bSMingming Cao 			EXT4_I(inode)->i_disksize = attr->ia_size;
5469617ba13bSMingming Cao 			rc = ext4_mark_inode_dirty(handle, inode);
5470ac27a0ecSDave Kleikamp 			if (!error)
5471ac27a0ecSDave Kleikamp 				error = rc;
547290e775b7SJan Kara 			/*
547390e775b7SJan Kara 			 * We have to update i_size under i_data_sem together
547490e775b7SJan Kara 			 * with i_disksize to avoid races with writeback code
547590e775b7SJan Kara 			 * running ext4_wb_update_i_disksize().
547690e775b7SJan Kara 			 */
547790e775b7SJan Kara 			if (!error)
547890e775b7SJan Kara 				i_size_write(inode, attr->ia_size);
5479f4534c9fSYe Bin 			else
5480f4534c9fSYe Bin 				EXT4_I(inode)->i_disksize = old_disksize;
548190e775b7SJan Kara 			up_write(&EXT4_I(inode)->i_data_sem);
5482617ba13bSMingming Cao 			ext4_journal_stop(handle);
5483b9c1c267SJan Kara 			if (error)
5484b9c1c267SJan Kara 				goto out_mmap_sem;
548582a25b02SJan Kara 			if (!shrink) {
5486b9c1c267SJan Kara 				pagecache_isize_extended(inode, oldsize,
5487b9c1c267SJan Kara 							 inode->i_size);
5488b9c1c267SJan Kara 			} else if (ext4_should_journal_data(inode)) {
548982a25b02SJan Kara 				ext4_wait_for_tail_page_commit(inode);
5490b9c1c267SJan Kara 			}
5491430657b6SRoss Zwisler 		}
5492430657b6SRoss Zwisler 
549353e87268SJan Kara 		/*
549453e87268SJan Kara 		 * Truncate pagecache after we've waited for commit
549553e87268SJan Kara 		 * in data=journal mode to make pages freeable.
549653e87268SJan Kara 		 */
54977caef267SKirill A. Shutemov 		truncate_pagecache(inode, inode->i_size);
5498b9c1c267SJan Kara 		/*
5499b9c1c267SJan Kara 		 * Call ext4_truncate() even if i_size didn't change to
5500b9c1c267SJan Kara 		 * truncate possible preallocated blocks.
5501b9c1c267SJan Kara 		 */
5502b9c1c267SJan Kara 		if (attr->ia_size <= oldsize) {
55032c98eb5eSTheodore Ts'o 			rc = ext4_truncate(inode);
55042c98eb5eSTheodore Ts'o 			if (rc)
55052c98eb5eSTheodore Ts'o 				error = rc;
55062c98eb5eSTheodore Ts'o 		}
5507b9c1c267SJan Kara out_mmap_sem:
5508d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
55093da40c7bSJosef Bacik 	}
5510ac27a0ecSDave Kleikamp 
55112c98eb5eSTheodore Ts'o 	if (!error) {
5512a642c2c0SJeff Layton 		if (inc_ivers)
5513a642c2c0SJeff Layton 			inode_inc_iversion(inode);
5514c1632a0fSChristian Brauner 		setattr_copy(idmap, inode, attr);
55151025774cSChristoph Hellwig 		mark_inode_dirty(inode);
55161025774cSChristoph Hellwig 	}
55171025774cSChristoph Hellwig 
55181025774cSChristoph Hellwig 	/*
55191025774cSChristoph Hellwig 	 * If the call to ext4_truncate failed to get a transaction handle at
55201025774cSChristoph Hellwig 	 * all, we need to clean up the in-core orphan list manually.
55211025774cSChristoph Hellwig 	 */
55223d287de3SDmitry Monakhov 	if (orphan && inode->i_nlink)
5523617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
5524ac27a0ecSDave Kleikamp 
55252c98eb5eSTheodore Ts'o 	if (!error && (ia_valid & ATTR_MODE))
552613e83a49SChristian Brauner 		rc = posix_acl_chmod(idmap, dentry, inode->i_mode);
5527ac27a0ecSDave Kleikamp 
5528ac27a0ecSDave Kleikamp err_out:
5529aa75f4d3SHarshad Shirwadkar 	if  (error)
5530617ba13bSMingming Cao 		ext4_std_error(inode->i_sb, error);
5531ac27a0ecSDave Kleikamp 	if (!error)
5532ac27a0ecSDave Kleikamp 		error = rc;
5533ac27a0ecSDave Kleikamp 	return error;
5534ac27a0ecSDave Kleikamp }
5535ac27a0ecSDave Kleikamp 
55368434ef1dSEric Biggers u32 ext4_dio_alignment(struct inode *inode)
55378434ef1dSEric Biggers {
55388434ef1dSEric Biggers 	if (fsverity_active(inode))
55398434ef1dSEric Biggers 		return 0;
55408434ef1dSEric Biggers 	if (ext4_should_journal_data(inode))
55418434ef1dSEric Biggers 		return 0;
55428434ef1dSEric Biggers 	if (ext4_has_inline_data(inode))
55438434ef1dSEric Biggers 		return 0;
55448434ef1dSEric Biggers 	if (IS_ENCRYPTED(inode)) {
55458434ef1dSEric Biggers 		if (!fscrypt_dio_supported(inode))
55468434ef1dSEric Biggers 			return 0;
55478434ef1dSEric Biggers 		return i_blocksize(inode);
55488434ef1dSEric Biggers 	}
55498434ef1dSEric Biggers 	return 1; /* use the iomap defaults */
55508434ef1dSEric Biggers }
55518434ef1dSEric Biggers 
5552b74d24f7SChristian Brauner int ext4_getattr(struct mnt_idmap *idmap, const struct path *path,
5553549c7297SChristian Brauner 		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
55543e3398a0SMingming Cao {
555599652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
555699652ea5SDavid Howells 	struct ext4_inode *raw_inode;
555799652ea5SDavid Howells 	struct ext4_inode_info *ei = EXT4_I(inode);
555899652ea5SDavid Howells 	unsigned int flags;
55593e3398a0SMingming Cao 
5560d4c5e960STheodore Ts'o 	if ((request_mask & STATX_BTIME) &&
5561d4c5e960STheodore Ts'o 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
556299652ea5SDavid Howells 		stat->result_mask |= STATX_BTIME;
556399652ea5SDavid Howells 		stat->btime.tv_sec = ei->i_crtime.tv_sec;
556499652ea5SDavid Howells 		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
556599652ea5SDavid Howells 	}
556699652ea5SDavid Howells 
55678434ef1dSEric Biggers 	/*
55688434ef1dSEric Biggers 	 * Return the DIO alignment restrictions if requested.  We only return
55698434ef1dSEric Biggers 	 * this information when requested, since on encrypted files it might
55708434ef1dSEric Biggers 	 * take a fair bit of work to get if the file wasn't opened recently.
55718434ef1dSEric Biggers 	 */
55728434ef1dSEric Biggers 	if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
55738434ef1dSEric Biggers 		u32 dio_align = ext4_dio_alignment(inode);
55748434ef1dSEric Biggers 
55758434ef1dSEric Biggers 		stat->result_mask |= STATX_DIOALIGN;
55768434ef1dSEric Biggers 		if (dio_align == 1) {
55778434ef1dSEric Biggers 			struct block_device *bdev = inode->i_sb->s_bdev;
55788434ef1dSEric Biggers 
55798434ef1dSEric Biggers 			/* iomap defaults */
55808434ef1dSEric Biggers 			stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
55818434ef1dSEric Biggers 			stat->dio_offset_align = bdev_logical_block_size(bdev);
55828434ef1dSEric Biggers 		} else {
55838434ef1dSEric Biggers 			stat->dio_mem_align = dio_align;
55848434ef1dSEric Biggers 			stat->dio_offset_align = dio_align;
55858434ef1dSEric Biggers 		}
55868434ef1dSEric Biggers 	}
55878434ef1dSEric Biggers 
558899652ea5SDavid Howells 	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
558999652ea5SDavid Howells 	if (flags & EXT4_APPEND_FL)
559099652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_APPEND;
559199652ea5SDavid Howells 	if (flags & EXT4_COMPR_FL)
559299652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_COMPRESSED;
559399652ea5SDavid Howells 	if (flags & EXT4_ENCRYPT_FL)
559499652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_ENCRYPTED;
559599652ea5SDavid Howells 	if (flags & EXT4_IMMUTABLE_FL)
559699652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_IMMUTABLE;
559799652ea5SDavid Howells 	if (flags & EXT4_NODUMP_FL)
559899652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_NODUMP;
55991f607195SEric Biggers 	if (flags & EXT4_VERITY_FL)
56001f607195SEric Biggers 		stat->attributes |= STATX_ATTR_VERITY;
560199652ea5SDavid Howells 
56023209f68bSDavid Howells 	stat->attributes_mask |= (STATX_ATTR_APPEND |
56033209f68bSDavid Howells 				  STATX_ATTR_COMPRESSED |
56043209f68bSDavid Howells 				  STATX_ATTR_ENCRYPTED |
56053209f68bSDavid Howells 				  STATX_ATTR_IMMUTABLE |
56061f607195SEric Biggers 				  STATX_ATTR_NODUMP |
56071f607195SEric Biggers 				  STATX_ATTR_VERITY);
56083209f68bSDavid Howells 
56090d72b928SJeff Layton 	generic_fillattr(idmap, request_mask, inode, stat);
561099652ea5SDavid Howells 	return 0;
561199652ea5SDavid Howells }
561299652ea5SDavid Howells 
5613b74d24f7SChristian Brauner int ext4_file_getattr(struct mnt_idmap *idmap,
5614549c7297SChristian Brauner 		      const struct path *path, struct kstat *stat,
561599652ea5SDavid Howells 		      u32 request_mask, unsigned int query_flags)
561699652ea5SDavid Howells {
561799652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
561899652ea5SDavid Howells 	u64 delalloc_blocks;
561999652ea5SDavid Howells 
5620b74d24f7SChristian Brauner 	ext4_getattr(idmap, path, stat, request_mask, query_flags);
56213e3398a0SMingming Cao 
56223e3398a0SMingming Cao 	/*
56239206c561SAndreas Dilger 	 * If there is inline data in the inode, the inode will normally not
56249206c561SAndreas Dilger 	 * have data blocks allocated (it may have an external xattr block).
56259206c561SAndreas Dilger 	 * Report at least one sector for such files, so tools like tar, rsync,
5626d67d64f4STheodore Ts'o 	 * others don't incorrectly think the file is completely sparse.
56279206c561SAndreas Dilger 	 */
56289206c561SAndreas Dilger 	if (unlikely(ext4_has_inline_data(inode)))
56299206c561SAndreas Dilger 		stat->blocks += (stat->size + 511) >> 9;
56309206c561SAndreas Dilger 
56319206c561SAndreas Dilger 	/*
56323e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
56333e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
56343e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
56353e3398a0SMingming Cao 	 * on-disk file blocks.
56363e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
56373e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
56383e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
56393e3398a0SMingming Cao 	 * blocks for this file.
56403e3398a0SMingming Cao 	 */
564196607551STao Ma 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
564296607551STao Ma 				   EXT4_I(inode)->i_reserved_data_blocks);
56438af8eeccSJan Kara 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
56443e3398a0SMingming Cao 	return 0;
56453e3398a0SMingming Cao }
5646ac27a0ecSDave Kleikamp 
5647fffb2739SJan Kara static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5648fffb2739SJan Kara 				   int pextents)
5649a02908f1SMingming Cao {
565012e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5651fffb2739SJan Kara 		return ext4_ind_trans_blocks(inode, lblocks);
5652fffb2739SJan Kara 	return ext4_ext_index_trans_blocks(inode, pextents);
5653a02908f1SMingming Cao }
5654ac51d837STheodore Ts'o 
5655a02908f1SMingming Cao /*
5656a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
5657a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
5658a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
5659a02908f1SMingming Cao  *
5660a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
56614907cb7bSAnatol Pomozov  * different block groups too. If they are contiguous, with flexbg,
5662a02908f1SMingming Cao  * they could still across block group boundary.
5663a02908f1SMingming Cao  *
5664a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
5665a02908f1SMingming Cao  */
5666dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5667fffb2739SJan Kara 				  int pextents)
5668a02908f1SMingming Cao {
56698df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
56708df9675fSTheodore Ts'o 	int gdpblocks;
5671a02908f1SMingming Cao 	int idxblocks;
56727fc51f92SXU pengfei 	int ret;
5673a02908f1SMingming Cao 
5674a02908f1SMingming Cao 	/*
5675fffb2739SJan Kara 	 * How many index blocks need to touch to map @lblocks logical blocks
5676fffb2739SJan Kara 	 * to @pextents physical extents?
5677a02908f1SMingming Cao 	 */
5678fffb2739SJan Kara 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5679a02908f1SMingming Cao 
5680a02908f1SMingming Cao 	ret = idxblocks;
5681a02908f1SMingming Cao 
5682a02908f1SMingming Cao 	/*
5683a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
5684a02908f1SMingming Cao 	 * to account
5685a02908f1SMingming Cao 	 */
5686fffb2739SJan Kara 	groups = idxblocks + pextents;
5687a02908f1SMingming Cao 	gdpblocks = groups;
56888df9675fSTheodore Ts'o 	if (groups > ngroups)
56898df9675fSTheodore Ts'o 		groups = ngroups;
5690a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5691a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5692a02908f1SMingming Cao 
5693a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
5694a02908f1SMingming Cao 	ret += groups + gdpblocks;
5695a02908f1SMingming Cao 
5696a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
5697a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5698ac27a0ecSDave Kleikamp 
5699ac27a0ecSDave Kleikamp 	return ret;
5700ac27a0ecSDave Kleikamp }
5701ac27a0ecSDave Kleikamp 
5702ac27a0ecSDave Kleikamp /*
570325985edcSLucas De Marchi  * Calculate the total number of credits to reserve to fit
5704f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
5705f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
5706a02908f1SMingming Cao  *
5707525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
5708a02908f1SMingming Cao  *
5709525f4ed8SMingming Cao  * We need to consider the worse case, when
5710a02908f1SMingming Cao  * one new block per extent.
5711a02908f1SMingming Cao  */
5712a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
5713a02908f1SMingming Cao {
5714a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
5715a02908f1SMingming Cao 	int ret;
5716a02908f1SMingming Cao 
5717fffb2739SJan Kara 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5718a02908f1SMingming Cao 
5719a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
5720a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
5721a02908f1SMingming Cao 		ret += bpp;
5722a02908f1SMingming Cao 	return ret;
5723a02908f1SMingming Cao }
5724f3bd1f3fSMingming Cao 
5725f3bd1f3fSMingming Cao /*
5726f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
5727f3bd1f3fSMingming Cao  *
5728f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
572979e83036SEric Sandeen  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5730f3bd1f3fSMingming Cao  *
5731f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
5732f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
5733f3bd1f3fSMingming Cao  */
5734f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5735f3bd1f3fSMingming Cao {
5736f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5737f3bd1f3fSMingming Cao }
5738f3bd1f3fSMingming Cao 
5739a02908f1SMingming Cao /*
5740617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
5741ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
5742ac27a0ecSDave Kleikamp  */
5743617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
5744617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
5745ac27a0ecSDave Kleikamp {
5746ac27a0ecSDave Kleikamp 	int err = 0;
5747ac27a0ecSDave Kleikamp 
5748eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb))) {
5749a6758309SVasily Averin 		put_bh(iloc->bh);
57500db1ff22STheodore Ts'o 		return -EIO;
5751a6758309SVasily Averin 	}
5752a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_inode(handle, inode);
5753aa75f4d3SHarshad Shirwadkar 
5754ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
5755ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
5756ac27a0ecSDave Kleikamp 
5757dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5758830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
5759ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
5760ac27a0ecSDave Kleikamp 	return err;
5761ac27a0ecSDave Kleikamp }
5762ac27a0ecSDave Kleikamp 
5763ac27a0ecSDave Kleikamp /*
5764ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
5765ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
5766ac27a0ecSDave Kleikamp  */
5767ac27a0ecSDave Kleikamp 
5768ac27a0ecSDave Kleikamp int
5769617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5770617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
5771ac27a0ecSDave Kleikamp {
57720390131bSFrank Mayhar 	int err;
57730390131bSFrank Mayhar 
5774eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
57750db1ff22STheodore Ts'o 		return -EIO;
57760db1ff22STheodore Ts'o 
5777617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
5778ac27a0ecSDave Kleikamp 	if (!err) {
5779ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
5780188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb,
5781188c299eSJan Kara 						    iloc->bh, EXT4_JTR_NONE);
5782ac27a0ecSDave Kleikamp 		if (err) {
5783ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
5784ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
5785ac27a0ecSDave Kleikamp 		}
5786ac27a0ecSDave Kleikamp 	}
5787617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5788ac27a0ecSDave Kleikamp 	return err;
5789ac27a0ecSDave Kleikamp }
5790ac27a0ecSDave Kleikamp 
5791c03b45b8SMiao Xie static int __ext4_expand_extra_isize(struct inode *inode,
5792c03b45b8SMiao Xie 				     unsigned int new_extra_isize,
5793c03b45b8SMiao Xie 				     struct ext4_iloc *iloc,
5794c03b45b8SMiao Xie 				     handle_t *handle, int *no_expand)
5795c03b45b8SMiao Xie {
5796c03b45b8SMiao Xie 	struct ext4_inode *raw_inode;
5797c03b45b8SMiao Xie 	struct ext4_xattr_ibody_header *header;
57984ea99936STheodore Ts'o 	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
57994ea99936STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
5800c03b45b8SMiao Xie 	int error;
5801c03b45b8SMiao Xie 
58024ea99936STheodore Ts'o 	/* this was checked at iget time, but double check for good measure */
58034ea99936STheodore Ts'o 	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
58044ea99936STheodore Ts'o 	    (ei->i_extra_isize & 3)) {
58054ea99936STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
58064ea99936STheodore Ts'o 				 ei->i_extra_isize,
58074ea99936STheodore Ts'o 				 EXT4_INODE_SIZE(inode->i_sb));
58084ea99936STheodore Ts'o 		return -EFSCORRUPTED;
58094ea99936STheodore Ts'o 	}
58104ea99936STheodore Ts'o 	if ((new_extra_isize < ei->i_extra_isize) ||
58114ea99936STheodore Ts'o 	    (new_extra_isize < 4) ||
58124ea99936STheodore Ts'o 	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
58134ea99936STheodore Ts'o 		return -EINVAL;	/* Should never happen */
58144ea99936STheodore Ts'o 
5815c03b45b8SMiao Xie 	raw_inode = ext4_raw_inode(iloc);
5816c03b45b8SMiao Xie 
5817c03b45b8SMiao Xie 	header = IHDR(inode, raw_inode);
5818c03b45b8SMiao Xie 
5819c03b45b8SMiao Xie 	/* No extended attributes present */
5820c03b45b8SMiao Xie 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5821c03b45b8SMiao Xie 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5822c03b45b8SMiao Xie 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5823c03b45b8SMiao Xie 		       EXT4_I(inode)->i_extra_isize, 0,
5824c03b45b8SMiao Xie 		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
5825c03b45b8SMiao Xie 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
5826c03b45b8SMiao Xie 		return 0;
5827c03b45b8SMiao Xie 	}
5828c03b45b8SMiao Xie 
58298994d113SJan Kara 	/*
58308994d113SJan Kara 	 * We may need to allocate external xattr block so we need quotas
58318994d113SJan Kara 	 * initialized. Here we can be called with various locks held so we
58328994d113SJan Kara 	 * cannot affort to initialize quotas ourselves. So just bail.
58338994d113SJan Kara 	 */
58348994d113SJan Kara 	if (dquot_initialize_needed(inode))
58358994d113SJan Kara 		return -EAGAIN;
58368994d113SJan Kara 
5837c03b45b8SMiao Xie 	/* try to expand with EAs present */
5838c03b45b8SMiao Xie 	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5839c03b45b8SMiao Xie 					   raw_inode, handle);
5840c03b45b8SMiao Xie 	if (error) {
5841c03b45b8SMiao Xie 		/*
5842c03b45b8SMiao Xie 		 * Inode size expansion failed; don't try again
5843c03b45b8SMiao Xie 		 */
5844c03b45b8SMiao Xie 		*no_expand = 1;
5845c03b45b8SMiao Xie 	}
5846c03b45b8SMiao Xie 
5847c03b45b8SMiao Xie 	return error;
5848c03b45b8SMiao Xie }
5849c03b45b8SMiao Xie 
5850ac27a0ecSDave Kleikamp /*
58516dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
58526dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
58536dd4ee7cSKalpak Shah  */
5854cf0a5e81SMiao Xie static int ext4_try_to_expand_extra_isize(struct inode *inode,
58551d03ec98SAneesh Kumar K.V 					  unsigned int new_extra_isize,
58561d03ec98SAneesh Kumar K.V 					  struct ext4_iloc iloc,
58571d03ec98SAneesh Kumar K.V 					  handle_t *handle)
58586dd4ee7cSKalpak Shah {
58593b10fdc6SMiao Xie 	int no_expand;
58603b10fdc6SMiao Xie 	int error;
58616dd4ee7cSKalpak Shah 
5862cf0a5e81SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5863cf0a5e81SMiao Xie 		return -EOVERFLOW;
5864cf0a5e81SMiao Xie 
5865cf0a5e81SMiao Xie 	/*
5866cf0a5e81SMiao Xie 	 * In nojournal mode, we can immediately attempt to expand
5867cf0a5e81SMiao Xie 	 * the inode.  When journaled, we first need to obtain extra
5868cf0a5e81SMiao Xie 	 * buffer credits since we may write into the EA block
5869cf0a5e81SMiao Xie 	 * with this same handle. If journal_extend fails, then it will
5870cf0a5e81SMiao Xie 	 * only result in a minor loss of functionality for that inode.
5871cf0a5e81SMiao Xie 	 * If this is felt to be critical, then e2fsck should be run to
5872cf0a5e81SMiao Xie 	 * force a large enough s_min_extra_isize.
5873cf0a5e81SMiao Xie 	 */
58746cb367c2SJan Kara 	if (ext4_journal_extend(handle,
587583448bdfSJan Kara 				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5876cf0a5e81SMiao Xie 		return -ENOSPC;
58776dd4ee7cSKalpak Shah 
58783b10fdc6SMiao Xie 	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5879cf0a5e81SMiao Xie 		return -EBUSY;
58803b10fdc6SMiao Xie 
5881c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5882c03b45b8SMiao Xie 					  handle, &no_expand);
58833b10fdc6SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5884c03b45b8SMiao Xie 
5885c03b45b8SMiao Xie 	return error;
58866dd4ee7cSKalpak Shah }
58876dd4ee7cSKalpak Shah 
5888c03b45b8SMiao Xie int ext4_expand_extra_isize(struct inode *inode,
5889c03b45b8SMiao Xie 			    unsigned int new_extra_isize,
5890c03b45b8SMiao Xie 			    struct ext4_iloc *iloc)
5891c03b45b8SMiao Xie {
5892c03b45b8SMiao Xie 	handle_t *handle;
5893c03b45b8SMiao Xie 	int no_expand;
5894c03b45b8SMiao Xie 	int error, rc;
5895c03b45b8SMiao Xie 
5896c03b45b8SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5897c03b45b8SMiao Xie 		brelse(iloc->bh);
5898c03b45b8SMiao Xie 		return -EOVERFLOW;
5899c03b45b8SMiao Xie 	}
5900c03b45b8SMiao Xie 
5901c03b45b8SMiao Xie 	handle = ext4_journal_start(inode, EXT4_HT_INODE,
5902c03b45b8SMiao Xie 				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5903c03b45b8SMiao Xie 	if (IS_ERR(handle)) {
5904c03b45b8SMiao Xie 		error = PTR_ERR(handle);
5905c03b45b8SMiao Xie 		brelse(iloc->bh);
5906c03b45b8SMiao Xie 		return error;
5907c03b45b8SMiao Xie 	}
5908c03b45b8SMiao Xie 
5909c03b45b8SMiao Xie 	ext4_write_lock_xattr(inode, &no_expand);
5910c03b45b8SMiao Xie 
5911ddccb6dbSzhangyi (F) 	BUFFER_TRACE(iloc->bh, "get_write_access");
5912188c299eSJan Kara 	error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
5913188c299eSJan Kara 					      EXT4_JTR_NONE);
59143b10fdc6SMiao Xie 	if (error) {
5915c03b45b8SMiao Xie 		brelse(iloc->bh);
59167f420d64SDan Carpenter 		goto out_unlock;
59173b10fdc6SMiao Xie 	}
5918cf0a5e81SMiao Xie 
5919c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5920c03b45b8SMiao Xie 					  handle, &no_expand);
5921c03b45b8SMiao Xie 
5922c03b45b8SMiao Xie 	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5923c03b45b8SMiao Xie 	if (!error)
5924c03b45b8SMiao Xie 		error = rc;
5925c03b45b8SMiao Xie 
59267f420d64SDan Carpenter out_unlock:
5927c03b45b8SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5928c03b45b8SMiao Xie 	ext4_journal_stop(handle);
59293b10fdc6SMiao Xie 	return error;
59306dd4ee7cSKalpak Shah }
59316dd4ee7cSKalpak Shah 
59326dd4ee7cSKalpak Shah /*
5933ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
5934ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
5935ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
5936ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
5937ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
5938ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
5939ac27a0ecSDave Kleikamp  *
5940ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
5941ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
5942ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5943ac27a0ecSDave Kleikamp  * we start and wait on commits.
5944ac27a0ecSDave Kleikamp  */
59454209ae12SHarshad Shirwadkar int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
59464209ae12SHarshad Shirwadkar 				const char *func, unsigned int line)
5947ac27a0ecSDave Kleikamp {
5948617ba13bSMingming Cao 	struct ext4_iloc iloc;
59496dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5950cf0a5e81SMiao Xie 	int err;
5951ac27a0ecSDave Kleikamp 
5952ac27a0ecSDave Kleikamp 	might_sleep();
59537ff9c073STheodore Ts'o 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5954617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
59555e1021f2SEryu Guan 	if (err)
59564209ae12SHarshad Shirwadkar 		goto out;
5957cf0a5e81SMiao Xie 
5958cf0a5e81SMiao Xie 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5959cf0a5e81SMiao Xie 		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
59606dd4ee7cSKalpak Shah 					       iloc, handle);
5961cf0a5e81SMiao Xie 
59624209ae12SHarshad Shirwadkar 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
59634209ae12SHarshad Shirwadkar out:
59644209ae12SHarshad Shirwadkar 	if (unlikely(err))
59654209ae12SHarshad Shirwadkar 		ext4_error_inode_err(inode, func, line, 0, err,
59664209ae12SHarshad Shirwadkar 					"mark_inode_dirty error");
59674209ae12SHarshad Shirwadkar 	return err;
5968ac27a0ecSDave Kleikamp }
5969ac27a0ecSDave Kleikamp 
5970ac27a0ecSDave Kleikamp /*
5971617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
5972ac27a0ecSDave Kleikamp  *
5973ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
5974ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
5975ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
5976ac27a0ecSDave Kleikamp  *
59775dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
5978ac27a0ecSDave Kleikamp  * are allocated to the file.
5979ac27a0ecSDave Kleikamp  *
5980ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
5981ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
5982ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
5983ac27a0ecSDave Kleikamp  */
5984aa385729SChristoph Hellwig void ext4_dirty_inode(struct inode *inode, int flags)
5985ac27a0ecSDave Kleikamp {
5986ac27a0ecSDave Kleikamp 	handle_t *handle;
5987ac27a0ecSDave Kleikamp 
59889924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5989ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5990ac27a0ecSDave Kleikamp 		return;
5991e2728c56SEric Biggers 	ext4_mark_inode_dirty(handle, inode);
5992e2728c56SEric Biggers 	ext4_journal_stop(handle);
5993ac27a0ecSDave Kleikamp }
5994ac27a0ecSDave Kleikamp 
5995617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
5996ac27a0ecSDave Kleikamp {
5997ac27a0ecSDave Kleikamp 	journal_t *journal;
5998ac27a0ecSDave Kleikamp 	handle_t *handle;
5999ac27a0ecSDave Kleikamp 	int err;
600000d873c1SJan Kara 	int alloc_ctx;
6001ac27a0ecSDave Kleikamp 
6002ac27a0ecSDave Kleikamp 	/*
6003ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
6004ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
6005ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
6006ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
6007ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
6008ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
6009ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
6010ac27a0ecSDave Kleikamp 	 */
6011ac27a0ecSDave Kleikamp 
6012617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
60130390131bSFrank Mayhar 	if (!journal)
60140390131bSFrank Mayhar 		return 0;
6015d699594dSDave Hansen 	if (is_journal_aborted(journal))
6016ac27a0ecSDave Kleikamp 		return -EROFS;
6017ac27a0ecSDave Kleikamp 
601817335dccSDmitry Monakhov 	/* Wait for all existing dio workers */
601917335dccSDmitry Monakhov 	inode_dio_wait(inode);
602017335dccSDmitry Monakhov 
60214c546592SDaeho Jeong 	/*
60224c546592SDaeho Jeong 	 * Before flushing the journal and switching inode's aops, we have
60234c546592SDaeho Jeong 	 * to flush all dirty data the inode has. There can be outstanding
60244c546592SDaeho Jeong 	 * delayed allocations, there can be unwritten extents created by
60254c546592SDaeho Jeong 	 * fallocate or buffered writes in dioread_nolock mode covered by
60264c546592SDaeho Jeong 	 * dirty data which can be converted only after flushing the dirty
60274c546592SDaeho Jeong 	 * data (and journalled aops don't know how to handle these cases).
60284c546592SDaeho Jeong 	 */
60294c546592SDaeho Jeong 	if (val) {
6030d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
60314c546592SDaeho Jeong 		err = filemap_write_and_wait(inode->i_mapping);
60324c546592SDaeho Jeong 		if (err < 0) {
6033d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
60344c546592SDaeho Jeong 			return err;
60354c546592SDaeho Jeong 		}
60364c546592SDaeho Jeong 	}
60374c546592SDaeho Jeong 
603800d873c1SJan Kara 	alloc_ctx = ext4_writepages_down_write(inode->i_sb);
6039dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
6040ac27a0ecSDave Kleikamp 
6041ac27a0ecSDave Kleikamp 	/*
6042ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
6043ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
6044ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
6045ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
6046ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
6047ac27a0ecSDave Kleikamp 	 */
6048ac27a0ecSDave Kleikamp 
6049ac27a0ecSDave Kleikamp 	if (val)
605012e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60515872ddaaSYongqiang Yang 	else {
605201d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
60534f879ca6SJan Kara 		if (err < 0) {
60544f879ca6SJan Kara 			jbd2_journal_unlock_updates(journal);
605500d873c1SJan Kara 			ext4_writepages_up_write(inode->i_sb, alloc_ctx);
60564f879ca6SJan Kara 			return err;
60574f879ca6SJan Kara 		}
605812e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60595872ddaaSYongqiang Yang 	}
6060617ba13bSMingming Cao 	ext4_set_aops(inode);
6061ac27a0ecSDave Kleikamp 
6062dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
606300d873c1SJan Kara 	ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6064c8585c6fSDaeho Jeong 
60654c546592SDaeho Jeong 	if (val)
6066d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
6067ac27a0ecSDave Kleikamp 
6068ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
6069ac27a0ecSDave Kleikamp 
60709924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6071ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
6072ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
6073ac27a0ecSDave Kleikamp 
6074aa75f4d3SHarshad Shirwadkar 	ext4_fc_mark_ineligible(inode->i_sb,
6075e85c81baSXin Yin 		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6076617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
60770390131bSFrank Mayhar 	ext4_handle_sync(handle);
6078617ba13bSMingming Cao 	ext4_journal_stop(handle);
6079617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
6080ac27a0ecSDave Kleikamp 
6081ac27a0ecSDave Kleikamp 	return err;
6082ac27a0ecSDave Kleikamp }
60832e9ee850SAneesh Kumar K.V 
6084188c299eSJan Kara static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6085188c299eSJan Kara 			    struct buffer_head *bh)
60862e9ee850SAneesh Kumar K.V {
60872e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
60882e9ee850SAneesh Kumar K.V }
60892e9ee850SAneesh Kumar K.V 
6090401b25aaSSouptick Joarder vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
60912e9ee850SAneesh Kumar K.V {
609211bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
60939ea0e45bSMatthew Wilcox 	struct folio *folio = page_folio(vmf->page);
60942e9ee850SAneesh Kumar K.V 	loff_t size;
60952e9ee850SAneesh Kumar K.V 	unsigned long len;
6096401b25aaSSouptick Joarder 	int err;
6097401b25aaSSouptick Joarder 	vm_fault_t ret;
60982e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
6099496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
61002e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
61019ea7df53SJan Kara 	handle_t *handle;
61029ea7df53SJan Kara 	get_block_t *get_block;
61039ea7df53SJan Kara 	int retries = 0;
61042e9ee850SAneesh Kumar K.V 
610502b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
610602b016caSTheodore Ts'o 		return VM_FAULT_SIGBUS;
610702b016caSTheodore Ts'o 
61088e8ad8a5SJan Kara 	sb_start_pagefault(inode->i_sb);
6109041bbb6dSTheodore Ts'o 	file_update_time(vma->vm_file);
6110ea3d7209SJan Kara 
6111d4f5258eSJan Kara 	filemap_invalidate_lock_shared(mapping);
61127b4cc978SEric Biggers 
6113401b25aaSSouptick Joarder 	err = ext4_convert_inline_data(inode);
6114401b25aaSSouptick Joarder 	if (err)
61157b4cc978SEric Biggers 		goto out_ret;
61167b4cc978SEric Biggers 
611764a9f144SMauricio Faria de Oliveira 	/*
611864a9f144SMauricio Faria de Oliveira 	 * On data journalling we skip straight to the transaction handle:
611964a9f144SMauricio Faria de Oliveira 	 * there's no delalloc; page truncated will be checked later; the
612064a9f144SMauricio Faria de Oliveira 	 * early return w/ all buffers mapped (calculates size/len) can't
612164a9f144SMauricio Faria de Oliveira 	 * be used; and there's no dioread_nolock, so only ext4_get_block.
612264a9f144SMauricio Faria de Oliveira 	 */
612364a9f144SMauricio Faria de Oliveira 	if (ext4_should_journal_data(inode))
612464a9f144SMauricio Faria de Oliveira 		goto retry_alloc;
612564a9f144SMauricio Faria de Oliveira 
61269ea7df53SJan Kara 	/* Delalloc case is easy... */
61279ea7df53SJan Kara 	if (test_opt(inode->i_sb, DELALLOC) &&
61289ea7df53SJan Kara 	    !ext4_nonda_switch(inode->i_sb)) {
61299ea7df53SJan Kara 		do {
6130401b25aaSSouptick Joarder 			err = block_page_mkwrite(vma, vmf,
61319ea7df53SJan Kara 						   ext4_da_get_block_prep);
6132401b25aaSSouptick Joarder 		} while (err == -ENOSPC &&
61339ea7df53SJan Kara 		       ext4_should_retry_alloc(inode->i_sb, &retries));
61349ea7df53SJan Kara 		goto out_ret;
61352e9ee850SAneesh Kumar K.V 	}
61360e499890SDarrick J. Wong 
61379ea0e45bSMatthew Wilcox 	folio_lock(folio);
61389ea7df53SJan Kara 	size = i_size_read(inode);
61399ea7df53SJan Kara 	/* Page got truncated from under us? */
61409ea0e45bSMatthew Wilcox 	if (folio->mapping != mapping || folio_pos(folio) > size) {
61419ea0e45bSMatthew Wilcox 		folio_unlock(folio);
61429ea7df53SJan Kara 		ret = VM_FAULT_NOPAGE;
61439ea7df53SJan Kara 		goto out;
61440e499890SDarrick J. Wong 	}
61452e9ee850SAneesh Kumar K.V 
61469ea0e45bSMatthew Wilcox 	len = folio_size(folio);
61479ea0e45bSMatthew Wilcox 	if (folio_pos(folio) + len > size)
61489ea0e45bSMatthew Wilcox 		len = size - folio_pos(folio);
6149a827eaffSAneesh Kumar K.V 	/*
61509ea7df53SJan Kara 	 * Return if we have all the buffers mapped. This avoids the need to do
61519ea7df53SJan Kara 	 * journal_start/journal_stop which can block and take a long time
615264a9f144SMauricio Faria de Oliveira 	 *
615364a9f144SMauricio Faria de Oliveira 	 * This cannot be done for data journalling, as we have to add the
615464a9f144SMauricio Faria de Oliveira 	 * inode to the transaction's list to writeprotect pages on commit.
6155a827eaffSAneesh Kumar K.V 	 */
61569ea0e45bSMatthew Wilcox 	if (folio_buffers(folio)) {
61579ea0e45bSMatthew Wilcox 		if (!ext4_walk_page_buffers(NULL, inode, folio_buffers(folio),
6158f19d5870STao Ma 					    0, len, NULL,
6159a827eaffSAneesh Kumar K.V 					    ext4_bh_unmapped)) {
61609ea7df53SJan Kara 			/* Wait so that we don't change page under IO */
61619ea0e45bSMatthew Wilcox 			folio_wait_stable(folio);
61629ea7df53SJan Kara 			ret = VM_FAULT_LOCKED;
61639ea7df53SJan Kara 			goto out;
61642e9ee850SAneesh Kumar K.V 		}
6165a827eaffSAneesh Kumar K.V 	}
61669ea0e45bSMatthew Wilcox 	folio_unlock(folio);
61679ea7df53SJan Kara 	/* OK, we need to fill the hole... */
61689ea7df53SJan Kara 	if (ext4_should_dioread_nolock(inode))
6169705965bdSJan Kara 		get_block = ext4_get_block_unwritten;
61709ea7df53SJan Kara 	else
61719ea7df53SJan Kara 		get_block = ext4_get_block;
61729ea7df53SJan Kara retry_alloc:
61739924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
61749924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
61759ea7df53SJan Kara 	if (IS_ERR(handle)) {
6176c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
61779ea7df53SJan Kara 		goto out;
61789ea7df53SJan Kara 	}
617964a9f144SMauricio Faria de Oliveira 	/*
618064a9f144SMauricio Faria de Oliveira 	 * Data journalling can't use block_page_mkwrite() because it
618164a9f144SMauricio Faria de Oliveira 	 * will set_buffer_dirty() before do_journal_get_write_access()
618264a9f144SMauricio Faria de Oliveira 	 * thus might hit warning messages for dirty metadata buffers.
618364a9f144SMauricio Faria de Oliveira 	 */
618464a9f144SMauricio Faria de Oliveira 	if (!ext4_should_journal_data(inode)) {
6185401b25aaSSouptick Joarder 		err = block_page_mkwrite(vma, vmf, get_block);
618664a9f144SMauricio Faria de Oliveira 	} else {
61879ea0e45bSMatthew Wilcox 		folio_lock(folio);
618864a9f144SMauricio Faria de Oliveira 		size = i_size_read(inode);
618964a9f144SMauricio Faria de Oliveira 		/* Page got truncated from under us? */
61909ea0e45bSMatthew Wilcox 		if (folio->mapping != mapping || folio_pos(folio) > size) {
619164a9f144SMauricio Faria de Oliveira 			ret = VM_FAULT_NOPAGE;
6192afb585a9SMauricio Faria de Oliveira 			goto out_error;
619364a9f144SMauricio Faria de Oliveira 		}
619464a9f144SMauricio Faria de Oliveira 
61959ea0e45bSMatthew Wilcox 		len = folio_size(folio);
61969ea0e45bSMatthew Wilcox 		if (folio_pos(folio) + len > size)
61979ea0e45bSMatthew Wilcox 			len = size - folio_pos(folio);
619864a9f144SMauricio Faria de Oliveira 
61999ea0e45bSMatthew Wilcox 		err = __block_write_begin(&folio->page, 0, len, ext4_get_block);
620064a9f144SMauricio Faria de Oliveira 		if (!err) {
62019ea7df53SJan Kara 			ret = VM_FAULT_SIGBUS;
620280be8c5cSRitesh Harjani 			if (ext4_journal_folio_buffers(handle, folio, len))
6203afb585a9SMauricio Faria de Oliveira 				goto out_error;
620464a9f144SMauricio Faria de Oliveira 		} else {
62059ea0e45bSMatthew Wilcox 			folio_unlock(folio);
620664a9f144SMauricio Faria de Oliveira 		}
62079ea7df53SJan Kara 	}
62089ea7df53SJan Kara 	ext4_journal_stop(handle);
6209401b25aaSSouptick Joarder 	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
62109ea7df53SJan Kara 		goto retry_alloc;
62119ea7df53SJan Kara out_ret:
62122ba39cc4SChristoph Hellwig 	ret = vmf_fs_error(err);
62139ea7df53SJan Kara out:
6214d4f5258eSJan Kara 	filemap_invalidate_unlock_shared(mapping);
62158e8ad8a5SJan Kara 	sb_end_pagefault(inode->i_sb);
62162e9ee850SAneesh Kumar K.V 	return ret;
6217afb585a9SMauricio Faria de Oliveira out_error:
62189ea0e45bSMatthew Wilcox 	folio_unlock(folio);
6219afb585a9SMauricio Faria de Oliveira 	ext4_journal_stop(handle);
6220afb585a9SMauricio Faria de Oliveira 	goto out;
62212e9ee850SAneesh Kumar K.V }
6222