xref: /openbmc/linux/fs/ext4/inode.c (revision 5f16f3225b06242a9ee876f07c1c9b6ed36a22b6)
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>
23dab291afSMingming Cao #include <linux/jbd2.h>
24ac27a0ecSDave Kleikamp #include <linux/highuid.h>
25ac27a0ecSDave Kleikamp #include <linux/pagemap.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>
39a8901d34STheodore Ts'o #include <linux/ratelimit.h>
40a27bb332SKent Overstreet #include <linux/aio.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 	__u16 csum_lo;
56814525f4SDarrick J. Wong 	__u16 csum_hi = 0;
57814525f4SDarrick J. Wong 	__u32 csum;
58814525f4SDarrick J. Wong 
59171a7f21SDmitry Monakhov 	csum_lo = le16_to_cpu(raw->i_checksum_lo);
60814525f4SDarrick J. Wong 	raw->i_checksum_lo = 0;
61814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
62814525f4SDarrick J. Wong 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
63171a7f21SDmitry Monakhov 		csum_hi = le16_to_cpu(raw->i_checksum_hi);
64814525f4SDarrick J. Wong 		raw->i_checksum_hi = 0;
65814525f4SDarrick J. Wong 	}
66814525f4SDarrick J. Wong 
67814525f4SDarrick J. Wong 	csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw,
68814525f4SDarrick J. Wong 			   EXT4_INODE_SIZE(inode->i_sb));
69814525f4SDarrick J. Wong 
70171a7f21SDmitry Monakhov 	raw->i_checksum_lo = cpu_to_le16(csum_lo);
71814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
72814525f4SDarrick J. Wong 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
73171a7f21SDmitry Monakhov 		raw->i_checksum_hi = cpu_to_le16(csum_hi);
74814525f4SDarrick J. Wong 
75814525f4SDarrick J. Wong 	return csum;
76814525f4SDarrick J. Wong }
77814525f4SDarrick J. Wong 
78814525f4SDarrick J. Wong static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
79814525f4SDarrick J. Wong 				  struct ext4_inode_info *ei)
80814525f4SDarrick J. Wong {
81814525f4SDarrick J. Wong 	__u32 provided, calculated;
82814525f4SDarrick J. Wong 
83814525f4SDarrick J. Wong 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
84814525f4SDarrick J. Wong 	    cpu_to_le32(EXT4_OS_LINUX) ||
85814525f4SDarrick J. Wong 	    !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
86814525f4SDarrick J. Wong 		EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
87814525f4SDarrick J. Wong 		return 1;
88814525f4SDarrick J. Wong 
89814525f4SDarrick J. Wong 	provided = le16_to_cpu(raw->i_checksum_lo);
90814525f4SDarrick J. Wong 	calculated = ext4_inode_csum(inode, raw, ei);
91814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
92814525f4SDarrick J. Wong 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
93814525f4SDarrick J. Wong 		provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
94814525f4SDarrick J. Wong 	else
95814525f4SDarrick J. Wong 		calculated &= 0xFFFF;
96814525f4SDarrick J. Wong 
97814525f4SDarrick J. Wong 	return provided == calculated;
98814525f4SDarrick J. Wong }
99814525f4SDarrick J. Wong 
100814525f4SDarrick J. Wong static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
101814525f4SDarrick J. Wong 				struct ext4_inode_info *ei)
102814525f4SDarrick J. Wong {
103814525f4SDarrick J. Wong 	__u32 csum;
104814525f4SDarrick J. Wong 
105814525f4SDarrick J. Wong 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
106814525f4SDarrick J. Wong 	    cpu_to_le32(EXT4_OS_LINUX) ||
107814525f4SDarrick J. Wong 	    !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
108814525f4SDarrick J. Wong 		EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
109814525f4SDarrick J. Wong 		return;
110814525f4SDarrick J. Wong 
111814525f4SDarrick J. Wong 	csum = ext4_inode_csum(inode, raw, ei);
112814525f4SDarrick J. Wong 	raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
113814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
114814525f4SDarrick J. Wong 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
115814525f4SDarrick J. Wong 		raw->i_checksum_hi = cpu_to_le16(csum >> 16);
116814525f4SDarrick J. Wong }
117814525f4SDarrick J. Wong 
118678aaf48SJan Kara static inline int ext4_begin_ordered_truncate(struct inode *inode,
119678aaf48SJan Kara 					      loff_t new_size)
120678aaf48SJan Kara {
1217ff9c073STheodore Ts'o 	trace_ext4_begin_ordered_truncate(inode, new_size);
1228aefcd55STheodore Ts'o 	/*
1238aefcd55STheodore Ts'o 	 * If jinode is zero, then we never opened the file for
1248aefcd55STheodore Ts'o 	 * writing, so there's no need to call
1258aefcd55STheodore Ts'o 	 * jbd2_journal_begin_ordered_truncate() since there's no
1268aefcd55STheodore Ts'o 	 * outstanding writes we need to flush.
1278aefcd55STheodore Ts'o 	 */
1288aefcd55STheodore Ts'o 	if (!EXT4_I(inode)->jinode)
1298aefcd55STheodore Ts'o 		return 0;
1308aefcd55STheodore Ts'o 	return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
1318aefcd55STheodore Ts'o 						   EXT4_I(inode)->jinode,
132678aaf48SJan Kara 						   new_size);
133678aaf48SJan Kara }
134678aaf48SJan Kara 
135d47992f8SLukas Czerner static void ext4_invalidatepage(struct page *page, unsigned int offset,
136d47992f8SLukas Czerner 				unsigned int length);
137cb20d518STheodore Ts'o static int __ext4_journalled_writepage(struct page *page, unsigned int len);
138cb20d518STheodore Ts'o static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
139fffb2739SJan Kara static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
140fffb2739SJan Kara 				  int pextents);
14164769240SAlex Tomas 
142ac27a0ecSDave Kleikamp /*
143ac27a0ecSDave Kleikamp  * Test whether an inode is a fast symlink.
144ac27a0ecSDave Kleikamp  */
145617ba13bSMingming Cao static int ext4_inode_is_fast_symlink(struct inode *inode)
146ac27a0ecSDave Kleikamp {
147617ba13bSMingming Cao         int ea_blocks = EXT4_I(inode)->i_file_acl ?
14865eddb56SYongqiang Yang 		EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
149ac27a0ecSDave Kleikamp 
150ac27a0ecSDave Kleikamp 	return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
151ac27a0ecSDave Kleikamp }
152ac27a0ecSDave Kleikamp 
153ac27a0ecSDave Kleikamp /*
154ac27a0ecSDave Kleikamp  * Restart the transaction associated with *handle.  This does a commit,
155ac27a0ecSDave Kleikamp  * so before we call here everything must be consistently dirtied against
156ac27a0ecSDave Kleikamp  * this transaction.
157ac27a0ecSDave Kleikamp  */
158487caeefSJan Kara int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
159487caeefSJan Kara 				 int nblocks)
160ac27a0ecSDave Kleikamp {
161487caeefSJan Kara 	int ret;
162487caeefSJan Kara 
163487caeefSJan Kara 	/*
164e35fd660STheodore Ts'o 	 * Drop i_data_sem to avoid deadlock with ext4_map_blocks.  At this
165487caeefSJan Kara 	 * moment, get_block can be called only for blocks inside i_size since
166487caeefSJan Kara 	 * page cache has been already dropped and writes are blocked by
167487caeefSJan Kara 	 * i_mutex. So we can safely drop the i_data_sem here.
168487caeefSJan Kara 	 */
1690390131bSFrank Mayhar 	BUG_ON(EXT4_JOURNAL(inode) == NULL);
170ac27a0ecSDave Kleikamp 	jbd_debug(2, "restarting handle %p\n", handle);
171487caeefSJan Kara 	up_write(&EXT4_I(inode)->i_data_sem);
1728e8eaabeSAmir Goldstein 	ret = ext4_journal_restart(handle, nblocks);
173487caeefSJan Kara 	down_write(&EXT4_I(inode)->i_data_sem);
174fa5d1113SAneesh Kumar K.V 	ext4_discard_preallocations(inode);
175487caeefSJan Kara 
176487caeefSJan Kara 	return ret;
177ac27a0ecSDave Kleikamp }
178ac27a0ecSDave Kleikamp 
179ac27a0ecSDave Kleikamp /*
180ac27a0ecSDave Kleikamp  * Called at the last iput() if i_nlink is zero.
181ac27a0ecSDave Kleikamp  */
1820930fcc1SAl Viro void ext4_evict_inode(struct inode *inode)
183ac27a0ecSDave Kleikamp {
184ac27a0ecSDave Kleikamp 	handle_t *handle;
185bc965ab3STheodore Ts'o 	int err;
186ac27a0ecSDave Kleikamp 
1877ff9c073STheodore Ts'o 	trace_ext4_evict_inode(inode);
1882581fdc8SJiaying Zhang 
1890930fcc1SAl Viro 	if (inode->i_nlink) {
1902d859db3SJan Kara 		/*
1912d859db3SJan Kara 		 * When journalling data dirty buffers are tracked only in the
1922d859db3SJan Kara 		 * journal. So although mm thinks everything is clean and
1932d859db3SJan Kara 		 * ready for reaping the inode might still have some pages to
1942d859db3SJan Kara 		 * write in the running transaction or waiting to be
1952d859db3SJan Kara 		 * checkpointed. Thus calling jbd2_journal_invalidatepage()
1962d859db3SJan Kara 		 * (via truncate_inode_pages()) to discard these buffers can
1972d859db3SJan Kara 		 * cause data loss. Also even if we did not discard these
1982d859db3SJan Kara 		 * buffers, we would have no way to find them after the inode
1992d859db3SJan Kara 		 * is reaped and thus user could see stale data if he tries to
2002d859db3SJan Kara 		 * read them before the transaction is checkpointed. So be
2012d859db3SJan Kara 		 * careful and force everything to disk here... We use
2022d859db3SJan Kara 		 * ei->i_datasync_tid to store the newest transaction
2032d859db3SJan Kara 		 * containing inode's data.
2042d859db3SJan Kara 		 *
2052d859db3SJan Kara 		 * Note that directories do not have this problem because they
2062d859db3SJan Kara 		 * don't use page cache.
2072d859db3SJan Kara 		 */
2082d859db3SJan Kara 		if (ext4_should_journal_data(inode) &&
2092b405bfaSTheodore Ts'o 		    (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
2102b405bfaSTheodore Ts'o 		    inode->i_ino != EXT4_JOURNAL_INO) {
2112d859db3SJan Kara 			journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
2122d859db3SJan Kara 			tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
2132d859db3SJan Kara 
214d76a3a77STheodore Ts'o 			jbd2_complete_transaction(journal, commit_tid);
2152d859db3SJan Kara 			filemap_write_and_wait(&inode->i_data);
2162d859db3SJan Kara 		}
2170930fcc1SAl Viro 		truncate_inode_pages(&inode->i_data, 0);
2185dc23bddSJan Kara 
2195dc23bddSJan Kara 		WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
2200930fcc1SAl Viro 		goto no_delete;
2210930fcc1SAl Viro 	}
2220930fcc1SAl Viro 
223907f4554SChristoph Hellwig 	if (!is_bad_inode(inode))
224871a2931SChristoph Hellwig 		dquot_initialize(inode);
225907f4554SChristoph Hellwig 
226678aaf48SJan Kara 	if (ext4_should_order_data(inode))
227678aaf48SJan Kara 		ext4_begin_ordered_truncate(inode, 0);
228ac27a0ecSDave Kleikamp 	truncate_inode_pages(&inode->i_data, 0);
229ac27a0ecSDave Kleikamp 
2305dc23bddSJan Kara 	WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
231ac27a0ecSDave Kleikamp 	if (is_bad_inode(inode))
232ac27a0ecSDave Kleikamp 		goto no_delete;
233ac27a0ecSDave Kleikamp 
2348e8ad8a5SJan Kara 	/*
2358e8ad8a5SJan Kara 	 * Protect us against freezing - iput() caller didn't have to have any
2368e8ad8a5SJan Kara 	 * protection against it
2378e8ad8a5SJan Kara 	 */
2388e8ad8a5SJan Kara 	sb_start_intwrite(inode->i_sb);
2399924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
2409924a92aSTheodore Ts'o 				    ext4_blocks_for_truncate(inode)+3);
241ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
242bc965ab3STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
243ac27a0ecSDave Kleikamp 		/*
244ac27a0ecSDave Kleikamp 		 * If we're going to skip the normal cleanup, we still need to
245ac27a0ecSDave Kleikamp 		 * make sure that the in-core orphan linked list is properly
246ac27a0ecSDave Kleikamp 		 * cleaned up.
247ac27a0ecSDave Kleikamp 		 */
248617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
2498e8ad8a5SJan Kara 		sb_end_intwrite(inode->i_sb);
250ac27a0ecSDave Kleikamp 		goto no_delete;
251ac27a0ecSDave Kleikamp 	}
252ac27a0ecSDave Kleikamp 
253ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
2540390131bSFrank Mayhar 		ext4_handle_sync(handle);
255ac27a0ecSDave Kleikamp 	inode->i_size = 0;
256bc965ab3STheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
257bc965ab3STheodore Ts'o 	if (err) {
25812062dddSEric Sandeen 		ext4_warning(inode->i_sb,
259bc965ab3STheodore Ts'o 			     "couldn't mark inode dirty (err %d)", err);
260bc965ab3STheodore Ts'o 		goto stop_handle;
261bc965ab3STheodore Ts'o 	}
262ac27a0ecSDave Kleikamp 	if (inode->i_blocks)
263617ba13bSMingming Cao 		ext4_truncate(inode);
264bc965ab3STheodore Ts'o 
265bc965ab3STheodore Ts'o 	/*
266bc965ab3STheodore Ts'o 	 * ext4_ext_truncate() doesn't reserve any slop when it
267bc965ab3STheodore Ts'o 	 * restarts journal transactions; therefore there may not be
268bc965ab3STheodore Ts'o 	 * enough credits left in the handle to remove the inode from
269bc965ab3STheodore Ts'o 	 * the orphan list and set the dtime field.
270bc965ab3STheodore Ts'o 	 */
2710390131bSFrank Mayhar 	if (!ext4_handle_has_enough_credits(handle, 3)) {
272bc965ab3STheodore Ts'o 		err = ext4_journal_extend(handle, 3);
273bc965ab3STheodore Ts'o 		if (err > 0)
274bc965ab3STheodore Ts'o 			err = ext4_journal_restart(handle, 3);
275bc965ab3STheodore Ts'o 		if (err != 0) {
27612062dddSEric Sandeen 			ext4_warning(inode->i_sb,
277bc965ab3STheodore Ts'o 				     "couldn't extend journal (err %d)", err);
278bc965ab3STheodore Ts'o 		stop_handle:
279bc965ab3STheodore Ts'o 			ext4_journal_stop(handle);
28045388219STheodore Ts'o 			ext4_orphan_del(NULL, inode);
2818e8ad8a5SJan Kara 			sb_end_intwrite(inode->i_sb);
282bc965ab3STheodore Ts'o 			goto no_delete;
283bc965ab3STheodore Ts'o 		}
284bc965ab3STheodore Ts'o 	}
285bc965ab3STheodore Ts'o 
286ac27a0ecSDave Kleikamp 	/*
287617ba13bSMingming Cao 	 * Kill off the orphan record which ext4_truncate created.
288ac27a0ecSDave Kleikamp 	 * AKPM: I think this can be inside the above `if'.
289617ba13bSMingming Cao 	 * Note that ext4_orphan_del() has to be able to cope with the
290ac27a0ecSDave Kleikamp 	 * deletion of a non-existent orphan - this is because we don't
291617ba13bSMingming Cao 	 * know if ext4_truncate() actually created an orphan record.
292ac27a0ecSDave Kleikamp 	 * (Well, we could do this if we need to, but heck - it works)
293ac27a0ecSDave Kleikamp 	 */
294617ba13bSMingming Cao 	ext4_orphan_del(handle, inode);
295617ba13bSMingming Cao 	EXT4_I(inode)->i_dtime	= get_seconds();
296ac27a0ecSDave Kleikamp 
297ac27a0ecSDave Kleikamp 	/*
298ac27a0ecSDave Kleikamp 	 * One subtle ordering requirement: if anything has gone wrong
299ac27a0ecSDave Kleikamp 	 * (transaction abort, IO errors, whatever), then we can still
300ac27a0ecSDave Kleikamp 	 * do these next steps (the fs will already have been marked as
301ac27a0ecSDave Kleikamp 	 * having errors), but we can't free the inode if the mark_dirty
302ac27a0ecSDave Kleikamp 	 * fails.
303ac27a0ecSDave Kleikamp 	 */
304617ba13bSMingming Cao 	if (ext4_mark_inode_dirty(handle, inode))
305ac27a0ecSDave Kleikamp 		/* If that failed, just do the required in-core inode clear. */
3060930fcc1SAl Viro 		ext4_clear_inode(inode);
307ac27a0ecSDave Kleikamp 	else
308617ba13bSMingming Cao 		ext4_free_inode(handle, inode);
309617ba13bSMingming Cao 	ext4_journal_stop(handle);
3108e8ad8a5SJan Kara 	sb_end_intwrite(inode->i_sb);
311ac27a0ecSDave Kleikamp 	return;
312ac27a0ecSDave Kleikamp no_delete:
3130930fcc1SAl Viro 	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
314ac27a0ecSDave Kleikamp }
315ac27a0ecSDave Kleikamp 
316a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
317a9e7f447SDmitry Monakhov qsize_t *ext4_get_reserved_space(struct inode *inode)
31860e58e0fSMingming Cao {
319a9e7f447SDmitry Monakhov 	return &EXT4_I(inode)->i_reserved_quota;
32060e58e0fSMingming Cao }
321a9e7f447SDmitry Monakhov #endif
3229d0be502STheodore Ts'o 
32312219aeaSAneesh Kumar K.V /*
32412219aeaSAneesh Kumar K.V  * Calculate the number of metadata blocks need to reserve
3259d0be502STheodore Ts'o  * to allocate a block located at @lblock
32612219aeaSAneesh Kumar K.V  */
32701f49d0bSTheodore Ts'o static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
32812219aeaSAneesh Kumar K.V {
32912e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3309d0be502STheodore Ts'o 		return ext4_ext_calc_metadata_amount(inode, lblock);
33112219aeaSAneesh Kumar K.V 
3328bb2b247SAmir Goldstein 	return ext4_ind_calc_metadata_amount(inode, lblock);
33312219aeaSAneesh Kumar K.V }
33412219aeaSAneesh Kumar K.V 
3350637c6f4STheodore Ts'o /*
3360637c6f4STheodore Ts'o  * Called with i_data_sem down, which is important since we can call
3370637c6f4STheodore Ts'o  * ext4_discard_preallocations() from here.
3380637c6f4STheodore Ts'o  */
3395f634d06SAneesh Kumar K.V void ext4_da_update_reserve_space(struct inode *inode,
3405f634d06SAneesh Kumar K.V 					int used, int quota_claim)
34112219aeaSAneesh Kumar K.V {
34212219aeaSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3430637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
34412219aeaSAneesh Kumar K.V 
3450637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
346d8990240SAditya Kali 	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
3470637c6f4STheodore Ts'o 	if (unlikely(used > ei->i_reserved_data_blocks)) {
3488de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
3491084f252STheodore Ts'o 			 "with only %d reserved data blocks",
3500637c6f4STheodore Ts'o 			 __func__, inode->i_ino, used,
3510637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
3520637c6f4STheodore Ts'o 		WARN_ON(1);
3530637c6f4STheodore Ts'o 		used = ei->i_reserved_data_blocks;
3546bc6e63fSAneesh Kumar K.V 	}
35512219aeaSAneesh Kumar K.V 
35697795d2aSBrian Foster 	if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
35701a523ebSTheodore Ts'o 		ext4_warning(inode->i_sb, "ino %lu, allocated %d "
35801a523ebSTheodore Ts'o 			"with only %d reserved metadata blocks "
35901a523ebSTheodore Ts'o 			"(releasing %d blocks with reserved %d data blocks)",
36097795d2aSBrian Foster 			inode->i_ino, ei->i_allocated_meta_blocks,
36101a523ebSTheodore Ts'o 			     ei->i_reserved_meta_blocks, used,
36201a523ebSTheodore Ts'o 			     ei->i_reserved_data_blocks);
36397795d2aSBrian Foster 		WARN_ON(1);
36497795d2aSBrian Foster 		ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
36597795d2aSBrian Foster 	}
36697795d2aSBrian Foster 
3670637c6f4STheodore Ts'o 	/* Update per-inode reservations */
3680637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= used;
3690637c6f4STheodore Ts'o 	ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
37057042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter,
37172b8ab9dSEric Sandeen 			   used + ei->i_allocated_meta_blocks);
3720637c6f4STheodore Ts'o 	ei->i_allocated_meta_blocks = 0;
3730637c6f4STheodore Ts'o 
3740637c6f4STheodore Ts'o 	if (ei->i_reserved_data_blocks == 0) {
3750637c6f4STheodore Ts'o 		/*
3760637c6f4STheodore Ts'o 		 * We can release all of the reserved metadata blocks
3770637c6f4STheodore Ts'o 		 * only when we have written all of the delayed
3780637c6f4STheodore Ts'o 		 * allocation blocks.
3790637c6f4STheodore Ts'o 		 */
38057042651STheodore Ts'o 		percpu_counter_sub(&sbi->s_dirtyclusters_counter,
38172b8ab9dSEric Sandeen 				   ei->i_reserved_meta_blocks);
382ee5f4d9cSTheodore Ts'o 		ei->i_reserved_meta_blocks = 0;
3839d0be502STheodore Ts'o 		ei->i_da_metadata_calc_len = 0;
3840637c6f4STheodore Ts'o 	}
38512219aeaSAneesh Kumar K.V 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
38660e58e0fSMingming Cao 
38772b8ab9dSEric Sandeen 	/* Update quota subsystem for data blocks */
38872b8ab9dSEric Sandeen 	if (quota_claim)
3897b415bf6SAditya Kali 		dquot_claim_block(inode, EXT4_C2B(sbi, used));
39072b8ab9dSEric Sandeen 	else {
3915f634d06SAneesh Kumar K.V 		/*
3925f634d06SAneesh Kumar K.V 		 * We did fallocate with an offset that is already delayed
3935f634d06SAneesh Kumar K.V 		 * allocated. So on delayed allocated writeback we should
39472b8ab9dSEric Sandeen 		 * not re-claim the quota for fallocated blocks.
3955f634d06SAneesh Kumar K.V 		 */
3967b415bf6SAditya Kali 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
3975f634d06SAneesh Kumar K.V 	}
398d6014301SAneesh Kumar K.V 
399d6014301SAneesh Kumar K.V 	/*
400d6014301SAneesh Kumar K.V 	 * If we have done all the pending block allocations and if
401d6014301SAneesh Kumar K.V 	 * there aren't any writers on the inode, we can discard the
402d6014301SAneesh Kumar K.V 	 * inode's preallocations.
403d6014301SAneesh Kumar K.V 	 */
4040637c6f4STheodore Ts'o 	if ((ei->i_reserved_data_blocks == 0) &&
4050637c6f4STheodore Ts'o 	    (atomic_read(&inode->i_writecount) == 0))
406d6014301SAneesh Kumar K.V 		ext4_discard_preallocations(inode);
40712219aeaSAneesh Kumar K.V }
40812219aeaSAneesh Kumar K.V 
409e29136f8STheodore Ts'o static int __check_block_validity(struct inode *inode, const char *func,
410c398eda0STheodore Ts'o 				unsigned int line,
41124676da4STheodore Ts'o 				struct ext4_map_blocks *map)
4126fd058f7STheodore Ts'o {
41324676da4STheodore Ts'o 	if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
41424676da4STheodore Ts'o 				   map->m_len)) {
415c398eda0STheodore Ts'o 		ext4_error_inode(inode, func, line, map->m_pblk,
416c398eda0STheodore Ts'o 				 "lblock %lu mapped to illegal pblock "
41724676da4STheodore Ts'o 				 "(length %d)", (unsigned long) map->m_lblk,
418c398eda0STheodore Ts'o 				 map->m_len);
4196fd058f7STheodore Ts'o 		return -EIO;
4206fd058f7STheodore Ts'o 	}
4216fd058f7STheodore Ts'o 	return 0;
4226fd058f7STheodore Ts'o }
4236fd058f7STheodore Ts'o 
424e29136f8STheodore Ts'o #define check_block_validity(inode, map)	\
425c398eda0STheodore Ts'o 	__check_block_validity((inode), __func__, __LINE__, (map))
426e29136f8STheodore Ts'o 
427921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
428921f266bSDmitry Monakhov static void ext4_map_blocks_es_recheck(handle_t *handle,
429921f266bSDmitry Monakhov 				       struct inode *inode,
430921f266bSDmitry Monakhov 				       struct ext4_map_blocks *es_map,
431921f266bSDmitry Monakhov 				       struct ext4_map_blocks *map,
432921f266bSDmitry Monakhov 				       int flags)
433921f266bSDmitry Monakhov {
434921f266bSDmitry Monakhov 	int retval;
435921f266bSDmitry Monakhov 
436921f266bSDmitry Monakhov 	map->m_flags = 0;
437921f266bSDmitry Monakhov 	/*
438921f266bSDmitry Monakhov 	 * There is a race window that the result is not the same.
439921f266bSDmitry Monakhov 	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
440921f266bSDmitry Monakhov 	 * is that we lookup a block mapping in extent status tree with
441921f266bSDmitry Monakhov 	 * out taking i_data_sem.  So at the time the unwritten extent
442921f266bSDmitry Monakhov 	 * could be converted.
443921f266bSDmitry Monakhov 	 */
444921f266bSDmitry Monakhov 	if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
445921f266bSDmitry Monakhov 		down_read((&EXT4_I(inode)->i_data_sem));
446921f266bSDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
447921f266bSDmitry Monakhov 		retval = ext4_ext_map_blocks(handle, inode, map, flags &
448921f266bSDmitry Monakhov 					     EXT4_GET_BLOCKS_KEEP_SIZE);
449921f266bSDmitry Monakhov 	} else {
450921f266bSDmitry Monakhov 		retval = ext4_ind_map_blocks(handle, inode, map, flags &
451921f266bSDmitry Monakhov 					     EXT4_GET_BLOCKS_KEEP_SIZE);
452921f266bSDmitry Monakhov 	}
453921f266bSDmitry Monakhov 	if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
454921f266bSDmitry Monakhov 		up_read((&EXT4_I(inode)->i_data_sem));
455921f266bSDmitry Monakhov 	/*
456921f266bSDmitry Monakhov 	 * Clear EXT4_MAP_FROM_CLUSTER and EXT4_MAP_BOUNDARY flag
457921f266bSDmitry Monakhov 	 * because it shouldn't be marked in es_map->m_flags.
458921f266bSDmitry Monakhov 	 */
459921f266bSDmitry Monakhov 	map->m_flags &= ~(EXT4_MAP_FROM_CLUSTER | EXT4_MAP_BOUNDARY);
460921f266bSDmitry Monakhov 
461921f266bSDmitry Monakhov 	/*
462921f266bSDmitry Monakhov 	 * We don't check m_len because extent will be collpased in status
463921f266bSDmitry Monakhov 	 * tree.  So the m_len might not equal.
464921f266bSDmitry Monakhov 	 */
465921f266bSDmitry Monakhov 	if (es_map->m_lblk != map->m_lblk ||
466921f266bSDmitry Monakhov 	    es_map->m_flags != map->m_flags ||
467921f266bSDmitry Monakhov 	    es_map->m_pblk != map->m_pblk) {
468bdafe42aSTheodore Ts'o 		printk("ES cache assertion failed for inode: %lu "
469921f266bSDmitry Monakhov 		       "es_cached ex [%d/%d/%llu/%x] != "
470921f266bSDmitry Monakhov 		       "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
471921f266bSDmitry Monakhov 		       inode->i_ino, es_map->m_lblk, es_map->m_len,
472921f266bSDmitry Monakhov 		       es_map->m_pblk, es_map->m_flags, map->m_lblk,
473921f266bSDmitry Monakhov 		       map->m_len, map->m_pblk, map->m_flags,
474921f266bSDmitry Monakhov 		       retval, flags);
475921f266bSDmitry Monakhov 	}
476921f266bSDmitry Monakhov }
477921f266bSDmitry Monakhov #endif /* ES_AGGRESSIVE_TEST */
478921f266bSDmitry Monakhov 
47955138e0bSTheodore Ts'o /*
480e35fd660STheodore Ts'o  * The ext4_map_blocks() function tries to look up the requested blocks,
4812b2d6d01STheodore Ts'o  * and returns if the blocks are already mapped.
482f5ab0d1fSMingming Cao  *
483f5ab0d1fSMingming Cao  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
484f5ab0d1fSMingming Cao  * and store the allocated blocks in the result buffer head and mark it
485f5ab0d1fSMingming Cao  * mapped.
486f5ab0d1fSMingming Cao  *
487e35fd660STheodore Ts'o  * If file type is extents based, it will call ext4_ext_map_blocks(),
488e35fd660STheodore Ts'o  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
489f5ab0d1fSMingming Cao  * based files
490f5ab0d1fSMingming Cao  *
491f5ab0d1fSMingming Cao  * On success, it returns the number of blocks being mapped or allocate.
492f5ab0d1fSMingming Cao  * if create==0 and the blocks are pre-allocated and uninitialized block,
493f5ab0d1fSMingming Cao  * the result buffer head is unmapped. If the create ==1, it will make sure
494f5ab0d1fSMingming Cao  * the buffer head is mapped.
495f5ab0d1fSMingming Cao  *
496f5ab0d1fSMingming Cao  * It returns 0 if plain look up failed (blocks have not been allocated), in
497df3ab170STao Ma  * that case, buffer head is unmapped
498f5ab0d1fSMingming Cao  *
499f5ab0d1fSMingming Cao  * It returns the error in case of allocation failure.
500f5ab0d1fSMingming Cao  */
501e35fd660STheodore Ts'o int ext4_map_blocks(handle_t *handle, struct inode *inode,
502e35fd660STheodore Ts'o 		    struct ext4_map_blocks *map, int flags)
5030e855ac8SAneesh Kumar K.V {
504d100eef2SZheng Liu 	struct extent_status es;
5050e855ac8SAneesh Kumar K.V 	int retval;
506b8a86845SLukas Czerner 	int ret = 0;
507921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
508921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
509921f266bSDmitry Monakhov 
510921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
511921f266bSDmitry Monakhov #endif
512f5ab0d1fSMingming Cao 
513e35fd660STheodore Ts'o 	map->m_flags = 0;
514e35fd660STheodore Ts'o 	ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
515e35fd660STheodore Ts'o 		  "logical block %lu\n", inode->i_ino, flags, map->m_len,
516e35fd660STheodore Ts'o 		  (unsigned long) map->m_lblk);
517d100eef2SZheng Liu 
518e861b5e9STheodore Ts'o 	/*
519e861b5e9STheodore Ts'o 	 * ext4_map_blocks returns an int, and m_len is an unsigned int
520e861b5e9STheodore Ts'o 	 */
521e861b5e9STheodore Ts'o 	if (unlikely(map->m_len > INT_MAX))
522e861b5e9STheodore Ts'o 		map->m_len = INT_MAX;
523e861b5e9STheodore Ts'o 
524d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
525d100eef2SZheng Liu 	if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
52663b99968STheodore Ts'o 		ext4_es_lru_add(inode);
527d100eef2SZheng Liu 		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
528d100eef2SZheng Liu 			map->m_pblk = ext4_es_pblock(&es) +
529d100eef2SZheng Liu 					map->m_lblk - es.es_lblk;
530d100eef2SZheng Liu 			map->m_flags |= ext4_es_is_written(&es) ?
531d100eef2SZheng Liu 					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
532d100eef2SZheng Liu 			retval = es.es_len - (map->m_lblk - es.es_lblk);
533d100eef2SZheng Liu 			if (retval > map->m_len)
534d100eef2SZheng Liu 				retval = map->m_len;
535d100eef2SZheng Liu 			map->m_len = retval;
536d100eef2SZheng Liu 		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
537d100eef2SZheng Liu 			retval = 0;
538d100eef2SZheng Liu 		} else {
539d100eef2SZheng Liu 			BUG_ON(1);
540d100eef2SZheng Liu 		}
541921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
542921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(handle, inode, map,
543921f266bSDmitry Monakhov 					   &orig_map, flags);
544921f266bSDmitry Monakhov #endif
545d100eef2SZheng Liu 		goto found;
546d100eef2SZheng Liu 	}
547d100eef2SZheng Liu 
5484df3d265SAneesh Kumar K.V 	/*
549b920c755STheodore Ts'o 	 * Try to see if we can get the block without requesting a new
550b920c755STheodore Ts'o 	 * file system block.
5514df3d265SAneesh Kumar K.V 	 */
552729f52c6SZheng Liu 	if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
5530e855ac8SAneesh Kumar K.V 		down_read((&EXT4_I(inode)->i_data_sem));
55412e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
555a4e5d88bSDmitry Monakhov 		retval = ext4_ext_map_blocks(handle, inode, map, flags &
556a4e5d88bSDmitry Monakhov 					     EXT4_GET_BLOCKS_KEEP_SIZE);
5574df3d265SAneesh Kumar K.V 	} else {
558a4e5d88bSDmitry Monakhov 		retval = ext4_ind_map_blocks(handle, inode, map, flags &
559a4e5d88bSDmitry Monakhov 					     EXT4_GET_BLOCKS_KEEP_SIZE);
5600e855ac8SAneesh Kumar K.V 	}
561f7fec032SZheng Liu 	if (retval > 0) {
5623be78c73STheodore Ts'o 		unsigned int status;
563f7fec032SZheng Liu 
56444fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
56544fb851dSZheng Liu 			ext4_warning(inode->i_sb,
56644fb851dSZheng Liu 				     "ES len assertion failed for inode "
56744fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
56844fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
56944fb851dSZheng Liu 			WARN_ON(1);
570921f266bSDmitry Monakhov 		}
571921f266bSDmitry Monakhov 
572f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
573f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
574f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
575f7fec032SZheng Liu 		    ext4_find_delalloc_range(inode, map->m_lblk,
576f7fec032SZheng Liu 					     map->m_lblk + map->m_len - 1))
577f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
578f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk,
579f7fec032SZheng Liu 					    map->m_len, map->m_pblk, status);
580f7fec032SZheng Liu 		if (ret < 0)
581f7fec032SZheng Liu 			retval = ret;
582f7fec032SZheng Liu 	}
583729f52c6SZheng Liu 	if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
5844df3d265SAneesh Kumar K.V 		up_read((&EXT4_I(inode)->i_data_sem));
585f5ab0d1fSMingming Cao 
586d100eef2SZheng Liu found:
587e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
588b8a86845SLukas Czerner 		ret = check_block_validity(inode, map);
5896fd058f7STheodore Ts'o 		if (ret != 0)
5906fd058f7STheodore Ts'o 			return ret;
5916fd058f7STheodore Ts'o 	}
5926fd058f7STheodore Ts'o 
593f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
594c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
5954df3d265SAneesh Kumar K.V 		return retval;
5964df3d265SAneesh Kumar K.V 
5974df3d265SAneesh Kumar K.V 	/*
598f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
599f5ab0d1fSMingming Cao 	 *
600f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
601df3ab170STao Ma 	 * ext4_ext_get_block() returns the create = 0
602f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
603f5ab0d1fSMingming Cao 	 */
604e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
605b8a86845SLukas Czerner 		/*
606b8a86845SLukas Czerner 		 * If we need to convert extent to unwritten
607b8a86845SLukas Czerner 		 * we continue and do the actual work in
608b8a86845SLukas Czerner 		 * ext4_ext_map_blocks()
609b8a86845SLukas Czerner 		 */
610b8a86845SLukas Czerner 		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
611f5ab0d1fSMingming Cao 			return retval;
612f5ab0d1fSMingming Cao 
613f5ab0d1fSMingming Cao 	/*
614a25a4e1aSZheng Liu 	 * Here we clear m_flags because after allocating an new extent,
615a25a4e1aSZheng Liu 	 * it will be set again.
6162a8964d6SAneesh Kumar K.V 	 */
617a25a4e1aSZheng Liu 	map->m_flags &= ~EXT4_MAP_FLAGS;
6182a8964d6SAneesh Kumar K.V 
6192a8964d6SAneesh Kumar K.V 	/*
620f5ab0d1fSMingming Cao 	 * New blocks allocate and/or writing to uninitialized extent
621f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
622f5ab0d1fSMingming Cao 	 * the write lock of i_data_sem, and call get_blocks()
623f5ab0d1fSMingming Cao 	 * with create == 1 flag.
6244df3d265SAneesh Kumar K.V 	 */
6254df3d265SAneesh Kumar K.V 	down_write((&EXT4_I(inode)->i_data_sem));
626d2a17637SMingming Cao 
627d2a17637SMingming Cao 	/*
628d2a17637SMingming Cao 	 * if the caller is from delayed allocation writeout path
629d2a17637SMingming Cao 	 * we have already reserved fs blocks for allocation
630d2a17637SMingming Cao 	 * let the underlying get_block() function know to
631d2a17637SMingming Cao 	 * avoid double accounting
632d2a17637SMingming Cao 	 */
633c2177057STheodore Ts'o 	if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
634f2321097STheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
6354df3d265SAneesh Kumar K.V 	/*
6364df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
6374df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
6384df3d265SAneesh Kumar K.V 	 */
63912e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
640e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
6410e855ac8SAneesh Kumar K.V 	} else {
642e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
643267e4db9SAneesh Kumar K.V 
644e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
645267e4db9SAneesh Kumar K.V 			/*
646267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
647267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
648267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
649267e4db9SAneesh Kumar K.V 			 */
65019f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
651267e4db9SAneesh Kumar K.V 		}
6522ac3b6e0STheodore Ts'o 
653d2a17637SMingming Cao 		/*
6542ac3b6e0STheodore Ts'o 		 * Update reserved blocks/metadata blocks after successful
6555f634d06SAneesh Kumar K.V 		 * block allocation which had been deferred till now. We don't
6565f634d06SAneesh Kumar K.V 		 * support fallocate for non extent files. So we can update
6575f634d06SAneesh Kumar K.V 		 * reserve space here.
658d2a17637SMingming Cao 		 */
6595f634d06SAneesh Kumar K.V 		if ((retval > 0) &&
6601296cc85SAneesh Kumar K.V 			(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
6615f634d06SAneesh Kumar K.V 			ext4_da_update_reserve_space(inode, retval, 1);
6625f634d06SAneesh Kumar K.V 	}
663f7fec032SZheng Liu 	if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
664f2321097STheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
665d2a17637SMingming Cao 
666f7fec032SZheng Liu 	if (retval > 0) {
6673be78c73STheodore Ts'o 		unsigned int status;
668f7fec032SZheng Liu 
66944fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
67044fb851dSZheng Liu 			ext4_warning(inode->i_sb,
67144fb851dSZheng Liu 				     "ES len assertion failed for inode "
67244fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
67344fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
67444fb851dSZheng Liu 			WARN_ON(1);
675921f266bSDmitry Monakhov 		}
676921f266bSDmitry Monakhov 
677adb23551SZheng Liu 		/*
678adb23551SZheng Liu 		 * If the extent has been zeroed out, we don't need to update
679adb23551SZheng Liu 		 * extent status tree.
680adb23551SZheng Liu 		 */
681adb23551SZheng Liu 		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
682adb23551SZheng Liu 		    ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
683adb23551SZheng Liu 			if (ext4_es_is_written(&es))
684adb23551SZheng Liu 				goto has_zeroout;
685adb23551SZheng Liu 		}
686f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
687f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
688f7fec032SZheng Liu 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
689f7fec032SZheng Liu 		    ext4_find_delalloc_range(inode, map->m_lblk,
690f7fec032SZheng Liu 					     map->m_lblk + map->m_len - 1))
691f7fec032SZheng Liu 			status |= EXTENT_STATUS_DELAYED;
692f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
693f7fec032SZheng Liu 					    map->m_pblk, status);
69451865fdaSZheng Liu 		if (ret < 0)
69551865fdaSZheng Liu 			retval = ret;
69651865fdaSZheng Liu 	}
6975356f261SAditya Kali 
698adb23551SZheng Liu has_zeroout:
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;
7046fd058f7STheodore Ts'o 	}
7050e855ac8SAneesh Kumar K.V 	return retval;
7060e855ac8SAneesh Kumar K.V }
7070e855ac8SAneesh Kumar K.V 
708f3bd1f3fSMingming Cao /* Maximum number of blocks we map for direct IO at once. */
709f3bd1f3fSMingming Cao #define DIO_MAX_BLOCKS 4096
710f3bd1f3fSMingming Cao 
7112ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
7122ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
713ac27a0ecSDave Kleikamp {
7143e4fdaf8SDmitriy Monakhov 	handle_t *handle = ext4_journal_current_handle();
7152ed88685STheodore Ts'o 	struct ext4_map_blocks map;
7167fb5409dSJan Kara 	int ret = 0, started = 0;
717f3bd1f3fSMingming Cao 	int dio_credits;
718ac27a0ecSDave Kleikamp 
71946c7f254STao Ma 	if (ext4_has_inline_data(inode))
72046c7f254STao Ma 		return -ERANGE;
72146c7f254STao Ma 
7222ed88685STheodore Ts'o 	map.m_lblk = iblock;
7232ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
7242ed88685STheodore Ts'o 
7258b0f165fSAnatol Pomozov 	if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
7267fb5409dSJan Kara 		/* Direct IO write... */
7272ed88685STheodore Ts'o 		if (map.m_len > DIO_MAX_BLOCKS)
7282ed88685STheodore Ts'o 			map.m_len = DIO_MAX_BLOCKS;
7292ed88685STheodore Ts'o 		dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
7309924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
7319924a92aSTheodore Ts'o 					    dio_credits);
7327fb5409dSJan Kara 		if (IS_ERR(handle)) {
733ac27a0ecSDave Kleikamp 			ret = PTR_ERR(handle);
7342ed88685STheodore Ts'o 			return ret;
7357fb5409dSJan Kara 		}
7367fb5409dSJan Kara 		started = 1;
737ac27a0ecSDave Kleikamp 	}
738ac27a0ecSDave Kleikamp 
7392ed88685STheodore Ts'o 	ret = ext4_map_blocks(handle, inode, &map, flags);
740ac27a0ecSDave Kleikamp 	if (ret > 0) {
7417b7a8665SChristoph Hellwig 		ext4_io_end_t *io_end = ext4_inode_aio(inode);
7427b7a8665SChristoph Hellwig 
7432ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
7442ed88685STheodore Ts'o 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
7457b7a8665SChristoph Hellwig 		if (io_end && io_end->flag & EXT4_IO_END_UNWRITTEN)
7467b7a8665SChristoph Hellwig 			set_buffer_defer_completion(bh);
7472ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
748ac27a0ecSDave Kleikamp 		ret = 0;
749ac27a0ecSDave Kleikamp 	}
7507fb5409dSJan Kara 	if (started)
7517fb5409dSJan Kara 		ext4_journal_stop(handle);
752ac27a0ecSDave Kleikamp 	return ret;
753ac27a0ecSDave Kleikamp }
754ac27a0ecSDave Kleikamp 
7552ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
7562ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
7572ed88685STheodore Ts'o {
7582ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
7592ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
7602ed88685STheodore Ts'o }
7612ed88685STheodore Ts'o 
762ac27a0ecSDave Kleikamp /*
763ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
764ac27a0ecSDave Kleikamp  */
765617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
766725d26d3SAneesh Kumar K.V 				ext4_lblk_t block, int create, int *errp)
767ac27a0ecSDave Kleikamp {
7682ed88685STheodore Ts'o 	struct ext4_map_blocks map;
7692ed88685STheodore Ts'o 	struct buffer_head *bh;
770ac27a0ecSDave Kleikamp 	int fatal = 0, err;
771ac27a0ecSDave Kleikamp 
772ac27a0ecSDave Kleikamp 	J_ASSERT(handle != NULL || create == 0);
773ac27a0ecSDave Kleikamp 
7742ed88685STheodore Ts'o 	map.m_lblk = block;
7752ed88685STheodore Ts'o 	map.m_len = 1;
7762ed88685STheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map,
7772ed88685STheodore Ts'o 			      create ? EXT4_GET_BLOCKS_CREATE : 0);
7782ed88685STheodore Ts'o 
77990b0a973SCarlos Maiolino 	/* ensure we send some value back into *errp */
78090b0a973SCarlos Maiolino 	*errp = 0;
78190b0a973SCarlos Maiolino 
7820f70b406STheodore Ts'o 	if (create && err == 0)
7830f70b406STheodore Ts'o 		err = -ENOSPC;	/* should never happen */
7842ed88685STheodore Ts'o 	if (err < 0)
785ac27a0ecSDave Kleikamp 		*errp = err;
7862ed88685STheodore Ts'o 	if (err <= 0)
7872ed88685STheodore Ts'o 		return NULL;
7882ed88685STheodore Ts'o 
7892ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
790aebf0243SWang Shilong 	if (unlikely(!bh)) {
791860d21e2STheodore Ts'o 		*errp = -ENOMEM;
7922ed88685STheodore Ts'o 		return NULL;
793ac27a0ecSDave Kleikamp 	}
7942ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
795ac27a0ecSDave Kleikamp 		J_ASSERT(create != 0);
796ac39849dSAneesh Kumar K.V 		J_ASSERT(handle != NULL);
797ac27a0ecSDave Kleikamp 
798ac27a0ecSDave Kleikamp 		/*
799ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
800ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
801ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
802617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
803ac27a0ecSDave Kleikamp 		 * problem.
804ac27a0ecSDave Kleikamp 		 */
805ac27a0ecSDave Kleikamp 		lock_buffer(bh);
806ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
807617ba13bSMingming Cao 		fatal = ext4_journal_get_create_access(handle, bh);
808ac27a0ecSDave Kleikamp 		if (!fatal && !buffer_uptodate(bh)) {
809ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
810ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
811ac27a0ecSDave Kleikamp 		}
812ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
8130390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
8140390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
815ac27a0ecSDave Kleikamp 		if (!fatal)
816ac27a0ecSDave Kleikamp 			fatal = err;
817ac27a0ecSDave Kleikamp 	} else {
818ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
819ac27a0ecSDave Kleikamp 	}
820ac27a0ecSDave Kleikamp 	if (fatal) {
821ac27a0ecSDave Kleikamp 		*errp = fatal;
822ac27a0ecSDave Kleikamp 		brelse(bh);
823ac27a0ecSDave Kleikamp 		bh = NULL;
824ac27a0ecSDave Kleikamp 	}
825ac27a0ecSDave Kleikamp 	return bh;
826ac27a0ecSDave Kleikamp }
827ac27a0ecSDave Kleikamp 
828617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
829725d26d3SAneesh Kumar K.V 			       ext4_lblk_t block, int create, int *err)
830ac27a0ecSDave Kleikamp {
831ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
832ac27a0ecSDave Kleikamp 
833617ba13bSMingming Cao 	bh = ext4_getblk(handle, inode, block, create, err);
834ac27a0ecSDave Kleikamp 	if (!bh)
835ac27a0ecSDave Kleikamp 		return bh;
836ac27a0ecSDave Kleikamp 	if (buffer_uptodate(bh))
837ac27a0ecSDave Kleikamp 		return bh;
83865299a3bSChristoph Hellwig 	ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
839ac27a0ecSDave Kleikamp 	wait_on_buffer(bh);
840ac27a0ecSDave Kleikamp 	if (buffer_uptodate(bh))
841ac27a0ecSDave Kleikamp 		return bh;
842ac27a0ecSDave Kleikamp 	put_bh(bh);
843ac27a0ecSDave Kleikamp 	*err = -EIO;
844ac27a0ecSDave Kleikamp 	return NULL;
845ac27a0ecSDave Kleikamp }
846ac27a0ecSDave Kleikamp 
847f19d5870STao Ma int ext4_walk_page_buffers(handle_t *handle,
848ac27a0ecSDave Kleikamp 			   struct buffer_head *head,
849ac27a0ecSDave Kleikamp 			   unsigned from,
850ac27a0ecSDave Kleikamp 			   unsigned to,
851ac27a0ecSDave Kleikamp 			   int *partial,
852ac27a0ecSDave Kleikamp 			   int (*fn)(handle_t *handle,
853ac27a0ecSDave Kleikamp 				     struct buffer_head *bh))
854ac27a0ecSDave Kleikamp {
855ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
856ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
857ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
858ac27a0ecSDave Kleikamp 	int err, ret = 0;
859ac27a0ecSDave Kleikamp 	struct buffer_head *next;
860ac27a0ecSDave Kleikamp 
861ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
862ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
863de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
864ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
865ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
866ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
867ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
868ac27a0ecSDave Kleikamp 				*partial = 1;
869ac27a0ecSDave Kleikamp 			continue;
870ac27a0ecSDave Kleikamp 		}
871ac27a0ecSDave Kleikamp 		err = (*fn)(handle, bh);
872ac27a0ecSDave Kleikamp 		if (!ret)
873ac27a0ecSDave Kleikamp 			ret = err;
874ac27a0ecSDave Kleikamp 	}
875ac27a0ecSDave Kleikamp 	return ret;
876ac27a0ecSDave Kleikamp }
877ac27a0ecSDave Kleikamp 
878ac27a0ecSDave Kleikamp /*
879ac27a0ecSDave Kleikamp  * To preserve ordering, it is essential that the hole instantiation and
880ac27a0ecSDave Kleikamp  * the data write be encapsulated in a single transaction.  We cannot
881617ba13bSMingming Cao  * close off a transaction and start a new one between the ext4_get_block()
882dab291afSMingming Cao  * and the commit_write().  So doing the jbd2_journal_start at the start of
883ac27a0ecSDave Kleikamp  * prepare_write() is the right place.
884ac27a0ecSDave Kleikamp  *
88536ade451SJan Kara  * Also, this function can nest inside ext4_writepage().  In that case, we
88636ade451SJan Kara  * *know* that ext4_writepage() has generated enough buffer credits to do the
88736ade451SJan Kara  * whole page.  So we won't block on the journal in that case, which is good,
88836ade451SJan Kara  * because the caller may be PF_MEMALLOC.
889ac27a0ecSDave Kleikamp  *
890617ba13bSMingming Cao  * By accident, ext4 can be reentered when a transaction is open via
891ac27a0ecSDave Kleikamp  * quota file writes.  If we were to commit the transaction while thus
892ac27a0ecSDave Kleikamp  * reentered, there can be a deadlock - we would be holding a quota
893ac27a0ecSDave Kleikamp  * lock, and the commit would never complete if another thread had a
894ac27a0ecSDave Kleikamp  * transaction open and was blocking on the quota lock - a ranking
895ac27a0ecSDave Kleikamp  * violation.
896ac27a0ecSDave Kleikamp  *
897dab291afSMingming Cao  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
898ac27a0ecSDave Kleikamp  * will _not_ run commit under these circumstances because handle->h_ref
899ac27a0ecSDave Kleikamp  * is elevated.  We'll still have enough credits for the tiny quotafile
900ac27a0ecSDave Kleikamp  * write.
901ac27a0ecSDave Kleikamp  */
902f19d5870STao Ma int do_journal_get_write_access(handle_t *handle,
903ac27a0ecSDave Kleikamp 				struct buffer_head *bh)
904ac27a0ecSDave Kleikamp {
90556d35a4cSJan Kara 	int dirty = buffer_dirty(bh);
90656d35a4cSJan Kara 	int ret;
90756d35a4cSJan Kara 
908ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
909ac27a0ecSDave Kleikamp 		return 0;
91056d35a4cSJan Kara 	/*
911ebdec241SChristoph Hellwig 	 * __block_write_begin() could have dirtied some buffers. Clean
91256d35a4cSJan Kara 	 * the dirty bit as jbd2_journal_get_write_access() could complain
91356d35a4cSJan Kara 	 * otherwise about fs integrity issues. Setting of the dirty bit
914ebdec241SChristoph Hellwig 	 * by __block_write_begin() isn't a real problem here as we clear
91556d35a4cSJan Kara 	 * the bit before releasing a page lock and thus writeback cannot
91656d35a4cSJan Kara 	 * ever write the buffer.
91756d35a4cSJan Kara 	 */
91856d35a4cSJan Kara 	if (dirty)
91956d35a4cSJan Kara 		clear_buffer_dirty(bh);
92056d35a4cSJan Kara 	ret = ext4_journal_get_write_access(handle, bh);
92156d35a4cSJan Kara 	if (!ret && dirty)
92256d35a4cSJan Kara 		ret = ext4_handle_dirty_metadata(handle, NULL, bh);
92356d35a4cSJan Kara 	return ret;
924ac27a0ecSDave Kleikamp }
925ac27a0ecSDave Kleikamp 
9268b0f165fSAnatol Pomozov static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
9278b0f165fSAnatol Pomozov 		   struct buffer_head *bh_result, int create);
928bfc1af65SNick Piggin static int ext4_write_begin(struct file *file, struct address_space *mapping,
929bfc1af65SNick Piggin 			    loff_t pos, unsigned len, unsigned flags,
930bfc1af65SNick Piggin 			    struct page **pagep, void **fsdata)
931ac27a0ecSDave Kleikamp {
932bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
9331938a150SAneesh Kumar K.V 	int ret, needed_blocks;
934ac27a0ecSDave Kleikamp 	handle_t *handle;
935ac27a0ecSDave Kleikamp 	int retries = 0;
936bfc1af65SNick Piggin 	struct page *page;
937bfc1af65SNick Piggin 	pgoff_t index;
938bfc1af65SNick Piggin 	unsigned from, to;
939bfc1af65SNick Piggin 
9409bffad1eSTheodore Ts'o 	trace_ext4_write_begin(inode, pos, len, flags);
9411938a150SAneesh Kumar K.V 	/*
9421938a150SAneesh Kumar K.V 	 * Reserve one block more for addition to orphan list in case
9431938a150SAneesh Kumar K.V 	 * we allocate blocks but write fails for some reason
9441938a150SAneesh Kumar K.V 	 */
9451938a150SAneesh Kumar K.V 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
946bfc1af65SNick Piggin 	index = pos >> PAGE_CACHE_SHIFT;
947bfc1af65SNick Piggin 	from = pos & (PAGE_CACHE_SIZE - 1);
948bfc1af65SNick Piggin 	to = from + len;
949ac27a0ecSDave Kleikamp 
950f19d5870STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
951f19d5870STao Ma 		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
952f19d5870STao Ma 						    flags, pagep);
953f19d5870STao Ma 		if (ret < 0)
95447564bfbSTheodore Ts'o 			return ret;
95547564bfbSTheodore Ts'o 		if (ret == 1)
95647564bfbSTheodore Ts'o 			return 0;
957f19d5870STao Ma 	}
958f19d5870STao Ma 
95947564bfbSTheodore Ts'o 	/*
96047564bfbSTheodore Ts'o 	 * grab_cache_page_write_begin() can take a long time if the
96147564bfbSTheodore Ts'o 	 * system is thrashing due to memory pressure, or if the page
96247564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
96347564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
96447564bfbSTheodore Ts'o 	 * the page (if needed) without using GFP_NOFS.
96547564bfbSTheodore Ts'o 	 */
96647564bfbSTheodore Ts'o retry_grab:
96754566b2cSNick Piggin 	page = grab_cache_page_write_begin(mapping, index, flags);
96847564bfbSTheodore Ts'o 	if (!page)
96947564bfbSTheodore Ts'o 		return -ENOMEM;
97047564bfbSTheodore Ts'o 	unlock_page(page);
97147564bfbSTheodore Ts'o 
97247564bfbSTheodore Ts'o retry_journal:
9739924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
974ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
97547564bfbSTheodore Ts'o 		page_cache_release(page);
97647564bfbSTheodore Ts'o 		return PTR_ERR(handle);
977cf108bcaSJan Kara 	}
978f19d5870STao Ma 
97947564bfbSTheodore Ts'o 	lock_page(page);
98047564bfbSTheodore Ts'o 	if (page->mapping != mapping) {
98147564bfbSTheodore Ts'o 		/* The page got truncated from under us */
98247564bfbSTheodore Ts'o 		unlock_page(page);
98347564bfbSTheodore Ts'o 		page_cache_release(page);
984cf108bcaSJan Kara 		ext4_journal_stop(handle);
98547564bfbSTheodore Ts'o 		goto retry_grab;
986cf108bcaSJan Kara 	}
9877afe5aa5SDmitry Monakhov 	/* In case writeback began while the page was unlocked */
9887afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
989cf108bcaSJan Kara 
990744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
9916e1db88dSChristoph Hellwig 		ret = __block_write_begin(page, pos, len, ext4_get_block_write);
992744692dcSJiaying Zhang 	else
9936e1db88dSChristoph Hellwig 		ret = __block_write_begin(page, pos, len, ext4_get_block);
994bfc1af65SNick Piggin 
995bfc1af65SNick Piggin 	if (!ret && ext4_should_journal_data(inode)) {
996f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_buffers(page),
997f19d5870STao Ma 					     from, to, NULL,
998f19d5870STao Ma 					     do_journal_get_write_access);
999b46be050SAndrey Savochkin 	}
1000bfc1af65SNick Piggin 
1001bfc1af65SNick Piggin 	if (ret) {
1002bfc1af65SNick Piggin 		unlock_page(page);
1003ae4d5372SAneesh Kumar K.V 		/*
10046e1db88dSChristoph Hellwig 		 * __block_write_begin may have instantiated a few blocks
1005ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
1006ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
10071938a150SAneesh Kumar K.V 		 *
10081938a150SAneesh Kumar K.V 		 * Add inode to orphan list in case we crash before
10091938a150SAneesh Kumar K.V 		 * truncate finishes
1010ae4d5372SAneesh Kumar K.V 		 */
1011ffacfa7aSJan Kara 		if (pos + len > inode->i_size && ext4_can_truncate(inode))
10121938a150SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
10131938a150SAneesh Kumar K.V 
10141938a150SAneesh Kumar K.V 		ext4_journal_stop(handle);
10151938a150SAneesh Kumar K.V 		if (pos + len > inode->i_size) {
1016b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
10171938a150SAneesh Kumar K.V 			/*
1018ffacfa7aSJan Kara 			 * If truncate failed early the inode might
10191938a150SAneesh Kumar K.V 			 * still be on the orphan list; we need to
10201938a150SAneesh Kumar K.V 			 * make sure the inode is removed from the
10211938a150SAneesh Kumar K.V 			 * orphan list in that case.
10221938a150SAneesh Kumar K.V 			 */
10231938a150SAneesh Kumar K.V 			if (inode->i_nlink)
10241938a150SAneesh Kumar K.V 				ext4_orphan_del(NULL, inode);
10251938a150SAneesh Kumar K.V 		}
1026bfc1af65SNick Piggin 
102747564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
102847564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
102947564bfbSTheodore Ts'o 			goto retry_journal;
103047564bfbSTheodore Ts'o 		page_cache_release(page);
103147564bfbSTheodore Ts'o 		return ret;
103247564bfbSTheodore Ts'o 	}
103347564bfbSTheodore Ts'o 	*pagep = page;
1034ac27a0ecSDave Kleikamp 	return ret;
1035ac27a0ecSDave Kleikamp }
1036ac27a0ecSDave Kleikamp 
1037bfc1af65SNick Piggin /* For write_end() in data=journal mode */
1038bfc1af65SNick Piggin static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1039ac27a0ecSDave Kleikamp {
104013fca323STheodore Ts'o 	int ret;
1041ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1042ac27a0ecSDave Kleikamp 		return 0;
1043ac27a0ecSDave Kleikamp 	set_buffer_uptodate(bh);
104413fca323STheodore Ts'o 	ret = ext4_handle_dirty_metadata(handle, NULL, bh);
104513fca323STheodore Ts'o 	clear_buffer_meta(bh);
104613fca323STheodore Ts'o 	clear_buffer_prio(bh);
104713fca323STheodore Ts'o 	return ret;
1048ac27a0ecSDave Kleikamp }
1049ac27a0ecSDave Kleikamp 
1050eed4333fSZheng Liu /*
1051eed4333fSZheng Liu  * We need to pick up the new inode size which generic_commit_write gave us
1052eed4333fSZheng Liu  * `file' can be NULL - eg, when called from page_symlink().
1053eed4333fSZheng Liu  *
1054eed4333fSZheng Liu  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1055eed4333fSZheng Liu  * buffers are managed internally.
1056eed4333fSZheng Liu  */
1057eed4333fSZheng Liu static int ext4_write_end(struct file *file,
1058f8514083SAneesh Kumar K.V 			  struct address_space *mapping,
1059f8514083SAneesh Kumar K.V 			  loff_t pos, unsigned len, unsigned copied,
1060f8514083SAneesh Kumar K.V 			  struct page *page, void *fsdata)
1061f8514083SAneesh Kumar K.V {
1062f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
1063eed4333fSZheng Liu 	struct inode *inode = mapping->host;
1064eed4333fSZheng Liu 	int ret = 0, ret2;
1065eed4333fSZheng Liu 	int i_size_changed = 0;
1066eed4333fSZheng Liu 
1067eed4333fSZheng Liu 	trace_ext4_write_end(inode, pos, len, copied);
1068eed4333fSZheng Liu 	if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) {
1069eed4333fSZheng Liu 		ret = ext4_jbd2_file_inode(handle, inode);
1070eed4333fSZheng Liu 		if (ret) {
1071eed4333fSZheng Liu 			unlock_page(page);
1072eed4333fSZheng Liu 			page_cache_release(page);
1073eed4333fSZheng Liu 			goto errout;
1074eed4333fSZheng Liu 		}
1075eed4333fSZheng Liu 	}
1076f8514083SAneesh Kumar K.V 
107742c832deSTheodore Ts'o 	if (ext4_has_inline_data(inode)) {
107842c832deSTheodore Ts'o 		ret = ext4_write_inline_data_end(inode, pos, len,
1079f19d5870STao Ma 						 copied, page);
108042c832deSTheodore Ts'o 		if (ret < 0)
108142c832deSTheodore Ts'o 			goto errout;
108242c832deSTheodore Ts'o 		copied = ret;
108342c832deSTheodore Ts'o 	} else
1084f19d5870STao Ma 		copied = block_write_end(file, mapping, pos,
1085f19d5870STao Ma 					 len, copied, page, fsdata);
1086f8514083SAneesh Kumar K.V 
1087f8514083SAneesh Kumar K.V 	/*
1088f8514083SAneesh Kumar K.V 	 * No need to use i_size_read() here, the i_size
1089eed4333fSZheng Liu 	 * cannot change under us because we hole i_mutex.
1090f8514083SAneesh Kumar K.V 	 *
1091f8514083SAneesh Kumar K.V 	 * But it's important to update i_size while still holding page lock:
1092f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
1093f8514083SAneesh Kumar K.V 	 */
1094f8514083SAneesh Kumar K.V 	if (pos + copied > inode->i_size) {
1095f8514083SAneesh Kumar K.V 		i_size_write(inode, pos + copied);
1096f8514083SAneesh Kumar K.V 		i_size_changed = 1;
1097f8514083SAneesh Kumar K.V 	}
1098f8514083SAneesh Kumar K.V 
1099f8514083SAneesh Kumar K.V 	if (pos + copied > EXT4_I(inode)->i_disksize) {
1100f8514083SAneesh Kumar K.V 		/* We need to mark inode dirty even if
1101f8514083SAneesh Kumar K.V 		 * new_i_size is less that inode->i_size
1102eed4333fSZheng Liu 		 * but greater than i_disksize. (hint delalloc)
1103f8514083SAneesh Kumar K.V 		 */
1104f8514083SAneesh Kumar K.V 		ext4_update_i_disksize(inode, (pos + copied));
1105f8514083SAneesh Kumar K.V 		i_size_changed = 1;
1106f8514083SAneesh Kumar K.V 	}
1107f8514083SAneesh Kumar K.V 	unlock_page(page);
1108f8514083SAneesh Kumar K.V 	page_cache_release(page);
1109f8514083SAneesh Kumar K.V 
1110f8514083SAneesh Kumar K.V 	/*
1111f8514083SAneesh Kumar K.V 	 * Don't mark the inode dirty under page lock. First, it unnecessarily
1112f8514083SAneesh Kumar K.V 	 * makes the holding time of page lock longer. Second, it forces lock
1113f8514083SAneesh Kumar K.V 	 * ordering of page lock and transaction start for journaling
1114f8514083SAneesh Kumar K.V 	 * filesystems.
1115f8514083SAneesh Kumar K.V 	 */
1116f8514083SAneesh Kumar K.V 	if (i_size_changed)
1117f8514083SAneesh Kumar K.V 		ext4_mark_inode_dirty(handle, inode);
1118f8514083SAneesh Kumar K.V 
1119ffacfa7aSJan Kara 	if (pos + len > inode->i_size && ext4_can_truncate(inode))
1120f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1121f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1122f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1123f8514083SAneesh Kumar K.V 		 */
1124f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
112574d553aaSTheodore Ts'o errout:
1126617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1127ac27a0ecSDave Kleikamp 	if (!ret)
1128ac27a0ecSDave Kleikamp 		ret = ret2;
1129bfc1af65SNick Piggin 
1130f8514083SAneesh Kumar K.V 	if (pos + len > inode->i_size) {
1131b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1132f8514083SAneesh Kumar K.V 		/*
1133ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1134f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1135f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1136f8514083SAneesh Kumar K.V 		 */
1137f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1138f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1139f8514083SAneesh Kumar K.V 	}
1140f8514083SAneesh Kumar K.V 
1141bfc1af65SNick Piggin 	return ret ? ret : copied;
1142ac27a0ecSDave Kleikamp }
1143ac27a0ecSDave Kleikamp 
1144bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
1145bfc1af65SNick Piggin 				     struct address_space *mapping,
1146bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
1147bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
1148ac27a0ecSDave Kleikamp {
1149617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1150bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
1151ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1152ac27a0ecSDave Kleikamp 	int partial = 0;
1153bfc1af65SNick Piggin 	unsigned from, to;
1154cf17fea6SAneesh Kumar K.V 	loff_t new_i_size;
1155ac27a0ecSDave Kleikamp 
11569bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
1157bfc1af65SNick Piggin 	from = pos & (PAGE_CACHE_SIZE - 1);
1158bfc1af65SNick Piggin 	to = from + len;
1159bfc1af65SNick Piggin 
1160441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1161441c8508SCurt Wohlgemuth 
11623fdcfb66STao Ma 	if (ext4_has_inline_data(inode))
11633fdcfb66STao Ma 		copied = ext4_write_inline_data_end(inode, pos, len,
11643fdcfb66STao Ma 						    copied, page);
11653fdcfb66STao Ma 	else {
1166bfc1af65SNick Piggin 		if (copied < len) {
1167bfc1af65SNick Piggin 			if (!PageUptodate(page))
1168bfc1af65SNick Piggin 				copied = 0;
1169bfc1af65SNick Piggin 			page_zero_new_buffers(page, from+copied, to);
1170bfc1af65SNick Piggin 		}
1171ac27a0ecSDave Kleikamp 
1172f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1173bfc1af65SNick Piggin 					     to, &partial, write_end_fn);
1174ac27a0ecSDave Kleikamp 		if (!partial)
1175ac27a0ecSDave Kleikamp 			SetPageUptodate(page);
11763fdcfb66STao Ma 	}
1177cf17fea6SAneesh Kumar K.V 	new_i_size = pos + copied;
1178cf17fea6SAneesh Kumar K.V 	if (new_i_size > inode->i_size)
1179bfc1af65SNick Piggin 		i_size_write(inode, pos+copied);
118019f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
11812d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1182cf17fea6SAneesh Kumar K.V 	if (new_i_size > EXT4_I(inode)->i_disksize) {
1183cf17fea6SAneesh Kumar K.V 		ext4_update_i_disksize(inode, new_i_size);
1184617ba13bSMingming Cao 		ret2 = ext4_mark_inode_dirty(handle, inode);
1185ac27a0ecSDave Kleikamp 		if (!ret)
1186ac27a0ecSDave Kleikamp 			ret = ret2;
1187ac27a0ecSDave Kleikamp 	}
1188bfc1af65SNick Piggin 
1189cf108bcaSJan Kara 	unlock_page(page);
1190f8514083SAneesh Kumar K.V 	page_cache_release(page);
1191ffacfa7aSJan Kara 	if (pos + len > inode->i_size && ext4_can_truncate(inode))
1192f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1193f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1194f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1195f8514083SAneesh Kumar K.V 		 */
1196f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1197f8514083SAneesh Kumar K.V 
1198617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1199ac27a0ecSDave Kleikamp 	if (!ret)
1200ac27a0ecSDave Kleikamp 		ret = ret2;
1201f8514083SAneesh Kumar K.V 	if (pos + len > inode->i_size) {
1202b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1203f8514083SAneesh Kumar K.V 		/*
1204ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1205f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1206f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1207f8514083SAneesh Kumar K.V 		 */
1208f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1209f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1210f8514083SAneesh Kumar K.V 	}
1211bfc1af65SNick Piggin 
1212bfc1af65SNick Piggin 	return ret ? ret : copied;
1213ac27a0ecSDave Kleikamp }
1214d2a17637SMingming Cao 
12159d0be502STheodore Ts'o /*
1216386ad67cSLukas Czerner  * Reserve a metadata for a single block located at lblock
1217386ad67cSLukas Czerner  */
1218386ad67cSLukas Czerner static int ext4_da_reserve_metadata(struct inode *inode, ext4_lblk_t lblock)
1219386ad67cSLukas Czerner {
1220386ad67cSLukas Czerner 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1221386ad67cSLukas Czerner 	struct ext4_inode_info *ei = EXT4_I(inode);
1222386ad67cSLukas Czerner 	unsigned int md_needed;
1223386ad67cSLukas Czerner 	ext4_lblk_t save_last_lblock;
1224386ad67cSLukas Czerner 	int save_len;
1225386ad67cSLukas Czerner 
1226386ad67cSLukas Czerner 	/*
1227386ad67cSLukas Czerner 	 * recalculate the amount of metadata blocks to reserve
1228386ad67cSLukas Czerner 	 * in order to allocate nrblocks
1229386ad67cSLukas Czerner 	 * worse case is one extent per block
1230386ad67cSLukas Czerner 	 */
1231386ad67cSLukas Czerner 	spin_lock(&ei->i_block_reservation_lock);
1232386ad67cSLukas Czerner 	/*
1233386ad67cSLukas Czerner 	 * ext4_calc_metadata_amount() has side effects, which we have
1234386ad67cSLukas Czerner 	 * to be prepared undo if we fail to claim space.
1235386ad67cSLukas Czerner 	 */
1236386ad67cSLukas Czerner 	save_len = ei->i_da_metadata_calc_len;
1237386ad67cSLukas Czerner 	save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1238386ad67cSLukas Czerner 	md_needed = EXT4_NUM_B2C(sbi,
1239386ad67cSLukas Czerner 				 ext4_calc_metadata_amount(inode, lblock));
1240386ad67cSLukas Czerner 	trace_ext4_da_reserve_space(inode, md_needed);
1241386ad67cSLukas Czerner 
1242386ad67cSLukas Czerner 	/*
1243386ad67cSLukas Czerner 	 * We do still charge estimated metadata to the sb though;
1244386ad67cSLukas Czerner 	 * we cannot afford to run out of free blocks.
1245386ad67cSLukas Czerner 	 */
1246386ad67cSLukas Czerner 	if (ext4_claim_free_clusters(sbi, md_needed, 0)) {
1247386ad67cSLukas Czerner 		ei->i_da_metadata_calc_len = save_len;
1248386ad67cSLukas Czerner 		ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1249386ad67cSLukas Czerner 		spin_unlock(&ei->i_block_reservation_lock);
1250386ad67cSLukas Czerner 		return -ENOSPC;
1251386ad67cSLukas Czerner 	}
1252386ad67cSLukas Czerner 	ei->i_reserved_meta_blocks += md_needed;
1253386ad67cSLukas Czerner 	spin_unlock(&ei->i_block_reservation_lock);
1254386ad67cSLukas Czerner 
1255386ad67cSLukas Czerner 	return 0;       /* success */
1256386ad67cSLukas Czerner }
1257386ad67cSLukas Czerner 
1258386ad67cSLukas Czerner /*
12597b415bf6SAditya Kali  * Reserve a single cluster located at lblock
12609d0be502STheodore Ts'o  */
126101f49d0bSTheodore Ts'o static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1262d2a17637SMingming Cao {
1263d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
12640637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
12657b415bf6SAditya Kali 	unsigned int md_needed;
12665dd4056dSChristoph Hellwig 	int ret;
126703179fe9STheodore Ts'o 	ext4_lblk_t save_last_lblock;
126803179fe9STheodore Ts'o 	int save_len;
1269d2a17637SMingming Cao 
127060e58e0fSMingming Cao 	/*
127172b8ab9dSEric Sandeen 	 * We will charge metadata quota at writeout time; this saves
127272b8ab9dSEric Sandeen 	 * us from metadata over-estimation, though we may go over by
127372b8ab9dSEric Sandeen 	 * a small amount in the end.  Here we just reserve for data.
127460e58e0fSMingming Cao 	 */
12757b415bf6SAditya Kali 	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
12765dd4056dSChristoph Hellwig 	if (ret)
12775dd4056dSChristoph Hellwig 		return ret;
127803179fe9STheodore Ts'o 
127903179fe9STheodore Ts'o 	/*
128003179fe9STheodore Ts'o 	 * recalculate the amount of metadata blocks to reserve
128103179fe9STheodore Ts'o 	 * in order to allocate nrblocks
128203179fe9STheodore Ts'o 	 * worse case is one extent per block
128303179fe9STheodore Ts'o 	 */
128403179fe9STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
128503179fe9STheodore Ts'o 	/*
128603179fe9STheodore Ts'o 	 * ext4_calc_metadata_amount() has side effects, which we have
128703179fe9STheodore Ts'o 	 * to be prepared undo if we fail to claim space.
128803179fe9STheodore Ts'o 	 */
128903179fe9STheodore Ts'o 	save_len = ei->i_da_metadata_calc_len;
129003179fe9STheodore Ts'o 	save_last_lblock = ei->i_da_metadata_calc_last_lblock;
129103179fe9STheodore Ts'o 	md_needed = EXT4_NUM_B2C(sbi,
129203179fe9STheodore Ts'o 				 ext4_calc_metadata_amount(inode, lblock));
129303179fe9STheodore Ts'o 	trace_ext4_da_reserve_space(inode, md_needed);
129403179fe9STheodore Ts'o 
129572b8ab9dSEric Sandeen 	/*
129672b8ab9dSEric Sandeen 	 * We do still charge estimated metadata to the sb though;
129772b8ab9dSEric Sandeen 	 * we cannot afford to run out of free blocks.
129872b8ab9dSEric Sandeen 	 */
1299e7d5f315STheodore Ts'o 	if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
130003179fe9STheodore Ts'o 		ei->i_da_metadata_calc_len = save_len;
130103179fe9STheodore Ts'o 		ei->i_da_metadata_calc_last_lblock = save_last_lblock;
130203179fe9STheodore Ts'o 		spin_unlock(&ei->i_block_reservation_lock);
130303179fe9STheodore Ts'o 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1304d2a17637SMingming Cao 		return -ENOSPC;
1305d2a17637SMingming Cao 	}
13069d0be502STheodore Ts'o 	ei->i_reserved_data_blocks++;
13070637c6f4STheodore Ts'o 	ei->i_reserved_meta_blocks += md_needed;
13080637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
130939bc680aSDmitry Monakhov 
1310d2a17637SMingming Cao 	return 0;       /* success */
1311d2a17637SMingming Cao }
1312d2a17637SMingming Cao 
131312219aeaSAneesh Kumar K.V static void ext4_da_release_space(struct inode *inode, int to_free)
1314d2a17637SMingming Cao {
1315d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
13160637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1317d2a17637SMingming Cao 
1318cd213226SMingming Cao 	if (!to_free)
1319cd213226SMingming Cao 		return;		/* Nothing to release, exit */
1320cd213226SMingming Cao 
1321d2a17637SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1322cd213226SMingming Cao 
13235a58ec87SLi Zefan 	trace_ext4_da_release_space(inode, to_free);
13240637c6f4STheodore Ts'o 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1325cd213226SMingming Cao 		/*
13260637c6f4STheodore Ts'o 		 * if there aren't enough reserved blocks, then the
13270637c6f4STheodore Ts'o 		 * counter is messed up somewhere.  Since this
13280637c6f4STheodore Ts'o 		 * function is called from invalidate page, it's
13290637c6f4STheodore Ts'o 		 * harmless to return without any action.
1330cd213226SMingming Cao 		 */
13318de5c325STheodore Ts'o 		ext4_warning(inode->i_sb, "ext4_da_release_space: "
13320637c6f4STheodore Ts'o 			 "ino %lu, to_free %d with only %d reserved "
13331084f252STheodore Ts'o 			 "data blocks", inode->i_ino, to_free,
13340637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
13350637c6f4STheodore Ts'o 		WARN_ON(1);
13360637c6f4STheodore Ts'o 		to_free = ei->i_reserved_data_blocks;
13370637c6f4STheodore Ts'o 	}
13380637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= to_free;
13390637c6f4STheodore Ts'o 
13400637c6f4STheodore Ts'o 	if (ei->i_reserved_data_blocks == 0) {
13410637c6f4STheodore Ts'o 		/*
13420637c6f4STheodore Ts'o 		 * We can release all of the reserved metadata blocks
13430637c6f4STheodore Ts'o 		 * only when we have written all of the delayed
13440637c6f4STheodore Ts'o 		 * allocation blocks.
13457b415bf6SAditya Kali 		 * Note that in case of bigalloc, i_reserved_meta_blocks,
13467b415bf6SAditya Kali 		 * i_reserved_data_blocks, etc. refer to number of clusters.
13470637c6f4STheodore Ts'o 		 */
134857042651STheodore Ts'o 		percpu_counter_sub(&sbi->s_dirtyclusters_counter,
134972b8ab9dSEric Sandeen 				   ei->i_reserved_meta_blocks);
1350ee5f4d9cSTheodore Ts'o 		ei->i_reserved_meta_blocks = 0;
13519d0be502STheodore Ts'o 		ei->i_da_metadata_calc_len = 0;
1352cd213226SMingming Cao 	}
1353cd213226SMingming Cao 
135472b8ab9dSEric Sandeen 	/* update fs dirty data blocks counter */
135557042651STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1356d2a17637SMingming Cao 
1357d2a17637SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
135860e58e0fSMingming Cao 
13597b415bf6SAditya Kali 	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1360d2a17637SMingming Cao }
1361d2a17637SMingming Cao 
1362d2a17637SMingming Cao static void ext4_da_page_release_reservation(struct page *page,
1363ca99fdd2SLukas Czerner 					     unsigned int offset,
1364ca99fdd2SLukas Czerner 					     unsigned int length)
1365d2a17637SMingming Cao {
1366d2a17637SMingming Cao 	int to_release = 0;
1367d2a17637SMingming Cao 	struct buffer_head *head, *bh;
1368d2a17637SMingming Cao 	unsigned int curr_off = 0;
13697b415bf6SAditya Kali 	struct inode *inode = page->mapping->host;
13707b415bf6SAditya Kali 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1371ca99fdd2SLukas Czerner 	unsigned int stop = offset + length;
13727b415bf6SAditya Kali 	int num_clusters;
137351865fdaSZheng Liu 	ext4_fsblk_t lblk;
1374d2a17637SMingming Cao 
1375ca99fdd2SLukas Czerner 	BUG_ON(stop > PAGE_CACHE_SIZE || stop < length);
1376ca99fdd2SLukas Czerner 
1377d2a17637SMingming Cao 	head = page_buffers(page);
1378d2a17637SMingming Cao 	bh = head;
1379d2a17637SMingming Cao 	do {
1380d2a17637SMingming Cao 		unsigned int next_off = curr_off + bh->b_size;
1381d2a17637SMingming Cao 
1382ca99fdd2SLukas Czerner 		if (next_off > stop)
1383ca99fdd2SLukas Czerner 			break;
1384ca99fdd2SLukas Czerner 
1385d2a17637SMingming Cao 		if ((offset <= curr_off) && (buffer_delay(bh))) {
1386d2a17637SMingming Cao 			to_release++;
1387d2a17637SMingming Cao 			clear_buffer_delay(bh);
1388d2a17637SMingming Cao 		}
1389d2a17637SMingming Cao 		curr_off = next_off;
1390d2a17637SMingming Cao 	} while ((bh = bh->b_this_page) != head);
13917b415bf6SAditya Kali 
139251865fdaSZheng Liu 	if (to_release) {
139351865fdaSZheng Liu 		lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
139451865fdaSZheng Liu 		ext4_es_remove_extent(inode, lblk, to_release);
139551865fdaSZheng Liu 	}
139651865fdaSZheng Liu 
13977b415bf6SAditya Kali 	/* If we have released all the blocks belonging to a cluster, then we
13987b415bf6SAditya Kali 	 * need to release the reserved space for that cluster. */
13997b415bf6SAditya Kali 	num_clusters = EXT4_NUM_B2C(sbi, to_release);
14007b415bf6SAditya Kali 	while (num_clusters > 0) {
14017b415bf6SAditya Kali 		lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
14027b415bf6SAditya Kali 			((num_clusters - 1) << sbi->s_cluster_bits);
14037b415bf6SAditya Kali 		if (sbi->s_cluster_ratio == 1 ||
14047d1b1fbcSZheng Liu 		    !ext4_find_delalloc_cluster(inode, lblk))
14057b415bf6SAditya Kali 			ext4_da_release_space(inode, 1);
14067b415bf6SAditya Kali 
14077b415bf6SAditya Kali 		num_clusters--;
14087b415bf6SAditya Kali 	}
1409d2a17637SMingming Cao }
1410ac27a0ecSDave Kleikamp 
1411ac27a0ecSDave Kleikamp /*
141264769240SAlex Tomas  * Delayed allocation stuff
141364769240SAlex Tomas  */
141464769240SAlex Tomas 
14154e7ea81dSJan Kara struct mpage_da_data {
14164e7ea81dSJan Kara 	struct inode *inode;
14174e7ea81dSJan Kara 	struct writeback_control *wbc;
14186b523df4SJan Kara 
14194e7ea81dSJan Kara 	pgoff_t first_page;	/* The first page to write */
14204e7ea81dSJan Kara 	pgoff_t next_page;	/* Current page to examine */
14214e7ea81dSJan Kara 	pgoff_t last_page;	/* Last page to examine */
142264769240SAlex Tomas 	/*
14234e7ea81dSJan Kara 	 * Extent to map - this can be after first_page because that can be
14244e7ea81dSJan Kara 	 * fully mapped. We somewhat abuse m_flags to store whether the extent
14254e7ea81dSJan Kara 	 * is delalloc or unwritten.
142664769240SAlex Tomas 	 */
14274e7ea81dSJan Kara 	struct ext4_map_blocks map;
14284e7ea81dSJan Kara 	struct ext4_io_submit io_submit;	/* IO submission data */
14294e7ea81dSJan Kara };
143064769240SAlex Tomas 
14314e7ea81dSJan Kara static void mpage_release_unused_pages(struct mpage_da_data *mpd,
14324e7ea81dSJan Kara 				       bool invalidate)
1433c4a0c46eSAneesh Kumar K.V {
1434c4a0c46eSAneesh Kumar K.V 	int nr_pages, i;
1435c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
1436c4a0c46eSAneesh Kumar K.V 	struct pagevec pvec;
1437c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1438c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
14394e7ea81dSJan Kara 
14404e7ea81dSJan Kara 	/* This is necessary when next_page == 0. */
14414e7ea81dSJan Kara 	if (mpd->first_page >= mpd->next_page)
14424e7ea81dSJan Kara 		return;
1443c4a0c46eSAneesh Kumar K.V 
1444c7f5938aSCurt Wohlgemuth 	index = mpd->first_page;
1445c7f5938aSCurt Wohlgemuth 	end   = mpd->next_page - 1;
14464e7ea81dSJan Kara 	if (invalidate) {
14474e7ea81dSJan Kara 		ext4_lblk_t start, last;
144851865fdaSZheng Liu 		start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
144951865fdaSZheng Liu 		last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
145051865fdaSZheng Liu 		ext4_es_remove_extent(inode, start, last - start + 1);
14514e7ea81dSJan Kara 	}
145251865fdaSZheng Liu 
145366bea92cSEric Sandeen 	pagevec_init(&pvec, 0);
1454c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
1455c4a0c46eSAneesh Kumar K.V 		nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1456c4a0c46eSAneesh Kumar K.V 		if (nr_pages == 0)
1457c4a0c46eSAneesh Kumar K.V 			break;
1458c4a0c46eSAneesh Kumar K.V 		for (i = 0; i < nr_pages; i++) {
1459c4a0c46eSAneesh Kumar K.V 			struct page *page = pvec.pages[i];
14609b1d0998SJan Kara 			if (page->index > end)
1461c4a0c46eSAneesh Kumar K.V 				break;
1462c4a0c46eSAneesh Kumar K.V 			BUG_ON(!PageLocked(page));
1463c4a0c46eSAneesh Kumar K.V 			BUG_ON(PageWriteback(page));
14644e7ea81dSJan Kara 			if (invalidate) {
1465d47992f8SLukas Czerner 				block_invalidatepage(page, 0, PAGE_CACHE_SIZE);
1466c4a0c46eSAneesh Kumar K.V 				ClearPageUptodate(page);
14674e7ea81dSJan Kara 			}
1468c4a0c46eSAneesh Kumar K.V 			unlock_page(page);
1469c4a0c46eSAneesh Kumar K.V 		}
14709b1d0998SJan Kara 		index = pvec.pages[nr_pages - 1]->index + 1;
14719b1d0998SJan Kara 		pagevec_release(&pvec);
1472c4a0c46eSAneesh Kumar K.V 	}
1473c4a0c46eSAneesh Kumar K.V }
1474c4a0c46eSAneesh Kumar K.V 
1475df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
1476df22291fSAneesh Kumar K.V {
1477df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
147892b97816STheodore Ts'o 	struct super_block *sb = inode->i_sb;
1479f78ee70dSLukas Czerner 	struct ext4_inode_info *ei = EXT4_I(inode);
148092b97816STheodore Ts'o 
148192b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
14825dee5437STheodore Ts'o 	       EXT4_C2B(EXT4_SB(inode->i_sb),
1483f78ee70dSLukas Czerner 			ext4_count_free_clusters(sb)));
148492b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
148592b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1486f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
148757042651STheodore Ts'o 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
148892b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1489f78ee70dSLukas Czerner 	       (long long) EXT4_C2B(EXT4_SB(sb),
14907b415bf6SAditya Kali 		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
149192b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "Block reservation details");
149292b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1493f78ee70dSLukas Czerner 		 ei->i_reserved_data_blocks);
149492b97816STheodore Ts'o 	ext4_msg(sb, KERN_CRIT, "i_reserved_meta_blocks=%u",
1495f78ee70dSLukas Czerner 	       ei->i_reserved_meta_blocks);
1496f78ee70dSLukas Czerner 	ext4_msg(sb, KERN_CRIT, "i_allocated_meta_blocks=%u",
1497f78ee70dSLukas Czerner 	       ei->i_allocated_meta_blocks);
1498df22291fSAneesh Kumar K.V 	return;
1499df22291fSAneesh Kumar K.V }
1500df22291fSAneesh Kumar K.V 
1501c364b22cSAneesh Kumar K.V static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
150229fa89d0SAneesh Kumar K.V {
1503c364b22cSAneesh Kumar K.V 	return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
150429fa89d0SAneesh Kumar K.V }
150529fa89d0SAneesh Kumar K.V 
150664769240SAlex Tomas /*
15075356f261SAditya Kali  * This function is grabs code from the very beginning of
15085356f261SAditya Kali  * ext4_map_blocks, but assumes that the caller is from delayed write
15095356f261SAditya Kali  * time. This function looks up the requested blocks and sets the
15105356f261SAditya Kali  * buffer delay bit under the protection of i_data_sem.
15115356f261SAditya Kali  */
15125356f261SAditya Kali static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
15135356f261SAditya Kali 			      struct ext4_map_blocks *map,
15145356f261SAditya Kali 			      struct buffer_head *bh)
15155356f261SAditya Kali {
1516d100eef2SZheng Liu 	struct extent_status es;
15175356f261SAditya Kali 	int retval;
15185356f261SAditya Kali 	sector_t invalid_block = ~((sector_t) 0xffff);
1519921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1520921f266bSDmitry Monakhov 	struct ext4_map_blocks orig_map;
1521921f266bSDmitry Monakhov 
1522921f266bSDmitry Monakhov 	memcpy(&orig_map, map, sizeof(*map));
1523921f266bSDmitry Monakhov #endif
15245356f261SAditya Kali 
15255356f261SAditya Kali 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
15265356f261SAditya Kali 		invalid_block = ~0;
15275356f261SAditya Kali 
15285356f261SAditya Kali 	map->m_flags = 0;
15295356f261SAditya Kali 	ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
15305356f261SAditya Kali 		  "logical block %lu\n", inode->i_ino, map->m_len,
15315356f261SAditya Kali 		  (unsigned long) map->m_lblk);
1532d100eef2SZheng Liu 
1533d100eef2SZheng Liu 	/* Lookup extent status tree firstly */
1534d100eef2SZheng Liu 	if (ext4_es_lookup_extent(inode, iblock, &es)) {
153563b99968STheodore Ts'o 		ext4_es_lru_add(inode);
1536d100eef2SZheng Liu 		if (ext4_es_is_hole(&es)) {
1537d100eef2SZheng Liu 			retval = 0;
1538d100eef2SZheng Liu 			down_read((&EXT4_I(inode)->i_data_sem));
1539d100eef2SZheng Liu 			goto add_delayed;
1540d100eef2SZheng Liu 		}
1541d100eef2SZheng Liu 
1542d100eef2SZheng Liu 		/*
1543d100eef2SZheng Liu 		 * Delayed extent could be allocated by fallocate.
1544d100eef2SZheng Liu 		 * So we need to check it.
1545d100eef2SZheng Liu 		 */
1546d100eef2SZheng Liu 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1547d100eef2SZheng Liu 			map_bh(bh, inode->i_sb, invalid_block);
1548d100eef2SZheng Liu 			set_buffer_new(bh);
1549d100eef2SZheng Liu 			set_buffer_delay(bh);
1550d100eef2SZheng Liu 			return 0;
1551d100eef2SZheng Liu 		}
1552d100eef2SZheng Liu 
1553d100eef2SZheng Liu 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1554d100eef2SZheng Liu 		retval = es.es_len - (iblock - es.es_lblk);
1555d100eef2SZheng Liu 		if (retval > map->m_len)
1556d100eef2SZheng Liu 			retval = map->m_len;
1557d100eef2SZheng Liu 		map->m_len = retval;
1558d100eef2SZheng Liu 		if (ext4_es_is_written(&es))
1559d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_MAPPED;
1560d100eef2SZheng Liu 		else if (ext4_es_is_unwritten(&es))
1561d100eef2SZheng Liu 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1562d100eef2SZheng Liu 		else
1563d100eef2SZheng Liu 			BUG_ON(1);
1564d100eef2SZheng Liu 
1565921f266bSDmitry Monakhov #ifdef ES_AGGRESSIVE_TEST
1566921f266bSDmitry Monakhov 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1567921f266bSDmitry Monakhov #endif
1568d100eef2SZheng Liu 		return retval;
1569d100eef2SZheng Liu 	}
1570d100eef2SZheng Liu 
15715356f261SAditya Kali 	/*
15725356f261SAditya Kali 	 * Try to see if we can get the block without requesting a new
15735356f261SAditya Kali 	 * file system block.
15745356f261SAditya Kali 	 */
15755356f261SAditya Kali 	down_read((&EXT4_I(inode)->i_data_sem));
15769c3569b5STao Ma 	if (ext4_has_inline_data(inode)) {
15779c3569b5STao Ma 		/*
15789c3569b5STao Ma 		 * We will soon create blocks for this page, and let
15799c3569b5STao Ma 		 * us pretend as if the blocks aren't allocated yet.
15809c3569b5STao Ma 		 * In case of clusters, we have to handle the work
15819c3569b5STao Ma 		 * of mapping from cluster so that the reserved space
15829c3569b5STao Ma 		 * is calculated properly.
15839c3569b5STao Ma 		 */
15849c3569b5STao Ma 		if ((EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) &&
15859c3569b5STao Ma 		    ext4_find_delalloc_cluster(inode, map->m_lblk))
15869c3569b5STao Ma 			map->m_flags |= EXT4_MAP_FROM_CLUSTER;
15879c3569b5STao Ma 		retval = 0;
15889c3569b5STao Ma 	} else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1589d100eef2SZheng Liu 		retval = ext4_ext_map_blocks(NULL, inode, map,
1590d100eef2SZheng Liu 					     EXT4_GET_BLOCKS_NO_PUT_HOLE);
15915356f261SAditya Kali 	else
1592d100eef2SZheng Liu 		retval = ext4_ind_map_blocks(NULL, inode, map,
1593d100eef2SZheng Liu 					     EXT4_GET_BLOCKS_NO_PUT_HOLE);
15945356f261SAditya Kali 
1595d100eef2SZheng Liu add_delayed:
15965356f261SAditya Kali 	if (retval == 0) {
1597f7fec032SZheng Liu 		int ret;
15985356f261SAditya Kali 		/*
15995356f261SAditya Kali 		 * XXX: __block_prepare_write() unmaps passed block,
16005356f261SAditya Kali 		 * is it OK?
16015356f261SAditya Kali 		 */
1602386ad67cSLukas Czerner 		/*
1603386ad67cSLukas Czerner 		 * If the block was allocated from previously allocated cluster,
1604386ad67cSLukas Czerner 		 * then we don't need to reserve it again. However we still need
1605386ad67cSLukas Czerner 		 * to reserve metadata for every block we're going to write.
1606386ad67cSLukas Czerner 		 */
16075356f261SAditya Kali 		if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1608f7fec032SZheng Liu 			ret = ext4_da_reserve_space(inode, iblock);
1609f7fec032SZheng Liu 			if (ret) {
16105356f261SAditya Kali 				/* not enough space to reserve */
1611f7fec032SZheng Liu 				retval = ret;
16125356f261SAditya Kali 				goto out_unlock;
16135356f261SAditya Kali 			}
1614386ad67cSLukas Czerner 		} else {
1615386ad67cSLukas Czerner 			ret = ext4_da_reserve_metadata(inode, iblock);
1616386ad67cSLukas Czerner 			if (ret) {
1617386ad67cSLukas Czerner 				/* not enough space to reserve */
1618386ad67cSLukas Czerner 				retval = ret;
1619386ad67cSLukas Czerner 				goto out_unlock;
1620386ad67cSLukas Czerner 			}
1621f7fec032SZheng Liu 		}
16225356f261SAditya Kali 
1623f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1624fdc0212eSZheng Liu 					    ~0, EXTENT_STATUS_DELAYED);
1625f7fec032SZheng Liu 		if (ret) {
1626f7fec032SZheng Liu 			retval = ret;
162751865fdaSZheng Liu 			goto out_unlock;
1628f7fec032SZheng Liu 		}
162951865fdaSZheng Liu 
16305356f261SAditya Kali 		/* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
16315356f261SAditya Kali 		 * and it should not appear on the bh->b_state.
16325356f261SAditya Kali 		 */
16335356f261SAditya Kali 		map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
16345356f261SAditya Kali 
16355356f261SAditya Kali 		map_bh(bh, inode->i_sb, invalid_block);
16365356f261SAditya Kali 		set_buffer_new(bh);
16375356f261SAditya Kali 		set_buffer_delay(bh);
1638f7fec032SZheng Liu 	} else if (retval > 0) {
1639f7fec032SZheng Liu 		int ret;
16403be78c73STheodore Ts'o 		unsigned int status;
1641f7fec032SZheng Liu 
164244fb851dSZheng Liu 		if (unlikely(retval != map->m_len)) {
164344fb851dSZheng Liu 			ext4_warning(inode->i_sb,
164444fb851dSZheng Liu 				     "ES len assertion failed for inode "
164544fb851dSZheng Liu 				     "%lu: retval %d != map->m_len %d",
164644fb851dSZheng Liu 				     inode->i_ino, retval, map->m_len);
164744fb851dSZheng Liu 			WARN_ON(1);
1648921f266bSDmitry Monakhov 		}
1649921f266bSDmitry Monakhov 
1650f7fec032SZheng Liu 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1651f7fec032SZheng Liu 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1652f7fec032SZheng Liu 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1653f7fec032SZheng Liu 					    map->m_pblk, status);
1654f7fec032SZheng Liu 		if (ret != 0)
1655f7fec032SZheng Liu 			retval = ret;
16565356f261SAditya Kali 	}
16575356f261SAditya Kali 
16585356f261SAditya Kali out_unlock:
16595356f261SAditya Kali 	up_read((&EXT4_I(inode)->i_data_sem));
16605356f261SAditya Kali 
16615356f261SAditya Kali 	return retval;
16625356f261SAditya Kali }
16635356f261SAditya Kali 
16645356f261SAditya Kali /*
1665b920c755STheodore Ts'o  * This is a special get_blocks_t callback which is used by
1666b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
1667b920c755STheodore Ts'o  * reserve space for a single block.
166829fa89d0SAneesh Kumar K.V  *
166929fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
167029fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
167129fa89d0SAneesh Kumar K.V  *
167229fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
167329fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
167429fa89d0SAneesh Kumar K.V  * initialized properly.
167564769240SAlex Tomas  */
16769c3569b5STao Ma int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
16772ed88685STheodore Ts'o 			   struct buffer_head *bh, int create)
167864769240SAlex Tomas {
16792ed88685STheodore Ts'o 	struct ext4_map_blocks map;
168064769240SAlex Tomas 	int ret = 0;
168164769240SAlex Tomas 
168264769240SAlex Tomas 	BUG_ON(create == 0);
16832ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
16842ed88685STheodore Ts'o 
16852ed88685STheodore Ts'o 	map.m_lblk = iblock;
16862ed88685STheodore Ts'o 	map.m_len = 1;
168764769240SAlex Tomas 
168864769240SAlex Tomas 	/*
168964769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
169064769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
169164769240SAlex Tomas 	 * the same as allocated blocks.
169264769240SAlex Tomas 	 */
16935356f261SAditya Kali 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
16945356f261SAditya Kali 	if (ret <= 0)
16952ed88685STheodore Ts'o 		return ret;
169664769240SAlex Tomas 
16972ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
16982ed88685STheodore Ts'o 	bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
16992ed88685STheodore Ts'o 
17002ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
17012ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
17022ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
17032ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
17042ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
17052ed88685STheodore Ts'o 		 * for partial write.
17062ed88685STheodore Ts'o 		 */
17072ed88685STheodore Ts'o 		set_buffer_new(bh);
1708c8205636STheodore Ts'o 		set_buffer_mapped(bh);
17092ed88685STheodore Ts'o 	}
17102ed88685STheodore Ts'o 	return 0;
171164769240SAlex Tomas }
171261628a3fSMingming Cao 
171362e086beSAneesh Kumar K.V static int bget_one(handle_t *handle, struct buffer_head *bh)
171462e086beSAneesh Kumar K.V {
171562e086beSAneesh Kumar K.V 	get_bh(bh);
171662e086beSAneesh Kumar K.V 	return 0;
171762e086beSAneesh Kumar K.V }
171862e086beSAneesh Kumar K.V 
171962e086beSAneesh Kumar K.V static int bput_one(handle_t *handle, struct buffer_head *bh)
172062e086beSAneesh Kumar K.V {
172162e086beSAneesh Kumar K.V 	put_bh(bh);
172262e086beSAneesh Kumar K.V 	return 0;
172362e086beSAneesh Kumar K.V }
172462e086beSAneesh Kumar K.V 
172562e086beSAneesh Kumar K.V static int __ext4_journalled_writepage(struct page *page,
172662e086beSAneesh Kumar K.V 				       unsigned int len)
172762e086beSAneesh Kumar K.V {
172862e086beSAneesh Kumar K.V 	struct address_space *mapping = page->mapping;
172962e086beSAneesh Kumar K.V 	struct inode *inode = mapping->host;
17303fdcfb66STao Ma 	struct buffer_head *page_bufs = NULL;
173162e086beSAneesh Kumar K.V 	handle_t *handle = NULL;
17323fdcfb66STao Ma 	int ret = 0, err = 0;
17333fdcfb66STao Ma 	int inline_data = ext4_has_inline_data(inode);
17343fdcfb66STao Ma 	struct buffer_head *inode_bh = NULL;
173562e086beSAneesh Kumar K.V 
1736cb20d518STheodore Ts'o 	ClearPageChecked(page);
17373fdcfb66STao Ma 
17383fdcfb66STao Ma 	if (inline_data) {
17393fdcfb66STao Ma 		BUG_ON(page->index != 0);
17403fdcfb66STao Ma 		BUG_ON(len > ext4_get_max_inline_size(inode));
17413fdcfb66STao Ma 		inode_bh = ext4_journalled_write_inline_data(inode, len, page);
17423fdcfb66STao Ma 		if (inode_bh == NULL)
17433fdcfb66STao Ma 			goto out;
17443fdcfb66STao Ma 	} else {
174562e086beSAneesh Kumar K.V 		page_bufs = page_buffers(page);
17463fdcfb66STao Ma 		if (!page_bufs) {
17473fdcfb66STao Ma 			BUG();
17483fdcfb66STao Ma 			goto out;
17493fdcfb66STao Ma 		}
17503fdcfb66STao Ma 		ext4_walk_page_buffers(handle, page_bufs, 0, len,
17513fdcfb66STao Ma 				       NULL, bget_one);
17523fdcfb66STao Ma 	}
175362e086beSAneesh Kumar K.V 	/* As soon as we unlock the page, it can go away, but we have
175462e086beSAneesh Kumar K.V 	 * references to buffers so we are safe */
175562e086beSAneesh Kumar K.V 	unlock_page(page);
175662e086beSAneesh Kumar K.V 
17579924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
17589924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
175962e086beSAneesh Kumar K.V 	if (IS_ERR(handle)) {
176062e086beSAneesh Kumar K.V 		ret = PTR_ERR(handle);
176162e086beSAneesh Kumar K.V 		goto out;
176262e086beSAneesh Kumar K.V 	}
176362e086beSAneesh Kumar K.V 
1764441c8508SCurt Wohlgemuth 	BUG_ON(!ext4_handle_valid(handle));
1765441c8508SCurt Wohlgemuth 
17663fdcfb66STao Ma 	if (inline_data) {
17673fdcfb66STao Ma 		ret = ext4_journal_get_write_access(handle, inode_bh);
17683fdcfb66STao Ma 
17693fdcfb66STao Ma 		err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
17703fdcfb66STao Ma 
17713fdcfb66STao Ma 	} else {
1772f19d5870STao Ma 		ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
177362e086beSAneesh Kumar K.V 					     do_journal_get_write_access);
177462e086beSAneesh Kumar K.V 
1775f19d5870STao Ma 		err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
177662e086beSAneesh Kumar K.V 					     write_end_fn);
17773fdcfb66STao Ma 	}
177862e086beSAneesh Kumar K.V 	if (ret == 0)
177962e086beSAneesh Kumar K.V 		ret = err;
17802d859db3SJan Kara 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
178162e086beSAneesh Kumar K.V 	err = ext4_journal_stop(handle);
178262e086beSAneesh Kumar K.V 	if (!ret)
178362e086beSAneesh Kumar K.V 		ret = err;
178462e086beSAneesh Kumar K.V 
17853fdcfb66STao Ma 	if (!ext4_has_inline_data(inode))
17868c9367fdSTheodore Ts'o 		ext4_walk_page_buffers(NULL, page_bufs, 0, len,
17873fdcfb66STao Ma 				       NULL, bput_one);
178819f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
178962e086beSAneesh Kumar K.V out:
17903fdcfb66STao Ma 	brelse(inode_bh);
179162e086beSAneesh Kumar K.V 	return ret;
179262e086beSAneesh Kumar K.V }
179362e086beSAneesh Kumar K.V 
179461628a3fSMingming Cao /*
179543ce1d23SAneesh Kumar K.V  * Note that we don't need to start a transaction unless we're journaling data
179643ce1d23SAneesh Kumar K.V  * because we should have holes filled from ext4_page_mkwrite(). We even don't
179743ce1d23SAneesh Kumar K.V  * need to file the inode to the transaction's list in ordered mode because if
179843ce1d23SAneesh Kumar K.V  * we are writing back data added by write(), the inode is already there and if
179943ce1d23SAneesh Kumar K.V  * we are writing back data modified via mmap(), no one guarantees in which
180043ce1d23SAneesh Kumar K.V  * transaction the data will hit the disk. In case we are journaling data, we
180143ce1d23SAneesh Kumar K.V  * cannot start transaction directly because transaction start ranks above page
180243ce1d23SAneesh Kumar K.V  * lock so we have to do some magic.
180343ce1d23SAneesh Kumar K.V  *
1804b920c755STheodore Ts'o  * This function can get called via...
180520970ba6STheodore Ts'o  *   - ext4_writepages after taking page lock (have journal handle)
1806b920c755STheodore Ts'o  *   - journal_submit_inode_data_buffers (no journal handle)
1807f6463b0dSArtem Bityutskiy  *   - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1808b920c755STheodore Ts'o  *   - grab_page_cache when doing write_begin (have journal handle)
180943ce1d23SAneesh Kumar K.V  *
181043ce1d23SAneesh Kumar K.V  * We don't do any block allocation in this function. If we have page with
181143ce1d23SAneesh Kumar K.V  * multiple blocks we need to write those buffer_heads that are mapped. This
181243ce1d23SAneesh Kumar K.V  * is important for mmaped based write. So if we do with blocksize 1K
181343ce1d23SAneesh Kumar K.V  * truncate(f, 1024);
181443ce1d23SAneesh Kumar K.V  * a = mmap(f, 0, 4096);
181543ce1d23SAneesh Kumar K.V  * a[0] = 'a';
181643ce1d23SAneesh Kumar K.V  * truncate(f, 4096);
181743ce1d23SAneesh Kumar K.V  * we have in the page first buffer_head mapped via page_mkwrite call back
181890802ed9SPaul Bolle  * but other buffer_heads would be unmapped but dirty (dirty done via the
181943ce1d23SAneesh Kumar K.V  * do_wp_page). So writepage should write the first block. If we modify
182043ce1d23SAneesh Kumar K.V  * the mmap area beyond 1024 we will again get a page_fault and the
182143ce1d23SAneesh Kumar K.V  * page_mkwrite callback will do the block allocation and mark the
182243ce1d23SAneesh Kumar K.V  * buffer_heads mapped.
182343ce1d23SAneesh Kumar K.V  *
182443ce1d23SAneesh Kumar K.V  * We redirty the page if we have any buffer_heads that is either delay or
182543ce1d23SAneesh Kumar K.V  * unwritten in the page.
182643ce1d23SAneesh Kumar K.V  *
182743ce1d23SAneesh Kumar K.V  * We can get recursively called as show below.
182843ce1d23SAneesh Kumar K.V  *
182943ce1d23SAneesh Kumar K.V  *	ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
183043ce1d23SAneesh Kumar K.V  *		ext4_writepage()
183143ce1d23SAneesh Kumar K.V  *
183243ce1d23SAneesh Kumar K.V  * But since we don't do any block allocation we should not deadlock.
183343ce1d23SAneesh Kumar K.V  * Page also have the dirty flag cleared so we don't get recurive page_lock.
183461628a3fSMingming Cao  */
183543ce1d23SAneesh Kumar K.V static int ext4_writepage(struct page *page,
183664769240SAlex Tomas 			  struct writeback_control *wbc)
183764769240SAlex Tomas {
1838f8bec370SJan Kara 	int ret = 0;
183961628a3fSMingming Cao 	loff_t size;
1840498e5f24STheodore Ts'o 	unsigned int len;
1841744692dcSJiaying Zhang 	struct buffer_head *page_bufs = NULL;
184261628a3fSMingming Cao 	struct inode *inode = page->mapping->host;
184336ade451SJan Kara 	struct ext4_io_submit io_submit;
184464769240SAlex Tomas 
1845a9c667f8SLukas Czerner 	trace_ext4_writepage(page);
184661628a3fSMingming Cao 	size = i_size_read(inode);
184761628a3fSMingming Cao 	if (page->index == size >> PAGE_CACHE_SHIFT)
184861628a3fSMingming Cao 		len = size & ~PAGE_CACHE_MASK;
184961628a3fSMingming Cao 	else
185061628a3fSMingming Cao 		len = PAGE_CACHE_SIZE;
185161628a3fSMingming Cao 
1852f0e6c985SAneesh Kumar K.V 	page_bufs = page_buffers(page);
185364769240SAlex Tomas 	/*
1854fe386132SJan Kara 	 * We cannot do block allocation or other extent handling in this
1855fe386132SJan Kara 	 * function. If there are buffers needing that, we have to redirty
1856fe386132SJan Kara 	 * the page. But we may reach here when we do a journal commit via
1857fe386132SJan Kara 	 * journal_submit_inode_data_buffers() and in that case we must write
1858fe386132SJan Kara 	 * allocated buffers to achieve data=ordered mode guarantees.
185964769240SAlex Tomas 	 */
1860f19d5870STao Ma 	if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1861c364b22cSAneesh Kumar K.V 				   ext4_bh_delay_or_unwritten)) {
186261628a3fSMingming Cao 		redirty_page_for_writepage(wbc, page);
1863fe386132SJan Kara 		if (current->flags & PF_MEMALLOC) {
1864fe386132SJan Kara 			/*
1865fe386132SJan Kara 			 * For memory cleaning there's no point in writing only
1866fe386132SJan Kara 			 * some buffers. So just bail out. Warn if we came here
1867fe386132SJan Kara 			 * from direct reclaim.
1868fe386132SJan Kara 			 */
1869fe386132SJan Kara 			WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
1870fe386132SJan Kara 							== PF_MEMALLOC);
187161628a3fSMingming Cao 			unlock_page(page);
187261628a3fSMingming Cao 			return 0;
187361628a3fSMingming Cao 		}
1874f0e6c985SAneesh Kumar K.V 	}
187564769240SAlex Tomas 
1876cb20d518STheodore Ts'o 	if (PageChecked(page) && ext4_should_journal_data(inode))
187743ce1d23SAneesh Kumar K.V 		/*
187843ce1d23SAneesh Kumar K.V 		 * It's mmapped pagecache.  Add buffers and journal it.  There
187943ce1d23SAneesh Kumar K.V 		 * doesn't seem much point in redirtying the page here.
188043ce1d23SAneesh Kumar K.V 		 */
18813f0ca309SWu Fengguang 		return __ext4_journalled_writepage(page, len);
188243ce1d23SAneesh Kumar K.V 
188397a851edSJan Kara 	ext4_io_submit_init(&io_submit, wbc);
188497a851edSJan Kara 	io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
188597a851edSJan Kara 	if (!io_submit.io_end) {
188697a851edSJan Kara 		redirty_page_for_writepage(wbc, page);
188797a851edSJan Kara 		unlock_page(page);
188897a851edSJan Kara 		return -ENOMEM;
188997a851edSJan Kara 	}
189036ade451SJan Kara 	ret = ext4_bio_write_page(&io_submit, page, len, wbc);
189136ade451SJan Kara 	ext4_io_submit(&io_submit);
189297a851edSJan Kara 	/* Drop io_end reference we got from init */
189397a851edSJan Kara 	ext4_put_io_end_defer(io_submit.io_end);
189464769240SAlex Tomas 	return ret;
189564769240SAlex Tomas }
189664769240SAlex Tomas 
18975f1132b2SJan Kara static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
18985f1132b2SJan Kara {
18995f1132b2SJan Kara 	int len;
19005f1132b2SJan Kara 	loff_t size = i_size_read(mpd->inode);
19015f1132b2SJan Kara 	int err;
19025f1132b2SJan Kara 
19035f1132b2SJan Kara 	BUG_ON(page->index != mpd->first_page);
19045f1132b2SJan Kara 	if (page->index == size >> PAGE_CACHE_SHIFT)
19055f1132b2SJan Kara 		len = size & ~PAGE_CACHE_MASK;
19065f1132b2SJan Kara 	else
19075f1132b2SJan Kara 		len = PAGE_CACHE_SIZE;
19085f1132b2SJan Kara 	clear_page_dirty_for_io(page);
19095f1132b2SJan Kara 	err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc);
19105f1132b2SJan Kara 	if (!err)
19115f1132b2SJan Kara 		mpd->wbc->nr_to_write--;
19125f1132b2SJan Kara 	mpd->first_page++;
19135f1132b2SJan Kara 
19145f1132b2SJan Kara 	return err;
19155f1132b2SJan Kara }
19165f1132b2SJan Kara 
19174e7ea81dSJan Kara #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
19184e7ea81dSJan Kara 
191961628a3fSMingming Cao /*
1920fffb2739SJan Kara  * mballoc gives us at most this number of blocks...
1921fffb2739SJan Kara  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1922fffb2739SJan Kara  * The rest of mballoc seems to handle chunks up to full group size.
192361628a3fSMingming Cao  */
1924fffb2739SJan Kara #define MAX_WRITEPAGES_EXTENT_LEN 2048
1925525f4ed8SMingming Cao 
1926525f4ed8SMingming Cao /*
19274e7ea81dSJan Kara  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
19284e7ea81dSJan Kara  *
19294e7ea81dSJan Kara  * @mpd - extent of blocks
19304e7ea81dSJan Kara  * @lblk - logical number of the block in the file
193109930042SJan Kara  * @bh - buffer head we want to add to the extent
19324e7ea81dSJan Kara  *
193309930042SJan Kara  * The function is used to collect contig. blocks in the same state. If the
193409930042SJan Kara  * buffer doesn't require mapping for writeback and we haven't started the
193509930042SJan Kara  * extent of buffers to map yet, the function returns 'true' immediately - the
193609930042SJan Kara  * caller can write the buffer right away. Otherwise the function returns true
193709930042SJan Kara  * if the block has been added to the extent, false if the block couldn't be
193809930042SJan Kara  * added.
19394e7ea81dSJan Kara  */
194009930042SJan Kara static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
194109930042SJan Kara 				   struct buffer_head *bh)
19424e7ea81dSJan Kara {
19434e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
19444e7ea81dSJan Kara 
194509930042SJan Kara 	/* Buffer that doesn't need mapping for writeback? */
194609930042SJan Kara 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
194709930042SJan Kara 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
194809930042SJan Kara 		/* So far no extent to map => we write the buffer right away */
194909930042SJan Kara 		if (map->m_len == 0)
195009930042SJan Kara 			return true;
195109930042SJan Kara 		return false;
195209930042SJan Kara 	}
19534e7ea81dSJan Kara 
19544e7ea81dSJan Kara 	/* First block in the extent? */
19554e7ea81dSJan Kara 	if (map->m_len == 0) {
19564e7ea81dSJan Kara 		map->m_lblk = lblk;
19574e7ea81dSJan Kara 		map->m_len = 1;
195809930042SJan Kara 		map->m_flags = bh->b_state & BH_FLAGS;
195909930042SJan Kara 		return true;
19604e7ea81dSJan Kara 	}
19614e7ea81dSJan Kara 
196209930042SJan Kara 	/* Don't go larger than mballoc is willing to allocate */
196309930042SJan Kara 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
196409930042SJan Kara 		return false;
196509930042SJan Kara 
19664e7ea81dSJan Kara 	/* Can we merge the block to our big extent? */
19674e7ea81dSJan Kara 	if (lblk == map->m_lblk + map->m_len &&
196809930042SJan Kara 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
19694e7ea81dSJan Kara 		map->m_len++;
197009930042SJan Kara 		return true;
19714e7ea81dSJan Kara 	}
197209930042SJan Kara 	return false;
19734e7ea81dSJan Kara }
19744e7ea81dSJan Kara 
19755f1132b2SJan Kara /*
19765f1132b2SJan Kara  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
19775f1132b2SJan Kara  *
19785f1132b2SJan Kara  * @mpd - extent of blocks for mapping
19795f1132b2SJan Kara  * @head - the first buffer in the page
19805f1132b2SJan Kara  * @bh - buffer we should start processing from
19815f1132b2SJan Kara  * @lblk - logical number of the block in the file corresponding to @bh
19825f1132b2SJan Kara  *
19835f1132b2SJan Kara  * Walk through page buffers from @bh upto @head (exclusive) and either submit
19845f1132b2SJan Kara  * the page for IO if all buffers in this page were mapped and there's no
19855f1132b2SJan Kara  * accumulated extent of buffers to map or add buffers in the page to the
19865f1132b2SJan Kara  * extent of buffers to map. The function returns 1 if the caller can continue
19875f1132b2SJan Kara  * by processing the next page, 0 if it should stop adding buffers to the
19885f1132b2SJan Kara  * extent to map because we cannot extend it anymore. It can also return value
19895f1132b2SJan Kara  * < 0 in case of error during IO submission.
19905f1132b2SJan Kara  */
19915f1132b2SJan Kara static int mpage_process_page_bufs(struct mpage_da_data *mpd,
19924e7ea81dSJan Kara 				   struct buffer_head *head,
19934e7ea81dSJan Kara 				   struct buffer_head *bh,
19944e7ea81dSJan Kara 				   ext4_lblk_t lblk)
19954e7ea81dSJan Kara {
19964e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
19975f1132b2SJan Kara 	int err;
19984e7ea81dSJan Kara 	ext4_lblk_t blocks = (i_size_read(inode) + (1 << inode->i_blkbits) - 1)
19994e7ea81dSJan Kara 							>> inode->i_blkbits;
20004e7ea81dSJan Kara 
20014e7ea81dSJan Kara 	do {
20024e7ea81dSJan Kara 		BUG_ON(buffer_locked(bh));
20034e7ea81dSJan Kara 
200409930042SJan Kara 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
20054e7ea81dSJan Kara 			/* Found extent to map? */
20064e7ea81dSJan Kara 			if (mpd->map.m_len)
20075f1132b2SJan Kara 				return 0;
200809930042SJan Kara 			/* Everything mapped so far and we hit EOF */
20095f1132b2SJan Kara 			break;
20104e7ea81dSJan Kara 		}
20114e7ea81dSJan Kara 	} while (lblk++, (bh = bh->b_this_page) != head);
20125f1132b2SJan Kara 	/* So far everything mapped? Submit the page for IO. */
20135f1132b2SJan Kara 	if (mpd->map.m_len == 0) {
20145f1132b2SJan Kara 		err = mpage_submit_page(mpd, head->b_page);
20155f1132b2SJan Kara 		if (err < 0)
20164e7ea81dSJan Kara 			return err;
20174e7ea81dSJan Kara 	}
20185f1132b2SJan Kara 	return lblk < blocks;
20195f1132b2SJan Kara }
20204e7ea81dSJan Kara 
20214e7ea81dSJan Kara /*
20224e7ea81dSJan Kara  * mpage_map_buffers - update buffers corresponding to changed extent and
20234e7ea81dSJan Kara  *		       submit fully mapped pages for IO
20244e7ea81dSJan Kara  *
20254e7ea81dSJan Kara  * @mpd - description of extent to map, on return next extent to map
20264e7ea81dSJan Kara  *
20274e7ea81dSJan Kara  * Scan buffers corresponding to changed extent (we expect corresponding pages
20284e7ea81dSJan Kara  * to be already locked) and update buffer state according to new extent state.
20294e7ea81dSJan Kara  * We map delalloc buffers to their physical location, clear unwritten bits,
20304e7ea81dSJan Kara  * and mark buffers as uninit when we perform writes to uninitialized extents
20314e7ea81dSJan Kara  * and do extent conversion after IO is finished. If the last page is not fully
20324e7ea81dSJan Kara  * mapped, we update @map to the next extent in the last page that needs
20334e7ea81dSJan Kara  * mapping. Otherwise we submit the page for IO.
20344e7ea81dSJan Kara  */
20354e7ea81dSJan Kara static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
20364e7ea81dSJan Kara {
20374e7ea81dSJan Kara 	struct pagevec pvec;
20384e7ea81dSJan Kara 	int nr_pages, i;
20394e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
20404e7ea81dSJan Kara 	struct buffer_head *head, *bh;
20414e7ea81dSJan Kara 	int bpp_bits = PAGE_CACHE_SHIFT - inode->i_blkbits;
20424e7ea81dSJan Kara 	pgoff_t start, end;
20434e7ea81dSJan Kara 	ext4_lblk_t lblk;
20444e7ea81dSJan Kara 	sector_t pblock;
20454e7ea81dSJan Kara 	int err;
20464e7ea81dSJan Kara 
20474e7ea81dSJan Kara 	start = mpd->map.m_lblk >> bpp_bits;
20484e7ea81dSJan Kara 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
20494e7ea81dSJan Kara 	lblk = start << bpp_bits;
20504e7ea81dSJan Kara 	pblock = mpd->map.m_pblk;
20514e7ea81dSJan Kara 
20524e7ea81dSJan Kara 	pagevec_init(&pvec, 0);
20534e7ea81dSJan Kara 	while (start <= end) {
20544e7ea81dSJan Kara 		nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start,
20554e7ea81dSJan Kara 					  PAGEVEC_SIZE);
20564e7ea81dSJan Kara 		if (nr_pages == 0)
20574e7ea81dSJan Kara 			break;
20584e7ea81dSJan Kara 		for (i = 0; i < nr_pages; i++) {
20594e7ea81dSJan Kara 			struct page *page = pvec.pages[i];
20604e7ea81dSJan Kara 
20614e7ea81dSJan Kara 			if (page->index > end)
20624e7ea81dSJan Kara 				break;
20634e7ea81dSJan Kara 			/* Up to 'end' pages must be contiguous */
20644e7ea81dSJan Kara 			BUG_ON(page->index != start);
20654e7ea81dSJan Kara 			bh = head = page_buffers(page);
20664e7ea81dSJan Kara 			do {
20674e7ea81dSJan Kara 				if (lblk < mpd->map.m_lblk)
20684e7ea81dSJan Kara 					continue;
20694e7ea81dSJan Kara 				if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
20704e7ea81dSJan Kara 					/*
20714e7ea81dSJan Kara 					 * Buffer after end of mapped extent.
20724e7ea81dSJan Kara 					 * Find next buffer in the page to map.
20734e7ea81dSJan Kara 					 */
20744e7ea81dSJan Kara 					mpd->map.m_len = 0;
20754e7ea81dSJan Kara 					mpd->map.m_flags = 0;
20765f1132b2SJan Kara 					/*
20775f1132b2SJan Kara 					 * FIXME: If dioread_nolock supports
20785f1132b2SJan Kara 					 * blocksize < pagesize, we need to make
20795f1132b2SJan Kara 					 * sure we add size mapped so far to
20805f1132b2SJan Kara 					 * io_end->size as the following call
20815f1132b2SJan Kara 					 * can submit the page for IO.
20825f1132b2SJan Kara 					 */
20835f1132b2SJan Kara 					err = mpage_process_page_bufs(mpd, head,
20845f1132b2SJan Kara 								      bh, lblk);
20854e7ea81dSJan Kara 					pagevec_release(&pvec);
20865f1132b2SJan Kara 					if (err > 0)
20875f1132b2SJan Kara 						err = 0;
20885f1132b2SJan Kara 					return err;
20894e7ea81dSJan Kara 				}
20904e7ea81dSJan Kara 				if (buffer_delay(bh)) {
20914e7ea81dSJan Kara 					clear_buffer_delay(bh);
20924e7ea81dSJan Kara 					bh->b_blocknr = pblock++;
20934e7ea81dSJan Kara 				}
20944e7ea81dSJan Kara 				clear_buffer_unwritten(bh);
20955f1132b2SJan Kara 			} while (lblk++, (bh = bh->b_this_page) != head);
20964e7ea81dSJan Kara 
20974e7ea81dSJan Kara 			/*
20984e7ea81dSJan Kara 			 * FIXME: This is going to break if dioread_nolock
20994e7ea81dSJan Kara 			 * supports blocksize < pagesize as we will try to
21004e7ea81dSJan Kara 			 * convert potentially unmapped parts of inode.
21014e7ea81dSJan Kara 			 */
21024e7ea81dSJan Kara 			mpd->io_submit.io_end->size += PAGE_CACHE_SIZE;
21034e7ea81dSJan Kara 			/* Page fully mapped - let IO run! */
21044e7ea81dSJan Kara 			err = mpage_submit_page(mpd, page);
21054e7ea81dSJan Kara 			if (err < 0) {
21064e7ea81dSJan Kara 				pagevec_release(&pvec);
21074e7ea81dSJan Kara 				return err;
21084e7ea81dSJan Kara 			}
21094e7ea81dSJan Kara 			start++;
21104e7ea81dSJan Kara 		}
21114e7ea81dSJan Kara 		pagevec_release(&pvec);
21124e7ea81dSJan Kara 	}
21134e7ea81dSJan Kara 	/* Extent fully mapped and matches with page boundary. We are done. */
21144e7ea81dSJan Kara 	mpd->map.m_len = 0;
21154e7ea81dSJan Kara 	mpd->map.m_flags = 0;
21164e7ea81dSJan Kara 	return 0;
21174e7ea81dSJan Kara }
21184e7ea81dSJan Kara 
21194e7ea81dSJan Kara static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
21204e7ea81dSJan Kara {
21214e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
21224e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
21234e7ea81dSJan Kara 	int get_blocks_flags;
21244e7ea81dSJan Kara 	int err;
21254e7ea81dSJan Kara 
21264e7ea81dSJan Kara 	trace_ext4_da_write_pages_extent(inode, map);
21274e7ea81dSJan Kara 	/*
21284e7ea81dSJan Kara 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
21294e7ea81dSJan Kara 	 * to convert an uninitialized extent to be initialized (in the case
21304e7ea81dSJan Kara 	 * where we have written into one or more preallocated blocks).  It is
21314e7ea81dSJan Kara 	 * possible that we're going to need more metadata blocks than
21324e7ea81dSJan Kara 	 * previously reserved. However we must not fail because we're in
21334e7ea81dSJan Kara 	 * writeback and there is nothing we can do about it so it might result
21344e7ea81dSJan Kara 	 * in data loss.  So use reserved blocks to allocate metadata if
21354e7ea81dSJan Kara 	 * possible.
21364e7ea81dSJan Kara 	 *
21374e7ea81dSJan Kara 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if the blocks
21384e7ea81dSJan Kara 	 * in question are delalloc blocks.  This affects functions in many
21394e7ea81dSJan Kara 	 * different parts of the allocation call path.  This flag exists
21404e7ea81dSJan Kara 	 * primarily because we don't want to change *many* call functions, so
21414e7ea81dSJan Kara 	 * ext4_map_blocks() will set the EXT4_STATE_DELALLOC_RESERVED flag
21424e7ea81dSJan Kara 	 * once the inode's allocation semaphore is taken.
21434e7ea81dSJan Kara 	 */
21444e7ea81dSJan Kara 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
21454e7ea81dSJan Kara 			   EXT4_GET_BLOCKS_METADATA_NOFAIL;
21464e7ea81dSJan Kara 	if (ext4_should_dioread_nolock(inode))
21474e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
21484e7ea81dSJan Kara 	if (map->m_flags & (1 << BH_Delay))
21494e7ea81dSJan Kara 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
21504e7ea81dSJan Kara 
21514e7ea81dSJan Kara 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
21524e7ea81dSJan Kara 	if (err < 0)
21534e7ea81dSJan Kara 		return err;
21546b523df4SJan Kara 	if (map->m_flags & EXT4_MAP_UNINIT) {
21556b523df4SJan Kara 		if (!mpd->io_submit.io_end->handle &&
21566b523df4SJan Kara 		    ext4_handle_valid(handle)) {
21576b523df4SJan Kara 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
21586b523df4SJan Kara 			handle->h_rsv_handle = NULL;
21596b523df4SJan Kara 		}
21603613d228SJan Kara 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
21616b523df4SJan Kara 	}
21624e7ea81dSJan Kara 
21634e7ea81dSJan Kara 	BUG_ON(map->m_len == 0);
21644e7ea81dSJan Kara 	if (map->m_flags & EXT4_MAP_NEW) {
21654e7ea81dSJan Kara 		struct block_device *bdev = inode->i_sb->s_bdev;
21664e7ea81dSJan Kara 		int i;
21674e7ea81dSJan Kara 
21684e7ea81dSJan Kara 		for (i = 0; i < map->m_len; i++)
21694e7ea81dSJan Kara 			unmap_underlying_metadata(bdev, map->m_pblk + i);
21704e7ea81dSJan Kara 	}
21714e7ea81dSJan Kara 	return 0;
21724e7ea81dSJan Kara }
21734e7ea81dSJan Kara 
21744e7ea81dSJan Kara /*
21754e7ea81dSJan Kara  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
21764e7ea81dSJan Kara  *				 mpd->len and submit pages underlying it for IO
21774e7ea81dSJan Kara  *
21784e7ea81dSJan Kara  * @handle - handle for journal operations
21794e7ea81dSJan Kara  * @mpd - extent to map
21807534e854SJan Kara  * @give_up_on_write - we set this to true iff there is a fatal error and there
21817534e854SJan Kara  *                     is no hope of writing the data. The caller should discard
21827534e854SJan Kara  *                     dirty pages to avoid infinite loops.
21834e7ea81dSJan Kara  *
21844e7ea81dSJan Kara  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
21854e7ea81dSJan Kara  * delayed, blocks are allocated, if it is unwritten, we may need to convert
21864e7ea81dSJan Kara  * them to initialized or split the described range from larger unwritten
21874e7ea81dSJan Kara  * extent. Note that we need not map all the described range since allocation
21884e7ea81dSJan Kara  * can return less blocks or the range is covered by more unwritten extents. We
21894e7ea81dSJan Kara  * cannot map more because we are limited by reserved transaction credits. On
21904e7ea81dSJan Kara  * the other hand we always make sure that the last touched page is fully
21914e7ea81dSJan Kara  * mapped so that it can be written out (and thus forward progress is
21924e7ea81dSJan Kara  * guaranteed). After mapping we submit all mapped pages for IO.
21934e7ea81dSJan Kara  */
21944e7ea81dSJan Kara static int mpage_map_and_submit_extent(handle_t *handle,
2195cb530541STheodore Ts'o 				       struct mpage_da_data *mpd,
2196cb530541STheodore Ts'o 				       bool *give_up_on_write)
21974e7ea81dSJan Kara {
21984e7ea81dSJan Kara 	struct inode *inode = mpd->inode;
21994e7ea81dSJan Kara 	struct ext4_map_blocks *map = &mpd->map;
22004e7ea81dSJan Kara 	int err;
22014e7ea81dSJan Kara 	loff_t disksize;
22024e7ea81dSJan Kara 
22034e7ea81dSJan Kara 	mpd->io_submit.io_end->offset =
22044e7ea81dSJan Kara 				((loff_t)map->m_lblk) << inode->i_blkbits;
220527d7c4edSJan Kara 	do {
22064e7ea81dSJan Kara 		err = mpage_map_one_extent(handle, mpd);
22074e7ea81dSJan Kara 		if (err < 0) {
22084e7ea81dSJan Kara 			struct super_block *sb = inode->i_sb;
22094e7ea81dSJan Kara 
2210cb530541STheodore Ts'o 			if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2211cb530541STheodore Ts'o 				goto invalidate_dirty_pages;
22124e7ea81dSJan Kara 			/*
2213cb530541STheodore Ts'o 			 * Let the uper layers retry transient errors.
2214cb530541STheodore Ts'o 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2215cb530541STheodore Ts'o 			 * is non-zero, a commit should free up blocks.
22164e7ea81dSJan Kara 			 */
2217cb530541STheodore Ts'o 			if ((err == -ENOMEM) ||
2218cb530541STheodore Ts'o 			    (err == -ENOSPC && ext4_count_free_clusters(sb)))
2219cb530541STheodore Ts'o 				return err;
22204e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
22214e7ea81dSJan Kara 				 "Delayed block allocation failed for "
22224e7ea81dSJan Kara 				 "inode %lu at logical offset %llu with"
22234e7ea81dSJan Kara 				 " max blocks %u with error %d",
22244e7ea81dSJan Kara 				 inode->i_ino,
22254e7ea81dSJan Kara 				 (unsigned long long)map->m_lblk,
2226cb530541STheodore Ts'o 				 (unsigned)map->m_len, -err);
22274e7ea81dSJan Kara 			ext4_msg(sb, KERN_CRIT,
22284e7ea81dSJan Kara 				 "This should not happen!! Data will "
22294e7ea81dSJan Kara 				 "be lost\n");
22304e7ea81dSJan Kara 			if (err == -ENOSPC)
22314e7ea81dSJan Kara 				ext4_print_free_blocks(inode);
2232cb530541STheodore Ts'o 		invalidate_dirty_pages:
2233cb530541STheodore Ts'o 			*give_up_on_write = true;
22344e7ea81dSJan Kara 			return err;
22354e7ea81dSJan Kara 		}
22364e7ea81dSJan Kara 		/*
22374e7ea81dSJan Kara 		 * Update buffer state, submit mapped pages, and get us new
22384e7ea81dSJan Kara 		 * extent to map
22394e7ea81dSJan Kara 		 */
22404e7ea81dSJan Kara 		err = mpage_map_and_submit_buffers(mpd);
22414e7ea81dSJan Kara 		if (err < 0)
22424e7ea81dSJan Kara 			return err;
224327d7c4edSJan Kara 	} while (map->m_len);
22444e7ea81dSJan Kara 
22454e7ea81dSJan Kara 	/* Update on-disk size after IO is submitted */
22464e7ea81dSJan Kara 	disksize = ((loff_t)mpd->first_page) << PAGE_CACHE_SHIFT;
22474e7ea81dSJan Kara 	if (disksize > EXT4_I(inode)->i_disksize) {
22484e7ea81dSJan Kara 		int err2;
22494e7ea81dSJan Kara 
225090e775b7SJan Kara 		ext4_wb_update_i_disksize(inode, disksize);
22514e7ea81dSJan Kara 		err2 = ext4_mark_inode_dirty(handle, inode);
22524e7ea81dSJan Kara 		if (err2)
22534e7ea81dSJan Kara 			ext4_error(inode->i_sb,
22544e7ea81dSJan Kara 				   "Failed to mark inode %lu dirty",
22554e7ea81dSJan Kara 				   inode->i_ino);
22564e7ea81dSJan Kara 		if (!err)
22574e7ea81dSJan Kara 			err = err2;
22584e7ea81dSJan Kara 	}
22594e7ea81dSJan Kara 	return err;
22604e7ea81dSJan Kara }
22614e7ea81dSJan Kara 
22624e7ea81dSJan Kara /*
2263fffb2739SJan Kara  * Calculate the total number of credits to reserve for one writepages
226420970ba6STheodore Ts'o  * iteration. This is called from ext4_writepages(). We map an extent of
2265fffb2739SJan Kara  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2266fffb2739SJan Kara  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2267fffb2739SJan Kara  * bpp - 1 blocks in bpp different extents.
2268525f4ed8SMingming Cao  */
2269fffb2739SJan Kara static int ext4_da_writepages_trans_blocks(struct inode *inode)
2270fffb2739SJan Kara {
2271fffb2739SJan Kara 	int bpp = ext4_journal_blocks_per_page(inode);
2272525f4ed8SMingming Cao 
2273fffb2739SJan Kara 	return ext4_meta_trans_blocks(inode,
2274fffb2739SJan Kara 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2275525f4ed8SMingming Cao }
227661628a3fSMingming Cao 
22778e48dcfbSTheodore Ts'o /*
22784e7ea81dSJan Kara  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
22794e7ea81dSJan Kara  * 				 and underlying extent to map
22804e7ea81dSJan Kara  *
22814e7ea81dSJan Kara  * @mpd - where to look for pages
22824e7ea81dSJan Kara  *
22834e7ea81dSJan Kara  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
22844e7ea81dSJan Kara  * IO immediately. When we find a page which isn't mapped we start accumulating
22854e7ea81dSJan Kara  * extent of buffers underlying these pages that needs mapping (formed by
22864e7ea81dSJan Kara  * either delayed or unwritten buffers). We also lock the pages containing
22874e7ea81dSJan Kara  * these buffers. The extent found is returned in @mpd structure (starting at
22884e7ea81dSJan Kara  * mpd->lblk with length mpd->len blocks).
22894e7ea81dSJan Kara  *
22904e7ea81dSJan Kara  * Note that this function can attach bios to one io_end structure which are
22914e7ea81dSJan Kara  * neither logically nor physically contiguous. Although it may seem as an
22924e7ea81dSJan Kara  * unnecessary complication, it is actually inevitable in blocksize < pagesize
22934e7ea81dSJan Kara  * case as we need to track IO to all buffers underlying a page in one io_end.
22948e48dcfbSTheodore Ts'o  */
22954e7ea81dSJan Kara static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
22968e48dcfbSTheodore Ts'o {
22974e7ea81dSJan Kara 	struct address_space *mapping = mpd->inode->i_mapping;
22988e48dcfbSTheodore Ts'o 	struct pagevec pvec;
22994f01b02cSTheodore Ts'o 	unsigned int nr_pages;
2300aeac589aSMing Lei 	long left = mpd->wbc->nr_to_write;
23014e7ea81dSJan Kara 	pgoff_t index = mpd->first_page;
23024e7ea81dSJan Kara 	pgoff_t end = mpd->last_page;
23034e7ea81dSJan Kara 	int tag;
23044e7ea81dSJan Kara 	int i, err = 0;
23054e7ea81dSJan Kara 	int blkbits = mpd->inode->i_blkbits;
23064e7ea81dSJan Kara 	ext4_lblk_t lblk;
23074e7ea81dSJan Kara 	struct buffer_head *head;
23088e48dcfbSTheodore Ts'o 
23094e7ea81dSJan Kara 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
23105b41d924SEric Sandeen 		tag = PAGECACHE_TAG_TOWRITE;
23115b41d924SEric Sandeen 	else
23125b41d924SEric Sandeen 		tag = PAGECACHE_TAG_DIRTY;
23135b41d924SEric Sandeen 
23144e7ea81dSJan Kara 	pagevec_init(&pvec, 0);
23154e7ea81dSJan Kara 	mpd->map.m_len = 0;
23164e7ea81dSJan Kara 	mpd->next_page = index;
23174f01b02cSTheodore Ts'o 	while (index <= end) {
23185b41d924SEric Sandeen 		nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
23198e48dcfbSTheodore Ts'o 			      min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
23208e48dcfbSTheodore Ts'o 		if (nr_pages == 0)
23214e7ea81dSJan Kara 			goto out;
23228e48dcfbSTheodore Ts'o 
23238e48dcfbSTheodore Ts'o 		for (i = 0; i < nr_pages; i++) {
23248e48dcfbSTheodore Ts'o 			struct page *page = pvec.pages[i];
23258e48dcfbSTheodore Ts'o 
23268e48dcfbSTheodore Ts'o 			/*
23278e48dcfbSTheodore Ts'o 			 * At this point, the page may be truncated or
23288e48dcfbSTheodore Ts'o 			 * invalidated (changing page->mapping to NULL), or
23298e48dcfbSTheodore Ts'o 			 * even swizzled back from swapper_space to tmpfs file
23308e48dcfbSTheodore Ts'o 			 * mapping. However, page->index will not change
23318e48dcfbSTheodore Ts'o 			 * because we have a reference on the page.
23328e48dcfbSTheodore Ts'o 			 */
23334f01b02cSTheodore Ts'o 			if (page->index > end)
23344f01b02cSTheodore Ts'o 				goto out;
23358e48dcfbSTheodore Ts'o 
2336aeac589aSMing Lei 			/*
2337aeac589aSMing Lei 			 * Accumulated enough dirty pages? This doesn't apply
2338aeac589aSMing Lei 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2339aeac589aSMing Lei 			 * keep going because someone may be concurrently
2340aeac589aSMing Lei 			 * dirtying pages, and we might have synced a lot of
2341aeac589aSMing Lei 			 * newly appeared dirty pages, but have not synced all
2342aeac589aSMing Lei 			 * of the old dirty pages.
2343aeac589aSMing Lei 			 */
2344aeac589aSMing Lei 			if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2345aeac589aSMing Lei 				goto out;
2346aeac589aSMing Lei 
23474e7ea81dSJan Kara 			/* If we can't merge this page, we are done. */
23484e7ea81dSJan Kara 			if (mpd->map.m_len > 0 && mpd->next_page != page->index)
23494e7ea81dSJan Kara 				goto out;
235078aaced3STheodore Ts'o 
23518e48dcfbSTheodore Ts'o 			lock_page(page);
23528e48dcfbSTheodore Ts'o 			/*
23534e7ea81dSJan Kara 			 * If the page is no longer dirty, or its mapping no
23544e7ea81dSJan Kara 			 * longer corresponds to inode we are writing (which
23554e7ea81dSJan Kara 			 * means it has been truncated or invalidated), or the
23564e7ea81dSJan Kara 			 * page is already under writeback and we are not doing
23574e7ea81dSJan Kara 			 * a data integrity writeback, skip the page
23588e48dcfbSTheodore Ts'o 			 */
23594f01b02cSTheodore Ts'o 			if (!PageDirty(page) ||
23604f01b02cSTheodore Ts'o 			    (PageWriteback(page) &&
23614e7ea81dSJan Kara 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
23624f01b02cSTheodore Ts'o 			    unlikely(page->mapping != mapping)) {
23638e48dcfbSTheodore Ts'o 				unlock_page(page);
23648e48dcfbSTheodore Ts'o 				continue;
23658e48dcfbSTheodore Ts'o 			}
23668e48dcfbSTheodore Ts'o 
23678e48dcfbSTheodore Ts'o 			wait_on_page_writeback(page);
23688e48dcfbSTheodore Ts'o 			BUG_ON(PageWriteback(page));
23698e48dcfbSTheodore Ts'o 
23704e7ea81dSJan Kara 			if (mpd->map.m_len == 0)
23718eb9e5ceSTheodore Ts'o 				mpd->first_page = page->index;
23728eb9e5ceSTheodore Ts'o 			mpd->next_page = page->index + 1;
2373f8bec370SJan Kara 			/* Add all dirty buffers to mpd */
23744e7ea81dSJan Kara 			lblk = ((ext4_lblk_t)page->index) <<
23754e7ea81dSJan Kara 				(PAGE_CACHE_SHIFT - blkbits);
23768eb9e5ceSTheodore Ts'o 			head = page_buffers(page);
23775f1132b2SJan Kara 			err = mpage_process_page_bufs(mpd, head, head, lblk);
23785f1132b2SJan Kara 			if (err <= 0)
23794e7ea81dSJan Kara 				goto out;
23805f1132b2SJan Kara 			err = 0;
2381aeac589aSMing Lei 			left--;
23828e48dcfbSTheodore Ts'o 		}
23838e48dcfbSTheodore Ts'o 		pagevec_release(&pvec);
23848e48dcfbSTheodore Ts'o 		cond_resched();
23858e48dcfbSTheodore Ts'o 	}
23864f01b02cSTheodore Ts'o 	return 0;
23878eb9e5ceSTheodore Ts'o out:
23888eb9e5ceSTheodore Ts'o 	pagevec_release(&pvec);
23894e7ea81dSJan Kara 	return err;
23908e48dcfbSTheodore Ts'o }
23918e48dcfbSTheodore Ts'o 
239220970ba6STheodore Ts'o static int __writepage(struct page *page, struct writeback_control *wbc,
239320970ba6STheodore Ts'o 		       void *data)
239420970ba6STheodore Ts'o {
239520970ba6STheodore Ts'o 	struct address_space *mapping = data;
239620970ba6STheodore Ts'o 	int ret = ext4_writepage(page, wbc);
239720970ba6STheodore Ts'o 	mapping_set_error(mapping, ret);
239820970ba6STheodore Ts'o 	return ret;
239920970ba6STheodore Ts'o }
240020970ba6STheodore Ts'o 
240120970ba6STheodore Ts'o static int ext4_writepages(struct address_space *mapping,
240264769240SAlex Tomas 			   struct writeback_control *wbc)
240364769240SAlex Tomas {
24044e7ea81dSJan Kara 	pgoff_t	writeback_index = 0;
24054e7ea81dSJan Kara 	long nr_to_write = wbc->nr_to_write;
240622208dedSAneesh Kumar K.V 	int range_whole = 0;
24074e7ea81dSJan Kara 	int cycled = 1;
240861628a3fSMingming Cao 	handle_t *handle = NULL;
2409df22291fSAneesh Kumar K.V 	struct mpage_da_data mpd;
24105e745b04SAneesh Kumar K.V 	struct inode *inode = mapping->host;
24116b523df4SJan Kara 	int needed_blocks, rsv_blocks = 0, ret = 0;
24125e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
24134e7ea81dSJan Kara 	bool done;
24141bce63d1SShaohua Li 	struct blk_plug plug;
2415cb530541STheodore Ts'o 	bool give_up_on_write = false;
241661628a3fSMingming Cao 
241720970ba6STheodore Ts'o 	trace_ext4_writepages(inode, wbc);
2418ba80b101STheodore Ts'o 
241961628a3fSMingming Cao 	/*
242061628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
242161628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
242261628a3fSMingming Cao 	 * because that could violate lock ordering on umount
242361628a3fSMingming Cao 	 */
2424a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2425bbf023c7SMing Lei 		goto out_writepages;
24262a21e37eSTheodore Ts'o 
242720970ba6STheodore Ts'o 	if (ext4_should_journal_data(inode)) {
242820970ba6STheodore Ts'o 		struct blk_plug plug;
242920970ba6STheodore Ts'o 
243020970ba6STheodore Ts'o 		blk_start_plug(&plug);
243120970ba6STheodore Ts'o 		ret = write_cache_pages(mapping, wbc, __writepage, mapping);
243220970ba6STheodore Ts'o 		blk_finish_plug(&plug);
2433bbf023c7SMing Lei 		goto out_writepages;
243420970ba6STheodore Ts'o 	}
243520970ba6STheodore Ts'o 
24362a21e37eSTheodore Ts'o 	/*
24372a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
24382a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
24392a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
24404ab2f15bSTheodore Ts'o 	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
24412a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
244220970ba6STheodore Ts'o 	 * read-only, and in that case, ext4_writepages should
24432a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
24442a21e37eSTheodore Ts'o 	 * the stack trace.
24452a21e37eSTheodore Ts'o 	 */
2446bbf023c7SMing Lei 	if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2447bbf023c7SMing Lei 		ret = -EROFS;
2448bbf023c7SMing Lei 		goto out_writepages;
2449bbf023c7SMing Lei 	}
24502a21e37eSTheodore Ts'o 
24516b523df4SJan Kara 	if (ext4_should_dioread_nolock(inode)) {
24526b523df4SJan Kara 		/*
24536b523df4SJan Kara 		 * We may need to convert up to one extent per block in
24546b523df4SJan Kara 		 * the page and we may dirty the inode.
24556b523df4SJan Kara 		 */
24566b523df4SJan Kara 		rsv_blocks = 1 + (PAGE_CACHE_SIZE >> inode->i_blkbits);
24576b523df4SJan Kara 	}
24586b523df4SJan Kara 
24594e7ea81dSJan Kara 	/*
24604e7ea81dSJan Kara 	 * If we have inline data and arrive here, it means that
24614e7ea81dSJan Kara 	 * we will soon create the block for the 1st page, so
24624e7ea81dSJan Kara 	 * we'd better clear the inline data here.
24634e7ea81dSJan Kara 	 */
24644e7ea81dSJan Kara 	if (ext4_has_inline_data(inode)) {
24654e7ea81dSJan Kara 		/* Just inode will be modified... */
24664e7ea81dSJan Kara 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
24674e7ea81dSJan Kara 		if (IS_ERR(handle)) {
24684e7ea81dSJan Kara 			ret = PTR_ERR(handle);
24694e7ea81dSJan Kara 			goto out_writepages;
24704e7ea81dSJan Kara 		}
24714e7ea81dSJan Kara 		BUG_ON(ext4_test_inode_state(inode,
24724e7ea81dSJan Kara 				EXT4_STATE_MAY_INLINE_DATA));
24734e7ea81dSJan Kara 		ext4_destroy_inline_data(handle, inode);
24744e7ea81dSJan Kara 		ext4_journal_stop(handle);
24754e7ea81dSJan Kara 	}
24764e7ea81dSJan Kara 
247722208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
247822208dedSAneesh Kumar K.V 		range_whole = 1;
247961628a3fSMingming Cao 
24802acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
24814e7ea81dSJan Kara 		writeback_index = mapping->writeback_index;
24824e7ea81dSJan Kara 		if (writeback_index)
24832acf2c26SAneesh Kumar K.V 			cycled = 0;
24844e7ea81dSJan Kara 		mpd.first_page = writeback_index;
24854e7ea81dSJan Kara 		mpd.last_page = -1;
24865b41d924SEric Sandeen 	} else {
24874e7ea81dSJan Kara 		mpd.first_page = wbc->range_start >> PAGE_CACHE_SHIFT;
24884e7ea81dSJan Kara 		mpd.last_page = wbc->range_end >> PAGE_CACHE_SHIFT;
24895b41d924SEric Sandeen 	}
2490a1d6cc56SAneesh Kumar K.V 
24914e7ea81dSJan Kara 	mpd.inode = inode;
24924e7ea81dSJan Kara 	mpd.wbc = wbc;
24934e7ea81dSJan Kara 	ext4_io_submit_init(&mpd.io_submit, wbc);
24942acf2c26SAneesh Kumar K.V retry:
24956e6938b6SWu Fengguang 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
24964e7ea81dSJan Kara 		tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
24974e7ea81dSJan Kara 	done = false;
24981bce63d1SShaohua Li 	blk_start_plug(&plug);
24994e7ea81dSJan Kara 	while (!done && mpd.first_page <= mpd.last_page) {
25004e7ea81dSJan Kara 		/* For each extent of pages we use new io_end */
25014e7ea81dSJan Kara 		mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
25024e7ea81dSJan Kara 		if (!mpd.io_submit.io_end) {
25034e7ea81dSJan Kara 			ret = -ENOMEM;
25044e7ea81dSJan Kara 			break;
25054e7ea81dSJan Kara 		}
2506a1d6cc56SAneesh Kumar K.V 
2507a1d6cc56SAneesh Kumar K.V 		/*
25084e7ea81dSJan Kara 		 * We have two constraints: We find one extent to map and we
25094e7ea81dSJan Kara 		 * must always write out whole page (makes a difference when
25104e7ea81dSJan Kara 		 * blocksize < pagesize) so that we don't block on IO when we
25114e7ea81dSJan Kara 		 * try to write out the rest of the page. Journalled mode is
25124e7ea81dSJan Kara 		 * not supported by delalloc.
2513a1d6cc56SAneesh Kumar K.V 		 */
2514a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
2515525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2516a1d6cc56SAneesh Kumar K.V 
251761628a3fSMingming Cao 		/* start a new transaction */
25186b523df4SJan Kara 		handle = ext4_journal_start_with_reserve(inode,
25196b523df4SJan Kara 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
252061628a3fSMingming Cao 		if (IS_ERR(handle)) {
252161628a3fSMingming Cao 			ret = PTR_ERR(handle);
25221693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2523fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
2524a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
25254e7ea81dSJan Kara 			/* Release allocated io_end */
25264e7ea81dSJan Kara 			ext4_put_io_end(mpd.io_submit.io_end);
25274e7ea81dSJan Kara 			break;
252861628a3fSMingming Cao 		}
2529f63e6005STheodore Ts'o 
25304e7ea81dSJan Kara 		trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
25314e7ea81dSJan Kara 		ret = mpage_prepare_extent_to_map(&mpd);
25324e7ea81dSJan Kara 		if (!ret) {
25334e7ea81dSJan Kara 			if (mpd.map.m_len)
2534cb530541STheodore Ts'o 				ret = mpage_map_and_submit_extent(handle, &mpd,
2535cb530541STheodore Ts'o 					&give_up_on_write);
25364e7ea81dSJan Kara 			else {
2537f63e6005STheodore Ts'o 				/*
25384e7ea81dSJan Kara 				 * We scanned the whole range (or exhausted
25394e7ea81dSJan Kara 				 * nr_to_write), submitted what was mapped and
25404e7ea81dSJan Kara 				 * didn't find anything needing mapping. We are
25414e7ea81dSJan Kara 				 * done.
2542f63e6005STheodore Ts'o 				 */
25434e7ea81dSJan Kara 				done = true;
2544f63e6005STheodore Ts'o 			}
25454e7ea81dSJan Kara 		}
254661628a3fSMingming Cao 		ext4_journal_stop(handle);
25474e7ea81dSJan Kara 		/* Submit prepared bio */
25484e7ea81dSJan Kara 		ext4_io_submit(&mpd.io_submit);
25494e7ea81dSJan Kara 		/* Unlock pages we didn't use */
2550cb530541STheodore Ts'o 		mpage_release_unused_pages(&mpd, give_up_on_write);
25514e7ea81dSJan Kara 		/* Drop our io_end reference we got from init */
25524e7ea81dSJan Kara 		ext4_put_io_end(mpd.io_submit.io_end);
2553df22291fSAneesh Kumar K.V 
25544e7ea81dSJan Kara 		if (ret == -ENOSPC && sbi->s_journal) {
25554e7ea81dSJan Kara 			/*
25564e7ea81dSJan Kara 			 * Commit the transaction which would
255722208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
255822208dedSAneesh Kumar K.V 			 * and try again
255922208dedSAneesh Kumar K.V 			 */
2560df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
256122208dedSAneesh Kumar K.V 			ret = 0;
25624e7ea81dSJan Kara 			continue;
25634e7ea81dSJan Kara 		}
25644e7ea81dSJan Kara 		/* Fatal error - ENOMEM, EIO... */
25654e7ea81dSJan Kara 		if (ret)
256661628a3fSMingming Cao 			break;
256761628a3fSMingming Cao 	}
25681bce63d1SShaohua Li 	blk_finish_plug(&plug);
25699c12a831SJan Kara 	if (!ret && !cycled && wbc->nr_to_write > 0) {
25702acf2c26SAneesh Kumar K.V 		cycled = 1;
25714e7ea81dSJan Kara 		mpd.last_page = writeback_index - 1;
25724e7ea81dSJan Kara 		mpd.first_page = 0;
25732acf2c26SAneesh Kumar K.V 		goto retry;
25742acf2c26SAneesh Kumar K.V 	}
257561628a3fSMingming Cao 
257622208dedSAneesh Kumar K.V 	/* Update index */
257722208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
257822208dedSAneesh Kumar K.V 		/*
25794e7ea81dSJan Kara 		 * Set the writeback_index so that range_cyclic
258022208dedSAneesh Kumar K.V 		 * mode will write it back later
258122208dedSAneesh Kumar K.V 		 */
25824e7ea81dSJan Kara 		mapping->writeback_index = mpd.first_page;
2583a1d6cc56SAneesh Kumar K.V 
258461628a3fSMingming Cao out_writepages:
258520970ba6STheodore Ts'o 	trace_ext4_writepages_result(inode, wbc, ret,
25864e7ea81dSJan Kara 				     nr_to_write - wbc->nr_to_write);
258761628a3fSMingming Cao 	return ret;
258864769240SAlex Tomas }
258964769240SAlex Tomas 
259079f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
259179f0be8dSAneesh Kumar K.V {
25925c1ff336SEric Whitney 	s64 free_clusters, dirty_clusters;
259379f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
259479f0be8dSAneesh Kumar K.V 
259579f0be8dSAneesh Kumar K.V 	/*
259679f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
259779f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
2598179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
259979f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
260079f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
260179f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
260279f0be8dSAneesh Kumar K.V 	 */
26035c1ff336SEric Whitney 	free_clusters =
26045c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
26055c1ff336SEric Whitney 	dirty_clusters =
26065c1ff336SEric Whitney 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
260700d4e736STheodore Ts'o 	/*
260800d4e736STheodore Ts'o 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
260900d4e736STheodore Ts'o 	 */
26105c1ff336SEric Whitney 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
261110ee27a0SMiao Xie 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
261200d4e736STheodore Ts'o 
26135c1ff336SEric Whitney 	if (2 * free_clusters < 3 * dirty_clusters ||
26145c1ff336SEric Whitney 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
261579f0be8dSAneesh Kumar K.V 		/*
2616c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
2617c8afb446SEric Sandeen 		 * or free blocks is less than watermark
261879f0be8dSAneesh Kumar K.V 		 */
261979f0be8dSAneesh Kumar K.V 		return 1;
262079f0be8dSAneesh Kumar K.V 	}
262179f0be8dSAneesh Kumar K.V 	return 0;
262279f0be8dSAneesh Kumar K.V }
262379f0be8dSAneesh Kumar K.V 
262464769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
262564769240SAlex Tomas 			       loff_t pos, unsigned len, unsigned flags,
262664769240SAlex Tomas 			       struct page **pagep, void **fsdata)
262764769240SAlex Tomas {
262872b8ab9dSEric Sandeen 	int ret, retries = 0;
262964769240SAlex Tomas 	struct page *page;
263064769240SAlex Tomas 	pgoff_t index;
263164769240SAlex Tomas 	struct inode *inode = mapping->host;
263264769240SAlex Tomas 	handle_t *handle;
263364769240SAlex Tomas 
263464769240SAlex Tomas 	index = pos >> PAGE_CACHE_SHIFT;
263579f0be8dSAneesh Kumar K.V 
263679f0be8dSAneesh Kumar K.V 	if (ext4_nonda_switch(inode->i_sb)) {
263779f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
263879f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
263979f0be8dSAneesh Kumar K.V 					len, flags, pagep, fsdata);
264079f0be8dSAneesh Kumar K.V 	}
264179f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
26429bffad1eSTheodore Ts'o 	trace_ext4_da_write_begin(inode, pos, len, flags);
26439c3569b5STao Ma 
26449c3569b5STao Ma 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
26459c3569b5STao Ma 		ret = ext4_da_write_inline_data_begin(mapping, inode,
26469c3569b5STao Ma 						      pos, len, flags,
26479c3569b5STao Ma 						      pagep, fsdata);
26489c3569b5STao Ma 		if (ret < 0)
264947564bfbSTheodore Ts'o 			return ret;
265047564bfbSTheodore Ts'o 		if (ret == 1)
265147564bfbSTheodore Ts'o 			return 0;
26529c3569b5STao Ma 	}
26539c3569b5STao Ma 
265447564bfbSTheodore Ts'o 	/*
265547564bfbSTheodore Ts'o 	 * grab_cache_page_write_begin() can take a long time if the
265647564bfbSTheodore Ts'o 	 * system is thrashing due to memory pressure, or if the page
265747564bfbSTheodore Ts'o 	 * is being written back.  So grab it first before we start
265847564bfbSTheodore Ts'o 	 * the transaction handle.  This also allows us to allocate
265947564bfbSTheodore Ts'o 	 * the page (if needed) without using GFP_NOFS.
266047564bfbSTheodore Ts'o 	 */
266147564bfbSTheodore Ts'o retry_grab:
266247564bfbSTheodore Ts'o 	page = grab_cache_page_write_begin(mapping, index, flags);
266347564bfbSTheodore Ts'o 	if (!page)
266447564bfbSTheodore Ts'o 		return -ENOMEM;
266547564bfbSTheodore Ts'o 	unlock_page(page);
266647564bfbSTheodore Ts'o 
266764769240SAlex Tomas 	/*
266864769240SAlex Tomas 	 * With delayed allocation, we don't log the i_disksize update
266964769240SAlex Tomas 	 * if there is delayed block allocation. But we still need
267064769240SAlex Tomas 	 * to journalling the i_disksize update if writes to the end
267164769240SAlex Tomas 	 * of file which has an already mapped buffer.
267264769240SAlex Tomas 	 */
267347564bfbSTheodore Ts'o retry_journal:
26749924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, 1);
267564769240SAlex Tomas 	if (IS_ERR(handle)) {
267647564bfbSTheodore Ts'o 		page_cache_release(page);
267747564bfbSTheodore Ts'o 		return PTR_ERR(handle);
267864769240SAlex Tomas 	}
267964769240SAlex Tomas 
268047564bfbSTheodore Ts'o 	lock_page(page);
268147564bfbSTheodore Ts'o 	if (page->mapping != mapping) {
268247564bfbSTheodore Ts'o 		/* The page got truncated from under us */
268347564bfbSTheodore Ts'o 		unlock_page(page);
268447564bfbSTheodore Ts'o 		page_cache_release(page);
2685d5a0d4f7SEric Sandeen 		ext4_journal_stop(handle);
268647564bfbSTheodore Ts'o 		goto retry_grab;
2687d5a0d4f7SEric Sandeen 	}
268847564bfbSTheodore Ts'o 	/* In case writeback began while the page was unlocked */
26897afe5aa5SDmitry Monakhov 	wait_for_stable_page(page);
269064769240SAlex Tomas 
26916e1db88dSChristoph Hellwig 	ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
269264769240SAlex Tomas 	if (ret < 0) {
269364769240SAlex Tomas 		unlock_page(page);
269464769240SAlex Tomas 		ext4_journal_stop(handle);
2695ae4d5372SAneesh Kumar K.V 		/*
2696ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
2697ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
2698ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
2699ae4d5372SAneesh Kumar K.V 		 */
2700ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
2701b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
270247564bfbSTheodore Ts'o 
270347564bfbSTheodore Ts'o 		if (ret == -ENOSPC &&
270447564bfbSTheodore Ts'o 		    ext4_should_retry_alloc(inode->i_sb, &retries))
270547564bfbSTheodore Ts'o 			goto retry_journal;
270647564bfbSTheodore Ts'o 
270747564bfbSTheodore Ts'o 		page_cache_release(page);
270847564bfbSTheodore Ts'o 		return ret;
270964769240SAlex Tomas 	}
271064769240SAlex Tomas 
271147564bfbSTheodore Ts'o 	*pagep = page;
271264769240SAlex Tomas 	return ret;
271364769240SAlex Tomas }
271464769240SAlex Tomas 
2715632eaeabSMingming Cao /*
2716632eaeabSMingming Cao  * Check if we should update i_disksize
2717632eaeabSMingming Cao  * when write to the end of file but not require block allocation
2718632eaeabSMingming Cao  */
2719632eaeabSMingming Cao static int ext4_da_should_update_i_disksize(struct page *page,
2720632eaeabSMingming Cao 					    unsigned long offset)
2721632eaeabSMingming Cao {
2722632eaeabSMingming Cao 	struct buffer_head *bh;
2723632eaeabSMingming Cao 	struct inode *inode = page->mapping->host;
2724632eaeabSMingming Cao 	unsigned int idx;
2725632eaeabSMingming Cao 	int i;
2726632eaeabSMingming Cao 
2727632eaeabSMingming Cao 	bh = page_buffers(page);
2728632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
2729632eaeabSMingming Cao 
2730632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
2731632eaeabSMingming Cao 		bh = bh->b_this_page;
2732632eaeabSMingming Cao 
273329fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2734632eaeabSMingming Cao 		return 0;
2735632eaeabSMingming Cao 	return 1;
2736632eaeabSMingming Cao }
2737632eaeabSMingming Cao 
273864769240SAlex Tomas static int ext4_da_write_end(struct file *file,
273964769240SAlex Tomas 			     struct address_space *mapping,
274064769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
274164769240SAlex Tomas 			     struct page *page, void *fsdata)
274264769240SAlex Tomas {
274364769240SAlex Tomas 	struct inode *inode = mapping->host;
274464769240SAlex Tomas 	int ret = 0, ret2;
274564769240SAlex Tomas 	handle_t *handle = ext4_journal_current_handle();
274664769240SAlex Tomas 	loff_t new_i_size;
2747632eaeabSMingming Cao 	unsigned long start, end;
274879f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
274979f0be8dSAneesh Kumar K.V 
275074d553aaSTheodore Ts'o 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
275174d553aaSTheodore Ts'o 		return ext4_write_end(file, mapping, pos,
275279f0be8dSAneesh Kumar K.V 				      len, copied, page, fsdata);
2753632eaeabSMingming Cao 
27549bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
2755632eaeabSMingming Cao 	start = pos & (PAGE_CACHE_SIZE - 1);
2756632eaeabSMingming Cao 	end = start + copied - 1;
275764769240SAlex Tomas 
275864769240SAlex Tomas 	/*
275964769240SAlex Tomas 	 * generic_write_end() will run mark_inode_dirty() if i_size
276064769240SAlex Tomas 	 * changes.  So let's piggyback the i_disksize mark_inode_dirty
276164769240SAlex Tomas 	 * into that.
276264769240SAlex Tomas 	 */
276364769240SAlex Tomas 	new_i_size = pos + copied;
2764ea51d132SAndrea Arcangeli 	if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
27659c3569b5STao Ma 		if (ext4_has_inline_data(inode) ||
27669c3569b5STao Ma 		    ext4_da_should_update_i_disksize(page, end)) {
2767632eaeabSMingming Cao 			down_write(&EXT4_I(inode)->i_data_sem);
2768f3b59291STheodore Ts'o 			if (new_i_size > EXT4_I(inode)->i_disksize)
276964769240SAlex Tomas 				EXT4_I(inode)->i_disksize = new_i_size;
2770632eaeabSMingming Cao 			up_write(&EXT4_I(inode)->i_data_sem);
2771cf17fea6SAneesh Kumar K.V 			/* We need to mark inode dirty even if
2772cf17fea6SAneesh Kumar K.V 			 * new_i_size is less that inode->i_size
2773cf17fea6SAneesh Kumar K.V 			 * bu greater than i_disksize.(hint delalloc)
2774cf17fea6SAneesh Kumar K.V 			 */
2775cf17fea6SAneesh Kumar K.V 			ext4_mark_inode_dirty(handle, inode);
2776632eaeabSMingming Cao 		}
2777632eaeabSMingming Cao 	}
27789c3569b5STao Ma 
27799c3569b5STao Ma 	if (write_mode != CONVERT_INLINE_DATA &&
27809c3569b5STao Ma 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
27819c3569b5STao Ma 	    ext4_has_inline_data(inode))
27829c3569b5STao Ma 		ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
27839c3569b5STao Ma 						     page);
27849c3569b5STao Ma 	else
278564769240SAlex Tomas 		ret2 = generic_write_end(file, mapping, pos, len, copied,
278664769240SAlex Tomas 							page, fsdata);
27879c3569b5STao Ma 
278864769240SAlex Tomas 	copied = ret2;
278964769240SAlex Tomas 	if (ret2 < 0)
279064769240SAlex Tomas 		ret = ret2;
279164769240SAlex Tomas 	ret2 = ext4_journal_stop(handle);
279264769240SAlex Tomas 	if (!ret)
279364769240SAlex Tomas 		ret = ret2;
279464769240SAlex Tomas 
279564769240SAlex Tomas 	return ret ? ret : copied;
279664769240SAlex Tomas }
279764769240SAlex Tomas 
2798d47992f8SLukas Czerner static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
2799d47992f8SLukas Czerner 				   unsigned int length)
280064769240SAlex Tomas {
280164769240SAlex Tomas 	/*
280264769240SAlex Tomas 	 * Drop reserved blocks
280364769240SAlex Tomas 	 */
280464769240SAlex Tomas 	BUG_ON(!PageLocked(page));
280564769240SAlex Tomas 	if (!page_has_buffers(page))
280664769240SAlex Tomas 		goto out;
280764769240SAlex Tomas 
2808ca99fdd2SLukas Czerner 	ext4_da_page_release_reservation(page, offset, length);
280964769240SAlex Tomas 
281064769240SAlex Tomas out:
2811d47992f8SLukas Czerner 	ext4_invalidatepage(page, offset, length);
281264769240SAlex Tomas 
281364769240SAlex Tomas 	return;
281464769240SAlex Tomas }
281564769240SAlex Tomas 
2816ccd2506bSTheodore Ts'o /*
2817ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
2818ccd2506bSTheodore Ts'o  */
2819ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
2820ccd2506bSTheodore Ts'o {
2821fb40ba0dSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
2822fb40ba0dSTheodore Ts'o 
2823ccd2506bSTheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks &&
2824ccd2506bSTheodore Ts'o 	    !EXT4_I(inode)->i_reserved_meta_blocks)
2825ccd2506bSTheodore Ts'o 		return 0;
2826ccd2506bSTheodore Ts'o 
2827ccd2506bSTheodore Ts'o 	/*
2828ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
2829ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
2830ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
2831ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
2832ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
2833ccd2506bSTheodore Ts'o 	 *
283420970ba6STheodore Ts'o 	 * ext4_writepages() ->
2835ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
2836ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
2837ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
2838ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
2839ccd2506bSTheodore Ts'o 	 *
2840ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
2841ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
2842ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
2843ccd2506bSTheodore Ts'o 	 * doing I/O at all.
2844ccd2506bSTheodore Ts'o 	 *
2845ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
2846380cf090SWu Fengguang 	 * the pages by calling redirty_page_for_writepage() but that
2847ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
2848ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
284925985edcSLucas De Marchi 	 * simplifying them because we wouldn't actually intend to
2850ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
2851ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
2852ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
2853ccd2506bSTheodore Ts'o 	 *
2854ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
2855ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
2856ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
2857ccd2506bSTheodore Ts'o 	 */
2858ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
2859ccd2506bSTheodore Ts'o }
286064769240SAlex Tomas 
286164769240SAlex Tomas /*
2862ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
2863ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
2864ac27a0ecSDave Kleikamp  *
2865ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
2866617ba13bSMingming Cao  * journal.  If somebody makes a swapfile on an ext4 data-journaling
2867ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
2868ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
2869ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
2870ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
2871ac27a0ecSDave Kleikamp  *
2872ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
2873ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
2874ac27a0ecSDave Kleikamp  */
2875617ba13bSMingming Cao static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2876ac27a0ecSDave Kleikamp {
2877ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
2878ac27a0ecSDave Kleikamp 	journal_t *journal;
2879ac27a0ecSDave Kleikamp 	int err;
2880ac27a0ecSDave Kleikamp 
288146c7f254STao Ma 	/*
288246c7f254STao Ma 	 * We can get here for an inline file via the FIBMAP ioctl
288346c7f254STao Ma 	 */
288446c7f254STao Ma 	if (ext4_has_inline_data(inode))
288546c7f254STao Ma 		return 0;
288646c7f254STao Ma 
288764769240SAlex Tomas 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
288864769240SAlex Tomas 			test_opt(inode->i_sb, DELALLOC)) {
288964769240SAlex Tomas 		/*
289064769240SAlex Tomas 		 * With delalloc we want to sync the file
289164769240SAlex Tomas 		 * so that we can make sure we allocate
289264769240SAlex Tomas 		 * blocks for file
289364769240SAlex Tomas 		 */
289464769240SAlex Tomas 		filemap_write_and_wait(mapping);
289564769240SAlex Tomas 	}
289664769240SAlex Tomas 
289719f5fb7aSTheodore Ts'o 	if (EXT4_JOURNAL(inode) &&
289819f5fb7aSTheodore Ts'o 	    ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2899ac27a0ecSDave Kleikamp 		/*
2900ac27a0ecSDave Kleikamp 		 * This is a REALLY heavyweight approach, but the use of
2901ac27a0ecSDave Kleikamp 		 * bmap on dirty files is expected to be extremely rare:
2902ac27a0ecSDave Kleikamp 		 * only if we run lilo or swapon on a freshly made file
2903ac27a0ecSDave Kleikamp 		 * do we expect this to happen.
2904ac27a0ecSDave Kleikamp 		 *
2905ac27a0ecSDave Kleikamp 		 * (bmap requires CAP_SYS_RAWIO so this does not
2906ac27a0ecSDave Kleikamp 		 * represent an unprivileged user DOS attack --- we'd be
2907ac27a0ecSDave Kleikamp 		 * in trouble if mortal users could trigger this path at
2908ac27a0ecSDave Kleikamp 		 * will.)
2909ac27a0ecSDave Kleikamp 		 *
2910617ba13bSMingming Cao 		 * NB. EXT4_STATE_JDATA is not set on files other than
2911ac27a0ecSDave Kleikamp 		 * regular files.  If somebody wants to bmap a directory
2912ac27a0ecSDave Kleikamp 		 * or symlink and gets confused because the buffer
2913ac27a0ecSDave Kleikamp 		 * hasn't yet been flushed to disk, they deserve
2914ac27a0ecSDave Kleikamp 		 * everything they get.
2915ac27a0ecSDave Kleikamp 		 */
2916ac27a0ecSDave Kleikamp 
291719f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2918617ba13bSMingming Cao 		journal = EXT4_JOURNAL(inode);
2919dab291afSMingming Cao 		jbd2_journal_lock_updates(journal);
2920dab291afSMingming Cao 		err = jbd2_journal_flush(journal);
2921dab291afSMingming Cao 		jbd2_journal_unlock_updates(journal);
2922ac27a0ecSDave Kleikamp 
2923ac27a0ecSDave Kleikamp 		if (err)
2924ac27a0ecSDave Kleikamp 			return 0;
2925ac27a0ecSDave Kleikamp 	}
2926ac27a0ecSDave Kleikamp 
2927617ba13bSMingming Cao 	return generic_block_bmap(mapping, block, ext4_get_block);
2928ac27a0ecSDave Kleikamp }
2929ac27a0ecSDave Kleikamp 
2930617ba13bSMingming Cao static int ext4_readpage(struct file *file, struct page *page)
2931ac27a0ecSDave Kleikamp {
293246c7f254STao Ma 	int ret = -EAGAIN;
293346c7f254STao Ma 	struct inode *inode = page->mapping->host;
293446c7f254STao Ma 
29350562e0baSJiaying Zhang 	trace_ext4_readpage(page);
293646c7f254STao Ma 
293746c7f254STao Ma 	if (ext4_has_inline_data(inode))
293846c7f254STao Ma 		ret = ext4_readpage_inline(inode, page);
293946c7f254STao Ma 
294046c7f254STao Ma 	if (ret == -EAGAIN)
2941617ba13bSMingming Cao 		return mpage_readpage(page, ext4_get_block);
294246c7f254STao Ma 
294346c7f254STao Ma 	return ret;
2944ac27a0ecSDave Kleikamp }
2945ac27a0ecSDave Kleikamp 
2946ac27a0ecSDave Kleikamp static int
2947617ba13bSMingming Cao ext4_readpages(struct file *file, struct address_space *mapping,
2948ac27a0ecSDave Kleikamp 		struct list_head *pages, unsigned nr_pages)
2949ac27a0ecSDave Kleikamp {
295046c7f254STao Ma 	struct inode *inode = mapping->host;
295146c7f254STao Ma 
295246c7f254STao Ma 	/* If the file has inline data, no need to do readpages. */
295346c7f254STao Ma 	if (ext4_has_inline_data(inode))
295446c7f254STao Ma 		return 0;
295546c7f254STao Ma 
2956617ba13bSMingming Cao 	return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2957ac27a0ecSDave Kleikamp }
2958ac27a0ecSDave Kleikamp 
2959d47992f8SLukas Czerner static void ext4_invalidatepage(struct page *page, unsigned int offset,
2960d47992f8SLukas Czerner 				unsigned int length)
2961ac27a0ecSDave Kleikamp {
2962ca99fdd2SLukas Czerner 	trace_ext4_invalidatepage(page, offset, length);
29630562e0baSJiaying Zhang 
29644520fb3cSJan Kara 	/* No journalling happens on data buffers when this function is used */
29654520fb3cSJan Kara 	WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
29664520fb3cSJan Kara 
2967ca99fdd2SLukas Czerner 	block_invalidatepage(page, offset, length);
29684520fb3cSJan Kara }
29694520fb3cSJan Kara 
297053e87268SJan Kara static int __ext4_journalled_invalidatepage(struct page *page,
2971ca99fdd2SLukas Czerner 					    unsigned int offset,
2972ca99fdd2SLukas Czerner 					    unsigned int length)
29734520fb3cSJan Kara {
29744520fb3cSJan Kara 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
29754520fb3cSJan Kara 
2976ca99fdd2SLukas Czerner 	trace_ext4_journalled_invalidatepage(page, offset, length);
29774520fb3cSJan Kara 
2978744692dcSJiaying Zhang 	/*
2979ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
2980ac27a0ecSDave Kleikamp 	 */
2981ca99fdd2SLukas Czerner 	if (offset == 0 && length == PAGE_CACHE_SIZE)
2982ac27a0ecSDave Kleikamp 		ClearPageChecked(page);
2983ac27a0ecSDave Kleikamp 
2984ca99fdd2SLukas Czerner 	return jbd2_journal_invalidatepage(journal, page, offset, length);
298553e87268SJan Kara }
298653e87268SJan Kara 
298753e87268SJan Kara /* Wrapper for aops... */
298853e87268SJan Kara static void ext4_journalled_invalidatepage(struct page *page,
2989d47992f8SLukas Czerner 					   unsigned int offset,
2990d47992f8SLukas Czerner 					   unsigned int length)
299153e87268SJan Kara {
2992ca99fdd2SLukas Czerner 	WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
2993ac27a0ecSDave Kleikamp }
2994ac27a0ecSDave Kleikamp 
2995617ba13bSMingming Cao static int ext4_releasepage(struct page *page, gfp_t wait)
2996ac27a0ecSDave Kleikamp {
2997617ba13bSMingming Cao 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2998ac27a0ecSDave Kleikamp 
29990562e0baSJiaying Zhang 	trace_ext4_releasepage(page);
30000562e0baSJiaying Zhang 
3001e1c36595SJan Kara 	/* Page has dirty journalled data -> cannot release */
3002e1c36595SJan Kara 	if (PageChecked(page))
3003ac27a0ecSDave Kleikamp 		return 0;
30040390131bSFrank Mayhar 	if (journal)
3005dab291afSMingming Cao 		return jbd2_journal_try_to_free_buffers(journal, page, wait);
30060390131bSFrank Mayhar 	else
30070390131bSFrank Mayhar 		return try_to_free_buffers(page);
3008ac27a0ecSDave Kleikamp }
3009ac27a0ecSDave Kleikamp 
3010ac27a0ecSDave Kleikamp /*
30112ed88685STheodore Ts'o  * ext4_get_block used when preparing for a DIO write or buffer write.
30122ed88685STheodore Ts'o  * We allocate an uinitialized extent if blocks haven't been allocated.
30132ed88685STheodore Ts'o  * The extent will be converted to initialized after the IO is complete.
30142ed88685STheodore Ts'o  */
3015f19d5870STao Ma int ext4_get_block_write(struct inode *inode, sector_t iblock,
30164c0425ffSMingming Cao 		   struct buffer_head *bh_result, int create)
30174c0425ffSMingming Cao {
3018c7064ef1SJiaying Zhang 	ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
30198d5d02e6SMingming Cao 		   inode->i_ino, create);
30202ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh_result,
30212ed88685STheodore Ts'o 			       EXT4_GET_BLOCKS_IO_CREATE_EXT);
30224c0425ffSMingming Cao }
30234c0425ffSMingming Cao 
3024729f52c6SZheng Liu static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
30258b0f165fSAnatol Pomozov 		   struct buffer_head *bh_result, int create)
3026729f52c6SZheng Liu {
30278b0f165fSAnatol Pomozov 	ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
30288b0f165fSAnatol Pomozov 		   inode->i_ino, create);
30298b0f165fSAnatol Pomozov 	return _ext4_get_block(inode, iblock, bh_result,
30308b0f165fSAnatol Pomozov 			       EXT4_GET_BLOCKS_NO_LOCK);
3031729f52c6SZheng Liu }
3032729f52c6SZheng Liu 
30334c0425ffSMingming Cao static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
30347b7a8665SChristoph Hellwig 			    ssize_t size, void *private)
30354c0425ffSMingming Cao {
30364c0425ffSMingming Cao         ext4_io_end_t *io_end = iocb->private;
30374c0425ffSMingming Cao 
303897a851edSJan Kara 	/* if not async direct IO just return */
30397b7a8665SChristoph Hellwig 	if (!io_end)
304097a851edSJan Kara 		return;
30414b70df18SMingming 
30428d5d02e6SMingming Cao 	ext_debug("ext4_end_io_dio(): io_end 0x%p "
3043ace36ad4SJoe Perches 		  "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
30448d5d02e6SMingming Cao  		  iocb->private, io_end->inode->i_ino, iocb, offset,
30458d5d02e6SMingming Cao 		  size);
30468d5d02e6SMingming Cao 
3047b5a7e970STheodore Ts'o 	iocb->private = NULL;
30484c0425ffSMingming Cao 	io_end->offset = offset;
30494c0425ffSMingming Cao 	io_end->size = size;
30507b7a8665SChristoph Hellwig 	ext4_put_io_end(io_end);
30514c0425ffSMingming Cao }
3052c7064ef1SJiaying Zhang 
30534c0425ffSMingming Cao /*
30544c0425ffSMingming Cao  * For ext4 extent files, ext4 will do direct-io write to holes,
30554c0425ffSMingming Cao  * preallocated extents, and those write extend the file, no need to
30564c0425ffSMingming Cao  * fall back to buffered IO.
30574c0425ffSMingming Cao  *
3058b595076aSUwe Kleine-König  * For holes, we fallocate those blocks, mark them as uninitialized
305969c499d1STheodore Ts'o  * If those blocks were preallocated, we mark sure they are split, but
3060b595076aSUwe Kleine-König  * still keep the range to write as uninitialized.
30614c0425ffSMingming Cao  *
306269c499d1STheodore Ts'o  * The unwritten extents will be converted to written when DIO is completed.
30638d5d02e6SMingming Cao  * For async direct IO, since the IO may still pending when return, we
306425985edcSLucas De Marchi  * set up an end_io call back function, which will do the conversion
30658d5d02e6SMingming Cao  * when async direct IO completed.
30664c0425ffSMingming Cao  *
30674c0425ffSMingming Cao  * If the O_DIRECT write will extend the file then add this inode to the
30684c0425ffSMingming Cao  * orphan list.  So recovery will truncate it back to the original size
30694c0425ffSMingming Cao  * if the machine crashes during the write.
30704c0425ffSMingming Cao  *
30714c0425ffSMingming Cao  */
30724c0425ffSMingming Cao static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
30734c0425ffSMingming Cao 			      const struct iovec *iov, loff_t offset,
30744c0425ffSMingming Cao 			      unsigned long nr_segs)
30754c0425ffSMingming Cao {
30764c0425ffSMingming Cao 	struct file *file = iocb->ki_filp;
30774c0425ffSMingming Cao 	struct inode *inode = file->f_mapping->host;
30784c0425ffSMingming Cao 	ssize_t ret;
30794c0425ffSMingming Cao 	size_t count = iov_length(iov, nr_segs);
3080729f52c6SZheng Liu 	int overwrite = 0;
30818b0f165fSAnatol Pomozov 	get_block_t *get_block_func = NULL;
30828b0f165fSAnatol Pomozov 	int dio_flags = 0;
308369c499d1STheodore Ts'o 	loff_t final_size = offset + count;
308497a851edSJan Kara 	ext4_io_end_t *io_end = NULL;
308569c499d1STheodore Ts'o 
308669c499d1STheodore Ts'o 	/* Use the old path for reads and writes beyond i_size. */
308769c499d1STheodore Ts'o 	if (rw != WRITE || final_size > inode->i_size)
308869c499d1STheodore Ts'o 		return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3089729f52c6SZheng Liu 
30904bd809dbSZheng Liu 	BUG_ON(iocb->private == NULL);
30914bd809dbSZheng Liu 
3092e8340395SJan Kara 	/*
3093e8340395SJan Kara 	 * Make all waiters for direct IO properly wait also for extent
3094e8340395SJan Kara 	 * conversion. This also disallows race between truncate() and
3095e8340395SJan Kara 	 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3096e8340395SJan Kara 	 */
3097e8340395SJan Kara 	if (rw == WRITE)
3098e8340395SJan Kara 		atomic_inc(&inode->i_dio_count);
3099e8340395SJan Kara 
31004bd809dbSZheng Liu 	/* If we do a overwrite dio, i_mutex locking can be released */
31014bd809dbSZheng Liu 	overwrite = *((int *)iocb->private);
31024bd809dbSZheng Liu 
31034bd809dbSZheng Liu 	if (overwrite) {
31044bd809dbSZheng Liu 		down_read(&EXT4_I(inode)->i_data_sem);
31054bd809dbSZheng Liu 		mutex_unlock(&inode->i_mutex);
31064bd809dbSZheng Liu 	}
31074bd809dbSZheng Liu 
31084c0425ffSMingming Cao 	/*
31098d5d02e6SMingming Cao 	 * We could direct write to holes and fallocate.
31108d5d02e6SMingming Cao 	 *
311169c499d1STheodore Ts'o 	 * Allocated blocks to fill the hole are marked as
311269c499d1STheodore Ts'o 	 * uninitialized to prevent parallel buffered read to expose
311369c499d1STheodore Ts'o 	 * the stale data before DIO complete the data IO.
31148d5d02e6SMingming Cao 	 *
311569c499d1STheodore Ts'o 	 * As to previously fallocated extents, ext4 get_block will
311669c499d1STheodore Ts'o 	 * just simply mark the buffer mapped but still keep the
311769c499d1STheodore Ts'o 	 * extents uninitialized.
31184c0425ffSMingming Cao 	 *
311969c499d1STheodore Ts'o 	 * For non AIO case, we will convert those unwritten extents
31208d5d02e6SMingming Cao 	 * to written after return back from blockdev_direct_IO.
31214c0425ffSMingming Cao 	 *
312269c499d1STheodore Ts'o 	 * For async DIO, the conversion needs to be deferred when the
312369c499d1STheodore Ts'o 	 * IO is completed. The ext4 end_io callback function will be
312469c499d1STheodore Ts'o 	 * called to take care of the conversion work.  Here for async
312569c499d1STheodore Ts'o 	 * case, we allocate an io_end structure to hook to the iocb.
31264c0425ffSMingming Cao 	 */
31278d5d02e6SMingming Cao 	iocb->private = NULL;
3128f45ee3a1SDmitry Monakhov 	ext4_inode_aio_set(inode, NULL);
31298d5d02e6SMingming Cao 	if (!is_sync_kiocb(iocb)) {
313097a851edSJan Kara 		io_end = ext4_init_io_end(inode, GFP_NOFS);
31314bd809dbSZheng Liu 		if (!io_end) {
31324bd809dbSZheng Liu 			ret = -ENOMEM;
31334bd809dbSZheng Liu 			goto retake_lock;
31344bd809dbSZheng Liu 		}
313597a851edSJan Kara 		/*
313697a851edSJan Kara 		 * Grab reference for DIO. Will be dropped in ext4_end_io_dio()
313797a851edSJan Kara 		 */
313897a851edSJan Kara 		iocb->private = ext4_get_io_end(io_end);
31398d5d02e6SMingming Cao 		/*
314069c499d1STheodore Ts'o 		 * we save the io structure for current async direct
314169c499d1STheodore Ts'o 		 * IO, so that later ext4_map_blocks() could flag the
314269c499d1STheodore Ts'o 		 * io structure whether there is a unwritten extents
314369c499d1STheodore Ts'o 		 * needs to be converted when IO is completed.
31448d5d02e6SMingming Cao 		 */
3145f45ee3a1SDmitry Monakhov 		ext4_inode_aio_set(inode, io_end);
31468d5d02e6SMingming Cao 	}
31478d5d02e6SMingming Cao 
31488b0f165fSAnatol Pomozov 	if (overwrite) {
31498b0f165fSAnatol Pomozov 		get_block_func = ext4_get_block_write_nolock;
31508b0f165fSAnatol Pomozov 	} else {
31518b0f165fSAnatol Pomozov 		get_block_func = ext4_get_block_write;
31528b0f165fSAnatol Pomozov 		dio_flags = DIO_LOCKING;
31538b0f165fSAnatol Pomozov 	}
3154729f52c6SZheng Liu 	ret = __blockdev_direct_IO(rw, iocb, inode,
3155729f52c6SZheng Liu 				   inode->i_sb->s_bdev, iov,
3156729f52c6SZheng Liu 				   offset, nr_segs,
31578b0f165fSAnatol Pomozov 				   get_block_func,
3158729f52c6SZheng Liu 				   ext4_end_io_dio,
3159729f52c6SZheng Liu 				   NULL,
31608b0f165fSAnatol Pomozov 				   dio_flags);
31618b0f165fSAnatol Pomozov 
31624eec708dSJan Kara 	/*
316397a851edSJan Kara 	 * Put our reference to io_end. This can free the io_end structure e.g.
316497a851edSJan Kara 	 * in sync IO case or in case of error. It can even perform extent
316597a851edSJan Kara 	 * conversion if all bios we submitted finished before we got here.
316697a851edSJan Kara 	 * Note that in that case iocb->private can be already set to NULL
316797a851edSJan Kara 	 * here.
31684eec708dSJan Kara 	 */
316997a851edSJan Kara 	if (io_end) {
317097a851edSJan Kara 		ext4_inode_aio_set(inode, NULL);
317197a851edSJan Kara 		ext4_put_io_end(io_end);
317297a851edSJan Kara 		/*
317397a851edSJan Kara 		 * When no IO was submitted ext4_end_io_dio() was not
317497a851edSJan Kara 		 * called so we have to put iocb's reference.
317597a851edSJan Kara 		 */
317697a851edSJan Kara 		if (ret <= 0 && ret != -EIOCBQUEUED && iocb->private) {
317797a851edSJan Kara 			WARN_ON(iocb->private != io_end);
317897a851edSJan Kara 			WARN_ON(io_end->flag & EXT4_IO_END_UNWRITTEN);
317997a851edSJan Kara 			ext4_put_io_end(io_end);
31808d5d02e6SMingming Cao 			iocb->private = NULL;
318197a851edSJan Kara 		}
318297a851edSJan Kara 	}
318397a851edSJan Kara 	if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
31845f524950SMingming 						EXT4_STATE_DIO_UNWRITTEN)) {
3185109f5565SMingming 		int err;
31868d5d02e6SMingming Cao 		/*
31878d5d02e6SMingming Cao 		 * for non AIO case, since the IO is already
318825985edcSLucas De Marchi 		 * completed, we could do the conversion right here
31898d5d02e6SMingming Cao 		 */
31906b523df4SJan Kara 		err = ext4_convert_unwritten_extents(NULL, inode,
31918d5d02e6SMingming Cao 						     offset, ret);
3192109f5565SMingming 		if (err < 0)
3193109f5565SMingming 			ret = err;
319419f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3195109f5565SMingming 	}
31964bd809dbSZheng Liu 
31974bd809dbSZheng Liu retake_lock:
3198e8340395SJan Kara 	if (rw == WRITE)
3199e8340395SJan Kara 		inode_dio_done(inode);
32004bd809dbSZheng Liu 	/* take i_mutex locking again if we do a ovewrite dio */
32014bd809dbSZheng Liu 	if (overwrite) {
32024bd809dbSZheng Liu 		up_read(&EXT4_I(inode)->i_data_sem);
32034bd809dbSZheng Liu 		mutex_lock(&inode->i_mutex);
32044bd809dbSZheng Liu 	}
32054bd809dbSZheng Liu 
32064c0425ffSMingming Cao 	return ret;
32074c0425ffSMingming Cao }
32088d5d02e6SMingming Cao 
32094c0425ffSMingming Cao static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
32104c0425ffSMingming Cao 			      const struct iovec *iov, loff_t offset,
32114c0425ffSMingming Cao 			      unsigned long nr_segs)
32124c0425ffSMingming Cao {
32134c0425ffSMingming Cao 	struct file *file = iocb->ki_filp;
32144c0425ffSMingming Cao 	struct inode *inode = file->f_mapping->host;
32150562e0baSJiaying Zhang 	ssize_t ret;
32164c0425ffSMingming Cao 
321784ebd795STheodore Ts'o 	/*
321884ebd795STheodore Ts'o 	 * If we are doing data journalling we don't support O_DIRECT
321984ebd795STheodore Ts'o 	 */
322084ebd795STheodore Ts'o 	if (ext4_should_journal_data(inode))
322184ebd795STheodore Ts'o 		return 0;
322284ebd795STheodore Ts'o 
322346c7f254STao Ma 	/* Let buffer I/O handle the inline data case. */
322446c7f254STao Ma 	if (ext4_has_inline_data(inode))
322546c7f254STao Ma 		return 0;
322646c7f254STao Ma 
32270562e0baSJiaying Zhang 	trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
322812e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
32290562e0baSJiaying Zhang 		ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
32300562e0baSJiaying Zhang 	else
32310562e0baSJiaying Zhang 		ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
32320562e0baSJiaying Zhang 	trace_ext4_direct_IO_exit(inode, offset,
32330562e0baSJiaying Zhang 				iov_length(iov, nr_segs), rw, ret);
32340562e0baSJiaying Zhang 	return ret;
32354c0425ffSMingming Cao }
32364c0425ffSMingming Cao 
3237ac27a0ecSDave Kleikamp /*
3238617ba13bSMingming Cao  * Pages can be marked dirty completely asynchronously from ext4's journalling
3239ac27a0ecSDave Kleikamp  * activity.  By filemap_sync_pte(), try_to_unmap_one(), etc.  We cannot do
3240ac27a0ecSDave Kleikamp  * much here because ->set_page_dirty is called under VFS locks.  The page is
3241ac27a0ecSDave Kleikamp  * not necessarily locked.
3242ac27a0ecSDave Kleikamp  *
3243ac27a0ecSDave Kleikamp  * We cannot just dirty the page and leave attached buffers clean, because the
3244ac27a0ecSDave Kleikamp  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3245ac27a0ecSDave Kleikamp  * or jbddirty because all the journalling code will explode.
3246ac27a0ecSDave Kleikamp  *
3247ac27a0ecSDave Kleikamp  * So what we do is to mark the page "pending dirty" and next time writepage
3248ac27a0ecSDave Kleikamp  * is called, propagate that into the buffers appropriately.
3249ac27a0ecSDave Kleikamp  */
3250617ba13bSMingming Cao static int ext4_journalled_set_page_dirty(struct page *page)
3251ac27a0ecSDave Kleikamp {
3252ac27a0ecSDave Kleikamp 	SetPageChecked(page);
3253ac27a0ecSDave Kleikamp 	return __set_page_dirty_nobuffers(page);
3254ac27a0ecSDave Kleikamp }
3255ac27a0ecSDave Kleikamp 
325674d553aaSTheodore Ts'o static const struct address_space_operations ext4_aops = {
3257617ba13bSMingming Cao 	.readpage		= ext4_readpage,
3258617ba13bSMingming Cao 	.readpages		= ext4_readpages,
325943ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
326020970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3261bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
326274d553aaSTheodore Ts'o 	.write_end		= ext4_write_end,
3263617ba13bSMingming Cao 	.bmap			= ext4_bmap,
3264617ba13bSMingming Cao 	.invalidatepage		= ext4_invalidatepage,
3265617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
3266617ba13bSMingming Cao 	.direct_IO		= ext4_direct_IO,
3267ac27a0ecSDave Kleikamp 	.migratepage		= buffer_migrate_page,
32688ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3269aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
3270ac27a0ecSDave Kleikamp };
3271ac27a0ecSDave Kleikamp 
3272617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
3273617ba13bSMingming Cao 	.readpage		= ext4_readpage,
3274617ba13bSMingming Cao 	.readpages		= ext4_readpages,
327543ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
327620970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
3277bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
3278bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
3279617ba13bSMingming Cao 	.set_page_dirty		= ext4_journalled_set_page_dirty,
3280617ba13bSMingming Cao 	.bmap			= ext4_bmap,
32814520fb3cSJan Kara 	.invalidatepage		= ext4_journalled_invalidatepage,
3282617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
328384ebd795STheodore Ts'o 	.direct_IO		= ext4_direct_IO,
32848ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3285aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
3286ac27a0ecSDave Kleikamp };
3287ac27a0ecSDave Kleikamp 
328864769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
328964769240SAlex Tomas 	.readpage		= ext4_readpage,
329064769240SAlex Tomas 	.readpages		= ext4_readpages,
329143ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
329220970ba6STheodore Ts'o 	.writepages		= ext4_writepages,
329364769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
329464769240SAlex Tomas 	.write_end		= ext4_da_write_end,
329564769240SAlex Tomas 	.bmap			= ext4_bmap,
329664769240SAlex Tomas 	.invalidatepage		= ext4_da_invalidatepage,
329764769240SAlex Tomas 	.releasepage		= ext4_releasepage,
329864769240SAlex Tomas 	.direct_IO		= ext4_direct_IO,
329964769240SAlex Tomas 	.migratepage		= buffer_migrate_page,
33008ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
3301aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
330264769240SAlex Tomas };
330364769240SAlex Tomas 
3304617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
3305ac27a0ecSDave Kleikamp {
33063d2b1582SLukas Czerner 	switch (ext4_inode_journal_mode(inode)) {
33073d2b1582SLukas Czerner 	case EXT4_INODE_ORDERED_DATA_MODE:
330874d553aaSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE);
33093d2b1582SLukas Czerner 		break;
33103d2b1582SLukas Czerner 	case EXT4_INODE_WRITEBACK_DATA_MODE:
331174d553aaSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE);
33123d2b1582SLukas Czerner 		break;
33133d2b1582SLukas Czerner 	case EXT4_INODE_JOURNAL_DATA_MODE:
3314617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
331574d553aaSTheodore Ts'o 		return;
33163d2b1582SLukas Czerner 	default:
33173d2b1582SLukas Czerner 		BUG();
33183d2b1582SLukas Czerner 	}
331974d553aaSTheodore Ts'o 	if (test_opt(inode->i_sb, DELALLOC))
332074d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_da_aops;
332174d553aaSTheodore Ts'o 	else
332274d553aaSTheodore Ts'o 		inode->i_mapping->a_ops = &ext4_aops;
3323ac27a0ecSDave Kleikamp }
3324ac27a0ecSDave Kleikamp 
3325d863dc36SLukas Czerner /*
3326d863dc36SLukas Czerner  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3327d863dc36SLukas Czerner  * up to the end of the block which corresponds to `from'.
3328d863dc36SLukas Czerner  * This required during truncate. We need to physically zero the tail end
3329d863dc36SLukas Czerner  * of that block so it doesn't yield old data if the file is later grown.
3330d863dc36SLukas Czerner  */
3331d863dc36SLukas Czerner int ext4_block_truncate_page(handle_t *handle,
3332d863dc36SLukas Czerner 		struct address_space *mapping, loff_t from)
3333d863dc36SLukas Czerner {
3334d863dc36SLukas Czerner 	unsigned offset = from & (PAGE_CACHE_SIZE-1);
3335d863dc36SLukas Czerner 	unsigned length;
3336d863dc36SLukas Czerner 	unsigned blocksize;
3337d863dc36SLukas Czerner 	struct inode *inode = mapping->host;
3338d863dc36SLukas Czerner 
3339d863dc36SLukas Czerner 	blocksize = inode->i_sb->s_blocksize;
3340d863dc36SLukas Czerner 	length = blocksize - (offset & (blocksize - 1));
3341d863dc36SLukas Czerner 
3342d863dc36SLukas Czerner 	return ext4_block_zero_page_range(handle, mapping, from, length);
3343d863dc36SLukas Czerner }
3344d863dc36SLukas Czerner 
3345d863dc36SLukas Czerner /*
3346d863dc36SLukas Czerner  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3347d863dc36SLukas Czerner  * starting from file offset 'from'.  The range to be zero'd must
3348d863dc36SLukas Czerner  * be contained with in one block.  If the specified range exceeds
3349d863dc36SLukas Czerner  * the end of the block it will be shortened to end of the block
3350d863dc36SLukas Czerner  * that cooresponds to 'from'
3351d863dc36SLukas Czerner  */
3352d863dc36SLukas Czerner int ext4_block_zero_page_range(handle_t *handle,
3353d863dc36SLukas Czerner 		struct address_space *mapping, loff_t from, loff_t length)
3354d863dc36SLukas Czerner {
3355d863dc36SLukas Czerner 	ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3356d863dc36SLukas Czerner 	unsigned offset = from & (PAGE_CACHE_SIZE-1);
3357d863dc36SLukas Czerner 	unsigned blocksize, max, pos;
3358d863dc36SLukas Czerner 	ext4_lblk_t iblock;
3359d863dc36SLukas Czerner 	struct inode *inode = mapping->host;
3360d863dc36SLukas Czerner 	struct buffer_head *bh;
3361d863dc36SLukas Czerner 	struct page *page;
3362d863dc36SLukas Czerner 	int err = 0;
3363d863dc36SLukas Czerner 
3364d863dc36SLukas Czerner 	page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3365d863dc36SLukas Czerner 				   mapping_gfp_mask(mapping) & ~__GFP_FS);
3366d863dc36SLukas Czerner 	if (!page)
3367d863dc36SLukas Czerner 		return -ENOMEM;
3368d863dc36SLukas Czerner 
3369d863dc36SLukas Czerner 	blocksize = inode->i_sb->s_blocksize;
3370d863dc36SLukas Czerner 	max = blocksize - (offset & (blocksize - 1));
3371d863dc36SLukas Czerner 
3372d863dc36SLukas Czerner 	/*
3373d863dc36SLukas Czerner 	 * correct length if it does not fall between
3374d863dc36SLukas Czerner 	 * 'from' and the end of the block
3375d863dc36SLukas Czerner 	 */
3376d863dc36SLukas Czerner 	if (length > max || length < 0)
3377d863dc36SLukas Czerner 		length = max;
3378d863dc36SLukas Czerner 
3379d863dc36SLukas Czerner 	iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3380d863dc36SLukas Czerner 
3381d863dc36SLukas Czerner 	if (!page_has_buffers(page))
3382d863dc36SLukas Czerner 		create_empty_buffers(page, blocksize, 0);
3383d863dc36SLukas Czerner 
3384d863dc36SLukas Czerner 	/* Find the buffer that contains "offset" */
3385d863dc36SLukas Czerner 	bh = page_buffers(page);
3386d863dc36SLukas Czerner 	pos = blocksize;
3387d863dc36SLukas Czerner 	while (offset >= pos) {
3388d863dc36SLukas Czerner 		bh = bh->b_this_page;
3389d863dc36SLukas Czerner 		iblock++;
3390d863dc36SLukas Czerner 		pos += blocksize;
3391d863dc36SLukas Czerner 	}
3392d863dc36SLukas Czerner 	if (buffer_freed(bh)) {
3393d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "freed: skip");
3394d863dc36SLukas Czerner 		goto unlock;
3395d863dc36SLukas Czerner 	}
3396d863dc36SLukas Czerner 	if (!buffer_mapped(bh)) {
3397d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "unmapped");
3398d863dc36SLukas Czerner 		ext4_get_block(inode, iblock, bh, 0);
3399d863dc36SLukas Czerner 		/* unmapped? It's a hole - nothing to do */
3400d863dc36SLukas Czerner 		if (!buffer_mapped(bh)) {
3401d863dc36SLukas Czerner 			BUFFER_TRACE(bh, "still unmapped");
3402d863dc36SLukas Czerner 			goto unlock;
3403d863dc36SLukas Czerner 		}
3404d863dc36SLukas Czerner 	}
3405d863dc36SLukas Czerner 
3406d863dc36SLukas Czerner 	/* Ok, it's mapped. Make sure it's up-to-date */
3407d863dc36SLukas Czerner 	if (PageUptodate(page))
3408d863dc36SLukas Czerner 		set_buffer_uptodate(bh);
3409d863dc36SLukas Czerner 
3410d863dc36SLukas Czerner 	if (!buffer_uptodate(bh)) {
3411d863dc36SLukas Czerner 		err = -EIO;
3412d863dc36SLukas Czerner 		ll_rw_block(READ, 1, &bh);
3413d863dc36SLukas Czerner 		wait_on_buffer(bh);
3414d863dc36SLukas Czerner 		/* Uhhuh. Read error. Complain and punt. */
3415d863dc36SLukas Czerner 		if (!buffer_uptodate(bh))
3416d863dc36SLukas Czerner 			goto unlock;
3417d863dc36SLukas Czerner 	}
3418d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3419d863dc36SLukas Czerner 		BUFFER_TRACE(bh, "get write access");
3420d863dc36SLukas Czerner 		err = ext4_journal_get_write_access(handle, bh);
3421d863dc36SLukas Czerner 		if (err)
3422d863dc36SLukas Czerner 			goto unlock;
3423d863dc36SLukas Czerner 	}
3424d863dc36SLukas Czerner 	zero_user(page, offset, length);
3425d863dc36SLukas Czerner 	BUFFER_TRACE(bh, "zeroed end of block");
3426d863dc36SLukas Czerner 
3427d863dc36SLukas Czerner 	if (ext4_should_journal_data(inode)) {
3428d863dc36SLukas Czerner 		err = ext4_handle_dirty_metadata(handle, inode, bh);
34290713ed0cSLukas Czerner 	} else {
3430353eefd3Sjon ernst 		err = 0;
3431d863dc36SLukas Czerner 		mark_buffer_dirty(bh);
34320713ed0cSLukas Czerner 		if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE))
34330713ed0cSLukas Czerner 			err = ext4_jbd2_file_inode(handle, inode);
34340713ed0cSLukas Czerner 	}
3435d863dc36SLukas Czerner 
3436d863dc36SLukas Czerner unlock:
3437d863dc36SLukas Czerner 	unlock_page(page);
3438d863dc36SLukas Czerner 	page_cache_release(page);
3439d863dc36SLukas Czerner 	return err;
3440d863dc36SLukas Czerner }
3441d863dc36SLukas Czerner 
3442a87dd18cSLukas Czerner int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3443a87dd18cSLukas Czerner 			     loff_t lstart, loff_t length)
3444a87dd18cSLukas Czerner {
3445a87dd18cSLukas Czerner 	struct super_block *sb = inode->i_sb;
3446a87dd18cSLukas Czerner 	struct address_space *mapping = inode->i_mapping;
3447e1be3a92SLukas Czerner 	unsigned partial_start, partial_end;
3448a87dd18cSLukas Czerner 	ext4_fsblk_t start, end;
3449a87dd18cSLukas Czerner 	loff_t byte_end = (lstart + length - 1);
3450a87dd18cSLukas Czerner 	int err = 0;
3451a87dd18cSLukas Czerner 
3452e1be3a92SLukas Czerner 	partial_start = lstart & (sb->s_blocksize - 1);
3453e1be3a92SLukas Czerner 	partial_end = byte_end & (sb->s_blocksize - 1);
3454e1be3a92SLukas Czerner 
3455a87dd18cSLukas Czerner 	start = lstart >> sb->s_blocksize_bits;
3456a87dd18cSLukas Czerner 	end = byte_end >> sb->s_blocksize_bits;
3457a87dd18cSLukas Czerner 
3458a87dd18cSLukas Czerner 	/* Handle partial zero within the single block */
3459e1be3a92SLukas Czerner 	if (start == end &&
3460e1be3a92SLukas Czerner 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3461a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3462a87dd18cSLukas Czerner 						 lstart, length);
3463a87dd18cSLukas Czerner 		return err;
3464a87dd18cSLukas Czerner 	}
3465a87dd18cSLukas Czerner 	/* Handle partial zero out on the start of the range */
3466e1be3a92SLukas Czerner 	if (partial_start) {
3467a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3468a87dd18cSLukas Czerner 						 lstart, sb->s_blocksize);
3469a87dd18cSLukas Czerner 		if (err)
3470a87dd18cSLukas Czerner 			return err;
3471a87dd18cSLukas Czerner 	}
3472a87dd18cSLukas Czerner 	/* Handle partial zero out on the end of the range */
3473e1be3a92SLukas Czerner 	if (partial_end != sb->s_blocksize - 1)
3474a87dd18cSLukas Czerner 		err = ext4_block_zero_page_range(handle, mapping,
3475e1be3a92SLukas Czerner 						 byte_end - partial_end,
3476e1be3a92SLukas Czerner 						 partial_end + 1);
3477a87dd18cSLukas Czerner 	return err;
3478a87dd18cSLukas Czerner }
3479a87dd18cSLukas Czerner 
348091ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
348191ef4cafSDuane Griffin {
348291ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
348391ef4cafSDuane Griffin 		return 1;
348491ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
348591ef4cafSDuane Griffin 		return 1;
348691ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
348791ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
348891ef4cafSDuane Griffin 	return 0;
348991ef4cafSDuane Griffin }
349091ef4cafSDuane Griffin 
3491ac27a0ecSDave Kleikamp /*
3492a4bb6b64SAllison Henderson  * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3493a4bb6b64SAllison Henderson  * associated with the given offset and length
3494a4bb6b64SAllison Henderson  *
3495a4bb6b64SAllison Henderson  * @inode:  File inode
3496a4bb6b64SAllison Henderson  * @offset: The offset where the hole will begin
3497a4bb6b64SAllison Henderson  * @len:    The length of the hole
3498a4bb6b64SAllison Henderson  *
34994907cb7bSAnatol Pomozov  * Returns: 0 on success or negative on failure
3500a4bb6b64SAllison Henderson  */
3501a4bb6b64SAllison Henderson 
3502aeb2817aSAshish Sangwan int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3503a4bb6b64SAllison Henderson {
350426a4c0c6STheodore Ts'o 	struct super_block *sb = inode->i_sb;
350526a4c0c6STheodore Ts'o 	ext4_lblk_t first_block, stop_block;
350626a4c0c6STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
3507a87dd18cSLukas Czerner 	loff_t first_block_offset, last_block_offset;
350826a4c0c6STheodore Ts'o 	handle_t *handle;
350926a4c0c6STheodore Ts'o 	unsigned int credits;
351026a4c0c6STheodore Ts'o 	int ret = 0;
351126a4c0c6STheodore Ts'o 
3512a4bb6b64SAllison Henderson 	if (!S_ISREG(inode->i_mode))
351373355192SAllison Henderson 		return -EOPNOTSUPP;
3514a4bb6b64SAllison Henderson 
3515b8a86845SLukas Czerner 	trace_ext4_punch_hole(inode, offset, length, 0);
3516aaddea81SZheng Liu 
351726a4c0c6STheodore Ts'o 	/*
351826a4c0c6STheodore Ts'o 	 * Write out all dirty pages to avoid race conditions
351926a4c0c6STheodore Ts'o 	 * Then release them.
352026a4c0c6STheodore Ts'o 	 */
352126a4c0c6STheodore Ts'o 	if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
352226a4c0c6STheodore Ts'o 		ret = filemap_write_and_wait_range(mapping, offset,
352326a4c0c6STheodore Ts'o 						   offset + length - 1);
352426a4c0c6STheodore Ts'o 		if (ret)
352526a4c0c6STheodore Ts'o 			return ret;
352626a4c0c6STheodore Ts'o 	}
352726a4c0c6STheodore Ts'o 
352826a4c0c6STheodore Ts'o 	mutex_lock(&inode->i_mutex);
352926a4c0c6STheodore Ts'o 	/* It's not possible punch hole on append only file */
353026a4c0c6STheodore Ts'o 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
353126a4c0c6STheodore Ts'o 		ret = -EPERM;
353226a4c0c6STheodore Ts'o 		goto out_mutex;
353326a4c0c6STheodore Ts'o 	}
353426a4c0c6STheodore Ts'o 	if (IS_SWAPFILE(inode)) {
353526a4c0c6STheodore Ts'o 		ret = -ETXTBSY;
353626a4c0c6STheodore Ts'o 		goto out_mutex;
353726a4c0c6STheodore Ts'o 	}
353826a4c0c6STheodore Ts'o 
353926a4c0c6STheodore Ts'o 	/* No need to punch hole beyond i_size */
354026a4c0c6STheodore Ts'o 	if (offset >= inode->i_size)
354126a4c0c6STheodore Ts'o 		goto out_mutex;
354226a4c0c6STheodore Ts'o 
354326a4c0c6STheodore Ts'o 	/*
354426a4c0c6STheodore Ts'o 	 * If the hole extends beyond i_size, set the hole
354526a4c0c6STheodore Ts'o 	 * to end after the page that contains i_size
354626a4c0c6STheodore Ts'o 	 */
354726a4c0c6STheodore Ts'o 	if (offset + length > inode->i_size) {
354826a4c0c6STheodore Ts'o 		length = inode->i_size +
354926a4c0c6STheodore Ts'o 		   PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
355026a4c0c6STheodore Ts'o 		   offset;
355126a4c0c6STheodore Ts'o 	}
355226a4c0c6STheodore Ts'o 
3553a361293fSJan Kara 	if (offset & (sb->s_blocksize - 1) ||
3554a361293fSJan Kara 	    (offset + length) & (sb->s_blocksize - 1)) {
3555a361293fSJan Kara 		/*
3556a361293fSJan Kara 		 * Attach jinode to inode for jbd2 if we do any zeroing of
3557a361293fSJan Kara 		 * partial block
3558a361293fSJan Kara 		 */
3559a361293fSJan Kara 		ret = ext4_inode_attach_jinode(inode);
3560a361293fSJan Kara 		if (ret < 0)
3561a361293fSJan Kara 			goto out_mutex;
3562a361293fSJan Kara 
3563a361293fSJan Kara 	}
3564a361293fSJan Kara 
3565a87dd18cSLukas Czerner 	first_block_offset = round_up(offset, sb->s_blocksize);
3566a87dd18cSLukas Czerner 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
356726a4c0c6STheodore Ts'o 
3568a87dd18cSLukas Czerner 	/* Now release the pages and zero block aligned part of pages*/
3569a87dd18cSLukas Czerner 	if (last_block_offset > first_block_offset)
3570a87dd18cSLukas Czerner 		truncate_pagecache_range(inode, first_block_offset,
3571a87dd18cSLukas Czerner 					 last_block_offset);
357226a4c0c6STheodore Ts'o 
357326a4c0c6STheodore Ts'o 	/* Wait all existing dio workers, newcomers will block on i_mutex */
357426a4c0c6STheodore Ts'o 	ext4_inode_block_unlocked_dio(inode);
357526a4c0c6STheodore Ts'o 	inode_dio_wait(inode);
357626a4c0c6STheodore Ts'o 
357726a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
357826a4c0c6STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
357926a4c0c6STheodore Ts'o 	else
358026a4c0c6STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
358126a4c0c6STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
358226a4c0c6STheodore Ts'o 	if (IS_ERR(handle)) {
358326a4c0c6STheodore Ts'o 		ret = PTR_ERR(handle);
358426a4c0c6STheodore Ts'o 		ext4_std_error(sb, ret);
358526a4c0c6STheodore Ts'o 		goto out_dio;
358626a4c0c6STheodore Ts'o 	}
358726a4c0c6STheodore Ts'o 
3588a87dd18cSLukas Czerner 	ret = ext4_zero_partial_blocks(handle, inode, offset,
3589a87dd18cSLukas Czerner 				       length);
359026a4c0c6STheodore Ts'o 	if (ret)
359126a4c0c6STheodore Ts'o 		goto out_stop;
359226a4c0c6STheodore Ts'o 
359326a4c0c6STheodore Ts'o 	first_block = (offset + sb->s_blocksize - 1) >>
359426a4c0c6STheodore Ts'o 		EXT4_BLOCK_SIZE_BITS(sb);
359526a4c0c6STheodore Ts'o 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
359626a4c0c6STheodore Ts'o 
359726a4c0c6STheodore Ts'o 	/* If there are no blocks to remove, return now */
359826a4c0c6STheodore Ts'o 	if (first_block >= stop_block)
359926a4c0c6STheodore Ts'o 		goto out_stop;
360026a4c0c6STheodore Ts'o 
360126a4c0c6STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
360226a4c0c6STheodore Ts'o 	ext4_discard_preallocations(inode);
360326a4c0c6STheodore Ts'o 
360426a4c0c6STheodore Ts'o 	ret = ext4_es_remove_extent(inode, first_block,
360526a4c0c6STheodore Ts'o 				    stop_block - first_block);
360626a4c0c6STheodore Ts'o 	if (ret) {
360726a4c0c6STheodore Ts'o 		up_write(&EXT4_I(inode)->i_data_sem);
360826a4c0c6STheodore Ts'o 		goto out_stop;
360926a4c0c6STheodore Ts'o 	}
361026a4c0c6STheodore Ts'o 
361126a4c0c6STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
361226a4c0c6STheodore Ts'o 		ret = ext4_ext_remove_space(inode, first_block,
361326a4c0c6STheodore Ts'o 					    stop_block - 1);
361426a4c0c6STheodore Ts'o 	else
361526a4c0c6STheodore Ts'o 		ret = ext4_free_hole_blocks(handle, inode, first_block,
361626a4c0c6STheodore Ts'o 					    stop_block);
361726a4c0c6STheodore Ts'o 
361826a4c0c6STheodore Ts'o 	ext4_discard_preallocations(inode);
3619819c4920STheodore Ts'o 	up_write(&EXT4_I(inode)->i_data_sem);
362026a4c0c6STheodore Ts'o 	if (IS_SYNC(inode))
362126a4c0c6STheodore Ts'o 		ext4_handle_sync(handle);
3622e251f9bcSMaxim Patlasov 
3623e251f9bcSMaxim Patlasov 	/* Now release the pages again to reduce race window */
3624e251f9bcSMaxim Patlasov 	if (last_block_offset > first_block_offset)
3625e251f9bcSMaxim Patlasov 		truncate_pagecache_range(inode, first_block_offset,
3626e251f9bcSMaxim Patlasov 					 last_block_offset);
3627e251f9bcSMaxim Patlasov 
362826a4c0c6STheodore Ts'o 	inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
362926a4c0c6STheodore Ts'o 	ext4_mark_inode_dirty(handle, inode);
363026a4c0c6STheodore Ts'o out_stop:
363126a4c0c6STheodore Ts'o 	ext4_journal_stop(handle);
363226a4c0c6STheodore Ts'o out_dio:
363326a4c0c6STheodore Ts'o 	ext4_inode_resume_unlocked_dio(inode);
363426a4c0c6STheodore Ts'o out_mutex:
363526a4c0c6STheodore Ts'o 	mutex_unlock(&inode->i_mutex);
363626a4c0c6STheodore Ts'o 	return ret;
3637a4bb6b64SAllison Henderson }
3638a4bb6b64SAllison Henderson 
3639a361293fSJan Kara int ext4_inode_attach_jinode(struct inode *inode)
3640a361293fSJan Kara {
3641a361293fSJan Kara 	struct ext4_inode_info *ei = EXT4_I(inode);
3642a361293fSJan Kara 	struct jbd2_inode *jinode;
3643a361293fSJan Kara 
3644a361293fSJan Kara 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
3645a361293fSJan Kara 		return 0;
3646a361293fSJan Kara 
3647a361293fSJan Kara 	jinode = jbd2_alloc_inode(GFP_KERNEL);
3648a361293fSJan Kara 	spin_lock(&inode->i_lock);
3649a361293fSJan Kara 	if (!ei->jinode) {
3650a361293fSJan Kara 		if (!jinode) {
3651a361293fSJan Kara 			spin_unlock(&inode->i_lock);
3652a361293fSJan Kara 			return -ENOMEM;
3653a361293fSJan Kara 		}
3654a361293fSJan Kara 		ei->jinode = jinode;
3655a361293fSJan Kara 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
3656a361293fSJan Kara 		jinode = NULL;
3657a361293fSJan Kara 	}
3658a361293fSJan Kara 	spin_unlock(&inode->i_lock);
3659a361293fSJan Kara 	if (unlikely(jinode != NULL))
3660a361293fSJan Kara 		jbd2_free_inode(jinode);
3661a361293fSJan Kara 	return 0;
3662a361293fSJan Kara }
3663a361293fSJan Kara 
3664a4bb6b64SAllison Henderson /*
3665617ba13bSMingming Cao  * ext4_truncate()
3666ac27a0ecSDave Kleikamp  *
3667617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
3668617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3669ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
3670ac27a0ecSDave Kleikamp  *
367142b2aa86SJustin P. Mattock  * As we work through the truncate and commit bits of it to the journal there
3672ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
3673ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
3674ac27a0ecSDave Kleikamp  *
3675ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
3676ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
3677ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
3678ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
3679ac27a0ecSDave Kleikamp  * left-to-right works OK too).
3680ac27a0ecSDave Kleikamp  *
3681ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
3682ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
3683ac27a0ecSDave Kleikamp  *
3684ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
3685617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
3686ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
3687617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
3688617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
3689ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
3690617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
3691ac27a0ecSDave Kleikamp  */
3692617ba13bSMingming Cao void ext4_truncate(struct inode *inode)
3693ac27a0ecSDave Kleikamp {
3694819c4920STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
3695819c4920STheodore Ts'o 	unsigned int credits;
3696819c4920STheodore Ts'o 	handle_t *handle;
3697819c4920STheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
3698819c4920STheodore Ts'o 
369919b5ef61STheodore Ts'o 	/*
370019b5ef61STheodore Ts'o 	 * There is a possibility that we're either freeing the inode
370119b5ef61STheodore Ts'o 	 * or it completely new indode. In those cases we might not
370219b5ef61STheodore Ts'o 	 * have i_mutex locked because it's not necessary.
370319b5ef61STheodore Ts'o 	 */
370419b5ef61STheodore Ts'o 	if (!(inode->i_state & (I_NEW|I_FREEING)))
370519b5ef61STheodore Ts'o 		WARN_ON(!mutex_is_locked(&inode->i_mutex));
37060562e0baSJiaying Zhang 	trace_ext4_truncate_enter(inode);
37070562e0baSJiaying Zhang 
370891ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
3709ac27a0ecSDave Kleikamp 		return;
3710ac27a0ecSDave Kleikamp 
371112e9b892SDmitry Monakhov 	ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3712c8d46e41SJiaying Zhang 
37135534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
371419f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
37157d8f9f7dSTheodore Ts'o 
3716aef1c851STao Ma 	if (ext4_has_inline_data(inode)) {
3717aef1c851STao Ma 		int has_inline = 1;
3718aef1c851STao Ma 
3719aef1c851STao Ma 		ext4_inline_data_truncate(inode, &has_inline);
3720aef1c851STao Ma 		if (has_inline)
3721aef1c851STao Ma 			return;
3722aef1c851STao Ma 	}
3723aef1c851STao Ma 
3724a361293fSJan Kara 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
3725a361293fSJan Kara 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
3726a361293fSJan Kara 		if (ext4_inode_attach_jinode(inode) < 0)
3727a361293fSJan Kara 			return;
3728a361293fSJan Kara 	}
3729a361293fSJan Kara 
3730ff9893dcSAmir Goldstein 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3731819c4920STheodore Ts'o 		credits = ext4_writepage_trans_blocks(inode);
3732ff9893dcSAmir Goldstein 	else
3733819c4920STheodore Ts'o 		credits = ext4_blocks_for_truncate(inode);
3734819c4920STheodore Ts'o 
3735819c4920STheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3736819c4920STheodore Ts'o 	if (IS_ERR(handle)) {
3737819c4920STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
3738819c4920STheodore Ts'o 		return;
3739819c4920STheodore Ts'o 	}
3740819c4920STheodore Ts'o 
3741eb3544c6SLukas Czerner 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3742eb3544c6SLukas Czerner 		ext4_block_truncate_page(handle, mapping, inode->i_size);
3743819c4920STheodore Ts'o 
3744819c4920STheodore Ts'o 	/*
3745819c4920STheodore Ts'o 	 * We add the inode to the orphan list, so that if this
3746819c4920STheodore Ts'o 	 * truncate spans multiple transactions, and we crash, we will
3747819c4920STheodore Ts'o 	 * resume the truncate when the filesystem recovers.  It also
3748819c4920STheodore Ts'o 	 * marks the inode dirty, to catch the new size.
3749819c4920STheodore Ts'o 	 *
3750819c4920STheodore Ts'o 	 * Implication: the file must always be in a sane, consistent
3751819c4920STheodore Ts'o 	 * truncatable state while each transaction commits.
3752819c4920STheodore Ts'o 	 */
3753819c4920STheodore Ts'o 	if (ext4_orphan_add(handle, inode))
3754819c4920STheodore Ts'o 		goto out_stop;
3755819c4920STheodore Ts'o 
3756819c4920STheodore Ts'o 	down_write(&EXT4_I(inode)->i_data_sem);
3757819c4920STheodore Ts'o 
3758819c4920STheodore Ts'o 	ext4_discard_preallocations(inode);
3759819c4920STheodore Ts'o 
3760819c4920STheodore Ts'o 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3761819c4920STheodore Ts'o 		ext4_ext_truncate(handle, inode);
3762819c4920STheodore Ts'o 	else
3763819c4920STheodore Ts'o 		ext4_ind_truncate(handle, inode);
3764819c4920STheodore Ts'o 
3765819c4920STheodore Ts'o 	up_write(&ei->i_data_sem);
3766819c4920STheodore Ts'o 
3767819c4920STheodore Ts'o 	if (IS_SYNC(inode))
3768819c4920STheodore Ts'o 		ext4_handle_sync(handle);
3769819c4920STheodore Ts'o 
3770819c4920STheodore Ts'o out_stop:
3771819c4920STheodore Ts'o 	/*
3772819c4920STheodore Ts'o 	 * If this was a simple ftruncate() and the file will remain alive,
3773819c4920STheodore Ts'o 	 * then we need to clear up the orphan record which we created above.
3774819c4920STheodore Ts'o 	 * However, if this was a real unlink then we were called by
3775819c4920STheodore Ts'o 	 * ext4_delete_inode(), and we allow that function to clean up the
3776819c4920STheodore Ts'o 	 * orphan info for us.
3777819c4920STheodore Ts'o 	 */
3778819c4920STheodore Ts'o 	if (inode->i_nlink)
3779819c4920STheodore Ts'o 		ext4_orphan_del(handle, inode);
3780819c4920STheodore Ts'o 
3781819c4920STheodore Ts'o 	inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3782819c4920STheodore Ts'o 	ext4_mark_inode_dirty(handle, inode);
3783819c4920STheodore Ts'o 	ext4_journal_stop(handle);
3784a86c6181SAlex Tomas 
37850562e0baSJiaying Zhang 	trace_ext4_truncate_exit(inode);
3786ac27a0ecSDave Kleikamp }
3787ac27a0ecSDave Kleikamp 
3788ac27a0ecSDave Kleikamp /*
3789617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
3790ac27a0ecSDave Kleikamp  * underlying buffer_head on success. If 'in_mem' is true, we have all
3791ac27a0ecSDave Kleikamp  * data in memory that is needed to recreate the on-disk version of this
3792ac27a0ecSDave Kleikamp  * inode.
3793ac27a0ecSDave Kleikamp  */
3794617ba13bSMingming Cao static int __ext4_get_inode_loc(struct inode *inode,
3795617ba13bSMingming Cao 				struct ext4_iloc *iloc, int in_mem)
3796ac27a0ecSDave Kleikamp {
3797240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
3798ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
3799240799cdSTheodore Ts'o 	struct super_block	*sb = inode->i_sb;
3800240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
3801240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
3802ac27a0ecSDave Kleikamp 
38033a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
3804240799cdSTheodore Ts'o 	if (!ext4_valid_inum(sb, inode->i_ino))
3805ac27a0ecSDave Kleikamp 		return -EIO;
3806ac27a0ecSDave Kleikamp 
3807240799cdSTheodore Ts'o 	iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3808240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3809240799cdSTheodore Ts'o 	if (!gdp)
3810240799cdSTheodore Ts'o 		return -EIO;
3811240799cdSTheodore Ts'o 
3812240799cdSTheodore Ts'o 	/*
3813240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
3814240799cdSTheodore Ts'o 	 */
381500d09882STao Ma 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3816240799cdSTheodore Ts'o 	inode_offset = ((inode->i_ino - 1) %
3817240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
3818240799cdSTheodore Ts'o 	block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3819240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3820240799cdSTheodore Ts'o 
3821240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
3822aebf0243SWang Shilong 	if (unlikely(!bh))
3823860d21e2STheodore Ts'o 		return -ENOMEM;
3824ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
3825ac27a0ecSDave Kleikamp 		lock_buffer(bh);
38269c83a923SHidehiro Kawai 
38279c83a923SHidehiro Kawai 		/*
38289c83a923SHidehiro Kawai 		 * If the buffer has the write error flag, we have failed
38299c83a923SHidehiro Kawai 		 * to write out another inode in the same block.  In this
38309c83a923SHidehiro Kawai 		 * case, we don't have to read the block because we may
38319c83a923SHidehiro Kawai 		 * read the old inode data successfully.
38329c83a923SHidehiro Kawai 		 */
38339c83a923SHidehiro Kawai 		if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
38349c83a923SHidehiro Kawai 			set_buffer_uptodate(bh);
38359c83a923SHidehiro Kawai 
3836ac27a0ecSDave Kleikamp 		if (buffer_uptodate(bh)) {
3837ac27a0ecSDave Kleikamp 			/* someone brought it uptodate while we waited */
3838ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
3839ac27a0ecSDave Kleikamp 			goto has_buffer;
3840ac27a0ecSDave Kleikamp 		}
3841ac27a0ecSDave Kleikamp 
3842ac27a0ecSDave Kleikamp 		/*
3843ac27a0ecSDave Kleikamp 		 * If we have all information of the inode in memory and this
3844ac27a0ecSDave Kleikamp 		 * is the only valid inode in the block, we need not read the
3845ac27a0ecSDave Kleikamp 		 * block.
3846ac27a0ecSDave Kleikamp 		 */
3847ac27a0ecSDave Kleikamp 		if (in_mem) {
3848ac27a0ecSDave Kleikamp 			struct buffer_head *bitmap_bh;
3849240799cdSTheodore Ts'o 			int i, start;
3850ac27a0ecSDave Kleikamp 
3851240799cdSTheodore Ts'o 			start = inode_offset & ~(inodes_per_block - 1);
3852ac27a0ecSDave Kleikamp 
3853ac27a0ecSDave Kleikamp 			/* Is the inode bitmap in cache? */
3854240799cdSTheodore Ts'o 			bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3855aebf0243SWang Shilong 			if (unlikely(!bitmap_bh))
3856ac27a0ecSDave Kleikamp 				goto make_io;
3857ac27a0ecSDave Kleikamp 
3858ac27a0ecSDave Kleikamp 			/*
3859ac27a0ecSDave Kleikamp 			 * If the inode bitmap isn't in cache then the
3860ac27a0ecSDave Kleikamp 			 * optimisation may end up performing two reads instead
3861ac27a0ecSDave Kleikamp 			 * of one, so skip it.
3862ac27a0ecSDave Kleikamp 			 */
3863ac27a0ecSDave Kleikamp 			if (!buffer_uptodate(bitmap_bh)) {
3864ac27a0ecSDave Kleikamp 				brelse(bitmap_bh);
3865ac27a0ecSDave Kleikamp 				goto make_io;
3866ac27a0ecSDave Kleikamp 			}
3867240799cdSTheodore Ts'o 			for (i = start; i < start + inodes_per_block; i++) {
3868ac27a0ecSDave Kleikamp 				if (i == inode_offset)
3869ac27a0ecSDave Kleikamp 					continue;
3870617ba13bSMingming Cao 				if (ext4_test_bit(i, bitmap_bh->b_data))
3871ac27a0ecSDave Kleikamp 					break;
3872ac27a0ecSDave Kleikamp 			}
3873ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
3874240799cdSTheodore Ts'o 			if (i == start + inodes_per_block) {
3875ac27a0ecSDave Kleikamp 				/* all other inodes are free, so skip I/O */
3876ac27a0ecSDave Kleikamp 				memset(bh->b_data, 0, bh->b_size);
3877ac27a0ecSDave Kleikamp 				set_buffer_uptodate(bh);
3878ac27a0ecSDave Kleikamp 				unlock_buffer(bh);
3879ac27a0ecSDave Kleikamp 				goto has_buffer;
3880ac27a0ecSDave Kleikamp 			}
3881ac27a0ecSDave Kleikamp 		}
3882ac27a0ecSDave Kleikamp 
3883ac27a0ecSDave Kleikamp make_io:
3884ac27a0ecSDave Kleikamp 		/*
3885240799cdSTheodore Ts'o 		 * If we need to do any I/O, try to pre-readahead extra
3886240799cdSTheodore Ts'o 		 * blocks from the inode table.
3887240799cdSTheodore Ts'o 		 */
3888240799cdSTheodore Ts'o 		if (EXT4_SB(sb)->s_inode_readahead_blks) {
3889240799cdSTheodore Ts'o 			ext4_fsblk_t b, end, table;
3890240799cdSTheodore Ts'o 			unsigned num;
38910d606e2cSTheodore Ts'o 			__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
3892240799cdSTheodore Ts'o 
3893240799cdSTheodore Ts'o 			table = ext4_inode_table(sb, gdp);
3894b713a5ecSTheodore Ts'o 			/* s_inode_readahead_blks is always a power of 2 */
38950d606e2cSTheodore Ts'o 			b = block & ~((ext4_fsblk_t) ra_blks - 1);
3896240799cdSTheodore Ts'o 			if (table > b)
3897240799cdSTheodore Ts'o 				b = table;
38980d606e2cSTheodore Ts'o 			end = b + ra_blks;
3899240799cdSTheodore Ts'o 			num = EXT4_INODES_PER_GROUP(sb);
3900feb0ab32SDarrick J. Wong 			if (ext4_has_group_desc_csum(sb))
3901560671a0SAneesh Kumar K.V 				num -= ext4_itable_unused_count(sb, gdp);
3902240799cdSTheodore Ts'o 			table += num / inodes_per_block;
3903240799cdSTheodore Ts'o 			if (end > table)
3904240799cdSTheodore Ts'o 				end = table;
3905240799cdSTheodore Ts'o 			while (b <= end)
3906240799cdSTheodore Ts'o 				sb_breadahead(sb, b++);
3907240799cdSTheodore Ts'o 		}
3908240799cdSTheodore Ts'o 
3909240799cdSTheodore Ts'o 		/*
3910ac27a0ecSDave Kleikamp 		 * There are other valid inodes in the buffer, this inode
3911ac27a0ecSDave Kleikamp 		 * has in-inode xattrs, or we don't have this inode in memory.
3912ac27a0ecSDave Kleikamp 		 * Read the block from disk.
3913ac27a0ecSDave Kleikamp 		 */
39140562e0baSJiaying Zhang 		trace_ext4_load_inode(inode);
3915ac27a0ecSDave Kleikamp 		get_bh(bh);
3916ac27a0ecSDave Kleikamp 		bh->b_end_io = end_buffer_read_sync;
391765299a3bSChristoph Hellwig 		submit_bh(READ | REQ_META | REQ_PRIO, bh);
3918ac27a0ecSDave Kleikamp 		wait_on_buffer(bh);
3919ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bh)) {
3920c398eda0STheodore Ts'o 			EXT4_ERROR_INODE_BLOCK(inode, block,
3921c398eda0STheodore Ts'o 					       "unable to read itable block");
3922ac27a0ecSDave Kleikamp 			brelse(bh);
3923ac27a0ecSDave Kleikamp 			return -EIO;
3924ac27a0ecSDave Kleikamp 		}
3925ac27a0ecSDave Kleikamp 	}
3926ac27a0ecSDave Kleikamp has_buffer:
3927ac27a0ecSDave Kleikamp 	iloc->bh = bh;
3928ac27a0ecSDave Kleikamp 	return 0;
3929ac27a0ecSDave Kleikamp }
3930ac27a0ecSDave Kleikamp 
3931617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3932ac27a0ecSDave Kleikamp {
3933ac27a0ecSDave Kleikamp 	/* We have all inode data except xattrs in memory here. */
3934617ba13bSMingming Cao 	return __ext4_get_inode_loc(inode, iloc,
393519f5fb7aSTheodore Ts'o 		!ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3936ac27a0ecSDave Kleikamp }
3937ac27a0ecSDave Kleikamp 
3938617ba13bSMingming Cao void ext4_set_inode_flags(struct inode *inode)
3939ac27a0ecSDave Kleikamp {
3940617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
3941*5f16f322STheodore Ts'o 	unsigned int new_fl = 0;
3942ac27a0ecSDave Kleikamp 
3943617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
3944*5f16f322STheodore Ts'o 		new_fl |= S_SYNC;
3945617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
3946*5f16f322STheodore Ts'o 		new_fl |= S_APPEND;
3947617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
3948*5f16f322STheodore Ts'o 		new_fl |= S_IMMUTABLE;
3949617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
3950*5f16f322STheodore Ts'o 		new_fl |= S_NOATIME;
3951617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
3952*5f16f322STheodore Ts'o 		new_fl |= S_DIRSYNC;
3953*5f16f322STheodore Ts'o 	inode_set_flags(inode, new_fl,
3954*5f16f322STheodore Ts'o 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
3955ac27a0ecSDave Kleikamp }
3956ac27a0ecSDave Kleikamp 
3957ff9ddf7eSJan Kara /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3958ff9ddf7eSJan Kara void ext4_get_inode_flags(struct ext4_inode_info *ei)
3959ff9ddf7eSJan Kara {
396084a8dce2SDmitry Monakhov 	unsigned int vfs_fl;
396184a8dce2SDmitry Monakhov 	unsigned long old_fl, new_fl;
3962ff9ddf7eSJan Kara 
396384a8dce2SDmitry Monakhov 	do {
396484a8dce2SDmitry Monakhov 		vfs_fl = ei->vfs_inode.i_flags;
396584a8dce2SDmitry Monakhov 		old_fl = ei->i_flags;
396684a8dce2SDmitry Monakhov 		new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
396784a8dce2SDmitry Monakhov 				EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
396884a8dce2SDmitry Monakhov 				EXT4_DIRSYNC_FL);
396984a8dce2SDmitry Monakhov 		if (vfs_fl & S_SYNC)
397084a8dce2SDmitry Monakhov 			new_fl |= EXT4_SYNC_FL;
397184a8dce2SDmitry Monakhov 		if (vfs_fl & S_APPEND)
397284a8dce2SDmitry Monakhov 			new_fl |= EXT4_APPEND_FL;
397384a8dce2SDmitry Monakhov 		if (vfs_fl & S_IMMUTABLE)
397484a8dce2SDmitry Monakhov 			new_fl |= EXT4_IMMUTABLE_FL;
397584a8dce2SDmitry Monakhov 		if (vfs_fl & S_NOATIME)
397684a8dce2SDmitry Monakhov 			new_fl |= EXT4_NOATIME_FL;
397784a8dce2SDmitry Monakhov 		if (vfs_fl & S_DIRSYNC)
397884a8dce2SDmitry Monakhov 			new_fl |= EXT4_DIRSYNC_FL;
397984a8dce2SDmitry Monakhov 	} while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3980ff9ddf7eSJan Kara }
3981de9a55b8STheodore Ts'o 
39820fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
39830fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
39840fc1b451SAneesh Kumar K.V {
39850fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
39868180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
39878180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
39880fc1b451SAneesh Kumar K.V 
39890fc1b451SAneesh Kumar K.V 	if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
39900fc1b451SAneesh Kumar K.V 				EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
39910fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
39920fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
39930fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
399407a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
39958180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
39968180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
39978180a562SAneesh Kumar K.V 		} else {
39980fc1b451SAneesh Kumar K.V 			return i_blocks;
39998180a562SAneesh Kumar K.V 		}
40000fc1b451SAneesh Kumar K.V 	} else {
40010fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
40020fc1b451SAneesh Kumar K.V 	}
40030fc1b451SAneesh Kumar K.V }
4004ff9ddf7eSJan Kara 
4005152a7b0aSTao Ma static inline void ext4_iget_extra_inode(struct inode *inode,
4006152a7b0aSTao Ma 					 struct ext4_inode *raw_inode,
4007152a7b0aSTao Ma 					 struct ext4_inode_info *ei)
4008152a7b0aSTao Ma {
4009152a7b0aSTao Ma 	__le32 *magic = (void *)raw_inode +
4010152a7b0aSTao Ma 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
401167cf5b09STao Ma 	if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4012152a7b0aSTao Ma 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
401367cf5b09STao Ma 		ext4_find_inline_data_nolock(inode);
4014f19d5870STao Ma 	} else
4015f19d5870STao Ma 		EXT4_I(inode)->i_inline_off = 0;
4016152a7b0aSTao Ma }
4017152a7b0aSTao Ma 
40181d1fe1eeSDavid Howells struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4019ac27a0ecSDave Kleikamp {
4020617ba13bSMingming Cao 	struct ext4_iloc iloc;
4021617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
40221d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
40231d1fe1eeSDavid Howells 	struct inode *inode;
4024b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
40251d1fe1eeSDavid Howells 	long ret;
4026ac27a0ecSDave Kleikamp 	int block;
402708cefc7aSEric W. Biederman 	uid_t i_uid;
402808cefc7aSEric W. Biederman 	gid_t i_gid;
4029ac27a0ecSDave Kleikamp 
40301d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
40311d1fe1eeSDavid Howells 	if (!inode)
40321d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
40331d1fe1eeSDavid Howells 	if (!(inode->i_state & I_NEW))
40341d1fe1eeSDavid Howells 		return inode;
40351d1fe1eeSDavid Howells 
40361d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
40377dc57615SPeter Huewe 	iloc.bh = NULL;
4038ac27a0ecSDave Kleikamp 
40391d1fe1eeSDavid Howells 	ret = __ext4_get_inode_loc(inode, &iloc, 0);
40401d1fe1eeSDavid Howells 	if (ret < 0)
4041ac27a0ecSDave Kleikamp 		goto bad_inode;
4042617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
4043814525f4SDarrick J. Wong 
4044814525f4SDarrick J. Wong 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4045814525f4SDarrick J. Wong 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4046814525f4SDarrick J. Wong 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4047814525f4SDarrick J. Wong 		    EXT4_INODE_SIZE(inode->i_sb)) {
4048814525f4SDarrick J. Wong 			EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4049814525f4SDarrick J. Wong 				EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4050814525f4SDarrick J. Wong 				EXT4_INODE_SIZE(inode->i_sb));
4051814525f4SDarrick J. Wong 			ret = -EIO;
4052814525f4SDarrick J. Wong 			goto bad_inode;
4053814525f4SDarrick J. Wong 		}
4054814525f4SDarrick J. Wong 	} else
4055814525f4SDarrick J. Wong 		ei->i_extra_isize = 0;
4056814525f4SDarrick J. Wong 
4057814525f4SDarrick J. Wong 	/* Precompute checksum seed for inode metadata */
4058814525f4SDarrick J. Wong 	if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4059814525f4SDarrick J. Wong 			EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
4060814525f4SDarrick J. Wong 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4061814525f4SDarrick J. Wong 		__u32 csum;
4062814525f4SDarrick J. Wong 		__le32 inum = cpu_to_le32(inode->i_ino);
4063814525f4SDarrick J. Wong 		__le32 gen = raw_inode->i_generation;
4064814525f4SDarrick J. Wong 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4065814525f4SDarrick J. Wong 				   sizeof(inum));
4066814525f4SDarrick J. Wong 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4067814525f4SDarrick J. Wong 					      sizeof(gen));
4068814525f4SDarrick J. Wong 	}
4069814525f4SDarrick J. Wong 
4070814525f4SDarrick J. Wong 	if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4071814525f4SDarrick J. Wong 		EXT4_ERROR_INODE(inode, "checksum invalid");
4072814525f4SDarrick J. Wong 		ret = -EIO;
4073814525f4SDarrick J. Wong 		goto bad_inode;
4074814525f4SDarrick J. Wong 	}
4075814525f4SDarrick J. Wong 
4076ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
407708cefc7aSEric W. Biederman 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
407808cefc7aSEric W. Biederman 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4079ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
408008cefc7aSEric W. Biederman 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
408108cefc7aSEric W. Biederman 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4082ac27a0ecSDave Kleikamp 	}
408308cefc7aSEric W. Biederman 	i_uid_write(inode, i_uid);
408408cefc7aSEric W. Biederman 	i_gid_write(inode, i_gid);
4085bfe86848SMiklos Szeredi 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4086ac27a0ecSDave Kleikamp 
4087353eb83cSTheodore Ts'o 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
408867cf5b09STao Ma 	ei->i_inline_off = 0;
4089ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
4090ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4091ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
4092ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
4093ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
4094ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
4095ac27a0ecSDave Kleikamp 	 */
4096ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
4097393d1d1dSDr. Tilmann Bubeck 		if ((inode->i_mode == 0 ||
4098393d1d1dSDr. Tilmann Bubeck 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4099393d1d1dSDr. Tilmann Bubeck 		    ino != EXT4_BOOT_LOADER_INO) {
4100ac27a0ecSDave Kleikamp 			/* this inode is deleted */
41011d1fe1eeSDavid Howells 			ret = -ESTALE;
4102ac27a0ecSDave Kleikamp 			goto bad_inode;
4103ac27a0ecSDave Kleikamp 		}
4104ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
4105ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
4106ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
4107393d1d1dSDr. Tilmann Bubeck 		 * the process of deleting those.
4108393d1d1dSDr. Tilmann Bubeck 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4109393d1d1dSDr. Tilmann Bubeck 		 * not initialized on a new filesystem. */
4110ac27a0ecSDave Kleikamp 	}
4111ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
41120fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
41137973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4114a9e81742STheodore Ts'o 	if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4115a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
4116a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4117a48380f7SAneesh Kumar K.V 	inode->i_size = ext4_isize(raw_inode);
4118ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
4119a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
4120a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
4121a9e7f447SDmitry Monakhov #endif
4122ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4123ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
4124a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
4125ac27a0ecSDave Kleikamp 	/*
4126ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
4127ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4128ac27a0ecSDave Kleikamp 	 */
4129617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4130ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
4131ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
4132ac27a0ecSDave Kleikamp 
4133b436b9beSJan Kara 	/*
4134b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
4135b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
4136b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
4137b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
4138b436b9beSJan Kara 	 * now it is reread from disk.
4139b436b9beSJan Kara 	 */
4140b436b9beSJan Kara 	if (journal) {
4141b436b9beSJan Kara 		transaction_t *transaction;
4142b436b9beSJan Kara 		tid_t tid;
4143b436b9beSJan Kara 
4144a931da6aSTheodore Ts'o 		read_lock(&journal->j_state_lock);
4145b436b9beSJan Kara 		if (journal->j_running_transaction)
4146b436b9beSJan Kara 			transaction = journal->j_running_transaction;
4147b436b9beSJan Kara 		else
4148b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
4149b436b9beSJan Kara 		if (transaction)
4150b436b9beSJan Kara 			tid = transaction->t_tid;
4151b436b9beSJan Kara 		else
4152b436b9beSJan Kara 			tid = journal->j_commit_sequence;
4153a931da6aSTheodore Ts'o 		read_unlock(&journal->j_state_lock);
4154b436b9beSJan Kara 		ei->i_sync_tid = tid;
4155b436b9beSJan Kara 		ei->i_datasync_tid = tid;
4156b436b9beSJan Kara 	}
4157b436b9beSJan Kara 
41580040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4159ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
4160ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
4161617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4162617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
4163ac27a0ecSDave Kleikamp 		} else {
4164152a7b0aSTao Ma 			ext4_iget_extra_inode(inode, raw_inode, ei);
4165ac27a0ecSDave Kleikamp 		}
4166814525f4SDarrick J. Wong 	}
4167ac27a0ecSDave Kleikamp 
4168ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4169ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4170ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4171ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4172ef7f3835SKalpak Shah 
4173ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
417425ec56b5SJean Noel Cordenner 		inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
417525ec56b5SJean Noel Cordenner 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
417625ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
417725ec56b5SJean Noel Cordenner 				inode->i_version |=
417825ec56b5SJean Noel Cordenner 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
417925ec56b5SJean Noel Cordenner 		}
4180c4f65706STheodore Ts'o 	}
418125ec56b5SJean Noel Cordenner 
4182c4b5a614STheodore Ts'o 	ret = 0;
4183485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
41841032988cSTheodore Ts'o 	    !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
418524676da4STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
418624676da4STheodore Ts'o 				 ei->i_file_acl);
4187485c26ecSTheodore Ts'o 		ret = -EIO;
4188485c26ecSTheodore Ts'o 		goto bad_inode;
4189f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
4190f19d5870STao Ma 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4191f19d5870STao Ma 			if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4192c4b5a614STheodore Ts'o 			    (S_ISLNK(inode->i_mode) &&
4193f19d5870STao Ma 			     !ext4_inode_is_fast_symlink(inode))))
41947a262f7cSAneesh Kumar K.V 				/* Validate extent which is part of inode */
41957a262f7cSAneesh Kumar K.V 				ret = ext4_ext_check_inode(inode);
4196fe2c8191SThiemo Nagel 		} else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4197fe2c8191SThiemo Nagel 			   (S_ISLNK(inode->i_mode) &&
4198fe2c8191SThiemo Nagel 			    !ext4_inode_is_fast_symlink(inode))) {
4199fe2c8191SThiemo Nagel 			/* Validate block references which are part of inode */
42001f7d1e77STheodore Ts'o 			ret = ext4_ind_check_inode(inode);
4201fe2c8191SThiemo Nagel 		}
4202f19d5870STao Ma 	}
4203567f3e9aSTheodore Ts'o 	if (ret)
42047a262f7cSAneesh Kumar K.V 		goto bad_inode;
42057a262f7cSAneesh Kumar K.V 
4206ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
4207617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
4208617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
4209617ba13bSMingming Cao 		ext4_set_aops(inode);
4210ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
4211617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
4212617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
4213ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
4214e83c1397SDuane Griffin 		if (ext4_inode_is_fast_symlink(inode)) {
4215617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
4216e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
4217e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
4218e83c1397SDuane Griffin 		} else {
4219617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
4220617ba13bSMingming Cao 			ext4_set_aops(inode);
4221ac27a0ecSDave Kleikamp 		}
4222563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4223563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4224617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
4225ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
4226ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
4227ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4228ac27a0ecSDave Kleikamp 		else
4229ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
4230ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4231393d1d1dSDr. Tilmann Bubeck 	} else if (ino == EXT4_BOOT_LOADER_INO) {
4232393d1d1dSDr. Tilmann Bubeck 		make_bad_inode(inode);
4233563bdd61STheodore Ts'o 	} else {
4234563bdd61STheodore Ts'o 		ret = -EIO;
423524676da4STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4236563bdd61STheodore Ts'o 		goto bad_inode;
4237ac27a0ecSDave Kleikamp 	}
4238ac27a0ecSDave Kleikamp 	brelse(iloc.bh);
4239617ba13bSMingming Cao 	ext4_set_inode_flags(inode);
42401d1fe1eeSDavid Howells 	unlock_new_inode(inode);
42411d1fe1eeSDavid Howells 	return inode;
4242ac27a0ecSDave Kleikamp 
4243ac27a0ecSDave Kleikamp bad_inode:
4244567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
42451d1fe1eeSDavid Howells 	iget_failed(inode);
42461d1fe1eeSDavid Howells 	return ERR_PTR(ret);
4247ac27a0ecSDave Kleikamp }
4248ac27a0ecSDave Kleikamp 
42490fc1b451SAneesh Kumar K.V static int ext4_inode_blocks_set(handle_t *handle,
42500fc1b451SAneesh Kumar K.V 				struct ext4_inode *raw_inode,
42510fc1b451SAneesh Kumar K.V 				struct ext4_inode_info *ei)
42520fc1b451SAneesh Kumar K.V {
42530fc1b451SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
42540fc1b451SAneesh Kumar K.V 	u64 i_blocks = inode->i_blocks;
42550fc1b451SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
42560fc1b451SAneesh Kumar K.V 
42570fc1b451SAneesh Kumar K.V 	if (i_blocks <= ~0U) {
42580fc1b451SAneesh Kumar K.V 		/*
42594907cb7bSAnatol Pomozov 		 * i_blocks can be represented in a 32 bit variable
42600fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
42610fc1b451SAneesh Kumar K.V 		 */
42628180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42630fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = 0;
426484a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4265f287a1a5STheodore Ts'o 		return 0;
4266f287a1a5STheodore Ts'o 	}
4267f287a1a5STheodore Ts'o 	if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4268f287a1a5STheodore Ts'o 		return -EFBIG;
4269f287a1a5STheodore Ts'o 
4270f287a1a5STheodore Ts'o 	if (i_blocks <= 0xffffffffffffULL) {
42710fc1b451SAneesh Kumar K.V 		/*
42720fc1b451SAneesh Kumar K.V 		 * i_blocks can be represented in a 48 bit variable
42730fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
42740fc1b451SAneesh Kumar K.V 		 */
42758180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42760fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
427784a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
42780fc1b451SAneesh Kumar K.V 	} else {
427984a8dce2SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
42808180a562SAneesh Kumar K.V 		/* i_block is stored in file system block size */
42818180a562SAneesh Kumar K.V 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
42828180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
42838180a562SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
42840fc1b451SAneesh Kumar K.V 	}
4285f287a1a5STheodore Ts'o 	return 0;
42860fc1b451SAneesh Kumar K.V }
42870fc1b451SAneesh Kumar K.V 
4288ac27a0ecSDave Kleikamp /*
4289ac27a0ecSDave Kleikamp  * Post the struct inode info into an on-disk inode location in the
4290ac27a0ecSDave Kleikamp  * buffer-cache.  This gobbles the caller's reference to the
4291ac27a0ecSDave Kleikamp  * buffer_head in the inode location struct.
4292ac27a0ecSDave Kleikamp  *
4293ac27a0ecSDave Kleikamp  * The caller must have write access to iloc->bh.
4294ac27a0ecSDave Kleikamp  */
4295617ba13bSMingming Cao static int ext4_do_update_inode(handle_t *handle,
4296ac27a0ecSDave Kleikamp 				struct inode *inode,
4297830156c7SFrank Mayhar 				struct ext4_iloc *iloc)
4298ac27a0ecSDave Kleikamp {
4299617ba13bSMingming Cao 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4300617ba13bSMingming Cao 	struct ext4_inode_info *ei = EXT4_I(inode);
4301ac27a0ecSDave Kleikamp 	struct buffer_head *bh = iloc->bh;
4302ac27a0ecSDave Kleikamp 	int err = 0, rc, block;
4303b71fc079SJan Kara 	int need_datasync = 0;
430408cefc7aSEric W. Biederman 	uid_t i_uid;
430508cefc7aSEric W. Biederman 	gid_t i_gid;
4306ac27a0ecSDave Kleikamp 
4307ac27a0ecSDave Kleikamp 	/* For fields not not tracking in the in-memory inode,
4308ac27a0ecSDave Kleikamp 	 * initialise them to zero for new inodes. */
430919f5fb7aSTheodore Ts'o 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4310617ba13bSMingming Cao 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4311ac27a0ecSDave Kleikamp 
4312ff9ddf7eSJan Kara 	ext4_get_inode_flags(ei);
4313ac27a0ecSDave Kleikamp 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
431408cefc7aSEric W. Biederman 	i_uid = i_uid_read(inode);
431508cefc7aSEric W. Biederman 	i_gid = i_gid_read(inode);
4316ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
431708cefc7aSEric W. Biederman 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
431808cefc7aSEric W. Biederman 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4319ac27a0ecSDave Kleikamp /*
4320ac27a0ecSDave Kleikamp  * Fix up interoperability with old kernels. Otherwise, old inodes get
4321ac27a0ecSDave Kleikamp  * re-used with the upper 16 bits of the uid/gid intact
4322ac27a0ecSDave Kleikamp  */
4323ac27a0ecSDave Kleikamp 		if (!ei->i_dtime) {
4324ac27a0ecSDave Kleikamp 			raw_inode->i_uid_high =
432508cefc7aSEric W. Biederman 				cpu_to_le16(high_16_bits(i_uid));
4326ac27a0ecSDave Kleikamp 			raw_inode->i_gid_high =
432708cefc7aSEric W. Biederman 				cpu_to_le16(high_16_bits(i_gid));
4328ac27a0ecSDave Kleikamp 		} else {
4329ac27a0ecSDave Kleikamp 			raw_inode->i_uid_high = 0;
4330ac27a0ecSDave Kleikamp 			raw_inode->i_gid_high = 0;
4331ac27a0ecSDave Kleikamp 		}
4332ac27a0ecSDave Kleikamp 	} else {
433308cefc7aSEric W. Biederman 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
433408cefc7aSEric W. Biederman 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4335ac27a0ecSDave Kleikamp 		raw_inode->i_uid_high = 0;
4336ac27a0ecSDave Kleikamp 		raw_inode->i_gid_high = 0;
4337ac27a0ecSDave Kleikamp 	}
4338ac27a0ecSDave Kleikamp 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4339ef7f3835SKalpak Shah 
4340ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4341ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4342ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4343ef7f3835SKalpak Shah 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4344ef7f3835SKalpak Shah 
43450fc1b451SAneesh Kumar K.V 	if (ext4_inode_blocks_set(handle, raw_inode, ei))
43460fc1b451SAneesh Kumar K.V 		goto out_brelse;
4347ac27a0ecSDave Kleikamp 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4348353eb83cSTheodore Ts'o 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4349ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4350a1ddeb7eSBadari Pulavarty 		raw_inode->i_file_acl_high =
4351a1ddeb7eSBadari Pulavarty 			cpu_to_le16(ei->i_file_acl >> 32);
43527973c0c1SAneesh Kumar K.V 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4353b71fc079SJan Kara 	if (ei->i_disksize != ext4_isize(raw_inode)) {
4354a48380f7SAneesh Kumar K.V 		ext4_isize_set(raw_inode, ei->i_disksize);
4355b71fc079SJan Kara 		need_datasync = 1;
4356b71fc079SJan Kara 	}
4357ac27a0ecSDave Kleikamp 	if (ei->i_disksize > 0x7fffffffULL) {
4358ac27a0ecSDave Kleikamp 		struct super_block *sb = inode->i_sb;
4359617ba13bSMingming Cao 		if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4360617ba13bSMingming Cao 				EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4361617ba13bSMingming Cao 				EXT4_SB(sb)->s_es->s_rev_level ==
4362617ba13bSMingming Cao 				cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4363ac27a0ecSDave Kleikamp 			/* If this is the first large file
4364ac27a0ecSDave Kleikamp 			 * created, add a flag to the superblock.
4365ac27a0ecSDave Kleikamp 			 */
4366617ba13bSMingming Cao 			err = ext4_journal_get_write_access(handle,
4367617ba13bSMingming Cao 					EXT4_SB(sb)->s_sbh);
4368ac27a0ecSDave Kleikamp 			if (err)
4369ac27a0ecSDave Kleikamp 				goto out_brelse;
4370617ba13bSMingming Cao 			ext4_update_dynamic_rev(sb);
4371617ba13bSMingming Cao 			EXT4_SET_RO_COMPAT_FEATURE(sb,
4372617ba13bSMingming Cao 					EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
43730390131bSFrank Mayhar 			ext4_handle_sync(handle);
4374b50924c2SArtem Bityutskiy 			err = ext4_handle_dirty_super(handle, sb);
4375ac27a0ecSDave Kleikamp 		}
4376ac27a0ecSDave Kleikamp 	}
4377ac27a0ecSDave Kleikamp 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4378ac27a0ecSDave Kleikamp 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4379ac27a0ecSDave Kleikamp 		if (old_valid_dev(inode->i_rdev)) {
4380ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] =
4381ac27a0ecSDave Kleikamp 				cpu_to_le32(old_encode_dev(inode->i_rdev));
4382ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] = 0;
4383ac27a0ecSDave Kleikamp 		} else {
4384ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] = 0;
4385ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] =
4386ac27a0ecSDave Kleikamp 				cpu_to_le32(new_encode_dev(inode->i_rdev));
4387ac27a0ecSDave Kleikamp 			raw_inode->i_block[2] = 0;
4388ac27a0ecSDave Kleikamp 		}
4389f19d5870STao Ma 	} else if (!ext4_has_inline_data(inode)) {
4390de9a55b8STheodore Ts'o 		for (block = 0; block < EXT4_N_BLOCKS; block++)
4391ac27a0ecSDave Kleikamp 			raw_inode->i_block[block] = ei->i_data[block];
4392f19d5870STao Ma 	}
4393ac27a0ecSDave Kleikamp 
4394ed3654ebSTheodore Ts'o 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
439525ec56b5SJean Noel Cordenner 		raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
439625ec56b5SJean Noel Cordenner 		if (ei->i_extra_isize) {
439725ec56b5SJean Noel Cordenner 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
439825ec56b5SJean Noel Cordenner 				raw_inode->i_version_hi =
439925ec56b5SJean Noel Cordenner 					cpu_to_le32(inode->i_version >> 32);
4400c4f65706STheodore Ts'o 			raw_inode->i_extra_isize =
4401c4f65706STheodore Ts'o 				cpu_to_le16(ei->i_extra_isize);
4402c4f65706STheodore Ts'o 		}
440325ec56b5SJean Noel Cordenner 	}
440425ec56b5SJean Noel Cordenner 
4405814525f4SDarrick J. Wong 	ext4_inode_csum_set(inode, raw_inode, ei);
4406814525f4SDarrick J. Wong 
44070390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
440873b50c1cSCurt Wohlgemuth 	rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4409ac27a0ecSDave Kleikamp 	if (!err)
4410ac27a0ecSDave Kleikamp 		err = rc;
441119f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4412ac27a0ecSDave Kleikamp 
4413b71fc079SJan Kara 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4414ac27a0ecSDave Kleikamp out_brelse:
4415ac27a0ecSDave Kleikamp 	brelse(bh);
4416617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
4417ac27a0ecSDave Kleikamp 	return err;
4418ac27a0ecSDave Kleikamp }
4419ac27a0ecSDave Kleikamp 
4420ac27a0ecSDave Kleikamp /*
4421617ba13bSMingming Cao  * ext4_write_inode()
4422ac27a0ecSDave Kleikamp  *
4423ac27a0ecSDave Kleikamp  * We are called from a few places:
4424ac27a0ecSDave Kleikamp  *
4425ac27a0ecSDave Kleikamp  * - Within generic_file_write() for O_SYNC files.
4426ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
44274907cb7bSAnatol Pomozov  *   transaction to commit.
4428ac27a0ecSDave Kleikamp  *
4429ac27a0ecSDave Kleikamp  * - Within sys_sync(), kupdate and such.
4430ac27a0ecSDave Kleikamp  *   We wait on commit, if tol to.
4431ac27a0ecSDave Kleikamp  *
4432ac27a0ecSDave Kleikamp  * - Within prune_icache() (PF_MEMALLOC == true)
4433ac27a0ecSDave Kleikamp  *   Here we simply return.  We can't afford to block kswapd on the
4434ac27a0ecSDave Kleikamp  *   journal commit.
4435ac27a0ecSDave Kleikamp  *
4436ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
4437ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
4438617ba13bSMingming Cao  * ext4_mark_inode_dirty().  This is a correctness thing for O_SYNC and for
4439ac27a0ecSDave Kleikamp  * knfsd.
4440ac27a0ecSDave Kleikamp  *
4441ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
4442ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
4443ac27a0ecSDave Kleikamp  * which we are interested.
4444ac27a0ecSDave Kleikamp  *
4445ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
4446ac27a0ecSDave Kleikamp  *
4447ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
4448ac27a0ecSDave Kleikamp  *	stuff();
4449ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
4450ac27a0ecSDave Kleikamp  *
4451ac27a0ecSDave Kleikamp  * is in error because a kswapd-driven write_inode() could occur while
4452ac27a0ecSDave Kleikamp  * `stuff()' is running, and the new i_size will be lost.  Plus the inode
4453ac27a0ecSDave Kleikamp  * will no longer be on the superblock's dirty inode list.
4454ac27a0ecSDave Kleikamp  */
4455a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4456ac27a0ecSDave Kleikamp {
445791ac6f43SFrank Mayhar 	int err;
445891ac6f43SFrank Mayhar 
4459ac27a0ecSDave Kleikamp 	if (current->flags & PF_MEMALLOC)
4460ac27a0ecSDave Kleikamp 		return 0;
4461ac27a0ecSDave Kleikamp 
446291ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
4463617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
4464b38bd33aSMingming Cao 			jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4465ac27a0ecSDave Kleikamp 			dump_stack();
4466ac27a0ecSDave Kleikamp 			return -EIO;
4467ac27a0ecSDave Kleikamp 		}
4468ac27a0ecSDave Kleikamp 
446910542c22SJan Kara 		/*
447010542c22SJan Kara 		 * No need to force transaction in WB_SYNC_NONE mode. Also
447110542c22SJan Kara 		 * ext4_sync_fs() will force the commit after everything is
447210542c22SJan Kara 		 * written.
447310542c22SJan Kara 		 */
447410542c22SJan Kara 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
4475ac27a0ecSDave Kleikamp 			return 0;
4476ac27a0ecSDave Kleikamp 
447791ac6f43SFrank Mayhar 		err = ext4_force_commit(inode->i_sb);
447891ac6f43SFrank Mayhar 	} else {
447991ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
448091ac6f43SFrank Mayhar 
44818b472d73SCurt Wohlgemuth 		err = __ext4_get_inode_loc(inode, &iloc, 0);
448291ac6f43SFrank Mayhar 		if (err)
448391ac6f43SFrank Mayhar 			return err;
448410542c22SJan Kara 		/*
448510542c22SJan Kara 		 * sync(2) will flush the whole buffer cache. No need to do
448610542c22SJan Kara 		 * it here separately for each inode.
448710542c22SJan Kara 		 */
448810542c22SJan Kara 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4489830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
4490830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4491c398eda0STheodore Ts'o 			EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4492c398eda0STheodore Ts'o 					 "IO error syncing inode");
4493830156c7SFrank Mayhar 			err = -EIO;
4494830156c7SFrank Mayhar 		}
4495fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
449691ac6f43SFrank Mayhar 	}
449791ac6f43SFrank Mayhar 	return err;
4498ac27a0ecSDave Kleikamp }
4499ac27a0ecSDave Kleikamp 
4500ac27a0ecSDave Kleikamp /*
450153e87268SJan Kara  * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
450253e87268SJan Kara  * buffers that are attached to a page stradding i_size and are undergoing
450353e87268SJan Kara  * commit. In that case we have to wait for commit to finish and try again.
450453e87268SJan Kara  */
450553e87268SJan Kara static void ext4_wait_for_tail_page_commit(struct inode *inode)
450653e87268SJan Kara {
450753e87268SJan Kara 	struct page *page;
450853e87268SJan Kara 	unsigned offset;
450953e87268SJan Kara 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
451053e87268SJan Kara 	tid_t commit_tid = 0;
451153e87268SJan Kara 	int ret;
451253e87268SJan Kara 
451353e87268SJan Kara 	offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
451453e87268SJan Kara 	/*
451553e87268SJan Kara 	 * All buffers in the last page remain valid? Then there's nothing to
451653e87268SJan Kara 	 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
451753e87268SJan Kara 	 * blocksize case
451853e87268SJan Kara 	 */
451953e87268SJan Kara 	if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
452053e87268SJan Kara 		return;
452153e87268SJan Kara 	while (1) {
452253e87268SJan Kara 		page = find_lock_page(inode->i_mapping,
452353e87268SJan Kara 				      inode->i_size >> PAGE_CACHE_SHIFT);
452453e87268SJan Kara 		if (!page)
452553e87268SJan Kara 			return;
4526ca99fdd2SLukas Czerner 		ret = __ext4_journalled_invalidatepage(page, offset,
4527ca99fdd2SLukas Czerner 						PAGE_CACHE_SIZE - offset);
452853e87268SJan Kara 		unlock_page(page);
452953e87268SJan Kara 		page_cache_release(page);
453053e87268SJan Kara 		if (ret != -EBUSY)
453153e87268SJan Kara 			return;
453253e87268SJan Kara 		commit_tid = 0;
453353e87268SJan Kara 		read_lock(&journal->j_state_lock);
453453e87268SJan Kara 		if (journal->j_committing_transaction)
453553e87268SJan Kara 			commit_tid = journal->j_committing_transaction->t_tid;
453653e87268SJan Kara 		read_unlock(&journal->j_state_lock);
453753e87268SJan Kara 		if (commit_tid)
453853e87268SJan Kara 			jbd2_log_wait_commit(journal, commit_tid);
453953e87268SJan Kara 	}
454053e87268SJan Kara }
454153e87268SJan Kara 
454253e87268SJan Kara /*
4543617ba13bSMingming Cao  * ext4_setattr()
4544ac27a0ecSDave Kleikamp  *
4545ac27a0ecSDave Kleikamp  * Called from notify_change.
4546ac27a0ecSDave Kleikamp  *
4547ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
4548ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
4549ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
4550ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
4551ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
4552ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
4553ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
4554ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
4555ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
4556ac27a0ecSDave Kleikamp  *
4557678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
4558678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
4559678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
4560678aaf48SJan Kara  * This way we are sure that all the data written in the previous
4561678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
4562678aaf48SJan Kara  * writeback).
4563678aaf48SJan Kara  *
4564678aaf48SJan Kara  * Called with inode->i_mutex down.
4565ac27a0ecSDave Kleikamp  */
4566617ba13bSMingming Cao int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4567ac27a0ecSDave Kleikamp {
4568ac27a0ecSDave Kleikamp 	struct inode *inode = dentry->d_inode;
4569ac27a0ecSDave Kleikamp 	int error, rc = 0;
45703d287de3SDmitry Monakhov 	int orphan = 0;
4571ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
4572ac27a0ecSDave Kleikamp 
4573ac27a0ecSDave Kleikamp 	error = inode_change_ok(inode, attr);
4574ac27a0ecSDave Kleikamp 	if (error)
4575ac27a0ecSDave Kleikamp 		return error;
4576ac27a0ecSDave Kleikamp 
457712755627SDmitry Monakhov 	if (is_quota_modification(inode, attr))
4578871a2931SChristoph Hellwig 		dquot_initialize(inode);
457908cefc7aSEric W. Biederman 	if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
458008cefc7aSEric W. Biederman 	    (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4581ac27a0ecSDave Kleikamp 		handle_t *handle;
4582ac27a0ecSDave Kleikamp 
4583ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
4584ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
45859924a92aSTheodore Ts'o 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
45869924a92aSTheodore Ts'o 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4587194074acSDmitry Monakhov 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4588ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
4589ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
4590ac27a0ecSDave Kleikamp 			goto err_out;
4591ac27a0ecSDave Kleikamp 		}
4592b43fa828SChristoph Hellwig 		error = dquot_transfer(inode, attr);
4593ac27a0ecSDave Kleikamp 		if (error) {
4594617ba13bSMingming Cao 			ext4_journal_stop(handle);
4595ac27a0ecSDave Kleikamp 			return error;
4596ac27a0ecSDave Kleikamp 		}
4597ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
4598ac27a0ecSDave Kleikamp 		 * one transaction */
4599ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_UID)
4600ac27a0ecSDave Kleikamp 			inode->i_uid = attr->ia_uid;
4601ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_GID)
4602ac27a0ecSDave Kleikamp 			inode->i_gid = attr->ia_gid;
4603617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
4604617ba13bSMingming Cao 		ext4_journal_stop(handle);
4605ac27a0ecSDave Kleikamp 	}
4606ac27a0ecSDave Kleikamp 
46075208386cSJan Kara 	if (attr->ia_valid & ATTR_SIZE && attr->ia_size != inode->i_size) {
46085208386cSJan Kara 		handle_t *handle;
4609562c72aaSChristoph Hellwig 
461012e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4611e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4612e2b46574SEric Sandeen 
46130c095c7fSTheodore Ts'o 			if (attr->ia_size > sbi->s_bitmap_maxbytes)
46140c095c7fSTheodore Ts'o 				return -EFBIG;
4615e2b46574SEric Sandeen 		}
4616dff6efc3SChristoph Hellwig 
4617dff6efc3SChristoph Hellwig 		if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
4618dff6efc3SChristoph Hellwig 			inode_inc_iversion(inode);
4619dff6efc3SChristoph Hellwig 
4620ac27a0ecSDave Kleikamp 		if (S_ISREG(inode->i_mode) &&
4621072bd7eaSTheodore Ts'o 		    (attr->ia_size < inode->i_size)) {
46225208386cSJan Kara 			if (ext4_should_order_data(inode)) {
46235208386cSJan Kara 				error = ext4_begin_ordered_truncate(inode,
46245208386cSJan Kara 							    attr->ia_size);
46255208386cSJan Kara 				if (error)
46265208386cSJan Kara 					goto err_out;
46275208386cSJan Kara 			}
46289924a92aSTheodore Ts'o 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4629ac27a0ecSDave Kleikamp 			if (IS_ERR(handle)) {
4630ac27a0ecSDave Kleikamp 				error = PTR_ERR(handle);
4631ac27a0ecSDave Kleikamp 				goto err_out;
4632ac27a0ecSDave Kleikamp 			}
46333d287de3SDmitry Monakhov 			if (ext4_handle_valid(handle)) {
4634617ba13bSMingming Cao 				error = ext4_orphan_add(handle, inode);
46353d287de3SDmitry Monakhov 				orphan = 1;
46363d287de3SDmitry Monakhov 			}
463790e775b7SJan Kara 			down_write(&EXT4_I(inode)->i_data_sem);
4638617ba13bSMingming Cao 			EXT4_I(inode)->i_disksize = attr->ia_size;
4639617ba13bSMingming Cao 			rc = ext4_mark_inode_dirty(handle, inode);
4640ac27a0ecSDave Kleikamp 			if (!error)
4641ac27a0ecSDave Kleikamp 				error = rc;
464290e775b7SJan Kara 			/*
464390e775b7SJan Kara 			 * We have to update i_size under i_data_sem together
464490e775b7SJan Kara 			 * with i_disksize to avoid races with writeback code
464590e775b7SJan Kara 			 * running ext4_wb_update_i_disksize().
464690e775b7SJan Kara 			 */
464790e775b7SJan Kara 			if (!error)
464890e775b7SJan Kara 				i_size_write(inode, attr->ia_size);
464990e775b7SJan Kara 			up_write(&EXT4_I(inode)->i_data_sem);
4650617ba13bSMingming Cao 			ext4_journal_stop(handle);
4651678aaf48SJan Kara 			if (error) {
4652678aaf48SJan Kara 				ext4_orphan_del(NULL, inode);
4653678aaf48SJan Kara 				goto err_out;
4654678aaf48SJan Kara 			}
465590e775b7SJan Kara 		} else
465653e87268SJan Kara 			i_size_write(inode, attr->ia_size);
465790e775b7SJan Kara 
465853e87268SJan Kara 		/*
465953e87268SJan Kara 		 * Blocks are going to be removed from the inode. Wait
466053e87268SJan Kara 		 * for dio in flight.  Temporarily disable
466153e87268SJan Kara 		 * dioread_nolock to prevent livelock.
466253e87268SJan Kara 		 */
46631b65007eSDmitry Monakhov 		if (orphan) {
466453e87268SJan Kara 			if (!ext4_should_journal_data(inode)) {
46651b65007eSDmitry Monakhov 				ext4_inode_block_unlocked_dio(inode);
46661c9114f9SDmitry Monakhov 				inode_dio_wait(inode);
46671b65007eSDmitry Monakhov 				ext4_inode_resume_unlocked_dio(inode);
466853e87268SJan Kara 			} else
466953e87268SJan Kara 				ext4_wait_for_tail_page_commit(inode);
46701b65007eSDmitry Monakhov 		}
467153e87268SJan Kara 		/*
467253e87268SJan Kara 		 * Truncate pagecache after we've waited for commit
467353e87268SJan Kara 		 * in data=journal mode to make pages freeable.
467453e87268SJan Kara 		 */
46757caef267SKirill A. Shutemov 			truncate_pagecache(inode, inode->i_size);
46761c9114f9SDmitry Monakhov 	}
46775208386cSJan Kara 	/*
46785208386cSJan Kara 	 * We want to call ext4_truncate() even if attr->ia_size ==
46795208386cSJan Kara 	 * inode->i_size for cases like truncation of fallocated space
46805208386cSJan Kara 	 */
46815208386cSJan Kara 	if (attr->ia_valid & ATTR_SIZE)
4682072bd7eaSTheodore Ts'o 		ext4_truncate(inode);
4683ac27a0ecSDave Kleikamp 
46841025774cSChristoph Hellwig 	if (!rc) {
46851025774cSChristoph Hellwig 		setattr_copy(inode, attr);
46861025774cSChristoph Hellwig 		mark_inode_dirty(inode);
46871025774cSChristoph Hellwig 	}
46881025774cSChristoph Hellwig 
46891025774cSChristoph Hellwig 	/*
46901025774cSChristoph Hellwig 	 * If the call to ext4_truncate failed to get a transaction handle at
46911025774cSChristoph Hellwig 	 * all, we need to clean up the in-core orphan list manually.
46921025774cSChristoph Hellwig 	 */
46933d287de3SDmitry Monakhov 	if (orphan && inode->i_nlink)
4694617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
4695ac27a0ecSDave Kleikamp 
4696ac27a0ecSDave Kleikamp 	if (!rc && (ia_valid & ATTR_MODE))
469764e178a7SChristoph Hellwig 		rc = posix_acl_chmod(inode, inode->i_mode);
4698ac27a0ecSDave Kleikamp 
4699ac27a0ecSDave Kleikamp err_out:
4700617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, error);
4701ac27a0ecSDave Kleikamp 	if (!error)
4702ac27a0ecSDave Kleikamp 		error = rc;
4703ac27a0ecSDave Kleikamp 	return error;
4704ac27a0ecSDave Kleikamp }
4705ac27a0ecSDave Kleikamp 
47063e3398a0SMingming Cao int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
47073e3398a0SMingming Cao 		 struct kstat *stat)
47083e3398a0SMingming Cao {
47093e3398a0SMingming Cao 	struct inode *inode;
47108af8eeccSJan Kara 	unsigned long long delalloc_blocks;
47113e3398a0SMingming Cao 
47123e3398a0SMingming Cao 	inode = dentry->d_inode;
47133e3398a0SMingming Cao 	generic_fillattr(inode, stat);
47143e3398a0SMingming Cao 
47153e3398a0SMingming Cao 	/*
47169206c561SAndreas Dilger 	 * If there is inline data in the inode, the inode will normally not
47179206c561SAndreas Dilger 	 * have data blocks allocated (it may have an external xattr block).
47189206c561SAndreas Dilger 	 * Report at least one sector for such files, so tools like tar, rsync,
47199206c561SAndreas Dilger 	 * others doen't incorrectly think the file is completely sparse.
47209206c561SAndreas Dilger 	 */
47219206c561SAndreas Dilger 	if (unlikely(ext4_has_inline_data(inode)))
47229206c561SAndreas Dilger 		stat->blocks += (stat->size + 511) >> 9;
47239206c561SAndreas Dilger 
47249206c561SAndreas Dilger 	/*
47253e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
47263e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
47273e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
47283e3398a0SMingming Cao 	 * on-disk file blocks.
47293e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
47303e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
47313e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
47323e3398a0SMingming Cao 	 * blocks for this file.
47333e3398a0SMingming Cao 	 */
473496607551STao Ma 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
473596607551STao Ma 				   EXT4_I(inode)->i_reserved_data_blocks);
47368af8eeccSJan Kara 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
47373e3398a0SMingming Cao 	return 0;
47383e3398a0SMingming Cao }
4739ac27a0ecSDave Kleikamp 
4740fffb2739SJan Kara static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
4741fffb2739SJan Kara 				   int pextents)
4742a02908f1SMingming Cao {
474312e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4744fffb2739SJan Kara 		return ext4_ind_trans_blocks(inode, lblocks);
4745fffb2739SJan Kara 	return ext4_ext_index_trans_blocks(inode, pextents);
4746a02908f1SMingming Cao }
4747ac51d837STheodore Ts'o 
4748a02908f1SMingming Cao /*
4749a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
4750a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
4751a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
4752a02908f1SMingming Cao  *
4753a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
47544907cb7bSAnatol Pomozov  * different block groups too. If they are contiguous, with flexbg,
4755a02908f1SMingming Cao  * they could still across block group boundary.
4756a02908f1SMingming Cao  *
4757a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
4758a02908f1SMingming Cao  */
4759fffb2739SJan Kara static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
4760fffb2739SJan Kara 				  int pextents)
4761a02908f1SMingming Cao {
47628df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
47638df9675fSTheodore Ts'o 	int gdpblocks;
4764a02908f1SMingming Cao 	int idxblocks;
4765a02908f1SMingming Cao 	int ret = 0;
4766a02908f1SMingming Cao 
4767a02908f1SMingming Cao 	/*
4768fffb2739SJan Kara 	 * How many index blocks need to touch to map @lblocks logical blocks
4769fffb2739SJan Kara 	 * to @pextents physical extents?
4770a02908f1SMingming Cao 	 */
4771fffb2739SJan Kara 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
4772a02908f1SMingming Cao 
4773a02908f1SMingming Cao 	ret = idxblocks;
4774a02908f1SMingming Cao 
4775a02908f1SMingming Cao 	/*
4776a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
4777a02908f1SMingming Cao 	 * to account
4778a02908f1SMingming Cao 	 */
4779fffb2739SJan Kara 	groups = idxblocks + pextents;
4780a02908f1SMingming Cao 	gdpblocks = groups;
47818df9675fSTheodore Ts'o 	if (groups > ngroups)
47828df9675fSTheodore Ts'o 		groups = ngroups;
4783a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4784a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4785a02908f1SMingming Cao 
4786a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
4787a02908f1SMingming Cao 	ret += groups + gdpblocks;
4788a02908f1SMingming Cao 
4789a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
4790a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4791ac27a0ecSDave Kleikamp 
4792ac27a0ecSDave Kleikamp 	return ret;
4793ac27a0ecSDave Kleikamp }
4794ac27a0ecSDave Kleikamp 
4795ac27a0ecSDave Kleikamp /*
479625985edcSLucas De Marchi  * Calculate the total number of credits to reserve to fit
4797f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
4798f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
4799a02908f1SMingming Cao  *
4800525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
4801a02908f1SMingming Cao  *
4802525f4ed8SMingming Cao  * We need to consider the worse case, when
4803a02908f1SMingming Cao  * one new block per extent.
4804a02908f1SMingming Cao  */
4805a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
4806a02908f1SMingming Cao {
4807a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
4808a02908f1SMingming Cao 	int ret;
4809a02908f1SMingming Cao 
4810fffb2739SJan Kara 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
4811a02908f1SMingming Cao 
4812a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
4813a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
4814a02908f1SMingming Cao 		ret += bpp;
4815a02908f1SMingming Cao 	return ret;
4816a02908f1SMingming Cao }
4817f3bd1f3fSMingming Cao 
4818f3bd1f3fSMingming Cao /*
4819f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
4820f3bd1f3fSMingming Cao  *
4821f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
482279e83036SEric Sandeen  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4823f3bd1f3fSMingming Cao  *
4824f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
4825f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
4826f3bd1f3fSMingming Cao  */
4827f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4828f3bd1f3fSMingming Cao {
4829f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
4830f3bd1f3fSMingming Cao }
4831f3bd1f3fSMingming Cao 
4832a02908f1SMingming Cao /*
4833617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
4834ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
4835ac27a0ecSDave Kleikamp  */
4836617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
4837617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
4838ac27a0ecSDave Kleikamp {
4839ac27a0ecSDave Kleikamp 	int err = 0;
4840ac27a0ecSDave Kleikamp 
4841c64db50eSTheodore Ts'o 	if (IS_I_VERSION(inode))
484225ec56b5SJean Noel Cordenner 		inode_inc_iversion(inode);
484325ec56b5SJean Noel Cordenner 
4844ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
4845ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
4846ac27a0ecSDave Kleikamp 
4847dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4848830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
4849ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
4850ac27a0ecSDave Kleikamp 	return err;
4851ac27a0ecSDave Kleikamp }
4852ac27a0ecSDave Kleikamp 
4853ac27a0ecSDave Kleikamp /*
4854ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
4855ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
4856ac27a0ecSDave Kleikamp  */
4857ac27a0ecSDave Kleikamp 
4858ac27a0ecSDave Kleikamp int
4859617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4860617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
4861ac27a0ecSDave Kleikamp {
48620390131bSFrank Mayhar 	int err;
48630390131bSFrank Mayhar 
4864617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
4865ac27a0ecSDave Kleikamp 	if (!err) {
4866ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
4867617ba13bSMingming Cao 		err = ext4_journal_get_write_access(handle, iloc->bh);
4868ac27a0ecSDave Kleikamp 		if (err) {
4869ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
4870ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
4871ac27a0ecSDave Kleikamp 		}
4872ac27a0ecSDave Kleikamp 	}
4873617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
4874ac27a0ecSDave Kleikamp 	return err;
4875ac27a0ecSDave Kleikamp }
4876ac27a0ecSDave Kleikamp 
4877ac27a0ecSDave Kleikamp /*
48786dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
48796dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
48806dd4ee7cSKalpak Shah  */
48811d03ec98SAneesh Kumar K.V static int ext4_expand_extra_isize(struct inode *inode,
48821d03ec98SAneesh Kumar K.V 				   unsigned int new_extra_isize,
48831d03ec98SAneesh Kumar K.V 				   struct ext4_iloc iloc,
48841d03ec98SAneesh Kumar K.V 				   handle_t *handle)
48856dd4ee7cSKalpak Shah {
48866dd4ee7cSKalpak Shah 	struct ext4_inode *raw_inode;
48876dd4ee7cSKalpak Shah 	struct ext4_xattr_ibody_header *header;
48886dd4ee7cSKalpak Shah 
48896dd4ee7cSKalpak Shah 	if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
48906dd4ee7cSKalpak Shah 		return 0;
48916dd4ee7cSKalpak Shah 
48926dd4ee7cSKalpak Shah 	raw_inode = ext4_raw_inode(&iloc);
48936dd4ee7cSKalpak Shah 
48946dd4ee7cSKalpak Shah 	header = IHDR(inode, raw_inode);
48956dd4ee7cSKalpak Shah 
48966dd4ee7cSKalpak Shah 	/* No extended attributes present */
489719f5fb7aSTheodore Ts'o 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
48986dd4ee7cSKalpak Shah 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
48996dd4ee7cSKalpak Shah 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
49006dd4ee7cSKalpak Shah 			new_extra_isize);
49016dd4ee7cSKalpak Shah 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
49026dd4ee7cSKalpak Shah 		return 0;
49036dd4ee7cSKalpak Shah 	}
49046dd4ee7cSKalpak Shah 
49056dd4ee7cSKalpak Shah 	/* try to expand with EAs present */
49066dd4ee7cSKalpak Shah 	return ext4_expand_extra_isize_ea(inode, new_extra_isize,
49076dd4ee7cSKalpak Shah 					  raw_inode, handle);
49086dd4ee7cSKalpak Shah }
49096dd4ee7cSKalpak Shah 
49106dd4ee7cSKalpak Shah /*
4911ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
4912ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
4913ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
4914ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
4915ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
4916ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
4917ac27a0ecSDave Kleikamp  *
4918ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
4919ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
4920ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4921ac27a0ecSDave Kleikamp  * we start and wait on commits.
4922ac27a0ecSDave Kleikamp  */
4923617ba13bSMingming Cao int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4924ac27a0ecSDave Kleikamp {
4925617ba13bSMingming Cao 	struct ext4_iloc iloc;
49266dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
49276dd4ee7cSKalpak Shah 	static unsigned int mnt_count;
49286dd4ee7cSKalpak Shah 	int err, ret;
4929ac27a0ecSDave Kleikamp 
4930ac27a0ecSDave Kleikamp 	might_sleep();
49317ff9c073STheodore Ts'o 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4932617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
49330390131bSFrank Mayhar 	if (ext4_handle_valid(handle) &&
49340390131bSFrank Mayhar 	    EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
493519f5fb7aSTheodore Ts'o 	    !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
49366dd4ee7cSKalpak Shah 		/*
49376dd4ee7cSKalpak Shah 		 * We need extra buffer credits since we may write into EA block
49386dd4ee7cSKalpak Shah 		 * with this same handle. If journal_extend fails, then it will
49396dd4ee7cSKalpak Shah 		 * only result in a minor loss of functionality for that inode.
49406dd4ee7cSKalpak Shah 		 * If this is felt to be critical, then e2fsck should be run to
49416dd4ee7cSKalpak Shah 		 * force a large enough s_min_extra_isize.
49426dd4ee7cSKalpak Shah 		 */
49436dd4ee7cSKalpak Shah 		if ((jbd2_journal_extend(handle,
49446dd4ee7cSKalpak Shah 			     EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
49456dd4ee7cSKalpak Shah 			ret = ext4_expand_extra_isize(inode,
49466dd4ee7cSKalpak Shah 						      sbi->s_want_extra_isize,
49476dd4ee7cSKalpak Shah 						      iloc, handle);
49486dd4ee7cSKalpak Shah 			if (ret) {
494919f5fb7aSTheodore Ts'o 				ext4_set_inode_state(inode,
495019f5fb7aSTheodore Ts'o 						     EXT4_STATE_NO_EXPAND);
4951c1bddad9SAneesh Kumar K.V 				if (mnt_count !=
4952c1bddad9SAneesh Kumar K.V 					le16_to_cpu(sbi->s_es->s_mnt_count)) {
495312062dddSEric Sandeen 					ext4_warning(inode->i_sb,
49546dd4ee7cSKalpak Shah 					"Unable to expand inode %lu. Delete"
49556dd4ee7cSKalpak Shah 					" some EAs or run e2fsck.",
49566dd4ee7cSKalpak Shah 					inode->i_ino);
4957c1bddad9SAneesh Kumar K.V 					mnt_count =
4958c1bddad9SAneesh Kumar K.V 					  le16_to_cpu(sbi->s_es->s_mnt_count);
49596dd4ee7cSKalpak Shah 				}
49606dd4ee7cSKalpak Shah 			}
49616dd4ee7cSKalpak Shah 		}
49626dd4ee7cSKalpak Shah 	}
4963ac27a0ecSDave Kleikamp 	if (!err)
4964617ba13bSMingming Cao 		err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4965ac27a0ecSDave Kleikamp 	return err;
4966ac27a0ecSDave Kleikamp }
4967ac27a0ecSDave Kleikamp 
4968ac27a0ecSDave Kleikamp /*
4969617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
4970ac27a0ecSDave Kleikamp  *
4971ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
4972ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
4973ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
4974ac27a0ecSDave Kleikamp  *
49755dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
4976ac27a0ecSDave Kleikamp  * are allocated to the file.
4977ac27a0ecSDave Kleikamp  *
4978ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
4979ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
4980ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
4981ac27a0ecSDave Kleikamp  */
4982aa385729SChristoph Hellwig void ext4_dirty_inode(struct inode *inode, int flags)
4983ac27a0ecSDave Kleikamp {
4984ac27a0ecSDave Kleikamp 	handle_t *handle;
4985ac27a0ecSDave Kleikamp 
49869924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
4987ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
4988ac27a0ecSDave Kleikamp 		goto out;
4989f3dc272fSCurt Wohlgemuth 
4990617ba13bSMingming Cao 	ext4_mark_inode_dirty(handle, inode);
4991f3dc272fSCurt Wohlgemuth 
4992617ba13bSMingming Cao 	ext4_journal_stop(handle);
4993ac27a0ecSDave Kleikamp out:
4994ac27a0ecSDave Kleikamp 	return;
4995ac27a0ecSDave Kleikamp }
4996ac27a0ecSDave Kleikamp 
4997ac27a0ecSDave Kleikamp #if 0
4998ac27a0ecSDave Kleikamp /*
4999ac27a0ecSDave Kleikamp  * Bind an inode's backing buffer_head into this transaction, to prevent
5000ac27a0ecSDave Kleikamp  * it from being flushed to disk early.  Unlike
5001617ba13bSMingming Cao  * ext4_reserve_inode_write, this leaves behind no bh reference and
5002ac27a0ecSDave Kleikamp  * returns no iloc structure, so the caller needs to repeat the iloc
5003ac27a0ecSDave Kleikamp  * lookup to mark the inode dirty later.
5004ac27a0ecSDave Kleikamp  */
5005617ba13bSMingming Cao static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5006ac27a0ecSDave Kleikamp {
5007617ba13bSMingming Cao 	struct ext4_iloc iloc;
5008ac27a0ecSDave Kleikamp 
5009ac27a0ecSDave Kleikamp 	int err = 0;
5010ac27a0ecSDave Kleikamp 	if (handle) {
5011617ba13bSMingming Cao 		err = ext4_get_inode_loc(inode, &iloc);
5012ac27a0ecSDave Kleikamp 		if (!err) {
5013ac27a0ecSDave Kleikamp 			BUFFER_TRACE(iloc.bh, "get_write_access");
5014dab291afSMingming Cao 			err = jbd2_journal_get_write_access(handle, iloc.bh);
5015ac27a0ecSDave Kleikamp 			if (!err)
50160390131bSFrank Mayhar 				err = ext4_handle_dirty_metadata(handle,
501773b50c1cSCurt Wohlgemuth 								 NULL,
5018ac27a0ecSDave Kleikamp 								 iloc.bh);
5019ac27a0ecSDave Kleikamp 			brelse(iloc.bh);
5020ac27a0ecSDave Kleikamp 		}
5021ac27a0ecSDave Kleikamp 	}
5022617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5023ac27a0ecSDave Kleikamp 	return err;
5024ac27a0ecSDave Kleikamp }
5025ac27a0ecSDave Kleikamp #endif
5026ac27a0ecSDave Kleikamp 
5027617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
5028ac27a0ecSDave Kleikamp {
5029ac27a0ecSDave Kleikamp 	journal_t *journal;
5030ac27a0ecSDave Kleikamp 	handle_t *handle;
5031ac27a0ecSDave Kleikamp 	int err;
5032ac27a0ecSDave Kleikamp 
5033ac27a0ecSDave Kleikamp 	/*
5034ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
5035ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
5036ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
5037ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
5038ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
5039ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
5040ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
5041ac27a0ecSDave Kleikamp 	 */
5042ac27a0ecSDave Kleikamp 
5043617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
50440390131bSFrank Mayhar 	if (!journal)
50450390131bSFrank Mayhar 		return 0;
5046d699594dSDave Hansen 	if (is_journal_aborted(journal))
5047ac27a0ecSDave Kleikamp 		return -EROFS;
50482aff57b0SYongqiang Yang 	/* We have to allocate physical blocks for delalloc blocks
50492aff57b0SYongqiang Yang 	 * before flushing journal. otherwise delalloc blocks can not
50502aff57b0SYongqiang Yang 	 * be allocated any more. even more truncate on delalloc blocks
50512aff57b0SYongqiang Yang 	 * could trigger BUG by flushing delalloc blocks in journal.
50522aff57b0SYongqiang Yang 	 * There is no delalloc block in non-journal data mode.
50532aff57b0SYongqiang Yang 	 */
50542aff57b0SYongqiang Yang 	if (val && test_opt(inode->i_sb, DELALLOC)) {
50552aff57b0SYongqiang Yang 		err = ext4_alloc_da_blocks(inode);
50562aff57b0SYongqiang Yang 		if (err < 0)
50572aff57b0SYongqiang Yang 			return err;
50582aff57b0SYongqiang Yang 	}
5059ac27a0ecSDave Kleikamp 
506017335dccSDmitry Monakhov 	/* Wait for all existing dio workers */
506117335dccSDmitry Monakhov 	ext4_inode_block_unlocked_dio(inode);
506217335dccSDmitry Monakhov 	inode_dio_wait(inode);
506317335dccSDmitry Monakhov 
5064dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
5065ac27a0ecSDave Kleikamp 
5066ac27a0ecSDave Kleikamp 	/*
5067ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
5068ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
5069ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
5070ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
5071ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
5072ac27a0ecSDave Kleikamp 	 */
5073ac27a0ecSDave Kleikamp 
5074ac27a0ecSDave Kleikamp 	if (val)
507512e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
50765872ddaaSYongqiang Yang 	else {
50775872ddaaSYongqiang Yang 		jbd2_journal_flush(journal);
507812e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
50795872ddaaSYongqiang Yang 	}
5080617ba13bSMingming Cao 	ext4_set_aops(inode);
5081ac27a0ecSDave Kleikamp 
5082dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
508317335dccSDmitry Monakhov 	ext4_inode_resume_unlocked_dio(inode);
5084ac27a0ecSDave Kleikamp 
5085ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
5086ac27a0ecSDave Kleikamp 
50879924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5088ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5089ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
5090ac27a0ecSDave Kleikamp 
5091617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
50920390131bSFrank Mayhar 	ext4_handle_sync(handle);
5093617ba13bSMingming Cao 	ext4_journal_stop(handle);
5094617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5095ac27a0ecSDave Kleikamp 
5096ac27a0ecSDave Kleikamp 	return err;
5097ac27a0ecSDave Kleikamp }
50982e9ee850SAneesh Kumar K.V 
50992e9ee850SAneesh Kumar K.V static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
51002e9ee850SAneesh Kumar K.V {
51012e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
51022e9ee850SAneesh Kumar K.V }
51032e9ee850SAneesh Kumar K.V 
5104c2ec175cSNick Piggin int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
51052e9ee850SAneesh Kumar K.V {
5106c2ec175cSNick Piggin 	struct page *page = vmf->page;
51072e9ee850SAneesh Kumar K.V 	loff_t size;
51082e9ee850SAneesh Kumar K.V 	unsigned long len;
51099ea7df53SJan Kara 	int ret;
51102e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
5111496ad9aaSAl Viro 	struct inode *inode = file_inode(file);
51122e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
51139ea7df53SJan Kara 	handle_t *handle;
51149ea7df53SJan Kara 	get_block_t *get_block;
51159ea7df53SJan Kara 	int retries = 0;
51162e9ee850SAneesh Kumar K.V 
51178e8ad8a5SJan Kara 	sb_start_pagefault(inode->i_sb);
5118041bbb6dSTheodore Ts'o 	file_update_time(vma->vm_file);
51199ea7df53SJan Kara 	/* Delalloc case is easy... */
51209ea7df53SJan Kara 	if (test_opt(inode->i_sb, DELALLOC) &&
51219ea7df53SJan Kara 	    !ext4_should_journal_data(inode) &&
51229ea7df53SJan Kara 	    !ext4_nonda_switch(inode->i_sb)) {
51239ea7df53SJan Kara 		do {
51249ea7df53SJan Kara 			ret = __block_page_mkwrite(vma, vmf,
51259ea7df53SJan Kara 						   ext4_da_get_block_prep);
51269ea7df53SJan Kara 		} while (ret == -ENOSPC &&
51279ea7df53SJan Kara 		       ext4_should_retry_alloc(inode->i_sb, &retries));
51289ea7df53SJan Kara 		goto out_ret;
51292e9ee850SAneesh Kumar K.V 	}
51300e499890SDarrick J. Wong 
51310e499890SDarrick J. Wong 	lock_page(page);
51329ea7df53SJan Kara 	size = i_size_read(inode);
51339ea7df53SJan Kara 	/* Page got truncated from under us? */
51349ea7df53SJan Kara 	if (page->mapping != mapping || page_offset(page) > size) {
51359ea7df53SJan Kara 		unlock_page(page);
51369ea7df53SJan Kara 		ret = VM_FAULT_NOPAGE;
51379ea7df53SJan Kara 		goto out;
51380e499890SDarrick J. Wong 	}
51392e9ee850SAneesh Kumar K.V 
51402e9ee850SAneesh Kumar K.V 	if (page->index == size >> PAGE_CACHE_SHIFT)
51412e9ee850SAneesh Kumar K.V 		len = size & ~PAGE_CACHE_MASK;
51422e9ee850SAneesh Kumar K.V 	else
51432e9ee850SAneesh Kumar K.V 		len = PAGE_CACHE_SIZE;
5144a827eaffSAneesh Kumar K.V 	/*
51459ea7df53SJan Kara 	 * Return if we have all the buffers mapped. This avoids the need to do
51469ea7df53SJan Kara 	 * journal_start/journal_stop which can block and take a long time
5147a827eaffSAneesh Kumar K.V 	 */
51482e9ee850SAneesh Kumar K.V 	if (page_has_buffers(page)) {
5149f19d5870STao Ma 		if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5150f19d5870STao Ma 					    0, len, NULL,
5151a827eaffSAneesh Kumar K.V 					    ext4_bh_unmapped)) {
51529ea7df53SJan Kara 			/* Wait so that we don't change page under IO */
51531d1d1a76SDarrick J. Wong 			wait_for_stable_page(page);
51549ea7df53SJan Kara 			ret = VM_FAULT_LOCKED;
51559ea7df53SJan Kara 			goto out;
51562e9ee850SAneesh Kumar K.V 		}
5157a827eaffSAneesh Kumar K.V 	}
5158a827eaffSAneesh Kumar K.V 	unlock_page(page);
51599ea7df53SJan Kara 	/* OK, we need to fill the hole... */
51609ea7df53SJan Kara 	if (ext4_should_dioread_nolock(inode))
51619ea7df53SJan Kara 		get_block = ext4_get_block_write;
51629ea7df53SJan Kara 	else
51639ea7df53SJan Kara 		get_block = ext4_get_block;
51649ea7df53SJan Kara retry_alloc:
51659924a92aSTheodore Ts'o 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
51669924a92aSTheodore Ts'o 				    ext4_writepage_trans_blocks(inode));
51679ea7df53SJan Kara 	if (IS_ERR(handle)) {
5168c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
51699ea7df53SJan Kara 		goto out;
51709ea7df53SJan Kara 	}
51719ea7df53SJan Kara 	ret = __block_page_mkwrite(vma, vmf, get_block);
51729ea7df53SJan Kara 	if (!ret && ext4_should_journal_data(inode)) {
5173f19d5870STao Ma 		if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
51749ea7df53SJan Kara 			  PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
51759ea7df53SJan Kara 			unlock_page(page);
51769ea7df53SJan Kara 			ret = VM_FAULT_SIGBUS;
5177fcbb5515SYongqiang Yang 			ext4_journal_stop(handle);
51789ea7df53SJan Kara 			goto out;
51799ea7df53SJan Kara 		}
51809ea7df53SJan Kara 		ext4_set_inode_state(inode, EXT4_STATE_JDATA);
51819ea7df53SJan Kara 	}
51829ea7df53SJan Kara 	ext4_journal_stop(handle);
51839ea7df53SJan Kara 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
51849ea7df53SJan Kara 		goto retry_alloc;
51859ea7df53SJan Kara out_ret:
51869ea7df53SJan Kara 	ret = block_page_mkwrite_return(ret);
51879ea7df53SJan Kara out:
51888e8ad8a5SJan Kara 	sb_end_pagefault(inode->i_sb);
51892e9ee850SAneesh Kumar K.V 	return ret;
51902e9ee850SAneesh Kumar K.V }
5191