xref: /openbmc/linux/fs/ext4/inode.c (revision 1f1a55f0bf069799edd5f21a99ac1e3b10ebafee)
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) {
1822d859db3SJan Kara 		/*
1832d859db3SJan Kara 		 * When journalling data dirty buffers are tracked only in the
1842d859db3SJan Kara 		 * journal. So although mm thinks everything is clean and
1852d859db3SJan Kara 		 * ready for reaping the inode might still have some pages to
1862d859db3SJan Kara 		 * write in the running transaction or waiting to be
187ccd16945SMatthew Wilcox (Oracle) 		 * checkpointed. Thus calling jbd2_journal_invalidate_folio()
1882d859db3SJan Kara 		 * (via truncate_inode_pages()) to discard these buffers can
1892d859db3SJan Kara 		 * cause data loss. Also even if we did not discard these
1902d859db3SJan Kara 		 * buffers, we would have no way to find them after the inode
1912d859db3SJan Kara 		 * is reaped and thus user could see stale data if he tries to
1922d859db3SJan Kara 		 * read them before the transaction is checkpointed. So be
1932d859db3SJan Kara 		 * careful and force everything to disk here... We use
1942d859db3SJan Kara 		 * ei->i_datasync_tid to store the newest transaction
1952d859db3SJan Kara 		 * containing inode's data.
1962d859db3SJan Kara 		 *
1972d859db3SJan Kara 		 * Note that directories do not have this problem because they
1982d859db3SJan Kara 		 * don't use page cache.
1992d859db3SJan Kara 		 */
2006a7fd522SVegard Nossum 		if (inode->i_ino != EXT4_JOURNAL_INO &&
2016a7fd522SVegard Nossum 		    ext4_should_journal_data(inode) &&
2026493792dSZhang Yi 		    S_ISREG(inode->i_mode) && inode->i_data.nrpages) {
2032d859db3SJan Kara 			journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
2042d859db3SJan Kara 			tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
2052d859db3SJan Kara 
206d76a3a77STheodore Ts'o 			jbd2_complete_transaction(journal, commit_tid);
2072d859db3SJan Kara 			filemap_write_and_wait(&inode->i_data);
2082d859db3SJan Kara 		}
20991b0abe3SJohannes Weiner 		truncate_inode_pages_final(&inode->i_data);
2105dc23bddSJan Kara 
2110930fcc1SAl Viro 		goto no_delete;
2120930fcc1SAl Viro 	}
2130930fcc1SAl Viro 
214e2bfb088STheodore Ts'o 	if (is_bad_inode(inode))
215e2bfb088STheodore Ts'o 		goto no_delete;
216871a2931SChristoph Hellwig 	dquot_initialize(inode);
217907f4554SChristoph Hellwig 
218678aaf48SJan Kara 	if (ext4_should_order_data(inode))
219678aaf48SJan Kara 		ext4_begin_ordered_truncate(inode, 0);
22091b0abe3SJohannes Weiner 	truncate_inode_pages_final(&inode->i_data);
221ac27a0ecSDave Kleikamp 
2228e8ad8a5SJan Kara 	/*
223ceff86fdSJan Kara 	 * For inodes with journalled data, transaction commit could have
224bc12ac98SZhang Yi 	 * dirtied the inode. And for inodes with dioread_nolock, unwritten
225bc12ac98SZhang Yi 	 * extents converting worker could merge extents and also have dirtied
226bc12ac98SZhang Yi 	 * the inode. Flush worker is ignoring it because of I_FREEING flag but
227bc12ac98SZhang Yi 	 * we still need to remove the inode from the writeback lists.
228ceff86fdSJan Kara 	 */
229bc12ac98SZhang Yi 	if (!list_empty_careful(&inode->i_io_list))
230ceff86fdSJan Kara 		inode_io_list_del(inode);
231ceff86fdSJan Kara 
232ceff86fdSJan Kara 	/*
2338e8ad8a5SJan Kara 	 * Protect us against freezing - iput() caller didn't have to have any
23446e294efSJan Kara 	 * protection against it. When we are in a running transaction though,
23546e294efSJan Kara 	 * we are already protected against freezing and we cannot grab further
23646e294efSJan Kara 	 * protection due to lock ordering constraints.
2378e8ad8a5SJan Kara 	 */
23846e294efSJan Kara 	if (!ext4_journal_current_handle()) {
2398e8ad8a5SJan Kara 		sb_start_intwrite(inode->i_sb);
24046e294efSJan Kara 		freeze_protected = true;
24146e294efSJan Kara 	}
242e50e5129SAndreas Dilger 
24330a7eb97STahsin Erdogan 	if (!IS_NOQUOTA(inode))
24430a7eb97STahsin Erdogan 		extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
24530a7eb97STahsin Erdogan 
24665db869cSJan Kara 	/*
24765db869cSJan Kara 	 * Block bitmap, group descriptor, and inode are accounted in both
24865db869cSJan Kara 	 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
24965db869cSJan Kara 	 */
25030a7eb97STahsin Erdogan 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
25165db869cSJan Kara 			 ext4_blocks_for_truncate(inode) + extra_credits - 3);
252ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
253bc965ab3STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
254ac27a0ecSDave Kleikamp 		/*
255ac27a0ecSDave Kleikamp 		 * If we're going to skip the normal cleanup, we still need to
256ac27a0ecSDave Kleikamp 		 * make sure that the in-core orphan linked list is properly
257ac27a0ecSDave Kleikamp 		 * cleaned up.
258ac27a0ecSDave Kleikamp 		 */
259617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
26046e294efSJan Kara 		if (freeze_protected)
2618e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
262ac27a0ecSDave Kleikamp 		goto no_delete;
263ac27a0ecSDave Kleikamp 	}
26430a7eb97STahsin Erdogan 
265ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
2660390131bSFrank Mayhar 		ext4_handle_sync(handle);
267407cd7fbSTahsin Erdogan 
268407cd7fbSTahsin Erdogan 	/*
269407cd7fbSTahsin Erdogan 	 * Set inode->i_size to 0 before calling ext4_truncate(). We need
270407cd7fbSTahsin Erdogan 	 * special handling of symlinks here because i_size is used to
271407cd7fbSTahsin Erdogan 	 * determine whether ext4_inode_info->i_data contains symlink data or
272407cd7fbSTahsin Erdogan 	 * block mappings. Setting i_size to 0 will remove its fast symlink
273407cd7fbSTahsin Erdogan 	 * status. Erase i_data so that it becomes a valid empty block map.
274407cd7fbSTahsin Erdogan 	 */
275407cd7fbSTahsin Erdogan 	if (ext4_inode_is_fast_symlink(inode))
276407cd7fbSTahsin Erdogan 		memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
277ac27a0ecSDave Kleikamp 	inode->i_size = 0;
278bc965ab3STheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
279bc965ab3STheodore Ts'o 	if (err) {
28012062dddSEric Sandeen 		ext4_warning(inode->i_sb,
281bc965ab3STheodore Ts'o 			     "couldn't mark inode dirty (err %d)", err);
282bc965ab3STheodore Ts'o 		goto stop_handle;
283bc965ab3STheodore Ts'o 	}
2842c98eb5eSTheodore Ts'o 	if (inode->i_blocks) {
2852c98eb5eSTheodore Ts'o 		err = ext4_truncate(inode);
2862c98eb5eSTheodore Ts'o 		if (err) {
28754d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err,
2882c98eb5eSTheodore Ts'o 				       "couldn't truncate inode %lu (err %d)",
2892c98eb5eSTheodore Ts'o 				       inode->i_ino, err);
2902c98eb5eSTheodore Ts'o 			goto stop_handle;
2912c98eb5eSTheodore Ts'o 		}
2922c98eb5eSTheodore Ts'o 	}
293bc965ab3STheodore Ts'o 
29430a7eb97STahsin Erdogan 	/* Remove xattr references. */
29530a7eb97STahsin Erdogan 	err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
29630a7eb97STahsin Erdogan 				      extra_credits);
29730a7eb97STahsin Erdogan 	if (err) {
29830a7eb97STahsin Erdogan 		ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
299bc965ab3STheodore Ts'o stop_handle:
300bc965ab3STheodore Ts'o 		ext4_journal_stop(handle);
30145388219STheodore Ts'o 		ext4_orphan_del(NULL, inode);
30246e294efSJan Kara 		if (freeze_protected)
3038e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
30430a7eb97STahsin Erdogan 		ext4_xattr_inode_array_free(ea_inode_array);
305bc965ab3STheodore Ts'o 		goto no_delete;
306bc965ab3STheodore Ts'o 	}
307bc965ab3STheodore Ts'o 
308ac27a0ecSDave Kleikamp 	/*
309617ba13bSMingming Cao 	 * Kill off the orphan record which ext4_truncate created.
310ac27a0ecSDave Kleikamp 	 * AKPM: I think this can be inside the above `if'.
311617ba13bSMingming Cao 	 * Note that ext4_orphan_del() has to be able to cope with the
312ac27a0ecSDave Kleikamp 	 * deletion of a non-existent orphan - this is because we don't
313617ba13bSMingming Cao 	 * know if ext4_truncate() actually created an orphan record.
314ac27a0ecSDave Kleikamp 	 * (Well, we could do this if we need to, but heck - it works)
315ac27a0ecSDave Kleikamp 	 */
316617ba13bSMingming Cao 	ext4_orphan_del(handle, inode);
3175ffff834SArnd Bergmann 	EXT4_I(inode)->i_dtime	= (__u32)ktime_get_real_seconds();
318ac27a0ecSDave Kleikamp 
319ac27a0ecSDave Kleikamp 	/*
320ac27a0ecSDave Kleikamp 	 * One subtle ordering requirement: if anything has gone wrong
321ac27a0ecSDave Kleikamp 	 * (transaction abort, IO errors, whatever), then we can still
322ac27a0ecSDave Kleikamp 	 * do these next steps (the fs will already have been marked as
323ac27a0ecSDave Kleikamp 	 * having errors), but we can't free the inode if the mark_dirty
324ac27a0ecSDave Kleikamp 	 * fails.
325ac27a0ecSDave Kleikamp 	 */
326617ba13bSMingming Cao 	if (ext4_mark_inode_dirty(handle, inode))
327ac27a0ecSDave Kleikamp 		/* If that failed, just do the required in-core inode clear. */
3280930fcc1SAl Viro 		ext4_clear_inode(inode);
329ac27a0ecSDave Kleikamp 	else
330617ba13bSMingming Cao 		ext4_free_inode(handle, inode);
331617ba13bSMingming Cao 	ext4_journal_stop(handle);
33246e294efSJan Kara 	if (freeze_protected)
3338e8ad8a5SJan Kara 		sb_end_intwrite(inode->i_sb);
3340421a189STahsin Erdogan 	ext4_xattr_inode_array_free(ea_inode_array);
335ac27a0ecSDave Kleikamp 	return;
336ac27a0ecSDave Kleikamp no_delete:
337318cdc82SZhang Yi 	/*
338318cdc82SZhang Yi 	 * Check out some where else accidentally dirty the evicting inode,
339318cdc82SZhang Yi 	 * which may probably cause inode use-after-free issues later.
340318cdc82SZhang Yi 	 */
341318cdc82SZhang Yi 	WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));
342318cdc82SZhang Yi 
343b21ebf14SHarshad Shirwadkar 	if (!list_empty(&EXT4_I(inode)->i_fc_list))
344e85c81baSXin Yin 		ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
3450930fcc1SAl Viro 	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
346ac27a0ecSDave Kleikamp }
347ac27a0ecSDave Kleikamp 
348a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
349a9e7f447SDmitry Monakhov qsize_t *ext4_get_reserved_space(struct inode *inode)
35060e58e0fSMingming Cao {
351a9e7f447SDmitry Monakhov 	return &EXT4_I(inode)->i_reserved_quota;
35260e58e0fSMingming Cao }
353a9e7f447SDmitry Monakhov #endif
3549d0be502STheodore Ts'o 
35512219aeaSAneesh Kumar K.V /*
3560637c6f4STheodore Ts'o  * Called with i_data_sem down, which is important since we can call
3570637c6f4STheodore Ts'o  * ext4_discard_preallocations() from here.
3580637c6f4STheodore Ts'o  */
3595f634d06SAneesh Kumar K.V void ext4_da_update_reserve_space(struct inode *inode,
3605f634d06SAneesh Kumar K.V 					int used, int quota_claim)
36112219aeaSAneesh Kumar K.V {
36212219aeaSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3630637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
36412219aeaSAneesh Kumar K.V 
3650637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
366d8990240SAditya Kali 	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
3670637c6f4STheodore Ts'o 	if (unlikely(used > ei->i_reserved_data_blocks)) {
3688de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
3691084f252STheodore Ts'o 			 "with only %d reserved data blocks",
3700637c6f4STheodore Ts'o 			 __func__, inode->i_ino, used,
3710637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
3720637c6f4STheodore Ts'o 		WARN_ON(1);
3730637c6f4STheodore Ts'o 		used = ei->i_reserved_data_blocks;
3746bc6e63fSAneesh Kumar K.V 	}
37512219aeaSAneesh Kumar K.V 
3760637c6f4STheodore Ts'o 	/* Update per-inode reservations */
3770637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= used;
37871d4f7d0STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
3790637c6f4STheodore Ts'o 
380f9505c72Schenyichong 	spin_unlock(&ei->i_block_reservation_lock);
38160e58e0fSMingming Cao 
38272b8ab9dSEric Sandeen 	/* Update quota subsystem for data blocks */
38372b8ab9dSEric Sandeen 	if (quota_claim)
3847b415bf6SAditya Kali 		dquot_claim_block(inode, EXT4_C2B(sbi, used));
38572b8ab9dSEric Sandeen 	else {
3865f634d06SAneesh Kumar K.V 		/*
3875f634d06SAneesh Kumar K.V 		 * We did fallocate with an offset that is already delayed
3885f634d06SAneesh Kumar K.V 		 * allocated. So on delayed allocated writeback we should
38972b8ab9dSEric Sandeen 		 * not re-claim the quota for fallocated blocks.
3905f634d06SAneesh Kumar K.V 		 */
3917b415bf6SAditya Kali 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
3925f634d06SAneesh Kumar K.V 	}
393d6014301SAneesh Kumar K.V 
394d6014301SAneesh Kumar K.V 	/*
395d6014301SAneesh Kumar K.V 	 * If we have done all the pending block allocations and if
396d6014301SAneesh Kumar K.V 	 * there aren't any writers on the inode, we can discard the
397d6014301SAneesh Kumar K.V 	 * inode's preallocations.
398d6014301SAneesh Kumar K.V 	 */
3990637c6f4STheodore Ts'o 	if ((ei->i_reserved_data_blocks == 0) &&
40082dd124cSNikolay Borisov 	    !inode_is_open_for_write(inode))
40127bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
40212219aeaSAneesh Kumar K.V }
40312219aeaSAneesh Kumar K.V 
404e29136f8STheodore Ts'o static int __check_block_validity(struct inode *inode, const char *func,
405c398eda0STheodore Ts'o 				unsigned int line,
40624676da4STheodore Ts'o 				struct ext4_map_blocks *map)
4076fd058f7STheodore Ts'o {
408345c0dbfSTheodore Ts'o 	if (ext4_has_feature_journal(inode->i_sb) &&
409345c0dbfSTheodore Ts'o 	    (inode->i_ino ==
410345c0dbfSTheodore Ts'o 	     le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
411345c0dbfSTheodore Ts'o 		return 0;
412ce9f24ccSJan Kara 	if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
413c398eda0STheodore Ts'o 		ext4_error_inode(inode, func, line, map->m_pblk,
414bdbd6ce0STheodore Ts'o 				 "lblock %lu mapped to illegal pblock %llu "
41524676da4STheodore Ts'o 				 "(length %d)", (unsigned long) map->m_lblk,
416bdbd6ce0STheodore Ts'o 				 map->m_pblk, map->m_len);
4176a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4186fd058f7STheodore Ts'o 	}
4196fd058f7STheodore Ts'o 	return 0;
4206fd058f7STheodore Ts'o }
4216fd058f7STheodore Ts'o 
42253085facSJan Kara int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
42353085facSJan Kara 		       ext4_lblk_t len)
42453085facSJan Kara {
42553085facSJan Kara 	int ret;
42653085facSJan Kara 
42733b4cc25SEric Biggers 	if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
428a7550b30SJaegeuk Kim 		return fscrypt_zeroout_range(inode, lblk, pblk, len);
42953085facSJan Kara 
43053085facSJan Kara 	ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
43153085facSJan Kara 	if (ret > 0)
43253085facSJan Kara 		ret = 0;
43353085facSJan Kara 
43453085facSJan Kara 	return ret;
43553085facSJan Kara }
43653085facSJan Kara 
437e29136f8STheodore Ts'o #define check_block_validity(inode, map)	\
438c398eda0STheodore Ts'o 	__check_block_validity((inode), __func__, __LINE__, (map))
439e29136f8STheodore Ts'o 
440921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
441921f266bSDmitry Monakhov static void ext4_map_blocks_es_recheck(handle_t *handle,
442921f266bSDmitry Monakhov 				       struct inode *inode,
443921f266bSDmitry Monakhov 				       struct ext4_map_blocks *es_map,
444921f266bSDmitry Monakhov 				       struct ext4_map_blocks *map,
445921f266bSDmitry Monakhov 				       int flags)
446921f266bSDmitry Monakhov {
447921f266bSDmitry Monakhov 	int retval;
448921f266bSDmitry Monakhov 
449921f266bSDmitry Monakhov 	map->m_flags = 0;
450921f266bSDmitry Monakhov 	/*
451921f266bSDmitry Monakhov 	 * There is a race window that the result is not the same.
452921f266bSDmitry Monakhov 	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
453921f266bSDmitry Monakhov 	 * is that we lookup a block mapping in extent status tree with
454921f266bSDmitry Monakhov 	 * out taking i_data_sem.  So at the time the unwritten extent
455921f266bSDmitry Monakhov 	 * could be converted.
456921f266bSDmitry Monakhov 	 */
457c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
458921f266bSDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4599e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
460921f266bSDmitry Monakhov 	} else {
4619e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
462921f266bSDmitry Monakhov 	}
463921f266bSDmitry Monakhov 	up_read((&EXT4_I(inode)->i_data_sem));
464921f266bSDmitry Monakhov 
465921f266bSDmitry Monakhov 	/*
466921f266bSDmitry Monakhov 	 * We don't check m_len because extent will be collpased in status
467921f266bSDmitry Monakhov 	 * tree.  So the m_len might not equal.
468921f266bSDmitry Monakhov 	 */
469921f266bSDmitry Monakhov 	if (es_map->m_lblk != map->m_lblk ||
470921f266bSDmitry Monakhov 	    es_map->m_flags != map->m_flags ||
471921f266bSDmitry Monakhov 	    es_map->m_pblk != map->m_pblk) {
472bdafe42aSTheodore Ts'o 		printk("ES cache assertion failed for inode: %lu "
473921f266bSDmitry Monakhov 		       "es_cached ex [%d/%d/%llu/%x] != "
474921f266bSDmitry Monakhov 		       "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
475921f266bSDmitry Monakhov 		       inode->i_ino, es_map->m_lblk, es_map->m_len,
476921f266bSDmitry Monakhov 		       es_map->m_pblk, es_map->m_flags, map->m_lblk,
477921f266bSDmitry Monakhov 		       map->m_len, map->m_pblk, map->m_flags,
478921f266bSDmitry Monakhov 		       retval, flags);
479921f266bSDmitry Monakhov 	}
480921f266bSDmitry Monakhov }
481921f266bSDmitry Monakhov #endif /* ES_AGGRESSIVE_TEST */
482921f266bSDmitry Monakhov 
48355138e0bSTheodore Ts'o /*
484e35fd660STheodore Ts'o  * The ext4_map_blocks() function tries to look up the requested blocks,
4852b2d6d01STheodore Ts'o  * and returns if the blocks are already mapped.
486f5ab0d1fSMingming Cao  *
487f5ab0d1fSMingming Cao  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
488f5ab0d1fSMingming Cao  * and store the allocated blocks in the result buffer head and mark it
489f5ab0d1fSMingming Cao  * mapped.
490f5ab0d1fSMingming Cao  *
491e35fd660STheodore Ts'o  * If file type is extents based, it will call ext4_ext_map_blocks(),
492e35fd660STheodore Ts'o  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
493f5ab0d1fSMingming Cao  * based files
494f5ab0d1fSMingming Cao  *
495facab4d9SJan Kara  * On success, it returns the number of blocks being mapped or allocated.  if
496facab4d9SJan Kara  * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
497facab4d9SJan Kara  * is marked as unwritten. If the create == 1, it will mark @map as mapped.
498f5ab0d1fSMingming Cao  *
499f5ab0d1fSMingming Cao  * It returns 0 if plain look up failed (blocks have not been allocated), in
500facab4d9SJan Kara  * that case, @map is returned as unmapped but we still do fill map->m_len to
501facab4d9SJan Kara  * indicate the length of a hole starting at map->m_lblk.
502f5ab0d1fSMingming Cao  *
503f5ab0d1fSMingming Cao  * It returns the error in case of allocation failure.
504f5ab0d1fSMingming Cao  */
505e35fd660STheodore Ts'o int ext4_map_blocks(handle_t *handle, struct inode *inode,
506e35fd660STheodore Ts'o 		    struct ext4_map_blocks *map, int flags)
5070e855ac8SAneesh Kumar K.V {
508d100eef2SZheng Liu 	struct extent_status es;
5090e855ac8SAneesh Kumar K.V 	int retval;
510b8a86845SLukas Czerner 	int ret = 0;
511921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
512921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
513921f266bSDmitry Monakhov 
514921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
515921f266bSDmitry Monakhov #endif
516f5ab0d1fSMingming Cao 
517e35fd660STheodore Ts'o 	map->m_flags = 0;
51870aa1554SRitesh Harjani 	ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
51970aa1554SRitesh Harjani 		  flags, map->m_len, (unsigned long) map->m_lblk);
520d100eef2SZheng Liu 
521e861b5e9STheodore Ts'o 	/*
522e861b5e9STheodore Ts'o 	 * ext4_map_blocks returns an int, and m_len is an unsigned int
523e861b5e9STheodore Ts'o 	 */
524e861b5e9STheodore Ts'o 	if (unlikely(map->m_len > INT_MAX))
525e861b5e9STheodore Ts'o 		map->m_len = INT_MAX;
526e861b5e9STheodore Ts'o 
5274adb6ab3SKazuya Mio 	/* We can handle the block number less than EXT_MAX_BLOCKS */
5284adb6ab3SKazuya Mio 	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
5296a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
5304adb6ab3SKazuya Mio 
531d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
5328016e29fSHarshad Shirwadkar 	if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
5338016e29fSHarshad Shirwadkar 	    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
534d100eef2SZheng Liu 		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
535d100eef2SZheng Liu 			map->m_pblk = ext4_es_pblock(&es) +
536d100eef2SZheng Liu 					map->m_lblk - es.es_lblk;
537d100eef2SZheng Liu 			map->m_flags |= ext4_es_is_written(&es) ?
538d100eef2SZheng Liu 					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
539d100eef2SZheng Liu 			retval = es.es_len - (map->m_lblk - es.es_lblk);
540d100eef2SZheng Liu 			if (retval > map->m_len)
541d100eef2SZheng Liu 				retval = map->m_len;
542d100eef2SZheng Liu 			map->m_len = retval;
543d100eef2SZheng Liu 		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
544facab4d9SJan Kara 			map->m_pblk = 0;
545facab4d9SJan Kara 			retval = es.es_len - (map->m_lblk - es.es_lblk);
546facab4d9SJan Kara 			if (retval > map->m_len)
547facab4d9SJan Kara 				retval = map->m_len;
548facab4d9SJan Kara 			map->m_len = retval;
549d100eef2SZheng Liu 			retval = 0;
550d100eef2SZheng Liu 		} else {
5511e83bc81SArnd Bergmann 			BUG();
552d100eef2SZheng Liu 		}
5539558cf14SZhang Yi 
5549558cf14SZhang Yi 		if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5559558cf14SZhang Yi 			return retval;
556921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
557921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(handle, inode, map,
558921f266bSDmitry Monakhov 					   &orig_map, flags);
559921f266bSDmitry Monakhov #endif
560d100eef2SZheng Liu 		goto found;
561d100eef2SZheng Liu 	}
5629558cf14SZhang Yi 	/*
5639558cf14SZhang Yi 	 * In the query cache no-wait mode, nothing we can do more if we
5649558cf14SZhang Yi 	 * cannot find extent in the cache.
5659558cf14SZhang Yi 	 */
5669558cf14SZhang Yi 	if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5679558cf14SZhang Yi 		return 0;
568d100eef2SZheng Liu 
5694df3d265SAneesh Kumar K.V 	/*
570b920c755STheodore Ts'o 	 * Try to see if we can get the block without requesting a new
571b920c755STheodore Ts'o 	 * file system block.
5724df3d265SAneesh Kumar K.V 	 */
573c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
57412e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5759e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
5764df3d265SAneesh Kumar K.V 	} else {
5779e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
5780e855ac8SAneesh Kumar K.V 	}
579f7fec032SZheng Liu 	if (retval > 0) {
5803be78c73STheodore Ts'o 		unsigned int status;
581f7fec032SZheng Liu 
58244fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
58344fb851dSZheng Liu 			ext4_warning(inode->i_sb,
58444fb851dSZheng Liu 				     "ES len assertion failed for inode "
58544fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
58644fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
58744fb851dSZheng Liu 			WARN_ON(1);
588921f266bSDmitry Monakhov 		}
589921f266bSDmitry Monakhov 
590f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
591f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
592f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
593d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
594ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
595f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
596f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
597f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk,
598f7fec032SZheng Liu 					    map->m_len, map->m_pblk, status);
599f7fec032SZheng Liu 		if (ret < 0)
600f7fec032SZheng Liu 			retval = ret;
601f7fec032SZheng Liu 	}
6024df3d265SAneesh Kumar K.V 	up_read((&EXT4_I(inode)->i_data_sem));
603f5ab0d1fSMingming Cao 
604d100eef2SZheng Liu found:
605e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
606b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
6076fd058f7STheodore Ts'o 		if (ret != 0)
6086fd058f7STheodore Ts'o 			return ret;
6096fd058f7STheodore Ts'o 	}
6106fd058f7STheodore Ts'o 
611f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
612c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
6134df3d265SAneesh Kumar K.V 		return retval;
6144df3d265SAneesh Kumar K.V 
6154df3d265SAneesh Kumar K.V 	/*
616f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
617f5ab0d1fSMingming Cao 	 *
618f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
619df3ab170STao Ma 	 * ext4_ext_get_block() returns the create = 0
620f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
621f5ab0d1fSMingming Cao 	 */
622e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
623b8a86845SLukas Czerner 		/*
624b8a86845SLukas Czerner 		 * If we need to convert extent to unwritten
625b8a86845SLukas Czerner 		 * we continue and do the actual work in
626b8a86845SLukas Czerner 		 * ext4_ext_map_blocks()
627b8a86845SLukas Czerner 		 */
628b8a86845SLukas Czerner 		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
629f5ab0d1fSMingming Cao 			return retval;
630f5ab0d1fSMingming Cao 
631f5ab0d1fSMingming Cao 	/*
632a25a4e1aSZheng Liu 	 * Here we clear m_flags because after allocating an new extent,
633a25a4e1aSZheng Liu 	 * it will be set again.
6342a8964d6SAneesh Kumar K.V 	 */
635a25a4e1aSZheng Liu 	map->m_flags &= ~EXT4_MAP_FLAGS;
6362a8964d6SAneesh Kumar K.V 
6372a8964d6SAneesh Kumar K.V 	/*
638556615dcSLukas Czerner 	 * New blocks allocate and/or writing to unwritten extent
639f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
640d91bd2c1SSeunghun Lee 	 * the write lock of i_data_sem, and call get_block()
641f5ab0d1fSMingming Cao 	 * with create == 1 flag.
6424df3d265SAneesh Kumar K.V 	 */
643c8b459f4SLukas Czerner 	down_write(&EXT4_I(inode)->i_data_sem);
644d2a17637SMingming Cao 
645d2a17637SMingming Cao 	/*
6464df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
6474df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
6484df3d265SAneesh Kumar K.V 	 */
64912e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
650e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
6510e855ac8SAneesh Kumar K.V 	} else {
652e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
653267e4db9SAneesh Kumar K.V 
654e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
655267e4db9SAneesh Kumar K.V 			/*
656267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
657267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
658267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
659267e4db9SAneesh Kumar K.V 			 */
66019f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
661267e4db9SAneesh Kumar K.V 		}
6622ac3b6e0STheodore Ts'o 
663d2a17637SMingming Cao 		/*
6642ac3b6e0STheodore Ts'o 		 * Update reserved blocks/metadata blocks after successful
6655f634d06SAneesh Kumar K.V 		 * block allocation which had been deferred till now. We don't
6665f634d06SAneesh Kumar K.V 		 * support fallocate for non extent files. So we can update
6675f634d06SAneesh Kumar K.V 		 * reserve space here.
668d2a17637SMingming Cao 		 */
6695f634d06SAneesh Kumar K.V 		if ((retval > 0) &&
6701296cc85SAneesh Kumar K.V 			(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
6715f634d06SAneesh Kumar K.V 			ext4_da_update_reserve_space(inode, retval, 1);
6725f634d06SAneesh Kumar K.V 	}
673d2a17637SMingming Cao 
674f7fec032SZheng Liu 	if (retval > 0) {
6753be78c73STheodore Ts'o 		unsigned int status;
676f7fec032SZheng Liu 
67744fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
67844fb851dSZheng Liu 			ext4_warning(inode->i_sb,
67944fb851dSZheng Liu 				     "ES len assertion failed for inode "
68044fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
68144fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
68244fb851dSZheng Liu 			WARN_ON(1);
683921f266bSDmitry Monakhov 		}
684921f266bSDmitry Monakhov 
685adb23551SZheng Liu 		/*
686c86d8db3SJan Kara 		 * We have to zeroout blocks before inserting them into extent
687c86d8db3SJan Kara 		 * status tree. Otherwise someone could look them up there and
6889b623df6SJan Kara 		 * use them before they are really zeroed. We also have to
6899b623df6SJan Kara 		 * unmap metadata before zeroing as otherwise writeback can
6909b623df6SJan Kara 		 * overwrite zeros with stale data from block device.
691c86d8db3SJan Kara 		 */
692c86d8db3SJan Kara 		if (flags & EXT4_GET_BLOCKS_ZERO &&
693c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_MAPPED &&
694c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_NEW) {
695c86d8db3SJan Kara 			ret = ext4_issue_zeroout(inode, map->m_lblk,
696c86d8db3SJan Kara 						 map->m_pblk, map->m_len);
697c86d8db3SJan Kara 			if (ret) {
698c86d8db3SJan Kara 				retval = ret;
699c86d8db3SJan Kara 				goto out_sem;
700c86d8db3SJan Kara 			}
701c86d8db3SJan Kara 		}
702c86d8db3SJan Kara 
703c86d8db3SJan Kara 		/*
704adb23551SZheng Liu 		 * If the extent has been zeroed out, we don't need to update
705adb23551SZheng Liu 		 * extent status tree.
706adb23551SZheng Liu 		 */
707adb23551SZheng Liu 		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
708bb5835edSTheodore Ts'o 		    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
709adb23551SZheng Liu 			if (ext4_es_is_written(&es))
710c86d8db3SJan Kara 				goto out_sem;
711adb23551SZheng Liu 		}
712f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
713f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
714f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
715d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
716ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
717f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
718f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
719f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
720f7fec032SZheng Liu 					    map->m_pblk, status);
721c86d8db3SJan Kara 		if (ret < 0) {
72251865fdaSZheng Liu 			retval = ret;
723c86d8db3SJan Kara 			goto out_sem;
724c86d8db3SJan Kara 		}
72551865fdaSZheng Liu 	}
7265356f261SAditya Kali 
727c86d8db3SJan Kara out_sem:
7280e855ac8SAneesh Kumar K.V 	up_write((&EXT4_I(inode)->i_data_sem));
729e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
730b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
7316fd058f7STheodore Ts'o 		if (ret != 0)
7326fd058f7STheodore Ts'o 			return ret;
73306bd3c36SJan Kara 
73406bd3c36SJan Kara 		/*
73506bd3c36SJan Kara 		 * Inodes with freshly allocated blocks where contents will be
73606bd3c36SJan Kara 		 * visible after transaction commit must be on transaction's
73706bd3c36SJan Kara 		 * ordered data list.
73806bd3c36SJan Kara 		 */
73906bd3c36SJan Kara 		if (map->m_flags & EXT4_MAP_NEW &&
74006bd3c36SJan Kara 		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
74106bd3c36SJan Kara 		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
74202749a4cSTahsin Erdogan 		    !ext4_is_quota_file(inode) &&
74306bd3c36SJan Kara 		    ext4_should_order_data(inode)) {
74473131fbbSRoss Zwisler 			loff_t start_byte =
74573131fbbSRoss Zwisler 				(loff_t)map->m_lblk << inode->i_blkbits;
74673131fbbSRoss Zwisler 			loff_t length = (loff_t)map->m_len << inode->i_blkbits;
74773131fbbSRoss Zwisler 
748ee0876bcSJan Kara 			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
74973131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_wait(handle, inode,
75073131fbbSRoss Zwisler 						start_byte, length);
751ee0876bcSJan Kara 			else
75273131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_write(handle, inode,
75373131fbbSRoss Zwisler 						start_byte, length);
75406bd3c36SJan Kara 			if (ret)
75506bd3c36SJan Kara 				return ret;
75606bd3c36SJan Kara 		}
7575e4d0ebaSXin Yin 	}
7585e4d0ebaSXin Yin 	if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
7595e4d0ebaSXin Yin 				map->m_flags & EXT4_MAP_MAPPED))
760a80f7fcfSHarshad Shirwadkar 		ext4_fc_track_range(handle, inode, map->m_lblk,
761aa75f4d3SHarshad Shirwadkar 					map->m_lblk + map->m_len - 1);
762ec8c60beSRitesh Harjani 	if (retval < 0)
76370aa1554SRitesh Harjani 		ext_debug(inode, "failed with err %d\n", retval);
7640e855ac8SAneesh Kumar K.V 	return retval;
7650e855ac8SAneesh Kumar K.V }
7660e855ac8SAneesh Kumar K.V 
767ed8ad838SJan Kara /*
768ed8ad838SJan Kara  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
769ed8ad838SJan Kara  * we have to be careful as someone else may be manipulating b_state as well.
770ed8ad838SJan Kara  */
771ed8ad838SJan Kara static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
772ed8ad838SJan Kara {
773ed8ad838SJan Kara 	unsigned long old_state;
774ed8ad838SJan Kara 	unsigned long new_state;
775ed8ad838SJan Kara 
776ed8ad838SJan Kara 	flags &= EXT4_MAP_FLAGS;
777ed8ad838SJan Kara 
778ed8ad838SJan Kara 	/* Dummy buffer_head? Set non-atomically. */
779ed8ad838SJan Kara 	if (!bh->b_page) {
780ed8ad838SJan Kara 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
781ed8ad838SJan Kara 		return;
782ed8ad838SJan Kara 	}
783ed8ad838SJan Kara 	/*
784ed8ad838SJan Kara 	 * Someone else may be modifying b_state. Be careful! This is ugly but
785ed8ad838SJan Kara 	 * once we get rid of using bh as a container for mapping information
786ed8ad838SJan Kara 	 * to pass to / from get_block functions, this can go away.
787ed8ad838SJan Kara 	 */
788ed8ad838SJan Kara 	old_state = READ_ONCE(bh->b_state);
7893ee2a3e7SUros Bizjak 	do {
790ed8ad838SJan Kara 		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
7913ee2a3e7SUros Bizjak 	} while (unlikely(!try_cmpxchg(&bh->b_state, &old_state, new_state)));
792ed8ad838SJan Kara }
793ed8ad838SJan Kara 
7942ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
7952ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
796ac27a0ecSDave Kleikamp {
7972ed88685STheodore Ts'o 	struct ext4_map_blocks map;
798efe70c29SJan Kara 	int ret = 0;
799ac27a0ecSDave Kleikamp 
80046c7f254STao Ma 	if (ext4_has_inline_data(inode))
80146c7f254STao Ma 		return -ERANGE;
80246c7f254STao Ma 
8032ed88685STheodore Ts'o 	map.m_lblk = iblock;
8042ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
8052ed88685STheodore Ts'o 
806efe70c29SJan Kara 	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
807efe70c29SJan Kara 			      flags);
808ac27a0ecSDave Kleikamp 	if (ret > 0) {
8092ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
810ed8ad838SJan Kara 		ext4_update_bh_state(bh, map.m_flags);
8112ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
812ac27a0ecSDave Kleikamp 		ret = 0;
813547edce3SRoss Zwisler 	} else if (ret == 0) {
814547edce3SRoss Zwisler 		/* hole case, need to fill in bh->b_size */
815547edce3SRoss Zwisler 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
816ac27a0ecSDave Kleikamp 	}
817ac27a0ecSDave Kleikamp 	return ret;
818ac27a0ecSDave Kleikamp }
819ac27a0ecSDave Kleikamp 
8202ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
8212ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
8222ed88685STheodore Ts'o {
8232ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
8242ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
8252ed88685STheodore Ts'o }
8262ed88685STheodore Ts'o 
827ac27a0ecSDave Kleikamp /*
828705965bdSJan Kara  * Get block function used when preparing for buffered write if we require
829705965bdSJan Kara  * creating an unwritten extent if blocks haven't been allocated.  The extent
830705965bdSJan Kara  * will be converted to written after the IO is complete.
831705965bdSJan Kara  */
832705965bdSJan Kara int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
833705965bdSJan Kara 			     struct buffer_head *bh_result, int create)
834705965bdSJan Kara {
835705965bdSJan Kara 	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
836705965bdSJan Kara 		   inode->i_ino, create);
837705965bdSJan Kara 	return _ext4_get_block(inode, iblock, bh_result,
8388d5459c1SJan Kara 			       EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
839705965bdSJan Kara }
840705965bdSJan Kara 
841efe70c29SJan Kara /* Maximum number of blocks we map for direct IO at once. */
842efe70c29SJan Kara #define DIO_MAX_BLOCKS 4096
843efe70c29SJan Kara 
844e84dfbe2SJan Kara /*
845ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
846ac27a0ecSDave Kleikamp  */
847617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
848c5e298aeSTheodore Ts'o 				ext4_lblk_t block, int map_flags)
849ac27a0ecSDave Kleikamp {
8502ed88685STheodore Ts'o 	struct ext4_map_blocks map;
8512ed88685STheodore Ts'o 	struct buffer_head *bh;
852c5e298aeSTheodore Ts'o 	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
8539558cf14SZhang Yi 	bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
85410560082STheodore Ts'o 	int err;
855ac27a0ecSDave Kleikamp 
856837c23fbSChunguang Xu 	ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8578016e29fSHarshad Shirwadkar 		    || handle != NULL || create == 0);
8589558cf14SZhang Yi 	ASSERT(create == 0 || !nowait);
859ac27a0ecSDave Kleikamp 
8602ed88685STheodore Ts'o 	map.m_lblk = block;
8612ed88685STheodore Ts'o 	map.m_len = 1;
862c5e298aeSTheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map, map_flags);
8632ed88685STheodore Ts'o 
86410560082STheodore Ts'o 	if (err == 0)
86510560082STheodore Ts'o 		return create ? ERR_PTR(-ENOSPC) : NULL;
8662ed88685STheodore Ts'o 	if (err < 0)
86710560082STheodore Ts'o 		return ERR_PTR(err);
8682ed88685STheodore Ts'o 
8699558cf14SZhang Yi 	if (nowait)
8709558cf14SZhang Yi 		return sb_find_get_block(inode->i_sb, map.m_pblk);
8719558cf14SZhang Yi 
8722ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
87310560082STheodore Ts'o 	if (unlikely(!bh))
87410560082STheodore Ts'o 		return ERR_PTR(-ENOMEM);
8752ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
876837c23fbSChunguang Xu 		ASSERT(create != 0);
877837c23fbSChunguang Xu 		ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8788016e29fSHarshad Shirwadkar 			    || (handle != NULL));
879ac27a0ecSDave Kleikamp 
880ac27a0ecSDave Kleikamp 		/*
881ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
882ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
883ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
884617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
885ac27a0ecSDave Kleikamp 		 * problem.
886ac27a0ecSDave Kleikamp 		 */
887ac27a0ecSDave Kleikamp 		lock_buffer(bh);
888ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
889188c299eSJan Kara 		err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
890188c299eSJan Kara 						     EXT4_JTR_NONE);
89110560082STheodore Ts'o 		if (unlikely(err)) {
89210560082STheodore Ts'o 			unlock_buffer(bh);
89310560082STheodore Ts'o 			goto errout;
89410560082STheodore Ts'o 		}
89510560082STheodore Ts'o 		if (!buffer_uptodate(bh)) {
896ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
897ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
898ac27a0ecSDave Kleikamp 		}
899ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
9000390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
9010390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
90210560082STheodore Ts'o 		if (unlikely(err))
90310560082STheodore Ts'o 			goto errout;
90410560082STheodore Ts'o 	} else
905ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
906ac27a0ecSDave Kleikamp 	return bh;
90710560082STheodore Ts'o errout:
90810560082STheodore Ts'o 	brelse(bh);
90910560082STheodore Ts'o 	return ERR_PTR(err);
910ac27a0ecSDave Kleikamp }
911ac27a0ecSDave Kleikamp 
912617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
913c5e298aeSTheodore Ts'o 			       ext4_lblk_t block, int map_flags)
914ac27a0ecSDave Kleikamp {
915ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
9162d069c08Szhangyi (F) 	int ret;
917ac27a0ecSDave Kleikamp 
918c5e298aeSTheodore Ts'o 	bh = ext4_getblk(handle, inode, block, map_flags);
9191c215028STheodore Ts'o 	if (IS_ERR(bh))
920ac27a0ecSDave Kleikamp 		return bh;
9217963e5acSZhangXiaoxu 	if (!bh || ext4_buffer_uptodate(bh))
922ac27a0ecSDave Kleikamp 		return bh;
9232d069c08Szhangyi (F) 
9242d069c08Szhangyi (F) 	ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
9252d069c08Szhangyi (F) 	if (ret) {
926ac27a0ecSDave Kleikamp 		put_bh(bh);
9272d069c08Szhangyi (F) 		return ERR_PTR(ret);
9282d069c08Szhangyi (F) 	}
9292d069c08Szhangyi (F) 	return bh;
930ac27a0ecSDave Kleikamp }
931ac27a0ecSDave Kleikamp 
9329699d4f9STahsin Erdogan /* Read a contiguous batch of blocks. */
9339699d4f9STahsin Erdogan int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
9349699d4f9STahsin Erdogan 		     bool wait, struct buffer_head **bhs)
9359699d4f9STahsin Erdogan {
9369699d4f9STahsin Erdogan 	int i, err;
9379699d4f9STahsin Erdogan 
9389699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9399699d4f9STahsin Erdogan 		bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
9409699d4f9STahsin Erdogan 		if (IS_ERR(bhs[i])) {
9419699d4f9STahsin Erdogan 			err = PTR_ERR(bhs[i]);
9429699d4f9STahsin Erdogan 			bh_count = i;
9439699d4f9STahsin Erdogan 			goto out_brelse;
9449699d4f9STahsin Erdogan 		}
9459699d4f9STahsin Erdogan 	}
9469699d4f9STahsin Erdogan 
9479699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9489699d4f9STahsin Erdogan 		/* Note that NULL bhs[i] is valid because of holes. */
9492d069c08Szhangyi (F) 		if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
9502d069c08Szhangyi (F) 			ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
9519699d4f9STahsin Erdogan 
9529699d4f9STahsin Erdogan 	if (!wait)
9539699d4f9STahsin Erdogan 		return 0;
9549699d4f9STahsin Erdogan 
9559699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9569699d4f9STahsin Erdogan 		if (bhs[i])
9579699d4f9STahsin Erdogan 			wait_on_buffer(bhs[i]);
9589699d4f9STahsin Erdogan 
9599699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9609699d4f9STahsin Erdogan 		if (bhs[i] && !buffer_uptodate(bhs[i])) {
9619699d4f9STahsin Erdogan 			err = -EIO;
9629699d4f9STahsin Erdogan 			goto out_brelse;
9639699d4f9STahsin Erdogan 		}
9649699d4f9STahsin Erdogan 	}
9659699d4f9STahsin Erdogan 	return 0;
9669699d4f9STahsin Erdogan 
9679699d4f9STahsin Erdogan out_brelse:
9689699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9699699d4f9STahsin Erdogan 		brelse(bhs[i]);
9709699d4f9STahsin Erdogan 		bhs[i] = NULL;
9719699d4f9STahsin Erdogan 	}
9729699d4f9STahsin Erdogan 	return err;
9739699d4f9STahsin Erdogan }
9749699d4f9STahsin Erdogan 
975188c299eSJan Kara int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
976ac27a0ecSDave Kleikamp 			   struct buffer_head *head,
977ac27a0ecSDave Kleikamp 			   unsigned from,
978ac27a0ecSDave Kleikamp 			   unsigned to,
979ac27a0ecSDave Kleikamp 			   int *partial,
980188c299eSJan Kara 			   int (*fn)(handle_t *handle, struct inode *inode,
981ac27a0ecSDave Kleikamp 				     struct buffer_head *bh))
982ac27a0ecSDave Kleikamp {
983ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
984ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
985ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
986ac27a0ecSDave Kleikamp 	int err, ret = 0;
987ac27a0ecSDave Kleikamp 	struct buffer_head *next;
988ac27a0ecSDave Kleikamp 
989ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
990ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
991de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
992ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
993ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
994ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
995ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
996ac27a0ecSDave Kleikamp 				*partial = 1;
997ac27a0ecSDave Kleikamp 			continue;
998ac27a0ecSDave Kleikamp 		}
999188c299eSJan Kara 		err = (*fn)(handle, inode, bh);
1000ac27a0ecSDave Kleikamp 		if (!ret)
1001ac27a0ecSDave Kleikamp 			ret = err;
1002ac27a0ecSDave Kleikamp 	}
1003ac27a0ecSDave Kleikamp 	return ret;
1004ac27a0ecSDave Kleikamp }
1005ac27a0ecSDave Kleikamp 
1006d84c9ebdSJan Kara /*
1007d84c9ebdSJan Kara  * Helper for handling dirtying of journalled data. We also mark the folio as
1008d84c9ebdSJan Kara  * dirty so that writeback code knows about this page (and inode) contains
1009d84c9ebdSJan Kara  * dirty data. ext4_writepages() then commits appropriate transaction to
1010d84c9ebdSJan Kara  * make data stable.
1011d84c9ebdSJan Kara  */
1012d84c9ebdSJan Kara static int ext4_dirty_journalled_data(handle_t *handle, struct buffer_head *bh)
1013d84c9ebdSJan Kara {
1014d84c9ebdSJan Kara 	folio_mark_dirty(bh->b_folio);
1015d84c9ebdSJan Kara 	return ext4_handle_dirty_metadata(handle, NULL, bh);
1016d84c9ebdSJan Kara }
1017d84c9ebdSJan Kara 
1018188c299eSJan Kara int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1019ac27a0ecSDave Kleikamp 				struct buffer_head *bh)
1020ac27a0ecSDave Kleikamp {
102156d35a4cSJan Kara 	int dirty = buffer_dirty(bh);
102256d35a4cSJan Kara 	int ret;
102356d35a4cSJan Kara 
1024ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1025ac27a0ecSDave Kleikamp 		return 0;
102656d35a4cSJan Kara 	/*
1027ebdec241SChristoph Hellwig 	 * __block_write_begin() could have dirtied some buffers. Clean
102856d35a4cSJan Kara 	 * the dirty bit as jbd2_journal_get_write_access() could complain
102956d35a4cSJan Kara 	 * otherwise about fs integrity issues. Setting of the dirty bit
1030ebdec241SChristoph Hellwig 	 * by __block_write_begin() isn't a real problem here as we clear
103156d35a4cSJan Kara 	 * the bit before releasing a page lock and thus writeback cannot
103256d35a4cSJan Kara 	 * ever write the buffer.
103356d35a4cSJan Kara 	 */
103456d35a4cSJan Kara 	if (dirty)
103556d35a4cSJan Kara 		clear_buffer_dirty(bh);
10365d601255Sliang xie 	BUFFER_TRACE(bh, "get write access");
1037188c299eSJan Kara 	ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
1038188c299eSJan Kara 					    EXT4_JTR_NONE);
103956d35a4cSJan Kara 	if (!ret && dirty)
1040d84c9ebdSJan Kara 		ret = ext4_dirty_journalled_data(handle, bh);
104156d35a4cSJan Kara 	return ret;
1042ac27a0ecSDave Kleikamp }
1043ac27a0ecSDave Kleikamp 
1044643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
104586b38c27SMatthew Wilcox static int ext4_block_write_begin(struct folio *folio, loff_t pos, unsigned len,
10462058f83aSMichael Halcrow 				  get_block_t *get_block)
10472058f83aSMichael Halcrow {
104809cbfeafSKirill A. Shutemov 	unsigned from = pos & (PAGE_SIZE - 1);
10492058f83aSMichael Halcrow 	unsigned to = from + len;
105086b38c27SMatthew Wilcox 	struct inode *inode = folio->mapping->host;
10512058f83aSMichael Halcrow 	unsigned block_start, block_end;
10522058f83aSMichael Halcrow 	sector_t block;
10532058f83aSMichael Halcrow 	int err = 0;
10542058f83aSMichael Halcrow 	unsigned blocksize = inode->i_sb->s_blocksize;
10552058f83aSMichael Halcrow 	unsigned bbits;
10560b578f35SChandan Rajendra 	struct buffer_head *bh, *head, *wait[2];
10570b578f35SChandan Rajendra 	int nr_wait = 0;
10580b578f35SChandan Rajendra 	int i;
10592058f83aSMichael Halcrow 
106086b38c27SMatthew Wilcox 	BUG_ON(!folio_test_locked(folio));
106109cbfeafSKirill A. Shutemov 	BUG_ON(from > PAGE_SIZE);
106209cbfeafSKirill A. Shutemov 	BUG_ON(to > PAGE_SIZE);
10632058f83aSMichael Halcrow 	BUG_ON(from > to);
10642058f83aSMichael Halcrow 
106586b38c27SMatthew Wilcox 	head = folio_buffers(folio);
106686b38c27SMatthew Wilcox 	if (!head) {
106786b38c27SMatthew Wilcox 		create_empty_buffers(&folio->page, blocksize, 0);
106886b38c27SMatthew Wilcox 		head = folio_buffers(folio);
106986b38c27SMatthew Wilcox 	}
10702058f83aSMichael Halcrow 	bbits = ilog2(blocksize);
107186b38c27SMatthew Wilcox 	block = (sector_t)folio->index << (PAGE_SHIFT - bbits);
10722058f83aSMichael Halcrow 
10732058f83aSMichael Halcrow 	for (bh = head, block_start = 0; bh != head || !block_start;
10742058f83aSMichael Halcrow 	    block++, block_start = block_end, bh = bh->b_this_page) {
10752058f83aSMichael Halcrow 		block_end = block_start + blocksize;
10762058f83aSMichael Halcrow 		if (block_end <= from || block_start >= to) {
107786b38c27SMatthew Wilcox 			if (folio_test_uptodate(folio)) {
10782058f83aSMichael Halcrow 				set_buffer_uptodate(bh);
10792058f83aSMichael Halcrow 			}
10802058f83aSMichael Halcrow 			continue;
10812058f83aSMichael Halcrow 		}
10822058f83aSMichael Halcrow 		if (buffer_new(bh))
10832058f83aSMichael Halcrow 			clear_buffer_new(bh);
10842058f83aSMichael Halcrow 		if (!buffer_mapped(bh)) {
10852058f83aSMichael Halcrow 			WARN_ON(bh->b_size != blocksize);
10862058f83aSMichael Halcrow 			err = get_block(inode, block, bh, 1);
10872058f83aSMichael Halcrow 			if (err)
10882058f83aSMichael Halcrow 				break;
10892058f83aSMichael Halcrow 			if (buffer_new(bh)) {
109086b38c27SMatthew Wilcox 				if (folio_test_uptodate(folio)) {
10912058f83aSMichael Halcrow 					clear_buffer_new(bh);
10922058f83aSMichael Halcrow 					set_buffer_uptodate(bh);
10932058f83aSMichael Halcrow 					mark_buffer_dirty(bh);
10942058f83aSMichael Halcrow 					continue;
10952058f83aSMichael Halcrow 				}
10962058f83aSMichael Halcrow 				if (block_end > to || block_start < from)
109786b38c27SMatthew Wilcox 					folio_zero_segments(folio, to,
109886b38c27SMatthew Wilcox 							    block_end,
10992058f83aSMichael Halcrow 							    block_start, from);
11002058f83aSMichael Halcrow 				continue;
11012058f83aSMichael Halcrow 			}
11022058f83aSMichael Halcrow 		}
110386b38c27SMatthew Wilcox 		if (folio_test_uptodate(folio)) {
11042058f83aSMichael Halcrow 			set_buffer_uptodate(bh);
11052058f83aSMichael Halcrow 			continue;
11062058f83aSMichael Halcrow 		}
11072058f83aSMichael Halcrow 		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
11082058f83aSMichael Halcrow 		    !buffer_unwritten(bh) &&
11092058f83aSMichael Halcrow 		    (block_start < from || block_end > to)) {
11102d069c08Szhangyi (F) 			ext4_read_bh_lock(bh, 0, false);
11110b578f35SChandan Rajendra 			wait[nr_wait++] = bh;
11122058f83aSMichael Halcrow 		}
11132058f83aSMichael Halcrow 	}
11142058f83aSMichael Halcrow 	/*
11152058f83aSMichael Halcrow 	 * If we issued read requests, let them complete.
11162058f83aSMichael Halcrow 	 */
11170b578f35SChandan Rajendra 	for (i = 0; i < nr_wait; i++) {
11180b578f35SChandan Rajendra 		wait_on_buffer(wait[i]);
11190b578f35SChandan Rajendra 		if (!buffer_uptodate(wait[i]))
11202058f83aSMichael Halcrow 			err = -EIO;
11212058f83aSMichael Halcrow 	}
11227e0785fcSChandan Rajendra 	if (unlikely(err)) {
112386b38c27SMatthew Wilcox 		page_zero_new_buffers(&folio->page, from, to);
11244f74d15fSEric Biggers 	} else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
11250b578f35SChandan Rajendra 		for (i = 0; i < nr_wait; i++) {
11260b578f35SChandan Rajendra 			int err2;
11270b578f35SChandan Rajendra 
112886b38c27SMatthew Wilcox 			err2 = fscrypt_decrypt_pagecache_blocks(folio,
112986b38c27SMatthew Wilcox 						blocksize, bh_offset(wait[i]));
11300b578f35SChandan Rajendra 			if (err2) {
11310b578f35SChandan Rajendra 				clear_buffer_uptodate(wait[i]);
11320b578f35SChandan Rajendra 				err = err2;
11330b578f35SChandan Rajendra 			}
11340b578f35SChandan Rajendra 		}
11357e0785fcSChandan Rajendra 	}
11367e0785fcSChandan Rajendra 
11372058f83aSMichael Halcrow 	return err;
11382058f83aSMichael Halcrow }
11392058f83aSMichael Halcrow #endif
11402058f83aSMichael Halcrow 
11419462f770SJan Kara /*
11429462f770SJan Kara  * To preserve ordering, it is essential that the hole instantiation and
11439462f770SJan Kara  * the data write be encapsulated in a single transaction.  We cannot
11449462f770SJan Kara  * close off a transaction and start a new one between the ext4_get_block()
11459462f770SJan Kara  * and the ext4_write_end().  So doing the jbd2_journal_start at the start of
11469462f770SJan Kara  * ext4_write_begin() is the right place.
11479462f770SJan Kara  */
1148bfc1af65SNick Piggin static int ext4_write_begin(struct file *file, struct address_space *mapping,
11499d6b0cd7SMatthew Wilcox (Oracle) 			    loff_t pos, unsigned len,
1150bfc1af65SNick Piggin 			    struct page **pagep, void **fsdata)
1151ac27a0ecSDave Kleikamp {
1152bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
11531938a150SAneesh Kumar K.V 	int ret, needed_blocks;
1154ac27a0ecSDave Kleikamp 	handle_t *handle;
1155ac27a0ecSDave Kleikamp 	int retries = 0;
11564d934a5eSMatthew Wilcox 	struct folio *folio;
1157bfc1af65SNick Piggin 	pgoff_t index;
1158bfc1af65SNick Piggin 	unsigned from, to;
1159bfc1af65SNick Piggin 
11600db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
11610db1ff22STheodore Ts'o 		return -EIO;
11620db1ff22STheodore Ts'o 
11639d6b0cd7SMatthew Wilcox (Oracle) 	trace_ext4_write_begin(inode, pos, len);
11641938a150SAneesh Kumar K.V 	/*
11651938a150SAneesh Kumar K.V 	 * Reserve one block more for addition to orphan list in case
11661938a150SAneesh Kumar K.V 	 * we allocate blocks but write fails for some reason
11671938a150SAneesh Kumar K.V 	 */
11681938a150SAneesh Kumar K.V 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
116909cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
117009cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1171bfc1af65SNick Piggin 	to = from + len;
1172ac27a0ecSDave Kleikamp 
1173f19d5870STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1174f19d5870STao Ma 		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1175832ee62dSMatthew Wilcox (Oracle) 						    pagep);
1176f19d5870STao Ma 		if (ret < 0)
117747564bfbSTheodore Ts'o 			return ret;
117847564bfbSTheodore Ts'o 		if (ret == 1)
117947564bfbSTheodore Ts'o 			return 0;
1180f19d5870STao Ma 	}
1181f19d5870STao Ma 
118247564bfbSTheodore Ts'o 	/*
11834d934a5eSMatthew Wilcox 	 * __filemap_get_folio() can take a long time if the
11844d934a5eSMatthew Wilcox 	 * system is thrashing due to memory pressure, or if the folio
118547564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
118647564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
11874d934a5eSMatthew Wilcox 	 * the folio (if needed) without using GFP_NOFS.
118847564bfbSTheodore Ts'o 	 */
118947564bfbSTheodore Ts'o retry_grab:
11904d934a5eSMatthew Wilcox 	folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
11914d934a5eSMatthew Wilcox 					mapping_gfp_mask(mapping));
11924d934a5eSMatthew Wilcox 	if (!folio)
119347564bfbSTheodore Ts'o 		return -ENOMEM;
1194d1052d23SJinke Han 	/*
1195d1052d23SJinke Han 	 * The same as page allocation, we prealloc buffer heads before
1196d1052d23SJinke Han 	 * starting the handle.
1197d1052d23SJinke Han 	 */
11984d934a5eSMatthew Wilcox 	if (!folio_buffers(folio))
11994d934a5eSMatthew Wilcox 		create_empty_buffers(&folio->page, inode->i_sb->s_blocksize, 0);
1200d1052d23SJinke Han 
12014d934a5eSMatthew Wilcox 	folio_unlock(folio);
120247564bfbSTheodore Ts'o 
120347564bfbSTheodore Ts'o retry_journal:
12049924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
12057479d2b9SAndrew Morton 	if (IS_ERR(handle)) {
12064d934a5eSMatthew Wilcox 		folio_put(folio);
120747564bfbSTheodore Ts'o 		return PTR_ERR(handle);
1208cf108bcaSJan Kara 	}
1209f19d5870STao Ma 
12104d934a5eSMatthew Wilcox 	folio_lock(folio);
12114d934a5eSMatthew Wilcox 	if (folio->mapping != mapping) {
12124d934a5eSMatthew Wilcox 		/* The folio got truncated from under us */
12134d934a5eSMatthew Wilcox 		folio_unlock(folio);
12144d934a5eSMatthew Wilcox 		folio_put(folio);
1215cf108bcaSJan Kara 		ext4_journal_stop(handle);
121647564bfbSTheodore Ts'o 		goto retry_grab;
1217cf108bcaSJan Kara 	}
12184d934a5eSMatthew Wilcox 	/* In case writeback began while the folio was unlocked */
12194d934a5eSMatthew Wilcox 	folio_wait_stable(folio);
1220cf108bcaSJan Kara 
1221643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
12222058f83aSMichael Halcrow 	if (ext4_should_dioread_nolock(inode))
122386b38c27SMatthew Wilcox 		ret = ext4_block_write_begin(folio, pos, len,
1224705965bdSJan Kara 					     ext4_get_block_unwritten);
12252058f83aSMichael Halcrow 	else
122686b38c27SMatthew Wilcox 		ret = ext4_block_write_begin(folio, pos, len, ext4_get_block);
12272058f83aSMichael Halcrow #else
1228744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
12294d934a5eSMatthew Wilcox 		ret = __block_write_begin(&folio->page, pos, len,
1230705965bdSJan Kara 					  ext4_get_block_unwritten);
1231744692dcSJiaying Zhang 	else
12324d934a5eSMatthew Wilcox 		ret = __block_write_begin(&folio->page, pos, len, ext4_get_block);
12332058f83aSMichael Halcrow #endif
1234bfc1af65SNick Piggin 	if (!ret && ext4_should_journal_data(inode)) {
1235188c299eSJan Kara 		ret = ext4_walk_page_buffers(handle, inode,
12364d934a5eSMatthew Wilcox 					     folio_buffers(folio), from, to,
12374d934a5eSMatthew Wilcox 					     NULL, do_journal_get_write_access);
1238b46be050SAndrey Savochkin 	}
1239bfc1af65SNick Piggin 
1240bfc1af65SNick Piggin 	if (ret) {
1241c93d8f88SEric Biggers 		bool extended = (pos + len > inode->i_size) &&
1242c93d8f88SEric Biggers 				!ext4_verity_in_progress(inode);
1243c93d8f88SEric Biggers 
12444d934a5eSMatthew Wilcox 		folio_unlock(folio);
1245ae4d5372SAneesh Kumar K.V 		/*
12466e1db88dSChristoph Hellwig 		 * __block_write_begin may have instantiated a few blocks
1247ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
1248f340b3d9Shongnanli 		 * i_size_read because we hold i_rwsem.
12491938a150SAneesh Kumar K.V 		 *
12501938a150SAneesh Kumar K.V 		 * Add inode to orphan list in case we crash before
12511938a150SAneesh Kumar K.V 		 * truncate finishes
1252ae4d5372SAneesh Kumar K.V 		 */
1253c93d8f88SEric Biggers 		if (extended && ext4_can_truncate(inode))
12541938a150SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
12551938a150SAneesh Kumar K.V 
12561938a150SAneesh Kumar K.V 		ext4_journal_stop(handle);
1257c93d8f88SEric Biggers 		if (extended) {
1258b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
12591938a150SAneesh Kumar K.V 			/*
1260ffacfa7aSJan Kara 			 * If truncate failed early the inode might
12611938a150SAneesh Kumar K.V 			 * still be on the orphan list; we need to
12621938a150SAneesh Kumar K.V 			 * make sure the inode is removed from the
12631938a150SAneesh Kumar K.V 			 * orphan list in that case.
12641938a150SAneesh Kumar K.V 			 */
12651938a150SAneesh Kumar K.V 			if (inode->i_nlink)
12661938a150SAneesh Kumar K.V 				ext4_orphan_del(NULL, inode);
12671938a150SAneesh Kumar K.V 		}
1268bfc1af65SNick Piggin 
126947564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
127047564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
127147564bfbSTheodore Ts'o 			goto retry_journal;
12724d934a5eSMatthew Wilcox 		folio_put(folio);
127347564bfbSTheodore Ts'o 		return ret;
127447564bfbSTheodore Ts'o 	}
12754d934a5eSMatthew Wilcox 	*pagep = &folio->page;
1276ac27a0ecSDave Kleikamp 	return ret;
1277ac27a0ecSDave Kleikamp }
1278ac27a0ecSDave Kleikamp 
1279bfc1af65SNick Piggin /* For write_end() in data=journal mode */
1280188c299eSJan Kara static int write_end_fn(handle_t *handle, struct inode *inode,
1281188c299eSJan Kara 			struct buffer_head *bh)
1282ac27a0ecSDave Kleikamp {
128313fca323STheodore Ts'o 	int ret;
1284ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1285ac27a0ecSDave Kleikamp 		return 0;
1286ac27a0ecSDave Kleikamp 	set_buffer_uptodate(bh);
1287d84c9ebdSJan Kara 	ret = ext4_dirty_journalled_data(handle, bh);
128813fca323STheodore Ts'o 	clear_buffer_meta(bh);
128913fca323STheodore Ts'o 	clear_buffer_prio(bh);
129013fca323STheodore Ts'o 	return ret;
1291ac27a0ecSDave Kleikamp }
1292ac27a0ecSDave Kleikamp 
1293eed4333fSZheng Liu /*
1294eed4333fSZheng Liu  * We need to pick up the new inode size which generic_commit_write gave us
1295eed4333fSZheng Liu  * `file' can be NULL - eg, when called from page_symlink().
1296eed4333fSZheng Liu  *
1297eed4333fSZheng Liu  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1298eed4333fSZheng Liu  * buffers are managed internally.
1299eed4333fSZheng Liu  */
1300eed4333fSZheng Liu static int ext4_write_end(struct file *file,
1301f8514083SAneesh Kumar K.V 			  struct address_space *mapping,
1302f8514083SAneesh Kumar K.V 			  loff_t pos, unsigned len, unsigned copied,
1303f8514083SAneesh Kumar K.V 			  struct page *page, void *fsdata)
1304f8514083SAneesh Kumar K.V {
130564fb3136SMatthew Wilcox 	struct folio *folio = page_folio(page);
1306f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
1307eed4333fSZheng Liu 	struct inode *inode = mapping->host;
13080572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1309eed4333fSZheng Liu 	int ret = 0, ret2;
1310eed4333fSZheng Liu 	int i_size_changed = 0;
1311c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1312eed4333fSZheng Liu 
1313eed4333fSZheng Liu 	trace_ext4_write_end(inode, pos, len, copied);
13146984aef5SZhang Yi 
13155c099c4fSYe Bin 	if (ext4_has_inline_data(inode) &&
13165c099c4fSYe Bin 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
13176984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
13186984aef5SZhang Yi 
13196984aef5SZhang Yi 	copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1320f8514083SAneesh Kumar K.V 	/*
132164fb3136SMatthew Wilcox 	 * it's important to update i_size while still holding folio lock:
1322f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
1323c93d8f88SEric Biggers 	 *
1324c93d8f88SEric Biggers 	 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1325c93d8f88SEric Biggers 	 * blocks are being written past EOF, so skip the i_size update.
1326f8514083SAneesh Kumar K.V 	 */
1327c93d8f88SEric Biggers 	if (!verity)
13284631dbf6SDmitry Monakhov 		i_size_changed = ext4_update_inode_size(inode, pos + copied);
132964fb3136SMatthew Wilcox 	folio_unlock(folio);
133064fb3136SMatthew Wilcox 	folio_put(folio);
1331f8514083SAneesh Kumar K.V 
1332c93d8f88SEric Biggers 	if (old_size < pos && !verity)
13330572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
1334f8514083SAneesh Kumar K.V 	/*
133564fb3136SMatthew Wilcox 	 * Don't mark the inode dirty under folio lock. First, it unnecessarily
133664fb3136SMatthew Wilcox 	 * makes the holding time of folio lock longer. Second, it forces lock
133764fb3136SMatthew Wilcox 	 * ordering of folio lock and transaction start for journaling
1338f8514083SAneesh Kumar K.V 	 * filesystems.
1339f8514083SAneesh Kumar K.V 	 */
13406984aef5SZhang Yi 	if (i_size_changed)
13414209ae12SHarshad Shirwadkar 		ret = ext4_mark_inode_dirty(handle, inode);
1342f8514083SAneesh Kumar K.V 
1343c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1344f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1345f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1346f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1347f8514083SAneesh Kumar K.V 		 */
1348f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
134955ce2f64SZhang Yi 
1350617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1351ac27a0ecSDave Kleikamp 	if (!ret)
1352ac27a0ecSDave Kleikamp 		ret = ret2;
1353bfc1af65SNick Piggin 
1354c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1355b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1356f8514083SAneesh Kumar K.V 		/*
1357ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1358f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1359f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1360f8514083SAneesh Kumar K.V 		 */
1361f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1362f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1363f8514083SAneesh Kumar K.V 	}
1364f8514083SAneesh Kumar K.V 
1365bfc1af65SNick Piggin 	return ret ? ret : copied;
1366ac27a0ecSDave Kleikamp }
1367ac27a0ecSDave Kleikamp 
1368b90197b6STheodore Ts'o /*
1369b90197b6STheodore Ts'o  * This is a private version of page_zero_new_buffers() which doesn't
1370b90197b6STheodore Ts'o  * set the buffer to be dirty, since in data=journalled mode we need
1371d84c9ebdSJan Kara  * to call ext4_dirty_journalled_data() instead.
1372b90197b6STheodore Ts'o  */
13733b136499SJan Kara static void ext4_journalled_zero_new_buffers(handle_t *handle,
1374188c299eSJan Kara 					    struct inode *inode,
137586324a21SMatthew Wilcox 					    struct folio *folio,
13763b136499SJan Kara 					    unsigned from, unsigned to)
1377b90197b6STheodore Ts'o {
1378b90197b6STheodore Ts'o 	unsigned int block_start = 0, block_end;
1379b90197b6STheodore Ts'o 	struct buffer_head *head, *bh;
1380b90197b6STheodore Ts'o 
138186324a21SMatthew Wilcox 	bh = head = folio_buffers(folio);
1382b90197b6STheodore Ts'o 	do {
1383b90197b6STheodore Ts'o 		block_end = block_start + bh->b_size;
1384b90197b6STheodore Ts'o 		if (buffer_new(bh)) {
1385b90197b6STheodore Ts'o 			if (block_end > from && block_start < to) {
138686324a21SMatthew Wilcox 				if (!folio_test_uptodate(folio)) {
1387b90197b6STheodore Ts'o 					unsigned start, size;
1388b90197b6STheodore Ts'o 
1389b90197b6STheodore Ts'o 					start = max(from, block_start);
1390b90197b6STheodore Ts'o 					size = min(to, block_end) - start;
1391b90197b6STheodore Ts'o 
139286324a21SMatthew Wilcox 					folio_zero_range(folio, start, size);
1393188c299eSJan Kara 					write_end_fn(handle, inode, bh);
1394b90197b6STheodore Ts'o 				}
1395b90197b6STheodore Ts'o 				clear_buffer_new(bh);
1396b90197b6STheodore Ts'o 			}
1397b90197b6STheodore Ts'o 		}
1398b90197b6STheodore Ts'o 		block_start = block_end;
1399b90197b6STheodore Ts'o 		bh = bh->b_this_page;
1400b90197b6STheodore Ts'o 	} while (bh != head);
1401b90197b6STheodore Ts'o }
1402b90197b6STheodore Ts'o 
1403bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
1404bfc1af65SNick Piggin 				     struct address_space *mapping,
1405bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
1406bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
1407ac27a0ecSDave Kleikamp {
1408feb22b77SMatthew Wilcox 	struct folio *folio = page_folio(page);
1409617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1410bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
14110572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1412ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1413ac27a0ecSDave Kleikamp 	int partial = 0;
1414bfc1af65SNick Piggin 	unsigned from, to;
14154631dbf6SDmitry Monakhov 	int size_changed = 0;
1416c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1417ac27a0ecSDave Kleikamp 
14189bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
141909cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1420bfc1af65SNick Piggin 	to = from + len;
1421bfc1af65SNick Piggin 
1422441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1423441c8508SCurt Wohlgemuth 
14246984aef5SZhang Yi 	if (ext4_has_inline_data(inode))
14256984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
14266984aef5SZhang Yi 
1427feb22b77SMatthew Wilcox 	if (unlikely(copied < len) && !folio_test_uptodate(folio)) {
1428bfc1af65SNick Piggin 		copied = 0;
142986324a21SMatthew Wilcox 		ext4_journalled_zero_new_buffers(handle, inode, folio,
143086324a21SMatthew Wilcox 						 from, to);
14313b136499SJan Kara 	} else {
14323b136499SJan Kara 		if (unlikely(copied < len))
143386324a21SMatthew Wilcox 			ext4_journalled_zero_new_buffers(handle, inode, folio,
14343b136499SJan Kara 							 from + copied, to);
1435feb22b77SMatthew Wilcox 		ret = ext4_walk_page_buffers(handle, inode,
1436feb22b77SMatthew Wilcox 					     folio_buffers(folio),
1437188c299eSJan Kara 					     from, from + copied, &partial,
14383b136499SJan Kara 					     write_end_fn);
1439ac27a0ecSDave Kleikamp 		if (!partial)
1440feb22b77SMatthew Wilcox 			folio_mark_uptodate(folio);
14413fdcfb66STao Ma 	}
1442c93d8f88SEric Biggers 	if (!verity)
14434631dbf6SDmitry Monakhov 		size_changed = ext4_update_inode_size(inode, pos + copied);
144419f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
14452d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1446feb22b77SMatthew Wilcox 	folio_unlock(folio);
1447feb22b77SMatthew Wilcox 	folio_put(folio);
14484631dbf6SDmitry Monakhov 
1449c93d8f88SEric Biggers 	if (old_size < pos && !verity)
14500572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
14510572639fSXiaoguang Wang 
14526984aef5SZhang Yi 	if (size_changed) {
1453617ba13bSMingming Cao 		ret2 = ext4_mark_inode_dirty(handle, inode);
1454ac27a0ecSDave Kleikamp 		if (!ret)
1455ac27a0ecSDave Kleikamp 			ret = ret2;
1456ac27a0ecSDave Kleikamp 	}
1457bfc1af65SNick Piggin 
1458c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1459f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1460f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1461f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1462f8514083SAneesh Kumar K.V 		 */
1463f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1464f8514083SAneesh Kumar K.V 
1465617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1466ac27a0ecSDave Kleikamp 	if (!ret)
1467ac27a0ecSDave Kleikamp 		ret = ret2;
1468c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1469b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1470f8514083SAneesh Kumar K.V 		/*
1471ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1472f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1473f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1474f8514083SAneesh Kumar K.V 		 */
1475f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1476f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1477f8514083SAneesh Kumar K.V 	}
1478bfc1af65SNick Piggin 
1479bfc1af65SNick Piggin 	return ret ? ret : copied;
1480ac27a0ecSDave Kleikamp }
1481d2a17637SMingming Cao 
14829d0be502STheodore Ts'o /*
1483c27e43a1SEric Whitney  * Reserve space for a single cluster
14849d0be502STheodore Ts'o  */
1485c27e43a1SEric Whitney static int ext4_da_reserve_space(struct inode *inode)
1486d2a17637SMingming Cao {
1487d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
14880637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
14895dd4056dSChristoph Hellwig 	int ret;
1490d2a17637SMingming Cao 
149160e58e0fSMingming Cao 	/*
149272b8ab9dSEric Sandeen 	 * We will charge metadata quota at writeout time; this saves
149372b8ab9dSEric Sandeen 	 * us from metadata over-estimation, though we may go over by
149472b8ab9dSEric Sandeen 	 * a small amount in the end.  Here we just reserve for data.
149560e58e0fSMingming Cao 	 */
14967b415bf6SAditya Kali 	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
14975dd4056dSChristoph Hellwig 	if (ret)
14985dd4056dSChristoph Hellwig 		return ret;
149903179fe9STheodore Ts'o 
150003179fe9STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
150171d4f7d0STheodore Ts'o 	if (ext4_claim_free_clusters(sbi, 1, 0)) {
150203179fe9STheodore Ts'o 		spin_unlock(&ei->i_block_reservation_lock);
150303179fe9STheodore Ts'o 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1504d2a17637SMingming Cao 		return -ENOSPC;
1505d2a17637SMingming Cao 	}
15069d0be502STheodore Ts'o 	ei->i_reserved_data_blocks++;
1507c27e43a1SEric Whitney 	trace_ext4_da_reserve_space(inode);
15080637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
150939bc680aSDmitry Monakhov 
1510d2a17637SMingming Cao 	return 0;       /* success */
1511d2a17637SMingming Cao }
1512d2a17637SMingming Cao 
1513f456767dSEric Whitney void ext4_da_release_space(struct inode *inode, int to_free)
1514d2a17637SMingming Cao {
1515d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
15160637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1517d2a17637SMingming Cao 
1518cd213226SMingming Cao 	if (!to_free)
1519cd213226SMingming Cao 		return;		/* Nothing to release, exit */
1520cd213226SMingming Cao 
1521d2a17637SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1522cd213226SMingming Cao 
15235a58ec87SLi Zefan 	trace_ext4_da_release_space(inode, to_free);
15240637c6f4STheodore Ts'o 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1525cd213226SMingming Cao 		/*
15260637c6f4STheodore Ts'o 		 * if there aren't enough reserved blocks, then the
15270637c6f4STheodore Ts'o 		 * counter is messed up somewhere.  Since this
15280637c6f4STheodore Ts'o 		 * function is called from invalidate page, it's
15290637c6f4STheodore Ts'o 		 * harmless to return without any action.
1530cd213226SMingming Cao 		 */
15318de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "ext4_da_release_space: "
15320637c6f4STheodore Ts'o 			 "ino %lu, to_free %d with only %d reserved "
15331084f252STheodore Ts'o 			 "data blocks", inode->i_ino, to_free,
15340637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
15350637c6f4STheodore Ts'o 		WARN_ON(1);
15360637c6f4STheodore Ts'o 		to_free = ei->i_reserved_data_blocks;
15370637c6f4STheodore Ts'o 	}
15380637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= to_free;
15390637c6f4STheodore Ts'o 
154072b8ab9dSEric Sandeen 	/* update fs dirty data blocks counter */
154157042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1542d2a17637SMingming Cao 
1543d2a17637SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
154460e58e0fSMingming Cao 
15457b415bf6SAditya Kali 	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1546d2a17637SMingming Cao }
1547d2a17637SMingming Cao 
1548ac27a0ecSDave Kleikamp /*
154964769240SAlex Tomas  * Delayed allocation stuff
155064769240SAlex Tomas  */
155164769240SAlex Tomas 
15524e7ea81dSJan Kara struct mpage_da_data {
155315648d59SJan Kara 	/* These are input fields for ext4_do_writepages() */
15544e7ea81dSJan Kara 	struct inode *inode;
15554e7ea81dSJan Kara 	struct writeback_control *wbc;
155615648d59SJan Kara 	unsigned int can_map:1;	/* Can writepages call map blocks? */
15576b523df4SJan Kara 
155815648d59SJan Kara 	/* These are internal state of ext4_do_writepages() */
15594e7ea81dSJan Kara 	pgoff_t first_page;	/* The first page to write */
15604e7ea81dSJan Kara 	pgoff_t next_page;	/* Current page to examine */
15614e7ea81dSJan Kara 	pgoff_t last_page;	/* Last page to examine */
156264769240SAlex Tomas 	/*
15634e7ea81dSJan Kara 	 * Extent to map - this can be after first_page because that can be
15644e7ea81dSJan Kara 	 * fully mapped. We somewhat abuse m_flags to store whether the extent
15654e7ea81dSJan Kara 	 * is delalloc or unwritten.
156664769240SAlex Tomas 	 */
15674e7ea81dSJan Kara 	struct ext4_map_blocks map;
15684e7ea81dSJan Kara 	struct ext4_io_submit io_submit;	/* IO submission data */
1569dddbd6acSJan Kara 	unsigned int do_map:1;
15706b8ed620SJan Kara 	unsigned int scanned_until_end:1;
1571*1f1a55f0SJan Kara 	unsigned int journalled_more_data:1;
15724e7ea81dSJan Kara };
157364769240SAlex Tomas 
15744e7ea81dSJan Kara static void mpage_release_unused_pages(struct mpage_da_data *mpd,
15754e7ea81dSJan Kara 				       bool invalidate)
1576c4a0c46eSAneesh Kumar K.V {
1577fb5a5be0SMatthew Wilcox (Oracle) 	unsigned nr, i;
1578c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
1579fb5a5be0SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
1580c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1581c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
15824e7ea81dSJan Kara 
15834e7ea81dSJan Kara 	/* This is necessary when next_page == 0. */
15844e7ea81dSJan Kara 	if (mpd->first_page >= mpd->next_page)
15854e7ea81dSJan Kara 		return;
1586c4a0c46eSAneesh Kumar K.V 
15876b8ed620SJan Kara 	mpd->scanned_until_end = 0;
1588c7f5938aSCurt Wohlgemuth 	index = mpd->first_page;
1589c7f5938aSCurt Wohlgemuth 	end   = mpd->next_page - 1;
15904e7ea81dSJan Kara 	if (invalidate) {
15914e7ea81dSJan Kara 		ext4_lblk_t start, last;
159209cbfeafSKirill A. Shutemov 		start = index << (PAGE_SHIFT - inode->i_blkbits);
159309cbfeafSKirill A. Shutemov 		last = end << (PAGE_SHIFT - inode->i_blkbits);
15947f0d8e1dSEric Whitney 
15957f0d8e1dSEric Whitney 		/*
15967f0d8e1dSEric Whitney 		 * avoid racing with extent status tree scans made by
15977f0d8e1dSEric Whitney 		 * ext4_insert_delayed_block()
15987f0d8e1dSEric Whitney 		 */
15997f0d8e1dSEric Whitney 		down_write(&EXT4_I(inode)->i_data_sem);
160051865fdaSZheng Liu 		ext4_es_remove_extent(inode, start, last - start + 1);
16017f0d8e1dSEric Whitney 		up_write(&EXT4_I(inode)->i_data_sem);
16024e7ea81dSJan Kara 	}
160351865fdaSZheng Liu 
1604fb5a5be0SMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
1605c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
1606fb5a5be0SMatthew Wilcox (Oracle) 		nr = filemap_get_folios(mapping, &index, end, &fbatch);
1607fb5a5be0SMatthew Wilcox (Oracle) 		if (nr == 0)
1608c4a0c46eSAneesh Kumar K.V 			break;
1609fb5a5be0SMatthew Wilcox (Oracle) 		for (i = 0; i < nr; i++) {
1610fb5a5be0SMatthew Wilcox (Oracle) 			struct folio *folio = fbatch.folios[i];
16112b85a617SJan Kara 
1612fb5a5be0SMatthew Wilcox (Oracle) 			if (folio->index < mpd->first_page)
1613fb5a5be0SMatthew Wilcox (Oracle) 				continue;
1614fb5a5be0SMatthew Wilcox (Oracle) 			if (folio->index + folio_nr_pages(folio) - 1 > end)
1615fb5a5be0SMatthew Wilcox (Oracle) 				continue;
16167ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(!folio_test_locked(folio));
16177ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(folio_test_writeback(folio));
16184e7ea81dSJan Kara 			if (invalidate) {
16197ba13abbSMatthew Wilcox (Oracle) 				if (folio_mapped(folio))
16207ba13abbSMatthew Wilcox (Oracle) 					folio_clear_dirty_for_io(folio);
16217ba13abbSMatthew Wilcox (Oracle) 				block_invalidate_folio(folio, 0,
16227ba13abbSMatthew Wilcox (Oracle) 						folio_size(folio));
16237ba13abbSMatthew Wilcox (Oracle) 				folio_clear_uptodate(folio);
16244e7ea81dSJan Kara 			}
16257ba13abbSMatthew Wilcox (Oracle) 			folio_unlock(folio);
1626c4a0c46eSAneesh Kumar K.V 		}
1627fb5a5be0SMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
1628c4a0c46eSAneesh Kumar K.V 	}
1629c4a0c46eSAneesh Kumar K.V }
1630c4a0c46eSAneesh Kumar K.V 
1631df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
1632df22291fSAneesh Kumar K.V {
1633df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
163492b97816STheodore Ts'o 	struct super_block *sb = inode->i_sb;
1635f78ee70dSLukas Czerner 	struct ext4_inode_info *ei = EXT4_I(inode);
163692b97816STheodore Ts'o 
163792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
16385dee5437STheodore Ts'o 	       EXT4_C2B(EXT4_SB(inode->i_sb),
1639f78ee70dSLukas Czerner 			ext4_count_free_clusters(sb)));
164092b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
164192b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1642f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
164357042651STheodore Ts'o 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
164492b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1645f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
16467b415bf6SAditya Kali 		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
164792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Block reservation details");
164892b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1649f78ee70dSLukas Czerner 		 ei->i_reserved_data_blocks);
1650df22291fSAneesh Kumar K.V 	return;
1651df22291fSAneesh Kumar K.V }
1652df22291fSAneesh Kumar K.V 
165364769240SAlex Tomas /*
16540b02f4c0SEric Whitney  * ext4_insert_delayed_block - adds a delayed block to the extents status
16550b02f4c0SEric Whitney  *                             tree, incrementing the reserved cluster/block
16560b02f4c0SEric Whitney  *                             count or making a pending reservation
16570b02f4c0SEric Whitney  *                             where needed
16580b02f4c0SEric Whitney  *
16590b02f4c0SEric Whitney  * @inode - file containing the newly added block
16600b02f4c0SEric Whitney  * @lblk - logical block to be added
16610b02f4c0SEric Whitney  *
16620b02f4c0SEric Whitney  * Returns 0 on success, negative error code on failure.
16630b02f4c0SEric Whitney  */
16640b02f4c0SEric Whitney static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
16650b02f4c0SEric Whitney {
16660b02f4c0SEric Whitney 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
16670b02f4c0SEric Whitney 	int ret;
16680b02f4c0SEric Whitney 	bool allocated = false;
16696fed8395SJeffle Xu 	bool reserved = false;
16700b02f4c0SEric Whitney 
16710b02f4c0SEric Whitney 	/*
16720b02f4c0SEric Whitney 	 * If the cluster containing lblk is shared with a delayed,
16730b02f4c0SEric Whitney 	 * written, or unwritten extent in a bigalloc file system, it's
16740b02f4c0SEric Whitney 	 * already been accounted for and does not need to be reserved.
16750b02f4c0SEric Whitney 	 * A pending reservation must be made for the cluster if it's
16760b02f4c0SEric Whitney 	 * shared with a written or unwritten extent and doesn't already
16770b02f4c0SEric Whitney 	 * have one.  Written and unwritten extents can be purged from the
16780b02f4c0SEric Whitney 	 * extents status tree if the system is under memory pressure, so
16790b02f4c0SEric Whitney 	 * it's necessary to examine the extent tree if a search of the
16800b02f4c0SEric Whitney 	 * extents status tree doesn't get a match.
16810b02f4c0SEric Whitney 	 */
16820b02f4c0SEric Whitney 	if (sbi->s_cluster_ratio == 1) {
16830b02f4c0SEric Whitney 		ret = ext4_da_reserve_space(inode);
16840b02f4c0SEric Whitney 		if (ret != 0)   /* ENOSPC */
16850b02f4c0SEric Whitney 			goto errout;
16866fed8395SJeffle Xu 		reserved = true;
16870b02f4c0SEric Whitney 	} else {   /* bigalloc */
16880b02f4c0SEric Whitney 		if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
16890b02f4c0SEric Whitney 			if (!ext4_es_scan_clu(inode,
16900b02f4c0SEric Whitney 					      &ext4_es_is_mapped, lblk)) {
16910b02f4c0SEric Whitney 				ret = ext4_clu_mapped(inode,
16920b02f4c0SEric Whitney 						      EXT4_B2C(sbi, lblk));
16930b02f4c0SEric Whitney 				if (ret < 0)
16940b02f4c0SEric Whitney 					goto errout;
16950b02f4c0SEric Whitney 				if (ret == 0) {
16960b02f4c0SEric Whitney 					ret = ext4_da_reserve_space(inode);
16970b02f4c0SEric Whitney 					if (ret != 0)   /* ENOSPC */
16980b02f4c0SEric Whitney 						goto errout;
16996fed8395SJeffle Xu 					reserved = true;
17000b02f4c0SEric Whitney 				} else {
17010b02f4c0SEric Whitney 					allocated = true;
17020b02f4c0SEric Whitney 				}
17030b02f4c0SEric Whitney 			} else {
17040b02f4c0SEric Whitney 				allocated = true;
17050b02f4c0SEric Whitney 			}
17060b02f4c0SEric Whitney 		}
17070b02f4c0SEric Whitney 	}
17080b02f4c0SEric Whitney 
17090b02f4c0SEric Whitney 	ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
17106fed8395SJeffle Xu 	if (ret && reserved)
17116fed8395SJeffle Xu 		ext4_da_release_space(inode, 1);
17120b02f4c0SEric Whitney 
17130b02f4c0SEric Whitney errout:
17140b02f4c0SEric Whitney 	return ret;
17150b02f4c0SEric Whitney }
17160b02f4c0SEric Whitney 
17170b02f4c0SEric Whitney /*
17185356f261SAditya Kali  * This function is grabs code from the very beginning of
17195356f261SAditya Kali  * ext4_map_blocks, but assumes that the caller is from delayed write
17205356f261SAditya Kali  * time. This function looks up the requested blocks and sets the
17215356f261SAditya Kali  * buffer delay bit under the protection of i_data_sem.
17225356f261SAditya Kali  */
17235356f261SAditya Kali static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
17245356f261SAditya Kali 			      struct ext4_map_blocks *map,
17255356f261SAditya Kali 			      struct buffer_head *bh)
17265356f261SAditya Kali {
1727d100eef2SZheng Liu 	struct extent_status es;
17285356f261SAditya Kali 	int retval;
17295356f261SAditya Kali 	sector_t invalid_block = ~((sector_t) 0xffff);
1730921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1731921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
1732921f266bSDmitry Monakhov 
1733921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
1734921f266bSDmitry Monakhov #endif
17355356f261SAditya Kali 
17365356f261SAditya Kali 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
17375356f261SAditya Kali 		invalid_block = ~0;
17385356f261SAditya Kali 
17395356f261SAditya Kali 	map->m_flags = 0;
174070aa1554SRitesh Harjani 	ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
17415356f261SAditya Kali 		  (unsigned long) map->m_lblk);
1742d100eef2SZheng Liu 
1743d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
1744bb5835edSTheodore Ts'o 	if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1745d100eef2SZheng Liu 		if (ext4_es_is_hole(&es)) {
1746d100eef2SZheng Liu 			retval = 0;
1747c8b459f4SLukas Czerner 			down_read(&EXT4_I(inode)->i_data_sem);
1748d100eef2SZheng Liu 			goto add_delayed;
1749d100eef2SZheng Liu 		}
1750d100eef2SZheng Liu 
1751d100eef2SZheng Liu 		/*
17523eda41dfSEric Whitney 		 * Delayed extent could be allocated by fallocate.
17533eda41dfSEric Whitney 		 * So we need to check it.
1754d100eef2SZheng Liu 		 */
17553eda41dfSEric Whitney 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
17563eda41dfSEric Whitney 			map_bh(bh, inode->i_sb, invalid_block);
17573eda41dfSEric Whitney 			set_buffer_new(bh);
17583eda41dfSEric Whitney 			set_buffer_delay(bh);
1759d100eef2SZheng Liu 			return 0;
1760d100eef2SZheng Liu 		}
1761d100eef2SZheng Liu 
1762d100eef2SZheng Liu 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1763d100eef2SZheng Liu 		retval = es.es_len - (iblock - es.es_lblk);
1764d100eef2SZheng Liu 		if (retval > map->m_len)
1765d100eef2SZheng Liu 			retval = map->m_len;
1766d100eef2SZheng Liu 		map->m_len = retval;
1767d100eef2SZheng Liu 		if (ext4_es_is_written(&es))
1768d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_MAPPED;
1769d100eef2SZheng Liu 		else if (ext4_es_is_unwritten(&es))
1770d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1771d100eef2SZheng Liu 		else
17721e83bc81SArnd Bergmann 			BUG();
1773d100eef2SZheng Liu 
1774921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1775921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1776921f266bSDmitry Monakhov #endif
1777d100eef2SZheng Liu 		return retval;
1778d100eef2SZheng Liu 	}
1779d100eef2SZheng Liu 
17805356f261SAditya Kali 	/*
17815356f261SAditya Kali 	 * Try to see if we can get the block without requesting a new
17825356f261SAditya Kali 	 * file system block.
17835356f261SAditya Kali 	 */
1784c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
1785cbd7584eSJan Kara 	if (ext4_has_inline_data(inode))
17869c3569b5STao Ma 		retval = 0;
1787cbd7584eSJan Kara 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
17882f8e0a7cSZheng Liu 		retval = ext4_ext_map_blocks(NULL, inode, map, 0);
17895356f261SAditya Kali 	else
17902f8e0a7cSZheng Liu 		retval = ext4_ind_map_blocks(NULL, inode, map, 0);
17915356f261SAditya Kali 
1792d100eef2SZheng Liu add_delayed:
17935356f261SAditya Kali 	if (retval == 0) {
1794f7fec032SZheng Liu 		int ret;
1795ad431025SEric Whitney 
17965356f261SAditya Kali 		/*
17975356f261SAditya Kali 		 * XXX: __block_prepare_write() unmaps passed block,
17985356f261SAditya Kali 		 * is it OK?
17995356f261SAditya Kali 		 */
18005356f261SAditya Kali 
18010b02f4c0SEric Whitney 		ret = ext4_insert_delayed_block(inode, map->m_lblk);
18020b02f4c0SEric Whitney 		if (ret != 0) {
1803f7fec032SZheng Liu 			retval = ret;
180451865fdaSZheng Liu 			goto out_unlock;
1805f7fec032SZheng Liu 		}
180651865fdaSZheng Liu 
18075356f261SAditya Kali 		map_bh(bh, inode->i_sb, invalid_block);
18085356f261SAditya Kali 		set_buffer_new(bh);
18095356f261SAditya Kali 		set_buffer_delay(bh);
1810f7fec032SZheng Liu 	} else if (retval > 0) {
1811f7fec032SZheng Liu 		int ret;
18123be78c73STheodore Ts'o 		unsigned int status;
1813f7fec032SZheng Liu 
181444fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
181544fb851dSZheng Liu 			ext4_warning(inode->i_sb,
181644fb851dSZheng Liu 				     "ES len assertion failed for inode "
181744fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
181844fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
181944fb851dSZheng Liu 			WARN_ON(1);
1820921f266bSDmitry Monakhov 		}
1821921f266bSDmitry Monakhov 
1822f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1823f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1824f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1825f7fec032SZheng Liu 					    map->m_pblk, status);
1826f7fec032SZheng Liu 		if (ret != 0)
1827f7fec032SZheng Liu 			retval = ret;
18285356f261SAditya Kali 	}
18295356f261SAditya Kali 
18305356f261SAditya Kali out_unlock:
18315356f261SAditya Kali 	up_read((&EXT4_I(inode)->i_data_sem));
18325356f261SAditya Kali 
18335356f261SAditya Kali 	return retval;
18345356f261SAditya Kali }
18355356f261SAditya Kali 
18365356f261SAditya Kali /*
1837d91bd2c1SSeunghun Lee  * This is a special get_block_t callback which is used by
1838b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
1839b920c755STheodore Ts'o  * reserve space for a single block.
184029fa89d0SAneesh Kumar K.V  *
184129fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
184229fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
184329fa89d0SAneesh Kumar K.V  *
184429fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
184529fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
184629fa89d0SAneesh Kumar K.V  * initialized properly.
184764769240SAlex Tomas  */
18489c3569b5STao Ma int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
18492ed88685STheodore Ts'o 			   struct buffer_head *bh, int create)
185064769240SAlex Tomas {
18512ed88685STheodore Ts'o 	struct ext4_map_blocks map;
185264769240SAlex Tomas 	int ret = 0;
185364769240SAlex Tomas 
185464769240SAlex Tomas 	BUG_ON(create == 0);
18552ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
18562ed88685STheodore Ts'o 
18572ed88685STheodore Ts'o 	map.m_lblk = iblock;
18582ed88685STheodore Ts'o 	map.m_len = 1;
185964769240SAlex Tomas 
186064769240SAlex Tomas 	/*
186164769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
186264769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
186364769240SAlex Tomas 	 * the same as allocated blocks.
186464769240SAlex Tomas 	 */
18655356f261SAditya Kali 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
18665356f261SAditya Kali 	if (ret <= 0)
18672ed88685STheodore Ts'o 		return ret;
186864769240SAlex Tomas 
18692ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
1870ed8ad838SJan Kara 	ext4_update_bh_state(bh, map.m_flags);
18712ed88685STheodore Ts'o 
18722ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
18732ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
18742ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
18752ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
18762ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
18772ed88685STheodore Ts'o 		 * for partial write.
18782ed88685STheodore Ts'o 		 */
18792ed88685STheodore Ts'o 		set_buffer_new(bh);
1880c8205636STheodore Ts'o 		set_buffer_mapped(bh);
18812ed88685STheodore Ts'o 	}
18822ed88685STheodore Ts'o 	return 0;
188364769240SAlex Tomas }
188461628a3fSMingming Cao 
188533483b3bSMatthew Wilcox static void mpage_folio_done(struct mpage_da_data *mpd, struct folio *folio)
1886eaf2ca10SJan Kara {
188733483b3bSMatthew Wilcox 	mpd->first_page += folio_nr_pages(folio);
188833483b3bSMatthew Wilcox 	folio_unlock(folio);
1889eaf2ca10SJan Kara }
1890eaf2ca10SJan Kara 
189181a0d3e1SMatthew Wilcox static int mpage_submit_folio(struct mpage_da_data *mpd, struct folio *folio)
18925f1132b2SJan Kara {
189381a0d3e1SMatthew Wilcox 	size_t len;
1894a056bdaaSJan Kara 	loff_t size;
18955f1132b2SJan Kara 	int err;
18965f1132b2SJan Kara 
189781a0d3e1SMatthew Wilcox 	BUG_ON(folio->index != mpd->first_page);
189881a0d3e1SMatthew Wilcox 	folio_clear_dirty_for_io(folio);
1899a056bdaaSJan Kara 	/*
1900a056bdaaSJan Kara 	 * We have to be very careful here!  Nothing protects writeback path
1901a056bdaaSJan Kara 	 * against i_size changes and the page can be writeably mapped into
1902a056bdaaSJan Kara 	 * page tables. So an application can be growing i_size and writing
190381a0d3e1SMatthew Wilcox 	 * data through mmap while writeback runs. folio_clear_dirty_for_io()
1904a056bdaaSJan Kara 	 * write-protects our page in page tables and the page cannot get
190581a0d3e1SMatthew Wilcox 	 * written to again until we release folio lock. So only after
190681a0d3e1SMatthew Wilcox 	 * folio_clear_dirty_for_io() we are safe to sample i_size for
1907e8d6062cSMatthew Wilcox 	 * ext4_bio_write_folio() to zero-out tail of the written page. We rely
1908e8d6062cSMatthew Wilcox 	 * on the barrier provided by folio_test_clear_dirty() in
190981a0d3e1SMatthew Wilcox 	 * folio_clear_dirty_for_io() to make sure i_size is really sampled only
1910a056bdaaSJan Kara 	 * after page tables are updated.
1911a056bdaaSJan Kara 	 */
1912a056bdaaSJan Kara 	size = i_size_read(mpd->inode);
191381a0d3e1SMatthew Wilcox 	len = folio_size(folio);
191481a0d3e1SMatthew Wilcox 	if (folio_pos(folio) + len > size &&
1915c93d8f88SEric Biggers 	    !ext4_verity_in_progress(mpd->inode))
191609cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
1917e8d6062cSMatthew Wilcox 	err = ext4_bio_write_folio(&mpd->io_submit, folio, len);
19185f1132b2SJan Kara 	if (!err)
19195f1132b2SJan Kara 		mpd->wbc->nr_to_write--;
19205f1132b2SJan Kara 
19215f1132b2SJan Kara 	return err;
19225f1132b2SJan Kara }
19235f1132b2SJan Kara 
19246db07461SRitesh Harjani #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
19254e7ea81dSJan Kara 
192661628a3fSMingming Cao /*
1927fffb2739SJan Kara  * mballoc gives us at most this number of blocks...
1928fffb2739SJan Kara  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1929fffb2739SJan Kara  * The rest of mballoc seems to handle chunks up to full group size.
193061628a3fSMingming Cao  */
1931fffb2739SJan Kara #define MAX_WRITEPAGES_EXTENT_LEN 2048
1932525f4ed8SMingming Cao 
1933525f4ed8SMingming Cao /*
19344e7ea81dSJan Kara  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
19354e7ea81dSJan Kara  *
19364e7ea81dSJan Kara  * @mpd - extent of blocks
19374e7ea81dSJan Kara  * @lblk - logical number of the block in the file
193809930042SJan Kara  * @bh - buffer head we want to add to the extent
19394e7ea81dSJan Kara  *
194009930042SJan Kara  * The function is used to collect contig. blocks in the same state. If the
194109930042SJan Kara  * buffer doesn't require mapping for writeback and we haven't started the
194209930042SJan Kara  * extent of buffers to map yet, the function returns 'true' immediately - the
194309930042SJan Kara  * caller can write the buffer right away. Otherwise the function returns true
194409930042SJan Kara  * if the block has been added to the extent, false if the block couldn't be
194509930042SJan Kara  * added.
19464e7ea81dSJan Kara  */
194709930042SJan Kara static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
194809930042SJan Kara 				   struct buffer_head *bh)
19494e7ea81dSJan Kara {
19504e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
19514e7ea81dSJan Kara 
195209930042SJan Kara 	/* Buffer that doesn't need mapping for writeback? */
195309930042SJan Kara 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
195409930042SJan Kara 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
195509930042SJan Kara 		/* So far no extent to map => we write the buffer right away */
195609930042SJan Kara 		if (map->m_len == 0)
195709930042SJan Kara 			return true;
195809930042SJan Kara 		return false;
195909930042SJan Kara 	}
19604e7ea81dSJan Kara 
19614e7ea81dSJan Kara 	/* First block in the extent? */
19624e7ea81dSJan Kara 	if (map->m_len == 0) {
1963dddbd6acSJan Kara 		/* We cannot map unless handle is started... */
1964dddbd6acSJan Kara 		if (!mpd->do_map)
1965dddbd6acSJan Kara 			return false;
19664e7ea81dSJan Kara 		map->m_lblk = lblk;
19674e7ea81dSJan Kara 		map->m_len = 1;
196809930042SJan Kara 		map->m_flags = bh->b_state & BH_FLAGS;
196909930042SJan Kara 		return true;
19704e7ea81dSJan Kara 	}
19714e7ea81dSJan Kara 
197209930042SJan Kara 	/* Don't go larger than mballoc is willing to allocate */
197309930042SJan Kara 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
197409930042SJan Kara 		return false;
197509930042SJan Kara 
19764e7ea81dSJan Kara 	/* Can we merge the block to our big extent? */
19774e7ea81dSJan Kara 	if (lblk == map->m_lblk + map->m_len &&
197809930042SJan Kara 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
19794e7ea81dSJan Kara 		map->m_len++;
198009930042SJan Kara 		return true;
19814e7ea81dSJan Kara 	}
198209930042SJan Kara 	return false;
19834e7ea81dSJan Kara }
19844e7ea81dSJan Kara 
19855f1132b2SJan Kara /*
19865f1132b2SJan Kara  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
19875f1132b2SJan Kara  *
19885f1132b2SJan Kara  * @mpd - extent of blocks for mapping
19895f1132b2SJan Kara  * @head - the first buffer in the page
19905f1132b2SJan Kara  * @bh - buffer we should start processing from
19915f1132b2SJan Kara  * @lblk - logical number of the block in the file corresponding to @bh
19925f1132b2SJan Kara  *
19935f1132b2SJan Kara  * Walk through page buffers from @bh upto @head (exclusive) and either submit
19945f1132b2SJan Kara  * the page for IO if all buffers in this page were mapped and there's no
19955f1132b2SJan Kara  * accumulated extent of buffers to map or add buffers in the page to the
19965f1132b2SJan Kara  * extent of buffers to map. The function returns 1 if the caller can continue
19975f1132b2SJan Kara  * by processing the next page, 0 if it should stop adding buffers to the
19985f1132b2SJan Kara  * extent to map because we cannot extend it anymore. It can also return value
19995f1132b2SJan Kara  * < 0 in case of error during IO submission.
20005f1132b2SJan Kara  */
20015f1132b2SJan Kara static int mpage_process_page_bufs(struct mpage_da_data *mpd,
20024e7ea81dSJan Kara 				   struct buffer_head *head,
20034e7ea81dSJan Kara 				   struct buffer_head *bh,
20044e7ea81dSJan Kara 				   ext4_lblk_t lblk)
20054e7ea81dSJan Kara {
20064e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
20075f1132b2SJan Kara 	int err;
200893407472SFabian Frederick 	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
20094e7ea81dSJan Kara 							>> inode->i_blkbits;
20104e7ea81dSJan Kara 
2011c93d8f88SEric Biggers 	if (ext4_verity_in_progress(inode))
2012c93d8f88SEric Biggers 		blocks = EXT_MAX_BLOCKS;
2013c93d8f88SEric Biggers 
20144e7ea81dSJan Kara 	do {
20154e7ea81dSJan Kara 		BUG_ON(buffer_locked(bh));
20164e7ea81dSJan Kara 
201709930042SJan Kara 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
20184e7ea81dSJan Kara 			/* Found extent to map? */
20194e7ea81dSJan Kara 			if (mpd->map.m_len)
20205f1132b2SJan Kara 				return 0;
2021dddbd6acSJan Kara 			/* Buffer needs mapping and handle is not started? */
2022dddbd6acSJan Kara 			if (!mpd->do_map)
2023dddbd6acSJan Kara 				return 0;
202409930042SJan Kara 			/* Everything mapped so far and we hit EOF */
20255f1132b2SJan Kara 			break;
20264e7ea81dSJan Kara 		}
20274e7ea81dSJan Kara 	} while (lblk++, (bh = bh->b_this_page) != head);
20285f1132b2SJan Kara 	/* So far everything mapped? Submit the page for IO. */
20295f1132b2SJan Kara 	if (mpd->map.m_len == 0) {
203081a0d3e1SMatthew Wilcox 		err = mpage_submit_folio(mpd, head->b_folio);
20315f1132b2SJan Kara 		if (err < 0)
20324e7ea81dSJan Kara 			return err;
203333483b3bSMatthew Wilcox 		mpage_folio_done(mpd, head->b_folio);
20344e7ea81dSJan Kara 	}
20356b8ed620SJan Kara 	if (lblk >= blocks) {
20366b8ed620SJan Kara 		mpd->scanned_until_end = 1;
20376b8ed620SJan Kara 		return 0;
20386b8ed620SJan Kara 	}
20396b8ed620SJan Kara 	return 1;
20405f1132b2SJan Kara }
20414e7ea81dSJan Kara 
20424e7ea81dSJan Kara /*
20434da2f6e3SMatthew Wilcox  * mpage_process_folio - update folio buffers corresponding to changed extent
20444da2f6e3SMatthew Wilcox  *			 and may submit fully mapped page for IO
20454da2f6e3SMatthew Wilcox  * @mpd: description of extent to map, on return next extent to map
20464da2f6e3SMatthew Wilcox  * @folio: Contains these buffers.
20474da2f6e3SMatthew Wilcox  * @m_lblk: logical block mapping.
20484da2f6e3SMatthew Wilcox  * @m_pblk: corresponding physical mapping.
20494da2f6e3SMatthew Wilcox  * @map_bh: determines on return whether this page requires any further
20502943fdbcSRitesh Harjani  *		  mapping or not.
20514da2f6e3SMatthew Wilcox  *
20524da2f6e3SMatthew Wilcox  * Scan given folio buffers corresponding to changed extent and update buffer
20532943fdbcSRitesh Harjani  * state according to new extent state.
20542943fdbcSRitesh Harjani  * We map delalloc buffers to their physical location, clear unwritten bits.
20554da2f6e3SMatthew Wilcox  * If the given folio is not fully mapped, we update @mpd to the next extent in
20564da2f6e3SMatthew Wilcox  * the given folio that needs mapping & return @map_bh as true.
20572943fdbcSRitesh Harjani  */
20584da2f6e3SMatthew Wilcox static int mpage_process_folio(struct mpage_da_data *mpd, struct folio *folio,
20592943fdbcSRitesh Harjani 			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
20602943fdbcSRitesh Harjani 			      bool *map_bh)
20612943fdbcSRitesh Harjani {
20622943fdbcSRitesh Harjani 	struct buffer_head *head, *bh;
20632943fdbcSRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
20642943fdbcSRitesh Harjani 	ext4_lblk_t lblk = *m_lblk;
20652943fdbcSRitesh Harjani 	ext4_fsblk_t pblock = *m_pblk;
20662943fdbcSRitesh Harjani 	int err = 0;
2067c8cc8816SRitesh Harjani 	int blkbits = mpd->inode->i_blkbits;
2068c8cc8816SRitesh Harjani 	ssize_t io_end_size = 0;
2069c8cc8816SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
20702943fdbcSRitesh Harjani 
20714da2f6e3SMatthew Wilcox 	bh = head = folio_buffers(folio);
20722943fdbcSRitesh Harjani 	do {
20732943fdbcSRitesh Harjani 		if (lblk < mpd->map.m_lblk)
20742943fdbcSRitesh Harjani 			continue;
20752943fdbcSRitesh Harjani 		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
20762943fdbcSRitesh Harjani 			/*
20772943fdbcSRitesh Harjani 			 * Buffer after end of mapped extent.
20784da2f6e3SMatthew Wilcox 			 * Find next buffer in the folio to map.
20792943fdbcSRitesh Harjani 			 */
20802943fdbcSRitesh Harjani 			mpd->map.m_len = 0;
20812943fdbcSRitesh Harjani 			mpd->map.m_flags = 0;
2082c8cc8816SRitesh Harjani 			io_end_vec->size += io_end_size;
20832943fdbcSRitesh Harjani 
20842943fdbcSRitesh Harjani 			err = mpage_process_page_bufs(mpd, head, bh, lblk);
20852943fdbcSRitesh Harjani 			if (err > 0)
20862943fdbcSRitesh Harjani 				err = 0;
2087c8cc8816SRitesh Harjani 			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2088c8cc8816SRitesh Harjani 				io_end_vec = ext4_alloc_io_end_vec(io_end);
20894d06bfb9SRitesh Harjani 				if (IS_ERR(io_end_vec)) {
20904d06bfb9SRitesh Harjani 					err = PTR_ERR(io_end_vec);
20914d06bfb9SRitesh Harjani 					goto out;
20924d06bfb9SRitesh Harjani 				}
2093d1e18b88SRitesh Harjani 				io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2094c8cc8816SRitesh Harjani 			}
20952943fdbcSRitesh Harjani 			*map_bh = true;
20962943fdbcSRitesh Harjani 			goto out;
20972943fdbcSRitesh Harjani 		}
20982943fdbcSRitesh Harjani 		if (buffer_delay(bh)) {
20992943fdbcSRitesh Harjani 			clear_buffer_delay(bh);
21002943fdbcSRitesh Harjani 			bh->b_blocknr = pblock++;
21012943fdbcSRitesh Harjani 		}
21022943fdbcSRitesh Harjani 		clear_buffer_unwritten(bh);
2103c8cc8816SRitesh Harjani 		io_end_size += (1 << blkbits);
21042943fdbcSRitesh Harjani 	} while (lblk++, (bh = bh->b_this_page) != head);
2105c8cc8816SRitesh Harjani 
2106c8cc8816SRitesh Harjani 	io_end_vec->size += io_end_size;
21072943fdbcSRitesh Harjani 	*map_bh = false;
21082943fdbcSRitesh Harjani out:
21092943fdbcSRitesh Harjani 	*m_lblk = lblk;
21102943fdbcSRitesh Harjani 	*m_pblk = pblock;
21112943fdbcSRitesh Harjani 	return err;
21122943fdbcSRitesh Harjani }
21132943fdbcSRitesh Harjani 
21142943fdbcSRitesh Harjani /*
21154e7ea81dSJan Kara  * mpage_map_buffers - update buffers corresponding to changed extent and
21164e7ea81dSJan Kara  *		       submit fully mapped pages for IO
21174e7ea81dSJan Kara  *
21184e7ea81dSJan Kara  * @mpd - description of extent to map, on return next extent to map
21194e7ea81dSJan Kara  *
21204e7ea81dSJan Kara  * Scan buffers corresponding to changed extent (we expect corresponding pages
21214e7ea81dSJan Kara  * to be already locked) and update buffer state according to new extent state.
21224e7ea81dSJan Kara  * We map delalloc buffers to their physical location, clear unwritten bits,
2123556615dcSLukas Czerner  * and mark buffers as uninit when we perform writes to unwritten extents
21244e7ea81dSJan Kara  * and do extent conversion after IO is finished. If the last page is not fully
21254e7ea81dSJan Kara  * mapped, we update @map to the next extent in the last page that needs
21264e7ea81dSJan Kara  * mapping. Otherwise we submit the page for IO.
21274e7ea81dSJan Kara  */
21284e7ea81dSJan Kara static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
21294e7ea81dSJan Kara {
21307530d093SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
21317530d093SMatthew Wilcox (Oracle) 	unsigned nr, i;
21324e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
213309cbfeafSKirill A. Shutemov 	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
21344e7ea81dSJan Kara 	pgoff_t start, end;
21354e7ea81dSJan Kara 	ext4_lblk_t lblk;
21362943fdbcSRitesh Harjani 	ext4_fsblk_t pblock;
21374e7ea81dSJan Kara 	int err;
21382943fdbcSRitesh Harjani 	bool map_bh = false;
21394e7ea81dSJan Kara 
21404e7ea81dSJan Kara 	start = mpd->map.m_lblk >> bpp_bits;
21414e7ea81dSJan Kara 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
21424e7ea81dSJan Kara 	lblk = start << bpp_bits;
21434e7ea81dSJan Kara 	pblock = mpd->map.m_pblk;
21444e7ea81dSJan Kara 
21457530d093SMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
21464e7ea81dSJan Kara 	while (start <= end) {
21477530d093SMatthew Wilcox (Oracle) 		nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
21487530d093SMatthew Wilcox (Oracle) 		if (nr == 0)
21494e7ea81dSJan Kara 			break;
21507530d093SMatthew Wilcox (Oracle) 		for (i = 0; i < nr; i++) {
21514da2f6e3SMatthew Wilcox 			struct folio *folio = fbatch.folios[i];
21524e7ea81dSJan Kara 
21534da2f6e3SMatthew Wilcox 			err = mpage_process_folio(mpd, folio, &lblk, &pblock,
21542943fdbcSRitesh Harjani 						 &map_bh);
21554e7ea81dSJan Kara 			/*
21562943fdbcSRitesh Harjani 			 * If map_bh is true, means page may require further bh
21572943fdbcSRitesh Harjani 			 * mapping, or maybe the page was submitted for IO.
21582943fdbcSRitesh Harjani 			 * So we return to call further extent mapping.
21594e7ea81dSJan Kara 			 */
216039c0ae16SJason Yan 			if (err < 0 || map_bh)
21612943fdbcSRitesh Harjani 				goto out;
21624e7ea81dSJan Kara 			/* Page fully mapped - let IO run! */
216381a0d3e1SMatthew Wilcox 			err = mpage_submit_folio(mpd, folio);
21642943fdbcSRitesh Harjani 			if (err < 0)
21652943fdbcSRitesh Harjani 				goto out;
216633483b3bSMatthew Wilcox 			mpage_folio_done(mpd, folio);
21674e7ea81dSJan Kara 		}
21687530d093SMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
21694e7ea81dSJan Kara 	}
21704e7ea81dSJan Kara 	/* Extent fully mapped and matches with page boundary. We are done. */
21714e7ea81dSJan Kara 	mpd->map.m_len = 0;
21724e7ea81dSJan Kara 	mpd->map.m_flags = 0;
21734e7ea81dSJan Kara 	return 0;
21742943fdbcSRitesh Harjani out:
21757530d093SMatthew Wilcox (Oracle) 	folio_batch_release(&fbatch);
21762943fdbcSRitesh Harjani 	return err;
21774e7ea81dSJan Kara }
21784e7ea81dSJan Kara 
21794e7ea81dSJan Kara static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
21804e7ea81dSJan Kara {
21814e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
21824e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
21834e7ea81dSJan Kara 	int get_blocks_flags;
2184090f32eeSLukas Czerner 	int err, dioread_nolock;
21854e7ea81dSJan Kara 
21864e7ea81dSJan Kara 	trace_ext4_da_write_pages_extent(inode, map);
21874e7ea81dSJan Kara 	/*
21884e7ea81dSJan Kara 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2189556615dcSLukas Czerner 	 * to convert an unwritten extent to be initialized (in the case
21904e7ea81dSJan Kara 	 * where we have written into one or more preallocated blocks).  It is
21914e7ea81dSJan Kara 	 * possible that we're going to need more metadata blocks than
21924e7ea81dSJan Kara 	 * previously reserved. However we must not fail because we're in
21934e7ea81dSJan Kara 	 * writeback and there is nothing we can do about it so it might result
21944e7ea81dSJan Kara 	 * in data loss.  So use reserved blocks to allocate metadata if
21954e7ea81dSJan Kara 	 * possible.
21964e7ea81dSJan Kara 	 *
2197754cfed6STheodore Ts'o 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2198754cfed6STheodore Ts'o 	 * the blocks in question are delalloc blocks.  This indicates
2199754cfed6STheodore Ts'o 	 * that the blocks and quotas has already been checked when
2200754cfed6STheodore Ts'o 	 * the data was copied into the page cache.
22014e7ea81dSJan Kara 	 */
22024e7ea81dSJan Kara 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2203ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2204ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_IO_SUBMIT;
2205090f32eeSLukas Czerner 	dioread_nolock = ext4_should_dioread_nolock(inode);
2206090f32eeSLukas Czerner 	if (dioread_nolock)
22074e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
22086db07461SRitesh Harjani 	if (map->m_flags & BIT(BH_Delay))
22094e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
22104e7ea81dSJan Kara 
22114e7ea81dSJan Kara 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
22124e7ea81dSJan Kara 	if (err < 0)
22134e7ea81dSJan Kara 		return err;
2214090f32eeSLukas Czerner 	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
22156b523df4SJan Kara 		if (!mpd->io_submit.io_end->handle &&
22166b523df4SJan Kara 		    ext4_handle_valid(handle)) {
22176b523df4SJan Kara 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
22186b523df4SJan Kara 			handle->h_rsv_handle = NULL;
22196b523df4SJan Kara 		}
22203613d228SJan Kara 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
22216b523df4SJan Kara 	}
22224e7ea81dSJan Kara 
22234e7ea81dSJan Kara 	BUG_ON(map->m_len == 0);
22244e7ea81dSJan Kara 	return 0;
22254e7ea81dSJan Kara }
22264e7ea81dSJan Kara 
22274e7ea81dSJan Kara /*
22284e7ea81dSJan Kara  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
22294e7ea81dSJan Kara  *				 mpd->len and submit pages underlying it for IO
22304e7ea81dSJan Kara  *
22314e7ea81dSJan Kara  * @handle - handle for journal operations
22324e7ea81dSJan Kara  * @mpd - extent to map
22337534e854SJan Kara  * @give_up_on_write - we set this to true iff there is a fatal error and there
22347534e854SJan Kara  *                     is no hope of writing the data. The caller should discard
22357534e854SJan Kara  *                     dirty pages to avoid infinite loops.
22364e7ea81dSJan Kara  *
22374e7ea81dSJan Kara  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
22384e7ea81dSJan Kara  * delayed, blocks are allocated, if it is unwritten, we may need to convert
22394e7ea81dSJan Kara  * them to initialized or split the described range from larger unwritten
22404e7ea81dSJan Kara  * extent. Note that we need not map all the described range since allocation
22414e7ea81dSJan Kara  * can return less blocks or the range is covered by more unwritten extents. We
22424e7ea81dSJan Kara  * cannot map more because we are limited by reserved transaction credits. On
22434e7ea81dSJan Kara  * the other hand we always make sure that the last touched page is fully
22444e7ea81dSJan Kara  * mapped so that it can be written out (and thus forward progress is
22454e7ea81dSJan Kara  * guaranteed). After mapping we submit all mapped pages for IO.
22464e7ea81dSJan Kara  */
22474e7ea81dSJan Kara static int mpage_map_and_submit_extent(handle_t *handle,
2248cb530541STheodore Ts'o 				       struct mpage_da_data *mpd,
2249cb530541STheodore Ts'o 				       bool *give_up_on_write)
22504e7ea81dSJan Kara {
22514e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
22524e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
22534e7ea81dSJan Kara 	int err;
22544e7ea81dSJan Kara 	loff_t disksize;
22556603120eSDmitry Monakhov 	int progress = 0;
2256c8cc8816SRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
22574d06bfb9SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec;
22584e7ea81dSJan Kara 
22594d06bfb9SRitesh Harjani 	io_end_vec = ext4_alloc_io_end_vec(io_end);
22604d06bfb9SRitesh Harjani 	if (IS_ERR(io_end_vec))
22614d06bfb9SRitesh Harjani 		return PTR_ERR(io_end_vec);
2262c8cc8816SRitesh Harjani 	io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
226327d7c4edSJan Kara 	do {
22644e7ea81dSJan Kara 		err = mpage_map_one_extent(handle, mpd);
22654e7ea81dSJan Kara 		if (err < 0) {
22664e7ea81dSJan Kara 			struct super_block *sb = inode->i_sb;
22674e7ea81dSJan Kara 
22680db1ff22STheodore Ts'o 			if (ext4_forced_shutdown(EXT4_SB(sb)) ||
22699b5f6c9bSHarshad Shirwadkar 			    ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
2270cb530541STheodore Ts'o 				goto invalidate_dirty_pages;
22714e7ea81dSJan Kara 			/*
2272cb530541STheodore Ts'o 			 * Let the uper layers retry transient errors.
2273cb530541STheodore Ts'o 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2274cb530541STheodore Ts'o 			 * is non-zero, a commit should free up blocks.
22754e7ea81dSJan Kara 			 */
2276cb530541STheodore Ts'o 			if ((err == -ENOMEM) ||
22776603120eSDmitry Monakhov 			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
22786603120eSDmitry Monakhov 				if (progress)
22796603120eSDmitry Monakhov 					goto update_disksize;
2280cb530541STheodore Ts'o 				return err;
22816603120eSDmitry Monakhov 			}
22824e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
22834e7ea81dSJan Kara 				 "Delayed block allocation failed for "
22844e7ea81dSJan Kara 				 "inode %lu at logical offset %llu with"
22854e7ea81dSJan Kara 				 " max blocks %u with error %d",
22864e7ea81dSJan Kara 				 inode->i_ino,
22874e7ea81dSJan Kara 				 (unsigned long long)map->m_lblk,
2288cb530541STheodore Ts'o 				 (unsigned)map->m_len, -err);
22894e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
22904e7ea81dSJan Kara 				 "This should not happen!! Data will "
22914e7ea81dSJan Kara 				 "be lost\n");
22924e7ea81dSJan Kara 			if (err == -ENOSPC)
22934e7ea81dSJan Kara 				ext4_print_free_blocks(inode);
2294cb530541STheodore Ts'o 		invalidate_dirty_pages:
2295cb530541STheodore Ts'o 			*give_up_on_write = true;
22964e7ea81dSJan Kara 			return err;
22974e7ea81dSJan Kara 		}
22986603120eSDmitry Monakhov 		progress = 1;
22994e7ea81dSJan Kara 		/*
23004e7ea81dSJan Kara 		 * Update buffer state, submit mapped pages, and get us new
23014e7ea81dSJan Kara 		 * extent to map
23024e7ea81dSJan Kara 		 */
23034e7ea81dSJan Kara 		err = mpage_map_and_submit_buffers(mpd);
23044e7ea81dSJan Kara 		if (err < 0)
23056603120eSDmitry Monakhov 			goto update_disksize;
230627d7c4edSJan Kara 	} while (map->m_len);
23074e7ea81dSJan Kara 
23086603120eSDmitry Monakhov update_disksize:
2309622cad13STheodore Ts'o 	/*
2310622cad13STheodore Ts'o 	 * Update on-disk size after IO is submitted.  Races with
2311622cad13STheodore Ts'o 	 * truncate are avoided by checking i_size under i_data_sem.
2312622cad13STheodore Ts'o 	 */
231309cbfeafSKirill A. Shutemov 	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
231435df4299SQian Cai 	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
23154e7ea81dSJan Kara 		int err2;
2316622cad13STheodore Ts'o 		loff_t i_size;
23174e7ea81dSJan Kara 
2318622cad13STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
2319622cad13STheodore Ts'o 		i_size = i_size_read(inode);
2320622cad13STheodore Ts'o 		if (disksize > i_size)
2321622cad13STheodore Ts'o 			disksize = i_size;
2322622cad13STheodore Ts'o 		if (disksize > EXT4_I(inode)->i_disksize)
2323622cad13STheodore Ts'o 			EXT4_I(inode)->i_disksize = disksize;
2324622cad13STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
2325b907f2d5STheodore Ts'o 		err2 = ext4_mark_inode_dirty(handle, inode);
2326878520acSTheodore Ts'o 		if (err2) {
232754d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err2,
23284e7ea81dSJan Kara 				       "Failed to mark inode %lu dirty",
23294e7ea81dSJan Kara 				       inode->i_ino);
2330878520acSTheodore Ts'o 		}
23314e7ea81dSJan Kara 		if (!err)
23324e7ea81dSJan Kara 			err = err2;
23334e7ea81dSJan Kara 	}
23344e7ea81dSJan Kara 	return err;
23354e7ea81dSJan Kara }
23364e7ea81dSJan Kara 
23374e7ea81dSJan Kara /*
2338fffb2739SJan Kara  * Calculate the total number of credits to reserve for one writepages
233920970ba6STheodore Ts'o  * iteration. This is called from ext4_writepages(). We map an extent of
2340fffb2739SJan Kara  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2341fffb2739SJan Kara  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2342fffb2739SJan Kara  * bpp - 1 blocks in bpp different extents.
2343525f4ed8SMingming Cao  */
2344fffb2739SJan Kara static int ext4_da_writepages_trans_blocks(struct inode *inode)
2345fffb2739SJan Kara {
2346fffb2739SJan Kara 	int bpp = ext4_journal_blocks_per_page(inode);
2347525f4ed8SMingming Cao 
2348fffb2739SJan Kara 	return ext4_meta_trans_blocks(inode,
2349fffb2739SJan Kara 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2350525f4ed8SMingming Cao }
235161628a3fSMingming Cao 
23523f079114SJan Kara static int ext4_journal_page_buffers(handle_t *handle, struct page *page,
23533f079114SJan Kara 				     int len)
23543f079114SJan Kara {
23553f079114SJan Kara 	struct buffer_head *page_bufs = page_buffers(page);
23563f079114SJan Kara 	struct inode *inode = page->mapping->host;
23573f079114SJan Kara 	int ret, err;
23583f079114SJan Kara 
23593f079114SJan Kara 	ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
23603f079114SJan Kara 				     NULL, do_journal_get_write_access);
23613f079114SJan Kara 	err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
23623f079114SJan Kara 				     NULL, write_end_fn);
23633f079114SJan Kara 	if (ret == 0)
23643f079114SJan Kara 		ret = err;
23653f079114SJan Kara 	err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
23663f079114SJan Kara 	if (ret == 0)
23673f079114SJan Kara 		ret = err;
23683f079114SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
23693f079114SJan Kara 
23703f079114SJan Kara 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
23713f079114SJan Kara 
23723f079114SJan Kara 	return ret;
23733f079114SJan Kara }
23743f079114SJan Kara 
23753f079114SJan Kara static int mpage_journal_page_buffers(handle_t *handle,
23763f079114SJan Kara 				      struct mpage_da_data *mpd,
23773f079114SJan Kara 				      struct page *page)
23783f079114SJan Kara {
23793f079114SJan Kara 	struct inode *inode = mpd->inode;
23803f079114SJan Kara 	loff_t size = i_size_read(inode);
23813f079114SJan Kara 	int len;
23823f079114SJan Kara 
23833f079114SJan Kara 	ClearPageChecked(page);
23843f079114SJan Kara 	mpd->wbc->nr_to_write--;
23853f079114SJan Kara 
23863f079114SJan Kara 	if (page->index == size >> PAGE_SHIFT &&
23873f079114SJan Kara 	    !ext4_verity_in_progress(inode))
23883f079114SJan Kara 		len = size & ~PAGE_MASK;
23893f079114SJan Kara 	else
23903f079114SJan Kara 		len = PAGE_SIZE;
23913f079114SJan Kara 
23923f079114SJan Kara 	return ext4_journal_page_buffers(handle, page, len);
23933f079114SJan Kara }
23943f079114SJan Kara 
23958e48dcfbSTheodore Ts'o /*
23964e7ea81dSJan Kara  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2397de0039f6SJan Kara  * 				 needing mapping, submit mapped pages
23984e7ea81dSJan Kara  *
23994e7ea81dSJan Kara  * @mpd - where to look for pages
24004e7ea81dSJan Kara  *
24014e7ea81dSJan Kara  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2402de0039f6SJan Kara  * IO immediately. If we cannot map blocks, we submit just already mapped
2403de0039f6SJan Kara  * buffers in the page for IO and keep page dirty. When we can map blocks and
2404de0039f6SJan Kara  * we find a page which isn't mapped we start accumulating extent of buffers
2405de0039f6SJan Kara  * underlying these pages that needs mapping (formed by either delayed or
2406de0039f6SJan Kara  * unwritten buffers). We also lock the pages containing these buffers. The
2407de0039f6SJan Kara  * extent found is returned in @mpd structure (starting at mpd->lblk with
2408de0039f6SJan Kara  * length mpd->len blocks).
24094e7ea81dSJan Kara  *
24104e7ea81dSJan Kara  * Note that this function can attach bios to one io_end structure which are
24114e7ea81dSJan Kara  * neither logically nor physically contiguous. Although it may seem as an
24124e7ea81dSJan Kara  * unnecessary complication, it is actually inevitable in blocksize < pagesize
24134e7ea81dSJan Kara  * case as we need to track IO to all buffers underlying a page in one io_end.
24148e48dcfbSTheodore Ts'o  */
24154e7ea81dSJan Kara static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
24168e48dcfbSTheodore Ts'o {
24174e7ea81dSJan Kara 	struct address_space *mapping = mpd->inode->i_mapping;
2418e6c28a26SJan Kara 	struct super_block *sb = mpd->inode->i_sb;
241950ead253SVishal Moola (Oracle) 	struct folio_batch fbatch;
242050ead253SVishal Moola (Oracle) 	unsigned int nr_folios;
24214e7ea81dSJan Kara 	pgoff_t index = mpd->first_page;
24224e7ea81dSJan Kara 	pgoff_t end = mpd->last_page;
242310bbd235SMatthew Wilcox 	xa_mark_t tag;
24244e7ea81dSJan Kara 	int i, err = 0;
24254e7ea81dSJan Kara 	int blkbits = mpd->inode->i_blkbits;
24264e7ea81dSJan Kara 	ext4_lblk_t lblk;
24274e7ea81dSJan Kara 	struct buffer_head *head;
24283f079114SJan Kara 	handle_t *handle = NULL;
24293f079114SJan Kara 	int bpp = ext4_journal_blocks_per_page(mpd->inode);
24308e48dcfbSTheodore Ts'o 
24314e7ea81dSJan Kara 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
24325b41d924SEric Sandeen 		tag = PAGECACHE_TAG_TOWRITE;
24335b41d924SEric Sandeen 	else
24345b41d924SEric Sandeen 		tag = PAGECACHE_TAG_DIRTY;
24353f079114SJan Kara 
2436e6c28a26SJan Kara 	mpd->map.m_len = 0;
2437e6c28a26SJan Kara 	mpd->next_page = index;
2438e6c28a26SJan Kara 	/*
2439e6c28a26SJan Kara 	 * Start a transaction for writeback of journalled data. We don't start
244098ccceeeSTheodore Ts'o 	 * the transaction if the filesystem is frozen. In that case we
2441e6c28a26SJan Kara 	 * should not have any dirty data to write anymore but possibly there
2442e6c28a26SJan Kara 	 * are stray page dirty bits left by the checkpointing code so this
2443e6c28a26SJan Kara 	 * loop clears them.
2444e6c28a26SJan Kara 	 */
2445e6c28a26SJan Kara 	if (ext4_should_journal_data(mpd->inode) &&
2446e6c28a26SJan Kara 	    sb->s_writers.frozen < SB_FREEZE_FS) {
24473f079114SJan Kara 		handle = ext4_journal_start(mpd->inode, EXT4_HT_WRITE_PAGE,
24483f079114SJan Kara 					    bpp);
24493f079114SJan Kara 		if (IS_ERR(handle))
24503f079114SJan Kara 			return PTR_ERR(handle);
24513f079114SJan Kara 	}
245250ead253SVishal Moola (Oracle) 	folio_batch_init(&fbatch);
24534f01b02cSTheodore Ts'o 	while (index <= end) {
245450ead253SVishal Moola (Oracle) 		nr_folios = filemap_get_folios_tag(mapping, &index, end,
245550ead253SVishal Moola (Oracle) 				tag, &fbatch);
245650ead253SVishal Moola (Oracle) 		if (nr_folios == 0)
24576b8ed620SJan Kara 			break;
24588e48dcfbSTheodore Ts'o 
245950ead253SVishal Moola (Oracle) 		for (i = 0; i < nr_folios; i++) {
246050ead253SVishal Moola (Oracle) 			struct folio *folio = fbatch.folios[i];
24618e48dcfbSTheodore Ts'o 
24628e48dcfbSTheodore Ts'o 			/*
2463aeac589aSMing Lei 			 * Accumulated enough dirty pages? This doesn't apply
2464aeac589aSMing Lei 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2465aeac589aSMing Lei 			 * keep going because someone may be concurrently
2466aeac589aSMing Lei 			 * dirtying pages, and we might have synced a lot of
2467aeac589aSMing Lei 			 * newly appeared dirty pages, but have not synced all
2468aeac589aSMing Lei 			 * of the old dirty pages.
2469aeac589aSMing Lei 			 */
2470c8e8e16dSJan Kara 			if (mpd->wbc->sync_mode == WB_SYNC_NONE &&
2471c8e8e16dSJan Kara 			    mpd->wbc->nr_to_write <=
2472c8e8e16dSJan Kara 			    mpd->map.m_len >> (PAGE_SHIFT - blkbits))
2473aeac589aSMing Lei 				goto out;
2474aeac589aSMing Lei 
24754e7ea81dSJan Kara 			/* If we can't merge this page, we are done. */
247650ead253SVishal Moola (Oracle) 			if (mpd->map.m_len > 0 && mpd->next_page != folio->index)
24774e7ea81dSJan Kara 				goto out;
247878aaced3STheodore Ts'o 
24793f079114SJan Kara 			if (handle) {
24803f079114SJan Kara 				err = ext4_journal_ensure_credits(handle, bpp,
24813f079114SJan Kara 								  0);
24823f079114SJan Kara 				if (err < 0)
24833f079114SJan Kara 					goto out;
24843f079114SJan Kara 			}
24853f079114SJan Kara 
248650ead253SVishal Moola (Oracle) 			folio_lock(folio);
24878e48dcfbSTheodore Ts'o 			/*
24884e7ea81dSJan Kara 			 * If the page is no longer dirty, or its mapping no
24894e7ea81dSJan Kara 			 * longer corresponds to inode we are writing (which
24904e7ea81dSJan Kara 			 * means it has been truncated or invalidated), or the
24914e7ea81dSJan Kara 			 * page is already under writeback and we are not doing
24924e7ea81dSJan Kara 			 * a data integrity writeback, skip the page
24938e48dcfbSTheodore Ts'o 			 */
249450ead253SVishal Moola (Oracle) 			if (!folio_test_dirty(folio) ||
249550ead253SVishal Moola (Oracle) 			    (folio_test_writeback(folio) &&
24964e7ea81dSJan Kara 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
249750ead253SVishal Moola (Oracle) 			    unlikely(folio->mapping != mapping)) {
249850ead253SVishal Moola (Oracle) 				folio_unlock(folio);
24998e48dcfbSTheodore Ts'o 				continue;
25008e48dcfbSTheodore Ts'o 			}
25018e48dcfbSTheodore Ts'o 
250250ead253SVishal Moola (Oracle) 			folio_wait_writeback(folio);
250350ead253SVishal Moola (Oracle) 			BUG_ON(folio_test_writeback(folio));
25048e48dcfbSTheodore Ts'o 
2505cc509574STheodore Ts'o 			/*
2506cc509574STheodore Ts'o 			 * Should never happen but for buggy code in
2507cc509574STheodore Ts'o 			 * other subsystems that call
2508cc509574STheodore Ts'o 			 * set_page_dirty() without properly warning
2509cc509574STheodore Ts'o 			 * the file system first.  See [1] for more
2510cc509574STheodore Ts'o 			 * information.
2511cc509574STheodore Ts'o 			 *
2512cc509574STheodore Ts'o 			 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2513cc509574STheodore Ts'o 			 */
251450ead253SVishal Moola (Oracle) 			if (!folio_buffers(folio)) {
251550ead253SVishal Moola (Oracle) 				ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", folio->index);
251650ead253SVishal Moola (Oracle) 				folio_clear_dirty(folio);
251750ead253SVishal Moola (Oracle) 				folio_unlock(folio);
2518cc509574STheodore Ts'o 				continue;
2519cc509574STheodore Ts'o 			}
2520cc509574STheodore Ts'o 
25214e7ea81dSJan Kara 			if (mpd->map.m_len == 0)
252250ead253SVishal Moola (Oracle) 				mpd->first_page = folio->index;
252350ead253SVishal Moola (Oracle) 			mpd->next_page = folio->index + folio_nr_pages(folio);
2524de0039f6SJan Kara 			/*
25253f079114SJan Kara 			 * Writeout when we cannot modify metadata is simple.
25263f079114SJan Kara 			 * Just submit the page. For data=journal mode we
25273f079114SJan Kara 			 * first handle writeout of the page for checkpoint and
25283f079114SJan Kara 			 * only after that handle delayed page dirtying. This
25293f079114SJan Kara 			 * is crutial so that forcing a transaction commit and
25303f079114SJan Kara 			 * then calling filemap_write_and_wait() guarantees
25313f079114SJan Kara 			 * current state of data is in its final location. Such
25323f079114SJan Kara 			 * sequence is used for example by insert/collapse
25333f079114SJan Kara 			 * range operations before discarding the page cache.
2534de0039f6SJan Kara 			 */
2535de0039f6SJan Kara 			if (!mpd->can_map) {
2536e6c28a26SJan Kara 				WARN_ON_ONCE(sb->s_writers.frozen ==
2537e6c28a26SJan Kara 					     SB_FREEZE_COMPLETE);
253881a0d3e1SMatthew Wilcox 				err = mpage_submit_folio(mpd, folio);
2539de0039f6SJan Kara 				if (err < 0)
2540de0039f6SJan Kara 					goto out;
25413f079114SJan Kara 				/* Pending dirtying of journalled data? */
254281a0d3e1SMatthew Wilcox 				if (folio_test_checked(folio)) {
2543e6c28a26SJan Kara 					WARN_ON_ONCE(sb->s_writers.frozen >=
2544e6c28a26SJan Kara 						     SB_FREEZE_FS);
25453f079114SJan Kara 					err = mpage_journal_page_buffers(handle,
25463f079114SJan Kara 						mpd, &folio->page);
25473f079114SJan Kara 					if (err < 0)
25483f079114SJan Kara 						goto out;
2549*1f1a55f0SJan Kara 					mpd->journalled_more_data = 1;
25503f079114SJan Kara 				}
255133483b3bSMatthew Wilcox 				mpage_folio_done(mpd, folio);
2552de0039f6SJan Kara 			} else {
2553f8bec370SJan Kara 				/* Add all dirty buffers to mpd */
255450ead253SVishal Moola (Oracle) 				lblk = ((ext4_lblk_t)folio->index) <<
255509cbfeafSKirill A. Shutemov 					(PAGE_SHIFT - blkbits);
255650ead253SVishal Moola (Oracle) 				head = folio_buffers(folio);
2557de0039f6SJan Kara 				err = mpage_process_page_bufs(mpd, head, head,
2558de0039f6SJan Kara 						lblk);
25595f1132b2SJan Kara 				if (err <= 0)
25604e7ea81dSJan Kara 					goto out;
25615f1132b2SJan Kara 				err = 0;
2562de0039f6SJan Kara 			}
25638e48dcfbSTheodore Ts'o 		}
256450ead253SVishal Moola (Oracle) 		folio_batch_release(&fbatch);
25658e48dcfbSTheodore Ts'o 		cond_resched();
25668e48dcfbSTheodore Ts'o 	}
25676b8ed620SJan Kara 	mpd->scanned_until_end = 1;
25683f079114SJan Kara 	if (handle)
25693f079114SJan Kara 		ext4_journal_stop(handle);
25704f01b02cSTheodore Ts'o 	return 0;
25718eb9e5ceSTheodore Ts'o out:
257250ead253SVishal Moola (Oracle) 	folio_batch_release(&fbatch);
25733f079114SJan Kara 	if (handle)
25743f079114SJan Kara 		ext4_journal_stop(handle);
25754e7ea81dSJan Kara 	return err;
25768e48dcfbSTheodore Ts'o }
25778e48dcfbSTheodore Ts'o 
257815648d59SJan Kara static int ext4_do_writepages(struct mpage_da_data *mpd)
257964769240SAlex Tomas {
258015648d59SJan Kara 	struct writeback_control *wbc = mpd->wbc;
25814e7ea81dSJan Kara 	pgoff_t	writeback_index = 0;
25824e7ea81dSJan Kara 	long nr_to_write = wbc->nr_to_write;
258322208dedSAneesh Kumar K.V 	int range_whole = 0;
25844e7ea81dSJan Kara 	int cycled = 1;
258561628a3fSMingming Cao 	handle_t *handle = NULL;
258615648d59SJan Kara 	struct inode *inode = mpd->inode;
258715648d59SJan Kara 	struct address_space *mapping = inode->i_mapping;
25886b523df4SJan Kara 	int needed_blocks, rsv_blocks = 0, ret = 0;
25895e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
25901bce63d1SShaohua Li 	struct blk_plug plug;
2591cb530541STheodore Ts'o 	bool give_up_on_write = false;
259261628a3fSMingming Cao 
259320970ba6STheodore Ts'o 	trace_ext4_writepages(inode, wbc);
2594ba80b101STheodore Ts'o 
259561628a3fSMingming Cao 	/*
259661628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
259761628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
259861628a3fSMingming Cao 	 * because that could violate lock ordering on umount
259961628a3fSMingming Cao 	 */
2600a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2601bbf023c7SMing Lei 		goto out_writepages;
26022a21e37eSTheodore Ts'o 
26032a21e37eSTheodore Ts'o 	/*
26042a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
26052a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
26062a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
26071751e8a6SLinus Torvalds 	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
26082a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
260920970ba6STheodore Ts'o 	 * read-only, and in that case, ext4_writepages should
26102a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
26112a21e37eSTheodore Ts'o 	 * the stack trace.
26122a21e37eSTheodore Ts'o 	 */
26130db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
26149b5f6c9bSHarshad Shirwadkar 		     ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
2615bbf023c7SMing Lei 		ret = -EROFS;
2616bbf023c7SMing Lei 		goto out_writepages;
2617bbf023c7SMing Lei 	}
26182a21e37eSTheodore Ts'o 
26194e7ea81dSJan Kara 	/*
26204e7ea81dSJan Kara 	 * If we have inline data and arrive here, it means that
26214e7ea81dSJan Kara 	 * we will soon create the block for the 1st page, so
26224e7ea81dSJan Kara 	 * we'd better clear the inline data here.
26234e7ea81dSJan Kara 	 */
26244e7ea81dSJan Kara 	if (ext4_has_inline_data(inode)) {
26254e7ea81dSJan Kara 		/* Just inode will be modified... */
26264e7ea81dSJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
26274e7ea81dSJan Kara 		if (IS_ERR(handle)) {
26284e7ea81dSJan Kara 			ret = PTR_ERR(handle);
26294e7ea81dSJan Kara 			goto out_writepages;
26304e7ea81dSJan Kara 		}
26314e7ea81dSJan Kara 		BUG_ON(ext4_test_inode_state(inode,
26324e7ea81dSJan Kara 				EXT4_STATE_MAY_INLINE_DATA));
26334e7ea81dSJan Kara 		ext4_destroy_inline_data(handle, inode);
26344e7ea81dSJan Kara 		ext4_journal_stop(handle);
26354e7ea81dSJan Kara 	}
26364e7ea81dSJan Kara 
26373f079114SJan Kara 	/*
26383f079114SJan Kara 	 * data=journal mode does not do delalloc so we just need to writeout /
2639*1f1a55f0SJan Kara 	 * journal already mapped buffers. On the other hand we need to commit
2640*1f1a55f0SJan Kara 	 * transaction to make data stable. We expect all the data to be
2641*1f1a55f0SJan Kara 	 * already in the journal (the only exception are DMA pinned pages
2642*1f1a55f0SJan Kara 	 * dirtied behind our back) so we commit transaction here and run the
2643*1f1a55f0SJan Kara 	 * writeback loop to checkpoint them. The checkpointing is not actually
2644*1f1a55f0SJan Kara 	 * necessary to make data persistent *but* quite a few places (extent
2645*1f1a55f0SJan Kara 	 * shifting operations, fsverity, ...) depend on being able to drop
2646*1f1a55f0SJan Kara 	 * pagecache pages after calling filemap_write_and_wait() and for that
2647*1f1a55f0SJan Kara 	 * checkpointing needs to happen.
26483f079114SJan Kara 	 */
2649*1f1a55f0SJan Kara 	if (ext4_should_journal_data(inode)) {
26503f079114SJan Kara 		mpd->can_map = 0;
2651*1f1a55f0SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL)
2652*1f1a55f0SJan Kara 			ext4_fc_commit(sbi->s_journal,
2653*1f1a55f0SJan Kara 				       EXT4_I(inode)->i_datasync_tid);
2654*1f1a55f0SJan Kara 	}
2655*1f1a55f0SJan Kara 	mpd->journalled_more_data = 0;
26563f079114SJan Kara 
26574e343231Syangerkun 	if (ext4_should_dioread_nolock(inode)) {
26584e343231Syangerkun 		/*
26594e343231Syangerkun 		 * We may need to convert up to one extent per block in
26604e343231Syangerkun 		 * the page and we may dirty the inode.
26614e343231Syangerkun 		 */
26624e343231Syangerkun 		rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
26634e343231Syangerkun 						PAGE_SIZE >> inode->i_blkbits);
26644e343231Syangerkun 	}
26654e343231Syangerkun 
266622208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
266722208dedSAneesh Kumar K.V 		range_whole = 1;
266861628a3fSMingming Cao 
26692acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
26704e7ea81dSJan Kara 		writeback_index = mapping->writeback_index;
26714e7ea81dSJan Kara 		if (writeback_index)
26722acf2c26SAneesh Kumar K.V 			cycled = 0;
267315648d59SJan Kara 		mpd->first_page = writeback_index;
267415648d59SJan Kara 		mpd->last_page = -1;
26755b41d924SEric Sandeen 	} else {
267615648d59SJan Kara 		mpd->first_page = wbc->range_start >> PAGE_SHIFT;
267715648d59SJan Kara 		mpd->last_page = wbc->range_end >> PAGE_SHIFT;
26785b41d924SEric Sandeen 	}
2679a1d6cc56SAneesh Kumar K.V 
268015648d59SJan Kara 	ext4_io_submit_init(&mpd->io_submit, wbc);
26812acf2c26SAneesh Kumar K.V retry:
26826e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
268315648d59SJan Kara 		tag_pages_for_writeback(mapping, mpd->first_page,
268415648d59SJan Kara 					mpd->last_page);
26851bce63d1SShaohua Li 	blk_start_plug(&plug);
2686dddbd6acSJan Kara 
2687dddbd6acSJan Kara 	/*
2688dddbd6acSJan Kara 	 * First writeback pages that don't need mapping - we can avoid
2689dddbd6acSJan Kara 	 * starting a transaction unnecessarily and also avoid being blocked
2690dddbd6acSJan Kara 	 * in the block layer on device congestion while having transaction
2691dddbd6acSJan Kara 	 * started.
2692dddbd6acSJan Kara 	 */
269315648d59SJan Kara 	mpd->do_map = 0;
269415648d59SJan Kara 	mpd->scanned_until_end = 0;
269515648d59SJan Kara 	mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
269615648d59SJan Kara 	if (!mpd->io_submit.io_end) {
2697dddbd6acSJan Kara 		ret = -ENOMEM;
2698dddbd6acSJan Kara 		goto unplug;
2699dddbd6acSJan Kara 	}
270015648d59SJan Kara 	ret = mpage_prepare_extent_to_map(mpd);
2701a297b2fcSXiaoguang Wang 	/* Unlock pages we didn't use */
270215648d59SJan Kara 	mpage_release_unused_pages(mpd, false);
2703dddbd6acSJan Kara 	/* Submit prepared bio */
270415648d59SJan Kara 	ext4_io_submit(&mpd->io_submit);
270515648d59SJan Kara 	ext4_put_io_end_defer(mpd->io_submit.io_end);
270615648d59SJan Kara 	mpd->io_submit.io_end = NULL;
2707dddbd6acSJan Kara 	if (ret < 0)
2708dddbd6acSJan Kara 		goto unplug;
2709dddbd6acSJan Kara 
271015648d59SJan Kara 	while (!mpd->scanned_until_end && wbc->nr_to_write > 0) {
27114e7ea81dSJan Kara 		/* For each extent of pages we use new io_end */
271215648d59SJan Kara 		mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
271315648d59SJan Kara 		if (!mpd->io_submit.io_end) {
27144e7ea81dSJan Kara 			ret = -ENOMEM;
27154e7ea81dSJan Kara 			break;
27164e7ea81dSJan Kara 		}
2717a1d6cc56SAneesh Kumar K.V 
2718de0039f6SJan Kara 		WARN_ON_ONCE(!mpd->can_map);
2719a1d6cc56SAneesh Kumar K.V 		/*
27204e7ea81dSJan Kara 		 * We have two constraints: We find one extent to map and we
27214e7ea81dSJan Kara 		 * must always write out whole page (makes a difference when
27224e7ea81dSJan Kara 		 * blocksize < pagesize) so that we don't block on IO when we
27234e7ea81dSJan Kara 		 * try to write out the rest of the page. Journalled mode is
27244e7ea81dSJan Kara 		 * not supported by delalloc.
2725a1d6cc56SAneesh Kumar K.V 		 */
2726a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
2727525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2728a1d6cc56SAneesh Kumar K.V 
272961628a3fSMingming Cao 		/* start a new transaction */
27306b523df4SJan Kara 		handle = ext4_journal_start_with_reserve(inode,
27316b523df4SJan Kara 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
273261628a3fSMingming Cao 		if (IS_ERR(handle)) {
273361628a3fSMingming Cao 			ret = PTR_ERR(handle);
27341693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2735fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
2736a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
27374e7ea81dSJan Kara 			/* Release allocated io_end */
273815648d59SJan Kara 			ext4_put_io_end(mpd->io_submit.io_end);
273915648d59SJan Kara 			mpd->io_submit.io_end = NULL;
27404e7ea81dSJan Kara 			break;
274161628a3fSMingming Cao 		}
274215648d59SJan Kara 		mpd->do_map = 1;
2743f63e6005STheodore Ts'o 
274415648d59SJan Kara 		trace_ext4_da_write_pages(inode, mpd->first_page, wbc);
274515648d59SJan Kara 		ret = mpage_prepare_extent_to_map(mpd);
274615648d59SJan Kara 		if (!ret && mpd->map.m_len)
274715648d59SJan Kara 			ret = mpage_map_and_submit_extent(handle, mpd,
2748cb530541STheodore Ts'o 					&give_up_on_write);
2749646caa9cSJan Kara 		/*
2750646caa9cSJan Kara 		 * Caution: If the handle is synchronous,
2751646caa9cSJan Kara 		 * ext4_journal_stop() can wait for transaction commit
2752646caa9cSJan Kara 		 * to finish which may depend on writeback of pages to
2753646caa9cSJan Kara 		 * complete or on page lock to be released.  In that
2754b483bb77SRandy Dunlap 		 * case, we have to wait until after we have
2755646caa9cSJan Kara 		 * submitted all the IO, released page locks we hold,
2756646caa9cSJan Kara 		 * and dropped io_end reference (for extent conversion
2757646caa9cSJan Kara 		 * to be able to complete) before stopping the handle.
2758646caa9cSJan Kara 		 */
2759646caa9cSJan Kara 		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
276061628a3fSMingming Cao 			ext4_journal_stop(handle);
2761646caa9cSJan Kara 			handle = NULL;
276215648d59SJan Kara 			mpd->do_map = 0;
2763646caa9cSJan Kara 		}
27644e7ea81dSJan Kara 		/* Unlock pages we didn't use */
276515648d59SJan Kara 		mpage_release_unused_pages(mpd, give_up_on_write);
2766a297b2fcSXiaoguang Wang 		/* Submit prepared bio */
276715648d59SJan Kara 		ext4_io_submit(&mpd->io_submit);
2768a297b2fcSXiaoguang Wang 
2769646caa9cSJan Kara 		/*
2770646caa9cSJan Kara 		 * Drop our io_end reference we got from init. We have
2771646caa9cSJan Kara 		 * to be careful and use deferred io_end finishing if
2772646caa9cSJan Kara 		 * we are still holding the transaction as we can
2773646caa9cSJan Kara 		 * release the last reference to io_end which may end
2774646caa9cSJan Kara 		 * up doing unwritten extent conversion.
2775646caa9cSJan Kara 		 */
2776646caa9cSJan Kara 		if (handle) {
277715648d59SJan Kara 			ext4_put_io_end_defer(mpd->io_submit.io_end);
2778646caa9cSJan Kara 			ext4_journal_stop(handle);
2779646caa9cSJan Kara 		} else
278015648d59SJan Kara 			ext4_put_io_end(mpd->io_submit.io_end);
278115648d59SJan Kara 		mpd->io_submit.io_end = NULL;
2782df22291fSAneesh Kumar K.V 
27834e7ea81dSJan Kara 		if (ret == -ENOSPC && sbi->s_journal) {
27844e7ea81dSJan Kara 			/*
27854e7ea81dSJan Kara 			 * Commit the transaction which would
278622208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
278722208dedSAneesh Kumar K.V 			 * and try again
278822208dedSAneesh Kumar K.V 			 */
2789df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
279022208dedSAneesh Kumar K.V 			ret = 0;
27914e7ea81dSJan Kara 			continue;
27924e7ea81dSJan Kara 		}
27934e7ea81dSJan Kara 		/* Fatal error - ENOMEM, EIO... */
27944e7ea81dSJan Kara 		if (ret)
279561628a3fSMingming Cao 			break;
279661628a3fSMingming Cao 	}
2797dddbd6acSJan Kara unplug:
27981bce63d1SShaohua Li 	blk_finish_plug(&plug);
27999c12a831SJan Kara 	if (!ret && !cycled && wbc->nr_to_write > 0) {
28002acf2c26SAneesh Kumar K.V 		cycled = 1;
280115648d59SJan Kara 		mpd->last_page = writeback_index - 1;
280215648d59SJan Kara 		mpd->first_page = 0;
28032acf2c26SAneesh Kumar K.V 		goto retry;
28042acf2c26SAneesh Kumar K.V 	}
280561628a3fSMingming Cao 
280622208dedSAneesh Kumar K.V 	/* Update index */
280722208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
280822208dedSAneesh Kumar K.V 		/*
28094e7ea81dSJan Kara 		 * Set the writeback_index so that range_cyclic
281022208dedSAneesh Kumar K.V 		 * mode will write it back later
281122208dedSAneesh Kumar K.V 		 */
281215648d59SJan Kara 		mapping->writeback_index = mpd->first_page;
2813a1d6cc56SAneesh Kumar K.V 
281461628a3fSMingming Cao out_writepages:
281520970ba6STheodore Ts'o 	trace_ext4_writepages_result(inode, wbc, ret,
28164e7ea81dSJan Kara 				     nr_to_write - wbc->nr_to_write);
281761628a3fSMingming Cao 	return ret;
281864769240SAlex Tomas }
281964769240SAlex Tomas 
282015648d59SJan Kara static int ext4_writepages(struct address_space *mapping,
282115648d59SJan Kara 			   struct writeback_control *wbc)
282215648d59SJan Kara {
282329bc9ceaSJan Kara 	struct super_block *sb = mapping->host->i_sb;
282415648d59SJan Kara 	struct mpage_da_data mpd = {
282515648d59SJan Kara 		.inode = mapping->host,
282615648d59SJan Kara 		.wbc = wbc,
282715648d59SJan Kara 		.can_map = 1,
282815648d59SJan Kara 	};
282929bc9ceaSJan Kara 	int ret;
283015648d59SJan Kara 
283129bc9ceaSJan Kara 	if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
283229bc9ceaSJan Kara 		return -EIO;
283329bc9ceaSJan Kara 
283429bc9ceaSJan Kara 	percpu_down_read(&EXT4_SB(sb)->s_writepages_rwsem);
283529bc9ceaSJan Kara 	ret = ext4_do_writepages(&mpd);
2836*1f1a55f0SJan Kara 	/*
2837*1f1a55f0SJan Kara 	 * For data=journal writeback we could have come across pages marked
2838*1f1a55f0SJan Kara 	 * for delayed dirtying (PageChecked) which were just added to the
2839*1f1a55f0SJan Kara 	 * running transaction. Try once more to get them to stable storage.
2840*1f1a55f0SJan Kara 	 */
2841*1f1a55f0SJan Kara 	if (!ret && mpd.journalled_more_data)
2842*1f1a55f0SJan Kara 		ret = ext4_do_writepages(&mpd);
284329bc9ceaSJan Kara 	percpu_up_read(&EXT4_SB(sb)->s_writepages_rwsem);
284429bc9ceaSJan Kara 
284529bc9ceaSJan Kara 	return ret;
284615648d59SJan Kara }
284715648d59SJan Kara 
284859205c8dSJan Kara int ext4_normal_submit_inode_data_buffers(struct jbd2_inode *jinode)
284959205c8dSJan Kara {
285059205c8dSJan Kara 	struct writeback_control wbc = {
285159205c8dSJan Kara 		.sync_mode = WB_SYNC_ALL,
285259205c8dSJan Kara 		.nr_to_write = LONG_MAX,
285359205c8dSJan Kara 		.range_start = jinode->i_dirty_start,
285459205c8dSJan Kara 		.range_end = jinode->i_dirty_end,
285559205c8dSJan Kara 	};
285659205c8dSJan Kara 	struct mpage_da_data mpd = {
285759205c8dSJan Kara 		.inode = jinode->i_vfs_inode,
285859205c8dSJan Kara 		.wbc = &wbc,
285959205c8dSJan Kara 		.can_map = 0,
286059205c8dSJan Kara 	};
286159205c8dSJan Kara 	return ext4_do_writepages(&mpd);
286259205c8dSJan Kara }
286359205c8dSJan Kara 
28645f0663bbSDan Williams static int ext4_dax_writepages(struct address_space *mapping,
28655f0663bbSDan Williams 			       struct writeback_control *wbc)
28665f0663bbSDan Williams {
28675f0663bbSDan Williams 	int ret;
28685f0663bbSDan Williams 	long nr_to_write = wbc->nr_to_write;
28695f0663bbSDan Williams 	struct inode *inode = mapping->host;
28705f0663bbSDan Williams 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
28715f0663bbSDan Williams 
28725f0663bbSDan Williams 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
28735f0663bbSDan Williams 		return -EIO;
28745f0663bbSDan Williams 
2875bbd55937SEric Biggers 	percpu_down_read(&sbi->s_writepages_rwsem);
28765f0663bbSDan Williams 	trace_ext4_writepages(inode, wbc);
28775f0663bbSDan Williams 
28783f666c56SVivek Goyal 	ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
28795f0663bbSDan Williams 	trace_ext4_writepages_result(inode, wbc, ret,
28805f0663bbSDan Williams 				     nr_to_write - wbc->nr_to_write);
2881bbd55937SEric Biggers 	percpu_up_read(&sbi->s_writepages_rwsem);
28825f0663bbSDan Williams 	return ret;
28835f0663bbSDan Williams }
28845f0663bbSDan Williams 
288579f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
288679f0be8dSAneesh Kumar K.V {
28875c1ff336SEric Whitney 	s64 free_clusters, dirty_clusters;
288879f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
288979f0be8dSAneesh Kumar K.V 
289079f0be8dSAneesh Kumar K.V 	/*
289179f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
289279f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
2893179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
289479f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
289579f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
289679f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
289779f0be8dSAneesh Kumar K.V 	 */
28985c1ff336SEric Whitney 	free_clusters =
28995c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
29005c1ff336SEric Whitney 	dirty_clusters =
29015c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
290200d4e736STheodore Ts'o 	/*
290300d4e736STheodore Ts'o 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
290400d4e736STheodore Ts'o 	 */
29055c1ff336SEric Whitney 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
290610ee27a0SMiao Xie 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
290700d4e736STheodore Ts'o 
29085c1ff336SEric Whitney 	if (2 * free_clusters < 3 * dirty_clusters ||
29095c1ff336SEric Whitney 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
291079f0be8dSAneesh Kumar K.V 		/*
2911c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
2912c8afb446SEric Sandeen 		 * or free blocks is less than watermark
291379f0be8dSAneesh Kumar K.V 		 */
291479f0be8dSAneesh Kumar K.V 		return 1;
291579f0be8dSAneesh Kumar K.V 	}
291679f0be8dSAneesh Kumar K.V 	return 0;
291779f0be8dSAneesh Kumar K.V }
291879f0be8dSAneesh Kumar K.V 
291964769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
29209d6b0cd7SMatthew Wilcox (Oracle) 			       loff_t pos, unsigned len,
292164769240SAlex Tomas 			       struct page **pagep, void **fsdata)
292264769240SAlex Tomas {
292372b8ab9dSEric Sandeen 	int ret, retries = 0;
29240b5a2543SMatthew Wilcox 	struct folio *folio;
292564769240SAlex Tomas 	pgoff_t index;
292664769240SAlex Tomas 	struct inode *inode = mapping->host;
292764769240SAlex Tomas 
29280db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
29290db1ff22STheodore Ts'o 		return -EIO;
29300db1ff22STheodore Ts'o 
293109cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
293279f0be8dSAneesh Kumar K.V 
29336493792dSZhang Yi 	if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
293479f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
293579f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
29369d6b0cd7SMatthew Wilcox (Oracle) 					len, pagep, fsdata);
293779f0be8dSAneesh Kumar K.V 	}
293879f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
29399d6b0cd7SMatthew Wilcox (Oracle) 	trace_ext4_da_write_begin(inode, pos, len);
29409c3569b5STao Ma 
29419c3569b5STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
294236d116e9SMatthew Wilcox (Oracle) 		ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len,
29439c3569b5STao Ma 						      pagep, fsdata);
29449c3569b5STao Ma 		if (ret < 0)
294547564bfbSTheodore Ts'o 			return ret;
294647564bfbSTheodore Ts'o 		if (ret == 1)
294747564bfbSTheodore Ts'o 			return 0;
29489c3569b5STao Ma 	}
29499c3569b5STao Ma 
2950cc883236SZhang Yi retry:
29510b5a2543SMatthew Wilcox 	folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
29520b5a2543SMatthew Wilcox 			mapping_gfp_mask(mapping));
29530b5a2543SMatthew Wilcox 	if (!folio)
295447564bfbSTheodore Ts'o 		return -ENOMEM;
295547564bfbSTheodore Ts'o 
29560b5a2543SMatthew Wilcox 	/* In case writeback began while the folio was unlocked */
29570b5a2543SMatthew Wilcox 	folio_wait_stable(folio);
295864769240SAlex Tomas 
2959643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
296086b38c27SMatthew Wilcox 	ret = ext4_block_write_begin(folio, pos, len, ext4_da_get_block_prep);
29612058f83aSMichael Halcrow #else
29620b5a2543SMatthew Wilcox 	ret = __block_write_begin(&folio->page, pos, len, ext4_da_get_block_prep);
29632058f83aSMichael Halcrow #endif
296464769240SAlex Tomas 	if (ret < 0) {
29650b5a2543SMatthew Wilcox 		folio_unlock(folio);
29660b5a2543SMatthew Wilcox 		folio_put(folio);
2967ae4d5372SAneesh Kumar K.V 		/*
2968ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
2969ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
2970cc883236SZhang Yi 		 * i_size_read because we hold inode lock.
2971ae4d5372SAneesh Kumar K.V 		 */
2972ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
2973b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
297447564bfbSTheodore Ts'o 
297547564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
297647564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
2977cc883236SZhang Yi 			goto retry;
297847564bfbSTheodore Ts'o 		return ret;
297964769240SAlex Tomas 	}
298064769240SAlex Tomas 
29810b5a2543SMatthew Wilcox 	*pagep = &folio->page;
298264769240SAlex Tomas 	return ret;
298364769240SAlex Tomas }
298464769240SAlex Tomas 
2985632eaeabSMingming Cao /*
2986632eaeabSMingming Cao  * Check if we should update i_disksize
2987632eaeabSMingming Cao  * when write to the end of file but not require block allocation
2988632eaeabSMingming Cao  */
2989632eaeabSMingming Cao static int ext4_da_should_update_i_disksize(struct page *page,
2990632eaeabSMingming Cao 					    unsigned long offset)
2991632eaeabSMingming Cao {
2992632eaeabSMingming Cao 	struct buffer_head *bh;
2993632eaeabSMingming Cao 	struct inode *inode = page->mapping->host;
2994632eaeabSMingming Cao 	unsigned int idx;
2995632eaeabSMingming Cao 	int i;
2996632eaeabSMingming Cao 
2997632eaeabSMingming Cao 	bh = page_buffers(page);
2998632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
2999632eaeabSMingming Cao 
3000632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
3001632eaeabSMingming Cao 		bh = bh->b_this_page;
3002632eaeabSMingming Cao 
300329fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3004632eaeabSMingming Cao 		return 0;
3005632eaeabSMingming Cao 	return 1;
3006632eaeabSMingming Cao }
3007632eaeabSMingming Cao 
300864769240SAlex Tomas static int ext4_da_write_end(struct file *file,
300964769240SAlex Tomas 			     struct address_space *mapping,
301064769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
301164769240SAlex Tomas 			     struct page *page, void *fsdata)
301264769240SAlex Tomas {
301364769240SAlex Tomas 	struct inode *inode = mapping->host;
301464769240SAlex Tomas 	loff_t new_i_size;
3015632eaeabSMingming Cao 	unsigned long start, end;
301679f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
301779f0be8dSAneesh Kumar K.V 
301874d553aaSTheodore Ts'o 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
301974d553aaSTheodore Ts'o 		return ext4_write_end(file, mapping, pos,
302079f0be8dSAneesh Kumar K.V 				      len, copied, page, fsdata);
3021632eaeabSMingming Cao 
30229bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
30239c3569b5STao Ma 
30249c3569b5STao Ma 	if (write_mode != CONVERT_INLINE_DATA &&
30259c3569b5STao Ma 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
30269c3569b5STao Ma 	    ext4_has_inline_data(inode))
30276984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
30289c3569b5STao Ma 
302964769240SAlex Tomas 	start = pos & (PAGE_SIZE - 1);
303064769240SAlex Tomas 	end = start + copied - 1;
303164769240SAlex Tomas 
303264769240SAlex Tomas 	/*
30334df031ffSZhang Yi 	 * Since we are holding inode lock, we are sure i_disksize <=
30344df031ffSZhang Yi 	 * i_size. We also know that if i_disksize < i_size, there are
30354df031ffSZhang Yi 	 * delalloc writes pending in the range upto i_size. If the end of
30364df031ffSZhang Yi 	 * the current write is <= i_size, there's no need to touch
30374df031ffSZhang Yi 	 * i_disksize since writeback will push i_disksize upto i_size
30384df031ffSZhang Yi 	 * eventually. If the end of the current write is > i_size and
30394df031ffSZhang Yi 	 * inside an allocated block (ext4_da_should_update_i_disksize()
30403f079114SJan Kara 	 * check), we need to update i_disksize here as certain
30413f079114SJan Kara 	 * ext4_writepages() paths not allocating blocks update i_disksize.
30424df031ffSZhang Yi 	 *
30434df031ffSZhang Yi 	 * Note that we defer inode dirtying to generic_write_end() /
30444df031ffSZhang Yi 	 * ext4_da_write_inline_data_end().
3045d2a17637SMingming Cao 	 */
304664769240SAlex Tomas 	new_i_size = pos + copied;
30476984aef5SZhang Yi 	if (copied && new_i_size > inode->i_size &&
30484df031ffSZhang Yi 	    ext4_da_should_update_i_disksize(page, end))
304964769240SAlex Tomas 		ext4_update_i_disksize(inode, new_i_size);
3050ccd2506bSTheodore Ts'o 
3051cc883236SZhang Yi 	return generic_write_end(file, mapping, pos, len, copied, page, fsdata);
3052ac27a0ecSDave Kleikamp }
3053ac27a0ecSDave Kleikamp 
3054ccd2506bSTheodore Ts'o /*
3055ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
3056ccd2506bSTheodore Ts'o  */
3057ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
3058ccd2506bSTheodore Ts'o {
3059ccd2506bSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
3060ccd2506bSTheodore Ts'o 
306171d4f7d0STheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks)
3062ccd2506bSTheodore Ts'o 		return 0;
3063ccd2506bSTheodore Ts'o 
3064ccd2506bSTheodore Ts'o 	/*
3065ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
3066ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
3067ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
3068ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
3069ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
3070ccd2506bSTheodore Ts'o 	 *
307120970ba6STheodore Ts'o 	 * ext4_writepages() ->
3072ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
3073ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
3074ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
3075ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
3076ccd2506bSTheodore Ts'o 	 *
3077ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
3078ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
3079ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
3080ccd2506bSTheodore Ts'o 	 * doing I/O at all.
3081ccd2506bSTheodore Ts'o 	 *
3082ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
3083380cf090SWu Fengguang 	 * the pages by calling redirty_page_for_writepage() but that
3084ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
3085ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
308625985edcSLucas De Marchi 	 * simplifying them because we wouldn't actually intend to
3087ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
3088ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
3089ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
3090ccd2506bSTheodore Ts'o 	 *
3091ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
3092ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
3093ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
3094ccd2506bSTheodore Ts'o 	 */
3095ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
3096ccd2506bSTheodore Ts'o }
3097ac27a0ecSDave Kleikamp 
3098ac27a0ecSDave Kleikamp /*
3099ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
3100ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
3101ac27a0ecSDave Kleikamp  *
3102ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
3103ac27a0ecSDave Kleikamp  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3104ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
3105ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
3106ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
3107ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
3108ac27a0ecSDave Kleikamp  *
3109ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
3110ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
3111ac27a0ecSDave Kleikamp  */
3112ac27a0ecSDave Kleikamp static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3113ac27a0ecSDave Kleikamp {
3114ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
3115ac27a0ecSDave Kleikamp 	journal_t *journal;
311651ae846cSYe Bin 	sector_t ret = 0;
3117ac27a0ecSDave Kleikamp 	int err;
3118ac27a0ecSDave Kleikamp 
311951ae846cSYe Bin 	inode_lock_shared(inode);
312046c7f254STao Ma 	/*
312146c7f254STao Ma 	 * We can get here for an inline file via the FIBMAP ioctl
312246c7f254STao Ma 	 */
312346c7f254STao Ma 	if (ext4_has_inline_data(inode))
312451ae846cSYe Bin 		goto out;
312546c7f254STao Ma 
3126ac27a0ecSDave Kleikamp 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3127ac27a0ecSDave Kleikamp 			test_opt(inode->i_sb, DELALLOC)) {
3128ac27a0ecSDave Kleikamp 		/*
3129ac27a0ecSDave Kleikamp 		 * With delalloc we want to sync the file
3130ac27a0ecSDave Kleikamp 		 * so that we can make sure we allocate
3131ac27a0ecSDave Kleikamp 		 * blocks for file
3132ac27a0ecSDave Kleikamp 		 */
3133ac27a0ecSDave Kleikamp 		filemap_write_and_wait(mapping);
3134ac27a0ecSDave Kleikamp 	}
3135ac27a0ecSDave Kleikamp 
313619f5fb7aSTheodore Ts'o 	if (EXT4_JOURNAL(inode) &&
313719f5fb7aSTheodore Ts'o 	    ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3138ac27a0ecSDave Kleikamp 		/*
3139ac27a0ecSDave Kleikamp 		 * This is a REALLY heavyweight approach, but the use of
3140ac27a0ecSDave Kleikamp 		 * bmap on dirty files is expected to be extremely rare:
3141ac27a0ecSDave Kleikamp 		 * only if we run lilo or swapon on a freshly made file
3142ac27a0ecSDave Kleikamp 		 * do we expect this to happen.
3143ac27a0ecSDave Kleikamp 		 *
3144ac27a0ecSDave Kleikamp 		 * (bmap requires CAP_SYS_RAWIO so this does not
3145ac27a0ecSDave Kleikamp 		 * represent an unprivileged user DOS attack --- we'd be
3146ac27a0ecSDave Kleikamp 		 * in trouble if mortal users could trigger this path at
3147ac27a0ecSDave Kleikamp 		 * will.)
3148ac27a0ecSDave Kleikamp 		 *
3149ac27a0ecSDave Kleikamp 		 * NB. EXT4_STATE_JDATA is not set on files other than
3150ac27a0ecSDave Kleikamp 		 * regular files.  If somebody wants to bmap a directory
3151ac27a0ecSDave Kleikamp 		 * or symlink and gets confused because the buffer
3152ac27a0ecSDave Kleikamp 		 * hasn't yet been flushed to disk, they deserve
3153ac27a0ecSDave Kleikamp 		 * everything they get.
3154ac27a0ecSDave Kleikamp 		 */
3155ac27a0ecSDave Kleikamp 
315619f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3157ac27a0ecSDave Kleikamp 		journal = EXT4_JOURNAL(inode);
3158ac27a0ecSDave Kleikamp 		jbd2_journal_lock_updates(journal);
315901d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
3160ac27a0ecSDave Kleikamp 		jbd2_journal_unlock_updates(journal);
3161ac27a0ecSDave Kleikamp 
3162ac27a0ecSDave Kleikamp 		if (err)
316351ae846cSYe Bin 			goto out;
3164ac27a0ecSDave Kleikamp 	}
3165ac27a0ecSDave Kleikamp 
316651ae846cSYe Bin 	ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
316751ae846cSYe Bin 
316851ae846cSYe Bin out:
316951ae846cSYe Bin 	inode_unlock_shared(inode);
317051ae846cSYe Bin 	return ret;
3171ac27a0ecSDave Kleikamp }
3172ac27a0ecSDave Kleikamp 
3173fe5ddf6bSMatthew Wilcox (Oracle) static int ext4_read_folio(struct file *file, struct folio *folio)
3174ac27a0ecSDave Kleikamp {
317546c7f254STao Ma 	int ret = -EAGAIN;
3176c0be8e6fSMatthew Wilcox 	struct inode *inode = folio->mapping->host;
317746c7f254STao Ma 
3178c0be8e6fSMatthew Wilcox 	trace_ext4_readpage(&folio->page);
317946c7f254STao Ma 
318046c7f254STao Ma 	if (ext4_has_inline_data(inode))
31813edde93eSMatthew Wilcox 		ret = ext4_readpage_inline(inode, folio);
318246c7f254STao Ma 
318346c7f254STao Ma 	if (ret == -EAGAIN)
3184c0be8e6fSMatthew Wilcox 		return ext4_mpage_readpages(inode, NULL, folio);
318546c7f254STao Ma 
318646c7f254STao Ma 	return ret;
3187ac27a0ecSDave Kleikamp }
3188ac27a0ecSDave Kleikamp 
31896311f91fSMatthew Wilcox (Oracle) static void ext4_readahead(struct readahead_control *rac)
3190ac27a0ecSDave Kleikamp {
31916311f91fSMatthew Wilcox (Oracle) 	struct inode *inode = rac->mapping->host;
319246c7f254STao Ma 
31936311f91fSMatthew Wilcox (Oracle) 	/* If the file has inline data, no need to do readahead. */
319446c7f254STao Ma 	if (ext4_has_inline_data(inode))
31956311f91fSMatthew Wilcox (Oracle) 		return;
319646c7f254STao Ma 
3197a07f624bSMatthew Wilcox (Oracle) 	ext4_mpage_readpages(inode, rac, NULL);
3198ac27a0ecSDave Kleikamp }
3199ac27a0ecSDave Kleikamp 
32007ba13abbSMatthew Wilcox (Oracle) static void ext4_invalidate_folio(struct folio *folio, size_t offset,
32017ba13abbSMatthew Wilcox (Oracle) 				size_t length)
3202ac27a0ecSDave Kleikamp {
3203ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_invalidate_folio(folio, offset, length);
32040562e0baSJiaying Zhang 
32054520fb3cSJan Kara 	/* No journalling happens on data buffers when this function is used */
32067ba13abbSMatthew Wilcox (Oracle) 	WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
32074520fb3cSJan Kara 
32087ba13abbSMatthew Wilcox (Oracle) 	block_invalidate_folio(folio, offset, length);
32094520fb3cSJan Kara }
32104520fb3cSJan Kara 
3211ccd16945SMatthew Wilcox (Oracle) static int __ext4_journalled_invalidate_folio(struct folio *folio,
3212ccd16945SMatthew Wilcox (Oracle) 					    size_t offset, size_t length)
32134520fb3cSJan Kara {
3214ccd16945SMatthew Wilcox (Oracle) 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
32154520fb3cSJan Kara 
3216ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_journalled_invalidate_folio(folio, offset, length);
32174520fb3cSJan Kara 
3218744692dcSJiaying Zhang 	/*
3219ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
3220ac27a0ecSDave Kleikamp 	 */
3221ccd16945SMatthew Wilcox (Oracle) 	if (offset == 0 && length == folio_size(folio))
3222ccd16945SMatthew Wilcox (Oracle) 		folio_clear_checked(folio);
3223ac27a0ecSDave Kleikamp 
3224ccd16945SMatthew Wilcox (Oracle) 	return jbd2_journal_invalidate_folio(journal, folio, offset, length);
322553e87268SJan Kara }
322653e87268SJan Kara 
322753e87268SJan Kara /* Wrapper for aops... */
3228ccd16945SMatthew Wilcox (Oracle) static void ext4_journalled_invalidate_folio(struct folio *folio,
3229ccd16945SMatthew Wilcox (Oracle) 					   size_t offset,
3230ccd16945SMatthew Wilcox (Oracle) 					   size_t length)
323153e87268SJan Kara {
3232ccd16945SMatthew Wilcox (Oracle) 	WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3233ac27a0ecSDave Kleikamp }
3234ac27a0ecSDave Kleikamp 
32353c402f15SMatthew Wilcox (Oracle) static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3236ac27a0ecSDave Kleikamp {
32373c402f15SMatthew Wilcox (Oracle) 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
3238ac27a0ecSDave Kleikamp 
32393c402f15SMatthew Wilcox (Oracle) 	trace_ext4_releasepage(&folio->page);
32400562e0baSJiaying Zhang 
3241e1c36595SJan Kara 	/* Page has dirty journalled data -> cannot release */
32423c402f15SMatthew Wilcox (Oracle) 	if (folio_test_checked(folio))
32433c402f15SMatthew Wilcox (Oracle) 		return false;
32440390131bSFrank Mayhar 	if (journal)
3245c56a6eb0SMatthew Wilcox (Oracle) 		return jbd2_journal_try_to_free_buffers(journal, folio);
32460390131bSFrank Mayhar 	else
324768189fefSMatthew Wilcox (Oracle) 		return try_to_free_buffers(folio);
3248ac27a0ecSDave Kleikamp }
3249ac27a0ecSDave Kleikamp 
3250b8a6176cSJan Kara static bool ext4_inode_datasync_dirty(struct inode *inode)
3251b8a6176cSJan Kara {
3252b8a6176cSJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3253b8a6176cSJan Kara 
3254aa75f4d3SHarshad Shirwadkar 	if (journal) {
3255aa75f4d3SHarshad Shirwadkar 		if (jbd2_transaction_committed(journal,
3256aa75f4d3SHarshad Shirwadkar 			EXT4_I(inode)->i_datasync_tid))
3257d0520df7SAndrea Righi 			return false;
3258d0520df7SAndrea Righi 		if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
32591ceecb53SHarshad Shirwadkar 			return !list_empty(&EXT4_I(inode)->i_fc_list);
3260d0520df7SAndrea Righi 		return true;
3261aa75f4d3SHarshad Shirwadkar 	}
3262aa75f4d3SHarshad Shirwadkar 
3263b8a6176cSJan Kara 	/* Any metadata buffers to write? */
3264b8a6176cSJan Kara 	if (!list_empty(&inode->i_mapping->private_list))
3265b8a6176cSJan Kara 		return true;
3266b8a6176cSJan Kara 	return inode->i_state & I_DIRTY_DATASYNC;
3267b8a6176cSJan Kara }
3268b8a6176cSJan Kara 
3269c8fdfe29SMatthew Bobrowski static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3270c8fdfe29SMatthew Bobrowski 			   struct ext4_map_blocks *map, loff_t offset,
3271de205114SChristoph Hellwig 			   loff_t length, unsigned int flags)
3272364443cbSJan Kara {
3273c8fdfe29SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3274c8fdfe29SMatthew Bobrowski 
3275c8fdfe29SMatthew Bobrowski 	/*
3276c8fdfe29SMatthew Bobrowski 	 * Writes that span EOF might trigger an I/O size update on completion,
3277c8fdfe29SMatthew Bobrowski 	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3278c8fdfe29SMatthew Bobrowski 	 * there is no other metadata changes being made or are pending.
3279c8fdfe29SMatthew Bobrowski 	 */
3280c8fdfe29SMatthew Bobrowski 	iomap->flags = 0;
3281c8fdfe29SMatthew Bobrowski 	if (ext4_inode_datasync_dirty(inode) ||
3282c8fdfe29SMatthew Bobrowski 	    offset + length > i_size_read(inode))
3283c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_DIRTY;
3284c8fdfe29SMatthew Bobrowski 
3285c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_NEW)
3286c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_NEW;
3287c8fdfe29SMatthew Bobrowski 
3288de205114SChristoph Hellwig 	if (flags & IOMAP_DAX)
3289c8fdfe29SMatthew Bobrowski 		iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3290de205114SChristoph Hellwig 	else
3291de205114SChristoph Hellwig 		iomap->bdev = inode->i_sb->s_bdev;
3292c8fdfe29SMatthew Bobrowski 	iomap->offset = (u64) map->m_lblk << blkbits;
3293c8fdfe29SMatthew Bobrowski 	iomap->length = (u64) map->m_len << blkbits;
3294c8fdfe29SMatthew Bobrowski 
32956386722aSRitesh Harjani 	if ((map->m_flags & EXT4_MAP_MAPPED) &&
32966386722aSRitesh Harjani 	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
32976386722aSRitesh Harjani 		iomap->flags |= IOMAP_F_MERGED;
32986386722aSRitesh Harjani 
3299c8fdfe29SMatthew Bobrowski 	/*
3300c8fdfe29SMatthew Bobrowski 	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3301c8fdfe29SMatthew Bobrowski 	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3302c8fdfe29SMatthew Bobrowski 	 * set. In order for any allocated unwritten extents to be converted
3303c8fdfe29SMatthew Bobrowski 	 * into written extents correctly within the ->end_io() handler, we
3304c8fdfe29SMatthew Bobrowski 	 * need to ensure that the iomap->type is set appropriately. Hence, the
3305c8fdfe29SMatthew Bobrowski 	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3306c8fdfe29SMatthew Bobrowski 	 * been set first.
3307c8fdfe29SMatthew Bobrowski 	 */
3308c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3309c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_UNWRITTEN;
3310c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3311de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3312de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3313c8fdfe29SMatthew Bobrowski 	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3314c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_MAPPED;
3315c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3316de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3317de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3318c8fdfe29SMatthew Bobrowski 	} else {
3319c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_HOLE;
3320c8fdfe29SMatthew Bobrowski 		iomap->addr = IOMAP_NULL_ADDR;
3321c8fdfe29SMatthew Bobrowski 	}
3322c8fdfe29SMatthew Bobrowski }
3323c8fdfe29SMatthew Bobrowski 
3324f063db5eSMatthew Bobrowski static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3325f063db5eSMatthew Bobrowski 			    unsigned int flags)
3326f063db5eSMatthew Bobrowski {
3327f063db5eSMatthew Bobrowski 	handle_t *handle;
3328378f32baSMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3329378f32baSMatthew Bobrowski 	int ret, dio_credits, m_flags = 0, retries = 0;
3330f063db5eSMatthew Bobrowski 
3331f063db5eSMatthew Bobrowski 	/*
3332f063db5eSMatthew Bobrowski 	 * Trim the mapping request to the maximum value that we can map at
3333f063db5eSMatthew Bobrowski 	 * once for direct I/O.
3334f063db5eSMatthew Bobrowski 	 */
3335f063db5eSMatthew Bobrowski 	if (map->m_len > DIO_MAX_BLOCKS)
3336f063db5eSMatthew Bobrowski 		map->m_len = DIO_MAX_BLOCKS;
3337f063db5eSMatthew Bobrowski 	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3338f063db5eSMatthew Bobrowski 
3339f063db5eSMatthew Bobrowski retry:
3340f063db5eSMatthew Bobrowski 	/*
3341f063db5eSMatthew Bobrowski 	 * Either we allocate blocks and then don't get an unwritten extent, so
3342f063db5eSMatthew Bobrowski 	 * in that case we have reserved enough credits. Or, the blocks are
3343f063db5eSMatthew Bobrowski 	 * already allocated and unwritten. In that case, the extent conversion
3344f063db5eSMatthew Bobrowski 	 * fits into the credits as well.
3345f063db5eSMatthew Bobrowski 	 */
3346f063db5eSMatthew Bobrowski 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3347f063db5eSMatthew Bobrowski 	if (IS_ERR(handle))
3348f063db5eSMatthew Bobrowski 		return PTR_ERR(handle);
3349f063db5eSMatthew Bobrowski 
3350378f32baSMatthew Bobrowski 	/*
3351378f32baSMatthew Bobrowski 	 * DAX and direct I/O are the only two operations that are currently
3352378f32baSMatthew Bobrowski 	 * supported with IOMAP_WRITE.
3353378f32baSMatthew Bobrowski 	 */
3354952da063SChristoph Hellwig 	WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3355952da063SChristoph Hellwig 	if (flags & IOMAP_DAX)
3356378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3357378f32baSMatthew Bobrowski 	/*
3358378f32baSMatthew Bobrowski 	 * We use i_size instead of i_disksize here because delalloc writeback
3359378f32baSMatthew Bobrowski 	 * can complete at any point during the I/O and subsequently push the
3360378f32baSMatthew Bobrowski 	 * i_disksize out to i_size. This could be beyond where direct I/O is
3361378f32baSMatthew Bobrowski 	 * happening and thus expose allocated blocks to direct I/O reads.
3362378f32baSMatthew Bobrowski 	 */
3363d0b040f5SJan Kara 	else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3364378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE;
3365378f32baSMatthew Bobrowski 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3366378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3367378f32baSMatthew Bobrowski 
3368378f32baSMatthew Bobrowski 	ret = ext4_map_blocks(handle, inode, map, m_flags);
3369378f32baSMatthew Bobrowski 
3370378f32baSMatthew Bobrowski 	/*
3371378f32baSMatthew Bobrowski 	 * We cannot fill holes in indirect tree based inodes as that could
3372378f32baSMatthew Bobrowski 	 * expose stale data in the case of a crash. Use the magic error code
3373378f32baSMatthew Bobrowski 	 * to fallback to buffered I/O.
3374378f32baSMatthew Bobrowski 	 */
3375378f32baSMatthew Bobrowski 	if (!m_flags && !ret)
3376378f32baSMatthew Bobrowski 		ret = -ENOTBLK;
3377f063db5eSMatthew Bobrowski 
3378f063db5eSMatthew Bobrowski 	ext4_journal_stop(handle);
3379f063db5eSMatthew Bobrowski 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3380f063db5eSMatthew Bobrowski 		goto retry;
3381f063db5eSMatthew Bobrowski 
3382f063db5eSMatthew Bobrowski 	return ret;
3383f063db5eSMatthew Bobrowski }
3384f063db5eSMatthew Bobrowski 
3385f063db5eSMatthew Bobrowski 
3386364443cbSJan Kara static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3387c039b997SGoldwyn Rodrigues 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3388364443cbSJan Kara {
3389364443cbSJan Kara 	int ret;
339009edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
339109edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3392364443cbSJan Kara 
3393bcd8e91fSTheodore Ts'o 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3394bcd8e91fSTheodore Ts'o 		return -EINVAL;
33957046ae35SAndreas Gruenbacher 
3396364443cbSJan Kara 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3397364443cbSJan Kara 		return -ERANGE;
3398364443cbSJan Kara 
339909edf4d3SMatthew Bobrowski 	/*
340009edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical blocks respectively.
340109edf4d3SMatthew Bobrowski 	 */
340209edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
340309edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
340409edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3405364443cbSJan Kara 
34069faac62dSRitesh Harjani 	if (flags & IOMAP_WRITE) {
34079faac62dSRitesh Harjani 		/*
34089faac62dSRitesh Harjani 		 * We check here if the blocks are already allocated, then we
34099faac62dSRitesh Harjani 		 * don't need to start a journal txn and we can directly return
34109faac62dSRitesh Harjani 		 * the mapping information. This could boost performance
34119faac62dSRitesh Harjani 		 * especially in multi-threaded overwrite requests.
34129faac62dSRitesh Harjani 		 */
34139faac62dSRitesh Harjani 		if (offset + length <= i_size_read(inode)) {
3414545052e9SChristoph Hellwig 			ret = ext4_map_blocks(NULL, inode, &map, 0);
34159faac62dSRitesh Harjani 			if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
34169faac62dSRitesh Harjani 				goto out;
34179faac62dSRitesh Harjani 		}
34189faac62dSRitesh Harjani 		ret = ext4_iomap_alloc(inode, &map, flags);
34199faac62dSRitesh Harjani 	} else {
34209faac62dSRitesh Harjani 		ret = ext4_map_blocks(NULL, inode, &map, 0);
34219faac62dSRitesh Harjani 	}
3422f063db5eSMatthew Bobrowski 
3423545052e9SChristoph Hellwig 	if (ret < 0)
3424545052e9SChristoph Hellwig 		return ret;
34259faac62dSRitesh Harjani out:
342638ea50daSEric Biggers 	/*
342738ea50daSEric Biggers 	 * When inline encryption is enabled, sometimes I/O to an encrypted file
342838ea50daSEric Biggers 	 * has to be broken up to guarantee DUN contiguity.  Handle this by
342938ea50daSEric Biggers 	 * limiting the length of the mapping returned.
343038ea50daSEric Biggers 	 */
343138ea50daSEric Biggers 	map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
343238ea50daSEric Biggers 
3433de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3434545052e9SChristoph Hellwig 
3435364443cbSJan Kara 	return 0;
3436364443cbSJan Kara }
3437364443cbSJan Kara 
34388cd115bdSJan Kara static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
34398cd115bdSJan Kara 		loff_t length, unsigned flags, struct iomap *iomap,
34408cd115bdSJan Kara 		struct iomap *srcmap)
34418cd115bdSJan Kara {
34428cd115bdSJan Kara 	int ret;
34438cd115bdSJan Kara 
34448cd115bdSJan Kara 	/*
34458cd115bdSJan Kara 	 * Even for writes we don't need to allocate blocks, so just pretend
34468cd115bdSJan Kara 	 * we are reading to save overhead of starting a transaction.
34478cd115bdSJan Kara 	 */
34488cd115bdSJan Kara 	flags &= ~IOMAP_WRITE;
34498cd115bdSJan Kara 	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
34508cd115bdSJan Kara 	WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
34518cd115bdSJan Kara 	return ret;
34528cd115bdSJan Kara }
34538cd115bdSJan Kara 
3454776722e8SJan Kara static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3455776722e8SJan Kara 			  ssize_t written, unsigned flags, struct iomap *iomap)
3456776722e8SJan Kara {
3457378f32baSMatthew Bobrowski 	/*
3458378f32baSMatthew Bobrowski 	 * Check to see whether an error occurred while writing out the data to
3459378f32baSMatthew Bobrowski 	 * the allocated blocks. If so, return the magic error code so that we
3460378f32baSMatthew Bobrowski 	 * fallback to buffered I/O and attempt to complete the remainder of
3461378f32baSMatthew Bobrowski 	 * the I/O. Any blocks that may have been allocated in preparation for
3462378f32baSMatthew Bobrowski 	 * the direct I/O will be reused during buffered I/O.
3463378f32baSMatthew Bobrowski 	 */
3464378f32baSMatthew Bobrowski 	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3465378f32baSMatthew Bobrowski 		return -ENOTBLK;
3466378f32baSMatthew Bobrowski 
3467776722e8SJan Kara 	return 0;
3468776722e8SJan Kara }
3469776722e8SJan Kara 
34708ff6daa1SChristoph Hellwig const struct iomap_ops ext4_iomap_ops = {
3471364443cbSJan Kara 	.iomap_begin		= ext4_iomap_begin,
3472776722e8SJan Kara 	.iomap_end		= ext4_iomap_end,
3473364443cbSJan Kara };
3474364443cbSJan Kara 
34758cd115bdSJan Kara const struct iomap_ops ext4_iomap_overwrite_ops = {
34768cd115bdSJan Kara 	.iomap_begin		= ext4_iomap_overwrite_begin,
34778cd115bdSJan Kara 	.iomap_end		= ext4_iomap_end,
34788cd115bdSJan Kara };
34798cd115bdSJan Kara 
348009edf4d3SMatthew Bobrowski static bool ext4_iomap_is_delalloc(struct inode *inode,
348109edf4d3SMatthew Bobrowski 				   struct ext4_map_blocks *map)
348209edf4d3SMatthew Bobrowski {
348309edf4d3SMatthew Bobrowski 	struct extent_status es;
348409edf4d3SMatthew Bobrowski 	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
348509edf4d3SMatthew Bobrowski 
348609edf4d3SMatthew Bobrowski 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
348709edf4d3SMatthew Bobrowski 				  map->m_lblk, end, &es);
348809edf4d3SMatthew Bobrowski 
348909edf4d3SMatthew Bobrowski 	if (!es.es_len || es.es_lblk > end)
349009edf4d3SMatthew Bobrowski 		return false;
349109edf4d3SMatthew Bobrowski 
349209edf4d3SMatthew Bobrowski 	if (es.es_lblk > map->m_lblk) {
349309edf4d3SMatthew Bobrowski 		map->m_len = es.es_lblk - map->m_lblk;
349409edf4d3SMatthew Bobrowski 		return false;
349509edf4d3SMatthew Bobrowski 	}
349609edf4d3SMatthew Bobrowski 
349709edf4d3SMatthew Bobrowski 	offset = map->m_lblk - es.es_lblk;
349809edf4d3SMatthew Bobrowski 	map->m_len = es.es_len - offset;
349909edf4d3SMatthew Bobrowski 
350009edf4d3SMatthew Bobrowski 	return true;
350109edf4d3SMatthew Bobrowski }
350209edf4d3SMatthew Bobrowski 
350309edf4d3SMatthew Bobrowski static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
350409edf4d3SMatthew Bobrowski 				   loff_t length, unsigned int flags,
350509edf4d3SMatthew Bobrowski 				   struct iomap *iomap, struct iomap *srcmap)
350609edf4d3SMatthew Bobrowski {
350709edf4d3SMatthew Bobrowski 	int ret;
350809edf4d3SMatthew Bobrowski 	bool delalloc = false;
350909edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
351009edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
351109edf4d3SMatthew Bobrowski 
351209edf4d3SMatthew Bobrowski 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
351309edf4d3SMatthew Bobrowski 		return -EINVAL;
351409edf4d3SMatthew Bobrowski 
35157cb476f8SJan Kara 	if (ext4_has_inline_data(inode)) {
35167cb476f8SJan Kara 		ret = ext4_inline_data_iomap(inode, iomap);
3517ba5843f5SJan Kara 		if (ret != -EAGAIN) {
3518ed923b57SMatthew Wilcox 			if (ret == 0 && offset >= iomap->length)
3519ba5843f5SJan Kara 				ret = -ENOENT;
3520ba5843f5SJan Kara 			return ret;
3521ba5843f5SJan Kara 		}
3522ba5843f5SJan Kara 	}
352312735f88SJan Kara 
352409edf4d3SMatthew Bobrowski 	/*
352509edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical block respectively.
352609edf4d3SMatthew Bobrowski 	 */
352709edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
352809edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
352909edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
353012735f88SJan Kara 
3531b2c57642SRitesh Harjani 	/*
3532b2c57642SRitesh Harjani 	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3533b2c57642SRitesh Harjani 	 * So handle it here itself instead of querying ext4_map_blocks().
3534b2c57642SRitesh Harjani 	 * Since ext4_map_blocks() will warn about it and will return
3535b2c57642SRitesh Harjani 	 * -EIO error.
3536b2c57642SRitesh Harjani 	 */
3537b2c57642SRitesh Harjani 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3538b2c57642SRitesh Harjani 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3539b2c57642SRitesh Harjani 
3540b2c57642SRitesh Harjani 		if (offset >= sbi->s_bitmap_maxbytes) {
3541b2c57642SRitesh Harjani 			map.m_flags = 0;
3542b2c57642SRitesh Harjani 			goto set_iomap;
3543b2c57642SRitesh Harjani 		}
3544b2c57642SRitesh Harjani 	}
3545b2c57642SRitesh Harjani 
354612735f88SJan Kara 	ret = ext4_map_blocks(NULL, inode, &map, 0);
3547ba5843f5SJan Kara 	if (ret < 0)
3548ba5843f5SJan Kara 		return ret;
3549914f82a3SJan Kara 	if (ret == 0)
355009edf4d3SMatthew Bobrowski 		delalloc = ext4_iomap_is_delalloc(inode, &map);
355109edf4d3SMatthew Bobrowski 
3552b2c57642SRitesh Harjani set_iomap:
3553de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
355409edf4d3SMatthew Bobrowski 	if (delalloc && iomap->type == IOMAP_HOLE)
355509edf4d3SMatthew Bobrowski 		iomap->type = IOMAP_DELALLOC;
355609edf4d3SMatthew Bobrowski 
355709edf4d3SMatthew Bobrowski 	return 0;
3558914f82a3SJan Kara }
3559914f82a3SJan Kara 
356009edf4d3SMatthew Bobrowski const struct iomap_ops ext4_iomap_report_ops = {
356109edf4d3SMatthew Bobrowski 	.iomap_begin = ext4_iomap_begin_report,
356209edf4d3SMatthew Bobrowski };
35634c0425ffSMingming Cao 
3564ac27a0ecSDave Kleikamp /*
35653f5d3063SJan Kara  * For data=journal mode, folio should be marked dirty only when it was
35663f5d3063SJan Kara  * writeably mapped. When that happens, it was already attached to the
35673f5d3063SJan Kara  * transaction and marked as jbddirty (we take care of this in
35683f5d3063SJan Kara  * ext4_page_mkwrite()). On transaction commit, we writeprotect page mappings
35693f5d3063SJan Kara  * so we should have nothing to do here, except for the case when someone
35703f5d3063SJan Kara  * had the page pinned and dirtied the page through this pin (e.g. by doing
35713f5d3063SJan Kara  * direct IO to it). In that case we'd need to attach buffers here to the
35723f5d3063SJan Kara  * transaction but we cannot due to lock ordering.  We cannot just dirty the
35733f5d3063SJan Kara  * folio and leave attached buffers clean, because the buffers' dirty state is
35743f5d3063SJan Kara  * "definitive".  We cannot just set the buffers dirty or jbddirty because all
35753f5d3063SJan Kara  * the journalling code will explode.  So what we do is to mark the folio
35763f5d3063SJan Kara  * "pending dirty" and next time ext4_writepages() is called, attach buffers
35773f5d3063SJan Kara  * to the transaction appropriately.
3578ac27a0ecSDave Kleikamp  */
3579187c82cbSMatthew Wilcox (Oracle) static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3580187c82cbSMatthew Wilcox (Oracle) 		struct folio *folio)
3581ac27a0ecSDave Kleikamp {
35820f252336SMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
35833f5d3063SJan Kara 	if (folio_maybe_dma_pinned(folio))
3584187c82cbSMatthew Wilcox (Oracle) 		folio_set_checked(folio);
3585187c82cbSMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
3586ac27a0ecSDave Kleikamp }
3587ac27a0ecSDave Kleikamp 
3588e621900aSMatthew Wilcox (Oracle) static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
35896dcc693bSJan Kara {
3590e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3591e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
3592e621900aSMatthew Wilcox (Oracle) 	return block_dirty_folio(mapping, folio);
35936dcc693bSJan Kara }
35946dcc693bSJan Kara 
35950e6895baSRitesh Harjani static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
35960e6895baSRitesh Harjani 				    struct file *file, sector_t *span)
35970e6895baSRitesh Harjani {
35980e6895baSRitesh Harjani 	return iomap_swapfile_activate(sis, file, span,
35990e6895baSRitesh Harjani 				       &ext4_iomap_report_ops);
36000e6895baSRitesh Harjani }
36010e6895baSRitesh Harjani 
360274d553aaSTheodore Ts'o static const struct address_space_operations ext4_aops = {
3603fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
36046311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
360520970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3606bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
360774d553aaSTheodore Ts'o 	.write_end		= ext4_write_end,
3608e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
3609617ba13bSMingming Cao 	.bmap			= ext4_bmap,
36107ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
36113c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3612378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
361367235182SMatthew Wilcox (Oracle) 	.migrate_folio		= buffer_migrate_folio,
36148ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3615aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36160e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3617ac27a0ecSDave Kleikamp };
3618ac27a0ecSDave Kleikamp 
3619617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
3620fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
36216311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
362220970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3623bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
3624bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
3625187c82cbSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_journalled_dirty_folio,
3626617ba13bSMingming Cao 	.bmap			= ext4_bmap,
3627ccd16945SMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_journalled_invalidate_folio,
36283c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3629378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
3630dae99960SJan Kara 	.migrate_folio		= buffer_migrate_folio_norefs,
36318ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3632aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36330e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3634ac27a0ecSDave Kleikamp };
3635ac27a0ecSDave Kleikamp 
363664769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
3637fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
36386311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
363920970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
364064769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
364164769240SAlex Tomas 	.write_end		= ext4_da_write_end,
3642e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
364364769240SAlex Tomas 	.bmap			= ext4_bmap,
36447ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
36453c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3646378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
364767235182SMatthew Wilcox (Oracle) 	.migrate_folio		= buffer_migrate_folio,
36488ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3649aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36500e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
365164769240SAlex Tomas };
365264769240SAlex Tomas 
36535f0663bbSDan Williams static const struct address_space_operations ext4_dax_aops = {
36545f0663bbSDan Williams 	.writepages		= ext4_dax_writepages,
36555f0663bbSDan Williams 	.direct_IO		= noop_direct_IO,
365646de8b97SMatthew Wilcox (Oracle) 	.dirty_folio		= noop_dirty_folio,
365794dbb631SToshi Kani 	.bmap			= ext4_bmap,
36580e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
36595f0663bbSDan Williams };
36605f0663bbSDan Williams 
3661617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
3662ac27a0ecSDave Kleikamp {
36633d2b1582SLukas Czerner 	switch (ext4_inode_journal_mode(inode)) {
36643d2b1582SLukas Czerner 	case EXT4_INODE_ORDERED_DATA_MODE:
36653d2b1582SLukas Czerner 	case EXT4_INODE_WRITEBACK_DATA_MODE:
36663d2b1582SLukas Czerner 		break;
36673d2b1582SLukas Czerner 	case EXT4_INODE_JOURNAL_DATA_MODE:
3668617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
366974d553aaSTheodore Ts'o 		return;
36703d2b1582SLukas Czerner 	default:
36713d2b1582SLukas Czerner 		BUG();
36723d2b1582SLukas Czerner 	}
36735f0663bbSDan Williams 	if (IS_DAX(inode))
36745f0663bbSDan Williams 		inode->i_mapping->a_ops = &ext4_dax_aops;
36755f0663bbSDan Williams 	else if (test_opt(inode->i_sb, DELALLOC))
367674d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_da_aops;
367774d553aaSTheodore Ts'o 	else
367874d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_aops;
3679ac27a0ecSDave Kleikamp }
3680ac27a0ecSDave Kleikamp 
3681923ae0ffSRoss Zwisler static int __ext4_block_zero_page_range(handle_t *handle,
3682d863dc36SLukas Czerner 		struct address_space *mapping, loff_t from, loff_t length)
3683d863dc36SLukas Czerner {
368409cbfeafSKirill A. Shutemov 	ext4_fsblk_t index = from >> PAGE_SHIFT;
368509cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3686923ae0ffSRoss Zwisler 	unsigned blocksize, pos;
3687d863dc36SLukas Czerner 	ext4_lblk_t iblock;
3688d863dc36SLukas Czerner 	struct inode *inode = mapping->host;
3689d863dc36SLukas Czerner 	struct buffer_head *bh;
36909d3973deSMatthew Wilcox 	struct folio *folio;
3691d863dc36SLukas Czerner 	int err = 0;
3692d863dc36SLukas Czerner 
36939d3973deSMatthew Wilcox 	folio = __filemap_get_folio(mapping, from >> PAGE_SHIFT,
36949d3973deSMatthew Wilcox 				    FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
3695c62d2555SMichal Hocko 				    mapping_gfp_constraint(mapping, ~__GFP_FS));
36969d3973deSMatthew Wilcox 	if (!folio)
3697d863dc36SLukas Czerner 		return -ENOMEM;
3698d863dc36SLukas Czerner 
3699d863dc36SLukas Czerner 	blocksize = inode->i_sb->s_blocksize;
3700d863dc36SLukas Czerner 
370109cbfeafSKirill A. Shutemov 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3702d863dc36SLukas Czerner 
37039d3973deSMatthew Wilcox 	bh = folio_buffers(folio);
37049d3973deSMatthew Wilcox 	if (!bh) {
37059d3973deSMatthew Wilcox 		create_empty_buffers(&folio->page, blocksize, 0);
37069d3973deSMatthew Wilcox 		bh = folio_buffers(folio);
37079d3973deSMatthew Wilcox 	}
3708d863dc36SLukas Czerner 
3709d863dc36SLukas Czerner 	/* Find the buffer that contains "offset" */
3710d863dc36SLukas Czerner 	pos = blocksize;
3711d863dc36SLukas Czerner 	while (offset >= pos) {
3712d863dc36SLukas Czerner 		bh = bh->b_this_page;
3713d863dc36SLukas Czerner 		iblock++;
3714d863dc36SLukas Czerner 		pos += blocksize;
3715d863dc36SLukas Czerner 	}
3716d863dc36SLukas Czerner 	if (buffer_freed(bh)) {
3717d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "freed: skip");
3718d863dc36SLukas Czerner 		goto unlock;
3719d863dc36SLukas Czerner 	}
3720d863dc36SLukas Czerner 	if (!buffer_mapped(bh)) {
3721d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "unmapped");
3722d863dc36SLukas Czerner 		ext4_get_block(inode, iblock, bh, 0);
3723d863dc36SLukas Czerner 		/* unmapped? It's a hole - nothing to do */
3724d863dc36SLukas Czerner 		if (!buffer_mapped(bh)) {
3725d863dc36SLukas Czerner 			BUFFER_TRACE(bh, "still unmapped");
3726d863dc36SLukas Czerner 			goto unlock;
3727d863dc36SLukas Czerner 		}
3728d863dc36SLukas Czerner 	}
3729d863dc36SLukas Czerner 
3730d863dc36SLukas Czerner 	/* Ok, it's mapped. Make sure it's up-to-date */
37319d3973deSMatthew Wilcox 	if (folio_test_uptodate(folio))
3732d863dc36SLukas Czerner 		set_buffer_uptodate(bh);
3733d863dc36SLukas Czerner 
3734d863dc36SLukas Czerner 	if (!buffer_uptodate(bh)) {
37352d069c08Szhangyi (F) 		err = ext4_read_bh_lock(bh, 0, true);
37362d069c08Szhangyi (F) 		if (err)
3737d863dc36SLukas Czerner 			goto unlock;
37384f74d15fSEric Biggers 		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3739c9c7429cSMichael Halcrow 			/* We expect the key to be set. */
3740a7550b30SJaegeuk Kim 			BUG_ON(!fscrypt_has_encryption_key(inode));
37419d3973deSMatthew Wilcox 			err = fscrypt_decrypt_pagecache_blocks(folio,
374251e4e315SEric Biggers 							       blocksize,
3743834f1565SEric Biggers 							       bh_offset(bh));
3744834f1565SEric Biggers 			if (err) {
3745834f1565SEric Biggers 				clear_buffer_uptodate(bh);
3746834f1565SEric Biggers 				goto unlock;
3747834f1565SEric Biggers 			}
3748c9c7429cSMichael Halcrow 		}
3749d863dc36SLukas Czerner 	}
3750d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3751d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "get write access");
3752188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
3753188c299eSJan Kara 						    EXT4_JTR_NONE);
3754d863dc36SLukas Czerner 		if (err)
3755d863dc36SLukas Czerner 			goto unlock;
3756d863dc36SLukas Czerner 	}
37579d3973deSMatthew Wilcox 	folio_zero_range(folio, offset, length);
3758d863dc36SLukas Czerner 	BUFFER_TRACE(bh, "zeroed end of block");
3759d863dc36SLukas Czerner 
3760d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3761d84c9ebdSJan Kara 		err = ext4_dirty_journalled_data(handle, bh);
37620713ed0cSLukas Czerner 	} else {
3763353eefd3Sjon ernst 		err = 0;
3764d863dc36SLukas Czerner 		mark_buffer_dirty(bh);
37653957ef53SJan Kara 		if (ext4_should_order_data(inode))
376673131fbbSRoss Zwisler 			err = ext4_jbd2_inode_add_write(handle, inode, from,
376773131fbbSRoss Zwisler 					length);
37680713ed0cSLukas Czerner 	}
3769d863dc36SLukas Czerner 
3770d863dc36SLukas Czerner unlock:
37719d3973deSMatthew Wilcox 	folio_unlock(folio);
37729d3973deSMatthew Wilcox 	folio_put(folio);
3773d863dc36SLukas Czerner 	return err;
3774d863dc36SLukas Czerner }
3775d863dc36SLukas Czerner 
377694350ab5SMatthew Wilcox /*
3777923ae0ffSRoss Zwisler  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3778923ae0ffSRoss Zwisler  * starting from file offset 'from'.  The range to be zero'd must
3779923ae0ffSRoss Zwisler  * be contained with in one block.  If the specified range exceeds
3780923ae0ffSRoss Zwisler  * the end of the block it will be shortened to end of the block
37813088e5a5SBhaskar Chowdhury  * that corresponds to 'from'
3782923ae0ffSRoss Zwisler  */
3783923ae0ffSRoss Zwisler static int ext4_block_zero_page_range(handle_t *handle,
3784923ae0ffSRoss Zwisler 		struct address_space *mapping, loff_t from, loff_t length)
3785923ae0ffSRoss Zwisler {
3786923ae0ffSRoss Zwisler 	struct inode *inode = mapping->host;
378709cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3788923ae0ffSRoss Zwisler 	unsigned blocksize = inode->i_sb->s_blocksize;
3789923ae0ffSRoss Zwisler 	unsigned max = blocksize - (offset & (blocksize - 1));
3790923ae0ffSRoss Zwisler 
3791923ae0ffSRoss Zwisler 	/*
3792923ae0ffSRoss Zwisler 	 * correct length if it does not fall between
3793923ae0ffSRoss Zwisler 	 * 'from' and the end of the block
3794923ae0ffSRoss Zwisler 	 */
3795923ae0ffSRoss Zwisler 	if (length > max || length < 0)
3796923ae0ffSRoss Zwisler 		length = max;
3797923ae0ffSRoss Zwisler 
379847e69351SJan Kara 	if (IS_DAX(inode)) {
3799c6f40468SChristoph Hellwig 		return dax_zero_range(inode, from, length, NULL,
380047e69351SJan Kara 				      &ext4_iomap_ops);
380147e69351SJan Kara 	}
3802923ae0ffSRoss Zwisler 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3803923ae0ffSRoss Zwisler }
3804923ae0ffSRoss Zwisler 
3805923ae0ffSRoss Zwisler /*
380694350ab5SMatthew Wilcox  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
380794350ab5SMatthew Wilcox  * up to the end of the block which corresponds to `from'.
380894350ab5SMatthew Wilcox  * This required during truncate. We need to physically zero the tail end
380994350ab5SMatthew Wilcox  * of that block so it doesn't yield old data if the file is later grown.
381094350ab5SMatthew Wilcox  */
3811c197855eSStephen Hemminger static int ext4_block_truncate_page(handle_t *handle,
381294350ab5SMatthew Wilcox 		struct address_space *mapping, loff_t from)
381394350ab5SMatthew Wilcox {
381409cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
381594350ab5SMatthew Wilcox 	unsigned length;
381694350ab5SMatthew Wilcox 	unsigned blocksize;
381794350ab5SMatthew Wilcox 	struct inode *inode = mapping->host;
381894350ab5SMatthew Wilcox 
38190d06863fSTheodore Ts'o 	/* If we are processing an encrypted inode during orphan list handling */
3820592ddec7SChandan Rajendra 	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
38210d06863fSTheodore Ts'o 		return 0;
38220d06863fSTheodore Ts'o 
382394350ab5SMatthew Wilcox 	blocksize = inode->i_sb->s_blocksize;
382494350ab5SMatthew Wilcox 	length = blocksize - (offset & (blocksize - 1));
382594350ab5SMatthew Wilcox 
382694350ab5SMatthew Wilcox 	return ext4_block_zero_page_range(handle, mapping, from, length);
382794350ab5SMatthew Wilcox }
382894350ab5SMatthew Wilcox 
3829a87dd18cSLukas Czerner int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3830a87dd18cSLukas Czerner 			     loff_t lstart, loff_t length)
3831a87dd18cSLukas Czerner {
3832a87dd18cSLukas Czerner 	struct super_block *sb = inode->i_sb;
3833a87dd18cSLukas Czerner 	struct address_space *mapping = inode->i_mapping;
3834e1be3a92SLukas Czerner 	unsigned partial_start, partial_end;
3835a87dd18cSLukas Czerner 	ext4_fsblk_t start, end;
3836a87dd18cSLukas Czerner 	loff_t byte_end = (lstart + length - 1);
3837a87dd18cSLukas Czerner 	int err = 0;
3838a87dd18cSLukas Czerner 
3839e1be3a92SLukas Czerner 	partial_start = lstart & (sb->s_blocksize - 1);
3840e1be3a92SLukas Czerner 	partial_end = byte_end & (sb->s_blocksize - 1);
3841e1be3a92SLukas Czerner 
3842a87dd18cSLukas Czerner 	start = lstart >> sb->s_blocksize_bits;
3843a87dd18cSLukas Czerner 	end = byte_end >> sb->s_blocksize_bits;
3844a87dd18cSLukas Czerner 
3845a87dd18cSLukas Czerner 	/* Handle partial zero within the single block */
3846e1be3a92SLukas Czerner 	if (start == end &&
3847e1be3a92SLukas Czerner 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3848a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3849a87dd18cSLukas Czerner 						 lstart, length);
3850a87dd18cSLukas Czerner 		return err;
3851a87dd18cSLukas Czerner 	}
3852a87dd18cSLukas Czerner 	/* Handle partial zero out on the start of the range */
3853e1be3a92SLukas Czerner 	if (partial_start) {
3854a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3855a87dd18cSLukas Czerner 						 lstart, sb->s_blocksize);
3856a87dd18cSLukas Czerner 		if (err)
3857a87dd18cSLukas Czerner 			return err;
3858a87dd18cSLukas Czerner 	}
3859a87dd18cSLukas Czerner 	/* Handle partial zero out on the end of the range */
3860e1be3a92SLukas Czerner 	if (partial_end != sb->s_blocksize - 1)
3861a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3862e1be3a92SLukas Czerner 						 byte_end - partial_end,
3863e1be3a92SLukas Czerner 						 partial_end + 1);
3864a87dd18cSLukas Czerner 	return err;
3865a87dd18cSLukas Czerner }
3866a87dd18cSLukas Czerner 
386791ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
386891ef4cafSDuane Griffin {
386991ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
387091ef4cafSDuane Griffin 		return 1;
387191ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
387291ef4cafSDuane Griffin 		return 1;
387391ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
387491ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
387591ef4cafSDuane Griffin 	return 0;
387691ef4cafSDuane Griffin }
387791ef4cafSDuane Griffin 
3878ac27a0ecSDave Kleikamp /*
387901127848SJan Kara  * We have to make sure i_disksize gets properly updated before we truncate
388001127848SJan Kara  * page cache due to hole punching or zero range. Otherwise i_disksize update
388101127848SJan Kara  * can get lost as it may have been postponed to submission of writeback but
388201127848SJan Kara  * that will never happen after we truncate page cache.
388301127848SJan Kara  */
388401127848SJan Kara int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
388501127848SJan Kara 				      loff_t len)
388601127848SJan Kara {
388701127848SJan Kara 	handle_t *handle;
38884209ae12SHarshad Shirwadkar 	int ret;
38894209ae12SHarshad Shirwadkar 
389001127848SJan Kara 	loff_t size = i_size_read(inode);
389101127848SJan Kara 
38925955102cSAl Viro 	WARN_ON(!inode_is_locked(inode));
389301127848SJan Kara 	if (offset > size || offset + len < size)
389401127848SJan Kara 		return 0;
389501127848SJan Kara 
389601127848SJan Kara 	if (EXT4_I(inode)->i_disksize >= size)
389701127848SJan Kara 		return 0;
389801127848SJan Kara 
389901127848SJan Kara 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
390001127848SJan Kara 	if (IS_ERR(handle))
390101127848SJan Kara 		return PTR_ERR(handle);
390201127848SJan Kara 	ext4_update_i_disksize(inode, size);
39034209ae12SHarshad Shirwadkar 	ret = ext4_mark_inode_dirty(handle, inode);
390401127848SJan Kara 	ext4_journal_stop(handle);
390501127848SJan Kara 
39064209ae12SHarshad Shirwadkar 	return ret;
390701127848SJan Kara }
390801127848SJan Kara 
3909d4f5258eSJan Kara static void ext4_wait_dax_page(struct inode *inode)
3910430657b6SRoss Zwisler {
3911d4f5258eSJan Kara 	filemap_invalidate_unlock(inode->i_mapping);
3912430657b6SRoss Zwisler 	schedule();
3913d4f5258eSJan Kara 	filemap_invalidate_lock(inode->i_mapping);
3914430657b6SRoss Zwisler }
3915430657b6SRoss Zwisler 
3916430657b6SRoss Zwisler int ext4_break_layouts(struct inode *inode)
3917430657b6SRoss Zwisler {
3918430657b6SRoss Zwisler 	struct page *page;
3919430657b6SRoss Zwisler 	int error;
3920430657b6SRoss Zwisler 
3921d4f5258eSJan Kara 	if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
3922430657b6SRoss Zwisler 		return -EINVAL;
3923430657b6SRoss Zwisler 
3924430657b6SRoss Zwisler 	do {
3925430657b6SRoss Zwisler 		page = dax_layout_busy_page(inode->i_mapping);
3926430657b6SRoss Zwisler 		if (!page)
3927430657b6SRoss Zwisler 			return 0;
3928430657b6SRoss Zwisler 
3929430657b6SRoss Zwisler 		error = ___wait_var_event(&page->_refcount,
3930430657b6SRoss Zwisler 				atomic_read(&page->_refcount) == 1,
3931430657b6SRoss Zwisler 				TASK_INTERRUPTIBLE, 0, 0,
3932d4f5258eSJan Kara 				ext4_wait_dax_page(inode));
3933b1f38217SRoss Zwisler 	} while (error == 0);
3934430657b6SRoss Zwisler 
3935430657b6SRoss Zwisler 	return error;
3936430657b6SRoss Zwisler }
3937430657b6SRoss Zwisler 
393801127848SJan Kara /*
3939cca32b7eSRoss Zwisler  * ext4_punch_hole: punches a hole in a file by releasing the blocks
3940a4bb6b64SAllison Henderson  * associated with the given offset and length
3941a4bb6b64SAllison Henderson  *
3942a4bb6b64SAllison Henderson  * @inode:  File inode
3943a4bb6b64SAllison Henderson  * @offset: The offset where the hole will begin
3944a4bb6b64SAllison Henderson  * @len:    The length of the hole
3945a4bb6b64SAllison Henderson  *
39464907cb7bSAnatol Pomozov  * Returns: 0 on success or negative on failure
3947a4bb6b64SAllison Henderson  */
3948a4bb6b64SAllison Henderson 
3949ad5cd4f4SDarrick J. Wong int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3950a4bb6b64SAllison Henderson {
3951ad5cd4f4SDarrick J. Wong 	struct inode *inode = file_inode(file);
395226a4c0c6STheodore Ts'o 	struct super_block *sb = inode->i_sb;
395326a4c0c6STheodore Ts'o 	ext4_lblk_t first_block, stop_block;
395426a4c0c6STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
39552da37622STadeusz Struk 	loff_t first_block_offset, last_block_offset, max_length;
39562da37622STadeusz Struk 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
395726a4c0c6STheodore Ts'o 	handle_t *handle;
395826a4c0c6STheodore Ts'o 	unsigned int credits;
39594209ae12SHarshad Shirwadkar 	int ret = 0, ret2 = 0;
396026a4c0c6STheodore Ts'o 
3961b8a86845SLukas Czerner 	trace_ext4_punch_hole(inode, offset, length, 0);
3962aaddea81SZheng Liu 
396326a4c0c6STheodore Ts'o 	/*
396426a4c0c6STheodore Ts'o 	 * Write out all dirty pages to avoid race conditions
396526a4c0c6STheodore Ts'o 	 * Then release them.
396626a4c0c6STheodore Ts'o 	 */
3967cca32b7eSRoss Zwisler 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
396826a4c0c6STheodore Ts'o 		ret = filemap_write_and_wait_range(mapping, offset,
396926a4c0c6STheodore Ts'o 						   offset + length - 1);
397026a4c0c6STheodore Ts'o 		if (ret)
397126a4c0c6STheodore Ts'o 			return ret;
397226a4c0c6STheodore Ts'o 	}
397326a4c0c6STheodore Ts'o 
39745955102cSAl Viro 	inode_lock(inode);
39759ef06cecSLukas Czerner 
397626a4c0c6STheodore Ts'o 	/* No need to punch hole beyond i_size */
397726a4c0c6STheodore Ts'o 	if (offset >= inode->i_size)
397826a4c0c6STheodore Ts'o 		goto out_mutex;
397926a4c0c6STheodore Ts'o 
398026a4c0c6STheodore Ts'o 	/*
398126a4c0c6STheodore Ts'o 	 * If the hole extends beyond i_size, set the hole
398226a4c0c6STheodore Ts'o 	 * to end after the page that contains i_size
398326a4c0c6STheodore Ts'o 	 */
398426a4c0c6STheodore Ts'o 	if (offset + length > inode->i_size) {
398526a4c0c6STheodore Ts'o 		length = inode->i_size +
398609cbfeafSKirill A. Shutemov 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
398726a4c0c6STheodore Ts'o 		   offset;
398826a4c0c6STheodore Ts'o 	}
398926a4c0c6STheodore Ts'o 
39902da37622STadeusz Struk 	/*
39912da37622STadeusz Struk 	 * For punch hole the length + offset needs to be within one block
39922da37622STadeusz Struk 	 * before last range. Adjust the length if it goes beyond that limit.
39932da37622STadeusz Struk 	 */
39942da37622STadeusz Struk 	max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
39952da37622STadeusz Struk 	if (offset + length > max_length)
39962da37622STadeusz Struk 		length = max_length - offset;
39972da37622STadeusz Struk 
3998a361293fSJan Kara 	if (offset & (sb->s_blocksize - 1) ||
3999a361293fSJan Kara 	    (offset + length) & (sb->s_blocksize - 1)) {
4000a361293fSJan Kara 		/*
4001a361293fSJan Kara 		 * Attach jinode to inode for jbd2 if we do any zeroing of
4002a361293fSJan Kara 		 * partial block
4003a361293fSJan Kara 		 */
4004a361293fSJan Kara 		ret = ext4_inode_attach_jinode(inode);
4005a361293fSJan Kara 		if (ret < 0)
4006a361293fSJan Kara 			goto out_mutex;
4007a361293fSJan Kara 
4008a361293fSJan Kara 	}
4009a361293fSJan Kara 
4010f340b3d9Shongnanli 	/* Wait all existing dio workers, newcomers will block on i_rwsem */
4011ea3d7209SJan Kara 	inode_dio_wait(inode);
4012ea3d7209SJan Kara 
4013ad5cd4f4SDarrick J. Wong 	ret = file_modified(file);
4014ad5cd4f4SDarrick J. Wong 	if (ret)
4015ad5cd4f4SDarrick J. Wong 		goto out_mutex;
4016ad5cd4f4SDarrick J. Wong 
4017ea3d7209SJan Kara 	/*
4018ea3d7209SJan Kara 	 * Prevent page faults from reinstantiating pages we have released from
4019ea3d7209SJan Kara 	 * page cache.
4020ea3d7209SJan Kara 	 */
4021d4f5258eSJan Kara 	filemap_invalidate_lock(mapping);
4022430657b6SRoss Zwisler 
4023430657b6SRoss Zwisler 	ret = ext4_break_layouts(inode);
4024430657b6SRoss Zwisler 	if (ret)
4025430657b6SRoss Zwisler 		goto out_dio;
4026430657b6SRoss Zwisler 
4027a87dd18cSLukas Czerner 	first_block_offset = round_up(offset, sb->s_blocksize);
4028a87dd18cSLukas Czerner 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
402926a4c0c6STheodore Ts'o 
4030a87dd18cSLukas Czerner 	/* Now release the pages and zero block aligned part of pages*/
403101127848SJan Kara 	if (last_block_offset > first_block_offset) {
403201127848SJan Kara 		ret = ext4_update_disksize_before_punch(inode, offset, length);
403301127848SJan Kara 		if (ret)
403401127848SJan Kara 			goto out_dio;
4035a87dd18cSLukas Czerner 		truncate_pagecache_range(inode, first_block_offset,
4036a87dd18cSLukas Czerner 					 last_block_offset);
403701127848SJan Kara 	}
403826a4c0c6STheodore Ts'o 
403926a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
404026a4c0c6STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
404126a4c0c6STheodore Ts'o 	else
404226a4c0c6STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
404326a4c0c6STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
404426a4c0c6STheodore Ts'o 	if (IS_ERR(handle)) {
404526a4c0c6STheodore Ts'o 		ret = PTR_ERR(handle);
404626a4c0c6STheodore Ts'o 		ext4_std_error(sb, ret);
404726a4c0c6STheodore Ts'o 		goto out_dio;
404826a4c0c6STheodore Ts'o 	}
404926a4c0c6STheodore Ts'o 
4050a87dd18cSLukas Czerner 	ret = ext4_zero_partial_blocks(handle, inode, offset,
4051a87dd18cSLukas Czerner 				       length);
405226a4c0c6STheodore Ts'o 	if (ret)
405326a4c0c6STheodore Ts'o 		goto out_stop;
405426a4c0c6STheodore Ts'o 
405526a4c0c6STheodore Ts'o 	first_block = (offset + sb->s_blocksize - 1) >>
405626a4c0c6STheodore Ts'o 		EXT4_BLOCK_SIZE_BITS(sb);
405726a4c0c6STheodore Ts'o 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
405826a4c0c6STheodore Ts'o 
4059eee597acSLukas Czerner 	/* If there are blocks to remove, do it */
4060eee597acSLukas Czerner 	if (stop_block > first_block) {
406126a4c0c6STheodore Ts'o 
406226a4c0c6STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
406327bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
406426a4c0c6STheodore Ts'o 
406526a4c0c6STheodore Ts'o 		ret = ext4_es_remove_extent(inode, first_block,
406626a4c0c6STheodore Ts'o 					    stop_block - first_block);
406726a4c0c6STheodore Ts'o 		if (ret) {
406826a4c0c6STheodore Ts'o 			up_write(&EXT4_I(inode)->i_data_sem);
406926a4c0c6STheodore Ts'o 			goto out_stop;
407026a4c0c6STheodore Ts'o 		}
407126a4c0c6STheodore Ts'o 
407226a4c0c6STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
407326a4c0c6STheodore Ts'o 			ret = ext4_ext_remove_space(inode, first_block,
407426a4c0c6STheodore Ts'o 						    stop_block - 1);
407526a4c0c6STheodore Ts'o 		else
40764f579ae7SLukas Czerner 			ret = ext4_ind_remove_space(handle, inode, first_block,
407726a4c0c6STheodore Ts'o 						    stop_block);
407826a4c0c6STheodore Ts'o 
4079819c4920STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
4080eee597acSLukas Czerner 	}
4081a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_range(handle, inode, first_block, stop_block);
408226a4c0c6STheodore Ts'o 	if (IS_SYNC(inode))
408326a4c0c6STheodore Ts'o 		ext4_handle_sync(handle);
4084e251f9bcSMaxim Patlasov 
4085eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
40864209ae12SHarshad Shirwadkar 	ret2 = ext4_mark_inode_dirty(handle, inode);
40874209ae12SHarshad Shirwadkar 	if (unlikely(ret2))
40884209ae12SHarshad Shirwadkar 		ret = ret2;
408967a7d5f5SJan Kara 	if (ret >= 0)
409067a7d5f5SJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
409126a4c0c6STheodore Ts'o out_stop:
409226a4c0c6STheodore Ts'o 	ext4_journal_stop(handle);
409326a4c0c6STheodore Ts'o out_dio:
4094d4f5258eSJan Kara 	filemap_invalidate_unlock(mapping);
409526a4c0c6STheodore Ts'o out_mutex:
40965955102cSAl Viro 	inode_unlock(inode);
409726a4c0c6STheodore Ts'o 	return ret;
4098a4bb6b64SAllison Henderson }
4099a4bb6b64SAllison Henderson 
4100a361293fSJan Kara int ext4_inode_attach_jinode(struct inode *inode)
4101a361293fSJan Kara {
4102a361293fSJan Kara 	struct ext4_inode_info *ei = EXT4_I(inode);
4103a361293fSJan Kara 	struct jbd2_inode *jinode;
4104a361293fSJan Kara 
4105a361293fSJan Kara 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4106a361293fSJan Kara 		return 0;
4107a361293fSJan Kara 
4108a361293fSJan Kara 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4109a361293fSJan Kara 	spin_lock(&inode->i_lock);
4110a361293fSJan Kara 	if (!ei->jinode) {
4111a361293fSJan Kara 		if (!jinode) {
4112a361293fSJan Kara 			spin_unlock(&inode->i_lock);
4113a361293fSJan Kara 			return -ENOMEM;
4114a361293fSJan Kara 		}
4115a361293fSJan Kara 		ei->jinode = jinode;
4116a361293fSJan Kara 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4117a361293fSJan Kara 		jinode = NULL;
4118a361293fSJan Kara 	}
4119a361293fSJan Kara 	spin_unlock(&inode->i_lock);
4120a361293fSJan Kara 	if (unlikely(jinode != NULL))
4121a361293fSJan Kara 		jbd2_free_inode(jinode);
4122a361293fSJan Kara 	return 0;
4123a361293fSJan Kara }
4124a361293fSJan Kara 
4125a4bb6b64SAllison Henderson /*
4126617ba13bSMingming Cao  * ext4_truncate()
4127ac27a0ecSDave Kleikamp  *
4128617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
4129617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4130ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
4131ac27a0ecSDave Kleikamp  *
413242b2aa86SJustin P. Mattock  * As we work through the truncate and commit bits of it to the journal there
4133ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
4134ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
4135ac27a0ecSDave Kleikamp  *
4136ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
4137ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
4138ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
4139ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
4140ac27a0ecSDave Kleikamp  * left-to-right works OK too).
4141ac27a0ecSDave Kleikamp  *
4142ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
4143ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
4144ac27a0ecSDave Kleikamp  *
4145ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
4146617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4147ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
4148617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
4149617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
4150ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
4151617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
4152ac27a0ecSDave Kleikamp  */
41532c98eb5eSTheodore Ts'o int ext4_truncate(struct inode *inode)
4154ac27a0ecSDave Kleikamp {
4155819c4920STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
4156819c4920STheodore Ts'o 	unsigned int credits;
41574209ae12SHarshad Shirwadkar 	int err = 0, err2;
4158819c4920STheodore Ts'o 	handle_t *handle;
4159819c4920STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
4160819c4920STheodore Ts'o 
416119b5ef61STheodore Ts'o 	/*
416219b5ef61STheodore Ts'o 	 * There is a possibility that we're either freeing the inode
4163e04027e8SMatthew Wilcox 	 * or it's a completely new inode. In those cases we might not
4164f340b3d9Shongnanli 	 * have i_rwsem locked because it's not necessary.
416519b5ef61STheodore Ts'o 	 */
416619b5ef61STheodore Ts'o 	if (!(inode->i_state & (I_NEW|I_FREEING)))
41675955102cSAl Viro 		WARN_ON(!inode_is_locked(inode));
41680562e0baSJiaying Zhang 	trace_ext4_truncate_enter(inode);
41690562e0baSJiaying Zhang 
417091ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
41719a5d265fSzhengliang 		goto out_trace;
4172ac27a0ecSDave Kleikamp 
41735534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
417419f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
41757d8f9f7dSTheodore Ts'o 
4176aef1c851STao Ma 	if (ext4_has_inline_data(inode)) {
4177aef1c851STao Ma 		int has_inline = 1;
4178aef1c851STao Ma 
417901daf945STheodore Ts'o 		err = ext4_inline_data_truncate(inode, &has_inline);
41809a5d265fSzhengliang 		if (err || has_inline)
41819a5d265fSzhengliang 			goto out_trace;
4182aef1c851STao Ma 	}
4183aef1c851STao Ma 
4184a361293fSJan Kara 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4185a361293fSJan Kara 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4186a71248b1SBaokun Li 		err = ext4_inode_attach_jinode(inode);
4187a71248b1SBaokun Li 		if (err)
41889a5d265fSzhengliang 			goto out_trace;
4189a361293fSJan Kara 	}
4190a361293fSJan Kara 
4191ff9893dcSAmir Goldstein 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4192819c4920STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
4193ff9893dcSAmir Goldstein 	else
4194819c4920STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
4195819c4920STheodore Ts'o 
4196819c4920STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
41979a5d265fSzhengliang 	if (IS_ERR(handle)) {
41989a5d265fSzhengliang 		err = PTR_ERR(handle);
41999a5d265fSzhengliang 		goto out_trace;
42009a5d265fSzhengliang 	}
4201819c4920STheodore Ts'o 
4202eb3544c6SLukas Czerner 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4203eb3544c6SLukas Czerner 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4204819c4920STheodore Ts'o 
4205819c4920STheodore Ts'o 	/*
4206819c4920STheodore Ts'o 	 * We add the inode to the orphan list, so that if this
4207819c4920STheodore Ts'o 	 * truncate spans multiple transactions, and we crash, we will
4208819c4920STheodore Ts'o 	 * resume the truncate when the filesystem recovers.  It also
4209819c4920STheodore Ts'o 	 * marks the inode dirty, to catch the new size.
4210819c4920STheodore Ts'o 	 *
4211819c4920STheodore Ts'o 	 * Implication: the file must always be in a sane, consistent
4212819c4920STheodore Ts'o 	 * truncatable state while each transaction commits.
4213819c4920STheodore Ts'o 	 */
42142c98eb5eSTheodore Ts'o 	err = ext4_orphan_add(handle, inode);
42152c98eb5eSTheodore Ts'o 	if (err)
4216819c4920STheodore Ts'o 		goto out_stop;
4217819c4920STheodore Ts'o 
4218819c4920STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
4219819c4920STheodore Ts'o 
422027bc446eSbrookxu 	ext4_discard_preallocations(inode, 0);
4221819c4920STheodore Ts'o 
4222819c4920STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4223d0abb36dSTheodore Ts'o 		err = ext4_ext_truncate(handle, inode);
4224819c4920STheodore Ts'o 	else
4225819c4920STheodore Ts'o 		ext4_ind_truncate(handle, inode);
4226819c4920STheodore Ts'o 
4227819c4920STheodore Ts'o 	up_write(&ei->i_data_sem);
4228d0abb36dSTheodore Ts'o 	if (err)
4229d0abb36dSTheodore Ts'o 		goto out_stop;
4230819c4920STheodore Ts'o 
4231819c4920STheodore Ts'o 	if (IS_SYNC(inode))
4232819c4920STheodore Ts'o 		ext4_handle_sync(handle);
4233819c4920STheodore Ts'o 
4234819c4920STheodore Ts'o out_stop:
4235819c4920STheodore Ts'o 	/*
4236819c4920STheodore Ts'o 	 * If this was a simple ftruncate() and the file will remain alive,
4237819c4920STheodore Ts'o 	 * then we need to clear up the orphan record which we created above.
4238819c4920STheodore Ts'o 	 * However, if this was a real unlink then we were called by
423958d86a50SWang Shilong 	 * ext4_evict_inode(), and we allow that function to clean up the
4240819c4920STheodore Ts'o 	 * orphan info for us.
4241819c4920STheodore Ts'o 	 */
4242819c4920STheodore Ts'o 	if (inode->i_nlink)
4243819c4920STheodore Ts'o 		ext4_orphan_del(handle, inode);
4244819c4920STheodore Ts'o 
4245eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
42464209ae12SHarshad Shirwadkar 	err2 = ext4_mark_inode_dirty(handle, inode);
42474209ae12SHarshad Shirwadkar 	if (unlikely(err2 && !err))
42484209ae12SHarshad Shirwadkar 		err = err2;
4249819c4920STheodore Ts'o 	ext4_journal_stop(handle);
4250a86c6181SAlex Tomas 
42519a5d265fSzhengliang out_trace:
42520562e0baSJiaying Zhang 	trace_ext4_truncate_exit(inode);
42532c98eb5eSTheodore Ts'o 	return err;
4254ac27a0ecSDave Kleikamp }
4255ac27a0ecSDave Kleikamp 
42569a1bf32cSZhang Yi static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
42579a1bf32cSZhang Yi {
42589a1bf32cSZhang Yi 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
42599a1bf32cSZhang Yi 		return inode_peek_iversion_raw(inode);
42609a1bf32cSZhang Yi 	else
42619a1bf32cSZhang Yi 		return inode_peek_iversion(inode);
42629a1bf32cSZhang Yi }
42639a1bf32cSZhang Yi 
42649a1bf32cSZhang Yi static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
42659a1bf32cSZhang Yi 				 struct ext4_inode_info *ei)
42669a1bf32cSZhang Yi {
42679a1bf32cSZhang Yi 	struct inode *inode = &(ei->vfs_inode);
42689a1bf32cSZhang Yi 	u64 i_blocks = READ_ONCE(inode->i_blocks);
42699a1bf32cSZhang Yi 	struct super_block *sb = inode->i_sb;
42709a1bf32cSZhang Yi 
42719a1bf32cSZhang Yi 	if (i_blocks <= ~0U) {
42729a1bf32cSZhang Yi 		/*
42739a1bf32cSZhang Yi 		 * i_blocks can be represented in a 32 bit variable
42749a1bf32cSZhang Yi 		 * as multiple of 512 bytes
42759a1bf32cSZhang Yi 		 */
42769a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42779a1bf32cSZhang Yi 		raw_inode->i_blocks_high = 0;
42789a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
42799a1bf32cSZhang Yi 		return 0;
42809a1bf32cSZhang Yi 	}
42819a1bf32cSZhang Yi 
42829a1bf32cSZhang Yi 	/*
42839a1bf32cSZhang Yi 	 * This should never happen since sb->s_maxbytes should not have
42849a1bf32cSZhang Yi 	 * allowed this, sb->s_maxbytes was set according to the huge_file
42859a1bf32cSZhang Yi 	 * feature in ext4_fill_super().
42869a1bf32cSZhang Yi 	 */
42879a1bf32cSZhang Yi 	if (!ext4_has_feature_huge_file(sb))
42889a1bf32cSZhang Yi 		return -EFSCORRUPTED;
42899a1bf32cSZhang Yi 
42909a1bf32cSZhang Yi 	if (i_blocks <= 0xffffffffffffULL) {
42919a1bf32cSZhang Yi 		/*
42929a1bf32cSZhang Yi 		 * i_blocks can be represented in a 48 bit variable
42939a1bf32cSZhang Yi 		 * as multiple of 512 bytes
42949a1bf32cSZhang Yi 		 */
42959a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42969a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
42979a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
42989a1bf32cSZhang Yi 	} else {
42999a1bf32cSZhang Yi 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
43009a1bf32cSZhang Yi 		/* i_block is stored in file system block size */
43019a1bf32cSZhang Yi 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
43029a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
43039a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
43049a1bf32cSZhang Yi 	}
43059a1bf32cSZhang Yi 	return 0;
43069a1bf32cSZhang Yi }
43079a1bf32cSZhang Yi 
43089a1bf32cSZhang Yi static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
43099a1bf32cSZhang Yi {
43109a1bf32cSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
43119a1bf32cSZhang Yi 	uid_t i_uid;
43129a1bf32cSZhang Yi 	gid_t i_gid;
43139a1bf32cSZhang Yi 	projid_t i_projid;
43149a1bf32cSZhang Yi 	int block;
43159a1bf32cSZhang Yi 	int err;
43169a1bf32cSZhang Yi 
43179a1bf32cSZhang Yi 	err = ext4_inode_blocks_set(raw_inode, ei);
43189a1bf32cSZhang Yi 
43199a1bf32cSZhang Yi 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
43209a1bf32cSZhang Yi 	i_uid = i_uid_read(inode);
43219a1bf32cSZhang Yi 	i_gid = i_gid_read(inode);
43229a1bf32cSZhang Yi 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
43239a1bf32cSZhang Yi 	if (!(test_opt(inode->i_sb, NO_UID32))) {
43249a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
43259a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
43269a1bf32cSZhang Yi 		/*
43279a1bf32cSZhang Yi 		 * Fix up interoperability with old kernels. Otherwise,
43289a1bf32cSZhang Yi 		 * old inodes get re-used with the upper 16 bits of the
43299a1bf32cSZhang Yi 		 * uid/gid intact.
43309a1bf32cSZhang Yi 		 */
43319a1bf32cSZhang Yi 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
43329a1bf32cSZhang Yi 			raw_inode->i_uid_high = 0;
43339a1bf32cSZhang Yi 			raw_inode->i_gid_high = 0;
43349a1bf32cSZhang Yi 		} else {
43359a1bf32cSZhang Yi 			raw_inode->i_uid_high =
43369a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_uid));
43379a1bf32cSZhang Yi 			raw_inode->i_gid_high =
43389a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_gid));
43399a1bf32cSZhang Yi 		}
43409a1bf32cSZhang Yi 	} else {
43419a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
43429a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
43439a1bf32cSZhang Yi 		raw_inode->i_uid_high = 0;
43449a1bf32cSZhang Yi 		raw_inode->i_gid_high = 0;
43459a1bf32cSZhang Yi 	}
43469a1bf32cSZhang Yi 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
43479a1bf32cSZhang Yi 
43489a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
43499a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
43509a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
43519a1bf32cSZhang Yi 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
43529a1bf32cSZhang Yi 
43539a1bf32cSZhang Yi 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
43549a1bf32cSZhang Yi 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
43559a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
43569a1bf32cSZhang Yi 		raw_inode->i_file_acl_high =
43579a1bf32cSZhang Yi 			cpu_to_le16(ei->i_file_acl >> 32);
43589a1bf32cSZhang Yi 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
43599a1bf32cSZhang Yi 	ext4_isize_set(raw_inode, ei->i_disksize);
43609a1bf32cSZhang Yi 
43619a1bf32cSZhang Yi 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
43629a1bf32cSZhang Yi 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
43639a1bf32cSZhang Yi 		if (old_valid_dev(inode->i_rdev)) {
43649a1bf32cSZhang Yi 			raw_inode->i_block[0] =
43659a1bf32cSZhang Yi 				cpu_to_le32(old_encode_dev(inode->i_rdev));
43669a1bf32cSZhang Yi 			raw_inode->i_block[1] = 0;
43679a1bf32cSZhang Yi 		} else {
43689a1bf32cSZhang Yi 			raw_inode->i_block[0] = 0;
43699a1bf32cSZhang Yi 			raw_inode->i_block[1] =
43709a1bf32cSZhang Yi 				cpu_to_le32(new_encode_dev(inode->i_rdev));
43719a1bf32cSZhang Yi 			raw_inode->i_block[2] = 0;
43729a1bf32cSZhang Yi 		}
43739a1bf32cSZhang Yi 	} else if (!ext4_has_inline_data(inode)) {
43749a1bf32cSZhang Yi 		for (block = 0; block < EXT4_N_BLOCKS; block++)
43759a1bf32cSZhang Yi 			raw_inode->i_block[block] = ei->i_data[block];
43769a1bf32cSZhang Yi 	}
43779a1bf32cSZhang Yi 
43789a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
43799a1bf32cSZhang Yi 		u64 ivers = ext4_inode_peek_iversion(inode);
43809a1bf32cSZhang Yi 
43819a1bf32cSZhang Yi 		raw_inode->i_disk_version = cpu_to_le32(ivers);
43829a1bf32cSZhang Yi 		if (ei->i_extra_isize) {
43839a1bf32cSZhang Yi 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
43849a1bf32cSZhang Yi 				raw_inode->i_version_hi =
43859a1bf32cSZhang Yi 					cpu_to_le32(ivers >> 32);
43869a1bf32cSZhang Yi 			raw_inode->i_extra_isize =
43879a1bf32cSZhang Yi 				cpu_to_le16(ei->i_extra_isize);
43889a1bf32cSZhang Yi 		}
43899a1bf32cSZhang Yi 	}
43909a1bf32cSZhang Yi 
43919a1bf32cSZhang Yi 	if (i_projid != EXT4_DEF_PROJID &&
43929a1bf32cSZhang Yi 	    !ext4_has_feature_project(inode->i_sb))
43939a1bf32cSZhang Yi 		err = err ?: -EFSCORRUPTED;
43949a1bf32cSZhang Yi 
43959a1bf32cSZhang Yi 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
43969a1bf32cSZhang Yi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
43979a1bf32cSZhang Yi 		raw_inode->i_projid = cpu_to_le32(i_projid);
43989a1bf32cSZhang Yi 
43999a1bf32cSZhang Yi 	ext4_inode_csum_set(inode, raw_inode, ei);
44009a1bf32cSZhang Yi 	return err;
44019a1bf32cSZhang Yi }
44029a1bf32cSZhang Yi 
4403ac27a0ecSDave Kleikamp /*
4404617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
4405de01f484SZhang Yi  * underlying buffer_head on success. If we pass 'inode' and it does not
4406de01f484SZhang Yi  * have in-inode xattr, we have all inode data in memory that is needed
4407de01f484SZhang Yi  * to recreate the on-disk version of this inode.
4408ac27a0ecSDave Kleikamp  */
44098016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4410de01f484SZhang Yi 				struct inode *inode, struct ext4_iloc *iloc,
44118016e29fSHarshad Shirwadkar 				ext4_fsblk_t *ret_block)
4412ac27a0ecSDave Kleikamp {
4413240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
4414ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
4415240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
441602f03c42SLinus Torvalds 	struct blk_plug		plug;
4417240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
4418ac27a0ecSDave Kleikamp 
44193a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
44208016e29fSHarshad Shirwadkar 	if (ino < EXT4_ROOT_INO ||
44218016e29fSHarshad Shirwadkar 	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
44226a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4423ac27a0ecSDave Kleikamp 
44248016e29fSHarshad Shirwadkar 	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4425240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4426240799cdSTheodore Ts'o 	if (!gdp)
4427240799cdSTheodore Ts'o 		return -EIO;
4428240799cdSTheodore Ts'o 
4429240799cdSTheodore Ts'o 	/*
4430240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
4431240799cdSTheodore Ts'o 	 */
443200d09882STao Ma 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
44338016e29fSHarshad Shirwadkar 	inode_offset = ((ino - 1) %
4434240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
4435240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4436240799cdSTheodore Ts'o 
4437eee22187SBaokun Li 	block = ext4_inode_table(sb, gdp);
4438eee22187SBaokun Li 	if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4439eee22187SBaokun Li 	    (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4440eee22187SBaokun Li 		ext4_error(sb, "Invalid inode table block %llu in "
4441eee22187SBaokun Li 			   "block_group %u", block, iloc->block_group);
4442eee22187SBaokun Li 		return -EFSCORRUPTED;
4443eee22187SBaokun Li 	}
4444eee22187SBaokun Li 	block += (inode_offset / inodes_per_block);
4445eee22187SBaokun Li 
4446240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
4447aebf0243SWang Shilong 	if (unlikely(!bh))
4448860d21e2STheodore Ts'o 		return -ENOMEM;
44498e33fadfSZhang Yi 	if (ext4_buffer_uptodate(bh))
4450ac27a0ecSDave Kleikamp 		goto has_buffer;
4451ac27a0ecSDave Kleikamp 
44528e33fadfSZhang Yi 	lock_buffer(bh);
4453f2c77973SZhang Yi 	if (ext4_buffer_uptodate(bh)) {
4454f2c77973SZhang Yi 		/* Someone brought it uptodate while we waited */
4455f2c77973SZhang Yi 		unlock_buffer(bh);
4456f2c77973SZhang Yi 		goto has_buffer;
4457f2c77973SZhang Yi 	}
4458f2c77973SZhang Yi 
4459ac27a0ecSDave Kleikamp 	/*
4460ac27a0ecSDave Kleikamp 	 * If we have all information of the inode in memory and this
4461ac27a0ecSDave Kleikamp 	 * is the only valid inode in the block, we need not read the
4462ac27a0ecSDave Kleikamp 	 * block.
4463ac27a0ecSDave Kleikamp 	 */
4464de01f484SZhang Yi 	if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4465ac27a0ecSDave Kleikamp 		struct buffer_head *bitmap_bh;
4466240799cdSTheodore Ts'o 		int i, start;
4467ac27a0ecSDave Kleikamp 
4468240799cdSTheodore Ts'o 		start = inode_offset & ~(inodes_per_block - 1);
4469ac27a0ecSDave Kleikamp 
4470ac27a0ecSDave Kleikamp 		/* Is the inode bitmap in cache? */
4471240799cdSTheodore Ts'o 		bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4472aebf0243SWang Shilong 		if (unlikely(!bitmap_bh))
4473ac27a0ecSDave Kleikamp 			goto make_io;
4474ac27a0ecSDave Kleikamp 
4475ac27a0ecSDave Kleikamp 		/*
4476ac27a0ecSDave Kleikamp 		 * If the inode bitmap isn't in cache then the
4477ac27a0ecSDave Kleikamp 		 * optimisation may end up performing two reads instead
4478ac27a0ecSDave Kleikamp 		 * of one, so skip it.
4479ac27a0ecSDave Kleikamp 		 */
4480ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bitmap_bh)) {
4481ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
4482ac27a0ecSDave Kleikamp 			goto make_io;
4483ac27a0ecSDave Kleikamp 		}
4484240799cdSTheodore Ts'o 		for (i = start; i < start + inodes_per_block; i++) {
4485ac27a0ecSDave Kleikamp 			if (i == inode_offset)
4486ac27a0ecSDave Kleikamp 				continue;
4487617ba13bSMingming Cao 			if (ext4_test_bit(i, bitmap_bh->b_data))
4488ac27a0ecSDave Kleikamp 				break;
4489ac27a0ecSDave Kleikamp 		}
4490ac27a0ecSDave Kleikamp 		brelse(bitmap_bh);
4491240799cdSTheodore Ts'o 		if (i == start + inodes_per_block) {
4492de01f484SZhang Yi 			struct ext4_inode *raw_inode =
4493de01f484SZhang Yi 				(struct ext4_inode *) (bh->b_data + iloc->offset);
4494de01f484SZhang Yi 
4495ac27a0ecSDave Kleikamp 			/* all other inodes are free, so skip I/O */
4496ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, bh->b_size);
4497de01f484SZhang Yi 			if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4498de01f484SZhang Yi 				ext4_fill_raw_inode(inode, raw_inode);
4499ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
4500ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
4501ac27a0ecSDave Kleikamp 			goto has_buffer;
4502ac27a0ecSDave Kleikamp 		}
4503ac27a0ecSDave Kleikamp 	}
4504ac27a0ecSDave Kleikamp 
4505ac27a0ecSDave Kleikamp make_io:
4506ac27a0ecSDave Kleikamp 	/*
4507240799cdSTheodore Ts'o 	 * If we need to do any I/O, try to pre-readahead extra
4508240799cdSTheodore Ts'o 	 * blocks from the inode table.
4509240799cdSTheodore Ts'o 	 */
451002f03c42SLinus Torvalds 	blk_start_plug(&plug);
4511240799cdSTheodore Ts'o 	if (EXT4_SB(sb)->s_inode_readahead_blks) {
4512240799cdSTheodore Ts'o 		ext4_fsblk_t b, end, table;
4513240799cdSTheodore Ts'o 		unsigned num;
45140d606e2cSTheodore Ts'o 		__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4515240799cdSTheodore Ts'o 
4516240799cdSTheodore Ts'o 		table = ext4_inode_table(sb, gdp);
4517b713a5ecSTheodore Ts'o 		/* s_inode_readahead_blks is always a power of 2 */
45180d606e2cSTheodore Ts'o 		b = block & ~((ext4_fsblk_t) ra_blks - 1);
4519240799cdSTheodore Ts'o 		if (table > b)
4520240799cdSTheodore Ts'o 			b = table;
45210d606e2cSTheodore Ts'o 		end = b + ra_blks;
4522240799cdSTheodore Ts'o 		num = EXT4_INODES_PER_GROUP(sb);
4523feb0ab32SDarrick J. Wong 		if (ext4_has_group_desc_csum(sb))
4524560671a0SAneesh Kumar K.V 			num -= ext4_itable_unused_count(sb, gdp);
4525240799cdSTheodore Ts'o 		table += num / inodes_per_block;
4526240799cdSTheodore Ts'o 		if (end > table)
4527240799cdSTheodore Ts'o 			end = table;
4528240799cdSTheodore Ts'o 		while (b <= end)
45295df1d412Szhangyi (F) 			ext4_sb_breadahead_unmovable(sb, b++);
4530240799cdSTheodore Ts'o 	}
4531240799cdSTheodore Ts'o 
4532240799cdSTheodore Ts'o 	/*
4533ac27a0ecSDave Kleikamp 	 * There are other valid inodes in the buffer, this inode
4534ac27a0ecSDave Kleikamp 	 * has in-inode xattrs, or we don't have this inode in memory.
4535ac27a0ecSDave Kleikamp 	 * Read the block from disk.
4536ac27a0ecSDave Kleikamp 	 */
45378016e29fSHarshad Shirwadkar 	trace_ext4_load_inode(sb, ino);
45382d069c08Szhangyi (F) 	ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
453902f03c42SLinus Torvalds 	blk_finish_plug(&plug);
4540ac27a0ecSDave Kleikamp 	wait_on_buffer(bh);
45410904c9aeSZhang Yi 	ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4542ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
45438016e29fSHarshad Shirwadkar 		if (ret_block)
45448016e29fSHarshad Shirwadkar 			*ret_block = block;
4545ac27a0ecSDave Kleikamp 		brelse(bh);
4546ac27a0ecSDave Kleikamp 		return -EIO;
4547ac27a0ecSDave Kleikamp 	}
4548ac27a0ecSDave Kleikamp has_buffer:
4549ac27a0ecSDave Kleikamp 	iloc->bh = bh;
4550ac27a0ecSDave Kleikamp 	return 0;
4551ac27a0ecSDave Kleikamp }
4552ac27a0ecSDave Kleikamp 
45538016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc_noinmem(struct inode *inode,
45548016e29fSHarshad Shirwadkar 					struct ext4_iloc *iloc)
45558016e29fSHarshad Shirwadkar {
4556c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
45578016e29fSHarshad Shirwadkar 	int ret;
45588016e29fSHarshad Shirwadkar 
4559de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
45608016e29fSHarshad Shirwadkar 					&err_blk);
45618016e29fSHarshad Shirwadkar 
45628016e29fSHarshad Shirwadkar 	if (ret == -EIO)
45638016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
45648016e29fSHarshad Shirwadkar 					"unable to read itable block");
45658016e29fSHarshad Shirwadkar 
45668016e29fSHarshad Shirwadkar 	return ret;
45678016e29fSHarshad Shirwadkar }
45688016e29fSHarshad Shirwadkar 
4569617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4570ac27a0ecSDave Kleikamp {
4571c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
45728016e29fSHarshad Shirwadkar 	int ret;
45738016e29fSHarshad Shirwadkar 
4574de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4575de01f484SZhang Yi 					&err_blk);
45768016e29fSHarshad Shirwadkar 
45778016e29fSHarshad Shirwadkar 	if (ret == -EIO)
45788016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
45798016e29fSHarshad Shirwadkar 					"unable to read itable block");
45808016e29fSHarshad Shirwadkar 
45818016e29fSHarshad Shirwadkar 	return ret;
45828016e29fSHarshad Shirwadkar }
45838016e29fSHarshad Shirwadkar 
45848016e29fSHarshad Shirwadkar 
45858016e29fSHarshad Shirwadkar int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
45868016e29fSHarshad Shirwadkar 			  struct ext4_iloc *iloc)
45878016e29fSHarshad Shirwadkar {
4588de01f484SZhang Yi 	return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4589ac27a0ecSDave Kleikamp }
4590ac27a0ecSDave Kleikamp 
4591a8ab6d38SIra Weiny static bool ext4_should_enable_dax(struct inode *inode)
45926642586bSRoss Zwisler {
4593a8ab6d38SIra Weiny 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4594a8ab6d38SIra Weiny 
45959cb20f94SIra Weiny 	if (test_opt2(inode->i_sb, DAX_NEVER))
45966642586bSRoss Zwisler 		return false;
45976642586bSRoss Zwisler 	if (!S_ISREG(inode->i_mode))
45986642586bSRoss Zwisler 		return false;
45996642586bSRoss Zwisler 	if (ext4_should_journal_data(inode))
46006642586bSRoss Zwisler 		return false;
46016642586bSRoss Zwisler 	if (ext4_has_inline_data(inode))
46026642586bSRoss Zwisler 		return false;
4603592ddec7SChandan Rajendra 	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
46046642586bSRoss Zwisler 		return false;
4605c93d8f88SEric Biggers 	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4606c93d8f88SEric Biggers 		return false;
4607a8ab6d38SIra Weiny 	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4608a8ab6d38SIra Weiny 		return false;
4609a8ab6d38SIra Weiny 	if (test_opt(inode->i_sb, DAX_ALWAYS))
46106642586bSRoss Zwisler 		return true;
4611a8ab6d38SIra Weiny 
4612b383a73fSIra Weiny 	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
46136642586bSRoss Zwisler }
46146642586bSRoss Zwisler 
4615043546e4SIra Weiny void ext4_set_inode_flags(struct inode *inode, bool init)
4616ac27a0ecSDave Kleikamp {
4617617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
461800a1a053STheodore Ts'o 	unsigned int new_fl = 0;
4619ac27a0ecSDave Kleikamp 
4620043546e4SIra Weiny 	WARN_ON_ONCE(IS_DAX(inode) && init);
4621043546e4SIra Weiny 
4622617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
462300a1a053STheodore Ts'o 		new_fl |= S_SYNC;
4624617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
462500a1a053STheodore Ts'o 		new_fl |= S_APPEND;
4626617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
462700a1a053STheodore Ts'o 		new_fl |= S_IMMUTABLE;
4628617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
462900a1a053STheodore Ts'o 		new_fl |= S_NOATIME;
4630617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
463100a1a053STheodore Ts'o 		new_fl |= S_DIRSYNC;
4632043546e4SIra Weiny 
4633043546e4SIra Weiny 	/* Because of the way inode_set_flags() works we must preserve S_DAX
4634043546e4SIra Weiny 	 * here if already set. */
4635043546e4SIra Weiny 	new_fl |= (inode->i_flags & S_DAX);
4636043546e4SIra Weiny 	if (init && ext4_should_enable_dax(inode))
4637923ae0ffSRoss Zwisler 		new_fl |= S_DAX;
4638043546e4SIra Weiny 
46392ee6a576SEric Biggers 	if (flags & EXT4_ENCRYPT_FL)
46402ee6a576SEric Biggers 		new_fl |= S_ENCRYPTED;
4641b886ee3eSGabriel Krisman Bertazi 	if (flags & EXT4_CASEFOLD_FL)
4642b886ee3eSGabriel Krisman Bertazi 		new_fl |= S_CASEFOLD;
4643c93d8f88SEric Biggers 	if (flags & EXT4_VERITY_FL)
4644c93d8f88SEric Biggers 		new_fl |= S_VERITY;
46455f16f322STheodore Ts'o 	inode_set_flags(inode, new_fl,
46462ee6a576SEric Biggers 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4647c93d8f88SEric Biggers 			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4648ac27a0ecSDave Kleikamp }
4649ac27a0ecSDave Kleikamp 
46500fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
46510fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
46520fc1b451SAneesh Kumar K.V {
46530fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
46548180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
46558180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
46560fc1b451SAneesh Kumar K.V 
4657e2b911c5SDarrick J. Wong 	if (ext4_has_feature_huge_file(sb)) {
46580fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
46590fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
46600fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
466107a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
46628180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
46638180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
46648180a562SAneesh Kumar K.V 		} else {
46650fc1b451SAneesh Kumar K.V 			return i_blocks;
46668180a562SAneesh Kumar K.V 		}
46670fc1b451SAneesh Kumar K.V 	} else {
46680fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
46690fc1b451SAneesh Kumar K.V 	}
46700fc1b451SAneesh Kumar K.V }
4671ff9ddf7eSJan Kara 
4672eb9b5f01STheodore Ts'o static inline int ext4_iget_extra_inode(struct inode *inode,
4673152a7b0aSTao Ma 					 struct ext4_inode *raw_inode,
4674152a7b0aSTao Ma 					 struct ext4_inode_info *ei)
4675152a7b0aSTao Ma {
4676152a7b0aSTao Ma 	__le32 *magic = (void *)raw_inode +
4677152a7b0aSTao Ma 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4678eb9b5f01STheodore Ts'o 
4679fd7e672eSBaokun Li 	if (EXT4_INODE_HAS_XATTR_SPACE(inode)  &&
4680290ab230SEric Biggers 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
46811dcdce59SYe Bin 		int err;
46821dcdce59SYe Bin 
4683152a7b0aSTao Ma 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
46841dcdce59SYe Bin 		err = ext4_find_inline_data_nolock(inode);
46851dcdce59SYe Bin 		if (!err && ext4_has_inline_data(inode))
46861dcdce59SYe Bin 			ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
46871dcdce59SYe Bin 		return err;
4688f19d5870STao Ma 	} else
4689f19d5870STao Ma 		EXT4_I(inode)->i_inline_off = 0;
4690eb9b5f01STheodore Ts'o 	return 0;
4691152a7b0aSTao Ma }
4692152a7b0aSTao Ma 
4693040cb378SLi Xi int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4694040cb378SLi Xi {
46950b7b7779SKaho Ng 	if (!ext4_has_feature_project(inode->i_sb))
4696040cb378SLi Xi 		return -EOPNOTSUPP;
4697040cb378SLi Xi 	*projid = EXT4_I(inode)->i_projid;
4698040cb378SLi Xi 	return 0;
4699040cb378SLi Xi }
4700040cb378SLi Xi 
4701e254d1afSEryu Guan /*
4702e254d1afSEryu Guan  * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4703e254d1afSEryu Guan  * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4704e254d1afSEryu Guan  * set.
4705e254d1afSEryu Guan  */
4706e254d1afSEryu Guan static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4707e254d1afSEryu Guan {
4708e254d1afSEryu Guan 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4709e254d1afSEryu Guan 		inode_set_iversion_raw(inode, val);
4710e254d1afSEryu Guan 	else
4711e254d1afSEryu Guan 		inode_set_iversion_queried(inode, val);
4712e254d1afSEryu Guan }
4713e254d1afSEryu Guan 
47148a363970STheodore Ts'o struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
47158a363970STheodore Ts'o 			  ext4_iget_flags flags, const char *function,
47168a363970STheodore Ts'o 			  unsigned int line)
4717ac27a0ecSDave Kleikamp {
4718617ba13bSMingming Cao 	struct ext4_iloc iloc;
4719617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
47201d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
4721bd2c38cfSJan Kara 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
47221d1fe1eeSDavid Howells 	struct inode *inode;
4723b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
47241d1fe1eeSDavid Howells 	long ret;
47257e6e1ef4SDarrick J. Wong 	loff_t size;
4726ac27a0ecSDave Kleikamp 	int block;
472708cefc7aSEric W. Biederman 	uid_t i_uid;
472808cefc7aSEric W. Biederman 	gid_t i_gid;
4729040cb378SLi Xi 	projid_t i_projid;
4730ac27a0ecSDave Kleikamp 
4731191ce178STheodore Ts'o 	if ((!(flags & EXT4_IGET_SPECIAL) &&
4732bd2c38cfSJan Kara 	     ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4733bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_usr_quota_inum) ||
4734bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_grp_quota_inum) ||
473502f310fcSJan Kara 	      ino == le32_to_cpu(es->s_prj_quota_inum) ||
473602f310fcSJan Kara 	      ino == le32_to_cpu(es->s_orphan_file_inum))) ||
47378a363970STheodore Ts'o 	    (ino < EXT4_ROOT_INO) ||
4738bd2c38cfSJan Kara 	    (ino > le32_to_cpu(es->s_inodes_count))) {
47398a363970STheodore Ts'o 		if (flags & EXT4_IGET_HANDLE)
47408a363970STheodore Ts'o 			return ERR_PTR(-ESTALE);
4741014c9caaSJan Kara 		__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
47428a363970STheodore Ts'o 			     "inode #%lu: comm %s: iget: illegal inode #",
47438a363970STheodore Ts'o 			     ino, current->comm);
47448a363970STheodore Ts'o 		return ERR_PTR(-EFSCORRUPTED);
47458a363970STheodore Ts'o 	}
47468a363970STheodore Ts'o 
47471d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
47481d1fe1eeSDavid Howells 	if (!inode)
47491d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
47501d1fe1eeSDavid Howells 	if (!(inode->i_state & I_NEW))
47511d1fe1eeSDavid Howells 		return inode;
47521d1fe1eeSDavid Howells 
47531d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
47547dc57615SPeter Huewe 	iloc.bh = NULL;
4755ac27a0ecSDave Kleikamp 
47568016e29fSHarshad Shirwadkar 	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
47571d1fe1eeSDavid Howells 	if (ret < 0)
4758ac27a0ecSDave Kleikamp 		goto bad_inode;
4759617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
4760814525f4SDarrick J. Wong 
47618a363970STheodore Ts'o 	if ((flags & EXT4_IGET_HANDLE) &&
47628a363970STheodore Ts'o 	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
47638a363970STheodore Ts'o 		ret = -ESTALE;
47648a363970STheodore Ts'o 		goto bad_inode;
47658a363970STheodore Ts'o 	}
47668a363970STheodore Ts'o 
4767814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4768814525f4SDarrick J. Wong 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4769814525f4SDarrick J. Wong 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
47702dc8d9e1SEric Biggers 			EXT4_INODE_SIZE(inode->i_sb) ||
47712dc8d9e1SEric Biggers 		    (ei->i_extra_isize & 3)) {
47728a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
47738a363970STheodore Ts'o 					 "iget: bad extra_isize %u "
47748a363970STheodore Ts'o 					 "(inode size %u)",
47752dc8d9e1SEric Biggers 					 ei->i_extra_isize,
4776814525f4SDarrick J. Wong 					 EXT4_INODE_SIZE(inode->i_sb));
47776a797d27SDarrick J. Wong 			ret = -EFSCORRUPTED;
4778814525f4SDarrick J. Wong 			goto bad_inode;
4779814525f4SDarrick J. Wong 		}
4780814525f4SDarrick J. Wong 	} else
4781814525f4SDarrick J. Wong 		ei->i_extra_isize = 0;
4782814525f4SDarrick J. Wong 
4783814525f4SDarrick J. Wong 	/* Precompute checksum seed for inode metadata */
47849aa5d32bSDmitry Monakhov 	if (ext4_has_metadata_csum(sb)) {
4785814525f4SDarrick J. Wong 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4786814525f4SDarrick J. Wong 		__u32 csum;
4787814525f4SDarrick J. Wong 		__le32 inum = cpu_to_le32(inode->i_ino);
4788814525f4SDarrick J. Wong 		__le32 gen = raw_inode->i_generation;
4789814525f4SDarrick J. Wong 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4790814525f4SDarrick J. Wong 				   sizeof(inum));
4791814525f4SDarrick J. Wong 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4792814525f4SDarrick J. Wong 					      sizeof(gen));
4793814525f4SDarrick J. Wong 	}
4794814525f4SDarrick J. Wong 
47958016e29fSHarshad Shirwadkar 	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
47968016e29fSHarshad Shirwadkar 	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
47978016e29fSHarshad Shirwadkar 	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
47988016e29fSHarshad Shirwadkar 		ext4_error_inode_err(inode, function, line, 0,
47998016e29fSHarshad Shirwadkar 				EFSBADCRC, "iget: checksum invalid");
48006a797d27SDarrick J. Wong 		ret = -EFSBADCRC;
4801814525f4SDarrick J. Wong 		goto bad_inode;
4802814525f4SDarrick J. Wong 	}
4803814525f4SDarrick J. Wong 
4804ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
480508cefc7aSEric W. Biederman 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
480608cefc7aSEric W. Biederman 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
48070b7b7779SKaho Ng 	if (ext4_has_feature_project(sb) &&
4808040cb378SLi Xi 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4809040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4810040cb378SLi Xi 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4811040cb378SLi Xi 	else
4812040cb378SLi Xi 		i_projid = EXT4_DEF_PROJID;
4813040cb378SLi Xi 
4814ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
481508cefc7aSEric W. Biederman 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
481608cefc7aSEric W. Biederman 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4817ac27a0ecSDave Kleikamp 	}
481808cefc7aSEric W. Biederman 	i_uid_write(inode, i_uid);
481908cefc7aSEric W. Biederman 	i_gid_write(inode, i_gid);
4820040cb378SLi Xi 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4821bfe86848SMiklos Szeredi 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4822ac27a0ecSDave Kleikamp 
4823353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
482467cf5b09STao Ma 	ei->i_inline_off = 0;
4825ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
4826ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4827ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
4828ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
4829ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
4830ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
4831ac27a0ecSDave Kleikamp 	 */
4832ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
48335cd74028SBaokun Li 		if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
4834393d1d1dSDr. Tilmann Bubeck 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4835393d1d1dSDr. Tilmann Bubeck 		    ino != EXT4_BOOT_LOADER_INO) {
48365cd74028SBaokun Li 			/* this inode is deleted or unallocated */
48375cd74028SBaokun Li 			if (flags & EXT4_IGET_SPECIAL) {
48385cd74028SBaokun Li 				ext4_error_inode(inode, function, line, 0,
48395cd74028SBaokun Li 						 "iget: special inode unallocated");
48405cd74028SBaokun Li 				ret = -EFSCORRUPTED;
48415cd74028SBaokun Li 			} else
48421d1fe1eeSDavid Howells 				ret = -ESTALE;
4843ac27a0ecSDave Kleikamp 			goto bad_inode;
4844ac27a0ecSDave Kleikamp 		}
4845ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
4846ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
4847ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
4848393d1d1dSDr. Tilmann Bubeck 		 * the process of deleting those.
4849393d1d1dSDr. Tilmann Bubeck 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4850393d1d1dSDr. Tilmann Bubeck 		 * not initialized on a new filesystem. */
4851ac27a0ecSDave Kleikamp 	}
4852ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4853043546e4SIra Weiny 	ext4_set_inode_flags(inode, true);
48540fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
48557973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4856e2b911c5SDarrick J. Wong 	if (ext4_has_feature_64bit(sb))
4857a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
4858a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4859e08ac99fSArtem Blagodarenko 	inode->i_size = ext4_isize(sb, raw_inode);
48607e6e1ef4SDarrick J. Wong 	if ((size = i_size_read(inode)) < 0) {
48618a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
48628a363970STheodore Ts'o 				 "iget: bad i_size value: %lld", size);
48637e6e1ef4SDarrick J. Wong 		ret = -EFSCORRUPTED;
48647e6e1ef4SDarrick J. Wong 		goto bad_inode;
48657e6e1ef4SDarrick J. Wong 	}
486648a34311SJan Kara 	/*
486748a34311SJan Kara 	 * If dir_index is not enabled but there's dir with INDEX flag set,
486848a34311SJan Kara 	 * we'd normally treat htree data as empty space. But with metadata
486948a34311SJan Kara 	 * checksumming that corrupts checksums so forbid that.
487048a34311SJan Kara 	 */
487148a34311SJan Kara 	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
487248a34311SJan Kara 	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
487348a34311SJan Kara 		ext4_error_inode(inode, function, line, 0,
487448a34311SJan Kara 			 "iget: Dir with htree data on filesystem without dir_index feature.");
487548a34311SJan Kara 		ret = -EFSCORRUPTED;
487648a34311SJan Kara 		goto bad_inode;
487748a34311SJan Kara 	}
4878ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
4879a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
4880a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
4881a9e7f447SDmitry Monakhov #endif
4882ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4883ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
4884a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
4885ac27a0ecSDave Kleikamp 	/*
4886ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
4887ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4888ac27a0ecSDave Kleikamp 	 */
4889617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4890ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
4891ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
4892aa75f4d3SHarshad Shirwadkar 	ext4_fc_init_inode(&ei->vfs_inode);
4893ac27a0ecSDave Kleikamp 
4894b436b9beSJan Kara 	/*
4895b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
4896b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
4897b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
4898b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
4899b436b9beSJan Kara 	 * now it is reread from disk.
4900b436b9beSJan Kara 	 */
4901b436b9beSJan Kara 	if (journal) {
4902b436b9beSJan Kara 		transaction_t *transaction;
4903b436b9beSJan Kara 		tid_t tid;
4904b436b9beSJan Kara 
4905a931da6aSTheodore Ts'o 		read_lock(&journal->j_state_lock);
4906b436b9beSJan Kara 		if (journal->j_running_transaction)
4907b436b9beSJan Kara 			transaction = journal->j_running_transaction;
4908b436b9beSJan Kara 		else
4909b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
4910b436b9beSJan Kara 		if (transaction)
4911b436b9beSJan Kara 			tid = transaction->t_tid;
4912b436b9beSJan Kara 		else
4913b436b9beSJan Kara 			tid = journal->j_commit_sequence;
4914a931da6aSTheodore Ts'o 		read_unlock(&journal->j_state_lock);
4915b436b9beSJan Kara 		ei->i_sync_tid = tid;
4916b436b9beSJan Kara 		ei->i_datasync_tid = tid;
4917b436b9beSJan Kara 	}
4918b436b9beSJan Kara 
49190040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4920ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
4921ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
49222dc8d9e1SEric Biggers 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4923617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4924617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
4925ac27a0ecSDave Kleikamp 		} else {
4926eb9b5f01STheodore Ts'o 			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4927eb9b5f01STheodore Ts'o 			if (ret)
4928eb9b5f01STheodore Ts'o 				goto bad_inode;
4929ac27a0ecSDave Kleikamp 		}
4930814525f4SDarrick J. Wong 	}
4931ac27a0ecSDave Kleikamp 
4932ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4933ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4934ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4935ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4936ef7f3835SKalpak Shah 
4937ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4938ee73f9a5SJeff Layton 		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4939ee73f9a5SJeff Layton 
494025ec56b5SJean Noel Cordenner 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
494125ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4942ee73f9a5SJeff Layton 				ivers |=
494325ec56b5SJean Noel Cordenner 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
494425ec56b5SJean Noel Cordenner 		}
4945e254d1afSEryu Guan 		ext4_inode_set_iversion_queried(inode, ivers);
4946c4f65706STheodore Ts'o 	}
494725ec56b5SJean Noel Cordenner 
4948c4b5a614STheodore Ts'o 	ret = 0;
4949485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
4950ce9f24ccSJan Kara 	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
49518a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
49528a363970STheodore Ts'o 				 "iget: bad extended attribute block %llu",
495324676da4STheodore Ts'o 				 ei->i_file_acl);
49546a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
4955485c26ecSTheodore Ts'o 		goto bad_inode;
4956f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
4957bc716523SLiu Song 		/* validate the block references in the inode */
49588016e29fSHarshad Shirwadkar 		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
49598016e29fSHarshad Shirwadkar 			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4960fe2c8191SThiemo Nagel 			(S_ISLNK(inode->i_mode) &&
49618016e29fSHarshad Shirwadkar 			!ext4_inode_is_fast_symlink(inode)))) {
4962bc716523SLiu Song 			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4963bc716523SLiu Song 				ret = ext4_ext_check_inode(inode);
4964bc716523SLiu Song 			else
49651f7d1e77STheodore Ts'o 				ret = ext4_ind_check_inode(inode);
4966fe2c8191SThiemo Nagel 		}
4967f19d5870STao Ma 	}
4968567f3e9aSTheodore Ts'o 	if (ret)
49697a262f7cSAneesh Kumar K.V 		goto bad_inode;
49707a262f7cSAneesh Kumar K.V 
4971ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
4972617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
4973617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
4974617ba13bSMingming Cao 		ext4_set_aops(inode);
4975ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
4976617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
4977617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
4978ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
49796390d33bSLuis R. Rodriguez 		/* VFS does not allow setting these so must be corruption */
49806390d33bSLuis R. Rodriguez 		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
49818a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
49828a363970STheodore Ts'o 					 "iget: immutable or append flags "
49838a363970STheodore Ts'o 					 "not allowed on symlinks");
49846390d33bSLuis R. Rodriguez 			ret = -EFSCORRUPTED;
49856390d33bSLuis R. Rodriguez 			goto bad_inode;
49866390d33bSLuis R. Rodriguez 		}
4987592ddec7SChandan Rajendra 		if (IS_ENCRYPTED(inode)) {
4988a7a67e8aSAl Viro 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
4989a7a67e8aSAl Viro 		} else if (ext4_inode_is_fast_symlink(inode)) {
499075e7566bSAl Viro 			inode->i_link = (char *)ei->i_data;
4991617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
4992e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
4993e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
4994e83c1397SDuane Griffin 		} else {
4995617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
4996ac27a0ecSDave Kleikamp 		}
4997563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4998563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4999617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
5000ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
5001ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5002ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5003ac27a0ecSDave Kleikamp 		else
5004ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5005ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5006393d1d1dSDr. Tilmann Bubeck 	} else if (ino == EXT4_BOOT_LOADER_INO) {
5007393d1d1dSDr. Tilmann Bubeck 		make_bad_inode(inode);
5008563bdd61STheodore Ts'o 	} else {
50096a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
50108a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
50118a363970STheodore Ts'o 				 "iget: bogus i_mode (%o)", inode->i_mode);
5012563bdd61STheodore Ts'o 		goto bad_inode;
5013ac27a0ecSDave Kleikamp 	}
50146456ca65STheodore Ts'o 	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
50156456ca65STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
50166456ca65STheodore Ts'o 				 "casefold flag without casefold feature");
501763b1e9bcSBaokun Li 	if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD)) {
501863b1e9bcSBaokun Li 		ext4_error_inode(inode, function, line, 0,
501963b1e9bcSBaokun Li 				 "bad inode without EXT4_IGET_BAD flag");
502063b1e9bcSBaokun Li 		ret = -EUCLEAN;
502163b1e9bcSBaokun Li 		goto bad_inode;
502263b1e9bcSBaokun Li 	}
5023dec214d0STahsin Erdogan 
502463b1e9bcSBaokun Li 	brelse(iloc.bh);
50251d1fe1eeSDavid Howells 	unlock_new_inode(inode);
50261d1fe1eeSDavid Howells 	return inode;
5027ac27a0ecSDave Kleikamp 
5028ac27a0ecSDave Kleikamp bad_inode:
5029567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
50301d1fe1eeSDavid Howells 	iget_failed(inode);
50311d1fe1eeSDavid Howells 	return ERR_PTR(ret);
5032ac27a0ecSDave Kleikamp }
5033ac27a0ecSDave Kleikamp 
50343f19b2abSDavid Howells static void __ext4_update_other_inode_time(struct super_block *sb,
50353f19b2abSDavid Howells 					   unsigned long orig_ino,
50363f19b2abSDavid Howells 					   unsigned long ino,
50373f19b2abSDavid Howells 					   struct ext4_inode *raw_inode)
5038a26f4992STheodore Ts'o {
50393f19b2abSDavid Howells 	struct inode *inode;
5040a26f4992STheodore Ts'o 
50413f19b2abSDavid Howells 	inode = find_inode_by_ino_rcu(sb, ino);
50423f19b2abSDavid Howells 	if (!inode)
50433f19b2abSDavid Howells 		return;
50443f19b2abSDavid Howells 
5045ed296c6cSEric Biggers 	if (!inode_is_dirtytime_only(inode))
50463f19b2abSDavid Howells 		return;
50473f19b2abSDavid Howells 
5048a26f4992STheodore Ts'o 	spin_lock(&inode->i_lock);
5049ed296c6cSEric Biggers 	if (inode_is_dirtytime_only(inode)) {
5050a26f4992STheodore Ts'o 		struct ext4_inode_info	*ei = EXT4_I(inode);
5051a26f4992STheodore Ts'o 
50525fcd5750SJan Kara 		inode->i_state &= ~I_DIRTY_TIME;
5053a26f4992STheodore Ts'o 		spin_unlock(&inode->i_lock);
5054a26f4992STheodore Ts'o 
5055a26f4992STheodore Ts'o 		spin_lock(&ei->i_raw_lock);
50563f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
50573f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
50583f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
50593f19b2abSDavid Howells 		ext4_inode_csum_set(inode, raw_inode, ei);
5060a26f4992STheodore Ts'o 		spin_unlock(&ei->i_raw_lock);
50613f19b2abSDavid Howells 		trace_ext4_other_inode_update_time(inode, orig_ino);
50623f19b2abSDavid Howells 		return;
5063a26f4992STheodore Ts'o 	}
5064a26f4992STheodore Ts'o 	spin_unlock(&inode->i_lock);
5065a26f4992STheodore Ts'o }
5066a26f4992STheodore Ts'o 
5067a26f4992STheodore Ts'o /*
5068a26f4992STheodore Ts'o  * Opportunistically update the other time fields for other inodes in
5069a26f4992STheodore Ts'o  * the same inode table block.
5070a26f4992STheodore Ts'o  */
5071a26f4992STheodore Ts'o static void ext4_update_other_inodes_time(struct super_block *sb,
5072a26f4992STheodore Ts'o 					  unsigned long orig_ino, char *buf)
5073a26f4992STheodore Ts'o {
5074a26f4992STheodore Ts'o 	unsigned long ino;
5075a26f4992STheodore Ts'o 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5076a26f4992STheodore Ts'o 	int inode_size = EXT4_INODE_SIZE(sb);
5077a26f4992STheodore Ts'o 
50780f0ff9a9STheodore Ts'o 	/*
50790f0ff9a9STheodore Ts'o 	 * Calculate the first inode in the inode table block.  Inode
50800f0ff9a9STheodore Ts'o 	 * numbers are one-based.  That is, the first inode in a block
50810f0ff9a9STheodore Ts'o 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
50820f0ff9a9STheodore Ts'o 	 */
50830f0ff9a9STheodore Ts'o 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
50843f19b2abSDavid Howells 	rcu_read_lock();
5085a26f4992STheodore Ts'o 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5086a26f4992STheodore Ts'o 		if (ino == orig_ino)
5087a26f4992STheodore Ts'o 			continue;
50883f19b2abSDavid Howells 		__ext4_update_other_inode_time(sb, orig_ino, ino,
50893f19b2abSDavid Howells 					       (struct ext4_inode *)buf);
5090a26f4992STheodore Ts'o 	}
50913f19b2abSDavid Howells 	rcu_read_unlock();
5092a26f4992STheodore Ts'o }
5093a26f4992STheodore Ts'o 
5094664bd38bSZhang Yi /*
5095664bd38bSZhang Yi  * Post the struct inode info into an on-disk inode location in the
5096664bd38bSZhang Yi  * buffer-cache.  This gobbles the caller's reference to the
5097664bd38bSZhang Yi  * buffer_head in the inode location struct.
5098664bd38bSZhang Yi  *
5099664bd38bSZhang Yi  * The caller must have write access to iloc->bh.
5100664bd38bSZhang Yi  */
5101664bd38bSZhang Yi static int ext4_do_update_inode(handle_t *handle,
5102664bd38bSZhang Yi 				struct inode *inode,
5103664bd38bSZhang Yi 				struct ext4_iloc *iloc)
5104664bd38bSZhang Yi {
5105664bd38bSZhang Yi 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5106664bd38bSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
5107664bd38bSZhang Yi 	struct buffer_head *bh = iloc->bh;
5108664bd38bSZhang Yi 	struct super_block *sb = inode->i_sb;
5109664bd38bSZhang Yi 	int err;
5110664bd38bSZhang Yi 	int need_datasync = 0, set_large_file = 0;
5111664bd38bSZhang Yi 
5112664bd38bSZhang Yi 	spin_lock(&ei->i_raw_lock);
5113664bd38bSZhang Yi 
5114664bd38bSZhang Yi 	/*
5115664bd38bSZhang Yi 	 * For fields not tracked in the in-memory inode, initialise them
5116664bd38bSZhang Yi 	 * to zero for new inodes.
5117664bd38bSZhang Yi 	 */
5118664bd38bSZhang Yi 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5119664bd38bSZhang Yi 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5120664bd38bSZhang Yi 
5121664bd38bSZhang Yi 	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5122664bd38bSZhang Yi 		need_datasync = 1;
5123664bd38bSZhang Yi 	if (ei->i_disksize > 0x7fffffffULL) {
5124664bd38bSZhang Yi 		if (!ext4_has_feature_large_file(sb) ||
5125664bd38bSZhang Yi 		    EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5126664bd38bSZhang Yi 			set_large_file = 1;
5127664bd38bSZhang Yi 	}
5128664bd38bSZhang Yi 
5129664bd38bSZhang Yi 	err = ext4_fill_raw_inode(inode, raw_inode);
5130202ee5dfSTheodore Ts'o 	spin_unlock(&ei->i_raw_lock);
5131baaae979SZhang Yi 	if (err) {
5132baaae979SZhang Yi 		EXT4_ERROR_INODE(inode, "corrupted inode contents");
5133baaae979SZhang Yi 		goto out_brelse;
5134baaae979SZhang Yi 	}
5135baaae979SZhang Yi 
51361751e8a6SLinus Torvalds 	if (inode->i_sb->s_flags & SB_LAZYTIME)
5137a26f4992STheodore Ts'o 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5138a26f4992STheodore Ts'o 					      bh->b_data);
5139202ee5dfSTheodore Ts'o 
51400390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
51417d8bd3c7SShijie Luo 	err = ext4_handle_dirty_metadata(handle, NULL, bh);
51427d8bd3c7SShijie Luo 	if (err)
5143baaae979SZhang Yi 		goto out_error;
514419f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5145202ee5dfSTheodore Ts'o 	if (set_large_file) {
51465d601255Sliang xie 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5147188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, sb,
5148188c299eSJan Kara 						    EXT4_SB(sb)->s_sbh,
5149188c299eSJan Kara 						    EXT4_JTR_NONE);
5150202ee5dfSTheodore Ts'o 		if (err)
5151baaae979SZhang Yi 			goto out_error;
515205c2c00fSJan Kara 		lock_buffer(EXT4_SB(sb)->s_sbh);
5153e2b911c5SDarrick J. Wong 		ext4_set_feature_large_file(sb);
515405c2c00fSJan Kara 		ext4_superblock_csum_set(sb);
515505c2c00fSJan Kara 		unlock_buffer(EXT4_SB(sb)->s_sbh);
5156202ee5dfSTheodore Ts'o 		ext4_handle_sync(handle);
5157a3f5cf14SJan Kara 		err = ext4_handle_dirty_metadata(handle, NULL,
5158a3f5cf14SJan Kara 						 EXT4_SB(sb)->s_sbh);
5159202ee5dfSTheodore Ts'o 	}
5160b71fc079SJan Kara 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5161baaae979SZhang Yi out_error:
5162baaae979SZhang Yi 	ext4_std_error(inode->i_sb, err);
5163ac27a0ecSDave Kleikamp out_brelse:
5164ac27a0ecSDave Kleikamp 	brelse(bh);
5165ac27a0ecSDave Kleikamp 	return err;
5166ac27a0ecSDave Kleikamp }
5167ac27a0ecSDave Kleikamp 
5168ac27a0ecSDave Kleikamp /*
5169617ba13bSMingming Cao  * ext4_write_inode()
5170ac27a0ecSDave Kleikamp  *
5171ac27a0ecSDave Kleikamp  * We are called from a few places:
5172ac27a0ecSDave Kleikamp  *
517387f7e416STheodore Ts'o  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5174ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
51754907cb7bSAnatol Pomozov  *   transaction to commit.
5176ac27a0ecSDave Kleikamp  *
517787f7e416STheodore Ts'o  * - Within flush work (sys_sync(), kupdate and such).
517887f7e416STheodore Ts'o  *   We wait on commit, if told to.
5179ac27a0ecSDave Kleikamp  *
518087f7e416STheodore Ts'o  * - Within iput_final() -> write_inode_now()
518187f7e416STheodore Ts'o  *   We wait on commit, if told to.
5182ac27a0ecSDave Kleikamp  *
5183ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
5184ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
518587f7e416STheodore Ts'o  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
518687f7e416STheodore Ts'o  * writeback.
5187ac27a0ecSDave Kleikamp  *
5188ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
5189ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5190ac27a0ecSDave Kleikamp  * which we are interested.
5191ac27a0ecSDave Kleikamp  *
5192ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
5193ac27a0ecSDave Kleikamp  *
5194ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
5195ac27a0ecSDave Kleikamp  *	stuff();
5196ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
5197ac27a0ecSDave Kleikamp  *
519887f7e416STheodore Ts'o  * is in error because write_inode() could occur while `stuff()' is running,
519987f7e416STheodore Ts'o  * and the new i_size will be lost.  Plus the inode will no longer be on the
520087f7e416STheodore Ts'o  * superblock's dirty inode list.
5201ac27a0ecSDave Kleikamp  */
5202a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5203ac27a0ecSDave Kleikamp {
520491ac6f43SFrank Mayhar 	int err;
520591ac6f43SFrank Mayhar 
520618f2c4fcSTheodore Ts'o 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
520718f2c4fcSTheodore Ts'o 	    sb_rdonly(inode->i_sb))
5208ac27a0ecSDave Kleikamp 		return 0;
5209ac27a0ecSDave Kleikamp 
521018f2c4fcSTheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
521118f2c4fcSTheodore Ts'o 		return -EIO;
521218f2c4fcSTheodore Ts'o 
521391ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
5214617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
52154978c659SJan Kara 			ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5216ac27a0ecSDave Kleikamp 			dump_stack();
5217ac27a0ecSDave Kleikamp 			return -EIO;
5218ac27a0ecSDave Kleikamp 		}
5219ac27a0ecSDave Kleikamp 
522010542c22SJan Kara 		/*
522110542c22SJan Kara 		 * No need to force transaction in WB_SYNC_NONE mode. Also
522210542c22SJan Kara 		 * ext4_sync_fs() will force the commit after everything is
522310542c22SJan Kara 		 * written.
522410542c22SJan Kara 		 */
522510542c22SJan Kara 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5226ac27a0ecSDave Kleikamp 			return 0;
5227ac27a0ecSDave Kleikamp 
5228aa75f4d3SHarshad Shirwadkar 		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
522918f2c4fcSTheodore Ts'o 						EXT4_I(inode)->i_sync_tid);
523091ac6f43SFrank Mayhar 	} else {
523191ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
523291ac6f43SFrank Mayhar 
52338016e29fSHarshad Shirwadkar 		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
523491ac6f43SFrank Mayhar 		if (err)
523591ac6f43SFrank Mayhar 			return err;
523610542c22SJan Kara 		/*
523710542c22SJan Kara 		 * sync(2) will flush the whole buffer cache. No need to do
523810542c22SJan Kara 		 * it here separately for each inode.
523910542c22SJan Kara 		 */
524010542c22SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5241830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
5242830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
524354d3adbcSTheodore Ts'o 			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5244c398eda0STheodore Ts'o 					       "IO error syncing inode");
5245830156c7SFrank Mayhar 			err = -EIO;
5246830156c7SFrank Mayhar 		}
5247fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
524891ac6f43SFrank Mayhar 	}
524991ac6f43SFrank Mayhar 	return err;
5250ac27a0ecSDave Kleikamp }
5251ac27a0ecSDave Kleikamp 
5252ac27a0ecSDave Kleikamp /*
5253ccd16945SMatthew Wilcox (Oracle)  * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5254ccd16945SMatthew Wilcox (Oracle)  * buffers that are attached to a folio straddling i_size and are undergoing
525553e87268SJan Kara  * commit. In that case we have to wait for commit to finish and try again.
525653e87268SJan Kara  */
525753e87268SJan Kara static void ext4_wait_for_tail_page_commit(struct inode *inode)
525853e87268SJan Kara {
525953e87268SJan Kara 	unsigned offset;
526053e87268SJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
526153e87268SJan Kara 	tid_t commit_tid = 0;
526253e87268SJan Kara 	int ret;
526353e87268SJan Kara 
526409cbfeafSKirill A. Shutemov 	offset = inode->i_size & (PAGE_SIZE - 1);
526553e87268SJan Kara 	/*
5266ccd16945SMatthew Wilcox (Oracle) 	 * If the folio is fully truncated, we don't need to wait for any commit
5267ccd16945SMatthew Wilcox (Oracle) 	 * (and we even should not as __ext4_journalled_invalidate_folio() may
5268ccd16945SMatthew Wilcox (Oracle) 	 * strip all buffers from the folio but keep the folio dirty which can then
52693f079114SJan Kara 	 * confuse e.g. concurrent ext4_writepages() seeing dirty folio without
5270565333a1Syangerkun 	 * buffers). Also we don't need to wait for any commit if all buffers in
5271ccd16945SMatthew Wilcox (Oracle) 	 * the folio remain valid. This is most beneficial for the common case of
5272565333a1Syangerkun 	 * blocksize == PAGESIZE.
527353e87268SJan Kara 	 */
5274565333a1Syangerkun 	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
527553e87268SJan Kara 		return;
527653e87268SJan Kara 	while (1) {
5277ccd16945SMatthew Wilcox (Oracle) 		struct folio *folio = filemap_lock_folio(inode->i_mapping,
527809cbfeafSKirill A. Shutemov 				      inode->i_size >> PAGE_SHIFT);
5279ccd16945SMatthew Wilcox (Oracle) 		if (!folio)
528053e87268SJan Kara 			return;
5281ccd16945SMatthew Wilcox (Oracle) 		ret = __ext4_journalled_invalidate_folio(folio, offset,
5282ccd16945SMatthew Wilcox (Oracle) 						folio_size(folio) - offset);
5283ccd16945SMatthew Wilcox (Oracle) 		folio_unlock(folio);
5284ccd16945SMatthew Wilcox (Oracle) 		folio_put(folio);
528553e87268SJan Kara 		if (ret != -EBUSY)
528653e87268SJan Kara 			return;
528753e87268SJan Kara 		commit_tid = 0;
528853e87268SJan Kara 		read_lock(&journal->j_state_lock);
528953e87268SJan Kara 		if (journal->j_committing_transaction)
529053e87268SJan Kara 			commit_tid = journal->j_committing_transaction->t_tid;
529153e87268SJan Kara 		read_unlock(&journal->j_state_lock);
529253e87268SJan Kara 		if (commit_tid)
529353e87268SJan Kara 			jbd2_log_wait_commit(journal, commit_tid);
529453e87268SJan Kara 	}
529553e87268SJan Kara }
529653e87268SJan Kara 
529753e87268SJan Kara /*
5298617ba13bSMingming Cao  * ext4_setattr()
5299ac27a0ecSDave Kleikamp  *
5300ac27a0ecSDave Kleikamp  * Called from notify_change.
5301ac27a0ecSDave Kleikamp  *
5302ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
5303ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
5304ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
5305ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
5306ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
5307ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
5308ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
5309ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
5310ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
5311ac27a0ecSDave Kleikamp  *
5312678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
5313678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
5314678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
5315678aaf48SJan Kara  * This way we are sure that all the data written in the previous
5316678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
5317678aaf48SJan Kara  * writeback).
5318678aaf48SJan Kara  *
5319f340b3d9Shongnanli  * Called with inode->i_rwsem down.
5320ac27a0ecSDave Kleikamp  */
5321c1632a0fSChristian Brauner int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5322549c7297SChristian Brauner 		 struct iattr *attr)
5323ac27a0ecSDave Kleikamp {
53242b0143b5SDavid Howells 	struct inode *inode = d_inode(dentry);
5325ac27a0ecSDave Kleikamp 	int error, rc = 0;
53263d287de3SDmitry Monakhov 	int orphan = 0;
5327ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
5328a642c2c0SJeff Layton 	bool inc_ivers = true;
5329ac27a0ecSDave Kleikamp 
53300db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
53310db1ff22STheodore Ts'o 		return -EIO;
53320db1ff22STheodore Ts'o 
533302b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
533402b016caSTheodore Ts'o 		return -EPERM;
533502b016caSTheodore Ts'o 
533602b016caSTheodore Ts'o 	if (unlikely(IS_APPEND(inode) &&
533702b016caSTheodore Ts'o 		     (ia_valid & (ATTR_MODE | ATTR_UID |
533802b016caSTheodore Ts'o 				  ATTR_GID | ATTR_TIMES_SET))))
533902b016caSTheodore Ts'o 		return -EPERM;
534002b016caSTheodore Ts'o 
5341c1632a0fSChristian Brauner 	error = setattr_prepare(idmap, dentry, attr);
5342ac27a0ecSDave Kleikamp 	if (error)
5343ac27a0ecSDave Kleikamp 		return error;
5344ac27a0ecSDave Kleikamp 
53453ce2b8ddSEric Biggers 	error = fscrypt_prepare_setattr(dentry, attr);
53463ce2b8ddSEric Biggers 	if (error)
53473ce2b8ddSEric Biggers 		return error;
53483ce2b8ddSEric Biggers 
5349c93d8f88SEric Biggers 	error = fsverity_prepare_setattr(dentry, attr);
5350c93d8f88SEric Biggers 	if (error)
5351c93d8f88SEric Biggers 		return error;
5352c93d8f88SEric Biggers 
5353f861646aSChristian Brauner 	if (is_quota_modification(idmap, inode, attr)) {
5354a7cdadeeSJan Kara 		error = dquot_initialize(inode);
5355a7cdadeeSJan Kara 		if (error)
5356a7cdadeeSJan Kara 			return error;
5357a7cdadeeSJan Kara 	}
53582729cfdcSHarshad Shirwadkar 
53590dbe12f2SChristian Brauner 	if (i_uid_needs_update(idmap, attr, inode) ||
53600dbe12f2SChristian Brauner 	    i_gid_needs_update(idmap, attr, inode)) {
5361ac27a0ecSDave Kleikamp 		handle_t *handle;
5362ac27a0ecSDave Kleikamp 
5363ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
5364ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
53659924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
53669924a92aSTheodore Ts'o 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5367194074acSDmitry Monakhov 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5368ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
5369ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
5370ac27a0ecSDave Kleikamp 			goto err_out;
5371ac27a0ecSDave Kleikamp 		}
53727a9ca53aSTahsin Erdogan 
53737a9ca53aSTahsin Erdogan 		/* dquot_transfer() calls back ext4_get_inode_usage() which
53747a9ca53aSTahsin Erdogan 		 * counts xattr inode references.
53757a9ca53aSTahsin Erdogan 		 */
53767a9ca53aSTahsin Erdogan 		down_read(&EXT4_I(inode)->xattr_sem);
5377f861646aSChristian Brauner 		error = dquot_transfer(idmap, inode, attr);
53787a9ca53aSTahsin Erdogan 		up_read(&EXT4_I(inode)->xattr_sem);
53797a9ca53aSTahsin Erdogan 
5380ac27a0ecSDave Kleikamp 		if (error) {
5381617ba13bSMingming Cao 			ext4_journal_stop(handle);
5382ac27a0ecSDave Kleikamp 			return error;
5383ac27a0ecSDave Kleikamp 		}
5384ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
5385ac27a0ecSDave Kleikamp 		 * one transaction */
53860dbe12f2SChristian Brauner 		i_uid_update(idmap, attr, inode);
53870dbe12f2SChristian Brauner 		i_gid_update(idmap, attr, inode);
5388617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
5389617ba13bSMingming Cao 		ext4_journal_stop(handle);
5390512c15efSPan Bian 		if (unlikely(error)) {
53914209ae12SHarshad Shirwadkar 			return error;
5392ac27a0ecSDave Kleikamp 		}
5393512c15efSPan Bian 	}
5394ac27a0ecSDave Kleikamp 
53953da40c7bSJosef Bacik 	if (attr->ia_valid & ATTR_SIZE) {
53965208386cSJan Kara 		handle_t *handle;
53973da40c7bSJosef Bacik 		loff_t oldsize = inode->i_size;
5398f4534c9fSYe Bin 		loff_t old_disksize;
5399b9c1c267SJan Kara 		int shrink = (attr->ia_size < inode->i_size);
5400562c72aaSChristoph Hellwig 
540112e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5402e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5403e2b46574SEric Sandeen 
5404aa75f4d3SHarshad Shirwadkar 			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
54050c095c7fSTheodore Ts'o 				return -EFBIG;
5406e2b46574SEric Sandeen 			}
5407aa75f4d3SHarshad Shirwadkar 		}
5408aa75f4d3SHarshad Shirwadkar 		if (!S_ISREG(inode->i_mode)) {
54093da40c7bSJosef Bacik 			return -EINVAL;
5410aa75f4d3SHarshad Shirwadkar 		}
5411dff6efc3SChristoph Hellwig 
5412a642c2c0SJeff Layton 		if (attr->ia_size == inode->i_size)
5413a642c2c0SJeff Layton 			inc_ivers = false;
5414dff6efc3SChristoph Hellwig 
5415b9c1c267SJan Kara 		if (shrink) {
5416b9c1c267SJan Kara 			if (ext4_should_order_data(inode)) {
54175208386cSJan Kara 				error = ext4_begin_ordered_truncate(inode,
54185208386cSJan Kara 							    attr->ia_size);
54195208386cSJan Kara 				if (error)
54205208386cSJan Kara 					goto err_out;
54215208386cSJan Kara 			}
5422b9c1c267SJan Kara 			/*
5423b9c1c267SJan Kara 			 * Blocks are going to be removed from the inode. Wait
5424b9c1c267SJan Kara 			 * for dio in flight.
5425b9c1c267SJan Kara 			 */
5426b9c1c267SJan Kara 			inode_dio_wait(inode);
5427b9c1c267SJan Kara 		}
5428b9c1c267SJan Kara 
5429d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
5430b9c1c267SJan Kara 
5431b9c1c267SJan Kara 		rc = ext4_break_layouts(inode);
5432b9c1c267SJan Kara 		if (rc) {
5433d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
5434aa75f4d3SHarshad Shirwadkar 			goto err_out;
5435b9c1c267SJan Kara 		}
5436b9c1c267SJan Kara 
54373da40c7bSJosef Bacik 		if (attr->ia_size != inode->i_size) {
54389924a92aSTheodore Ts'o 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5439ac27a0ecSDave Kleikamp 			if (IS_ERR(handle)) {
5440ac27a0ecSDave Kleikamp 				error = PTR_ERR(handle);
5441b9c1c267SJan Kara 				goto out_mmap_sem;
5442ac27a0ecSDave Kleikamp 			}
54433da40c7bSJosef Bacik 			if (ext4_handle_valid(handle) && shrink) {
5444617ba13bSMingming Cao 				error = ext4_orphan_add(handle, inode);
54453d287de3SDmitry Monakhov 				orphan = 1;
54463d287de3SDmitry Monakhov 			}
5447911af577SEryu Guan 			/*
5448911af577SEryu Guan 			 * Update c/mtime on truncate up, ext4_truncate() will
5449911af577SEryu Guan 			 * update c/mtime in shrink case below
5450911af577SEryu Guan 			 */
5451911af577SEryu Guan 			if (!shrink) {
5452eeca7ea1SDeepa Dinamani 				inode->i_mtime = current_time(inode);
5453911af577SEryu Guan 				inode->i_ctime = inode->i_mtime;
5454911af577SEryu Guan 			}
5455aa75f4d3SHarshad Shirwadkar 
5456aa75f4d3SHarshad Shirwadkar 			if (shrink)
5457a80f7fcfSHarshad Shirwadkar 				ext4_fc_track_range(handle, inode,
5458aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5459aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
54609725958bSXin Yin 					EXT_MAX_BLOCKS - 1);
5461aa75f4d3SHarshad Shirwadkar 			else
5462aa75f4d3SHarshad Shirwadkar 				ext4_fc_track_range(
5463a80f7fcfSHarshad Shirwadkar 					handle, inode,
5464aa75f4d3SHarshad Shirwadkar 					(oldsize > 0 ? oldsize - 1 : oldsize) >>
5465aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
5466aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5467aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits);
5468aa75f4d3SHarshad Shirwadkar 
546990e775b7SJan Kara 			down_write(&EXT4_I(inode)->i_data_sem);
5470f4534c9fSYe Bin 			old_disksize = EXT4_I(inode)->i_disksize;
5471617ba13bSMingming Cao 			EXT4_I(inode)->i_disksize = attr->ia_size;
5472617ba13bSMingming Cao 			rc = ext4_mark_inode_dirty(handle, inode);
5473ac27a0ecSDave Kleikamp 			if (!error)
5474ac27a0ecSDave Kleikamp 				error = rc;
547590e775b7SJan Kara 			/*
547690e775b7SJan Kara 			 * We have to update i_size under i_data_sem together
547790e775b7SJan Kara 			 * with i_disksize to avoid races with writeback code
547890e775b7SJan Kara 			 * running ext4_wb_update_i_disksize().
547990e775b7SJan Kara 			 */
548090e775b7SJan Kara 			if (!error)
548190e775b7SJan Kara 				i_size_write(inode, attr->ia_size);
5482f4534c9fSYe Bin 			else
5483f4534c9fSYe Bin 				EXT4_I(inode)->i_disksize = old_disksize;
548490e775b7SJan Kara 			up_write(&EXT4_I(inode)->i_data_sem);
5485617ba13bSMingming Cao 			ext4_journal_stop(handle);
5486b9c1c267SJan Kara 			if (error)
5487b9c1c267SJan Kara 				goto out_mmap_sem;
548882a25b02SJan Kara 			if (!shrink) {
5489b9c1c267SJan Kara 				pagecache_isize_extended(inode, oldsize,
5490b9c1c267SJan Kara 							 inode->i_size);
5491b9c1c267SJan Kara 			} else if (ext4_should_journal_data(inode)) {
549282a25b02SJan Kara 				ext4_wait_for_tail_page_commit(inode);
5493b9c1c267SJan Kara 			}
5494430657b6SRoss Zwisler 		}
5495430657b6SRoss Zwisler 
549653e87268SJan Kara 		/*
549753e87268SJan Kara 		 * Truncate pagecache after we've waited for commit
549853e87268SJan Kara 		 * in data=journal mode to make pages freeable.
549953e87268SJan Kara 		 */
55007caef267SKirill A. Shutemov 		truncate_pagecache(inode, inode->i_size);
5501b9c1c267SJan Kara 		/*
5502b9c1c267SJan Kara 		 * Call ext4_truncate() even if i_size didn't change to
5503b9c1c267SJan Kara 		 * truncate possible preallocated blocks.
5504b9c1c267SJan Kara 		 */
5505b9c1c267SJan Kara 		if (attr->ia_size <= oldsize) {
55062c98eb5eSTheodore Ts'o 			rc = ext4_truncate(inode);
55072c98eb5eSTheodore Ts'o 			if (rc)
55082c98eb5eSTheodore Ts'o 				error = rc;
55092c98eb5eSTheodore Ts'o 		}
5510b9c1c267SJan Kara out_mmap_sem:
5511d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
55123da40c7bSJosef Bacik 	}
5513ac27a0ecSDave Kleikamp 
55142c98eb5eSTheodore Ts'o 	if (!error) {
5515a642c2c0SJeff Layton 		if (inc_ivers)
5516a642c2c0SJeff Layton 			inode_inc_iversion(inode);
5517c1632a0fSChristian Brauner 		setattr_copy(idmap, inode, attr);
55181025774cSChristoph Hellwig 		mark_inode_dirty(inode);
55191025774cSChristoph Hellwig 	}
55201025774cSChristoph Hellwig 
55211025774cSChristoph Hellwig 	/*
55221025774cSChristoph Hellwig 	 * If the call to ext4_truncate failed to get a transaction handle at
55231025774cSChristoph Hellwig 	 * all, we need to clean up the in-core orphan list manually.
55241025774cSChristoph Hellwig 	 */
55253d287de3SDmitry Monakhov 	if (orphan && inode->i_nlink)
5526617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
5527ac27a0ecSDave Kleikamp 
55282c98eb5eSTheodore Ts'o 	if (!error && (ia_valid & ATTR_MODE))
552913e83a49SChristian Brauner 		rc = posix_acl_chmod(idmap, dentry, inode->i_mode);
5530ac27a0ecSDave Kleikamp 
5531ac27a0ecSDave Kleikamp err_out:
5532aa75f4d3SHarshad Shirwadkar 	if  (error)
5533617ba13bSMingming Cao 		ext4_std_error(inode->i_sb, error);
5534ac27a0ecSDave Kleikamp 	if (!error)
5535ac27a0ecSDave Kleikamp 		error = rc;
5536ac27a0ecSDave Kleikamp 	return error;
5537ac27a0ecSDave Kleikamp }
5538ac27a0ecSDave Kleikamp 
55398434ef1dSEric Biggers u32 ext4_dio_alignment(struct inode *inode)
55408434ef1dSEric Biggers {
55418434ef1dSEric Biggers 	if (fsverity_active(inode))
55428434ef1dSEric Biggers 		return 0;
55438434ef1dSEric Biggers 	if (ext4_should_journal_data(inode))
55448434ef1dSEric Biggers 		return 0;
55458434ef1dSEric Biggers 	if (ext4_has_inline_data(inode))
55468434ef1dSEric Biggers 		return 0;
55478434ef1dSEric Biggers 	if (IS_ENCRYPTED(inode)) {
55488434ef1dSEric Biggers 		if (!fscrypt_dio_supported(inode))
55498434ef1dSEric Biggers 			return 0;
55508434ef1dSEric Biggers 		return i_blocksize(inode);
55518434ef1dSEric Biggers 	}
55528434ef1dSEric Biggers 	return 1; /* use the iomap defaults */
55538434ef1dSEric Biggers }
55548434ef1dSEric Biggers 
5555b74d24f7SChristian Brauner int ext4_getattr(struct mnt_idmap *idmap, const struct path *path,
5556549c7297SChristian Brauner 		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
55573e3398a0SMingming Cao {
555899652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
555999652ea5SDavid Howells 	struct ext4_inode *raw_inode;
556099652ea5SDavid Howells 	struct ext4_inode_info *ei = EXT4_I(inode);
556199652ea5SDavid Howells 	unsigned int flags;
55623e3398a0SMingming Cao 
5563d4c5e960STheodore Ts'o 	if ((request_mask & STATX_BTIME) &&
5564d4c5e960STheodore Ts'o 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
556599652ea5SDavid Howells 		stat->result_mask |= STATX_BTIME;
556699652ea5SDavid Howells 		stat->btime.tv_sec = ei->i_crtime.tv_sec;
556799652ea5SDavid Howells 		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
556899652ea5SDavid Howells 	}
556999652ea5SDavid Howells 
55708434ef1dSEric Biggers 	/*
55718434ef1dSEric Biggers 	 * Return the DIO alignment restrictions if requested.  We only return
55728434ef1dSEric Biggers 	 * this information when requested, since on encrypted files it might
55738434ef1dSEric Biggers 	 * take a fair bit of work to get if the file wasn't opened recently.
55748434ef1dSEric Biggers 	 */
55758434ef1dSEric Biggers 	if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
55768434ef1dSEric Biggers 		u32 dio_align = ext4_dio_alignment(inode);
55778434ef1dSEric Biggers 
55788434ef1dSEric Biggers 		stat->result_mask |= STATX_DIOALIGN;
55798434ef1dSEric Biggers 		if (dio_align == 1) {
55808434ef1dSEric Biggers 			struct block_device *bdev = inode->i_sb->s_bdev;
55818434ef1dSEric Biggers 
55828434ef1dSEric Biggers 			/* iomap defaults */
55838434ef1dSEric Biggers 			stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
55848434ef1dSEric Biggers 			stat->dio_offset_align = bdev_logical_block_size(bdev);
55858434ef1dSEric Biggers 		} else {
55868434ef1dSEric Biggers 			stat->dio_mem_align = dio_align;
55878434ef1dSEric Biggers 			stat->dio_offset_align = dio_align;
55888434ef1dSEric Biggers 		}
55898434ef1dSEric Biggers 	}
55908434ef1dSEric Biggers 
559199652ea5SDavid Howells 	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
559299652ea5SDavid Howells 	if (flags & EXT4_APPEND_FL)
559399652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_APPEND;
559499652ea5SDavid Howells 	if (flags & EXT4_COMPR_FL)
559599652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_COMPRESSED;
559699652ea5SDavid Howells 	if (flags & EXT4_ENCRYPT_FL)
559799652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_ENCRYPTED;
559899652ea5SDavid Howells 	if (flags & EXT4_IMMUTABLE_FL)
559999652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_IMMUTABLE;
560099652ea5SDavid Howells 	if (flags & EXT4_NODUMP_FL)
560199652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_NODUMP;
56021f607195SEric Biggers 	if (flags & EXT4_VERITY_FL)
56031f607195SEric Biggers 		stat->attributes |= STATX_ATTR_VERITY;
560499652ea5SDavid Howells 
56053209f68bSDavid Howells 	stat->attributes_mask |= (STATX_ATTR_APPEND |
56063209f68bSDavid Howells 				  STATX_ATTR_COMPRESSED |
56073209f68bSDavid Howells 				  STATX_ATTR_ENCRYPTED |
56083209f68bSDavid Howells 				  STATX_ATTR_IMMUTABLE |
56091f607195SEric Biggers 				  STATX_ATTR_NODUMP |
56101f607195SEric Biggers 				  STATX_ATTR_VERITY);
56113209f68bSDavid Howells 
5612b74d24f7SChristian Brauner 	generic_fillattr(idmap, inode, stat);
561399652ea5SDavid Howells 	return 0;
561499652ea5SDavid Howells }
561599652ea5SDavid Howells 
5616b74d24f7SChristian Brauner int ext4_file_getattr(struct mnt_idmap *idmap,
5617549c7297SChristian Brauner 		      const struct path *path, struct kstat *stat,
561899652ea5SDavid Howells 		      u32 request_mask, unsigned int query_flags)
561999652ea5SDavid Howells {
562099652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
562199652ea5SDavid Howells 	u64 delalloc_blocks;
562299652ea5SDavid Howells 
5623b74d24f7SChristian Brauner 	ext4_getattr(idmap, path, stat, request_mask, query_flags);
56243e3398a0SMingming Cao 
56253e3398a0SMingming Cao 	/*
56269206c561SAndreas Dilger 	 * If there is inline data in the inode, the inode will normally not
56279206c561SAndreas Dilger 	 * have data blocks allocated (it may have an external xattr block).
56289206c561SAndreas Dilger 	 * Report at least one sector for such files, so tools like tar, rsync,
5629d67d64f4STheodore Ts'o 	 * others don't incorrectly think the file is completely sparse.
56309206c561SAndreas Dilger 	 */
56319206c561SAndreas Dilger 	if (unlikely(ext4_has_inline_data(inode)))
56329206c561SAndreas Dilger 		stat->blocks += (stat->size + 511) >> 9;
56339206c561SAndreas Dilger 
56349206c561SAndreas Dilger 	/*
56353e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
56363e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
56373e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
56383e3398a0SMingming Cao 	 * on-disk file blocks.
56393e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
56403e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
56413e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
56423e3398a0SMingming Cao 	 * blocks for this file.
56433e3398a0SMingming Cao 	 */
564496607551STao Ma 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
564596607551STao Ma 				   EXT4_I(inode)->i_reserved_data_blocks);
56468af8eeccSJan Kara 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
56473e3398a0SMingming Cao 	return 0;
56483e3398a0SMingming Cao }
5649ac27a0ecSDave Kleikamp 
5650fffb2739SJan Kara static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5651fffb2739SJan Kara 				   int pextents)
5652a02908f1SMingming Cao {
565312e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5654fffb2739SJan Kara 		return ext4_ind_trans_blocks(inode, lblocks);
5655fffb2739SJan Kara 	return ext4_ext_index_trans_blocks(inode, pextents);
5656a02908f1SMingming Cao }
5657ac51d837STheodore Ts'o 
5658a02908f1SMingming Cao /*
5659a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
5660a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
5661a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
5662a02908f1SMingming Cao  *
5663a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
56644907cb7bSAnatol Pomozov  * different block groups too. If they are contiguous, with flexbg,
5665a02908f1SMingming Cao  * they could still across block group boundary.
5666a02908f1SMingming Cao  *
5667a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
5668a02908f1SMingming Cao  */
5669dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5670fffb2739SJan Kara 				  int pextents)
5671a02908f1SMingming Cao {
56728df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
56738df9675fSTheodore Ts'o 	int gdpblocks;
5674a02908f1SMingming Cao 	int idxblocks;
56757fc51f92SXU pengfei 	int ret;
5676a02908f1SMingming Cao 
5677a02908f1SMingming Cao 	/*
5678fffb2739SJan Kara 	 * How many index blocks need to touch to map @lblocks logical blocks
5679fffb2739SJan Kara 	 * to @pextents physical extents?
5680a02908f1SMingming Cao 	 */
5681fffb2739SJan Kara 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5682a02908f1SMingming Cao 
5683a02908f1SMingming Cao 	ret = idxblocks;
5684a02908f1SMingming Cao 
5685a02908f1SMingming Cao 	/*
5686a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
5687a02908f1SMingming Cao 	 * to account
5688a02908f1SMingming Cao 	 */
5689fffb2739SJan Kara 	groups = idxblocks + pextents;
5690a02908f1SMingming Cao 	gdpblocks = groups;
56918df9675fSTheodore Ts'o 	if (groups > ngroups)
56928df9675fSTheodore Ts'o 		groups = ngroups;
5693a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5694a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5695a02908f1SMingming Cao 
5696a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
5697a02908f1SMingming Cao 	ret += groups + gdpblocks;
5698a02908f1SMingming Cao 
5699a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
5700a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5701ac27a0ecSDave Kleikamp 
5702ac27a0ecSDave Kleikamp 	return ret;
5703ac27a0ecSDave Kleikamp }
5704ac27a0ecSDave Kleikamp 
5705ac27a0ecSDave Kleikamp /*
570625985edcSLucas De Marchi  * Calculate the total number of credits to reserve to fit
5707f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
5708f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
5709a02908f1SMingming Cao  *
5710525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
5711a02908f1SMingming Cao  *
5712525f4ed8SMingming Cao  * We need to consider the worse case, when
5713a02908f1SMingming Cao  * one new block per extent.
5714a02908f1SMingming Cao  */
5715a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
5716a02908f1SMingming Cao {
5717a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
5718a02908f1SMingming Cao 	int ret;
5719a02908f1SMingming Cao 
5720fffb2739SJan Kara 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5721a02908f1SMingming Cao 
5722a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
5723a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
5724a02908f1SMingming Cao 		ret += bpp;
5725a02908f1SMingming Cao 	return ret;
5726a02908f1SMingming Cao }
5727f3bd1f3fSMingming Cao 
5728f3bd1f3fSMingming Cao /*
5729f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
5730f3bd1f3fSMingming Cao  *
5731f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
573279e83036SEric Sandeen  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5733f3bd1f3fSMingming Cao  *
5734f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
5735f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
5736f3bd1f3fSMingming Cao  */
5737f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5738f3bd1f3fSMingming Cao {
5739f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5740f3bd1f3fSMingming Cao }
5741f3bd1f3fSMingming Cao 
5742a02908f1SMingming Cao /*
5743617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
5744ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
5745ac27a0ecSDave Kleikamp  */
5746617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
5747617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
5748ac27a0ecSDave Kleikamp {
5749ac27a0ecSDave Kleikamp 	int err = 0;
5750ac27a0ecSDave Kleikamp 
5751a6758309SVasily Averin 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5752a6758309SVasily Averin 		put_bh(iloc->bh);
57530db1ff22STheodore Ts'o 		return -EIO;
5754a6758309SVasily Averin 	}
5755a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_inode(handle, inode);
5756aa75f4d3SHarshad Shirwadkar 
5757ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
5758ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
5759ac27a0ecSDave Kleikamp 
5760dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5761830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
5762ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
5763ac27a0ecSDave Kleikamp 	return err;
5764ac27a0ecSDave Kleikamp }
5765ac27a0ecSDave Kleikamp 
5766ac27a0ecSDave Kleikamp /*
5767ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
5768ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
5769ac27a0ecSDave Kleikamp  */
5770ac27a0ecSDave Kleikamp 
5771ac27a0ecSDave Kleikamp int
5772617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5773617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
5774ac27a0ecSDave Kleikamp {
57750390131bSFrank Mayhar 	int err;
57760390131bSFrank Mayhar 
57770db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
57780db1ff22STheodore Ts'o 		return -EIO;
57790db1ff22STheodore Ts'o 
5780617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
5781ac27a0ecSDave Kleikamp 	if (!err) {
5782ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
5783188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb,
5784188c299eSJan Kara 						    iloc->bh, EXT4_JTR_NONE);
5785ac27a0ecSDave Kleikamp 		if (err) {
5786ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
5787ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
5788ac27a0ecSDave Kleikamp 		}
5789ac27a0ecSDave Kleikamp 	}
5790617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5791ac27a0ecSDave Kleikamp 	return err;
5792ac27a0ecSDave Kleikamp }
5793ac27a0ecSDave Kleikamp 
5794c03b45b8SMiao Xie static int __ext4_expand_extra_isize(struct inode *inode,
5795c03b45b8SMiao Xie 				     unsigned int new_extra_isize,
5796c03b45b8SMiao Xie 				     struct ext4_iloc *iloc,
5797c03b45b8SMiao Xie 				     handle_t *handle, int *no_expand)
5798c03b45b8SMiao Xie {
5799c03b45b8SMiao Xie 	struct ext4_inode *raw_inode;
5800c03b45b8SMiao Xie 	struct ext4_xattr_ibody_header *header;
58014ea99936STheodore Ts'o 	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
58024ea99936STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
5803c03b45b8SMiao Xie 	int error;
5804c03b45b8SMiao Xie 
58054ea99936STheodore Ts'o 	/* this was checked at iget time, but double check for good measure */
58064ea99936STheodore Ts'o 	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
58074ea99936STheodore Ts'o 	    (ei->i_extra_isize & 3)) {
58084ea99936STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
58094ea99936STheodore Ts'o 				 ei->i_extra_isize,
58104ea99936STheodore Ts'o 				 EXT4_INODE_SIZE(inode->i_sb));
58114ea99936STheodore Ts'o 		return -EFSCORRUPTED;
58124ea99936STheodore Ts'o 	}
58134ea99936STheodore Ts'o 	if ((new_extra_isize < ei->i_extra_isize) ||
58144ea99936STheodore Ts'o 	    (new_extra_isize < 4) ||
58154ea99936STheodore Ts'o 	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
58164ea99936STheodore Ts'o 		return -EINVAL;	/* Should never happen */
58174ea99936STheodore Ts'o 
5818c03b45b8SMiao Xie 	raw_inode = ext4_raw_inode(iloc);
5819c03b45b8SMiao Xie 
5820c03b45b8SMiao Xie 	header = IHDR(inode, raw_inode);
5821c03b45b8SMiao Xie 
5822c03b45b8SMiao Xie 	/* No extended attributes present */
5823c03b45b8SMiao Xie 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5824c03b45b8SMiao Xie 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5825c03b45b8SMiao Xie 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5826c03b45b8SMiao Xie 		       EXT4_I(inode)->i_extra_isize, 0,
5827c03b45b8SMiao Xie 		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
5828c03b45b8SMiao Xie 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
5829c03b45b8SMiao Xie 		return 0;
5830c03b45b8SMiao Xie 	}
5831c03b45b8SMiao Xie 
58328994d113SJan Kara 	/*
58338994d113SJan Kara 	 * We may need to allocate external xattr block so we need quotas
58348994d113SJan Kara 	 * initialized. Here we can be called with various locks held so we
58358994d113SJan Kara 	 * cannot affort to initialize quotas ourselves. So just bail.
58368994d113SJan Kara 	 */
58378994d113SJan Kara 	if (dquot_initialize_needed(inode))
58388994d113SJan Kara 		return -EAGAIN;
58398994d113SJan Kara 
5840c03b45b8SMiao Xie 	/* try to expand with EAs present */
5841c03b45b8SMiao Xie 	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5842c03b45b8SMiao Xie 					   raw_inode, handle);
5843c03b45b8SMiao Xie 	if (error) {
5844c03b45b8SMiao Xie 		/*
5845c03b45b8SMiao Xie 		 * Inode size expansion failed; don't try again
5846c03b45b8SMiao Xie 		 */
5847c03b45b8SMiao Xie 		*no_expand = 1;
5848c03b45b8SMiao Xie 	}
5849c03b45b8SMiao Xie 
5850c03b45b8SMiao Xie 	return error;
5851c03b45b8SMiao Xie }
5852c03b45b8SMiao Xie 
5853ac27a0ecSDave Kleikamp /*
58546dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
58556dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
58566dd4ee7cSKalpak Shah  */
5857cf0a5e81SMiao Xie static int ext4_try_to_expand_extra_isize(struct inode *inode,
58581d03ec98SAneesh Kumar K.V 					  unsigned int new_extra_isize,
58591d03ec98SAneesh Kumar K.V 					  struct ext4_iloc iloc,
58601d03ec98SAneesh Kumar K.V 					  handle_t *handle)
58616dd4ee7cSKalpak Shah {
58623b10fdc6SMiao Xie 	int no_expand;
58633b10fdc6SMiao Xie 	int error;
58646dd4ee7cSKalpak Shah 
5865cf0a5e81SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5866cf0a5e81SMiao Xie 		return -EOVERFLOW;
5867cf0a5e81SMiao Xie 
5868cf0a5e81SMiao Xie 	/*
5869cf0a5e81SMiao Xie 	 * In nojournal mode, we can immediately attempt to expand
5870cf0a5e81SMiao Xie 	 * the inode.  When journaled, we first need to obtain extra
5871cf0a5e81SMiao Xie 	 * buffer credits since we may write into the EA block
5872cf0a5e81SMiao Xie 	 * with this same handle. If journal_extend fails, then it will
5873cf0a5e81SMiao Xie 	 * only result in a minor loss of functionality for that inode.
5874cf0a5e81SMiao Xie 	 * If this is felt to be critical, then e2fsck should be run to
5875cf0a5e81SMiao Xie 	 * force a large enough s_min_extra_isize.
5876cf0a5e81SMiao Xie 	 */
58776cb367c2SJan Kara 	if (ext4_journal_extend(handle,
587883448bdfSJan Kara 				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5879cf0a5e81SMiao Xie 		return -ENOSPC;
58806dd4ee7cSKalpak Shah 
58813b10fdc6SMiao Xie 	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5882cf0a5e81SMiao Xie 		return -EBUSY;
58833b10fdc6SMiao Xie 
5884c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5885c03b45b8SMiao Xie 					  handle, &no_expand);
58863b10fdc6SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5887c03b45b8SMiao Xie 
5888c03b45b8SMiao Xie 	return error;
58896dd4ee7cSKalpak Shah }
58906dd4ee7cSKalpak Shah 
5891c03b45b8SMiao Xie int ext4_expand_extra_isize(struct inode *inode,
5892c03b45b8SMiao Xie 			    unsigned int new_extra_isize,
5893c03b45b8SMiao Xie 			    struct ext4_iloc *iloc)
5894c03b45b8SMiao Xie {
5895c03b45b8SMiao Xie 	handle_t *handle;
5896c03b45b8SMiao Xie 	int no_expand;
5897c03b45b8SMiao Xie 	int error, rc;
5898c03b45b8SMiao Xie 
5899c03b45b8SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5900c03b45b8SMiao Xie 		brelse(iloc->bh);
5901c03b45b8SMiao Xie 		return -EOVERFLOW;
5902c03b45b8SMiao Xie 	}
5903c03b45b8SMiao Xie 
5904c03b45b8SMiao Xie 	handle = ext4_journal_start(inode, EXT4_HT_INODE,
5905c03b45b8SMiao Xie 				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5906c03b45b8SMiao Xie 	if (IS_ERR(handle)) {
5907c03b45b8SMiao Xie 		error = PTR_ERR(handle);
5908c03b45b8SMiao Xie 		brelse(iloc->bh);
5909c03b45b8SMiao Xie 		return error;
5910c03b45b8SMiao Xie 	}
5911c03b45b8SMiao Xie 
5912c03b45b8SMiao Xie 	ext4_write_lock_xattr(inode, &no_expand);
5913c03b45b8SMiao Xie 
5914ddccb6dbSzhangyi (F) 	BUFFER_TRACE(iloc->bh, "get_write_access");
5915188c299eSJan Kara 	error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
5916188c299eSJan Kara 					      EXT4_JTR_NONE);
59173b10fdc6SMiao Xie 	if (error) {
5918c03b45b8SMiao Xie 		brelse(iloc->bh);
59197f420d64SDan Carpenter 		goto out_unlock;
59203b10fdc6SMiao Xie 	}
5921cf0a5e81SMiao Xie 
5922c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5923c03b45b8SMiao Xie 					  handle, &no_expand);
5924c03b45b8SMiao Xie 
5925c03b45b8SMiao Xie 	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5926c03b45b8SMiao Xie 	if (!error)
5927c03b45b8SMiao Xie 		error = rc;
5928c03b45b8SMiao Xie 
59297f420d64SDan Carpenter out_unlock:
5930c03b45b8SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5931c03b45b8SMiao Xie 	ext4_journal_stop(handle);
59323b10fdc6SMiao Xie 	return error;
59336dd4ee7cSKalpak Shah }
59346dd4ee7cSKalpak Shah 
59356dd4ee7cSKalpak Shah /*
5936ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
5937ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
5938ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
5939ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
5940ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
5941ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
5942ac27a0ecSDave Kleikamp  *
5943ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
5944ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
5945ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5946ac27a0ecSDave Kleikamp  * we start and wait on commits.
5947ac27a0ecSDave Kleikamp  */
59484209ae12SHarshad Shirwadkar int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
59494209ae12SHarshad Shirwadkar 				const char *func, unsigned int line)
5950ac27a0ecSDave Kleikamp {
5951617ba13bSMingming Cao 	struct ext4_iloc iloc;
59526dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5953cf0a5e81SMiao Xie 	int err;
5954ac27a0ecSDave Kleikamp 
5955ac27a0ecSDave Kleikamp 	might_sleep();
59567ff9c073STheodore Ts'o 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5957617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
59585e1021f2SEryu Guan 	if (err)
59594209ae12SHarshad Shirwadkar 		goto out;
5960cf0a5e81SMiao Xie 
5961cf0a5e81SMiao Xie 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5962cf0a5e81SMiao Xie 		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
59636dd4ee7cSKalpak Shah 					       iloc, handle);
5964cf0a5e81SMiao Xie 
59654209ae12SHarshad Shirwadkar 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
59664209ae12SHarshad Shirwadkar out:
59674209ae12SHarshad Shirwadkar 	if (unlikely(err))
59684209ae12SHarshad Shirwadkar 		ext4_error_inode_err(inode, func, line, 0, err,
59694209ae12SHarshad Shirwadkar 					"mark_inode_dirty error");
59704209ae12SHarshad Shirwadkar 	return err;
5971ac27a0ecSDave Kleikamp }
5972ac27a0ecSDave Kleikamp 
5973ac27a0ecSDave Kleikamp /*
5974617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
5975ac27a0ecSDave Kleikamp  *
5976ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
5977ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
5978ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
5979ac27a0ecSDave Kleikamp  *
59805dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
5981ac27a0ecSDave Kleikamp  * are allocated to the file.
5982ac27a0ecSDave Kleikamp  *
5983ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
5984ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
5985ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
5986ac27a0ecSDave Kleikamp  */
5987aa385729SChristoph Hellwig void ext4_dirty_inode(struct inode *inode, int flags)
5988ac27a0ecSDave Kleikamp {
5989ac27a0ecSDave Kleikamp 	handle_t *handle;
5990ac27a0ecSDave Kleikamp 
59919924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5992ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5993ac27a0ecSDave Kleikamp 		return;
5994e2728c56SEric Biggers 	ext4_mark_inode_dirty(handle, inode);
5995e2728c56SEric Biggers 	ext4_journal_stop(handle);
5996ac27a0ecSDave Kleikamp }
5997ac27a0ecSDave Kleikamp 
5998617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
5999ac27a0ecSDave Kleikamp {
6000ac27a0ecSDave Kleikamp 	journal_t *journal;
6001ac27a0ecSDave Kleikamp 	handle_t *handle;
6002ac27a0ecSDave Kleikamp 	int err;
6003c8585c6fSDaeho Jeong 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6004ac27a0ecSDave Kleikamp 
6005ac27a0ecSDave Kleikamp 	/*
6006ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
6007ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
6008ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
6009ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
6010ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
6011ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
6012ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
6013ac27a0ecSDave Kleikamp 	 */
6014ac27a0ecSDave Kleikamp 
6015617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
60160390131bSFrank Mayhar 	if (!journal)
60170390131bSFrank Mayhar 		return 0;
6018d699594dSDave Hansen 	if (is_journal_aborted(journal))
6019ac27a0ecSDave Kleikamp 		return -EROFS;
6020ac27a0ecSDave Kleikamp 
602117335dccSDmitry Monakhov 	/* Wait for all existing dio workers */
602217335dccSDmitry Monakhov 	inode_dio_wait(inode);
602317335dccSDmitry Monakhov 
60244c546592SDaeho Jeong 	/*
60254c546592SDaeho Jeong 	 * Before flushing the journal and switching inode's aops, we have
60264c546592SDaeho Jeong 	 * to flush all dirty data the inode has. There can be outstanding
60274c546592SDaeho Jeong 	 * delayed allocations, there can be unwritten extents created by
60284c546592SDaeho Jeong 	 * fallocate or buffered writes in dioread_nolock mode covered by
60294c546592SDaeho Jeong 	 * dirty data which can be converted only after flushing the dirty
60304c546592SDaeho Jeong 	 * data (and journalled aops don't know how to handle these cases).
60314c546592SDaeho Jeong 	 */
60324c546592SDaeho Jeong 	if (val) {
6033d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
60344c546592SDaeho Jeong 		err = filemap_write_and_wait(inode->i_mapping);
60354c546592SDaeho Jeong 		if (err < 0) {
6036d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
60374c546592SDaeho Jeong 			return err;
60384c546592SDaeho Jeong 		}
60394c546592SDaeho Jeong 	}
60404c546592SDaeho Jeong 
6041bbd55937SEric Biggers 	percpu_down_write(&sbi->s_writepages_rwsem);
6042dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
6043ac27a0ecSDave Kleikamp 
6044ac27a0ecSDave Kleikamp 	/*
6045ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
6046ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
6047ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
6048ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
6049ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
6050ac27a0ecSDave Kleikamp 	 */
6051ac27a0ecSDave Kleikamp 
6052ac27a0ecSDave Kleikamp 	if (val)
605312e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60545872ddaaSYongqiang Yang 	else {
605501d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
60564f879ca6SJan Kara 		if (err < 0) {
60574f879ca6SJan Kara 			jbd2_journal_unlock_updates(journal);
6058bbd55937SEric Biggers 			percpu_up_write(&sbi->s_writepages_rwsem);
60594f879ca6SJan Kara 			return err;
60604f879ca6SJan Kara 		}
606112e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60625872ddaaSYongqiang Yang 	}
6063617ba13bSMingming Cao 	ext4_set_aops(inode);
6064ac27a0ecSDave Kleikamp 
6065dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
6066bbd55937SEric Biggers 	percpu_up_write(&sbi->s_writepages_rwsem);
6067c8585c6fSDaeho Jeong 
60684c546592SDaeho Jeong 	if (val)
6069d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
6070ac27a0ecSDave Kleikamp 
6071ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
6072ac27a0ecSDave Kleikamp 
60739924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6074ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
6075ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
6076ac27a0ecSDave Kleikamp 
6077aa75f4d3SHarshad Shirwadkar 	ext4_fc_mark_ineligible(inode->i_sb,
6078e85c81baSXin Yin 		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6079617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
60800390131bSFrank Mayhar 	ext4_handle_sync(handle);
6081617ba13bSMingming Cao 	ext4_journal_stop(handle);
6082617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
6083ac27a0ecSDave Kleikamp 
6084ac27a0ecSDave Kleikamp 	return err;
6085ac27a0ecSDave Kleikamp }
60862e9ee850SAneesh Kumar K.V 
6087188c299eSJan Kara static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6088188c299eSJan Kara 			    struct buffer_head *bh)
60892e9ee850SAneesh Kumar K.V {
60902e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
60912e9ee850SAneesh Kumar K.V }
60922e9ee850SAneesh Kumar K.V 
6093401b25aaSSouptick Joarder vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
60942e9ee850SAneesh Kumar K.V {
609511bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
60969ea0e45bSMatthew Wilcox 	struct folio *folio = page_folio(vmf->page);
60972e9ee850SAneesh Kumar K.V 	loff_t size;
60982e9ee850SAneesh Kumar K.V 	unsigned long len;
6099401b25aaSSouptick Joarder 	int err;
6100401b25aaSSouptick Joarder 	vm_fault_t ret;
61012e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
6102496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
61032e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
61049ea7df53SJan Kara 	handle_t *handle;
61059ea7df53SJan Kara 	get_block_t *get_block;
61069ea7df53SJan Kara 	int retries = 0;
61072e9ee850SAneesh Kumar K.V 
610802b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
610902b016caSTheodore Ts'o 		return VM_FAULT_SIGBUS;
611002b016caSTheodore Ts'o 
61118e8ad8a5SJan Kara 	sb_start_pagefault(inode->i_sb);
6112041bbb6dSTheodore Ts'o 	file_update_time(vma->vm_file);
6113ea3d7209SJan Kara 
6114d4f5258eSJan Kara 	filemap_invalidate_lock_shared(mapping);
61157b4cc978SEric Biggers 
6116401b25aaSSouptick Joarder 	err = ext4_convert_inline_data(inode);
6117401b25aaSSouptick Joarder 	if (err)
61187b4cc978SEric Biggers 		goto out_ret;
61197b4cc978SEric Biggers 
612064a9f144SMauricio Faria de Oliveira 	/*
612164a9f144SMauricio Faria de Oliveira 	 * On data journalling we skip straight to the transaction handle:
612264a9f144SMauricio Faria de Oliveira 	 * there's no delalloc; page truncated will be checked later; the
612364a9f144SMauricio Faria de Oliveira 	 * early return w/ all buffers mapped (calculates size/len) can't
612464a9f144SMauricio Faria de Oliveira 	 * be used; and there's no dioread_nolock, so only ext4_get_block.
612564a9f144SMauricio Faria de Oliveira 	 */
612664a9f144SMauricio Faria de Oliveira 	if (ext4_should_journal_data(inode))
612764a9f144SMauricio Faria de Oliveira 		goto retry_alloc;
612864a9f144SMauricio Faria de Oliveira 
61299ea7df53SJan Kara 	/* Delalloc case is easy... */
61309ea7df53SJan Kara 	if (test_opt(inode->i_sb, DELALLOC) &&
61319ea7df53SJan Kara 	    !ext4_nonda_switch(inode->i_sb)) {
61329ea7df53SJan Kara 		do {
6133401b25aaSSouptick Joarder 			err = block_page_mkwrite(vma, vmf,
61349ea7df53SJan Kara 						   ext4_da_get_block_prep);
6135401b25aaSSouptick Joarder 		} while (err == -ENOSPC &&
61369ea7df53SJan Kara 		       ext4_should_retry_alloc(inode->i_sb, &retries));
61379ea7df53SJan Kara 		goto out_ret;
61382e9ee850SAneesh Kumar K.V 	}
61390e499890SDarrick J. Wong 
61409ea0e45bSMatthew Wilcox 	folio_lock(folio);
61419ea7df53SJan Kara 	size = i_size_read(inode);
61429ea7df53SJan Kara 	/* Page got truncated from under us? */
61439ea0e45bSMatthew Wilcox 	if (folio->mapping != mapping || folio_pos(folio) > size) {
61449ea0e45bSMatthew Wilcox 		folio_unlock(folio);
61459ea7df53SJan Kara 		ret = VM_FAULT_NOPAGE;
61469ea7df53SJan Kara 		goto out;
61470e499890SDarrick J. Wong 	}
61482e9ee850SAneesh Kumar K.V 
61499ea0e45bSMatthew Wilcox 	len = folio_size(folio);
61509ea0e45bSMatthew Wilcox 	if (folio_pos(folio) + len > size)
61519ea0e45bSMatthew Wilcox 		len = size - folio_pos(folio);
6152a827eaffSAneesh Kumar K.V 	/*
61539ea7df53SJan Kara 	 * Return if we have all the buffers mapped. This avoids the need to do
61549ea7df53SJan Kara 	 * journal_start/journal_stop which can block and take a long time
615564a9f144SMauricio Faria de Oliveira 	 *
615664a9f144SMauricio Faria de Oliveira 	 * This cannot be done for data journalling, as we have to add the
615764a9f144SMauricio Faria de Oliveira 	 * inode to the transaction's list to writeprotect pages on commit.
6158a827eaffSAneesh Kumar K.V 	 */
61599ea0e45bSMatthew Wilcox 	if (folio_buffers(folio)) {
61609ea0e45bSMatthew Wilcox 		if (!ext4_walk_page_buffers(NULL, inode, folio_buffers(folio),
6161f19d5870STao Ma 					    0, len, NULL,
6162a827eaffSAneesh Kumar K.V 					    ext4_bh_unmapped)) {
61639ea7df53SJan Kara 			/* Wait so that we don't change page under IO */
61649ea0e45bSMatthew Wilcox 			folio_wait_stable(folio);
61659ea7df53SJan Kara 			ret = VM_FAULT_LOCKED;
61669ea7df53SJan Kara 			goto out;
61672e9ee850SAneesh Kumar K.V 		}
6168a827eaffSAneesh Kumar K.V 	}
61699ea0e45bSMatthew Wilcox 	folio_unlock(folio);
61709ea7df53SJan Kara 	/* OK, we need to fill the hole... */
61719ea7df53SJan Kara 	if (ext4_should_dioread_nolock(inode))
6172705965bdSJan Kara 		get_block = ext4_get_block_unwritten;
61739ea7df53SJan Kara 	else
61749ea7df53SJan Kara 		get_block = ext4_get_block;
61759ea7df53SJan Kara retry_alloc:
61769924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
61779924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
61789ea7df53SJan Kara 	if (IS_ERR(handle)) {
6179c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
61809ea7df53SJan Kara 		goto out;
61819ea7df53SJan Kara 	}
618264a9f144SMauricio Faria de Oliveira 	/*
618364a9f144SMauricio Faria de Oliveira 	 * Data journalling can't use block_page_mkwrite() because it
618464a9f144SMauricio Faria de Oliveira 	 * will set_buffer_dirty() before do_journal_get_write_access()
618564a9f144SMauricio Faria de Oliveira 	 * thus might hit warning messages for dirty metadata buffers.
618664a9f144SMauricio Faria de Oliveira 	 */
618764a9f144SMauricio Faria de Oliveira 	if (!ext4_should_journal_data(inode)) {
6188401b25aaSSouptick Joarder 		err = block_page_mkwrite(vma, vmf, get_block);
618964a9f144SMauricio Faria de Oliveira 	} else {
61909ea0e45bSMatthew Wilcox 		folio_lock(folio);
619164a9f144SMauricio Faria de Oliveira 		size = i_size_read(inode);
619264a9f144SMauricio Faria de Oliveira 		/* Page got truncated from under us? */
61939ea0e45bSMatthew Wilcox 		if (folio->mapping != mapping || folio_pos(folio) > size) {
619464a9f144SMauricio Faria de Oliveira 			ret = VM_FAULT_NOPAGE;
6195afb585a9SMauricio Faria de Oliveira 			goto out_error;
619664a9f144SMauricio Faria de Oliveira 		}
619764a9f144SMauricio Faria de Oliveira 
61989ea0e45bSMatthew Wilcox 		len = folio_size(folio);
61999ea0e45bSMatthew Wilcox 		if (folio_pos(folio) + len > size)
62009ea0e45bSMatthew Wilcox 			len = size - folio_pos(folio);
620164a9f144SMauricio Faria de Oliveira 
62029ea0e45bSMatthew Wilcox 		err = __block_write_begin(&folio->page, 0, len, ext4_get_block);
620364a9f144SMauricio Faria de Oliveira 		if (!err) {
62049ea7df53SJan Kara 			ret = VM_FAULT_SIGBUS;
62059ea0e45bSMatthew Wilcox 			if (ext4_journal_page_buffers(handle, &folio->page, len))
6206afb585a9SMauricio Faria de Oliveira 				goto out_error;
620764a9f144SMauricio Faria de Oliveira 		} else {
62089ea0e45bSMatthew Wilcox 			folio_unlock(folio);
620964a9f144SMauricio Faria de Oliveira 		}
62109ea7df53SJan Kara 	}
62119ea7df53SJan Kara 	ext4_journal_stop(handle);
6212401b25aaSSouptick Joarder 	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
62139ea7df53SJan Kara 		goto retry_alloc;
62149ea7df53SJan Kara out_ret:
6215401b25aaSSouptick Joarder 	ret = block_page_mkwrite_return(err);
62169ea7df53SJan Kara out:
6217d4f5258eSJan Kara 	filemap_invalidate_unlock_shared(mapping);
62188e8ad8a5SJan Kara 	sb_end_pagefault(inode->i_sb);
62192e9ee850SAneesh Kumar K.V 	return ret;
6220afb585a9SMauricio Faria de Oliveira out_error:
62219ea0e45bSMatthew Wilcox 	folio_unlock(folio);
6222afb585a9SMauricio Faria de Oliveira 	ext4_journal_stop(handle);
6223afb585a9SMauricio Faria de Oliveira 	goto out;
62242e9ee850SAneesh Kumar K.V }
6225