xref: /openbmc/linux/fs/ext4/inode.c (revision 8216776ccff6fcd40e3fdaa109aa4150ebe760b3)
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 
45655138e0bSTheodore Ts'o /*
457e35fd660STheodore Ts'o  * The ext4_map_blocks() function tries to look up the requested blocks,
4582b2d6d01STheodore Ts'o  * and returns if the blocks are already mapped.
459f5ab0d1fSMingming Cao  *
460f5ab0d1fSMingming Cao  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
461f5ab0d1fSMingming Cao  * and store the allocated blocks in the result buffer head and mark it
462f5ab0d1fSMingming Cao  * mapped.
463f5ab0d1fSMingming Cao  *
464e35fd660STheodore Ts'o  * If file type is extents based, it will call ext4_ext_map_blocks(),
465e35fd660STheodore Ts'o  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
466f5ab0d1fSMingming Cao  * based files
467f5ab0d1fSMingming Cao  *
468facab4d9SJan Kara  * On success, it returns the number of blocks being mapped or allocated.  if
469facab4d9SJan Kara  * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
470facab4d9SJan Kara  * is marked as unwritten. If the create == 1, it will mark @map as mapped.
471f5ab0d1fSMingming Cao  *
472f5ab0d1fSMingming Cao  * It returns 0 if plain look up failed (blocks have not been allocated), in
473facab4d9SJan Kara  * that case, @map is returned as unmapped but we still do fill map->m_len to
474facab4d9SJan Kara  * indicate the length of a hole starting at map->m_lblk.
475f5ab0d1fSMingming Cao  *
476f5ab0d1fSMingming Cao  * It returns the error in case of allocation failure.
477f5ab0d1fSMingming Cao  */
478e35fd660STheodore Ts'o int ext4_map_blocks(handle_t *handle, struct inode *inode,
479e35fd660STheodore Ts'o 		    struct ext4_map_blocks *map, int flags)
4800e855ac8SAneesh Kumar K.V {
481d100eef2SZheng Liu 	struct extent_status es;
4820e855ac8SAneesh Kumar K.V 	int retval;
483b8a86845SLukas Czerner 	int ret = 0;
484921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
485921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
486921f266bSDmitry Monakhov 
487921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
488921f266bSDmitry Monakhov #endif
489f5ab0d1fSMingming Cao 
490e35fd660STheodore Ts'o 	map->m_flags = 0;
49170aa1554SRitesh Harjani 	ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
49270aa1554SRitesh Harjani 		  flags, map->m_len, (unsigned long) map->m_lblk);
493d100eef2SZheng Liu 
494e861b5e9STheodore Ts'o 	/*
495e861b5e9STheodore Ts'o 	 * ext4_map_blocks returns an int, and m_len is an unsigned int
496e861b5e9STheodore Ts'o 	 */
497e861b5e9STheodore Ts'o 	if (unlikely(map->m_len > INT_MAX))
498e861b5e9STheodore Ts'o 		map->m_len = INT_MAX;
499e861b5e9STheodore Ts'o 
5004adb6ab3SKazuya Mio 	/* We can handle the block number less than EXT_MAX_BLOCKS */
5014adb6ab3SKazuya Mio 	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
5026a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
5034adb6ab3SKazuya Mio 
504d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
5058016e29fSHarshad Shirwadkar 	if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
5068016e29fSHarshad Shirwadkar 	    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
507d100eef2SZheng Liu 		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
508d100eef2SZheng Liu 			map->m_pblk = ext4_es_pblock(&es) +
509d100eef2SZheng Liu 					map->m_lblk - es.es_lblk;
510d100eef2SZheng Liu 			map->m_flags |= ext4_es_is_written(&es) ?
511d100eef2SZheng Liu 					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
512d100eef2SZheng Liu 			retval = es.es_len - (map->m_lblk - es.es_lblk);
513d100eef2SZheng Liu 			if (retval > map->m_len)
514d100eef2SZheng Liu 				retval = map->m_len;
515d100eef2SZheng Liu 			map->m_len = retval;
516d100eef2SZheng Liu 		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
517facab4d9SJan Kara 			map->m_pblk = 0;
518facab4d9SJan Kara 			retval = es.es_len - (map->m_lblk - es.es_lblk);
519facab4d9SJan Kara 			if (retval > map->m_len)
520facab4d9SJan Kara 				retval = map->m_len;
521facab4d9SJan Kara 			map->m_len = retval;
522d100eef2SZheng Liu 			retval = 0;
523d100eef2SZheng Liu 		} else {
5241e83bc81SArnd Bergmann 			BUG();
525d100eef2SZheng Liu 		}
5269558cf14SZhang Yi 
5279558cf14SZhang Yi 		if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5289558cf14SZhang Yi 			return retval;
529921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
530921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(handle, inode, map,
531921f266bSDmitry Monakhov 					   &orig_map, flags);
532921f266bSDmitry Monakhov #endif
533d100eef2SZheng Liu 		goto found;
534d100eef2SZheng Liu 	}
5359558cf14SZhang Yi 	/*
5369558cf14SZhang Yi 	 * In the query cache no-wait mode, nothing we can do more if we
5379558cf14SZhang Yi 	 * cannot find extent in the cache.
5389558cf14SZhang Yi 	 */
5399558cf14SZhang Yi 	if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5409558cf14SZhang Yi 		return 0;
541d100eef2SZheng Liu 
5424df3d265SAneesh Kumar K.V 	/*
543b920c755STheodore Ts'o 	 * Try to see if we can get the block without requesting a new
544b920c755STheodore Ts'o 	 * file system block.
5454df3d265SAneesh Kumar K.V 	 */
546c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
54712e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5489e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
5494df3d265SAneesh Kumar K.V 	} else {
5509e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
5510e855ac8SAneesh Kumar K.V 	}
552f7fec032SZheng Liu 	if (retval > 0) {
5533be78c73STheodore Ts'o 		unsigned int status;
554f7fec032SZheng Liu 
55544fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
55644fb851dSZheng Liu 			ext4_warning(inode->i_sb,
55744fb851dSZheng Liu 				     "ES len assertion failed for inode "
55844fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
55944fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
56044fb851dSZheng Liu 			WARN_ON(1);
561921f266bSDmitry Monakhov 		}
562921f266bSDmitry Monakhov 
563f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
564f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
565f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
566d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
567ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
568f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
569f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
5706c120399SBaokun Li 		ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
5716c120399SBaokun Li 				      map->m_pblk, status);
572f7fec032SZheng Liu 	}
5734df3d265SAneesh Kumar K.V 	up_read((&EXT4_I(inode)->i_data_sem));
574f5ab0d1fSMingming Cao 
575d100eef2SZheng Liu found:
576e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
577b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
5786fd058f7STheodore Ts'o 		if (ret != 0)
5796fd058f7STheodore Ts'o 			return ret;
5806fd058f7STheodore Ts'o 	}
5816fd058f7STheodore Ts'o 
582f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
583c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
5844df3d265SAneesh Kumar K.V 		return retval;
5854df3d265SAneesh Kumar K.V 
5864df3d265SAneesh Kumar K.V 	/*
587f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
588f5ab0d1fSMingming Cao 	 *
589f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
590df3ab170STao Ma 	 * ext4_ext_get_block() returns the create = 0
591f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
592f5ab0d1fSMingming Cao 	 */
593e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
594b8a86845SLukas Czerner 		/*
595b8a86845SLukas Czerner 		 * If we need to convert extent to unwritten
596b8a86845SLukas Czerner 		 * we continue and do the actual work in
597b8a86845SLukas Czerner 		 * ext4_ext_map_blocks()
598b8a86845SLukas Czerner 		 */
599b8a86845SLukas Czerner 		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
600f5ab0d1fSMingming Cao 			return retval;
601f5ab0d1fSMingming Cao 
602f5ab0d1fSMingming Cao 	/*
603a25a4e1aSZheng Liu 	 * Here we clear m_flags because after allocating an new extent,
604a25a4e1aSZheng Liu 	 * it will be set again.
6052a8964d6SAneesh Kumar K.V 	 */
606a25a4e1aSZheng Liu 	map->m_flags &= ~EXT4_MAP_FLAGS;
6072a8964d6SAneesh Kumar K.V 
6082a8964d6SAneesh Kumar K.V 	/*
609556615dcSLukas Czerner 	 * New blocks allocate and/or writing to unwritten extent
610f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
611d91bd2c1SSeunghun Lee 	 * the write lock of i_data_sem, and call get_block()
612f5ab0d1fSMingming Cao 	 * with create == 1 flag.
6134df3d265SAneesh Kumar K.V 	 */
614c8b459f4SLukas Czerner 	down_write(&EXT4_I(inode)->i_data_sem);
615d2a17637SMingming Cao 
616d2a17637SMingming Cao 	/*
6174df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
6184df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
6194df3d265SAneesh Kumar K.V 	 */
62012e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
621e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
6220e855ac8SAneesh Kumar K.V 	} else {
623e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
624267e4db9SAneesh Kumar K.V 
625e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
626267e4db9SAneesh Kumar K.V 			/*
627267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
628267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
629267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
630267e4db9SAneesh Kumar K.V 			 */
63119f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
632267e4db9SAneesh Kumar K.V 		}
6335f634d06SAneesh Kumar K.V 	}
634d2a17637SMingming Cao 
635f7fec032SZheng Liu 	if (retval > 0) {
6363be78c73STheodore Ts'o 		unsigned int status;
637f7fec032SZheng Liu 
63844fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
63944fb851dSZheng Liu 			ext4_warning(inode->i_sb,
64044fb851dSZheng Liu 				     "ES len assertion failed for inode "
64144fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
64244fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
64344fb851dSZheng Liu 			WARN_ON(1);
644921f266bSDmitry Monakhov 		}
645921f266bSDmitry Monakhov 
646adb23551SZheng Liu 		/*
647c86d8db3SJan Kara 		 * We have to zeroout blocks before inserting them into extent
648c86d8db3SJan Kara 		 * status tree. Otherwise someone could look them up there and
6499b623df6SJan Kara 		 * use them before they are really zeroed. We also have to
6509b623df6SJan Kara 		 * unmap metadata before zeroing as otherwise writeback can
6519b623df6SJan Kara 		 * overwrite zeros with stale data from block device.
652c86d8db3SJan Kara 		 */
653c86d8db3SJan Kara 		if (flags & EXT4_GET_BLOCKS_ZERO &&
654c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_MAPPED &&
655c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_NEW) {
656c86d8db3SJan Kara 			ret = ext4_issue_zeroout(inode, map->m_lblk,
657c86d8db3SJan Kara 						 map->m_pblk, map->m_len);
658c86d8db3SJan Kara 			if (ret) {
659c86d8db3SJan Kara 				retval = ret;
660c86d8db3SJan Kara 				goto out_sem;
661c86d8db3SJan Kara 			}
662c86d8db3SJan Kara 		}
663c86d8db3SJan Kara 
664c86d8db3SJan Kara 		/*
665adb23551SZheng Liu 		 * If the extent has been zeroed out, we don't need to update
666adb23551SZheng Liu 		 * extent status tree.
667adb23551SZheng Liu 		 */
668adb23551SZheng Liu 		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
669bb5835edSTheodore Ts'o 		    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
670adb23551SZheng Liu 			if (ext4_es_is_written(&es))
671c86d8db3SJan Kara 				goto out_sem;
672adb23551SZheng Liu 		}
673f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
674f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
675f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
676d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
677ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
678f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
679f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
6806c120399SBaokun Li 		ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
681f7fec032SZheng Liu 				      map->m_pblk, status);
68251865fdaSZheng Liu 	}
6835356f261SAditya Kali 
684c86d8db3SJan Kara out_sem:
6850e855ac8SAneesh Kumar K.V 	up_write((&EXT4_I(inode)->i_data_sem));
686e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
687b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
6886fd058f7STheodore Ts'o 		if (ret != 0)
6896fd058f7STheodore Ts'o 			return ret;
69006bd3c36SJan Kara 
69106bd3c36SJan Kara 		/*
69206bd3c36SJan Kara 		 * Inodes with freshly allocated blocks where contents will be
69306bd3c36SJan Kara 		 * visible after transaction commit must be on transaction's
69406bd3c36SJan Kara 		 * ordered data list.
69506bd3c36SJan Kara 		 */
69606bd3c36SJan Kara 		if (map->m_flags & EXT4_MAP_NEW &&
69706bd3c36SJan Kara 		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
69806bd3c36SJan Kara 		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
69902749a4cSTahsin Erdogan 		    !ext4_is_quota_file(inode) &&
70006bd3c36SJan Kara 		    ext4_should_order_data(inode)) {
70173131fbbSRoss Zwisler 			loff_t start_byte =
70273131fbbSRoss Zwisler 				(loff_t)map->m_lblk << inode->i_blkbits;
70373131fbbSRoss Zwisler 			loff_t length = (loff_t)map->m_len << inode->i_blkbits;
70473131fbbSRoss Zwisler 
705ee0876bcSJan Kara 			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
70673131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_wait(handle, inode,
70773131fbbSRoss Zwisler 						start_byte, length);
708ee0876bcSJan Kara 			else
70973131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_write(handle, inode,
71073131fbbSRoss Zwisler 						start_byte, length);
71106bd3c36SJan Kara 			if (ret)
71206bd3c36SJan Kara 				return ret;
71306bd3c36SJan Kara 		}
7145e4d0ebaSXin Yin 	}
7155e4d0ebaSXin Yin 	if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
7165e4d0ebaSXin Yin 				map->m_flags & EXT4_MAP_MAPPED))
717a80f7fcfSHarshad Shirwadkar 		ext4_fc_track_range(handle, inode, map->m_lblk,
718aa75f4d3SHarshad Shirwadkar 					map->m_lblk + map->m_len - 1);
719ec8c60beSRitesh Harjani 	if (retval < 0)
72070aa1554SRitesh Harjani 		ext_debug(inode, "failed with err %d\n", retval);
7210e855ac8SAneesh Kumar K.V 	return retval;
7220e855ac8SAneesh Kumar K.V }
7230e855ac8SAneesh Kumar K.V 
724ed8ad838SJan Kara /*
725ed8ad838SJan Kara  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
726ed8ad838SJan Kara  * we have to be careful as someone else may be manipulating b_state as well.
727ed8ad838SJan Kara  */
728ed8ad838SJan Kara static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
729ed8ad838SJan Kara {
730ed8ad838SJan Kara 	unsigned long old_state;
731ed8ad838SJan Kara 	unsigned long new_state;
732ed8ad838SJan Kara 
733ed8ad838SJan Kara 	flags &= EXT4_MAP_FLAGS;
734ed8ad838SJan Kara 
735ed8ad838SJan Kara 	/* Dummy buffer_head? Set non-atomically. */
736ed8ad838SJan Kara 	if (!bh->b_page) {
737ed8ad838SJan Kara 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
738ed8ad838SJan Kara 		return;
739ed8ad838SJan Kara 	}
740ed8ad838SJan Kara 	/*
741ed8ad838SJan Kara 	 * Someone else may be modifying b_state. Be careful! This is ugly but
742ed8ad838SJan Kara 	 * once we get rid of using bh as a container for mapping information
743ed8ad838SJan Kara 	 * to pass to / from get_block functions, this can go away.
744ed8ad838SJan Kara 	 */
745ed8ad838SJan Kara 	old_state = READ_ONCE(bh->b_state);
7463ee2a3e7SUros Bizjak 	do {
747ed8ad838SJan Kara 		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
7483ee2a3e7SUros Bizjak 	} while (unlikely(!try_cmpxchg(&bh->b_state, &old_state, new_state)));
749ed8ad838SJan Kara }
750ed8ad838SJan Kara 
7512ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
7522ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
753ac27a0ecSDave Kleikamp {
7542ed88685STheodore Ts'o 	struct ext4_map_blocks map;
755efe70c29SJan Kara 	int ret = 0;
756ac27a0ecSDave Kleikamp 
75746c7f254STao Ma 	if (ext4_has_inline_data(inode))
75846c7f254STao Ma 		return -ERANGE;
75946c7f254STao Ma 
7602ed88685STheodore Ts'o 	map.m_lblk = iblock;
7612ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
7622ed88685STheodore Ts'o 
763efe70c29SJan Kara 	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
764efe70c29SJan Kara 			      flags);
765ac27a0ecSDave Kleikamp 	if (ret > 0) {
7662ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
767ed8ad838SJan Kara 		ext4_update_bh_state(bh, map.m_flags);
7682ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
769ac27a0ecSDave Kleikamp 		ret = 0;
770547edce3SRoss Zwisler 	} else if (ret == 0) {
771547edce3SRoss Zwisler 		/* hole case, need to fill in bh->b_size */
772547edce3SRoss Zwisler 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
773ac27a0ecSDave Kleikamp 	}
774ac27a0ecSDave Kleikamp 	return ret;
775ac27a0ecSDave Kleikamp }
776ac27a0ecSDave Kleikamp 
7772ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
7782ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
7792ed88685STheodore Ts'o {
7802ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
7812ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
7822ed88685STheodore Ts'o }
7832ed88685STheodore Ts'o 
784ac27a0ecSDave Kleikamp /*
785705965bdSJan Kara  * Get block function used when preparing for buffered write if we require
786705965bdSJan Kara  * creating an unwritten extent if blocks haven't been allocated.  The extent
787705965bdSJan Kara  * will be converted to written after the IO is complete.
788705965bdSJan Kara  */
789705965bdSJan Kara int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
790705965bdSJan Kara 			     struct buffer_head *bh_result, int create)
791705965bdSJan Kara {
792705965bdSJan Kara 	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
793705965bdSJan Kara 		   inode->i_ino, create);
794705965bdSJan Kara 	return _ext4_get_block(inode, iblock, bh_result,
7958d5459c1SJan Kara 			       EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
796705965bdSJan Kara }
797705965bdSJan Kara 
798efe70c29SJan Kara /* Maximum number of blocks we map for direct IO at once. */
799efe70c29SJan Kara #define DIO_MAX_BLOCKS 4096
800efe70c29SJan Kara 
801e84dfbe2SJan Kara /*
802ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
803ac27a0ecSDave Kleikamp  */
804617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
805c5e298aeSTheodore Ts'o 				ext4_lblk_t block, int map_flags)
806ac27a0ecSDave Kleikamp {
8072ed88685STheodore Ts'o 	struct ext4_map_blocks map;
8082ed88685STheodore Ts'o 	struct buffer_head *bh;
809c5e298aeSTheodore Ts'o 	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
8109558cf14SZhang Yi 	bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
81110560082STheodore Ts'o 	int err;
812ac27a0ecSDave Kleikamp 
813837c23fbSChunguang Xu 	ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8148016e29fSHarshad Shirwadkar 		    || handle != NULL || create == 0);
8159558cf14SZhang Yi 	ASSERT(create == 0 || !nowait);
816ac27a0ecSDave Kleikamp 
8172ed88685STheodore Ts'o 	map.m_lblk = block;
8182ed88685STheodore Ts'o 	map.m_len = 1;
819c5e298aeSTheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map, map_flags);
8202ed88685STheodore Ts'o 
82110560082STheodore Ts'o 	if (err == 0)
82210560082STheodore Ts'o 		return create ? ERR_PTR(-ENOSPC) : NULL;
8232ed88685STheodore Ts'o 	if (err < 0)
82410560082STheodore Ts'o 		return ERR_PTR(err);
8252ed88685STheodore Ts'o 
8269558cf14SZhang Yi 	if (nowait)
8279558cf14SZhang Yi 		return sb_find_get_block(inode->i_sb, map.m_pblk);
8289558cf14SZhang Yi 
8292ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
83010560082STheodore Ts'o 	if (unlikely(!bh))
83110560082STheodore Ts'o 		return ERR_PTR(-ENOMEM);
8322ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
833837c23fbSChunguang Xu 		ASSERT(create != 0);
834837c23fbSChunguang Xu 		ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8358016e29fSHarshad Shirwadkar 			    || (handle != NULL));
836ac27a0ecSDave Kleikamp 
837ac27a0ecSDave Kleikamp 		/*
838ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
839ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
840ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
841617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
842ac27a0ecSDave Kleikamp 		 * problem.
843ac27a0ecSDave Kleikamp 		 */
844ac27a0ecSDave Kleikamp 		lock_buffer(bh);
845ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
846188c299eSJan Kara 		err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
847188c299eSJan Kara 						     EXT4_JTR_NONE);
84810560082STheodore Ts'o 		if (unlikely(err)) {
84910560082STheodore Ts'o 			unlock_buffer(bh);
85010560082STheodore Ts'o 			goto errout;
85110560082STheodore Ts'o 		}
85210560082STheodore Ts'o 		if (!buffer_uptodate(bh)) {
853ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
854ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
855ac27a0ecSDave Kleikamp 		}
856ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
8570390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
8580390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
85910560082STheodore Ts'o 		if (unlikely(err))
86010560082STheodore Ts'o 			goto errout;
86110560082STheodore Ts'o 	} else
862ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
863ac27a0ecSDave Kleikamp 	return bh;
86410560082STheodore Ts'o errout:
86510560082STheodore Ts'o 	brelse(bh);
86610560082STheodore Ts'o 	return ERR_PTR(err);
867ac27a0ecSDave Kleikamp }
868ac27a0ecSDave Kleikamp 
869617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
870c5e298aeSTheodore Ts'o 			       ext4_lblk_t block, int map_flags)
871ac27a0ecSDave Kleikamp {
872ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
8732d069c08Szhangyi (F) 	int ret;
874ac27a0ecSDave Kleikamp 
875c5e298aeSTheodore Ts'o 	bh = ext4_getblk(handle, inode, block, map_flags);
8761c215028STheodore Ts'o 	if (IS_ERR(bh))
877ac27a0ecSDave Kleikamp 		return bh;
8787963e5acSZhangXiaoxu 	if (!bh || ext4_buffer_uptodate(bh))
879ac27a0ecSDave Kleikamp 		return bh;
8802d069c08Szhangyi (F) 
8812d069c08Szhangyi (F) 	ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
8822d069c08Szhangyi (F) 	if (ret) {
883ac27a0ecSDave Kleikamp 		put_bh(bh);
8842d069c08Szhangyi (F) 		return ERR_PTR(ret);
8852d069c08Szhangyi (F) 	}
8862d069c08Szhangyi (F) 	return bh;
887ac27a0ecSDave Kleikamp }
888ac27a0ecSDave Kleikamp 
8899699d4f9STahsin Erdogan /* Read a contiguous batch of blocks. */
8909699d4f9STahsin Erdogan int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
8919699d4f9STahsin Erdogan 		     bool wait, struct buffer_head **bhs)
8929699d4f9STahsin Erdogan {
8939699d4f9STahsin Erdogan 	int i, err;
8949699d4f9STahsin Erdogan 
8959699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
8969699d4f9STahsin Erdogan 		bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
8979699d4f9STahsin Erdogan 		if (IS_ERR(bhs[i])) {
8989699d4f9STahsin Erdogan 			err = PTR_ERR(bhs[i]);
8999699d4f9STahsin Erdogan 			bh_count = i;
9009699d4f9STahsin Erdogan 			goto out_brelse;
9019699d4f9STahsin Erdogan 		}
9029699d4f9STahsin Erdogan 	}
9039699d4f9STahsin Erdogan 
9049699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9059699d4f9STahsin Erdogan 		/* Note that NULL bhs[i] is valid because of holes. */
9062d069c08Szhangyi (F) 		if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
9072d069c08Szhangyi (F) 			ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
9089699d4f9STahsin Erdogan 
9099699d4f9STahsin Erdogan 	if (!wait)
9109699d4f9STahsin Erdogan 		return 0;
9119699d4f9STahsin Erdogan 
9129699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9139699d4f9STahsin Erdogan 		if (bhs[i])
9149699d4f9STahsin Erdogan 			wait_on_buffer(bhs[i]);
9159699d4f9STahsin Erdogan 
9169699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9179699d4f9STahsin Erdogan 		if (bhs[i] && !buffer_uptodate(bhs[i])) {
9189699d4f9STahsin Erdogan 			err = -EIO;
9199699d4f9STahsin Erdogan 			goto out_brelse;
9209699d4f9STahsin Erdogan 		}
9219699d4f9STahsin Erdogan 	}
9229699d4f9STahsin Erdogan 	return 0;
9239699d4f9STahsin Erdogan 
9249699d4f9STahsin Erdogan out_brelse:
9259699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9269699d4f9STahsin Erdogan 		brelse(bhs[i]);
9279699d4f9STahsin Erdogan 		bhs[i] = NULL;
9289699d4f9STahsin Erdogan 	}
9299699d4f9STahsin Erdogan 	return err;
9309699d4f9STahsin Erdogan }
9319699d4f9STahsin Erdogan 
932188c299eSJan Kara int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
933ac27a0ecSDave Kleikamp 			   struct buffer_head *head,
934ac27a0ecSDave Kleikamp 			   unsigned from,
935ac27a0ecSDave Kleikamp 			   unsigned to,
936ac27a0ecSDave Kleikamp 			   int *partial,
937188c299eSJan Kara 			   int (*fn)(handle_t *handle, struct inode *inode,
938ac27a0ecSDave Kleikamp 				     struct buffer_head *bh))
939ac27a0ecSDave Kleikamp {
940ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
941ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
942ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
943ac27a0ecSDave Kleikamp 	int err, ret = 0;
944ac27a0ecSDave Kleikamp 	struct buffer_head *next;
945ac27a0ecSDave Kleikamp 
946ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
947ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
948de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
949ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
950ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
951ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
952ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
953ac27a0ecSDave Kleikamp 				*partial = 1;
954ac27a0ecSDave Kleikamp 			continue;
955ac27a0ecSDave Kleikamp 		}
956188c299eSJan Kara 		err = (*fn)(handle, inode, bh);
957ac27a0ecSDave Kleikamp 		if (!ret)
958ac27a0ecSDave Kleikamp 			ret = err;
959ac27a0ecSDave Kleikamp 	}
960ac27a0ecSDave Kleikamp 	return ret;
961ac27a0ecSDave Kleikamp }
962ac27a0ecSDave Kleikamp 
963d84c9ebdSJan Kara /*
964d84c9ebdSJan Kara  * Helper for handling dirtying of journalled data. We also mark the folio as
965d84c9ebdSJan Kara  * dirty so that writeback code knows about this page (and inode) contains
966d84c9ebdSJan Kara  * dirty data. ext4_writepages() then commits appropriate transaction to
967d84c9ebdSJan Kara  * make data stable.
968d84c9ebdSJan Kara  */
969d84c9ebdSJan Kara static int ext4_dirty_journalled_data(handle_t *handle, struct buffer_head *bh)
970d84c9ebdSJan Kara {
971d84c9ebdSJan Kara 	folio_mark_dirty(bh->b_folio);
972d84c9ebdSJan Kara 	return ext4_handle_dirty_metadata(handle, NULL, bh);
973d84c9ebdSJan Kara }
974d84c9ebdSJan Kara 
975188c299eSJan Kara int do_journal_get_write_access(handle_t *handle, struct inode *inode,
976ac27a0ecSDave Kleikamp 				struct buffer_head *bh)
977ac27a0ecSDave Kleikamp {
97856d35a4cSJan Kara 	int dirty = buffer_dirty(bh);
97956d35a4cSJan Kara 	int ret;
98056d35a4cSJan Kara 
981ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
982ac27a0ecSDave Kleikamp 		return 0;
98356d35a4cSJan Kara 	/*
984ebdec241SChristoph Hellwig 	 * __block_write_begin() could have dirtied some buffers. Clean
98556d35a4cSJan Kara 	 * the dirty bit as jbd2_journal_get_write_access() could complain
98656d35a4cSJan Kara 	 * otherwise about fs integrity issues. Setting of the dirty bit
987ebdec241SChristoph Hellwig 	 * by __block_write_begin() isn't a real problem here as we clear
98856d35a4cSJan Kara 	 * the bit before releasing a page lock and thus writeback cannot
98956d35a4cSJan Kara 	 * ever write the buffer.
99056d35a4cSJan Kara 	 */
99156d35a4cSJan Kara 	if (dirty)
99256d35a4cSJan Kara 		clear_buffer_dirty(bh);
9935d601255Sliang xie 	BUFFER_TRACE(bh, "get write access");
994188c299eSJan Kara 	ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
995188c299eSJan Kara 					    EXT4_JTR_NONE);
99656d35a4cSJan Kara 	if (!ret && dirty)
997d84c9ebdSJan Kara 		ret = ext4_dirty_journalled_data(handle, bh);
99856d35a4cSJan Kara 	return ret;
999ac27a0ecSDave Kleikamp }
1000ac27a0ecSDave Kleikamp 
1001643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
100286b38c27SMatthew Wilcox static int ext4_block_write_begin(struct folio *folio, loff_t pos, unsigned len,
10032058f83aSMichael Halcrow 				  get_block_t *get_block)
10042058f83aSMichael Halcrow {
100509cbfeafSKirill A. Shutemov 	unsigned from = pos & (PAGE_SIZE - 1);
10062058f83aSMichael Halcrow 	unsigned to = from + len;
100786b38c27SMatthew Wilcox 	struct inode *inode = folio->mapping->host;
10082058f83aSMichael Halcrow 	unsigned block_start, block_end;
10092058f83aSMichael Halcrow 	sector_t block;
10102058f83aSMichael Halcrow 	int err = 0;
10112058f83aSMichael Halcrow 	unsigned blocksize = inode->i_sb->s_blocksize;
10122058f83aSMichael Halcrow 	unsigned bbits;
10130b578f35SChandan Rajendra 	struct buffer_head *bh, *head, *wait[2];
10140b578f35SChandan Rajendra 	int nr_wait = 0;
10150b578f35SChandan Rajendra 	int i;
10162058f83aSMichael Halcrow 
101786b38c27SMatthew Wilcox 	BUG_ON(!folio_test_locked(folio));
101809cbfeafSKirill A. Shutemov 	BUG_ON(from > PAGE_SIZE);
101909cbfeafSKirill A. Shutemov 	BUG_ON(to > PAGE_SIZE);
10202058f83aSMichael Halcrow 	BUG_ON(from > to);
10212058f83aSMichael Halcrow 
102286b38c27SMatthew Wilcox 	head = folio_buffers(folio);
102386b38c27SMatthew Wilcox 	if (!head) {
102486b38c27SMatthew Wilcox 		create_empty_buffers(&folio->page, blocksize, 0);
102586b38c27SMatthew Wilcox 		head = folio_buffers(folio);
102686b38c27SMatthew Wilcox 	}
10272058f83aSMichael Halcrow 	bbits = ilog2(blocksize);
102886b38c27SMatthew Wilcox 	block = (sector_t)folio->index << (PAGE_SHIFT - bbits);
10292058f83aSMichael Halcrow 
10302058f83aSMichael Halcrow 	for (bh = head, block_start = 0; bh != head || !block_start;
10312058f83aSMichael Halcrow 	    block++, block_start = block_end, bh = bh->b_this_page) {
10322058f83aSMichael Halcrow 		block_end = block_start + blocksize;
10332058f83aSMichael Halcrow 		if (block_end <= from || block_start >= to) {
103486b38c27SMatthew Wilcox 			if (folio_test_uptodate(folio)) {
10352058f83aSMichael Halcrow 				set_buffer_uptodate(bh);
10362058f83aSMichael Halcrow 			}
10372058f83aSMichael Halcrow 			continue;
10382058f83aSMichael Halcrow 		}
10392058f83aSMichael Halcrow 		if (buffer_new(bh))
10402058f83aSMichael Halcrow 			clear_buffer_new(bh);
10412058f83aSMichael Halcrow 		if (!buffer_mapped(bh)) {
10422058f83aSMichael Halcrow 			WARN_ON(bh->b_size != blocksize);
10432058f83aSMichael Halcrow 			err = get_block(inode, block, bh, 1);
10442058f83aSMichael Halcrow 			if (err)
10452058f83aSMichael Halcrow 				break;
10462058f83aSMichael Halcrow 			if (buffer_new(bh)) {
104786b38c27SMatthew Wilcox 				if (folio_test_uptodate(folio)) {
10482058f83aSMichael Halcrow 					clear_buffer_new(bh);
10492058f83aSMichael Halcrow 					set_buffer_uptodate(bh);
10502058f83aSMichael Halcrow 					mark_buffer_dirty(bh);
10512058f83aSMichael Halcrow 					continue;
10522058f83aSMichael Halcrow 				}
10532058f83aSMichael Halcrow 				if (block_end > to || block_start < from)
105486b38c27SMatthew Wilcox 					folio_zero_segments(folio, to,
105586b38c27SMatthew Wilcox 							    block_end,
10562058f83aSMichael Halcrow 							    block_start, from);
10572058f83aSMichael Halcrow 				continue;
10582058f83aSMichael Halcrow 			}
10592058f83aSMichael Halcrow 		}
106086b38c27SMatthew Wilcox 		if (folio_test_uptodate(folio)) {
10612058f83aSMichael Halcrow 			set_buffer_uptodate(bh);
10622058f83aSMichael Halcrow 			continue;
10632058f83aSMichael Halcrow 		}
10642058f83aSMichael Halcrow 		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
10652058f83aSMichael Halcrow 		    !buffer_unwritten(bh) &&
10662058f83aSMichael Halcrow 		    (block_start < from || block_end > to)) {
10672d069c08Szhangyi (F) 			ext4_read_bh_lock(bh, 0, false);
10680b578f35SChandan Rajendra 			wait[nr_wait++] = bh;
10692058f83aSMichael Halcrow 		}
10702058f83aSMichael Halcrow 	}
10712058f83aSMichael Halcrow 	/*
10722058f83aSMichael Halcrow 	 * If we issued read requests, let them complete.
10732058f83aSMichael Halcrow 	 */
10740b578f35SChandan Rajendra 	for (i = 0; i < nr_wait; i++) {
10750b578f35SChandan Rajendra 		wait_on_buffer(wait[i]);
10760b578f35SChandan Rajendra 		if (!buffer_uptodate(wait[i]))
10772058f83aSMichael Halcrow 			err = -EIO;
10782058f83aSMichael Halcrow 	}
10797e0785fcSChandan Rajendra 	if (unlikely(err)) {
10804a9622f2SMatthew Wilcox (Oracle) 		folio_zero_new_buffers(folio, from, to);
10814f74d15fSEric Biggers 	} else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
10820b578f35SChandan Rajendra 		for (i = 0; i < nr_wait; i++) {
10830b578f35SChandan Rajendra 			int err2;
10840b578f35SChandan Rajendra 
108586b38c27SMatthew Wilcox 			err2 = fscrypt_decrypt_pagecache_blocks(folio,
108686b38c27SMatthew Wilcox 						blocksize, bh_offset(wait[i]));
10870b578f35SChandan Rajendra 			if (err2) {
10880b578f35SChandan Rajendra 				clear_buffer_uptodate(wait[i]);
10890b578f35SChandan Rajendra 				err = err2;
10900b578f35SChandan Rajendra 			}
10910b578f35SChandan Rajendra 		}
10927e0785fcSChandan Rajendra 	}
10937e0785fcSChandan Rajendra 
10942058f83aSMichael Halcrow 	return err;
10952058f83aSMichael Halcrow }
10962058f83aSMichael Halcrow #endif
10972058f83aSMichael Halcrow 
10989462f770SJan Kara /*
10999462f770SJan Kara  * To preserve ordering, it is essential that the hole instantiation and
11009462f770SJan Kara  * the data write be encapsulated in a single transaction.  We cannot
11019462f770SJan Kara  * close off a transaction and start a new one between the ext4_get_block()
11029462f770SJan Kara  * and the ext4_write_end().  So doing the jbd2_journal_start at the start of
11039462f770SJan Kara  * ext4_write_begin() is the right place.
11049462f770SJan Kara  */
1105bfc1af65SNick Piggin static int ext4_write_begin(struct file *file, struct address_space *mapping,
11069d6b0cd7SMatthew Wilcox (Oracle) 			    loff_t pos, unsigned len,
1107bfc1af65SNick Piggin 			    struct page **pagep, void **fsdata)
1108ac27a0ecSDave Kleikamp {
1109bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
11101938a150SAneesh Kumar K.V 	int ret, needed_blocks;
1111ac27a0ecSDave Kleikamp 	handle_t *handle;
1112ac27a0ecSDave Kleikamp 	int retries = 0;
11134d934a5eSMatthew Wilcox 	struct folio *folio;
1114bfc1af65SNick Piggin 	pgoff_t index;
1115bfc1af65SNick Piggin 	unsigned from, to;
1116bfc1af65SNick Piggin 
1117eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
11180db1ff22STheodore Ts'o 		return -EIO;
11190db1ff22STheodore Ts'o 
11209d6b0cd7SMatthew Wilcox (Oracle) 	trace_ext4_write_begin(inode, pos, len);
11211938a150SAneesh Kumar K.V 	/*
11221938a150SAneesh Kumar K.V 	 * Reserve one block more for addition to orphan list in case
11231938a150SAneesh Kumar K.V 	 * we allocate blocks but write fails for some reason
11241938a150SAneesh Kumar K.V 	 */
11251938a150SAneesh Kumar K.V 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
112609cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
112709cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1128bfc1af65SNick Piggin 	to = from + len;
1129ac27a0ecSDave Kleikamp 
1130f19d5870STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1131f19d5870STao Ma 		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1132832ee62dSMatthew Wilcox (Oracle) 						    pagep);
1133f19d5870STao Ma 		if (ret < 0)
113447564bfbSTheodore Ts'o 			return ret;
113547564bfbSTheodore Ts'o 		if (ret == 1)
113647564bfbSTheodore Ts'o 			return 0;
1137f19d5870STao Ma 	}
1138f19d5870STao Ma 
113947564bfbSTheodore Ts'o 	/*
11404d934a5eSMatthew Wilcox 	 * __filemap_get_folio() can take a long time if the
11414d934a5eSMatthew Wilcox 	 * system is thrashing due to memory pressure, or if the folio
114247564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
114347564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
11444d934a5eSMatthew Wilcox 	 * the folio (if needed) without using GFP_NOFS.
114547564bfbSTheodore Ts'o 	 */
114647564bfbSTheodore Ts'o retry_grab:
11474d934a5eSMatthew Wilcox 	folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
11484d934a5eSMatthew Wilcox 					mapping_gfp_mask(mapping));
11497fa8a8eeSLinus Torvalds 	if (IS_ERR(folio))
11507fa8a8eeSLinus Torvalds 		return PTR_ERR(folio);
1151d1052d23SJinke Han 	/*
1152d1052d23SJinke Han 	 * The same as page allocation, we prealloc buffer heads before
1153d1052d23SJinke Han 	 * starting the handle.
1154d1052d23SJinke Han 	 */
11554d934a5eSMatthew Wilcox 	if (!folio_buffers(folio))
11564d934a5eSMatthew Wilcox 		create_empty_buffers(&folio->page, inode->i_sb->s_blocksize, 0);
1157d1052d23SJinke Han 
11584d934a5eSMatthew Wilcox 	folio_unlock(folio);
115947564bfbSTheodore Ts'o 
116047564bfbSTheodore Ts'o retry_journal:
11619924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
11627479d2b9SAndrew Morton 	if (IS_ERR(handle)) {
11634d934a5eSMatthew Wilcox 		folio_put(folio);
116447564bfbSTheodore Ts'o 		return PTR_ERR(handle);
1165cf108bcaSJan Kara 	}
1166f19d5870STao Ma 
11674d934a5eSMatthew Wilcox 	folio_lock(folio);
11684d934a5eSMatthew Wilcox 	if (folio->mapping != mapping) {
11694d934a5eSMatthew Wilcox 		/* The folio got truncated from under us */
11704d934a5eSMatthew Wilcox 		folio_unlock(folio);
11714d934a5eSMatthew Wilcox 		folio_put(folio);
1172cf108bcaSJan Kara 		ext4_journal_stop(handle);
117347564bfbSTheodore Ts'o 		goto retry_grab;
1174cf108bcaSJan Kara 	}
11754d934a5eSMatthew Wilcox 	/* In case writeback began while the folio was unlocked */
11764d934a5eSMatthew Wilcox 	folio_wait_stable(folio);
1177cf108bcaSJan Kara 
1178643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
11792058f83aSMichael Halcrow 	if (ext4_should_dioread_nolock(inode))
118086b38c27SMatthew Wilcox 		ret = ext4_block_write_begin(folio, pos, len,
1181705965bdSJan Kara 					     ext4_get_block_unwritten);
11822058f83aSMichael Halcrow 	else
118386b38c27SMatthew Wilcox 		ret = ext4_block_write_begin(folio, pos, len, ext4_get_block);
11842058f83aSMichael Halcrow #else
1185744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
11864d934a5eSMatthew Wilcox 		ret = __block_write_begin(&folio->page, pos, len,
1187705965bdSJan Kara 					  ext4_get_block_unwritten);
1188744692dcSJiaying Zhang 	else
11894d934a5eSMatthew Wilcox 		ret = __block_write_begin(&folio->page, pos, len, ext4_get_block);
11902058f83aSMichael Halcrow #endif
1191bfc1af65SNick Piggin 	if (!ret && ext4_should_journal_data(inode)) {
1192188c299eSJan Kara 		ret = ext4_walk_page_buffers(handle, inode,
11934d934a5eSMatthew Wilcox 					     folio_buffers(folio), from, to,
11944d934a5eSMatthew Wilcox 					     NULL, do_journal_get_write_access);
1195b46be050SAndrey Savochkin 	}
1196bfc1af65SNick Piggin 
1197bfc1af65SNick Piggin 	if (ret) {
1198c93d8f88SEric Biggers 		bool extended = (pos + len > inode->i_size) &&
1199c93d8f88SEric Biggers 				!ext4_verity_in_progress(inode);
1200c93d8f88SEric Biggers 
12014d934a5eSMatthew Wilcox 		folio_unlock(folio);
1202ae4d5372SAneesh Kumar K.V 		/*
12036e1db88dSChristoph Hellwig 		 * __block_write_begin may have instantiated a few blocks
1204ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
1205f340b3d9Shongnanli 		 * i_size_read because we hold i_rwsem.
12061938a150SAneesh Kumar K.V 		 *
12071938a150SAneesh Kumar K.V 		 * Add inode to orphan list in case we crash before
12081938a150SAneesh Kumar K.V 		 * truncate finishes
1209ae4d5372SAneesh Kumar K.V 		 */
1210c93d8f88SEric Biggers 		if (extended && ext4_can_truncate(inode))
12111938a150SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
12121938a150SAneesh Kumar K.V 
12131938a150SAneesh Kumar K.V 		ext4_journal_stop(handle);
1214c93d8f88SEric Biggers 		if (extended) {
1215b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
12161938a150SAneesh Kumar K.V 			/*
1217ffacfa7aSJan Kara 			 * If truncate failed early the inode might
12181938a150SAneesh Kumar K.V 			 * still be on the orphan list; we need to
12191938a150SAneesh Kumar K.V 			 * make sure the inode is removed from the
12201938a150SAneesh Kumar K.V 			 * orphan list in that case.
12211938a150SAneesh Kumar K.V 			 */
12221938a150SAneesh Kumar K.V 			if (inode->i_nlink)
12231938a150SAneesh Kumar K.V 				ext4_orphan_del(NULL, inode);
12241938a150SAneesh Kumar K.V 		}
1225bfc1af65SNick Piggin 
122647564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
122747564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
122847564bfbSTheodore Ts'o 			goto retry_journal;
12294d934a5eSMatthew Wilcox 		folio_put(folio);
123047564bfbSTheodore Ts'o 		return ret;
123147564bfbSTheodore Ts'o 	}
12324d934a5eSMatthew Wilcox 	*pagep = &folio->page;
1233ac27a0ecSDave Kleikamp 	return ret;
1234ac27a0ecSDave Kleikamp }
1235ac27a0ecSDave Kleikamp 
1236bfc1af65SNick Piggin /* For write_end() in data=journal mode */
1237188c299eSJan Kara static int write_end_fn(handle_t *handle, struct inode *inode,
1238188c299eSJan Kara 			struct buffer_head *bh)
1239ac27a0ecSDave Kleikamp {
124013fca323STheodore Ts'o 	int ret;
1241ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1242ac27a0ecSDave Kleikamp 		return 0;
1243ac27a0ecSDave Kleikamp 	set_buffer_uptodate(bh);
1244d84c9ebdSJan Kara 	ret = ext4_dirty_journalled_data(handle, bh);
124513fca323STheodore Ts'o 	clear_buffer_meta(bh);
124613fca323STheodore Ts'o 	clear_buffer_prio(bh);
124713fca323STheodore Ts'o 	return ret;
1248ac27a0ecSDave Kleikamp }
1249ac27a0ecSDave Kleikamp 
1250eed4333fSZheng Liu /*
1251eed4333fSZheng Liu  * We need to pick up the new inode size which generic_commit_write gave us
1252eed4333fSZheng Liu  * `file' can be NULL - eg, when called from page_symlink().
1253eed4333fSZheng Liu  *
1254eed4333fSZheng Liu  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1255eed4333fSZheng Liu  * buffers are managed internally.
1256eed4333fSZheng Liu  */
1257eed4333fSZheng Liu static int ext4_write_end(struct file *file,
1258f8514083SAneesh Kumar K.V 			  struct address_space *mapping,
1259f8514083SAneesh Kumar K.V 			  loff_t pos, unsigned len, unsigned copied,
1260f8514083SAneesh Kumar K.V 			  struct page *page, void *fsdata)
1261f8514083SAneesh Kumar K.V {
126264fb3136SMatthew Wilcox 	struct folio *folio = page_folio(page);
1263f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
1264eed4333fSZheng Liu 	struct inode *inode = mapping->host;
12650572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1266eed4333fSZheng Liu 	int ret = 0, ret2;
1267eed4333fSZheng Liu 	int i_size_changed = 0;
1268c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1269eed4333fSZheng Liu 
1270eed4333fSZheng Liu 	trace_ext4_write_end(inode, pos, len, copied);
12716984aef5SZhang Yi 
12725c099c4fSYe Bin 	if (ext4_has_inline_data(inode) &&
12735c099c4fSYe Bin 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
1274d19500daSRitesh Harjani 		return ext4_write_inline_data_end(inode, pos, len, copied,
1275d19500daSRitesh Harjani 						  folio);
12766984aef5SZhang Yi 
12776984aef5SZhang Yi 	copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1278f8514083SAneesh Kumar K.V 	/*
127964fb3136SMatthew Wilcox 	 * it's important to update i_size while still holding folio lock:
1280f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
1281c93d8f88SEric Biggers 	 *
1282c93d8f88SEric Biggers 	 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1283c93d8f88SEric Biggers 	 * blocks are being written past EOF, so skip the i_size update.
1284f8514083SAneesh Kumar K.V 	 */
1285c93d8f88SEric Biggers 	if (!verity)
12864631dbf6SDmitry Monakhov 		i_size_changed = ext4_update_inode_size(inode, pos + copied);
128764fb3136SMatthew Wilcox 	folio_unlock(folio);
128864fb3136SMatthew Wilcox 	folio_put(folio);
1289f8514083SAneesh Kumar K.V 
1290c93d8f88SEric Biggers 	if (old_size < pos && !verity)
12910572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
1292f8514083SAneesh Kumar K.V 	/*
129364fb3136SMatthew Wilcox 	 * Don't mark the inode dirty under folio lock. First, it unnecessarily
129464fb3136SMatthew Wilcox 	 * makes the holding time of folio lock longer. Second, it forces lock
129564fb3136SMatthew Wilcox 	 * ordering of folio lock and transaction start for journaling
1296f8514083SAneesh Kumar K.V 	 * filesystems.
1297f8514083SAneesh Kumar K.V 	 */
12986984aef5SZhang Yi 	if (i_size_changed)
12994209ae12SHarshad Shirwadkar 		ret = ext4_mark_inode_dirty(handle, inode);
1300f8514083SAneesh Kumar K.V 
1301c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1302f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1303f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1304f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1305f8514083SAneesh Kumar K.V 		 */
1306f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
130755ce2f64SZhang Yi 
1308617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1309ac27a0ecSDave Kleikamp 	if (!ret)
1310ac27a0ecSDave Kleikamp 		ret = ret2;
1311bfc1af65SNick Piggin 
1312c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1313b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1314f8514083SAneesh Kumar K.V 		/*
1315ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1316f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1317f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1318f8514083SAneesh Kumar K.V 		 */
1319f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1320f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1321f8514083SAneesh Kumar K.V 	}
1322f8514083SAneesh Kumar K.V 
1323bfc1af65SNick Piggin 	return ret ? ret : copied;
1324ac27a0ecSDave Kleikamp }
1325ac27a0ecSDave Kleikamp 
1326b90197b6STheodore Ts'o /*
13274a9622f2SMatthew Wilcox (Oracle)  * This is a private version of folio_zero_new_buffers() which doesn't
1328b90197b6STheodore Ts'o  * set the buffer to be dirty, since in data=journalled mode we need
1329d84c9ebdSJan Kara  * to call ext4_dirty_journalled_data() instead.
1330b90197b6STheodore Ts'o  */
13313b136499SJan Kara static void ext4_journalled_zero_new_buffers(handle_t *handle,
1332188c299eSJan Kara 					    struct inode *inode,
133386324a21SMatthew Wilcox 					    struct folio *folio,
13343b136499SJan Kara 					    unsigned from, unsigned to)
1335b90197b6STheodore Ts'o {
1336b90197b6STheodore Ts'o 	unsigned int block_start = 0, block_end;
1337b90197b6STheodore Ts'o 	struct buffer_head *head, *bh;
1338b90197b6STheodore Ts'o 
133986324a21SMatthew Wilcox 	bh = head = folio_buffers(folio);
1340b90197b6STheodore Ts'o 	do {
1341b90197b6STheodore Ts'o 		block_end = block_start + bh->b_size;
1342b90197b6STheodore Ts'o 		if (buffer_new(bh)) {
1343b90197b6STheodore Ts'o 			if (block_end > from && block_start < to) {
134486324a21SMatthew Wilcox 				if (!folio_test_uptodate(folio)) {
1345b90197b6STheodore Ts'o 					unsigned start, size;
1346b90197b6STheodore Ts'o 
1347b90197b6STheodore Ts'o 					start = max(from, block_start);
1348b90197b6STheodore Ts'o 					size = min(to, block_end) - start;
1349b90197b6STheodore Ts'o 
135086324a21SMatthew Wilcox 					folio_zero_range(folio, start, size);
1351188c299eSJan Kara 					write_end_fn(handle, inode, bh);
1352b90197b6STheodore Ts'o 				}
1353b90197b6STheodore Ts'o 				clear_buffer_new(bh);
1354b90197b6STheodore Ts'o 			}
1355b90197b6STheodore Ts'o 		}
1356b90197b6STheodore Ts'o 		block_start = block_end;
1357b90197b6STheodore Ts'o 		bh = bh->b_this_page;
1358b90197b6STheodore Ts'o 	} while (bh != head);
1359b90197b6STheodore Ts'o }
1360b90197b6STheodore Ts'o 
1361bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
1362bfc1af65SNick Piggin 				     struct address_space *mapping,
1363bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
1364bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
1365ac27a0ecSDave Kleikamp {
1366feb22b77SMatthew Wilcox 	struct folio *folio = page_folio(page);
1367617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1368bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
13690572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1370ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1371ac27a0ecSDave Kleikamp 	int partial = 0;
1372bfc1af65SNick Piggin 	unsigned from, to;
13734631dbf6SDmitry Monakhov 	int size_changed = 0;
1374c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1375ac27a0ecSDave Kleikamp 
13769bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
137709cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1378bfc1af65SNick Piggin 	to = from + len;
1379bfc1af65SNick Piggin 
1380441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1381441c8508SCurt Wohlgemuth 
13826984aef5SZhang Yi 	if (ext4_has_inline_data(inode))
1383d19500daSRitesh Harjani 		return ext4_write_inline_data_end(inode, pos, len, copied,
1384d19500daSRitesh Harjani 						  folio);
13856984aef5SZhang Yi 
1386feb22b77SMatthew Wilcox 	if (unlikely(copied < len) && !folio_test_uptodate(folio)) {
1387bfc1af65SNick Piggin 		copied = 0;
138886324a21SMatthew Wilcox 		ext4_journalled_zero_new_buffers(handle, inode, folio,
138986324a21SMatthew Wilcox 						 from, to);
13903b136499SJan Kara 	} else {
13913b136499SJan Kara 		if (unlikely(copied < len))
139286324a21SMatthew Wilcox 			ext4_journalled_zero_new_buffers(handle, inode, folio,
13933b136499SJan Kara 							 from + copied, to);
1394feb22b77SMatthew Wilcox 		ret = ext4_walk_page_buffers(handle, inode,
1395feb22b77SMatthew Wilcox 					     folio_buffers(folio),
1396188c299eSJan Kara 					     from, from + copied, &partial,
13973b136499SJan Kara 					     write_end_fn);
1398ac27a0ecSDave Kleikamp 		if (!partial)
1399feb22b77SMatthew Wilcox 			folio_mark_uptodate(folio);
14003fdcfb66STao Ma 	}
1401c93d8f88SEric Biggers 	if (!verity)
14024631dbf6SDmitry Monakhov 		size_changed = ext4_update_inode_size(inode, pos + copied);
14032d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1404feb22b77SMatthew Wilcox 	folio_unlock(folio);
1405feb22b77SMatthew Wilcox 	folio_put(folio);
14064631dbf6SDmitry Monakhov 
1407c93d8f88SEric Biggers 	if (old_size < pos && !verity)
14080572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
14090572639fSXiaoguang Wang 
14106984aef5SZhang Yi 	if (size_changed) {
1411617ba13bSMingming Cao 		ret2 = ext4_mark_inode_dirty(handle, inode);
1412ac27a0ecSDave Kleikamp 		if (!ret)
1413ac27a0ecSDave Kleikamp 			ret = ret2;
1414ac27a0ecSDave Kleikamp 	}
1415bfc1af65SNick Piggin 
1416c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1417f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1418f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1419f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1420f8514083SAneesh Kumar K.V 		 */
1421f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1422f8514083SAneesh Kumar K.V 
1423617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1424ac27a0ecSDave Kleikamp 	if (!ret)
1425ac27a0ecSDave Kleikamp 		ret = ret2;
1426c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1427b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1428f8514083SAneesh Kumar K.V 		/*
1429ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1430f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1431f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1432f8514083SAneesh Kumar K.V 		 */
1433f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1434f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1435f8514083SAneesh Kumar K.V 	}
1436bfc1af65SNick Piggin 
1437bfc1af65SNick Piggin 	return ret ? ret : copied;
1438ac27a0ecSDave Kleikamp }
1439d2a17637SMingming Cao 
14409d0be502STheodore Ts'o /*
1441c27e43a1SEric Whitney  * Reserve space for a single cluster
14429d0be502STheodore Ts'o  */
1443c27e43a1SEric Whitney static int ext4_da_reserve_space(struct inode *inode)
1444d2a17637SMingming Cao {
1445d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
14460637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
14475dd4056dSChristoph Hellwig 	int ret;
1448d2a17637SMingming Cao 
144960e58e0fSMingming Cao 	/*
145072b8ab9dSEric Sandeen 	 * We will charge metadata quota at writeout time; this saves
145172b8ab9dSEric Sandeen 	 * us from metadata over-estimation, though we may go over by
145272b8ab9dSEric Sandeen 	 * a small amount in the end.  Here we just reserve for data.
145360e58e0fSMingming Cao 	 */
14547b415bf6SAditya Kali 	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
14555dd4056dSChristoph Hellwig 	if (ret)
14565dd4056dSChristoph Hellwig 		return ret;
145703179fe9STheodore Ts'o 
145803179fe9STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
145971d4f7d0STheodore Ts'o 	if (ext4_claim_free_clusters(sbi, 1, 0)) {
146003179fe9STheodore Ts'o 		spin_unlock(&ei->i_block_reservation_lock);
146103179fe9STheodore Ts'o 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1462d2a17637SMingming Cao 		return -ENOSPC;
1463d2a17637SMingming Cao 	}
14649d0be502STheodore Ts'o 	ei->i_reserved_data_blocks++;
1465c27e43a1SEric Whitney 	trace_ext4_da_reserve_space(inode);
14660637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
146739bc680aSDmitry Monakhov 
1468d2a17637SMingming Cao 	return 0;       /* success */
1469d2a17637SMingming Cao }
1470d2a17637SMingming Cao 
1471f456767dSEric Whitney void ext4_da_release_space(struct inode *inode, int to_free)
1472d2a17637SMingming Cao {
1473d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
14740637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1475d2a17637SMingming Cao 
1476cd213226SMingming Cao 	if (!to_free)
1477cd213226SMingming Cao 		return;		/* Nothing to release, exit */
1478cd213226SMingming Cao 
1479d2a17637SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1480cd213226SMingming Cao 
14815a58ec87SLi Zefan 	trace_ext4_da_release_space(inode, to_free);
14820637c6f4STheodore Ts'o 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1483cd213226SMingming Cao 		/*
14840637c6f4STheodore Ts'o 		 * if there aren't enough reserved blocks, then the
14850637c6f4STheodore Ts'o 		 * counter is messed up somewhere.  Since this
14860637c6f4STheodore Ts'o 		 * function is called from invalidate page, it's
14870637c6f4STheodore Ts'o 		 * harmless to return without any action.
1488cd213226SMingming Cao 		 */
14898de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "ext4_da_release_space: "
14900637c6f4STheodore Ts'o 			 "ino %lu, to_free %d with only %d reserved "
14911084f252STheodore Ts'o 			 "data blocks", inode->i_ino, to_free,
14920637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
14930637c6f4STheodore Ts'o 		WARN_ON(1);
14940637c6f4STheodore Ts'o 		to_free = ei->i_reserved_data_blocks;
14950637c6f4STheodore Ts'o 	}
14960637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= to_free;
14970637c6f4STheodore Ts'o 
149872b8ab9dSEric Sandeen 	/* update fs dirty data blocks counter */
149957042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1500d2a17637SMingming Cao 
1501d2a17637SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
150260e58e0fSMingming Cao 
15037b415bf6SAditya Kali 	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1504d2a17637SMingming Cao }
1505d2a17637SMingming Cao 
1506ac27a0ecSDave Kleikamp /*
150764769240SAlex Tomas  * Delayed allocation stuff
150864769240SAlex Tomas  */
150964769240SAlex Tomas 
15104e7ea81dSJan Kara struct mpage_da_data {
151115648d59SJan Kara 	/* These are input fields for ext4_do_writepages() */
15124e7ea81dSJan Kara 	struct inode *inode;
15134e7ea81dSJan Kara 	struct writeback_control *wbc;
151415648d59SJan Kara 	unsigned int can_map:1;	/* Can writepages call map blocks? */
15156b523df4SJan Kara 
151615648d59SJan Kara 	/* These are internal state of ext4_do_writepages() */
15174e7ea81dSJan Kara 	pgoff_t first_page;	/* The first page to write */
15184e7ea81dSJan Kara 	pgoff_t next_page;	/* Current page to examine */
15194e7ea81dSJan Kara 	pgoff_t last_page;	/* Last page to examine */
152064769240SAlex Tomas 	/*
15214e7ea81dSJan Kara 	 * Extent to map - this can be after first_page because that can be
15224e7ea81dSJan Kara 	 * fully mapped. We somewhat abuse m_flags to store whether the extent
15234e7ea81dSJan Kara 	 * is delalloc or unwritten.
152464769240SAlex Tomas 	 */
15254e7ea81dSJan Kara 	struct ext4_map_blocks map;
15264e7ea81dSJan Kara 	struct ext4_io_submit io_submit;	/* IO submission data */
1527dddbd6acSJan Kara 	unsigned int do_map:1;
15286b8ed620SJan Kara 	unsigned int scanned_until_end:1;
15291f1a55f0SJan Kara 	unsigned int journalled_more_data:1;
15304e7ea81dSJan Kara };
153164769240SAlex Tomas 
15324e7ea81dSJan Kara static void mpage_release_unused_pages(struct mpage_da_data *mpd,
15334e7ea81dSJan Kara 				       bool invalidate)
1534c4a0c46eSAneesh Kumar K.V {
1535fb5a5be0SMatthew Wilcox (Oracle) 	unsigned nr, i;
1536c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
1537fb5a5be0SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
1538c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1539c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
15404e7ea81dSJan Kara 
15414e7ea81dSJan Kara 	/* This is necessary when next_page == 0. */
15424e7ea81dSJan Kara 	if (mpd->first_page >= mpd->next_page)
15434e7ea81dSJan Kara 		return;
1544c4a0c46eSAneesh Kumar K.V 
15456b8ed620SJan Kara 	mpd->scanned_until_end = 0;
1546c7f5938aSCurt Wohlgemuth 	index = mpd->first_page;
1547c7f5938aSCurt Wohlgemuth 	end   = mpd->next_page - 1;
15484e7ea81dSJan Kara 	if (invalidate) {
15494e7ea81dSJan Kara 		ext4_lblk_t start, last;
155009cbfeafSKirill A. Shutemov 		start = index << (PAGE_SHIFT - inode->i_blkbits);
155109cbfeafSKirill A. Shutemov 		last = end << (PAGE_SHIFT - inode->i_blkbits);
15527f0d8e1dSEric Whitney 
15537f0d8e1dSEric Whitney 		/*
15547f0d8e1dSEric Whitney 		 * avoid racing with extent status tree scans made by
15557f0d8e1dSEric Whitney 		 * ext4_insert_delayed_block()
15567f0d8e1dSEric Whitney 		 */
15577f0d8e1dSEric Whitney 		down_write(&EXT4_I(inode)->i_data_sem);
155851865fdaSZheng Liu 		ext4_es_remove_extent(inode, start, last - start + 1);
15597f0d8e1dSEric Whitney 		up_write(&EXT4_I(inode)->i_data_sem);
15604e7ea81dSJan Kara 	}
156151865fdaSZheng Liu 
1562fb5a5be0SMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
1563c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
1564fb5a5be0SMatthew Wilcox (Oracle) 		nr = filemap_get_folios(mapping, &index, end, &fbatch);
1565fb5a5be0SMatthew Wilcox (Oracle) 		if (nr == 0)
1566c4a0c46eSAneesh Kumar K.V 			break;
1567fb5a5be0SMatthew Wilcox (Oracle) 		for (i = 0; i < nr; i++) {
1568fb5a5be0SMatthew Wilcox (Oracle) 			struct folio *folio = fbatch.folios[i];
15692b85a617SJan Kara 
1570fb5a5be0SMatthew Wilcox (Oracle) 			if (folio->index < mpd->first_page)
1571fb5a5be0SMatthew Wilcox (Oracle) 				continue;
1572fb5a5be0SMatthew Wilcox (Oracle) 			if (folio->index + folio_nr_pages(folio) - 1 > end)
1573fb5a5be0SMatthew Wilcox (Oracle) 				continue;
15747ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(!folio_test_locked(folio));
15757ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(folio_test_writeback(folio));
15764e7ea81dSJan Kara 			if (invalidate) {
15777ba13abbSMatthew Wilcox (Oracle) 				if (folio_mapped(folio))
15787ba13abbSMatthew Wilcox (Oracle) 					folio_clear_dirty_for_io(folio);
15797ba13abbSMatthew Wilcox (Oracle) 				block_invalidate_folio(folio, 0,
15807ba13abbSMatthew Wilcox (Oracle) 						folio_size(folio));
15817ba13abbSMatthew Wilcox (Oracle) 				folio_clear_uptodate(folio);
15824e7ea81dSJan Kara 			}
15837ba13abbSMatthew Wilcox (Oracle) 			folio_unlock(folio);
1584c4a0c46eSAneesh Kumar K.V 		}
1585fb5a5be0SMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
1586c4a0c46eSAneesh Kumar K.V 	}
1587c4a0c46eSAneesh Kumar K.V }
1588c4a0c46eSAneesh Kumar K.V 
1589df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
1590df22291fSAneesh Kumar K.V {
1591df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
159292b97816STheodore Ts'o 	struct super_block *sb = inode->i_sb;
1593f78ee70dSLukas Czerner 	struct ext4_inode_info *ei = EXT4_I(inode);
159492b97816STheodore Ts'o 
159592b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
15965dee5437STheodore Ts'o 	       EXT4_C2B(EXT4_SB(inode->i_sb),
1597f78ee70dSLukas Czerner 			ext4_count_free_clusters(sb)));
159892b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
159992b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1600f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
160157042651STheodore Ts'o 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
160292b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1603f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
16047b415bf6SAditya Kali 		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
160592b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Block reservation details");
160692b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1607f78ee70dSLukas Czerner 		 ei->i_reserved_data_blocks);
1608df22291fSAneesh Kumar K.V 	return;
1609df22291fSAneesh Kumar K.V }
1610df22291fSAneesh Kumar K.V 
161164769240SAlex Tomas /*
16120b02f4c0SEric Whitney  * ext4_insert_delayed_block - adds a delayed block to the extents status
16130b02f4c0SEric Whitney  *                             tree, incrementing the reserved cluster/block
16140b02f4c0SEric Whitney  *                             count or making a pending reservation
16150b02f4c0SEric Whitney  *                             where needed
16160b02f4c0SEric Whitney  *
16170b02f4c0SEric Whitney  * @inode - file containing the newly added block
16180b02f4c0SEric Whitney  * @lblk - logical block to be added
16190b02f4c0SEric Whitney  *
16200b02f4c0SEric Whitney  * Returns 0 on success, negative error code on failure.
16210b02f4c0SEric Whitney  */
16220b02f4c0SEric Whitney static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
16230b02f4c0SEric Whitney {
16240b02f4c0SEric Whitney 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
16250b02f4c0SEric Whitney 	int ret;
16260b02f4c0SEric Whitney 	bool allocated = false;
16270b02f4c0SEric Whitney 
16280b02f4c0SEric Whitney 	/*
16290b02f4c0SEric Whitney 	 * If the cluster containing lblk is shared with a delayed,
16300b02f4c0SEric Whitney 	 * written, or unwritten extent in a bigalloc file system, it's
16310b02f4c0SEric Whitney 	 * already been accounted for and does not need to be reserved.
16320b02f4c0SEric Whitney 	 * A pending reservation must be made for the cluster if it's
16330b02f4c0SEric Whitney 	 * shared with a written or unwritten extent and doesn't already
16340b02f4c0SEric Whitney 	 * have one.  Written and unwritten extents can be purged from the
16350b02f4c0SEric Whitney 	 * extents status tree if the system is under memory pressure, so
16360b02f4c0SEric Whitney 	 * it's necessary to examine the extent tree if a search of the
16370b02f4c0SEric Whitney 	 * extents status tree doesn't get a match.
16380b02f4c0SEric Whitney 	 */
16390b02f4c0SEric Whitney 	if (sbi->s_cluster_ratio == 1) {
16400b02f4c0SEric Whitney 		ret = ext4_da_reserve_space(inode);
16410b02f4c0SEric Whitney 		if (ret != 0)   /* ENOSPC */
16428782b020SBaokun Li 			return ret;
16430b02f4c0SEric Whitney 	} else {   /* bigalloc */
16440b02f4c0SEric Whitney 		if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
16450b02f4c0SEric Whitney 			if (!ext4_es_scan_clu(inode,
16460b02f4c0SEric Whitney 					      &ext4_es_is_mapped, lblk)) {
16470b02f4c0SEric Whitney 				ret = ext4_clu_mapped(inode,
16480b02f4c0SEric Whitney 						      EXT4_B2C(sbi, lblk));
16490b02f4c0SEric Whitney 				if (ret < 0)
16508782b020SBaokun Li 					return ret;
16510b02f4c0SEric Whitney 				if (ret == 0) {
16520b02f4c0SEric Whitney 					ret = ext4_da_reserve_space(inode);
16530b02f4c0SEric Whitney 					if (ret != 0)   /* ENOSPC */
16540b02f4c0SEric Whitney 						return ret;
16558782b020SBaokun Li 				} else {
16568782b020SBaokun Li 					allocated = true;
16578782b020SBaokun Li 				}
16588782b020SBaokun Li 			} else {
16598782b020SBaokun Li 				allocated = true;
16608782b020SBaokun Li 			}
16618782b020SBaokun Li 		}
16628782b020SBaokun Li 	}
16638782b020SBaokun Li 
16648782b020SBaokun Li 	ext4_es_insert_delayed_block(inode, lblk, allocated);
16658782b020SBaokun Li 	return 0;
16660b02f4c0SEric Whitney }
16670b02f4c0SEric Whitney 
16680b02f4c0SEric Whitney /*
16695356f261SAditya Kali  * This function is grabs code from the very beginning of
16705356f261SAditya Kali  * ext4_map_blocks, but assumes that the caller is from delayed write
16715356f261SAditya Kali  * time. This function looks up the requested blocks and sets the
16725356f261SAditya Kali  * buffer delay bit under the protection of i_data_sem.
16735356f261SAditya Kali  */
16745356f261SAditya Kali static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
16755356f261SAditya Kali 			      struct ext4_map_blocks *map,
16765356f261SAditya Kali 			      struct buffer_head *bh)
16775356f261SAditya Kali {
1678d100eef2SZheng Liu 	struct extent_status es;
16795356f261SAditya Kali 	int retval;
16805356f261SAditya Kali 	sector_t invalid_block = ~((sector_t) 0xffff);
1681921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1682921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
1683921f266bSDmitry Monakhov 
1684921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
1685921f266bSDmitry Monakhov #endif
16865356f261SAditya Kali 
16875356f261SAditya Kali 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
16885356f261SAditya Kali 		invalid_block = ~0;
16895356f261SAditya Kali 
16905356f261SAditya Kali 	map->m_flags = 0;
169170aa1554SRitesh Harjani 	ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
16925356f261SAditya Kali 		  (unsigned long) map->m_lblk);
1693d100eef2SZheng Liu 
1694d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
1695bb5835edSTheodore Ts'o 	if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1696d100eef2SZheng Liu 		if (ext4_es_is_hole(&es)) {
1697d100eef2SZheng Liu 			retval = 0;
1698c8b459f4SLukas Czerner 			down_read(&EXT4_I(inode)->i_data_sem);
1699d100eef2SZheng Liu 			goto add_delayed;
1700d100eef2SZheng Liu 		}
1701d100eef2SZheng Liu 
1702d100eef2SZheng Liu 		/*
17033eda41dfSEric Whitney 		 * Delayed extent could be allocated by fallocate.
17043eda41dfSEric Whitney 		 * So we need to check it.
1705d100eef2SZheng Liu 		 */
17063eda41dfSEric Whitney 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
17073eda41dfSEric Whitney 			map_bh(bh, inode->i_sb, invalid_block);
17083eda41dfSEric Whitney 			set_buffer_new(bh);
17093eda41dfSEric Whitney 			set_buffer_delay(bh);
1710d100eef2SZheng Liu 			return 0;
1711d100eef2SZheng Liu 		}
1712d100eef2SZheng Liu 
1713d100eef2SZheng Liu 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1714d100eef2SZheng Liu 		retval = es.es_len - (iblock - es.es_lblk);
1715d100eef2SZheng Liu 		if (retval > map->m_len)
1716d100eef2SZheng Liu 			retval = map->m_len;
1717d100eef2SZheng Liu 		map->m_len = retval;
1718d100eef2SZheng Liu 		if (ext4_es_is_written(&es))
1719d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_MAPPED;
1720d100eef2SZheng Liu 		else if (ext4_es_is_unwritten(&es))
1721d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1722d100eef2SZheng Liu 		else
17231e83bc81SArnd Bergmann 			BUG();
1724d100eef2SZheng Liu 
1725921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1726921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1727921f266bSDmitry Monakhov #endif
1728d100eef2SZheng Liu 		return retval;
1729d100eef2SZheng Liu 	}
1730d100eef2SZheng Liu 
17315356f261SAditya Kali 	/*
17325356f261SAditya Kali 	 * Try to see if we can get the block without requesting a new
17335356f261SAditya Kali 	 * file system block.
17345356f261SAditya Kali 	 */
1735c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
1736cbd7584eSJan Kara 	if (ext4_has_inline_data(inode))
17379c3569b5STao Ma 		retval = 0;
1738cbd7584eSJan Kara 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
17392f8e0a7cSZheng Liu 		retval = ext4_ext_map_blocks(NULL, inode, map, 0);
17405356f261SAditya Kali 	else
17412f8e0a7cSZheng Liu 		retval = ext4_ind_map_blocks(NULL, inode, map, 0);
17425356f261SAditya Kali 
1743d100eef2SZheng Liu add_delayed:
17445356f261SAditya Kali 	if (retval == 0) {
1745f7fec032SZheng Liu 		int ret;
1746ad431025SEric Whitney 
17475356f261SAditya Kali 		/*
17485356f261SAditya Kali 		 * XXX: __block_prepare_write() unmaps passed block,
17495356f261SAditya Kali 		 * is it OK?
17505356f261SAditya Kali 		 */
17515356f261SAditya Kali 
17520b02f4c0SEric Whitney 		ret = ext4_insert_delayed_block(inode, map->m_lblk);
17530b02f4c0SEric Whitney 		if (ret != 0) {
1754f7fec032SZheng Liu 			retval = ret;
175551865fdaSZheng Liu 			goto out_unlock;
1756f7fec032SZheng Liu 		}
175751865fdaSZheng Liu 
17585356f261SAditya Kali 		map_bh(bh, inode->i_sb, invalid_block);
17595356f261SAditya Kali 		set_buffer_new(bh);
17605356f261SAditya Kali 		set_buffer_delay(bh);
1761f7fec032SZheng Liu 	} else if (retval > 0) {
17623be78c73STheodore Ts'o 		unsigned int status;
1763f7fec032SZheng Liu 
176444fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
176544fb851dSZheng Liu 			ext4_warning(inode->i_sb,
176644fb851dSZheng Liu 				     "ES len assertion failed for inode "
176744fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
176844fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
176944fb851dSZheng Liu 			WARN_ON(1);
1770921f266bSDmitry Monakhov 		}
1771921f266bSDmitry Monakhov 
1772f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1773f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
17746c120399SBaokun Li 		ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1775f7fec032SZheng Liu 				      map->m_pblk, status);
17765356f261SAditya Kali 	}
17775356f261SAditya Kali 
17785356f261SAditya Kali out_unlock:
17795356f261SAditya Kali 	up_read((&EXT4_I(inode)->i_data_sem));
17805356f261SAditya Kali 
17815356f261SAditya Kali 	return retval;
17825356f261SAditya Kali }
17835356f261SAditya Kali 
17845356f261SAditya Kali /*
1785d91bd2c1SSeunghun Lee  * This is a special get_block_t callback which is used by
1786b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
1787b920c755STheodore Ts'o  * reserve space for a single block.
178829fa89d0SAneesh Kumar K.V  *
178929fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
179029fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
179129fa89d0SAneesh Kumar K.V  *
179229fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
179329fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
179429fa89d0SAneesh Kumar K.V  * initialized properly.
179564769240SAlex Tomas  */
17969c3569b5STao Ma int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
17972ed88685STheodore Ts'o 			   struct buffer_head *bh, int create)
179864769240SAlex Tomas {
17992ed88685STheodore Ts'o 	struct ext4_map_blocks map;
180064769240SAlex Tomas 	int ret = 0;
180164769240SAlex Tomas 
180264769240SAlex Tomas 	BUG_ON(create == 0);
18032ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
18042ed88685STheodore Ts'o 
18052ed88685STheodore Ts'o 	map.m_lblk = iblock;
18062ed88685STheodore Ts'o 	map.m_len = 1;
180764769240SAlex Tomas 
180864769240SAlex Tomas 	/*
180964769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
181064769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
181164769240SAlex Tomas 	 * the same as allocated blocks.
181264769240SAlex Tomas 	 */
18135356f261SAditya Kali 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
18145356f261SAditya Kali 	if (ret <= 0)
18152ed88685STheodore Ts'o 		return ret;
181664769240SAlex Tomas 
18172ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
1818ed8ad838SJan Kara 	ext4_update_bh_state(bh, map.m_flags);
18192ed88685STheodore Ts'o 
18202ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
18212ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
18222ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
18232ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
18242ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
18252ed88685STheodore Ts'o 		 * for partial write.
18262ed88685STheodore Ts'o 		 */
18272ed88685STheodore Ts'o 		set_buffer_new(bh);
1828c8205636STheodore Ts'o 		set_buffer_mapped(bh);
18292ed88685STheodore Ts'o 	}
18302ed88685STheodore Ts'o 	return 0;
183164769240SAlex Tomas }
183261628a3fSMingming Cao 
183333483b3bSMatthew Wilcox static void mpage_folio_done(struct mpage_da_data *mpd, struct folio *folio)
1834eaf2ca10SJan Kara {
183533483b3bSMatthew Wilcox 	mpd->first_page += folio_nr_pages(folio);
183633483b3bSMatthew Wilcox 	folio_unlock(folio);
1837eaf2ca10SJan Kara }
1838eaf2ca10SJan Kara 
183981a0d3e1SMatthew Wilcox static int mpage_submit_folio(struct mpage_da_data *mpd, struct folio *folio)
18405f1132b2SJan Kara {
184181a0d3e1SMatthew Wilcox 	size_t len;
1842a056bdaaSJan Kara 	loff_t size;
18435f1132b2SJan Kara 	int err;
18445f1132b2SJan Kara 
184581a0d3e1SMatthew Wilcox 	BUG_ON(folio->index != mpd->first_page);
184681a0d3e1SMatthew Wilcox 	folio_clear_dirty_for_io(folio);
1847a056bdaaSJan Kara 	/*
1848a056bdaaSJan Kara 	 * We have to be very careful here!  Nothing protects writeback path
1849a056bdaaSJan Kara 	 * against i_size changes and the page can be writeably mapped into
1850a056bdaaSJan Kara 	 * page tables. So an application can be growing i_size and writing
185181a0d3e1SMatthew Wilcox 	 * data through mmap while writeback runs. folio_clear_dirty_for_io()
1852a056bdaaSJan Kara 	 * write-protects our page in page tables and the page cannot get
185381a0d3e1SMatthew Wilcox 	 * written to again until we release folio lock. So only after
185481a0d3e1SMatthew Wilcox 	 * folio_clear_dirty_for_io() we are safe to sample i_size for
1855e8d6062cSMatthew Wilcox 	 * ext4_bio_write_folio() to zero-out tail of the written page. We rely
1856e8d6062cSMatthew Wilcox 	 * on the barrier provided by folio_test_clear_dirty() in
185781a0d3e1SMatthew Wilcox 	 * folio_clear_dirty_for_io() to make sure i_size is really sampled only
1858a056bdaaSJan Kara 	 * after page tables are updated.
1859a056bdaaSJan Kara 	 */
1860a056bdaaSJan Kara 	size = i_size_read(mpd->inode);
186181a0d3e1SMatthew Wilcox 	len = folio_size(folio);
186281a0d3e1SMatthew Wilcox 	if (folio_pos(folio) + len > size &&
1863c93d8f88SEric Biggers 	    !ext4_verity_in_progress(mpd->inode))
186409cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
1865e8d6062cSMatthew Wilcox 	err = ext4_bio_write_folio(&mpd->io_submit, folio, len);
18665f1132b2SJan Kara 	if (!err)
18675f1132b2SJan Kara 		mpd->wbc->nr_to_write--;
18685f1132b2SJan Kara 
18695f1132b2SJan Kara 	return err;
18705f1132b2SJan Kara }
18715f1132b2SJan Kara 
18726db07461SRitesh Harjani #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
18734e7ea81dSJan Kara 
187461628a3fSMingming Cao /*
1875fffb2739SJan Kara  * mballoc gives us at most this number of blocks...
1876fffb2739SJan Kara  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1877fffb2739SJan Kara  * The rest of mballoc seems to handle chunks up to full group size.
187861628a3fSMingming Cao  */
1879fffb2739SJan Kara #define MAX_WRITEPAGES_EXTENT_LEN 2048
1880525f4ed8SMingming Cao 
1881525f4ed8SMingming Cao /*
18824e7ea81dSJan Kara  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
18834e7ea81dSJan Kara  *
18844e7ea81dSJan Kara  * @mpd - extent of blocks
18854e7ea81dSJan Kara  * @lblk - logical number of the block in the file
188609930042SJan Kara  * @bh - buffer head we want to add to the extent
18874e7ea81dSJan Kara  *
188809930042SJan Kara  * The function is used to collect contig. blocks in the same state. If the
188909930042SJan Kara  * buffer doesn't require mapping for writeback and we haven't started the
189009930042SJan Kara  * extent of buffers to map yet, the function returns 'true' immediately - the
189109930042SJan Kara  * caller can write the buffer right away. Otherwise the function returns true
189209930042SJan Kara  * if the block has been added to the extent, false if the block couldn't be
189309930042SJan Kara  * added.
18944e7ea81dSJan Kara  */
189509930042SJan Kara static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
189609930042SJan Kara 				   struct buffer_head *bh)
18974e7ea81dSJan Kara {
18984e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
18994e7ea81dSJan Kara 
190009930042SJan Kara 	/* Buffer that doesn't need mapping for writeback? */
190109930042SJan Kara 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
190209930042SJan Kara 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
190309930042SJan Kara 		/* So far no extent to map => we write the buffer right away */
190409930042SJan Kara 		if (map->m_len == 0)
190509930042SJan Kara 			return true;
190609930042SJan Kara 		return false;
190709930042SJan Kara 	}
19084e7ea81dSJan Kara 
19094e7ea81dSJan Kara 	/* First block in the extent? */
19104e7ea81dSJan Kara 	if (map->m_len == 0) {
1911dddbd6acSJan Kara 		/* We cannot map unless handle is started... */
1912dddbd6acSJan Kara 		if (!mpd->do_map)
1913dddbd6acSJan Kara 			return false;
19144e7ea81dSJan Kara 		map->m_lblk = lblk;
19154e7ea81dSJan Kara 		map->m_len = 1;
191609930042SJan Kara 		map->m_flags = bh->b_state & BH_FLAGS;
191709930042SJan Kara 		return true;
19184e7ea81dSJan Kara 	}
19194e7ea81dSJan Kara 
192009930042SJan Kara 	/* Don't go larger than mballoc is willing to allocate */
192109930042SJan Kara 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
192209930042SJan Kara 		return false;
192309930042SJan Kara 
19244e7ea81dSJan Kara 	/* Can we merge the block to our big extent? */
19254e7ea81dSJan Kara 	if (lblk == map->m_lblk + map->m_len &&
192609930042SJan Kara 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
19274e7ea81dSJan Kara 		map->m_len++;
192809930042SJan Kara 		return true;
19294e7ea81dSJan Kara 	}
193009930042SJan Kara 	return false;
19314e7ea81dSJan Kara }
19324e7ea81dSJan Kara 
19335f1132b2SJan Kara /*
19345f1132b2SJan Kara  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
19355f1132b2SJan Kara  *
19365f1132b2SJan Kara  * @mpd - extent of blocks for mapping
19375f1132b2SJan Kara  * @head - the first buffer in the page
19385f1132b2SJan Kara  * @bh - buffer we should start processing from
19395f1132b2SJan Kara  * @lblk - logical number of the block in the file corresponding to @bh
19405f1132b2SJan Kara  *
19415f1132b2SJan Kara  * Walk through page buffers from @bh upto @head (exclusive) and either submit
19425f1132b2SJan Kara  * the page for IO if all buffers in this page were mapped and there's no
19435f1132b2SJan Kara  * accumulated extent of buffers to map or add buffers in the page to the
19445f1132b2SJan Kara  * extent of buffers to map. The function returns 1 if the caller can continue
19455f1132b2SJan Kara  * by processing the next page, 0 if it should stop adding buffers to the
19465f1132b2SJan Kara  * extent to map because we cannot extend it anymore. It can also return value
19475f1132b2SJan Kara  * < 0 in case of error during IO submission.
19485f1132b2SJan Kara  */
19495f1132b2SJan Kara static int mpage_process_page_bufs(struct mpage_da_data *mpd,
19504e7ea81dSJan Kara 				   struct buffer_head *head,
19514e7ea81dSJan Kara 				   struct buffer_head *bh,
19524e7ea81dSJan Kara 				   ext4_lblk_t lblk)
19534e7ea81dSJan Kara {
19544e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
19555f1132b2SJan Kara 	int err;
195693407472SFabian Frederick 	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
19574e7ea81dSJan Kara 							>> inode->i_blkbits;
19584e7ea81dSJan Kara 
1959c93d8f88SEric Biggers 	if (ext4_verity_in_progress(inode))
1960c93d8f88SEric Biggers 		blocks = EXT_MAX_BLOCKS;
1961c93d8f88SEric Biggers 
19624e7ea81dSJan Kara 	do {
19634e7ea81dSJan Kara 		BUG_ON(buffer_locked(bh));
19644e7ea81dSJan Kara 
196509930042SJan Kara 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
19664e7ea81dSJan Kara 			/* Found extent to map? */
19674e7ea81dSJan Kara 			if (mpd->map.m_len)
19685f1132b2SJan Kara 				return 0;
1969dddbd6acSJan Kara 			/* Buffer needs mapping and handle is not started? */
1970dddbd6acSJan Kara 			if (!mpd->do_map)
1971dddbd6acSJan Kara 				return 0;
197209930042SJan Kara 			/* Everything mapped so far and we hit EOF */
19735f1132b2SJan Kara 			break;
19744e7ea81dSJan Kara 		}
19754e7ea81dSJan Kara 	} while (lblk++, (bh = bh->b_this_page) != head);
19765f1132b2SJan Kara 	/* So far everything mapped? Submit the page for IO. */
19775f1132b2SJan Kara 	if (mpd->map.m_len == 0) {
197881a0d3e1SMatthew Wilcox 		err = mpage_submit_folio(mpd, head->b_folio);
19795f1132b2SJan Kara 		if (err < 0)
19804e7ea81dSJan Kara 			return err;
198133483b3bSMatthew Wilcox 		mpage_folio_done(mpd, head->b_folio);
19824e7ea81dSJan Kara 	}
19836b8ed620SJan Kara 	if (lblk >= blocks) {
19846b8ed620SJan Kara 		mpd->scanned_until_end = 1;
19856b8ed620SJan Kara 		return 0;
19866b8ed620SJan Kara 	}
19876b8ed620SJan Kara 	return 1;
19885f1132b2SJan Kara }
19894e7ea81dSJan Kara 
19904e7ea81dSJan Kara /*
19914da2f6e3SMatthew Wilcox  * mpage_process_folio - update folio buffers corresponding to changed extent
19924da2f6e3SMatthew Wilcox  *			 and may submit fully mapped page for IO
19934da2f6e3SMatthew Wilcox  * @mpd: description of extent to map, on return next extent to map
19944da2f6e3SMatthew Wilcox  * @folio: Contains these buffers.
19954da2f6e3SMatthew Wilcox  * @m_lblk: logical block mapping.
19964da2f6e3SMatthew Wilcox  * @m_pblk: corresponding physical mapping.
19974da2f6e3SMatthew Wilcox  * @map_bh: determines on return whether this page requires any further
19982943fdbcSRitesh Harjani  *		  mapping or not.
19994da2f6e3SMatthew Wilcox  *
20004da2f6e3SMatthew Wilcox  * Scan given folio buffers corresponding to changed extent and update buffer
20012943fdbcSRitesh Harjani  * state according to new extent state.
20022943fdbcSRitesh Harjani  * We map delalloc buffers to their physical location, clear unwritten bits.
20034da2f6e3SMatthew Wilcox  * If the given folio is not fully mapped, we update @mpd to the next extent in
20044da2f6e3SMatthew Wilcox  * the given folio that needs mapping & return @map_bh as true.
20052943fdbcSRitesh Harjani  */
20064da2f6e3SMatthew Wilcox static int mpage_process_folio(struct mpage_da_data *mpd, struct folio *folio,
20072943fdbcSRitesh Harjani 			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
20082943fdbcSRitesh Harjani 			      bool *map_bh)
20092943fdbcSRitesh Harjani {
20102943fdbcSRitesh Harjani 	struct buffer_head *head, *bh;
20112943fdbcSRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
20122943fdbcSRitesh Harjani 	ext4_lblk_t lblk = *m_lblk;
20132943fdbcSRitesh Harjani 	ext4_fsblk_t pblock = *m_pblk;
20142943fdbcSRitesh Harjani 	int err = 0;
2015c8cc8816SRitesh Harjani 	int blkbits = mpd->inode->i_blkbits;
2016c8cc8816SRitesh Harjani 	ssize_t io_end_size = 0;
2017c8cc8816SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
20182943fdbcSRitesh Harjani 
20194da2f6e3SMatthew Wilcox 	bh = head = folio_buffers(folio);
20202943fdbcSRitesh Harjani 	do {
20212943fdbcSRitesh Harjani 		if (lblk < mpd->map.m_lblk)
20222943fdbcSRitesh Harjani 			continue;
20232943fdbcSRitesh Harjani 		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
20242943fdbcSRitesh Harjani 			/*
20252943fdbcSRitesh Harjani 			 * Buffer after end of mapped extent.
20264da2f6e3SMatthew Wilcox 			 * Find next buffer in the folio to map.
20272943fdbcSRitesh Harjani 			 */
20282943fdbcSRitesh Harjani 			mpd->map.m_len = 0;
20292943fdbcSRitesh Harjani 			mpd->map.m_flags = 0;
2030c8cc8816SRitesh Harjani 			io_end_vec->size += io_end_size;
20312943fdbcSRitesh Harjani 
20322943fdbcSRitesh Harjani 			err = mpage_process_page_bufs(mpd, head, bh, lblk);
20332943fdbcSRitesh Harjani 			if (err > 0)
20342943fdbcSRitesh Harjani 				err = 0;
2035c8cc8816SRitesh Harjani 			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2036c8cc8816SRitesh Harjani 				io_end_vec = ext4_alloc_io_end_vec(io_end);
20374d06bfb9SRitesh Harjani 				if (IS_ERR(io_end_vec)) {
20384d06bfb9SRitesh Harjani 					err = PTR_ERR(io_end_vec);
20394d06bfb9SRitesh Harjani 					goto out;
20404d06bfb9SRitesh Harjani 				}
2041d1e18b88SRitesh Harjani 				io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2042c8cc8816SRitesh Harjani 			}
20432943fdbcSRitesh Harjani 			*map_bh = true;
20442943fdbcSRitesh Harjani 			goto out;
20452943fdbcSRitesh Harjani 		}
20462943fdbcSRitesh Harjani 		if (buffer_delay(bh)) {
20472943fdbcSRitesh Harjani 			clear_buffer_delay(bh);
20482943fdbcSRitesh Harjani 			bh->b_blocknr = pblock++;
20492943fdbcSRitesh Harjani 		}
20502943fdbcSRitesh Harjani 		clear_buffer_unwritten(bh);
2051c8cc8816SRitesh Harjani 		io_end_size += (1 << blkbits);
20522943fdbcSRitesh Harjani 	} while (lblk++, (bh = bh->b_this_page) != head);
2053c8cc8816SRitesh Harjani 
2054c8cc8816SRitesh Harjani 	io_end_vec->size += io_end_size;
20552943fdbcSRitesh Harjani 	*map_bh = false;
20562943fdbcSRitesh Harjani out:
20572943fdbcSRitesh Harjani 	*m_lblk = lblk;
20582943fdbcSRitesh Harjani 	*m_pblk = pblock;
20592943fdbcSRitesh Harjani 	return err;
20602943fdbcSRitesh Harjani }
20612943fdbcSRitesh Harjani 
20622943fdbcSRitesh Harjani /*
20634e7ea81dSJan Kara  * mpage_map_buffers - update buffers corresponding to changed extent and
20644e7ea81dSJan Kara  *		       submit fully mapped pages for IO
20654e7ea81dSJan Kara  *
20664e7ea81dSJan Kara  * @mpd - description of extent to map, on return next extent to map
20674e7ea81dSJan Kara  *
20684e7ea81dSJan Kara  * Scan buffers corresponding to changed extent (we expect corresponding pages
20694e7ea81dSJan Kara  * to be already locked) and update buffer state according to new extent state.
20704e7ea81dSJan Kara  * We map delalloc buffers to their physical location, clear unwritten bits,
2071556615dcSLukas Czerner  * and mark buffers as uninit when we perform writes to unwritten extents
20724e7ea81dSJan Kara  * and do extent conversion after IO is finished. If the last page is not fully
20734e7ea81dSJan Kara  * mapped, we update @map to the next extent in the last page that needs
20744e7ea81dSJan Kara  * mapping. Otherwise we submit the page for IO.
20754e7ea81dSJan Kara  */
20764e7ea81dSJan Kara static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
20774e7ea81dSJan Kara {
20787530d093SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
20797530d093SMatthew Wilcox (Oracle) 	unsigned nr, i;
20804e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
208109cbfeafSKirill A. Shutemov 	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
20824e7ea81dSJan Kara 	pgoff_t start, end;
20834e7ea81dSJan Kara 	ext4_lblk_t lblk;
20842943fdbcSRitesh Harjani 	ext4_fsblk_t pblock;
20854e7ea81dSJan Kara 	int err;
20862943fdbcSRitesh Harjani 	bool map_bh = false;
20874e7ea81dSJan Kara 
20884e7ea81dSJan Kara 	start = mpd->map.m_lblk >> bpp_bits;
20894e7ea81dSJan Kara 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
20904e7ea81dSJan Kara 	lblk = start << bpp_bits;
20914e7ea81dSJan Kara 	pblock = mpd->map.m_pblk;
20924e7ea81dSJan Kara 
20937530d093SMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
20944e7ea81dSJan Kara 	while (start <= end) {
20957530d093SMatthew Wilcox (Oracle) 		nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
20967530d093SMatthew Wilcox (Oracle) 		if (nr == 0)
20974e7ea81dSJan Kara 			break;
20987530d093SMatthew Wilcox (Oracle) 		for (i = 0; i < nr; i++) {
20994da2f6e3SMatthew Wilcox 			struct folio *folio = fbatch.folios[i];
21004e7ea81dSJan Kara 
21014da2f6e3SMatthew Wilcox 			err = mpage_process_folio(mpd, folio, &lblk, &pblock,
21022943fdbcSRitesh Harjani 						 &map_bh);
21034e7ea81dSJan Kara 			/*
21042943fdbcSRitesh Harjani 			 * If map_bh is true, means page may require further bh
21052943fdbcSRitesh Harjani 			 * mapping, or maybe the page was submitted for IO.
21062943fdbcSRitesh Harjani 			 * So we return to call further extent mapping.
21074e7ea81dSJan Kara 			 */
210839c0ae16SJason Yan 			if (err < 0 || map_bh)
21092943fdbcSRitesh Harjani 				goto out;
21104e7ea81dSJan Kara 			/* Page fully mapped - let IO run! */
211181a0d3e1SMatthew Wilcox 			err = mpage_submit_folio(mpd, folio);
21122943fdbcSRitesh Harjani 			if (err < 0)
21132943fdbcSRitesh Harjani 				goto out;
211433483b3bSMatthew Wilcox 			mpage_folio_done(mpd, folio);
21154e7ea81dSJan Kara 		}
21167530d093SMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
21174e7ea81dSJan Kara 	}
21184e7ea81dSJan Kara 	/* Extent fully mapped and matches with page boundary. We are done. */
21194e7ea81dSJan Kara 	mpd->map.m_len = 0;
21204e7ea81dSJan Kara 	mpd->map.m_flags = 0;
21214e7ea81dSJan Kara 	return 0;
21222943fdbcSRitesh Harjani out:
21237530d093SMatthew Wilcox (Oracle) 	folio_batch_release(&fbatch);
21242943fdbcSRitesh Harjani 	return err;
21254e7ea81dSJan Kara }
21264e7ea81dSJan Kara 
21274e7ea81dSJan Kara static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
21284e7ea81dSJan Kara {
21294e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
21304e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
21314e7ea81dSJan Kara 	int get_blocks_flags;
2132090f32eeSLukas Czerner 	int err, dioread_nolock;
21334e7ea81dSJan Kara 
21344e7ea81dSJan Kara 	trace_ext4_da_write_pages_extent(inode, map);
21354e7ea81dSJan Kara 	/*
21364e7ea81dSJan Kara 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2137556615dcSLukas Czerner 	 * to convert an unwritten extent to be initialized (in the case
21384e7ea81dSJan Kara 	 * where we have written into one or more preallocated blocks).  It is
21394e7ea81dSJan Kara 	 * possible that we're going to need more metadata blocks than
21404e7ea81dSJan Kara 	 * previously reserved. However we must not fail because we're in
21414e7ea81dSJan Kara 	 * writeback and there is nothing we can do about it so it might result
21424e7ea81dSJan Kara 	 * in data loss.  So use reserved blocks to allocate metadata if
21434e7ea81dSJan Kara 	 * possible.
21444e7ea81dSJan Kara 	 *
2145754cfed6STheodore Ts'o 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2146754cfed6STheodore Ts'o 	 * the blocks in question are delalloc blocks.  This indicates
2147754cfed6STheodore Ts'o 	 * that the blocks and quotas has already been checked when
2148754cfed6STheodore Ts'o 	 * the data was copied into the page cache.
21494e7ea81dSJan Kara 	 */
21504e7ea81dSJan Kara 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2151ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2152ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_IO_SUBMIT;
2153090f32eeSLukas Czerner 	dioread_nolock = ext4_should_dioread_nolock(inode);
2154090f32eeSLukas Czerner 	if (dioread_nolock)
21554e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
21566db07461SRitesh Harjani 	if (map->m_flags & BIT(BH_Delay))
21574e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
21584e7ea81dSJan Kara 
21594e7ea81dSJan Kara 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
21604e7ea81dSJan Kara 	if (err < 0)
21614e7ea81dSJan Kara 		return err;
2162090f32eeSLukas Czerner 	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
21636b523df4SJan Kara 		if (!mpd->io_submit.io_end->handle &&
21646b523df4SJan Kara 		    ext4_handle_valid(handle)) {
21656b523df4SJan Kara 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
21666b523df4SJan Kara 			handle->h_rsv_handle = NULL;
21676b523df4SJan Kara 		}
21683613d228SJan Kara 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
21696b523df4SJan Kara 	}
21704e7ea81dSJan Kara 
21714e7ea81dSJan Kara 	BUG_ON(map->m_len == 0);
21724e7ea81dSJan Kara 	return 0;
21734e7ea81dSJan Kara }
21744e7ea81dSJan Kara 
21754e7ea81dSJan Kara /*
21764e7ea81dSJan Kara  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
21774e7ea81dSJan Kara  *				 mpd->len and submit pages underlying it for IO
21784e7ea81dSJan Kara  *
21794e7ea81dSJan Kara  * @handle - handle for journal operations
21804e7ea81dSJan Kara  * @mpd - extent to map
21817534e854SJan Kara  * @give_up_on_write - we set this to true iff there is a fatal error and there
21827534e854SJan Kara  *                     is no hope of writing the data. The caller should discard
21837534e854SJan Kara  *                     dirty pages to avoid infinite loops.
21844e7ea81dSJan Kara  *
21854e7ea81dSJan Kara  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
21864e7ea81dSJan Kara  * delayed, blocks are allocated, if it is unwritten, we may need to convert
21874e7ea81dSJan Kara  * them to initialized or split the described range from larger unwritten
21884e7ea81dSJan Kara  * extent. Note that we need not map all the described range since allocation
21894e7ea81dSJan Kara  * can return less blocks or the range is covered by more unwritten extents. We
21904e7ea81dSJan Kara  * cannot map more because we are limited by reserved transaction credits. On
21914e7ea81dSJan Kara  * the other hand we always make sure that the last touched page is fully
21924e7ea81dSJan Kara  * mapped so that it can be written out (and thus forward progress is
21934e7ea81dSJan Kara  * guaranteed). After mapping we submit all mapped pages for IO.
21944e7ea81dSJan Kara  */
21954e7ea81dSJan Kara static int mpage_map_and_submit_extent(handle_t *handle,
2196cb530541STheodore Ts'o 				       struct mpage_da_data *mpd,
2197cb530541STheodore Ts'o 				       bool *give_up_on_write)
21984e7ea81dSJan Kara {
21994e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
22004e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
22014e7ea81dSJan Kara 	int err;
22024e7ea81dSJan Kara 	loff_t disksize;
22036603120eSDmitry Monakhov 	int progress = 0;
2204c8cc8816SRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
22054d06bfb9SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec;
22064e7ea81dSJan Kara 
22074d06bfb9SRitesh Harjani 	io_end_vec = ext4_alloc_io_end_vec(io_end);
22084d06bfb9SRitesh Harjani 	if (IS_ERR(io_end_vec))
22094d06bfb9SRitesh Harjani 		return PTR_ERR(io_end_vec);
2210c8cc8816SRitesh Harjani 	io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
221127d7c4edSJan Kara 	do {
22124e7ea81dSJan Kara 		err = mpage_map_one_extent(handle, mpd);
22134e7ea81dSJan Kara 		if (err < 0) {
22144e7ea81dSJan Kara 			struct super_block *sb = inode->i_sb;
22154e7ea81dSJan Kara 
221695257987SJan Kara 			if (ext4_forced_shutdown(sb))
2217cb530541STheodore Ts'o 				goto invalidate_dirty_pages;
22184e7ea81dSJan Kara 			/*
2219cb530541STheodore Ts'o 			 * Let the uper layers retry transient errors.
2220cb530541STheodore Ts'o 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2221cb530541STheodore Ts'o 			 * is non-zero, a commit should free up blocks.
22224e7ea81dSJan Kara 			 */
2223cb530541STheodore Ts'o 			if ((err == -ENOMEM) ||
22246603120eSDmitry Monakhov 			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
22256603120eSDmitry Monakhov 				if (progress)
22266603120eSDmitry Monakhov 					goto update_disksize;
2227cb530541STheodore Ts'o 				return err;
22286603120eSDmitry Monakhov 			}
22294e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
22304e7ea81dSJan Kara 				 "Delayed block allocation failed for "
22314e7ea81dSJan Kara 				 "inode %lu at logical offset %llu with"
22324e7ea81dSJan Kara 				 " max blocks %u with error %d",
22334e7ea81dSJan Kara 				 inode->i_ino,
22344e7ea81dSJan Kara 				 (unsigned long long)map->m_lblk,
2235cb530541STheodore Ts'o 				 (unsigned)map->m_len, -err);
22364e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
22374e7ea81dSJan Kara 				 "This should not happen!! Data will "
22384e7ea81dSJan Kara 				 "be lost\n");
22394e7ea81dSJan Kara 			if (err == -ENOSPC)
22404e7ea81dSJan Kara 				ext4_print_free_blocks(inode);
2241cb530541STheodore Ts'o 		invalidate_dirty_pages:
2242cb530541STheodore Ts'o 			*give_up_on_write = true;
22434e7ea81dSJan Kara 			return err;
22444e7ea81dSJan Kara 		}
22456603120eSDmitry Monakhov 		progress = 1;
22464e7ea81dSJan Kara 		/*
22474e7ea81dSJan Kara 		 * Update buffer state, submit mapped pages, and get us new
22484e7ea81dSJan Kara 		 * extent to map
22494e7ea81dSJan Kara 		 */
22504e7ea81dSJan Kara 		err = mpage_map_and_submit_buffers(mpd);
22514e7ea81dSJan Kara 		if (err < 0)
22526603120eSDmitry Monakhov 			goto update_disksize;
225327d7c4edSJan Kara 	} while (map->m_len);
22544e7ea81dSJan Kara 
22556603120eSDmitry Monakhov update_disksize:
2256622cad13STheodore Ts'o 	/*
2257622cad13STheodore Ts'o 	 * Update on-disk size after IO is submitted.  Races with
2258622cad13STheodore Ts'o 	 * truncate are avoided by checking i_size under i_data_sem.
2259622cad13STheodore Ts'o 	 */
226009cbfeafSKirill A. Shutemov 	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
226135df4299SQian Cai 	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
22624e7ea81dSJan Kara 		int err2;
2263622cad13STheodore Ts'o 		loff_t i_size;
22644e7ea81dSJan Kara 
2265622cad13STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
2266622cad13STheodore Ts'o 		i_size = i_size_read(inode);
2267622cad13STheodore Ts'o 		if (disksize > i_size)
2268622cad13STheodore Ts'o 			disksize = i_size;
2269622cad13STheodore Ts'o 		if (disksize > EXT4_I(inode)->i_disksize)
2270622cad13STheodore Ts'o 			EXT4_I(inode)->i_disksize = disksize;
2271622cad13STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
2272b907f2d5STheodore Ts'o 		err2 = ext4_mark_inode_dirty(handle, inode);
2273878520acSTheodore Ts'o 		if (err2) {
227454d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err2,
22754e7ea81dSJan Kara 				       "Failed to mark inode %lu dirty",
22764e7ea81dSJan Kara 				       inode->i_ino);
2277878520acSTheodore Ts'o 		}
22784e7ea81dSJan Kara 		if (!err)
22794e7ea81dSJan Kara 			err = err2;
22804e7ea81dSJan Kara 	}
22814e7ea81dSJan Kara 	return err;
22824e7ea81dSJan Kara }
22834e7ea81dSJan Kara 
22844e7ea81dSJan Kara /*
2285fffb2739SJan Kara  * Calculate the total number of credits to reserve for one writepages
228620970ba6STheodore Ts'o  * iteration. This is called from ext4_writepages(). We map an extent of
2287fffb2739SJan Kara  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2288fffb2739SJan Kara  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2289fffb2739SJan Kara  * bpp - 1 blocks in bpp different extents.
2290525f4ed8SMingming Cao  */
2291fffb2739SJan Kara static int ext4_da_writepages_trans_blocks(struct inode *inode)
2292fffb2739SJan Kara {
2293fffb2739SJan Kara 	int bpp = ext4_journal_blocks_per_page(inode);
2294525f4ed8SMingming Cao 
2295fffb2739SJan Kara 	return ext4_meta_trans_blocks(inode,
2296fffb2739SJan Kara 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2297525f4ed8SMingming Cao }
229861628a3fSMingming Cao 
229980be8c5cSRitesh Harjani static int ext4_journal_folio_buffers(handle_t *handle, struct folio *folio,
230080be8c5cSRitesh Harjani 				     size_t len)
23013f079114SJan Kara {
230280be8c5cSRitesh Harjani 	struct buffer_head *page_bufs = folio_buffers(folio);
230380be8c5cSRitesh Harjani 	struct inode *inode = folio->mapping->host;
23043f079114SJan Kara 	int ret, err;
23053f079114SJan Kara 
23063f079114SJan Kara 	ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
23073f079114SJan Kara 				     NULL, do_journal_get_write_access);
23083f079114SJan Kara 	err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
23093f079114SJan Kara 				     NULL, write_end_fn);
23103f079114SJan Kara 	if (ret == 0)
23113f079114SJan Kara 		ret = err;
231280be8c5cSRitesh Harjani 	err = ext4_jbd2_inode_add_write(handle, inode, folio_pos(folio), len);
23133f079114SJan Kara 	if (ret == 0)
23143f079114SJan Kara 		ret = err;
23153f079114SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
23163f079114SJan Kara 
23173f079114SJan Kara 	return ret;
23183f079114SJan Kara }
23193f079114SJan Kara 
23203f079114SJan Kara static int mpage_journal_page_buffers(handle_t *handle,
23213f079114SJan Kara 				      struct mpage_da_data *mpd,
232280be8c5cSRitesh Harjani 				      struct folio *folio)
23233f079114SJan Kara {
23243f079114SJan Kara 	struct inode *inode = mpd->inode;
23253f079114SJan Kara 	loff_t size = i_size_read(inode);
232680be8c5cSRitesh Harjani 	size_t len = folio_size(folio);
23273f079114SJan Kara 
232880be8c5cSRitesh Harjani 	folio_clear_checked(folio);
23293f079114SJan Kara 	mpd->wbc->nr_to_write--;
23303f079114SJan Kara 
233180be8c5cSRitesh Harjani 	if (folio_pos(folio) + len > size &&
23323f079114SJan Kara 	    !ext4_verity_in_progress(inode))
233380be8c5cSRitesh Harjani 		len = size - folio_pos(folio);
23343f079114SJan Kara 
233580be8c5cSRitesh Harjani 	return ext4_journal_folio_buffers(handle, folio, len);
23363f079114SJan Kara }
23373f079114SJan Kara 
23388e48dcfbSTheodore Ts'o /*
23394e7ea81dSJan Kara  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2340de0039f6SJan Kara  * 				 needing mapping, submit mapped pages
23414e7ea81dSJan Kara  *
23424e7ea81dSJan Kara  * @mpd - where to look for pages
23434e7ea81dSJan Kara  *
23444e7ea81dSJan Kara  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2345de0039f6SJan Kara  * IO immediately. If we cannot map blocks, we submit just already mapped
2346de0039f6SJan Kara  * buffers in the page for IO and keep page dirty. When we can map blocks and
2347de0039f6SJan Kara  * we find a page which isn't mapped we start accumulating extent of buffers
2348de0039f6SJan Kara  * underlying these pages that needs mapping (formed by either delayed or
2349de0039f6SJan Kara  * unwritten buffers). We also lock the pages containing these buffers. The
2350de0039f6SJan Kara  * extent found is returned in @mpd structure (starting at mpd->lblk with
2351de0039f6SJan Kara  * length mpd->len blocks).
23524e7ea81dSJan Kara  *
23534e7ea81dSJan Kara  * Note that this function can attach bios to one io_end structure which are
23544e7ea81dSJan Kara  * neither logically nor physically contiguous. Although it may seem as an
23554e7ea81dSJan Kara  * unnecessary complication, it is actually inevitable in blocksize < pagesize
23564e7ea81dSJan Kara  * case as we need to track IO to all buffers underlying a page in one io_end.
23578e48dcfbSTheodore Ts'o  */
23584e7ea81dSJan Kara static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
23598e48dcfbSTheodore Ts'o {
23604e7ea81dSJan Kara 	struct address_space *mapping = mpd->inode->i_mapping;
236150ead253SVishal Moola (Oracle) 	struct folio_batch fbatch;
236250ead253SVishal Moola (Oracle) 	unsigned int nr_folios;
23634e7ea81dSJan Kara 	pgoff_t index = mpd->first_page;
23644e7ea81dSJan Kara 	pgoff_t end = mpd->last_page;
236510bbd235SMatthew Wilcox 	xa_mark_t tag;
23664e7ea81dSJan Kara 	int i, err = 0;
23674e7ea81dSJan Kara 	int blkbits = mpd->inode->i_blkbits;
23684e7ea81dSJan Kara 	ext4_lblk_t lblk;
23694e7ea81dSJan Kara 	struct buffer_head *head;
23703f079114SJan Kara 	handle_t *handle = NULL;
23713f079114SJan Kara 	int bpp = ext4_journal_blocks_per_page(mpd->inode);
23728e48dcfbSTheodore Ts'o 
23734e7ea81dSJan Kara 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
23745b41d924SEric Sandeen 		tag = PAGECACHE_TAG_TOWRITE;
23755b41d924SEric Sandeen 	else
23765b41d924SEric Sandeen 		tag = PAGECACHE_TAG_DIRTY;
23773f079114SJan Kara 
2378e6c28a26SJan Kara 	mpd->map.m_len = 0;
2379e6c28a26SJan Kara 	mpd->next_page = index;
2380d0ab8368SJan Kara 	if (ext4_should_journal_data(mpd->inode)) {
23813f079114SJan Kara 		handle = ext4_journal_start(mpd->inode, EXT4_HT_WRITE_PAGE,
23823f079114SJan Kara 					    bpp);
23833f079114SJan Kara 		if (IS_ERR(handle))
23843f079114SJan Kara 			return PTR_ERR(handle);
23853f079114SJan Kara 	}
238650ead253SVishal Moola (Oracle) 	folio_batch_init(&fbatch);
23874f01b02cSTheodore Ts'o 	while (index <= end) {
238850ead253SVishal Moola (Oracle) 		nr_folios = filemap_get_folios_tag(mapping, &index, end,
238950ead253SVishal Moola (Oracle) 				tag, &fbatch);
239050ead253SVishal Moola (Oracle) 		if (nr_folios == 0)
23916b8ed620SJan Kara 			break;
23928e48dcfbSTheodore Ts'o 
239350ead253SVishal Moola (Oracle) 		for (i = 0; i < nr_folios; i++) {
239450ead253SVishal Moola (Oracle) 			struct folio *folio = fbatch.folios[i];
23958e48dcfbSTheodore Ts'o 
23968e48dcfbSTheodore Ts'o 			/*
2397aeac589aSMing Lei 			 * Accumulated enough dirty pages? This doesn't apply
2398aeac589aSMing Lei 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2399aeac589aSMing Lei 			 * keep going because someone may be concurrently
2400aeac589aSMing Lei 			 * dirtying pages, and we might have synced a lot of
2401aeac589aSMing Lei 			 * newly appeared dirty pages, but have not synced all
2402aeac589aSMing Lei 			 * of the old dirty pages.
2403aeac589aSMing Lei 			 */
2404c8e8e16dSJan Kara 			if (mpd->wbc->sync_mode == WB_SYNC_NONE &&
2405c8e8e16dSJan Kara 			    mpd->wbc->nr_to_write <=
2406c8e8e16dSJan Kara 			    mpd->map.m_len >> (PAGE_SHIFT - blkbits))
2407aeac589aSMing Lei 				goto out;
2408aeac589aSMing Lei 
24094e7ea81dSJan Kara 			/* If we can't merge this page, we are done. */
241050ead253SVishal Moola (Oracle) 			if (mpd->map.m_len > 0 && mpd->next_page != folio->index)
24114e7ea81dSJan Kara 				goto out;
241278aaced3STheodore Ts'o 
24133f079114SJan Kara 			if (handle) {
24143f079114SJan Kara 				err = ext4_journal_ensure_credits(handle, bpp,
24153f079114SJan Kara 								  0);
24163f079114SJan Kara 				if (err < 0)
24173f079114SJan Kara 					goto out;
24183f079114SJan Kara 			}
24193f079114SJan Kara 
242050ead253SVishal Moola (Oracle) 			folio_lock(folio);
24218e48dcfbSTheodore Ts'o 			/*
24224e7ea81dSJan Kara 			 * If the page is no longer dirty, or its mapping no
24234e7ea81dSJan Kara 			 * longer corresponds to inode we are writing (which
24244e7ea81dSJan Kara 			 * means it has been truncated or invalidated), or the
24254e7ea81dSJan Kara 			 * page is already under writeback and we are not doing
24264e7ea81dSJan Kara 			 * a data integrity writeback, skip the page
24278e48dcfbSTheodore Ts'o 			 */
242850ead253SVishal Moola (Oracle) 			if (!folio_test_dirty(folio) ||
242950ead253SVishal Moola (Oracle) 			    (folio_test_writeback(folio) &&
24304e7ea81dSJan Kara 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
243150ead253SVishal Moola (Oracle) 			    unlikely(folio->mapping != mapping)) {
243250ead253SVishal Moola (Oracle) 				folio_unlock(folio);
24338e48dcfbSTheodore Ts'o 				continue;
24348e48dcfbSTheodore Ts'o 			}
24358e48dcfbSTheodore Ts'o 
243650ead253SVishal Moola (Oracle) 			folio_wait_writeback(folio);
243750ead253SVishal Moola (Oracle) 			BUG_ON(folio_test_writeback(folio));
24388e48dcfbSTheodore Ts'o 
2439cc509574STheodore Ts'o 			/*
2440cc509574STheodore Ts'o 			 * Should never happen but for buggy code in
2441cc509574STheodore Ts'o 			 * other subsystems that call
2442cc509574STheodore Ts'o 			 * set_page_dirty() without properly warning
2443cc509574STheodore Ts'o 			 * the file system first.  See [1] for more
2444cc509574STheodore Ts'o 			 * information.
2445cc509574STheodore Ts'o 			 *
2446cc509574STheodore Ts'o 			 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2447cc509574STheodore Ts'o 			 */
244850ead253SVishal Moola (Oracle) 			if (!folio_buffers(folio)) {
244950ead253SVishal Moola (Oracle) 				ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", folio->index);
245050ead253SVishal Moola (Oracle) 				folio_clear_dirty(folio);
245150ead253SVishal Moola (Oracle) 				folio_unlock(folio);
2452cc509574STheodore Ts'o 				continue;
2453cc509574STheodore Ts'o 			}
2454cc509574STheodore Ts'o 
24554e7ea81dSJan Kara 			if (mpd->map.m_len == 0)
245650ead253SVishal Moola (Oracle) 				mpd->first_page = folio->index;
245750ead253SVishal Moola (Oracle) 			mpd->next_page = folio->index + folio_nr_pages(folio);
2458de0039f6SJan Kara 			/*
24593f079114SJan Kara 			 * Writeout when we cannot modify metadata is simple.
24603f079114SJan Kara 			 * Just submit the page. For data=journal mode we
24613f079114SJan Kara 			 * first handle writeout of the page for checkpoint and
24623f079114SJan Kara 			 * only after that handle delayed page dirtying. This
2463ab382539SJan Kara 			 * makes sure current data is checkpointed to the final
2464ab382539SJan Kara 			 * location before possibly journalling it again which
2465ab382539SJan Kara 			 * is desirable when the page is frequently dirtied
2466ab382539SJan Kara 			 * through a pin.
2467de0039f6SJan Kara 			 */
2468de0039f6SJan Kara 			if (!mpd->can_map) {
246981a0d3e1SMatthew Wilcox 				err = mpage_submit_folio(mpd, folio);
2470de0039f6SJan Kara 				if (err < 0)
2471de0039f6SJan Kara 					goto out;
24723f079114SJan Kara 				/* Pending dirtying of journalled data? */
247381a0d3e1SMatthew Wilcox 				if (folio_test_checked(folio)) {
24743f079114SJan Kara 					err = mpage_journal_page_buffers(handle,
247580be8c5cSRitesh Harjani 						mpd, folio);
24763f079114SJan Kara 					if (err < 0)
24773f079114SJan Kara 						goto out;
24781f1a55f0SJan Kara 					mpd->journalled_more_data = 1;
24793f079114SJan Kara 				}
248033483b3bSMatthew Wilcox 				mpage_folio_done(mpd, folio);
2481de0039f6SJan Kara 			} else {
2482f8bec370SJan Kara 				/* Add all dirty buffers to mpd */
248350ead253SVishal Moola (Oracle) 				lblk = ((ext4_lblk_t)folio->index) <<
248409cbfeafSKirill A. Shutemov 					(PAGE_SHIFT - blkbits);
248550ead253SVishal Moola (Oracle) 				head = folio_buffers(folio);
2486de0039f6SJan Kara 				err = mpage_process_page_bufs(mpd, head, head,
2487de0039f6SJan Kara 						lblk);
24885f1132b2SJan Kara 				if (err <= 0)
24894e7ea81dSJan Kara 					goto out;
24905f1132b2SJan Kara 				err = 0;
2491de0039f6SJan Kara 			}
24928e48dcfbSTheodore Ts'o 		}
249350ead253SVishal Moola (Oracle) 		folio_batch_release(&fbatch);
24948e48dcfbSTheodore Ts'o 		cond_resched();
24958e48dcfbSTheodore Ts'o 	}
24966b8ed620SJan Kara 	mpd->scanned_until_end = 1;
24973f079114SJan Kara 	if (handle)
24983f079114SJan Kara 		ext4_journal_stop(handle);
24994f01b02cSTheodore Ts'o 	return 0;
25008eb9e5ceSTheodore Ts'o out:
250150ead253SVishal Moola (Oracle) 	folio_batch_release(&fbatch);
25023f079114SJan Kara 	if (handle)
25033f079114SJan Kara 		ext4_journal_stop(handle);
25044e7ea81dSJan Kara 	return err;
25058e48dcfbSTheodore Ts'o }
25068e48dcfbSTheodore Ts'o 
250715648d59SJan Kara static int ext4_do_writepages(struct mpage_da_data *mpd)
250864769240SAlex Tomas {
250915648d59SJan Kara 	struct writeback_control *wbc = mpd->wbc;
25104e7ea81dSJan Kara 	pgoff_t	writeback_index = 0;
25114e7ea81dSJan Kara 	long nr_to_write = wbc->nr_to_write;
251222208dedSAneesh Kumar K.V 	int range_whole = 0;
25134e7ea81dSJan Kara 	int cycled = 1;
251461628a3fSMingming Cao 	handle_t *handle = NULL;
251515648d59SJan Kara 	struct inode *inode = mpd->inode;
251615648d59SJan Kara 	struct address_space *mapping = inode->i_mapping;
25176b523df4SJan Kara 	int needed_blocks, rsv_blocks = 0, ret = 0;
25185e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
25191bce63d1SShaohua Li 	struct blk_plug plug;
2520cb530541STheodore Ts'o 	bool give_up_on_write = false;
252161628a3fSMingming Cao 
252220970ba6STheodore Ts'o 	trace_ext4_writepages(inode, wbc);
2523ba80b101STheodore Ts'o 
252461628a3fSMingming Cao 	/*
252561628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
252661628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
252761628a3fSMingming Cao 	 * because that could violate lock ordering on umount
252861628a3fSMingming Cao 	 */
2529a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2530bbf023c7SMing Lei 		goto out_writepages;
25312a21e37eSTheodore Ts'o 
25322a21e37eSTheodore Ts'o 	/*
25332a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
25342a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
25352a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
253695257987SJan Kara 	 * fs shutdown state instead of sb->s_flag's SB_RDONLY because
25372a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
253820970ba6STheodore Ts'o 	 * read-only, and in that case, ext4_writepages should
25392a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
25402a21e37eSTheodore Ts'o 	 * the stack trace.
25412a21e37eSTheodore Ts'o 	 */
254295257987SJan Kara 	if (unlikely(ext4_forced_shutdown(mapping->host->i_sb))) {
2543bbf023c7SMing Lei 		ret = -EROFS;
2544bbf023c7SMing Lei 		goto out_writepages;
2545bbf023c7SMing Lei 	}
25462a21e37eSTheodore Ts'o 
25474e7ea81dSJan Kara 	/*
25484e7ea81dSJan Kara 	 * If we have inline data and arrive here, it means that
25494e7ea81dSJan Kara 	 * we will soon create the block for the 1st page, so
25504e7ea81dSJan Kara 	 * we'd better clear the inline data here.
25514e7ea81dSJan Kara 	 */
25524e7ea81dSJan Kara 	if (ext4_has_inline_data(inode)) {
25534e7ea81dSJan Kara 		/* Just inode will be modified... */
25544e7ea81dSJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
25554e7ea81dSJan Kara 		if (IS_ERR(handle)) {
25564e7ea81dSJan Kara 			ret = PTR_ERR(handle);
25574e7ea81dSJan Kara 			goto out_writepages;
25584e7ea81dSJan Kara 		}
25594e7ea81dSJan Kara 		BUG_ON(ext4_test_inode_state(inode,
25604e7ea81dSJan Kara 				EXT4_STATE_MAY_INLINE_DATA));
25614e7ea81dSJan Kara 		ext4_destroy_inline_data(handle, inode);
25624e7ea81dSJan Kara 		ext4_journal_stop(handle);
25634e7ea81dSJan Kara 	}
25644e7ea81dSJan Kara 
25653f079114SJan Kara 	/*
25663f079114SJan Kara 	 * data=journal mode does not do delalloc so we just need to writeout /
25671f1a55f0SJan Kara 	 * journal already mapped buffers. On the other hand we need to commit
25681f1a55f0SJan Kara 	 * transaction to make data stable. We expect all the data to be
25691f1a55f0SJan Kara 	 * already in the journal (the only exception are DMA pinned pages
25701f1a55f0SJan Kara 	 * dirtied behind our back) so we commit transaction here and run the
25711f1a55f0SJan Kara 	 * writeback loop to checkpoint them. The checkpointing is not actually
25721f1a55f0SJan Kara 	 * necessary to make data persistent *but* quite a few places (extent
25731f1a55f0SJan Kara 	 * shifting operations, fsverity, ...) depend on being able to drop
25741f1a55f0SJan Kara 	 * pagecache pages after calling filemap_write_and_wait() and for that
25751f1a55f0SJan Kara 	 * checkpointing needs to happen.
25763f079114SJan Kara 	 */
25771f1a55f0SJan Kara 	if (ext4_should_journal_data(inode)) {
25783f079114SJan Kara 		mpd->can_map = 0;
25791f1a55f0SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL)
25801f1a55f0SJan Kara 			ext4_fc_commit(sbi->s_journal,
25811f1a55f0SJan Kara 				       EXT4_I(inode)->i_datasync_tid);
25821f1a55f0SJan Kara 	}
25831f1a55f0SJan Kara 	mpd->journalled_more_data = 0;
25843f079114SJan Kara 
25854e343231Syangerkun 	if (ext4_should_dioread_nolock(inode)) {
25864e343231Syangerkun 		/*
25874e343231Syangerkun 		 * We may need to convert up to one extent per block in
25884e343231Syangerkun 		 * the page and we may dirty the inode.
25894e343231Syangerkun 		 */
25904e343231Syangerkun 		rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
25914e343231Syangerkun 						PAGE_SIZE >> inode->i_blkbits);
25924e343231Syangerkun 	}
25934e343231Syangerkun 
259422208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
259522208dedSAneesh Kumar K.V 		range_whole = 1;
259661628a3fSMingming Cao 
25972acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
25984e7ea81dSJan Kara 		writeback_index = mapping->writeback_index;
25994e7ea81dSJan Kara 		if (writeback_index)
26002acf2c26SAneesh Kumar K.V 			cycled = 0;
260115648d59SJan Kara 		mpd->first_page = writeback_index;
260215648d59SJan Kara 		mpd->last_page = -1;
26035b41d924SEric Sandeen 	} else {
260415648d59SJan Kara 		mpd->first_page = wbc->range_start >> PAGE_SHIFT;
260515648d59SJan Kara 		mpd->last_page = wbc->range_end >> PAGE_SHIFT;
26065b41d924SEric Sandeen 	}
2607a1d6cc56SAneesh Kumar K.V 
260815648d59SJan Kara 	ext4_io_submit_init(&mpd->io_submit, wbc);
26092acf2c26SAneesh Kumar K.V retry:
26106e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
261115648d59SJan Kara 		tag_pages_for_writeback(mapping, mpd->first_page,
261215648d59SJan Kara 					mpd->last_page);
26131bce63d1SShaohua Li 	blk_start_plug(&plug);
2614dddbd6acSJan Kara 
2615dddbd6acSJan Kara 	/*
2616dddbd6acSJan Kara 	 * First writeback pages that don't need mapping - we can avoid
2617dddbd6acSJan Kara 	 * starting a transaction unnecessarily and also avoid being blocked
2618dddbd6acSJan Kara 	 * in the block layer on device congestion while having transaction
2619dddbd6acSJan Kara 	 * started.
2620dddbd6acSJan Kara 	 */
262115648d59SJan Kara 	mpd->do_map = 0;
262215648d59SJan Kara 	mpd->scanned_until_end = 0;
262315648d59SJan Kara 	mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
262415648d59SJan Kara 	if (!mpd->io_submit.io_end) {
2625dddbd6acSJan Kara 		ret = -ENOMEM;
2626dddbd6acSJan Kara 		goto unplug;
2627dddbd6acSJan Kara 	}
262815648d59SJan Kara 	ret = mpage_prepare_extent_to_map(mpd);
2629a297b2fcSXiaoguang Wang 	/* Unlock pages we didn't use */
263015648d59SJan Kara 	mpage_release_unused_pages(mpd, false);
2631dddbd6acSJan Kara 	/* Submit prepared bio */
263215648d59SJan Kara 	ext4_io_submit(&mpd->io_submit);
263315648d59SJan Kara 	ext4_put_io_end_defer(mpd->io_submit.io_end);
263415648d59SJan Kara 	mpd->io_submit.io_end = NULL;
2635dddbd6acSJan Kara 	if (ret < 0)
2636dddbd6acSJan Kara 		goto unplug;
2637dddbd6acSJan Kara 
263815648d59SJan Kara 	while (!mpd->scanned_until_end && wbc->nr_to_write > 0) {
26394e7ea81dSJan Kara 		/* For each extent of pages we use new io_end */
264015648d59SJan Kara 		mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
264115648d59SJan Kara 		if (!mpd->io_submit.io_end) {
26424e7ea81dSJan Kara 			ret = -ENOMEM;
26434e7ea81dSJan Kara 			break;
26444e7ea81dSJan Kara 		}
2645a1d6cc56SAneesh Kumar K.V 
2646de0039f6SJan Kara 		WARN_ON_ONCE(!mpd->can_map);
2647a1d6cc56SAneesh Kumar K.V 		/*
26484e7ea81dSJan Kara 		 * We have two constraints: We find one extent to map and we
26494e7ea81dSJan Kara 		 * must always write out whole page (makes a difference when
26504e7ea81dSJan Kara 		 * blocksize < pagesize) so that we don't block on IO when we
26514e7ea81dSJan Kara 		 * try to write out the rest of the page. Journalled mode is
26524e7ea81dSJan Kara 		 * not supported by delalloc.
2653a1d6cc56SAneesh Kumar K.V 		 */
2654a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
2655525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2656a1d6cc56SAneesh Kumar K.V 
265761628a3fSMingming Cao 		/* start a new transaction */
26586b523df4SJan Kara 		handle = ext4_journal_start_with_reserve(inode,
26596b523df4SJan Kara 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
266061628a3fSMingming Cao 		if (IS_ERR(handle)) {
266161628a3fSMingming Cao 			ret = PTR_ERR(handle);
26621693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2663fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
2664a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
26654e7ea81dSJan Kara 			/* Release allocated io_end */
266615648d59SJan Kara 			ext4_put_io_end(mpd->io_submit.io_end);
266715648d59SJan Kara 			mpd->io_submit.io_end = NULL;
26684e7ea81dSJan Kara 			break;
266961628a3fSMingming Cao 		}
267015648d59SJan Kara 		mpd->do_map = 1;
2671f63e6005STheodore Ts'o 
267215648d59SJan Kara 		trace_ext4_da_write_pages(inode, mpd->first_page, wbc);
267315648d59SJan Kara 		ret = mpage_prepare_extent_to_map(mpd);
267415648d59SJan Kara 		if (!ret && mpd->map.m_len)
267515648d59SJan Kara 			ret = mpage_map_and_submit_extent(handle, mpd,
2676cb530541STheodore Ts'o 					&give_up_on_write);
2677646caa9cSJan Kara 		/*
2678646caa9cSJan Kara 		 * Caution: If the handle is synchronous,
2679646caa9cSJan Kara 		 * ext4_journal_stop() can wait for transaction commit
2680646caa9cSJan Kara 		 * to finish which may depend on writeback of pages to
2681646caa9cSJan Kara 		 * complete or on page lock to be released.  In that
2682b483bb77SRandy Dunlap 		 * case, we have to wait until after we have
2683646caa9cSJan Kara 		 * submitted all the IO, released page locks we hold,
2684646caa9cSJan Kara 		 * and dropped io_end reference (for extent conversion
2685646caa9cSJan Kara 		 * to be able to complete) before stopping the handle.
2686646caa9cSJan Kara 		 */
2687646caa9cSJan Kara 		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
268861628a3fSMingming Cao 			ext4_journal_stop(handle);
2689646caa9cSJan Kara 			handle = NULL;
269015648d59SJan Kara 			mpd->do_map = 0;
2691646caa9cSJan Kara 		}
26924e7ea81dSJan Kara 		/* Unlock pages we didn't use */
269315648d59SJan Kara 		mpage_release_unused_pages(mpd, give_up_on_write);
2694a297b2fcSXiaoguang Wang 		/* Submit prepared bio */
269515648d59SJan Kara 		ext4_io_submit(&mpd->io_submit);
2696a297b2fcSXiaoguang Wang 
2697646caa9cSJan Kara 		/*
2698646caa9cSJan Kara 		 * Drop our io_end reference we got from init. We have
2699646caa9cSJan Kara 		 * to be careful and use deferred io_end finishing if
2700646caa9cSJan Kara 		 * we are still holding the transaction as we can
2701646caa9cSJan Kara 		 * release the last reference to io_end which may end
2702646caa9cSJan Kara 		 * up doing unwritten extent conversion.
2703646caa9cSJan Kara 		 */
2704646caa9cSJan Kara 		if (handle) {
270515648d59SJan Kara 			ext4_put_io_end_defer(mpd->io_submit.io_end);
2706646caa9cSJan Kara 			ext4_journal_stop(handle);
2707646caa9cSJan Kara 		} else
270815648d59SJan Kara 			ext4_put_io_end(mpd->io_submit.io_end);
270915648d59SJan Kara 		mpd->io_submit.io_end = NULL;
2710df22291fSAneesh Kumar K.V 
27114e7ea81dSJan Kara 		if (ret == -ENOSPC && sbi->s_journal) {
27124e7ea81dSJan Kara 			/*
27134e7ea81dSJan Kara 			 * Commit the transaction which would
271422208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
271522208dedSAneesh Kumar K.V 			 * and try again
271622208dedSAneesh Kumar K.V 			 */
2717df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
271822208dedSAneesh Kumar K.V 			ret = 0;
27194e7ea81dSJan Kara 			continue;
27204e7ea81dSJan Kara 		}
27214e7ea81dSJan Kara 		/* Fatal error - ENOMEM, EIO... */
27224e7ea81dSJan Kara 		if (ret)
272361628a3fSMingming Cao 			break;
272461628a3fSMingming Cao 	}
2725dddbd6acSJan Kara unplug:
27261bce63d1SShaohua Li 	blk_finish_plug(&plug);
27279c12a831SJan Kara 	if (!ret && !cycled && wbc->nr_to_write > 0) {
27282acf2c26SAneesh Kumar K.V 		cycled = 1;
272915648d59SJan Kara 		mpd->last_page = writeback_index - 1;
273015648d59SJan Kara 		mpd->first_page = 0;
27312acf2c26SAneesh Kumar K.V 		goto retry;
27322acf2c26SAneesh Kumar K.V 	}
273361628a3fSMingming Cao 
273422208dedSAneesh Kumar K.V 	/* Update index */
273522208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
273622208dedSAneesh Kumar K.V 		/*
27374e7ea81dSJan Kara 		 * Set the writeback_index so that range_cyclic
273822208dedSAneesh Kumar K.V 		 * mode will write it back later
273922208dedSAneesh Kumar K.V 		 */
274015648d59SJan Kara 		mapping->writeback_index = mpd->first_page;
2741a1d6cc56SAneesh Kumar K.V 
274261628a3fSMingming Cao out_writepages:
274320970ba6STheodore Ts'o 	trace_ext4_writepages_result(inode, wbc, ret,
27444e7ea81dSJan Kara 				     nr_to_write - wbc->nr_to_write);
274561628a3fSMingming Cao 	return ret;
274664769240SAlex Tomas }
274764769240SAlex Tomas 
274815648d59SJan Kara static int ext4_writepages(struct address_space *mapping,
274915648d59SJan Kara 			   struct writeback_control *wbc)
275015648d59SJan Kara {
275129bc9ceaSJan Kara 	struct super_block *sb = mapping->host->i_sb;
275215648d59SJan Kara 	struct mpage_da_data mpd = {
275315648d59SJan Kara 		.inode = mapping->host,
275415648d59SJan Kara 		.wbc = wbc,
275515648d59SJan Kara 		.can_map = 1,
275615648d59SJan Kara 	};
275729bc9ceaSJan Kara 	int ret;
275800d873c1SJan Kara 	int alloc_ctx;
275915648d59SJan Kara 
2760eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(sb)))
276129bc9ceaSJan Kara 		return -EIO;
276229bc9ceaSJan Kara 
276300d873c1SJan Kara 	alloc_ctx = ext4_writepages_down_read(sb);
276429bc9ceaSJan Kara 	ret = ext4_do_writepages(&mpd);
27651f1a55f0SJan Kara 	/*
27661f1a55f0SJan Kara 	 * For data=journal writeback we could have come across pages marked
27671f1a55f0SJan Kara 	 * for delayed dirtying (PageChecked) which were just added to the
27681f1a55f0SJan Kara 	 * running transaction. Try once more to get them to stable storage.
27691f1a55f0SJan Kara 	 */
27701f1a55f0SJan Kara 	if (!ret && mpd.journalled_more_data)
27711f1a55f0SJan Kara 		ret = ext4_do_writepages(&mpd);
277200d873c1SJan Kara 	ext4_writepages_up_read(sb, alloc_ctx);
277329bc9ceaSJan Kara 
277429bc9ceaSJan Kara 	return ret;
277515648d59SJan Kara }
277615648d59SJan Kara 
277759205c8dSJan Kara int ext4_normal_submit_inode_data_buffers(struct jbd2_inode *jinode)
277859205c8dSJan Kara {
277959205c8dSJan Kara 	struct writeback_control wbc = {
278059205c8dSJan Kara 		.sync_mode = WB_SYNC_ALL,
278159205c8dSJan Kara 		.nr_to_write = LONG_MAX,
278259205c8dSJan Kara 		.range_start = jinode->i_dirty_start,
278359205c8dSJan Kara 		.range_end = jinode->i_dirty_end,
278459205c8dSJan Kara 	};
278559205c8dSJan Kara 	struct mpage_da_data mpd = {
278659205c8dSJan Kara 		.inode = jinode->i_vfs_inode,
278759205c8dSJan Kara 		.wbc = &wbc,
278859205c8dSJan Kara 		.can_map = 0,
278959205c8dSJan Kara 	};
279059205c8dSJan Kara 	return ext4_do_writepages(&mpd);
279159205c8dSJan Kara }
279259205c8dSJan Kara 
27935f0663bbSDan Williams static int ext4_dax_writepages(struct address_space *mapping,
27945f0663bbSDan Williams 			       struct writeback_control *wbc)
27955f0663bbSDan Williams {
27965f0663bbSDan Williams 	int ret;
27975f0663bbSDan Williams 	long nr_to_write = wbc->nr_to_write;
27985f0663bbSDan Williams 	struct inode *inode = mapping->host;
279900d873c1SJan Kara 	int alloc_ctx;
28005f0663bbSDan Williams 
2801eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
28025f0663bbSDan Williams 		return -EIO;
28035f0663bbSDan Williams 
280400d873c1SJan Kara 	alloc_ctx = ext4_writepages_down_read(inode->i_sb);
28055f0663bbSDan Williams 	trace_ext4_writepages(inode, wbc);
28065f0663bbSDan Williams 
2807eb8ab444SJan Kara 	ret = dax_writeback_mapping_range(mapping,
2808eb8ab444SJan Kara 					  EXT4_SB(inode->i_sb)->s_daxdev, wbc);
28095f0663bbSDan Williams 	trace_ext4_writepages_result(inode, wbc, ret,
28105f0663bbSDan Williams 				     nr_to_write - wbc->nr_to_write);
281100d873c1SJan Kara 	ext4_writepages_up_read(inode->i_sb, alloc_ctx);
28125f0663bbSDan Williams 	return ret;
28135f0663bbSDan Williams }
28145f0663bbSDan Williams 
281579f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
281679f0be8dSAneesh Kumar K.V {
28175c1ff336SEric Whitney 	s64 free_clusters, dirty_clusters;
281879f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
281979f0be8dSAneesh Kumar K.V 
282079f0be8dSAneesh Kumar K.V 	/*
282179f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
282279f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
2823179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
282479f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
282579f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
282679f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
282779f0be8dSAneesh Kumar K.V 	 */
28285c1ff336SEric Whitney 	free_clusters =
28295c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
28305c1ff336SEric Whitney 	dirty_clusters =
28315c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
283200d4e736STheodore Ts'o 	/*
283300d4e736STheodore Ts'o 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
283400d4e736STheodore Ts'o 	 */
28355c1ff336SEric Whitney 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
283610ee27a0SMiao Xie 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
283700d4e736STheodore Ts'o 
28385c1ff336SEric Whitney 	if (2 * free_clusters < 3 * dirty_clusters ||
28395c1ff336SEric Whitney 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
284079f0be8dSAneesh Kumar K.V 		/*
2841c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
2842c8afb446SEric Sandeen 		 * or free blocks is less than watermark
284379f0be8dSAneesh Kumar K.V 		 */
284479f0be8dSAneesh Kumar K.V 		return 1;
284579f0be8dSAneesh Kumar K.V 	}
284679f0be8dSAneesh Kumar K.V 	return 0;
284779f0be8dSAneesh Kumar K.V }
284879f0be8dSAneesh Kumar K.V 
284964769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
28509d6b0cd7SMatthew Wilcox (Oracle) 			       loff_t pos, unsigned len,
285164769240SAlex Tomas 			       struct page **pagep, void **fsdata)
285264769240SAlex Tomas {
285372b8ab9dSEric Sandeen 	int ret, retries = 0;
28540b5a2543SMatthew Wilcox 	struct folio *folio;
285564769240SAlex Tomas 	pgoff_t index;
285664769240SAlex Tomas 	struct inode *inode = mapping->host;
285764769240SAlex Tomas 
2858eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
28590db1ff22STheodore Ts'o 		return -EIO;
28600db1ff22STheodore Ts'o 
286109cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
286279f0be8dSAneesh Kumar K.V 
28636493792dSZhang Yi 	if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
286479f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
286579f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
28669d6b0cd7SMatthew Wilcox (Oracle) 					len, pagep, fsdata);
286779f0be8dSAneesh Kumar K.V 	}
286879f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
28699d6b0cd7SMatthew Wilcox (Oracle) 	trace_ext4_da_write_begin(inode, pos, len);
28709c3569b5STao Ma 
28719c3569b5STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
287236d116e9SMatthew Wilcox (Oracle) 		ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len,
28739c3569b5STao Ma 						      pagep, fsdata);
28749c3569b5STao Ma 		if (ret < 0)
287547564bfbSTheodore Ts'o 			return ret;
287647564bfbSTheodore Ts'o 		if (ret == 1)
287747564bfbSTheodore Ts'o 			return 0;
28789c3569b5STao Ma 	}
28799c3569b5STao Ma 
2880cc883236SZhang Yi retry:
28810b5a2543SMatthew Wilcox 	folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
28820b5a2543SMatthew Wilcox 			mapping_gfp_mask(mapping));
28837fa8a8eeSLinus Torvalds 	if (IS_ERR(folio))
28847fa8a8eeSLinus Torvalds 		return PTR_ERR(folio);
288547564bfbSTheodore Ts'o 
28860b5a2543SMatthew Wilcox 	/* In case writeback began while the folio was unlocked */
28870b5a2543SMatthew Wilcox 	folio_wait_stable(folio);
288864769240SAlex Tomas 
2889643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
289086b38c27SMatthew Wilcox 	ret = ext4_block_write_begin(folio, pos, len, ext4_da_get_block_prep);
28912058f83aSMichael Halcrow #else
28920b5a2543SMatthew Wilcox 	ret = __block_write_begin(&folio->page, pos, len, ext4_da_get_block_prep);
28932058f83aSMichael Halcrow #endif
289464769240SAlex Tomas 	if (ret < 0) {
28950b5a2543SMatthew Wilcox 		folio_unlock(folio);
28960b5a2543SMatthew Wilcox 		folio_put(folio);
2897ae4d5372SAneesh Kumar K.V 		/*
2898ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
2899ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
2900cc883236SZhang Yi 		 * i_size_read because we hold inode lock.
2901ae4d5372SAneesh Kumar K.V 		 */
2902ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
2903b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
290447564bfbSTheodore Ts'o 
290547564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
290647564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
2907cc883236SZhang Yi 			goto retry;
290847564bfbSTheodore Ts'o 		return ret;
290964769240SAlex Tomas 	}
291064769240SAlex Tomas 
29110b5a2543SMatthew Wilcox 	*pagep = &folio->page;
291264769240SAlex Tomas 	return ret;
291364769240SAlex Tomas }
291464769240SAlex Tomas 
2915632eaeabSMingming Cao /*
2916632eaeabSMingming Cao  * Check if we should update i_disksize
2917632eaeabSMingming Cao  * when write to the end of file but not require block allocation
2918632eaeabSMingming Cao  */
2919d19500daSRitesh Harjani static int ext4_da_should_update_i_disksize(struct folio *folio,
2920632eaeabSMingming Cao 					    unsigned long offset)
2921632eaeabSMingming Cao {
2922632eaeabSMingming Cao 	struct buffer_head *bh;
2923d19500daSRitesh Harjani 	struct inode *inode = folio->mapping->host;
2924632eaeabSMingming Cao 	unsigned int idx;
2925632eaeabSMingming Cao 	int i;
2926632eaeabSMingming Cao 
2927d19500daSRitesh Harjani 	bh = folio_buffers(folio);
2928632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
2929632eaeabSMingming Cao 
2930632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
2931632eaeabSMingming Cao 		bh = bh->b_this_page;
2932632eaeabSMingming Cao 
293329fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2934632eaeabSMingming Cao 		return 0;
2935632eaeabSMingming Cao 	return 1;
2936632eaeabSMingming Cao }
2937632eaeabSMingming Cao 
293803de20beSLiu Song static int ext4_da_do_write_end(struct address_space *mapping,
293903de20beSLiu Song 			loff_t pos, unsigned len, unsigned copied,
294003de20beSLiu Song 			struct page *page)
294103de20beSLiu Song {
294203de20beSLiu Song 	struct inode *inode = mapping->host;
294303de20beSLiu Song 	loff_t old_size = inode->i_size;
294403de20beSLiu Song 	bool disksize_changed = false;
294503de20beSLiu Song 	loff_t new_i_size;
294603de20beSLiu Song 
294703de20beSLiu Song 	/*
294803de20beSLiu Song 	 * block_write_end() will mark the inode as dirty with I_DIRTY_PAGES
294903de20beSLiu Song 	 * flag, which all that's needed to trigger page writeback.
295003de20beSLiu Song 	 */
295103de20beSLiu Song 	copied = block_write_end(NULL, mapping, pos, len, copied, page, NULL);
295203de20beSLiu Song 	new_i_size = pos + copied;
295303de20beSLiu Song 
295403de20beSLiu Song 	/*
295503de20beSLiu Song 	 * It's important to update i_size while still holding page lock,
295603de20beSLiu Song 	 * because page writeout could otherwise come in and zero beyond
295703de20beSLiu Song 	 * i_size.
295803de20beSLiu Song 	 *
295903de20beSLiu Song 	 * Since we are holding inode lock, we are sure i_disksize <=
296003de20beSLiu Song 	 * i_size. We also know that if i_disksize < i_size, there are
296103de20beSLiu Song 	 * delalloc writes pending in the range up to i_size. If the end of
296203de20beSLiu Song 	 * the current write is <= i_size, there's no need to touch
296303de20beSLiu Song 	 * i_disksize since writeback will push i_disksize up to i_size
296403de20beSLiu Song 	 * eventually. If the end of the current write is > i_size and
296503de20beSLiu Song 	 * inside an allocated block which ext4_da_should_update_i_disksize()
296603de20beSLiu Song 	 * checked, we need to update i_disksize here as certain
296703de20beSLiu Song 	 * ext4_writepages() paths not allocating blocks and update i_disksize.
296803de20beSLiu Song 	 */
296903de20beSLiu Song 	if (new_i_size > inode->i_size) {
297003de20beSLiu Song 		unsigned long end;
297103de20beSLiu Song 
297203de20beSLiu Song 		i_size_write(inode, new_i_size);
297303de20beSLiu Song 		end = (new_i_size - 1) & (PAGE_SIZE - 1);
297403de20beSLiu Song 		if (copied && ext4_da_should_update_i_disksize(page_folio(page), end)) {
297503de20beSLiu Song 			ext4_update_i_disksize(inode, new_i_size);
297603de20beSLiu Song 			disksize_changed = true;
297703de20beSLiu Song 		}
297803de20beSLiu Song 	}
297903de20beSLiu Song 
298003de20beSLiu Song 	unlock_page(page);
298103de20beSLiu Song 	put_page(page);
298203de20beSLiu Song 
298303de20beSLiu Song 	if (old_size < pos)
298403de20beSLiu Song 		pagecache_isize_extended(inode, old_size, pos);
298503de20beSLiu Song 
298603de20beSLiu Song 	if (disksize_changed) {
298703de20beSLiu Song 		handle_t *handle;
298803de20beSLiu Song 
298903de20beSLiu Song 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
299003de20beSLiu Song 		if (IS_ERR(handle))
299103de20beSLiu Song 			return PTR_ERR(handle);
299203de20beSLiu Song 		ext4_mark_inode_dirty(handle, inode);
299303de20beSLiu Song 		ext4_journal_stop(handle);
299403de20beSLiu Song 	}
299503de20beSLiu Song 
299603de20beSLiu Song 	return copied;
299703de20beSLiu Song }
299803de20beSLiu Song 
299964769240SAlex Tomas static int ext4_da_write_end(struct file *file,
300064769240SAlex Tomas 			     struct address_space *mapping,
300164769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
300264769240SAlex Tomas 			     struct page *page, void *fsdata)
300364769240SAlex Tomas {
300464769240SAlex Tomas 	struct inode *inode = mapping->host;
300579f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
3006d19500daSRitesh Harjani 	struct folio *folio = page_folio(page);
300779f0be8dSAneesh Kumar K.V 
300874d553aaSTheodore Ts'o 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
300974d553aaSTheodore Ts'o 		return ext4_write_end(file, mapping, pos,
3010d19500daSRitesh Harjani 				      len, copied, &folio->page, fsdata);
3011632eaeabSMingming Cao 
30129bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
30139c3569b5STao Ma 
30149c3569b5STao Ma 	if (write_mode != CONVERT_INLINE_DATA &&
30159c3569b5STao Ma 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
30169c3569b5STao Ma 	    ext4_has_inline_data(inode))
3017d19500daSRitesh Harjani 		return ext4_write_inline_data_end(inode, pos, len, copied,
3018d19500daSRitesh Harjani 						  folio);
30199c3569b5STao Ma 
30201dedde69SZhihao Cheng 	if (unlikely(copied < len) && !PageUptodate(page))
30211dedde69SZhihao Cheng 		copied = 0;
30221dedde69SZhihao Cheng 
302303de20beSLiu Song 	return ext4_da_do_write_end(mapping, pos, len, copied, &folio->page);
302464769240SAlex Tomas }
302564769240SAlex Tomas 
3026ccd2506bSTheodore Ts'o /*
3027ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
3028ccd2506bSTheodore Ts'o  */
3029ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
3030ccd2506bSTheodore Ts'o {
3031fb40ba0dSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
3032fb40ba0dSTheodore Ts'o 
303371d4f7d0STheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks)
3034ccd2506bSTheodore Ts'o 		return 0;
3035ccd2506bSTheodore Ts'o 
3036ccd2506bSTheodore Ts'o 	/*
3037ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
3038ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
3039ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
3040ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
3041ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
3042ccd2506bSTheodore Ts'o 	 *
304320970ba6STheodore Ts'o 	 * ext4_writepages() ->
3044ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
3045ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
3046ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
3047ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
3048ccd2506bSTheodore Ts'o 	 *
3049ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
3050ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
3051ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
3052ccd2506bSTheodore Ts'o 	 * doing I/O at all.
3053ccd2506bSTheodore Ts'o 	 *
3054ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
3055380cf090SWu Fengguang 	 * the pages by calling redirty_page_for_writepage() but that
3056ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
3057ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
305825985edcSLucas De Marchi 	 * simplifying them because we wouldn't actually intend to
3059ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
3060ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
3061ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
3062ccd2506bSTheodore Ts'o 	 *
3063ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
3064ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
3065ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
3066ccd2506bSTheodore Ts'o 	 */
3067ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
3068ccd2506bSTheodore Ts'o }
306964769240SAlex Tomas 
307064769240SAlex Tomas /*
3071ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
3072ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
3073ac27a0ecSDave Kleikamp  *
3074ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
3075617ba13bSMingming Cao  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3076ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
3077ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
3078ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
3079ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
3080ac27a0ecSDave Kleikamp  *
3081ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
3082ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
3083ac27a0ecSDave Kleikamp  */
3084617ba13bSMingming Cao static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3085ac27a0ecSDave Kleikamp {
3086ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
308751ae846cSYe Bin 	sector_t ret = 0;
3088ac27a0ecSDave Kleikamp 
308951ae846cSYe Bin 	inode_lock_shared(inode);
309046c7f254STao Ma 	/*
309146c7f254STao Ma 	 * We can get here for an inline file via the FIBMAP ioctl
309246c7f254STao Ma 	 */
309346c7f254STao Ma 	if (ext4_has_inline_data(inode))
309451ae846cSYe Bin 		goto out;
309546c7f254STao Ma 
309664769240SAlex Tomas 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3097951cafa6SJan Kara 	    (test_opt(inode->i_sb, DELALLOC) ||
3098951cafa6SJan Kara 	     ext4_should_journal_data(inode))) {
309964769240SAlex Tomas 		/*
3100951cafa6SJan Kara 		 * With delalloc or journalled data we want to sync the file so
3101951cafa6SJan Kara 		 * that we can make sure we allocate blocks for file and data
3102951cafa6SJan Kara 		 * is in place for the user to see it
310364769240SAlex Tomas 		 */
310464769240SAlex Tomas 		filemap_write_and_wait(mapping);
310564769240SAlex Tomas 	}
310664769240SAlex Tomas 
310751ae846cSYe Bin 	ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
310851ae846cSYe Bin 
310951ae846cSYe Bin out:
311051ae846cSYe Bin 	inode_unlock_shared(inode);
311151ae846cSYe Bin 	return ret;
3112ac27a0ecSDave Kleikamp }
3113ac27a0ecSDave Kleikamp 
3114fe5ddf6bSMatthew Wilcox (Oracle) static int ext4_read_folio(struct file *file, struct folio *folio)
3115ac27a0ecSDave Kleikamp {
311646c7f254STao Ma 	int ret = -EAGAIN;
3117c0be8e6fSMatthew Wilcox 	struct inode *inode = folio->mapping->host;
311846c7f254STao Ma 
311936c9b450SRitesh Harjani 	trace_ext4_read_folio(inode, folio);
312046c7f254STao Ma 
312146c7f254STao Ma 	if (ext4_has_inline_data(inode))
31223edde93eSMatthew Wilcox 		ret = ext4_readpage_inline(inode, folio);
312346c7f254STao Ma 
312446c7f254STao Ma 	if (ret == -EAGAIN)
3125c0be8e6fSMatthew Wilcox 		return ext4_mpage_readpages(inode, NULL, folio);
312646c7f254STao Ma 
312746c7f254STao Ma 	return ret;
3128ac27a0ecSDave Kleikamp }
3129ac27a0ecSDave Kleikamp 
31306311f91fSMatthew Wilcox (Oracle) static void ext4_readahead(struct readahead_control *rac)
3131ac27a0ecSDave Kleikamp {
31326311f91fSMatthew Wilcox (Oracle) 	struct inode *inode = rac->mapping->host;
313346c7f254STao Ma 
31346311f91fSMatthew Wilcox (Oracle) 	/* If the file has inline data, no need to do readahead. */
313546c7f254STao Ma 	if (ext4_has_inline_data(inode))
31366311f91fSMatthew Wilcox (Oracle) 		return;
313746c7f254STao Ma 
3138a07f624bSMatthew Wilcox (Oracle) 	ext4_mpage_readpages(inode, rac, NULL);
3139ac27a0ecSDave Kleikamp }
3140ac27a0ecSDave Kleikamp 
31417ba13abbSMatthew Wilcox (Oracle) static void ext4_invalidate_folio(struct folio *folio, size_t offset,
31427ba13abbSMatthew Wilcox (Oracle) 				size_t length)
3143ac27a0ecSDave Kleikamp {
3144ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_invalidate_folio(folio, offset, length);
31450562e0baSJiaying Zhang 
31464520fb3cSJan Kara 	/* No journalling happens on data buffers when this function is used */
31477ba13abbSMatthew Wilcox (Oracle) 	WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
31484520fb3cSJan Kara 
31497ba13abbSMatthew Wilcox (Oracle) 	block_invalidate_folio(folio, offset, length);
31504520fb3cSJan Kara }
31514520fb3cSJan Kara 
3152ccd16945SMatthew Wilcox (Oracle) static int __ext4_journalled_invalidate_folio(struct folio *folio,
3153ccd16945SMatthew Wilcox (Oracle) 					    size_t offset, size_t length)
31544520fb3cSJan Kara {
3155ccd16945SMatthew Wilcox (Oracle) 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
31564520fb3cSJan Kara 
3157ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_journalled_invalidate_folio(folio, offset, length);
31584520fb3cSJan Kara 
3159744692dcSJiaying Zhang 	/*
3160ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
3161ac27a0ecSDave Kleikamp 	 */
3162ccd16945SMatthew Wilcox (Oracle) 	if (offset == 0 && length == folio_size(folio))
3163ccd16945SMatthew Wilcox (Oracle) 		folio_clear_checked(folio);
3164ac27a0ecSDave Kleikamp 
3165ccd16945SMatthew Wilcox (Oracle) 	return jbd2_journal_invalidate_folio(journal, folio, offset, length);
316653e87268SJan Kara }
316753e87268SJan Kara 
316853e87268SJan Kara /* Wrapper for aops... */
3169ccd16945SMatthew Wilcox (Oracle) static void ext4_journalled_invalidate_folio(struct folio *folio,
3170ccd16945SMatthew Wilcox (Oracle) 					   size_t offset,
3171ccd16945SMatthew Wilcox (Oracle) 					   size_t length)
317253e87268SJan Kara {
3173ccd16945SMatthew Wilcox (Oracle) 	WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3174ac27a0ecSDave Kleikamp }
3175ac27a0ecSDave Kleikamp 
31763c402f15SMatthew Wilcox (Oracle) static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3177ac27a0ecSDave Kleikamp {
317836c9b450SRitesh Harjani 	struct inode *inode = folio->mapping->host;
317936c9b450SRitesh Harjani 	journal_t *journal = EXT4_JOURNAL(inode);
3180ac27a0ecSDave Kleikamp 
318136c9b450SRitesh Harjani 	trace_ext4_release_folio(inode, folio);
31820562e0baSJiaying Zhang 
3183e1c36595SJan Kara 	/* Page has dirty journalled data -> cannot release */
31843c402f15SMatthew Wilcox (Oracle) 	if (folio_test_checked(folio))
31853c402f15SMatthew Wilcox (Oracle) 		return false;
31860390131bSFrank Mayhar 	if (journal)
3187c56a6eb0SMatthew Wilcox (Oracle) 		return jbd2_journal_try_to_free_buffers(journal, folio);
31880390131bSFrank Mayhar 	else
318968189fefSMatthew Wilcox (Oracle) 		return try_to_free_buffers(folio);
3190ac27a0ecSDave Kleikamp }
3191ac27a0ecSDave Kleikamp 
3192b8a6176cSJan Kara static bool ext4_inode_datasync_dirty(struct inode *inode)
3193b8a6176cSJan Kara {
3194b8a6176cSJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3195b8a6176cSJan Kara 
3196aa75f4d3SHarshad Shirwadkar 	if (journal) {
3197aa75f4d3SHarshad Shirwadkar 		if (jbd2_transaction_committed(journal,
3198aa75f4d3SHarshad Shirwadkar 			EXT4_I(inode)->i_datasync_tid))
3199d0520df7SAndrea Righi 			return false;
3200d0520df7SAndrea Righi 		if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
32011ceecb53SHarshad Shirwadkar 			return !list_empty(&EXT4_I(inode)->i_fc_list);
3202d0520df7SAndrea Righi 		return true;
3203aa75f4d3SHarshad Shirwadkar 	}
3204aa75f4d3SHarshad Shirwadkar 
3205b8a6176cSJan Kara 	/* Any metadata buffers to write? */
3206b8a6176cSJan Kara 	if (!list_empty(&inode->i_mapping->private_list))
3207b8a6176cSJan Kara 		return true;
3208b8a6176cSJan Kara 	return inode->i_state & I_DIRTY_DATASYNC;
3209b8a6176cSJan Kara }
3210b8a6176cSJan Kara 
3211c8fdfe29SMatthew Bobrowski static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3212c8fdfe29SMatthew Bobrowski 			   struct ext4_map_blocks *map, loff_t offset,
3213de205114SChristoph Hellwig 			   loff_t length, unsigned int flags)
3214364443cbSJan Kara {
3215c8fdfe29SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3216c8fdfe29SMatthew Bobrowski 
3217c8fdfe29SMatthew Bobrowski 	/*
3218c8fdfe29SMatthew Bobrowski 	 * Writes that span EOF might trigger an I/O size update on completion,
3219c8fdfe29SMatthew Bobrowski 	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3220c8fdfe29SMatthew Bobrowski 	 * there is no other metadata changes being made or are pending.
3221c8fdfe29SMatthew Bobrowski 	 */
3222c8fdfe29SMatthew Bobrowski 	iomap->flags = 0;
3223c8fdfe29SMatthew Bobrowski 	if (ext4_inode_datasync_dirty(inode) ||
3224c8fdfe29SMatthew Bobrowski 	    offset + length > i_size_read(inode))
3225c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_DIRTY;
3226c8fdfe29SMatthew Bobrowski 
3227c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_NEW)
3228c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_NEW;
3229c8fdfe29SMatthew Bobrowski 
3230de205114SChristoph Hellwig 	if (flags & IOMAP_DAX)
3231c8fdfe29SMatthew Bobrowski 		iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3232de205114SChristoph Hellwig 	else
3233de205114SChristoph Hellwig 		iomap->bdev = inode->i_sb->s_bdev;
3234c8fdfe29SMatthew Bobrowski 	iomap->offset = (u64) map->m_lblk << blkbits;
3235c8fdfe29SMatthew Bobrowski 	iomap->length = (u64) map->m_len << blkbits;
3236c8fdfe29SMatthew Bobrowski 
32376386722aSRitesh Harjani 	if ((map->m_flags & EXT4_MAP_MAPPED) &&
32386386722aSRitesh Harjani 	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
32396386722aSRitesh Harjani 		iomap->flags |= IOMAP_F_MERGED;
32406386722aSRitesh Harjani 
3241c8fdfe29SMatthew Bobrowski 	/*
3242c8fdfe29SMatthew Bobrowski 	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3243c8fdfe29SMatthew Bobrowski 	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3244c8fdfe29SMatthew Bobrowski 	 * set. In order for any allocated unwritten extents to be converted
3245c8fdfe29SMatthew Bobrowski 	 * into written extents correctly within the ->end_io() handler, we
3246c8fdfe29SMatthew Bobrowski 	 * need to ensure that the iomap->type is set appropriately. Hence, the
3247c8fdfe29SMatthew Bobrowski 	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3248c8fdfe29SMatthew Bobrowski 	 * been set first.
3249c8fdfe29SMatthew Bobrowski 	 */
3250c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3251c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_UNWRITTEN;
3252c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3253de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3254de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3255c8fdfe29SMatthew Bobrowski 	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3256c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_MAPPED;
3257c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3258de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3259de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3260c8fdfe29SMatthew Bobrowski 	} else {
3261c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_HOLE;
3262c8fdfe29SMatthew Bobrowski 		iomap->addr = IOMAP_NULL_ADDR;
3263c8fdfe29SMatthew Bobrowski 	}
3264c8fdfe29SMatthew Bobrowski }
3265c8fdfe29SMatthew Bobrowski 
3266f063db5eSMatthew Bobrowski static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3267f063db5eSMatthew Bobrowski 			    unsigned int flags)
3268f063db5eSMatthew Bobrowski {
3269f063db5eSMatthew Bobrowski 	handle_t *handle;
3270378f32baSMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3271378f32baSMatthew Bobrowski 	int ret, dio_credits, m_flags = 0, retries = 0;
3272f063db5eSMatthew Bobrowski 
3273f063db5eSMatthew Bobrowski 	/*
3274f063db5eSMatthew Bobrowski 	 * Trim the mapping request to the maximum value that we can map at
3275f063db5eSMatthew Bobrowski 	 * once for direct I/O.
3276f063db5eSMatthew Bobrowski 	 */
3277f063db5eSMatthew Bobrowski 	if (map->m_len > DIO_MAX_BLOCKS)
3278f063db5eSMatthew Bobrowski 		map->m_len = DIO_MAX_BLOCKS;
3279f063db5eSMatthew Bobrowski 	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3280f063db5eSMatthew Bobrowski 
3281f063db5eSMatthew Bobrowski retry:
3282f063db5eSMatthew Bobrowski 	/*
3283f063db5eSMatthew Bobrowski 	 * Either we allocate blocks and then don't get an unwritten extent, so
3284f063db5eSMatthew Bobrowski 	 * in that case we have reserved enough credits. Or, the blocks are
3285f063db5eSMatthew Bobrowski 	 * already allocated and unwritten. In that case, the extent conversion
3286f063db5eSMatthew Bobrowski 	 * fits into the credits as well.
3287f063db5eSMatthew Bobrowski 	 */
3288f063db5eSMatthew Bobrowski 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3289f063db5eSMatthew Bobrowski 	if (IS_ERR(handle))
3290f063db5eSMatthew Bobrowski 		return PTR_ERR(handle);
3291f063db5eSMatthew Bobrowski 
3292378f32baSMatthew Bobrowski 	/*
3293378f32baSMatthew Bobrowski 	 * DAX and direct I/O are the only two operations that are currently
3294378f32baSMatthew Bobrowski 	 * supported with IOMAP_WRITE.
3295378f32baSMatthew Bobrowski 	 */
3296952da063SChristoph Hellwig 	WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3297952da063SChristoph Hellwig 	if (flags & IOMAP_DAX)
3298378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3299378f32baSMatthew Bobrowski 	/*
3300378f32baSMatthew Bobrowski 	 * We use i_size instead of i_disksize here because delalloc writeback
3301378f32baSMatthew Bobrowski 	 * can complete at any point during the I/O and subsequently push the
3302378f32baSMatthew Bobrowski 	 * i_disksize out to i_size. This could be beyond where direct I/O is
3303378f32baSMatthew Bobrowski 	 * happening and thus expose allocated blocks to direct I/O reads.
3304378f32baSMatthew Bobrowski 	 */
3305d0b040f5SJan Kara 	else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3306378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE;
3307378f32baSMatthew Bobrowski 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3308378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3309378f32baSMatthew Bobrowski 
3310378f32baSMatthew Bobrowski 	ret = ext4_map_blocks(handle, inode, map, m_flags);
3311378f32baSMatthew Bobrowski 
3312378f32baSMatthew Bobrowski 	/*
3313378f32baSMatthew Bobrowski 	 * We cannot fill holes in indirect tree based inodes as that could
3314378f32baSMatthew Bobrowski 	 * expose stale data in the case of a crash. Use the magic error code
3315378f32baSMatthew Bobrowski 	 * to fallback to buffered I/O.
3316378f32baSMatthew Bobrowski 	 */
3317378f32baSMatthew Bobrowski 	if (!m_flags && !ret)
3318378f32baSMatthew Bobrowski 		ret = -ENOTBLK;
3319f063db5eSMatthew Bobrowski 
3320f063db5eSMatthew Bobrowski 	ext4_journal_stop(handle);
3321f063db5eSMatthew Bobrowski 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3322f063db5eSMatthew Bobrowski 		goto retry;
3323f063db5eSMatthew Bobrowski 
3324f063db5eSMatthew Bobrowski 	return ret;
3325f063db5eSMatthew Bobrowski }
3326f063db5eSMatthew Bobrowski 
3327f063db5eSMatthew Bobrowski 
3328364443cbSJan Kara static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3329c039b997SGoldwyn Rodrigues 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3330364443cbSJan Kara {
3331364443cbSJan Kara 	int ret;
333209edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
333309edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3334364443cbSJan Kara 
3335bcd8e91fSTheodore Ts'o 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3336bcd8e91fSTheodore Ts'o 		return -EINVAL;
33377046ae35SAndreas Gruenbacher 
3338364443cbSJan Kara 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3339364443cbSJan Kara 		return -ERANGE;
3340364443cbSJan Kara 
334109edf4d3SMatthew Bobrowski 	/*
334209edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical blocks respectively.
334309edf4d3SMatthew Bobrowski 	 */
334409edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
334509edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
334609edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3347364443cbSJan Kara 
33489faac62dSRitesh Harjani 	if (flags & IOMAP_WRITE) {
33499faac62dSRitesh Harjani 		/*
33509faac62dSRitesh Harjani 		 * We check here if the blocks are already allocated, then we
33519faac62dSRitesh Harjani 		 * don't need to start a journal txn and we can directly return
33529faac62dSRitesh Harjani 		 * the mapping information. This could boost performance
33539faac62dSRitesh Harjani 		 * especially in multi-threaded overwrite requests.
33549faac62dSRitesh Harjani 		 */
33559faac62dSRitesh Harjani 		if (offset + length <= i_size_read(inode)) {
3356545052e9SChristoph Hellwig 			ret = ext4_map_blocks(NULL, inode, &map, 0);
33579faac62dSRitesh Harjani 			if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
33589faac62dSRitesh Harjani 				goto out;
33599faac62dSRitesh Harjani 		}
33609faac62dSRitesh Harjani 		ret = ext4_iomap_alloc(inode, &map, flags);
33619faac62dSRitesh Harjani 	} else {
33629faac62dSRitesh Harjani 		ret = ext4_map_blocks(NULL, inode, &map, 0);
33639faac62dSRitesh Harjani 	}
3364f063db5eSMatthew Bobrowski 
3365545052e9SChristoph Hellwig 	if (ret < 0)
3366545052e9SChristoph Hellwig 		return ret;
33679faac62dSRitesh Harjani out:
336838ea50daSEric Biggers 	/*
336938ea50daSEric Biggers 	 * When inline encryption is enabled, sometimes I/O to an encrypted file
337038ea50daSEric Biggers 	 * has to be broken up to guarantee DUN contiguity.  Handle this by
337138ea50daSEric Biggers 	 * limiting the length of the mapping returned.
337238ea50daSEric Biggers 	 */
337338ea50daSEric Biggers 	map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
337438ea50daSEric Biggers 
3375de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3376545052e9SChristoph Hellwig 
3377364443cbSJan Kara 	return 0;
3378364443cbSJan Kara }
3379364443cbSJan Kara 
33808cd115bdSJan Kara static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
33818cd115bdSJan Kara 		loff_t length, unsigned flags, struct iomap *iomap,
33828cd115bdSJan Kara 		struct iomap *srcmap)
33838cd115bdSJan Kara {
33848cd115bdSJan Kara 	int ret;
33858cd115bdSJan Kara 
33868cd115bdSJan Kara 	/*
33878cd115bdSJan Kara 	 * Even for writes we don't need to allocate blocks, so just pretend
33888cd115bdSJan Kara 	 * we are reading to save overhead of starting a transaction.
33898cd115bdSJan Kara 	 */
33908cd115bdSJan Kara 	flags &= ~IOMAP_WRITE;
33918cd115bdSJan Kara 	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3392fa83c34eSBaokun Li 	WARN_ON_ONCE(!ret && iomap->type != IOMAP_MAPPED);
33938cd115bdSJan Kara 	return ret;
33948cd115bdSJan Kara }
33958cd115bdSJan Kara 
3396776722e8SJan Kara static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3397776722e8SJan Kara 			  ssize_t written, unsigned flags, struct iomap *iomap)
3398776722e8SJan Kara {
3399378f32baSMatthew Bobrowski 	/*
3400378f32baSMatthew Bobrowski 	 * Check to see whether an error occurred while writing out the data to
3401378f32baSMatthew Bobrowski 	 * the allocated blocks. If so, return the magic error code so that we
3402378f32baSMatthew Bobrowski 	 * fallback to buffered I/O and attempt to complete the remainder of
3403378f32baSMatthew Bobrowski 	 * the I/O. Any blocks that may have been allocated in preparation for
3404378f32baSMatthew Bobrowski 	 * the direct I/O will be reused during buffered I/O.
3405378f32baSMatthew Bobrowski 	 */
3406378f32baSMatthew Bobrowski 	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3407378f32baSMatthew Bobrowski 		return -ENOTBLK;
3408378f32baSMatthew Bobrowski 
3409776722e8SJan Kara 	return 0;
3410776722e8SJan Kara }
3411776722e8SJan Kara 
34128ff6daa1SChristoph Hellwig const struct iomap_ops ext4_iomap_ops = {
3413364443cbSJan Kara 	.iomap_begin		= ext4_iomap_begin,
3414776722e8SJan Kara 	.iomap_end		= ext4_iomap_end,
3415364443cbSJan Kara };
3416364443cbSJan Kara 
34178cd115bdSJan Kara const struct iomap_ops ext4_iomap_overwrite_ops = {
34188cd115bdSJan Kara 	.iomap_begin		= ext4_iomap_overwrite_begin,
34198cd115bdSJan Kara 	.iomap_end		= ext4_iomap_end,
34208cd115bdSJan Kara };
34218cd115bdSJan Kara 
342209edf4d3SMatthew Bobrowski static bool ext4_iomap_is_delalloc(struct inode *inode,
342309edf4d3SMatthew Bobrowski 				   struct ext4_map_blocks *map)
342409edf4d3SMatthew Bobrowski {
342509edf4d3SMatthew Bobrowski 	struct extent_status es;
342609edf4d3SMatthew Bobrowski 	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
342709edf4d3SMatthew Bobrowski 
342809edf4d3SMatthew Bobrowski 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
342909edf4d3SMatthew Bobrowski 				  map->m_lblk, end, &es);
343009edf4d3SMatthew Bobrowski 
343109edf4d3SMatthew Bobrowski 	if (!es.es_len || es.es_lblk > end)
343209edf4d3SMatthew Bobrowski 		return false;
343309edf4d3SMatthew Bobrowski 
343409edf4d3SMatthew Bobrowski 	if (es.es_lblk > map->m_lblk) {
343509edf4d3SMatthew Bobrowski 		map->m_len = es.es_lblk - map->m_lblk;
343609edf4d3SMatthew Bobrowski 		return false;
343709edf4d3SMatthew Bobrowski 	}
343809edf4d3SMatthew Bobrowski 
343909edf4d3SMatthew Bobrowski 	offset = map->m_lblk - es.es_lblk;
344009edf4d3SMatthew Bobrowski 	map->m_len = es.es_len - offset;
344109edf4d3SMatthew Bobrowski 
344209edf4d3SMatthew Bobrowski 	return true;
344309edf4d3SMatthew Bobrowski }
344409edf4d3SMatthew Bobrowski 
344509edf4d3SMatthew Bobrowski static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
344609edf4d3SMatthew Bobrowski 				   loff_t length, unsigned int flags,
344709edf4d3SMatthew Bobrowski 				   struct iomap *iomap, struct iomap *srcmap)
344809edf4d3SMatthew Bobrowski {
344909edf4d3SMatthew Bobrowski 	int ret;
345009edf4d3SMatthew Bobrowski 	bool delalloc = false;
345109edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
345209edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
345309edf4d3SMatthew Bobrowski 
345409edf4d3SMatthew Bobrowski 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
345509edf4d3SMatthew Bobrowski 		return -EINVAL;
345609edf4d3SMatthew Bobrowski 
34577cb476f8SJan Kara 	if (ext4_has_inline_data(inode)) {
34587cb476f8SJan Kara 		ret = ext4_inline_data_iomap(inode, iomap);
3459ba5843f5SJan Kara 		if (ret != -EAGAIN) {
3460ed923b57SMatthew Wilcox 			if (ret == 0 && offset >= iomap->length)
3461ba5843f5SJan Kara 				ret = -ENOENT;
3462ba5843f5SJan Kara 			return ret;
3463ba5843f5SJan Kara 		}
3464ba5843f5SJan Kara 	}
346512735f88SJan Kara 
346609edf4d3SMatthew Bobrowski 	/*
346709edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical block respectively.
346809edf4d3SMatthew Bobrowski 	 */
346909edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
347009edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
347109edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
347212735f88SJan Kara 
3473b2c57642SRitesh Harjani 	/*
3474b2c57642SRitesh Harjani 	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3475b2c57642SRitesh Harjani 	 * So handle it here itself instead of querying ext4_map_blocks().
3476b2c57642SRitesh Harjani 	 * Since ext4_map_blocks() will warn about it and will return
3477b2c57642SRitesh Harjani 	 * -EIO error.
3478b2c57642SRitesh Harjani 	 */
3479b2c57642SRitesh Harjani 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3480b2c57642SRitesh Harjani 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3481b2c57642SRitesh Harjani 
3482b2c57642SRitesh Harjani 		if (offset >= sbi->s_bitmap_maxbytes) {
3483b2c57642SRitesh Harjani 			map.m_flags = 0;
3484b2c57642SRitesh Harjani 			goto set_iomap;
3485b2c57642SRitesh Harjani 		}
3486b2c57642SRitesh Harjani 	}
3487b2c57642SRitesh Harjani 
348812735f88SJan Kara 	ret = ext4_map_blocks(NULL, inode, &map, 0);
3489ba5843f5SJan Kara 	if (ret < 0)
3490ba5843f5SJan Kara 		return ret;
3491914f82a3SJan Kara 	if (ret == 0)
349209edf4d3SMatthew Bobrowski 		delalloc = ext4_iomap_is_delalloc(inode, &map);
349309edf4d3SMatthew Bobrowski 
3494b2c57642SRitesh Harjani set_iomap:
3495de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
349609edf4d3SMatthew Bobrowski 	if (delalloc && iomap->type == IOMAP_HOLE)
349709edf4d3SMatthew Bobrowski 		iomap->type = IOMAP_DELALLOC;
349809edf4d3SMatthew Bobrowski 
349909edf4d3SMatthew Bobrowski 	return 0;
3500914f82a3SJan Kara }
3501914f82a3SJan Kara 
350209edf4d3SMatthew Bobrowski const struct iomap_ops ext4_iomap_report_ops = {
350309edf4d3SMatthew Bobrowski 	.iomap_begin = ext4_iomap_begin_report,
350409edf4d3SMatthew Bobrowski };
35054c0425ffSMingming Cao 
3506ac27a0ecSDave Kleikamp /*
35073f5d3063SJan Kara  * For data=journal mode, folio should be marked dirty only when it was
35083f5d3063SJan Kara  * writeably mapped. When that happens, it was already attached to the
35093f5d3063SJan Kara  * transaction and marked as jbddirty (we take care of this in
35103f5d3063SJan Kara  * ext4_page_mkwrite()). On transaction commit, we writeprotect page mappings
35113f5d3063SJan Kara  * so we should have nothing to do here, except for the case when someone
35123f5d3063SJan Kara  * had the page pinned and dirtied the page through this pin (e.g. by doing
35133f5d3063SJan Kara  * direct IO to it). In that case we'd need to attach buffers here to the
35143f5d3063SJan Kara  * transaction but we cannot due to lock ordering.  We cannot just dirty the
35153f5d3063SJan Kara  * folio and leave attached buffers clean, because the buffers' dirty state is
35163f5d3063SJan Kara  * "definitive".  We cannot just set the buffers dirty or jbddirty because all
35173f5d3063SJan Kara  * the journalling code will explode.  So what we do is to mark the folio
35183f5d3063SJan Kara  * "pending dirty" and next time ext4_writepages() is called, attach buffers
35193f5d3063SJan Kara  * to the transaction appropriately.
3520ac27a0ecSDave Kleikamp  */
3521187c82cbSMatthew Wilcox (Oracle) static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3522187c82cbSMatthew Wilcox (Oracle) 		struct folio *folio)
3523ac27a0ecSDave Kleikamp {
35240f252336SMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
35253f5d3063SJan Kara 	if (folio_maybe_dma_pinned(folio))
3526187c82cbSMatthew Wilcox (Oracle) 		folio_set_checked(folio);
3527187c82cbSMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
3528ac27a0ecSDave Kleikamp }
3529ac27a0ecSDave Kleikamp 
3530e621900aSMatthew Wilcox (Oracle) static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
35316dcc693bSJan Kara {
3532e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3533e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
3534e621900aSMatthew Wilcox (Oracle) 	return block_dirty_folio(mapping, folio);
35356dcc693bSJan Kara }
35366dcc693bSJan Kara 
35370e6895baSRitesh Harjani static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
35380e6895baSRitesh Harjani 				    struct file *file, sector_t *span)
35390e6895baSRitesh Harjani {
35400e6895baSRitesh Harjani 	return iomap_swapfile_activate(sis, file, span,
35410e6895baSRitesh Harjani 				       &ext4_iomap_report_ops);
35420e6895baSRitesh Harjani }
35430e6895baSRitesh Harjani 
354474d553aaSTheodore Ts'o static const struct address_space_operations ext4_aops = {
3545fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
35466311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
354720970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3548bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
354974d553aaSTheodore Ts'o 	.write_end		= ext4_write_end,
3550e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
3551617ba13bSMingming Cao 	.bmap			= ext4_bmap,
35527ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
35533c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3554378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
355567235182SMatthew Wilcox (Oracle) 	.migrate_folio		= buffer_migrate_folio,
35568ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3557aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
35580e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3559ac27a0ecSDave Kleikamp };
3560ac27a0ecSDave Kleikamp 
3561617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
3562fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
35636311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
356420970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3565bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
3566bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
3567187c82cbSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_journalled_dirty_folio,
3568617ba13bSMingming Cao 	.bmap			= ext4_bmap,
3569ccd16945SMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_journalled_invalidate_folio,
35703c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3571378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
3572dae99960SJan Kara 	.migrate_folio		= buffer_migrate_folio_norefs,
35738ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3574aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
35750e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3576ac27a0ecSDave Kleikamp };
3577ac27a0ecSDave Kleikamp 
357864769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
3579fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
35806311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
358120970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
358264769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
358364769240SAlex Tomas 	.write_end		= ext4_da_write_end,
3584e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
358564769240SAlex Tomas 	.bmap			= ext4_bmap,
35867ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
35873c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3588378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
358967235182SMatthew Wilcox (Oracle) 	.migrate_folio		= buffer_migrate_folio,
35908ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3591aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
35920e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
359364769240SAlex Tomas };
359464769240SAlex Tomas 
35955f0663bbSDan Williams static const struct address_space_operations ext4_dax_aops = {
35965f0663bbSDan Williams 	.writepages		= ext4_dax_writepages,
35975f0663bbSDan Williams 	.direct_IO		= noop_direct_IO,
359846de8b97SMatthew Wilcox (Oracle) 	.dirty_folio		= noop_dirty_folio,
359994dbb631SToshi Kani 	.bmap			= ext4_bmap,
36000e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
36015f0663bbSDan Williams };
36025f0663bbSDan Williams 
3603617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
3604ac27a0ecSDave Kleikamp {
36053d2b1582SLukas Czerner 	switch (ext4_inode_journal_mode(inode)) {
36063d2b1582SLukas Czerner 	case EXT4_INODE_ORDERED_DATA_MODE:
36073d2b1582SLukas Czerner 	case EXT4_INODE_WRITEBACK_DATA_MODE:
36083d2b1582SLukas Czerner 		break;
36093d2b1582SLukas Czerner 	case EXT4_INODE_JOURNAL_DATA_MODE:
3610617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
361174d553aaSTheodore Ts'o 		return;
36123d2b1582SLukas Czerner 	default:
36133d2b1582SLukas Czerner 		BUG();
36143d2b1582SLukas Czerner 	}
36155f0663bbSDan Williams 	if (IS_DAX(inode))
36165f0663bbSDan Williams 		inode->i_mapping->a_ops = &ext4_dax_aops;
36175f0663bbSDan Williams 	else if (test_opt(inode->i_sb, DELALLOC))
361874d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_da_aops;
361974d553aaSTheodore Ts'o 	else
362074d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_aops;
3621ac27a0ecSDave Kleikamp }
3622ac27a0ecSDave Kleikamp 
3623923ae0ffSRoss Zwisler static int __ext4_block_zero_page_range(handle_t *handle,
3624d863dc36SLukas Czerner 		struct address_space *mapping, loff_t from, loff_t length)
3625d863dc36SLukas Czerner {
362609cbfeafSKirill A. Shutemov 	ext4_fsblk_t index = from >> PAGE_SHIFT;
362709cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3628923ae0ffSRoss Zwisler 	unsigned blocksize, pos;
3629d863dc36SLukas Czerner 	ext4_lblk_t iblock;
3630d863dc36SLukas Czerner 	struct inode *inode = mapping->host;
3631d863dc36SLukas Czerner 	struct buffer_head *bh;
36329d3973deSMatthew Wilcox 	struct folio *folio;
3633d863dc36SLukas Czerner 	int err = 0;
3634d863dc36SLukas Czerner 
36359d3973deSMatthew Wilcox 	folio = __filemap_get_folio(mapping, from >> PAGE_SHIFT,
36369d3973deSMatthew Wilcox 				    FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
3637c62d2555SMichal Hocko 				    mapping_gfp_constraint(mapping, ~__GFP_FS));
36387fa8a8eeSLinus Torvalds 	if (IS_ERR(folio))
36397fa8a8eeSLinus Torvalds 		return PTR_ERR(folio);
3640d863dc36SLukas Czerner 
3641d863dc36SLukas Czerner 	blocksize = inode->i_sb->s_blocksize;
3642d863dc36SLukas Czerner 
364309cbfeafSKirill A. Shutemov 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3644d863dc36SLukas Czerner 
36459d3973deSMatthew Wilcox 	bh = folio_buffers(folio);
36469d3973deSMatthew Wilcox 	if (!bh) {
36479d3973deSMatthew Wilcox 		create_empty_buffers(&folio->page, blocksize, 0);
36489d3973deSMatthew Wilcox 		bh = folio_buffers(folio);
36499d3973deSMatthew Wilcox 	}
3650d863dc36SLukas Czerner 
3651d863dc36SLukas Czerner 	/* Find the buffer that contains "offset" */
3652d863dc36SLukas Czerner 	pos = blocksize;
3653d863dc36SLukas Czerner 	while (offset >= pos) {
3654d863dc36SLukas Czerner 		bh = bh->b_this_page;
3655d863dc36SLukas Czerner 		iblock++;
3656d863dc36SLukas Czerner 		pos += blocksize;
3657d863dc36SLukas Czerner 	}
3658d863dc36SLukas Czerner 	if (buffer_freed(bh)) {
3659d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "freed: skip");
3660d863dc36SLukas Czerner 		goto unlock;
3661d863dc36SLukas Czerner 	}
3662d863dc36SLukas Czerner 	if (!buffer_mapped(bh)) {
3663d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "unmapped");
3664d863dc36SLukas Czerner 		ext4_get_block(inode, iblock, bh, 0);
3665d863dc36SLukas Czerner 		/* unmapped? It's a hole - nothing to do */
3666d863dc36SLukas Czerner 		if (!buffer_mapped(bh)) {
3667d863dc36SLukas Czerner 			BUFFER_TRACE(bh, "still unmapped");
3668d863dc36SLukas Czerner 			goto unlock;
3669d863dc36SLukas Czerner 		}
3670d863dc36SLukas Czerner 	}
3671d863dc36SLukas Czerner 
3672d863dc36SLukas Czerner 	/* Ok, it's mapped. Make sure it's up-to-date */
36739d3973deSMatthew Wilcox 	if (folio_test_uptodate(folio))
3674d863dc36SLukas Czerner 		set_buffer_uptodate(bh);
3675d863dc36SLukas Czerner 
3676d863dc36SLukas Czerner 	if (!buffer_uptodate(bh)) {
36772d069c08Szhangyi (F) 		err = ext4_read_bh_lock(bh, 0, true);
36782d069c08Szhangyi (F) 		if (err)
3679d863dc36SLukas Czerner 			goto unlock;
36804f74d15fSEric Biggers 		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3681c9c7429cSMichael Halcrow 			/* We expect the key to be set. */
3682a7550b30SJaegeuk Kim 			BUG_ON(!fscrypt_has_encryption_key(inode));
36839d3973deSMatthew Wilcox 			err = fscrypt_decrypt_pagecache_blocks(folio,
368451e4e315SEric Biggers 							       blocksize,
3685834f1565SEric Biggers 							       bh_offset(bh));
3686834f1565SEric Biggers 			if (err) {
3687834f1565SEric Biggers 				clear_buffer_uptodate(bh);
3688834f1565SEric Biggers 				goto unlock;
3689834f1565SEric Biggers 			}
3690c9c7429cSMichael Halcrow 		}
3691d863dc36SLukas Czerner 	}
3692d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3693d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "get write access");
3694188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
3695188c299eSJan Kara 						    EXT4_JTR_NONE);
3696d863dc36SLukas Czerner 		if (err)
3697d863dc36SLukas Czerner 			goto unlock;
3698d863dc36SLukas Czerner 	}
36999d3973deSMatthew Wilcox 	folio_zero_range(folio, offset, length);
3700d863dc36SLukas Czerner 	BUFFER_TRACE(bh, "zeroed end of block");
3701d863dc36SLukas Czerner 
3702d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3703d84c9ebdSJan Kara 		err = ext4_dirty_journalled_data(handle, bh);
37040713ed0cSLukas Czerner 	} else {
3705353eefd3Sjon ernst 		err = 0;
3706d863dc36SLukas Czerner 		mark_buffer_dirty(bh);
37073957ef53SJan Kara 		if (ext4_should_order_data(inode))
370873131fbbSRoss Zwisler 			err = ext4_jbd2_inode_add_write(handle, inode, from,
370973131fbbSRoss Zwisler 					length);
37100713ed0cSLukas Czerner 	}
3711d863dc36SLukas Czerner 
3712d863dc36SLukas Czerner unlock:
37139d3973deSMatthew Wilcox 	folio_unlock(folio);
37149d3973deSMatthew Wilcox 	folio_put(folio);
3715d863dc36SLukas Czerner 	return err;
3716d863dc36SLukas Czerner }
3717d863dc36SLukas Czerner 
371894350ab5SMatthew Wilcox /*
3719923ae0ffSRoss Zwisler  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3720923ae0ffSRoss Zwisler  * starting from file offset 'from'.  The range to be zero'd must
3721923ae0ffSRoss Zwisler  * be contained with in one block.  If the specified range exceeds
3722923ae0ffSRoss Zwisler  * the end of the block it will be shortened to end of the block
37233088e5a5SBhaskar Chowdhury  * that corresponds to 'from'
3724923ae0ffSRoss Zwisler  */
3725923ae0ffSRoss Zwisler static int ext4_block_zero_page_range(handle_t *handle,
3726923ae0ffSRoss Zwisler 		struct address_space *mapping, loff_t from, loff_t length)
3727923ae0ffSRoss Zwisler {
3728923ae0ffSRoss Zwisler 	struct inode *inode = mapping->host;
372909cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3730923ae0ffSRoss Zwisler 	unsigned blocksize = inode->i_sb->s_blocksize;
3731923ae0ffSRoss Zwisler 	unsigned max = blocksize - (offset & (blocksize - 1));
3732923ae0ffSRoss Zwisler 
3733923ae0ffSRoss Zwisler 	/*
3734923ae0ffSRoss Zwisler 	 * correct length if it does not fall between
3735923ae0ffSRoss Zwisler 	 * 'from' and the end of the block
3736923ae0ffSRoss Zwisler 	 */
3737923ae0ffSRoss Zwisler 	if (length > max || length < 0)
3738923ae0ffSRoss Zwisler 		length = max;
3739923ae0ffSRoss Zwisler 
374047e69351SJan Kara 	if (IS_DAX(inode)) {
3741c6f40468SChristoph Hellwig 		return dax_zero_range(inode, from, length, NULL,
374247e69351SJan Kara 				      &ext4_iomap_ops);
374347e69351SJan Kara 	}
3744923ae0ffSRoss Zwisler 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3745923ae0ffSRoss Zwisler }
3746923ae0ffSRoss Zwisler 
3747923ae0ffSRoss Zwisler /*
374894350ab5SMatthew Wilcox  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
374994350ab5SMatthew Wilcox  * up to the end of the block which corresponds to `from'.
375094350ab5SMatthew Wilcox  * This required during truncate. We need to physically zero the tail end
375194350ab5SMatthew Wilcox  * of that block so it doesn't yield old data if the file is later grown.
375294350ab5SMatthew Wilcox  */
3753c197855eSStephen Hemminger static int ext4_block_truncate_page(handle_t *handle,
375494350ab5SMatthew Wilcox 		struct address_space *mapping, loff_t from)
375594350ab5SMatthew Wilcox {
375609cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
375794350ab5SMatthew Wilcox 	unsigned length;
375894350ab5SMatthew Wilcox 	unsigned blocksize;
375994350ab5SMatthew Wilcox 	struct inode *inode = mapping->host;
376094350ab5SMatthew Wilcox 
37610d06863fSTheodore Ts'o 	/* If we are processing an encrypted inode during orphan list handling */
3762592ddec7SChandan Rajendra 	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
37630d06863fSTheodore Ts'o 		return 0;
37640d06863fSTheodore Ts'o 
376594350ab5SMatthew Wilcox 	blocksize = inode->i_sb->s_blocksize;
376694350ab5SMatthew Wilcox 	length = blocksize - (offset & (blocksize - 1));
376794350ab5SMatthew Wilcox 
376894350ab5SMatthew Wilcox 	return ext4_block_zero_page_range(handle, mapping, from, length);
376994350ab5SMatthew Wilcox }
377094350ab5SMatthew Wilcox 
3771a87dd18cSLukas Czerner int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3772a87dd18cSLukas Czerner 			     loff_t lstart, loff_t length)
3773a87dd18cSLukas Czerner {
3774a87dd18cSLukas Czerner 	struct super_block *sb = inode->i_sb;
3775a87dd18cSLukas Czerner 	struct address_space *mapping = inode->i_mapping;
3776e1be3a92SLukas Czerner 	unsigned partial_start, partial_end;
3777a87dd18cSLukas Czerner 	ext4_fsblk_t start, end;
3778a87dd18cSLukas Czerner 	loff_t byte_end = (lstart + length - 1);
3779a87dd18cSLukas Czerner 	int err = 0;
3780a87dd18cSLukas Czerner 
3781e1be3a92SLukas Czerner 	partial_start = lstart & (sb->s_blocksize - 1);
3782e1be3a92SLukas Czerner 	partial_end = byte_end & (sb->s_blocksize - 1);
3783e1be3a92SLukas Czerner 
3784a87dd18cSLukas Czerner 	start = lstart >> sb->s_blocksize_bits;
3785a87dd18cSLukas Czerner 	end = byte_end >> sb->s_blocksize_bits;
3786a87dd18cSLukas Czerner 
3787a87dd18cSLukas Czerner 	/* Handle partial zero within the single block */
3788e1be3a92SLukas Czerner 	if (start == end &&
3789e1be3a92SLukas Czerner 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3790a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3791a87dd18cSLukas Czerner 						 lstart, length);
3792a87dd18cSLukas Czerner 		return err;
3793a87dd18cSLukas Czerner 	}
3794a87dd18cSLukas Czerner 	/* Handle partial zero out on the start of the range */
3795e1be3a92SLukas Czerner 	if (partial_start) {
3796a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3797a87dd18cSLukas Czerner 						 lstart, sb->s_blocksize);
3798a87dd18cSLukas Czerner 		if (err)
3799a87dd18cSLukas Czerner 			return err;
3800a87dd18cSLukas Czerner 	}
3801a87dd18cSLukas Czerner 	/* Handle partial zero out on the end of the range */
3802e1be3a92SLukas Czerner 	if (partial_end != sb->s_blocksize - 1)
3803a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3804e1be3a92SLukas Czerner 						 byte_end - partial_end,
3805e1be3a92SLukas Czerner 						 partial_end + 1);
3806a87dd18cSLukas Czerner 	return err;
3807a87dd18cSLukas Czerner }
3808a87dd18cSLukas Czerner 
380991ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
381091ef4cafSDuane Griffin {
381191ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
381291ef4cafSDuane Griffin 		return 1;
381391ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
381491ef4cafSDuane Griffin 		return 1;
381591ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
381691ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
381791ef4cafSDuane Griffin 	return 0;
381891ef4cafSDuane Griffin }
381991ef4cafSDuane Griffin 
3820ac27a0ecSDave Kleikamp /*
382101127848SJan Kara  * We have to make sure i_disksize gets properly updated before we truncate
382201127848SJan Kara  * page cache due to hole punching or zero range. Otherwise i_disksize update
382301127848SJan Kara  * can get lost as it may have been postponed to submission of writeback but
382401127848SJan Kara  * that will never happen after we truncate page cache.
382501127848SJan Kara  */
382601127848SJan Kara int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
382701127848SJan Kara 				      loff_t len)
382801127848SJan Kara {
382901127848SJan Kara 	handle_t *handle;
38304209ae12SHarshad Shirwadkar 	int ret;
38314209ae12SHarshad Shirwadkar 
383201127848SJan Kara 	loff_t size = i_size_read(inode);
383301127848SJan Kara 
38345955102cSAl Viro 	WARN_ON(!inode_is_locked(inode));
383501127848SJan Kara 	if (offset > size || offset + len < size)
383601127848SJan Kara 		return 0;
383701127848SJan Kara 
383801127848SJan Kara 	if (EXT4_I(inode)->i_disksize >= size)
383901127848SJan Kara 		return 0;
384001127848SJan Kara 
384101127848SJan Kara 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
384201127848SJan Kara 	if (IS_ERR(handle))
384301127848SJan Kara 		return PTR_ERR(handle);
384401127848SJan Kara 	ext4_update_i_disksize(inode, size);
38454209ae12SHarshad Shirwadkar 	ret = ext4_mark_inode_dirty(handle, inode);
384601127848SJan Kara 	ext4_journal_stop(handle);
384701127848SJan Kara 
38484209ae12SHarshad Shirwadkar 	return ret;
384901127848SJan Kara }
385001127848SJan Kara 
3851d4f5258eSJan Kara static void ext4_wait_dax_page(struct inode *inode)
3852430657b6SRoss Zwisler {
3853d4f5258eSJan Kara 	filemap_invalidate_unlock(inode->i_mapping);
3854430657b6SRoss Zwisler 	schedule();
3855d4f5258eSJan Kara 	filemap_invalidate_lock(inode->i_mapping);
3856430657b6SRoss Zwisler }
3857430657b6SRoss Zwisler 
3858430657b6SRoss Zwisler int ext4_break_layouts(struct inode *inode)
3859430657b6SRoss Zwisler {
3860430657b6SRoss Zwisler 	struct page *page;
3861430657b6SRoss Zwisler 	int error;
3862430657b6SRoss Zwisler 
3863d4f5258eSJan Kara 	if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
3864430657b6SRoss Zwisler 		return -EINVAL;
3865430657b6SRoss Zwisler 
3866430657b6SRoss Zwisler 	do {
3867430657b6SRoss Zwisler 		page = dax_layout_busy_page(inode->i_mapping);
3868430657b6SRoss Zwisler 		if (!page)
3869430657b6SRoss Zwisler 			return 0;
3870430657b6SRoss Zwisler 
3871430657b6SRoss Zwisler 		error = ___wait_var_event(&page->_refcount,
3872430657b6SRoss Zwisler 				atomic_read(&page->_refcount) == 1,
3873430657b6SRoss Zwisler 				TASK_INTERRUPTIBLE, 0, 0,
3874d4f5258eSJan Kara 				ext4_wait_dax_page(inode));
3875b1f38217SRoss Zwisler 	} while (error == 0);
3876430657b6SRoss Zwisler 
3877430657b6SRoss Zwisler 	return error;
3878430657b6SRoss Zwisler }
3879430657b6SRoss Zwisler 
388001127848SJan Kara /*
3881cca32b7eSRoss Zwisler  * ext4_punch_hole: punches a hole in a file by releasing the blocks
3882a4bb6b64SAllison Henderson  * associated with the given offset and length
3883a4bb6b64SAllison Henderson  *
3884a4bb6b64SAllison Henderson  * @inode:  File inode
3885a4bb6b64SAllison Henderson  * @offset: The offset where the hole will begin
3886a4bb6b64SAllison Henderson  * @len:    The length of the hole
3887a4bb6b64SAllison Henderson  *
38884907cb7bSAnatol Pomozov  * Returns: 0 on success or negative on failure
3889a4bb6b64SAllison Henderson  */
3890a4bb6b64SAllison Henderson 
3891ad5cd4f4SDarrick J. Wong int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3892a4bb6b64SAllison Henderson {
3893ad5cd4f4SDarrick J. Wong 	struct inode *inode = file_inode(file);
389426a4c0c6STheodore Ts'o 	struct super_block *sb = inode->i_sb;
389526a4c0c6STheodore Ts'o 	ext4_lblk_t first_block, stop_block;
389626a4c0c6STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
38972da37622STadeusz Struk 	loff_t first_block_offset, last_block_offset, max_length;
38982da37622STadeusz Struk 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
389926a4c0c6STheodore Ts'o 	handle_t *handle;
390026a4c0c6STheodore Ts'o 	unsigned int credits;
39014209ae12SHarshad Shirwadkar 	int ret = 0, ret2 = 0;
390226a4c0c6STheodore Ts'o 
3903b8a86845SLukas Czerner 	trace_ext4_punch_hole(inode, offset, length, 0);
3904aaddea81SZheng Liu 
390526a4c0c6STheodore Ts'o 	/*
390626a4c0c6STheodore Ts'o 	 * Write out all dirty pages to avoid race conditions
390726a4c0c6STheodore Ts'o 	 * Then release them.
390826a4c0c6STheodore Ts'o 	 */
3909cca32b7eSRoss Zwisler 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
391026a4c0c6STheodore Ts'o 		ret = filemap_write_and_wait_range(mapping, offset,
391126a4c0c6STheodore Ts'o 						   offset + length - 1);
391226a4c0c6STheodore Ts'o 		if (ret)
391326a4c0c6STheodore Ts'o 			return ret;
391426a4c0c6STheodore Ts'o 	}
391526a4c0c6STheodore Ts'o 
39165955102cSAl Viro 	inode_lock(inode);
39179ef06cecSLukas Czerner 
391826a4c0c6STheodore Ts'o 	/* No need to punch hole beyond i_size */
391926a4c0c6STheodore Ts'o 	if (offset >= inode->i_size)
392026a4c0c6STheodore Ts'o 		goto out_mutex;
392126a4c0c6STheodore Ts'o 
392226a4c0c6STheodore Ts'o 	/*
392326a4c0c6STheodore Ts'o 	 * If the hole extends beyond i_size, set the hole
392426a4c0c6STheodore Ts'o 	 * to end after the page that contains i_size
392526a4c0c6STheodore Ts'o 	 */
392626a4c0c6STheodore Ts'o 	if (offset + length > inode->i_size) {
392726a4c0c6STheodore Ts'o 		length = inode->i_size +
392809cbfeafSKirill A. Shutemov 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
392926a4c0c6STheodore Ts'o 		   offset;
393026a4c0c6STheodore Ts'o 	}
393126a4c0c6STheodore Ts'o 
39322da37622STadeusz Struk 	/*
39332da37622STadeusz Struk 	 * For punch hole the length + offset needs to be within one block
39342da37622STadeusz Struk 	 * before last range. Adjust the length if it goes beyond that limit.
39352da37622STadeusz Struk 	 */
39362da37622STadeusz Struk 	max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
39372da37622STadeusz Struk 	if (offset + length > max_length)
39382da37622STadeusz Struk 		length = max_length - offset;
39392da37622STadeusz Struk 
3940a361293fSJan Kara 	if (offset & (sb->s_blocksize - 1) ||
3941a361293fSJan Kara 	    (offset + length) & (sb->s_blocksize - 1)) {
3942a361293fSJan Kara 		/*
3943a361293fSJan Kara 		 * Attach jinode to inode for jbd2 if we do any zeroing of
3944a361293fSJan Kara 		 * partial block
3945a361293fSJan Kara 		 */
3946a361293fSJan Kara 		ret = ext4_inode_attach_jinode(inode);
3947a361293fSJan Kara 		if (ret < 0)
3948a361293fSJan Kara 			goto out_mutex;
3949a361293fSJan Kara 
3950a361293fSJan Kara 	}
3951a361293fSJan Kara 
3952f340b3d9Shongnanli 	/* Wait all existing dio workers, newcomers will block on i_rwsem */
3953ea3d7209SJan Kara 	inode_dio_wait(inode);
3954ea3d7209SJan Kara 
3955ad5cd4f4SDarrick J. Wong 	ret = file_modified(file);
3956ad5cd4f4SDarrick J. Wong 	if (ret)
3957ad5cd4f4SDarrick J. Wong 		goto out_mutex;
3958ad5cd4f4SDarrick J. Wong 
3959ea3d7209SJan Kara 	/*
3960ea3d7209SJan Kara 	 * Prevent page faults from reinstantiating pages we have released from
3961ea3d7209SJan Kara 	 * page cache.
3962ea3d7209SJan Kara 	 */
3963d4f5258eSJan Kara 	filemap_invalidate_lock(mapping);
3964430657b6SRoss Zwisler 
3965430657b6SRoss Zwisler 	ret = ext4_break_layouts(inode);
3966430657b6SRoss Zwisler 	if (ret)
3967430657b6SRoss Zwisler 		goto out_dio;
3968430657b6SRoss Zwisler 
3969a87dd18cSLukas Czerner 	first_block_offset = round_up(offset, sb->s_blocksize);
3970a87dd18cSLukas Czerner 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
397126a4c0c6STheodore Ts'o 
3972a87dd18cSLukas Czerner 	/* Now release the pages and zero block aligned part of pages*/
397301127848SJan Kara 	if (last_block_offset > first_block_offset) {
397401127848SJan Kara 		ret = ext4_update_disksize_before_punch(inode, offset, length);
397501127848SJan Kara 		if (ret)
397601127848SJan Kara 			goto out_dio;
3977a87dd18cSLukas Czerner 		truncate_pagecache_range(inode, first_block_offset,
3978a87dd18cSLukas Czerner 					 last_block_offset);
397901127848SJan Kara 	}
398026a4c0c6STheodore Ts'o 
398126a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
398226a4c0c6STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
398326a4c0c6STheodore Ts'o 	else
398426a4c0c6STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
398526a4c0c6STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
398626a4c0c6STheodore Ts'o 	if (IS_ERR(handle)) {
398726a4c0c6STheodore Ts'o 		ret = PTR_ERR(handle);
398826a4c0c6STheodore Ts'o 		ext4_std_error(sb, ret);
398926a4c0c6STheodore Ts'o 		goto out_dio;
399026a4c0c6STheodore Ts'o 	}
399126a4c0c6STheodore Ts'o 
3992a87dd18cSLukas Czerner 	ret = ext4_zero_partial_blocks(handle, inode, offset,
3993a87dd18cSLukas Czerner 				       length);
399426a4c0c6STheodore Ts'o 	if (ret)
399526a4c0c6STheodore Ts'o 		goto out_stop;
399626a4c0c6STheodore Ts'o 
399726a4c0c6STheodore Ts'o 	first_block = (offset + sb->s_blocksize - 1) >>
399826a4c0c6STheodore Ts'o 		EXT4_BLOCK_SIZE_BITS(sb);
399926a4c0c6STheodore Ts'o 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
400026a4c0c6STheodore Ts'o 
4001eee597acSLukas Czerner 	/* If there are blocks to remove, do it */
4002eee597acSLukas Czerner 	if (stop_block > first_block) {
400326a4c0c6STheodore Ts'o 
400426a4c0c6STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
400527bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
400626a4c0c6STheodore Ts'o 
4007ed5d285bSBaokun Li 		ext4_es_remove_extent(inode, first_block,
400826a4c0c6STheodore Ts'o 				      stop_block - first_block);
400926a4c0c6STheodore Ts'o 
401026a4c0c6STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
401126a4c0c6STheodore Ts'o 			ret = ext4_ext_remove_space(inode, first_block,
401226a4c0c6STheodore Ts'o 						    stop_block - 1);
401326a4c0c6STheodore Ts'o 		else
40144f579ae7SLukas Czerner 			ret = ext4_ind_remove_space(handle, inode, first_block,
401526a4c0c6STheodore Ts'o 						    stop_block);
401626a4c0c6STheodore Ts'o 
4017819c4920STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
4018eee597acSLukas Czerner 	}
4019a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_range(handle, inode, first_block, stop_block);
402026a4c0c6STheodore Ts'o 	if (IS_SYNC(inode))
402126a4c0c6STheodore Ts'o 		ext4_handle_sync(handle);
4022e251f9bcSMaxim Patlasov 
4023eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
40244209ae12SHarshad Shirwadkar 	ret2 = ext4_mark_inode_dirty(handle, inode);
40254209ae12SHarshad Shirwadkar 	if (unlikely(ret2))
40264209ae12SHarshad Shirwadkar 		ret = ret2;
402767a7d5f5SJan Kara 	if (ret >= 0)
402867a7d5f5SJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
402926a4c0c6STheodore Ts'o out_stop:
403026a4c0c6STheodore Ts'o 	ext4_journal_stop(handle);
403126a4c0c6STheodore Ts'o out_dio:
4032d4f5258eSJan Kara 	filemap_invalidate_unlock(mapping);
403326a4c0c6STheodore Ts'o out_mutex:
40345955102cSAl Viro 	inode_unlock(inode);
403526a4c0c6STheodore Ts'o 	return ret;
4036a4bb6b64SAllison Henderson }
4037a4bb6b64SAllison Henderson 
4038a361293fSJan Kara int ext4_inode_attach_jinode(struct inode *inode)
4039a361293fSJan Kara {
4040a361293fSJan Kara 	struct ext4_inode_info *ei = EXT4_I(inode);
4041a361293fSJan Kara 	struct jbd2_inode *jinode;
4042a361293fSJan Kara 
4043a361293fSJan Kara 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4044a361293fSJan Kara 		return 0;
4045a361293fSJan Kara 
4046a361293fSJan Kara 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4047a361293fSJan Kara 	spin_lock(&inode->i_lock);
4048a361293fSJan Kara 	if (!ei->jinode) {
4049a361293fSJan Kara 		if (!jinode) {
4050a361293fSJan Kara 			spin_unlock(&inode->i_lock);
4051a361293fSJan Kara 			return -ENOMEM;
4052a361293fSJan Kara 		}
4053a361293fSJan Kara 		ei->jinode = jinode;
4054a361293fSJan Kara 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4055a361293fSJan Kara 		jinode = NULL;
4056a361293fSJan Kara 	}
4057a361293fSJan Kara 	spin_unlock(&inode->i_lock);
4058a361293fSJan Kara 	if (unlikely(jinode != NULL))
4059a361293fSJan Kara 		jbd2_free_inode(jinode);
4060a361293fSJan Kara 	return 0;
4061a361293fSJan Kara }
4062a361293fSJan Kara 
4063a4bb6b64SAllison Henderson /*
4064617ba13bSMingming Cao  * ext4_truncate()
4065ac27a0ecSDave Kleikamp  *
4066617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
4067617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4068ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
4069ac27a0ecSDave Kleikamp  *
407042b2aa86SJustin P. Mattock  * As we work through the truncate and commit bits of it to the journal there
4071ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
4072ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
4073ac27a0ecSDave Kleikamp  *
4074ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
4075ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
4076ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
4077ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
4078ac27a0ecSDave Kleikamp  * left-to-right works OK too).
4079ac27a0ecSDave Kleikamp  *
4080ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
4081ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
4082ac27a0ecSDave Kleikamp  *
4083ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
4084617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4085ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
4086617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
4087617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
4088ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
4089617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
4090ac27a0ecSDave Kleikamp  */
40912c98eb5eSTheodore Ts'o int ext4_truncate(struct inode *inode)
4092ac27a0ecSDave Kleikamp {
4093819c4920STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
4094819c4920STheodore Ts'o 	unsigned int credits;
40954209ae12SHarshad Shirwadkar 	int err = 0, err2;
4096819c4920STheodore Ts'o 	handle_t *handle;
4097819c4920STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
4098819c4920STheodore Ts'o 
409919b5ef61STheodore Ts'o 	/*
410019b5ef61STheodore Ts'o 	 * There is a possibility that we're either freeing the inode
4101e04027e8SMatthew Wilcox 	 * or it's a completely new inode. In those cases we might not
4102f340b3d9Shongnanli 	 * have i_rwsem locked because it's not necessary.
410319b5ef61STheodore Ts'o 	 */
410419b5ef61STheodore Ts'o 	if (!(inode->i_state & (I_NEW|I_FREEING)))
41055955102cSAl Viro 		WARN_ON(!inode_is_locked(inode));
41060562e0baSJiaying Zhang 	trace_ext4_truncate_enter(inode);
41070562e0baSJiaying Zhang 
410891ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
41099a5d265fSzhengliang 		goto out_trace;
4110ac27a0ecSDave Kleikamp 
41115534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
411219f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
41137d8f9f7dSTheodore Ts'o 
4114aef1c851STao Ma 	if (ext4_has_inline_data(inode)) {
4115aef1c851STao Ma 		int has_inline = 1;
4116aef1c851STao Ma 
411701daf945STheodore Ts'o 		err = ext4_inline_data_truncate(inode, &has_inline);
41189a5d265fSzhengliang 		if (err || has_inline)
41199a5d265fSzhengliang 			goto out_trace;
4120aef1c851STao Ma 	}
4121aef1c851STao Ma 
4122a361293fSJan Kara 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4123a361293fSJan Kara 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4124a71248b1SBaokun Li 		err = ext4_inode_attach_jinode(inode);
4125a71248b1SBaokun Li 		if (err)
41269a5d265fSzhengliang 			goto out_trace;
4127a361293fSJan Kara 	}
4128a361293fSJan Kara 
4129ff9893dcSAmir Goldstein 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4130819c4920STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
4131ff9893dcSAmir Goldstein 	else
4132819c4920STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
4133819c4920STheodore Ts'o 
4134819c4920STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
41359a5d265fSzhengliang 	if (IS_ERR(handle)) {
41369a5d265fSzhengliang 		err = PTR_ERR(handle);
41379a5d265fSzhengliang 		goto out_trace;
41389a5d265fSzhengliang 	}
4139819c4920STheodore Ts'o 
4140eb3544c6SLukas Czerner 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4141eb3544c6SLukas Czerner 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4142819c4920STheodore Ts'o 
4143819c4920STheodore Ts'o 	/*
4144819c4920STheodore Ts'o 	 * We add the inode to the orphan list, so that if this
4145819c4920STheodore Ts'o 	 * truncate spans multiple transactions, and we crash, we will
4146819c4920STheodore Ts'o 	 * resume the truncate when the filesystem recovers.  It also
4147819c4920STheodore Ts'o 	 * marks the inode dirty, to catch the new size.
4148819c4920STheodore Ts'o 	 *
4149819c4920STheodore Ts'o 	 * Implication: the file must always be in a sane, consistent
4150819c4920STheodore Ts'o 	 * truncatable state while each transaction commits.
4151819c4920STheodore Ts'o 	 */
41522c98eb5eSTheodore Ts'o 	err = ext4_orphan_add(handle, inode);
41532c98eb5eSTheodore Ts'o 	if (err)
4154819c4920STheodore Ts'o 		goto out_stop;
4155819c4920STheodore Ts'o 
4156819c4920STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
4157819c4920STheodore Ts'o 
415827bc446eSbrookxu 	ext4_discard_preallocations(inode, 0);
4159819c4920STheodore Ts'o 
4160819c4920STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4161d0abb36dSTheodore Ts'o 		err = ext4_ext_truncate(handle, inode);
4162819c4920STheodore Ts'o 	else
4163819c4920STheodore Ts'o 		ext4_ind_truncate(handle, inode);
4164819c4920STheodore Ts'o 
4165819c4920STheodore Ts'o 	up_write(&ei->i_data_sem);
4166d0abb36dSTheodore Ts'o 	if (err)
4167d0abb36dSTheodore Ts'o 		goto out_stop;
4168819c4920STheodore Ts'o 
4169819c4920STheodore Ts'o 	if (IS_SYNC(inode))
4170819c4920STheodore Ts'o 		ext4_handle_sync(handle);
4171819c4920STheodore Ts'o 
4172819c4920STheodore Ts'o out_stop:
4173819c4920STheodore Ts'o 	/*
4174819c4920STheodore Ts'o 	 * If this was a simple ftruncate() and the file will remain alive,
4175819c4920STheodore Ts'o 	 * then we need to clear up the orphan record which we created above.
4176819c4920STheodore Ts'o 	 * However, if this was a real unlink then we were called by
417758d86a50SWang Shilong 	 * ext4_evict_inode(), and we allow that function to clean up the
4178819c4920STheodore Ts'o 	 * orphan info for us.
4179819c4920STheodore Ts'o 	 */
4180819c4920STheodore Ts'o 	if (inode->i_nlink)
4181819c4920STheodore Ts'o 		ext4_orphan_del(handle, inode);
4182819c4920STheodore Ts'o 
4183eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
41844209ae12SHarshad Shirwadkar 	err2 = ext4_mark_inode_dirty(handle, inode);
41854209ae12SHarshad Shirwadkar 	if (unlikely(err2 && !err))
41864209ae12SHarshad Shirwadkar 		err = err2;
4187819c4920STheodore Ts'o 	ext4_journal_stop(handle);
4188a86c6181SAlex Tomas 
41899a5d265fSzhengliang out_trace:
41900562e0baSJiaying Zhang 	trace_ext4_truncate_exit(inode);
41912c98eb5eSTheodore Ts'o 	return err;
4192ac27a0ecSDave Kleikamp }
4193ac27a0ecSDave Kleikamp 
41949a1bf32cSZhang Yi static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
41959a1bf32cSZhang Yi {
41969a1bf32cSZhang Yi 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
41979a1bf32cSZhang Yi 		return inode_peek_iversion_raw(inode);
41989a1bf32cSZhang Yi 	else
41999a1bf32cSZhang Yi 		return inode_peek_iversion(inode);
42009a1bf32cSZhang Yi }
42019a1bf32cSZhang Yi 
42029a1bf32cSZhang Yi static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
42039a1bf32cSZhang Yi 				 struct ext4_inode_info *ei)
42049a1bf32cSZhang Yi {
42059a1bf32cSZhang Yi 	struct inode *inode = &(ei->vfs_inode);
42069a1bf32cSZhang Yi 	u64 i_blocks = READ_ONCE(inode->i_blocks);
42079a1bf32cSZhang Yi 	struct super_block *sb = inode->i_sb;
42089a1bf32cSZhang Yi 
42099a1bf32cSZhang Yi 	if (i_blocks <= ~0U) {
42109a1bf32cSZhang Yi 		/*
42119a1bf32cSZhang Yi 		 * i_blocks can be represented in a 32 bit variable
42129a1bf32cSZhang Yi 		 * as multiple of 512 bytes
42139a1bf32cSZhang Yi 		 */
42149a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42159a1bf32cSZhang Yi 		raw_inode->i_blocks_high = 0;
42169a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
42179a1bf32cSZhang Yi 		return 0;
42189a1bf32cSZhang Yi 	}
42199a1bf32cSZhang Yi 
42209a1bf32cSZhang Yi 	/*
42219a1bf32cSZhang Yi 	 * This should never happen since sb->s_maxbytes should not have
42229a1bf32cSZhang Yi 	 * allowed this, sb->s_maxbytes was set according to the huge_file
42239a1bf32cSZhang Yi 	 * feature in ext4_fill_super().
42249a1bf32cSZhang Yi 	 */
42259a1bf32cSZhang Yi 	if (!ext4_has_feature_huge_file(sb))
42269a1bf32cSZhang Yi 		return -EFSCORRUPTED;
42279a1bf32cSZhang Yi 
42289a1bf32cSZhang Yi 	if (i_blocks <= 0xffffffffffffULL) {
42299a1bf32cSZhang Yi 		/*
42309a1bf32cSZhang Yi 		 * i_blocks can be represented in a 48 bit variable
42319a1bf32cSZhang Yi 		 * as multiple of 512 bytes
42329a1bf32cSZhang Yi 		 */
42339a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42349a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
42359a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
42369a1bf32cSZhang Yi 	} else {
42379a1bf32cSZhang Yi 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
42389a1bf32cSZhang Yi 		/* i_block is stored in file system block size */
42399a1bf32cSZhang Yi 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
42409a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42419a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
42429a1bf32cSZhang Yi 	}
42439a1bf32cSZhang Yi 	return 0;
42449a1bf32cSZhang Yi }
42459a1bf32cSZhang Yi 
42469a1bf32cSZhang Yi static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
42479a1bf32cSZhang Yi {
42489a1bf32cSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
42499a1bf32cSZhang Yi 	uid_t i_uid;
42509a1bf32cSZhang Yi 	gid_t i_gid;
42519a1bf32cSZhang Yi 	projid_t i_projid;
42529a1bf32cSZhang Yi 	int block;
42539a1bf32cSZhang Yi 	int err;
42549a1bf32cSZhang Yi 
42559a1bf32cSZhang Yi 	err = ext4_inode_blocks_set(raw_inode, ei);
42569a1bf32cSZhang Yi 
42579a1bf32cSZhang Yi 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
42589a1bf32cSZhang Yi 	i_uid = i_uid_read(inode);
42599a1bf32cSZhang Yi 	i_gid = i_gid_read(inode);
42609a1bf32cSZhang Yi 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
42619a1bf32cSZhang Yi 	if (!(test_opt(inode->i_sb, NO_UID32))) {
42629a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
42639a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
42649a1bf32cSZhang Yi 		/*
42659a1bf32cSZhang Yi 		 * Fix up interoperability with old kernels. Otherwise,
42669a1bf32cSZhang Yi 		 * old inodes get re-used with the upper 16 bits of the
42679a1bf32cSZhang Yi 		 * uid/gid intact.
42689a1bf32cSZhang Yi 		 */
42699a1bf32cSZhang Yi 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
42709a1bf32cSZhang Yi 			raw_inode->i_uid_high = 0;
42719a1bf32cSZhang Yi 			raw_inode->i_gid_high = 0;
42729a1bf32cSZhang Yi 		} else {
42739a1bf32cSZhang Yi 			raw_inode->i_uid_high =
42749a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_uid));
42759a1bf32cSZhang Yi 			raw_inode->i_gid_high =
42769a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_gid));
42779a1bf32cSZhang Yi 		}
42789a1bf32cSZhang Yi 	} else {
42799a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
42809a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
42819a1bf32cSZhang Yi 		raw_inode->i_uid_high = 0;
42829a1bf32cSZhang Yi 		raw_inode->i_gid_high = 0;
42839a1bf32cSZhang Yi 	}
42849a1bf32cSZhang Yi 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
42859a1bf32cSZhang Yi 
42869a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
42879a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
42889a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
42899a1bf32cSZhang Yi 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
42909a1bf32cSZhang Yi 
42919a1bf32cSZhang Yi 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
42929a1bf32cSZhang Yi 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
42939a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
42949a1bf32cSZhang Yi 		raw_inode->i_file_acl_high =
42959a1bf32cSZhang Yi 			cpu_to_le16(ei->i_file_acl >> 32);
42969a1bf32cSZhang Yi 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
42979a1bf32cSZhang Yi 	ext4_isize_set(raw_inode, ei->i_disksize);
42989a1bf32cSZhang Yi 
42999a1bf32cSZhang Yi 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
43009a1bf32cSZhang Yi 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
43019a1bf32cSZhang Yi 		if (old_valid_dev(inode->i_rdev)) {
43029a1bf32cSZhang Yi 			raw_inode->i_block[0] =
43039a1bf32cSZhang Yi 				cpu_to_le32(old_encode_dev(inode->i_rdev));
43049a1bf32cSZhang Yi 			raw_inode->i_block[1] = 0;
43059a1bf32cSZhang Yi 		} else {
43069a1bf32cSZhang Yi 			raw_inode->i_block[0] = 0;
43079a1bf32cSZhang Yi 			raw_inode->i_block[1] =
43089a1bf32cSZhang Yi 				cpu_to_le32(new_encode_dev(inode->i_rdev));
43099a1bf32cSZhang Yi 			raw_inode->i_block[2] = 0;
43109a1bf32cSZhang Yi 		}
43119a1bf32cSZhang Yi 	} else if (!ext4_has_inline_data(inode)) {
43129a1bf32cSZhang Yi 		for (block = 0; block < EXT4_N_BLOCKS; block++)
43139a1bf32cSZhang Yi 			raw_inode->i_block[block] = ei->i_data[block];
43149a1bf32cSZhang Yi 	}
43159a1bf32cSZhang Yi 
43169a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
43179a1bf32cSZhang Yi 		u64 ivers = ext4_inode_peek_iversion(inode);
43189a1bf32cSZhang Yi 
43199a1bf32cSZhang Yi 		raw_inode->i_disk_version = cpu_to_le32(ivers);
43209a1bf32cSZhang Yi 		if (ei->i_extra_isize) {
43219a1bf32cSZhang Yi 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
43229a1bf32cSZhang Yi 				raw_inode->i_version_hi =
43239a1bf32cSZhang Yi 					cpu_to_le32(ivers >> 32);
43249a1bf32cSZhang Yi 			raw_inode->i_extra_isize =
43259a1bf32cSZhang Yi 				cpu_to_le16(ei->i_extra_isize);
43269a1bf32cSZhang Yi 		}
43279a1bf32cSZhang Yi 	}
43289a1bf32cSZhang Yi 
43299a1bf32cSZhang Yi 	if (i_projid != EXT4_DEF_PROJID &&
43309a1bf32cSZhang Yi 	    !ext4_has_feature_project(inode->i_sb))
43319a1bf32cSZhang Yi 		err = err ?: -EFSCORRUPTED;
43329a1bf32cSZhang Yi 
43339a1bf32cSZhang Yi 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
43349a1bf32cSZhang Yi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
43359a1bf32cSZhang Yi 		raw_inode->i_projid = cpu_to_le32(i_projid);
43369a1bf32cSZhang Yi 
43379a1bf32cSZhang Yi 	ext4_inode_csum_set(inode, raw_inode, ei);
43389a1bf32cSZhang Yi 	return err;
43399a1bf32cSZhang Yi }
43409a1bf32cSZhang Yi 
4341ac27a0ecSDave Kleikamp /*
4342617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
4343de01f484SZhang Yi  * underlying buffer_head on success. If we pass 'inode' and it does not
4344de01f484SZhang Yi  * have in-inode xattr, we have all inode data in memory that is needed
4345de01f484SZhang Yi  * to recreate the on-disk version of this inode.
4346ac27a0ecSDave Kleikamp  */
43478016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4348de01f484SZhang Yi 				struct inode *inode, struct ext4_iloc *iloc,
43498016e29fSHarshad Shirwadkar 				ext4_fsblk_t *ret_block)
4350ac27a0ecSDave Kleikamp {
4351240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
4352ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
4353240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
435402f03c42SLinus Torvalds 	struct blk_plug		plug;
4355240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
4356ac27a0ecSDave Kleikamp 
43573a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
43588016e29fSHarshad Shirwadkar 	if (ino < EXT4_ROOT_INO ||
43598016e29fSHarshad Shirwadkar 	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
43606a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4361ac27a0ecSDave Kleikamp 
43628016e29fSHarshad Shirwadkar 	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4363240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4364240799cdSTheodore Ts'o 	if (!gdp)
4365240799cdSTheodore Ts'o 		return -EIO;
4366240799cdSTheodore Ts'o 
4367240799cdSTheodore Ts'o 	/*
4368240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
4369240799cdSTheodore Ts'o 	 */
437000d09882STao Ma 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
43718016e29fSHarshad Shirwadkar 	inode_offset = ((ino - 1) %
4372240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
4373240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4374240799cdSTheodore Ts'o 
4375eee22187SBaokun Li 	block = ext4_inode_table(sb, gdp);
4376eee22187SBaokun Li 	if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4377eee22187SBaokun Li 	    (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4378eee22187SBaokun Li 		ext4_error(sb, "Invalid inode table block %llu in "
4379eee22187SBaokun Li 			   "block_group %u", block, iloc->block_group);
4380eee22187SBaokun Li 		return -EFSCORRUPTED;
4381eee22187SBaokun Li 	}
4382eee22187SBaokun Li 	block += (inode_offset / inodes_per_block);
4383eee22187SBaokun Li 
4384240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
4385aebf0243SWang Shilong 	if (unlikely(!bh))
4386860d21e2STheodore Ts'o 		return -ENOMEM;
43878e33fadfSZhang Yi 	if (ext4_buffer_uptodate(bh))
4388ac27a0ecSDave Kleikamp 		goto has_buffer;
4389ac27a0ecSDave Kleikamp 
43908e33fadfSZhang Yi 	lock_buffer(bh);
4391f2c77973SZhang Yi 	if (ext4_buffer_uptodate(bh)) {
4392f2c77973SZhang Yi 		/* Someone brought it uptodate while we waited */
4393f2c77973SZhang Yi 		unlock_buffer(bh);
4394f2c77973SZhang Yi 		goto has_buffer;
4395f2c77973SZhang Yi 	}
4396f2c77973SZhang Yi 
4397ac27a0ecSDave Kleikamp 	/*
4398ac27a0ecSDave Kleikamp 	 * If we have all information of the inode in memory and this
4399ac27a0ecSDave Kleikamp 	 * is the only valid inode in the block, we need not read the
4400ac27a0ecSDave Kleikamp 	 * block.
4401ac27a0ecSDave Kleikamp 	 */
4402de01f484SZhang Yi 	if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4403ac27a0ecSDave Kleikamp 		struct buffer_head *bitmap_bh;
4404240799cdSTheodore Ts'o 		int i, start;
4405ac27a0ecSDave Kleikamp 
4406240799cdSTheodore Ts'o 		start = inode_offset & ~(inodes_per_block - 1);
4407ac27a0ecSDave Kleikamp 
4408ac27a0ecSDave Kleikamp 		/* Is the inode bitmap in cache? */
4409240799cdSTheodore Ts'o 		bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4410aebf0243SWang Shilong 		if (unlikely(!bitmap_bh))
4411ac27a0ecSDave Kleikamp 			goto make_io;
4412ac27a0ecSDave Kleikamp 
4413ac27a0ecSDave Kleikamp 		/*
4414ac27a0ecSDave Kleikamp 		 * If the inode bitmap isn't in cache then the
4415ac27a0ecSDave Kleikamp 		 * optimisation may end up performing two reads instead
4416ac27a0ecSDave Kleikamp 		 * of one, so skip it.
4417ac27a0ecSDave Kleikamp 		 */
4418ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bitmap_bh)) {
4419ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
4420ac27a0ecSDave Kleikamp 			goto make_io;
4421ac27a0ecSDave Kleikamp 		}
4422240799cdSTheodore Ts'o 		for (i = start; i < start + inodes_per_block; i++) {
4423ac27a0ecSDave Kleikamp 			if (i == inode_offset)
4424ac27a0ecSDave Kleikamp 				continue;
4425617ba13bSMingming Cao 			if (ext4_test_bit(i, bitmap_bh->b_data))
4426ac27a0ecSDave Kleikamp 				break;
4427ac27a0ecSDave Kleikamp 		}
4428ac27a0ecSDave Kleikamp 		brelse(bitmap_bh);
4429240799cdSTheodore Ts'o 		if (i == start + inodes_per_block) {
4430de01f484SZhang Yi 			struct ext4_inode *raw_inode =
4431de01f484SZhang Yi 				(struct ext4_inode *) (bh->b_data + iloc->offset);
4432de01f484SZhang Yi 
4433ac27a0ecSDave Kleikamp 			/* all other inodes are free, so skip I/O */
4434ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, bh->b_size);
4435de01f484SZhang Yi 			if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4436de01f484SZhang Yi 				ext4_fill_raw_inode(inode, raw_inode);
4437ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
4438ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
4439ac27a0ecSDave Kleikamp 			goto has_buffer;
4440ac27a0ecSDave Kleikamp 		}
4441ac27a0ecSDave Kleikamp 	}
4442ac27a0ecSDave Kleikamp 
4443ac27a0ecSDave Kleikamp make_io:
4444ac27a0ecSDave Kleikamp 	/*
4445240799cdSTheodore Ts'o 	 * If we need to do any I/O, try to pre-readahead extra
4446240799cdSTheodore Ts'o 	 * blocks from the inode table.
4447240799cdSTheodore Ts'o 	 */
444802f03c42SLinus Torvalds 	blk_start_plug(&plug);
4449240799cdSTheodore Ts'o 	if (EXT4_SB(sb)->s_inode_readahead_blks) {
4450240799cdSTheodore Ts'o 		ext4_fsblk_t b, end, table;
4451240799cdSTheodore Ts'o 		unsigned num;
44520d606e2cSTheodore Ts'o 		__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4453240799cdSTheodore Ts'o 
4454240799cdSTheodore Ts'o 		table = ext4_inode_table(sb, gdp);
4455b713a5ecSTheodore Ts'o 		/* s_inode_readahead_blks is always a power of 2 */
44560d606e2cSTheodore Ts'o 		b = block & ~((ext4_fsblk_t) ra_blks - 1);
4457240799cdSTheodore Ts'o 		if (table > b)
4458240799cdSTheodore Ts'o 			b = table;
44590d606e2cSTheodore Ts'o 		end = b + ra_blks;
4460240799cdSTheodore Ts'o 		num = EXT4_INODES_PER_GROUP(sb);
4461feb0ab32SDarrick J. Wong 		if (ext4_has_group_desc_csum(sb))
4462560671a0SAneesh Kumar K.V 			num -= ext4_itable_unused_count(sb, gdp);
4463240799cdSTheodore Ts'o 		table += num / inodes_per_block;
4464240799cdSTheodore Ts'o 		if (end > table)
4465240799cdSTheodore Ts'o 			end = table;
4466240799cdSTheodore Ts'o 		while (b <= end)
44675df1d412Szhangyi (F) 			ext4_sb_breadahead_unmovable(sb, b++);
4468240799cdSTheodore Ts'o 	}
4469240799cdSTheodore Ts'o 
4470240799cdSTheodore Ts'o 	/*
4471ac27a0ecSDave Kleikamp 	 * There are other valid inodes in the buffer, this inode
4472ac27a0ecSDave Kleikamp 	 * has in-inode xattrs, or we don't have this inode in memory.
4473ac27a0ecSDave Kleikamp 	 * Read the block from disk.
4474ac27a0ecSDave Kleikamp 	 */
44758016e29fSHarshad Shirwadkar 	trace_ext4_load_inode(sb, ino);
44762d069c08Szhangyi (F) 	ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
447702f03c42SLinus Torvalds 	blk_finish_plug(&plug);
4478ac27a0ecSDave Kleikamp 	wait_on_buffer(bh);
44790904c9aeSZhang Yi 	ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4480ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
44818016e29fSHarshad Shirwadkar 		if (ret_block)
44828016e29fSHarshad Shirwadkar 			*ret_block = block;
4483ac27a0ecSDave Kleikamp 		brelse(bh);
4484ac27a0ecSDave Kleikamp 		return -EIO;
4485ac27a0ecSDave Kleikamp 	}
4486ac27a0ecSDave Kleikamp has_buffer:
4487ac27a0ecSDave Kleikamp 	iloc->bh = bh;
4488ac27a0ecSDave Kleikamp 	return 0;
4489ac27a0ecSDave Kleikamp }
4490ac27a0ecSDave Kleikamp 
44918016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc_noinmem(struct inode *inode,
44928016e29fSHarshad Shirwadkar 					struct ext4_iloc *iloc)
44938016e29fSHarshad Shirwadkar {
4494c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
44958016e29fSHarshad Shirwadkar 	int ret;
44968016e29fSHarshad Shirwadkar 
4497de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
44988016e29fSHarshad Shirwadkar 					&err_blk);
44998016e29fSHarshad Shirwadkar 
45008016e29fSHarshad Shirwadkar 	if (ret == -EIO)
45018016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
45028016e29fSHarshad Shirwadkar 					"unable to read itable block");
45038016e29fSHarshad Shirwadkar 
45048016e29fSHarshad Shirwadkar 	return ret;
45058016e29fSHarshad Shirwadkar }
45068016e29fSHarshad Shirwadkar 
4507617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4508ac27a0ecSDave Kleikamp {
4509c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
45108016e29fSHarshad Shirwadkar 	int ret;
45118016e29fSHarshad Shirwadkar 
4512de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4513de01f484SZhang Yi 					&err_blk);
45148016e29fSHarshad Shirwadkar 
45158016e29fSHarshad Shirwadkar 	if (ret == -EIO)
45168016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
45178016e29fSHarshad Shirwadkar 					"unable to read itable block");
45188016e29fSHarshad Shirwadkar 
45198016e29fSHarshad Shirwadkar 	return ret;
45208016e29fSHarshad Shirwadkar }
45218016e29fSHarshad Shirwadkar 
45228016e29fSHarshad Shirwadkar 
45238016e29fSHarshad Shirwadkar int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
45248016e29fSHarshad Shirwadkar 			  struct ext4_iloc *iloc)
45258016e29fSHarshad Shirwadkar {
4526de01f484SZhang Yi 	return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4527ac27a0ecSDave Kleikamp }
4528ac27a0ecSDave Kleikamp 
4529a8ab6d38SIra Weiny static bool ext4_should_enable_dax(struct inode *inode)
45306642586bSRoss Zwisler {
4531a8ab6d38SIra Weiny 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4532a8ab6d38SIra Weiny 
45339cb20f94SIra Weiny 	if (test_opt2(inode->i_sb, DAX_NEVER))
45346642586bSRoss Zwisler 		return false;
45356642586bSRoss Zwisler 	if (!S_ISREG(inode->i_mode))
45366642586bSRoss Zwisler 		return false;
45376642586bSRoss Zwisler 	if (ext4_should_journal_data(inode))
45386642586bSRoss Zwisler 		return false;
45396642586bSRoss Zwisler 	if (ext4_has_inline_data(inode))
45406642586bSRoss Zwisler 		return false;
4541592ddec7SChandan Rajendra 	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
45426642586bSRoss Zwisler 		return false;
4543c93d8f88SEric Biggers 	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4544c93d8f88SEric Biggers 		return false;
4545a8ab6d38SIra Weiny 	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4546a8ab6d38SIra Weiny 		return false;
4547a8ab6d38SIra Weiny 	if (test_opt(inode->i_sb, DAX_ALWAYS))
45486642586bSRoss Zwisler 		return true;
4549a8ab6d38SIra Weiny 
4550b383a73fSIra Weiny 	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
45516642586bSRoss Zwisler }
45526642586bSRoss Zwisler 
4553043546e4SIra Weiny void ext4_set_inode_flags(struct inode *inode, bool init)
4554ac27a0ecSDave Kleikamp {
4555617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
455600a1a053STheodore Ts'o 	unsigned int new_fl = 0;
4557ac27a0ecSDave Kleikamp 
4558043546e4SIra Weiny 	WARN_ON_ONCE(IS_DAX(inode) && init);
4559043546e4SIra Weiny 
4560617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
456100a1a053STheodore Ts'o 		new_fl |= S_SYNC;
4562617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
456300a1a053STheodore Ts'o 		new_fl |= S_APPEND;
4564617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
456500a1a053STheodore Ts'o 		new_fl |= S_IMMUTABLE;
4566617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
456700a1a053STheodore Ts'o 		new_fl |= S_NOATIME;
4568617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
456900a1a053STheodore Ts'o 		new_fl |= S_DIRSYNC;
4570043546e4SIra Weiny 
4571043546e4SIra Weiny 	/* Because of the way inode_set_flags() works we must preserve S_DAX
4572043546e4SIra Weiny 	 * here if already set. */
4573043546e4SIra Weiny 	new_fl |= (inode->i_flags & S_DAX);
4574043546e4SIra Weiny 	if (init && ext4_should_enable_dax(inode))
4575923ae0ffSRoss Zwisler 		new_fl |= S_DAX;
4576043546e4SIra Weiny 
45772ee6a576SEric Biggers 	if (flags & EXT4_ENCRYPT_FL)
45782ee6a576SEric Biggers 		new_fl |= S_ENCRYPTED;
4579b886ee3eSGabriel Krisman Bertazi 	if (flags & EXT4_CASEFOLD_FL)
4580b886ee3eSGabriel Krisman Bertazi 		new_fl |= S_CASEFOLD;
4581c93d8f88SEric Biggers 	if (flags & EXT4_VERITY_FL)
4582c93d8f88SEric Biggers 		new_fl |= S_VERITY;
45835f16f322STheodore Ts'o 	inode_set_flags(inode, new_fl,
45842ee6a576SEric Biggers 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4585c93d8f88SEric Biggers 			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4586ac27a0ecSDave Kleikamp }
4587ac27a0ecSDave Kleikamp 
45880fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
45890fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
45900fc1b451SAneesh Kumar K.V {
45910fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
45928180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
45938180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
45940fc1b451SAneesh Kumar K.V 
4595e2b911c5SDarrick J. Wong 	if (ext4_has_feature_huge_file(sb)) {
45960fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
45970fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
45980fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
459907a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
46008180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
46018180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
46028180a562SAneesh Kumar K.V 		} else {
46030fc1b451SAneesh Kumar K.V 			return i_blocks;
46048180a562SAneesh Kumar K.V 		}
46050fc1b451SAneesh Kumar K.V 	} else {
46060fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
46070fc1b451SAneesh Kumar K.V 	}
46080fc1b451SAneesh Kumar K.V }
4609ff9ddf7eSJan Kara 
4610eb9b5f01STheodore Ts'o static inline int ext4_iget_extra_inode(struct inode *inode,
4611152a7b0aSTao Ma 					 struct ext4_inode *raw_inode,
4612152a7b0aSTao Ma 					 struct ext4_inode_info *ei)
4613152a7b0aSTao Ma {
4614152a7b0aSTao Ma 	__le32 *magic = (void *)raw_inode +
4615152a7b0aSTao Ma 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4616eb9b5f01STheodore Ts'o 
4617fd7e672eSBaokun Li 	if (EXT4_INODE_HAS_XATTR_SPACE(inode)  &&
4618290ab230SEric Biggers 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
46191dcdce59SYe Bin 		int err;
46201dcdce59SYe Bin 
4621152a7b0aSTao Ma 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
46221dcdce59SYe Bin 		err = ext4_find_inline_data_nolock(inode);
46231dcdce59SYe Bin 		if (!err && ext4_has_inline_data(inode))
46241dcdce59SYe Bin 			ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
46251dcdce59SYe Bin 		return err;
4626f19d5870STao Ma 	} else
4627f19d5870STao Ma 		EXT4_I(inode)->i_inline_off = 0;
4628eb9b5f01STheodore Ts'o 	return 0;
4629152a7b0aSTao Ma }
4630152a7b0aSTao Ma 
4631040cb378SLi Xi int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4632040cb378SLi Xi {
46330b7b7779SKaho Ng 	if (!ext4_has_feature_project(inode->i_sb))
4634040cb378SLi Xi 		return -EOPNOTSUPP;
4635040cb378SLi Xi 	*projid = EXT4_I(inode)->i_projid;
4636040cb378SLi Xi 	return 0;
4637040cb378SLi Xi }
4638040cb378SLi Xi 
4639e254d1afSEryu Guan /*
4640e254d1afSEryu Guan  * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4641e254d1afSEryu Guan  * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4642e254d1afSEryu Guan  * set.
4643e254d1afSEryu Guan  */
4644e254d1afSEryu Guan static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4645e254d1afSEryu Guan {
4646e254d1afSEryu Guan 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4647e254d1afSEryu Guan 		inode_set_iversion_raw(inode, val);
4648e254d1afSEryu Guan 	else
4649e254d1afSEryu Guan 		inode_set_iversion_queried(inode, val);
4650e254d1afSEryu Guan }
4651e254d1afSEryu Guan 
4652b3e6bcb9STheodore Ts'o static const char *check_igot_inode(struct inode *inode, ext4_iget_flags flags)
4653b3e6bcb9STheodore Ts'o 
4654b3e6bcb9STheodore Ts'o {
4655b3e6bcb9STheodore Ts'o 	if (flags & EXT4_IGET_EA_INODE) {
4656b3e6bcb9STheodore Ts'o 		if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4657b3e6bcb9STheodore Ts'o 			return "missing EA_INODE flag";
46582bc7e7c1STheodore Ts'o 		if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
46592bc7e7c1STheodore Ts'o 		    EXT4_I(inode)->i_file_acl)
46602bc7e7c1STheodore Ts'o 			return "ea_inode with extended attributes";
4661b3e6bcb9STheodore Ts'o 	} else {
4662b3e6bcb9STheodore Ts'o 		if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4663b3e6bcb9STheodore Ts'o 			return "unexpected EA_INODE flag";
4664b3e6bcb9STheodore Ts'o 	}
4665b3e6bcb9STheodore Ts'o 	if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD))
4666b3e6bcb9STheodore Ts'o 		return "unexpected bad inode w/o EXT4_IGET_BAD";
4667b3e6bcb9STheodore Ts'o 	return NULL;
4668b3e6bcb9STheodore Ts'o }
4669b3e6bcb9STheodore Ts'o 
46708a363970STheodore Ts'o struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
46718a363970STheodore Ts'o 			  ext4_iget_flags flags, const char *function,
46728a363970STheodore Ts'o 			  unsigned int line)
4673ac27a0ecSDave Kleikamp {
4674617ba13bSMingming Cao 	struct ext4_iloc iloc;
4675617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
46761d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
4677bd2c38cfSJan Kara 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
46781d1fe1eeSDavid Howells 	struct inode *inode;
4679b3e6bcb9STheodore Ts'o 	const char *err_str;
4680b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
46811d1fe1eeSDavid Howells 	long ret;
46827e6e1ef4SDarrick J. Wong 	loff_t size;
4683ac27a0ecSDave Kleikamp 	int block;
468408cefc7aSEric W. Biederman 	uid_t i_uid;
468508cefc7aSEric W. Biederman 	gid_t i_gid;
4686040cb378SLi Xi 	projid_t i_projid;
4687ac27a0ecSDave Kleikamp 
4688191ce178STheodore Ts'o 	if ((!(flags & EXT4_IGET_SPECIAL) &&
4689bd2c38cfSJan Kara 	     ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4690bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_usr_quota_inum) ||
4691bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_grp_quota_inum) ||
469202f310fcSJan Kara 	      ino == le32_to_cpu(es->s_prj_quota_inum) ||
469302f310fcSJan Kara 	      ino == le32_to_cpu(es->s_orphan_file_inum))) ||
46948a363970STheodore Ts'o 	    (ino < EXT4_ROOT_INO) ||
4695bd2c38cfSJan Kara 	    (ino > le32_to_cpu(es->s_inodes_count))) {
46968a363970STheodore Ts'o 		if (flags & EXT4_IGET_HANDLE)
46978a363970STheodore Ts'o 			return ERR_PTR(-ESTALE);
4698014c9caaSJan Kara 		__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
46998a363970STheodore Ts'o 			     "inode #%lu: comm %s: iget: illegal inode #",
47008a363970STheodore Ts'o 			     ino, current->comm);
47018a363970STheodore Ts'o 		return ERR_PTR(-EFSCORRUPTED);
47028a363970STheodore Ts'o 	}
47038a363970STheodore Ts'o 
47041d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
47051d1fe1eeSDavid Howells 	if (!inode)
47061d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
4707b3e6bcb9STheodore Ts'o 	if (!(inode->i_state & I_NEW)) {
4708b3e6bcb9STheodore Ts'o 		if ((err_str = check_igot_inode(inode, flags)) != NULL) {
4709b3e6bcb9STheodore Ts'o 			ext4_error_inode(inode, function, line, 0, err_str);
4710b3e6bcb9STheodore Ts'o 			iput(inode);
4711b3e6bcb9STheodore Ts'o 			return ERR_PTR(-EFSCORRUPTED);
4712b3e6bcb9STheodore Ts'o 		}
47131d1fe1eeSDavid Howells 		return inode;
4714b3e6bcb9STheodore Ts'o 	}
47151d1fe1eeSDavid Howells 
47161d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
47177dc57615SPeter Huewe 	iloc.bh = NULL;
4718ac27a0ecSDave Kleikamp 
47198016e29fSHarshad Shirwadkar 	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
47201d1fe1eeSDavid Howells 	if (ret < 0)
4721ac27a0ecSDave Kleikamp 		goto bad_inode;
4722617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
4723814525f4SDarrick J. Wong 
47248a363970STheodore Ts'o 	if ((flags & EXT4_IGET_HANDLE) &&
47258a363970STheodore Ts'o 	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
47268a363970STheodore Ts'o 		ret = -ESTALE;
47278a363970STheodore Ts'o 		goto bad_inode;
47288a363970STheodore Ts'o 	}
47298a363970STheodore Ts'o 
4730814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4731814525f4SDarrick J. Wong 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4732814525f4SDarrick J. Wong 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
47332dc8d9e1SEric Biggers 			EXT4_INODE_SIZE(inode->i_sb) ||
47342dc8d9e1SEric Biggers 		    (ei->i_extra_isize & 3)) {
47358a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
47368a363970STheodore Ts'o 					 "iget: bad extra_isize %u "
47378a363970STheodore Ts'o 					 "(inode size %u)",
47382dc8d9e1SEric Biggers 					 ei->i_extra_isize,
4739814525f4SDarrick J. Wong 					 EXT4_INODE_SIZE(inode->i_sb));
47406a797d27SDarrick J. Wong 			ret = -EFSCORRUPTED;
4741814525f4SDarrick J. Wong 			goto bad_inode;
4742814525f4SDarrick J. Wong 		}
4743814525f4SDarrick J. Wong 	} else
4744814525f4SDarrick J. Wong 		ei->i_extra_isize = 0;
4745814525f4SDarrick J. Wong 
4746814525f4SDarrick J. Wong 	/* Precompute checksum seed for inode metadata */
47479aa5d32bSDmitry Monakhov 	if (ext4_has_metadata_csum(sb)) {
4748814525f4SDarrick J. Wong 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4749814525f4SDarrick J. Wong 		__u32 csum;
4750814525f4SDarrick J. Wong 		__le32 inum = cpu_to_le32(inode->i_ino);
4751814525f4SDarrick J. Wong 		__le32 gen = raw_inode->i_generation;
4752814525f4SDarrick J. Wong 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4753814525f4SDarrick J. Wong 				   sizeof(inum));
4754814525f4SDarrick J. Wong 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4755814525f4SDarrick J. Wong 					      sizeof(gen));
4756814525f4SDarrick J. Wong 	}
4757814525f4SDarrick J. Wong 
47588016e29fSHarshad Shirwadkar 	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
47598016e29fSHarshad Shirwadkar 	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
47608016e29fSHarshad Shirwadkar 	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
47618016e29fSHarshad Shirwadkar 		ext4_error_inode_err(inode, function, line, 0,
47628016e29fSHarshad Shirwadkar 				EFSBADCRC, "iget: checksum invalid");
47636a797d27SDarrick J. Wong 		ret = -EFSBADCRC;
4764814525f4SDarrick J. Wong 		goto bad_inode;
4765814525f4SDarrick J. Wong 	}
4766814525f4SDarrick J. Wong 
4767ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
476808cefc7aSEric W. Biederman 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
476908cefc7aSEric W. Biederman 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
47700b7b7779SKaho Ng 	if (ext4_has_feature_project(sb) &&
4771040cb378SLi Xi 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4772040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4773040cb378SLi Xi 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4774040cb378SLi Xi 	else
4775040cb378SLi Xi 		i_projid = EXT4_DEF_PROJID;
4776040cb378SLi Xi 
4777ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
477808cefc7aSEric W. Biederman 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
477908cefc7aSEric W. Biederman 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4780ac27a0ecSDave Kleikamp 	}
478108cefc7aSEric W. Biederman 	i_uid_write(inode, i_uid);
478208cefc7aSEric W. Biederman 	i_gid_write(inode, i_gid);
4783040cb378SLi Xi 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4784bfe86848SMiklos Szeredi 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4785ac27a0ecSDave Kleikamp 
4786353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
478767cf5b09STao Ma 	ei->i_inline_off = 0;
4788ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
4789ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4790ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
4791ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
4792ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
4793ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
4794ac27a0ecSDave Kleikamp 	 */
4795ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
47965cd74028SBaokun Li 		if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
4797393d1d1dSDr. Tilmann Bubeck 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4798393d1d1dSDr. Tilmann Bubeck 		    ino != EXT4_BOOT_LOADER_INO) {
47995cd74028SBaokun Li 			/* this inode is deleted or unallocated */
48005cd74028SBaokun Li 			if (flags & EXT4_IGET_SPECIAL) {
48015cd74028SBaokun Li 				ext4_error_inode(inode, function, line, 0,
48025cd74028SBaokun Li 						 "iget: special inode unallocated");
48035cd74028SBaokun Li 				ret = -EFSCORRUPTED;
48045cd74028SBaokun Li 			} else
48051d1fe1eeSDavid Howells 				ret = -ESTALE;
4806ac27a0ecSDave Kleikamp 			goto bad_inode;
4807ac27a0ecSDave Kleikamp 		}
4808ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
4809ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
4810ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
4811393d1d1dSDr. Tilmann Bubeck 		 * the process of deleting those.
4812393d1d1dSDr. Tilmann Bubeck 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4813393d1d1dSDr. Tilmann Bubeck 		 * not initialized on a new filesystem. */
4814ac27a0ecSDave Kleikamp 	}
4815ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4816043546e4SIra Weiny 	ext4_set_inode_flags(inode, true);
48170fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
48187973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4819e2b911c5SDarrick J. Wong 	if (ext4_has_feature_64bit(sb))
4820a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
4821a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4822e08ac99fSArtem Blagodarenko 	inode->i_size = ext4_isize(sb, raw_inode);
48237e6e1ef4SDarrick J. Wong 	if ((size = i_size_read(inode)) < 0) {
48248a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
48258a363970STheodore Ts'o 				 "iget: bad i_size value: %lld", size);
48267e6e1ef4SDarrick J. Wong 		ret = -EFSCORRUPTED;
48277e6e1ef4SDarrick J. Wong 		goto bad_inode;
48287e6e1ef4SDarrick J. Wong 	}
482948a34311SJan Kara 	/*
483048a34311SJan Kara 	 * If dir_index is not enabled but there's dir with INDEX flag set,
483148a34311SJan Kara 	 * we'd normally treat htree data as empty space. But with metadata
483248a34311SJan Kara 	 * checksumming that corrupts checksums so forbid that.
483348a34311SJan Kara 	 */
483448a34311SJan Kara 	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
483548a34311SJan Kara 	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
483648a34311SJan Kara 		ext4_error_inode(inode, function, line, 0,
483748a34311SJan Kara 			 "iget: Dir with htree data on filesystem without dir_index feature.");
483848a34311SJan Kara 		ret = -EFSCORRUPTED;
483948a34311SJan Kara 		goto bad_inode;
484048a34311SJan Kara 	}
4841ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
4842a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
4843a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
4844a9e7f447SDmitry Monakhov #endif
4845ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4846ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
4847a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
4848ac27a0ecSDave Kleikamp 	/*
4849ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
4850ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4851ac27a0ecSDave Kleikamp 	 */
4852617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4853ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
4854ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
4855aa75f4d3SHarshad Shirwadkar 	ext4_fc_init_inode(&ei->vfs_inode);
4856ac27a0ecSDave Kleikamp 
4857b436b9beSJan Kara 	/*
4858b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
4859b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
4860b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
4861b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
4862b436b9beSJan Kara 	 * now it is reread from disk.
4863b436b9beSJan Kara 	 */
4864b436b9beSJan Kara 	if (journal) {
4865b436b9beSJan Kara 		transaction_t *transaction;
4866b436b9beSJan Kara 		tid_t tid;
4867b436b9beSJan Kara 
4868a931da6aSTheodore Ts'o 		read_lock(&journal->j_state_lock);
4869b436b9beSJan Kara 		if (journal->j_running_transaction)
4870b436b9beSJan Kara 			transaction = journal->j_running_transaction;
4871b436b9beSJan Kara 		else
4872b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
4873b436b9beSJan Kara 		if (transaction)
4874b436b9beSJan Kara 			tid = transaction->t_tid;
4875b436b9beSJan Kara 		else
4876b436b9beSJan Kara 			tid = journal->j_commit_sequence;
4877a931da6aSTheodore Ts'o 		read_unlock(&journal->j_state_lock);
4878b436b9beSJan Kara 		ei->i_sync_tid = tid;
4879b436b9beSJan Kara 		ei->i_datasync_tid = tid;
4880b436b9beSJan Kara 	}
4881b436b9beSJan Kara 
48820040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4883ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
4884ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
48852dc8d9e1SEric Biggers 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4886617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4887617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
4888ac27a0ecSDave Kleikamp 		} else {
4889eb9b5f01STheodore Ts'o 			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4890eb9b5f01STheodore Ts'o 			if (ret)
4891eb9b5f01STheodore Ts'o 				goto bad_inode;
4892ac27a0ecSDave Kleikamp 		}
4893814525f4SDarrick J. Wong 	}
4894ac27a0ecSDave Kleikamp 
4895ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4896ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4897ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4898ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4899ef7f3835SKalpak Shah 
4900ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4901ee73f9a5SJeff Layton 		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4902ee73f9a5SJeff Layton 
490325ec56b5SJean Noel Cordenner 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
490425ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4905ee73f9a5SJeff Layton 				ivers |=
490625ec56b5SJean Noel Cordenner 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
490725ec56b5SJean Noel Cordenner 		}
4908e254d1afSEryu Guan 		ext4_inode_set_iversion_queried(inode, ivers);
4909c4f65706STheodore Ts'o 	}
491025ec56b5SJean Noel Cordenner 
4911c4b5a614STheodore Ts'o 	ret = 0;
4912485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
4913ce9f24ccSJan Kara 	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
49148a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
49158a363970STheodore Ts'o 				 "iget: bad extended attribute block %llu",
491624676da4STheodore Ts'o 				 ei->i_file_acl);
49176a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
4918485c26ecSTheodore Ts'o 		goto bad_inode;
4919f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
4920bc716523SLiu Song 		/* validate the block references in the inode */
49218016e29fSHarshad Shirwadkar 		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
49228016e29fSHarshad Shirwadkar 			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4923fe2c8191SThiemo Nagel 			(S_ISLNK(inode->i_mode) &&
49248016e29fSHarshad Shirwadkar 			!ext4_inode_is_fast_symlink(inode)))) {
4925bc716523SLiu Song 			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4926bc716523SLiu Song 				ret = ext4_ext_check_inode(inode);
4927bc716523SLiu Song 			else
49281f7d1e77STheodore Ts'o 				ret = ext4_ind_check_inode(inode);
4929fe2c8191SThiemo Nagel 		}
4930f19d5870STao Ma 	}
4931567f3e9aSTheodore Ts'o 	if (ret)
49327a262f7cSAneesh Kumar K.V 		goto bad_inode;
49337a262f7cSAneesh Kumar K.V 
4934ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
4935617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
4936617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
4937617ba13bSMingming Cao 		ext4_set_aops(inode);
4938ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
4939617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
4940617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
4941ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
49426390d33bSLuis R. Rodriguez 		/* VFS does not allow setting these so must be corruption */
49436390d33bSLuis R. Rodriguez 		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
49448a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
49458a363970STheodore Ts'o 					 "iget: immutable or append flags "
49468a363970STheodore Ts'o 					 "not allowed on symlinks");
49476390d33bSLuis R. Rodriguez 			ret = -EFSCORRUPTED;
49486390d33bSLuis R. Rodriguez 			goto bad_inode;
49496390d33bSLuis R. Rodriguez 		}
4950592ddec7SChandan Rajendra 		if (IS_ENCRYPTED(inode)) {
4951a7a67e8aSAl Viro 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
4952a7a67e8aSAl Viro 		} else if (ext4_inode_is_fast_symlink(inode)) {
495375e7566bSAl Viro 			inode->i_link = (char *)ei->i_data;
4954617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
4955e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
4956e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
4957e83c1397SDuane Griffin 		} else {
4958617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
4959ac27a0ecSDave Kleikamp 		}
4960563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4961563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4962617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
4963ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
4964ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
4965ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4966ac27a0ecSDave Kleikamp 		else
4967ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
4968ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4969393d1d1dSDr. Tilmann Bubeck 	} else if (ino == EXT4_BOOT_LOADER_INO) {
4970393d1d1dSDr. Tilmann Bubeck 		make_bad_inode(inode);
4971563bdd61STheodore Ts'o 	} else {
49726a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
49738a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
49748a363970STheodore Ts'o 				 "iget: bogus i_mode (%o)", inode->i_mode);
4975563bdd61STheodore Ts'o 		goto bad_inode;
4976ac27a0ecSDave Kleikamp 	}
4977*8216776cSEric Biggers 	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb)) {
49786456ca65STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
49796456ca65STheodore Ts'o 				 "casefold flag without casefold feature");
4980*8216776cSEric Biggers 		ret = -EFSCORRUPTED;
4981*8216776cSEric Biggers 		goto bad_inode;
4982*8216776cSEric Biggers 	}
4983b3e6bcb9STheodore Ts'o 	if ((err_str = check_igot_inode(inode, flags)) != NULL) {
4984b3e6bcb9STheodore Ts'o 		ext4_error_inode(inode, function, line, 0, err_str);
4985b3e6bcb9STheodore Ts'o 		ret = -EFSCORRUPTED;
498663b1e9bcSBaokun Li 		goto bad_inode;
498763b1e9bcSBaokun Li 	}
4988dec214d0STahsin Erdogan 
498963b1e9bcSBaokun Li 	brelse(iloc.bh);
49901d1fe1eeSDavid Howells 	unlock_new_inode(inode);
49911d1fe1eeSDavid Howells 	return inode;
4992ac27a0ecSDave Kleikamp 
4993ac27a0ecSDave Kleikamp bad_inode:
4994567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
49951d1fe1eeSDavid Howells 	iget_failed(inode);
49961d1fe1eeSDavid Howells 	return ERR_PTR(ret);
4997ac27a0ecSDave Kleikamp }
4998ac27a0ecSDave Kleikamp 
49993f19b2abSDavid Howells static void __ext4_update_other_inode_time(struct super_block *sb,
50003f19b2abSDavid Howells 					   unsigned long orig_ino,
50013f19b2abSDavid Howells 					   unsigned long ino,
50023f19b2abSDavid Howells 					   struct ext4_inode *raw_inode)
5003a26f4992STheodore Ts'o {
50043f19b2abSDavid Howells 	struct inode *inode;
5005a26f4992STheodore Ts'o 
50063f19b2abSDavid Howells 	inode = find_inode_by_ino_rcu(sb, ino);
50073f19b2abSDavid Howells 	if (!inode)
50083f19b2abSDavid Howells 		return;
50093f19b2abSDavid Howells 
5010ed296c6cSEric Biggers 	if (!inode_is_dirtytime_only(inode))
50113f19b2abSDavid Howells 		return;
50123f19b2abSDavid Howells 
5013a26f4992STheodore Ts'o 	spin_lock(&inode->i_lock);
5014ed296c6cSEric Biggers 	if (inode_is_dirtytime_only(inode)) {
5015a26f4992STheodore Ts'o 		struct ext4_inode_info	*ei = EXT4_I(inode);
5016a26f4992STheodore Ts'o 
50175fcd5750SJan Kara 		inode->i_state &= ~I_DIRTY_TIME;
5018a26f4992STheodore Ts'o 		spin_unlock(&inode->i_lock);
5019a26f4992STheodore Ts'o 
5020a26f4992STheodore Ts'o 		spin_lock(&ei->i_raw_lock);
50213f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
50223f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
50233f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
50243f19b2abSDavid Howells 		ext4_inode_csum_set(inode, raw_inode, ei);
5025a26f4992STheodore Ts'o 		spin_unlock(&ei->i_raw_lock);
50263f19b2abSDavid Howells 		trace_ext4_other_inode_update_time(inode, orig_ino);
50273f19b2abSDavid Howells 		return;
5028a26f4992STheodore Ts'o 	}
5029a26f4992STheodore Ts'o 	spin_unlock(&inode->i_lock);
5030a26f4992STheodore Ts'o }
5031a26f4992STheodore Ts'o 
5032a26f4992STheodore Ts'o /*
5033a26f4992STheodore Ts'o  * Opportunistically update the other time fields for other inodes in
5034a26f4992STheodore Ts'o  * the same inode table block.
5035a26f4992STheodore Ts'o  */
5036a26f4992STheodore Ts'o static void ext4_update_other_inodes_time(struct super_block *sb,
5037a26f4992STheodore Ts'o 					  unsigned long orig_ino, char *buf)
5038a26f4992STheodore Ts'o {
5039a26f4992STheodore Ts'o 	unsigned long ino;
5040a26f4992STheodore Ts'o 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5041a26f4992STheodore Ts'o 	int inode_size = EXT4_INODE_SIZE(sb);
5042a26f4992STheodore Ts'o 
50430f0ff9a9STheodore Ts'o 	/*
50440f0ff9a9STheodore Ts'o 	 * Calculate the first inode in the inode table block.  Inode
50450f0ff9a9STheodore Ts'o 	 * numbers are one-based.  That is, the first inode in a block
50460f0ff9a9STheodore Ts'o 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
50470f0ff9a9STheodore Ts'o 	 */
50480f0ff9a9STheodore Ts'o 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
50493f19b2abSDavid Howells 	rcu_read_lock();
5050a26f4992STheodore Ts'o 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5051a26f4992STheodore Ts'o 		if (ino == orig_ino)
5052a26f4992STheodore Ts'o 			continue;
50533f19b2abSDavid Howells 		__ext4_update_other_inode_time(sb, orig_ino, ino,
50543f19b2abSDavid Howells 					       (struct ext4_inode *)buf);
5055a26f4992STheodore Ts'o 	}
50563f19b2abSDavid Howells 	rcu_read_unlock();
5057a26f4992STheodore Ts'o }
5058a26f4992STheodore Ts'o 
5059664bd38bSZhang Yi /*
5060664bd38bSZhang Yi  * Post the struct inode info into an on-disk inode location in the
5061664bd38bSZhang Yi  * buffer-cache.  This gobbles the caller's reference to the
5062664bd38bSZhang Yi  * buffer_head in the inode location struct.
5063664bd38bSZhang Yi  *
5064664bd38bSZhang Yi  * The caller must have write access to iloc->bh.
5065664bd38bSZhang Yi  */
5066664bd38bSZhang Yi static int ext4_do_update_inode(handle_t *handle,
5067664bd38bSZhang Yi 				struct inode *inode,
5068664bd38bSZhang Yi 				struct ext4_iloc *iloc)
5069664bd38bSZhang Yi {
5070664bd38bSZhang Yi 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5071664bd38bSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
5072664bd38bSZhang Yi 	struct buffer_head *bh = iloc->bh;
5073664bd38bSZhang Yi 	struct super_block *sb = inode->i_sb;
5074664bd38bSZhang Yi 	int err;
5075664bd38bSZhang Yi 	int need_datasync = 0, set_large_file = 0;
5076664bd38bSZhang Yi 
5077664bd38bSZhang Yi 	spin_lock(&ei->i_raw_lock);
5078664bd38bSZhang Yi 
5079664bd38bSZhang Yi 	/*
5080664bd38bSZhang Yi 	 * For fields not tracked in the in-memory inode, initialise them
5081664bd38bSZhang Yi 	 * to zero for new inodes.
5082664bd38bSZhang Yi 	 */
5083664bd38bSZhang Yi 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5084664bd38bSZhang Yi 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5085664bd38bSZhang Yi 
5086664bd38bSZhang Yi 	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5087664bd38bSZhang Yi 		need_datasync = 1;
5088664bd38bSZhang Yi 	if (ei->i_disksize > 0x7fffffffULL) {
5089664bd38bSZhang Yi 		if (!ext4_has_feature_large_file(sb) ||
5090664bd38bSZhang Yi 		    EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5091664bd38bSZhang Yi 			set_large_file = 1;
5092664bd38bSZhang Yi 	}
5093664bd38bSZhang Yi 
5094664bd38bSZhang Yi 	err = ext4_fill_raw_inode(inode, raw_inode);
5095202ee5dfSTheodore Ts'o 	spin_unlock(&ei->i_raw_lock);
5096baaae979SZhang Yi 	if (err) {
5097baaae979SZhang Yi 		EXT4_ERROR_INODE(inode, "corrupted inode contents");
5098baaae979SZhang Yi 		goto out_brelse;
5099baaae979SZhang Yi 	}
5100baaae979SZhang Yi 
51011751e8a6SLinus Torvalds 	if (inode->i_sb->s_flags & SB_LAZYTIME)
5102a26f4992STheodore Ts'o 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5103a26f4992STheodore Ts'o 					      bh->b_data);
5104202ee5dfSTheodore Ts'o 
51050390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
51067d8bd3c7SShijie Luo 	err = ext4_handle_dirty_metadata(handle, NULL, bh);
51077d8bd3c7SShijie Luo 	if (err)
5108baaae979SZhang Yi 		goto out_error;
510919f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5110202ee5dfSTheodore Ts'o 	if (set_large_file) {
51115d601255Sliang xie 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5112188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, sb,
5113188c299eSJan Kara 						    EXT4_SB(sb)->s_sbh,
5114188c299eSJan Kara 						    EXT4_JTR_NONE);
5115202ee5dfSTheodore Ts'o 		if (err)
5116baaae979SZhang Yi 			goto out_error;
511705c2c00fSJan Kara 		lock_buffer(EXT4_SB(sb)->s_sbh);
5118e2b911c5SDarrick J. Wong 		ext4_set_feature_large_file(sb);
511905c2c00fSJan Kara 		ext4_superblock_csum_set(sb);
512005c2c00fSJan Kara 		unlock_buffer(EXT4_SB(sb)->s_sbh);
5121202ee5dfSTheodore Ts'o 		ext4_handle_sync(handle);
5122a3f5cf14SJan Kara 		err = ext4_handle_dirty_metadata(handle, NULL,
5123a3f5cf14SJan Kara 						 EXT4_SB(sb)->s_sbh);
5124202ee5dfSTheodore Ts'o 	}
5125b71fc079SJan Kara 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5126baaae979SZhang Yi out_error:
5127baaae979SZhang Yi 	ext4_std_error(inode->i_sb, err);
5128ac27a0ecSDave Kleikamp out_brelse:
5129ac27a0ecSDave Kleikamp 	brelse(bh);
5130ac27a0ecSDave Kleikamp 	return err;
5131ac27a0ecSDave Kleikamp }
5132ac27a0ecSDave Kleikamp 
5133ac27a0ecSDave Kleikamp /*
5134617ba13bSMingming Cao  * ext4_write_inode()
5135ac27a0ecSDave Kleikamp  *
5136ac27a0ecSDave Kleikamp  * We are called from a few places:
5137ac27a0ecSDave Kleikamp  *
513887f7e416STheodore Ts'o  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5139ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
51404907cb7bSAnatol Pomozov  *   transaction to commit.
5141ac27a0ecSDave Kleikamp  *
514287f7e416STheodore Ts'o  * - Within flush work (sys_sync(), kupdate and such).
514387f7e416STheodore Ts'o  *   We wait on commit, if told to.
5144ac27a0ecSDave Kleikamp  *
514587f7e416STheodore Ts'o  * - Within iput_final() -> write_inode_now()
514687f7e416STheodore Ts'o  *   We wait on commit, if told to.
5147ac27a0ecSDave Kleikamp  *
5148ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
5149ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
515087f7e416STheodore Ts'o  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
515187f7e416STheodore Ts'o  * writeback.
5152ac27a0ecSDave Kleikamp  *
5153ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
5154ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5155ac27a0ecSDave Kleikamp  * which we are interested.
5156ac27a0ecSDave Kleikamp  *
5157ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
5158ac27a0ecSDave Kleikamp  *
5159ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
5160ac27a0ecSDave Kleikamp  *	stuff();
5161ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
5162ac27a0ecSDave Kleikamp  *
516387f7e416STheodore Ts'o  * is in error because write_inode() could occur while `stuff()' is running,
516487f7e416STheodore Ts'o  * and the new i_size will be lost.  Plus the inode will no longer be on the
516587f7e416STheodore Ts'o  * superblock's dirty inode list.
5166ac27a0ecSDave Kleikamp  */
5167a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5168ac27a0ecSDave Kleikamp {
516991ac6f43SFrank Mayhar 	int err;
517091ac6f43SFrank Mayhar 
5171f1128084SJan Kara 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
5172ac27a0ecSDave Kleikamp 		return 0;
5173ac27a0ecSDave Kleikamp 
5174eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
517518f2c4fcSTheodore Ts'o 		return -EIO;
517618f2c4fcSTheodore Ts'o 
517791ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
5178617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
51794978c659SJan Kara 			ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5180ac27a0ecSDave Kleikamp 			dump_stack();
5181ac27a0ecSDave Kleikamp 			return -EIO;
5182ac27a0ecSDave Kleikamp 		}
5183ac27a0ecSDave Kleikamp 
518410542c22SJan Kara 		/*
518510542c22SJan Kara 		 * No need to force transaction in WB_SYNC_NONE mode. Also
518610542c22SJan Kara 		 * ext4_sync_fs() will force the commit after everything is
518710542c22SJan Kara 		 * written.
518810542c22SJan Kara 		 */
518910542c22SJan Kara 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5190ac27a0ecSDave Kleikamp 			return 0;
5191ac27a0ecSDave Kleikamp 
5192aa75f4d3SHarshad Shirwadkar 		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
519318f2c4fcSTheodore Ts'o 						EXT4_I(inode)->i_sync_tid);
519491ac6f43SFrank Mayhar 	} else {
519591ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
519691ac6f43SFrank Mayhar 
51978016e29fSHarshad Shirwadkar 		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
519891ac6f43SFrank Mayhar 		if (err)
519991ac6f43SFrank Mayhar 			return err;
520010542c22SJan Kara 		/*
520110542c22SJan Kara 		 * sync(2) will flush the whole buffer cache. No need to do
520210542c22SJan Kara 		 * it here separately for each inode.
520310542c22SJan Kara 		 */
520410542c22SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5205830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
5206830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
520754d3adbcSTheodore Ts'o 			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5208c398eda0STheodore Ts'o 					       "IO error syncing inode");
5209830156c7SFrank Mayhar 			err = -EIO;
5210830156c7SFrank Mayhar 		}
5211fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
521291ac6f43SFrank Mayhar 	}
521391ac6f43SFrank Mayhar 	return err;
5214ac27a0ecSDave Kleikamp }
5215ac27a0ecSDave Kleikamp 
5216ac27a0ecSDave Kleikamp /*
5217ccd16945SMatthew Wilcox (Oracle)  * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5218ccd16945SMatthew Wilcox (Oracle)  * buffers that are attached to a folio straddling i_size and are undergoing
521953e87268SJan Kara  * commit. In that case we have to wait for commit to finish and try again.
522053e87268SJan Kara  */
522153e87268SJan Kara static void ext4_wait_for_tail_page_commit(struct inode *inode)
522253e87268SJan Kara {
522353e87268SJan Kara 	unsigned offset;
522453e87268SJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
522553e87268SJan Kara 	tid_t commit_tid = 0;
522653e87268SJan Kara 	int ret;
522753e87268SJan Kara 
522809cbfeafSKirill A. Shutemov 	offset = inode->i_size & (PAGE_SIZE - 1);
522953e87268SJan Kara 	/*
5230ccd16945SMatthew Wilcox (Oracle) 	 * If the folio is fully truncated, we don't need to wait for any commit
5231ccd16945SMatthew Wilcox (Oracle) 	 * (and we even should not as __ext4_journalled_invalidate_folio() may
5232ccd16945SMatthew Wilcox (Oracle) 	 * strip all buffers from the folio but keep the folio dirty which can then
52333f079114SJan Kara 	 * confuse e.g. concurrent ext4_writepages() seeing dirty folio without
5234565333a1Syangerkun 	 * buffers). Also we don't need to wait for any commit if all buffers in
5235ccd16945SMatthew Wilcox (Oracle) 	 * the folio remain valid. This is most beneficial for the common case of
5236565333a1Syangerkun 	 * blocksize == PAGESIZE.
523753e87268SJan Kara 	 */
5238565333a1Syangerkun 	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
523953e87268SJan Kara 		return;
524053e87268SJan Kara 	while (1) {
5241ccd16945SMatthew Wilcox (Oracle) 		struct folio *folio = filemap_lock_folio(inode->i_mapping,
524209cbfeafSKirill A. Shutemov 				      inode->i_size >> PAGE_SHIFT);
524366dabbb6SChristoph Hellwig 		if (IS_ERR(folio))
524453e87268SJan Kara 			return;
5245ccd16945SMatthew Wilcox (Oracle) 		ret = __ext4_journalled_invalidate_folio(folio, offset,
5246ccd16945SMatthew Wilcox (Oracle) 						folio_size(folio) - offset);
5247ccd16945SMatthew Wilcox (Oracle) 		folio_unlock(folio);
5248ccd16945SMatthew Wilcox (Oracle) 		folio_put(folio);
524953e87268SJan Kara 		if (ret != -EBUSY)
525053e87268SJan Kara 			return;
525153e87268SJan Kara 		commit_tid = 0;
525253e87268SJan Kara 		read_lock(&journal->j_state_lock);
525353e87268SJan Kara 		if (journal->j_committing_transaction)
525453e87268SJan Kara 			commit_tid = journal->j_committing_transaction->t_tid;
525553e87268SJan Kara 		read_unlock(&journal->j_state_lock);
525653e87268SJan Kara 		if (commit_tid)
525753e87268SJan Kara 			jbd2_log_wait_commit(journal, commit_tid);
525853e87268SJan Kara 	}
525953e87268SJan Kara }
526053e87268SJan Kara 
526153e87268SJan Kara /*
5262617ba13bSMingming Cao  * ext4_setattr()
5263ac27a0ecSDave Kleikamp  *
5264ac27a0ecSDave Kleikamp  * Called from notify_change.
5265ac27a0ecSDave Kleikamp  *
5266ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
5267ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
5268ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
5269ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
5270ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
5271ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
5272ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
5273ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
5274ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
5275ac27a0ecSDave Kleikamp  *
5276678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
5277678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
5278678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
5279678aaf48SJan Kara  * This way we are sure that all the data written in the previous
5280678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
5281678aaf48SJan Kara  * writeback).
5282678aaf48SJan Kara  *
5283f340b3d9Shongnanli  * Called with inode->i_rwsem down.
5284ac27a0ecSDave Kleikamp  */
5285c1632a0fSChristian Brauner int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5286549c7297SChristian Brauner 		 struct iattr *attr)
5287ac27a0ecSDave Kleikamp {
52882b0143b5SDavid Howells 	struct inode *inode = d_inode(dentry);
5289ac27a0ecSDave Kleikamp 	int error, rc = 0;
52903d287de3SDmitry Monakhov 	int orphan = 0;
5291ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
5292a642c2c0SJeff Layton 	bool inc_ivers = true;
5293ac27a0ecSDave Kleikamp 
5294eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
52950db1ff22STheodore Ts'o 		return -EIO;
52960db1ff22STheodore Ts'o 
529702b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
529802b016caSTheodore Ts'o 		return -EPERM;
529902b016caSTheodore Ts'o 
530002b016caSTheodore Ts'o 	if (unlikely(IS_APPEND(inode) &&
530102b016caSTheodore Ts'o 		     (ia_valid & (ATTR_MODE | ATTR_UID |
530202b016caSTheodore Ts'o 				  ATTR_GID | ATTR_TIMES_SET))))
530302b016caSTheodore Ts'o 		return -EPERM;
530402b016caSTheodore Ts'o 
5305c1632a0fSChristian Brauner 	error = setattr_prepare(idmap, dentry, attr);
5306ac27a0ecSDave Kleikamp 	if (error)
5307ac27a0ecSDave Kleikamp 		return error;
5308ac27a0ecSDave Kleikamp 
53093ce2b8ddSEric Biggers 	error = fscrypt_prepare_setattr(dentry, attr);
53103ce2b8ddSEric Biggers 	if (error)
53113ce2b8ddSEric Biggers 		return error;
53123ce2b8ddSEric Biggers 
5313c93d8f88SEric Biggers 	error = fsverity_prepare_setattr(dentry, attr);
5314c93d8f88SEric Biggers 	if (error)
5315c93d8f88SEric Biggers 		return error;
5316c93d8f88SEric Biggers 
5317f861646aSChristian Brauner 	if (is_quota_modification(idmap, inode, attr)) {
5318a7cdadeeSJan Kara 		error = dquot_initialize(inode);
5319a7cdadeeSJan Kara 		if (error)
5320a7cdadeeSJan Kara 			return error;
5321a7cdadeeSJan Kara 	}
53222729cfdcSHarshad Shirwadkar 
53230dbe12f2SChristian Brauner 	if (i_uid_needs_update(idmap, attr, inode) ||
53240dbe12f2SChristian Brauner 	    i_gid_needs_update(idmap, attr, inode)) {
5325ac27a0ecSDave Kleikamp 		handle_t *handle;
5326ac27a0ecSDave Kleikamp 
5327ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
5328ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
53299924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
53309924a92aSTheodore Ts'o 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5331194074acSDmitry Monakhov 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5332ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
5333ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
5334ac27a0ecSDave Kleikamp 			goto err_out;
5335ac27a0ecSDave Kleikamp 		}
53367a9ca53aSTahsin Erdogan 
53377a9ca53aSTahsin Erdogan 		/* dquot_transfer() calls back ext4_get_inode_usage() which
53387a9ca53aSTahsin Erdogan 		 * counts xattr inode references.
53397a9ca53aSTahsin Erdogan 		 */
53407a9ca53aSTahsin Erdogan 		down_read(&EXT4_I(inode)->xattr_sem);
5341f861646aSChristian Brauner 		error = dquot_transfer(idmap, inode, attr);
53427a9ca53aSTahsin Erdogan 		up_read(&EXT4_I(inode)->xattr_sem);
53437a9ca53aSTahsin Erdogan 
5344ac27a0ecSDave Kleikamp 		if (error) {
5345617ba13bSMingming Cao 			ext4_journal_stop(handle);
5346ac27a0ecSDave Kleikamp 			return error;
5347ac27a0ecSDave Kleikamp 		}
5348ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
5349ac27a0ecSDave Kleikamp 		 * one transaction */
53500dbe12f2SChristian Brauner 		i_uid_update(idmap, attr, inode);
53510dbe12f2SChristian Brauner 		i_gid_update(idmap, attr, inode);
5352617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
5353617ba13bSMingming Cao 		ext4_journal_stop(handle);
5354512c15efSPan Bian 		if (unlikely(error)) {
53554209ae12SHarshad Shirwadkar 			return error;
5356ac27a0ecSDave Kleikamp 		}
5357512c15efSPan Bian 	}
5358ac27a0ecSDave Kleikamp 
53593da40c7bSJosef Bacik 	if (attr->ia_valid & ATTR_SIZE) {
53605208386cSJan Kara 		handle_t *handle;
53613da40c7bSJosef Bacik 		loff_t oldsize = inode->i_size;
5362f4534c9fSYe Bin 		loff_t old_disksize;
5363b9c1c267SJan Kara 		int shrink = (attr->ia_size < inode->i_size);
5364562c72aaSChristoph Hellwig 
536512e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5366e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5367e2b46574SEric Sandeen 
5368aa75f4d3SHarshad Shirwadkar 			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
53690c095c7fSTheodore Ts'o 				return -EFBIG;
5370e2b46574SEric Sandeen 			}
5371aa75f4d3SHarshad Shirwadkar 		}
5372aa75f4d3SHarshad Shirwadkar 		if (!S_ISREG(inode->i_mode)) {
53733da40c7bSJosef Bacik 			return -EINVAL;
5374aa75f4d3SHarshad Shirwadkar 		}
5375dff6efc3SChristoph Hellwig 
5376a642c2c0SJeff Layton 		if (attr->ia_size == inode->i_size)
5377a642c2c0SJeff Layton 			inc_ivers = false;
5378dff6efc3SChristoph Hellwig 
5379b9c1c267SJan Kara 		if (shrink) {
5380b9c1c267SJan Kara 			if (ext4_should_order_data(inode)) {
53815208386cSJan Kara 				error = ext4_begin_ordered_truncate(inode,
53825208386cSJan Kara 							    attr->ia_size);
53835208386cSJan Kara 				if (error)
53845208386cSJan Kara 					goto err_out;
53855208386cSJan Kara 			}
5386b9c1c267SJan Kara 			/*
5387b9c1c267SJan Kara 			 * Blocks are going to be removed from the inode. Wait
5388b9c1c267SJan Kara 			 * for dio in flight.
5389b9c1c267SJan Kara 			 */
5390b9c1c267SJan Kara 			inode_dio_wait(inode);
5391b9c1c267SJan Kara 		}
5392b9c1c267SJan Kara 
5393d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
5394b9c1c267SJan Kara 
5395b9c1c267SJan Kara 		rc = ext4_break_layouts(inode);
5396b9c1c267SJan Kara 		if (rc) {
5397d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
5398aa75f4d3SHarshad Shirwadkar 			goto err_out;
5399b9c1c267SJan Kara 		}
5400b9c1c267SJan Kara 
54013da40c7bSJosef Bacik 		if (attr->ia_size != inode->i_size) {
54029924a92aSTheodore Ts'o 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5403ac27a0ecSDave Kleikamp 			if (IS_ERR(handle)) {
5404ac27a0ecSDave Kleikamp 				error = PTR_ERR(handle);
5405b9c1c267SJan Kara 				goto out_mmap_sem;
5406ac27a0ecSDave Kleikamp 			}
54073da40c7bSJosef Bacik 			if (ext4_handle_valid(handle) && shrink) {
5408617ba13bSMingming Cao 				error = ext4_orphan_add(handle, inode);
54093d287de3SDmitry Monakhov 				orphan = 1;
54103d287de3SDmitry Monakhov 			}
5411911af577SEryu Guan 			/*
5412911af577SEryu Guan 			 * Update c/mtime on truncate up, ext4_truncate() will
5413911af577SEryu Guan 			 * update c/mtime in shrink case below
5414911af577SEryu Guan 			 */
5415911af577SEryu Guan 			if (!shrink) {
5416eeca7ea1SDeepa Dinamani 				inode->i_mtime = current_time(inode);
5417911af577SEryu Guan 				inode->i_ctime = inode->i_mtime;
5418911af577SEryu Guan 			}
5419aa75f4d3SHarshad Shirwadkar 
5420aa75f4d3SHarshad Shirwadkar 			if (shrink)
5421a80f7fcfSHarshad Shirwadkar 				ext4_fc_track_range(handle, inode,
5422aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5423aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
54249725958bSXin Yin 					EXT_MAX_BLOCKS - 1);
5425aa75f4d3SHarshad Shirwadkar 			else
5426aa75f4d3SHarshad Shirwadkar 				ext4_fc_track_range(
5427a80f7fcfSHarshad Shirwadkar 					handle, inode,
5428aa75f4d3SHarshad Shirwadkar 					(oldsize > 0 ? oldsize - 1 : oldsize) >>
5429aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
5430aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5431aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits);
5432aa75f4d3SHarshad Shirwadkar 
543390e775b7SJan Kara 			down_write(&EXT4_I(inode)->i_data_sem);
5434f4534c9fSYe Bin 			old_disksize = EXT4_I(inode)->i_disksize;
5435617ba13bSMingming Cao 			EXT4_I(inode)->i_disksize = attr->ia_size;
5436617ba13bSMingming Cao 			rc = ext4_mark_inode_dirty(handle, inode);
5437ac27a0ecSDave Kleikamp 			if (!error)
5438ac27a0ecSDave Kleikamp 				error = rc;
543990e775b7SJan Kara 			/*
544090e775b7SJan Kara 			 * We have to update i_size under i_data_sem together
544190e775b7SJan Kara 			 * with i_disksize to avoid races with writeback code
544290e775b7SJan Kara 			 * running ext4_wb_update_i_disksize().
544390e775b7SJan Kara 			 */
544490e775b7SJan Kara 			if (!error)
544590e775b7SJan Kara 				i_size_write(inode, attr->ia_size);
5446f4534c9fSYe Bin 			else
5447f4534c9fSYe Bin 				EXT4_I(inode)->i_disksize = old_disksize;
544890e775b7SJan Kara 			up_write(&EXT4_I(inode)->i_data_sem);
5449617ba13bSMingming Cao 			ext4_journal_stop(handle);
5450b9c1c267SJan Kara 			if (error)
5451b9c1c267SJan Kara 				goto out_mmap_sem;
545282a25b02SJan Kara 			if (!shrink) {
5453b9c1c267SJan Kara 				pagecache_isize_extended(inode, oldsize,
5454b9c1c267SJan Kara 							 inode->i_size);
5455b9c1c267SJan Kara 			} else if (ext4_should_journal_data(inode)) {
545682a25b02SJan Kara 				ext4_wait_for_tail_page_commit(inode);
5457b9c1c267SJan Kara 			}
5458430657b6SRoss Zwisler 		}
5459430657b6SRoss Zwisler 
546053e87268SJan Kara 		/*
546153e87268SJan Kara 		 * Truncate pagecache after we've waited for commit
546253e87268SJan Kara 		 * in data=journal mode to make pages freeable.
546353e87268SJan Kara 		 */
54647caef267SKirill A. Shutemov 		truncate_pagecache(inode, inode->i_size);
5465b9c1c267SJan Kara 		/*
5466b9c1c267SJan Kara 		 * Call ext4_truncate() even if i_size didn't change to
5467b9c1c267SJan Kara 		 * truncate possible preallocated blocks.
5468b9c1c267SJan Kara 		 */
5469b9c1c267SJan Kara 		if (attr->ia_size <= oldsize) {
54702c98eb5eSTheodore Ts'o 			rc = ext4_truncate(inode);
54712c98eb5eSTheodore Ts'o 			if (rc)
54722c98eb5eSTheodore Ts'o 				error = rc;
54732c98eb5eSTheodore Ts'o 		}
5474b9c1c267SJan Kara out_mmap_sem:
5475d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
54763da40c7bSJosef Bacik 	}
5477ac27a0ecSDave Kleikamp 
54782c98eb5eSTheodore Ts'o 	if (!error) {
5479a642c2c0SJeff Layton 		if (inc_ivers)
5480a642c2c0SJeff Layton 			inode_inc_iversion(inode);
5481c1632a0fSChristian Brauner 		setattr_copy(idmap, inode, attr);
54821025774cSChristoph Hellwig 		mark_inode_dirty(inode);
54831025774cSChristoph Hellwig 	}
54841025774cSChristoph Hellwig 
54851025774cSChristoph Hellwig 	/*
54861025774cSChristoph Hellwig 	 * If the call to ext4_truncate failed to get a transaction handle at
54871025774cSChristoph Hellwig 	 * all, we need to clean up the in-core orphan list manually.
54881025774cSChristoph Hellwig 	 */
54893d287de3SDmitry Monakhov 	if (orphan && inode->i_nlink)
5490617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
5491ac27a0ecSDave Kleikamp 
54922c98eb5eSTheodore Ts'o 	if (!error && (ia_valid & ATTR_MODE))
549313e83a49SChristian Brauner 		rc = posix_acl_chmod(idmap, dentry, inode->i_mode);
5494ac27a0ecSDave Kleikamp 
5495ac27a0ecSDave Kleikamp err_out:
5496aa75f4d3SHarshad Shirwadkar 	if  (error)
5497617ba13bSMingming Cao 		ext4_std_error(inode->i_sb, error);
5498ac27a0ecSDave Kleikamp 	if (!error)
5499ac27a0ecSDave Kleikamp 		error = rc;
5500ac27a0ecSDave Kleikamp 	return error;
5501ac27a0ecSDave Kleikamp }
5502ac27a0ecSDave Kleikamp 
55038434ef1dSEric Biggers u32 ext4_dio_alignment(struct inode *inode)
55048434ef1dSEric Biggers {
55058434ef1dSEric Biggers 	if (fsverity_active(inode))
55068434ef1dSEric Biggers 		return 0;
55078434ef1dSEric Biggers 	if (ext4_should_journal_data(inode))
55088434ef1dSEric Biggers 		return 0;
55098434ef1dSEric Biggers 	if (ext4_has_inline_data(inode))
55108434ef1dSEric Biggers 		return 0;
55118434ef1dSEric Biggers 	if (IS_ENCRYPTED(inode)) {
55128434ef1dSEric Biggers 		if (!fscrypt_dio_supported(inode))
55138434ef1dSEric Biggers 			return 0;
55148434ef1dSEric Biggers 		return i_blocksize(inode);
55158434ef1dSEric Biggers 	}
55168434ef1dSEric Biggers 	return 1; /* use the iomap defaults */
55178434ef1dSEric Biggers }
55188434ef1dSEric Biggers 
5519b74d24f7SChristian Brauner int ext4_getattr(struct mnt_idmap *idmap, const struct path *path,
5520549c7297SChristian Brauner 		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
55213e3398a0SMingming Cao {
552299652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
552399652ea5SDavid Howells 	struct ext4_inode *raw_inode;
552499652ea5SDavid Howells 	struct ext4_inode_info *ei = EXT4_I(inode);
552599652ea5SDavid Howells 	unsigned int flags;
55263e3398a0SMingming Cao 
5527d4c5e960STheodore Ts'o 	if ((request_mask & STATX_BTIME) &&
5528d4c5e960STheodore Ts'o 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
552999652ea5SDavid Howells 		stat->result_mask |= STATX_BTIME;
553099652ea5SDavid Howells 		stat->btime.tv_sec = ei->i_crtime.tv_sec;
553199652ea5SDavid Howells 		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
553299652ea5SDavid Howells 	}
553399652ea5SDavid Howells 
55348434ef1dSEric Biggers 	/*
55358434ef1dSEric Biggers 	 * Return the DIO alignment restrictions if requested.  We only return
55368434ef1dSEric Biggers 	 * this information when requested, since on encrypted files it might
55378434ef1dSEric Biggers 	 * take a fair bit of work to get if the file wasn't opened recently.
55388434ef1dSEric Biggers 	 */
55398434ef1dSEric Biggers 	if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
55408434ef1dSEric Biggers 		u32 dio_align = ext4_dio_alignment(inode);
55418434ef1dSEric Biggers 
55428434ef1dSEric Biggers 		stat->result_mask |= STATX_DIOALIGN;
55438434ef1dSEric Biggers 		if (dio_align == 1) {
55448434ef1dSEric Biggers 			struct block_device *bdev = inode->i_sb->s_bdev;
55458434ef1dSEric Biggers 
55468434ef1dSEric Biggers 			/* iomap defaults */
55478434ef1dSEric Biggers 			stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
55488434ef1dSEric Biggers 			stat->dio_offset_align = bdev_logical_block_size(bdev);
55498434ef1dSEric Biggers 		} else {
55508434ef1dSEric Biggers 			stat->dio_mem_align = dio_align;
55518434ef1dSEric Biggers 			stat->dio_offset_align = dio_align;
55528434ef1dSEric Biggers 		}
55538434ef1dSEric Biggers 	}
55548434ef1dSEric Biggers 
555599652ea5SDavid Howells 	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
555699652ea5SDavid Howells 	if (flags & EXT4_APPEND_FL)
555799652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_APPEND;
555899652ea5SDavid Howells 	if (flags & EXT4_COMPR_FL)
555999652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_COMPRESSED;
556099652ea5SDavid Howells 	if (flags & EXT4_ENCRYPT_FL)
556199652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_ENCRYPTED;
556299652ea5SDavid Howells 	if (flags & EXT4_IMMUTABLE_FL)
556399652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_IMMUTABLE;
556499652ea5SDavid Howells 	if (flags & EXT4_NODUMP_FL)
556599652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_NODUMP;
55661f607195SEric Biggers 	if (flags & EXT4_VERITY_FL)
55671f607195SEric Biggers 		stat->attributes |= STATX_ATTR_VERITY;
556899652ea5SDavid Howells 
55693209f68bSDavid Howells 	stat->attributes_mask |= (STATX_ATTR_APPEND |
55703209f68bSDavid Howells 				  STATX_ATTR_COMPRESSED |
55713209f68bSDavid Howells 				  STATX_ATTR_ENCRYPTED |
55723209f68bSDavid Howells 				  STATX_ATTR_IMMUTABLE |
55731f607195SEric Biggers 				  STATX_ATTR_NODUMP |
55741f607195SEric Biggers 				  STATX_ATTR_VERITY);
55753209f68bSDavid Howells 
5576b74d24f7SChristian Brauner 	generic_fillattr(idmap, inode, stat);
557799652ea5SDavid Howells 	return 0;
557899652ea5SDavid Howells }
557999652ea5SDavid Howells 
5580b74d24f7SChristian Brauner int ext4_file_getattr(struct mnt_idmap *idmap,
5581549c7297SChristian Brauner 		      const struct path *path, struct kstat *stat,
558299652ea5SDavid Howells 		      u32 request_mask, unsigned int query_flags)
558399652ea5SDavid Howells {
558499652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
558599652ea5SDavid Howells 	u64 delalloc_blocks;
558699652ea5SDavid Howells 
5587b74d24f7SChristian Brauner 	ext4_getattr(idmap, path, stat, request_mask, query_flags);
55883e3398a0SMingming Cao 
55893e3398a0SMingming Cao 	/*
55909206c561SAndreas Dilger 	 * If there is inline data in the inode, the inode will normally not
55919206c561SAndreas Dilger 	 * have data blocks allocated (it may have an external xattr block).
55929206c561SAndreas Dilger 	 * Report at least one sector for such files, so tools like tar, rsync,
5593d67d64f4STheodore Ts'o 	 * others don't incorrectly think the file is completely sparse.
55949206c561SAndreas Dilger 	 */
55959206c561SAndreas Dilger 	if (unlikely(ext4_has_inline_data(inode)))
55969206c561SAndreas Dilger 		stat->blocks += (stat->size + 511) >> 9;
55979206c561SAndreas Dilger 
55989206c561SAndreas Dilger 	/*
55993e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
56003e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
56013e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
56023e3398a0SMingming Cao 	 * on-disk file blocks.
56033e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
56043e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
56053e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
56063e3398a0SMingming Cao 	 * blocks for this file.
56073e3398a0SMingming Cao 	 */
560896607551STao Ma 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
560996607551STao Ma 				   EXT4_I(inode)->i_reserved_data_blocks);
56108af8eeccSJan Kara 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
56113e3398a0SMingming Cao 	return 0;
56123e3398a0SMingming Cao }
5613ac27a0ecSDave Kleikamp 
5614fffb2739SJan Kara static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5615fffb2739SJan Kara 				   int pextents)
5616a02908f1SMingming Cao {
561712e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5618fffb2739SJan Kara 		return ext4_ind_trans_blocks(inode, lblocks);
5619fffb2739SJan Kara 	return ext4_ext_index_trans_blocks(inode, pextents);
5620a02908f1SMingming Cao }
5621ac51d837STheodore Ts'o 
5622a02908f1SMingming Cao /*
5623a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
5624a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
5625a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
5626a02908f1SMingming Cao  *
5627a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
56284907cb7bSAnatol Pomozov  * different block groups too. If they are contiguous, with flexbg,
5629a02908f1SMingming Cao  * they could still across block group boundary.
5630a02908f1SMingming Cao  *
5631a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
5632a02908f1SMingming Cao  */
5633dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5634fffb2739SJan Kara 				  int pextents)
5635a02908f1SMingming Cao {
56368df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
56378df9675fSTheodore Ts'o 	int gdpblocks;
5638a02908f1SMingming Cao 	int idxblocks;
56397fc51f92SXU pengfei 	int ret;
5640a02908f1SMingming Cao 
5641a02908f1SMingming Cao 	/*
5642fffb2739SJan Kara 	 * How many index blocks need to touch to map @lblocks logical blocks
5643fffb2739SJan Kara 	 * to @pextents physical extents?
5644a02908f1SMingming Cao 	 */
5645fffb2739SJan Kara 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5646a02908f1SMingming Cao 
5647a02908f1SMingming Cao 	ret = idxblocks;
5648a02908f1SMingming Cao 
5649a02908f1SMingming Cao 	/*
5650a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
5651a02908f1SMingming Cao 	 * to account
5652a02908f1SMingming Cao 	 */
5653fffb2739SJan Kara 	groups = idxblocks + pextents;
5654a02908f1SMingming Cao 	gdpblocks = groups;
56558df9675fSTheodore Ts'o 	if (groups > ngroups)
56568df9675fSTheodore Ts'o 		groups = ngroups;
5657a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5658a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5659a02908f1SMingming Cao 
5660a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
5661a02908f1SMingming Cao 	ret += groups + gdpblocks;
5662a02908f1SMingming Cao 
5663a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
5664a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5665ac27a0ecSDave Kleikamp 
5666ac27a0ecSDave Kleikamp 	return ret;
5667ac27a0ecSDave Kleikamp }
5668ac27a0ecSDave Kleikamp 
5669ac27a0ecSDave Kleikamp /*
567025985edcSLucas De Marchi  * Calculate the total number of credits to reserve to fit
5671f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
5672f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
5673a02908f1SMingming Cao  *
5674525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
5675a02908f1SMingming Cao  *
5676525f4ed8SMingming Cao  * We need to consider the worse case, when
5677a02908f1SMingming Cao  * one new block per extent.
5678a02908f1SMingming Cao  */
5679a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
5680a02908f1SMingming Cao {
5681a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
5682a02908f1SMingming Cao 	int ret;
5683a02908f1SMingming Cao 
5684fffb2739SJan Kara 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5685a02908f1SMingming Cao 
5686a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
5687a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
5688a02908f1SMingming Cao 		ret += bpp;
5689a02908f1SMingming Cao 	return ret;
5690a02908f1SMingming Cao }
5691f3bd1f3fSMingming Cao 
5692f3bd1f3fSMingming Cao /*
5693f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
5694f3bd1f3fSMingming Cao  *
5695f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
569679e83036SEric Sandeen  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5697f3bd1f3fSMingming Cao  *
5698f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
5699f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
5700f3bd1f3fSMingming Cao  */
5701f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5702f3bd1f3fSMingming Cao {
5703f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5704f3bd1f3fSMingming Cao }
5705f3bd1f3fSMingming Cao 
5706a02908f1SMingming Cao /*
5707617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
5708ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
5709ac27a0ecSDave Kleikamp  */
5710617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
5711617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
5712ac27a0ecSDave Kleikamp {
5713ac27a0ecSDave Kleikamp 	int err = 0;
5714ac27a0ecSDave Kleikamp 
5715eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb))) {
5716a6758309SVasily Averin 		put_bh(iloc->bh);
57170db1ff22STheodore Ts'o 		return -EIO;
5718a6758309SVasily Averin 	}
5719a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_inode(handle, inode);
5720aa75f4d3SHarshad Shirwadkar 
5721ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
5722ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
5723ac27a0ecSDave Kleikamp 
5724dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5725830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
5726ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
5727ac27a0ecSDave Kleikamp 	return err;
5728ac27a0ecSDave Kleikamp }
5729ac27a0ecSDave Kleikamp 
5730ac27a0ecSDave Kleikamp /*
5731ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
5732ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
5733ac27a0ecSDave Kleikamp  */
5734ac27a0ecSDave Kleikamp 
5735ac27a0ecSDave Kleikamp int
5736617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5737617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
5738ac27a0ecSDave Kleikamp {
57390390131bSFrank Mayhar 	int err;
57400390131bSFrank Mayhar 
5741eb8ab444SJan Kara 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
57420db1ff22STheodore Ts'o 		return -EIO;
57430db1ff22STheodore Ts'o 
5744617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
5745ac27a0ecSDave Kleikamp 	if (!err) {
5746ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
5747188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb,
5748188c299eSJan Kara 						    iloc->bh, EXT4_JTR_NONE);
5749ac27a0ecSDave Kleikamp 		if (err) {
5750ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
5751ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
5752ac27a0ecSDave Kleikamp 		}
5753ac27a0ecSDave Kleikamp 	}
5754617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5755ac27a0ecSDave Kleikamp 	return err;
5756ac27a0ecSDave Kleikamp }
5757ac27a0ecSDave Kleikamp 
5758c03b45b8SMiao Xie static int __ext4_expand_extra_isize(struct inode *inode,
5759c03b45b8SMiao Xie 				     unsigned int new_extra_isize,
5760c03b45b8SMiao Xie 				     struct ext4_iloc *iloc,
5761c03b45b8SMiao Xie 				     handle_t *handle, int *no_expand)
5762c03b45b8SMiao Xie {
5763c03b45b8SMiao Xie 	struct ext4_inode *raw_inode;
5764c03b45b8SMiao Xie 	struct ext4_xattr_ibody_header *header;
57654ea99936STheodore Ts'o 	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
57664ea99936STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
5767c03b45b8SMiao Xie 	int error;
5768c03b45b8SMiao Xie 
57694ea99936STheodore Ts'o 	/* this was checked at iget time, but double check for good measure */
57704ea99936STheodore Ts'o 	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
57714ea99936STheodore Ts'o 	    (ei->i_extra_isize & 3)) {
57724ea99936STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
57734ea99936STheodore Ts'o 				 ei->i_extra_isize,
57744ea99936STheodore Ts'o 				 EXT4_INODE_SIZE(inode->i_sb));
57754ea99936STheodore Ts'o 		return -EFSCORRUPTED;
57764ea99936STheodore Ts'o 	}
57774ea99936STheodore Ts'o 	if ((new_extra_isize < ei->i_extra_isize) ||
57784ea99936STheodore Ts'o 	    (new_extra_isize < 4) ||
57794ea99936STheodore Ts'o 	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
57804ea99936STheodore Ts'o 		return -EINVAL;	/* Should never happen */
57814ea99936STheodore Ts'o 
5782c03b45b8SMiao Xie 	raw_inode = ext4_raw_inode(iloc);
5783c03b45b8SMiao Xie 
5784c03b45b8SMiao Xie 	header = IHDR(inode, raw_inode);
5785c03b45b8SMiao Xie 
5786c03b45b8SMiao Xie 	/* No extended attributes present */
5787c03b45b8SMiao Xie 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5788c03b45b8SMiao Xie 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5789c03b45b8SMiao Xie 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5790c03b45b8SMiao Xie 		       EXT4_I(inode)->i_extra_isize, 0,
5791c03b45b8SMiao Xie 		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
5792c03b45b8SMiao Xie 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
5793c03b45b8SMiao Xie 		return 0;
5794c03b45b8SMiao Xie 	}
5795c03b45b8SMiao Xie 
57968994d113SJan Kara 	/*
57978994d113SJan Kara 	 * We may need to allocate external xattr block so we need quotas
57988994d113SJan Kara 	 * initialized. Here we can be called with various locks held so we
57998994d113SJan Kara 	 * cannot affort to initialize quotas ourselves. So just bail.
58008994d113SJan Kara 	 */
58018994d113SJan Kara 	if (dquot_initialize_needed(inode))
58028994d113SJan Kara 		return -EAGAIN;
58038994d113SJan Kara 
5804c03b45b8SMiao Xie 	/* try to expand with EAs present */
5805c03b45b8SMiao Xie 	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5806c03b45b8SMiao Xie 					   raw_inode, handle);
5807c03b45b8SMiao Xie 	if (error) {
5808c03b45b8SMiao Xie 		/*
5809c03b45b8SMiao Xie 		 * Inode size expansion failed; don't try again
5810c03b45b8SMiao Xie 		 */
5811c03b45b8SMiao Xie 		*no_expand = 1;
5812c03b45b8SMiao Xie 	}
5813c03b45b8SMiao Xie 
5814c03b45b8SMiao Xie 	return error;
5815c03b45b8SMiao Xie }
5816c03b45b8SMiao Xie 
5817ac27a0ecSDave Kleikamp /*
58186dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
58196dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
58206dd4ee7cSKalpak Shah  */
5821cf0a5e81SMiao Xie static int ext4_try_to_expand_extra_isize(struct inode *inode,
58221d03ec98SAneesh Kumar K.V 					  unsigned int new_extra_isize,
58231d03ec98SAneesh Kumar K.V 					  struct ext4_iloc iloc,
58241d03ec98SAneesh Kumar K.V 					  handle_t *handle)
58256dd4ee7cSKalpak Shah {
58263b10fdc6SMiao Xie 	int no_expand;
58273b10fdc6SMiao Xie 	int error;
58286dd4ee7cSKalpak Shah 
5829cf0a5e81SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5830cf0a5e81SMiao Xie 		return -EOVERFLOW;
5831cf0a5e81SMiao Xie 
5832cf0a5e81SMiao Xie 	/*
5833cf0a5e81SMiao Xie 	 * In nojournal mode, we can immediately attempt to expand
5834cf0a5e81SMiao Xie 	 * the inode.  When journaled, we first need to obtain extra
5835cf0a5e81SMiao Xie 	 * buffer credits since we may write into the EA block
5836cf0a5e81SMiao Xie 	 * with this same handle. If journal_extend fails, then it will
5837cf0a5e81SMiao Xie 	 * only result in a minor loss of functionality for that inode.
5838cf0a5e81SMiao Xie 	 * If this is felt to be critical, then e2fsck should be run to
5839cf0a5e81SMiao Xie 	 * force a large enough s_min_extra_isize.
5840cf0a5e81SMiao Xie 	 */
58416cb367c2SJan Kara 	if (ext4_journal_extend(handle,
584283448bdfSJan Kara 				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5843cf0a5e81SMiao Xie 		return -ENOSPC;
58446dd4ee7cSKalpak Shah 
58453b10fdc6SMiao Xie 	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5846cf0a5e81SMiao Xie 		return -EBUSY;
58473b10fdc6SMiao Xie 
5848c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5849c03b45b8SMiao Xie 					  handle, &no_expand);
58503b10fdc6SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5851c03b45b8SMiao Xie 
5852c03b45b8SMiao Xie 	return error;
58536dd4ee7cSKalpak Shah }
58546dd4ee7cSKalpak Shah 
5855c03b45b8SMiao Xie int ext4_expand_extra_isize(struct inode *inode,
5856c03b45b8SMiao Xie 			    unsigned int new_extra_isize,
5857c03b45b8SMiao Xie 			    struct ext4_iloc *iloc)
5858c03b45b8SMiao Xie {
5859c03b45b8SMiao Xie 	handle_t *handle;
5860c03b45b8SMiao Xie 	int no_expand;
5861c03b45b8SMiao Xie 	int error, rc;
5862c03b45b8SMiao Xie 
5863c03b45b8SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5864c03b45b8SMiao Xie 		brelse(iloc->bh);
5865c03b45b8SMiao Xie 		return -EOVERFLOW;
5866c03b45b8SMiao Xie 	}
5867c03b45b8SMiao Xie 
5868c03b45b8SMiao Xie 	handle = ext4_journal_start(inode, EXT4_HT_INODE,
5869c03b45b8SMiao Xie 				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5870c03b45b8SMiao Xie 	if (IS_ERR(handle)) {
5871c03b45b8SMiao Xie 		error = PTR_ERR(handle);
5872c03b45b8SMiao Xie 		brelse(iloc->bh);
5873c03b45b8SMiao Xie 		return error;
5874c03b45b8SMiao Xie 	}
5875c03b45b8SMiao Xie 
5876c03b45b8SMiao Xie 	ext4_write_lock_xattr(inode, &no_expand);
5877c03b45b8SMiao Xie 
5878ddccb6dbSzhangyi (F) 	BUFFER_TRACE(iloc->bh, "get_write_access");
5879188c299eSJan Kara 	error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
5880188c299eSJan Kara 					      EXT4_JTR_NONE);
58813b10fdc6SMiao Xie 	if (error) {
5882c03b45b8SMiao Xie 		brelse(iloc->bh);
58837f420d64SDan Carpenter 		goto out_unlock;
58843b10fdc6SMiao Xie 	}
5885cf0a5e81SMiao Xie 
5886c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5887c03b45b8SMiao Xie 					  handle, &no_expand);
5888c03b45b8SMiao Xie 
5889c03b45b8SMiao Xie 	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5890c03b45b8SMiao Xie 	if (!error)
5891c03b45b8SMiao Xie 		error = rc;
5892c03b45b8SMiao Xie 
58937f420d64SDan Carpenter out_unlock:
5894c03b45b8SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5895c03b45b8SMiao Xie 	ext4_journal_stop(handle);
58963b10fdc6SMiao Xie 	return error;
58976dd4ee7cSKalpak Shah }
58986dd4ee7cSKalpak Shah 
58996dd4ee7cSKalpak Shah /*
5900ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
5901ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
5902ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
5903ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
5904ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
5905ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
5906ac27a0ecSDave Kleikamp  *
5907ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
5908ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
5909ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5910ac27a0ecSDave Kleikamp  * we start and wait on commits.
5911ac27a0ecSDave Kleikamp  */
59124209ae12SHarshad Shirwadkar int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
59134209ae12SHarshad Shirwadkar 				const char *func, unsigned int line)
5914ac27a0ecSDave Kleikamp {
5915617ba13bSMingming Cao 	struct ext4_iloc iloc;
59166dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5917cf0a5e81SMiao Xie 	int err;
5918ac27a0ecSDave Kleikamp 
5919ac27a0ecSDave Kleikamp 	might_sleep();
59207ff9c073STheodore Ts'o 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5921617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
59225e1021f2SEryu Guan 	if (err)
59234209ae12SHarshad Shirwadkar 		goto out;
5924cf0a5e81SMiao Xie 
5925cf0a5e81SMiao Xie 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5926cf0a5e81SMiao Xie 		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
59276dd4ee7cSKalpak Shah 					       iloc, handle);
5928cf0a5e81SMiao Xie 
59294209ae12SHarshad Shirwadkar 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
59304209ae12SHarshad Shirwadkar out:
59314209ae12SHarshad Shirwadkar 	if (unlikely(err))
59324209ae12SHarshad Shirwadkar 		ext4_error_inode_err(inode, func, line, 0, err,
59334209ae12SHarshad Shirwadkar 					"mark_inode_dirty error");
59344209ae12SHarshad Shirwadkar 	return err;
5935ac27a0ecSDave Kleikamp }
5936ac27a0ecSDave Kleikamp 
5937ac27a0ecSDave Kleikamp /*
5938617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
5939ac27a0ecSDave Kleikamp  *
5940ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
5941ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
5942ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
5943ac27a0ecSDave Kleikamp  *
59445dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
5945ac27a0ecSDave Kleikamp  * are allocated to the file.
5946ac27a0ecSDave Kleikamp  *
5947ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
5948ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
5949ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
5950ac27a0ecSDave Kleikamp  */
5951aa385729SChristoph Hellwig void ext4_dirty_inode(struct inode *inode, int flags)
5952ac27a0ecSDave Kleikamp {
5953ac27a0ecSDave Kleikamp 	handle_t *handle;
5954ac27a0ecSDave Kleikamp 
59559924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5956ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5957ac27a0ecSDave Kleikamp 		return;
5958e2728c56SEric Biggers 	ext4_mark_inode_dirty(handle, inode);
5959e2728c56SEric Biggers 	ext4_journal_stop(handle);
5960ac27a0ecSDave Kleikamp }
5961ac27a0ecSDave Kleikamp 
5962617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
5963ac27a0ecSDave Kleikamp {
5964ac27a0ecSDave Kleikamp 	journal_t *journal;
5965ac27a0ecSDave Kleikamp 	handle_t *handle;
5966ac27a0ecSDave Kleikamp 	int err;
596700d873c1SJan Kara 	int alloc_ctx;
5968ac27a0ecSDave Kleikamp 
5969ac27a0ecSDave Kleikamp 	/*
5970ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
5971ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
5972ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
5973ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
5974ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
5975ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
5976ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
5977ac27a0ecSDave Kleikamp 	 */
5978ac27a0ecSDave Kleikamp 
5979617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
59800390131bSFrank Mayhar 	if (!journal)
59810390131bSFrank Mayhar 		return 0;
5982d699594dSDave Hansen 	if (is_journal_aborted(journal))
5983ac27a0ecSDave Kleikamp 		return -EROFS;
5984ac27a0ecSDave Kleikamp 
598517335dccSDmitry Monakhov 	/* Wait for all existing dio workers */
598617335dccSDmitry Monakhov 	inode_dio_wait(inode);
598717335dccSDmitry Monakhov 
59884c546592SDaeho Jeong 	/*
59894c546592SDaeho Jeong 	 * Before flushing the journal and switching inode's aops, we have
59904c546592SDaeho Jeong 	 * to flush all dirty data the inode has. There can be outstanding
59914c546592SDaeho Jeong 	 * delayed allocations, there can be unwritten extents created by
59924c546592SDaeho Jeong 	 * fallocate or buffered writes in dioread_nolock mode covered by
59934c546592SDaeho Jeong 	 * dirty data which can be converted only after flushing the dirty
59944c546592SDaeho Jeong 	 * data (and journalled aops don't know how to handle these cases).
59954c546592SDaeho Jeong 	 */
59964c546592SDaeho Jeong 	if (val) {
5997d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
59984c546592SDaeho Jeong 		err = filemap_write_and_wait(inode->i_mapping);
59994c546592SDaeho Jeong 		if (err < 0) {
6000d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
60014c546592SDaeho Jeong 			return err;
60024c546592SDaeho Jeong 		}
60034c546592SDaeho Jeong 	}
60044c546592SDaeho Jeong 
600500d873c1SJan Kara 	alloc_ctx = ext4_writepages_down_write(inode->i_sb);
6006dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
6007ac27a0ecSDave Kleikamp 
6008ac27a0ecSDave Kleikamp 	/*
6009ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
6010ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
6011ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
6012ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
6013ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
6014ac27a0ecSDave Kleikamp 	 */
6015ac27a0ecSDave Kleikamp 
6016ac27a0ecSDave Kleikamp 	if (val)
601712e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60185872ddaaSYongqiang Yang 	else {
601901d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
60204f879ca6SJan Kara 		if (err < 0) {
60214f879ca6SJan Kara 			jbd2_journal_unlock_updates(journal);
602200d873c1SJan Kara 			ext4_writepages_up_write(inode->i_sb, alloc_ctx);
60234f879ca6SJan Kara 			return err;
60244f879ca6SJan Kara 		}
602512e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60265872ddaaSYongqiang Yang 	}
6027617ba13bSMingming Cao 	ext4_set_aops(inode);
6028ac27a0ecSDave Kleikamp 
6029dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
603000d873c1SJan Kara 	ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6031c8585c6fSDaeho Jeong 
60324c546592SDaeho Jeong 	if (val)
6033d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
6034ac27a0ecSDave Kleikamp 
6035ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
6036ac27a0ecSDave Kleikamp 
60379924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6038ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
6039ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
6040ac27a0ecSDave Kleikamp 
6041aa75f4d3SHarshad Shirwadkar 	ext4_fc_mark_ineligible(inode->i_sb,
6042e85c81baSXin Yin 		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6043617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
60440390131bSFrank Mayhar 	ext4_handle_sync(handle);
6045617ba13bSMingming Cao 	ext4_journal_stop(handle);
6046617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
6047ac27a0ecSDave Kleikamp 
6048ac27a0ecSDave Kleikamp 	return err;
6049ac27a0ecSDave Kleikamp }
60502e9ee850SAneesh Kumar K.V 
6051188c299eSJan Kara static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6052188c299eSJan Kara 			    struct buffer_head *bh)
60532e9ee850SAneesh Kumar K.V {
60542e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
60552e9ee850SAneesh Kumar K.V }
60562e9ee850SAneesh Kumar K.V 
6057401b25aaSSouptick Joarder vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
60582e9ee850SAneesh Kumar K.V {
605911bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
60609ea0e45bSMatthew Wilcox 	struct folio *folio = page_folio(vmf->page);
60612e9ee850SAneesh Kumar K.V 	loff_t size;
60622e9ee850SAneesh Kumar K.V 	unsigned long len;
6063401b25aaSSouptick Joarder 	int err;
6064401b25aaSSouptick Joarder 	vm_fault_t ret;
60652e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
6066496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
60672e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
60689ea7df53SJan Kara 	handle_t *handle;
60699ea7df53SJan Kara 	get_block_t *get_block;
60709ea7df53SJan Kara 	int retries = 0;
60712e9ee850SAneesh Kumar K.V 
607202b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
607302b016caSTheodore Ts'o 		return VM_FAULT_SIGBUS;
607402b016caSTheodore Ts'o 
60758e8ad8a5SJan Kara 	sb_start_pagefault(inode->i_sb);
6076041bbb6dSTheodore Ts'o 	file_update_time(vma->vm_file);
6077ea3d7209SJan Kara 
6078d4f5258eSJan Kara 	filemap_invalidate_lock_shared(mapping);
60797b4cc978SEric Biggers 
6080401b25aaSSouptick Joarder 	err = ext4_convert_inline_data(inode);
6081401b25aaSSouptick Joarder 	if (err)
60827b4cc978SEric Biggers 		goto out_ret;
60837b4cc978SEric Biggers 
608464a9f144SMauricio Faria de Oliveira 	/*
608564a9f144SMauricio Faria de Oliveira 	 * On data journalling we skip straight to the transaction handle:
608664a9f144SMauricio Faria de Oliveira 	 * there's no delalloc; page truncated will be checked later; the
608764a9f144SMauricio Faria de Oliveira 	 * early return w/ all buffers mapped (calculates size/len) can't
608864a9f144SMauricio Faria de Oliveira 	 * be used; and there's no dioread_nolock, so only ext4_get_block.
608964a9f144SMauricio Faria de Oliveira 	 */
609064a9f144SMauricio Faria de Oliveira 	if (ext4_should_journal_data(inode))
609164a9f144SMauricio Faria de Oliveira 		goto retry_alloc;
609264a9f144SMauricio Faria de Oliveira 
60939ea7df53SJan Kara 	/* Delalloc case is easy... */
60949ea7df53SJan Kara 	if (test_opt(inode->i_sb, DELALLOC) &&
60959ea7df53SJan Kara 	    !ext4_nonda_switch(inode->i_sb)) {
60969ea7df53SJan Kara 		do {
6097401b25aaSSouptick Joarder 			err = block_page_mkwrite(vma, vmf,
60989ea7df53SJan Kara 						   ext4_da_get_block_prep);
6099401b25aaSSouptick Joarder 		} while (err == -ENOSPC &&
61009ea7df53SJan Kara 		       ext4_should_retry_alloc(inode->i_sb, &retries));
61019ea7df53SJan Kara 		goto out_ret;
61022e9ee850SAneesh Kumar K.V 	}
61030e499890SDarrick J. Wong 
61049ea0e45bSMatthew Wilcox 	folio_lock(folio);
61059ea7df53SJan Kara 	size = i_size_read(inode);
61069ea7df53SJan Kara 	/* Page got truncated from under us? */
61079ea0e45bSMatthew Wilcox 	if (folio->mapping != mapping || folio_pos(folio) > size) {
61089ea0e45bSMatthew Wilcox 		folio_unlock(folio);
61099ea7df53SJan Kara 		ret = VM_FAULT_NOPAGE;
61109ea7df53SJan Kara 		goto out;
61110e499890SDarrick J. Wong 	}
61122e9ee850SAneesh Kumar K.V 
61139ea0e45bSMatthew Wilcox 	len = folio_size(folio);
61149ea0e45bSMatthew Wilcox 	if (folio_pos(folio) + len > size)
61159ea0e45bSMatthew Wilcox 		len = size - folio_pos(folio);
6116a827eaffSAneesh Kumar K.V 	/*
61179ea7df53SJan Kara 	 * Return if we have all the buffers mapped. This avoids the need to do
61189ea7df53SJan Kara 	 * journal_start/journal_stop which can block and take a long time
611964a9f144SMauricio Faria de Oliveira 	 *
612064a9f144SMauricio Faria de Oliveira 	 * This cannot be done for data journalling, as we have to add the
612164a9f144SMauricio Faria de Oliveira 	 * inode to the transaction's list to writeprotect pages on commit.
6122a827eaffSAneesh Kumar K.V 	 */
61239ea0e45bSMatthew Wilcox 	if (folio_buffers(folio)) {
61249ea0e45bSMatthew Wilcox 		if (!ext4_walk_page_buffers(NULL, inode, folio_buffers(folio),
6125f19d5870STao Ma 					    0, len, NULL,
6126a827eaffSAneesh Kumar K.V 					    ext4_bh_unmapped)) {
61279ea7df53SJan Kara 			/* Wait so that we don't change page under IO */
61289ea0e45bSMatthew Wilcox 			folio_wait_stable(folio);
61299ea7df53SJan Kara 			ret = VM_FAULT_LOCKED;
61309ea7df53SJan Kara 			goto out;
61312e9ee850SAneesh Kumar K.V 		}
6132a827eaffSAneesh Kumar K.V 	}
61339ea0e45bSMatthew Wilcox 	folio_unlock(folio);
61349ea7df53SJan Kara 	/* OK, we need to fill the hole... */
61359ea7df53SJan Kara 	if (ext4_should_dioread_nolock(inode))
6136705965bdSJan Kara 		get_block = ext4_get_block_unwritten;
61379ea7df53SJan Kara 	else
61389ea7df53SJan Kara 		get_block = ext4_get_block;
61399ea7df53SJan Kara retry_alloc:
61409924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
61419924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
61429ea7df53SJan Kara 	if (IS_ERR(handle)) {
6143c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
61449ea7df53SJan Kara 		goto out;
61459ea7df53SJan Kara 	}
614664a9f144SMauricio Faria de Oliveira 	/*
614764a9f144SMauricio Faria de Oliveira 	 * Data journalling can't use block_page_mkwrite() because it
614864a9f144SMauricio Faria de Oliveira 	 * will set_buffer_dirty() before do_journal_get_write_access()
614964a9f144SMauricio Faria de Oliveira 	 * thus might hit warning messages for dirty metadata buffers.
615064a9f144SMauricio Faria de Oliveira 	 */
615164a9f144SMauricio Faria de Oliveira 	if (!ext4_should_journal_data(inode)) {
6152401b25aaSSouptick Joarder 		err = block_page_mkwrite(vma, vmf, get_block);
615364a9f144SMauricio Faria de Oliveira 	} else {
61549ea0e45bSMatthew Wilcox 		folio_lock(folio);
615564a9f144SMauricio Faria de Oliveira 		size = i_size_read(inode);
615664a9f144SMauricio Faria de Oliveira 		/* Page got truncated from under us? */
61579ea0e45bSMatthew Wilcox 		if (folio->mapping != mapping || folio_pos(folio) > size) {
615864a9f144SMauricio Faria de Oliveira 			ret = VM_FAULT_NOPAGE;
6159afb585a9SMauricio Faria de Oliveira 			goto out_error;
616064a9f144SMauricio Faria de Oliveira 		}
616164a9f144SMauricio Faria de Oliveira 
61629ea0e45bSMatthew Wilcox 		len = folio_size(folio);
61639ea0e45bSMatthew Wilcox 		if (folio_pos(folio) + len > size)
61649ea0e45bSMatthew Wilcox 			len = size - folio_pos(folio);
616564a9f144SMauricio Faria de Oliveira 
61669ea0e45bSMatthew Wilcox 		err = __block_write_begin(&folio->page, 0, len, ext4_get_block);
616764a9f144SMauricio Faria de Oliveira 		if (!err) {
61689ea7df53SJan Kara 			ret = VM_FAULT_SIGBUS;
616980be8c5cSRitesh Harjani 			if (ext4_journal_folio_buffers(handle, folio, len))
6170afb585a9SMauricio Faria de Oliveira 				goto out_error;
617164a9f144SMauricio Faria de Oliveira 		} else {
61729ea0e45bSMatthew Wilcox 			folio_unlock(folio);
617364a9f144SMauricio Faria de Oliveira 		}
61749ea7df53SJan Kara 	}
61759ea7df53SJan Kara 	ext4_journal_stop(handle);
6176401b25aaSSouptick Joarder 	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
61779ea7df53SJan Kara 		goto retry_alloc;
61789ea7df53SJan Kara out_ret:
6179401b25aaSSouptick Joarder 	ret = block_page_mkwrite_return(err);
61809ea7df53SJan Kara out:
6181d4f5258eSJan Kara 	filemap_invalidate_unlock_shared(mapping);
61828e8ad8a5SJan Kara 	sb_end_pagefault(inode->i_sb);
61832e9ee850SAneesh Kumar K.V 	return ret;
6184afb585a9SMauricio Faria de Oliveira out_error:
61859ea0e45bSMatthew Wilcox 	folio_unlock(folio);
6186afb585a9SMauricio Faria de Oliveira 	ext4_journal_stop(handle);
6187afb585a9SMauricio Faria de Oliveira 	goto out;
61882e9ee850SAneesh Kumar K.V }
6189