xref: /openbmc/linux/fs/ext4/inode.c (revision 4df031ff5876d94b48dd9ee486ba5522382a06b2)
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 
139d47992f8SLukas Czerner static void ext4_invalidatepage(struct page *page, unsigned int offset,
140d47992f8SLukas Czerner 				unsigned int length);
141cb20d518STheodore Ts'o static int __ext4_journalled_writepage(struct page *page, unsigned int len);
142cb20d518STheodore Ts'o static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
143dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
144dec214d0STahsin Erdogan 				  int pextents);
14564769240SAlex Tomas 
146ac27a0ecSDave Kleikamp /*
147ac27a0ecSDave Kleikamp  * Test whether an inode is a fast symlink.
148407cd7fbSTahsin Erdogan  * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
149ac27a0ecSDave Kleikamp  */
150f348c252STheodore Ts'o int ext4_inode_is_fast_symlink(struct inode *inode)
151ac27a0ecSDave Kleikamp {
152fc82228aSAndi Kleen 	if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
153fc82228aSAndi Kleen 		int ea_blocks = EXT4_I(inode)->i_file_acl ?
154fc82228aSAndi Kleen 				EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
155fc82228aSAndi Kleen 
156fc82228aSAndi Kleen 		if (ext4_has_inline_data(inode))
157fc82228aSAndi Kleen 			return 0;
158fc82228aSAndi Kleen 
159fc82228aSAndi Kleen 		return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
160fc82228aSAndi Kleen 	}
161407cd7fbSTahsin Erdogan 	return S_ISLNK(inode->i_mode) && inode->i_size &&
162407cd7fbSTahsin Erdogan 	       (inode->i_size < EXT4_N_BLOCKS * 4);
163ac27a0ecSDave Kleikamp }
164ac27a0ecSDave Kleikamp 
165ac27a0ecSDave Kleikamp /*
166ac27a0ecSDave Kleikamp  * Called at the last iput() if i_nlink is zero.
167ac27a0ecSDave Kleikamp  */
1680930fcc1SAl Viro void ext4_evict_inode(struct inode *inode)
169ac27a0ecSDave Kleikamp {
170ac27a0ecSDave Kleikamp 	handle_t *handle;
171bc965ab3STheodore Ts'o 	int err;
17265db869cSJan Kara 	/*
17365db869cSJan Kara 	 * Credits for final inode cleanup and freeing:
17465db869cSJan Kara 	 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
17565db869cSJan Kara 	 * (xattr block freeing), bitmap, group descriptor (inode freeing)
17665db869cSJan Kara 	 */
17765db869cSJan Kara 	int extra_credits = 6;
1780421a189STahsin Erdogan 	struct ext4_xattr_inode_array *ea_inode_array = NULL;
17946e294efSJan Kara 	bool freeze_protected = false;
180ac27a0ecSDave Kleikamp 
1817ff9c073STheodore Ts'o 	trace_ext4_evict_inode(inode);
1822581fdc8SJiaying Zhang 
1830930fcc1SAl Viro 	if (inode->i_nlink) {
1842d859db3SJan Kara 		/*
1852d859db3SJan Kara 		 * When journalling data dirty buffers are tracked only in the
1862d859db3SJan Kara 		 * journal. So although mm thinks everything is clean and
1872d859db3SJan Kara 		 * ready for reaping the inode might still have some pages to
1882d859db3SJan Kara 		 * write in the running transaction or waiting to be
1892d859db3SJan Kara 		 * checkpointed. Thus calling jbd2_journal_invalidatepage()
1902d859db3SJan Kara 		 * (via truncate_inode_pages()) to discard these buffers can
1912d859db3SJan Kara 		 * cause data loss. Also even if we did not discard these
1922d859db3SJan Kara 		 * buffers, we would have no way to find them after the inode
1932d859db3SJan Kara 		 * is reaped and thus user could see stale data if he tries to
1942d859db3SJan Kara 		 * read them before the transaction is checkpointed. So be
1952d859db3SJan Kara 		 * careful and force everything to disk here... We use
1962d859db3SJan Kara 		 * ei->i_datasync_tid to store the newest transaction
1972d859db3SJan Kara 		 * containing inode's data.
1982d859db3SJan Kara 		 *
1992d859db3SJan Kara 		 * Note that directories do not have this problem because they
2002d859db3SJan Kara 		 * don't use page cache.
2012d859db3SJan Kara 		 */
2026a7fd522SVegard Nossum 		if (inode->i_ino != EXT4_JOURNAL_INO &&
2036a7fd522SVegard Nossum 		    ext4_should_journal_data(inode) &&
2043abb1a0fSJan Kara 		    (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
2053abb1a0fSJan Kara 		    inode->i_data.nrpages) {
2062d859db3SJan Kara 			journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
2072d859db3SJan Kara 			tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
2082d859db3SJan Kara 
209d76a3a77STheodore Ts'o 			jbd2_complete_transaction(journal, commit_tid);
2102d859db3SJan Kara 			filemap_write_and_wait(&inode->i_data);
2112d859db3SJan Kara 		}
21291b0abe3SJohannes Weiner 		truncate_inode_pages_final(&inode->i_data);
2135dc23bddSJan Kara 
2140930fcc1SAl Viro 		goto no_delete;
2150930fcc1SAl Viro 	}
2160930fcc1SAl Viro 
217e2bfb088STheodore Ts'o 	if (is_bad_inode(inode))
218e2bfb088STheodore Ts'o 		goto no_delete;
219871a2931SChristoph Hellwig 	dquot_initialize(inode);
220907f4554SChristoph Hellwig 
221678aaf48SJan Kara 	if (ext4_should_order_data(inode))
222678aaf48SJan Kara 		ext4_begin_ordered_truncate(inode, 0);
22391b0abe3SJohannes Weiner 	truncate_inode_pages_final(&inode->i_data);
224ac27a0ecSDave Kleikamp 
2258e8ad8a5SJan Kara 	/*
226ceff86fdSJan Kara 	 * For inodes with journalled data, transaction commit could have
227ceff86fdSJan Kara 	 * dirtied the inode. Flush worker is ignoring it because of I_FREEING
228ceff86fdSJan Kara 	 * flag but we still need to remove the inode from the writeback lists.
229ceff86fdSJan Kara 	 */
230ceff86fdSJan Kara 	if (!list_empty_careful(&inode->i_io_list)) {
231ceff86fdSJan Kara 		WARN_ON_ONCE(!ext4_should_journal_data(inode));
232ceff86fdSJan Kara 		inode_io_list_del(inode);
233ceff86fdSJan Kara 	}
234ceff86fdSJan Kara 
235ceff86fdSJan Kara 	/*
2368e8ad8a5SJan Kara 	 * Protect us against freezing - iput() caller didn't have to have any
23746e294efSJan Kara 	 * protection against it. When we are in a running transaction though,
23846e294efSJan Kara 	 * we are already protected against freezing and we cannot grab further
23946e294efSJan Kara 	 * protection due to lock ordering constraints.
2408e8ad8a5SJan Kara 	 */
24146e294efSJan Kara 	if (!ext4_journal_current_handle()) {
2428e8ad8a5SJan Kara 		sb_start_intwrite(inode->i_sb);
24346e294efSJan Kara 		freeze_protected = true;
24446e294efSJan Kara 	}
245e50e5129SAndreas Dilger 
24630a7eb97STahsin Erdogan 	if (!IS_NOQUOTA(inode))
24730a7eb97STahsin Erdogan 		extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
24830a7eb97STahsin Erdogan 
24965db869cSJan Kara 	/*
25065db869cSJan Kara 	 * Block bitmap, group descriptor, and inode are accounted in both
25165db869cSJan Kara 	 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
25265db869cSJan Kara 	 */
25330a7eb97STahsin Erdogan 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
25465db869cSJan Kara 			 ext4_blocks_for_truncate(inode) + extra_credits - 3);
255ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
256bc965ab3STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
257ac27a0ecSDave Kleikamp 		/*
258ac27a0ecSDave Kleikamp 		 * If we're going to skip the normal cleanup, we still need to
259ac27a0ecSDave Kleikamp 		 * make sure that the in-core orphan linked list is properly
260ac27a0ecSDave Kleikamp 		 * cleaned up.
261ac27a0ecSDave Kleikamp 		 */
262617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
26346e294efSJan Kara 		if (freeze_protected)
2648e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
265ac27a0ecSDave Kleikamp 		goto no_delete;
266ac27a0ecSDave Kleikamp 	}
26730a7eb97STahsin Erdogan 
268ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
2690390131bSFrank Mayhar 		ext4_handle_sync(handle);
270407cd7fbSTahsin Erdogan 
271407cd7fbSTahsin Erdogan 	/*
272407cd7fbSTahsin Erdogan 	 * Set inode->i_size to 0 before calling ext4_truncate(). We need
273407cd7fbSTahsin Erdogan 	 * special handling of symlinks here because i_size is used to
274407cd7fbSTahsin Erdogan 	 * determine whether ext4_inode_info->i_data contains symlink data or
275407cd7fbSTahsin Erdogan 	 * block mappings. Setting i_size to 0 will remove its fast symlink
276407cd7fbSTahsin Erdogan 	 * status. Erase i_data so that it becomes a valid empty block map.
277407cd7fbSTahsin Erdogan 	 */
278407cd7fbSTahsin Erdogan 	if (ext4_inode_is_fast_symlink(inode))
279407cd7fbSTahsin Erdogan 		memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
280ac27a0ecSDave Kleikamp 	inode->i_size = 0;
281bc965ab3STheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
282bc965ab3STheodore Ts'o 	if (err) {
28312062dddSEric Sandeen 		ext4_warning(inode->i_sb,
284bc965ab3STheodore Ts'o 			     "couldn't mark inode dirty (err %d)", err);
285bc965ab3STheodore Ts'o 		goto stop_handle;
286bc965ab3STheodore Ts'o 	}
2872c98eb5eSTheodore Ts'o 	if (inode->i_blocks) {
2882c98eb5eSTheodore Ts'o 		err = ext4_truncate(inode);
2892c98eb5eSTheodore Ts'o 		if (err) {
29054d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err,
2912c98eb5eSTheodore Ts'o 				       "couldn't truncate inode %lu (err %d)",
2922c98eb5eSTheodore Ts'o 				       inode->i_ino, err);
2932c98eb5eSTheodore Ts'o 			goto stop_handle;
2942c98eb5eSTheodore Ts'o 		}
2952c98eb5eSTheodore Ts'o 	}
296bc965ab3STheodore Ts'o 
29730a7eb97STahsin Erdogan 	/* Remove xattr references. */
29830a7eb97STahsin Erdogan 	err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
29930a7eb97STahsin Erdogan 				      extra_credits);
30030a7eb97STahsin Erdogan 	if (err) {
30130a7eb97STahsin Erdogan 		ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
302bc965ab3STheodore Ts'o stop_handle:
303bc965ab3STheodore Ts'o 		ext4_journal_stop(handle);
30445388219STheodore Ts'o 		ext4_orphan_del(NULL, inode);
30546e294efSJan Kara 		if (freeze_protected)
3068e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
30730a7eb97STahsin Erdogan 		ext4_xattr_inode_array_free(ea_inode_array);
308bc965ab3STheodore Ts'o 		goto no_delete;
309bc965ab3STheodore Ts'o 	}
310bc965ab3STheodore Ts'o 
311ac27a0ecSDave Kleikamp 	/*
312617ba13bSMingming Cao 	 * Kill off the orphan record which ext4_truncate created.
313ac27a0ecSDave Kleikamp 	 * AKPM: I think this can be inside the above `if'.
314617ba13bSMingming Cao 	 * Note that ext4_orphan_del() has to be able to cope with the
315ac27a0ecSDave Kleikamp 	 * deletion of a non-existent orphan - this is because we don't
316617ba13bSMingming Cao 	 * know if ext4_truncate() actually created an orphan record.
317ac27a0ecSDave Kleikamp 	 * (Well, we could do this if we need to, but heck - it works)
318ac27a0ecSDave Kleikamp 	 */
319617ba13bSMingming Cao 	ext4_orphan_del(handle, inode);
3205ffff834SArnd Bergmann 	EXT4_I(inode)->i_dtime	= (__u32)ktime_get_real_seconds();
321ac27a0ecSDave Kleikamp 
322ac27a0ecSDave Kleikamp 	/*
323ac27a0ecSDave Kleikamp 	 * One subtle ordering requirement: if anything has gone wrong
324ac27a0ecSDave Kleikamp 	 * (transaction abort, IO errors, whatever), then we can still
325ac27a0ecSDave Kleikamp 	 * do these next steps (the fs will already have been marked as
326ac27a0ecSDave Kleikamp 	 * having errors), but we can't free the inode if the mark_dirty
327ac27a0ecSDave Kleikamp 	 * fails.
328ac27a0ecSDave Kleikamp 	 */
329617ba13bSMingming Cao 	if (ext4_mark_inode_dirty(handle, inode))
330ac27a0ecSDave Kleikamp 		/* If that failed, just do the required in-core inode clear. */
3310930fcc1SAl Viro 		ext4_clear_inode(inode);
332ac27a0ecSDave Kleikamp 	else
333617ba13bSMingming Cao 		ext4_free_inode(handle, inode);
334617ba13bSMingming Cao 	ext4_journal_stop(handle);
33546e294efSJan Kara 	if (freeze_protected)
3368e8ad8a5SJan Kara 		sb_end_intwrite(inode->i_sb);
3370421a189STahsin Erdogan 	ext4_xattr_inode_array_free(ea_inode_array);
338ac27a0ecSDave Kleikamp 	return;
339ac27a0ecSDave Kleikamp no_delete:
340b21ebf14SHarshad Shirwadkar 	if (!list_empty(&EXT4_I(inode)->i_fc_list))
341b21ebf14SHarshad Shirwadkar 		ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM);
3420930fcc1SAl Viro 	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
343ac27a0ecSDave Kleikamp }
344ac27a0ecSDave Kleikamp 
345a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
346a9e7f447SDmitry Monakhov qsize_t *ext4_get_reserved_space(struct inode *inode)
34760e58e0fSMingming Cao {
348a9e7f447SDmitry Monakhov 	return &EXT4_I(inode)->i_reserved_quota;
34960e58e0fSMingming Cao }
350a9e7f447SDmitry Monakhov #endif
3519d0be502STheodore Ts'o 
35212219aeaSAneesh Kumar K.V /*
3530637c6f4STheodore Ts'o  * Called with i_data_sem down, which is important since we can call
3540637c6f4STheodore Ts'o  * ext4_discard_preallocations() from here.
3550637c6f4STheodore Ts'o  */
3565f634d06SAneesh Kumar K.V void ext4_da_update_reserve_space(struct inode *inode,
3575f634d06SAneesh Kumar K.V 					int used, int quota_claim)
35812219aeaSAneesh Kumar K.V {
35912219aeaSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3600637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
36112219aeaSAneesh Kumar K.V 
3620637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
363d8990240SAditya Kali 	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
3640637c6f4STheodore Ts'o 	if (unlikely(used > ei->i_reserved_data_blocks)) {
3658de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
3661084f252STheodore Ts'o 			 "with only %d reserved data blocks",
3670637c6f4STheodore Ts'o 			 __func__, inode->i_ino, used,
3680637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
3690637c6f4STheodore Ts'o 		WARN_ON(1);
3700637c6f4STheodore Ts'o 		used = ei->i_reserved_data_blocks;
3716bc6e63fSAneesh Kumar K.V 	}
37212219aeaSAneesh Kumar K.V 
3730637c6f4STheodore Ts'o 	/* Update per-inode reservations */
3740637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= used;
37571d4f7d0STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
3760637c6f4STheodore Ts'o 
377f9505c72Schenyichong 	spin_unlock(&ei->i_block_reservation_lock);
37860e58e0fSMingming Cao 
37972b8ab9dSEric Sandeen 	/* Update quota subsystem for data blocks */
38072b8ab9dSEric Sandeen 	if (quota_claim)
3817b415bf6SAditya Kali 		dquot_claim_block(inode, EXT4_C2B(sbi, used));
38272b8ab9dSEric Sandeen 	else {
3835f634d06SAneesh Kumar K.V 		/*
3845f634d06SAneesh Kumar K.V 		 * We did fallocate with an offset that is already delayed
3855f634d06SAneesh Kumar K.V 		 * allocated. So on delayed allocated writeback we should
38672b8ab9dSEric Sandeen 		 * not re-claim the quota for fallocated blocks.
3875f634d06SAneesh Kumar K.V 		 */
3887b415bf6SAditya Kali 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
3895f634d06SAneesh Kumar K.V 	}
390d6014301SAneesh Kumar K.V 
391d6014301SAneesh Kumar K.V 	/*
392d6014301SAneesh Kumar K.V 	 * If we have done all the pending block allocations and if
393d6014301SAneesh Kumar K.V 	 * there aren't any writers on the inode, we can discard the
394d6014301SAneesh Kumar K.V 	 * inode's preallocations.
395d6014301SAneesh Kumar K.V 	 */
3960637c6f4STheodore Ts'o 	if ((ei->i_reserved_data_blocks == 0) &&
39782dd124cSNikolay Borisov 	    !inode_is_open_for_write(inode))
39827bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
39912219aeaSAneesh Kumar K.V }
40012219aeaSAneesh Kumar K.V 
401e29136f8STheodore Ts'o static int __check_block_validity(struct inode *inode, const char *func,
402c398eda0STheodore Ts'o 				unsigned int line,
40324676da4STheodore Ts'o 				struct ext4_map_blocks *map)
4046fd058f7STheodore Ts'o {
405345c0dbfSTheodore Ts'o 	if (ext4_has_feature_journal(inode->i_sb) &&
406345c0dbfSTheodore Ts'o 	    (inode->i_ino ==
407345c0dbfSTheodore Ts'o 	     le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
408345c0dbfSTheodore Ts'o 		return 0;
409ce9f24ccSJan Kara 	if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
410c398eda0STheodore Ts'o 		ext4_error_inode(inode, func, line, map->m_pblk,
411bdbd6ce0STheodore Ts'o 				 "lblock %lu mapped to illegal pblock %llu "
41224676da4STheodore Ts'o 				 "(length %d)", (unsigned long) map->m_lblk,
413bdbd6ce0STheodore Ts'o 				 map->m_pblk, map->m_len);
4146a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4156fd058f7STheodore Ts'o 	}
4166fd058f7STheodore Ts'o 	return 0;
4176fd058f7STheodore Ts'o }
4186fd058f7STheodore Ts'o 
41953085facSJan Kara int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
42053085facSJan Kara 		       ext4_lblk_t len)
42153085facSJan Kara {
42253085facSJan Kara 	int ret;
42353085facSJan Kara 
42433b4cc25SEric Biggers 	if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
425a7550b30SJaegeuk Kim 		return fscrypt_zeroout_range(inode, lblk, pblk, len);
42653085facSJan Kara 
42753085facSJan Kara 	ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
42853085facSJan Kara 	if (ret > 0)
42953085facSJan Kara 		ret = 0;
43053085facSJan Kara 
43153085facSJan Kara 	return ret;
43253085facSJan Kara }
43353085facSJan Kara 
434e29136f8STheodore Ts'o #define check_block_validity(inode, map)	\
435c398eda0STheodore Ts'o 	__check_block_validity((inode), __func__, __LINE__, (map))
436e29136f8STheodore Ts'o 
437921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
438921f266bSDmitry Monakhov static void ext4_map_blocks_es_recheck(handle_t *handle,
439921f266bSDmitry Monakhov 				       struct inode *inode,
440921f266bSDmitry Monakhov 				       struct ext4_map_blocks *es_map,
441921f266bSDmitry Monakhov 				       struct ext4_map_blocks *map,
442921f266bSDmitry Monakhov 				       int flags)
443921f266bSDmitry Monakhov {
444921f266bSDmitry Monakhov 	int retval;
445921f266bSDmitry Monakhov 
446921f266bSDmitry Monakhov 	map->m_flags = 0;
447921f266bSDmitry Monakhov 	/*
448921f266bSDmitry Monakhov 	 * There is a race window that the result is not the same.
449921f266bSDmitry Monakhov 	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
450921f266bSDmitry Monakhov 	 * is that we lookup a block mapping in extent status tree with
451921f266bSDmitry Monakhov 	 * out taking i_data_sem.  So at the time the unwritten extent
452921f266bSDmitry Monakhov 	 * could be converted.
453921f266bSDmitry Monakhov 	 */
454c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
455921f266bSDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4569e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
457921f266bSDmitry Monakhov 	} else {
4589e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
459921f266bSDmitry Monakhov 	}
460921f266bSDmitry Monakhov 	up_read((&EXT4_I(inode)->i_data_sem));
461921f266bSDmitry Monakhov 
462921f266bSDmitry Monakhov 	/*
463921f266bSDmitry Monakhov 	 * We don't check m_len because extent will be collpased in status
464921f266bSDmitry Monakhov 	 * tree.  So the m_len might not equal.
465921f266bSDmitry Monakhov 	 */
466921f266bSDmitry Monakhov 	if (es_map->m_lblk != map->m_lblk ||
467921f266bSDmitry Monakhov 	    es_map->m_flags != map->m_flags ||
468921f266bSDmitry Monakhov 	    es_map->m_pblk != map->m_pblk) {
469bdafe42aSTheodore Ts'o 		printk("ES cache assertion failed for inode: %lu "
470921f266bSDmitry Monakhov 		       "es_cached ex [%d/%d/%llu/%x] != "
471921f266bSDmitry Monakhov 		       "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
472921f266bSDmitry Monakhov 		       inode->i_ino, es_map->m_lblk, es_map->m_len,
473921f266bSDmitry Monakhov 		       es_map->m_pblk, es_map->m_flags, map->m_lblk,
474921f266bSDmitry Monakhov 		       map->m_len, map->m_pblk, map->m_flags,
475921f266bSDmitry Monakhov 		       retval, flags);
476921f266bSDmitry Monakhov 	}
477921f266bSDmitry Monakhov }
478921f266bSDmitry Monakhov #endif /* ES_AGGRESSIVE_TEST */
479921f266bSDmitry Monakhov 
48055138e0bSTheodore Ts'o /*
481e35fd660STheodore Ts'o  * The ext4_map_blocks() function tries to look up the requested blocks,
4822b2d6d01STheodore Ts'o  * and returns if the blocks are already mapped.
483f5ab0d1fSMingming Cao  *
484f5ab0d1fSMingming Cao  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
485f5ab0d1fSMingming Cao  * and store the allocated blocks in the result buffer head and mark it
486f5ab0d1fSMingming Cao  * mapped.
487f5ab0d1fSMingming Cao  *
488e35fd660STheodore Ts'o  * If file type is extents based, it will call ext4_ext_map_blocks(),
489e35fd660STheodore Ts'o  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
490f5ab0d1fSMingming Cao  * based files
491f5ab0d1fSMingming Cao  *
492facab4d9SJan Kara  * On success, it returns the number of blocks being mapped or allocated.  if
493facab4d9SJan Kara  * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
494facab4d9SJan Kara  * is marked as unwritten. If the create == 1, it will mark @map as mapped.
495f5ab0d1fSMingming Cao  *
496f5ab0d1fSMingming Cao  * It returns 0 if plain look up failed (blocks have not been allocated), in
497facab4d9SJan Kara  * that case, @map is returned as unmapped but we still do fill map->m_len to
498facab4d9SJan Kara  * indicate the length of a hole starting at map->m_lblk.
499f5ab0d1fSMingming Cao  *
500f5ab0d1fSMingming Cao  * It returns the error in case of allocation failure.
501f5ab0d1fSMingming Cao  */
502e35fd660STheodore Ts'o int ext4_map_blocks(handle_t *handle, struct inode *inode,
503e35fd660STheodore Ts'o 		    struct ext4_map_blocks *map, int flags)
5040e855ac8SAneesh Kumar K.V {
505d100eef2SZheng Liu 	struct extent_status es;
5060e855ac8SAneesh Kumar K.V 	int retval;
507b8a86845SLukas Czerner 	int ret = 0;
508921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
509921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
510921f266bSDmitry Monakhov 
511921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
512921f266bSDmitry Monakhov #endif
513f5ab0d1fSMingming Cao 
514e35fd660STheodore Ts'o 	map->m_flags = 0;
51570aa1554SRitesh Harjani 	ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
51670aa1554SRitesh Harjani 		  flags, map->m_len, (unsigned long) map->m_lblk);
517d100eef2SZheng Liu 
518e861b5e9STheodore Ts'o 	/*
519e861b5e9STheodore Ts'o 	 * ext4_map_blocks returns an int, and m_len is an unsigned int
520e861b5e9STheodore Ts'o 	 */
521e861b5e9STheodore Ts'o 	if (unlikely(map->m_len > INT_MAX))
522e861b5e9STheodore Ts'o 		map->m_len = INT_MAX;
523e861b5e9STheodore Ts'o 
5244adb6ab3SKazuya Mio 	/* We can handle the block number less than EXT_MAX_BLOCKS */
5254adb6ab3SKazuya Mio 	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
5266a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
5274adb6ab3SKazuya Mio 
528d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
5298016e29fSHarshad Shirwadkar 	if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
5308016e29fSHarshad Shirwadkar 	    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
531d100eef2SZheng Liu 		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
532d100eef2SZheng Liu 			map->m_pblk = ext4_es_pblock(&es) +
533d100eef2SZheng Liu 					map->m_lblk - es.es_lblk;
534d100eef2SZheng Liu 			map->m_flags |= ext4_es_is_written(&es) ?
535d100eef2SZheng Liu 					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
536d100eef2SZheng Liu 			retval = es.es_len - (map->m_lblk - es.es_lblk);
537d100eef2SZheng Liu 			if (retval > map->m_len)
538d100eef2SZheng Liu 				retval = map->m_len;
539d100eef2SZheng Liu 			map->m_len = retval;
540d100eef2SZheng Liu 		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
541facab4d9SJan Kara 			map->m_pblk = 0;
542facab4d9SJan Kara 			retval = es.es_len - (map->m_lblk - es.es_lblk);
543facab4d9SJan Kara 			if (retval > map->m_len)
544facab4d9SJan Kara 				retval = map->m_len;
545facab4d9SJan Kara 			map->m_len = retval;
546d100eef2SZheng Liu 			retval = 0;
547d100eef2SZheng Liu 		} else {
5481e83bc81SArnd Bergmann 			BUG();
549d100eef2SZheng Liu 		}
550921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
551921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(handle, inode, map,
552921f266bSDmitry Monakhov 					   &orig_map, flags);
553921f266bSDmitry Monakhov #endif
554d100eef2SZheng Liu 		goto found;
555d100eef2SZheng Liu 	}
556d100eef2SZheng Liu 
5574df3d265SAneesh Kumar K.V 	/*
558b920c755STheodore Ts'o 	 * Try to see if we can get the block without requesting a new
559b920c755STheodore Ts'o 	 * file system block.
5604df3d265SAneesh Kumar K.V 	 */
561c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
56212e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5639e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
5644df3d265SAneesh Kumar K.V 	} else {
5659e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
5660e855ac8SAneesh Kumar K.V 	}
567f7fec032SZheng Liu 	if (retval > 0) {
5683be78c73STheodore Ts'o 		unsigned int status;
569f7fec032SZheng Liu 
57044fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
57144fb851dSZheng Liu 			ext4_warning(inode->i_sb,
57244fb851dSZheng Liu 				     "ES len assertion failed for inode "
57344fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
57444fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
57544fb851dSZheng Liu 			WARN_ON(1);
576921f266bSDmitry Monakhov 		}
577921f266bSDmitry Monakhov 
578f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
579f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
580f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
581d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
582ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
583f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
584f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
585f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk,
586f7fec032SZheng Liu 					    map->m_len, map->m_pblk, status);
587f7fec032SZheng Liu 		if (ret < 0)
588f7fec032SZheng Liu 			retval = ret;
589f7fec032SZheng Liu 	}
5904df3d265SAneesh Kumar K.V 	up_read((&EXT4_I(inode)->i_data_sem));
591f5ab0d1fSMingming Cao 
592d100eef2SZheng Liu found:
593e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
594b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
5956fd058f7STheodore Ts'o 		if (ret != 0)
5966fd058f7STheodore Ts'o 			return ret;
5976fd058f7STheodore Ts'o 	}
5986fd058f7STheodore Ts'o 
599f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
600c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
6014df3d265SAneesh Kumar K.V 		return retval;
6024df3d265SAneesh Kumar K.V 
6034df3d265SAneesh Kumar K.V 	/*
604f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
605f5ab0d1fSMingming Cao 	 *
606f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
607df3ab170STao Ma 	 * ext4_ext_get_block() returns the create = 0
608f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
609f5ab0d1fSMingming Cao 	 */
610e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
611b8a86845SLukas Czerner 		/*
612b8a86845SLukas Czerner 		 * If we need to convert extent to unwritten
613b8a86845SLukas Czerner 		 * we continue and do the actual work in
614b8a86845SLukas Czerner 		 * ext4_ext_map_blocks()
615b8a86845SLukas Czerner 		 */
616b8a86845SLukas Czerner 		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
617f5ab0d1fSMingming Cao 			return retval;
618f5ab0d1fSMingming Cao 
619f5ab0d1fSMingming Cao 	/*
620a25a4e1aSZheng Liu 	 * Here we clear m_flags because after allocating an new extent,
621a25a4e1aSZheng Liu 	 * it will be set again.
6222a8964d6SAneesh Kumar K.V 	 */
623a25a4e1aSZheng Liu 	map->m_flags &= ~EXT4_MAP_FLAGS;
6242a8964d6SAneesh Kumar K.V 
6252a8964d6SAneesh Kumar K.V 	/*
626556615dcSLukas Czerner 	 * New blocks allocate and/or writing to unwritten extent
627f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
628d91bd2c1SSeunghun Lee 	 * the write lock of i_data_sem, and call get_block()
629f5ab0d1fSMingming Cao 	 * with create == 1 flag.
6304df3d265SAneesh Kumar K.V 	 */
631c8b459f4SLukas Czerner 	down_write(&EXT4_I(inode)->i_data_sem);
632d2a17637SMingming Cao 
633d2a17637SMingming Cao 	/*
6344df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
6354df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
6364df3d265SAneesh Kumar K.V 	 */
63712e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
638e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
6390e855ac8SAneesh Kumar K.V 	} else {
640e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
641267e4db9SAneesh Kumar K.V 
642e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
643267e4db9SAneesh Kumar K.V 			/*
644267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
645267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
646267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
647267e4db9SAneesh Kumar K.V 			 */
64819f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
649267e4db9SAneesh Kumar K.V 		}
6502ac3b6e0STheodore Ts'o 
651d2a17637SMingming Cao 		/*
6522ac3b6e0STheodore Ts'o 		 * Update reserved blocks/metadata blocks after successful
6535f634d06SAneesh Kumar K.V 		 * block allocation which had been deferred till now. We don't
6545f634d06SAneesh Kumar K.V 		 * support fallocate for non extent files. So we can update
6555f634d06SAneesh Kumar K.V 		 * reserve space here.
656d2a17637SMingming Cao 		 */
6575f634d06SAneesh Kumar K.V 		if ((retval > 0) &&
6581296cc85SAneesh Kumar K.V 			(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
6595f634d06SAneesh Kumar K.V 			ext4_da_update_reserve_space(inode, retval, 1);
6605f634d06SAneesh Kumar K.V 	}
661d2a17637SMingming Cao 
662f7fec032SZheng Liu 	if (retval > 0) {
6633be78c73STheodore Ts'o 		unsigned int status;
664f7fec032SZheng Liu 
66544fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
66644fb851dSZheng Liu 			ext4_warning(inode->i_sb,
66744fb851dSZheng Liu 				     "ES len assertion failed for inode "
66844fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
66944fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
67044fb851dSZheng Liu 			WARN_ON(1);
671921f266bSDmitry Monakhov 		}
672921f266bSDmitry Monakhov 
673adb23551SZheng Liu 		/*
674c86d8db3SJan Kara 		 * We have to zeroout blocks before inserting them into extent
675c86d8db3SJan Kara 		 * status tree. Otherwise someone could look them up there and
6769b623df6SJan Kara 		 * use them before they are really zeroed. We also have to
6779b623df6SJan Kara 		 * unmap metadata before zeroing as otherwise writeback can
6789b623df6SJan Kara 		 * overwrite zeros with stale data from block device.
679c86d8db3SJan Kara 		 */
680c86d8db3SJan Kara 		if (flags & EXT4_GET_BLOCKS_ZERO &&
681c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_MAPPED &&
682c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_NEW) {
683c86d8db3SJan Kara 			ret = ext4_issue_zeroout(inode, map->m_lblk,
684c86d8db3SJan Kara 						 map->m_pblk, map->m_len);
685c86d8db3SJan Kara 			if (ret) {
686c86d8db3SJan Kara 				retval = ret;
687c86d8db3SJan Kara 				goto out_sem;
688c86d8db3SJan Kara 			}
689c86d8db3SJan Kara 		}
690c86d8db3SJan Kara 
691c86d8db3SJan Kara 		/*
692adb23551SZheng Liu 		 * If the extent has been zeroed out, we don't need to update
693adb23551SZheng Liu 		 * extent status tree.
694adb23551SZheng Liu 		 */
695adb23551SZheng Liu 		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
696bb5835edSTheodore Ts'o 		    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
697adb23551SZheng Liu 			if (ext4_es_is_written(&es))
698c86d8db3SJan Kara 				goto out_sem;
699adb23551SZheng Liu 		}
700f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
701f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
702f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
703d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
704ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
705f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
706f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
707f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
708f7fec032SZheng Liu 					    map->m_pblk, status);
709c86d8db3SJan Kara 		if (ret < 0) {
71051865fdaSZheng Liu 			retval = ret;
711c86d8db3SJan Kara 			goto out_sem;
712c86d8db3SJan Kara 		}
71351865fdaSZheng Liu 	}
7145356f261SAditya Kali 
715c86d8db3SJan Kara out_sem:
7160e855ac8SAneesh Kumar K.V 	up_write((&EXT4_I(inode)->i_data_sem));
717e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
718b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
7196fd058f7STheodore Ts'o 		if (ret != 0)
7206fd058f7STheodore Ts'o 			return ret;
72106bd3c36SJan Kara 
72206bd3c36SJan Kara 		/*
72306bd3c36SJan Kara 		 * Inodes with freshly allocated blocks where contents will be
72406bd3c36SJan Kara 		 * visible after transaction commit must be on transaction's
72506bd3c36SJan Kara 		 * ordered data list.
72606bd3c36SJan Kara 		 */
72706bd3c36SJan Kara 		if (map->m_flags & EXT4_MAP_NEW &&
72806bd3c36SJan Kara 		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
72906bd3c36SJan Kara 		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
73002749a4cSTahsin Erdogan 		    !ext4_is_quota_file(inode) &&
73106bd3c36SJan Kara 		    ext4_should_order_data(inode)) {
73273131fbbSRoss Zwisler 			loff_t start_byte =
73373131fbbSRoss Zwisler 				(loff_t)map->m_lblk << inode->i_blkbits;
73473131fbbSRoss Zwisler 			loff_t length = (loff_t)map->m_len << inode->i_blkbits;
73573131fbbSRoss Zwisler 
736ee0876bcSJan Kara 			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
73773131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_wait(handle, inode,
73873131fbbSRoss Zwisler 						start_byte, length);
739ee0876bcSJan Kara 			else
74073131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_write(handle, inode,
74173131fbbSRoss Zwisler 						start_byte, length);
74206bd3c36SJan Kara 			if (ret)
74306bd3c36SJan Kara 				return ret;
74406bd3c36SJan Kara 		}
745a80f7fcfSHarshad Shirwadkar 		ext4_fc_track_range(handle, inode, map->m_lblk,
746aa75f4d3SHarshad Shirwadkar 			    map->m_lblk + map->m_len - 1);
7476fd058f7STheodore Ts'o 	}
748ec8c60beSRitesh Harjani 
749ec8c60beSRitesh Harjani 	if (retval < 0)
75070aa1554SRitesh Harjani 		ext_debug(inode, "failed with err %d\n", retval);
7510e855ac8SAneesh Kumar K.V 	return retval;
7520e855ac8SAneesh Kumar K.V }
7530e855ac8SAneesh Kumar K.V 
754ed8ad838SJan Kara /*
755ed8ad838SJan Kara  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
756ed8ad838SJan Kara  * we have to be careful as someone else may be manipulating b_state as well.
757ed8ad838SJan Kara  */
758ed8ad838SJan Kara static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
759ed8ad838SJan Kara {
760ed8ad838SJan Kara 	unsigned long old_state;
761ed8ad838SJan Kara 	unsigned long new_state;
762ed8ad838SJan Kara 
763ed8ad838SJan Kara 	flags &= EXT4_MAP_FLAGS;
764ed8ad838SJan Kara 
765ed8ad838SJan Kara 	/* Dummy buffer_head? Set non-atomically. */
766ed8ad838SJan Kara 	if (!bh->b_page) {
767ed8ad838SJan Kara 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
768ed8ad838SJan Kara 		return;
769ed8ad838SJan Kara 	}
770ed8ad838SJan Kara 	/*
771ed8ad838SJan Kara 	 * Someone else may be modifying b_state. Be careful! This is ugly but
772ed8ad838SJan Kara 	 * once we get rid of using bh as a container for mapping information
773ed8ad838SJan Kara 	 * to pass to / from get_block functions, this can go away.
774ed8ad838SJan Kara 	 */
775ed8ad838SJan Kara 	do {
776ed8ad838SJan Kara 		old_state = READ_ONCE(bh->b_state);
777ed8ad838SJan Kara 		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
778ed8ad838SJan Kara 	} while (unlikely(
779ed8ad838SJan Kara 		 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
780ed8ad838SJan Kara }
781ed8ad838SJan Kara 
7822ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
7832ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
784ac27a0ecSDave Kleikamp {
7852ed88685STheodore Ts'o 	struct ext4_map_blocks map;
786efe70c29SJan Kara 	int ret = 0;
787ac27a0ecSDave Kleikamp 
78846c7f254STao Ma 	if (ext4_has_inline_data(inode))
78946c7f254STao Ma 		return -ERANGE;
79046c7f254STao Ma 
7912ed88685STheodore Ts'o 	map.m_lblk = iblock;
7922ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
7932ed88685STheodore Ts'o 
794efe70c29SJan Kara 	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
795efe70c29SJan Kara 			      flags);
796ac27a0ecSDave Kleikamp 	if (ret > 0) {
7972ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
798ed8ad838SJan Kara 		ext4_update_bh_state(bh, map.m_flags);
7992ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
800ac27a0ecSDave Kleikamp 		ret = 0;
801547edce3SRoss Zwisler 	} else if (ret == 0) {
802547edce3SRoss Zwisler 		/* hole case, need to fill in bh->b_size */
803547edce3SRoss Zwisler 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
804ac27a0ecSDave Kleikamp 	}
805ac27a0ecSDave Kleikamp 	return ret;
806ac27a0ecSDave Kleikamp }
807ac27a0ecSDave Kleikamp 
8082ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
8092ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
8102ed88685STheodore Ts'o {
8112ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
8122ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
8132ed88685STheodore Ts'o }
8142ed88685STheodore Ts'o 
815ac27a0ecSDave Kleikamp /*
816705965bdSJan Kara  * Get block function used when preparing for buffered write if we require
817705965bdSJan Kara  * creating an unwritten extent if blocks haven't been allocated.  The extent
818705965bdSJan Kara  * will be converted to written after the IO is complete.
819705965bdSJan Kara  */
820705965bdSJan Kara int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
821705965bdSJan Kara 			     struct buffer_head *bh_result, int create)
822705965bdSJan Kara {
823705965bdSJan Kara 	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
824705965bdSJan Kara 		   inode->i_ino, create);
825705965bdSJan Kara 	return _ext4_get_block(inode, iblock, bh_result,
826705965bdSJan Kara 			       EXT4_GET_BLOCKS_IO_CREATE_EXT);
827705965bdSJan Kara }
828705965bdSJan Kara 
829efe70c29SJan Kara /* Maximum number of blocks we map for direct IO at once. */
830efe70c29SJan Kara #define DIO_MAX_BLOCKS 4096
831efe70c29SJan Kara 
832e84dfbe2SJan Kara /*
833ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
834ac27a0ecSDave Kleikamp  */
835617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
836c5e298aeSTheodore Ts'o 				ext4_lblk_t block, int map_flags)
837ac27a0ecSDave Kleikamp {
8382ed88685STheodore Ts'o 	struct ext4_map_blocks map;
8392ed88685STheodore Ts'o 	struct buffer_head *bh;
840c5e298aeSTheodore Ts'o 	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
84110560082STheodore Ts'o 	int err;
842ac27a0ecSDave Kleikamp 
843837c23fbSChunguang Xu 	ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8448016e29fSHarshad Shirwadkar 		    || handle != NULL || create == 0);
845ac27a0ecSDave Kleikamp 
8462ed88685STheodore Ts'o 	map.m_lblk = block;
8472ed88685STheodore Ts'o 	map.m_len = 1;
848c5e298aeSTheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map, map_flags);
8492ed88685STheodore Ts'o 
85010560082STheodore Ts'o 	if (err == 0)
85110560082STheodore Ts'o 		return create ? ERR_PTR(-ENOSPC) : NULL;
8522ed88685STheodore Ts'o 	if (err < 0)
85310560082STheodore Ts'o 		return ERR_PTR(err);
8542ed88685STheodore Ts'o 
8552ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
85610560082STheodore Ts'o 	if (unlikely(!bh))
85710560082STheodore Ts'o 		return ERR_PTR(-ENOMEM);
8582ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
859837c23fbSChunguang Xu 		ASSERT(create != 0);
860837c23fbSChunguang Xu 		ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
8618016e29fSHarshad Shirwadkar 			    || (handle != NULL));
862ac27a0ecSDave Kleikamp 
863ac27a0ecSDave Kleikamp 		/*
864ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
865ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
866ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
867617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
868ac27a0ecSDave Kleikamp 		 * problem.
869ac27a0ecSDave Kleikamp 		 */
870ac27a0ecSDave Kleikamp 		lock_buffer(bh);
871ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
87210560082STheodore Ts'o 		err = ext4_journal_get_create_access(handle, bh);
87310560082STheodore Ts'o 		if (unlikely(err)) {
87410560082STheodore Ts'o 			unlock_buffer(bh);
87510560082STheodore Ts'o 			goto errout;
87610560082STheodore Ts'o 		}
87710560082STheodore Ts'o 		if (!buffer_uptodate(bh)) {
878ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
879ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
880ac27a0ecSDave Kleikamp 		}
881ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
8820390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
8830390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
88410560082STheodore Ts'o 		if (unlikely(err))
88510560082STheodore Ts'o 			goto errout;
88610560082STheodore Ts'o 	} else
887ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
888ac27a0ecSDave Kleikamp 	return bh;
88910560082STheodore Ts'o errout:
89010560082STheodore Ts'o 	brelse(bh);
89110560082STheodore Ts'o 	return ERR_PTR(err);
892ac27a0ecSDave Kleikamp }
893ac27a0ecSDave Kleikamp 
894617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
895c5e298aeSTheodore Ts'o 			       ext4_lblk_t block, int map_flags)
896ac27a0ecSDave Kleikamp {
897ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
8982d069c08Szhangyi (F) 	int ret;
899ac27a0ecSDave Kleikamp 
900c5e298aeSTheodore Ts'o 	bh = ext4_getblk(handle, inode, block, map_flags);
9011c215028STheodore Ts'o 	if (IS_ERR(bh))
902ac27a0ecSDave Kleikamp 		return bh;
9037963e5acSZhangXiaoxu 	if (!bh || ext4_buffer_uptodate(bh))
904ac27a0ecSDave Kleikamp 		return bh;
9052d069c08Szhangyi (F) 
9062d069c08Szhangyi (F) 	ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
9072d069c08Szhangyi (F) 	if (ret) {
908ac27a0ecSDave Kleikamp 		put_bh(bh);
9092d069c08Szhangyi (F) 		return ERR_PTR(ret);
9102d069c08Szhangyi (F) 	}
9112d069c08Szhangyi (F) 	return bh;
912ac27a0ecSDave Kleikamp }
913ac27a0ecSDave Kleikamp 
9149699d4f9STahsin Erdogan /* Read a contiguous batch of blocks. */
9159699d4f9STahsin Erdogan int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
9169699d4f9STahsin Erdogan 		     bool wait, struct buffer_head **bhs)
9179699d4f9STahsin Erdogan {
9189699d4f9STahsin Erdogan 	int i, err;
9199699d4f9STahsin Erdogan 
9209699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9219699d4f9STahsin Erdogan 		bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
9229699d4f9STahsin Erdogan 		if (IS_ERR(bhs[i])) {
9239699d4f9STahsin Erdogan 			err = PTR_ERR(bhs[i]);
9249699d4f9STahsin Erdogan 			bh_count = i;
9259699d4f9STahsin Erdogan 			goto out_brelse;
9269699d4f9STahsin Erdogan 		}
9279699d4f9STahsin Erdogan 	}
9289699d4f9STahsin Erdogan 
9299699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9309699d4f9STahsin Erdogan 		/* Note that NULL bhs[i] is valid because of holes. */
9312d069c08Szhangyi (F) 		if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
9322d069c08Szhangyi (F) 			ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
9339699d4f9STahsin Erdogan 
9349699d4f9STahsin Erdogan 	if (!wait)
9359699d4f9STahsin Erdogan 		return 0;
9369699d4f9STahsin Erdogan 
9379699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9389699d4f9STahsin Erdogan 		if (bhs[i])
9399699d4f9STahsin Erdogan 			wait_on_buffer(bhs[i]);
9409699d4f9STahsin Erdogan 
9419699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9429699d4f9STahsin Erdogan 		if (bhs[i] && !buffer_uptodate(bhs[i])) {
9439699d4f9STahsin Erdogan 			err = -EIO;
9449699d4f9STahsin Erdogan 			goto out_brelse;
9459699d4f9STahsin Erdogan 		}
9469699d4f9STahsin Erdogan 	}
9479699d4f9STahsin Erdogan 	return 0;
9489699d4f9STahsin Erdogan 
9499699d4f9STahsin Erdogan out_brelse:
9509699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9519699d4f9STahsin Erdogan 		brelse(bhs[i]);
9529699d4f9STahsin Erdogan 		bhs[i] = NULL;
9539699d4f9STahsin Erdogan 	}
9549699d4f9STahsin Erdogan 	return err;
9559699d4f9STahsin Erdogan }
9569699d4f9STahsin Erdogan 
957f19d5870STao Ma int ext4_walk_page_buffers(handle_t *handle,
958ac27a0ecSDave Kleikamp 			   struct buffer_head *head,
959ac27a0ecSDave Kleikamp 			   unsigned from,
960ac27a0ecSDave Kleikamp 			   unsigned to,
961ac27a0ecSDave Kleikamp 			   int *partial,
962ac27a0ecSDave Kleikamp 			   int (*fn)(handle_t *handle,
963ac27a0ecSDave Kleikamp 				     struct buffer_head *bh))
964ac27a0ecSDave Kleikamp {
965ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
966ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
967ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
968ac27a0ecSDave Kleikamp 	int err, ret = 0;
969ac27a0ecSDave Kleikamp 	struct buffer_head *next;
970ac27a0ecSDave Kleikamp 
971ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
972ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
973de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
974ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
975ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
976ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
977ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
978ac27a0ecSDave Kleikamp 				*partial = 1;
979ac27a0ecSDave Kleikamp 			continue;
980ac27a0ecSDave Kleikamp 		}
981ac27a0ecSDave Kleikamp 		err = (*fn)(handle, bh);
982ac27a0ecSDave Kleikamp 		if (!ret)
983ac27a0ecSDave Kleikamp 			ret = err;
984ac27a0ecSDave Kleikamp 	}
985ac27a0ecSDave Kleikamp 	return ret;
986ac27a0ecSDave Kleikamp }
987ac27a0ecSDave Kleikamp 
988ac27a0ecSDave Kleikamp /*
989ac27a0ecSDave Kleikamp  * To preserve ordering, it is essential that the hole instantiation and
990ac27a0ecSDave Kleikamp  * the data write be encapsulated in a single transaction.  We cannot
991617ba13bSMingming Cao  * close off a transaction and start a new one between the ext4_get_block()
992dab291afSMingming Cao  * and the commit_write().  So doing the jbd2_journal_start at the start of
993ac27a0ecSDave Kleikamp  * prepare_write() is the right place.
994ac27a0ecSDave Kleikamp  *
99536ade451SJan Kara  * Also, this function can nest inside ext4_writepage().  In that case, we
99636ade451SJan Kara  * *know* that ext4_writepage() has generated enough buffer credits to do the
99736ade451SJan Kara  * whole page.  So we won't block on the journal in that case, which is good,
99836ade451SJan Kara  * because the caller may be PF_MEMALLOC.
999ac27a0ecSDave Kleikamp  *
1000617ba13bSMingming Cao  * By accident, ext4 can be reentered when a transaction is open via
1001ac27a0ecSDave Kleikamp  * quota file writes.  If we were to commit the transaction while thus
1002ac27a0ecSDave Kleikamp  * reentered, there can be a deadlock - we would be holding a quota
1003ac27a0ecSDave Kleikamp  * lock, and the commit would never complete if another thread had a
1004ac27a0ecSDave Kleikamp  * transaction open and was blocking on the quota lock - a ranking
1005ac27a0ecSDave Kleikamp  * violation.
1006ac27a0ecSDave Kleikamp  *
1007dab291afSMingming Cao  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1008ac27a0ecSDave Kleikamp  * will _not_ run commit under these circumstances because handle->h_ref
1009ac27a0ecSDave Kleikamp  * is elevated.  We'll still have enough credits for the tiny quotafile
1010ac27a0ecSDave Kleikamp  * write.
1011ac27a0ecSDave Kleikamp  */
1012f19d5870STao Ma int do_journal_get_write_access(handle_t *handle,
1013ac27a0ecSDave Kleikamp 				struct buffer_head *bh)
1014ac27a0ecSDave Kleikamp {
101556d35a4cSJan Kara 	int dirty = buffer_dirty(bh);
101656d35a4cSJan Kara 	int ret;
101756d35a4cSJan Kara 
1018ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1019ac27a0ecSDave Kleikamp 		return 0;
102056d35a4cSJan Kara 	/*
1021ebdec241SChristoph Hellwig 	 * __block_write_begin() could have dirtied some buffers. Clean
102256d35a4cSJan Kara 	 * the dirty bit as jbd2_journal_get_write_access() could complain
102356d35a4cSJan Kara 	 * otherwise about fs integrity issues. Setting of the dirty bit
1024ebdec241SChristoph Hellwig 	 * by __block_write_begin() isn't a real problem here as we clear
102556d35a4cSJan Kara 	 * the bit before releasing a page lock and thus writeback cannot
102656d35a4cSJan Kara 	 * ever write the buffer.
102756d35a4cSJan Kara 	 */
102856d35a4cSJan Kara 	if (dirty)
102956d35a4cSJan Kara 		clear_buffer_dirty(bh);
10305d601255Sliang xie 	BUFFER_TRACE(bh, "get write access");
103156d35a4cSJan Kara 	ret = ext4_journal_get_write_access(handle, bh);
103256d35a4cSJan Kara 	if (!ret && dirty)
103356d35a4cSJan Kara 		ret = ext4_handle_dirty_metadata(handle, NULL, bh);
103456d35a4cSJan Kara 	return ret;
1035ac27a0ecSDave Kleikamp }
1036ac27a0ecSDave Kleikamp 
1037643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
10382058f83aSMichael Halcrow static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
10392058f83aSMichael Halcrow 				  get_block_t *get_block)
10402058f83aSMichael Halcrow {
104109cbfeafSKirill A. Shutemov 	unsigned from = pos & (PAGE_SIZE - 1);
10422058f83aSMichael Halcrow 	unsigned to = from + len;
10432058f83aSMichael Halcrow 	struct inode *inode = page->mapping->host;
10442058f83aSMichael Halcrow 	unsigned block_start, block_end;
10452058f83aSMichael Halcrow 	sector_t block;
10462058f83aSMichael Halcrow 	int err = 0;
10472058f83aSMichael Halcrow 	unsigned blocksize = inode->i_sb->s_blocksize;
10482058f83aSMichael Halcrow 	unsigned bbits;
10490b578f35SChandan Rajendra 	struct buffer_head *bh, *head, *wait[2];
10500b578f35SChandan Rajendra 	int nr_wait = 0;
10510b578f35SChandan Rajendra 	int i;
10522058f83aSMichael Halcrow 
10532058f83aSMichael Halcrow 	BUG_ON(!PageLocked(page));
105409cbfeafSKirill A. Shutemov 	BUG_ON(from > PAGE_SIZE);
105509cbfeafSKirill A. Shutemov 	BUG_ON(to > PAGE_SIZE);
10562058f83aSMichael Halcrow 	BUG_ON(from > to);
10572058f83aSMichael Halcrow 
10582058f83aSMichael Halcrow 	if (!page_has_buffers(page))
10592058f83aSMichael Halcrow 		create_empty_buffers(page, blocksize, 0);
10602058f83aSMichael Halcrow 	head = page_buffers(page);
10612058f83aSMichael Halcrow 	bbits = ilog2(blocksize);
106209cbfeafSKirill A. Shutemov 	block = (sector_t)page->index << (PAGE_SHIFT - bbits);
10632058f83aSMichael Halcrow 
10642058f83aSMichael Halcrow 	for (bh = head, block_start = 0; bh != head || !block_start;
10652058f83aSMichael Halcrow 	    block++, block_start = block_end, bh = bh->b_this_page) {
10662058f83aSMichael Halcrow 		block_end = block_start + blocksize;
10672058f83aSMichael Halcrow 		if (block_end <= from || block_start >= to) {
10682058f83aSMichael Halcrow 			if (PageUptodate(page)) {
10692058f83aSMichael Halcrow 				set_buffer_uptodate(bh);
10702058f83aSMichael Halcrow 			}
10712058f83aSMichael Halcrow 			continue;
10722058f83aSMichael Halcrow 		}
10732058f83aSMichael Halcrow 		if (buffer_new(bh))
10742058f83aSMichael Halcrow 			clear_buffer_new(bh);
10752058f83aSMichael Halcrow 		if (!buffer_mapped(bh)) {
10762058f83aSMichael Halcrow 			WARN_ON(bh->b_size != blocksize);
10772058f83aSMichael Halcrow 			err = get_block(inode, block, bh, 1);
10782058f83aSMichael Halcrow 			if (err)
10792058f83aSMichael Halcrow 				break;
10802058f83aSMichael Halcrow 			if (buffer_new(bh)) {
10812058f83aSMichael Halcrow 				if (PageUptodate(page)) {
10822058f83aSMichael Halcrow 					clear_buffer_new(bh);
10832058f83aSMichael Halcrow 					set_buffer_uptodate(bh);
10842058f83aSMichael Halcrow 					mark_buffer_dirty(bh);
10852058f83aSMichael Halcrow 					continue;
10862058f83aSMichael Halcrow 				}
10872058f83aSMichael Halcrow 				if (block_end > to || block_start < from)
10882058f83aSMichael Halcrow 					zero_user_segments(page, to, block_end,
10892058f83aSMichael Halcrow 							   block_start, from);
10902058f83aSMichael Halcrow 				continue;
10912058f83aSMichael Halcrow 			}
10922058f83aSMichael Halcrow 		}
10932058f83aSMichael Halcrow 		if (PageUptodate(page)) {
10942058f83aSMichael Halcrow 			set_buffer_uptodate(bh);
10952058f83aSMichael Halcrow 			continue;
10962058f83aSMichael Halcrow 		}
10972058f83aSMichael Halcrow 		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
10982058f83aSMichael Halcrow 		    !buffer_unwritten(bh) &&
10992058f83aSMichael Halcrow 		    (block_start < from || block_end > to)) {
11002d069c08Szhangyi (F) 			ext4_read_bh_lock(bh, 0, false);
11010b578f35SChandan Rajendra 			wait[nr_wait++] = bh;
11022058f83aSMichael Halcrow 		}
11032058f83aSMichael Halcrow 	}
11042058f83aSMichael Halcrow 	/*
11052058f83aSMichael Halcrow 	 * If we issued read requests, let them complete.
11062058f83aSMichael Halcrow 	 */
11070b578f35SChandan Rajendra 	for (i = 0; i < nr_wait; i++) {
11080b578f35SChandan Rajendra 		wait_on_buffer(wait[i]);
11090b578f35SChandan Rajendra 		if (!buffer_uptodate(wait[i]))
11102058f83aSMichael Halcrow 			err = -EIO;
11112058f83aSMichael Halcrow 	}
11127e0785fcSChandan Rajendra 	if (unlikely(err)) {
11132058f83aSMichael Halcrow 		page_zero_new_buffers(page, from, to);
11144f74d15fSEric Biggers 	} else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
11150b578f35SChandan Rajendra 		for (i = 0; i < nr_wait; i++) {
11160b578f35SChandan Rajendra 			int err2;
11170b578f35SChandan Rajendra 
11180b578f35SChandan Rajendra 			err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
11190b578f35SChandan Rajendra 								bh_offset(wait[i]));
11200b578f35SChandan Rajendra 			if (err2) {
11210b578f35SChandan Rajendra 				clear_buffer_uptodate(wait[i]);
11220b578f35SChandan Rajendra 				err = err2;
11230b578f35SChandan Rajendra 			}
11240b578f35SChandan Rajendra 		}
11257e0785fcSChandan Rajendra 	}
11267e0785fcSChandan Rajendra 
11272058f83aSMichael Halcrow 	return err;
11282058f83aSMichael Halcrow }
11292058f83aSMichael Halcrow #endif
11302058f83aSMichael Halcrow 
1131bfc1af65SNick Piggin static int ext4_write_begin(struct file *file, struct address_space *mapping,
1132bfc1af65SNick Piggin 			    loff_t pos, unsigned len, unsigned flags,
1133bfc1af65SNick Piggin 			    struct page **pagep, void **fsdata)
1134ac27a0ecSDave Kleikamp {
1135bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
11361938a150SAneesh Kumar K.V 	int ret, needed_blocks;
1137ac27a0ecSDave Kleikamp 	handle_t *handle;
1138ac27a0ecSDave Kleikamp 	int retries = 0;
1139bfc1af65SNick Piggin 	struct page *page;
1140bfc1af65SNick Piggin 	pgoff_t index;
1141bfc1af65SNick Piggin 	unsigned from, to;
1142bfc1af65SNick Piggin 
11430db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
11440db1ff22STheodore Ts'o 		return -EIO;
11450db1ff22STheodore Ts'o 
11469bffad1eSTheodore Ts'o 	trace_ext4_write_begin(inode, pos, len, flags);
11471938a150SAneesh Kumar K.V 	/*
11481938a150SAneesh Kumar K.V 	 * Reserve one block more for addition to orphan list in case
11491938a150SAneesh Kumar K.V 	 * we allocate blocks but write fails for some reason
11501938a150SAneesh Kumar K.V 	 */
11511938a150SAneesh Kumar K.V 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
115209cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
115309cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1154bfc1af65SNick Piggin 	to = from + len;
1155ac27a0ecSDave Kleikamp 
1156f19d5870STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1157f19d5870STao Ma 		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1158f19d5870STao Ma 						    flags, pagep);
1159f19d5870STao Ma 		if (ret < 0)
116047564bfbSTheodore Ts'o 			return ret;
116147564bfbSTheodore Ts'o 		if (ret == 1)
116247564bfbSTheodore Ts'o 			return 0;
1163f19d5870STao Ma 	}
1164f19d5870STao Ma 
116547564bfbSTheodore Ts'o 	/*
116647564bfbSTheodore Ts'o 	 * grab_cache_page_write_begin() can take a long time if the
116747564bfbSTheodore Ts'o 	 * system is thrashing due to memory pressure, or if the page
116847564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
116947564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
117047564bfbSTheodore Ts'o 	 * the page (if needed) without using GFP_NOFS.
117147564bfbSTheodore Ts'o 	 */
117247564bfbSTheodore Ts'o retry_grab:
117354566b2cSNick Piggin 	page = grab_cache_page_write_begin(mapping, index, flags);
117447564bfbSTheodore Ts'o 	if (!page)
117547564bfbSTheodore Ts'o 		return -ENOMEM;
117647564bfbSTheodore Ts'o 	unlock_page(page);
117747564bfbSTheodore Ts'o 
117847564bfbSTheodore Ts'o retry_journal:
11799924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1180ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
118109cbfeafSKirill A. Shutemov 		put_page(page);
118247564bfbSTheodore Ts'o 		return PTR_ERR(handle);
1183cf108bcaSJan Kara 	}
1184f19d5870STao Ma 
118547564bfbSTheodore Ts'o 	lock_page(page);
118647564bfbSTheodore Ts'o 	if (page->mapping != mapping) {
118747564bfbSTheodore Ts'o 		/* The page got truncated from under us */
118847564bfbSTheodore Ts'o 		unlock_page(page);
118909cbfeafSKirill A. Shutemov 		put_page(page);
1190cf108bcaSJan Kara 		ext4_journal_stop(handle);
119147564bfbSTheodore Ts'o 		goto retry_grab;
1192cf108bcaSJan Kara 	}
11937afe5aa5SDmitry Monakhov 	/* In case writeback began while the page was unlocked */
11947afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
1195cf108bcaSJan Kara 
1196643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
11972058f83aSMichael Halcrow 	if (ext4_should_dioread_nolock(inode))
11982058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
1199705965bdSJan Kara 					     ext4_get_block_unwritten);
12002058f83aSMichael Halcrow 	else
12012058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
12022058f83aSMichael Halcrow 					     ext4_get_block);
12032058f83aSMichael Halcrow #else
1204744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
1205705965bdSJan Kara 		ret = __block_write_begin(page, pos, len,
1206705965bdSJan Kara 					  ext4_get_block_unwritten);
1207744692dcSJiaying Zhang 	else
12086e1db88dSChristoph Hellwig 		ret = __block_write_begin(page, pos, len, ext4_get_block);
12092058f83aSMichael Halcrow #endif
1210bfc1af65SNick Piggin 	if (!ret && ext4_should_journal_data(inode)) {
1211f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_buffers(page),
1212f19d5870STao Ma 					     from, to, NULL,
1213f19d5870STao Ma 					     do_journal_get_write_access);
1214b46be050SAndrey Savochkin 	}
1215bfc1af65SNick Piggin 
1216bfc1af65SNick Piggin 	if (ret) {
1217c93d8f88SEric Biggers 		bool extended = (pos + len > inode->i_size) &&
1218c93d8f88SEric Biggers 				!ext4_verity_in_progress(inode);
1219c93d8f88SEric Biggers 
1220bfc1af65SNick Piggin 		unlock_page(page);
1221ae4d5372SAneesh Kumar K.V 		/*
12226e1db88dSChristoph Hellwig 		 * __block_write_begin may have instantiated a few blocks
1223ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
1224ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
12251938a150SAneesh Kumar K.V 		 *
12261938a150SAneesh Kumar K.V 		 * Add inode to orphan list in case we crash before
12271938a150SAneesh Kumar K.V 		 * truncate finishes
1228ae4d5372SAneesh Kumar K.V 		 */
1229c93d8f88SEric Biggers 		if (extended && ext4_can_truncate(inode))
12301938a150SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
12311938a150SAneesh Kumar K.V 
12321938a150SAneesh Kumar K.V 		ext4_journal_stop(handle);
1233c93d8f88SEric Biggers 		if (extended) {
1234b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
12351938a150SAneesh Kumar K.V 			/*
1236ffacfa7aSJan Kara 			 * If truncate failed early the inode might
12371938a150SAneesh Kumar K.V 			 * still be on the orphan list; we need to
12381938a150SAneesh Kumar K.V 			 * make sure the inode is removed from the
12391938a150SAneesh Kumar K.V 			 * orphan list in that case.
12401938a150SAneesh Kumar K.V 			 */
12411938a150SAneesh Kumar K.V 			if (inode->i_nlink)
12421938a150SAneesh Kumar K.V 				ext4_orphan_del(NULL, inode);
12431938a150SAneesh Kumar K.V 		}
1244bfc1af65SNick Piggin 
124547564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
124647564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
124747564bfbSTheodore Ts'o 			goto retry_journal;
124809cbfeafSKirill A. Shutemov 		put_page(page);
124947564bfbSTheodore Ts'o 		return ret;
125047564bfbSTheodore Ts'o 	}
125147564bfbSTheodore Ts'o 	*pagep = page;
1252ac27a0ecSDave Kleikamp 	return ret;
1253ac27a0ecSDave Kleikamp }
1254ac27a0ecSDave Kleikamp 
1255bfc1af65SNick Piggin /* For write_end() in data=journal mode */
1256bfc1af65SNick Piggin static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1257ac27a0ecSDave Kleikamp {
125813fca323STheodore Ts'o 	int ret;
1259ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1260ac27a0ecSDave Kleikamp 		return 0;
1261ac27a0ecSDave Kleikamp 	set_buffer_uptodate(bh);
126213fca323STheodore Ts'o 	ret = ext4_handle_dirty_metadata(handle, NULL, bh);
126313fca323STheodore Ts'o 	clear_buffer_meta(bh);
126413fca323STheodore Ts'o 	clear_buffer_prio(bh);
126513fca323STheodore Ts'o 	return ret;
1266ac27a0ecSDave Kleikamp }
1267ac27a0ecSDave Kleikamp 
1268eed4333fSZheng Liu /*
1269eed4333fSZheng Liu  * We need to pick up the new inode size which generic_commit_write gave us
1270eed4333fSZheng Liu  * `file' can be NULL - eg, when called from page_symlink().
1271eed4333fSZheng Liu  *
1272eed4333fSZheng Liu  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1273eed4333fSZheng Liu  * buffers are managed internally.
1274eed4333fSZheng Liu  */
1275eed4333fSZheng Liu static int ext4_write_end(struct file *file,
1276f8514083SAneesh Kumar K.V 			  struct address_space *mapping,
1277f8514083SAneesh Kumar K.V 			  loff_t pos, unsigned len, unsigned copied,
1278f8514083SAneesh Kumar K.V 			  struct page *page, void *fsdata)
1279f8514083SAneesh Kumar K.V {
1280f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
1281eed4333fSZheng Liu 	struct inode *inode = mapping->host;
12820572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1283eed4333fSZheng Liu 	int ret = 0, ret2;
1284eed4333fSZheng Liu 	int i_size_changed = 0;
1285362eca70STheodore Ts'o 	int inline_data = ext4_has_inline_data(inode);
1286c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1287eed4333fSZheng Liu 
1288eed4333fSZheng Liu 	trace_ext4_write_end(inode, pos, len, copied);
1289362eca70STheodore Ts'o 	if (inline_data) {
129042c832deSTheodore Ts'o 		ret = ext4_write_inline_data_end(inode, pos, len,
1291f19d5870STao Ma 						 copied, page);
1292eb5efbcbSTheodore Ts'o 		if (ret < 0) {
1293eb5efbcbSTheodore Ts'o 			unlock_page(page);
1294eb5efbcbSTheodore Ts'o 			put_page(page);
129542c832deSTheodore Ts'o 			goto errout;
1296eb5efbcbSTheodore Ts'o 		}
129742c832deSTheodore Ts'o 		copied = ret;
129842c832deSTheodore Ts'o 	} else
1299f19d5870STao Ma 		copied = block_write_end(file, mapping, pos,
1300f19d5870STao Ma 					 len, copied, page, fsdata);
1301f8514083SAneesh Kumar K.V 	/*
13024631dbf6SDmitry Monakhov 	 * it's important to update i_size while still holding page lock:
1303f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
1304c93d8f88SEric Biggers 	 *
1305c93d8f88SEric Biggers 	 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1306c93d8f88SEric Biggers 	 * blocks are being written past EOF, so skip the i_size update.
1307f8514083SAneesh Kumar K.V 	 */
1308c93d8f88SEric Biggers 	if (!verity)
13094631dbf6SDmitry Monakhov 		i_size_changed = ext4_update_inode_size(inode, pos + copied);
1310f8514083SAneesh Kumar K.V 	unlock_page(page);
131109cbfeafSKirill A. Shutemov 	put_page(page);
1312f8514083SAneesh Kumar K.V 
1313c93d8f88SEric Biggers 	if (old_size < pos && !verity)
13140572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
1315f8514083SAneesh Kumar K.V 	/*
1316f8514083SAneesh Kumar K.V 	 * Don't mark the inode dirty under page lock. First, it unnecessarily
1317f8514083SAneesh Kumar K.V 	 * makes the holding time of page lock longer. Second, it forces lock
1318f8514083SAneesh Kumar K.V 	 * ordering of page lock and transaction start for journaling
1319f8514083SAneesh Kumar K.V 	 * filesystems.
1320f8514083SAneesh Kumar K.V 	 */
1321362eca70STheodore Ts'o 	if (i_size_changed || inline_data)
13224209ae12SHarshad Shirwadkar 		ret = ext4_mark_inode_dirty(handle, inode);
1323f8514083SAneesh Kumar K.V 
1324c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1325f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1326f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1327f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1328f8514083SAneesh Kumar K.V 		 */
1329f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
133074d553aaSTheodore Ts'o errout:
1331617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1332ac27a0ecSDave Kleikamp 	if (!ret)
1333ac27a0ecSDave Kleikamp 		ret = ret2;
1334bfc1af65SNick Piggin 
1335c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1336b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1337f8514083SAneesh Kumar K.V 		/*
1338ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1339f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1340f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1341f8514083SAneesh Kumar K.V 		 */
1342f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1343f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1344f8514083SAneesh Kumar K.V 	}
1345f8514083SAneesh Kumar K.V 
1346bfc1af65SNick Piggin 	return ret ? ret : copied;
1347ac27a0ecSDave Kleikamp }
1348ac27a0ecSDave Kleikamp 
1349b90197b6STheodore Ts'o /*
1350b90197b6STheodore Ts'o  * This is a private version of page_zero_new_buffers() which doesn't
1351b90197b6STheodore Ts'o  * set the buffer to be dirty, since in data=journalled mode we need
1352b90197b6STheodore Ts'o  * to call ext4_handle_dirty_metadata() instead.
1353b90197b6STheodore Ts'o  */
13543b136499SJan Kara static void ext4_journalled_zero_new_buffers(handle_t *handle,
13553b136499SJan Kara 					    struct page *page,
13563b136499SJan Kara 					    unsigned from, unsigned to)
1357b90197b6STheodore Ts'o {
1358b90197b6STheodore Ts'o 	unsigned int block_start = 0, block_end;
1359b90197b6STheodore Ts'o 	struct buffer_head *head, *bh;
1360b90197b6STheodore Ts'o 
1361b90197b6STheodore Ts'o 	bh = head = page_buffers(page);
1362b90197b6STheodore Ts'o 	do {
1363b90197b6STheodore Ts'o 		block_end = block_start + bh->b_size;
1364b90197b6STheodore Ts'o 		if (buffer_new(bh)) {
1365b90197b6STheodore Ts'o 			if (block_end > from && block_start < to) {
1366b90197b6STheodore Ts'o 				if (!PageUptodate(page)) {
1367b90197b6STheodore Ts'o 					unsigned start, size;
1368b90197b6STheodore Ts'o 
1369b90197b6STheodore Ts'o 					start = max(from, block_start);
1370b90197b6STheodore Ts'o 					size = min(to, block_end) - start;
1371b90197b6STheodore Ts'o 
1372b90197b6STheodore Ts'o 					zero_user(page, start, size);
13733b136499SJan Kara 					write_end_fn(handle, bh);
1374b90197b6STheodore Ts'o 				}
1375b90197b6STheodore Ts'o 				clear_buffer_new(bh);
1376b90197b6STheodore Ts'o 			}
1377b90197b6STheodore Ts'o 		}
1378b90197b6STheodore Ts'o 		block_start = block_end;
1379b90197b6STheodore Ts'o 		bh = bh->b_this_page;
1380b90197b6STheodore Ts'o 	} while (bh != head);
1381b90197b6STheodore Ts'o }
1382b90197b6STheodore Ts'o 
1383bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
1384bfc1af65SNick Piggin 				     struct address_space *mapping,
1385bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
1386bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
1387ac27a0ecSDave Kleikamp {
1388617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1389bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
13900572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1391ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1392ac27a0ecSDave Kleikamp 	int partial = 0;
1393bfc1af65SNick Piggin 	unsigned from, to;
13944631dbf6SDmitry Monakhov 	int size_changed = 0;
1395362eca70STheodore Ts'o 	int inline_data = ext4_has_inline_data(inode);
1396c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1397ac27a0ecSDave Kleikamp 
13989bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
139909cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1400bfc1af65SNick Piggin 	to = from + len;
1401bfc1af65SNick Piggin 
1402441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1403441c8508SCurt Wohlgemuth 
1404362eca70STheodore Ts'o 	if (inline_data) {
1405eb5efbcbSTheodore Ts'o 		ret = ext4_write_inline_data_end(inode, pos, len,
14063fdcfb66STao Ma 						 copied, page);
1407eb5efbcbSTheodore Ts'o 		if (ret < 0) {
1408eb5efbcbSTheodore Ts'o 			unlock_page(page);
1409eb5efbcbSTheodore Ts'o 			put_page(page);
1410eb5efbcbSTheodore Ts'o 			goto errout;
1411eb5efbcbSTheodore Ts'o 		}
1412eb5efbcbSTheodore Ts'o 		copied = ret;
1413eb5efbcbSTheodore Ts'o 	} else if (unlikely(copied < len) && !PageUptodate(page)) {
1414bfc1af65SNick Piggin 		copied = 0;
14153b136499SJan Kara 		ext4_journalled_zero_new_buffers(handle, page, from, to);
14163b136499SJan Kara 	} else {
14173b136499SJan Kara 		if (unlikely(copied < len))
14183b136499SJan Kara 			ext4_journalled_zero_new_buffers(handle, page,
14193b136499SJan Kara 							 from + copied, to);
1420f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
14213b136499SJan Kara 					     from + copied, &partial,
14223b136499SJan Kara 					     write_end_fn);
1423ac27a0ecSDave Kleikamp 		if (!partial)
1424ac27a0ecSDave Kleikamp 			SetPageUptodate(page);
14253fdcfb66STao Ma 	}
1426c93d8f88SEric Biggers 	if (!verity)
14274631dbf6SDmitry Monakhov 		size_changed = ext4_update_inode_size(inode, pos + copied);
142819f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
14292d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
14304631dbf6SDmitry Monakhov 	unlock_page(page);
143109cbfeafSKirill A. Shutemov 	put_page(page);
14324631dbf6SDmitry Monakhov 
1433c93d8f88SEric Biggers 	if (old_size < pos && !verity)
14340572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
14350572639fSXiaoguang Wang 
1436362eca70STheodore Ts'o 	if (size_changed || inline_data) {
1437617ba13bSMingming Cao 		ret2 = ext4_mark_inode_dirty(handle, inode);
1438ac27a0ecSDave Kleikamp 		if (!ret)
1439ac27a0ecSDave Kleikamp 			ret = ret2;
1440ac27a0ecSDave Kleikamp 	}
1441bfc1af65SNick Piggin 
1442c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1443f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1444f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1445f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1446f8514083SAneesh Kumar K.V 		 */
1447f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1448f8514083SAneesh Kumar K.V 
1449eb5efbcbSTheodore Ts'o errout:
1450617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1451ac27a0ecSDave Kleikamp 	if (!ret)
1452ac27a0ecSDave Kleikamp 		ret = ret2;
1453c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1454b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1455f8514083SAneesh Kumar K.V 		/*
1456ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1457f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1458f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1459f8514083SAneesh Kumar K.V 		 */
1460f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1461f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1462f8514083SAneesh Kumar K.V 	}
1463bfc1af65SNick Piggin 
1464bfc1af65SNick Piggin 	return ret ? ret : copied;
1465ac27a0ecSDave Kleikamp }
1466d2a17637SMingming Cao 
14679d0be502STheodore Ts'o /*
1468c27e43a1SEric Whitney  * Reserve space for a single cluster
14699d0be502STheodore Ts'o  */
1470c27e43a1SEric Whitney static int ext4_da_reserve_space(struct inode *inode)
1471d2a17637SMingming Cao {
1472d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
14730637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
14745dd4056dSChristoph Hellwig 	int ret;
1475d2a17637SMingming Cao 
147660e58e0fSMingming Cao 	/*
147772b8ab9dSEric Sandeen 	 * We will charge metadata quota at writeout time; this saves
147872b8ab9dSEric Sandeen 	 * us from metadata over-estimation, though we may go over by
147972b8ab9dSEric Sandeen 	 * a small amount in the end.  Here we just reserve for data.
148060e58e0fSMingming Cao 	 */
14817b415bf6SAditya Kali 	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
14825dd4056dSChristoph Hellwig 	if (ret)
14835dd4056dSChristoph Hellwig 		return ret;
148403179fe9STheodore Ts'o 
148503179fe9STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
148671d4f7d0STheodore Ts'o 	if (ext4_claim_free_clusters(sbi, 1, 0)) {
148703179fe9STheodore Ts'o 		spin_unlock(&ei->i_block_reservation_lock);
148803179fe9STheodore Ts'o 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1489d2a17637SMingming Cao 		return -ENOSPC;
1490d2a17637SMingming Cao 	}
14919d0be502STheodore Ts'o 	ei->i_reserved_data_blocks++;
1492c27e43a1SEric Whitney 	trace_ext4_da_reserve_space(inode);
14930637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
149439bc680aSDmitry Monakhov 
1495d2a17637SMingming Cao 	return 0;       /* success */
1496d2a17637SMingming Cao }
1497d2a17637SMingming Cao 
1498f456767dSEric Whitney void ext4_da_release_space(struct inode *inode, int to_free)
1499d2a17637SMingming Cao {
1500d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
15010637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1502d2a17637SMingming Cao 
1503cd213226SMingming Cao 	if (!to_free)
1504cd213226SMingming Cao 		return;		/* Nothing to release, exit */
1505cd213226SMingming Cao 
1506d2a17637SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1507cd213226SMingming Cao 
15085a58ec87SLi Zefan 	trace_ext4_da_release_space(inode, to_free);
15090637c6f4STheodore Ts'o 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1510cd213226SMingming Cao 		/*
15110637c6f4STheodore Ts'o 		 * if there aren't enough reserved blocks, then the
15120637c6f4STheodore Ts'o 		 * counter is messed up somewhere.  Since this
15130637c6f4STheodore Ts'o 		 * function is called from invalidate page, it's
15140637c6f4STheodore Ts'o 		 * harmless to return without any action.
1515cd213226SMingming Cao 		 */
15168de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "ext4_da_release_space: "
15170637c6f4STheodore Ts'o 			 "ino %lu, to_free %d with only %d reserved "
15181084f252STheodore Ts'o 			 "data blocks", inode->i_ino, to_free,
15190637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
15200637c6f4STheodore Ts'o 		WARN_ON(1);
15210637c6f4STheodore Ts'o 		to_free = ei->i_reserved_data_blocks;
15220637c6f4STheodore Ts'o 	}
15230637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= to_free;
15240637c6f4STheodore Ts'o 
152572b8ab9dSEric Sandeen 	/* update fs dirty data blocks counter */
152657042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1527d2a17637SMingming Cao 
1528d2a17637SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
152960e58e0fSMingming Cao 
15307b415bf6SAditya Kali 	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1531d2a17637SMingming Cao }
1532d2a17637SMingming Cao 
1533ac27a0ecSDave Kleikamp /*
153464769240SAlex Tomas  * Delayed allocation stuff
153564769240SAlex Tomas  */
153664769240SAlex Tomas 
15374e7ea81dSJan Kara struct mpage_da_data {
15384e7ea81dSJan Kara 	struct inode *inode;
15394e7ea81dSJan Kara 	struct writeback_control *wbc;
15406b523df4SJan Kara 
15414e7ea81dSJan Kara 	pgoff_t first_page;	/* The first page to write */
15424e7ea81dSJan Kara 	pgoff_t next_page;	/* Current page to examine */
15434e7ea81dSJan Kara 	pgoff_t last_page;	/* Last page to examine */
154464769240SAlex Tomas 	/*
15454e7ea81dSJan Kara 	 * Extent to map - this can be after first_page because that can be
15464e7ea81dSJan Kara 	 * fully mapped. We somewhat abuse m_flags to store whether the extent
15474e7ea81dSJan Kara 	 * is delalloc or unwritten.
154864769240SAlex Tomas 	 */
15494e7ea81dSJan Kara 	struct ext4_map_blocks map;
15504e7ea81dSJan Kara 	struct ext4_io_submit io_submit;	/* IO submission data */
1551dddbd6acSJan Kara 	unsigned int do_map:1;
15526b8ed620SJan Kara 	unsigned int scanned_until_end:1;
15534e7ea81dSJan Kara };
155464769240SAlex Tomas 
15554e7ea81dSJan Kara static void mpage_release_unused_pages(struct mpage_da_data *mpd,
15564e7ea81dSJan Kara 				       bool invalidate)
1557c4a0c46eSAneesh Kumar K.V {
1558c4a0c46eSAneesh Kumar K.V 	int nr_pages, i;
1559c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
1560c4a0c46eSAneesh Kumar K.V 	struct pagevec pvec;
1561c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1562c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
15634e7ea81dSJan Kara 
15644e7ea81dSJan Kara 	/* This is necessary when next_page == 0. */
15654e7ea81dSJan Kara 	if (mpd->first_page >= mpd->next_page)
15664e7ea81dSJan Kara 		return;
1567c4a0c46eSAneesh Kumar K.V 
15686b8ed620SJan Kara 	mpd->scanned_until_end = 0;
1569c7f5938aSCurt Wohlgemuth 	index = mpd->first_page;
1570c7f5938aSCurt Wohlgemuth 	end   = mpd->next_page - 1;
15714e7ea81dSJan Kara 	if (invalidate) {
15724e7ea81dSJan Kara 		ext4_lblk_t start, last;
157309cbfeafSKirill A. Shutemov 		start = index << (PAGE_SHIFT - inode->i_blkbits);
157409cbfeafSKirill A. Shutemov 		last = end << (PAGE_SHIFT - inode->i_blkbits);
157551865fdaSZheng Liu 		ext4_es_remove_extent(inode, start, last - start + 1);
15764e7ea81dSJan Kara 	}
157751865fdaSZheng Liu 
157886679820SMel Gorman 	pagevec_init(&pvec);
1579c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
1580397162ffSJan Kara 		nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1581c4a0c46eSAneesh Kumar K.V 		if (nr_pages == 0)
1582c4a0c46eSAneesh Kumar K.V 			break;
1583c4a0c46eSAneesh Kumar K.V 		for (i = 0; i < nr_pages; i++) {
1584c4a0c46eSAneesh Kumar K.V 			struct page *page = pvec.pages[i];
15852b85a617SJan Kara 
1586c4a0c46eSAneesh Kumar K.V 			BUG_ON(!PageLocked(page));
1587c4a0c46eSAneesh Kumar K.V 			BUG_ON(PageWriteback(page));
15884e7ea81dSJan Kara 			if (invalidate) {
15894e800c03Swangguang 				if (page_mapped(page))
15904e800c03Swangguang 					clear_page_dirty_for_io(page);
159109cbfeafSKirill A. Shutemov 				block_invalidatepage(page, 0, PAGE_SIZE);
1592c4a0c46eSAneesh Kumar K.V 				ClearPageUptodate(page);
15934e7ea81dSJan Kara 			}
1594c4a0c46eSAneesh Kumar K.V 			unlock_page(page);
1595c4a0c46eSAneesh Kumar K.V 		}
15969b1d0998SJan Kara 		pagevec_release(&pvec);
1597c4a0c46eSAneesh Kumar K.V 	}
1598c4a0c46eSAneesh Kumar K.V }
1599c4a0c46eSAneesh Kumar K.V 
1600df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
1601df22291fSAneesh Kumar K.V {
1602df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
160392b97816STheodore Ts'o 	struct super_block *sb = inode->i_sb;
1604f78ee70dSLukas Czerner 	struct ext4_inode_info *ei = EXT4_I(inode);
160592b97816STheodore Ts'o 
160692b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
16075dee5437STheodore Ts'o 	       EXT4_C2B(EXT4_SB(inode->i_sb),
1608f78ee70dSLukas Czerner 			ext4_count_free_clusters(sb)));
160992b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
161092b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1611f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
161257042651STheodore Ts'o 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
161392b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1614f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
16157b415bf6SAditya Kali 		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
161692b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Block reservation details");
161792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1618f78ee70dSLukas Czerner 		 ei->i_reserved_data_blocks);
1619df22291fSAneesh Kumar K.V 	return;
1620df22291fSAneesh Kumar K.V }
1621df22291fSAneesh Kumar K.V 
1622c364b22cSAneesh Kumar K.V static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
162329fa89d0SAneesh Kumar K.V {
1624c364b22cSAneesh Kumar K.V 	return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
162529fa89d0SAneesh Kumar K.V }
162629fa89d0SAneesh Kumar K.V 
162764769240SAlex Tomas /*
16280b02f4c0SEric Whitney  * ext4_insert_delayed_block - adds a delayed block to the extents status
16290b02f4c0SEric Whitney  *                             tree, incrementing the reserved cluster/block
16300b02f4c0SEric Whitney  *                             count or making a pending reservation
16310b02f4c0SEric Whitney  *                             where needed
16320b02f4c0SEric Whitney  *
16330b02f4c0SEric Whitney  * @inode - file containing the newly added block
16340b02f4c0SEric Whitney  * @lblk - logical block to be added
16350b02f4c0SEric Whitney  *
16360b02f4c0SEric Whitney  * Returns 0 on success, negative error code on failure.
16370b02f4c0SEric Whitney  */
16380b02f4c0SEric Whitney static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
16390b02f4c0SEric Whitney {
16400b02f4c0SEric Whitney 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
16410b02f4c0SEric Whitney 	int ret;
16420b02f4c0SEric Whitney 	bool allocated = false;
16430b02f4c0SEric Whitney 
16440b02f4c0SEric Whitney 	/*
16450b02f4c0SEric Whitney 	 * If the cluster containing lblk is shared with a delayed,
16460b02f4c0SEric Whitney 	 * written, or unwritten extent in a bigalloc file system, it's
16470b02f4c0SEric Whitney 	 * already been accounted for and does not need to be reserved.
16480b02f4c0SEric Whitney 	 * A pending reservation must be made for the cluster if it's
16490b02f4c0SEric Whitney 	 * shared with a written or unwritten extent and doesn't already
16500b02f4c0SEric Whitney 	 * have one.  Written and unwritten extents can be purged from the
16510b02f4c0SEric Whitney 	 * extents status tree if the system is under memory pressure, so
16520b02f4c0SEric Whitney 	 * it's necessary to examine the extent tree if a search of the
16530b02f4c0SEric Whitney 	 * extents status tree doesn't get a match.
16540b02f4c0SEric Whitney 	 */
16550b02f4c0SEric Whitney 	if (sbi->s_cluster_ratio == 1) {
16560b02f4c0SEric Whitney 		ret = ext4_da_reserve_space(inode);
16570b02f4c0SEric Whitney 		if (ret != 0)   /* ENOSPC */
16580b02f4c0SEric Whitney 			goto errout;
16590b02f4c0SEric Whitney 	} else {   /* bigalloc */
16600b02f4c0SEric Whitney 		if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
16610b02f4c0SEric Whitney 			if (!ext4_es_scan_clu(inode,
16620b02f4c0SEric Whitney 					      &ext4_es_is_mapped, lblk)) {
16630b02f4c0SEric Whitney 				ret = ext4_clu_mapped(inode,
16640b02f4c0SEric Whitney 						      EXT4_B2C(sbi, lblk));
16650b02f4c0SEric Whitney 				if (ret < 0)
16660b02f4c0SEric Whitney 					goto errout;
16670b02f4c0SEric Whitney 				if (ret == 0) {
16680b02f4c0SEric Whitney 					ret = ext4_da_reserve_space(inode);
16690b02f4c0SEric Whitney 					if (ret != 0)   /* ENOSPC */
16700b02f4c0SEric Whitney 						goto errout;
16710b02f4c0SEric Whitney 				} else {
16720b02f4c0SEric Whitney 					allocated = true;
16730b02f4c0SEric Whitney 				}
16740b02f4c0SEric Whitney 			} else {
16750b02f4c0SEric Whitney 				allocated = true;
16760b02f4c0SEric Whitney 			}
16770b02f4c0SEric Whitney 		}
16780b02f4c0SEric Whitney 	}
16790b02f4c0SEric Whitney 
16800b02f4c0SEric Whitney 	ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
16810b02f4c0SEric Whitney 
16820b02f4c0SEric Whitney errout:
16830b02f4c0SEric Whitney 	return ret;
16840b02f4c0SEric Whitney }
16850b02f4c0SEric Whitney 
16860b02f4c0SEric Whitney /*
16875356f261SAditya Kali  * This function is grabs code from the very beginning of
16885356f261SAditya Kali  * ext4_map_blocks, but assumes that the caller is from delayed write
16895356f261SAditya Kali  * time. This function looks up the requested blocks and sets the
16905356f261SAditya Kali  * buffer delay bit under the protection of i_data_sem.
16915356f261SAditya Kali  */
16925356f261SAditya Kali static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
16935356f261SAditya Kali 			      struct ext4_map_blocks *map,
16945356f261SAditya Kali 			      struct buffer_head *bh)
16955356f261SAditya Kali {
1696d100eef2SZheng Liu 	struct extent_status es;
16975356f261SAditya Kali 	int retval;
16985356f261SAditya Kali 	sector_t invalid_block = ~((sector_t) 0xffff);
1699921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1700921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
1701921f266bSDmitry Monakhov 
1702921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
1703921f266bSDmitry Monakhov #endif
17045356f261SAditya Kali 
17055356f261SAditya Kali 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
17065356f261SAditya Kali 		invalid_block = ~0;
17075356f261SAditya Kali 
17085356f261SAditya Kali 	map->m_flags = 0;
170970aa1554SRitesh Harjani 	ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
17105356f261SAditya Kali 		  (unsigned long) map->m_lblk);
1711d100eef2SZheng Liu 
1712d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
1713bb5835edSTheodore Ts'o 	if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1714d100eef2SZheng Liu 		if (ext4_es_is_hole(&es)) {
1715d100eef2SZheng Liu 			retval = 0;
1716c8b459f4SLukas Czerner 			down_read(&EXT4_I(inode)->i_data_sem);
1717d100eef2SZheng Liu 			goto add_delayed;
1718d100eef2SZheng Liu 		}
1719d100eef2SZheng Liu 
1720d100eef2SZheng Liu 		/*
1721d100eef2SZheng Liu 		 * Delayed extent could be allocated by fallocate.
1722d100eef2SZheng Liu 		 * So we need to check it.
1723d100eef2SZheng Liu 		 */
1724d100eef2SZheng Liu 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1725d100eef2SZheng Liu 			map_bh(bh, inode->i_sb, invalid_block);
1726d100eef2SZheng Liu 			set_buffer_new(bh);
1727d100eef2SZheng Liu 			set_buffer_delay(bh);
1728d100eef2SZheng Liu 			return 0;
1729d100eef2SZheng Liu 		}
1730d100eef2SZheng Liu 
1731d100eef2SZheng Liu 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1732d100eef2SZheng Liu 		retval = es.es_len - (iblock - es.es_lblk);
1733d100eef2SZheng Liu 		if (retval > map->m_len)
1734d100eef2SZheng Liu 			retval = map->m_len;
1735d100eef2SZheng Liu 		map->m_len = retval;
1736d100eef2SZheng Liu 		if (ext4_es_is_written(&es))
1737d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_MAPPED;
1738d100eef2SZheng Liu 		else if (ext4_es_is_unwritten(&es))
1739d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1740d100eef2SZheng Liu 		else
17411e83bc81SArnd Bergmann 			BUG();
1742d100eef2SZheng Liu 
1743921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1744921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1745921f266bSDmitry Monakhov #endif
1746d100eef2SZheng Liu 		return retval;
1747d100eef2SZheng Liu 	}
1748d100eef2SZheng Liu 
17495356f261SAditya Kali 	/*
17505356f261SAditya Kali 	 * Try to see if we can get the block without requesting a new
17515356f261SAditya Kali 	 * file system block.
17525356f261SAditya Kali 	 */
1753c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
1754cbd7584eSJan Kara 	if (ext4_has_inline_data(inode))
17559c3569b5STao Ma 		retval = 0;
1756cbd7584eSJan Kara 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
17572f8e0a7cSZheng Liu 		retval = ext4_ext_map_blocks(NULL, inode, map, 0);
17585356f261SAditya Kali 	else
17592f8e0a7cSZheng Liu 		retval = ext4_ind_map_blocks(NULL, inode, map, 0);
17605356f261SAditya Kali 
1761d100eef2SZheng Liu add_delayed:
17625356f261SAditya Kali 	if (retval == 0) {
1763f7fec032SZheng Liu 		int ret;
1764ad431025SEric Whitney 
17655356f261SAditya Kali 		/*
17665356f261SAditya Kali 		 * XXX: __block_prepare_write() unmaps passed block,
17675356f261SAditya Kali 		 * is it OK?
17685356f261SAditya Kali 		 */
17695356f261SAditya Kali 
17700b02f4c0SEric Whitney 		ret = ext4_insert_delayed_block(inode, map->m_lblk);
17710b02f4c0SEric Whitney 		if (ret != 0) {
1772f7fec032SZheng Liu 			retval = ret;
177351865fdaSZheng Liu 			goto out_unlock;
1774f7fec032SZheng Liu 		}
177551865fdaSZheng Liu 
17765356f261SAditya Kali 		map_bh(bh, inode->i_sb, invalid_block);
17775356f261SAditya Kali 		set_buffer_new(bh);
17785356f261SAditya Kali 		set_buffer_delay(bh);
1779f7fec032SZheng Liu 	} else if (retval > 0) {
1780f7fec032SZheng Liu 		int ret;
17813be78c73STheodore Ts'o 		unsigned int status;
1782f7fec032SZheng Liu 
178344fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
178444fb851dSZheng Liu 			ext4_warning(inode->i_sb,
178544fb851dSZheng Liu 				     "ES len assertion failed for inode "
178644fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
178744fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
178844fb851dSZheng Liu 			WARN_ON(1);
1789921f266bSDmitry Monakhov 		}
1790921f266bSDmitry Monakhov 
1791f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1792f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1793f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1794f7fec032SZheng Liu 					    map->m_pblk, status);
1795f7fec032SZheng Liu 		if (ret != 0)
1796f7fec032SZheng Liu 			retval = ret;
17975356f261SAditya Kali 	}
17985356f261SAditya Kali 
17995356f261SAditya Kali out_unlock:
18005356f261SAditya Kali 	up_read((&EXT4_I(inode)->i_data_sem));
18015356f261SAditya Kali 
18025356f261SAditya Kali 	return retval;
18035356f261SAditya Kali }
18045356f261SAditya Kali 
18055356f261SAditya Kali /*
1806d91bd2c1SSeunghun Lee  * This is a special get_block_t callback which is used by
1807b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
1808b920c755STheodore Ts'o  * reserve space for a single block.
180929fa89d0SAneesh Kumar K.V  *
181029fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
181129fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
181229fa89d0SAneesh Kumar K.V  *
181329fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
181429fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
181529fa89d0SAneesh Kumar K.V  * initialized properly.
181664769240SAlex Tomas  */
18179c3569b5STao Ma int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
18182ed88685STheodore Ts'o 			   struct buffer_head *bh, int create)
181964769240SAlex Tomas {
18202ed88685STheodore Ts'o 	struct ext4_map_blocks map;
182164769240SAlex Tomas 	int ret = 0;
182264769240SAlex Tomas 
182364769240SAlex Tomas 	BUG_ON(create == 0);
18242ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
18252ed88685STheodore Ts'o 
18262ed88685STheodore Ts'o 	map.m_lblk = iblock;
18272ed88685STheodore Ts'o 	map.m_len = 1;
182864769240SAlex Tomas 
182964769240SAlex Tomas 	/*
183064769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
183164769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
183264769240SAlex Tomas 	 * the same as allocated blocks.
183364769240SAlex Tomas 	 */
18345356f261SAditya Kali 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
18355356f261SAditya Kali 	if (ret <= 0)
18362ed88685STheodore Ts'o 		return ret;
183764769240SAlex Tomas 
18382ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
1839ed8ad838SJan Kara 	ext4_update_bh_state(bh, map.m_flags);
18402ed88685STheodore Ts'o 
18412ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
18422ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
18432ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
18442ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
18452ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
18462ed88685STheodore Ts'o 		 * for partial write.
18472ed88685STheodore Ts'o 		 */
18482ed88685STheodore Ts'o 		set_buffer_new(bh);
1849c8205636STheodore Ts'o 		set_buffer_mapped(bh);
18502ed88685STheodore Ts'o 	}
18512ed88685STheodore Ts'o 	return 0;
185264769240SAlex Tomas }
185361628a3fSMingming Cao 
185462e086beSAneesh Kumar K.V static int bget_one(handle_t *handle, struct buffer_head *bh)
185562e086beSAneesh Kumar K.V {
185662e086beSAneesh Kumar K.V 	get_bh(bh);
185762e086beSAneesh Kumar K.V 	return 0;
185862e086beSAneesh Kumar K.V }
185962e086beSAneesh Kumar K.V 
186062e086beSAneesh Kumar K.V static int bput_one(handle_t *handle, struct buffer_head *bh)
186162e086beSAneesh Kumar K.V {
186262e086beSAneesh Kumar K.V 	put_bh(bh);
186362e086beSAneesh Kumar K.V 	return 0;
186462e086beSAneesh Kumar K.V }
186562e086beSAneesh Kumar K.V 
186662e086beSAneesh Kumar K.V static int __ext4_journalled_writepage(struct page *page,
186762e086beSAneesh Kumar K.V 				       unsigned int len)
186862e086beSAneesh Kumar K.V {
186962e086beSAneesh Kumar K.V 	struct address_space *mapping = page->mapping;
187062e086beSAneesh Kumar K.V 	struct inode *inode = mapping->host;
18713fdcfb66STao Ma 	struct buffer_head *page_bufs = NULL;
187262e086beSAneesh Kumar K.V 	handle_t *handle = NULL;
18733fdcfb66STao Ma 	int ret = 0, err = 0;
18743fdcfb66STao Ma 	int inline_data = ext4_has_inline_data(inode);
18753fdcfb66STao Ma 	struct buffer_head *inode_bh = NULL;
187662e086beSAneesh Kumar K.V 
1877cb20d518STheodore Ts'o 	ClearPageChecked(page);
18783fdcfb66STao Ma 
18793fdcfb66STao Ma 	if (inline_data) {
18803fdcfb66STao Ma 		BUG_ON(page->index != 0);
18813fdcfb66STao Ma 		BUG_ON(len > ext4_get_max_inline_size(inode));
18823fdcfb66STao Ma 		inode_bh = ext4_journalled_write_inline_data(inode, len, page);
18833fdcfb66STao Ma 		if (inode_bh == NULL)
18843fdcfb66STao Ma 			goto out;
18853fdcfb66STao Ma 	} else {
188662e086beSAneesh Kumar K.V 		page_bufs = page_buffers(page);
18873fdcfb66STao Ma 		if (!page_bufs) {
18883fdcfb66STao Ma 			BUG();
18893fdcfb66STao Ma 			goto out;
18903fdcfb66STao Ma 		}
18913fdcfb66STao Ma 		ext4_walk_page_buffers(handle, page_bufs, 0, len,
18923fdcfb66STao Ma 				       NULL, bget_one);
18933fdcfb66STao Ma 	}
1894bdf96838STheodore Ts'o 	/*
1895bdf96838STheodore Ts'o 	 * We need to release the page lock before we start the
1896bdf96838STheodore Ts'o 	 * journal, so grab a reference so the page won't disappear
1897bdf96838STheodore Ts'o 	 * out from under us.
1898bdf96838STheodore Ts'o 	 */
1899bdf96838STheodore Ts'o 	get_page(page);
190062e086beSAneesh Kumar K.V 	unlock_page(page);
190162e086beSAneesh Kumar K.V 
19029924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
19039924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
190462e086beSAneesh Kumar K.V 	if (IS_ERR(handle)) {
190562e086beSAneesh Kumar K.V 		ret = PTR_ERR(handle);
1906bdf96838STheodore Ts'o 		put_page(page);
1907bdf96838STheodore Ts'o 		goto out_no_pagelock;
1908bdf96838STheodore Ts'o 	}
1909bdf96838STheodore Ts'o 	BUG_ON(!ext4_handle_valid(handle));
1910bdf96838STheodore Ts'o 
1911bdf96838STheodore Ts'o 	lock_page(page);
1912bdf96838STheodore Ts'o 	put_page(page);
1913bdf96838STheodore Ts'o 	if (page->mapping != mapping) {
1914bdf96838STheodore Ts'o 		/* The page got truncated from under us */
1915bdf96838STheodore Ts'o 		ext4_journal_stop(handle);
1916bdf96838STheodore Ts'o 		ret = 0;
191762e086beSAneesh Kumar K.V 		goto out;
191862e086beSAneesh Kumar K.V 	}
191962e086beSAneesh Kumar K.V 
19203fdcfb66STao Ma 	if (inline_data) {
1921362eca70STheodore Ts'o 		ret = ext4_mark_inode_dirty(handle, inode);
19223fdcfb66STao Ma 	} else {
1923f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
192462e086beSAneesh Kumar K.V 					     do_journal_get_write_access);
192562e086beSAneesh Kumar K.V 
1926f19d5870STao Ma 		err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
192762e086beSAneesh Kumar K.V 					     write_end_fn);
19283fdcfb66STao Ma 	}
192962e086beSAneesh Kumar K.V 	if (ret == 0)
193062e086beSAneesh Kumar K.V 		ret = err;
1931b5b18160SJan Kara 	err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
1932afb585a9SMauricio Faria de Oliveira 	if (ret == 0)
1933afb585a9SMauricio Faria de Oliveira 		ret = err;
19342d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
193562e086beSAneesh Kumar K.V 	err = ext4_journal_stop(handle);
193662e086beSAneesh Kumar K.V 	if (!ret)
193762e086beSAneesh Kumar K.V 		ret = err;
193862e086beSAneesh Kumar K.V 
193919f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
194062e086beSAneesh Kumar K.V out:
1941bdf96838STheodore Ts'o 	unlock_page(page);
1942bdf96838STheodore Ts'o out_no_pagelock:
1943c915fb80SZhaolong Zhang 	if (!inline_data && page_bufs)
1944c915fb80SZhaolong Zhang 		ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1945c915fb80SZhaolong Zhang 				       NULL, bput_one);
19463fdcfb66STao Ma 	brelse(inode_bh);
194762e086beSAneesh Kumar K.V 	return ret;
194862e086beSAneesh Kumar K.V }
194962e086beSAneesh Kumar K.V 
195061628a3fSMingming Cao /*
195143ce1d23SAneesh Kumar K.V  * Note that we don't need to start a transaction unless we're journaling data
195243ce1d23SAneesh Kumar K.V  * because we should have holes filled from ext4_page_mkwrite(). We even don't
195343ce1d23SAneesh Kumar K.V  * need to file the inode to the transaction's list in ordered mode because if
195443ce1d23SAneesh Kumar K.V  * we are writing back data added by write(), the inode is already there and if
195543ce1d23SAneesh Kumar K.V  * we are writing back data modified via mmap(), no one guarantees in which
195643ce1d23SAneesh Kumar K.V  * transaction the data will hit the disk. In case we are journaling data, we
195743ce1d23SAneesh Kumar K.V  * cannot start transaction directly because transaction start ranks above page
195843ce1d23SAneesh Kumar K.V  * lock so we have to do some magic.
195943ce1d23SAneesh Kumar K.V  *
1960b920c755STheodore Ts'o  * This function can get called via...
196120970ba6STheodore Ts'o  *   - ext4_writepages after taking page lock (have journal handle)
1962b920c755STheodore Ts'o  *   - journal_submit_inode_data_buffers (no journal handle)
1963f6463b0dSArtem Bityutskiy  *   - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1964b920c755STheodore Ts'o  *   - grab_page_cache when doing write_begin (have journal handle)
196543ce1d23SAneesh Kumar K.V  *
196643ce1d23SAneesh Kumar K.V  * We don't do any block allocation in this function. If we have page with
196743ce1d23SAneesh Kumar K.V  * multiple blocks we need to write those buffer_heads that are mapped. This
196843ce1d23SAneesh Kumar K.V  * is important for mmaped based write. So if we do with blocksize 1K
196943ce1d23SAneesh Kumar K.V  * truncate(f, 1024);
197043ce1d23SAneesh Kumar K.V  * a = mmap(f, 0, 4096);
197143ce1d23SAneesh Kumar K.V  * a[0] = 'a';
197243ce1d23SAneesh Kumar K.V  * truncate(f, 4096);
197343ce1d23SAneesh Kumar K.V  * we have in the page first buffer_head mapped via page_mkwrite call back
197490802ed9SPaul Bolle  * but other buffer_heads would be unmapped but dirty (dirty done via the
197543ce1d23SAneesh Kumar K.V  * do_wp_page). So writepage should write the first block. If we modify
197643ce1d23SAneesh Kumar K.V  * the mmap area beyond 1024 we will again get a page_fault and the
197743ce1d23SAneesh Kumar K.V  * page_mkwrite callback will do the block allocation and mark the
197843ce1d23SAneesh Kumar K.V  * buffer_heads mapped.
197943ce1d23SAneesh Kumar K.V  *
198043ce1d23SAneesh Kumar K.V  * We redirty the page if we have any buffer_heads that is either delay or
198143ce1d23SAneesh Kumar K.V  * unwritten in the page.
198243ce1d23SAneesh Kumar K.V  *
198343ce1d23SAneesh Kumar K.V  * We can get recursively called as show below.
198443ce1d23SAneesh Kumar K.V  *
198543ce1d23SAneesh Kumar K.V  *	ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
198643ce1d23SAneesh Kumar K.V  *		ext4_writepage()
198743ce1d23SAneesh Kumar K.V  *
198843ce1d23SAneesh Kumar K.V  * But since we don't do any block allocation we should not deadlock.
198943ce1d23SAneesh Kumar K.V  * Page also have the dirty flag cleared so we don't get recurive page_lock.
199061628a3fSMingming Cao  */
199143ce1d23SAneesh Kumar K.V static int ext4_writepage(struct page *page,
199264769240SAlex Tomas 			  struct writeback_control *wbc)
199364769240SAlex Tomas {
1994f8bec370SJan Kara 	int ret = 0;
199561628a3fSMingming Cao 	loff_t size;
1996498e5f24STheodore Ts'o 	unsigned int len;
1997744692dcSJiaying Zhang 	struct buffer_head *page_bufs = NULL;
199861628a3fSMingming Cao 	struct inode *inode = page->mapping->host;
199936ade451SJan Kara 	struct ext4_io_submit io_submit;
20001c8349a1SNamjae Jeon 	bool keep_towrite = false;
200164769240SAlex Tomas 
20020db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
2003c2a559bcSyangerkun 		inode->i_mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
20040db1ff22STheodore Ts'o 		unlock_page(page);
20050db1ff22STheodore Ts'o 		return -EIO;
20060db1ff22STheodore Ts'o 	}
20070db1ff22STheodore Ts'o 
2008a9c667f8SLukas Czerner 	trace_ext4_writepage(page);
200961628a3fSMingming Cao 	size = i_size_read(inode);
2010c93d8f88SEric Biggers 	if (page->index == size >> PAGE_SHIFT &&
2011c93d8f88SEric Biggers 	    !ext4_verity_in_progress(inode))
201209cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
201361628a3fSMingming Cao 	else
201409cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
201561628a3fSMingming Cao 
2016f0e6c985SAneesh Kumar K.V 	page_bufs = page_buffers(page);
201764769240SAlex Tomas 	/*
2018fe386132SJan Kara 	 * We cannot do block allocation or other extent handling in this
2019fe386132SJan Kara 	 * function. If there are buffers needing that, we have to redirty
2020fe386132SJan Kara 	 * the page. But we may reach here when we do a journal commit via
2021fe386132SJan Kara 	 * journal_submit_inode_data_buffers() and in that case we must write
2022fe386132SJan Kara 	 * allocated buffers to achieve data=ordered mode guarantees.
2023cccd147aSTheodore Ts'o 	 *
2024cccd147aSTheodore Ts'o 	 * Also, if there is only one buffer per page (the fs block
2025cccd147aSTheodore Ts'o 	 * size == the page size), if one buffer needs block
2026cccd147aSTheodore Ts'o 	 * allocation or needs to modify the extent tree to clear the
2027cccd147aSTheodore Ts'o 	 * unwritten flag, we know that the page can't be written at
2028cccd147aSTheodore Ts'o 	 * all, so we might as well refuse the write immediately.
2029cccd147aSTheodore Ts'o 	 * Unfortunately if the block size != page size, we can't as
2030cccd147aSTheodore Ts'o 	 * easily detect this case using ext4_walk_page_buffers(), but
2031cccd147aSTheodore Ts'o 	 * for the extremely common case, this is an optimization that
2032cccd147aSTheodore Ts'o 	 * skips a useless round trip through ext4_bio_write_page().
203364769240SAlex Tomas 	 */
2034f19d5870STao Ma 	if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2035c364b22cSAneesh Kumar K.V 				   ext4_bh_delay_or_unwritten)) {
203661628a3fSMingming Cao 		redirty_page_for_writepage(wbc, page);
2037cccd147aSTheodore Ts'o 		if ((current->flags & PF_MEMALLOC) ||
203809cbfeafSKirill A. Shutemov 		    (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2039fe386132SJan Kara 			/*
2040fe386132SJan Kara 			 * For memory cleaning there's no point in writing only
2041fe386132SJan Kara 			 * some buffers. So just bail out. Warn if we came here
2042fe386132SJan Kara 			 * from direct reclaim.
2043fe386132SJan Kara 			 */
2044fe386132SJan Kara 			WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2045fe386132SJan Kara 							== PF_MEMALLOC);
204661628a3fSMingming Cao 			unlock_page(page);
204761628a3fSMingming Cao 			return 0;
204861628a3fSMingming Cao 		}
20491c8349a1SNamjae Jeon 		keep_towrite = true;
2050f0e6c985SAneesh Kumar K.V 	}
205164769240SAlex Tomas 
2052cb20d518STheodore Ts'o 	if (PageChecked(page) && ext4_should_journal_data(inode))
205343ce1d23SAneesh Kumar K.V 		/*
205443ce1d23SAneesh Kumar K.V 		 * It's mmapped pagecache.  Add buffers and journal it.  There
205543ce1d23SAneesh Kumar K.V 		 * doesn't seem much point in redirtying the page here.
205643ce1d23SAneesh Kumar K.V 		 */
20573f0ca309SWu Fengguang 		return __ext4_journalled_writepage(page, len);
205843ce1d23SAneesh Kumar K.V 
205997a851edSJan Kara 	ext4_io_submit_init(&io_submit, wbc);
206097a851edSJan Kara 	io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
206197a851edSJan Kara 	if (!io_submit.io_end) {
206297a851edSJan Kara 		redirty_page_for_writepage(wbc, page);
206397a851edSJan Kara 		unlock_page(page);
206497a851edSJan Kara 		return -ENOMEM;
206597a851edSJan Kara 	}
2066be993933SLei Chen 	ret = ext4_bio_write_page(&io_submit, page, len, keep_towrite);
206736ade451SJan Kara 	ext4_io_submit(&io_submit);
206897a851edSJan Kara 	/* Drop io_end reference we got from init */
206997a851edSJan Kara 	ext4_put_io_end_defer(io_submit.io_end);
207064769240SAlex Tomas 	return ret;
207164769240SAlex Tomas }
207264769240SAlex Tomas 
20735f1132b2SJan Kara static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
20745f1132b2SJan Kara {
20755f1132b2SJan Kara 	int len;
2076a056bdaaSJan Kara 	loff_t size;
20775f1132b2SJan Kara 	int err;
20785f1132b2SJan Kara 
20795f1132b2SJan Kara 	BUG_ON(page->index != mpd->first_page);
2080a056bdaaSJan Kara 	clear_page_dirty_for_io(page);
2081a056bdaaSJan Kara 	/*
2082a056bdaaSJan Kara 	 * We have to be very careful here!  Nothing protects writeback path
2083a056bdaaSJan Kara 	 * against i_size changes and the page can be writeably mapped into
2084a056bdaaSJan Kara 	 * page tables. So an application can be growing i_size and writing
2085a056bdaaSJan Kara 	 * data through mmap while writeback runs. clear_page_dirty_for_io()
2086a056bdaaSJan Kara 	 * write-protects our page in page tables and the page cannot get
2087a056bdaaSJan Kara 	 * written to again until we release page lock. So only after
2088a056bdaaSJan Kara 	 * clear_page_dirty_for_io() we are safe to sample i_size for
2089a056bdaaSJan Kara 	 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2090a056bdaaSJan Kara 	 * on the barrier provided by TestClearPageDirty in
2091a056bdaaSJan Kara 	 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2092a056bdaaSJan Kara 	 * after page tables are updated.
2093a056bdaaSJan Kara 	 */
2094a056bdaaSJan Kara 	size = i_size_read(mpd->inode);
2095c93d8f88SEric Biggers 	if (page->index == size >> PAGE_SHIFT &&
2096c93d8f88SEric Biggers 	    !ext4_verity_in_progress(mpd->inode))
209709cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
20985f1132b2SJan Kara 	else
209909cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
2100be993933SLei Chen 	err = ext4_bio_write_page(&mpd->io_submit, page, len, false);
21015f1132b2SJan Kara 	if (!err)
21025f1132b2SJan Kara 		mpd->wbc->nr_to_write--;
21035f1132b2SJan Kara 	mpd->first_page++;
21045f1132b2SJan Kara 
21055f1132b2SJan Kara 	return err;
21065f1132b2SJan Kara }
21075f1132b2SJan Kara 
21086db07461SRitesh Harjani #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
21094e7ea81dSJan Kara 
211061628a3fSMingming Cao /*
2111fffb2739SJan Kara  * mballoc gives us at most this number of blocks...
2112fffb2739SJan Kara  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2113fffb2739SJan Kara  * The rest of mballoc seems to handle chunks up to full group size.
211461628a3fSMingming Cao  */
2115fffb2739SJan Kara #define MAX_WRITEPAGES_EXTENT_LEN 2048
2116525f4ed8SMingming Cao 
2117525f4ed8SMingming Cao /*
21184e7ea81dSJan Kara  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
21194e7ea81dSJan Kara  *
21204e7ea81dSJan Kara  * @mpd - extent of blocks
21214e7ea81dSJan Kara  * @lblk - logical number of the block in the file
212209930042SJan Kara  * @bh - buffer head we want to add to the extent
21234e7ea81dSJan Kara  *
212409930042SJan Kara  * The function is used to collect contig. blocks in the same state. If the
212509930042SJan Kara  * buffer doesn't require mapping for writeback and we haven't started the
212609930042SJan Kara  * extent of buffers to map yet, the function returns 'true' immediately - the
212709930042SJan Kara  * caller can write the buffer right away. Otherwise the function returns true
212809930042SJan Kara  * if the block has been added to the extent, false if the block couldn't be
212909930042SJan Kara  * added.
21304e7ea81dSJan Kara  */
213109930042SJan Kara static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
213209930042SJan Kara 				   struct buffer_head *bh)
21334e7ea81dSJan Kara {
21344e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
21354e7ea81dSJan Kara 
213609930042SJan Kara 	/* Buffer that doesn't need mapping for writeback? */
213709930042SJan Kara 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
213809930042SJan Kara 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
213909930042SJan Kara 		/* So far no extent to map => we write the buffer right away */
214009930042SJan Kara 		if (map->m_len == 0)
214109930042SJan Kara 			return true;
214209930042SJan Kara 		return false;
214309930042SJan Kara 	}
21444e7ea81dSJan Kara 
21454e7ea81dSJan Kara 	/* First block in the extent? */
21464e7ea81dSJan Kara 	if (map->m_len == 0) {
2147dddbd6acSJan Kara 		/* We cannot map unless handle is started... */
2148dddbd6acSJan Kara 		if (!mpd->do_map)
2149dddbd6acSJan Kara 			return false;
21504e7ea81dSJan Kara 		map->m_lblk = lblk;
21514e7ea81dSJan Kara 		map->m_len = 1;
215209930042SJan Kara 		map->m_flags = bh->b_state & BH_FLAGS;
215309930042SJan Kara 		return true;
21544e7ea81dSJan Kara 	}
21554e7ea81dSJan Kara 
215609930042SJan Kara 	/* Don't go larger than mballoc is willing to allocate */
215709930042SJan Kara 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
215809930042SJan Kara 		return false;
215909930042SJan Kara 
21604e7ea81dSJan Kara 	/* Can we merge the block to our big extent? */
21614e7ea81dSJan Kara 	if (lblk == map->m_lblk + map->m_len &&
216209930042SJan Kara 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
21634e7ea81dSJan Kara 		map->m_len++;
216409930042SJan Kara 		return true;
21654e7ea81dSJan Kara 	}
216609930042SJan Kara 	return false;
21674e7ea81dSJan Kara }
21684e7ea81dSJan Kara 
21695f1132b2SJan Kara /*
21705f1132b2SJan Kara  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
21715f1132b2SJan Kara  *
21725f1132b2SJan Kara  * @mpd - extent of blocks for mapping
21735f1132b2SJan Kara  * @head - the first buffer in the page
21745f1132b2SJan Kara  * @bh - buffer we should start processing from
21755f1132b2SJan Kara  * @lblk - logical number of the block in the file corresponding to @bh
21765f1132b2SJan Kara  *
21775f1132b2SJan Kara  * Walk through page buffers from @bh upto @head (exclusive) and either submit
21785f1132b2SJan Kara  * the page for IO if all buffers in this page were mapped and there's no
21795f1132b2SJan Kara  * accumulated extent of buffers to map or add buffers in the page to the
21805f1132b2SJan Kara  * extent of buffers to map. The function returns 1 if the caller can continue
21815f1132b2SJan Kara  * by processing the next page, 0 if it should stop adding buffers to the
21825f1132b2SJan Kara  * extent to map because we cannot extend it anymore. It can also return value
21835f1132b2SJan Kara  * < 0 in case of error during IO submission.
21845f1132b2SJan Kara  */
21855f1132b2SJan Kara static int mpage_process_page_bufs(struct mpage_da_data *mpd,
21864e7ea81dSJan Kara 				   struct buffer_head *head,
21874e7ea81dSJan Kara 				   struct buffer_head *bh,
21884e7ea81dSJan Kara 				   ext4_lblk_t lblk)
21894e7ea81dSJan Kara {
21904e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
21915f1132b2SJan Kara 	int err;
219293407472SFabian Frederick 	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
21934e7ea81dSJan Kara 							>> inode->i_blkbits;
21944e7ea81dSJan Kara 
2195c93d8f88SEric Biggers 	if (ext4_verity_in_progress(inode))
2196c93d8f88SEric Biggers 		blocks = EXT_MAX_BLOCKS;
2197c93d8f88SEric Biggers 
21984e7ea81dSJan Kara 	do {
21994e7ea81dSJan Kara 		BUG_ON(buffer_locked(bh));
22004e7ea81dSJan Kara 
220109930042SJan Kara 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
22024e7ea81dSJan Kara 			/* Found extent to map? */
22034e7ea81dSJan Kara 			if (mpd->map.m_len)
22045f1132b2SJan Kara 				return 0;
2205dddbd6acSJan Kara 			/* Buffer needs mapping and handle is not started? */
2206dddbd6acSJan Kara 			if (!mpd->do_map)
2207dddbd6acSJan Kara 				return 0;
220809930042SJan Kara 			/* Everything mapped so far and we hit EOF */
22095f1132b2SJan Kara 			break;
22104e7ea81dSJan Kara 		}
22114e7ea81dSJan Kara 	} while (lblk++, (bh = bh->b_this_page) != head);
22125f1132b2SJan Kara 	/* So far everything mapped? Submit the page for IO. */
22135f1132b2SJan Kara 	if (mpd->map.m_len == 0) {
22145f1132b2SJan Kara 		err = mpage_submit_page(mpd, head->b_page);
22155f1132b2SJan Kara 		if (err < 0)
22164e7ea81dSJan Kara 			return err;
22174e7ea81dSJan Kara 	}
22186b8ed620SJan Kara 	if (lblk >= blocks) {
22196b8ed620SJan Kara 		mpd->scanned_until_end = 1;
22206b8ed620SJan Kara 		return 0;
22216b8ed620SJan Kara 	}
22226b8ed620SJan Kara 	return 1;
22235f1132b2SJan Kara }
22244e7ea81dSJan Kara 
22254e7ea81dSJan Kara /*
22262943fdbcSRitesh Harjani  * mpage_process_page - update page buffers corresponding to changed extent and
22272943fdbcSRitesh Harjani  *		       may submit fully mapped page for IO
22282943fdbcSRitesh Harjani  *
22292943fdbcSRitesh Harjani  * @mpd		- description of extent to map, on return next extent to map
22302943fdbcSRitesh Harjani  * @m_lblk	- logical block mapping.
22312943fdbcSRitesh Harjani  * @m_pblk	- corresponding physical mapping.
22322943fdbcSRitesh Harjani  * @map_bh	- determines on return whether this page requires any further
22332943fdbcSRitesh Harjani  *		  mapping or not.
22342943fdbcSRitesh Harjani  * Scan given page buffers corresponding to changed extent and update buffer
22352943fdbcSRitesh Harjani  * state according to new extent state.
22362943fdbcSRitesh Harjani  * We map delalloc buffers to their physical location, clear unwritten bits.
22372943fdbcSRitesh Harjani  * If the given page is not fully mapped, we update @map to the next extent in
22382943fdbcSRitesh Harjani  * the given page that needs mapping & return @map_bh as true.
22392943fdbcSRitesh Harjani  */
22402943fdbcSRitesh Harjani static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
22412943fdbcSRitesh Harjani 			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
22422943fdbcSRitesh Harjani 			      bool *map_bh)
22432943fdbcSRitesh Harjani {
22442943fdbcSRitesh Harjani 	struct buffer_head *head, *bh;
22452943fdbcSRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
22462943fdbcSRitesh Harjani 	ext4_lblk_t lblk = *m_lblk;
22472943fdbcSRitesh Harjani 	ext4_fsblk_t pblock = *m_pblk;
22482943fdbcSRitesh Harjani 	int err = 0;
2249c8cc8816SRitesh Harjani 	int blkbits = mpd->inode->i_blkbits;
2250c8cc8816SRitesh Harjani 	ssize_t io_end_size = 0;
2251c8cc8816SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
22522943fdbcSRitesh Harjani 
22532943fdbcSRitesh Harjani 	bh = head = page_buffers(page);
22542943fdbcSRitesh Harjani 	do {
22552943fdbcSRitesh Harjani 		if (lblk < mpd->map.m_lblk)
22562943fdbcSRitesh Harjani 			continue;
22572943fdbcSRitesh Harjani 		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
22582943fdbcSRitesh Harjani 			/*
22592943fdbcSRitesh Harjani 			 * Buffer after end of mapped extent.
22602943fdbcSRitesh Harjani 			 * Find next buffer in the page to map.
22612943fdbcSRitesh Harjani 			 */
22622943fdbcSRitesh Harjani 			mpd->map.m_len = 0;
22632943fdbcSRitesh Harjani 			mpd->map.m_flags = 0;
2264c8cc8816SRitesh Harjani 			io_end_vec->size += io_end_size;
2265c8cc8816SRitesh Harjani 			io_end_size = 0;
22662943fdbcSRitesh Harjani 
22672943fdbcSRitesh Harjani 			err = mpage_process_page_bufs(mpd, head, bh, lblk);
22682943fdbcSRitesh Harjani 			if (err > 0)
22692943fdbcSRitesh Harjani 				err = 0;
2270c8cc8816SRitesh Harjani 			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2271c8cc8816SRitesh Harjani 				io_end_vec = ext4_alloc_io_end_vec(io_end);
22724d06bfb9SRitesh Harjani 				if (IS_ERR(io_end_vec)) {
22734d06bfb9SRitesh Harjani 					err = PTR_ERR(io_end_vec);
22744d06bfb9SRitesh Harjani 					goto out;
22754d06bfb9SRitesh Harjani 				}
2276d1e18b88SRitesh Harjani 				io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2277c8cc8816SRitesh Harjani 			}
22782943fdbcSRitesh Harjani 			*map_bh = true;
22792943fdbcSRitesh Harjani 			goto out;
22802943fdbcSRitesh Harjani 		}
22812943fdbcSRitesh Harjani 		if (buffer_delay(bh)) {
22822943fdbcSRitesh Harjani 			clear_buffer_delay(bh);
22832943fdbcSRitesh Harjani 			bh->b_blocknr = pblock++;
22842943fdbcSRitesh Harjani 		}
22852943fdbcSRitesh Harjani 		clear_buffer_unwritten(bh);
2286c8cc8816SRitesh Harjani 		io_end_size += (1 << blkbits);
22872943fdbcSRitesh Harjani 	} while (lblk++, (bh = bh->b_this_page) != head);
2288c8cc8816SRitesh Harjani 
2289c8cc8816SRitesh Harjani 	io_end_vec->size += io_end_size;
2290c8cc8816SRitesh Harjani 	io_end_size = 0;
22912943fdbcSRitesh Harjani 	*map_bh = false;
22922943fdbcSRitesh Harjani out:
22932943fdbcSRitesh Harjani 	*m_lblk = lblk;
22942943fdbcSRitesh Harjani 	*m_pblk = pblock;
22952943fdbcSRitesh Harjani 	return err;
22962943fdbcSRitesh Harjani }
22972943fdbcSRitesh Harjani 
22982943fdbcSRitesh Harjani /*
22994e7ea81dSJan Kara  * mpage_map_buffers - update buffers corresponding to changed extent and
23004e7ea81dSJan Kara  *		       submit fully mapped pages for IO
23014e7ea81dSJan Kara  *
23024e7ea81dSJan Kara  * @mpd - description of extent to map, on return next extent to map
23034e7ea81dSJan Kara  *
23044e7ea81dSJan Kara  * Scan buffers corresponding to changed extent (we expect corresponding pages
23054e7ea81dSJan Kara  * to be already locked) and update buffer state according to new extent state.
23064e7ea81dSJan Kara  * We map delalloc buffers to their physical location, clear unwritten bits,
2307556615dcSLukas Czerner  * and mark buffers as uninit when we perform writes to unwritten extents
23084e7ea81dSJan Kara  * and do extent conversion after IO is finished. If the last page is not fully
23094e7ea81dSJan Kara  * mapped, we update @map to the next extent in the last page that needs
23104e7ea81dSJan Kara  * mapping. Otherwise we submit the page for IO.
23114e7ea81dSJan Kara  */
23124e7ea81dSJan Kara static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
23134e7ea81dSJan Kara {
23144e7ea81dSJan Kara 	struct pagevec pvec;
23154e7ea81dSJan Kara 	int nr_pages, i;
23164e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
231709cbfeafSKirill A. Shutemov 	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
23184e7ea81dSJan Kara 	pgoff_t start, end;
23194e7ea81dSJan Kara 	ext4_lblk_t lblk;
23202943fdbcSRitesh Harjani 	ext4_fsblk_t pblock;
23214e7ea81dSJan Kara 	int err;
23222943fdbcSRitesh Harjani 	bool map_bh = false;
23234e7ea81dSJan Kara 
23244e7ea81dSJan Kara 	start = mpd->map.m_lblk >> bpp_bits;
23254e7ea81dSJan Kara 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
23264e7ea81dSJan Kara 	lblk = start << bpp_bits;
23274e7ea81dSJan Kara 	pblock = mpd->map.m_pblk;
23284e7ea81dSJan Kara 
232986679820SMel Gorman 	pagevec_init(&pvec);
23304e7ea81dSJan Kara 	while (start <= end) {
23312b85a617SJan Kara 		nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2332397162ffSJan Kara 						&start, end);
23334e7ea81dSJan Kara 		if (nr_pages == 0)
23344e7ea81dSJan Kara 			break;
23354e7ea81dSJan Kara 		for (i = 0; i < nr_pages; i++) {
23364e7ea81dSJan Kara 			struct page *page = pvec.pages[i];
23374e7ea81dSJan Kara 
23382943fdbcSRitesh Harjani 			err = mpage_process_page(mpd, page, &lblk, &pblock,
23392943fdbcSRitesh Harjani 						 &map_bh);
23404e7ea81dSJan Kara 			/*
23412943fdbcSRitesh Harjani 			 * If map_bh is true, means page may require further bh
23422943fdbcSRitesh Harjani 			 * mapping, or maybe the page was submitted for IO.
23432943fdbcSRitesh Harjani 			 * So we return to call further extent mapping.
23444e7ea81dSJan Kara 			 */
234539c0ae16SJason Yan 			if (err < 0 || map_bh)
23462943fdbcSRitesh Harjani 				goto out;
23474e7ea81dSJan Kara 			/* Page fully mapped - let IO run! */
23484e7ea81dSJan Kara 			err = mpage_submit_page(mpd, page);
23492943fdbcSRitesh Harjani 			if (err < 0)
23502943fdbcSRitesh Harjani 				goto out;
23514e7ea81dSJan Kara 		}
23524e7ea81dSJan Kara 		pagevec_release(&pvec);
23534e7ea81dSJan Kara 	}
23544e7ea81dSJan Kara 	/* Extent fully mapped and matches with page boundary. We are done. */
23554e7ea81dSJan Kara 	mpd->map.m_len = 0;
23564e7ea81dSJan Kara 	mpd->map.m_flags = 0;
23574e7ea81dSJan Kara 	return 0;
23582943fdbcSRitesh Harjani out:
23592943fdbcSRitesh Harjani 	pagevec_release(&pvec);
23602943fdbcSRitesh Harjani 	return err;
23614e7ea81dSJan Kara }
23624e7ea81dSJan Kara 
23634e7ea81dSJan Kara static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
23644e7ea81dSJan Kara {
23654e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
23664e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
23674e7ea81dSJan Kara 	int get_blocks_flags;
2368090f32eeSLukas Czerner 	int err, dioread_nolock;
23694e7ea81dSJan Kara 
23704e7ea81dSJan Kara 	trace_ext4_da_write_pages_extent(inode, map);
23714e7ea81dSJan Kara 	/*
23724e7ea81dSJan Kara 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2373556615dcSLukas Czerner 	 * to convert an unwritten extent to be initialized (in the case
23744e7ea81dSJan Kara 	 * where we have written into one or more preallocated blocks).  It is
23754e7ea81dSJan Kara 	 * possible that we're going to need more metadata blocks than
23764e7ea81dSJan Kara 	 * previously reserved. However we must not fail because we're in
23774e7ea81dSJan Kara 	 * writeback and there is nothing we can do about it so it might result
23784e7ea81dSJan Kara 	 * in data loss.  So use reserved blocks to allocate metadata if
23794e7ea81dSJan Kara 	 * possible.
23804e7ea81dSJan Kara 	 *
2381754cfed6STheodore Ts'o 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2382754cfed6STheodore Ts'o 	 * the blocks in question are delalloc blocks.  This indicates
2383754cfed6STheodore Ts'o 	 * that the blocks and quotas has already been checked when
2384754cfed6STheodore Ts'o 	 * the data was copied into the page cache.
23854e7ea81dSJan Kara 	 */
23864e7ea81dSJan Kara 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2387ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2388ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_IO_SUBMIT;
2389090f32eeSLukas Czerner 	dioread_nolock = ext4_should_dioread_nolock(inode);
2390090f32eeSLukas Czerner 	if (dioread_nolock)
23914e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
23926db07461SRitesh Harjani 	if (map->m_flags & BIT(BH_Delay))
23934e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
23944e7ea81dSJan Kara 
23954e7ea81dSJan Kara 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
23964e7ea81dSJan Kara 	if (err < 0)
23974e7ea81dSJan Kara 		return err;
2398090f32eeSLukas Czerner 	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
23996b523df4SJan Kara 		if (!mpd->io_submit.io_end->handle &&
24006b523df4SJan Kara 		    ext4_handle_valid(handle)) {
24016b523df4SJan Kara 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
24026b523df4SJan Kara 			handle->h_rsv_handle = NULL;
24036b523df4SJan Kara 		}
24043613d228SJan Kara 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
24056b523df4SJan Kara 	}
24064e7ea81dSJan Kara 
24074e7ea81dSJan Kara 	BUG_ON(map->m_len == 0);
24084e7ea81dSJan Kara 	return 0;
24094e7ea81dSJan Kara }
24104e7ea81dSJan Kara 
24114e7ea81dSJan Kara /*
24124e7ea81dSJan Kara  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
24134e7ea81dSJan Kara  *				 mpd->len and submit pages underlying it for IO
24144e7ea81dSJan Kara  *
24154e7ea81dSJan Kara  * @handle - handle for journal operations
24164e7ea81dSJan Kara  * @mpd - extent to map
24177534e854SJan Kara  * @give_up_on_write - we set this to true iff there is a fatal error and there
24187534e854SJan Kara  *                     is no hope of writing the data. The caller should discard
24197534e854SJan Kara  *                     dirty pages to avoid infinite loops.
24204e7ea81dSJan Kara  *
24214e7ea81dSJan Kara  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
24224e7ea81dSJan Kara  * delayed, blocks are allocated, if it is unwritten, we may need to convert
24234e7ea81dSJan Kara  * them to initialized or split the described range from larger unwritten
24244e7ea81dSJan Kara  * extent. Note that we need not map all the described range since allocation
24254e7ea81dSJan Kara  * can return less blocks or the range is covered by more unwritten extents. We
24264e7ea81dSJan Kara  * cannot map more because we are limited by reserved transaction credits. On
24274e7ea81dSJan Kara  * the other hand we always make sure that the last touched page is fully
24284e7ea81dSJan Kara  * mapped so that it can be written out (and thus forward progress is
24294e7ea81dSJan Kara  * guaranteed). After mapping we submit all mapped pages for IO.
24304e7ea81dSJan Kara  */
24314e7ea81dSJan Kara static int mpage_map_and_submit_extent(handle_t *handle,
2432cb530541STheodore Ts'o 				       struct mpage_da_data *mpd,
2433cb530541STheodore Ts'o 				       bool *give_up_on_write)
24344e7ea81dSJan Kara {
24354e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
24364e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
24374e7ea81dSJan Kara 	int err;
24384e7ea81dSJan Kara 	loff_t disksize;
24396603120eSDmitry Monakhov 	int progress = 0;
2440c8cc8816SRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
24414d06bfb9SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec;
24424e7ea81dSJan Kara 
24434d06bfb9SRitesh Harjani 	io_end_vec = ext4_alloc_io_end_vec(io_end);
24444d06bfb9SRitesh Harjani 	if (IS_ERR(io_end_vec))
24454d06bfb9SRitesh Harjani 		return PTR_ERR(io_end_vec);
2446c8cc8816SRitesh Harjani 	io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
244727d7c4edSJan Kara 	do {
24484e7ea81dSJan Kara 		err = mpage_map_one_extent(handle, mpd);
24494e7ea81dSJan Kara 		if (err < 0) {
24504e7ea81dSJan Kara 			struct super_block *sb = inode->i_sb;
24514e7ea81dSJan Kara 
24520db1ff22STheodore Ts'o 			if (ext4_forced_shutdown(EXT4_SB(sb)) ||
24539b5f6c9bSHarshad Shirwadkar 			    ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
2454cb530541STheodore Ts'o 				goto invalidate_dirty_pages;
24554e7ea81dSJan Kara 			/*
2456cb530541STheodore Ts'o 			 * Let the uper layers retry transient errors.
2457cb530541STheodore Ts'o 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2458cb530541STheodore Ts'o 			 * is non-zero, a commit should free up blocks.
24594e7ea81dSJan Kara 			 */
2460cb530541STheodore Ts'o 			if ((err == -ENOMEM) ||
24616603120eSDmitry Monakhov 			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
24626603120eSDmitry Monakhov 				if (progress)
24636603120eSDmitry Monakhov 					goto update_disksize;
2464cb530541STheodore Ts'o 				return err;
24656603120eSDmitry Monakhov 			}
24664e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24674e7ea81dSJan Kara 				 "Delayed block allocation failed for "
24684e7ea81dSJan Kara 				 "inode %lu at logical offset %llu with"
24694e7ea81dSJan Kara 				 " max blocks %u with error %d",
24704e7ea81dSJan Kara 				 inode->i_ino,
24714e7ea81dSJan Kara 				 (unsigned long long)map->m_lblk,
2472cb530541STheodore Ts'o 				 (unsigned)map->m_len, -err);
24734e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24744e7ea81dSJan Kara 				 "This should not happen!! Data will "
24754e7ea81dSJan Kara 				 "be lost\n");
24764e7ea81dSJan Kara 			if (err == -ENOSPC)
24774e7ea81dSJan Kara 				ext4_print_free_blocks(inode);
2478cb530541STheodore Ts'o 		invalidate_dirty_pages:
2479cb530541STheodore Ts'o 			*give_up_on_write = true;
24804e7ea81dSJan Kara 			return err;
24814e7ea81dSJan Kara 		}
24826603120eSDmitry Monakhov 		progress = 1;
24834e7ea81dSJan Kara 		/*
24844e7ea81dSJan Kara 		 * Update buffer state, submit mapped pages, and get us new
24854e7ea81dSJan Kara 		 * extent to map
24864e7ea81dSJan Kara 		 */
24874e7ea81dSJan Kara 		err = mpage_map_and_submit_buffers(mpd);
24884e7ea81dSJan Kara 		if (err < 0)
24896603120eSDmitry Monakhov 			goto update_disksize;
249027d7c4edSJan Kara 	} while (map->m_len);
24914e7ea81dSJan Kara 
24926603120eSDmitry Monakhov update_disksize:
2493622cad13STheodore Ts'o 	/*
2494622cad13STheodore Ts'o 	 * Update on-disk size after IO is submitted.  Races with
2495622cad13STheodore Ts'o 	 * truncate are avoided by checking i_size under i_data_sem.
2496622cad13STheodore Ts'o 	 */
249709cbfeafSKirill A. Shutemov 	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
249835df4299SQian Cai 	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
24994e7ea81dSJan Kara 		int err2;
2500622cad13STheodore Ts'o 		loff_t i_size;
25014e7ea81dSJan Kara 
2502622cad13STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
2503622cad13STheodore Ts'o 		i_size = i_size_read(inode);
2504622cad13STheodore Ts'o 		if (disksize > i_size)
2505622cad13STheodore Ts'o 			disksize = i_size;
2506622cad13STheodore Ts'o 		if (disksize > EXT4_I(inode)->i_disksize)
2507622cad13STheodore Ts'o 			EXT4_I(inode)->i_disksize = disksize;
2508622cad13STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
2509b907f2d5STheodore Ts'o 		err2 = ext4_mark_inode_dirty(handle, inode);
2510878520acSTheodore Ts'o 		if (err2) {
251154d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err2,
25124e7ea81dSJan Kara 				       "Failed to mark inode %lu dirty",
25134e7ea81dSJan Kara 				       inode->i_ino);
2514878520acSTheodore Ts'o 		}
25154e7ea81dSJan Kara 		if (!err)
25164e7ea81dSJan Kara 			err = err2;
25174e7ea81dSJan Kara 	}
25184e7ea81dSJan Kara 	return err;
25194e7ea81dSJan Kara }
25204e7ea81dSJan Kara 
25214e7ea81dSJan Kara /*
2522fffb2739SJan Kara  * Calculate the total number of credits to reserve for one writepages
252320970ba6STheodore Ts'o  * iteration. This is called from ext4_writepages(). We map an extent of
2524fffb2739SJan Kara  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2525fffb2739SJan Kara  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2526fffb2739SJan Kara  * bpp - 1 blocks in bpp different extents.
2527525f4ed8SMingming Cao  */
2528fffb2739SJan Kara static int ext4_da_writepages_trans_blocks(struct inode *inode)
2529fffb2739SJan Kara {
2530fffb2739SJan Kara 	int bpp = ext4_journal_blocks_per_page(inode);
2531525f4ed8SMingming Cao 
2532fffb2739SJan Kara 	return ext4_meta_trans_blocks(inode,
2533fffb2739SJan Kara 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2534525f4ed8SMingming Cao }
253561628a3fSMingming Cao 
25368e48dcfbSTheodore Ts'o /*
25374e7ea81dSJan Kara  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
25384e7ea81dSJan Kara  * 				 and underlying extent to map
25394e7ea81dSJan Kara  *
25404e7ea81dSJan Kara  * @mpd - where to look for pages
25414e7ea81dSJan Kara  *
25424e7ea81dSJan Kara  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
25434e7ea81dSJan Kara  * IO immediately. When we find a page which isn't mapped we start accumulating
25444e7ea81dSJan Kara  * extent of buffers underlying these pages that needs mapping (formed by
25454e7ea81dSJan Kara  * either delayed or unwritten buffers). We also lock the pages containing
25464e7ea81dSJan Kara  * these buffers. The extent found is returned in @mpd structure (starting at
25474e7ea81dSJan Kara  * mpd->lblk with length mpd->len blocks).
25484e7ea81dSJan Kara  *
25494e7ea81dSJan Kara  * Note that this function can attach bios to one io_end structure which are
25504e7ea81dSJan Kara  * neither logically nor physically contiguous. Although it may seem as an
25514e7ea81dSJan Kara  * unnecessary complication, it is actually inevitable in blocksize < pagesize
25524e7ea81dSJan Kara  * case as we need to track IO to all buffers underlying a page in one io_end.
25538e48dcfbSTheodore Ts'o  */
25544e7ea81dSJan Kara static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
25558e48dcfbSTheodore Ts'o {
25564e7ea81dSJan Kara 	struct address_space *mapping = mpd->inode->i_mapping;
25578e48dcfbSTheodore Ts'o 	struct pagevec pvec;
25584f01b02cSTheodore Ts'o 	unsigned int nr_pages;
2559aeac589aSMing Lei 	long left = mpd->wbc->nr_to_write;
25604e7ea81dSJan Kara 	pgoff_t index = mpd->first_page;
25614e7ea81dSJan Kara 	pgoff_t end = mpd->last_page;
256210bbd235SMatthew Wilcox 	xa_mark_t tag;
25634e7ea81dSJan Kara 	int i, err = 0;
25644e7ea81dSJan Kara 	int blkbits = mpd->inode->i_blkbits;
25654e7ea81dSJan Kara 	ext4_lblk_t lblk;
25664e7ea81dSJan Kara 	struct buffer_head *head;
25678e48dcfbSTheodore Ts'o 
25684e7ea81dSJan Kara 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
25695b41d924SEric Sandeen 		tag = PAGECACHE_TAG_TOWRITE;
25705b41d924SEric Sandeen 	else
25715b41d924SEric Sandeen 		tag = PAGECACHE_TAG_DIRTY;
25725b41d924SEric Sandeen 
257386679820SMel Gorman 	pagevec_init(&pvec);
25744e7ea81dSJan Kara 	mpd->map.m_len = 0;
25754e7ea81dSJan Kara 	mpd->next_page = index;
25764f01b02cSTheodore Ts'o 	while (index <= end) {
2577dc7f3e86SJan Kara 		nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
257867fd707fSJan Kara 				tag);
25798e48dcfbSTheodore Ts'o 		if (nr_pages == 0)
25806b8ed620SJan Kara 			break;
25818e48dcfbSTheodore Ts'o 
25828e48dcfbSTheodore Ts'o 		for (i = 0; i < nr_pages; i++) {
25838e48dcfbSTheodore Ts'o 			struct page *page = pvec.pages[i];
25848e48dcfbSTheodore Ts'o 
25858e48dcfbSTheodore Ts'o 			/*
2586aeac589aSMing Lei 			 * Accumulated enough dirty pages? This doesn't apply
2587aeac589aSMing Lei 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2588aeac589aSMing Lei 			 * keep going because someone may be concurrently
2589aeac589aSMing Lei 			 * dirtying pages, and we might have synced a lot of
2590aeac589aSMing Lei 			 * newly appeared dirty pages, but have not synced all
2591aeac589aSMing Lei 			 * of the old dirty pages.
2592aeac589aSMing Lei 			 */
2593aeac589aSMing Lei 			if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2594aeac589aSMing Lei 				goto out;
2595aeac589aSMing Lei 
25964e7ea81dSJan Kara 			/* If we can't merge this page, we are done. */
25974e7ea81dSJan Kara 			if (mpd->map.m_len > 0 && mpd->next_page != page->index)
25984e7ea81dSJan Kara 				goto out;
259978aaced3STheodore Ts'o 
26008e48dcfbSTheodore Ts'o 			lock_page(page);
26018e48dcfbSTheodore Ts'o 			/*
26024e7ea81dSJan Kara 			 * If the page is no longer dirty, or its mapping no
26034e7ea81dSJan Kara 			 * longer corresponds to inode we are writing (which
26044e7ea81dSJan Kara 			 * means it has been truncated or invalidated), or the
26054e7ea81dSJan Kara 			 * page is already under writeback and we are not doing
26064e7ea81dSJan Kara 			 * a data integrity writeback, skip the page
26078e48dcfbSTheodore Ts'o 			 */
26084f01b02cSTheodore Ts'o 			if (!PageDirty(page) ||
26094f01b02cSTheodore Ts'o 			    (PageWriteback(page) &&
26104e7ea81dSJan Kara 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
26114f01b02cSTheodore Ts'o 			    unlikely(page->mapping != mapping)) {
26128e48dcfbSTheodore Ts'o 				unlock_page(page);
26138e48dcfbSTheodore Ts'o 				continue;
26148e48dcfbSTheodore Ts'o 			}
26158e48dcfbSTheodore Ts'o 
26168e48dcfbSTheodore Ts'o 			wait_on_page_writeback(page);
26178e48dcfbSTheodore Ts'o 			BUG_ON(PageWriteback(page));
26188e48dcfbSTheodore Ts'o 
26194e7ea81dSJan Kara 			if (mpd->map.m_len == 0)
26208eb9e5ceSTheodore Ts'o 				mpd->first_page = page->index;
26218eb9e5ceSTheodore Ts'o 			mpd->next_page = page->index + 1;
2622f8bec370SJan Kara 			/* Add all dirty buffers to mpd */
26234e7ea81dSJan Kara 			lblk = ((ext4_lblk_t)page->index) <<
262409cbfeafSKirill A. Shutemov 				(PAGE_SHIFT - blkbits);
26258eb9e5ceSTheodore Ts'o 			head = page_buffers(page);
26265f1132b2SJan Kara 			err = mpage_process_page_bufs(mpd, head, head, lblk);
26275f1132b2SJan Kara 			if (err <= 0)
26284e7ea81dSJan Kara 				goto out;
26295f1132b2SJan Kara 			err = 0;
2630aeac589aSMing Lei 			left--;
26318e48dcfbSTheodore Ts'o 		}
26328e48dcfbSTheodore Ts'o 		pagevec_release(&pvec);
26338e48dcfbSTheodore Ts'o 		cond_resched();
26348e48dcfbSTheodore Ts'o 	}
26356b8ed620SJan Kara 	mpd->scanned_until_end = 1;
26364f01b02cSTheodore Ts'o 	return 0;
26378eb9e5ceSTheodore Ts'o out:
26388eb9e5ceSTheodore Ts'o 	pagevec_release(&pvec);
26394e7ea81dSJan Kara 	return err;
26408e48dcfbSTheodore Ts'o }
26418e48dcfbSTheodore Ts'o 
264220970ba6STheodore Ts'o static int ext4_writepages(struct address_space *mapping,
264364769240SAlex Tomas 			   struct writeback_control *wbc)
264464769240SAlex Tomas {
26454e7ea81dSJan Kara 	pgoff_t	writeback_index = 0;
26464e7ea81dSJan Kara 	long nr_to_write = wbc->nr_to_write;
264722208dedSAneesh Kumar K.V 	int range_whole = 0;
26484e7ea81dSJan Kara 	int cycled = 1;
264961628a3fSMingming Cao 	handle_t *handle = NULL;
2650df22291fSAneesh Kumar K.V 	struct mpage_da_data mpd;
26515e745b04SAneesh Kumar K.V 	struct inode *inode = mapping->host;
26526b523df4SJan Kara 	int needed_blocks, rsv_blocks = 0, ret = 0;
26535e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
26541bce63d1SShaohua Li 	struct blk_plug plug;
2655cb530541STheodore Ts'o 	bool give_up_on_write = false;
265661628a3fSMingming Cao 
26570db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
26580db1ff22STheodore Ts'o 		return -EIO;
26590db1ff22STheodore Ts'o 
2660bbd55937SEric Biggers 	percpu_down_read(&sbi->s_writepages_rwsem);
266120970ba6STheodore Ts'o 	trace_ext4_writepages(inode, wbc);
2662ba80b101STheodore Ts'o 
266361628a3fSMingming Cao 	/*
266461628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
266561628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
266661628a3fSMingming Cao 	 * because that could violate lock ordering on umount
266761628a3fSMingming Cao 	 */
2668a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2669bbf023c7SMing Lei 		goto out_writepages;
26702a21e37eSTheodore Ts'o 
267120970ba6STheodore Ts'o 	if (ext4_should_journal_data(inode)) {
2672043d20d1SGoldwyn Rodrigues 		ret = generic_writepages(mapping, wbc);
2673bbf023c7SMing Lei 		goto out_writepages;
267420970ba6STheodore Ts'o 	}
267520970ba6STheodore Ts'o 
26762a21e37eSTheodore Ts'o 	/*
26772a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
26782a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
26792a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
26801751e8a6SLinus Torvalds 	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
26812a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
268220970ba6STheodore Ts'o 	 * read-only, and in that case, ext4_writepages should
26832a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
26842a21e37eSTheodore Ts'o 	 * the stack trace.
26852a21e37eSTheodore Ts'o 	 */
26860db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
26879b5f6c9bSHarshad Shirwadkar 		     ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
2688bbf023c7SMing Lei 		ret = -EROFS;
2689bbf023c7SMing Lei 		goto out_writepages;
2690bbf023c7SMing Lei 	}
26912a21e37eSTheodore Ts'o 
26924e7ea81dSJan Kara 	/*
26934e7ea81dSJan Kara 	 * If we have inline data and arrive here, it means that
26944e7ea81dSJan Kara 	 * we will soon create the block for the 1st page, so
26954e7ea81dSJan Kara 	 * we'd better clear the inline data here.
26964e7ea81dSJan Kara 	 */
26974e7ea81dSJan Kara 	if (ext4_has_inline_data(inode)) {
26984e7ea81dSJan Kara 		/* Just inode will be modified... */
26994e7ea81dSJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
27004e7ea81dSJan Kara 		if (IS_ERR(handle)) {
27014e7ea81dSJan Kara 			ret = PTR_ERR(handle);
27024e7ea81dSJan Kara 			goto out_writepages;
27034e7ea81dSJan Kara 		}
27044e7ea81dSJan Kara 		BUG_ON(ext4_test_inode_state(inode,
27054e7ea81dSJan Kara 				EXT4_STATE_MAY_INLINE_DATA));
27064e7ea81dSJan Kara 		ext4_destroy_inline_data(handle, inode);
27074e7ea81dSJan Kara 		ext4_journal_stop(handle);
27084e7ea81dSJan Kara 	}
27094e7ea81dSJan Kara 
27104e343231Syangerkun 	if (ext4_should_dioread_nolock(inode)) {
27114e343231Syangerkun 		/*
27124e343231Syangerkun 		 * We may need to convert up to one extent per block in
27134e343231Syangerkun 		 * the page and we may dirty the inode.
27144e343231Syangerkun 		 */
27154e343231Syangerkun 		rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
27164e343231Syangerkun 						PAGE_SIZE >> inode->i_blkbits);
27174e343231Syangerkun 	}
27184e343231Syangerkun 
271922208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
272022208dedSAneesh Kumar K.V 		range_whole = 1;
272161628a3fSMingming Cao 
27222acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
27234e7ea81dSJan Kara 		writeback_index = mapping->writeback_index;
27244e7ea81dSJan Kara 		if (writeback_index)
27252acf2c26SAneesh Kumar K.V 			cycled = 0;
27264e7ea81dSJan Kara 		mpd.first_page = writeback_index;
27274e7ea81dSJan Kara 		mpd.last_page = -1;
27285b41d924SEric Sandeen 	} else {
272909cbfeafSKirill A. Shutemov 		mpd.first_page = wbc->range_start >> PAGE_SHIFT;
273009cbfeafSKirill A. Shutemov 		mpd.last_page = wbc->range_end >> PAGE_SHIFT;
27315b41d924SEric Sandeen 	}
2732a1d6cc56SAneesh Kumar K.V 
27334e7ea81dSJan Kara 	mpd.inode = inode;
27344e7ea81dSJan Kara 	mpd.wbc = wbc;
27354e7ea81dSJan Kara 	ext4_io_submit_init(&mpd.io_submit, wbc);
27362acf2c26SAneesh Kumar K.V retry:
27376e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
27384e7ea81dSJan Kara 		tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
27391bce63d1SShaohua Li 	blk_start_plug(&plug);
2740dddbd6acSJan Kara 
2741dddbd6acSJan Kara 	/*
2742dddbd6acSJan Kara 	 * First writeback pages that don't need mapping - we can avoid
2743dddbd6acSJan Kara 	 * starting a transaction unnecessarily and also avoid being blocked
2744dddbd6acSJan Kara 	 * in the block layer on device congestion while having transaction
2745dddbd6acSJan Kara 	 * started.
2746dddbd6acSJan Kara 	 */
2747dddbd6acSJan Kara 	mpd.do_map = 0;
27486b8ed620SJan Kara 	mpd.scanned_until_end = 0;
2749dddbd6acSJan Kara 	mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2750dddbd6acSJan Kara 	if (!mpd.io_submit.io_end) {
2751dddbd6acSJan Kara 		ret = -ENOMEM;
2752dddbd6acSJan Kara 		goto unplug;
2753dddbd6acSJan Kara 	}
2754dddbd6acSJan Kara 	ret = mpage_prepare_extent_to_map(&mpd);
2755a297b2fcSXiaoguang Wang 	/* Unlock pages we didn't use */
2756a297b2fcSXiaoguang Wang 	mpage_release_unused_pages(&mpd, false);
2757dddbd6acSJan Kara 	/* Submit prepared bio */
2758dddbd6acSJan Kara 	ext4_io_submit(&mpd.io_submit);
2759dddbd6acSJan Kara 	ext4_put_io_end_defer(mpd.io_submit.io_end);
2760dddbd6acSJan Kara 	mpd.io_submit.io_end = NULL;
2761dddbd6acSJan Kara 	if (ret < 0)
2762dddbd6acSJan Kara 		goto unplug;
2763dddbd6acSJan Kara 
27646b8ed620SJan Kara 	while (!mpd.scanned_until_end && wbc->nr_to_write > 0) {
27654e7ea81dSJan Kara 		/* For each extent of pages we use new io_end */
27664e7ea81dSJan Kara 		mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
27674e7ea81dSJan Kara 		if (!mpd.io_submit.io_end) {
27684e7ea81dSJan Kara 			ret = -ENOMEM;
27694e7ea81dSJan Kara 			break;
27704e7ea81dSJan Kara 		}
2771a1d6cc56SAneesh Kumar K.V 
2772a1d6cc56SAneesh Kumar K.V 		/*
27734e7ea81dSJan Kara 		 * We have two constraints: We find one extent to map and we
27744e7ea81dSJan Kara 		 * must always write out whole page (makes a difference when
27754e7ea81dSJan Kara 		 * blocksize < pagesize) so that we don't block on IO when we
27764e7ea81dSJan Kara 		 * try to write out the rest of the page. Journalled mode is
27774e7ea81dSJan Kara 		 * not supported by delalloc.
2778a1d6cc56SAneesh Kumar K.V 		 */
2779a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
2780525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2781a1d6cc56SAneesh Kumar K.V 
278261628a3fSMingming Cao 		/* start a new transaction */
27836b523df4SJan Kara 		handle = ext4_journal_start_with_reserve(inode,
27846b523df4SJan Kara 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
278561628a3fSMingming Cao 		if (IS_ERR(handle)) {
278661628a3fSMingming Cao 			ret = PTR_ERR(handle);
27871693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2788fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
2789a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
27904e7ea81dSJan Kara 			/* Release allocated io_end */
27914e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
2792dddbd6acSJan Kara 			mpd.io_submit.io_end = NULL;
27934e7ea81dSJan Kara 			break;
279461628a3fSMingming Cao 		}
2795dddbd6acSJan Kara 		mpd.do_map = 1;
2796f63e6005STheodore Ts'o 
27974e7ea81dSJan Kara 		trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
27984e7ea81dSJan Kara 		ret = mpage_prepare_extent_to_map(&mpd);
27996b8ed620SJan Kara 		if (!ret && mpd.map.m_len)
2800cb530541STheodore Ts'o 			ret = mpage_map_and_submit_extent(handle, &mpd,
2801cb530541STheodore Ts'o 					&give_up_on_write);
2802646caa9cSJan Kara 		/*
2803646caa9cSJan Kara 		 * Caution: If the handle is synchronous,
2804646caa9cSJan Kara 		 * ext4_journal_stop() can wait for transaction commit
2805646caa9cSJan Kara 		 * to finish which may depend on writeback of pages to
2806646caa9cSJan Kara 		 * complete or on page lock to be released.  In that
2807b483bb77SRandy Dunlap 		 * case, we have to wait until after we have
2808646caa9cSJan Kara 		 * submitted all the IO, released page locks we hold,
2809646caa9cSJan Kara 		 * and dropped io_end reference (for extent conversion
2810646caa9cSJan Kara 		 * to be able to complete) before stopping the handle.
2811646caa9cSJan Kara 		 */
2812646caa9cSJan Kara 		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
281361628a3fSMingming Cao 			ext4_journal_stop(handle);
2814646caa9cSJan Kara 			handle = NULL;
2815dddbd6acSJan Kara 			mpd.do_map = 0;
2816646caa9cSJan Kara 		}
28174e7ea81dSJan Kara 		/* Unlock pages we didn't use */
2818cb530541STheodore Ts'o 		mpage_release_unused_pages(&mpd, give_up_on_write);
2819a297b2fcSXiaoguang Wang 		/* Submit prepared bio */
2820a297b2fcSXiaoguang Wang 		ext4_io_submit(&mpd.io_submit);
2821a297b2fcSXiaoguang Wang 
2822646caa9cSJan Kara 		/*
2823646caa9cSJan Kara 		 * Drop our io_end reference we got from init. We have
2824646caa9cSJan Kara 		 * to be careful and use deferred io_end finishing if
2825646caa9cSJan Kara 		 * we are still holding the transaction as we can
2826646caa9cSJan Kara 		 * release the last reference to io_end which may end
2827646caa9cSJan Kara 		 * up doing unwritten extent conversion.
2828646caa9cSJan Kara 		 */
2829646caa9cSJan Kara 		if (handle) {
2830646caa9cSJan Kara 			ext4_put_io_end_defer(mpd.io_submit.io_end);
2831646caa9cSJan Kara 			ext4_journal_stop(handle);
2832646caa9cSJan Kara 		} else
28334e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
2834dddbd6acSJan Kara 		mpd.io_submit.io_end = NULL;
2835df22291fSAneesh Kumar K.V 
28364e7ea81dSJan Kara 		if (ret == -ENOSPC && sbi->s_journal) {
28374e7ea81dSJan Kara 			/*
28384e7ea81dSJan Kara 			 * Commit the transaction which would
283922208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
284022208dedSAneesh Kumar K.V 			 * and try again
284122208dedSAneesh Kumar K.V 			 */
2842df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
284322208dedSAneesh Kumar K.V 			ret = 0;
28444e7ea81dSJan Kara 			continue;
28454e7ea81dSJan Kara 		}
28464e7ea81dSJan Kara 		/* Fatal error - ENOMEM, EIO... */
28474e7ea81dSJan Kara 		if (ret)
284861628a3fSMingming Cao 			break;
284961628a3fSMingming Cao 	}
2850dddbd6acSJan Kara unplug:
28511bce63d1SShaohua Li 	blk_finish_plug(&plug);
28529c12a831SJan Kara 	if (!ret && !cycled && wbc->nr_to_write > 0) {
28532acf2c26SAneesh Kumar K.V 		cycled = 1;
28544e7ea81dSJan Kara 		mpd.last_page = writeback_index - 1;
28554e7ea81dSJan Kara 		mpd.first_page = 0;
28562acf2c26SAneesh Kumar K.V 		goto retry;
28572acf2c26SAneesh Kumar K.V 	}
285861628a3fSMingming Cao 
285922208dedSAneesh Kumar K.V 	/* Update index */
286022208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
286122208dedSAneesh Kumar K.V 		/*
28624e7ea81dSJan Kara 		 * Set the writeback_index so that range_cyclic
286322208dedSAneesh Kumar K.V 		 * mode will write it back later
286422208dedSAneesh Kumar K.V 		 */
28654e7ea81dSJan Kara 		mapping->writeback_index = mpd.first_page;
2866a1d6cc56SAneesh Kumar K.V 
286761628a3fSMingming Cao out_writepages:
286820970ba6STheodore Ts'o 	trace_ext4_writepages_result(inode, wbc, ret,
28694e7ea81dSJan Kara 				     nr_to_write - wbc->nr_to_write);
2870bbd55937SEric Biggers 	percpu_up_read(&sbi->s_writepages_rwsem);
287161628a3fSMingming Cao 	return ret;
287264769240SAlex Tomas }
287364769240SAlex Tomas 
28745f0663bbSDan Williams static int ext4_dax_writepages(struct address_space *mapping,
28755f0663bbSDan Williams 			       struct writeback_control *wbc)
28765f0663bbSDan Williams {
28775f0663bbSDan Williams 	int ret;
28785f0663bbSDan Williams 	long nr_to_write = wbc->nr_to_write;
28795f0663bbSDan Williams 	struct inode *inode = mapping->host;
28805f0663bbSDan Williams 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
28815f0663bbSDan Williams 
28825f0663bbSDan Williams 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
28835f0663bbSDan Williams 		return -EIO;
28845f0663bbSDan Williams 
2885bbd55937SEric Biggers 	percpu_down_read(&sbi->s_writepages_rwsem);
28865f0663bbSDan Williams 	trace_ext4_writepages(inode, wbc);
28875f0663bbSDan Williams 
28883f666c56SVivek Goyal 	ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
28895f0663bbSDan Williams 	trace_ext4_writepages_result(inode, wbc, ret,
28905f0663bbSDan Williams 				     nr_to_write - wbc->nr_to_write);
2891bbd55937SEric Biggers 	percpu_up_read(&sbi->s_writepages_rwsem);
28925f0663bbSDan Williams 	return ret;
28935f0663bbSDan Williams }
28945f0663bbSDan Williams 
289579f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
289679f0be8dSAneesh Kumar K.V {
28975c1ff336SEric Whitney 	s64 free_clusters, dirty_clusters;
289879f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
289979f0be8dSAneesh Kumar K.V 
290079f0be8dSAneesh Kumar K.V 	/*
290179f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
290279f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
2903179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
290479f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
290579f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
290679f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
290779f0be8dSAneesh Kumar K.V 	 */
29085c1ff336SEric Whitney 	free_clusters =
29095c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
29105c1ff336SEric Whitney 	dirty_clusters =
29115c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
291200d4e736STheodore Ts'o 	/*
291300d4e736STheodore Ts'o 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
291400d4e736STheodore Ts'o 	 */
29155c1ff336SEric Whitney 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
291610ee27a0SMiao Xie 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
291700d4e736STheodore Ts'o 
29185c1ff336SEric Whitney 	if (2 * free_clusters < 3 * dirty_clusters ||
29195c1ff336SEric Whitney 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
292079f0be8dSAneesh Kumar K.V 		/*
2921c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
2922c8afb446SEric Sandeen 		 * or free blocks is less than watermark
292379f0be8dSAneesh Kumar K.V 		 */
292479f0be8dSAneesh Kumar K.V 		return 1;
292579f0be8dSAneesh Kumar K.V 	}
292679f0be8dSAneesh Kumar K.V 	return 0;
292779f0be8dSAneesh Kumar K.V }
292879f0be8dSAneesh Kumar K.V 
29290ff8947fSEric Sandeen /* We always reserve for an inode update; the superblock could be there too */
29300ff8947fSEric Sandeen static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
29310ff8947fSEric Sandeen {
2932e2b911c5SDarrick J. Wong 	if (likely(ext4_has_feature_large_file(inode->i_sb)))
29330ff8947fSEric Sandeen 		return 1;
29340ff8947fSEric Sandeen 
29350ff8947fSEric Sandeen 	if (pos + len <= 0x7fffffffULL)
29360ff8947fSEric Sandeen 		return 1;
29370ff8947fSEric Sandeen 
29380ff8947fSEric Sandeen 	/* We might need to update the superblock to set LARGE_FILE */
29390ff8947fSEric Sandeen 	return 2;
29400ff8947fSEric Sandeen }
29410ff8947fSEric Sandeen 
294264769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
294364769240SAlex Tomas 			       loff_t pos, unsigned len, unsigned flags,
294464769240SAlex Tomas 			       struct page **pagep, void **fsdata)
294564769240SAlex Tomas {
294672b8ab9dSEric Sandeen 	int ret, retries = 0;
294764769240SAlex Tomas 	struct page *page;
294864769240SAlex Tomas 	pgoff_t index;
294964769240SAlex Tomas 	struct inode *inode = mapping->host;
295064769240SAlex Tomas 	handle_t *handle;
295164769240SAlex Tomas 
29520db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
29530db1ff22STheodore Ts'o 		return -EIO;
29540db1ff22STheodore Ts'o 
295509cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
295679f0be8dSAneesh Kumar K.V 
2957c93d8f88SEric Biggers 	if (ext4_nonda_switch(inode->i_sb) || S_ISLNK(inode->i_mode) ||
2958c93d8f88SEric Biggers 	    ext4_verity_in_progress(inode)) {
295979f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
296079f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
296179f0be8dSAneesh Kumar K.V 					len, flags, pagep, fsdata);
296279f0be8dSAneesh Kumar K.V 	}
296379f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
29649bffad1eSTheodore Ts'o 	trace_ext4_da_write_begin(inode, pos, len, flags);
29659c3569b5STao Ma 
29669c3569b5STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
29679c3569b5STao Ma 		ret = ext4_da_write_inline_data_begin(mapping, inode,
29689c3569b5STao Ma 						      pos, len, flags,
29699c3569b5STao Ma 						      pagep, fsdata);
29709c3569b5STao Ma 		if (ret < 0)
297147564bfbSTheodore Ts'o 			return ret;
297247564bfbSTheodore Ts'o 		if (ret == 1)
297347564bfbSTheodore Ts'o 			return 0;
29749c3569b5STao Ma 	}
29759c3569b5STao Ma 
297647564bfbSTheodore Ts'o 	/*
297747564bfbSTheodore Ts'o 	 * grab_cache_page_write_begin() can take a long time if the
297847564bfbSTheodore Ts'o 	 * system is thrashing due to memory pressure, or if the page
297947564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
298047564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
298147564bfbSTheodore Ts'o 	 * the page (if needed) without using GFP_NOFS.
298247564bfbSTheodore Ts'o 	 */
298347564bfbSTheodore Ts'o retry_grab:
298447564bfbSTheodore Ts'o 	page = grab_cache_page_write_begin(mapping, index, flags);
298547564bfbSTheodore Ts'o 	if (!page)
298647564bfbSTheodore Ts'o 		return -ENOMEM;
298747564bfbSTheodore Ts'o 	unlock_page(page);
298847564bfbSTheodore Ts'o 
298964769240SAlex Tomas 	/*
299064769240SAlex Tomas 	 * With delayed allocation, we don't log the i_disksize update
299164769240SAlex Tomas 	 * if there is delayed block allocation. But we still need
299264769240SAlex Tomas 	 * to journalling the i_disksize update if writes to the end
299364769240SAlex Tomas 	 * of file which has an already mapped buffer.
299464769240SAlex Tomas 	 */
299547564bfbSTheodore Ts'o retry_journal:
29960ff8947fSEric Sandeen 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
29970ff8947fSEric Sandeen 				ext4_da_write_credits(inode, pos, len));
299864769240SAlex Tomas 	if (IS_ERR(handle)) {
299909cbfeafSKirill A. Shutemov 		put_page(page);
300047564bfbSTheodore Ts'o 		return PTR_ERR(handle);
300164769240SAlex Tomas 	}
300264769240SAlex Tomas 
300347564bfbSTheodore Ts'o 	lock_page(page);
300447564bfbSTheodore Ts'o 	if (page->mapping != mapping) {
300547564bfbSTheodore Ts'o 		/* The page got truncated from under us */
300647564bfbSTheodore Ts'o 		unlock_page(page);
300709cbfeafSKirill A. Shutemov 		put_page(page);
3008d5a0d4f7SEric Sandeen 		ext4_journal_stop(handle);
300947564bfbSTheodore Ts'o 		goto retry_grab;
3010d5a0d4f7SEric Sandeen 	}
301147564bfbSTheodore Ts'o 	/* In case writeback began while the page was unlocked */
30127afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
301364769240SAlex Tomas 
3014643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
30152058f83aSMichael Halcrow 	ret = ext4_block_write_begin(page, pos, len,
30162058f83aSMichael Halcrow 				     ext4_da_get_block_prep);
30172058f83aSMichael Halcrow #else
30186e1db88dSChristoph Hellwig 	ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
30192058f83aSMichael Halcrow #endif
302064769240SAlex Tomas 	if (ret < 0) {
302164769240SAlex Tomas 		unlock_page(page);
302264769240SAlex Tomas 		ext4_journal_stop(handle);
3023ae4d5372SAneesh Kumar K.V 		/*
3024ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
3025ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
3026ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
3027ae4d5372SAneesh Kumar K.V 		 */
3028ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
3029b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
303047564bfbSTheodore Ts'o 
303147564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
303247564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
303347564bfbSTheodore Ts'o 			goto retry_journal;
303447564bfbSTheodore Ts'o 
303509cbfeafSKirill A. Shutemov 		put_page(page);
303647564bfbSTheodore Ts'o 		return ret;
303764769240SAlex Tomas 	}
303864769240SAlex Tomas 
303947564bfbSTheodore Ts'o 	*pagep = page;
304064769240SAlex Tomas 	return ret;
304164769240SAlex Tomas }
304264769240SAlex Tomas 
3043632eaeabSMingming Cao /*
3044632eaeabSMingming Cao  * Check if we should update i_disksize
3045632eaeabSMingming Cao  * when write to the end of file but not require block allocation
3046632eaeabSMingming Cao  */
3047632eaeabSMingming Cao static int ext4_da_should_update_i_disksize(struct page *page,
3048632eaeabSMingming Cao 					    unsigned long offset)
3049632eaeabSMingming Cao {
3050632eaeabSMingming Cao 	struct buffer_head *bh;
3051632eaeabSMingming Cao 	struct inode *inode = page->mapping->host;
3052632eaeabSMingming Cao 	unsigned int idx;
3053632eaeabSMingming Cao 	int i;
3054632eaeabSMingming Cao 
3055632eaeabSMingming Cao 	bh = page_buffers(page);
3056632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
3057632eaeabSMingming Cao 
3058632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
3059632eaeabSMingming Cao 		bh = bh->b_this_page;
3060632eaeabSMingming Cao 
306129fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3062632eaeabSMingming Cao 		return 0;
3063632eaeabSMingming Cao 	return 1;
3064632eaeabSMingming Cao }
3065632eaeabSMingming Cao 
306664769240SAlex Tomas static int ext4_da_write_end(struct file *file,
306764769240SAlex Tomas 			     struct address_space *mapping,
306864769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
306964769240SAlex Tomas 			     struct page *page, void *fsdata)
307064769240SAlex Tomas {
307164769240SAlex Tomas 	struct inode *inode = mapping->host;
307264769240SAlex Tomas 	int ret = 0, ret2;
307364769240SAlex Tomas 	handle_t *handle = ext4_journal_current_handle();
307464769240SAlex Tomas 	loff_t new_i_size;
3075632eaeabSMingming Cao 	unsigned long start, end;
307679f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
307779f0be8dSAneesh Kumar K.V 
307874d553aaSTheodore Ts'o 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
307974d553aaSTheodore Ts'o 		return ext4_write_end(file, mapping, pos,
308079f0be8dSAneesh Kumar K.V 				      len, copied, page, fsdata);
3081632eaeabSMingming Cao 
30829bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
308309cbfeafSKirill A. Shutemov 	start = pos & (PAGE_SIZE - 1);
3084632eaeabSMingming Cao 	end = start + copied - 1;
308564769240SAlex Tomas 
308664769240SAlex Tomas 	/*
3087*4df031ffSZhang Yi 	 * Since we are holding inode lock, we are sure i_disksize <=
3088*4df031ffSZhang Yi 	 * i_size. We also know that if i_disksize < i_size, there are
3089*4df031ffSZhang Yi 	 * delalloc writes pending in the range upto i_size. If the end of
3090*4df031ffSZhang Yi 	 * the current write is <= i_size, there's no need to touch
3091*4df031ffSZhang Yi 	 * i_disksize since writeback will push i_disksize upto i_size
3092*4df031ffSZhang Yi 	 * eventually. If the end of the current write is > i_size and
3093*4df031ffSZhang Yi 	 * inside an allocated block (ext4_da_should_update_i_disksize()
3094*4df031ffSZhang Yi 	 * check), we need to update i_disksize here as neither
3095*4df031ffSZhang Yi 	 * ext4_writepage() nor certain ext4_writepages() paths not
3096*4df031ffSZhang Yi 	 * allocating blocks update i_disksize.
3097*4df031ffSZhang Yi 	 *
3098*4df031ffSZhang Yi 	 * Note that we defer inode dirtying to generic_write_end() /
3099*4df031ffSZhang Yi 	 * ext4_da_write_inline_data_end().
310064769240SAlex Tomas 	 */
310164769240SAlex Tomas 	new_i_size = pos + copied;
3102*4df031ffSZhang Yi 	if (copied && new_i_size > inode->i_size) {
31039c3569b5STao Ma 		if (ext4_has_inline_data(inode) ||
3104*4df031ffSZhang Yi 		    ext4_da_should_update_i_disksize(page, end))
3105ee124d27SDmitry Monakhov 			ext4_update_i_disksize(inode, new_i_size);
3106632eaeabSMingming Cao 	}
31079c3569b5STao Ma 
31089c3569b5STao Ma 	if (write_mode != CONVERT_INLINE_DATA &&
31099c3569b5STao Ma 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
31109c3569b5STao Ma 	    ext4_has_inline_data(inode))
3111*4df031ffSZhang Yi 		ret = ext4_da_write_inline_data_end(inode, pos, len, copied,
31129c3569b5STao Ma 						     page);
31139c3569b5STao Ma 	else
3114*4df031ffSZhang Yi 		ret = generic_write_end(file, mapping, pos, len, copied,
311564769240SAlex Tomas 							page, fsdata);
31169c3569b5STao Ma 
3117*4df031ffSZhang Yi 	copied = ret;
311864769240SAlex Tomas 	ret2 = ext4_journal_stop(handle);
31194209ae12SHarshad Shirwadkar 	if (unlikely(ret2 && !ret))
312064769240SAlex Tomas 		ret = ret2;
312164769240SAlex Tomas 
312264769240SAlex Tomas 	return ret ? ret : copied;
312364769240SAlex Tomas }
312464769240SAlex Tomas 
3125ccd2506bSTheodore Ts'o /*
3126ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
3127ccd2506bSTheodore Ts'o  */
3128ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
3129ccd2506bSTheodore Ts'o {
3130fb40ba0dSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
3131fb40ba0dSTheodore Ts'o 
313271d4f7d0STheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks)
3133ccd2506bSTheodore Ts'o 		return 0;
3134ccd2506bSTheodore Ts'o 
3135ccd2506bSTheodore Ts'o 	/*
3136ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
3137ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
3138ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
3139ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
3140ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
3141ccd2506bSTheodore Ts'o 	 *
314220970ba6STheodore Ts'o 	 * ext4_writepages() ->
3143ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
3144ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
3145ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
3146ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
3147ccd2506bSTheodore Ts'o 	 *
3148ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
3149ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
3150ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
3151ccd2506bSTheodore Ts'o 	 * doing I/O at all.
3152ccd2506bSTheodore Ts'o 	 *
3153ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
3154380cf090SWu Fengguang 	 * the pages by calling redirty_page_for_writepage() but that
3155ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
3156ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
315725985edcSLucas De Marchi 	 * simplifying them because we wouldn't actually intend to
3158ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
3159ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
3160ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
3161ccd2506bSTheodore Ts'o 	 *
3162ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
3163ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
3164ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
3165ccd2506bSTheodore Ts'o 	 */
3166ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
3167ccd2506bSTheodore Ts'o }
316864769240SAlex Tomas 
316964769240SAlex Tomas /*
3170ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
3171ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
3172ac27a0ecSDave Kleikamp  *
3173ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
3174617ba13bSMingming Cao  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3175ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
3176ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
3177ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
3178ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
3179ac27a0ecSDave Kleikamp  *
3180ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
3181ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
3182ac27a0ecSDave Kleikamp  */
3183617ba13bSMingming Cao static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3184ac27a0ecSDave Kleikamp {
3185ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
3186ac27a0ecSDave Kleikamp 	journal_t *journal;
3187ac27a0ecSDave Kleikamp 	int err;
3188ac27a0ecSDave Kleikamp 
318946c7f254STao Ma 	/*
319046c7f254STao Ma 	 * We can get here for an inline file via the FIBMAP ioctl
319146c7f254STao Ma 	 */
319246c7f254STao Ma 	if (ext4_has_inline_data(inode))
319346c7f254STao Ma 		return 0;
319446c7f254STao Ma 
319564769240SAlex Tomas 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
319664769240SAlex Tomas 			test_opt(inode->i_sb, DELALLOC)) {
319764769240SAlex Tomas 		/*
319864769240SAlex Tomas 		 * With delalloc we want to sync the file
319964769240SAlex Tomas 		 * so that we can make sure we allocate
320064769240SAlex Tomas 		 * blocks for file
320164769240SAlex Tomas 		 */
320264769240SAlex Tomas 		filemap_write_and_wait(mapping);
320364769240SAlex Tomas 	}
320464769240SAlex Tomas 
320519f5fb7aSTheodore Ts'o 	if (EXT4_JOURNAL(inode) &&
320619f5fb7aSTheodore Ts'o 	    ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3207ac27a0ecSDave Kleikamp 		/*
3208ac27a0ecSDave Kleikamp 		 * This is a REALLY heavyweight approach, but the use of
3209ac27a0ecSDave Kleikamp 		 * bmap on dirty files is expected to be extremely rare:
3210ac27a0ecSDave Kleikamp 		 * only if we run lilo or swapon on a freshly made file
3211ac27a0ecSDave Kleikamp 		 * do we expect this to happen.
3212ac27a0ecSDave Kleikamp 		 *
3213ac27a0ecSDave Kleikamp 		 * (bmap requires CAP_SYS_RAWIO so this does not
3214ac27a0ecSDave Kleikamp 		 * represent an unprivileged user DOS attack --- we'd be
3215ac27a0ecSDave Kleikamp 		 * in trouble if mortal users could trigger this path at
3216ac27a0ecSDave Kleikamp 		 * will.)
3217ac27a0ecSDave Kleikamp 		 *
3218617ba13bSMingming Cao 		 * NB. EXT4_STATE_JDATA is not set on files other than
3219ac27a0ecSDave Kleikamp 		 * regular files.  If somebody wants to bmap a directory
3220ac27a0ecSDave Kleikamp 		 * or symlink and gets confused because the buffer
3221ac27a0ecSDave Kleikamp 		 * hasn't yet been flushed to disk, they deserve
3222ac27a0ecSDave Kleikamp 		 * everything they get.
3223ac27a0ecSDave Kleikamp 		 */
3224ac27a0ecSDave Kleikamp 
322519f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3226617ba13bSMingming Cao 		journal = EXT4_JOURNAL(inode);
3227dab291afSMingming Cao 		jbd2_journal_lock_updates(journal);
322801d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
3229dab291afSMingming Cao 		jbd2_journal_unlock_updates(journal);
3230ac27a0ecSDave Kleikamp 
3231ac27a0ecSDave Kleikamp 		if (err)
3232ac27a0ecSDave Kleikamp 			return 0;
3233ac27a0ecSDave Kleikamp 	}
3234ac27a0ecSDave Kleikamp 
3235ac58e4fbSRitesh Harjani 	return iomap_bmap(mapping, block, &ext4_iomap_ops);
3236ac27a0ecSDave Kleikamp }
3237ac27a0ecSDave Kleikamp 
3238617ba13bSMingming Cao static int ext4_readpage(struct file *file, struct page *page)
3239ac27a0ecSDave Kleikamp {
324046c7f254STao Ma 	int ret = -EAGAIN;
324146c7f254STao Ma 	struct inode *inode = page->mapping->host;
324246c7f254STao Ma 
32430562e0baSJiaying Zhang 	trace_ext4_readpage(page);
324446c7f254STao Ma 
324546c7f254STao Ma 	if (ext4_has_inline_data(inode))
324646c7f254STao Ma 		ret = ext4_readpage_inline(inode, page);
324746c7f254STao Ma 
324846c7f254STao Ma 	if (ret == -EAGAIN)
3249a07f624bSMatthew Wilcox (Oracle) 		return ext4_mpage_readpages(inode, NULL, page);
325046c7f254STao Ma 
325146c7f254STao Ma 	return ret;
3252ac27a0ecSDave Kleikamp }
3253ac27a0ecSDave Kleikamp 
32546311f91fSMatthew Wilcox (Oracle) static void ext4_readahead(struct readahead_control *rac)
3255ac27a0ecSDave Kleikamp {
32566311f91fSMatthew Wilcox (Oracle) 	struct inode *inode = rac->mapping->host;
325746c7f254STao Ma 
32586311f91fSMatthew Wilcox (Oracle) 	/* If the file has inline data, no need to do readahead. */
325946c7f254STao Ma 	if (ext4_has_inline_data(inode))
32606311f91fSMatthew Wilcox (Oracle) 		return;
326146c7f254STao Ma 
3262a07f624bSMatthew Wilcox (Oracle) 	ext4_mpage_readpages(inode, rac, NULL);
3263ac27a0ecSDave Kleikamp }
3264ac27a0ecSDave Kleikamp 
3265d47992f8SLukas Czerner static void ext4_invalidatepage(struct page *page, unsigned int offset,
3266d47992f8SLukas Czerner 				unsigned int length)
3267ac27a0ecSDave Kleikamp {
3268ca99fdd2SLukas Czerner 	trace_ext4_invalidatepage(page, offset, length);
32690562e0baSJiaying Zhang 
32704520fb3cSJan Kara 	/* No journalling happens on data buffers when this function is used */
32714520fb3cSJan Kara 	WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
32724520fb3cSJan Kara 
3273ca99fdd2SLukas Czerner 	block_invalidatepage(page, offset, length);
32744520fb3cSJan Kara }
32754520fb3cSJan Kara 
327653e87268SJan Kara static int __ext4_journalled_invalidatepage(struct page *page,
3277ca99fdd2SLukas Czerner 					    unsigned int offset,
3278ca99fdd2SLukas Czerner 					    unsigned int length)
32794520fb3cSJan Kara {
32804520fb3cSJan Kara 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
32814520fb3cSJan Kara 
3282ca99fdd2SLukas Czerner 	trace_ext4_journalled_invalidatepage(page, offset, length);
32834520fb3cSJan Kara 
3284744692dcSJiaying Zhang 	/*
3285ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
3286ac27a0ecSDave Kleikamp 	 */
328709cbfeafSKirill A. Shutemov 	if (offset == 0 && length == PAGE_SIZE)
3288ac27a0ecSDave Kleikamp 		ClearPageChecked(page);
3289ac27a0ecSDave Kleikamp 
3290ca99fdd2SLukas Czerner 	return jbd2_journal_invalidatepage(journal, page, offset, length);
329153e87268SJan Kara }
329253e87268SJan Kara 
329353e87268SJan Kara /* Wrapper for aops... */
329453e87268SJan Kara static void ext4_journalled_invalidatepage(struct page *page,
3295d47992f8SLukas Czerner 					   unsigned int offset,
3296d47992f8SLukas Czerner 					   unsigned int length)
329753e87268SJan Kara {
3298ca99fdd2SLukas Czerner 	WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3299ac27a0ecSDave Kleikamp }
3300ac27a0ecSDave Kleikamp 
3301617ba13bSMingming Cao static int ext4_releasepage(struct page *page, gfp_t wait)
3302ac27a0ecSDave Kleikamp {
3303617ba13bSMingming Cao 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3304ac27a0ecSDave Kleikamp 
33050562e0baSJiaying Zhang 	trace_ext4_releasepage(page);
33060562e0baSJiaying Zhang 
3307e1c36595SJan Kara 	/* Page has dirty journalled data -> cannot release */
3308e1c36595SJan Kara 	if (PageChecked(page))
3309ac27a0ecSDave Kleikamp 		return 0;
33100390131bSFrank Mayhar 	if (journal)
3311529a781eSzhangyi (F) 		return jbd2_journal_try_to_free_buffers(journal, page);
33120390131bSFrank Mayhar 	else
33130390131bSFrank Mayhar 		return try_to_free_buffers(page);
3314ac27a0ecSDave Kleikamp }
3315ac27a0ecSDave Kleikamp 
3316b8a6176cSJan Kara static bool ext4_inode_datasync_dirty(struct inode *inode)
3317b8a6176cSJan Kara {
3318b8a6176cSJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3319b8a6176cSJan Kara 
3320aa75f4d3SHarshad Shirwadkar 	if (journal) {
3321aa75f4d3SHarshad Shirwadkar 		if (jbd2_transaction_committed(journal,
3322aa75f4d3SHarshad Shirwadkar 			EXT4_I(inode)->i_datasync_tid))
3323d0520df7SAndrea Righi 			return false;
3324d0520df7SAndrea Righi 		if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
33251ceecb53SHarshad Shirwadkar 			return !list_empty(&EXT4_I(inode)->i_fc_list);
3326d0520df7SAndrea Righi 		return true;
3327aa75f4d3SHarshad Shirwadkar 	}
3328aa75f4d3SHarshad Shirwadkar 
3329b8a6176cSJan Kara 	/* Any metadata buffers to write? */
3330b8a6176cSJan Kara 	if (!list_empty(&inode->i_mapping->private_list))
3331b8a6176cSJan Kara 		return true;
3332b8a6176cSJan Kara 	return inode->i_state & I_DIRTY_DATASYNC;
3333b8a6176cSJan Kara }
3334b8a6176cSJan Kara 
3335c8fdfe29SMatthew Bobrowski static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3336c8fdfe29SMatthew Bobrowski 			   struct ext4_map_blocks *map, loff_t offset,
3337c8fdfe29SMatthew Bobrowski 			   loff_t length)
3338364443cbSJan Kara {
3339c8fdfe29SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3340c8fdfe29SMatthew Bobrowski 
3341c8fdfe29SMatthew Bobrowski 	/*
3342c8fdfe29SMatthew Bobrowski 	 * Writes that span EOF might trigger an I/O size update on completion,
3343c8fdfe29SMatthew Bobrowski 	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3344c8fdfe29SMatthew Bobrowski 	 * there is no other metadata changes being made or are pending.
3345c8fdfe29SMatthew Bobrowski 	 */
3346c8fdfe29SMatthew Bobrowski 	iomap->flags = 0;
3347c8fdfe29SMatthew Bobrowski 	if (ext4_inode_datasync_dirty(inode) ||
3348c8fdfe29SMatthew Bobrowski 	    offset + length > i_size_read(inode))
3349c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_DIRTY;
3350c8fdfe29SMatthew Bobrowski 
3351c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_NEW)
3352c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_NEW;
3353c8fdfe29SMatthew Bobrowski 
3354c8fdfe29SMatthew Bobrowski 	iomap->bdev = inode->i_sb->s_bdev;
3355c8fdfe29SMatthew Bobrowski 	iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3356c8fdfe29SMatthew Bobrowski 	iomap->offset = (u64) map->m_lblk << blkbits;
3357c8fdfe29SMatthew Bobrowski 	iomap->length = (u64) map->m_len << blkbits;
3358c8fdfe29SMatthew Bobrowski 
33596386722aSRitesh Harjani 	if ((map->m_flags & EXT4_MAP_MAPPED) &&
33606386722aSRitesh Harjani 	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
33616386722aSRitesh Harjani 		iomap->flags |= IOMAP_F_MERGED;
33626386722aSRitesh Harjani 
3363c8fdfe29SMatthew Bobrowski 	/*
3364c8fdfe29SMatthew Bobrowski 	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3365c8fdfe29SMatthew Bobrowski 	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3366c8fdfe29SMatthew Bobrowski 	 * set. In order for any allocated unwritten extents to be converted
3367c8fdfe29SMatthew Bobrowski 	 * into written extents correctly within the ->end_io() handler, we
3368c8fdfe29SMatthew Bobrowski 	 * need to ensure that the iomap->type is set appropriately. Hence, the
3369c8fdfe29SMatthew Bobrowski 	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3370c8fdfe29SMatthew Bobrowski 	 * been set first.
3371c8fdfe29SMatthew Bobrowski 	 */
3372c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3373c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_UNWRITTEN;
3374c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3375c8fdfe29SMatthew Bobrowski 	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3376c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_MAPPED;
3377c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3378c8fdfe29SMatthew Bobrowski 	} else {
3379c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_HOLE;
3380c8fdfe29SMatthew Bobrowski 		iomap->addr = IOMAP_NULL_ADDR;
3381c8fdfe29SMatthew Bobrowski 	}
3382c8fdfe29SMatthew Bobrowski }
3383c8fdfe29SMatthew Bobrowski 
3384f063db5eSMatthew Bobrowski static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3385f063db5eSMatthew Bobrowski 			    unsigned int flags)
3386f063db5eSMatthew Bobrowski {
3387f063db5eSMatthew Bobrowski 	handle_t *handle;
3388378f32baSMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3389378f32baSMatthew Bobrowski 	int ret, dio_credits, m_flags = 0, retries = 0;
3390f063db5eSMatthew Bobrowski 
3391f063db5eSMatthew Bobrowski 	/*
3392f063db5eSMatthew Bobrowski 	 * Trim the mapping request to the maximum value that we can map at
3393f063db5eSMatthew Bobrowski 	 * once for direct I/O.
3394f063db5eSMatthew Bobrowski 	 */
3395f063db5eSMatthew Bobrowski 	if (map->m_len > DIO_MAX_BLOCKS)
3396f063db5eSMatthew Bobrowski 		map->m_len = DIO_MAX_BLOCKS;
3397f063db5eSMatthew Bobrowski 	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3398f063db5eSMatthew Bobrowski 
3399f063db5eSMatthew Bobrowski retry:
3400f063db5eSMatthew Bobrowski 	/*
3401f063db5eSMatthew Bobrowski 	 * Either we allocate blocks and then don't get an unwritten extent, so
3402f063db5eSMatthew Bobrowski 	 * in that case we have reserved enough credits. Or, the blocks are
3403f063db5eSMatthew Bobrowski 	 * already allocated and unwritten. In that case, the extent conversion
3404f063db5eSMatthew Bobrowski 	 * fits into the credits as well.
3405f063db5eSMatthew Bobrowski 	 */
3406f063db5eSMatthew Bobrowski 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3407f063db5eSMatthew Bobrowski 	if (IS_ERR(handle))
3408f063db5eSMatthew Bobrowski 		return PTR_ERR(handle);
3409f063db5eSMatthew Bobrowski 
3410378f32baSMatthew Bobrowski 	/*
3411378f32baSMatthew Bobrowski 	 * DAX and direct I/O are the only two operations that are currently
3412378f32baSMatthew Bobrowski 	 * supported with IOMAP_WRITE.
3413378f32baSMatthew Bobrowski 	 */
3414378f32baSMatthew Bobrowski 	WARN_ON(!IS_DAX(inode) && !(flags & IOMAP_DIRECT));
3415378f32baSMatthew Bobrowski 	if (IS_DAX(inode))
3416378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3417378f32baSMatthew Bobrowski 	/*
3418378f32baSMatthew Bobrowski 	 * We use i_size instead of i_disksize here because delalloc writeback
3419378f32baSMatthew Bobrowski 	 * can complete at any point during the I/O and subsequently push the
3420378f32baSMatthew Bobrowski 	 * i_disksize out to i_size. This could be beyond where direct I/O is
3421378f32baSMatthew Bobrowski 	 * happening and thus expose allocated blocks to direct I/O reads.
3422378f32baSMatthew Bobrowski 	 */
3423d0b040f5SJan Kara 	else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3424378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE;
3425378f32baSMatthew Bobrowski 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3426378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3427378f32baSMatthew Bobrowski 
3428378f32baSMatthew Bobrowski 	ret = ext4_map_blocks(handle, inode, map, m_flags);
3429378f32baSMatthew Bobrowski 
3430378f32baSMatthew Bobrowski 	/*
3431378f32baSMatthew Bobrowski 	 * We cannot fill holes in indirect tree based inodes as that could
3432378f32baSMatthew Bobrowski 	 * expose stale data in the case of a crash. Use the magic error code
3433378f32baSMatthew Bobrowski 	 * to fallback to buffered I/O.
3434378f32baSMatthew Bobrowski 	 */
3435378f32baSMatthew Bobrowski 	if (!m_flags && !ret)
3436378f32baSMatthew Bobrowski 		ret = -ENOTBLK;
3437f063db5eSMatthew Bobrowski 
3438f063db5eSMatthew Bobrowski 	ext4_journal_stop(handle);
3439f063db5eSMatthew Bobrowski 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3440f063db5eSMatthew Bobrowski 		goto retry;
3441f063db5eSMatthew Bobrowski 
3442f063db5eSMatthew Bobrowski 	return ret;
3443f063db5eSMatthew Bobrowski }
3444f063db5eSMatthew Bobrowski 
3445f063db5eSMatthew Bobrowski 
3446364443cbSJan Kara static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3447c039b997SGoldwyn Rodrigues 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3448364443cbSJan Kara {
3449364443cbSJan Kara 	int ret;
345009edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
345109edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3452364443cbSJan Kara 
3453bcd8e91fSTheodore Ts'o 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3454bcd8e91fSTheodore Ts'o 		return -EINVAL;
34557046ae35SAndreas Gruenbacher 
3456364443cbSJan Kara 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3457364443cbSJan Kara 		return -ERANGE;
3458364443cbSJan Kara 
345909edf4d3SMatthew Bobrowski 	/*
346009edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical blocks respectively.
346109edf4d3SMatthew Bobrowski 	 */
346209edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
346309edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
346409edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3465364443cbSJan Kara 
34669faac62dSRitesh Harjani 	if (flags & IOMAP_WRITE) {
34679faac62dSRitesh Harjani 		/*
34689faac62dSRitesh Harjani 		 * We check here if the blocks are already allocated, then we
34699faac62dSRitesh Harjani 		 * don't need to start a journal txn and we can directly return
34709faac62dSRitesh Harjani 		 * the mapping information. This could boost performance
34719faac62dSRitesh Harjani 		 * especially in multi-threaded overwrite requests.
34729faac62dSRitesh Harjani 		 */
34739faac62dSRitesh Harjani 		if (offset + length <= i_size_read(inode)) {
3474545052e9SChristoph Hellwig 			ret = ext4_map_blocks(NULL, inode, &map, 0);
34759faac62dSRitesh Harjani 			if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
34769faac62dSRitesh Harjani 				goto out;
34779faac62dSRitesh Harjani 		}
34789faac62dSRitesh Harjani 		ret = ext4_iomap_alloc(inode, &map, flags);
34799faac62dSRitesh Harjani 	} else {
34809faac62dSRitesh Harjani 		ret = ext4_map_blocks(NULL, inode, &map, 0);
34819faac62dSRitesh Harjani 	}
3482f063db5eSMatthew Bobrowski 
3483545052e9SChristoph Hellwig 	if (ret < 0)
3484545052e9SChristoph Hellwig 		return ret;
34859faac62dSRitesh Harjani out:
3486c8fdfe29SMatthew Bobrowski 	ext4_set_iomap(inode, iomap, &map, offset, length);
3487545052e9SChristoph Hellwig 
3488364443cbSJan Kara 	return 0;
3489364443cbSJan Kara }
3490364443cbSJan Kara 
34918cd115bdSJan Kara static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
34928cd115bdSJan Kara 		loff_t length, unsigned flags, struct iomap *iomap,
34938cd115bdSJan Kara 		struct iomap *srcmap)
34948cd115bdSJan Kara {
34958cd115bdSJan Kara 	int ret;
34968cd115bdSJan Kara 
34978cd115bdSJan Kara 	/*
34988cd115bdSJan Kara 	 * Even for writes we don't need to allocate blocks, so just pretend
34998cd115bdSJan Kara 	 * we are reading to save overhead of starting a transaction.
35008cd115bdSJan Kara 	 */
35018cd115bdSJan Kara 	flags &= ~IOMAP_WRITE;
35028cd115bdSJan Kara 	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
35038cd115bdSJan Kara 	WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
35048cd115bdSJan Kara 	return ret;
35058cd115bdSJan Kara }
35068cd115bdSJan Kara 
3507776722e8SJan Kara static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3508776722e8SJan Kara 			  ssize_t written, unsigned flags, struct iomap *iomap)
3509776722e8SJan Kara {
3510378f32baSMatthew Bobrowski 	/*
3511378f32baSMatthew Bobrowski 	 * Check to see whether an error occurred while writing out the data to
3512378f32baSMatthew Bobrowski 	 * the allocated blocks. If so, return the magic error code so that we
3513378f32baSMatthew Bobrowski 	 * fallback to buffered I/O and attempt to complete the remainder of
3514378f32baSMatthew Bobrowski 	 * the I/O. Any blocks that may have been allocated in preparation for
3515378f32baSMatthew Bobrowski 	 * the direct I/O will be reused during buffered I/O.
3516378f32baSMatthew Bobrowski 	 */
3517378f32baSMatthew Bobrowski 	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3518378f32baSMatthew Bobrowski 		return -ENOTBLK;
3519378f32baSMatthew Bobrowski 
3520776722e8SJan Kara 	return 0;
3521776722e8SJan Kara }
3522776722e8SJan Kara 
35238ff6daa1SChristoph Hellwig const struct iomap_ops ext4_iomap_ops = {
3524364443cbSJan Kara 	.iomap_begin		= ext4_iomap_begin,
3525776722e8SJan Kara 	.iomap_end		= ext4_iomap_end,
3526364443cbSJan Kara };
3527364443cbSJan Kara 
35288cd115bdSJan Kara const struct iomap_ops ext4_iomap_overwrite_ops = {
35298cd115bdSJan Kara 	.iomap_begin		= ext4_iomap_overwrite_begin,
35308cd115bdSJan Kara 	.iomap_end		= ext4_iomap_end,
35318cd115bdSJan Kara };
35328cd115bdSJan Kara 
353309edf4d3SMatthew Bobrowski static bool ext4_iomap_is_delalloc(struct inode *inode,
353409edf4d3SMatthew Bobrowski 				   struct ext4_map_blocks *map)
353509edf4d3SMatthew Bobrowski {
353609edf4d3SMatthew Bobrowski 	struct extent_status es;
353709edf4d3SMatthew Bobrowski 	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
353809edf4d3SMatthew Bobrowski 
353909edf4d3SMatthew Bobrowski 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
354009edf4d3SMatthew Bobrowski 				  map->m_lblk, end, &es);
354109edf4d3SMatthew Bobrowski 
354209edf4d3SMatthew Bobrowski 	if (!es.es_len || es.es_lblk > end)
354309edf4d3SMatthew Bobrowski 		return false;
354409edf4d3SMatthew Bobrowski 
354509edf4d3SMatthew Bobrowski 	if (es.es_lblk > map->m_lblk) {
354609edf4d3SMatthew Bobrowski 		map->m_len = es.es_lblk - map->m_lblk;
354709edf4d3SMatthew Bobrowski 		return false;
354809edf4d3SMatthew Bobrowski 	}
354909edf4d3SMatthew Bobrowski 
355009edf4d3SMatthew Bobrowski 	offset = map->m_lblk - es.es_lblk;
355109edf4d3SMatthew Bobrowski 	map->m_len = es.es_len - offset;
355209edf4d3SMatthew Bobrowski 
355309edf4d3SMatthew Bobrowski 	return true;
355409edf4d3SMatthew Bobrowski }
355509edf4d3SMatthew Bobrowski 
355609edf4d3SMatthew Bobrowski static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
355709edf4d3SMatthew Bobrowski 				   loff_t length, unsigned int flags,
355809edf4d3SMatthew Bobrowski 				   struct iomap *iomap, struct iomap *srcmap)
355909edf4d3SMatthew Bobrowski {
356009edf4d3SMatthew Bobrowski 	int ret;
356109edf4d3SMatthew Bobrowski 	bool delalloc = false;
356209edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
356309edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
356409edf4d3SMatthew Bobrowski 
356509edf4d3SMatthew Bobrowski 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
356609edf4d3SMatthew Bobrowski 		return -EINVAL;
356709edf4d3SMatthew Bobrowski 
35687cb476f8SJan Kara 	if (ext4_has_inline_data(inode)) {
35697cb476f8SJan Kara 		ret = ext4_inline_data_iomap(inode, iomap);
3570ba5843f5SJan Kara 		if (ret != -EAGAIN) {
3571ed923b57SMatthew Wilcox 			if (ret == 0 && offset >= iomap->length)
3572ba5843f5SJan Kara 				ret = -ENOENT;
3573ba5843f5SJan Kara 			return ret;
3574ba5843f5SJan Kara 		}
3575ba5843f5SJan Kara 	}
357612735f88SJan Kara 
357709edf4d3SMatthew Bobrowski 	/*
357809edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical block respectively.
357909edf4d3SMatthew Bobrowski 	 */
358009edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
358109edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
358209edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
358312735f88SJan Kara 
3584b2c57642SRitesh Harjani 	/*
3585b2c57642SRitesh Harjani 	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3586b2c57642SRitesh Harjani 	 * So handle it here itself instead of querying ext4_map_blocks().
3587b2c57642SRitesh Harjani 	 * Since ext4_map_blocks() will warn about it and will return
3588b2c57642SRitesh Harjani 	 * -EIO error.
3589b2c57642SRitesh Harjani 	 */
3590b2c57642SRitesh Harjani 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3591b2c57642SRitesh Harjani 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3592b2c57642SRitesh Harjani 
3593b2c57642SRitesh Harjani 		if (offset >= sbi->s_bitmap_maxbytes) {
3594b2c57642SRitesh Harjani 			map.m_flags = 0;
3595b2c57642SRitesh Harjani 			goto set_iomap;
3596b2c57642SRitesh Harjani 		}
3597b2c57642SRitesh Harjani 	}
3598b2c57642SRitesh Harjani 
359912735f88SJan Kara 	ret = ext4_map_blocks(NULL, inode, &map, 0);
3600ba5843f5SJan Kara 	if (ret < 0)
3601ba5843f5SJan Kara 		return ret;
3602914f82a3SJan Kara 	if (ret == 0)
360309edf4d3SMatthew Bobrowski 		delalloc = ext4_iomap_is_delalloc(inode, &map);
360409edf4d3SMatthew Bobrowski 
3605b2c57642SRitesh Harjani set_iomap:
360609edf4d3SMatthew Bobrowski 	ext4_set_iomap(inode, iomap, &map, offset, length);
360709edf4d3SMatthew Bobrowski 	if (delalloc && iomap->type == IOMAP_HOLE)
360809edf4d3SMatthew Bobrowski 		iomap->type = IOMAP_DELALLOC;
360909edf4d3SMatthew Bobrowski 
361009edf4d3SMatthew Bobrowski 	return 0;
3611914f82a3SJan Kara }
3612914f82a3SJan Kara 
361309edf4d3SMatthew Bobrowski const struct iomap_ops ext4_iomap_report_ops = {
361409edf4d3SMatthew Bobrowski 	.iomap_begin = ext4_iomap_begin_report,
361509edf4d3SMatthew Bobrowski };
36164c0425ffSMingming Cao 
3617ac27a0ecSDave Kleikamp /*
3618617ba13bSMingming Cao  * Pages can be marked dirty completely asynchronously from ext4's journalling
3619ac27a0ecSDave Kleikamp  * activity.  By filemap_sync_pte(), try_to_unmap_one(), etc.  We cannot do
3620ac27a0ecSDave Kleikamp  * much here because ->set_page_dirty is called under VFS locks.  The page is
3621ac27a0ecSDave Kleikamp  * not necessarily locked.
3622ac27a0ecSDave Kleikamp  *
3623ac27a0ecSDave Kleikamp  * We cannot just dirty the page and leave attached buffers clean, because the
3624ac27a0ecSDave Kleikamp  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3625ac27a0ecSDave Kleikamp  * or jbddirty because all the journalling code will explode.
3626ac27a0ecSDave Kleikamp  *
3627ac27a0ecSDave Kleikamp  * So what we do is to mark the page "pending dirty" and next time writepage
3628ac27a0ecSDave Kleikamp  * is called, propagate that into the buffers appropriately.
3629ac27a0ecSDave Kleikamp  */
3630617ba13bSMingming Cao static int ext4_journalled_set_page_dirty(struct page *page)
3631ac27a0ecSDave Kleikamp {
3632ac27a0ecSDave Kleikamp 	SetPageChecked(page);
3633ac27a0ecSDave Kleikamp 	return __set_page_dirty_nobuffers(page);
3634ac27a0ecSDave Kleikamp }
3635ac27a0ecSDave Kleikamp 
36366dcc693bSJan Kara static int ext4_set_page_dirty(struct page *page)
36376dcc693bSJan Kara {
36386dcc693bSJan Kara 	WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
36396dcc693bSJan Kara 	WARN_ON_ONCE(!page_has_buffers(page));
36406dcc693bSJan Kara 	return __set_page_dirty_buffers(page);
36416dcc693bSJan Kara }
36426dcc693bSJan Kara 
36430e6895baSRitesh Harjani static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
36440e6895baSRitesh Harjani 				    struct file *file, sector_t *span)
36450e6895baSRitesh Harjani {
36460e6895baSRitesh Harjani 	return iomap_swapfile_activate(sis, file, span,
36470e6895baSRitesh Harjani 				       &ext4_iomap_report_ops);
36480e6895baSRitesh Harjani }
36490e6895baSRitesh Harjani 
365074d553aaSTheodore Ts'o static const struct address_space_operations ext4_aops = {
3651617ba13bSMingming Cao 	.readpage		= ext4_readpage,
36526311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
365343ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
365420970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3655bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
365674d553aaSTheodore Ts'o 	.write_end		= ext4_write_end,
36576dcc693bSJan Kara 	.set_page_dirty		= ext4_set_page_dirty,
3658617ba13bSMingming Cao 	.bmap			= ext4_bmap,
3659617ba13bSMingming Cao 	.invalidatepage		= ext4_invalidatepage,
3660617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
3661378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
3662ac27a0ecSDave Kleikamp 	.migratepage		= buffer_migrate_page,
36638ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3664aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36650e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3666ac27a0ecSDave Kleikamp };
3667ac27a0ecSDave Kleikamp 
3668617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
3669617ba13bSMingming Cao 	.readpage		= ext4_readpage,
36706311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
367143ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
367220970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3673bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
3674bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
3675617ba13bSMingming Cao 	.set_page_dirty		= ext4_journalled_set_page_dirty,
3676617ba13bSMingming Cao 	.bmap			= ext4_bmap,
36774520fb3cSJan Kara 	.invalidatepage		= ext4_journalled_invalidatepage,
3678617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
3679378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
36808ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3681aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
36820e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
3683ac27a0ecSDave Kleikamp };
3684ac27a0ecSDave Kleikamp 
368564769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
368664769240SAlex Tomas 	.readpage		= ext4_readpage,
36876311f91fSMatthew Wilcox (Oracle) 	.readahead		= ext4_readahead,
368843ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
368920970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
369064769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
369164769240SAlex Tomas 	.write_end		= ext4_da_write_end,
36926dcc693bSJan Kara 	.set_page_dirty		= ext4_set_page_dirty,
369364769240SAlex Tomas 	.bmap			= ext4_bmap,
36948fcc3a58SEric Whitney 	.invalidatepage		= ext4_invalidatepage,
369564769240SAlex Tomas 	.releasepage		= ext4_releasepage,
3696378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
369764769240SAlex Tomas 	.migratepage		= buffer_migrate_page,
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,
370164769240SAlex Tomas };
370264769240SAlex Tomas 
37035f0663bbSDan Williams static const struct address_space_operations ext4_dax_aops = {
37045f0663bbSDan Williams 	.writepages		= ext4_dax_writepages,
37055f0663bbSDan Williams 	.direct_IO		= noop_direct_IO,
3706b82a96c9SMatthew Wilcox (Oracle) 	.set_page_dirty		= __set_page_dirty_no_writeback,
370794dbb631SToshi Kani 	.bmap			= ext4_bmap,
37085f0663bbSDan Williams 	.invalidatepage		= noop_invalidatepage,
37090e6895baSRitesh Harjani 	.swap_activate		= ext4_iomap_swap_activate,
37105f0663bbSDan Williams };
37115f0663bbSDan Williams 
3712617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
3713ac27a0ecSDave Kleikamp {
37143d2b1582SLukas Czerner 	switch (ext4_inode_journal_mode(inode)) {
37153d2b1582SLukas Czerner 	case EXT4_INODE_ORDERED_DATA_MODE:
37163d2b1582SLukas Czerner 	case EXT4_INODE_WRITEBACK_DATA_MODE:
37173d2b1582SLukas Czerner 		break;
37183d2b1582SLukas Czerner 	case EXT4_INODE_JOURNAL_DATA_MODE:
3719617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
372074d553aaSTheodore Ts'o 		return;
37213d2b1582SLukas Czerner 	default:
37223d2b1582SLukas Czerner 		BUG();
37233d2b1582SLukas Czerner 	}
37245f0663bbSDan Williams 	if (IS_DAX(inode))
37255f0663bbSDan Williams 		inode->i_mapping->a_ops = &ext4_dax_aops;
37265f0663bbSDan Williams 	else if (test_opt(inode->i_sb, DELALLOC))
372774d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_da_aops;
372874d553aaSTheodore Ts'o 	else
372974d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_aops;
3730ac27a0ecSDave Kleikamp }
3731ac27a0ecSDave Kleikamp 
3732923ae0ffSRoss Zwisler static int __ext4_block_zero_page_range(handle_t *handle,
3733d863dc36SLukas Czerner 		struct address_space *mapping, loff_t from, loff_t length)
3734d863dc36SLukas Czerner {
373509cbfeafSKirill A. Shutemov 	ext4_fsblk_t index = from >> PAGE_SHIFT;
373609cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3737923ae0ffSRoss Zwisler 	unsigned blocksize, pos;
3738d863dc36SLukas Czerner 	ext4_lblk_t iblock;
3739d863dc36SLukas Czerner 	struct inode *inode = mapping->host;
3740d863dc36SLukas Czerner 	struct buffer_head *bh;
3741d863dc36SLukas Czerner 	struct page *page;
3742d863dc36SLukas Czerner 	int err = 0;
3743d863dc36SLukas Czerner 
374409cbfeafSKirill A. Shutemov 	page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3745c62d2555SMichal Hocko 				   mapping_gfp_constraint(mapping, ~__GFP_FS));
3746d863dc36SLukas Czerner 	if (!page)
3747d863dc36SLukas Czerner 		return -ENOMEM;
3748d863dc36SLukas Czerner 
3749d863dc36SLukas Czerner 	blocksize = inode->i_sb->s_blocksize;
3750d863dc36SLukas Czerner 
375109cbfeafSKirill A. Shutemov 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3752d863dc36SLukas Czerner 
3753d863dc36SLukas Czerner 	if (!page_has_buffers(page))
3754d863dc36SLukas Czerner 		create_empty_buffers(page, blocksize, 0);
3755d863dc36SLukas Czerner 
3756d863dc36SLukas Czerner 	/* Find the buffer that contains "offset" */
3757d863dc36SLukas Czerner 	bh = page_buffers(page);
3758d863dc36SLukas Czerner 	pos = blocksize;
3759d863dc36SLukas Czerner 	while (offset >= pos) {
3760d863dc36SLukas Czerner 		bh = bh->b_this_page;
3761d863dc36SLukas Czerner 		iblock++;
3762d863dc36SLukas Czerner 		pos += blocksize;
3763d863dc36SLukas Czerner 	}
3764d863dc36SLukas Czerner 	if (buffer_freed(bh)) {
3765d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "freed: skip");
3766d863dc36SLukas Czerner 		goto unlock;
3767d863dc36SLukas Czerner 	}
3768d863dc36SLukas Czerner 	if (!buffer_mapped(bh)) {
3769d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "unmapped");
3770d863dc36SLukas Czerner 		ext4_get_block(inode, iblock, bh, 0);
3771d863dc36SLukas Czerner 		/* unmapped? It's a hole - nothing to do */
3772d863dc36SLukas Czerner 		if (!buffer_mapped(bh)) {
3773d863dc36SLukas Czerner 			BUFFER_TRACE(bh, "still unmapped");
3774d863dc36SLukas Czerner 			goto unlock;
3775d863dc36SLukas Czerner 		}
3776d863dc36SLukas Czerner 	}
3777d863dc36SLukas Czerner 
3778d863dc36SLukas Czerner 	/* Ok, it's mapped. Make sure it's up-to-date */
3779d863dc36SLukas Czerner 	if (PageUptodate(page))
3780d863dc36SLukas Czerner 		set_buffer_uptodate(bh);
3781d863dc36SLukas Czerner 
3782d863dc36SLukas Czerner 	if (!buffer_uptodate(bh)) {
37832d069c08Szhangyi (F) 		err = ext4_read_bh_lock(bh, 0, true);
37842d069c08Szhangyi (F) 		if (err)
3785d863dc36SLukas Czerner 			goto unlock;
37864f74d15fSEric Biggers 		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3787c9c7429cSMichael Halcrow 			/* We expect the key to be set. */
3788a7550b30SJaegeuk Kim 			BUG_ON(!fscrypt_has_encryption_key(inode));
3789834f1565SEric Biggers 			err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3790834f1565SEric Biggers 							       bh_offset(bh));
3791834f1565SEric Biggers 			if (err) {
3792834f1565SEric Biggers 				clear_buffer_uptodate(bh);
3793834f1565SEric Biggers 				goto unlock;
3794834f1565SEric Biggers 			}
3795c9c7429cSMichael Halcrow 		}
3796d863dc36SLukas Czerner 	}
3797d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3798d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "get write access");
3799d863dc36SLukas Czerner 		err = ext4_journal_get_write_access(handle, bh);
3800d863dc36SLukas Czerner 		if (err)
3801d863dc36SLukas Czerner 			goto unlock;
3802d863dc36SLukas Czerner 	}
3803d863dc36SLukas Czerner 	zero_user(page, offset, length);
3804d863dc36SLukas Czerner 	BUFFER_TRACE(bh, "zeroed end of block");
3805d863dc36SLukas Czerner 
3806d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3807d863dc36SLukas Czerner 		err = ext4_handle_dirty_metadata(handle, inode, bh);
38080713ed0cSLukas Czerner 	} else {
3809353eefd3Sjon ernst 		err = 0;
3810d863dc36SLukas Czerner 		mark_buffer_dirty(bh);
38113957ef53SJan Kara 		if (ext4_should_order_data(inode))
381273131fbbSRoss Zwisler 			err = ext4_jbd2_inode_add_write(handle, inode, from,
381373131fbbSRoss Zwisler 					length);
38140713ed0cSLukas Czerner 	}
3815d863dc36SLukas Czerner 
3816d863dc36SLukas Czerner unlock:
3817d863dc36SLukas Czerner 	unlock_page(page);
381809cbfeafSKirill A. Shutemov 	put_page(page);
3819d863dc36SLukas Czerner 	return err;
3820d863dc36SLukas Czerner }
3821d863dc36SLukas Czerner 
382294350ab5SMatthew Wilcox /*
3823923ae0ffSRoss Zwisler  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3824923ae0ffSRoss Zwisler  * starting from file offset 'from'.  The range to be zero'd must
3825923ae0ffSRoss Zwisler  * be contained with in one block.  If the specified range exceeds
3826923ae0ffSRoss Zwisler  * the end of the block it will be shortened to end of the block
38273088e5a5SBhaskar Chowdhury  * that corresponds to 'from'
3828923ae0ffSRoss Zwisler  */
3829923ae0ffSRoss Zwisler static int ext4_block_zero_page_range(handle_t *handle,
3830923ae0ffSRoss Zwisler 		struct address_space *mapping, loff_t from, loff_t length)
3831923ae0ffSRoss Zwisler {
3832923ae0ffSRoss Zwisler 	struct inode *inode = mapping->host;
383309cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3834923ae0ffSRoss Zwisler 	unsigned blocksize = inode->i_sb->s_blocksize;
3835923ae0ffSRoss Zwisler 	unsigned max = blocksize - (offset & (blocksize - 1));
3836923ae0ffSRoss Zwisler 
3837923ae0ffSRoss Zwisler 	/*
3838923ae0ffSRoss Zwisler 	 * correct length if it does not fall between
3839923ae0ffSRoss Zwisler 	 * 'from' and the end of the block
3840923ae0ffSRoss Zwisler 	 */
3841923ae0ffSRoss Zwisler 	if (length > max || length < 0)
3842923ae0ffSRoss Zwisler 		length = max;
3843923ae0ffSRoss Zwisler 
384447e69351SJan Kara 	if (IS_DAX(inode)) {
384547e69351SJan Kara 		return iomap_zero_range(inode, from, length, NULL,
384647e69351SJan Kara 					&ext4_iomap_ops);
384747e69351SJan Kara 	}
3848923ae0ffSRoss Zwisler 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3849923ae0ffSRoss Zwisler }
3850923ae0ffSRoss Zwisler 
3851923ae0ffSRoss Zwisler /*
385294350ab5SMatthew Wilcox  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
385394350ab5SMatthew Wilcox  * up to the end of the block which corresponds to `from'.
385494350ab5SMatthew Wilcox  * This required during truncate. We need to physically zero the tail end
385594350ab5SMatthew Wilcox  * of that block so it doesn't yield old data if the file is later grown.
385694350ab5SMatthew Wilcox  */
3857c197855eSStephen Hemminger static int ext4_block_truncate_page(handle_t *handle,
385894350ab5SMatthew Wilcox 		struct address_space *mapping, loff_t from)
385994350ab5SMatthew Wilcox {
386009cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
386194350ab5SMatthew Wilcox 	unsigned length;
386294350ab5SMatthew Wilcox 	unsigned blocksize;
386394350ab5SMatthew Wilcox 	struct inode *inode = mapping->host;
386494350ab5SMatthew Wilcox 
38650d06863fSTheodore Ts'o 	/* If we are processing an encrypted inode during orphan list handling */
3866592ddec7SChandan Rajendra 	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
38670d06863fSTheodore Ts'o 		return 0;
38680d06863fSTheodore Ts'o 
386994350ab5SMatthew Wilcox 	blocksize = inode->i_sb->s_blocksize;
387094350ab5SMatthew Wilcox 	length = blocksize - (offset & (blocksize - 1));
387194350ab5SMatthew Wilcox 
387294350ab5SMatthew Wilcox 	return ext4_block_zero_page_range(handle, mapping, from, length);
387394350ab5SMatthew Wilcox }
387494350ab5SMatthew Wilcox 
3875a87dd18cSLukas Czerner int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3876a87dd18cSLukas Czerner 			     loff_t lstart, loff_t length)
3877a87dd18cSLukas Czerner {
3878a87dd18cSLukas Czerner 	struct super_block *sb = inode->i_sb;
3879a87dd18cSLukas Czerner 	struct address_space *mapping = inode->i_mapping;
3880e1be3a92SLukas Czerner 	unsigned partial_start, partial_end;
3881a87dd18cSLukas Czerner 	ext4_fsblk_t start, end;
3882a87dd18cSLukas Czerner 	loff_t byte_end = (lstart + length - 1);
3883a87dd18cSLukas Czerner 	int err = 0;
3884a87dd18cSLukas Czerner 
3885e1be3a92SLukas Czerner 	partial_start = lstart & (sb->s_blocksize - 1);
3886e1be3a92SLukas Czerner 	partial_end = byte_end & (sb->s_blocksize - 1);
3887e1be3a92SLukas Czerner 
3888a87dd18cSLukas Czerner 	start = lstart >> sb->s_blocksize_bits;
3889a87dd18cSLukas Czerner 	end = byte_end >> sb->s_blocksize_bits;
3890a87dd18cSLukas Czerner 
3891a87dd18cSLukas Czerner 	/* Handle partial zero within the single block */
3892e1be3a92SLukas Czerner 	if (start == end &&
3893e1be3a92SLukas Czerner 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3894a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3895a87dd18cSLukas Czerner 						 lstart, length);
3896a87dd18cSLukas Czerner 		return err;
3897a87dd18cSLukas Czerner 	}
3898a87dd18cSLukas Czerner 	/* Handle partial zero out on the start of the range */
3899e1be3a92SLukas Czerner 	if (partial_start) {
3900a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3901a87dd18cSLukas Czerner 						 lstart, sb->s_blocksize);
3902a87dd18cSLukas Czerner 		if (err)
3903a87dd18cSLukas Czerner 			return err;
3904a87dd18cSLukas Czerner 	}
3905a87dd18cSLukas Czerner 	/* Handle partial zero out on the end of the range */
3906e1be3a92SLukas Czerner 	if (partial_end != sb->s_blocksize - 1)
3907a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3908e1be3a92SLukas Czerner 						 byte_end - partial_end,
3909e1be3a92SLukas Czerner 						 partial_end + 1);
3910a87dd18cSLukas Czerner 	return err;
3911a87dd18cSLukas Czerner }
3912a87dd18cSLukas Czerner 
391391ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
391491ef4cafSDuane Griffin {
391591ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
391691ef4cafSDuane Griffin 		return 1;
391791ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
391891ef4cafSDuane Griffin 		return 1;
391991ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
392091ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
392191ef4cafSDuane Griffin 	return 0;
392291ef4cafSDuane Griffin }
392391ef4cafSDuane Griffin 
3924ac27a0ecSDave Kleikamp /*
392501127848SJan Kara  * We have to make sure i_disksize gets properly updated before we truncate
392601127848SJan Kara  * page cache due to hole punching or zero range. Otherwise i_disksize update
392701127848SJan Kara  * can get lost as it may have been postponed to submission of writeback but
392801127848SJan Kara  * that will never happen after we truncate page cache.
392901127848SJan Kara  */
393001127848SJan Kara int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
393101127848SJan Kara 				      loff_t len)
393201127848SJan Kara {
393301127848SJan Kara 	handle_t *handle;
39344209ae12SHarshad Shirwadkar 	int ret;
39354209ae12SHarshad Shirwadkar 
393601127848SJan Kara 	loff_t size = i_size_read(inode);
393701127848SJan Kara 
39385955102cSAl Viro 	WARN_ON(!inode_is_locked(inode));
393901127848SJan Kara 	if (offset > size || offset + len < size)
394001127848SJan Kara 		return 0;
394101127848SJan Kara 
394201127848SJan Kara 	if (EXT4_I(inode)->i_disksize >= size)
394301127848SJan Kara 		return 0;
394401127848SJan Kara 
394501127848SJan Kara 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
394601127848SJan Kara 	if (IS_ERR(handle))
394701127848SJan Kara 		return PTR_ERR(handle);
394801127848SJan Kara 	ext4_update_i_disksize(inode, size);
39494209ae12SHarshad Shirwadkar 	ret = ext4_mark_inode_dirty(handle, inode);
395001127848SJan Kara 	ext4_journal_stop(handle);
395101127848SJan Kara 
39524209ae12SHarshad Shirwadkar 	return ret;
395301127848SJan Kara }
395401127848SJan Kara 
3955b1f38217SRoss Zwisler static void ext4_wait_dax_page(struct ext4_inode_info *ei)
3956430657b6SRoss Zwisler {
3957430657b6SRoss Zwisler 	up_write(&ei->i_mmap_sem);
3958430657b6SRoss Zwisler 	schedule();
3959430657b6SRoss Zwisler 	down_write(&ei->i_mmap_sem);
3960430657b6SRoss Zwisler }
3961430657b6SRoss Zwisler 
3962430657b6SRoss Zwisler int ext4_break_layouts(struct inode *inode)
3963430657b6SRoss Zwisler {
3964430657b6SRoss Zwisler 	struct ext4_inode_info *ei = EXT4_I(inode);
3965430657b6SRoss Zwisler 	struct page *page;
3966430657b6SRoss Zwisler 	int error;
3967430657b6SRoss Zwisler 
3968430657b6SRoss Zwisler 	if (WARN_ON_ONCE(!rwsem_is_locked(&ei->i_mmap_sem)))
3969430657b6SRoss Zwisler 		return -EINVAL;
3970430657b6SRoss Zwisler 
3971430657b6SRoss Zwisler 	do {
3972430657b6SRoss Zwisler 		page = dax_layout_busy_page(inode->i_mapping);
3973430657b6SRoss Zwisler 		if (!page)
3974430657b6SRoss Zwisler 			return 0;
3975430657b6SRoss Zwisler 
3976430657b6SRoss Zwisler 		error = ___wait_var_event(&page->_refcount,
3977430657b6SRoss Zwisler 				atomic_read(&page->_refcount) == 1,
3978430657b6SRoss Zwisler 				TASK_INTERRUPTIBLE, 0, 0,
3979b1f38217SRoss Zwisler 				ext4_wait_dax_page(ei));
3980b1f38217SRoss Zwisler 	} while (error == 0);
3981430657b6SRoss Zwisler 
3982430657b6SRoss Zwisler 	return error;
3983430657b6SRoss Zwisler }
3984430657b6SRoss Zwisler 
398501127848SJan Kara /*
3986cca32b7eSRoss Zwisler  * ext4_punch_hole: punches a hole in a file by releasing the blocks
3987a4bb6b64SAllison Henderson  * associated with the given offset and length
3988a4bb6b64SAllison Henderson  *
3989a4bb6b64SAllison Henderson  * @inode:  File inode
3990a4bb6b64SAllison Henderson  * @offset: The offset where the hole will begin
3991a4bb6b64SAllison Henderson  * @len:    The length of the hole
3992a4bb6b64SAllison Henderson  *
39934907cb7bSAnatol Pomozov  * Returns: 0 on success or negative on failure
3994a4bb6b64SAllison Henderson  */
3995a4bb6b64SAllison Henderson 
3996aeb2817aSAshish Sangwan int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3997a4bb6b64SAllison Henderson {
399826a4c0c6STheodore Ts'o 	struct super_block *sb = inode->i_sb;
399926a4c0c6STheodore Ts'o 	ext4_lblk_t first_block, stop_block;
400026a4c0c6STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
4001a87dd18cSLukas Czerner 	loff_t first_block_offset, last_block_offset;
400226a4c0c6STheodore Ts'o 	handle_t *handle;
400326a4c0c6STheodore Ts'o 	unsigned int credits;
40044209ae12SHarshad Shirwadkar 	int ret = 0, ret2 = 0;
400526a4c0c6STheodore Ts'o 
4006b8a86845SLukas Czerner 	trace_ext4_punch_hole(inode, offset, length, 0);
4007aaddea81SZheng Liu 
4008c1e8220bSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
4009c1e8220bSTheodore Ts'o 	if (ext4_has_inline_data(inode)) {
4010c1e8220bSTheodore Ts'o 		down_write(&EXT4_I(inode)->i_mmap_sem);
4011c1e8220bSTheodore Ts'o 		ret = ext4_convert_inline_data(inode);
4012c1e8220bSTheodore Ts'o 		up_write(&EXT4_I(inode)->i_mmap_sem);
4013c1e8220bSTheodore Ts'o 		if (ret)
4014c1e8220bSTheodore Ts'o 			return ret;
4015c1e8220bSTheodore Ts'o 	}
4016c1e8220bSTheodore Ts'o 
401726a4c0c6STheodore Ts'o 	/*
401826a4c0c6STheodore Ts'o 	 * Write out all dirty pages to avoid race conditions
401926a4c0c6STheodore Ts'o 	 * Then release them.
402026a4c0c6STheodore Ts'o 	 */
4021cca32b7eSRoss Zwisler 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
402226a4c0c6STheodore Ts'o 		ret = filemap_write_and_wait_range(mapping, offset,
402326a4c0c6STheodore Ts'o 						   offset + length - 1);
402426a4c0c6STheodore Ts'o 		if (ret)
402526a4c0c6STheodore Ts'o 			return ret;
402626a4c0c6STheodore Ts'o 	}
402726a4c0c6STheodore Ts'o 
40285955102cSAl Viro 	inode_lock(inode);
40299ef06cecSLukas Czerner 
403026a4c0c6STheodore Ts'o 	/* No need to punch hole beyond i_size */
403126a4c0c6STheodore Ts'o 	if (offset >= inode->i_size)
403226a4c0c6STheodore Ts'o 		goto out_mutex;
403326a4c0c6STheodore Ts'o 
403426a4c0c6STheodore Ts'o 	/*
403526a4c0c6STheodore Ts'o 	 * If the hole extends beyond i_size, set the hole
403626a4c0c6STheodore Ts'o 	 * to end after the page that contains i_size
403726a4c0c6STheodore Ts'o 	 */
403826a4c0c6STheodore Ts'o 	if (offset + length > inode->i_size) {
403926a4c0c6STheodore Ts'o 		length = inode->i_size +
404009cbfeafSKirill A. Shutemov 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
404126a4c0c6STheodore Ts'o 		   offset;
404226a4c0c6STheodore Ts'o 	}
404326a4c0c6STheodore Ts'o 
4044a361293fSJan Kara 	if (offset & (sb->s_blocksize - 1) ||
4045a361293fSJan Kara 	    (offset + length) & (sb->s_blocksize - 1)) {
4046a361293fSJan Kara 		/*
4047a361293fSJan Kara 		 * Attach jinode to inode for jbd2 if we do any zeroing of
4048a361293fSJan Kara 		 * partial block
4049a361293fSJan Kara 		 */
4050a361293fSJan Kara 		ret = ext4_inode_attach_jinode(inode);
4051a361293fSJan Kara 		if (ret < 0)
4052a361293fSJan Kara 			goto out_mutex;
4053a361293fSJan Kara 
4054a361293fSJan Kara 	}
4055a361293fSJan Kara 
4056ea3d7209SJan Kara 	/* Wait all existing dio workers, newcomers will block on i_mutex */
4057ea3d7209SJan Kara 	inode_dio_wait(inode);
4058ea3d7209SJan Kara 
4059ea3d7209SJan Kara 	/*
4060ea3d7209SJan Kara 	 * Prevent page faults from reinstantiating pages we have released from
4061ea3d7209SJan Kara 	 * page cache.
4062ea3d7209SJan Kara 	 */
4063ea3d7209SJan Kara 	down_write(&EXT4_I(inode)->i_mmap_sem);
4064430657b6SRoss Zwisler 
4065430657b6SRoss Zwisler 	ret = ext4_break_layouts(inode);
4066430657b6SRoss Zwisler 	if (ret)
4067430657b6SRoss Zwisler 		goto out_dio;
4068430657b6SRoss Zwisler 
4069a87dd18cSLukas Czerner 	first_block_offset = round_up(offset, sb->s_blocksize);
4070a87dd18cSLukas Czerner 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
407126a4c0c6STheodore Ts'o 
4072a87dd18cSLukas Czerner 	/* Now release the pages and zero block aligned part of pages*/
407301127848SJan Kara 	if (last_block_offset > first_block_offset) {
407401127848SJan Kara 		ret = ext4_update_disksize_before_punch(inode, offset, length);
407501127848SJan Kara 		if (ret)
407601127848SJan Kara 			goto out_dio;
4077a87dd18cSLukas Czerner 		truncate_pagecache_range(inode, first_block_offset,
4078a87dd18cSLukas Czerner 					 last_block_offset);
407901127848SJan Kara 	}
408026a4c0c6STheodore Ts'o 
408126a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
408226a4c0c6STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
408326a4c0c6STheodore Ts'o 	else
408426a4c0c6STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
408526a4c0c6STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
408626a4c0c6STheodore Ts'o 	if (IS_ERR(handle)) {
408726a4c0c6STheodore Ts'o 		ret = PTR_ERR(handle);
408826a4c0c6STheodore Ts'o 		ext4_std_error(sb, ret);
408926a4c0c6STheodore Ts'o 		goto out_dio;
409026a4c0c6STheodore Ts'o 	}
409126a4c0c6STheodore Ts'o 
4092a87dd18cSLukas Czerner 	ret = ext4_zero_partial_blocks(handle, inode, offset,
4093a87dd18cSLukas Czerner 				       length);
409426a4c0c6STheodore Ts'o 	if (ret)
409526a4c0c6STheodore Ts'o 		goto out_stop;
409626a4c0c6STheodore Ts'o 
409726a4c0c6STheodore Ts'o 	first_block = (offset + sb->s_blocksize - 1) >>
409826a4c0c6STheodore Ts'o 		EXT4_BLOCK_SIZE_BITS(sb);
409926a4c0c6STheodore Ts'o 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
410026a4c0c6STheodore Ts'o 
4101eee597acSLukas Czerner 	/* If there are blocks to remove, do it */
4102eee597acSLukas Czerner 	if (stop_block > first_block) {
410326a4c0c6STheodore Ts'o 
410426a4c0c6STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
410527bc446eSbrookxu 		ext4_discard_preallocations(inode, 0);
410626a4c0c6STheodore Ts'o 
410726a4c0c6STheodore Ts'o 		ret = ext4_es_remove_extent(inode, first_block,
410826a4c0c6STheodore Ts'o 					    stop_block - first_block);
410926a4c0c6STheodore Ts'o 		if (ret) {
411026a4c0c6STheodore Ts'o 			up_write(&EXT4_I(inode)->i_data_sem);
411126a4c0c6STheodore Ts'o 			goto out_stop;
411226a4c0c6STheodore Ts'o 		}
411326a4c0c6STheodore Ts'o 
411426a4c0c6STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
411526a4c0c6STheodore Ts'o 			ret = ext4_ext_remove_space(inode, first_block,
411626a4c0c6STheodore Ts'o 						    stop_block - 1);
411726a4c0c6STheodore Ts'o 		else
41184f579ae7SLukas Czerner 			ret = ext4_ind_remove_space(handle, inode, first_block,
411926a4c0c6STheodore Ts'o 						    stop_block);
412026a4c0c6STheodore Ts'o 
4121819c4920STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
4122eee597acSLukas Czerner 	}
4123a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_range(handle, inode, first_block, stop_block);
412426a4c0c6STheodore Ts'o 	if (IS_SYNC(inode))
412526a4c0c6STheodore Ts'o 		ext4_handle_sync(handle);
4126e251f9bcSMaxim Patlasov 
4127eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
41284209ae12SHarshad Shirwadkar 	ret2 = ext4_mark_inode_dirty(handle, inode);
41294209ae12SHarshad Shirwadkar 	if (unlikely(ret2))
41304209ae12SHarshad Shirwadkar 		ret = ret2;
413167a7d5f5SJan Kara 	if (ret >= 0)
413267a7d5f5SJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
413326a4c0c6STheodore Ts'o out_stop:
413426a4c0c6STheodore Ts'o 	ext4_journal_stop(handle);
413526a4c0c6STheodore Ts'o out_dio:
4136ea3d7209SJan Kara 	up_write(&EXT4_I(inode)->i_mmap_sem);
413726a4c0c6STheodore Ts'o out_mutex:
41385955102cSAl Viro 	inode_unlock(inode);
413926a4c0c6STheodore Ts'o 	return ret;
4140a4bb6b64SAllison Henderson }
4141a4bb6b64SAllison Henderson 
4142a361293fSJan Kara int ext4_inode_attach_jinode(struct inode *inode)
4143a361293fSJan Kara {
4144a361293fSJan Kara 	struct ext4_inode_info *ei = EXT4_I(inode);
4145a361293fSJan Kara 	struct jbd2_inode *jinode;
4146a361293fSJan Kara 
4147a361293fSJan Kara 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4148a361293fSJan Kara 		return 0;
4149a361293fSJan Kara 
4150a361293fSJan Kara 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4151a361293fSJan Kara 	spin_lock(&inode->i_lock);
4152a361293fSJan Kara 	if (!ei->jinode) {
4153a361293fSJan Kara 		if (!jinode) {
4154a361293fSJan Kara 			spin_unlock(&inode->i_lock);
4155a361293fSJan Kara 			return -ENOMEM;
4156a361293fSJan Kara 		}
4157a361293fSJan Kara 		ei->jinode = jinode;
4158a361293fSJan Kara 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4159a361293fSJan Kara 		jinode = NULL;
4160a361293fSJan Kara 	}
4161a361293fSJan Kara 	spin_unlock(&inode->i_lock);
4162a361293fSJan Kara 	if (unlikely(jinode != NULL))
4163a361293fSJan Kara 		jbd2_free_inode(jinode);
4164a361293fSJan Kara 	return 0;
4165a361293fSJan Kara }
4166a361293fSJan Kara 
4167a4bb6b64SAllison Henderson /*
4168617ba13bSMingming Cao  * ext4_truncate()
4169ac27a0ecSDave Kleikamp  *
4170617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
4171617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4172ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
4173ac27a0ecSDave Kleikamp  *
417442b2aa86SJustin P. Mattock  * As we work through the truncate and commit bits of it to the journal there
4175ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
4176ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
4177ac27a0ecSDave Kleikamp  *
4178ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
4179ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
4180ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
4181ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
4182ac27a0ecSDave Kleikamp  * left-to-right works OK too).
4183ac27a0ecSDave Kleikamp  *
4184ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
4185ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
4186ac27a0ecSDave Kleikamp  *
4187ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
4188617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4189ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
4190617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
4191617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
4192ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
4193617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
4194ac27a0ecSDave Kleikamp  */
41952c98eb5eSTheodore Ts'o int ext4_truncate(struct inode *inode)
4196ac27a0ecSDave Kleikamp {
4197819c4920STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
4198819c4920STheodore Ts'o 	unsigned int credits;
41994209ae12SHarshad Shirwadkar 	int err = 0, err2;
4200819c4920STheodore Ts'o 	handle_t *handle;
4201819c4920STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
4202819c4920STheodore Ts'o 
420319b5ef61STheodore Ts'o 	/*
420419b5ef61STheodore Ts'o 	 * There is a possibility that we're either freeing the inode
4205e04027e8SMatthew Wilcox 	 * or it's a completely new inode. In those cases we might not
420619b5ef61STheodore Ts'o 	 * have i_mutex locked because it's not necessary.
420719b5ef61STheodore Ts'o 	 */
420819b5ef61STheodore Ts'o 	if (!(inode->i_state & (I_NEW|I_FREEING)))
42095955102cSAl Viro 		WARN_ON(!inode_is_locked(inode));
42100562e0baSJiaying Zhang 	trace_ext4_truncate_enter(inode);
42110562e0baSJiaying Zhang 
421291ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
42139a5d265fSzhengliang 		goto out_trace;
4214ac27a0ecSDave Kleikamp 
42155534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
421619f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
42177d8f9f7dSTheodore Ts'o 
4218aef1c851STao Ma 	if (ext4_has_inline_data(inode)) {
4219aef1c851STao Ma 		int has_inline = 1;
4220aef1c851STao Ma 
422101daf945STheodore Ts'o 		err = ext4_inline_data_truncate(inode, &has_inline);
42229a5d265fSzhengliang 		if (err || has_inline)
42239a5d265fSzhengliang 			goto out_trace;
4224aef1c851STao Ma 	}
4225aef1c851STao Ma 
4226a361293fSJan Kara 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4227a361293fSJan Kara 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4228a361293fSJan Kara 		if (ext4_inode_attach_jinode(inode) < 0)
42299a5d265fSzhengliang 			goto out_trace;
4230a361293fSJan Kara 	}
4231a361293fSJan Kara 
4232ff9893dcSAmir Goldstein 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4233819c4920STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
4234ff9893dcSAmir Goldstein 	else
4235819c4920STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
4236819c4920STheodore Ts'o 
4237819c4920STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
42389a5d265fSzhengliang 	if (IS_ERR(handle)) {
42399a5d265fSzhengliang 		err = PTR_ERR(handle);
42409a5d265fSzhengliang 		goto out_trace;
42419a5d265fSzhengliang 	}
4242819c4920STheodore Ts'o 
4243eb3544c6SLukas Czerner 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4244eb3544c6SLukas Czerner 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4245819c4920STheodore Ts'o 
4246819c4920STheodore Ts'o 	/*
4247819c4920STheodore Ts'o 	 * We add the inode to the orphan list, so that if this
4248819c4920STheodore Ts'o 	 * truncate spans multiple transactions, and we crash, we will
4249819c4920STheodore Ts'o 	 * resume the truncate when the filesystem recovers.  It also
4250819c4920STheodore Ts'o 	 * marks the inode dirty, to catch the new size.
4251819c4920STheodore Ts'o 	 *
4252819c4920STheodore Ts'o 	 * Implication: the file must always be in a sane, consistent
4253819c4920STheodore Ts'o 	 * truncatable state while each transaction commits.
4254819c4920STheodore Ts'o 	 */
42552c98eb5eSTheodore Ts'o 	err = ext4_orphan_add(handle, inode);
42562c98eb5eSTheodore Ts'o 	if (err)
4257819c4920STheodore Ts'o 		goto out_stop;
4258819c4920STheodore Ts'o 
4259819c4920STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
4260819c4920STheodore Ts'o 
426127bc446eSbrookxu 	ext4_discard_preallocations(inode, 0);
4262819c4920STheodore Ts'o 
4263819c4920STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4264d0abb36dSTheodore Ts'o 		err = ext4_ext_truncate(handle, inode);
4265819c4920STheodore Ts'o 	else
4266819c4920STheodore Ts'o 		ext4_ind_truncate(handle, inode);
4267819c4920STheodore Ts'o 
4268819c4920STheodore Ts'o 	up_write(&ei->i_data_sem);
4269d0abb36dSTheodore Ts'o 	if (err)
4270d0abb36dSTheodore Ts'o 		goto out_stop;
4271819c4920STheodore Ts'o 
4272819c4920STheodore Ts'o 	if (IS_SYNC(inode))
4273819c4920STheodore Ts'o 		ext4_handle_sync(handle);
4274819c4920STheodore Ts'o 
4275819c4920STheodore Ts'o out_stop:
4276819c4920STheodore Ts'o 	/*
4277819c4920STheodore Ts'o 	 * If this was a simple ftruncate() and the file will remain alive,
4278819c4920STheodore Ts'o 	 * then we need to clear up the orphan record which we created above.
4279819c4920STheodore Ts'o 	 * However, if this was a real unlink then we were called by
428058d86a50SWang Shilong 	 * ext4_evict_inode(), and we allow that function to clean up the
4281819c4920STheodore Ts'o 	 * orphan info for us.
4282819c4920STheodore Ts'o 	 */
4283819c4920STheodore Ts'o 	if (inode->i_nlink)
4284819c4920STheodore Ts'o 		ext4_orphan_del(handle, inode);
4285819c4920STheodore Ts'o 
4286eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
42874209ae12SHarshad Shirwadkar 	err2 = ext4_mark_inode_dirty(handle, inode);
42884209ae12SHarshad Shirwadkar 	if (unlikely(err2 && !err))
42894209ae12SHarshad Shirwadkar 		err = err2;
4290819c4920STheodore Ts'o 	ext4_journal_stop(handle);
4291a86c6181SAlex Tomas 
42929a5d265fSzhengliang out_trace:
42930562e0baSJiaying Zhang 	trace_ext4_truncate_exit(inode);
42942c98eb5eSTheodore Ts'o 	return err;
4295ac27a0ecSDave Kleikamp }
4296ac27a0ecSDave Kleikamp 
4297ac27a0ecSDave Kleikamp /*
4298617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
4299ac27a0ecSDave Kleikamp  * underlying buffer_head on success. If 'in_mem' is true, we have all
4300ac27a0ecSDave Kleikamp  * data in memory that is needed to recreate the on-disk version of this
4301ac27a0ecSDave Kleikamp  * inode.
4302ac27a0ecSDave Kleikamp  */
43038016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
43048016e29fSHarshad Shirwadkar 				struct ext4_iloc *iloc, int in_mem,
43058016e29fSHarshad Shirwadkar 				ext4_fsblk_t *ret_block)
4306ac27a0ecSDave Kleikamp {
4307240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
4308ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
4309240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
431002f03c42SLinus Torvalds 	struct blk_plug		plug;
4311240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
4312ac27a0ecSDave Kleikamp 
43133a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
43148016e29fSHarshad Shirwadkar 	if (ino < EXT4_ROOT_INO ||
43158016e29fSHarshad Shirwadkar 	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
43166a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4317ac27a0ecSDave Kleikamp 
43188016e29fSHarshad Shirwadkar 	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4319240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4320240799cdSTheodore Ts'o 	if (!gdp)
4321240799cdSTheodore Ts'o 		return -EIO;
4322240799cdSTheodore Ts'o 
4323240799cdSTheodore Ts'o 	/*
4324240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
4325240799cdSTheodore Ts'o 	 */
432600d09882STao Ma 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
43278016e29fSHarshad Shirwadkar 	inode_offset = ((ino - 1) %
4328240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
4329240799cdSTheodore Ts'o 	block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4330240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4331240799cdSTheodore Ts'o 
4332240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
4333aebf0243SWang Shilong 	if (unlikely(!bh))
4334860d21e2STheodore Ts'o 		return -ENOMEM;
433546f870d6STheodore Ts'o 	if (ext4_simulate_fail(sb, EXT4_SIM_INODE_EIO))
433646f870d6STheodore Ts'o 		goto simulate_eio;
4337ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
4338ac27a0ecSDave Kleikamp 		lock_buffer(bh);
43399c83a923SHidehiro Kawai 
434060c776e5Szhangyi (F) 		if (ext4_buffer_uptodate(bh)) {
4341ac27a0ecSDave Kleikamp 			/* someone brought it uptodate while we waited */
4342ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
4343ac27a0ecSDave Kleikamp 			goto has_buffer;
4344ac27a0ecSDave Kleikamp 		}
4345ac27a0ecSDave Kleikamp 
4346ac27a0ecSDave Kleikamp 		/*
4347ac27a0ecSDave Kleikamp 		 * If we have all information of the inode in memory and this
4348ac27a0ecSDave Kleikamp 		 * is the only valid inode in the block, we need not read the
4349ac27a0ecSDave Kleikamp 		 * block.
4350ac27a0ecSDave Kleikamp 		 */
4351ac27a0ecSDave Kleikamp 		if (in_mem) {
4352ac27a0ecSDave Kleikamp 			struct buffer_head *bitmap_bh;
4353240799cdSTheodore Ts'o 			int i, start;
4354ac27a0ecSDave Kleikamp 
4355240799cdSTheodore Ts'o 			start = inode_offset & ~(inodes_per_block - 1);
4356ac27a0ecSDave Kleikamp 
4357ac27a0ecSDave Kleikamp 			/* Is the inode bitmap in cache? */
4358240799cdSTheodore Ts'o 			bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4359aebf0243SWang Shilong 			if (unlikely(!bitmap_bh))
4360ac27a0ecSDave Kleikamp 				goto make_io;
4361ac27a0ecSDave Kleikamp 
4362ac27a0ecSDave Kleikamp 			/*
4363ac27a0ecSDave Kleikamp 			 * If the inode bitmap isn't in cache then the
4364ac27a0ecSDave Kleikamp 			 * optimisation may end up performing two reads instead
4365ac27a0ecSDave Kleikamp 			 * of one, so skip it.
4366ac27a0ecSDave Kleikamp 			 */
4367ac27a0ecSDave Kleikamp 			if (!buffer_uptodate(bitmap_bh)) {
4368ac27a0ecSDave Kleikamp 				brelse(bitmap_bh);
4369ac27a0ecSDave Kleikamp 				goto make_io;
4370ac27a0ecSDave Kleikamp 			}
4371240799cdSTheodore Ts'o 			for (i = start; i < start + inodes_per_block; i++) {
4372ac27a0ecSDave Kleikamp 				if (i == inode_offset)
4373ac27a0ecSDave Kleikamp 					continue;
4374617ba13bSMingming Cao 				if (ext4_test_bit(i, bitmap_bh->b_data))
4375ac27a0ecSDave Kleikamp 					break;
4376ac27a0ecSDave Kleikamp 			}
4377ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
4378240799cdSTheodore Ts'o 			if (i == start + inodes_per_block) {
4379ac27a0ecSDave Kleikamp 				/* all other inodes are free, so skip I/O */
4380ac27a0ecSDave Kleikamp 				memset(bh->b_data, 0, bh->b_size);
4381ac27a0ecSDave Kleikamp 				set_buffer_uptodate(bh);
4382ac27a0ecSDave Kleikamp 				unlock_buffer(bh);
4383ac27a0ecSDave Kleikamp 				goto has_buffer;
4384ac27a0ecSDave Kleikamp 			}
4385ac27a0ecSDave Kleikamp 		}
4386ac27a0ecSDave Kleikamp 
4387ac27a0ecSDave Kleikamp make_io:
4388ac27a0ecSDave Kleikamp 		/*
4389240799cdSTheodore Ts'o 		 * If we need to do any I/O, try to pre-readahead extra
4390240799cdSTheodore Ts'o 		 * blocks from the inode table.
4391240799cdSTheodore Ts'o 		 */
439202f03c42SLinus Torvalds 		blk_start_plug(&plug);
4393240799cdSTheodore Ts'o 		if (EXT4_SB(sb)->s_inode_readahead_blks) {
4394240799cdSTheodore Ts'o 			ext4_fsblk_t b, end, table;
4395240799cdSTheodore Ts'o 			unsigned num;
43960d606e2cSTheodore Ts'o 			__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4397240799cdSTheodore Ts'o 
4398240799cdSTheodore Ts'o 			table = ext4_inode_table(sb, gdp);
4399b713a5ecSTheodore Ts'o 			/* s_inode_readahead_blks is always a power of 2 */
44000d606e2cSTheodore Ts'o 			b = block & ~((ext4_fsblk_t) ra_blks - 1);
4401240799cdSTheodore Ts'o 			if (table > b)
4402240799cdSTheodore Ts'o 				b = table;
44030d606e2cSTheodore Ts'o 			end = b + ra_blks;
4404240799cdSTheodore Ts'o 			num = EXT4_INODES_PER_GROUP(sb);
4405feb0ab32SDarrick J. Wong 			if (ext4_has_group_desc_csum(sb))
4406560671a0SAneesh Kumar K.V 				num -= ext4_itable_unused_count(sb, gdp);
4407240799cdSTheodore Ts'o 			table += num / inodes_per_block;
4408240799cdSTheodore Ts'o 			if (end > table)
4409240799cdSTheodore Ts'o 				end = table;
4410240799cdSTheodore Ts'o 			while (b <= end)
44115df1d412Szhangyi (F) 				ext4_sb_breadahead_unmovable(sb, b++);
4412240799cdSTheodore Ts'o 		}
4413240799cdSTheodore Ts'o 
4414240799cdSTheodore Ts'o 		/*
4415ac27a0ecSDave Kleikamp 		 * There are other valid inodes in the buffer, this inode
4416ac27a0ecSDave Kleikamp 		 * has in-inode xattrs, or we don't have this inode in memory.
4417ac27a0ecSDave Kleikamp 		 * Read the block from disk.
4418ac27a0ecSDave Kleikamp 		 */
44198016e29fSHarshad Shirwadkar 		trace_ext4_load_inode(sb, ino);
44202d069c08Szhangyi (F) 		ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
442102f03c42SLinus Torvalds 		blk_finish_plug(&plug);
4422ac27a0ecSDave Kleikamp 		wait_on_buffer(bh);
4423ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bh)) {
442446f870d6STheodore Ts'o 		simulate_eio:
44258016e29fSHarshad Shirwadkar 			if (ret_block)
44268016e29fSHarshad Shirwadkar 				*ret_block = block;
4427ac27a0ecSDave Kleikamp 			brelse(bh);
4428ac27a0ecSDave Kleikamp 			return -EIO;
4429ac27a0ecSDave Kleikamp 		}
4430ac27a0ecSDave Kleikamp 	}
4431ac27a0ecSDave Kleikamp has_buffer:
4432ac27a0ecSDave Kleikamp 	iloc->bh = bh;
4433ac27a0ecSDave Kleikamp 	return 0;
4434ac27a0ecSDave Kleikamp }
4435ac27a0ecSDave Kleikamp 
44368016e29fSHarshad Shirwadkar static int __ext4_get_inode_loc_noinmem(struct inode *inode,
44378016e29fSHarshad Shirwadkar 					struct ext4_iloc *iloc)
44388016e29fSHarshad Shirwadkar {
44398016e29fSHarshad Shirwadkar 	ext4_fsblk_t err_blk;
44408016e29fSHarshad Shirwadkar 	int ret;
44418016e29fSHarshad Shirwadkar 
44428016e29fSHarshad Shirwadkar 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc, 0,
44438016e29fSHarshad Shirwadkar 					&err_blk);
44448016e29fSHarshad Shirwadkar 
44458016e29fSHarshad Shirwadkar 	if (ret == -EIO)
44468016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
44478016e29fSHarshad Shirwadkar 					"unable to read itable block");
44488016e29fSHarshad Shirwadkar 
44498016e29fSHarshad Shirwadkar 	return ret;
44508016e29fSHarshad Shirwadkar }
44518016e29fSHarshad Shirwadkar 
4452617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4453ac27a0ecSDave Kleikamp {
44548016e29fSHarshad Shirwadkar 	ext4_fsblk_t err_blk;
44558016e29fSHarshad Shirwadkar 	int ret;
44568016e29fSHarshad Shirwadkar 
4457ac27a0ecSDave Kleikamp 	/* We have all inode data except xattrs in memory here. */
44588016e29fSHarshad Shirwadkar 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc,
44598016e29fSHarshad Shirwadkar 		!ext4_test_inode_state(inode, EXT4_STATE_XATTR), &err_blk);
44608016e29fSHarshad Shirwadkar 
44618016e29fSHarshad Shirwadkar 	if (ret == -EIO)
44628016e29fSHarshad Shirwadkar 		ext4_error_inode_block(inode, err_blk, EIO,
44638016e29fSHarshad Shirwadkar 					"unable to read itable block");
44648016e29fSHarshad Shirwadkar 
44658016e29fSHarshad Shirwadkar 	return ret;
44668016e29fSHarshad Shirwadkar }
44678016e29fSHarshad Shirwadkar 
44688016e29fSHarshad Shirwadkar 
44698016e29fSHarshad Shirwadkar int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
44708016e29fSHarshad Shirwadkar 			  struct ext4_iloc *iloc)
44718016e29fSHarshad Shirwadkar {
44728016e29fSHarshad Shirwadkar 	return __ext4_get_inode_loc(sb, ino, iloc, 0, NULL);
4473ac27a0ecSDave Kleikamp }
4474ac27a0ecSDave Kleikamp 
4475a8ab6d38SIra Weiny static bool ext4_should_enable_dax(struct inode *inode)
44766642586bSRoss Zwisler {
4477a8ab6d38SIra Weiny 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4478a8ab6d38SIra Weiny 
44799cb20f94SIra Weiny 	if (test_opt2(inode->i_sb, DAX_NEVER))
44806642586bSRoss Zwisler 		return false;
44816642586bSRoss Zwisler 	if (!S_ISREG(inode->i_mode))
44826642586bSRoss Zwisler 		return false;
44836642586bSRoss Zwisler 	if (ext4_should_journal_data(inode))
44846642586bSRoss Zwisler 		return false;
44856642586bSRoss Zwisler 	if (ext4_has_inline_data(inode))
44866642586bSRoss Zwisler 		return false;
4487592ddec7SChandan Rajendra 	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
44886642586bSRoss Zwisler 		return false;
4489c93d8f88SEric Biggers 	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4490c93d8f88SEric Biggers 		return false;
4491a8ab6d38SIra Weiny 	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4492a8ab6d38SIra Weiny 		return false;
4493a8ab6d38SIra Weiny 	if (test_opt(inode->i_sb, DAX_ALWAYS))
44946642586bSRoss Zwisler 		return true;
4495a8ab6d38SIra Weiny 
4496b383a73fSIra Weiny 	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
44976642586bSRoss Zwisler }
44986642586bSRoss Zwisler 
4499043546e4SIra Weiny void ext4_set_inode_flags(struct inode *inode, bool init)
4500ac27a0ecSDave Kleikamp {
4501617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
450200a1a053STheodore Ts'o 	unsigned int new_fl = 0;
4503ac27a0ecSDave Kleikamp 
4504043546e4SIra Weiny 	WARN_ON_ONCE(IS_DAX(inode) && init);
4505043546e4SIra Weiny 
4506617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
450700a1a053STheodore Ts'o 		new_fl |= S_SYNC;
4508617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
450900a1a053STheodore Ts'o 		new_fl |= S_APPEND;
4510617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
451100a1a053STheodore Ts'o 		new_fl |= S_IMMUTABLE;
4512617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
451300a1a053STheodore Ts'o 		new_fl |= S_NOATIME;
4514617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
451500a1a053STheodore Ts'o 		new_fl |= S_DIRSYNC;
4516043546e4SIra Weiny 
4517043546e4SIra Weiny 	/* Because of the way inode_set_flags() works we must preserve S_DAX
4518043546e4SIra Weiny 	 * here if already set. */
4519043546e4SIra Weiny 	new_fl |= (inode->i_flags & S_DAX);
4520043546e4SIra Weiny 	if (init && ext4_should_enable_dax(inode))
4521923ae0ffSRoss Zwisler 		new_fl |= S_DAX;
4522043546e4SIra Weiny 
45232ee6a576SEric Biggers 	if (flags & EXT4_ENCRYPT_FL)
45242ee6a576SEric Biggers 		new_fl |= S_ENCRYPTED;
4525b886ee3eSGabriel Krisman Bertazi 	if (flags & EXT4_CASEFOLD_FL)
4526b886ee3eSGabriel Krisman Bertazi 		new_fl |= S_CASEFOLD;
4527c93d8f88SEric Biggers 	if (flags & EXT4_VERITY_FL)
4528c93d8f88SEric Biggers 		new_fl |= S_VERITY;
45295f16f322STheodore Ts'o 	inode_set_flags(inode, new_fl,
45302ee6a576SEric Biggers 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4531c93d8f88SEric Biggers 			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4532ac27a0ecSDave Kleikamp }
4533ac27a0ecSDave Kleikamp 
45340fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
45350fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
45360fc1b451SAneesh Kumar K.V {
45370fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
45388180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
45398180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
45400fc1b451SAneesh Kumar K.V 
4541e2b911c5SDarrick J. Wong 	if (ext4_has_feature_huge_file(sb)) {
45420fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
45430fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
45440fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
454507a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
45468180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
45478180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
45488180a562SAneesh Kumar K.V 		} else {
45490fc1b451SAneesh Kumar K.V 			return i_blocks;
45508180a562SAneesh Kumar K.V 		}
45510fc1b451SAneesh Kumar K.V 	} else {
45520fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
45530fc1b451SAneesh Kumar K.V 	}
45540fc1b451SAneesh Kumar K.V }
4555ff9ddf7eSJan Kara 
4556eb9b5f01STheodore Ts'o static inline int ext4_iget_extra_inode(struct inode *inode,
4557152a7b0aSTao Ma 					 struct ext4_inode *raw_inode,
4558152a7b0aSTao Ma 					 struct ext4_inode_info *ei)
4559152a7b0aSTao Ma {
4560152a7b0aSTao Ma 	__le32 *magic = (void *)raw_inode +
4561152a7b0aSTao Ma 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4562eb9b5f01STheodore Ts'o 
4563290ab230SEric Biggers 	if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
4564290ab230SEric Biggers 	    EXT4_INODE_SIZE(inode->i_sb) &&
4565290ab230SEric Biggers 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4566152a7b0aSTao Ma 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4567eb9b5f01STheodore Ts'o 		return ext4_find_inline_data_nolock(inode);
4568f19d5870STao Ma 	} else
4569f19d5870STao Ma 		EXT4_I(inode)->i_inline_off = 0;
4570eb9b5f01STheodore Ts'o 	return 0;
4571152a7b0aSTao Ma }
4572152a7b0aSTao Ma 
4573040cb378SLi Xi int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4574040cb378SLi Xi {
45750b7b7779SKaho Ng 	if (!ext4_has_feature_project(inode->i_sb))
4576040cb378SLi Xi 		return -EOPNOTSUPP;
4577040cb378SLi Xi 	*projid = EXT4_I(inode)->i_projid;
4578040cb378SLi Xi 	return 0;
4579040cb378SLi Xi }
4580040cb378SLi Xi 
4581e254d1afSEryu Guan /*
4582e254d1afSEryu Guan  * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4583e254d1afSEryu Guan  * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4584e254d1afSEryu Guan  * set.
4585e254d1afSEryu Guan  */
4586e254d1afSEryu Guan static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4587e254d1afSEryu Guan {
4588e254d1afSEryu Guan 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4589e254d1afSEryu Guan 		inode_set_iversion_raw(inode, val);
4590e254d1afSEryu Guan 	else
4591e254d1afSEryu Guan 		inode_set_iversion_queried(inode, val);
4592e254d1afSEryu Guan }
4593e254d1afSEryu Guan static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4594e254d1afSEryu Guan {
4595e254d1afSEryu Guan 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4596e254d1afSEryu Guan 		return inode_peek_iversion_raw(inode);
4597e254d1afSEryu Guan 	else
4598e254d1afSEryu Guan 		return inode_peek_iversion(inode);
4599e254d1afSEryu Guan }
4600e254d1afSEryu Guan 
46018a363970STheodore Ts'o struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
46028a363970STheodore Ts'o 			  ext4_iget_flags flags, const char *function,
46038a363970STheodore Ts'o 			  unsigned int line)
4604ac27a0ecSDave Kleikamp {
4605617ba13bSMingming Cao 	struct ext4_iloc iloc;
4606617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
46071d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
4608bd2c38cfSJan Kara 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
46091d1fe1eeSDavid Howells 	struct inode *inode;
4610b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
46111d1fe1eeSDavid Howells 	long ret;
46127e6e1ef4SDarrick J. Wong 	loff_t size;
4613ac27a0ecSDave Kleikamp 	int block;
461408cefc7aSEric W. Biederman 	uid_t i_uid;
461508cefc7aSEric W. Biederman 	gid_t i_gid;
4616040cb378SLi Xi 	projid_t i_projid;
4617ac27a0ecSDave Kleikamp 
4618191ce178STheodore Ts'o 	if ((!(flags & EXT4_IGET_SPECIAL) &&
4619bd2c38cfSJan Kara 	     ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4620bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_usr_quota_inum) ||
4621bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_grp_quota_inum) ||
4622bd2c38cfSJan Kara 	      ino == le32_to_cpu(es->s_prj_quota_inum))) ||
46238a363970STheodore Ts'o 	    (ino < EXT4_ROOT_INO) ||
4624bd2c38cfSJan Kara 	    (ino > le32_to_cpu(es->s_inodes_count))) {
46258a363970STheodore Ts'o 		if (flags & EXT4_IGET_HANDLE)
46268a363970STheodore Ts'o 			return ERR_PTR(-ESTALE);
4627014c9caaSJan Kara 		__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
46288a363970STheodore Ts'o 			     "inode #%lu: comm %s: iget: illegal inode #",
46298a363970STheodore Ts'o 			     ino, current->comm);
46308a363970STheodore Ts'o 		return ERR_PTR(-EFSCORRUPTED);
46318a363970STheodore Ts'o 	}
46328a363970STheodore Ts'o 
46331d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
46341d1fe1eeSDavid Howells 	if (!inode)
46351d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
46361d1fe1eeSDavid Howells 	if (!(inode->i_state & I_NEW))
46371d1fe1eeSDavid Howells 		return inode;
46381d1fe1eeSDavid Howells 
46391d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
46407dc57615SPeter Huewe 	iloc.bh = NULL;
4641ac27a0ecSDave Kleikamp 
46428016e29fSHarshad Shirwadkar 	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
46431d1fe1eeSDavid Howells 	if (ret < 0)
4644ac27a0ecSDave Kleikamp 		goto bad_inode;
4645617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
4646814525f4SDarrick J. Wong 
46478e4b5eaeSTheodore Ts'o 	if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
46488a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
46498a363970STheodore Ts'o 				 "iget: root inode unallocated");
46508e4b5eaeSTheodore Ts'o 		ret = -EFSCORRUPTED;
46518e4b5eaeSTheodore Ts'o 		goto bad_inode;
46528e4b5eaeSTheodore Ts'o 	}
46538e4b5eaeSTheodore Ts'o 
46548a363970STheodore Ts'o 	if ((flags & EXT4_IGET_HANDLE) &&
46558a363970STheodore Ts'o 	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
46568a363970STheodore Ts'o 		ret = -ESTALE;
46578a363970STheodore Ts'o 		goto bad_inode;
46588a363970STheodore Ts'o 	}
46598a363970STheodore Ts'o 
4660814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4661814525f4SDarrick J. Wong 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4662814525f4SDarrick J. Wong 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
46632dc8d9e1SEric Biggers 			EXT4_INODE_SIZE(inode->i_sb) ||
46642dc8d9e1SEric Biggers 		    (ei->i_extra_isize & 3)) {
46658a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
46668a363970STheodore Ts'o 					 "iget: bad extra_isize %u "
46678a363970STheodore Ts'o 					 "(inode size %u)",
46682dc8d9e1SEric Biggers 					 ei->i_extra_isize,
4669814525f4SDarrick J. Wong 					 EXT4_INODE_SIZE(inode->i_sb));
46706a797d27SDarrick J. Wong 			ret = -EFSCORRUPTED;
4671814525f4SDarrick J. Wong 			goto bad_inode;
4672814525f4SDarrick J. Wong 		}
4673814525f4SDarrick J. Wong 	} else
4674814525f4SDarrick J. Wong 		ei->i_extra_isize = 0;
4675814525f4SDarrick J. Wong 
4676814525f4SDarrick J. Wong 	/* Precompute checksum seed for inode metadata */
46779aa5d32bSDmitry Monakhov 	if (ext4_has_metadata_csum(sb)) {
4678814525f4SDarrick J. Wong 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4679814525f4SDarrick J. Wong 		__u32 csum;
4680814525f4SDarrick J. Wong 		__le32 inum = cpu_to_le32(inode->i_ino);
4681814525f4SDarrick J. Wong 		__le32 gen = raw_inode->i_generation;
4682814525f4SDarrick J. Wong 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4683814525f4SDarrick J. Wong 				   sizeof(inum));
4684814525f4SDarrick J. Wong 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4685814525f4SDarrick J. Wong 					      sizeof(gen));
4686814525f4SDarrick J. Wong 	}
4687814525f4SDarrick J. Wong 
46888016e29fSHarshad Shirwadkar 	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
46898016e29fSHarshad Shirwadkar 	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
46908016e29fSHarshad Shirwadkar 	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
46918016e29fSHarshad Shirwadkar 		ext4_error_inode_err(inode, function, line, 0,
46928016e29fSHarshad Shirwadkar 				EFSBADCRC, "iget: checksum invalid");
46936a797d27SDarrick J. Wong 		ret = -EFSBADCRC;
4694814525f4SDarrick J. Wong 		goto bad_inode;
4695814525f4SDarrick J. Wong 	}
4696814525f4SDarrick J. Wong 
4697ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
469808cefc7aSEric W. Biederman 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
469908cefc7aSEric W. Biederman 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
47000b7b7779SKaho Ng 	if (ext4_has_feature_project(sb) &&
4701040cb378SLi Xi 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4702040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4703040cb378SLi Xi 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4704040cb378SLi Xi 	else
4705040cb378SLi Xi 		i_projid = EXT4_DEF_PROJID;
4706040cb378SLi Xi 
4707ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
470808cefc7aSEric W. Biederman 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
470908cefc7aSEric W. Biederman 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4710ac27a0ecSDave Kleikamp 	}
471108cefc7aSEric W. Biederman 	i_uid_write(inode, i_uid);
471208cefc7aSEric W. Biederman 	i_gid_write(inode, i_gid);
4713040cb378SLi Xi 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4714bfe86848SMiklos Szeredi 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4715ac27a0ecSDave Kleikamp 
4716353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
471767cf5b09STao Ma 	ei->i_inline_off = 0;
4718ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
4719ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4720ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
4721ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
4722ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
4723ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
4724ac27a0ecSDave Kleikamp 	 */
4725ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
4726393d1d1dSDr. Tilmann Bubeck 		if ((inode->i_mode == 0 ||
4727393d1d1dSDr. Tilmann Bubeck 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4728393d1d1dSDr. Tilmann Bubeck 		    ino != EXT4_BOOT_LOADER_INO) {
4729ac27a0ecSDave Kleikamp 			/* this inode is deleted */
47301d1fe1eeSDavid Howells 			ret = -ESTALE;
4731ac27a0ecSDave Kleikamp 			goto bad_inode;
4732ac27a0ecSDave Kleikamp 		}
4733ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
4734ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
4735ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
4736393d1d1dSDr. Tilmann Bubeck 		 * the process of deleting those.
4737393d1d1dSDr. Tilmann Bubeck 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4738393d1d1dSDr. Tilmann Bubeck 		 * not initialized on a new filesystem. */
4739ac27a0ecSDave Kleikamp 	}
4740ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4741043546e4SIra Weiny 	ext4_set_inode_flags(inode, true);
47420fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
47437973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4744e2b911c5SDarrick J. Wong 	if (ext4_has_feature_64bit(sb))
4745a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
4746a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4747e08ac99fSArtem Blagodarenko 	inode->i_size = ext4_isize(sb, raw_inode);
47487e6e1ef4SDarrick J. Wong 	if ((size = i_size_read(inode)) < 0) {
47498a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
47508a363970STheodore Ts'o 				 "iget: bad i_size value: %lld", size);
47517e6e1ef4SDarrick J. Wong 		ret = -EFSCORRUPTED;
47527e6e1ef4SDarrick J. Wong 		goto bad_inode;
47537e6e1ef4SDarrick J. Wong 	}
475448a34311SJan Kara 	/*
475548a34311SJan Kara 	 * If dir_index is not enabled but there's dir with INDEX flag set,
475648a34311SJan Kara 	 * we'd normally treat htree data as empty space. But with metadata
475748a34311SJan Kara 	 * checksumming that corrupts checksums so forbid that.
475848a34311SJan Kara 	 */
475948a34311SJan Kara 	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
476048a34311SJan Kara 	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
476148a34311SJan Kara 		ext4_error_inode(inode, function, line, 0,
476248a34311SJan Kara 			 "iget: Dir with htree data on filesystem without dir_index feature.");
476348a34311SJan Kara 		ret = -EFSCORRUPTED;
476448a34311SJan Kara 		goto bad_inode;
476548a34311SJan Kara 	}
4766ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
4767a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
4768a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
4769a9e7f447SDmitry Monakhov #endif
4770ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4771ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
4772a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
4773ac27a0ecSDave Kleikamp 	/*
4774ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
4775ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4776ac27a0ecSDave Kleikamp 	 */
4777617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4778ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
4779ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
4780aa75f4d3SHarshad Shirwadkar 	ext4_fc_init_inode(&ei->vfs_inode);
4781ac27a0ecSDave Kleikamp 
4782b436b9beSJan Kara 	/*
4783b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
4784b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
4785b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
4786b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
4787b436b9beSJan Kara 	 * now it is reread from disk.
4788b436b9beSJan Kara 	 */
4789b436b9beSJan Kara 	if (journal) {
4790b436b9beSJan Kara 		transaction_t *transaction;
4791b436b9beSJan Kara 		tid_t tid;
4792b436b9beSJan Kara 
4793a931da6aSTheodore Ts'o 		read_lock(&journal->j_state_lock);
4794b436b9beSJan Kara 		if (journal->j_running_transaction)
4795b436b9beSJan Kara 			transaction = journal->j_running_transaction;
4796b436b9beSJan Kara 		else
4797b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
4798b436b9beSJan Kara 		if (transaction)
4799b436b9beSJan Kara 			tid = transaction->t_tid;
4800b436b9beSJan Kara 		else
4801b436b9beSJan Kara 			tid = journal->j_commit_sequence;
4802a931da6aSTheodore Ts'o 		read_unlock(&journal->j_state_lock);
4803b436b9beSJan Kara 		ei->i_sync_tid = tid;
4804b436b9beSJan Kara 		ei->i_datasync_tid = tid;
4805b436b9beSJan Kara 	}
4806b436b9beSJan Kara 
48070040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4808ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
4809ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
48102dc8d9e1SEric Biggers 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4811617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4812617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
4813ac27a0ecSDave Kleikamp 		} else {
4814eb9b5f01STheodore Ts'o 			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4815eb9b5f01STheodore Ts'o 			if (ret)
4816eb9b5f01STheodore Ts'o 				goto bad_inode;
4817ac27a0ecSDave Kleikamp 		}
4818814525f4SDarrick J. Wong 	}
4819ac27a0ecSDave Kleikamp 
4820ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4821ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4822ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4823ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4824ef7f3835SKalpak Shah 
4825ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4826ee73f9a5SJeff Layton 		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4827ee73f9a5SJeff Layton 
482825ec56b5SJean Noel Cordenner 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
482925ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4830ee73f9a5SJeff Layton 				ivers |=
483125ec56b5SJean Noel Cordenner 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
483225ec56b5SJean Noel Cordenner 		}
4833e254d1afSEryu Guan 		ext4_inode_set_iversion_queried(inode, ivers);
4834c4f65706STheodore Ts'o 	}
483525ec56b5SJean Noel Cordenner 
4836c4b5a614STheodore Ts'o 	ret = 0;
4837485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
4838ce9f24ccSJan Kara 	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
48398a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
48408a363970STheodore Ts'o 				 "iget: bad extended attribute block %llu",
484124676da4STheodore Ts'o 				 ei->i_file_acl);
48426a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
4843485c26ecSTheodore Ts'o 		goto bad_inode;
4844f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
4845bc716523SLiu Song 		/* validate the block references in the inode */
48468016e29fSHarshad Shirwadkar 		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
48478016e29fSHarshad Shirwadkar 			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4848fe2c8191SThiemo Nagel 			(S_ISLNK(inode->i_mode) &&
48498016e29fSHarshad Shirwadkar 			!ext4_inode_is_fast_symlink(inode)))) {
4850bc716523SLiu Song 			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4851bc716523SLiu Song 				ret = ext4_ext_check_inode(inode);
4852bc716523SLiu Song 			else
48531f7d1e77STheodore Ts'o 				ret = ext4_ind_check_inode(inode);
4854fe2c8191SThiemo Nagel 		}
4855f19d5870STao Ma 	}
4856567f3e9aSTheodore Ts'o 	if (ret)
48577a262f7cSAneesh Kumar K.V 		goto bad_inode;
48587a262f7cSAneesh Kumar K.V 
4859ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
4860617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
4861617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
4862617ba13bSMingming Cao 		ext4_set_aops(inode);
4863ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
4864617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
4865617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
4866ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
48676390d33bSLuis R. Rodriguez 		/* VFS does not allow setting these so must be corruption */
48686390d33bSLuis R. Rodriguez 		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
48698a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
48708a363970STheodore Ts'o 					 "iget: immutable or append flags "
48718a363970STheodore Ts'o 					 "not allowed on symlinks");
48726390d33bSLuis R. Rodriguez 			ret = -EFSCORRUPTED;
48736390d33bSLuis R. Rodriguez 			goto bad_inode;
48746390d33bSLuis R. Rodriguez 		}
4875592ddec7SChandan Rajendra 		if (IS_ENCRYPTED(inode)) {
4876a7a67e8aSAl Viro 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
4877a7a67e8aSAl Viro 			ext4_set_aops(inode);
4878a7a67e8aSAl Viro 		} else if (ext4_inode_is_fast_symlink(inode)) {
487975e7566bSAl Viro 			inode->i_link = (char *)ei->i_data;
4880617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
4881e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
4882e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
4883e83c1397SDuane Griffin 		} else {
4884617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
4885617ba13bSMingming Cao 			ext4_set_aops(inode);
4886ac27a0ecSDave Kleikamp 		}
488721fc61c7SAl Viro 		inode_nohighmem(inode);
4888563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4889563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4890617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
4891ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
4892ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
4893ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4894ac27a0ecSDave Kleikamp 		else
4895ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
4896ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4897393d1d1dSDr. Tilmann Bubeck 	} else if (ino == EXT4_BOOT_LOADER_INO) {
4898393d1d1dSDr. Tilmann Bubeck 		make_bad_inode(inode);
4899563bdd61STheodore Ts'o 	} else {
49006a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
49018a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
49028a363970STheodore Ts'o 				 "iget: bogus i_mode (%o)", inode->i_mode);
4903563bdd61STheodore Ts'o 		goto bad_inode;
4904ac27a0ecSDave Kleikamp 	}
49056456ca65STheodore Ts'o 	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
49066456ca65STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
49076456ca65STheodore Ts'o 				 "casefold flag without casefold feature");
4908ac27a0ecSDave Kleikamp 	brelse(iloc.bh);
4909dec214d0STahsin Erdogan 
49101d1fe1eeSDavid Howells 	unlock_new_inode(inode);
49111d1fe1eeSDavid Howells 	return inode;
4912ac27a0ecSDave Kleikamp 
4913ac27a0ecSDave Kleikamp bad_inode:
4914567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
49151d1fe1eeSDavid Howells 	iget_failed(inode);
49161d1fe1eeSDavid Howells 	return ERR_PTR(ret);
4917ac27a0ecSDave Kleikamp }
4918ac27a0ecSDave Kleikamp 
49190fc1b451SAneesh Kumar K.V static int ext4_inode_blocks_set(handle_t *handle,
49200fc1b451SAneesh Kumar K.V 				struct ext4_inode *raw_inode,
49210fc1b451SAneesh Kumar K.V 				struct ext4_inode_info *ei)
49220fc1b451SAneesh Kumar K.V {
49230fc1b451SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
492428936b62SQian Cai 	u64 i_blocks = READ_ONCE(inode->i_blocks);
49250fc1b451SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
49260fc1b451SAneesh Kumar K.V 
49270fc1b451SAneesh Kumar K.V 	if (i_blocks <= ~0U) {
49280fc1b451SAneesh Kumar K.V 		/*
49294907cb7bSAnatol Pomozov 		 * i_blocks can be represented in a 32 bit variable
49300fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
49310fc1b451SAneesh Kumar K.V 		 */
49328180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
49330fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = 0;
493484a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4935f287a1a5STheodore Ts'o 		return 0;
4936f287a1a5STheodore Ts'o 	}
4937e2b911c5SDarrick J. Wong 	if (!ext4_has_feature_huge_file(sb))
4938f287a1a5STheodore Ts'o 		return -EFBIG;
4939f287a1a5STheodore Ts'o 
4940f287a1a5STheodore Ts'o 	if (i_blocks <= 0xffffffffffffULL) {
49410fc1b451SAneesh Kumar K.V 		/*
49420fc1b451SAneesh Kumar K.V 		 * i_blocks can be represented in a 48 bit variable
49430fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
49440fc1b451SAneesh Kumar K.V 		 */
49458180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
49460fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
494784a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
49480fc1b451SAneesh Kumar K.V 	} else {
494984a8dce2SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
49508180a562SAneesh Kumar K.V 		/* i_block is stored in file system block size */
49518180a562SAneesh Kumar K.V 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
49528180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
49538180a562SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
49540fc1b451SAneesh Kumar K.V 	}
4955f287a1a5STheodore Ts'o 	return 0;
49560fc1b451SAneesh Kumar K.V }
49570fc1b451SAneesh Kumar K.V 
49583f19b2abSDavid Howells static void __ext4_update_other_inode_time(struct super_block *sb,
49593f19b2abSDavid Howells 					   unsigned long orig_ino,
49603f19b2abSDavid Howells 					   unsigned long ino,
49613f19b2abSDavid Howells 					   struct ext4_inode *raw_inode)
4962a26f4992STheodore Ts'o {
49633f19b2abSDavid Howells 	struct inode *inode;
4964a26f4992STheodore Ts'o 
49653f19b2abSDavid Howells 	inode = find_inode_by_ino_rcu(sb, ino);
49663f19b2abSDavid Howells 	if (!inode)
49673f19b2abSDavid Howells 		return;
49683f19b2abSDavid Howells 
4969ed296c6cSEric Biggers 	if (!inode_is_dirtytime_only(inode))
49703f19b2abSDavid Howells 		return;
49713f19b2abSDavid Howells 
4972a26f4992STheodore Ts'o 	spin_lock(&inode->i_lock);
4973ed296c6cSEric Biggers 	if (inode_is_dirtytime_only(inode)) {
4974a26f4992STheodore Ts'o 		struct ext4_inode_info	*ei = EXT4_I(inode);
4975a26f4992STheodore Ts'o 
49765fcd5750SJan Kara 		inode->i_state &= ~I_DIRTY_TIME;
4977a26f4992STheodore Ts'o 		spin_unlock(&inode->i_lock);
4978a26f4992STheodore Ts'o 
4979a26f4992STheodore Ts'o 		spin_lock(&ei->i_raw_lock);
49803f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
49813f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
49823f19b2abSDavid Howells 		EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
49833f19b2abSDavid Howells 		ext4_inode_csum_set(inode, raw_inode, ei);
4984a26f4992STheodore Ts'o 		spin_unlock(&ei->i_raw_lock);
49853f19b2abSDavid Howells 		trace_ext4_other_inode_update_time(inode, orig_ino);
49863f19b2abSDavid Howells 		return;
4987a26f4992STheodore Ts'o 	}
4988a26f4992STheodore Ts'o 	spin_unlock(&inode->i_lock);
4989a26f4992STheodore Ts'o }
4990a26f4992STheodore Ts'o 
4991a26f4992STheodore Ts'o /*
4992a26f4992STheodore Ts'o  * Opportunistically update the other time fields for other inodes in
4993a26f4992STheodore Ts'o  * the same inode table block.
4994a26f4992STheodore Ts'o  */
4995a26f4992STheodore Ts'o static void ext4_update_other_inodes_time(struct super_block *sb,
4996a26f4992STheodore Ts'o 					  unsigned long orig_ino, char *buf)
4997a26f4992STheodore Ts'o {
4998a26f4992STheodore Ts'o 	unsigned long ino;
4999a26f4992STheodore Ts'o 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5000a26f4992STheodore Ts'o 	int inode_size = EXT4_INODE_SIZE(sb);
5001a26f4992STheodore Ts'o 
50020f0ff9a9STheodore Ts'o 	/*
50030f0ff9a9STheodore Ts'o 	 * Calculate the first inode in the inode table block.  Inode
50040f0ff9a9STheodore Ts'o 	 * numbers are one-based.  That is, the first inode in a block
50050f0ff9a9STheodore Ts'o 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
50060f0ff9a9STheodore Ts'o 	 */
50070f0ff9a9STheodore Ts'o 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
50083f19b2abSDavid Howells 	rcu_read_lock();
5009a26f4992STheodore Ts'o 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5010a26f4992STheodore Ts'o 		if (ino == orig_ino)
5011a26f4992STheodore Ts'o 			continue;
50123f19b2abSDavid Howells 		__ext4_update_other_inode_time(sb, orig_ino, ino,
50133f19b2abSDavid Howells 					       (struct ext4_inode *)buf);
5014a26f4992STheodore Ts'o 	}
50153f19b2abSDavid Howells 	rcu_read_unlock();
5016a26f4992STheodore Ts'o }
5017a26f4992STheodore Ts'o 
5018ac27a0ecSDave Kleikamp /*
5019ac27a0ecSDave Kleikamp  * Post the struct inode info into an on-disk inode location in the
5020ac27a0ecSDave Kleikamp  * buffer-cache.  This gobbles the caller's reference to the
5021ac27a0ecSDave Kleikamp  * buffer_head in the inode location struct.
5022ac27a0ecSDave Kleikamp  *
5023ac27a0ecSDave Kleikamp  * The caller must have write access to iloc->bh.
5024ac27a0ecSDave Kleikamp  */
5025617ba13bSMingming Cao static int ext4_do_update_inode(handle_t *handle,
5026ac27a0ecSDave Kleikamp 				struct inode *inode,
5027830156c7SFrank Mayhar 				struct ext4_iloc *iloc)
5028ac27a0ecSDave Kleikamp {
5029617ba13bSMingming Cao 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5030617ba13bSMingming Cao 	struct ext4_inode_info *ei = EXT4_I(inode);
5031ac27a0ecSDave Kleikamp 	struct buffer_head *bh = iloc->bh;
5032202ee5dfSTheodore Ts'o 	struct super_block *sb = inode->i_sb;
50337d8bd3c7SShijie Luo 	int err = 0, block;
5034202ee5dfSTheodore Ts'o 	int need_datasync = 0, set_large_file = 0;
503508cefc7aSEric W. Biederman 	uid_t i_uid;
503608cefc7aSEric W. Biederman 	gid_t i_gid;
5037040cb378SLi Xi 	projid_t i_projid;
5038ac27a0ecSDave Kleikamp 
5039202ee5dfSTheodore Ts'o 	spin_lock(&ei->i_raw_lock);
5040202ee5dfSTheodore Ts'o 
5041202ee5dfSTheodore Ts'o 	/* For fields not tracked in the in-memory inode,
5042ac27a0ecSDave Kleikamp 	 * initialise them to zero for new inodes. */
504319f5fb7aSTheodore Ts'o 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5044617ba13bSMingming Cao 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5045ac27a0ecSDave Kleikamp 
504613221811SLuo Meng 	err = ext4_inode_blocks_set(handle, raw_inode, ei);
504713221811SLuo Meng 	if (err) {
504813221811SLuo Meng 		spin_unlock(&ei->i_raw_lock);
504913221811SLuo Meng 		goto out_brelse;
505013221811SLuo Meng 	}
505113221811SLuo Meng 
5052ac27a0ecSDave Kleikamp 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
505308cefc7aSEric W. Biederman 	i_uid = i_uid_read(inode);
505408cefc7aSEric W. Biederman 	i_gid = i_gid_read(inode);
5055040cb378SLi Xi 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
5056ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
505708cefc7aSEric W. Biederman 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
505808cefc7aSEric W. Biederman 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
5059ac27a0ecSDave Kleikamp /*
5060ac27a0ecSDave Kleikamp  * Fix up interoperability with old kernels. Otherwise, old inodes get
5061ac27a0ecSDave Kleikamp  * re-used with the upper 16 bits of the uid/gid intact
5062ac27a0ecSDave Kleikamp  */
506393e3b4e6SDaeho Jeong 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
506493e3b4e6SDaeho Jeong 			raw_inode->i_uid_high = 0;
506593e3b4e6SDaeho Jeong 			raw_inode->i_gid_high = 0;
506693e3b4e6SDaeho Jeong 		} else {
5067ac27a0ecSDave Kleikamp 			raw_inode->i_uid_high =
506808cefc7aSEric W. Biederman 				cpu_to_le16(high_16_bits(i_uid));
5069ac27a0ecSDave Kleikamp 			raw_inode->i_gid_high =
507008cefc7aSEric W. Biederman 				cpu_to_le16(high_16_bits(i_gid));
5071ac27a0ecSDave Kleikamp 		}
5072ac27a0ecSDave Kleikamp 	} else {
507308cefc7aSEric W. Biederman 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
507408cefc7aSEric W. Biederman 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
5075ac27a0ecSDave Kleikamp 		raw_inode->i_uid_high = 0;
5076ac27a0ecSDave Kleikamp 		raw_inode->i_gid_high = 0;
5077ac27a0ecSDave Kleikamp 	}
5078ac27a0ecSDave Kleikamp 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5079ef7f3835SKalpak Shah 
5080ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5081ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5082ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5083ef7f3835SKalpak Shah 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5084ef7f3835SKalpak Shah 
5085ac27a0ecSDave Kleikamp 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5086353eb83cSTheodore Ts'o 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5087ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
5088a1ddeb7eSBadari Pulavarty 		raw_inode->i_file_acl_high =
5089a1ddeb7eSBadari Pulavarty 			cpu_to_le16(ei->i_file_acl >> 32);
50907973c0c1SAneesh Kumar K.V 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5091dce8e237SQiujun Huang 	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) {
5092a48380f7SAneesh Kumar K.V 		ext4_isize_set(raw_inode, ei->i_disksize);
5093b71fc079SJan Kara 		need_datasync = 1;
5094b71fc079SJan Kara 	}
5095ac27a0ecSDave Kleikamp 	if (ei->i_disksize > 0x7fffffffULL) {
5096e2b911c5SDarrick J. Wong 		if (!ext4_has_feature_large_file(sb) ||
5097617ba13bSMingming Cao 				EXT4_SB(sb)->s_es->s_rev_level ==
5098202ee5dfSTheodore Ts'o 		    cpu_to_le32(EXT4_GOOD_OLD_REV))
5099202ee5dfSTheodore Ts'o 			set_large_file = 1;
5100ac27a0ecSDave Kleikamp 	}
5101ac27a0ecSDave Kleikamp 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5102ac27a0ecSDave Kleikamp 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5103ac27a0ecSDave Kleikamp 		if (old_valid_dev(inode->i_rdev)) {
5104ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] =
5105ac27a0ecSDave Kleikamp 				cpu_to_le32(old_encode_dev(inode->i_rdev));
5106ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] = 0;
5107ac27a0ecSDave Kleikamp 		} else {
5108ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] = 0;
5109ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] =
5110ac27a0ecSDave Kleikamp 				cpu_to_le32(new_encode_dev(inode->i_rdev));
5111ac27a0ecSDave Kleikamp 			raw_inode->i_block[2] = 0;
5112ac27a0ecSDave Kleikamp 		}
5113f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
5114de9a55b8STheodore Ts'o 		for (block = 0; block < EXT4_N_BLOCKS; block++)
5115ac27a0ecSDave Kleikamp 			raw_inode->i_block[block] = ei->i_data[block];
5116f19d5870STao Ma 	}
5117ac27a0ecSDave Kleikamp 
5118ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5119e254d1afSEryu Guan 		u64 ivers = ext4_inode_peek_iversion(inode);
5120ee73f9a5SJeff Layton 
5121ee73f9a5SJeff Layton 		raw_inode->i_disk_version = cpu_to_le32(ivers);
512225ec56b5SJean Noel Cordenner 		if (ei->i_extra_isize) {
512325ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
512425ec56b5SJean Noel Cordenner 				raw_inode->i_version_hi =
5125ee73f9a5SJeff Layton 					cpu_to_le32(ivers >> 32);
5126c4f65706STheodore Ts'o 			raw_inode->i_extra_isize =
5127c4f65706STheodore Ts'o 				cpu_to_le16(ei->i_extra_isize);
5128c4f65706STheodore Ts'o 		}
512925ec56b5SJean Noel Cordenner 	}
5130040cb378SLi Xi 
51310b7b7779SKaho Ng 	BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
5132040cb378SLi Xi 	       i_projid != EXT4_DEF_PROJID);
5133040cb378SLi Xi 
5134040cb378SLi Xi 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5135040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5136040cb378SLi Xi 		raw_inode->i_projid = cpu_to_le32(i_projid);
5137040cb378SLi Xi 
5138814525f4SDarrick J. Wong 	ext4_inode_csum_set(inode, raw_inode, ei);
5139202ee5dfSTheodore Ts'o 	spin_unlock(&ei->i_raw_lock);
51401751e8a6SLinus Torvalds 	if (inode->i_sb->s_flags & SB_LAZYTIME)
5141a26f4992STheodore Ts'o 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5142a26f4992STheodore Ts'o 					      bh->b_data);
5143202ee5dfSTheodore Ts'o 
51440390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
51457d8bd3c7SShijie Luo 	err = ext4_handle_dirty_metadata(handle, NULL, bh);
51467d8bd3c7SShijie Luo 	if (err)
51477d8bd3c7SShijie Luo 		goto out_brelse;
514819f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5149202ee5dfSTheodore Ts'o 	if (set_large_file) {
51505d601255Sliang xie 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5151202ee5dfSTheodore Ts'o 		err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5152202ee5dfSTheodore Ts'o 		if (err)
5153202ee5dfSTheodore Ts'o 			goto out_brelse;
515405c2c00fSJan Kara 		lock_buffer(EXT4_SB(sb)->s_sbh);
5155e2b911c5SDarrick J. Wong 		ext4_set_feature_large_file(sb);
515605c2c00fSJan Kara 		ext4_superblock_csum_set(sb);
515705c2c00fSJan Kara 		unlock_buffer(EXT4_SB(sb)->s_sbh);
5158202ee5dfSTheodore Ts'o 		ext4_handle_sync(handle);
5159a3f5cf14SJan Kara 		err = ext4_handle_dirty_metadata(handle, NULL,
5160a3f5cf14SJan Kara 						 EXT4_SB(sb)->s_sbh);
5161202ee5dfSTheodore Ts'o 	}
5162b71fc079SJan Kara 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5163ac27a0ecSDave Kleikamp out_brelse:
5164ac27a0ecSDave Kleikamp 	brelse(bh);
5165617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5166ac27a0ecSDave Kleikamp 	return err;
5167ac27a0ecSDave Kleikamp }
5168ac27a0ecSDave Kleikamp 
5169ac27a0ecSDave Kleikamp /*
5170617ba13bSMingming Cao  * ext4_write_inode()
5171ac27a0ecSDave Kleikamp  *
5172ac27a0ecSDave Kleikamp  * We are called from a few places:
5173ac27a0ecSDave Kleikamp  *
517487f7e416STheodore Ts'o  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5175ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
51764907cb7bSAnatol Pomozov  *   transaction to commit.
5177ac27a0ecSDave Kleikamp  *
517887f7e416STheodore Ts'o  * - Within flush work (sys_sync(), kupdate and such).
517987f7e416STheodore Ts'o  *   We wait on commit, if told to.
5180ac27a0ecSDave Kleikamp  *
518187f7e416STheodore Ts'o  * - Within iput_final() -> write_inode_now()
518287f7e416STheodore Ts'o  *   We wait on commit, if told to.
5183ac27a0ecSDave Kleikamp  *
5184ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
5185ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
518687f7e416STheodore Ts'o  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
518787f7e416STheodore Ts'o  * writeback.
5188ac27a0ecSDave Kleikamp  *
5189ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
5190ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5191ac27a0ecSDave Kleikamp  * which we are interested.
5192ac27a0ecSDave Kleikamp  *
5193ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
5194ac27a0ecSDave Kleikamp  *
5195ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
5196ac27a0ecSDave Kleikamp  *	stuff();
5197ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
5198ac27a0ecSDave Kleikamp  *
519987f7e416STheodore Ts'o  * is in error because write_inode() could occur while `stuff()' is running,
520087f7e416STheodore Ts'o  * and the new i_size will be lost.  Plus the inode will no longer be on the
520187f7e416STheodore Ts'o  * superblock's dirty inode list.
5202ac27a0ecSDave Kleikamp  */
5203a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5204ac27a0ecSDave Kleikamp {
520591ac6f43SFrank Mayhar 	int err;
520691ac6f43SFrank Mayhar 
520718f2c4fcSTheodore Ts'o 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
520818f2c4fcSTheodore Ts'o 	    sb_rdonly(inode->i_sb))
5209ac27a0ecSDave Kleikamp 		return 0;
5210ac27a0ecSDave Kleikamp 
521118f2c4fcSTheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
521218f2c4fcSTheodore Ts'o 		return -EIO;
521318f2c4fcSTheodore Ts'o 
521491ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
5215617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
5216b38bd33aSMingming Cao 			jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5217ac27a0ecSDave Kleikamp 			dump_stack();
5218ac27a0ecSDave Kleikamp 			return -EIO;
5219ac27a0ecSDave Kleikamp 		}
5220ac27a0ecSDave Kleikamp 
522110542c22SJan Kara 		/*
522210542c22SJan Kara 		 * No need to force transaction in WB_SYNC_NONE mode. Also
522310542c22SJan Kara 		 * ext4_sync_fs() will force the commit after everything is
522410542c22SJan Kara 		 * written.
522510542c22SJan Kara 		 */
522610542c22SJan Kara 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5227ac27a0ecSDave Kleikamp 			return 0;
5228ac27a0ecSDave Kleikamp 
5229aa75f4d3SHarshad Shirwadkar 		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
523018f2c4fcSTheodore Ts'o 						EXT4_I(inode)->i_sync_tid);
523191ac6f43SFrank Mayhar 	} else {
523291ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
523391ac6f43SFrank Mayhar 
52348016e29fSHarshad Shirwadkar 		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
523591ac6f43SFrank Mayhar 		if (err)
523691ac6f43SFrank Mayhar 			return err;
523710542c22SJan Kara 		/*
523810542c22SJan Kara 		 * sync(2) will flush the whole buffer cache. No need to do
523910542c22SJan Kara 		 * it here separately for each inode.
524010542c22SJan Kara 		 */
524110542c22SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5242830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
5243830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
524454d3adbcSTheodore Ts'o 			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5245c398eda0STheodore Ts'o 					       "IO error syncing inode");
5246830156c7SFrank Mayhar 			err = -EIO;
5247830156c7SFrank Mayhar 		}
5248fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
524991ac6f43SFrank Mayhar 	}
525091ac6f43SFrank Mayhar 	return err;
5251ac27a0ecSDave Kleikamp }
5252ac27a0ecSDave Kleikamp 
5253ac27a0ecSDave Kleikamp /*
525453e87268SJan Kara  * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
525553e87268SJan Kara  * buffers that are attached to a page stradding i_size and are undergoing
525653e87268SJan Kara  * commit. In that case we have to wait for commit to finish and try again.
525753e87268SJan Kara  */
525853e87268SJan Kara static void ext4_wait_for_tail_page_commit(struct inode *inode)
525953e87268SJan Kara {
526053e87268SJan Kara 	struct page *page;
526153e87268SJan Kara 	unsigned offset;
526253e87268SJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
526353e87268SJan Kara 	tid_t commit_tid = 0;
526453e87268SJan Kara 	int ret;
526553e87268SJan Kara 
526609cbfeafSKirill A. Shutemov 	offset = inode->i_size & (PAGE_SIZE - 1);
526753e87268SJan Kara 	/*
5268565333a1Syangerkun 	 * If the page is fully truncated, we don't need to wait for any commit
5269565333a1Syangerkun 	 * (and we even should not as __ext4_journalled_invalidatepage() may
5270565333a1Syangerkun 	 * strip all buffers from the page but keep the page dirty which can then
5271565333a1Syangerkun 	 * confuse e.g. concurrent ext4_writepage() seeing dirty page without
5272565333a1Syangerkun 	 * buffers). Also we don't need to wait for any commit if all buffers in
5273565333a1Syangerkun 	 * the page remain valid. This is most beneficial for the common case of
5274565333a1Syangerkun 	 * blocksize == PAGESIZE.
527553e87268SJan Kara 	 */
5276565333a1Syangerkun 	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
527753e87268SJan Kara 		return;
527853e87268SJan Kara 	while (1) {
527953e87268SJan Kara 		page = find_lock_page(inode->i_mapping,
528009cbfeafSKirill A. Shutemov 				      inode->i_size >> PAGE_SHIFT);
528153e87268SJan Kara 		if (!page)
528253e87268SJan Kara 			return;
5283ca99fdd2SLukas Czerner 		ret = __ext4_journalled_invalidatepage(page, offset,
528409cbfeafSKirill A. Shutemov 						PAGE_SIZE - offset);
528553e87268SJan Kara 		unlock_page(page);
528609cbfeafSKirill A. Shutemov 		put_page(page);
528753e87268SJan Kara 		if (ret != -EBUSY)
528853e87268SJan Kara 			return;
528953e87268SJan Kara 		commit_tid = 0;
529053e87268SJan Kara 		read_lock(&journal->j_state_lock);
529153e87268SJan Kara 		if (journal->j_committing_transaction)
529253e87268SJan Kara 			commit_tid = journal->j_committing_transaction->t_tid;
529353e87268SJan Kara 		read_unlock(&journal->j_state_lock);
529453e87268SJan Kara 		if (commit_tid)
529553e87268SJan Kara 			jbd2_log_wait_commit(journal, commit_tid);
529653e87268SJan Kara 	}
529753e87268SJan Kara }
529853e87268SJan Kara 
529953e87268SJan Kara /*
5300617ba13bSMingming Cao  * ext4_setattr()
5301ac27a0ecSDave Kleikamp  *
5302ac27a0ecSDave Kleikamp  * Called from notify_change.
5303ac27a0ecSDave Kleikamp  *
5304ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
5305ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
5306ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
5307ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
5308ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
5309ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
5310ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
5311ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
5312ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
5313ac27a0ecSDave Kleikamp  *
5314678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
5315678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
5316678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
5317678aaf48SJan Kara  * This way we are sure that all the data written in the previous
5318678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
5319678aaf48SJan Kara  * writeback).
5320678aaf48SJan Kara  *
5321678aaf48SJan Kara  * Called with inode->i_mutex down.
5322ac27a0ecSDave Kleikamp  */
5323549c7297SChristian Brauner int ext4_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5324549c7297SChristian Brauner 		 struct iattr *attr)
5325ac27a0ecSDave Kleikamp {
53262b0143b5SDavid Howells 	struct inode *inode = d_inode(dentry);
5327ac27a0ecSDave Kleikamp 	int error, rc = 0;
53283d287de3SDmitry Monakhov 	int orphan = 0;
5329ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
5330ac27a0ecSDave Kleikamp 
53310db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
53320db1ff22STheodore Ts'o 		return -EIO;
53330db1ff22STheodore Ts'o 
533402b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
533502b016caSTheodore Ts'o 		return -EPERM;
533602b016caSTheodore Ts'o 
533702b016caSTheodore Ts'o 	if (unlikely(IS_APPEND(inode) &&
533802b016caSTheodore Ts'o 		     (ia_valid & (ATTR_MODE | ATTR_UID |
533902b016caSTheodore Ts'o 				  ATTR_GID | ATTR_TIMES_SET))))
534002b016caSTheodore Ts'o 		return -EPERM;
534102b016caSTheodore Ts'o 
534214f3db55SChristian Brauner 	error = setattr_prepare(mnt_userns, dentry, attr);
5343ac27a0ecSDave Kleikamp 	if (error)
5344ac27a0ecSDave Kleikamp 		return error;
5345ac27a0ecSDave Kleikamp 
53463ce2b8ddSEric Biggers 	error = fscrypt_prepare_setattr(dentry, attr);
53473ce2b8ddSEric Biggers 	if (error)
53483ce2b8ddSEric Biggers 		return error;
53493ce2b8ddSEric Biggers 
5350c93d8f88SEric Biggers 	error = fsverity_prepare_setattr(dentry, attr);
5351c93d8f88SEric Biggers 	if (error)
5352c93d8f88SEric Biggers 		return error;
5353c93d8f88SEric Biggers 
5354a7cdadeeSJan Kara 	if (is_quota_modification(inode, attr)) {
5355a7cdadeeSJan Kara 		error = dquot_initialize(inode);
5356a7cdadeeSJan Kara 		if (error)
5357a7cdadeeSJan Kara 			return error;
5358a7cdadeeSJan Kara 	}
5359aa75f4d3SHarshad Shirwadkar 	ext4_fc_start_update(inode);
536008cefc7aSEric W. Biederman 	if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
536108cefc7aSEric W. Biederman 	    (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5362ac27a0ecSDave Kleikamp 		handle_t *handle;
5363ac27a0ecSDave Kleikamp 
5364ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
5365ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
53669924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
53679924a92aSTheodore Ts'o 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5368194074acSDmitry Monakhov 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5369ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
5370ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
5371ac27a0ecSDave Kleikamp 			goto err_out;
5372ac27a0ecSDave Kleikamp 		}
53737a9ca53aSTahsin Erdogan 
53747a9ca53aSTahsin Erdogan 		/* dquot_transfer() calls back ext4_get_inode_usage() which
53757a9ca53aSTahsin Erdogan 		 * counts xattr inode references.
53767a9ca53aSTahsin Erdogan 		 */
53777a9ca53aSTahsin Erdogan 		down_read(&EXT4_I(inode)->xattr_sem);
5378b43fa828SChristoph Hellwig 		error = dquot_transfer(inode, attr);
53797a9ca53aSTahsin Erdogan 		up_read(&EXT4_I(inode)->xattr_sem);
53807a9ca53aSTahsin Erdogan 
5381ac27a0ecSDave Kleikamp 		if (error) {
5382617ba13bSMingming Cao 			ext4_journal_stop(handle);
5383aa75f4d3SHarshad Shirwadkar 			ext4_fc_stop_update(inode);
5384ac27a0ecSDave Kleikamp 			return error;
5385ac27a0ecSDave Kleikamp 		}
5386ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
5387ac27a0ecSDave Kleikamp 		 * one transaction */
5388ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_UID)
5389ac27a0ecSDave Kleikamp 			inode->i_uid = attr->ia_uid;
5390ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_GID)
5391ac27a0ecSDave Kleikamp 			inode->i_gid = attr->ia_gid;
5392617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
5393617ba13bSMingming Cao 		ext4_journal_stop(handle);
5394512c15efSPan Bian 		if (unlikely(error)) {
5395512c15efSPan Bian 			ext4_fc_stop_update(inode);
53964209ae12SHarshad Shirwadkar 			return error;
5397ac27a0ecSDave Kleikamp 		}
5398512c15efSPan Bian 	}
5399ac27a0ecSDave Kleikamp 
54003da40c7bSJosef Bacik 	if (attr->ia_valid & ATTR_SIZE) {
54015208386cSJan Kara 		handle_t *handle;
54023da40c7bSJosef Bacik 		loff_t oldsize = inode->i_size;
5403b9c1c267SJan Kara 		int shrink = (attr->ia_size < inode->i_size);
5404562c72aaSChristoph Hellwig 
540512e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5406e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5407e2b46574SEric Sandeen 
5408aa75f4d3SHarshad Shirwadkar 			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5409aa75f4d3SHarshad Shirwadkar 				ext4_fc_stop_update(inode);
54100c095c7fSTheodore Ts'o 				return -EFBIG;
5411e2b46574SEric Sandeen 			}
5412aa75f4d3SHarshad Shirwadkar 		}
5413aa75f4d3SHarshad Shirwadkar 		if (!S_ISREG(inode->i_mode)) {
5414aa75f4d3SHarshad Shirwadkar 			ext4_fc_stop_update(inode);
54153da40c7bSJosef Bacik 			return -EINVAL;
5416aa75f4d3SHarshad Shirwadkar 		}
5417dff6efc3SChristoph Hellwig 
5418dff6efc3SChristoph Hellwig 		if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5419dff6efc3SChristoph Hellwig 			inode_inc_iversion(inode);
5420dff6efc3SChristoph Hellwig 
5421b9c1c267SJan Kara 		if (shrink) {
5422b9c1c267SJan Kara 			if (ext4_should_order_data(inode)) {
54235208386cSJan Kara 				error = ext4_begin_ordered_truncate(inode,
54245208386cSJan Kara 							    attr->ia_size);
54255208386cSJan Kara 				if (error)
54265208386cSJan Kara 					goto err_out;
54275208386cSJan Kara 			}
5428b9c1c267SJan Kara 			/*
5429b9c1c267SJan Kara 			 * Blocks are going to be removed from the inode. Wait
5430b9c1c267SJan Kara 			 * for dio in flight.
5431b9c1c267SJan Kara 			 */
5432b9c1c267SJan Kara 			inode_dio_wait(inode);
5433b9c1c267SJan Kara 		}
5434b9c1c267SJan Kara 
5435b9c1c267SJan Kara 		down_write(&EXT4_I(inode)->i_mmap_sem);
5436b9c1c267SJan Kara 
5437b9c1c267SJan Kara 		rc = ext4_break_layouts(inode);
5438b9c1c267SJan Kara 		if (rc) {
5439b9c1c267SJan Kara 			up_write(&EXT4_I(inode)->i_mmap_sem);
5440aa75f4d3SHarshad Shirwadkar 			goto err_out;
5441b9c1c267SJan Kara 		}
5442b9c1c267SJan Kara 
54433da40c7bSJosef Bacik 		if (attr->ia_size != inode->i_size) {
54449924a92aSTheodore Ts'o 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5445ac27a0ecSDave Kleikamp 			if (IS_ERR(handle)) {
5446ac27a0ecSDave Kleikamp 				error = PTR_ERR(handle);
5447b9c1c267SJan Kara 				goto out_mmap_sem;
5448ac27a0ecSDave Kleikamp 			}
54493da40c7bSJosef Bacik 			if (ext4_handle_valid(handle) && shrink) {
5450617ba13bSMingming Cao 				error = ext4_orphan_add(handle, inode);
54513d287de3SDmitry Monakhov 				orphan = 1;
54523d287de3SDmitry Monakhov 			}
5453911af577SEryu Guan 			/*
5454911af577SEryu Guan 			 * Update c/mtime on truncate up, ext4_truncate() will
5455911af577SEryu Guan 			 * update c/mtime in shrink case below
5456911af577SEryu Guan 			 */
5457911af577SEryu Guan 			if (!shrink) {
5458eeca7ea1SDeepa Dinamani 				inode->i_mtime = current_time(inode);
5459911af577SEryu Guan 				inode->i_ctime = inode->i_mtime;
5460911af577SEryu Guan 			}
5461aa75f4d3SHarshad Shirwadkar 
5462aa75f4d3SHarshad Shirwadkar 			if (shrink)
5463a80f7fcfSHarshad Shirwadkar 				ext4_fc_track_range(handle, inode,
5464aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5465aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
5466aa75f4d3SHarshad Shirwadkar 					(oldsize > 0 ? oldsize - 1 : 0) >>
5467aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits);
5468aa75f4d3SHarshad Shirwadkar 			else
5469aa75f4d3SHarshad Shirwadkar 				ext4_fc_track_range(
5470a80f7fcfSHarshad Shirwadkar 					handle, inode,
5471aa75f4d3SHarshad Shirwadkar 					(oldsize > 0 ? oldsize - 1 : oldsize) >>
5472aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits,
5473aa75f4d3SHarshad Shirwadkar 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5474aa75f4d3SHarshad Shirwadkar 					inode->i_sb->s_blocksize_bits);
5475aa75f4d3SHarshad Shirwadkar 
547690e775b7SJan Kara 			down_write(&EXT4_I(inode)->i_data_sem);
5477617ba13bSMingming Cao 			EXT4_I(inode)->i_disksize = attr->ia_size;
5478617ba13bSMingming Cao 			rc = ext4_mark_inode_dirty(handle, inode);
5479ac27a0ecSDave Kleikamp 			if (!error)
5480ac27a0ecSDave Kleikamp 				error = rc;
548190e775b7SJan Kara 			/*
548290e775b7SJan Kara 			 * We have to update i_size under i_data_sem together
548390e775b7SJan Kara 			 * with i_disksize to avoid races with writeback code
548490e775b7SJan Kara 			 * running ext4_wb_update_i_disksize().
548590e775b7SJan Kara 			 */
548690e775b7SJan Kara 			if (!error)
548790e775b7SJan Kara 				i_size_write(inode, attr->ia_size);
548890e775b7SJan Kara 			up_write(&EXT4_I(inode)->i_data_sem);
5489617ba13bSMingming Cao 			ext4_journal_stop(handle);
5490b9c1c267SJan Kara 			if (error)
5491b9c1c267SJan Kara 				goto out_mmap_sem;
549282a25b02SJan Kara 			if (!shrink) {
5493b9c1c267SJan Kara 				pagecache_isize_extended(inode, oldsize,
5494b9c1c267SJan Kara 							 inode->i_size);
5495b9c1c267SJan Kara 			} else if (ext4_should_journal_data(inode)) {
549682a25b02SJan Kara 				ext4_wait_for_tail_page_commit(inode);
5497b9c1c267SJan Kara 			}
5498430657b6SRoss Zwisler 		}
5499430657b6SRoss Zwisler 
550053e87268SJan Kara 		/*
550153e87268SJan Kara 		 * Truncate pagecache after we've waited for commit
550253e87268SJan Kara 		 * in data=journal mode to make pages freeable.
550353e87268SJan Kara 		 */
55047caef267SKirill A. Shutemov 		truncate_pagecache(inode, inode->i_size);
5505b9c1c267SJan Kara 		/*
5506b9c1c267SJan Kara 		 * Call ext4_truncate() even if i_size didn't change to
5507b9c1c267SJan Kara 		 * truncate possible preallocated blocks.
5508b9c1c267SJan Kara 		 */
5509b9c1c267SJan Kara 		if (attr->ia_size <= oldsize) {
55102c98eb5eSTheodore Ts'o 			rc = ext4_truncate(inode);
55112c98eb5eSTheodore Ts'o 			if (rc)
55122c98eb5eSTheodore Ts'o 				error = rc;
55132c98eb5eSTheodore Ts'o 		}
5514b9c1c267SJan Kara out_mmap_sem:
5515ea3d7209SJan Kara 		up_write(&EXT4_I(inode)->i_mmap_sem);
55163da40c7bSJosef Bacik 	}
5517ac27a0ecSDave Kleikamp 
55182c98eb5eSTheodore Ts'o 	if (!error) {
551914f3db55SChristian Brauner 		setattr_copy(mnt_userns, inode, attr);
55201025774cSChristoph Hellwig 		mark_inode_dirty(inode);
55211025774cSChristoph Hellwig 	}
55221025774cSChristoph Hellwig 
55231025774cSChristoph Hellwig 	/*
55241025774cSChristoph Hellwig 	 * If the call to ext4_truncate failed to get a transaction handle at
55251025774cSChristoph Hellwig 	 * all, we need to clean up the in-core orphan list manually.
55261025774cSChristoph Hellwig 	 */
55273d287de3SDmitry Monakhov 	if (orphan && inode->i_nlink)
5528617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
5529ac27a0ecSDave Kleikamp 
55302c98eb5eSTheodore Ts'o 	if (!error && (ia_valid & ATTR_MODE))
553114f3db55SChristian Brauner 		rc = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5532ac27a0ecSDave Kleikamp 
5533ac27a0ecSDave Kleikamp err_out:
5534aa75f4d3SHarshad Shirwadkar 	if  (error)
5535617ba13bSMingming Cao 		ext4_std_error(inode->i_sb, error);
5536ac27a0ecSDave Kleikamp 	if (!error)
5537ac27a0ecSDave Kleikamp 		error = rc;
5538aa75f4d3SHarshad Shirwadkar 	ext4_fc_stop_update(inode);
5539ac27a0ecSDave Kleikamp 	return error;
5540ac27a0ecSDave Kleikamp }
5541ac27a0ecSDave Kleikamp 
5542549c7297SChristian Brauner int ext4_getattr(struct user_namespace *mnt_userns, const struct path *path,
5543549c7297SChristian Brauner 		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
55443e3398a0SMingming Cao {
554599652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
554699652ea5SDavid Howells 	struct ext4_inode *raw_inode;
554799652ea5SDavid Howells 	struct ext4_inode_info *ei = EXT4_I(inode);
554899652ea5SDavid Howells 	unsigned int flags;
55493e3398a0SMingming Cao 
5550d4c5e960STheodore Ts'o 	if ((request_mask & STATX_BTIME) &&
5551d4c5e960STheodore Ts'o 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
555299652ea5SDavid Howells 		stat->result_mask |= STATX_BTIME;
555399652ea5SDavid Howells 		stat->btime.tv_sec = ei->i_crtime.tv_sec;
555499652ea5SDavid Howells 		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
555599652ea5SDavid Howells 	}
555699652ea5SDavid Howells 
555799652ea5SDavid Howells 	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
555899652ea5SDavid Howells 	if (flags & EXT4_APPEND_FL)
555999652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_APPEND;
556099652ea5SDavid Howells 	if (flags & EXT4_COMPR_FL)
556199652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_COMPRESSED;
556299652ea5SDavid Howells 	if (flags & EXT4_ENCRYPT_FL)
556399652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_ENCRYPTED;
556499652ea5SDavid Howells 	if (flags & EXT4_IMMUTABLE_FL)
556599652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_IMMUTABLE;
556699652ea5SDavid Howells 	if (flags & EXT4_NODUMP_FL)
556799652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_NODUMP;
55681f607195SEric Biggers 	if (flags & EXT4_VERITY_FL)
55691f607195SEric Biggers 		stat->attributes |= STATX_ATTR_VERITY;
557099652ea5SDavid Howells 
55713209f68bSDavid Howells 	stat->attributes_mask |= (STATX_ATTR_APPEND |
55723209f68bSDavid Howells 				  STATX_ATTR_COMPRESSED |
55733209f68bSDavid Howells 				  STATX_ATTR_ENCRYPTED |
55743209f68bSDavid Howells 				  STATX_ATTR_IMMUTABLE |
55751f607195SEric Biggers 				  STATX_ATTR_NODUMP |
55761f607195SEric Biggers 				  STATX_ATTR_VERITY);
55773209f68bSDavid Howells 
557814f3db55SChristian Brauner 	generic_fillattr(mnt_userns, inode, stat);
557999652ea5SDavid Howells 	return 0;
558099652ea5SDavid Howells }
558199652ea5SDavid Howells 
5582549c7297SChristian Brauner int ext4_file_getattr(struct user_namespace *mnt_userns,
5583549c7297SChristian Brauner 		      const struct path *path, struct kstat *stat,
558499652ea5SDavid Howells 		      u32 request_mask, unsigned int query_flags)
558599652ea5SDavid Howells {
558699652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
558799652ea5SDavid Howells 	u64 delalloc_blocks;
558899652ea5SDavid Howells 
558914f3db55SChristian Brauner 	ext4_getattr(mnt_userns, path, stat, request_mask, query_flags);
55903e3398a0SMingming Cao 
55913e3398a0SMingming Cao 	/*
55929206c561SAndreas Dilger 	 * If there is inline data in the inode, the inode will normally not
55939206c561SAndreas Dilger 	 * have data blocks allocated (it may have an external xattr block).
55949206c561SAndreas Dilger 	 * Report at least one sector for such files, so tools like tar, rsync,
5595d67d64f4STheodore Ts'o 	 * others don't incorrectly think the file is completely sparse.
55969206c561SAndreas Dilger 	 */
55979206c561SAndreas Dilger 	if (unlikely(ext4_has_inline_data(inode)))
55989206c561SAndreas Dilger 		stat->blocks += (stat->size + 511) >> 9;
55999206c561SAndreas Dilger 
56009206c561SAndreas Dilger 	/*
56013e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
56023e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
56033e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
56043e3398a0SMingming Cao 	 * on-disk file blocks.
56053e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
56063e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
56073e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
56083e3398a0SMingming Cao 	 * blocks for this file.
56093e3398a0SMingming Cao 	 */
561096607551STao Ma 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
561196607551STao Ma 				   EXT4_I(inode)->i_reserved_data_blocks);
56128af8eeccSJan Kara 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
56133e3398a0SMingming Cao 	return 0;
56143e3398a0SMingming Cao }
5615ac27a0ecSDave Kleikamp 
5616fffb2739SJan Kara static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5617fffb2739SJan Kara 				   int pextents)
5618a02908f1SMingming Cao {
561912e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5620fffb2739SJan Kara 		return ext4_ind_trans_blocks(inode, lblocks);
5621fffb2739SJan Kara 	return ext4_ext_index_trans_blocks(inode, pextents);
5622a02908f1SMingming Cao }
5623ac51d837STheodore Ts'o 
5624a02908f1SMingming Cao /*
5625a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
5626a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
5627a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
5628a02908f1SMingming Cao  *
5629a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
56304907cb7bSAnatol Pomozov  * different block groups too. If they are contiguous, with flexbg,
5631a02908f1SMingming Cao  * they could still across block group boundary.
5632a02908f1SMingming Cao  *
5633a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
5634a02908f1SMingming Cao  */
5635dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5636fffb2739SJan Kara 				  int pextents)
5637a02908f1SMingming Cao {
56388df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
56398df9675fSTheodore Ts'o 	int gdpblocks;
5640a02908f1SMingming Cao 	int idxblocks;
5641a02908f1SMingming Cao 	int ret = 0;
5642a02908f1SMingming Cao 
5643a02908f1SMingming Cao 	/*
5644fffb2739SJan Kara 	 * How many index blocks need to touch to map @lblocks logical blocks
5645fffb2739SJan Kara 	 * to @pextents physical extents?
5646a02908f1SMingming Cao 	 */
5647fffb2739SJan Kara 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5648a02908f1SMingming Cao 
5649a02908f1SMingming Cao 	ret = idxblocks;
5650a02908f1SMingming Cao 
5651a02908f1SMingming Cao 	/*
5652a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
5653a02908f1SMingming Cao 	 * to account
5654a02908f1SMingming Cao 	 */
5655fffb2739SJan Kara 	groups = idxblocks + pextents;
5656a02908f1SMingming Cao 	gdpblocks = groups;
56578df9675fSTheodore Ts'o 	if (groups > ngroups)
56588df9675fSTheodore Ts'o 		groups = ngroups;
5659a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5660a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5661a02908f1SMingming Cao 
5662a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
5663a02908f1SMingming Cao 	ret += groups + gdpblocks;
5664a02908f1SMingming Cao 
5665a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
5666a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5667ac27a0ecSDave Kleikamp 
5668ac27a0ecSDave Kleikamp 	return ret;
5669ac27a0ecSDave Kleikamp }
5670ac27a0ecSDave Kleikamp 
5671ac27a0ecSDave Kleikamp /*
567225985edcSLucas De Marchi  * Calculate the total number of credits to reserve to fit
5673f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
5674f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
5675a02908f1SMingming Cao  *
5676525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
5677a02908f1SMingming Cao  *
5678525f4ed8SMingming Cao  * We need to consider the worse case, when
5679a02908f1SMingming Cao  * one new block per extent.
5680a02908f1SMingming Cao  */
5681a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
5682a02908f1SMingming Cao {
5683a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
5684a02908f1SMingming Cao 	int ret;
5685a02908f1SMingming Cao 
5686fffb2739SJan Kara 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5687a02908f1SMingming Cao 
5688a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
5689a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
5690a02908f1SMingming Cao 		ret += bpp;
5691a02908f1SMingming Cao 	return ret;
5692a02908f1SMingming Cao }
5693f3bd1f3fSMingming Cao 
5694f3bd1f3fSMingming Cao /*
5695f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
5696f3bd1f3fSMingming Cao  *
5697f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
569879e83036SEric Sandeen  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5699f3bd1f3fSMingming Cao  *
5700f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
5701f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
5702f3bd1f3fSMingming Cao  */
5703f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5704f3bd1f3fSMingming Cao {
5705f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5706f3bd1f3fSMingming Cao }
5707f3bd1f3fSMingming Cao 
5708a02908f1SMingming Cao /*
5709617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
5710ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
5711ac27a0ecSDave Kleikamp  */
5712617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
5713617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
5714ac27a0ecSDave Kleikamp {
5715ac27a0ecSDave Kleikamp 	int err = 0;
5716ac27a0ecSDave Kleikamp 
5717a6758309SVasily Averin 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5718a6758309SVasily Averin 		put_bh(iloc->bh);
57190db1ff22STheodore Ts'o 		return -EIO;
5720a6758309SVasily Averin 	}
5721a80f7fcfSHarshad Shirwadkar 	ext4_fc_track_inode(handle, inode);
5722aa75f4d3SHarshad Shirwadkar 
5723c64db50eSTheodore Ts'o 	if (IS_I_VERSION(inode))
572425ec56b5SJean Noel Cordenner 		inode_inc_iversion(inode);
572525ec56b5SJean Noel Cordenner 
5726ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
5727ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
5728ac27a0ecSDave Kleikamp 
5729dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5730830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
5731ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
5732ac27a0ecSDave Kleikamp 	return err;
5733ac27a0ecSDave Kleikamp }
5734ac27a0ecSDave Kleikamp 
5735ac27a0ecSDave Kleikamp /*
5736ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
5737ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
5738ac27a0ecSDave Kleikamp  */
5739ac27a0ecSDave Kleikamp 
5740ac27a0ecSDave Kleikamp int
5741617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5742617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
5743ac27a0ecSDave Kleikamp {
57440390131bSFrank Mayhar 	int err;
57450390131bSFrank Mayhar 
57460db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
57470db1ff22STheodore Ts'o 		return -EIO;
57480db1ff22STheodore Ts'o 
5749617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
5750ac27a0ecSDave Kleikamp 	if (!err) {
5751ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
5752617ba13bSMingming Cao 		err = ext4_journal_get_write_access(handle, iloc->bh);
5753ac27a0ecSDave Kleikamp 		if (err) {
5754ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
5755ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
5756ac27a0ecSDave Kleikamp 		}
5757ac27a0ecSDave Kleikamp 	}
5758617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5759ac27a0ecSDave Kleikamp 	return err;
5760ac27a0ecSDave Kleikamp }
5761ac27a0ecSDave Kleikamp 
5762c03b45b8SMiao Xie static int __ext4_expand_extra_isize(struct inode *inode,
5763c03b45b8SMiao Xie 				     unsigned int new_extra_isize,
5764c03b45b8SMiao Xie 				     struct ext4_iloc *iloc,
5765c03b45b8SMiao Xie 				     handle_t *handle, int *no_expand)
5766c03b45b8SMiao Xie {
5767c03b45b8SMiao Xie 	struct ext4_inode *raw_inode;
5768c03b45b8SMiao Xie 	struct ext4_xattr_ibody_header *header;
57694ea99936STheodore Ts'o 	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
57704ea99936STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
5771c03b45b8SMiao Xie 	int error;
5772c03b45b8SMiao Xie 
57734ea99936STheodore Ts'o 	/* this was checked at iget time, but double check for good measure */
57744ea99936STheodore Ts'o 	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
57754ea99936STheodore Ts'o 	    (ei->i_extra_isize & 3)) {
57764ea99936STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
57774ea99936STheodore Ts'o 				 ei->i_extra_isize,
57784ea99936STheodore Ts'o 				 EXT4_INODE_SIZE(inode->i_sb));
57794ea99936STheodore Ts'o 		return -EFSCORRUPTED;
57804ea99936STheodore Ts'o 	}
57814ea99936STheodore Ts'o 	if ((new_extra_isize < ei->i_extra_isize) ||
57824ea99936STheodore Ts'o 	    (new_extra_isize < 4) ||
57834ea99936STheodore Ts'o 	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
57844ea99936STheodore Ts'o 		return -EINVAL;	/* Should never happen */
57854ea99936STheodore Ts'o 
5786c03b45b8SMiao Xie 	raw_inode = ext4_raw_inode(iloc);
5787c03b45b8SMiao Xie 
5788c03b45b8SMiao Xie 	header = IHDR(inode, raw_inode);
5789c03b45b8SMiao Xie 
5790c03b45b8SMiao Xie 	/* No extended attributes present */
5791c03b45b8SMiao Xie 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5792c03b45b8SMiao Xie 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5793c03b45b8SMiao Xie 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5794c03b45b8SMiao Xie 		       EXT4_I(inode)->i_extra_isize, 0,
5795c03b45b8SMiao Xie 		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
5796c03b45b8SMiao Xie 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
5797c03b45b8SMiao Xie 		return 0;
5798c03b45b8SMiao Xie 	}
5799c03b45b8SMiao Xie 
5800c03b45b8SMiao Xie 	/* try to expand with EAs present */
5801c03b45b8SMiao Xie 	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5802c03b45b8SMiao Xie 					   raw_inode, handle);
5803c03b45b8SMiao Xie 	if (error) {
5804c03b45b8SMiao Xie 		/*
5805c03b45b8SMiao Xie 		 * Inode size expansion failed; don't try again
5806c03b45b8SMiao Xie 		 */
5807c03b45b8SMiao Xie 		*no_expand = 1;
5808c03b45b8SMiao Xie 	}
5809c03b45b8SMiao Xie 
5810c03b45b8SMiao Xie 	return error;
5811c03b45b8SMiao Xie }
5812c03b45b8SMiao Xie 
5813ac27a0ecSDave Kleikamp /*
58146dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
58156dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
58166dd4ee7cSKalpak Shah  */
5817cf0a5e81SMiao Xie static int ext4_try_to_expand_extra_isize(struct inode *inode,
58181d03ec98SAneesh Kumar K.V 					  unsigned int new_extra_isize,
58191d03ec98SAneesh Kumar K.V 					  struct ext4_iloc iloc,
58201d03ec98SAneesh Kumar K.V 					  handle_t *handle)
58216dd4ee7cSKalpak Shah {
58223b10fdc6SMiao Xie 	int no_expand;
58233b10fdc6SMiao Xie 	int error;
58246dd4ee7cSKalpak Shah 
5825cf0a5e81SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5826cf0a5e81SMiao Xie 		return -EOVERFLOW;
5827cf0a5e81SMiao Xie 
5828cf0a5e81SMiao Xie 	/*
5829cf0a5e81SMiao Xie 	 * In nojournal mode, we can immediately attempt to expand
5830cf0a5e81SMiao Xie 	 * the inode.  When journaled, we first need to obtain extra
5831cf0a5e81SMiao Xie 	 * buffer credits since we may write into the EA block
5832cf0a5e81SMiao Xie 	 * with this same handle. If journal_extend fails, then it will
5833cf0a5e81SMiao Xie 	 * only result in a minor loss of functionality for that inode.
5834cf0a5e81SMiao Xie 	 * If this is felt to be critical, then e2fsck should be run to
5835cf0a5e81SMiao Xie 	 * force a large enough s_min_extra_isize.
5836cf0a5e81SMiao Xie 	 */
58376cb367c2SJan Kara 	if (ext4_journal_extend(handle,
583883448bdfSJan Kara 				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5839cf0a5e81SMiao Xie 		return -ENOSPC;
58406dd4ee7cSKalpak Shah 
58413b10fdc6SMiao Xie 	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5842cf0a5e81SMiao Xie 		return -EBUSY;
58433b10fdc6SMiao Xie 
5844c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5845c03b45b8SMiao Xie 					  handle, &no_expand);
58463b10fdc6SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5847c03b45b8SMiao Xie 
5848c03b45b8SMiao Xie 	return error;
58496dd4ee7cSKalpak Shah }
58506dd4ee7cSKalpak Shah 
5851c03b45b8SMiao Xie int ext4_expand_extra_isize(struct inode *inode,
5852c03b45b8SMiao Xie 			    unsigned int new_extra_isize,
5853c03b45b8SMiao Xie 			    struct ext4_iloc *iloc)
5854c03b45b8SMiao Xie {
5855c03b45b8SMiao Xie 	handle_t *handle;
5856c03b45b8SMiao Xie 	int no_expand;
5857c03b45b8SMiao Xie 	int error, rc;
5858c03b45b8SMiao Xie 
5859c03b45b8SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5860c03b45b8SMiao Xie 		brelse(iloc->bh);
5861c03b45b8SMiao Xie 		return -EOVERFLOW;
5862c03b45b8SMiao Xie 	}
5863c03b45b8SMiao Xie 
5864c03b45b8SMiao Xie 	handle = ext4_journal_start(inode, EXT4_HT_INODE,
5865c03b45b8SMiao Xie 				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5866c03b45b8SMiao Xie 	if (IS_ERR(handle)) {
5867c03b45b8SMiao Xie 		error = PTR_ERR(handle);
5868c03b45b8SMiao Xie 		brelse(iloc->bh);
5869c03b45b8SMiao Xie 		return error;
5870c03b45b8SMiao Xie 	}
5871c03b45b8SMiao Xie 
5872c03b45b8SMiao Xie 	ext4_write_lock_xattr(inode, &no_expand);
5873c03b45b8SMiao Xie 
5874ddccb6dbSzhangyi (F) 	BUFFER_TRACE(iloc->bh, "get_write_access");
5875c03b45b8SMiao Xie 	error = ext4_journal_get_write_access(handle, iloc->bh);
58763b10fdc6SMiao Xie 	if (error) {
5877c03b45b8SMiao Xie 		brelse(iloc->bh);
58787f420d64SDan Carpenter 		goto out_unlock;
58793b10fdc6SMiao Xie 	}
5880cf0a5e81SMiao Xie 
5881c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5882c03b45b8SMiao Xie 					  handle, &no_expand);
5883c03b45b8SMiao Xie 
5884c03b45b8SMiao Xie 	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5885c03b45b8SMiao Xie 	if (!error)
5886c03b45b8SMiao Xie 		error = rc;
5887c03b45b8SMiao Xie 
58887f420d64SDan Carpenter out_unlock:
5889c03b45b8SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5890c03b45b8SMiao Xie 	ext4_journal_stop(handle);
58913b10fdc6SMiao Xie 	return error;
58926dd4ee7cSKalpak Shah }
58936dd4ee7cSKalpak Shah 
58946dd4ee7cSKalpak Shah /*
5895ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
5896ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
5897ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
5898ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
5899ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
5900ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
5901ac27a0ecSDave Kleikamp  *
5902ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
5903ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
5904ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5905ac27a0ecSDave Kleikamp  * we start and wait on commits.
5906ac27a0ecSDave Kleikamp  */
59074209ae12SHarshad Shirwadkar int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
59084209ae12SHarshad Shirwadkar 				const char *func, unsigned int line)
5909ac27a0ecSDave Kleikamp {
5910617ba13bSMingming Cao 	struct ext4_iloc iloc;
59116dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5912cf0a5e81SMiao Xie 	int err;
5913ac27a0ecSDave Kleikamp 
5914ac27a0ecSDave Kleikamp 	might_sleep();
59157ff9c073STheodore Ts'o 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5916617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
59175e1021f2SEryu Guan 	if (err)
59184209ae12SHarshad Shirwadkar 		goto out;
5919cf0a5e81SMiao Xie 
5920cf0a5e81SMiao Xie 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5921cf0a5e81SMiao Xie 		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
59226dd4ee7cSKalpak Shah 					       iloc, handle);
5923cf0a5e81SMiao Xie 
59244209ae12SHarshad Shirwadkar 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
59254209ae12SHarshad Shirwadkar out:
59264209ae12SHarshad Shirwadkar 	if (unlikely(err))
59274209ae12SHarshad Shirwadkar 		ext4_error_inode_err(inode, func, line, 0, err,
59284209ae12SHarshad Shirwadkar 					"mark_inode_dirty error");
59294209ae12SHarshad Shirwadkar 	return err;
5930ac27a0ecSDave Kleikamp }
5931ac27a0ecSDave Kleikamp 
5932ac27a0ecSDave Kleikamp /*
5933617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
5934ac27a0ecSDave Kleikamp  *
5935ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
5936ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
5937ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
5938ac27a0ecSDave Kleikamp  *
59395dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
5940ac27a0ecSDave Kleikamp  * are allocated to the file.
5941ac27a0ecSDave Kleikamp  *
5942ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
5943ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
5944ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
5945ac27a0ecSDave Kleikamp  */
5946aa385729SChristoph Hellwig void ext4_dirty_inode(struct inode *inode, int flags)
5947ac27a0ecSDave Kleikamp {
5948ac27a0ecSDave Kleikamp 	handle_t *handle;
5949ac27a0ecSDave Kleikamp 
59509924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5951ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5952ac27a0ecSDave Kleikamp 		return;
5953e2728c56SEric Biggers 	ext4_mark_inode_dirty(handle, inode);
5954e2728c56SEric Biggers 	ext4_journal_stop(handle);
5955ac27a0ecSDave Kleikamp }
5956ac27a0ecSDave Kleikamp 
5957617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
5958ac27a0ecSDave Kleikamp {
5959ac27a0ecSDave Kleikamp 	journal_t *journal;
5960ac27a0ecSDave Kleikamp 	handle_t *handle;
5961ac27a0ecSDave Kleikamp 	int err;
5962c8585c6fSDaeho Jeong 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5963ac27a0ecSDave Kleikamp 
5964ac27a0ecSDave Kleikamp 	/*
5965ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
5966ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
5967ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
5968ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
5969ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
5970ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
5971ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
5972ac27a0ecSDave Kleikamp 	 */
5973ac27a0ecSDave Kleikamp 
5974617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
59750390131bSFrank Mayhar 	if (!journal)
59760390131bSFrank Mayhar 		return 0;
5977d699594dSDave Hansen 	if (is_journal_aborted(journal))
5978ac27a0ecSDave Kleikamp 		return -EROFS;
5979ac27a0ecSDave Kleikamp 
598017335dccSDmitry Monakhov 	/* Wait for all existing dio workers */
598117335dccSDmitry Monakhov 	inode_dio_wait(inode);
598217335dccSDmitry Monakhov 
59834c546592SDaeho Jeong 	/*
59844c546592SDaeho Jeong 	 * Before flushing the journal and switching inode's aops, we have
59854c546592SDaeho Jeong 	 * to flush all dirty data the inode has. There can be outstanding
59864c546592SDaeho Jeong 	 * delayed allocations, there can be unwritten extents created by
59874c546592SDaeho Jeong 	 * fallocate or buffered writes in dioread_nolock mode covered by
59884c546592SDaeho Jeong 	 * dirty data which can be converted only after flushing the dirty
59894c546592SDaeho Jeong 	 * data (and journalled aops don't know how to handle these cases).
59904c546592SDaeho Jeong 	 */
59914c546592SDaeho Jeong 	if (val) {
59924c546592SDaeho Jeong 		down_write(&EXT4_I(inode)->i_mmap_sem);
59934c546592SDaeho Jeong 		err = filemap_write_and_wait(inode->i_mapping);
59944c546592SDaeho Jeong 		if (err < 0) {
59954c546592SDaeho Jeong 			up_write(&EXT4_I(inode)->i_mmap_sem);
59964c546592SDaeho Jeong 			return err;
59974c546592SDaeho Jeong 		}
59984c546592SDaeho Jeong 	}
59994c546592SDaeho Jeong 
6000bbd55937SEric Biggers 	percpu_down_write(&sbi->s_writepages_rwsem);
6001dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
6002ac27a0ecSDave Kleikamp 
6003ac27a0ecSDave Kleikamp 	/*
6004ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
6005ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
6006ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
6007ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
6008ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
6009ac27a0ecSDave Kleikamp 	 */
6010ac27a0ecSDave Kleikamp 
6011ac27a0ecSDave Kleikamp 	if (val)
601212e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60135872ddaaSYongqiang Yang 	else {
601401d5d965SLeah Rumancik 		err = jbd2_journal_flush(journal, 0);
60154f879ca6SJan Kara 		if (err < 0) {
60164f879ca6SJan Kara 			jbd2_journal_unlock_updates(journal);
6017bbd55937SEric Biggers 			percpu_up_write(&sbi->s_writepages_rwsem);
60184f879ca6SJan Kara 			return err;
60194f879ca6SJan Kara 		}
602012e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
60215872ddaaSYongqiang Yang 	}
6022617ba13bSMingming Cao 	ext4_set_aops(inode);
6023ac27a0ecSDave Kleikamp 
6024dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
6025bbd55937SEric Biggers 	percpu_up_write(&sbi->s_writepages_rwsem);
6026c8585c6fSDaeho Jeong 
60274c546592SDaeho Jeong 	if (val)
60284c546592SDaeho Jeong 		up_write(&EXT4_I(inode)->i_mmap_sem);
6029ac27a0ecSDave Kleikamp 
6030ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
6031ac27a0ecSDave Kleikamp 
60329924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6033ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
6034ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
6035ac27a0ecSDave Kleikamp 
6036aa75f4d3SHarshad Shirwadkar 	ext4_fc_mark_ineligible(inode->i_sb,
6037aa75f4d3SHarshad Shirwadkar 		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE);
6038617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
60390390131bSFrank Mayhar 	ext4_handle_sync(handle);
6040617ba13bSMingming Cao 	ext4_journal_stop(handle);
6041617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
6042ac27a0ecSDave Kleikamp 
6043ac27a0ecSDave Kleikamp 	return err;
6044ac27a0ecSDave Kleikamp }
60452e9ee850SAneesh Kumar K.V 
60462e9ee850SAneesh Kumar K.V static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
60472e9ee850SAneesh Kumar K.V {
60482e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
60492e9ee850SAneesh Kumar K.V }
60502e9ee850SAneesh Kumar K.V 
6051401b25aaSSouptick Joarder vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
60522e9ee850SAneesh Kumar K.V {
605311bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
6054c2ec175cSNick Piggin 	struct page *page = vmf->page;
60552e9ee850SAneesh Kumar K.V 	loff_t size;
60562e9ee850SAneesh Kumar K.V 	unsigned long len;
6057401b25aaSSouptick Joarder 	int err;
6058401b25aaSSouptick Joarder 	vm_fault_t ret;
60592e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
6060496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
60612e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
60629ea7df53SJan Kara 	handle_t *handle;
60639ea7df53SJan Kara 	get_block_t *get_block;
60649ea7df53SJan Kara 	int retries = 0;
60652e9ee850SAneesh Kumar K.V 
606602b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
606702b016caSTheodore Ts'o 		return VM_FAULT_SIGBUS;
606802b016caSTheodore Ts'o 
60698e8ad8a5SJan Kara 	sb_start_pagefault(inode->i_sb);
6070041bbb6dSTheodore Ts'o 	file_update_time(vma->vm_file);
6071ea3d7209SJan Kara 
6072ea3d7209SJan Kara 	down_read(&EXT4_I(inode)->i_mmap_sem);
60737b4cc978SEric Biggers 
6074401b25aaSSouptick Joarder 	err = ext4_convert_inline_data(inode);
6075401b25aaSSouptick Joarder 	if (err)
60767b4cc978SEric Biggers 		goto out_ret;
60777b4cc978SEric Biggers 
607864a9f144SMauricio Faria de Oliveira 	/*
607964a9f144SMauricio Faria de Oliveira 	 * On data journalling we skip straight to the transaction handle:
608064a9f144SMauricio Faria de Oliveira 	 * there's no delalloc; page truncated will be checked later; the
608164a9f144SMauricio Faria de Oliveira 	 * early return w/ all buffers mapped (calculates size/len) can't
608264a9f144SMauricio Faria de Oliveira 	 * be used; and there's no dioread_nolock, so only ext4_get_block.
608364a9f144SMauricio Faria de Oliveira 	 */
608464a9f144SMauricio Faria de Oliveira 	if (ext4_should_journal_data(inode))
608564a9f144SMauricio Faria de Oliveira 		goto retry_alloc;
608664a9f144SMauricio Faria de Oliveira 
60879ea7df53SJan Kara 	/* Delalloc case is easy... */
60889ea7df53SJan Kara 	if (test_opt(inode->i_sb, DELALLOC) &&
60899ea7df53SJan Kara 	    !ext4_nonda_switch(inode->i_sb)) {
60909ea7df53SJan Kara 		do {
6091401b25aaSSouptick Joarder 			err = block_page_mkwrite(vma, vmf,
60929ea7df53SJan Kara 						   ext4_da_get_block_prep);
6093401b25aaSSouptick Joarder 		} while (err == -ENOSPC &&
60949ea7df53SJan Kara 		       ext4_should_retry_alloc(inode->i_sb, &retries));
60959ea7df53SJan Kara 		goto out_ret;
60962e9ee850SAneesh Kumar K.V 	}
60970e499890SDarrick J. Wong 
60980e499890SDarrick J. Wong 	lock_page(page);
60999ea7df53SJan Kara 	size = i_size_read(inode);
61009ea7df53SJan Kara 	/* Page got truncated from under us? */
61019ea7df53SJan Kara 	if (page->mapping != mapping || page_offset(page) > size) {
61029ea7df53SJan Kara 		unlock_page(page);
61039ea7df53SJan Kara 		ret = VM_FAULT_NOPAGE;
61049ea7df53SJan Kara 		goto out;
61050e499890SDarrick J. Wong 	}
61062e9ee850SAneesh Kumar K.V 
610709cbfeafSKirill A. Shutemov 	if (page->index == size >> PAGE_SHIFT)
610809cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
61092e9ee850SAneesh Kumar K.V 	else
611009cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
6111a827eaffSAneesh Kumar K.V 	/*
61129ea7df53SJan Kara 	 * Return if we have all the buffers mapped. This avoids the need to do
61139ea7df53SJan Kara 	 * journal_start/journal_stop which can block and take a long time
611464a9f144SMauricio Faria de Oliveira 	 *
611564a9f144SMauricio Faria de Oliveira 	 * This cannot be done for data journalling, as we have to add the
611664a9f144SMauricio Faria de Oliveira 	 * inode to the transaction's list to writeprotect pages on commit.
6117a827eaffSAneesh Kumar K.V 	 */
61182e9ee850SAneesh Kumar K.V 	if (page_has_buffers(page)) {
6119f19d5870STao Ma 		if (!ext4_walk_page_buffers(NULL, page_buffers(page),
6120f19d5870STao Ma 					    0, len, NULL,
6121a827eaffSAneesh Kumar K.V 					    ext4_bh_unmapped)) {
61229ea7df53SJan Kara 			/* Wait so that we don't change page under IO */
61231d1d1a76SDarrick J. Wong 			wait_for_stable_page(page);
61249ea7df53SJan Kara 			ret = VM_FAULT_LOCKED;
61259ea7df53SJan Kara 			goto out;
61262e9ee850SAneesh Kumar K.V 		}
6127a827eaffSAneesh Kumar K.V 	}
6128a827eaffSAneesh Kumar K.V 	unlock_page(page);
61299ea7df53SJan Kara 	/* OK, we need to fill the hole... */
61309ea7df53SJan Kara 	if (ext4_should_dioread_nolock(inode))
6131705965bdSJan Kara 		get_block = ext4_get_block_unwritten;
61329ea7df53SJan Kara 	else
61339ea7df53SJan Kara 		get_block = ext4_get_block;
61349ea7df53SJan Kara retry_alloc:
61359924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
61369924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
61379ea7df53SJan Kara 	if (IS_ERR(handle)) {
6138c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
61399ea7df53SJan Kara 		goto out;
61409ea7df53SJan Kara 	}
614164a9f144SMauricio Faria de Oliveira 	/*
614264a9f144SMauricio Faria de Oliveira 	 * Data journalling can't use block_page_mkwrite() because it
614364a9f144SMauricio Faria de Oliveira 	 * will set_buffer_dirty() before do_journal_get_write_access()
614464a9f144SMauricio Faria de Oliveira 	 * thus might hit warning messages for dirty metadata buffers.
614564a9f144SMauricio Faria de Oliveira 	 */
614664a9f144SMauricio Faria de Oliveira 	if (!ext4_should_journal_data(inode)) {
6147401b25aaSSouptick Joarder 		err = block_page_mkwrite(vma, vmf, get_block);
614864a9f144SMauricio Faria de Oliveira 	} else {
614964a9f144SMauricio Faria de Oliveira 		lock_page(page);
615064a9f144SMauricio Faria de Oliveira 		size = i_size_read(inode);
615164a9f144SMauricio Faria de Oliveira 		/* Page got truncated from under us? */
615264a9f144SMauricio Faria de Oliveira 		if (page->mapping != mapping || page_offset(page) > size) {
615364a9f144SMauricio Faria de Oliveira 			ret = VM_FAULT_NOPAGE;
6154afb585a9SMauricio Faria de Oliveira 			goto out_error;
615564a9f144SMauricio Faria de Oliveira 		}
615664a9f144SMauricio Faria de Oliveira 
615764a9f144SMauricio Faria de Oliveira 		if (page->index == size >> PAGE_SHIFT)
615864a9f144SMauricio Faria de Oliveira 			len = size & ~PAGE_MASK;
615964a9f144SMauricio Faria de Oliveira 		else
616064a9f144SMauricio Faria de Oliveira 			len = PAGE_SIZE;
616164a9f144SMauricio Faria de Oliveira 
616264a9f144SMauricio Faria de Oliveira 		err = __block_write_begin(page, 0, len, ext4_get_block);
616364a9f144SMauricio Faria de Oliveira 		if (!err) {
61649ea7df53SJan Kara 			ret = VM_FAULT_SIGBUS;
6165afb585a9SMauricio Faria de Oliveira 			if (ext4_walk_page_buffers(handle, page_buffers(page),
6166afb585a9SMauricio Faria de Oliveira 					0, len, NULL, do_journal_get_write_access))
6167afb585a9SMauricio Faria de Oliveira 				goto out_error;
6168afb585a9SMauricio Faria de Oliveira 			if (ext4_walk_page_buffers(handle, page_buffers(page),
6169afb585a9SMauricio Faria de Oliveira 					0, len, NULL, write_end_fn))
6170afb585a9SMauricio Faria de Oliveira 				goto out_error;
6171b5b18160SJan Kara 			if (ext4_jbd2_inode_add_write(handle, inode,
6172b5b18160SJan Kara 						      page_offset(page), len))
6173afb585a9SMauricio Faria de Oliveira 				goto out_error;
61749ea7df53SJan Kara 			ext4_set_inode_state(inode, EXT4_STATE_JDATA);
617564a9f144SMauricio Faria de Oliveira 		} else {
617664a9f144SMauricio Faria de Oliveira 			unlock_page(page);
617764a9f144SMauricio Faria de Oliveira 		}
61789ea7df53SJan Kara 	}
61799ea7df53SJan Kara 	ext4_journal_stop(handle);
6180401b25aaSSouptick Joarder 	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
61819ea7df53SJan Kara 		goto retry_alloc;
61829ea7df53SJan Kara out_ret:
6183401b25aaSSouptick Joarder 	ret = block_page_mkwrite_return(err);
61849ea7df53SJan Kara out:
6185ea3d7209SJan Kara 	up_read(&EXT4_I(inode)->i_mmap_sem);
61868e8ad8a5SJan Kara 	sb_end_pagefault(inode->i_sb);
61872e9ee850SAneesh Kumar K.V 	return ret;
6188afb585a9SMauricio Faria de Oliveira out_error:
6189afb585a9SMauricio Faria de Oliveira 	unlock_page(page);
6190afb585a9SMauricio Faria de Oliveira 	ext4_journal_stop(handle);
6191afb585a9SMauricio Faria de Oliveira 	goto out;
61922e9ee850SAneesh Kumar K.V }
6193ea3d7209SJan Kara 
6194401b25aaSSouptick Joarder vm_fault_t ext4_filemap_fault(struct vm_fault *vmf)
6195ea3d7209SJan Kara {
619611bac800SDave Jiang 	struct inode *inode = file_inode(vmf->vma->vm_file);
6197401b25aaSSouptick Joarder 	vm_fault_t ret;
6198ea3d7209SJan Kara 
6199ea3d7209SJan Kara 	down_read(&EXT4_I(inode)->i_mmap_sem);
6200401b25aaSSouptick Joarder 	ret = filemap_fault(vmf);
6201ea3d7209SJan Kara 	up_read(&EXT4_I(inode)->i_mmap_sem);
6202ea3d7209SJan Kara 
6203401b25aaSSouptick Joarder 	return ret;
6204ea3d7209SJan Kara }
6205