xref: /openbmc/linux/fs/ext4/inode.c (revision 3b136499e906460919f0d21a49db1aaccf0ae963)
1ac27a0ecSDave Kleikamp /*
2617ba13bSMingming Cao  *  linux/fs/ext4/inode.c
3ac27a0ecSDave Kleikamp  *
4ac27a0ecSDave Kleikamp  * Copyright (C) 1992, 1993, 1994, 1995
5ac27a0ecSDave Kleikamp  * Remy Card (card@masi.ibp.fr)
6ac27a0ecSDave Kleikamp  * Laboratoire MASI - Institut Blaise Pascal
7ac27a0ecSDave Kleikamp  * Universite Pierre et Marie Curie (Paris VI)
8ac27a0ecSDave Kleikamp  *
9ac27a0ecSDave Kleikamp  *  from
10ac27a0ecSDave Kleikamp  *
11ac27a0ecSDave Kleikamp  *  linux/fs/minix/inode.c
12ac27a0ecSDave Kleikamp  *
13ac27a0ecSDave Kleikamp  *  Copyright (C) 1991, 1992  Linus Torvalds
14ac27a0ecSDave Kleikamp  *
15ac27a0ecSDave Kleikamp  *  64-bit file support on 64-bit platforms by Jakub Jelinek
16ac27a0ecSDave Kleikamp  *	(jj@sunsite.ms.mff.cuni.cz)
17ac27a0ecSDave Kleikamp  *
18617ba13bSMingming Cao  *  Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
19ac27a0ecSDave Kleikamp  */
20ac27a0ecSDave Kleikamp 
21ac27a0ecSDave Kleikamp #include <linux/fs.h>
22ac27a0ecSDave Kleikamp #include <linux/time.h>
23ac27a0ecSDave Kleikamp #include <linux/highuid.h>
24ac27a0ecSDave Kleikamp #include <linux/pagemap.h>
25c94c2acfSMatthew Wilcox #include <linux/dax.h>
26ac27a0ecSDave Kleikamp #include <linux/quotaops.h>
27ac27a0ecSDave Kleikamp #include <linux/string.h>
28ac27a0ecSDave Kleikamp #include <linux/buffer_head.h>
29ac27a0ecSDave Kleikamp #include <linux/writeback.h>
3064769240SAlex Tomas #include <linux/pagevec.h>
31ac27a0ecSDave Kleikamp #include <linux/mpage.h>
32e83c1397SDuane Griffin #include <linux/namei.h>
33ac27a0ecSDave Kleikamp #include <linux/uio.h>
34ac27a0ecSDave Kleikamp #include <linux/bio.h>
354c0425ffSMingming Cao #include <linux/workqueue.h>
36744692dcSJiaying Zhang #include <linux/kernel.h>
376db26ffcSAndrew Morton #include <linux/printk.h>
385a0e3ad6STejun Heo #include <linux/slab.h>
3900a1a053STheodore Ts'o #include <linux/bitops.h>
40364443cbSJan Kara #include <linux/iomap.h>
419bffad1eSTheodore Ts'o 
423dcf5451SChristoph Hellwig #include "ext4_jbd2.h"
43ac27a0ecSDave Kleikamp #include "xattr.h"
44ac27a0ecSDave Kleikamp #include "acl.h"
459f125d64STheodore Ts'o #include "truncate.h"
46ac27a0ecSDave Kleikamp 
479bffad1eSTheodore Ts'o #include <trace/events/ext4.h>
489bffad1eSTheodore Ts'o 
49a1d6cc56SAneesh Kumar K.V #define MPAGE_DA_EXTENT_TAIL 0x01
50a1d6cc56SAneesh Kumar K.V 
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);
142fffb2739SJan Kara static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
143fffb2739SJan Kara 				  int pextents);
14464769240SAlex Tomas 
145ac27a0ecSDave Kleikamp /*
146ac27a0ecSDave Kleikamp  * Test whether an inode is a fast symlink.
147ac27a0ecSDave Kleikamp  */
148f348c252STheodore Ts'o int ext4_inode_is_fast_symlink(struct inode *inode)
149ac27a0ecSDave Kleikamp {
150617ba13bSMingming Cao         int ea_blocks = EXT4_I(inode)->i_file_acl ?
15165eddb56SYongqiang Yang 		EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
152ac27a0ecSDave Kleikamp 
153bd9db175SZheng Liu 	if (ext4_has_inline_data(inode))
154bd9db175SZheng Liu 		return 0;
155bd9db175SZheng Liu 
156ac27a0ecSDave Kleikamp 	return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
157ac27a0ecSDave Kleikamp }
158ac27a0ecSDave Kleikamp 
159ac27a0ecSDave Kleikamp /*
160ac27a0ecSDave Kleikamp  * Restart the transaction associated with *handle.  This does a commit,
161ac27a0ecSDave Kleikamp  * so before we call here everything must be consistently dirtied against
162ac27a0ecSDave Kleikamp  * this transaction.
163ac27a0ecSDave Kleikamp  */
164487caeefSJan Kara int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
165487caeefSJan Kara 				 int nblocks)
166ac27a0ecSDave Kleikamp {
167487caeefSJan Kara 	int ret;
168487caeefSJan Kara 
169487caeefSJan Kara 	/*
170e35fd660STheodore Ts'o 	 * Drop i_data_sem to avoid deadlock with ext4_map_blocks.  At this
171487caeefSJan Kara 	 * moment, get_block can be called only for blocks inside i_size since
172487caeefSJan Kara 	 * page cache has been already dropped and writes are blocked by
173487caeefSJan Kara 	 * i_mutex. So we can safely drop the i_data_sem here.
174487caeefSJan Kara 	 */
1750390131bSFrank Mayhar 	BUG_ON(EXT4_JOURNAL(inode) == NULL);
176ac27a0ecSDave Kleikamp 	jbd_debug(2, "restarting handle %p\n", handle);
177487caeefSJan Kara 	up_write(&EXT4_I(inode)->i_data_sem);
1788e8eaabeSAmir Goldstein 	ret = ext4_journal_restart(handle, nblocks);
179487caeefSJan Kara 	down_write(&EXT4_I(inode)->i_data_sem);
180fa5d1113SAneesh Kumar K.V 	ext4_discard_preallocations(inode);
181487caeefSJan Kara 
182487caeefSJan Kara 	return ret;
183ac27a0ecSDave Kleikamp }
184ac27a0ecSDave Kleikamp 
185ac27a0ecSDave Kleikamp /*
186ac27a0ecSDave Kleikamp  * Called at the last iput() if i_nlink is zero.
187ac27a0ecSDave Kleikamp  */
1880930fcc1SAl Viro void ext4_evict_inode(struct inode *inode)
189ac27a0ecSDave Kleikamp {
190ac27a0ecSDave Kleikamp 	handle_t *handle;
191bc965ab3STheodore Ts'o 	int err;
192ac27a0ecSDave Kleikamp 
1937ff9c073STheodore Ts'o 	trace_ext4_evict_inode(inode);
1942581fdc8SJiaying Zhang 
1950930fcc1SAl Viro 	if (inode->i_nlink) {
1962d859db3SJan Kara 		/*
1972d859db3SJan Kara 		 * When journalling data dirty buffers are tracked only in the
1982d859db3SJan Kara 		 * journal. So although mm thinks everything is clean and
1992d859db3SJan Kara 		 * ready for reaping the inode might still have some pages to
2002d859db3SJan Kara 		 * write in the running transaction or waiting to be
2012d859db3SJan Kara 		 * checkpointed. Thus calling jbd2_journal_invalidatepage()
2022d859db3SJan Kara 		 * (via truncate_inode_pages()) to discard these buffers can
2032d859db3SJan Kara 		 * cause data loss. Also even if we did not discard these
2042d859db3SJan Kara 		 * buffers, we would have no way to find them after the inode
2052d859db3SJan Kara 		 * is reaped and thus user could see stale data if he tries to
2062d859db3SJan Kara 		 * read them before the transaction is checkpointed. So be
2072d859db3SJan Kara 		 * careful and force everything to disk here... We use
2082d859db3SJan Kara 		 * ei->i_datasync_tid to store the newest transaction
2092d859db3SJan Kara 		 * containing inode's data.
2102d859db3SJan Kara 		 *
2112d859db3SJan Kara 		 * Note that directories do not have this problem because they
2122d859db3SJan Kara 		 * don't use page cache.
2132d859db3SJan Kara 		 */
2146a7fd522SVegard Nossum 		if (inode->i_ino != EXT4_JOURNAL_INO &&
2156a7fd522SVegard Nossum 		    ext4_should_journal_data(inode) &&
2166a7fd522SVegard Nossum 		    (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
2172d859db3SJan Kara 			journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
2182d859db3SJan Kara 			tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
2192d859db3SJan Kara 
220d76a3a77STheodore Ts'o 			jbd2_complete_transaction(journal, commit_tid);
2212d859db3SJan Kara 			filemap_write_and_wait(&inode->i_data);
2222d859db3SJan Kara 		}
22391b0abe3SJohannes Weiner 		truncate_inode_pages_final(&inode->i_data);
2245dc23bddSJan Kara 
2250930fcc1SAl Viro 		goto no_delete;
2260930fcc1SAl Viro 	}
2270930fcc1SAl Viro 
228e2bfb088STheodore Ts'o 	if (is_bad_inode(inode))
229e2bfb088STheodore Ts'o 		goto no_delete;
230871a2931SChristoph Hellwig 	dquot_initialize(inode);
231907f4554SChristoph Hellwig 
232678aaf48SJan Kara 	if (ext4_should_order_data(inode))
233678aaf48SJan Kara 		ext4_begin_ordered_truncate(inode, 0);
23491b0abe3SJohannes Weiner 	truncate_inode_pages_final(&inode->i_data);
235ac27a0ecSDave Kleikamp 
2368e8ad8a5SJan Kara 	/*
2378e8ad8a5SJan Kara 	 * Protect us against freezing - iput() caller didn't have to have any
2388e8ad8a5SJan Kara 	 * protection against it
2398e8ad8a5SJan Kara 	 */
2408e8ad8a5SJan Kara 	sb_start_intwrite(inode->i_sb);
2419924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
2429924a92aSTheodore Ts'o 				    ext4_blocks_for_truncate(inode)+3);
243ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
244bc965ab3STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
245ac27a0ecSDave Kleikamp 		/*
246ac27a0ecSDave Kleikamp 		 * If we're going to skip the normal cleanup, we still need to
247ac27a0ecSDave Kleikamp 		 * make sure that the in-core orphan linked list is properly
248ac27a0ecSDave Kleikamp 		 * cleaned up.
249ac27a0ecSDave Kleikamp 		 */
250617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
2518e8ad8a5SJan Kara 		sb_end_intwrite(inode->i_sb);
252ac27a0ecSDave Kleikamp 		goto no_delete;
253ac27a0ecSDave Kleikamp 	}
254ac27a0ecSDave Kleikamp 
255ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
2560390131bSFrank Mayhar 		ext4_handle_sync(handle);
257ac27a0ecSDave Kleikamp 	inode->i_size = 0;
258bc965ab3STheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
259bc965ab3STheodore Ts'o 	if (err) {
26012062dddSEric Sandeen 		ext4_warning(inode->i_sb,
261bc965ab3STheodore Ts'o 			     "couldn't mark inode dirty (err %d)", err);
262bc965ab3STheodore Ts'o 		goto stop_handle;
263bc965ab3STheodore Ts'o 	}
2642c98eb5eSTheodore Ts'o 	if (inode->i_blocks) {
2652c98eb5eSTheodore Ts'o 		err = ext4_truncate(inode);
2662c98eb5eSTheodore Ts'o 		if (err) {
2672c98eb5eSTheodore Ts'o 			ext4_error(inode->i_sb,
2682c98eb5eSTheodore Ts'o 				   "couldn't truncate inode %lu (err %d)",
2692c98eb5eSTheodore Ts'o 				   inode->i_ino, err);
2702c98eb5eSTheodore Ts'o 			goto stop_handle;
2712c98eb5eSTheodore Ts'o 		}
2722c98eb5eSTheodore Ts'o 	}
273bc965ab3STheodore Ts'o 
274bc965ab3STheodore Ts'o 	/*
275bc965ab3STheodore Ts'o 	 * ext4_ext_truncate() doesn't reserve any slop when it
276bc965ab3STheodore Ts'o 	 * restarts journal transactions; therefore there may not be
277bc965ab3STheodore Ts'o 	 * enough credits left in the handle to remove the inode from
278bc965ab3STheodore Ts'o 	 * the orphan list and set the dtime field.
279bc965ab3STheodore Ts'o 	 */
2800390131bSFrank Mayhar 	if (!ext4_handle_has_enough_credits(handle, 3)) {
281bc965ab3STheodore Ts'o 		err = ext4_journal_extend(handle, 3);
282bc965ab3STheodore Ts'o 		if (err > 0)
283bc965ab3STheodore Ts'o 			err = ext4_journal_restart(handle, 3);
284bc965ab3STheodore Ts'o 		if (err != 0) {
28512062dddSEric Sandeen 			ext4_warning(inode->i_sb,
286bc965ab3STheodore Ts'o 				     "couldn't extend journal (err %d)", err);
287bc965ab3STheodore Ts'o 		stop_handle:
288bc965ab3STheodore Ts'o 			ext4_journal_stop(handle);
28945388219STheodore Ts'o 			ext4_orphan_del(NULL, inode);
2908e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
291bc965ab3STheodore Ts'o 			goto no_delete;
292bc965ab3STheodore Ts'o 		}
293bc965ab3STheodore Ts'o 	}
294bc965ab3STheodore Ts'o 
295ac27a0ecSDave Kleikamp 	/*
296617ba13bSMingming Cao 	 * Kill off the orphan record which ext4_truncate created.
297ac27a0ecSDave Kleikamp 	 * AKPM: I think this can be inside the above `if'.
298617ba13bSMingming Cao 	 * Note that ext4_orphan_del() has to be able to cope with the
299ac27a0ecSDave Kleikamp 	 * deletion of a non-existent orphan - this is because we don't
300617ba13bSMingming Cao 	 * know if ext4_truncate() actually created an orphan record.
301ac27a0ecSDave Kleikamp 	 * (Well, we could do this if we need to, but heck - it works)
302ac27a0ecSDave Kleikamp 	 */
303617ba13bSMingming Cao 	ext4_orphan_del(handle, inode);
304617ba13bSMingming Cao 	EXT4_I(inode)->i_dtime	= get_seconds();
305ac27a0ecSDave Kleikamp 
306ac27a0ecSDave Kleikamp 	/*
307ac27a0ecSDave Kleikamp 	 * One subtle ordering requirement: if anything has gone wrong
308ac27a0ecSDave Kleikamp 	 * (transaction abort, IO errors, whatever), then we can still
309ac27a0ecSDave Kleikamp 	 * do these next steps (the fs will already have been marked as
310ac27a0ecSDave Kleikamp 	 * having errors), but we can't free the inode if the mark_dirty
311ac27a0ecSDave Kleikamp 	 * fails.
312ac27a0ecSDave Kleikamp 	 */
313617ba13bSMingming Cao 	if (ext4_mark_inode_dirty(handle, inode))
314ac27a0ecSDave Kleikamp 		/* If that failed, just do the required in-core inode clear. */
3150930fcc1SAl Viro 		ext4_clear_inode(inode);
316ac27a0ecSDave Kleikamp 	else
317617ba13bSMingming Cao 		ext4_free_inode(handle, inode);
318617ba13bSMingming Cao 	ext4_journal_stop(handle);
3198e8ad8a5SJan Kara 	sb_end_intwrite(inode->i_sb);
320ac27a0ecSDave Kleikamp 	return;
321ac27a0ecSDave Kleikamp no_delete:
3220930fcc1SAl Viro 	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
323ac27a0ecSDave Kleikamp }
324ac27a0ecSDave Kleikamp 
325a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
326a9e7f447SDmitry Monakhov qsize_t *ext4_get_reserved_space(struct inode *inode)
32760e58e0fSMingming Cao {
328a9e7f447SDmitry Monakhov 	return &EXT4_I(inode)->i_reserved_quota;
32960e58e0fSMingming Cao }
330a9e7f447SDmitry Monakhov #endif
3319d0be502STheodore Ts'o 
33212219aeaSAneesh Kumar K.V /*
3330637c6f4STheodore Ts'o  * Called with i_data_sem down, which is important since we can call
3340637c6f4STheodore Ts'o  * ext4_discard_preallocations() from here.
3350637c6f4STheodore Ts'o  */
3365f634d06SAneesh Kumar K.V void ext4_da_update_reserve_space(struct inode *inode,
3375f634d06SAneesh Kumar K.V 					int used, int quota_claim)
33812219aeaSAneesh Kumar K.V {
33912219aeaSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3400637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
34112219aeaSAneesh Kumar K.V 
3420637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
343d8990240SAditya Kali 	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
3440637c6f4STheodore Ts'o 	if (unlikely(used > ei->i_reserved_data_blocks)) {
3458de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
3461084f252STheodore Ts'o 			 "with only %d reserved data blocks",
3470637c6f4STheodore Ts'o 			 __func__, inode->i_ino, used,
3480637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
3490637c6f4STheodore Ts'o 		WARN_ON(1);
3500637c6f4STheodore Ts'o 		used = ei->i_reserved_data_blocks;
3516bc6e63fSAneesh Kumar K.V 	}
35212219aeaSAneesh Kumar K.V 
3530637c6f4STheodore Ts'o 	/* Update per-inode reservations */
3540637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= used;
35571d4f7d0STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
3560637c6f4STheodore Ts'o 
35712219aeaSAneesh Kumar K.V 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
35860e58e0fSMingming Cao 
35972b8ab9dSEric Sandeen 	/* Update quota subsystem for data blocks */
36072b8ab9dSEric Sandeen 	if (quota_claim)
3617b415bf6SAditya Kali 		dquot_claim_block(inode, EXT4_C2B(sbi, used));
36272b8ab9dSEric Sandeen 	else {
3635f634d06SAneesh Kumar K.V 		/*
3645f634d06SAneesh Kumar K.V 		 * We did fallocate with an offset that is already delayed
3655f634d06SAneesh Kumar K.V 		 * allocated. So on delayed allocated writeback we should
36672b8ab9dSEric Sandeen 		 * not re-claim the quota for fallocated blocks.
3675f634d06SAneesh Kumar K.V 		 */
3687b415bf6SAditya Kali 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
3695f634d06SAneesh Kumar K.V 	}
370d6014301SAneesh Kumar K.V 
371d6014301SAneesh Kumar K.V 	/*
372d6014301SAneesh Kumar K.V 	 * If we have done all the pending block allocations and if
373d6014301SAneesh Kumar K.V 	 * there aren't any writers on the inode, we can discard the
374d6014301SAneesh Kumar K.V 	 * inode's preallocations.
375d6014301SAneesh Kumar K.V 	 */
3760637c6f4STheodore Ts'o 	if ((ei->i_reserved_data_blocks == 0) &&
3770637c6f4STheodore Ts'o 	    (atomic_read(&inode->i_writecount) == 0))
378d6014301SAneesh Kumar K.V 		ext4_discard_preallocations(inode);
37912219aeaSAneesh Kumar K.V }
38012219aeaSAneesh Kumar K.V 
381e29136f8STheodore Ts'o static int __check_block_validity(struct inode *inode, const char *func,
382c398eda0STheodore Ts'o 				unsigned int line,
38324676da4STheodore Ts'o 				struct ext4_map_blocks *map)
3846fd058f7STheodore Ts'o {
38524676da4STheodore Ts'o 	if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
38624676da4STheodore Ts'o 				   map->m_len)) {
387c398eda0STheodore Ts'o 		ext4_error_inode(inode, func, line, map->m_pblk,
388c398eda0STheodore Ts'o 				 "lblock %lu mapped to illegal pblock "
38924676da4STheodore Ts'o 				 "(length %d)", (unsigned long) map->m_lblk,
390c398eda0STheodore Ts'o 				 map->m_len);
3916a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
3926fd058f7STheodore Ts'o 	}
3936fd058f7STheodore Ts'o 	return 0;
3946fd058f7STheodore Ts'o }
3956fd058f7STheodore Ts'o 
39653085facSJan Kara int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
39753085facSJan Kara 		       ext4_lblk_t len)
39853085facSJan Kara {
39953085facSJan Kara 	int ret;
40053085facSJan Kara 
40153085facSJan Kara 	if (ext4_encrypted_inode(inode))
402a7550b30SJaegeuk Kim 		return fscrypt_zeroout_range(inode, lblk, pblk, len);
40353085facSJan Kara 
40453085facSJan Kara 	ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
40553085facSJan Kara 	if (ret > 0)
40653085facSJan Kara 		ret = 0;
40753085facSJan Kara 
40853085facSJan Kara 	return ret;
40953085facSJan Kara }
41053085facSJan Kara 
411e29136f8STheodore Ts'o #define check_block_validity(inode, map)	\
412c398eda0STheodore Ts'o 	__check_block_validity((inode), __func__, __LINE__, (map))
413e29136f8STheodore Ts'o 
414921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
415921f266bSDmitry Monakhov static void ext4_map_blocks_es_recheck(handle_t *handle,
416921f266bSDmitry Monakhov 				       struct inode *inode,
417921f266bSDmitry Monakhov 				       struct ext4_map_blocks *es_map,
418921f266bSDmitry Monakhov 				       struct ext4_map_blocks *map,
419921f266bSDmitry Monakhov 				       int flags)
420921f266bSDmitry Monakhov {
421921f266bSDmitry Monakhov 	int retval;
422921f266bSDmitry Monakhov 
423921f266bSDmitry Monakhov 	map->m_flags = 0;
424921f266bSDmitry Monakhov 	/*
425921f266bSDmitry Monakhov 	 * There is a race window that the result is not the same.
426921f266bSDmitry Monakhov 	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
427921f266bSDmitry Monakhov 	 * is that we lookup a block mapping in extent status tree with
428921f266bSDmitry Monakhov 	 * out taking i_data_sem.  So at the time the unwritten extent
429921f266bSDmitry Monakhov 	 * could be converted.
430921f266bSDmitry Monakhov 	 */
431c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
432921f266bSDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
433921f266bSDmitry Monakhov 		retval = ext4_ext_map_blocks(handle, inode, map, flags &
434921f266bSDmitry Monakhov 					     EXT4_GET_BLOCKS_KEEP_SIZE);
435921f266bSDmitry Monakhov 	} else {
436921f266bSDmitry Monakhov 		retval = ext4_ind_map_blocks(handle, inode, map, flags &
437921f266bSDmitry Monakhov 					     EXT4_GET_BLOCKS_KEEP_SIZE);
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 */
509d100eef2SZheng Liu 	if (ext4_es_lookup_extent(inode, map->m_lblk, &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 {
527d100eef2SZheng Liu 			BUG_ON(1);
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)) {
542a4e5d88bSDmitry Monakhov 		retval = ext4_ext_map_blocks(handle, inode, map, flags &
543a4e5d88bSDmitry Monakhov 					     EXT4_GET_BLOCKS_KEEP_SIZE);
5444df3d265SAneesh Kumar K.V 	} else {
545a4e5d88bSDmitry Monakhov 		retval = ext4_ind_map_blocks(handle, inode, map, flags &
546a4e5d88bSDmitry Monakhov 					     EXT4_GET_BLOCKS_KEEP_SIZE);
5470e855ac8SAneesh Kumar K.V 	}
548f7fec032SZheng Liu 	if (retval > 0) {
5493be78c73STheodore Ts'o 		unsigned int status;
550f7fec032SZheng Liu 
55144fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
55244fb851dSZheng Liu 			ext4_warning(inode->i_sb,
55344fb851dSZheng Liu 				     "ES len assertion failed for inode "
55444fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
55544fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
55644fb851dSZheng Liu 			WARN_ON(1);
557921f266bSDmitry Monakhov 		}
558921f266bSDmitry Monakhov 
559f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
560f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
561f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
562d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
563f7fec032SZheng Liu 		    ext4_find_delalloc_range(inode, map->m_lblk,
564f7fec032SZheng Liu 					     map->m_lblk + map->m_len - 1))
565f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
566f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk,
567f7fec032SZheng Liu 					    map->m_len, map->m_pblk, status);
568f7fec032SZheng Liu 		if (ret < 0)
569f7fec032SZheng Liu 			retval = ret;
570f7fec032SZheng Liu 	}
5714df3d265SAneesh Kumar K.V 	up_read((&EXT4_I(inode)->i_data_sem));
572f5ab0d1fSMingming Cao 
573d100eef2SZheng Liu found:
574e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
575b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
5766fd058f7STheodore Ts'o 		if (ret != 0)
5776fd058f7STheodore Ts'o 			return ret;
5786fd058f7STheodore Ts'o 	}
5796fd058f7STheodore Ts'o 
580f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
581c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
5824df3d265SAneesh Kumar K.V 		return retval;
5834df3d265SAneesh Kumar K.V 
5844df3d265SAneesh Kumar K.V 	/*
585f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
586f5ab0d1fSMingming Cao 	 *
587f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
588df3ab170STao Ma 	 * ext4_ext_get_block() returns the create = 0
589f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
590f5ab0d1fSMingming Cao 	 */
591e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
592b8a86845SLukas Czerner 		/*
593b8a86845SLukas Czerner 		 * If we need to convert extent to unwritten
594b8a86845SLukas Czerner 		 * we continue and do the actual work in
595b8a86845SLukas Czerner 		 * ext4_ext_map_blocks()
596b8a86845SLukas Czerner 		 */
597b8a86845SLukas Czerner 		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
598f5ab0d1fSMingming Cao 			return retval;
599f5ab0d1fSMingming Cao 
600f5ab0d1fSMingming Cao 	/*
601a25a4e1aSZheng Liu 	 * Here we clear m_flags because after allocating an new extent,
602a25a4e1aSZheng Liu 	 * it will be set again.
6032a8964d6SAneesh Kumar K.V 	 */
604a25a4e1aSZheng Liu 	map->m_flags &= ~EXT4_MAP_FLAGS;
6052a8964d6SAneesh Kumar K.V 
6062a8964d6SAneesh Kumar K.V 	/*
607556615dcSLukas Czerner 	 * New blocks allocate and/or writing to unwritten extent
608f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
609d91bd2c1SSeunghun Lee 	 * the write lock of i_data_sem, and call get_block()
610f5ab0d1fSMingming Cao 	 * with create == 1 flag.
6114df3d265SAneesh Kumar K.V 	 */
612c8b459f4SLukas Czerner 	down_write(&EXT4_I(inode)->i_data_sem);
613d2a17637SMingming Cao 
614d2a17637SMingming Cao 	/*
6154df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
6164df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
6174df3d265SAneesh Kumar K.V 	 */
61812e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
619e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
6200e855ac8SAneesh Kumar K.V 	} else {
621e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
622267e4db9SAneesh Kumar K.V 
623e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
624267e4db9SAneesh Kumar K.V 			/*
625267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
626267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
627267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
628267e4db9SAneesh Kumar K.V 			 */
62919f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
630267e4db9SAneesh Kumar K.V 		}
6312ac3b6e0STheodore Ts'o 
632d2a17637SMingming Cao 		/*
6332ac3b6e0STheodore Ts'o 		 * Update reserved blocks/metadata blocks after successful
6345f634d06SAneesh Kumar K.V 		 * block allocation which had been deferred till now. We don't
6355f634d06SAneesh Kumar K.V 		 * support fallocate for non extent files. So we can update
6365f634d06SAneesh Kumar K.V 		 * reserve space here.
637d2a17637SMingming Cao 		 */
6385f634d06SAneesh Kumar K.V 		if ((retval > 0) &&
6391296cc85SAneesh Kumar K.V 			(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
6405f634d06SAneesh Kumar K.V 			ext4_da_update_reserve_space(inode, retval, 1);
6415f634d06SAneesh Kumar K.V 	}
642d2a17637SMingming Cao 
643f7fec032SZheng Liu 	if (retval > 0) {
6443be78c73STheodore Ts'o 		unsigned int status;
645f7fec032SZheng Liu 
64644fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
64744fb851dSZheng Liu 			ext4_warning(inode->i_sb,
64844fb851dSZheng Liu 				     "ES len assertion failed for inode "
64944fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
65044fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
65144fb851dSZheng Liu 			WARN_ON(1);
652921f266bSDmitry Monakhov 		}
653921f266bSDmitry Monakhov 
654adb23551SZheng Liu 		/*
655c86d8db3SJan Kara 		 * We have to zeroout blocks before inserting them into extent
656c86d8db3SJan Kara 		 * status tree. Otherwise someone could look them up there and
6579b623df6SJan Kara 		 * use them before they are really zeroed. We also have to
6589b623df6SJan Kara 		 * unmap metadata before zeroing as otherwise writeback can
6599b623df6SJan Kara 		 * overwrite zeros with stale data from block device.
660c86d8db3SJan Kara 		 */
661c86d8db3SJan Kara 		if (flags & EXT4_GET_BLOCKS_ZERO &&
662c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_MAPPED &&
663c86d8db3SJan Kara 		    map->m_flags & EXT4_MAP_NEW) {
66464e1c57fSJan Kara 			clean_bdev_aliases(inode->i_sb->s_bdev, map->m_pblk,
66564e1c57fSJan Kara 					   map->m_len);
666c86d8db3SJan Kara 			ret = ext4_issue_zeroout(inode, map->m_lblk,
667c86d8db3SJan Kara 						 map->m_pblk, map->m_len);
668c86d8db3SJan Kara 			if (ret) {
669c86d8db3SJan Kara 				retval = ret;
670c86d8db3SJan Kara 				goto out_sem;
671c86d8db3SJan Kara 			}
672c86d8db3SJan Kara 		}
673c86d8db3SJan Kara 
674c86d8db3SJan Kara 		/*
675adb23551SZheng Liu 		 * If the extent has been zeroed out, we don't need to update
676adb23551SZheng Liu 		 * extent status tree.
677adb23551SZheng Liu 		 */
678adb23551SZheng Liu 		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
679adb23551SZheng Liu 		    ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
680adb23551SZheng Liu 			if (ext4_es_is_written(&es))
681c86d8db3SJan Kara 				goto out_sem;
682adb23551SZheng Liu 		}
683f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
684f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
685f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
686d2dc317dSLukas Czerner 		    !(status & EXTENT_STATUS_WRITTEN) &&
687f7fec032SZheng Liu 		    ext4_find_delalloc_range(inode, map->m_lblk,
688f7fec032SZheng Liu 					     map->m_lblk + map->m_len - 1))
689f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
690f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
691f7fec032SZheng Liu 					    map->m_pblk, status);
692c86d8db3SJan Kara 		if (ret < 0) {
69351865fdaSZheng Liu 			retval = ret;
694c86d8db3SJan Kara 			goto out_sem;
695c86d8db3SJan Kara 		}
69651865fdaSZheng Liu 	}
6975356f261SAditya Kali 
698c86d8db3SJan Kara out_sem:
6990e855ac8SAneesh Kumar K.V 	up_write((&EXT4_I(inode)->i_data_sem));
700e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
701b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
7026fd058f7STheodore Ts'o 		if (ret != 0)
7036fd058f7STheodore Ts'o 			return ret;
70406bd3c36SJan Kara 
70506bd3c36SJan Kara 		/*
70606bd3c36SJan Kara 		 * Inodes with freshly allocated blocks where contents will be
70706bd3c36SJan Kara 		 * visible after transaction commit must be on transaction's
70806bd3c36SJan Kara 		 * ordered data list.
70906bd3c36SJan Kara 		 */
71006bd3c36SJan Kara 		if (map->m_flags & EXT4_MAP_NEW &&
71106bd3c36SJan Kara 		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
71206bd3c36SJan Kara 		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
71306bd3c36SJan Kara 		    !IS_NOQUOTA(inode) &&
71406bd3c36SJan Kara 		    ext4_should_order_data(inode)) {
715ee0876bcSJan Kara 			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
716ee0876bcSJan Kara 				ret = ext4_jbd2_inode_add_wait(handle, inode);
717ee0876bcSJan Kara 			else
718ee0876bcSJan Kara 				ret = ext4_jbd2_inode_add_write(handle, inode);
71906bd3c36SJan Kara 			if (ret)
72006bd3c36SJan Kara 				return ret;
72106bd3c36SJan Kara 		}
7226fd058f7STheodore Ts'o 	}
7230e855ac8SAneesh Kumar K.V 	return retval;
7240e855ac8SAneesh Kumar K.V }
7250e855ac8SAneesh Kumar K.V 
726ed8ad838SJan Kara /*
727ed8ad838SJan Kara  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
728ed8ad838SJan Kara  * we have to be careful as someone else may be manipulating b_state as well.
729ed8ad838SJan Kara  */
730ed8ad838SJan Kara static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
731ed8ad838SJan Kara {
732ed8ad838SJan Kara 	unsigned long old_state;
733ed8ad838SJan Kara 	unsigned long new_state;
734ed8ad838SJan Kara 
735ed8ad838SJan Kara 	flags &= EXT4_MAP_FLAGS;
736ed8ad838SJan Kara 
737ed8ad838SJan Kara 	/* Dummy buffer_head? Set non-atomically. */
738ed8ad838SJan Kara 	if (!bh->b_page) {
739ed8ad838SJan Kara 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
740ed8ad838SJan Kara 		return;
741ed8ad838SJan Kara 	}
742ed8ad838SJan Kara 	/*
743ed8ad838SJan Kara 	 * Someone else may be modifying b_state. Be careful! This is ugly but
744ed8ad838SJan Kara 	 * once we get rid of using bh as a container for mapping information
745ed8ad838SJan Kara 	 * to pass to / from get_block functions, this can go away.
746ed8ad838SJan Kara 	 */
747ed8ad838SJan Kara 	do {
748ed8ad838SJan Kara 		old_state = READ_ONCE(bh->b_state);
749ed8ad838SJan Kara 		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
750ed8ad838SJan Kara 	} while (unlikely(
751ed8ad838SJan Kara 		 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
752ed8ad838SJan Kara }
753ed8ad838SJan Kara 
7542ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
7552ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
756ac27a0ecSDave Kleikamp {
7572ed88685STheodore Ts'o 	struct ext4_map_blocks map;
758efe70c29SJan Kara 	int ret = 0;
759ac27a0ecSDave Kleikamp 
76046c7f254STao Ma 	if (ext4_has_inline_data(inode))
76146c7f254STao Ma 		return -ERANGE;
76246c7f254STao Ma 
7632ed88685STheodore Ts'o 	map.m_lblk = iblock;
7642ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
7652ed88685STheodore Ts'o 
766efe70c29SJan Kara 	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
767efe70c29SJan Kara 			      flags);
768ac27a0ecSDave Kleikamp 	if (ret > 0) {
7692ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
770ed8ad838SJan Kara 		ext4_update_bh_state(bh, map.m_flags);
7712ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
772ac27a0ecSDave Kleikamp 		ret = 0;
773547edce3SRoss Zwisler 	} else if (ret == 0) {
774547edce3SRoss Zwisler 		/* hole case, need to fill in bh->b_size */
775547edce3SRoss Zwisler 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
776ac27a0ecSDave Kleikamp 	}
777ac27a0ecSDave Kleikamp 	return ret;
778ac27a0ecSDave Kleikamp }
779ac27a0ecSDave Kleikamp 
7802ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
7812ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
7822ed88685STheodore Ts'o {
7832ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
7842ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
7852ed88685STheodore Ts'o }
7862ed88685STheodore Ts'o 
787ac27a0ecSDave Kleikamp /*
788705965bdSJan Kara  * Get block function used when preparing for buffered write if we require
789705965bdSJan Kara  * creating an unwritten extent if blocks haven't been allocated.  The extent
790705965bdSJan Kara  * will be converted to written after the IO is complete.
791705965bdSJan Kara  */
792705965bdSJan Kara int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
793705965bdSJan Kara 			     struct buffer_head *bh_result, int create)
794705965bdSJan Kara {
795705965bdSJan Kara 	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
796705965bdSJan Kara 		   inode->i_ino, create);
797705965bdSJan Kara 	return _ext4_get_block(inode, iblock, bh_result,
798705965bdSJan Kara 			       EXT4_GET_BLOCKS_IO_CREATE_EXT);
799705965bdSJan Kara }
800705965bdSJan Kara 
801efe70c29SJan Kara /* Maximum number of blocks we map for direct IO at once. */
802efe70c29SJan Kara #define DIO_MAX_BLOCKS 4096
803efe70c29SJan Kara 
804e84dfbe2SJan Kara /*
805e84dfbe2SJan Kara  * Get blocks function for the cases that need to start a transaction -
806e84dfbe2SJan Kara  * generally difference cases of direct IO and DAX IO. It also handles retries
807e84dfbe2SJan Kara  * in case of ENOSPC.
808e84dfbe2SJan Kara  */
809e84dfbe2SJan Kara static int ext4_get_block_trans(struct inode *inode, sector_t iblock,
810e84dfbe2SJan Kara 				struct buffer_head *bh_result, int flags)
811efe70c29SJan Kara {
812efe70c29SJan Kara 	int dio_credits;
813e84dfbe2SJan Kara 	handle_t *handle;
814e84dfbe2SJan Kara 	int retries = 0;
815e84dfbe2SJan Kara 	int ret;
816efe70c29SJan Kara 
817efe70c29SJan Kara 	/* Trim mapping request to maximum we can map at once for DIO */
818efe70c29SJan Kara 	if (bh_result->b_size >> inode->i_blkbits > DIO_MAX_BLOCKS)
819efe70c29SJan Kara 		bh_result->b_size = DIO_MAX_BLOCKS << inode->i_blkbits;
820efe70c29SJan Kara 	dio_credits = ext4_chunk_trans_blocks(inode,
821efe70c29SJan Kara 				      bh_result->b_size >> inode->i_blkbits);
822e84dfbe2SJan Kara retry:
823e84dfbe2SJan Kara 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
824e84dfbe2SJan Kara 	if (IS_ERR(handle))
825e84dfbe2SJan Kara 		return PTR_ERR(handle);
826e84dfbe2SJan Kara 
827e84dfbe2SJan Kara 	ret = _ext4_get_block(inode, iblock, bh_result, flags);
828e84dfbe2SJan Kara 	ext4_journal_stop(handle);
829e84dfbe2SJan Kara 
830e84dfbe2SJan Kara 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
831e84dfbe2SJan Kara 		goto retry;
832e84dfbe2SJan Kara 	return ret;
833efe70c29SJan Kara }
834efe70c29SJan Kara 
835705965bdSJan Kara /* Get block function for DIO reads and writes to inodes without extents */
836705965bdSJan Kara int ext4_dio_get_block(struct inode *inode, sector_t iblock,
837705965bdSJan Kara 		       struct buffer_head *bh, int create)
838705965bdSJan Kara {
839efe70c29SJan Kara 	/* We don't expect handle for direct IO */
840efe70c29SJan Kara 	WARN_ON_ONCE(ext4_journal_current_handle());
841efe70c29SJan Kara 
842e84dfbe2SJan Kara 	if (!create)
843e84dfbe2SJan Kara 		return _ext4_get_block(inode, iblock, bh, 0);
844e84dfbe2SJan Kara 	return ext4_get_block_trans(inode, iblock, bh, EXT4_GET_BLOCKS_CREATE);
845705965bdSJan Kara }
846705965bdSJan Kara 
847705965bdSJan Kara /*
848109811c2SJan Kara  * Get block function for AIO DIO writes when we create unwritten extent if
849705965bdSJan Kara  * blocks are not allocated yet. The extent will be converted to written
850705965bdSJan Kara  * after IO is complete.
851705965bdSJan Kara  */
852109811c2SJan Kara static int ext4_dio_get_block_unwritten_async(struct inode *inode,
853109811c2SJan Kara 		sector_t iblock, struct buffer_head *bh_result,	int create)
854705965bdSJan Kara {
855efe70c29SJan Kara 	int ret;
856efe70c29SJan Kara 
857efe70c29SJan Kara 	/* We don't expect handle for direct IO */
858efe70c29SJan Kara 	WARN_ON_ONCE(ext4_journal_current_handle());
859efe70c29SJan Kara 
860e84dfbe2SJan Kara 	ret = ext4_get_block_trans(inode, iblock, bh_result,
861705965bdSJan Kara 				   EXT4_GET_BLOCKS_IO_CREATE_EXT);
862efe70c29SJan Kara 
863109811c2SJan Kara 	/*
864109811c2SJan Kara 	 * When doing DIO using unwritten extents, we need io_end to convert
865109811c2SJan Kara 	 * unwritten extents to written on IO completion. We allocate io_end
866109811c2SJan Kara 	 * once we spot unwritten extent and store it in b_private. Generic
867109811c2SJan Kara 	 * DIO code keeps b_private set and furthermore passes the value to
868109811c2SJan Kara 	 * our completion callback in 'private' argument.
869109811c2SJan Kara 	 */
870109811c2SJan Kara 	if (!ret && buffer_unwritten(bh_result)) {
871109811c2SJan Kara 		if (!bh_result->b_private) {
872109811c2SJan Kara 			ext4_io_end_t *io_end;
873109811c2SJan Kara 
874109811c2SJan Kara 			io_end = ext4_init_io_end(inode, GFP_KERNEL);
875109811c2SJan Kara 			if (!io_end)
876109811c2SJan Kara 				return -ENOMEM;
877109811c2SJan Kara 			bh_result->b_private = io_end;
878109811c2SJan Kara 			ext4_set_io_unwritten_flag(inode, io_end);
879efe70c29SJan Kara 		}
880109811c2SJan Kara 		set_buffer_defer_completion(bh_result);
881109811c2SJan Kara 	}
882109811c2SJan Kara 
883109811c2SJan Kara 	return ret;
884109811c2SJan Kara }
885109811c2SJan Kara 
886109811c2SJan Kara /*
887109811c2SJan Kara  * Get block function for non-AIO DIO writes when we create unwritten extent if
888109811c2SJan Kara  * blocks are not allocated yet. The extent will be converted to written
889109811c2SJan Kara  * after IO is complete from ext4_ext_direct_IO() function.
890109811c2SJan Kara  */
891109811c2SJan Kara static int ext4_dio_get_block_unwritten_sync(struct inode *inode,
892109811c2SJan Kara 		sector_t iblock, struct buffer_head *bh_result,	int create)
893109811c2SJan Kara {
894109811c2SJan Kara 	int ret;
895109811c2SJan Kara 
896109811c2SJan Kara 	/* We don't expect handle for direct IO */
897109811c2SJan Kara 	WARN_ON_ONCE(ext4_journal_current_handle());
898109811c2SJan Kara 
899e84dfbe2SJan Kara 	ret = ext4_get_block_trans(inode, iblock, bh_result,
900109811c2SJan Kara 				   EXT4_GET_BLOCKS_IO_CREATE_EXT);
901109811c2SJan Kara 
902109811c2SJan Kara 	/*
903109811c2SJan Kara 	 * Mark inode as having pending DIO writes to unwritten extents.
904109811c2SJan Kara 	 * ext4_ext_direct_IO() checks this flag and converts extents to
905109811c2SJan Kara 	 * written.
906109811c2SJan Kara 	 */
907109811c2SJan Kara 	if (!ret && buffer_unwritten(bh_result))
908109811c2SJan Kara 		ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
909efe70c29SJan Kara 
910efe70c29SJan Kara 	return ret;
911705965bdSJan Kara }
912705965bdSJan Kara 
913705965bdSJan Kara static int ext4_dio_get_block_overwrite(struct inode *inode, sector_t iblock,
914705965bdSJan Kara 		   struct buffer_head *bh_result, int create)
915705965bdSJan Kara {
916705965bdSJan Kara 	int ret;
917705965bdSJan Kara 
918705965bdSJan Kara 	ext4_debug("ext4_dio_get_block_overwrite: inode %lu, create flag %d\n",
919705965bdSJan Kara 		   inode->i_ino, create);
920efe70c29SJan Kara 	/* We don't expect handle for direct IO */
921efe70c29SJan Kara 	WARN_ON_ONCE(ext4_journal_current_handle());
922efe70c29SJan Kara 
923705965bdSJan Kara 	ret = _ext4_get_block(inode, iblock, bh_result, 0);
924705965bdSJan Kara 	/*
925705965bdSJan Kara 	 * Blocks should have been preallocated! ext4_file_write_iter() checks
926705965bdSJan Kara 	 * that.
927705965bdSJan Kara 	 */
928efe70c29SJan Kara 	WARN_ON_ONCE(!buffer_mapped(bh_result) || buffer_unwritten(bh_result));
929705965bdSJan Kara 
930705965bdSJan Kara 	return ret;
931705965bdSJan Kara }
932705965bdSJan Kara 
933705965bdSJan Kara 
934705965bdSJan Kara /*
935ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
936ac27a0ecSDave Kleikamp  */
937617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
938c5e298aeSTheodore Ts'o 				ext4_lblk_t block, int map_flags)
939ac27a0ecSDave Kleikamp {
9402ed88685STheodore Ts'o 	struct ext4_map_blocks map;
9412ed88685STheodore Ts'o 	struct buffer_head *bh;
942c5e298aeSTheodore Ts'o 	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
94310560082STheodore Ts'o 	int err;
944ac27a0ecSDave Kleikamp 
945ac27a0ecSDave Kleikamp 	J_ASSERT(handle != NULL || create == 0);
946ac27a0ecSDave Kleikamp 
9472ed88685STheodore Ts'o 	map.m_lblk = block;
9482ed88685STheodore Ts'o 	map.m_len = 1;
949c5e298aeSTheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map, map_flags);
9502ed88685STheodore Ts'o 
95110560082STheodore Ts'o 	if (err == 0)
95210560082STheodore Ts'o 		return create ? ERR_PTR(-ENOSPC) : NULL;
9532ed88685STheodore Ts'o 	if (err < 0)
95410560082STheodore Ts'o 		return ERR_PTR(err);
9552ed88685STheodore Ts'o 
9562ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
95710560082STheodore Ts'o 	if (unlikely(!bh))
95810560082STheodore Ts'o 		return ERR_PTR(-ENOMEM);
9592ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
960ac27a0ecSDave Kleikamp 		J_ASSERT(create != 0);
961ac39849dSAneesh Kumar K.V 		J_ASSERT(handle != NULL);
962ac27a0ecSDave Kleikamp 
963ac27a0ecSDave Kleikamp 		/*
964ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
965ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
966ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
967617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
968ac27a0ecSDave Kleikamp 		 * problem.
969ac27a0ecSDave Kleikamp 		 */
970ac27a0ecSDave Kleikamp 		lock_buffer(bh);
971ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
97210560082STheodore Ts'o 		err = ext4_journal_get_create_access(handle, bh);
97310560082STheodore Ts'o 		if (unlikely(err)) {
97410560082STheodore Ts'o 			unlock_buffer(bh);
97510560082STheodore Ts'o 			goto errout;
97610560082STheodore Ts'o 		}
97710560082STheodore Ts'o 		if (!buffer_uptodate(bh)) {
978ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
979ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
980ac27a0ecSDave Kleikamp 		}
981ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
9820390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
9830390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
98410560082STheodore Ts'o 		if (unlikely(err))
98510560082STheodore Ts'o 			goto errout;
98610560082STheodore Ts'o 	} else
987ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
988ac27a0ecSDave Kleikamp 	return bh;
98910560082STheodore Ts'o errout:
99010560082STheodore Ts'o 	brelse(bh);
99110560082STheodore Ts'o 	return ERR_PTR(err);
992ac27a0ecSDave Kleikamp }
993ac27a0ecSDave Kleikamp 
994617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
995c5e298aeSTheodore Ts'o 			       ext4_lblk_t block, int map_flags)
996ac27a0ecSDave Kleikamp {
997ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
998ac27a0ecSDave Kleikamp 
999c5e298aeSTheodore Ts'o 	bh = ext4_getblk(handle, inode, block, map_flags);
10001c215028STheodore Ts'o 	if (IS_ERR(bh))
1001ac27a0ecSDave Kleikamp 		return bh;
10021c215028STheodore Ts'o 	if (!bh || buffer_uptodate(bh))
1003ac27a0ecSDave Kleikamp 		return bh;
1004dfec8a14SMike Christie 	ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1, &bh);
1005ac27a0ecSDave Kleikamp 	wait_on_buffer(bh);
1006ac27a0ecSDave Kleikamp 	if (buffer_uptodate(bh))
1007ac27a0ecSDave Kleikamp 		return bh;
1008ac27a0ecSDave Kleikamp 	put_bh(bh);
10091c215028STheodore Ts'o 	return ERR_PTR(-EIO);
1010ac27a0ecSDave Kleikamp }
1011ac27a0ecSDave Kleikamp 
1012f19d5870STao Ma int ext4_walk_page_buffers(handle_t *handle,
1013ac27a0ecSDave Kleikamp 			   struct buffer_head *head,
1014ac27a0ecSDave Kleikamp 			   unsigned from,
1015ac27a0ecSDave Kleikamp 			   unsigned to,
1016ac27a0ecSDave Kleikamp 			   int *partial,
1017ac27a0ecSDave Kleikamp 			   int (*fn)(handle_t *handle,
1018ac27a0ecSDave Kleikamp 				     struct buffer_head *bh))
1019ac27a0ecSDave Kleikamp {
1020ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
1021ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
1022ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
1023ac27a0ecSDave Kleikamp 	int err, ret = 0;
1024ac27a0ecSDave Kleikamp 	struct buffer_head *next;
1025ac27a0ecSDave Kleikamp 
1026ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
1027ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
1028de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
1029ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
1030ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
1031ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
1032ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
1033ac27a0ecSDave Kleikamp 				*partial = 1;
1034ac27a0ecSDave Kleikamp 			continue;
1035ac27a0ecSDave Kleikamp 		}
1036ac27a0ecSDave Kleikamp 		err = (*fn)(handle, bh);
1037ac27a0ecSDave Kleikamp 		if (!ret)
1038ac27a0ecSDave Kleikamp 			ret = err;
1039ac27a0ecSDave Kleikamp 	}
1040ac27a0ecSDave Kleikamp 	return ret;
1041ac27a0ecSDave Kleikamp }
1042ac27a0ecSDave Kleikamp 
1043ac27a0ecSDave Kleikamp /*
1044ac27a0ecSDave Kleikamp  * To preserve ordering, it is essential that the hole instantiation and
1045ac27a0ecSDave Kleikamp  * the data write be encapsulated in a single transaction.  We cannot
1046617ba13bSMingming Cao  * close off a transaction and start a new one between the ext4_get_block()
1047dab291afSMingming Cao  * and the commit_write().  So doing the jbd2_journal_start at the start of
1048ac27a0ecSDave Kleikamp  * prepare_write() is the right place.
1049ac27a0ecSDave Kleikamp  *
105036ade451SJan Kara  * Also, this function can nest inside ext4_writepage().  In that case, we
105136ade451SJan Kara  * *know* that ext4_writepage() has generated enough buffer credits to do the
105236ade451SJan Kara  * whole page.  So we won't block on the journal in that case, which is good,
105336ade451SJan Kara  * because the caller may be PF_MEMALLOC.
1054ac27a0ecSDave Kleikamp  *
1055617ba13bSMingming Cao  * By accident, ext4 can be reentered when a transaction is open via
1056ac27a0ecSDave Kleikamp  * quota file writes.  If we were to commit the transaction while thus
1057ac27a0ecSDave Kleikamp  * reentered, there can be a deadlock - we would be holding a quota
1058ac27a0ecSDave Kleikamp  * lock, and the commit would never complete if another thread had a
1059ac27a0ecSDave Kleikamp  * transaction open and was blocking on the quota lock - a ranking
1060ac27a0ecSDave Kleikamp  * violation.
1061ac27a0ecSDave Kleikamp  *
1062dab291afSMingming Cao  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1063ac27a0ecSDave Kleikamp  * will _not_ run commit under these circumstances because handle->h_ref
1064ac27a0ecSDave Kleikamp  * is elevated.  We'll still have enough credits for the tiny quotafile
1065ac27a0ecSDave Kleikamp  * write.
1066ac27a0ecSDave Kleikamp  */
1067f19d5870STao Ma int do_journal_get_write_access(handle_t *handle,
1068ac27a0ecSDave Kleikamp 				struct buffer_head *bh)
1069ac27a0ecSDave Kleikamp {
107056d35a4cSJan Kara 	int dirty = buffer_dirty(bh);
107156d35a4cSJan Kara 	int ret;
107256d35a4cSJan Kara 
1073ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1074ac27a0ecSDave Kleikamp 		return 0;
107556d35a4cSJan Kara 	/*
1076ebdec241SChristoph Hellwig 	 * __block_write_begin() could have dirtied some buffers. Clean
107756d35a4cSJan Kara 	 * the dirty bit as jbd2_journal_get_write_access() could complain
107856d35a4cSJan Kara 	 * otherwise about fs integrity issues. Setting of the dirty bit
1079ebdec241SChristoph Hellwig 	 * by __block_write_begin() isn't a real problem here as we clear
108056d35a4cSJan Kara 	 * the bit before releasing a page lock and thus writeback cannot
108156d35a4cSJan Kara 	 * ever write the buffer.
108256d35a4cSJan Kara 	 */
108356d35a4cSJan Kara 	if (dirty)
108456d35a4cSJan Kara 		clear_buffer_dirty(bh);
10855d601255Sliang xie 	BUFFER_TRACE(bh, "get write access");
108656d35a4cSJan Kara 	ret = ext4_journal_get_write_access(handle, bh);
108756d35a4cSJan Kara 	if (!ret && dirty)
108856d35a4cSJan Kara 		ret = ext4_handle_dirty_metadata(handle, NULL, bh);
108956d35a4cSJan Kara 	return ret;
1090ac27a0ecSDave Kleikamp }
1091ac27a0ecSDave Kleikamp 
10922058f83aSMichael Halcrow #ifdef CONFIG_EXT4_FS_ENCRYPTION
10932058f83aSMichael Halcrow static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
10942058f83aSMichael Halcrow 				  get_block_t *get_block)
10952058f83aSMichael Halcrow {
109609cbfeafSKirill A. Shutemov 	unsigned from = pos & (PAGE_SIZE - 1);
10972058f83aSMichael Halcrow 	unsigned to = from + len;
10982058f83aSMichael Halcrow 	struct inode *inode = page->mapping->host;
10992058f83aSMichael Halcrow 	unsigned block_start, block_end;
11002058f83aSMichael Halcrow 	sector_t block;
11012058f83aSMichael Halcrow 	int err = 0;
11022058f83aSMichael Halcrow 	unsigned blocksize = inode->i_sb->s_blocksize;
11032058f83aSMichael Halcrow 	unsigned bbits;
11042058f83aSMichael Halcrow 	struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
11052058f83aSMichael Halcrow 	bool decrypt = false;
11062058f83aSMichael Halcrow 
11072058f83aSMichael Halcrow 	BUG_ON(!PageLocked(page));
110809cbfeafSKirill A. Shutemov 	BUG_ON(from > PAGE_SIZE);
110909cbfeafSKirill A. Shutemov 	BUG_ON(to > PAGE_SIZE);
11102058f83aSMichael Halcrow 	BUG_ON(from > to);
11112058f83aSMichael Halcrow 
11122058f83aSMichael Halcrow 	if (!page_has_buffers(page))
11132058f83aSMichael Halcrow 		create_empty_buffers(page, blocksize, 0);
11142058f83aSMichael Halcrow 	head = page_buffers(page);
11152058f83aSMichael Halcrow 	bbits = ilog2(blocksize);
111609cbfeafSKirill A. Shutemov 	block = (sector_t)page->index << (PAGE_SHIFT - bbits);
11172058f83aSMichael Halcrow 
11182058f83aSMichael Halcrow 	for (bh = head, block_start = 0; bh != head || !block_start;
11192058f83aSMichael Halcrow 	    block++, block_start = block_end, bh = bh->b_this_page) {
11202058f83aSMichael Halcrow 		block_end = block_start + blocksize;
11212058f83aSMichael Halcrow 		if (block_end <= from || block_start >= to) {
11222058f83aSMichael Halcrow 			if (PageUptodate(page)) {
11232058f83aSMichael Halcrow 				if (!buffer_uptodate(bh))
11242058f83aSMichael Halcrow 					set_buffer_uptodate(bh);
11252058f83aSMichael Halcrow 			}
11262058f83aSMichael Halcrow 			continue;
11272058f83aSMichael Halcrow 		}
11282058f83aSMichael Halcrow 		if (buffer_new(bh))
11292058f83aSMichael Halcrow 			clear_buffer_new(bh);
11302058f83aSMichael Halcrow 		if (!buffer_mapped(bh)) {
11312058f83aSMichael Halcrow 			WARN_ON(bh->b_size != blocksize);
11322058f83aSMichael Halcrow 			err = get_block(inode, block, bh, 1);
11332058f83aSMichael Halcrow 			if (err)
11342058f83aSMichael Halcrow 				break;
11352058f83aSMichael Halcrow 			if (buffer_new(bh)) {
1136e64855c6SJan Kara 				clean_bdev_bh_alias(bh);
11372058f83aSMichael Halcrow 				if (PageUptodate(page)) {
11382058f83aSMichael Halcrow 					clear_buffer_new(bh);
11392058f83aSMichael Halcrow 					set_buffer_uptodate(bh);
11402058f83aSMichael Halcrow 					mark_buffer_dirty(bh);
11412058f83aSMichael Halcrow 					continue;
11422058f83aSMichael Halcrow 				}
11432058f83aSMichael Halcrow 				if (block_end > to || block_start < from)
11442058f83aSMichael Halcrow 					zero_user_segments(page, to, block_end,
11452058f83aSMichael Halcrow 							   block_start, from);
11462058f83aSMichael Halcrow 				continue;
11472058f83aSMichael Halcrow 			}
11482058f83aSMichael Halcrow 		}
11492058f83aSMichael Halcrow 		if (PageUptodate(page)) {
11502058f83aSMichael Halcrow 			if (!buffer_uptodate(bh))
11512058f83aSMichael Halcrow 				set_buffer_uptodate(bh);
11522058f83aSMichael Halcrow 			continue;
11532058f83aSMichael Halcrow 		}
11542058f83aSMichael Halcrow 		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
11552058f83aSMichael Halcrow 		    !buffer_unwritten(bh) &&
11562058f83aSMichael Halcrow 		    (block_start < from || block_end > to)) {
1157dfec8a14SMike Christie 			ll_rw_block(REQ_OP_READ, 0, 1, &bh);
11582058f83aSMichael Halcrow 			*wait_bh++ = bh;
11592058f83aSMichael Halcrow 			decrypt = ext4_encrypted_inode(inode) &&
11602058f83aSMichael Halcrow 				S_ISREG(inode->i_mode);
11612058f83aSMichael Halcrow 		}
11622058f83aSMichael Halcrow 	}
11632058f83aSMichael Halcrow 	/*
11642058f83aSMichael Halcrow 	 * If we issued read requests, let them complete.
11652058f83aSMichael Halcrow 	 */
11662058f83aSMichael Halcrow 	while (wait_bh > wait) {
11672058f83aSMichael Halcrow 		wait_on_buffer(*--wait_bh);
11682058f83aSMichael Halcrow 		if (!buffer_uptodate(*wait_bh))
11692058f83aSMichael Halcrow 			err = -EIO;
11702058f83aSMichael Halcrow 	}
11712058f83aSMichael Halcrow 	if (unlikely(err))
11722058f83aSMichael Halcrow 		page_zero_new_buffers(page, from, to);
11732058f83aSMichael Halcrow 	else if (decrypt)
11747821d4ddSDavid Gstir 		err = fscrypt_decrypt_page(page->mapping->host, page,
11759c4bb8a3SDavid Gstir 				PAGE_SIZE, 0, page->index);
11762058f83aSMichael Halcrow 	return err;
11772058f83aSMichael Halcrow }
11782058f83aSMichael Halcrow #endif
11792058f83aSMichael Halcrow 
1180bfc1af65SNick Piggin static int ext4_write_begin(struct file *file, struct address_space *mapping,
1181bfc1af65SNick Piggin 			    loff_t pos, unsigned len, unsigned flags,
1182bfc1af65SNick Piggin 			    struct page **pagep, void **fsdata)
1183ac27a0ecSDave Kleikamp {
1184bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
11851938a150SAneesh Kumar K.V 	int ret, needed_blocks;
1186ac27a0ecSDave Kleikamp 	handle_t *handle;
1187ac27a0ecSDave Kleikamp 	int retries = 0;
1188bfc1af65SNick Piggin 	struct page *page;
1189bfc1af65SNick Piggin 	pgoff_t index;
1190bfc1af65SNick Piggin 	unsigned from, to;
1191bfc1af65SNick Piggin 
11929bffad1eSTheodore Ts'o 	trace_ext4_write_begin(inode, pos, len, flags);
11931938a150SAneesh Kumar K.V 	/*
11941938a150SAneesh Kumar K.V 	 * Reserve one block more for addition to orphan list in case
11951938a150SAneesh Kumar K.V 	 * we allocate blocks but write fails for some reason
11961938a150SAneesh Kumar K.V 	 */
11971938a150SAneesh Kumar K.V 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
119809cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
119909cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1200bfc1af65SNick Piggin 	to = from + len;
1201ac27a0ecSDave Kleikamp 
1202f19d5870STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1203f19d5870STao Ma 		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1204f19d5870STao Ma 						    flags, pagep);
1205f19d5870STao Ma 		if (ret < 0)
120647564bfbSTheodore Ts'o 			return ret;
120747564bfbSTheodore Ts'o 		if (ret == 1)
120847564bfbSTheodore Ts'o 			return 0;
1209f19d5870STao Ma 	}
1210f19d5870STao Ma 
121147564bfbSTheodore Ts'o 	/*
121247564bfbSTheodore Ts'o 	 * grab_cache_page_write_begin() can take a long time if the
121347564bfbSTheodore Ts'o 	 * system is thrashing due to memory pressure, or if the page
121447564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
121547564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
121647564bfbSTheodore Ts'o 	 * the page (if needed) without using GFP_NOFS.
121747564bfbSTheodore Ts'o 	 */
121847564bfbSTheodore Ts'o retry_grab:
121954566b2cSNick Piggin 	page = grab_cache_page_write_begin(mapping, index, flags);
122047564bfbSTheodore Ts'o 	if (!page)
122147564bfbSTheodore Ts'o 		return -ENOMEM;
122247564bfbSTheodore Ts'o 	unlock_page(page);
122347564bfbSTheodore Ts'o 
122447564bfbSTheodore Ts'o retry_journal:
12259924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1226ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
122709cbfeafSKirill A. Shutemov 		put_page(page);
122847564bfbSTheodore Ts'o 		return PTR_ERR(handle);
1229cf108bcaSJan Kara 	}
1230f19d5870STao Ma 
123147564bfbSTheodore Ts'o 	lock_page(page);
123247564bfbSTheodore Ts'o 	if (page->mapping != mapping) {
123347564bfbSTheodore Ts'o 		/* The page got truncated from under us */
123447564bfbSTheodore Ts'o 		unlock_page(page);
123509cbfeafSKirill A. Shutemov 		put_page(page);
1236cf108bcaSJan Kara 		ext4_journal_stop(handle);
123747564bfbSTheodore Ts'o 		goto retry_grab;
1238cf108bcaSJan Kara 	}
12397afe5aa5SDmitry Monakhov 	/* In case writeback began while the page was unlocked */
12407afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
1241cf108bcaSJan Kara 
12422058f83aSMichael Halcrow #ifdef CONFIG_EXT4_FS_ENCRYPTION
12432058f83aSMichael Halcrow 	if (ext4_should_dioread_nolock(inode))
12442058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
1245705965bdSJan Kara 					     ext4_get_block_unwritten);
12462058f83aSMichael Halcrow 	else
12472058f83aSMichael Halcrow 		ret = ext4_block_write_begin(page, pos, len,
12482058f83aSMichael Halcrow 					     ext4_get_block);
12492058f83aSMichael Halcrow #else
1250744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
1251705965bdSJan Kara 		ret = __block_write_begin(page, pos, len,
1252705965bdSJan Kara 					  ext4_get_block_unwritten);
1253744692dcSJiaying Zhang 	else
12546e1db88dSChristoph Hellwig 		ret = __block_write_begin(page, pos, len, ext4_get_block);
12552058f83aSMichael Halcrow #endif
1256bfc1af65SNick Piggin 	if (!ret && ext4_should_journal_data(inode)) {
1257f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_buffers(page),
1258f19d5870STao Ma 					     from, to, NULL,
1259f19d5870STao Ma 					     do_journal_get_write_access);
1260b46be050SAndrey Savochkin 	}
1261bfc1af65SNick Piggin 
1262bfc1af65SNick Piggin 	if (ret) {
1263bfc1af65SNick Piggin 		unlock_page(page);
1264ae4d5372SAneesh Kumar K.V 		/*
12656e1db88dSChristoph Hellwig 		 * __block_write_begin may have instantiated a few blocks
1266ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
1267ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
12681938a150SAneesh Kumar K.V 		 *
12691938a150SAneesh Kumar K.V 		 * Add inode to orphan list in case we crash before
12701938a150SAneesh Kumar K.V 		 * truncate finishes
1271ae4d5372SAneesh Kumar K.V 		 */
1272ffacfa7aSJan Kara 		if (pos + len > inode->i_size && ext4_can_truncate(inode))
12731938a150SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
12741938a150SAneesh Kumar K.V 
12751938a150SAneesh Kumar K.V 		ext4_journal_stop(handle);
12761938a150SAneesh Kumar K.V 		if (pos + len > inode->i_size) {
1277b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
12781938a150SAneesh Kumar K.V 			/*
1279ffacfa7aSJan Kara 			 * If truncate failed early the inode might
12801938a150SAneesh Kumar K.V 			 * still be on the orphan list; we need to
12811938a150SAneesh Kumar K.V 			 * make sure the inode is removed from the
12821938a150SAneesh Kumar K.V 			 * orphan list in that case.
12831938a150SAneesh Kumar K.V 			 */
12841938a150SAneesh Kumar K.V 			if (inode->i_nlink)
12851938a150SAneesh Kumar K.V 				ext4_orphan_del(NULL, inode);
12861938a150SAneesh Kumar K.V 		}
1287bfc1af65SNick Piggin 
128847564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
128947564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
129047564bfbSTheodore Ts'o 			goto retry_journal;
129109cbfeafSKirill A. Shutemov 		put_page(page);
129247564bfbSTheodore Ts'o 		return ret;
129347564bfbSTheodore Ts'o 	}
129447564bfbSTheodore Ts'o 	*pagep = page;
1295ac27a0ecSDave Kleikamp 	return ret;
1296ac27a0ecSDave Kleikamp }
1297ac27a0ecSDave Kleikamp 
1298bfc1af65SNick Piggin /* For write_end() in data=journal mode */
1299bfc1af65SNick Piggin static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1300ac27a0ecSDave Kleikamp {
130113fca323STheodore Ts'o 	int ret;
1302ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1303ac27a0ecSDave Kleikamp 		return 0;
1304ac27a0ecSDave Kleikamp 	set_buffer_uptodate(bh);
130513fca323STheodore Ts'o 	ret = ext4_handle_dirty_metadata(handle, NULL, bh);
130613fca323STheodore Ts'o 	clear_buffer_meta(bh);
130713fca323STheodore Ts'o 	clear_buffer_prio(bh);
130813fca323STheodore Ts'o 	return ret;
1309ac27a0ecSDave Kleikamp }
1310ac27a0ecSDave Kleikamp 
1311eed4333fSZheng Liu /*
1312eed4333fSZheng Liu  * We need to pick up the new inode size which generic_commit_write gave us
1313eed4333fSZheng Liu  * `file' can be NULL - eg, when called from page_symlink().
1314eed4333fSZheng Liu  *
1315eed4333fSZheng Liu  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1316eed4333fSZheng Liu  * buffers are managed internally.
1317eed4333fSZheng Liu  */
1318eed4333fSZheng Liu static int ext4_write_end(struct file *file,
1319f8514083SAneesh Kumar K.V 			  struct address_space *mapping,
1320f8514083SAneesh Kumar K.V 			  loff_t pos, unsigned len, unsigned copied,
1321f8514083SAneesh Kumar K.V 			  struct page *page, void *fsdata)
1322f8514083SAneesh Kumar K.V {
1323f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
1324eed4333fSZheng Liu 	struct inode *inode = mapping->host;
13250572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1326eed4333fSZheng Liu 	int ret = 0, ret2;
1327eed4333fSZheng Liu 	int i_size_changed = 0;
1328eed4333fSZheng Liu 
1329eed4333fSZheng Liu 	trace_ext4_write_end(inode, pos, len, copied);
133042c832deSTheodore Ts'o 	if (ext4_has_inline_data(inode)) {
133142c832deSTheodore Ts'o 		ret = ext4_write_inline_data_end(inode, pos, len,
1332f19d5870STao Ma 						 copied, page);
133342c832deSTheodore Ts'o 		if (ret < 0)
133442c832deSTheodore Ts'o 			goto errout;
133542c832deSTheodore Ts'o 		copied = ret;
133642c832deSTheodore Ts'o 	} else
1337f19d5870STao Ma 		copied = block_write_end(file, mapping, pos,
1338f19d5870STao Ma 					 len, copied, page, fsdata);
1339f8514083SAneesh Kumar K.V 	/*
13404631dbf6SDmitry Monakhov 	 * it's important to update i_size while still holding page lock:
1341f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
1342f8514083SAneesh Kumar K.V 	 */
13434631dbf6SDmitry Monakhov 	i_size_changed = ext4_update_inode_size(inode, pos + copied);
1344f8514083SAneesh Kumar K.V 	unlock_page(page);
134509cbfeafSKirill A. Shutemov 	put_page(page);
1346f8514083SAneesh Kumar K.V 
13470572639fSXiaoguang Wang 	if (old_size < pos)
13480572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
1349f8514083SAneesh Kumar K.V 	/*
1350f8514083SAneesh Kumar K.V 	 * Don't mark the inode dirty under page lock. First, it unnecessarily
1351f8514083SAneesh Kumar K.V 	 * makes the holding time of page lock longer. Second, it forces lock
1352f8514083SAneesh Kumar K.V 	 * ordering of page lock and transaction start for journaling
1353f8514083SAneesh Kumar K.V 	 * filesystems.
1354f8514083SAneesh Kumar K.V 	 */
1355f8514083SAneesh Kumar K.V 	if (i_size_changed)
1356f8514083SAneesh Kumar K.V 		ext4_mark_inode_dirty(handle, inode);
1357f8514083SAneesh Kumar K.V 
1358ffacfa7aSJan Kara 	if (pos + len > inode->i_size && ext4_can_truncate(inode))
1359f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1360f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1361f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1362f8514083SAneesh Kumar K.V 		 */
1363f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
136474d553aaSTheodore Ts'o errout:
1365617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1366ac27a0ecSDave Kleikamp 	if (!ret)
1367ac27a0ecSDave Kleikamp 		ret = ret2;
1368bfc1af65SNick Piggin 
1369f8514083SAneesh Kumar K.V 	if (pos + len > inode->i_size) {
1370b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1371f8514083SAneesh Kumar K.V 		/*
1372ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1373f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1374f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1375f8514083SAneesh Kumar K.V 		 */
1376f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1377f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1378f8514083SAneesh Kumar K.V 	}
1379f8514083SAneesh Kumar K.V 
1380bfc1af65SNick Piggin 	return ret ? ret : copied;
1381ac27a0ecSDave Kleikamp }
1382ac27a0ecSDave Kleikamp 
1383b90197b6STheodore Ts'o /*
1384b90197b6STheodore Ts'o  * This is a private version of page_zero_new_buffers() which doesn't
1385b90197b6STheodore Ts'o  * set the buffer to be dirty, since in data=journalled mode we need
1386b90197b6STheodore Ts'o  * to call ext4_handle_dirty_metadata() instead.
1387b90197b6STheodore Ts'o  */
1388*3b136499SJan Kara static void ext4_journalled_zero_new_buffers(handle_t *handle,
1389*3b136499SJan Kara 					    struct page *page,
1390*3b136499SJan Kara 					    unsigned from, unsigned to)
1391b90197b6STheodore Ts'o {
1392b90197b6STheodore Ts'o 	unsigned int block_start = 0, block_end;
1393b90197b6STheodore Ts'o 	struct buffer_head *head, *bh;
1394b90197b6STheodore Ts'o 
1395b90197b6STheodore Ts'o 	bh = head = page_buffers(page);
1396b90197b6STheodore Ts'o 	do {
1397b90197b6STheodore Ts'o 		block_end = block_start + bh->b_size;
1398b90197b6STheodore Ts'o 		if (buffer_new(bh)) {
1399b90197b6STheodore Ts'o 			if (block_end > from && block_start < to) {
1400b90197b6STheodore Ts'o 				if (!PageUptodate(page)) {
1401b90197b6STheodore Ts'o 					unsigned start, size;
1402b90197b6STheodore Ts'o 
1403b90197b6STheodore Ts'o 					start = max(from, block_start);
1404b90197b6STheodore Ts'o 					size = min(to, block_end) - start;
1405b90197b6STheodore Ts'o 
1406b90197b6STheodore Ts'o 					zero_user(page, start, size);
1407*3b136499SJan Kara 					write_end_fn(handle, bh);
1408b90197b6STheodore Ts'o 				}
1409b90197b6STheodore Ts'o 				clear_buffer_new(bh);
1410b90197b6STheodore Ts'o 			}
1411b90197b6STheodore Ts'o 		}
1412b90197b6STheodore Ts'o 		block_start = block_end;
1413b90197b6STheodore Ts'o 		bh = bh->b_this_page;
1414b90197b6STheodore Ts'o 	} while (bh != head);
1415b90197b6STheodore Ts'o }
1416b90197b6STheodore Ts'o 
1417bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
1418bfc1af65SNick Piggin 				     struct address_space *mapping,
1419bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
1420bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
1421ac27a0ecSDave Kleikamp {
1422617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1423bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
14240572639fSXiaoguang Wang 	loff_t old_size = inode->i_size;
1425ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1426ac27a0ecSDave Kleikamp 	int partial = 0;
1427bfc1af65SNick Piggin 	unsigned from, to;
14284631dbf6SDmitry Monakhov 	int size_changed = 0;
1429ac27a0ecSDave Kleikamp 
14309bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
143109cbfeafSKirill A. Shutemov 	from = pos & (PAGE_SIZE - 1);
1432bfc1af65SNick Piggin 	to = from + len;
1433bfc1af65SNick Piggin 
1434441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1435441c8508SCurt Wohlgemuth 
14363fdcfb66STao Ma 	if (ext4_has_inline_data(inode))
14373fdcfb66STao Ma 		copied = ext4_write_inline_data_end(inode, pos, len,
14383fdcfb66STao Ma 						    copied, page);
1439*3b136499SJan Kara 	else if (unlikely(copied < len) && !PageUptodate(page)) {
1440bfc1af65SNick Piggin 		copied = 0;
1441*3b136499SJan Kara 		ext4_journalled_zero_new_buffers(handle, page, from, to);
1442*3b136499SJan Kara 	} else {
1443*3b136499SJan Kara 		if (unlikely(copied < len))
1444*3b136499SJan Kara 			ext4_journalled_zero_new_buffers(handle, page,
1445*3b136499SJan Kara 							 from + copied, to);
1446f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1447*3b136499SJan Kara 					     from + copied, &partial,
1448*3b136499SJan Kara 					     write_end_fn);
1449ac27a0ecSDave Kleikamp 		if (!partial)
1450ac27a0ecSDave Kleikamp 			SetPageUptodate(page);
14513fdcfb66STao Ma 	}
14524631dbf6SDmitry Monakhov 	size_changed = ext4_update_inode_size(inode, pos + copied);
145319f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
14542d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
14554631dbf6SDmitry Monakhov 	unlock_page(page);
145609cbfeafSKirill A. Shutemov 	put_page(page);
14574631dbf6SDmitry Monakhov 
14580572639fSXiaoguang Wang 	if (old_size < pos)
14590572639fSXiaoguang Wang 		pagecache_isize_extended(inode, old_size, pos);
14600572639fSXiaoguang Wang 
14614631dbf6SDmitry Monakhov 	if (size_changed) {
1462617ba13bSMingming Cao 		ret2 = ext4_mark_inode_dirty(handle, inode);
1463ac27a0ecSDave Kleikamp 		if (!ret)
1464ac27a0ecSDave Kleikamp 			ret = ret2;
1465ac27a0ecSDave Kleikamp 	}
1466bfc1af65SNick Piggin 
1467ffacfa7aSJan Kara 	if (pos + len > inode->i_size && ext4_can_truncate(inode))
1468f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1469f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1470f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1471f8514083SAneesh Kumar K.V 		 */
1472f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1473f8514083SAneesh Kumar K.V 
1474617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1475ac27a0ecSDave Kleikamp 	if (!ret)
1476ac27a0ecSDave Kleikamp 		ret = ret2;
1477f8514083SAneesh Kumar K.V 	if (pos + len > inode->i_size) {
1478b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1479f8514083SAneesh Kumar K.V 		/*
1480ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1481f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1482f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1483f8514083SAneesh Kumar K.V 		 */
1484f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1485f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1486f8514083SAneesh Kumar K.V 	}
1487bfc1af65SNick Piggin 
1488bfc1af65SNick Piggin 	return ret ? ret : copied;
1489ac27a0ecSDave Kleikamp }
1490d2a17637SMingming Cao 
14919d0be502STheodore Ts'o /*
1492c27e43a1SEric Whitney  * Reserve space for a single cluster
14939d0be502STheodore Ts'o  */
1494c27e43a1SEric Whitney static int ext4_da_reserve_space(struct inode *inode)
1495d2a17637SMingming Cao {
1496d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
14970637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
14985dd4056dSChristoph Hellwig 	int ret;
1499d2a17637SMingming Cao 
150060e58e0fSMingming Cao 	/*
150172b8ab9dSEric Sandeen 	 * We will charge metadata quota at writeout time; this saves
150272b8ab9dSEric Sandeen 	 * us from metadata over-estimation, though we may go over by
150372b8ab9dSEric Sandeen 	 * a small amount in the end.  Here we just reserve for data.
150460e58e0fSMingming Cao 	 */
15057b415bf6SAditya Kali 	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
15065dd4056dSChristoph Hellwig 	if (ret)
15075dd4056dSChristoph Hellwig 		return ret;
150803179fe9STheodore Ts'o 
150903179fe9STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
151071d4f7d0STheodore Ts'o 	if (ext4_claim_free_clusters(sbi, 1, 0)) {
151103179fe9STheodore Ts'o 		spin_unlock(&ei->i_block_reservation_lock);
151203179fe9STheodore Ts'o 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1513d2a17637SMingming Cao 		return -ENOSPC;
1514d2a17637SMingming Cao 	}
15159d0be502STheodore Ts'o 	ei->i_reserved_data_blocks++;
1516c27e43a1SEric Whitney 	trace_ext4_da_reserve_space(inode);
15170637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
151839bc680aSDmitry Monakhov 
1519d2a17637SMingming Cao 	return 0;       /* success */
1520d2a17637SMingming Cao }
1521d2a17637SMingming Cao 
152212219aeaSAneesh Kumar K.V static void ext4_da_release_space(struct inode *inode, int to_free)
1523d2a17637SMingming Cao {
1524d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
15250637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1526d2a17637SMingming Cao 
1527cd213226SMingming Cao 	if (!to_free)
1528cd213226SMingming Cao 		return;		/* Nothing to release, exit */
1529cd213226SMingming Cao 
1530d2a17637SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1531cd213226SMingming Cao 
15325a58ec87SLi Zefan 	trace_ext4_da_release_space(inode, to_free);
15330637c6f4STheodore Ts'o 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1534cd213226SMingming Cao 		/*
15350637c6f4STheodore Ts'o 		 * if there aren't enough reserved blocks, then the
15360637c6f4STheodore Ts'o 		 * counter is messed up somewhere.  Since this
15370637c6f4STheodore Ts'o 		 * function is called from invalidate page, it's
15380637c6f4STheodore Ts'o 		 * harmless to return without any action.
1539cd213226SMingming Cao 		 */
15408de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "ext4_da_release_space: "
15410637c6f4STheodore Ts'o 			 "ino %lu, to_free %d with only %d reserved "
15421084f252STheodore Ts'o 			 "data blocks", inode->i_ino, to_free,
15430637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
15440637c6f4STheodore Ts'o 		WARN_ON(1);
15450637c6f4STheodore Ts'o 		to_free = ei->i_reserved_data_blocks;
15460637c6f4STheodore Ts'o 	}
15470637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= to_free;
15480637c6f4STheodore Ts'o 
154972b8ab9dSEric Sandeen 	/* update fs dirty data blocks counter */
155057042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1551d2a17637SMingming Cao 
1552d2a17637SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
155360e58e0fSMingming Cao 
15547b415bf6SAditya Kali 	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1555d2a17637SMingming Cao }
1556d2a17637SMingming Cao 
1557d2a17637SMingming Cao static void ext4_da_page_release_reservation(struct page *page,
1558ca99fdd2SLukas Czerner 					     unsigned int offset,
1559ca99fdd2SLukas Czerner 					     unsigned int length)
1560d2a17637SMingming Cao {
15619705acd6SLukas Czerner 	int to_release = 0, contiguous_blks = 0;
1562d2a17637SMingming Cao 	struct buffer_head *head, *bh;
1563d2a17637SMingming Cao 	unsigned int curr_off = 0;
15647b415bf6SAditya Kali 	struct inode *inode = page->mapping->host;
15657b415bf6SAditya Kali 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1566ca99fdd2SLukas Czerner 	unsigned int stop = offset + length;
15677b415bf6SAditya Kali 	int num_clusters;
156851865fdaSZheng Liu 	ext4_fsblk_t lblk;
1569d2a17637SMingming Cao 
157009cbfeafSKirill A. Shutemov 	BUG_ON(stop > PAGE_SIZE || stop < length);
1571ca99fdd2SLukas Czerner 
1572d2a17637SMingming Cao 	head = page_buffers(page);
1573d2a17637SMingming Cao 	bh = head;
1574d2a17637SMingming Cao 	do {
1575d2a17637SMingming Cao 		unsigned int next_off = curr_off + bh->b_size;
1576d2a17637SMingming Cao 
1577ca99fdd2SLukas Czerner 		if (next_off > stop)
1578ca99fdd2SLukas Czerner 			break;
1579ca99fdd2SLukas Czerner 
1580d2a17637SMingming Cao 		if ((offset <= curr_off) && (buffer_delay(bh))) {
1581d2a17637SMingming Cao 			to_release++;
15829705acd6SLukas Czerner 			contiguous_blks++;
1583d2a17637SMingming Cao 			clear_buffer_delay(bh);
15849705acd6SLukas Czerner 		} else if (contiguous_blks) {
15859705acd6SLukas Czerner 			lblk = page->index <<
158609cbfeafSKirill A. Shutemov 			       (PAGE_SHIFT - inode->i_blkbits);
15879705acd6SLukas Czerner 			lblk += (curr_off >> inode->i_blkbits) -
15889705acd6SLukas Czerner 				contiguous_blks;
15899705acd6SLukas Czerner 			ext4_es_remove_extent(inode, lblk, contiguous_blks);
15909705acd6SLukas Czerner 			contiguous_blks = 0;
1591d2a17637SMingming Cao 		}
1592d2a17637SMingming Cao 		curr_off = next_off;
1593d2a17637SMingming Cao 	} while ((bh = bh->b_this_page) != head);
15947b415bf6SAditya Kali 
15959705acd6SLukas Czerner 	if (contiguous_blks) {
159609cbfeafSKirill A. Shutemov 		lblk = page->index << (PAGE_SHIFT - inode->i_blkbits);
15979705acd6SLukas Czerner 		lblk += (curr_off >> inode->i_blkbits) - contiguous_blks;
15989705acd6SLukas Czerner 		ext4_es_remove_extent(inode, lblk, contiguous_blks);
159951865fdaSZheng Liu 	}
160051865fdaSZheng Liu 
16017b415bf6SAditya Kali 	/* If we have released all the blocks belonging to a cluster, then we
16027b415bf6SAditya Kali 	 * need to release the reserved space for that cluster. */
16037b415bf6SAditya Kali 	num_clusters = EXT4_NUM_B2C(sbi, to_release);
16047b415bf6SAditya Kali 	while (num_clusters > 0) {
160509cbfeafSKirill A. Shutemov 		lblk = (page->index << (PAGE_SHIFT - inode->i_blkbits)) +
16067b415bf6SAditya Kali 			((num_clusters - 1) << sbi->s_cluster_bits);
16077b415bf6SAditya Kali 		if (sbi->s_cluster_ratio == 1 ||
16087d1b1fbcSZheng Liu 		    !ext4_find_delalloc_cluster(inode, lblk))
16097b415bf6SAditya Kali 			ext4_da_release_space(inode, 1);
16107b415bf6SAditya Kali 
16117b415bf6SAditya Kali 		num_clusters--;
16127b415bf6SAditya Kali 	}
1613d2a17637SMingming Cao }
1614ac27a0ecSDave Kleikamp 
1615ac27a0ecSDave Kleikamp /*
161664769240SAlex Tomas  * Delayed allocation stuff
161764769240SAlex Tomas  */
161864769240SAlex Tomas 
16194e7ea81dSJan Kara struct mpage_da_data {
16204e7ea81dSJan Kara 	struct inode *inode;
16214e7ea81dSJan Kara 	struct writeback_control *wbc;
16226b523df4SJan Kara 
16234e7ea81dSJan Kara 	pgoff_t first_page;	/* The first page to write */
16244e7ea81dSJan Kara 	pgoff_t next_page;	/* Current page to examine */
16254e7ea81dSJan Kara 	pgoff_t last_page;	/* Last page to examine */
162664769240SAlex Tomas 	/*
16274e7ea81dSJan Kara 	 * Extent to map - this can be after first_page because that can be
16284e7ea81dSJan Kara 	 * fully mapped. We somewhat abuse m_flags to store whether the extent
16294e7ea81dSJan Kara 	 * is delalloc or unwritten.
163064769240SAlex Tomas 	 */
16314e7ea81dSJan Kara 	struct ext4_map_blocks map;
16324e7ea81dSJan Kara 	struct ext4_io_submit io_submit;	/* IO submission data */
16334e7ea81dSJan Kara };
163464769240SAlex Tomas 
16354e7ea81dSJan Kara static void mpage_release_unused_pages(struct mpage_da_data *mpd,
16364e7ea81dSJan Kara 				       bool invalidate)
1637c4a0c46eSAneesh Kumar K.V {
1638c4a0c46eSAneesh Kumar K.V 	int nr_pages, i;
1639c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
1640c4a0c46eSAneesh Kumar K.V 	struct pagevec pvec;
1641c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1642c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
16434e7ea81dSJan Kara 
16444e7ea81dSJan Kara 	/* This is necessary when next_page == 0. */
16454e7ea81dSJan Kara 	if (mpd->first_page >= mpd->next_page)
16464e7ea81dSJan Kara 		return;
1647c4a0c46eSAneesh Kumar K.V 
1648c7f5938aSCurt Wohlgemuth 	index = mpd->first_page;
1649c7f5938aSCurt Wohlgemuth 	end   = mpd->next_page - 1;
16504e7ea81dSJan Kara 	if (invalidate) {
16514e7ea81dSJan Kara 		ext4_lblk_t start, last;
165209cbfeafSKirill A. Shutemov 		start = index << (PAGE_SHIFT - inode->i_blkbits);
165309cbfeafSKirill A. Shutemov 		last = end << (PAGE_SHIFT - inode->i_blkbits);
165451865fdaSZheng Liu 		ext4_es_remove_extent(inode, start, last - start + 1);
16554e7ea81dSJan Kara 	}
165651865fdaSZheng Liu 
165766bea92cSEric Sandeen 	pagevec_init(&pvec, 0);
1658c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
1659c4a0c46eSAneesh Kumar K.V 		nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1660c4a0c46eSAneesh Kumar K.V 		if (nr_pages == 0)
1661c4a0c46eSAneesh Kumar K.V 			break;
1662c4a0c46eSAneesh Kumar K.V 		for (i = 0; i < nr_pages; i++) {
1663c4a0c46eSAneesh Kumar K.V 			struct page *page = pvec.pages[i];
16649b1d0998SJan Kara 			if (page->index > end)
1665c4a0c46eSAneesh Kumar K.V 				break;
1666c4a0c46eSAneesh Kumar K.V 			BUG_ON(!PageLocked(page));
1667c4a0c46eSAneesh Kumar K.V 			BUG_ON(PageWriteback(page));
16684e7ea81dSJan Kara 			if (invalidate) {
16694e800c03Swangguang 				if (page_mapped(page))
16704e800c03Swangguang 					clear_page_dirty_for_io(page);
167109cbfeafSKirill A. Shutemov 				block_invalidatepage(page, 0, PAGE_SIZE);
1672c4a0c46eSAneesh Kumar K.V 				ClearPageUptodate(page);
16734e7ea81dSJan Kara 			}
1674c4a0c46eSAneesh Kumar K.V 			unlock_page(page);
1675c4a0c46eSAneesh Kumar K.V 		}
16769b1d0998SJan Kara 		index = pvec.pages[nr_pages - 1]->index + 1;
16779b1d0998SJan Kara 		pagevec_release(&pvec);
1678c4a0c46eSAneesh Kumar K.V 	}
1679c4a0c46eSAneesh Kumar K.V }
1680c4a0c46eSAneesh Kumar K.V 
1681df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
1682df22291fSAneesh Kumar K.V {
1683df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
168492b97816STheodore Ts'o 	struct super_block *sb = inode->i_sb;
1685f78ee70dSLukas Czerner 	struct ext4_inode_info *ei = EXT4_I(inode);
168692b97816STheodore Ts'o 
168792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
16885dee5437STheodore Ts'o 	       EXT4_C2B(EXT4_SB(inode->i_sb),
1689f78ee70dSLukas Czerner 			ext4_count_free_clusters(sb)));
169092b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
169192b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1692f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
169357042651STheodore Ts'o 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
169492b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1695f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
16967b415bf6SAditya Kali 		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
169792b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Block reservation details");
169892b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1699f78ee70dSLukas Czerner 		 ei->i_reserved_data_blocks);
1700df22291fSAneesh Kumar K.V 	return;
1701df22291fSAneesh Kumar K.V }
1702df22291fSAneesh Kumar K.V 
1703c364b22cSAneesh Kumar K.V static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
170429fa89d0SAneesh Kumar K.V {
1705c364b22cSAneesh Kumar K.V 	return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
170629fa89d0SAneesh Kumar K.V }
170729fa89d0SAneesh Kumar K.V 
170864769240SAlex Tomas /*
17095356f261SAditya Kali  * This function is grabs code from the very beginning of
17105356f261SAditya Kali  * ext4_map_blocks, but assumes that the caller is from delayed write
17115356f261SAditya Kali  * time. This function looks up the requested blocks and sets the
17125356f261SAditya Kali  * buffer delay bit under the protection of i_data_sem.
17135356f261SAditya Kali  */
17145356f261SAditya Kali static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
17155356f261SAditya Kali 			      struct ext4_map_blocks *map,
17165356f261SAditya Kali 			      struct buffer_head *bh)
17175356f261SAditya Kali {
1718d100eef2SZheng Liu 	struct extent_status es;
17195356f261SAditya Kali 	int retval;
17205356f261SAditya Kali 	sector_t invalid_block = ~((sector_t) 0xffff);
1721921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1722921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
1723921f266bSDmitry Monakhov 
1724921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
1725921f266bSDmitry Monakhov #endif
17265356f261SAditya Kali 
17275356f261SAditya Kali 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
17285356f261SAditya Kali 		invalid_block = ~0;
17295356f261SAditya Kali 
17305356f261SAditya Kali 	map->m_flags = 0;
17315356f261SAditya Kali 	ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
17325356f261SAditya Kali 		  "logical block %lu\n", inode->i_ino, map->m_len,
17335356f261SAditya Kali 		  (unsigned long) map->m_lblk);
1734d100eef2SZheng Liu 
1735d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
1736d100eef2SZheng Liu 	if (ext4_es_lookup_extent(inode, iblock, &es)) {
1737d100eef2SZheng Liu 		if (ext4_es_is_hole(&es)) {
1738d100eef2SZheng Liu 			retval = 0;
1739c8b459f4SLukas Czerner 			down_read(&EXT4_I(inode)->i_data_sem);
1740d100eef2SZheng Liu 			goto add_delayed;
1741d100eef2SZheng Liu 		}
1742d100eef2SZheng Liu 
1743d100eef2SZheng Liu 		/*
1744d100eef2SZheng Liu 		 * Delayed extent could be allocated by fallocate.
1745d100eef2SZheng Liu 		 * So we need to check it.
1746d100eef2SZheng Liu 		 */
1747d100eef2SZheng Liu 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1748d100eef2SZheng Liu 			map_bh(bh, inode->i_sb, invalid_block);
1749d100eef2SZheng Liu 			set_buffer_new(bh);
1750d100eef2SZheng Liu 			set_buffer_delay(bh);
1751d100eef2SZheng Liu 			return 0;
1752d100eef2SZheng Liu 		}
1753d100eef2SZheng Liu 
1754d100eef2SZheng Liu 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1755d100eef2SZheng Liu 		retval = es.es_len - (iblock - es.es_lblk);
1756d100eef2SZheng Liu 		if (retval > map->m_len)
1757d100eef2SZheng Liu 			retval = map->m_len;
1758d100eef2SZheng Liu 		map->m_len = retval;
1759d100eef2SZheng Liu 		if (ext4_es_is_written(&es))
1760d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_MAPPED;
1761d100eef2SZheng Liu 		else if (ext4_es_is_unwritten(&es))
1762d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1763d100eef2SZheng Liu 		else
1764d100eef2SZheng Liu 			BUG_ON(1);
1765d100eef2SZheng Liu 
1766921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1767921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1768921f266bSDmitry Monakhov #endif
1769d100eef2SZheng Liu 		return retval;
1770d100eef2SZheng Liu 	}
1771d100eef2SZheng Liu 
17725356f261SAditya Kali 	/*
17735356f261SAditya Kali 	 * Try to see if we can get the block without requesting a new
17745356f261SAditya Kali 	 * file system block.
17755356f261SAditya Kali 	 */
1776c8b459f4SLukas Czerner 	down_read(&EXT4_I(inode)->i_data_sem);
1777cbd7584eSJan Kara 	if (ext4_has_inline_data(inode))
17789c3569b5STao Ma 		retval = 0;
1779cbd7584eSJan Kara 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
17802f8e0a7cSZheng Liu 		retval = ext4_ext_map_blocks(NULL, inode, map, 0);
17815356f261SAditya Kali 	else
17822f8e0a7cSZheng Liu 		retval = ext4_ind_map_blocks(NULL, inode, map, 0);
17835356f261SAditya Kali 
1784d100eef2SZheng Liu add_delayed:
17855356f261SAditya Kali 	if (retval == 0) {
1786f7fec032SZheng Liu 		int ret;
17875356f261SAditya Kali 		/*
17885356f261SAditya Kali 		 * XXX: __block_prepare_write() unmaps passed block,
17895356f261SAditya Kali 		 * is it OK?
17905356f261SAditya Kali 		 */
1791386ad67cSLukas Czerner 		/*
1792386ad67cSLukas Czerner 		 * If the block was allocated from previously allocated cluster,
1793386ad67cSLukas Czerner 		 * then we don't need to reserve it again. However we still need
1794386ad67cSLukas Czerner 		 * to reserve metadata for every block we're going to write.
1795386ad67cSLukas Czerner 		 */
1796c27e43a1SEric Whitney 		if (EXT4_SB(inode->i_sb)->s_cluster_ratio == 1 ||
1797cbd7584eSJan Kara 		    !ext4_find_delalloc_cluster(inode, map->m_lblk)) {
1798c27e43a1SEric Whitney 			ret = ext4_da_reserve_space(inode);
1799f7fec032SZheng Liu 			if (ret) {
18005356f261SAditya Kali 				/* not enough space to reserve */
1801f7fec032SZheng Liu 				retval = ret;
18025356f261SAditya Kali 				goto out_unlock;
18035356f261SAditya Kali 			}
1804f7fec032SZheng Liu 		}
18055356f261SAditya Kali 
1806f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1807fdc0212eSZheng Liu 					    ~0, EXTENT_STATUS_DELAYED);
1808f7fec032SZheng Liu 		if (ret) {
1809f7fec032SZheng Liu 			retval = ret;
181051865fdaSZheng Liu 			goto out_unlock;
1811f7fec032SZheng Liu 		}
181251865fdaSZheng Liu 
18135356f261SAditya Kali 		map_bh(bh, inode->i_sb, invalid_block);
18145356f261SAditya Kali 		set_buffer_new(bh);
18155356f261SAditya Kali 		set_buffer_delay(bh);
1816f7fec032SZheng Liu 	} else if (retval > 0) {
1817f7fec032SZheng Liu 		int ret;
18183be78c73STheodore Ts'o 		unsigned int status;
1819f7fec032SZheng Liu 
182044fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
182144fb851dSZheng Liu 			ext4_warning(inode->i_sb,
182244fb851dSZheng Liu 				     "ES len assertion failed for inode "
182344fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
182444fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
182544fb851dSZheng Liu 			WARN_ON(1);
1826921f266bSDmitry Monakhov 		}
1827921f266bSDmitry Monakhov 
1828f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1829f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1830f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1831f7fec032SZheng Liu 					    map->m_pblk, status);
1832f7fec032SZheng Liu 		if (ret != 0)
1833f7fec032SZheng Liu 			retval = ret;
18345356f261SAditya Kali 	}
18355356f261SAditya Kali 
18365356f261SAditya Kali out_unlock:
18375356f261SAditya Kali 	up_read((&EXT4_I(inode)->i_data_sem));
18385356f261SAditya Kali 
18395356f261SAditya Kali 	return retval;
18405356f261SAditya Kali }
18415356f261SAditya Kali 
18425356f261SAditya Kali /*
1843d91bd2c1SSeunghun Lee  * This is a special get_block_t callback which is used by
1844b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
1845b920c755STheodore Ts'o  * reserve space for a single block.
184629fa89d0SAneesh Kumar K.V  *
184729fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
184829fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
184929fa89d0SAneesh Kumar K.V  *
185029fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
185129fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
185229fa89d0SAneesh Kumar K.V  * initialized properly.
185364769240SAlex Tomas  */
18549c3569b5STao Ma int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
18552ed88685STheodore Ts'o 			   struct buffer_head *bh, int create)
185664769240SAlex Tomas {
18572ed88685STheodore Ts'o 	struct ext4_map_blocks map;
185864769240SAlex Tomas 	int ret = 0;
185964769240SAlex Tomas 
186064769240SAlex Tomas 	BUG_ON(create == 0);
18612ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
18622ed88685STheodore Ts'o 
18632ed88685STheodore Ts'o 	map.m_lblk = iblock;
18642ed88685STheodore Ts'o 	map.m_len = 1;
186564769240SAlex Tomas 
186664769240SAlex Tomas 	/*
186764769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
186864769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
186964769240SAlex Tomas 	 * the same as allocated blocks.
187064769240SAlex Tomas 	 */
18715356f261SAditya Kali 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
18725356f261SAditya Kali 	if (ret <= 0)
18732ed88685STheodore Ts'o 		return ret;
187464769240SAlex Tomas 
18752ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
1876ed8ad838SJan Kara 	ext4_update_bh_state(bh, map.m_flags);
18772ed88685STheodore Ts'o 
18782ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
18792ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
18802ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
18812ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
18822ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
18832ed88685STheodore Ts'o 		 * for partial write.
18842ed88685STheodore Ts'o 		 */
18852ed88685STheodore Ts'o 		set_buffer_new(bh);
1886c8205636STheodore Ts'o 		set_buffer_mapped(bh);
18872ed88685STheodore Ts'o 	}
18882ed88685STheodore Ts'o 	return 0;
188964769240SAlex Tomas }
189061628a3fSMingming Cao 
189162e086beSAneesh Kumar K.V static int bget_one(handle_t *handle, struct buffer_head *bh)
189262e086beSAneesh Kumar K.V {
189362e086beSAneesh Kumar K.V 	get_bh(bh);
189462e086beSAneesh Kumar K.V 	return 0;
189562e086beSAneesh Kumar K.V }
189662e086beSAneesh Kumar K.V 
189762e086beSAneesh Kumar K.V static int bput_one(handle_t *handle, struct buffer_head *bh)
189862e086beSAneesh Kumar K.V {
189962e086beSAneesh Kumar K.V 	put_bh(bh);
190062e086beSAneesh Kumar K.V 	return 0;
190162e086beSAneesh Kumar K.V }
190262e086beSAneesh Kumar K.V 
190362e086beSAneesh Kumar K.V static int __ext4_journalled_writepage(struct page *page,
190462e086beSAneesh Kumar K.V 				       unsigned int len)
190562e086beSAneesh Kumar K.V {
190662e086beSAneesh Kumar K.V 	struct address_space *mapping = page->mapping;
190762e086beSAneesh Kumar K.V 	struct inode *inode = mapping->host;
19083fdcfb66STao Ma 	struct buffer_head *page_bufs = NULL;
190962e086beSAneesh Kumar K.V 	handle_t *handle = NULL;
19103fdcfb66STao Ma 	int ret = 0, err = 0;
19113fdcfb66STao Ma 	int inline_data = ext4_has_inline_data(inode);
19123fdcfb66STao Ma 	struct buffer_head *inode_bh = NULL;
191362e086beSAneesh Kumar K.V 
1914cb20d518STheodore Ts'o 	ClearPageChecked(page);
19153fdcfb66STao Ma 
19163fdcfb66STao Ma 	if (inline_data) {
19173fdcfb66STao Ma 		BUG_ON(page->index != 0);
19183fdcfb66STao Ma 		BUG_ON(len > ext4_get_max_inline_size(inode));
19193fdcfb66STao Ma 		inode_bh = ext4_journalled_write_inline_data(inode, len, page);
19203fdcfb66STao Ma 		if (inode_bh == NULL)
19213fdcfb66STao Ma 			goto out;
19223fdcfb66STao Ma 	} else {
192362e086beSAneesh Kumar K.V 		page_bufs = page_buffers(page);
19243fdcfb66STao Ma 		if (!page_bufs) {
19253fdcfb66STao Ma 			BUG();
19263fdcfb66STao Ma 			goto out;
19273fdcfb66STao Ma 		}
19283fdcfb66STao Ma 		ext4_walk_page_buffers(handle, page_bufs, 0, len,
19293fdcfb66STao Ma 				       NULL, bget_one);
19303fdcfb66STao Ma 	}
1931bdf96838STheodore Ts'o 	/*
1932bdf96838STheodore Ts'o 	 * We need to release the page lock before we start the
1933bdf96838STheodore Ts'o 	 * journal, so grab a reference so the page won't disappear
1934bdf96838STheodore Ts'o 	 * out from under us.
1935bdf96838STheodore Ts'o 	 */
1936bdf96838STheodore Ts'o 	get_page(page);
193762e086beSAneesh Kumar K.V 	unlock_page(page);
193862e086beSAneesh Kumar K.V 
19399924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
19409924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
194162e086beSAneesh Kumar K.V 	if (IS_ERR(handle)) {
194262e086beSAneesh Kumar K.V 		ret = PTR_ERR(handle);
1943bdf96838STheodore Ts'o 		put_page(page);
1944bdf96838STheodore Ts'o 		goto out_no_pagelock;
1945bdf96838STheodore Ts'o 	}
1946bdf96838STheodore Ts'o 	BUG_ON(!ext4_handle_valid(handle));
1947bdf96838STheodore Ts'o 
1948bdf96838STheodore Ts'o 	lock_page(page);
1949bdf96838STheodore Ts'o 	put_page(page);
1950bdf96838STheodore Ts'o 	if (page->mapping != mapping) {
1951bdf96838STheodore Ts'o 		/* The page got truncated from under us */
1952bdf96838STheodore Ts'o 		ext4_journal_stop(handle);
1953bdf96838STheodore Ts'o 		ret = 0;
195462e086beSAneesh Kumar K.V 		goto out;
195562e086beSAneesh Kumar K.V 	}
195662e086beSAneesh Kumar K.V 
19573fdcfb66STao Ma 	if (inline_data) {
19585d601255Sliang xie 		BUFFER_TRACE(inode_bh, "get write access");
19593fdcfb66STao Ma 		ret = ext4_journal_get_write_access(handle, inode_bh);
19603fdcfb66STao Ma 
19613fdcfb66STao Ma 		err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
19623fdcfb66STao Ma 
19633fdcfb66STao Ma 	} else {
1964f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
196562e086beSAneesh Kumar K.V 					     do_journal_get_write_access);
196662e086beSAneesh Kumar K.V 
1967f19d5870STao Ma 		err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
196862e086beSAneesh Kumar K.V 					     write_end_fn);
19693fdcfb66STao Ma 	}
197062e086beSAneesh Kumar K.V 	if (ret == 0)
197162e086beSAneesh Kumar K.V 		ret = err;
19722d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
197362e086beSAneesh Kumar K.V 	err = ext4_journal_stop(handle);
197462e086beSAneesh Kumar K.V 	if (!ret)
197562e086beSAneesh Kumar K.V 		ret = err;
197662e086beSAneesh Kumar K.V 
19773fdcfb66STao Ma 	if (!ext4_has_inline_data(inode))
19788c9367fdSTheodore Ts'o 		ext4_walk_page_buffers(NULL, page_bufs, 0, len,
19793fdcfb66STao Ma 				       NULL, bput_one);
198019f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
198162e086beSAneesh Kumar K.V out:
1982bdf96838STheodore Ts'o 	unlock_page(page);
1983bdf96838STheodore Ts'o out_no_pagelock:
19843fdcfb66STao Ma 	brelse(inode_bh);
198562e086beSAneesh Kumar K.V 	return ret;
198662e086beSAneesh Kumar K.V }
198762e086beSAneesh Kumar K.V 
198861628a3fSMingming Cao /*
198943ce1d23SAneesh Kumar K.V  * Note that we don't need to start a transaction unless we're journaling data
199043ce1d23SAneesh Kumar K.V  * because we should have holes filled from ext4_page_mkwrite(). We even don't
199143ce1d23SAneesh Kumar K.V  * need to file the inode to the transaction's list in ordered mode because if
199243ce1d23SAneesh Kumar K.V  * we are writing back data added by write(), the inode is already there and if
199343ce1d23SAneesh Kumar K.V  * we are writing back data modified via mmap(), no one guarantees in which
199443ce1d23SAneesh Kumar K.V  * transaction the data will hit the disk. In case we are journaling data, we
199543ce1d23SAneesh Kumar K.V  * cannot start transaction directly because transaction start ranks above page
199643ce1d23SAneesh Kumar K.V  * lock so we have to do some magic.
199743ce1d23SAneesh Kumar K.V  *
1998b920c755STheodore Ts'o  * This function can get called via...
199920970ba6STheodore Ts'o  *   - ext4_writepages after taking page lock (have journal handle)
2000b920c755STheodore Ts'o  *   - journal_submit_inode_data_buffers (no journal handle)
2001f6463b0dSArtem Bityutskiy  *   - shrink_page_list via the kswapd/direct reclaim (no journal handle)
2002b920c755STheodore Ts'o  *   - grab_page_cache when doing write_begin (have journal handle)
200343ce1d23SAneesh Kumar K.V  *
200443ce1d23SAneesh Kumar K.V  * We don't do any block allocation in this function. If we have page with
200543ce1d23SAneesh Kumar K.V  * multiple blocks we need to write those buffer_heads that are mapped. This
200643ce1d23SAneesh Kumar K.V  * is important for mmaped based write. So if we do with blocksize 1K
200743ce1d23SAneesh Kumar K.V  * truncate(f, 1024);
200843ce1d23SAneesh Kumar K.V  * a = mmap(f, 0, 4096);
200943ce1d23SAneesh Kumar K.V  * a[0] = 'a';
201043ce1d23SAneesh Kumar K.V  * truncate(f, 4096);
201143ce1d23SAneesh Kumar K.V  * we have in the page first buffer_head mapped via page_mkwrite call back
201290802ed9SPaul Bolle  * but other buffer_heads would be unmapped but dirty (dirty done via the
201343ce1d23SAneesh Kumar K.V  * do_wp_page). So writepage should write the first block. If we modify
201443ce1d23SAneesh Kumar K.V  * the mmap area beyond 1024 we will again get a page_fault and the
201543ce1d23SAneesh Kumar K.V  * page_mkwrite callback will do the block allocation and mark the
201643ce1d23SAneesh Kumar K.V  * buffer_heads mapped.
201743ce1d23SAneesh Kumar K.V  *
201843ce1d23SAneesh Kumar K.V  * We redirty the page if we have any buffer_heads that is either delay or
201943ce1d23SAneesh Kumar K.V  * unwritten in the page.
202043ce1d23SAneesh Kumar K.V  *
202143ce1d23SAneesh Kumar K.V  * We can get recursively called as show below.
202243ce1d23SAneesh Kumar K.V  *
202343ce1d23SAneesh Kumar K.V  *	ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
202443ce1d23SAneesh Kumar K.V  *		ext4_writepage()
202543ce1d23SAneesh Kumar K.V  *
202643ce1d23SAneesh Kumar K.V  * But since we don't do any block allocation we should not deadlock.
202743ce1d23SAneesh Kumar K.V  * Page also have the dirty flag cleared so we don't get recurive page_lock.
202861628a3fSMingming Cao  */
202943ce1d23SAneesh Kumar K.V static int ext4_writepage(struct page *page,
203064769240SAlex Tomas 			  struct writeback_control *wbc)
203164769240SAlex Tomas {
2032f8bec370SJan Kara 	int ret = 0;
203361628a3fSMingming Cao 	loff_t size;
2034498e5f24STheodore Ts'o 	unsigned int len;
2035744692dcSJiaying Zhang 	struct buffer_head *page_bufs = NULL;
203661628a3fSMingming Cao 	struct inode *inode = page->mapping->host;
203736ade451SJan Kara 	struct ext4_io_submit io_submit;
20381c8349a1SNamjae Jeon 	bool keep_towrite = false;
203964769240SAlex Tomas 
2040a9c667f8SLukas Czerner 	trace_ext4_writepage(page);
204161628a3fSMingming Cao 	size = i_size_read(inode);
204209cbfeafSKirill A. Shutemov 	if (page->index == size >> PAGE_SHIFT)
204309cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
204461628a3fSMingming Cao 	else
204509cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
204661628a3fSMingming Cao 
2047f0e6c985SAneesh Kumar K.V 	page_bufs = page_buffers(page);
204864769240SAlex Tomas 	/*
2049fe386132SJan Kara 	 * We cannot do block allocation or other extent handling in this
2050fe386132SJan Kara 	 * function. If there are buffers needing that, we have to redirty
2051fe386132SJan Kara 	 * the page. But we may reach here when we do a journal commit via
2052fe386132SJan Kara 	 * journal_submit_inode_data_buffers() and in that case we must write
2053fe386132SJan Kara 	 * allocated buffers to achieve data=ordered mode guarantees.
2054cccd147aSTheodore Ts'o 	 *
2055cccd147aSTheodore Ts'o 	 * Also, if there is only one buffer per page (the fs block
2056cccd147aSTheodore Ts'o 	 * size == the page size), if one buffer needs block
2057cccd147aSTheodore Ts'o 	 * allocation or needs to modify the extent tree to clear the
2058cccd147aSTheodore Ts'o 	 * unwritten flag, we know that the page can't be written at
2059cccd147aSTheodore Ts'o 	 * all, so we might as well refuse the write immediately.
2060cccd147aSTheodore Ts'o 	 * Unfortunately if the block size != page size, we can't as
2061cccd147aSTheodore Ts'o 	 * easily detect this case using ext4_walk_page_buffers(), but
2062cccd147aSTheodore Ts'o 	 * for the extremely common case, this is an optimization that
2063cccd147aSTheodore Ts'o 	 * skips a useless round trip through ext4_bio_write_page().
206464769240SAlex Tomas 	 */
2065f19d5870STao Ma 	if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2066c364b22cSAneesh Kumar K.V 				   ext4_bh_delay_or_unwritten)) {
206761628a3fSMingming Cao 		redirty_page_for_writepage(wbc, page);
2068cccd147aSTheodore Ts'o 		if ((current->flags & PF_MEMALLOC) ||
206909cbfeafSKirill A. Shutemov 		    (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2070fe386132SJan Kara 			/*
2071fe386132SJan Kara 			 * For memory cleaning there's no point in writing only
2072fe386132SJan Kara 			 * some buffers. So just bail out. Warn if we came here
2073fe386132SJan Kara 			 * from direct reclaim.
2074fe386132SJan Kara 			 */
2075fe386132SJan Kara 			WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2076fe386132SJan Kara 							== PF_MEMALLOC);
207761628a3fSMingming Cao 			unlock_page(page);
207861628a3fSMingming Cao 			return 0;
207961628a3fSMingming Cao 		}
20801c8349a1SNamjae Jeon 		keep_towrite = true;
2081f0e6c985SAneesh Kumar K.V 	}
208264769240SAlex Tomas 
2083cb20d518STheodore Ts'o 	if (PageChecked(page) && ext4_should_journal_data(inode))
208443ce1d23SAneesh Kumar K.V 		/*
208543ce1d23SAneesh Kumar K.V 		 * It's mmapped pagecache.  Add buffers and journal it.  There
208643ce1d23SAneesh Kumar K.V 		 * doesn't seem much point in redirtying the page here.
208743ce1d23SAneesh Kumar K.V 		 */
20883f0ca309SWu Fengguang 		return __ext4_journalled_writepage(page, len);
208943ce1d23SAneesh Kumar K.V 
209097a851edSJan Kara 	ext4_io_submit_init(&io_submit, wbc);
209197a851edSJan Kara 	io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
209297a851edSJan Kara 	if (!io_submit.io_end) {
209397a851edSJan Kara 		redirty_page_for_writepage(wbc, page);
209497a851edSJan Kara 		unlock_page(page);
209597a851edSJan Kara 		return -ENOMEM;
209697a851edSJan Kara 	}
20971c8349a1SNamjae Jeon 	ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
209836ade451SJan Kara 	ext4_io_submit(&io_submit);
209997a851edSJan Kara 	/* Drop io_end reference we got from init */
210097a851edSJan Kara 	ext4_put_io_end_defer(io_submit.io_end);
210164769240SAlex Tomas 	return ret;
210264769240SAlex Tomas }
210364769240SAlex Tomas 
21045f1132b2SJan Kara static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
21055f1132b2SJan Kara {
21065f1132b2SJan Kara 	int len;
21075f1132b2SJan Kara 	loff_t size = i_size_read(mpd->inode);
21085f1132b2SJan Kara 	int err;
21095f1132b2SJan Kara 
21105f1132b2SJan Kara 	BUG_ON(page->index != mpd->first_page);
211109cbfeafSKirill A. Shutemov 	if (page->index == size >> PAGE_SHIFT)
211209cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
21135f1132b2SJan Kara 	else
211409cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
21155f1132b2SJan Kara 	clear_page_dirty_for_io(page);
21161c8349a1SNamjae Jeon 	err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
21175f1132b2SJan Kara 	if (!err)
21185f1132b2SJan Kara 		mpd->wbc->nr_to_write--;
21195f1132b2SJan Kara 	mpd->first_page++;
21205f1132b2SJan Kara 
21215f1132b2SJan Kara 	return err;
21225f1132b2SJan Kara }
21235f1132b2SJan Kara 
21244e7ea81dSJan Kara #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
21254e7ea81dSJan Kara 
212661628a3fSMingming Cao /*
2127fffb2739SJan Kara  * mballoc gives us at most this number of blocks...
2128fffb2739SJan Kara  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2129fffb2739SJan Kara  * The rest of mballoc seems to handle chunks up to full group size.
213061628a3fSMingming Cao  */
2131fffb2739SJan Kara #define MAX_WRITEPAGES_EXTENT_LEN 2048
2132525f4ed8SMingming Cao 
2133525f4ed8SMingming Cao /*
21344e7ea81dSJan Kara  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
21354e7ea81dSJan Kara  *
21364e7ea81dSJan Kara  * @mpd - extent of blocks
21374e7ea81dSJan Kara  * @lblk - logical number of the block in the file
213809930042SJan Kara  * @bh - buffer head we want to add to the extent
21394e7ea81dSJan Kara  *
214009930042SJan Kara  * The function is used to collect contig. blocks in the same state. If the
214109930042SJan Kara  * buffer doesn't require mapping for writeback and we haven't started the
214209930042SJan Kara  * extent of buffers to map yet, the function returns 'true' immediately - the
214309930042SJan Kara  * caller can write the buffer right away. Otherwise the function returns true
214409930042SJan Kara  * if the block has been added to the extent, false if the block couldn't be
214509930042SJan Kara  * added.
21464e7ea81dSJan Kara  */
214709930042SJan Kara static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
214809930042SJan Kara 				   struct buffer_head *bh)
21494e7ea81dSJan Kara {
21504e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
21514e7ea81dSJan Kara 
215209930042SJan Kara 	/* Buffer that doesn't need mapping for writeback? */
215309930042SJan Kara 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
215409930042SJan Kara 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
215509930042SJan Kara 		/* So far no extent to map => we write the buffer right away */
215609930042SJan Kara 		if (map->m_len == 0)
215709930042SJan Kara 			return true;
215809930042SJan Kara 		return false;
215909930042SJan Kara 	}
21604e7ea81dSJan Kara 
21614e7ea81dSJan Kara 	/* First block in the extent? */
21624e7ea81dSJan Kara 	if (map->m_len == 0) {
21634e7ea81dSJan Kara 		map->m_lblk = lblk;
21644e7ea81dSJan Kara 		map->m_len = 1;
216509930042SJan Kara 		map->m_flags = bh->b_state & BH_FLAGS;
216609930042SJan Kara 		return true;
21674e7ea81dSJan Kara 	}
21684e7ea81dSJan Kara 
216909930042SJan Kara 	/* Don't go larger than mballoc is willing to allocate */
217009930042SJan Kara 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
217109930042SJan Kara 		return false;
217209930042SJan Kara 
21734e7ea81dSJan Kara 	/* Can we merge the block to our big extent? */
21744e7ea81dSJan Kara 	if (lblk == map->m_lblk + map->m_len &&
217509930042SJan Kara 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
21764e7ea81dSJan Kara 		map->m_len++;
217709930042SJan Kara 		return true;
21784e7ea81dSJan Kara 	}
217909930042SJan Kara 	return false;
21804e7ea81dSJan Kara }
21814e7ea81dSJan Kara 
21825f1132b2SJan Kara /*
21835f1132b2SJan Kara  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
21845f1132b2SJan Kara  *
21855f1132b2SJan Kara  * @mpd - extent of blocks for mapping
21865f1132b2SJan Kara  * @head - the first buffer in the page
21875f1132b2SJan Kara  * @bh - buffer we should start processing from
21885f1132b2SJan Kara  * @lblk - logical number of the block in the file corresponding to @bh
21895f1132b2SJan Kara  *
21905f1132b2SJan Kara  * Walk through page buffers from @bh upto @head (exclusive) and either submit
21915f1132b2SJan Kara  * the page for IO if all buffers in this page were mapped and there's no
21925f1132b2SJan Kara  * accumulated extent of buffers to map or add buffers in the page to the
21935f1132b2SJan Kara  * extent of buffers to map. The function returns 1 if the caller can continue
21945f1132b2SJan Kara  * by processing the next page, 0 if it should stop adding buffers to the
21955f1132b2SJan Kara  * extent to map because we cannot extend it anymore. It can also return value
21965f1132b2SJan Kara  * < 0 in case of error during IO submission.
21975f1132b2SJan Kara  */
21985f1132b2SJan Kara static int mpage_process_page_bufs(struct mpage_da_data *mpd,
21994e7ea81dSJan Kara 				   struct buffer_head *head,
22004e7ea81dSJan Kara 				   struct buffer_head *bh,
22014e7ea81dSJan Kara 				   ext4_lblk_t lblk)
22024e7ea81dSJan Kara {
22034e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
22045f1132b2SJan Kara 	int err;
22054e7ea81dSJan Kara 	ext4_lblk_t blocks = (i_size_read(inode) + (1 << inode->i_blkbits) - 1)
22064e7ea81dSJan Kara 							>> inode->i_blkbits;
22074e7ea81dSJan Kara 
22084e7ea81dSJan Kara 	do {
22094e7ea81dSJan Kara 		BUG_ON(buffer_locked(bh));
22104e7ea81dSJan Kara 
221109930042SJan Kara 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
22124e7ea81dSJan Kara 			/* Found extent to map? */
22134e7ea81dSJan Kara 			if (mpd->map.m_len)
22145f1132b2SJan Kara 				return 0;
221509930042SJan Kara 			/* Everything mapped so far and we hit EOF */
22165f1132b2SJan Kara 			break;
22174e7ea81dSJan Kara 		}
22184e7ea81dSJan Kara 	} while (lblk++, (bh = bh->b_this_page) != head);
22195f1132b2SJan Kara 	/* So far everything mapped? Submit the page for IO. */
22205f1132b2SJan Kara 	if (mpd->map.m_len == 0) {
22215f1132b2SJan Kara 		err = mpage_submit_page(mpd, head->b_page);
22225f1132b2SJan Kara 		if (err < 0)
22234e7ea81dSJan Kara 			return err;
22244e7ea81dSJan Kara 	}
22255f1132b2SJan Kara 	return lblk < blocks;
22265f1132b2SJan Kara }
22274e7ea81dSJan Kara 
22284e7ea81dSJan Kara /*
22294e7ea81dSJan Kara  * mpage_map_buffers - update buffers corresponding to changed extent and
22304e7ea81dSJan Kara  *		       submit fully mapped pages for IO
22314e7ea81dSJan Kara  *
22324e7ea81dSJan Kara  * @mpd - description of extent to map, on return next extent to map
22334e7ea81dSJan Kara  *
22344e7ea81dSJan Kara  * Scan buffers corresponding to changed extent (we expect corresponding pages
22354e7ea81dSJan Kara  * to be already locked) and update buffer state according to new extent state.
22364e7ea81dSJan Kara  * We map delalloc buffers to their physical location, clear unwritten bits,
2237556615dcSLukas Czerner  * and mark buffers as uninit when we perform writes to unwritten extents
22384e7ea81dSJan Kara  * and do extent conversion after IO is finished. If the last page is not fully
22394e7ea81dSJan Kara  * mapped, we update @map to the next extent in the last page that needs
22404e7ea81dSJan Kara  * mapping. Otherwise we submit the page for IO.
22414e7ea81dSJan Kara  */
22424e7ea81dSJan Kara static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
22434e7ea81dSJan Kara {
22444e7ea81dSJan Kara 	struct pagevec pvec;
22454e7ea81dSJan Kara 	int nr_pages, i;
22464e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
22474e7ea81dSJan Kara 	struct buffer_head *head, *bh;
224809cbfeafSKirill A. Shutemov 	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
22494e7ea81dSJan Kara 	pgoff_t start, end;
22504e7ea81dSJan Kara 	ext4_lblk_t lblk;
22514e7ea81dSJan Kara 	sector_t pblock;
22524e7ea81dSJan Kara 	int err;
22534e7ea81dSJan Kara 
22544e7ea81dSJan Kara 	start = mpd->map.m_lblk >> bpp_bits;
22554e7ea81dSJan Kara 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
22564e7ea81dSJan Kara 	lblk = start << bpp_bits;
22574e7ea81dSJan Kara 	pblock = mpd->map.m_pblk;
22584e7ea81dSJan Kara 
22594e7ea81dSJan Kara 	pagevec_init(&pvec, 0);
22604e7ea81dSJan Kara 	while (start <= end) {
22614e7ea81dSJan Kara 		nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start,
22624e7ea81dSJan Kara 					  PAGEVEC_SIZE);
22634e7ea81dSJan Kara 		if (nr_pages == 0)
22644e7ea81dSJan Kara 			break;
22654e7ea81dSJan Kara 		for (i = 0; i < nr_pages; i++) {
22664e7ea81dSJan Kara 			struct page *page = pvec.pages[i];
22674e7ea81dSJan Kara 
22684e7ea81dSJan Kara 			if (page->index > end)
22694e7ea81dSJan Kara 				break;
22704e7ea81dSJan Kara 			/* Up to 'end' pages must be contiguous */
22714e7ea81dSJan Kara 			BUG_ON(page->index != start);
22724e7ea81dSJan Kara 			bh = head = page_buffers(page);
22734e7ea81dSJan Kara 			do {
22744e7ea81dSJan Kara 				if (lblk < mpd->map.m_lblk)
22754e7ea81dSJan Kara 					continue;
22764e7ea81dSJan Kara 				if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
22774e7ea81dSJan Kara 					/*
22784e7ea81dSJan Kara 					 * Buffer after end of mapped extent.
22794e7ea81dSJan Kara 					 * Find next buffer in the page to map.
22804e7ea81dSJan Kara 					 */
22814e7ea81dSJan Kara 					mpd->map.m_len = 0;
22824e7ea81dSJan Kara 					mpd->map.m_flags = 0;
22835f1132b2SJan Kara 					/*
22845f1132b2SJan Kara 					 * FIXME: If dioread_nolock supports
22855f1132b2SJan Kara 					 * blocksize < pagesize, we need to make
22865f1132b2SJan Kara 					 * sure we add size mapped so far to
22875f1132b2SJan Kara 					 * io_end->size as the following call
22885f1132b2SJan Kara 					 * can submit the page for IO.
22895f1132b2SJan Kara 					 */
22905f1132b2SJan Kara 					err = mpage_process_page_bufs(mpd, head,
22915f1132b2SJan Kara 								      bh, lblk);
22924e7ea81dSJan Kara 					pagevec_release(&pvec);
22935f1132b2SJan Kara 					if (err > 0)
22945f1132b2SJan Kara 						err = 0;
22955f1132b2SJan Kara 					return err;
22964e7ea81dSJan Kara 				}
22974e7ea81dSJan Kara 				if (buffer_delay(bh)) {
22984e7ea81dSJan Kara 					clear_buffer_delay(bh);
22994e7ea81dSJan Kara 					bh->b_blocknr = pblock++;
23004e7ea81dSJan Kara 				}
23014e7ea81dSJan Kara 				clear_buffer_unwritten(bh);
23025f1132b2SJan Kara 			} while (lblk++, (bh = bh->b_this_page) != head);
23034e7ea81dSJan Kara 
23044e7ea81dSJan Kara 			/*
23054e7ea81dSJan Kara 			 * FIXME: This is going to break if dioread_nolock
23064e7ea81dSJan Kara 			 * supports blocksize < pagesize as we will try to
23074e7ea81dSJan Kara 			 * convert potentially unmapped parts of inode.
23084e7ea81dSJan Kara 			 */
230909cbfeafSKirill A. Shutemov 			mpd->io_submit.io_end->size += PAGE_SIZE;
23104e7ea81dSJan Kara 			/* Page fully mapped - let IO run! */
23114e7ea81dSJan Kara 			err = mpage_submit_page(mpd, page);
23124e7ea81dSJan Kara 			if (err < 0) {
23134e7ea81dSJan Kara 				pagevec_release(&pvec);
23144e7ea81dSJan Kara 				return err;
23154e7ea81dSJan Kara 			}
23164e7ea81dSJan Kara 			start++;
23174e7ea81dSJan Kara 		}
23184e7ea81dSJan Kara 		pagevec_release(&pvec);
23194e7ea81dSJan Kara 	}
23204e7ea81dSJan Kara 	/* Extent fully mapped and matches with page boundary. We are done. */
23214e7ea81dSJan Kara 	mpd->map.m_len = 0;
23224e7ea81dSJan Kara 	mpd->map.m_flags = 0;
23234e7ea81dSJan Kara 	return 0;
23244e7ea81dSJan Kara }
23254e7ea81dSJan Kara 
23264e7ea81dSJan Kara static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
23274e7ea81dSJan Kara {
23284e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
23294e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
23304e7ea81dSJan Kara 	int get_blocks_flags;
2331090f32eeSLukas Czerner 	int err, dioread_nolock;
23324e7ea81dSJan Kara 
23334e7ea81dSJan Kara 	trace_ext4_da_write_pages_extent(inode, map);
23344e7ea81dSJan Kara 	/*
23354e7ea81dSJan Kara 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2336556615dcSLukas Czerner 	 * to convert an unwritten extent to be initialized (in the case
23374e7ea81dSJan Kara 	 * where we have written into one or more preallocated blocks).  It is
23384e7ea81dSJan Kara 	 * possible that we're going to need more metadata blocks than
23394e7ea81dSJan Kara 	 * previously reserved. However we must not fail because we're in
23404e7ea81dSJan Kara 	 * writeback and there is nothing we can do about it so it might result
23414e7ea81dSJan Kara 	 * in data loss.  So use reserved blocks to allocate metadata if
23424e7ea81dSJan Kara 	 * possible.
23434e7ea81dSJan Kara 	 *
2344754cfed6STheodore Ts'o 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2345754cfed6STheodore Ts'o 	 * the blocks in question are delalloc blocks.  This indicates
2346754cfed6STheodore Ts'o 	 * that the blocks and quotas has already been checked when
2347754cfed6STheodore Ts'o 	 * the data was copied into the page cache.
23484e7ea81dSJan Kara 	 */
23494e7ea81dSJan Kara 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2350ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2351ee0876bcSJan Kara 			   EXT4_GET_BLOCKS_IO_SUBMIT;
2352090f32eeSLukas Czerner 	dioread_nolock = ext4_should_dioread_nolock(inode);
2353090f32eeSLukas Czerner 	if (dioread_nolock)
23544e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
23554e7ea81dSJan Kara 	if (map->m_flags & (1 << BH_Delay))
23564e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
23574e7ea81dSJan Kara 
23584e7ea81dSJan Kara 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
23594e7ea81dSJan Kara 	if (err < 0)
23604e7ea81dSJan Kara 		return err;
2361090f32eeSLukas Czerner 	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
23626b523df4SJan Kara 		if (!mpd->io_submit.io_end->handle &&
23636b523df4SJan Kara 		    ext4_handle_valid(handle)) {
23646b523df4SJan Kara 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
23656b523df4SJan Kara 			handle->h_rsv_handle = NULL;
23666b523df4SJan Kara 		}
23673613d228SJan Kara 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
23686b523df4SJan Kara 	}
23694e7ea81dSJan Kara 
23704e7ea81dSJan Kara 	BUG_ON(map->m_len == 0);
23714e7ea81dSJan Kara 	if (map->m_flags & EXT4_MAP_NEW) {
237264e1c57fSJan Kara 		clean_bdev_aliases(inode->i_sb->s_bdev, map->m_pblk,
237364e1c57fSJan Kara 				   map->m_len);
23744e7ea81dSJan Kara 	}
23754e7ea81dSJan Kara 	return 0;
23764e7ea81dSJan Kara }
23774e7ea81dSJan Kara 
23784e7ea81dSJan Kara /*
23794e7ea81dSJan Kara  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
23804e7ea81dSJan Kara  *				 mpd->len and submit pages underlying it for IO
23814e7ea81dSJan Kara  *
23824e7ea81dSJan Kara  * @handle - handle for journal operations
23834e7ea81dSJan Kara  * @mpd - extent to map
23847534e854SJan Kara  * @give_up_on_write - we set this to true iff there is a fatal error and there
23857534e854SJan Kara  *                     is no hope of writing the data. The caller should discard
23867534e854SJan Kara  *                     dirty pages to avoid infinite loops.
23874e7ea81dSJan Kara  *
23884e7ea81dSJan Kara  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
23894e7ea81dSJan Kara  * delayed, blocks are allocated, if it is unwritten, we may need to convert
23904e7ea81dSJan Kara  * them to initialized or split the described range from larger unwritten
23914e7ea81dSJan Kara  * extent. Note that we need not map all the described range since allocation
23924e7ea81dSJan Kara  * can return less blocks or the range is covered by more unwritten extents. We
23934e7ea81dSJan Kara  * cannot map more because we are limited by reserved transaction credits. On
23944e7ea81dSJan Kara  * the other hand we always make sure that the last touched page is fully
23954e7ea81dSJan Kara  * mapped so that it can be written out (and thus forward progress is
23964e7ea81dSJan Kara  * guaranteed). After mapping we submit all mapped pages for IO.
23974e7ea81dSJan Kara  */
23984e7ea81dSJan Kara static int mpage_map_and_submit_extent(handle_t *handle,
2399cb530541STheodore Ts'o 				       struct mpage_da_data *mpd,
2400cb530541STheodore Ts'o 				       bool *give_up_on_write)
24014e7ea81dSJan Kara {
24024e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
24034e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
24044e7ea81dSJan Kara 	int err;
24054e7ea81dSJan Kara 	loff_t disksize;
24066603120eSDmitry Monakhov 	int progress = 0;
24074e7ea81dSJan Kara 
24084e7ea81dSJan Kara 	mpd->io_submit.io_end->offset =
24094e7ea81dSJan Kara 				((loff_t)map->m_lblk) << inode->i_blkbits;
241027d7c4edSJan Kara 	do {
24114e7ea81dSJan Kara 		err = mpage_map_one_extent(handle, mpd);
24124e7ea81dSJan Kara 		if (err < 0) {
24134e7ea81dSJan Kara 			struct super_block *sb = inode->i_sb;
24144e7ea81dSJan Kara 
2415cb530541STheodore Ts'o 			if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2416cb530541STheodore Ts'o 				goto invalidate_dirty_pages;
24174e7ea81dSJan Kara 			/*
2418cb530541STheodore Ts'o 			 * Let the uper layers retry transient errors.
2419cb530541STheodore Ts'o 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2420cb530541STheodore Ts'o 			 * is non-zero, a commit should free up blocks.
24214e7ea81dSJan Kara 			 */
2422cb530541STheodore Ts'o 			if ((err == -ENOMEM) ||
24236603120eSDmitry Monakhov 			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
24246603120eSDmitry Monakhov 				if (progress)
24256603120eSDmitry Monakhov 					goto update_disksize;
2426cb530541STheodore Ts'o 				return err;
24276603120eSDmitry Monakhov 			}
24284e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24294e7ea81dSJan Kara 				 "Delayed block allocation failed for "
24304e7ea81dSJan Kara 				 "inode %lu at logical offset %llu with"
24314e7ea81dSJan Kara 				 " max blocks %u with error %d",
24324e7ea81dSJan Kara 				 inode->i_ino,
24334e7ea81dSJan Kara 				 (unsigned long long)map->m_lblk,
2434cb530541STheodore Ts'o 				 (unsigned)map->m_len, -err);
24354e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
24364e7ea81dSJan Kara 				 "This should not happen!! Data will "
24374e7ea81dSJan Kara 				 "be lost\n");
24384e7ea81dSJan Kara 			if (err == -ENOSPC)
24394e7ea81dSJan Kara 				ext4_print_free_blocks(inode);
2440cb530541STheodore Ts'o 		invalidate_dirty_pages:
2441cb530541STheodore Ts'o 			*give_up_on_write = true;
24424e7ea81dSJan Kara 			return err;
24434e7ea81dSJan Kara 		}
24446603120eSDmitry Monakhov 		progress = 1;
24454e7ea81dSJan Kara 		/*
24464e7ea81dSJan Kara 		 * Update buffer state, submit mapped pages, and get us new
24474e7ea81dSJan Kara 		 * extent to map
24484e7ea81dSJan Kara 		 */
24494e7ea81dSJan Kara 		err = mpage_map_and_submit_buffers(mpd);
24504e7ea81dSJan Kara 		if (err < 0)
24516603120eSDmitry Monakhov 			goto update_disksize;
245227d7c4edSJan Kara 	} while (map->m_len);
24534e7ea81dSJan Kara 
24546603120eSDmitry Monakhov update_disksize:
2455622cad13STheodore Ts'o 	/*
2456622cad13STheodore Ts'o 	 * Update on-disk size after IO is submitted.  Races with
2457622cad13STheodore Ts'o 	 * truncate are avoided by checking i_size under i_data_sem.
2458622cad13STheodore Ts'o 	 */
245909cbfeafSKirill A. Shutemov 	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
24604e7ea81dSJan Kara 	if (disksize > EXT4_I(inode)->i_disksize) {
24614e7ea81dSJan Kara 		int err2;
2462622cad13STheodore Ts'o 		loff_t i_size;
24634e7ea81dSJan Kara 
2464622cad13STheodore Ts'o 		down_write(&EXT4_I(inode)->i_data_sem);
2465622cad13STheodore Ts'o 		i_size = i_size_read(inode);
2466622cad13STheodore Ts'o 		if (disksize > i_size)
2467622cad13STheodore Ts'o 			disksize = i_size;
2468622cad13STheodore Ts'o 		if (disksize > EXT4_I(inode)->i_disksize)
2469622cad13STheodore Ts'o 			EXT4_I(inode)->i_disksize = disksize;
2470622cad13STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
2471b907f2d5STheodore Ts'o 		err2 = ext4_mark_inode_dirty(handle, inode);
24724e7ea81dSJan Kara 		if (err2)
24734e7ea81dSJan Kara 			ext4_error(inode->i_sb,
24744e7ea81dSJan Kara 				   "Failed to mark inode %lu dirty",
24754e7ea81dSJan Kara 				   inode->i_ino);
24764e7ea81dSJan Kara 		if (!err)
24774e7ea81dSJan Kara 			err = err2;
24784e7ea81dSJan Kara 	}
24794e7ea81dSJan Kara 	return err;
24804e7ea81dSJan Kara }
24814e7ea81dSJan Kara 
24824e7ea81dSJan Kara /*
2483fffb2739SJan Kara  * Calculate the total number of credits to reserve for one writepages
248420970ba6STheodore Ts'o  * iteration. This is called from ext4_writepages(). We map an extent of
2485fffb2739SJan Kara  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2486fffb2739SJan Kara  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2487fffb2739SJan Kara  * bpp - 1 blocks in bpp different extents.
2488525f4ed8SMingming Cao  */
2489fffb2739SJan Kara static int ext4_da_writepages_trans_blocks(struct inode *inode)
2490fffb2739SJan Kara {
2491fffb2739SJan Kara 	int bpp = ext4_journal_blocks_per_page(inode);
2492525f4ed8SMingming Cao 
2493fffb2739SJan Kara 	return ext4_meta_trans_blocks(inode,
2494fffb2739SJan Kara 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2495525f4ed8SMingming Cao }
249661628a3fSMingming Cao 
24978e48dcfbSTheodore Ts'o /*
24984e7ea81dSJan Kara  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
24994e7ea81dSJan Kara  * 				 and underlying extent to map
25004e7ea81dSJan Kara  *
25014e7ea81dSJan Kara  * @mpd - where to look for pages
25024e7ea81dSJan Kara  *
25034e7ea81dSJan Kara  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
25044e7ea81dSJan Kara  * IO immediately. When we find a page which isn't mapped we start accumulating
25054e7ea81dSJan Kara  * extent of buffers underlying these pages that needs mapping (formed by
25064e7ea81dSJan Kara  * either delayed or unwritten buffers). We also lock the pages containing
25074e7ea81dSJan Kara  * these buffers. The extent found is returned in @mpd structure (starting at
25084e7ea81dSJan Kara  * mpd->lblk with length mpd->len blocks).
25094e7ea81dSJan Kara  *
25104e7ea81dSJan Kara  * Note that this function can attach bios to one io_end structure which are
25114e7ea81dSJan Kara  * neither logically nor physically contiguous. Although it may seem as an
25124e7ea81dSJan Kara  * unnecessary complication, it is actually inevitable in blocksize < pagesize
25134e7ea81dSJan Kara  * case as we need to track IO to all buffers underlying a page in one io_end.
25148e48dcfbSTheodore Ts'o  */
25154e7ea81dSJan Kara static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
25168e48dcfbSTheodore Ts'o {
25174e7ea81dSJan Kara 	struct address_space *mapping = mpd->inode->i_mapping;
25188e48dcfbSTheodore Ts'o 	struct pagevec pvec;
25194f01b02cSTheodore Ts'o 	unsigned int nr_pages;
2520aeac589aSMing Lei 	long left = mpd->wbc->nr_to_write;
25214e7ea81dSJan Kara 	pgoff_t index = mpd->first_page;
25224e7ea81dSJan Kara 	pgoff_t end = mpd->last_page;
25234e7ea81dSJan Kara 	int tag;
25244e7ea81dSJan Kara 	int i, err = 0;
25254e7ea81dSJan Kara 	int blkbits = mpd->inode->i_blkbits;
25264e7ea81dSJan Kara 	ext4_lblk_t lblk;
25274e7ea81dSJan Kara 	struct buffer_head *head;
25288e48dcfbSTheodore Ts'o 
25294e7ea81dSJan Kara 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
25305b41d924SEric Sandeen 		tag = PAGECACHE_TAG_TOWRITE;
25315b41d924SEric Sandeen 	else
25325b41d924SEric Sandeen 		tag = PAGECACHE_TAG_DIRTY;
25335b41d924SEric Sandeen 
25344e7ea81dSJan Kara 	pagevec_init(&pvec, 0);
25354e7ea81dSJan Kara 	mpd->map.m_len = 0;
25364e7ea81dSJan Kara 	mpd->next_page = index;
25374f01b02cSTheodore Ts'o 	while (index <= end) {
25385b41d924SEric Sandeen 		nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
25398e48dcfbSTheodore Ts'o 			      min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
25408e48dcfbSTheodore Ts'o 		if (nr_pages == 0)
25414e7ea81dSJan Kara 			goto out;
25428e48dcfbSTheodore Ts'o 
25438e48dcfbSTheodore Ts'o 		for (i = 0; i < nr_pages; i++) {
25448e48dcfbSTheodore Ts'o 			struct page *page = pvec.pages[i];
25458e48dcfbSTheodore Ts'o 
25468e48dcfbSTheodore Ts'o 			/*
25478e48dcfbSTheodore Ts'o 			 * At this point, the page may be truncated or
25488e48dcfbSTheodore Ts'o 			 * invalidated (changing page->mapping to NULL), or
25498e48dcfbSTheodore Ts'o 			 * even swizzled back from swapper_space to tmpfs file
25508e48dcfbSTheodore Ts'o 			 * mapping. However, page->index will not change
25518e48dcfbSTheodore Ts'o 			 * because we have a reference on the page.
25528e48dcfbSTheodore Ts'o 			 */
25534f01b02cSTheodore Ts'o 			if (page->index > end)
25544f01b02cSTheodore Ts'o 				goto out;
25558e48dcfbSTheodore Ts'o 
2556aeac589aSMing Lei 			/*
2557aeac589aSMing Lei 			 * Accumulated enough dirty pages? This doesn't apply
2558aeac589aSMing Lei 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2559aeac589aSMing Lei 			 * keep going because someone may be concurrently
2560aeac589aSMing Lei 			 * dirtying pages, and we might have synced a lot of
2561aeac589aSMing Lei 			 * newly appeared dirty pages, but have not synced all
2562aeac589aSMing Lei 			 * of the old dirty pages.
2563aeac589aSMing Lei 			 */
2564aeac589aSMing Lei 			if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2565aeac589aSMing Lei 				goto out;
2566aeac589aSMing Lei 
25674e7ea81dSJan Kara 			/* If we can't merge this page, we are done. */
25684e7ea81dSJan Kara 			if (mpd->map.m_len > 0 && mpd->next_page != page->index)
25694e7ea81dSJan Kara 				goto out;
257078aaced3STheodore Ts'o 
25718e48dcfbSTheodore Ts'o 			lock_page(page);
25728e48dcfbSTheodore Ts'o 			/*
25734e7ea81dSJan Kara 			 * If the page is no longer dirty, or its mapping no
25744e7ea81dSJan Kara 			 * longer corresponds to inode we are writing (which
25754e7ea81dSJan Kara 			 * means it has been truncated or invalidated), or the
25764e7ea81dSJan Kara 			 * page is already under writeback and we are not doing
25774e7ea81dSJan Kara 			 * a data integrity writeback, skip the page
25788e48dcfbSTheodore Ts'o 			 */
25794f01b02cSTheodore Ts'o 			if (!PageDirty(page) ||
25804f01b02cSTheodore Ts'o 			    (PageWriteback(page) &&
25814e7ea81dSJan Kara 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
25824f01b02cSTheodore Ts'o 			    unlikely(page->mapping != mapping)) {
25838e48dcfbSTheodore Ts'o 				unlock_page(page);
25848e48dcfbSTheodore Ts'o 				continue;
25858e48dcfbSTheodore Ts'o 			}
25868e48dcfbSTheodore Ts'o 
25878e48dcfbSTheodore Ts'o 			wait_on_page_writeback(page);
25888e48dcfbSTheodore Ts'o 			BUG_ON(PageWriteback(page));
25898e48dcfbSTheodore Ts'o 
25904e7ea81dSJan Kara 			if (mpd->map.m_len == 0)
25918eb9e5ceSTheodore Ts'o 				mpd->first_page = page->index;
25928eb9e5ceSTheodore Ts'o 			mpd->next_page = page->index + 1;
2593f8bec370SJan Kara 			/* Add all dirty buffers to mpd */
25944e7ea81dSJan Kara 			lblk = ((ext4_lblk_t)page->index) <<
259509cbfeafSKirill A. Shutemov 				(PAGE_SHIFT - blkbits);
25968eb9e5ceSTheodore Ts'o 			head = page_buffers(page);
25975f1132b2SJan Kara 			err = mpage_process_page_bufs(mpd, head, head, lblk);
25985f1132b2SJan Kara 			if (err <= 0)
25994e7ea81dSJan Kara 				goto out;
26005f1132b2SJan Kara 			err = 0;
2601aeac589aSMing Lei 			left--;
26028e48dcfbSTheodore Ts'o 		}
26038e48dcfbSTheodore Ts'o 		pagevec_release(&pvec);
26048e48dcfbSTheodore Ts'o 		cond_resched();
26058e48dcfbSTheodore Ts'o 	}
26064f01b02cSTheodore Ts'o 	return 0;
26078eb9e5ceSTheodore Ts'o out:
26088eb9e5ceSTheodore Ts'o 	pagevec_release(&pvec);
26094e7ea81dSJan Kara 	return err;
26108e48dcfbSTheodore Ts'o }
26118e48dcfbSTheodore Ts'o 
261220970ba6STheodore Ts'o static int __writepage(struct page *page, struct writeback_control *wbc,
261320970ba6STheodore Ts'o 		       void *data)
261420970ba6STheodore Ts'o {
261520970ba6STheodore Ts'o 	struct address_space *mapping = data;
261620970ba6STheodore Ts'o 	int ret = ext4_writepage(page, wbc);
261720970ba6STheodore Ts'o 	mapping_set_error(mapping, ret);
261820970ba6STheodore Ts'o 	return ret;
261920970ba6STheodore Ts'o }
262020970ba6STheodore Ts'o 
262120970ba6STheodore Ts'o static int ext4_writepages(struct address_space *mapping,
262264769240SAlex Tomas 			   struct writeback_control *wbc)
262364769240SAlex Tomas {
26244e7ea81dSJan Kara 	pgoff_t	writeback_index = 0;
26254e7ea81dSJan Kara 	long nr_to_write = wbc->nr_to_write;
262622208dedSAneesh Kumar K.V 	int range_whole = 0;
26274e7ea81dSJan Kara 	int cycled = 1;
262861628a3fSMingming Cao 	handle_t *handle = NULL;
2629df22291fSAneesh Kumar K.V 	struct mpage_da_data mpd;
26305e745b04SAneesh Kumar K.V 	struct inode *inode = mapping->host;
26316b523df4SJan Kara 	int needed_blocks, rsv_blocks = 0, ret = 0;
26325e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
26334e7ea81dSJan Kara 	bool done;
26341bce63d1SShaohua Li 	struct blk_plug plug;
2635cb530541STheodore Ts'o 	bool give_up_on_write = false;
263661628a3fSMingming Cao 
2637c8585c6fSDaeho Jeong 	percpu_down_read(&sbi->s_journal_flag_rwsem);
263820970ba6STheodore Ts'o 	trace_ext4_writepages(inode, wbc);
2639ba80b101STheodore Ts'o 
2640c8585c6fSDaeho Jeong 	if (dax_mapping(mapping)) {
2641c8585c6fSDaeho Jeong 		ret = dax_writeback_mapping_range(mapping, inode->i_sb->s_bdev,
26427f6d5b52SRoss Zwisler 						  wbc);
2643c8585c6fSDaeho Jeong 		goto out_writepages;
2644c8585c6fSDaeho Jeong 	}
26457f6d5b52SRoss Zwisler 
264661628a3fSMingming Cao 	/*
264761628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
264861628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
264961628a3fSMingming Cao 	 * because that could violate lock ordering on umount
265061628a3fSMingming Cao 	 */
2651a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2652bbf023c7SMing Lei 		goto out_writepages;
26532a21e37eSTheodore Ts'o 
265420970ba6STheodore Ts'o 	if (ext4_should_journal_data(inode)) {
265520970ba6STheodore Ts'o 		struct blk_plug plug;
265620970ba6STheodore Ts'o 
265720970ba6STheodore Ts'o 		blk_start_plug(&plug);
265820970ba6STheodore Ts'o 		ret = write_cache_pages(mapping, wbc, __writepage, mapping);
265920970ba6STheodore Ts'o 		blk_finish_plug(&plug);
2660bbf023c7SMing Lei 		goto out_writepages;
266120970ba6STheodore Ts'o 	}
266220970ba6STheodore Ts'o 
26632a21e37eSTheodore Ts'o 	/*
26642a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
26652a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
26662a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
26674ab2f15bSTheodore Ts'o 	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
26682a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
266920970ba6STheodore Ts'o 	 * read-only, and in that case, ext4_writepages should
26702a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
26712a21e37eSTheodore Ts'o 	 * the stack trace.
26722a21e37eSTheodore Ts'o 	 */
2673bbf023c7SMing Lei 	if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2674bbf023c7SMing Lei 		ret = -EROFS;
2675bbf023c7SMing Lei 		goto out_writepages;
2676bbf023c7SMing Lei 	}
26772a21e37eSTheodore Ts'o 
26786b523df4SJan Kara 	if (ext4_should_dioread_nolock(inode)) {
26796b523df4SJan Kara 		/*
26806b523df4SJan Kara 		 * We may need to convert up to one extent per block in
26816b523df4SJan Kara 		 * the page and we may dirty the inode.
26826b523df4SJan Kara 		 */
268309cbfeafSKirill A. Shutemov 		rsv_blocks = 1 + (PAGE_SIZE >> inode->i_blkbits);
26846b523df4SJan Kara 	}
26856b523df4SJan Kara 
26864e7ea81dSJan Kara 	/*
26874e7ea81dSJan Kara 	 * If we have inline data and arrive here, it means that
26884e7ea81dSJan Kara 	 * we will soon create the block for the 1st page, so
26894e7ea81dSJan Kara 	 * we'd better clear the inline data here.
26904e7ea81dSJan Kara 	 */
26914e7ea81dSJan Kara 	if (ext4_has_inline_data(inode)) {
26924e7ea81dSJan Kara 		/* Just inode will be modified... */
26934e7ea81dSJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
26944e7ea81dSJan Kara 		if (IS_ERR(handle)) {
26954e7ea81dSJan Kara 			ret = PTR_ERR(handle);
26964e7ea81dSJan Kara 			goto out_writepages;
26974e7ea81dSJan Kara 		}
26984e7ea81dSJan Kara 		BUG_ON(ext4_test_inode_state(inode,
26994e7ea81dSJan Kara 				EXT4_STATE_MAY_INLINE_DATA));
27004e7ea81dSJan Kara 		ext4_destroy_inline_data(handle, inode);
27014e7ea81dSJan Kara 		ext4_journal_stop(handle);
27024e7ea81dSJan Kara 	}
27034e7ea81dSJan Kara 
270422208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
270522208dedSAneesh Kumar K.V 		range_whole = 1;
270661628a3fSMingming Cao 
27072acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
27084e7ea81dSJan Kara 		writeback_index = mapping->writeback_index;
27094e7ea81dSJan Kara 		if (writeback_index)
27102acf2c26SAneesh Kumar K.V 			cycled = 0;
27114e7ea81dSJan Kara 		mpd.first_page = writeback_index;
27124e7ea81dSJan Kara 		mpd.last_page = -1;
27135b41d924SEric Sandeen 	} else {
271409cbfeafSKirill A. Shutemov 		mpd.first_page = wbc->range_start >> PAGE_SHIFT;
271509cbfeafSKirill A. Shutemov 		mpd.last_page = wbc->range_end >> PAGE_SHIFT;
27165b41d924SEric Sandeen 	}
2717a1d6cc56SAneesh Kumar K.V 
27184e7ea81dSJan Kara 	mpd.inode = inode;
27194e7ea81dSJan Kara 	mpd.wbc = wbc;
27204e7ea81dSJan Kara 	ext4_io_submit_init(&mpd.io_submit, wbc);
27212acf2c26SAneesh Kumar K.V retry:
27226e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
27234e7ea81dSJan Kara 		tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
27244e7ea81dSJan Kara 	done = false;
27251bce63d1SShaohua Li 	blk_start_plug(&plug);
27264e7ea81dSJan Kara 	while (!done && mpd.first_page <= mpd.last_page) {
27274e7ea81dSJan Kara 		/* For each extent of pages we use new io_end */
27284e7ea81dSJan Kara 		mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
27294e7ea81dSJan Kara 		if (!mpd.io_submit.io_end) {
27304e7ea81dSJan Kara 			ret = -ENOMEM;
27314e7ea81dSJan Kara 			break;
27324e7ea81dSJan Kara 		}
2733a1d6cc56SAneesh Kumar K.V 
2734a1d6cc56SAneesh Kumar K.V 		/*
27354e7ea81dSJan Kara 		 * We have two constraints: We find one extent to map and we
27364e7ea81dSJan Kara 		 * must always write out whole page (makes a difference when
27374e7ea81dSJan Kara 		 * blocksize < pagesize) so that we don't block on IO when we
27384e7ea81dSJan Kara 		 * try to write out the rest of the page. Journalled mode is
27394e7ea81dSJan Kara 		 * not supported by delalloc.
2740a1d6cc56SAneesh Kumar K.V 		 */
2741a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
2742525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2743a1d6cc56SAneesh Kumar K.V 
274461628a3fSMingming Cao 		/* start a new transaction */
27456b523df4SJan Kara 		handle = ext4_journal_start_with_reserve(inode,
27466b523df4SJan Kara 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
274761628a3fSMingming Cao 		if (IS_ERR(handle)) {
274861628a3fSMingming Cao 			ret = PTR_ERR(handle);
27491693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2750fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
2751a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
27524e7ea81dSJan Kara 			/* Release allocated io_end */
27534e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
27544e7ea81dSJan Kara 			break;
275561628a3fSMingming Cao 		}
2756f63e6005STheodore Ts'o 
27574e7ea81dSJan Kara 		trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
27584e7ea81dSJan Kara 		ret = mpage_prepare_extent_to_map(&mpd);
27594e7ea81dSJan Kara 		if (!ret) {
27604e7ea81dSJan Kara 			if (mpd.map.m_len)
2761cb530541STheodore Ts'o 				ret = mpage_map_and_submit_extent(handle, &mpd,
2762cb530541STheodore Ts'o 					&give_up_on_write);
27634e7ea81dSJan Kara 			else {
2764f63e6005STheodore Ts'o 				/*
27654e7ea81dSJan Kara 				 * We scanned the whole range (or exhausted
27664e7ea81dSJan Kara 				 * nr_to_write), submitted what was mapped and
27674e7ea81dSJan Kara 				 * didn't find anything needing mapping. We are
27684e7ea81dSJan Kara 				 * done.
2769f63e6005STheodore Ts'o 				 */
27704e7ea81dSJan Kara 				done = true;
2771f63e6005STheodore Ts'o 			}
27724e7ea81dSJan Kara 		}
2773646caa9cSJan Kara 		/*
2774646caa9cSJan Kara 		 * Caution: If the handle is synchronous,
2775646caa9cSJan Kara 		 * ext4_journal_stop() can wait for transaction commit
2776646caa9cSJan Kara 		 * to finish which may depend on writeback of pages to
2777646caa9cSJan Kara 		 * complete or on page lock to be released.  In that
2778646caa9cSJan Kara 		 * case, we have to wait until after after we have
2779646caa9cSJan Kara 		 * submitted all the IO, released page locks we hold,
2780646caa9cSJan Kara 		 * and dropped io_end reference (for extent conversion
2781646caa9cSJan Kara 		 * to be able to complete) before stopping the handle.
2782646caa9cSJan Kara 		 */
2783646caa9cSJan Kara 		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
278461628a3fSMingming Cao 			ext4_journal_stop(handle);
2785646caa9cSJan Kara 			handle = NULL;
2786646caa9cSJan Kara 		}
27874e7ea81dSJan Kara 		/* Submit prepared bio */
27884e7ea81dSJan Kara 		ext4_io_submit(&mpd.io_submit);
27894e7ea81dSJan Kara 		/* Unlock pages we didn't use */
2790cb530541STheodore Ts'o 		mpage_release_unused_pages(&mpd, give_up_on_write);
2791646caa9cSJan Kara 		/*
2792646caa9cSJan Kara 		 * Drop our io_end reference we got from init. We have
2793646caa9cSJan Kara 		 * to be careful and use deferred io_end finishing if
2794646caa9cSJan Kara 		 * we are still holding the transaction as we can
2795646caa9cSJan Kara 		 * release the last reference to io_end which may end
2796646caa9cSJan Kara 		 * up doing unwritten extent conversion.
2797646caa9cSJan Kara 		 */
2798646caa9cSJan Kara 		if (handle) {
2799646caa9cSJan Kara 			ext4_put_io_end_defer(mpd.io_submit.io_end);
2800646caa9cSJan Kara 			ext4_journal_stop(handle);
2801646caa9cSJan Kara 		} else
28024e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
2803df22291fSAneesh Kumar K.V 
28044e7ea81dSJan Kara 		if (ret == -ENOSPC && sbi->s_journal) {
28054e7ea81dSJan Kara 			/*
28064e7ea81dSJan Kara 			 * Commit the transaction which would
280722208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
280822208dedSAneesh Kumar K.V 			 * and try again
280922208dedSAneesh Kumar K.V 			 */
2810df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
281122208dedSAneesh Kumar K.V 			ret = 0;
28124e7ea81dSJan Kara 			continue;
28134e7ea81dSJan Kara 		}
28144e7ea81dSJan Kara 		/* Fatal error - ENOMEM, EIO... */
28154e7ea81dSJan Kara 		if (ret)
281661628a3fSMingming Cao 			break;
281761628a3fSMingming Cao 	}
28181bce63d1SShaohua Li 	blk_finish_plug(&plug);
28199c12a831SJan Kara 	if (!ret && !cycled && wbc->nr_to_write > 0) {
28202acf2c26SAneesh Kumar K.V 		cycled = 1;
28214e7ea81dSJan Kara 		mpd.last_page = writeback_index - 1;
28224e7ea81dSJan Kara 		mpd.first_page = 0;
28232acf2c26SAneesh Kumar K.V 		goto retry;
28242acf2c26SAneesh Kumar K.V 	}
282561628a3fSMingming Cao 
282622208dedSAneesh Kumar K.V 	/* Update index */
282722208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
282822208dedSAneesh Kumar K.V 		/*
28294e7ea81dSJan Kara 		 * Set the writeback_index so that range_cyclic
283022208dedSAneesh Kumar K.V 		 * mode will write it back later
283122208dedSAneesh Kumar K.V 		 */
28324e7ea81dSJan Kara 		mapping->writeback_index = mpd.first_page;
2833a1d6cc56SAneesh Kumar K.V 
283461628a3fSMingming Cao out_writepages:
283520970ba6STheodore Ts'o 	trace_ext4_writepages_result(inode, wbc, ret,
28364e7ea81dSJan Kara 				     nr_to_write - wbc->nr_to_write);
2837c8585c6fSDaeho Jeong 	percpu_up_read(&sbi->s_journal_flag_rwsem);
283861628a3fSMingming Cao 	return ret;
283964769240SAlex Tomas }
284064769240SAlex Tomas 
284179f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
284279f0be8dSAneesh Kumar K.V {
28435c1ff336SEric Whitney 	s64 free_clusters, dirty_clusters;
284479f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
284579f0be8dSAneesh Kumar K.V 
284679f0be8dSAneesh Kumar K.V 	/*
284779f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
284879f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
2849179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
285079f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
285179f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
285279f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
285379f0be8dSAneesh Kumar K.V 	 */
28545c1ff336SEric Whitney 	free_clusters =
28555c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
28565c1ff336SEric Whitney 	dirty_clusters =
28575c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
285800d4e736STheodore Ts'o 	/*
285900d4e736STheodore Ts'o 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
286000d4e736STheodore Ts'o 	 */
28615c1ff336SEric Whitney 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
286210ee27a0SMiao Xie 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
286300d4e736STheodore Ts'o 
28645c1ff336SEric Whitney 	if (2 * free_clusters < 3 * dirty_clusters ||
28655c1ff336SEric Whitney 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
286679f0be8dSAneesh Kumar K.V 		/*
2867c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
2868c8afb446SEric Sandeen 		 * or free blocks is less than watermark
286979f0be8dSAneesh Kumar K.V 		 */
287079f0be8dSAneesh Kumar K.V 		return 1;
287179f0be8dSAneesh Kumar K.V 	}
287279f0be8dSAneesh Kumar K.V 	return 0;
287379f0be8dSAneesh Kumar K.V }
287479f0be8dSAneesh Kumar K.V 
28750ff8947fSEric Sandeen /* We always reserve for an inode update; the superblock could be there too */
28760ff8947fSEric Sandeen static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
28770ff8947fSEric Sandeen {
2878e2b911c5SDarrick J. Wong 	if (likely(ext4_has_feature_large_file(inode->i_sb)))
28790ff8947fSEric Sandeen 		return 1;
28800ff8947fSEric Sandeen 
28810ff8947fSEric Sandeen 	if (pos + len <= 0x7fffffffULL)
28820ff8947fSEric Sandeen 		return 1;
28830ff8947fSEric Sandeen 
28840ff8947fSEric Sandeen 	/* We might need to update the superblock to set LARGE_FILE */
28850ff8947fSEric Sandeen 	return 2;
28860ff8947fSEric Sandeen }
28870ff8947fSEric Sandeen 
288864769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
288964769240SAlex Tomas 			       loff_t pos, unsigned len, unsigned flags,
289064769240SAlex Tomas 			       struct page **pagep, void **fsdata)
289164769240SAlex Tomas {
289272b8ab9dSEric Sandeen 	int ret, retries = 0;
289364769240SAlex Tomas 	struct page *page;
289464769240SAlex Tomas 	pgoff_t index;
289564769240SAlex Tomas 	struct inode *inode = mapping->host;
289664769240SAlex Tomas 	handle_t *handle;
289764769240SAlex Tomas 
289809cbfeafSKirill A. Shutemov 	index = pos >> PAGE_SHIFT;
289979f0be8dSAneesh Kumar K.V 
29004db0d88eSTheodore Ts'o 	if (ext4_nonda_switch(inode->i_sb) ||
29014db0d88eSTheodore Ts'o 	    S_ISLNK(inode->i_mode)) {
290279f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
290379f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
290479f0be8dSAneesh Kumar K.V 					len, flags, pagep, fsdata);
290579f0be8dSAneesh Kumar K.V 	}
290679f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
29079bffad1eSTheodore Ts'o 	trace_ext4_da_write_begin(inode, pos, len, flags);
29089c3569b5STao Ma 
29099c3569b5STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
29109c3569b5STao Ma 		ret = ext4_da_write_inline_data_begin(mapping, inode,
29119c3569b5STao Ma 						      pos, len, flags,
29129c3569b5STao Ma 						      pagep, fsdata);
29139c3569b5STao Ma 		if (ret < 0)
291447564bfbSTheodore Ts'o 			return ret;
291547564bfbSTheodore Ts'o 		if (ret == 1)
291647564bfbSTheodore Ts'o 			return 0;
29179c3569b5STao Ma 	}
29189c3569b5STao Ma 
291947564bfbSTheodore Ts'o 	/*
292047564bfbSTheodore Ts'o 	 * grab_cache_page_write_begin() can take a long time if the
292147564bfbSTheodore Ts'o 	 * system is thrashing due to memory pressure, or if the page
292247564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
292347564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
292447564bfbSTheodore Ts'o 	 * the page (if needed) without using GFP_NOFS.
292547564bfbSTheodore Ts'o 	 */
292647564bfbSTheodore Ts'o retry_grab:
292747564bfbSTheodore Ts'o 	page = grab_cache_page_write_begin(mapping, index, flags);
292847564bfbSTheodore Ts'o 	if (!page)
292947564bfbSTheodore Ts'o 		return -ENOMEM;
293047564bfbSTheodore Ts'o 	unlock_page(page);
293147564bfbSTheodore Ts'o 
293264769240SAlex Tomas 	/*
293364769240SAlex Tomas 	 * With delayed allocation, we don't log the i_disksize update
293464769240SAlex Tomas 	 * if there is delayed block allocation. But we still need
293564769240SAlex Tomas 	 * to journalling the i_disksize update if writes to the end
293664769240SAlex Tomas 	 * of file which has an already mapped buffer.
293764769240SAlex Tomas 	 */
293847564bfbSTheodore Ts'o retry_journal:
29390ff8947fSEric Sandeen 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
29400ff8947fSEric Sandeen 				ext4_da_write_credits(inode, pos, len));
294164769240SAlex Tomas 	if (IS_ERR(handle)) {
294209cbfeafSKirill A. Shutemov 		put_page(page);
294347564bfbSTheodore Ts'o 		return PTR_ERR(handle);
294464769240SAlex Tomas 	}
294564769240SAlex Tomas 
294647564bfbSTheodore Ts'o 	lock_page(page);
294747564bfbSTheodore Ts'o 	if (page->mapping != mapping) {
294847564bfbSTheodore Ts'o 		/* The page got truncated from under us */
294947564bfbSTheodore Ts'o 		unlock_page(page);
295009cbfeafSKirill A. Shutemov 		put_page(page);
2951d5a0d4f7SEric Sandeen 		ext4_journal_stop(handle);
295247564bfbSTheodore Ts'o 		goto retry_grab;
2953d5a0d4f7SEric Sandeen 	}
295447564bfbSTheodore Ts'o 	/* In case writeback began while the page was unlocked */
29557afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
295664769240SAlex Tomas 
29572058f83aSMichael Halcrow #ifdef CONFIG_EXT4_FS_ENCRYPTION
29582058f83aSMichael Halcrow 	ret = ext4_block_write_begin(page, pos, len,
29592058f83aSMichael Halcrow 				     ext4_da_get_block_prep);
29602058f83aSMichael Halcrow #else
29616e1db88dSChristoph Hellwig 	ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
29622058f83aSMichael Halcrow #endif
296364769240SAlex Tomas 	if (ret < 0) {
296464769240SAlex Tomas 		unlock_page(page);
296564769240SAlex Tomas 		ext4_journal_stop(handle);
2966ae4d5372SAneesh Kumar K.V 		/*
2967ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
2968ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
2969ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
2970ae4d5372SAneesh Kumar K.V 		 */
2971ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
2972b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
297347564bfbSTheodore Ts'o 
297447564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
297547564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
297647564bfbSTheodore Ts'o 			goto retry_journal;
297747564bfbSTheodore Ts'o 
297809cbfeafSKirill A. Shutemov 		put_page(page);
297947564bfbSTheodore Ts'o 		return ret;
298064769240SAlex Tomas 	}
298164769240SAlex Tomas 
298247564bfbSTheodore Ts'o 	*pagep = page;
298364769240SAlex Tomas 	return ret;
298464769240SAlex Tomas }
298564769240SAlex Tomas 
2986632eaeabSMingming Cao /*
2987632eaeabSMingming Cao  * Check if we should update i_disksize
2988632eaeabSMingming Cao  * when write to the end of file but not require block allocation
2989632eaeabSMingming Cao  */
2990632eaeabSMingming Cao static int ext4_da_should_update_i_disksize(struct page *page,
2991632eaeabSMingming Cao 					    unsigned long offset)
2992632eaeabSMingming Cao {
2993632eaeabSMingming Cao 	struct buffer_head *bh;
2994632eaeabSMingming Cao 	struct inode *inode = page->mapping->host;
2995632eaeabSMingming Cao 	unsigned int idx;
2996632eaeabSMingming Cao 	int i;
2997632eaeabSMingming Cao 
2998632eaeabSMingming Cao 	bh = page_buffers(page);
2999632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
3000632eaeabSMingming Cao 
3001632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
3002632eaeabSMingming Cao 		bh = bh->b_this_page;
3003632eaeabSMingming Cao 
300429fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3005632eaeabSMingming Cao 		return 0;
3006632eaeabSMingming Cao 	return 1;
3007632eaeabSMingming Cao }
3008632eaeabSMingming Cao 
300964769240SAlex Tomas static int ext4_da_write_end(struct file *file,
301064769240SAlex Tomas 			     struct address_space *mapping,
301164769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
301264769240SAlex Tomas 			     struct page *page, void *fsdata)
301364769240SAlex Tomas {
301464769240SAlex Tomas 	struct inode *inode = mapping->host;
301564769240SAlex Tomas 	int ret = 0, ret2;
301664769240SAlex Tomas 	handle_t *handle = ext4_journal_current_handle();
301764769240SAlex Tomas 	loff_t new_i_size;
3018632eaeabSMingming Cao 	unsigned long start, end;
301979f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
302079f0be8dSAneesh Kumar K.V 
302174d553aaSTheodore Ts'o 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
302274d553aaSTheodore Ts'o 		return ext4_write_end(file, mapping, pos,
302379f0be8dSAneesh Kumar K.V 				      len, copied, page, fsdata);
3024632eaeabSMingming Cao 
30259bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
302609cbfeafSKirill A. Shutemov 	start = pos & (PAGE_SIZE - 1);
3027632eaeabSMingming Cao 	end = start + copied - 1;
302864769240SAlex Tomas 
302964769240SAlex Tomas 	/*
303064769240SAlex Tomas 	 * generic_write_end() will run mark_inode_dirty() if i_size
303164769240SAlex Tomas 	 * changes.  So let's piggyback the i_disksize mark_inode_dirty
303264769240SAlex Tomas 	 * into that.
303364769240SAlex Tomas 	 */
303464769240SAlex Tomas 	new_i_size = pos + copied;
3035ea51d132SAndrea Arcangeli 	if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
30369c3569b5STao Ma 		if (ext4_has_inline_data(inode) ||
30379c3569b5STao Ma 		    ext4_da_should_update_i_disksize(page, end)) {
3038ee124d27SDmitry Monakhov 			ext4_update_i_disksize(inode, new_i_size);
3039cf17fea6SAneesh Kumar K.V 			/* We need to mark inode dirty even if
3040cf17fea6SAneesh Kumar K.V 			 * new_i_size is less that inode->i_size
3041cf17fea6SAneesh Kumar K.V 			 * bu greater than i_disksize.(hint delalloc)
3042cf17fea6SAneesh Kumar K.V 			 */
3043cf17fea6SAneesh Kumar K.V 			ext4_mark_inode_dirty(handle, inode);
3044632eaeabSMingming Cao 		}
3045632eaeabSMingming Cao 	}
30469c3569b5STao Ma 
30479c3569b5STao Ma 	if (write_mode != CONVERT_INLINE_DATA &&
30489c3569b5STao Ma 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
30499c3569b5STao Ma 	    ext4_has_inline_data(inode))
30509c3569b5STao Ma 		ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
30519c3569b5STao Ma 						     page);
30529c3569b5STao Ma 	else
305364769240SAlex Tomas 		ret2 = generic_write_end(file, mapping, pos, len, copied,
305464769240SAlex Tomas 							page, fsdata);
30559c3569b5STao Ma 
305664769240SAlex Tomas 	copied = ret2;
305764769240SAlex Tomas 	if (ret2 < 0)
305864769240SAlex Tomas 		ret = ret2;
305964769240SAlex Tomas 	ret2 = ext4_journal_stop(handle);
306064769240SAlex Tomas 	if (!ret)
306164769240SAlex Tomas 		ret = ret2;
306264769240SAlex Tomas 
306364769240SAlex Tomas 	return ret ? ret : copied;
306464769240SAlex Tomas }
306564769240SAlex Tomas 
3066d47992f8SLukas Czerner static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
3067d47992f8SLukas Czerner 				   unsigned int length)
306864769240SAlex Tomas {
306964769240SAlex Tomas 	/*
307064769240SAlex Tomas 	 * Drop reserved blocks
307164769240SAlex Tomas 	 */
307264769240SAlex Tomas 	BUG_ON(!PageLocked(page));
307364769240SAlex Tomas 	if (!page_has_buffers(page))
307464769240SAlex Tomas 		goto out;
307564769240SAlex Tomas 
3076ca99fdd2SLukas Czerner 	ext4_da_page_release_reservation(page, offset, length);
307764769240SAlex Tomas 
307864769240SAlex Tomas out:
3079d47992f8SLukas Czerner 	ext4_invalidatepage(page, offset, length);
308064769240SAlex Tomas 
308164769240SAlex Tomas 	return;
308264769240SAlex Tomas }
308364769240SAlex Tomas 
3084ccd2506bSTheodore Ts'o /*
3085ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
3086ccd2506bSTheodore Ts'o  */
3087ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
3088ccd2506bSTheodore Ts'o {
3089fb40ba0dSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
3090fb40ba0dSTheodore Ts'o 
309171d4f7d0STheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks)
3092ccd2506bSTheodore Ts'o 		return 0;
3093ccd2506bSTheodore Ts'o 
3094ccd2506bSTheodore Ts'o 	/*
3095ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
3096ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
3097ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
3098ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
3099ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
3100ccd2506bSTheodore Ts'o 	 *
310120970ba6STheodore Ts'o 	 * ext4_writepages() ->
3102ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
3103ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
3104ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
3105ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
3106ccd2506bSTheodore Ts'o 	 *
3107ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
3108ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
3109ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
3110ccd2506bSTheodore Ts'o 	 * doing I/O at all.
3111ccd2506bSTheodore Ts'o 	 *
3112ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
3113380cf090SWu Fengguang 	 * the pages by calling redirty_page_for_writepage() but that
3114ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
3115ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
311625985edcSLucas De Marchi 	 * simplifying them because we wouldn't actually intend to
3117ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
3118ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
3119ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
3120ccd2506bSTheodore Ts'o 	 *
3121ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
3122ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
3123ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
3124ccd2506bSTheodore Ts'o 	 */
3125ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
3126ccd2506bSTheodore Ts'o }
312764769240SAlex Tomas 
312864769240SAlex Tomas /*
3129ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
3130ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
3131ac27a0ecSDave Kleikamp  *
3132ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
3133617ba13bSMingming Cao  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3134ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
3135ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
3136ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
3137ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
3138ac27a0ecSDave Kleikamp  *
3139ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
3140ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
3141ac27a0ecSDave Kleikamp  */
3142617ba13bSMingming Cao static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3143ac27a0ecSDave Kleikamp {
3144ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
3145ac27a0ecSDave Kleikamp 	journal_t *journal;
3146ac27a0ecSDave Kleikamp 	int err;
3147ac27a0ecSDave Kleikamp 
314846c7f254STao Ma 	/*
314946c7f254STao Ma 	 * We can get here for an inline file via the FIBMAP ioctl
315046c7f254STao Ma 	 */
315146c7f254STao Ma 	if (ext4_has_inline_data(inode))
315246c7f254STao Ma 		return 0;
315346c7f254STao Ma 
315464769240SAlex Tomas 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
315564769240SAlex Tomas 			test_opt(inode->i_sb, DELALLOC)) {
315664769240SAlex Tomas 		/*
315764769240SAlex Tomas 		 * With delalloc we want to sync the file
315864769240SAlex Tomas 		 * so that we can make sure we allocate
315964769240SAlex Tomas 		 * blocks for file
316064769240SAlex Tomas 		 */
316164769240SAlex Tomas 		filemap_write_and_wait(mapping);
316264769240SAlex Tomas 	}
316364769240SAlex Tomas 
316419f5fb7aSTheodore Ts'o 	if (EXT4_JOURNAL(inode) &&
316519f5fb7aSTheodore Ts'o 	    ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3166ac27a0ecSDave Kleikamp 		/*
3167ac27a0ecSDave Kleikamp 		 * This is a REALLY heavyweight approach, but the use of
3168ac27a0ecSDave Kleikamp 		 * bmap on dirty files is expected to be extremely rare:
3169ac27a0ecSDave Kleikamp 		 * only if we run lilo or swapon on a freshly made file
3170ac27a0ecSDave Kleikamp 		 * do we expect this to happen.
3171ac27a0ecSDave Kleikamp 		 *
3172ac27a0ecSDave Kleikamp 		 * (bmap requires CAP_SYS_RAWIO so this does not
3173ac27a0ecSDave Kleikamp 		 * represent an unprivileged user DOS attack --- we'd be
3174ac27a0ecSDave Kleikamp 		 * in trouble if mortal users could trigger this path at
3175ac27a0ecSDave Kleikamp 		 * will.)
3176ac27a0ecSDave Kleikamp 		 *
3177617ba13bSMingming Cao 		 * NB. EXT4_STATE_JDATA is not set on files other than
3178ac27a0ecSDave Kleikamp 		 * regular files.  If somebody wants to bmap a directory
3179ac27a0ecSDave Kleikamp 		 * or symlink and gets confused because the buffer
3180ac27a0ecSDave Kleikamp 		 * hasn't yet been flushed to disk, they deserve
3181ac27a0ecSDave Kleikamp 		 * everything they get.
3182ac27a0ecSDave Kleikamp 		 */
3183ac27a0ecSDave Kleikamp 
318419f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3185617ba13bSMingming Cao 		journal = EXT4_JOURNAL(inode);
3186dab291afSMingming Cao 		jbd2_journal_lock_updates(journal);
3187dab291afSMingming Cao 		err = jbd2_journal_flush(journal);
3188dab291afSMingming Cao 		jbd2_journal_unlock_updates(journal);
3189ac27a0ecSDave Kleikamp 
3190ac27a0ecSDave Kleikamp 		if (err)
3191ac27a0ecSDave Kleikamp 			return 0;
3192ac27a0ecSDave Kleikamp 	}
3193ac27a0ecSDave Kleikamp 
3194617ba13bSMingming Cao 	return generic_block_bmap(mapping, block, ext4_get_block);
3195ac27a0ecSDave Kleikamp }
3196ac27a0ecSDave Kleikamp 
3197617ba13bSMingming Cao static int ext4_readpage(struct file *file, struct page *page)
3198ac27a0ecSDave Kleikamp {
319946c7f254STao Ma 	int ret = -EAGAIN;
320046c7f254STao Ma 	struct inode *inode = page->mapping->host;
320146c7f254STao Ma 
32020562e0baSJiaying Zhang 	trace_ext4_readpage(page);
320346c7f254STao Ma 
320446c7f254STao Ma 	if (ext4_has_inline_data(inode))
320546c7f254STao Ma 		ret = ext4_readpage_inline(inode, page);
320646c7f254STao Ma 
320746c7f254STao Ma 	if (ret == -EAGAIN)
3208f64e02feSTheodore Ts'o 		return ext4_mpage_readpages(page->mapping, NULL, page, 1);
320946c7f254STao Ma 
321046c7f254STao Ma 	return ret;
3211ac27a0ecSDave Kleikamp }
3212ac27a0ecSDave Kleikamp 
3213ac27a0ecSDave Kleikamp static int
3214617ba13bSMingming Cao ext4_readpages(struct file *file, struct address_space *mapping,
3215ac27a0ecSDave Kleikamp 		struct list_head *pages, unsigned nr_pages)
3216ac27a0ecSDave Kleikamp {
321746c7f254STao Ma 	struct inode *inode = mapping->host;
321846c7f254STao Ma 
321946c7f254STao Ma 	/* If the file has inline data, no need to do readpages. */
322046c7f254STao Ma 	if (ext4_has_inline_data(inode))
322146c7f254STao Ma 		return 0;
322246c7f254STao Ma 
3223f64e02feSTheodore Ts'o 	return ext4_mpage_readpages(mapping, pages, NULL, nr_pages);
3224ac27a0ecSDave Kleikamp }
3225ac27a0ecSDave Kleikamp 
3226d47992f8SLukas Czerner static void ext4_invalidatepage(struct page *page, unsigned int offset,
3227d47992f8SLukas Czerner 				unsigned int length)
3228ac27a0ecSDave Kleikamp {
3229ca99fdd2SLukas Czerner 	trace_ext4_invalidatepage(page, offset, length);
32300562e0baSJiaying Zhang 
32314520fb3cSJan Kara 	/* No journalling happens on data buffers when this function is used */
32324520fb3cSJan Kara 	WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
32334520fb3cSJan Kara 
3234ca99fdd2SLukas Czerner 	block_invalidatepage(page, offset, length);
32354520fb3cSJan Kara }
32364520fb3cSJan Kara 
323753e87268SJan Kara static int __ext4_journalled_invalidatepage(struct page *page,
3238ca99fdd2SLukas Czerner 					    unsigned int offset,
3239ca99fdd2SLukas Czerner 					    unsigned int length)
32404520fb3cSJan Kara {
32414520fb3cSJan Kara 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
32424520fb3cSJan Kara 
3243ca99fdd2SLukas Czerner 	trace_ext4_journalled_invalidatepage(page, offset, length);
32444520fb3cSJan Kara 
3245744692dcSJiaying Zhang 	/*
3246ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
3247ac27a0ecSDave Kleikamp 	 */
324809cbfeafSKirill A. Shutemov 	if (offset == 0 && length == PAGE_SIZE)
3249ac27a0ecSDave Kleikamp 		ClearPageChecked(page);
3250ac27a0ecSDave Kleikamp 
3251ca99fdd2SLukas Czerner 	return jbd2_journal_invalidatepage(journal, page, offset, length);
325253e87268SJan Kara }
325353e87268SJan Kara 
325453e87268SJan Kara /* Wrapper for aops... */
325553e87268SJan Kara static void ext4_journalled_invalidatepage(struct page *page,
3256d47992f8SLukas Czerner 					   unsigned int offset,
3257d47992f8SLukas Czerner 					   unsigned int length)
325853e87268SJan Kara {
3259ca99fdd2SLukas Czerner 	WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3260ac27a0ecSDave Kleikamp }
3261ac27a0ecSDave Kleikamp 
3262617ba13bSMingming Cao static int ext4_releasepage(struct page *page, gfp_t wait)
3263ac27a0ecSDave Kleikamp {
3264617ba13bSMingming Cao 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3265ac27a0ecSDave Kleikamp 
32660562e0baSJiaying Zhang 	trace_ext4_releasepage(page);
32670562e0baSJiaying Zhang 
3268e1c36595SJan Kara 	/* Page has dirty journalled data -> cannot release */
3269e1c36595SJan Kara 	if (PageChecked(page))
3270ac27a0ecSDave Kleikamp 		return 0;
32710390131bSFrank Mayhar 	if (journal)
3272dab291afSMingming Cao 		return jbd2_journal_try_to_free_buffers(journal, page, wait);
32730390131bSFrank Mayhar 	else
32740390131bSFrank Mayhar 		return try_to_free_buffers(page);
3275ac27a0ecSDave Kleikamp }
3276ac27a0ecSDave Kleikamp 
3277ba5843f5SJan Kara #ifdef CONFIG_FS_DAX
3278364443cbSJan Kara static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3279364443cbSJan Kara 			    unsigned flags, struct iomap *iomap)
3280364443cbSJan Kara {
3281364443cbSJan Kara 	unsigned int blkbits = inode->i_blkbits;
3282364443cbSJan Kara 	unsigned long first_block = offset >> blkbits;
3283364443cbSJan Kara 	unsigned long last_block = (offset + length - 1) >> blkbits;
3284364443cbSJan Kara 	struct ext4_map_blocks map;
3285364443cbSJan Kara 	int ret;
3286364443cbSJan Kara 
3287364443cbSJan Kara 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3288364443cbSJan Kara 		return -ERANGE;
3289364443cbSJan Kara 
3290364443cbSJan Kara 	map.m_lblk = first_block;
3291364443cbSJan Kara 	map.m_len = last_block - first_block + 1;
3292364443cbSJan Kara 
3293776722e8SJan Kara 	if (!(flags & IOMAP_WRITE)) {
3294364443cbSJan Kara 		ret = ext4_map_blocks(NULL, inode, &map, 0);
3295776722e8SJan Kara 	} else {
3296776722e8SJan Kara 		int dio_credits;
3297776722e8SJan Kara 		handle_t *handle;
3298776722e8SJan Kara 		int retries = 0;
3299776722e8SJan Kara 
3300776722e8SJan Kara 		/* Trim mapping request to maximum we can map at once for DIO */
3301776722e8SJan Kara 		if (map.m_len > DIO_MAX_BLOCKS)
3302776722e8SJan Kara 			map.m_len = DIO_MAX_BLOCKS;
3303776722e8SJan Kara 		dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
3304776722e8SJan Kara retry:
3305776722e8SJan Kara 		/*
3306776722e8SJan Kara 		 * Either we allocate blocks and then we don't get unwritten
3307776722e8SJan Kara 		 * extent so we have reserved enough credits, or the blocks
3308776722e8SJan Kara 		 * are already allocated and unwritten and in that case
3309776722e8SJan Kara 		 * extent conversion fits in the credits as well.
3310776722e8SJan Kara 		 */
3311776722e8SJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
3312776722e8SJan Kara 					    dio_credits);
3313776722e8SJan Kara 		if (IS_ERR(handle))
3314776722e8SJan Kara 			return PTR_ERR(handle);
3315776722e8SJan Kara 
3316776722e8SJan Kara 		ret = ext4_map_blocks(handle, inode, &map,
3317776722e8SJan Kara 				      EXT4_GET_BLOCKS_CREATE_ZERO);
3318776722e8SJan Kara 		if (ret < 0) {
3319776722e8SJan Kara 			ext4_journal_stop(handle);
3320776722e8SJan Kara 			if (ret == -ENOSPC &&
3321776722e8SJan Kara 			    ext4_should_retry_alloc(inode->i_sb, &retries))
3322776722e8SJan Kara 				goto retry;
3323364443cbSJan Kara 			return ret;
3324776722e8SJan Kara 		}
3325776722e8SJan Kara 
3326776722e8SJan Kara 		/*
3327e2ae766cSJan Kara 		 * If we added blocks beyond i_size, we need to make sure they
3328776722e8SJan Kara 		 * will get truncated if we crash before updating i_size in
3329e2ae766cSJan Kara 		 * ext4_iomap_end(). For faults we don't need to do that (and
3330e2ae766cSJan Kara 		 * even cannot because for orphan list operations inode_lock is
3331e2ae766cSJan Kara 		 * required) - if we happen to instantiate block beyond i_size,
3332e2ae766cSJan Kara 		 * it is because we race with truncate which has already added
3333e2ae766cSJan Kara 		 * the inode to the orphan list.
3334776722e8SJan Kara 		 */
3335e2ae766cSJan Kara 		if (!(flags & IOMAP_FAULT) && first_block + map.m_len >
3336e2ae766cSJan Kara 		    (i_size_read(inode) + (1 << blkbits) - 1) >> blkbits) {
3337776722e8SJan Kara 			int err;
3338776722e8SJan Kara 
3339776722e8SJan Kara 			err = ext4_orphan_add(handle, inode);
3340776722e8SJan Kara 			if (err < 0) {
3341776722e8SJan Kara 				ext4_journal_stop(handle);
3342776722e8SJan Kara 				return err;
3343776722e8SJan Kara 			}
3344776722e8SJan Kara 		}
3345776722e8SJan Kara 		ext4_journal_stop(handle);
3346776722e8SJan Kara 	}
3347364443cbSJan Kara 
3348364443cbSJan Kara 	iomap->flags = 0;
3349364443cbSJan Kara 	iomap->bdev = inode->i_sb->s_bdev;
3350364443cbSJan Kara 	iomap->offset = first_block << blkbits;
3351364443cbSJan Kara 
3352364443cbSJan Kara 	if (ret == 0) {
3353364443cbSJan Kara 		iomap->type = IOMAP_HOLE;
3354364443cbSJan Kara 		iomap->blkno = IOMAP_NULL_BLOCK;
3355364443cbSJan Kara 		iomap->length = (u64)map.m_len << blkbits;
3356364443cbSJan Kara 	} else {
3357364443cbSJan Kara 		if (map.m_flags & EXT4_MAP_MAPPED) {
3358364443cbSJan Kara 			iomap->type = IOMAP_MAPPED;
3359364443cbSJan Kara 		} else if (map.m_flags & EXT4_MAP_UNWRITTEN) {
3360364443cbSJan Kara 			iomap->type = IOMAP_UNWRITTEN;
3361364443cbSJan Kara 		} else {
3362364443cbSJan Kara 			WARN_ON_ONCE(1);
3363364443cbSJan Kara 			return -EIO;
3364364443cbSJan Kara 		}
3365364443cbSJan Kara 		iomap->blkno = (sector_t)map.m_pblk << (blkbits - 9);
3366364443cbSJan Kara 		iomap->length = (u64)map.m_len << blkbits;
3367364443cbSJan Kara 	}
3368364443cbSJan Kara 
3369364443cbSJan Kara 	if (map.m_flags & EXT4_MAP_NEW)
3370364443cbSJan Kara 		iomap->flags |= IOMAP_F_NEW;
3371364443cbSJan Kara 	return 0;
3372364443cbSJan Kara }
3373364443cbSJan Kara 
3374776722e8SJan Kara static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3375776722e8SJan Kara 			  ssize_t written, unsigned flags, struct iomap *iomap)
3376776722e8SJan Kara {
3377776722e8SJan Kara 	int ret = 0;
3378776722e8SJan Kara 	handle_t *handle;
3379776722e8SJan Kara 	int blkbits = inode->i_blkbits;
3380776722e8SJan Kara 	bool truncate = false;
3381776722e8SJan Kara 
3382e2ae766cSJan Kara 	if (!(flags & IOMAP_WRITE) || (flags & IOMAP_FAULT))
3383776722e8SJan Kara 		return 0;
3384776722e8SJan Kara 
3385776722e8SJan Kara 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3386776722e8SJan Kara 	if (IS_ERR(handle)) {
3387776722e8SJan Kara 		ret = PTR_ERR(handle);
3388776722e8SJan Kara 		goto orphan_del;
3389776722e8SJan Kara 	}
3390776722e8SJan Kara 	if (ext4_update_inode_size(inode, offset + written))
3391776722e8SJan Kara 		ext4_mark_inode_dirty(handle, inode);
3392776722e8SJan Kara 	/*
3393776722e8SJan Kara 	 * We may need to truncate allocated but not written blocks beyond EOF.
3394776722e8SJan Kara 	 */
3395776722e8SJan Kara 	if (iomap->offset + iomap->length >
3396776722e8SJan Kara 	    ALIGN(inode->i_size, 1 << blkbits)) {
3397776722e8SJan Kara 		ext4_lblk_t written_blk, end_blk;
3398776722e8SJan Kara 
3399776722e8SJan Kara 		written_blk = (offset + written) >> blkbits;
3400776722e8SJan Kara 		end_blk = (offset + length) >> blkbits;
3401776722e8SJan Kara 		if (written_blk < end_blk && ext4_can_truncate(inode))
3402776722e8SJan Kara 			truncate = true;
3403776722e8SJan Kara 	}
3404776722e8SJan Kara 	/*
3405776722e8SJan Kara 	 * Remove inode from orphan list if we were extending a inode and
3406776722e8SJan Kara 	 * everything went fine.
3407776722e8SJan Kara 	 */
3408776722e8SJan Kara 	if (!truncate && inode->i_nlink &&
3409776722e8SJan Kara 	    !list_empty(&EXT4_I(inode)->i_orphan))
3410776722e8SJan Kara 		ext4_orphan_del(handle, inode);
3411776722e8SJan Kara 	ext4_journal_stop(handle);
3412776722e8SJan Kara 	if (truncate) {
3413776722e8SJan Kara 		ext4_truncate_failed_write(inode);
3414776722e8SJan Kara orphan_del:
3415776722e8SJan Kara 		/*
3416776722e8SJan Kara 		 * If truncate failed early the inode might still be on the
3417776722e8SJan Kara 		 * orphan list; we need to make sure the inode is removed from
3418776722e8SJan Kara 		 * the orphan list in that case.
3419776722e8SJan Kara 		 */
3420776722e8SJan Kara 		if (inode->i_nlink)
3421776722e8SJan Kara 			ext4_orphan_del(NULL, inode);
3422776722e8SJan Kara 	}
3423776722e8SJan Kara 	return ret;
3424776722e8SJan Kara }
3425776722e8SJan Kara 
3426364443cbSJan Kara struct iomap_ops ext4_iomap_ops = {
3427364443cbSJan Kara 	.iomap_begin		= ext4_iomap_begin,
3428776722e8SJan Kara 	.iomap_end		= ext4_iomap_end,
3429364443cbSJan Kara };
3430364443cbSJan Kara 
3431ba5843f5SJan Kara #endif
3432ed923b57SMatthew Wilcox 
3433187372a3SChristoph Hellwig static int ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
34347b7a8665SChristoph Hellwig 			    ssize_t size, void *private)
34354c0425ffSMingming Cao {
3436109811c2SJan Kara         ext4_io_end_t *io_end = private;
34374c0425ffSMingming Cao 
343897a851edSJan Kara 	/* if not async direct IO just return */
34397b7a8665SChristoph Hellwig 	if (!io_end)
3440187372a3SChristoph Hellwig 		return 0;
34414b70df18SMingming 
34428d5d02e6SMingming Cao 	ext_debug("ext4_end_io_dio(): io_end 0x%p "
3443ace36ad4SJoe Perches 		  "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3444109811c2SJan Kara 		  io_end, io_end->inode->i_ino, iocb, offset, size);
34458d5d02e6SMingming Cao 
344674c66bcbSJan Kara 	/*
344774c66bcbSJan Kara 	 * Error during AIO DIO. We cannot convert unwritten extents as the
344874c66bcbSJan Kara 	 * data was not written. Just clear the unwritten flag and drop io_end.
344974c66bcbSJan Kara 	 */
345074c66bcbSJan Kara 	if (size <= 0) {
345174c66bcbSJan Kara 		ext4_clear_io_unwritten_flag(io_end);
345274c66bcbSJan Kara 		size = 0;
345374c66bcbSJan Kara 	}
34544c0425ffSMingming Cao 	io_end->offset = offset;
34554c0425ffSMingming Cao 	io_end->size = size;
34567b7a8665SChristoph Hellwig 	ext4_put_io_end(io_end);
3457187372a3SChristoph Hellwig 
3458187372a3SChristoph Hellwig 	return 0;
34594c0425ffSMingming Cao }
3460c7064ef1SJiaying Zhang 
34614c0425ffSMingming Cao /*
3462914f82a3SJan Kara  * Handling of direct IO writes.
3463914f82a3SJan Kara  *
3464914f82a3SJan Kara  * For ext4 extent files, ext4 will do direct-io write even to holes,
34654c0425ffSMingming Cao  * preallocated extents, and those write extend the file, no need to
34664c0425ffSMingming Cao  * fall back to buffered IO.
34674c0425ffSMingming Cao  *
3468556615dcSLukas Czerner  * For holes, we fallocate those blocks, mark them as unwritten
346969c499d1STheodore Ts'o  * If those blocks were preallocated, we mark sure they are split, but
3470556615dcSLukas Czerner  * still keep the range to write as unwritten.
34714c0425ffSMingming Cao  *
347269c499d1STheodore Ts'o  * The unwritten extents will be converted to written when DIO is completed.
34738d5d02e6SMingming Cao  * For async direct IO, since the IO may still pending when return, we
347425985edcSLucas De Marchi  * set up an end_io call back function, which will do the conversion
34758d5d02e6SMingming Cao  * when async direct IO completed.
34764c0425ffSMingming Cao  *
34774c0425ffSMingming Cao  * If the O_DIRECT write will extend the file then add this inode to the
34784c0425ffSMingming Cao  * orphan list.  So recovery will truncate it back to the original size
34794c0425ffSMingming Cao  * if the machine crashes during the write.
34804c0425ffSMingming Cao  *
34814c0425ffSMingming Cao  */
34820e01df10SLinus Torvalds static ssize_t ext4_direct_IO_write(struct kiocb *iocb, struct iov_iter *iter)
34834c0425ffSMingming Cao {
34844c0425ffSMingming Cao 	struct file *file = iocb->ki_filp;
34854c0425ffSMingming Cao 	struct inode *inode = file->f_mapping->host;
3486914f82a3SJan Kara 	struct ext4_inode_info *ei = EXT4_I(inode);
34874c0425ffSMingming Cao 	ssize_t ret;
3488c8b8e32dSChristoph Hellwig 	loff_t offset = iocb->ki_pos;
3489a6cbcd4aSAl Viro 	size_t count = iov_iter_count(iter);
3490729f52c6SZheng Liu 	int overwrite = 0;
34918b0f165fSAnatol Pomozov 	get_block_t *get_block_func = NULL;
34928b0f165fSAnatol Pomozov 	int dio_flags = 0;
349369c499d1STheodore Ts'o 	loff_t final_size = offset + count;
3494914f82a3SJan Kara 	int orphan = 0;
3495914f82a3SJan Kara 	handle_t *handle;
349669c499d1STheodore Ts'o 
3497914f82a3SJan Kara 	if (final_size > inode->i_size) {
3498914f82a3SJan Kara 		/* Credits for sb + inode write */
3499914f82a3SJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3500914f82a3SJan Kara 		if (IS_ERR(handle)) {
3501914f82a3SJan Kara 			ret = PTR_ERR(handle);
3502914f82a3SJan Kara 			goto out;
3503914f82a3SJan Kara 		}
3504914f82a3SJan Kara 		ret = ext4_orphan_add(handle, inode);
3505914f82a3SJan Kara 		if (ret) {
3506914f82a3SJan Kara 			ext4_journal_stop(handle);
3507914f82a3SJan Kara 			goto out;
3508914f82a3SJan Kara 		}
3509914f82a3SJan Kara 		orphan = 1;
3510914f82a3SJan Kara 		ei->i_disksize = inode->i_size;
3511914f82a3SJan Kara 		ext4_journal_stop(handle);
3512914f82a3SJan Kara 	}
3513729f52c6SZheng Liu 
35144bd809dbSZheng Liu 	BUG_ON(iocb->private == NULL);
35154bd809dbSZheng Liu 
3516e8340395SJan Kara 	/*
3517e8340395SJan Kara 	 * Make all waiters for direct IO properly wait also for extent
3518e8340395SJan Kara 	 * conversion. This also disallows race between truncate() and
3519e8340395SJan Kara 	 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3520e8340395SJan Kara 	 */
3521fe0f07d0SJens Axboe 	inode_dio_begin(inode);
3522e8340395SJan Kara 
35234bd809dbSZheng Liu 	/* If we do a overwrite dio, i_mutex locking can be released */
35244bd809dbSZheng Liu 	overwrite = *((int *)iocb->private);
35254bd809dbSZheng Liu 
35262dcba478SJan Kara 	if (overwrite)
35275955102cSAl Viro 		inode_unlock(inode);
35284bd809dbSZheng Liu 
35294c0425ffSMingming Cao 	/*
3530914f82a3SJan Kara 	 * For extent mapped files we could direct write to holes and fallocate.
35318d5d02e6SMingming Cao 	 *
3532109811c2SJan Kara 	 * Allocated blocks to fill the hole are marked as unwritten to prevent
3533109811c2SJan Kara 	 * parallel buffered read to expose the stale data before DIO complete
3534109811c2SJan Kara 	 * the data IO.
35358d5d02e6SMingming Cao 	 *
3536109811c2SJan Kara 	 * As to previously fallocated extents, ext4 get_block will just simply
3537109811c2SJan Kara 	 * mark the buffer mapped but still keep the extents unwritten.
35384c0425ffSMingming Cao 	 *
3539109811c2SJan Kara 	 * For non AIO case, we will convert those unwritten extents to written
3540109811c2SJan Kara 	 * after return back from blockdev_direct_IO. That way we save us from
3541109811c2SJan Kara 	 * allocating io_end structure and also the overhead of offloading
3542109811c2SJan Kara 	 * the extent convertion to a workqueue.
35434c0425ffSMingming Cao 	 *
354469c499d1STheodore Ts'o 	 * For async DIO, the conversion needs to be deferred when the
354569c499d1STheodore Ts'o 	 * IO is completed. The ext4 end_io callback function will be
354669c499d1STheodore Ts'o 	 * called to take care of the conversion work.  Here for async
354769c499d1STheodore Ts'o 	 * case, we allocate an io_end structure to hook to the iocb.
35484c0425ffSMingming Cao 	 */
35498d5d02e6SMingming Cao 	iocb->private = NULL;
3550109811c2SJan Kara 	if (overwrite)
3551705965bdSJan Kara 		get_block_func = ext4_dio_get_block_overwrite;
35520bd2d5ecSJan Kara 	else if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) ||
3553914f82a3SJan Kara 		   round_down(offset, 1 << inode->i_blkbits) >= inode->i_size) {
3554914f82a3SJan Kara 		get_block_func = ext4_dio_get_block;
3555914f82a3SJan Kara 		dio_flags = DIO_LOCKING | DIO_SKIP_HOLES;
3556914f82a3SJan Kara 	} else if (is_sync_kiocb(iocb)) {
3557109811c2SJan Kara 		get_block_func = ext4_dio_get_block_unwritten_sync;
3558109811c2SJan Kara 		dio_flags = DIO_LOCKING;
355974dae427SJan Kara 	} else {
3560109811c2SJan Kara 		get_block_func = ext4_dio_get_block_unwritten_async;
35618b0f165fSAnatol Pomozov 		dio_flags = DIO_LOCKING;
35628b0f165fSAnatol Pomozov 	}
35632058f83aSMichael Halcrow #ifdef CONFIG_EXT4_FS_ENCRYPTION
35642058f83aSMichael Halcrow 	BUG_ON(ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode));
35652058f83aSMichael Halcrow #endif
35660bd2d5ecSJan Kara 	ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, iter,
35670bd2d5ecSJan Kara 				   get_block_func, ext4_end_io_dio, NULL,
35680bd2d5ecSJan Kara 				   dio_flags);
35698b0f165fSAnatol Pomozov 
357097a851edSJan Kara 	if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
35715f524950SMingming 						EXT4_STATE_DIO_UNWRITTEN)) {
3572109f5565SMingming 		int err;
35738d5d02e6SMingming Cao 		/*
35748d5d02e6SMingming Cao 		 * for non AIO case, since the IO is already
357525985edcSLucas De Marchi 		 * completed, we could do the conversion right here
35768d5d02e6SMingming Cao 		 */
35776b523df4SJan Kara 		err = ext4_convert_unwritten_extents(NULL, inode,
35788d5d02e6SMingming Cao 						     offset, ret);
3579109f5565SMingming 		if (err < 0)
3580109f5565SMingming 			ret = err;
358119f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3582109f5565SMingming 	}
35834bd809dbSZheng Liu 
3584fe0f07d0SJens Axboe 	inode_dio_end(inode);
35854bd809dbSZheng Liu 	/* take i_mutex locking again if we do a ovewrite dio */
35862dcba478SJan Kara 	if (overwrite)
35875955102cSAl Viro 		inode_lock(inode);
35884bd809dbSZheng Liu 
3589914f82a3SJan Kara 	if (ret < 0 && final_size > inode->i_size)
3590914f82a3SJan Kara 		ext4_truncate_failed_write(inode);
3591914f82a3SJan Kara 
3592914f82a3SJan Kara 	/* Handle extending of i_size after direct IO write */
3593914f82a3SJan Kara 	if (orphan) {
3594914f82a3SJan Kara 		int err;
3595914f82a3SJan Kara 
3596914f82a3SJan Kara 		/* Credits for sb + inode write */
3597914f82a3SJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3598914f82a3SJan Kara 		if (IS_ERR(handle)) {
3599914f82a3SJan Kara 			/* This is really bad luck. We've written the data
3600914f82a3SJan Kara 			 * but cannot extend i_size. Bail out and pretend
3601914f82a3SJan Kara 			 * the write failed... */
3602914f82a3SJan Kara 			ret = PTR_ERR(handle);
3603914f82a3SJan Kara 			if (inode->i_nlink)
3604914f82a3SJan Kara 				ext4_orphan_del(NULL, inode);
3605914f82a3SJan Kara 
3606914f82a3SJan Kara 			goto out;
3607914f82a3SJan Kara 		}
3608914f82a3SJan Kara 		if (inode->i_nlink)
3609914f82a3SJan Kara 			ext4_orphan_del(handle, inode);
3610914f82a3SJan Kara 		if (ret > 0) {
3611914f82a3SJan Kara 			loff_t end = offset + ret;
3612914f82a3SJan Kara 			if (end > inode->i_size) {
3613914f82a3SJan Kara 				ei->i_disksize = end;
3614914f82a3SJan Kara 				i_size_write(inode, end);
3615914f82a3SJan Kara 				/*
3616914f82a3SJan Kara 				 * We're going to return a positive `ret'
3617914f82a3SJan Kara 				 * here due to non-zero-length I/O, so there's
3618914f82a3SJan Kara 				 * no way of reporting error returns from
3619914f82a3SJan Kara 				 * ext4_mark_inode_dirty() to userspace.  So
3620914f82a3SJan Kara 				 * ignore it.
3621914f82a3SJan Kara 				 */
3622914f82a3SJan Kara 				ext4_mark_inode_dirty(handle, inode);
3623914f82a3SJan Kara 			}
3624914f82a3SJan Kara 		}
3625914f82a3SJan Kara 		err = ext4_journal_stop(handle);
3626914f82a3SJan Kara 		if (ret == 0)
3627914f82a3SJan Kara 			ret = err;
3628914f82a3SJan Kara 	}
3629914f82a3SJan Kara out:
3630914f82a3SJan Kara 	return ret;
3631914f82a3SJan Kara }
3632914f82a3SJan Kara 
36330e01df10SLinus Torvalds static ssize_t ext4_direct_IO_read(struct kiocb *iocb, struct iov_iter *iter)
3634914f82a3SJan Kara {
363516c54688SJan Kara 	struct address_space *mapping = iocb->ki_filp->f_mapping;
363616c54688SJan Kara 	struct inode *inode = mapping->host;
36370bd2d5ecSJan Kara 	size_t count = iov_iter_count(iter);
3638914f82a3SJan Kara 	ssize_t ret;
3639914f82a3SJan Kara 
3640914f82a3SJan Kara 	/*
364116c54688SJan Kara 	 * Shared inode_lock is enough for us - it protects against concurrent
364216c54688SJan Kara 	 * writes & truncates and since we take care of writing back page cache,
364316c54688SJan Kara 	 * we are protected against page writeback as well.
3644914f82a3SJan Kara 	 */
364516c54688SJan Kara 	inode_lock_shared(inode);
364616c54688SJan Kara 	ret = filemap_write_and_wait_range(mapping, iocb->ki_pos,
364716c54688SJan Kara 					   iocb->ki_pos + count);
364816c54688SJan Kara 	if (ret)
364916c54688SJan Kara 		goto out_unlock;
3650914f82a3SJan Kara 	ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
36510bd2d5ecSJan Kara 				   iter, ext4_dio_get_block, NULL, NULL, 0);
365216c54688SJan Kara out_unlock:
365316c54688SJan Kara 	inode_unlock_shared(inode);
36544c0425ffSMingming Cao 	return ret;
36554c0425ffSMingming Cao }
36568d5d02e6SMingming Cao 
3657c8b8e32dSChristoph Hellwig static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
36584c0425ffSMingming Cao {
36594c0425ffSMingming Cao 	struct file *file = iocb->ki_filp;
36604c0425ffSMingming Cao 	struct inode *inode = file->f_mapping->host;
3661a6cbcd4aSAl Viro 	size_t count = iov_iter_count(iter);
3662c8b8e32dSChristoph Hellwig 	loff_t offset = iocb->ki_pos;
36630562e0baSJiaying Zhang 	ssize_t ret;
36644c0425ffSMingming Cao 
36652058f83aSMichael Halcrow #ifdef CONFIG_EXT4_FS_ENCRYPTION
36662058f83aSMichael Halcrow 	if (ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode))
36672058f83aSMichael Halcrow 		return 0;
36682058f83aSMichael Halcrow #endif
36692058f83aSMichael Halcrow 
367084ebd795STheodore Ts'o 	/*
367184ebd795STheodore Ts'o 	 * If we are doing data journalling we don't support O_DIRECT
367284ebd795STheodore Ts'o 	 */
367384ebd795STheodore Ts'o 	if (ext4_should_journal_data(inode))
367484ebd795STheodore Ts'o 		return 0;
367584ebd795STheodore Ts'o 
367646c7f254STao Ma 	/* Let buffer I/O handle the inline data case. */
367746c7f254STao Ma 	if (ext4_has_inline_data(inode))
367846c7f254STao Ma 		return 0;
367946c7f254STao Ma 
36800bd2d5ecSJan Kara 	/* DAX uses iomap path now */
36810bd2d5ecSJan Kara 	if (WARN_ON_ONCE(IS_DAX(inode)))
36820bd2d5ecSJan Kara 		return 0;
36830bd2d5ecSJan Kara 
36846f673763SOmar Sandoval 	trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
3685914f82a3SJan Kara 	if (iov_iter_rw(iter) == READ)
36860e01df10SLinus Torvalds 		ret = ext4_direct_IO_read(iocb, iter);
36870562e0baSJiaying Zhang 	else
36880e01df10SLinus Torvalds 		ret = ext4_direct_IO_write(iocb, iter);
36896f673763SOmar Sandoval 	trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
36900562e0baSJiaying Zhang 	return ret;
36914c0425ffSMingming Cao }
36924c0425ffSMingming Cao 
3693ac27a0ecSDave Kleikamp /*
3694617ba13bSMingming Cao  * Pages can be marked dirty completely asynchronously from ext4's journalling
3695ac27a0ecSDave Kleikamp  * activity.  By filemap_sync_pte(), try_to_unmap_one(), etc.  We cannot do
3696ac27a0ecSDave Kleikamp  * much here because ->set_page_dirty is called under VFS locks.  The page is
3697ac27a0ecSDave Kleikamp  * not necessarily locked.
3698ac27a0ecSDave Kleikamp  *
3699ac27a0ecSDave Kleikamp  * We cannot just dirty the page and leave attached buffers clean, because the
3700ac27a0ecSDave Kleikamp  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3701ac27a0ecSDave Kleikamp  * or jbddirty because all the journalling code will explode.
3702ac27a0ecSDave Kleikamp  *
3703ac27a0ecSDave Kleikamp  * So what we do is to mark the page "pending dirty" and next time writepage
3704ac27a0ecSDave Kleikamp  * is called, propagate that into the buffers appropriately.
3705ac27a0ecSDave Kleikamp  */
3706617ba13bSMingming Cao static int ext4_journalled_set_page_dirty(struct page *page)
3707ac27a0ecSDave Kleikamp {
3708ac27a0ecSDave Kleikamp 	SetPageChecked(page);
3709ac27a0ecSDave Kleikamp 	return __set_page_dirty_nobuffers(page);
3710ac27a0ecSDave Kleikamp }
3711ac27a0ecSDave Kleikamp 
37126dcc693bSJan Kara static int ext4_set_page_dirty(struct page *page)
37136dcc693bSJan Kara {
37146dcc693bSJan Kara 	WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
37156dcc693bSJan Kara 	WARN_ON_ONCE(!page_has_buffers(page));
37166dcc693bSJan Kara 	return __set_page_dirty_buffers(page);
37176dcc693bSJan Kara }
37186dcc693bSJan Kara 
371974d553aaSTheodore Ts'o static const struct address_space_operations ext4_aops = {
3720617ba13bSMingming Cao 	.readpage		= ext4_readpage,
3721617ba13bSMingming Cao 	.readpages		= ext4_readpages,
372243ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
372320970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3724bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
372574d553aaSTheodore Ts'o 	.write_end		= ext4_write_end,
37266dcc693bSJan Kara 	.set_page_dirty		= ext4_set_page_dirty,
3727617ba13bSMingming Cao 	.bmap			= ext4_bmap,
3728617ba13bSMingming Cao 	.invalidatepage		= ext4_invalidatepage,
3729617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
3730617ba13bSMingming Cao 	.direct_IO		= ext4_direct_IO,
3731ac27a0ecSDave Kleikamp 	.migratepage		= buffer_migrate_page,
37328ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3733aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
3734ac27a0ecSDave Kleikamp };
3735ac27a0ecSDave Kleikamp 
3736617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
3737617ba13bSMingming Cao 	.readpage		= ext4_readpage,
3738617ba13bSMingming Cao 	.readpages		= ext4_readpages,
373943ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
374020970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3741bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
3742bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
3743617ba13bSMingming Cao 	.set_page_dirty		= ext4_journalled_set_page_dirty,
3744617ba13bSMingming Cao 	.bmap			= ext4_bmap,
37454520fb3cSJan Kara 	.invalidatepage		= ext4_journalled_invalidatepage,
3746617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
374784ebd795STheodore Ts'o 	.direct_IO		= ext4_direct_IO,
37488ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3749aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
3750ac27a0ecSDave Kleikamp };
3751ac27a0ecSDave Kleikamp 
375264769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
375364769240SAlex Tomas 	.readpage		= ext4_readpage,
375464769240SAlex Tomas 	.readpages		= ext4_readpages,
375543ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
375620970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
375764769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
375864769240SAlex Tomas 	.write_end		= ext4_da_write_end,
37596dcc693bSJan Kara 	.set_page_dirty		= ext4_set_page_dirty,
376064769240SAlex Tomas 	.bmap			= ext4_bmap,
376164769240SAlex Tomas 	.invalidatepage		= ext4_da_invalidatepage,
376264769240SAlex Tomas 	.releasepage		= ext4_releasepage,
376364769240SAlex Tomas 	.direct_IO		= ext4_direct_IO,
376464769240SAlex Tomas 	.migratepage		= buffer_migrate_page,
37658ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3766aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
376764769240SAlex Tomas };
376864769240SAlex Tomas 
3769617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
3770ac27a0ecSDave Kleikamp {
37713d2b1582SLukas Czerner 	switch (ext4_inode_journal_mode(inode)) {
37723d2b1582SLukas Czerner 	case EXT4_INODE_ORDERED_DATA_MODE:
37733d2b1582SLukas Czerner 	case EXT4_INODE_WRITEBACK_DATA_MODE:
37743d2b1582SLukas Czerner 		break;
37753d2b1582SLukas Czerner 	case EXT4_INODE_JOURNAL_DATA_MODE:
3776617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
377774d553aaSTheodore Ts'o 		return;
37783d2b1582SLukas Czerner 	default:
37793d2b1582SLukas Czerner 		BUG();
37803d2b1582SLukas Czerner 	}
378174d553aaSTheodore Ts'o 	if (test_opt(inode->i_sb, DELALLOC))
378274d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_da_aops;
378374d553aaSTheodore Ts'o 	else
378474d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_aops;
3785ac27a0ecSDave Kleikamp }
3786ac27a0ecSDave Kleikamp 
3787923ae0ffSRoss Zwisler static int __ext4_block_zero_page_range(handle_t *handle,
3788d863dc36SLukas Czerner 		struct address_space *mapping, loff_t from, loff_t length)
3789d863dc36SLukas Czerner {
379009cbfeafSKirill A. Shutemov 	ext4_fsblk_t index = from >> PAGE_SHIFT;
379109cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3792923ae0ffSRoss Zwisler 	unsigned blocksize, pos;
3793d863dc36SLukas Czerner 	ext4_lblk_t iblock;
3794d863dc36SLukas Czerner 	struct inode *inode = mapping->host;
3795d863dc36SLukas Czerner 	struct buffer_head *bh;
3796d863dc36SLukas Czerner 	struct page *page;
3797d863dc36SLukas Czerner 	int err = 0;
3798d863dc36SLukas Czerner 
379909cbfeafSKirill A. Shutemov 	page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3800c62d2555SMichal Hocko 				   mapping_gfp_constraint(mapping, ~__GFP_FS));
3801d863dc36SLukas Czerner 	if (!page)
3802d863dc36SLukas Czerner 		return -ENOMEM;
3803d863dc36SLukas Czerner 
3804d863dc36SLukas Czerner 	blocksize = inode->i_sb->s_blocksize;
3805d863dc36SLukas Czerner 
380609cbfeafSKirill A. Shutemov 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3807d863dc36SLukas Czerner 
3808d863dc36SLukas Czerner 	if (!page_has_buffers(page))
3809d863dc36SLukas Czerner 		create_empty_buffers(page, blocksize, 0);
3810d863dc36SLukas Czerner 
3811d863dc36SLukas Czerner 	/* Find the buffer that contains "offset" */
3812d863dc36SLukas Czerner 	bh = page_buffers(page);
3813d863dc36SLukas Czerner 	pos = blocksize;
3814d863dc36SLukas Czerner 	while (offset >= pos) {
3815d863dc36SLukas Czerner 		bh = bh->b_this_page;
3816d863dc36SLukas Czerner 		iblock++;
3817d863dc36SLukas Czerner 		pos += blocksize;
3818d863dc36SLukas Czerner 	}
3819d863dc36SLukas Czerner 	if (buffer_freed(bh)) {
3820d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "freed: skip");
3821d863dc36SLukas Czerner 		goto unlock;
3822d863dc36SLukas Czerner 	}
3823d863dc36SLukas Czerner 	if (!buffer_mapped(bh)) {
3824d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "unmapped");
3825d863dc36SLukas Czerner 		ext4_get_block(inode, iblock, bh, 0);
3826d863dc36SLukas Czerner 		/* unmapped? It's a hole - nothing to do */
3827d863dc36SLukas Czerner 		if (!buffer_mapped(bh)) {
3828d863dc36SLukas Czerner 			BUFFER_TRACE(bh, "still unmapped");
3829d863dc36SLukas Czerner 			goto unlock;
3830d863dc36SLukas Czerner 		}
3831d863dc36SLukas Czerner 	}
3832d863dc36SLukas Czerner 
3833d863dc36SLukas Czerner 	/* Ok, it's mapped. Make sure it's up-to-date */
3834d863dc36SLukas Czerner 	if (PageUptodate(page))
3835d863dc36SLukas Czerner 		set_buffer_uptodate(bh);
3836d863dc36SLukas Czerner 
3837d863dc36SLukas Czerner 	if (!buffer_uptodate(bh)) {
3838d863dc36SLukas Czerner 		err = -EIO;
3839dfec8a14SMike Christie 		ll_rw_block(REQ_OP_READ, 0, 1, &bh);
3840d863dc36SLukas Czerner 		wait_on_buffer(bh);
3841d863dc36SLukas Czerner 		/* Uhhuh. Read error. Complain and punt. */
3842d863dc36SLukas Czerner 		if (!buffer_uptodate(bh))
3843d863dc36SLukas Czerner 			goto unlock;
3844c9c7429cSMichael Halcrow 		if (S_ISREG(inode->i_mode) &&
3845c9c7429cSMichael Halcrow 		    ext4_encrypted_inode(inode)) {
3846c9c7429cSMichael Halcrow 			/* We expect the key to be set. */
3847a7550b30SJaegeuk Kim 			BUG_ON(!fscrypt_has_encryption_key(inode));
384809cbfeafSKirill A. Shutemov 			BUG_ON(blocksize != PAGE_SIZE);
3849b50f7b26SDavid Gstir 			WARN_ON_ONCE(fscrypt_decrypt_page(page->mapping->host,
38509c4bb8a3SDavid Gstir 						page, PAGE_SIZE, 0, page->index));
3851c9c7429cSMichael Halcrow 		}
3852d863dc36SLukas Czerner 	}
3853d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3854d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "get write access");
3855d863dc36SLukas Czerner 		err = ext4_journal_get_write_access(handle, bh);
3856d863dc36SLukas Czerner 		if (err)
3857d863dc36SLukas Czerner 			goto unlock;
3858d863dc36SLukas Czerner 	}
3859d863dc36SLukas Czerner 	zero_user(page, offset, length);
3860d863dc36SLukas Czerner 	BUFFER_TRACE(bh, "zeroed end of block");
3861d863dc36SLukas Czerner 
3862d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3863d863dc36SLukas Czerner 		err = ext4_handle_dirty_metadata(handle, inode, bh);
38640713ed0cSLukas Czerner 	} else {
3865353eefd3Sjon ernst 		err = 0;
3866d863dc36SLukas Czerner 		mark_buffer_dirty(bh);
38673957ef53SJan Kara 		if (ext4_should_order_data(inode))
3868ee0876bcSJan Kara 			err = ext4_jbd2_inode_add_write(handle, inode);
38690713ed0cSLukas Czerner 	}
3870d863dc36SLukas Czerner 
3871d863dc36SLukas Czerner unlock:
3872d863dc36SLukas Czerner 	unlock_page(page);
387309cbfeafSKirill A. Shutemov 	put_page(page);
3874d863dc36SLukas Czerner 	return err;
3875d863dc36SLukas Czerner }
3876d863dc36SLukas Czerner 
387794350ab5SMatthew Wilcox /*
3878923ae0ffSRoss Zwisler  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3879923ae0ffSRoss Zwisler  * starting from file offset 'from'.  The range to be zero'd must
3880923ae0ffSRoss Zwisler  * be contained with in one block.  If the specified range exceeds
3881923ae0ffSRoss Zwisler  * the end of the block it will be shortened to end of the block
3882923ae0ffSRoss Zwisler  * that cooresponds to 'from'
3883923ae0ffSRoss Zwisler  */
3884923ae0ffSRoss Zwisler static int ext4_block_zero_page_range(handle_t *handle,
3885923ae0ffSRoss Zwisler 		struct address_space *mapping, loff_t from, loff_t length)
3886923ae0ffSRoss Zwisler {
3887923ae0ffSRoss Zwisler 	struct inode *inode = mapping->host;
388809cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
3889923ae0ffSRoss Zwisler 	unsigned blocksize = inode->i_sb->s_blocksize;
3890923ae0ffSRoss Zwisler 	unsigned max = blocksize - (offset & (blocksize - 1));
3891923ae0ffSRoss Zwisler 
3892923ae0ffSRoss Zwisler 	/*
3893923ae0ffSRoss Zwisler 	 * correct length if it does not fall between
3894923ae0ffSRoss Zwisler 	 * 'from' and the end of the block
3895923ae0ffSRoss Zwisler 	 */
3896923ae0ffSRoss Zwisler 	if (length > max || length < 0)
3897923ae0ffSRoss Zwisler 		length = max;
3898923ae0ffSRoss Zwisler 
389947e69351SJan Kara 	if (IS_DAX(inode)) {
390047e69351SJan Kara 		return iomap_zero_range(inode, from, length, NULL,
390147e69351SJan Kara 					&ext4_iomap_ops);
390247e69351SJan Kara 	}
3903923ae0ffSRoss Zwisler 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3904923ae0ffSRoss Zwisler }
3905923ae0ffSRoss Zwisler 
3906923ae0ffSRoss Zwisler /*
390794350ab5SMatthew Wilcox  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
390894350ab5SMatthew Wilcox  * up to the end of the block which corresponds to `from'.
390994350ab5SMatthew Wilcox  * This required during truncate. We need to physically zero the tail end
391094350ab5SMatthew Wilcox  * of that block so it doesn't yield old data if the file is later grown.
391194350ab5SMatthew Wilcox  */
3912c197855eSStephen Hemminger static int ext4_block_truncate_page(handle_t *handle,
391394350ab5SMatthew Wilcox 		struct address_space *mapping, loff_t from)
391494350ab5SMatthew Wilcox {
391509cbfeafSKirill A. Shutemov 	unsigned offset = from & (PAGE_SIZE-1);
391694350ab5SMatthew Wilcox 	unsigned length;
391794350ab5SMatthew Wilcox 	unsigned blocksize;
391894350ab5SMatthew Wilcox 	struct inode *inode = mapping->host;
391994350ab5SMatthew Wilcox 
392094350ab5SMatthew Wilcox 	blocksize = inode->i_sb->s_blocksize;
392194350ab5SMatthew Wilcox 	length = blocksize - (offset & (blocksize - 1));
392294350ab5SMatthew Wilcox 
392394350ab5SMatthew Wilcox 	return ext4_block_zero_page_range(handle, mapping, from, length);
392494350ab5SMatthew Wilcox }
392594350ab5SMatthew Wilcox 
3926a87dd18cSLukas Czerner int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3927a87dd18cSLukas Czerner 			     loff_t lstart, loff_t length)
3928a87dd18cSLukas Czerner {
3929a87dd18cSLukas Czerner 	struct super_block *sb = inode->i_sb;
3930a87dd18cSLukas Czerner 	struct address_space *mapping = inode->i_mapping;
3931e1be3a92SLukas Czerner 	unsigned partial_start, partial_end;
3932a87dd18cSLukas Czerner 	ext4_fsblk_t start, end;
3933a87dd18cSLukas Czerner 	loff_t byte_end = (lstart + length - 1);
3934a87dd18cSLukas Czerner 	int err = 0;
3935a87dd18cSLukas Czerner 
3936e1be3a92SLukas Czerner 	partial_start = lstart & (sb->s_blocksize - 1);
3937e1be3a92SLukas Czerner 	partial_end = byte_end & (sb->s_blocksize - 1);
3938e1be3a92SLukas Czerner 
3939a87dd18cSLukas Czerner 	start = lstart >> sb->s_blocksize_bits;
3940a87dd18cSLukas Czerner 	end = byte_end >> sb->s_blocksize_bits;
3941a87dd18cSLukas Czerner 
3942a87dd18cSLukas Czerner 	/* Handle partial zero within the single block */
3943e1be3a92SLukas Czerner 	if (start == end &&
3944e1be3a92SLukas Czerner 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3945a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3946a87dd18cSLukas Czerner 						 lstart, length);
3947a87dd18cSLukas Czerner 		return err;
3948a87dd18cSLukas Czerner 	}
3949a87dd18cSLukas Czerner 	/* Handle partial zero out on the start of the range */
3950e1be3a92SLukas Czerner 	if (partial_start) {
3951a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3952a87dd18cSLukas Czerner 						 lstart, sb->s_blocksize);
3953a87dd18cSLukas Czerner 		if (err)
3954a87dd18cSLukas Czerner 			return err;
3955a87dd18cSLukas Czerner 	}
3956a87dd18cSLukas Czerner 	/* Handle partial zero out on the end of the range */
3957e1be3a92SLukas Czerner 	if (partial_end != sb->s_blocksize - 1)
3958a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3959e1be3a92SLukas Czerner 						 byte_end - partial_end,
3960e1be3a92SLukas Czerner 						 partial_end + 1);
3961a87dd18cSLukas Czerner 	return err;
3962a87dd18cSLukas Czerner }
3963a87dd18cSLukas Czerner 
396491ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
396591ef4cafSDuane Griffin {
396691ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
396791ef4cafSDuane Griffin 		return 1;
396891ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
396991ef4cafSDuane Griffin 		return 1;
397091ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
397191ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
397291ef4cafSDuane Griffin 	return 0;
397391ef4cafSDuane Griffin }
397491ef4cafSDuane Griffin 
3975ac27a0ecSDave Kleikamp /*
397601127848SJan Kara  * We have to make sure i_disksize gets properly updated before we truncate
397701127848SJan Kara  * page cache due to hole punching or zero range. Otherwise i_disksize update
397801127848SJan Kara  * can get lost as it may have been postponed to submission of writeback but
397901127848SJan Kara  * that will never happen after we truncate page cache.
398001127848SJan Kara  */
398101127848SJan Kara int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
398201127848SJan Kara 				      loff_t len)
398301127848SJan Kara {
398401127848SJan Kara 	handle_t *handle;
398501127848SJan Kara 	loff_t size = i_size_read(inode);
398601127848SJan Kara 
39875955102cSAl Viro 	WARN_ON(!inode_is_locked(inode));
398801127848SJan Kara 	if (offset > size || offset + len < size)
398901127848SJan Kara 		return 0;
399001127848SJan Kara 
399101127848SJan Kara 	if (EXT4_I(inode)->i_disksize >= size)
399201127848SJan Kara 		return 0;
399301127848SJan Kara 
399401127848SJan Kara 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
399501127848SJan Kara 	if (IS_ERR(handle))
399601127848SJan Kara 		return PTR_ERR(handle);
399701127848SJan Kara 	ext4_update_i_disksize(inode, size);
399801127848SJan Kara 	ext4_mark_inode_dirty(handle, inode);
399901127848SJan Kara 	ext4_journal_stop(handle);
400001127848SJan Kara 
400101127848SJan Kara 	return 0;
400201127848SJan Kara }
400301127848SJan Kara 
400401127848SJan Kara /*
4005cca32b7eSRoss Zwisler  * ext4_punch_hole: punches a hole in a file by releasing the blocks
4006a4bb6b64SAllison Henderson  * associated with the given offset and length
4007a4bb6b64SAllison Henderson  *
4008a4bb6b64SAllison Henderson  * @inode:  File inode
4009a4bb6b64SAllison Henderson  * @offset: The offset where the hole will begin
4010a4bb6b64SAllison Henderson  * @len:    The length of the hole
4011a4bb6b64SAllison Henderson  *
40124907cb7bSAnatol Pomozov  * Returns: 0 on success or negative on failure
4013a4bb6b64SAllison Henderson  */
4014a4bb6b64SAllison Henderson 
4015aeb2817aSAshish Sangwan int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
4016a4bb6b64SAllison Henderson {
401726a4c0c6STheodore Ts'o 	struct super_block *sb = inode->i_sb;
401826a4c0c6STheodore Ts'o 	ext4_lblk_t first_block, stop_block;
401926a4c0c6STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
4020a87dd18cSLukas Czerner 	loff_t first_block_offset, last_block_offset;
402126a4c0c6STheodore Ts'o 	handle_t *handle;
402226a4c0c6STheodore Ts'o 	unsigned int credits;
402326a4c0c6STheodore Ts'o 	int ret = 0;
402426a4c0c6STheodore Ts'o 
4025a4bb6b64SAllison Henderson 	if (!S_ISREG(inode->i_mode))
402673355192SAllison Henderson 		return -EOPNOTSUPP;
4027a4bb6b64SAllison Henderson 
4028b8a86845SLukas Czerner 	trace_ext4_punch_hole(inode, offset, length, 0);
4029aaddea81SZheng Liu 
403026a4c0c6STheodore Ts'o 	/*
403126a4c0c6STheodore Ts'o 	 * Write out all dirty pages to avoid race conditions
403226a4c0c6STheodore Ts'o 	 * Then release them.
403326a4c0c6STheodore Ts'o 	 */
4034cca32b7eSRoss Zwisler 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
403526a4c0c6STheodore Ts'o 		ret = filemap_write_and_wait_range(mapping, offset,
403626a4c0c6STheodore Ts'o 						   offset + length - 1);
403726a4c0c6STheodore Ts'o 		if (ret)
403826a4c0c6STheodore Ts'o 			return ret;
403926a4c0c6STheodore Ts'o 	}
404026a4c0c6STheodore Ts'o 
40415955102cSAl Viro 	inode_lock(inode);
40429ef06cecSLukas Czerner 
404326a4c0c6STheodore Ts'o 	/* No need to punch hole beyond i_size */
404426a4c0c6STheodore Ts'o 	if (offset >= inode->i_size)
404526a4c0c6STheodore Ts'o 		goto out_mutex;
404626a4c0c6STheodore Ts'o 
404726a4c0c6STheodore Ts'o 	/*
404826a4c0c6STheodore Ts'o 	 * If the hole extends beyond i_size, set the hole
404926a4c0c6STheodore Ts'o 	 * to end after the page that contains i_size
405026a4c0c6STheodore Ts'o 	 */
405126a4c0c6STheodore Ts'o 	if (offset + length > inode->i_size) {
405226a4c0c6STheodore Ts'o 		length = inode->i_size +
405309cbfeafSKirill A. Shutemov 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
405426a4c0c6STheodore Ts'o 		   offset;
405526a4c0c6STheodore Ts'o 	}
405626a4c0c6STheodore Ts'o 
4057a361293fSJan Kara 	if (offset & (sb->s_blocksize - 1) ||
4058a361293fSJan Kara 	    (offset + length) & (sb->s_blocksize - 1)) {
4059a361293fSJan Kara 		/*
4060a361293fSJan Kara 		 * Attach jinode to inode for jbd2 if we do any zeroing of
4061a361293fSJan Kara 		 * partial block
4062a361293fSJan Kara 		 */
4063a361293fSJan Kara 		ret = ext4_inode_attach_jinode(inode);
4064a361293fSJan Kara 		if (ret < 0)
4065a361293fSJan Kara 			goto out_mutex;
4066a361293fSJan Kara 
4067a361293fSJan Kara 	}
4068a361293fSJan Kara 
4069ea3d7209SJan Kara 	/* Wait all existing dio workers, newcomers will block on i_mutex */
4070ea3d7209SJan Kara 	ext4_inode_block_unlocked_dio(inode);
4071ea3d7209SJan Kara 	inode_dio_wait(inode);
4072ea3d7209SJan Kara 
4073ea3d7209SJan Kara 	/*
4074ea3d7209SJan Kara 	 * Prevent page faults from reinstantiating pages we have released from
4075ea3d7209SJan Kara 	 * page cache.
4076ea3d7209SJan Kara 	 */
4077ea3d7209SJan Kara 	down_write(&EXT4_I(inode)->i_mmap_sem);
4078a87dd18cSLukas Czerner 	first_block_offset = round_up(offset, sb->s_blocksize);
4079a87dd18cSLukas Czerner 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
408026a4c0c6STheodore Ts'o 
4081a87dd18cSLukas Czerner 	/* Now release the pages and zero block aligned part of pages*/
408201127848SJan Kara 	if (last_block_offset > first_block_offset) {
408301127848SJan Kara 		ret = ext4_update_disksize_before_punch(inode, offset, length);
408401127848SJan Kara 		if (ret)
408501127848SJan Kara 			goto out_dio;
4086a87dd18cSLukas Czerner 		truncate_pagecache_range(inode, first_block_offset,
4087a87dd18cSLukas Czerner 					 last_block_offset);
408801127848SJan Kara 	}
408926a4c0c6STheodore Ts'o 
409026a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
409126a4c0c6STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
409226a4c0c6STheodore Ts'o 	else
409326a4c0c6STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
409426a4c0c6STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
409526a4c0c6STheodore Ts'o 	if (IS_ERR(handle)) {
409626a4c0c6STheodore Ts'o 		ret = PTR_ERR(handle);
409726a4c0c6STheodore Ts'o 		ext4_std_error(sb, ret);
409826a4c0c6STheodore Ts'o 		goto out_dio;
409926a4c0c6STheodore Ts'o 	}
410026a4c0c6STheodore Ts'o 
4101a87dd18cSLukas Czerner 	ret = ext4_zero_partial_blocks(handle, inode, offset,
4102a87dd18cSLukas Czerner 				       length);
410326a4c0c6STheodore Ts'o 	if (ret)
410426a4c0c6STheodore Ts'o 		goto out_stop;
410526a4c0c6STheodore Ts'o 
410626a4c0c6STheodore Ts'o 	first_block = (offset + sb->s_blocksize - 1) >>
410726a4c0c6STheodore Ts'o 		EXT4_BLOCK_SIZE_BITS(sb);
410826a4c0c6STheodore Ts'o 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
410926a4c0c6STheodore Ts'o 
411026a4c0c6STheodore Ts'o 	/* If there are no blocks to remove, return now */
411126a4c0c6STheodore Ts'o 	if (first_block >= stop_block)
411226a4c0c6STheodore Ts'o 		goto out_stop;
411326a4c0c6STheodore Ts'o 
411426a4c0c6STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
411526a4c0c6STheodore Ts'o 	ext4_discard_preallocations(inode);
411626a4c0c6STheodore Ts'o 
411726a4c0c6STheodore Ts'o 	ret = ext4_es_remove_extent(inode, first_block,
411826a4c0c6STheodore Ts'o 				    stop_block - first_block);
411926a4c0c6STheodore Ts'o 	if (ret) {
412026a4c0c6STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
412126a4c0c6STheodore Ts'o 		goto out_stop;
412226a4c0c6STheodore Ts'o 	}
412326a4c0c6STheodore Ts'o 
412426a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
412526a4c0c6STheodore Ts'o 		ret = ext4_ext_remove_space(inode, first_block,
412626a4c0c6STheodore Ts'o 					    stop_block - 1);
412726a4c0c6STheodore Ts'o 	else
41284f579ae7SLukas Czerner 		ret = ext4_ind_remove_space(handle, inode, first_block,
412926a4c0c6STheodore Ts'o 					    stop_block);
413026a4c0c6STheodore Ts'o 
4131819c4920STheodore Ts'o 	up_write(&EXT4_I(inode)->i_data_sem);
413226a4c0c6STheodore Ts'o 	if (IS_SYNC(inode))
413326a4c0c6STheodore Ts'o 		ext4_handle_sync(handle);
4134e251f9bcSMaxim Patlasov 
4135eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
413626a4c0c6STheodore Ts'o 	ext4_mark_inode_dirty(handle, inode);
413726a4c0c6STheodore Ts'o out_stop:
413826a4c0c6STheodore Ts'o 	ext4_journal_stop(handle);
413926a4c0c6STheodore Ts'o out_dio:
4140ea3d7209SJan Kara 	up_write(&EXT4_I(inode)->i_mmap_sem);
414126a4c0c6STheodore Ts'o 	ext4_inode_resume_unlocked_dio(inode);
414226a4c0c6STheodore Ts'o out_mutex:
41435955102cSAl Viro 	inode_unlock(inode);
414426a4c0c6STheodore Ts'o 	return ret;
4145a4bb6b64SAllison Henderson }
4146a4bb6b64SAllison Henderson 
4147a361293fSJan Kara int ext4_inode_attach_jinode(struct inode *inode)
4148a361293fSJan Kara {
4149a361293fSJan Kara 	struct ext4_inode_info *ei = EXT4_I(inode);
4150a361293fSJan Kara 	struct jbd2_inode *jinode;
4151a361293fSJan Kara 
4152a361293fSJan Kara 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4153a361293fSJan Kara 		return 0;
4154a361293fSJan Kara 
4155a361293fSJan Kara 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4156a361293fSJan Kara 	spin_lock(&inode->i_lock);
4157a361293fSJan Kara 	if (!ei->jinode) {
4158a361293fSJan Kara 		if (!jinode) {
4159a361293fSJan Kara 			spin_unlock(&inode->i_lock);
4160a361293fSJan Kara 			return -ENOMEM;
4161a361293fSJan Kara 		}
4162a361293fSJan Kara 		ei->jinode = jinode;
4163a361293fSJan Kara 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4164a361293fSJan Kara 		jinode = NULL;
4165a361293fSJan Kara 	}
4166a361293fSJan Kara 	spin_unlock(&inode->i_lock);
4167a361293fSJan Kara 	if (unlikely(jinode != NULL))
4168a361293fSJan Kara 		jbd2_free_inode(jinode);
4169a361293fSJan Kara 	return 0;
4170a361293fSJan Kara }
4171a361293fSJan Kara 
4172a4bb6b64SAllison Henderson /*
4173617ba13bSMingming Cao  * ext4_truncate()
4174ac27a0ecSDave Kleikamp  *
4175617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
4176617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4177ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
4178ac27a0ecSDave Kleikamp  *
417942b2aa86SJustin P. Mattock  * As we work through the truncate and commit bits of it to the journal there
4180ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
4181ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
4182ac27a0ecSDave Kleikamp  *
4183ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
4184ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
4185ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
4186ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
4187ac27a0ecSDave Kleikamp  * left-to-right works OK too).
4188ac27a0ecSDave Kleikamp  *
4189ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
4190ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
4191ac27a0ecSDave Kleikamp  *
4192ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
4193617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4194ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
4195617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
4196617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
4197ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
4198617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
4199ac27a0ecSDave Kleikamp  */
42002c98eb5eSTheodore Ts'o int ext4_truncate(struct inode *inode)
4201ac27a0ecSDave Kleikamp {
4202819c4920STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
4203819c4920STheodore Ts'o 	unsigned int credits;
42042c98eb5eSTheodore Ts'o 	int err = 0;
4205819c4920STheodore Ts'o 	handle_t *handle;
4206819c4920STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
4207819c4920STheodore Ts'o 
420819b5ef61STheodore Ts'o 	/*
420919b5ef61STheodore Ts'o 	 * There is a possibility that we're either freeing the inode
4210e04027e8SMatthew Wilcox 	 * or it's a completely new inode. In those cases we might not
421119b5ef61STheodore Ts'o 	 * have i_mutex locked because it's not necessary.
421219b5ef61STheodore Ts'o 	 */
421319b5ef61STheodore Ts'o 	if (!(inode->i_state & (I_NEW|I_FREEING)))
42145955102cSAl Viro 		WARN_ON(!inode_is_locked(inode));
42150562e0baSJiaying Zhang 	trace_ext4_truncate_enter(inode);
42160562e0baSJiaying Zhang 
421791ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
42182c98eb5eSTheodore Ts'o 		return 0;
4219ac27a0ecSDave Kleikamp 
422012e9b892SDmitry Monakhov 	ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4221c8d46e41SJiaying Zhang 
42225534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
422319f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
42247d8f9f7dSTheodore Ts'o 
4225aef1c851STao Ma 	if (ext4_has_inline_data(inode)) {
4226aef1c851STao Ma 		int has_inline = 1;
4227aef1c851STao Ma 
422801daf945STheodore Ts'o 		err = ext4_inline_data_truncate(inode, &has_inline);
422901daf945STheodore Ts'o 		if (err)
423001daf945STheodore Ts'o 			return err;
4231aef1c851STao Ma 		if (has_inline)
42322c98eb5eSTheodore Ts'o 			return 0;
4233aef1c851STao Ma 	}
4234aef1c851STao Ma 
4235a361293fSJan Kara 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4236a361293fSJan Kara 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4237a361293fSJan Kara 		if (ext4_inode_attach_jinode(inode) < 0)
42382c98eb5eSTheodore Ts'o 			return 0;
4239a361293fSJan Kara 	}
4240a361293fSJan Kara 
4241ff9893dcSAmir Goldstein 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4242819c4920STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
4243ff9893dcSAmir Goldstein 	else
4244819c4920STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
4245819c4920STheodore Ts'o 
4246819c4920STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
42472c98eb5eSTheodore Ts'o 	if (IS_ERR(handle))
42482c98eb5eSTheodore Ts'o 		return PTR_ERR(handle);
4249819c4920STheodore Ts'o 
4250eb3544c6SLukas Czerner 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4251eb3544c6SLukas Czerner 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4252819c4920STheodore Ts'o 
4253819c4920STheodore Ts'o 	/*
4254819c4920STheodore Ts'o 	 * We add the inode to the orphan list, so that if this
4255819c4920STheodore Ts'o 	 * truncate spans multiple transactions, and we crash, we will
4256819c4920STheodore Ts'o 	 * resume the truncate when the filesystem recovers.  It also
4257819c4920STheodore Ts'o 	 * marks the inode dirty, to catch the new size.
4258819c4920STheodore Ts'o 	 *
4259819c4920STheodore Ts'o 	 * Implication: the file must always be in a sane, consistent
4260819c4920STheodore Ts'o 	 * truncatable state while each transaction commits.
4261819c4920STheodore Ts'o 	 */
42622c98eb5eSTheodore Ts'o 	err = ext4_orphan_add(handle, inode);
42632c98eb5eSTheodore Ts'o 	if (err)
4264819c4920STheodore Ts'o 		goto out_stop;
4265819c4920STheodore Ts'o 
4266819c4920STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
4267819c4920STheodore Ts'o 
4268819c4920STheodore Ts'o 	ext4_discard_preallocations(inode);
4269819c4920STheodore Ts'o 
4270819c4920STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4271d0abb36dSTheodore Ts'o 		err = ext4_ext_truncate(handle, inode);
4272819c4920STheodore Ts'o 	else
4273819c4920STheodore Ts'o 		ext4_ind_truncate(handle, inode);
4274819c4920STheodore Ts'o 
4275819c4920STheodore Ts'o 	up_write(&ei->i_data_sem);
4276d0abb36dSTheodore Ts'o 	if (err)
4277d0abb36dSTheodore Ts'o 		goto out_stop;
4278819c4920STheodore Ts'o 
4279819c4920STheodore Ts'o 	if (IS_SYNC(inode))
4280819c4920STheodore Ts'o 		ext4_handle_sync(handle);
4281819c4920STheodore Ts'o 
4282819c4920STheodore Ts'o out_stop:
4283819c4920STheodore Ts'o 	/*
4284819c4920STheodore Ts'o 	 * If this was a simple ftruncate() and the file will remain alive,
4285819c4920STheodore Ts'o 	 * then we need to clear up the orphan record which we created above.
4286819c4920STheodore Ts'o 	 * However, if this was a real unlink then we were called by
428758d86a50SWang Shilong 	 * ext4_evict_inode(), and we allow that function to clean up the
4288819c4920STheodore Ts'o 	 * orphan info for us.
4289819c4920STheodore Ts'o 	 */
4290819c4920STheodore Ts'o 	if (inode->i_nlink)
4291819c4920STheodore Ts'o 		ext4_orphan_del(handle, inode);
4292819c4920STheodore Ts'o 
4293eeca7ea1SDeepa Dinamani 	inode->i_mtime = inode->i_ctime = current_time(inode);
4294819c4920STheodore Ts'o 	ext4_mark_inode_dirty(handle, inode);
4295819c4920STheodore Ts'o 	ext4_journal_stop(handle);
4296a86c6181SAlex Tomas 
42970562e0baSJiaying Zhang 	trace_ext4_truncate_exit(inode);
42982c98eb5eSTheodore Ts'o 	return err;
4299ac27a0ecSDave Kleikamp }
4300ac27a0ecSDave Kleikamp 
4301ac27a0ecSDave Kleikamp /*
4302617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
4303ac27a0ecSDave Kleikamp  * underlying buffer_head on success. If 'in_mem' is true, we have all
4304ac27a0ecSDave Kleikamp  * data in memory that is needed to recreate the on-disk version of this
4305ac27a0ecSDave Kleikamp  * inode.
4306ac27a0ecSDave Kleikamp  */
4307617ba13bSMingming Cao static int __ext4_get_inode_loc(struct inode *inode,
4308617ba13bSMingming Cao 				struct ext4_iloc *iloc, int in_mem)
4309ac27a0ecSDave Kleikamp {
4310240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
4311ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
4312240799cdSTheodore Ts'o 	struct super_block	*sb = inode->i_sb;
4313240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
4314240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
4315ac27a0ecSDave Kleikamp 
43163a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
4317240799cdSTheodore Ts'o 	if (!ext4_valid_inum(sb, inode->i_ino))
43186a797d27SDarrick J. Wong 		return -EFSCORRUPTED;
4319ac27a0ecSDave Kleikamp 
4320240799cdSTheodore Ts'o 	iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4321240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4322240799cdSTheodore Ts'o 	if (!gdp)
4323240799cdSTheodore Ts'o 		return -EIO;
4324240799cdSTheodore Ts'o 
4325240799cdSTheodore Ts'o 	/*
4326240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
4327240799cdSTheodore Ts'o 	 */
432800d09882STao Ma 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4329240799cdSTheodore Ts'o 	inode_offset = ((inode->i_ino - 1) %
4330240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
4331240799cdSTheodore Ts'o 	block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4332240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4333240799cdSTheodore Ts'o 
4334240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
4335aebf0243SWang Shilong 	if (unlikely(!bh))
4336860d21e2STheodore Ts'o 		return -ENOMEM;
4337ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
4338ac27a0ecSDave Kleikamp 		lock_buffer(bh);
43399c83a923SHidehiro Kawai 
43409c83a923SHidehiro Kawai 		/*
43419c83a923SHidehiro Kawai 		 * If the buffer has the write error flag, we have failed
43429c83a923SHidehiro Kawai 		 * to write out another inode in the same block.  In this
43439c83a923SHidehiro Kawai 		 * case, we don't have to read the block because we may
43449c83a923SHidehiro Kawai 		 * read the old inode data successfully.
43459c83a923SHidehiro Kawai 		 */
43469c83a923SHidehiro Kawai 		if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
43479c83a923SHidehiro Kawai 			set_buffer_uptodate(bh);
43489c83a923SHidehiro Kawai 
4349ac27a0ecSDave Kleikamp 		if (buffer_uptodate(bh)) {
4350ac27a0ecSDave Kleikamp 			/* someone brought it uptodate while we waited */
4351ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
4352ac27a0ecSDave Kleikamp 			goto has_buffer;
4353ac27a0ecSDave Kleikamp 		}
4354ac27a0ecSDave Kleikamp 
4355ac27a0ecSDave Kleikamp 		/*
4356ac27a0ecSDave Kleikamp 		 * If we have all information of the inode in memory and this
4357ac27a0ecSDave Kleikamp 		 * is the only valid inode in the block, we need not read the
4358ac27a0ecSDave Kleikamp 		 * block.
4359ac27a0ecSDave Kleikamp 		 */
4360ac27a0ecSDave Kleikamp 		if (in_mem) {
4361ac27a0ecSDave Kleikamp 			struct buffer_head *bitmap_bh;
4362240799cdSTheodore Ts'o 			int i, start;
4363ac27a0ecSDave Kleikamp 
4364240799cdSTheodore Ts'o 			start = inode_offset & ~(inodes_per_block - 1);
4365ac27a0ecSDave Kleikamp 
4366ac27a0ecSDave Kleikamp 			/* Is the inode bitmap in cache? */
4367240799cdSTheodore Ts'o 			bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4368aebf0243SWang Shilong 			if (unlikely(!bitmap_bh))
4369ac27a0ecSDave Kleikamp 				goto make_io;
4370ac27a0ecSDave Kleikamp 
4371ac27a0ecSDave Kleikamp 			/*
4372ac27a0ecSDave Kleikamp 			 * If the inode bitmap isn't in cache then the
4373ac27a0ecSDave Kleikamp 			 * optimisation may end up performing two reads instead
4374ac27a0ecSDave Kleikamp 			 * of one, so skip it.
4375ac27a0ecSDave Kleikamp 			 */
4376ac27a0ecSDave Kleikamp 			if (!buffer_uptodate(bitmap_bh)) {
4377ac27a0ecSDave Kleikamp 				brelse(bitmap_bh);
4378ac27a0ecSDave Kleikamp 				goto make_io;
4379ac27a0ecSDave Kleikamp 			}
4380240799cdSTheodore Ts'o 			for (i = start; i < start + inodes_per_block; i++) {
4381ac27a0ecSDave Kleikamp 				if (i == inode_offset)
4382ac27a0ecSDave Kleikamp 					continue;
4383617ba13bSMingming Cao 				if (ext4_test_bit(i, bitmap_bh->b_data))
4384ac27a0ecSDave Kleikamp 					break;
4385ac27a0ecSDave Kleikamp 			}
4386ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
4387240799cdSTheodore Ts'o 			if (i == start + inodes_per_block) {
4388ac27a0ecSDave Kleikamp 				/* all other inodes are free, so skip I/O */
4389ac27a0ecSDave Kleikamp 				memset(bh->b_data, 0, bh->b_size);
4390ac27a0ecSDave Kleikamp 				set_buffer_uptodate(bh);
4391ac27a0ecSDave Kleikamp 				unlock_buffer(bh);
4392ac27a0ecSDave Kleikamp 				goto has_buffer;
4393ac27a0ecSDave Kleikamp 			}
4394ac27a0ecSDave Kleikamp 		}
4395ac27a0ecSDave Kleikamp 
4396ac27a0ecSDave Kleikamp make_io:
4397ac27a0ecSDave Kleikamp 		/*
4398240799cdSTheodore Ts'o 		 * If we need to do any I/O, try to pre-readahead extra
4399240799cdSTheodore Ts'o 		 * blocks from the inode table.
4400240799cdSTheodore Ts'o 		 */
4401240799cdSTheodore Ts'o 		if (EXT4_SB(sb)->s_inode_readahead_blks) {
4402240799cdSTheodore Ts'o 			ext4_fsblk_t b, end, table;
4403240799cdSTheodore Ts'o 			unsigned num;
44040d606e2cSTheodore Ts'o 			__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4405240799cdSTheodore Ts'o 
4406240799cdSTheodore Ts'o 			table = ext4_inode_table(sb, gdp);
4407b713a5ecSTheodore Ts'o 			/* s_inode_readahead_blks is always a power of 2 */
44080d606e2cSTheodore Ts'o 			b = block & ~((ext4_fsblk_t) ra_blks - 1);
4409240799cdSTheodore Ts'o 			if (table > b)
4410240799cdSTheodore Ts'o 				b = table;
44110d606e2cSTheodore Ts'o 			end = b + ra_blks;
4412240799cdSTheodore Ts'o 			num = EXT4_INODES_PER_GROUP(sb);
4413feb0ab32SDarrick J. Wong 			if (ext4_has_group_desc_csum(sb))
4414560671a0SAneesh Kumar K.V 				num -= ext4_itable_unused_count(sb, gdp);
4415240799cdSTheodore Ts'o 			table += num / inodes_per_block;
4416240799cdSTheodore Ts'o 			if (end > table)
4417240799cdSTheodore Ts'o 				end = table;
4418240799cdSTheodore Ts'o 			while (b <= end)
4419240799cdSTheodore Ts'o 				sb_breadahead(sb, b++);
4420240799cdSTheodore Ts'o 		}
4421240799cdSTheodore Ts'o 
4422240799cdSTheodore Ts'o 		/*
4423ac27a0ecSDave Kleikamp 		 * There are other valid inodes in the buffer, this inode
4424ac27a0ecSDave Kleikamp 		 * has in-inode xattrs, or we don't have this inode in memory.
4425ac27a0ecSDave Kleikamp 		 * Read the block from disk.
4426ac27a0ecSDave Kleikamp 		 */
44270562e0baSJiaying Zhang 		trace_ext4_load_inode(inode);
4428ac27a0ecSDave Kleikamp 		get_bh(bh);
4429ac27a0ecSDave Kleikamp 		bh->b_end_io = end_buffer_read_sync;
44302a222ca9SMike Christie 		submit_bh(REQ_OP_READ, REQ_META | REQ_PRIO, bh);
4431ac27a0ecSDave Kleikamp 		wait_on_buffer(bh);
4432ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bh)) {
4433c398eda0STheodore Ts'o 			EXT4_ERROR_INODE_BLOCK(inode, block,
4434c398eda0STheodore Ts'o 					       "unable to read itable block");
4435ac27a0ecSDave Kleikamp 			brelse(bh);
4436ac27a0ecSDave Kleikamp 			return -EIO;
4437ac27a0ecSDave Kleikamp 		}
4438ac27a0ecSDave Kleikamp 	}
4439ac27a0ecSDave Kleikamp has_buffer:
4440ac27a0ecSDave Kleikamp 	iloc->bh = bh;
4441ac27a0ecSDave Kleikamp 	return 0;
4442ac27a0ecSDave Kleikamp }
4443ac27a0ecSDave Kleikamp 
4444617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4445ac27a0ecSDave Kleikamp {
4446ac27a0ecSDave Kleikamp 	/* We have all inode data except xattrs in memory here. */
4447617ba13bSMingming Cao 	return __ext4_get_inode_loc(inode, iloc,
444819f5fb7aSTheodore Ts'o 		!ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4449ac27a0ecSDave Kleikamp }
4450ac27a0ecSDave Kleikamp 
4451617ba13bSMingming Cao void ext4_set_inode_flags(struct inode *inode)
4452ac27a0ecSDave Kleikamp {
4453617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
445400a1a053STheodore Ts'o 	unsigned int new_fl = 0;
4455ac27a0ecSDave Kleikamp 
4456617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
445700a1a053STheodore Ts'o 		new_fl |= S_SYNC;
4458617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
445900a1a053STheodore Ts'o 		new_fl |= S_APPEND;
4460617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
446100a1a053STheodore Ts'o 		new_fl |= S_IMMUTABLE;
4462617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
446300a1a053STheodore Ts'o 		new_fl |= S_NOATIME;
4464617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
446500a1a053STheodore Ts'o 		new_fl |= S_DIRSYNC;
4466a3caa24bSJan Kara 	if (test_opt(inode->i_sb, DAX) && S_ISREG(inode->i_mode) &&
4467a3caa24bSJan Kara 	    !ext4_should_journal_data(inode) && !ext4_has_inline_data(inode) &&
4468a3caa24bSJan Kara 	    !ext4_encrypted_inode(inode))
4469923ae0ffSRoss Zwisler 		new_fl |= S_DAX;
44705f16f322STheodore Ts'o 	inode_set_flags(inode, new_fl,
4471923ae0ffSRoss Zwisler 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX);
4472ac27a0ecSDave Kleikamp }
4473ac27a0ecSDave Kleikamp 
4474ff9ddf7eSJan Kara /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4475ff9ddf7eSJan Kara void ext4_get_inode_flags(struct ext4_inode_info *ei)
4476ff9ddf7eSJan Kara {
447784a8dce2SDmitry Monakhov 	unsigned int vfs_fl;
447884a8dce2SDmitry Monakhov 	unsigned long old_fl, new_fl;
4479ff9ddf7eSJan Kara 
448084a8dce2SDmitry Monakhov 	do {
448184a8dce2SDmitry Monakhov 		vfs_fl = ei->vfs_inode.i_flags;
448284a8dce2SDmitry Monakhov 		old_fl = ei->i_flags;
448384a8dce2SDmitry Monakhov 		new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
448484a8dce2SDmitry Monakhov 				EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
448584a8dce2SDmitry Monakhov 				EXT4_DIRSYNC_FL);
448684a8dce2SDmitry Monakhov 		if (vfs_fl & S_SYNC)
448784a8dce2SDmitry Monakhov 			new_fl |= EXT4_SYNC_FL;
448884a8dce2SDmitry Monakhov 		if (vfs_fl & S_APPEND)
448984a8dce2SDmitry Monakhov 			new_fl |= EXT4_APPEND_FL;
449084a8dce2SDmitry Monakhov 		if (vfs_fl & S_IMMUTABLE)
449184a8dce2SDmitry Monakhov 			new_fl |= EXT4_IMMUTABLE_FL;
449284a8dce2SDmitry Monakhov 		if (vfs_fl & S_NOATIME)
449384a8dce2SDmitry Monakhov 			new_fl |= EXT4_NOATIME_FL;
449484a8dce2SDmitry Monakhov 		if (vfs_fl & S_DIRSYNC)
449584a8dce2SDmitry Monakhov 			new_fl |= EXT4_DIRSYNC_FL;
449684a8dce2SDmitry Monakhov 	} while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
4497ff9ddf7eSJan Kara }
4498de9a55b8STheodore Ts'o 
44990fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
45000fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
45010fc1b451SAneesh Kumar K.V {
45020fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
45038180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
45048180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
45050fc1b451SAneesh Kumar K.V 
4506e2b911c5SDarrick J. Wong 	if (ext4_has_feature_huge_file(sb)) {
45070fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
45080fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
45090fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
451007a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
45118180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
45128180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
45138180a562SAneesh Kumar K.V 		} else {
45140fc1b451SAneesh Kumar K.V 			return i_blocks;
45158180a562SAneesh Kumar K.V 		}
45160fc1b451SAneesh Kumar K.V 	} else {
45170fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
45180fc1b451SAneesh Kumar K.V 	}
45190fc1b451SAneesh Kumar K.V }
4520ff9ddf7eSJan Kara 
4521152a7b0aSTao Ma static inline void ext4_iget_extra_inode(struct inode *inode,
4522152a7b0aSTao Ma 					 struct ext4_inode *raw_inode,
4523152a7b0aSTao Ma 					 struct ext4_inode_info *ei)
4524152a7b0aSTao Ma {
4525152a7b0aSTao Ma 	__le32 *magic = (void *)raw_inode +
4526152a7b0aSTao Ma 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4527290ab230SEric Biggers 	if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
4528290ab230SEric Biggers 	    EXT4_INODE_SIZE(inode->i_sb) &&
4529290ab230SEric Biggers 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4530152a7b0aSTao Ma 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
453167cf5b09STao Ma 		ext4_find_inline_data_nolock(inode);
4532f19d5870STao Ma 	} else
4533f19d5870STao Ma 		EXT4_I(inode)->i_inline_off = 0;
4534152a7b0aSTao Ma }
4535152a7b0aSTao Ma 
4536040cb378SLi Xi int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4537040cb378SLi Xi {
45380b7b7779SKaho Ng 	if (!ext4_has_feature_project(inode->i_sb))
4539040cb378SLi Xi 		return -EOPNOTSUPP;
4540040cb378SLi Xi 	*projid = EXT4_I(inode)->i_projid;
4541040cb378SLi Xi 	return 0;
4542040cb378SLi Xi }
4543040cb378SLi Xi 
45441d1fe1eeSDavid Howells struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4545ac27a0ecSDave Kleikamp {
4546617ba13bSMingming Cao 	struct ext4_iloc iloc;
4547617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
45481d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
45491d1fe1eeSDavid Howells 	struct inode *inode;
4550b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
45511d1fe1eeSDavid Howells 	long ret;
45527e6e1ef4SDarrick J. Wong 	loff_t size;
4553ac27a0ecSDave Kleikamp 	int block;
455408cefc7aSEric W. Biederman 	uid_t i_uid;
455508cefc7aSEric W. Biederman 	gid_t i_gid;
4556040cb378SLi Xi 	projid_t i_projid;
4557ac27a0ecSDave Kleikamp 
45581d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
45591d1fe1eeSDavid Howells 	if (!inode)
45601d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
45611d1fe1eeSDavid Howells 	if (!(inode->i_state & I_NEW))
45621d1fe1eeSDavid Howells 		return inode;
45631d1fe1eeSDavid Howells 
45641d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
45657dc57615SPeter Huewe 	iloc.bh = NULL;
4566ac27a0ecSDave Kleikamp 
45671d1fe1eeSDavid Howells 	ret = __ext4_get_inode_loc(inode, &iloc, 0);
45681d1fe1eeSDavid Howells 	if (ret < 0)
4569ac27a0ecSDave Kleikamp 		goto bad_inode;
4570617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
4571814525f4SDarrick J. Wong 
4572814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4573814525f4SDarrick J. Wong 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4574814525f4SDarrick J. Wong 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
45752dc8d9e1SEric Biggers 			EXT4_INODE_SIZE(inode->i_sb) ||
45762dc8d9e1SEric Biggers 		    (ei->i_extra_isize & 3)) {
45772dc8d9e1SEric Biggers 			EXT4_ERROR_INODE(inode,
45782dc8d9e1SEric Biggers 					 "bad extra_isize %u (inode size %u)",
45792dc8d9e1SEric Biggers 					 ei->i_extra_isize,
4580814525f4SDarrick J. Wong 					 EXT4_INODE_SIZE(inode->i_sb));
45816a797d27SDarrick J. Wong 			ret = -EFSCORRUPTED;
4582814525f4SDarrick J. Wong 			goto bad_inode;
4583814525f4SDarrick J. Wong 		}
4584814525f4SDarrick J. Wong 	} else
4585814525f4SDarrick J. Wong 		ei->i_extra_isize = 0;
4586814525f4SDarrick J. Wong 
4587814525f4SDarrick J. Wong 	/* Precompute checksum seed for inode metadata */
45889aa5d32bSDmitry Monakhov 	if (ext4_has_metadata_csum(sb)) {
4589814525f4SDarrick J. Wong 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4590814525f4SDarrick J. Wong 		__u32 csum;
4591814525f4SDarrick J. Wong 		__le32 inum = cpu_to_le32(inode->i_ino);
4592814525f4SDarrick J. Wong 		__le32 gen = raw_inode->i_generation;
4593814525f4SDarrick J. Wong 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4594814525f4SDarrick J. Wong 				   sizeof(inum));
4595814525f4SDarrick J. Wong 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4596814525f4SDarrick J. Wong 					      sizeof(gen));
4597814525f4SDarrick J. Wong 	}
4598814525f4SDarrick J. Wong 
4599814525f4SDarrick J. Wong 	if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4600814525f4SDarrick J. Wong 		EXT4_ERROR_INODE(inode, "checksum invalid");
46016a797d27SDarrick J. Wong 		ret = -EFSBADCRC;
4602814525f4SDarrick J. Wong 		goto bad_inode;
4603814525f4SDarrick J. Wong 	}
4604814525f4SDarrick J. Wong 
4605ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
460608cefc7aSEric W. Biederman 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
460708cefc7aSEric W. Biederman 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
46080b7b7779SKaho Ng 	if (ext4_has_feature_project(sb) &&
4609040cb378SLi Xi 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4610040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4611040cb378SLi Xi 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4612040cb378SLi Xi 	else
4613040cb378SLi Xi 		i_projid = EXT4_DEF_PROJID;
4614040cb378SLi Xi 
4615ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
461608cefc7aSEric W. Biederman 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
461708cefc7aSEric W. Biederman 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4618ac27a0ecSDave Kleikamp 	}
461908cefc7aSEric W. Biederman 	i_uid_write(inode, i_uid);
462008cefc7aSEric W. Biederman 	i_gid_write(inode, i_gid);
4621040cb378SLi Xi 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4622bfe86848SMiklos Szeredi 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4623ac27a0ecSDave Kleikamp 
4624353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
462567cf5b09STao Ma 	ei->i_inline_off = 0;
4626ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
4627ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4628ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
4629ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
4630ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
4631ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
4632ac27a0ecSDave Kleikamp 	 */
4633ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
4634393d1d1dSDr. Tilmann Bubeck 		if ((inode->i_mode == 0 ||
4635393d1d1dSDr. Tilmann Bubeck 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4636393d1d1dSDr. Tilmann Bubeck 		    ino != EXT4_BOOT_LOADER_INO) {
4637ac27a0ecSDave Kleikamp 			/* this inode is deleted */
46381d1fe1eeSDavid Howells 			ret = -ESTALE;
4639ac27a0ecSDave Kleikamp 			goto bad_inode;
4640ac27a0ecSDave Kleikamp 		}
4641ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
4642ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
4643ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
4644393d1d1dSDr. Tilmann Bubeck 		 * the process of deleting those.
4645393d1d1dSDr. Tilmann Bubeck 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4646393d1d1dSDr. Tilmann Bubeck 		 * not initialized on a new filesystem. */
4647ac27a0ecSDave Kleikamp 	}
4648ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
46490fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
46507973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4651e2b911c5SDarrick J. Wong 	if (ext4_has_feature_64bit(sb))
4652a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
4653a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4654a48380f7SAneesh Kumar K.V 	inode->i_size = ext4_isize(raw_inode);
46557e6e1ef4SDarrick J. Wong 	if ((size = i_size_read(inode)) < 0) {
46567e6e1ef4SDarrick J. Wong 		EXT4_ERROR_INODE(inode, "bad i_size value: %lld", size);
46577e6e1ef4SDarrick J. Wong 		ret = -EFSCORRUPTED;
46587e6e1ef4SDarrick J. Wong 		goto bad_inode;
46597e6e1ef4SDarrick J. Wong 	}
4660ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
4661a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
4662a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
4663a9e7f447SDmitry Monakhov #endif
4664ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4665ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
4666a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
4667ac27a0ecSDave Kleikamp 	/*
4668ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
4669ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4670ac27a0ecSDave Kleikamp 	 */
4671617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4672ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
4673ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
4674ac27a0ecSDave Kleikamp 
4675b436b9beSJan Kara 	/*
4676b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
4677b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
4678b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
4679b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
4680b436b9beSJan Kara 	 * now it is reread from disk.
4681b436b9beSJan Kara 	 */
4682b436b9beSJan Kara 	if (journal) {
4683b436b9beSJan Kara 		transaction_t *transaction;
4684b436b9beSJan Kara 		tid_t tid;
4685b436b9beSJan Kara 
4686a931da6aSTheodore Ts'o 		read_lock(&journal->j_state_lock);
4687b436b9beSJan Kara 		if (journal->j_running_transaction)
4688b436b9beSJan Kara 			transaction = journal->j_running_transaction;
4689b436b9beSJan Kara 		else
4690b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
4691b436b9beSJan Kara 		if (transaction)
4692b436b9beSJan Kara 			tid = transaction->t_tid;
4693b436b9beSJan Kara 		else
4694b436b9beSJan Kara 			tid = journal->j_commit_sequence;
4695a931da6aSTheodore Ts'o 		read_unlock(&journal->j_state_lock);
4696b436b9beSJan Kara 		ei->i_sync_tid = tid;
4697b436b9beSJan Kara 		ei->i_datasync_tid = tid;
4698b436b9beSJan Kara 	}
4699b436b9beSJan Kara 
47000040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4701ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
4702ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
47032dc8d9e1SEric Biggers 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4704617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4705617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
4706ac27a0ecSDave Kleikamp 		} else {
4707152a7b0aSTao Ma 			ext4_iget_extra_inode(inode, raw_inode, ei);
4708ac27a0ecSDave Kleikamp 		}
4709814525f4SDarrick J. Wong 	}
4710ac27a0ecSDave Kleikamp 
4711ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4712ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4713ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4714ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4715ef7f3835SKalpak Shah 
4716ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
471725ec56b5SJean Noel Cordenner 		inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
471825ec56b5SJean Noel Cordenner 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
471925ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
472025ec56b5SJean Noel Cordenner 				inode->i_version |=
472125ec56b5SJean Noel Cordenner 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
472225ec56b5SJean Noel Cordenner 		}
4723c4f65706STheodore Ts'o 	}
472425ec56b5SJean Noel Cordenner 
4725c4b5a614STheodore Ts'o 	ret = 0;
4726485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
47271032988cSTheodore Ts'o 	    !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
472824676da4STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
472924676da4STheodore Ts'o 				 ei->i_file_acl);
47306a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
4731485c26ecSTheodore Ts'o 		goto bad_inode;
4732f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
4733f19d5870STao Ma 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4734f19d5870STao Ma 			if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4735c4b5a614STheodore Ts'o 			    (S_ISLNK(inode->i_mode) &&
4736f19d5870STao Ma 			     !ext4_inode_is_fast_symlink(inode))))
47377a262f7cSAneesh Kumar K.V 				/* Validate extent which is part of inode */
47387a262f7cSAneesh Kumar K.V 				ret = ext4_ext_check_inode(inode);
4739fe2c8191SThiemo Nagel 		} else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4740fe2c8191SThiemo Nagel 			   (S_ISLNK(inode->i_mode) &&
4741fe2c8191SThiemo Nagel 			    !ext4_inode_is_fast_symlink(inode))) {
4742fe2c8191SThiemo Nagel 			/* Validate block references which are part of inode */
47431f7d1e77STheodore Ts'o 			ret = ext4_ind_check_inode(inode);
4744fe2c8191SThiemo Nagel 		}
4745f19d5870STao Ma 	}
4746567f3e9aSTheodore Ts'o 	if (ret)
47477a262f7cSAneesh Kumar K.V 		goto bad_inode;
47487a262f7cSAneesh Kumar K.V 
4749ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
4750617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
4751617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
4752617ba13bSMingming Cao 		ext4_set_aops(inode);
4753ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
4754617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
4755617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
4756ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
4757a7a67e8aSAl Viro 		if (ext4_encrypted_inode(inode)) {
4758a7a67e8aSAl Viro 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
4759a7a67e8aSAl Viro 			ext4_set_aops(inode);
4760a7a67e8aSAl Viro 		} else if (ext4_inode_is_fast_symlink(inode)) {
476175e7566bSAl Viro 			inode->i_link = (char *)ei->i_data;
4762617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
4763e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
4764e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
4765e83c1397SDuane Griffin 		} else {
4766617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
4767617ba13bSMingming Cao 			ext4_set_aops(inode);
4768ac27a0ecSDave Kleikamp 		}
476921fc61c7SAl Viro 		inode_nohighmem(inode);
4770563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4771563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4772617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
4773ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
4774ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
4775ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4776ac27a0ecSDave Kleikamp 		else
4777ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
4778ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4779393d1d1dSDr. Tilmann Bubeck 	} else if (ino == EXT4_BOOT_LOADER_INO) {
4780393d1d1dSDr. Tilmann Bubeck 		make_bad_inode(inode);
4781563bdd61STheodore Ts'o 	} else {
47826a797d27SDarrick J. Wong 		ret = -EFSCORRUPTED;
478324676da4STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4784563bdd61STheodore Ts'o 		goto bad_inode;
4785ac27a0ecSDave Kleikamp 	}
4786ac27a0ecSDave Kleikamp 	brelse(iloc.bh);
4787617ba13bSMingming Cao 	ext4_set_inode_flags(inode);
47881d1fe1eeSDavid Howells 	unlock_new_inode(inode);
47891d1fe1eeSDavid Howells 	return inode;
4790ac27a0ecSDave Kleikamp 
4791ac27a0ecSDave Kleikamp bad_inode:
4792567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
47931d1fe1eeSDavid Howells 	iget_failed(inode);
47941d1fe1eeSDavid Howells 	return ERR_PTR(ret);
4795ac27a0ecSDave Kleikamp }
4796ac27a0ecSDave Kleikamp 
4797f4bb2981STheodore Ts'o struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino)
4798f4bb2981STheodore Ts'o {
4799f4bb2981STheodore Ts'o 	if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
48006a797d27SDarrick J. Wong 		return ERR_PTR(-EFSCORRUPTED);
4801f4bb2981STheodore Ts'o 	return ext4_iget(sb, ino);
4802f4bb2981STheodore Ts'o }
4803f4bb2981STheodore Ts'o 
48040fc1b451SAneesh Kumar K.V static int ext4_inode_blocks_set(handle_t *handle,
48050fc1b451SAneesh Kumar K.V 				struct ext4_inode *raw_inode,
48060fc1b451SAneesh Kumar K.V 				struct ext4_inode_info *ei)
48070fc1b451SAneesh Kumar K.V {
48080fc1b451SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
48090fc1b451SAneesh Kumar K.V 	u64 i_blocks = inode->i_blocks;
48100fc1b451SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
48110fc1b451SAneesh Kumar K.V 
48120fc1b451SAneesh Kumar K.V 	if (i_blocks <= ~0U) {
48130fc1b451SAneesh Kumar K.V 		/*
48144907cb7bSAnatol Pomozov 		 * i_blocks can be represented in a 32 bit variable
48150fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
48160fc1b451SAneesh Kumar K.V 		 */
48178180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
48180fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = 0;
481984a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4820f287a1a5STheodore Ts'o 		return 0;
4821f287a1a5STheodore Ts'o 	}
4822e2b911c5SDarrick J. Wong 	if (!ext4_has_feature_huge_file(sb))
4823f287a1a5STheodore Ts'o 		return -EFBIG;
4824f287a1a5STheodore Ts'o 
4825f287a1a5STheodore Ts'o 	if (i_blocks <= 0xffffffffffffULL) {
48260fc1b451SAneesh Kumar K.V 		/*
48270fc1b451SAneesh Kumar K.V 		 * i_blocks can be represented in a 48 bit variable
48280fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
48290fc1b451SAneesh Kumar K.V 		 */
48308180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
48310fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
483284a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
48330fc1b451SAneesh Kumar K.V 	} else {
483484a8dce2SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
48358180a562SAneesh Kumar K.V 		/* i_block is stored in file system block size */
48368180a562SAneesh Kumar K.V 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
48378180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
48388180a562SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
48390fc1b451SAneesh Kumar K.V 	}
4840f287a1a5STheodore Ts'o 	return 0;
48410fc1b451SAneesh Kumar K.V }
48420fc1b451SAneesh Kumar K.V 
4843a26f4992STheodore Ts'o struct other_inode {
4844a26f4992STheodore Ts'o 	unsigned long		orig_ino;
4845a26f4992STheodore Ts'o 	struct ext4_inode	*raw_inode;
4846a26f4992STheodore Ts'o };
4847a26f4992STheodore Ts'o 
4848a26f4992STheodore Ts'o static int other_inode_match(struct inode * inode, unsigned long ino,
4849a26f4992STheodore Ts'o 			     void *data)
4850a26f4992STheodore Ts'o {
4851a26f4992STheodore Ts'o 	struct other_inode *oi = (struct other_inode *) data;
4852a26f4992STheodore Ts'o 
4853a26f4992STheodore Ts'o 	if ((inode->i_ino != ino) ||
4854a26f4992STheodore Ts'o 	    (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4855a26f4992STheodore Ts'o 			       I_DIRTY_SYNC | I_DIRTY_DATASYNC)) ||
4856a26f4992STheodore Ts'o 	    ((inode->i_state & I_DIRTY_TIME) == 0))
4857a26f4992STheodore Ts'o 		return 0;
4858a26f4992STheodore Ts'o 	spin_lock(&inode->i_lock);
4859a26f4992STheodore Ts'o 	if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4860a26f4992STheodore Ts'o 				I_DIRTY_SYNC | I_DIRTY_DATASYNC)) == 0) &&
4861a26f4992STheodore Ts'o 	    (inode->i_state & I_DIRTY_TIME)) {
4862a26f4992STheodore Ts'o 		struct ext4_inode_info	*ei = EXT4_I(inode);
4863a26f4992STheodore Ts'o 
4864a26f4992STheodore Ts'o 		inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED);
4865a26f4992STheodore Ts'o 		spin_unlock(&inode->i_lock);
4866a26f4992STheodore Ts'o 
4867a26f4992STheodore Ts'o 		spin_lock(&ei->i_raw_lock);
4868a26f4992STheodore Ts'o 		EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
4869a26f4992STheodore Ts'o 		EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
4870a26f4992STheodore Ts'o 		EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
4871a26f4992STheodore Ts'o 		ext4_inode_csum_set(inode, oi->raw_inode, ei);
4872a26f4992STheodore Ts'o 		spin_unlock(&ei->i_raw_lock);
4873a26f4992STheodore Ts'o 		trace_ext4_other_inode_update_time(inode, oi->orig_ino);
4874a26f4992STheodore Ts'o 		return -1;
4875a26f4992STheodore Ts'o 	}
4876a26f4992STheodore Ts'o 	spin_unlock(&inode->i_lock);
4877a26f4992STheodore Ts'o 	return -1;
4878a26f4992STheodore Ts'o }
4879a26f4992STheodore Ts'o 
4880a26f4992STheodore Ts'o /*
4881a26f4992STheodore Ts'o  * Opportunistically update the other time fields for other inodes in
4882a26f4992STheodore Ts'o  * the same inode table block.
4883a26f4992STheodore Ts'o  */
4884a26f4992STheodore Ts'o static void ext4_update_other_inodes_time(struct super_block *sb,
4885a26f4992STheodore Ts'o 					  unsigned long orig_ino, char *buf)
4886a26f4992STheodore Ts'o {
4887a26f4992STheodore Ts'o 	struct other_inode oi;
4888a26f4992STheodore Ts'o 	unsigned long ino;
4889a26f4992STheodore Ts'o 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4890a26f4992STheodore Ts'o 	int inode_size = EXT4_INODE_SIZE(sb);
4891a26f4992STheodore Ts'o 
4892a26f4992STheodore Ts'o 	oi.orig_ino = orig_ino;
48930f0ff9a9STheodore Ts'o 	/*
48940f0ff9a9STheodore Ts'o 	 * Calculate the first inode in the inode table block.  Inode
48950f0ff9a9STheodore Ts'o 	 * numbers are one-based.  That is, the first inode in a block
48960f0ff9a9STheodore Ts'o 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
48970f0ff9a9STheodore Ts'o 	 */
48980f0ff9a9STheodore Ts'o 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
4899a26f4992STheodore Ts'o 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
4900a26f4992STheodore Ts'o 		if (ino == orig_ino)
4901a26f4992STheodore Ts'o 			continue;
4902a26f4992STheodore Ts'o 		oi.raw_inode = (struct ext4_inode *) buf;
4903a26f4992STheodore Ts'o 		(void) find_inode_nowait(sb, ino, other_inode_match, &oi);
4904a26f4992STheodore Ts'o 	}
4905a26f4992STheodore Ts'o }
4906a26f4992STheodore Ts'o 
4907ac27a0ecSDave Kleikamp /*
4908ac27a0ecSDave Kleikamp  * Post the struct inode info into an on-disk inode location in the
4909ac27a0ecSDave Kleikamp  * buffer-cache.  This gobbles the caller's reference to the
4910ac27a0ecSDave Kleikamp  * buffer_head in the inode location struct.
4911ac27a0ecSDave Kleikamp  *
4912ac27a0ecSDave Kleikamp  * The caller must have write access to iloc->bh.
4913ac27a0ecSDave Kleikamp  */
4914617ba13bSMingming Cao static int ext4_do_update_inode(handle_t *handle,
4915ac27a0ecSDave Kleikamp 				struct inode *inode,
4916830156c7SFrank Mayhar 				struct ext4_iloc *iloc)
4917ac27a0ecSDave Kleikamp {
4918617ba13bSMingming Cao 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4919617ba13bSMingming Cao 	struct ext4_inode_info *ei = EXT4_I(inode);
4920ac27a0ecSDave Kleikamp 	struct buffer_head *bh = iloc->bh;
4921202ee5dfSTheodore Ts'o 	struct super_block *sb = inode->i_sb;
4922ac27a0ecSDave Kleikamp 	int err = 0, rc, block;
4923202ee5dfSTheodore Ts'o 	int need_datasync = 0, set_large_file = 0;
492408cefc7aSEric W. Biederman 	uid_t i_uid;
492508cefc7aSEric W. Biederman 	gid_t i_gid;
4926040cb378SLi Xi 	projid_t i_projid;
4927ac27a0ecSDave Kleikamp 
4928202ee5dfSTheodore Ts'o 	spin_lock(&ei->i_raw_lock);
4929202ee5dfSTheodore Ts'o 
4930202ee5dfSTheodore Ts'o 	/* For fields not tracked in the in-memory inode,
4931ac27a0ecSDave Kleikamp 	 * initialise them to zero for new inodes. */
493219f5fb7aSTheodore Ts'o 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4933617ba13bSMingming Cao 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4934ac27a0ecSDave Kleikamp 
4935ff9ddf7eSJan Kara 	ext4_get_inode_flags(ei);
4936ac27a0ecSDave Kleikamp 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
493708cefc7aSEric W. Biederman 	i_uid = i_uid_read(inode);
493808cefc7aSEric W. Biederman 	i_gid = i_gid_read(inode);
4939040cb378SLi Xi 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
4940ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
494108cefc7aSEric W. Biederman 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
494208cefc7aSEric W. Biederman 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4943ac27a0ecSDave Kleikamp /*
4944ac27a0ecSDave Kleikamp  * Fix up interoperability with old kernels. Otherwise, old inodes get
4945ac27a0ecSDave Kleikamp  * re-used with the upper 16 bits of the uid/gid intact
4946ac27a0ecSDave Kleikamp  */
494793e3b4e6SDaeho Jeong 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
494893e3b4e6SDaeho Jeong 			raw_inode->i_uid_high = 0;
494993e3b4e6SDaeho Jeong 			raw_inode->i_gid_high = 0;
495093e3b4e6SDaeho Jeong 		} else {
4951ac27a0ecSDave Kleikamp 			raw_inode->i_uid_high =
495208cefc7aSEric W. Biederman 				cpu_to_le16(high_16_bits(i_uid));
4953ac27a0ecSDave Kleikamp 			raw_inode->i_gid_high =
495408cefc7aSEric W. Biederman 				cpu_to_le16(high_16_bits(i_gid));
4955ac27a0ecSDave Kleikamp 		}
4956ac27a0ecSDave Kleikamp 	} else {
495708cefc7aSEric W. Biederman 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
495808cefc7aSEric W. Biederman 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4959ac27a0ecSDave Kleikamp 		raw_inode->i_uid_high = 0;
4960ac27a0ecSDave Kleikamp 		raw_inode->i_gid_high = 0;
4961ac27a0ecSDave Kleikamp 	}
4962ac27a0ecSDave Kleikamp 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4963ef7f3835SKalpak Shah 
4964ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4965ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4966ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4967ef7f3835SKalpak Shah 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4968ef7f3835SKalpak Shah 
4969bce92d56SLi Xi 	err = ext4_inode_blocks_set(handle, raw_inode, ei);
4970bce92d56SLi Xi 	if (err) {
4971202ee5dfSTheodore Ts'o 		spin_unlock(&ei->i_raw_lock);
49720fc1b451SAneesh Kumar K.V 		goto out_brelse;
4973202ee5dfSTheodore Ts'o 	}
4974ac27a0ecSDave Kleikamp 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4975353eb83cSTheodore Ts'o 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4976ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4977a1ddeb7eSBadari Pulavarty 		raw_inode->i_file_acl_high =
4978a1ddeb7eSBadari Pulavarty 			cpu_to_le16(ei->i_file_acl >> 32);
49797973c0c1SAneesh Kumar K.V 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4980b71fc079SJan Kara 	if (ei->i_disksize != ext4_isize(raw_inode)) {
4981a48380f7SAneesh Kumar K.V 		ext4_isize_set(raw_inode, ei->i_disksize);
4982b71fc079SJan Kara 		need_datasync = 1;
4983b71fc079SJan Kara 	}
4984ac27a0ecSDave Kleikamp 	if (ei->i_disksize > 0x7fffffffULL) {
4985e2b911c5SDarrick J. Wong 		if (!ext4_has_feature_large_file(sb) ||
4986617ba13bSMingming Cao 				EXT4_SB(sb)->s_es->s_rev_level ==
4987202ee5dfSTheodore Ts'o 		    cpu_to_le32(EXT4_GOOD_OLD_REV))
4988202ee5dfSTheodore Ts'o 			set_large_file = 1;
4989ac27a0ecSDave Kleikamp 	}
4990ac27a0ecSDave Kleikamp 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4991ac27a0ecSDave Kleikamp 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4992ac27a0ecSDave Kleikamp 		if (old_valid_dev(inode->i_rdev)) {
4993ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] =
4994ac27a0ecSDave Kleikamp 				cpu_to_le32(old_encode_dev(inode->i_rdev));
4995ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] = 0;
4996ac27a0ecSDave Kleikamp 		} else {
4997ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] = 0;
4998ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] =
4999ac27a0ecSDave Kleikamp 				cpu_to_le32(new_encode_dev(inode->i_rdev));
5000ac27a0ecSDave Kleikamp 			raw_inode->i_block[2] = 0;
5001ac27a0ecSDave Kleikamp 		}
5002f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
5003de9a55b8STheodore Ts'o 		for (block = 0; block < EXT4_N_BLOCKS; block++)
5004ac27a0ecSDave Kleikamp 			raw_inode->i_block[block] = ei->i_data[block];
5005f19d5870STao Ma 	}
5006ac27a0ecSDave Kleikamp 
5007ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
500825ec56b5SJean Noel Cordenner 		raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
500925ec56b5SJean Noel Cordenner 		if (ei->i_extra_isize) {
501025ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
501125ec56b5SJean Noel Cordenner 				raw_inode->i_version_hi =
501225ec56b5SJean Noel Cordenner 					cpu_to_le32(inode->i_version >> 32);
5013c4f65706STheodore Ts'o 			raw_inode->i_extra_isize =
5014c4f65706STheodore Ts'o 				cpu_to_le16(ei->i_extra_isize);
5015c4f65706STheodore Ts'o 		}
501625ec56b5SJean Noel Cordenner 	}
5017040cb378SLi Xi 
50180b7b7779SKaho Ng 	BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
5019040cb378SLi Xi 	       i_projid != EXT4_DEF_PROJID);
5020040cb378SLi Xi 
5021040cb378SLi Xi 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5022040cb378SLi Xi 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5023040cb378SLi Xi 		raw_inode->i_projid = cpu_to_le32(i_projid);
5024040cb378SLi Xi 
5025814525f4SDarrick J. Wong 	ext4_inode_csum_set(inode, raw_inode, ei);
5026202ee5dfSTheodore Ts'o 	spin_unlock(&ei->i_raw_lock);
5027a26f4992STheodore Ts'o 	if (inode->i_sb->s_flags & MS_LAZYTIME)
5028a26f4992STheodore Ts'o 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5029a26f4992STheodore Ts'o 					      bh->b_data);
5030202ee5dfSTheodore Ts'o 
50310390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
503273b50c1cSCurt Wohlgemuth 	rc = ext4_handle_dirty_metadata(handle, NULL, bh);
5033ac27a0ecSDave Kleikamp 	if (!err)
5034ac27a0ecSDave Kleikamp 		err = rc;
503519f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5036202ee5dfSTheodore Ts'o 	if (set_large_file) {
50375d601255Sliang xie 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5038202ee5dfSTheodore Ts'o 		err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5039202ee5dfSTheodore Ts'o 		if (err)
5040202ee5dfSTheodore Ts'o 			goto out_brelse;
5041202ee5dfSTheodore Ts'o 		ext4_update_dynamic_rev(sb);
5042e2b911c5SDarrick J. Wong 		ext4_set_feature_large_file(sb);
5043202ee5dfSTheodore Ts'o 		ext4_handle_sync(handle);
5044202ee5dfSTheodore Ts'o 		err = ext4_handle_dirty_super(handle, sb);
5045202ee5dfSTheodore Ts'o 	}
5046b71fc079SJan Kara 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5047ac27a0ecSDave Kleikamp out_brelse:
5048ac27a0ecSDave Kleikamp 	brelse(bh);
5049617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5050ac27a0ecSDave Kleikamp 	return err;
5051ac27a0ecSDave Kleikamp }
5052ac27a0ecSDave Kleikamp 
5053ac27a0ecSDave Kleikamp /*
5054617ba13bSMingming Cao  * ext4_write_inode()
5055ac27a0ecSDave Kleikamp  *
5056ac27a0ecSDave Kleikamp  * We are called from a few places:
5057ac27a0ecSDave Kleikamp  *
505887f7e416STheodore Ts'o  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5059ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
50604907cb7bSAnatol Pomozov  *   transaction to commit.
5061ac27a0ecSDave Kleikamp  *
506287f7e416STheodore Ts'o  * - Within flush work (sys_sync(), kupdate and such).
506387f7e416STheodore Ts'o  *   We wait on commit, if told to.
5064ac27a0ecSDave Kleikamp  *
506587f7e416STheodore Ts'o  * - Within iput_final() -> write_inode_now()
506687f7e416STheodore Ts'o  *   We wait on commit, if told to.
5067ac27a0ecSDave Kleikamp  *
5068ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
5069ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
507087f7e416STheodore Ts'o  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
507187f7e416STheodore Ts'o  * writeback.
5072ac27a0ecSDave Kleikamp  *
5073ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
5074ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5075ac27a0ecSDave Kleikamp  * which we are interested.
5076ac27a0ecSDave Kleikamp  *
5077ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
5078ac27a0ecSDave Kleikamp  *
5079ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
5080ac27a0ecSDave Kleikamp  *	stuff();
5081ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
5082ac27a0ecSDave Kleikamp  *
508387f7e416STheodore Ts'o  * is in error because write_inode() could occur while `stuff()' is running,
508487f7e416STheodore Ts'o  * and the new i_size will be lost.  Plus the inode will no longer be on the
508587f7e416STheodore Ts'o  * superblock's dirty inode list.
5086ac27a0ecSDave Kleikamp  */
5087a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5088ac27a0ecSDave Kleikamp {
508991ac6f43SFrank Mayhar 	int err;
509091ac6f43SFrank Mayhar 
509187f7e416STheodore Ts'o 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
5092ac27a0ecSDave Kleikamp 		return 0;
5093ac27a0ecSDave Kleikamp 
509491ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
5095617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
5096b38bd33aSMingming Cao 			jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5097ac27a0ecSDave Kleikamp 			dump_stack();
5098ac27a0ecSDave Kleikamp 			return -EIO;
5099ac27a0ecSDave Kleikamp 		}
5100ac27a0ecSDave Kleikamp 
510110542c22SJan Kara 		/*
510210542c22SJan Kara 		 * No need to force transaction in WB_SYNC_NONE mode. Also
510310542c22SJan Kara 		 * ext4_sync_fs() will force the commit after everything is
510410542c22SJan Kara 		 * written.
510510542c22SJan Kara 		 */
510610542c22SJan Kara 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5107ac27a0ecSDave Kleikamp 			return 0;
5108ac27a0ecSDave Kleikamp 
510991ac6f43SFrank Mayhar 		err = ext4_force_commit(inode->i_sb);
511091ac6f43SFrank Mayhar 	} else {
511191ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
511291ac6f43SFrank Mayhar 
51138b472d73SCurt Wohlgemuth 		err = __ext4_get_inode_loc(inode, &iloc, 0);
511491ac6f43SFrank Mayhar 		if (err)
511591ac6f43SFrank Mayhar 			return err;
511610542c22SJan Kara 		/*
511710542c22SJan Kara 		 * sync(2) will flush the whole buffer cache. No need to do
511810542c22SJan Kara 		 * it here separately for each inode.
511910542c22SJan Kara 		 */
512010542c22SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5121830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
5122830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5123c398eda0STheodore Ts'o 			EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
5124c398eda0STheodore Ts'o 					 "IO error syncing inode");
5125830156c7SFrank Mayhar 			err = -EIO;
5126830156c7SFrank Mayhar 		}
5127fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
512891ac6f43SFrank Mayhar 	}
512991ac6f43SFrank Mayhar 	return err;
5130ac27a0ecSDave Kleikamp }
5131ac27a0ecSDave Kleikamp 
5132ac27a0ecSDave Kleikamp /*
513353e87268SJan Kara  * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
513453e87268SJan Kara  * buffers that are attached to a page stradding i_size and are undergoing
513553e87268SJan Kara  * commit. In that case we have to wait for commit to finish and try again.
513653e87268SJan Kara  */
513753e87268SJan Kara static void ext4_wait_for_tail_page_commit(struct inode *inode)
513853e87268SJan Kara {
513953e87268SJan Kara 	struct page *page;
514053e87268SJan Kara 	unsigned offset;
514153e87268SJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
514253e87268SJan Kara 	tid_t commit_tid = 0;
514353e87268SJan Kara 	int ret;
514453e87268SJan Kara 
514509cbfeafSKirill A. Shutemov 	offset = inode->i_size & (PAGE_SIZE - 1);
514653e87268SJan Kara 	/*
514753e87268SJan Kara 	 * All buffers in the last page remain valid? Then there's nothing to
5148ea1754a0SKirill A. Shutemov 	 * do. We do the check mainly to optimize the common PAGE_SIZE ==
514953e87268SJan Kara 	 * blocksize case
515053e87268SJan Kara 	 */
515109cbfeafSKirill A. Shutemov 	if (offset > PAGE_SIZE - (1 << inode->i_blkbits))
515253e87268SJan Kara 		return;
515353e87268SJan Kara 	while (1) {
515453e87268SJan Kara 		page = find_lock_page(inode->i_mapping,
515509cbfeafSKirill A. Shutemov 				      inode->i_size >> PAGE_SHIFT);
515653e87268SJan Kara 		if (!page)
515753e87268SJan Kara 			return;
5158ca99fdd2SLukas Czerner 		ret = __ext4_journalled_invalidatepage(page, offset,
515909cbfeafSKirill A. Shutemov 						PAGE_SIZE - offset);
516053e87268SJan Kara 		unlock_page(page);
516109cbfeafSKirill A. Shutemov 		put_page(page);
516253e87268SJan Kara 		if (ret != -EBUSY)
516353e87268SJan Kara 			return;
516453e87268SJan Kara 		commit_tid = 0;
516553e87268SJan Kara 		read_lock(&journal->j_state_lock);
516653e87268SJan Kara 		if (journal->j_committing_transaction)
516753e87268SJan Kara 			commit_tid = journal->j_committing_transaction->t_tid;
516853e87268SJan Kara 		read_unlock(&journal->j_state_lock);
516953e87268SJan Kara 		if (commit_tid)
517053e87268SJan Kara 			jbd2_log_wait_commit(journal, commit_tid);
517153e87268SJan Kara 	}
517253e87268SJan Kara }
517353e87268SJan Kara 
517453e87268SJan Kara /*
5175617ba13bSMingming Cao  * ext4_setattr()
5176ac27a0ecSDave Kleikamp  *
5177ac27a0ecSDave Kleikamp  * Called from notify_change.
5178ac27a0ecSDave Kleikamp  *
5179ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
5180ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
5181ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
5182ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
5183ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
5184ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
5185ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
5186ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
5187ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
5188ac27a0ecSDave Kleikamp  *
5189678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
5190678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
5191678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
5192678aaf48SJan Kara  * This way we are sure that all the data written in the previous
5193678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
5194678aaf48SJan Kara  * writeback).
5195678aaf48SJan Kara  *
5196678aaf48SJan Kara  * Called with inode->i_mutex down.
5197ac27a0ecSDave Kleikamp  */
5198617ba13bSMingming Cao int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5199ac27a0ecSDave Kleikamp {
52002b0143b5SDavid Howells 	struct inode *inode = d_inode(dentry);
5201ac27a0ecSDave Kleikamp 	int error, rc = 0;
52023d287de3SDmitry Monakhov 	int orphan = 0;
5203ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
5204ac27a0ecSDave Kleikamp 
520531051c85SJan Kara 	error = setattr_prepare(dentry, attr);
5206ac27a0ecSDave Kleikamp 	if (error)
5207ac27a0ecSDave Kleikamp 		return error;
5208ac27a0ecSDave Kleikamp 
5209a7cdadeeSJan Kara 	if (is_quota_modification(inode, attr)) {
5210a7cdadeeSJan Kara 		error = dquot_initialize(inode);
5211a7cdadeeSJan Kara 		if (error)
5212a7cdadeeSJan Kara 			return error;
5213a7cdadeeSJan Kara 	}
521408cefc7aSEric W. Biederman 	if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
521508cefc7aSEric W. Biederman 	    (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5216ac27a0ecSDave Kleikamp 		handle_t *handle;
5217ac27a0ecSDave Kleikamp 
5218ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
5219ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
52209924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
52219924a92aSTheodore Ts'o 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5222194074acSDmitry Monakhov 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5223ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
5224ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
5225ac27a0ecSDave Kleikamp 			goto err_out;
5226ac27a0ecSDave Kleikamp 		}
5227b43fa828SChristoph Hellwig 		error = dquot_transfer(inode, attr);
5228ac27a0ecSDave Kleikamp 		if (error) {
5229617ba13bSMingming Cao 			ext4_journal_stop(handle);
5230ac27a0ecSDave Kleikamp 			return error;
5231ac27a0ecSDave Kleikamp 		}
5232ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
5233ac27a0ecSDave Kleikamp 		 * one transaction */
5234ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_UID)
5235ac27a0ecSDave Kleikamp 			inode->i_uid = attr->ia_uid;
5236ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_GID)
5237ac27a0ecSDave Kleikamp 			inode->i_gid = attr->ia_gid;
5238617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
5239617ba13bSMingming Cao 		ext4_journal_stop(handle);
5240ac27a0ecSDave Kleikamp 	}
5241ac27a0ecSDave Kleikamp 
52423da40c7bSJosef Bacik 	if (attr->ia_valid & ATTR_SIZE) {
52435208386cSJan Kara 		handle_t *handle;
52443da40c7bSJosef Bacik 		loff_t oldsize = inode->i_size;
52453da40c7bSJosef Bacik 		int shrink = (attr->ia_size <= inode->i_size);
5246562c72aaSChristoph Hellwig 
524712e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5248e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5249e2b46574SEric Sandeen 
52500c095c7fSTheodore Ts'o 			if (attr->ia_size > sbi->s_bitmap_maxbytes)
52510c095c7fSTheodore Ts'o 				return -EFBIG;
5252e2b46574SEric Sandeen 		}
52533da40c7bSJosef Bacik 		if (!S_ISREG(inode->i_mode))
52543da40c7bSJosef Bacik 			return -EINVAL;
5255dff6efc3SChristoph Hellwig 
5256dff6efc3SChristoph Hellwig 		if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5257dff6efc3SChristoph Hellwig 			inode_inc_iversion(inode);
5258dff6efc3SChristoph Hellwig 
52593da40c7bSJosef Bacik 		if (ext4_should_order_data(inode) &&
5260072bd7eaSTheodore Ts'o 		    (attr->ia_size < inode->i_size)) {
52615208386cSJan Kara 			error = ext4_begin_ordered_truncate(inode,
52625208386cSJan Kara 							    attr->ia_size);
52635208386cSJan Kara 			if (error)
52645208386cSJan Kara 				goto err_out;
52655208386cSJan Kara 		}
52663da40c7bSJosef Bacik 		if (attr->ia_size != inode->i_size) {
52679924a92aSTheodore Ts'o 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5268ac27a0ecSDave Kleikamp 			if (IS_ERR(handle)) {
5269ac27a0ecSDave Kleikamp 				error = PTR_ERR(handle);
5270ac27a0ecSDave Kleikamp 				goto err_out;
5271ac27a0ecSDave Kleikamp 			}
52723da40c7bSJosef Bacik 			if (ext4_handle_valid(handle) && shrink) {
5273617ba13bSMingming Cao 				error = ext4_orphan_add(handle, inode);
52743d287de3SDmitry Monakhov 				orphan = 1;
52753d287de3SDmitry Monakhov 			}
5276911af577SEryu Guan 			/*
5277911af577SEryu Guan 			 * Update c/mtime on truncate up, ext4_truncate() will
5278911af577SEryu Guan 			 * update c/mtime in shrink case below
5279911af577SEryu Guan 			 */
5280911af577SEryu Guan 			if (!shrink) {
5281eeca7ea1SDeepa Dinamani 				inode->i_mtime = current_time(inode);
5282911af577SEryu Guan 				inode->i_ctime = inode->i_mtime;
5283911af577SEryu Guan 			}
528490e775b7SJan Kara 			down_write(&EXT4_I(inode)->i_data_sem);
5285617ba13bSMingming Cao 			EXT4_I(inode)->i_disksize = attr->ia_size;
5286617ba13bSMingming Cao 			rc = ext4_mark_inode_dirty(handle, inode);
5287ac27a0ecSDave Kleikamp 			if (!error)
5288ac27a0ecSDave Kleikamp 				error = rc;
528990e775b7SJan Kara 			/*
529090e775b7SJan Kara 			 * We have to update i_size under i_data_sem together
529190e775b7SJan Kara 			 * with i_disksize to avoid races with writeback code
529290e775b7SJan Kara 			 * running ext4_wb_update_i_disksize().
529390e775b7SJan Kara 			 */
529490e775b7SJan Kara 			if (!error)
529590e775b7SJan Kara 				i_size_write(inode, attr->ia_size);
529690e775b7SJan Kara 			up_write(&EXT4_I(inode)->i_data_sem);
5297617ba13bSMingming Cao 			ext4_journal_stop(handle);
5298678aaf48SJan Kara 			if (error) {
52993da40c7bSJosef Bacik 				if (orphan)
5300678aaf48SJan Kara 					ext4_orphan_del(NULL, inode);
5301678aaf48SJan Kara 				goto err_out;
5302678aaf48SJan Kara 			}
5303d6320cbfSJan Kara 		}
53043da40c7bSJosef Bacik 		if (!shrink)
53053da40c7bSJosef Bacik 			pagecache_isize_extended(inode, oldsize, inode->i_size);
530690e775b7SJan Kara 
530753e87268SJan Kara 		/*
530853e87268SJan Kara 		 * Blocks are going to be removed from the inode. Wait
530953e87268SJan Kara 		 * for dio in flight.  Temporarily disable
531053e87268SJan Kara 		 * dioread_nolock to prevent livelock.
531153e87268SJan Kara 		 */
53121b65007eSDmitry Monakhov 		if (orphan) {
531353e87268SJan Kara 			if (!ext4_should_journal_data(inode)) {
53141b65007eSDmitry Monakhov 				ext4_inode_block_unlocked_dio(inode);
53151c9114f9SDmitry Monakhov 				inode_dio_wait(inode);
53161b65007eSDmitry Monakhov 				ext4_inode_resume_unlocked_dio(inode);
531753e87268SJan Kara 			} else
531853e87268SJan Kara 				ext4_wait_for_tail_page_commit(inode);
53191b65007eSDmitry Monakhov 		}
5320ea3d7209SJan Kara 		down_write(&EXT4_I(inode)->i_mmap_sem);
532153e87268SJan Kara 		/*
532253e87268SJan Kara 		 * Truncate pagecache after we've waited for commit
532353e87268SJan Kara 		 * in data=journal mode to make pages freeable.
532453e87268SJan Kara 		 */
53257caef267SKirill A. Shutemov 		truncate_pagecache(inode, inode->i_size);
53262c98eb5eSTheodore Ts'o 		if (shrink) {
53272c98eb5eSTheodore Ts'o 			rc = ext4_truncate(inode);
53282c98eb5eSTheodore Ts'o 			if (rc)
53292c98eb5eSTheodore Ts'o 				error = rc;
53302c98eb5eSTheodore Ts'o 		}
5331ea3d7209SJan Kara 		up_write(&EXT4_I(inode)->i_mmap_sem);
53323da40c7bSJosef Bacik 	}
5333ac27a0ecSDave Kleikamp 
53342c98eb5eSTheodore Ts'o 	if (!error) {
53351025774cSChristoph Hellwig 		setattr_copy(inode, attr);
53361025774cSChristoph Hellwig 		mark_inode_dirty(inode);
53371025774cSChristoph Hellwig 	}
53381025774cSChristoph Hellwig 
53391025774cSChristoph Hellwig 	/*
53401025774cSChristoph Hellwig 	 * If the call to ext4_truncate failed to get a transaction handle at
53411025774cSChristoph Hellwig 	 * all, we need to clean up the in-core orphan list manually.
53421025774cSChristoph Hellwig 	 */
53433d287de3SDmitry Monakhov 	if (orphan && inode->i_nlink)
5344617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
5345ac27a0ecSDave Kleikamp 
53462c98eb5eSTheodore Ts'o 	if (!error && (ia_valid & ATTR_MODE))
534764e178a7SChristoph Hellwig 		rc = posix_acl_chmod(inode, inode->i_mode);
5348ac27a0ecSDave Kleikamp 
5349ac27a0ecSDave Kleikamp err_out:
5350617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, error);
5351ac27a0ecSDave Kleikamp 	if (!error)
5352ac27a0ecSDave Kleikamp 		error = rc;
5353ac27a0ecSDave Kleikamp 	return error;
5354ac27a0ecSDave Kleikamp }
5355ac27a0ecSDave Kleikamp 
53563e3398a0SMingming Cao int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
53573e3398a0SMingming Cao 		 struct kstat *stat)
53583e3398a0SMingming Cao {
53593e3398a0SMingming Cao 	struct inode *inode;
53608af8eeccSJan Kara 	unsigned long long delalloc_blocks;
53613e3398a0SMingming Cao 
53622b0143b5SDavid Howells 	inode = d_inode(dentry);
53633e3398a0SMingming Cao 	generic_fillattr(inode, stat);
53643e3398a0SMingming Cao 
53653e3398a0SMingming Cao 	/*
53669206c561SAndreas Dilger 	 * If there is inline data in the inode, the inode will normally not
53679206c561SAndreas Dilger 	 * have data blocks allocated (it may have an external xattr block).
53689206c561SAndreas Dilger 	 * Report at least one sector for such files, so tools like tar, rsync,
53699206c561SAndreas Dilger 	 * others doen't incorrectly think the file is completely sparse.
53709206c561SAndreas Dilger 	 */
53719206c561SAndreas Dilger 	if (unlikely(ext4_has_inline_data(inode)))
53729206c561SAndreas Dilger 		stat->blocks += (stat->size + 511) >> 9;
53739206c561SAndreas Dilger 
53749206c561SAndreas Dilger 	/*
53753e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
53763e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
53773e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
53783e3398a0SMingming Cao 	 * on-disk file blocks.
53793e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
53803e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
53813e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
53823e3398a0SMingming Cao 	 * blocks for this file.
53833e3398a0SMingming Cao 	 */
538496607551STao Ma 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
538596607551STao Ma 				   EXT4_I(inode)->i_reserved_data_blocks);
53868af8eeccSJan Kara 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
53873e3398a0SMingming Cao 	return 0;
53883e3398a0SMingming Cao }
5389ac27a0ecSDave Kleikamp 
5390fffb2739SJan Kara static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5391fffb2739SJan Kara 				   int pextents)
5392a02908f1SMingming Cao {
539312e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5394fffb2739SJan Kara 		return ext4_ind_trans_blocks(inode, lblocks);
5395fffb2739SJan Kara 	return ext4_ext_index_trans_blocks(inode, pextents);
5396a02908f1SMingming Cao }
5397ac51d837STheodore Ts'o 
5398a02908f1SMingming Cao /*
5399a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
5400a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
5401a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
5402a02908f1SMingming Cao  *
5403a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
54044907cb7bSAnatol Pomozov  * different block groups too. If they are contiguous, with flexbg,
5405a02908f1SMingming Cao  * they could still across block group boundary.
5406a02908f1SMingming Cao  *
5407a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
5408a02908f1SMingming Cao  */
5409fffb2739SJan Kara static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5410fffb2739SJan Kara 				  int pextents)
5411a02908f1SMingming Cao {
54128df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
54138df9675fSTheodore Ts'o 	int gdpblocks;
5414a02908f1SMingming Cao 	int idxblocks;
5415a02908f1SMingming Cao 	int ret = 0;
5416a02908f1SMingming Cao 
5417a02908f1SMingming Cao 	/*
5418fffb2739SJan Kara 	 * How many index blocks need to touch to map @lblocks logical blocks
5419fffb2739SJan Kara 	 * to @pextents physical extents?
5420a02908f1SMingming Cao 	 */
5421fffb2739SJan Kara 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5422a02908f1SMingming Cao 
5423a02908f1SMingming Cao 	ret = idxblocks;
5424a02908f1SMingming Cao 
5425a02908f1SMingming Cao 	/*
5426a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
5427a02908f1SMingming Cao 	 * to account
5428a02908f1SMingming Cao 	 */
5429fffb2739SJan Kara 	groups = idxblocks + pextents;
5430a02908f1SMingming Cao 	gdpblocks = groups;
54318df9675fSTheodore Ts'o 	if (groups > ngroups)
54328df9675fSTheodore Ts'o 		groups = ngroups;
5433a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5434a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5435a02908f1SMingming Cao 
5436a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
5437a02908f1SMingming Cao 	ret += groups + gdpblocks;
5438a02908f1SMingming Cao 
5439a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
5440a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5441ac27a0ecSDave Kleikamp 
5442ac27a0ecSDave Kleikamp 	return ret;
5443ac27a0ecSDave Kleikamp }
5444ac27a0ecSDave Kleikamp 
5445ac27a0ecSDave Kleikamp /*
544625985edcSLucas De Marchi  * Calculate the total number of credits to reserve to fit
5447f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
5448f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
5449a02908f1SMingming Cao  *
5450525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
5451a02908f1SMingming Cao  *
5452525f4ed8SMingming Cao  * We need to consider the worse case, when
5453a02908f1SMingming Cao  * one new block per extent.
5454a02908f1SMingming Cao  */
5455a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
5456a02908f1SMingming Cao {
5457a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
5458a02908f1SMingming Cao 	int ret;
5459a02908f1SMingming Cao 
5460fffb2739SJan Kara 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5461a02908f1SMingming Cao 
5462a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
5463a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
5464a02908f1SMingming Cao 		ret += bpp;
5465a02908f1SMingming Cao 	return ret;
5466a02908f1SMingming Cao }
5467f3bd1f3fSMingming Cao 
5468f3bd1f3fSMingming Cao /*
5469f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
5470f3bd1f3fSMingming Cao  *
5471f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
547279e83036SEric Sandeen  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5473f3bd1f3fSMingming Cao  *
5474f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
5475f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
5476f3bd1f3fSMingming Cao  */
5477f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5478f3bd1f3fSMingming Cao {
5479f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5480f3bd1f3fSMingming Cao }
5481f3bd1f3fSMingming Cao 
5482a02908f1SMingming Cao /*
5483617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
5484ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
5485ac27a0ecSDave Kleikamp  */
5486617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
5487617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
5488ac27a0ecSDave Kleikamp {
5489ac27a0ecSDave Kleikamp 	int err = 0;
5490ac27a0ecSDave Kleikamp 
5491c64db50eSTheodore Ts'o 	if (IS_I_VERSION(inode))
549225ec56b5SJean Noel Cordenner 		inode_inc_iversion(inode);
549325ec56b5SJean Noel Cordenner 
5494ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
5495ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
5496ac27a0ecSDave Kleikamp 
5497dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5498830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
5499ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
5500ac27a0ecSDave Kleikamp 	return err;
5501ac27a0ecSDave Kleikamp }
5502ac27a0ecSDave Kleikamp 
5503ac27a0ecSDave Kleikamp /*
5504ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
5505ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
5506ac27a0ecSDave Kleikamp  */
5507ac27a0ecSDave Kleikamp 
5508ac27a0ecSDave Kleikamp int
5509617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5510617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
5511ac27a0ecSDave Kleikamp {
55120390131bSFrank Mayhar 	int err;
55130390131bSFrank Mayhar 
5514617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
5515ac27a0ecSDave Kleikamp 	if (!err) {
5516ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
5517617ba13bSMingming Cao 		err = ext4_journal_get_write_access(handle, iloc->bh);
5518ac27a0ecSDave Kleikamp 		if (err) {
5519ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
5520ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
5521ac27a0ecSDave Kleikamp 		}
5522ac27a0ecSDave Kleikamp 	}
5523617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5524ac27a0ecSDave Kleikamp 	return err;
5525ac27a0ecSDave Kleikamp }
5526ac27a0ecSDave Kleikamp 
5527ac27a0ecSDave Kleikamp /*
55286dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
55296dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
55306dd4ee7cSKalpak Shah  */
55311d03ec98SAneesh Kumar K.V static int ext4_expand_extra_isize(struct inode *inode,
55321d03ec98SAneesh Kumar K.V 				   unsigned int new_extra_isize,
55331d03ec98SAneesh Kumar K.V 				   struct ext4_iloc iloc,
55341d03ec98SAneesh Kumar K.V 				   handle_t *handle)
55356dd4ee7cSKalpak Shah {
55366dd4ee7cSKalpak Shah 	struct ext4_inode *raw_inode;
55376dd4ee7cSKalpak Shah 	struct ext4_xattr_ibody_header *header;
55386dd4ee7cSKalpak Shah 
55396dd4ee7cSKalpak Shah 	if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
55406dd4ee7cSKalpak Shah 		return 0;
55416dd4ee7cSKalpak Shah 
55426dd4ee7cSKalpak Shah 	raw_inode = ext4_raw_inode(&iloc);
55436dd4ee7cSKalpak Shah 
55446dd4ee7cSKalpak Shah 	header = IHDR(inode, raw_inode);
55456dd4ee7cSKalpak Shah 
55466dd4ee7cSKalpak Shah 	/* No extended attributes present */
554719f5fb7aSTheodore Ts'o 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
55486dd4ee7cSKalpak Shah 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
55496dd4ee7cSKalpak Shah 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
55506dd4ee7cSKalpak Shah 			new_extra_isize);
55516dd4ee7cSKalpak Shah 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
55526dd4ee7cSKalpak Shah 		return 0;
55536dd4ee7cSKalpak Shah 	}
55546dd4ee7cSKalpak Shah 
55556dd4ee7cSKalpak Shah 	/* try to expand with EAs present */
55566dd4ee7cSKalpak Shah 	return ext4_expand_extra_isize_ea(inode, new_extra_isize,
55576dd4ee7cSKalpak Shah 					  raw_inode, handle);
55586dd4ee7cSKalpak Shah }
55596dd4ee7cSKalpak Shah 
55606dd4ee7cSKalpak Shah /*
5561ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
5562ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
5563ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
5564ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
5565ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
5566ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
5567ac27a0ecSDave Kleikamp  *
5568ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
5569ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
5570ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5571ac27a0ecSDave Kleikamp  * we start and wait on commits.
5572ac27a0ecSDave Kleikamp  */
5573617ba13bSMingming Cao int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5574ac27a0ecSDave Kleikamp {
5575617ba13bSMingming Cao 	struct ext4_iloc iloc;
55766dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
55776dd4ee7cSKalpak Shah 	static unsigned int mnt_count;
55786dd4ee7cSKalpak Shah 	int err, ret;
5579ac27a0ecSDave Kleikamp 
5580ac27a0ecSDave Kleikamp 	might_sleep();
55817ff9c073STheodore Ts'o 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5582617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
55835e1021f2SEryu Guan 	if (err)
55845e1021f2SEryu Guan 		return err;
558588e03877SEric Whitney 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
558619f5fb7aSTheodore Ts'o 	    !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
55876dd4ee7cSKalpak Shah 		/*
558888e03877SEric Whitney 		 * In nojournal mode, we can immediately attempt to expand
558988e03877SEric Whitney 		 * the inode.  When journaled, we first need to obtain extra
559088e03877SEric Whitney 		 * buffer credits since we may write into the EA block
55916dd4ee7cSKalpak Shah 		 * with this same handle. If journal_extend fails, then it will
55926dd4ee7cSKalpak Shah 		 * only result in a minor loss of functionality for that inode.
55936dd4ee7cSKalpak Shah 		 * If this is felt to be critical, then e2fsck should be run to
55946dd4ee7cSKalpak Shah 		 * force a large enough s_min_extra_isize.
55956dd4ee7cSKalpak Shah 		 */
559688e03877SEric Whitney 		if (!ext4_handle_valid(handle) ||
559788e03877SEric Whitney 		    jbd2_journal_extend(handle,
559888e03877SEric Whitney 			     EXT4_DATA_TRANS_BLOCKS(inode->i_sb)) == 0) {
55996dd4ee7cSKalpak Shah 			ret = ext4_expand_extra_isize(inode,
56006dd4ee7cSKalpak Shah 						      sbi->s_want_extra_isize,
56016dd4ee7cSKalpak Shah 						      iloc, handle);
56026dd4ee7cSKalpak Shah 			if (ret) {
5603c1bddad9SAneesh Kumar K.V 				if (mnt_count !=
5604c1bddad9SAneesh Kumar K.V 					le16_to_cpu(sbi->s_es->s_mnt_count)) {
560512062dddSEric Sandeen 					ext4_warning(inode->i_sb,
56066dd4ee7cSKalpak Shah 					"Unable to expand inode %lu. Delete"
56076dd4ee7cSKalpak Shah 					" some EAs or run e2fsck.",
56086dd4ee7cSKalpak Shah 					inode->i_ino);
5609c1bddad9SAneesh Kumar K.V 					mnt_count =
5610c1bddad9SAneesh Kumar K.V 					  le16_to_cpu(sbi->s_es->s_mnt_count);
56116dd4ee7cSKalpak Shah 				}
56126dd4ee7cSKalpak Shah 			}
56136dd4ee7cSKalpak Shah 		}
56146dd4ee7cSKalpak Shah 	}
56155e1021f2SEryu Guan 	return ext4_mark_iloc_dirty(handle, inode, &iloc);
5616ac27a0ecSDave Kleikamp }
5617ac27a0ecSDave Kleikamp 
5618ac27a0ecSDave Kleikamp /*
5619617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
5620ac27a0ecSDave Kleikamp  *
5621ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
5622ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
5623ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
5624ac27a0ecSDave Kleikamp  *
56255dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
5626ac27a0ecSDave Kleikamp  * are allocated to the file.
5627ac27a0ecSDave Kleikamp  *
5628ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
5629ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
5630ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
56310ae45f63STheodore Ts'o  *
56320ae45f63STheodore Ts'o  * If only the I_DIRTY_TIME flag is set, we can skip everything.  If
56330ae45f63STheodore Ts'o  * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
56340ae45f63STheodore Ts'o  * to copy into the on-disk inode structure are the timestamp files.
5635ac27a0ecSDave Kleikamp  */
5636aa385729SChristoph Hellwig void ext4_dirty_inode(struct inode *inode, int flags)
5637ac27a0ecSDave Kleikamp {
5638ac27a0ecSDave Kleikamp 	handle_t *handle;
5639ac27a0ecSDave Kleikamp 
56400ae45f63STheodore Ts'o 	if (flags == I_DIRTY_TIME)
56410ae45f63STheodore Ts'o 		return;
56429924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5643ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5644ac27a0ecSDave Kleikamp 		goto out;
5645f3dc272fSCurt Wohlgemuth 
5646617ba13bSMingming Cao 	ext4_mark_inode_dirty(handle, inode);
5647f3dc272fSCurt Wohlgemuth 
5648617ba13bSMingming Cao 	ext4_journal_stop(handle);
5649ac27a0ecSDave Kleikamp out:
5650ac27a0ecSDave Kleikamp 	return;
5651ac27a0ecSDave Kleikamp }
5652ac27a0ecSDave Kleikamp 
5653ac27a0ecSDave Kleikamp #if 0
5654ac27a0ecSDave Kleikamp /*
5655ac27a0ecSDave Kleikamp  * Bind an inode's backing buffer_head into this transaction, to prevent
5656ac27a0ecSDave Kleikamp  * it from being flushed to disk early.  Unlike
5657617ba13bSMingming Cao  * ext4_reserve_inode_write, this leaves behind no bh reference and
5658ac27a0ecSDave Kleikamp  * returns no iloc structure, so the caller needs to repeat the iloc
5659ac27a0ecSDave Kleikamp  * lookup to mark the inode dirty later.
5660ac27a0ecSDave Kleikamp  */
5661617ba13bSMingming Cao static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5662ac27a0ecSDave Kleikamp {
5663617ba13bSMingming Cao 	struct ext4_iloc iloc;
5664ac27a0ecSDave Kleikamp 
5665ac27a0ecSDave Kleikamp 	int err = 0;
5666ac27a0ecSDave Kleikamp 	if (handle) {
5667617ba13bSMingming Cao 		err = ext4_get_inode_loc(inode, &iloc);
5668ac27a0ecSDave Kleikamp 		if (!err) {
5669ac27a0ecSDave Kleikamp 			BUFFER_TRACE(iloc.bh, "get_write_access");
5670dab291afSMingming Cao 			err = jbd2_journal_get_write_access(handle, iloc.bh);
5671ac27a0ecSDave Kleikamp 			if (!err)
56720390131bSFrank Mayhar 				err = ext4_handle_dirty_metadata(handle,
567373b50c1cSCurt Wohlgemuth 								 NULL,
5674ac27a0ecSDave Kleikamp 								 iloc.bh);
5675ac27a0ecSDave Kleikamp 			brelse(iloc.bh);
5676ac27a0ecSDave Kleikamp 		}
5677ac27a0ecSDave Kleikamp 	}
5678617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5679ac27a0ecSDave Kleikamp 	return err;
5680ac27a0ecSDave Kleikamp }
5681ac27a0ecSDave Kleikamp #endif
5682ac27a0ecSDave Kleikamp 
5683617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
5684ac27a0ecSDave Kleikamp {
5685ac27a0ecSDave Kleikamp 	journal_t *journal;
5686ac27a0ecSDave Kleikamp 	handle_t *handle;
5687ac27a0ecSDave Kleikamp 	int err;
5688c8585c6fSDaeho Jeong 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5689ac27a0ecSDave Kleikamp 
5690ac27a0ecSDave Kleikamp 	/*
5691ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
5692ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
5693ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
5694ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
5695ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
5696ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
5697ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
5698ac27a0ecSDave Kleikamp 	 */
5699ac27a0ecSDave Kleikamp 
5700617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
57010390131bSFrank Mayhar 	if (!journal)
57020390131bSFrank Mayhar 		return 0;
5703d699594dSDave Hansen 	if (is_journal_aborted(journal))
5704ac27a0ecSDave Kleikamp 		return -EROFS;
5705ac27a0ecSDave Kleikamp 
570617335dccSDmitry Monakhov 	/* Wait for all existing dio workers */
570717335dccSDmitry Monakhov 	ext4_inode_block_unlocked_dio(inode);
570817335dccSDmitry Monakhov 	inode_dio_wait(inode);
570917335dccSDmitry Monakhov 
57104c546592SDaeho Jeong 	/*
57114c546592SDaeho Jeong 	 * Before flushing the journal and switching inode's aops, we have
57124c546592SDaeho Jeong 	 * to flush all dirty data the inode has. There can be outstanding
57134c546592SDaeho Jeong 	 * delayed allocations, there can be unwritten extents created by
57144c546592SDaeho Jeong 	 * fallocate or buffered writes in dioread_nolock mode covered by
57154c546592SDaeho Jeong 	 * dirty data which can be converted only after flushing the dirty
57164c546592SDaeho Jeong 	 * data (and journalled aops don't know how to handle these cases).
57174c546592SDaeho Jeong 	 */
57184c546592SDaeho Jeong 	if (val) {
57194c546592SDaeho Jeong 		down_write(&EXT4_I(inode)->i_mmap_sem);
57204c546592SDaeho Jeong 		err = filemap_write_and_wait(inode->i_mapping);
57214c546592SDaeho Jeong 		if (err < 0) {
57224c546592SDaeho Jeong 			up_write(&EXT4_I(inode)->i_mmap_sem);
57234c546592SDaeho Jeong 			ext4_inode_resume_unlocked_dio(inode);
57244c546592SDaeho Jeong 			return err;
57254c546592SDaeho Jeong 		}
57264c546592SDaeho Jeong 	}
57274c546592SDaeho Jeong 
5728c8585c6fSDaeho Jeong 	percpu_down_write(&sbi->s_journal_flag_rwsem);
5729dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
5730ac27a0ecSDave Kleikamp 
5731ac27a0ecSDave Kleikamp 	/*
5732ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
5733ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
5734ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
5735ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
5736ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
5737ac27a0ecSDave Kleikamp 	 */
5738ac27a0ecSDave Kleikamp 
5739ac27a0ecSDave Kleikamp 	if (val)
574012e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
57415872ddaaSYongqiang Yang 	else {
57424f879ca6SJan Kara 		err = jbd2_journal_flush(journal);
57434f879ca6SJan Kara 		if (err < 0) {
57444f879ca6SJan Kara 			jbd2_journal_unlock_updates(journal);
5745c8585c6fSDaeho Jeong 			percpu_up_write(&sbi->s_journal_flag_rwsem);
57464f879ca6SJan Kara 			ext4_inode_resume_unlocked_dio(inode);
57474f879ca6SJan Kara 			return err;
57484f879ca6SJan Kara 		}
574912e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
57505872ddaaSYongqiang Yang 	}
5751617ba13bSMingming Cao 	ext4_set_aops(inode);
5752a3caa24bSJan Kara 	/*
5753a3caa24bSJan Kara 	 * Update inode->i_flags after EXT4_INODE_JOURNAL_DATA was updated.
5754a3caa24bSJan Kara 	 * E.g. S_DAX may get cleared / set.
5755a3caa24bSJan Kara 	 */
5756a3caa24bSJan Kara 	ext4_set_inode_flags(inode);
5757ac27a0ecSDave Kleikamp 
5758dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
5759c8585c6fSDaeho Jeong 	percpu_up_write(&sbi->s_journal_flag_rwsem);
5760c8585c6fSDaeho Jeong 
57614c546592SDaeho Jeong 	if (val)
57624c546592SDaeho Jeong 		up_write(&EXT4_I(inode)->i_mmap_sem);
576317335dccSDmitry Monakhov 	ext4_inode_resume_unlocked_dio(inode);
5764ac27a0ecSDave Kleikamp 
5765ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
5766ac27a0ecSDave Kleikamp 
57679924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5768ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5769ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
5770ac27a0ecSDave Kleikamp 
5771617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
57720390131bSFrank Mayhar 	ext4_handle_sync(handle);
5773617ba13bSMingming Cao 	ext4_journal_stop(handle);
5774617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5775ac27a0ecSDave Kleikamp 
5776ac27a0ecSDave Kleikamp 	return err;
5777ac27a0ecSDave Kleikamp }
57782e9ee850SAneesh Kumar K.V 
57792e9ee850SAneesh Kumar K.V static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
57802e9ee850SAneesh Kumar K.V {
57812e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
57822e9ee850SAneesh Kumar K.V }
57832e9ee850SAneesh Kumar K.V 
5784c2ec175cSNick Piggin int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
57852e9ee850SAneesh Kumar K.V {
5786c2ec175cSNick Piggin 	struct page *page = vmf->page;
57872e9ee850SAneesh Kumar K.V 	loff_t size;
57882e9ee850SAneesh Kumar K.V 	unsigned long len;
57899ea7df53SJan Kara 	int ret;
57902e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
5791496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
57922e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
57939ea7df53SJan Kara 	handle_t *handle;
57949ea7df53SJan Kara 	get_block_t *get_block;
57959ea7df53SJan Kara 	int retries = 0;
57962e9ee850SAneesh Kumar K.V 
57978e8ad8a5SJan Kara 	sb_start_pagefault(inode->i_sb);
5798041bbb6dSTheodore Ts'o 	file_update_time(vma->vm_file);
5799ea3d7209SJan Kara 
5800ea3d7209SJan Kara 	down_read(&EXT4_I(inode)->i_mmap_sem);
58019ea7df53SJan Kara 	/* Delalloc case is easy... */
58029ea7df53SJan Kara 	if (test_opt(inode->i_sb, DELALLOC) &&
58039ea7df53SJan Kara 	    !ext4_should_journal_data(inode) &&
58049ea7df53SJan Kara 	    !ext4_nonda_switch(inode->i_sb)) {
58059ea7df53SJan Kara 		do {
58065c500029SRoss Zwisler 			ret = block_page_mkwrite(vma, vmf,
58079ea7df53SJan Kara 						   ext4_da_get_block_prep);
58089ea7df53SJan Kara 		} while (ret == -ENOSPC &&
58099ea7df53SJan Kara 		       ext4_should_retry_alloc(inode->i_sb, &retries));
58109ea7df53SJan Kara 		goto out_ret;
58112e9ee850SAneesh Kumar K.V 	}
58120e499890SDarrick J. Wong 
58130e499890SDarrick J. Wong 	lock_page(page);
58149ea7df53SJan Kara 	size = i_size_read(inode);
58159ea7df53SJan Kara 	/* Page got truncated from under us? */
58169ea7df53SJan Kara 	if (page->mapping != mapping || page_offset(page) > size) {
58179ea7df53SJan Kara 		unlock_page(page);
58189ea7df53SJan Kara 		ret = VM_FAULT_NOPAGE;
58199ea7df53SJan Kara 		goto out;
58200e499890SDarrick J. Wong 	}
58212e9ee850SAneesh Kumar K.V 
582209cbfeafSKirill A. Shutemov 	if (page->index == size >> PAGE_SHIFT)
582309cbfeafSKirill A. Shutemov 		len = size & ~PAGE_MASK;
58242e9ee850SAneesh Kumar K.V 	else
582509cbfeafSKirill A. Shutemov 		len = PAGE_SIZE;
5826a827eaffSAneesh Kumar K.V 	/*
58279ea7df53SJan Kara 	 * Return if we have all the buffers mapped. This avoids the need to do
58289ea7df53SJan Kara 	 * journal_start/journal_stop which can block and take a long time
5829a827eaffSAneesh Kumar K.V 	 */
58302e9ee850SAneesh Kumar K.V 	if (page_has_buffers(page)) {
5831f19d5870STao Ma 		if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5832f19d5870STao Ma 					    0, len, NULL,
5833a827eaffSAneesh Kumar K.V 					    ext4_bh_unmapped)) {
58349ea7df53SJan Kara 			/* Wait so that we don't change page under IO */
58351d1d1a76SDarrick J. Wong 			wait_for_stable_page(page);
58369ea7df53SJan Kara 			ret = VM_FAULT_LOCKED;
58379ea7df53SJan Kara 			goto out;
58382e9ee850SAneesh Kumar K.V 		}
5839a827eaffSAneesh Kumar K.V 	}
5840a827eaffSAneesh Kumar K.V 	unlock_page(page);
58419ea7df53SJan Kara 	/* OK, we need to fill the hole... */
58429ea7df53SJan Kara 	if (ext4_should_dioread_nolock(inode))
5843705965bdSJan Kara 		get_block = ext4_get_block_unwritten;
58449ea7df53SJan Kara 	else
58459ea7df53SJan Kara 		get_block = ext4_get_block;
58469ea7df53SJan Kara retry_alloc:
58479924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
58489924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
58499ea7df53SJan Kara 	if (IS_ERR(handle)) {
5850c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
58519ea7df53SJan Kara 		goto out;
58529ea7df53SJan Kara 	}
58535c500029SRoss Zwisler 	ret = block_page_mkwrite(vma, vmf, get_block);
58549ea7df53SJan Kara 	if (!ret && ext4_should_journal_data(inode)) {
5855f19d5870STao Ma 		if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
585609cbfeafSKirill A. Shutemov 			  PAGE_SIZE, NULL, do_journal_get_write_access)) {
58579ea7df53SJan Kara 			unlock_page(page);
58589ea7df53SJan Kara 			ret = VM_FAULT_SIGBUS;
5859fcbb5515SYongqiang Yang 			ext4_journal_stop(handle);
58609ea7df53SJan Kara 			goto out;
58619ea7df53SJan Kara 		}
58629ea7df53SJan Kara 		ext4_set_inode_state(inode, EXT4_STATE_JDATA);
58639ea7df53SJan Kara 	}
58649ea7df53SJan Kara 	ext4_journal_stop(handle);
58659ea7df53SJan Kara 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
58669ea7df53SJan Kara 		goto retry_alloc;
58679ea7df53SJan Kara out_ret:
58689ea7df53SJan Kara 	ret = block_page_mkwrite_return(ret);
58699ea7df53SJan Kara out:
5870ea3d7209SJan Kara 	up_read(&EXT4_I(inode)->i_mmap_sem);
58718e8ad8a5SJan Kara 	sb_end_pagefault(inode->i_sb);
58722e9ee850SAneesh Kumar K.V 	return ret;
58732e9ee850SAneesh Kumar K.V }
5874ea3d7209SJan Kara 
5875ea3d7209SJan Kara int ext4_filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
5876ea3d7209SJan Kara {
5877ea3d7209SJan Kara 	struct inode *inode = file_inode(vma->vm_file);
5878ea3d7209SJan Kara 	int err;
5879ea3d7209SJan Kara 
5880ea3d7209SJan Kara 	down_read(&EXT4_I(inode)->i_mmap_sem);
5881ea3d7209SJan Kara 	err = filemap_fault(vma, vmf);
5882ea3d7209SJan Kara 	up_read(&EXT4_I(inode)->i_mmap_sem);
5883ea3d7209SJan Kara 
5884ea3d7209SJan Kara 	return err;
5885ea3d7209SJan Kara }
58862d90c160SJan Kara 
58872d90c160SJan Kara /*
58882d90c160SJan Kara  * Find the first extent at or after @lblk in an inode that is not a hole.
58892d90c160SJan Kara  * Search for @map_len blocks at most. The extent is returned in @result.
58902d90c160SJan Kara  *
58912d90c160SJan Kara  * The function returns 1 if we found an extent. The function returns 0 in
58922d90c160SJan Kara  * case there is no extent at or after @lblk and in that case also sets
58932d90c160SJan Kara  * @result->es_len to 0. In case of error, the error code is returned.
58942d90c160SJan Kara  */
58952d90c160SJan Kara int ext4_get_next_extent(struct inode *inode, ext4_lblk_t lblk,
58962d90c160SJan Kara 			 unsigned int map_len, struct extent_status *result)
58972d90c160SJan Kara {
58982d90c160SJan Kara 	struct ext4_map_blocks map;
58992d90c160SJan Kara 	struct extent_status es = {};
59002d90c160SJan Kara 	int ret;
59012d90c160SJan Kara 
59022d90c160SJan Kara 	map.m_lblk = lblk;
59032d90c160SJan Kara 	map.m_len = map_len;
59042d90c160SJan Kara 
59052d90c160SJan Kara 	/*
59062d90c160SJan Kara 	 * For non-extent based files this loop may iterate several times since
59072d90c160SJan Kara 	 * we do not determine full hole size.
59082d90c160SJan Kara 	 */
59092d90c160SJan Kara 	while (map.m_len > 0) {
59102d90c160SJan Kara 		ret = ext4_map_blocks(NULL, inode, &map, 0);
59112d90c160SJan Kara 		if (ret < 0)
59122d90c160SJan Kara 			return ret;
59132d90c160SJan Kara 		/* There's extent covering m_lblk? Just return it. */
59142d90c160SJan Kara 		if (ret > 0) {
59152d90c160SJan Kara 			int status;
59162d90c160SJan Kara 
59172d90c160SJan Kara 			ext4_es_store_pblock(result, map.m_pblk);
59182d90c160SJan Kara 			result->es_lblk = map.m_lblk;
59192d90c160SJan Kara 			result->es_len = map.m_len;
59202d90c160SJan Kara 			if (map.m_flags & EXT4_MAP_UNWRITTEN)
59212d90c160SJan Kara 				status = EXTENT_STATUS_UNWRITTEN;
59222d90c160SJan Kara 			else
59232d90c160SJan Kara 				status = EXTENT_STATUS_WRITTEN;
59242d90c160SJan Kara 			ext4_es_store_status(result, status);
59252d90c160SJan Kara 			return 1;
59262d90c160SJan Kara 		}
59272d90c160SJan Kara 		ext4_es_find_delayed_extent_range(inode, map.m_lblk,
59282d90c160SJan Kara 						  map.m_lblk + map.m_len - 1,
59292d90c160SJan Kara 						  &es);
59302d90c160SJan Kara 		/* Is delalloc data before next block in extent tree? */
59312d90c160SJan Kara 		if (es.es_len && es.es_lblk < map.m_lblk + map.m_len) {
59322d90c160SJan Kara 			ext4_lblk_t offset = 0;
59332d90c160SJan Kara 
59342d90c160SJan Kara 			if (es.es_lblk < lblk)
59352d90c160SJan Kara 				offset = lblk - es.es_lblk;
59362d90c160SJan Kara 			result->es_lblk = es.es_lblk + offset;
59372d90c160SJan Kara 			ext4_es_store_pblock(result,
59382d90c160SJan Kara 					     ext4_es_pblock(&es) + offset);
59392d90c160SJan Kara 			result->es_len = es.es_len - offset;
59402d90c160SJan Kara 			ext4_es_store_status(result, ext4_es_status(&es));
59412d90c160SJan Kara 
59422d90c160SJan Kara 			return 1;
59432d90c160SJan Kara 		}
59442d90c160SJan Kara 		/* There's a hole at m_lblk, advance us after it */
59452d90c160SJan Kara 		map.m_lblk += map.m_len;
59462d90c160SJan Kara 		map_len -= map.m_len;
59472d90c160SJan Kara 		map.m_len = map_len;
59482d90c160SJan Kara 		cond_resched();
59492d90c160SJan Kara 	}
59502d90c160SJan Kara 	result->es_len = 0;
59512d90c160SJan Kara 	return 0;
59522d90c160SJan Kara }
5953