xref: /openbmc/linux/fs/ext4/inode.c (revision de0039f69c95692539bcb7cfc3b01f31e1c9f342)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2ac27a0ecSDave Kleikamp /*
3617ba13bSMingming Cao  *  linux/fs/ext4/inode.c
4ac27a0ecSDave Kleikamp  *
5ac27a0ecSDave Kleikamp  * Copyright (C) 1992, 1993, 1994, 1995
6ac27a0ecSDave Kleikamp  * Remy Card (card@masi.ibp.fr)
7ac27a0ecSDave Kleikamp  * Laboratoire MASI - Institut Blaise Pascal
8ac27a0ecSDave Kleikamp  * Universite Pierre et Marie Curie (Paris VI)
9ac27a0ecSDave Kleikamp  *
10ac27a0ecSDave Kleikamp  *  from
11ac27a0ecSDave Kleikamp  *
12ac27a0ecSDave Kleikamp  *  linux/fs/minix/inode.c
13ac27a0ecSDave Kleikamp  *
14ac27a0ecSDave Kleikamp  *  Copyright (C) 1991, 1992  Linus Torvalds
15ac27a0ecSDave Kleikamp  *
16ac27a0ecSDave Kleikamp  *  64-bit file support on 64-bit platforms by Jakub Jelinek
17ac27a0ecSDave Kleikamp  *	(jj@sunsite.ms.mff.cuni.cz)
18ac27a0ecSDave Kleikamp  *
19617ba13bSMingming Cao  *  Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
20ac27a0ecSDave Kleikamp  */
21ac27a0ecSDave Kleikamp 
22ac27a0ecSDave Kleikamp #include <linux/fs.h>
2314f3db55SChristian Brauner #include <linux/mount.h>
24ac27a0ecSDave Kleikamp #include <linux/time.h>
25ac27a0ecSDave Kleikamp #include <linux/highuid.h>
26ac27a0ecSDave Kleikamp #include <linux/pagemap.h>
27c94c2acfSMatthew Wilcox #include <linux/dax.h>
28ac27a0ecSDave Kleikamp #include <linux/quotaops.h>
29ac27a0ecSDave Kleikamp #include <linux/string.h>
30ac27a0ecSDave Kleikamp #include <linux/buffer_head.h>
31ac27a0ecSDave Kleikamp #include <linux/writeback.h>
3264769240SAlex Tomas #include <linux/pagevec.h>
33ac27a0ecSDave Kleikamp #include <linux/mpage.h>
34e83c1397SDuane Griffin #include <linux/namei.h>
35ac27a0ecSDave Kleikamp #include <linux/uio.h>
36ac27a0ecSDave Kleikamp #include <linux/bio.h>
374c0425ffSMingming Cao #include <linux/workqueue.h>
38744692dcSJiaying Zhang #include <linux/kernel.h>
396db26ffcSAndrew Morton #include <linux/printk.h>
405a0e3ad6STejun Heo #include <linux/slab.h>
4100a1a053STheodore Ts'o #include <linux/bitops.h>
42364443cbSJan Kara #include <linux/iomap.h>
43ae5e165dSJeff Layton #include <linux/iversion.h>
449bffad1eSTheodore Ts'o 
453dcf5451SChristoph Hellwig #include "ext4_jbd2.h"
46ac27a0ecSDave Kleikamp #include "xattr.h"
47ac27a0ecSDave Kleikamp #include "acl.h"
489f125d64STheodore Ts'o #include "truncate.h"
49ac27a0ecSDave Kleikamp 
509bffad1eSTheodore Ts'o #include <trace/events/ext4.h>
519bffad1eSTheodore Ts'o 
52814525f4SDarrick J. Wong static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
53814525f4SDarrick J. Wong 			      struct ext4_inode_info *ei)
54814525f4SDarrick J. Wong {
55814525f4SDarrick J. Wong 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
56814525f4SDarrick J. Wong 	__u32 csum;
57b47820edSDaeho Jeong 	__u16 dummy_csum = 0;
58b47820edSDaeho Jeong 	int offset = offsetof(struct ext4_inode, i_checksum_lo);
59b47820edSDaeho Jeong 	unsigned int csum_size = sizeof(dummy_csum);
60814525f4SDarrick J. Wong 
61b47820edSDaeho Jeong 	csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
62b47820edSDaeho Jeong 	csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
63b47820edSDaeho Jeong 	offset += csum_size;
64b47820edSDaeho Jeong 	csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
65b47820edSDaeho Jeong 			   EXT4_GOOD_OLD_INODE_SIZE - offset);
66b47820edSDaeho Jeong 
67b47820edSDaeho Jeong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
68b47820edSDaeho Jeong 		offset = offsetof(struct ext4_inode, i_checksum_hi);
69b47820edSDaeho Jeong 		csum = ext4_chksum(sbi, csum, (__u8 *)raw +
70b47820edSDaeho Jeong 				   EXT4_GOOD_OLD_INODE_SIZE,
71b47820edSDaeho Jeong 				   offset - EXT4_GOOD_OLD_INODE_SIZE);
72b47820edSDaeho Jeong 		if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
73b47820edSDaeho Jeong 			csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
74b47820edSDaeho Jeong 					   csum_size);
75b47820edSDaeho Jeong 			offset += csum_size;
76814525f4SDarrick J. Wong 		}
7705ac5aa1SDaeho Jeong 		csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
7805ac5aa1SDaeho Jeong 				   EXT4_INODE_SIZE(inode->i_sb) - offset);
79b47820edSDaeho Jeong 	}
80814525f4SDarrick J. Wong 
81814525f4SDarrick J. Wong 	return csum;
82814525f4SDarrick J. Wong }
83814525f4SDarrick J. Wong 
84814525f4SDarrick J. Wong static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
85814525f4SDarrick J. Wong 				  struct ext4_inode_info *ei)
86814525f4SDarrick J. Wong {
87814525f4SDarrick J. Wong 	__u32 provided, calculated;
88814525f4SDarrick J. Wong 
89814525f4SDarrick J. Wong 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
90814525f4SDarrick J. Wong 	    cpu_to_le32(EXT4_OS_LINUX) ||
919aa5d32bSDmitry Monakhov 	    !ext4_has_metadata_csum(inode->i_sb))
92814525f4SDarrick J. Wong 		return 1;
93814525f4SDarrick J. Wong 
94814525f4SDarrick J. Wong 	provided = le16_to_cpu(raw->i_checksum_lo);
95814525f4SDarrick J. Wong 	calculated = ext4_inode_csum(inode, raw, ei);
96814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
97814525f4SDarrick J. Wong 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
98814525f4SDarrick J. Wong 		provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
99814525f4SDarrick J. Wong 	else
100814525f4SDarrick J. Wong 		calculated &= 0xFFFF;
101814525f4SDarrick J. Wong 
102814525f4SDarrick J. Wong 	return provided == calculated;
103814525f4SDarrick J. Wong }
104814525f4SDarrick J. Wong 
1058016e29fSHarshad Shirwadkar void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
106814525f4SDarrick J. Wong 			 struct ext4_inode_info *ei)
107814525f4SDarrick J. Wong {
108814525f4SDarrick J. Wong 	__u32 csum;
109814525f4SDarrick J. Wong 
110814525f4SDarrick J. Wong 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
111814525f4SDarrick J. Wong 	    cpu_to_le32(EXT4_OS_LINUX) ||
1129aa5d32bSDmitry Monakhov 	    !ext4_has_metadata_csum(inode->i_sb))
113814525f4SDarrick J. Wong 		return;
114814525f4SDarrick J. Wong 
115814525f4SDarrick J. Wong 	csum = ext4_inode_csum(inode, raw, ei);
116814525f4SDarrick J. Wong 	raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
117814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
118814525f4SDarrick J. Wong 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
119814525f4SDarrick J. Wong 		raw->i_checksum_hi = cpu_to_le16(csum >> 16);
120814525f4SDarrick J. Wong }
121814525f4SDarrick J. Wong 
122678aaf48SJan Kara static inline int ext4_begin_ordered_truncate(struct inode *inode,
123678aaf48SJan Kara 					      loff_t new_size)
124678aaf48SJan Kara {
1257ff9c073STheodore Ts'o 	trace_ext4_begin_ordered_truncate(inode, new_size);
1268aefcd55STheodore Ts'o 	/*
1278aefcd55STheodore Ts'o 	 * If jinode is zero, then we never opened the file for
1288aefcd55STheodore Ts'o 	 * writing, so there's no need to call
1298aefcd55STheodore Ts'o 	 * jbd2_journal_begin_ordered_truncate() since there's no
1308aefcd55STheodore Ts'o 	 * outstanding writes we need to flush.
1318aefcd55STheodore Ts'o 	 */
1328aefcd55STheodore Ts'o 	if (!EXT4_I(inode)->jinode)
1338aefcd55STheodore Ts'o 		return 0;
1348aefcd55STheodore Ts'o 	return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
1358aefcd55STheodore Ts'o 						   EXT4_I(inode)->jinode,
136678aaf48SJan Kara 						   new_size);
137678aaf48SJan Kara }
138678aaf48SJan Kara 
139cb20d518STheodore Ts'o static int __ext4_journalled_writepage(struct page *page, unsigned int len);
140dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
141dec214d0STahsin Erdogan 				  int pextents);
14264769240SAlex Tomas 
143ac27a0ecSDave Kleikamp /*
144ac27a0ecSDave Kleikamp  * Test whether an inode is a fast symlink.
145407cd7fbSTahsin Erdogan  * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
146ac27a0ecSDave Kleikamp  */
147f348c252STheodore Ts'o int ext4_inode_is_fast_symlink(struct inode *inode)
148ac27a0ecSDave Kleikamp {
149fc82228aSAndi Kleen 	if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
150fc82228aSAndi Kleen 		int ea_blocks = EXT4_I(inode)->i_file_acl ?
151fc82228aSAndi Kleen 				EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
152fc82228aSAndi Kleen 
153fc82228aSAndi Kleen 		if (ext4_has_inline_data(inode))
154fc82228aSAndi Kleen 			return 0;
155fc82228aSAndi Kleen 
156fc82228aSAndi Kleen 		return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
157fc82228aSAndi Kleen 	}
158407cd7fbSTahsin Erdogan 	return S_ISLNK(inode->i_mode) && inode->i_size &&
159407cd7fbSTahsin Erdogan 	       (inode->i_size < EXT4_N_BLOCKS * 4);
160ac27a0ecSDave Kleikamp }
161ac27a0ecSDave Kleikamp 
162ac27a0ecSDave Kleikamp /*
163ac27a0ecSDave Kleikamp  * Called at the last iput() if i_nlink is zero.
164ac27a0ecSDave Kleikamp  */
1650930fcc1SAl Viro void ext4_evict_inode(struct inode *inode)
166ac27a0ecSDave Kleikamp {
167ac27a0ecSDave Kleikamp 	handle_t *handle;
168bc965ab3STheodore Ts'o 	int err;
16965db869cSJan Kara 	/*
17065db869cSJan Kara 	 * Credits for final inode cleanup and freeing:
17165db869cSJan Kara 	 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
17265db869cSJan Kara 	 * (xattr block freeing), bitmap, group descriptor (inode freeing)
17365db869cSJan Kara 	 */
17465db869cSJan Kara 	int extra_credits = 6;
1750421a189STahsin Erdogan 	struct ext4_xattr_inode_array *ea_inode_array = NULL;
17646e294efSJan Kara 	bool freeze_protected = false;
177ac27a0ecSDave Kleikamp 
1787ff9c073STheodore Ts'o 	trace_ext4_evict_inode(inode);
1792581fdc8SJiaying Zhang 
1806bc0d63dSJan Kara 	if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
1816bc0d63dSJan Kara 		ext4_evict_ea_inode(inode);
1820930fcc1SAl Viro 	if (inode->i_nlink) {
1832d859db3SJan Kara 		/*
1842d859db3SJan Kara 		 * When journalling data dirty buffers are tracked only in the
1852d859db3SJan Kara 		 * journal. So although mm thinks everything is clean and
1862d859db3SJan Kara 		 * ready for reaping the inode might still have some pages to
1872d859db3SJan Kara 		 * write in the running transaction or waiting to be
188ccd16945SMatthew Wilcox (Oracle) 		 * checkpointed. Thus calling jbd2_journal_invalidate_folio()
1892d859db3SJan Kara 		 * (via truncate_inode_pages()) to discard these buffers can
1902d859db3SJan Kara 		 * cause data loss. Also even if we did not discard these
1912d859db3SJan Kara 		 * buffers, we would have no way to find them after the inode
1922d859db3SJan Kara 		 * is reaped and thus user could see stale data if he tries to
1932d859db3SJan Kara 		 * read them before the transaction is checkpointed. So be
1942d859db3SJan Kara 		 * careful and force everything to disk here... We use
1952d859db3SJan Kara 		 * ei->i_datasync_tid to store the newest transaction
1962d859db3SJan Kara 		 * containing inode's data.
1972d859db3SJan Kara 		 *
1982d859db3SJan Kara 		 * Note that directories do not have this problem because they
1992d859db3SJan Kara 		 * don't use page cache.
2002d859db3SJan Kara 		 */
2016a7fd522SVegard Nossum 		if (inode->i_ino != EXT4_JOURNAL_INO &&
2026a7fd522SVegard Nossum 		    ext4_should_journal_data(inode) &&
2036493792dSZhang Yi 		    S_ISREG(inode->i_mode) && inode->i_data.nrpages) {
2042d859db3SJan Kara 			journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
2052d859db3SJan Kara 			tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
2062d859db3SJan Kara 
207d76a3a77STheodore Ts'o 			jbd2_complete_transaction(journal, commit_tid);
2082d859db3SJan Kara 			filemap_write_and_wait(&inode->i_data);
2092d859db3SJan Kara 		}
21091b0abe3SJohannes Weiner 		truncate_inode_pages_final(&inode->i_data);
2115dc23bddSJan Kara 
2120930fcc1SAl Viro 		goto no_delete;
2130930fcc1SAl Viro 	}
2140930fcc1SAl Viro 
215e2bfb088STheodore Ts'o 	if (is_bad_inode(inode))
216e2bfb088STheodore Ts'o 		goto no_delete;
217871a2931SChristoph Hellwig 	dquot_initialize(inode);
218907f4554SChristoph Hellwig 
219678aaf48SJan Kara 	if (ext4_should_order_data(inode))
220678aaf48SJan Kara 		ext4_begin_ordered_truncate(inode, 0);
22191b0abe3SJohannes Weiner 	truncate_inode_pages_final(&inode->i_data);
222ac27a0ecSDave Kleikamp 
2238e8ad8a5SJan Kara 	/*
224ceff86fdSJan Kara 	 * For inodes with journalled data, transaction commit could have
225bc12ac98SZhang Yi 	 * dirtied the inode. And for inodes with dioread_nolock, unwritten
226bc12ac98SZhang Yi 	 * extents converting worker could merge extents and also have dirtied
227bc12ac98SZhang Yi 	 * the inode. Flush worker is ignoring it because of I_FREEING flag but
228bc12ac98SZhang Yi 	 * we still need to remove the inode from the writeback lists.
229ceff86fdSJan Kara 	 */
230bc12ac98SZhang Yi 	if (!list_empty_careful(&inode->i_io_list))
231ceff86fdSJan Kara 		inode_io_list_del(inode);
232ceff86fdSJan Kara 
233ceff86fdSJan Kara 	/*
2348e8ad8a5SJan Kara 	 * Protect us against freezing - iput() caller didn't have to have any
23546e294efSJan Kara 	 * protection against it. When we are in a running transaction though,
23646e294efSJan Kara 	 * we are already protected against freezing and we cannot grab further
23746e294efSJan Kara 	 * protection due to lock ordering constraints.
2388e8ad8a5SJan Kara 	 */
23946e294efSJan Kara 	if (!ext4_journal_current_handle()) {
2408e8ad8a5SJan Kara 		sb_start_intwrite(inode->i_sb);
24146e294efSJan Kara 		freeze_protected = true;
24246e294efSJan Kara 	}
243e50e5129SAndreas Dilger 
24430a7eb97STahsin Erdogan 	if (!IS_NOQUOTA(inode))
24530a7eb97STahsin Erdogan 		extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
24630a7eb97STahsin Erdogan 
24765db869cSJan Kara 	/*
24865db869cSJan Kara 	 * Block bitmap, group descriptor, and inode are accounted in both
24965db869cSJan Kara 	 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
25065db869cSJan Kara 	 */
25130a7eb97STahsin Erdogan 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
25265db869cSJan Kara 			 ext4_blocks_for_truncate(inode) + extra_credits - 3);
253ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
254bc965ab3STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
255ac27a0ecSDave Kleikamp 		/*
256ac27a0ecSDave Kleikamp 		 * If we're going to skip the normal cleanup, we still need to
257ac27a0ecSDave Kleikamp 		 * make sure that the in-core orphan linked list is properly
258ac27a0ecSDave Kleikamp 		 * cleaned up.
259ac27a0ecSDave Kleikamp 		 */
260617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
26146e294efSJan Kara 		if (freeze_protected)
2628e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
263ac27a0ecSDave Kleikamp 		goto no_delete;
264ac27a0ecSDave Kleikamp 	}
26530a7eb97STahsin Erdogan 
266ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
2670390131bSFrank Mayhar 		ext4_handle_sync(handle);
268407cd7fbSTahsin Erdogan 
269407cd7fbSTahsin Erdogan 	/*
270407cd7fbSTahsin Erdogan 	 * Set inode->i_size to 0 before calling ext4_truncate(). We need
271407cd7fbSTahsin Erdogan 	 * special handling of symlinks here because i_size is used to
272407cd7fbSTahsin Erdogan 	 * determine whether ext4_inode_info->i_data contains symlink data or
273407cd7fbSTahsin Erdogan 	 * block mappings. Setting i_size to 0 will remove its fast symlink
274407cd7fbSTahsin Erdogan 	 * status. Erase i_data so that it becomes a valid empty block map.
275407cd7fbSTahsin Erdogan 	 */
276407cd7fbSTahsin Erdogan 	if (ext4_inode_is_fast_symlink(inode))
277407cd7fbSTahsin Erdogan 		memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
278ac27a0ecSDave Kleikamp 	inode->i_size = 0;
279bc965ab3STheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
280bc965ab3STheodore Ts'o 	if (err) {
28112062dddSEric Sandeen 		ext4_warning(inode->i_sb,
282bc965ab3STheodore Ts'o 			     "couldn't mark inode dirty (err %d)", err);
283bc965ab3STheodore Ts'o 		goto stop_handle;
284bc965ab3STheodore Ts'o 	}
2852c98eb5eSTheodore Ts'o 	if (inode->i_blocks) {
2862c98eb5eSTheodore Ts'o 		err = ext4_truncate(inode);
2872c98eb5eSTheodore Ts'o 		if (err) {
28854d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err,
2892c98eb5eSTheodore Ts'o 				       "couldn't truncate inode %lu (err %d)",
2902c98eb5eSTheodore Ts'o 				       inode->i_ino, err);
2912c98eb5eSTheodore Ts'o 			goto stop_handle;
2922c98eb5eSTheodore Ts'o 		}
2932c98eb5eSTheodore Ts'o 	}
294bc965ab3STheodore Ts'o 
29530a7eb97STahsin Erdogan 	/* Remove xattr references. */
29630a7eb97STahsin Erdogan 	err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
29730a7eb97STahsin Erdogan 				      extra_credits);
29830a7eb97STahsin Erdogan 	if (err) {
29930a7eb97STahsin Erdogan 		ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
300bc965ab3STheodore Ts'o stop_handle:
301bc965ab3STheodore Ts'o 		ext4_journal_stop(handle);
30245388219STheodore Ts'o 		ext4_orphan_del(NULL, inode);
30346e294efSJan Kara 		if (freeze_protected)
3048e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
30530a7eb97STahsin Erdogan 		ext4_xattr_inode_array_free(ea_inode_array);
306bc965ab3STheodore Ts'o 		goto no_delete;
307bc965ab3STheodore Ts'o 	}
308bc965ab3STheodore Ts'o 
309ac27a0ecSDave Kleikamp 	/*
310617ba13bSMingming Cao 	 * Kill off the orphan record which ext4_truncate created.
311ac27a0ecSDave Kleikamp 	 * AKPM: I think this can be inside the above `if'.
312617ba13bSMingming Cao 	 * Note that ext4_orphan_del() has to be able to cope with the
313ac27a0ecSDave Kleikamp 	 * deletion of a non-existent orphan - this is because we don't
314617ba13bSMingming Cao 	 * know if ext4_truncate() actually created an orphan record.
315ac27a0ecSDave Kleikamp 	 * (Well, we could do this if we need to, but heck - it works)
316ac27a0ecSDave Kleikamp 	 */
317617ba13bSMingming Cao 	ext4_orphan_del(handle, inode);
3185ffff834SArnd Bergmann 	EXT4_I(inode)->i_dtime	= (__u32)ktime_get_real_seconds();
319ac27a0ecSDave Kleikamp 
320ac27a0ecSDave Kleikamp 	/*
321ac27a0ecSDave Kleikamp 	 * One subtle ordering requirement: if anything has gone wrong
322ac27a0ecSDave Kleikamp 	 * (transaction abort, IO errors, whatever), then we can still
323ac27a0ecSDave Kleikamp 	 * do these next steps (the fs will already have been marked as
324ac27a0ecSDave Kleikamp 	 * having errors), but we can't free the inode if the mark_dirty
325ac27a0ecSDave Kleikamp 	 * fails.
326ac27a0ecSDave Kleikamp 	 */
327617ba13bSMingming Cao 	if (ext4_mark_inode_dirty(handle, inode))
328ac27a0ecSDave Kleikamp 		/* If that failed, just do the required in-core inode clear. */
3290930fcc1SAl Viro 		ext4_clear_inode(inode);
330ac27a0ecSDave Kleikamp 	else
331617ba13bSMingming Cao 		ext4_free_inode(handle, inode);
332617ba13bSMingming Cao 	ext4_journal_stop(handle);
33346e294efSJan Kara 	if (freeze_protected)
3348e8ad8a5SJan Kara 		sb_end_intwrite(inode->i_sb);
3350421a189STahsin Erdogan 	ext4_xattr_inode_array_free(ea_inode_array);
336ac27a0ecSDave Kleikamp 	return;
337ac27a0ecSDave Kleikamp no_delete:
338318cdc82SZhang Yi 	/*
339318cdc82SZhang Yi 	 * Check out some where else accidentally dirty the evicting inode,
340318cdc82SZhang Yi 	 * which may probably cause inode use-after-free issues later.
341318cdc82SZhang Yi 	 */
342318cdc82SZhang Yi 	WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));
343318cdc82SZhang Yi 
344b21ebf14SHarshad Shirwadkar 	if (!list_empty(&EXT4_I(inode)->i_fc_list))
345e85c81baSXin Yin 		ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
3460930fcc1SAl Viro 	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
347ac27a0ecSDave Kleikamp }
348ac27a0ecSDave Kleikamp 
349a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
350a9e7f447SDmitry Monakhov qsize_t *ext4_get_reserved_space(struct inode *inode)
35160e58e0fSMingming Cao {
352a9e7f447SDmitry Monakhov 	return &EXT4_I(inode)->i_reserved_quota;
35360e58e0fSMingming Cao }
354a9e7f447SDmitry Monakhov #endif
3559d0be502STheodore Ts'o 
35612219aeaSAneesh Kumar K.V /*
3570637c6f4STheodore Ts'o  * Called with i_data_sem down, which is important since we can call
3580637c6f4STheodore Ts'o  * ext4_discard_preallocations() from here.
3590637c6f4STheodore Ts'o  */
3605f634d06SAneesh Kumar K.V void ext4_da_update_reserve_space(struct inode *inode,
3615f634d06SAneesh Kumar K.V 					int used, int quota_claim)
36212219aeaSAneesh Kumar K.V {
36312219aeaSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3640637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
36512219aeaSAneesh Kumar K.V 
3660637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
367d8990240SAditya Kali 	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
3680637c6f4STheodore Ts'o 	if (unlikely(used > ei->i_reserved_data_blocks)) {
3698de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
3701084f252STheodore Ts'o 			 "with only %d reserved data blocks",
3710637c6f4STheodore Ts'o 			 __func__, inode->i_ino, used,
3720637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
3730637c6f4STheodore Ts'o 		WARN_ON(1);
3740637c6f4STheodore Ts'o 		used = ei->i_reserved_data_blocks;
3756bc6e63fSAneesh Kumar K.V 	}
37612219aeaSAneesh Kumar K.V 
3770637c6f4STheodore Ts'o 	/* Update per-inode reservations */
3780637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= used;
37971d4f7d0STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
3800637c6f4STheodore Ts'o 
381f9505c72Schenyichong 	spin_unlock(&ei->i_block_reservation_lock);
38260e58e0fSMingming Cao 
38372b8ab9dSEric Sandeen 	/* Update quota subsystem for data blocks */
38472b8ab9dSEric Sandeen 	if (quota_claim)
3857b415bf6SAditya Kali 		dquot_claim_block(inode, EXT4_C2B(sbi, used));
38672b8ab9dSEric Sandeen 	else {
3875f634d06SAneesh Kumar K.V 		/*
3885f634d06SAneesh Kumar K.V 		 * We did fallocate with an offset that is already delayed
3895f634d06SAneesh Kumar K.V 		 * allocated. So on delayed allocated writeback we should
39072b8ab9dSEric Sandeen 		 * not re-claim the quota for fallocated blocks.
3915f634d06SAneesh Kumar K.V 		 */
3927b415bf6SAditya Kali 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
3935f634d06SAneesh Kumar K.V 	}
394d6014301SAneesh Kumar K.V 
395d6014301SAneesh Kumar K.V 	/*
396d6014301SAneesh Kumar K.V 	 * If we have done all the pending block allocations and if
397d6014301SAneesh Kumar K.V 	 * there aren't any writers on the inode, we can discard the
398d6014301SAneesh Kumar K.V 	 * inode's preallocations.
399d6014301SAneesh Kumar K.V 	 */
4000637c6f4STheodore Ts'o 	if ((ei->i_reserved_data_blocks == 0) &&
40182dd124cSNikolay Borisov 	    !inode_is_open_for_write(inode))
40227bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
40312219aeaSAneesh Kumar K.V }
40412219aeaSAneesh Kumar K.V 
405e29136f8STheodore Ts'o static int __check_block_validity(struct inode *inode, const char *func,
406c398eda0STheodore Ts'o 				unsigned int line,
40724676da4STheodore Ts'o 				struct ext4_map_blocks *map)
4086fd058f7STheodore Ts'o {
409345c0dbfSTheodore Ts'o 	if (ext4_has_feature_journal(inode->i_sb) &&
410345c0dbfSTheodore Ts'o 	    (inode->i_ino ==
411345c0dbfSTheodore Ts'o 	     le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
412345c0dbfSTheodore Ts'o 		return 0;
413ce9f24ccSJan Kara 	if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
414c398eda0STheodore Ts'o 		ext4_error_inode(inode, func, line, map->m_pblk,
415bdbd6ce0STheodore Ts'o 				 "lblock %lu mapped to illegal pblock %llu "
41624676da4STheodore Ts'o 				 "(length %d)", (unsigned long) map->m_lblk,
417bdbd6ce0STheodore Ts'o 				 map->m_pblk, map->m_len);
4186a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4196fd058f7STheodore Ts'o 	}
4206fd058f7STheodore Ts'o 	return 0;
4216fd058f7STheodore Ts'o }
4226fd058f7STheodore Ts'o 
42353085facSJan Kara int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
42453085facSJan Kara 		       ext4_lblk_t len)
42553085facSJan Kara {
42653085facSJan Kara 	int ret;
42753085facSJan Kara 
42833b4cc25SEric Biggers 	if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
429a7550b30SJaegeuk Kim 		return fscrypt_zeroout_range(inode, lblk, pblk, len);
43053085facSJan Kara 
43153085facSJan Kara 	ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
43253085facSJan Kara 	if (ret > 0)
43353085facSJan Kara 		ret = 0;
43453085facSJan Kara 
43553085facSJan Kara 	return ret;
43653085facSJan Kara }
43753085facSJan Kara 
438e29136f8STheodore Ts'o #define check_block_validity(inode, map)	\
439c398eda0STheodore Ts'o 	__check_block_validity((inode), __func__, __LINE__, (map))
440e29136f8STheodore Ts'o 
441921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
442921f266bSDmitry Monakhov static void ext4_map_blocks_es_recheck(handle_t *handle,
443921f266bSDmitry Monakhov 				       struct inode *inode,
444921f266bSDmitry Monakhov 				       struct ext4_map_blocks *es_map,
445921f266bSDmitry Monakhov 				       struct ext4_map_blocks *map,
446921f266bSDmitry Monakhov 				       int flags)
447921f266bSDmitry Monakhov {
448921f266bSDmitry Monakhov 	int retval;
449921f266bSDmitry Monakhov 
450921f266bSDmitry Monakhov 	map->m_flags = 0;
451921f266bSDmitry Monakhov 	/*
452921f266bSDmitry Monakhov 	 * There is a race window that the result is not the same.
453921f266bSDmitry Monakhov 	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
454921f266bSDmitry Monakhov 	 * is that we lookup a block mapping in extent status tree with
455921f266bSDmitry Monakhov 	 * out taking i_data_sem.  So at the time the unwritten extent
456921f266bSDmitry Monakhov 	 * could be converted.
457921f266bSDmitry Monakhov 	 */
458c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
459921f266bSDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4609e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
461921f266bSDmitry Monakhov 	} else {
4629e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
463921f266bSDmitry Monakhov 	}
464921f266bSDmitry Monakhov 	up_read((&EXT4_I(inode)->i_data_sem));
465921f266bSDmitry Monakhov 
466921f266bSDmitry Monakhov 	/*
467921f266bSDmitry Monakhov 	 * We don't check m_len because extent will be collpased in status
468921f266bSDmitry Monakhov 	 * tree.  So the m_len might not equal.
469921f266bSDmitry Monakhov 	 */
470921f266bSDmitry Monakhov 	if (es_map->m_lblk != map->m_lblk ||
471921f266bSDmitry Monakhov 	    es_map->m_flags != map->m_flags ||
472921f266bSDmitry Monakhov 	    es_map->m_pblk != map->m_pblk) {
473bdafe42aSTheodore Ts'o 		printk("ES cache assertion failed for inode: %lu "
474921f266bSDmitry Monakhov 		       "es_cached ex [%d/%d/%llu/%x] != "
475921f266bSDmitry Monakhov 		       "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
476921f266bSDmitry Monakhov 		       inode->i_ino, es_map->m_lblk, es_map->m_len,
477921f266bSDmitry Monakhov 		       es_map->m_pblk, es_map->m_flags, map->m_lblk,
478921f266bSDmitry Monakhov 		       map->m_len, map->m_pblk, map->m_flags,
479921f266bSDmitry Monakhov 		       retval, flags);
480921f266bSDmitry Monakhov 	}
481921f266bSDmitry Monakhov }
482921f266bSDmitry Monakhov #endif /* ES_AGGRESSIVE_TEST */
483921f266bSDmitry Monakhov 
48455138e0bSTheodore Ts'o /*
485e35fd660STheodore Ts'o  * The ext4_map_blocks() function tries to look up the requested blocks,
4862b2d6d01STheodore Ts'o  * and returns if the blocks are already mapped.
487f5ab0d1fSMingming Cao  *
488f5ab0d1fSMingming Cao  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
489f5ab0d1fSMingming Cao  * and store the allocated blocks in the result buffer head and mark it
490f5ab0d1fSMingming Cao  * mapped.
491f5ab0d1fSMingming Cao  *
492e35fd660STheodore Ts'o  * If file type is extents based, it will call ext4_ext_map_blocks(),
493e35fd660STheodore Ts'o  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
494f5ab0d1fSMingming Cao  * based files
495f5ab0d1fSMingming Cao  *
496facab4d9SJan Kara  * On success, it returns the number of blocks being mapped or allocated.  if
497facab4d9SJan Kara  * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
498facab4d9SJan Kara  * is marked as unwritten. If the create == 1, it will mark @map as mapped.
499f5ab0d1fSMingming Cao  *
500f5ab0d1fSMingming Cao  * It returns 0 if plain look up failed (blocks have not been allocated), in
501facab4d9SJan Kara  * that case, @map is returned as unmapped but we still do fill map->m_len to
502facab4d9SJan Kara  * indicate the length of a hole starting at map->m_lblk.
503f5ab0d1fSMingming Cao  *
504f5ab0d1fSMingming Cao  * It returns the error in case of allocation failure.
505f5ab0d1fSMingming Cao  */
506e35fd660STheodore Ts'o int ext4_map_blocks(handle_t *handle, struct inode *inode,
507e35fd660STheodore Ts'o 		    struct ext4_map_blocks *map, int flags)
5080e855ac8SAneesh Kumar K.V {
509d100eef2SZheng Liu 	struct extent_status es;
5100e855ac8SAneesh Kumar K.V 	int retval;
511b8a86845SLukas Czerner 	int ret = 0;
512921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
513921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
514921f266bSDmitry Monakhov 
515921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
516921f266bSDmitry Monakhov #endif
517f5ab0d1fSMingming Cao 
518e35fd660STheodore Ts'o 	map->m_flags = 0;
51970aa1554SRitesh Harjani 	ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
52070aa1554SRitesh Harjani 		  flags, map->m_len, (unsigned long) map->m_lblk);
521d100eef2SZheng Liu 
522e861b5e9STheodore Ts'o 	/*
523e861b5e9STheodore Ts'o 	 * ext4_map_blocks returns an int, and m_len is an unsigned int
524e861b5e9STheodore Ts'o 	 */
525e861b5e9STheodore Ts'o 	if (unlikely(map->m_len > INT_MAX))
526e861b5e9STheodore Ts'o 		map->m_len = INT_MAX;
527e861b5e9STheodore Ts'o 
5284adb6ab3SKazuya Mio 	/* We can handle the block number less than EXT_MAX_BLOCKS */
5294adb6ab3SKazuya Mio 	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
5306a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
5314adb6ab3SKazuya Mio 
532d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
5338016e29fSHarshad Shirwadkar 	if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
5348016e29fSHarshad Shirwadkar 	    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
535d100eef2SZheng Liu 		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
536d100eef2SZheng Liu 			map->m_pblk = ext4_es_pblock(&es) +
537d100eef2SZheng Liu 					map->m_lblk - es.es_lblk;
538d100eef2SZheng Liu 			map->m_flags |= ext4_es_is_written(&es) ?
539d100eef2SZheng Liu 					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
540d100eef2SZheng Liu 			retval = es.es_len - (map->m_lblk - es.es_lblk);
541d100eef2SZheng Liu 			if (retval > map->m_len)
542d100eef2SZheng Liu 				retval = map->m_len;
543d100eef2SZheng Liu 			map->m_len = retval;
544d100eef2SZheng Liu 		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
545facab4d9SJan Kara 			map->m_pblk = 0;
546facab4d9SJan Kara 			retval = es.es_len - (map->m_lblk - es.es_lblk);
547facab4d9SJan Kara 			if (retval > map->m_len)
548facab4d9SJan Kara 				retval = map->m_len;
549facab4d9SJan Kara 			map->m_len = retval;
550d100eef2SZheng Liu 			retval = 0;
551d100eef2SZheng Liu 		} else {
5521e83bc81SArnd Bergmann 			BUG();
553d100eef2SZheng Liu 		}
5549558cf14SZhang Yi 
5559558cf14SZhang Yi 		if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5569558cf14SZhang Yi 			return retval;
557921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
558921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(handle, inode, map,
559921f266bSDmitry Monakhov 					   &orig_map, flags);
560921f266bSDmitry Monakhov #endif
561d100eef2SZheng Liu 		goto found;
562d100eef2SZheng Liu 	}
5639558cf14SZhang Yi 	/*
5649558cf14SZhang Yi 	 * In the query cache no-wait mode, nothing we can do more if we
5659558cf14SZhang Yi 	 * cannot find extent in the cache.
5669558cf14SZhang Yi 	 */
5679558cf14SZhang Yi 	if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
5689558cf14SZhang Yi 		return 0;
569d100eef2SZheng Liu 
5704df3d265SAneesh Kumar K.V 	/*
571b920c755STheodore Ts'o 	 * Try to see if we can get the block without requesting a new
572b920c755STheodore Ts'o 	 * file system block.
5734df3d265SAneesh Kumar K.V 	 */
574c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
57512e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5769e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
5774df3d265SAneesh Kumar K.V 	} else {
5789e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
5790e855ac8SAneesh Kumar K.V 	}
580f7fec032SZheng Liu 	if (retval > 0) {
5813be78c73STheodore Ts'o 		unsigned int status;
582f7fec032SZheng Liu 
58344fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
58444fb851dSZheng Liu 			ext4_warning(inode->i_sb,
58544fb851dSZheng Liu 				     "ES len assertion failed for inode "
58644fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
58744fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
58844fb851dSZheng Liu 			WARN_ON(1);
589921f266bSDmitry Monakhov 		}
590921f266bSDmitry Monakhov 
591f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
592f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
593f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
594d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
595ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
596f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
597f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
598f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk,
599f7fec032SZheng Liu 					    map->m_len, map->m_pblk, status);
600f7fec032SZheng Liu 		if (ret < 0)
601f7fec032SZheng Liu 			retval = ret;
602f7fec032SZheng Liu 	}
6034df3d265SAneesh Kumar K.V 	up_read((&EXT4_I(inode)->i_data_sem));
604f5ab0d1fSMingming Cao 
605d100eef2SZheng Liu found:
606e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
607b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
6086fd058f7STheodore Ts'o 		if (ret != 0)
6096fd058f7STheodore Ts'o 			return ret;
6106fd058f7STheodore Ts'o 	}
6116fd058f7STheodore Ts'o 
612f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
613c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
6144df3d265SAneesh Kumar K.V 		return retval;
6154df3d265SAneesh Kumar K.V 
6164df3d265SAneesh Kumar K.V 	/*
617f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
618f5ab0d1fSMingming Cao 	 *
619f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
620df3ab170STao Ma 	 * ext4_ext_get_block() returns the create = 0
621f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
622f5ab0d1fSMingming Cao 	 */
623e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
624b8a86845SLukas Czerner 		/*
625b8a86845SLukas Czerner 		 * If we need to convert extent to unwritten
626b8a86845SLukas Czerner 		 * we continue and do the actual work in
627b8a86845SLukas Czerner 		 * ext4_ext_map_blocks()
628b8a86845SLukas Czerner 		 */
629b8a86845SLukas Czerner 		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
630f5ab0d1fSMingming Cao 			return retval;
631f5ab0d1fSMingming Cao 
632f5ab0d1fSMingming Cao 	/*
633a25a4e1aSZheng Liu 	 * Here we clear m_flags because after allocating an new extent,
634a25a4e1aSZheng Liu 	 * it will be set again.
6352a8964d6SAneesh Kumar K.V 	 */
636a25a4e1aSZheng Liu 	map->m_flags &= ~EXT4_MAP_FLAGS;
6372a8964d6SAneesh Kumar K.V 
6382a8964d6SAneesh Kumar K.V 	/*
639556615dcSLukas Czerner 	 * New blocks allocate and/or writing to unwritten extent
640f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
641d91bd2c1SSeunghun Lee 	 * the write lock of i_data_sem, and call get_block()
642f5ab0d1fSMingming Cao 	 * with create == 1 flag.
6434df3d265SAneesh Kumar K.V 	 */
644c8b459f4SLukas Czerner 	down_write(&EXT4_I(inode)->i_data_sem);
645d2a17637SMingming Cao 
646d2a17637SMingming Cao 	/*
6474df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
6484df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
6494df3d265SAneesh Kumar K.V 	 */
65012e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
651e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
6520e855ac8SAneesh Kumar K.V 	} else {
653e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
654267e4db9SAneesh Kumar K.V 
655e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
656267e4db9SAneesh Kumar K.V 			/*
657267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
658267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
659267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
660267e4db9SAneesh Kumar K.V 			 */
66119f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
662267e4db9SAneesh Kumar K.V 		}
6632ac3b6e0STheodore Ts'o 
664d2a17637SMingming Cao 		/*
6652ac3b6e0STheodore Ts'o 		 * Update reserved blocks/metadata blocks after successful
6665f634d06SAneesh Kumar K.V 		 * block allocation which had been deferred till now. We don't
6675f634d06SAneesh Kumar K.V 		 * support fallocate for non extent files. So we can update
6685f634d06SAneesh Kumar K.V 		 * reserve space here.
669d2a17637SMingming Cao 		 */
6705f634d06SAneesh Kumar K.V 		if ((retval > 0) &&
6711296cc85SAneesh Kumar K.V 			(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
6725f634d06SAneesh Kumar K.V 			ext4_da_update_reserve_space(inode, retval, 1);
6735f634d06SAneesh Kumar K.V 	}
674d2a17637SMingming Cao 
675f7fec032SZheng Liu 	if (retval > 0) {
6763be78c73STheodore Ts'o 		unsigned int status;
677f7fec032SZheng Liu 
67844fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
67944fb851dSZheng Liu 			ext4_warning(inode->i_sb,
68044fb851dSZheng Liu 				     "ES len assertion failed for inode "
68144fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
68244fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
68344fb851dSZheng Liu 			WARN_ON(1);
684921f266bSDmitry Monakhov 		}
685921f266bSDmitry Monakhov 
686adb23551SZheng Liu 		/*
687c86d8db3SJan Kara 		 * We have to zeroout blocks before inserting them into extent
688c86d8db3SJan Kara 		 * status tree. Otherwise someone could look them up there and
6899b623df6SJan Kara 		 * use them before they are really zeroed. We also have to
6909b623df6SJan Kara 		 * unmap metadata before zeroing as otherwise writeback can
6919b623df6SJan Kara 		 * overwrite zeros with stale data from block device.
692c86d8db3SJan Kara 		 */
693c86d8db3SJan Kara 		if (flags & EXT4_GET_BLOCKS_ZERO &&
694c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_MAPPED &&
695c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_NEW) {
696c86d8db3SJan Kara 			ret = ext4_issue_zeroout(inode, map->m_lblk,
697c86d8db3SJan Kara 						 map->m_pblk, map->m_len);
698c86d8db3SJan Kara 			if (ret) {
699c86d8db3SJan Kara 				retval = ret;
700c86d8db3SJan Kara 				goto out_sem;
701c86d8db3SJan Kara 			}
702c86d8db3SJan Kara 		}
703c86d8db3SJan Kara 
704c86d8db3SJan Kara 		/*
705adb23551SZheng Liu 		 * If the extent has been zeroed out, we don't need to update
706adb23551SZheng Liu 		 * extent status tree.
707adb23551SZheng Liu 		 */
708adb23551SZheng Liu 		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
709bb5835edSTheodore Ts'o 		    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
710adb23551SZheng Liu 			if (ext4_es_is_written(&es))
711c86d8db3SJan Kara 				goto out_sem;
712adb23551SZheng Liu 		}
713f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
714f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
715f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
716d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
717ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
718f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
719f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
720f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
721f7fec032SZheng Liu 					    map->m_pblk, status);
722c86d8db3SJan Kara 		if (ret < 0) {
72351865fdaSZheng Liu 			retval = ret;
724c86d8db3SJan Kara 			goto out_sem;
725c86d8db3SJan Kara 		}
72651865fdaSZheng Liu 	}
7275356f261SAditya Kali 
728c86d8db3SJan Kara out_sem:
7290e855ac8SAneesh Kumar K.V 	up_write((&EXT4_I(inode)->i_data_sem));
730e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
731b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
7326fd058f7STheodore Ts'o 		if (ret != 0)
7336fd058f7STheodore Ts'o 			return ret;
73406bd3c36SJan Kara 
73506bd3c36SJan Kara 		/*
73606bd3c36SJan Kara 		 * Inodes with freshly allocated blocks where contents will be
73706bd3c36SJan Kara 		 * visible after transaction commit must be on transaction's
73806bd3c36SJan Kara 		 * ordered data list.
73906bd3c36SJan Kara 		 */
74006bd3c36SJan Kara 		if (map->m_flags & EXT4_MAP_NEW &&
74106bd3c36SJan Kara 		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
74206bd3c36SJan Kara 		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
74302749a4cSTahsin Erdogan 		    !ext4_is_quota_file(inode) &&
74406bd3c36SJan Kara 		    ext4_should_order_data(inode)) {
74573131fbbSRoss Zwisler 			loff_t start_byte =
74673131fbbSRoss Zwisler 				(loff_t)map->m_lblk << inode->i_blkbits;
74773131fbbSRoss Zwisler 			loff_t length = (loff_t)map->m_len << inode->i_blkbits;
74873131fbbSRoss Zwisler 
749ee0876bcSJan Kara 			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
75073131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_wait(handle, inode,
75173131fbbSRoss Zwisler 						start_byte, length);
752ee0876bcSJan Kara 			else
75373131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_write(handle, inode,
75473131fbbSRoss Zwisler 						start_byte, length);
75506bd3c36SJan Kara 			if (ret)
75606bd3c36SJan Kara 				return ret;
75706bd3c36SJan Kara 		}
7585e4d0ebaSXin Yin 	}
7595e4d0ebaSXin Yin 	if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
7605e4d0ebaSXin Yin 				map->m_flags & EXT4_MAP_MAPPED))
761a80f7fcfSHarshad Shirwadkar 		ext4_fc_track_range(handle, inode, map->m_lblk,
762aa75f4d3SHarshad Shirwadkar 					map->m_lblk + map->m_len - 1);
763ec8c60beSRitesh Harjani 	if (retval < 0)
76470aa1554SRitesh Harjani 		ext_debug(inode, "failed with err %d\n", retval);
7650e855ac8SAneesh Kumar K.V 	return retval;
7660e855ac8SAneesh Kumar K.V }
7670e855ac8SAneesh Kumar K.V 
768ed8ad838SJan Kara /*
769ed8ad838SJan Kara  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
770ed8ad838SJan Kara  * we have to be careful as someone else may be manipulating b_state as well.
771ed8ad838SJan Kara  */
772ed8ad838SJan Kara static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
773ed8ad838SJan Kara {
774ed8ad838SJan Kara 	unsigned long old_state;
775ed8ad838SJan Kara 	unsigned long new_state;
776ed8ad838SJan Kara 
777ed8ad838SJan Kara 	flags &= EXT4_MAP_FLAGS;
778ed8ad838SJan Kara 
779ed8ad838SJan Kara 	/* Dummy buffer_head? Set non-atomically. */
780ed8ad838SJan Kara 	if (!bh->b_page) {
781ed8ad838SJan Kara 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
782ed8ad838SJan Kara 		return;
783ed8ad838SJan Kara 	}
784ed8ad838SJan Kara 	/*
785ed8ad838SJan Kara 	 * Someone else may be modifying b_state. Be careful! This is ugly but
786ed8ad838SJan Kara 	 * once we get rid of using bh as a container for mapping information
787ed8ad838SJan Kara 	 * to pass to / from get_block functions, this can go away.
788ed8ad838SJan Kara 	 */
789ed8ad838SJan Kara 	do {
790ed8ad838SJan Kara 		old_state = READ_ONCE(bh->b_state);
791ed8ad838SJan Kara 		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
792ed8ad838SJan Kara 	} while (unlikely(
793ed8ad838SJan Kara 		 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
794ed8ad838SJan Kara }
795ed8ad838SJan Kara 
7962ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
7972ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
798ac27a0ecSDave Kleikamp {
7992ed88685STheodore Ts'o 	struct ext4_map_blocks map;
800efe70c29SJan Kara 	int ret = 0;
801ac27a0ecSDave Kleikamp 
80246c7f254STao Ma 	if (ext4_has_inline_data(inode))
80346c7f254STao Ma 		return -ERANGE;
80446c7f254STao Ma 
8052ed88685STheodore Ts'o 	map.m_lblk = iblock;
8062ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
8072ed88685STheodore Ts'o 
808efe70c29SJan Kara 	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
809efe70c29SJan Kara 			      flags);
810ac27a0ecSDave Kleikamp 	if (ret > 0) {
8112ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
812ed8ad838SJan Kara 		ext4_update_bh_state(bh, map.m_flags);
8132ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
814ac27a0ecSDave Kleikamp 		ret = 0;
815547edce3SRoss Zwisler 	} else if (ret == 0) {
816547edce3SRoss Zwisler 		/* hole case, need to fill in bh->b_size */
817547edce3SRoss Zwisler 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
818ac27a0ecSDave Kleikamp 	}
819ac27a0ecSDave Kleikamp 	return ret;
820ac27a0ecSDave Kleikamp }
821ac27a0ecSDave Kleikamp 
8222ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
8232ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
8242ed88685STheodore Ts'o {
8252ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
8262ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
8272ed88685STheodore Ts'o }
8282ed88685STheodore Ts'o 
829ac27a0ecSDave Kleikamp /*
830705965bdSJan Kara  * Get block function used when preparing for buffered write if we require
831705965bdSJan Kara  * creating an unwritten extent if blocks haven't been allocated.  The extent
832705965bdSJan Kara  * will be converted to written after the IO is complete.
833705965bdSJan Kara  */
834705965bdSJan Kara int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
835705965bdSJan Kara 			     struct buffer_head *bh_result, int create)
836705965bdSJan Kara {
837705965bdSJan Kara 	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
838705965bdSJan Kara 		   inode->i_ino, create);
839705965bdSJan Kara 	return _ext4_get_block(inode, iblock, bh_result,
8408d5459c1SJan Kara 			       EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
841705965bdSJan Kara }
842705965bdSJan Kara 
843efe70c29SJan Kara /* Maximum number of blocks we map for direct IO at once. */
844efe70c29SJan Kara #define DIO_MAX_BLOCKS 4096
845efe70c29SJan Kara 
846e84dfbe2SJan Kara /*
847ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
848ac27a0ecSDave Kleikamp  */
849617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
850c5e298aeSTheodore Ts'o 				ext4_lblk_t block, int map_flags)
851ac27a0ecSDave Kleikamp {
8522ed88685STheodore Ts'o 	struct ext4_map_blocks map;
8532ed88685STheodore Ts'o 	struct buffer_head *bh;
854c5e298aeSTheodore Ts'o 	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
8559558cf14SZhang Yi 	bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
85610560082STheodore Ts'o 	int err;
857ac27a0ecSDave Kleikamp 
858837c23fbSChunguang Xu 	ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8598016e29fSHarshad Shirwadkar 		    || handle != NULL || create == 0);
8609558cf14SZhang Yi 	ASSERT(create == 0 || !nowait);
861ac27a0ecSDave Kleikamp 
8622ed88685STheodore Ts'o 	map.m_lblk = block;
8632ed88685STheodore Ts'o 	map.m_len = 1;
864c5e298aeSTheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map, map_flags);
8652ed88685STheodore Ts'o 
86610560082STheodore Ts'o 	if (err == 0)
86710560082STheodore Ts'o 		return create ? ERR_PTR(-ENOSPC) : NULL;
8682ed88685STheodore Ts'o 	if (err < 0)
86910560082STheodore Ts'o 		return ERR_PTR(err);
8702ed88685STheodore Ts'o 
8719558cf14SZhang Yi 	if (nowait)
8729558cf14SZhang Yi 		return sb_find_get_block(inode->i_sb, map.m_pblk);
8739558cf14SZhang Yi 
8742ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
87510560082STheodore Ts'o 	if (unlikely(!bh))
87610560082STheodore Ts'o 		return ERR_PTR(-ENOMEM);
8772ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
878837c23fbSChunguang Xu 		ASSERT(create != 0);
879837c23fbSChunguang Xu 		ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8808016e29fSHarshad Shirwadkar 			    || (handle != NULL));
881ac27a0ecSDave Kleikamp 
882ac27a0ecSDave Kleikamp 		/*
883ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
884ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
885ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
886617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
887ac27a0ecSDave Kleikamp 		 * problem.
888ac27a0ecSDave Kleikamp 		 */
889ac27a0ecSDave Kleikamp 		lock_buffer(bh);
890ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
891188c299eSJan Kara 		err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
892188c299eSJan Kara 						     EXT4_JTR_NONE);
89310560082STheodore Ts'o 		if (unlikely(err)) {
89410560082STheodore Ts'o 			unlock_buffer(bh);
89510560082STheodore Ts'o 			goto errout;
89610560082STheodore Ts'o 		}
89710560082STheodore Ts'o 		if (!buffer_uptodate(bh)) {
898ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
899ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
900ac27a0ecSDave Kleikamp 		}
901ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
9020390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
9030390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
90410560082STheodore Ts'o 		if (unlikely(err))
90510560082STheodore Ts'o 			goto errout;
90610560082STheodore Ts'o 	} else
907ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
908ac27a0ecSDave Kleikamp 	return bh;
90910560082STheodore Ts'o errout:
91010560082STheodore Ts'o 	brelse(bh);
91110560082STheodore Ts'o 	return ERR_PTR(err);
912ac27a0ecSDave Kleikamp }
913ac27a0ecSDave Kleikamp 
914617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
915c5e298aeSTheodore Ts'o 			       ext4_lblk_t block, int map_flags)
916ac27a0ecSDave Kleikamp {
917ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
9182d069c08Szhangyi (F) 	int ret;
919ac27a0ecSDave Kleikamp 
920c5e298aeSTheodore Ts'o 	bh = ext4_getblk(handle, inode, block, map_flags);
9211c215028STheodore Ts'o 	if (IS_ERR(bh))
922ac27a0ecSDave Kleikamp 		return bh;
9237963e5acSZhangXiaoxu 	if (!bh || ext4_buffer_uptodate(bh))
924ac27a0ecSDave Kleikamp 		return bh;
9252d069c08Szhangyi (F) 
9262d069c08Szhangyi (F) 	ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
9272d069c08Szhangyi (F) 	if (ret) {
928ac27a0ecSDave Kleikamp 		put_bh(bh);
9292d069c08Szhangyi (F) 		return ERR_PTR(ret);
9302d069c08Szhangyi (F) 	}
9312d069c08Szhangyi (F) 	return bh;
932ac27a0ecSDave Kleikamp }
933ac27a0ecSDave Kleikamp 
9349699d4f9STahsin Erdogan /* Read a contiguous batch of blocks. */
9359699d4f9STahsin Erdogan int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
9369699d4f9STahsin Erdogan 		     bool wait, struct buffer_head **bhs)
9379699d4f9STahsin Erdogan {
9389699d4f9STahsin Erdogan 	int i, err;
9399699d4f9STahsin Erdogan 
9409699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9419699d4f9STahsin Erdogan 		bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
9429699d4f9STahsin Erdogan 		if (IS_ERR(bhs[i])) {
9439699d4f9STahsin Erdogan 			err = PTR_ERR(bhs[i]);
9449699d4f9STahsin Erdogan 			bh_count = i;
9459699d4f9STahsin Erdogan 			goto out_brelse;
9469699d4f9STahsin Erdogan 		}
9479699d4f9STahsin Erdogan 	}
9489699d4f9STahsin Erdogan 
9499699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9509699d4f9STahsin Erdogan 		/* Note that NULL bhs[i] is valid because of holes. */
9512d069c08Szhangyi (F) 		if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
9522d069c08Szhangyi (F) 			ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
9539699d4f9STahsin Erdogan 
9549699d4f9STahsin Erdogan 	if (!wait)
9559699d4f9STahsin Erdogan 		return 0;
9569699d4f9STahsin Erdogan 
9579699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9589699d4f9STahsin Erdogan 		if (bhs[i])
9599699d4f9STahsin Erdogan 			wait_on_buffer(bhs[i]);
9609699d4f9STahsin Erdogan 
9619699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9629699d4f9STahsin Erdogan 		if (bhs[i] && !buffer_uptodate(bhs[i])) {
9639699d4f9STahsin Erdogan 			err = -EIO;
9649699d4f9STahsin Erdogan 			goto out_brelse;
9659699d4f9STahsin Erdogan 		}
9669699d4f9STahsin Erdogan 	}
9679699d4f9STahsin Erdogan 	return 0;
9689699d4f9STahsin Erdogan 
9699699d4f9STahsin Erdogan out_brelse:
9709699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9719699d4f9STahsin Erdogan 		brelse(bhs[i]);
9729699d4f9STahsin Erdogan 		bhs[i] = NULL;
9739699d4f9STahsin Erdogan 	}
9749699d4f9STahsin Erdogan 	return err;
9759699d4f9STahsin Erdogan }
9769699d4f9STahsin Erdogan 
977188c299eSJan Kara int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
978ac27a0ecSDave Kleikamp 			   struct buffer_head *head,
979ac27a0ecSDave Kleikamp 			   unsigned from,
980ac27a0ecSDave Kleikamp 			   unsigned to,
981ac27a0ecSDave Kleikamp 			   int *partial,
982188c299eSJan Kara 			   int (*fn)(handle_t *handle, struct inode *inode,
983ac27a0ecSDave Kleikamp 				     struct buffer_head *bh))
984ac27a0ecSDave Kleikamp {
985ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
986ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
987ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
988ac27a0ecSDave Kleikamp 	int err, ret = 0;
989ac27a0ecSDave Kleikamp 	struct buffer_head *next;
990ac27a0ecSDave Kleikamp 
991ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
992ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
993de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
994ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
995ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
996ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
997ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
998ac27a0ecSDave Kleikamp 				*partial = 1;
999ac27a0ecSDave Kleikamp 			continue;
1000ac27a0ecSDave Kleikamp 		}
1001188c299eSJan Kara 		err = (*fn)(handle, inode, bh);
1002ac27a0ecSDave Kleikamp 		if (!ret)
1003ac27a0ecSDave Kleikamp 			ret = err;
1004ac27a0ecSDave Kleikamp 	}
1005ac27a0ecSDave Kleikamp 	return ret;
1006ac27a0ecSDave Kleikamp }
1007ac27a0ecSDave Kleikamp 
1008ac27a0ecSDave Kleikamp /*
1009ac27a0ecSDave Kleikamp  * To preserve ordering, it is essential that the hole instantiation and
1010ac27a0ecSDave Kleikamp  * the data write be encapsulated in a single transaction.  We cannot
1011617ba13bSMingming Cao  * close off a transaction and start a new one between the ext4_get_block()
1012dab291afSMingming Cao  * and the commit_write().  So doing the jbd2_journal_start at the start of
1013ac27a0ecSDave Kleikamp  * prepare_write() is the right place.
1014ac27a0ecSDave Kleikamp  *
101536ade451SJan Kara  * Also, this function can nest inside ext4_writepage().  In that case, we
101636ade451SJan Kara  * *know* that ext4_writepage() has generated enough buffer credits to do the
101736ade451SJan Kara  * whole page.  So we won't block on the journal in that case, which is good,
101836ade451SJan Kara  * because the caller may be PF_MEMALLOC.
1019ac27a0ecSDave Kleikamp  *
1020617ba13bSMingming Cao  * By accident, ext4 can be reentered when a transaction is open via
1021ac27a0ecSDave Kleikamp  * quota file writes.  If we were to commit the transaction while thus
1022ac27a0ecSDave Kleikamp  * reentered, there can be a deadlock - we would be holding a quota
1023ac27a0ecSDave Kleikamp  * lock, and the commit would never complete if another thread had a
1024ac27a0ecSDave Kleikamp  * transaction open and was blocking on the quota lock - a ranking
1025ac27a0ecSDave Kleikamp  * violation.
1026ac27a0ecSDave Kleikamp  *
1027dab291afSMingming Cao  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1028ac27a0ecSDave Kleikamp  * will _not_ run commit under these circumstances because handle->h_ref
1029ac27a0ecSDave Kleikamp  * is elevated.  We'll still have enough credits for the tiny quotafile
1030ac27a0ecSDave Kleikamp  * write.
1031ac27a0ecSDave Kleikamp  */
1032188c299eSJan Kara int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1033ac27a0ecSDave Kleikamp 				struct buffer_head *bh)
1034ac27a0ecSDave Kleikamp {
103556d35a4cSJan Kara 	int dirty = buffer_dirty(bh);
103656d35a4cSJan Kara 	int ret;
103756d35a4cSJan Kara 
1038ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1039ac27a0ecSDave Kleikamp 		return 0;
104056d35a4cSJan Kara 	/*
1041ebdec241SChristoph Hellwig 	 * __block_write_begin() could have dirtied some buffers. Clean
104256d35a4cSJan Kara 	 * the dirty bit as jbd2_journal_get_write_access() could complain
104356d35a4cSJan Kara 	 * otherwise about fs integrity issues. Setting of the dirty bit
1044ebdec241SChristoph Hellwig 	 * by __block_write_begin() isn't a real problem here as we clear
104556d35a4cSJan Kara 	 * the bit before releasing a page lock and thus writeback cannot
104656d35a4cSJan Kara 	 * ever write the buffer.
104756d35a4cSJan Kara 	 */
104856d35a4cSJan Kara 	if (dirty)
104956d35a4cSJan Kara 		clear_buffer_dirty(bh);
10505d601255Sliang xie 	BUFFER_TRACE(bh, "get write access");
1051188c299eSJan Kara 	ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
1052188c299eSJan Kara 					    EXT4_JTR_NONE);
105356d35a4cSJan Kara 	if (!ret && dirty)
105456d35a4cSJan Kara 		ret = ext4_handle_dirty_metadata(handle, NULL, bh);
105556d35a4cSJan Kara 	return ret;
1056ac27a0ecSDave Kleikamp }
1057ac27a0ecSDave Kleikamp 
1058643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
10592058f83aSMichael Halcrow static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
10602058f83aSMichael Halcrow 				  get_block_t *get_block)
10612058f83aSMichael Halcrow {
106209cbfeafSKirill A. Shutemov 	unsigned from = pos & (PAGE_SIZE - 1);
10632058f83aSMichael Halcrow 	unsigned to = from + len;
10642058f83aSMichael Halcrow 	struct inode *inode = page->mapping->host;
10652058f83aSMichael Halcrow 	unsigned block_start, block_end;
10662058f83aSMichael Halcrow 	sector_t block;
10672058f83aSMichael Halcrow 	int err = 0;
10682058f83aSMichael Halcrow 	unsigned blocksize = inode->i_sb->s_blocksize;
10692058f83aSMichael Halcrow 	unsigned bbits;
10700b578f35SChandan Rajendra 	struct buffer_head *bh, *head, *wait[2];
10710b578f35SChandan Rajendra 	int nr_wait = 0;
10720b578f35SChandan Rajendra 	int i;
10732058f83aSMichael Halcrow 
10742058f83aSMichael Halcrow 	BUG_ON(!PageLocked(page));
107509cbfeafSKirill A. Shutemov 	BUG_ON(from > PAGE_SIZE);
107609cbfeafSKirill A. Shutemov 	BUG_ON(to > PAGE_SIZE);
10772058f83aSMichael Halcrow 	BUG_ON(from > to);
10782058f83aSMichael Halcrow 
10792058f83aSMichael Halcrow 	if (!page_has_buffers(page))
10802058f83aSMichael Halcrow 		create_empty_buffers(page, blocksize, 0);
10812058f83aSMichael Halcrow 	head = page_buffers(page);
10822058f83aSMichael Halcrow 	bbits = ilog2(blocksize);
108309cbfeafSKirill A. Shutemov 	block = (sector_t)page->index << (PAGE_SHIFT - bbits);
10842058f83aSMichael Halcrow 
10852058f83aSMichael Halcrow 	for (bh = head, block_start = 0; bh != head || !block_start;
10862058f83aSMichael Halcrow 	    block++, block_start = block_end, bh = bh->b_this_page) {
10872058f83aSMichael Halcrow 		block_end = block_start + blocksize;
10882058f83aSMichael Halcrow 		if (block_end <= from || block_start >= to) {
10892058f83aSMichael Halcrow 			if (PageUptodate(page)) {
10902058f83aSMichael Halcrow 				set_buffer_uptodate(bh);
10912058f83aSMichael Halcrow 			}
10922058f83aSMichael Halcrow 			continue;
10932058f83aSMichael Halcrow 		}
10942058f83aSMichael Halcrow 		if (buffer_new(bh))
10952058f83aSMichael Halcrow 			clear_buffer_new(bh);
10962058f83aSMichael Halcrow 		if (!buffer_mapped(bh)) {
10972058f83aSMichael Halcrow 			WARN_ON(bh->b_size != blocksize);
10982058f83aSMichael Halcrow 			err = get_block(inode, block, bh, 1);
10992058f83aSMichael Halcrow 			if (err)
11002058f83aSMichael Halcrow 				break;
11012058f83aSMichael Halcrow 			if (buffer_new(bh)) {
11022058f83aSMichael Halcrow 				if (PageUptodate(page)) {
11032058f83aSMichael Halcrow 					clear_buffer_new(bh);
11042058f83aSMichael Halcrow 					set_buffer_uptodate(bh);
11052058f83aSMichael Halcrow 					mark_buffer_dirty(bh);
11062058f83aSMichael Halcrow 					continue;
11072058f83aSMichael Halcrow 				}
11082058f83aSMichael Halcrow 				if (block_end > to || block_start < from)
11092058f83aSMichael Halcrow 					zero_user_segments(page, to, block_end,
11102058f83aSMichael Halcrow 							   block_start, from);
11112058f83aSMichael Halcrow 				continue;
11122058f83aSMichael Halcrow 			}
11132058f83aSMichael Halcrow 		}
11142058f83aSMichael Halcrow 		if (PageUptodate(page)) {
11152058f83aSMichael Halcrow 			set_buffer_uptodate(bh);
11162058f83aSMichael Halcrow 			continue;
11172058f83aSMichael Halcrow 		}
11182058f83aSMichael Halcrow 		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
11192058f83aSMichael Halcrow 		    !buffer_unwritten(bh) &&
11202058f83aSMichael Halcrow 		    (block_start < from || block_end > to)) {
11212d069c08Szhangyi (F) 			ext4_read_bh_lock(bh, 0, false);
11220b578f35SChandan Rajendra 			wait[nr_wait++] = bh;
11232058f83aSMichael Halcrow 		}
11242058f83aSMichael Halcrow 	}
11252058f83aSMichael Halcrow 	/*
11262058f83aSMichael Halcrow 	 * If we issued read requests, let them complete.
11272058f83aSMichael Halcrow 	 */
11280b578f35SChandan Rajendra 	for (i = 0; i < nr_wait; i++) {
11290b578f35SChandan Rajendra 		wait_on_buffer(wait[i]);
11300b578f35SChandan Rajendra 		if (!buffer_uptodate(wait[i]))
11312058f83aSMichael Halcrow 			err = -EIO;
11322058f83aSMichael Halcrow 	}
11337e0785fcSChandan Rajendra 	if (unlikely(err)) {
11342058f83aSMichael Halcrow 		page_zero_new_buffers(page, from, to);
11354f74d15fSEric Biggers 	} else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
11360b578f35SChandan Rajendra 		for (i = 0; i < nr_wait; i++) {
11370b578f35SChandan Rajendra 			int err2;
11380b578f35SChandan Rajendra 
11390b578f35SChandan Rajendra 			err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
11400b578f35SChandan Rajendra 								bh_offset(wait[i]));
11410b578f35SChandan Rajendra 			if (err2) {
11420b578f35SChandan Rajendra 				clear_buffer_uptodate(wait[i]);
11430b578f35SChandan Rajendra 				err = err2;
11440b578f35SChandan Rajendra 			}
11450b578f35SChandan Rajendra 		}
11467e0785fcSChandan Rajendra 	}
11477e0785fcSChandan Rajendra 
11482058f83aSMichael Halcrow 	return err;
11492058f83aSMichael Halcrow }
11502058f83aSMichael Halcrow #endif
11512058f83aSMichael Halcrow 
1152bfc1af65SNick Piggin static int ext4_write_begin(struct file *file, struct address_space *mapping,
11539d6b0cd7SMatthew Wilcox (Oracle) 			    loff_t pos, unsigned len,
1154bfc1af65SNick Piggin 			    struct page **pagep, void **fsdata)
1155ac27a0ecSDave Kleikamp {
1156bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
11571938a150SAneesh Kumar K.V 	int ret, needed_blocks;
1158ac27a0ecSDave Kleikamp 	handle_t *handle;
1159ac27a0ecSDave Kleikamp 	int retries = 0;
1160bfc1af65SNick Piggin 	struct page *page;
1161bfc1af65SNick Piggin 	pgoff_t index;
1162bfc1af65SNick Piggin 	unsigned from, to;
1163bfc1af65SNick Piggin 
11640db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
11650db1ff22STheodore Ts'o 		return -EIO;
11660db1ff22STheodore Ts'o 
11679d6b0cd7SMatthew Wilcox (Oracle) 	trace_ext4_write_begin(inode, pos, len);
11681938a150SAneesh Kumar K.V 	/*
11691938a150SAneesh Kumar K.V 	 * Reserve one block more for addition to orphan list in case
11701938a150SAneesh Kumar K.V 	 * we allocate blocks but write fails for some reason
11711938a150SAneesh Kumar K.V 	 */
11721938a150SAneesh Kumar K.V 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
117309cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
117409cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1175bfc1af65SNick Piggin 	to = from + len;
1176ac27a0ecSDave Kleikamp 
1177f19d5870STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1178f19d5870STao Ma 		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1179832ee62dSMatthew Wilcox (Oracle) 						    pagep);
1180f19d5870STao Ma 		if (ret < 0)
118147564bfbSTheodore Ts'o 			return ret;
118247564bfbSTheodore Ts'o 		if (ret == 1)
118347564bfbSTheodore Ts'o 			return 0;
1184f19d5870STao Ma 	}
1185f19d5870STao Ma 
118647564bfbSTheodore Ts'o 	/*
118747564bfbSTheodore Ts'o 	 * grab_cache_page_write_begin() can take a long time if the
118847564bfbSTheodore Ts'o 	 * system is thrashing due to memory pressure, or if the page
118947564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
119047564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
119147564bfbSTheodore Ts'o 	 * the page (if needed) without using GFP_NOFS.
119247564bfbSTheodore Ts'o 	 */
119347564bfbSTheodore Ts'o retry_grab:
1194b7446e7cSMatthew Wilcox (Oracle) 	page = grab_cache_page_write_begin(mapping, index);
119547564bfbSTheodore Ts'o 	if (!page)
119647564bfbSTheodore Ts'o 		return -ENOMEM;
1197d1052d23SJinke Han 	/*
1198d1052d23SJinke Han 	 * The same as page allocation, we prealloc buffer heads before
1199d1052d23SJinke Han 	 * starting the handle.
1200d1052d23SJinke Han 	 */
1201d1052d23SJinke Han 	if (!page_has_buffers(page))
1202d1052d23SJinke Han 		create_empty_buffers(page, inode->i_sb->s_blocksize, 0);
1203d1052d23SJinke Han 
120447564bfbSTheodore Ts'o 	unlock_page(page);
120547564bfbSTheodore Ts'o 
120647564bfbSTheodore Ts'o retry_journal:
12079924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
12087479d2b9SAndrew Morton 	if (IS_ERR(handle)) {
120909cbfeafSKirill A. Shutemov 		put_page(page);
121047564bfbSTheodore Ts'o 		return PTR_ERR(handle);
1211cf108bcaSJan Kara 	}
1212f19d5870STao Ma 
121347564bfbSTheodore Ts'o 	lock_page(page);
121447564bfbSTheodore Ts'o 	if (page->mapping != mapping) {
121547564bfbSTheodore Ts'o 		/* The page got truncated from under us */
121647564bfbSTheodore Ts'o 		unlock_page(page);
121709cbfeafSKirill A. Shutemov 		put_page(page);
1218cf108bcaSJan Kara 		ext4_journal_stop(handle);
121947564bfbSTheodore Ts'o 		goto retry_grab;
1220cf108bcaSJan Kara 	}
12217afe5aa5SDmitry Monakhov 	/* In case writeback began while the page was unlocked */
12227afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
1223cf108bcaSJan Kara 
1224643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
12252058f83aSMichael Halcrow 	if (ext4_should_dioread_nolock(inode))
12262058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
1227705965bdSJan Kara 					     ext4_get_block_unwritten);
12282058f83aSMichael Halcrow 	else
12292058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
12302058f83aSMichael Halcrow 					     ext4_get_block);
12312058f83aSMichael Halcrow #else
1232744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
1233705965bdSJan Kara 		ret = __block_write_begin(page, pos, len,
1234705965bdSJan Kara 					  ext4_get_block_unwritten);
1235744692dcSJiaying Zhang 	else
12366e1db88dSChristoph Hellwig 		ret = __block_write_begin(page, pos, len, ext4_get_block);
12372058f83aSMichael Halcrow #endif
1238bfc1af65SNick Piggin 	if (!ret && ext4_should_journal_data(inode)) {
1239188c299eSJan Kara 		ret = ext4_walk_page_buffers(handle, inode,
1240188c299eSJan Kara 					     page_buffers(page), from, to, NULL,
1241f19d5870STao Ma 					     do_journal_get_write_access);
1242b46be050SAndrey Savochkin 	}
1243bfc1af65SNick Piggin 
1244bfc1af65SNick Piggin 	if (ret) {
1245c93d8f88SEric Biggers 		bool extended = (pos + len > inode->i_size) &&
1246c93d8f88SEric Biggers 				!ext4_verity_in_progress(inode);
1247c93d8f88SEric Biggers 
1248bfc1af65SNick Piggin 		unlock_page(page);
1249ae4d5372SAneesh Kumar K.V 		/*
12506e1db88dSChristoph Hellwig 		 * __block_write_begin may have instantiated a few blocks
1251ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
1252f340b3d9Shongnanli 		 * i_size_read because we hold i_rwsem.
12531938a150SAneesh Kumar K.V 		 *
12541938a150SAneesh Kumar K.V 		 * Add inode to orphan list in case we crash before
12551938a150SAneesh Kumar K.V 		 * truncate finishes
1256ae4d5372SAneesh Kumar K.V 		 */
1257c93d8f88SEric Biggers 		if (extended && ext4_can_truncate(inode))
12581938a150SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
12591938a150SAneesh Kumar K.V 
12601938a150SAneesh Kumar K.V 		ext4_journal_stop(handle);
1261c93d8f88SEric Biggers 		if (extended) {
1262b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
12631938a150SAneesh Kumar K.V 			/*
1264ffacfa7aSJan Kara 			 * If truncate failed early the inode might
12651938a150SAneesh Kumar K.V 			 * still be on the orphan list; we need to
12661938a150SAneesh Kumar K.V 			 * make sure the inode is removed from the
12671938a150SAneesh Kumar K.V 			 * orphan list in that case.
12681938a150SAneesh Kumar K.V 			 */
12691938a150SAneesh Kumar K.V 			if (inode->i_nlink)
12701938a150SAneesh Kumar K.V 				ext4_orphan_del(NULL, inode);
12711938a150SAneesh Kumar K.V 		}
1272bfc1af65SNick Piggin 
127347564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
127447564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
127547564bfbSTheodore Ts'o 			goto retry_journal;
127609cbfeafSKirill A. Shutemov 		put_page(page);
127747564bfbSTheodore Ts'o 		return ret;
127847564bfbSTheodore Ts'o 	}
127947564bfbSTheodore Ts'o 	*pagep = page;
1280ac27a0ecSDave Kleikamp 	return ret;
1281ac27a0ecSDave Kleikamp }
1282ac27a0ecSDave Kleikamp 
1283bfc1af65SNick Piggin /* For write_end() in data=journal mode */
1284188c299eSJan Kara static int write_end_fn(handle_t *handle, struct inode *inode,
1285188c299eSJan Kara 			struct buffer_head *bh)
1286ac27a0ecSDave Kleikamp {
128713fca323STheodore Ts'o 	int ret;
1288ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1289ac27a0ecSDave Kleikamp 		return 0;
1290ac27a0ecSDave Kleikamp 	set_buffer_uptodate(bh);
129113fca323STheodore Ts'o 	ret = ext4_handle_dirty_metadata(handle, NULL, bh);
129213fca323STheodore Ts'o 	clear_buffer_meta(bh);
129313fca323STheodore Ts'o 	clear_buffer_prio(bh);
129413fca323STheodore Ts'o 	return ret;
1295ac27a0ecSDave Kleikamp }
1296ac27a0ecSDave Kleikamp 
1297eed4333fSZheng Liu /*
1298eed4333fSZheng Liu  * We need to pick up the new inode size which generic_commit_write gave us
1299eed4333fSZheng Liu  * `file' can be NULL - eg, when called from page_symlink().
1300eed4333fSZheng Liu  *
1301eed4333fSZheng Liu  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1302eed4333fSZheng Liu  * buffers are managed internally.
1303eed4333fSZheng Liu  */
1304eed4333fSZheng Liu static int ext4_write_end(struct file *file,
1305f8514083SAneesh Kumar K.V 			  struct address_space *mapping,
1306f8514083SAneesh Kumar K.V 			  loff_t pos, unsigned len, unsigned copied,
1307f8514083SAneesh Kumar K.V 			  struct page *page, void *fsdata)
1308f8514083SAneesh Kumar K.V {
1309f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
1310eed4333fSZheng Liu 	struct inode *inode = mapping->host;
13110572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1312eed4333fSZheng Liu 	int ret = 0, ret2;
1313eed4333fSZheng Liu 	int i_size_changed = 0;
1314c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1315eed4333fSZheng Liu 
1316eed4333fSZheng Liu 	trace_ext4_write_end(inode, pos, len, copied);
13176984aef5SZhang Yi 
13185c099c4fSYe Bin 	if (ext4_has_inline_data(inode) &&
13195c099c4fSYe Bin 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
13206984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
13216984aef5SZhang Yi 
13226984aef5SZhang Yi 	copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1323f8514083SAneesh Kumar K.V 	/*
13244631dbf6SDmitry Monakhov 	 * it's important to update i_size while still holding page lock:
1325f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
1326c93d8f88SEric Biggers 	 *
1327c93d8f88SEric Biggers 	 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1328c93d8f88SEric Biggers 	 * blocks are being written past EOF, so skip the i_size update.
1329f8514083SAneesh Kumar K.V 	 */
1330c93d8f88SEric Biggers 	if (!verity)
13314631dbf6SDmitry Monakhov 		i_size_changed = ext4_update_inode_size(inode, pos + copied);
1332f8514083SAneesh Kumar K.V 	unlock_page(page);
133309cbfeafSKirill A. Shutemov 	put_page(page);
1334f8514083SAneesh Kumar K.V 
1335c93d8f88SEric Biggers 	if (old_size < pos && !verity)
13360572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
1337f8514083SAneesh Kumar K.V 	/*
1338f8514083SAneesh Kumar K.V 	 * Don't mark the inode dirty under page lock. First, it unnecessarily
1339f8514083SAneesh Kumar K.V 	 * makes the holding time of page lock longer. Second, it forces lock
1340f8514083SAneesh Kumar K.V 	 * ordering of page lock and transaction start for journaling
1341f8514083SAneesh Kumar K.V 	 * filesystems.
1342f8514083SAneesh Kumar K.V 	 */
13436984aef5SZhang Yi 	if (i_size_changed)
13444209ae12SHarshad Shirwadkar 		ret = ext4_mark_inode_dirty(handle, inode);
1345f8514083SAneesh Kumar K.V 
1346c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1347f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1348f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1349f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1350f8514083SAneesh Kumar K.V 		 */
1351f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
135255ce2f64SZhang Yi 
1353617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1354ac27a0ecSDave Kleikamp 	if (!ret)
1355ac27a0ecSDave Kleikamp 		ret = ret2;
1356bfc1af65SNick Piggin 
1357c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1358b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1359f8514083SAneesh Kumar K.V 		/*
1360ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1361f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1362f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1363f8514083SAneesh Kumar K.V 		 */
1364f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1365f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1366f8514083SAneesh Kumar K.V 	}
1367f8514083SAneesh Kumar K.V 
1368bfc1af65SNick Piggin 	return ret ? ret : copied;
1369ac27a0ecSDave Kleikamp }
1370ac27a0ecSDave Kleikamp 
1371b90197b6STheodore Ts'o /*
1372b90197b6STheodore Ts'o  * This is a private version of page_zero_new_buffers() which doesn't
1373b90197b6STheodore Ts'o  * set the buffer to be dirty, since in data=journalled mode we need
1374b90197b6STheodore Ts'o  * to call ext4_handle_dirty_metadata() instead.
1375b90197b6STheodore Ts'o  */
13763b136499SJan Kara static void ext4_journalled_zero_new_buffers(handle_t *handle,
1377188c299eSJan Kara 					    struct inode *inode,
13783b136499SJan Kara 					    struct page *page,
13793b136499SJan Kara 					    unsigned from, unsigned to)
1380b90197b6STheodore Ts'o {
1381b90197b6STheodore Ts'o 	unsigned int block_start = 0, block_end;
1382b90197b6STheodore Ts'o 	struct buffer_head *head, *bh;
1383b90197b6STheodore Ts'o 
1384b90197b6STheodore Ts'o 	bh = head = page_buffers(page);
1385b90197b6STheodore Ts'o 	do {
1386b90197b6STheodore Ts'o 		block_end = block_start + bh->b_size;
1387b90197b6STheodore Ts'o 		if (buffer_new(bh)) {
1388b90197b6STheodore Ts'o 			if (block_end > from && block_start < to) {
1389b90197b6STheodore Ts'o 				if (!PageUptodate(page)) {
1390b90197b6STheodore Ts'o 					unsigned start, size;
1391b90197b6STheodore Ts'o 
1392b90197b6STheodore Ts'o 					start = max(from, block_start);
1393b90197b6STheodore Ts'o 					size = min(to, block_end) - start;
1394b90197b6STheodore Ts'o 
1395b90197b6STheodore Ts'o 					zero_user(page, start, size);
1396188c299eSJan Kara 					write_end_fn(handle, inode, bh);
1397b90197b6STheodore Ts'o 				}
1398b90197b6STheodore Ts'o 				clear_buffer_new(bh);
1399b90197b6STheodore Ts'o 			}
1400b90197b6STheodore Ts'o 		}
1401b90197b6STheodore Ts'o 		block_start = block_end;
1402b90197b6STheodore Ts'o 		bh = bh->b_this_page;
1403b90197b6STheodore Ts'o 	} while (bh != head);
1404b90197b6STheodore Ts'o }
1405b90197b6STheodore Ts'o 
1406bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
1407bfc1af65SNick Piggin 				     struct address_space *mapping,
1408bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
1409bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
1410ac27a0ecSDave Kleikamp {
1411617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1412bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
14130572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1414ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1415ac27a0ecSDave Kleikamp 	int partial = 0;
1416bfc1af65SNick Piggin 	unsigned from, to;
14174631dbf6SDmitry Monakhov 	int size_changed = 0;
1418c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1419ac27a0ecSDave Kleikamp 
14209bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
142109cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1422bfc1af65SNick Piggin 	to = from + len;
1423bfc1af65SNick Piggin 
1424441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1425441c8508SCurt Wohlgemuth 
14266984aef5SZhang Yi 	if (ext4_has_inline_data(inode))
14276984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
14286984aef5SZhang Yi 
14296984aef5SZhang Yi 	if (unlikely(copied < len) && !PageUptodate(page)) {
1430bfc1af65SNick Piggin 		copied = 0;
1431188c299eSJan Kara 		ext4_journalled_zero_new_buffers(handle, inode, page, from, to);
14323b136499SJan Kara 	} else {
14333b136499SJan Kara 		if (unlikely(copied < len))
1434188c299eSJan Kara 			ext4_journalled_zero_new_buffers(handle, inode, page,
14353b136499SJan Kara 							 from + copied, to);
1436188c299eSJan Kara 		ret = ext4_walk_page_buffers(handle, inode, page_buffers(page),
1437188c299eSJan Kara 					     from, from + copied, &partial,
14383b136499SJan Kara 					     write_end_fn);
1439ac27a0ecSDave Kleikamp 		if (!partial)
1440ac27a0ecSDave Kleikamp 			SetPageUptodate(page);
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;
14464631dbf6SDmitry Monakhov 	unlock_page(page);
144709cbfeafSKirill A. Shutemov 	put_page(page);
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 {
15534e7ea81dSJan Kara 	struct inode *inode;
15544e7ea81dSJan Kara 	struct writeback_control *wbc;
15556b523df4SJan Kara 
15564e7ea81dSJan Kara 	pgoff_t first_page;	/* The first page to write */
15574e7ea81dSJan Kara 	pgoff_t next_page;	/* Current page to examine */
15584e7ea81dSJan Kara 	pgoff_t last_page;	/* Last page to examine */
155964769240SAlex Tomas 	/*
15604e7ea81dSJan Kara 	 * Extent to map - this can be after first_page because that can be
15614e7ea81dSJan Kara 	 * fully mapped. We somewhat abuse m_flags to store whether the extent
15624e7ea81dSJan Kara 	 * is delalloc or unwritten.
156364769240SAlex Tomas 	 */
15644e7ea81dSJan Kara 	struct ext4_map_blocks map;
15654e7ea81dSJan Kara 	struct ext4_io_submit io_submit;	/* IO submission data */
1566dddbd6acSJan Kara 	unsigned int do_map:1;
1567*de0039f6SJan Kara 	unsigned int can_map:1;	/* Can writepages call map blocks? */
15686b8ed620SJan Kara 	unsigned int scanned_until_end:1;
15694e7ea81dSJan Kara };
157064769240SAlex Tomas 
15714e7ea81dSJan Kara static void mpage_release_unused_pages(struct mpage_da_data *mpd,
15724e7ea81dSJan Kara 				       bool invalidate)
1573c4a0c46eSAneesh Kumar K.V {
1574fb5a5be0SMatthew Wilcox (Oracle) 	unsigned nr, i;
1575c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
1576fb5a5be0SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
1577c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1578c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
15794e7ea81dSJan Kara 
15804e7ea81dSJan Kara 	/* This is necessary when next_page == 0. */
15814e7ea81dSJan Kara 	if (mpd->first_page >= mpd->next_page)
15824e7ea81dSJan Kara 		return;
1583c4a0c46eSAneesh Kumar K.V 
15846b8ed620SJan Kara 	mpd->scanned_until_end = 0;
1585c7f5938aSCurt Wohlgemuth 	index = mpd->first_page;
1586c7f5938aSCurt Wohlgemuth 	end   = mpd->next_page - 1;
15874e7ea81dSJan Kara 	if (invalidate) {
15884e7ea81dSJan Kara 		ext4_lblk_t start, last;
158909cbfeafSKirill A. Shutemov 		start = index << (PAGE_SHIFT - inode->i_blkbits);
159009cbfeafSKirill A. Shutemov 		last = end << (PAGE_SHIFT - inode->i_blkbits);
15917f0d8e1dSEric Whitney 
15927f0d8e1dSEric Whitney 		/*
15937f0d8e1dSEric Whitney 		 * avoid racing with extent status tree scans made by
15947f0d8e1dSEric Whitney 		 * ext4_insert_delayed_block()
15957f0d8e1dSEric Whitney 		 */
15967f0d8e1dSEric Whitney 		down_write(&EXT4_I(inode)->i_data_sem);
159751865fdaSZheng Liu 		ext4_es_remove_extent(inode, start, last - start + 1);
15987f0d8e1dSEric Whitney 		up_write(&EXT4_I(inode)->i_data_sem);
15994e7ea81dSJan Kara 	}
160051865fdaSZheng Liu 
1601fb5a5be0SMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
1602c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
1603fb5a5be0SMatthew Wilcox (Oracle) 		nr = filemap_get_folios(mapping, &index, end, &fbatch);
1604fb5a5be0SMatthew Wilcox (Oracle) 		if (nr == 0)
1605c4a0c46eSAneesh Kumar K.V 			break;
1606fb5a5be0SMatthew Wilcox (Oracle) 		for (i = 0; i < nr; i++) {
1607fb5a5be0SMatthew Wilcox (Oracle) 			struct folio *folio = fbatch.folios[i];
16082b85a617SJan Kara 
1609fb5a5be0SMatthew Wilcox (Oracle) 			if (folio->index < mpd->first_page)
1610fb5a5be0SMatthew Wilcox (Oracle) 				continue;
1611fb5a5be0SMatthew Wilcox (Oracle) 			if (folio->index + folio_nr_pages(folio) - 1 > end)
1612fb5a5be0SMatthew Wilcox (Oracle) 				continue;
16137ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(!folio_test_locked(folio));
16147ba13abbSMatthew Wilcox (Oracle) 			BUG_ON(folio_test_writeback(folio));
16154e7ea81dSJan Kara 			if (invalidate) {
16167ba13abbSMatthew Wilcox (Oracle) 				if (folio_mapped(folio))
16177ba13abbSMatthew Wilcox (Oracle) 					folio_clear_dirty_for_io(folio);
16187ba13abbSMatthew Wilcox (Oracle) 				block_invalidate_folio(folio, 0,
16197ba13abbSMatthew Wilcox (Oracle) 						folio_size(folio));
16207ba13abbSMatthew Wilcox (Oracle) 				folio_clear_uptodate(folio);
16214e7ea81dSJan Kara 			}
16227ba13abbSMatthew Wilcox (Oracle) 			folio_unlock(folio);
1623c4a0c46eSAneesh Kumar K.V 		}
1624fb5a5be0SMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
1625c4a0c46eSAneesh Kumar K.V 	}
1626c4a0c46eSAneesh Kumar K.V }
1627c4a0c46eSAneesh Kumar K.V 
1628df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
1629df22291fSAneesh Kumar K.V {
1630df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
163192b97816STheodore Ts'o 	struct super_block *sb = inode->i_sb;
1632f78ee70dSLukas Czerner 	struct ext4_inode_info *ei = EXT4_I(inode);
163392b97816STheodore Ts'o 
163492b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
16355dee5437STheodore Ts'o 	       EXT4_C2B(EXT4_SB(inode->i_sb),
1636f78ee70dSLukas Czerner 			ext4_count_free_clusters(sb)));
163792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
163892b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1639f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
164057042651STheodore Ts'o 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
164192b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1642f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
16437b415bf6SAditya Kali 		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
164492b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Block reservation details");
164592b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1646f78ee70dSLukas Czerner 		 ei->i_reserved_data_blocks);
1647df22291fSAneesh Kumar K.V 	return;
1648df22291fSAneesh Kumar K.V }
1649df22291fSAneesh Kumar K.V 
1650188c299eSJan Kara static int ext4_bh_delay_or_unwritten(handle_t *handle, struct inode *inode,
1651188c299eSJan Kara 				      struct buffer_head *bh)
165229fa89d0SAneesh Kumar K.V {
1653c364b22cSAneesh Kumar K.V 	return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
165429fa89d0SAneesh Kumar K.V }
165529fa89d0SAneesh Kumar K.V 
165664769240SAlex Tomas /*
16570b02f4c0SEric Whitney  * ext4_insert_delayed_block - adds a delayed block to the extents status
16580b02f4c0SEric Whitney  *                             tree, incrementing the reserved cluster/block
16590b02f4c0SEric Whitney  *                             count or making a pending reservation
16600b02f4c0SEric Whitney  *                             where needed
16610b02f4c0SEric Whitney  *
16620b02f4c0SEric Whitney  * @inode - file containing the newly added block
16630b02f4c0SEric Whitney  * @lblk - logical block to be added
16640b02f4c0SEric Whitney  *
16650b02f4c0SEric Whitney  * Returns 0 on success, negative error code on failure.
16660b02f4c0SEric Whitney  */
16670b02f4c0SEric Whitney static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
16680b02f4c0SEric Whitney {
16690b02f4c0SEric Whitney 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
16700b02f4c0SEric Whitney 	int ret;
16710b02f4c0SEric Whitney 	bool allocated = false;
16726fed8395SJeffle Xu 	bool reserved = false;
16730b02f4c0SEric Whitney 
16740b02f4c0SEric Whitney 	/*
16750b02f4c0SEric Whitney 	 * If the cluster containing lblk is shared with a delayed,
16760b02f4c0SEric Whitney 	 * written, or unwritten extent in a bigalloc file system, it's
16770b02f4c0SEric Whitney 	 * already been accounted for and does not need to be reserved.
16780b02f4c0SEric Whitney 	 * A pending reservation must be made for the cluster if it's
16790b02f4c0SEric Whitney 	 * shared with a written or unwritten extent and doesn't already
16800b02f4c0SEric Whitney 	 * have one.  Written and unwritten extents can be purged from the
16810b02f4c0SEric Whitney 	 * extents status tree if the system is under memory pressure, so
16820b02f4c0SEric Whitney 	 * it's necessary to examine the extent tree if a search of the
16830b02f4c0SEric Whitney 	 * extents status tree doesn't get a match.
16840b02f4c0SEric Whitney 	 */
16850b02f4c0SEric Whitney 	if (sbi->s_cluster_ratio == 1) {
16860b02f4c0SEric Whitney 		ret = ext4_da_reserve_space(inode);
16870b02f4c0SEric Whitney 		if (ret != 0)   /* ENOSPC */
16880b02f4c0SEric Whitney 			goto errout;
16896fed8395SJeffle Xu 		reserved = true;
16900b02f4c0SEric Whitney 	} else {   /* bigalloc */
16910b02f4c0SEric Whitney 		if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
16920b02f4c0SEric Whitney 			if (!ext4_es_scan_clu(inode,
16930b02f4c0SEric Whitney 					      &ext4_es_is_mapped, lblk)) {
16940b02f4c0SEric Whitney 				ret = ext4_clu_mapped(inode,
16950b02f4c0SEric Whitney 						      EXT4_B2C(sbi, lblk));
16960b02f4c0SEric Whitney 				if (ret < 0)
16970b02f4c0SEric Whitney 					goto errout;
16980b02f4c0SEric Whitney 				if (ret == 0) {
16990b02f4c0SEric Whitney 					ret = ext4_da_reserve_space(inode);
17000b02f4c0SEric Whitney 					if (ret != 0)   /* ENOSPC */
17010b02f4c0SEric Whitney 						goto errout;
17026fed8395SJeffle Xu 					reserved = true;
17030b02f4c0SEric Whitney 				} else {
17040b02f4c0SEric Whitney 					allocated = true;
17050b02f4c0SEric Whitney 				}
17060b02f4c0SEric Whitney 			} else {
17070b02f4c0SEric Whitney 				allocated = true;
17080b02f4c0SEric Whitney 			}
17090b02f4c0SEric Whitney 		}
17100b02f4c0SEric Whitney 	}
17110b02f4c0SEric Whitney 
17120b02f4c0SEric Whitney 	ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
17136fed8395SJeffle Xu 	if (ret && reserved)
17146fed8395SJeffle Xu 		ext4_da_release_space(inode, 1);
17150b02f4c0SEric Whitney 
17160b02f4c0SEric Whitney errout:
17170b02f4c0SEric Whitney 	return ret;
17180b02f4c0SEric Whitney }
17190b02f4c0SEric Whitney 
17200b02f4c0SEric Whitney /*
17215356f261SAditya Kali  * This function is grabs code from the very beginning of
17225356f261SAditya Kali  * ext4_map_blocks, but assumes that the caller is from delayed write
17235356f261SAditya Kali  * time. This function looks up the requested blocks and sets the
17245356f261SAditya Kali  * buffer delay bit under the protection of i_data_sem.
17255356f261SAditya Kali  */
17265356f261SAditya Kali static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
17275356f261SAditya Kali 			      struct ext4_map_blocks *map,
17285356f261SAditya Kali 			      struct buffer_head *bh)
17295356f261SAditya Kali {
1730d100eef2SZheng Liu 	struct extent_status es;
17315356f261SAditya Kali 	int retval;
17325356f261SAditya Kali 	sector_t invalid_block = ~((sector_t) 0xffff);
1733921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1734921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
1735921f266bSDmitry Monakhov 
1736921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
1737921f266bSDmitry Monakhov #endif
17385356f261SAditya Kali 
17395356f261SAditya Kali 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
17405356f261SAditya Kali 		invalid_block = ~0;
17415356f261SAditya Kali 
17425356f261SAditya Kali 	map->m_flags = 0;
174370aa1554SRitesh Harjani 	ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
17445356f261SAditya Kali 		  (unsigned long) map->m_lblk);
1745d100eef2SZheng Liu 
1746d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
1747bb5835edSTheodore Ts'o 	if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1748d100eef2SZheng Liu 		if (ext4_es_is_hole(&es)) {
1749d100eef2SZheng Liu 			retval = 0;
1750c8b459f4SLukas Czerner 			down_read(&EXT4_I(inode)->i_data_sem);
1751d100eef2SZheng Liu 			goto add_delayed;
1752d100eef2SZheng Liu 		}
1753d100eef2SZheng Liu 
1754d100eef2SZheng Liu 		/*
17553eda41dfSEric Whitney 		 * Delayed extent could be allocated by fallocate.
17563eda41dfSEric Whitney 		 * So we need to check it.
1757d100eef2SZheng Liu 		 */
17583eda41dfSEric Whitney 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
17593eda41dfSEric Whitney 			map_bh(bh, inode->i_sb, invalid_block);
17603eda41dfSEric Whitney 			set_buffer_new(bh);
17613eda41dfSEric Whitney 			set_buffer_delay(bh);
1762d100eef2SZheng Liu 			return 0;
1763d100eef2SZheng Liu 		}
1764d100eef2SZheng Liu 
1765d100eef2SZheng Liu 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1766d100eef2SZheng Liu 		retval = es.es_len - (iblock - es.es_lblk);
1767d100eef2SZheng Liu 		if (retval > map->m_len)
1768d100eef2SZheng Liu 			retval = map->m_len;
1769d100eef2SZheng Liu 		map->m_len = retval;
1770d100eef2SZheng Liu 		if (ext4_es_is_written(&es))
1771d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_MAPPED;
1772d100eef2SZheng Liu 		else if (ext4_es_is_unwritten(&es))
1773d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1774d100eef2SZheng Liu 		else
17751e83bc81SArnd Bergmann 			BUG();
1776d100eef2SZheng Liu 
1777921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1778921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1779921f266bSDmitry Monakhov #endif
1780d100eef2SZheng Liu 		return retval;
1781d100eef2SZheng Liu 	}
1782d100eef2SZheng Liu 
17835356f261SAditya Kali 	/*
17845356f261SAditya Kali 	 * Try to see if we can get the block without requesting a new
17855356f261SAditya Kali 	 * file system block.
17865356f261SAditya Kali 	 */
1787c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
1788cbd7584eSJan Kara 	if (ext4_has_inline_data(inode))
17899c3569b5STao Ma 		retval = 0;
1790cbd7584eSJan Kara 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
17912f8e0a7cSZheng Liu 		retval = ext4_ext_map_blocks(NULL, inode, map, 0);
17925356f261SAditya Kali 	else
17932f8e0a7cSZheng Liu 		retval = ext4_ind_map_blocks(NULL, inode, map, 0);
17945356f261SAditya Kali 
1795d100eef2SZheng Liu add_delayed:
17965356f261SAditya Kali 	if (retval == 0) {
1797f7fec032SZheng Liu 		int ret;
1798ad431025SEric Whitney 
17995356f261SAditya Kali 		/*
18005356f261SAditya Kali 		 * XXX: __block_prepare_write() unmaps passed block,
18015356f261SAditya Kali 		 * is it OK?
18025356f261SAditya Kali 		 */
18035356f261SAditya Kali 
18040b02f4c0SEric Whitney 		ret = ext4_insert_delayed_block(inode, map->m_lblk);
18050b02f4c0SEric Whitney 		if (ret != 0) {
1806f7fec032SZheng Liu 			retval = ret;
180751865fdaSZheng Liu 			goto out_unlock;
1808f7fec032SZheng Liu 		}
180951865fdaSZheng Liu 
18105356f261SAditya Kali 		map_bh(bh, inode->i_sb, invalid_block);
18115356f261SAditya Kali 		set_buffer_new(bh);
18125356f261SAditya Kali 		set_buffer_delay(bh);
1813f7fec032SZheng Liu 	} else if (retval > 0) {
1814f7fec032SZheng Liu 		int ret;
18153be78c73STheodore Ts'o 		unsigned int status;
1816f7fec032SZheng Liu 
181744fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
181844fb851dSZheng Liu 			ext4_warning(inode->i_sb,
181944fb851dSZheng Liu 				     "ES len assertion failed for inode "
182044fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
182144fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
182244fb851dSZheng Liu 			WARN_ON(1);
1823921f266bSDmitry Monakhov 		}
1824921f266bSDmitry Monakhov 
1825f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1826f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1827f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1828f7fec032SZheng Liu 					    map->m_pblk, status);
1829f7fec032SZheng Liu 		if (ret != 0)
1830f7fec032SZheng Liu 			retval = ret;
18315356f261SAditya Kali 	}
18325356f261SAditya Kali 
18335356f261SAditya Kali out_unlock:
18345356f261SAditya Kali 	up_read((&EXT4_I(inode)->i_data_sem));
18355356f261SAditya Kali 
18365356f261SAditya Kali 	return retval;
18375356f261SAditya Kali }
18385356f261SAditya Kali 
18395356f261SAditya Kali /*
1840d91bd2c1SSeunghun Lee  * This is a special get_block_t callback which is used by
1841b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
1842b920c755STheodore Ts'o  * reserve space for a single block.
184329fa89d0SAneesh Kumar K.V  *
184429fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
184529fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
184629fa89d0SAneesh Kumar K.V  *
184729fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
184829fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
184929fa89d0SAneesh Kumar K.V  * initialized properly.
185064769240SAlex Tomas  */
18519c3569b5STao Ma int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
18522ed88685STheodore Ts'o 			   struct buffer_head *bh, int create)
185364769240SAlex Tomas {
18542ed88685STheodore Ts'o 	struct ext4_map_blocks map;
185564769240SAlex Tomas 	int ret = 0;
185664769240SAlex Tomas 
185764769240SAlex Tomas 	BUG_ON(create == 0);
18582ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
18592ed88685STheodore Ts'o 
18602ed88685STheodore Ts'o 	map.m_lblk = iblock;
18612ed88685STheodore Ts'o 	map.m_len = 1;
186264769240SAlex Tomas 
186364769240SAlex Tomas 	/*
186464769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
186564769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
186664769240SAlex Tomas 	 * the same as allocated blocks.
186764769240SAlex Tomas 	 */
18685356f261SAditya Kali 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
18695356f261SAditya Kali 	if (ret <= 0)
18702ed88685STheodore Ts'o 		return ret;
187164769240SAlex Tomas 
18722ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
1873ed8ad838SJan Kara 	ext4_update_bh_state(bh, map.m_flags);
18742ed88685STheodore Ts'o 
18752ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
18762ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
18772ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
18782ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
18792ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
18802ed88685STheodore Ts'o 		 * for partial write.
18812ed88685STheodore Ts'o 		 */
18822ed88685STheodore Ts'o 		set_buffer_new(bh);
1883c8205636STheodore Ts'o 		set_buffer_mapped(bh);
18842ed88685STheodore Ts'o 	}
18852ed88685STheodore Ts'o 	return 0;
188664769240SAlex Tomas }
188761628a3fSMingming Cao 
188862e086beSAneesh Kumar K.V static int __ext4_journalled_writepage(struct page *page,
188962e086beSAneesh Kumar K.V 				       unsigned int len)
189062e086beSAneesh Kumar K.V {
189162e086beSAneesh Kumar K.V 	struct address_space *mapping = page->mapping;
189262e086beSAneesh Kumar K.V 	struct inode *inode = mapping->host;
189362e086beSAneesh Kumar K.V 	handle_t *handle = NULL;
18943fdcfb66STao Ma 	int ret = 0, err = 0;
18953fdcfb66STao Ma 	int inline_data = ext4_has_inline_data(inode);
18963fdcfb66STao Ma 	struct buffer_head *inode_bh = NULL;
18975c48a7dfSZhang Yi 	loff_t size;
189862e086beSAneesh Kumar K.V 
1899cb20d518STheodore Ts'o 	ClearPageChecked(page);
19003fdcfb66STao Ma 
19013fdcfb66STao Ma 	if (inline_data) {
19023fdcfb66STao Ma 		BUG_ON(page->index != 0);
19033fdcfb66STao Ma 		BUG_ON(len > ext4_get_max_inline_size(inode));
19043fdcfb66STao Ma 		inode_bh = ext4_journalled_write_inline_data(inode, len, page);
19053fdcfb66STao Ma 		if (inode_bh == NULL)
19063fdcfb66STao Ma 			goto out;
19073fdcfb66STao Ma 	}
1908bdf96838STheodore Ts'o 	/*
1909bdf96838STheodore Ts'o 	 * We need to release the page lock before we start the
1910bdf96838STheodore Ts'o 	 * journal, so grab a reference so the page won't disappear
1911bdf96838STheodore Ts'o 	 * out from under us.
1912bdf96838STheodore Ts'o 	 */
1913bdf96838STheodore Ts'o 	get_page(page);
191462e086beSAneesh Kumar K.V 	unlock_page(page);
191562e086beSAneesh Kumar K.V 
19169924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
19179924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
191862e086beSAneesh Kumar K.V 	if (IS_ERR(handle)) {
191962e086beSAneesh Kumar K.V 		ret = PTR_ERR(handle);
1920bdf96838STheodore Ts'o 		put_page(page);
1921bdf96838STheodore Ts'o 		goto out_no_pagelock;
1922bdf96838STheodore Ts'o 	}
1923bdf96838STheodore Ts'o 	BUG_ON(!ext4_handle_valid(handle));
1924bdf96838STheodore Ts'o 
1925bdf96838STheodore Ts'o 	lock_page(page);
1926bdf96838STheodore Ts'o 	put_page(page);
19275c48a7dfSZhang Yi 	size = i_size_read(inode);
19285c48a7dfSZhang Yi 	if (page->mapping != mapping || page_offset(page) > size) {
1929bdf96838STheodore Ts'o 		/* The page got truncated from under us */
1930bdf96838STheodore Ts'o 		ext4_journal_stop(handle);
1931bdf96838STheodore Ts'o 		ret = 0;
193262e086beSAneesh Kumar K.V 		goto out;
193362e086beSAneesh Kumar K.V 	}
193462e086beSAneesh Kumar K.V 
19353fdcfb66STao Ma 	if (inline_data) {
1936362eca70STheodore Ts'o 		ret = ext4_mark_inode_dirty(handle, inode);
19373fdcfb66STao Ma 	} else {
19385c48a7dfSZhang Yi 		struct buffer_head *page_bufs = page_buffers(page);
19395c48a7dfSZhang Yi 
19405c48a7dfSZhang Yi 		if (page->index == size >> PAGE_SHIFT)
19415c48a7dfSZhang Yi 			len = size & ~PAGE_MASK;
19425c48a7dfSZhang Yi 		else
19435c48a7dfSZhang Yi 			len = PAGE_SIZE;
19445c48a7dfSZhang Yi 
1945188c299eSJan Kara 		ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1946188c299eSJan Kara 					     NULL, do_journal_get_write_access);
194762e086beSAneesh Kumar K.V 
1948188c299eSJan Kara 		err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1949188c299eSJan Kara 					     NULL, write_end_fn);
19503fdcfb66STao Ma 	}
195162e086beSAneesh Kumar K.V 	if (ret == 0)
195262e086beSAneesh Kumar K.V 		ret = err;
1953b5b18160SJan Kara 	err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
1954afb585a9SMauricio Faria de Oliveira 	if (ret == 0)
1955afb585a9SMauricio Faria de Oliveira 		ret = err;
19562d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
195762e086beSAneesh Kumar K.V 	err = ext4_journal_stop(handle);
195862e086beSAneesh Kumar K.V 	if (!ret)
195962e086beSAneesh Kumar K.V 		ret = err;
196062e086beSAneesh Kumar K.V 
196119f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
196262e086beSAneesh Kumar K.V out:
1963bdf96838STheodore Ts'o 	unlock_page(page);
1964bdf96838STheodore Ts'o out_no_pagelock:
19653fdcfb66STao Ma 	brelse(inode_bh);
196662e086beSAneesh Kumar K.V 	return ret;
196762e086beSAneesh Kumar K.V }
196862e086beSAneesh Kumar K.V 
196961628a3fSMingming Cao /*
197043ce1d23SAneesh Kumar K.V  * Note that we don't need to start a transaction unless we're journaling data
197143ce1d23SAneesh Kumar K.V  * because we should have holes filled from ext4_page_mkwrite(). We even don't
197243ce1d23SAneesh Kumar K.V  * need to file the inode to the transaction's list in ordered mode because if
197343ce1d23SAneesh Kumar K.V  * we are writing back data added by write(), the inode is already there and if
197443ce1d23SAneesh Kumar K.V  * we are writing back data modified via mmap(), no one guarantees in which
197543ce1d23SAneesh Kumar K.V  * transaction the data will hit the disk. In case we are journaling data, we
197643ce1d23SAneesh Kumar K.V  * cannot start transaction directly because transaction start ranks above page
197743ce1d23SAneesh Kumar K.V  * lock so we have to do some magic.
197843ce1d23SAneesh Kumar K.V  *
1979b920c755STheodore Ts'o  * This function can get called via...
198020970ba6STheodore Ts'o  *   - ext4_writepages after taking page lock (have journal handle)
1981b920c755STheodore Ts'o  *   - journal_submit_inode_data_buffers (no journal handle)
1982f6463b0dSArtem Bityutskiy  *   - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1983b920c755STheodore Ts'o  *   - grab_page_cache when doing write_begin (have journal handle)
198443ce1d23SAneesh Kumar K.V  *
198543ce1d23SAneesh Kumar K.V  * We don't do any block allocation in this function. If we have page with
198643ce1d23SAneesh Kumar K.V  * multiple blocks we need to write those buffer_heads that are mapped. This
198743ce1d23SAneesh Kumar K.V  * is important for mmaped based write. So if we do with blocksize 1K
198843ce1d23SAneesh Kumar K.V  * truncate(f, 1024);
198943ce1d23SAneesh Kumar K.V  * a = mmap(f, 0, 4096);
199043ce1d23SAneesh Kumar K.V  * a[0] = 'a';
199143ce1d23SAneesh Kumar K.V  * truncate(f, 4096);
199243ce1d23SAneesh Kumar K.V  * we have in the page first buffer_head mapped via page_mkwrite call back
199390802ed9SPaul Bolle  * but other buffer_heads would be unmapped but dirty (dirty done via the
199443ce1d23SAneesh Kumar K.V  * do_wp_page). So writepage should write the first block. If we modify
199543ce1d23SAneesh Kumar K.V  * the mmap area beyond 1024 we will again get a page_fault and the
199643ce1d23SAneesh Kumar K.V  * page_mkwrite callback will do the block allocation and mark the
199743ce1d23SAneesh Kumar K.V  * buffer_heads mapped.
199843ce1d23SAneesh Kumar K.V  *
199943ce1d23SAneesh Kumar K.V  * We redirty the page if we have any buffer_heads that is either delay or
200043ce1d23SAneesh Kumar K.V  * unwritten in the page.
200143ce1d23SAneesh Kumar K.V  *
200243ce1d23SAneesh Kumar K.V  * We can get recursively called as show below.
200343ce1d23SAneesh Kumar K.V  *
200443ce1d23SAneesh Kumar K.V  *	ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
200543ce1d23SAneesh Kumar K.V  *		ext4_writepage()
200643ce1d23SAneesh Kumar K.V  *
200743ce1d23SAneesh Kumar K.V  * But since we don't do any block allocation we should not deadlock.
200843ce1d23SAneesh Kumar K.V  * Page also have the dirty flag cleared so we don't get recurive page_lock.
200961628a3fSMingming Cao  */
201043ce1d23SAneesh Kumar K.V static int ext4_writepage(struct page *page,
201164769240SAlex Tomas 			  struct writeback_control *wbc)
201264769240SAlex Tomas {
2013020df9baSMatthew Wilcox (Oracle) 	struct folio *folio = page_folio(page);
2014f8bec370SJan Kara 	int ret = 0;
201561628a3fSMingming Cao 	loff_t size;
2016498e5f24STheodore Ts'o 	unsigned int len;
2017744692dcSJiaying Zhang 	struct buffer_head *page_bufs = NULL;
201861628a3fSMingming Cao 	struct inode *inode = page->mapping->host;
201936ade451SJan Kara 	struct ext4_io_submit io_submit;
202064769240SAlex Tomas 
20210db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
2022020df9baSMatthew Wilcox (Oracle) 		folio_invalidate(folio, 0, folio_size(folio));
2023020df9baSMatthew Wilcox (Oracle) 		folio_unlock(folio);
20240db1ff22STheodore Ts'o 		return -EIO;
20250db1ff22STheodore Ts'o 	}
20260db1ff22STheodore Ts'o 
2027a9c667f8SLukas Czerner 	trace_ext4_writepage(page);
202861628a3fSMingming Cao 	size = i_size_read(inode);
2029c93d8f88SEric Biggers 	if (page->index == size >> PAGE_SHIFT &&
2030c93d8f88SEric Biggers 	    !ext4_verity_in_progress(inode))
203109cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
203261628a3fSMingming Cao 	else
203309cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
203461628a3fSMingming Cao 
2035cc509574STheodore Ts'o 	/* Should never happen but for bugs in other kernel subsystems */
2036cc509574STheodore Ts'o 	if (!page_has_buffers(page)) {
2037cc509574STheodore Ts'o 		ext4_warning_inode(inode,
2038cc509574STheodore Ts'o 		   "page %lu does not have buffers attached", page->index);
2039cc509574STheodore Ts'o 		ClearPageDirty(page);
2040cc509574STheodore Ts'o 		unlock_page(page);
2041cc509574STheodore Ts'o 		return 0;
2042cc509574STheodore Ts'o 	}
2043cc509574STheodore Ts'o 
2044f0e6c985SAneesh Kumar K.V 	page_bufs = page_buffers(page);
204564769240SAlex Tomas 	/*
2046fe386132SJan Kara 	 * We cannot do block allocation or other extent handling in this
2047fe386132SJan Kara 	 * function. If there are buffers needing that, we have to redirty
2048fe386132SJan Kara 	 * the page. But we may reach here when we do a journal commit via
2049fe386132SJan Kara 	 * journal_submit_inode_data_buffers() and in that case we must write
2050fe386132SJan Kara 	 * allocated buffers to achieve data=ordered mode guarantees.
2051cccd147aSTheodore Ts'o 	 *
2052cccd147aSTheodore Ts'o 	 * Also, if there is only one buffer per page (the fs block
2053cccd147aSTheodore Ts'o 	 * size == the page size), if one buffer needs block
2054cccd147aSTheodore Ts'o 	 * allocation or needs to modify the extent tree to clear the
2055cccd147aSTheodore Ts'o 	 * unwritten flag, we know that the page can't be written at
2056cccd147aSTheodore Ts'o 	 * all, so we might as well refuse the write immediately.
2057cccd147aSTheodore Ts'o 	 * Unfortunately if the block size != page size, we can't as
2058cccd147aSTheodore Ts'o 	 * easily detect this case using ext4_walk_page_buffers(), but
2059cccd147aSTheodore Ts'o 	 * for the extremely common case, this is an optimization that
2060cccd147aSTheodore Ts'o 	 * skips a useless round trip through ext4_bio_write_page().
206164769240SAlex Tomas 	 */
2062188c299eSJan Kara 	if (ext4_walk_page_buffers(NULL, inode, page_bufs, 0, len, NULL,
2063c364b22cSAneesh Kumar K.V 				   ext4_bh_delay_or_unwritten)) {
206461628a3fSMingming Cao 		redirty_page_for_writepage(wbc, page);
2065cccd147aSTheodore Ts'o 		if ((current->flags & PF_MEMALLOC) ||
206609cbfeafSKirill A. Shutemov 		    (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2067fe386132SJan Kara 			/*
2068fe386132SJan Kara 			 * For memory cleaning there's no point in writing only
2069fe386132SJan Kara 			 * some buffers. So just bail out. Warn if we came here
2070fe386132SJan Kara 			 * from direct reclaim.
2071fe386132SJan Kara 			 */
2072fe386132SJan Kara 			WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2073fe386132SJan Kara 							== PF_MEMALLOC);
207461628a3fSMingming Cao 			unlock_page(page);
207561628a3fSMingming Cao 			return 0;
207661628a3fSMingming Cao 		}
2077f0e6c985SAneesh Kumar K.V 	}
207864769240SAlex Tomas 
2079cb20d518STheodore Ts'o 	if (PageChecked(page) && ext4_should_journal_data(inode))
208043ce1d23SAneesh Kumar K.V 		/*
208143ce1d23SAneesh Kumar K.V 		 * It's mmapped pagecache.  Add buffers and journal it.  There
208243ce1d23SAneesh Kumar K.V 		 * doesn't seem much point in redirtying the page here.
208343ce1d23SAneesh Kumar K.V 		 */
20843f0ca309SWu Fengguang 		return __ext4_journalled_writepage(page, len);
208543ce1d23SAneesh Kumar K.V 
208697a851edSJan Kara 	ext4_io_submit_init(&io_submit, wbc);
208797a851edSJan Kara 	io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
208897a851edSJan Kara 	if (!io_submit.io_end) {
208997a851edSJan Kara 		redirty_page_for_writepage(wbc, page);
209097a851edSJan Kara 		unlock_page(page);
209197a851edSJan Kara 		return -ENOMEM;
209297a851edSJan Kara 	}
2093dff4ac75SJan Kara 	ret = ext4_bio_write_page(&io_submit, page, len);
209436ade451SJan Kara 	ext4_io_submit(&io_submit);
209597a851edSJan Kara 	/* Drop io_end reference we got from init */
209697a851edSJan Kara 	ext4_put_io_end_defer(io_submit.io_end);
209764769240SAlex Tomas 	return ret;
209864769240SAlex Tomas }
209964769240SAlex Tomas 
21005f1132b2SJan Kara static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
21015f1132b2SJan Kara {
21025f1132b2SJan Kara 	int len;
2103a056bdaaSJan Kara 	loff_t size;
21045f1132b2SJan Kara 	int err;
21055f1132b2SJan Kara 
21065f1132b2SJan Kara 	BUG_ON(page->index != mpd->first_page);
2107a056bdaaSJan Kara 	clear_page_dirty_for_io(page);
2108a056bdaaSJan Kara 	/*
2109a056bdaaSJan Kara 	 * We have to be very careful here!  Nothing protects writeback path
2110a056bdaaSJan Kara 	 * against i_size changes and the page can be writeably mapped into
2111a056bdaaSJan Kara 	 * page tables. So an application can be growing i_size and writing
2112a056bdaaSJan Kara 	 * data through mmap while writeback runs. clear_page_dirty_for_io()
2113a056bdaaSJan Kara 	 * write-protects our page in page tables and the page cannot get
2114a056bdaaSJan Kara 	 * written to again until we release page lock. So only after
2115a056bdaaSJan Kara 	 * clear_page_dirty_for_io() we are safe to sample i_size for
2116a056bdaaSJan Kara 	 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2117a056bdaaSJan Kara 	 * on the barrier provided by TestClearPageDirty in
2118a056bdaaSJan Kara 	 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2119a056bdaaSJan Kara 	 * after page tables are updated.
2120a056bdaaSJan Kara 	 */
2121a056bdaaSJan Kara 	size = i_size_read(mpd->inode);
2122c93d8f88SEric Biggers 	if (page->index == size >> PAGE_SHIFT &&
2123c93d8f88SEric Biggers 	    !ext4_verity_in_progress(mpd->inode))
212409cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
21255f1132b2SJan Kara 	else
212609cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
2127dff4ac75SJan Kara 	err = ext4_bio_write_page(&mpd->io_submit, page, len);
21285f1132b2SJan Kara 	if (!err)
21295f1132b2SJan Kara 		mpd->wbc->nr_to_write--;
21305f1132b2SJan Kara 	mpd->first_page++;
21315f1132b2SJan Kara 
21325f1132b2SJan Kara 	return err;
21335f1132b2SJan Kara }
21345f1132b2SJan Kara 
21356db07461SRitesh Harjani #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
21364e7ea81dSJan Kara 
213761628a3fSMingming Cao /*
2138fffb2739SJan Kara  * mballoc gives us at most this number of blocks...
2139fffb2739SJan Kara  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2140fffb2739SJan Kara  * The rest of mballoc seems to handle chunks up to full group size.
214161628a3fSMingming Cao  */
2142fffb2739SJan Kara #define MAX_WRITEPAGES_EXTENT_LEN 2048
2143525f4ed8SMingming Cao 
2144525f4ed8SMingming Cao /*
21454e7ea81dSJan Kara  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
21464e7ea81dSJan Kara  *
21474e7ea81dSJan Kara  * @mpd - extent of blocks
21484e7ea81dSJan Kara  * @lblk - logical number of the block in the file
214909930042SJan Kara  * @bh - buffer head we want to add to the extent
21504e7ea81dSJan Kara  *
215109930042SJan Kara  * The function is used to collect contig. blocks in the same state. If the
215209930042SJan Kara  * buffer doesn't require mapping for writeback and we haven't started the
215309930042SJan Kara  * extent of buffers to map yet, the function returns 'true' immediately - the
215409930042SJan Kara  * caller can write the buffer right away. Otherwise the function returns true
215509930042SJan Kara  * if the block has been added to the extent, false if the block couldn't be
215609930042SJan Kara  * added.
21574e7ea81dSJan Kara  */
215809930042SJan Kara static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
215909930042SJan Kara 				   struct buffer_head *bh)
21604e7ea81dSJan Kara {
21614e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
21624e7ea81dSJan Kara 
216309930042SJan Kara 	/* Buffer that doesn't need mapping for writeback? */
216409930042SJan Kara 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
216509930042SJan Kara 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
216609930042SJan Kara 		/* So far no extent to map => we write the buffer right away */
216709930042SJan Kara 		if (map->m_len == 0)
216809930042SJan Kara 			return true;
216909930042SJan Kara 		return false;
217009930042SJan Kara 	}
21714e7ea81dSJan Kara 
21724e7ea81dSJan Kara 	/* First block in the extent? */
21734e7ea81dSJan Kara 	if (map->m_len == 0) {
2174dddbd6acSJan Kara 		/* We cannot map unless handle is started... */
2175dddbd6acSJan Kara 		if (!mpd->do_map)
2176dddbd6acSJan Kara 			return false;
21774e7ea81dSJan Kara 		map->m_lblk = lblk;
21784e7ea81dSJan Kara 		map->m_len = 1;
217909930042SJan Kara 		map->m_flags = bh->b_state & BH_FLAGS;
218009930042SJan Kara 		return true;
21814e7ea81dSJan Kara 	}
21824e7ea81dSJan Kara 
218309930042SJan Kara 	/* Don't go larger than mballoc is willing to allocate */
218409930042SJan Kara 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
218509930042SJan Kara 		return false;
218609930042SJan Kara 
21874e7ea81dSJan Kara 	/* Can we merge the block to our big extent? */
21884e7ea81dSJan Kara 	if (lblk == map->m_lblk + map->m_len &&
218909930042SJan Kara 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
21904e7ea81dSJan Kara 		map->m_len++;
219109930042SJan Kara 		return true;
21924e7ea81dSJan Kara 	}
219309930042SJan Kara 	return false;
21944e7ea81dSJan Kara }
21954e7ea81dSJan Kara 
21965f1132b2SJan Kara /*
21975f1132b2SJan Kara  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
21985f1132b2SJan Kara  *
21995f1132b2SJan Kara  * @mpd - extent of blocks for mapping
22005f1132b2SJan Kara  * @head - the first buffer in the page
22015f1132b2SJan Kara  * @bh - buffer we should start processing from
22025f1132b2SJan Kara  * @lblk - logical number of the block in the file corresponding to @bh
22035f1132b2SJan Kara  *
22045f1132b2SJan Kara  * Walk through page buffers from @bh upto @head (exclusive) and either submit
22055f1132b2SJan Kara  * the page for IO if all buffers in this page were mapped and there's no
22065f1132b2SJan Kara  * accumulated extent of buffers to map or add buffers in the page to the
22075f1132b2SJan Kara  * extent of buffers to map. The function returns 1 if the caller can continue
22085f1132b2SJan Kara  * by processing the next page, 0 if it should stop adding buffers to the
22095f1132b2SJan Kara  * extent to map because we cannot extend it anymore. It can also return value
22105f1132b2SJan Kara  * < 0 in case of error during IO submission.
22115f1132b2SJan Kara  */
22125f1132b2SJan Kara static int mpage_process_page_bufs(struct mpage_da_data *mpd,
22134e7ea81dSJan Kara 				   struct buffer_head *head,
22144e7ea81dSJan Kara 				   struct buffer_head *bh,
22154e7ea81dSJan Kara 				   ext4_lblk_t lblk)
22164e7ea81dSJan Kara {
22174e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
22185f1132b2SJan Kara 	int err;
221993407472SFabian Frederick 	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
22204e7ea81dSJan Kara 							>> inode->i_blkbits;
22214e7ea81dSJan Kara 
2222c93d8f88SEric Biggers 	if (ext4_verity_in_progress(inode))
2223c93d8f88SEric Biggers 		blocks = EXT_MAX_BLOCKS;
2224c93d8f88SEric Biggers 
22254e7ea81dSJan Kara 	do {
22264e7ea81dSJan Kara 		BUG_ON(buffer_locked(bh));
22274e7ea81dSJan Kara 
222809930042SJan Kara 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
22294e7ea81dSJan Kara 			/* Found extent to map? */
22304e7ea81dSJan Kara 			if (mpd->map.m_len)
22315f1132b2SJan Kara 				return 0;
2232dddbd6acSJan Kara 			/* Buffer needs mapping and handle is not started? */
2233dddbd6acSJan Kara 			if (!mpd->do_map)
2234dddbd6acSJan Kara 				return 0;
223509930042SJan Kara 			/* Everything mapped so far and we hit EOF */
22365f1132b2SJan Kara 			break;
22374e7ea81dSJan Kara 		}
22384e7ea81dSJan Kara 	} while (lblk++, (bh = bh->b_this_page) != head);
22395f1132b2SJan Kara 	/* So far everything mapped? Submit the page for IO. */
22405f1132b2SJan Kara 	if (mpd->map.m_len == 0) {
22415f1132b2SJan Kara 		err = mpage_submit_page(mpd, head->b_page);
22425f1132b2SJan Kara 		if (err < 0)
22434e7ea81dSJan Kara 			return err;
22444e7ea81dSJan Kara 	}
22456b8ed620SJan Kara 	if (lblk >= blocks) {
22466b8ed620SJan Kara 		mpd->scanned_until_end = 1;
22476b8ed620SJan Kara 		return 0;
22486b8ed620SJan Kara 	}
22496b8ed620SJan Kara 	return 1;
22505f1132b2SJan Kara }
22514e7ea81dSJan Kara 
22524e7ea81dSJan Kara /*
22532943fdbcSRitesh Harjani  * mpage_process_page - update page buffers corresponding to changed extent and
22542943fdbcSRitesh Harjani  *		       may submit fully mapped page for IO
22552943fdbcSRitesh Harjani  *
22562943fdbcSRitesh Harjani  * @mpd		- description of extent to map, on return next extent to map
22572943fdbcSRitesh Harjani  * @m_lblk	- logical block mapping.
22582943fdbcSRitesh Harjani  * @m_pblk	- corresponding physical mapping.
22592943fdbcSRitesh Harjani  * @map_bh	- determines on return whether this page requires any further
22602943fdbcSRitesh Harjani  *		  mapping or not.
22612943fdbcSRitesh Harjani  * Scan given page buffers corresponding to changed extent and update buffer
22622943fdbcSRitesh Harjani  * state according to new extent state.
22632943fdbcSRitesh Harjani  * We map delalloc buffers to their physical location, clear unwritten bits.
22642943fdbcSRitesh Harjani  * If the given page is not fully mapped, we update @map to the next extent in
22652943fdbcSRitesh Harjani  * the given page that needs mapping & return @map_bh as true.
22662943fdbcSRitesh Harjani  */
22672943fdbcSRitesh Harjani static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
22682943fdbcSRitesh Harjani 			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
22692943fdbcSRitesh Harjani 			      bool *map_bh)
22702943fdbcSRitesh Harjani {
22712943fdbcSRitesh Harjani 	struct buffer_head *head, *bh;
22722943fdbcSRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
22732943fdbcSRitesh Harjani 	ext4_lblk_t lblk = *m_lblk;
22742943fdbcSRitesh Harjani 	ext4_fsblk_t pblock = *m_pblk;
22752943fdbcSRitesh Harjani 	int err = 0;
2276c8cc8816SRitesh Harjani 	int blkbits = mpd->inode->i_blkbits;
2277c8cc8816SRitesh Harjani 	ssize_t io_end_size = 0;
2278c8cc8816SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
22792943fdbcSRitesh Harjani 
22802943fdbcSRitesh Harjani 	bh = head = page_buffers(page);
22812943fdbcSRitesh Harjani 	do {
22822943fdbcSRitesh Harjani 		if (lblk < mpd->map.m_lblk)
22832943fdbcSRitesh Harjani 			continue;
22842943fdbcSRitesh Harjani 		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
22852943fdbcSRitesh Harjani 			/*
22862943fdbcSRitesh Harjani 			 * Buffer after end of mapped extent.
22872943fdbcSRitesh Harjani 			 * Find next buffer in the page to map.
22882943fdbcSRitesh Harjani 			 */
22892943fdbcSRitesh Harjani 			mpd->map.m_len = 0;
22902943fdbcSRitesh Harjani 			mpd->map.m_flags = 0;
2291c8cc8816SRitesh Harjani 			io_end_vec->size += io_end_size;
22922943fdbcSRitesh Harjani 
22932943fdbcSRitesh Harjani 			err = mpage_process_page_bufs(mpd, head, bh, lblk);
22942943fdbcSRitesh Harjani 			if (err > 0)
22952943fdbcSRitesh Harjani 				err = 0;
2296c8cc8816SRitesh Harjani 			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2297c8cc8816SRitesh Harjani 				io_end_vec = ext4_alloc_io_end_vec(io_end);
22984d06bfb9SRitesh Harjani 				if (IS_ERR(io_end_vec)) {
22994d06bfb9SRitesh Harjani 					err = PTR_ERR(io_end_vec);
23004d06bfb9SRitesh Harjani 					goto out;
23014d06bfb9SRitesh Harjani 				}
2302d1e18b88SRitesh Harjani 				io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2303c8cc8816SRitesh Harjani 			}
23042943fdbcSRitesh Harjani 			*map_bh = true;
23052943fdbcSRitesh Harjani 			goto out;
23062943fdbcSRitesh Harjani 		}
23072943fdbcSRitesh Harjani 		if (buffer_delay(bh)) {
23082943fdbcSRitesh Harjani 			clear_buffer_delay(bh);
23092943fdbcSRitesh Harjani 			bh->b_blocknr = pblock++;
23102943fdbcSRitesh Harjani 		}
23112943fdbcSRitesh Harjani 		clear_buffer_unwritten(bh);
2312c8cc8816SRitesh Harjani 		io_end_size += (1 << blkbits);
23132943fdbcSRitesh Harjani 	} while (lblk++, (bh = bh->b_this_page) != head);
2314c8cc8816SRitesh Harjani 
2315c8cc8816SRitesh Harjani 	io_end_vec->size += io_end_size;
23162943fdbcSRitesh Harjani 	*map_bh = false;
23172943fdbcSRitesh Harjani out:
23182943fdbcSRitesh Harjani 	*m_lblk = lblk;
23192943fdbcSRitesh Harjani 	*m_pblk = pblock;
23202943fdbcSRitesh Harjani 	return err;
23212943fdbcSRitesh Harjani }
23222943fdbcSRitesh Harjani 
23232943fdbcSRitesh Harjani /*
23244e7ea81dSJan Kara  * mpage_map_buffers - update buffers corresponding to changed extent and
23254e7ea81dSJan Kara  *		       submit fully mapped pages for IO
23264e7ea81dSJan Kara  *
23274e7ea81dSJan Kara  * @mpd - description of extent to map, on return next extent to map
23284e7ea81dSJan Kara  *
23294e7ea81dSJan Kara  * Scan buffers corresponding to changed extent (we expect corresponding pages
23304e7ea81dSJan Kara  * to be already locked) and update buffer state according to new extent state.
23314e7ea81dSJan Kara  * We map delalloc buffers to their physical location, clear unwritten bits,
2332556615dcSLukas Czerner  * and mark buffers as uninit when we perform writes to unwritten extents
23334e7ea81dSJan Kara  * and do extent conversion after IO is finished. If the last page is not fully
23344e7ea81dSJan Kara  * mapped, we update @map to the next extent in the last page that needs
23354e7ea81dSJan Kara  * mapping. Otherwise we submit the page for IO.
23364e7ea81dSJan Kara  */
23374e7ea81dSJan Kara static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
23384e7ea81dSJan Kara {
23397530d093SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
23407530d093SMatthew Wilcox (Oracle) 	unsigned nr, i;
23414e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
234209cbfeafSKirill A. Shutemov 	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
23434e7ea81dSJan Kara 	pgoff_t start, end;
23444e7ea81dSJan Kara 	ext4_lblk_t lblk;
23452943fdbcSRitesh Harjani 	ext4_fsblk_t pblock;
23464e7ea81dSJan Kara 	int err;
23472943fdbcSRitesh Harjani 	bool map_bh = false;
23484e7ea81dSJan Kara 
23494e7ea81dSJan Kara 	start = mpd->map.m_lblk >> bpp_bits;
23504e7ea81dSJan Kara 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
23514e7ea81dSJan Kara 	lblk = start << bpp_bits;
23524e7ea81dSJan Kara 	pblock = mpd->map.m_pblk;
23534e7ea81dSJan Kara 
23547530d093SMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
23554e7ea81dSJan Kara 	while (start <= end) {
23567530d093SMatthew Wilcox (Oracle) 		nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
23577530d093SMatthew Wilcox (Oracle) 		if (nr == 0)
23584e7ea81dSJan Kara 			break;
23597530d093SMatthew Wilcox (Oracle) 		for (i = 0; i < nr; i++) {
23607530d093SMatthew Wilcox (Oracle) 			struct page *page = &fbatch.folios[i]->page;
23614e7ea81dSJan Kara 
23622943fdbcSRitesh Harjani 			err = mpage_process_page(mpd, page, &lblk, &pblock,
23632943fdbcSRitesh Harjani 						 &map_bh);
23644e7ea81dSJan Kara 			/*
23652943fdbcSRitesh Harjani 			 * If map_bh is true, means page may require further bh
23662943fdbcSRitesh Harjani 			 * mapping, or maybe the page was submitted for IO.
23672943fdbcSRitesh Harjani 			 * So we return to call further extent mapping.
23684e7ea81dSJan Kara 			 */
236939c0ae16SJason Yan 			if (err < 0 || map_bh)
23702943fdbcSRitesh Harjani 				goto out;
23714e7ea81dSJan Kara 			/* Page fully mapped - let IO run! */
23724e7ea81dSJan Kara 			err = mpage_submit_page(mpd, page);
23732943fdbcSRitesh Harjani 			if (err < 0)
23742943fdbcSRitesh Harjani 				goto out;
23754e7ea81dSJan Kara 		}
23767530d093SMatthew Wilcox (Oracle) 		folio_batch_release(&fbatch);
23774e7ea81dSJan Kara 	}
23784e7ea81dSJan Kara 	/* Extent fully mapped and matches with page boundary. We are done. */
23794e7ea81dSJan Kara 	mpd->map.m_len = 0;
23804e7ea81dSJan Kara 	mpd->map.m_flags = 0;
23814e7ea81dSJan Kara 	return 0;
23822943fdbcSRitesh Harjani out:
23837530d093SMatthew Wilcox (Oracle) 	folio_batch_release(&fbatch);
23842943fdbcSRitesh Harjani 	return err;
23854e7ea81dSJan Kara }
23864e7ea81dSJan Kara 
23874e7ea81dSJan Kara static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
23884e7ea81dSJan Kara {
23894e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
23904e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
23914e7ea81dSJan Kara 	int get_blocks_flags;
2392090f32eeSLukas Czerner 	int err, dioread_nolock;
23934e7ea81dSJan Kara 
23944e7ea81dSJan Kara 	trace_ext4_da_write_pages_extent(inode, map);
23954e7ea81dSJan Kara 	/*
23964e7ea81dSJan Kara 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2397556615dcSLukas Czerner 	 * to convert an unwritten extent to be initialized (in the case
23984e7ea81dSJan Kara 	 * where we have written into one or more preallocated blocks).  It is
23994e7ea81dSJan Kara 	 * possible that we're going to need more metadata blocks than
24004e7ea81dSJan Kara 	 * previously reserved. However we must not fail because we're in
24014e7ea81dSJan Kara 	 * writeback and there is nothing we can do about it so it might result
24024e7ea81dSJan Kara 	 * in data loss.  So use reserved blocks to allocate metadata if
24034e7ea81dSJan Kara 	 * possible.
24044e7ea81dSJan Kara 	 *
2405754cfed6STheodore Ts'o 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2406754cfed6STheodore Ts'o 	 * the blocks in question are delalloc blocks.  This indicates
2407754cfed6STheodore Ts'o 	 * that the blocks and quotas has already been checked when
2408754cfed6STheodore Ts'o 	 * the data was copied into the page cache.
24094e7ea81dSJan Kara 	 */
24104e7ea81dSJan Kara 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2411ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2412ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_IO_SUBMIT;
2413090f32eeSLukas Czerner 	dioread_nolock = ext4_should_dioread_nolock(inode);
2414090f32eeSLukas Czerner 	if (dioread_nolock)
24154e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
24166db07461SRitesh Harjani 	if (map->m_flags & BIT(BH_Delay))
24174e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
24184e7ea81dSJan Kara 
24194e7ea81dSJan Kara 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
24204e7ea81dSJan Kara 	if (err < 0)
24214e7ea81dSJan Kara 		return err;
2422090f32eeSLukas Czerner 	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
24236b523df4SJan Kara 		if (!mpd->io_submit.io_end->handle &&
24246b523df4SJan Kara 		    ext4_handle_valid(handle)) {
24256b523df4SJan Kara 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
24266b523df4SJan Kara 			handle->h_rsv_handle = NULL;
24276b523df4SJan Kara 		}
24283613d228SJan Kara 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
24296b523df4SJan Kara 	}
24304e7ea81dSJan Kara 
24314e7ea81dSJan Kara 	BUG_ON(map->m_len == 0);
24324e7ea81dSJan Kara 	return 0;
24334e7ea81dSJan Kara }
24344e7ea81dSJan Kara 
24354e7ea81dSJan Kara /*
24364e7ea81dSJan Kara  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
24374e7ea81dSJan Kara  *				 mpd->len and submit pages underlying it for IO
24384e7ea81dSJan Kara  *
24394e7ea81dSJan Kara  * @handle - handle for journal operations
24404e7ea81dSJan Kara  * @mpd - extent to map
24417534e854SJan Kara  * @give_up_on_write - we set this to true iff there is a fatal error and there
24427534e854SJan Kara  *                     is no hope of writing the data. The caller should discard
24437534e854SJan Kara  *                     dirty pages to avoid infinite loops.
24444e7ea81dSJan Kara  *
24454e7ea81dSJan Kara  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
24464e7ea81dSJan Kara  * delayed, blocks are allocated, if it is unwritten, we may need to convert
24474e7ea81dSJan Kara  * them to initialized or split the described range from larger unwritten
24484e7ea81dSJan Kara  * extent. Note that we need not map all the described range since allocation
24494e7ea81dSJan Kara  * can return less blocks or the range is covered by more unwritten extents. We
24504e7ea81dSJan Kara  * cannot map more because we are limited by reserved transaction credits. On
24514e7ea81dSJan Kara  * the other hand we always make sure that the last touched page is fully
24524e7ea81dSJan Kara  * mapped so that it can be written out (and thus forward progress is
24534e7ea81dSJan Kara  * guaranteed). After mapping we submit all mapped pages for IO.
24544e7ea81dSJan Kara  */
24554e7ea81dSJan Kara static int mpage_map_and_submit_extent(handle_t *handle,
2456cb530541STheodore Ts'o 				       struct mpage_da_data *mpd,
2457cb530541STheodore Ts'o 				       bool *give_up_on_write)
24584e7ea81dSJan Kara {
24594e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
24604e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
24614e7ea81dSJan Kara 	int err;
24624e7ea81dSJan Kara 	loff_t disksize;
24636603120eSDmitry Monakhov 	int progress = 0;
2464c8cc8816SRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
24654d06bfb9SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec;
24664e7ea81dSJan Kara 
24674d06bfb9SRitesh Harjani 	io_end_vec = ext4_alloc_io_end_vec(io_end);
24684d06bfb9SRitesh Harjani 	if (IS_ERR(io_end_vec))
24694d06bfb9SRitesh Harjani 		return PTR_ERR(io_end_vec);
2470c8cc8816SRitesh Harjani 	io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
247127d7c4edSJan Kara 	do {
24724e7ea81dSJan Kara 		err = mpage_map_one_extent(handle, mpd);
24734e7ea81dSJan Kara 		if (err < 0) {
24744e7ea81dSJan Kara 			struct super_block *sb = inode->i_sb;
24754e7ea81dSJan Kara 
24760db1ff22STheodore Ts'o 			if (ext4_forced_shutdown(EXT4_SB(sb)) ||
24779b5f6c9bSHarshad Shirwadkar 			    ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
2478cb530541STheodore Ts'o 				goto invalidate_dirty_pages;
24794e7ea81dSJan Kara 			/*
2480cb530541STheodore Ts'o 			 * Let the uper layers retry transient errors.
2481cb530541STheodore Ts'o 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2482cb530541STheodore Ts'o 			 * is non-zero, a commit should free up blocks.
24834e7ea81dSJan Kara 			 */
2484cb530541STheodore Ts'o 			if ((err == -ENOMEM) ||
24856603120eSDmitry Monakhov 			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
24866603120eSDmitry Monakhov 				if (progress)
24876603120eSDmitry Monakhov 					goto update_disksize;
2488cb530541STheodore Ts'o 				return err;
24896603120eSDmitry Monakhov 			}
24904e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24914e7ea81dSJan Kara 				 "Delayed block allocation failed for "
24924e7ea81dSJan Kara 				 "inode %lu at logical offset %llu with"
24934e7ea81dSJan Kara 				 " max blocks %u with error %d",
24944e7ea81dSJan Kara 				 inode->i_ino,
24954e7ea81dSJan Kara 				 (unsigned long long)map->m_lblk,
2496cb530541STheodore Ts'o 				 (unsigned)map->m_len, -err);
24974e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24984e7ea81dSJan Kara 				 "This should not happen!! Data will "
24994e7ea81dSJan Kara 				 "be lost\n");
25004e7ea81dSJan Kara 			if (err == -ENOSPC)
25014e7ea81dSJan Kara 				ext4_print_free_blocks(inode);
2502cb530541STheodore Ts'o 		invalidate_dirty_pages:
2503cb530541STheodore Ts'o 			*give_up_on_write = true;
25044e7ea81dSJan Kara 			return err;
25054e7ea81dSJan Kara 		}
25066603120eSDmitry Monakhov 		progress = 1;
25074e7ea81dSJan Kara 		/*
25084e7ea81dSJan Kara 		 * Update buffer state, submit mapped pages, and get us new
25094e7ea81dSJan Kara 		 * extent to map
25104e7ea81dSJan Kara 		 */
25114e7ea81dSJan Kara 		err = mpage_map_and_submit_buffers(mpd);
25124e7ea81dSJan Kara 		if (err < 0)
25136603120eSDmitry Monakhov 			goto update_disksize;
251427d7c4edSJan Kara 	} while (map->m_len);
25154e7ea81dSJan Kara 
25166603120eSDmitry Monakhov update_disksize:
2517622cad13STheodore Ts'o 	/*
2518622cad13STheodore Ts'o 	 * Update on-disk size after IO is submitted.  Races with
2519622cad13STheodore Ts'o 	 * truncate are avoided by checking i_size under i_data_sem.
2520622cad13STheodore Ts'o 	 */
252109cbfeafSKirill A. Shutemov 	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
252235df4299SQian Cai 	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
25234e7ea81dSJan Kara 		int err2;
2524622cad13STheodore Ts'o 		loff_t i_size;
25254e7ea81dSJan Kara 
2526622cad13STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
2527622cad13STheodore Ts'o 		i_size = i_size_read(inode);
2528622cad13STheodore Ts'o 		if (disksize > i_size)
2529622cad13STheodore Ts'o 			disksize = i_size;
2530622cad13STheodore Ts'o 		if (disksize > EXT4_I(inode)->i_disksize)
2531622cad13STheodore Ts'o 			EXT4_I(inode)->i_disksize = disksize;
2532622cad13STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
2533b907f2d5STheodore Ts'o 		err2 = ext4_mark_inode_dirty(handle, inode);
2534878520acSTheodore Ts'o 		if (err2) {
253554d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err2,
25364e7ea81dSJan Kara 				       "Failed to mark inode %lu dirty",
25374e7ea81dSJan Kara 				       inode->i_ino);
2538878520acSTheodore Ts'o 		}
25394e7ea81dSJan Kara 		if (!err)
25404e7ea81dSJan Kara 			err = err2;
25414e7ea81dSJan Kara 	}
25424e7ea81dSJan Kara 	return err;
25434e7ea81dSJan Kara }
25444e7ea81dSJan Kara 
25454e7ea81dSJan Kara /*
2546fffb2739SJan Kara  * Calculate the total number of credits to reserve for one writepages
254720970ba6STheodore Ts'o  * iteration. This is called from ext4_writepages(). We map an extent of
2548fffb2739SJan Kara  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2549fffb2739SJan Kara  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2550fffb2739SJan Kara  * bpp - 1 blocks in bpp different extents.
2551525f4ed8SMingming Cao  */
2552fffb2739SJan Kara static int ext4_da_writepages_trans_blocks(struct inode *inode)
2553fffb2739SJan Kara {
2554fffb2739SJan Kara 	int bpp = ext4_journal_blocks_per_page(inode);
2555525f4ed8SMingming Cao 
2556fffb2739SJan Kara 	return ext4_meta_trans_blocks(inode,
2557fffb2739SJan Kara 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2558525f4ed8SMingming Cao }
255961628a3fSMingming Cao 
2560*de0039f6SJan Kara /* Return true if the page needs to be written as part of transaction commit */
2561*de0039f6SJan Kara static bool ext4_page_nomap_can_writeout(struct page *page)
2562*de0039f6SJan Kara {
2563*de0039f6SJan Kara 	struct buffer_head *bh, *head;
2564*de0039f6SJan Kara 
2565*de0039f6SJan Kara 	bh = head = page_buffers(page);
2566*de0039f6SJan Kara 	do {
2567*de0039f6SJan Kara 		if (buffer_dirty(bh) && buffer_mapped(bh) && !buffer_delay(bh))
2568*de0039f6SJan Kara 			return true;
2569*de0039f6SJan Kara 	} while ((bh = bh->b_this_page) != head);
2570*de0039f6SJan Kara 	return false;
2571*de0039f6SJan Kara }
2572*de0039f6SJan Kara 
25738e48dcfbSTheodore Ts'o /*
25744e7ea81dSJan Kara  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2575*de0039f6SJan Kara  * 				 needing mapping, submit mapped pages
25764e7ea81dSJan Kara  *
25774e7ea81dSJan Kara  * @mpd - where to look for pages
25784e7ea81dSJan Kara  *
25794e7ea81dSJan Kara  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2580*de0039f6SJan Kara  * IO immediately. If we cannot map blocks, we submit just already mapped
2581*de0039f6SJan Kara  * buffers in the page for IO and keep page dirty. When we can map blocks and
2582*de0039f6SJan Kara  * we find a page which isn't mapped we start accumulating extent of buffers
2583*de0039f6SJan Kara  * underlying these pages that needs mapping (formed by either delayed or
2584*de0039f6SJan Kara  * unwritten buffers). We also lock the pages containing these buffers. The
2585*de0039f6SJan Kara  * extent found is returned in @mpd structure (starting at mpd->lblk with
2586*de0039f6SJan Kara  * length mpd->len blocks).
25874e7ea81dSJan Kara  *
25884e7ea81dSJan Kara  * Note that this function can attach bios to one io_end structure which are
25894e7ea81dSJan Kara  * neither logically nor physically contiguous. Although it may seem as an
25904e7ea81dSJan Kara  * unnecessary complication, it is actually inevitable in blocksize < pagesize
25914e7ea81dSJan Kara  * case as we need to track IO to all buffers underlying a page in one io_end.
25928e48dcfbSTheodore Ts'o  */
25934e7ea81dSJan Kara static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
25948e48dcfbSTheodore Ts'o {
25954e7ea81dSJan Kara 	struct address_space *mapping = mpd->inode->i_mapping;
25968e48dcfbSTheodore Ts'o 	struct pagevec pvec;
25974f01b02cSTheodore Ts'o 	unsigned int nr_pages;
2598aeac589aSMing Lei 	long left = mpd->wbc->nr_to_write;
25994e7ea81dSJan Kara 	pgoff_t index = mpd->first_page;
26004e7ea81dSJan Kara 	pgoff_t end = mpd->last_page;
260110bbd235SMatthew Wilcox 	xa_mark_t tag;
26024e7ea81dSJan Kara 	int i, err = 0;
26034e7ea81dSJan Kara 	int blkbits = mpd->inode->i_blkbits;
26044e7ea81dSJan Kara 	ext4_lblk_t lblk;
26054e7ea81dSJan Kara 	struct buffer_head *head;
26068e48dcfbSTheodore Ts'o 
26074e7ea81dSJan Kara 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
26085b41d924SEric Sandeen 		tag = PAGECACHE_TAG_TOWRITE;
26095b41d924SEric Sandeen 	else
26105b41d924SEric Sandeen 		tag = PAGECACHE_TAG_DIRTY;
26115b41d924SEric Sandeen 
261286679820SMel Gorman 	pagevec_init(&pvec);
26134e7ea81dSJan Kara 	mpd->map.m_len = 0;
26144e7ea81dSJan Kara 	mpd->next_page = index;
26154f01b02cSTheodore Ts'o 	while (index <= end) {
2616dc7f3e86SJan Kara 		nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
261767fd707fSJan Kara 				tag);
26188e48dcfbSTheodore Ts'o 		if (nr_pages == 0)
26196b8ed620SJan Kara 			break;
26208e48dcfbSTheodore Ts'o 
26218e48dcfbSTheodore Ts'o 		for (i = 0; i < nr_pages; i++) {
26228e48dcfbSTheodore Ts'o 			struct page *page = pvec.pages[i];
26238e48dcfbSTheodore Ts'o 
26248e48dcfbSTheodore Ts'o 			/*
2625aeac589aSMing Lei 			 * Accumulated enough dirty pages? This doesn't apply
2626aeac589aSMing Lei 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2627aeac589aSMing Lei 			 * keep going because someone may be concurrently
2628aeac589aSMing Lei 			 * dirtying pages, and we might have synced a lot of
2629aeac589aSMing Lei 			 * newly appeared dirty pages, but have not synced all
2630aeac589aSMing Lei 			 * of the old dirty pages.
2631aeac589aSMing Lei 			 */
2632aeac589aSMing Lei 			if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2633aeac589aSMing Lei 				goto out;
2634aeac589aSMing Lei 
26354e7ea81dSJan Kara 			/* If we can't merge this page, we are done. */
26364e7ea81dSJan Kara 			if (mpd->map.m_len > 0 && mpd->next_page != page->index)
26374e7ea81dSJan Kara 				goto out;
263878aaced3STheodore Ts'o 
26398e48dcfbSTheodore Ts'o 			lock_page(page);
26408e48dcfbSTheodore Ts'o 			/*
26414e7ea81dSJan Kara 			 * If the page is no longer dirty, or its mapping no
26424e7ea81dSJan Kara 			 * longer corresponds to inode we are writing (which
26434e7ea81dSJan Kara 			 * means it has been truncated or invalidated), or the
26444e7ea81dSJan Kara 			 * page is already under writeback and we are not doing
26454e7ea81dSJan Kara 			 * a data integrity writeback, skip the page
26468e48dcfbSTheodore Ts'o 			 */
26474f01b02cSTheodore Ts'o 			if (!PageDirty(page) ||
26484f01b02cSTheodore Ts'o 			    (PageWriteback(page) &&
26494e7ea81dSJan Kara 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
26504f01b02cSTheodore Ts'o 			    unlikely(page->mapping != mapping)) {
26518e48dcfbSTheodore Ts'o 				unlock_page(page);
26528e48dcfbSTheodore Ts'o 				continue;
26538e48dcfbSTheodore Ts'o 			}
26548e48dcfbSTheodore Ts'o 
26558e48dcfbSTheodore Ts'o 			wait_on_page_writeback(page);
26568e48dcfbSTheodore Ts'o 			BUG_ON(PageWriteback(page));
26578e48dcfbSTheodore Ts'o 
2658cc509574STheodore Ts'o 			/*
2659cc509574STheodore Ts'o 			 * Should never happen but for buggy code in
2660cc509574STheodore Ts'o 			 * other subsystems that call
2661cc509574STheodore Ts'o 			 * set_page_dirty() without properly warning
2662cc509574STheodore Ts'o 			 * the file system first.  See [1] for more
2663cc509574STheodore Ts'o 			 * information.
2664cc509574STheodore Ts'o 			 *
2665cc509574STheodore Ts'o 			 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2666cc509574STheodore Ts'o 			 */
2667cc509574STheodore Ts'o 			if (!page_has_buffers(page)) {
2668cc509574STheodore Ts'o 				ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", page->index);
2669cc509574STheodore Ts'o 				ClearPageDirty(page);
2670cc509574STheodore Ts'o 				unlock_page(page);
2671cc509574STheodore Ts'o 				continue;
2672cc509574STheodore Ts'o 			}
2673cc509574STheodore Ts'o 
26744e7ea81dSJan Kara 			if (mpd->map.m_len == 0)
26758eb9e5ceSTheodore Ts'o 				mpd->first_page = page->index;
26768eb9e5ceSTheodore Ts'o 			mpd->next_page = page->index + 1;
2677*de0039f6SJan Kara 			/*
2678*de0039f6SJan Kara 			 * Writeout for transaction commit where we cannot
2679*de0039f6SJan Kara 			 * modify metadata is simple. Just submit the page.
2680*de0039f6SJan Kara 			 */
2681*de0039f6SJan Kara 			if (!mpd->can_map) {
2682*de0039f6SJan Kara 				if (ext4_page_nomap_can_writeout(page)) {
2683*de0039f6SJan Kara 					err = mpage_submit_page(mpd, page);
2684*de0039f6SJan Kara 					if (err < 0)
2685*de0039f6SJan Kara 						goto out;
2686*de0039f6SJan Kara 				} else {
2687*de0039f6SJan Kara 					unlock_page(page);
2688*de0039f6SJan Kara 					mpd->first_page++;
2689*de0039f6SJan Kara 				}
2690*de0039f6SJan Kara 			} else {
2691f8bec370SJan Kara 				/* Add all dirty buffers to mpd */
26924e7ea81dSJan Kara 				lblk = ((ext4_lblk_t)page->index) <<
269309cbfeafSKirill A. Shutemov 					(PAGE_SHIFT - blkbits);
26948eb9e5ceSTheodore Ts'o 				head = page_buffers(page);
2695*de0039f6SJan Kara 				err = mpage_process_page_bufs(mpd, head, head,
2696*de0039f6SJan Kara 							      lblk);
26975f1132b2SJan Kara 				if (err <= 0)
26984e7ea81dSJan Kara 					goto out;
26995f1132b2SJan Kara 				err = 0;
2700*de0039f6SJan Kara 			}
2701aeac589aSMing Lei 			left--;
27028e48dcfbSTheodore Ts'o 		}
27038e48dcfbSTheodore Ts'o 		pagevec_release(&pvec);
27048e48dcfbSTheodore Ts'o 		cond_resched();
27058e48dcfbSTheodore Ts'o 	}
27066b8ed620SJan Kara 	mpd->scanned_until_end = 1;
27074f01b02cSTheodore Ts'o 	return 0;
27088eb9e5ceSTheodore Ts'o out:
27098eb9e5ceSTheodore Ts'o 	pagevec_release(&pvec);
27104e7ea81dSJan Kara 	return err;
27118e48dcfbSTheodore Ts'o }
27128e48dcfbSTheodore Ts'o 
271320970ba6STheodore Ts'o static int ext4_writepages(struct address_space *mapping,
271464769240SAlex Tomas 			   struct writeback_control *wbc)
271564769240SAlex Tomas {
27164e7ea81dSJan Kara 	pgoff_t	writeback_index = 0;
27174e7ea81dSJan Kara 	long nr_to_write = wbc->nr_to_write;
271822208dedSAneesh Kumar K.V 	int range_whole = 0;
27194e7ea81dSJan Kara 	int cycled = 1;
272061628a3fSMingming Cao 	handle_t *handle = NULL;
2721df22291fSAneesh Kumar K.V 	struct mpage_da_data mpd;
27225e745b04SAneesh Kumar K.V 	struct inode *inode = mapping->host;
27236b523df4SJan Kara 	int needed_blocks, rsv_blocks = 0, ret = 0;
27245e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
27251bce63d1SShaohua Li 	struct blk_plug plug;
2726cb530541STheodore Ts'o 	bool give_up_on_write = false;
272761628a3fSMingming Cao 
27280db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
27290db1ff22STheodore Ts'o 		return -EIO;
27300db1ff22STheodore Ts'o 
2731bbd55937SEric Biggers 	percpu_down_read(&sbi->s_writepages_rwsem);
273220970ba6STheodore Ts'o 	trace_ext4_writepages(inode, wbc);
2733ba80b101STheodore Ts'o 
273461628a3fSMingming Cao 	/*
273561628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
273661628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
273761628a3fSMingming Cao 	 * because that could violate lock ordering on umount
273861628a3fSMingming Cao 	 */
2739a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2740bbf023c7SMing Lei 		goto out_writepages;
27412a21e37eSTheodore Ts'o 
274220970ba6STheodore Ts'o 	if (ext4_should_journal_data(inode)) {
2743043d20d1SGoldwyn Rodrigues 		ret = generic_writepages(mapping, wbc);
2744bbf023c7SMing Lei 		goto out_writepages;
274520970ba6STheodore Ts'o 	}
274620970ba6STheodore Ts'o 
27472a21e37eSTheodore Ts'o 	/*
27482a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
27492a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
27502a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
27511751e8a6SLinus Torvalds 	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
27522a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
275320970ba6STheodore Ts'o 	 * read-only, and in that case, ext4_writepages should
27542a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
27552a21e37eSTheodore Ts'o 	 * the stack trace.
27562a21e37eSTheodore Ts'o 	 */
27570db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
27589b5f6c9bSHarshad Shirwadkar 		     ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
2759bbf023c7SMing Lei 		ret = -EROFS;
2760bbf023c7SMing Lei 		goto out_writepages;
2761bbf023c7SMing Lei 	}
27622a21e37eSTheodore Ts'o 
27634e7ea81dSJan Kara 	/*
27644e7ea81dSJan Kara 	 * If we have inline data and arrive here, it means that
27654e7ea81dSJan Kara 	 * we will soon create the block for the 1st page, so
27664e7ea81dSJan Kara 	 * we'd better clear the inline data here.
27674e7ea81dSJan Kara 	 */
27684e7ea81dSJan Kara 	if (ext4_has_inline_data(inode)) {
27694e7ea81dSJan Kara 		/* Just inode will be modified... */
27704e7ea81dSJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
27714e7ea81dSJan Kara 		if (IS_ERR(handle)) {
27724e7ea81dSJan Kara 			ret = PTR_ERR(handle);
27734e7ea81dSJan Kara 			goto out_writepages;
27744e7ea81dSJan Kara 		}
27754e7ea81dSJan Kara 		BUG_ON(ext4_test_inode_state(inode,
27764e7ea81dSJan Kara 				EXT4_STATE_MAY_INLINE_DATA));
27774e7ea81dSJan Kara 		ext4_destroy_inline_data(handle, inode);
27784e7ea81dSJan Kara 		ext4_journal_stop(handle);
27794e7ea81dSJan Kara 	}
27804e7ea81dSJan Kara 
27814e343231Syangerkun 	if (ext4_should_dioread_nolock(inode)) {
27824e343231Syangerkun 		/*
27834e343231Syangerkun 		 * We may need to convert up to one extent per block in
27844e343231Syangerkun 		 * the page and we may dirty the inode.
27854e343231Syangerkun 		 */
27864e343231Syangerkun 		rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
27874e343231Syangerkun 						PAGE_SIZE >> inode->i_blkbits);
27884e343231Syangerkun 	}
27894e343231Syangerkun 
279022208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
279122208dedSAneesh Kumar K.V 		range_whole = 1;
279261628a3fSMingming Cao 
27932acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
27944e7ea81dSJan Kara 		writeback_index = mapping->writeback_index;
27954e7ea81dSJan Kara 		if (writeback_index)
27962acf2c26SAneesh Kumar K.V 			cycled = 0;
27974e7ea81dSJan Kara 		mpd.first_page = writeback_index;
27984e7ea81dSJan Kara 		mpd.last_page = -1;
27995b41d924SEric Sandeen 	} else {
280009cbfeafSKirill A. Shutemov 		mpd.first_page = wbc->range_start >> PAGE_SHIFT;
280109cbfeafSKirill A. Shutemov 		mpd.last_page = wbc->range_end >> PAGE_SHIFT;
28025b41d924SEric Sandeen 	}
2803a1d6cc56SAneesh Kumar K.V 
28044e7ea81dSJan Kara 	mpd.inode = inode;
28054e7ea81dSJan Kara 	mpd.wbc = wbc;
28064e7ea81dSJan Kara 	ext4_io_submit_init(&mpd.io_submit, wbc);
28072acf2c26SAneesh Kumar K.V retry:
28086e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
28094e7ea81dSJan Kara 		tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
28101bce63d1SShaohua Li 	blk_start_plug(&plug);
2811dddbd6acSJan Kara 
2812dddbd6acSJan Kara 	/*
2813dddbd6acSJan Kara 	 * First writeback pages that don't need mapping - we can avoid
2814dddbd6acSJan Kara 	 * starting a transaction unnecessarily and also avoid being blocked
2815dddbd6acSJan Kara 	 * in the block layer on device congestion while having transaction
2816dddbd6acSJan Kara 	 * started.
2817dddbd6acSJan Kara 	 */
2818dddbd6acSJan Kara 	mpd.do_map = 0;
28196b8ed620SJan Kara 	mpd.scanned_until_end = 0;
2820*de0039f6SJan Kara 	mpd.can_map = 1;
2821dddbd6acSJan Kara 	mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2822dddbd6acSJan Kara 	if (!mpd.io_submit.io_end) {
2823dddbd6acSJan Kara 		ret = -ENOMEM;
2824dddbd6acSJan Kara 		goto unplug;
2825dddbd6acSJan Kara 	}
2826dddbd6acSJan Kara 	ret = mpage_prepare_extent_to_map(&mpd);
2827a297b2fcSXiaoguang Wang 	/* Unlock pages we didn't use */
2828a297b2fcSXiaoguang Wang 	mpage_release_unused_pages(&mpd, false);
2829dddbd6acSJan Kara 	/* Submit prepared bio */
2830dddbd6acSJan Kara 	ext4_io_submit(&mpd.io_submit);
2831dddbd6acSJan Kara 	ext4_put_io_end_defer(mpd.io_submit.io_end);
2832dddbd6acSJan Kara 	mpd.io_submit.io_end = NULL;
2833dddbd6acSJan Kara 	if (ret < 0)
2834dddbd6acSJan Kara 		goto unplug;
2835dddbd6acSJan Kara 
28366b8ed620SJan Kara 	while (!mpd.scanned_until_end && wbc->nr_to_write > 0) {
28374e7ea81dSJan Kara 		/* For each extent of pages we use new io_end */
28384e7ea81dSJan Kara 		mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
28394e7ea81dSJan Kara 		if (!mpd.io_submit.io_end) {
28404e7ea81dSJan Kara 			ret = -ENOMEM;
28414e7ea81dSJan Kara 			break;
28424e7ea81dSJan Kara 		}
2843a1d6cc56SAneesh Kumar K.V 
2844*de0039f6SJan Kara 		WARN_ON_ONCE(!mpd->can_map);
2845a1d6cc56SAneesh Kumar K.V 		/*
28464e7ea81dSJan Kara 		 * We have two constraints: We find one extent to map and we
28474e7ea81dSJan Kara 		 * must always write out whole page (makes a difference when
28484e7ea81dSJan Kara 		 * blocksize < pagesize) so that we don't block on IO when we
28494e7ea81dSJan Kara 		 * try to write out the rest of the page. Journalled mode is
28504e7ea81dSJan Kara 		 * not supported by delalloc.
2851a1d6cc56SAneesh Kumar K.V 		 */
2852a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
2853525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2854a1d6cc56SAneesh Kumar K.V 
285561628a3fSMingming Cao 		/* start a new transaction */
28566b523df4SJan Kara 		handle = ext4_journal_start_with_reserve(inode,
28576b523df4SJan Kara 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
285861628a3fSMingming Cao 		if (IS_ERR(handle)) {
285961628a3fSMingming Cao 			ret = PTR_ERR(handle);
28601693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2861fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
2862a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
28634e7ea81dSJan Kara 			/* Release allocated io_end */
28644e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
2865dddbd6acSJan Kara 			mpd.io_submit.io_end = NULL;
28664e7ea81dSJan Kara 			break;
286761628a3fSMingming Cao 		}
2868dddbd6acSJan Kara 		mpd.do_map = 1;
2869f63e6005STheodore Ts'o 
28704e7ea81dSJan Kara 		trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
28714e7ea81dSJan Kara 		ret = mpage_prepare_extent_to_map(&mpd);
28726b8ed620SJan Kara 		if (!ret && mpd.map.m_len)
2873cb530541STheodore Ts'o 			ret = mpage_map_and_submit_extent(handle, &mpd,
2874cb530541STheodore Ts'o 					&give_up_on_write);
2875646caa9cSJan Kara 		/*
2876646caa9cSJan Kara 		 * Caution: If the handle is synchronous,
2877646caa9cSJan Kara 		 * ext4_journal_stop() can wait for transaction commit
2878646caa9cSJan Kara 		 * to finish which may depend on writeback of pages to
2879646caa9cSJan Kara 		 * complete or on page lock to be released.  In that
2880b483bb77SRandy Dunlap 		 * case, we have to wait until after we have
2881646caa9cSJan Kara 		 * submitted all the IO, released page locks we hold,
2882646caa9cSJan Kara 		 * and dropped io_end reference (for extent conversion
2883646caa9cSJan Kara 		 * to be able to complete) before stopping the handle.
2884646caa9cSJan Kara 		 */
2885646caa9cSJan Kara 		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
288661628a3fSMingming Cao 			ext4_journal_stop(handle);
2887646caa9cSJan Kara 			handle = NULL;
2888dddbd6acSJan Kara 			mpd.do_map = 0;
2889646caa9cSJan Kara 		}
28904e7ea81dSJan Kara 		/* Unlock pages we didn't use */
2891cb530541STheodore Ts'o 		mpage_release_unused_pages(&mpd, give_up_on_write);
2892a297b2fcSXiaoguang Wang 		/* Submit prepared bio */
2893a297b2fcSXiaoguang Wang 		ext4_io_submit(&mpd.io_submit);
2894a297b2fcSXiaoguang Wang 
2895646caa9cSJan Kara 		/*
2896646caa9cSJan Kara 		 * Drop our io_end reference we got from init. We have
2897646caa9cSJan Kara 		 * to be careful and use deferred io_end finishing if
2898646caa9cSJan Kara 		 * we are still holding the transaction as we can
2899646caa9cSJan Kara 		 * release the last reference to io_end which may end
2900646caa9cSJan Kara 		 * up doing unwritten extent conversion.
2901646caa9cSJan Kara 		 */
2902646caa9cSJan Kara 		if (handle) {
2903646caa9cSJan Kara 			ext4_put_io_end_defer(mpd.io_submit.io_end);
2904646caa9cSJan Kara 			ext4_journal_stop(handle);
2905646caa9cSJan Kara 		} else
29064e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
2907dddbd6acSJan Kara 		mpd.io_submit.io_end = NULL;
2908df22291fSAneesh Kumar K.V 
29094e7ea81dSJan Kara 		if (ret == -ENOSPC && sbi->s_journal) {
29104e7ea81dSJan Kara 			/*
29114e7ea81dSJan Kara 			 * Commit the transaction which would
291222208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
291322208dedSAneesh Kumar K.V 			 * and try again
291422208dedSAneesh Kumar K.V 			 */
2915df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
291622208dedSAneesh Kumar K.V 			ret = 0;
29174e7ea81dSJan Kara 			continue;
29184e7ea81dSJan Kara 		}
29194e7ea81dSJan Kara 		/* Fatal error - ENOMEM, EIO... */
29204e7ea81dSJan Kara 		if (ret)
292161628a3fSMingming Cao 			break;
292261628a3fSMingming Cao 	}
2923dddbd6acSJan Kara unplug:
29241bce63d1SShaohua Li 	blk_finish_plug(&plug);
29259c12a831SJan Kara 	if (!ret && !cycled && wbc->nr_to_write > 0) {
29262acf2c26SAneesh Kumar K.V 		cycled = 1;
29274e7ea81dSJan Kara 		mpd.last_page = writeback_index - 1;
29284e7ea81dSJan Kara 		mpd.first_page = 0;
29292acf2c26SAneesh Kumar K.V 		goto retry;
29302acf2c26SAneesh Kumar K.V 	}
293161628a3fSMingming Cao 
293222208dedSAneesh Kumar K.V 	/* Update index */
293322208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
293422208dedSAneesh Kumar K.V 		/*
29354e7ea81dSJan Kara 		 * Set the writeback_index so that range_cyclic
293622208dedSAneesh Kumar K.V 		 * mode will write it back later
293722208dedSAneesh Kumar K.V 		 */
29384e7ea81dSJan Kara 		mapping->writeback_index = mpd.first_page;
2939a1d6cc56SAneesh Kumar K.V 
294061628a3fSMingming Cao out_writepages:
294120970ba6STheodore Ts'o 	trace_ext4_writepages_result(inode, wbc, ret,
29424e7ea81dSJan Kara 				     nr_to_write - wbc->nr_to_write);
2943bbd55937SEric Biggers 	percpu_up_read(&sbi->s_writepages_rwsem);
294461628a3fSMingming Cao 	return ret;
294564769240SAlex Tomas }
294664769240SAlex Tomas 
29475f0663bbSDan Williams static int ext4_dax_writepages(struct address_space *mapping,
29485f0663bbSDan Williams 			       struct writeback_control *wbc)
29495f0663bbSDan Williams {
29505f0663bbSDan Williams 	int ret;
29515f0663bbSDan Williams 	long nr_to_write = wbc->nr_to_write;
29525f0663bbSDan Williams 	struct inode *inode = mapping->host;
29535f0663bbSDan Williams 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
29545f0663bbSDan Williams 
29555f0663bbSDan Williams 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
29565f0663bbSDan Williams 		return -EIO;
29575f0663bbSDan Williams 
2958bbd55937SEric Biggers 	percpu_down_read(&sbi->s_writepages_rwsem);
29595f0663bbSDan Williams 	trace_ext4_writepages(inode, wbc);
29605f0663bbSDan Williams 
29613f666c56SVivek Goyal 	ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
29625f0663bbSDan Williams 	trace_ext4_writepages_result(inode, wbc, ret,
29635f0663bbSDan Williams 				     nr_to_write - wbc->nr_to_write);
2964bbd55937SEric Biggers 	percpu_up_read(&sbi->s_writepages_rwsem);
29655f0663bbSDan Williams 	return ret;
29665f0663bbSDan Williams }
29675f0663bbSDan Williams 
296879f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
296979f0be8dSAneesh Kumar K.V {
29705c1ff336SEric Whitney 	s64 free_clusters, dirty_clusters;
297179f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
297279f0be8dSAneesh Kumar K.V 
297379f0be8dSAneesh Kumar K.V 	/*
297479f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
297579f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
2976179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
297779f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
297879f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
297979f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
298079f0be8dSAneesh Kumar K.V 	 */
29815c1ff336SEric Whitney 	free_clusters =
29825c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
29835c1ff336SEric Whitney 	dirty_clusters =
29845c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
298500d4e736STheodore Ts'o 	/*
298600d4e736STheodore Ts'o 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
298700d4e736STheodore Ts'o 	 */
29885c1ff336SEric Whitney 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
298910ee27a0SMiao Xie 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
299000d4e736STheodore Ts'o 
29915c1ff336SEric Whitney 	if (2 * free_clusters < 3 * dirty_clusters ||
29925c1ff336SEric Whitney 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
299379f0be8dSAneesh Kumar K.V 		/*
2994c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
2995c8afb446SEric Sandeen 		 * or free blocks is less than watermark
299679f0be8dSAneesh Kumar K.V 		 */
299779f0be8dSAneesh Kumar K.V 		return 1;
299879f0be8dSAneesh Kumar K.V 	}
299979f0be8dSAneesh Kumar K.V 	return 0;
300079f0be8dSAneesh Kumar K.V }
300179f0be8dSAneesh Kumar K.V 
300264769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
30039d6b0cd7SMatthew Wilcox (Oracle) 			       loff_t pos, unsigned len,
300464769240SAlex Tomas 			       struct page **pagep, void **fsdata)
300564769240SAlex Tomas {
300672b8ab9dSEric Sandeen 	int ret, retries = 0;
300764769240SAlex Tomas 	struct page *page;
300864769240SAlex Tomas 	pgoff_t index;
300964769240SAlex Tomas 	struct inode *inode = mapping->host;
301064769240SAlex Tomas 
30110db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
30120db1ff22STheodore Ts'o 		return -EIO;
30130db1ff22STheodore Ts'o 
301409cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
301579f0be8dSAneesh Kumar K.V 
30166493792dSZhang Yi 	if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
301779f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
301879f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
30199d6b0cd7SMatthew Wilcox (Oracle) 					len, pagep, fsdata);
302079f0be8dSAneesh Kumar K.V 	}
302179f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
30229d6b0cd7SMatthew Wilcox (Oracle) 	trace_ext4_da_write_begin(inode, pos, len);
30239c3569b5STao Ma 
30249c3569b5STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
302536d116e9SMatthew Wilcox (Oracle) 		ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len,
30269c3569b5STao Ma 						      pagep, fsdata);
30279c3569b5STao Ma 		if (ret < 0)
302847564bfbSTheodore Ts'o 			return ret;
302947564bfbSTheodore Ts'o 		if (ret == 1)
303047564bfbSTheodore Ts'o 			return 0;
30319c3569b5STao Ma 	}
30329c3569b5STao Ma 
3033cc883236SZhang Yi retry:
3034b7446e7cSMatthew Wilcox (Oracle) 	page = grab_cache_page_write_begin(mapping, index);
303547564bfbSTheodore Ts'o 	if (!page)
303647564bfbSTheodore Ts'o 		return -ENOMEM;
303747564bfbSTheodore Ts'o 
303847564bfbSTheodore Ts'o 	/* In case writeback began while the page was unlocked */
30397afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
304064769240SAlex Tomas 
3041643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
30422058f83aSMichael Halcrow 	ret = ext4_block_write_begin(page, pos, len,
30432058f83aSMichael Halcrow 				     ext4_da_get_block_prep);
30442058f83aSMichael Halcrow #else
30456e1db88dSChristoph Hellwig 	ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
30462058f83aSMichael Halcrow #endif
304764769240SAlex Tomas 	if (ret < 0) {
304864769240SAlex Tomas 		unlock_page(page);
3049cc883236SZhang Yi 		put_page(page);
3050ae4d5372SAneesh Kumar K.V 		/*
3051ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
3052ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
3053cc883236SZhang Yi 		 * i_size_read because we hold inode lock.
3054ae4d5372SAneesh Kumar K.V 		 */
3055ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
3056b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
305747564bfbSTheodore Ts'o 
305847564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
305947564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
3060cc883236SZhang Yi 			goto retry;
306147564bfbSTheodore Ts'o 		return ret;
306264769240SAlex Tomas 	}
306364769240SAlex Tomas 
306447564bfbSTheodore Ts'o 	*pagep = page;
306564769240SAlex Tomas 	return ret;
306664769240SAlex Tomas }
306764769240SAlex Tomas 
3068632eaeabSMingming Cao /*
3069632eaeabSMingming Cao  * Check if we should update i_disksize
3070632eaeabSMingming Cao  * when write to the end of file but not require block allocation
3071632eaeabSMingming Cao  */
3072632eaeabSMingming Cao static int ext4_da_should_update_i_disksize(struct page *page,
3073632eaeabSMingming Cao 					    unsigned long offset)
3074632eaeabSMingming Cao {
3075632eaeabSMingming Cao 	struct buffer_head *bh;
3076632eaeabSMingming Cao 	struct inode *inode = page->mapping->host;
3077632eaeabSMingming Cao 	unsigned int idx;
3078632eaeabSMingming Cao 	int i;
3079632eaeabSMingming Cao 
3080632eaeabSMingming Cao 	bh = page_buffers(page);
3081632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
3082632eaeabSMingming Cao 
3083632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
3084632eaeabSMingming Cao 		bh = bh->b_this_page;
3085632eaeabSMingming Cao 
308629fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3087632eaeabSMingming Cao 		return 0;
3088632eaeabSMingming Cao 	return 1;
3089632eaeabSMingming Cao }
3090632eaeabSMingming Cao 
309164769240SAlex Tomas static int ext4_da_write_end(struct file *file,
309264769240SAlex Tomas 			     struct address_space *mapping,
309364769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
309464769240SAlex Tomas 			     struct page *page, void *fsdata)
309564769240SAlex Tomas {
309664769240SAlex Tomas 	struct inode *inode = mapping->host;
309764769240SAlex Tomas 	loff_t new_i_size;
3098632eaeabSMingming Cao 	unsigned long start, end;
309979f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
310079f0be8dSAneesh Kumar K.V 
310174d553aaSTheodore Ts'o 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
310274d553aaSTheodore Ts'o 		return ext4_write_end(file, mapping, pos,
310379f0be8dSAneesh Kumar K.V 				      len, copied, page, fsdata);
3104632eaeabSMingming Cao 
31059bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
31069c3569b5STao Ma 
31079c3569b5STao Ma 	if (write_mode != CONVERT_INLINE_DATA &&
31089c3569b5STao Ma 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
31099c3569b5STao Ma 	    ext4_has_inline_data(inode))
31106984aef5SZhang Yi 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
31119c3569b5STao Ma 
311264769240SAlex Tomas 	start = pos & (PAGE_SIZE - 1);
311364769240SAlex Tomas 	end = start + copied - 1;
311464769240SAlex Tomas 
311564769240SAlex Tomas 	/*
31164df031ffSZhang Yi 	 * Since we are holding inode lock, we are sure i_disksize <=
31174df031ffSZhang Yi 	 * i_size. We also know that if i_disksize < i_size, there are
31184df031ffSZhang Yi 	 * delalloc writes pending in the range upto i_size. If the end of
31194df031ffSZhang Yi 	 * the current write is <= i_size, there's no need to touch
31204df031ffSZhang Yi 	 * i_disksize since writeback will push i_disksize upto i_size
31214df031ffSZhang Yi 	 * eventually. If the end of the current write is > i_size and
31224df031ffSZhang Yi 	 * inside an allocated block (ext4_da_should_update_i_disksize()
31234df031ffSZhang Yi 	 * check), we need to update i_disksize here as neither
31244df031ffSZhang Yi 	 * ext4_writepage() nor certain ext4_writepages() paths not
31254df031ffSZhang Yi 	 * allocating blocks update i_disksize.
31264df031ffSZhang Yi 	 *
31274df031ffSZhang Yi 	 * Note that we defer inode dirtying to generic_write_end() /
31284df031ffSZhang Yi 	 * ext4_da_write_inline_data_end().
3129d2a17637SMingming Cao 	 */
313064769240SAlex Tomas 	new_i_size = pos + copied;
31316984aef5SZhang Yi 	if (copied && new_i_size > inode->i_size &&
31324df031ffSZhang Yi 	    ext4_da_should_update_i_disksize(page, end))
313364769240SAlex Tomas 		ext4_update_i_disksize(inode, new_i_size);
3134ccd2506bSTheodore Ts'o 
3135cc883236SZhang Yi 	return generic_write_end(file, mapping, pos, len, copied, page, fsdata);
3136ac27a0ecSDave Kleikamp }
3137ac27a0ecSDave Kleikamp 
3138ccd2506bSTheodore Ts'o /*
3139ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
3140ccd2506bSTheodore Ts'o  */
3141ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
3142ccd2506bSTheodore Ts'o {
3143ccd2506bSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
3144ccd2506bSTheodore Ts'o 
314571d4f7d0STheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks)
3146ccd2506bSTheodore Ts'o 		return 0;
3147ccd2506bSTheodore Ts'o 
3148ccd2506bSTheodore Ts'o 	/*
3149ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
3150ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
3151ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
3152ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
3153ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
3154ccd2506bSTheodore Ts'o 	 *
315520970ba6STheodore Ts'o 	 * ext4_writepages() ->
3156ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
3157ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
3158ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
3159ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
3160ccd2506bSTheodore Ts'o 	 *
3161ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
3162ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
3163ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
3164ccd2506bSTheodore Ts'o 	 * doing I/O at all.
3165ccd2506bSTheodore Ts'o 	 *
3166ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
3167380cf090SWu Fengguang 	 * the pages by calling redirty_page_for_writepage() but that
3168ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
3169ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
317025985edcSLucas De Marchi 	 * simplifying them because we wouldn't actually intend to
3171ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
3172ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
3173ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
3174ccd2506bSTheodore Ts'o 	 *
3175ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
3176ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
3177ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
3178ccd2506bSTheodore Ts'o 	 */
3179ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
3180ccd2506bSTheodore Ts'o }
3181ac27a0ecSDave Kleikamp 
3182ac27a0ecSDave Kleikamp /*
3183ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
3184ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
3185ac27a0ecSDave Kleikamp  *
3186ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
3187ac27a0ecSDave Kleikamp  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3188ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
3189ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
3190ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
3191ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
3192ac27a0ecSDave Kleikamp  *
3193ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
3194ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
3195ac27a0ecSDave Kleikamp  */
3196ac27a0ecSDave Kleikamp static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3197ac27a0ecSDave Kleikamp {
3198ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
3199ac27a0ecSDave Kleikamp 	journal_t *journal;
320051ae846cSYe Bin 	sector_t ret = 0;
3201ac27a0ecSDave Kleikamp 	int err;
3202ac27a0ecSDave Kleikamp 
320351ae846cSYe Bin 	inode_lock_shared(inode);
320446c7f254STao Ma 	/*
320546c7f254STao Ma 	 * We can get here for an inline file via the FIBMAP ioctl
320646c7f254STao Ma 	 */
320746c7f254STao Ma 	if (ext4_has_inline_data(inode))
320851ae846cSYe Bin 		goto out;
320946c7f254STao Ma 
3210ac27a0ecSDave Kleikamp 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3211ac27a0ecSDave Kleikamp 			test_opt(inode->i_sb, DELALLOC)) {
3212ac27a0ecSDave Kleikamp 		/*
3213ac27a0ecSDave Kleikamp 		 * With delalloc we want to sync the file
3214ac27a0ecSDave Kleikamp 		 * so that we can make sure we allocate
3215ac27a0ecSDave Kleikamp 		 * blocks for file
3216ac27a0ecSDave Kleikamp 		 */
3217ac27a0ecSDave Kleikamp 		filemap_write_and_wait(mapping);
3218ac27a0ecSDave Kleikamp 	}
3219ac27a0ecSDave Kleikamp 
322019f5fb7aSTheodore Ts'o 	if (EXT4_JOURNAL(inode) &&
322119f5fb7aSTheodore Ts'o 	    ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3222ac27a0ecSDave Kleikamp 		/*
3223ac27a0ecSDave Kleikamp 		 * This is a REALLY heavyweight approach, but the use of
3224ac27a0ecSDave Kleikamp 		 * bmap on dirty files is expected to be extremely rare:
3225ac27a0ecSDave Kleikamp 		 * only if we run lilo or swapon on a freshly made file
3226ac27a0ecSDave Kleikamp 		 * do we expect this to happen.
3227ac27a0ecSDave Kleikamp 		 *
3228ac27a0ecSDave Kleikamp 		 * (bmap requires CAP_SYS_RAWIO so this does not
3229ac27a0ecSDave Kleikamp 		 * represent an unprivileged user DOS attack --- we'd be
3230ac27a0ecSDave Kleikamp 		 * in trouble if mortal users could trigger this path at
3231ac27a0ecSDave Kleikamp 		 * will.)
3232ac27a0ecSDave Kleikamp 		 *
3233ac27a0ecSDave Kleikamp 		 * NB. EXT4_STATE_JDATA is not set on files other than
3234ac27a0ecSDave Kleikamp 		 * regular files.  If somebody wants to bmap a directory
3235ac27a0ecSDave Kleikamp 		 * or symlink and gets confused because the buffer
3236ac27a0ecSDave Kleikamp 		 * hasn't yet been flushed to disk, they deserve
3237ac27a0ecSDave Kleikamp 		 * everything they get.
3238ac27a0ecSDave Kleikamp 		 */
3239ac27a0ecSDave Kleikamp 
324019f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3241ac27a0ecSDave Kleikamp 		journal = EXT4_JOURNAL(inode);
3242ac27a0ecSDave Kleikamp 		jbd2_journal_lock_updates(journal);
324301d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
3244ac27a0ecSDave Kleikamp 		jbd2_journal_unlock_updates(journal);
3245ac27a0ecSDave Kleikamp 
3246ac27a0ecSDave Kleikamp 		if (err)
324751ae846cSYe Bin 			goto out;
3248ac27a0ecSDave Kleikamp 	}
3249ac27a0ecSDave Kleikamp 
325051ae846cSYe Bin 	ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
325151ae846cSYe Bin 
325251ae846cSYe Bin out:
325351ae846cSYe Bin 	inode_unlock_shared(inode);
325451ae846cSYe Bin 	return ret;
3255ac27a0ecSDave Kleikamp }
3256ac27a0ecSDave Kleikamp 
3257fe5ddf6bSMatthew Wilcox (Oracle) static int ext4_read_folio(struct file *file, struct folio *folio)
3258ac27a0ecSDave Kleikamp {
3259fe5ddf6bSMatthew Wilcox (Oracle) 	struct page *page = &folio->page;
326046c7f254STao Ma 	int ret = -EAGAIN;
326146c7f254STao Ma 	struct inode *inode = page->mapping->host;
326246c7f254STao Ma 
32630562e0baSJiaying Zhang 	trace_ext4_readpage(page);
326446c7f254STao Ma 
326546c7f254STao Ma 	if (ext4_has_inline_data(inode))
326646c7f254STao Ma 		ret = ext4_readpage_inline(inode, page);
326746c7f254STao Ma 
326846c7f254STao Ma 	if (ret == -EAGAIN)
3269a07f624bSMatthew Wilcox (Oracle) 		return ext4_mpage_readpages(inode, NULL, page);
327046c7f254STao Ma 
327146c7f254STao Ma 	return ret;
3272ac27a0ecSDave Kleikamp }
3273ac27a0ecSDave Kleikamp 
32746311f91fSMatthew Wilcox (Oracle) static void ext4_readahead(struct readahead_control *rac)
3275ac27a0ecSDave Kleikamp {
32766311f91fSMatthew Wilcox (Oracle) 	struct inode *inode = rac->mapping->host;
327746c7f254STao Ma 
32786311f91fSMatthew Wilcox (Oracle) 	/* If the file has inline data, no need to do readahead. */
327946c7f254STao Ma 	if (ext4_has_inline_data(inode))
32806311f91fSMatthew Wilcox (Oracle) 		return;
328146c7f254STao Ma 
3282a07f624bSMatthew Wilcox (Oracle) 	ext4_mpage_readpages(inode, rac, NULL);
3283ac27a0ecSDave Kleikamp }
3284ac27a0ecSDave Kleikamp 
32857ba13abbSMatthew Wilcox (Oracle) static void ext4_invalidate_folio(struct folio *folio, size_t offset,
32867ba13abbSMatthew Wilcox (Oracle) 				size_t length)
3287ac27a0ecSDave Kleikamp {
3288ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_invalidate_folio(folio, offset, length);
32890562e0baSJiaying Zhang 
32904520fb3cSJan Kara 	/* No journalling happens on data buffers when this function is used */
32917ba13abbSMatthew Wilcox (Oracle) 	WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
32924520fb3cSJan Kara 
32937ba13abbSMatthew Wilcox (Oracle) 	block_invalidate_folio(folio, offset, length);
32944520fb3cSJan Kara }
32954520fb3cSJan Kara 
3296ccd16945SMatthew Wilcox (Oracle) static int __ext4_journalled_invalidate_folio(struct folio *folio,
3297ccd16945SMatthew Wilcox (Oracle) 					    size_t offset, size_t length)
32984520fb3cSJan Kara {
3299ccd16945SMatthew Wilcox (Oracle) 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
33004520fb3cSJan Kara 
3301ccd16945SMatthew Wilcox (Oracle) 	trace_ext4_journalled_invalidate_folio(folio, offset, length);
33024520fb3cSJan Kara 
3303744692dcSJiaying Zhang 	/*
3304ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
3305ac27a0ecSDave Kleikamp 	 */
3306ccd16945SMatthew Wilcox (Oracle) 	if (offset == 0 && length == folio_size(folio))
3307ccd16945SMatthew Wilcox (Oracle) 		folio_clear_checked(folio);
3308ac27a0ecSDave Kleikamp 
3309ccd16945SMatthew Wilcox (Oracle) 	return jbd2_journal_invalidate_folio(journal, folio, offset, length);
331053e87268SJan Kara }
331153e87268SJan Kara 
331253e87268SJan Kara /* Wrapper for aops... */
3313ccd16945SMatthew Wilcox (Oracle) static void ext4_journalled_invalidate_folio(struct folio *folio,
3314ccd16945SMatthew Wilcox (Oracle) 					   size_t offset,
3315ccd16945SMatthew Wilcox (Oracle) 					   size_t length)
331653e87268SJan Kara {
3317ccd16945SMatthew Wilcox (Oracle) 	WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3318ac27a0ecSDave Kleikamp }
3319ac27a0ecSDave Kleikamp 
33203c402f15SMatthew Wilcox (Oracle) static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3321ac27a0ecSDave Kleikamp {
33223c402f15SMatthew Wilcox (Oracle) 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
3323ac27a0ecSDave Kleikamp 
33243c402f15SMatthew Wilcox (Oracle) 	trace_ext4_releasepage(&folio->page);
33250562e0baSJiaying Zhang 
3326e1c36595SJan Kara 	/* Page has dirty journalled data -> cannot release */
33273c402f15SMatthew Wilcox (Oracle) 	if (folio_test_checked(folio))
33283c402f15SMatthew Wilcox (Oracle) 		return false;
33290390131bSFrank Mayhar 	if (journal)
3330c56a6eb0SMatthew Wilcox (Oracle) 		return jbd2_journal_try_to_free_buffers(journal, folio);
33310390131bSFrank Mayhar 	else
333268189fefSMatthew Wilcox (Oracle) 		return try_to_free_buffers(folio);
3333ac27a0ecSDave Kleikamp }
3334ac27a0ecSDave Kleikamp 
3335b8a6176cSJan Kara static bool ext4_inode_datasync_dirty(struct inode *inode)
3336b8a6176cSJan Kara {
3337b8a6176cSJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3338b8a6176cSJan Kara 
3339aa75f4d3SHarshad Shirwadkar 	if (journal) {
3340aa75f4d3SHarshad Shirwadkar 		if (jbd2_transaction_committed(journal,
3341aa75f4d3SHarshad Shirwadkar 			EXT4_I(inode)->i_datasync_tid))
3342d0520df7SAndrea Righi 			return false;
3343d0520df7SAndrea Righi 		if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
33441ceecb53SHarshad Shirwadkar 			return !list_empty(&EXT4_I(inode)->i_fc_list);
3345d0520df7SAndrea Righi 		return true;
3346aa75f4d3SHarshad Shirwadkar 	}
3347aa75f4d3SHarshad Shirwadkar 
3348b8a6176cSJan Kara 	/* Any metadata buffers to write? */
3349b8a6176cSJan Kara 	if (!list_empty(&inode->i_mapping->private_list))
3350b8a6176cSJan Kara 		return true;
3351b8a6176cSJan Kara 	return inode->i_state & I_DIRTY_DATASYNC;
3352b8a6176cSJan Kara }
3353b8a6176cSJan Kara 
3354c8fdfe29SMatthew Bobrowski static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3355c8fdfe29SMatthew Bobrowski 			   struct ext4_map_blocks *map, loff_t offset,
3356de205114SChristoph Hellwig 			   loff_t length, unsigned int flags)
3357364443cbSJan Kara {
3358c8fdfe29SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3359c8fdfe29SMatthew Bobrowski 
3360c8fdfe29SMatthew Bobrowski 	/*
3361c8fdfe29SMatthew Bobrowski 	 * Writes that span EOF might trigger an I/O size update on completion,
3362c8fdfe29SMatthew Bobrowski 	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3363c8fdfe29SMatthew Bobrowski 	 * there is no other metadata changes being made or are pending.
3364c8fdfe29SMatthew Bobrowski 	 */
3365c8fdfe29SMatthew Bobrowski 	iomap->flags = 0;
3366c8fdfe29SMatthew Bobrowski 	if (ext4_inode_datasync_dirty(inode) ||
3367c8fdfe29SMatthew Bobrowski 	    offset + length > i_size_read(inode))
3368c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_DIRTY;
3369c8fdfe29SMatthew Bobrowski 
3370c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_NEW)
3371c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_NEW;
3372c8fdfe29SMatthew Bobrowski 
3373de205114SChristoph Hellwig 	if (flags & IOMAP_DAX)
3374c8fdfe29SMatthew Bobrowski 		iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3375de205114SChristoph Hellwig 	else
3376de205114SChristoph Hellwig 		iomap->bdev = inode->i_sb->s_bdev;
3377c8fdfe29SMatthew Bobrowski 	iomap->offset = (u64) map->m_lblk << blkbits;
3378c8fdfe29SMatthew Bobrowski 	iomap->length = (u64) map->m_len << blkbits;
3379c8fdfe29SMatthew Bobrowski 
33806386722aSRitesh Harjani 	if ((map->m_flags & EXT4_MAP_MAPPED) &&
33816386722aSRitesh Harjani 	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
33826386722aSRitesh Harjani 		iomap->flags |= IOMAP_F_MERGED;
33836386722aSRitesh Harjani 
3384c8fdfe29SMatthew Bobrowski 	/*
3385c8fdfe29SMatthew Bobrowski 	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3386c8fdfe29SMatthew Bobrowski 	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3387c8fdfe29SMatthew Bobrowski 	 * set. In order for any allocated unwritten extents to be converted
3388c8fdfe29SMatthew Bobrowski 	 * into written extents correctly within the ->end_io() handler, we
3389c8fdfe29SMatthew Bobrowski 	 * need to ensure that the iomap->type is set appropriately. Hence, the
3390c8fdfe29SMatthew Bobrowski 	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3391c8fdfe29SMatthew Bobrowski 	 * been set first.
3392c8fdfe29SMatthew Bobrowski 	 */
3393c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3394c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_UNWRITTEN;
3395c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3396de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3397de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3398c8fdfe29SMatthew Bobrowski 	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3399c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_MAPPED;
3400c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3401de205114SChristoph Hellwig 		if (flags & IOMAP_DAX)
3402de205114SChristoph Hellwig 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3403c8fdfe29SMatthew Bobrowski 	} else {
3404c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_HOLE;
3405c8fdfe29SMatthew Bobrowski 		iomap->addr = IOMAP_NULL_ADDR;
3406c8fdfe29SMatthew Bobrowski 	}
3407c8fdfe29SMatthew Bobrowski }
3408c8fdfe29SMatthew Bobrowski 
3409f063db5eSMatthew Bobrowski static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3410f063db5eSMatthew Bobrowski 			    unsigned int flags)
3411f063db5eSMatthew Bobrowski {
3412f063db5eSMatthew Bobrowski 	handle_t *handle;
3413378f32baSMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3414378f32baSMatthew Bobrowski 	int ret, dio_credits, m_flags = 0, retries = 0;
3415f063db5eSMatthew Bobrowski 
3416f063db5eSMatthew Bobrowski 	/*
3417f063db5eSMatthew Bobrowski 	 * Trim the mapping request to the maximum value that we can map at
3418f063db5eSMatthew Bobrowski 	 * once for direct I/O.
3419f063db5eSMatthew Bobrowski 	 */
3420f063db5eSMatthew Bobrowski 	if (map->m_len > DIO_MAX_BLOCKS)
3421f063db5eSMatthew Bobrowski 		map->m_len = DIO_MAX_BLOCKS;
3422f063db5eSMatthew Bobrowski 	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3423f063db5eSMatthew Bobrowski 
3424f063db5eSMatthew Bobrowski retry:
3425f063db5eSMatthew Bobrowski 	/*
3426f063db5eSMatthew Bobrowski 	 * Either we allocate blocks and then don't get an unwritten extent, so
3427f063db5eSMatthew Bobrowski 	 * in that case we have reserved enough credits. Or, the blocks are
3428f063db5eSMatthew Bobrowski 	 * already allocated and unwritten. In that case, the extent conversion
3429f063db5eSMatthew Bobrowski 	 * fits into the credits as well.
3430f063db5eSMatthew Bobrowski 	 */
3431f063db5eSMatthew Bobrowski 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3432f063db5eSMatthew Bobrowski 	if (IS_ERR(handle))
3433f063db5eSMatthew Bobrowski 		return PTR_ERR(handle);
3434f063db5eSMatthew Bobrowski 
3435378f32baSMatthew Bobrowski 	/*
3436378f32baSMatthew Bobrowski 	 * DAX and direct I/O are the only two operations that are currently
3437378f32baSMatthew Bobrowski 	 * supported with IOMAP_WRITE.
3438378f32baSMatthew Bobrowski 	 */
3439952da063SChristoph Hellwig 	WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3440952da063SChristoph Hellwig 	if (flags & IOMAP_DAX)
3441378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3442378f32baSMatthew Bobrowski 	/*
3443378f32baSMatthew Bobrowski 	 * We use i_size instead of i_disksize here because delalloc writeback
3444378f32baSMatthew Bobrowski 	 * can complete at any point during the I/O and subsequently push the
3445378f32baSMatthew Bobrowski 	 * i_disksize out to i_size. This could be beyond where direct I/O is
3446378f32baSMatthew Bobrowski 	 * happening and thus expose allocated blocks to direct I/O reads.
3447378f32baSMatthew Bobrowski 	 */
3448d0b040f5SJan Kara 	else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3449378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE;
3450378f32baSMatthew Bobrowski 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3451378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3452378f32baSMatthew Bobrowski 
3453378f32baSMatthew Bobrowski 	ret = ext4_map_blocks(handle, inode, map, m_flags);
3454378f32baSMatthew Bobrowski 
3455378f32baSMatthew Bobrowski 	/*
3456378f32baSMatthew Bobrowski 	 * We cannot fill holes in indirect tree based inodes as that could
3457378f32baSMatthew Bobrowski 	 * expose stale data in the case of a crash. Use the magic error code
3458378f32baSMatthew Bobrowski 	 * to fallback to buffered I/O.
3459378f32baSMatthew Bobrowski 	 */
3460378f32baSMatthew Bobrowski 	if (!m_flags && !ret)
3461378f32baSMatthew Bobrowski 		ret = -ENOTBLK;
3462f063db5eSMatthew Bobrowski 
3463f063db5eSMatthew Bobrowski 	ext4_journal_stop(handle);
3464f063db5eSMatthew Bobrowski 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3465f063db5eSMatthew Bobrowski 		goto retry;
3466f063db5eSMatthew Bobrowski 
3467f063db5eSMatthew Bobrowski 	return ret;
3468f063db5eSMatthew Bobrowski }
3469f063db5eSMatthew Bobrowski 
3470f063db5eSMatthew Bobrowski 
3471364443cbSJan Kara static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3472c039b997SGoldwyn Rodrigues 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3473364443cbSJan Kara {
3474364443cbSJan Kara 	int ret;
347509edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
347609edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3477364443cbSJan Kara 
3478bcd8e91fSTheodore Ts'o 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3479bcd8e91fSTheodore Ts'o 		return -EINVAL;
34807046ae35SAndreas Gruenbacher 
3481364443cbSJan Kara 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3482364443cbSJan Kara 		return -ERANGE;
3483364443cbSJan Kara 
348409edf4d3SMatthew Bobrowski 	/*
348509edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical blocks respectively.
348609edf4d3SMatthew Bobrowski 	 */
348709edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
348809edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
348909edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3490364443cbSJan Kara 
34919faac62dSRitesh Harjani 	if (flags & IOMAP_WRITE) {
34929faac62dSRitesh Harjani 		/*
34939faac62dSRitesh Harjani 		 * We check here if the blocks are already allocated, then we
34949faac62dSRitesh Harjani 		 * don't need to start a journal txn and we can directly return
34959faac62dSRitesh Harjani 		 * the mapping information. This could boost performance
34969faac62dSRitesh Harjani 		 * especially in multi-threaded overwrite requests.
34979faac62dSRitesh Harjani 		 */
34989faac62dSRitesh Harjani 		if (offset + length <= i_size_read(inode)) {
3499545052e9SChristoph Hellwig 			ret = ext4_map_blocks(NULL, inode, &map, 0);
35009faac62dSRitesh Harjani 			if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
35019faac62dSRitesh Harjani 				goto out;
35029faac62dSRitesh Harjani 		}
35039faac62dSRitesh Harjani 		ret = ext4_iomap_alloc(inode, &map, flags);
35049faac62dSRitesh Harjani 	} else {
35059faac62dSRitesh Harjani 		ret = ext4_map_blocks(NULL, inode, &map, 0);
35069faac62dSRitesh Harjani 	}
3507f063db5eSMatthew Bobrowski 
3508545052e9SChristoph Hellwig 	if (ret < 0)
3509545052e9SChristoph Hellwig 		return ret;
35109faac62dSRitesh Harjani out:
351138ea50daSEric Biggers 	/*
351238ea50daSEric Biggers 	 * When inline encryption is enabled, sometimes I/O to an encrypted file
351338ea50daSEric Biggers 	 * has to be broken up to guarantee DUN contiguity.  Handle this by
351438ea50daSEric Biggers 	 * limiting the length of the mapping returned.
351538ea50daSEric Biggers 	 */
351638ea50daSEric Biggers 	map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
351738ea50daSEric Biggers 
3518de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3519545052e9SChristoph Hellwig 
3520364443cbSJan Kara 	return 0;
3521364443cbSJan Kara }
3522364443cbSJan Kara 
35238cd115bdSJan Kara static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
35248cd115bdSJan Kara 		loff_t length, unsigned flags, struct iomap *iomap,
35258cd115bdSJan Kara 		struct iomap *srcmap)
35268cd115bdSJan Kara {
35278cd115bdSJan Kara 	int ret;
35288cd115bdSJan Kara 
35298cd115bdSJan Kara 	/*
35308cd115bdSJan Kara 	 * Even for writes we don't need to allocate blocks, so just pretend
35318cd115bdSJan Kara 	 * we are reading to save overhead of starting a transaction.
35328cd115bdSJan Kara 	 */
35338cd115bdSJan Kara 	flags &= ~IOMAP_WRITE;
35348cd115bdSJan Kara 	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
35358cd115bdSJan Kara 	WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
35368cd115bdSJan Kara 	return ret;
35378cd115bdSJan Kara }
35388cd115bdSJan Kara 
3539776722e8SJan Kara static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3540776722e8SJan Kara 			  ssize_t written, unsigned flags, struct iomap *iomap)
3541776722e8SJan Kara {
3542378f32baSMatthew Bobrowski 	/*
3543378f32baSMatthew Bobrowski 	 * Check to see whether an error occurred while writing out the data to
3544378f32baSMatthew Bobrowski 	 * the allocated blocks. If so, return the magic error code so that we
3545378f32baSMatthew Bobrowski 	 * fallback to buffered I/O and attempt to complete the remainder of
3546378f32baSMatthew Bobrowski 	 * the I/O. Any blocks that may have been allocated in preparation for
3547378f32baSMatthew Bobrowski 	 * the direct I/O will be reused during buffered I/O.
3548378f32baSMatthew Bobrowski 	 */
3549378f32baSMatthew Bobrowski 	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3550378f32baSMatthew Bobrowski 		return -ENOTBLK;
3551378f32baSMatthew Bobrowski 
3552776722e8SJan Kara 	return 0;
3553776722e8SJan Kara }
3554776722e8SJan Kara 
35558ff6daa1SChristoph Hellwig const struct iomap_ops ext4_iomap_ops = {
3556364443cbSJan Kara 	.iomap_begin		= ext4_iomap_begin,
3557776722e8SJan Kara 	.iomap_end		= ext4_iomap_end,
3558364443cbSJan Kara };
3559364443cbSJan Kara 
35608cd115bdSJan Kara const struct iomap_ops ext4_iomap_overwrite_ops = {
35618cd115bdSJan Kara 	.iomap_begin		= ext4_iomap_overwrite_begin,
35628cd115bdSJan Kara 	.iomap_end		= ext4_iomap_end,
35638cd115bdSJan Kara };
35648cd115bdSJan Kara 
356509edf4d3SMatthew Bobrowski static bool ext4_iomap_is_delalloc(struct inode *inode,
356609edf4d3SMatthew Bobrowski 				   struct ext4_map_blocks *map)
356709edf4d3SMatthew Bobrowski {
356809edf4d3SMatthew Bobrowski 	struct extent_status es;
356909edf4d3SMatthew Bobrowski 	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
357009edf4d3SMatthew Bobrowski 
357109edf4d3SMatthew Bobrowski 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
357209edf4d3SMatthew Bobrowski 				  map->m_lblk, end, &es);
357309edf4d3SMatthew Bobrowski 
357409edf4d3SMatthew Bobrowski 	if (!es.es_len || es.es_lblk > end)
357509edf4d3SMatthew Bobrowski 		return false;
357609edf4d3SMatthew Bobrowski 
357709edf4d3SMatthew Bobrowski 	if (es.es_lblk > map->m_lblk) {
357809edf4d3SMatthew Bobrowski 		map->m_len = es.es_lblk - map->m_lblk;
357909edf4d3SMatthew Bobrowski 		return false;
358009edf4d3SMatthew Bobrowski 	}
358109edf4d3SMatthew Bobrowski 
358209edf4d3SMatthew Bobrowski 	offset = map->m_lblk - es.es_lblk;
358309edf4d3SMatthew Bobrowski 	map->m_len = es.es_len - offset;
358409edf4d3SMatthew Bobrowski 
358509edf4d3SMatthew Bobrowski 	return true;
358609edf4d3SMatthew Bobrowski }
358709edf4d3SMatthew Bobrowski 
358809edf4d3SMatthew Bobrowski static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
358909edf4d3SMatthew Bobrowski 				   loff_t length, unsigned int flags,
359009edf4d3SMatthew Bobrowski 				   struct iomap *iomap, struct iomap *srcmap)
359109edf4d3SMatthew Bobrowski {
359209edf4d3SMatthew Bobrowski 	int ret;
359309edf4d3SMatthew Bobrowski 	bool delalloc = false;
359409edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
359509edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
359609edf4d3SMatthew Bobrowski 
359709edf4d3SMatthew Bobrowski 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
359809edf4d3SMatthew Bobrowski 		return -EINVAL;
359909edf4d3SMatthew Bobrowski 
36007cb476f8SJan Kara 	if (ext4_has_inline_data(inode)) {
36017cb476f8SJan Kara 		ret = ext4_inline_data_iomap(inode, iomap);
3602ba5843f5SJan Kara 		if (ret != -EAGAIN) {
3603ed923b57SMatthew Wilcox 			if (ret == 0 && offset >= iomap->length)
3604ba5843f5SJan Kara 				ret = -ENOENT;
3605ba5843f5SJan Kara 			return ret;
3606ba5843f5SJan Kara 		}
3607ba5843f5SJan Kara 	}
360812735f88SJan Kara 
360909edf4d3SMatthew Bobrowski 	/*
361009edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical block respectively.
361109edf4d3SMatthew Bobrowski 	 */
361209edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
361309edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
361409edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
361512735f88SJan Kara 
3616b2c57642SRitesh Harjani 	/*
3617b2c57642SRitesh Harjani 	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3618b2c57642SRitesh Harjani 	 * So handle it here itself instead of querying ext4_map_blocks().
3619b2c57642SRitesh Harjani 	 * Since ext4_map_blocks() will warn about it and will return
3620b2c57642SRitesh Harjani 	 * -EIO error.
3621b2c57642SRitesh Harjani 	 */
3622b2c57642SRitesh Harjani 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3623b2c57642SRitesh Harjani 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3624b2c57642SRitesh Harjani 
3625b2c57642SRitesh Harjani 		if (offset >= sbi->s_bitmap_maxbytes) {
3626b2c57642SRitesh Harjani 			map.m_flags = 0;
3627b2c57642SRitesh Harjani 			goto set_iomap;
3628b2c57642SRitesh Harjani 		}
3629b2c57642SRitesh Harjani 	}
3630b2c57642SRitesh Harjani 
363112735f88SJan Kara 	ret = ext4_map_blocks(NULL, inode, &map, 0);
3632ba5843f5SJan Kara 	if (ret < 0)
3633ba5843f5SJan Kara 		return ret;
3634914f82a3SJan Kara 	if (ret == 0)
363509edf4d3SMatthew Bobrowski 		delalloc = ext4_iomap_is_delalloc(inode, &map);
363609edf4d3SMatthew Bobrowski 
3637b2c57642SRitesh Harjani set_iomap:
3638de205114SChristoph Hellwig 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
363909edf4d3SMatthew Bobrowski 	if (delalloc && iomap->type == IOMAP_HOLE)
364009edf4d3SMatthew Bobrowski 		iomap->type = IOMAP_DELALLOC;
364109edf4d3SMatthew Bobrowski 
364209edf4d3SMatthew Bobrowski 	return 0;
3643914f82a3SJan Kara }
3644914f82a3SJan Kara 
364509edf4d3SMatthew Bobrowski const struct iomap_ops ext4_iomap_report_ops = {
364609edf4d3SMatthew Bobrowski 	.iomap_begin = ext4_iomap_begin_report,
364709edf4d3SMatthew Bobrowski };
36484c0425ffSMingming Cao 
3649ac27a0ecSDave Kleikamp /*
36506b1f86f8SLinus Torvalds  * Whenever the folio is being dirtied, corresponding buffers should already
36516b1f86f8SLinus Torvalds  * be attached to the transaction (we take care of this in ext4_page_mkwrite()
36526b1f86f8SLinus Torvalds  * and ext4_write_begin()). However we cannot move buffers to dirty transaction
36536b1f86f8SLinus Torvalds  * lists here because ->dirty_folio is called under VFS locks and the folio
36542bb8dd40SJan Kara  * is not necessarily locked.
3655ac27a0ecSDave Kleikamp  *
3656187c82cbSMatthew Wilcox (Oracle)  * We cannot just dirty the folio and leave attached buffers clean, because the
3657ac27a0ecSDave Kleikamp  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3658ac27a0ecSDave Kleikamp  * or jbddirty because all the journalling code will explode.
3659ac27a0ecSDave Kleikamp  *
3660187c82cbSMatthew Wilcox (Oracle)  * So what we do is to mark the folio "pending dirty" and next time writepage
3661ac27a0ecSDave Kleikamp  * is called, propagate that into the buffers appropriately.
3662ac27a0ecSDave Kleikamp  */
3663187c82cbSMatthew Wilcox (Oracle) static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3664187c82cbSMatthew Wilcox (Oracle) 		struct folio *folio)
3665ac27a0ecSDave Kleikamp {
36660f252336SMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
3667187c82cbSMatthew Wilcox (Oracle) 	folio_set_checked(folio);
3668187c82cbSMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
3669ac27a0ecSDave Kleikamp }
3670ac27a0ecSDave Kleikamp 
3671e621900aSMatthew Wilcox (Oracle) static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
36726dcc693bSJan Kara {
3673e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3674e621900aSMatthew Wilcox (Oracle) 	WARN_ON_ONCE(!folio_buffers(folio));
3675e621900aSMatthew Wilcox (Oracle) 	return block_dirty_folio(mapping, folio);
36766dcc693bSJan Kara }
36776dcc693bSJan Kara 
36780e6895baSRitesh Harjani static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
36790e6895baSRitesh Harjani 				    struct file *file, sector_t *span)
36800e6895baSRitesh Harjani {
36810e6895baSRitesh Harjani 	return iomap_swapfile_activate(sis, file, span,
36820e6895baSRitesh Harjani 				       &ext4_iomap_report_ops);
36830e6895baSRitesh Harjani }
36840e6895baSRitesh Harjani 
368574d553aaSTheodore Ts'o static const struct address_space_operations ext4_aops = {
3686fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
36876311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
368843ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
368920970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3690bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
369174d553aaSTheodore Ts'o 	.write_end		= ext4_write_end,
3692e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
3693617ba13bSMingming Cao 	.bmap			= ext4_bmap,
36947ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
36953c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3696378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
369767235182SMatthew Wilcox (Oracle) 	.migrate_folio		= buffer_migrate_folio,
36988ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3699aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
37000e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3701ac27a0ecSDave Kleikamp };
3702ac27a0ecSDave Kleikamp 
3703617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
3704fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
37056311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
370643ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
370720970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3708bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
3709bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
3710187c82cbSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_journalled_dirty_folio,
3711617ba13bSMingming Cao 	.bmap			= ext4_bmap,
3712ccd16945SMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_journalled_invalidate_folio,
37133c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3714378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
37158ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3716aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
37170e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3718ac27a0ecSDave Kleikamp };
3719ac27a0ecSDave Kleikamp 
372064769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
3721fe5ddf6bSMatthew Wilcox (Oracle) 	.read_folio		= ext4_read_folio,
37226311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
372343ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
372420970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
372564769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
372664769240SAlex Tomas 	.write_end		= ext4_da_write_end,
3727e621900aSMatthew Wilcox (Oracle) 	.dirty_folio		= ext4_dirty_folio,
372864769240SAlex Tomas 	.bmap			= ext4_bmap,
37297ba13abbSMatthew Wilcox (Oracle) 	.invalidate_folio	= ext4_invalidate_folio,
37303c402f15SMatthew Wilcox (Oracle) 	.release_folio		= ext4_release_folio,
3731378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
373267235182SMatthew Wilcox (Oracle) 	.migrate_folio		= buffer_migrate_folio,
37338ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3734aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
37350e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
373664769240SAlex Tomas };
373764769240SAlex Tomas 
37385f0663bbSDan Williams static const struct address_space_operations ext4_dax_aops = {
37395f0663bbSDan Williams 	.writepages		= ext4_dax_writepages,
37405f0663bbSDan Williams 	.direct_IO		= noop_direct_IO,
374146de8b97SMatthew Wilcox (Oracle) 	.dirty_folio		= noop_dirty_folio,
374294dbb631SToshi Kani 	.bmap			= ext4_bmap,
37430e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
37445f0663bbSDan Williams };
37455f0663bbSDan Williams 
3746617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
3747ac27a0ecSDave Kleikamp {
37483d2b1582SLukas Czerner 	switch (ext4_inode_journal_mode(inode)) {
37493d2b1582SLukas Czerner 	case EXT4_INODE_ORDERED_DATA_MODE:
37503d2b1582SLukas Czerner 	case EXT4_INODE_WRITEBACK_DATA_MODE:
37513d2b1582SLukas Czerner 		break;
37523d2b1582SLukas Czerner 	case EXT4_INODE_JOURNAL_DATA_MODE:
3753617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
375474d553aaSTheodore Ts'o 		return;
37553d2b1582SLukas Czerner 	default:
37563d2b1582SLukas Czerner 		BUG();
37573d2b1582SLukas Czerner 	}
37585f0663bbSDan Williams 	if (IS_DAX(inode))
37595f0663bbSDan Williams 		inode->i_mapping->a_ops = &ext4_dax_aops;
37605f0663bbSDan Williams 	else if (test_opt(inode->i_sb, DELALLOC))
376174d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_da_aops;
376274d553aaSTheodore Ts'o 	else
376374d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_aops;
3764ac27a0ecSDave Kleikamp }
3765ac27a0ecSDave Kleikamp 
3766923ae0ffSRoss Zwisler static int __ext4_block_zero_page_range(handle_t *handle,
3767d863dc36SLukas Czerner 		struct address_space *mapping, loff_t from, loff_t length)
3768d863dc36SLukas Czerner {
376909cbfeafSKirill A. Shutemov 	ext4_fsblk_t index = from >> PAGE_SHIFT;
377009cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3771923ae0ffSRoss Zwisler 	unsigned blocksize, pos;
3772d863dc36SLukas Czerner 	ext4_lblk_t iblock;
3773d863dc36SLukas Czerner 	struct inode *inode = mapping->host;
3774d863dc36SLukas Czerner 	struct buffer_head *bh;
3775d863dc36SLukas Czerner 	struct page *page;
3776d863dc36SLukas Czerner 	int err = 0;
3777d863dc36SLukas Czerner 
377809cbfeafSKirill A. Shutemov 	page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3779c62d2555SMichal Hocko 				   mapping_gfp_constraint(mapping, ~__GFP_FS));
3780d863dc36SLukas Czerner 	if (!page)
3781d863dc36SLukas Czerner 		return -ENOMEM;
3782d863dc36SLukas Czerner 
3783d863dc36SLukas Czerner 	blocksize = inode->i_sb->s_blocksize;
3784d863dc36SLukas Czerner 
378509cbfeafSKirill A. Shutemov 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3786d863dc36SLukas Czerner 
3787d863dc36SLukas Czerner 	if (!page_has_buffers(page))
3788d863dc36SLukas Czerner 		create_empty_buffers(page, blocksize, 0);
3789d863dc36SLukas Czerner 
3790d863dc36SLukas Czerner 	/* Find the buffer that contains "offset" */
3791d863dc36SLukas Czerner 	bh = page_buffers(page);
3792d863dc36SLukas Czerner 	pos = blocksize;
3793d863dc36SLukas Czerner 	while (offset >= pos) {
3794d863dc36SLukas Czerner 		bh = bh->b_this_page;
3795d863dc36SLukas Czerner 		iblock++;
3796d863dc36SLukas Czerner 		pos += blocksize;
3797d863dc36SLukas Czerner 	}
3798d863dc36SLukas Czerner 	if (buffer_freed(bh)) {
3799d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "freed: skip");
3800d863dc36SLukas Czerner 		goto unlock;
3801d863dc36SLukas Czerner 	}
3802d863dc36SLukas Czerner 	if (!buffer_mapped(bh)) {
3803d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "unmapped");
3804d863dc36SLukas Czerner 		ext4_get_block(inode, iblock, bh, 0);
3805d863dc36SLukas Czerner 		/* unmapped? It's a hole - nothing to do */
3806d863dc36SLukas Czerner 		if (!buffer_mapped(bh)) {
3807d863dc36SLukas Czerner 			BUFFER_TRACE(bh, "still unmapped");
3808d863dc36SLukas Czerner 			goto unlock;
3809d863dc36SLukas Czerner 		}
3810d863dc36SLukas Czerner 	}
3811d863dc36SLukas Czerner 
3812d863dc36SLukas Czerner 	/* Ok, it's mapped. Make sure it's up-to-date */
3813d863dc36SLukas Czerner 	if (PageUptodate(page))
3814d863dc36SLukas Czerner 		set_buffer_uptodate(bh);
3815d863dc36SLukas Czerner 
3816d863dc36SLukas Czerner 	if (!buffer_uptodate(bh)) {
38172d069c08Szhangyi (F) 		err = ext4_read_bh_lock(bh, 0, true);
38182d069c08Szhangyi (F) 		if (err)
3819d863dc36SLukas Czerner 			goto unlock;
38204f74d15fSEric Biggers 		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3821c9c7429cSMichael Halcrow 			/* We expect the key to be set. */
3822a7550b30SJaegeuk Kim 			BUG_ON(!fscrypt_has_encryption_key(inode));
3823834f1565SEric Biggers 			err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3824834f1565SEric Biggers 							       bh_offset(bh));
3825834f1565SEric Biggers 			if (err) {
3826834f1565SEric Biggers 				clear_buffer_uptodate(bh);
3827834f1565SEric Biggers 				goto unlock;
3828834f1565SEric Biggers 			}
3829c9c7429cSMichael Halcrow 		}
3830d863dc36SLukas Czerner 	}
3831d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3832d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "get write access");
3833188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
3834188c299eSJan Kara 						    EXT4_JTR_NONE);
3835d863dc36SLukas Czerner 		if (err)
3836d863dc36SLukas Czerner 			goto unlock;
3837d863dc36SLukas Czerner 	}
3838d863dc36SLukas Czerner 	zero_user(page, offset, length);
3839d863dc36SLukas Czerner 	BUFFER_TRACE(bh, "zeroed end of block");
3840d863dc36SLukas Czerner 
3841d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3842d863dc36SLukas Czerner 		err = ext4_handle_dirty_metadata(handle, inode, bh);
38430713ed0cSLukas Czerner 	} else {
3844353eefd3Sjon ernst 		err = 0;
3845d863dc36SLukas Czerner 		mark_buffer_dirty(bh);
38463957ef53SJan Kara 		if (ext4_should_order_data(inode))
384773131fbbSRoss Zwisler 			err = ext4_jbd2_inode_add_write(handle, inode, from,
384873131fbbSRoss Zwisler 					length);
38490713ed0cSLukas Czerner 	}
3850d863dc36SLukas Czerner 
3851d863dc36SLukas Czerner unlock:
3852d863dc36SLukas Czerner 	unlock_page(page);
385309cbfeafSKirill A. Shutemov 	put_page(page);
3854d863dc36SLukas Czerner 	return err;
3855d863dc36SLukas Czerner }
3856d863dc36SLukas Czerner 
385794350ab5SMatthew Wilcox /*
3858923ae0ffSRoss Zwisler  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3859923ae0ffSRoss Zwisler  * starting from file offset 'from'.  The range to be zero'd must
3860923ae0ffSRoss Zwisler  * be contained with in one block.  If the specified range exceeds
3861923ae0ffSRoss Zwisler  * the end of the block it will be shortened to end of the block
38623088e5a5SBhaskar Chowdhury  * that corresponds to 'from'
3863923ae0ffSRoss Zwisler  */
3864923ae0ffSRoss Zwisler static int ext4_block_zero_page_range(handle_t *handle,
3865923ae0ffSRoss Zwisler 		struct address_space *mapping, loff_t from, loff_t length)
3866923ae0ffSRoss Zwisler {
3867923ae0ffSRoss Zwisler 	struct inode *inode = mapping->host;
386809cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3869923ae0ffSRoss Zwisler 	unsigned blocksize = inode->i_sb->s_blocksize;
3870923ae0ffSRoss Zwisler 	unsigned max = blocksize - (offset & (blocksize - 1));
3871923ae0ffSRoss Zwisler 
3872923ae0ffSRoss Zwisler 	/*
3873923ae0ffSRoss Zwisler 	 * correct length if it does not fall between
3874923ae0ffSRoss Zwisler 	 * 'from' and the end of the block
3875923ae0ffSRoss Zwisler 	 */
3876923ae0ffSRoss Zwisler 	if (length > max || length < 0)
3877923ae0ffSRoss Zwisler 		length = max;
3878923ae0ffSRoss Zwisler 
387947e69351SJan Kara 	if (IS_DAX(inode)) {
3880c6f40468SChristoph Hellwig 		return dax_zero_range(inode, from, length, NULL,
388147e69351SJan Kara 				      &ext4_iomap_ops);
388247e69351SJan Kara 	}
3883923ae0ffSRoss Zwisler 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3884923ae0ffSRoss Zwisler }
3885923ae0ffSRoss Zwisler 
3886923ae0ffSRoss Zwisler /*
388794350ab5SMatthew Wilcox  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
388894350ab5SMatthew Wilcox  * up to the end of the block which corresponds to `from'.
388994350ab5SMatthew Wilcox  * This required during truncate. We need to physically zero the tail end
389094350ab5SMatthew Wilcox  * of that block so it doesn't yield old data if the file is later grown.
389194350ab5SMatthew Wilcox  */
3892c197855eSStephen Hemminger static int ext4_block_truncate_page(handle_t *handle,
389394350ab5SMatthew Wilcox 		struct address_space *mapping, loff_t from)
389494350ab5SMatthew Wilcox {
389509cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
389694350ab5SMatthew Wilcox 	unsigned length;
389794350ab5SMatthew Wilcox 	unsigned blocksize;
389894350ab5SMatthew Wilcox 	struct inode *inode = mapping->host;
389994350ab5SMatthew Wilcox 
39000d06863fSTheodore Ts'o 	/* If we are processing an encrypted inode during orphan list handling */
3901592ddec7SChandan Rajendra 	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
39020d06863fSTheodore Ts'o 		return 0;
39030d06863fSTheodore Ts'o 
390494350ab5SMatthew Wilcox 	blocksize = inode->i_sb->s_blocksize;
390594350ab5SMatthew Wilcox 	length = blocksize - (offset & (blocksize - 1));
390694350ab5SMatthew Wilcox 
390794350ab5SMatthew Wilcox 	return ext4_block_zero_page_range(handle, mapping, from, length);
390894350ab5SMatthew Wilcox }
390994350ab5SMatthew Wilcox 
3910a87dd18cSLukas Czerner int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3911a87dd18cSLukas Czerner 			     loff_t lstart, loff_t length)
3912a87dd18cSLukas Czerner {
3913a87dd18cSLukas Czerner 	struct super_block *sb = inode->i_sb;
3914a87dd18cSLukas Czerner 	struct address_space *mapping = inode->i_mapping;
3915e1be3a92SLukas Czerner 	unsigned partial_start, partial_end;
3916a87dd18cSLukas Czerner 	ext4_fsblk_t start, end;
3917a87dd18cSLukas Czerner 	loff_t byte_end = (lstart + length - 1);
3918a87dd18cSLukas Czerner 	int err = 0;
3919a87dd18cSLukas Czerner 
3920e1be3a92SLukas Czerner 	partial_start = lstart & (sb->s_blocksize - 1);
3921e1be3a92SLukas Czerner 	partial_end = byte_end & (sb->s_blocksize - 1);
3922e1be3a92SLukas Czerner 
3923a87dd18cSLukas Czerner 	start = lstart >> sb->s_blocksize_bits;
3924a87dd18cSLukas Czerner 	end = byte_end >> sb->s_blocksize_bits;
3925a87dd18cSLukas Czerner 
3926a87dd18cSLukas Czerner 	/* Handle partial zero within the single block */
3927e1be3a92SLukas Czerner 	if (start == end &&
3928e1be3a92SLukas Czerner 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3929a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3930a87dd18cSLukas Czerner 						 lstart, length);
3931a87dd18cSLukas Czerner 		return err;
3932a87dd18cSLukas Czerner 	}
3933a87dd18cSLukas Czerner 	/* Handle partial zero out on the start of the range */
3934e1be3a92SLukas Czerner 	if (partial_start) {
3935a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3936a87dd18cSLukas Czerner 						 lstart, sb->s_blocksize);
3937a87dd18cSLukas Czerner 		if (err)
3938a87dd18cSLukas Czerner 			return err;
3939a87dd18cSLukas Czerner 	}
3940a87dd18cSLukas Czerner 	/* Handle partial zero out on the end of the range */
3941e1be3a92SLukas Czerner 	if (partial_end != sb->s_blocksize - 1)
3942a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3943e1be3a92SLukas Czerner 						 byte_end - partial_end,
3944e1be3a92SLukas Czerner 						 partial_end + 1);
3945a87dd18cSLukas Czerner 	return err;
3946a87dd18cSLukas Czerner }
3947a87dd18cSLukas Czerner 
394891ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
394991ef4cafSDuane Griffin {
395091ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
395191ef4cafSDuane Griffin 		return 1;
395291ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
395391ef4cafSDuane Griffin 		return 1;
395491ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
395591ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
395691ef4cafSDuane Griffin 	return 0;
395791ef4cafSDuane Griffin }
395891ef4cafSDuane Griffin 
3959ac27a0ecSDave Kleikamp /*
396001127848SJan Kara  * We have to make sure i_disksize gets properly updated before we truncate
396101127848SJan Kara  * page cache due to hole punching or zero range. Otherwise i_disksize update
396201127848SJan Kara  * can get lost as it may have been postponed to submission of writeback but
396301127848SJan Kara  * that will never happen after we truncate page cache.
396401127848SJan Kara  */
396501127848SJan Kara int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
396601127848SJan Kara 				      loff_t len)
396701127848SJan Kara {
396801127848SJan Kara 	handle_t *handle;
39694209ae12SHarshad Shirwadkar 	int ret;
39704209ae12SHarshad Shirwadkar 
397101127848SJan Kara 	loff_t size = i_size_read(inode);
397201127848SJan Kara 
39735955102cSAl Viro 	WARN_ON(!inode_is_locked(inode));
397401127848SJan Kara 	if (offset > size || offset + len < size)
397501127848SJan Kara 		return 0;
397601127848SJan Kara 
397701127848SJan Kara 	if (EXT4_I(inode)->i_disksize >= size)
397801127848SJan Kara 		return 0;
397901127848SJan Kara 
398001127848SJan Kara 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
398101127848SJan Kara 	if (IS_ERR(handle))
398201127848SJan Kara 		return PTR_ERR(handle);
398301127848SJan Kara 	ext4_update_i_disksize(inode, size);
39844209ae12SHarshad Shirwadkar 	ret = ext4_mark_inode_dirty(handle, inode);
398501127848SJan Kara 	ext4_journal_stop(handle);
398601127848SJan Kara 
39874209ae12SHarshad Shirwadkar 	return ret;
398801127848SJan Kara }
398901127848SJan Kara 
3990d4f5258eSJan Kara static void ext4_wait_dax_page(struct inode *inode)
3991430657b6SRoss Zwisler {
3992d4f5258eSJan Kara 	filemap_invalidate_unlock(inode->i_mapping);
3993430657b6SRoss Zwisler 	schedule();
3994d4f5258eSJan Kara 	filemap_invalidate_lock(inode->i_mapping);
3995430657b6SRoss Zwisler }
3996430657b6SRoss Zwisler 
3997430657b6SRoss Zwisler int ext4_break_layouts(struct inode *inode)
3998430657b6SRoss Zwisler {
3999430657b6SRoss Zwisler 	struct page *page;
4000430657b6SRoss Zwisler 	int error;
4001430657b6SRoss Zwisler 
4002d4f5258eSJan Kara 	if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
4003430657b6SRoss Zwisler 		return -EINVAL;
4004430657b6SRoss Zwisler 
4005430657b6SRoss Zwisler 	do {
4006430657b6SRoss Zwisler 		page = dax_layout_busy_page(inode->i_mapping);
4007430657b6SRoss Zwisler 		if (!page)
4008430657b6SRoss Zwisler 			return 0;
4009430657b6SRoss Zwisler 
4010430657b6SRoss Zwisler 		error = ___wait_var_event(&page->_refcount,
4011430657b6SRoss Zwisler 				atomic_read(&page->_refcount) == 1,
4012430657b6SRoss Zwisler 				TASK_INTERRUPTIBLE, 0, 0,
4013d4f5258eSJan Kara 				ext4_wait_dax_page(inode));
4014b1f38217SRoss Zwisler 	} while (error == 0);
4015430657b6SRoss Zwisler 
4016430657b6SRoss Zwisler 	return error;
4017430657b6SRoss Zwisler }
4018430657b6SRoss Zwisler 
401901127848SJan Kara /*
4020cca32b7eSRoss Zwisler  * ext4_punch_hole: punches a hole in a file by releasing the blocks
4021a4bb6b64SAllison Henderson  * associated with the given offset and length
4022a4bb6b64SAllison Henderson  *
4023a4bb6b64SAllison Henderson  * @inode:  File inode
4024a4bb6b64SAllison Henderson  * @offset: The offset where the hole will begin
4025a4bb6b64SAllison Henderson  * @len:    The length of the hole
4026a4bb6b64SAllison Henderson  *
40274907cb7bSAnatol Pomozov  * Returns: 0 on success or negative on failure
4028a4bb6b64SAllison Henderson  */
4029a4bb6b64SAllison Henderson 
4030ad5cd4f4SDarrick J. Wong int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
4031a4bb6b64SAllison Henderson {
4032ad5cd4f4SDarrick J. Wong 	struct inode *inode = file_inode(file);
403326a4c0c6STheodore Ts'o 	struct super_block *sb = inode->i_sb;
403426a4c0c6STheodore Ts'o 	ext4_lblk_t first_block, stop_block;
403526a4c0c6STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
40362da37622STadeusz Struk 	loff_t first_block_offset, last_block_offset, max_length;
40372da37622STadeusz Struk 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
403826a4c0c6STheodore Ts'o 	handle_t *handle;
403926a4c0c6STheodore Ts'o 	unsigned int credits;
40404209ae12SHarshad Shirwadkar 	int ret = 0, ret2 = 0;
404126a4c0c6STheodore Ts'o 
4042b8a86845SLukas Czerner 	trace_ext4_punch_hole(inode, offset, length, 0);
4043aaddea81SZheng Liu 
404426a4c0c6STheodore Ts'o 	/*
404526a4c0c6STheodore Ts'o 	 * Write out all dirty pages to avoid race conditions
404626a4c0c6STheodore Ts'o 	 * Then release them.
404726a4c0c6STheodore Ts'o 	 */
4048cca32b7eSRoss Zwisler 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
404926a4c0c6STheodore Ts'o 		ret = filemap_write_and_wait_range(mapping, offset,
405026a4c0c6STheodore Ts'o 						   offset + length - 1);
405126a4c0c6STheodore Ts'o 		if (ret)
405226a4c0c6STheodore Ts'o 			return ret;
405326a4c0c6STheodore Ts'o 	}
405426a4c0c6STheodore Ts'o 
40555955102cSAl Viro 	inode_lock(inode);
40569ef06cecSLukas Czerner 
405726a4c0c6STheodore Ts'o 	/* No need to punch hole beyond i_size */
405826a4c0c6STheodore Ts'o 	if (offset >= inode->i_size)
405926a4c0c6STheodore Ts'o 		goto out_mutex;
406026a4c0c6STheodore Ts'o 
406126a4c0c6STheodore Ts'o 	/*
406226a4c0c6STheodore Ts'o 	 * If the hole extends beyond i_size, set the hole
406326a4c0c6STheodore Ts'o 	 * to end after the page that contains i_size
406426a4c0c6STheodore Ts'o 	 */
406526a4c0c6STheodore Ts'o 	if (offset + length > inode->i_size) {
406626a4c0c6STheodore Ts'o 		length = inode->i_size +
406709cbfeafSKirill A. Shutemov 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
406826a4c0c6STheodore Ts'o 		   offset;
406926a4c0c6STheodore Ts'o 	}
407026a4c0c6STheodore Ts'o 
40712da37622STadeusz Struk 	/*
40722da37622STadeusz Struk 	 * For punch hole the length + offset needs to be within one block
40732da37622STadeusz Struk 	 * before last range. Adjust the length if it goes beyond that limit.
40742da37622STadeusz Struk 	 */
40752da37622STadeusz Struk 	max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
40762da37622STadeusz Struk 	if (offset + length > max_length)
40772da37622STadeusz Struk 		length = max_length - offset;
40782da37622STadeusz Struk 
4079a361293fSJan Kara 	if (offset & (sb->s_blocksize - 1) ||
4080a361293fSJan Kara 	    (offset + length) & (sb->s_blocksize - 1)) {
4081a361293fSJan Kara 		/*
4082a361293fSJan Kara 		 * Attach jinode to inode for jbd2 if we do any zeroing of
4083a361293fSJan Kara 		 * partial block
4084a361293fSJan Kara 		 */
4085a361293fSJan Kara 		ret = ext4_inode_attach_jinode(inode);
4086a361293fSJan Kara 		if (ret < 0)
4087a361293fSJan Kara 			goto out_mutex;
4088a361293fSJan Kara 
4089a361293fSJan Kara 	}
4090a361293fSJan Kara 
4091f340b3d9Shongnanli 	/* Wait all existing dio workers, newcomers will block on i_rwsem */
4092ea3d7209SJan Kara 	inode_dio_wait(inode);
4093ea3d7209SJan Kara 
4094ad5cd4f4SDarrick J. Wong 	ret = file_modified(file);
4095ad5cd4f4SDarrick J. Wong 	if (ret)
4096ad5cd4f4SDarrick J. Wong 		goto out_mutex;
4097ad5cd4f4SDarrick J. Wong 
4098ea3d7209SJan Kara 	/*
4099ea3d7209SJan Kara 	 * Prevent page faults from reinstantiating pages we have released from
4100ea3d7209SJan Kara 	 * page cache.
4101ea3d7209SJan Kara 	 */
4102d4f5258eSJan Kara 	filemap_invalidate_lock(mapping);
4103430657b6SRoss Zwisler 
4104430657b6SRoss Zwisler 	ret = ext4_break_layouts(inode);
4105430657b6SRoss Zwisler 	if (ret)
4106430657b6SRoss Zwisler 		goto out_dio;
4107430657b6SRoss Zwisler 
4108a87dd18cSLukas Czerner 	first_block_offset = round_up(offset, sb->s_blocksize);
4109a87dd18cSLukas Czerner 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
411026a4c0c6STheodore Ts'o 
4111a87dd18cSLukas Czerner 	/* Now release the pages and zero block aligned part of pages*/
411201127848SJan Kara 	if (last_block_offset > first_block_offset) {
411301127848SJan Kara 		ret = ext4_update_disksize_before_punch(inode, offset, length);
411401127848SJan Kara 		if (ret)
411501127848SJan Kara 			goto out_dio;
4116a87dd18cSLukas Czerner 		truncate_pagecache_range(inode, first_block_offset,
4117a87dd18cSLukas Czerner 					 last_block_offset);
411801127848SJan Kara 	}
411926a4c0c6STheodore Ts'o 
412026a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
412126a4c0c6STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
412226a4c0c6STheodore Ts'o 	else
412326a4c0c6STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
412426a4c0c6STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
412526a4c0c6STheodore Ts'o 	if (IS_ERR(handle)) {
412626a4c0c6STheodore Ts'o 		ret = PTR_ERR(handle);
412726a4c0c6STheodore Ts'o 		ext4_std_error(sb, ret);
412826a4c0c6STheodore Ts'o 		goto out_dio;
412926a4c0c6STheodore Ts'o 	}
413026a4c0c6STheodore Ts'o 
4131a87dd18cSLukas Czerner 	ret = ext4_zero_partial_blocks(handle, inode, offset,
4132a87dd18cSLukas Czerner 				       length);
413326a4c0c6STheodore Ts'o 	if (ret)
413426a4c0c6STheodore Ts'o 		goto out_stop;
413526a4c0c6STheodore Ts'o 
413626a4c0c6STheodore Ts'o 	first_block = (offset + sb->s_blocksize - 1) >>
413726a4c0c6STheodore Ts'o 		EXT4_BLOCK_SIZE_BITS(sb);
413826a4c0c6STheodore Ts'o 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
413926a4c0c6STheodore Ts'o 
4140eee597acSLukas Czerner 	/* If there are blocks to remove, do it */
4141eee597acSLukas Czerner 	if (stop_block > first_block) {
414226a4c0c6STheodore Ts'o 
414326a4c0c6STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
414427bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
414526a4c0c6STheodore Ts'o 
414626a4c0c6STheodore Ts'o 		ret = ext4_es_remove_extent(inode, first_block,
414726a4c0c6STheodore Ts'o 					    stop_block - first_block);
414826a4c0c6STheodore Ts'o 		if (ret) {
414926a4c0c6STheodore Ts'o 			up_write(&EXT4_I(inode)->i_data_sem);
415026a4c0c6STheodore Ts'o 			goto out_stop;
415126a4c0c6STheodore Ts'o 		}
415226a4c0c6STheodore Ts'o 
415326a4c0c6STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
415426a4c0c6STheodore Ts'o 			ret = ext4_ext_remove_space(inode, first_block,
415526a4c0c6STheodore Ts'o 						    stop_block - 1);
415626a4c0c6STheodore Ts'o 		else
41574f579ae7SLukas Czerner 			ret = ext4_ind_remove_space(handle, inode, first_block,
415826a4c0c6STheodore Ts'o 						    stop_block);
415926a4c0c6STheodore Ts'o 
4160819c4920STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
4161eee597acSLukas Czerner 	}
4162a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_range(handle, inode, first_block, stop_block);
416326a4c0c6STheodore Ts'o 	if (IS_SYNC(inode))
416426a4c0c6STheodore Ts'o 		ext4_handle_sync(handle);
4165e251f9bcSMaxim Patlasov 
4166eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
41674209ae12SHarshad Shirwadkar 	ret2 = ext4_mark_inode_dirty(handle, inode);
41684209ae12SHarshad Shirwadkar 	if (unlikely(ret2))
41694209ae12SHarshad Shirwadkar 		ret = ret2;
417067a7d5f5SJan Kara 	if (ret >= 0)
417167a7d5f5SJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
417226a4c0c6STheodore Ts'o out_stop:
417326a4c0c6STheodore Ts'o 	ext4_journal_stop(handle);
417426a4c0c6STheodore Ts'o out_dio:
4175d4f5258eSJan Kara 	filemap_invalidate_unlock(mapping);
417626a4c0c6STheodore Ts'o out_mutex:
41775955102cSAl Viro 	inode_unlock(inode);
417826a4c0c6STheodore Ts'o 	return ret;
4179a4bb6b64SAllison Henderson }
4180a4bb6b64SAllison Henderson 
4181a361293fSJan Kara int ext4_inode_attach_jinode(struct inode *inode)
4182a361293fSJan Kara {
4183a361293fSJan Kara 	struct ext4_inode_info *ei = EXT4_I(inode);
4184a361293fSJan Kara 	struct jbd2_inode *jinode;
4185a361293fSJan Kara 
4186a361293fSJan Kara 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4187a361293fSJan Kara 		return 0;
4188a361293fSJan Kara 
4189a361293fSJan Kara 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4190a361293fSJan Kara 	spin_lock(&inode->i_lock);
4191a361293fSJan Kara 	if (!ei->jinode) {
4192a361293fSJan Kara 		if (!jinode) {
4193a361293fSJan Kara 			spin_unlock(&inode->i_lock);
4194a361293fSJan Kara 			return -ENOMEM;
4195a361293fSJan Kara 		}
4196a361293fSJan Kara 		ei->jinode = jinode;
4197a361293fSJan Kara 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4198a361293fSJan Kara 		jinode = NULL;
4199a361293fSJan Kara 	}
4200a361293fSJan Kara 	spin_unlock(&inode->i_lock);
4201a361293fSJan Kara 	if (unlikely(jinode != NULL))
4202a361293fSJan Kara 		jbd2_free_inode(jinode);
4203a361293fSJan Kara 	return 0;
4204a361293fSJan Kara }
4205a361293fSJan Kara 
4206a4bb6b64SAllison Henderson /*
4207617ba13bSMingming Cao  * ext4_truncate()
4208ac27a0ecSDave Kleikamp  *
4209617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
4210617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4211ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
4212ac27a0ecSDave Kleikamp  *
421342b2aa86SJustin P. Mattock  * As we work through the truncate and commit bits of it to the journal there
4214ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
4215ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
4216ac27a0ecSDave Kleikamp  *
4217ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
4218ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
4219ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
4220ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
4221ac27a0ecSDave Kleikamp  * left-to-right works OK too).
4222ac27a0ecSDave Kleikamp  *
4223ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
4224ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
4225ac27a0ecSDave Kleikamp  *
4226ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
4227617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4228ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
4229617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
4230617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
4231ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
4232617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
4233ac27a0ecSDave Kleikamp  */
42342c98eb5eSTheodore Ts'o int ext4_truncate(struct inode *inode)
4235ac27a0ecSDave Kleikamp {
4236819c4920STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
4237819c4920STheodore Ts'o 	unsigned int credits;
42384209ae12SHarshad Shirwadkar 	int err = 0, err2;
4239819c4920STheodore Ts'o 	handle_t *handle;
4240819c4920STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
4241819c4920STheodore Ts'o 
424219b5ef61STheodore Ts'o 	/*
424319b5ef61STheodore Ts'o 	 * There is a possibility that we're either freeing the inode
4244e04027e8SMatthew Wilcox 	 * or it's a completely new inode. In those cases we might not
4245f340b3d9Shongnanli 	 * have i_rwsem locked because it's not necessary.
424619b5ef61STheodore Ts'o 	 */
424719b5ef61STheodore Ts'o 	if (!(inode->i_state & (I_NEW|I_FREEING)))
42485955102cSAl Viro 		WARN_ON(!inode_is_locked(inode));
42490562e0baSJiaying Zhang 	trace_ext4_truncate_enter(inode);
42500562e0baSJiaying Zhang 
425191ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
42529a5d265fSzhengliang 		goto out_trace;
4253ac27a0ecSDave Kleikamp 
42545534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
425519f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
42567d8f9f7dSTheodore Ts'o 
4257aef1c851STao Ma 	if (ext4_has_inline_data(inode)) {
4258aef1c851STao Ma 		int has_inline = 1;
4259aef1c851STao Ma 
426001daf945STheodore Ts'o 		err = ext4_inline_data_truncate(inode, &has_inline);
42619a5d265fSzhengliang 		if (err || has_inline)
42629a5d265fSzhengliang 			goto out_trace;
4263aef1c851STao Ma 	}
4264aef1c851STao Ma 
4265a361293fSJan Kara 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4266a361293fSJan Kara 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4267a71248b1SBaokun Li 		err = ext4_inode_attach_jinode(inode);
4268a71248b1SBaokun Li 		if (err)
42699a5d265fSzhengliang 			goto out_trace;
4270a361293fSJan Kara 	}
4271a361293fSJan Kara 
4272ff9893dcSAmir Goldstein 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4273819c4920STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
4274ff9893dcSAmir Goldstein 	else
4275819c4920STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
4276819c4920STheodore Ts'o 
4277819c4920STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
42789a5d265fSzhengliang 	if (IS_ERR(handle)) {
42799a5d265fSzhengliang 		err = PTR_ERR(handle);
42809a5d265fSzhengliang 		goto out_trace;
42819a5d265fSzhengliang 	}
4282819c4920STheodore Ts'o 
4283eb3544c6SLukas Czerner 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4284eb3544c6SLukas Czerner 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4285819c4920STheodore Ts'o 
4286819c4920STheodore Ts'o 	/*
4287819c4920STheodore Ts'o 	 * We add the inode to the orphan list, so that if this
4288819c4920STheodore Ts'o 	 * truncate spans multiple transactions, and we crash, we will
4289819c4920STheodore Ts'o 	 * resume the truncate when the filesystem recovers.  It also
4290819c4920STheodore Ts'o 	 * marks the inode dirty, to catch the new size.
4291819c4920STheodore Ts'o 	 *
4292819c4920STheodore Ts'o 	 * Implication: the file must always be in a sane, consistent
4293819c4920STheodore Ts'o 	 * truncatable state while each transaction commits.
4294819c4920STheodore Ts'o 	 */
42952c98eb5eSTheodore Ts'o 	err = ext4_orphan_add(handle, inode);
42962c98eb5eSTheodore Ts'o 	if (err)
4297819c4920STheodore Ts'o 		goto out_stop;
4298819c4920STheodore Ts'o 
4299819c4920STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
4300819c4920STheodore Ts'o 
430127bc446eSbrookxu 	ext4_discard_preallocations(inode, 0);
4302819c4920STheodore Ts'o 
4303819c4920STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4304d0abb36dSTheodore Ts'o 		err = ext4_ext_truncate(handle, inode);
4305819c4920STheodore Ts'o 	else
4306819c4920STheodore Ts'o 		ext4_ind_truncate(handle, inode);
4307819c4920STheodore Ts'o 
4308819c4920STheodore Ts'o 	up_write(&ei->i_data_sem);
4309d0abb36dSTheodore Ts'o 	if (err)
4310d0abb36dSTheodore Ts'o 		goto out_stop;
4311819c4920STheodore Ts'o 
4312819c4920STheodore Ts'o 	if (IS_SYNC(inode))
4313819c4920STheodore Ts'o 		ext4_handle_sync(handle);
4314819c4920STheodore Ts'o 
4315819c4920STheodore Ts'o out_stop:
4316819c4920STheodore Ts'o 	/*
4317819c4920STheodore Ts'o 	 * If this was a simple ftruncate() and the file will remain alive,
4318819c4920STheodore Ts'o 	 * then we need to clear up the orphan record which we created above.
4319819c4920STheodore Ts'o 	 * However, if this was a real unlink then we were called by
432058d86a50SWang Shilong 	 * ext4_evict_inode(), and we allow that function to clean up the
4321819c4920STheodore Ts'o 	 * orphan info for us.
4322819c4920STheodore Ts'o 	 */
4323819c4920STheodore Ts'o 	if (inode->i_nlink)
4324819c4920STheodore Ts'o 		ext4_orphan_del(handle, inode);
4325819c4920STheodore Ts'o 
4326eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
43274209ae12SHarshad Shirwadkar 	err2 = ext4_mark_inode_dirty(handle, inode);
43284209ae12SHarshad Shirwadkar 	if (unlikely(err2 && !err))
43294209ae12SHarshad Shirwadkar 		err = err2;
4330819c4920STheodore Ts'o 	ext4_journal_stop(handle);
4331a86c6181SAlex Tomas 
43329a5d265fSzhengliang out_trace:
43330562e0baSJiaying Zhang 	trace_ext4_truncate_exit(inode);
43342c98eb5eSTheodore Ts'o 	return err;
4335ac27a0ecSDave Kleikamp }
4336ac27a0ecSDave Kleikamp 
43379a1bf32cSZhang Yi static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
43389a1bf32cSZhang Yi {
43399a1bf32cSZhang Yi 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
43409a1bf32cSZhang Yi 		return inode_peek_iversion_raw(inode);
43419a1bf32cSZhang Yi 	else
43429a1bf32cSZhang Yi 		return inode_peek_iversion(inode);
43439a1bf32cSZhang Yi }
43449a1bf32cSZhang Yi 
43459a1bf32cSZhang Yi static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
43469a1bf32cSZhang Yi 				 struct ext4_inode_info *ei)
43479a1bf32cSZhang Yi {
43489a1bf32cSZhang Yi 	struct inode *inode = &(ei->vfs_inode);
43499a1bf32cSZhang Yi 	u64 i_blocks = READ_ONCE(inode->i_blocks);
43509a1bf32cSZhang Yi 	struct super_block *sb = inode->i_sb;
43519a1bf32cSZhang Yi 
43529a1bf32cSZhang Yi 	if (i_blocks <= ~0U) {
43539a1bf32cSZhang Yi 		/*
43549a1bf32cSZhang Yi 		 * i_blocks can be represented in a 32 bit variable
43559a1bf32cSZhang Yi 		 * as multiple of 512 bytes
43569a1bf32cSZhang Yi 		 */
43579a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
43589a1bf32cSZhang Yi 		raw_inode->i_blocks_high = 0;
43599a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
43609a1bf32cSZhang Yi 		return 0;
43619a1bf32cSZhang Yi 	}
43629a1bf32cSZhang Yi 
43639a1bf32cSZhang Yi 	/*
43649a1bf32cSZhang Yi 	 * This should never happen since sb->s_maxbytes should not have
43659a1bf32cSZhang Yi 	 * allowed this, sb->s_maxbytes was set according to the huge_file
43669a1bf32cSZhang Yi 	 * feature in ext4_fill_super().
43679a1bf32cSZhang Yi 	 */
43689a1bf32cSZhang Yi 	if (!ext4_has_feature_huge_file(sb))
43699a1bf32cSZhang Yi 		return -EFSCORRUPTED;
43709a1bf32cSZhang Yi 
43719a1bf32cSZhang Yi 	if (i_blocks <= 0xffffffffffffULL) {
43729a1bf32cSZhang Yi 		/*
43739a1bf32cSZhang Yi 		 * i_blocks can be represented in a 48 bit variable
43749a1bf32cSZhang Yi 		 * as multiple of 512 bytes
43759a1bf32cSZhang Yi 		 */
43769a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
43779a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
43789a1bf32cSZhang Yi 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
43799a1bf32cSZhang Yi 	} else {
43809a1bf32cSZhang Yi 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
43819a1bf32cSZhang Yi 		/* i_block is stored in file system block size */
43829a1bf32cSZhang Yi 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
43839a1bf32cSZhang Yi 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
43849a1bf32cSZhang Yi 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
43859a1bf32cSZhang Yi 	}
43869a1bf32cSZhang Yi 	return 0;
43879a1bf32cSZhang Yi }
43889a1bf32cSZhang Yi 
43899a1bf32cSZhang Yi static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
43909a1bf32cSZhang Yi {
43919a1bf32cSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
43929a1bf32cSZhang Yi 	uid_t i_uid;
43939a1bf32cSZhang Yi 	gid_t i_gid;
43949a1bf32cSZhang Yi 	projid_t i_projid;
43959a1bf32cSZhang Yi 	int block;
43969a1bf32cSZhang Yi 	int err;
43979a1bf32cSZhang Yi 
43989a1bf32cSZhang Yi 	err = ext4_inode_blocks_set(raw_inode, ei);
43999a1bf32cSZhang Yi 
44009a1bf32cSZhang Yi 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
44019a1bf32cSZhang Yi 	i_uid = i_uid_read(inode);
44029a1bf32cSZhang Yi 	i_gid = i_gid_read(inode);
44039a1bf32cSZhang Yi 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
44049a1bf32cSZhang Yi 	if (!(test_opt(inode->i_sb, NO_UID32))) {
44059a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
44069a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
44079a1bf32cSZhang Yi 		/*
44089a1bf32cSZhang Yi 		 * Fix up interoperability with old kernels. Otherwise,
44099a1bf32cSZhang Yi 		 * old inodes get re-used with the upper 16 bits of the
44109a1bf32cSZhang Yi 		 * uid/gid intact.
44119a1bf32cSZhang Yi 		 */
44129a1bf32cSZhang Yi 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
44139a1bf32cSZhang Yi 			raw_inode->i_uid_high = 0;
44149a1bf32cSZhang Yi 			raw_inode->i_gid_high = 0;
44159a1bf32cSZhang Yi 		} else {
44169a1bf32cSZhang Yi 			raw_inode->i_uid_high =
44179a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_uid));
44189a1bf32cSZhang Yi 			raw_inode->i_gid_high =
44199a1bf32cSZhang Yi 				cpu_to_le16(high_16_bits(i_gid));
44209a1bf32cSZhang Yi 		}
44219a1bf32cSZhang Yi 	} else {
44229a1bf32cSZhang Yi 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
44239a1bf32cSZhang Yi 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
44249a1bf32cSZhang Yi 		raw_inode->i_uid_high = 0;
44259a1bf32cSZhang Yi 		raw_inode->i_gid_high = 0;
44269a1bf32cSZhang Yi 	}
44279a1bf32cSZhang Yi 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
44289a1bf32cSZhang Yi 
44299a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
44309a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
44319a1bf32cSZhang Yi 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
44329a1bf32cSZhang Yi 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
44339a1bf32cSZhang Yi 
44349a1bf32cSZhang Yi 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
44359a1bf32cSZhang Yi 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
44369a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
44379a1bf32cSZhang Yi 		raw_inode->i_file_acl_high =
44389a1bf32cSZhang Yi 			cpu_to_le16(ei->i_file_acl >> 32);
44399a1bf32cSZhang Yi 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
44409a1bf32cSZhang Yi 	ext4_isize_set(raw_inode, ei->i_disksize);
44419a1bf32cSZhang Yi 
44429a1bf32cSZhang Yi 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
44439a1bf32cSZhang Yi 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
44449a1bf32cSZhang Yi 		if (old_valid_dev(inode->i_rdev)) {
44459a1bf32cSZhang Yi 			raw_inode->i_block[0] =
44469a1bf32cSZhang Yi 				cpu_to_le32(old_encode_dev(inode->i_rdev));
44479a1bf32cSZhang Yi 			raw_inode->i_block[1] = 0;
44489a1bf32cSZhang Yi 		} else {
44499a1bf32cSZhang Yi 			raw_inode->i_block[0] = 0;
44509a1bf32cSZhang Yi 			raw_inode->i_block[1] =
44519a1bf32cSZhang Yi 				cpu_to_le32(new_encode_dev(inode->i_rdev));
44529a1bf32cSZhang Yi 			raw_inode->i_block[2] = 0;
44539a1bf32cSZhang Yi 		}
44549a1bf32cSZhang Yi 	} else if (!ext4_has_inline_data(inode)) {
44559a1bf32cSZhang Yi 		for (block = 0; block < EXT4_N_BLOCKS; block++)
44569a1bf32cSZhang Yi 			raw_inode->i_block[block] = ei->i_data[block];
44579a1bf32cSZhang Yi 	}
44589a1bf32cSZhang Yi 
44599a1bf32cSZhang Yi 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
44609a1bf32cSZhang Yi 		u64 ivers = ext4_inode_peek_iversion(inode);
44619a1bf32cSZhang Yi 
44629a1bf32cSZhang Yi 		raw_inode->i_disk_version = cpu_to_le32(ivers);
44639a1bf32cSZhang Yi 		if (ei->i_extra_isize) {
44649a1bf32cSZhang Yi 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
44659a1bf32cSZhang Yi 				raw_inode->i_version_hi =
44669a1bf32cSZhang Yi 					cpu_to_le32(ivers >> 32);
44679a1bf32cSZhang Yi 			raw_inode->i_extra_isize =
44689a1bf32cSZhang Yi 				cpu_to_le16(ei->i_extra_isize);
44699a1bf32cSZhang Yi 		}
44709a1bf32cSZhang Yi 	}
44719a1bf32cSZhang Yi 
44729a1bf32cSZhang Yi 	if (i_projid != EXT4_DEF_PROJID &&
44739a1bf32cSZhang Yi 	    !ext4_has_feature_project(inode->i_sb))
44749a1bf32cSZhang Yi 		err = err ?: -EFSCORRUPTED;
44759a1bf32cSZhang Yi 
44769a1bf32cSZhang Yi 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
44779a1bf32cSZhang Yi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
44789a1bf32cSZhang Yi 		raw_inode->i_projid = cpu_to_le32(i_projid);
44799a1bf32cSZhang Yi 
44809a1bf32cSZhang Yi 	ext4_inode_csum_set(inode, raw_inode, ei);
44819a1bf32cSZhang Yi 	return err;
44829a1bf32cSZhang Yi }
44839a1bf32cSZhang Yi 
4484ac27a0ecSDave Kleikamp /*
4485617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
4486de01f484SZhang Yi  * underlying buffer_head on success. If we pass 'inode' and it does not
4487de01f484SZhang Yi  * have in-inode xattr, we have all inode data in memory that is needed
4488de01f484SZhang Yi  * to recreate the on-disk version of this inode.
4489ac27a0ecSDave Kleikamp  */
44908016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4491de01f484SZhang Yi 				struct inode *inode, struct ext4_iloc *iloc,
44928016e29fSHarshad Shirwadkar 				ext4_fsblk_t *ret_block)
4493ac27a0ecSDave Kleikamp {
4494240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
4495ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
4496240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
449702f03c42SLinus Torvalds 	struct blk_plug		plug;
4498240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
4499ac27a0ecSDave Kleikamp 
45003a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
45018016e29fSHarshad Shirwadkar 	if (ino < EXT4_ROOT_INO ||
45028016e29fSHarshad Shirwadkar 	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
45036a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4504ac27a0ecSDave Kleikamp 
45058016e29fSHarshad Shirwadkar 	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4506240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4507240799cdSTheodore Ts'o 	if (!gdp)
4508240799cdSTheodore Ts'o 		return -EIO;
4509240799cdSTheodore Ts'o 
4510240799cdSTheodore Ts'o 	/*
4511240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
4512240799cdSTheodore Ts'o 	 */
451300d09882STao Ma 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
45148016e29fSHarshad Shirwadkar 	inode_offset = ((ino - 1) %
4515240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
4516240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4517240799cdSTheodore Ts'o 
4518eee22187SBaokun Li 	block = ext4_inode_table(sb, gdp);
4519eee22187SBaokun Li 	if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4520eee22187SBaokun Li 	    (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4521eee22187SBaokun Li 		ext4_error(sb, "Invalid inode table block %llu in "
4522eee22187SBaokun Li 			   "block_group %u", block, iloc->block_group);
4523eee22187SBaokun Li 		return -EFSCORRUPTED;
4524eee22187SBaokun Li 	}
4525eee22187SBaokun Li 	block += (inode_offset / inodes_per_block);
4526eee22187SBaokun Li 
4527240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
4528aebf0243SWang Shilong 	if (unlikely(!bh))
4529860d21e2STheodore Ts'o 		return -ENOMEM;
45308e33fadfSZhang Yi 	if (ext4_buffer_uptodate(bh))
4531ac27a0ecSDave Kleikamp 		goto has_buffer;
4532ac27a0ecSDave Kleikamp 
45338e33fadfSZhang Yi 	lock_buffer(bh);
4534f2c77973SZhang Yi 	if (ext4_buffer_uptodate(bh)) {
4535f2c77973SZhang Yi 		/* Someone brought it uptodate while we waited */
4536f2c77973SZhang Yi 		unlock_buffer(bh);
4537f2c77973SZhang Yi 		goto has_buffer;
4538f2c77973SZhang Yi 	}
4539f2c77973SZhang Yi 
4540ac27a0ecSDave Kleikamp 	/*
4541ac27a0ecSDave Kleikamp 	 * If we have all information of the inode in memory and this
4542ac27a0ecSDave Kleikamp 	 * is the only valid inode in the block, we need not read the
4543ac27a0ecSDave Kleikamp 	 * block.
4544ac27a0ecSDave Kleikamp 	 */
4545de01f484SZhang Yi 	if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4546ac27a0ecSDave Kleikamp 		struct buffer_head *bitmap_bh;
4547240799cdSTheodore Ts'o 		int i, start;
4548ac27a0ecSDave Kleikamp 
4549240799cdSTheodore Ts'o 		start = inode_offset & ~(inodes_per_block - 1);
4550ac27a0ecSDave Kleikamp 
4551ac27a0ecSDave Kleikamp 		/* Is the inode bitmap in cache? */
4552240799cdSTheodore Ts'o 		bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4553aebf0243SWang Shilong 		if (unlikely(!bitmap_bh))
4554ac27a0ecSDave Kleikamp 			goto make_io;
4555ac27a0ecSDave Kleikamp 
4556ac27a0ecSDave Kleikamp 		/*
4557ac27a0ecSDave Kleikamp 		 * If the inode bitmap isn't in cache then the
4558ac27a0ecSDave Kleikamp 		 * optimisation may end up performing two reads instead
4559ac27a0ecSDave Kleikamp 		 * of one, so skip it.
4560ac27a0ecSDave Kleikamp 		 */
4561ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bitmap_bh)) {
4562ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
4563ac27a0ecSDave Kleikamp 			goto make_io;
4564ac27a0ecSDave Kleikamp 		}
4565240799cdSTheodore Ts'o 		for (i = start; i < start + inodes_per_block; i++) {
4566ac27a0ecSDave Kleikamp 			if (i == inode_offset)
4567ac27a0ecSDave Kleikamp 				continue;
4568617ba13bSMingming Cao 			if (ext4_test_bit(i, bitmap_bh->b_data))
4569ac27a0ecSDave Kleikamp 				break;
4570ac27a0ecSDave Kleikamp 		}
4571ac27a0ecSDave Kleikamp 		brelse(bitmap_bh);
4572240799cdSTheodore Ts'o 		if (i == start + inodes_per_block) {
4573de01f484SZhang Yi 			struct ext4_inode *raw_inode =
4574de01f484SZhang Yi 				(struct ext4_inode *) (bh->b_data + iloc->offset);
4575de01f484SZhang Yi 
4576ac27a0ecSDave Kleikamp 			/* all other inodes are free, so skip I/O */
4577ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, bh->b_size);
4578de01f484SZhang Yi 			if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4579de01f484SZhang Yi 				ext4_fill_raw_inode(inode, raw_inode);
4580ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
4581ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
4582ac27a0ecSDave Kleikamp 			goto has_buffer;
4583ac27a0ecSDave Kleikamp 		}
4584ac27a0ecSDave Kleikamp 	}
4585ac27a0ecSDave Kleikamp 
4586ac27a0ecSDave Kleikamp make_io:
4587ac27a0ecSDave Kleikamp 	/*
4588240799cdSTheodore Ts'o 	 * If we need to do any I/O, try to pre-readahead extra
4589240799cdSTheodore Ts'o 	 * blocks from the inode table.
4590240799cdSTheodore Ts'o 	 */
459102f03c42SLinus Torvalds 	blk_start_plug(&plug);
4592240799cdSTheodore Ts'o 	if (EXT4_SB(sb)->s_inode_readahead_blks) {
4593240799cdSTheodore Ts'o 		ext4_fsblk_t b, end, table;
4594240799cdSTheodore Ts'o 		unsigned num;
45950d606e2cSTheodore Ts'o 		__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4596240799cdSTheodore Ts'o 
4597240799cdSTheodore Ts'o 		table = ext4_inode_table(sb, gdp);
4598b713a5ecSTheodore Ts'o 		/* s_inode_readahead_blks is always a power of 2 */
45990d606e2cSTheodore Ts'o 		b = block & ~((ext4_fsblk_t) ra_blks - 1);
4600240799cdSTheodore Ts'o 		if (table > b)
4601240799cdSTheodore Ts'o 			b = table;
46020d606e2cSTheodore Ts'o 		end = b + ra_blks;
4603240799cdSTheodore Ts'o 		num = EXT4_INODES_PER_GROUP(sb);
4604feb0ab32SDarrick J. Wong 		if (ext4_has_group_desc_csum(sb))
4605560671a0SAneesh Kumar K.V 			num -= ext4_itable_unused_count(sb, gdp);
4606240799cdSTheodore Ts'o 		table += num / inodes_per_block;
4607240799cdSTheodore Ts'o 		if (end > table)
4608240799cdSTheodore Ts'o 			end = table;
4609240799cdSTheodore Ts'o 		while (b <= end)
46105df1d412Szhangyi (F) 			ext4_sb_breadahead_unmovable(sb, b++);
4611240799cdSTheodore Ts'o 	}
4612240799cdSTheodore Ts'o 
4613240799cdSTheodore Ts'o 	/*
4614ac27a0ecSDave Kleikamp 	 * There are other valid inodes in the buffer, this inode
4615ac27a0ecSDave Kleikamp 	 * has in-inode xattrs, or we don't have this inode in memory.
4616ac27a0ecSDave Kleikamp 	 * Read the block from disk.
4617ac27a0ecSDave Kleikamp 	 */
46188016e29fSHarshad Shirwadkar 	trace_ext4_load_inode(sb, ino);
46192d069c08Szhangyi (F) 	ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
462002f03c42SLinus Torvalds 	blk_finish_plug(&plug);
4621ac27a0ecSDave Kleikamp 	wait_on_buffer(bh);
46220904c9aeSZhang Yi 	ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4623ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
46248016e29fSHarshad Shirwadkar 		if (ret_block)
46258016e29fSHarshad Shirwadkar 			*ret_block = block;
4626ac27a0ecSDave Kleikamp 		brelse(bh);
4627ac27a0ecSDave Kleikamp 		return -EIO;
4628ac27a0ecSDave Kleikamp 	}
4629ac27a0ecSDave Kleikamp has_buffer:
4630ac27a0ecSDave Kleikamp 	iloc->bh = bh;
4631ac27a0ecSDave Kleikamp 	return 0;
4632ac27a0ecSDave Kleikamp }
4633ac27a0ecSDave Kleikamp 
46348016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc_noinmem(struct inode *inode,
46358016e29fSHarshad Shirwadkar 					struct ext4_iloc *iloc)
46368016e29fSHarshad Shirwadkar {
4637c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
46388016e29fSHarshad Shirwadkar 	int ret;
46398016e29fSHarshad Shirwadkar 
4640de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
46418016e29fSHarshad Shirwadkar 					&err_blk);
46428016e29fSHarshad Shirwadkar 
46438016e29fSHarshad Shirwadkar 	if (ret == -EIO)
46448016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
46458016e29fSHarshad Shirwadkar 					"unable to read itable block");
46468016e29fSHarshad Shirwadkar 
46478016e29fSHarshad Shirwadkar 	return ret;
46488016e29fSHarshad Shirwadkar }
46498016e29fSHarshad Shirwadkar 
4650617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4651ac27a0ecSDave Kleikamp {
4652c27c29c6SHarshad Shirwadkar 	ext4_fsblk_t err_blk = 0;
46538016e29fSHarshad Shirwadkar 	int ret;
46548016e29fSHarshad Shirwadkar 
4655de01f484SZhang Yi 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4656de01f484SZhang Yi 					&err_blk);
46578016e29fSHarshad Shirwadkar 
46588016e29fSHarshad Shirwadkar 	if (ret == -EIO)
46598016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
46608016e29fSHarshad Shirwadkar 					"unable to read itable block");
46618016e29fSHarshad Shirwadkar 
46628016e29fSHarshad Shirwadkar 	return ret;
46638016e29fSHarshad Shirwadkar }
46648016e29fSHarshad Shirwadkar 
46658016e29fSHarshad Shirwadkar 
46668016e29fSHarshad Shirwadkar int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
46678016e29fSHarshad Shirwadkar 			  struct ext4_iloc *iloc)
46688016e29fSHarshad Shirwadkar {
4669de01f484SZhang Yi 	return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4670ac27a0ecSDave Kleikamp }
4671ac27a0ecSDave Kleikamp 
4672a8ab6d38SIra Weiny static bool ext4_should_enable_dax(struct inode *inode)
46736642586bSRoss Zwisler {
4674a8ab6d38SIra Weiny 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4675a8ab6d38SIra Weiny 
46769cb20f94SIra Weiny 	if (test_opt2(inode->i_sb, DAX_NEVER))
46776642586bSRoss Zwisler 		return false;
46786642586bSRoss Zwisler 	if (!S_ISREG(inode->i_mode))
46796642586bSRoss Zwisler 		return false;
46806642586bSRoss Zwisler 	if (ext4_should_journal_data(inode))
46816642586bSRoss Zwisler 		return false;
46826642586bSRoss Zwisler 	if (ext4_has_inline_data(inode))
46836642586bSRoss Zwisler 		return false;
4684592ddec7SChandan Rajendra 	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
46856642586bSRoss Zwisler 		return false;
4686c93d8f88SEric Biggers 	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4687c93d8f88SEric Biggers 		return false;
4688a8ab6d38SIra Weiny 	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4689a8ab6d38SIra Weiny 		return false;
4690a8ab6d38SIra Weiny 	if (test_opt(inode->i_sb, DAX_ALWAYS))
46916642586bSRoss Zwisler 		return true;
4692a8ab6d38SIra Weiny 
4693b383a73fSIra Weiny 	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
46946642586bSRoss Zwisler }
46956642586bSRoss Zwisler 
4696043546e4SIra Weiny void ext4_set_inode_flags(struct inode *inode, bool init)
4697ac27a0ecSDave Kleikamp {
4698617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
469900a1a053STheodore Ts'o 	unsigned int new_fl = 0;
4700ac27a0ecSDave Kleikamp 
4701043546e4SIra Weiny 	WARN_ON_ONCE(IS_DAX(inode) && init);
4702043546e4SIra Weiny 
4703617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
470400a1a053STheodore Ts'o 		new_fl |= S_SYNC;
4705617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
470600a1a053STheodore Ts'o 		new_fl |= S_APPEND;
4707617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
470800a1a053STheodore Ts'o 		new_fl |= S_IMMUTABLE;
4709617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
471000a1a053STheodore Ts'o 		new_fl |= S_NOATIME;
4711617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
471200a1a053STheodore Ts'o 		new_fl |= S_DIRSYNC;
4713043546e4SIra Weiny 
4714043546e4SIra Weiny 	/* Because of the way inode_set_flags() works we must preserve S_DAX
4715043546e4SIra Weiny 	 * here if already set. */
4716043546e4SIra Weiny 	new_fl |= (inode->i_flags & S_DAX);
4717043546e4SIra Weiny 	if (init && ext4_should_enable_dax(inode))
4718923ae0ffSRoss Zwisler 		new_fl |= S_DAX;
4719043546e4SIra Weiny 
47202ee6a576SEric Biggers 	if (flags & EXT4_ENCRYPT_FL)
47212ee6a576SEric Biggers 		new_fl |= S_ENCRYPTED;
4722b886ee3eSGabriel Krisman Bertazi 	if (flags & EXT4_CASEFOLD_FL)
4723b886ee3eSGabriel Krisman Bertazi 		new_fl |= S_CASEFOLD;
4724c93d8f88SEric Biggers 	if (flags & EXT4_VERITY_FL)
4725c93d8f88SEric Biggers 		new_fl |= S_VERITY;
47265f16f322STheodore Ts'o 	inode_set_flags(inode, new_fl,
47272ee6a576SEric Biggers 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4728c93d8f88SEric Biggers 			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4729ac27a0ecSDave Kleikamp }
4730ac27a0ecSDave Kleikamp 
47310fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
47320fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
47330fc1b451SAneesh Kumar K.V {
47340fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
47358180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
47368180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
47370fc1b451SAneesh Kumar K.V 
4738e2b911c5SDarrick J. Wong 	if (ext4_has_feature_huge_file(sb)) {
47390fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
47400fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
47410fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
474207a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
47438180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
47448180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
47458180a562SAneesh Kumar K.V 		} else {
47460fc1b451SAneesh Kumar K.V 			return i_blocks;
47478180a562SAneesh Kumar K.V 		}
47480fc1b451SAneesh Kumar K.V 	} else {
47490fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
47500fc1b451SAneesh Kumar K.V 	}
47510fc1b451SAneesh Kumar K.V }
4752ff9ddf7eSJan Kara 
4753eb9b5f01STheodore Ts'o static inline int ext4_iget_extra_inode(struct inode *inode,
4754152a7b0aSTao Ma 					 struct ext4_inode *raw_inode,
4755152a7b0aSTao Ma 					 struct ext4_inode_info *ei)
4756152a7b0aSTao Ma {
4757152a7b0aSTao Ma 	__le32 *magic = (void *)raw_inode +
4758152a7b0aSTao Ma 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4759eb9b5f01STheodore Ts'o 
4760fd7e672eSBaokun Li 	if (EXT4_INODE_HAS_XATTR_SPACE(inode)  &&
4761290ab230SEric Biggers 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4762152a7b0aSTao Ma 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4763eb9b5f01STheodore Ts'o 		return ext4_find_inline_data_nolock(inode);
4764f19d5870STao Ma 	} else
4765f19d5870STao Ma 		EXT4_I(inode)->i_inline_off = 0;
4766eb9b5f01STheodore Ts'o 	return 0;
4767152a7b0aSTao Ma }
4768152a7b0aSTao Ma 
4769040cb378SLi Xi int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4770040cb378SLi Xi {
47710b7b7779SKaho Ng 	if (!ext4_has_feature_project(inode->i_sb))
4772040cb378SLi Xi 		return -EOPNOTSUPP;
4773040cb378SLi Xi 	*projid = EXT4_I(inode)->i_projid;
4774040cb378SLi Xi 	return 0;
4775040cb378SLi Xi }
4776040cb378SLi Xi 
4777e254d1afSEryu Guan /*
4778e254d1afSEryu Guan  * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4779e254d1afSEryu Guan  * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4780e254d1afSEryu Guan  * set.
4781e254d1afSEryu Guan  */
4782e254d1afSEryu Guan static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4783e254d1afSEryu Guan {
4784e254d1afSEryu Guan 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4785e254d1afSEryu Guan 		inode_set_iversion_raw(inode, val);
4786e254d1afSEryu Guan 	else
4787e254d1afSEryu Guan 		inode_set_iversion_queried(inode, val);
4788e254d1afSEryu Guan }
4789e254d1afSEryu Guan 
47908a363970STheodore Ts'o struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
47918a363970STheodore Ts'o 			  ext4_iget_flags flags, const char *function,
47928a363970STheodore Ts'o 			  unsigned int line)
4793ac27a0ecSDave Kleikamp {
4794617ba13bSMingming Cao 	struct ext4_iloc iloc;
4795617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
47961d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
4797bd2c38cfSJan Kara 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
47981d1fe1eeSDavid Howells 	struct inode *inode;
4799b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
48001d1fe1eeSDavid Howells 	long ret;
48017e6e1ef4SDarrick J. Wong 	loff_t size;
4802ac27a0ecSDave Kleikamp 	int block;
480308cefc7aSEric W. Biederman 	uid_t i_uid;
480408cefc7aSEric W. Biederman 	gid_t i_gid;
4805040cb378SLi Xi 	projid_t i_projid;
4806ac27a0ecSDave Kleikamp 
4807191ce178STheodore Ts'o 	if ((!(flags & EXT4_IGET_SPECIAL) &&
4808bd2c38cfSJan Kara 	     ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4809bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_usr_quota_inum) ||
4810bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_grp_quota_inum) ||
481102f310fcSJan Kara 	      ino == le32_to_cpu(es->s_prj_quota_inum) ||
481202f310fcSJan Kara 	      ino == le32_to_cpu(es->s_orphan_file_inum))) ||
48138a363970STheodore Ts'o 	    (ino < EXT4_ROOT_INO) ||
4814bd2c38cfSJan Kara 	    (ino > le32_to_cpu(es->s_inodes_count))) {
48158a363970STheodore Ts'o 		if (flags & EXT4_IGET_HANDLE)
48168a363970STheodore Ts'o 			return ERR_PTR(-ESTALE);
4817014c9caaSJan Kara 		__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
48188a363970STheodore Ts'o 			     "inode #%lu: comm %s: iget: illegal inode #",
48198a363970STheodore Ts'o 			     ino, current->comm);
48208a363970STheodore Ts'o 		return ERR_PTR(-EFSCORRUPTED);
48218a363970STheodore Ts'o 	}
48228a363970STheodore Ts'o 
48231d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
48241d1fe1eeSDavid Howells 	if (!inode)
48251d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
48261d1fe1eeSDavid Howells 	if (!(inode->i_state & I_NEW))
48271d1fe1eeSDavid Howells 		return inode;
48281d1fe1eeSDavid Howells 
48291d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
48307dc57615SPeter Huewe 	iloc.bh = NULL;
4831ac27a0ecSDave Kleikamp 
48328016e29fSHarshad Shirwadkar 	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
48331d1fe1eeSDavid Howells 	if (ret < 0)
4834ac27a0ecSDave Kleikamp 		goto bad_inode;
4835617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
4836814525f4SDarrick J. Wong 
48378e4b5eaeSTheodore Ts'o 	if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
48388a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
48398a363970STheodore Ts'o 				 "iget: root inode unallocated");
48408e4b5eaeSTheodore Ts'o 		ret = -EFSCORRUPTED;
48418e4b5eaeSTheodore Ts'o 		goto bad_inode;
48428e4b5eaeSTheodore Ts'o 	}
48438e4b5eaeSTheodore Ts'o 
48448a363970STheodore Ts'o 	if ((flags & EXT4_IGET_HANDLE) &&
48458a363970STheodore Ts'o 	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
48468a363970STheodore Ts'o 		ret = -ESTALE;
48478a363970STheodore Ts'o 		goto bad_inode;
48488a363970STheodore Ts'o 	}
48498a363970STheodore Ts'o 
4850814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4851814525f4SDarrick J. Wong 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4852814525f4SDarrick J. Wong 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
48532dc8d9e1SEric Biggers 			EXT4_INODE_SIZE(inode->i_sb) ||
48542dc8d9e1SEric Biggers 		    (ei->i_extra_isize & 3)) {
48558a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
48568a363970STheodore Ts'o 					 "iget: bad extra_isize %u "
48578a363970STheodore Ts'o 					 "(inode size %u)",
48582dc8d9e1SEric Biggers 					 ei->i_extra_isize,
4859814525f4SDarrick J. Wong 					 EXT4_INODE_SIZE(inode->i_sb));
48606a797d27SDarrick J. Wong 			ret = -EFSCORRUPTED;
4861814525f4SDarrick J. Wong 			goto bad_inode;
4862814525f4SDarrick J. Wong 		}
4863814525f4SDarrick J. Wong 	} else
4864814525f4SDarrick J. Wong 		ei->i_extra_isize = 0;
4865814525f4SDarrick J. Wong 
4866814525f4SDarrick J. Wong 	/* Precompute checksum seed for inode metadata */
48679aa5d32bSDmitry Monakhov 	if (ext4_has_metadata_csum(sb)) {
4868814525f4SDarrick J. Wong 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4869814525f4SDarrick J. Wong 		__u32 csum;
4870814525f4SDarrick J. Wong 		__le32 inum = cpu_to_le32(inode->i_ino);
4871814525f4SDarrick J. Wong 		__le32 gen = raw_inode->i_generation;
4872814525f4SDarrick J. Wong 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4873814525f4SDarrick J. Wong 				   sizeof(inum));
4874814525f4SDarrick J. Wong 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4875814525f4SDarrick J. Wong 					      sizeof(gen));
4876814525f4SDarrick J. Wong 	}
4877814525f4SDarrick J. Wong 
48788016e29fSHarshad Shirwadkar 	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
48798016e29fSHarshad Shirwadkar 	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
48808016e29fSHarshad Shirwadkar 	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
48818016e29fSHarshad Shirwadkar 		ext4_error_inode_err(inode, function, line, 0,
48828016e29fSHarshad Shirwadkar 				EFSBADCRC, "iget: checksum invalid");
48836a797d27SDarrick J. Wong 		ret = -EFSBADCRC;
4884814525f4SDarrick J. Wong 		goto bad_inode;
4885814525f4SDarrick J. Wong 	}
4886814525f4SDarrick J. Wong 
4887ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
488808cefc7aSEric W. Biederman 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
488908cefc7aSEric W. Biederman 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
48900b7b7779SKaho Ng 	if (ext4_has_feature_project(sb) &&
4891040cb378SLi Xi 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4892040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4893040cb378SLi Xi 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4894040cb378SLi Xi 	else
4895040cb378SLi Xi 		i_projid = EXT4_DEF_PROJID;
4896040cb378SLi Xi 
4897ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
489808cefc7aSEric W. Biederman 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
489908cefc7aSEric W. Biederman 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4900ac27a0ecSDave Kleikamp 	}
490108cefc7aSEric W. Biederman 	i_uid_write(inode, i_uid);
490208cefc7aSEric W. Biederman 	i_gid_write(inode, i_gid);
4903040cb378SLi Xi 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4904bfe86848SMiklos Szeredi 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4905ac27a0ecSDave Kleikamp 
4906353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
490767cf5b09STao Ma 	ei->i_inline_off = 0;
4908ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
4909ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4910ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
4911ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
4912ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
4913ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
4914ac27a0ecSDave Kleikamp 	 */
4915ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
4916393d1d1dSDr. Tilmann Bubeck 		if ((inode->i_mode == 0 ||
4917393d1d1dSDr. Tilmann Bubeck 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4918393d1d1dSDr. Tilmann Bubeck 		    ino != EXT4_BOOT_LOADER_INO) {
4919ac27a0ecSDave Kleikamp 			/* this inode is deleted */
49201d1fe1eeSDavid Howells 			ret = -ESTALE;
4921ac27a0ecSDave Kleikamp 			goto bad_inode;
4922ac27a0ecSDave Kleikamp 		}
4923ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
4924ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
4925ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
4926393d1d1dSDr. Tilmann Bubeck 		 * the process of deleting those.
4927393d1d1dSDr. Tilmann Bubeck 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4928393d1d1dSDr. Tilmann Bubeck 		 * not initialized on a new filesystem. */
4929ac27a0ecSDave Kleikamp 	}
4930ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4931043546e4SIra Weiny 	ext4_set_inode_flags(inode, true);
49320fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
49337973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4934e2b911c5SDarrick J. Wong 	if (ext4_has_feature_64bit(sb))
4935a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
4936a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4937e08ac99fSArtem Blagodarenko 	inode->i_size = ext4_isize(sb, raw_inode);
49387e6e1ef4SDarrick J. Wong 	if ((size = i_size_read(inode)) < 0) {
49398a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
49408a363970STheodore Ts'o 				 "iget: bad i_size value: %lld", size);
49417e6e1ef4SDarrick J. Wong 		ret = -EFSCORRUPTED;
49427e6e1ef4SDarrick J. Wong 		goto bad_inode;
49437e6e1ef4SDarrick J. Wong 	}
494448a34311SJan Kara 	/*
494548a34311SJan Kara 	 * If dir_index is not enabled but there's dir with INDEX flag set,
494648a34311SJan Kara 	 * we'd normally treat htree data as empty space. But with metadata
494748a34311SJan Kara 	 * checksumming that corrupts checksums so forbid that.
494848a34311SJan Kara 	 */
494948a34311SJan Kara 	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
495048a34311SJan Kara 	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
495148a34311SJan Kara 		ext4_error_inode(inode, function, line, 0,
495248a34311SJan Kara 			 "iget: Dir with htree data on filesystem without dir_index feature.");
495348a34311SJan Kara 		ret = -EFSCORRUPTED;
495448a34311SJan Kara 		goto bad_inode;
495548a34311SJan Kara 	}
4956ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
4957a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
4958a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
4959a9e7f447SDmitry Monakhov #endif
4960ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4961ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
4962a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
4963ac27a0ecSDave Kleikamp 	/*
4964ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
4965ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4966ac27a0ecSDave Kleikamp 	 */
4967617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4968ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
4969ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
4970aa75f4d3SHarshad Shirwadkar 	ext4_fc_init_inode(&ei->vfs_inode);
4971ac27a0ecSDave Kleikamp 
4972b436b9beSJan Kara 	/*
4973b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
4974b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
4975b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
4976b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
4977b436b9beSJan Kara 	 * now it is reread from disk.
4978b436b9beSJan Kara 	 */
4979b436b9beSJan Kara 	if (journal) {
4980b436b9beSJan Kara 		transaction_t *transaction;
4981b436b9beSJan Kara 		tid_t tid;
4982b436b9beSJan Kara 
4983a931da6aSTheodore Ts'o 		read_lock(&journal->j_state_lock);
4984b436b9beSJan Kara 		if (journal->j_running_transaction)
4985b436b9beSJan Kara 			transaction = journal->j_running_transaction;
4986b436b9beSJan Kara 		else
4987b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
4988b436b9beSJan Kara 		if (transaction)
4989b436b9beSJan Kara 			tid = transaction->t_tid;
4990b436b9beSJan Kara 		else
4991b436b9beSJan Kara 			tid = journal->j_commit_sequence;
4992a931da6aSTheodore Ts'o 		read_unlock(&journal->j_state_lock);
4993b436b9beSJan Kara 		ei->i_sync_tid = tid;
4994b436b9beSJan Kara 		ei->i_datasync_tid = tid;
4995b436b9beSJan Kara 	}
4996b436b9beSJan Kara 
49970040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4998ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
4999ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
50002dc8d9e1SEric Biggers 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
5001617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
5002617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
5003ac27a0ecSDave Kleikamp 		} else {
5004eb9b5f01STheodore Ts'o 			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
5005eb9b5f01STheodore Ts'o 			if (ret)
5006eb9b5f01STheodore Ts'o 				goto bad_inode;
5007ac27a0ecSDave Kleikamp 		}
5008814525f4SDarrick J. Wong 	}
5009ac27a0ecSDave Kleikamp 
5010ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
5011ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
5012ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
5013ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
5014ef7f3835SKalpak Shah 
5015ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5016ee73f9a5SJeff Layton 		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
5017ee73f9a5SJeff Layton 
501825ec56b5SJean Noel Cordenner 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
501925ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5020ee73f9a5SJeff Layton 				ivers |=
502125ec56b5SJean Noel Cordenner 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
502225ec56b5SJean Noel Cordenner 		}
5023e254d1afSEryu Guan 		ext4_inode_set_iversion_queried(inode, ivers);
5024c4f65706STheodore Ts'o 	}
502525ec56b5SJean Noel Cordenner 
5026c4b5a614STheodore Ts'o 	ret = 0;
5027485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
5028ce9f24ccSJan Kara 	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
50298a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
50308a363970STheodore Ts'o 				 "iget: bad extended attribute block %llu",
503124676da4STheodore Ts'o 				 ei->i_file_acl);
50326a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
5033485c26ecSTheodore Ts'o 		goto bad_inode;
5034f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
5035bc716523SLiu Song 		/* validate the block references in the inode */
50368016e29fSHarshad Shirwadkar 		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
50378016e29fSHarshad Shirwadkar 			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5038fe2c8191SThiemo Nagel 			(S_ISLNK(inode->i_mode) &&
50398016e29fSHarshad Shirwadkar 			!ext4_inode_is_fast_symlink(inode)))) {
5040bc716523SLiu Song 			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5041bc716523SLiu Song 				ret = ext4_ext_check_inode(inode);
5042bc716523SLiu Song 			else
50431f7d1e77STheodore Ts'o 				ret = ext4_ind_check_inode(inode);
5044fe2c8191SThiemo Nagel 		}
5045f19d5870STao Ma 	}
5046567f3e9aSTheodore Ts'o 	if (ret)
50477a262f7cSAneesh Kumar K.V 		goto bad_inode;
50487a262f7cSAneesh Kumar K.V 
5049ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
5050617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
5051617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
5052617ba13bSMingming Cao 		ext4_set_aops(inode);
5053ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
5054617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
5055617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
5056ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
50576390d33bSLuis R. Rodriguez 		/* VFS does not allow setting these so must be corruption */
50586390d33bSLuis R. Rodriguez 		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
50598a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
50608a363970STheodore Ts'o 					 "iget: immutable or append flags "
50618a363970STheodore Ts'o 					 "not allowed on symlinks");
50626390d33bSLuis R. Rodriguez 			ret = -EFSCORRUPTED;
50636390d33bSLuis R. Rodriguez 			goto bad_inode;
50646390d33bSLuis R. Rodriguez 		}
5065592ddec7SChandan Rajendra 		if (IS_ENCRYPTED(inode)) {
5066a7a67e8aSAl Viro 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
5067a7a67e8aSAl Viro 		} else if (ext4_inode_is_fast_symlink(inode)) {
506875e7566bSAl Viro 			inode->i_link = (char *)ei->i_data;
5069617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
5070e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
5071e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
5072e83c1397SDuane Griffin 		} else {
5073617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
5074ac27a0ecSDave Kleikamp 		}
5075563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5076563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5077617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
5078ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
5079ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5080ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5081ac27a0ecSDave Kleikamp 		else
5082ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5083ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5084393d1d1dSDr. Tilmann Bubeck 	} else if (ino == EXT4_BOOT_LOADER_INO) {
5085393d1d1dSDr. Tilmann Bubeck 		make_bad_inode(inode);
5086563bdd61STheodore Ts'o 	} else {
50876a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
50888a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
50898a363970STheodore Ts'o 				 "iget: bogus i_mode (%o)", inode->i_mode);
5090563bdd61STheodore Ts'o 		goto bad_inode;
5091ac27a0ecSDave Kleikamp 	}
50926456ca65STheodore Ts'o 	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
50936456ca65STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
50946456ca65STheodore Ts'o 				 "casefold flag without casefold feature");
509563b1e9bcSBaokun Li 	if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD)) {
509663b1e9bcSBaokun Li 		ext4_error_inode(inode, function, line, 0,
509763b1e9bcSBaokun Li 				 "bad inode without EXT4_IGET_BAD flag");
509863b1e9bcSBaokun Li 		ret = -EUCLEAN;
509963b1e9bcSBaokun Li 		goto bad_inode;
510063b1e9bcSBaokun Li 	}
5101dec214d0STahsin Erdogan 
510263b1e9bcSBaokun Li 	brelse(iloc.bh);
51031d1fe1eeSDavid Howells 	unlock_new_inode(inode);
51041d1fe1eeSDavid Howells 	return inode;
5105ac27a0ecSDave Kleikamp 
5106ac27a0ecSDave Kleikamp bad_inode:
5107567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
51081d1fe1eeSDavid Howells 	iget_failed(inode);
51091d1fe1eeSDavid Howells 	return ERR_PTR(ret);
5110ac27a0ecSDave Kleikamp }
5111ac27a0ecSDave Kleikamp 
51123f19b2abSDavid Howells static void __ext4_update_other_inode_time(struct super_block *sb,
51133f19b2abSDavid Howells 					   unsigned long orig_ino,
51143f19b2abSDavid Howells 					   unsigned long ino,
51153f19b2abSDavid Howells 					   struct ext4_inode *raw_inode)
5116a26f4992STheodore Ts'o {
51173f19b2abSDavid Howells 	struct inode *inode;
5118a26f4992STheodore Ts'o 
51193f19b2abSDavid Howells 	inode = find_inode_by_ino_rcu(sb, ino);
51203f19b2abSDavid Howells 	if (!inode)
51213f19b2abSDavid Howells 		return;
51223f19b2abSDavid Howells 
5123ed296c6cSEric Biggers 	if (!inode_is_dirtytime_only(inode))
51243f19b2abSDavid Howells 		return;
51253f19b2abSDavid Howells 
5126a26f4992STheodore Ts'o 	spin_lock(&inode->i_lock);
5127ed296c6cSEric Biggers 	if (inode_is_dirtytime_only(inode)) {
5128a26f4992STheodore Ts'o 		struct ext4_inode_info	*ei = EXT4_I(inode);
5129a26f4992STheodore Ts'o 
51305fcd5750SJan Kara 		inode->i_state &= ~I_DIRTY_TIME;
5131a26f4992STheodore Ts'o 		spin_unlock(&inode->i_lock);
5132a26f4992STheodore Ts'o 
5133a26f4992STheodore Ts'o 		spin_lock(&ei->i_raw_lock);
51343f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
51353f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
51363f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
51373f19b2abSDavid Howells 		ext4_inode_csum_set(inode, raw_inode, ei);
5138a26f4992STheodore Ts'o 		spin_unlock(&ei->i_raw_lock);
51393f19b2abSDavid Howells 		trace_ext4_other_inode_update_time(inode, orig_ino);
51403f19b2abSDavid Howells 		return;
5141a26f4992STheodore Ts'o 	}
5142a26f4992STheodore Ts'o 	spin_unlock(&inode->i_lock);
5143a26f4992STheodore Ts'o }
5144a26f4992STheodore Ts'o 
5145a26f4992STheodore Ts'o /*
5146a26f4992STheodore Ts'o  * Opportunistically update the other time fields for other inodes in
5147a26f4992STheodore Ts'o  * the same inode table block.
5148a26f4992STheodore Ts'o  */
5149a26f4992STheodore Ts'o static void ext4_update_other_inodes_time(struct super_block *sb,
5150a26f4992STheodore Ts'o 					  unsigned long orig_ino, char *buf)
5151a26f4992STheodore Ts'o {
5152a26f4992STheodore Ts'o 	unsigned long ino;
5153a26f4992STheodore Ts'o 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5154a26f4992STheodore Ts'o 	int inode_size = EXT4_INODE_SIZE(sb);
5155a26f4992STheodore Ts'o 
51560f0ff9a9STheodore Ts'o 	/*
51570f0ff9a9STheodore Ts'o 	 * Calculate the first inode in the inode table block.  Inode
51580f0ff9a9STheodore Ts'o 	 * numbers are one-based.  That is, the first inode in a block
51590f0ff9a9STheodore Ts'o 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
51600f0ff9a9STheodore Ts'o 	 */
51610f0ff9a9STheodore Ts'o 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
51623f19b2abSDavid Howells 	rcu_read_lock();
5163a26f4992STheodore Ts'o 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5164a26f4992STheodore Ts'o 		if (ino == orig_ino)
5165a26f4992STheodore Ts'o 			continue;
51663f19b2abSDavid Howells 		__ext4_update_other_inode_time(sb, orig_ino, ino,
51673f19b2abSDavid Howells 					       (struct ext4_inode *)buf);
5168a26f4992STheodore Ts'o 	}
51693f19b2abSDavid Howells 	rcu_read_unlock();
5170a26f4992STheodore Ts'o }
5171a26f4992STheodore Ts'o 
5172664bd38bSZhang Yi /*
5173664bd38bSZhang Yi  * Post the struct inode info into an on-disk inode location in the
5174664bd38bSZhang Yi  * buffer-cache.  This gobbles the caller's reference to the
5175664bd38bSZhang Yi  * buffer_head in the inode location struct.
5176664bd38bSZhang Yi  *
5177664bd38bSZhang Yi  * The caller must have write access to iloc->bh.
5178664bd38bSZhang Yi  */
5179664bd38bSZhang Yi static int ext4_do_update_inode(handle_t *handle,
5180664bd38bSZhang Yi 				struct inode *inode,
5181664bd38bSZhang Yi 				struct ext4_iloc *iloc)
5182664bd38bSZhang Yi {
5183664bd38bSZhang Yi 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5184664bd38bSZhang Yi 	struct ext4_inode_info *ei = EXT4_I(inode);
5185664bd38bSZhang Yi 	struct buffer_head *bh = iloc->bh;
5186664bd38bSZhang Yi 	struct super_block *sb = inode->i_sb;
5187664bd38bSZhang Yi 	int err;
5188664bd38bSZhang Yi 	int need_datasync = 0, set_large_file = 0;
5189664bd38bSZhang Yi 
5190664bd38bSZhang Yi 	spin_lock(&ei->i_raw_lock);
5191664bd38bSZhang Yi 
5192664bd38bSZhang Yi 	/*
5193664bd38bSZhang Yi 	 * For fields not tracked in the in-memory inode, initialise them
5194664bd38bSZhang Yi 	 * to zero for new inodes.
5195664bd38bSZhang Yi 	 */
5196664bd38bSZhang Yi 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5197664bd38bSZhang Yi 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5198664bd38bSZhang Yi 
5199664bd38bSZhang Yi 	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5200664bd38bSZhang Yi 		need_datasync = 1;
5201664bd38bSZhang Yi 	if (ei->i_disksize > 0x7fffffffULL) {
5202664bd38bSZhang Yi 		if (!ext4_has_feature_large_file(sb) ||
5203664bd38bSZhang Yi 		    EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5204664bd38bSZhang Yi 			set_large_file = 1;
5205664bd38bSZhang Yi 	}
5206664bd38bSZhang Yi 
5207664bd38bSZhang Yi 	err = ext4_fill_raw_inode(inode, raw_inode);
5208202ee5dfSTheodore Ts'o 	spin_unlock(&ei->i_raw_lock);
5209baaae979SZhang Yi 	if (err) {
5210baaae979SZhang Yi 		EXT4_ERROR_INODE(inode, "corrupted inode contents");
5211baaae979SZhang Yi 		goto out_brelse;
5212baaae979SZhang Yi 	}
5213baaae979SZhang Yi 
52141751e8a6SLinus Torvalds 	if (inode->i_sb->s_flags & SB_LAZYTIME)
5215a26f4992STheodore Ts'o 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5216a26f4992STheodore Ts'o 					      bh->b_data);
5217202ee5dfSTheodore Ts'o 
52180390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
52197d8bd3c7SShijie Luo 	err = ext4_handle_dirty_metadata(handle, NULL, bh);
52207d8bd3c7SShijie Luo 	if (err)
5221baaae979SZhang Yi 		goto out_error;
522219f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5223202ee5dfSTheodore Ts'o 	if (set_large_file) {
52245d601255Sliang xie 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5225188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, sb,
5226188c299eSJan Kara 						    EXT4_SB(sb)->s_sbh,
5227188c299eSJan Kara 						    EXT4_JTR_NONE);
5228202ee5dfSTheodore Ts'o 		if (err)
5229baaae979SZhang Yi 			goto out_error;
523005c2c00fSJan Kara 		lock_buffer(EXT4_SB(sb)->s_sbh);
5231e2b911c5SDarrick J. Wong 		ext4_set_feature_large_file(sb);
523205c2c00fSJan Kara 		ext4_superblock_csum_set(sb);
523305c2c00fSJan Kara 		unlock_buffer(EXT4_SB(sb)->s_sbh);
5234202ee5dfSTheodore Ts'o 		ext4_handle_sync(handle);
5235a3f5cf14SJan Kara 		err = ext4_handle_dirty_metadata(handle, NULL,
5236a3f5cf14SJan Kara 						 EXT4_SB(sb)->s_sbh);
5237202ee5dfSTheodore Ts'o 	}
5238b71fc079SJan Kara 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5239baaae979SZhang Yi out_error:
5240baaae979SZhang Yi 	ext4_std_error(inode->i_sb, err);
5241ac27a0ecSDave Kleikamp out_brelse:
5242ac27a0ecSDave Kleikamp 	brelse(bh);
5243ac27a0ecSDave Kleikamp 	return err;
5244ac27a0ecSDave Kleikamp }
5245ac27a0ecSDave Kleikamp 
5246ac27a0ecSDave Kleikamp /*
5247617ba13bSMingming Cao  * ext4_write_inode()
5248ac27a0ecSDave Kleikamp  *
5249ac27a0ecSDave Kleikamp  * We are called from a few places:
5250ac27a0ecSDave Kleikamp  *
525187f7e416STheodore Ts'o  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5252ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
52534907cb7bSAnatol Pomozov  *   transaction to commit.
5254ac27a0ecSDave Kleikamp  *
525587f7e416STheodore Ts'o  * - Within flush work (sys_sync(), kupdate and such).
525687f7e416STheodore Ts'o  *   We wait on commit, if told to.
5257ac27a0ecSDave Kleikamp  *
525887f7e416STheodore Ts'o  * - Within iput_final() -> write_inode_now()
525987f7e416STheodore Ts'o  *   We wait on commit, if told to.
5260ac27a0ecSDave Kleikamp  *
5261ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
5262ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
526387f7e416STheodore Ts'o  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
526487f7e416STheodore Ts'o  * writeback.
5265ac27a0ecSDave Kleikamp  *
5266ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
5267ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5268ac27a0ecSDave Kleikamp  * which we are interested.
5269ac27a0ecSDave Kleikamp  *
5270ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
5271ac27a0ecSDave Kleikamp  *
5272ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
5273ac27a0ecSDave Kleikamp  *	stuff();
5274ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
5275ac27a0ecSDave Kleikamp  *
527687f7e416STheodore Ts'o  * is in error because write_inode() could occur while `stuff()' is running,
527787f7e416STheodore Ts'o  * and the new i_size will be lost.  Plus the inode will no longer be on the
527887f7e416STheodore Ts'o  * superblock's dirty inode list.
5279ac27a0ecSDave Kleikamp  */
5280a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5281ac27a0ecSDave Kleikamp {
528291ac6f43SFrank Mayhar 	int err;
528391ac6f43SFrank Mayhar 
528418f2c4fcSTheodore Ts'o 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
528518f2c4fcSTheodore Ts'o 	    sb_rdonly(inode->i_sb))
5286ac27a0ecSDave Kleikamp 		return 0;
5287ac27a0ecSDave Kleikamp 
528818f2c4fcSTheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
528918f2c4fcSTheodore Ts'o 		return -EIO;
529018f2c4fcSTheodore Ts'o 
529191ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
5292617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
52934978c659SJan Kara 			ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5294ac27a0ecSDave Kleikamp 			dump_stack();
5295ac27a0ecSDave Kleikamp 			return -EIO;
5296ac27a0ecSDave Kleikamp 		}
5297ac27a0ecSDave Kleikamp 
529810542c22SJan Kara 		/*
529910542c22SJan Kara 		 * No need to force transaction in WB_SYNC_NONE mode. Also
530010542c22SJan Kara 		 * ext4_sync_fs() will force the commit after everything is
530110542c22SJan Kara 		 * written.
530210542c22SJan Kara 		 */
530310542c22SJan Kara 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5304ac27a0ecSDave Kleikamp 			return 0;
5305ac27a0ecSDave Kleikamp 
5306aa75f4d3SHarshad Shirwadkar 		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
530718f2c4fcSTheodore Ts'o 						EXT4_I(inode)->i_sync_tid);
530891ac6f43SFrank Mayhar 	} else {
530991ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
531091ac6f43SFrank Mayhar 
53118016e29fSHarshad Shirwadkar 		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
531291ac6f43SFrank Mayhar 		if (err)
531391ac6f43SFrank Mayhar 			return err;
531410542c22SJan Kara 		/*
531510542c22SJan Kara 		 * sync(2) will flush the whole buffer cache. No need to do
531610542c22SJan Kara 		 * it here separately for each inode.
531710542c22SJan Kara 		 */
531810542c22SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5319830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
5320830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
532154d3adbcSTheodore Ts'o 			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5322c398eda0STheodore Ts'o 					       "IO error syncing inode");
5323830156c7SFrank Mayhar 			err = -EIO;
5324830156c7SFrank Mayhar 		}
5325fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
532691ac6f43SFrank Mayhar 	}
532791ac6f43SFrank Mayhar 	return err;
5328ac27a0ecSDave Kleikamp }
5329ac27a0ecSDave Kleikamp 
5330ac27a0ecSDave Kleikamp /*
5331ccd16945SMatthew Wilcox (Oracle)  * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5332ccd16945SMatthew Wilcox (Oracle)  * buffers that are attached to a folio straddling i_size and are undergoing
533353e87268SJan Kara  * commit. In that case we have to wait for commit to finish and try again.
533453e87268SJan Kara  */
533553e87268SJan Kara static void ext4_wait_for_tail_page_commit(struct inode *inode)
533653e87268SJan Kara {
533753e87268SJan Kara 	unsigned offset;
533853e87268SJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
533953e87268SJan Kara 	tid_t commit_tid = 0;
534053e87268SJan Kara 	int ret;
534153e87268SJan Kara 
534209cbfeafSKirill A. Shutemov 	offset = inode->i_size & (PAGE_SIZE - 1);
534353e87268SJan Kara 	/*
5344ccd16945SMatthew Wilcox (Oracle) 	 * If the folio is fully truncated, we don't need to wait for any commit
5345ccd16945SMatthew Wilcox (Oracle) 	 * (and we even should not as __ext4_journalled_invalidate_folio() may
5346ccd16945SMatthew Wilcox (Oracle) 	 * strip all buffers from the folio but keep the folio dirty which can then
5347ccd16945SMatthew Wilcox (Oracle) 	 * confuse e.g. concurrent ext4_writepage() seeing dirty folio without
5348565333a1Syangerkun 	 * buffers). Also we don't need to wait for any commit if all buffers in
5349ccd16945SMatthew Wilcox (Oracle) 	 * the folio remain valid. This is most beneficial for the common case of
5350565333a1Syangerkun 	 * blocksize == PAGESIZE.
535153e87268SJan Kara 	 */
5352565333a1Syangerkun 	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
535353e87268SJan Kara 		return;
535453e87268SJan Kara 	while (1) {
5355ccd16945SMatthew Wilcox (Oracle) 		struct folio *folio = filemap_lock_folio(inode->i_mapping,
535609cbfeafSKirill A. Shutemov 				      inode->i_size >> PAGE_SHIFT);
5357ccd16945SMatthew Wilcox (Oracle) 		if (!folio)
535853e87268SJan Kara 			return;
5359ccd16945SMatthew Wilcox (Oracle) 		ret = __ext4_journalled_invalidate_folio(folio, offset,
5360ccd16945SMatthew Wilcox (Oracle) 						folio_size(folio) - offset);
5361ccd16945SMatthew Wilcox (Oracle) 		folio_unlock(folio);
5362ccd16945SMatthew Wilcox (Oracle) 		folio_put(folio);
536353e87268SJan Kara 		if (ret != -EBUSY)
536453e87268SJan Kara 			return;
536553e87268SJan Kara 		commit_tid = 0;
536653e87268SJan Kara 		read_lock(&journal->j_state_lock);
536753e87268SJan Kara 		if (journal->j_committing_transaction)
536853e87268SJan Kara 			commit_tid = journal->j_committing_transaction->t_tid;
536953e87268SJan Kara 		read_unlock(&journal->j_state_lock);
537053e87268SJan Kara 		if (commit_tid)
537153e87268SJan Kara 			jbd2_log_wait_commit(journal, commit_tid);
537253e87268SJan Kara 	}
537353e87268SJan Kara }
537453e87268SJan Kara 
537553e87268SJan Kara /*
5376617ba13bSMingming Cao  * ext4_setattr()
5377ac27a0ecSDave Kleikamp  *
5378ac27a0ecSDave Kleikamp  * Called from notify_change.
5379ac27a0ecSDave Kleikamp  *
5380ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
5381ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
5382ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
5383ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
5384ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
5385ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
5386ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
5387ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
5388ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
5389ac27a0ecSDave Kleikamp  *
5390678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
5391678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
5392678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
5393678aaf48SJan Kara  * This way we are sure that all the data written in the previous
5394678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
5395678aaf48SJan Kara  * writeback).
5396678aaf48SJan Kara  *
5397f340b3d9Shongnanli  * Called with inode->i_rwsem down.
5398ac27a0ecSDave Kleikamp  */
5399549c7297SChristian Brauner int ext4_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5400549c7297SChristian Brauner 		 struct iattr *attr)
5401ac27a0ecSDave Kleikamp {
54022b0143b5SDavid Howells 	struct inode *inode = d_inode(dentry);
5403ac27a0ecSDave Kleikamp 	int error, rc = 0;
54043d287de3SDmitry Monakhov 	int orphan = 0;
5405ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
5406a642c2c0SJeff Layton 	bool inc_ivers = true;
5407ac27a0ecSDave Kleikamp 
54080db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
54090db1ff22STheodore Ts'o 		return -EIO;
54100db1ff22STheodore Ts'o 
541102b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
541202b016caSTheodore Ts'o 		return -EPERM;
541302b016caSTheodore Ts'o 
541402b016caSTheodore Ts'o 	if (unlikely(IS_APPEND(inode) &&
541502b016caSTheodore Ts'o 		     (ia_valid & (ATTR_MODE | ATTR_UID |
541602b016caSTheodore Ts'o 				  ATTR_GID | ATTR_TIMES_SET))))
541702b016caSTheodore Ts'o 		return -EPERM;
541802b016caSTheodore Ts'o 
541914f3db55SChristian Brauner 	error = setattr_prepare(mnt_userns, dentry, attr);
5420ac27a0ecSDave Kleikamp 	if (error)
5421ac27a0ecSDave Kleikamp 		return error;
5422ac27a0ecSDave Kleikamp 
54233ce2b8ddSEric Biggers 	error = fscrypt_prepare_setattr(dentry, attr);
54243ce2b8ddSEric Biggers 	if (error)
54253ce2b8ddSEric Biggers 		return error;
54263ce2b8ddSEric Biggers 
5427c93d8f88SEric Biggers 	error = fsverity_prepare_setattr(dentry, attr);
5428c93d8f88SEric Biggers 	if (error)
5429c93d8f88SEric Biggers 		return error;
5430c93d8f88SEric Biggers 
5431b27c82e1SChristian Brauner 	if (is_quota_modification(mnt_userns, inode, attr)) {
5432a7cdadeeSJan Kara 		error = dquot_initialize(inode);
5433a7cdadeeSJan Kara 		if (error)
5434a7cdadeeSJan Kara 			return error;
5435a7cdadeeSJan Kara 	}
54362729cfdcSHarshad Shirwadkar 
5437b27c82e1SChristian Brauner 	if (i_uid_needs_update(mnt_userns, attr, inode) ||
5438b27c82e1SChristian Brauner 	    i_gid_needs_update(mnt_userns, attr, inode)) {
5439ac27a0ecSDave Kleikamp 		handle_t *handle;
5440ac27a0ecSDave Kleikamp 
5441ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
5442ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
54439924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
54449924a92aSTheodore Ts'o 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5445194074acSDmitry Monakhov 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5446ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
5447ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
5448ac27a0ecSDave Kleikamp 			goto err_out;
5449ac27a0ecSDave Kleikamp 		}
54507a9ca53aSTahsin Erdogan 
54517a9ca53aSTahsin Erdogan 		/* dquot_transfer() calls back ext4_get_inode_usage() which
54527a9ca53aSTahsin Erdogan 		 * counts xattr inode references.
54537a9ca53aSTahsin Erdogan 		 */
54547a9ca53aSTahsin Erdogan 		down_read(&EXT4_I(inode)->xattr_sem);
5455b27c82e1SChristian Brauner 		error = dquot_transfer(mnt_userns, inode, attr);
54567a9ca53aSTahsin Erdogan 		up_read(&EXT4_I(inode)->xattr_sem);
54577a9ca53aSTahsin Erdogan 
5458ac27a0ecSDave Kleikamp 		if (error) {
5459617ba13bSMingming Cao 			ext4_journal_stop(handle);
5460ac27a0ecSDave Kleikamp 			return error;
5461ac27a0ecSDave Kleikamp 		}
5462ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
5463ac27a0ecSDave Kleikamp 		 * one transaction */
5464b27c82e1SChristian Brauner 		i_uid_update(mnt_userns, attr, inode);
5465b27c82e1SChristian Brauner 		i_gid_update(mnt_userns, attr, inode);
5466617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
5467617ba13bSMingming Cao 		ext4_journal_stop(handle);
5468512c15efSPan Bian 		if (unlikely(error)) {
54694209ae12SHarshad Shirwadkar 			return error;
5470ac27a0ecSDave Kleikamp 		}
5471512c15efSPan Bian 	}
5472ac27a0ecSDave Kleikamp 
54733da40c7bSJosef Bacik 	if (attr->ia_valid & ATTR_SIZE) {
54745208386cSJan Kara 		handle_t *handle;
54753da40c7bSJosef Bacik 		loff_t oldsize = inode->i_size;
5476f4534c9fSYe Bin 		loff_t old_disksize;
5477b9c1c267SJan Kara 		int shrink = (attr->ia_size < inode->i_size);
5478562c72aaSChristoph Hellwig 
547912e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5480e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5481e2b46574SEric Sandeen 
5482aa75f4d3SHarshad Shirwadkar 			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
54830c095c7fSTheodore Ts'o 				return -EFBIG;
5484e2b46574SEric Sandeen 			}
5485aa75f4d3SHarshad Shirwadkar 		}
5486aa75f4d3SHarshad Shirwadkar 		if (!S_ISREG(inode->i_mode)) {
54873da40c7bSJosef Bacik 			return -EINVAL;
5488aa75f4d3SHarshad Shirwadkar 		}
5489dff6efc3SChristoph Hellwig 
5490a642c2c0SJeff Layton 		if (attr->ia_size == inode->i_size)
5491a642c2c0SJeff Layton 			inc_ivers = false;
5492dff6efc3SChristoph Hellwig 
5493b9c1c267SJan Kara 		if (shrink) {
5494b9c1c267SJan Kara 			if (ext4_should_order_data(inode)) {
54955208386cSJan Kara 				error = ext4_begin_ordered_truncate(inode,
54965208386cSJan Kara 							    attr->ia_size);
54975208386cSJan Kara 				if (error)
54985208386cSJan Kara 					goto err_out;
54995208386cSJan Kara 			}
5500b9c1c267SJan Kara 			/*
5501b9c1c267SJan Kara 			 * Blocks are going to be removed from the inode. Wait
5502b9c1c267SJan Kara 			 * for dio in flight.
5503b9c1c267SJan Kara 			 */
5504b9c1c267SJan Kara 			inode_dio_wait(inode);
5505b9c1c267SJan Kara 		}
5506b9c1c267SJan Kara 
5507d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
5508b9c1c267SJan Kara 
5509b9c1c267SJan Kara 		rc = ext4_break_layouts(inode);
5510b9c1c267SJan Kara 		if (rc) {
5511d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
5512aa75f4d3SHarshad Shirwadkar 			goto err_out;
5513b9c1c267SJan Kara 		}
5514b9c1c267SJan Kara 
55153da40c7bSJosef Bacik 		if (attr->ia_size != inode->i_size) {
55169924a92aSTheodore Ts'o 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5517ac27a0ecSDave Kleikamp 			if (IS_ERR(handle)) {
5518ac27a0ecSDave Kleikamp 				error = PTR_ERR(handle);
5519b9c1c267SJan Kara 				goto out_mmap_sem;
5520ac27a0ecSDave Kleikamp 			}
55213da40c7bSJosef Bacik 			if (ext4_handle_valid(handle) && shrink) {
5522617ba13bSMingming Cao 				error = ext4_orphan_add(handle, inode);
55233d287de3SDmitry Monakhov 				orphan = 1;
55243d287de3SDmitry Monakhov 			}
5525911af577SEryu Guan 			/*
5526911af577SEryu Guan 			 * Update c/mtime on truncate up, ext4_truncate() will
5527911af577SEryu Guan 			 * update c/mtime in shrink case below
5528911af577SEryu Guan 			 */
5529911af577SEryu Guan 			if (!shrink) {
5530eeca7ea1SDeepa Dinamani 				inode->i_mtime = current_time(inode);
5531911af577SEryu Guan 				inode->i_ctime = inode->i_mtime;
5532911af577SEryu Guan 			}
5533aa75f4d3SHarshad Shirwadkar 
5534aa75f4d3SHarshad Shirwadkar 			if (shrink)
5535a80f7fcfSHarshad Shirwadkar 				ext4_fc_track_range(handle, inode,
5536aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5537aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
55389725958bSXin Yin 					EXT_MAX_BLOCKS - 1);
5539aa75f4d3SHarshad Shirwadkar 			else
5540aa75f4d3SHarshad Shirwadkar 				ext4_fc_track_range(
5541a80f7fcfSHarshad Shirwadkar 					handle, inode,
5542aa75f4d3SHarshad Shirwadkar 					(oldsize > 0 ? oldsize - 1 : oldsize) >>
5543aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
5544aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5545aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits);
5546aa75f4d3SHarshad Shirwadkar 
554790e775b7SJan Kara 			down_write(&EXT4_I(inode)->i_data_sem);
5548f4534c9fSYe Bin 			old_disksize = EXT4_I(inode)->i_disksize;
5549617ba13bSMingming Cao 			EXT4_I(inode)->i_disksize = attr->ia_size;
5550617ba13bSMingming Cao 			rc = ext4_mark_inode_dirty(handle, inode);
5551ac27a0ecSDave Kleikamp 			if (!error)
5552ac27a0ecSDave Kleikamp 				error = rc;
555390e775b7SJan Kara 			/*
555490e775b7SJan Kara 			 * We have to update i_size under i_data_sem together
555590e775b7SJan Kara 			 * with i_disksize to avoid races with writeback code
555690e775b7SJan Kara 			 * running ext4_wb_update_i_disksize().
555790e775b7SJan Kara 			 */
555890e775b7SJan Kara 			if (!error)
555990e775b7SJan Kara 				i_size_write(inode, attr->ia_size);
5560f4534c9fSYe Bin 			else
5561f4534c9fSYe Bin 				EXT4_I(inode)->i_disksize = old_disksize;
556290e775b7SJan Kara 			up_write(&EXT4_I(inode)->i_data_sem);
5563617ba13bSMingming Cao 			ext4_journal_stop(handle);
5564b9c1c267SJan Kara 			if (error)
5565b9c1c267SJan Kara 				goto out_mmap_sem;
556682a25b02SJan Kara 			if (!shrink) {
5567b9c1c267SJan Kara 				pagecache_isize_extended(inode, oldsize,
5568b9c1c267SJan Kara 							 inode->i_size);
5569b9c1c267SJan Kara 			} else if (ext4_should_journal_data(inode)) {
557082a25b02SJan Kara 				ext4_wait_for_tail_page_commit(inode);
5571b9c1c267SJan Kara 			}
5572430657b6SRoss Zwisler 		}
5573430657b6SRoss Zwisler 
557453e87268SJan Kara 		/*
557553e87268SJan Kara 		 * Truncate pagecache after we've waited for commit
557653e87268SJan Kara 		 * in data=journal mode to make pages freeable.
557753e87268SJan Kara 		 */
55787caef267SKirill A. Shutemov 		truncate_pagecache(inode, inode->i_size);
5579b9c1c267SJan Kara 		/*
5580b9c1c267SJan Kara 		 * Call ext4_truncate() even if i_size didn't change to
5581b9c1c267SJan Kara 		 * truncate possible preallocated blocks.
5582b9c1c267SJan Kara 		 */
5583b9c1c267SJan Kara 		if (attr->ia_size <= oldsize) {
55842c98eb5eSTheodore Ts'o 			rc = ext4_truncate(inode);
55852c98eb5eSTheodore Ts'o 			if (rc)
55862c98eb5eSTheodore Ts'o 				error = rc;
55872c98eb5eSTheodore Ts'o 		}
5588b9c1c267SJan Kara out_mmap_sem:
5589d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
55903da40c7bSJosef Bacik 	}
5591ac27a0ecSDave Kleikamp 
55922c98eb5eSTheodore Ts'o 	if (!error) {
5593a642c2c0SJeff Layton 		if (inc_ivers)
5594a642c2c0SJeff Layton 			inode_inc_iversion(inode);
559514f3db55SChristian Brauner 		setattr_copy(mnt_userns, inode, attr);
55961025774cSChristoph Hellwig 		mark_inode_dirty(inode);
55971025774cSChristoph Hellwig 	}
55981025774cSChristoph Hellwig 
55991025774cSChristoph Hellwig 	/*
56001025774cSChristoph Hellwig 	 * If the call to ext4_truncate failed to get a transaction handle at
56011025774cSChristoph Hellwig 	 * all, we need to clean up the in-core orphan list manually.
56021025774cSChristoph Hellwig 	 */
56033d287de3SDmitry Monakhov 	if (orphan && inode->i_nlink)
5604617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
5605ac27a0ecSDave Kleikamp 
56062c98eb5eSTheodore Ts'o 	if (!error && (ia_valid & ATTR_MODE))
560714f3db55SChristian Brauner 		rc = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5608ac27a0ecSDave Kleikamp 
5609ac27a0ecSDave Kleikamp err_out:
5610aa75f4d3SHarshad Shirwadkar 	if  (error)
5611617ba13bSMingming Cao 		ext4_std_error(inode->i_sb, error);
5612ac27a0ecSDave Kleikamp 	if (!error)
5613ac27a0ecSDave Kleikamp 		error = rc;
5614ac27a0ecSDave Kleikamp 	return error;
5615ac27a0ecSDave Kleikamp }
5616ac27a0ecSDave Kleikamp 
56178434ef1dSEric Biggers u32 ext4_dio_alignment(struct inode *inode)
56188434ef1dSEric Biggers {
56198434ef1dSEric Biggers 	if (fsverity_active(inode))
56208434ef1dSEric Biggers 		return 0;
56218434ef1dSEric Biggers 	if (ext4_should_journal_data(inode))
56228434ef1dSEric Biggers 		return 0;
56238434ef1dSEric Biggers 	if (ext4_has_inline_data(inode))
56248434ef1dSEric Biggers 		return 0;
56258434ef1dSEric Biggers 	if (IS_ENCRYPTED(inode)) {
56268434ef1dSEric Biggers 		if (!fscrypt_dio_supported(inode))
56278434ef1dSEric Biggers 			return 0;
56288434ef1dSEric Biggers 		return i_blocksize(inode);
56298434ef1dSEric Biggers 	}
56308434ef1dSEric Biggers 	return 1; /* use the iomap defaults */
56318434ef1dSEric Biggers }
56328434ef1dSEric Biggers 
5633549c7297SChristian Brauner int ext4_getattr(struct user_namespace *mnt_userns, const struct path *path,
5634549c7297SChristian Brauner 		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
56353e3398a0SMingming Cao {
563699652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
563799652ea5SDavid Howells 	struct ext4_inode *raw_inode;
563899652ea5SDavid Howells 	struct ext4_inode_info *ei = EXT4_I(inode);
563999652ea5SDavid Howells 	unsigned int flags;
56403e3398a0SMingming Cao 
5641d4c5e960STheodore Ts'o 	if ((request_mask & STATX_BTIME) &&
5642d4c5e960STheodore Ts'o 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
564399652ea5SDavid Howells 		stat->result_mask |= STATX_BTIME;
564499652ea5SDavid Howells 		stat->btime.tv_sec = ei->i_crtime.tv_sec;
564599652ea5SDavid Howells 		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
564699652ea5SDavid Howells 	}
564799652ea5SDavid Howells 
56488434ef1dSEric Biggers 	/*
56498434ef1dSEric Biggers 	 * Return the DIO alignment restrictions if requested.  We only return
56508434ef1dSEric Biggers 	 * this information when requested, since on encrypted files it might
56518434ef1dSEric Biggers 	 * take a fair bit of work to get if the file wasn't opened recently.
56528434ef1dSEric Biggers 	 */
56538434ef1dSEric Biggers 	if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
56548434ef1dSEric Biggers 		u32 dio_align = ext4_dio_alignment(inode);
56558434ef1dSEric Biggers 
56568434ef1dSEric Biggers 		stat->result_mask |= STATX_DIOALIGN;
56578434ef1dSEric Biggers 		if (dio_align == 1) {
56588434ef1dSEric Biggers 			struct block_device *bdev = inode->i_sb->s_bdev;
56598434ef1dSEric Biggers 
56608434ef1dSEric Biggers 			/* iomap defaults */
56618434ef1dSEric Biggers 			stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
56628434ef1dSEric Biggers 			stat->dio_offset_align = bdev_logical_block_size(bdev);
56638434ef1dSEric Biggers 		} else {
56648434ef1dSEric Biggers 			stat->dio_mem_align = dio_align;
56658434ef1dSEric Biggers 			stat->dio_offset_align = dio_align;
56668434ef1dSEric Biggers 		}
56678434ef1dSEric Biggers 	}
56688434ef1dSEric Biggers 
566999652ea5SDavid Howells 	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
567099652ea5SDavid Howells 	if (flags & EXT4_APPEND_FL)
567199652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_APPEND;
567299652ea5SDavid Howells 	if (flags & EXT4_COMPR_FL)
567399652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_COMPRESSED;
567499652ea5SDavid Howells 	if (flags & EXT4_ENCRYPT_FL)
567599652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_ENCRYPTED;
567699652ea5SDavid Howells 	if (flags & EXT4_IMMUTABLE_FL)
567799652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_IMMUTABLE;
567899652ea5SDavid Howells 	if (flags & EXT4_NODUMP_FL)
567999652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_NODUMP;
56801f607195SEric Biggers 	if (flags & EXT4_VERITY_FL)
56811f607195SEric Biggers 		stat->attributes |= STATX_ATTR_VERITY;
568299652ea5SDavid Howells 
56833209f68bSDavid Howells 	stat->attributes_mask |= (STATX_ATTR_APPEND |
56843209f68bSDavid Howells 				  STATX_ATTR_COMPRESSED |
56853209f68bSDavid Howells 				  STATX_ATTR_ENCRYPTED |
56863209f68bSDavid Howells 				  STATX_ATTR_IMMUTABLE |
56871f607195SEric Biggers 				  STATX_ATTR_NODUMP |
56881f607195SEric Biggers 				  STATX_ATTR_VERITY);
56893209f68bSDavid Howells 
569014f3db55SChristian Brauner 	generic_fillattr(mnt_userns, inode, stat);
569199652ea5SDavid Howells 	return 0;
569299652ea5SDavid Howells }
569399652ea5SDavid Howells 
5694549c7297SChristian Brauner int ext4_file_getattr(struct user_namespace *mnt_userns,
5695549c7297SChristian Brauner 		      const struct path *path, struct kstat *stat,
569699652ea5SDavid Howells 		      u32 request_mask, unsigned int query_flags)
569799652ea5SDavid Howells {
569899652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
569999652ea5SDavid Howells 	u64 delalloc_blocks;
570099652ea5SDavid Howells 
570114f3db55SChristian Brauner 	ext4_getattr(mnt_userns, path, stat, request_mask, query_flags);
57023e3398a0SMingming Cao 
57033e3398a0SMingming Cao 	/*
57049206c561SAndreas Dilger 	 * If there is inline data in the inode, the inode will normally not
57059206c561SAndreas Dilger 	 * have data blocks allocated (it may have an external xattr block).
57069206c561SAndreas Dilger 	 * Report at least one sector for such files, so tools like tar, rsync,
5707d67d64f4STheodore Ts'o 	 * others don't incorrectly think the file is completely sparse.
57089206c561SAndreas Dilger 	 */
57099206c561SAndreas Dilger 	if (unlikely(ext4_has_inline_data(inode)))
57109206c561SAndreas Dilger 		stat->blocks += (stat->size + 511) >> 9;
57119206c561SAndreas Dilger 
57129206c561SAndreas Dilger 	/*
57133e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
57143e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
57153e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
57163e3398a0SMingming Cao 	 * on-disk file blocks.
57173e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
57183e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
57193e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
57203e3398a0SMingming Cao 	 * blocks for this file.
57213e3398a0SMingming Cao 	 */
572296607551STao Ma 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
572396607551STao Ma 				   EXT4_I(inode)->i_reserved_data_blocks);
57248af8eeccSJan Kara 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
57253e3398a0SMingming Cao 	return 0;
57263e3398a0SMingming Cao }
5727ac27a0ecSDave Kleikamp 
5728fffb2739SJan Kara static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5729fffb2739SJan Kara 				   int pextents)
5730a02908f1SMingming Cao {
573112e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5732fffb2739SJan Kara 		return ext4_ind_trans_blocks(inode, lblocks);
5733fffb2739SJan Kara 	return ext4_ext_index_trans_blocks(inode, pextents);
5734a02908f1SMingming Cao }
5735ac51d837STheodore Ts'o 
5736a02908f1SMingming Cao /*
5737a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
5738a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
5739a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
5740a02908f1SMingming Cao  *
5741a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
57424907cb7bSAnatol Pomozov  * different block groups too. If they are contiguous, with flexbg,
5743a02908f1SMingming Cao  * they could still across block group boundary.
5744a02908f1SMingming Cao  *
5745a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
5746a02908f1SMingming Cao  */
5747dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5748fffb2739SJan Kara 				  int pextents)
5749a02908f1SMingming Cao {
57508df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
57518df9675fSTheodore Ts'o 	int gdpblocks;
5752a02908f1SMingming Cao 	int idxblocks;
5753a02908f1SMingming Cao 	int ret = 0;
5754a02908f1SMingming Cao 
5755a02908f1SMingming Cao 	/*
5756fffb2739SJan Kara 	 * How many index blocks need to touch to map @lblocks logical blocks
5757fffb2739SJan Kara 	 * to @pextents physical extents?
5758a02908f1SMingming Cao 	 */
5759fffb2739SJan Kara 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5760a02908f1SMingming Cao 
5761a02908f1SMingming Cao 	ret = idxblocks;
5762a02908f1SMingming Cao 
5763a02908f1SMingming Cao 	/*
5764a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
5765a02908f1SMingming Cao 	 * to account
5766a02908f1SMingming Cao 	 */
5767fffb2739SJan Kara 	groups = idxblocks + pextents;
5768a02908f1SMingming Cao 	gdpblocks = groups;
57698df9675fSTheodore Ts'o 	if (groups > ngroups)
57708df9675fSTheodore Ts'o 		groups = ngroups;
5771a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5772a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5773a02908f1SMingming Cao 
5774a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
5775a02908f1SMingming Cao 	ret += groups + gdpblocks;
5776a02908f1SMingming Cao 
5777a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
5778a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5779ac27a0ecSDave Kleikamp 
5780ac27a0ecSDave Kleikamp 	return ret;
5781ac27a0ecSDave Kleikamp }
5782ac27a0ecSDave Kleikamp 
5783ac27a0ecSDave Kleikamp /*
578425985edcSLucas De Marchi  * Calculate the total number of credits to reserve to fit
5785f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
5786f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
5787a02908f1SMingming Cao  *
5788525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
5789a02908f1SMingming Cao  *
5790525f4ed8SMingming Cao  * We need to consider the worse case, when
5791a02908f1SMingming Cao  * one new block per extent.
5792a02908f1SMingming Cao  */
5793a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
5794a02908f1SMingming Cao {
5795a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
5796a02908f1SMingming Cao 	int ret;
5797a02908f1SMingming Cao 
5798fffb2739SJan Kara 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5799a02908f1SMingming Cao 
5800a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
5801a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
5802a02908f1SMingming Cao 		ret += bpp;
5803a02908f1SMingming Cao 	return ret;
5804a02908f1SMingming Cao }
5805f3bd1f3fSMingming Cao 
5806f3bd1f3fSMingming Cao /*
5807f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
5808f3bd1f3fSMingming Cao  *
5809f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
581079e83036SEric Sandeen  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5811f3bd1f3fSMingming Cao  *
5812f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
5813f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
5814f3bd1f3fSMingming Cao  */
5815f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5816f3bd1f3fSMingming Cao {
5817f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5818f3bd1f3fSMingming Cao }
5819f3bd1f3fSMingming Cao 
5820a02908f1SMingming Cao /*
5821617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
5822ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
5823ac27a0ecSDave Kleikamp  */
5824617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
5825617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
5826ac27a0ecSDave Kleikamp {
5827ac27a0ecSDave Kleikamp 	int err = 0;
5828ac27a0ecSDave Kleikamp 
5829a6758309SVasily Averin 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5830a6758309SVasily Averin 		put_bh(iloc->bh);
58310db1ff22STheodore Ts'o 		return -EIO;
5832a6758309SVasily Averin 	}
5833a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_inode(handle, inode);
5834aa75f4d3SHarshad Shirwadkar 
5835ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
5836ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
5837ac27a0ecSDave Kleikamp 
5838dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5839830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
5840ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
5841ac27a0ecSDave Kleikamp 	return err;
5842ac27a0ecSDave Kleikamp }
5843ac27a0ecSDave Kleikamp 
5844ac27a0ecSDave Kleikamp /*
5845ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
5846ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
5847ac27a0ecSDave Kleikamp  */
5848ac27a0ecSDave Kleikamp 
5849ac27a0ecSDave Kleikamp int
5850617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5851617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
5852ac27a0ecSDave Kleikamp {
58530390131bSFrank Mayhar 	int err;
58540390131bSFrank Mayhar 
58550db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
58560db1ff22STheodore Ts'o 		return -EIO;
58570db1ff22STheodore Ts'o 
5858617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
5859ac27a0ecSDave Kleikamp 	if (!err) {
5860ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
5861188c299eSJan Kara 		err = ext4_journal_get_write_access(handle, inode->i_sb,
5862188c299eSJan Kara 						    iloc->bh, EXT4_JTR_NONE);
5863ac27a0ecSDave Kleikamp 		if (err) {
5864ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
5865ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
5866ac27a0ecSDave Kleikamp 		}
5867ac27a0ecSDave Kleikamp 	}
5868617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5869ac27a0ecSDave Kleikamp 	return err;
5870ac27a0ecSDave Kleikamp }
5871ac27a0ecSDave Kleikamp 
5872c03b45b8SMiao Xie static int __ext4_expand_extra_isize(struct inode *inode,
5873c03b45b8SMiao Xie 				     unsigned int new_extra_isize,
5874c03b45b8SMiao Xie 				     struct ext4_iloc *iloc,
5875c03b45b8SMiao Xie 				     handle_t *handle, int *no_expand)
5876c03b45b8SMiao Xie {
5877c03b45b8SMiao Xie 	struct ext4_inode *raw_inode;
5878c03b45b8SMiao Xie 	struct ext4_xattr_ibody_header *header;
58794ea99936STheodore Ts'o 	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
58804ea99936STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
5881c03b45b8SMiao Xie 	int error;
5882c03b45b8SMiao Xie 
58834ea99936STheodore Ts'o 	/* this was checked at iget time, but double check for good measure */
58844ea99936STheodore Ts'o 	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
58854ea99936STheodore Ts'o 	    (ei->i_extra_isize & 3)) {
58864ea99936STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
58874ea99936STheodore Ts'o 				 ei->i_extra_isize,
58884ea99936STheodore Ts'o 				 EXT4_INODE_SIZE(inode->i_sb));
58894ea99936STheodore Ts'o 		return -EFSCORRUPTED;
58904ea99936STheodore Ts'o 	}
58914ea99936STheodore Ts'o 	if ((new_extra_isize < ei->i_extra_isize) ||
58924ea99936STheodore Ts'o 	    (new_extra_isize < 4) ||
58934ea99936STheodore Ts'o 	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
58944ea99936STheodore Ts'o 		return -EINVAL;	/* Should never happen */
58954ea99936STheodore Ts'o 
5896c03b45b8SMiao Xie 	raw_inode = ext4_raw_inode(iloc);
5897c03b45b8SMiao Xie 
5898c03b45b8SMiao Xie 	header = IHDR(inode, raw_inode);
5899c03b45b8SMiao Xie 
5900c03b45b8SMiao Xie 	/* No extended attributes present */
5901c03b45b8SMiao Xie 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5902c03b45b8SMiao Xie 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5903c03b45b8SMiao Xie 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5904c03b45b8SMiao Xie 		       EXT4_I(inode)->i_extra_isize, 0,
5905c03b45b8SMiao Xie 		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
5906c03b45b8SMiao Xie 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
5907c03b45b8SMiao Xie 		return 0;
5908c03b45b8SMiao Xie 	}
5909c03b45b8SMiao Xie 
5910c03b45b8SMiao Xie 	/* try to expand with EAs present */
5911c03b45b8SMiao Xie 	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5912c03b45b8SMiao Xie 					   raw_inode, handle);
5913c03b45b8SMiao Xie 	if (error) {
5914c03b45b8SMiao Xie 		/*
5915c03b45b8SMiao Xie 		 * Inode size expansion failed; don't try again
5916c03b45b8SMiao Xie 		 */
5917c03b45b8SMiao Xie 		*no_expand = 1;
5918c03b45b8SMiao Xie 	}
5919c03b45b8SMiao Xie 
5920c03b45b8SMiao Xie 	return error;
5921c03b45b8SMiao Xie }
5922c03b45b8SMiao Xie 
5923ac27a0ecSDave Kleikamp /*
59246dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
59256dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
59266dd4ee7cSKalpak Shah  */
5927cf0a5e81SMiao Xie static int ext4_try_to_expand_extra_isize(struct inode *inode,
59281d03ec98SAneesh Kumar K.V 					  unsigned int new_extra_isize,
59291d03ec98SAneesh Kumar K.V 					  struct ext4_iloc iloc,
59301d03ec98SAneesh Kumar K.V 					  handle_t *handle)
59316dd4ee7cSKalpak Shah {
59323b10fdc6SMiao Xie 	int no_expand;
59333b10fdc6SMiao Xie 	int error;
59346dd4ee7cSKalpak Shah 
5935cf0a5e81SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5936cf0a5e81SMiao Xie 		return -EOVERFLOW;
5937cf0a5e81SMiao Xie 
5938cf0a5e81SMiao Xie 	/*
5939cf0a5e81SMiao Xie 	 * In nojournal mode, we can immediately attempt to expand
5940cf0a5e81SMiao Xie 	 * the inode.  When journaled, we first need to obtain extra
5941cf0a5e81SMiao Xie 	 * buffer credits since we may write into the EA block
5942cf0a5e81SMiao Xie 	 * with this same handle. If journal_extend fails, then it will
5943cf0a5e81SMiao Xie 	 * only result in a minor loss of functionality for that inode.
5944cf0a5e81SMiao Xie 	 * If this is felt to be critical, then e2fsck should be run to
5945cf0a5e81SMiao Xie 	 * force a large enough s_min_extra_isize.
5946cf0a5e81SMiao Xie 	 */
59476cb367c2SJan Kara 	if (ext4_journal_extend(handle,
594883448bdfSJan Kara 				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5949cf0a5e81SMiao Xie 		return -ENOSPC;
59506dd4ee7cSKalpak Shah 
59513b10fdc6SMiao Xie 	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5952cf0a5e81SMiao Xie 		return -EBUSY;
59533b10fdc6SMiao Xie 
5954c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5955c03b45b8SMiao Xie 					  handle, &no_expand);
59563b10fdc6SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5957c03b45b8SMiao Xie 
5958c03b45b8SMiao Xie 	return error;
59596dd4ee7cSKalpak Shah }
59606dd4ee7cSKalpak Shah 
5961c03b45b8SMiao Xie int ext4_expand_extra_isize(struct inode *inode,
5962c03b45b8SMiao Xie 			    unsigned int new_extra_isize,
5963c03b45b8SMiao Xie 			    struct ext4_iloc *iloc)
5964c03b45b8SMiao Xie {
5965c03b45b8SMiao Xie 	handle_t *handle;
5966c03b45b8SMiao Xie 	int no_expand;
5967c03b45b8SMiao Xie 	int error, rc;
5968c03b45b8SMiao Xie 
5969c03b45b8SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5970c03b45b8SMiao Xie 		brelse(iloc->bh);
5971c03b45b8SMiao Xie 		return -EOVERFLOW;
5972c03b45b8SMiao Xie 	}
5973c03b45b8SMiao Xie 
5974c03b45b8SMiao Xie 	handle = ext4_journal_start(inode, EXT4_HT_INODE,
5975c03b45b8SMiao Xie 				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5976c03b45b8SMiao Xie 	if (IS_ERR(handle)) {
5977c03b45b8SMiao Xie 		error = PTR_ERR(handle);
5978c03b45b8SMiao Xie 		brelse(iloc->bh);
5979c03b45b8SMiao Xie 		return error;
5980c03b45b8SMiao Xie 	}
5981c03b45b8SMiao Xie 
5982c03b45b8SMiao Xie 	ext4_write_lock_xattr(inode, &no_expand);
5983c03b45b8SMiao Xie 
5984ddccb6dbSzhangyi (F) 	BUFFER_TRACE(iloc->bh, "get_write_access");
5985188c299eSJan Kara 	error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
5986188c299eSJan Kara 					      EXT4_JTR_NONE);
59873b10fdc6SMiao Xie 	if (error) {
5988c03b45b8SMiao Xie 		brelse(iloc->bh);
59897f420d64SDan Carpenter 		goto out_unlock;
59903b10fdc6SMiao Xie 	}
5991cf0a5e81SMiao Xie 
5992c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5993c03b45b8SMiao Xie 					  handle, &no_expand);
5994c03b45b8SMiao Xie 
5995c03b45b8SMiao Xie 	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5996c03b45b8SMiao Xie 	if (!error)
5997c03b45b8SMiao Xie 		error = rc;
5998c03b45b8SMiao Xie 
59997f420d64SDan Carpenter out_unlock:
6000c03b45b8SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
6001c03b45b8SMiao Xie 	ext4_journal_stop(handle);
60023b10fdc6SMiao Xie 	return error;
60036dd4ee7cSKalpak Shah }
60046dd4ee7cSKalpak Shah 
60056dd4ee7cSKalpak Shah /*
6006ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
6007ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
6008ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
6009ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
6010ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
6011ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
6012ac27a0ecSDave Kleikamp  *
6013ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
6014ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
6015ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
6016ac27a0ecSDave Kleikamp  * we start and wait on commits.
6017ac27a0ecSDave Kleikamp  */
60184209ae12SHarshad Shirwadkar int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
60194209ae12SHarshad Shirwadkar 				const char *func, unsigned int line)
6020ac27a0ecSDave Kleikamp {
6021617ba13bSMingming Cao 	struct ext4_iloc iloc;
60226dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6023cf0a5e81SMiao Xie 	int err;
6024ac27a0ecSDave Kleikamp 
6025ac27a0ecSDave Kleikamp 	might_sleep();
60267ff9c073STheodore Ts'o 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
6027617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
60285e1021f2SEryu Guan 	if (err)
60294209ae12SHarshad Shirwadkar 		goto out;
6030cf0a5e81SMiao Xie 
6031cf0a5e81SMiao Xie 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
6032cf0a5e81SMiao Xie 		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
60336dd4ee7cSKalpak Shah 					       iloc, handle);
6034cf0a5e81SMiao Xie 
60354209ae12SHarshad Shirwadkar 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
60364209ae12SHarshad Shirwadkar out:
60374209ae12SHarshad Shirwadkar 	if (unlikely(err))
60384209ae12SHarshad Shirwadkar 		ext4_error_inode_err(inode, func, line, 0, err,
60394209ae12SHarshad Shirwadkar 					"mark_inode_dirty error");
60404209ae12SHarshad Shirwadkar 	return err;
6041ac27a0ecSDave Kleikamp }
6042ac27a0ecSDave Kleikamp 
6043ac27a0ecSDave Kleikamp /*
6044617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
6045ac27a0ecSDave Kleikamp  *
6046ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
6047ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
6048ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
6049ac27a0ecSDave Kleikamp  *
60505dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
6051ac27a0ecSDave Kleikamp  * are allocated to the file.
6052ac27a0ecSDave Kleikamp  *
6053ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
6054ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
6055ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
6056ac27a0ecSDave Kleikamp  */
6057aa385729SChristoph Hellwig void ext4_dirty_inode(struct inode *inode, int flags)
6058ac27a0ecSDave Kleikamp {
6059ac27a0ecSDave Kleikamp 	handle_t *handle;
6060ac27a0ecSDave Kleikamp 
60619924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
6062ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
6063ac27a0ecSDave Kleikamp 		return;
6064e2728c56SEric Biggers 	ext4_mark_inode_dirty(handle, inode);
6065e2728c56SEric Biggers 	ext4_journal_stop(handle);
6066ac27a0ecSDave Kleikamp }
6067ac27a0ecSDave Kleikamp 
6068617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
6069ac27a0ecSDave Kleikamp {
6070ac27a0ecSDave Kleikamp 	journal_t *journal;
6071ac27a0ecSDave Kleikamp 	handle_t *handle;
6072ac27a0ecSDave Kleikamp 	int err;
6073c8585c6fSDaeho Jeong 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6074ac27a0ecSDave Kleikamp 
6075ac27a0ecSDave Kleikamp 	/*
6076ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
6077ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
6078ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
6079ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
6080ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
6081ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
6082ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
6083ac27a0ecSDave Kleikamp 	 */
6084ac27a0ecSDave Kleikamp 
6085617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
60860390131bSFrank Mayhar 	if (!journal)
60870390131bSFrank Mayhar 		return 0;
6088d699594dSDave Hansen 	if (is_journal_aborted(journal))
6089ac27a0ecSDave Kleikamp 		return -EROFS;
6090ac27a0ecSDave Kleikamp 
609117335dccSDmitry Monakhov 	/* Wait for all existing dio workers */
609217335dccSDmitry Monakhov 	inode_dio_wait(inode);
609317335dccSDmitry Monakhov 
60944c546592SDaeho Jeong 	/*
60954c546592SDaeho Jeong 	 * Before flushing the journal and switching inode's aops, we have
60964c546592SDaeho Jeong 	 * to flush all dirty data the inode has. There can be outstanding
60974c546592SDaeho Jeong 	 * delayed allocations, there can be unwritten extents created by
60984c546592SDaeho Jeong 	 * fallocate or buffered writes in dioread_nolock mode covered by
60994c546592SDaeho Jeong 	 * dirty data which can be converted only after flushing the dirty
61004c546592SDaeho Jeong 	 * data (and journalled aops don't know how to handle these cases).
61014c546592SDaeho Jeong 	 */
61024c546592SDaeho Jeong 	if (val) {
6103d4f5258eSJan Kara 		filemap_invalidate_lock(inode->i_mapping);
61044c546592SDaeho Jeong 		err = filemap_write_and_wait(inode->i_mapping);
61054c546592SDaeho Jeong 		if (err < 0) {
6106d4f5258eSJan Kara 			filemap_invalidate_unlock(inode->i_mapping);
61074c546592SDaeho Jeong 			return err;
61084c546592SDaeho Jeong 		}
61094c546592SDaeho Jeong 	}
61104c546592SDaeho Jeong 
6111bbd55937SEric Biggers 	percpu_down_write(&sbi->s_writepages_rwsem);
6112dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
6113ac27a0ecSDave Kleikamp 
6114ac27a0ecSDave Kleikamp 	/*
6115ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
6116ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
6117ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
6118ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
6119ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
6120ac27a0ecSDave Kleikamp 	 */
6121ac27a0ecSDave Kleikamp 
6122ac27a0ecSDave Kleikamp 	if (val)
612312e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
61245872ddaaSYongqiang Yang 	else {
612501d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
61264f879ca6SJan Kara 		if (err < 0) {
61274f879ca6SJan Kara 			jbd2_journal_unlock_updates(journal);
6128bbd55937SEric Biggers 			percpu_up_write(&sbi->s_writepages_rwsem);
61294f879ca6SJan Kara 			return err;
61304f879ca6SJan Kara 		}
613112e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
61325872ddaaSYongqiang Yang 	}
6133617ba13bSMingming Cao 	ext4_set_aops(inode);
6134ac27a0ecSDave Kleikamp 
6135dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
6136bbd55937SEric Biggers 	percpu_up_write(&sbi->s_writepages_rwsem);
6137c8585c6fSDaeho Jeong 
61384c546592SDaeho Jeong 	if (val)
6139d4f5258eSJan Kara 		filemap_invalidate_unlock(inode->i_mapping);
6140ac27a0ecSDave Kleikamp 
6141ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
6142ac27a0ecSDave Kleikamp 
61439924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6144ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
6145ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
6146ac27a0ecSDave Kleikamp 
6147aa75f4d3SHarshad Shirwadkar 	ext4_fc_mark_ineligible(inode->i_sb,
6148e85c81baSXin Yin 		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6149617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
61500390131bSFrank Mayhar 	ext4_handle_sync(handle);
6151617ba13bSMingming Cao 	ext4_journal_stop(handle);
6152617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
6153ac27a0ecSDave Kleikamp 
6154ac27a0ecSDave Kleikamp 	return err;
6155ac27a0ecSDave Kleikamp }
61562e9ee850SAneesh Kumar K.V 
6157188c299eSJan Kara static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6158188c299eSJan Kara 			    struct buffer_head *bh)
61592e9ee850SAneesh Kumar K.V {
61602e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
61612e9ee850SAneesh Kumar K.V }
61622e9ee850SAneesh Kumar K.V 
6163401b25aaSSouptick Joarder vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
61642e9ee850SAneesh Kumar K.V {
616511bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
6166c2ec175cSNick Piggin 	struct page *page = vmf->page;
61672e9ee850SAneesh Kumar K.V 	loff_t size;
61682e9ee850SAneesh Kumar K.V 	unsigned long len;
6169401b25aaSSouptick Joarder 	int err;
6170401b25aaSSouptick Joarder 	vm_fault_t ret;
61712e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
6172496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
61732e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
61749ea7df53SJan Kara 	handle_t *handle;
61759ea7df53SJan Kara 	get_block_t *get_block;
61769ea7df53SJan Kara 	int retries = 0;
61772e9ee850SAneesh Kumar K.V 
617802b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
617902b016caSTheodore Ts'o 		return VM_FAULT_SIGBUS;
618002b016caSTheodore Ts'o 
61818e8ad8a5SJan Kara 	sb_start_pagefault(inode->i_sb);
6182041bbb6dSTheodore Ts'o 	file_update_time(vma->vm_file);
6183ea3d7209SJan Kara 
6184d4f5258eSJan Kara 	filemap_invalidate_lock_shared(mapping);
61857b4cc978SEric Biggers 
6186401b25aaSSouptick Joarder 	err = ext4_convert_inline_data(inode);
6187401b25aaSSouptick Joarder 	if (err)
61887b4cc978SEric Biggers 		goto out_ret;
61897b4cc978SEric Biggers 
619064a9f144SMauricio Faria de Oliveira 	/*
619164a9f144SMauricio Faria de Oliveira 	 * On data journalling we skip straight to the transaction handle:
619264a9f144SMauricio Faria de Oliveira 	 * there's no delalloc; page truncated will be checked later; the
619364a9f144SMauricio Faria de Oliveira 	 * early return w/ all buffers mapped (calculates size/len) can't
619464a9f144SMauricio Faria de Oliveira 	 * be used; and there's no dioread_nolock, so only ext4_get_block.
619564a9f144SMauricio Faria de Oliveira 	 */
619664a9f144SMauricio Faria de Oliveira 	if (ext4_should_journal_data(inode))
619764a9f144SMauricio Faria de Oliveira 		goto retry_alloc;
619864a9f144SMauricio Faria de Oliveira 
61999ea7df53SJan Kara 	/* Delalloc case is easy... */
62009ea7df53SJan Kara 	if (test_opt(inode->i_sb, DELALLOC) &&
62019ea7df53SJan Kara 	    !ext4_nonda_switch(inode->i_sb)) {
62029ea7df53SJan Kara 		do {
6203401b25aaSSouptick Joarder 			err = block_page_mkwrite(vma, vmf,
62049ea7df53SJan Kara 						   ext4_da_get_block_prep);
6205401b25aaSSouptick Joarder 		} while (err == -ENOSPC &&
62069ea7df53SJan Kara 		       ext4_should_retry_alloc(inode->i_sb, &retries));
62079ea7df53SJan Kara 		goto out_ret;
62082e9ee850SAneesh Kumar K.V 	}
62090e499890SDarrick J. Wong 
62100e499890SDarrick J. Wong 	lock_page(page);
62119ea7df53SJan Kara 	size = i_size_read(inode);
62129ea7df53SJan Kara 	/* Page got truncated from under us? */
62139ea7df53SJan Kara 	if (page->mapping != mapping || page_offset(page) > size) {
62149ea7df53SJan Kara 		unlock_page(page);
62159ea7df53SJan Kara 		ret = VM_FAULT_NOPAGE;
62169ea7df53SJan Kara 		goto out;
62170e499890SDarrick J. Wong 	}
62182e9ee850SAneesh Kumar K.V 
621909cbfeafSKirill A. Shutemov 	if (page->index == size >> PAGE_SHIFT)
622009cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
62212e9ee850SAneesh Kumar K.V 	else
622209cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
6223a827eaffSAneesh Kumar K.V 	/*
62249ea7df53SJan Kara 	 * Return if we have all the buffers mapped. This avoids the need to do
62259ea7df53SJan Kara 	 * journal_start/journal_stop which can block and take a long time
622664a9f144SMauricio Faria de Oliveira 	 *
622764a9f144SMauricio Faria de Oliveira 	 * This cannot be done for data journalling, as we have to add the
622864a9f144SMauricio Faria de Oliveira 	 * inode to the transaction's list to writeprotect pages on commit.
6229a827eaffSAneesh Kumar K.V 	 */
62302e9ee850SAneesh Kumar K.V 	if (page_has_buffers(page)) {
6231188c299eSJan Kara 		if (!ext4_walk_page_buffers(NULL, inode, page_buffers(page),
6232f19d5870STao Ma 					    0, len, NULL,
6233a827eaffSAneesh Kumar K.V 					    ext4_bh_unmapped)) {
62349ea7df53SJan Kara 			/* Wait so that we don't change page under IO */
62351d1d1a76SDarrick J. Wong 			wait_for_stable_page(page);
62369ea7df53SJan Kara 			ret = VM_FAULT_LOCKED;
62379ea7df53SJan Kara 			goto out;
62382e9ee850SAneesh Kumar K.V 		}
6239a827eaffSAneesh Kumar K.V 	}
6240a827eaffSAneesh Kumar K.V 	unlock_page(page);
62419ea7df53SJan Kara 	/* OK, we need to fill the hole... */
62429ea7df53SJan Kara 	if (ext4_should_dioread_nolock(inode))
6243705965bdSJan Kara 		get_block = ext4_get_block_unwritten;
62449ea7df53SJan Kara 	else
62459ea7df53SJan Kara 		get_block = ext4_get_block;
62469ea7df53SJan Kara retry_alloc:
62479924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
62489924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
62499ea7df53SJan Kara 	if (IS_ERR(handle)) {
6250c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
62519ea7df53SJan Kara 		goto out;
62529ea7df53SJan Kara 	}
625364a9f144SMauricio Faria de Oliveira 	/*
625464a9f144SMauricio Faria de Oliveira 	 * Data journalling can't use block_page_mkwrite() because it
625564a9f144SMauricio Faria de Oliveira 	 * will set_buffer_dirty() before do_journal_get_write_access()
625664a9f144SMauricio Faria de Oliveira 	 * thus might hit warning messages for dirty metadata buffers.
625764a9f144SMauricio Faria de Oliveira 	 */
625864a9f144SMauricio Faria de Oliveira 	if (!ext4_should_journal_data(inode)) {
6259401b25aaSSouptick Joarder 		err = block_page_mkwrite(vma, vmf, get_block);
626064a9f144SMauricio Faria de Oliveira 	} else {
626164a9f144SMauricio Faria de Oliveira 		lock_page(page);
626264a9f144SMauricio Faria de Oliveira 		size = i_size_read(inode);
626364a9f144SMauricio Faria de Oliveira 		/* Page got truncated from under us? */
626464a9f144SMauricio Faria de Oliveira 		if (page->mapping != mapping || page_offset(page) > size) {
626564a9f144SMauricio Faria de Oliveira 			ret = VM_FAULT_NOPAGE;
6266afb585a9SMauricio Faria de Oliveira 			goto out_error;
626764a9f144SMauricio Faria de Oliveira 		}
626864a9f144SMauricio Faria de Oliveira 
626964a9f144SMauricio Faria de Oliveira 		if (page->index == size >> PAGE_SHIFT)
627064a9f144SMauricio Faria de Oliveira 			len = size & ~PAGE_MASK;
627164a9f144SMauricio Faria de Oliveira 		else
627264a9f144SMauricio Faria de Oliveira 			len = PAGE_SIZE;
627364a9f144SMauricio Faria de Oliveira 
627464a9f144SMauricio Faria de Oliveira 		err = __block_write_begin(page, 0, len, ext4_get_block);
627564a9f144SMauricio Faria de Oliveira 		if (!err) {
62769ea7df53SJan Kara 			ret = VM_FAULT_SIGBUS;
6277188c299eSJan Kara 			if (ext4_walk_page_buffers(handle, inode,
6278188c299eSJan Kara 					page_buffers(page), 0, len, NULL,
6279188c299eSJan Kara 					do_journal_get_write_access))
6280afb585a9SMauricio Faria de Oliveira 				goto out_error;
6281188c299eSJan Kara 			if (ext4_walk_page_buffers(handle, inode,
6282188c299eSJan Kara 					page_buffers(page), 0, len, NULL,
6283188c299eSJan Kara 					write_end_fn))
6284afb585a9SMauricio Faria de Oliveira 				goto out_error;
6285b5b18160SJan Kara 			if (ext4_jbd2_inode_add_write(handle, inode,
6286b5b18160SJan Kara 						      page_offset(page), len))
6287afb585a9SMauricio Faria de Oliveira 				goto out_error;
62889ea7df53SJan Kara 			ext4_set_inode_state(inode, EXT4_STATE_JDATA);
628964a9f144SMauricio Faria de Oliveira 		} else {
629064a9f144SMauricio Faria de Oliveira 			unlock_page(page);
629164a9f144SMauricio Faria de Oliveira 		}
62929ea7df53SJan Kara 	}
62939ea7df53SJan Kara 	ext4_journal_stop(handle);
6294401b25aaSSouptick Joarder 	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
62959ea7df53SJan Kara 		goto retry_alloc;
62969ea7df53SJan Kara out_ret:
6297401b25aaSSouptick Joarder 	ret = block_page_mkwrite_return(err);
62989ea7df53SJan Kara out:
6299d4f5258eSJan Kara 	filemap_invalidate_unlock_shared(mapping);
63008e8ad8a5SJan Kara 	sb_end_pagefault(inode->i_sb);
63012e9ee850SAneesh Kumar K.V 	return ret;
6302afb585a9SMauricio Faria de Oliveira out_error:
6303afb585a9SMauricio Faria de Oliveira 	unlock_page(page);
6304afb585a9SMauricio Faria de Oliveira 	ext4_journal_stop(handle);
6305afb585a9SMauricio Faria de Oliveira 	goto out;
63062e9ee850SAneesh Kumar K.V }
6307