xref: /openbmc/linux/fs/ext4/inode.c (revision 9e52484c713321e84e8834803a44ca0a001376d2)
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>
23ac27a0ecSDave Kleikamp #include <linux/time.h>
24ac27a0ecSDave Kleikamp #include <linux/highuid.h>
25ac27a0ecSDave Kleikamp #include <linux/pagemap.h>
26c94c2acfSMatthew Wilcox #include <linux/dax.h>
27ac27a0ecSDave Kleikamp #include <linux/quotaops.h>
28ac27a0ecSDave Kleikamp #include <linux/string.h>
29ac27a0ecSDave Kleikamp #include <linux/buffer_head.h>
30ac27a0ecSDave Kleikamp #include <linux/writeback.h>
3164769240SAlex Tomas #include <linux/pagevec.h>
32ac27a0ecSDave Kleikamp #include <linux/mpage.h>
33e83c1397SDuane Griffin #include <linux/namei.h>
34ac27a0ecSDave Kleikamp #include <linux/uio.h>
35ac27a0ecSDave Kleikamp #include <linux/bio.h>
364c0425ffSMingming Cao #include <linux/workqueue.h>
37744692dcSJiaying Zhang #include <linux/kernel.h>
386db26ffcSAndrew Morton #include <linux/printk.h>
395a0e3ad6STejun Heo #include <linux/slab.h>
4000a1a053STheodore Ts'o #include <linux/bitops.h>
41364443cbSJan Kara #include <linux/iomap.h>
42ae5e165dSJeff Layton #include <linux/iversion.h>
439bffad1eSTheodore Ts'o 
443dcf5451SChristoph Hellwig #include "ext4_jbd2.h"
45ac27a0ecSDave Kleikamp #include "xattr.h"
46ac27a0ecSDave Kleikamp #include "acl.h"
479f125d64STheodore Ts'o #include "truncate.h"
48ac27a0ecSDave Kleikamp 
499bffad1eSTheodore Ts'o #include <trace/events/ext4.h>
509bffad1eSTheodore Ts'o 
51814525f4SDarrick J. Wong static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
52814525f4SDarrick J. Wong 			      struct ext4_inode_info *ei)
53814525f4SDarrick J. Wong {
54814525f4SDarrick J. Wong 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
55814525f4SDarrick J. Wong 	__u32 csum;
56b47820edSDaeho Jeong 	__u16 dummy_csum = 0;
57b47820edSDaeho Jeong 	int offset = offsetof(struct ext4_inode, i_checksum_lo);
58b47820edSDaeho Jeong 	unsigned int csum_size = sizeof(dummy_csum);
59814525f4SDarrick J. Wong 
60b47820edSDaeho Jeong 	csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
61b47820edSDaeho Jeong 	csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
62b47820edSDaeho Jeong 	offset += csum_size;
63b47820edSDaeho Jeong 	csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
64b47820edSDaeho Jeong 			   EXT4_GOOD_OLD_INODE_SIZE - offset);
65b47820edSDaeho Jeong 
66b47820edSDaeho Jeong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
67b47820edSDaeho Jeong 		offset = offsetof(struct ext4_inode, i_checksum_hi);
68b47820edSDaeho Jeong 		csum = ext4_chksum(sbi, csum, (__u8 *)raw +
69b47820edSDaeho Jeong 				   EXT4_GOOD_OLD_INODE_SIZE,
70b47820edSDaeho Jeong 				   offset - EXT4_GOOD_OLD_INODE_SIZE);
71b47820edSDaeho Jeong 		if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
72b47820edSDaeho Jeong 			csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
73b47820edSDaeho Jeong 					   csum_size);
74b47820edSDaeho Jeong 			offset += csum_size;
75814525f4SDarrick J. Wong 		}
7605ac5aa1SDaeho Jeong 		csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
7705ac5aa1SDaeho Jeong 				   EXT4_INODE_SIZE(inode->i_sb) - offset);
78b47820edSDaeho Jeong 	}
79814525f4SDarrick J. Wong 
80814525f4SDarrick J. Wong 	return csum;
81814525f4SDarrick J. Wong }
82814525f4SDarrick J. Wong 
83814525f4SDarrick J. Wong static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
84814525f4SDarrick J. Wong 				  struct ext4_inode_info *ei)
85814525f4SDarrick J. Wong {
86814525f4SDarrick J. Wong 	__u32 provided, calculated;
87814525f4SDarrick J. Wong 
88814525f4SDarrick J. Wong 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
89814525f4SDarrick J. Wong 	    cpu_to_le32(EXT4_OS_LINUX) ||
909aa5d32bSDmitry Monakhov 	    !ext4_has_metadata_csum(inode->i_sb))
91814525f4SDarrick J. Wong 		return 1;
92814525f4SDarrick J. Wong 
93814525f4SDarrick J. Wong 	provided = le16_to_cpu(raw->i_checksum_lo);
94814525f4SDarrick J. Wong 	calculated = ext4_inode_csum(inode, raw, ei);
95814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
96814525f4SDarrick J. Wong 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
97814525f4SDarrick J. Wong 		provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
98814525f4SDarrick J. Wong 	else
99814525f4SDarrick J. Wong 		calculated &= 0xFFFF;
100814525f4SDarrick J. Wong 
101814525f4SDarrick J. Wong 	return provided == calculated;
102814525f4SDarrick J. Wong }
103814525f4SDarrick J. Wong 
104814525f4SDarrick J. Wong static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
105814525f4SDarrick J. Wong 				struct ext4_inode_info *ei)
106814525f4SDarrick J. Wong {
107814525f4SDarrick J. Wong 	__u32 csum;
108814525f4SDarrick J. Wong 
109814525f4SDarrick J. Wong 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
110814525f4SDarrick J. Wong 	    cpu_to_le32(EXT4_OS_LINUX) ||
1119aa5d32bSDmitry Monakhov 	    !ext4_has_metadata_csum(inode->i_sb))
112814525f4SDarrick J. Wong 		return;
113814525f4SDarrick J. Wong 
114814525f4SDarrick J. Wong 	csum = ext4_inode_csum(inode, raw, ei);
115814525f4SDarrick J. Wong 	raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
116814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
117814525f4SDarrick J. Wong 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
118814525f4SDarrick J. Wong 		raw->i_checksum_hi = cpu_to_le16(csum >> 16);
119814525f4SDarrick J. Wong }
120814525f4SDarrick J. Wong 
121678aaf48SJan Kara static inline int ext4_begin_ordered_truncate(struct inode *inode,
122678aaf48SJan Kara 					      loff_t new_size)
123678aaf48SJan Kara {
1247ff9c073STheodore Ts'o 	trace_ext4_begin_ordered_truncate(inode, new_size);
1258aefcd55STheodore Ts'o 	/*
1268aefcd55STheodore Ts'o 	 * If jinode is zero, then we never opened the file for
1278aefcd55STheodore Ts'o 	 * writing, so there's no need to call
1288aefcd55STheodore Ts'o 	 * jbd2_journal_begin_ordered_truncate() since there's no
1298aefcd55STheodore Ts'o 	 * outstanding writes we need to flush.
1308aefcd55STheodore Ts'o 	 */
1318aefcd55STheodore Ts'o 	if (!EXT4_I(inode)->jinode)
1328aefcd55STheodore Ts'o 		return 0;
1338aefcd55STheodore Ts'o 	return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
1348aefcd55STheodore Ts'o 						   EXT4_I(inode)->jinode,
135678aaf48SJan Kara 						   new_size);
136678aaf48SJan Kara }
137678aaf48SJan Kara 
138d47992f8SLukas Czerner static void ext4_invalidatepage(struct page *page, unsigned int offset,
139d47992f8SLukas Czerner 				unsigned int length);
140cb20d518STheodore Ts'o static int __ext4_journalled_writepage(struct page *page, unsigned int len);
141cb20d518STheodore Ts'o static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
142dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
143dec214d0STahsin Erdogan 				  int pextents);
14464769240SAlex Tomas 
145ac27a0ecSDave Kleikamp /*
146ac27a0ecSDave Kleikamp  * Test whether an inode is a fast symlink.
147407cd7fbSTahsin Erdogan  * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
148ac27a0ecSDave Kleikamp  */
149f348c252STheodore Ts'o int ext4_inode_is_fast_symlink(struct inode *inode)
150ac27a0ecSDave Kleikamp {
151fc82228aSAndi Kleen 	if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
152fc82228aSAndi Kleen 		int ea_blocks = EXT4_I(inode)->i_file_acl ?
153fc82228aSAndi Kleen 				EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
154fc82228aSAndi Kleen 
155fc82228aSAndi Kleen 		if (ext4_has_inline_data(inode))
156fc82228aSAndi Kleen 			return 0;
157fc82228aSAndi Kleen 
158fc82228aSAndi Kleen 		return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
159fc82228aSAndi Kleen 	}
160407cd7fbSTahsin Erdogan 	return S_ISLNK(inode->i_mode) && inode->i_size &&
161407cd7fbSTahsin Erdogan 	       (inode->i_size < EXT4_N_BLOCKS * 4);
162ac27a0ecSDave Kleikamp }
163ac27a0ecSDave Kleikamp 
164ac27a0ecSDave Kleikamp /*
165ac27a0ecSDave Kleikamp  * Called at the last iput() if i_nlink is zero.
166ac27a0ecSDave Kleikamp  */
1670930fcc1SAl Viro void ext4_evict_inode(struct inode *inode)
168ac27a0ecSDave Kleikamp {
169ac27a0ecSDave Kleikamp 	handle_t *handle;
170bc965ab3STheodore Ts'o 	int err;
17165db869cSJan Kara 	/*
17265db869cSJan Kara 	 * Credits for final inode cleanup and freeing:
17365db869cSJan Kara 	 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
17465db869cSJan Kara 	 * (xattr block freeing), bitmap, group descriptor (inode freeing)
17565db869cSJan Kara 	 */
17665db869cSJan Kara 	int extra_credits = 6;
1770421a189STahsin Erdogan 	struct ext4_xattr_inode_array *ea_inode_array = NULL;
178ac27a0ecSDave Kleikamp 
1797ff9c073STheodore Ts'o 	trace_ext4_evict_inode(inode);
1802581fdc8SJiaying Zhang 
1810930fcc1SAl Viro 	if (inode->i_nlink) {
1822d859db3SJan Kara 		/*
1832d859db3SJan Kara 		 * When journalling data dirty buffers are tracked only in the
1842d859db3SJan Kara 		 * journal. So although mm thinks everything is clean and
1852d859db3SJan Kara 		 * ready for reaping the inode might still have some pages to
1862d859db3SJan Kara 		 * write in the running transaction or waiting to be
1872d859db3SJan Kara 		 * checkpointed. Thus calling jbd2_journal_invalidatepage()
1882d859db3SJan Kara 		 * (via truncate_inode_pages()) to discard these buffers can
1892d859db3SJan Kara 		 * cause data loss. Also even if we did not discard these
1902d859db3SJan Kara 		 * buffers, we would have no way to find them after the inode
1912d859db3SJan Kara 		 * is reaped and thus user could see stale data if he tries to
1922d859db3SJan Kara 		 * read them before the transaction is checkpointed. So be
1932d859db3SJan Kara 		 * careful and force everything to disk here... We use
1942d859db3SJan Kara 		 * ei->i_datasync_tid to store the newest transaction
1952d859db3SJan Kara 		 * containing inode's data.
1962d859db3SJan Kara 		 *
1972d859db3SJan Kara 		 * Note that directories do not have this problem because they
1982d859db3SJan Kara 		 * don't use page cache.
1992d859db3SJan Kara 		 */
2006a7fd522SVegard Nossum 		if (inode->i_ino != EXT4_JOURNAL_INO &&
2016a7fd522SVegard Nossum 		    ext4_should_journal_data(inode) &&
2023abb1a0fSJan Kara 		    (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
2033abb1a0fSJan Kara 		    inode->i_data.nrpages) {
2042d859db3SJan Kara 			journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
2052d859db3SJan Kara 			tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
2062d859db3SJan Kara 
207d76a3a77STheodore Ts'o 			jbd2_complete_transaction(journal, commit_tid);
2082d859db3SJan Kara 			filemap_write_and_wait(&inode->i_data);
2092d859db3SJan Kara 		}
21091b0abe3SJohannes Weiner 		truncate_inode_pages_final(&inode->i_data);
2115dc23bddSJan Kara 
2120930fcc1SAl Viro 		goto no_delete;
2130930fcc1SAl Viro 	}
2140930fcc1SAl Viro 
215e2bfb088STheodore Ts'o 	if (is_bad_inode(inode))
216e2bfb088STheodore Ts'o 		goto no_delete;
217871a2931SChristoph Hellwig 	dquot_initialize(inode);
218907f4554SChristoph Hellwig 
219678aaf48SJan Kara 	if (ext4_should_order_data(inode))
220678aaf48SJan Kara 		ext4_begin_ordered_truncate(inode, 0);
22191b0abe3SJohannes Weiner 	truncate_inode_pages_final(&inode->i_data);
222ac27a0ecSDave Kleikamp 
2238e8ad8a5SJan Kara 	/*
2248e8ad8a5SJan Kara 	 * Protect us against freezing - iput() caller didn't have to have any
2258e8ad8a5SJan Kara 	 * protection against it
2268e8ad8a5SJan Kara 	 */
2278e8ad8a5SJan Kara 	sb_start_intwrite(inode->i_sb);
228e50e5129SAndreas Dilger 
22930a7eb97STahsin Erdogan 	if (!IS_NOQUOTA(inode))
23030a7eb97STahsin Erdogan 		extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
23130a7eb97STahsin Erdogan 
23265db869cSJan Kara 	/*
23365db869cSJan Kara 	 * Block bitmap, group descriptor, and inode are accounted in both
23465db869cSJan Kara 	 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
23565db869cSJan Kara 	 */
23630a7eb97STahsin Erdogan 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
23765db869cSJan Kara 			 ext4_blocks_for_truncate(inode) + extra_credits - 3);
238ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
239bc965ab3STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
240ac27a0ecSDave Kleikamp 		/*
241ac27a0ecSDave Kleikamp 		 * If we're going to skip the normal cleanup, we still need to
242ac27a0ecSDave Kleikamp 		 * make sure that the in-core orphan linked list is properly
243ac27a0ecSDave Kleikamp 		 * cleaned up.
244ac27a0ecSDave Kleikamp 		 */
245617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
2468e8ad8a5SJan Kara 		sb_end_intwrite(inode->i_sb);
247ac27a0ecSDave Kleikamp 		goto no_delete;
248ac27a0ecSDave Kleikamp 	}
24930a7eb97STahsin Erdogan 
250ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
2510390131bSFrank Mayhar 		ext4_handle_sync(handle);
252407cd7fbSTahsin Erdogan 
253407cd7fbSTahsin Erdogan 	/*
254407cd7fbSTahsin Erdogan 	 * Set inode->i_size to 0 before calling ext4_truncate(). We need
255407cd7fbSTahsin Erdogan 	 * special handling of symlinks here because i_size is used to
256407cd7fbSTahsin Erdogan 	 * determine whether ext4_inode_info->i_data contains symlink data or
257407cd7fbSTahsin Erdogan 	 * block mappings. Setting i_size to 0 will remove its fast symlink
258407cd7fbSTahsin Erdogan 	 * status. Erase i_data so that it becomes a valid empty block map.
259407cd7fbSTahsin Erdogan 	 */
260407cd7fbSTahsin Erdogan 	if (ext4_inode_is_fast_symlink(inode))
261407cd7fbSTahsin Erdogan 		memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
262ac27a0ecSDave Kleikamp 	inode->i_size = 0;
263bc965ab3STheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
264bc965ab3STheodore Ts'o 	if (err) {
26512062dddSEric Sandeen 		ext4_warning(inode->i_sb,
266bc965ab3STheodore Ts'o 			     "couldn't mark inode dirty (err %d)", err);
267bc965ab3STheodore Ts'o 		goto stop_handle;
268bc965ab3STheodore Ts'o 	}
2692c98eb5eSTheodore Ts'o 	if (inode->i_blocks) {
2702c98eb5eSTheodore Ts'o 		err = ext4_truncate(inode);
2712c98eb5eSTheodore Ts'o 		if (err) {
27254d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err,
2732c98eb5eSTheodore Ts'o 				       "couldn't truncate inode %lu (err %d)",
2742c98eb5eSTheodore Ts'o 				       inode->i_ino, err);
2752c98eb5eSTheodore Ts'o 			goto stop_handle;
2762c98eb5eSTheodore Ts'o 		}
2772c98eb5eSTheodore Ts'o 	}
278bc965ab3STheodore Ts'o 
27930a7eb97STahsin Erdogan 	/* Remove xattr references. */
28030a7eb97STahsin Erdogan 	err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
28130a7eb97STahsin Erdogan 				      extra_credits);
28230a7eb97STahsin Erdogan 	if (err) {
28330a7eb97STahsin Erdogan 		ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
284bc965ab3STheodore Ts'o stop_handle:
285bc965ab3STheodore Ts'o 		ext4_journal_stop(handle);
28645388219STheodore Ts'o 		ext4_orphan_del(NULL, inode);
2878e8ad8a5SJan Kara 		sb_end_intwrite(inode->i_sb);
28830a7eb97STahsin Erdogan 		ext4_xattr_inode_array_free(ea_inode_array);
289bc965ab3STheodore Ts'o 		goto no_delete;
290bc965ab3STheodore Ts'o 	}
291bc965ab3STheodore Ts'o 
292ac27a0ecSDave Kleikamp 	/*
293617ba13bSMingming Cao 	 * Kill off the orphan record which ext4_truncate created.
294ac27a0ecSDave Kleikamp 	 * AKPM: I think this can be inside the above `if'.
295617ba13bSMingming Cao 	 * Note that ext4_orphan_del() has to be able to cope with the
296ac27a0ecSDave Kleikamp 	 * deletion of a non-existent orphan - this is because we don't
297617ba13bSMingming Cao 	 * know if ext4_truncate() actually created an orphan record.
298ac27a0ecSDave Kleikamp 	 * (Well, we could do this if we need to, but heck - it works)
299ac27a0ecSDave Kleikamp 	 */
300617ba13bSMingming Cao 	ext4_orphan_del(handle, inode);
3015ffff834SArnd Bergmann 	EXT4_I(inode)->i_dtime	= (__u32)ktime_get_real_seconds();
302ac27a0ecSDave Kleikamp 
303ac27a0ecSDave Kleikamp 	/*
304ac27a0ecSDave Kleikamp 	 * One subtle ordering requirement: if anything has gone wrong
305ac27a0ecSDave Kleikamp 	 * (transaction abort, IO errors, whatever), then we can still
306ac27a0ecSDave Kleikamp 	 * do these next steps (the fs will already have been marked as
307ac27a0ecSDave Kleikamp 	 * having errors), but we can't free the inode if the mark_dirty
308ac27a0ecSDave Kleikamp 	 * fails.
309ac27a0ecSDave Kleikamp 	 */
310617ba13bSMingming Cao 	if (ext4_mark_inode_dirty(handle, inode))
311ac27a0ecSDave Kleikamp 		/* If that failed, just do the required in-core inode clear. */
3120930fcc1SAl Viro 		ext4_clear_inode(inode);
313ac27a0ecSDave Kleikamp 	else
314617ba13bSMingming Cao 		ext4_free_inode(handle, inode);
315617ba13bSMingming Cao 	ext4_journal_stop(handle);
3168e8ad8a5SJan Kara 	sb_end_intwrite(inode->i_sb);
3170421a189STahsin Erdogan 	ext4_xattr_inode_array_free(ea_inode_array);
318ac27a0ecSDave Kleikamp 	return;
319ac27a0ecSDave Kleikamp no_delete:
3200930fcc1SAl Viro 	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
321ac27a0ecSDave Kleikamp }
322ac27a0ecSDave Kleikamp 
323a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
324a9e7f447SDmitry Monakhov qsize_t *ext4_get_reserved_space(struct inode *inode)
32560e58e0fSMingming Cao {
326a9e7f447SDmitry Monakhov 	return &EXT4_I(inode)->i_reserved_quota;
32760e58e0fSMingming Cao }
328a9e7f447SDmitry Monakhov #endif
3299d0be502STheodore Ts'o 
33012219aeaSAneesh Kumar K.V /*
3310637c6f4STheodore Ts'o  * Called with i_data_sem down, which is important since we can call
3320637c6f4STheodore Ts'o  * ext4_discard_preallocations() from here.
3330637c6f4STheodore Ts'o  */
3345f634d06SAneesh Kumar K.V void ext4_da_update_reserve_space(struct inode *inode,
3355f634d06SAneesh Kumar K.V 					int used, int quota_claim)
33612219aeaSAneesh Kumar K.V {
33712219aeaSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3380637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
33912219aeaSAneesh Kumar K.V 
3400637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
341d8990240SAditya Kali 	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
3420637c6f4STheodore Ts'o 	if (unlikely(used > ei->i_reserved_data_blocks)) {
3438de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
3441084f252STheodore Ts'o 			 "with only %d reserved data blocks",
3450637c6f4STheodore Ts'o 			 __func__, inode->i_ino, used,
3460637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
3470637c6f4STheodore Ts'o 		WARN_ON(1);
3480637c6f4STheodore Ts'o 		used = ei->i_reserved_data_blocks;
3496bc6e63fSAneesh Kumar K.V 	}
35012219aeaSAneesh Kumar K.V 
3510637c6f4STheodore Ts'o 	/* Update per-inode reservations */
3520637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= used;
35371d4f7d0STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
3540637c6f4STheodore Ts'o 
35512219aeaSAneesh Kumar K.V 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
35660e58e0fSMingming Cao 
35772b8ab9dSEric Sandeen 	/* Update quota subsystem for data blocks */
35872b8ab9dSEric Sandeen 	if (quota_claim)
3597b415bf6SAditya Kali 		dquot_claim_block(inode, EXT4_C2B(sbi, used));
36072b8ab9dSEric Sandeen 	else {
3615f634d06SAneesh Kumar K.V 		/*
3625f634d06SAneesh Kumar K.V 		 * We did fallocate with an offset that is already delayed
3635f634d06SAneesh Kumar K.V 		 * allocated. So on delayed allocated writeback we should
36472b8ab9dSEric Sandeen 		 * not re-claim the quota for fallocated blocks.
3655f634d06SAneesh Kumar K.V 		 */
3667b415bf6SAditya Kali 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
3675f634d06SAneesh Kumar K.V 	}
368d6014301SAneesh Kumar K.V 
369d6014301SAneesh Kumar K.V 	/*
370d6014301SAneesh Kumar K.V 	 * If we have done all the pending block allocations and if
371d6014301SAneesh Kumar K.V 	 * there aren't any writers on the inode, we can discard the
372d6014301SAneesh Kumar K.V 	 * inode's preallocations.
373d6014301SAneesh Kumar K.V 	 */
3740637c6f4STheodore Ts'o 	if ((ei->i_reserved_data_blocks == 0) &&
37582dd124cSNikolay Borisov 	    !inode_is_open_for_write(inode))
376d6014301SAneesh Kumar K.V 		ext4_discard_preallocations(inode);
37712219aeaSAneesh Kumar K.V }
37812219aeaSAneesh Kumar K.V 
379e29136f8STheodore Ts'o static int __check_block_validity(struct inode *inode, const char *func,
380c398eda0STheodore Ts'o 				unsigned int line,
38124676da4STheodore Ts'o 				struct ext4_map_blocks *map)
3826fd058f7STheodore Ts'o {
383345c0dbfSTheodore Ts'o 	if (ext4_has_feature_journal(inode->i_sb) &&
384345c0dbfSTheodore Ts'o 	    (inode->i_ino ==
385345c0dbfSTheodore Ts'o 	     le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
386345c0dbfSTheodore Ts'o 		return 0;
38724676da4STheodore Ts'o 	if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
38824676da4STheodore Ts'o 				   map->m_len)) {
389c398eda0STheodore Ts'o 		ext4_error_inode(inode, func, line, map->m_pblk,
390bdbd6ce0STheodore Ts'o 				 "lblock %lu mapped to illegal pblock %llu "
39124676da4STheodore Ts'o 				 "(length %d)", (unsigned long) map->m_lblk,
392bdbd6ce0STheodore Ts'o 				 map->m_pblk, map->m_len);
3936a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
3946fd058f7STheodore Ts'o 	}
3956fd058f7STheodore Ts'o 	return 0;
3966fd058f7STheodore Ts'o }
3976fd058f7STheodore Ts'o 
39853085facSJan Kara int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
39953085facSJan Kara 		       ext4_lblk_t len)
40053085facSJan Kara {
40153085facSJan Kara 	int ret;
40253085facSJan Kara 
40333b4cc25SEric Biggers 	if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
404a7550b30SJaegeuk Kim 		return fscrypt_zeroout_range(inode, lblk, pblk, len);
40553085facSJan Kara 
40653085facSJan Kara 	ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
40753085facSJan Kara 	if (ret > 0)
40853085facSJan Kara 		ret = 0;
40953085facSJan Kara 
41053085facSJan Kara 	return ret;
41153085facSJan Kara }
41253085facSJan Kara 
413e29136f8STheodore Ts'o #define check_block_validity(inode, map)	\
414c398eda0STheodore Ts'o 	__check_block_validity((inode), __func__, __LINE__, (map))
415e29136f8STheodore Ts'o 
416921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
417921f266bSDmitry Monakhov static void ext4_map_blocks_es_recheck(handle_t *handle,
418921f266bSDmitry Monakhov 				       struct inode *inode,
419921f266bSDmitry Monakhov 				       struct ext4_map_blocks *es_map,
420921f266bSDmitry Monakhov 				       struct ext4_map_blocks *map,
421921f266bSDmitry Monakhov 				       int flags)
422921f266bSDmitry Monakhov {
423921f266bSDmitry Monakhov 	int retval;
424921f266bSDmitry Monakhov 
425921f266bSDmitry Monakhov 	map->m_flags = 0;
426921f266bSDmitry Monakhov 	/*
427921f266bSDmitry Monakhov 	 * There is a race window that the result is not the same.
428921f266bSDmitry Monakhov 	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
429921f266bSDmitry Monakhov 	 * is that we lookup a block mapping in extent status tree with
430921f266bSDmitry Monakhov 	 * out taking i_data_sem.  So at the time the unwritten extent
431921f266bSDmitry Monakhov 	 * could be converted.
432921f266bSDmitry Monakhov 	 */
433c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
434921f266bSDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
435*9e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
436921f266bSDmitry Monakhov 	} else {
437*9e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
438921f266bSDmitry Monakhov 	}
439921f266bSDmitry Monakhov 	up_read((&EXT4_I(inode)->i_data_sem));
440921f266bSDmitry Monakhov 
441921f266bSDmitry Monakhov 	/*
442921f266bSDmitry Monakhov 	 * We don't check m_len because extent will be collpased in status
443921f266bSDmitry Monakhov 	 * tree.  So the m_len might not equal.
444921f266bSDmitry Monakhov 	 */
445921f266bSDmitry Monakhov 	if (es_map->m_lblk != map->m_lblk ||
446921f266bSDmitry Monakhov 	    es_map->m_flags != map->m_flags ||
447921f266bSDmitry Monakhov 	    es_map->m_pblk != map->m_pblk) {
448bdafe42aSTheodore Ts'o 		printk("ES cache assertion failed for inode: %lu "
449921f266bSDmitry Monakhov 		       "es_cached ex [%d/%d/%llu/%x] != "
450921f266bSDmitry Monakhov 		       "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
451921f266bSDmitry Monakhov 		       inode->i_ino, es_map->m_lblk, es_map->m_len,
452921f266bSDmitry Monakhov 		       es_map->m_pblk, es_map->m_flags, map->m_lblk,
453921f266bSDmitry Monakhov 		       map->m_len, map->m_pblk, map->m_flags,
454921f266bSDmitry Monakhov 		       retval, flags);
455921f266bSDmitry Monakhov 	}
456921f266bSDmitry Monakhov }
457921f266bSDmitry Monakhov #endif /* ES_AGGRESSIVE_TEST */
458921f266bSDmitry Monakhov 
45955138e0bSTheodore Ts'o /*
460e35fd660STheodore Ts'o  * The ext4_map_blocks() function tries to look up the requested blocks,
4612b2d6d01STheodore Ts'o  * and returns if the blocks are already mapped.
462f5ab0d1fSMingming Cao  *
463f5ab0d1fSMingming Cao  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
464f5ab0d1fSMingming Cao  * and store the allocated blocks in the result buffer head and mark it
465f5ab0d1fSMingming Cao  * mapped.
466f5ab0d1fSMingming Cao  *
467e35fd660STheodore Ts'o  * If file type is extents based, it will call ext4_ext_map_blocks(),
468e35fd660STheodore Ts'o  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
469f5ab0d1fSMingming Cao  * based files
470f5ab0d1fSMingming Cao  *
471facab4d9SJan Kara  * On success, it returns the number of blocks being mapped or allocated.  if
472facab4d9SJan Kara  * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
473facab4d9SJan Kara  * is marked as unwritten. If the create == 1, it will mark @map as mapped.
474f5ab0d1fSMingming Cao  *
475f5ab0d1fSMingming Cao  * It returns 0 if plain look up failed (blocks have not been allocated), in
476facab4d9SJan Kara  * that case, @map is returned as unmapped but we still do fill map->m_len to
477facab4d9SJan Kara  * indicate the length of a hole starting at map->m_lblk.
478f5ab0d1fSMingming Cao  *
479f5ab0d1fSMingming Cao  * It returns the error in case of allocation failure.
480f5ab0d1fSMingming Cao  */
481e35fd660STheodore Ts'o int ext4_map_blocks(handle_t *handle, struct inode *inode,
482e35fd660STheodore Ts'o 		    struct ext4_map_blocks *map, int flags)
4830e855ac8SAneesh Kumar K.V {
484d100eef2SZheng Liu 	struct extent_status es;
4850e855ac8SAneesh Kumar K.V 	int retval;
486b8a86845SLukas Czerner 	int ret = 0;
487921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
488921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
489921f266bSDmitry Monakhov 
490921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
491921f266bSDmitry Monakhov #endif
492f5ab0d1fSMingming Cao 
493e35fd660STheodore Ts'o 	map->m_flags = 0;
494e35fd660STheodore Ts'o 	ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
495e35fd660STheodore Ts'o 		  "logical block %lu\n", inode->i_ino, flags, map->m_len,
496e35fd660STheodore Ts'o 		  (unsigned long) map->m_lblk);
497d100eef2SZheng Liu 
498e861b5e9STheodore Ts'o 	/*
499e861b5e9STheodore Ts'o 	 * ext4_map_blocks returns an int, and m_len is an unsigned int
500e861b5e9STheodore Ts'o 	 */
501e861b5e9STheodore Ts'o 	if (unlikely(map->m_len > INT_MAX))
502e861b5e9STheodore Ts'o 		map->m_len = INT_MAX;
503e861b5e9STheodore Ts'o 
5044adb6ab3SKazuya Mio 	/* We can handle the block number less than EXT_MAX_BLOCKS */
5054adb6ab3SKazuya Mio 	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
5066a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
5074adb6ab3SKazuya Mio 
508d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
509bb5835edSTheodore Ts'o 	if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
510d100eef2SZheng Liu 		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
511d100eef2SZheng Liu 			map->m_pblk = ext4_es_pblock(&es) +
512d100eef2SZheng Liu 					map->m_lblk - es.es_lblk;
513d100eef2SZheng Liu 			map->m_flags |= ext4_es_is_written(&es) ?
514d100eef2SZheng Liu 					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
515d100eef2SZheng Liu 			retval = es.es_len - (map->m_lblk - es.es_lblk);
516d100eef2SZheng Liu 			if (retval > map->m_len)
517d100eef2SZheng Liu 				retval = map->m_len;
518d100eef2SZheng Liu 			map->m_len = retval;
519d100eef2SZheng Liu 		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
520facab4d9SJan Kara 			map->m_pblk = 0;
521facab4d9SJan Kara 			retval = es.es_len - (map->m_lblk - es.es_lblk);
522facab4d9SJan Kara 			if (retval > map->m_len)
523facab4d9SJan Kara 				retval = map->m_len;
524facab4d9SJan Kara 			map->m_len = retval;
525d100eef2SZheng Liu 			retval = 0;
526d100eef2SZheng Liu 		} else {
5271e83bc81SArnd Bergmann 			BUG();
528d100eef2SZheng Liu 		}
529921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
530921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(handle, inode, map,
531921f266bSDmitry Monakhov 					   &orig_map, flags);
532921f266bSDmitry Monakhov #endif
533d100eef2SZheng Liu 		goto found;
534d100eef2SZheng Liu 	}
535d100eef2SZheng Liu 
5364df3d265SAneesh Kumar K.V 	/*
537b920c755STheodore Ts'o 	 * Try to see if we can get the block without requesting a new
538b920c755STheodore Ts'o 	 * file system block.
5394df3d265SAneesh Kumar K.V 	 */
540c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
54112e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
542*9e52484cSEric Whitney 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
5434df3d265SAneesh Kumar K.V 	} else {
544*9e52484cSEric Whitney 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
5450e855ac8SAneesh Kumar K.V 	}
546f7fec032SZheng Liu 	if (retval > 0) {
5473be78c73STheodore Ts'o 		unsigned int status;
548f7fec032SZheng Liu 
54944fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
55044fb851dSZheng Liu 			ext4_warning(inode->i_sb,
55144fb851dSZheng Liu 				     "ES len assertion failed for inode "
55244fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
55344fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
55444fb851dSZheng Liu 			WARN_ON(1);
555921f266bSDmitry Monakhov 		}
556921f266bSDmitry Monakhov 
557f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
558f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
559f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
560d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
561ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
562f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
563f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
564f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk,
565f7fec032SZheng Liu 					    map->m_len, map->m_pblk, status);
566f7fec032SZheng Liu 		if (ret < 0)
567f7fec032SZheng Liu 			retval = ret;
568f7fec032SZheng Liu 	}
5694df3d265SAneesh Kumar K.V 	up_read((&EXT4_I(inode)->i_data_sem));
570f5ab0d1fSMingming Cao 
571d100eef2SZheng Liu found:
572e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
573b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
5746fd058f7STheodore Ts'o 		if (ret != 0)
5756fd058f7STheodore Ts'o 			return ret;
5766fd058f7STheodore Ts'o 	}
5776fd058f7STheodore Ts'o 
578f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
579c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
5804df3d265SAneesh Kumar K.V 		return retval;
5814df3d265SAneesh Kumar K.V 
5824df3d265SAneesh Kumar K.V 	/*
583f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
584f5ab0d1fSMingming Cao 	 *
585f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
586df3ab170STao Ma 	 * ext4_ext_get_block() returns the create = 0
587f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
588f5ab0d1fSMingming Cao 	 */
589e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
590b8a86845SLukas Czerner 		/*
591b8a86845SLukas Czerner 		 * If we need to convert extent to unwritten
592b8a86845SLukas Czerner 		 * we continue and do the actual work in
593b8a86845SLukas Czerner 		 * ext4_ext_map_blocks()
594b8a86845SLukas Czerner 		 */
595b8a86845SLukas Czerner 		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
596f5ab0d1fSMingming Cao 			return retval;
597f5ab0d1fSMingming Cao 
598f5ab0d1fSMingming Cao 	/*
599a25a4e1aSZheng Liu 	 * Here we clear m_flags because after allocating an new extent,
600a25a4e1aSZheng Liu 	 * it will be set again.
6012a8964d6SAneesh Kumar K.V 	 */
602a25a4e1aSZheng Liu 	map->m_flags &= ~EXT4_MAP_FLAGS;
6032a8964d6SAneesh Kumar K.V 
6042a8964d6SAneesh Kumar K.V 	/*
605556615dcSLukas Czerner 	 * New blocks allocate and/or writing to unwritten extent
606f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
607d91bd2c1SSeunghun Lee 	 * the write lock of i_data_sem, and call get_block()
608f5ab0d1fSMingming Cao 	 * with create == 1 flag.
6094df3d265SAneesh Kumar K.V 	 */
610c8b459f4SLukas Czerner 	down_write(&EXT4_I(inode)->i_data_sem);
611d2a17637SMingming Cao 
612d2a17637SMingming Cao 	/*
6134df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
6144df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
6154df3d265SAneesh Kumar K.V 	 */
61612e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
617e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
6180e855ac8SAneesh Kumar K.V 	} else {
619e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
620267e4db9SAneesh Kumar K.V 
621e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
622267e4db9SAneesh Kumar K.V 			/*
623267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
624267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
625267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
626267e4db9SAneesh Kumar K.V 			 */
62719f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
628267e4db9SAneesh Kumar K.V 		}
6292ac3b6e0STheodore Ts'o 
630d2a17637SMingming Cao 		/*
6312ac3b6e0STheodore Ts'o 		 * Update reserved blocks/metadata blocks after successful
6325f634d06SAneesh Kumar K.V 		 * block allocation which had been deferred till now. We don't
6335f634d06SAneesh Kumar K.V 		 * support fallocate for non extent files. So we can update
6345f634d06SAneesh Kumar K.V 		 * reserve space here.
635d2a17637SMingming Cao 		 */
6365f634d06SAneesh Kumar K.V 		if ((retval > 0) &&
6371296cc85SAneesh Kumar K.V 			(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
6385f634d06SAneesh Kumar K.V 			ext4_da_update_reserve_space(inode, retval, 1);
6395f634d06SAneesh Kumar K.V 	}
640d2a17637SMingming Cao 
641f7fec032SZheng Liu 	if (retval > 0) {
6423be78c73STheodore Ts'o 		unsigned int status;
643f7fec032SZheng Liu 
64444fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
64544fb851dSZheng Liu 			ext4_warning(inode->i_sb,
64644fb851dSZheng Liu 				     "ES len assertion failed for inode "
64744fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
64844fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
64944fb851dSZheng Liu 			WARN_ON(1);
650921f266bSDmitry Monakhov 		}
651921f266bSDmitry Monakhov 
652adb23551SZheng Liu 		/*
653c86d8db3SJan Kara 		 * We have to zeroout blocks before inserting them into extent
654c86d8db3SJan Kara 		 * status tree. Otherwise someone could look them up there and
6559b623df6SJan Kara 		 * use them before they are really zeroed. We also have to
6569b623df6SJan Kara 		 * unmap metadata before zeroing as otherwise writeback can
6579b623df6SJan Kara 		 * overwrite zeros with stale data from block device.
658c86d8db3SJan Kara 		 */
659c86d8db3SJan Kara 		if (flags & EXT4_GET_BLOCKS_ZERO &&
660c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_MAPPED &&
661c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_NEW) {
662c86d8db3SJan Kara 			ret = ext4_issue_zeroout(inode, map->m_lblk,
663c86d8db3SJan Kara 						 map->m_pblk, map->m_len);
664c86d8db3SJan Kara 			if (ret) {
665c86d8db3SJan Kara 				retval = ret;
666c86d8db3SJan Kara 				goto out_sem;
667c86d8db3SJan Kara 			}
668c86d8db3SJan Kara 		}
669c86d8db3SJan Kara 
670c86d8db3SJan Kara 		/*
671adb23551SZheng Liu 		 * If the extent has been zeroed out, we don't need to update
672adb23551SZheng Liu 		 * extent status tree.
673adb23551SZheng Liu 		 */
674adb23551SZheng Liu 		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
675bb5835edSTheodore Ts'o 		    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
676adb23551SZheng Liu 			if (ext4_es_is_written(&es))
677c86d8db3SJan Kara 				goto out_sem;
678adb23551SZheng Liu 		}
679f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
680f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
681f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
682d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
683ad431025SEric Whitney 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
684f7fec032SZheng Liu 				       map->m_lblk + map->m_len - 1))
685f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
686f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
687f7fec032SZheng Liu 					    map->m_pblk, status);
688c86d8db3SJan Kara 		if (ret < 0) {
68951865fdaSZheng Liu 			retval = ret;
690c86d8db3SJan Kara 			goto out_sem;
691c86d8db3SJan Kara 		}
69251865fdaSZheng Liu 	}
6935356f261SAditya Kali 
694c86d8db3SJan Kara out_sem:
6950e855ac8SAneesh Kumar K.V 	up_write((&EXT4_I(inode)->i_data_sem));
696e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
697b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
6986fd058f7STheodore Ts'o 		if (ret != 0)
6996fd058f7STheodore Ts'o 			return ret;
70006bd3c36SJan Kara 
70106bd3c36SJan Kara 		/*
70206bd3c36SJan Kara 		 * Inodes with freshly allocated blocks where contents will be
70306bd3c36SJan Kara 		 * visible after transaction commit must be on transaction's
70406bd3c36SJan Kara 		 * ordered data list.
70506bd3c36SJan Kara 		 */
70606bd3c36SJan Kara 		if (map->m_flags & EXT4_MAP_NEW &&
70706bd3c36SJan Kara 		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
70806bd3c36SJan Kara 		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
70902749a4cSTahsin Erdogan 		    !ext4_is_quota_file(inode) &&
71006bd3c36SJan Kara 		    ext4_should_order_data(inode)) {
71173131fbbSRoss Zwisler 			loff_t start_byte =
71273131fbbSRoss Zwisler 				(loff_t)map->m_lblk << inode->i_blkbits;
71373131fbbSRoss Zwisler 			loff_t length = (loff_t)map->m_len << inode->i_blkbits;
71473131fbbSRoss Zwisler 
715ee0876bcSJan Kara 			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
71673131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_wait(handle, inode,
71773131fbbSRoss Zwisler 						start_byte, length);
718ee0876bcSJan Kara 			else
71973131fbbSRoss Zwisler 				ret = ext4_jbd2_inode_add_write(handle, inode,
72073131fbbSRoss Zwisler 						start_byte, length);
72106bd3c36SJan Kara 			if (ret)
72206bd3c36SJan Kara 				return ret;
72306bd3c36SJan Kara 		}
7246fd058f7STheodore Ts'o 	}
7250e855ac8SAneesh Kumar K.V 	return retval;
7260e855ac8SAneesh Kumar K.V }
7270e855ac8SAneesh Kumar K.V 
728ed8ad838SJan Kara /*
729ed8ad838SJan Kara  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
730ed8ad838SJan Kara  * we have to be careful as someone else may be manipulating b_state as well.
731ed8ad838SJan Kara  */
732ed8ad838SJan Kara static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
733ed8ad838SJan Kara {
734ed8ad838SJan Kara 	unsigned long old_state;
735ed8ad838SJan Kara 	unsigned long new_state;
736ed8ad838SJan Kara 
737ed8ad838SJan Kara 	flags &= EXT4_MAP_FLAGS;
738ed8ad838SJan Kara 
739ed8ad838SJan Kara 	/* Dummy buffer_head? Set non-atomically. */
740ed8ad838SJan Kara 	if (!bh->b_page) {
741ed8ad838SJan Kara 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
742ed8ad838SJan Kara 		return;
743ed8ad838SJan Kara 	}
744ed8ad838SJan Kara 	/*
745ed8ad838SJan Kara 	 * Someone else may be modifying b_state. Be careful! This is ugly but
746ed8ad838SJan Kara 	 * once we get rid of using bh as a container for mapping information
747ed8ad838SJan Kara 	 * to pass to / from get_block functions, this can go away.
748ed8ad838SJan Kara 	 */
749ed8ad838SJan Kara 	do {
750ed8ad838SJan Kara 		old_state = READ_ONCE(bh->b_state);
751ed8ad838SJan Kara 		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
752ed8ad838SJan Kara 	} while (unlikely(
753ed8ad838SJan Kara 		 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
754ed8ad838SJan Kara }
755ed8ad838SJan Kara 
7562ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
7572ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
758ac27a0ecSDave Kleikamp {
7592ed88685STheodore Ts'o 	struct ext4_map_blocks map;
760efe70c29SJan Kara 	int ret = 0;
761ac27a0ecSDave Kleikamp 
76246c7f254STao Ma 	if (ext4_has_inline_data(inode))
76346c7f254STao Ma 		return -ERANGE;
76446c7f254STao Ma 
7652ed88685STheodore Ts'o 	map.m_lblk = iblock;
7662ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
7672ed88685STheodore Ts'o 
768efe70c29SJan Kara 	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
769efe70c29SJan Kara 			      flags);
770ac27a0ecSDave Kleikamp 	if (ret > 0) {
7712ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
772ed8ad838SJan Kara 		ext4_update_bh_state(bh, map.m_flags);
7732ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
774ac27a0ecSDave Kleikamp 		ret = 0;
775547edce3SRoss Zwisler 	} else if (ret == 0) {
776547edce3SRoss Zwisler 		/* hole case, need to fill in bh->b_size */
777547edce3SRoss Zwisler 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
778ac27a0ecSDave Kleikamp 	}
779ac27a0ecSDave Kleikamp 	return ret;
780ac27a0ecSDave Kleikamp }
781ac27a0ecSDave Kleikamp 
7822ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
7832ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
7842ed88685STheodore Ts'o {
7852ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
7862ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
7872ed88685STheodore Ts'o }
7882ed88685STheodore Ts'o 
789ac27a0ecSDave Kleikamp /*
790705965bdSJan Kara  * Get block function used when preparing for buffered write if we require
791705965bdSJan Kara  * creating an unwritten extent if blocks haven't been allocated.  The extent
792705965bdSJan Kara  * will be converted to written after the IO is complete.
793705965bdSJan Kara  */
794705965bdSJan Kara int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
795705965bdSJan Kara 			     struct buffer_head *bh_result, int create)
796705965bdSJan Kara {
797705965bdSJan Kara 	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
798705965bdSJan Kara 		   inode->i_ino, create);
799705965bdSJan Kara 	return _ext4_get_block(inode, iblock, bh_result,
800705965bdSJan Kara 			       EXT4_GET_BLOCKS_IO_CREATE_EXT);
801705965bdSJan Kara }
802705965bdSJan Kara 
803efe70c29SJan Kara /* Maximum number of blocks we map for direct IO at once. */
804efe70c29SJan Kara #define DIO_MAX_BLOCKS 4096
805efe70c29SJan Kara 
806e84dfbe2SJan Kara /*
807ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
808ac27a0ecSDave Kleikamp  */
809617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
810c5e298aeSTheodore Ts'o 				ext4_lblk_t block, int map_flags)
811ac27a0ecSDave Kleikamp {
8122ed88685STheodore Ts'o 	struct ext4_map_blocks map;
8132ed88685STheodore Ts'o 	struct buffer_head *bh;
814c5e298aeSTheodore Ts'o 	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
81510560082STheodore Ts'o 	int err;
816ac27a0ecSDave Kleikamp 
817ac27a0ecSDave Kleikamp 	J_ASSERT(handle != NULL || create == 0);
818ac27a0ecSDave Kleikamp 
8192ed88685STheodore Ts'o 	map.m_lblk = block;
8202ed88685STheodore Ts'o 	map.m_len = 1;
821c5e298aeSTheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map, map_flags);
8222ed88685STheodore Ts'o 
82310560082STheodore Ts'o 	if (err == 0)
82410560082STheodore Ts'o 		return create ? ERR_PTR(-ENOSPC) : NULL;
8252ed88685STheodore Ts'o 	if (err < 0)
82610560082STheodore Ts'o 		return ERR_PTR(err);
8272ed88685STheodore Ts'o 
8282ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
82910560082STheodore Ts'o 	if (unlikely(!bh))
83010560082STheodore Ts'o 		return ERR_PTR(-ENOMEM);
8312ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
832ac27a0ecSDave Kleikamp 		J_ASSERT(create != 0);
833ac39849dSAneesh Kumar K.V 		J_ASSERT(handle != NULL);
834ac27a0ecSDave Kleikamp 
835ac27a0ecSDave Kleikamp 		/*
836ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
837ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
838ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
839617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
840ac27a0ecSDave Kleikamp 		 * problem.
841ac27a0ecSDave Kleikamp 		 */
842ac27a0ecSDave Kleikamp 		lock_buffer(bh);
843ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
84410560082STheodore Ts'o 		err = ext4_journal_get_create_access(handle, bh);
84510560082STheodore Ts'o 		if (unlikely(err)) {
84610560082STheodore Ts'o 			unlock_buffer(bh);
84710560082STheodore Ts'o 			goto errout;
84810560082STheodore Ts'o 		}
84910560082STheodore Ts'o 		if (!buffer_uptodate(bh)) {
850ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
851ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
852ac27a0ecSDave Kleikamp 		}
853ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
8540390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
8550390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
85610560082STheodore Ts'o 		if (unlikely(err))
85710560082STheodore Ts'o 			goto errout;
85810560082STheodore Ts'o 	} else
859ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
860ac27a0ecSDave Kleikamp 	return bh;
86110560082STheodore Ts'o errout:
86210560082STheodore Ts'o 	brelse(bh);
86310560082STheodore Ts'o 	return ERR_PTR(err);
864ac27a0ecSDave Kleikamp }
865ac27a0ecSDave Kleikamp 
866617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
867c5e298aeSTheodore Ts'o 			       ext4_lblk_t block, int map_flags)
868ac27a0ecSDave Kleikamp {
869ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
870ac27a0ecSDave Kleikamp 
871c5e298aeSTheodore Ts'o 	bh = ext4_getblk(handle, inode, block, map_flags);
8721c215028STheodore Ts'o 	if (IS_ERR(bh))
873ac27a0ecSDave Kleikamp 		return bh;
8747963e5acSZhangXiaoxu 	if (!bh || ext4_buffer_uptodate(bh))
875ac27a0ecSDave Kleikamp 		return bh;
876dfec8a14SMike Christie 	ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1, &bh);
877ac27a0ecSDave Kleikamp 	wait_on_buffer(bh);
878ac27a0ecSDave Kleikamp 	if (buffer_uptodate(bh))
879ac27a0ecSDave Kleikamp 		return bh;
880ac27a0ecSDave Kleikamp 	put_bh(bh);
8811c215028STheodore Ts'o 	return ERR_PTR(-EIO);
882ac27a0ecSDave Kleikamp }
883ac27a0ecSDave Kleikamp 
8849699d4f9STahsin Erdogan /* Read a contiguous batch of blocks. */
8859699d4f9STahsin Erdogan int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
8869699d4f9STahsin Erdogan 		     bool wait, struct buffer_head **bhs)
8879699d4f9STahsin Erdogan {
8889699d4f9STahsin Erdogan 	int i, err;
8899699d4f9STahsin Erdogan 
8909699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
8919699d4f9STahsin Erdogan 		bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
8929699d4f9STahsin Erdogan 		if (IS_ERR(bhs[i])) {
8939699d4f9STahsin Erdogan 			err = PTR_ERR(bhs[i]);
8949699d4f9STahsin Erdogan 			bh_count = i;
8959699d4f9STahsin Erdogan 			goto out_brelse;
8969699d4f9STahsin Erdogan 		}
8979699d4f9STahsin Erdogan 	}
8989699d4f9STahsin Erdogan 
8999699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9009699d4f9STahsin Erdogan 		/* Note that NULL bhs[i] is valid because of holes. */
9017963e5acSZhangXiaoxu 		if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
9029699d4f9STahsin Erdogan 			ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1,
9039699d4f9STahsin Erdogan 				    &bhs[i]);
9049699d4f9STahsin Erdogan 
9059699d4f9STahsin Erdogan 	if (!wait)
9069699d4f9STahsin Erdogan 		return 0;
9079699d4f9STahsin Erdogan 
9089699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++)
9099699d4f9STahsin Erdogan 		if (bhs[i])
9109699d4f9STahsin Erdogan 			wait_on_buffer(bhs[i]);
9119699d4f9STahsin Erdogan 
9129699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9139699d4f9STahsin Erdogan 		if (bhs[i] && !buffer_uptodate(bhs[i])) {
9149699d4f9STahsin Erdogan 			err = -EIO;
9159699d4f9STahsin Erdogan 			goto out_brelse;
9169699d4f9STahsin Erdogan 		}
9179699d4f9STahsin Erdogan 	}
9189699d4f9STahsin Erdogan 	return 0;
9199699d4f9STahsin Erdogan 
9209699d4f9STahsin Erdogan out_brelse:
9219699d4f9STahsin Erdogan 	for (i = 0; i < bh_count; i++) {
9229699d4f9STahsin Erdogan 		brelse(bhs[i]);
9239699d4f9STahsin Erdogan 		bhs[i] = NULL;
9249699d4f9STahsin Erdogan 	}
9259699d4f9STahsin Erdogan 	return err;
9269699d4f9STahsin Erdogan }
9279699d4f9STahsin Erdogan 
928f19d5870STao Ma int ext4_walk_page_buffers(handle_t *handle,
929ac27a0ecSDave Kleikamp 			   struct buffer_head *head,
930ac27a0ecSDave Kleikamp 			   unsigned from,
931ac27a0ecSDave Kleikamp 			   unsigned to,
932ac27a0ecSDave Kleikamp 			   int *partial,
933ac27a0ecSDave Kleikamp 			   int (*fn)(handle_t *handle,
934ac27a0ecSDave Kleikamp 				     struct buffer_head *bh))
935ac27a0ecSDave Kleikamp {
936ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
937ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
938ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
939ac27a0ecSDave Kleikamp 	int err, ret = 0;
940ac27a0ecSDave Kleikamp 	struct buffer_head *next;
941ac27a0ecSDave Kleikamp 
942ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
943ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
944de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
945ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
946ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
947ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
948ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
949ac27a0ecSDave Kleikamp 				*partial = 1;
950ac27a0ecSDave Kleikamp 			continue;
951ac27a0ecSDave Kleikamp 		}
952ac27a0ecSDave Kleikamp 		err = (*fn)(handle, bh);
953ac27a0ecSDave Kleikamp 		if (!ret)
954ac27a0ecSDave Kleikamp 			ret = err;
955ac27a0ecSDave Kleikamp 	}
956ac27a0ecSDave Kleikamp 	return ret;
957ac27a0ecSDave Kleikamp }
958ac27a0ecSDave Kleikamp 
959ac27a0ecSDave Kleikamp /*
960ac27a0ecSDave Kleikamp  * To preserve ordering, it is essential that the hole instantiation and
961ac27a0ecSDave Kleikamp  * the data write be encapsulated in a single transaction.  We cannot
962617ba13bSMingming Cao  * close off a transaction and start a new one between the ext4_get_block()
963dab291afSMingming Cao  * and the commit_write().  So doing the jbd2_journal_start at the start of
964ac27a0ecSDave Kleikamp  * prepare_write() is the right place.
965ac27a0ecSDave Kleikamp  *
96636ade451SJan Kara  * Also, this function can nest inside ext4_writepage().  In that case, we
96736ade451SJan Kara  * *know* that ext4_writepage() has generated enough buffer credits to do the
96836ade451SJan Kara  * whole page.  So we won't block on the journal in that case, which is good,
96936ade451SJan Kara  * because the caller may be PF_MEMALLOC.
970ac27a0ecSDave Kleikamp  *
971617ba13bSMingming Cao  * By accident, ext4 can be reentered when a transaction is open via
972ac27a0ecSDave Kleikamp  * quota file writes.  If we were to commit the transaction while thus
973ac27a0ecSDave Kleikamp  * reentered, there can be a deadlock - we would be holding a quota
974ac27a0ecSDave Kleikamp  * lock, and the commit would never complete if another thread had a
975ac27a0ecSDave Kleikamp  * transaction open and was blocking on the quota lock - a ranking
976ac27a0ecSDave Kleikamp  * violation.
977ac27a0ecSDave Kleikamp  *
978dab291afSMingming Cao  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
979ac27a0ecSDave Kleikamp  * will _not_ run commit under these circumstances because handle->h_ref
980ac27a0ecSDave Kleikamp  * is elevated.  We'll still have enough credits for the tiny quotafile
981ac27a0ecSDave Kleikamp  * write.
982ac27a0ecSDave Kleikamp  */
983f19d5870STao Ma int do_journal_get_write_access(handle_t *handle,
984ac27a0ecSDave Kleikamp 				struct buffer_head *bh)
985ac27a0ecSDave Kleikamp {
98656d35a4cSJan Kara 	int dirty = buffer_dirty(bh);
98756d35a4cSJan Kara 	int ret;
98856d35a4cSJan Kara 
989ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
990ac27a0ecSDave Kleikamp 		return 0;
99156d35a4cSJan Kara 	/*
992ebdec241SChristoph Hellwig 	 * __block_write_begin() could have dirtied some buffers. Clean
99356d35a4cSJan Kara 	 * the dirty bit as jbd2_journal_get_write_access() could complain
99456d35a4cSJan Kara 	 * otherwise about fs integrity issues. Setting of the dirty bit
995ebdec241SChristoph Hellwig 	 * by __block_write_begin() isn't a real problem here as we clear
99656d35a4cSJan Kara 	 * the bit before releasing a page lock and thus writeback cannot
99756d35a4cSJan Kara 	 * ever write the buffer.
99856d35a4cSJan Kara 	 */
99956d35a4cSJan Kara 	if (dirty)
100056d35a4cSJan Kara 		clear_buffer_dirty(bh);
10015d601255Sliang xie 	BUFFER_TRACE(bh, "get write access");
100256d35a4cSJan Kara 	ret = ext4_journal_get_write_access(handle, bh);
100356d35a4cSJan Kara 	if (!ret && dirty)
100456d35a4cSJan Kara 		ret = ext4_handle_dirty_metadata(handle, NULL, bh);
100556d35a4cSJan Kara 	return ret;
1006ac27a0ecSDave Kleikamp }
1007ac27a0ecSDave Kleikamp 
1008643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
10092058f83aSMichael Halcrow static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
10102058f83aSMichael Halcrow 				  get_block_t *get_block)
10112058f83aSMichael Halcrow {
101209cbfeafSKirill A. Shutemov 	unsigned from = pos & (PAGE_SIZE - 1);
10132058f83aSMichael Halcrow 	unsigned to = from + len;
10142058f83aSMichael Halcrow 	struct inode *inode = page->mapping->host;
10152058f83aSMichael Halcrow 	unsigned block_start, block_end;
10162058f83aSMichael Halcrow 	sector_t block;
10172058f83aSMichael Halcrow 	int err = 0;
10182058f83aSMichael Halcrow 	unsigned blocksize = inode->i_sb->s_blocksize;
10192058f83aSMichael Halcrow 	unsigned bbits;
10200b578f35SChandan Rajendra 	struct buffer_head *bh, *head, *wait[2];
10210b578f35SChandan Rajendra 	int nr_wait = 0;
10220b578f35SChandan Rajendra 	int i;
10232058f83aSMichael Halcrow 
10242058f83aSMichael Halcrow 	BUG_ON(!PageLocked(page));
102509cbfeafSKirill A. Shutemov 	BUG_ON(from > PAGE_SIZE);
102609cbfeafSKirill A. Shutemov 	BUG_ON(to > PAGE_SIZE);
10272058f83aSMichael Halcrow 	BUG_ON(from > to);
10282058f83aSMichael Halcrow 
10292058f83aSMichael Halcrow 	if (!page_has_buffers(page))
10302058f83aSMichael Halcrow 		create_empty_buffers(page, blocksize, 0);
10312058f83aSMichael Halcrow 	head = page_buffers(page);
10322058f83aSMichael Halcrow 	bbits = ilog2(blocksize);
103309cbfeafSKirill A. Shutemov 	block = (sector_t)page->index << (PAGE_SHIFT - bbits);
10342058f83aSMichael Halcrow 
10352058f83aSMichael Halcrow 	for (bh = head, block_start = 0; bh != head || !block_start;
10362058f83aSMichael Halcrow 	    block++, block_start = block_end, bh = bh->b_this_page) {
10372058f83aSMichael Halcrow 		block_end = block_start + blocksize;
10382058f83aSMichael Halcrow 		if (block_end <= from || block_start >= to) {
10392058f83aSMichael Halcrow 			if (PageUptodate(page)) {
10402058f83aSMichael Halcrow 				if (!buffer_uptodate(bh))
10412058f83aSMichael Halcrow 					set_buffer_uptodate(bh);
10422058f83aSMichael Halcrow 			}
10432058f83aSMichael Halcrow 			continue;
10442058f83aSMichael Halcrow 		}
10452058f83aSMichael Halcrow 		if (buffer_new(bh))
10462058f83aSMichael Halcrow 			clear_buffer_new(bh);
10472058f83aSMichael Halcrow 		if (!buffer_mapped(bh)) {
10482058f83aSMichael Halcrow 			WARN_ON(bh->b_size != blocksize);
10492058f83aSMichael Halcrow 			err = get_block(inode, block, bh, 1);
10502058f83aSMichael Halcrow 			if (err)
10512058f83aSMichael Halcrow 				break;
10522058f83aSMichael Halcrow 			if (buffer_new(bh)) {
10532058f83aSMichael Halcrow 				if (PageUptodate(page)) {
10542058f83aSMichael Halcrow 					clear_buffer_new(bh);
10552058f83aSMichael Halcrow 					set_buffer_uptodate(bh);
10562058f83aSMichael Halcrow 					mark_buffer_dirty(bh);
10572058f83aSMichael Halcrow 					continue;
10582058f83aSMichael Halcrow 				}
10592058f83aSMichael Halcrow 				if (block_end > to || block_start < from)
10602058f83aSMichael Halcrow 					zero_user_segments(page, to, block_end,
10612058f83aSMichael Halcrow 							   block_start, from);
10622058f83aSMichael Halcrow 				continue;
10632058f83aSMichael Halcrow 			}
10642058f83aSMichael Halcrow 		}
10652058f83aSMichael Halcrow 		if (PageUptodate(page)) {
10662058f83aSMichael Halcrow 			if (!buffer_uptodate(bh))
10672058f83aSMichael Halcrow 				set_buffer_uptodate(bh);
10682058f83aSMichael Halcrow 			continue;
10692058f83aSMichael Halcrow 		}
10702058f83aSMichael Halcrow 		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
10712058f83aSMichael Halcrow 		    !buffer_unwritten(bh) &&
10722058f83aSMichael Halcrow 		    (block_start < from || block_end > to)) {
1073dfec8a14SMike Christie 			ll_rw_block(REQ_OP_READ, 0, 1, &bh);
10740b578f35SChandan Rajendra 			wait[nr_wait++] = bh;
10752058f83aSMichael Halcrow 		}
10762058f83aSMichael Halcrow 	}
10772058f83aSMichael Halcrow 	/*
10782058f83aSMichael Halcrow 	 * If we issued read requests, let them complete.
10792058f83aSMichael Halcrow 	 */
10800b578f35SChandan Rajendra 	for (i = 0; i < nr_wait; i++) {
10810b578f35SChandan Rajendra 		wait_on_buffer(wait[i]);
10820b578f35SChandan Rajendra 		if (!buffer_uptodate(wait[i]))
10832058f83aSMichael Halcrow 			err = -EIO;
10842058f83aSMichael Halcrow 	}
10857e0785fcSChandan Rajendra 	if (unlikely(err)) {
10862058f83aSMichael Halcrow 		page_zero_new_buffers(page, from, to);
10870b578f35SChandan Rajendra 	} else if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode)) {
10880b578f35SChandan Rajendra 		for (i = 0; i < nr_wait; i++) {
10890b578f35SChandan Rajendra 			int err2;
10900b578f35SChandan Rajendra 
10910b578f35SChandan Rajendra 			err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
10920b578f35SChandan Rajendra 								bh_offset(wait[i]));
10930b578f35SChandan Rajendra 			if (err2) {
10940b578f35SChandan Rajendra 				clear_buffer_uptodate(wait[i]);
10950b578f35SChandan Rajendra 				err = err2;
10960b578f35SChandan Rajendra 			}
10970b578f35SChandan Rajendra 		}
10987e0785fcSChandan Rajendra 	}
10997e0785fcSChandan Rajendra 
11002058f83aSMichael Halcrow 	return err;
11012058f83aSMichael Halcrow }
11022058f83aSMichael Halcrow #endif
11032058f83aSMichael Halcrow 
1104bfc1af65SNick Piggin static int ext4_write_begin(struct file *file, struct address_space *mapping,
1105bfc1af65SNick Piggin 			    loff_t pos, unsigned len, unsigned flags,
1106bfc1af65SNick Piggin 			    struct page **pagep, void **fsdata)
1107ac27a0ecSDave Kleikamp {
1108bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
11091938a150SAneesh Kumar K.V 	int ret, needed_blocks;
1110ac27a0ecSDave Kleikamp 	handle_t *handle;
1111ac27a0ecSDave Kleikamp 	int retries = 0;
1112bfc1af65SNick Piggin 	struct page *page;
1113bfc1af65SNick Piggin 	pgoff_t index;
1114bfc1af65SNick Piggin 	unsigned from, to;
1115bfc1af65SNick Piggin 
11160db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
11170db1ff22STheodore Ts'o 		return -EIO;
11180db1ff22STheodore Ts'o 
11199bffad1eSTheodore Ts'o 	trace_ext4_write_begin(inode, pos, len, flags);
11201938a150SAneesh Kumar K.V 	/*
11211938a150SAneesh Kumar K.V 	 * Reserve one block more for addition to orphan list in case
11221938a150SAneesh Kumar K.V 	 * we allocate blocks but write fails for some reason
11231938a150SAneesh Kumar K.V 	 */
11241938a150SAneesh Kumar K.V 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
112509cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
112609cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1127bfc1af65SNick Piggin 	to = from + len;
1128ac27a0ecSDave Kleikamp 
1129f19d5870STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1130f19d5870STao Ma 		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1131f19d5870STao Ma 						    flags, pagep);
1132f19d5870STao Ma 		if (ret < 0)
113347564bfbSTheodore Ts'o 			return ret;
113447564bfbSTheodore Ts'o 		if (ret == 1)
113547564bfbSTheodore Ts'o 			return 0;
1136f19d5870STao Ma 	}
1137f19d5870STao Ma 
113847564bfbSTheodore Ts'o 	/*
113947564bfbSTheodore Ts'o 	 * grab_cache_page_write_begin() can take a long time if the
114047564bfbSTheodore Ts'o 	 * system is thrashing due to memory pressure, or if the page
114147564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
114247564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
114347564bfbSTheodore Ts'o 	 * the page (if needed) without using GFP_NOFS.
114447564bfbSTheodore Ts'o 	 */
114547564bfbSTheodore Ts'o retry_grab:
114654566b2cSNick Piggin 	page = grab_cache_page_write_begin(mapping, index, flags);
114747564bfbSTheodore Ts'o 	if (!page)
114847564bfbSTheodore Ts'o 		return -ENOMEM;
114947564bfbSTheodore Ts'o 	unlock_page(page);
115047564bfbSTheodore Ts'o 
115147564bfbSTheodore Ts'o retry_journal:
11529924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1153ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
115409cbfeafSKirill A. Shutemov 		put_page(page);
115547564bfbSTheodore Ts'o 		return PTR_ERR(handle);
1156cf108bcaSJan Kara 	}
1157f19d5870STao Ma 
115847564bfbSTheodore Ts'o 	lock_page(page);
115947564bfbSTheodore Ts'o 	if (page->mapping != mapping) {
116047564bfbSTheodore Ts'o 		/* The page got truncated from under us */
116147564bfbSTheodore Ts'o 		unlock_page(page);
116209cbfeafSKirill A. Shutemov 		put_page(page);
1163cf108bcaSJan Kara 		ext4_journal_stop(handle);
116447564bfbSTheodore Ts'o 		goto retry_grab;
1165cf108bcaSJan Kara 	}
11667afe5aa5SDmitry Monakhov 	/* In case writeback began while the page was unlocked */
11677afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
1168cf108bcaSJan Kara 
1169643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
11702058f83aSMichael Halcrow 	if (ext4_should_dioread_nolock(inode))
11712058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
1172705965bdSJan Kara 					     ext4_get_block_unwritten);
11732058f83aSMichael Halcrow 	else
11742058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
11752058f83aSMichael Halcrow 					     ext4_get_block);
11762058f83aSMichael Halcrow #else
1177744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
1178705965bdSJan Kara 		ret = __block_write_begin(page, pos, len,
1179705965bdSJan Kara 					  ext4_get_block_unwritten);
1180744692dcSJiaying Zhang 	else
11816e1db88dSChristoph Hellwig 		ret = __block_write_begin(page, pos, len, ext4_get_block);
11822058f83aSMichael Halcrow #endif
1183bfc1af65SNick Piggin 	if (!ret && ext4_should_journal_data(inode)) {
1184f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_buffers(page),
1185f19d5870STao Ma 					     from, to, NULL,
1186f19d5870STao Ma 					     do_journal_get_write_access);
1187b46be050SAndrey Savochkin 	}
1188bfc1af65SNick Piggin 
1189bfc1af65SNick Piggin 	if (ret) {
1190c93d8f88SEric Biggers 		bool extended = (pos + len > inode->i_size) &&
1191c93d8f88SEric Biggers 				!ext4_verity_in_progress(inode);
1192c93d8f88SEric Biggers 
1193bfc1af65SNick Piggin 		unlock_page(page);
1194ae4d5372SAneesh Kumar K.V 		/*
11956e1db88dSChristoph Hellwig 		 * __block_write_begin may have instantiated a few blocks
1196ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
1197ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
11981938a150SAneesh Kumar K.V 		 *
11991938a150SAneesh Kumar K.V 		 * Add inode to orphan list in case we crash before
12001938a150SAneesh Kumar K.V 		 * truncate finishes
1201ae4d5372SAneesh Kumar K.V 		 */
1202c93d8f88SEric Biggers 		if (extended && ext4_can_truncate(inode))
12031938a150SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
12041938a150SAneesh Kumar K.V 
12051938a150SAneesh Kumar K.V 		ext4_journal_stop(handle);
1206c93d8f88SEric Biggers 		if (extended) {
1207b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
12081938a150SAneesh Kumar K.V 			/*
1209ffacfa7aSJan Kara 			 * If truncate failed early the inode might
12101938a150SAneesh Kumar K.V 			 * still be on the orphan list; we need to
12111938a150SAneesh Kumar K.V 			 * make sure the inode is removed from the
12121938a150SAneesh Kumar K.V 			 * orphan list in that case.
12131938a150SAneesh Kumar K.V 			 */
12141938a150SAneesh Kumar K.V 			if (inode->i_nlink)
12151938a150SAneesh Kumar K.V 				ext4_orphan_del(NULL, inode);
12161938a150SAneesh Kumar K.V 		}
1217bfc1af65SNick Piggin 
121847564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
121947564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
122047564bfbSTheodore Ts'o 			goto retry_journal;
122109cbfeafSKirill A. Shutemov 		put_page(page);
122247564bfbSTheodore Ts'o 		return ret;
122347564bfbSTheodore Ts'o 	}
122447564bfbSTheodore Ts'o 	*pagep = page;
1225ac27a0ecSDave Kleikamp 	return ret;
1226ac27a0ecSDave Kleikamp }
1227ac27a0ecSDave Kleikamp 
1228bfc1af65SNick Piggin /* For write_end() in data=journal mode */
1229bfc1af65SNick Piggin static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1230ac27a0ecSDave Kleikamp {
123113fca323STheodore Ts'o 	int ret;
1232ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1233ac27a0ecSDave Kleikamp 		return 0;
1234ac27a0ecSDave Kleikamp 	set_buffer_uptodate(bh);
123513fca323STheodore Ts'o 	ret = ext4_handle_dirty_metadata(handle, NULL, bh);
123613fca323STheodore Ts'o 	clear_buffer_meta(bh);
123713fca323STheodore Ts'o 	clear_buffer_prio(bh);
123813fca323STheodore Ts'o 	return ret;
1239ac27a0ecSDave Kleikamp }
1240ac27a0ecSDave Kleikamp 
1241eed4333fSZheng Liu /*
1242eed4333fSZheng Liu  * We need to pick up the new inode size which generic_commit_write gave us
1243eed4333fSZheng Liu  * `file' can be NULL - eg, when called from page_symlink().
1244eed4333fSZheng Liu  *
1245eed4333fSZheng Liu  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1246eed4333fSZheng Liu  * buffers are managed internally.
1247eed4333fSZheng Liu  */
1248eed4333fSZheng Liu static int ext4_write_end(struct file *file,
1249f8514083SAneesh Kumar K.V 			  struct address_space *mapping,
1250f8514083SAneesh Kumar K.V 			  loff_t pos, unsigned len, unsigned copied,
1251f8514083SAneesh Kumar K.V 			  struct page *page, void *fsdata)
1252f8514083SAneesh Kumar K.V {
1253f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
1254eed4333fSZheng Liu 	struct inode *inode = mapping->host;
12550572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1256eed4333fSZheng Liu 	int ret = 0, ret2;
1257eed4333fSZheng Liu 	int i_size_changed = 0;
1258362eca70STheodore Ts'o 	int inline_data = ext4_has_inline_data(inode);
1259c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1260eed4333fSZheng Liu 
1261eed4333fSZheng Liu 	trace_ext4_write_end(inode, pos, len, copied);
1262362eca70STheodore Ts'o 	if (inline_data) {
126342c832deSTheodore Ts'o 		ret = ext4_write_inline_data_end(inode, pos, len,
1264f19d5870STao Ma 						 copied, page);
1265eb5efbcbSTheodore Ts'o 		if (ret < 0) {
1266eb5efbcbSTheodore Ts'o 			unlock_page(page);
1267eb5efbcbSTheodore Ts'o 			put_page(page);
126842c832deSTheodore Ts'o 			goto errout;
1269eb5efbcbSTheodore Ts'o 		}
127042c832deSTheodore Ts'o 		copied = ret;
127142c832deSTheodore Ts'o 	} else
1272f19d5870STao Ma 		copied = block_write_end(file, mapping, pos,
1273f19d5870STao Ma 					 len, copied, page, fsdata);
1274f8514083SAneesh Kumar K.V 	/*
12754631dbf6SDmitry Monakhov 	 * it's important to update i_size while still holding page lock:
1276f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
1277c93d8f88SEric Biggers 	 *
1278c93d8f88SEric Biggers 	 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1279c93d8f88SEric Biggers 	 * blocks are being written past EOF, so skip the i_size update.
1280f8514083SAneesh Kumar K.V 	 */
1281c93d8f88SEric Biggers 	if (!verity)
12824631dbf6SDmitry Monakhov 		i_size_changed = ext4_update_inode_size(inode, pos + copied);
1283f8514083SAneesh Kumar K.V 	unlock_page(page);
128409cbfeafSKirill A. Shutemov 	put_page(page);
1285f8514083SAneesh Kumar K.V 
1286c93d8f88SEric Biggers 	if (old_size < pos && !verity)
12870572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
1288f8514083SAneesh Kumar K.V 	/*
1289f8514083SAneesh Kumar K.V 	 * Don't mark the inode dirty under page lock. First, it unnecessarily
1290f8514083SAneesh Kumar K.V 	 * makes the holding time of page lock longer. Second, it forces lock
1291f8514083SAneesh Kumar K.V 	 * ordering of page lock and transaction start for journaling
1292f8514083SAneesh Kumar K.V 	 * filesystems.
1293f8514083SAneesh Kumar K.V 	 */
1294362eca70STheodore Ts'o 	if (i_size_changed || inline_data)
1295f8514083SAneesh Kumar K.V 		ext4_mark_inode_dirty(handle, inode);
1296f8514083SAneesh Kumar K.V 
1297c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1298f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1299f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1300f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1301f8514083SAneesh Kumar K.V 		 */
1302f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
130374d553aaSTheodore Ts'o errout:
1304617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1305ac27a0ecSDave Kleikamp 	if (!ret)
1306ac27a0ecSDave Kleikamp 		ret = ret2;
1307bfc1af65SNick Piggin 
1308c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1309b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1310f8514083SAneesh Kumar K.V 		/*
1311ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1312f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1313f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1314f8514083SAneesh Kumar K.V 		 */
1315f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1316f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1317f8514083SAneesh Kumar K.V 	}
1318f8514083SAneesh Kumar K.V 
1319bfc1af65SNick Piggin 	return ret ? ret : copied;
1320ac27a0ecSDave Kleikamp }
1321ac27a0ecSDave Kleikamp 
1322b90197b6STheodore Ts'o /*
1323b90197b6STheodore Ts'o  * This is a private version of page_zero_new_buffers() which doesn't
1324b90197b6STheodore Ts'o  * set the buffer to be dirty, since in data=journalled mode we need
1325b90197b6STheodore Ts'o  * to call ext4_handle_dirty_metadata() instead.
1326b90197b6STheodore Ts'o  */
13273b136499SJan Kara static void ext4_journalled_zero_new_buffers(handle_t *handle,
13283b136499SJan Kara 					    struct page *page,
13293b136499SJan Kara 					    unsigned from, unsigned to)
1330b90197b6STheodore Ts'o {
1331b90197b6STheodore Ts'o 	unsigned int block_start = 0, block_end;
1332b90197b6STheodore Ts'o 	struct buffer_head *head, *bh;
1333b90197b6STheodore Ts'o 
1334b90197b6STheodore Ts'o 	bh = head = page_buffers(page);
1335b90197b6STheodore Ts'o 	do {
1336b90197b6STheodore Ts'o 		block_end = block_start + bh->b_size;
1337b90197b6STheodore Ts'o 		if (buffer_new(bh)) {
1338b90197b6STheodore Ts'o 			if (block_end > from && block_start < to) {
1339b90197b6STheodore Ts'o 				if (!PageUptodate(page)) {
1340b90197b6STheodore Ts'o 					unsigned start, size;
1341b90197b6STheodore Ts'o 
1342b90197b6STheodore Ts'o 					start = max(from, block_start);
1343b90197b6STheodore Ts'o 					size = min(to, block_end) - start;
1344b90197b6STheodore Ts'o 
1345b90197b6STheodore Ts'o 					zero_user(page, start, size);
13463b136499SJan Kara 					write_end_fn(handle, bh);
1347b90197b6STheodore Ts'o 				}
1348b90197b6STheodore Ts'o 				clear_buffer_new(bh);
1349b90197b6STheodore Ts'o 			}
1350b90197b6STheodore Ts'o 		}
1351b90197b6STheodore Ts'o 		block_start = block_end;
1352b90197b6STheodore Ts'o 		bh = bh->b_this_page;
1353b90197b6STheodore Ts'o 	} while (bh != head);
1354b90197b6STheodore Ts'o }
1355b90197b6STheodore Ts'o 
1356bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
1357bfc1af65SNick Piggin 				     struct address_space *mapping,
1358bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
1359bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
1360ac27a0ecSDave Kleikamp {
1361617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1362bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
13630572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1364ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1365ac27a0ecSDave Kleikamp 	int partial = 0;
1366bfc1af65SNick Piggin 	unsigned from, to;
13674631dbf6SDmitry Monakhov 	int size_changed = 0;
1368362eca70STheodore Ts'o 	int inline_data = ext4_has_inline_data(inode);
1369c93d8f88SEric Biggers 	bool verity = ext4_verity_in_progress(inode);
1370ac27a0ecSDave Kleikamp 
13719bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
137209cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1373bfc1af65SNick Piggin 	to = from + len;
1374bfc1af65SNick Piggin 
1375441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1376441c8508SCurt Wohlgemuth 
1377362eca70STheodore Ts'o 	if (inline_data) {
1378eb5efbcbSTheodore Ts'o 		ret = ext4_write_inline_data_end(inode, pos, len,
13793fdcfb66STao Ma 						 copied, page);
1380eb5efbcbSTheodore Ts'o 		if (ret < 0) {
1381eb5efbcbSTheodore Ts'o 			unlock_page(page);
1382eb5efbcbSTheodore Ts'o 			put_page(page);
1383eb5efbcbSTheodore Ts'o 			goto errout;
1384eb5efbcbSTheodore Ts'o 		}
1385eb5efbcbSTheodore Ts'o 		copied = ret;
1386eb5efbcbSTheodore Ts'o 	} else if (unlikely(copied < len) && !PageUptodate(page)) {
1387bfc1af65SNick Piggin 		copied = 0;
13883b136499SJan Kara 		ext4_journalled_zero_new_buffers(handle, page, from, to);
13893b136499SJan Kara 	} else {
13903b136499SJan Kara 		if (unlikely(copied < len))
13913b136499SJan Kara 			ext4_journalled_zero_new_buffers(handle, page,
13923b136499SJan Kara 							 from + copied, to);
1393f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
13943b136499SJan Kara 					     from + copied, &partial,
13953b136499SJan Kara 					     write_end_fn);
1396ac27a0ecSDave Kleikamp 		if (!partial)
1397ac27a0ecSDave Kleikamp 			SetPageUptodate(page);
13983fdcfb66STao Ma 	}
1399c93d8f88SEric Biggers 	if (!verity)
14004631dbf6SDmitry Monakhov 		size_changed = ext4_update_inode_size(inode, pos + copied);
140119f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
14022d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
14034631dbf6SDmitry Monakhov 	unlock_page(page);
140409cbfeafSKirill A. Shutemov 	put_page(page);
14054631dbf6SDmitry Monakhov 
1406c93d8f88SEric Biggers 	if (old_size < pos && !verity)
14070572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
14080572639fSXiaoguang Wang 
1409362eca70STheodore Ts'o 	if (size_changed || inline_data) {
1410617ba13bSMingming Cao 		ret2 = ext4_mark_inode_dirty(handle, inode);
1411ac27a0ecSDave Kleikamp 		if (!ret)
1412ac27a0ecSDave Kleikamp 			ret = ret2;
1413ac27a0ecSDave Kleikamp 	}
1414bfc1af65SNick Piggin 
1415c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1416f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1417f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1418f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1419f8514083SAneesh Kumar K.V 		 */
1420f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1421f8514083SAneesh Kumar K.V 
1422eb5efbcbSTheodore Ts'o errout:
1423617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1424ac27a0ecSDave Kleikamp 	if (!ret)
1425ac27a0ecSDave Kleikamp 		ret = ret2;
1426c93d8f88SEric Biggers 	if (pos + len > inode->i_size && !verity) {
1427b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1428f8514083SAneesh Kumar K.V 		/*
1429ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1430f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1431f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1432f8514083SAneesh Kumar K.V 		 */
1433f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1434f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1435f8514083SAneesh Kumar K.V 	}
1436bfc1af65SNick Piggin 
1437bfc1af65SNick Piggin 	return ret ? ret : copied;
1438ac27a0ecSDave Kleikamp }
1439d2a17637SMingming Cao 
14409d0be502STheodore Ts'o /*
1441c27e43a1SEric Whitney  * Reserve space for a single cluster
14429d0be502STheodore Ts'o  */
1443c27e43a1SEric Whitney static int ext4_da_reserve_space(struct inode *inode)
1444d2a17637SMingming Cao {
1445d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
14460637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
14475dd4056dSChristoph Hellwig 	int ret;
1448d2a17637SMingming Cao 
144960e58e0fSMingming Cao 	/*
145072b8ab9dSEric Sandeen 	 * We will charge metadata quota at writeout time; this saves
145172b8ab9dSEric Sandeen 	 * us from metadata over-estimation, though we may go over by
145272b8ab9dSEric Sandeen 	 * a small amount in the end.  Here we just reserve for data.
145360e58e0fSMingming Cao 	 */
14547b415bf6SAditya Kali 	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
14555dd4056dSChristoph Hellwig 	if (ret)
14565dd4056dSChristoph Hellwig 		return ret;
145703179fe9STheodore Ts'o 
145803179fe9STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
145971d4f7d0STheodore Ts'o 	if (ext4_claim_free_clusters(sbi, 1, 0)) {
146003179fe9STheodore Ts'o 		spin_unlock(&ei->i_block_reservation_lock);
146103179fe9STheodore Ts'o 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1462d2a17637SMingming Cao 		return -ENOSPC;
1463d2a17637SMingming Cao 	}
14649d0be502STheodore Ts'o 	ei->i_reserved_data_blocks++;
1465c27e43a1SEric Whitney 	trace_ext4_da_reserve_space(inode);
14660637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
146739bc680aSDmitry Monakhov 
1468d2a17637SMingming Cao 	return 0;       /* success */
1469d2a17637SMingming Cao }
1470d2a17637SMingming Cao 
1471f456767dSEric Whitney void ext4_da_release_space(struct inode *inode, int to_free)
1472d2a17637SMingming Cao {
1473d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
14740637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1475d2a17637SMingming Cao 
1476cd213226SMingming Cao 	if (!to_free)
1477cd213226SMingming Cao 		return;		/* Nothing to release, exit */
1478cd213226SMingming Cao 
1479d2a17637SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1480cd213226SMingming Cao 
14815a58ec87SLi Zefan 	trace_ext4_da_release_space(inode, to_free);
14820637c6f4STheodore Ts'o 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1483cd213226SMingming Cao 		/*
14840637c6f4STheodore Ts'o 		 * if there aren't enough reserved blocks, then the
14850637c6f4STheodore Ts'o 		 * counter is messed up somewhere.  Since this
14860637c6f4STheodore Ts'o 		 * function is called from invalidate page, it's
14870637c6f4STheodore Ts'o 		 * harmless to return without any action.
1488cd213226SMingming Cao 		 */
14898de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "ext4_da_release_space: "
14900637c6f4STheodore Ts'o 			 "ino %lu, to_free %d with only %d reserved "
14911084f252STheodore Ts'o 			 "data blocks", inode->i_ino, to_free,
14920637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
14930637c6f4STheodore Ts'o 		WARN_ON(1);
14940637c6f4STheodore Ts'o 		to_free = ei->i_reserved_data_blocks;
14950637c6f4STheodore Ts'o 	}
14960637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= to_free;
14970637c6f4STheodore Ts'o 
149872b8ab9dSEric Sandeen 	/* update fs dirty data blocks counter */
149957042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1500d2a17637SMingming Cao 
1501d2a17637SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
150260e58e0fSMingming Cao 
15037b415bf6SAditya Kali 	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1504d2a17637SMingming Cao }
1505d2a17637SMingming Cao 
1506ac27a0ecSDave Kleikamp /*
150764769240SAlex Tomas  * Delayed allocation stuff
150864769240SAlex Tomas  */
150964769240SAlex Tomas 
15104e7ea81dSJan Kara struct mpage_da_data {
15114e7ea81dSJan Kara 	struct inode *inode;
15124e7ea81dSJan Kara 	struct writeback_control *wbc;
15136b523df4SJan Kara 
15144e7ea81dSJan Kara 	pgoff_t first_page;	/* The first page to write */
15154e7ea81dSJan Kara 	pgoff_t next_page;	/* Current page to examine */
15164e7ea81dSJan Kara 	pgoff_t last_page;	/* Last page to examine */
151764769240SAlex Tomas 	/*
15184e7ea81dSJan Kara 	 * Extent to map - this can be after first_page because that can be
15194e7ea81dSJan Kara 	 * fully mapped. We somewhat abuse m_flags to store whether the extent
15204e7ea81dSJan Kara 	 * is delalloc or unwritten.
152164769240SAlex Tomas 	 */
15224e7ea81dSJan Kara 	struct ext4_map_blocks map;
15234e7ea81dSJan Kara 	struct ext4_io_submit io_submit;	/* IO submission data */
1524dddbd6acSJan Kara 	unsigned int do_map:1;
15254e7ea81dSJan Kara };
152664769240SAlex Tomas 
15274e7ea81dSJan Kara static void mpage_release_unused_pages(struct mpage_da_data *mpd,
15284e7ea81dSJan Kara 				       bool invalidate)
1529c4a0c46eSAneesh Kumar K.V {
1530c4a0c46eSAneesh Kumar K.V 	int nr_pages, i;
1531c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
1532c4a0c46eSAneesh Kumar K.V 	struct pagevec pvec;
1533c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1534c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
15354e7ea81dSJan Kara 
15364e7ea81dSJan Kara 	/* This is necessary when next_page == 0. */
15374e7ea81dSJan Kara 	if (mpd->first_page >= mpd->next_page)
15384e7ea81dSJan Kara 		return;
1539c4a0c46eSAneesh Kumar K.V 
1540c7f5938aSCurt Wohlgemuth 	index = mpd->first_page;
1541c7f5938aSCurt Wohlgemuth 	end   = mpd->next_page - 1;
15424e7ea81dSJan Kara 	if (invalidate) {
15434e7ea81dSJan Kara 		ext4_lblk_t start, last;
154409cbfeafSKirill A. Shutemov 		start = index << (PAGE_SHIFT - inode->i_blkbits);
154509cbfeafSKirill A. Shutemov 		last = end << (PAGE_SHIFT - inode->i_blkbits);
154651865fdaSZheng Liu 		ext4_es_remove_extent(inode, start, last - start + 1);
15474e7ea81dSJan Kara 	}
154851865fdaSZheng Liu 
154986679820SMel Gorman 	pagevec_init(&pvec);
1550c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
1551397162ffSJan Kara 		nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1552c4a0c46eSAneesh Kumar K.V 		if (nr_pages == 0)
1553c4a0c46eSAneesh Kumar K.V 			break;
1554c4a0c46eSAneesh Kumar K.V 		for (i = 0; i < nr_pages; i++) {
1555c4a0c46eSAneesh Kumar K.V 			struct page *page = pvec.pages[i];
15562b85a617SJan Kara 
1557c4a0c46eSAneesh Kumar K.V 			BUG_ON(!PageLocked(page));
1558c4a0c46eSAneesh Kumar K.V 			BUG_ON(PageWriteback(page));
15594e7ea81dSJan Kara 			if (invalidate) {
15604e800c03Swangguang 				if (page_mapped(page))
15614e800c03Swangguang 					clear_page_dirty_for_io(page);
156209cbfeafSKirill A. Shutemov 				block_invalidatepage(page, 0, PAGE_SIZE);
1563c4a0c46eSAneesh Kumar K.V 				ClearPageUptodate(page);
15644e7ea81dSJan Kara 			}
1565c4a0c46eSAneesh Kumar K.V 			unlock_page(page);
1566c4a0c46eSAneesh Kumar K.V 		}
15679b1d0998SJan Kara 		pagevec_release(&pvec);
1568c4a0c46eSAneesh Kumar K.V 	}
1569c4a0c46eSAneesh Kumar K.V }
1570c4a0c46eSAneesh Kumar K.V 
1571df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
1572df22291fSAneesh Kumar K.V {
1573df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
157492b97816STheodore Ts'o 	struct super_block *sb = inode->i_sb;
1575f78ee70dSLukas Czerner 	struct ext4_inode_info *ei = EXT4_I(inode);
157692b97816STheodore Ts'o 
157792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
15785dee5437STheodore Ts'o 	       EXT4_C2B(EXT4_SB(inode->i_sb),
1579f78ee70dSLukas Czerner 			ext4_count_free_clusters(sb)));
158092b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
158192b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1582f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
158357042651STheodore Ts'o 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
158492b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1585f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
15867b415bf6SAditya Kali 		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
158792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Block reservation details");
158892b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1589f78ee70dSLukas Czerner 		 ei->i_reserved_data_blocks);
1590df22291fSAneesh Kumar K.V 	return;
1591df22291fSAneesh Kumar K.V }
1592df22291fSAneesh Kumar K.V 
1593c364b22cSAneesh Kumar K.V static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
159429fa89d0SAneesh Kumar K.V {
1595c364b22cSAneesh Kumar K.V 	return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
159629fa89d0SAneesh Kumar K.V }
159729fa89d0SAneesh Kumar K.V 
159864769240SAlex Tomas /*
15990b02f4c0SEric Whitney  * ext4_insert_delayed_block - adds a delayed block to the extents status
16000b02f4c0SEric Whitney  *                             tree, incrementing the reserved cluster/block
16010b02f4c0SEric Whitney  *                             count or making a pending reservation
16020b02f4c0SEric Whitney  *                             where needed
16030b02f4c0SEric Whitney  *
16040b02f4c0SEric Whitney  * @inode - file containing the newly added block
16050b02f4c0SEric Whitney  * @lblk - logical block to be added
16060b02f4c0SEric Whitney  *
16070b02f4c0SEric Whitney  * Returns 0 on success, negative error code on failure.
16080b02f4c0SEric Whitney  */
16090b02f4c0SEric Whitney static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
16100b02f4c0SEric Whitney {
16110b02f4c0SEric Whitney 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
16120b02f4c0SEric Whitney 	int ret;
16130b02f4c0SEric Whitney 	bool allocated = false;
16140b02f4c0SEric Whitney 
16150b02f4c0SEric Whitney 	/*
16160b02f4c0SEric Whitney 	 * If the cluster containing lblk is shared with a delayed,
16170b02f4c0SEric Whitney 	 * written, or unwritten extent in a bigalloc file system, it's
16180b02f4c0SEric Whitney 	 * already been accounted for and does not need to be reserved.
16190b02f4c0SEric Whitney 	 * A pending reservation must be made for the cluster if it's
16200b02f4c0SEric Whitney 	 * shared with a written or unwritten extent and doesn't already
16210b02f4c0SEric Whitney 	 * have one.  Written and unwritten extents can be purged from the
16220b02f4c0SEric Whitney 	 * extents status tree if the system is under memory pressure, so
16230b02f4c0SEric Whitney 	 * it's necessary to examine the extent tree if a search of the
16240b02f4c0SEric Whitney 	 * extents status tree doesn't get a match.
16250b02f4c0SEric Whitney 	 */
16260b02f4c0SEric Whitney 	if (sbi->s_cluster_ratio == 1) {
16270b02f4c0SEric Whitney 		ret = ext4_da_reserve_space(inode);
16280b02f4c0SEric Whitney 		if (ret != 0)   /* ENOSPC */
16290b02f4c0SEric Whitney 			goto errout;
16300b02f4c0SEric Whitney 	} else {   /* bigalloc */
16310b02f4c0SEric Whitney 		if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
16320b02f4c0SEric Whitney 			if (!ext4_es_scan_clu(inode,
16330b02f4c0SEric Whitney 					      &ext4_es_is_mapped, lblk)) {
16340b02f4c0SEric Whitney 				ret = ext4_clu_mapped(inode,
16350b02f4c0SEric Whitney 						      EXT4_B2C(sbi, lblk));
16360b02f4c0SEric Whitney 				if (ret < 0)
16370b02f4c0SEric Whitney 					goto errout;
16380b02f4c0SEric Whitney 				if (ret == 0) {
16390b02f4c0SEric Whitney 					ret = ext4_da_reserve_space(inode);
16400b02f4c0SEric Whitney 					if (ret != 0)   /* ENOSPC */
16410b02f4c0SEric Whitney 						goto errout;
16420b02f4c0SEric Whitney 				} else {
16430b02f4c0SEric Whitney 					allocated = true;
16440b02f4c0SEric Whitney 				}
16450b02f4c0SEric Whitney 			} else {
16460b02f4c0SEric Whitney 				allocated = true;
16470b02f4c0SEric Whitney 			}
16480b02f4c0SEric Whitney 		}
16490b02f4c0SEric Whitney 	}
16500b02f4c0SEric Whitney 
16510b02f4c0SEric Whitney 	ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
16520b02f4c0SEric Whitney 
16530b02f4c0SEric Whitney errout:
16540b02f4c0SEric Whitney 	return ret;
16550b02f4c0SEric Whitney }
16560b02f4c0SEric Whitney 
16570b02f4c0SEric Whitney /*
16585356f261SAditya Kali  * This function is grabs code from the very beginning of
16595356f261SAditya Kali  * ext4_map_blocks, but assumes that the caller is from delayed write
16605356f261SAditya Kali  * time. This function looks up the requested blocks and sets the
16615356f261SAditya Kali  * buffer delay bit under the protection of i_data_sem.
16625356f261SAditya Kali  */
16635356f261SAditya Kali static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
16645356f261SAditya Kali 			      struct ext4_map_blocks *map,
16655356f261SAditya Kali 			      struct buffer_head *bh)
16665356f261SAditya Kali {
1667d100eef2SZheng Liu 	struct extent_status es;
16685356f261SAditya Kali 	int retval;
16695356f261SAditya Kali 	sector_t invalid_block = ~((sector_t) 0xffff);
1670921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1671921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
1672921f266bSDmitry Monakhov 
1673921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
1674921f266bSDmitry Monakhov #endif
16755356f261SAditya Kali 
16765356f261SAditya Kali 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
16775356f261SAditya Kali 		invalid_block = ~0;
16785356f261SAditya Kali 
16795356f261SAditya Kali 	map->m_flags = 0;
16805356f261SAditya Kali 	ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
16815356f261SAditya Kali 		  "logical block %lu\n", inode->i_ino, map->m_len,
16825356f261SAditya Kali 		  (unsigned long) map->m_lblk);
1683d100eef2SZheng Liu 
1684d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
1685bb5835edSTheodore Ts'o 	if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1686d100eef2SZheng Liu 		if (ext4_es_is_hole(&es)) {
1687d100eef2SZheng Liu 			retval = 0;
1688c8b459f4SLukas Czerner 			down_read(&EXT4_I(inode)->i_data_sem);
1689d100eef2SZheng Liu 			goto add_delayed;
1690d100eef2SZheng Liu 		}
1691d100eef2SZheng Liu 
1692d100eef2SZheng Liu 		/*
1693d100eef2SZheng Liu 		 * Delayed extent could be allocated by fallocate.
1694d100eef2SZheng Liu 		 * So we need to check it.
1695d100eef2SZheng Liu 		 */
1696d100eef2SZheng Liu 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1697d100eef2SZheng Liu 			map_bh(bh, inode->i_sb, invalid_block);
1698d100eef2SZheng Liu 			set_buffer_new(bh);
1699d100eef2SZheng Liu 			set_buffer_delay(bh);
1700d100eef2SZheng Liu 			return 0;
1701d100eef2SZheng Liu 		}
1702d100eef2SZheng Liu 
1703d100eef2SZheng Liu 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1704d100eef2SZheng Liu 		retval = es.es_len - (iblock - es.es_lblk);
1705d100eef2SZheng Liu 		if (retval > map->m_len)
1706d100eef2SZheng Liu 			retval = map->m_len;
1707d100eef2SZheng Liu 		map->m_len = retval;
1708d100eef2SZheng Liu 		if (ext4_es_is_written(&es))
1709d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_MAPPED;
1710d100eef2SZheng Liu 		else if (ext4_es_is_unwritten(&es))
1711d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1712d100eef2SZheng Liu 		else
17131e83bc81SArnd Bergmann 			BUG();
1714d100eef2SZheng Liu 
1715921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1716921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1717921f266bSDmitry Monakhov #endif
1718d100eef2SZheng Liu 		return retval;
1719d100eef2SZheng Liu 	}
1720d100eef2SZheng Liu 
17215356f261SAditya Kali 	/*
17225356f261SAditya Kali 	 * Try to see if we can get the block without requesting a new
17235356f261SAditya Kali 	 * file system block.
17245356f261SAditya Kali 	 */
1725c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
1726cbd7584eSJan Kara 	if (ext4_has_inline_data(inode))
17279c3569b5STao Ma 		retval = 0;
1728cbd7584eSJan Kara 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
17292f8e0a7cSZheng Liu 		retval = ext4_ext_map_blocks(NULL, inode, map, 0);
17305356f261SAditya Kali 	else
17312f8e0a7cSZheng Liu 		retval = ext4_ind_map_blocks(NULL, inode, map, 0);
17325356f261SAditya Kali 
1733d100eef2SZheng Liu add_delayed:
17345356f261SAditya Kali 	if (retval == 0) {
1735f7fec032SZheng Liu 		int ret;
1736ad431025SEric Whitney 
17375356f261SAditya Kali 		/*
17385356f261SAditya Kali 		 * XXX: __block_prepare_write() unmaps passed block,
17395356f261SAditya Kali 		 * is it OK?
17405356f261SAditya Kali 		 */
17415356f261SAditya Kali 
17420b02f4c0SEric Whitney 		ret = ext4_insert_delayed_block(inode, map->m_lblk);
17430b02f4c0SEric Whitney 		if (ret != 0) {
1744f7fec032SZheng Liu 			retval = ret;
174551865fdaSZheng Liu 			goto out_unlock;
1746f7fec032SZheng Liu 		}
174751865fdaSZheng Liu 
17485356f261SAditya Kali 		map_bh(bh, inode->i_sb, invalid_block);
17495356f261SAditya Kali 		set_buffer_new(bh);
17505356f261SAditya Kali 		set_buffer_delay(bh);
1751f7fec032SZheng Liu 	} else if (retval > 0) {
1752f7fec032SZheng Liu 		int ret;
17533be78c73STheodore Ts'o 		unsigned int status;
1754f7fec032SZheng Liu 
175544fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
175644fb851dSZheng Liu 			ext4_warning(inode->i_sb,
175744fb851dSZheng Liu 				     "ES len assertion failed for inode "
175844fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
175944fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
176044fb851dSZheng Liu 			WARN_ON(1);
1761921f266bSDmitry Monakhov 		}
1762921f266bSDmitry Monakhov 
1763f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1764f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1765f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1766f7fec032SZheng Liu 					    map->m_pblk, status);
1767f7fec032SZheng Liu 		if (ret != 0)
1768f7fec032SZheng Liu 			retval = ret;
17695356f261SAditya Kali 	}
17705356f261SAditya Kali 
17715356f261SAditya Kali out_unlock:
17725356f261SAditya Kali 	up_read((&EXT4_I(inode)->i_data_sem));
17735356f261SAditya Kali 
17745356f261SAditya Kali 	return retval;
17755356f261SAditya Kali }
17765356f261SAditya Kali 
17775356f261SAditya Kali /*
1778d91bd2c1SSeunghun Lee  * This is a special get_block_t callback which is used by
1779b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
1780b920c755STheodore Ts'o  * reserve space for a single block.
178129fa89d0SAneesh Kumar K.V  *
178229fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
178329fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
178429fa89d0SAneesh Kumar K.V  *
178529fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
178629fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
178729fa89d0SAneesh Kumar K.V  * initialized properly.
178864769240SAlex Tomas  */
17899c3569b5STao Ma int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
17902ed88685STheodore Ts'o 			   struct buffer_head *bh, int create)
179164769240SAlex Tomas {
17922ed88685STheodore Ts'o 	struct ext4_map_blocks map;
179364769240SAlex Tomas 	int ret = 0;
179464769240SAlex Tomas 
179564769240SAlex Tomas 	BUG_ON(create == 0);
17962ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
17972ed88685STheodore Ts'o 
17982ed88685STheodore Ts'o 	map.m_lblk = iblock;
17992ed88685STheodore Ts'o 	map.m_len = 1;
180064769240SAlex Tomas 
180164769240SAlex Tomas 	/*
180264769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
180364769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
180464769240SAlex Tomas 	 * the same as allocated blocks.
180564769240SAlex Tomas 	 */
18065356f261SAditya Kali 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
18075356f261SAditya Kali 	if (ret <= 0)
18082ed88685STheodore Ts'o 		return ret;
180964769240SAlex Tomas 
18102ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
1811ed8ad838SJan Kara 	ext4_update_bh_state(bh, map.m_flags);
18122ed88685STheodore Ts'o 
18132ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
18142ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
18152ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
18162ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
18172ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
18182ed88685STheodore Ts'o 		 * for partial write.
18192ed88685STheodore Ts'o 		 */
18202ed88685STheodore Ts'o 		set_buffer_new(bh);
1821c8205636STheodore Ts'o 		set_buffer_mapped(bh);
18222ed88685STheodore Ts'o 	}
18232ed88685STheodore Ts'o 	return 0;
182464769240SAlex Tomas }
182561628a3fSMingming Cao 
182662e086beSAneesh Kumar K.V static int bget_one(handle_t *handle, struct buffer_head *bh)
182762e086beSAneesh Kumar K.V {
182862e086beSAneesh Kumar K.V 	get_bh(bh);
182962e086beSAneesh Kumar K.V 	return 0;
183062e086beSAneesh Kumar K.V }
183162e086beSAneesh Kumar K.V 
183262e086beSAneesh Kumar K.V static int bput_one(handle_t *handle, struct buffer_head *bh)
183362e086beSAneesh Kumar K.V {
183462e086beSAneesh Kumar K.V 	put_bh(bh);
183562e086beSAneesh Kumar K.V 	return 0;
183662e086beSAneesh Kumar K.V }
183762e086beSAneesh Kumar K.V 
183862e086beSAneesh Kumar K.V static int __ext4_journalled_writepage(struct page *page,
183962e086beSAneesh Kumar K.V 				       unsigned int len)
184062e086beSAneesh Kumar K.V {
184162e086beSAneesh Kumar K.V 	struct address_space *mapping = page->mapping;
184262e086beSAneesh Kumar K.V 	struct inode *inode = mapping->host;
18433fdcfb66STao Ma 	struct buffer_head *page_bufs = NULL;
184462e086beSAneesh Kumar K.V 	handle_t *handle = NULL;
18453fdcfb66STao Ma 	int ret = 0, err = 0;
18463fdcfb66STao Ma 	int inline_data = ext4_has_inline_data(inode);
18473fdcfb66STao Ma 	struct buffer_head *inode_bh = NULL;
184862e086beSAneesh Kumar K.V 
1849cb20d518STheodore Ts'o 	ClearPageChecked(page);
18503fdcfb66STao Ma 
18513fdcfb66STao Ma 	if (inline_data) {
18523fdcfb66STao Ma 		BUG_ON(page->index != 0);
18533fdcfb66STao Ma 		BUG_ON(len > ext4_get_max_inline_size(inode));
18543fdcfb66STao Ma 		inode_bh = ext4_journalled_write_inline_data(inode, len, page);
18553fdcfb66STao Ma 		if (inode_bh == NULL)
18563fdcfb66STao Ma 			goto out;
18573fdcfb66STao Ma 	} else {
185862e086beSAneesh Kumar K.V 		page_bufs = page_buffers(page);
18593fdcfb66STao Ma 		if (!page_bufs) {
18603fdcfb66STao Ma 			BUG();
18613fdcfb66STao Ma 			goto out;
18623fdcfb66STao Ma 		}
18633fdcfb66STao Ma 		ext4_walk_page_buffers(handle, page_bufs, 0, len,
18643fdcfb66STao Ma 				       NULL, bget_one);
18653fdcfb66STao Ma 	}
1866bdf96838STheodore Ts'o 	/*
1867bdf96838STheodore Ts'o 	 * We need to release the page lock before we start the
1868bdf96838STheodore Ts'o 	 * journal, so grab a reference so the page won't disappear
1869bdf96838STheodore Ts'o 	 * out from under us.
1870bdf96838STheodore Ts'o 	 */
1871bdf96838STheodore Ts'o 	get_page(page);
187262e086beSAneesh Kumar K.V 	unlock_page(page);
187362e086beSAneesh Kumar K.V 
18749924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
18759924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
187662e086beSAneesh Kumar K.V 	if (IS_ERR(handle)) {
187762e086beSAneesh Kumar K.V 		ret = PTR_ERR(handle);
1878bdf96838STheodore Ts'o 		put_page(page);
1879bdf96838STheodore Ts'o 		goto out_no_pagelock;
1880bdf96838STheodore Ts'o 	}
1881bdf96838STheodore Ts'o 	BUG_ON(!ext4_handle_valid(handle));
1882bdf96838STheodore Ts'o 
1883bdf96838STheodore Ts'o 	lock_page(page);
1884bdf96838STheodore Ts'o 	put_page(page);
1885bdf96838STheodore Ts'o 	if (page->mapping != mapping) {
1886bdf96838STheodore Ts'o 		/* The page got truncated from under us */
1887bdf96838STheodore Ts'o 		ext4_journal_stop(handle);
1888bdf96838STheodore Ts'o 		ret = 0;
188962e086beSAneesh Kumar K.V 		goto out;
189062e086beSAneesh Kumar K.V 	}
189162e086beSAneesh Kumar K.V 
18923fdcfb66STao Ma 	if (inline_data) {
1893362eca70STheodore Ts'o 		ret = ext4_mark_inode_dirty(handle, inode);
18943fdcfb66STao Ma 	} else {
1895f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
189662e086beSAneesh Kumar K.V 					     do_journal_get_write_access);
189762e086beSAneesh Kumar K.V 
1898f19d5870STao Ma 		err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
189962e086beSAneesh Kumar K.V 					     write_end_fn);
19003fdcfb66STao Ma 	}
190162e086beSAneesh Kumar K.V 	if (ret == 0)
190262e086beSAneesh Kumar K.V 		ret = err;
19032d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
190462e086beSAneesh Kumar K.V 	err = ext4_journal_stop(handle);
190562e086beSAneesh Kumar K.V 	if (!ret)
190662e086beSAneesh Kumar K.V 		ret = err;
190762e086beSAneesh Kumar K.V 
19083fdcfb66STao Ma 	if (!ext4_has_inline_data(inode))
19098c9367fdSTheodore Ts'o 		ext4_walk_page_buffers(NULL, page_bufs, 0, len,
19103fdcfb66STao Ma 				       NULL, bput_one);
191119f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
191262e086beSAneesh Kumar K.V out:
1913bdf96838STheodore Ts'o 	unlock_page(page);
1914bdf96838STheodore Ts'o out_no_pagelock:
19153fdcfb66STao Ma 	brelse(inode_bh);
191662e086beSAneesh Kumar K.V 	return ret;
191762e086beSAneesh Kumar K.V }
191862e086beSAneesh Kumar K.V 
191961628a3fSMingming Cao /*
192043ce1d23SAneesh Kumar K.V  * Note that we don't need to start a transaction unless we're journaling data
192143ce1d23SAneesh Kumar K.V  * because we should have holes filled from ext4_page_mkwrite(). We even don't
192243ce1d23SAneesh Kumar K.V  * need to file the inode to the transaction's list in ordered mode because if
192343ce1d23SAneesh Kumar K.V  * we are writing back data added by write(), the inode is already there and if
192443ce1d23SAneesh Kumar K.V  * we are writing back data modified via mmap(), no one guarantees in which
192543ce1d23SAneesh Kumar K.V  * transaction the data will hit the disk. In case we are journaling data, we
192643ce1d23SAneesh Kumar K.V  * cannot start transaction directly because transaction start ranks above page
192743ce1d23SAneesh Kumar K.V  * lock so we have to do some magic.
192843ce1d23SAneesh Kumar K.V  *
1929b920c755STheodore Ts'o  * This function can get called via...
193020970ba6STheodore Ts'o  *   - ext4_writepages after taking page lock (have journal handle)
1931b920c755STheodore Ts'o  *   - journal_submit_inode_data_buffers (no journal handle)
1932f6463b0dSArtem Bityutskiy  *   - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1933b920c755STheodore Ts'o  *   - grab_page_cache when doing write_begin (have journal handle)
193443ce1d23SAneesh Kumar K.V  *
193543ce1d23SAneesh Kumar K.V  * We don't do any block allocation in this function. If we have page with
193643ce1d23SAneesh Kumar K.V  * multiple blocks we need to write those buffer_heads that are mapped. This
193743ce1d23SAneesh Kumar K.V  * is important for mmaped based write. So if we do with blocksize 1K
193843ce1d23SAneesh Kumar K.V  * truncate(f, 1024);
193943ce1d23SAneesh Kumar K.V  * a = mmap(f, 0, 4096);
194043ce1d23SAneesh Kumar K.V  * a[0] = 'a';
194143ce1d23SAneesh Kumar K.V  * truncate(f, 4096);
194243ce1d23SAneesh Kumar K.V  * we have in the page first buffer_head mapped via page_mkwrite call back
194390802ed9SPaul Bolle  * but other buffer_heads would be unmapped but dirty (dirty done via the
194443ce1d23SAneesh Kumar K.V  * do_wp_page). So writepage should write the first block. If we modify
194543ce1d23SAneesh Kumar K.V  * the mmap area beyond 1024 we will again get a page_fault and the
194643ce1d23SAneesh Kumar K.V  * page_mkwrite callback will do the block allocation and mark the
194743ce1d23SAneesh Kumar K.V  * buffer_heads mapped.
194843ce1d23SAneesh Kumar K.V  *
194943ce1d23SAneesh Kumar K.V  * We redirty the page if we have any buffer_heads that is either delay or
195043ce1d23SAneesh Kumar K.V  * unwritten in the page.
195143ce1d23SAneesh Kumar K.V  *
195243ce1d23SAneesh Kumar K.V  * We can get recursively called as show below.
195343ce1d23SAneesh Kumar K.V  *
195443ce1d23SAneesh Kumar K.V  *	ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
195543ce1d23SAneesh Kumar K.V  *		ext4_writepage()
195643ce1d23SAneesh Kumar K.V  *
195743ce1d23SAneesh Kumar K.V  * But since we don't do any block allocation we should not deadlock.
195843ce1d23SAneesh Kumar K.V  * Page also have the dirty flag cleared so we don't get recurive page_lock.
195961628a3fSMingming Cao  */
196043ce1d23SAneesh Kumar K.V static int ext4_writepage(struct page *page,
196164769240SAlex Tomas 			  struct writeback_control *wbc)
196264769240SAlex Tomas {
1963f8bec370SJan Kara 	int ret = 0;
196461628a3fSMingming Cao 	loff_t size;
1965498e5f24STheodore Ts'o 	unsigned int len;
1966744692dcSJiaying Zhang 	struct buffer_head *page_bufs = NULL;
196761628a3fSMingming Cao 	struct inode *inode = page->mapping->host;
196836ade451SJan Kara 	struct ext4_io_submit io_submit;
19691c8349a1SNamjae Jeon 	bool keep_towrite = false;
197064769240SAlex Tomas 
19710db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
1972c2a559bcSyangerkun 		inode->i_mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
19730db1ff22STheodore Ts'o 		unlock_page(page);
19740db1ff22STheodore Ts'o 		return -EIO;
19750db1ff22STheodore Ts'o 	}
19760db1ff22STheodore Ts'o 
1977a9c667f8SLukas Czerner 	trace_ext4_writepage(page);
197861628a3fSMingming Cao 	size = i_size_read(inode);
1979c93d8f88SEric Biggers 	if (page->index == size >> PAGE_SHIFT &&
1980c93d8f88SEric Biggers 	    !ext4_verity_in_progress(inode))
198109cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
198261628a3fSMingming Cao 	else
198309cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
198461628a3fSMingming Cao 
1985f0e6c985SAneesh Kumar K.V 	page_bufs = page_buffers(page);
198664769240SAlex Tomas 	/*
1987fe386132SJan Kara 	 * We cannot do block allocation or other extent handling in this
1988fe386132SJan Kara 	 * function. If there are buffers needing that, we have to redirty
1989fe386132SJan Kara 	 * the page. But we may reach here when we do a journal commit via
1990fe386132SJan Kara 	 * journal_submit_inode_data_buffers() and in that case we must write
1991fe386132SJan Kara 	 * allocated buffers to achieve data=ordered mode guarantees.
1992cccd147aSTheodore Ts'o 	 *
1993cccd147aSTheodore Ts'o 	 * Also, if there is only one buffer per page (the fs block
1994cccd147aSTheodore Ts'o 	 * size == the page size), if one buffer needs block
1995cccd147aSTheodore Ts'o 	 * allocation or needs to modify the extent tree to clear the
1996cccd147aSTheodore Ts'o 	 * unwritten flag, we know that the page can't be written at
1997cccd147aSTheodore Ts'o 	 * all, so we might as well refuse the write immediately.
1998cccd147aSTheodore Ts'o 	 * Unfortunately if the block size != page size, we can't as
1999cccd147aSTheodore Ts'o 	 * easily detect this case using ext4_walk_page_buffers(), but
2000cccd147aSTheodore Ts'o 	 * for the extremely common case, this is an optimization that
2001cccd147aSTheodore Ts'o 	 * skips a useless round trip through ext4_bio_write_page().
200264769240SAlex Tomas 	 */
2003f19d5870STao Ma 	if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2004c364b22cSAneesh Kumar K.V 				   ext4_bh_delay_or_unwritten)) {
200561628a3fSMingming Cao 		redirty_page_for_writepage(wbc, page);
2006cccd147aSTheodore Ts'o 		if ((current->flags & PF_MEMALLOC) ||
200709cbfeafSKirill A. Shutemov 		    (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2008fe386132SJan Kara 			/*
2009fe386132SJan Kara 			 * For memory cleaning there's no point in writing only
2010fe386132SJan Kara 			 * some buffers. So just bail out. Warn if we came here
2011fe386132SJan Kara 			 * from direct reclaim.
2012fe386132SJan Kara 			 */
2013fe386132SJan Kara 			WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2014fe386132SJan Kara 							== PF_MEMALLOC);
201561628a3fSMingming Cao 			unlock_page(page);
201661628a3fSMingming Cao 			return 0;
201761628a3fSMingming Cao 		}
20181c8349a1SNamjae Jeon 		keep_towrite = true;
2019f0e6c985SAneesh Kumar K.V 	}
202064769240SAlex Tomas 
2021cb20d518STheodore Ts'o 	if (PageChecked(page) && ext4_should_journal_data(inode))
202243ce1d23SAneesh Kumar K.V 		/*
202343ce1d23SAneesh Kumar K.V 		 * It's mmapped pagecache.  Add buffers and journal it.  There
202443ce1d23SAneesh Kumar K.V 		 * doesn't seem much point in redirtying the page here.
202543ce1d23SAneesh Kumar K.V 		 */
20263f0ca309SWu Fengguang 		return __ext4_journalled_writepage(page, len);
202743ce1d23SAneesh Kumar K.V 
202897a851edSJan Kara 	ext4_io_submit_init(&io_submit, wbc);
202997a851edSJan Kara 	io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
203097a851edSJan Kara 	if (!io_submit.io_end) {
203197a851edSJan Kara 		redirty_page_for_writepage(wbc, page);
203297a851edSJan Kara 		unlock_page(page);
203397a851edSJan Kara 		return -ENOMEM;
203497a851edSJan Kara 	}
20351c8349a1SNamjae Jeon 	ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
203636ade451SJan Kara 	ext4_io_submit(&io_submit);
203797a851edSJan Kara 	/* Drop io_end reference we got from init */
203897a851edSJan Kara 	ext4_put_io_end_defer(io_submit.io_end);
203964769240SAlex Tomas 	return ret;
204064769240SAlex Tomas }
204164769240SAlex Tomas 
20425f1132b2SJan Kara static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
20435f1132b2SJan Kara {
20445f1132b2SJan Kara 	int len;
2045a056bdaaSJan Kara 	loff_t size;
20465f1132b2SJan Kara 	int err;
20475f1132b2SJan Kara 
20485f1132b2SJan Kara 	BUG_ON(page->index != mpd->first_page);
2049a056bdaaSJan Kara 	clear_page_dirty_for_io(page);
2050a056bdaaSJan Kara 	/*
2051a056bdaaSJan Kara 	 * We have to be very careful here!  Nothing protects writeback path
2052a056bdaaSJan Kara 	 * against i_size changes and the page can be writeably mapped into
2053a056bdaaSJan Kara 	 * page tables. So an application can be growing i_size and writing
2054a056bdaaSJan Kara 	 * data through mmap while writeback runs. clear_page_dirty_for_io()
2055a056bdaaSJan Kara 	 * write-protects our page in page tables and the page cannot get
2056a056bdaaSJan Kara 	 * written to again until we release page lock. So only after
2057a056bdaaSJan Kara 	 * clear_page_dirty_for_io() we are safe to sample i_size for
2058a056bdaaSJan Kara 	 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2059a056bdaaSJan Kara 	 * on the barrier provided by TestClearPageDirty in
2060a056bdaaSJan Kara 	 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2061a056bdaaSJan Kara 	 * after page tables are updated.
2062a056bdaaSJan Kara 	 */
2063a056bdaaSJan Kara 	size = i_size_read(mpd->inode);
2064c93d8f88SEric Biggers 	if (page->index == size >> PAGE_SHIFT &&
2065c93d8f88SEric Biggers 	    !ext4_verity_in_progress(mpd->inode))
206609cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
20675f1132b2SJan Kara 	else
206809cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
20691c8349a1SNamjae Jeon 	err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
20705f1132b2SJan Kara 	if (!err)
20715f1132b2SJan Kara 		mpd->wbc->nr_to_write--;
20725f1132b2SJan Kara 	mpd->first_page++;
20735f1132b2SJan Kara 
20745f1132b2SJan Kara 	return err;
20755f1132b2SJan Kara }
20765f1132b2SJan Kara 
20774e7ea81dSJan Kara #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
20784e7ea81dSJan Kara 
207961628a3fSMingming Cao /*
2080fffb2739SJan Kara  * mballoc gives us at most this number of blocks...
2081fffb2739SJan Kara  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2082fffb2739SJan Kara  * The rest of mballoc seems to handle chunks up to full group size.
208361628a3fSMingming Cao  */
2084fffb2739SJan Kara #define MAX_WRITEPAGES_EXTENT_LEN 2048
2085525f4ed8SMingming Cao 
2086525f4ed8SMingming Cao /*
20874e7ea81dSJan Kara  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
20884e7ea81dSJan Kara  *
20894e7ea81dSJan Kara  * @mpd - extent of blocks
20904e7ea81dSJan Kara  * @lblk - logical number of the block in the file
209109930042SJan Kara  * @bh - buffer head we want to add to the extent
20924e7ea81dSJan Kara  *
209309930042SJan Kara  * The function is used to collect contig. blocks in the same state. If the
209409930042SJan Kara  * buffer doesn't require mapping for writeback and we haven't started the
209509930042SJan Kara  * extent of buffers to map yet, the function returns 'true' immediately - the
209609930042SJan Kara  * caller can write the buffer right away. Otherwise the function returns true
209709930042SJan Kara  * if the block has been added to the extent, false if the block couldn't be
209809930042SJan Kara  * added.
20994e7ea81dSJan Kara  */
210009930042SJan Kara static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
210109930042SJan Kara 				   struct buffer_head *bh)
21024e7ea81dSJan Kara {
21034e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
21044e7ea81dSJan Kara 
210509930042SJan Kara 	/* Buffer that doesn't need mapping for writeback? */
210609930042SJan Kara 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
210709930042SJan Kara 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
210809930042SJan Kara 		/* So far no extent to map => we write the buffer right away */
210909930042SJan Kara 		if (map->m_len == 0)
211009930042SJan Kara 			return true;
211109930042SJan Kara 		return false;
211209930042SJan Kara 	}
21134e7ea81dSJan Kara 
21144e7ea81dSJan Kara 	/* First block in the extent? */
21154e7ea81dSJan Kara 	if (map->m_len == 0) {
2116dddbd6acSJan Kara 		/* We cannot map unless handle is started... */
2117dddbd6acSJan Kara 		if (!mpd->do_map)
2118dddbd6acSJan Kara 			return false;
21194e7ea81dSJan Kara 		map->m_lblk = lblk;
21204e7ea81dSJan Kara 		map->m_len = 1;
212109930042SJan Kara 		map->m_flags = bh->b_state & BH_FLAGS;
212209930042SJan Kara 		return true;
21234e7ea81dSJan Kara 	}
21244e7ea81dSJan Kara 
212509930042SJan Kara 	/* Don't go larger than mballoc is willing to allocate */
212609930042SJan Kara 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
212709930042SJan Kara 		return false;
212809930042SJan Kara 
21294e7ea81dSJan Kara 	/* Can we merge the block to our big extent? */
21304e7ea81dSJan Kara 	if (lblk == map->m_lblk + map->m_len &&
213109930042SJan Kara 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
21324e7ea81dSJan Kara 		map->m_len++;
213309930042SJan Kara 		return true;
21344e7ea81dSJan Kara 	}
213509930042SJan Kara 	return false;
21364e7ea81dSJan Kara }
21374e7ea81dSJan Kara 
21385f1132b2SJan Kara /*
21395f1132b2SJan Kara  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
21405f1132b2SJan Kara  *
21415f1132b2SJan Kara  * @mpd - extent of blocks for mapping
21425f1132b2SJan Kara  * @head - the first buffer in the page
21435f1132b2SJan Kara  * @bh - buffer we should start processing from
21445f1132b2SJan Kara  * @lblk - logical number of the block in the file corresponding to @bh
21455f1132b2SJan Kara  *
21465f1132b2SJan Kara  * Walk through page buffers from @bh upto @head (exclusive) and either submit
21475f1132b2SJan Kara  * the page for IO if all buffers in this page were mapped and there's no
21485f1132b2SJan Kara  * accumulated extent of buffers to map or add buffers in the page to the
21495f1132b2SJan Kara  * extent of buffers to map. The function returns 1 if the caller can continue
21505f1132b2SJan Kara  * by processing the next page, 0 if it should stop adding buffers to the
21515f1132b2SJan Kara  * extent to map because we cannot extend it anymore. It can also return value
21525f1132b2SJan Kara  * < 0 in case of error during IO submission.
21535f1132b2SJan Kara  */
21545f1132b2SJan Kara static int mpage_process_page_bufs(struct mpage_da_data *mpd,
21554e7ea81dSJan Kara 				   struct buffer_head *head,
21564e7ea81dSJan Kara 				   struct buffer_head *bh,
21574e7ea81dSJan Kara 				   ext4_lblk_t lblk)
21584e7ea81dSJan Kara {
21594e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
21605f1132b2SJan Kara 	int err;
216193407472SFabian Frederick 	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
21624e7ea81dSJan Kara 							>> inode->i_blkbits;
21634e7ea81dSJan Kara 
2164c93d8f88SEric Biggers 	if (ext4_verity_in_progress(inode))
2165c93d8f88SEric Biggers 		blocks = EXT_MAX_BLOCKS;
2166c93d8f88SEric Biggers 
21674e7ea81dSJan Kara 	do {
21684e7ea81dSJan Kara 		BUG_ON(buffer_locked(bh));
21694e7ea81dSJan Kara 
217009930042SJan Kara 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
21714e7ea81dSJan Kara 			/* Found extent to map? */
21724e7ea81dSJan Kara 			if (mpd->map.m_len)
21735f1132b2SJan Kara 				return 0;
2174dddbd6acSJan Kara 			/* Buffer needs mapping and handle is not started? */
2175dddbd6acSJan Kara 			if (!mpd->do_map)
2176dddbd6acSJan Kara 				return 0;
217709930042SJan Kara 			/* Everything mapped so far and we hit EOF */
21785f1132b2SJan Kara 			break;
21794e7ea81dSJan Kara 		}
21804e7ea81dSJan Kara 	} while (lblk++, (bh = bh->b_this_page) != head);
21815f1132b2SJan Kara 	/* So far everything mapped? Submit the page for IO. */
21825f1132b2SJan Kara 	if (mpd->map.m_len == 0) {
21835f1132b2SJan Kara 		err = mpage_submit_page(mpd, head->b_page);
21845f1132b2SJan Kara 		if (err < 0)
21854e7ea81dSJan Kara 			return err;
21864e7ea81dSJan Kara 	}
21875f1132b2SJan Kara 	return lblk < blocks;
21885f1132b2SJan Kara }
21894e7ea81dSJan Kara 
21904e7ea81dSJan Kara /*
21912943fdbcSRitesh Harjani  * mpage_process_page - update page buffers corresponding to changed extent and
21922943fdbcSRitesh Harjani  *		       may submit fully mapped page for IO
21932943fdbcSRitesh Harjani  *
21942943fdbcSRitesh Harjani  * @mpd		- description of extent to map, on return next extent to map
21952943fdbcSRitesh Harjani  * @m_lblk	- logical block mapping.
21962943fdbcSRitesh Harjani  * @m_pblk	- corresponding physical mapping.
21972943fdbcSRitesh Harjani  * @map_bh	- determines on return whether this page requires any further
21982943fdbcSRitesh Harjani  *		  mapping or not.
21992943fdbcSRitesh Harjani  * Scan given page buffers corresponding to changed extent and update buffer
22002943fdbcSRitesh Harjani  * state according to new extent state.
22012943fdbcSRitesh Harjani  * We map delalloc buffers to their physical location, clear unwritten bits.
22022943fdbcSRitesh Harjani  * If the given page is not fully mapped, we update @map to the next extent in
22032943fdbcSRitesh Harjani  * the given page that needs mapping & return @map_bh as true.
22042943fdbcSRitesh Harjani  */
22052943fdbcSRitesh Harjani static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
22062943fdbcSRitesh Harjani 			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
22072943fdbcSRitesh Harjani 			      bool *map_bh)
22082943fdbcSRitesh Harjani {
22092943fdbcSRitesh Harjani 	struct buffer_head *head, *bh;
22102943fdbcSRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
22112943fdbcSRitesh Harjani 	ext4_lblk_t lblk = *m_lblk;
22122943fdbcSRitesh Harjani 	ext4_fsblk_t pblock = *m_pblk;
22132943fdbcSRitesh Harjani 	int err = 0;
2214c8cc8816SRitesh Harjani 	int blkbits = mpd->inode->i_blkbits;
2215c8cc8816SRitesh Harjani 	ssize_t io_end_size = 0;
2216c8cc8816SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
22172943fdbcSRitesh Harjani 
22182943fdbcSRitesh Harjani 	bh = head = page_buffers(page);
22192943fdbcSRitesh Harjani 	do {
22202943fdbcSRitesh Harjani 		if (lblk < mpd->map.m_lblk)
22212943fdbcSRitesh Harjani 			continue;
22222943fdbcSRitesh Harjani 		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
22232943fdbcSRitesh Harjani 			/*
22242943fdbcSRitesh Harjani 			 * Buffer after end of mapped extent.
22252943fdbcSRitesh Harjani 			 * Find next buffer in the page to map.
22262943fdbcSRitesh Harjani 			 */
22272943fdbcSRitesh Harjani 			mpd->map.m_len = 0;
22282943fdbcSRitesh Harjani 			mpd->map.m_flags = 0;
2229c8cc8816SRitesh Harjani 			io_end_vec->size += io_end_size;
2230c8cc8816SRitesh Harjani 			io_end_size = 0;
22312943fdbcSRitesh Harjani 
22322943fdbcSRitesh Harjani 			err = mpage_process_page_bufs(mpd, head, bh, lblk);
22332943fdbcSRitesh Harjani 			if (err > 0)
22342943fdbcSRitesh Harjani 				err = 0;
2235c8cc8816SRitesh Harjani 			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2236c8cc8816SRitesh Harjani 				io_end_vec = ext4_alloc_io_end_vec(io_end);
22374d06bfb9SRitesh Harjani 				if (IS_ERR(io_end_vec)) {
22384d06bfb9SRitesh Harjani 					err = PTR_ERR(io_end_vec);
22394d06bfb9SRitesh Harjani 					goto out;
22404d06bfb9SRitesh Harjani 				}
2241c8cc8816SRitesh Harjani 				io_end_vec->offset = mpd->map.m_lblk << blkbits;
2242c8cc8816SRitesh Harjani 			}
22432943fdbcSRitesh Harjani 			*map_bh = true;
22442943fdbcSRitesh Harjani 			goto out;
22452943fdbcSRitesh Harjani 		}
22462943fdbcSRitesh Harjani 		if (buffer_delay(bh)) {
22472943fdbcSRitesh Harjani 			clear_buffer_delay(bh);
22482943fdbcSRitesh Harjani 			bh->b_blocknr = pblock++;
22492943fdbcSRitesh Harjani 		}
22502943fdbcSRitesh Harjani 		clear_buffer_unwritten(bh);
2251c8cc8816SRitesh Harjani 		io_end_size += (1 << blkbits);
22522943fdbcSRitesh Harjani 	} while (lblk++, (bh = bh->b_this_page) != head);
2253c8cc8816SRitesh Harjani 
2254c8cc8816SRitesh Harjani 	io_end_vec->size += io_end_size;
2255c8cc8816SRitesh Harjani 	io_end_size = 0;
22562943fdbcSRitesh Harjani 	*map_bh = false;
22572943fdbcSRitesh Harjani out:
22582943fdbcSRitesh Harjani 	*m_lblk = lblk;
22592943fdbcSRitesh Harjani 	*m_pblk = pblock;
22602943fdbcSRitesh Harjani 	return err;
22612943fdbcSRitesh Harjani }
22622943fdbcSRitesh Harjani 
22632943fdbcSRitesh Harjani /*
22644e7ea81dSJan Kara  * mpage_map_buffers - update buffers corresponding to changed extent and
22654e7ea81dSJan Kara  *		       submit fully mapped pages for IO
22664e7ea81dSJan Kara  *
22674e7ea81dSJan Kara  * @mpd - description of extent to map, on return next extent to map
22684e7ea81dSJan Kara  *
22694e7ea81dSJan Kara  * Scan buffers corresponding to changed extent (we expect corresponding pages
22704e7ea81dSJan Kara  * to be already locked) and update buffer state according to new extent state.
22714e7ea81dSJan Kara  * We map delalloc buffers to their physical location, clear unwritten bits,
2272556615dcSLukas Czerner  * and mark buffers as uninit when we perform writes to unwritten extents
22734e7ea81dSJan Kara  * and do extent conversion after IO is finished. If the last page is not fully
22744e7ea81dSJan Kara  * mapped, we update @map to the next extent in the last page that needs
22754e7ea81dSJan Kara  * mapping. Otherwise we submit the page for IO.
22764e7ea81dSJan Kara  */
22774e7ea81dSJan Kara static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
22784e7ea81dSJan Kara {
22794e7ea81dSJan Kara 	struct pagevec pvec;
22804e7ea81dSJan Kara 	int nr_pages, i;
22814e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
228209cbfeafSKirill A. Shutemov 	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
22834e7ea81dSJan Kara 	pgoff_t start, end;
22844e7ea81dSJan Kara 	ext4_lblk_t lblk;
22852943fdbcSRitesh Harjani 	ext4_fsblk_t pblock;
22864e7ea81dSJan Kara 	int err;
22872943fdbcSRitesh Harjani 	bool map_bh = false;
22884e7ea81dSJan Kara 
22894e7ea81dSJan Kara 	start = mpd->map.m_lblk >> bpp_bits;
22904e7ea81dSJan Kara 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
22914e7ea81dSJan Kara 	lblk = start << bpp_bits;
22924e7ea81dSJan Kara 	pblock = mpd->map.m_pblk;
22934e7ea81dSJan Kara 
229486679820SMel Gorman 	pagevec_init(&pvec);
22954e7ea81dSJan Kara 	while (start <= end) {
22962b85a617SJan Kara 		nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2297397162ffSJan Kara 						&start, end);
22984e7ea81dSJan Kara 		if (nr_pages == 0)
22994e7ea81dSJan Kara 			break;
23004e7ea81dSJan Kara 		for (i = 0; i < nr_pages; i++) {
23014e7ea81dSJan Kara 			struct page *page = pvec.pages[i];
23024e7ea81dSJan Kara 
23032943fdbcSRitesh Harjani 			err = mpage_process_page(mpd, page, &lblk, &pblock,
23042943fdbcSRitesh Harjani 						 &map_bh);
23054e7ea81dSJan Kara 			/*
23062943fdbcSRitesh Harjani 			 * If map_bh is true, means page may require further bh
23072943fdbcSRitesh Harjani 			 * mapping, or maybe the page was submitted for IO.
23082943fdbcSRitesh Harjani 			 * So we return to call further extent mapping.
23094e7ea81dSJan Kara 			 */
23102943fdbcSRitesh Harjani 			if (err < 0 || map_bh == true)
23112943fdbcSRitesh Harjani 				goto out;
23124e7ea81dSJan Kara 			/* Page fully mapped - let IO run! */
23134e7ea81dSJan Kara 			err = mpage_submit_page(mpd, page);
23142943fdbcSRitesh Harjani 			if (err < 0)
23152943fdbcSRitesh Harjani 				goto out;
23164e7ea81dSJan Kara 		}
23174e7ea81dSJan Kara 		pagevec_release(&pvec);
23184e7ea81dSJan Kara 	}
23194e7ea81dSJan Kara 	/* Extent fully mapped and matches with page boundary. We are done. */
23204e7ea81dSJan Kara 	mpd->map.m_len = 0;
23214e7ea81dSJan Kara 	mpd->map.m_flags = 0;
23224e7ea81dSJan Kara 	return 0;
23232943fdbcSRitesh Harjani out:
23242943fdbcSRitesh Harjani 	pagevec_release(&pvec);
23252943fdbcSRitesh Harjani 	return err;
23264e7ea81dSJan Kara }
23274e7ea81dSJan Kara 
23284e7ea81dSJan Kara static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
23294e7ea81dSJan Kara {
23304e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
23314e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
23324e7ea81dSJan Kara 	int get_blocks_flags;
2333090f32eeSLukas Czerner 	int err, dioread_nolock;
23344e7ea81dSJan Kara 
23354e7ea81dSJan Kara 	trace_ext4_da_write_pages_extent(inode, map);
23364e7ea81dSJan Kara 	/*
23374e7ea81dSJan Kara 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2338556615dcSLukas Czerner 	 * to convert an unwritten extent to be initialized (in the case
23394e7ea81dSJan Kara 	 * where we have written into one or more preallocated blocks).  It is
23404e7ea81dSJan Kara 	 * possible that we're going to need more metadata blocks than
23414e7ea81dSJan Kara 	 * previously reserved. However we must not fail because we're in
23424e7ea81dSJan Kara 	 * writeback and there is nothing we can do about it so it might result
23434e7ea81dSJan Kara 	 * in data loss.  So use reserved blocks to allocate metadata if
23444e7ea81dSJan Kara 	 * possible.
23454e7ea81dSJan Kara 	 *
2346754cfed6STheodore Ts'o 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2347754cfed6STheodore Ts'o 	 * the blocks in question are delalloc blocks.  This indicates
2348754cfed6STheodore Ts'o 	 * that the blocks and quotas has already been checked when
2349754cfed6STheodore Ts'o 	 * the data was copied into the page cache.
23504e7ea81dSJan Kara 	 */
23514e7ea81dSJan Kara 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2352ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2353ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_IO_SUBMIT;
2354090f32eeSLukas Czerner 	dioread_nolock = ext4_should_dioread_nolock(inode);
2355090f32eeSLukas Czerner 	if (dioread_nolock)
23564e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
23574e7ea81dSJan Kara 	if (map->m_flags & (1 << BH_Delay))
23584e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
23594e7ea81dSJan Kara 
23604e7ea81dSJan Kara 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
23614e7ea81dSJan Kara 	if (err < 0)
23624e7ea81dSJan Kara 		return err;
2363090f32eeSLukas Czerner 	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
23646b523df4SJan Kara 		if (!mpd->io_submit.io_end->handle &&
23656b523df4SJan Kara 		    ext4_handle_valid(handle)) {
23666b523df4SJan Kara 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
23676b523df4SJan Kara 			handle->h_rsv_handle = NULL;
23686b523df4SJan Kara 		}
23693613d228SJan Kara 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
23706b523df4SJan Kara 	}
23714e7ea81dSJan Kara 
23724e7ea81dSJan Kara 	BUG_ON(map->m_len == 0);
23734e7ea81dSJan Kara 	return 0;
23744e7ea81dSJan Kara }
23754e7ea81dSJan Kara 
23764e7ea81dSJan Kara /*
23774e7ea81dSJan Kara  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
23784e7ea81dSJan Kara  *				 mpd->len and submit pages underlying it for IO
23794e7ea81dSJan Kara  *
23804e7ea81dSJan Kara  * @handle - handle for journal operations
23814e7ea81dSJan Kara  * @mpd - extent to map
23827534e854SJan Kara  * @give_up_on_write - we set this to true iff there is a fatal error and there
23837534e854SJan Kara  *                     is no hope of writing the data. The caller should discard
23847534e854SJan Kara  *                     dirty pages to avoid infinite loops.
23854e7ea81dSJan Kara  *
23864e7ea81dSJan Kara  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
23874e7ea81dSJan Kara  * delayed, blocks are allocated, if it is unwritten, we may need to convert
23884e7ea81dSJan Kara  * them to initialized or split the described range from larger unwritten
23894e7ea81dSJan Kara  * extent. Note that we need not map all the described range since allocation
23904e7ea81dSJan Kara  * can return less blocks or the range is covered by more unwritten extents. We
23914e7ea81dSJan Kara  * cannot map more because we are limited by reserved transaction credits. On
23924e7ea81dSJan Kara  * the other hand we always make sure that the last touched page is fully
23934e7ea81dSJan Kara  * mapped so that it can be written out (and thus forward progress is
23944e7ea81dSJan Kara  * guaranteed). After mapping we submit all mapped pages for IO.
23954e7ea81dSJan Kara  */
23964e7ea81dSJan Kara static int mpage_map_and_submit_extent(handle_t *handle,
2397cb530541STheodore Ts'o 				       struct mpage_da_data *mpd,
2398cb530541STheodore Ts'o 				       bool *give_up_on_write)
23994e7ea81dSJan Kara {
24004e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
24014e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
24024e7ea81dSJan Kara 	int err;
24034e7ea81dSJan Kara 	loff_t disksize;
24046603120eSDmitry Monakhov 	int progress = 0;
2405c8cc8816SRitesh Harjani 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
24064d06bfb9SRitesh Harjani 	struct ext4_io_end_vec *io_end_vec;
24074e7ea81dSJan Kara 
24084d06bfb9SRitesh Harjani 	io_end_vec = ext4_alloc_io_end_vec(io_end);
24094d06bfb9SRitesh Harjani 	if (IS_ERR(io_end_vec))
24104d06bfb9SRitesh Harjani 		return PTR_ERR(io_end_vec);
2411c8cc8816SRitesh Harjani 	io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
241227d7c4edSJan Kara 	do {
24134e7ea81dSJan Kara 		err = mpage_map_one_extent(handle, mpd);
24144e7ea81dSJan Kara 		if (err < 0) {
24154e7ea81dSJan Kara 			struct super_block *sb = inode->i_sb;
24164e7ea81dSJan Kara 
24170db1ff22STheodore Ts'o 			if (ext4_forced_shutdown(EXT4_SB(sb)) ||
24180db1ff22STheodore Ts'o 			    EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2419cb530541STheodore Ts'o 				goto invalidate_dirty_pages;
24204e7ea81dSJan Kara 			/*
2421cb530541STheodore Ts'o 			 * Let the uper layers retry transient errors.
2422cb530541STheodore Ts'o 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2423cb530541STheodore Ts'o 			 * is non-zero, a commit should free up blocks.
24244e7ea81dSJan Kara 			 */
2425cb530541STheodore Ts'o 			if ((err == -ENOMEM) ||
24266603120eSDmitry Monakhov 			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
24276603120eSDmitry Monakhov 				if (progress)
24286603120eSDmitry Monakhov 					goto update_disksize;
2429cb530541STheodore Ts'o 				return err;
24306603120eSDmitry Monakhov 			}
24314e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24324e7ea81dSJan Kara 				 "Delayed block allocation failed for "
24334e7ea81dSJan Kara 				 "inode %lu at logical offset %llu with"
24344e7ea81dSJan Kara 				 " max blocks %u with error %d",
24354e7ea81dSJan Kara 				 inode->i_ino,
24364e7ea81dSJan Kara 				 (unsigned long long)map->m_lblk,
2437cb530541STheodore Ts'o 				 (unsigned)map->m_len, -err);
24384e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24394e7ea81dSJan Kara 				 "This should not happen!! Data will "
24404e7ea81dSJan Kara 				 "be lost\n");
24414e7ea81dSJan Kara 			if (err == -ENOSPC)
24424e7ea81dSJan Kara 				ext4_print_free_blocks(inode);
2443cb530541STheodore Ts'o 		invalidate_dirty_pages:
2444cb530541STheodore Ts'o 			*give_up_on_write = true;
24454e7ea81dSJan Kara 			return err;
24464e7ea81dSJan Kara 		}
24476603120eSDmitry Monakhov 		progress = 1;
24484e7ea81dSJan Kara 		/*
24494e7ea81dSJan Kara 		 * Update buffer state, submit mapped pages, and get us new
24504e7ea81dSJan Kara 		 * extent to map
24514e7ea81dSJan Kara 		 */
24524e7ea81dSJan Kara 		err = mpage_map_and_submit_buffers(mpd);
24534e7ea81dSJan Kara 		if (err < 0)
24546603120eSDmitry Monakhov 			goto update_disksize;
245527d7c4edSJan Kara 	} while (map->m_len);
24564e7ea81dSJan Kara 
24576603120eSDmitry Monakhov update_disksize:
2458622cad13STheodore Ts'o 	/*
2459622cad13STheodore Ts'o 	 * Update on-disk size after IO is submitted.  Races with
2460622cad13STheodore Ts'o 	 * truncate are avoided by checking i_size under i_data_sem.
2461622cad13STheodore Ts'o 	 */
246209cbfeafSKirill A. Shutemov 	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
246335df4299SQian Cai 	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
24644e7ea81dSJan Kara 		int err2;
2465622cad13STheodore Ts'o 		loff_t i_size;
24664e7ea81dSJan Kara 
2467622cad13STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
2468622cad13STheodore Ts'o 		i_size = i_size_read(inode);
2469622cad13STheodore Ts'o 		if (disksize > i_size)
2470622cad13STheodore Ts'o 			disksize = i_size;
2471622cad13STheodore Ts'o 		if (disksize > EXT4_I(inode)->i_disksize)
2472622cad13STheodore Ts'o 			EXT4_I(inode)->i_disksize = disksize;
2473622cad13STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
2474b907f2d5STheodore Ts'o 		err2 = ext4_mark_inode_dirty(handle, inode);
2475878520acSTheodore Ts'o 		if (err2) {
247654d3adbcSTheodore Ts'o 			ext4_error_err(inode->i_sb, -err2,
24774e7ea81dSJan Kara 				       "Failed to mark inode %lu dirty",
24784e7ea81dSJan Kara 				       inode->i_ino);
2479878520acSTheodore Ts'o 		}
24804e7ea81dSJan Kara 		if (!err)
24814e7ea81dSJan Kara 			err = err2;
24824e7ea81dSJan Kara 	}
24834e7ea81dSJan Kara 	return err;
24844e7ea81dSJan Kara }
24854e7ea81dSJan Kara 
24864e7ea81dSJan Kara /*
2487fffb2739SJan Kara  * Calculate the total number of credits to reserve for one writepages
248820970ba6STheodore Ts'o  * iteration. This is called from ext4_writepages(). We map an extent of
2489fffb2739SJan Kara  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2490fffb2739SJan Kara  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2491fffb2739SJan Kara  * bpp - 1 blocks in bpp different extents.
2492525f4ed8SMingming Cao  */
2493fffb2739SJan Kara static int ext4_da_writepages_trans_blocks(struct inode *inode)
2494fffb2739SJan Kara {
2495fffb2739SJan Kara 	int bpp = ext4_journal_blocks_per_page(inode);
2496525f4ed8SMingming Cao 
2497fffb2739SJan Kara 	return ext4_meta_trans_blocks(inode,
2498fffb2739SJan Kara 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2499525f4ed8SMingming Cao }
250061628a3fSMingming Cao 
25018e48dcfbSTheodore Ts'o /*
25024e7ea81dSJan Kara  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
25034e7ea81dSJan Kara  * 				 and underlying extent to map
25044e7ea81dSJan Kara  *
25054e7ea81dSJan Kara  * @mpd - where to look for pages
25064e7ea81dSJan Kara  *
25074e7ea81dSJan Kara  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
25084e7ea81dSJan Kara  * IO immediately. When we find a page which isn't mapped we start accumulating
25094e7ea81dSJan Kara  * extent of buffers underlying these pages that needs mapping (formed by
25104e7ea81dSJan Kara  * either delayed or unwritten buffers). We also lock the pages containing
25114e7ea81dSJan Kara  * these buffers. The extent found is returned in @mpd structure (starting at
25124e7ea81dSJan Kara  * mpd->lblk with length mpd->len blocks).
25134e7ea81dSJan Kara  *
25144e7ea81dSJan Kara  * Note that this function can attach bios to one io_end structure which are
25154e7ea81dSJan Kara  * neither logically nor physically contiguous. Although it may seem as an
25164e7ea81dSJan Kara  * unnecessary complication, it is actually inevitable in blocksize < pagesize
25174e7ea81dSJan Kara  * case as we need to track IO to all buffers underlying a page in one io_end.
25188e48dcfbSTheodore Ts'o  */
25194e7ea81dSJan Kara static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
25208e48dcfbSTheodore Ts'o {
25214e7ea81dSJan Kara 	struct address_space *mapping = mpd->inode->i_mapping;
25228e48dcfbSTheodore Ts'o 	struct pagevec pvec;
25234f01b02cSTheodore Ts'o 	unsigned int nr_pages;
2524aeac589aSMing Lei 	long left = mpd->wbc->nr_to_write;
25254e7ea81dSJan Kara 	pgoff_t index = mpd->first_page;
25264e7ea81dSJan Kara 	pgoff_t end = mpd->last_page;
252710bbd235SMatthew Wilcox 	xa_mark_t tag;
25284e7ea81dSJan Kara 	int i, err = 0;
25294e7ea81dSJan Kara 	int blkbits = mpd->inode->i_blkbits;
25304e7ea81dSJan Kara 	ext4_lblk_t lblk;
25314e7ea81dSJan Kara 	struct buffer_head *head;
25328e48dcfbSTheodore Ts'o 
25334e7ea81dSJan Kara 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
25345b41d924SEric Sandeen 		tag = PAGECACHE_TAG_TOWRITE;
25355b41d924SEric Sandeen 	else
25365b41d924SEric Sandeen 		tag = PAGECACHE_TAG_DIRTY;
25375b41d924SEric Sandeen 
253886679820SMel Gorman 	pagevec_init(&pvec);
25394e7ea81dSJan Kara 	mpd->map.m_len = 0;
25404e7ea81dSJan Kara 	mpd->next_page = index;
25414f01b02cSTheodore Ts'o 	while (index <= end) {
2542dc7f3e86SJan Kara 		nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
254367fd707fSJan Kara 				tag);
25448e48dcfbSTheodore Ts'o 		if (nr_pages == 0)
25454e7ea81dSJan Kara 			goto out;
25468e48dcfbSTheodore Ts'o 
25478e48dcfbSTheodore Ts'o 		for (i = 0; i < nr_pages; i++) {
25488e48dcfbSTheodore Ts'o 			struct page *page = pvec.pages[i];
25498e48dcfbSTheodore Ts'o 
25508e48dcfbSTheodore Ts'o 			/*
2551aeac589aSMing Lei 			 * Accumulated enough dirty pages? This doesn't apply
2552aeac589aSMing Lei 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2553aeac589aSMing Lei 			 * keep going because someone may be concurrently
2554aeac589aSMing Lei 			 * dirtying pages, and we might have synced a lot of
2555aeac589aSMing Lei 			 * newly appeared dirty pages, but have not synced all
2556aeac589aSMing Lei 			 * of the old dirty pages.
2557aeac589aSMing Lei 			 */
2558aeac589aSMing Lei 			if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2559aeac589aSMing Lei 				goto out;
2560aeac589aSMing Lei 
25614e7ea81dSJan Kara 			/* If we can't merge this page, we are done. */
25624e7ea81dSJan Kara 			if (mpd->map.m_len > 0 && mpd->next_page != page->index)
25634e7ea81dSJan Kara 				goto out;
256478aaced3STheodore Ts'o 
25658e48dcfbSTheodore Ts'o 			lock_page(page);
25668e48dcfbSTheodore Ts'o 			/*
25674e7ea81dSJan Kara 			 * If the page is no longer dirty, or its mapping no
25684e7ea81dSJan Kara 			 * longer corresponds to inode we are writing (which
25694e7ea81dSJan Kara 			 * means it has been truncated or invalidated), or the
25704e7ea81dSJan Kara 			 * page is already under writeback and we are not doing
25714e7ea81dSJan Kara 			 * a data integrity writeback, skip the page
25728e48dcfbSTheodore Ts'o 			 */
25734f01b02cSTheodore Ts'o 			if (!PageDirty(page) ||
25744f01b02cSTheodore Ts'o 			    (PageWriteback(page) &&
25754e7ea81dSJan Kara 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
25764f01b02cSTheodore Ts'o 			    unlikely(page->mapping != mapping)) {
25778e48dcfbSTheodore Ts'o 				unlock_page(page);
25788e48dcfbSTheodore Ts'o 				continue;
25798e48dcfbSTheodore Ts'o 			}
25808e48dcfbSTheodore Ts'o 
25818e48dcfbSTheodore Ts'o 			wait_on_page_writeback(page);
25828e48dcfbSTheodore Ts'o 			BUG_ON(PageWriteback(page));
25838e48dcfbSTheodore Ts'o 
25844e7ea81dSJan Kara 			if (mpd->map.m_len == 0)
25858eb9e5ceSTheodore Ts'o 				mpd->first_page = page->index;
25868eb9e5ceSTheodore Ts'o 			mpd->next_page = page->index + 1;
2587f8bec370SJan Kara 			/* Add all dirty buffers to mpd */
25884e7ea81dSJan Kara 			lblk = ((ext4_lblk_t)page->index) <<
258909cbfeafSKirill A. Shutemov 				(PAGE_SHIFT - blkbits);
25908eb9e5ceSTheodore Ts'o 			head = page_buffers(page);
25915f1132b2SJan Kara 			err = mpage_process_page_bufs(mpd, head, head, lblk);
25925f1132b2SJan Kara 			if (err <= 0)
25934e7ea81dSJan Kara 				goto out;
25945f1132b2SJan Kara 			err = 0;
2595aeac589aSMing Lei 			left--;
25968e48dcfbSTheodore Ts'o 		}
25978e48dcfbSTheodore Ts'o 		pagevec_release(&pvec);
25988e48dcfbSTheodore Ts'o 		cond_resched();
25998e48dcfbSTheodore Ts'o 	}
26004f01b02cSTheodore Ts'o 	return 0;
26018eb9e5ceSTheodore Ts'o out:
26028eb9e5ceSTheodore Ts'o 	pagevec_release(&pvec);
26034e7ea81dSJan Kara 	return err;
26048e48dcfbSTheodore Ts'o }
26058e48dcfbSTheodore Ts'o 
260620970ba6STheodore Ts'o static int ext4_writepages(struct address_space *mapping,
260764769240SAlex Tomas 			   struct writeback_control *wbc)
260864769240SAlex Tomas {
26094e7ea81dSJan Kara 	pgoff_t	writeback_index = 0;
26104e7ea81dSJan Kara 	long nr_to_write = wbc->nr_to_write;
261122208dedSAneesh Kumar K.V 	int range_whole = 0;
26124e7ea81dSJan Kara 	int cycled = 1;
261361628a3fSMingming Cao 	handle_t *handle = NULL;
2614df22291fSAneesh Kumar K.V 	struct mpage_da_data mpd;
26155e745b04SAneesh Kumar K.V 	struct inode *inode = mapping->host;
26166b523df4SJan Kara 	int needed_blocks, rsv_blocks = 0, ret = 0;
26175e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
26184e7ea81dSJan Kara 	bool done;
26191bce63d1SShaohua Li 	struct blk_plug plug;
2620cb530541STheodore Ts'o 	bool give_up_on_write = false;
262161628a3fSMingming Cao 
26220db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
26230db1ff22STheodore Ts'o 		return -EIO;
26240db1ff22STheodore Ts'o 
2625bbd55937SEric Biggers 	percpu_down_read(&sbi->s_writepages_rwsem);
262620970ba6STheodore Ts'o 	trace_ext4_writepages(inode, wbc);
2627ba80b101STheodore Ts'o 
262861628a3fSMingming Cao 	/*
262961628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
263061628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
263161628a3fSMingming Cao 	 * because that could violate lock ordering on umount
263261628a3fSMingming Cao 	 */
2633a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2634bbf023c7SMing Lei 		goto out_writepages;
26352a21e37eSTheodore Ts'o 
263620970ba6STheodore Ts'o 	if (ext4_should_journal_data(inode)) {
2637043d20d1SGoldwyn Rodrigues 		ret = generic_writepages(mapping, wbc);
2638bbf023c7SMing Lei 		goto out_writepages;
263920970ba6STheodore Ts'o 	}
264020970ba6STheodore Ts'o 
26412a21e37eSTheodore Ts'o 	/*
26422a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
26432a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
26442a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
26451751e8a6SLinus Torvalds 	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
26462a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
264720970ba6STheodore Ts'o 	 * read-only, and in that case, ext4_writepages should
26482a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
26492a21e37eSTheodore Ts'o 	 * the stack trace.
26502a21e37eSTheodore Ts'o 	 */
26510db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
26520db1ff22STheodore Ts'o 		     sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2653bbf023c7SMing Lei 		ret = -EROFS;
2654bbf023c7SMing Lei 		goto out_writepages;
2655bbf023c7SMing Lei 	}
26562a21e37eSTheodore Ts'o 
26574e7ea81dSJan Kara 	/*
26584e7ea81dSJan Kara 	 * If we have inline data and arrive here, it means that
26594e7ea81dSJan Kara 	 * we will soon create the block for the 1st page, so
26604e7ea81dSJan Kara 	 * we'd better clear the inline data here.
26614e7ea81dSJan Kara 	 */
26624e7ea81dSJan Kara 	if (ext4_has_inline_data(inode)) {
26634e7ea81dSJan Kara 		/* Just inode will be modified... */
26644e7ea81dSJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
26654e7ea81dSJan Kara 		if (IS_ERR(handle)) {
26664e7ea81dSJan Kara 			ret = PTR_ERR(handle);
26674e7ea81dSJan Kara 			goto out_writepages;
26684e7ea81dSJan Kara 		}
26694e7ea81dSJan Kara 		BUG_ON(ext4_test_inode_state(inode,
26704e7ea81dSJan Kara 				EXT4_STATE_MAY_INLINE_DATA));
26714e7ea81dSJan Kara 		ext4_destroy_inline_data(handle, inode);
26724e7ea81dSJan Kara 		ext4_journal_stop(handle);
26734e7ea81dSJan Kara 	}
26744e7ea81dSJan Kara 
26754e343231Syangerkun 	if (ext4_should_dioread_nolock(inode)) {
26764e343231Syangerkun 		/*
26774e343231Syangerkun 		 * We may need to convert up to one extent per block in
26784e343231Syangerkun 		 * the page and we may dirty the inode.
26794e343231Syangerkun 		 */
26804e343231Syangerkun 		rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
26814e343231Syangerkun 						PAGE_SIZE >> inode->i_blkbits);
26824e343231Syangerkun 	}
26834e343231Syangerkun 
268422208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
268522208dedSAneesh Kumar K.V 		range_whole = 1;
268661628a3fSMingming Cao 
26872acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
26884e7ea81dSJan Kara 		writeback_index = mapping->writeback_index;
26894e7ea81dSJan Kara 		if (writeback_index)
26902acf2c26SAneesh Kumar K.V 			cycled = 0;
26914e7ea81dSJan Kara 		mpd.first_page = writeback_index;
26924e7ea81dSJan Kara 		mpd.last_page = -1;
26935b41d924SEric Sandeen 	} else {
269409cbfeafSKirill A. Shutemov 		mpd.first_page = wbc->range_start >> PAGE_SHIFT;
269509cbfeafSKirill A. Shutemov 		mpd.last_page = wbc->range_end >> PAGE_SHIFT;
26965b41d924SEric Sandeen 	}
2697a1d6cc56SAneesh Kumar K.V 
26984e7ea81dSJan Kara 	mpd.inode = inode;
26994e7ea81dSJan Kara 	mpd.wbc = wbc;
27004e7ea81dSJan Kara 	ext4_io_submit_init(&mpd.io_submit, wbc);
27012acf2c26SAneesh Kumar K.V retry:
27026e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
27034e7ea81dSJan Kara 		tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
27044e7ea81dSJan Kara 	done = false;
27051bce63d1SShaohua Li 	blk_start_plug(&plug);
2706dddbd6acSJan Kara 
2707dddbd6acSJan Kara 	/*
2708dddbd6acSJan Kara 	 * First writeback pages that don't need mapping - we can avoid
2709dddbd6acSJan Kara 	 * starting a transaction unnecessarily and also avoid being blocked
2710dddbd6acSJan Kara 	 * in the block layer on device congestion while having transaction
2711dddbd6acSJan Kara 	 * started.
2712dddbd6acSJan Kara 	 */
2713dddbd6acSJan Kara 	mpd.do_map = 0;
2714dddbd6acSJan Kara 	mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2715dddbd6acSJan Kara 	if (!mpd.io_submit.io_end) {
2716dddbd6acSJan Kara 		ret = -ENOMEM;
2717dddbd6acSJan Kara 		goto unplug;
2718dddbd6acSJan Kara 	}
2719dddbd6acSJan Kara 	ret = mpage_prepare_extent_to_map(&mpd);
2720a297b2fcSXiaoguang Wang 	/* Unlock pages we didn't use */
2721a297b2fcSXiaoguang Wang 	mpage_release_unused_pages(&mpd, false);
2722dddbd6acSJan Kara 	/* Submit prepared bio */
2723dddbd6acSJan Kara 	ext4_io_submit(&mpd.io_submit);
2724dddbd6acSJan Kara 	ext4_put_io_end_defer(mpd.io_submit.io_end);
2725dddbd6acSJan Kara 	mpd.io_submit.io_end = NULL;
2726dddbd6acSJan Kara 	if (ret < 0)
2727dddbd6acSJan Kara 		goto unplug;
2728dddbd6acSJan Kara 
27294e7ea81dSJan Kara 	while (!done && mpd.first_page <= mpd.last_page) {
27304e7ea81dSJan Kara 		/* For each extent of pages we use new io_end */
27314e7ea81dSJan Kara 		mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
27324e7ea81dSJan Kara 		if (!mpd.io_submit.io_end) {
27334e7ea81dSJan Kara 			ret = -ENOMEM;
27344e7ea81dSJan Kara 			break;
27354e7ea81dSJan Kara 		}
2736a1d6cc56SAneesh Kumar K.V 
2737a1d6cc56SAneesh Kumar K.V 		/*
27384e7ea81dSJan Kara 		 * We have two constraints: We find one extent to map and we
27394e7ea81dSJan Kara 		 * must always write out whole page (makes a difference when
27404e7ea81dSJan Kara 		 * blocksize < pagesize) so that we don't block on IO when we
27414e7ea81dSJan Kara 		 * try to write out the rest of the page. Journalled mode is
27424e7ea81dSJan Kara 		 * not supported by delalloc.
2743a1d6cc56SAneesh Kumar K.V 		 */
2744a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
2745525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2746a1d6cc56SAneesh Kumar K.V 
274761628a3fSMingming Cao 		/* start a new transaction */
27486b523df4SJan Kara 		handle = ext4_journal_start_with_reserve(inode,
27496b523df4SJan Kara 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
275061628a3fSMingming Cao 		if (IS_ERR(handle)) {
275161628a3fSMingming Cao 			ret = PTR_ERR(handle);
27521693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2753fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
2754a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
27554e7ea81dSJan Kara 			/* Release allocated io_end */
27564e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
2757dddbd6acSJan Kara 			mpd.io_submit.io_end = NULL;
27584e7ea81dSJan Kara 			break;
275961628a3fSMingming Cao 		}
2760dddbd6acSJan Kara 		mpd.do_map = 1;
2761f63e6005STheodore Ts'o 
27624e7ea81dSJan Kara 		trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
27634e7ea81dSJan Kara 		ret = mpage_prepare_extent_to_map(&mpd);
27644e7ea81dSJan Kara 		if (!ret) {
27654e7ea81dSJan Kara 			if (mpd.map.m_len)
2766cb530541STheodore Ts'o 				ret = mpage_map_and_submit_extent(handle, &mpd,
2767cb530541STheodore Ts'o 					&give_up_on_write);
27684e7ea81dSJan Kara 			else {
2769f63e6005STheodore Ts'o 				/*
27704e7ea81dSJan Kara 				 * We scanned the whole range (or exhausted
27714e7ea81dSJan Kara 				 * nr_to_write), submitted what was mapped and
27724e7ea81dSJan Kara 				 * didn't find anything needing mapping. We are
27734e7ea81dSJan Kara 				 * done.
2774f63e6005STheodore Ts'o 				 */
27754e7ea81dSJan Kara 				done = true;
2776f63e6005STheodore Ts'o 			}
27774e7ea81dSJan Kara 		}
2778646caa9cSJan Kara 		/*
2779646caa9cSJan Kara 		 * Caution: If the handle is synchronous,
2780646caa9cSJan Kara 		 * ext4_journal_stop() can wait for transaction commit
2781646caa9cSJan Kara 		 * to finish which may depend on writeback of pages to
2782646caa9cSJan Kara 		 * complete or on page lock to be released.  In that
2783646caa9cSJan Kara 		 * case, we have to wait until after after we have
2784646caa9cSJan Kara 		 * submitted all the IO, released page locks we hold,
2785646caa9cSJan Kara 		 * and dropped io_end reference (for extent conversion
2786646caa9cSJan Kara 		 * to be able to complete) before stopping the handle.
2787646caa9cSJan Kara 		 */
2788646caa9cSJan Kara 		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
278961628a3fSMingming Cao 			ext4_journal_stop(handle);
2790646caa9cSJan Kara 			handle = NULL;
2791dddbd6acSJan Kara 			mpd.do_map = 0;
2792646caa9cSJan Kara 		}
27934e7ea81dSJan Kara 		/* Unlock pages we didn't use */
2794cb530541STheodore Ts'o 		mpage_release_unused_pages(&mpd, give_up_on_write);
2795a297b2fcSXiaoguang Wang 		/* Submit prepared bio */
2796a297b2fcSXiaoguang Wang 		ext4_io_submit(&mpd.io_submit);
2797a297b2fcSXiaoguang Wang 
2798646caa9cSJan Kara 		/*
2799646caa9cSJan Kara 		 * Drop our io_end reference we got from init. We have
2800646caa9cSJan Kara 		 * to be careful and use deferred io_end finishing if
2801646caa9cSJan Kara 		 * we are still holding the transaction as we can
2802646caa9cSJan Kara 		 * release the last reference to io_end which may end
2803646caa9cSJan Kara 		 * up doing unwritten extent conversion.
2804646caa9cSJan Kara 		 */
2805646caa9cSJan Kara 		if (handle) {
2806646caa9cSJan Kara 			ext4_put_io_end_defer(mpd.io_submit.io_end);
2807646caa9cSJan Kara 			ext4_journal_stop(handle);
2808646caa9cSJan Kara 		} else
28094e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
2810dddbd6acSJan Kara 		mpd.io_submit.io_end = NULL;
2811df22291fSAneesh Kumar K.V 
28124e7ea81dSJan Kara 		if (ret == -ENOSPC && sbi->s_journal) {
28134e7ea81dSJan Kara 			/*
28144e7ea81dSJan Kara 			 * Commit the transaction which would
281522208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
281622208dedSAneesh Kumar K.V 			 * and try again
281722208dedSAneesh Kumar K.V 			 */
2818df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
281922208dedSAneesh Kumar K.V 			ret = 0;
28204e7ea81dSJan Kara 			continue;
28214e7ea81dSJan Kara 		}
28224e7ea81dSJan Kara 		/* Fatal error - ENOMEM, EIO... */
28234e7ea81dSJan Kara 		if (ret)
282461628a3fSMingming Cao 			break;
282561628a3fSMingming Cao 	}
2826dddbd6acSJan Kara unplug:
28271bce63d1SShaohua Li 	blk_finish_plug(&plug);
28289c12a831SJan Kara 	if (!ret && !cycled && wbc->nr_to_write > 0) {
28292acf2c26SAneesh Kumar K.V 		cycled = 1;
28304e7ea81dSJan Kara 		mpd.last_page = writeback_index - 1;
28314e7ea81dSJan Kara 		mpd.first_page = 0;
28322acf2c26SAneesh Kumar K.V 		goto retry;
28332acf2c26SAneesh Kumar K.V 	}
283461628a3fSMingming Cao 
283522208dedSAneesh Kumar K.V 	/* Update index */
283622208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
283722208dedSAneesh Kumar K.V 		/*
28384e7ea81dSJan Kara 		 * Set the writeback_index so that range_cyclic
283922208dedSAneesh Kumar K.V 		 * mode will write it back later
284022208dedSAneesh Kumar K.V 		 */
28414e7ea81dSJan Kara 		mapping->writeback_index = mpd.first_page;
2842a1d6cc56SAneesh Kumar K.V 
284361628a3fSMingming Cao out_writepages:
284420970ba6STheodore Ts'o 	trace_ext4_writepages_result(inode, wbc, ret,
28454e7ea81dSJan Kara 				     nr_to_write - wbc->nr_to_write);
2846bbd55937SEric Biggers 	percpu_up_read(&sbi->s_writepages_rwsem);
284761628a3fSMingming Cao 	return ret;
284864769240SAlex Tomas }
284964769240SAlex Tomas 
28505f0663bbSDan Williams static int ext4_dax_writepages(struct address_space *mapping,
28515f0663bbSDan Williams 			       struct writeback_control *wbc)
28525f0663bbSDan Williams {
28535f0663bbSDan Williams 	int ret;
28545f0663bbSDan Williams 	long nr_to_write = wbc->nr_to_write;
28555f0663bbSDan Williams 	struct inode *inode = mapping->host;
28565f0663bbSDan Williams 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
28575f0663bbSDan Williams 
28585f0663bbSDan Williams 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
28595f0663bbSDan Williams 		return -EIO;
28605f0663bbSDan Williams 
2861bbd55937SEric Biggers 	percpu_down_read(&sbi->s_writepages_rwsem);
28625f0663bbSDan Williams 	trace_ext4_writepages(inode, wbc);
28635f0663bbSDan Williams 
28643f666c56SVivek Goyal 	ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
28655f0663bbSDan Williams 	trace_ext4_writepages_result(inode, wbc, ret,
28665f0663bbSDan Williams 				     nr_to_write - wbc->nr_to_write);
2867bbd55937SEric Biggers 	percpu_up_read(&sbi->s_writepages_rwsem);
28685f0663bbSDan Williams 	return ret;
28695f0663bbSDan Williams }
28705f0663bbSDan Williams 
287179f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
287279f0be8dSAneesh Kumar K.V {
28735c1ff336SEric Whitney 	s64 free_clusters, dirty_clusters;
287479f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
287579f0be8dSAneesh Kumar K.V 
287679f0be8dSAneesh Kumar K.V 	/*
287779f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
287879f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
2879179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
288079f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
288179f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
288279f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
288379f0be8dSAneesh Kumar K.V 	 */
28845c1ff336SEric Whitney 	free_clusters =
28855c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
28865c1ff336SEric Whitney 	dirty_clusters =
28875c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
288800d4e736STheodore Ts'o 	/*
288900d4e736STheodore Ts'o 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
289000d4e736STheodore Ts'o 	 */
28915c1ff336SEric Whitney 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
289210ee27a0SMiao Xie 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
289300d4e736STheodore Ts'o 
28945c1ff336SEric Whitney 	if (2 * free_clusters < 3 * dirty_clusters ||
28955c1ff336SEric Whitney 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
289679f0be8dSAneesh Kumar K.V 		/*
2897c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
2898c8afb446SEric Sandeen 		 * or free blocks is less than watermark
289979f0be8dSAneesh Kumar K.V 		 */
290079f0be8dSAneesh Kumar K.V 		return 1;
290179f0be8dSAneesh Kumar K.V 	}
290279f0be8dSAneesh Kumar K.V 	return 0;
290379f0be8dSAneesh Kumar K.V }
290479f0be8dSAneesh Kumar K.V 
29050ff8947fSEric Sandeen /* We always reserve for an inode update; the superblock could be there too */
29060ff8947fSEric Sandeen static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
29070ff8947fSEric Sandeen {
2908e2b911c5SDarrick J. Wong 	if (likely(ext4_has_feature_large_file(inode->i_sb)))
29090ff8947fSEric Sandeen 		return 1;
29100ff8947fSEric Sandeen 
29110ff8947fSEric Sandeen 	if (pos + len <= 0x7fffffffULL)
29120ff8947fSEric Sandeen 		return 1;
29130ff8947fSEric Sandeen 
29140ff8947fSEric Sandeen 	/* We might need to update the superblock to set LARGE_FILE */
29150ff8947fSEric Sandeen 	return 2;
29160ff8947fSEric Sandeen }
29170ff8947fSEric Sandeen 
291864769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
291964769240SAlex Tomas 			       loff_t pos, unsigned len, unsigned flags,
292064769240SAlex Tomas 			       struct page **pagep, void **fsdata)
292164769240SAlex Tomas {
292272b8ab9dSEric Sandeen 	int ret, retries = 0;
292364769240SAlex Tomas 	struct page *page;
292464769240SAlex Tomas 	pgoff_t index;
292564769240SAlex Tomas 	struct inode *inode = mapping->host;
292664769240SAlex Tomas 	handle_t *handle;
292764769240SAlex Tomas 
29280db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
29290db1ff22STheodore Ts'o 		return -EIO;
29300db1ff22STheodore Ts'o 
293109cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
293279f0be8dSAneesh Kumar K.V 
2933c93d8f88SEric Biggers 	if (ext4_nonda_switch(inode->i_sb) || S_ISLNK(inode->i_mode) ||
2934c93d8f88SEric Biggers 	    ext4_verity_in_progress(inode)) {
293579f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
293679f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
293779f0be8dSAneesh Kumar K.V 					len, flags, pagep, fsdata);
293879f0be8dSAneesh Kumar K.V 	}
293979f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
29409bffad1eSTheodore Ts'o 	trace_ext4_da_write_begin(inode, pos, len, flags);
29419c3569b5STao Ma 
29429c3569b5STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
29439c3569b5STao Ma 		ret = ext4_da_write_inline_data_begin(mapping, inode,
29449c3569b5STao Ma 						      pos, len, flags,
29459c3569b5STao Ma 						      pagep, fsdata);
29469c3569b5STao Ma 		if (ret < 0)
294747564bfbSTheodore Ts'o 			return ret;
294847564bfbSTheodore Ts'o 		if (ret == 1)
294947564bfbSTheodore Ts'o 			return 0;
29509c3569b5STao Ma 	}
29519c3569b5STao Ma 
295247564bfbSTheodore Ts'o 	/*
295347564bfbSTheodore Ts'o 	 * grab_cache_page_write_begin() can take a long time if the
295447564bfbSTheodore Ts'o 	 * system is thrashing due to memory pressure, or if the page
295547564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
295647564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
295747564bfbSTheodore Ts'o 	 * the page (if needed) without using GFP_NOFS.
295847564bfbSTheodore Ts'o 	 */
295947564bfbSTheodore Ts'o retry_grab:
296047564bfbSTheodore Ts'o 	page = grab_cache_page_write_begin(mapping, index, flags);
296147564bfbSTheodore Ts'o 	if (!page)
296247564bfbSTheodore Ts'o 		return -ENOMEM;
296347564bfbSTheodore Ts'o 	unlock_page(page);
296447564bfbSTheodore Ts'o 
296564769240SAlex Tomas 	/*
296664769240SAlex Tomas 	 * With delayed allocation, we don't log the i_disksize update
296764769240SAlex Tomas 	 * if there is delayed block allocation. But we still need
296864769240SAlex Tomas 	 * to journalling the i_disksize update if writes to the end
296964769240SAlex Tomas 	 * of file which has an already mapped buffer.
297064769240SAlex Tomas 	 */
297147564bfbSTheodore Ts'o retry_journal:
29720ff8947fSEric Sandeen 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
29730ff8947fSEric Sandeen 				ext4_da_write_credits(inode, pos, len));
297464769240SAlex Tomas 	if (IS_ERR(handle)) {
297509cbfeafSKirill A. Shutemov 		put_page(page);
297647564bfbSTheodore Ts'o 		return PTR_ERR(handle);
297764769240SAlex Tomas 	}
297864769240SAlex Tomas 
297947564bfbSTheodore Ts'o 	lock_page(page);
298047564bfbSTheodore Ts'o 	if (page->mapping != mapping) {
298147564bfbSTheodore Ts'o 		/* The page got truncated from under us */
298247564bfbSTheodore Ts'o 		unlock_page(page);
298309cbfeafSKirill A. Shutemov 		put_page(page);
2984d5a0d4f7SEric Sandeen 		ext4_journal_stop(handle);
298547564bfbSTheodore Ts'o 		goto retry_grab;
2986d5a0d4f7SEric Sandeen 	}
298747564bfbSTheodore Ts'o 	/* In case writeback began while the page was unlocked */
29887afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
298964769240SAlex Tomas 
2990643fa961SChandan Rajendra #ifdef CONFIG_FS_ENCRYPTION
29912058f83aSMichael Halcrow 	ret = ext4_block_write_begin(page, pos, len,
29922058f83aSMichael Halcrow 				     ext4_da_get_block_prep);
29932058f83aSMichael Halcrow #else
29946e1db88dSChristoph Hellwig 	ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
29952058f83aSMichael Halcrow #endif
299664769240SAlex Tomas 	if (ret < 0) {
299764769240SAlex Tomas 		unlock_page(page);
299864769240SAlex Tomas 		ext4_journal_stop(handle);
2999ae4d5372SAneesh Kumar K.V 		/*
3000ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
3001ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
3002ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
3003ae4d5372SAneesh Kumar K.V 		 */
3004ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
3005b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
300647564bfbSTheodore Ts'o 
300747564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
300847564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
300947564bfbSTheodore Ts'o 			goto retry_journal;
301047564bfbSTheodore Ts'o 
301109cbfeafSKirill A. Shutemov 		put_page(page);
301247564bfbSTheodore Ts'o 		return ret;
301364769240SAlex Tomas 	}
301464769240SAlex Tomas 
301547564bfbSTheodore Ts'o 	*pagep = page;
301664769240SAlex Tomas 	return ret;
301764769240SAlex Tomas }
301864769240SAlex Tomas 
3019632eaeabSMingming Cao /*
3020632eaeabSMingming Cao  * Check if we should update i_disksize
3021632eaeabSMingming Cao  * when write to the end of file but not require block allocation
3022632eaeabSMingming Cao  */
3023632eaeabSMingming Cao static int ext4_da_should_update_i_disksize(struct page *page,
3024632eaeabSMingming Cao 					    unsigned long offset)
3025632eaeabSMingming Cao {
3026632eaeabSMingming Cao 	struct buffer_head *bh;
3027632eaeabSMingming Cao 	struct inode *inode = page->mapping->host;
3028632eaeabSMingming Cao 	unsigned int idx;
3029632eaeabSMingming Cao 	int i;
3030632eaeabSMingming Cao 
3031632eaeabSMingming Cao 	bh = page_buffers(page);
3032632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
3033632eaeabSMingming Cao 
3034632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
3035632eaeabSMingming Cao 		bh = bh->b_this_page;
3036632eaeabSMingming Cao 
303729fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3038632eaeabSMingming Cao 		return 0;
3039632eaeabSMingming Cao 	return 1;
3040632eaeabSMingming Cao }
3041632eaeabSMingming Cao 
304264769240SAlex Tomas static int ext4_da_write_end(struct file *file,
304364769240SAlex Tomas 			     struct address_space *mapping,
304464769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
304564769240SAlex Tomas 			     struct page *page, void *fsdata)
304664769240SAlex Tomas {
304764769240SAlex Tomas 	struct inode *inode = mapping->host;
304864769240SAlex Tomas 	int ret = 0, ret2;
304964769240SAlex Tomas 	handle_t *handle = ext4_journal_current_handle();
305064769240SAlex Tomas 	loff_t new_i_size;
3051632eaeabSMingming Cao 	unsigned long start, end;
305279f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
305379f0be8dSAneesh Kumar K.V 
305474d553aaSTheodore Ts'o 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
305574d553aaSTheodore Ts'o 		return ext4_write_end(file, mapping, pos,
305679f0be8dSAneesh Kumar K.V 				      len, copied, page, fsdata);
3057632eaeabSMingming Cao 
30589bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
305909cbfeafSKirill A. Shutemov 	start = pos & (PAGE_SIZE - 1);
3060632eaeabSMingming Cao 	end = start + copied - 1;
306164769240SAlex Tomas 
306264769240SAlex Tomas 	/*
306364769240SAlex Tomas 	 * generic_write_end() will run mark_inode_dirty() if i_size
306464769240SAlex Tomas 	 * changes.  So let's piggyback the i_disksize mark_inode_dirty
306564769240SAlex Tomas 	 * into that.
306664769240SAlex Tomas 	 */
306764769240SAlex Tomas 	new_i_size = pos + copied;
3068ea51d132SAndrea Arcangeli 	if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
30699c3569b5STao Ma 		if (ext4_has_inline_data(inode) ||
30709c3569b5STao Ma 		    ext4_da_should_update_i_disksize(page, end)) {
3071ee124d27SDmitry Monakhov 			ext4_update_i_disksize(inode, new_i_size);
3072cf17fea6SAneesh Kumar K.V 			/* We need to mark inode dirty even if
3073cf17fea6SAneesh Kumar K.V 			 * new_i_size is less that inode->i_size
3074cf17fea6SAneesh Kumar K.V 			 * bu greater than i_disksize.(hint delalloc)
3075cf17fea6SAneesh Kumar K.V 			 */
3076cf17fea6SAneesh Kumar K.V 			ext4_mark_inode_dirty(handle, inode);
3077632eaeabSMingming Cao 		}
3078632eaeabSMingming Cao 	}
30799c3569b5STao Ma 
30809c3569b5STao Ma 	if (write_mode != CONVERT_INLINE_DATA &&
30819c3569b5STao Ma 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
30829c3569b5STao Ma 	    ext4_has_inline_data(inode))
30839c3569b5STao Ma 		ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
30849c3569b5STao Ma 						     page);
30859c3569b5STao Ma 	else
308664769240SAlex Tomas 		ret2 = generic_write_end(file, mapping, pos, len, copied,
308764769240SAlex Tomas 							page, fsdata);
30889c3569b5STao Ma 
308964769240SAlex Tomas 	copied = ret2;
309064769240SAlex Tomas 	if (ret2 < 0)
309164769240SAlex Tomas 		ret = ret2;
309264769240SAlex Tomas 	ret2 = ext4_journal_stop(handle);
309364769240SAlex Tomas 	if (!ret)
309464769240SAlex Tomas 		ret = ret2;
309564769240SAlex Tomas 
309664769240SAlex Tomas 	return ret ? ret : copied;
309764769240SAlex Tomas }
309864769240SAlex Tomas 
3099ccd2506bSTheodore Ts'o /*
3100ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
3101ccd2506bSTheodore Ts'o  */
3102ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
3103ccd2506bSTheodore Ts'o {
3104fb40ba0dSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
3105fb40ba0dSTheodore Ts'o 
310671d4f7d0STheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks)
3107ccd2506bSTheodore Ts'o 		return 0;
3108ccd2506bSTheodore Ts'o 
3109ccd2506bSTheodore Ts'o 	/*
3110ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
3111ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
3112ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
3113ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
3114ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
3115ccd2506bSTheodore Ts'o 	 *
311620970ba6STheodore Ts'o 	 * ext4_writepages() ->
3117ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
3118ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
3119ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
3120ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
3121ccd2506bSTheodore Ts'o 	 *
3122ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
3123ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
3124ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
3125ccd2506bSTheodore Ts'o 	 * doing I/O at all.
3126ccd2506bSTheodore Ts'o 	 *
3127ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
3128380cf090SWu Fengguang 	 * the pages by calling redirty_page_for_writepage() but that
3129ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
3130ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
313125985edcSLucas De Marchi 	 * simplifying them because we wouldn't actually intend to
3132ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
3133ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
3134ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
3135ccd2506bSTheodore Ts'o 	 *
3136ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
3137ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
3138ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
3139ccd2506bSTheodore Ts'o 	 */
3140ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
3141ccd2506bSTheodore Ts'o }
314264769240SAlex Tomas 
314364769240SAlex Tomas /*
3144ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
3145ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
3146ac27a0ecSDave Kleikamp  *
3147ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
3148617ba13bSMingming Cao  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3149ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
3150ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
3151ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
3152ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
3153ac27a0ecSDave Kleikamp  *
3154ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
3155ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
3156ac27a0ecSDave Kleikamp  */
3157617ba13bSMingming Cao static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3158ac27a0ecSDave Kleikamp {
3159ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
3160ac27a0ecSDave Kleikamp 	journal_t *journal;
3161ac27a0ecSDave Kleikamp 	int err;
3162ac27a0ecSDave Kleikamp 
316346c7f254STao Ma 	/*
316446c7f254STao Ma 	 * We can get here for an inline file via the FIBMAP ioctl
316546c7f254STao Ma 	 */
316646c7f254STao Ma 	if (ext4_has_inline_data(inode))
316746c7f254STao Ma 		return 0;
316846c7f254STao Ma 
316964769240SAlex Tomas 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
317064769240SAlex Tomas 			test_opt(inode->i_sb, DELALLOC)) {
317164769240SAlex Tomas 		/*
317264769240SAlex Tomas 		 * With delalloc we want to sync the file
317364769240SAlex Tomas 		 * so that we can make sure we allocate
317464769240SAlex Tomas 		 * blocks for file
317564769240SAlex Tomas 		 */
317664769240SAlex Tomas 		filemap_write_and_wait(mapping);
317764769240SAlex Tomas 	}
317864769240SAlex Tomas 
317919f5fb7aSTheodore Ts'o 	if (EXT4_JOURNAL(inode) &&
318019f5fb7aSTheodore Ts'o 	    ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3181ac27a0ecSDave Kleikamp 		/*
3182ac27a0ecSDave Kleikamp 		 * This is a REALLY heavyweight approach, but the use of
3183ac27a0ecSDave Kleikamp 		 * bmap on dirty files is expected to be extremely rare:
3184ac27a0ecSDave Kleikamp 		 * only if we run lilo or swapon on a freshly made file
3185ac27a0ecSDave Kleikamp 		 * do we expect this to happen.
3186ac27a0ecSDave Kleikamp 		 *
3187ac27a0ecSDave Kleikamp 		 * (bmap requires CAP_SYS_RAWIO so this does not
3188ac27a0ecSDave Kleikamp 		 * represent an unprivileged user DOS attack --- we'd be
3189ac27a0ecSDave Kleikamp 		 * in trouble if mortal users could trigger this path at
3190ac27a0ecSDave Kleikamp 		 * will.)
3191ac27a0ecSDave Kleikamp 		 *
3192617ba13bSMingming Cao 		 * NB. EXT4_STATE_JDATA is not set on files other than
3193ac27a0ecSDave Kleikamp 		 * regular files.  If somebody wants to bmap a directory
3194ac27a0ecSDave Kleikamp 		 * or symlink and gets confused because the buffer
3195ac27a0ecSDave Kleikamp 		 * hasn't yet been flushed to disk, they deserve
3196ac27a0ecSDave Kleikamp 		 * everything they get.
3197ac27a0ecSDave Kleikamp 		 */
3198ac27a0ecSDave Kleikamp 
319919f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3200617ba13bSMingming Cao 		journal = EXT4_JOURNAL(inode);
3201dab291afSMingming Cao 		jbd2_journal_lock_updates(journal);
3202dab291afSMingming Cao 		err = jbd2_journal_flush(journal);
3203dab291afSMingming Cao 		jbd2_journal_unlock_updates(journal);
3204ac27a0ecSDave Kleikamp 
3205ac27a0ecSDave Kleikamp 		if (err)
3206ac27a0ecSDave Kleikamp 			return 0;
3207ac27a0ecSDave Kleikamp 	}
3208ac27a0ecSDave Kleikamp 
3209ac58e4fbSRitesh Harjani 	return iomap_bmap(mapping, block, &ext4_iomap_ops);
3210ac27a0ecSDave Kleikamp }
3211ac27a0ecSDave Kleikamp 
3212617ba13bSMingming Cao static int ext4_readpage(struct file *file, struct page *page)
3213ac27a0ecSDave Kleikamp {
321446c7f254STao Ma 	int ret = -EAGAIN;
321546c7f254STao Ma 	struct inode *inode = page->mapping->host;
321646c7f254STao Ma 
32170562e0baSJiaying Zhang 	trace_ext4_readpage(page);
321846c7f254STao Ma 
321946c7f254STao Ma 	if (ext4_has_inline_data(inode))
322046c7f254STao Ma 		ret = ext4_readpage_inline(inode, page);
322146c7f254STao Ma 
322246c7f254STao Ma 	if (ret == -EAGAIN)
3223ac22b46aSJens Axboe 		return ext4_mpage_readpages(page->mapping, NULL, page, 1,
3224ac22b46aSJens Axboe 						false);
322546c7f254STao Ma 
322646c7f254STao Ma 	return ret;
3227ac27a0ecSDave Kleikamp }
3228ac27a0ecSDave Kleikamp 
3229ac27a0ecSDave Kleikamp static int
3230617ba13bSMingming Cao ext4_readpages(struct file *file, struct address_space *mapping,
3231ac27a0ecSDave Kleikamp 		struct list_head *pages, unsigned nr_pages)
3232ac27a0ecSDave Kleikamp {
323346c7f254STao Ma 	struct inode *inode = mapping->host;
323446c7f254STao Ma 
323546c7f254STao Ma 	/* If the file has inline data, no need to do readpages. */
323646c7f254STao Ma 	if (ext4_has_inline_data(inode))
323746c7f254STao Ma 		return 0;
323846c7f254STao Ma 
3239ac22b46aSJens Axboe 	return ext4_mpage_readpages(mapping, pages, NULL, nr_pages, true);
3240ac27a0ecSDave Kleikamp }
3241ac27a0ecSDave Kleikamp 
3242d47992f8SLukas Czerner static void ext4_invalidatepage(struct page *page, unsigned int offset,
3243d47992f8SLukas Czerner 				unsigned int length)
3244ac27a0ecSDave Kleikamp {
3245ca99fdd2SLukas Czerner 	trace_ext4_invalidatepage(page, offset, length);
32460562e0baSJiaying Zhang 
32474520fb3cSJan Kara 	/* No journalling happens on data buffers when this function is used */
32484520fb3cSJan Kara 	WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
32494520fb3cSJan Kara 
3250ca99fdd2SLukas Czerner 	block_invalidatepage(page, offset, length);
32514520fb3cSJan Kara }
32524520fb3cSJan Kara 
325353e87268SJan Kara static int __ext4_journalled_invalidatepage(struct page *page,
3254ca99fdd2SLukas Czerner 					    unsigned int offset,
3255ca99fdd2SLukas Czerner 					    unsigned int length)
32564520fb3cSJan Kara {
32574520fb3cSJan Kara 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
32584520fb3cSJan Kara 
3259ca99fdd2SLukas Czerner 	trace_ext4_journalled_invalidatepage(page, offset, length);
32604520fb3cSJan Kara 
3261744692dcSJiaying Zhang 	/*
3262ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
3263ac27a0ecSDave Kleikamp 	 */
326409cbfeafSKirill A. Shutemov 	if (offset == 0 && length == PAGE_SIZE)
3265ac27a0ecSDave Kleikamp 		ClearPageChecked(page);
3266ac27a0ecSDave Kleikamp 
3267ca99fdd2SLukas Czerner 	return jbd2_journal_invalidatepage(journal, page, offset, length);
326853e87268SJan Kara }
326953e87268SJan Kara 
327053e87268SJan Kara /* Wrapper for aops... */
327153e87268SJan Kara static void ext4_journalled_invalidatepage(struct page *page,
3272d47992f8SLukas Czerner 					   unsigned int offset,
3273d47992f8SLukas Czerner 					   unsigned int length)
327453e87268SJan Kara {
3275ca99fdd2SLukas Czerner 	WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3276ac27a0ecSDave Kleikamp }
3277ac27a0ecSDave Kleikamp 
3278617ba13bSMingming Cao static int ext4_releasepage(struct page *page, gfp_t wait)
3279ac27a0ecSDave Kleikamp {
3280617ba13bSMingming Cao 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3281ac27a0ecSDave Kleikamp 
32820562e0baSJiaying Zhang 	trace_ext4_releasepage(page);
32830562e0baSJiaying Zhang 
3284e1c36595SJan Kara 	/* Page has dirty journalled data -> cannot release */
3285e1c36595SJan Kara 	if (PageChecked(page))
3286ac27a0ecSDave Kleikamp 		return 0;
32870390131bSFrank Mayhar 	if (journal)
3288dab291afSMingming Cao 		return jbd2_journal_try_to_free_buffers(journal, page, wait);
32890390131bSFrank Mayhar 	else
32900390131bSFrank Mayhar 		return try_to_free_buffers(page);
3291ac27a0ecSDave Kleikamp }
3292ac27a0ecSDave Kleikamp 
3293b8a6176cSJan Kara static bool ext4_inode_datasync_dirty(struct inode *inode)
3294b8a6176cSJan Kara {
3295b8a6176cSJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3296b8a6176cSJan Kara 
3297b8a6176cSJan Kara 	if (journal)
3298b8a6176cSJan Kara 		return !jbd2_transaction_committed(journal,
3299b8a6176cSJan Kara 					EXT4_I(inode)->i_datasync_tid);
3300b8a6176cSJan Kara 	/* Any metadata buffers to write? */
3301b8a6176cSJan Kara 	if (!list_empty(&inode->i_mapping->private_list))
3302b8a6176cSJan Kara 		return true;
3303b8a6176cSJan Kara 	return inode->i_state & I_DIRTY_DATASYNC;
3304b8a6176cSJan Kara }
3305b8a6176cSJan Kara 
3306c8fdfe29SMatthew Bobrowski static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3307c8fdfe29SMatthew Bobrowski 			   struct ext4_map_blocks *map, loff_t offset,
3308c8fdfe29SMatthew Bobrowski 			   loff_t length)
3309364443cbSJan Kara {
3310c8fdfe29SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3311c8fdfe29SMatthew Bobrowski 
3312c8fdfe29SMatthew Bobrowski 	/*
3313c8fdfe29SMatthew Bobrowski 	 * Writes that span EOF might trigger an I/O size update on completion,
3314c8fdfe29SMatthew Bobrowski 	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3315c8fdfe29SMatthew Bobrowski 	 * there is no other metadata changes being made or are pending.
3316c8fdfe29SMatthew Bobrowski 	 */
3317c8fdfe29SMatthew Bobrowski 	iomap->flags = 0;
3318c8fdfe29SMatthew Bobrowski 	if (ext4_inode_datasync_dirty(inode) ||
3319c8fdfe29SMatthew Bobrowski 	    offset + length > i_size_read(inode))
3320c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_DIRTY;
3321c8fdfe29SMatthew Bobrowski 
3322c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_NEW)
3323c8fdfe29SMatthew Bobrowski 		iomap->flags |= IOMAP_F_NEW;
3324c8fdfe29SMatthew Bobrowski 
3325c8fdfe29SMatthew Bobrowski 	iomap->bdev = inode->i_sb->s_bdev;
3326c8fdfe29SMatthew Bobrowski 	iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3327c8fdfe29SMatthew Bobrowski 	iomap->offset = (u64) map->m_lblk << blkbits;
3328c8fdfe29SMatthew Bobrowski 	iomap->length = (u64) map->m_len << blkbits;
3329c8fdfe29SMatthew Bobrowski 
33306386722aSRitesh Harjani 	if ((map->m_flags & EXT4_MAP_MAPPED) &&
33316386722aSRitesh Harjani 	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
33326386722aSRitesh Harjani 		iomap->flags |= IOMAP_F_MERGED;
33336386722aSRitesh Harjani 
3334c8fdfe29SMatthew Bobrowski 	/*
3335c8fdfe29SMatthew Bobrowski 	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3336c8fdfe29SMatthew Bobrowski 	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3337c8fdfe29SMatthew Bobrowski 	 * set. In order for any allocated unwritten extents to be converted
3338c8fdfe29SMatthew Bobrowski 	 * into written extents correctly within the ->end_io() handler, we
3339c8fdfe29SMatthew Bobrowski 	 * need to ensure that the iomap->type is set appropriately. Hence, the
3340c8fdfe29SMatthew Bobrowski 	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3341c8fdfe29SMatthew Bobrowski 	 * been set first.
3342c8fdfe29SMatthew Bobrowski 	 */
3343c8fdfe29SMatthew Bobrowski 	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3344c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_UNWRITTEN;
3345c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3346c8fdfe29SMatthew Bobrowski 	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3347c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_MAPPED;
3348c8fdfe29SMatthew Bobrowski 		iomap->addr = (u64) map->m_pblk << blkbits;
3349c8fdfe29SMatthew Bobrowski 	} else {
3350c8fdfe29SMatthew Bobrowski 		iomap->type = IOMAP_HOLE;
3351c8fdfe29SMatthew Bobrowski 		iomap->addr = IOMAP_NULL_ADDR;
3352c8fdfe29SMatthew Bobrowski 	}
3353c8fdfe29SMatthew Bobrowski }
3354c8fdfe29SMatthew Bobrowski 
3355f063db5eSMatthew Bobrowski static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3356f063db5eSMatthew Bobrowski 			    unsigned int flags)
3357f063db5eSMatthew Bobrowski {
3358f063db5eSMatthew Bobrowski 	handle_t *handle;
3359378f32baSMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3360378f32baSMatthew Bobrowski 	int ret, dio_credits, m_flags = 0, retries = 0;
3361f063db5eSMatthew Bobrowski 
3362f063db5eSMatthew Bobrowski 	/*
3363f063db5eSMatthew Bobrowski 	 * Trim the mapping request to the maximum value that we can map at
3364f063db5eSMatthew Bobrowski 	 * once for direct I/O.
3365f063db5eSMatthew Bobrowski 	 */
3366f063db5eSMatthew Bobrowski 	if (map->m_len > DIO_MAX_BLOCKS)
3367f063db5eSMatthew Bobrowski 		map->m_len = DIO_MAX_BLOCKS;
3368f063db5eSMatthew Bobrowski 	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3369f063db5eSMatthew Bobrowski 
3370f063db5eSMatthew Bobrowski retry:
3371f063db5eSMatthew Bobrowski 	/*
3372f063db5eSMatthew Bobrowski 	 * Either we allocate blocks and then don't get an unwritten extent, so
3373f063db5eSMatthew Bobrowski 	 * in that case we have reserved enough credits. Or, the blocks are
3374f063db5eSMatthew Bobrowski 	 * already allocated and unwritten. In that case, the extent conversion
3375f063db5eSMatthew Bobrowski 	 * fits into the credits as well.
3376f063db5eSMatthew Bobrowski 	 */
3377f063db5eSMatthew Bobrowski 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3378f063db5eSMatthew Bobrowski 	if (IS_ERR(handle))
3379f063db5eSMatthew Bobrowski 		return PTR_ERR(handle);
3380f063db5eSMatthew Bobrowski 
3381378f32baSMatthew Bobrowski 	/*
3382378f32baSMatthew Bobrowski 	 * DAX and direct I/O are the only two operations that are currently
3383378f32baSMatthew Bobrowski 	 * supported with IOMAP_WRITE.
3384378f32baSMatthew Bobrowski 	 */
3385378f32baSMatthew Bobrowski 	WARN_ON(!IS_DAX(inode) && !(flags & IOMAP_DIRECT));
3386378f32baSMatthew Bobrowski 	if (IS_DAX(inode))
3387378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3388378f32baSMatthew Bobrowski 	/*
3389378f32baSMatthew Bobrowski 	 * We use i_size instead of i_disksize here because delalloc writeback
3390378f32baSMatthew Bobrowski 	 * can complete at any point during the I/O and subsequently push the
3391378f32baSMatthew Bobrowski 	 * i_disksize out to i_size. This could be beyond where direct I/O is
3392378f32baSMatthew Bobrowski 	 * happening and thus expose allocated blocks to direct I/O reads.
3393378f32baSMatthew Bobrowski 	 */
3394378f32baSMatthew Bobrowski 	else if ((map->m_lblk * (1 << blkbits)) >= i_size_read(inode))
3395378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_CREATE;
3396378f32baSMatthew Bobrowski 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3397378f32baSMatthew Bobrowski 		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3398378f32baSMatthew Bobrowski 
3399378f32baSMatthew Bobrowski 	ret = ext4_map_blocks(handle, inode, map, m_flags);
3400378f32baSMatthew Bobrowski 
3401378f32baSMatthew Bobrowski 	/*
3402378f32baSMatthew Bobrowski 	 * We cannot fill holes in indirect tree based inodes as that could
3403378f32baSMatthew Bobrowski 	 * expose stale data in the case of a crash. Use the magic error code
3404378f32baSMatthew Bobrowski 	 * to fallback to buffered I/O.
3405378f32baSMatthew Bobrowski 	 */
3406378f32baSMatthew Bobrowski 	if (!m_flags && !ret)
3407378f32baSMatthew Bobrowski 		ret = -ENOTBLK;
3408f063db5eSMatthew Bobrowski 
3409f063db5eSMatthew Bobrowski 	ext4_journal_stop(handle);
3410f063db5eSMatthew Bobrowski 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3411f063db5eSMatthew Bobrowski 		goto retry;
3412f063db5eSMatthew Bobrowski 
3413f063db5eSMatthew Bobrowski 	return ret;
3414f063db5eSMatthew Bobrowski }
3415f063db5eSMatthew Bobrowski 
3416f063db5eSMatthew Bobrowski 
3417364443cbSJan Kara static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3418c039b997SGoldwyn Rodrigues 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3419364443cbSJan Kara {
3420364443cbSJan Kara 	int ret;
342109edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
342209edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
3423364443cbSJan Kara 
3424bcd8e91fSTheodore Ts'o 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3425bcd8e91fSTheodore Ts'o 		return -EINVAL;
34267046ae35SAndreas Gruenbacher 
3427364443cbSJan Kara 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3428364443cbSJan Kara 		return -ERANGE;
3429364443cbSJan Kara 
343009edf4d3SMatthew Bobrowski 	/*
343109edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical blocks respectively.
343209edf4d3SMatthew Bobrowski 	 */
343309edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
343409edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
343509edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3436364443cbSJan Kara 
343709edf4d3SMatthew Bobrowski 	if (flags & IOMAP_WRITE)
3438f063db5eSMatthew Bobrowski 		ret = ext4_iomap_alloc(inode, &map, flags);
343909edf4d3SMatthew Bobrowski 	else
3440545052e9SChristoph Hellwig 		ret = ext4_map_blocks(NULL, inode, &map, 0);
3441f063db5eSMatthew Bobrowski 
3442545052e9SChristoph Hellwig 	if (ret < 0)
3443545052e9SChristoph Hellwig 		return ret;
3444364443cbSJan Kara 
3445c8fdfe29SMatthew Bobrowski 	ext4_set_iomap(inode, iomap, &map, offset, length);
3446545052e9SChristoph Hellwig 
3447364443cbSJan Kara 	return 0;
3448364443cbSJan Kara }
3449364443cbSJan Kara 
34508cd115bdSJan Kara static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
34518cd115bdSJan Kara 		loff_t length, unsigned flags, struct iomap *iomap,
34528cd115bdSJan Kara 		struct iomap *srcmap)
34538cd115bdSJan Kara {
34548cd115bdSJan Kara 	int ret;
34558cd115bdSJan Kara 
34568cd115bdSJan Kara 	/*
34578cd115bdSJan Kara 	 * Even for writes we don't need to allocate blocks, so just pretend
34588cd115bdSJan Kara 	 * we are reading to save overhead of starting a transaction.
34598cd115bdSJan Kara 	 */
34608cd115bdSJan Kara 	flags &= ~IOMAP_WRITE;
34618cd115bdSJan Kara 	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
34628cd115bdSJan Kara 	WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
34638cd115bdSJan Kara 	return ret;
34648cd115bdSJan Kara }
34658cd115bdSJan Kara 
3466776722e8SJan Kara static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3467776722e8SJan Kara 			  ssize_t written, unsigned flags, struct iomap *iomap)
3468776722e8SJan Kara {
3469378f32baSMatthew Bobrowski 	/*
3470378f32baSMatthew Bobrowski 	 * Check to see whether an error occurred while writing out the data to
3471378f32baSMatthew Bobrowski 	 * the allocated blocks. If so, return the magic error code so that we
3472378f32baSMatthew Bobrowski 	 * fallback to buffered I/O and attempt to complete the remainder of
3473378f32baSMatthew Bobrowski 	 * the I/O. Any blocks that may have been allocated in preparation for
3474378f32baSMatthew Bobrowski 	 * the direct I/O will be reused during buffered I/O.
3475378f32baSMatthew Bobrowski 	 */
3476378f32baSMatthew Bobrowski 	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3477378f32baSMatthew Bobrowski 		return -ENOTBLK;
3478378f32baSMatthew Bobrowski 
3479776722e8SJan Kara 	return 0;
3480776722e8SJan Kara }
3481776722e8SJan Kara 
34828ff6daa1SChristoph Hellwig const struct iomap_ops ext4_iomap_ops = {
3483364443cbSJan Kara 	.iomap_begin		= ext4_iomap_begin,
3484776722e8SJan Kara 	.iomap_end		= ext4_iomap_end,
3485364443cbSJan Kara };
3486364443cbSJan Kara 
34878cd115bdSJan Kara const struct iomap_ops ext4_iomap_overwrite_ops = {
34888cd115bdSJan Kara 	.iomap_begin		= ext4_iomap_overwrite_begin,
34898cd115bdSJan Kara 	.iomap_end		= ext4_iomap_end,
34908cd115bdSJan Kara };
34918cd115bdSJan Kara 
349209edf4d3SMatthew Bobrowski static bool ext4_iomap_is_delalloc(struct inode *inode,
349309edf4d3SMatthew Bobrowski 				   struct ext4_map_blocks *map)
349409edf4d3SMatthew Bobrowski {
349509edf4d3SMatthew Bobrowski 	struct extent_status es;
349609edf4d3SMatthew Bobrowski 	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
349709edf4d3SMatthew Bobrowski 
349809edf4d3SMatthew Bobrowski 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
349909edf4d3SMatthew Bobrowski 				  map->m_lblk, end, &es);
350009edf4d3SMatthew Bobrowski 
350109edf4d3SMatthew Bobrowski 	if (!es.es_len || es.es_lblk > end)
350209edf4d3SMatthew Bobrowski 		return false;
350309edf4d3SMatthew Bobrowski 
350409edf4d3SMatthew Bobrowski 	if (es.es_lblk > map->m_lblk) {
350509edf4d3SMatthew Bobrowski 		map->m_len = es.es_lblk - map->m_lblk;
350609edf4d3SMatthew Bobrowski 		return false;
350709edf4d3SMatthew Bobrowski 	}
350809edf4d3SMatthew Bobrowski 
350909edf4d3SMatthew Bobrowski 	offset = map->m_lblk - es.es_lblk;
351009edf4d3SMatthew Bobrowski 	map->m_len = es.es_len - offset;
351109edf4d3SMatthew Bobrowski 
351209edf4d3SMatthew Bobrowski 	return true;
351309edf4d3SMatthew Bobrowski }
351409edf4d3SMatthew Bobrowski 
351509edf4d3SMatthew Bobrowski static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
351609edf4d3SMatthew Bobrowski 				   loff_t length, unsigned int flags,
351709edf4d3SMatthew Bobrowski 				   struct iomap *iomap, struct iomap *srcmap)
351809edf4d3SMatthew Bobrowski {
351909edf4d3SMatthew Bobrowski 	int ret;
352009edf4d3SMatthew Bobrowski 	bool delalloc = false;
352109edf4d3SMatthew Bobrowski 	struct ext4_map_blocks map;
352209edf4d3SMatthew Bobrowski 	u8 blkbits = inode->i_blkbits;
352309edf4d3SMatthew Bobrowski 
352409edf4d3SMatthew Bobrowski 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
352509edf4d3SMatthew Bobrowski 		return -EINVAL;
352609edf4d3SMatthew Bobrowski 
35277cb476f8SJan Kara 	if (ext4_has_inline_data(inode)) {
35287cb476f8SJan Kara 		ret = ext4_inline_data_iomap(inode, iomap);
3529ba5843f5SJan Kara 		if (ret != -EAGAIN) {
3530ed923b57SMatthew Wilcox 			if (ret == 0 && offset >= iomap->length)
3531ba5843f5SJan Kara 				ret = -ENOENT;
3532ba5843f5SJan Kara 			return ret;
3533ba5843f5SJan Kara 		}
3534ba5843f5SJan Kara 	}
353512735f88SJan Kara 
353609edf4d3SMatthew Bobrowski 	/*
353709edf4d3SMatthew Bobrowski 	 * Calculate the first and last logical block respectively.
353809edf4d3SMatthew Bobrowski 	 */
353909edf4d3SMatthew Bobrowski 	map.m_lblk = offset >> blkbits;
354009edf4d3SMatthew Bobrowski 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
354109edf4d3SMatthew Bobrowski 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
354212735f88SJan Kara 
3543b2c57642SRitesh Harjani 	/*
3544b2c57642SRitesh Harjani 	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3545b2c57642SRitesh Harjani 	 * So handle it here itself instead of querying ext4_map_blocks().
3546b2c57642SRitesh Harjani 	 * Since ext4_map_blocks() will warn about it and will return
3547b2c57642SRitesh Harjani 	 * -EIO error.
3548b2c57642SRitesh Harjani 	 */
3549b2c57642SRitesh Harjani 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3550b2c57642SRitesh Harjani 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3551b2c57642SRitesh Harjani 
3552b2c57642SRitesh Harjani 		if (offset >= sbi->s_bitmap_maxbytes) {
3553b2c57642SRitesh Harjani 			map.m_flags = 0;
3554b2c57642SRitesh Harjani 			goto set_iomap;
3555b2c57642SRitesh Harjani 		}
3556b2c57642SRitesh Harjani 	}
3557b2c57642SRitesh Harjani 
355812735f88SJan Kara 	ret = ext4_map_blocks(NULL, inode, &map, 0);
3559ba5843f5SJan Kara 	if (ret < 0)
3560ba5843f5SJan Kara 		return ret;
3561914f82a3SJan Kara 	if (ret == 0)
356209edf4d3SMatthew Bobrowski 		delalloc = ext4_iomap_is_delalloc(inode, &map);
356309edf4d3SMatthew Bobrowski 
3564b2c57642SRitesh Harjani set_iomap:
356509edf4d3SMatthew Bobrowski 	ext4_set_iomap(inode, iomap, &map, offset, length);
356609edf4d3SMatthew Bobrowski 	if (delalloc && iomap->type == IOMAP_HOLE)
356709edf4d3SMatthew Bobrowski 		iomap->type = IOMAP_DELALLOC;
356809edf4d3SMatthew Bobrowski 
356909edf4d3SMatthew Bobrowski 	return 0;
3570914f82a3SJan Kara }
3571914f82a3SJan Kara 
357209edf4d3SMatthew Bobrowski const struct iomap_ops ext4_iomap_report_ops = {
357309edf4d3SMatthew Bobrowski 	.iomap_begin = ext4_iomap_begin_report,
357409edf4d3SMatthew Bobrowski };
35754c0425ffSMingming Cao 
3576ac27a0ecSDave Kleikamp /*
3577617ba13bSMingming Cao  * Pages can be marked dirty completely asynchronously from ext4's journalling
3578ac27a0ecSDave Kleikamp  * activity.  By filemap_sync_pte(), try_to_unmap_one(), etc.  We cannot do
3579ac27a0ecSDave Kleikamp  * much here because ->set_page_dirty is called under VFS locks.  The page is
3580ac27a0ecSDave Kleikamp  * not necessarily locked.
3581ac27a0ecSDave Kleikamp  *
3582ac27a0ecSDave Kleikamp  * We cannot just dirty the page and leave attached buffers clean, because the
3583ac27a0ecSDave Kleikamp  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3584ac27a0ecSDave Kleikamp  * or jbddirty because all the journalling code will explode.
3585ac27a0ecSDave Kleikamp  *
3586ac27a0ecSDave Kleikamp  * So what we do is to mark the page "pending dirty" and next time writepage
3587ac27a0ecSDave Kleikamp  * is called, propagate that into the buffers appropriately.
3588ac27a0ecSDave Kleikamp  */
3589617ba13bSMingming Cao static int ext4_journalled_set_page_dirty(struct page *page)
3590ac27a0ecSDave Kleikamp {
3591ac27a0ecSDave Kleikamp 	SetPageChecked(page);
3592ac27a0ecSDave Kleikamp 	return __set_page_dirty_nobuffers(page);
3593ac27a0ecSDave Kleikamp }
3594ac27a0ecSDave Kleikamp 
35956dcc693bSJan Kara static int ext4_set_page_dirty(struct page *page)
35966dcc693bSJan Kara {
35976dcc693bSJan Kara 	WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
35986dcc693bSJan Kara 	WARN_ON_ONCE(!page_has_buffers(page));
35996dcc693bSJan Kara 	return __set_page_dirty_buffers(page);
36006dcc693bSJan Kara }
36016dcc693bSJan Kara 
360274d553aaSTheodore Ts'o static const struct address_space_operations ext4_aops = {
3603617ba13bSMingming Cao 	.readpage		= ext4_readpage,
3604617ba13bSMingming Cao 	.readpages		= ext4_readpages,
360543ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
360620970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3607bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
360874d553aaSTheodore Ts'o 	.write_end		= ext4_write_end,
36096dcc693bSJan Kara 	.set_page_dirty		= ext4_set_page_dirty,
3610617ba13bSMingming Cao 	.bmap			= ext4_bmap,
3611617ba13bSMingming Cao 	.invalidatepage		= ext4_invalidatepage,
3612617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
3613378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
3614ac27a0ecSDave Kleikamp 	.migratepage		= buffer_migrate_page,
36158ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3616aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
3617ac27a0ecSDave Kleikamp };
3618ac27a0ecSDave Kleikamp 
3619617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
3620617ba13bSMingming Cao 	.readpage		= ext4_readpage,
3621617ba13bSMingming Cao 	.readpages		= ext4_readpages,
362243ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
362320970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3624bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
3625bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
3626617ba13bSMingming Cao 	.set_page_dirty		= ext4_journalled_set_page_dirty,
3627617ba13bSMingming Cao 	.bmap			= ext4_bmap,
36284520fb3cSJan Kara 	.invalidatepage		= ext4_journalled_invalidatepage,
3629617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
3630378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
36318ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3632aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
3633ac27a0ecSDave Kleikamp };
3634ac27a0ecSDave Kleikamp 
363564769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
363664769240SAlex Tomas 	.readpage		= ext4_readpage,
363764769240SAlex Tomas 	.readpages		= ext4_readpages,
363843ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
363920970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
364064769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
364164769240SAlex Tomas 	.write_end		= ext4_da_write_end,
36426dcc693bSJan Kara 	.set_page_dirty		= ext4_set_page_dirty,
364364769240SAlex Tomas 	.bmap			= ext4_bmap,
36448fcc3a58SEric Whitney 	.invalidatepage		= ext4_invalidatepage,
364564769240SAlex Tomas 	.releasepage		= ext4_releasepage,
3646378f32baSMatthew Bobrowski 	.direct_IO		= noop_direct_IO,
364764769240SAlex Tomas 	.migratepage		= buffer_migrate_page,
36488ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3649aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
365064769240SAlex Tomas };
365164769240SAlex Tomas 
36525f0663bbSDan Williams static const struct address_space_operations ext4_dax_aops = {
36535f0663bbSDan Williams 	.writepages		= ext4_dax_writepages,
36545f0663bbSDan Williams 	.direct_IO		= noop_direct_IO,
36555f0663bbSDan Williams 	.set_page_dirty		= noop_set_page_dirty,
365694dbb631SToshi Kani 	.bmap			= ext4_bmap,
36575f0663bbSDan Williams 	.invalidatepage		= noop_invalidatepage,
36585f0663bbSDan Williams };
36595f0663bbSDan Williams 
3660617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
3661ac27a0ecSDave Kleikamp {
36623d2b1582SLukas Czerner 	switch (ext4_inode_journal_mode(inode)) {
36633d2b1582SLukas Czerner 	case EXT4_INODE_ORDERED_DATA_MODE:
36643d2b1582SLukas Czerner 	case EXT4_INODE_WRITEBACK_DATA_MODE:
36653d2b1582SLukas Czerner 		break;
36663d2b1582SLukas Czerner 	case EXT4_INODE_JOURNAL_DATA_MODE:
3667617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
366874d553aaSTheodore Ts'o 		return;
36693d2b1582SLukas Czerner 	default:
36703d2b1582SLukas Czerner 		BUG();
36713d2b1582SLukas Czerner 	}
36725f0663bbSDan Williams 	if (IS_DAX(inode))
36735f0663bbSDan Williams 		inode->i_mapping->a_ops = &ext4_dax_aops;
36745f0663bbSDan Williams 	else if (test_opt(inode->i_sb, DELALLOC))
367574d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_da_aops;
367674d553aaSTheodore Ts'o 	else
367774d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_aops;
3678ac27a0ecSDave Kleikamp }
3679ac27a0ecSDave Kleikamp 
3680923ae0ffSRoss Zwisler static int __ext4_block_zero_page_range(handle_t *handle,
3681d863dc36SLukas Czerner 		struct address_space *mapping, loff_t from, loff_t length)
3682d863dc36SLukas Czerner {
368309cbfeafSKirill A. Shutemov 	ext4_fsblk_t index = from >> PAGE_SHIFT;
368409cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3685923ae0ffSRoss Zwisler 	unsigned blocksize, pos;
3686d863dc36SLukas Czerner 	ext4_lblk_t iblock;
3687d863dc36SLukas Czerner 	struct inode *inode = mapping->host;
3688d863dc36SLukas Czerner 	struct buffer_head *bh;
3689d863dc36SLukas Czerner 	struct page *page;
3690d863dc36SLukas Czerner 	int err = 0;
3691d863dc36SLukas Czerner 
369209cbfeafSKirill A. Shutemov 	page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3693c62d2555SMichal Hocko 				   mapping_gfp_constraint(mapping, ~__GFP_FS));
3694d863dc36SLukas Czerner 	if (!page)
3695d863dc36SLukas Czerner 		return -ENOMEM;
3696d863dc36SLukas Czerner 
3697d863dc36SLukas Czerner 	blocksize = inode->i_sb->s_blocksize;
3698d863dc36SLukas Czerner 
369909cbfeafSKirill A. Shutemov 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3700d863dc36SLukas Czerner 
3701d863dc36SLukas Czerner 	if (!page_has_buffers(page))
3702d863dc36SLukas Czerner 		create_empty_buffers(page, blocksize, 0);
3703d863dc36SLukas Czerner 
3704d863dc36SLukas Czerner 	/* Find the buffer that contains "offset" */
3705d863dc36SLukas Czerner 	bh = page_buffers(page);
3706d863dc36SLukas Czerner 	pos = blocksize;
3707d863dc36SLukas Czerner 	while (offset >= pos) {
3708d863dc36SLukas Czerner 		bh = bh->b_this_page;
3709d863dc36SLukas Czerner 		iblock++;
3710d863dc36SLukas Czerner 		pos += blocksize;
3711d863dc36SLukas Czerner 	}
3712d863dc36SLukas Czerner 	if (buffer_freed(bh)) {
3713d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "freed: skip");
3714d863dc36SLukas Czerner 		goto unlock;
3715d863dc36SLukas Czerner 	}
3716d863dc36SLukas Czerner 	if (!buffer_mapped(bh)) {
3717d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "unmapped");
3718d863dc36SLukas Czerner 		ext4_get_block(inode, iblock, bh, 0);
3719d863dc36SLukas Czerner 		/* unmapped? It's a hole - nothing to do */
3720d863dc36SLukas Czerner 		if (!buffer_mapped(bh)) {
3721d863dc36SLukas Czerner 			BUFFER_TRACE(bh, "still unmapped");
3722d863dc36SLukas Czerner 			goto unlock;
3723d863dc36SLukas Czerner 		}
3724d863dc36SLukas Czerner 	}
3725d863dc36SLukas Czerner 
3726d863dc36SLukas Czerner 	/* Ok, it's mapped. Make sure it's up-to-date */
3727d863dc36SLukas Czerner 	if (PageUptodate(page))
3728d863dc36SLukas Czerner 		set_buffer_uptodate(bh);
3729d863dc36SLukas Czerner 
3730d863dc36SLukas Czerner 	if (!buffer_uptodate(bh)) {
3731d863dc36SLukas Czerner 		err = -EIO;
3732dfec8a14SMike Christie 		ll_rw_block(REQ_OP_READ, 0, 1, &bh);
3733d863dc36SLukas Czerner 		wait_on_buffer(bh);
3734d863dc36SLukas Czerner 		/* Uhhuh. Read error. Complain and punt. */
3735d863dc36SLukas Czerner 		if (!buffer_uptodate(bh))
3736d863dc36SLukas Czerner 			goto unlock;
3737592ddec7SChandan Rajendra 		if (S_ISREG(inode->i_mode) && IS_ENCRYPTED(inode)) {
3738c9c7429cSMichael Halcrow 			/* We expect the key to be set. */
3739a7550b30SJaegeuk Kim 			BUG_ON(!fscrypt_has_encryption_key(inode));
3740834f1565SEric Biggers 			err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3741834f1565SEric Biggers 							       bh_offset(bh));
3742834f1565SEric Biggers 			if (err) {
3743834f1565SEric Biggers 				clear_buffer_uptodate(bh);
3744834f1565SEric Biggers 				goto unlock;
3745834f1565SEric Biggers 			}
3746c9c7429cSMichael Halcrow 		}
3747d863dc36SLukas Czerner 	}
3748d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3749d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "get write access");
3750d863dc36SLukas Czerner 		err = ext4_journal_get_write_access(handle, bh);
3751d863dc36SLukas Czerner 		if (err)
3752d863dc36SLukas Czerner 			goto unlock;
3753d863dc36SLukas Czerner 	}
3754d863dc36SLukas Czerner 	zero_user(page, offset, length);
3755d863dc36SLukas Czerner 	BUFFER_TRACE(bh, "zeroed end of block");
3756d863dc36SLukas Czerner 
3757d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3758d863dc36SLukas Czerner 		err = ext4_handle_dirty_metadata(handle, inode, bh);
37590713ed0cSLukas Czerner 	} else {
3760353eefd3Sjon ernst 		err = 0;
3761d863dc36SLukas Czerner 		mark_buffer_dirty(bh);
37623957ef53SJan Kara 		if (ext4_should_order_data(inode))
376373131fbbSRoss Zwisler 			err = ext4_jbd2_inode_add_write(handle, inode, from,
376473131fbbSRoss Zwisler 					length);
37650713ed0cSLukas Czerner 	}
3766d863dc36SLukas Czerner 
3767d863dc36SLukas Czerner unlock:
3768d863dc36SLukas Czerner 	unlock_page(page);
376909cbfeafSKirill A. Shutemov 	put_page(page);
3770d863dc36SLukas Czerner 	return err;
3771d863dc36SLukas Czerner }
3772d863dc36SLukas Czerner 
377394350ab5SMatthew Wilcox /*
3774923ae0ffSRoss Zwisler  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3775923ae0ffSRoss Zwisler  * starting from file offset 'from'.  The range to be zero'd must
3776923ae0ffSRoss Zwisler  * be contained with in one block.  If the specified range exceeds
3777923ae0ffSRoss Zwisler  * the end of the block it will be shortened to end of the block
3778923ae0ffSRoss Zwisler  * that cooresponds to 'from'
3779923ae0ffSRoss Zwisler  */
3780923ae0ffSRoss Zwisler static int ext4_block_zero_page_range(handle_t *handle,
3781923ae0ffSRoss Zwisler 		struct address_space *mapping, loff_t from, loff_t length)
3782923ae0ffSRoss Zwisler {
3783923ae0ffSRoss Zwisler 	struct inode *inode = mapping->host;
378409cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3785923ae0ffSRoss Zwisler 	unsigned blocksize = inode->i_sb->s_blocksize;
3786923ae0ffSRoss Zwisler 	unsigned max = blocksize - (offset & (blocksize - 1));
3787923ae0ffSRoss Zwisler 
3788923ae0ffSRoss Zwisler 	/*
3789923ae0ffSRoss Zwisler 	 * correct length if it does not fall between
3790923ae0ffSRoss Zwisler 	 * 'from' and the end of the block
3791923ae0ffSRoss Zwisler 	 */
3792923ae0ffSRoss Zwisler 	if (length > max || length < 0)
3793923ae0ffSRoss Zwisler 		length = max;
3794923ae0ffSRoss Zwisler 
379547e69351SJan Kara 	if (IS_DAX(inode)) {
379647e69351SJan Kara 		return iomap_zero_range(inode, from, length, NULL,
379747e69351SJan Kara 					&ext4_iomap_ops);
379847e69351SJan Kara 	}
3799923ae0ffSRoss Zwisler 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3800923ae0ffSRoss Zwisler }
3801923ae0ffSRoss Zwisler 
3802923ae0ffSRoss Zwisler /*
380394350ab5SMatthew Wilcox  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
380494350ab5SMatthew Wilcox  * up to the end of the block which corresponds to `from'.
380594350ab5SMatthew Wilcox  * This required during truncate. We need to physically zero the tail end
380694350ab5SMatthew Wilcox  * of that block so it doesn't yield old data if the file is later grown.
380794350ab5SMatthew Wilcox  */
3808c197855eSStephen Hemminger static int ext4_block_truncate_page(handle_t *handle,
380994350ab5SMatthew Wilcox 		struct address_space *mapping, loff_t from)
381094350ab5SMatthew Wilcox {
381109cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
381294350ab5SMatthew Wilcox 	unsigned length;
381394350ab5SMatthew Wilcox 	unsigned blocksize;
381494350ab5SMatthew Wilcox 	struct inode *inode = mapping->host;
381594350ab5SMatthew Wilcox 
38160d06863fSTheodore Ts'o 	/* If we are processing an encrypted inode during orphan list handling */
3817592ddec7SChandan Rajendra 	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
38180d06863fSTheodore Ts'o 		return 0;
38190d06863fSTheodore Ts'o 
382094350ab5SMatthew Wilcox 	blocksize = inode->i_sb->s_blocksize;
382194350ab5SMatthew Wilcox 	length = blocksize - (offset & (blocksize - 1));
382294350ab5SMatthew Wilcox 
382394350ab5SMatthew Wilcox 	return ext4_block_zero_page_range(handle, mapping, from, length);
382494350ab5SMatthew Wilcox }
382594350ab5SMatthew Wilcox 
3826a87dd18cSLukas Czerner int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3827a87dd18cSLukas Czerner 			     loff_t lstart, loff_t length)
3828a87dd18cSLukas Czerner {
3829a87dd18cSLukas Czerner 	struct super_block *sb = inode->i_sb;
3830a87dd18cSLukas Czerner 	struct address_space *mapping = inode->i_mapping;
3831e1be3a92SLukas Czerner 	unsigned partial_start, partial_end;
3832a87dd18cSLukas Czerner 	ext4_fsblk_t start, end;
3833a87dd18cSLukas Czerner 	loff_t byte_end = (lstart + length - 1);
3834a87dd18cSLukas Czerner 	int err = 0;
3835a87dd18cSLukas Czerner 
3836e1be3a92SLukas Czerner 	partial_start = lstart & (sb->s_blocksize - 1);
3837e1be3a92SLukas Czerner 	partial_end = byte_end & (sb->s_blocksize - 1);
3838e1be3a92SLukas Czerner 
3839a87dd18cSLukas Czerner 	start = lstart >> sb->s_blocksize_bits;
3840a87dd18cSLukas Czerner 	end = byte_end >> sb->s_blocksize_bits;
3841a87dd18cSLukas Czerner 
3842a87dd18cSLukas Czerner 	/* Handle partial zero within the single block */
3843e1be3a92SLukas Czerner 	if (start == end &&
3844e1be3a92SLukas Czerner 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3845a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3846a87dd18cSLukas Czerner 						 lstart, length);
3847a87dd18cSLukas Czerner 		return err;
3848a87dd18cSLukas Czerner 	}
3849a87dd18cSLukas Czerner 	/* Handle partial zero out on the start of the range */
3850e1be3a92SLukas Czerner 	if (partial_start) {
3851a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3852a87dd18cSLukas Czerner 						 lstart, sb->s_blocksize);
3853a87dd18cSLukas Czerner 		if (err)
3854a87dd18cSLukas Czerner 			return err;
3855a87dd18cSLukas Czerner 	}
3856a87dd18cSLukas Czerner 	/* Handle partial zero out on the end of the range */
3857e1be3a92SLukas Czerner 	if (partial_end != sb->s_blocksize - 1)
3858a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3859e1be3a92SLukas Czerner 						 byte_end - partial_end,
3860e1be3a92SLukas Czerner 						 partial_end + 1);
3861a87dd18cSLukas Czerner 	return err;
3862a87dd18cSLukas Czerner }
3863a87dd18cSLukas Czerner 
386491ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
386591ef4cafSDuane Griffin {
386691ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
386791ef4cafSDuane Griffin 		return 1;
386891ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
386991ef4cafSDuane Griffin 		return 1;
387091ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
387191ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
387291ef4cafSDuane Griffin 	return 0;
387391ef4cafSDuane Griffin }
387491ef4cafSDuane Griffin 
3875ac27a0ecSDave Kleikamp /*
387601127848SJan Kara  * We have to make sure i_disksize gets properly updated before we truncate
387701127848SJan Kara  * page cache due to hole punching or zero range. Otherwise i_disksize update
387801127848SJan Kara  * can get lost as it may have been postponed to submission of writeback but
387901127848SJan Kara  * that will never happen after we truncate page cache.
388001127848SJan Kara  */
388101127848SJan Kara int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
388201127848SJan Kara 				      loff_t len)
388301127848SJan Kara {
388401127848SJan Kara 	handle_t *handle;
388501127848SJan Kara 	loff_t size = i_size_read(inode);
388601127848SJan Kara 
38875955102cSAl Viro 	WARN_ON(!inode_is_locked(inode));
388801127848SJan Kara 	if (offset > size || offset + len < size)
388901127848SJan Kara 		return 0;
389001127848SJan Kara 
389101127848SJan Kara 	if (EXT4_I(inode)->i_disksize >= size)
389201127848SJan Kara 		return 0;
389301127848SJan Kara 
389401127848SJan Kara 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
389501127848SJan Kara 	if (IS_ERR(handle))
389601127848SJan Kara 		return PTR_ERR(handle);
389701127848SJan Kara 	ext4_update_i_disksize(inode, size);
389801127848SJan Kara 	ext4_mark_inode_dirty(handle, inode);
389901127848SJan Kara 	ext4_journal_stop(handle);
390001127848SJan Kara 
390101127848SJan Kara 	return 0;
390201127848SJan Kara }
390301127848SJan Kara 
3904b1f38217SRoss Zwisler static void ext4_wait_dax_page(struct ext4_inode_info *ei)
3905430657b6SRoss Zwisler {
3906430657b6SRoss Zwisler 	up_write(&ei->i_mmap_sem);
3907430657b6SRoss Zwisler 	schedule();
3908430657b6SRoss Zwisler 	down_write(&ei->i_mmap_sem);
3909430657b6SRoss Zwisler }
3910430657b6SRoss Zwisler 
3911430657b6SRoss Zwisler int ext4_break_layouts(struct inode *inode)
3912430657b6SRoss Zwisler {
3913430657b6SRoss Zwisler 	struct ext4_inode_info *ei = EXT4_I(inode);
3914430657b6SRoss Zwisler 	struct page *page;
3915430657b6SRoss Zwisler 	int error;
3916430657b6SRoss Zwisler 
3917430657b6SRoss Zwisler 	if (WARN_ON_ONCE(!rwsem_is_locked(&ei->i_mmap_sem)))
3918430657b6SRoss Zwisler 		return -EINVAL;
3919430657b6SRoss Zwisler 
3920430657b6SRoss Zwisler 	do {
3921430657b6SRoss Zwisler 		page = dax_layout_busy_page(inode->i_mapping);
3922430657b6SRoss Zwisler 		if (!page)
3923430657b6SRoss Zwisler 			return 0;
3924430657b6SRoss Zwisler 
3925430657b6SRoss Zwisler 		error = ___wait_var_event(&page->_refcount,
3926430657b6SRoss Zwisler 				atomic_read(&page->_refcount) == 1,
3927430657b6SRoss Zwisler 				TASK_INTERRUPTIBLE, 0, 0,
3928b1f38217SRoss Zwisler 				ext4_wait_dax_page(ei));
3929b1f38217SRoss Zwisler 	} while (error == 0);
3930430657b6SRoss Zwisler 
3931430657b6SRoss Zwisler 	return error;
3932430657b6SRoss Zwisler }
3933430657b6SRoss Zwisler 
393401127848SJan Kara /*
3935cca32b7eSRoss Zwisler  * ext4_punch_hole: punches a hole in a file by releasing the blocks
3936a4bb6b64SAllison Henderson  * associated with the given offset and length
3937a4bb6b64SAllison Henderson  *
3938a4bb6b64SAllison Henderson  * @inode:  File inode
3939a4bb6b64SAllison Henderson  * @offset: The offset where the hole will begin
3940a4bb6b64SAllison Henderson  * @len:    The length of the hole
3941a4bb6b64SAllison Henderson  *
39424907cb7bSAnatol Pomozov  * Returns: 0 on success or negative on failure
3943a4bb6b64SAllison Henderson  */
3944a4bb6b64SAllison Henderson 
3945aeb2817aSAshish Sangwan int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3946a4bb6b64SAllison Henderson {
394726a4c0c6STheodore Ts'o 	struct super_block *sb = inode->i_sb;
394826a4c0c6STheodore Ts'o 	ext4_lblk_t first_block, stop_block;
394926a4c0c6STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
3950a87dd18cSLukas Czerner 	loff_t first_block_offset, last_block_offset;
395126a4c0c6STheodore Ts'o 	handle_t *handle;
395226a4c0c6STheodore Ts'o 	unsigned int credits;
395326a4c0c6STheodore Ts'o 	int ret = 0;
395426a4c0c6STheodore Ts'o 
3955b8a86845SLukas Czerner 	trace_ext4_punch_hole(inode, offset, length, 0);
3956aaddea81SZheng Liu 
3957c1e8220bSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
3958c1e8220bSTheodore Ts'o 	if (ext4_has_inline_data(inode)) {
3959c1e8220bSTheodore Ts'o 		down_write(&EXT4_I(inode)->i_mmap_sem);
3960c1e8220bSTheodore Ts'o 		ret = ext4_convert_inline_data(inode);
3961c1e8220bSTheodore Ts'o 		up_write(&EXT4_I(inode)->i_mmap_sem);
3962c1e8220bSTheodore Ts'o 		if (ret)
3963c1e8220bSTheodore Ts'o 			return ret;
3964c1e8220bSTheodore Ts'o 	}
3965c1e8220bSTheodore Ts'o 
396626a4c0c6STheodore Ts'o 	/*
396726a4c0c6STheodore Ts'o 	 * Write out all dirty pages to avoid race conditions
396826a4c0c6STheodore Ts'o 	 * Then release them.
396926a4c0c6STheodore Ts'o 	 */
3970cca32b7eSRoss Zwisler 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
397126a4c0c6STheodore Ts'o 		ret = filemap_write_and_wait_range(mapping, offset,
397226a4c0c6STheodore Ts'o 						   offset + length - 1);
397326a4c0c6STheodore Ts'o 		if (ret)
397426a4c0c6STheodore Ts'o 			return ret;
397526a4c0c6STheodore Ts'o 	}
397626a4c0c6STheodore Ts'o 
39775955102cSAl Viro 	inode_lock(inode);
39789ef06cecSLukas Czerner 
397926a4c0c6STheodore Ts'o 	/* No need to punch hole beyond i_size */
398026a4c0c6STheodore Ts'o 	if (offset >= inode->i_size)
398126a4c0c6STheodore Ts'o 		goto out_mutex;
398226a4c0c6STheodore Ts'o 
398326a4c0c6STheodore Ts'o 	/*
398426a4c0c6STheodore Ts'o 	 * If the hole extends beyond i_size, set the hole
398526a4c0c6STheodore Ts'o 	 * to end after the page that contains i_size
398626a4c0c6STheodore Ts'o 	 */
398726a4c0c6STheodore Ts'o 	if (offset + length > inode->i_size) {
398826a4c0c6STheodore Ts'o 		length = inode->i_size +
398909cbfeafSKirill A. Shutemov 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
399026a4c0c6STheodore Ts'o 		   offset;
399126a4c0c6STheodore Ts'o 	}
399226a4c0c6STheodore Ts'o 
3993a361293fSJan Kara 	if (offset & (sb->s_blocksize - 1) ||
3994a361293fSJan Kara 	    (offset + length) & (sb->s_blocksize - 1)) {
3995a361293fSJan Kara 		/*
3996a361293fSJan Kara 		 * Attach jinode to inode for jbd2 if we do any zeroing of
3997a361293fSJan Kara 		 * partial block
3998a361293fSJan Kara 		 */
3999a361293fSJan Kara 		ret = ext4_inode_attach_jinode(inode);
4000a361293fSJan Kara 		if (ret < 0)
4001a361293fSJan Kara 			goto out_mutex;
4002a361293fSJan Kara 
4003a361293fSJan Kara 	}
4004a361293fSJan Kara 
4005ea3d7209SJan Kara 	/* Wait all existing dio workers, newcomers will block on i_mutex */
4006ea3d7209SJan Kara 	inode_dio_wait(inode);
4007ea3d7209SJan Kara 
4008ea3d7209SJan Kara 	/*
4009ea3d7209SJan Kara 	 * Prevent page faults from reinstantiating pages we have released from
4010ea3d7209SJan Kara 	 * page cache.
4011ea3d7209SJan Kara 	 */
4012ea3d7209SJan Kara 	down_write(&EXT4_I(inode)->i_mmap_sem);
4013430657b6SRoss Zwisler 
4014430657b6SRoss Zwisler 	ret = ext4_break_layouts(inode);
4015430657b6SRoss Zwisler 	if (ret)
4016430657b6SRoss Zwisler 		goto out_dio;
4017430657b6SRoss Zwisler 
4018a87dd18cSLukas Czerner 	first_block_offset = round_up(offset, sb->s_blocksize);
4019a87dd18cSLukas Czerner 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
402026a4c0c6STheodore Ts'o 
4021a87dd18cSLukas Czerner 	/* Now release the pages and zero block aligned part of pages*/
402201127848SJan Kara 	if (last_block_offset > first_block_offset) {
402301127848SJan Kara 		ret = ext4_update_disksize_before_punch(inode, offset, length);
402401127848SJan Kara 		if (ret)
402501127848SJan Kara 			goto out_dio;
4026a87dd18cSLukas Czerner 		truncate_pagecache_range(inode, first_block_offset,
4027a87dd18cSLukas Czerner 					 last_block_offset);
402801127848SJan Kara 	}
402926a4c0c6STheodore Ts'o 
403026a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
403126a4c0c6STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
403226a4c0c6STheodore Ts'o 	else
403326a4c0c6STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
403426a4c0c6STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
403526a4c0c6STheodore Ts'o 	if (IS_ERR(handle)) {
403626a4c0c6STheodore Ts'o 		ret = PTR_ERR(handle);
403726a4c0c6STheodore Ts'o 		ext4_std_error(sb, ret);
403826a4c0c6STheodore Ts'o 		goto out_dio;
403926a4c0c6STheodore Ts'o 	}
404026a4c0c6STheodore Ts'o 
4041a87dd18cSLukas Czerner 	ret = ext4_zero_partial_blocks(handle, inode, offset,
4042a87dd18cSLukas Czerner 				       length);
404326a4c0c6STheodore Ts'o 	if (ret)
404426a4c0c6STheodore Ts'o 		goto out_stop;
404526a4c0c6STheodore Ts'o 
404626a4c0c6STheodore Ts'o 	first_block = (offset + sb->s_blocksize - 1) >>
404726a4c0c6STheodore Ts'o 		EXT4_BLOCK_SIZE_BITS(sb);
404826a4c0c6STheodore Ts'o 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
404926a4c0c6STheodore Ts'o 
4050eee597acSLukas Czerner 	/* If there are blocks to remove, do it */
4051eee597acSLukas Czerner 	if (stop_block > first_block) {
405226a4c0c6STheodore Ts'o 
405326a4c0c6STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
405426a4c0c6STheodore Ts'o 		ext4_discard_preallocations(inode);
405526a4c0c6STheodore Ts'o 
405626a4c0c6STheodore Ts'o 		ret = ext4_es_remove_extent(inode, first_block,
405726a4c0c6STheodore Ts'o 					    stop_block - first_block);
405826a4c0c6STheodore Ts'o 		if (ret) {
405926a4c0c6STheodore Ts'o 			up_write(&EXT4_I(inode)->i_data_sem);
406026a4c0c6STheodore Ts'o 			goto out_stop;
406126a4c0c6STheodore Ts'o 		}
406226a4c0c6STheodore Ts'o 
406326a4c0c6STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
406426a4c0c6STheodore Ts'o 			ret = ext4_ext_remove_space(inode, first_block,
406526a4c0c6STheodore Ts'o 						    stop_block - 1);
406626a4c0c6STheodore Ts'o 		else
40674f579ae7SLukas Czerner 			ret = ext4_ind_remove_space(handle, inode, first_block,
406826a4c0c6STheodore Ts'o 						    stop_block);
406926a4c0c6STheodore Ts'o 
4070819c4920STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
4071eee597acSLukas Czerner 	}
407226a4c0c6STheodore Ts'o 	if (IS_SYNC(inode))
407326a4c0c6STheodore Ts'o 		ext4_handle_sync(handle);
4074e251f9bcSMaxim Patlasov 
4075eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
407626a4c0c6STheodore Ts'o 	ext4_mark_inode_dirty(handle, inode);
407767a7d5f5SJan Kara 	if (ret >= 0)
407867a7d5f5SJan Kara 		ext4_update_inode_fsync_trans(handle, inode, 1);
407926a4c0c6STheodore Ts'o out_stop:
408026a4c0c6STheodore Ts'o 	ext4_journal_stop(handle);
408126a4c0c6STheodore Ts'o out_dio:
4082ea3d7209SJan Kara 	up_write(&EXT4_I(inode)->i_mmap_sem);
408326a4c0c6STheodore Ts'o out_mutex:
40845955102cSAl Viro 	inode_unlock(inode);
408526a4c0c6STheodore Ts'o 	return ret;
4086a4bb6b64SAllison Henderson }
4087a4bb6b64SAllison Henderson 
4088a361293fSJan Kara int ext4_inode_attach_jinode(struct inode *inode)
4089a361293fSJan Kara {
4090a361293fSJan Kara 	struct ext4_inode_info *ei = EXT4_I(inode);
4091a361293fSJan Kara 	struct jbd2_inode *jinode;
4092a361293fSJan Kara 
4093a361293fSJan Kara 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4094a361293fSJan Kara 		return 0;
4095a361293fSJan Kara 
4096a361293fSJan Kara 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4097a361293fSJan Kara 	spin_lock(&inode->i_lock);
4098a361293fSJan Kara 	if (!ei->jinode) {
4099a361293fSJan Kara 		if (!jinode) {
4100a361293fSJan Kara 			spin_unlock(&inode->i_lock);
4101a361293fSJan Kara 			return -ENOMEM;
4102a361293fSJan Kara 		}
4103a361293fSJan Kara 		ei->jinode = jinode;
4104a361293fSJan Kara 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4105a361293fSJan Kara 		jinode = NULL;
4106a361293fSJan Kara 	}
4107a361293fSJan Kara 	spin_unlock(&inode->i_lock);
4108a361293fSJan Kara 	if (unlikely(jinode != NULL))
4109a361293fSJan Kara 		jbd2_free_inode(jinode);
4110a361293fSJan Kara 	return 0;
4111a361293fSJan Kara }
4112a361293fSJan Kara 
4113a4bb6b64SAllison Henderson /*
4114617ba13bSMingming Cao  * ext4_truncate()
4115ac27a0ecSDave Kleikamp  *
4116617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
4117617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4118ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
4119ac27a0ecSDave Kleikamp  *
412042b2aa86SJustin P. Mattock  * As we work through the truncate and commit bits of it to the journal there
4121ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
4122ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
4123ac27a0ecSDave Kleikamp  *
4124ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
4125ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
4126ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
4127ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
4128ac27a0ecSDave Kleikamp  * left-to-right works OK too).
4129ac27a0ecSDave Kleikamp  *
4130ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
4131ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
4132ac27a0ecSDave Kleikamp  *
4133ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
4134617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4135ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
4136617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
4137617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
4138ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
4139617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
4140ac27a0ecSDave Kleikamp  */
41412c98eb5eSTheodore Ts'o int ext4_truncate(struct inode *inode)
4142ac27a0ecSDave Kleikamp {
4143819c4920STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
4144819c4920STheodore Ts'o 	unsigned int credits;
41452c98eb5eSTheodore Ts'o 	int err = 0;
4146819c4920STheodore Ts'o 	handle_t *handle;
4147819c4920STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
4148819c4920STheodore Ts'o 
414919b5ef61STheodore Ts'o 	/*
415019b5ef61STheodore Ts'o 	 * There is a possibility that we're either freeing the inode
4151e04027e8SMatthew Wilcox 	 * or it's a completely new inode. In those cases we might not
415219b5ef61STheodore Ts'o 	 * have i_mutex locked because it's not necessary.
415319b5ef61STheodore Ts'o 	 */
415419b5ef61STheodore Ts'o 	if (!(inode->i_state & (I_NEW|I_FREEING)))
41555955102cSAl Viro 		WARN_ON(!inode_is_locked(inode));
41560562e0baSJiaying Zhang 	trace_ext4_truncate_enter(inode);
41570562e0baSJiaying Zhang 
415891ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
41592c98eb5eSTheodore Ts'o 		return 0;
4160ac27a0ecSDave Kleikamp 
41615534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
416219f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
41637d8f9f7dSTheodore Ts'o 
4164aef1c851STao Ma 	if (ext4_has_inline_data(inode)) {
4165aef1c851STao Ma 		int has_inline = 1;
4166aef1c851STao Ma 
416701daf945STheodore Ts'o 		err = ext4_inline_data_truncate(inode, &has_inline);
416801daf945STheodore Ts'o 		if (err)
416901daf945STheodore Ts'o 			return err;
4170aef1c851STao Ma 		if (has_inline)
41712c98eb5eSTheodore Ts'o 			return 0;
4172aef1c851STao Ma 	}
4173aef1c851STao Ma 
4174a361293fSJan Kara 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4175a361293fSJan Kara 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4176a361293fSJan Kara 		if (ext4_inode_attach_jinode(inode) < 0)
41772c98eb5eSTheodore Ts'o 			return 0;
4178a361293fSJan Kara 	}
4179a361293fSJan Kara 
4180ff9893dcSAmir Goldstein 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4181819c4920STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
4182ff9893dcSAmir Goldstein 	else
4183819c4920STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
4184819c4920STheodore Ts'o 
4185819c4920STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
41862c98eb5eSTheodore Ts'o 	if (IS_ERR(handle))
41872c98eb5eSTheodore Ts'o 		return PTR_ERR(handle);
4188819c4920STheodore Ts'o 
4189eb3544c6SLukas Czerner 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4190eb3544c6SLukas Czerner 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4191819c4920STheodore Ts'o 
4192819c4920STheodore Ts'o 	/*
4193819c4920STheodore Ts'o 	 * We add the inode to the orphan list, so that if this
4194819c4920STheodore Ts'o 	 * truncate spans multiple transactions, and we crash, we will
4195819c4920STheodore Ts'o 	 * resume the truncate when the filesystem recovers.  It also
4196819c4920STheodore Ts'o 	 * marks the inode dirty, to catch the new size.
4197819c4920STheodore Ts'o 	 *
4198819c4920STheodore Ts'o 	 * Implication: the file must always be in a sane, consistent
4199819c4920STheodore Ts'o 	 * truncatable state while each transaction commits.
4200819c4920STheodore Ts'o 	 */
42012c98eb5eSTheodore Ts'o 	err = ext4_orphan_add(handle, inode);
42022c98eb5eSTheodore Ts'o 	if (err)
4203819c4920STheodore Ts'o 		goto out_stop;
4204819c4920STheodore Ts'o 
4205819c4920STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
4206819c4920STheodore Ts'o 
4207819c4920STheodore Ts'o 	ext4_discard_preallocations(inode);
4208819c4920STheodore Ts'o 
4209819c4920STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4210d0abb36dSTheodore Ts'o 		err = ext4_ext_truncate(handle, inode);
4211819c4920STheodore Ts'o 	else
4212819c4920STheodore Ts'o 		ext4_ind_truncate(handle, inode);
4213819c4920STheodore Ts'o 
4214819c4920STheodore Ts'o 	up_write(&ei->i_data_sem);
4215d0abb36dSTheodore Ts'o 	if (err)
4216d0abb36dSTheodore Ts'o 		goto out_stop;
4217819c4920STheodore Ts'o 
4218819c4920STheodore Ts'o 	if (IS_SYNC(inode))
4219819c4920STheodore Ts'o 		ext4_handle_sync(handle);
4220819c4920STheodore Ts'o 
4221819c4920STheodore Ts'o out_stop:
4222819c4920STheodore Ts'o 	/*
4223819c4920STheodore Ts'o 	 * If this was a simple ftruncate() and the file will remain alive,
4224819c4920STheodore Ts'o 	 * then we need to clear up the orphan record which we created above.
4225819c4920STheodore Ts'o 	 * However, if this was a real unlink then we were called by
422658d86a50SWang Shilong 	 * ext4_evict_inode(), and we allow that function to clean up the
4227819c4920STheodore Ts'o 	 * orphan info for us.
4228819c4920STheodore Ts'o 	 */
4229819c4920STheodore Ts'o 	if (inode->i_nlink)
4230819c4920STheodore Ts'o 		ext4_orphan_del(handle, inode);
4231819c4920STheodore Ts'o 
4232eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
4233819c4920STheodore Ts'o 	ext4_mark_inode_dirty(handle, inode);
4234819c4920STheodore Ts'o 	ext4_journal_stop(handle);
4235a86c6181SAlex Tomas 
42360562e0baSJiaying Zhang 	trace_ext4_truncate_exit(inode);
42372c98eb5eSTheodore Ts'o 	return err;
4238ac27a0ecSDave Kleikamp }
4239ac27a0ecSDave Kleikamp 
4240ac27a0ecSDave Kleikamp /*
4241617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
4242ac27a0ecSDave Kleikamp  * underlying buffer_head on success. If 'in_mem' is true, we have all
4243ac27a0ecSDave Kleikamp  * data in memory that is needed to recreate the on-disk version of this
4244ac27a0ecSDave Kleikamp  * inode.
4245ac27a0ecSDave Kleikamp  */
4246617ba13bSMingming Cao static int __ext4_get_inode_loc(struct inode *inode,
4247617ba13bSMingming Cao 				struct ext4_iloc *iloc, int in_mem)
4248ac27a0ecSDave Kleikamp {
4249240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
4250ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
4251240799cdSTheodore Ts'o 	struct super_block	*sb = inode->i_sb;
4252240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
425302f03c42SLinus Torvalds 	struct blk_plug		plug;
4254240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
4255ac27a0ecSDave Kleikamp 
42563a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
4257c37e9e01STheodore Ts'o 	if (inode->i_ino < EXT4_ROOT_INO ||
4258c37e9e01STheodore Ts'o 	    inode->i_ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
42596a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4260ac27a0ecSDave Kleikamp 
4261240799cdSTheodore Ts'o 	iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4262240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4263240799cdSTheodore Ts'o 	if (!gdp)
4264240799cdSTheodore Ts'o 		return -EIO;
4265240799cdSTheodore Ts'o 
4266240799cdSTheodore Ts'o 	/*
4267240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
4268240799cdSTheodore Ts'o 	 */
426900d09882STao Ma 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4270240799cdSTheodore Ts'o 	inode_offset = ((inode->i_ino - 1) %
4271240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
4272240799cdSTheodore Ts'o 	block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4273240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4274240799cdSTheodore Ts'o 
4275240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
4276aebf0243SWang Shilong 	if (unlikely(!bh))
4277860d21e2STheodore Ts'o 		return -ENOMEM;
427846f870d6STheodore Ts'o 	if (ext4_simulate_fail(sb, EXT4_SIM_INODE_EIO))
427946f870d6STheodore Ts'o 		goto simulate_eio;
4280ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
4281ac27a0ecSDave Kleikamp 		lock_buffer(bh);
42829c83a923SHidehiro Kawai 
42839c83a923SHidehiro Kawai 		/*
42849c83a923SHidehiro Kawai 		 * If the buffer has the write error flag, we have failed
42859c83a923SHidehiro Kawai 		 * to write out another inode in the same block.  In this
42869c83a923SHidehiro Kawai 		 * case, we don't have to read the block because we may
42879c83a923SHidehiro Kawai 		 * read the old inode data successfully.
42889c83a923SHidehiro Kawai 		 */
42899c83a923SHidehiro Kawai 		if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
42909c83a923SHidehiro Kawai 			set_buffer_uptodate(bh);
42919c83a923SHidehiro Kawai 
4292ac27a0ecSDave Kleikamp 		if (buffer_uptodate(bh)) {
4293ac27a0ecSDave Kleikamp 			/* someone brought it uptodate while we waited */
4294ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
4295ac27a0ecSDave Kleikamp 			goto has_buffer;
4296ac27a0ecSDave Kleikamp 		}
4297ac27a0ecSDave Kleikamp 
4298ac27a0ecSDave Kleikamp 		/*
4299ac27a0ecSDave Kleikamp 		 * If we have all information of the inode in memory and this
4300ac27a0ecSDave Kleikamp 		 * is the only valid inode in the block, we need not read the
4301ac27a0ecSDave Kleikamp 		 * block.
4302ac27a0ecSDave Kleikamp 		 */
4303ac27a0ecSDave Kleikamp 		if (in_mem) {
4304ac27a0ecSDave Kleikamp 			struct buffer_head *bitmap_bh;
4305240799cdSTheodore Ts'o 			int i, start;
4306ac27a0ecSDave Kleikamp 
4307240799cdSTheodore Ts'o 			start = inode_offset & ~(inodes_per_block - 1);
4308ac27a0ecSDave Kleikamp 
4309ac27a0ecSDave Kleikamp 			/* Is the inode bitmap in cache? */
4310240799cdSTheodore Ts'o 			bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4311aebf0243SWang Shilong 			if (unlikely(!bitmap_bh))
4312ac27a0ecSDave Kleikamp 				goto make_io;
4313ac27a0ecSDave Kleikamp 
4314ac27a0ecSDave Kleikamp 			/*
4315ac27a0ecSDave Kleikamp 			 * If the inode bitmap isn't in cache then the
4316ac27a0ecSDave Kleikamp 			 * optimisation may end up performing two reads instead
4317ac27a0ecSDave Kleikamp 			 * of one, so skip it.
4318ac27a0ecSDave Kleikamp 			 */
4319ac27a0ecSDave Kleikamp 			if (!buffer_uptodate(bitmap_bh)) {
4320ac27a0ecSDave Kleikamp 				brelse(bitmap_bh);
4321ac27a0ecSDave Kleikamp 				goto make_io;
4322ac27a0ecSDave Kleikamp 			}
4323240799cdSTheodore Ts'o 			for (i = start; i < start + inodes_per_block; i++) {
4324ac27a0ecSDave Kleikamp 				if (i == inode_offset)
4325ac27a0ecSDave Kleikamp 					continue;
4326617ba13bSMingming Cao 				if (ext4_test_bit(i, bitmap_bh->b_data))
4327ac27a0ecSDave Kleikamp 					break;
4328ac27a0ecSDave Kleikamp 			}
4329ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
4330240799cdSTheodore Ts'o 			if (i == start + inodes_per_block) {
4331ac27a0ecSDave Kleikamp 				/* all other inodes are free, so skip I/O */
4332ac27a0ecSDave Kleikamp 				memset(bh->b_data, 0, bh->b_size);
4333ac27a0ecSDave Kleikamp 				set_buffer_uptodate(bh);
4334ac27a0ecSDave Kleikamp 				unlock_buffer(bh);
4335ac27a0ecSDave Kleikamp 				goto has_buffer;
4336ac27a0ecSDave Kleikamp 			}
4337ac27a0ecSDave Kleikamp 		}
4338ac27a0ecSDave Kleikamp 
4339ac27a0ecSDave Kleikamp make_io:
4340ac27a0ecSDave Kleikamp 		/*
4341240799cdSTheodore Ts'o 		 * If we need to do any I/O, try to pre-readahead extra
4342240799cdSTheodore Ts'o 		 * blocks from the inode table.
4343240799cdSTheodore Ts'o 		 */
434402f03c42SLinus Torvalds 		blk_start_plug(&plug);
4345240799cdSTheodore Ts'o 		if (EXT4_SB(sb)->s_inode_readahead_blks) {
4346240799cdSTheodore Ts'o 			ext4_fsblk_t b, end, table;
4347240799cdSTheodore Ts'o 			unsigned num;
43480d606e2cSTheodore Ts'o 			__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4349240799cdSTheodore Ts'o 
4350240799cdSTheodore Ts'o 			table = ext4_inode_table(sb, gdp);
4351b713a5ecSTheodore Ts'o 			/* s_inode_readahead_blks is always a power of 2 */
43520d606e2cSTheodore Ts'o 			b = block & ~((ext4_fsblk_t) ra_blks - 1);
4353240799cdSTheodore Ts'o 			if (table > b)
4354240799cdSTheodore Ts'o 				b = table;
43550d606e2cSTheodore Ts'o 			end = b + ra_blks;
4356240799cdSTheodore Ts'o 			num = EXT4_INODES_PER_GROUP(sb);
4357feb0ab32SDarrick J. Wong 			if (ext4_has_group_desc_csum(sb))
4358560671a0SAneesh Kumar K.V 				num -= ext4_itable_unused_count(sb, gdp);
4359240799cdSTheodore Ts'o 			table += num / inodes_per_block;
4360240799cdSTheodore Ts'o 			if (end > table)
4361240799cdSTheodore Ts'o 				end = table;
4362240799cdSTheodore Ts'o 			while (b <= end)
4363d87f6392SRoman Gushchin 				sb_breadahead_unmovable(sb, b++);
4364240799cdSTheodore Ts'o 		}
4365240799cdSTheodore Ts'o 
4366240799cdSTheodore Ts'o 		/*
4367ac27a0ecSDave Kleikamp 		 * There are other valid inodes in the buffer, this inode
4368ac27a0ecSDave Kleikamp 		 * has in-inode xattrs, or we don't have this inode in memory.
4369ac27a0ecSDave Kleikamp 		 * Read the block from disk.
4370ac27a0ecSDave Kleikamp 		 */
43710562e0baSJiaying Zhang 		trace_ext4_load_inode(inode);
4372ac27a0ecSDave Kleikamp 		get_bh(bh);
4373ac27a0ecSDave Kleikamp 		bh->b_end_io = end_buffer_read_sync;
43742a222ca9SMike Christie 		submit_bh(REQ_OP_READ, REQ_META | REQ_PRIO, bh);
437502f03c42SLinus Torvalds 		blk_finish_plug(&plug);
4376ac27a0ecSDave Kleikamp 		wait_on_buffer(bh);
4377ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bh)) {
437846f870d6STheodore Ts'o 		simulate_eio:
437954d3adbcSTheodore Ts'o 			ext4_error_inode_block(inode, block, EIO,
4380c398eda0STheodore Ts'o 					       "unable to read itable block");
4381ac27a0ecSDave Kleikamp 			brelse(bh);
4382ac27a0ecSDave Kleikamp 			return -EIO;
4383ac27a0ecSDave Kleikamp 		}
4384ac27a0ecSDave Kleikamp 	}
4385ac27a0ecSDave Kleikamp has_buffer:
4386ac27a0ecSDave Kleikamp 	iloc->bh = bh;
4387ac27a0ecSDave Kleikamp 	return 0;
4388ac27a0ecSDave Kleikamp }
4389ac27a0ecSDave Kleikamp 
4390617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4391ac27a0ecSDave Kleikamp {
4392ac27a0ecSDave Kleikamp 	/* We have all inode data except xattrs in memory here. */
4393617ba13bSMingming Cao 	return __ext4_get_inode_loc(inode, iloc,
439419f5fb7aSTheodore Ts'o 		!ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4395ac27a0ecSDave Kleikamp }
4396ac27a0ecSDave Kleikamp 
43976642586bSRoss Zwisler static bool ext4_should_use_dax(struct inode *inode)
43986642586bSRoss Zwisler {
43996642586bSRoss Zwisler 	if (!test_opt(inode->i_sb, DAX))
44006642586bSRoss Zwisler 		return false;
44016642586bSRoss Zwisler 	if (!S_ISREG(inode->i_mode))
44026642586bSRoss Zwisler 		return false;
44036642586bSRoss Zwisler 	if (ext4_should_journal_data(inode))
44046642586bSRoss Zwisler 		return false;
44056642586bSRoss Zwisler 	if (ext4_has_inline_data(inode))
44066642586bSRoss Zwisler 		return false;
4407592ddec7SChandan Rajendra 	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
44086642586bSRoss Zwisler 		return false;
4409c93d8f88SEric Biggers 	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4410c93d8f88SEric Biggers 		return false;
44116642586bSRoss Zwisler 	return true;
44126642586bSRoss Zwisler }
44136642586bSRoss Zwisler 
4414617ba13bSMingming Cao void ext4_set_inode_flags(struct inode *inode)
4415ac27a0ecSDave Kleikamp {
4416617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
441700a1a053STheodore Ts'o 	unsigned int new_fl = 0;
4418ac27a0ecSDave Kleikamp 
4419617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
442000a1a053STheodore Ts'o 		new_fl |= S_SYNC;
4421617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
442200a1a053STheodore Ts'o 		new_fl |= S_APPEND;
4423617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
442400a1a053STheodore Ts'o 		new_fl |= S_IMMUTABLE;
4425617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
442600a1a053STheodore Ts'o 		new_fl |= S_NOATIME;
4427617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
442800a1a053STheodore Ts'o 		new_fl |= S_DIRSYNC;
44296642586bSRoss Zwisler 	if (ext4_should_use_dax(inode))
4430923ae0ffSRoss Zwisler 		new_fl |= S_DAX;
44312ee6a576SEric Biggers 	if (flags & EXT4_ENCRYPT_FL)
44322ee6a576SEric Biggers 		new_fl |= S_ENCRYPTED;
4433b886ee3eSGabriel Krisman Bertazi 	if (flags & EXT4_CASEFOLD_FL)
4434b886ee3eSGabriel Krisman Bertazi 		new_fl |= S_CASEFOLD;
4435c93d8f88SEric Biggers 	if (flags & EXT4_VERITY_FL)
4436c93d8f88SEric Biggers 		new_fl |= S_VERITY;
44375f16f322STheodore Ts'o 	inode_set_flags(inode, new_fl,
44382ee6a576SEric Biggers 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4439c93d8f88SEric Biggers 			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4440ac27a0ecSDave Kleikamp }
4441ac27a0ecSDave Kleikamp 
44420fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
44430fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
44440fc1b451SAneesh Kumar K.V {
44450fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
44468180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
44478180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
44480fc1b451SAneesh Kumar K.V 
4449e2b911c5SDarrick J. Wong 	if (ext4_has_feature_huge_file(sb)) {
44500fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
44510fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
44520fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
445307a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
44548180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
44558180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
44568180a562SAneesh Kumar K.V 		} else {
44570fc1b451SAneesh Kumar K.V 			return i_blocks;
44588180a562SAneesh Kumar K.V 		}
44590fc1b451SAneesh Kumar K.V 	} else {
44600fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
44610fc1b451SAneesh Kumar K.V 	}
44620fc1b451SAneesh Kumar K.V }
4463ff9ddf7eSJan Kara 
4464eb9b5f01STheodore Ts'o static inline int ext4_iget_extra_inode(struct inode *inode,
4465152a7b0aSTao Ma 					 struct ext4_inode *raw_inode,
4466152a7b0aSTao Ma 					 struct ext4_inode_info *ei)
4467152a7b0aSTao Ma {
4468152a7b0aSTao Ma 	__le32 *magic = (void *)raw_inode +
4469152a7b0aSTao Ma 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4470eb9b5f01STheodore Ts'o 
4471290ab230SEric Biggers 	if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
4472290ab230SEric Biggers 	    EXT4_INODE_SIZE(inode->i_sb) &&
4473290ab230SEric Biggers 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4474152a7b0aSTao Ma 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4475eb9b5f01STheodore Ts'o 		return ext4_find_inline_data_nolock(inode);
4476f19d5870STao Ma 	} else
4477f19d5870STao Ma 		EXT4_I(inode)->i_inline_off = 0;
4478eb9b5f01STheodore Ts'o 	return 0;
4479152a7b0aSTao Ma }
4480152a7b0aSTao Ma 
4481040cb378SLi Xi int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4482040cb378SLi Xi {
44830b7b7779SKaho Ng 	if (!ext4_has_feature_project(inode->i_sb))
4484040cb378SLi Xi 		return -EOPNOTSUPP;
4485040cb378SLi Xi 	*projid = EXT4_I(inode)->i_projid;
4486040cb378SLi Xi 	return 0;
4487040cb378SLi Xi }
4488040cb378SLi Xi 
4489e254d1afSEryu Guan /*
4490e254d1afSEryu Guan  * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4491e254d1afSEryu Guan  * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4492e254d1afSEryu Guan  * set.
4493e254d1afSEryu Guan  */
4494e254d1afSEryu Guan static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4495e254d1afSEryu Guan {
4496e254d1afSEryu Guan 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4497e254d1afSEryu Guan 		inode_set_iversion_raw(inode, val);
4498e254d1afSEryu Guan 	else
4499e254d1afSEryu Guan 		inode_set_iversion_queried(inode, val);
4500e254d1afSEryu Guan }
4501e254d1afSEryu Guan static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4502e254d1afSEryu Guan {
4503e254d1afSEryu Guan 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4504e254d1afSEryu Guan 		return inode_peek_iversion_raw(inode);
4505e254d1afSEryu Guan 	else
4506e254d1afSEryu Guan 		return inode_peek_iversion(inode);
4507e254d1afSEryu Guan }
4508e254d1afSEryu Guan 
45098a363970STheodore Ts'o struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
45108a363970STheodore Ts'o 			  ext4_iget_flags flags, const char *function,
45118a363970STheodore Ts'o 			  unsigned int line)
4512ac27a0ecSDave Kleikamp {
4513617ba13bSMingming Cao 	struct ext4_iloc iloc;
4514617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
45151d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
45161d1fe1eeSDavid Howells 	struct inode *inode;
4517b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
45181d1fe1eeSDavid Howells 	long ret;
45197e6e1ef4SDarrick J. Wong 	loff_t size;
4520ac27a0ecSDave Kleikamp 	int block;
452108cefc7aSEric W. Biederman 	uid_t i_uid;
452208cefc7aSEric W. Biederman 	gid_t i_gid;
4523040cb378SLi Xi 	projid_t i_projid;
4524ac27a0ecSDave Kleikamp 
4525191ce178STheodore Ts'o 	if ((!(flags & EXT4_IGET_SPECIAL) &&
45268a363970STheodore Ts'o 	     (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)) ||
45278a363970STheodore Ts'o 	    (ino < EXT4_ROOT_INO) ||
45288a363970STheodore Ts'o 	    (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) {
45298a363970STheodore Ts'o 		if (flags & EXT4_IGET_HANDLE)
45308a363970STheodore Ts'o 			return ERR_PTR(-ESTALE);
453154d3adbcSTheodore Ts'o 		__ext4_error(sb, function, line, EFSCORRUPTED, 0,
45328a363970STheodore Ts'o 			     "inode #%lu: comm %s: iget: illegal inode #",
45338a363970STheodore Ts'o 			     ino, current->comm);
45348a363970STheodore Ts'o 		return ERR_PTR(-EFSCORRUPTED);
45358a363970STheodore Ts'o 	}
45368a363970STheodore Ts'o 
45371d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
45381d1fe1eeSDavid Howells 	if (!inode)
45391d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
45401d1fe1eeSDavid Howells 	if (!(inode->i_state & I_NEW))
45411d1fe1eeSDavid Howells 		return inode;
45421d1fe1eeSDavid Howells 
45431d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
45447dc57615SPeter Huewe 	iloc.bh = NULL;
4545ac27a0ecSDave Kleikamp 
45461d1fe1eeSDavid Howells 	ret = __ext4_get_inode_loc(inode, &iloc, 0);
45471d1fe1eeSDavid Howells 	if (ret < 0)
4548ac27a0ecSDave Kleikamp 		goto bad_inode;
4549617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
4550814525f4SDarrick J. Wong 
45518e4b5eaeSTheodore Ts'o 	if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
45528a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
45538a363970STheodore Ts'o 				 "iget: root inode unallocated");
45548e4b5eaeSTheodore Ts'o 		ret = -EFSCORRUPTED;
45558e4b5eaeSTheodore Ts'o 		goto bad_inode;
45568e4b5eaeSTheodore Ts'o 	}
45578e4b5eaeSTheodore Ts'o 
45588a363970STheodore Ts'o 	if ((flags & EXT4_IGET_HANDLE) &&
45598a363970STheodore Ts'o 	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
45608a363970STheodore Ts'o 		ret = -ESTALE;
45618a363970STheodore Ts'o 		goto bad_inode;
45628a363970STheodore Ts'o 	}
45638a363970STheodore Ts'o 
4564814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4565814525f4SDarrick J. Wong 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4566814525f4SDarrick J. Wong 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
45672dc8d9e1SEric Biggers 			EXT4_INODE_SIZE(inode->i_sb) ||
45682dc8d9e1SEric Biggers 		    (ei->i_extra_isize & 3)) {
45698a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
45708a363970STheodore Ts'o 					 "iget: bad extra_isize %u "
45718a363970STheodore Ts'o 					 "(inode size %u)",
45722dc8d9e1SEric Biggers 					 ei->i_extra_isize,
4573814525f4SDarrick J. Wong 					 EXT4_INODE_SIZE(inode->i_sb));
45746a797d27SDarrick J. Wong 			ret = -EFSCORRUPTED;
4575814525f4SDarrick J. Wong 			goto bad_inode;
4576814525f4SDarrick J. Wong 		}
4577814525f4SDarrick J. Wong 	} else
4578814525f4SDarrick J. Wong 		ei->i_extra_isize = 0;
4579814525f4SDarrick J. Wong 
4580814525f4SDarrick J. Wong 	/* Precompute checksum seed for inode metadata */
45819aa5d32bSDmitry Monakhov 	if (ext4_has_metadata_csum(sb)) {
4582814525f4SDarrick J. Wong 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4583814525f4SDarrick J. Wong 		__u32 csum;
4584814525f4SDarrick J. Wong 		__le32 inum = cpu_to_le32(inode->i_ino);
4585814525f4SDarrick J. Wong 		__le32 gen = raw_inode->i_generation;
4586814525f4SDarrick J. Wong 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4587814525f4SDarrick J. Wong 				   sizeof(inum));
4588814525f4SDarrick J. Wong 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4589814525f4SDarrick J. Wong 					      sizeof(gen));
4590814525f4SDarrick J. Wong 	}
4591814525f4SDarrick J. Wong 
459246f870d6STheodore Ts'o 	if (!ext4_inode_csum_verify(inode, raw_inode, ei) ||
459346f870d6STheodore Ts'o 	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) {
459454d3adbcSTheodore Ts'o 		ext4_error_inode_err(inode, function, line, 0, EFSBADCRC,
45958a363970STheodore Ts'o 				     "iget: checksum invalid");
45966a797d27SDarrick J. Wong 		ret = -EFSBADCRC;
4597814525f4SDarrick J. Wong 		goto bad_inode;
4598814525f4SDarrick J. Wong 	}
4599814525f4SDarrick J. Wong 
4600ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
460108cefc7aSEric W. Biederman 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
460208cefc7aSEric W. Biederman 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
46030b7b7779SKaho Ng 	if (ext4_has_feature_project(sb) &&
4604040cb378SLi Xi 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4605040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4606040cb378SLi Xi 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4607040cb378SLi Xi 	else
4608040cb378SLi Xi 		i_projid = EXT4_DEF_PROJID;
4609040cb378SLi Xi 
4610ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
461108cefc7aSEric W. Biederman 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
461208cefc7aSEric W. Biederman 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4613ac27a0ecSDave Kleikamp 	}
461408cefc7aSEric W. Biederman 	i_uid_write(inode, i_uid);
461508cefc7aSEric W. Biederman 	i_gid_write(inode, i_gid);
4616040cb378SLi Xi 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4617bfe86848SMiklos Szeredi 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4618ac27a0ecSDave Kleikamp 
4619353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
462067cf5b09STao Ma 	ei->i_inline_off = 0;
4621ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
4622ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4623ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
4624ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
4625ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
4626ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
4627ac27a0ecSDave Kleikamp 	 */
4628ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
4629393d1d1dSDr. Tilmann Bubeck 		if ((inode->i_mode == 0 ||
4630393d1d1dSDr. Tilmann Bubeck 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4631393d1d1dSDr. Tilmann Bubeck 		    ino != EXT4_BOOT_LOADER_INO) {
4632ac27a0ecSDave Kleikamp 			/* this inode is deleted */
46331d1fe1eeSDavid Howells 			ret = -ESTALE;
4634ac27a0ecSDave Kleikamp 			goto bad_inode;
4635ac27a0ecSDave Kleikamp 		}
4636ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
4637ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
4638ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
4639393d1d1dSDr. Tilmann Bubeck 		 * the process of deleting those.
4640393d1d1dSDr. Tilmann Bubeck 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4641393d1d1dSDr. Tilmann Bubeck 		 * not initialized on a new filesystem. */
4642ac27a0ecSDave Kleikamp 	}
4643ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4644cce6c9f7SToshi Kani 	ext4_set_inode_flags(inode);
46450fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
46467973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4647e2b911c5SDarrick J. Wong 	if (ext4_has_feature_64bit(sb))
4648a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
4649a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4650e08ac99fSArtem Blagodarenko 	inode->i_size = ext4_isize(sb, raw_inode);
46517e6e1ef4SDarrick J. Wong 	if ((size = i_size_read(inode)) < 0) {
46528a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
46538a363970STheodore Ts'o 				 "iget: bad i_size value: %lld", size);
46547e6e1ef4SDarrick J. Wong 		ret = -EFSCORRUPTED;
46557e6e1ef4SDarrick J. Wong 		goto bad_inode;
46567e6e1ef4SDarrick J. Wong 	}
465748a34311SJan Kara 	/*
465848a34311SJan Kara 	 * If dir_index is not enabled but there's dir with INDEX flag set,
465948a34311SJan Kara 	 * we'd normally treat htree data as empty space. But with metadata
466048a34311SJan Kara 	 * checksumming that corrupts checksums so forbid that.
466148a34311SJan Kara 	 */
466248a34311SJan Kara 	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
466348a34311SJan Kara 	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
466448a34311SJan Kara 		ext4_error_inode(inode, function, line, 0,
466548a34311SJan Kara 			 "iget: Dir with htree data on filesystem without dir_index feature.");
466648a34311SJan Kara 		ret = -EFSCORRUPTED;
466748a34311SJan Kara 		goto bad_inode;
466848a34311SJan Kara 	}
4669ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
4670a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
4671a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
4672a9e7f447SDmitry Monakhov #endif
4673ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4674ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
4675a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
4676ac27a0ecSDave Kleikamp 	/*
4677ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
4678ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4679ac27a0ecSDave Kleikamp 	 */
4680617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4681ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
4682ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
4683ac27a0ecSDave Kleikamp 
4684b436b9beSJan Kara 	/*
4685b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
4686b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
4687b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
4688b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
4689b436b9beSJan Kara 	 * now it is reread from disk.
4690b436b9beSJan Kara 	 */
4691b436b9beSJan Kara 	if (journal) {
4692b436b9beSJan Kara 		transaction_t *transaction;
4693b436b9beSJan Kara 		tid_t tid;
4694b436b9beSJan Kara 
4695a931da6aSTheodore Ts'o 		read_lock(&journal->j_state_lock);
4696b436b9beSJan Kara 		if (journal->j_running_transaction)
4697b436b9beSJan Kara 			transaction = journal->j_running_transaction;
4698b436b9beSJan Kara 		else
4699b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
4700b436b9beSJan Kara 		if (transaction)
4701b436b9beSJan Kara 			tid = transaction->t_tid;
4702b436b9beSJan Kara 		else
4703b436b9beSJan Kara 			tid = journal->j_commit_sequence;
4704a931da6aSTheodore Ts'o 		read_unlock(&journal->j_state_lock);
4705b436b9beSJan Kara 		ei->i_sync_tid = tid;
4706b436b9beSJan Kara 		ei->i_datasync_tid = tid;
4707b436b9beSJan Kara 	}
4708b436b9beSJan Kara 
47090040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4710ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
4711ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
47122dc8d9e1SEric Biggers 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4713617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4714617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
4715ac27a0ecSDave Kleikamp 		} else {
4716eb9b5f01STheodore Ts'o 			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4717eb9b5f01STheodore Ts'o 			if (ret)
4718eb9b5f01STheodore Ts'o 				goto bad_inode;
4719ac27a0ecSDave Kleikamp 		}
4720814525f4SDarrick J. Wong 	}
4721ac27a0ecSDave Kleikamp 
4722ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4723ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4724ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4725ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4726ef7f3835SKalpak Shah 
4727ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4728ee73f9a5SJeff Layton 		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4729ee73f9a5SJeff Layton 
473025ec56b5SJean Noel Cordenner 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
473125ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4732ee73f9a5SJeff Layton 				ivers |=
473325ec56b5SJean Noel Cordenner 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
473425ec56b5SJean Noel Cordenner 		}
4735e254d1afSEryu Guan 		ext4_inode_set_iversion_queried(inode, ivers);
4736c4f65706STheodore Ts'o 	}
473725ec56b5SJean Noel Cordenner 
4738c4b5a614STheodore Ts'o 	ret = 0;
4739485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
47401032988cSTheodore Ts'o 	    !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
47418a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
47428a363970STheodore Ts'o 				 "iget: bad extended attribute block %llu",
474324676da4STheodore Ts'o 				 ei->i_file_acl);
47446a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
4745485c26ecSTheodore Ts'o 		goto bad_inode;
4746f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
4747bc716523SLiu Song 		/* validate the block references in the inode */
4748bc716523SLiu Song 		if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4749fe2c8191SThiemo Nagel 		   (S_ISLNK(inode->i_mode) &&
4750fe2c8191SThiemo Nagel 		    !ext4_inode_is_fast_symlink(inode))) {
4751bc716523SLiu Song 			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4752bc716523SLiu Song 				ret = ext4_ext_check_inode(inode);
4753bc716523SLiu Song 			else
47541f7d1e77STheodore Ts'o 				ret = ext4_ind_check_inode(inode);
4755fe2c8191SThiemo Nagel 		}
4756f19d5870STao Ma 	}
4757567f3e9aSTheodore Ts'o 	if (ret)
47587a262f7cSAneesh Kumar K.V 		goto bad_inode;
47597a262f7cSAneesh Kumar K.V 
4760ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
4761617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
4762617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
4763617ba13bSMingming Cao 		ext4_set_aops(inode);
4764ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
4765617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
4766617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
4767ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
47686390d33bSLuis R. Rodriguez 		/* VFS does not allow setting these so must be corruption */
47696390d33bSLuis R. Rodriguez 		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
47708a363970STheodore Ts'o 			ext4_error_inode(inode, function, line, 0,
47718a363970STheodore Ts'o 					 "iget: immutable or append flags "
47728a363970STheodore Ts'o 					 "not allowed on symlinks");
47736390d33bSLuis R. Rodriguez 			ret = -EFSCORRUPTED;
47746390d33bSLuis R. Rodriguez 			goto bad_inode;
47756390d33bSLuis R. Rodriguez 		}
4776592ddec7SChandan Rajendra 		if (IS_ENCRYPTED(inode)) {
4777a7a67e8aSAl Viro 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
4778a7a67e8aSAl Viro 			ext4_set_aops(inode);
4779a7a67e8aSAl Viro 		} else if (ext4_inode_is_fast_symlink(inode)) {
478075e7566bSAl Viro 			inode->i_link = (char *)ei->i_data;
4781617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
4782e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
4783e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
4784e83c1397SDuane Griffin 		} else {
4785617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
4786617ba13bSMingming Cao 			ext4_set_aops(inode);
4787ac27a0ecSDave Kleikamp 		}
478821fc61c7SAl Viro 		inode_nohighmem(inode);
4789563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4790563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4791617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
4792ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
4793ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
4794ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4795ac27a0ecSDave Kleikamp 		else
4796ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
4797ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4798393d1d1dSDr. Tilmann Bubeck 	} else if (ino == EXT4_BOOT_LOADER_INO) {
4799393d1d1dSDr. Tilmann Bubeck 		make_bad_inode(inode);
4800563bdd61STheodore Ts'o 	} else {
48016a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
48028a363970STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
48038a363970STheodore Ts'o 				 "iget: bogus i_mode (%o)", inode->i_mode);
4804563bdd61STheodore Ts'o 		goto bad_inode;
4805ac27a0ecSDave Kleikamp 	}
48066456ca65STheodore Ts'o 	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
48076456ca65STheodore Ts'o 		ext4_error_inode(inode, function, line, 0,
48086456ca65STheodore Ts'o 				 "casefold flag without casefold feature");
4809ac27a0ecSDave Kleikamp 	brelse(iloc.bh);
4810dec214d0STahsin Erdogan 
48111d1fe1eeSDavid Howells 	unlock_new_inode(inode);
48121d1fe1eeSDavid Howells 	return inode;
4813ac27a0ecSDave Kleikamp 
4814ac27a0ecSDave Kleikamp bad_inode:
4815567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
48161d1fe1eeSDavid Howells 	iget_failed(inode);
48171d1fe1eeSDavid Howells 	return ERR_PTR(ret);
4818ac27a0ecSDave Kleikamp }
4819ac27a0ecSDave Kleikamp 
48200fc1b451SAneesh Kumar K.V static int ext4_inode_blocks_set(handle_t *handle,
48210fc1b451SAneesh Kumar K.V 				struct ext4_inode *raw_inode,
48220fc1b451SAneesh Kumar K.V 				struct ext4_inode_info *ei)
48230fc1b451SAneesh Kumar K.V {
48240fc1b451SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
482528936b62SQian Cai 	u64 i_blocks = READ_ONCE(inode->i_blocks);
48260fc1b451SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
48270fc1b451SAneesh Kumar K.V 
48280fc1b451SAneesh Kumar K.V 	if (i_blocks <= ~0U) {
48290fc1b451SAneesh Kumar K.V 		/*
48304907cb7bSAnatol Pomozov 		 * i_blocks can be represented in a 32 bit variable
48310fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
48320fc1b451SAneesh Kumar K.V 		 */
48338180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
48340fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = 0;
483584a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4836f287a1a5STheodore Ts'o 		return 0;
4837f287a1a5STheodore Ts'o 	}
4838e2b911c5SDarrick J. Wong 	if (!ext4_has_feature_huge_file(sb))
4839f287a1a5STheodore Ts'o 		return -EFBIG;
4840f287a1a5STheodore Ts'o 
4841f287a1a5STheodore Ts'o 	if (i_blocks <= 0xffffffffffffULL) {
48420fc1b451SAneesh Kumar K.V 		/*
48430fc1b451SAneesh Kumar K.V 		 * i_blocks can be represented in a 48 bit variable
48440fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
48450fc1b451SAneesh Kumar K.V 		 */
48468180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
48470fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
484884a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
48490fc1b451SAneesh Kumar K.V 	} else {
485084a8dce2SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
48518180a562SAneesh Kumar K.V 		/* i_block is stored in file system block size */
48528180a562SAneesh Kumar K.V 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
48538180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
48548180a562SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
48550fc1b451SAneesh Kumar K.V 	}
4856f287a1a5STheodore Ts'o 	return 0;
48570fc1b451SAneesh Kumar K.V }
48580fc1b451SAneesh Kumar K.V 
4859a26f4992STheodore Ts'o struct other_inode {
4860a26f4992STheodore Ts'o 	unsigned long		orig_ino;
4861a26f4992STheodore Ts'o 	struct ext4_inode	*raw_inode;
4862a26f4992STheodore Ts'o };
4863a26f4992STheodore Ts'o 
4864a26f4992STheodore Ts'o static int other_inode_match(struct inode * inode, unsigned long ino,
4865a26f4992STheodore Ts'o 			     void *data)
4866a26f4992STheodore Ts'o {
4867a26f4992STheodore Ts'o 	struct other_inode *oi = (struct other_inode *) data;
4868a26f4992STheodore Ts'o 
4869a26f4992STheodore Ts'o 	if ((inode->i_ino != ino) ||
4870a26f4992STheodore Ts'o 	    (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
48710e11f644SChristoph Hellwig 			       I_DIRTY_INODE)) ||
4872a26f4992STheodore Ts'o 	    ((inode->i_state & I_DIRTY_TIME) == 0))
4873a26f4992STheodore Ts'o 		return 0;
4874a26f4992STheodore Ts'o 	spin_lock(&inode->i_lock);
4875a26f4992STheodore Ts'o 	if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
48760e11f644SChristoph Hellwig 				I_DIRTY_INODE)) == 0) &&
4877a26f4992STheodore Ts'o 	    (inode->i_state & I_DIRTY_TIME)) {
4878a26f4992STheodore Ts'o 		struct ext4_inode_info	*ei = EXT4_I(inode);
4879a26f4992STheodore Ts'o 
4880a26f4992STheodore Ts'o 		inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED);
4881a26f4992STheodore Ts'o 		spin_unlock(&inode->i_lock);
4882a26f4992STheodore Ts'o 
4883a26f4992STheodore Ts'o 		spin_lock(&ei->i_raw_lock);
4884a26f4992STheodore Ts'o 		EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
4885a26f4992STheodore Ts'o 		EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
4886a26f4992STheodore Ts'o 		EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
4887a26f4992STheodore Ts'o 		ext4_inode_csum_set(inode, oi->raw_inode, ei);
4888a26f4992STheodore Ts'o 		spin_unlock(&ei->i_raw_lock);
4889a26f4992STheodore Ts'o 		trace_ext4_other_inode_update_time(inode, oi->orig_ino);
4890a26f4992STheodore Ts'o 		return -1;
4891a26f4992STheodore Ts'o 	}
4892a26f4992STheodore Ts'o 	spin_unlock(&inode->i_lock);
4893a26f4992STheodore Ts'o 	return -1;
4894a26f4992STheodore Ts'o }
4895a26f4992STheodore Ts'o 
4896a26f4992STheodore Ts'o /*
4897a26f4992STheodore Ts'o  * Opportunistically update the other time fields for other inodes in
4898a26f4992STheodore Ts'o  * the same inode table block.
4899a26f4992STheodore Ts'o  */
4900a26f4992STheodore Ts'o static void ext4_update_other_inodes_time(struct super_block *sb,
4901a26f4992STheodore Ts'o 					  unsigned long orig_ino, char *buf)
4902a26f4992STheodore Ts'o {
4903a26f4992STheodore Ts'o 	struct other_inode oi;
4904a26f4992STheodore Ts'o 	unsigned long ino;
4905a26f4992STheodore Ts'o 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4906a26f4992STheodore Ts'o 	int inode_size = EXT4_INODE_SIZE(sb);
4907a26f4992STheodore Ts'o 
4908a26f4992STheodore Ts'o 	oi.orig_ino = orig_ino;
49090f0ff9a9STheodore Ts'o 	/*
49100f0ff9a9STheodore Ts'o 	 * Calculate the first inode in the inode table block.  Inode
49110f0ff9a9STheodore Ts'o 	 * numbers are one-based.  That is, the first inode in a block
49120f0ff9a9STheodore Ts'o 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
49130f0ff9a9STheodore Ts'o 	 */
49140f0ff9a9STheodore Ts'o 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
4915a26f4992STheodore Ts'o 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
4916a26f4992STheodore Ts'o 		if (ino == orig_ino)
4917a26f4992STheodore Ts'o 			continue;
4918a26f4992STheodore Ts'o 		oi.raw_inode = (struct ext4_inode *) buf;
4919a26f4992STheodore Ts'o 		(void) find_inode_nowait(sb, ino, other_inode_match, &oi);
4920a26f4992STheodore Ts'o 	}
4921a26f4992STheodore Ts'o }
4922a26f4992STheodore Ts'o 
4923ac27a0ecSDave Kleikamp /*
4924ac27a0ecSDave Kleikamp  * Post the struct inode info into an on-disk inode location in the
4925ac27a0ecSDave Kleikamp  * buffer-cache.  This gobbles the caller's reference to the
4926ac27a0ecSDave Kleikamp  * buffer_head in the inode location struct.
4927ac27a0ecSDave Kleikamp  *
4928ac27a0ecSDave Kleikamp  * The caller must have write access to iloc->bh.
4929ac27a0ecSDave Kleikamp  */
4930617ba13bSMingming Cao static int ext4_do_update_inode(handle_t *handle,
4931ac27a0ecSDave Kleikamp 				struct inode *inode,
4932830156c7SFrank Mayhar 				struct ext4_iloc *iloc)
4933ac27a0ecSDave Kleikamp {
4934617ba13bSMingming Cao 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4935617ba13bSMingming Cao 	struct ext4_inode_info *ei = EXT4_I(inode);
4936ac27a0ecSDave Kleikamp 	struct buffer_head *bh = iloc->bh;
4937202ee5dfSTheodore Ts'o 	struct super_block *sb = inode->i_sb;
4938ac27a0ecSDave Kleikamp 	int err = 0, rc, block;
4939202ee5dfSTheodore Ts'o 	int need_datasync = 0, set_large_file = 0;
494008cefc7aSEric W. Biederman 	uid_t i_uid;
494108cefc7aSEric W. Biederman 	gid_t i_gid;
4942040cb378SLi Xi 	projid_t i_projid;
4943ac27a0ecSDave Kleikamp 
4944202ee5dfSTheodore Ts'o 	spin_lock(&ei->i_raw_lock);
4945202ee5dfSTheodore Ts'o 
4946202ee5dfSTheodore Ts'o 	/* For fields not tracked in the in-memory inode,
4947ac27a0ecSDave Kleikamp 	 * initialise them to zero for new inodes. */
494819f5fb7aSTheodore Ts'o 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4949617ba13bSMingming Cao 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4950ac27a0ecSDave Kleikamp 
4951ac27a0ecSDave Kleikamp 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
495208cefc7aSEric W. Biederman 	i_uid = i_uid_read(inode);
495308cefc7aSEric W. Biederman 	i_gid = i_gid_read(inode);
4954040cb378SLi Xi 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
4955ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
495608cefc7aSEric W. Biederman 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
495708cefc7aSEric W. Biederman 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4958ac27a0ecSDave Kleikamp /*
4959ac27a0ecSDave Kleikamp  * Fix up interoperability with old kernels. Otherwise, old inodes get
4960ac27a0ecSDave Kleikamp  * re-used with the upper 16 bits of the uid/gid intact
4961ac27a0ecSDave Kleikamp  */
496293e3b4e6SDaeho Jeong 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
496393e3b4e6SDaeho Jeong 			raw_inode->i_uid_high = 0;
496493e3b4e6SDaeho Jeong 			raw_inode->i_gid_high = 0;
496593e3b4e6SDaeho Jeong 		} else {
4966ac27a0ecSDave Kleikamp 			raw_inode->i_uid_high =
496708cefc7aSEric W. Biederman 				cpu_to_le16(high_16_bits(i_uid));
4968ac27a0ecSDave Kleikamp 			raw_inode->i_gid_high =
496908cefc7aSEric W. Biederman 				cpu_to_le16(high_16_bits(i_gid));
4970ac27a0ecSDave Kleikamp 		}
4971ac27a0ecSDave Kleikamp 	} else {
497208cefc7aSEric W. Biederman 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
497308cefc7aSEric W. Biederman 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4974ac27a0ecSDave Kleikamp 		raw_inode->i_uid_high = 0;
4975ac27a0ecSDave Kleikamp 		raw_inode->i_gid_high = 0;
4976ac27a0ecSDave Kleikamp 	}
4977ac27a0ecSDave Kleikamp 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4978ef7f3835SKalpak Shah 
4979ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4980ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4981ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4982ef7f3835SKalpak Shah 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4983ef7f3835SKalpak Shah 
4984bce92d56SLi Xi 	err = ext4_inode_blocks_set(handle, raw_inode, ei);
4985bce92d56SLi Xi 	if (err) {
4986202ee5dfSTheodore Ts'o 		spin_unlock(&ei->i_raw_lock);
49870fc1b451SAneesh Kumar K.V 		goto out_brelse;
4988202ee5dfSTheodore Ts'o 	}
4989ac27a0ecSDave Kleikamp 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4990353eb83cSTheodore Ts'o 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4991ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4992a1ddeb7eSBadari Pulavarty 		raw_inode->i_file_acl_high =
4993a1ddeb7eSBadari Pulavarty 			cpu_to_le16(ei->i_file_acl >> 32);
49947973c0c1SAneesh Kumar K.V 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4995dce8e237SQiujun Huang 	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) {
4996a48380f7SAneesh Kumar K.V 		ext4_isize_set(raw_inode, ei->i_disksize);
4997b71fc079SJan Kara 		need_datasync = 1;
4998b71fc079SJan Kara 	}
4999ac27a0ecSDave Kleikamp 	if (ei->i_disksize > 0x7fffffffULL) {
5000e2b911c5SDarrick J. Wong 		if (!ext4_has_feature_large_file(sb) ||
5001617ba13bSMingming Cao 				EXT4_SB(sb)->s_es->s_rev_level ==
5002202ee5dfSTheodore Ts'o 		    cpu_to_le32(EXT4_GOOD_OLD_REV))
5003202ee5dfSTheodore Ts'o 			set_large_file = 1;
5004ac27a0ecSDave Kleikamp 	}
5005ac27a0ecSDave Kleikamp 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5006ac27a0ecSDave Kleikamp 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5007ac27a0ecSDave Kleikamp 		if (old_valid_dev(inode->i_rdev)) {
5008ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] =
5009ac27a0ecSDave Kleikamp 				cpu_to_le32(old_encode_dev(inode->i_rdev));
5010ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] = 0;
5011ac27a0ecSDave Kleikamp 		} else {
5012ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] = 0;
5013ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] =
5014ac27a0ecSDave Kleikamp 				cpu_to_le32(new_encode_dev(inode->i_rdev));
5015ac27a0ecSDave Kleikamp 			raw_inode->i_block[2] = 0;
5016ac27a0ecSDave Kleikamp 		}
5017f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
5018de9a55b8STheodore Ts'o 		for (block = 0; block < EXT4_N_BLOCKS; block++)
5019ac27a0ecSDave Kleikamp 			raw_inode->i_block[block] = ei->i_data[block];
5020f19d5870STao Ma 	}
5021ac27a0ecSDave Kleikamp 
5022ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5023e254d1afSEryu Guan 		u64 ivers = ext4_inode_peek_iversion(inode);
5024ee73f9a5SJeff Layton 
5025ee73f9a5SJeff Layton 		raw_inode->i_disk_version = cpu_to_le32(ivers);
502625ec56b5SJean Noel Cordenner 		if (ei->i_extra_isize) {
502725ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
502825ec56b5SJean Noel Cordenner 				raw_inode->i_version_hi =
5029ee73f9a5SJeff Layton 					cpu_to_le32(ivers >> 32);
5030c4f65706STheodore Ts'o 			raw_inode->i_extra_isize =
5031c4f65706STheodore Ts'o 				cpu_to_le16(ei->i_extra_isize);
5032c4f65706STheodore Ts'o 		}
503325ec56b5SJean Noel Cordenner 	}
5034040cb378SLi Xi 
50350b7b7779SKaho Ng 	BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
5036040cb378SLi Xi 	       i_projid != EXT4_DEF_PROJID);
5037040cb378SLi Xi 
5038040cb378SLi Xi 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5039040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5040040cb378SLi Xi 		raw_inode->i_projid = cpu_to_le32(i_projid);
5041040cb378SLi Xi 
5042814525f4SDarrick J. Wong 	ext4_inode_csum_set(inode, raw_inode, ei);
5043202ee5dfSTheodore Ts'o 	spin_unlock(&ei->i_raw_lock);
50441751e8a6SLinus Torvalds 	if (inode->i_sb->s_flags & SB_LAZYTIME)
5045a26f4992STheodore Ts'o 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5046a26f4992STheodore Ts'o 					      bh->b_data);
5047202ee5dfSTheodore Ts'o 
50480390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
504973b50c1cSCurt Wohlgemuth 	rc = ext4_handle_dirty_metadata(handle, NULL, bh);
5050ac27a0ecSDave Kleikamp 	if (!err)
5051ac27a0ecSDave Kleikamp 		err = rc;
505219f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5053202ee5dfSTheodore Ts'o 	if (set_large_file) {
50545d601255Sliang xie 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5055202ee5dfSTheodore Ts'o 		err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5056202ee5dfSTheodore Ts'o 		if (err)
5057202ee5dfSTheodore Ts'o 			goto out_brelse;
5058e2b911c5SDarrick J. Wong 		ext4_set_feature_large_file(sb);
5059202ee5dfSTheodore Ts'o 		ext4_handle_sync(handle);
5060202ee5dfSTheodore Ts'o 		err = ext4_handle_dirty_super(handle, sb);
5061202ee5dfSTheodore Ts'o 	}
5062b71fc079SJan Kara 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5063ac27a0ecSDave Kleikamp out_brelse:
5064ac27a0ecSDave Kleikamp 	brelse(bh);
5065617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5066ac27a0ecSDave Kleikamp 	return err;
5067ac27a0ecSDave Kleikamp }
5068ac27a0ecSDave Kleikamp 
5069ac27a0ecSDave Kleikamp /*
5070617ba13bSMingming Cao  * ext4_write_inode()
5071ac27a0ecSDave Kleikamp  *
5072ac27a0ecSDave Kleikamp  * We are called from a few places:
5073ac27a0ecSDave Kleikamp  *
507487f7e416STheodore Ts'o  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5075ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
50764907cb7bSAnatol Pomozov  *   transaction to commit.
5077ac27a0ecSDave Kleikamp  *
507887f7e416STheodore Ts'o  * - Within flush work (sys_sync(), kupdate and such).
507987f7e416STheodore Ts'o  *   We wait on commit, if told to.
5080ac27a0ecSDave Kleikamp  *
508187f7e416STheodore Ts'o  * - Within iput_final() -> write_inode_now()
508287f7e416STheodore Ts'o  *   We wait on commit, if told to.
5083ac27a0ecSDave Kleikamp  *
5084ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
5085ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
508687f7e416STheodore Ts'o  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
508787f7e416STheodore Ts'o  * writeback.
5088ac27a0ecSDave Kleikamp  *
5089ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
5090ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5091ac27a0ecSDave Kleikamp  * which we are interested.
5092ac27a0ecSDave Kleikamp  *
5093ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
5094ac27a0ecSDave Kleikamp  *
5095ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
5096ac27a0ecSDave Kleikamp  *	stuff();
5097ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
5098ac27a0ecSDave Kleikamp  *
509987f7e416STheodore Ts'o  * is in error because write_inode() could occur while `stuff()' is running,
510087f7e416STheodore Ts'o  * and the new i_size will be lost.  Plus the inode will no longer be on the
510187f7e416STheodore Ts'o  * superblock's dirty inode list.
5102ac27a0ecSDave Kleikamp  */
5103a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5104ac27a0ecSDave Kleikamp {
510591ac6f43SFrank Mayhar 	int err;
510691ac6f43SFrank Mayhar 
510718f2c4fcSTheodore Ts'o 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
510818f2c4fcSTheodore Ts'o 	    sb_rdonly(inode->i_sb))
5109ac27a0ecSDave Kleikamp 		return 0;
5110ac27a0ecSDave Kleikamp 
511118f2c4fcSTheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
511218f2c4fcSTheodore Ts'o 		return -EIO;
511318f2c4fcSTheodore Ts'o 
511491ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
5115617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
5116b38bd33aSMingming Cao 			jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5117ac27a0ecSDave Kleikamp 			dump_stack();
5118ac27a0ecSDave Kleikamp 			return -EIO;
5119ac27a0ecSDave Kleikamp 		}
5120ac27a0ecSDave Kleikamp 
512110542c22SJan Kara 		/*
512210542c22SJan Kara 		 * No need to force transaction in WB_SYNC_NONE mode. Also
512310542c22SJan Kara 		 * ext4_sync_fs() will force the commit after everything is
512410542c22SJan Kara 		 * written.
512510542c22SJan Kara 		 */
512610542c22SJan Kara 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5127ac27a0ecSDave Kleikamp 			return 0;
5128ac27a0ecSDave Kleikamp 
512918f2c4fcSTheodore Ts'o 		err = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
513018f2c4fcSTheodore Ts'o 						EXT4_I(inode)->i_sync_tid);
513191ac6f43SFrank Mayhar 	} else {
513291ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
513391ac6f43SFrank Mayhar 
51348b472d73SCurt Wohlgemuth 		err = __ext4_get_inode_loc(inode, &iloc, 0);
513591ac6f43SFrank Mayhar 		if (err)
513691ac6f43SFrank Mayhar 			return err;
513710542c22SJan Kara 		/*
513810542c22SJan Kara 		 * sync(2) will flush the whole buffer cache. No need to do
513910542c22SJan Kara 		 * it here separately for each inode.
514010542c22SJan Kara 		 */
514110542c22SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5142830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
5143830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
514454d3adbcSTheodore Ts'o 			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5145c398eda0STheodore Ts'o 					       "IO error syncing inode");
5146830156c7SFrank Mayhar 			err = -EIO;
5147830156c7SFrank Mayhar 		}
5148fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
514991ac6f43SFrank Mayhar 	}
515091ac6f43SFrank Mayhar 	return err;
5151ac27a0ecSDave Kleikamp }
5152ac27a0ecSDave Kleikamp 
5153ac27a0ecSDave Kleikamp /*
515453e87268SJan Kara  * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
515553e87268SJan Kara  * buffers that are attached to a page stradding i_size and are undergoing
515653e87268SJan Kara  * commit. In that case we have to wait for commit to finish and try again.
515753e87268SJan Kara  */
515853e87268SJan Kara static void ext4_wait_for_tail_page_commit(struct inode *inode)
515953e87268SJan Kara {
516053e87268SJan Kara 	struct page *page;
516153e87268SJan Kara 	unsigned offset;
516253e87268SJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
516353e87268SJan Kara 	tid_t commit_tid = 0;
516453e87268SJan Kara 	int ret;
516553e87268SJan Kara 
516609cbfeafSKirill A. Shutemov 	offset = inode->i_size & (PAGE_SIZE - 1);
516753e87268SJan Kara 	/*
5168565333a1Syangerkun 	 * If the page is fully truncated, we don't need to wait for any commit
5169565333a1Syangerkun 	 * (and we even should not as __ext4_journalled_invalidatepage() may
5170565333a1Syangerkun 	 * strip all buffers from the page but keep the page dirty which can then
5171565333a1Syangerkun 	 * confuse e.g. concurrent ext4_writepage() seeing dirty page without
5172565333a1Syangerkun 	 * buffers). Also we don't need to wait for any commit if all buffers in
5173565333a1Syangerkun 	 * the page remain valid. This is most beneficial for the common case of
5174565333a1Syangerkun 	 * blocksize == PAGESIZE.
517553e87268SJan Kara 	 */
5176565333a1Syangerkun 	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
517753e87268SJan Kara 		return;
517853e87268SJan Kara 	while (1) {
517953e87268SJan Kara 		page = find_lock_page(inode->i_mapping,
518009cbfeafSKirill A. Shutemov 				      inode->i_size >> PAGE_SHIFT);
518153e87268SJan Kara 		if (!page)
518253e87268SJan Kara 			return;
5183ca99fdd2SLukas Czerner 		ret = __ext4_journalled_invalidatepage(page, offset,
518409cbfeafSKirill A. Shutemov 						PAGE_SIZE - offset);
518553e87268SJan Kara 		unlock_page(page);
518609cbfeafSKirill A. Shutemov 		put_page(page);
518753e87268SJan Kara 		if (ret != -EBUSY)
518853e87268SJan Kara 			return;
518953e87268SJan Kara 		commit_tid = 0;
519053e87268SJan Kara 		read_lock(&journal->j_state_lock);
519153e87268SJan Kara 		if (journal->j_committing_transaction)
519253e87268SJan Kara 			commit_tid = journal->j_committing_transaction->t_tid;
519353e87268SJan Kara 		read_unlock(&journal->j_state_lock);
519453e87268SJan Kara 		if (commit_tid)
519553e87268SJan Kara 			jbd2_log_wait_commit(journal, commit_tid);
519653e87268SJan Kara 	}
519753e87268SJan Kara }
519853e87268SJan Kara 
519953e87268SJan Kara /*
5200617ba13bSMingming Cao  * ext4_setattr()
5201ac27a0ecSDave Kleikamp  *
5202ac27a0ecSDave Kleikamp  * Called from notify_change.
5203ac27a0ecSDave Kleikamp  *
5204ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
5205ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
5206ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
5207ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
5208ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
5209ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
5210ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
5211ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
5212ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
5213ac27a0ecSDave Kleikamp  *
5214678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
5215678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
5216678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
5217678aaf48SJan Kara  * This way we are sure that all the data written in the previous
5218678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
5219678aaf48SJan Kara  * writeback).
5220678aaf48SJan Kara  *
5221678aaf48SJan Kara  * Called with inode->i_mutex down.
5222ac27a0ecSDave Kleikamp  */
5223617ba13bSMingming Cao int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5224ac27a0ecSDave Kleikamp {
52252b0143b5SDavid Howells 	struct inode *inode = d_inode(dentry);
5226ac27a0ecSDave Kleikamp 	int error, rc = 0;
52273d287de3SDmitry Monakhov 	int orphan = 0;
5228ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
5229ac27a0ecSDave Kleikamp 
52300db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
52310db1ff22STheodore Ts'o 		return -EIO;
52320db1ff22STheodore Ts'o 
523302b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
523402b016caSTheodore Ts'o 		return -EPERM;
523502b016caSTheodore Ts'o 
523602b016caSTheodore Ts'o 	if (unlikely(IS_APPEND(inode) &&
523702b016caSTheodore Ts'o 		     (ia_valid & (ATTR_MODE | ATTR_UID |
523802b016caSTheodore Ts'o 				  ATTR_GID | ATTR_TIMES_SET))))
523902b016caSTheodore Ts'o 		return -EPERM;
524002b016caSTheodore Ts'o 
524131051c85SJan Kara 	error = setattr_prepare(dentry, attr);
5242ac27a0ecSDave Kleikamp 	if (error)
5243ac27a0ecSDave Kleikamp 		return error;
5244ac27a0ecSDave Kleikamp 
52453ce2b8ddSEric Biggers 	error = fscrypt_prepare_setattr(dentry, attr);
52463ce2b8ddSEric Biggers 	if (error)
52473ce2b8ddSEric Biggers 		return error;
52483ce2b8ddSEric Biggers 
5249c93d8f88SEric Biggers 	error = fsverity_prepare_setattr(dentry, attr);
5250c93d8f88SEric Biggers 	if (error)
5251c93d8f88SEric Biggers 		return error;
5252c93d8f88SEric Biggers 
5253a7cdadeeSJan Kara 	if (is_quota_modification(inode, attr)) {
5254a7cdadeeSJan Kara 		error = dquot_initialize(inode);
5255a7cdadeeSJan Kara 		if (error)
5256a7cdadeeSJan Kara 			return error;
5257a7cdadeeSJan Kara 	}
525808cefc7aSEric W. Biederman 	if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
525908cefc7aSEric W. Biederman 	    (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5260ac27a0ecSDave Kleikamp 		handle_t *handle;
5261ac27a0ecSDave Kleikamp 
5262ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
5263ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
52649924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
52659924a92aSTheodore Ts'o 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5266194074acSDmitry Monakhov 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5267ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
5268ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
5269ac27a0ecSDave Kleikamp 			goto err_out;
5270ac27a0ecSDave Kleikamp 		}
52717a9ca53aSTahsin Erdogan 
52727a9ca53aSTahsin Erdogan 		/* dquot_transfer() calls back ext4_get_inode_usage() which
52737a9ca53aSTahsin Erdogan 		 * counts xattr inode references.
52747a9ca53aSTahsin Erdogan 		 */
52757a9ca53aSTahsin Erdogan 		down_read(&EXT4_I(inode)->xattr_sem);
5276b43fa828SChristoph Hellwig 		error = dquot_transfer(inode, attr);
52777a9ca53aSTahsin Erdogan 		up_read(&EXT4_I(inode)->xattr_sem);
52787a9ca53aSTahsin Erdogan 
5279ac27a0ecSDave Kleikamp 		if (error) {
5280617ba13bSMingming Cao 			ext4_journal_stop(handle);
5281ac27a0ecSDave Kleikamp 			return error;
5282ac27a0ecSDave Kleikamp 		}
5283ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
5284ac27a0ecSDave Kleikamp 		 * one transaction */
5285ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_UID)
5286ac27a0ecSDave Kleikamp 			inode->i_uid = attr->ia_uid;
5287ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_GID)
5288ac27a0ecSDave Kleikamp 			inode->i_gid = attr->ia_gid;
5289617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
5290617ba13bSMingming Cao 		ext4_journal_stop(handle);
5291ac27a0ecSDave Kleikamp 	}
5292ac27a0ecSDave Kleikamp 
52933da40c7bSJosef Bacik 	if (attr->ia_valid & ATTR_SIZE) {
52945208386cSJan Kara 		handle_t *handle;
52953da40c7bSJosef Bacik 		loff_t oldsize = inode->i_size;
5296b9c1c267SJan Kara 		int shrink = (attr->ia_size < inode->i_size);
5297562c72aaSChristoph Hellwig 
529812e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5299e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5300e2b46574SEric Sandeen 
53010c095c7fSTheodore Ts'o 			if (attr->ia_size > sbi->s_bitmap_maxbytes)
53020c095c7fSTheodore Ts'o 				return -EFBIG;
5303e2b46574SEric Sandeen 		}
53043da40c7bSJosef Bacik 		if (!S_ISREG(inode->i_mode))
53053da40c7bSJosef Bacik 			return -EINVAL;
5306dff6efc3SChristoph Hellwig 
5307dff6efc3SChristoph Hellwig 		if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5308dff6efc3SChristoph Hellwig 			inode_inc_iversion(inode);
5309dff6efc3SChristoph Hellwig 
5310b9c1c267SJan Kara 		if (shrink) {
5311b9c1c267SJan Kara 			if (ext4_should_order_data(inode)) {
53125208386cSJan Kara 				error = ext4_begin_ordered_truncate(inode,
53135208386cSJan Kara 							    attr->ia_size);
53145208386cSJan Kara 				if (error)
53155208386cSJan Kara 					goto err_out;
53165208386cSJan Kara 			}
5317b9c1c267SJan Kara 			/*
5318b9c1c267SJan Kara 			 * Blocks are going to be removed from the inode. Wait
5319b9c1c267SJan Kara 			 * for dio in flight.
5320b9c1c267SJan Kara 			 */
5321b9c1c267SJan Kara 			inode_dio_wait(inode);
5322b9c1c267SJan Kara 		}
5323b9c1c267SJan Kara 
5324b9c1c267SJan Kara 		down_write(&EXT4_I(inode)->i_mmap_sem);
5325b9c1c267SJan Kara 
5326b9c1c267SJan Kara 		rc = ext4_break_layouts(inode);
5327b9c1c267SJan Kara 		if (rc) {
5328b9c1c267SJan Kara 			up_write(&EXT4_I(inode)->i_mmap_sem);
5329b9c1c267SJan Kara 			return rc;
5330b9c1c267SJan Kara 		}
5331b9c1c267SJan Kara 
53323da40c7bSJosef Bacik 		if (attr->ia_size != inode->i_size) {
53339924a92aSTheodore Ts'o 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5334ac27a0ecSDave Kleikamp 			if (IS_ERR(handle)) {
5335ac27a0ecSDave Kleikamp 				error = PTR_ERR(handle);
5336b9c1c267SJan Kara 				goto out_mmap_sem;
5337ac27a0ecSDave Kleikamp 			}
53383da40c7bSJosef Bacik 			if (ext4_handle_valid(handle) && shrink) {
5339617ba13bSMingming Cao 				error = ext4_orphan_add(handle, inode);
53403d287de3SDmitry Monakhov 				orphan = 1;
53413d287de3SDmitry Monakhov 			}
5342911af577SEryu Guan 			/*
5343911af577SEryu Guan 			 * Update c/mtime on truncate up, ext4_truncate() will
5344911af577SEryu Guan 			 * update c/mtime in shrink case below
5345911af577SEryu Guan 			 */
5346911af577SEryu Guan 			if (!shrink) {
5347eeca7ea1SDeepa Dinamani 				inode->i_mtime = current_time(inode);
5348911af577SEryu Guan 				inode->i_ctime = inode->i_mtime;
5349911af577SEryu Guan 			}
535090e775b7SJan Kara 			down_write(&EXT4_I(inode)->i_data_sem);
5351617ba13bSMingming Cao 			EXT4_I(inode)->i_disksize = attr->ia_size;
5352617ba13bSMingming Cao 			rc = ext4_mark_inode_dirty(handle, inode);
5353ac27a0ecSDave Kleikamp 			if (!error)
5354ac27a0ecSDave Kleikamp 				error = rc;
535590e775b7SJan Kara 			/*
535690e775b7SJan Kara 			 * We have to update i_size under i_data_sem together
535790e775b7SJan Kara 			 * with i_disksize to avoid races with writeback code
535890e775b7SJan Kara 			 * running ext4_wb_update_i_disksize().
535990e775b7SJan Kara 			 */
536090e775b7SJan Kara 			if (!error)
536190e775b7SJan Kara 				i_size_write(inode, attr->ia_size);
536290e775b7SJan Kara 			up_write(&EXT4_I(inode)->i_data_sem);
5363617ba13bSMingming Cao 			ext4_journal_stop(handle);
5364b9c1c267SJan Kara 			if (error)
5365b9c1c267SJan Kara 				goto out_mmap_sem;
536682a25b02SJan Kara 			if (!shrink) {
5367b9c1c267SJan Kara 				pagecache_isize_extended(inode, oldsize,
5368b9c1c267SJan Kara 							 inode->i_size);
5369b9c1c267SJan Kara 			} else if (ext4_should_journal_data(inode)) {
537082a25b02SJan Kara 				ext4_wait_for_tail_page_commit(inode);
5371b9c1c267SJan Kara 			}
5372430657b6SRoss Zwisler 		}
5373430657b6SRoss Zwisler 
537453e87268SJan Kara 		/*
537553e87268SJan Kara 		 * Truncate pagecache after we've waited for commit
537653e87268SJan Kara 		 * in data=journal mode to make pages freeable.
537753e87268SJan Kara 		 */
53787caef267SKirill A. Shutemov 		truncate_pagecache(inode, inode->i_size);
5379b9c1c267SJan Kara 		/*
5380b9c1c267SJan Kara 		 * Call ext4_truncate() even if i_size didn't change to
5381b9c1c267SJan Kara 		 * truncate possible preallocated blocks.
5382b9c1c267SJan Kara 		 */
5383b9c1c267SJan Kara 		if (attr->ia_size <= oldsize) {
53842c98eb5eSTheodore Ts'o 			rc = ext4_truncate(inode);
53852c98eb5eSTheodore Ts'o 			if (rc)
53862c98eb5eSTheodore Ts'o 				error = rc;
53872c98eb5eSTheodore Ts'o 		}
5388b9c1c267SJan Kara out_mmap_sem:
5389ea3d7209SJan Kara 		up_write(&EXT4_I(inode)->i_mmap_sem);
53903da40c7bSJosef Bacik 	}
5391ac27a0ecSDave Kleikamp 
53922c98eb5eSTheodore Ts'o 	if (!error) {
53931025774cSChristoph Hellwig 		setattr_copy(inode, attr);
53941025774cSChristoph Hellwig 		mark_inode_dirty(inode);
53951025774cSChristoph Hellwig 	}
53961025774cSChristoph Hellwig 
53971025774cSChristoph Hellwig 	/*
53981025774cSChristoph Hellwig 	 * If the call to ext4_truncate failed to get a transaction handle at
53991025774cSChristoph Hellwig 	 * all, we need to clean up the in-core orphan list manually.
54001025774cSChristoph Hellwig 	 */
54013d287de3SDmitry Monakhov 	if (orphan && inode->i_nlink)
5402617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
5403ac27a0ecSDave Kleikamp 
54042c98eb5eSTheodore Ts'o 	if (!error && (ia_valid & ATTR_MODE))
540564e178a7SChristoph Hellwig 		rc = posix_acl_chmod(inode, inode->i_mode);
5406ac27a0ecSDave Kleikamp 
5407ac27a0ecSDave Kleikamp err_out:
5408617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, error);
5409ac27a0ecSDave Kleikamp 	if (!error)
5410ac27a0ecSDave Kleikamp 		error = rc;
5411ac27a0ecSDave Kleikamp 	return error;
5412ac27a0ecSDave Kleikamp }
5413ac27a0ecSDave Kleikamp 
5414a528d35eSDavid Howells int ext4_getattr(const struct path *path, struct kstat *stat,
5415a528d35eSDavid Howells 		 u32 request_mask, unsigned int query_flags)
54163e3398a0SMingming Cao {
541799652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
541899652ea5SDavid Howells 	struct ext4_inode *raw_inode;
541999652ea5SDavid Howells 	struct ext4_inode_info *ei = EXT4_I(inode);
542099652ea5SDavid Howells 	unsigned int flags;
54213e3398a0SMingming Cao 
5422d4c5e960STheodore Ts'o 	if ((request_mask & STATX_BTIME) &&
5423d4c5e960STheodore Ts'o 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
542499652ea5SDavid Howells 		stat->result_mask |= STATX_BTIME;
542599652ea5SDavid Howells 		stat->btime.tv_sec = ei->i_crtime.tv_sec;
542699652ea5SDavid Howells 		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
542799652ea5SDavid Howells 	}
542899652ea5SDavid Howells 
542999652ea5SDavid Howells 	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
543099652ea5SDavid Howells 	if (flags & EXT4_APPEND_FL)
543199652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_APPEND;
543299652ea5SDavid Howells 	if (flags & EXT4_COMPR_FL)
543399652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_COMPRESSED;
543499652ea5SDavid Howells 	if (flags & EXT4_ENCRYPT_FL)
543599652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_ENCRYPTED;
543699652ea5SDavid Howells 	if (flags & EXT4_IMMUTABLE_FL)
543799652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_IMMUTABLE;
543899652ea5SDavid Howells 	if (flags & EXT4_NODUMP_FL)
543999652ea5SDavid Howells 		stat->attributes |= STATX_ATTR_NODUMP;
54401f607195SEric Biggers 	if (flags & EXT4_VERITY_FL)
54411f607195SEric Biggers 		stat->attributes |= STATX_ATTR_VERITY;
544299652ea5SDavid Howells 
54433209f68bSDavid Howells 	stat->attributes_mask |= (STATX_ATTR_APPEND |
54443209f68bSDavid Howells 				  STATX_ATTR_COMPRESSED |
54453209f68bSDavid Howells 				  STATX_ATTR_ENCRYPTED |
54463209f68bSDavid Howells 				  STATX_ATTR_IMMUTABLE |
54471f607195SEric Biggers 				  STATX_ATTR_NODUMP |
54481f607195SEric Biggers 				  STATX_ATTR_VERITY);
54493209f68bSDavid Howells 
54503e3398a0SMingming Cao 	generic_fillattr(inode, stat);
545199652ea5SDavid Howells 	return 0;
545299652ea5SDavid Howells }
545399652ea5SDavid Howells 
545499652ea5SDavid Howells int ext4_file_getattr(const struct path *path, struct kstat *stat,
545599652ea5SDavid Howells 		      u32 request_mask, unsigned int query_flags)
545699652ea5SDavid Howells {
545799652ea5SDavid Howells 	struct inode *inode = d_inode(path->dentry);
545899652ea5SDavid Howells 	u64 delalloc_blocks;
545999652ea5SDavid Howells 
546099652ea5SDavid Howells 	ext4_getattr(path, stat, request_mask, query_flags);
54613e3398a0SMingming Cao 
54623e3398a0SMingming Cao 	/*
54639206c561SAndreas Dilger 	 * If there is inline data in the inode, the inode will normally not
54649206c561SAndreas Dilger 	 * have data blocks allocated (it may have an external xattr block).
54659206c561SAndreas Dilger 	 * Report at least one sector for such files, so tools like tar, rsync,
5466d67d64f4STheodore Ts'o 	 * others don't incorrectly think the file is completely sparse.
54679206c561SAndreas Dilger 	 */
54689206c561SAndreas Dilger 	if (unlikely(ext4_has_inline_data(inode)))
54699206c561SAndreas Dilger 		stat->blocks += (stat->size + 511) >> 9;
54709206c561SAndreas Dilger 
54719206c561SAndreas Dilger 	/*
54723e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
54733e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
54743e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
54753e3398a0SMingming Cao 	 * on-disk file blocks.
54763e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
54773e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
54783e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
54793e3398a0SMingming Cao 	 * blocks for this file.
54803e3398a0SMingming Cao 	 */
548196607551STao Ma 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
548296607551STao Ma 				   EXT4_I(inode)->i_reserved_data_blocks);
54838af8eeccSJan Kara 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
54843e3398a0SMingming Cao 	return 0;
54853e3398a0SMingming Cao }
5486ac27a0ecSDave Kleikamp 
5487fffb2739SJan Kara static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5488fffb2739SJan Kara 				   int pextents)
5489a02908f1SMingming Cao {
549012e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5491fffb2739SJan Kara 		return ext4_ind_trans_blocks(inode, lblocks);
5492fffb2739SJan Kara 	return ext4_ext_index_trans_blocks(inode, pextents);
5493a02908f1SMingming Cao }
5494ac51d837STheodore Ts'o 
5495a02908f1SMingming Cao /*
5496a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
5497a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
5498a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
5499a02908f1SMingming Cao  *
5500a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
55014907cb7bSAnatol Pomozov  * different block groups too. If they are contiguous, with flexbg,
5502a02908f1SMingming Cao  * they could still across block group boundary.
5503a02908f1SMingming Cao  *
5504a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
5505a02908f1SMingming Cao  */
5506dec214d0STahsin Erdogan static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5507fffb2739SJan Kara 				  int pextents)
5508a02908f1SMingming Cao {
55098df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
55108df9675fSTheodore Ts'o 	int gdpblocks;
5511a02908f1SMingming Cao 	int idxblocks;
5512a02908f1SMingming Cao 	int ret = 0;
5513a02908f1SMingming Cao 
5514a02908f1SMingming Cao 	/*
5515fffb2739SJan Kara 	 * How many index blocks need to touch to map @lblocks logical blocks
5516fffb2739SJan Kara 	 * to @pextents physical extents?
5517a02908f1SMingming Cao 	 */
5518fffb2739SJan Kara 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5519a02908f1SMingming Cao 
5520a02908f1SMingming Cao 	ret = idxblocks;
5521a02908f1SMingming Cao 
5522a02908f1SMingming Cao 	/*
5523a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
5524a02908f1SMingming Cao 	 * to account
5525a02908f1SMingming Cao 	 */
5526fffb2739SJan Kara 	groups = idxblocks + pextents;
5527a02908f1SMingming Cao 	gdpblocks = groups;
55288df9675fSTheodore Ts'o 	if (groups > ngroups)
55298df9675fSTheodore Ts'o 		groups = ngroups;
5530a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5531a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5532a02908f1SMingming Cao 
5533a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
5534a02908f1SMingming Cao 	ret += groups + gdpblocks;
5535a02908f1SMingming Cao 
5536a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
5537a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5538ac27a0ecSDave Kleikamp 
5539ac27a0ecSDave Kleikamp 	return ret;
5540ac27a0ecSDave Kleikamp }
5541ac27a0ecSDave Kleikamp 
5542ac27a0ecSDave Kleikamp /*
554325985edcSLucas De Marchi  * Calculate the total number of credits to reserve to fit
5544f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
5545f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
5546a02908f1SMingming Cao  *
5547525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
5548a02908f1SMingming Cao  *
5549525f4ed8SMingming Cao  * We need to consider the worse case, when
5550a02908f1SMingming Cao  * one new block per extent.
5551a02908f1SMingming Cao  */
5552a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
5553a02908f1SMingming Cao {
5554a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
5555a02908f1SMingming Cao 	int ret;
5556a02908f1SMingming Cao 
5557fffb2739SJan Kara 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5558a02908f1SMingming Cao 
5559a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
5560a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
5561a02908f1SMingming Cao 		ret += bpp;
5562a02908f1SMingming Cao 	return ret;
5563a02908f1SMingming Cao }
5564f3bd1f3fSMingming Cao 
5565f3bd1f3fSMingming Cao /*
5566f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
5567f3bd1f3fSMingming Cao  *
5568f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
556979e83036SEric Sandeen  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5570f3bd1f3fSMingming Cao  *
5571f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
5572f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
5573f3bd1f3fSMingming Cao  */
5574f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5575f3bd1f3fSMingming Cao {
5576f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5577f3bd1f3fSMingming Cao }
5578f3bd1f3fSMingming Cao 
5579a02908f1SMingming Cao /*
5580617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
5581ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
5582ac27a0ecSDave Kleikamp  */
5583617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
5584617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
5585ac27a0ecSDave Kleikamp {
5586ac27a0ecSDave Kleikamp 	int err = 0;
5587ac27a0ecSDave Kleikamp 
5588a6758309SVasily Averin 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5589a6758309SVasily Averin 		put_bh(iloc->bh);
55900db1ff22STheodore Ts'o 		return -EIO;
5591a6758309SVasily Averin 	}
5592c64db50eSTheodore Ts'o 	if (IS_I_VERSION(inode))
559325ec56b5SJean Noel Cordenner 		inode_inc_iversion(inode);
559425ec56b5SJean Noel Cordenner 
5595ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
5596ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
5597ac27a0ecSDave Kleikamp 
5598dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5599830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
5600ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
5601ac27a0ecSDave Kleikamp 	return err;
5602ac27a0ecSDave Kleikamp }
5603ac27a0ecSDave Kleikamp 
5604ac27a0ecSDave Kleikamp /*
5605ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
5606ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
5607ac27a0ecSDave Kleikamp  */
5608ac27a0ecSDave Kleikamp 
5609ac27a0ecSDave Kleikamp int
5610617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5611617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
5612ac27a0ecSDave Kleikamp {
56130390131bSFrank Mayhar 	int err;
56140390131bSFrank Mayhar 
56150db1ff22STheodore Ts'o 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
56160db1ff22STheodore Ts'o 		return -EIO;
56170db1ff22STheodore Ts'o 
5618617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
5619ac27a0ecSDave Kleikamp 	if (!err) {
5620ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
5621617ba13bSMingming Cao 		err = ext4_journal_get_write_access(handle, iloc->bh);
5622ac27a0ecSDave Kleikamp 		if (err) {
5623ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
5624ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
5625ac27a0ecSDave Kleikamp 		}
5626ac27a0ecSDave Kleikamp 	}
5627617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5628ac27a0ecSDave Kleikamp 	return err;
5629ac27a0ecSDave Kleikamp }
5630ac27a0ecSDave Kleikamp 
5631c03b45b8SMiao Xie static int __ext4_expand_extra_isize(struct inode *inode,
5632c03b45b8SMiao Xie 				     unsigned int new_extra_isize,
5633c03b45b8SMiao Xie 				     struct ext4_iloc *iloc,
5634c03b45b8SMiao Xie 				     handle_t *handle, int *no_expand)
5635c03b45b8SMiao Xie {
5636c03b45b8SMiao Xie 	struct ext4_inode *raw_inode;
5637c03b45b8SMiao Xie 	struct ext4_xattr_ibody_header *header;
56384ea99936STheodore Ts'o 	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
56394ea99936STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
5640c03b45b8SMiao Xie 	int error;
5641c03b45b8SMiao Xie 
56424ea99936STheodore Ts'o 	/* this was checked at iget time, but double check for good measure */
56434ea99936STheodore Ts'o 	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
56444ea99936STheodore Ts'o 	    (ei->i_extra_isize & 3)) {
56454ea99936STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
56464ea99936STheodore Ts'o 				 ei->i_extra_isize,
56474ea99936STheodore Ts'o 				 EXT4_INODE_SIZE(inode->i_sb));
56484ea99936STheodore Ts'o 		return -EFSCORRUPTED;
56494ea99936STheodore Ts'o 	}
56504ea99936STheodore Ts'o 	if ((new_extra_isize < ei->i_extra_isize) ||
56514ea99936STheodore Ts'o 	    (new_extra_isize < 4) ||
56524ea99936STheodore Ts'o 	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
56534ea99936STheodore Ts'o 		return -EINVAL;	/* Should never happen */
56544ea99936STheodore Ts'o 
5655c03b45b8SMiao Xie 	raw_inode = ext4_raw_inode(iloc);
5656c03b45b8SMiao Xie 
5657c03b45b8SMiao Xie 	header = IHDR(inode, raw_inode);
5658c03b45b8SMiao Xie 
5659c03b45b8SMiao Xie 	/* No extended attributes present */
5660c03b45b8SMiao Xie 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5661c03b45b8SMiao Xie 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5662c03b45b8SMiao Xie 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5663c03b45b8SMiao Xie 		       EXT4_I(inode)->i_extra_isize, 0,
5664c03b45b8SMiao Xie 		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
5665c03b45b8SMiao Xie 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
5666c03b45b8SMiao Xie 		return 0;
5667c03b45b8SMiao Xie 	}
5668c03b45b8SMiao Xie 
5669c03b45b8SMiao Xie 	/* try to expand with EAs present */
5670c03b45b8SMiao Xie 	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5671c03b45b8SMiao Xie 					   raw_inode, handle);
5672c03b45b8SMiao Xie 	if (error) {
5673c03b45b8SMiao Xie 		/*
5674c03b45b8SMiao Xie 		 * Inode size expansion failed; don't try again
5675c03b45b8SMiao Xie 		 */
5676c03b45b8SMiao Xie 		*no_expand = 1;
5677c03b45b8SMiao Xie 	}
5678c03b45b8SMiao Xie 
5679c03b45b8SMiao Xie 	return error;
5680c03b45b8SMiao Xie }
5681c03b45b8SMiao Xie 
5682ac27a0ecSDave Kleikamp /*
56836dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
56846dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
56856dd4ee7cSKalpak Shah  */
5686cf0a5e81SMiao Xie static int ext4_try_to_expand_extra_isize(struct inode *inode,
56871d03ec98SAneesh Kumar K.V 					  unsigned int new_extra_isize,
56881d03ec98SAneesh Kumar K.V 					  struct ext4_iloc iloc,
56891d03ec98SAneesh Kumar K.V 					  handle_t *handle)
56906dd4ee7cSKalpak Shah {
56913b10fdc6SMiao Xie 	int no_expand;
56923b10fdc6SMiao Xie 	int error;
56936dd4ee7cSKalpak Shah 
5694cf0a5e81SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5695cf0a5e81SMiao Xie 		return -EOVERFLOW;
5696cf0a5e81SMiao Xie 
5697cf0a5e81SMiao Xie 	/*
5698cf0a5e81SMiao Xie 	 * In nojournal mode, we can immediately attempt to expand
5699cf0a5e81SMiao Xie 	 * the inode.  When journaled, we first need to obtain extra
5700cf0a5e81SMiao Xie 	 * buffer credits since we may write into the EA block
5701cf0a5e81SMiao Xie 	 * with this same handle. If journal_extend fails, then it will
5702cf0a5e81SMiao Xie 	 * only result in a minor loss of functionality for that inode.
5703cf0a5e81SMiao Xie 	 * If this is felt to be critical, then e2fsck should be run to
5704cf0a5e81SMiao Xie 	 * force a large enough s_min_extra_isize.
5705cf0a5e81SMiao Xie 	 */
57066cb367c2SJan Kara 	if (ext4_journal_extend(handle,
570783448bdfSJan Kara 				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5708cf0a5e81SMiao Xie 		return -ENOSPC;
57096dd4ee7cSKalpak Shah 
57103b10fdc6SMiao Xie 	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5711cf0a5e81SMiao Xie 		return -EBUSY;
57123b10fdc6SMiao Xie 
5713c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5714c03b45b8SMiao Xie 					  handle, &no_expand);
57153b10fdc6SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5716c03b45b8SMiao Xie 
5717c03b45b8SMiao Xie 	return error;
57186dd4ee7cSKalpak Shah }
57196dd4ee7cSKalpak Shah 
5720c03b45b8SMiao Xie int ext4_expand_extra_isize(struct inode *inode,
5721c03b45b8SMiao Xie 			    unsigned int new_extra_isize,
5722c03b45b8SMiao Xie 			    struct ext4_iloc *iloc)
5723c03b45b8SMiao Xie {
5724c03b45b8SMiao Xie 	handle_t *handle;
5725c03b45b8SMiao Xie 	int no_expand;
5726c03b45b8SMiao Xie 	int error, rc;
5727c03b45b8SMiao Xie 
5728c03b45b8SMiao Xie 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5729c03b45b8SMiao Xie 		brelse(iloc->bh);
5730c03b45b8SMiao Xie 		return -EOVERFLOW;
5731c03b45b8SMiao Xie 	}
5732c03b45b8SMiao Xie 
5733c03b45b8SMiao Xie 	handle = ext4_journal_start(inode, EXT4_HT_INODE,
5734c03b45b8SMiao Xie 				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5735c03b45b8SMiao Xie 	if (IS_ERR(handle)) {
5736c03b45b8SMiao Xie 		error = PTR_ERR(handle);
5737c03b45b8SMiao Xie 		brelse(iloc->bh);
5738c03b45b8SMiao Xie 		return error;
5739c03b45b8SMiao Xie 	}
5740c03b45b8SMiao Xie 
5741c03b45b8SMiao Xie 	ext4_write_lock_xattr(inode, &no_expand);
5742c03b45b8SMiao Xie 
5743ddccb6dbSzhangyi (F) 	BUFFER_TRACE(iloc->bh, "get_write_access");
5744c03b45b8SMiao Xie 	error = ext4_journal_get_write_access(handle, iloc->bh);
57453b10fdc6SMiao Xie 	if (error) {
5746c03b45b8SMiao Xie 		brelse(iloc->bh);
57477f420d64SDan Carpenter 		goto out_unlock;
57483b10fdc6SMiao Xie 	}
5749cf0a5e81SMiao Xie 
5750c03b45b8SMiao Xie 	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5751c03b45b8SMiao Xie 					  handle, &no_expand);
5752c03b45b8SMiao Xie 
5753c03b45b8SMiao Xie 	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5754c03b45b8SMiao Xie 	if (!error)
5755c03b45b8SMiao Xie 		error = rc;
5756c03b45b8SMiao Xie 
57577f420d64SDan Carpenter out_unlock:
5758c03b45b8SMiao Xie 	ext4_write_unlock_xattr(inode, &no_expand);
5759c03b45b8SMiao Xie 	ext4_journal_stop(handle);
57603b10fdc6SMiao Xie 	return error;
57616dd4ee7cSKalpak Shah }
57626dd4ee7cSKalpak Shah 
57636dd4ee7cSKalpak Shah /*
5764ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
5765ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
5766ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
5767ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
5768ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
5769ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
5770ac27a0ecSDave Kleikamp  *
5771ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
5772ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
5773ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5774ac27a0ecSDave Kleikamp  * we start and wait on commits.
5775ac27a0ecSDave Kleikamp  */
5776617ba13bSMingming Cao int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5777ac27a0ecSDave Kleikamp {
5778617ba13bSMingming Cao 	struct ext4_iloc iloc;
57796dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5780cf0a5e81SMiao Xie 	int err;
5781ac27a0ecSDave Kleikamp 
5782ac27a0ecSDave Kleikamp 	might_sleep();
57837ff9c073STheodore Ts'o 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5784617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
57855e1021f2SEryu Guan 	if (err)
57865e1021f2SEryu Guan 		return err;
5787cf0a5e81SMiao Xie 
5788cf0a5e81SMiao Xie 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5789cf0a5e81SMiao Xie 		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
57906dd4ee7cSKalpak Shah 					       iloc, handle);
5791cf0a5e81SMiao Xie 
57925e1021f2SEryu Guan 	return ext4_mark_iloc_dirty(handle, inode, &iloc);
5793ac27a0ecSDave Kleikamp }
5794ac27a0ecSDave Kleikamp 
5795ac27a0ecSDave Kleikamp /*
5796617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
5797ac27a0ecSDave Kleikamp  *
5798ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
5799ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
5800ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
5801ac27a0ecSDave Kleikamp  *
58025dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
5803ac27a0ecSDave Kleikamp  * are allocated to the file.
5804ac27a0ecSDave Kleikamp  *
5805ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
5806ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
5807ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
58080ae45f63STheodore Ts'o  *
58090ae45f63STheodore Ts'o  * If only the I_DIRTY_TIME flag is set, we can skip everything.  If
58100ae45f63STheodore Ts'o  * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
58110ae45f63STheodore Ts'o  * to copy into the on-disk inode structure are the timestamp files.
5812ac27a0ecSDave Kleikamp  */
5813aa385729SChristoph Hellwig void ext4_dirty_inode(struct inode *inode, int flags)
5814ac27a0ecSDave Kleikamp {
5815ac27a0ecSDave Kleikamp 	handle_t *handle;
5816ac27a0ecSDave Kleikamp 
58170ae45f63STheodore Ts'o 	if (flags == I_DIRTY_TIME)
58180ae45f63STheodore Ts'o 		return;
58199924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5820ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5821ac27a0ecSDave Kleikamp 		goto out;
5822f3dc272fSCurt Wohlgemuth 
5823617ba13bSMingming Cao 	ext4_mark_inode_dirty(handle, inode);
5824f3dc272fSCurt Wohlgemuth 
5825617ba13bSMingming Cao 	ext4_journal_stop(handle);
5826ac27a0ecSDave Kleikamp out:
5827ac27a0ecSDave Kleikamp 	return;
5828ac27a0ecSDave Kleikamp }
5829ac27a0ecSDave Kleikamp 
5830617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
5831ac27a0ecSDave Kleikamp {
5832ac27a0ecSDave Kleikamp 	journal_t *journal;
5833ac27a0ecSDave Kleikamp 	handle_t *handle;
5834ac27a0ecSDave Kleikamp 	int err;
5835c8585c6fSDaeho Jeong 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5836ac27a0ecSDave Kleikamp 
5837ac27a0ecSDave Kleikamp 	/*
5838ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
5839ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
5840ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
5841ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
5842ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
5843ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
5844ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
5845ac27a0ecSDave Kleikamp 	 */
5846ac27a0ecSDave Kleikamp 
5847617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
58480390131bSFrank Mayhar 	if (!journal)
58490390131bSFrank Mayhar 		return 0;
5850d699594dSDave Hansen 	if (is_journal_aborted(journal))
5851ac27a0ecSDave Kleikamp 		return -EROFS;
5852ac27a0ecSDave Kleikamp 
585317335dccSDmitry Monakhov 	/* Wait for all existing dio workers */
585417335dccSDmitry Monakhov 	inode_dio_wait(inode);
585517335dccSDmitry Monakhov 
58564c546592SDaeho Jeong 	/*
58574c546592SDaeho Jeong 	 * Before flushing the journal and switching inode's aops, we have
58584c546592SDaeho Jeong 	 * to flush all dirty data the inode has. There can be outstanding
58594c546592SDaeho Jeong 	 * delayed allocations, there can be unwritten extents created by
58604c546592SDaeho Jeong 	 * fallocate or buffered writes in dioread_nolock mode covered by
58614c546592SDaeho Jeong 	 * dirty data which can be converted only after flushing the dirty
58624c546592SDaeho Jeong 	 * data (and journalled aops don't know how to handle these cases).
58634c546592SDaeho Jeong 	 */
58644c546592SDaeho Jeong 	if (val) {
58654c546592SDaeho Jeong 		down_write(&EXT4_I(inode)->i_mmap_sem);
58664c546592SDaeho Jeong 		err = filemap_write_and_wait(inode->i_mapping);
58674c546592SDaeho Jeong 		if (err < 0) {
58684c546592SDaeho Jeong 			up_write(&EXT4_I(inode)->i_mmap_sem);
58694c546592SDaeho Jeong 			return err;
58704c546592SDaeho Jeong 		}
58714c546592SDaeho Jeong 	}
58724c546592SDaeho Jeong 
5873bbd55937SEric Biggers 	percpu_down_write(&sbi->s_writepages_rwsem);
5874dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
5875ac27a0ecSDave Kleikamp 
5876ac27a0ecSDave Kleikamp 	/*
5877ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
5878ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
5879ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
5880ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
5881ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
5882ac27a0ecSDave Kleikamp 	 */
5883ac27a0ecSDave Kleikamp 
5884ac27a0ecSDave Kleikamp 	if (val)
588512e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
58865872ddaaSYongqiang Yang 	else {
58874f879ca6SJan Kara 		err = jbd2_journal_flush(journal);
58884f879ca6SJan Kara 		if (err < 0) {
58894f879ca6SJan Kara 			jbd2_journal_unlock_updates(journal);
5890bbd55937SEric Biggers 			percpu_up_write(&sbi->s_writepages_rwsem);
58914f879ca6SJan Kara 			return err;
58924f879ca6SJan Kara 		}
589312e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
58945872ddaaSYongqiang Yang 	}
5895617ba13bSMingming Cao 	ext4_set_aops(inode);
5896ac27a0ecSDave Kleikamp 
5897dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
5898bbd55937SEric Biggers 	percpu_up_write(&sbi->s_writepages_rwsem);
5899c8585c6fSDaeho Jeong 
59004c546592SDaeho Jeong 	if (val)
59014c546592SDaeho Jeong 		up_write(&EXT4_I(inode)->i_mmap_sem);
5902ac27a0ecSDave Kleikamp 
5903ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
5904ac27a0ecSDave Kleikamp 
59059924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5906ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5907ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
5908ac27a0ecSDave Kleikamp 
5909617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
59100390131bSFrank Mayhar 	ext4_handle_sync(handle);
5911617ba13bSMingming Cao 	ext4_journal_stop(handle);
5912617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5913ac27a0ecSDave Kleikamp 
5914ac27a0ecSDave Kleikamp 	return err;
5915ac27a0ecSDave Kleikamp }
59162e9ee850SAneesh Kumar K.V 
59172e9ee850SAneesh Kumar K.V static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
59182e9ee850SAneesh Kumar K.V {
59192e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
59202e9ee850SAneesh Kumar K.V }
59212e9ee850SAneesh Kumar K.V 
5922401b25aaSSouptick Joarder vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
59232e9ee850SAneesh Kumar K.V {
592411bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
5925c2ec175cSNick Piggin 	struct page *page = vmf->page;
59262e9ee850SAneesh Kumar K.V 	loff_t size;
59272e9ee850SAneesh Kumar K.V 	unsigned long len;
5928401b25aaSSouptick Joarder 	int err;
5929401b25aaSSouptick Joarder 	vm_fault_t ret;
59302e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
5931496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
59322e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
59339ea7df53SJan Kara 	handle_t *handle;
59349ea7df53SJan Kara 	get_block_t *get_block;
59359ea7df53SJan Kara 	int retries = 0;
59362e9ee850SAneesh Kumar K.V 
593702b016caSTheodore Ts'o 	if (unlikely(IS_IMMUTABLE(inode)))
593802b016caSTheodore Ts'o 		return VM_FAULT_SIGBUS;
593902b016caSTheodore Ts'o 
59408e8ad8a5SJan Kara 	sb_start_pagefault(inode->i_sb);
5941041bbb6dSTheodore Ts'o 	file_update_time(vma->vm_file);
5942ea3d7209SJan Kara 
5943ea3d7209SJan Kara 	down_read(&EXT4_I(inode)->i_mmap_sem);
59447b4cc978SEric Biggers 
5945401b25aaSSouptick Joarder 	err = ext4_convert_inline_data(inode);
5946401b25aaSSouptick Joarder 	if (err)
59477b4cc978SEric Biggers 		goto out_ret;
59487b4cc978SEric Biggers 
59499ea7df53SJan Kara 	/* Delalloc case is easy... */
59509ea7df53SJan Kara 	if (test_opt(inode->i_sb, DELALLOC) &&
59519ea7df53SJan Kara 	    !ext4_should_journal_data(inode) &&
59529ea7df53SJan Kara 	    !ext4_nonda_switch(inode->i_sb)) {
59539ea7df53SJan Kara 		do {
5954401b25aaSSouptick Joarder 			err = block_page_mkwrite(vma, vmf,
59559ea7df53SJan Kara 						   ext4_da_get_block_prep);
5956401b25aaSSouptick Joarder 		} while (err == -ENOSPC &&
59579ea7df53SJan Kara 		       ext4_should_retry_alloc(inode->i_sb, &retries));
59589ea7df53SJan Kara 		goto out_ret;
59592e9ee850SAneesh Kumar K.V 	}
59600e499890SDarrick J. Wong 
59610e499890SDarrick J. Wong 	lock_page(page);
59629ea7df53SJan Kara 	size = i_size_read(inode);
59639ea7df53SJan Kara 	/* Page got truncated from under us? */
59649ea7df53SJan Kara 	if (page->mapping != mapping || page_offset(page) > size) {
59659ea7df53SJan Kara 		unlock_page(page);
59669ea7df53SJan Kara 		ret = VM_FAULT_NOPAGE;
59679ea7df53SJan Kara 		goto out;
59680e499890SDarrick J. Wong 	}
59692e9ee850SAneesh Kumar K.V 
597009cbfeafSKirill A. Shutemov 	if (page->index == size >> PAGE_SHIFT)
597109cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
59722e9ee850SAneesh Kumar K.V 	else
597309cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
5974a827eaffSAneesh Kumar K.V 	/*
59759ea7df53SJan Kara 	 * Return if we have all the buffers mapped. This avoids the need to do
59769ea7df53SJan Kara 	 * journal_start/journal_stop which can block and take a long time
5977a827eaffSAneesh Kumar K.V 	 */
59782e9ee850SAneesh Kumar K.V 	if (page_has_buffers(page)) {
5979f19d5870STao Ma 		if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5980f19d5870STao Ma 					    0, len, NULL,
5981a827eaffSAneesh Kumar K.V 					    ext4_bh_unmapped)) {
59829ea7df53SJan Kara 			/* Wait so that we don't change page under IO */
59831d1d1a76SDarrick J. Wong 			wait_for_stable_page(page);
59849ea7df53SJan Kara 			ret = VM_FAULT_LOCKED;
59859ea7df53SJan Kara 			goto out;
59862e9ee850SAneesh Kumar K.V 		}
5987a827eaffSAneesh Kumar K.V 	}
5988a827eaffSAneesh Kumar K.V 	unlock_page(page);
59899ea7df53SJan Kara 	/* OK, we need to fill the hole... */
59909ea7df53SJan Kara 	if (ext4_should_dioread_nolock(inode))
5991705965bdSJan Kara 		get_block = ext4_get_block_unwritten;
59929ea7df53SJan Kara 	else
59939ea7df53SJan Kara 		get_block = ext4_get_block;
59949ea7df53SJan Kara retry_alloc:
59959924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
59969924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
59979ea7df53SJan Kara 	if (IS_ERR(handle)) {
5998c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
59999ea7df53SJan Kara 		goto out;
60009ea7df53SJan Kara 	}
6001401b25aaSSouptick Joarder 	err = block_page_mkwrite(vma, vmf, get_block);
6002401b25aaSSouptick Joarder 	if (!err && ext4_should_journal_data(inode)) {
6003f19d5870STao Ma 		if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
600409cbfeafSKirill A. Shutemov 			  PAGE_SIZE, NULL, do_journal_get_write_access)) {
60059ea7df53SJan Kara 			unlock_page(page);
60069ea7df53SJan Kara 			ret = VM_FAULT_SIGBUS;
6007fcbb5515SYongqiang Yang 			ext4_journal_stop(handle);
60089ea7df53SJan Kara 			goto out;
60099ea7df53SJan Kara 		}
60109ea7df53SJan Kara 		ext4_set_inode_state(inode, EXT4_STATE_JDATA);
60119ea7df53SJan Kara 	}
60129ea7df53SJan Kara 	ext4_journal_stop(handle);
6013401b25aaSSouptick Joarder 	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
60149ea7df53SJan Kara 		goto retry_alloc;
60159ea7df53SJan Kara out_ret:
6016401b25aaSSouptick Joarder 	ret = block_page_mkwrite_return(err);
60179ea7df53SJan Kara out:
6018ea3d7209SJan Kara 	up_read(&EXT4_I(inode)->i_mmap_sem);
60198e8ad8a5SJan Kara 	sb_end_pagefault(inode->i_sb);
60202e9ee850SAneesh Kumar K.V 	return ret;
60212e9ee850SAneesh Kumar K.V }
6022ea3d7209SJan Kara 
6023401b25aaSSouptick Joarder vm_fault_t ext4_filemap_fault(struct vm_fault *vmf)
6024ea3d7209SJan Kara {
602511bac800SDave Jiang 	struct inode *inode = file_inode(vmf->vma->vm_file);
6026401b25aaSSouptick Joarder 	vm_fault_t ret;
6027ea3d7209SJan Kara 
6028ea3d7209SJan Kara 	down_read(&EXT4_I(inode)->i_mmap_sem);
6029401b25aaSSouptick Joarder 	ret = filemap_fault(vmf);
6030ea3d7209SJan Kara 	up_read(&EXT4_I(inode)->i_mmap_sem);
6031ea3d7209SJan Kara 
6032401b25aaSSouptick Joarder 	return ret;
6033ea3d7209SJan Kara }
6034