xref: /openbmc/linux/fs/ext4/inode.c (revision c398eda0e43a791be0fca6f197a1e2bbb9f16070)
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  *  Goal-directed block allocation by Stephen Tweedie
16ac27a0ecSDave Kleikamp  *	(sct@redhat.com), 1993, 1998
17ac27a0ecSDave Kleikamp  *  Big-endian to little-endian byte-swapping/bitmaps by
18ac27a0ecSDave Kleikamp  *        David S. Miller (davem@caip.rutgers.edu), 1995
19ac27a0ecSDave Kleikamp  *  64-bit file support on 64-bit platforms by Jakub Jelinek
20ac27a0ecSDave Kleikamp  *	(jj@sunsite.ms.mff.cuni.cz)
21ac27a0ecSDave Kleikamp  *
22617ba13bSMingming Cao  *  Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
23ac27a0ecSDave Kleikamp  */
24ac27a0ecSDave Kleikamp 
25ac27a0ecSDave Kleikamp #include <linux/module.h>
26ac27a0ecSDave Kleikamp #include <linux/fs.h>
27ac27a0ecSDave Kleikamp #include <linux/time.h>
28dab291afSMingming Cao #include <linux/jbd2.h>
29ac27a0ecSDave Kleikamp #include <linux/highuid.h>
30ac27a0ecSDave Kleikamp #include <linux/pagemap.h>
31ac27a0ecSDave Kleikamp #include <linux/quotaops.h>
32ac27a0ecSDave Kleikamp #include <linux/string.h>
33ac27a0ecSDave Kleikamp #include <linux/buffer_head.h>
34ac27a0ecSDave Kleikamp #include <linux/writeback.h>
3564769240SAlex Tomas #include <linux/pagevec.h>
36ac27a0ecSDave Kleikamp #include <linux/mpage.h>
37e83c1397SDuane Griffin #include <linux/namei.h>
38ac27a0ecSDave Kleikamp #include <linux/uio.h>
39ac27a0ecSDave Kleikamp #include <linux/bio.h>
404c0425ffSMingming Cao #include <linux/workqueue.h>
41744692dcSJiaying Zhang #include <linux/kernel.h>
425a0e3ad6STejun Heo #include <linux/slab.h>
439bffad1eSTheodore Ts'o 
443dcf5451SChristoph Hellwig #include "ext4_jbd2.h"
45ac27a0ecSDave Kleikamp #include "xattr.h"
46ac27a0ecSDave Kleikamp #include "acl.h"
47d2a17637SMingming Cao #include "ext4_extents.h"
48ac27a0ecSDave Kleikamp 
499bffad1eSTheodore Ts'o #include <trace/events/ext4.h>
509bffad1eSTheodore Ts'o 
51a1d6cc56SAneesh Kumar K.V #define MPAGE_DA_EXTENT_TAIL 0x01
52a1d6cc56SAneesh Kumar K.V 
53678aaf48SJan Kara static inline int ext4_begin_ordered_truncate(struct inode *inode,
54678aaf48SJan Kara 					      loff_t new_size)
55678aaf48SJan Kara {
567f5aa215SJan Kara 	return jbd2_journal_begin_ordered_truncate(
577f5aa215SJan Kara 					EXT4_SB(inode->i_sb)->s_journal,
587f5aa215SJan Kara 					&EXT4_I(inode)->jinode,
59678aaf48SJan Kara 					new_size);
60678aaf48SJan Kara }
61678aaf48SJan Kara 
6264769240SAlex Tomas static void ext4_invalidatepage(struct page *page, unsigned long offset);
6364769240SAlex Tomas 
64ac27a0ecSDave Kleikamp /*
65ac27a0ecSDave Kleikamp  * Test whether an inode is a fast symlink.
66ac27a0ecSDave Kleikamp  */
67617ba13bSMingming Cao static int ext4_inode_is_fast_symlink(struct inode *inode)
68ac27a0ecSDave Kleikamp {
69617ba13bSMingming Cao 	int ea_blocks = EXT4_I(inode)->i_file_acl ?
70ac27a0ecSDave Kleikamp 		(inode->i_sb->s_blocksize >> 9) : 0;
71ac27a0ecSDave Kleikamp 
72ac27a0ecSDave Kleikamp 	return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
73ac27a0ecSDave Kleikamp }
74ac27a0ecSDave Kleikamp 
75ac27a0ecSDave Kleikamp /*
76ac27a0ecSDave Kleikamp  * Work out how many blocks we need to proceed with the next chunk of a
77ac27a0ecSDave Kleikamp  * truncate transaction.
78ac27a0ecSDave Kleikamp  */
79ac27a0ecSDave Kleikamp static unsigned long blocks_for_truncate(struct inode *inode)
80ac27a0ecSDave Kleikamp {
81725d26d3SAneesh Kumar K.V 	ext4_lblk_t needed;
82ac27a0ecSDave Kleikamp 
83ac27a0ecSDave Kleikamp 	needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
84ac27a0ecSDave Kleikamp 
85ac27a0ecSDave Kleikamp 	/* Give ourselves just enough room to cope with inodes in which
86ac27a0ecSDave Kleikamp 	 * i_blocks is corrupt: we've seen disk corruptions in the past
87ac27a0ecSDave Kleikamp 	 * which resulted in random data in an inode which looked enough
88617ba13bSMingming Cao 	 * like a regular file for ext4 to try to delete it.  Things
89ac27a0ecSDave Kleikamp 	 * will go a bit crazy if that happens, but at least we should
90ac27a0ecSDave Kleikamp 	 * try not to panic the whole kernel. */
91ac27a0ecSDave Kleikamp 	if (needed < 2)
92ac27a0ecSDave Kleikamp 		needed = 2;
93ac27a0ecSDave Kleikamp 
94ac27a0ecSDave Kleikamp 	/* But we need to bound the transaction so we don't overflow the
95ac27a0ecSDave Kleikamp 	 * journal. */
96617ba13bSMingming Cao 	if (needed > EXT4_MAX_TRANS_DATA)
97617ba13bSMingming Cao 		needed = EXT4_MAX_TRANS_DATA;
98ac27a0ecSDave Kleikamp 
99617ba13bSMingming Cao 	return EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + needed;
100ac27a0ecSDave Kleikamp }
101ac27a0ecSDave Kleikamp 
102ac27a0ecSDave Kleikamp /*
103ac27a0ecSDave Kleikamp  * Truncate transactions can be complex and absolutely huge.  So we need to
104ac27a0ecSDave Kleikamp  * be able to restart the transaction at a conventient checkpoint to make
105ac27a0ecSDave Kleikamp  * sure we don't overflow the journal.
106ac27a0ecSDave Kleikamp  *
107ac27a0ecSDave Kleikamp  * start_transaction gets us a new handle for a truncate transaction,
108ac27a0ecSDave Kleikamp  * and extend_transaction tries to extend the existing one a bit.  If
109ac27a0ecSDave Kleikamp  * extend fails, we need to propagate the failure up and restart the
110ac27a0ecSDave Kleikamp  * transaction in the top-level truncate loop. --sct
111ac27a0ecSDave Kleikamp  */
112ac27a0ecSDave Kleikamp static handle_t *start_transaction(struct inode *inode)
113ac27a0ecSDave Kleikamp {
114ac27a0ecSDave Kleikamp 	handle_t *result;
115ac27a0ecSDave Kleikamp 
116617ba13bSMingming Cao 	result = ext4_journal_start(inode, blocks_for_truncate(inode));
117ac27a0ecSDave Kleikamp 	if (!IS_ERR(result))
118ac27a0ecSDave Kleikamp 		return result;
119ac27a0ecSDave Kleikamp 
120617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, PTR_ERR(result));
121ac27a0ecSDave Kleikamp 	return result;
122ac27a0ecSDave Kleikamp }
123ac27a0ecSDave Kleikamp 
124ac27a0ecSDave Kleikamp /*
125ac27a0ecSDave Kleikamp  * Try to extend this transaction for the purposes of truncation.
126ac27a0ecSDave Kleikamp  *
127ac27a0ecSDave Kleikamp  * Returns 0 if we managed to create more room.  If we can't create more
128ac27a0ecSDave Kleikamp  * room, and the transaction must be restarted we return 1.
129ac27a0ecSDave Kleikamp  */
130ac27a0ecSDave Kleikamp static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
131ac27a0ecSDave Kleikamp {
1320390131bSFrank Mayhar 	if (!ext4_handle_valid(handle))
1330390131bSFrank Mayhar 		return 0;
1340390131bSFrank Mayhar 	if (ext4_handle_has_enough_credits(handle, EXT4_RESERVE_TRANS_BLOCKS+1))
135ac27a0ecSDave Kleikamp 		return 0;
136617ba13bSMingming Cao 	if (!ext4_journal_extend(handle, blocks_for_truncate(inode)))
137ac27a0ecSDave Kleikamp 		return 0;
138ac27a0ecSDave Kleikamp 	return 1;
139ac27a0ecSDave Kleikamp }
140ac27a0ecSDave Kleikamp 
141ac27a0ecSDave Kleikamp /*
142ac27a0ecSDave Kleikamp  * Restart the transaction associated with *handle.  This does a commit,
143ac27a0ecSDave Kleikamp  * so before we call here everything must be consistently dirtied against
144ac27a0ecSDave Kleikamp  * this transaction.
145ac27a0ecSDave Kleikamp  */
146487caeefSJan Kara int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
147487caeefSJan Kara 				 int nblocks)
148ac27a0ecSDave Kleikamp {
149487caeefSJan Kara 	int ret;
150487caeefSJan Kara 
151487caeefSJan Kara 	/*
152e35fd660STheodore Ts'o 	 * Drop i_data_sem to avoid deadlock with ext4_map_blocks.  At this
153487caeefSJan Kara 	 * moment, get_block can be called only for blocks inside i_size since
154487caeefSJan Kara 	 * page cache has been already dropped and writes are blocked by
155487caeefSJan Kara 	 * i_mutex. So we can safely drop the i_data_sem here.
156487caeefSJan Kara 	 */
1570390131bSFrank Mayhar 	BUG_ON(EXT4_JOURNAL(inode) == NULL);
158ac27a0ecSDave Kleikamp 	jbd_debug(2, "restarting handle %p\n", handle);
159487caeefSJan Kara 	up_write(&EXT4_I(inode)->i_data_sem);
160487caeefSJan Kara 	ret = ext4_journal_restart(handle, blocks_for_truncate(inode));
161487caeefSJan Kara 	down_write(&EXT4_I(inode)->i_data_sem);
162fa5d1113SAneesh Kumar K.V 	ext4_discard_preallocations(inode);
163487caeefSJan Kara 
164487caeefSJan Kara 	return ret;
165ac27a0ecSDave Kleikamp }
166ac27a0ecSDave Kleikamp 
167ac27a0ecSDave Kleikamp /*
168ac27a0ecSDave Kleikamp  * Called at the last iput() if i_nlink is zero.
169ac27a0ecSDave Kleikamp  */
170617ba13bSMingming Cao void ext4_delete_inode(struct inode *inode)
171ac27a0ecSDave Kleikamp {
172ac27a0ecSDave Kleikamp 	handle_t *handle;
173bc965ab3STheodore Ts'o 	int err;
174ac27a0ecSDave Kleikamp 
175907f4554SChristoph Hellwig 	if (!is_bad_inode(inode))
176871a2931SChristoph Hellwig 		dquot_initialize(inode);
177907f4554SChristoph Hellwig 
178678aaf48SJan Kara 	if (ext4_should_order_data(inode))
179678aaf48SJan Kara 		ext4_begin_ordered_truncate(inode, 0);
180ac27a0ecSDave Kleikamp 	truncate_inode_pages(&inode->i_data, 0);
181ac27a0ecSDave Kleikamp 
182ac27a0ecSDave Kleikamp 	if (is_bad_inode(inode))
183ac27a0ecSDave Kleikamp 		goto no_delete;
184ac27a0ecSDave Kleikamp 
185bc965ab3STheodore Ts'o 	handle = ext4_journal_start(inode, blocks_for_truncate(inode)+3);
186ac27a0ecSDave Kleikamp 	if (IS_ERR(handle)) {
187bc965ab3STheodore Ts'o 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
188ac27a0ecSDave Kleikamp 		/*
189ac27a0ecSDave Kleikamp 		 * If we're going to skip the normal cleanup, we still need to
190ac27a0ecSDave Kleikamp 		 * make sure that the in-core orphan linked list is properly
191ac27a0ecSDave Kleikamp 		 * cleaned up.
192ac27a0ecSDave Kleikamp 		 */
193617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
194ac27a0ecSDave Kleikamp 		goto no_delete;
195ac27a0ecSDave Kleikamp 	}
196ac27a0ecSDave Kleikamp 
197ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
1980390131bSFrank Mayhar 		ext4_handle_sync(handle);
199ac27a0ecSDave Kleikamp 	inode->i_size = 0;
200bc965ab3STheodore Ts'o 	err = ext4_mark_inode_dirty(handle, inode);
201bc965ab3STheodore Ts'o 	if (err) {
20212062dddSEric Sandeen 		ext4_warning(inode->i_sb,
203bc965ab3STheodore Ts'o 			     "couldn't mark inode dirty (err %d)", err);
204bc965ab3STheodore Ts'o 		goto stop_handle;
205bc965ab3STheodore Ts'o 	}
206ac27a0ecSDave Kleikamp 	if (inode->i_blocks)
207617ba13bSMingming Cao 		ext4_truncate(inode);
208bc965ab3STheodore Ts'o 
209bc965ab3STheodore Ts'o 	/*
210bc965ab3STheodore Ts'o 	 * ext4_ext_truncate() doesn't reserve any slop when it
211bc965ab3STheodore Ts'o 	 * restarts journal transactions; therefore there may not be
212bc965ab3STheodore Ts'o 	 * enough credits left in the handle to remove the inode from
213bc965ab3STheodore Ts'o 	 * the orphan list and set the dtime field.
214bc965ab3STheodore Ts'o 	 */
2150390131bSFrank Mayhar 	if (!ext4_handle_has_enough_credits(handle, 3)) {
216bc965ab3STheodore Ts'o 		err = ext4_journal_extend(handle, 3);
217bc965ab3STheodore Ts'o 		if (err > 0)
218bc965ab3STheodore Ts'o 			err = ext4_journal_restart(handle, 3);
219bc965ab3STheodore Ts'o 		if (err != 0) {
22012062dddSEric Sandeen 			ext4_warning(inode->i_sb,
221bc965ab3STheodore Ts'o 				     "couldn't extend journal (err %d)", err);
222bc965ab3STheodore Ts'o 		stop_handle:
223bc965ab3STheodore Ts'o 			ext4_journal_stop(handle);
224bc965ab3STheodore Ts'o 			goto no_delete;
225bc965ab3STheodore Ts'o 		}
226bc965ab3STheodore Ts'o 	}
227bc965ab3STheodore Ts'o 
228ac27a0ecSDave Kleikamp 	/*
229617ba13bSMingming Cao 	 * Kill off the orphan record which ext4_truncate created.
230ac27a0ecSDave Kleikamp 	 * AKPM: I think this can be inside the above `if'.
231617ba13bSMingming Cao 	 * Note that ext4_orphan_del() has to be able to cope with the
232ac27a0ecSDave Kleikamp 	 * deletion of a non-existent orphan - this is because we don't
233617ba13bSMingming Cao 	 * know if ext4_truncate() actually created an orphan record.
234ac27a0ecSDave Kleikamp 	 * (Well, we could do this if we need to, but heck - it works)
235ac27a0ecSDave Kleikamp 	 */
236617ba13bSMingming Cao 	ext4_orphan_del(handle, inode);
237617ba13bSMingming Cao 	EXT4_I(inode)->i_dtime	= get_seconds();
238ac27a0ecSDave Kleikamp 
239ac27a0ecSDave Kleikamp 	/*
240ac27a0ecSDave Kleikamp 	 * One subtle ordering requirement: if anything has gone wrong
241ac27a0ecSDave Kleikamp 	 * (transaction abort, IO errors, whatever), then we can still
242ac27a0ecSDave Kleikamp 	 * do these next steps (the fs will already have been marked as
243ac27a0ecSDave Kleikamp 	 * having errors), but we can't free the inode if the mark_dirty
244ac27a0ecSDave Kleikamp 	 * fails.
245ac27a0ecSDave Kleikamp 	 */
246617ba13bSMingming Cao 	if (ext4_mark_inode_dirty(handle, inode))
247ac27a0ecSDave Kleikamp 		/* If that failed, just do the required in-core inode clear. */
248ac27a0ecSDave Kleikamp 		clear_inode(inode);
249ac27a0ecSDave Kleikamp 	else
250617ba13bSMingming Cao 		ext4_free_inode(handle, inode);
251617ba13bSMingming Cao 	ext4_journal_stop(handle);
252ac27a0ecSDave Kleikamp 	return;
253ac27a0ecSDave Kleikamp no_delete:
254ac27a0ecSDave Kleikamp 	clear_inode(inode);	/* We must guarantee clearing of inode... */
255ac27a0ecSDave Kleikamp }
256ac27a0ecSDave Kleikamp 
257ac27a0ecSDave Kleikamp typedef struct {
258ac27a0ecSDave Kleikamp 	__le32	*p;
259ac27a0ecSDave Kleikamp 	__le32	key;
260ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
261ac27a0ecSDave Kleikamp } Indirect;
262ac27a0ecSDave Kleikamp 
263ac27a0ecSDave Kleikamp static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
264ac27a0ecSDave Kleikamp {
265ac27a0ecSDave Kleikamp 	p->key = *(p->p = v);
266ac27a0ecSDave Kleikamp 	p->bh = bh;
267ac27a0ecSDave Kleikamp }
268ac27a0ecSDave Kleikamp 
269ac27a0ecSDave Kleikamp /**
270617ba13bSMingming Cao  *	ext4_block_to_path - parse the block number into array of offsets
271ac27a0ecSDave Kleikamp  *	@inode: inode in question (we are only interested in its superblock)
272ac27a0ecSDave Kleikamp  *	@i_block: block number to be parsed
273ac27a0ecSDave Kleikamp  *	@offsets: array to store the offsets in
274ac27a0ecSDave Kleikamp  *	@boundary: set this non-zero if the referred-to block is likely to be
275ac27a0ecSDave Kleikamp  *	       followed (on disk) by an indirect block.
276ac27a0ecSDave Kleikamp  *
277617ba13bSMingming Cao  *	To store the locations of file's data ext4 uses a data structure common
278ac27a0ecSDave Kleikamp  *	for UNIX filesystems - tree of pointers anchored in the inode, with
279ac27a0ecSDave Kleikamp  *	data blocks at leaves and indirect blocks in intermediate nodes.
280ac27a0ecSDave Kleikamp  *	This function translates the block number into path in that tree -
281ac27a0ecSDave Kleikamp  *	return value is the path length and @offsets[n] is the offset of
282ac27a0ecSDave Kleikamp  *	pointer to (n+1)th node in the nth one. If @block is out of range
283ac27a0ecSDave Kleikamp  *	(negative or too large) warning is printed and zero returned.
284ac27a0ecSDave Kleikamp  *
285ac27a0ecSDave Kleikamp  *	Note: function doesn't find node addresses, so no IO is needed. All
286ac27a0ecSDave Kleikamp  *	we need to know is the capacity of indirect blocks (taken from the
287ac27a0ecSDave Kleikamp  *	inode->i_sb).
288ac27a0ecSDave Kleikamp  */
289ac27a0ecSDave Kleikamp 
290ac27a0ecSDave Kleikamp /*
291ac27a0ecSDave Kleikamp  * Portability note: the last comparison (check that we fit into triple
292ac27a0ecSDave Kleikamp  * indirect block) is spelled differently, because otherwise on an
293ac27a0ecSDave Kleikamp  * architecture with 32-bit longs and 8Kb pages we might get into trouble
294ac27a0ecSDave Kleikamp  * if our filesystem had 8Kb blocks. We might use long long, but that would
295ac27a0ecSDave Kleikamp  * kill us on x86. Oh, well, at least the sign propagation does not matter -
296ac27a0ecSDave Kleikamp  * i_block would have to be negative in the very beginning, so we would not
297ac27a0ecSDave Kleikamp  * get there at all.
298ac27a0ecSDave Kleikamp  */
299ac27a0ecSDave Kleikamp 
300617ba13bSMingming Cao static int ext4_block_to_path(struct inode *inode,
301725d26d3SAneesh Kumar K.V 			      ext4_lblk_t i_block,
302725d26d3SAneesh Kumar K.V 			      ext4_lblk_t offsets[4], int *boundary)
303ac27a0ecSDave Kleikamp {
304617ba13bSMingming Cao 	int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
305617ba13bSMingming Cao 	int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
306617ba13bSMingming Cao 	const long direct_blocks = EXT4_NDIR_BLOCKS,
307ac27a0ecSDave Kleikamp 		indirect_blocks = ptrs,
308ac27a0ecSDave Kleikamp 		double_blocks = (1 << (ptrs_bits * 2));
309ac27a0ecSDave Kleikamp 	int n = 0;
310ac27a0ecSDave Kleikamp 	int final = 0;
311ac27a0ecSDave Kleikamp 
312c333e073SRoel Kluin 	if (i_block < direct_blocks) {
313ac27a0ecSDave Kleikamp 		offsets[n++] = i_block;
314ac27a0ecSDave Kleikamp 		final = direct_blocks;
315ac27a0ecSDave Kleikamp 	} else if ((i_block -= direct_blocks) < indirect_blocks) {
316617ba13bSMingming Cao 		offsets[n++] = EXT4_IND_BLOCK;
317ac27a0ecSDave Kleikamp 		offsets[n++] = i_block;
318ac27a0ecSDave Kleikamp 		final = ptrs;
319ac27a0ecSDave Kleikamp 	} else if ((i_block -= indirect_blocks) < double_blocks) {
320617ba13bSMingming Cao 		offsets[n++] = EXT4_DIND_BLOCK;
321ac27a0ecSDave Kleikamp 		offsets[n++] = i_block >> ptrs_bits;
322ac27a0ecSDave Kleikamp 		offsets[n++] = i_block & (ptrs - 1);
323ac27a0ecSDave Kleikamp 		final = ptrs;
324ac27a0ecSDave Kleikamp 	} else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
325617ba13bSMingming Cao 		offsets[n++] = EXT4_TIND_BLOCK;
326ac27a0ecSDave Kleikamp 		offsets[n++] = i_block >> (ptrs_bits * 2);
327ac27a0ecSDave Kleikamp 		offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
328ac27a0ecSDave Kleikamp 		offsets[n++] = i_block & (ptrs - 1);
329ac27a0ecSDave Kleikamp 		final = ptrs;
330ac27a0ecSDave Kleikamp 	} else {
33112062dddSEric Sandeen 		ext4_warning(inode->i_sb, "block %lu > max in inode %lu",
332e2b46574SEric Sandeen 			     i_block + direct_blocks +
33306a279d6STheodore Ts'o 			     indirect_blocks + double_blocks, inode->i_ino);
334ac27a0ecSDave Kleikamp 	}
335ac27a0ecSDave Kleikamp 	if (boundary)
336ac27a0ecSDave Kleikamp 		*boundary = final - 1 - (i_block & (ptrs - 1));
337ac27a0ecSDave Kleikamp 	return n;
338ac27a0ecSDave Kleikamp }
339ac27a0ecSDave Kleikamp 
340*c398eda0STheodore Ts'o static int __ext4_check_blockref(const char *function, unsigned int line,
341*c398eda0STheodore Ts'o 				 struct inode *inode,
3426fd058f7STheodore Ts'o 				 __le32 *p, unsigned int max)
3436fd058f7STheodore Ts'o {
344f73953c0SThiemo Nagel 	__le32 *bref = p;
3456fd058f7STheodore Ts'o 	unsigned int blk;
3466fd058f7STheodore Ts'o 
347fe2c8191SThiemo Nagel 	while (bref < p+max) {
3486fd058f7STheodore Ts'o 		blk = le32_to_cpu(*bref++);
3496fd058f7STheodore Ts'o 		if (blk &&
3506fd058f7STheodore Ts'o 		    unlikely(!ext4_data_block_valid(EXT4_SB(inode->i_sb),
3516fd058f7STheodore Ts'o 						    blk, 1))) {
352*c398eda0STheodore Ts'o 			ext4_error_inode(inode, function, line, blk,
353*c398eda0STheodore Ts'o 					 "invalid block");
354fe2c8191SThiemo Nagel 			return -EIO;
355fe2c8191SThiemo Nagel 		}
356fe2c8191SThiemo Nagel 	}
357fe2c8191SThiemo Nagel 	return 0;
358fe2c8191SThiemo Nagel }
359fe2c8191SThiemo Nagel 
360fe2c8191SThiemo Nagel 
361fe2c8191SThiemo Nagel #define ext4_check_indirect_blockref(inode, bh)                         \
362*c398eda0STheodore Ts'o 	__ext4_check_blockref(__func__, __LINE__, inode,		\
363*c398eda0STheodore Ts'o 			      (__le32 *)(bh)->b_data,			\
364fe2c8191SThiemo Nagel 			      EXT4_ADDR_PER_BLOCK((inode)->i_sb))
365fe2c8191SThiemo Nagel 
366fe2c8191SThiemo Nagel #define ext4_check_inode_blockref(inode)                                \
367*c398eda0STheodore Ts'o 	__ext4_check_blockref(__func__, __LINE__, inode,		\
368*c398eda0STheodore Ts'o 			      EXT4_I(inode)->i_data,			\
369fe2c8191SThiemo Nagel 			      EXT4_NDIR_BLOCKS)
370fe2c8191SThiemo Nagel 
371ac27a0ecSDave Kleikamp /**
372617ba13bSMingming Cao  *	ext4_get_branch - read the chain of indirect blocks leading to data
373ac27a0ecSDave Kleikamp  *	@inode: inode in question
374ac27a0ecSDave Kleikamp  *	@depth: depth of the chain (1 - direct pointer, etc.)
375ac27a0ecSDave Kleikamp  *	@offsets: offsets of pointers in inode/indirect blocks
376ac27a0ecSDave Kleikamp  *	@chain: place to store the result
377ac27a0ecSDave Kleikamp  *	@err: here we store the error value
378ac27a0ecSDave Kleikamp  *
379ac27a0ecSDave Kleikamp  *	Function fills the array of triples <key, p, bh> and returns %NULL
380ac27a0ecSDave Kleikamp  *	if everything went OK or the pointer to the last filled triple
381ac27a0ecSDave Kleikamp  *	(incomplete one) otherwise. Upon the return chain[i].key contains
382ac27a0ecSDave Kleikamp  *	the number of (i+1)-th block in the chain (as it is stored in memory,
383ac27a0ecSDave Kleikamp  *	i.e. little-endian 32-bit), chain[i].p contains the address of that
384ac27a0ecSDave Kleikamp  *	number (it points into struct inode for i==0 and into the bh->b_data
385ac27a0ecSDave Kleikamp  *	for i>0) and chain[i].bh points to the buffer_head of i-th indirect
386ac27a0ecSDave Kleikamp  *	block for i>0 and NULL for i==0. In other words, it holds the block
387ac27a0ecSDave Kleikamp  *	numbers of the chain, addresses they were taken from (and where we can
388ac27a0ecSDave Kleikamp  *	verify that chain did not change) and buffer_heads hosting these
389ac27a0ecSDave Kleikamp  *	numbers.
390ac27a0ecSDave Kleikamp  *
391ac27a0ecSDave Kleikamp  *	Function stops when it stumbles upon zero pointer (absent block)
392ac27a0ecSDave Kleikamp  *		(pointer to last triple returned, *@err == 0)
393ac27a0ecSDave Kleikamp  *	or when it gets an IO error reading an indirect block
394ac27a0ecSDave Kleikamp  *		(ditto, *@err == -EIO)
395ac27a0ecSDave Kleikamp  *	or when it reads all @depth-1 indirect blocks successfully and finds
396ac27a0ecSDave Kleikamp  *	the whole chain, all way to the data (returns %NULL, *err == 0).
397c278bfecSAneesh Kumar K.V  *
398c278bfecSAneesh Kumar K.V  *      Need to be called with
3990e855ac8SAneesh Kumar K.V  *      down_read(&EXT4_I(inode)->i_data_sem)
400ac27a0ecSDave Kleikamp  */
401725d26d3SAneesh Kumar K.V static Indirect *ext4_get_branch(struct inode *inode, int depth,
402725d26d3SAneesh Kumar K.V 				 ext4_lblk_t  *offsets,
403ac27a0ecSDave Kleikamp 				 Indirect chain[4], int *err)
404ac27a0ecSDave Kleikamp {
405ac27a0ecSDave Kleikamp 	struct super_block *sb = inode->i_sb;
406ac27a0ecSDave Kleikamp 	Indirect *p = chain;
407ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
408ac27a0ecSDave Kleikamp 
409ac27a0ecSDave Kleikamp 	*err = 0;
410ac27a0ecSDave Kleikamp 	/* i_data is not going away, no lock needed */
411617ba13bSMingming Cao 	add_chain(chain, NULL, EXT4_I(inode)->i_data + *offsets);
412ac27a0ecSDave Kleikamp 	if (!p->key)
413ac27a0ecSDave Kleikamp 		goto no_block;
414ac27a0ecSDave Kleikamp 	while (--depth) {
415fe2c8191SThiemo Nagel 		bh = sb_getblk(sb, le32_to_cpu(p->key));
416fe2c8191SThiemo Nagel 		if (unlikely(!bh))
417ac27a0ecSDave Kleikamp 			goto failure;
418fe2c8191SThiemo Nagel 
419fe2c8191SThiemo Nagel 		if (!bh_uptodate_or_lock(bh)) {
420fe2c8191SThiemo Nagel 			if (bh_submit_read(bh) < 0) {
421fe2c8191SThiemo Nagel 				put_bh(bh);
422fe2c8191SThiemo Nagel 				goto failure;
423fe2c8191SThiemo Nagel 			}
424fe2c8191SThiemo Nagel 			/* validate block references */
425fe2c8191SThiemo Nagel 			if (ext4_check_indirect_blockref(inode, bh)) {
426fe2c8191SThiemo Nagel 				put_bh(bh);
427fe2c8191SThiemo Nagel 				goto failure;
428fe2c8191SThiemo Nagel 			}
429fe2c8191SThiemo Nagel 		}
430fe2c8191SThiemo Nagel 
431ac27a0ecSDave Kleikamp 		add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
432ac27a0ecSDave Kleikamp 		/* Reader: end */
433ac27a0ecSDave Kleikamp 		if (!p->key)
434ac27a0ecSDave Kleikamp 			goto no_block;
435ac27a0ecSDave Kleikamp 	}
436ac27a0ecSDave Kleikamp 	return NULL;
437ac27a0ecSDave Kleikamp 
438ac27a0ecSDave Kleikamp failure:
439ac27a0ecSDave Kleikamp 	*err = -EIO;
440ac27a0ecSDave Kleikamp no_block:
441ac27a0ecSDave Kleikamp 	return p;
442ac27a0ecSDave Kleikamp }
443ac27a0ecSDave Kleikamp 
444ac27a0ecSDave Kleikamp /**
445617ba13bSMingming Cao  *	ext4_find_near - find a place for allocation with sufficient locality
446ac27a0ecSDave Kleikamp  *	@inode: owner
447ac27a0ecSDave Kleikamp  *	@ind: descriptor of indirect block.
448ac27a0ecSDave Kleikamp  *
4491cc8dcf5SBenoit Boissinot  *	This function returns the preferred place for block allocation.
450ac27a0ecSDave Kleikamp  *	It is used when heuristic for sequential allocation fails.
451ac27a0ecSDave Kleikamp  *	Rules are:
452ac27a0ecSDave Kleikamp  *	  + if there is a block to the left of our position - allocate near it.
453ac27a0ecSDave Kleikamp  *	  + if pointer will live in indirect block - allocate near that block.
454ac27a0ecSDave Kleikamp  *	  + if pointer will live in inode - allocate in the same
455ac27a0ecSDave Kleikamp  *	    cylinder group.
456ac27a0ecSDave Kleikamp  *
457ac27a0ecSDave Kleikamp  * In the latter case we colour the starting block by the callers PID to
458ac27a0ecSDave Kleikamp  * prevent it from clashing with concurrent allocations for a different inode
459ac27a0ecSDave Kleikamp  * in the same block group.   The PID is used here so that functionally related
460ac27a0ecSDave Kleikamp  * files will be close-by on-disk.
461ac27a0ecSDave Kleikamp  *
462ac27a0ecSDave Kleikamp  *	Caller must make sure that @ind is valid and will stay that way.
463ac27a0ecSDave Kleikamp  */
464617ba13bSMingming Cao static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
465ac27a0ecSDave Kleikamp {
466617ba13bSMingming Cao 	struct ext4_inode_info *ei = EXT4_I(inode);
467ac27a0ecSDave Kleikamp 	__le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
468ac27a0ecSDave Kleikamp 	__le32 *p;
469617ba13bSMingming Cao 	ext4_fsblk_t bg_start;
47074d3487fSValerie Clement 	ext4_fsblk_t last_block;
471617ba13bSMingming Cao 	ext4_grpblk_t colour;
472a4912123STheodore Ts'o 	ext4_group_t block_group;
473a4912123STheodore Ts'o 	int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
474ac27a0ecSDave Kleikamp 
475ac27a0ecSDave Kleikamp 	/* Try to find previous block */
476ac27a0ecSDave Kleikamp 	for (p = ind->p - 1; p >= start; p--) {
477ac27a0ecSDave Kleikamp 		if (*p)
478ac27a0ecSDave Kleikamp 			return le32_to_cpu(*p);
479ac27a0ecSDave Kleikamp 	}
480ac27a0ecSDave Kleikamp 
481ac27a0ecSDave Kleikamp 	/* No such thing, so let's try location of indirect block */
482ac27a0ecSDave Kleikamp 	if (ind->bh)
483ac27a0ecSDave Kleikamp 		return ind->bh->b_blocknr;
484ac27a0ecSDave Kleikamp 
485ac27a0ecSDave Kleikamp 	/*
486ac27a0ecSDave Kleikamp 	 * It is going to be referred to from the inode itself? OK, just put it
487ac27a0ecSDave Kleikamp 	 * into the same cylinder group then.
488ac27a0ecSDave Kleikamp 	 */
489a4912123STheodore Ts'o 	block_group = ei->i_block_group;
490a4912123STheodore Ts'o 	if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
491a4912123STheodore Ts'o 		block_group &= ~(flex_size-1);
492a4912123STheodore Ts'o 		if (S_ISREG(inode->i_mode))
493a4912123STheodore Ts'o 			block_group++;
494a4912123STheodore Ts'o 	}
495a4912123STheodore Ts'o 	bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
49674d3487fSValerie Clement 	last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
49774d3487fSValerie Clement 
498a4912123STheodore Ts'o 	/*
499a4912123STheodore Ts'o 	 * If we are doing delayed allocation, we don't need take
500a4912123STheodore Ts'o 	 * colour into account.
501a4912123STheodore Ts'o 	 */
502a4912123STheodore Ts'o 	if (test_opt(inode->i_sb, DELALLOC))
503a4912123STheodore Ts'o 		return bg_start;
504a4912123STheodore Ts'o 
50574d3487fSValerie Clement 	if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
506ac27a0ecSDave Kleikamp 		colour = (current->pid % 16) *
507617ba13bSMingming Cao 			(EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
50874d3487fSValerie Clement 	else
50974d3487fSValerie Clement 		colour = (current->pid % 16) * ((last_block - bg_start) / 16);
510ac27a0ecSDave Kleikamp 	return bg_start + colour;
511ac27a0ecSDave Kleikamp }
512ac27a0ecSDave Kleikamp 
513ac27a0ecSDave Kleikamp /**
5141cc8dcf5SBenoit Boissinot  *	ext4_find_goal - find a preferred place for allocation.
515ac27a0ecSDave Kleikamp  *	@inode: owner
516ac27a0ecSDave Kleikamp  *	@block:  block we want
517ac27a0ecSDave Kleikamp  *	@partial: pointer to the last triple within a chain
518ac27a0ecSDave Kleikamp  *
5191cc8dcf5SBenoit Boissinot  *	Normally this function find the preferred place for block allocation,
520fb01bfdaSAkinobu Mita  *	returns it.
521fb0a387dSEric Sandeen  *	Because this is only used for non-extent files, we limit the block nr
522fb0a387dSEric Sandeen  *	to 32 bits.
523ac27a0ecSDave Kleikamp  */
524725d26d3SAneesh Kumar K.V static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
525fb01bfdaSAkinobu Mita 				   Indirect *partial)
526ac27a0ecSDave Kleikamp {
527fb0a387dSEric Sandeen 	ext4_fsblk_t goal;
528fb0a387dSEric Sandeen 
529ac27a0ecSDave Kleikamp 	/*
530c2ea3fdeSTheodore Ts'o 	 * XXX need to get goal block from mballoc's data structures
531ac27a0ecSDave Kleikamp 	 */
532ac27a0ecSDave Kleikamp 
533fb0a387dSEric Sandeen 	goal = ext4_find_near(inode, partial);
534fb0a387dSEric Sandeen 	goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
535fb0a387dSEric Sandeen 	return goal;
536ac27a0ecSDave Kleikamp }
537ac27a0ecSDave Kleikamp 
538ac27a0ecSDave Kleikamp /**
539617ba13bSMingming Cao  *	ext4_blks_to_allocate: Look up the block map and count the number
540ac27a0ecSDave Kleikamp  *	of direct blocks need to be allocated for the given branch.
541ac27a0ecSDave Kleikamp  *
542ac27a0ecSDave Kleikamp  *	@branch: chain of indirect blocks
543ac27a0ecSDave Kleikamp  *	@k: number of blocks need for indirect blocks
544ac27a0ecSDave Kleikamp  *	@blks: number of data blocks to be mapped.
545ac27a0ecSDave Kleikamp  *	@blocks_to_boundary:  the offset in the indirect block
546ac27a0ecSDave Kleikamp  *
547ac27a0ecSDave Kleikamp  *	return the total number of blocks to be allocate, including the
548ac27a0ecSDave Kleikamp  *	direct and indirect blocks.
549ac27a0ecSDave Kleikamp  */
550498e5f24STheodore Ts'o static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
551ac27a0ecSDave Kleikamp 				 int blocks_to_boundary)
552ac27a0ecSDave Kleikamp {
553498e5f24STheodore Ts'o 	unsigned int count = 0;
554ac27a0ecSDave Kleikamp 
555ac27a0ecSDave Kleikamp 	/*
556ac27a0ecSDave Kleikamp 	 * Simple case, [t,d]Indirect block(s) has not allocated yet
557ac27a0ecSDave Kleikamp 	 * then it's clear blocks on that path have not allocated
558ac27a0ecSDave Kleikamp 	 */
559ac27a0ecSDave Kleikamp 	if (k > 0) {
560ac27a0ecSDave Kleikamp 		/* right now we don't handle cross boundary allocation */
561ac27a0ecSDave Kleikamp 		if (blks < blocks_to_boundary + 1)
562ac27a0ecSDave Kleikamp 			count += blks;
563ac27a0ecSDave Kleikamp 		else
564ac27a0ecSDave Kleikamp 			count += blocks_to_boundary + 1;
565ac27a0ecSDave Kleikamp 		return count;
566ac27a0ecSDave Kleikamp 	}
567ac27a0ecSDave Kleikamp 
568ac27a0ecSDave Kleikamp 	count++;
569ac27a0ecSDave Kleikamp 	while (count < blks && count <= blocks_to_boundary &&
570ac27a0ecSDave Kleikamp 		le32_to_cpu(*(branch[0].p + count)) == 0) {
571ac27a0ecSDave Kleikamp 		count++;
572ac27a0ecSDave Kleikamp 	}
573ac27a0ecSDave Kleikamp 	return count;
574ac27a0ecSDave Kleikamp }
575ac27a0ecSDave Kleikamp 
576ac27a0ecSDave Kleikamp /**
577617ba13bSMingming Cao  *	ext4_alloc_blocks: multiple allocate blocks needed for a branch
578ac27a0ecSDave Kleikamp  *	@indirect_blks: the number of blocks need to allocate for indirect
579ac27a0ecSDave Kleikamp  *			blocks
580ac27a0ecSDave Kleikamp  *
581ac27a0ecSDave Kleikamp  *	@new_blocks: on return it will store the new block numbers for
582ac27a0ecSDave Kleikamp  *	the indirect blocks(if needed) and the first direct block,
583ac27a0ecSDave Kleikamp  *	@blks:	on return it will store the total number of allocated
584ac27a0ecSDave Kleikamp  *		direct blocks
585ac27a0ecSDave Kleikamp  */
586617ba13bSMingming Cao static int ext4_alloc_blocks(handle_t *handle, struct inode *inode,
5877061eba7SAneesh Kumar K.V 			     ext4_lblk_t iblock, ext4_fsblk_t goal,
5887061eba7SAneesh Kumar K.V 			     int indirect_blks, int blks,
589617ba13bSMingming Cao 			     ext4_fsblk_t new_blocks[4], int *err)
590ac27a0ecSDave Kleikamp {
591815a1130STheodore Ts'o 	struct ext4_allocation_request ar;
592ac27a0ecSDave Kleikamp 	int target, i;
5937061eba7SAneesh Kumar K.V 	unsigned long count = 0, blk_allocated = 0;
594ac27a0ecSDave Kleikamp 	int index = 0;
595617ba13bSMingming Cao 	ext4_fsblk_t current_block = 0;
596ac27a0ecSDave Kleikamp 	int ret = 0;
597ac27a0ecSDave Kleikamp 
598ac27a0ecSDave Kleikamp 	/*
599ac27a0ecSDave Kleikamp 	 * Here we try to allocate the requested multiple blocks at once,
600ac27a0ecSDave Kleikamp 	 * on a best-effort basis.
601ac27a0ecSDave Kleikamp 	 * To build a branch, we should allocate blocks for
602ac27a0ecSDave Kleikamp 	 * the indirect blocks(if not allocated yet), and at least
603ac27a0ecSDave Kleikamp 	 * the first direct block of this branch.  That's the
604ac27a0ecSDave Kleikamp 	 * minimum number of blocks need to allocate(required)
605ac27a0ecSDave Kleikamp 	 */
6067061eba7SAneesh Kumar K.V 	/* first we try to allocate the indirect blocks */
6077061eba7SAneesh Kumar K.V 	target = indirect_blks;
6087061eba7SAneesh Kumar K.V 	while (target > 0) {
609ac27a0ecSDave Kleikamp 		count = target;
610ac27a0ecSDave Kleikamp 		/* allocating blocks for indirect blocks and direct blocks */
6117061eba7SAneesh Kumar K.V 		current_block = ext4_new_meta_blocks(handle, inode,
6127061eba7SAneesh Kumar K.V 							goal, &count, err);
613ac27a0ecSDave Kleikamp 		if (*err)
614ac27a0ecSDave Kleikamp 			goto failed_out;
615ac27a0ecSDave Kleikamp 
616273df556SFrank Mayhar 		if (unlikely(current_block + count > EXT4_MAX_BLOCK_FILE_PHYS)) {
617273df556SFrank Mayhar 			EXT4_ERROR_INODE(inode,
618273df556SFrank Mayhar 					 "current_block %llu + count %lu > %d!",
619273df556SFrank Mayhar 					 current_block, count,
620273df556SFrank Mayhar 					 EXT4_MAX_BLOCK_FILE_PHYS);
621273df556SFrank Mayhar 			*err = -EIO;
622273df556SFrank Mayhar 			goto failed_out;
623273df556SFrank Mayhar 		}
624fb0a387dSEric Sandeen 
625ac27a0ecSDave Kleikamp 		target -= count;
626ac27a0ecSDave Kleikamp 		/* allocate blocks for indirect blocks */
627ac27a0ecSDave Kleikamp 		while (index < indirect_blks && count) {
628ac27a0ecSDave Kleikamp 			new_blocks[index++] = current_block++;
629ac27a0ecSDave Kleikamp 			count--;
630ac27a0ecSDave Kleikamp 		}
6317061eba7SAneesh Kumar K.V 		if (count > 0) {
6327061eba7SAneesh Kumar K.V 			/*
6337061eba7SAneesh Kumar K.V 			 * save the new block number
6347061eba7SAneesh Kumar K.V 			 * for the first direct block
6357061eba7SAneesh Kumar K.V 			 */
6367061eba7SAneesh Kumar K.V 			new_blocks[index] = current_block;
6377061eba7SAneesh Kumar K.V 			printk(KERN_INFO "%s returned more blocks than "
6387061eba7SAneesh Kumar K.V 						"requested\n", __func__);
6397061eba7SAneesh Kumar K.V 			WARN_ON(1);
640ac27a0ecSDave Kleikamp 			break;
641ac27a0ecSDave Kleikamp 		}
6427061eba7SAneesh Kumar K.V 	}
643ac27a0ecSDave Kleikamp 
6447061eba7SAneesh Kumar K.V 	target = blks - count ;
6457061eba7SAneesh Kumar K.V 	blk_allocated = count;
6467061eba7SAneesh Kumar K.V 	if (!target)
6477061eba7SAneesh Kumar K.V 		goto allocated;
6487061eba7SAneesh Kumar K.V 	/* Now allocate data blocks */
649815a1130STheodore Ts'o 	memset(&ar, 0, sizeof(ar));
650815a1130STheodore Ts'o 	ar.inode = inode;
651815a1130STheodore Ts'o 	ar.goal = goal;
652815a1130STheodore Ts'o 	ar.len = target;
653815a1130STheodore Ts'o 	ar.logical = iblock;
654815a1130STheodore Ts'o 	if (S_ISREG(inode->i_mode))
655815a1130STheodore Ts'o 		/* enable in-core preallocation only for regular files */
656815a1130STheodore Ts'o 		ar.flags = EXT4_MB_HINT_DATA;
657815a1130STheodore Ts'o 
658815a1130STheodore Ts'o 	current_block = ext4_mb_new_blocks(handle, &ar, err);
659273df556SFrank Mayhar 	if (unlikely(current_block + ar.len > EXT4_MAX_BLOCK_FILE_PHYS)) {
660273df556SFrank Mayhar 		EXT4_ERROR_INODE(inode,
661273df556SFrank Mayhar 				 "current_block %llu + ar.len %d > %d!",
662273df556SFrank Mayhar 				 current_block, ar.len,
663273df556SFrank Mayhar 				 EXT4_MAX_BLOCK_FILE_PHYS);
664273df556SFrank Mayhar 		*err = -EIO;
665273df556SFrank Mayhar 		goto failed_out;
666273df556SFrank Mayhar 	}
667815a1130STheodore Ts'o 
6687061eba7SAneesh Kumar K.V 	if (*err && (target == blks)) {
6697061eba7SAneesh Kumar K.V 		/*
6707061eba7SAneesh Kumar K.V 		 * if the allocation failed and we didn't allocate
6717061eba7SAneesh Kumar K.V 		 * any blocks before
6727061eba7SAneesh Kumar K.V 		 */
6737061eba7SAneesh Kumar K.V 		goto failed_out;
6747061eba7SAneesh Kumar K.V 	}
6757061eba7SAneesh Kumar K.V 	if (!*err) {
6767061eba7SAneesh Kumar K.V 		if (target == blks) {
6777061eba7SAneesh Kumar K.V 			/*
6787061eba7SAneesh Kumar K.V 			 * save the new block number
6797061eba7SAneesh Kumar K.V 			 * for the first direct block
6807061eba7SAneesh Kumar K.V 			 */
681ac27a0ecSDave Kleikamp 			new_blocks[index] = current_block;
6827061eba7SAneesh Kumar K.V 		}
683815a1130STheodore Ts'o 		blk_allocated += ar.len;
6847061eba7SAneesh Kumar K.V 	}
6857061eba7SAneesh Kumar K.V allocated:
686ac27a0ecSDave Kleikamp 	/* total number of blocks allocated for direct blocks */
6877061eba7SAneesh Kumar K.V 	ret = blk_allocated;
688ac27a0ecSDave Kleikamp 	*err = 0;
689ac27a0ecSDave Kleikamp 	return ret;
690ac27a0ecSDave Kleikamp failed_out:
691ac27a0ecSDave Kleikamp 	for (i = 0; i < index; i++)
692e6362609STheodore Ts'o 		ext4_free_blocks(handle, inode, 0, new_blocks[i], 1, 0);
693ac27a0ecSDave Kleikamp 	return ret;
694ac27a0ecSDave Kleikamp }
695ac27a0ecSDave Kleikamp 
696ac27a0ecSDave Kleikamp /**
697617ba13bSMingming Cao  *	ext4_alloc_branch - allocate and set up a chain of blocks.
698ac27a0ecSDave Kleikamp  *	@inode: owner
699ac27a0ecSDave Kleikamp  *	@indirect_blks: number of allocated indirect blocks
700ac27a0ecSDave Kleikamp  *	@blks: number of allocated direct blocks
701ac27a0ecSDave Kleikamp  *	@offsets: offsets (in the blocks) to store the pointers to next.
702ac27a0ecSDave Kleikamp  *	@branch: place to store the chain in.
703ac27a0ecSDave Kleikamp  *
704ac27a0ecSDave Kleikamp  *	This function allocates blocks, zeroes out all but the last one,
705ac27a0ecSDave Kleikamp  *	links them into chain and (if we are synchronous) writes them to disk.
706ac27a0ecSDave Kleikamp  *	In other words, it prepares a branch that can be spliced onto the
707ac27a0ecSDave Kleikamp  *	inode. It stores the information about that chain in the branch[], in
708617ba13bSMingming Cao  *	the same format as ext4_get_branch() would do. We are calling it after
709ac27a0ecSDave Kleikamp  *	we had read the existing part of chain and partial points to the last
710ac27a0ecSDave Kleikamp  *	triple of that (one with zero ->key). Upon the exit we have the same
711617ba13bSMingming Cao  *	picture as after the successful ext4_get_block(), except that in one
712ac27a0ecSDave Kleikamp  *	place chain is disconnected - *branch->p is still zero (we did not
713ac27a0ecSDave Kleikamp  *	set the last link), but branch->key contains the number that should
714ac27a0ecSDave Kleikamp  *	be placed into *branch->p to fill that gap.
715ac27a0ecSDave Kleikamp  *
716ac27a0ecSDave Kleikamp  *	If allocation fails we free all blocks we've allocated (and forget
717ac27a0ecSDave Kleikamp  *	their buffer_heads) and return the error value the from failed
718617ba13bSMingming Cao  *	ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
719ac27a0ecSDave Kleikamp  *	as described above and return 0.
720ac27a0ecSDave Kleikamp  */
721617ba13bSMingming Cao static int ext4_alloc_branch(handle_t *handle, struct inode *inode,
7227061eba7SAneesh Kumar K.V 			     ext4_lblk_t iblock, int indirect_blks,
7237061eba7SAneesh Kumar K.V 			     int *blks, ext4_fsblk_t goal,
724725d26d3SAneesh Kumar K.V 			     ext4_lblk_t *offsets, Indirect *branch)
725ac27a0ecSDave Kleikamp {
726ac27a0ecSDave Kleikamp 	int blocksize = inode->i_sb->s_blocksize;
727ac27a0ecSDave Kleikamp 	int i, n = 0;
728ac27a0ecSDave Kleikamp 	int err = 0;
729ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
730ac27a0ecSDave Kleikamp 	int num;
731617ba13bSMingming Cao 	ext4_fsblk_t new_blocks[4];
732617ba13bSMingming Cao 	ext4_fsblk_t current_block;
733ac27a0ecSDave Kleikamp 
7347061eba7SAneesh Kumar K.V 	num = ext4_alloc_blocks(handle, inode, iblock, goal, indirect_blks,
735ac27a0ecSDave Kleikamp 				*blks, new_blocks, &err);
736ac27a0ecSDave Kleikamp 	if (err)
737ac27a0ecSDave Kleikamp 		return err;
738ac27a0ecSDave Kleikamp 
739ac27a0ecSDave Kleikamp 	branch[0].key = cpu_to_le32(new_blocks[0]);
740ac27a0ecSDave Kleikamp 	/*
741ac27a0ecSDave Kleikamp 	 * metadata blocks and data blocks are allocated.
742ac27a0ecSDave Kleikamp 	 */
743ac27a0ecSDave Kleikamp 	for (n = 1; n <= indirect_blks;  n++) {
744ac27a0ecSDave Kleikamp 		/*
745ac27a0ecSDave Kleikamp 		 * Get buffer_head for parent block, zero it out
746ac27a0ecSDave Kleikamp 		 * and set the pointer to new one, then send
747ac27a0ecSDave Kleikamp 		 * parent to disk.
748ac27a0ecSDave Kleikamp 		 */
749ac27a0ecSDave Kleikamp 		bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
750ac27a0ecSDave Kleikamp 		branch[n].bh = bh;
751ac27a0ecSDave Kleikamp 		lock_buffer(bh);
752ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
753617ba13bSMingming Cao 		err = ext4_journal_get_create_access(handle, bh);
754ac27a0ecSDave Kleikamp 		if (err) {
7556487a9d3SCurt Wohlgemuth 			/* Don't brelse(bh) here; it's done in
7566487a9d3SCurt Wohlgemuth 			 * ext4_journal_forget() below */
757ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
758ac27a0ecSDave Kleikamp 			goto failed;
759ac27a0ecSDave Kleikamp 		}
760ac27a0ecSDave Kleikamp 
761ac27a0ecSDave Kleikamp 		memset(bh->b_data, 0, blocksize);
762ac27a0ecSDave Kleikamp 		branch[n].p = (__le32 *) bh->b_data + offsets[n];
763ac27a0ecSDave Kleikamp 		branch[n].key = cpu_to_le32(new_blocks[n]);
764ac27a0ecSDave Kleikamp 		*branch[n].p = branch[n].key;
765ac27a0ecSDave Kleikamp 		if (n == indirect_blks) {
766ac27a0ecSDave Kleikamp 			current_block = new_blocks[n];
767ac27a0ecSDave Kleikamp 			/*
768ac27a0ecSDave Kleikamp 			 * End of chain, update the last new metablock of
769ac27a0ecSDave Kleikamp 			 * the chain to point to the new allocated
770ac27a0ecSDave Kleikamp 			 * data blocks numbers
771ac27a0ecSDave Kleikamp 			 */
772ac27a0ecSDave Kleikamp 			for (i = 1; i < num; i++)
773ac27a0ecSDave Kleikamp 				*(branch[n].p + i) = cpu_to_le32(++current_block);
774ac27a0ecSDave Kleikamp 		}
775ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "marking uptodate");
776ac27a0ecSDave Kleikamp 		set_buffer_uptodate(bh);
777ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
778ac27a0ecSDave Kleikamp 
7790390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
7800390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
781ac27a0ecSDave Kleikamp 		if (err)
782ac27a0ecSDave Kleikamp 			goto failed;
783ac27a0ecSDave Kleikamp 	}
784ac27a0ecSDave Kleikamp 	*blks = num;
785ac27a0ecSDave Kleikamp 	return err;
786ac27a0ecSDave Kleikamp failed:
787ac27a0ecSDave Kleikamp 	/* Allocation failed, free what we already allocated */
788e6362609STheodore Ts'o 	ext4_free_blocks(handle, inode, 0, new_blocks[0], 1, 0);
789ac27a0ecSDave Kleikamp 	for (i = 1; i <= n ; i++) {
790b7e57e7cSTheodore Ts'o 		/*
791e6362609STheodore Ts'o 		 * branch[i].bh is newly allocated, so there is no
792e6362609STheodore Ts'o 		 * need to revoke the block, which is why we don't
793e6362609STheodore Ts'o 		 * need to set EXT4_FREE_BLOCKS_METADATA.
794b7e57e7cSTheodore Ts'o 		 */
795e6362609STheodore Ts'o 		ext4_free_blocks(handle, inode, 0, new_blocks[i], 1,
796e6362609STheodore Ts'o 				 EXT4_FREE_BLOCKS_FORGET);
797ac27a0ecSDave Kleikamp 	}
798e6362609STheodore Ts'o 	for (i = n+1; i < indirect_blks; i++)
799e6362609STheodore Ts'o 		ext4_free_blocks(handle, inode, 0, new_blocks[i], 1, 0);
800ac27a0ecSDave Kleikamp 
801e6362609STheodore Ts'o 	ext4_free_blocks(handle, inode, 0, new_blocks[i], num, 0);
802ac27a0ecSDave Kleikamp 
803ac27a0ecSDave Kleikamp 	return err;
804ac27a0ecSDave Kleikamp }
805ac27a0ecSDave Kleikamp 
806ac27a0ecSDave Kleikamp /**
807617ba13bSMingming Cao  * ext4_splice_branch - splice the allocated branch onto inode.
808ac27a0ecSDave Kleikamp  * @inode: owner
809ac27a0ecSDave Kleikamp  * @block: (logical) number of block we are adding
810ac27a0ecSDave Kleikamp  * @chain: chain of indirect blocks (with a missing link - see
811617ba13bSMingming Cao  *	ext4_alloc_branch)
812ac27a0ecSDave Kleikamp  * @where: location of missing link
813ac27a0ecSDave Kleikamp  * @num:   number of indirect blocks we are adding
814ac27a0ecSDave Kleikamp  * @blks:  number of direct blocks we are adding
815ac27a0ecSDave Kleikamp  *
816ac27a0ecSDave Kleikamp  * This function fills the missing link and does all housekeeping needed in
817ac27a0ecSDave Kleikamp  * inode (->i_blocks, etc.). In case of success we end up with the full
818ac27a0ecSDave Kleikamp  * chain to new block and return 0.
819ac27a0ecSDave Kleikamp  */
820617ba13bSMingming Cao static int ext4_splice_branch(handle_t *handle, struct inode *inode,
821de9a55b8STheodore Ts'o 			      ext4_lblk_t block, Indirect *where, int num,
822de9a55b8STheodore Ts'o 			      int blks)
823ac27a0ecSDave Kleikamp {
824ac27a0ecSDave Kleikamp 	int i;
825ac27a0ecSDave Kleikamp 	int err = 0;
826617ba13bSMingming Cao 	ext4_fsblk_t current_block;
827ac27a0ecSDave Kleikamp 
828ac27a0ecSDave Kleikamp 	/*
829ac27a0ecSDave Kleikamp 	 * If we're splicing into a [td]indirect block (as opposed to the
830ac27a0ecSDave Kleikamp 	 * inode) then we need to get write access to the [td]indirect block
831ac27a0ecSDave Kleikamp 	 * before the splice.
832ac27a0ecSDave Kleikamp 	 */
833ac27a0ecSDave Kleikamp 	if (where->bh) {
834ac27a0ecSDave Kleikamp 		BUFFER_TRACE(where->bh, "get_write_access");
835617ba13bSMingming Cao 		err = ext4_journal_get_write_access(handle, where->bh);
836ac27a0ecSDave Kleikamp 		if (err)
837ac27a0ecSDave Kleikamp 			goto err_out;
838ac27a0ecSDave Kleikamp 	}
839ac27a0ecSDave Kleikamp 	/* That's it */
840ac27a0ecSDave Kleikamp 
841ac27a0ecSDave Kleikamp 	*where->p = where->key;
842ac27a0ecSDave Kleikamp 
843ac27a0ecSDave Kleikamp 	/*
844ac27a0ecSDave Kleikamp 	 * Update the host buffer_head or inode to point to more just allocated
845ac27a0ecSDave Kleikamp 	 * direct blocks blocks
846ac27a0ecSDave Kleikamp 	 */
847ac27a0ecSDave Kleikamp 	if (num == 0 && blks > 1) {
848ac27a0ecSDave Kleikamp 		current_block = le32_to_cpu(where->key) + 1;
849ac27a0ecSDave Kleikamp 		for (i = 1; i < blks; i++)
850ac27a0ecSDave Kleikamp 			*(where->p + i) = cpu_to_le32(current_block++);
851ac27a0ecSDave Kleikamp 	}
852ac27a0ecSDave Kleikamp 
853ac27a0ecSDave Kleikamp 	/* We are done with atomic stuff, now do the rest of housekeeping */
854ac27a0ecSDave Kleikamp 	/* had we spliced it onto indirect block? */
855ac27a0ecSDave Kleikamp 	if (where->bh) {
856ac27a0ecSDave Kleikamp 		/*
857ac27a0ecSDave Kleikamp 		 * If we spliced it onto an indirect block, we haven't
858ac27a0ecSDave Kleikamp 		 * altered the inode.  Note however that if it is being spliced
859ac27a0ecSDave Kleikamp 		 * onto an indirect block at the very end of the file (the
860ac27a0ecSDave Kleikamp 		 * file is growing) then we *will* alter the inode to reflect
861ac27a0ecSDave Kleikamp 		 * the new i_size.  But that is not done here - it is done in
862617ba13bSMingming Cao 		 * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
863ac27a0ecSDave Kleikamp 		 */
864ac27a0ecSDave Kleikamp 		jbd_debug(5, "splicing indirect only\n");
8650390131bSFrank Mayhar 		BUFFER_TRACE(where->bh, "call ext4_handle_dirty_metadata");
8660390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, where->bh);
867ac27a0ecSDave Kleikamp 		if (err)
868ac27a0ecSDave Kleikamp 			goto err_out;
869ac27a0ecSDave Kleikamp 	} else {
870ac27a0ecSDave Kleikamp 		/*
871ac27a0ecSDave Kleikamp 		 * OK, we spliced it into the inode itself on a direct block.
872ac27a0ecSDave Kleikamp 		 */
87341591750STheodore Ts'o 		ext4_mark_inode_dirty(handle, inode);
874ac27a0ecSDave Kleikamp 		jbd_debug(5, "splicing direct\n");
875ac27a0ecSDave Kleikamp 	}
876ac27a0ecSDave Kleikamp 	return err;
877ac27a0ecSDave Kleikamp 
878ac27a0ecSDave Kleikamp err_out:
879ac27a0ecSDave Kleikamp 	for (i = 1; i <= num; i++) {
880b7e57e7cSTheodore Ts'o 		/*
881e6362609STheodore Ts'o 		 * branch[i].bh is newly allocated, so there is no
882e6362609STheodore Ts'o 		 * need to revoke the block, which is why we don't
883e6362609STheodore Ts'o 		 * need to set EXT4_FREE_BLOCKS_METADATA.
884b7e57e7cSTheodore Ts'o 		 */
885e6362609STheodore Ts'o 		ext4_free_blocks(handle, inode, where[i].bh, 0, 1,
886e6362609STheodore Ts'o 				 EXT4_FREE_BLOCKS_FORGET);
887ac27a0ecSDave Kleikamp 	}
888e6362609STheodore Ts'o 	ext4_free_blocks(handle, inode, 0, le32_to_cpu(where[num].key),
889e6362609STheodore Ts'o 			 blks, 0);
890ac27a0ecSDave Kleikamp 
891ac27a0ecSDave Kleikamp 	return err;
892ac27a0ecSDave Kleikamp }
893ac27a0ecSDave Kleikamp 
894ac27a0ecSDave Kleikamp /*
895e35fd660STheodore Ts'o  * The ext4_ind_map_blocks() function handles non-extents inodes
896b920c755STheodore Ts'o  * (i.e., using the traditional indirect/double-indirect i_blocks
897e35fd660STheodore Ts'o  * scheme) for ext4_map_blocks().
898b920c755STheodore Ts'o  *
899ac27a0ecSDave Kleikamp  * Allocation strategy is simple: if we have to allocate something, we will
900ac27a0ecSDave Kleikamp  * have to go the whole way to leaf. So let's do it before attaching anything
901ac27a0ecSDave Kleikamp  * to tree, set linkage between the newborn blocks, write them if sync is
902ac27a0ecSDave Kleikamp  * required, recheck the path, free and repeat if check fails, otherwise
903ac27a0ecSDave Kleikamp  * set the last missing link (that will protect us from any truncate-generated
904ac27a0ecSDave Kleikamp  * removals - all blocks on the path are immune now) and possibly force the
905ac27a0ecSDave Kleikamp  * write on the parent block.
906ac27a0ecSDave Kleikamp  * That has a nice additional property: no special recovery from the failed
907ac27a0ecSDave Kleikamp  * allocations is needed - we simply release blocks and do not touch anything
908ac27a0ecSDave Kleikamp  * reachable from inode.
909ac27a0ecSDave Kleikamp  *
910ac27a0ecSDave Kleikamp  * `handle' can be NULL if create == 0.
911ac27a0ecSDave Kleikamp  *
912ac27a0ecSDave Kleikamp  * return > 0, # of blocks mapped or allocated.
913ac27a0ecSDave Kleikamp  * return = 0, if plain lookup failed.
914ac27a0ecSDave Kleikamp  * return < 0, error case.
915c278bfecSAneesh Kumar K.V  *
916b920c755STheodore Ts'o  * The ext4_ind_get_blocks() function should be called with
917b920c755STheodore Ts'o  * down_write(&EXT4_I(inode)->i_data_sem) if allocating filesystem
918b920c755STheodore Ts'o  * blocks (i.e., flags has EXT4_GET_BLOCKS_CREATE set) or
919b920c755STheodore Ts'o  * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system
920b920c755STheodore Ts'o  * blocks.
921ac27a0ecSDave Kleikamp  */
922e35fd660STheodore Ts'o static int ext4_ind_map_blocks(handle_t *handle, struct inode *inode,
923e35fd660STheodore Ts'o 			       struct ext4_map_blocks *map,
924c2177057STheodore Ts'o 			       int flags)
925ac27a0ecSDave Kleikamp {
926ac27a0ecSDave Kleikamp 	int err = -EIO;
927725d26d3SAneesh Kumar K.V 	ext4_lblk_t offsets[4];
928ac27a0ecSDave Kleikamp 	Indirect chain[4];
929ac27a0ecSDave Kleikamp 	Indirect *partial;
930617ba13bSMingming Cao 	ext4_fsblk_t goal;
931ac27a0ecSDave Kleikamp 	int indirect_blks;
932ac27a0ecSDave Kleikamp 	int blocks_to_boundary = 0;
933ac27a0ecSDave Kleikamp 	int depth;
934ac27a0ecSDave Kleikamp 	int count = 0;
935617ba13bSMingming Cao 	ext4_fsblk_t first_block = 0;
936ac27a0ecSDave Kleikamp 
93712e9b892SDmitry Monakhov 	J_ASSERT(!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)));
938c2177057STheodore Ts'o 	J_ASSERT(handle != NULL || (flags & EXT4_GET_BLOCKS_CREATE) == 0);
939e35fd660STheodore Ts'o 	depth = ext4_block_to_path(inode, map->m_lblk, offsets,
940725d26d3SAneesh Kumar K.V 				   &blocks_to_boundary);
941ac27a0ecSDave Kleikamp 
942ac27a0ecSDave Kleikamp 	if (depth == 0)
943ac27a0ecSDave Kleikamp 		goto out;
944ac27a0ecSDave Kleikamp 
945617ba13bSMingming Cao 	partial = ext4_get_branch(inode, depth, offsets, chain, &err);
946ac27a0ecSDave Kleikamp 
947ac27a0ecSDave Kleikamp 	/* Simplest case - block found, no allocation needed */
948ac27a0ecSDave Kleikamp 	if (!partial) {
949ac27a0ecSDave Kleikamp 		first_block = le32_to_cpu(chain[depth - 1].key);
950ac27a0ecSDave Kleikamp 		count++;
951ac27a0ecSDave Kleikamp 		/*map more blocks*/
952e35fd660STheodore Ts'o 		while (count < map->m_len && count <= blocks_to_boundary) {
953617ba13bSMingming Cao 			ext4_fsblk_t blk;
954ac27a0ecSDave Kleikamp 
955ac27a0ecSDave Kleikamp 			blk = le32_to_cpu(*(chain[depth-1].p + count));
956ac27a0ecSDave Kleikamp 
957ac27a0ecSDave Kleikamp 			if (blk == first_block + count)
958ac27a0ecSDave Kleikamp 				count++;
959ac27a0ecSDave Kleikamp 			else
960ac27a0ecSDave Kleikamp 				break;
961ac27a0ecSDave Kleikamp 		}
962ac27a0ecSDave Kleikamp 		goto got_it;
963ac27a0ecSDave Kleikamp 	}
964ac27a0ecSDave Kleikamp 
965ac27a0ecSDave Kleikamp 	/* Next simple case - plain lookup or failed read of indirect block */
966c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0 || err == -EIO)
967ac27a0ecSDave Kleikamp 		goto cleanup;
968ac27a0ecSDave Kleikamp 
969ac27a0ecSDave Kleikamp 	/*
970c2ea3fdeSTheodore Ts'o 	 * Okay, we need to do block allocation.
971ac27a0ecSDave Kleikamp 	*/
972e35fd660STheodore Ts'o 	goal = ext4_find_goal(inode, map->m_lblk, partial);
973ac27a0ecSDave Kleikamp 
974ac27a0ecSDave Kleikamp 	/* the number of blocks need to allocate for [d,t]indirect blocks */
975ac27a0ecSDave Kleikamp 	indirect_blks = (chain + depth) - partial - 1;
976ac27a0ecSDave Kleikamp 
977ac27a0ecSDave Kleikamp 	/*
978ac27a0ecSDave Kleikamp 	 * Next look up the indirect map to count the totoal number of
979ac27a0ecSDave Kleikamp 	 * direct blocks to allocate for this branch.
980ac27a0ecSDave Kleikamp 	 */
981617ba13bSMingming Cao 	count = ext4_blks_to_allocate(partial, indirect_blks,
982e35fd660STheodore Ts'o 				      map->m_len, blocks_to_boundary);
983ac27a0ecSDave Kleikamp 	/*
984617ba13bSMingming Cao 	 * Block out ext4_truncate while we alter the tree
985ac27a0ecSDave Kleikamp 	 */
986e35fd660STheodore Ts'o 	err = ext4_alloc_branch(handle, inode, map->m_lblk, indirect_blks,
9877061eba7SAneesh Kumar K.V 				&count, goal,
988ac27a0ecSDave Kleikamp 				offsets + (partial - chain), partial);
989ac27a0ecSDave Kleikamp 
990ac27a0ecSDave Kleikamp 	/*
991617ba13bSMingming Cao 	 * The ext4_splice_branch call will free and forget any buffers
992ac27a0ecSDave Kleikamp 	 * on the new chain if there is a failure, but that risks using
993ac27a0ecSDave Kleikamp 	 * up transaction credits, especially for bitmaps where the
994ac27a0ecSDave Kleikamp 	 * credits cannot be returned.  Can we handle this somehow?  We
995ac27a0ecSDave Kleikamp 	 * may need to return -EAGAIN upwards in the worst case.  --sct
996ac27a0ecSDave Kleikamp 	 */
997ac27a0ecSDave Kleikamp 	if (!err)
998e35fd660STheodore Ts'o 		err = ext4_splice_branch(handle, inode, map->m_lblk,
999ac27a0ecSDave Kleikamp 					 partial, indirect_blks, count);
10002bba702dSJan Kara 	if (err)
1001ac27a0ecSDave Kleikamp 		goto cleanup;
1002ac27a0ecSDave Kleikamp 
1003e35fd660STheodore Ts'o 	map->m_flags |= EXT4_MAP_NEW;
1004b436b9beSJan Kara 
1005b436b9beSJan Kara 	ext4_update_inode_fsync_trans(handle, inode, 1);
1006ac27a0ecSDave Kleikamp got_it:
1007e35fd660STheodore Ts'o 	map->m_flags |= EXT4_MAP_MAPPED;
1008e35fd660STheodore Ts'o 	map->m_pblk = le32_to_cpu(chain[depth-1].key);
1009e35fd660STheodore Ts'o 	map->m_len = count;
1010ac27a0ecSDave Kleikamp 	if (count > blocks_to_boundary)
1011e35fd660STheodore Ts'o 		map->m_flags |= EXT4_MAP_BOUNDARY;
1012ac27a0ecSDave Kleikamp 	err = count;
1013ac27a0ecSDave Kleikamp 	/* Clean up and exit */
1014ac27a0ecSDave Kleikamp 	partial = chain + depth - 1;	/* the whole chain */
1015ac27a0ecSDave Kleikamp cleanup:
1016ac27a0ecSDave Kleikamp 	while (partial > chain) {
1017ac27a0ecSDave Kleikamp 		BUFFER_TRACE(partial->bh, "call brelse");
1018ac27a0ecSDave Kleikamp 		brelse(partial->bh);
1019ac27a0ecSDave Kleikamp 		partial--;
1020ac27a0ecSDave Kleikamp 	}
1021ac27a0ecSDave Kleikamp out:
1022ac27a0ecSDave Kleikamp 	return err;
1023ac27a0ecSDave Kleikamp }
1024ac27a0ecSDave Kleikamp 
1025a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
1026a9e7f447SDmitry Monakhov qsize_t *ext4_get_reserved_space(struct inode *inode)
102760e58e0fSMingming Cao {
1028a9e7f447SDmitry Monakhov 	return &EXT4_I(inode)->i_reserved_quota;
102960e58e0fSMingming Cao }
1030a9e7f447SDmitry Monakhov #endif
10319d0be502STheodore Ts'o 
103212219aeaSAneesh Kumar K.V /*
103312219aeaSAneesh Kumar K.V  * Calculate the number of metadata blocks need to reserve
10349d0be502STheodore Ts'o  * to allocate a new block at @lblocks for non extent file based file
103512219aeaSAneesh Kumar K.V  */
10369d0be502STheodore Ts'o static int ext4_indirect_calc_metadata_amount(struct inode *inode,
10379d0be502STheodore Ts'o 					      sector_t lblock)
103812219aeaSAneesh Kumar K.V {
10399d0be502STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1040d330a5beSJan Kara 	sector_t dind_mask = ~((sector_t)EXT4_ADDR_PER_BLOCK(inode->i_sb) - 1);
10419d0be502STheodore Ts'o 	int blk_bits;
104212219aeaSAneesh Kumar K.V 
10439d0be502STheodore Ts'o 	if (lblock < EXT4_NDIR_BLOCKS)
10449d0be502STheodore Ts'o 		return 0;
104512219aeaSAneesh Kumar K.V 
10469d0be502STheodore Ts'o 	lblock -= EXT4_NDIR_BLOCKS;
104712219aeaSAneesh Kumar K.V 
10489d0be502STheodore Ts'o 	if (ei->i_da_metadata_calc_len &&
10499d0be502STheodore Ts'o 	    (lblock & dind_mask) == ei->i_da_metadata_calc_last_lblock) {
10509d0be502STheodore Ts'o 		ei->i_da_metadata_calc_len++;
10519d0be502STheodore Ts'o 		return 0;
10529d0be502STheodore Ts'o 	}
10539d0be502STheodore Ts'o 	ei->i_da_metadata_calc_last_lblock = lblock & dind_mask;
10549d0be502STheodore Ts'o 	ei->i_da_metadata_calc_len = 1;
1055d330a5beSJan Kara 	blk_bits = order_base_2(lblock);
10569d0be502STheodore Ts'o 	return (blk_bits / EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb)) + 1;
105712219aeaSAneesh Kumar K.V }
105812219aeaSAneesh Kumar K.V 
105912219aeaSAneesh Kumar K.V /*
106012219aeaSAneesh Kumar K.V  * Calculate the number of metadata blocks need to reserve
10619d0be502STheodore Ts'o  * to allocate a block located at @lblock
106212219aeaSAneesh Kumar K.V  */
10639d0be502STheodore Ts'o static int ext4_calc_metadata_amount(struct inode *inode, sector_t lblock)
106412219aeaSAneesh Kumar K.V {
106512e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
10669d0be502STheodore Ts'o 		return ext4_ext_calc_metadata_amount(inode, lblock);
106712219aeaSAneesh Kumar K.V 
10689d0be502STheodore Ts'o 	return ext4_indirect_calc_metadata_amount(inode, lblock);
106912219aeaSAneesh Kumar K.V }
107012219aeaSAneesh Kumar K.V 
10710637c6f4STheodore Ts'o /*
10720637c6f4STheodore Ts'o  * Called with i_data_sem down, which is important since we can call
10730637c6f4STheodore Ts'o  * ext4_discard_preallocations() from here.
10740637c6f4STheodore Ts'o  */
10755f634d06SAneesh Kumar K.V void ext4_da_update_reserve_space(struct inode *inode,
10765f634d06SAneesh Kumar K.V 					int used, int quota_claim)
107712219aeaSAneesh Kumar K.V {
107812219aeaSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
10790637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
108012219aeaSAneesh Kumar K.V 
10810637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
1082f8ec9d68STheodore Ts'o 	trace_ext4_da_update_reserve_space(inode, used);
10830637c6f4STheodore Ts'o 	if (unlikely(used > ei->i_reserved_data_blocks)) {
10840637c6f4STheodore Ts'o 		ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
10850637c6f4STheodore Ts'o 			 "with only %d reserved data blocks\n",
10860637c6f4STheodore Ts'o 			 __func__, inode->i_ino, used,
10870637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
10880637c6f4STheodore Ts'o 		WARN_ON(1);
10890637c6f4STheodore Ts'o 		used = ei->i_reserved_data_blocks;
10906bc6e63fSAneesh Kumar K.V 	}
109112219aeaSAneesh Kumar K.V 
10920637c6f4STheodore Ts'o 	/* Update per-inode reservations */
10930637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= used;
10940637c6f4STheodore Ts'o 	ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
109572b8ab9dSEric Sandeen 	percpu_counter_sub(&sbi->s_dirtyblocks_counter,
109672b8ab9dSEric Sandeen 			   used + ei->i_allocated_meta_blocks);
10970637c6f4STheodore Ts'o 	ei->i_allocated_meta_blocks = 0;
10980637c6f4STheodore Ts'o 
10990637c6f4STheodore Ts'o 	if (ei->i_reserved_data_blocks == 0) {
11000637c6f4STheodore Ts'o 		/*
11010637c6f4STheodore Ts'o 		 * We can release all of the reserved metadata blocks
11020637c6f4STheodore Ts'o 		 * only when we have written all of the delayed
11030637c6f4STheodore Ts'o 		 * allocation blocks.
11040637c6f4STheodore Ts'o 		 */
110572b8ab9dSEric Sandeen 		percpu_counter_sub(&sbi->s_dirtyblocks_counter,
110672b8ab9dSEric Sandeen 				   ei->i_reserved_meta_blocks);
1107ee5f4d9cSTheodore Ts'o 		ei->i_reserved_meta_blocks = 0;
11089d0be502STheodore Ts'o 		ei->i_da_metadata_calc_len = 0;
11090637c6f4STheodore Ts'o 	}
111012219aeaSAneesh Kumar K.V 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
111160e58e0fSMingming Cao 
111272b8ab9dSEric Sandeen 	/* Update quota subsystem for data blocks */
111372b8ab9dSEric Sandeen 	if (quota_claim)
11145dd4056dSChristoph Hellwig 		dquot_claim_block(inode, used);
111572b8ab9dSEric Sandeen 	else {
11165f634d06SAneesh Kumar K.V 		/*
11175f634d06SAneesh Kumar K.V 		 * We did fallocate with an offset that is already delayed
11185f634d06SAneesh Kumar K.V 		 * allocated. So on delayed allocated writeback we should
111972b8ab9dSEric Sandeen 		 * not re-claim the quota for fallocated blocks.
11205f634d06SAneesh Kumar K.V 		 */
112172b8ab9dSEric Sandeen 		dquot_release_reservation_block(inode, used);
11225f634d06SAneesh Kumar K.V 	}
1123d6014301SAneesh Kumar K.V 
1124d6014301SAneesh Kumar K.V 	/*
1125d6014301SAneesh Kumar K.V 	 * If we have done all the pending block allocations and if
1126d6014301SAneesh Kumar K.V 	 * there aren't any writers on the inode, we can discard the
1127d6014301SAneesh Kumar K.V 	 * inode's preallocations.
1128d6014301SAneesh Kumar K.V 	 */
11290637c6f4STheodore Ts'o 	if ((ei->i_reserved_data_blocks == 0) &&
11300637c6f4STheodore Ts'o 	    (atomic_read(&inode->i_writecount) == 0))
1131d6014301SAneesh Kumar K.V 		ext4_discard_preallocations(inode);
113212219aeaSAneesh Kumar K.V }
113312219aeaSAneesh Kumar K.V 
1134e29136f8STheodore Ts'o static int __check_block_validity(struct inode *inode, const char *func,
1135*c398eda0STheodore Ts'o 				unsigned int line,
113624676da4STheodore Ts'o 				struct ext4_map_blocks *map)
11376fd058f7STheodore Ts'o {
113824676da4STheodore Ts'o 	if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
113924676da4STheodore Ts'o 				   map->m_len)) {
1140*c398eda0STheodore Ts'o 		ext4_error_inode(inode, func, line, map->m_pblk,
1141*c398eda0STheodore Ts'o 				 "lblock %lu mapped to illegal pblock "
114224676da4STheodore Ts'o 				 "(length %d)", (unsigned long) map->m_lblk,
1143*c398eda0STheodore Ts'o 				 map->m_len);
11446fd058f7STheodore Ts'o 		return -EIO;
11456fd058f7STheodore Ts'o 	}
11466fd058f7STheodore Ts'o 	return 0;
11476fd058f7STheodore Ts'o }
11486fd058f7STheodore Ts'o 
1149e29136f8STheodore Ts'o #define check_block_validity(inode, map)	\
1150*c398eda0STheodore Ts'o 	__check_block_validity((inode), __func__, __LINE__, (map))
1151e29136f8STheodore Ts'o 
1152f5ab0d1fSMingming Cao /*
11531f94533dSTheodore Ts'o  * Return the number of contiguous dirty pages in a given inode
11541f94533dSTheodore Ts'o  * starting at page frame idx.
115555138e0bSTheodore Ts'o  */
115655138e0bSTheodore Ts'o static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
115755138e0bSTheodore Ts'o 				    unsigned int max_pages)
115855138e0bSTheodore Ts'o {
115955138e0bSTheodore Ts'o 	struct address_space *mapping = inode->i_mapping;
116055138e0bSTheodore Ts'o 	pgoff_t	index;
116155138e0bSTheodore Ts'o 	struct pagevec pvec;
116255138e0bSTheodore Ts'o 	pgoff_t num = 0;
116355138e0bSTheodore Ts'o 	int i, nr_pages, done = 0;
116455138e0bSTheodore Ts'o 
116555138e0bSTheodore Ts'o 	if (max_pages == 0)
116655138e0bSTheodore Ts'o 		return 0;
116755138e0bSTheodore Ts'o 	pagevec_init(&pvec, 0);
116855138e0bSTheodore Ts'o 	while (!done) {
116955138e0bSTheodore Ts'o 		index = idx;
117055138e0bSTheodore Ts'o 		nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
117155138e0bSTheodore Ts'o 					      PAGECACHE_TAG_DIRTY,
117255138e0bSTheodore Ts'o 					      (pgoff_t)PAGEVEC_SIZE);
117355138e0bSTheodore Ts'o 		if (nr_pages == 0)
117455138e0bSTheodore Ts'o 			break;
117555138e0bSTheodore Ts'o 		for (i = 0; i < nr_pages; i++) {
117655138e0bSTheodore Ts'o 			struct page *page = pvec.pages[i];
117755138e0bSTheodore Ts'o 			struct buffer_head *bh, *head;
117855138e0bSTheodore Ts'o 
117955138e0bSTheodore Ts'o 			lock_page(page);
118055138e0bSTheodore Ts'o 			if (unlikely(page->mapping != mapping) ||
118155138e0bSTheodore Ts'o 			    !PageDirty(page) ||
118255138e0bSTheodore Ts'o 			    PageWriteback(page) ||
118355138e0bSTheodore Ts'o 			    page->index != idx) {
118455138e0bSTheodore Ts'o 				done = 1;
118555138e0bSTheodore Ts'o 				unlock_page(page);
118655138e0bSTheodore Ts'o 				break;
118755138e0bSTheodore Ts'o 			}
11881f94533dSTheodore Ts'o 			if (page_has_buffers(page)) {
11891f94533dSTheodore Ts'o 				bh = head = page_buffers(page);
119055138e0bSTheodore Ts'o 				do {
119155138e0bSTheodore Ts'o 					if (!buffer_delay(bh) &&
11921f94533dSTheodore Ts'o 					    !buffer_unwritten(bh))
119355138e0bSTheodore Ts'o 						done = 1;
11941f94533dSTheodore Ts'o 					bh = bh->b_this_page;
11951f94533dSTheodore Ts'o 				} while (!done && (bh != head));
119655138e0bSTheodore Ts'o 			}
119755138e0bSTheodore Ts'o 			unlock_page(page);
119855138e0bSTheodore Ts'o 			if (done)
119955138e0bSTheodore Ts'o 				break;
120055138e0bSTheodore Ts'o 			idx++;
120155138e0bSTheodore Ts'o 			num++;
120255138e0bSTheodore Ts'o 			if (num >= max_pages)
120355138e0bSTheodore Ts'o 				break;
120455138e0bSTheodore Ts'o 		}
120555138e0bSTheodore Ts'o 		pagevec_release(&pvec);
120655138e0bSTheodore Ts'o 	}
120755138e0bSTheodore Ts'o 	return num;
120855138e0bSTheodore Ts'o }
120955138e0bSTheodore Ts'o 
121055138e0bSTheodore Ts'o /*
1211e35fd660STheodore Ts'o  * The ext4_map_blocks() function tries to look up the requested blocks,
12122b2d6d01STheodore Ts'o  * and returns if the blocks are already mapped.
1213f5ab0d1fSMingming Cao  *
1214f5ab0d1fSMingming Cao  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
1215f5ab0d1fSMingming Cao  * and store the allocated blocks in the result buffer head and mark it
1216f5ab0d1fSMingming Cao  * mapped.
1217f5ab0d1fSMingming Cao  *
1218e35fd660STheodore Ts'o  * If file type is extents based, it will call ext4_ext_map_blocks(),
1219e35fd660STheodore Ts'o  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
1220f5ab0d1fSMingming Cao  * based files
1221f5ab0d1fSMingming Cao  *
1222f5ab0d1fSMingming Cao  * On success, it returns the number of blocks being mapped or allocate.
1223f5ab0d1fSMingming Cao  * if create==0 and the blocks are pre-allocated and uninitialized block,
1224f5ab0d1fSMingming Cao  * the result buffer head is unmapped. If the create ==1, it will make sure
1225f5ab0d1fSMingming Cao  * the buffer head is mapped.
1226f5ab0d1fSMingming Cao  *
1227f5ab0d1fSMingming Cao  * It returns 0 if plain look up failed (blocks have not been allocated), in
1228f5ab0d1fSMingming Cao  * that casem, buffer head is unmapped
1229f5ab0d1fSMingming Cao  *
1230f5ab0d1fSMingming Cao  * It returns the error in case of allocation failure.
1231f5ab0d1fSMingming Cao  */
1232e35fd660STheodore Ts'o int ext4_map_blocks(handle_t *handle, struct inode *inode,
1233e35fd660STheodore Ts'o 		    struct ext4_map_blocks *map, int flags)
12340e855ac8SAneesh Kumar K.V {
12350e855ac8SAneesh Kumar K.V 	int retval;
1236f5ab0d1fSMingming Cao 
1237e35fd660STheodore Ts'o 	map->m_flags = 0;
1238e35fd660STheodore Ts'o 	ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
1239e35fd660STheodore Ts'o 		  "logical block %lu\n", inode->i_ino, flags, map->m_len,
1240e35fd660STheodore Ts'o 		  (unsigned long) map->m_lblk);
12414df3d265SAneesh Kumar K.V 	/*
1242b920c755STheodore Ts'o 	 * Try to see if we can get the block without requesting a new
1243b920c755STheodore Ts'o 	 * file system block.
12444df3d265SAneesh Kumar K.V 	 */
12450e855ac8SAneesh Kumar K.V 	down_read((&EXT4_I(inode)->i_data_sem));
124612e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
1247e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
12484df3d265SAneesh Kumar K.V 	} else {
1249e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
12500e855ac8SAneesh Kumar K.V 	}
12514df3d265SAneesh Kumar K.V 	up_read((&EXT4_I(inode)->i_data_sem));
1252f5ab0d1fSMingming Cao 
1253e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
1254e29136f8STheodore Ts'o 		int ret = check_block_validity(inode, map);
12556fd058f7STheodore Ts'o 		if (ret != 0)
12566fd058f7STheodore Ts'o 			return ret;
12576fd058f7STheodore Ts'o 	}
12586fd058f7STheodore Ts'o 
1259f5ab0d1fSMingming Cao 	/* If it is only a block(s) look up */
1260c2177057STheodore Ts'o 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
12614df3d265SAneesh Kumar K.V 		return retval;
12624df3d265SAneesh Kumar K.V 
12634df3d265SAneesh Kumar K.V 	/*
1264f5ab0d1fSMingming Cao 	 * Returns if the blocks have already allocated
1265f5ab0d1fSMingming Cao 	 *
1266f5ab0d1fSMingming Cao 	 * Note that if blocks have been preallocated
1267f5ab0d1fSMingming Cao 	 * ext4_ext_get_block() returns th create = 0
1268f5ab0d1fSMingming Cao 	 * with buffer head unmapped.
1269f5ab0d1fSMingming Cao 	 */
1270e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
1271f5ab0d1fSMingming Cao 		return retval;
1272f5ab0d1fSMingming Cao 
1273f5ab0d1fSMingming Cao 	/*
12742a8964d6SAneesh Kumar K.V 	 * When we call get_blocks without the create flag, the
12752a8964d6SAneesh Kumar K.V 	 * BH_Unwritten flag could have gotten set if the blocks
12762a8964d6SAneesh Kumar K.V 	 * requested were part of a uninitialized extent.  We need to
12772a8964d6SAneesh Kumar K.V 	 * clear this flag now that we are committed to convert all or
12782a8964d6SAneesh Kumar K.V 	 * part of the uninitialized extent to be an initialized
12792a8964d6SAneesh Kumar K.V 	 * extent.  This is because we need to avoid the combination
12802a8964d6SAneesh Kumar K.V 	 * of BH_Unwritten and BH_Mapped flags being simultaneously
12812a8964d6SAneesh Kumar K.V 	 * set on the buffer_head.
12822a8964d6SAneesh Kumar K.V 	 */
1283e35fd660STheodore Ts'o 	map->m_flags &= ~EXT4_MAP_UNWRITTEN;
12842a8964d6SAneesh Kumar K.V 
12852a8964d6SAneesh Kumar K.V 	/*
1286f5ab0d1fSMingming Cao 	 * New blocks allocate and/or writing to uninitialized extent
1287f5ab0d1fSMingming Cao 	 * will possibly result in updating i_data, so we take
1288f5ab0d1fSMingming Cao 	 * the write lock of i_data_sem, and call get_blocks()
1289f5ab0d1fSMingming Cao 	 * with create == 1 flag.
12904df3d265SAneesh Kumar K.V 	 */
12914df3d265SAneesh Kumar K.V 	down_write((&EXT4_I(inode)->i_data_sem));
1292d2a17637SMingming Cao 
1293d2a17637SMingming Cao 	/*
1294d2a17637SMingming Cao 	 * if the caller is from delayed allocation writeout path
1295d2a17637SMingming Cao 	 * we have already reserved fs blocks for allocation
1296d2a17637SMingming Cao 	 * let the underlying get_block() function know to
1297d2a17637SMingming Cao 	 * avoid double accounting
1298d2a17637SMingming Cao 	 */
1299c2177057STheodore Ts'o 	if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1300d2a17637SMingming Cao 		EXT4_I(inode)->i_delalloc_reserved_flag = 1;
13014df3d265SAneesh Kumar K.V 	/*
13024df3d265SAneesh Kumar K.V 	 * We need to check for EXT4 here because migrate
13034df3d265SAneesh Kumar K.V 	 * could have changed the inode type in between
13044df3d265SAneesh Kumar K.V 	 */
130512e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
1306e35fd660STheodore Ts'o 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
13070e855ac8SAneesh Kumar K.V 	} else {
1308e35fd660STheodore Ts'o 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
1309267e4db9SAneesh Kumar K.V 
1310e35fd660STheodore Ts'o 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
1311267e4db9SAneesh Kumar K.V 			/*
1312267e4db9SAneesh Kumar K.V 			 * We allocated new blocks which will result in
1313267e4db9SAneesh Kumar K.V 			 * i_data's format changing.  Force the migrate
1314267e4db9SAneesh Kumar K.V 			 * to fail by clearing migrate flags
1315267e4db9SAneesh Kumar K.V 			 */
131619f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
1317267e4db9SAneesh Kumar K.V 		}
13182ac3b6e0STheodore Ts'o 
1319d2a17637SMingming Cao 		/*
13202ac3b6e0STheodore Ts'o 		 * Update reserved blocks/metadata blocks after successful
13215f634d06SAneesh Kumar K.V 		 * block allocation which had been deferred till now. We don't
13225f634d06SAneesh Kumar K.V 		 * support fallocate for non extent files. So we can update
13235f634d06SAneesh Kumar K.V 		 * reserve space here.
1324d2a17637SMingming Cao 		 */
13255f634d06SAneesh Kumar K.V 		if ((retval > 0) &&
13261296cc85SAneesh Kumar K.V 			(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
13275f634d06SAneesh Kumar K.V 			ext4_da_update_reserve_space(inode, retval, 1);
13285f634d06SAneesh Kumar K.V 	}
13295f634d06SAneesh Kumar K.V 	if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
13305f634d06SAneesh Kumar K.V 		EXT4_I(inode)->i_delalloc_reserved_flag = 0;
1331d2a17637SMingming Cao 
13320e855ac8SAneesh Kumar K.V 	up_write((&EXT4_I(inode)->i_data_sem));
1333e35fd660STheodore Ts'o 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
1334e29136f8STheodore Ts'o 		int ret = check_block_validity(inode, map);
13356fd058f7STheodore Ts'o 		if (ret != 0)
13366fd058f7STheodore Ts'o 			return ret;
13376fd058f7STheodore Ts'o 	}
13380e855ac8SAneesh Kumar K.V 	return retval;
13390e855ac8SAneesh Kumar K.V }
13400e855ac8SAneesh Kumar K.V 
1341f3bd1f3fSMingming Cao /* Maximum number of blocks we map for direct IO at once. */
1342f3bd1f3fSMingming Cao #define DIO_MAX_BLOCKS 4096
1343f3bd1f3fSMingming Cao 
13442ed88685STheodore Ts'o static int _ext4_get_block(struct inode *inode, sector_t iblock,
13452ed88685STheodore Ts'o 			   struct buffer_head *bh, int flags)
1346ac27a0ecSDave Kleikamp {
13473e4fdaf8SDmitriy Monakhov 	handle_t *handle = ext4_journal_current_handle();
13482ed88685STheodore Ts'o 	struct ext4_map_blocks map;
13497fb5409dSJan Kara 	int ret = 0, started = 0;
1350f3bd1f3fSMingming Cao 	int dio_credits;
1351ac27a0ecSDave Kleikamp 
13522ed88685STheodore Ts'o 	map.m_lblk = iblock;
13532ed88685STheodore Ts'o 	map.m_len = bh->b_size >> inode->i_blkbits;
13542ed88685STheodore Ts'o 
13552ed88685STheodore Ts'o 	if (flags && !handle) {
13567fb5409dSJan Kara 		/* Direct IO write... */
13572ed88685STheodore Ts'o 		if (map.m_len > DIO_MAX_BLOCKS)
13582ed88685STheodore Ts'o 			map.m_len = DIO_MAX_BLOCKS;
13592ed88685STheodore Ts'o 		dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
1360f3bd1f3fSMingming Cao 		handle = ext4_journal_start(inode, dio_credits);
13617fb5409dSJan Kara 		if (IS_ERR(handle)) {
1362ac27a0ecSDave Kleikamp 			ret = PTR_ERR(handle);
13632ed88685STheodore Ts'o 			return ret;
13647fb5409dSJan Kara 		}
13657fb5409dSJan Kara 		started = 1;
1366ac27a0ecSDave Kleikamp 	}
1367ac27a0ecSDave Kleikamp 
13682ed88685STheodore Ts'o 	ret = ext4_map_blocks(handle, inode, &map, flags);
1369ac27a0ecSDave Kleikamp 	if (ret > 0) {
13702ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, map.m_pblk);
13712ed88685STheodore Ts'o 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
13722ed88685STheodore Ts'o 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
1373ac27a0ecSDave Kleikamp 		ret = 0;
1374ac27a0ecSDave Kleikamp 	}
13757fb5409dSJan Kara 	if (started)
13767fb5409dSJan Kara 		ext4_journal_stop(handle);
1377ac27a0ecSDave Kleikamp 	return ret;
1378ac27a0ecSDave Kleikamp }
1379ac27a0ecSDave Kleikamp 
13802ed88685STheodore Ts'o int ext4_get_block(struct inode *inode, sector_t iblock,
13812ed88685STheodore Ts'o 		   struct buffer_head *bh, int create)
13822ed88685STheodore Ts'o {
13832ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh,
13842ed88685STheodore Ts'o 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
13852ed88685STheodore Ts'o }
13862ed88685STheodore Ts'o 
1387ac27a0ecSDave Kleikamp /*
1388ac27a0ecSDave Kleikamp  * `handle' can be NULL if create is zero
1389ac27a0ecSDave Kleikamp  */
1390617ba13bSMingming Cao struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
1391725d26d3SAneesh Kumar K.V 				ext4_lblk_t block, int create, int *errp)
1392ac27a0ecSDave Kleikamp {
13932ed88685STheodore Ts'o 	struct ext4_map_blocks map;
13942ed88685STheodore Ts'o 	struct buffer_head *bh;
1395ac27a0ecSDave Kleikamp 	int fatal = 0, err;
1396ac27a0ecSDave Kleikamp 
1397ac27a0ecSDave Kleikamp 	J_ASSERT(handle != NULL || create == 0);
1398ac27a0ecSDave Kleikamp 
13992ed88685STheodore Ts'o 	map.m_lblk = block;
14002ed88685STheodore Ts'o 	map.m_len = 1;
14012ed88685STheodore Ts'o 	err = ext4_map_blocks(handle, inode, &map,
14022ed88685STheodore Ts'o 			      create ? EXT4_GET_BLOCKS_CREATE : 0);
14032ed88685STheodore Ts'o 
14042ed88685STheodore Ts'o 	if (err < 0)
1405ac27a0ecSDave Kleikamp 		*errp = err;
14062ed88685STheodore Ts'o 	if (err <= 0)
14072ed88685STheodore Ts'o 		return NULL;
14082ed88685STheodore Ts'o 	*errp = 0;
14092ed88685STheodore Ts'o 
14102ed88685STheodore Ts'o 	bh = sb_getblk(inode->i_sb, map.m_pblk);
1411ac27a0ecSDave Kleikamp 	if (!bh) {
1412ac27a0ecSDave Kleikamp 		*errp = -EIO;
14132ed88685STheodore Ts'o 		return NULL;
1414ac27a0ecSDave Kleikamp 	}
14152ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
1416ac27a0ecSDave Kleikamp 		J_ASSERT(create != 0);
1417ac39849dSAneesh Kumar K.V 		J_ASSERT(handle != NULL);
1418ac27a0ecSDave Kleikamp 
1419ac27a0ecSDave Kleikamp 		/*
1420ac27a0ecSDave Kleikamp 		 * Now that we do not always journal data, we should
1421ac27a0ecSDave Kleikamp 		 * keep in mind whether this should always journal the
1422ac27a0ecSDave Kleikamp 		 * new buffer as metadata.  For now, regular file
1423617ba13bSMingming Cao 		 * writes use ext4_get_block instead, so it's not a
1424ac27a0ecSDave Kleikamp 		 * problem.
1425ac27a0ecSDave Kleikamp 		 */
1426ac27a0ecSDave Kleikamp 		lock_buffer(bh);
1427ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "call get_create_access");
1428617ba13bSMingming Cao 		fatal = ext4_journal_get_create_access(handle, bh);
1429ac27a0ecSDave Kleikamp 		if (!fatal && !buffer_uptodate(bh)) {
1430ac27a0ecSDave Kleikamp 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1431ac27a0ecSDave Kleikamp 			set_buffer_uptodate(bh);
1432ac27a0ecSDave Kleikamp 		}
1433ac27a0ecSDave Kleikamp 		unlock_buffer(bh);
14340390131bSFrank Mayhar 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
14350390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
1436ac27a0ecSDave Kleikamp 		if (!fatal)
1437ac27a0ecSDave Kleikamp 			fatal = err;
1438ac27a0ecSDave Kleikamp 	} else {
1439ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "not a new buffer");
1440ac27a0ecSDave Kleikamp 	}
1441ac27a0ecSDave Kleikamp 	if (fatal) {
1442ac27a0ecSDave Kleikamp 		*errp = fatal;
1443ac27a0ecSDave Kleikamp 		brelse(bh);
1444ac27a0ecSDave Kleikamp 		bh = NULL;
1445ac27a0ecSDave Kleikamp 	}
1446ac27a0ecSDave Kleikamp 	return bh;
1447ac27a0ecSDave Kleikamp }
1448ac27a0ecSDave Kleikamp 
1449617ba13bSMingming Cao struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1450725d26d3SAneesh Kumar K.V 			       ext4_lblk_t block, int create, int *err)
1451ac27a0ecSDave Kleikamp {
1452ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
1453ac27a0ecSDave Kleikamp 
1454617ba13bSMingming Cao 	bh = ext4_getblk(handle, inode, block, create, err);
1455ac27a0ecSDave Kleikamp 	if (!bh)
1456ac27a0ecSDave Kleikamp 		return bh;
1457ac27a0ecSDave Kleikamp 	if (buffer_uptodate(bh))
1458ac27a0ecSDave Kleikamp 		return bh;
1459ac27a0ecSDave Kleikamp 	ll_rw_block(READ_META, 1, &bh);
1460ac27a0ecSDave Kleikamp 	wait_on_buffer(bh);
1461ac27a0ecSDave Kleikamp 	if (buffer_uptodate(bh))
1462ac27a0ecSDave Kleikamp 		return bh;
1463ac27a0ecSDave Kleikamp 	put_bh(bh);
1464ac27a0ecSDave Kleikamp 	*err = -EIO;
1465ac27a0ecSDave Kleikamp 	return NULL;
1466ac27a0ecSDave Kleikamp }
1467ac27a0ecSDave Kleikamp 
1468ac27a0ecSDave Kleikamp static int walk_page_buffers(handle_t *handle,
1469ac27a0ecSDave Kleikamp 			     struct buffer_head *head,
1470ac27a0ecSDave Kleikamp 			     unsigned from,
1471ac27a0ecSDave Kleikamp 			     unsigned to,
1472ac27a0ecSDave Kleikamp 			     int *partial,
1473ac27a0ecSDave Kleikamp 			     int (*fn)(handle_t *handle,
1474ac27a0ecSDave Kleikamp 				       struct buffer_head *bh))
1475ac27a0ecSDave Kleikamp {
1476ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
1477ac27a0ecSDave Kleikamp 	unsigned block_start, block_end;
1478ac27a0ecSDave Kleikamp 	unsigned blocksize = head->b_size;
1479ac27a0ecSDave Kleikamp 	int err, ret = 0;
1480ac27a0ecSDave Kleikamp 	struct buffer_head *next;
1481ac27a0ecSDave Kleikamp 
1482ac27a0ecSDave Kleikamp 	for (bh = head, block_start = 0;
1483ac27a0ecSDave Kleikamp 	     ret == 0 && (bh != head || !block_start);
1484de9a55b8STheodore Ts'o 	     block_start = block_end, bh = next) {
1485ac27a0ecSDave Kleikamp 		next = bh->b_this_page;
1486ac27a0ecSDave Kleikamp 		block_end = block_start + blocksize;
1487ac27a0ecSDave Kleikamp 		if (block_end <= from || block_start >= to) {
1488ac27a0ecSDave Kleikamp 			if (partial && !buffer_uptodate(bh))
1489ac27a0ecSDave Kleikamp 				*partial = 1;
1490ac27a0ecSDave Kleikamp 			continue;
1491ac27a0ecSDave Kleikamp 		}
1492ac27a0ecSDave Kleikamp 		err = (*fn)(handle, bh);
1493ac27a0ecSDave Kleikamp 		if (!ret)
1494ac27a0ecSDave Kleikamp 			ret = err;
1495ac27a0ecSDave Kleikamp 	}
1496ac27a0ecSDave Kleikamp 	return ret;
1497ac27a0ecSDave Kleikamp }
1498ac27a0ecSDave Kleikamp 
1499ac27a0ecSDave Kleikamp /*
1500ac27a0ecSDave Kleikamp  * To preserve ordering, it is essential that the hole instantiation and
1501ac27a0ecSDave Kleikamp  * the data write be encapsulated in a single transaction.  We cannot
1502617ba13bSMingming Cao  * close off a transaction and start a new one between the ext4_get_block()
1503dab291afSMingming Cao  * and the commit_write().  So doing the jbd2_journal_start at the start of
1504ac27a0ecSDave Kleikamp  * prepare_write() is the right place.
1505ac27a0ecSDave Kleikamp  *
1506617ba13bSMingming Cao  * Also, this function can nest inside ext4_writepage() ->
1507617ba13bSMingming Cao  * block_write_full_page(). In that case, we *know* that ext4_writepage()
1508ac27a0ecSDave Kleikamp  * has generated enough buffer credits to do the whole page.  So we won't
1509ac27a0ecSDave Kleikamp  * block on the journal in that case, which is good, because the caller may
1510ac27a0ecSDave Kleikamp  * be PF_MEMALLOC.
1511ac27a0ecSDave Kleikamp  *
1512617ba13bSMingming Cao  * By accident, ext4 can be reentered when a transaction is open via
1513ac27a0ecSDave Kleikamp  * quota file writes.  If we were to commit the transaction while thus
1514ac27a0ecSDave Kleikamp  * reentered, there can be a deadlock - we would be holding a quota
1515ac27a0ecSDave Kleikamp  * lock, and the commit would never complete if another thread had a
1516ac27a0ecSDave Kleikamp  * transaction open and was blocking on the quota lock - a ranking
1517ac27a0ecSDave Kleikamp  * violation.
1518ac27a0ecSDave Kleikamp  *
1519dab291afSMingming Cao  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1520ac27a0ecSDave Kleikamp  * will _not_ run commit under these circumstances because handle->h_ref
1521ac27a0ecSDave Kleikamp  * is elevated.  We'll still have enough credits for the tiny quotafile
1522ac27a0ecSDave Kleikamp  * write.
1523ac27a0ecSDave Kleikamp  */
1524ac27a0ecSDave Kleikamp static int do_journal_get_write_access(handle_t *handle,
1525ac27a0ecSDave Kleikamp 				       struct buffer_head *bh)
1526ac27a0ecSDave Kleikamp {
1527ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1528ac27a0ecSDave Kleikamp 		return 0;
1529617ba13bSMingming Cao 	return ext4_journal_get_write_access(handle, bh);
1530ac27a0ecSDave Kleikamp }
1531ac27a0ecSDave Kleikamp 
1532b9a4207dSJan Kara /*
1533b9a4207dSJan Kara  * Truncate blocks that were not used by write. We have to truncate the
1534b9a4207dSJan Kara  * pagecache as well so that corresponding buffers get properly unmapped.
1535b9a4207dSJan Kara  */
1536b9a4207dSJan Kara static void ext4_truncate_failed_write(struct inode *inode)
1537b9a4207dSJan Kara {
1538b9a4207dSJan Kara 	truncate_inode_pages(inode->i_mapping, inode->i_size);
1539b9a4207dSJan Kara 	ext4_truncate(inode);
1540b9a4207dSJan Kara }
1541b9a4207dSJan Kara 
1542744692dcSJiaying Zhang static int ext4_get_block_write(struct inode *inode, sector_t iblock,
1543744692dcSJiaying Zhang 		   struct buffer_head *bh_result, int create);
1544bfc1af65SNick Piggin static int ext4_write_begin(struct file *file, struct address_space *mapping,
1545bfc1af65SNick Piggin 			    loff_t pos, unsigned len, unsigned flags,
1546bfc1af65SNick Piggin 			    struct page **pagep, void **fsdata)
1547ac27a0ecSDave Kleikamp {
1548bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
15491938a150SAneesh Kumar K.V 	int ret, needed_blocks;
1550ac27a0ecSDave Kleikamp 	handle_t *handle;
1551ac27a0ecSDave Kleikamp 	int retries = 0;
1552bfc1af65SNick Piggin 	struct page *page;
1553bfc1af65SNick Piggin 	pgoff_t index;
1554bfc1af65SNick Piggin 	unsigned from, to;
1555bfc1af65SNick Piggin 
15569bffad1eSTheodore Ts'o 	trace_ext4_write_begin(inode, pos, len, flags);
15571938a150SAneesh Kumar K.V 	/*
15581938a150SAneesh Kumar K.V 	 * Reserve one block more for addition to orphan list in case
15591938a150SAneesh Kumar K.V 	 * we allocate blocks but write fails for some reason
15601938a150SAneesh Kumar K.V 	 */
15611938a150SAneesh Kumar K.V 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1562bfc1af65SNick Piggin 	index = pos >> PAGE_CACHE_SHIFT;
1563bfc1af65SNick Piggin 	from = pos & (PAGE_CACHE_SIZE - 1);
1564bfc1af65SNick Piggin 	to = from + len;
1565ac27a0ecSDave Kleikamp 
1566ac27a0ecSDave Kleikamp retry:
1567617ba13bSMingming Cao 	handle = ext4_journal_start(inode, needed_blocks);
15687479d2b9SAndrew Morton 	if (IS_ERR(handle)) {
15697479d2b9SAndrew Morton 		ret = PTR_ERR(handle);
15707479d2b9SAndrew Morton 		goto out;
15717479d2b9SAndrew Morton 	}
1572ac27a0ecSDave Kleikamp 
1573ebd3610bSJan Kara 	/* We cannot recurse into the filesystem as the transaction is already
1574ebd3610bSJan Kara 	 * started */
1575ebd3610bSJan Kara 	flags |= AOP_FLAG_NOFS;
1576ebd3610bSJan Kara 
157754566b2cSNick Piggin 	page = grab_cache_page_write_begin(mapping, index, flags);
1578cf108bcaSJan Kara 	if (!page) {
1579cf108bcaSJan Kara 		ext4_journal_stop(handle);
1580cf108bcaSJan Kara 		ret = -ENOMEM;
1581cf108bcaSJan Kara 		goto out;
1582cf108bcaSJan Kara 	}
1583cf108bcaSJan Kara 	*pagep = page;
1584cf108bcaSJan Kara 
1585744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(inode))
1586744692dcSJiaying Zhang 		ret = block_write_begin(file, mapping, pos, len, flags, pagep,
1587744692dcSJiaying Zhang 				fsdata, ext4_get_block_write);
1588744692dcSJiaying Zhang 	else
1589744692dcSJiaying Zhang 		ret = block_write_begin(file, mapping, pos, len, flags, pagep,
1590744692dcSJiaying Zhang 				fsdata, ext4_get_block);
1591bfc1af65SNick Piggin 
1592bfc1af65SNick Piggin 	if (!ret && ext4_should_journal_data(inode)) {
1593ac27a0ecSDave Kleikamp 		ret = walk_page_buffers(handle, page_buffers(page),
1594ac27a0ecSDave Kleikamp 				from, to, NULL, do_journal_get_write_access);
1595b46be050SAndrey Savochkin 	}
1596bfc1af65SNick Piggin 
1597bfc1af65SNick Piggin 	if (ret) {
1598bfc1af65SNick Piggin 		unlock_page(page);
1599bfc1af65SNick Piggin 		page_cache_release(page);
1600ae4d5372SAneesh Kumar K.V 		/*
1601ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
1602ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
1603ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
16041938a150SAneesh Kumar K.V 		 *
16051938a150SAneesh Kumar K.V 		 * Add inode to orphan list in case we crash before
16061938a150SAneesh Kumar K.V 		 * truncate finishes
1607ae4d5372SAneesh Kumar K.V 		 */
1608ffacfa7aSJan Kara 		if (pos + len > inode->i_size && ext4_can_truncate(inode))
16091938a150SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
16101938a150SAneesh Kumar K.V 
16111938a150SAneesh Kumar K.V 		ext4_journal_stop(handle);
16121938a150SAneesh Kumar K.V 		if (pos + len > inode->i_size) {
1613b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
16141938a150SAneesh Kumar K.V 			/*
1615ffacfa7aSJan Kara 			 * If truncate failed early the inode might
16161938a150SAneesh Kumar K.V 			 * still be on the orphan list; we need to
16171938a150SAneesh Kumar K.V 			 * make sure the inode is removed from the
16181938a150SAneesh Kumar K.V 			 * orphan list in that case.
16191938a150SAneesh Kumar K.V 			 */
16201938a150SAneesh Kumar K.V 			if (inode->i_nlink)
16211938a150SAneesh Kumar K.V 				ext4_orphan_del(NULL, inode);
16221938a150SAneesh Kumar K.V 		}
1623bfc1af65SNick Piggin 	}
1624bfc1af65SNick Piggin 
1625617ba13bSMingming Cao 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1626ac27a0ecSDave Kleikamp 		goto retry;
16277479d2b9SAndrew Morton out:
1628ac27a0ecSDave Kleikamp 	return ret;
1629ac27a0ecSDave Kleikamp }
1630ac27a0ecSDave Kleikamp 
1631bfc1af65SNick Piggin /* For write_end() in data=journal mode */
1632bfc1af65SNick Piggin static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1633ac27a0ecSDave Kleikamp {
1634ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh) || buffer_freed(bh))
1635ac27a0ecSDave Kleikamp 		return 0;
1636ac27a0ecSDave Kleikamp 	set_buffer_uptodate(bh);
16370390131bSFrank Mayhar 	return ext4_handle_dirty_metadata(handle, NULL, bh);
1638ac27a0ecSDave Kleikamp }
1639ac27a0ecSDave Kleikamp 
1640f8514083SAneesh Kumar K.V static int ext4_generic_write_end(struct file *file,
1641f8514083SAneesh Kumar K.V 				  struct address_space *mapping,
1642f8514083SAneesh Kumar K.V 				  loff_t pos, unsigned len, unsigned copied,
1643f8514083SAneesh Kumar K.V 				  struct page *page, void *fsdata)
1644f8514083SAneesh Kumar K.V {
1645f8514083SAneesh Kumar K.V 	int i_size_changed = 0;
1646f8514083SAneesh Kumar K.V 	struct inode *inode = mapping->host;
1647f8514083SAneesh Kumar K.V 	handle_t *handle = ext4_journal_current_handle();
1648f8514083SAneesh Kumar K.V 
1649f8514083SAneesh Kumar K.V 	copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1650f8514083SAneesh Kumar K.V 
1651f8514083SAneesh Kumar K.V 	/*
1652f8514083SAneesh Kumar K.V 	 * No need to use i_size_read() here, the i_size
1653f8514083SAneesh Kumar K.V 	 * cannot change under us because we hold i_mutex.
1654f8514083SAneesh Kumar K.V 	 *
1655f8514083SAneesh Kumar K.V 	 * But it's important to update i_size while still holding page lock:
1656f8514083SAneesh Kumar K.V 	 * page writeout could otherwise come in and zero beyond i_size.
1657f8514083SAneesh Kumar K.V 	 */
1658f8514083SAneesh Kumar K.V 	if (pos + copied > inode->i_size) {
1659f8514083SAneesh Kumar K.V 		i_size_write(inode, pos + copied);
1660f8514083SAneesh Kumar K.V 		i_size_changed = 1;
1661f8514083SAneesh Kumar K.V 	}
1662f8514083SAneesh Kumar K.V 
1663f8514083SAneesh Kumar K.V 	if (pos + copied >  EXT4_I(inode)->i_disksize) {
1664f8514083SAneesh Kumar K.V 		/* We need to mark inode dirty even if
1665f8514083SAneesh Kumar K.V 		 * new_i_size is less that inode->i_size
1666f8514083SAneesh Kumar K.V 		 * bu greater than i_disksize.(hint delalloc)
1667f8514083SAneesh Kumar K.V 		 */
1668f8514083SAneesh Kumar K.V 		ext4_update_i_disksize(inode, (pos + copied));
1669f8514083SAneesh Kumar K.V 		i_size_changed = 1;
1670f8514083SAneesh Kumar K.V 	}
1671f8514083SAneesh Kumar K.V 	unlock_page(page);
1672f8514083SAneesh Kumar K.V 	page_cache_release(page);
1673f8514083SAneesh Kumar K.V 
1674f8514083SAneesh Kumar K.V 	/*
1675f8514083SAneesh Kumar K.V 	 * Don't mark the inode dirty under page lock. First, it unnecessarily
1676f8514083SAneesh Kumar K.V 	 * makes the holding time of page lock longer. Second, it forces lock
1677f8514083SAneesh Kumar K.V 	 * ordering of page lock and transaction start for journaling
1678f8514083SAneesh Kumar K.V 	 * filesystems.
1679f8514083SAneesh Kumar K.V 	 */
1680f8514083SAneesh Kumar K.V 	if (i_size_changed)
1681f8514083SAneesh Kumar K.V 		ext4_mark_inode_dirty(handle, inode);
1682f8514083SAneesh Kumar K.V 
1683f8514083SAneesh Kumar K.V 	return copied;
1684f8514083SAneesh Kumar K.V }
1685f8514083SAneesh Kumar K.V 
1686ac27a0ecSDave Kleikamp /*
1687ac27a0ecSDave Kleikamp  * We need to pick up the new inode size which generic_commit_write gave us
1688ac27a0ecSDave Kleikamp  * `file' can be NULL - eg, when called from page_symlink().
1689ac27a0ecSDave Kleikamp  *
1690617ba13bSMingming Cao  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1691ac27a0ecSDave Kleikamp  * buffers are managed internally.
1692ac27a0ecSDave Kleikamp  */
1693bfc1af65SNick Piggin static int ext4_ordered_write_end(struct file *file,
1694bfc1af65SNick Piggin 				  struct address_space *mapping,
1695bfc1af65SNick Piggin 				  loff_t pos, unsigned len, unsigned copied,
1696bfc1af65SNick Piggin 				  struct page *page, void *fsdata)
1697ac27a0ecSDave Kleikamp {
1698617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1699cf108bcaSJan Kara 	struct inode *inode = mapping->host;
1700ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1701ac27a0ecSDave Kleikamp 
17029bffad1eSTheodore Ts'o 	trace_ext4_ordered_write_end(inode, pos, len, copied);
1703678aaf48SJan Kara 	ret = ext4_jbd2_file_inode(handle, inode);
1704ac27a0ecSDave Kleikamp 
1705ac27a0ecSDave Kleikamp 	if (ret == 0) {
1706f8514083SAneesh Kumar K.V 		ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1707bfc1af65SNick Piggin 							page, fsdata);
1708f8a87d89SRoel Kluin 		copied = ret2;
1709ffacfa7aSJan Kara 		if (pos + len > inode->i_size && ext4_can_truncate(inode))
1710f8514083SAneesh Kumar K.V 			/* if we have allocated more blocks and copied
1711f8514083SAneesh Kumar K.V 			 * less. We will have blocks allocated outside
1712f8514083SAneesh Kumar K.V 			 * inode->i_size. So truncate them
1713f8514083SAneesh Kumar K.V 			 */
1714f8514083SAneesh Kumar K.V 			ext4_orphan_add(handle, inode);
1715f8a87d89SRoel Kluin 		if (ret2 < 0)
1716f8a87d89SRoel Kluin 			ret = ret2;
1717ac27a0ecSDave Kleikamp 	}
1718617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1719ac27a0ecSDave Kleikamp 	if (!ret)
1720ac27a0ecSDave Kleikamp 		ret = ret2;
1721bfc1af65SNick Piggin 
1722f8514083SAneesh Kumar K.V 	if (pos + len > inode->i_size) {
1723b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1724f8514083SAneesh Kumar K.V 		/*
1725ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1726f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1727f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1728f8514083SAneesh Kumar K.V 		 */
1729f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1730f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1731f8514083SAneesh Kumar K.V 	}
1732f8514083SAneesh Kumar K.V 
1733f8514083SAneesh Kumar K.V 
1734bfc1af65SNick Piggin 	return ret ? ret : copied;
1735ac27a0ecSDave Kleikamp }
1736ac27a0ecSDave Kleikamp 
1737bfc1af65SNick Piggin static int ext4_writeback_write_end(struct file *file,
1738bfc1af65SNick Piggin 				    struct address_space *mapping,
1739bfc1af65SNick Piggin 				    loff_t pos, unsigned len, unsigned copied,
1740bfc1af65SNick Piggin 				    struct page *page, void *fsdata)
1741ac27a0ecSDave Kleikamp {
1742617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1743cf108bcaSJan Kara 	struct inode *inode = mapping->host;
1744ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1745ac27a0ecSDave Kleikamp 
17469bffad1eSTheodore Ts'o 	trace_ext4_writeback_write_end(inode, pos, len, copied);
1747f8514083SAneesh Kumar K.V 	ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1748bfc1af65SNick Piggin 							page, fsdata);
1749f8a87d89SRoel Kluin 	copied = ret2;
1750ffacfa7aSJan Kara 	if (pos + len > inode->i_size && ext4_can_truncate(inode))
1751f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1752f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1753f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1754f8514083SAneesh Kumar K.V 		 */
1755f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1756f8514083SAneesh Kumar K.V 
1757f8a87d89SRoel Kluin 	if (ret2 < 0)
1758f8a87d89SRoel Kluin 		ret = ret2;
1759ac27a0ecSDave Kleikamp 
1760617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1761ac27a0ecSDave Kleikamp 	if (!ret)
1762ac27a0ecSDave Kleikamp 		ret = ret2;
1763bfc1af65SNick Piggin 
1764f8514083SAneesh Kumar K.V 	if (pos + len > inode->i_size) {
1765b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1766f8514083SAneesh Kumar K.V 		/*
1767ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1768f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1769f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1770f8514083SAneesh Kumar K.V 		 */
1771f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1772f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1773f8514083SAneesh Kumar K.V 	}
1774f8514083SAneesh Kumar K.V 
1775bfc1af65SNick Piggin 	return ret ? ret : copied;
1776ac27a0ecSDave Kleikamp }
1777ac27a0ecSDave Kleikamp 
1778bfc1af65SNick Piggin static int ext4_journalled_write_end(struct file *file,
1779bfc1af65SNick Piggin 				     struct address_space *mapping,
1780bfc1af65SNick Piggin 				     loff_t pos, unsigned len, unsigned copied,
1781bfc1af65SNick Piggin 				     struct page *page, void *fsdata)
1782ac27a0ecSDave Kleikamp {
1783617ba13bSMingming Cao 	handle_t *handle = ext4_journal_current_handle();
1784bfc1af65SNick Piggin 	struct inode *inode = mapping->host;
1785ac27a0ecSDave Kleikamp 	int ret = 0, ret2;
1786ac27a0ecSDave Kleikamp 	int partial = 0;
1787bfc1af65SNick Piggin 	unsigned from, to;
1788cf17fea6SAneesh Kumar K.V 	loff_t new_i_size;
1789ac27a0ecSDave Kleikamp 
17909bffad1eSTheodore Ts'o 	trace_ext4_journalled_write_end(inode, pos, len, copied);
1791bfc1af65SNick Piggin 	from = pos & (PAGE_CACHE_SIZE - 1);
1792bfc1af65SNick Piggin 	to = from + len;
1793bfc1af65SNick Piggin 
1794bfc1af65SNick Piggin 	if (copied < len) {
1795bfc1af65SNick Piggin 		if (!PageUptodate(page))
1796bfc1af65SNick Piggin 			copied = 0;
1797bfc1af65SNick Piggin 		page_zero_new_buffers(page, from+copied, to);
1798bfc1af65SNick Piggin 	}
1799ac27a0ecSDave Kleikamp 
1800ac27a0ecSDave Kleikamp 	ret = walk_page_buffers(handle, page_buffers(page), from,
1801bfc1af65SNick Piggin 				to, &partial, write_end_fn);
1802ac27a0ecSDave Kleikamp 	if (!partial)
1803ac27a0ecSDave Kleikamp 		SetPageUptodate(page);
1804cf17fea6SAneesh Kumar K.V 	new_i_size = pos + copied;
1805cf17fea6SAneesh Kumar K.V 	if (new_i_size > inode->i_size)
1806bfc1af65SNick Piggin 		i_size_write(inode, pos+copied);
180719f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1808cf17fea6SAneesh Kumar K.V 	if (new_i_size > EXT4_I(inode)->i_disksize) {
1809cf17fea6SAneesh Kumar K.V 		ext4_update_i_disksize(inode, new_i_size);
1810617ba13bSMingming Cao 		ret2 = ext4_mark_inode_dirty(handle, inode);
1811ac27a0ecSDave Kleikamp 		if (!ret)
1812ac27a0ecSDave Kleikamp 			ret = ret2;
1813ac27a0ecSDave Kleikamp 	}
1814bfc1af65SNick Piggin 
1815cf108bcaSJan Kara 	unlock_page(page);
1816f8514083SAneesh Kumar K.V 	page_cache_release(page);
1817ffacfa7aSJan Kara 	if (pos + len > inode->i_size && ext4_can_truncate(inode))
1818f8514083SAneesh Kumar K.V 		/* if we have allocated more blocks and copied
1819f8514083SAneesh Kumar K.V 		 * less. We will have blocks allocated outside
1820f8514083SAneesh Kumar K.V 		 * inode->i_size. So truncate them
1821f8514083SAneesh Kumar K.V 		 */
1822f8514083SAneesh Kumar K.V 		ext4_orphan_add(handle, inode);
1823f8514083SAneesh Kumar K.V 
1824617ba13bSMingming Cao 	ret2 = ext4_journal_stop(handle);
1825ac27a0ecSDave Kleikamp 	if (!ret)
1826ac27a0ecSDave Kleikamp 		ret = ret2;
1827f8514083SAneesh Kumar K.V 	if (pos + len > inode->i_size) {
1828b9a4207dSJan Kara 		ext4_truncate_failed_write(inode);
1829f8514083SAneesh Kumar K.V 		/*
1830ffacfa7aSJan Kara 		 * If truncate failed early the inode might still be
1831f8514083SAneesh Kumar K.V 		 * on the orphan list; we need to make sure the inode
1832f8514083SAneesh Kumar K.V 		 * is removed from the orphan list in that case.
1833f8514083SAneesh Kumar K.V 		 */
1834f8514083SAneesh Kumar K.V 		if (inode->i_nlink)
1835f8514083SAneesh Kumar K.V 			ext4_orphan_del(NULL, inode);
1836f8514083SAneesh Kumar K.V 	}
1837bfc1af65SNick Piggin 
1838bfc1af65SNick Piggin 	return ret ? ret : copied;
1839ac27a0ecSDave Kleikamp }
1840d2a17637SMingming Cao 
18419d0be502STheodore Ts'o /*
18429d0be502STheodore Ts'o  * Reserve a single block located at lblock
18439d0be502STheodore Ts'o  */
18449d0be502STheodore Ts'o static int ext4_da_reserve_space(struct inode *inode, sector_t lblock)
1845d2a17637SMingming Cao {
1846030ba6bcSAneesh Kumar K.V 	int retries = 0;
1847d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
18480637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
184972b8ab9dSEric Sandeen 	unsigned long md_needed;
18505dd4056dSChristoph Hellwig 	int ret;
1851d2a17637SMingming Cao 
1852d2a17637SMingming Cao 	/*
1853d2a17637SMingming Cao 	 * recalculate the amount of metadata blocks to reserve
1854d2a17637SMingming Cao 	 * in order to allocate nrblocks
1855d2a17637SMingming Cao 	 * worse case is one extent per block
1856d2a17637SMingming Cao 	 */
1857030ba6bcSAneesh Kumar K.V repeat:
18580637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
18599d0be502STheodore Ts'o 	md_needed = ext4_calc_metadata_amount(inode, lblock);
1860f8ec9d68STheodore Ts'o 	trace_ext4_da_reserve_space(inode, md_needed);
18610637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
1862d2a17637SMingming Cao 
186360e58e0fSMingming Cao 	/*
186472b8ab9dSEric Sandeen 	 * We will charge metadata quota at writeout time; this saves
186572b8ab9dSEric Sandeen 	 * us from metadata over-estimation, though we may go over by
186672b8ab9dSEric Sandeen 	 * a small amount in the end.  Here we just reserve for data.
186760e58e0fSMingming Cao 	 */
186872b8ab9dSEric Sandeen 	ret = dquot_reserve_block(inode, 1);
18695dd4056dSChristoph Hellwig 	if (ret)
18705dd4056dSChristoph Hellwig 		return ret;
187172b8ab9dSEric Sandeen 	/*
187272b8ab9dSEric Sandeen 	 * We do still charge estimated metadata to the sb though;
187372b8ab9dSEric Sandeen 	 * we cannot afford to run out of free blocks.
187472b8ab9dSEric Sandeen 	 */
18759d0be502STheodore Ts'o 	if (ext4_claim_free_blocks(sbi, md_needed + 1)) {
187672b8ab9dSEric Sandeen 		dquot_release_reservation_block(inode, 1);
1877030ba6bcSAneesh Kumar K.V 		if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1878030ba6bcSAneesh Kumar K.V 			yield();
1879030ba6bcSAneesh Kumar K.V 			goto repeat;
1880030ba6bcSAneesh Kumar K.V 		}
1881d2a17637SMingming Cao 		return -ENOSPC;
1882d2a17637SMingming Cao 	}
18830637c6f4STheodore Ts'o 	spin_lock(&ei->i_block_reservation_lock);
18849d0be502STheodore Ts'o 	ei->i_reserved_data_blocks++;
18850637c6f4STheodore Ts'o 	ei->i_reserved_meta_blocks += md_needed;
18860637c6f4STheodore Ts'o 	spin_unlock(&ei->i_block_reservation_lock);
188739bc680aSDmitry Monakhov 
1888d2a17637SMingming Cao 	return 0;       /* success */
1889d2a17637SMingming Cao }
1890d2a17637SMingming Cao 
189112219aeaSAneesh Kumar K.V static void ext4_da_release_space(struct inode *inode, int to_free)
1892d2a17637SMingming Cao {
1893d2a17637SMingming Cao 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
18940637c6f4STheodore Ts'o 	struct ext4_inode_info *ei = EXT4_I(inode);
1895d2a17637SMingming Cao 
1896cd213226SMingming Cao 	if (!to_free)
1897cd213226SMingming Cao 		return;		/* Nothing to release, exit */
1898cd213226SMingming Cao 
1899d2a17637SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1900cd213226SMingming Cao 
19015a58ec87SLi Zefan 	trace_ext4_da_release_space(inode, to_free);
19020637c6f4STheodore Ts'o 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1903cd213226SMingming Cao 		/*
19040637c6f4STheodore Ts'o 		 * if there aren't enough reserved blocks, then the
19050637c6f4STheodore Ts'o 		 * counter is messed up somewhere.  Since this
19060637c6f4STheodore Ts'o 		 * function is called from invalidate page, it's
19070637c6f4STheodore Ts'o 		 * harmless to return without any action.
1908cd213226SMingming Cao 		 */
19090637c6f4STheodore Ts'o 		ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
19100637c6f4STheodore Ts'o 			 "ino %lu, to_free %d with only %d reserved "
19110637c6f4STheodore Ts'o 			 "data blocks\n", inode->i_ino, to_free,
19120637c6f4STheodore Ts'o 			 ei->i_reserved_data_blocks);
19130637c6f4STheodore Ts'o 		WARN_ON(1);
19140637c6f4STheodore Ts'o 		to_free = ei->i_reserved_data_blocks;
19150637c6f4STheodore Ts'o 	}
19160637c6f4STheodore Ts'o 	ei->i_reserved_data_blocks -= to_free;
19170637c6f4STheodore Ts'o 
19180637c6f4STheodore Ts'o 	if (ei->i_reserved_data_blocks == 0) {
19190637c6f4STheodore Ts'o 		/*
19200637c6f4STheodore Ts'o 		 * We can release all of the reserved metadata blocks
19210637c6f4STheodore Ts'o 		 * only when we have written all of the delayed
19220637c6f4STheodore Ts'o 		 * allocation blocks.
19230637c6f4STheodore Ts'o 		 */
192472b8ab9dSEric Sandeen 		percpu_counter_sub(&sbi->s_dirtyblocks_counter,
192572b8ab9dSEric Sandeen 				   ei->i_reserved_meta_blocks);
1926ee5f4d9cSTheodore Ts'o 		ei->i_reserved_meta_blocks = 0;
19279d0be502STheodore Ts'o 		ei->i_da_metadata_calc_len = 0;
1928cd213226SMingming Cao 	}
1929cd213226SMingming Cao 
193072b8ab9dSEric Sandeen 	/* update fs dirty data blocks counter */
19310637c6f4STheodore Ts'o 	percpu_counter_sub(&sbi->s_dirtyblocks_counter, to_free);
1932d2a17637SMingming Cao 
1933d2a17637SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
193460e58e0fSMingming Cao 
19355dd4056dSChristoph Hellwig 	dquot_release_reservation_block(inode, to_free);
1936d2a17637SMingming Cao }
1937d2a17637SMingming Cao 
1938d2a17637SMingming Cao static void ext4_da_page_release_reservation(struct page *page,
1939d2a17637SMingming Cao 					     unsigned long offset)
1940d2a17637SMingming Cao {
1941d2a17637SMingming Cao 	int to_release = 0;
1942d2a17637SMingming Cao 	struct buffer_head *head, *bh;
1943d2a17637SMingming Cao 	unsigned int curr_off = 0;
1944d2a17637SMingming Cao 
1945d2a17637SMingming Cao 	head = page_buffers(page);
1946d2a17637SMingming Cao 	bh = head;
1947d2a17637SMingming Cao 	do {
1948d2a17637SMingming Cao 		unsigned int next_off = curr_off + bh->b_size;
1949d2a17637SMingming Cao 
1950d2a17637SMingming Cao 		if ((offset <= curr_off) && (buffer_delay(bh))) {
1951d2a17637SMingming Cao 			to_release++;
1952d2a17637SMingming Cao 			clear_buffer_delay(bh);
1953d2a17637SMingming Cao 		}
1954d2a17637SMingming Cao 		curr_off = next_off;
1955d2a17637SMingming Cao 	} while ((bh = bh->b_this_page) != head);
195612219aeaSAneesh Kumar K.V 	ext4_da_release_space(page->mapping->host, to_release);
1957d2a17637SMingming Cao }
1958ac27a0ecSDave Kleikamp 
1959ac27a0ecSDave Kleikamp /*
196064769240SAlex Tomas  * Delayed allocation stuff
196164769240SAlex Tomas  */
196264769240SAlex Tomas 
196364769240SAlex Tomas /*
196464769240SAlex Tomas  * mpage_da_submit_io - walks through extent of pages and try to write
1965a1d6cc56SAneesh Kumar K.V  * them with writepage() call back
196664769240SAlex Tomas  *
196764769240SAlex Tomas  * @mpd->inode: inode
196864769240SAlex Tomas  * @mpd->first_page: first page of the extent
196964769240SAlex Tomas  * @mpd->next_page: page after the last page of the extent
197064769240SAlex Tomas  *
197164769240SAlex Tomas  * By the time mpage_da_submit_io() is called we expect all blocks
197264769240SAlex Tomas  * to be allocated. this may be wrong if allocation failed.
197364769240SAlex Tomas  *
197464769240SAlex Tomas  * As pages are already locked by write_cache_pages(), we can't use it
197564769240SAlex Tomas  */
197664769240SAlex Tomas static int mpage_da_submit_io(struct mpage_da_data *mpd)
197764769240SAlex Tomas {
197822208dedSAneesh Kumar K.V 	long pages_skipped;
1979791b7f08SAneesh Kumar K.V 	struct pagevec pvec;
1980791b7f08SAneesh Kumar K.V 	unsigned long index, end;
1981791b7f08SAneesh Kumar K.V 	int ret = 0, err, nr_pages, i;
1982791b7f08SAneesh Kumar K.V 	struct inode *inode = mpd->inode;
1983791b7f08SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
198464769240SAlex Tomas 
198564769240SAlex Tomas 	BUG_ON(mpd->next_page <= mpd->first_page);
1986791b7f08SAneesh Kumar K.V 	/*
1987791b7f08SAneesh Kumar K.V 	 * We need to start from the first_page to the next_page - 1
1988791b7f08SAneesh Kumar K.V 	 * to make sure we also write the mapped dirty buffer_heads.
19898dc207c0STheodore Ts'o 	 * If we look at mpd->b_blocknr we would only be looking
1990791b7f08SAneesh Kumar K.V 	 * at the currently mapped buffer_heads.
1991791b7f08SAneesh Kumar K.V 	 */
199264769240SAlex Tomas 	index = mpd->first_page;
199364769240SAlex Tomas 	end = mpd->next_page - 1;
199464769240SAlex Tomas 
1995791b7f08SAneesh Kumar K.V 	pagevec_init(&pvec, 0);
199664769240SAlex Tomas 	while (index <= end) {
1997791b7f08SAneesh Kumar K.V 		nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
199864769240SAlex Tomas 		if (nr_pages == 0)
199964769240SAlex Tomas 			break;
200064769240SAlex Tomas 		for (i = 0; i < nr_pages; i++) {
200164769240SAlex Tomas 			struct page *page = pvec.pages[i];
200264769240SAlex Tomas 
2003791b7f08SAneesh Kumar K.V 			index = page->index;
2004791b7f08SAneesh Kumar K.V 			if (index > end)
2005791b7f08SAneesh Kumar K.V 				break;
2006791b7f08SAneesh Kumar K.V 			index++;
2007791b7f08SAneesh Kumar K.V 
2008791b7f08SAneesh Kumar K.V 			BUG_ON(!PageLocked(page));
2009791b7f08SAneesh Kumar K.V 			BUG_ON(PageWriteback(page));
2010791b7f08SAneesh Kumar K.V 
201122208dedSAneesh Kumar K.V 			pages_skipped = mpd->wbc->pages_skipped;
2012a1d6cc56SAneesh Kumar K.V 			err = mapping->a_ops->writepage(page, mpd->wbc);
201322208dedSAneesh Kumar K.V 			if (!err && (pages_skipped == mpd->wbc->pages_skipped))
201422208dedSAneesh Kumar K.V 				/*
201522208dedSAneesh Kumar K.V 				 * have successfully written the page
201622208dedSAneesh Kumar K.V 				 * without skipping the same
201722208dedSAneesh Kumar K.V 				 */
2018a1d6cc56SAneesh Kumar K.V 				mpd->pages_written++;
201964769240SAlex Tomas 			/*
202064769240SAlex Tomas 			 * In error case, we have to continue because
202164769240SAlex Tomas 			 * remaining pages are still locked
202264769240SAlex Tomas 			 * XXX: unlock and re-dirty them?
202364769240SAlex Tomas 			 */
202464769240SAlex Tomas 			if (ret == 0)
202564769240SAlex Tomas 				ret = err;
202664769240SAlex Tomas 		}
202764769240SAlex Tomas 		pagevec_release(&pvec);
202864769240SAlex Tomas 	}
202964769240SAlex Tomas 	return ret;
203064769240SAlex Tomas }
203164769240SAlex Tomas 
203264769240SAlex Tomas /*
203364769240SAlex Tomas  * mpage_put_bnr_to_bhs - walk blocks and assign them actual numbers
203464769240SAlex Tomas  *
203564769240SAlex Tomas  * the function goes through all passed space and put actual disk
203629fa89d0SAneesh Kumar K.V  * block numbers into buffer heads, dropping BH_Delay and BH_Unwritten
203764769240SAlex Tomas  */
20382ed88685STheodore Ts'o static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd,
20392ed88685STheodore Ts'o 				 struct ext4_map_blocks *map)
204064769240SAlex Tomas {
204164769240SAlex Tomas 	struct inode *inode = mpd->inode;
204264769240SAlex Tomas 	struct address_space *mapping = inode->i_mapping;
20432ed88685STheodore Ts'o 	int blocks = map->m_len;
20442ed88685STheodore Ts'o 	sector_t pblock = map->m_pblk, cur_logical;
204564769240SAlex Tomas 	struct buffer_head *head, *bh;
2046a1d6cc56SAneesh Kumar K.V 	pgoff_t index, end;
204764769240SAlex Tomas 	struct pagevec pvec;
204864769240SAlex Tomas 	int nr_pages, i;
204964769240SAlex Tomas 
20502ed88685STheodore Ts'o 	index = map->m_lblk >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
20512ed88685STheodore Ts'o 	end = (map->m_lblk + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
205264769240SAlex Tomas 	cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
205364769240SAlex Tomas 
205464769240SAlex Tomas 	pagevec_init(&pvec, 0);
205564769240SAlex Tomas 
205664769240SAlex Tomas 	while (index <= end) {
205764769240SAlex Tomas 		/* XXX: optimize tail */
205864769240SAlex Tomas 		nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
205964769240SAlex Tomas 		if (nr_pages == 0)
206064769240SAlex Tomas 			break;
206164769240SAlex Tomas 		for (i = 0; i < nr_pages; i++) {
206264769240SAlex Tomas 			struct page *page = pvec.pages[i];
206364769240SAlex Tomas 
206464769240SAlex Tomas 			index = page->index;
206564769240SAlex Tomas 			if (index > end)
206664769240SAlex Tomas 				break;
206764769240SAlex Tomas 			index++;
206864769240SAlex Tomas 
206964769240SAlex Tomas 			BUG_ON(!PageLocked(page));
207064769240SAlex Tomas 			BUG_ON(PageWriteback(page));
207164769240SAlex Tomas 			BUG_ON(!page_has_buffers(page));
207264769240SAlex Tomas 
207364769240SAlex Tomas 			bh = page_buffers(page);
207464769240SAlex Tomas 			head = bh;
207564769240SAlex Tomas 
207664769240SAlex Tomas 			/* skip blocks out of the range */
207764769240SAlex Tomas 			do {
20782ed88685STheodore Ts'o 				if (cur_logical >= map->m_lblk)
207964769240SAlex Tomas 					break;
208064769240SAlex Tomas 				cur_logical++;
208164769240SAlex Tomas 			} while ((bh = bh->b_this_page) != head);
208264769240SAlex Tomas 
208364769240SAlex Tomas 			do {
20842ed88685STheodore Ts'o 				if (cur_logical >= map->m_lblk + blocks)
208564769240SAlex Tomas 					break;
208629fa89d0SAneesh Kumar K.V 
20872ed88685STheodore Ts'o 				if (buffer_delay(bh) || buffer_unwritten(bh)) {
208829fa89d0SAneesh Kumar K.V 
208929fa89d0SAneesh Kumar K.V 					BUG_ON(bh->b_bdev != inode->i_sb->s_bdev);
209029fa89d0SAneesh Kumar K.V 
209164769240SAlex Tomas 					if (buffer_delay(bh)) {
209264769240SAlex Tomas 						clear_buffer_delay(bh);
2093bf068ee2SAneesh Kumar K.V 						bh->b_blocknr = pblock;
209429fa89d0SAneesh Kumar K.V 					} else {
209529fa89d0SAneesh Kumar K.V 						/*
209629fa89d0SAneesh Kumar K.V 						 * unwritten already should have
209729fa89d0SAneesh Kumar K.V 						 * blocknr assigned. Verify that
209829fa89d0SAneesh Kumar K.V 						 */
2099bf068ee2SAneesh Kumar K.V 						clear_buffer_unwritten(bh);
210029fa89d0SAneesh Kumar K.V 						BUG_ON(bh->b_blocknr != pblock);
210129fa89d0SAneesh Kumar K.V 					}
210229fa89d0SAneesh Kumar K.V 
210361628a3fSMingming Cao 				} else if (buffer_mapped(bh))
210464769240SAlex Tomas 					BUG_ON(bh->b_blocknr != pblock);
210564769240SAlex Tomas 
21062ed88685STheodore Ts'o 				if (map->m_flags & EXT4_MAP_UNINIT)
2107744692dcSJiaying Zhang 					set_buffer_uninit(bh);
210864769240SAlex Tomas 				cur_logical++;
210964769240SAlex Tomas 				pblock++;
211064769240SAlex Tomas 			} while ((bh = bh->b_this_page) != head);
211164769240SAlex Tomas 		}
211264769240SAlex Tomas 		pagevec_release(&pvec);
211364769240SAlex Tomas 	}
211464769240SAlex Tomas }
211564769240SAlex Tomas 
211664769240SAlex Tomas 
2117c4a0c46eSAneesh Kumar K.V static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd,
2118c4a0c46eSAneesh Kumar K.V 					sector_t logical, long blk_cnt)
2119c4a0c46eSAneesh Kumar K.V {
2120c4a0c46eSAneesh Kumar K.V 	int nr_pages, i;
2121c4a0c46eSAneesh Kumar K.V 	pgoff_t index, end;
2122c4a0c46eSAneesh Kumar K.V 	struct pagevec pvec;
2123c4a0c46eSAneesh Kumar K.V 	struct inode *inode = mpd->inode;
2124c4a0c46eSAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
2125c4a0c46eSAneesh Kumar K.V 
2126c4a0c46eSAneesh Kumar K.V 	index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
2127c4a0c46eSAneesh Kumar K.V 	end   = (logical + blk_cnt - 1) >>
2128c4a0c46eSAneesh Kumar K.V 				(PAGE_CACHE_SHIFT - inode->i_blkbits);
2129c4a0c46eSAneesh Kumar K.V 	while (index <= end) {
2130c4a0c46eSAneesh Kumar K.V 		nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2131c4a0c46eSAneesh Kumar K.V 		if (nr_pages == 0)
2132c4a0c46eSAneesh Kumar K.V 			break;
2133c4a0c46eSAneesh Kumar K.V 		for (i = 0; i < nr_pages; i++) {
2134c4a0c46eSAneesh Kumar K.V 			struct page *page = pvec.pages[i];
21359b1d0998SJan Kara 			if (page->index > end)
2136c4a0c46eSAneesh Kumar K.V 				break;
2137c4a0c46eSAneesh Kumar K.V 			BUG_ON(!PageLocked(page));
2138c4a0c46eSAneesh Kumar K.V 			BUG_ON(PageWriteback(page));
2139c4a0c46eSAneesh Kumar K.V 			block_invalidatepage(page, 0);
2140c4a0c46eSAneesh Kumar K.V 			ClearPageUptodate(page);
2141c4a0c46eSAneesh Kumar K.V 			unlock_page(page);
2142c4a0c46eSAneesh Kumar K.V 		}
21439b1d0998SJan Kara 		index = pvec.pages[nr_pages - 1]->index + 1;
21449b1d0998SJan Kara 		pagevec_release(&pvec);
2145c4a0c46eSAneesh Kumar K.V 	}
2146c4a0c46eSAneesh Kumar K.V 	return;
2147c4a0c46eSAneesh Kumar K.V }
2148c4a0c46eSAneesh Kumar K.V 
2149df22291fSAneesh Kumar K.V static void ext4_print_free_blocks(struct inode *inode)
2150df22291fSAneesh Kumar K.V {
2151df22291fSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
21521693918eSTheodore Ts'o 	printk(KERN_CRIT "Total free blocks count %lld\n",
2153df22291fSAneesh Kumar K.V 	       ext4_count_free_blocks(inode->i_sb));
21541693918eSTheodore Ts'o 	printk(KERN_CRIT "Free/Dirty block details\n");
21551693918eSTheodore Ts'o 	printk(KERN_CRIT "free_blocks=%lld\n",
21568f72fbdfSAlexander Beregalov 	       (long long) percpu_counter_sum(&sbi->s_freeblocks_counter));
21571693918eSTheodore Ts'o 	printk(KERN_CRIT "dirty_blocks=%lld\n",
21588f72fbdfSAlexander Beregalov 	       (long long) percpu_counter_sum(&sbi->s_dirtyblocks_counter));
21591693918eSTheodore Ts'o 	printk(KERN_CRIT "Block reservation details\n");
21601693918eSTheodore Ts'o 	printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
2161df22291fSAneesh Kumar K.V 	       EXT4_I(inode)->i_reserved_data_blocks);
21621693918eSTheodore Ts'o 	printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
2163df22291fSAneesh Kumar K.V 	       EXT4_I(inode)->i_reserved_meta_blocks);
2164df22291fSAneesh Kumar K.V 	return;
2165df22291fSAneesh Kumar K.V }
2166df22291fSAneesh Kumar K.V 
2167b920c755STheodore Ts'o /*
216864769240SAlex Tomas  * mpage_da_map_blocks - go through given space
216964769240SAlex Tomas  *
21708dc207c0STheodore Ts'o  * @mpd - bh describing space
217164769240SAlex Tomas  *
217264769240SAlex Tomas  * The function skips space we know is already mapped to disk blocks.
217364769240SAlex Tomas  *
217464769240SAlex Tomas  */
2175c4a0c46eSAneesh Kumar K.V static int mpage_da_map_blocks(struct mpage_da_data *mpd)
217664769240SAlex Tomas {
21772ac3b6e0STheodore Ts'o 	int err, blks, get_blocks_flags;
21782ed88685STheodore Ts'o 	struct ext4_map_blocks map;
21792fa3cdfbSTheodore Ts'o 	sector_t next = mpd->b_blocknr;
21802fa3cdfbSTheodore Ts'o 	unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
21812fa3cdfbSTheodore Ts'o 	loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
21822fa3cdfbSTheodore Ts'o 	handle_t *handle = NULL;
218364769240SAlex Tomas 
218464769240SAlex Tomas 	/*
218564769240SAlex Tomas 	 * We consider only non-mapped and non-allocated blocks
218664769240SAlex Tomas 	 */
21878dc207c0STheodore Ts'o 	if ((mpd->b_state  & (1 << BH_Mapped)) &&
218829fa89d0SAneesh Kumar K.V 		!(mpd->b_state & (1 << BH_Delay)) &&
218929fa89d0SAneesh Kumar K.V 		!(mpd->b_state & (1 << BH_Unwritten)))
2190c4a0c46eSAneesh Kumar K.V 		return 0;
21912fa3cdfbSTheodore Ts'o 
21922fa3cdfbSTheodore Ts'o 	/*
21932fa3cdfbSTheodore Ts'o 	 * If we didn't accumulate anything to write simply return
21942fa3cdfbSTheodore Ts'o 	 */
21952fa3cdfbSTheodore Ts'o 	if (!mpd->b_size)
21962fa3cdfbSTheodore Ts'o 		return 0;
21972fa3cdfbSTheodore Ts'o 
21982fa3cdfbSTheodore Ts'o 	handle = ext4_journal_current_handle();
21992fa3cdfbSTheodore Ts'o 	BUG_ON(!handle);
22002fa3cdfbSTheodore Ts'o 
220179ffab34SAneesh Kumar K.V 	/*
22022ac3b6e0STheodore Ts'o 	 * Call ext4_get_blocks() to allocate any delayed allocation
22032ac3b6e0STheodore Ts'o 	 * blocks, or to convert an uninitialized extent to be
22042ac3b6e0STheodore Ts'o 	 * initialized (in the case where we have written into
22052ac3b6e0STheodore Ts'o 	 * one or more preallocated blocks).
22062ac3b6e0STheodore Ts'o 	 *
22072ac3b6e0STheodore Ts'o 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
22082ac3b6e0STheodore Ts'o 	 * indicate that we are on the delayed allocation path.  This
22092ac3b6e0STheodore Ts'o 	 * affects functions in many different parts of the allocation
22102ac3b6e0STheodore Ts'o 	 * call path.  This flag exists primarily because we don't
22112ac3b6e0STheodore Ts'o 	 * want to change *many* call functions, so ext4_get_blocks()
22122ac3b6e0STheodore Ts'o 	 * will set the magic i_delalloc_reserved_flag once the
22132ac3b6e0STheodore Ts'o 	 * inode's allocation semaphore is taken.
22142ac3b6e0STheodore Ts'o 	 *
22152ac3b6e0STheodore Ts'o 	 * If the blocks in questions were delalloc blocks, set
22162ac3b6e0STheodore Ts'o 	 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
22172ac3b6e0STheodore Ts'o 	 * variables are updated after the blocks have been allocated.
221879ffab34SAneesh Kumar K.V 	 */
22192ed88685STheodore Ts'o 	map.m_lblk = next;
22202ed88685STheodore Ts'o 	map.m_len = max_blocks;
22211296cc85SAneesh Kumar K.V 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
2222744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(mpd->inode))
2223744692dcSJiaying Zhang 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
22242ac3b6e0STheodore Ts'o 	if (mpd->b_state & (1 << BH_Delay))
22251296cc85SAneesh Kumar K.V 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
22261296cc85SAneesh Kumar K.V 
22272ed88685STheodore Ts'o 	blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
22282fa3cdfbSTheodore Ts'o 	if (blks < 0) {
22292fa3cdfbSTheodore Ts'o 		err = blks;
2230ed5bde0bSTheodore Ts'o 		/*
2231ed5bde0bSTheodore Ts'o 		 * If get block returns with error we simply
2232ed5bde0bSTheodore Ts'o 		 * return. Later writepage will redirty the page and
2233ed5bde0bSTheodore Ts'o 		 * writepages will find the dirty page again
2234c4a0c46eSAneesh Kumar K.V 		 */
2235c4a0c46eSAneesh Kumar K.V 		if (err == -EAGAIN)
2236c4a0c46eSAneesh Kumar K.V 			return 0;
2237df22291fSAneesh Kumar K.V 
2238df22291fSAneesh Kumar K.V 		if (err == -ENOSPC &&
2239df22291fSAneesh Kumar K.V 		    ext4_count_free_blocks(mpd->inode->i_sb)) {
2240df22291fSAneesh Kumar K.V 			mpd->retval = err;
2241df22291fSAneesh Kumar K.V 			return 0;
2242df22291fSAneesh Kumar K.V 		}
2243df22291fSAneesh Kumar K.V 
2244c4a0c46eSAneesh Kumar K.V 		/*
2245ed5bde0bSTheodore Ts'o 		 * get block failure will cause us to loop in
2246ed5bde0bSTheodore Ts'o 		 * writepages, because a_ops->writepage won't be able
2247ed5bde0bSTheodore Ts'o 		 * to make progress. The page will be redirtied by
2248ed5bde0bSTheodore Ts'o 		 * writepage and writepages will again try to write
2249ed5bde0bSTheodore Ts'o 		 * the same.
2250c4a0c46eSAneesh Kumar K.V 		 */
22511693918eSTheodore Ts'o 		ext4_msg(mpd->inode->i_sb, KERN_CRIT,
22521693918eSTheodore Ts'o 			 "delayed block allocation failed for inode %lu at "
22531693918eSTheodore Ts'o 			 "logical offset %llu with max blocks %zd with "
2254fbe845ddSCurt Wohlgemuth 			 "error %d", mpd->inode->i_ino,
2255c4a0c46eSAneesh Kumar K.V 			 (unsigned long long) next,
22568dc207c0STheodore Ts'o 			 mpd->b_size >> mpd->inode->i_blkbits, err);
22571693918eSTheodore Ts'o 		printk(KERN_CRIT "This should not happen!!  "
2258c4a0c46eSAneesh Kumar K.V 		       "Data will be lost\n");
2259030ba6bcSAneesh Kumar K.V 		if (err == -ENOSPC) {
2260df22291fSAneesh Kumar K.V 			ext4_print_free_blocks(mpd->inode);
2261030ba6bcSAneesh Kumar K.V 		}
22622fa3cdfbSTheodore Ts'o 		/* invalidate all the pages */
2263c4a0c46eSAneesh Kumar K.V 		ext4_da_block_invalidatepages(mpd, next,
22648dc207c0STheodore Ts'o 				mpd->b_size >> mpd->inode->i_blkbits);
2265c4a0c46eSAneesh Kumar K.V 		return err;
2266c4a0c46eSAneesh Kumar K.V 	}
22672fa3cdfbSTheodore Ts'o 	BUG_ON(blks == 0);
22682fa3cdfbSTheodore Ts'o 
22692ed88685STheodore Ts'o 	if (map.m_flags & EXT4_MAP_NEW) {
22702ed88685STheodore Ts'o 		struct block_device *bdev = mpd->inode->i_sb->s_bdev;
22712ed88685STheodore Ts'o 		int i;
227264769240SAlex Tomas 
22732ed88685STheodore Ts'o 		for (i = 0; i < map.m_len; i++)
22742ed88685STheodore Ts'o 			unmap_underlying_metadata(bdev, map.m_pblk + i);
22752ed88685STheodore Ts'o 	}
227664769240SAlex Tomas 
227764769240SAlex Tomas 	/*
227864769240SAlex Tomas 	 * If blocks are delayed marked, we need to
227964769240SAlex Tomas 	 * put actual blocknr and drop delayed bit
228064769240SAlex Tomas 	 */
22818dc207c0STheodore Ts'o 	if ((mpd->b_state & (1 << BH_Delay)) ||
22828dc207c0STheodore Ts'o 	    (mpd->b_state & (1 << BH_Unwritten)))
22832ed88685STheodore Ts'o 		mpage_put_bnr_to_bhs(mpd, &map);
228464769240SAlex Tomas 
22852fa3cdfbSTheodore Ts'o 	if (ext4_should_order_data(mpd->inode)) {
22862fa3cdfbSTheodore Ts'o 		err = ext4_jbd2_file_inode(handle, mpd->inode);
22872fa3cdfbSTheodore Ts'o 		if (err)
22882fa3cdfbSTheodore Ts'o 			return err;
22892fa3cdfbSTheodore Ts'o 	}
22902fa3cdfbSTheodore Ts'o 
22912fa3cdfbSTheodore Ts'o 	/*
229203f5d8bcSJan Kara 	 * Update on-disk size along with block allocation.
22932fa3cdfbSTheodore Ts'o 	 */
22942fa3cdfbSTheodore Ts'o 	disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
22952fa3cdfbSTheodore Ts'o 	if (disksize > i_size_read(mpd->inode))
22962fa3cdfbSTheodore Ts'o 		disksize = i_size_read(mpd->inode);
22972fa3cdfbSTheodore Ts'o 	if (disksize > EXT4_I(mpd->inode)->i_disksize) {
22982fa3cdfbSTheodore Ts'o 		ext4_update_i_disksize(mpd->inode, disksize);
22992fa3cdfbSTheodore Ts'o 		return ext4_mark_inode_dirty(handle, mpd->inode);
23002fa3cdfbSTheodore Ts'o 	}
23012fa3cdfbSTheodore Ts'o 
2302c4a0c46eSAneesh Kumar K.V 	return 0;
230364769240SAlex Tomas }
230464769240SAlex Tomas 
2305bf068ee2SAneesh Kumar K.V #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
2306bf068ee2SAneesh Kumar K.V 		(1 << BH_Delay) | (1 << BH_Unwritten))
230764769240SAlex Tomas 
230864769240SAlex Tomas /*
230964769240SAlex Tomas  * mpage_add_bh_to_extent - try to add one more block to extent of blocks
231064769240SAlex Tomas  *
231164769240SAlex Tomas  * @mpd->lbh - extent of blocks
231264769240SAlex Tomas  * @logical - logical number of the block in the file
231364769240SAlex Tomas  * @bh - bh of the block (used to access block's state)
231464769240SAlex Tomas  *
231564769240SAlex Tomas  * the function is used to collect contig. blocks in same state
231664769240SAlex Tomas  */
231764769240SAlex Tomas static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
23188dc207c0STheodore Ts'o 				   sector_t logical, size_t b_size,
23198dc207c0STheodore Ts'o 				   unsigned long b_state)
232064769240SAlex Tomas {
232164769240SAlex Tomas 	sector_t next;
23228dc207c0STheodore Ts'o 	int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
232364769240SAlex Tomas 
2324c445e3e0SEric Sandeen 	/*
2325c445e3e0SEric Sandeen 	 * XXX Don't go larger than mballoc is willing to allocate
2326c445e3e0SEric Sandeen 	 * This is a stopgap solution.  We eventually need to fold
2327c445e3e0SEric Sandeen 	 * mpage_da_submit_io() into this function and then call
2328c445e3e0SEric Sandeen 	 * ext4_get_blocks() multiple times in a loop
2329c445e3e0SEric Sandeen 	 */
2330c445e3e0SEric Sandeen 	if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
2331c445e3e0SEric Sandeen 		goto flush_it;
2332c445e3e0SEric Sandeen 
2333525f4ed8SMingming Cao 	/* check if thereserved journal credits might overflow */
233412e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
2335525f4ed8SMingming Cao 		if (nrblocks >= EXT4_MAX_TRANS_DATA) {
2336525f4ed8SMingming Cao 			/*
2337525f4ed8SMingming Cao 			 * With non-extent format we are limited by the journal
2338525f4ed8SMingming Cao 			 * credit available.  Total credit needed to insert
2339525f4ed8SMingming Cao 			 * nrblocks contiguous blocks is dependent on the
2340525f4ed8SMingming Cao 			 * nrblocks.  So limit nrblocks.
2341525f4ed8SMingming Cao 			 */
2342525f4ed8SMingming Cao 			goto flush_it;
2343525f4ed8SMingming Cao 		} else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
2344525f4ed8SMingming Cao 				EXT4_MAX_TRANS_DATA) {
2345525f4ed8SMingming Cao 			/*
2346525f4ed8SMingming Cao 			 * Adding the new buffer_head would make it cross the
2347525f4ed8SMingming Cao 			 * allowed limit for which we have journal credit
2348525f4ed8SMingming Cao 			 * reserved. So limit the new bh->b_size
2349525f4ed8SMingming Cao 			 */
2350525f4ed8SMingming Cao 			b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
2351525f4ed8SMingming Cao 						mpd->inode->i_blkbits;
2352525f4ed8SMingming Cao 			/* we will do mpage_da_submit_io in the next loop */
2353525f4ed8SMingming Cao 		}
2354525f4ed8SMingming Cao 	}
235564769240SAlex Tomas 	/*
235664769240SAlex Tomas 	 * First block in the extent
235764769240SAlex Tomas 	 */
23588dc207c0STheodore Ts'o 	if (mpd->b_size == 0) {
23598dc207c0STheodore Ts'o 		mpd->b_blocknr = logical;
23608dc207c0STheodore Ts'o 		mpd->b_size = b_size;
23618dc207c0STheodore Ts'o 		mpd->b_state = b_state & BH_FLAGS;
236264769240SAlex Tomas 		return;
236364769240SAlex Tomas 	}
236464769240SAlex Tomas 
23658dc207c0STheodore Ts'o 	next = mpd->b_blocknr + nrblocks;
236664769240SAlex Tomas 	/*
236764769240SAlex Tomas 	 * Can we merge the block to our big extent?
236864769240SAlex Tomas 	 */
23698dc207c0STheodore Ts'o 	if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
23708dc207c0STheodore Ts'o 		mpd->b_size += b_size;
237164769240SAlex Tomas 		return;
237264769240SAlex Tomas 	}
237364769240SAlex Tomas 
2374525f4ed8SMingming Cao flush_it:
237564769240SAlex Tomas 	/*
237664769240SAlex Tomas 	 * We couldn't merge the block to our extent, so we
237764769240SAlex Tomas 	 * need to flush current  extent and start new one
237864769240SAlex Tomas 	 */
2379c4a0c46eSAneesh Kumar K.V 	if (mpage_da_map_blocks(mpd) == 0)
2380a1d6cc56SAneesh Kumar K.V 		mpage_da_submit_io(mpd);
2381a1d6cc56SAneesh Kumar K.V 	mpd->io_done = 1;
2382a1d6cc56SAneesh Kumar K.V 	return;
238364769240SAlex Tomas }
238464769240SAlex Tomas 
2385c364b22cSAneesh Kumar K.V static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
238629fa89d0SAneesh Kumar K.V {
2387c364b22cSAneesh Kumar K.V 	return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
238829fa89d0SAneesh Kumar K.V }
238929fa89d0SAneesh Kumar K.V 
239064769240SAlex Tomas /*
239164769240SAlex Tomas  * __mpage_da_writepage - finds extent of pages and blocks
239264769240SAlex Tomas  *
239364769240SAlex Tomas  * @page: page to consider
239464769240SAlex Tomas  * @wbc: not used, we just follow rules
239564769240SAlex Tomas  * @data: context
239664769240SAlex Tomas  *
239764769240SAlex Tomas  * The function finds extents of pages and scan them for all blocks.
239864769240SAlex Tomas  */
239964769240SAlex Tomas static int __mpage_da_writepage(struct page *page,
240064769240SAlex Tomas 				struct writeback_control *wbc, void *data)
240164769240SAlex Tomas {
240264769240SAlex Tomas 	struct mpage_da_data *mpd = data;
240364769240SAlex Tomas 	struct inode *inode = mpd->inode;
24048dc207c0STheodore Ts'o 	struct buffer_head *bh, *head;
240564769240SAlex Tomas 	sector_t logical;
240664769240SAlex Tomas 
240764769240SAlex Tomas 	/*
240864769240SAlex Tomas 	 * Can we merge this page to current extent?
240964769240SAlex Tomas 	 */
241064769240SAlex Tomas 	if (mpd->next_page != page->index) {
241164769240SAlex Tomas 		/*
241264769240SAlex Tomas 		 * Nope, we can't. So, we map non-allocated blocks
2413a1d6cc56SAneesh Kumar K.V 		 * and start IO on them using writepage()
241464769240SAlex Tomas 		 */
241564769240SAlex Tomas 		if (mpd->next_page != mpd->first_page) {
2416c4a0c46eSAneesh Kumar K.V 			if (mpage_da_map_blocks(mpd) == 0)
241764769240SAlex Tomas 				mpage_da_submit_io(mpd);
2418a1d6cc56SAneesh Kumar K.V 			/*
2419a1d6cc56SAneesh Kumar K.V 			 * skip rest of the page in the page_vec
2420a1d6cc56SAneesh Kumar K.V 			 */
2421a1d6cc56SAneesh Kumar K.V 			mpd->io_done = 1;
2422a1d6cc56SAneesh Kumar K.V 			redirty_page_for_writepage(wbc, page);
2423a1d6cc56SAneesh Kumar K.V 			unlock_page(page);
2424a1d6cc56SAneesh Kumar K.V 			return MPAGE_DA_EXTENT_TAIL;
242564769240SAlex Tomas 		}
242664769240SAlex Tomas 
242764769240SAlex Tomas 		/*
242864769240SAlex Tomas 		 * Start next extent of pages ...
242964769240SAlex Tomas 		 */
243064769240SAlex Tomas 		mpd->first_page = page->index;
243164769240SAlex Tomas 
243264769240SAlex Tomas 		/*
243364769240SAlex Tomas 		 * ... and blocks
243464769240SAlex Tomas 		 */
24358dc207c0STheodore Ts'o 		mpd->b_size = 0;
24368dc207c0STheodore Ts'o 		mpd->b_state = 0;
24378dc207c0STheodore Ts'o 		mpd->b_blocknr = 0;
243864769240SAlex Tomas 	}
243964769240SAlex Tomas 
244064769240SAlex Tomas 	mpd->next_page = page->index + 1;
244164769240SAlex Tomas 	logical = (sector_t) page->index <<
244264769240SAlex Tomas 		  (PAGE_CACHE_SHIFT - inode->i_blkbits);
244364769240SAlex Tomas 
244464769240SAlex Tomas 	if (!page_has_buffers(page)) {
24458dc207c0STheodore Ts'o 		mpage_add_bh_to_extent(mpd, logical, PAGE_CACHE_SIZE,
24468dc207c0STheodore Ts'o 				       (1 << BH_Dirty) | (1 << BH_Uptodate));
2447a1d6cc56SAneesh Kumar K.V 		if (mpd->io_done)
2448a1d6cc56SAneesh Kumar K.V 			return MPAGE_DA_EXTENT_TAIL;
244964769240SAlex Tomas 	} else {
245064769240SAlex Tomas 		/*
245164769240SAlex Tomas 		 * Page with regular buffer heads, just add all dirty ones
245264769240SAlex Tomas 		 */
245364769240SAlex Tomas 		head = page_buffers(page);
245464769240SAlex Tomas 		bh = head;
245564769240SAlex Tomas 		do {
245664769240SAlex Tomas 			BUG_ON(buffer_locked(bh));
2457791b7f08SAneesh Kumar K.V 			/*
2458791b7f08SAneesh Kumar K.V 			 * We need to try to allocate
2459791b7f08SAneesh Kumar K.V 			 * unmapped blocks in the same page.
2460791b7f08SAneesh Kumar K.V 			 * Otherwise we won't make progress
246143ce1d23SAneesh Kumar K.V 			 * with the page in ext4_writepage
2462791b7f08SAneesh Kumar K.V 			 */
2463c364b22cSAneesh Kumar K.V 			if (ext4_bh_delay_or_unwritten(NULL, bh)) {
24648dc207c0STheodore Ts'o 				mpage_add_bh_to_extent(mpd, logical,
24658dc207c0STheodore Ts'o 						       bh->b_size,
24668dc207c0STheodore Ts'o 						       bh->b_state);
2467a1d6cc56SAneesh Kumar K.V 				if (mpd->io_done)
2468a1d6cc56SAneesh Kumar K.V 					return MPAGE_DA_EXTENT_TAIL;
2469791b7f08SAneesh Kumar K.V 			} else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2470791b7f08SAneesh Kumar K.V 				/*
2471791b7f08SAneesh Kumar K.V 				 * mapped dirty buffer. We need to update
2472791b7f08SAneesh Kumar K.V 				 * the b_state because we look at
2473791b7f08SAneesh Kumar K.V 				 * b_state in mpage_da_map_blocks. We don't
2474791b7f08SAneesh Kumar K.V 				 * update b_size because if we find an
2475791b7f08SAneesh Kumar K.V 				 * unmapped buffer_head later we need to
2476791b7f08SAneesh Kumar K.V 				 * use the b_state flag of that buffer_head.
2477791b7f08SAneesh Kumar K.V 				 */
24788dc207c0STheodore Ts'o 				if (mpd->b_size == 0)
24798dc207c0STheodore Ts'o 					mpd->b_state = bh->b_state & BH_FLAGS;
2480a1d6cc56SAneesh Kumar K.V 			}
248164769240SAlex Tomas 			logical++;
248264769240SAlex Tomas 		} while ((bh = bh->b_this_page) != head);
248364769240SAlex Tomas 	}
248464769240SAlex Tomas 
248564769240SAlex Tomas 	return 0;
248664769240SAlex Tomas }
248764769240SAlex Tomas 
248864769240SAlex Tomas /*
2489b920c755STheodore Ts'o  * This is a special get_blocks_t callback which is used by
2490b920c755STheodore Ts'o  * ext4_da_write_begin().  It will either return mapped block or
2491b920c755STheodore Ts'o  * reserve space for a single block.
249229fa89d0SAneesh Kumar K.V  *
249329fa89d0SAneesh Kumar K.V  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
249429fa89d0SAneesh Kumar K.V  * We also have b_blocknr = -1 and b_bdev initialized properly
249529fa89d0SAneesh Kumar K.V  *
249629fa89d0SAneesh Kumar K.V  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
249729fa89d0SAneesh Kumar K.V  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
249829fa89d0SAneesh Kumar K.V  * initialized properly.
249964769240SAlex Tomas  */
250064769240SAlex Tomas static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
25012ed88685STheodore Ts'o 				  struct buffer_head *bh, int create)
250264769240SAlex Tomas {
25032ed88685STheodore Ts'o 	struct ext4_map_blocks map;
250464769240SAlex Tomas 	int ret = 0;
250533b9817eSAneesh Kumar K.V 	sector_t invalid_block = ~((sector_t) 0xffff);
250633b9817eSAneesh Kumar K.V 
250733b9817eSAneesh Kumar K.V 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
250833b9817eSAneesh Kumar K.V 		invalid_block = ~0;
250964769240SAlex Tomas 
251064769240SAlex Tomas 	BUG_ON(create == 0);
25112ed88685STheodore Ts'o 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
25122ed88685STheodore Ts'o 
25132ed88685STheodore Ts'o 	map.m_lblk = iblock;
25142ed88685STheodore Ts'o 	map.m_len = 1;
251564769240SAlex Tomas 
251664769240SAlex Tomas 	/*
251764769240SAlex Tomas 	 * first, we need to know whether the block is allocated already
251864769240SAlex Tomas 	 * preallocated blocks are unmapped but should treated
251964769240SAlex Tomas 	 * the same as allocated blocks.
252064769240SAlex Tomas 	 */
25212ed88685STheodore Ts'o 	ret = ext4_map_blocks(NULL, inode, &map, 0);
25222ed88685STheodore Ts'o 	if (ret < 0)
25232ed88685STheodore Ts'o 		return ret;
25242ed88685STheodore Ts'o 	if (ret == 0) {
25252ed88685STheodore Ts'o 		if (buffer_delay(bh))
25262ed88685STheodore Ts'o 			return 0; /* Not sure this could or should happen */
252764769240SAlex Tomas 		/*
252864769240SAlex Tomas 		 * XXX: __block_prepare_write() unmaps passed block,
252964769240SAlex Tomas 		 * is it OK?
253064769240SAlex Tomas 		 */
25319d0be502STheodore Ts'o 		ret = ext4_da_reserve_space(inode, iblock);
2532d2a17637SMingming Cao 		if (ret)
2533d2a17637SMingming Cao 			/* not enough space to reserve */
2534d2a17637SMingming Cao 			return ret;
2535d2a17637SMingming Cao 
25362ed88685STheodore Ts'o 		map_bh(bh, inode->i_sb, invalid_block);
25372ed88685STheodore Ts'o 		set_buffer_new(bh);
25382ed88685STheodore Ts'o 		set_buffer_delay(bh);
25392ed88685STheodore Ts'o 		return 0;
254064769240SAlex Tomas 	}
254164769240SAlex Tomas 
25422ed88685STheodore Ts'o 	map_bh(bh, inode->i_sb, map.m_pblk);
25432ed88685STheodore Ts'o 	bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
25442ed88685STheodore Ts'o 
25452ed88685STheodore Ts'o 	if (buffer_unwritten(bh)) {
25462ed88685STheodore Ts'o 		/* A delayed write to unwritten bh should be marked
25472ed88685STheodore Ts'o 		 * new and mapped.  Mapped ensures that we don't do
25482ed88685STheodore Ts'o 		 * get_block multiple times when we write to the same
25492ed88685STheodore Ts'o 		 * offset and new ensures that we do proper zero out
25502ed88685STheodore Ts'o 		 * for partial write.
25512ed88685STheodore Ts'o 		 */
25522ed88685STheodore Ts'o 		set_buffer_new(bh);
25532ed88685STheodore Ts'o 		set_buffer_mapped(bh);
25542ed88685STheodore Ts'o 	}
25552ed88685STheodore Ts'o 	return 0;
255664769240SAlex Tomas }
255761628a3fSMingming Cao 
2558b920c755STheodore Ts'o /*
2559b920c755STheodore Ts'o  * This function is used as a standard get_block_t calback function
2560b920c755STheodore Ts'o  * when there is no desire to allocate any blocks.  It is used as a
2561206f7ab4SChristoph Hellwig  * callback function for block_prepare_write() and block_write_full_page().
2562206f7ab4SChristoph Hellwig  * These functions should only try to map a single block at a time.
2563b920c755STheodore Ts'o  *
2564b920c755STheodore Ts'o  * Since this function doesn't do block allocations even if the caller
2565b920c755STheodore Ts'o  * requests it by passing in create=1, it is critically important that
2566b920c755STheodore Ts'o  * any caller checks to make sure that any buffer heads are returned
2567b920c755STheodore Ts'o  * by this function are either all already mapped or marked for
2568206f7ab4SChristoph Hellwig  * delayed allocation before calling  block_write_full_page().  Otherwise,
2569206f7ab4SChristoph Hellwig  * b_blocknr could be left unitialized, and the page write functions will
2570206f7ab4SChristoph Hellwig  * be taken by surprise.
2571b920c755STheodore Ts'o  */
2572b920c755STheodore Ts'o static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
2573f0e6c985SAneesh Kumar K.V 				   struct buffer_head *bh_result, int create)
2574f0e6c985SAneesh Kumar K.V {
2575a2dc52b5STheodore Ts'o 	BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
25762ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh_result, 0);
257761628a3fSMingming Cao }
257861628a3fSMingming Cao 
257962e086beSAneesh Kumar K.V static int bget_one(handle_t *handle, struct buffer_head *bh)
258062e086beSAneesh Kumar K.V {
258162e086beSAneesh Kumar K.V 	get_bh(bh);
258262e086beSAneesh Kumar K.V 	return 0;
258362e086beSAneesh Kumar K.V }
258462e086beSAneesh Kumar K.V 
258562e086beSAneesh Kumar K.V static int bput_one(handle_t *handle, struct buffer_head *bh)
258662e086beSAneesh Kumar K.V {
258762e086beSAneesh Kumar K.V 	put_bh(bh);
258862e086beSAneesh Kumar K.V 	return 0;
258962e086beSAneesh Kumar K.V }
259062e086beSAneesh Kumar K.V 
259162e086beSAneesh Kumar K.V static int __ext4_journalled_writepage(struct page *page,
259262e086beSAneesh Kumar K.V 				       unsigned int len)
259362e086beSAneesh Kumar K.V {
259462e086beSAneesh Kumar K.V 	struct address_space *mapping = page->mapping;
259562e086beSAneesh Kumar K.V 	struct inode *inode = mapping->host;
259662e086beSAneesh Kumar K.V 	struct buffer_head *page_bufs;
259762e086beSAneesh Kumar K.V 	handle_t *handle = NULL;
259862e086beSAneesh Kumar K.V 	int ret = 0;
259962e086beSAneesh Kumar K.V 	int err;
260062e086beSAneesh Kumar K.V 
260162e086beSAneesh Kumar K.V 	page_bufs = page_buffers(page);
260262e086beSAneesh Kumar K.V 	BUG_ON(!page_bufs);
260362e086beSAneesh Kumar K.V 	walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
260462e086beSAneesh Kumar K.V 	/* As soon as we unlock the page, it can go away, but we have
260562e086beSAneesh Kumar K.V 	 * references to buffers so we are safe */
260662e086beSAneesh Kumar K.V 	unlock_page(page);
260762e086beSAneesh Kumar K.V 
260862e086beSAneesh Kumar K.V 	handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
260962e086beSAneesh Kumar K.V 	if (IS_ERR(handle)) {
261062e086beSAneesh Kumar K.V 		ret = PTR_ERR(handle);
261162e086beSAneesh Kumar K.V 		goto out;
261262e086beSAneesh Kumar K.V 	}
261362e086beSAneesh Kumar K.V 
261462e086beSAneesh Kumar K.V 	ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
261562e086beSAneesh Kumar K.V 				do_journal_get_write_access);
261662e086beSAneesh Kumar K.V 
261762e086beSAneesh Kumar K.V 	err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
261862e086beSAneesh Kumar K.V 				write_end_fn);
261962e086beSAneesh Kumar K.V 	if (ret == 0)
262062e086beSAneesh Kumar K.V 		ret = err;
262162e086beSAneesh Kumar K.V 	err = ext4_journal_stop(handle);
262262e086beSAneesh Kumar K.V 	if (!ret)
262362e086beSAneesh Kumar K.V 		ret = err;
262462e086beSAneesh Kumar K.V 
262562e086beSAneesh Kumar K.V 	walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
262619f5fb7aSTheodore Ts'o 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
262762e086beSAneesh Kumar K.V out:
262862e086beSAneesh Kumar K.V 	return ret;
262962e086beSAneesh Kumar K.V }
263062e086beSAneesh Kumar K.V 
2631744692dcSJiaying Zhang static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
2632744692dcSJiaying Zhang static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
2633744692dcSJiaying Zhang 
263461628a3fSMingming Cao /*
263543ce1d23SAneesh Kumar K.V  * Note that we don't need to start a transaction unless we're journaling data
263643ce1d23SAneesh Kumar K.V  * because we should have holes filled from ext4_page_mkwrite(). We even don't
263743ce1d23SAneesh Kumar K.V  * need to file the inode to the transaction's list in ordered mode because if
263843ce1d23SAneesh Kumar K.V  * we are writing back data added by write(), the inode is already there and if
263943ce1d23SAneesh Kumar K.V  * we are writing back data modified via mmap(), noone guarantees in which
264043ce1d23SAneesh Kumar K.V  * transaction the data will hit the disk. In case we are journaling data, we
264143ce1d23SAneesh Kumar K.V  * cannot start transaction directly because transaction start ranks above page
264243ce1d23SAneesh Kumar K.V  * lock so we have to do some magic.
264343ce1d23SAneesh Kumar K.V  *
2644b920c755STheodore Ts'o  * This function can get called via...
2645b920c755STheodore Ts'o  *   - ext4_da_writepages after taking page lock (have journal handle)
2646b920c755STheodore Ts'o  *   - journal_submit_inode_data_buffers (no journal handle)
2647b920c755STheodore Ts'o  *   - shrink_page_list via pdflush (no journal handle)
2648b920c755STheodore Ts'o  *   - grab_page_cache when doing write_begin (have journal handle)
264943ce1d23SAneesh Kumar K.V  *
265043ce1d23SAneesh Kumar K.V  * We don't do any block allocation in this function. If we have page with
265143ce1d23SAneesh Kumar K.V  * multiple blocks we need to write those buffer_heads that are mapped. This
265243ce1d23SAneesh Kumar K.V  * is important for mmaped based write. So if we do with blocksize 1K
265343ce1d23SAneesh Kumar K.V  * truncate(f, 1024);
265443ce1d23SAneesh Kumar K.V  * a = mmap(f, 0, 4096);
265543ce1d23SAneesh Kumar K.V  * a[0] = 'a';
265643ce1d23SAneesh Kumar K.V  * truncate(f, 4096);
265743ce1d23SAneesh Kumar K.V  * we have in the page first buffer_head mapped via page_mkwrite call back
265843ce1d23SAneesh Kumar K.V  * but other bufer_heads would be unmapped but dirty(dirty done via the
265943ce1d23SAneesh Kumar K.V  * do_wp_page). So writepage should write the first block. If we modify
266043ce1d23SAneesh Kumar K.V  * the mmap area beyond 1024 we will again get a page_fault and the
266143ce1d23SAneesh Kumar K.V  * page_mkwrite callback will do the block allocation and mark the
266243ce1d23SAneesh Kumar K.V  * buffer_heads mapped.
266343ce1d23SAneesh Kumar K.V  *
266443ce1d23SAneesh Kumar K.V  * We redirty the page if we have any buffer_heads that is either delay or
266543ce1d23SAneesh Kumar K.V  * unwritten in the page.
266643ce1d23SAneesh Kumar K.V  *
266743ce1d23SAneesh Kumar K.V  * We can get recursively called as show below.
266843ce1d23SAneesh Kumar K.V  *
266943ce1d23SAneesh Kumar K.V  *	ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
267043ce1d23SAneesh Kumar K.V  *		ext4_writepage()
267143ce1d23SAneesh Kumar K.V  *
267243ce1d23SAneesh Kumar K.V  * But since we don't do any block allocation we should not deadlock.
267343ce1d23SAneesh Kumar K.V  * Page also have the dirty flag cleared so we don't get recurive page_lock.
267461628a3fSMingming Cao  */
267543ce1d23SAneesh Kumar K.V static int ext4_writepage(struct page *page,
267664769240SAlex Tomas 			  struct writeback_control *wbc)
267764769240SAlex Tomas {
267864769240SAlex Tomas 	int ret = 0;
267961628a3fSMingming Cao 	loff_t size;
2680498e5f24STheodore Ts'o 	unsigned int len;
2681744692dcSJiaying Zhang 	struct buffer_head *page_bufs = NULL;
268261628a3fSMingming Cao 	struct inode *inode = page->mapping->host;
268364769240SAlex Tomas 
268443ce1d23SAneesh Kumar K.V 	trace_ext4_writepage(inode, page);
268561628a3fSMingming Cao 	size = i_size_read(inode);
268661628a3fSMingming Cao 	if (page->index == size >> PAGE_CACHE_SHIFT)
268761628a3fSMingming Cao 		len = size & ~PAGE_CACHE_MASK;
268861628a3fSMingming Cao 	else
268961628a3fSMingming Cao 		len = PAGE_CACHE_SIZE;
269061628a3fSMingming Cao 
2691f0e6c985SAneesh Kumar K.V 	if (page_has_buffers(page)) {
2692f0e6c985SAneesh Kumar K.V 		page_bufs = page_buffers(page);
2693f0e6c985SAneesh Kumar K.V 		if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2694c364b22cSAneesh Kumar K.V 					ext4_bh_delay_or_unwritten)) {
269561628a3fSMingming Cao 			/*
2696f0e6c985SAneesh Kumar K.V 			 * We don't want to do  block allocation
2697f0e6c985SAneesh Kumar K.V 			 * So redirty the page and return
2698cd1aac32SAneesh Kumar K.V 			 * We may reach here when we do a journal commit
2699cd1aac32SAneesh Kumar K.V 			 * via journal_submit_inode_data_buffers.
2700cd1aac32SAneesh Kumar K.V 			 * If we don't have mapping block we just ignore
2701f0e6c985SAneesh Kumar K.V 			 * them. We can also reach here via shrink_page_list
2702f0e6c985SAneesh Kumar K.V 			 */
2703f0e6c985SAneesh Kumar K.V 			redirty_page_for_writepage(wbc, page);
2704f0e6c985SAneesh Kumar K.V 			unlock_page(page);
2705f0e6c985SAneesh Kumar K.V 			return 0;
2706f0e6c985SAneesh Kumar K.V 		}
2707f0e6c985SAneesh Kumar K.V 	} else {
2708f0e6c985SAneesh Kumar K.V 		/*
2709f0e6c985SAneesh Kumar K.V 		 * The test for page_has_buffers() is subtle:
2710f0e6c985SAneesh Kumar K.V 		 * We know the page is dirty but it lost buffers. That means
2711f0e6c985SAneesh Kumar K.V 		 * that at some moment in time after write_begin()/write_end()
2712f0e6c985SAneesh Kumar K.V 		 * has been called all buffers have been clean and thus they
2713f0e6c985SAneesh Kumar K.V 		 * must have been written at least once. So they are all
2714f0e6c985SAneesh Kumar K.V 		 * mapped and we can happily proceed with mapping them
2715f0e6c985SAneesh Kumar K.V 		 * and writing the page.
2716f0e6c985SAneesh Kumar K.V 		 *
2717f0e6c985SAneesh Kumar K.V 		 * Try to initialize the buffer_heads and check whether
2718f0e6c985SAneesh Kumar K.V 		 * all are mapped and non delay. We don't want to
2719f0e6c985SAneesh Kumar K.V 		 * do block allocation here.
2720f0e6c985SAneesh Kumar K.V 		 */
2721b767e78aSAneesh Kumar K.V 		ret = block_prepare_write(page, 0, len,
2722b920c755STheodore Ts'o 					  noalloc_get_block_write);
2723f0e6c985SAneesh Kumar K.V 		if (!ret) {
2724f0e6c985SAneesh Kumar K.V 			page_bufs = page_buffers(page);
2725f0e6c985SAneesh Kumar K.V 			/* check whether all are mapped and non delay */
2726f0e6c985SAneesh Kumar K.V 			if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2727c364b22cSAneesh Kumar K.V 						ext4_bh_delay_or_unwritten)) {
2728f0e6c985SAneesh Kumar K.V 				redirty_page_for_writepage(wbc, page);
2729f0e6c985SAneesh Kumar K.V 				unlock_page(page);
2730f0e6c985SAneesh Kumar K.V 				return 0;
2731f0e6c985SAneesh Kumar K.V 			}
2732f0e6c985SAneesh Kumar K.V 		} else {
2733f0e6c985SAneesh Kumar K.V 			/*
2734f0e6c985SAneesh Kumar K.V 			 * We can't do block allocation here
2735f0e6c985SAneesh Kumar K.V 			 * so just redity the page and unlock
2736f0e6c985SAneesh Kumar K.V 			 * and return
273761628a3fSMingming Cao 			 */
273861628a3fSMingming Cao 			redirty_page_for_writepage(wbc, page);
273961628a3fSMingming Cao 			unlock_page(page);
274061628a3fSMingming Cao 			return 0;
274161628a3fSMingming Cao 		}
2742ed9b3e33SAneesh Kumar K.V 		/* now mark the buffer_heads as dirty and uptodate */
2743b767e78aSAneesh Kumar K.V 		block_commit_write(page, 0, len);
274464769240SAlex Tomas 	}
274564769240SAlex Tomas 
274643ce1d23SAneesh Kumar K.V 	if (PageChecked(page) && ext4_should_journal_data(inode)) {
274743ce1d23SAneesh Kumar K.V 		/*
274843ce1d23SAneesh Kumar K.V 		 * It's mmapped pagecache.  Add buffers and journal it.  There
274943ce1d23SAneesh Kumar K.V 		 * doesn't seem much point in redirtying the page here.
275043ce1d23SAneesh Kumar K.V 		 */
275143ce1d23SAneesh Kumar K.V 		ClearPageChecked(page);
27523f0ca309SWu Fengguang 		return __ext4_journalled_writepage(page, len);
275343ce1d23SAneesh Kumar K.V 	}
275443ce1d23SAneesh Kumar K.V 
2755206f7ab4SChristoph Hellwig 	if (page_bufs && buffer_uninit(page_bufs)) {
2756744692dcSJiaying Zhang 		ext4_set_bh_endio(page_bufs, inode);
2757744692dcSJiaying Zhang 		ret = block_write_full_page_endio(page, noalloc_get_block_write,
2758744692dcSJiaying Zhang 					    wbc, ext4_end_io_buffer_write);
2759744692dcSJiaying Zhang 	} else
2760b920c755STheodore Ts'o 		ret = block_write_full_page(page, noalloc_get_block_write,
2761f0e6c985SAneesh Kumar K.V 					    wbc);
276264769240SAlex Tomas 
276364769240SAlex Tomas 	return ret;
276464769240SAlex Tomas }
276564769240SAlex Tomas 
276661628a3fSMingming Cao /*
2767525f4ed8SMingming Cao  * This is called via ext4_da_writepages() to
2768525f4ed8SMingming Cao  * calulate the total number of credits to reserve to fit
2769525f4ed8SMingming Cao  * a single extent allocation into a single transaction,
2770525f4ed8SMingming Cao  * ext4_da_writpeages() will loop calling this before
2771525f4ed8SMingming Cao  * the block allocation.
277261628a3fSMingming Cao  */
2773525f4ed8SMingming Cao 
2774525f4ed8SMingming Cao static int ext4_da_writepages_trans_blocks(struct inode *inode)
2775525f4ed8SMingming Cao {
2776525f4ed8SMingming Cao 	int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2777525f4ed8SMingming Cao 
2778525f4ed8SMingming Cao 	/*
2779525f4ed8SMingming Cao 	 * With non-extent format the journal credit needed to
2780525f4ed8SMingming Cao 	 * insert nrblocks contiguous block is dependent on
2781525f4ed8SMingming Cao 	 * number of contiguous block. So we will limit
2782525f4ed8SMingming Cao 	 * number of contiguous block to a sane value
2783525f4ed8SMingming Cao 	 */
278412e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2785525f4ed8SMingming Cao 	    (max_blocks > EXT4_MAX_TRANS_DATA))
2786525f4ed8SMingming Cao 		max_blocks = EXT4_MAX_TRANS_DATA;
2787525f4ed8SMingming Cao 
2788525f4ed8SMingming Cao 	return ext4_chunk_trans_blocks(inode, max_blocks);
2789525f4ed8SMingming Cao }
279061628a3fSMingming Cao 
27918e48dcfbSTheodore Ts'o /*
27928e48dcfbSTheodore Ts'o  * write_cache_pages_da - walk the list of dirty pages of the given
27938e48dcfbSTheodore Ts'o  * address space and call the callback function (which usually writes
27948e48dcfbSTheodore Ts'o  * the pages).
27958e48dcfbSTheodore Ts'o  *
27968e48dcfbSTheodore Ts'o  * This is a forked version of write_cache_pages().  Differences:
27978e48dcfbSTheodore Ts'o  *	Range cyclic is ignored.
27988e48dcfbSTheodore Ts'o  *	no_nrwrite_index_update is always presumed true
27998e48dcfbSTheodore Ts'o  */
28008e48dcfbSTheodore Ts'o static int write_cache_pages_da(struct address_space *mapping,
28018e48dcfbSTheodore Ts'o 				struct writeback_control *wbc,
28028e48dcfbSTheodore Ts'o 				struct mpage_da_data *mpd)
28038e48dcfbSTheodore Ts'o {
28048e48dcfbSTheodore Ts'o 	int ret = 0;
28058e48dcfbSTheodore Ts'o 	int done = 0;
28068e48dcfbSTheodore Ts'o 	struct pagevec pvec;
28078e48dcfbSTheodore Ts'o 	int nr_pages;
28088e48dcfbSTheodore Ts'o 	pgoff_t index;
28098e48dcfbSTheodore Ts'o 	pgoff_t end;		/* Inclusive */
28108e48dcfbSTheodore Ts'o 	long nr_to_write = wbc->nr_to_write;
28118e48dcfbSTheodore Ts'o 
28128e48dcfbSTheodore Ts'o 	pagevec_init(&pvec, 0);
28138e48dcfbSTheodore Ts'o 	index = wbc->range_start >> PAGE_CACHE_SHIFT;
28148e48dcfbSTheodore Ts'o 	end = wbc->range_end >> PAGE_CACHE_SHIFT;
28158e48dcfbSTheodore Ts'o 
28168e48dcfbSTheodore Ts'o 	while (!done && (index <= end)) {
28178e48dcfbSTheodore Ts'o 		int i;
28188e48dcfbSTheodore Ts'o 
28198e48dcfbSTheodore Ts'o 		nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
28208e48dcfbSTheodore Ts'o 			      PAGECACHE_TAG_DIRTY,
28218e48dcfbSTheodore Ts'o 			      min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
28228e48dcfbSTheodore Ts'o 		if (nr_pages == 0)
28238e48dcfbSTheodore Ts'o 			break;
28248e48dcfbSTheodore Ts'o 
28258e48dcfbSTheodore Ts'o 		for (i = 0; i < nr_pages; i++) {
28268e48dcfbSTheodore Ts'o 			struct page *page = pvec.pages[i];
28278e48dcfbSTheodore Ts'o 
28288e48dcfbSTheodore Ts'o 			/*
28298e48dcfbSTheodore Ts'o 			 * At this point, the page may be truncated or
28308e48dcfbSTheodore Ts'o 			 * invalidated (changing page->mapping to NULL), or
28318e48dcfbSTheodore Ts'o 			 * even swizzled back from swapper_space to tmpfs file
28328e48dcfbSTheodore Ts'o 			 * mapping. However, page->index will not change
28338e48dcfbSTheodore Ts'o 			 * because we have a reference on the page.
28348e48dcfbSTheodore Ts'o 			 */
28358e48dcfbSTheodore Ts'o 			if (page->index > end) {
28368e48dcfbSTheodore Ts'o 				done = 1;
28378e48dcfbSTheodore Ts'o 				break;
28388e48dcfbSTheodore Ts'o 			}
28398e48dcfbSTheodore Ts'o 
28408e48dcfbSTheodore Ts'o 			lock_page(page);
28418e48dcfbSTheodore Ts'o 
28428e48dcfbSTheodore Ts'o 			/*
28438e48dcfbSTheodore Ts'o 			 * Page truncated or invalidated. We can freely skip it
28448e48dcfbSTheodore Ts'o 			 * then, even for data integrity operations: the page
28458e48dcfbSTheodore Ts'o 			 * has disappeared concurrently, so there could be no
28468e48dcfbSTheodore Ts'o 			 * real expectation of this data interity operation
28478e48dcfbSTheodore Ts'o 			 * even if there is now a new, dirty page at the same
28488e48dcfbSTheodore Ts'o 			 * pagecache address.
28498e48dcfbSTheodore Ts'o 			 */
28508e48dcfbSTheodore Ts'o 			if (unlikely(page->mapping != mapping)) {
28518e48dcfbSTheodore Ts'o continue_unlock:
28528e48dcfbSTheodore Ts'o 				unlock_page(page);
28538e48dcfbSTheodore Ts'o 				continue;
28548e48dcfbSTheodore Ts'o 			}
28558e48dcfbSTheodore Ts'o 
28568e48dcfbSTheodore Ts'o 			if (!PageDirty(page)) {
28578e48dcfbSTheodore Ts'o 				/* someone wrote it for us */
28588e48dcfbSTheodore Ts'o 				goto continue_unlock;
28598e48dcfbSTheodore Ts'o 			}
28608e48dcfbSTheodore Ts'o 
28618e48dcfbSTheodore Ts'o 			if (PageWriteback(page)) {
28628e48dcfbSTheodore Ts'o 				if (wbc->sync_mode != WB_SYNC_NONE)
28638e48dcfbSTheodore Ts'o 					wait_on_page_writeback(page);
28648e48dcfbSTheodore Ts'o 				else
28658e48dcfbSTheodore Ts'o 					goto continue_unlock;
28668e48dcfbSTheodore Ts'o 			}
28678e48dcfbSTheodore Ts'o 
28688e48dcfbSTheodore Ts'o 			BUG_ON(PageWriteback(page));
28698e48dcfbSTheodore Ts'o 			if (!clear_page_dirty_for_io(page))
28708e48dcfbSTheodore Ts'o 				goto continue_unlock;
28718e48dcfbSTheodore Ts'o 
28728e48dcfbSTheodore Ts'o 			ret = __mpage_da_writepage(page, wbc, mpd);
28738e48dcfbSTheodore Ts'o 			if (unlikely(ret)) {
28748e48dcfbSTheodore Ts'o 				if (ret == AOP_WRITEPAGE_ACTIVATE) {
28758e48dcfbSTheodore Ts'o 					unlock_page(page);
28768e48dcfbSTheodore Ts'o 					ret = 0;
28778e48dcfbSTheodore Ts'o 				} else {
28788e48dcfbSTheodore Ts'o 					done = 1;
28798e48dcfbSTheodore Ts'o 					break;
28808e48dcfbSTheodore Ts'o 				}
28818e48dcfbSTheodore Ts'o 			}
28828e48dcfbSTheodore Ts'o 
28838e48dcfbSTheodore Ts'o 			if (nr_to_write > 0) {
28848e48dcfbSTheodore Ts'o 				nr_to_write--;
28858e48dcfbSTheodore Ts'o 				if (nr_to_write == 0 &&
28868e48dcfbSTheodore Ts'o 				    wbc->sync_mode == WB_SYNC_NONE) {
28878e48dcfbSTheodore Ts'o 					/*
28888e48dcfbSTheodore Ts'o 					 * We stop writing back only if we are
28898e48dcfbSTheodore Ts'o 					 * not doing integrity sync. In case of
28908e48dcfbSTheodore Ts'o 					 * integrity sync we have to keep going
28918e48dcfbSTheodore Ts'o 					 * because someone may be concurrently
28928e48dcfbSTheodore Ts'o 					 * dirtying pages, and we might have
28938e48dcfbSTheodore Ts'o 					 * synced a lot of newly appeared dirty
28948e48dcfbSTheodore Ts'o 					 * pages, but have not synced all of the
28958e48dcfbSTheodore Ts'o 					 * old dirty pages.
28968e48dcfbSTheodore Ts'o 					 */
28978e48dcfbSTheodore Ts'o 					done = 1;
28988e48dcfbSTheodore Ts'o 					break;
28998e48dcfbSTheodore Ts'o 				}
29008e48dcfbSTheodore Ts'o 			}
29018e48dcfbSTheodore Ts'o 		}
29028e48dcfbSTheodore Ts'o 		pagevec_release(&pvec);
29038e48dcfbSTheodore Ts'o 		cond_resched();
29048e48dcfbSTheodore Ts'o 	}
29058e48dcfbSTheodore Ts'o 	return ret;
29068e48dcfbSTheodore Ts'o }
29078e48dcfbSTheodore Ts'o 
29088e48dcfbSTheodore Ts'o 
290964769240SAlex Tomas static int ext4_da_writepages(struct address_space *mapping,
291064769240SAlex Tomas 			      struct writeback_control *wbc)
291164769240SAlex Tomas {
291222208dedSAneesh Kumar K.V 	pgoff_t	index;
291322208dedSAneesh Kumar K.V 	int range_whole = 0;
291461628a3fSMingming Cao 	handle_t *handle = NULL;
2915df22291fSAneesh Kumar K.V 	struct mpage_da_data mpd;
29165e745b04SAneesh Kumar K.V 	struct inode *inode = mapping->host;
2917498e5f24STheodore Ts'o 	int pages_written = 0;
2918498e5f24STheodore Ts'o 	long pages_skipped;
291955138e0bSTheodore Ts'o 	unsigned int max_pages;
29202acf2c26SAneesh Kumar K.V 	int range_cyclic, cycled = 1, io_done = 0;
292155138e0bSTheodore Ts'o 	int needed_blocks, ret = 0;
292255138e0bSTheodore Ts'o 	long desired_nr_to_write, nr_to_writebump = 0;
2923de89de6eSTheodore Ts'o 	loff_t range_start = wbc->range_start;
29245e745b04SAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
292561628a3fSMingming Cao 
29269bffad1eSTheodore Ts'o 	trace_ext4_da_writepages(inode, wbc);
2927ba80b101STheodore Ts'o 
292861628a3fSMingming Cao 	/*
292961628a3fSMingming Cao 	 * No pages to write? This is mainly a kludge to avoid starting
293061628a3fSMingming Cao 	 * a transaction for special inodes like journal inode on last iput()
293161628a3fSMingming Cao 	 * because that could violate lock ordering on umount
293261628a3fSMingming Cao 	 */
2933a1d6cc56SAneesh Kumar K.V 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
293461628a3fSMingming Cao 		return 0;
29352a21e37eSTheodore Ts'o 
29362a21e37eSTheodore Ts'o 	/*
29372a21e37eSTheodore Ts'o 	 * If the filesystem has aborted, it is read-only, so return
29382a21e37eSTheodore Ts'o 	 * right away instead of dumping stack traces later on that
29392a21e37eSTheodore Ts'o 	 * will obscure the real source of the problem.  We test
29404ab2f15bSTheodore Ts'o 	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
29412a21e37eSTheodore Ts'o 	 * the latter could be true if the filesystem is mounted
29422a21e37eSTheodore Ts'o 	 * read-only, and in that case, ext4_da_writepages should
29432a21e37eSTheodore Ts'o 	 * *never* be called, so if that ever happens, we would want
29442a21e37eSTheodore Ts'o 	 * the stack trace.
29452a21e37eSTheodore Ts'o 	 */
29464ab2f15bSTheodore Ts'o 	if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
29472a21e37eSTheodore Ts'o 		return -EROFS;
29482a21e37eSTheodore Ts'o 
294922208dedSAneesh Kumar K.V 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
295022208dedSAneesh Kumar K.V 		range_whole = 1;
295161628a3fSMingming Cao 
29522acf2c26SAneesh Kumar K.V 	range_cyclic = wbc->range_cyclic;
29532acf2c26SAneesh Kumar K.V 	if (wbc->range_cyclic) {
295422208dedSAneesh Kumar K.V 		index = mapping->writeback_index;
29552acf2c26SAneesh Kumar K.V 		if (index)
29562acf2c26SAneesh Kumar K.V 			cycled = 0;
29572acf2c26SAneesh Kumar K.V 		wbc->range_start = index << PAGE_CACHE_SHIFT;
29582acf2c26SAneesh Kumar K.V 		wbc->range_end  = LLONG_MAX;
29592acf2c26SAneesh Kumar K.V 		wbc->range_cyclic = 0;
29602acf2c26SAneesh Kumar K.V 	} else
296122208dedSAneesh Kumar K.V 		index = wbc->range_start >> PAGE_CACHE_SHIFT;
2962a1d6cc56SAneesh Kumar K.V 
296355138e0bSTheodore Ts'o 	/*
296455138e0bSTheodore Ts'o 	 * This works around two forms of stupidity.  The first is in
296555138e0bSTheodore Ts'o 	 * the writeback code, which caps the maximum number of pages
296655138e0bSTheodore Ts'o 	 * written to be 1024 pages.  This is wrong on multiple
296755138e0bSTheodore Ts'o 	 * levels; different architectues have a different page size,
296855138e0bSTheodore Ts'o 	 * which changes the maximum amount of data which gets
296955138e0bSTheodore Ts'o 	 * written.  Secondly, 4 megabytes is way too small.  XFS
297055138e0bSTheodore Ts'o 	 * forces this value to be 16 megabytes by multiplying
297155138e0bSTheodore Ts'o 	 * nr_to_write parameter by four, and then relies on its
297255138e0bSTheodore Ts'o 	 * allocator to allocate larger extents to make them
297355138e0bSTheodore Ts'o 	 * contiguous.  Unfortunately this brings us to the second
297455138e0bSTheodore Ts'o 	 * stupidity, which is that ext4's mballoc code only allocates
297555138e0bSTheodore Ts'o 	 * at most 2048 blocks.  So we force contiguous writes up to
297655138e0bSTheodore Ts'o 	 * the number of dirty blocks in the inode, or
297755138e0bSTheodore Ts'o 	 * sbi->max_writeback_mb_bump whichever is smaller.
297855138e0bSTheodore Ts'o 	 */
297955138e0bSTheodore Ts'o 	max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
298055138e0bSTheodore Ts'o 	if (!range_cyclic && range_whole)
298155138e0bSTheodore Ts'o 		desired_nr_to_write = wbc->nr_to_write * 8;
298255138e0bSTheodore Ts'o 	else
298355138e0bSTheodore Ts'o 		desired_nr_to_write = ext4_num_dirty_pages(inode, index,
298455138e0bSTheodore Ts'o 							   max_pages);
298555138e0bSTheodore Ts'o 	if (desired_nr_to_write > max_pages)
298655138e0bSTheodore Ts'o 		desired_nr_to_write = max_pages;
298755138e0bSTheodore Ts'o 
298855138e0bSTheodore Ts'o 	if (wbc->nr_to_write < desired_nr_to_write) {
298955138e0bSTheodore Ts'o 		nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
299055138e0bSTheodore Ts'o 		wbc->nr_to_write = desired_nr_to_write;
299155138e0bSTheodore Ts'o 	}
299255138e0bSTheodore Ts'o 
2993df22291fSAneesh Kumar K.V 	mpd.wbc = wbc;
2994df22291fSAneesh Kumar K.V 	mpd.inode = mapping->host;
2995df22291fSAneesh Kumar K.V 
299622208dedSAneesh Kumar K.V 	pages_skipped = wbc->pages_skipped;
299722208dedSAneesh Kumar K.V 
29982acf2c26SAneesh Kumar K.V retry:
299922208dedSAneesh Kumar K.V 	while (!ret && wbc->nr_to_write > 0) {
3000a1d6cc56SAneesh Kumar K.V 
3001a1d6cc56SAneesh Kumar K.V 		/*
3002a1d6cc56SAneesh Kumar K.V 		 * we  insert one extent at a time. So we need
3003a1d6cc56SAneesh Kumar K.V 		 * credit needed for single extent allocation.
3004a1d6cc56SAneesh Kumar K.V 		 * journalled mode is currently not supported
3005a1d6cc56SAneesh Kumar K.V 		 * by delalloc
3006a1d6cc56SAneesh Kumar K.V 		 */
3007a1d6cc56SAneesh Kumar K.V 		BUG_ON(ext4_should_journal_data(inode));
3008525f4ed8SMingming Cao 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
3009a1d6cc56SAneesh Kumar K.V 
301061628a3fSMingming Cao 		/* start a new transaction*/
301161628a3fSMingming Cao 		handle = ext4_journal_start(inode, needed_blocks);
301261628a3fSMingming Cao 		if (IS_ERR(handle)) {
301361628a3fSMingming Cao 			ret = PTR_ERR(handle);
30141693918eSTheodore Ts'o 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
3015fbe845ddSCurt Wohlgemuth 			       "%ld pages, ino %lu; err %d", __func__,
3016a1d6cc56SAneesh Kumar K.V 				wbc->nr_to_write, inode->i_ino, ret);
301761628a3fSMingming Cao 			goto out_writepages;
301861628a3fSMingming Cao 		}
3019f63e6005STheodore Ts'o 
3020f63e6005STheodore Ts'o 		/*
3021f63e6005STheodore Ts'o 		 * Now call __mpage_da_writepage to find the next
3022f63e6005STheodore Ts'o 		 * contiguous region of logical blocks that need
3023f63e6005STheodore Ts'o 		 * blocks to be allocated by ext4.  We don't actually
3024f63e6005STheodore Ts'o 		 * submit the blocks for I/O here, even though
3025f63e6005STheodore Ts'o 		 * write_cache_pages thinks it will, and will set the
3026f63e6005STheodore Ts'o 		 * pages as clean for write before calling
3027f63e6005STheodore Ts'o 		 * __mpage_da_writepage().
3028f63e6005STheodore Ts'o 		 */
3029f63e6005STheodore Ts'o 		mpd.b_size = 0;
3030f63e6005STheodore Ts'o 		mpd.b_state = 0;
3031f63e6005STheodore Ts'o 		mpd.b_blocknr = 0;
3032f63e6005STheodore Ts'o 		mpd.first_page = 0;
3033f63e6005STheodore Ts'o 		mpd.next_page = 0;
3034f63e6005STheodore Ts'o 		mpd.io_done = 0;
3035f63e6005STheodore Ts'o 		mpd.pages_written = 0;
3036f63e6005STheodore Ts'o 		mpd.retval = 0;
30378e48dcfbSTheodore Ts'o 		ret = write_cache_pages_da(mapping, wbc, &mpd);
3038f63e6005STheodore Ts'o 		/*
3039af901ca1SAndré Goddard Rosa 		 * If we have a contiguous extent of pages and we
3040f63e6005STheodore Ts'o 		 * haven't done the I/O yet, map the blocks and submit
3041f63e6005STheodore Ts'o 		 * them for I/O.
3042f63e6005STheodore Ts'o 		 */
3043f63e6005STheodore Ts'o 		if (!mpd.io_done && mpd.next_page != mpd.first_page) {
3044f63e6005STheodore Ts'o 			if (mpage_da_map_blocks(&mpd) == 0)
3045f63e6005STheodore Ts'o 				mpage_da_submit_io(&mpd);
3046f63e6005STheodore Ts'o 			mpd.io_done = 1;
3047f63e6005STheodore Ts'o 			ret = MPAGE_DA_EXTENT_TAIL;
3048f63e6005STheodore Ts'o 		}
3049b3a3ca8cSTheodore Ts'o 		trace_ext4_da_write_pages(inode, &mpd);
3050f63e6005STheodore Ts'o 		wbc->nr_to_write -= mpd.pages_written;
3051df22291fSAneesh Kumar K.V 
305261628a3fSMingming Cao 		ext4_journal_stop(handle);
3053df22291fSAneesh Kumar K.V 
30548f64b32eSEric Sandeen 		if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
305522208dedSAneesh Kumar K.V 			/* commit the transaction which would
305622208dedSAneesh Kumar K.V 			 * free blocks released in the transaction
305722208dedSAneesh Kumar K.V 			 * and try again
305822208dedSAneesh Kumar K.V 			 */
3059df22291fSAneesh Kumar K.V 			jbd2_journal_force_commit_nested(sbi->s_journal);
306022208dedSAneesh Kumar K.V 			wbc->pages_skipped = pages_skipped;
306122208dedSAneesh Kumar K.V 			ret = 0;
306222208dedSAneesh Kumar K.V 		} else if (ret == MPAGE_DA_EXTENT_TAIL) {
3063a1d6cc56SAneesh Kumar K.V 			/*
3064a1d6cc56SAneesh Kumar K.V 			 * got one extent now try with
3065a1d6cc56SAneesh Kumar K.V 			 * rest of the pages
3066a1d6cc56SAneesh Kumar K.V 			 */
306722208dedSAneesh Kumar K.V 			pages_written += mpd.pages_written;
306822208dedSAneesh Kumar K.V 			wbc->pages_skipped = pages_skipped;
3069a1d6cc56SAneesh Kumar K.V 			ret = 0;
30702acf2c26SAneesh Kumar K.V 			io_done = 1;
307122208dedSAneesh Kumar K.V 		} else if (wbc->nr_to_write)
307261628a3fSMingming Cao 			/*
307361628a3fSMingming Cao 			 * There is no more writeout needed
307461628a3fSMingming Cao 			 * or we requested for a noblocking writeout
307561628a3fSMingming Cao 			 * and we found the device congested
307661628a3fSMingming Cao 			 */
307761628a3fSMingming Cao 			break;
307861628a3fSMingming Cao 	}
30792acf2c26SAneesh Kumar K.V 	if (!io_done && !cycled) {
30802acf2c26SAneesh Kumar K.V 		cycled = 1;
30812acf2c26SAneesh Kumar K.V 		index = 0;
30822acf2c26SAneesh Kumar K.V 		wbc->range_start = index << PAGE_CACHE_SHIFT;
30832acf2c26SAneesh Kumar K.V 		wbc->range_end  = mapping->writeback_index - 1;
30842acf2c26SAneesh Kumar K.V 		goto retry;
30852acf2c26SAneesh Kumar K.V 	}
308622208dedSAneesh Kumar K.V 	if (pages_skipped != wbc->pages_skipped)
30871693918eSTheodore Ts'o 		ext4_msg(inode->i_sb, KERN_CRIT,
30881693918eSTheodore Ts'o 			 "This should not happen leaving %s "
3089fbe845ddSCurt Wohlgemuth 			 "with nr_to_write = %ld ret = %d",
309022208dedSAneesh Kumar K.V 			 __func__, wbc->nr_to_write, ret);
309161628a3fSMingming Cao 
309222208dedSAneesh Kumar K.V 	/* Update index */
309322208dedSAneesh Kumar K.V 	index += pages_written;
30942acf2c26SAneesh Kumar K.V 	wbc->range_cyclic = range_cyclic;
309522208dedSAneesh Kumar K.V 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
309622208dedSAneesh Kumar K.V 		/*
309722208dedSAneesh Kumar K.V 		 * set the writeback_index so that range_cyclic
309822208dedSAneesh Kumar K.V 		 * mode will write it back later
309922208dedSAneesh Kumar K.V 		 */
310022208dedSAneesh Kumar K.V 		mapping->writeback_index = index;
3101a1d6cc56SAneesh Kumar K.V 
310261628a3fSMingming Cao out_writepages:
310322208dedSAneesh Kumar K.V 	wbc->nr_to_write -= nr_to_writebump;
3104de89de6eSTheodore Ts'o 	wbc->range_start = range_start;
31059bffad1eSTheodore Ts'o 	trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
310661628a3fSMingming Cao 	return ret;
310764769240SAlex Tomas }
310864769240SAlex Tomas 
310979f0be8dSAneesh Kumar K.V #define FALL_BACK_TO_NONDELALLOC 1
311079f0be8dSAneesh Kumar K.V static int ext4_nonda_switch(struct super_block *sb)
311179f0be8dSAneesh Kumar K.V {
311279f0be8dSAneesh Kumar K.V 	s64 free_blocks, dirty_blocks;
311379f0be8dSAneesh Kumar K.V 	struct ext4_sb_info *sbi = EXT4_SB(sb);
311479f0be8dSAneesh Kumar K.V 
311579f0be8dSAneesh Kumar K.V 	/*
311679f0be8dSAneesh Kumar K.V 	 * switch to non delalloc mode if we are running low
311779f0be8dSAneesh Kumar K.V 	 * on free block. The free block accounting via percpu
3118179f7ebfSEric Dumazet 	 * counters can get slightly wrong with percpu_counter_batch getting
311979f0be8dSAneesh Kumar K.V 	 * accumulated on each CPU without updating global counters
312079f0be8dSAneesh Kumar K.V 	 * Delalloc need an accurate free block accounting. So switch
312179f0be8dSAneesh Kumar K.V 	 * to non delalloc when we are near to error range.
312279f0be8dSAneesh Kumar K.V 	 */
312379f0be8dSAneesh Kumar K.V 	free_blocks  = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
312479f0be8dSAneesh Kumar K.V 	dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
312579f0be8dSAneesh Kumar K.V 	if (2 * free_blocks < 3 * dirty_blocks ||
312679f0be8dSAneesh Kumar K.V 		free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
312779f0be8dSAneesh Kumar K.V 		/*
3128c8afb446SEric Sandeen 		 * free block count is less than 150% of dirty blocks
3129c8afb446SEric Sandeen 		 * or free blocks is less than watermark
313079f0be8dSAneesh Kumar K.V 		 */
313179f0be8dSAneesh Kumar K.V 		return 1;
313279f0be8dSAneesh Kumar K.V 	}
3133c8afb446SEric Sandeen 	/*
3134c8afb446SEric Sandeen 	 * Even if we don't switch but are nearing capacity,
3135c8afb446SEric Sandeen 	 * start pushing delalloc when 1/2 of free blocks are dirty.
3136c8afb446SEric Sandeen 	 */
3137c8afb446SEric Sandeen 	if (free_blocks < 2 * dirty_blocks)
3138c8afb446SEric Sandeen 		writeback_inodes_sb_if_idle(sb);
3139c8afb446SEric Sandeen 
314079f0be8dSAneesh Kumar K.V 	return 0;
314179f0be8dSAneesh Kumar K.V }
314279f0be8dSAneesh Kumar K.V 
314364769240SAlex Tomas static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
314464769240SAlex Tomas 			       loff_t pos, unsigned len, unsigned flags,
314564769240SAlex Tomas 			       struct page **pagep, void **fsdata)
314664769240SAlex Tomas {
314772b8ab9dSEric Sandeen 	int ret, retries = 0;
314864769240SAlex Tomas 	struct page *page;
314964769240SAlex Tomas 	pgoff_t index;
315064769240SAlex Tomas 	struct inode *inode = mapping->host;
315164769240SAlex Tomas 	handle_t *handle;
315264769240SAlex Tomas 
315364769240SAlex Tomas 	index = pos >> PAGE_CACHE_SHIFT;
315479f0be8dSAneesh Kumar K.V 
315579f0be8dSAneesh Kumar K.V 	if (ext4_nonda_switch(inode->i_sb)) {
315679f0be8dSAneesh Kumar K.V 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
315779f0be8dSAneesh Kumar K.V 		return ext4_write_begin(file, mapping, pos,
315879f0be8dSAneesh Kumar K.V 					len, flags, pagep, fsdata);
315979f0be8dSAneesh Kumar K.V 	}
316079f0be8dSAneesh Kumar K.V 	*fsdata = (void *)0;
31619bffad1eSTheodore Ts'o 	trace_ext4_da_write_begin(inode, pos, len, flags);
3162d2a17637SMingming Cao retry:
316364769240SAlex Tomas 	/*
316464769240SAlex Tomas 	 * With delayed allocation, we don't log the i_disksize update
316564769240SAlex Tomas 	 * if there is delayed block allocation. But we still need
316664769240SAlex Tomas 	 * to journalling the i_disksize update if writes to the end
316764769240SAlex Tomas 	 * of file which has an already mapped buffer.
316864769240SAlex Tomas 	 */
316964769240SAlex Tomas 	handle = ext4_journal_start(inode, 1);
317064769240SAlex Tomas 	if (IS_ERR(handle)) {
317164769240SAlex Tomas 		ret = PTR_ERR(handle);
317264769240SAlex Tomas 		goto out;
317364769240SAlex Tomas 	}
3174ebd3610bSJan Kara 	/* We cannot recurse into the filesystem as the transaction is already
3175ebd3610bSJan Kara 	 * started */
3176ebd3610bSJan Kara 	flags |= AOP_FLAG_NOFS;
317764769240SAlex Tomas 
317854566b2cSNick Piggin 	page = grab_cache_page_write_begin(mapping, index, flags);
3179d5a0d4f7SEric Sandeen 	if (!page) {
3180d5a0d4f7SEric Sandeen 		ext4_journal_stop(handle);
3181d5a0d4f7SEric Sandeen 		ret = -ENOMEM;
3182d5a0d4f7SEric Sandeen 		goto out;
3183d5a0d4f7SEric Sandeen 	}
318464769240SAlex Tomas 	*pagep = page;
318564769240SAlex Tomas 
318664769240SAlex Tomas 	ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
318764769240SAlex Tomas 				ext4_da_get_block_prep);
318864769240SAlex Tomas 	if (ret < 0) {
318964769240SAlex Tomas 		unlock_page(page);
319064769240SAlex Tomas 		ext4_journal_stop(handle);
319164769240SAlex Tomas 		page_cache_release(page);
3192ae4d5372SAneesh Kumar K.V 		/*
3193ae4d5372SAneesh Kumar K.V 		 * block_write_begin may have instantiated a few blocks
3194ae4d5372SAneesh Kumar K.V 		 * outside i_size.  Trim these off again. Don't need
3195ae4d5372SAneesh Kumar K.V 		 * i_size_read because we hold i_mutex.
3196ae4d5372SAneesh Kumar K.V 		 */
3197ae4d5372SAneesh Kumar K.V 		if (pos + len > inode->i_size)
3198b9a4207dSJan Kara 			ext4_truncate_failed_write(inode);
319964769240SAlex Tomas 	}
320064769240SAlex Tomas 
3201d2a17637SMingming Cao 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3202d2a17637SMingming Cao 		goto retry;
320364769240SAlex Tomas out:
320464769240SAlex Tomas 	return ret;
320564769240SAlex Tomas }
320664769240SAlex Tomas 
3207632eaeabSMingming Cao /*
3208632eaeabSMingming Cao  * Check if we should update i_disksize
3209632eaeabSMingming Cao  * when write to the end of file but not require block allocation
3210632eaeabSMingming Cao  */
3211632eaeabSMingming Cao static int ext4_da_should_update_i_disksize(struct page *page,
3212632eaeabSMingming Cao 					    unsigned long offset)
3213632eaeabSMingming Cao {
3214632eaeabSMingming Cao 	struct buffer_head *bh;
3215632eaeabSMingming Cao 	struct inode *inode = page->mapping->host;
3216632eaeabSMingming Cao 	unsigned int idx;
3217632eaeabSMingming Cao 	int i;
3218632eaeabSMingming Cao 
3219632eaeabSMingming Cao 	bh = page_buffers(page);
3220632eaeabSMingming Cao 	idx = offset >> inode->i_blkbits;
3221632eaeabSMingming Cao 
3222632eaeabSMingming Cao 	for (i = 0; i < idx; i++)
3223632eaeabSMingming Cao 		bh = bh->b_this_page;
3224632eaeabSMingming Cao 
322529fa89d0SAneesh Kumar K.V 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3226632eaeabSMingming Cao 		return 0;
3227632eaeabSMingming Cao 	return 1;
3228632eaeabSMingming Cao }
3229632eaeabSMingming Cao 
323064769240SAlex Tomas static int ext4_da_write_end(struct file *file,
323164769240SAlex Tomas 			     struct address_space *mapping,
323264769240SAlex Tomas 			     loff_t pos, unsigned len, unsigned copied,
323364769240SAlex Tomas 			     struct page *page, void *fsdata)
323464769240SAlex Tomas {
323564769240SAlex Tomas 	struct inode *inode = mapping->host;
323664769240SAlex Tomas 	int ret = 0, ret2;
323764769240SAlex Tomas 	handle_t *handle = ext4_journal_current_handle();
323864769240SAlex Tomas 	loff_t new_i_size;
3239632eaeabSMingming Cao 	unsigned long start, end;
324079f0be8dSAneesh Kumar K.V 	int write_mode = (int)(unsigned long)fsdata;
324179f0be8dSAneesh Kumar K.V 
324279f0be8dSAneesh Kumar K.V 	if (write_mode == FALL_BACK_TO_NONDELALLOC) {
324379f0be8dSAneesh Kumar K.V 		if (ext4_should_order_data(inode)) {
324479f0be8dSAneesh Kumar K.V 			return ext4_ordered_write_end(file, mapping, pos,
324579f0be8dSAneesh Kumar K.V 					len, copied, page, fsdata);
324679f0be8dSAneesh Kumar K.V 		} else if (ext4_should_writeback_data(inode)) {
324779f0be8dSAneesh Kumar K.V 			return ext4_writeback_write_end(file, mapping, pos,
324879f0be8dSAneesh Kumar K.V 					len, copied, page, fsdata);
324979f0be8dSAneesh Kumar K.V 		} else {
325079f0be8dSAneesh Kumar K.V 			BUG();
325179f0be8dSAneesh Kumar K.V 		}
325279f0be8dSAneesh Kumar K.V 	}
3253632eaeabSMingming Cao 
32549bffad1eSTheodore Ts'o 	trace_ext4_da_write_end(inode, pos, len, copied);
3255632eaeabSMingming Cao 	start = pos & (PAGE_CACHE_SIZE - 1);
3256632eaeabSMingming Cao 	end = start + copied - 1;
325764769240SAlex Tomas 
325864769240SAlex Tomas 	/*
325964769240SAlex Tomas 	 * generic_write_end() will run mark_inode_dirty() if i_size
326064769240SAlex Tomas 	 * changes.  So let's piggyback the i_disksize mark_inode_dirty
326164769240SAlex Tomas 	 * into that.
326264769240SAlex Tomas 	 */
326364769240SAlex Tomas 
326464769240SAlex Tomas 	new_i_size = pos + copied;
3265632eaeabSMingming Cao 	if (new_i_size > EXT4_I(inode)->i_disksize) {
3266632eaeabSMingming Cao 		if (ext4_da_should_update_i_disksize(page, end)) {
3267632eaeabSMingming Cao 			down_write(&EXT4_I(inode)->i_data_sem);
3268632eaeabSMingming Cao 			if (new_i_size > EXT4_I(inode)->i_disksize) {
326964769240SAlex Tomas 				/*
3270632eaeabSMingming Cao 				 * Updating i_disksize when extending file
3271632eaeabSMingming Cao 				 * without needing block allocation
327264769240SAlex Tomas 				 */
327364769240SAlex Tomas 				if (ext4_should_order_data(inode))
3274632eaeabSMingming Cao 					ret = ext4_jbd2_file_inode(handle,
3275632eaeabSMingming Cao 								   inode);
327664769240SAlex Tomas 
327764769240SAlex Tomas 				EXT4_I(inode)->i_disksize = new_i_size;
327864769240SAlex Tomas 			}
3279632eaeabSMingming Cao 			up_write(&EXT4_I(inode)->i_data_sem);
3280cf17fea6SAneesh Kumar K.V 			/* We need to mark inode dirty even if
3281cf17fea6SAneesh Kumar K.V 			 * new_i_size is less that inode->i_size
3282cf17fea6SAneesh Kumar K.V 			 * bu greater than i_disksize.(hint delalloc)
3283cf17fea6SAneesh Kumar K.V 			 */
3284cf17fea6SAneesh Kumar K.V 			ext4_mark_inode_dirty(handle, inode);
3285632eaeabSMingming Cao 		}
3286632eaeabSMingming Cao 	}
328764769240SAlex Tomas 	ret2 = generic_write_end(file, mapping, pos, len, copied,
328864769240SAlex Tomas 							page, fsdata);
328964769240SAlex Tomas 	copied = ret2;
329064769240SAlex Tomas 	if (ret2 < 0)
329164769240SAlex Tomas 		ret = ret2;
329264769240SAlex Tomas 	ret2 = ext4_journal_stop(handle);
329364769240SAlex Tomas 	if (!ret)
329464769240SAlex Tomas 		ret = ret2;
329564769240SAlex Tomas 
329664769240SAlex Tomas 	return ret ? ret : copied;
329764769240SAlex Tomas }
329864769240SAlex Tomas 
329964769240SAlex Tomas static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
330064769240SAlex Tomas {
330164769240SAlex Tomas 	/*
330264769240SAlex Tomas 	 * Drop reserved blocks
330364769240SAlex Tomas 	 */
330464769240SAlex Tomas 	BUG_ON(!PageLocked(page));
330564769240SAlex Tomas 	if (!page_has_buffers(page))
330664769240SAlex Tomas 		goto out;
330764769240SAlex Tomas 
3308d2a17637SMingming Cao 	ext4_da_page_release_reservation(page, offset);
330964769240SAlex Tomas 
331064769240SAlex Tomas out:
331164769240SAlex Tomas 	ext4_invalidatepage(page, offset);
331264769240SAlex Tomas 
331364769240SAlex Tomas 	return;
331464769240SAlex Tomas }
331564769240SAlex Tomas 
3316ccd2506bSTheodore Ts'o /*
3317ccd2506bSTheodore Ts'o  * Force all delayed allocation blocks to be allocated for a given inode.
3318ccd2506bSTheodore Ts'o  */
3319ccd2506bSTheodore Ts'o int ext4_alloc_da_blocks(struct inode *inode)
3320ccd2506bSTheodore Ts'o {
3321fb40ba0dSTheodore Ts'o 	trace_ext4_alloc_da_blocks(inode);
3322fb40ba0dSTheodore Ts'o 
3323ccd2506bSTheodore Ts'o 	if (!EXT4_I(inode)->i_reserved_data_blocks &&
3324ccd2506bSTheodore Ts'o 	    !EXT4_I(inode)->i_reserved_meta_blocks)
3325ccd2506bSTheodore Ts'o 		return 0;
3326ccd2506bSTheodore Ts'o 
3327ccd2506bSTheodore Ts'o 	/*
3328ccd2506bSTheodore Ts'o 	 * We do something simple for now.  The filemap_flush() will
3329ccd2506bSTheodore Ts'o 	 * also start triggering a write of the data blocks, which is
3330ccd2506bSTheodore Ts'o 	 * not strictly speaking necessary (and for users of
3331ccd2506bSTheodore Ts'o 	 * laptop_mode, not even desirable).  However, to do otherwise
3332ccd2506bSTheodore Ts'o 	 * would require replicating code paths in:
3333ccd2506bSTheodore Ts'o 	 *
3334ccd2506bSTheodore Ts'o 	 * ext4_da_writepages() ->
3335ccd2506bSTheodore Ts'o 	 *    write_cache_pages() ---> (via passed in callback function)
3336ccd2506bSTheodore Ts'o 	 *        __mpage_da_writepage() -->
3337ccd2506bSTheodore Ts'o 	 *           mpage_add_bh_to_extent()
3338ccd2506bSTheodore Ts'o 	 *           mpage_da_map_blocks()
3339ccd2506bSTheodore Ts'o 	 *
3340ccd2506bSTheodore Ts'o 	 * The problem is that write_cache_pages(), located in
3341ccd2506bSTheodore Ts'o 	 * mm/page-writeback.c, marks pages clean in preparation for
3342ccd2506bSTheodore Ts'o 	 * doing I/O, which is not desirable if we're not planning on
3343ccd2506bSTheodore Ts'o 	 * doing I/O at all.
3344ccd2506bSTheodore Ts'o 	 *
3345ccd2506bSTheodore Ts'o 	 * We could call write_cache_pages(), and then redirty all of
3346ccd2506bSTheodore Ts'o 	 * the pages by calling redirty_page_for_writeback() but that
3347ccd2506bSTheodore Ts'o 	 * would be ugly in the extreme.  So instead we would need to
3348ccd2506bSTheodore Ts'o 	 * replicate parts of the code in the above functions,
3349ccd2506bSTheodore Ts'o 	 * simplifying them becuase we wouldn't actually intend to
3350ccd2506bSTheodore Ts'o 	 * write out the pages, but rather only collect contiguous
3351ccd2506bSTheodore Ts'o 	 * logical block extents, call the multi-block allocator, and
3352ccd2506bSTheodore Ts'o 	 * then update the buffer heads with the block allocations.
3353ccd2506bSTheodore Ts'o 	 *
3354ccd2506bSTheodore Ts'o 	 * For now, though, we'll cheat by calling filemap_flush(),
3355ccd2506bSTheodore Ts'o 	 * which will map the blocks, and start the I/O, but not
3356ccd2506bSTheodore Ts'o 	 * actually wait for the I/O to complete.
3357ccd2506bSTheodore Ts'o 	 */
3358ccd2506bSTheodore Ts'o 	return filemap_flush(inode->i_mapping);
3359ccd2506bSTheodore Ts'o }
336064769240SAlex Tomas 
336164769240SAlex Tomas /*
3362ac27a0ecSDave Kleikamp  * bmap() is special.  It gets used by applications such as lilo and by
3363ac27a0ecSDave Kleikamp  * the swapper to find the on-disk block of a specific piece of data.
3364ac27a0ecSDave Kleikamp  *
3365ac27a0ecSDave Kleikamp  * Naturally, this is dangerous if the block concerned is still in the
3366617ba13bSMingming Cao  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3367ac27a0ecSDave Kleikamp  * filesystem and enables swap, then they may get a nasty shock when the
3368ac27a0ecSDave Kleikamp  * data getting swapped to that swapfile suddenly gets overwritten by
3369ac27a0ecSDave Kleikamp  * the original zero's written out previously to the journal and
3370ac27a0ecSDave Kleikamp  * awaiting writeback in the kernel's buffer cache.
3371ac27a0ecSDave Kleikamp  *
3372ac27a0ecSDave Kleikamp  * So, if we see any bmap calls here on a modified, data-journaled file,
3373ac27a0ecSDave Kleikamp  * take extra steps to flush any blocks which might be in the cache.
3374ac27a0ecSDave Kleikamp  */
3375617ba13bSMingming Cao static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3376ac27a0ecSDave Kleikamp {
3377ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
3378ac27a0ecSDave Kleikamp 	journal_t *journal;
3379ac27a0ecSDave Kleikamp 	int err;
3380ac27a0ecSDave Kleikamp 
338164769240SAlex Tomas 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
338264769240SAlex Tomas 			test_opt(inode->i_sb, DELALLOC)) {
338364769240SAlex Tomas 		/*
338464769240SAlex Tomas 		 * With delalloc we want to sync the file
338564769240SAlex Tomas 		 * so that we can make sure we allocate
338664769240SAlex Tomas 		 * blocks for file
338764769240SAlex Tomas 		 */
338864769240SAlex Tomas 		filemap_write_and_wait(mapping);
338964769240SAlex Tomas 	}
339064769240SAlex Tomas 
339119f5fb7aSTheodore Ts'o 	if (EXT4_JOURNAL(inode) &&
339219f5fb7aSTheodore Ts'o 	    ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3393ac27a0ecSDave Kleikamp 		/*
3394ac27a0ecSDave Kleikamp 		 * This is a REALLY heavyweight approach, but the use of
3395ac27a0ecSDave Kleikamp 		 * bmap on dirty files is expected to be extremely rare:
3396ac27a0ecSDave Kleikamp 		 * only if we run lilo or swapon on a freshly made file
3397ac27a0ecSDave Kleikamp 		 * do we expect this to happen.
3398ac27a0ecSDave Kleikamp 		 *
3399ac27a0ecSDave Kleikamp 		 * (bmap requires CAP_SYS_RAWIO so this does not
3400ac27a0ecSDave Kleikamp 		 * represent an unprivileged user DOS attack --- we'd be
3401ac27a0ecSDave Kleikamp 		 * in trouble if mortal users could trigger this path at
3402ac27a0ecSDave Kleikamp 		 * will.)
3403ac27a0ecSDave Kleikamp 		 *
3404617ba13bSMingming Cao 		 * NB. EXT4_STATE_JDATA is not set on files other than
3405ac27a0ecSDave Kleikamp 		 * regular files.  If somebody wants to bmap a directory
3406ac27a0ecSDave Kleikamp 		 * or symlink and gets confused because the buffer
3407ac27a0ecSDave Kleikamp 		 * hasn't yet been flushed to disk, they deserve
3408ac27a0ecSDave Kleikamp 		 * everything they get.
3409ac27a0ecSDave Kleikamp 		 */
3410ac27a0ecSDave Kleikamp 
341119f5fb7aSTheodore Ts'o 		ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3412617ba13bSMingming Cao 		journal = EXT4_JOURNAL(inode);
3413dab291afSMingming Cao 		jbd2_journal_lock_updates(journal);
3414dab291afSMingming Cao 		err = jbd2_journal_flush(journal);
3415dab291afSMingming Cao 		jbd2_journal_unlock_updates(journal);
3416ac27a0ecSDave Kleikamp 
3417ac27a0ecSDave Kleikamp 		if (err)
3418ac27a0ecSDave Kleikamp 			return 0;
3419ac27a0ecSDave Kleikamp 	}
3420ac27a0ecSDave Kleikamp 
3421617ba13bSMingming Cao 	return generic_block_bmap(mapping, block, ext4_get_block);
3422ac27a0ecSDave Kleikamp }
3423ac27a0ecSDave Kleikamp 
3424617ba13bSMingming Cao static int ext4_readpage(struct file *file, struct page *page)
3425ac27a0ecSDave Kleikamp {
3426617ba13bSMingming Cao 	return mpage_readpage(page, ext4_get_block);
3427ac27a0ecSDave Kleikamp }
3428ac27a0ecSDave Kleikamp 
3429ac27a0ecSDave Kleikamp static int
3430617ba13bSMingming Cao ext4_readpages(struct file *file, struct address_space *mapping,
3431ac27a0ecSDave Kleikamp 		struct list_head *pages, unsigned nr_pages)
3432ac27a0ecSDave Kleikamp {
3433617ba13bSMingming Cao 	return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
3434ac27a0ecSDave Kleikamp }
3435ac27a0ecSDave Kleikamp 
3436744692dcSJiaying Zhang static void ext4_free_io_end(ext4_io_end_t *io)
3437744692dcSJiaying Zhang {
3438744692dcSJiaying Zhang 	BUG_ON(!io);
3439744692dcSJiaying Zhang 	if (io->page)
3440744692dcSJiaying Zhang 		put_page(io->page);
3441744692dcSJiaying Zhang 	iput(io->inode);
3442744692dcSJiaying Zhang 	kfree(io);
3443744692dcSJiaying Zhang }
3444744692dcSJiaying Zhang 
3445744692dcSJiaying Zhang static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
3446744692dcSJiaying Zhang {
3447744692dcSJiaying Zhang 	struct buffer_head *head, *bh;
3448744692dcSJiaying Zhang 	unsigned int curr_off = 0;
3449744692dcSJiaying Zhang 
3450744692dcSJiaying Zhang 	if (!page_has_buffers(page))
3451744692dcSJiaying Zhang 		return;
3452744692dcSJiaying Zhang 	head = bh = page_buffers(page);
3453744692dcSJiaying Zhang 	do {
3454744692dcSJiaying Zhang 		if (offset <= curr_off && test_clear_buffer_uninit(bh)
3455744692dcSJiaying Zhang 					&& bh->b_private) {
3456744692dcSJiaying Zhang 			ext4_free_io_end(bh->b_private);
3457744692dcSJiaying Zhang 			bh->b_private = NULL;
3458744692dcSJiaying Zhang 			bh->b_end_io = NULL;
3459744692dcSJiaying Zhang 		}
3460744692dcSJiaying Zhang 		curr_off = curr_off + bh->b_size;
3461744692dcSJiaying Zhang 		bh = bh->b_this_page;
3462744692dcSJiaying Zhang 	} while (bh != head);
3463744692dcSJiaying Zhang }
3464744692dcSJiaying Zhang 
3465617ba13bSMingming Cao static void ext4_invalidatepage(struct page *page, unsigned long offset)
3466ac27a0ecSDave Kleikamp {
3467617ba13bSMingming Cao 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3468ac27a0ecSDave Kleikamp 
3469ac27a0ecSDave Kleikamp 	/*
3470744692dcSJiaying Zhang 	 * free any io_end structure allocated for buffers to be discarded
3471744692dcSJiaying Zhang 	 */
3472744692dcSJiaying Zhang 	if (ext4_should_dioread_nolock(page->mapping->host))
3473744692dcSJiaying Zhang 		ext4_invalidatepage_free_endio(page, offset);
3474744692dcSJiaying Zhang 	/*
3475ac27a0ecSDave Kleikamp 	 * If it's a full truncate we just forget about the pending dirtying
3476ac27a0ecSDave Kleikamp 	 */
3477ac27a0ecSDave Kleikamp 	if (offset == 0)
3478ac27a0ecSDave Kleikamp 		ClearPageChecked(page);
3479ac27a0ecSDave Kleikamp 
34800390131bSFrank Mayhar 	if (journal)
3481dab291afSMingming Cao 		jbd2_journal_invalidatepage(journal, page, offset);
34820390131bSFrank Mayhar 	else
34830390131bSFrank Mayhar 		block_invalidatepage(page, offset);
3484ac27a0ecSDave Kleikamp }
3485ac27a0ecSDave Kleikamp 
3486617ba13bSMingming Cao static int ext4_releasepage(struct page *page, gfp_t wait)
3487ac27a0ecSDave Kleikamp {
3488617ba13bSMingming Cao 	journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3489ac27a0ecSDave Kleikamp 
3490ac27a0ecSDave Kleikamp 	WARN_ON(PageChecked(page));
3491ac27a0ecSDave Kleikamp 	if (!page_has_buffers(page))
3492ac27a0ecSDave Kleikamp 		return 0;
34930390131bSFrank Mayhar 	if (journal)
3494dab291afSMingming Cao 		return jbd2_journal_try_to_free_buffers(journal, page, wait);
34950390131bSFrank Mayhar 	else
34960390131bSFrank Mayhar 		return try_to_free_buffers(page);
3497ac27a0ecSDave Kleikamp }
3498ac27a0ecSDave Kleikamp 
3499ac27a0ecSDave Kleikamp /*
35004c0425ffSMingming Cao  * O_DIRECT for ext3 (or indirect map) based files
35014c0425ffSMingming Cao  *
3502ac27a0ecSDave Kleikamp  * If the O_DIRECT write will extend the file then add this inode to the
3503ac27a0ecSDave Kleikamp  * orphan list.  So recovery will truncate it back to the original size
3504ac27a0ecSDave Kleikamp  * if the machine crashes during the write.
3505ac27a0ecSDave Kleikamp  *
3506ac27a0ecSDave Kleikamp  * If the O_DIRECT write is intantiating holes inside i_size and the machine
35077fb5409dSJan Kara  * crashes then stale disk data _may_ be exposed inside the file. But current
35087fb5409dSJan Kara  * VFS code falls back into buffered path in that case so we are safe.
3509ac27a0ecSDave Kleikamp  */
35104c0425ffSMingming Cao static ssize_t ext4_ind_direct_IO(int rw, struct kiocb *iocb,
3511ac27a0ecSDave Kleikamp 			      const struct iovec *iov, loff_t offset,
3512ac27a0ecSDave Kleikamp 			      unsigned long nr_segs)
3513ac27a0ecSDave Kleikamp {
3514ac27a0ecSDave Kleikamp 	struct file *file = iocb->ki_filp;
3515ac27a0ecSDave Kleikamp 	struct inode *inode = file->f_mapping->host;
3516617ba13bSMingming Cao 	struct ext4_inode_info *ei = EXT4_I(inode);
35177fb5409dSJan Kara 	handle_t *handle;
3518ac27a0ecSDave Kleikamp 	ssize_t ret;
3519ac27a0ecSDave Kleikamp 	int orphan = 0;
3520ac27a0ecSDave Kleikamp 	size_t count = iov_length(iov, nr_segs);
3521fbbf6945SEric Sandeen 	int retries = 0;
3522ac27a0ecSDave Kleikamp 
3523ac27a0ecSDave Kleikamp 	if (rw == WRITE) {
3524ac27a0ecSDave Kleikamp 		loff_t final_size = offset + count;
3525ac27a0ecSDave Kleikamp 
35267fb5409dSJan Kara 		if (final_size > inode->i_size) {
35277fb5409dSJan Kara 			/* Credits for sb + inode write */
35287fb5409dSJan Kara 			handle = ext4_journal_start(inode, 2);
3529ac27a0ecSDave Kleikamp 			if (IS_ERR(handle)) {
3530ac27a0ecSDave Kleikamp 				ret = PTR_ERR(handle);
3531ac27a0ecSDave Kleikamp 				goto out;
3532ac27a0ecSDave Kleikamp 			}
3533617ba13bSMingming Cao 			ret = ext4_orphan_add(handle, inode);
35347fb5409dSJan Kara 			if (ret) {
35357fb5409dSJan Kara 				ext4_journal_stop(handle);
35367fb5409dSJan Kara 				goto out;
35377fb5409dSJan Kara 			}
3538ac27a0ecSDave Kleikamp 			orphan = 1;
3539ac27a0ecSDave Kleikamp 			ei->i_disksize = inode->i_size;
35407fb5409dSJan Kara 			ext4_journal_stop(handle);
3541ac27a0ecSDave Kleikamp 		}
3542ac27a0ecSDave Kleikamp 	}
3543ac27a0ecSDave Kleikamp 
3544fbbf6945SEric Sandeen retry:
3545b7adc1f3SJiaying Zhang 	if (rw == READ && ext4_should_dioread_nolock(inode))
3546b7adc1f3SJiaying Zhang 		ret = blockdev_direct_IO_no_locking(rw, iocb, inode,
3547b7adc1f3SJiaying Zhang 				 inode->i_sb->s_bdev, iov,
3548b7adc1f3SJiaying Zhang 				 offset, nr_segs,
3549b7adc1f3SJiaying Zhang 				 ext4_get_block, NULL);
3550b7adc1f3SJiaying Zhang 	else
3551b7adc1f3SJiaying Zhang 		ret = blockdev_direct_IO(rw, iocb, inode,
3552b7adc1f3SJiaying Zhang 				 inode->i_sb->s_bdev, iov,
3553ac27a0ecSDave Kleikamp 				 offset, nr_segs,
3554617ba13bSMingming Cao 				 ext4_get_block, NULL);
3555fbbf6945SEric Sandeen 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3556fbbf6945SEric Sandeen 		goto retry;
3557ac27a0ecSDave Kleikamp 
35587fb5409dSJan Kara 	if (orphan) {
3559ac27a0ecSDave Kleikamp 		int err;
3560ac27a0ecSDave Kleikamp 
35617fb5409dSJan Kara 		/* Credits for sb + inode write */
35627fb5409dSJan Kara 		handle = ext4_journal_start(inode, 2);
35637fb5409dSJan Kara 		if (IS_ERR(handle)) {
35647fb5409dSJan Kara 			/* This is really bad luck. We've written the data
35657fb5409dSJan Kara 			 * but cannot extend i_size. Bail out and pretend
35667fb5409dSJan Kara 			 * the write failed... */
35677fb5409dSJan Kara 			ret = PTR_ERR(handle);
3568da1dafcaSDmitry Monakhov 			if (inode->i_nlink)
3569da1dafcaSDmitry Monakhov 				ext4_orphan_del(NULL, inode);
3570da1dafcaSDmitry Monakhov 
35717fb5409dSJan Kara 			goto out;
35727fb5409dSJan Kara 		}
35737fb5409dSJan Kara 		if (inode->i_nlink)
3574617ba13bSMingming Cao 			ext4_orphan_del(handle, inode);
35757fb5409dSJan Kara 		if (ret > 0) {
3576ac27a0ecSDave Kleikamp 			loff_t end = offset + ret;
3577ac27a0ecSDave Kleikamp 			if (end > inode->i_size) {
3578ac27a0ecSDave Kleikamp 				ei->i_disksize = end;
3579ac27a0ecSDave Kleikamp 				i_size_write(inode, end);
3580ac27a0ecSDave Kleikamp 				/*
3581ac27a0ecSDave Kleikamp 				 * We're going to return a positive `ret'
3582ac27a0ecSDave Kleikamp 				 * here due to non-zero-length I/O, so there's
3583ac27a0ecSDave Kleikamp 				 * no way of reporting error returns from
3584617ba13bSMingming Cao 				 * ext4_mark_inode_dirty() to userspace.  So
3585ac27a0ecSDave Kleikamp 				 * ignore it.
3586ac27a0ecSDave Kleikamp 				 */
3587617ba13bSMingming Cao 				ext4_mark_inode_dirty(handle, inode);
3588ac27a0ecSDave Kleikamp 			}
3589ac27a0ecSDave Kleikamp 		}
3590617ba13bSMingming Cao 		err = ext4_journal_stop(handle);
3591ac27a0ecSDave Kleikamp 		if (ret == 0)
3592ac27a0ecSDave Kleikamp 			ret = err;
3593ac27a0ecSDave Kleikamp 	}
3594ac27a0ecSDave Kleikamp out:
3595ac27a0ecSDave Kleikamp 	return ret;
3596ac27a0ecSDave Kleikamp }
3597ac27a0ecSDave Kleikamp 
35982ed88685STheodore Ts'o /*
35992ed88685STheodore Ts'o  * ext4_get_block used when preparing for a DIO write or buffer write.
36002ed88685STheodore Ts'o  * We allocate an uinitialized extent if blocks haven't been allocated.
36012ed88685STheodore Ts'o  * The extent will be converted to initialized after the IO is complete.
36022ed88685STheodore Ts'o  */
3603c7064ef1SJiaying Zhang static int ext4_get_block_write(struct inode *inode, sector_t iblock,
36044c0425ffSMingming Cao 		   struct buffer_head *bh_result, int create)
36054c0425ffSMingming Cao {
3606c7064ef1SJiaying Zhang 	ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
36078d5d02e6SMingming Cao 		   inode->i_ino, create);
36082ed88685STheodore Ts'o 	return _ext4_get_block(inode, iblock, bh_result,
36092ed88685STheodore Ts'o 			       EXT4_GET_BLOCKS_IO_CREATE_EXT);
36104c0425ffSMingming Cao }
36114c0425ffSMingming Cao 
3612c7064ef1SJiaying Zhang static void dump_completed_IO(struct inode * inode)
36138d5d02e6SMingming Cao {
36148d5d02e6SMingming Cao #ifdef	EXT4_DEBUG
36158d5d02e6SMingming Cao 	struct list_head *cur, *before, *after;
36168d5d02e6SMingming Cao 	ext4_io_end_t *io, *io0, *io1;
3617744692dcSJiaying Zhang 	unsigned long flags;
36188d5d02e6SMingming Cao 
3619c7064ef1SJiaying Zhang 	if (list_empty(&EXT4_I(inode)->i_completed_io_list)){
3620c7064ef1SJiaying Zhang 		ext4_debug("inode %lu completed_io list is empty\n", inode->i_ino);
36218d5d02e6SMingming Cao 		return;
36228d5d02e6SMingming Cao 	}
36238d5d02e6SMingming Cao 
3624c7064ef1SJiaying Zhang 	ext4_debug("Dump inode %lu completed_io list \n", inode->i_ino);
3625744692dcSJiaying Zhang 	spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
3626c7064ef1SJiaying Zhang 	list_for_each_entry(io, &EXT4_I(inode)->i_completed_io_list, list){
36278d5d02e6SMingming Cao 		cur = &io->list;
36288d5d02e6SMingming Cao 		before = cur->prev;
36298d5d02e6SMingming Cao 		io0 = container_of(before, ext4_io_end_t, list);
36308d5d02e6SMingming Cao 		after = cur->next;
36318d5d02e6SMingming Cao 		io1 = container_of(after, ext4_io_end_t, list);
36328d5d02e6SMingming Cao 
36338d5d02e6SMingming Cao 		ext4_debug("io 0x%p from inode %lu,prev 0x%p,next 0x%p\n",
36348d5d02e6SMingming Cao 			    io, inode->i_ino, io0, io1);
36358d5d02e6SMingming Cao 	}
3636744692dcSJiaying Zhang 	spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
36378d5d02e6SMingming Cao #endif
36388d5d02e6SMingming Cao }
36394c0425ffSMingming Cao 
36404c0425ffSMingming Cao /*
36414c0425ffSMingming Cao  * check a range of space and convert unwritten extents to written.
36424c0425ffSMingming Cao  */
3643c7064ef1SJiaying Zhang static int ext4_end_io_nolock(ext4_io_end_t *io)
36444c0425ffSMingming Cao {
36454c0425ffSMingming Cao 	struct inode *inode = io->inode;
36464c0425ffSMingming Cao 	loff_t offset = io->offset;
3647a1de02dcSEric Sandeen 	ssize_t size = io->size;
36484c0425ffSMingming Cao 	int ret = 0;
36494c0425ffSMingming Cao 
3650c7064ef1SJiaying Zhang 	ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p,"
36518d5d02e6SMingming Cao 		   "list->prev 0x%p\n",
36528d5d02e6SMingming Cao 	           io, inode->i_ino, io->list.next, io->list.prev);
36538d5d02e6SMingming Cao 
36548d5d02e6SMingming Cao 	if (list_empty(&io->list))
36558d5d02e6SMingming Cao 		return ret;
36568d5d02e6SMingming Cao 
3657c7064ef1SJiaying Zhang 	if (io->flag != EXT4_IO_UNWRITTEN)
36588d5d02e6SMingming Cao 		return ret;
36598d5d02e6SMingming Cao 
36604c0425ffSMingming Cao 	ret = ext4_convert_unwritten_extents(inode, offset, size);
36618d5d02e6SMingming Cao 	if (ret < 0) {
36624c0425ffSMingming Cao 		printk(KERN_EMERG "%s: failed to convert unwritten"
36638d5d02e6SMingming Cao 			"extents to written extents, error is %d"
36648d5d02e6SMingming Cao 			" io is still on inode %lu aio dio list\n",
36658d5d02e6SMingming Cao                        __func__, ret, inode->i_ino);
36668d5d02e6SMingming Cao 		return ret;
36674c0425ffSMingming Cao 	}
36684c0425ffSMingming Cao 
36698d5d02e6SMingming Cao 	/* clear the DIO AIO unwritten flag */
36708d5d02e6SMingming Cao 	io->flag = 0;
36718d5d02e6SMingming Cao 	return ret;
36728d5d02e6SMingming Cao }
3673c7064ef1SJiaying Zhang 
36748d5d02e6SMingming Cao /*
36758d5d02e6SMingming Cao  * work on completed aio dio IO, to convert unwritten extents to extents
36768d5d02e6SMingming Cao  */
3677c7064ef1SJiaying Zhang static void ext4_end_io_work(struct work_struct *work)
36788d5d02e6SMingming Cao {
36798d5d02e6SMingming Cao 	ext4_io_end_t		*io = container_of(work, ext4_io_end_t, work);
36808d5d02e6SMingming Cao 	struct inode		*inode = io->inode;
3681744692dcSJiaying Zhang 	struct ext4_inode_info	*ei = EXT4_I(inode);
3682744692dcSJiaying Zhang 	unsigned long		flags;
3683744692dcSJiaying Zhang 	int			ret;
36848d5d02e6SMingming Cao 
36858d5d02e6SMingming Cao 	mutex_lock(&inode->i_mutex);
3686c7064ef1SJiaying Zhang 	ret = ext4_end_io_nolock(io);
3687744692dcSJiaying Zhang 	if (ret < 0) {
3688744692dcSJiaying Zhang 		mutex_unlock(&inode->i_mutex);
3689744692dcSJiaying Zhang 		return;
3690744692dcSJiaying Zhang 	}
3691744692dcSJiaying Zhang 
3692744692dcSJiaying Zhang 	spin_lock_irqsave(&ei->i_completed_io_lock, flags);
36938d5d02e6SMingming Cao 	if (!list_empty(&io->list))
36948d5d02e6SMingming Cao 		list_del_init(&io->list);
3695744692dcSJiaying Zhang 	spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
36968d5d02e6SMingming Cao 	mutex_unlock(&inode->i_mutex);
3697744692dcSJiaying Zhang 	ext4_free_io_end(io);
36988d5d02e6SMingming Cao }
3699c7064ef1SJiaying Zhang 
37008d5d02e6SMingming Cao /*
37018d5d02e6SMingming Cao  * This function is called from ext4_sync_file().
37028d5d02e6SMingming Cao  *
3703c7064ef1SJiaying Zhang  * When IO is completed, the work to convert unwritten extents to
3704c7064ef1SJiaying Zhang  * written is queued on workqueue but may not get immediately
37058d5d02e6SMingming Cao  * scheduled. When fsync is called, we need to ensure the
37068d5d02e6SMingming Cao  * conversion is complete before fsync returns.
3707c7064ef1SJiaying Zhang  * The inode keeps track of a list of pending/completed IO that
3708c7064ef1SJiaying Zhang  * might needs to do the conversion. This function walks through
3709c7064ef1SJiaying Zhang  * the list and convert the related unwritten extents for completed IO
3710c7064ef1SJiaying Zhang  * to written.
3711c7064ef1SJiaying Zhang  * The function return the number of pending IOs on success.
37128d5d02e6SMingming Cao  */
3713c7064ef1SJiaying Zhang int flush_completed_IO(struct inode *inode)
37148d5d02e6SMingming Cao {
37158d5d02e6SMingming Cao 	ext4_io_end_t *io;
3716744692dcSJiaying Zhang 	struct ext4_inode_info *ei = EXT4_I(inode);
3717744692dcSJiaying Zhang 	unsigned long flags;
37188d5d02e6SMingming Cao 	int ret = 0;
37198d5d02e6SMingming Cao 	int ret2 = 0;
37208d5d02e6SMingming Cao 
3721744692dcSJiaying Zhang 	if (list_empty(&ei->i_completed_io_list))
37228d5d02e6SMingming Cao 		return ret;
37238d5d02e6SMingming Cao 
3724c7064ef1SJiaying Zhang 	dump_completed_IO(inode);
3725744692dcSJiaying Zhang 	spin_lock_irqsave(&ei->i_completed_io_lock, flags);
3726744692dcSJiaying Zhang 	while (!list_empty(&ei->i_completed_io_list)){
3727744692dcSJiaying Zhang 		io = list_entry(ei->i_completed_io_list.next,
37288d5d02e6SMingming Cao 				ext4_io_end_t, list);
37298d5d02e6SMingming Cao 		/*
3730c7064ef1SJiaying Zhang 		 * Calling ext4_end_io_nolock() to convert completed
37318d5d02e6SMingming Cao 		 * IO to written.
37328d5d02e6SMingming Cao 		 *
37338d5d02e6SMingming Cao 		 * When ext4_sync_file() is called, run_queue() may already
37348d5d02e6SMingming Cao 		 * about to flush the work corresponding to this io structure.
37358d5d02e6SMingming Cao 		 * It will be upset if it founds the io structure related
37368d5d02e6SMingming Cao 		 * to the work-to-be schedule is freed.
37378d5d02e6SMingming Cao 		 *
37388d5d02e6SMingming Cao 		 * Thus we need to keep the io structure still valid here after
37398d5d02e6SMingming Cao 		 * convertion finished. The io structure has a flag to
37408d5d02e6SMingming Cao 		 * avoid double converting from both fsync and background work
37418d5d02e6SMingming Cao 		 * queue work.
37428d5d02e6SMingming Cao 		 */
3743744692dcSJiaying Zhang 		spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
3744c7064ef1SJiaying Zhang 		ret = ext4_end_io_nolock(io);
3745744692dcSJiaying Zhang 		spin_lock_irqsave(&ei->i_completed_io_lock, flags);
37468d5d02e6SMingming Cao 		if (ret < 0)
37478d5d02e6SMingming Cao 			ret2 = ret;
37488d5d02e6SMingming Cao 		else
37498d5d02e6SMingming Cao 			list_del_init(&io->list);
37508d5d02e6SMingming Cao 	}
3751744692dcSJiaying Zhang 	spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
37528d5d02e6SMingming Cao 	return (ret2 < 0) ? ret2 : 0;
37538d5d02e6SMingming Cao }
37548d5d02e6SMingming Cao 
3755744692dcSJiaying Zhang static ext4_io_end_t *ext4_init_io_end (struct inode *inode, gfp_t flags)
37564c0425ffSMingming Cao {
37574c0425ffSMingming Cao 	ext4_io_end_t *io = NULL;
37584c0425ffSMingming Cao 
3759744692dcSJiaying Zhang 	io = kmalloc(sizeof(*io), flags);
37604c0425ffSMingming Cao 
37614c0425ffSMingming Cao 	if (io) {
37628d5d02e6SMingming Cao 		igrab(inode);
37634c0425ffSMingming Cao 		io->inode = inode;
37648d5d02e6SMingming Cao 		io->flag = 0;
37654c0425ffSMingming Cao 		io->offset = 0;
37664c0425ffSMingming Cao 		io->size = 0;
3767744692dcSJiaying Zhang 		io->page = NULL;
3768c7064ef1SJiaying Zhang 		INIT_WORK(&io->work, ext4_end_io_work);
37698d5d02e6SMingming Cao 		INIT_LIST_HEAD(&io->list);
37704c0425ffSMingming Cao 	}
37714c0425ffSMingming Cao 
37724c0425ffSMingming Cao 	return io;
37734c0425ffSMingming Cao }
37744c0425ffSMingming Cao 
37754c0425ffSMingming Cao static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
37764c0425ffSMingming Cao 			    ssize_t size, void *private)
37774c0425ffSMingming Cao {
37784c0425ffSMingming Cao         ext4_io_end_t *io_end = iocb->private;
37794c0425ffSMingming Cao 	struct workqueue_struct *wq;
3780744692dcSJiaying Zhang 	unsigned long flags;
3781744692dcSJiaying Zhang 	struct ext4_inode_info *ei;
37824c0425ffSMingming Cao 
37834b70df18SMingming 	/* if not async direct IO or dio with 0 bytes write, just return */
37844b70df18SMingming 	if (!io_end || !size)
37854b70df18SMingming 		return;
37864b70df18SMingming 
37878d5d02e6SMingming Cao 	ext_debug("ext4_end_io_dio(): io_end 0x%p"
37888d5d02e6SMingming Cao 		  "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
37898d5d02e6SMingming Cao  		  iocb->private, io_end->inode->i_ino, iocb, offset,
37908d5d02e6SMingming Cao 		  size);
37918d5d02e6SMingming Cao 
37928d5d02e6SMingming Cao 	/* if not aio dio with unwritten extents, just free io and return */
3793c7064ef1SJiaying Zhang 	if (io_end->flag != EXT4_IO_UNWRITTEN){
37948d5d02e6SMingming Cao 		ext4_free_io_end(io_end);
37958d5d02e6SMingming Cao 		iocb->private = NULL;
37968d5d02e6SMingming Cao 		return;
37978d5d02e6SMingming Cao 	}
37988d5d02e6SMingming Cao 
37994c0425ffSMingming Cao 	io_end->offset = offset;
38004c0425ffSMingming Cao 	io_end->size = size;
3801744692dcSJiaying Zhang 	io_end->flag = EXT4_IO_UNWRITTEN;
38024c0425ffSMingming Cao 	wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
38034c0425ffSMingming Cao 
38048d5d02e6SMingming Cao 	/* queue the work to convert unwritten extents to written */
38054c0425ffSMingming Cao 	queue_work(wq, &io_end->work);
38064c0425ffSMingming Cao 
38078d5d02e6SMingming Cao 	/* Add the io_end to per-inode completed aio dio list*/
3808744692dcSJiaying Zhang 	ei = EXT4_I(io_end->inode);
3809744692dcSJiaying Zhang 	spin_lock_irqsave(&ei->i_completed_io_lock, flags);
3810744692dcSJiaying Zhang 	list_add_tail(&io_end->list, &ei->i_completed_io_list);
3811744692dcSJiaying Zhang 	spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
38124c0425ffSMingming Cao 	iocb->private = NULL;
38134c0425ffSMingming Cao }
3814c7064ef1SJiaying Zhang 
3815744692dcSJiaying Zhang static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
3816744692dcSJiaying Zhang {
3817744692dcSJiaying Zhang 	ext4_io_end_t *io_end = bh->b_private;
3818744692dcSJiaying Zhang 	struct workqueue_struct *wq;
3819744692dcSJiaying Zhang 	struct inode *inode;
3820744692dcSJiaying Zhang 	unsigned long flags;
3821744692dcSJiaying Zhang 
3822744692dcSJiaying Zhang 	if (!test_clear_buffer_uninit(bh) || !io_end)
3823744692dcSJiaying Zhang 		goto out;
3824744692dcSJiaying Zhang 
3825744692dcSJiaying Zhang 	if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
3826744692dcSJiaying Zhang 		printk("sb umounted, discard end_io request for inode %lu\n",
3827744692dcSJiaying Zhang 			io_end->inode->i_ino);
3828744692dcSJiaying Zhang 		ext4_free_io_end(io_end);
3829744692dcSJiaying Zhang 		goto out;
3830744692dcSJiaying Zhang 	}
3831744692dcSJiaying Zhang 
3832744692dcSJiaying Zhang 	io_end->flag = EXT4_IO_UNWRITTEN;
3833744692dcSJiaying Zhang 	inode = io_end->inode;
3834744692dcSJiaying Zhang 
3835744692dcSJiaying Zhang 	/* Add the io_end to per-inode completed io list*/
3836744692dcSJiaying Zhang 	spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
3837744692dcSJiaying Zhang 	list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
3838744692dcSJiaying Zhang 	spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
3839744692dcSJiaying Zhang 
3840744692dcSJiaying Zhang 	wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
3841744692dcSJiaying Zhang 	/* queue the work to convert unwritten extents to written */
3842744692dcSJiaying Zhang 	queue_work(wq, &io_end->work);
3843744692dcSJiaying Zhang out:
3844744692dcSJiaying Zhang 	bh->b_private = NULL;
3845744692dcSJiaying Zhang 	bh->b_end_io = NULL;
3846744692dcSJiaying Zhang 	clear_buffer_uninit(bh);
3847744692dcSJiaying Zhang 	end_buffer_async_write(bh, uptodate);
3848744692dcSJiaying Zhang }
3849744692dcSJiaying Zhang 
3850744692dcSJiaying Zhang static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
3851744692dcSJiaying Zhang {
3852744692dcSJiaying Zhang 	ext4_io_end_t *io_end;
3853744692dcSJiaying Zhang 	struct page *page = bh->b_page;
3854744692dcSJiaying Zhang 	loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
3855744692dcSJiaying Zhang 	size_t size = bh->b_size;
3856744692dcSJiaying Zhang 
3857744692dcSJiaying Zhang retry:
3858744692dcSJiaying Zhang 	io_end = ext4_init_io_end(inode, GFP_ATOMIC);
3859744692dcSJiaying Zhang 	if (!io_end) {
3860744692dcSJiaying Zhang 		if (printk_ratelimit())
3861744692dcSJiaying Zhang 			printk(KERN_WARNING "%s: allocation fail\n", __func__);
3862744692dcSJiaying Zhang 		schedule();
3863744692dcSJiaying Zhang 		goto retry;
3864744692dcSJiaying Zhang 	}
3865744692dcSJiaying Zhang 	io_end->offset = offset;
3866744692dcSJiaying Zhang 	io_end->size = size;
3867744692dcSJiaying Zhang 	/*
3868744692dcSJiaying Zhang 	 * We need to hold a reference to the page to make sure it
3869744692dcSJiaying Zhang 	 * doesn't get evicted before ext4_end_io_work() has a chance
3870744692dcSJiaying Zhang 	 * to convert the extent from written to unwritten.
3871744692dcSJiaying Zhang 	 */
3872744692dcSJiaying Zhang 	io_end->page = page;
3873744692dcSJiaying Zhang 	get_page(io_end->page);
3874744692dcSJiaying Zhang 
3875744692dcSJiaying Zhang 	bh->b_private = io_end;
3876744692dcSJiaying Zhang 	bh->b_end_io = ext4_end_io_buffer_write;
3877744692dcSJiaying Zhang 	return 0;
3878744692dcSJiaying Zhang }
3879744692dcSJiaying Zhang 
38804c0425ffSMingming Cao /*
38814c0425ffSMingming Cao  * For ext4 extent files, ext4 will do direct-io write to holes,
38824c0425ffSMingming Cao  * preallocated extents, and those write extend the file, no need to
38834c0425ffSMingming Cao  * fall back to buffered IO.
38844c0425ffSMingming Cao  *
38854c0425ffSMingming Cao  * For holes, we fallocate those blocks, mark them as unintialized
38864c0425ffSMingming Cao  * If those blocks were preallocated, we mark sure they are splited, but
38874c0425ffSMingming Cao  * still keep the range to write as unintialized.
38884c0425ffSMingming Cao  *
38898d5d02e6SMingming Cao  * The unwrritten extents will be converted to written when DIO is completed.
38908d5d02e6SMingming Cao  * For async direct IO, since the IO may still pending when return, we
38918d5d02e6SMingming Cao  * set up an end_io call back function, which will do the convertion
38928d5d02e6SMingming Cao  * when async direct IO completed.
38934c0425ffSMingming Cao  *
38944c0425ffSMingming Cao  * If the O_DIRECT write will extend the file then add this inode to the
38954c0425ffSMingming Cao  * orphan list.  So recovery will truncate it back to the original size
38964c0425ffSMingming Cao  * if the machine crashes during the write.
38974c0425ffSMingming Cao  *
38984c0425ffSMingming Cao  */
38994c0425ffSMingming Cao static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
39004c0425ffSMingming Cao 			      const struct iovec *iov, loff_t offset,
39014c0425ffSMingming Cao 			      unsigned long nr_segs)
39024c0425ffSMingming Cao {
39034c0425ffSMingming Cao 	struct file *file = iocb->ki_filp;
39044c0425ffSMingming Cao 	struct inode *inode = file->f_mapping->host;
39054c0425ffSMingming Cao 	ssize_t ret;
39064c0425ffSMingming Cao 	size_t count = iov_length(iov, nr_segs);
39074c0425ffSMingming Cao 
39084c0425ffSMingming Cao 	loff_t final_size = offset + count;
39094c0425ffSMingming Cao 	if (rw == WRITE && final_size <= inode->i_size) {
39104c0425ffSMingming Cao 		/*
39118d5d02e6SMingming Cao  		 * We could direct write to holes and fallocate.
39128d5d02e6SMingming Cao 		 *
39138d5d02e6SMingming Cao  		 * Allocated blocks to fill the hole are marked as uninitialized
39144c0425ffSMingming Cao  		 * to prevent paralel buffered read to expose the stale data
39154c0425ffSMingming Cao  		 * before DIO complete the data IO.
39168d5d02e6SMingming Cao 		 *
39178d5d02e6SMingming Cao  		 * As to previously fallocated extents, ext4 get_block
39184c0425ffSMingming Cao  		 * will just simply mark the buffer mapped but still
39194c0425ffSMingming Cao  		 * keep the extents uninitialized.
39204c0425ffSMingming Cao  		 *
39218d5d02e6SMingming Cao 		 * for non AIO case, we will convert those unwritten extents
39228d5d02e6SMingming Cao 		 * to written after return back from blockdev_direct_IO.
39234c0425ffSMingming Cao 		 *
39248d5d02e6SMingming Cao 		 * for async DIO, the conversion needs to be defered when
39258d5d02e6SMingming Cao 		 * the IO is completed. The ext4 end_io callback function
39268d5d02e6SMingming Cao 		 * will be called to take care of the conversion work.
39278d5d02e6SMingming Cao 		 * Here for async case, we allocate an io_end structure to
39288d5d02e6SMingming Cao 		 * hook to the iocb.
39294c0425ffSMingming Cao  		 */
39308d5d02e6SMingming Cao 		iocb->private = NULL;
39318d5d02e6SMingming Cao 		EXT4_I(inode)->cur_aio_dio = NULL;
39328d5d02e6SMingming Cao 		if (!is_sync_kiocb(iocb)) {
3933744692dcSJiaying Zhang 			iocb->private = ext4_init_io_end(inode, GFP_NOFS);
39344c0425ffSMingming Cao 			if (!iocb->private)
39354c0425ffSMingming Cao 				return -ENOMEM;
39368d5d02e6SMingming Cao 			/*
39378d5d02e6SMingming Cao 			 * we save the io structure for current async
39388d5d02e6SMingming Cao 			 * direct IO, so that later ext4_get_blocks()
39398d5d02e6SMingming Cao 			 * could flag the io structure whether there
39408d5d02e6SMingming Cao 			 * is a unwritten extents needs to be converted
39418d5d02e6SMingming Cao 			 * when IO is completed.
39428d5d02e6SMingming Cao 			 */
39438d5d02e6SMingming Cao 			EXT4_I(inode)->cur_aio_dio = iocb->private;
39448d5d02e6SMingming Cao 		}
39458d5d02e6SMingming Cao 
39464c0425ffSMingming Cao 		ret = blockdev_direct_IO(rw, iocb, inode,
39474c0425ffSMingming Cao 					 inode->i_sb->s_bdev, iov,
39484c0425ffSMingming Cao 					 offset, nr_segs,
3949c7064ef1SJiaying Zhang 					 ext4_get_block_write,
39504c0425ffSMingming Cao 					 ext4_end_io_dio);
39518d5d02e6SMingming Cao 		if (iocb->private)
39528d5d02e6SMingming Cao 			EXT4_I(inode)->cur_aio_dio = NULL;
39538d5d02e6SMingming Cao 		/*
39548d5d02e6SMingming Cao 		 * The io_end structure takes a reference to the inode,
39558d5d02e6SMingming Cao 		 * that structure needs to be destroyed and the
39568d5d02e6SMingming Cao 		 * reference to the inode need to be dropped, when IO is
39578d5d02e6SMingming Cao 		 * complete, even with 0 byte write, or failed.
39588d5d02e6SMingming Cao 		 *
39598d5d02e6SMingming Cao 		 * In the successful AIO DIO case, the io_end structure will be
39608d5d02e6SMingming Cao 		 * desctroyed and the reference to the inode will be dropped
39618d5d02e6SMingming Cao 		 * after the end_io call back function is called.
39628d5d02e6SMingming Cao 		 *
39638d5d02e6SMingming Cao 		 * In the case there is 0 byte write, or error case, since
39648d5d02e6SMingming Cao 		 * VFS direct IO won't invoke the end_io call back function,
39658d5d02e6SMingming Cao 		 * we need to free the end_io structure here.
39668d5d02e6SMingming Cao 		 */
39678d5d02e6SMingming Cao 		if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
39688d5d02e6SMingming Cao 			ext4_free_io_end(iocb->private);
39698d5d02e6SMingming Cao 			iocb->private = NULL;
397019f5fb7aSTheodore Ts'o 		} else if (ret > 0 && ext4_test_inode_state(inode,
39715f524950SMingming 						EXT4_STATE_DIO_UNWRITTEN)) {
3972109f5565SMingming 			int err;
39738d5d02e6SMingming Cao 			/*
39748d5d02e6SMingming Cao 			 * for non AIO case, since the IO is already
39758d5d02e6SMingming Cao 			 * completed, we could do the convertion right here
39768d5d02e6SMingming Cao 			 */
3977109f5565SMingming 			err = ext4_convert_unwritten_extents(inode,
39788d5d02e6SMingming Cao 							     offset, ret);
3979109f5565SMingming 			if (err < 0)
3980109f5565SMingming 				ret = err;
398119f5fb7aSTheodore Ts'o 			ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3982109f5565SMingming 		}
39834c0425ffSMingming Cao 		return ret;
39844c0425ffSMingming Cao 	}
39858d5d02e6SMingming Cao 
39868d5d02e6SMingming Cao 	/* for write the the end of file case, we fall back to old way */
39874c0425ffSMingming Cao 	return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
39884c0425ffSMingming Cao }
39894c0425ffSMingming Cao 
39904c0425ffSMingming Cao static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
39914c0425ffSMingming Cao 			      const struct iovec *iov, loff_t offset,
39924c0425ffSMingming Cao 			      unsigned long nr_segs)
39934c0425ffSMingming Cao {
39944c0425ffSMingming Cao 	struct file *file = iocb->ki_filp;
39954c0425ffSMingming Cao 	struct inode *inode = file->f_mapping->host;
39964c0425ffSMingming Cao 
399712e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
39984c0425ffSMingming Cao 		return ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
39994c0425ffSMingming Cao 
40004c0425ffSMingming Cao 	return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
40014c0425ffSMingming Cao }
40024c0425ffSMingming Cao 
4003ac27a0ecSDave Kleikamp /*
4004617ba13bSMingming Cao  * Pages can be marked dirty completely asynchronously from ext4's journalling
4005ac27a0ecSDave Kleikamp  * activity.  By filemap_sync_pte(), try_to_unmap_one(), etc.  We cannot do
4006ac27a0ecSDave Kleikamp  * much here because ->set_page_dirty is called under VFS locks.  The page is
4007ac27a0ecSDave Kleikamp  * not necessarily locked.
4008ac27a0ecSDave Kleikamp  *
4009ac27a0ecSDave Kleikamp  * We cannot just dirty the page and leave attached buffers clean, because the
4010ac27a0ecSDave Kleikamp  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
4011ac27a0ecSDave Kleikamp  * or jbddirty because all the journalling code will explode.
4012ac27a0ecSDave Kleikamp  *
4013ac27a0ecSDave Kleikamp  * So what we do is to mark the page "pending dirty" and next time writepage
4014ac27a0ecSDave Kleikamp  * is called, propagate that into the buffers appropriately.
4015ac27a0ecSDave Kleikamp  */
4016617ba13bSMingming Cao static int ext4_journalled_set_page_dirty(struct page *page)
4017ac27a0ecSDave Kleikamp {
4018ac27a0ecSDave Kleikamp 	SetPageChecked(page);
4019ac27a0ecSDave Kleikamp 	return __set_page_dirty_nobuffers(page);
4020ac27a0ecSDave Kleikamp }
4021ac27a0ecSDave Kleikamp 
4022617ba13bSMingming Cao static const struct address_space_operations ext4_ordered_aops = {
4023617ba13bSMingming Cao 	.readpage		= ext4_readpage,
4024617ba13bSMingming Cao 	.readpages		= ext4_readpages,
402543ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
4026ac27a0ecSDave Kleikamp 	.sync_page		= block_sync_page,
4027bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
4028bfc1af65SNick Piggin 	.write_end		= ext4_ordered_write_end,
4029617ba13bSMingming Cao 	.bmap			= ext4_bmap,
4030617ba13bSMingming Cao 	.invalidatepage		= ext4_invalidatepage,
4031617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
4032617ba13bSMingming Cao 	.direct_IO		= ext4_direct_IO,
4033ac27a0ecSDave Kleikamp 	.migratepage		= buffer_migrate_page,
40348ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
4035aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
4036ac27a0ecSDave Kleikamp };
4037ac27a0ecSDave Kleikamp 
4038617ba13bSMingming Cao static const struct address_space_operations ext4_writeback_aops = {
4039617ba13bSMingming Cao 	.readpage		= ext4_readpage,
4040617ba13bSMingming Cao 	.readpages		= ext4_readpages,
404143ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
4042ac27a0ecSDave Kleikamp 	.sync_page		= block_sync_page,
4043bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
4044bfc1af65SNick Piggin 	.write_end		= ext4_writeback_write_end,
4045617ba13bSMingming Cao 	.bmap			= ext4_bmap,
4046617ba13bSMingming Cao 	.invalidatepage		= ext4_invalidatepage,
4047617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
4048617ba13bSMingming Cao 	.direct_IO		= ext4_direct_IO,
4049ac27a0ecSDave Kleikamp 	.migratepage		= buffer_migrate_page,
40508ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
4051aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
4052ac27a0ecSDave Kleikamp };
4053ac27a0ecSDave Kleikamp 
4054617ba13bSMingming Cao static const struct address_space_operations ext4_journalled_aops = {
4055617ba13bSMingming Cao 	.readpage		= ext4_readpage,
4056617ba13bSMingming Cao 	.readpages		= ext4_readpages,
405743ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
4058ac27a0ecSDave Kleikamp 	.sync_page		= block_sync_page,
4059bfc1af65SNick Piggin 	.write_begin		= ext4_write_begin,
4060bfc1af65SNick Piggin 	.write_end		= ext4_journalled_write_end,
4061617ba13bSMingming Cao 	.set_page_dirty		= ext4_journalled_set_page_dirty,
4062617ba13bSMingming Cao 	.bmap			= ext4_bmap,
4063617ba13bSMingming Cao 	.invalidatepage		= ext4_invalidatepage,
4064617ba13bSMingming Cao 	.releasepage		= ext4_releasepage,
40658ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
4066aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
4067ac27a0ecSDave Kleikamp };
4068ac27a0ecSDave Kleikamp 
406964769240SAlex Tomas static const struct address_space_operations ext4_da_aops = {
407064769240SAlex Tomas 	.readpage		= ext4_readpage,
407164769240SAlex Tomas 	.readpages		= ext4_readpages,
407243ce1d23SAneesh Kumar K.V 	.writepage		= ext4_writepage,
407364769240SAlex Tomas 	.writepages		= ext4_da_writepages,
407464769240SAlex Tomas 	.sync_page		= block_sync_page,
407564769240SAlex Tomas 	.write_begin		= ext4_da_write_begin,
407664769240SAlex Tomas 	.write_end		= ext4_da_write_end,
407764769240SAlex Tomas 	.bmap			= ext4_bmap,
407864769240SAlex Tomas 	.invalidatepage		= ext4_da_invalidatepage,
407964769240SAlex Tomas 	.releasepage		= ext4_releasepage,
408064769240SAlex Tomas 	.direct_IO		= ext4_direct_IO,
408164769240SAlex Tomas 	.migratepage		= buffer_migrate_page,
40828ab22b9aSHisashi Hifumi 	.is_partially_uptodate  = block_is_partially_uptodate,
4083aa261f54SAndi Kleen 	.error_remove_page	= generic_error_remove_page,
408464769240SAlex Tomas };
408564769240SAlex Tomas 
4086617ba13bSMingming Cao void ext4_set_aops(struct inode *inode)
4087ac27a0ecSDave Kleikamp {
4088cd1aac32SAneesh Kumar K.V 	if (ext4_should_order_data(inode) &&
4089cd1aac32SAneesh Kumar K.V 		test_opt(inode->i_sb, DELALLOC))
4090cd1aac32SAneesh Kumar K.V 		inode->i_mapping->a_ops = &ext4_da_aops;
4091cd1aac32SAneesh Kumar K.V 	else if (ext4_should_order_data(inode))
4092617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_ordered_aops;
409364769240SAlex Tomas 	else if (ext4_should_writeback_data(inode) &&
409464769240SAlex Tomas 		 test_opt(inode->i_sb, DELALLOC))
409564769240SAlex Tomas 		inode->i_mapping->a_ops = &ext4_da_aops;
4096617ba13bSMingming Cao 	else if (ext4_should_writeback_data(inode))
4097617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_writeback_aops;
4098ac27a0ecSDave Kleikamp 	else
4099617ba13bSMingming Cao 		inode->i_mapping->a_ops = &ext4_journalled_aops;
4100ac27a0ecSDave Kleikamp }
4101ac27a0ecSDave Kleikamp 
4102ac27a0ecSDave Kleikamp /*
4103617ba13bSMingming Cao  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
4104ac27a0ecSDave Kleikamp  * up to the end of the block which corresponds to `from'.
4105ac27a0ecSDave Kleikamp  * This required during truncate. We need to physically zero the tail end
4106ac27a0ecSDave Kleikamp  * of that block so it doesn't yield old data if the file is later grown.
4107ac27a0ecSDave Kleikamp  */
4108cf108bcaSJan Kara int ext4_block_truncate_page(handle_t *handle,
4109ac27a0ecSDave Kleikamp 		struct address_space *mapping, loff_t from)
4110ac27a0ecSDave Kleikamp {
4111617ba13bSMingming Cao 	ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
4112ac27a0ecSDave Kleikamp 	unsigned offset = from & (PAGE_CACHE_SIZE-1);
4113725d26d3SAneesh Kumar K.V 	unsigned blocksize, length, pos;
4114725d26d3SAneesh Kumar K.V 	ext4_lblk_t iblock;
4115ac27a0ecSDave Kleikamp 	struct inode *inode = mapping->host;
4116ac27a0ecSDave Kleikamp 	struct buffer_head *bh;
4117cf108bcaSJan Kara 	struct page *page;
4118ac27a0ecSDave Kleikamp 	int err = 0;
4119ac27a0ecSDave Kleikamp 
4120f4a01017STheodore Ts'o 	page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
4121f4a01017STheodore Ts'o 				   mapping_gfp_mask(mapping) & ~__GFP_FS);
4122cf108bcaSJan Kara 	if (!page)
4123cf108bcaSJan Kara 		return -EINVAL;
4124cf108bcaSJan Kara 
4125ac27a0ecSDave Kleikamp 	blocksize = inode->i_sb->s_blocksize;
4126ac27a0ecSDave Kleikamp 	length = blocksize - (offset & (blocksize - 1));
4127ac27a0ecSDave Kleikamp 	iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
4128ac27a0ecSDave Kleikamp 
4129ac27a0ecSDave Kleikamp 	if (!page_has_buffers(page))
4130ac27a0ecSDave Kleikamp 		create_empty_buffers(page, blocksize, 0);
4131ac27a0ecSDave Kleikamp 
4132ac27a0ecSDave Kleikamp 	/* Find the buffer that contains "offset" */
4133ac27a0ecSDave Kleikamp 	bh = page_buffers(page);
4134ac27a0ecSDave Kleikamp 	pos = blocksize;
4135ac27a0ecSDave Kleikamp 	while (offset >= pos) {
4136ac27a0ecSDave Kleikamp 		bh = bh->b_this_page;
4137ac27a0ecSDave Kleikamp 		iblock++;
4138ac27a0ecSDave Kleikamp 		pos += blocksize;
4139ac27a0ecSDave Kleikamp 	}
4140ac27a0ecSDave Kleikamp 
4141ac27a0ecSDave Kleikamp 	err = 0;
4142ac27a0ecSDave Kleikamp 	if (buffer_freed(bh)) {
4143ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "freed: skip");
4144ac27a0ecSDave Kleikamp 		goto unlock;
4145ac27a0ecSDave Kleikamp 	}
4146ac27a0ecSDave Kleikamp 
4147ac27a0ecSDave Kleikamp 	if (!buffer_mapped(bh)) {
4148ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "unmapped");
4149617ba13bSMingming Cao 		ext4_get_block(inode, iblock, bh, 0);
4150ac27a0ecSDave Kleikamp 		/* unmapped? It's a hole - nothing to do */
4151ac27a0ecSDave Kleikamp 		if (!buffer_mapped(bh)) {
4152ac27a0ecSDave Kleikamp 			BUFFER_TRACE(bh, "still unmapped");
4153ac27a0ecSDave Kleikamp 			goto unlock;
4154ac27a0ecSDave Kleikamp 		}
4155ac27a0ecSDave Kleikamp 	}
4156ac27a0ecSDave Kleikamp 
4157ac27a0ecSDave Kleikamp 	/* Ok, it's mapped. Make sure it's up-to-date */
4158ac27a0ecSDave Kleikamp 	if (PageUptodate(page))
4159ac27a0ecSDave Kleikamp 		set_buffer_uptodate(bh);
4160ac27a0ecSDave Kleikamp 
4161ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
4162ac27a0ecSDave Kleikamp 		err = -EIO;
4163ac27a0ecSDave Kleikamp 		ll_rw_block(READ, 1, &bh);
4164ac27a0ecSDave Kleikamp 		wait_on_buffer(bh);
4165ac27a0ecSDave Kleikamp 		/* Uhhuh. Read error. Complain and punt. */
4166ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bh))
4167ac27a0ecSDave Kleikamp 			goto unlock;
4168ac27a0ecSDave Kleikamp 	}
4169ac27a0ecSDave Kleikamp 
4170617ba13bSMingming Cao 	if (ext4_should_journal_data(inode)) {
4171ac27a0ecSDave Kleikamp 		BUFFER_TRACE(bh, "get write access");
4172617ba13bSMingming Cao 		err = ext4_journal_get_write_access(handle, bh);
4173ac27a0ecSDave Kleikamp 		if (err)
4174ac27a0ecSDave Kleikamp 			goto unlock;
4175ac27a0ecSDave Kleikamp 	}
4176ac27a0ecSDave Kleikamp 
4177eebd2aa3SChristoph Lameter 	zero_user(page, offset, length);
4178ac27a0ecSDave Kleikamp 
4179ac27a0ecSDave Kleikamp 	BUFFER_TRACE(bh, "zeroed end of block");
4180ac27a0ecSDave Kleikamp 
4181ac27a0ecSDave Kleikamp 	err = 0;
4182617ba13bSMingming Cao 	if (ext4_should_journal_data(inode)) {
41830390131bSFrank Mayhar 		err = ext4_handle_dirty_metadata(handle, inode, bh);
4184ac27a0ecSDave Kleikamp 	} else {
4185617ba13bSMingming Cao 		if (ext4_should_order_data(inode))
4186678aaf48SJan Kara 			err = ext4_jbd2_file_inode(handle, inode);
4187ac27a0ecSDave Kleikamp 		mark_buffer_dirty(bh);
4188ac27a0ecSDave Kleikamp 	}
4189ac27a0ecSDave Kleikamp 
4190ac27a0ecSDave Kleikamp unlock:
4191ac27a0ecSDave Kleikamp 	unlock_page(page);
4192ac27a0ecSDave Kleikamp 	page_cache_release(page);
4193ac27a0ecSDave Kleikamp 	return err;
4194ac27a0ecSDave Kleikamp }
4195ac27a0ecSDave Kleikamp 
4196ac27a0ecSDave Kleikamp /*
4197ac27a0ecSDave Kleikamp  * Probably it should be a library function... search for first non-zero word
4198ac27a0ecSDave Kleikamp  * or memcmp with zero_page, whatever is better for particular architecture.
4199ac27a0ecSDave Kleikamp  * Linus?
4200ac27a0ecSDave Kleikamp  */
4201ac27a0ecSDave Kleikamp static inline int all_zeroes(__le32 *p, __le32 *q)
4202ac27a0ecSDave Kleikamp {
4203ac27a0ecSDave Kleikamp 	while (p < q)
4204ac27a0ecSDave Kleikamp 		if (*p++)
4205ac27a0ecSDave Kleikamp 			return 0;
4206ac27a0ecSDave Kleikamp 	return 1;
4207ac27a0ecSDave Kleikamp }
4208ac27a0ecSDave Kleikamp 
4209ac27a0ecSDave Kleikamp /**
4210617ba13bSMingming Cao  *	ext4_find_shared - find the indirect blocks for partial truncation.
4211ac27a0ecSDave Kleikamp  *	@inode:	  inode in question
4212ac27a0ecSDave Kleikamp  *	@depth:	  depth of the affected branch
4213617ba13bSMingming Cao  *	@offsets: offsets of pointers in that branch (see ext4_block_to_path)
4214ac27a0ecSDave Kleikamp  *	@chain:	  place to store the pointers to partial indirect blocks
4215ac27a0ecSDave Kleikamp  *	@top:	  place to the (detached) top of branch
4216ac27a0ecSDave Kleikamp  *
4217617ba13bSMingming Cao  *	This is a helper function used by ext4_truncate().
4218ac27a0ecSDave Kleikamp  *
4219ac27a0ecSDave Kleikamp  *	When we do truncate() we may have to clean the ends of several
4220ac27a0ecSDave Kleikamp  *	indirect blocks but leave the blocks themselves alive. Block is
4221ac27a0ecSDave Kleikamp  *	partially truncated if some data below the new i_size is refered
4222ac27a0ecSDave Kleikamp  *	from it (and it is on the path to the first completely truncated
4223ac27a0ecSDave Kleikamp  *	data block, indeed).  We have to free the top of that path along
4224ac27a0ecSDave Kleikamp  *	with everything to the right of the path. Since no allocation
4225617ba13bSMingming Cao  *	past the truncation point is possible until ext4_truncate()
4226ac27a0ecSDave Kleikamp  *	finishes, we may safely do the latter, but top of branch may
4227ac27a0ecSDave Kleikamp  *	require special attention - pageout below the truncation point
4228ac27a0ecSDave Kleikamp  *	might try to populate it.
4229ac27a0ecSDave Kleikamp  *
4230ac27a0ecSDave Kleikamp  *	We atomically detach the top of branch from the tree, store the
4231ac27a0ecSDave Kleikamp  *	block number of its root in *@top, pointers to buffer_heads of
4232ac27a0ecSDave Kleikamp  *	partially truncated blocks - in @chain[].bh and pointers to
4233ac27a0ecSDave Kleikamp  *	their last elements that should not be removed - in
4234ac27a0ecSDave Kleikamp  *	@chain[].p. Return value is the pointer to last filled element
4235ac27a0ecSDave Kleikamp  *	of @chain.
4236ac27a0ecSDave Kleikamp  *
4237ac27a0ecSDave Kleikamp  *	The work left to caller to do the actual freeing of subtrees:
4238ac27a0ecSDave Kleikamp  *		a) free the subtree starting from *@top
4239ac27a0ecSDave Kleikamp  *		b) free the subtrees whose roots are stored in
4240ac27a0ecSDave Kleikamp  *			(@chain[i].p+1 .. end of @chain[i].bh->b_data)
4241ac27a0ecSDave Kleikamp  *		c) free the subtrees growing from the inode past the @chain[0].
4242ac27a0ecSDave Kleikamp  *			(no partially truncated stuff there).  */
4243ac27a0ecSDave Kleikamp 
4244617ba13bSMingming Cao static Indirect *ext4_find_shared(struct inode *inode, int depth,
4245de9a55b8STheodore Ts'o 				  ext4_lblk_t offsets[4], Indirect chain[4],
4246de9a55b8STheodore Ts'o 				  __le32 *top)
4247ac27a0ecSDave Kleikamp {
4248ac27a0ecSDave Kleikamp 	Indirect *partial, *p;
4249ac27a0ecSDave Kleikamp 	int k, err;
4250ac27a0ecSDave Kleikamp 
4251ac27a0ecSDave Kleikamp 	*top = 0;
4252bf48aabbSUwe Kleine-König 	/* Make k index the deepest non-null offset + 1 */
4253ac27a0ecSDave Kleikamp 	for (k = depth; k > 1 && !offsets[k-1]; k--)
4254ac27a0ecSDave Kleikamp 		;
4255617ba13bSMingming Cao 	partial = ext4_get_branch(inode, k, offsets, chain, &err);
4256ac27a0ecSDave Kleikamp 	/* Writer: pointers */
4257ac27a0ecSDave Kleikamp 	if (!partial)
4258ac27a0ecSDave Kleikamp 		partial = chain + k-1;
4259ac27a0ecSDave Kleikamp 	/*
4260ac27a0ecSDave Kleikamp 	 * If the branch acquired continuation since we've looked at it -
4261ac27a0ecSDave Kleikamp 	 * fine, it should all survive and (new) top doesn't belong to us.
4262ac27a0ecSDave Kleikamp 	 */
4263ac27a0ecSDave Kleikamp 	if (!partial->key && *partial->p)
4264ac27a0ecSDave Kleikamp 		/* Writer: end */
4265ac27a0ecSDave Kleikamp 		goto no_top;
4266af5bc92dSTheodore Ts'o 	for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
4267ac27a0ecSDave Kleikamp 		;
4268ac27a0ecSDave Kleikamp 	/*
4269ac27a0ecSDave Kleikamp 	 * OK, we've found the last block that must survive. The rest of our
4270ac27a0ecSDave Kleikamp 	 * branch should be detached before unlocking. However, if that rest
4271ac27a0ecSDave Kleikamp 	 * of branch is all ours and does not grow immediately from the inode
4272ac27a0ecSDave Kleikamp 	 * it's easier to cheat and just decrement partial->p.
4273ac27a0ecSDave Kleikamp 	 */
4274ac27a0ecSDave Kleikamp 	if (p == chain + k - 1 && p > chain) {
4275ac27a0ecSDave Kleikamp 		p->p--;
4276ac27a0ecSDave Kleikamp 	} else {
4277ac27a0ecSDave Kleikamp 		*top = *p->p;
4278617ba13bSMingming Cao 		/* Nope, don't do this in ext4.  Must leave the tree intact */
4279ac27a0ecSDave Kleikamp #if 0
4280ac27a0ecSDave Kleikamp 		*p->p = 0;
4281ac27a0ecSDave Kleikamp #endif
4282ac27a0ecSDave Kleikamp 	}
4283ac27a0ecSDave Kleikamp 	/* Writer: end */
4284ac27a0ecSDave Kleikamp 
4285ac27a0ecSDave Kleikamp 	while (partial > p) {
4286ac27a0ecSDave Kleikamp 		brelse(partial->bh);
4287ac27a0ecSDave Kleikamp 		partial--;
4288ac27a0ecSDave Kleikamp 	}
4289ac27a0ecSDave Kleikamp no_top:
4290ac27a0ecSDave Kleikamp 	return partial;
4291ac27a0ecSDave Kleikamp }
4292ac27a0ecSDave Kleikamp 
4293ac27a0ecSDave Kleikamp /*
4294ac27a0ecSDave Kleikamp  * Zero a number of block pointers in either an inode or an indirect block.
4295ac27a0ecSDave Kleikamp  * If we restart the transaction we must again get write access to the
4296ac27a0ecSDave Kleikamp  * indirect block for further modification.
4297ac27a0ecSDave Kleikamp  *
4298ac27a0ecSDave Kleikamp  * We release `count' blocks on disk, but (last - first) may be greater
4299ac27a0ecSDave Kleikamp  * than `count' because there can be holes in there.
4300ac27a0ecSDave Kleikamp  */
43011f2acb60STheodore Ts'o static int ext4_clear_blocks(handle_t *handle, struct inode *inode,
4302de9a55b8STheodore Ts'o 			     struct buffer_head *bh,
4303de9a55b8STheodore Ts'o 			     ext4_fsblk_t block_to_free,
4304de9a55b8STheodore Ts'o 			     unsigned long count, __le32 *first,
4305de9a55b8STheodore Ts'o 			     __le32 *last)
4306ac27a0ecSDave Kleikamp {
4307ac27a0ecSDave Kleikamp 	__le32 *p;
43081f2acb60STheodore Ts'o 	int	flags = EXT4_FREE_BLOCKS_FORGET | EXT4_FREE_BLOCKS_VALIDATED;
4309e6362609STheodore Ts'o 
4310e6362609STheodore Ts'o 	if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
4311e6362609STheodore Ts'o 		flags |= EXT4_FREE_BLOCKS_METADATA;
431250689696STheodore Ts'o 
43131f2acb60STheodore Ts'o 	if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), block_to_free,
43141f2acb60STheodore Ts'o 				   count)) {
431524676da4STheodore Ts'o 		EXT4_ERROR_INODE(inode, "attempt to clear invalid "
431624676da4STheodore Ts'o 				 "blocks %llu len %lu",
431724676da4STheodore Ts'o 				 (unsigned long long) block_to_free, count);
43181f2acb60STheodore Ts'o 		return 1;
43191f2acb60STheodore Ts'o 	}
43201f2acb60STheodore Ts'o 
4321ac27a0ecSDave Kleikamp 	if (try_to_extend_transaction(handle, inode)) {
4322ac27a0ecSDave Kleikamp 		if (bh) {
43230390131bSFrank Mayhar 			BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
43240390131bSFrank Mayhar 			ext4_handle_dirty_metadata(handle, inode, bh);
4325ac27a0ecSDave Kleikamp 		}
4326617ba13bSMingming Cao 		ext4_mark_inode_dirty(handle, inode);
4327487caeefSJan Kara 		ext4_truncate_restart_trans(handle, inode,
4328487caeefSJan Kara 					    blocks_for_truncate(inode));
4329ac27a0ecSDave Kleikamp 		if (bh) {
4330ac27a0ecSDave Kleikamp 			BUFFER_TRACE(bh, "retaking write access");
4331617ba13bSMingming Cao 			ext4_journal_get_write_access(handle, bh);
4332ac27a0ecSDave Kleikamp 		}
4333ac27a0ecSDave Kleikamp 	}
4334ac27a0ecSDave Kleikamp 
4335e6362609STheodore Ts'o 	for (p = first; p < last; p++)
4336ac27a0ecSDave Kleikamp 		*p = 0;
4337ac27a0ecSDave Kleikamp 
4338e6362609STheodore Ts'o 	ext4_free_blocks(handle, inode, 0, block_to_free, count, flags);
43391f2acb60STheodore Ts'o 	return 0;
4340ac27a0ecSDave Kleikamp }
4341ac27a0ecSDave Kleikamp 
4342ac27a0ecSDave Kleikamp /**
4343617ba13bSMingming Cao  * ext4_free_data - free a list of data blocks
4344ac27a0ecSDave Kleikamp  * @handle:	handle for this transaction
4345ac27a0ecSDave Kleikamp  * @inode:	inode we are dealing with
4346ac27a0ecSDave Kleikamp  * @this_bh:	indirect buffer_head which contains *@first and *@last
4347ac27a0ecSDave Kleikamp  * @first:	array of block numbers
4348ac27a0ecSDave Kleikamp  * @last:	points immediately past the end of array
4349ac27a0ecSDave Kleikamp  *
4350ac27a0ecSDave Kleikamp  * We are freeing all blocks refered from that array (numbers are stored as
4351ac27a0ecSDave Kleikamp  * little-endian 32-bit) and updating @inode->i_blocks appropriately.
4352ac27a0ecSDave Kleikamp  *
4353ac27a0ecSDave Kleikamp  * We accumulate contiguous runs of blocks to free.  Conveniently, if these
4354ac27a0ecSDave Kleikamp  * blocks are contiguous then releasing them at one time will only affect one
4355ac27a0ecSDave Kleikamp  * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
4356ac27a0ecSDave Kleikamp  * actually use a lot of journal space.
4357ac27a0ecSDave Kleikamp  *
4358ac27a0ecSDave Kleikamp  * @this_bh will be %NULL if @first and @last point into the inode's direct
4359ac27a0ecSDave Kleikamp  * block pointers.
4360ac27a0ecSDave Kleikamp  */
4361617ba13bSMingming Cao static void ext4_free_data(handle_t *handle, struct inode *inode,
4362ac27a0ecSDave Kleikamp 			   struct buffer_head *this_bh,
4363ac27a0ecSDave Kleikamp 			   __le32 *first, __le32 *last)
4364ac27a0ecSDave Kleikamp {
4365617ba13bSMingming Cao 	ext4_fsblk_t block_to_free = 0;    /* Starting block # of a run */
4366ac27a0ecSDave Kleikamp 	unsigned long count = 0;	    /* Number of blocks in the run */
4367ac27a0ecSDave Kleikamp 	__le32 *block_to_free_p = NULL;	    /* Pointer into inode/ind
4368ac27a0ecSDave Kleikamp 					       corresponding to
4369ac27a0ecSDave Kleikamp 					       block_to_free */
4370617ba13bSMingming Cao 	ext4_fsblk_t nr;		    /* Current block # */
4371ac27a0ecSDave Kleikamp 	__le32 *p;			    /* Pointer into inode/ind
4372ac27a0ecSDave Kleikamp 					       for current block */
4373ac27a0ecSDave Kleikamp 	int err;
4374ac27a0ecSDave Kleikamp 
4375ac27a0ecSDave Kleikamp 	if (this_bh) {				/* For indirect block */
4376ac27a0ecSDave Kleikamp 		BUFFER_TRACE(this_bh, "get_write_access");
4377617ba13bSMingming Cao 		err = ext4_journal_get_write_access(handle, this_bh);
4378ac27a0ecSDave Kleikamp 		/* Important: if we can't update the indirect pointers
4379ac27a0ecSDave Kleikamp 		 * to the blocks, we can't free them. */
4380ac27a0ecSDave Kleikamp 		if (err)
4381ac27a0ecSDave Kleikamp 			return;
4382ac27a0ecSDave Kleikamp 	}
4383ac27a0ecSDave Kleikamp 
4384ac27a0ecSDave Kleikamp 	for (p = first; p < last; p++) {
4385ac27a0ecSDave Kleikamp 		nr = le32_to_cpu(*p);
4386ac27a0ecSDave Kleikamp 		if (nr) {
4387ac27a0ecSDave Kleikamp 			/* accumulate blocks to free if they're contiguous */
4388ac27a0ecSDave Kleikamp 			if (count == 0) {
4389ac27a0ecSDave Kleikamp 				block_to_free = nr;
4390ac27a0ecSDave Kleikamp 				block_to_free_p = p;
4391ac27a0ecSDave Kleikamp 				count = 1;
4392ac27a0ecSDave Kleikamp 			} else if (nr == block_to_free + count) {
4393ac27a0ecSDave Kleikamp 				count++;
4394ac27a0ecSDave Kleikamp 			} else {
43951f2acb60STheodore Ts'o 				if (ext4_clear_blocks(handle, inode, this_bh,
43961f2acb60STheodore Ts'o 						      block_to_free, count,
43971f2acb60STheodore Ts'o 						      block_to_free_p, p))
43981f2acb60STheodore Ts'o 					break;
4399ac27a0ecSDave Kleikamp 				block_to_free = nr;
4400ac27a0ecSDave Kleikamp 				block_to_free_p = p;
4401ac27a0ecSDave Kleikamp 				count = 1;
4402ac27a0ecSDave Kleikamp 			}
4403ac27a0ecSDave Kleikamp 		}
4404ac27a0ecSDave Kleikamp 	}
4405ac27a0ecSDave Kleikamp 
4406ac27a0ecSDave Kleikamp 	if (count > 0)
4407617ba13bSMingming Cao 		ext4_clear_blocks(handle, inode, this_bh, block_to_free,
4408ac27a0ecSDave Kleikamp 				  count, block_to_free_p, p);
4409ac27a0ecSDave Kleikamp 
4410ac27a0ecSDave Kleikamp 	if (this_bh) {
44110390131bSFrank Mayhar 		BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
441271dc8fbcSDuane Griffin 
441371dc8fbcSDuane Griffin 		/*
441471dc8fbcSDuane Griffin 		 * The buffer head should have an attached journal head at this
441571dc8fbcSDuane Griffin 		 * point. However, if the data is corrupted and an indirect
441671dc8fbcSDuane Griffin 		 * block pointed to itself, it would have been detached when
441771dc8fbcSDuane Griffin 		 * the block was cleared. Check for this instead of OOPSing.
441871dc8fbcSDuane Griffin 		 */
4419e7f07968STheodore Ts'o 		if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
44200390131bSFrank Mayhar 			ext4_handle_dirty_metadata(handle, inode, this_bh);
442171dc8fbcSDuane Griffin 		else
442224676da4STheodore Ts'o 			EXT4_ERROR_INODE(inode,
442324676da4STheodore Ts'o 					 "circular indirect block detected at "
442424676da4STheodore Ts'o 					 "block %llu",
442571dc8fbcSDuane Griffin 				(unsigned long long) this_bh->b_blocknr);
4426ac27a0ecSDave Kleikamp 	}
4427ac27a0ecSDave Kleikamp }
4428ac27a0ecSDave Kleikamp 
4429ac27a0ecSDave Kleikamp /**
4430617ba13bSMingming Cao  *	ext4_free_branches - free an array of branches
4431ac27a0ecSDave Kleikamp  *	@handle: JBD handle for this transaction
4432ac27a0ecSDave Kleikamp  *	@inode:	inode we are dealing with
4433ac27a0ecSDave Kleikamp  *	@parent_bh: the buffer_head which contains *@first and *@last
4434ac27a0ecSDave Kleikamp  *	@first:	array of block numbers
4435ac27a0ecSDave Kleikamp  *	@last:	pointer immediately past the end of array
4436ac27a0ecSDave Kleikamp  *	@depth:	depth of the branches to free
4437ac27a0ecSDave Kleikamp  *
4438ac27a0ecSDave Kleikamp  *	We are freeing all blocks refered from these branches (numbers are
4439ac27a0ecSDave Kleikamp  *	stored as little-endian 32-bit) and updating @inode->i_blocks
4440ac27a0ecSDave Kleikamp  *	appropriately.
4441ac27a0ecSDave Kleikamp  */
4442617ba13bSMingming Cao static void ext4_free_branches(handle_t *handle, struct inode *inode,
4443ac27a0ecSDave Kleikamp 			       struct buffer_head *parent_bh,
4444ac27a0ecSDave Kleikamp 			       __le32 *first, __le32 *last, int depth)
4445ac27a0ecSDave Kleikamp {
4446617ba13bSMingming Cao 	ext4_fsblk_t nr;
4447ac27a0ecSDave Kleikamp 	__le32 *p;
4448ac27a0ecSDave Kleikamp 
44490390131bSFrank Mayhar 	if (ext4_handle_is_aborted(handle))
4450ac27a0ecSDave Kleikamp 		return;
4451ac27a0ecSDave Kleikamp 
4452ac27a0ecSDave Kleikamp 	if (depth--) {
4453ac27a0ecSDave Kleikamp 		struct buffer_head *bh;
4454617ba13bSMingming Cao 		int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4455ac27a0ecSDave Kleikamp 		p = last;
4456ac27a0ecSDave Kleikamp 		while (--p >= first) {
4457ac27a0ecSDave Kleikamp 			nr = le32_to_cpu(*p);
4458ac27a0ecSDave Kleikamp 			if (!nr)
4459ac27a0ecSDave Kleikamp 				continue;		/* A hole */
4460ac27a0ecSDave Kleikamp 
44611f2acb60STheodore Ts'o 			if (!ext4_data_block_valid(EXT4_SB(inode->i_sb),
44621f2acb60STheodore Ts'o 						   nr, 1)) {
446324676da4STheodore Ts'o 				EXT4_ERROR_INODE(inode,
446424676da4STheodore Ts'o 						 "invalid indirect mapped "
446524676da4STheodore Ts'o 						 "block %lu (level %d)",
446624676da4STheodore Ts'o 						 (unsigned long) nr, depth);
44671f2acb60STheodore Ts'o 				break;
44681f2acb60STheodore Ts'o 			}
44691f2acb60STheodore Ts'o 
4470ac27a0ecSDave Kleikamp 			/* Go read the buffer for the next level down */
4471ac27a0ecSDave Kleikamp 			bh = sb_bread(inode->i_sb, nr);
4472ac27a0ecSDave Kleikamp 
4473ac27a0ecSDave Kleikamp 			/*
4474ac27a0ecSDave Kleikamp 			 * A read failure? Report error and clear slot
4475ac27a0ecSDave Kleikamp 			 * (should be rare).
4476ac27a0ecSDave Kleikamp 			 */
4477ac27a0ecSDave Kleikamp 			if (!bh) {
4478*c398eda0STheodore Ts'o 				EXT4_ERROR_INODE_BLOCK(inode, nr,
4479*c398eda0STheodore Ts'o 						       "Read failure");
4480ac27a0ecSDave Kleikamp 				continue;
4481ac27a0ecSDave Kleikamp 			}
4482ac27a0ecSDave Kleikamp 
4483ac27a0ecSDave Kleikamp 			/* This zaps the entire block.  Bottom up. */
4484ac27a0ecSDave Kleikamp 			BUFFER_TRACE(bh, "free child branches");
4485617ba13bSMingming Cao 			ext4_free_branches(handle, inode, bh,
4486ac27a0ecSDave Kleikamp 					(__le32 *) bh->b_data,
4487ac27a0ecSDave Kleikamp 					(__le32 *) bh->b_data + addr_per_block,
4488ac27a0ecSDave Kleikamp 					depth);
4489ac27a0ecSDave Kleikamp 
4490ac27a0ecSDave Kleikamp 			/*
4491ac27a0ecSDave Kleikamp 			 * We've probably journalled the indirect block several
4492ac27a0ecSDave Kleikamp 			 * times during the truncate.  But it's no longer
4493ac27a0ecSDave Kleikamp 			 * needed and we now drop it from the transaction via
4494dab291afSMingming Cao 			 * jbd2_journal_revoke().
4495ac27a0ecSDave Kleikamp 			 *
4496ac27a0ecSDave Kleikamp 			 * That's easy if it's exclusively part of this
4497ac27a0ecSDave Kleikamp 			 * transaction.  But if it's part of the committing
4498dab291afSMingming Cao 			 * transaction then jbd2_journal_forget() will simply
4499ac27a0ecSDave Kleikamp 			 * brelse() it.  That means that if the underlying
4500617ba13bSMingming Cao 			 * block is reallocated in ext4_get_block(),
4501ac27a0ecSDave Kleikamp 			 * unmap_underlying_metadata() will find this block
4502ac27a0ecSDave Kleikamp 			 * and will try to get rid of it.  damn, damn.
4503ac27a0ecSDave Kleikamp 			 *
4504ac27a0ecSDave Kleikamp 			 * If this block has already been committed to the
4505ac27a0ecSDave Kleikamp 			 * journal, a revoke record will be written.  And
4506ac27a0ecSDave Kleikamp 			 * revoke records must be emitted *before* clearing
4507ac27a0ecSDave Kleikamp 			 * this block's bit in the bitmaps.
4508ac27a0ecSDave Kleikamp 			 */
4509617ba13bSMingming Cao 			ext4_forget(handle, 1, inode, bh, bh->b_blocknr);
4510ac27a0ecSDave Kleikamp 
4511ac27a0ecSDave Kleikamp 			/*
4512ac27a0ecSDave Kleikamp 			 * Everything below this this pointer has been
4513ac27a0ecSDave Kleikamp 			 * released.  Now let this top-of-subtree go.
4514ac27a0ecSDave Kleikamp 			 *
4515ac27a0ecSDave Kleikamp 			 * We want the freeing of this indirect block to be
4516ac27a0ecSDave Kleikamp 			 * atomic in the journal with the updating of the
4517ac27a0ecSDave Kleikamp 			 * bitmap block which owns it.  So make some room in
4518ac27a0ecSDave Kleikamp 			 * the journal.
4519ac27a0ecSDave Kleikamp 			 *
4520ac27a0ecSDave Kleikamp 			 * We zero the parent pointer *after* freeing its
4521ac27a0ecSDave Kleikamp 			 * pointee in the bitmaps, so if extend_transaction()
4522ac27a0ecSDave Kleikamp 			 * for some reason fails to put the bitmap changes and
4523ac27a0ecSDave Kleikamp 			 * the release into the same transaction, recovery
4524ac27a0ecSDave Kleikamp 			 * will merely complain about releasing a free block,
4525ac27a0ecSDave Kleikamp 			 * rather than leaking blocks.
4526ac27a0ecSDave Kleikamp 			 */
45270390131bSFrank Mayhar 			if (ext4_handle_is_aborted(handle))
4528ac27a0ecSDave Kleikamp 				return;
4529ac27a0ecSDave Kleikamp 			if (try_to_extend_transaction(handle, inode)) {
4530617ba13bSMingming Cao 				ext4_mark_inode_dirty(handle, inode);
4531487caeefSJan Kara 				ext4_truncate_restart_trans(handle, inode,
4532487caeefSJan Kara 					    blocks_for_truncate(inode));
4533ac27a0ecSDave Kleikamp 			}
4534ac27a0ecSDave Kleikamp 
4535e6362609STheodore Ts'o 			ext4_free_blocks(handle, inode, 0, nr, 1,
4536e6362609STheodore Ts'o 					 EXT4_FREE_BLOCKS_METADATA);
4537ac27a0ecSDave Kleikamp 
4538ac27a0ecSDave Kleikamp 			if (parent_bh) {
4539ac27a0ecSDave Kleikamp 				/*
4540ac27a0ecSDave Kleikamp 				 * The block which we have just freed is
4541ac27a0ecSDave Kleikamp 				 * pointed to by an indirect block: journal it
4542ac27a0ecSDave Kleikamp 				 */
4543ac27a0ecSDave Kleikamp 				BUFFER_TRACE(parent_bh, "get_write_access");
4544617ba13bSMingming Cao 				if (!ext4_journal_get_write_access(handle,
4545ac27a0ecSDave Kleikamp 								   parent_bh)){
4546ac27a0ecSDave Kleikamp 					*p = 0;
4547ac27a0ecSDave Kleikamp 					BUFFER_TRACE(parent_bh,
45480390131bSFrank Mayhar 					"call ext4_handle_dirty_metadata");
45490390131bSFrank Mayhar 					ext4_handle_dirty_metadata(handle,
45500390131bSFrank Mayhar 								   inode,
4551ac27a0ecSDave Kleikamp 								   parent_bh);
4552ac27a0ecSDave Kleikamp 				}
4553ac27a0ecSDave Kleikamp 			}
4554ac27a0ecSDave Kleikamp 		}
4555ac27a0ecSDave Kleikamp 	} else {
4556ac27a0ecSDave Kleikamp 		/* We have reached the bottom of the tree. */
4557ac27a0ecSDave Kleikamp 		BUFFER_TRACE(parent_bh, "free data blocks");
4558617ba13bSMingming Cao 		ext4_free_data(handle, inode, parent_bh, first, last);
4559ac27a0ecSDave Kleikamp 	}
4560ac27a0ecSDave Kleikamp }
4561ac27a0ecSDave Kleikamp 
456291ef4cafSDuane Griffin int ext4_can_truncate(struct inode *inode)
456391ef4cafSDuane Griffin {
456491ef4cafSDuane Griffin 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
456591ef4cafSDuane Griffin 		return 0;
456691ef4cafSDuane Griffin 	if (S_ISREG(inode->i_mode))
456791ef4cafSDuane Griffin 		return 1;
456891ef4cafSDuane Griffin 	if (S_ISDIR(inode->i_mode))
456991ef4cafSDuane Griffin 		return 1;
457091ef4cafSDuane Griffin 	if (S_ISLNK(inode->i_mode))
457191ef4cafSDuane Griffin 		return !ext4_inode_is_fast_symlink(inode);
457291ef4cafSDuane Griffin 	return 0;
457391ef4cafSDuane Griffin }
457491ef4cafSDuane Griffin 
4575ac27a0ecSDave Kleikamp /*
4576617ba13bSMingming Cao  * ext4_truncate()
4577ac27a0ecSDave Kleikamp  *
4578617ba13bSMingming Cao  * We block out ext4_get_block() block instantiations across the entire
4579617ba13bSMingming Cao  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4580ac27a0ecSDave Kleikamp  * simultaneously on behalf of the same inode.
4581ac27a0ecSDave Kleikamp  *
4582ac27a0ecSDave Kleikamp  * As we work through the truncate and commmit bits of it to the journal there
4583ac27a0ecSDave Kleikamp  * is one core, guiding principle: the file's tree must always be consistent on
4584ac27a0ecSDave Kleikamp  * disk.  We must be able to restart the truncate after a crash.
4585ac27a0ecSDave Kleikamp  *
4586ac27a0ecSDave Kleikamp  * The file's tree may be transiently inconsistent in memory (although it
4587ac27a0ecSDave Kleikamp  * probably isn't), but whenever we close off and commit a journal transaction,
4588ac27a0ecSDave Kleikamp  * the contents of (the filesystem + the journal) must be consistent and
4589ac27a0ecSDave Kleikamp  * restartable.  It's pretty simple, really: bottom up, right to left (although
4590ac27a0ecSDave Kleikamp  * left-to-right works OK too).
4591ac27a0ecSDave Kleikamp  *
4592ac27a0ecSDave Kleikamp  * Note that at recovery time, journal replay occurs *before* the restart of
4593ac27a0ecSDave Kleikamp  * truncate against the orphan inode list.
4594ac27a0ecSDave Kleikamp  *
4595ac27a0ecSDave Kleikamp  * The committed inode has the new, desired i_size (which is the same as
4596617ba13bSMingming Cao  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4597ac27a0ecSDave Kleikamp  * that this inode's truncate did not complete and it will again call
4598617ba13bSMingming Cao  * ext4_truncate() to have another go.  So there will be instantiated blocks
4599617ba13bSMingming Cao  * to the right of the truncation point in a crashed ext4 filesystem.  But
4600ac27a0ecSDave Kleikamp  * that's fine - as long as they are linked from the inode, the post-crash
4601617ba13bSMingming Cao  * ext4_truncate() run will find them and release them.
4602ac27a0ecSDave Kleikamp  */
4603617ba13bSMingming Cao void ext4_truncate(struct inode *inode)
4604ac27a0ecSDave Kleikamp {
4605ac27a0ecSDave Kleikamp 	handle_t *handle;
4606617ba13bSMingming Cao 	struct ext4_inode_info *ei = EXT4_I(inode);
4607ac27a0ecSDave Kleikamp 	__le32 *i_data = ei->i_data;
4608617ba13bSMingming Cao 	int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4609ac27a0ecSDave Kleikamp 	struct address_space *mapping = inode->i_mapping;
4610725d26d3SAneesh Kumar K.V 	ext4_lblk_t offsets[4];
4611ac27a0ecSDave Kleikamp 	Indirect chain[4];
4612ac27a0ecSDave Kleikamp 	Indirect *partial;
4613ac27a0ecSDave Kleikamp 	__le32 nr = 0;
4614ac27a0ecSDave Kleikamp 	int n;
4615725d26d3SAneesh Kumar K.V 	ext4_lblk_t last_block;
4616ac27a0ecSDave Kleikamp 	unsigned blocksize = inode->i_sb->s_blocksize;
4617ac27a0ecSDave Kleikamp 
461891ef4cafSDuane Griffin 	if (!ext4_can_truncate(inode))
4619ac27a0ecSDave Kleikamp 		return;
4620ac27a0ecSDave Kleikamp 
462112e9b892SDmitry Monakhov 	ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4622c8d46e41SJiaying Zhang 
46235534fb5bSTheodore Ts'o 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
462419f5fb7aSTheodore Ts'o 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
46257d8f9f7dSTheodore Ts'o 
462612e9b892SDmitry Monakhov 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4627cf108bcaSJan Kara 		ext4_ext_truncate(inode);
46281d03ec98SAneesh Kumar K.V 		return;
46291d03ec98SAneesh Kumar K.V 	}
4630a86c6181SAlex Tomas 
4631ac27a0ecSDave Kleikamp 	handle = start_transaction(inode);
4632cf108bcaSJan Kara 	if (IS_ERR(handle))
4633ac27a0ecSDave Kleikamp 		return;		/* AKPM: return what? */
4634ac27a0ecSDave Kleikamp 
4635ac27a0ecSDave Kleikamp 	last_block = (inode->i_size + blocksize-1)
4636617ba13bSMingming Cao 					>> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
4637ac27a0ecSDave Kleikamp 
4638cf108bcaSJan Kara 	if (inode->i_size & (blocksize - 1))
4639cf108bcaSJan Kara 		if (ext4_block_truncate_page(handle, mapping, inode->i_size))
4640cf108bcaSJan Kara 			goto out_stop;
4641ac27a0ecSDave Kleikamp 
4642617ba13bSMingming Cao 	n = ext4_block_to_path(inode, last_block, offsets, NULL);
4643ac27a0ecSDave Kleikamp 	if (n == 0)
4644ac27a0ecSDave Kleikamp 		goto out_stop;	/* error */
4645ac27a0ecSDave Kleikamp 
4646ac27a0ecSDave Kleikamp 	/*
4647ac27a0ecSDave Kleikamp 	 * OK.  This truncate is going to happen.  We add the inode to the
4648ac27a0ecSDave Kleikamp 	 * orphan list, so that if this truncate spans multiple transactions,
4649ac27a0ecSDave Kleikamp 	 * and we crash, we will resume the truncate when the filesystem
4650ac27a0ecSDave Kleikamp 	 * recovers.  It also marks the inode dirty, to catch the new size.
4651ac27a0ecSDave Kleikamp 	 *
4652ac27a0ecSDave Kleikamp 	 * Implication: the file must always be in a sane, consistent
4653ac27a0ecSDave Kleikamp 	 * truncatable state while each transaction commits.
4654ac27a0ecSDave Kleikamp 	 */
4655617ba13bSMingming Cao 	if (ext4_orphan_add(handle, inode))
4656ac27a0ecSDave Kleikamp 		goto out_stop;
4657ac27a0ecSDave Kleikamp 
4658ac27a0ecSDave Kleikamp 	/*
4659632eaeabSMingming Cao 	 * From here we block out all ext4_get_block() callers who want to
4660632eaeabSMingming Cao 	 * modify the block allocation tree.
4661632eaeabSMingming Cao 	 */
4662632eaeabSMingming Cao 	down_write(&ei->i_data_sem);
4663b4df2030STheodore Ts'o 
4664c2ea3fdeSTheodore Ts'o 	ext4_discard_preallocations(inode);
4665b4df2030STheodore Ts'o 
4666632eaeabSMingming Cao 	/*
4667ac27a0ecSDave Kleikamp 	 * The orphan list entry will now protect us from any crash which
4668ac27a0ecSDave Kleikamp 	 * occurs before the truncate completes, so it is now safe to propagate
4669ac27a0ecSDave Kleikamp 	 * the new, shorter inode size (held for now in i_size) into the
4670ac27a0ecSDave Kleikamp 	 * on-disk inode. We do this via i_disksize, which is the value which
4671617ba13bSMingming Cao 	 * ext4 *really* writes onto the disk inode.
4672ac27a0ecSDave Kleikamp 	 */
4673ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
4674ac27a0ecSDave Kleikamp 
4675ac27a0ecSDave Kleikamp 	if (n == 1) {		/* direct blocks */
4676617ba13bSMingming Cao 		ext4_free_data(handle, inode, NULL, i_data+offsets[0],
4677617ba13bSMingming Cao 			       i_data + EXT4_NDIR_BLOCKS);
4678ac27a0ecSDave Kleikamp 		goto do_indirects;
4679ac27a0ecSDave Kleikamp 	}
4680ac27a0ecSDave Kleikamp 
4681617ba13bSMingming Cao 	partial = ext4_find_shared(inode, n, offsets, chain, &nr);
4682ac27a0ecSDave Kleikamp 	/* Kill the top of shared branch (not detached) */
4683ac27a0ecSDave Kleikamp 	if (nr) {
4684ac27a0ecSDave Kleikamp 		if (partial == chain) {
4685ac27a0ecSDave Kleikamp 			/* Shared branch grows from the inode */
4686617ba13bSMingming Cao 			ext4_free_branches(handle, inode, NULL,
4687ac27a0ecSDave Kleikamp 					   &nr, &nr+1, (chain+n-1) - partial);
4688ac27a0ecSDave Kleikamp 			*partial->p = 0;
4689ac27a0ecSDave Kleikamp 			/*
4690ac27a0ecSDave Kleikamp 			 * We mark the inode dirty prior to restart,
4691ac27a0ecSDave Kleikamp 			 * and prior to stop.  No need for it here.
4692ac27a0ecSDave Kleikamp 			 */
4693ac27a0ecSDave Kleikamp 		} else {
4694ac27a0ecSDave Kleikamp 			/* Shared branch grows from an indirect block */
4695ac27a0ecSDave Kleikamp 			BUFFER_TRACE(partial->bh, "get_write_access");
4696617ba13bSMingming Cao 			ext4_free_branches(handle, inode, partial->bh,
4697ac27a0ecSDave Kleikamp 					partial->p,
4698ac27a0ecSDave Kleikamp 					partial->p+1, (chain+n-1) - partial);
4699ac27a0ecSDave Kleikamp 		}
4700ac27a0ecSDave Kleikamp 	}
4701ac27a0ecSDave Kleikamp 	/* Clear the ends of indirect blocks on the shared branch */
4702ac27a0ecSDave Kleikamp 	while (partial > chain) {
4703617ba13bSMingming Cao 		ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
4704ac27a0ecSDave Kleikamp 				   (__le32*)partial->bh->b_data+addr_per_block,
4705ac27a0ecSDave Kleikamp 				   (chain+n-1) - partial);
4706ac27a0ecSDave Kleikamp 		BUFFER_TRACE(partial->bh, "call brelse");
4707ac27a0ecSDave Kleikamp 		brelse(partial->bh);
4708ac27a0ecSDave Kleikamp 		partial--;
4709ac27a0ecSDave Kleikamp 	}
4710ac27a0ecSDave Kleikamp do_indirects:
4711ac27a0ecSDave Kleikamp 	/* Kill the remaining (whole) subtrees */
4712ac27a0ecSDave Kleikamp 	switch (offsets[0]) {
4713ac27a0ecSDave Kleikamp 	default:
4714617ba13bSMingming Cao 		nr = i_data[EXT4_IND_BLOCK];
4715ac27a0ecSDave Kleikamp 		if (nr) {
4716617ba13bSMingming Cao 			ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
4717617ba13bSMingming Cao 			i_data[EXT4_IND_BLOCK] = 0;
4718ac27a0ecSDave Kleikamp 		}
4719617ba13bSMingming Cao 	case EXT4_IND_BLOCK:
4720617ba13bSMingming Cao 		nr = i_data[EXT4_DIND_BLOCK];
4721ac27a0ecSDave Kleikamp 		if (nr) {
4722617ba13bSMingming Cao 			ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
4723617ba13bSMingming Cao 			i_data[EXT4_DIND_BLOCK] = 0;
4724ac27a0ecSDave Kleikamp 		}
4725617ba13bSMingming Cao 	case EXT4_DIND_BLOCK:
4726617ba13bSMingming Cao 		nr = i_data[EXT4_TIND_BLOCK];
4727ac27a0ecSDave Kleikamp 		if (nr) {
4728617ba13bSMingming Cao 			ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
4729617ba13bSMingming Cao 			i_data[EXT4_TIND_BLOCK] = 0;
4730ac27a0ecSDave Kleikamp 		}
4731617ba13bSMingming Cao 	case EXT4_TIND_BLOCK:
4732ac27a0ecSDave Kleikamp 		;
4733ac27a0ecSDave Kleikamp 	}
4734ac27a0ecSDave Kleikamp 
47350e855ac8SAneesh Kumar K.V 	up_write(&ei->i_data_sem);
4736ef7f3835SKalpak Shah 	inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4737617ba13bSMingming Cao 	ext4_mark_inode_dirty(handle, inode);
4738ac27a0ecSDave Kleikamp 
4739ac27a0ecSDave Kleikamp 	/*
4740ac27a0ecSDave Kleikamp 	 * In a multi-transaction truncate, we only make the final transaction
4741ac27a0ecSDave Kleikamp 	 * synchronous
4742ac27a0ecSDave Kleikamp 	 */
4743ac27a0ecSDave Kleikamp 	if (IS_SYNC(inode))
47440390131bSFrank Mayhar 		ext4_handle_sync(handle);
4745ac27a0ecSDave Kleikamp out_stop:
4746ac27a0ecSDave Kleikamp 	/*
4747ac27a0ecSDave Kleikamp 	 * If this was a simple ftruncate(), and the file will remain alive
4748ac27a0ecSDave Kleikamp 	 * then we need to clear up the orphan record which we created above.
4749ac27a0ecSDave Kleikamp 	 * However, if this was a real unlink then we were called by
4750617ba13bSMingming Cao 	 * ext4_delete_inode(), and we allow that function to clean up the
4751ac27a0ecSDave Kleikamp 	 * orphan info for us.
4752ac27a0ecSDave Kleikamp 	 */
4753ac27a0ecSDave Kleikamp 	if (inode->i_nlink)
4754617ba13bSMingming Cao 		ext4_orphan_del(handle, inode);
4755ac27a0ecSDave Kleikamp 
4756617ba13bSMingming Cao 	ext4_journal_stop(handle);
4757ac27a0ecSDave Kleikamp }
4758ac27a0ecSDave Kleikamp 
4759ac27a0ecSDave Kleikamp /*
4760617ba13bSMingming Cao  * ext4_get_inode_loc returns with an extra refcount against the inode's
4761ac27a0ecSDave Kleikamp  * underlying buffer_head on success. If 'in_mem' is true, we have all
4762ac27a0ecSDave Kleikamp  * data in memory that is needed to recreate the on-disk version of this
4763ac27a0ecSDave Kleikamp  * inode.
4764ac27a0ecSDave Kleikamp  */
4765617ba13bSMingming Cao static int __ext4_get_inode_loc(struct inode *inode,
4766617ba13bSMingming Cao 				struct ext4_iloc *iloc, int in_mem)
4767ac27a0ecSDave Kleikamp {
4768240799cdSTheodore Ts'o 	struct ext4_group_desc	*gdp;
4769ac27a0ecSDave Kleikamp 	struct buffer_head	*bh;
4770240799cdSTheodore Ts'o 	struct super_block	*sb = inode->i_sb;
4771240799cdSTheodore Ts'o 	ext4_fsblk_t		block;
4772240799cdSTheodore Ts'o 	int			inodes_per_block, inode_offset;
4773ac27a0ecSDave Kleikamp 
47743a06d778SAneesh Kumar K.V 	iloc->bh = NULL;
4775240799cdSTheodore Ts'o 	if (!ext4_valid_inum(sb, inode->i_ino))
4776ac27a0ecSDave Kleikamp 		return -EIO;
4777ac27a0ecSDave Kleikamp 
4778240799cdSTheodore Ts'o 	iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4779240799cdSTheodore Ts'o 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4780240799cdSTheodore Ts'o 	if (!gdp)
4781240799cdSTheodore Ts'o 		return -EIO;
4782240799cdSTheodore Ts'o 
4783240799cdSTheodore Ts'o 	/*
4784240799cdSTheodore Ts'o 	 * Figure out the offset within the block group inode table
4785240799cdSTheodore Ts'o 	 */
4786240799cdSTheodore Ts'o 	inodes_per_block = (EXT4_BLOCK_SIZE(sb) / EXT4_INODE_SIZE(sb));
4787240799cdSTheodore Ts'o 	inode_offset = ((inode->i_ino - 1) %
4788240799cdSTheodore Ts'o 			EXT4_INODES_PER_GROUP(sb));
4789240799cdSTheodore Ts'o 	block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4790240799cdSTheodore Ts'o 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4791240799cdSTheodore Ts'o 
4792240799cdSTheodore Ts'o 	bh = sb_getblk(sb, block);
4793ac27a0ecSDave Kleikamp 	if (!bh) {
4794*c398eda0STheodore Ts'o 		EXT4_ERROR_INODE_BLOCK(inode, block,
4795*c398eda0STheodore Ts'o 				       "unable to read itable block");
4796ac27a0ecSDave Kleikamp 		return -EIO;
4797ac27a0ecSDave Kleikamp 	}
4798ac27a0ecSDave Kleikamp 	if (!buffer_uptodate(bh)) {
4799ac27a0ecSDave Kleikamp 		lock_buffer(bh);
48009c83a923SHidehiro Kawai 
48019c83a923SHidehiro Kawai 		/*
48029c83a923SHidehiro Kawai 		 * If the buffer has the write error flag, we have failed
48039c83a923SHidehiro Kawai 		 * to write out another inode in the same block.  In this
48049c83a923SHidehiro Kawai 		 * case, we don't have to read the block because we may
48059c83a923SHidehiro Kawai 		 * read the old inode data successfully.
48069c83a923SHidehiro Kawai 		 */
48079c83a923SHidehiro Kawai 		if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
48089c83a923SHidehiro Kawai 			set_buffer_uptodate(bh);
48099c83a923SHidehiro Kawai 
4810ac27a0ecSDave Kleikamp 		if (buffer_uptodate(bh)) {
4811ac27a0ecSDave Kleikamp 			/* someone brought it uptodate while we waited */
4812ac27a0ecSDave Kleikamp 			unlock_buffer(bh);
4813ac27a0ecSDave Kleikamp 			goto has_buffer;
4814ac27a0ecSDave Kleikamp 		}
4815ac27a0ecSDave Kleikamp 
4816ac27a0ecSDave Kleikamp 		/*
4817ac27a0ecSDave Kleikamp 		 * If we have all information of the inode in memory and this
4818ac27a0ecSDave Kleikamp 		 * is the only valid inode in the block, we need not read the
4819ac27a0ecSDave Kleikamp 		 * block.
4820ac27a0ecSDave Kleikamp 		 */
4821ac27a0ecSDave Kleikamp 		if (in_mem) {
4822ac27a0ecSDave Kleikamp 			struct buffer_head *bitmap_bh;
4823240799cdSTheodore Ts'o 			int i, start;
4824ac27a0ecSDave Kleikamp 
4825240799cdSTheodore Ts'o 			start = inode_offset & ~(inodes_per_block - 1);
4826ac27a0ecSDave Kleikamp 
4827ac27a0ecSDave Kleikamp 			/* Is the inode bitmap in cache? */
4828240799cdSTheodore Ts'o 			bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4829ac27a0ecSDave Kleikamp 			if (!bitmap_bh)
4830ac27a0ecSDave Kleikamp 				goto make_io;
4831ac27a0ecSDave Kleikamp 
4832ac27a0ecSDave Kleikamp 			/*
4833ac27a0ecSDave Kleikamp 			 * If the inode bitmap isn't in cache then the
4834ac27a0ecSDave Kleikamp 			 * optimisation may end up performing two reads instead
4835ac27a0ecSDave Kleikamp 			 * of one, so skip it.
4836ac27a0ecSDave Kleikamp 			 */
4837ac27a0ecSDave Kleikamp 			if (!buffer_uptodate(bitmap_bh)) {
4838ac27a0ecSDave Kleikamp 				brelse(bitmap_bh);
4839ac27a0ecSDave Kleikamp 				goto make_io;
4840ac27a0ecSDave Kleikamp 			}
4841240799cdSTheodore Ts'o 			for (i = start; i < start + inodes_per_block; i++) {
4842ac27a0ecSDave Kleikamp 				if (i == inode_offset)
4843ac27a0ecSDave Kleikamp 					continue;
4844617ba13bSMingming Cao 				if (ext4_test_bit(i, bitmap_bh->b_data))
4845ac27a0ecSDave Kleikamp 					break;
4846ac27a0ecSDave Kleikamp 			}
4847ac27a0ecSDave Kleikamp 			brelse(bitmap_bh);
4848240799cdSTheodore Ts'o 			if (i == start + inodes_per_block) {
4849ac27a0ecSDave Kleikamp 				/* all other inodes are free, so skip I/O */
4850ac27a0ecSDave Kleikamp 				memset(bh->b_data, 0, bh->b_size);
4851ac27a0ecSDave Kleikamp 				set_buffer_uptodate(bh);
4852ac27a0ecSDave Kleikamp 				unlock_buffer(bh);
4853ac27a0ecSDave Kleikamp 				goto has_buffer;
4854ac27a0ecSDave Kleikamp 			}
4855ac27a0ecSDave Kleikamp 		}
4856ac27a0ecSDave Kleikamp 
4857ac27a0ecSDave Kleikamp make_io:
4858ac27a0ecSDave Kleikamp 		/*
4859240799cdSTheodore Ts'o 		 * If we need to do any I/O, try to pre-readahead extra
4860240799cdSTheodore Ts'o 		 * blocks from the inode table.
4861240799cdSTheodore Ts'o 		 */
4862240799cdSTheodore Ts'o 		if (EXT4_SB(sb)->s_inode_readahead_blks) {
4863240799cdSTheodore Ts'o 			ext4_fsblk_t b, end, table;
4864240799cdSTheodore Ts'o 			unsigned num;
4865240799cdSTheodore Ts'o 
4866240799cdSTheodore Ts'o 			table = ext4_inode_table(sb, gdp);
4867b713a5ecSTheodore Ts'o 			/* s_inode_readahead_blks is always a power of 2 */
4868240799cdSTheodore Ts'o 			b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
4869240799cdSTheodore Ts'o 			if (table > b)
4870240799cdSTheodore Ts'o 				b = table;
4871240799cdSTheodore Ts'o 			end = b + EXT4_SB(sb)->s_inode_readahead_blks;
4872240799cdSTheodore Ts'o 			num = EXT4_INODES_PER_GROUP(sb);
4873240799cdSTheodore Ts'o 			if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4874240799cdSTheodore Ts'o 				       EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
4875560671a0SAneesh Kumar K.V 				num -= ext4_itable_unused_count(sb, gdp);
4876240799cdSTheodore Ts'o 			table += num / inodes_per_block;
4877240799cdSTheodore Ts'o 			if (end > table)
4878240799cdSTheodore Ts'o 				end = table;
4879240799cdSTheodore Ts'o 			while (b <= end)
4880240799cdSTheodore Ts'o 				sb_breadahead(sb, b++);
4881240799cdSTheodore Ts'o 		}
4882240799cdSTheodore Ts'o 
4883240799cdSTheodore Ts'o 		/*
4884ac27a0ecSDave Kleikamp 		 * There are other valid inodes in the buffer, this inode
4885ac27a0ecSDave Kleikamp 		 * has in-inode xattrs, or we don't have this inode in memory.
4886ac27a0ecSDave Kleikamp 		 * Read the block from disk.
4887ac27a0ecSDave Kleikamp 		 */
4888ac27a0ecSDave Kleikamp 		get_bh(bh);
4889ac27a0ecSDave Kleikamp 		bh->b_end_io = end_buffer_read_sync;
4890ac27a0ecSDave Kleikamp 		submit_bh(READ_META, bh);
4891ac27a0ecSDave Kleikamp 		wait_on_buffer(bh);
4892ac27a0ecSDave Kleikamp 		if (!buffer_uptodate(bh)) {
4893*c398eda0STheodore Ts'o 			EXT4_ERROR_INODE_BLOCK(inode, block,
4894*c398eda0STheodore Ts'o 					       "unable to read itable block");
4895ac27a0ecSDave Kleikamp 			brelse(bh);
4896ac27a0ecSDave Kleikamp 			return -EIO;
4897ac27a0ecSDave Kleikamp 		}
4898ac27a0ecSDave Kleikamp 	}
4899ac27a0ecSDave Kleikamp has_buffer:
4900ac27a0ecSDave Kleikamp 	iloc->bh = bh;
4901ac27a0ecSDave Kleikamp 	return 0;
4902ac27a0ecSDave Kleikamp }
4903ac27a0ecSDave Kleikamp 
4904617ba13bSMingming Cao int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4905ac27a0ecSDave Kleikamp {
4906ac27a0ecSDave Kleikamp 	/* We have all inode data except xattrs in memory here. */
4907617ba13bSMingming Cao 	return __ext4_get_inode_loc(inode, iloc,
490819f5fb7aSTheodore Ts'o 		!ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4909ac27a0ecSDave Kleikamp }
4910ac27a0ecSDave Kleikamp 
4911617ba13bSMingming Cao void ext4_set_inode_flags(struct inode *inode)
4912ac27a0ecSDave Kleikamp {
4913617ba13bSMingming Cao 	unsigned int flags = EXT4_I(inode)->i_flags;
4914ac27a0ecSDave Kleikamp 
4915ac27a0ecSDave Kleikamp 	inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
4916617ba13bSMingming Cao 	if (flags & EXT4_SYNC_FL)
4917ac27a0ecSDave Kleikamp 		inode->i_flags |= S_SYNC;
4918617ba13bSMingming Cao 	if (flags & EXT4_APPEND_FL)
4919ac27a0ecSDave Kleikamp 		inode->i_flags |= S_APPEND;
4920617ba13bSMingming Cao 	if (flags & EXT4_IMMUTABLE_FL)
4921ac27a0ecSDave Kleikamp 		inode->i_flags |= S_IMMUTABLE;
4922617ba13bSMingming Cao 	if (flags & EXT4_NOATIME_FL)
4923ac27a0ecSDave Kleikamp 		inode->i_flags |= S_NOATIME;
4924617ba13bSMingming Cao 	if (flags & EXT4_DIRSYNC_FL)
4925ac27a0ecSDave Kleikamp 		inode->i_flags |= S_DIRSYNC;
4926ac27a0ecSDave Kleikamp }
4927ac27a0ecSDave Kleikamp 
4928ff9ddf7eSJan Kara /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4929ff9ddf7eSJan Kara void ext4_get_inode_flags(struct ext4_inode_info *ei)
4930ff9ddf7eSJan Kara {
493184a8dce2SDmitry Monakhov 	unsigned int vfs_fl;
493284a8dce2SDmitry Monakhov 	unsigned long old_fl, new_fl;
4933ff9ddf7eSJan Kara 
493484a8dce2SDmitry Monakhov 	do {
493584a8dce2SDmitry Monakhov 		vfs_fl = ei->vfs_inode.i_flags;
493684a8dce2SDmitry Monakhov 		old_fl = ei->i_flags;
493784a8dce2SDmitry Monakhov 		new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
493884a8dce2SDmitry Monakhov 				EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
493984a8dce2SDmitry Monakhov 				EXT4_DIRSYNC_FL);
494084a8dce2SDmitry Monakhov 		if (vfs_fl & S_SYNC)
494184a8dce2SDmitry Monakhov 			new_fl |= EXT4_SYNC_FL;
494284a8dce2SDmitry Monakhov 		if (vfs_fl & S_APPEND)
494384a8dce2SDmitry Monakhov 			new_fl |= EXT4_APPEND_FL;
494484a8dce2SDmitry Monakhov 		if (vfs_fl & S_IMMUTABLE)
494584a8dce2SDmitry Monakhov 			new_fl |= EXT4_IMMUTABLE_FL;
494684a8dce2SDmitry Monakhov 		if (vfs_fl & S_NOATIME)
494784a8dce2SDmitry Monakhov 			new_fl |= EXT4_NOATIME_FL;
494884a8dce2SDmitry Monakhov 		if (vfs_fl & S_DIRSYNC)
494984a8dce2SDmitry Monakhov 			new_fl |= EXT4_DIRSYNC_FL;
495084a8dce2SDmitry Monakhov 	} while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
4951ff9ddf7eSJan Kara }
4952de9a55b8STheodore Ts'o 
49530fc1b451SAneesh Kumar K.V static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
49540fc1b451SAneesh Kumar K.V 				  struct ext4_inode_info *ei)
49550fc1b451SAneesh Kumar K.V {
49560fc1b451SAneesh Kumar K.V 	blkcnt_t i_blocks ;
49578180a562SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
49588180a562SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
49590fc1b451SAneesh Kumar K.V 
49600fc1b451SAneesh Kumar K.V 	if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
49610fc1b451SAneesh Kumar K.V 				EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
49620fc1b451SAneesh Kumar K.V 		/* we are using combined 48 bit field */
49630fc1b451SAneesh Kumar K.V 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
49640fc1b451SAneesh Kumar K.V 					le32_to_cpu(raw_inode->i_blocks_lo);
496507a03824STheodore Ts'o 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
49668180a562SAneesh Kumar K.V 			/* i_blocks represent file system block size */
49678180a562SAneesh Kumar K.V 			return i_blocks  << (inode->i_blkbits - 9);
49688180a562SAneesh Kumar K.V 		} else {
49690fc1b451SAneesh Kumar K.V 			return i_blocks;
49708180a562SAneesh Kumar K.V 		}
49710fc1b451SAneesh Kumar K.V 	} else {
49720fc1b451SAneesh Kumar K.V 		return le32_to_cpu(raw_inode->i_blocks_lo);
49730fc1b451SAneesh Kumar K.V 	}
49740fc1b451SAneesh Kumar K.V }
4975ff9ddf7eSJan Kara 
49761d1fe1eeSDavid Howells struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4977ac27a0ecSDave Kleikamp {
4978617ba13bSMingming Cao 	struct ext4_iloc iloc;
4979617ba13bSMingming Cao 	struct ext4_inode *raw_inode;
49801d1fe1eeSDavid Howells 	struct ext4_inode_info *ei;
49811d1fe1eeSDavid Howells 	struct inode *inode;
4982b436b9beSJan Kara 	journal_t *journal = EXT4_SB(sb)->s_journal;
49831d1fe1eeSDavid Howells 	long ret;
4984ac27a0ecSDave Kleikamp 	int block;
4985ac27a0ecSDave Kleikamp 
49861d1fe1eeSDavid Howells 	inode = iget_locked(sb, ino);
49871d1fe1eeSDavid Howells 	if (!inode)
49881d1fe1eeSDavid Howells 		return ERR_PTR(-ENOMEM);
49891d1fe1eeSDavid Howells 	if (!(inode->i_state & I_NEW))
49901d1fe1eeSDavid Howells 		return inode;
49911d1fe1eeSDavid Howells 
49921d1fe1eeSDavid Howells 	ei = EXT4_I(inode);
4993567f3e9aSTheodore Ts'o 	iloc.bh = 0;
4994ac27a0ecSDave Kleikamp 
49951d1fe1eeSDavid Howells 	ret = __ext4_get_inode_loc(inode, &iloc, 0);
49961d1fe1eeSDavid Howells 	if (ret < 0)
4997ac27a0ecSDave Kleikamp 		goto bad_inode;
4998617ba13bSMingming Cao 	raw_inode = ext4_raw_inode(&iloc);
4999ac27a0ecSDave Kleikamp 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
5000ac27a0ecSDave Kleikamp 	inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
5001ac27a0ecSDave Kleikamp 	inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
5002ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
5003ac27a0ecSDave Kleikamp 		inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
5004ac27a0ecSDave Kleikamp 		inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
5005ac27a0ecSDave Kleikamp 	}
5006ac27a0ecSDave Kleikamp 	inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
5007ac27a0ecSDave Kleikamp 
500819f5fb7aSTheodore Ts'o 	ei->i_state_flags = 0;
5009ac27a0ecSDave Kleikamp 	ei->i_dir_start_lookup = 0;
5010ac27a0ecSDave Kleikamp 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
5011ac27a0ecSDave Kleikamp 	/* We now have enough fields to check if the inode was active or not.
5012ac27a0ecSDave Kleikamp 	 * This is needed because nfsd might try to access dead inodes
5013ac27a0ecSDave Kleikamp 	 * the test is that same one that e2fsck uses
5014ac27a0ecSDave Kleikamp 	 * NeilBrown 1999oct15
5015ac27a0ecSDave Kleikamp 	 */
5016ac27a0ecSDave Kleikamp 	if (inode->i_nlink == 0) {
5017ac27a0ecSDave Kleikamp 		if (inode->i_mode == 0 ||
5018617ba13bSMingming Cao 		    !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
5019ac27a0ecSDave Kleikamp 			/* this inode is deleted */
50201d1fe1eeSDavid Howells 			ret = -ESTALE;
5021ac27a0ecSDave Kleikamp 			goto bad_inode;
5022ac27a0ecSDave Kleikamp 		}
5023ac27a0ecSDave Kleikamp 		/* The only unlinked inodes we let through here have
5024ac27a0ecSDave Kleikamp 		 * valid i_mode and are being read by the orphan
5025ac27a0ecSDave Kleikamp 		 * recovery code: that's fine, we're about to complete
5026ac27a0ecSDave Kleikamp 		 * the process of deleting those. */
5027ac27a0ecSDave Kleikamp 	}
5028ac27a0ecSDave Kleikamp 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
50290fc1b451SAneesh Kumar K.V 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
50307973c0c1SAneesh Kumar K.V 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
5031a9e81742STheodore Ts'o 	if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
5032a1ddeb7eSBadari Pulavarty 		ei->i_file_acl |=
5033a1ddeb7eSBadari Pulavarty 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
5034a48380f7SAneesh Kumar K.V 	inode->i_size = ext4_isize(raw_inode);
5035ac27a0ecSDave Kleikamp 	ei->i_disksize = inode->i_size;
5036a9e7f447SDmitry Monakhov #ifdef CONFIG_QUOTA
5037a9e7f447SDmitry Monakhov 	ei->i_reserved_quota = 0;
5038a9e7f447SDmitry Monakhov #endif
5039ac27a0ecSDave Kleikamp 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
5040ac27a0ecSDave Kleikamp 	ei->i_block_group = iloc.block_group;
5041a4912123STheodore Ts'o 	ei->i_last_alloc_group = ~0;
5042ac27a0ecSDave Kleikamp 	/*
5043ac27a0ecSDave Kleikamp 	 * NOTE! The in-memory inode i_data array is in little-endian order
5044ac27a0ecSDave Kleikamp 	 * even on big-endian machines: we do NOT byteswap the block numbers!
5045ac27a0ecSDave Kleikamp 	 */
5046617ba13bSMingming Cao 	for (block = 0; block < EXT4_N_BLOCKS; block++)
5047ac27a0ecSDave Kleikamp 		ei->i_data[block] = raw_inode->i_block[block];
5048ac27a0ecSDave Kleikamp 	INIT_LIST_HEAD(&ei->i_orphan);
5049ac27a0ecSDave Kleikamp 
5050b436b9beSJan Kara 	/*
5051b436b9beSJan Kara 	 * Set transaction id's of transactions that have to be committed
5052b436b9beSJan Kara 	 * to finish f[data]sync. We set them to currently running transaction
5053b436b9beSJan Kara 	 * as we cannot be sure that the inode or some of its metadata isn't
5054b436b9beSJan Kara 	 * part of the transaction - the inode could have been reclaimed and
5055b436b9beSJan Kara 	 * now it is reread from disk.
5056b436b9beSJan Kara 	 */
5057b436b9beSJan Kara 	if (journal) {
5058b436b9beSJan Kara 		transaction_t *transaction;
5059b436b9beSJan Kara 		tid_t tid;
5060b436b9beSJan Kara 
5061b436b9beSJan Kara 		spin_lock(&journal->j_state_lock);
5062b436b9beSJan Kara 		if (journal->j_running_transaction)
5063b436b9beSJan Kara 			transaction = journal->j_running_transaction;
5064b436b9beSJan Kara 		else
5065b436b9beSJan Kara 			transaction = journal->j_committing_transaction;
5066b436b9beSJan Kara 		if (transaction)
5067b436b9beSJan Kara 			tid = transaction->t_tid;
5068b436b9beSJan Kara 		else
5069b436b9beSJan Kara 			tid = journal->j_commit_sequence;
5070b436b9beSJan Kara 		spin_unlock(&journal->j_state_lock);
5071b436b9beSJan Kara 		ei->i_sync_tid = tid;
5072b436b9beSJan Kara 		ei->i_datasync_tid = tid;
5073b436b9beSJan Kara 	}
5074b436b9beSJan Kara 
50750040d987SEric Sandeen 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5076ac27a0ecSDave Kleikamp 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
5077617ba13bSMingming Cao 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
5078e5d2861fSKirill Korotaev 		    EXT4_INODE_SIZE(inode->i_sb)) {
50791d1fe1eeSDavid Howells 			ret = -EIO;
5080ac27a0ecSDave Kleikamp 			goto bad_inode;
5081e5d2861fSKirill Korotaev 		}
5082ac27a0ecSDave Kleikamp 		if (ei->i_extra_isize == 0) {
5083ac27a0ecSDave Kleikamp 			/* The extra space is currently unused. Use it. */
5084617ba13bSMingming Cao 			ei->i_extra_isize = sizeof(struct ext4_inode) -
5085617ba13bSMingming Cao 					    EXT4_GOOD_OLD_INODE_SIZE;
5086ac27a0ecSDave Kleikamp 		} else {
5087ac27a0ecSDave Kleikamp 			__le32 *magic = (void *)raw_inode +
5088617ba13bSMingming Cao 					EXT4_GOOD_OLD_INODE_SIZE +
5089ac27a0ecSDave Kleikamp 					ei->i_extra_isize;
5090617ba13bSMingming Cao 			if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
509119f5fb7aSTheodore Ts'o 				ext4_set_inode_state(inode, EXT4_STATE_XATTR);
5092ac27a0ecSDave Kleikamp 		}
5093ac27a0ecSDave Kleikamp 	} else
5094ac27a0ecSDave Kleikamp 		ei->i_extra_isize = 0;
5095ac27a0ecSDave Kleikamp 
5096ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
5097ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
5098ef7f3835SKalpak Shah 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
5099ef7f3835SKalpak Shah 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
5100ef7f3835SKalpak Shah 
510125ec56b5SJean Noel Cordenner 	inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
510225ec56b5SJean Noel Cordenner 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
510325ec56b5SJean Noel Cordenner 		if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
510425ec56b5SJean Noel Cordenner 			inode->i_version |=
510525ec56b5SJean Noel Cordenner 			(__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
510625ec56b5SJean Noel Cordenner 	}
510725ec56b5SJean Noel Cordenner 
5108c4b5a614STheodore Ts'o 	ret = 0;
5109485c26ecSTheodore Ts'o 	if (ei->i_file_acl &&
51101032988cSTheodore Ts'o 	    !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
511124676da4STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
511224676da4STheodore Ts'o 				 ei->i_file_acl);
5113485c26ecSTheodore Ts'o 		ret = -EIO;
5114485c26ecSTheodore Ts'o 		goto bad_inode;
511507a03824STheodore Ts'o 	} else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5116c4b5a614STheodore Ts'o 		if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5117c4b5a614STheodore Ts'o 		    (S_ISLNK(inode->i_mode) &&
5118c4b5a614STheodore Ts'o 		     !ext4_inode_is_fast_symlink(inode)))
51197a262f7cSAneesh Kumar K.V 			/* Validate extent which is part of inode */
51207a262f7cSAneesh Kumar K.V 			ret = ext4_ext_check_inode(inode);
5121fe2c8191SThiemo Nagel 	} else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5122fe2c8191SThiemo Nagel 		   (S_ISLNK(inode->i_mode) &&
5123fe2c8191SThiemo Nagel 		    !ext4_inode_is_fast_symlink(inode))) {
5124fe2c8191SThiemo Nagel 		/* Validate block references which are part of inode */
5125fe2c8191SThiemo Nagel 		ret = ext4_check_inode_blockref(inode);
5126fe2c8191SThiemo Nagel 	}
5127567f3e9aSTheodore Ts'o 	if (ret)
51287a262f7cSAneesh Kumar K.V 		goto bad_inode;
51297a262f7cSAneesh Kumar K.V 
5130ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode)) {
5131617ba13bSMingming Cao 		inode->i_op = &ext4_file_inode_operations;
5132617ba13bSMingming Cao 		inode->i_fop = &ext4_file_operations;
5133617ba13bSMingming Cao 		ext4_set_aops(inode);
5134ac27a0ecSDave Kleikamp 	} else if (S_ISDIR(inode->i_mode)) {
5135617ba13bSMingming Cao 		inode->i_op = &ext4_dir_inode_operations;
5136617ba13bSMingming Cao 		inode->i_fop = &ext4_dir_operations;
5137ac27a0ecSDave Kleikamp 	} else if (S_ISLNK(inode->i_mode)) {
5138e83c1397SDuane Griffin 		if (ext4_inode_is_fast_symlink(inode)) {
5139617ba13bSMingming Cao 			inode->i_op = &ext4_fast_symlink_inode_operations;
5140e83c1397SDuane Griffin 			nd_terminate_link(ei->i_data, inode->i_size,
5141e83c1397SDuane Griffin 				sizeof(ei->i_data) - 1);
5142e83c1397SDuane Griffin 		} else {
5143617ba13bSMingming Cao 			inode->i_op = &ext4_symlink_inode_operations;
5144617ba13bSMingming Cao 			ext4_set_aops(inode);
5145ac27a0ecSDave Kleikamp 		}
5146563bdd61STheodore Ts'o 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5147563bdd61STheodore Ts'o 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5148617ba13bSMingming Cao 		inode->i_op = &ext4_special_inode_operations;
5149ac27a0ecSDave Kleikamp 		if (raw_inode->i_block[0])
5150ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5151ac27a0ecSDave Kleikamp 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5152ac27a0ecSDave Kleikamp 		else
5153ac27a0ecSDave Kleikamp 			init_special_inode(inode, inode->i_mode,
5154ac27a0ecSDave Kleikamp 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5155563bdd61STheodore Ts'o 	} else {
5156563bdd61STheodore Ts'o 		ret = -EIO;
515724676da4STheodore Ts'o 		EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
5158563bdd61STheodore Ts'o 		goto bad_inode;
5159ac27a0ecSDave Kleikamp 	}
5160ac27a0ecSDave Kleikamp 	brelse(iloc.bh);
5161617ba13bSMingming Cao 	ext4_set_inode_flags(inode);
51621d1fe1eeSDavid Howells 	unlock_new_inode(inode);
51631d1fe1eeSDavid Howells 	return inode;
5164ac27a0ecSDave Kleikamp 
5165ac27a0ecSDave Kleikamp bad_inode:
5166567f3e9aSTheodore Ts'o 	brelse(iloc.bh);
51671d1fe1eeSDavid Howells 	iget_failed(inode);
51681d1fe1eeSDavid Howells 	return ERR_PTR(ret);
5169ac27a0ecSDave Kleikamp }
5170ac27a0ecSDave Kleikamp 
51710fc1b451SAneesh Kumar K.V static int ext4_inode_blocks_set(handle_t *handle,
51720fc1b451SAneesh Kumar K.V 				struct ext4_inode *raw_inode,
51730fc1b451SAneesh Kumar K.V 				struct ext4_inode_info *ei)
51740fc1b451SAneesh Kumar K.V {
51750fc1b451SAneesh Kumar K.V 	struct inode *inode = &(ei->vfs_inode);
51760fc1b451SAneesh Kumar K.V 	u64 i_blocks = inode->i_blocks;
51770fc1b451SAneesh Kumar K.V 	struct super_block *sb = inode->i_sb;
51780fc1b451SAneesh Kumar K.V 
51790fc1b451SAneesh Kumar K.V 	if (i_blocks <= ~0U) {
51800fc1b451SAneesh Kumar K.V 		/*
51810fc1b451SAneesh Kumar K.V 		 * i_blocks can be represnted in a 32 bit variable
51820fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
51830fc1b451SAneesh Kumar K.V 		 */
51848180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
51850fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = 0;
518684a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5187f287a1a5STheodore Ts'o 		return 0;
5188f287a1a5STheodore Ts'o 	}
5189f287a1a5STheodore Ts'o 	if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
5190f287a1a5STheodore Ts'o 		return -EFBIG;
5191f287a1a5STheodore Ts'o 
5192f287a1a5STheodore Ts'o 	if (i_blocks <= 0xffffffffffffULL) {
51930fc1b451SAneesh Kumar K.V 		/*
51940fc1b451SAneesh Kumar K.V 		 * i_blocks can be represented in a 48 bit variable
51950fc1b451SAneesh Kumar K.V 		 * as multiple of 512 bytes
51960fc1b451SAneesh Kumar K.V 		 */
51978180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
51980fc1b451SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
519984a8dce2SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
52000fc1b451SAneesh Kumar K.V 	} else {
520184a8dce2SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
52028180a562SAneesh Kumar K.V 		/* i_block is stored in file system block size */
52038180a562SAneesh Kumar K.V 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
52048180a562SAneesh Kumar K.V 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
52058180a562SAneesh Kumar K.V 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
52060fc1b451SAneesh Kumar K.V 	}
5207f287a1a5STheodore Ts'o 	return 0;
52080fc1b451SAneesh Kumar K.V }
52090fc1b451SAneesh Kumar K.V 
5210ac27a0ecSDave Kleikamp /*
5211ac27a0ecSDave Kleikamp  * Post the struct inode info into an on-disk inode location in the
5212ac27a0ecSDave Kleikamp  * buffer-cache.  This gobbles the caller's reference to the
5213ac27a0ecSDave Kleikamp  * buffer_head in the inode location struct.
5214ac27a0ecSDave Kleikamp  *
5215ac27a0ecSDave Kleikamp  * The caller must have write access to iloc->bh.
5216ac27a0ecSDave Kleikamp  */
5217617ba13bSMingming Cao static int ext4_do_update_inode(handle_t *handle,
5218ac27a0ecSDave Kleikamp 				struct inode *inode,
5219830156c7SFrank Mayhar 				struct ext4_iloc *iloc)
5220ac27a0ecSDave Kleikamp {
5221617ba13bSMingming Cao 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5222617ba13bSMingming Cao 	struct ext4_inode_info *ei = EXT4_I(inode);
5223ac27a0ecSDave Kleikamp 	struct buffer_head *bh = iloc->bh;
5224ac27a0ecSDave Kleikamp 	int err = 0, rc, block;
5225ac27a0ecSDave Kleikamp 
5226ac27a0ecSDave Kleikamp 	/* For fields not not tracking in the in-memory inode,
5227ac27a0ecSDave Kleikamp 	 * initialise them to zero for new inodes. */
522819f5fb7aSTheodore Ts'o 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5229617ba13bSMingming Cao 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5230ac27a0ecSDave Kleikamp 
5231ff9ddf7eSJan Kara 	ext4_get_inode_flags(ei);
5232ac27a0ecSDave Kleikamp 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5233ac27a0ecSDave Kleikamp 	if (!(test_opt(inode->i_sb, NO_UID32))) {
5234ac27a0ecSDave Kleikamp 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
5235ac27a0ecSDave Kleikamp 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
5236ac27a0ecSDave Kleikamp /*
5237ac27a0ecSDave Kleikamp  * Fix up interoperability with old kernels. Otherwise, old inodes get
5238ac27a0ecSDave Kleikamp  * re-used with the upper 16 bits of the uid/gid intact
5239ac27a0ecSDave Kleikamp  */
5240ac27a0ecSDave Kleikamp 		if (!ei->i_dtime) {
5241ac27a0ecSDave Kleikamp 			raw_inode->i_uid_high =
5242ac27a0ecSDave Kleikamp 				cpu_to_le16(high_16_bits(inode->i_uid));
5243ac27a0ecSDave Kleikamp 			raw_inode->i_gid_high =
5244ac27a0ecSDave Kleikamp 				cpu_to_le16(high_16_bits(inode->i_gid));
5245ac27a0ecSDave Kleikamp 		} else {
5246ac27a0ecSDave Kleikamp 			raw_inode->i_uid_high = 0;
5247ac27a0ecSDave Kleikamp 			raw_inode->i_gid_high = 0;
5248ac27a0ecSDave Kleikamp 		}
5249ac27a0ecSDave Kleikamp 	} else {
5250ac27a0ecSDave Kleikamp 		raw_inode->i_uid_low =
5251ac27a0ecSDave Kleikamp 			cpu_to_le16(fs_high2lowuid(inode->i_uid));
5252ac27a0ecSDave Kleikamp 		raw_inode->i_gid_low =
5253ac27a0ecSDave Kleikamp 			cpu_to_le16(fs_high2lowgid(inode->i_gid));
5254ac27a0ecSDave Kleikamp 		raw_inode->i_uid_high = 0;
5255ac27a0ecSDave Kleikamp 		raw_inode->i_gid_high = 0;
5256ac27a0ecSDave Kleikamp 	}
5257ac27a0ecSDave Kleikamp 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5258ef7f3835SKalpak Shah 
5259ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5260ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5261ef7f3835SKalpak Shah 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5262ef7f3835SKalpak Shah 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5263ef7f3835SKalpak Shah 
52640fc1b451SAneesh Kumar K.V 	if (ext4_inode_blocks_set(handle, raw_inode, ei))
52650fc1b451SAneesh Kumar K.V 		goto out_brelse;
5266ac27a0ecSDave Kleikamp 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
52671b9c12f4STheodore Ts'o 	raw_inode->i_flags = cpu_to_le32(ei->i_flags);
52689b8f1f01SMingming Cao 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
52699b8f1f01SMingming Cao 	    cpu_to_le32(EXT4_OS_HURD))
5270a1ddeb7eSBadari Pulavarty 		raw_inode->i_file_acl_high =
5271a1ddeb7eSBadari Pulavarty 			cpu_to_le16(ei->i_file_acl >> 32);
52727973c0c1SAneesh Kumar K.V 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5273a48380f7SAneesh Kumar K.V 	ext4_isize_set(raw_inode, ei->i_disksize);
5274ac27a0ecSDave Kleikamp 	if (ei->i_disksize > 0x7fffffffULL) {
5275ac27a0ecSDave Kleikamp 		struct super_block *sb = inode->i_sb;
5276617ba13bSMingming Cao 		if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
5277617ba13bSMingming Cao 				EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
5278617ba13bSMingming Cao 				EXT4_SB(sb)->s_es->s_rev_level ==
5279617ba13bSMingming Cao 				cpu_to_le32(EXT4_GOOD_OLD_REV)) {
5280ac27a0ecSDave Kleikamp 			/* If this is the first large file
5281ac27a0ecSDave Kleikamp 			 * created, add a flag to the superblock.
5282ac27a0ecSDave Kleikamp 			 */
5283617ba13bSMingming Cao 			err = ext4_journal_get_write_access(handle,
5284617ba13bSMingming Cao 					EXT4_SB(sb)->s_sbh);
5285ac27a0ecSDave Kleikamp 			if (err)
5286ac27a0ecSDave Kleikamp 				goto out_brelse;
5287617ba13bSMingming Cao 			ext4_update_dynamic_rev(sb);
5288617ba13bSMingming Cao 			EXT4_SET_RO_COMPAT_FEATURE(sb,
5289617ba13bSMingming Cao 					EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
5290ac27a0ecSDave Kleikamp 			sb->s_dirt = 1;
52910390131bSFrank Mayhar 			ext4_handle_sync(handle);
529273b50c1cSCurt Wohlgemuth 			err = ext4_handle_dirty_metadata(handle, NULL,
5293617ba13bSMingming Cao 					EXT4_SB(sb)->s_sbh);
5294ac27a0ecSDave Kleikamp 		}
5295ac27a0ecSDave Kleikamp 	}
5296ac27a0ecSDave Kleikamp 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5297ac27a0ecSDave Kleikamp 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5298ac27a0ecSDave Kleikamp 		if (old_valid_dev(inode->i_rdev)) {
5299ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] =
5300ac27a0ecSDave Kleikamp 				cpu_to_le32(old_encode_dev(inode->i_rdev));
5301ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] = 0;
5302ac27a0ecSDave Kleikamp 		} else {
5303ac27a0ecSDave Kleikamp 			raw_inode->i_block[0] = 0;
5304ac27a0ecSDave Kleikamp 			raw_inode->i_block[1] =
5305ac27a0ecSDave Kleikamp 				cpu_to_le32(new_encode_dev(inode->i_rdev));
5306ac27a0ecSDave Kleikamp 			raw_inode->i_block[2] = 0;
5307ac27a0ecSDave Kleikamp 		}
5308de9a55b8STheodore Ts'o 	} else
5309de9a55b8STheodore Ts'o 		for (block = 0; block < EXT4_N_BLOCKS; block++)
5310ac27a0ecSDave Kleikamp 			raw_inode->i_block[block] = ei->i_data[block];
5311ac27a0ecSDave Kleikamp 
531225ec56b5SJean Noel Cordenner 	raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
531325ec56b5SJean Noel Cordenner 	if (ei->i_extra_isize) {
531425ec56b5SJean Noel Cordenner 		if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
531525ec56b5SJean Noel Cordenner 			raw_inode->i_version_hi =
531625ec56b5SJean Noel Cordenner 			cpu_to_le32(inode->i_version >> 32);
5317ac27a0ecSDave Kleikamp 		raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
531825ec56b5SJean Noel Cordenner 	}
531925ec56b5SJean Noel Cordenner 
53200390131bSFrank Mayhar 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
532173b50c1cSCurt Wohlgemuth 	rc = ext4_handle_dirty_metadata(handle, NULL, bh);
5322ac27a0ecSDave Kleikamp 	if (!err)
5323ac27a0ecSDave Kleikamp 		err = rc;
532419f5fb7aSTheodore Ts'o 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5325ac27a0ecSDave Kleikamp 
5326b436b9beSJan Kara 	ext4_update_inode_fsync_trans(handle, inode, 0);
5327ac27a0ecSDave Kleikamp out_brelse:
5328ac27a0ecSDave Kleikamp 	brelse(bh);
5329617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5330ac27a0ecSDave Kleikamp 	return err;
5331ac27a0ecSDave Kleikamp }
5332ac27a0ecSDave Kleikamp 
5333ac27a0ecSDave Kleikamp /*
5334617ba13bSMingming Cao  * ext4_write_inode()
5335ac27a0ecSDave Kleikamp  *
5336ac27a0ecSDave Kleikamp  * We are called from a few places:
5337ac27a0ecSDave Kleikamp  *
5338ac27a0ecSDave Kleikamp  * - Within generic_file_write() for O_SYNC files.
5339ac27a0ecSDave Kleikamp  *   Here, there will be no transaction running. We wait for any running
5340ac27a0ecSDave Kleikamp  *   trasnaction to commit.
5341ac27a0ecSDave Kleikamp  *
5342ac27a0ecSDave Kleikamp  * - Within sys_sync(), kupdate and such.
5343ac27a0ecSDave Kleikamp  *   We wait on commit, if tol to.
5344ac27a0ecSDave Kleikamp  *
5345ac27a0ecSDave Kleikamp  * - Within prune_icache() (PF_MEMALLOC == true)
5346ac27a0ecSDave Kleikamp  *   Here we simply return.  We can't afford to block kswapd on the
5347ac27a0ecSDave Kleikamp  *   journal commit.
5348ac27a0ecSDave Kleikamp  *
5349ac27a0ecSDave Kleikamp  * In all cases it is actually safe for us to return without doing anything,
5350ac27a0ecSDave Kleikamp  * because the inode has been copied into a raw inode buffer in
5351617ba13bSMingming Cao  * ext4_mark_inode_dirty().  This is a correctness thing for O_SYNC and for
5352ac27a0ecSDave Kleikamp  * knfsd.
5353ac27a0ecSDave Kleikamp  *
5354ac27a0ecSDave Kleikamp  * Note that we are absolutely dependent upon all inode dirtiers doing the
5355ac27a0ecSDave Kleikamp  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5356ac27a0ecSDave Kleikamp  * which we are interested.
5357ac27a0ecSDave Kleikamp  *
5358ac27a0ecSDave Kleikamp  * It would be a bug for them to not do this.  The code:
5359ac27a0ecSDave Kleikamp  *
5360ac27a0ecSDave Kleikamp  *	mark_inode_dirty(inode)
5361ac27a0ecSDave Kleikamp  *	stuff();
5362ac27a0ecSDave Kleikamp  *	inode->i_size = expr;
5363ac27a0ecSDave Kleikamp  *
5364ac27a0ecSDave Kleikamp  * is in error because a kswapd-driven write_inode() could occur while
5365ac27a0ecSDave Kleikamp  * `stuff()' is running, and the new i_size will be lost.  Plus the inode
5366ac27a0ecSDave Kleikamp  * will no longer be on the superblock's dirty inode list.
5367ac27a0ecSDave Kleikamp  */
5368a9185b41SChristoph Hellwig int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5369ac27a0ecSDave Kleikamp {
537091ac6f43SFrank Mayhar 	int err;
537191ac6f43SFrank Mayhar 
5372ac27a0ecSDave Kleikamp 	if (current->flags & PF_MEMALLOC)
5373ac27a0ecSDave Kleikamp 		return 0;
5374ac27a0ecSDave Kleikamp 
537591ac6f43SFrank Mayhar 	if (EXT4_SB(inode->i_sb)->s_journal) {
5376617ba13bSMingming Cao 		if (ext4_journal_current_handle()) {
5377b38bd33aSMingming Cao 			jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5378ac27a0ecSDave Kleikamp 			dump_stack();
5379ac27a0ecSDave Kleikamp 			return -EIO;
5380ac27a0ecSDave Kleikamp 		}
5381ac27a0ecSDave Kleikamp 
5382a9185b41SChristoph Hellwig 		if (wbc->sync_mode != WB_SYNC_ALL)
5383ac27a0ecSDave Kleikamp 			return 0;
5384ac27a0ecSDave Kleikamp 
538591ac6f43SFrank Mayhar 		err = ext4_force_commit(inode->i_sb);
538691ac6f43SFrank Mayhar 	} else {
538791ac6f43SFrank Mayhar 		struct ext4_iloc iloc;
538891ac6f43SFrank Mayhar 
53898b472d73SCurt Wohlgemuth 		err = __ext4_get_inode_loc(inode, &iloc, 0);
539091ac6f43SFrank Mayhar 		if (err)
539191ac6f43SFrank Mayhar 			return err;
5392a9185b41SChristoph Hellwig 		if (wbc->sync_mode == WB_SYNC_ALL)
5393830156c7SFrank Mayhar 			sync_dirty_buffer(iloc.bh);
5394830156c7SFrank Mayhar 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5395*c398eda0STheodore Ts'o 			EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
5396*c398eda0STheodore Ts'o 					 "IO error syncing inode");
5397830156c7SFrank Mayhar 			err = -EIO;
5398830156c7SFrank Mayhar 		}
5399fd2dd9fbSCurt Wohlgemuth 		brelse(iloc.bh);
540091ac6f43SFrank Mayhar 	}
540191ac6f43SFrank Mayhar 	return err;
5402ac27a0ecSDave Kleikamp }
5403ac27a0ecSDave Kleikamp 
5404ac27a0ecSDave Kleikamp /*
5405617ba13bSMingming Cao  * ext4_setattr()
5406ac27a0ecSDave Kleikamp  *
5407ac27a0ecSDave Kleikamp  * Called from notify_change.
5408ac27a0ecSDave Kleikamp  *
5409ac27a0ecSDave Kleikamp  * We want to trap VFS attempts to truncate the file as soon as
5410ac27a0ecSDave Kleikamp  * possible.  In particular, we want to make sure that when the VFS
5411ac27a0ecSDave Kleikamp  * shrinks i_size, we put the inode on the orphan list and modify
5412ac27a0ecSDave Kleikamp  * i_disksize immediately, so that during the subsequent flushing of
5413ac27a0ecSDave Kleikamp  * dirty pages and freeing of disk blocks, we can guarantee that any
5414ac27a0ecSDave Kleikamp  * commit will leave the blocks being flushed in an unused state on
5415ac27a0ecSDave Kleikamp  * disk.  (On recovery, the inode will get truncated and the blocks will
5416ac27a0ecSDave Kleikamp  * be freed, so we have a strong guarantee that no future commit will
5417ac27a0ecSDave Kleikamp  * leave these blocks visible to the user.)
5418ac27a0ecSDave Kleikamp  *
5419678aaf48SJan Kara  * Another thing we have to assure is that if we are in ordered mode
5420678aaf48SJan Kara  * and inode is still attached to the committing transaction, we must
5421678aaf48SJan Kara  * we start writeout of all the dirty pages which are being truncated.
5422678aaf48SJan Kara  * This way we are sure that all the data written in the previous
5423678aaf48SJan Kara  * transaction are already on disk (truncate waits for pages under
5424678aaf48SJan Kara  * writeback).
5425678aaf48SJan Kara  *
5426678aaf48SJan Kara  * Called with inode->i_mutex down.
5427ac27a0ecSDave Kleikamp  */
5428617ba13bSMingming Cao int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5429ac27a0ecSDave Kleikamp {
5430ac27a0ecSDave Kleikamp 	struct inode *inode = dentry->d_inode;
5431ac27a0ecSDave Kleikamp 	int error, rc = 0;
5432ac27a0ecSDave Kleikamp 	const unsigned int ia_valid = attr->ia_valid;
5433ac27a0ecSDave Kleikamp 
5434ac27a0ecSDave Kleikamp 	error = inode_change_ok(inode, attr);
5435ac27a0ecSDave Kleikamp 	if (error)
5436ac27a0ecSDave Kleikamp 		return error;
5437ac27a0ecSDave Kleikamp 
543812755627SDmitry Monakhov 	if (is_quota_modification(inode, attr))
5439871a2931SChristoph Hellwig 		dquot_initialize(inode);
5440ac27a0ecSDave Kleikamp 	if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
5441ac27a0ecSDave Kleikamp 		(ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
5442ac27a0ecSDave Kleikamp 		handle_t *handle;
5443ac27a0ecSDave Kleikamp 
5444ac27a0ecSDave Kleikamp 		/* (user+group)*(old+new) structure, inode write (sb,
5445ac27a0ecSDave Kleikamp 		 * inode block, ? - but truncate inode update has it) */
54465aca07ebSDmitry Monakhov 		handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
5447194074acSDmitry Monakhov 					EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
5448ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
5449ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
5450ac27a0ecSDave Kleikamp 			goto err_out;
5451ac27a0ecSDave Kleikamp 		}
5452b43fa828SChristoph Hellwig 		error = dquot_transfer(inode, attr);
5453ac27a0ecSDave Kleikamp 		if (error) {
5454617ba13bSMingming Cao 			ext4_journal_stop(handle);
5455ac27a0ecSDave Kleikamp 			return error;
5456ac27a0ecSDave Kleikamp 		}
5457ac27a0ecSDave Kleikamp 		/* Update corresponding info in inode so that everything is in
5458ac27a0ecSDave Kleikamp 		 * one transaction */
5459ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_UID)
5460ac27a0ecSDave Kleikamp 			inode->i_uid = attr->ia_uid;
5461ac27a0ecSDave Kleikamp 		if (attr->ia_valid & ATTR_GID)
5462ac27a0ecSDave Kleikamp 			inode->i_gid = attr->ia_gid;
5463617ba13bSMingming Cao 		error = ext4_mark_inode_dirty(handle, inode);
5464617ba13bSMingming Cao 		ext4_journal_stop(handle);
5465ac27a0ecSDave Kleikamp 	}
5466ac27a0ecSDave Kleikamp 
5467e2b46574SEric Sandeen 	if (attr->ia_valid & ATTR_SIZE) {
546812e9b892SDmitry Monakhov 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5469e2b46574SEric Sandeen 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5470e2b46574SEric Sandeen 
5471e2b46574SEric Sandeen 			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5472e2b46574SEric Sandeen 				error = -EFBIG;
5473e2b46574SEric Sandeen 				goto err_out;
5474e2b46574SEric Sandeen 			}
5475e2b46574SEric Sandeen 		}
5476e2b46574SEric Sandeen 	}
5477e2b46574SEric Sandeen 
5478ac27a0ecSDave Kleikamp 	if (S_ISREG(inode->i_mode) &&
5479c8d46e41SJiaying Zhang 	    attr->ia_valid & ATTR_SIZE &&
5480c8d46e41SJiaying Zhang 	    (attr->ia_size < inode->i_size ||
548112e9b892SDmitry Monakhov 	     (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS)))) {
5482ac27a0ecSDave Kleikamp 		handle_t *handle;
5483ac27a0ecSDave Kleikamp 
5484617ba13bSMingming Cao 		handle = ext4_journal_start(inode, 3);
5485ac27a0ecSDave Kleikamp 		if (IS_ERR(handle)) {
5486ac27a0ecSDave Kleikamp 			error = PTR_ERR(handle);
5487ac27a0ecSDave Kleikamp 			goto err_out;
5488ac27a0ecSDave Kleikamp 		}
5489ac27a0ecSDave Kleikamp 
5490617ba13bSMingming Cao 		error = ext4_orphan_add(handle, inode);
5491617ba13bSMingming Cao 		EXT4_I(inode)->i_disksize = attr->ia_size;
5492617ba13bSMingming Cao 		rc = ext4_mark_inode_dirty(handle, inode);
5493ac27a0ecSDave Kleikamp 		if (!error)
5494ac27a0ecSDave Kleikamp 			error = rc;
5495617ba13bSMingming Cao 		ext4_journal_stop(handle);
5496678aaf48SJan Kara 
5497678aaf48SJan Kara 		if (ext4_should_order_data(inode)) {
5498678aaf48SJan Kara 			error = ext4_begin_ordered_truncate(inode,
5499678aaf48SJan Kara 							    attr->ia_size);
5500678aaf48SJan Kara 			if (error) {
5501678aaf48SJan Kara 				/* Do as much error cleanup as possible */
5502678aaf48SJan Kara 				handle = ext4_journal_start(inode, 3);
5503678aaf48SJan Kara 				if (IS_ERR(handle)) {
5504678aaf48SJan Kara 					ext4_orphan_del(NULL, inode);
5505678aaf48SJan Kara 					goto err_out;
5506678aaf48SJan Kara 				}
5507678aaf48SJan Kara 				ext4_orphan_del(handle, inode);
5508678aaf48SJan Kara 				ext4_journal_stop(handle);
5509678aaf48SJan Kara 				goto err_out;
5510678aaf48SJan Kara 			}
5511678aaf48SJan Kara 		}
5512c8d46e41SJiaying Zhang 		/* ext4_truncate will clear the flag */
551312e9b892SDmitry Monakhov 		if ((ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS)))
5514c8d46e41SJiaying Zhang 			ext4_truncate(inode);
5515ac27a0ecSDave Kleikamp 	}
5516ac27a0ecSDave Kleikamp 
5517ac27a0ecSDave Kleikamp 	rc = inode_setattr(inode, attr);
5518ac27a0ecSDave Kleikamp 
5519617ba13bSMingming Cao 	/* If inode_setattr's call to ext4_truncate failed to get a
5520ac27a0ecSDave Kleikamp 	 * transaction handle at all, we need to clean up the in-core
5521ac27a0ecSDave Kleikamp 	 * orphan list manually. */
5522ac27a0ecSDave Kleikamp 	if (inode->i_nlink)
5523617ba13bSMingming Cao 		ext4_orphan_del(NULL, inode);
5524ac27a0ecSDave Kleikamp 
5525ac27a0ecSDave Kleikamp 	if (!rc && (ia_valid & ATTR_MODE))
5526617ba13bSMingming Cao 		rc = ext4_acl_chmod(inode);
5527ac27a0ecSDave Kleikamp 
5528ac27a0ecSDave Kleikamp err_out:
5529617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, error);
5530ac27a0ecSDave Kleikamp 	if (!error)
5531ac27a0ecSDave Kleikamp 		error = rc;
5532ac27a0ecSDave Kleikamp 	return error;
5533ac27a0ecSDave Kleikamp }
5534ac27a0ecSDave Kleikamp 
55353e3398a0SMingming Cao int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
55363e3398a0SMingming Cao 		 struct kstat *stat)
55373e3398a0SMingming Cao {
55383e3398a0SMingming Cao 	struct inode *inode;
55393e3398a0SMingming Cao 	unsigned long delalloc_blocks;
55403e3398a0SMingming Cao 
55413e3398a0SMingming Cao 	inode = dentry->d_inode;
55423e3398a0SMingming Cao 	generic_fillattr(inode, stat);
55433e3398a0SMingming Cao 
55443e3398a0SMingming Cao 	/*
55453e3398a0SMingming Cao 	 * We can't update i_blocks if the block allocation is delayed
55463e3398a0SMingming Cao 	 * otherwise in the case of system crash before the real block
55473e3398a0SMingming Cao 	 * allocation is done, we will have i_blocks inconsistent with
55483e3398a0SMingming Cao 	 * on-disk file blocks.
55493e3398a0SMingming Cao 	 * We always keep i_blocks updated together with real
55503e3398a0SMingming Cao 	 * allocation. But to not confuse with user, stat
55513e3398a0SMingming Cao 	 * will return the blocks that include the delayed allocation
55523e3398a0SMingming Cao 	 * blocks for this file.
55533e3398a0SMingming Cao 	 */
55543e3398a0SMingming Cao 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
55553e3398a0SMingming Cao 	delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
55563e3398a0SMingming Cao 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
55573e3398a0SMingming Cao 
55583e3398a0SMingming Cao 	stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
55593e3398a0SMingming Cao 	return 0;
55603e3398a0SMingming Cao }
5561ac27a0ecSDave Kleikamp 
5562a02908f1SMingming Cao static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
5563a02908f1SMingming Cao 				      int chunk)
5564ac27a0ecSDave Kleikamp {
5565a02908f1SMingming Cao 	int indirects;
5566ac27a0ecSDave Kleikamp 
5567a02908f1SMingming Cao 	/* if nrblocks are contiguous */
5568a02908f1SMingming Cao 	if (chunk) {
5569a02908f1SMingming Cao 		/*
5570a02908f1SMingming Cao 		 * With N contiguous data blocks, it need at most
5571a02908f1SMingming Cao 		 * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) indirect blocks
5572a02908f1SMingming Cao 		 * 2 dindirect blocks
5573a02908f1SMingming Cao 		 * 1 tindirect block
5574a02908f1SMingming Cao 		 */
5575a02908f1SMingming Cao 		indirects = nrblocks / EXT4_ADDR_PER_BLOCK(inode->i_sb);
5576a02908f1SMingming Cao 		return indirects + 3;
5577a02908f1SMingming Cao 	}
5578a02908f1SMingming Cao 	/*
5579a02908f1SMingming Cao 	 * if nrblocks are not contiguous, worse case, each block touch
5580a02908f1SMingming Cao 	 * a indirect block, and each indirect block touch a double indirect
5581a02908f1SMingming Cao 	 * block, plus a triple indirect block
5582a02908f1SMingming Cao 	 */
5583a02908f1SMingming Cao 	indirects = nrblocks * 2 + 1;
5584a02908f1SMingming Cao 	return indirects;
5585a02908f1SMingming Cao }
5586a86c6181SAlex Tomas 
5587a02908f1SMingming Cao static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5588a02908f1SMingming Cao {
558912e9b892SDmitry Monakhov 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5590ac51d837STheodore Ts'o 		return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
5591ac51d837STheodore Ts'o 	return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
5592a02908f1SMingming Cao }
5593ac51d837STheodore Ts'o 
5594a02908f1SMingming Cao /*
5595a02908f1SMingming Cao  * Account for index blocks, block groups bitmaps and block group
5596a02908f1SMingming Cao  * descriptor blocks if modify datablocks and index blocks
5597a02908f1SMingming Cao  * worse case, the indexs blocks spread over different block groups
5598a02908f1SMingming Cao  *
5599a02908f1SMingming Cao  * If datablocks are discontiguous, they are possible to spread over
5600af901ca1SAndré Goddard Rosa  * different block groups too. If they are contiuguous, with flexbg,
5601a02908f1SMingming Cao  * they could still across block group boundary.
5602a02908f1SMingming Cao  *
5603a02908f1SMingming Cao  * Also account for superblock, inode, quota and xattr blocks
5604a02908f1SMingming Cao  */
5605a02908f1SMingming Cao int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5606a02908f1SMingming Cao {
56078df9675fSTheodore Ts'o 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
56088df9675fSTheodore Ts'o 	int gdpblocks;
5609a02908f1SMingming Cao 	int idxblocks;
5610a02908f1SMingming Cao 	int ret = 0;
5611a02908f1SMingming Cao 
5612a02908f1SMingming Cao 	/*
5613a02908f1SMingming Cao 	 * How many index blocks need to touch to modify nrblocks?
5614a02908f1SMingming Cao 	 * The "Chunk" flag indicating whether the nrblocks is
5615a02908f1SMingming Cao 	 * physically contiguous on disk
5616a02908f1SMingming Cao 	 *
5617a02908f1SMingming Cao 	 * For Direct IO and fallocate, they calls get_block to allocate
5618a02908f1SMingming Cao 	 * one single extent at a time, so they could set the "Chunk" flag
5619a02908f1SMingming Cao 	 */
5620a02908f1SMingming Cao 	idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
5621a02908f1SMingming Cao 
5622a02908f1SMingming Cao 	ret = idxblocks;
5623a02908f1SMingming Cao 
5624a02908f1SMingming Cao 	/*
5625a02908f1SMingming Cao 	 * Now let's see how many group bitmaps and group descriptors need
5626a02908f1SMingming Cao 	 * to account
5627a02908f1SMingming Cao 	 */
5628a02908f1SMingming Cao 	groups = idxblocks;
5629a02908f1SMingming Cao 	if (chunk)
5630a02908f1SMingming Cao 		groups += 1;
5631ac27a0ecSDave Kleikamp 	else
5632a02908f1SMingming Cao 		groups += nrblocks;
5633ac27a0ecSDave Kleikamp 
5634a02908f1SMingming Cao 	gdpblocks = groups;
56358df9675fSTheodore Ts'o 	if (groups > ngroups)
56368df9675fSTheodore Ts'o 		groups = ngroups;
5637a02908f1SMingming Cao 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5638a02908f1SMingming Cao 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5639a02908f1SMingming Cao 
5640a02908f1SMingming Cao 	/* bitmaps and block group descriptor blocks */
5641a02908f1SMingming Cao 	ret += groups + gdpblocks;
5642a02908f1SMingming Cao 
5643a02908f1SMingming Cao 	/* Blocks for super block, inode, quota and xattr blocks */
5644a02908f1SMingming Cao 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5645ac27a0ecSDave Kleikamp 
5646ac27a0ecSDave Kleikamp 	return ret;
5647ac27a0ecSDave Kleikamp }
5648ac27a0ecSDave Kleikamp 
5649ac27a0ecSDave Kleikamp /*
5650a02908f1SMingming Cao  * Calulate the total number of credits to reserve to fit
5651f3bd1f3fSMingming Cao  * the modification of a single pages into a single transaction,
5652f3bd1f3fSMingming Cao  * which may include multiple chunks of block allocations.
5653a02908f1SMingming Cao  *
5654525f4ed8SMingming Cao  * This could be called via ext4_write_begin()
5655a02908f1SMingming Cao  *
5656525f4ed8SMingming Cao  * We need to consider the worse case, when
5657a02908f1SMingming Cao  * one new block per extent.
5658a02908f1SMingming Cao  */
5659a02908f1SMingming Cao int ext4_writepage_trans_blocks(struct inode *inode)
5660a02908f1SMingming Cao {
5661a02908f1SMingming Cao 	int bpp = ext4_journal_blocks_per_page(inode);
5662a02908f1SMingming Cao 	int ret;
5663a02908f1SMingming Cao 
5664a02908f1SMingming Cao 	ret = ext4_meta_trans_blocks(inode, bpp, 0);
5665a02908f1SMingming Cao 
5666a02908f1SMingming Cao 	/* Account for data blocks for journalled mode */
5667a02908f1SMingming Cao 	if (ext4_should_journal_data(inode))
5668a02908f1SMingming Cao 		ret += bpp;
5669a02908f1SMingming Cao 	return ret;
5670a02908f1SMingming Cao }
5671f3bd1f3fSMingming Cao 
5672f3bd1f3fSMingming Cao /*
5673f3bd1f3fSMingming Cao  * Calculate the journal credits for a chunk of data modification.
5674f3bd1f3fSMingming Cao  *
5675f3bd1f3fSMingming Cao  * This is called from DIO, fallocate or whoever calling
5676af901ca1SAndré Goddard Rosa  * ext4_get_blocks() to map/allocate a chunk of contiguous disk blocks.
5677f3bd1f3fSMingming Cao  *
5678f3bd1f3fSMingming Cao  * journal buffers for data blocks are not included here, as DIO
5679f3bd1f3fSMingming Cao  * and fallocate do no need to journal data buffers.
5680f3bd1f3fSMingming Cao  */
5681f3bd1f3fSMingming Cao int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5682f3bd1f3fSMingming Cao {
5683f3bd1f3fSMingming Cao 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5684f3bd1f3fSMingming Cao }
5685f3bd1f3fSMingming Cao 
5686a02908f1SMingming Cao /*
5687617ba13bSMingming Cao  * The caller must have previously called ext4_reserve_inode_write().
5688ac27a0ecSDave Kleikamp  * Give this, we know that the caller already has write access to iloc->bh.
5689ac27a0ecSDave Kleikamp  */
5690617ba13bSMingming Cao int ext4_mark_iloc_dirty(handle_t *handle,
5691617ba13bSMingming Cao 			 struct inode *inode, struct ext4_iloc *iloc)
5692ac27a0ecSDave Kleikamp {
5693ac27a0ecSDave Kleikamp 	int err = 0;
5694ac27a0ecSDave Kleikamp 
569525ec56b5SJean Noel Cordenner 	if (test_opt(inode->i_sb, I_VERSION))
569625ec56b5SJean Noel Cordenner 		inode_inc_iversion(inode);
569725ec56b5SJean Noel Cordenner 
5698ac27a0ecSDave Kleikamp 	/* the do_update_inode consumes one bh->b_count */
5699ac27a0ecSDave Kleikamp 	get_bh(iloc->bh);
5700ac27a0ecSDave Kleikamp 
5701dab291afSMingming Cao 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5702830156c7SFrank Mayhar 	err = ext4_do_update_inode(handle, inode, iloc);
5703ac27a0ecSDave Kleikamp 	put_bh(iloc->bh);
5704ac27a0ecSDave Kleikamp 	return err;
5705ac27a0ecSDave Kleikamp }
5706ac27a0ecSDave Kleikamp 
5707ac27a0ecSDave Kleikamp /*
5708ac27a0ecSDave Kleikamp  * On success, We end up with an outstanding reference count against
5709ac27a0ecSDave Kleikamp  * iloc->bh.  This _must_ be cleaned up later.
5710ac27a0ecSDave Kleikamp  */
5711ac27a0ecSDave Kleikamp 
5712ac27a0ecSDave Kleikamp int
5713617ba13bSMingming Cao ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5714617ba13bSMingming Cao 			 struct ext4_iloc *iloc)
5715ac27a0ecSDave Kleikamp {
57160390131bSFrank Mayhar 	int err;
57170390131bSFrank Mayhar 
5718617ba13bSMingming Cao 	err = ext4_get_inode_loc(inode, iloc);
5719ac27a0ecSDave Kleikamp 	if (!err) {
5720ac27a0ecSDave Kleikamp 		BUFFER_TRACE(iloc->bh, "get_write_access");
5721617ba13bSMingming Cao 		err = ext4_journal_get_write_access(handle, iloc->bh);
5722ac27a0ecSDave Kleikamp 		if (err) {
5723ac27a0ecSDave Kleikamp 			brelse(iloc->bh);
5724ac27a0ecSDave Kleikamp 			iloc->bh = NULL;
5725ac27a0ecSDave Kleikamp 		}
5726ac27a0ecSDave Kleikamp 	}
5727617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5728ac27a0ecSDave Kleikamp 	return err;
5729ac27a0ecSDave Kleikamp }
5730ac27a0ecSDave Kleikamp 
5731ac27a0ecSDave Kleikamp /*
57326dd4ee7cSKalpak Shah  * Expand an inode by new_extra_isize bytes.
57336dd4ee7cSKalpak Shah  * Returns 0 on success or negative error number on failure.
57346dd4ee7cSKalpak Shah  */
57351d03ec98SAneesh Kumar K.V static int ext4_expand_extra_isize(struct inode *inode,
57361d03ec98SAneesh Kumar K.V 				   unsigned int new_extra_isize,
57371d03ec98SAneesh Kumar K.V 				   struct ext4_iloc iloc,
57381d03ec98SAneesh Kumar K.V 				   handle_t *handle)
57396dd4ee7cSKalpak Shah {
57406dd4ee7cSKalpak Shah 	struct ext4_inode *raw_inode;
57416dd4ee7cSKalpak Shah 	struct ext4_xattr_ibody_header *header;
57426dd4ee7cSKalpak Shah 
57436dd4ee7cSKalpak Shah 	if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
57446dd4ee7cSKalpak Shah 		return 0;
57456dd4ee7cSKalpak Shah 
57466dd4ee7cSKalpak Shah 	raw_inode = ext4_raw_inode(&iloc);
57476dd4ee7cSKalpak Shah 
57486dd4ee7cSKalpak Shah 	header = IHDR(inode, raw_inode);
57496dd4ee7cSKalpak Shah 
57506dd4ee7cSKalpak Shah 	/* No extended attributes present */
575119f5fb7aSTheodore Ts'o 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
57526dd4ee7cSKalpak Shah 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
57536dd4ee7cSKalpak Shah 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
57546dd4ee7cSKalpak Shah 			new_extra_isize);
57556dd4ee7cSKalpak Shah 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
57566dd4ee7cSKalpak Shah 		return 0;
57576dd4ee7cSKalpak Shah 	}
57586dd4ee7cSKalpak Shah 
57596dd4ee7cSKalpak Shah 	/* try to expand with EAs present */
57606dd4ee7cSKalpak Shah 	return ext4_expand_extra_isize_ea(inode, new_extra_isize,
57616dd4ee7cSKalpak Shah 					  raw_inode, handle);
57626dd4ee7cSKalpak Shah }
57636dd4ee7cSKalpak Shah 
57646dd4ee7cSKalpak Shah /*
5765ac27a0ecSDave Kleikamp  * What we do here is to mark the in-core inode as clean with respect to inode
5766ac27a0ecSDave Kleikamp  * dirtiness (it may still be data-dirty).
5767ac27a0ecSDave Kleikamp  * This means that the in-core inode may be reaped by prune_icache
5768ac27a0ecSDave Kleikamp  * without having to perform any I/O.  This is a very good thing,
5769ac27a0ecSDave Kleikamp  * because *any* task may call prune_icache - even ones which
5770ac27a0ecSDave Kleikamp  * have a transaction open against a different journal.
5771ac27a0ecSDave Kleikamp  *
5772ac27a0ecSDave Kleikamp  * Is this cheating?  Not really.  Sure, we haven't written the
5773ac27a0ecSDave Kleikamp  * inode out, but prune_icache isn't a user-visible syncing function.
5774ac27a0ecSDave Kleikamp  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5775ac27a0ecSDave Kleikamp  * we start and wait on commits.
5776ac27a0ecSDave Kleikamp  *
5777ac27a0ecSDave Kleikamp  * Is this efficient/effective?  Well, we're being nice to the system
5778ac27a0ecSDave Kleikamp  * by cleaning up our inodes proactively so they can be reaped
5779ac27a0ecSDave Kleikamp  * without I/O.  But we are potentially leaving up to five seconds'
5780ac27a0ecSDave Kleikamp  * worth of inodes floating about which prune_icache wants us to
5781ac27a0ecSDave Kleikamp  * write out.  One way to fix that would be to get prune_icache()
5782ac27a0ecSDave Kleikamp  * to do a write_super() to free up some memory.  It has the desired
5783ac27a0ecSDave Kleikamp  * effect.
5784ac27a0ecSDave Kleikamp  */
5785617ba13bSMingming Cao int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5786ac27a0ecSDave Kleikamp {
5787617ba13bSMingming Cao 	struct ext4_iloc iloc;
57886dd4ee7cSKalpak Shah 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
57896dd4ee7cSKalpak Shah 	static unsigned int mnt_count;
57906dd4ee7cSKalpak Shah 	int err, ret;
5791ac27a0ecSDave Kleikamp 
5792ac27a0ecSDave Kleikamp 	might_sleep();
5793617ba13bSMingming Cao 	err = ext4_reserve_inode_write(handle, inode, &iloc);
57940390131bSFrank Mayhar 	if (ext4_handle_valid(handle) &&
57950390131bSFrank Mayhar 	    EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
579619f5fb7aSTheodore Ts'o 	    !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
57976dd4ee7cSKalpak Shah 		/*
57986dd4ee7cSKalpak Shah 		 * We need extra buffer credits since we may write into EA block
57996dd4ee7cSKalpak Shah 		 * with this same handle. If journal_extend fails, then it will
58006dd4ee7cSKalpak Shah 		 * only result in a minor loss of functionality for that inode.
58016dd4ee7cSKalpak Shah 		 * If this is felt to be critical, then e2fsck should be run to
58026dd4ee7cSKalpak Shah 		 * force a large enough s_min_extra_isize.
58036dd4ee7cSKalpak Shah 		 */
58046dd4ee7cSKalpak Shah 		if ((jbd2_journal_extend(handle,
58056dd4ee7cSKalpak Shah 			     EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
58066dd4ee7cSKalpak Shah 			ret = ext4_expand_extra_isize(inode,
58076dd4ee7cSKalpak Shah 						      sbi->s_want_extra_isize,
58086dd4ee7cSKalpak Shah 						      iloc, handle);
58096dd4ee7cSKalpak Shah 			if (ret) {
581019f5fb7aSTheodore Ts'o 				ext4_set_inode_state(inode,
581119f5fb7aSTheodore Ts'o 						     EXT4_STATE_NO_EXPAND);
5812c1bddad9SAneesh Kumar K.V 				if (mnt_count !=
5813c1bddad9SAneesh Kumar K.V 					le16_to_cpu(sbi->s_es->s_mnt_count)) {
581412062dddSEric Sandeen 					ext4_warning(inode->i_sb,
58156dd4ee7cSKalpak Shah 					"Unable to expand inode %lu. Delete"
58166dd4ee7cSKalpak Shah 					" some EAs or run e2fsck.",
58176dd4ee7cSKalpak Shah 					inode->i_ino);
5818c1bddad9SAneesh Kumar K.V 					mnt_count =
5819c1bddad9SAneesh Kumar K.V 					  le16_to_cpu(sbi->s_es->s_mnt_count);
58206dd4ee7cSKalpak Shah 				}
58216dd4ee7cSKalpak Shah 			}
58226dd4ee7cSKalpak Shah 		}
58236dd4ee7cSKalpak Shah 	}
5824ac27a0ecSDave Kleikamp 	if (!err)
5825617ba13bSMingming Cao 		err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5826ac27a0ecSDave Kleikamp 	return err;
5827ac27a0ecSDave Kleikamp }
5828ac27a0ecSDave Kleikamp 
5829ac27a0ecSDave Kleikamp /*
5830617ba13bSMingming Cao  * ext4_dirty_inode() is called from __mark_inode_dirty()
5831ac27a0ecSDave Kleikamp  *
5832ac27a0ecSDave Kleikamp  * We're really interested in the case where a file is being extended.
5833ac27a0ecSDave Kleikamp  * i_size has been changed by generic_commit_write() and we thus need
5834ac27a0ecSDave Kleikamp  * to include the updated inode in the current transaction.
5835ac27a0ecSDave Kleikamp  *
58365dd4056dSChristoph Hellwig  * Also, dquot_alloc_block() will always dirty the inode when blocks
5837ac27a0ecSDave Kleikamp  * are allocated to the file.
5838ac27a0ecSDave Kleikamp  *
5839ac27a0ecSDave Kleikamp  * If the inode is marked synchronous, we don't honour that here - doing
5840ac27a0ecSDave Kleikamp  * so would cause a commit on atime updates, which we don't bother doing.
5841ac27a0ecSDave Kleikamp  * We handle synchronous inodes at the highest possible level.
5842ac27a0ecSDave Kleikamp  */
5843617ba13bSMingming Cao void ext4_dirty_inode(struct inode *inode)
5844ac27a0ecSDave Kleikamp {
5845ac27a0ecSDave Kleikamp 	handle_t *handle;
5846ac27a0ecSDave Kleikamp 
5847617ba13bSMingming Cao 	handle = ext4_journal_start(inode, 2);
5848ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5849ac27a0ecSDave Kleikamp 		goto out;
5850f3dc272fSCurt Wohlgemuth 
5851617ba13bSMingming Cao 	ext4_mark_inode_dirty(handle, inode);
5852f3dc272fSCurt Wohlgemuth 
5853617ba13bSMingming Cao 	ext4_journal_stop(handle);
5854ac27a0ecSDave Kleikamp out:
5855ac27a0ecSDave Kleikamp 	return;
5856ac27a0ecSDave Kleikamp }
5857ac27a0ecSDave Kleikamp 
5858ac27a0ecSDave Kleikamp #if 0
5859ac27a0ecSDave Kleikamp /*
5860ac27a0ecSDave Kleikamp  * Bind an inode's backing buffer_head into this transaction, to prevent
5861ac27a0ecSDave Kleikamp  * it from being flushed to disk early.  Unlike
5862617ba13bSMingming Cao  * ext4_reserve_inode_write, this leaves behind no bh reference and
5863ac27a0ecSDave Kleikamp  * returns no iloc structure, so the caller needs to repeat the iloc
5864ac27a0ecSDave Kleikamp  * lookup to mark the inode dirty later.
5865ac27a0ecSDave Kleikamp  */
5866617ba13bSMingming Cao static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5867ac27a0ecSDave Kleikamp {
5868617ba13bSMingming Cao 	struct ext4_iloc iloc;
5869ac27a0ecSDave Kleikamp 
5870ac27a0ecSDave Kleikamp 	int err = 0;
5871ac27a0ecSDave Kleikamp 	if (handle) {
5872617ba13bSMingming Cao 		err = ext4_get_inode_loc(inode, &iloc);
5873ac27a0ecSDave Kleikamp 		if (!err) {
5874ac27a0ecSDave Kleikamp 			BUFFER_TRACE(iloc.bh, "get_write_access");
5875dab291afSMingming Cao 			err = jbd2_journal_get_write_access(handle, iloc.bh);
5876ac27a0ecSDave Kleikamp 			if (!err)
58770390131bSFrank Mayhar 				err = ext4_handle_dirty_metadata(handle,
587873b50c1cSCurt Wohlgemuth 								 NULL,
5879ac27a0ecSDave Kleikamp 								 iloc.bh);
5880ac27a0ecSDave Kleikamp 			brelse(iloc.bh);
5881ac27a0ecSDave Kleikamp 		}
5882ac27a0ecSDave Kleikamp 	}
5883617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5884ac27a0ecSDave Kleikamp 	return err;
5885ac27a0ecSDave Kleikamp }
5886ac27a0ecSDave Kleikamp #endif
5887ac27a0ecSDave Kleikamp 
5888617ba13bSMingming Cao int ext4_change_inode_journal_flag(struct inode *inode, int val)
5889ac27a0ecSDave Kleikamp {
5890ac27a0ecSDave Kleikamp 	journal_t *journal;
5891ac27a0ecSDave Kleikamp 	handle_t *handle;
5892ac27a0ecSDave Kleikamp 	int err;
5893ac27a0ecSDave Kleikamp 
5894ac27a0ecSDave Kleikamp 	/*
5895ac27a0ecSDave Kleikamp 	 * We have to be very careful here: changing a data block's
5896ac27a0ecSDave Kleikamp 	 * journaling status dynamically is dangerous.  If we write a
5897ac27a0ecSDave Kleikamp 	 * data block to the journal, change the status and then delete
5898ac27a0ecSDave Kleikamp 	 * that block, we risk forgetting to revoke the old log record
5899ac27a0ecSDave Kleikamp 	 * from the journal and so a subsequent replay can corrupt data.
5900ac27a0ecSDave Kleikamp 	 * So, first we make sure that the journal is empty and that
5901ac27a0ecSDave Kleikamp 	 * nobody is changing anything.
5902ac27a0ecSDave Kleikamp 	 */
5903ac27a0ecSDave Kleikamp 
5904617ba13bSMingming Cao 	journal = EXT4_JOURNAL(inode);
59050390131bSFrank Mayhar 	if (!journal)
59060390131bSFrank Mayhar 		return 0;
5907d699594dSDave Hansen 	if (is_journal_aborted(journal))
5908ac27a0ecSDave Kleikamp 		return -EROFS;
5909ac27a0ecSDave Kleikamp 
5910dab291afSMingming Cao 	jbd2_journal_lock_updates(journal);
5911dab291afSMingming Cao 	jbd2_journal_flush(journal);
5912ac27a0ecSDave Kleikamp 
5913ac27a0ecSDave Kleikamp 	/*
5914ac27a0ecSDave Kleikamp 	 * OK, there are no updates running now, and all cached data is
5915ac27a0ecSDave Kleikamp 	 * synced to disk.  We are now in a completely consistent state
5916ac27a0ecSDave Kleikamp 	 * which doesn't have anything in the journal, and we know that
5917ac27a0ecSDave Kleikamp 	 * no filesystem updates are running, so it is safe to modify
5918ac27a0ecSDave Kleikamp 	 * the inode's in-core data-journaling state flag now.
5919ac27a0ecSDave Kleikamp 	 */
5920ac27a0ecSDave Kleikamp 
5921ac27a0ecSDave Kleikamp 	if (val)
592212e9b892SDmitry Monakhov 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5923ac27a0ecSDave Kleikamp 	else
592412e9b892SDmitry Monakhov 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5925617ba13bSMingming Cao 	ext4_set_aops(inode);
5926ac27a0ecSDave Kleikamp 
5927dab291afSMingming Cao 	jbd2_journal_unlock_updates(journal);
5928ac27a0ecSDave Kleikamp 
5929ac27a0ecSDave Kleikamp 	/* Finally we can mark the inode as dirty. */
5930ac27a0ecSDave Kleikamp 
5931617ba13bSMingming Cao 	handle = ext4_journal_start(inode, 1);
5932ac27a0ecSDave Kleikamp 	if (IS_ERR(handle))
5933ac27a0ecSDave Kleikamp 		return PTR_ERR(handle);
5934ac27a0ecSDave Kleikamp 
5935617ba13bSMingming Cao 	err = ext4_mark_inode_dirty(handle, inode);
59360390131bSFrank Mayhar 	ext4_handle_sync(handle);
5937617ba13bSMingming Cao 	ext4_journal_stop(handle);
5938617ba13bSMingming Cao 	ext4_std_error(inode->i_sb, err);
5939ac27a0ecSDave Kleikamp 
5940ac27a0ecSDave Kleikamp 	return err;
5941ac27a0ecSDave Kleikamp }
59422e9ee850SAneesh Kumar K.V 
59432e9ee850SAneesh Kumar K.V static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
59442e9ee850SAneesh Kumar K.V {
59452e9ee850SAneesh Kumar K.V 	return !buffer_mapped(bh);
59462e9ee850SAneesh Kumar K.V }
59472e9ee850SAneesh Kumar K.V 
5948c2ec175cSNick Piggin int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
59492e9ee850SAneesh Kumar K.V {
5950c2ec175cSNick Piggin 	struct page *page = vmf->page;
59512e9ee850SAneesh Kumar K.V 	loff_t size;
59522e9ee850SAneesh Kumar K.V 	unsigned long len;
59532e9ee850SAneesh Kumar K.V 	int ret = -EINVAL;
595479f0be8dSAneesh Kumar K.V 	void *fsdata;
59552e9ee850SAneesh Kumar K.V 	struct file *file = vma->vm_file;
59562e9ee850SAneesh Kumar K.V 	struct inode *inode = file->f_path.dentry->d_inode;
59572e9ee850SAneesh Kumar K.V 	struct address_space *mapping = inode->i_mapping;
59582e9ee850SAneesh Kumar K.V 
59592e9ee850SAneesh Kumar K.V 	/*
59602e9ee850SAneesh Kumar K.V 	 * Get i_alloc_sem to stop truncates messing with the inode. We cannot
59612e9ee850SAneesh Kumar K.V 	 * get i_mutex because we are already holding mmap_sem.
59622e9ee850SAneesh Kumar K.V 	 */
59632e9ee850SAneesh Kumar K.V 	down_read(&inode->i_alloc_sem);
59642e9ee850SAneesh Kumar K.V 	size = i_size_read(inode);
59652e9ee850SAneesh Kumar K.V 	if (page->mapping != mapping || size <= page_offset(page)
59662e9ee850SAneesh Kumar K.V 	    || !PageUptodate(page)) {
59672e9ee850SAneesh Kumar K.V 		/* page got truncated from under us? */
59682e9ee850SAneesh Kumar K.V 		goto out_unlock;
59692e9ee850SAneesh Kumar K.V 	}
59702e9ee850SAneesh Kumar K.V 	ret = 0;
59712e9ee850SAneesh Kumar K.V 	if (PageMappedToDisk(page))
59722e9ee850SAneesh Kumar K.V 		goto out_unlock;
59732e9ee850SAneesh Kumar K.V 
59742e9ee850SAneesh Kumar K.V 	if (page->index == size >> PAGE_CACHE_SHIFT)
59752e9ee850SAneesh Kumar K.V 		len = size & ~PAGE_CACHE_MASK;
59762e9ee850SAneesh Kumar K.V 	else
59772e9ee850SAneesh Kumar K.V 		len = PAGE_CACHE_SIZE;
59782e9ee850SAneesh Kumar K.V 
5979a827eaffSAneesh Kumar K.V 	lock_page(page);
5980a827eaffSAneesh Kumar K.V 	/*
5981a827eaffSAneesh Kumar K.V 	 * return if we have all the buffers mapped. This avoid
5982a827eaffSAneesh Kumar K.V 	 * the need to call write_begin/write_end which does a
5983a827eaffSAneesh Kumar K.V 	 * journal_start/journal_stop which can block and take
5984a827eaffSAneesh Kumar K.V 	 * long time
5985a827eaffSAneesh Kumar K.V 	 */
59862e9ee850SAneesh Kumar K.V 	if (page_has_buffers(page)) {
59872e9ee850SAneesh Kumar K.V 		if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
5988a827eaffSAneesh Kumar K.V 					ext4_bh_unmapped)) {
5989a827eaffSAneesh Kumar K.V 			unlock_page(page);
59902e9ee850SAneesh Kumar K.V 			goto out_unlock;
59912e9ee850SAneesh Kumar K.V 		}
5992a827eaffSAneesh Kumar K.V 	}
5993a827eaffSAneesh Kumar K.V 	unlock_page(page);
59942e9ee850SAneesh Kumar K.V 	/*
59952e9ee850SAneesh Kumar K.V 	 * OK, we need to fill the hole... Do write_begin write_end
59962e9ee850SAneesh Kumar K.V 	 * to do block allocation/reservation.We are not holding
59972e9ee850SAneesh Kumar K.V 	 * inode.i__mutex here. That allow * parallel write_begin,
59982e9ee850SAneesh Kumar K.V 	 * write_end call. lock_page prevent this from happening
59992e9ee850SAneesh Kumar K.V 	 * on the same page though
60002e9ee850SAneesh Kumar K.V 	 */
60012e9ee850SAneesh Kumar K.V 	ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
600279f0be8dSAneesh Kumar K.V 			len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
60032e9ee850SAneesh Kumar K.V 	if (ret < 0)
60042e9ee850SAneesh Kumar K.V 		goto out_unlock;
60052e9ee850SAneesh Kumar K.V 	ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
600679f0be8dSAneesh Kumar K.V 			len, len, page, fsdata);
60072e9ee850SAneesh Kumar K.V 	if (ret < 0)
60082e9ee850SAneesh Kumar K.V 		goto out_unlock;
60092e9ee850SAneesh Kumar K.V 	ret = 0;
60102e9ee850SAneesh Kumar K.V out_unlock:
6011c2ec175cSNick Piggin 	if (ret)
6012c2ec175cSNick Piggin 		ret = VM_FAULT_SIGBUS;
60132e9ee850SAneesh Kumar K.V 	up_read(&inode->i_alloc_sem);
60142e9ee850SAneesh Kumar K.V 	return ret;
60152e9ee850SAneesh Kumar K.V }
6016